xref: /freebsd/sys/dev/isp/isp_freebsd.c (revision b1f92fa22938fe29ab7e53692ffe0ed7a0ecc4d0)
1 /*-
2  * Copyright (c) 1997-2009 by Matthew Jacob
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice immediately at the beginning of the file, without modification,
10  *    this list of conditions, and the following disclaimer.
11  * 2. The name of the author may not be used to endorse or promote products
12  *    derived from this software without specific prior written permission.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
18  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26 
27 /*
28  * Platform (FreeBSD) dependent common attachment code for Qlogic adapters.
29  */
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
32 
33 #include <dev/isp/isp_freebsd.h>
34 #include <sys/unistd.h>
35 #include <sys/kthread.h>
36 #include <sys/conf.h>
37 #include <sys/module.h>
38 #include <sys/ioccom.h>
39 #include <dev/isp/isp_ioctl.h>
40 #include <sys/devicestat.h>
41 #include <cam/cam_periph.h>
42 #include <cam/cam_xpt_periph.h>
43 
44 #if	__FreeBSD_version < 800002
45 #define	THREAD_CREATE	kthread_create
46 #else
47 #define	THREAD_CREATE	kproc_create
48 #endif
49 
50 MODULE_VERSION(isp, 1);
51 MODULE_DEPEND(isp, cam, 1, 1, 1);
52 int isp_announced = 0;
53 int isp_loop_down_limit = 60;	/* default loop down limit */
54 int isp_quickboot_time = 7;	/* don't wait more than N secs for loop up */
55 int isp_gone_device_time = 30;	/* grace time before reporting device lost */
56 static const char prom3[] = "Chan %d [%u] PortID 0x%06x Departed because of %s";
57 
58 static void isp_freeze_loopdown(ispsoftc_t *, int);
59 static void isp_loop_changed(ispsoftc_t *isp, int chan);
60 static d_ioctl_t ispioctl;
61 static void isp_intr_enable(void *);
62 static void isp_cam_async(void *, uint32_t, struct cam_path *, void *);
63 static void isp_poll(struct cam_sim *);
64 static timeout_t isp_watchdog;
65 static timeout_t isp_gdt;
66 static task_fn_t isp_gdt_task;
67 static void isp_kthread(void *);
68 static void isp_action(struct cam_sim *, union ccb *);
69 static int isp_timer_count;
70 static void isp_timer(void *);
71 
72 static struct cdevsw isp_cdevsw = {
73 	.d_version =	D_VERSION,
74 	.d_ioctl =	ispioctl,
75 	.d_name =	"isp",
76 };
77 
78 static int
79 isp_role_sysctl(SYSCTL_HANDLER_ARGS)
80 {
81 	ispsoftc_t *isp = (ispsoftc_t *)arg1;
82 	int chan = arg2;
83 	int error, old, value;
84 
85 	value = FCPARAM(isp, chan)->role;
86 
87 	error = sysctl_handle_int(oidp, &value, 0, req);
88 	if ((error != 0) || (req->newptr == NULL))
89 		return (error);
90 
91 	if (value < ISP_ROLE_NONE || value > ISP_ROLE_BOTH)
92 		return (EINVAL);
93 
94 	ISP_LOCK(isp);
95 	old = FCPARAM(isp, chan)->role;
96 
97 	/* We don't allow target mode switch from here. */
98 	value = (old & ISP_ROLE_TARGET) | (value & ISP_ROLE_INITIATOR);
99 
100 	/* If nothing has changed -- we are done. */
101 	if (value == old) {
102 		ISP_UNLOCK(isp);
103 		return (0);
104 	}
105 
106 	/* Actually change the role. */
107 	error = isp_control(isp, ISPCTL_CHANGE_ROLE, chan, value);
108 	ISP_UNLOCK(isp);
109 	return (error);
110 }
111 
112 static int
113 isp_attach_chan(ispsoftc_t *isp, struct cam_devq *devq, int chan)
114 {
115 	struct ccb_setasync csa;
116 	struct cam_sim *sim;
117 	struct cam_path *path;
118 
119 	/*
120 	 * Construct our SIM entry.
121 	 */
122 	sim = cam_sim_alloc(isp_action, isp_poll, "isp", isp, device_get_unit(isp->isp_dev), &isp->isp_osinfo.lock, isp->isp_maxcmds, isp->isp_maxcmds, devq);
123 
124 	if (sim == NULL) {
125 		return (ENOMEM);
126 	}
127 
128 	ISP_LOCK(isp);
129 	if (xpt_bus_register(sim, isp->isp_dev, chan) != CAM_SUCCESS) {
130 		ISP_UNLOCK(isp);
131 		cam_sim_free(sim, FALSE);
132 		return (EIO);
133 	}
134 	ISP_UNLOCK(isp);
135 	if (xpt_create_path(&path, NULL, cam_sim_path(sim), CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
136 		ISP_LOCK(isp);
137 		xpt_bus_deregister(cam_sim_path(sim));
138 		ISP_UNLOCK(isp);
139 		cam_sim_free(sim, FALSE);
140 		return (ENXIO);
141 	}
142 	xpt_setup_ccb(&csa.ccb_h, path, 5);
143 	csa.ccb_h.func_code = XPT_SASYNC_CB;
144 	csa.event_enable = AC_LOST_DEVICE;
145 	csa.callback = isp_cam_async;
146 	csa.callback_arg = sim;
147 
148 	ISP_LOCK(isp);
149 	xpt_action((union ccb *)&csa);
150 	ISP_UNLOCK(isp);
151 
152 	if (IS_SCSI(isp)) {
153 		struct isp_spi *spi = ISP_SPI_PC(isp, chan);
154 		spi->sim = sim;
155 		spi->path = path;
156 	} else {
157 		fcparam *fcp = FCPARAM(isp, chan);
158 		struct isp_fc *fc = ISP_FC_PC(isp, chan);
159 		struct sysctl_ctx_list *ctx = device_get_sysctl_ctx(isp->isp_osinfo.dev);
160 		struct sysctl_oid *tree = device_get_sysctl_tree(isp->isp_osinfo.dev);
161 		char name[16];
162 
163 		ISP_LOCK(isp);
164 		fc->sim = sim;
165 		fc->path = path;
166 		fc->isp = isp;
167 		fc->ready = 1;
168 
169 		callout_init_mtx(&fc->gdt, &isp->isp_osinfo.lock, 0);
170 		TASK_INIT(&fc->gtask, 1, isp_gdt_task, fc);
171 		isp_loop_changed(isp, chan);
172 		ISP_UNLOCK(isp);
173 		if (THREAD_CREATE(isp_kthread, fc, &fc->kproc, 0, 0, "%s: fc_thrd%d", device_get_nameunit(isp->isp_osinfo.dev), chan)) {
174 			xpt_free_path(fc->path);
175 			ISP_LOCK(isp);
176 			xpt_bus_deregister(cam_sim_path(fc->sim));
177 			ISP_UNLOCK(isp);
178 			cam_sim_free(fc->sim, FALSE);
179 			return (ENOMEM);
180 		}
181 		fc->num_threads += 1;
182 		if (chan > 0) {
183 			snprintf(name, sizeof(name), "chan%d", chan);
184 			tree = SYSCTL_ADD_NODE(ctx, SYSCTL_CHILDREN(tree),
185 			    OID_AUTO, name, CTLFLAG_RW, 0, "Virtual channel");
186 		}
187 		SYSCTL_ADD_QUAD(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
188 		    "wwnn", CTLFLAG_RD, &fcp->isp_wwnn,
189 		    "World Wide Node Name");
190 		SYSCTL_ADD_QUAD(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
191 		    "wwpn", CTLFLAG_RD, &fcp->isp_wwpn,
192 		    "World Wide Port Name");
193 		SYSCTL_ADD_UINT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
194 		    "loop_down_limit", CTLFLAG_RW, &fc->loop_down_limit, 0,
195 		    "Loop Down Limit");
196 		SYSCTL_ADD_UINT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
197 		    "gone_device_time", CTLFLAG_RW, &fc->gone_device_time, 0,
198 		    "Gone Device Time");
199 #if defined(ISP_TARGET_MODE) && defined(DEBUG)
200 		SYSCTL_ADD_UINT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
201 		    "inject_lost_data_frame", CTLFLAG_RW, &fc->inject_lost_data_frame, 0,
202 		    "Cause a Lost Frame on a Read");
203 #endif
204 		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
205 		    "role", CTLTYPE_INT | CTLFLAG_RW, isp, chan,
206 		    isp_role_sysctl, "I", "Current role");
207 		SYSCTL_ADD_UINT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
208 		    "speed", CTLFLAG_RD, &fcp->isp_gbspeed, 0,
209 		    "Connection speed in gigabits");
210 		SYSCTL_ADD_UINT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
211 		    "linkstate", CTLFLAG_RD, &fcp->isp_linkstate, 0,
212 		    "Link state");
213 		SYSCTL_ADD_UINT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
214 		    "fwstate", CTLFLAG_RD, &fcp->isp_fwstate, 0,
215 		    "Firmware state");
216 		SYSCTL_ADD_UINT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
217 		    "loopstate", CTLFLAG_RD, &fcp->isp_loopstate, 0,
218 		    "Loop state");
219 		SYSCTL_ADD_UINT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
220 		    "topo", CTLFLAG_RD, &fcp->isp_topo, 0,
221 		    "Connection topology");
222 	}
223 	return (0);
224 }
225 
226 static void
227 isp_detach_chan(ispsoftc_t *isp, int chan)
228 {
229 	struct cam_sim *sim;
230 	struct cam_path *path;
231 	struct ccb_setasync csa;
232 	int *num_threads;
233 
234 	ISP_GET_PC(isp, chan, sim, sim);
235 	ISP_GET_PC(isp, chan, path, path);
236 	ISP_GET_PC_ADDR(isp, chan, num_threads, num_threads);
237 
238 	xpt_setup_ccb(&csa.ccb_h, path, 5);
239 	csa.ccb_h.func_code = XPT_SASYNC_CB;
240 	csa.event_enable = 0;
241 	csa.callback = isp_cam_async;
242 	csa.callback_arg = sim;
243 	xpt_action((union ccb *)&csa);
244 	xpt_free_path(path);
245 	xpt_bus_deregister(cam_sim_path(sim));
246 	cam_sim_free(sim, FALSE);
247 
248 	/* Wait for the channel's spawned threads to exit. */
249 	wakeup(isp->isp_osinfo.pc.ptr);
250 	while (*num_threads != 0)
251 		mtx_sleep(isp, &isp->isp_osinfo.lock, PRIBIO, "isp_reap", 100);
252 }
253 
254 int
255 isp_attach(ispsoftc_t *isp)
256 {
257 	const char *nu = device_get_nameunit(isp->isp_osinfo.dev);
258 	int du = device_get_unit(isp->isp_dev);
259 	int chan;
260 
261 	isp->isp_osinfo.ehook.ich_func = isp_intr_enable;
262 	isp->isp_osinfo.ehook.ich_arg = isp;
263 	/*
264 	 * Haha. Set this first, because if we're loaded as a module isp_intr_enable
265 	 * will be called right awawy, which will clear isp_osinfo.ehook_active,
266 	 * which would be unwise to then set again later.
267 	 */
268 	isp->isp_osinfo.ehook_active = 1;
269 	if (config_intrhook_establish(&isp->isp_osinfo.ehook) != 0) {
270 		isp_prt(isp, ISP_LOGERR, "could not establish interrupt enable hook");
271 		return (-EIO);
272 	}
273 
274 	/*
275 	 * Create the device queue for our SIM(s).
276 	 */
277 	isp->isp_osinfo.devq = cam_simq_alloc(isp->isp_maxcmds);
278 	if (isp->isp_osinfo.devq == NULL) {
279 		config_intrhook_disestablish(&isp->isp_osinfo.ehook);
280 		return (EIO);
281 	}
282 
283 	for (chan = 0; chan < isp->isp_nchan; chan++) {
284 		if (isp_attach_chan(isp, isp->isp_osinfo.devq, chan)) {
285 			goto unwind;
286 		}
287 	}
288 
289 	callout_init_mtx(&isp->isp_osinfo.tmo, &isp->isp_osinfo.lock, 0);
290 	isp_timer_count = hz >> 2;
291 	callout_reset(&isp->isp_osinfo.tmo, isp_timer_count, isp_timer, isp);
292 	isp->isp_osinfo.timer_active = 1;
293 
294 	isp->isp_osinfo.cdev = make_dev(&isp_cdevsw, du, UID_ROOT, GID_OPERATOR, 0600, "%s", nu);
295 	if (isp->isp_osinfo.cdev) {
296 		isp->isp_osinfo.cdev->si_drv1 = isp;
297 	}
298 	return (0);
299 
300 unwind:
301 	while (--chan >= 0) {
302 		struct cam_sim *sim;
303 		struct cam_path *path;
304 
305 		ISP_GET_PC(isp, chan, sim, sim);
306 		ISP_GET_PC(isp, chan, path, path);
307 		xpt_free_path(path);
308 		ISP_LOCK(isp);
309 		xpt_bus_deregister(cam_sim_path(sim));
310 		ISP_UNLOCK(isp);
311 		cam_sim_free(sim, FALSE);
312 	}
313 	if (isp->isp_osinfo.ehook_active) {
314 		config_intrhook_disestablish(&isp->isp_osinfo.ehook);
315 		isp->isp_osinfo.ehook_active = 0;
316 	}
317 	if (isp->isp_osinfo.cdev) {
318 		destroy_dev(isp->isp_osinfo.cdev);
319 		isp->isp_osinfo.cdev = NULL;
320 	}
321 	cam_simq_free(isp->isp_osinfo.devq);
322 	isp->isp_osinfo.devq = NULL;
323 	return (-1);
324 }
325 
326 int
327 isp_detach(ispsoftc_t *isp)
328 {
329 	struct cam_sim *sim;
330 	int chan;
331 
332 	ISP_LOCK(isp);
333 	for (chan = isp->isp_nchan - 1; chan >= 0; chan -= 1) {
334 		ISP_GET_PC(isp, chan, sim, sim);
335 		if (sim->refcount > 2) {
336 			ISP_UNLOCK(isp);
337 			return (EBUSY);
338 		}
339 	}
340 	/* Tell spawned threads that we're exiting. */
341 	isp->isp_osinfo.is_exiting = 1;
342 	if (isp->isp_osinfo.timer_active) {
343 		callout_stop(&isp->isp_osinfo.tmo);
344 		isp->isp_osinfo.timer_active = 0;
345 	}
346 	for (chan = isp->isp_nchan - 1; chan >= 0; chan -= 1)
347 		isp_detach_chan(isp, chan);
348 	ISP_UNLOCK(isp);
349 
350 	if (isp->isp_osinfo.cdev) {
351 		destroy_dev(isp->isp_osinfo.cdev);
352 		isp->isp_osinfo.cdev = NULL;
353 	}
354 	if (isp->isp_osinfo.ehook_active) {
355 		config_intrhook_disestablish(&isp->isp_osinfo.ehook);
356 		isp->isp_osinfo.ehook_active = 0;
357 	}
358 	if (isp->isp_osinfo.devq != NULL) {
359 		cam_simq_free(isp->isp_osinfo.devq);
360 		isp->isp_osinfo.devq = NULL;
361 	}
362 	return (0);
363 }
364 
365 static void
366 isp_freeze_loopdown(ispsoftc_t *isp, int chan)
367 {
368 	if (IS_FC(isp)) {
369 		struct isp_fc *fc = ISP_FC_PC(isp, chan);
370 		if (fc->simqfrozen == 0) {
371 			isp_prt(isp, ISP_LOGDEBUG0,
372 			    "Chan %d Freeze simq (loopdown)", chan);
373 			fc->simqfrozen = SIMQFRZ_LOOPDOWN;
374 #if __FreeBSD_version >= 1000039
375 			xpt_hold_boot();
376 #endif
377 			xpt_freeze_simq(fc->sim, 1);
378 		} else {
379 			isp_prt(isp, ISP_LOGDEBUG0,
380 			    "Chan %d Mark simq frozen (loopdown)", chan);
381 			fc->simqfrozen |= SIMQFRZ_LOOPDOWN;
382 		}
383 	}
384 }
385 
386 static void
387 isp_unfreeze_loopdown(ispsoftc_t *isp, int chan)
388 {
389 	if (IS_FC(isp)) {
390 		struct isp_fc *fc = ISP_FC_PC(isp, chan);
391 		int wasfrozen = fc->simqfrozen & SIMQFRZ_LOOPDOWN;
392 		fc->simqfrozen &= ~SIMQFRZ_LOOPDOWN;
393 		if (wasfrozen && fc->simqfrozen == 0) {
394 			isp_prt(isp, ISP_LOGDEBUG0,
395 			    "Chan %d Release simq", chan);
396 			xpt_release_simq(fc->sim, 1);
397 #if __FreeBSD_version >= 1000039
398 			xpt_release_boot();
399 #endif
400 		}
401 	}
402 }
403 
404 
405 static int
406 ispioctl(struct cdev *dev, u_long c, caddr_t addr, int flags, struct thread *td)
407 {
408 	ispsoftc_t *isp;
409 	int nr, chan, retval = ENOTTY;
410 
411 	isp = dev->si_drv1;
412 
413 	switch (c) {
414 	case ISP_SDBLEV:
415 	{
416 		int olddblev = isp->isp_dblev;
417 		isp->isp_dblev = *(int *)addr;
418 		*(int *)addr = olddblev;
419 		retval = 0;
420 		break;
421 	}
422 	case ISP_GETROLE:
423 		chan = *(int *)addr;
424 		if (chan < 0 || chan >= isp->isp_nchan) {
425 			retval = -ENXIO;
426 			break;
427 		}
428 		if (IS_FC(isp)) {
429 			*(int *)addr = FCPARAM(isp, chan)->role;
430 		} else {
431 			*(int *)addr = ISP_ROLE_INITIATOR;
432 		}
433 		retval = 0;
434 		break;
435 	case ISP_SETROLE:
436 		if (IS_SCSI(isp))
437 			break;
438 		nr = *(int *)addr;
439 		chan = nr >> 8;
440 		if (chan < 0 || chan >= isp->isp_nchan) {
441 			retval = -ENXIO;
442 			break;
443 		}
444 		nr &= 0xff;
445 		if (nr & ~(ISP_ROLE_INITIATOR|ISP_ROLE_TARGET)) {
446 			retval = EINVAL;
447 			break;
448 		}
449 		ISP_LOCK(isp);
450 		*(int *)addr = FCPARAM(isp, chan)->role;
451 		retval = isp_control(isp, ISPCTL_CHANGE_ROLE, chan, nr);
452 		ISP_UNLOCK(isp);
453 		retval = 0;
454 		break;
455 
456 	case ISP_RESETHBA:
457 		ISP_LOCK(isp);
458 		isp_reinit(isp, 0);
459 		ISP_UNLOCK(isp);
460 		retval = 0;
461 		break;
462 
463 	case ISP_RESCAN:
464 		if (IS_FC(isp)) {
465 			chan = *(int *)addr;
466 			if (chan < 0 || chan >= isp->isp_nchan) {
467 				retval = -ENXIO;
468 				break;
469 			}
470 			ISP_LOCK(isp);
471 			if (isp_fc_runstate(isp, chan, 5 * 1000000) != LOOP_READY) {
472 				retval = EIO;
473 			} else {
474 				retval = 0;
475 			}
476 			ISP_UNLOCK(isp);
477 		}
478 		break;
479 
480 	case ISP_FC_LIP:
481 		if (IS_FC(isp)) {
482 			chan = *(int *)addr;
483 			if (chan < 0 || chan >= isp->isp_nchan) {
484 				retval = -ENXIO;
485 				break;
486 			}
487 			ISP_LOCK(isp);
488 			if (isp_control(isp, ISPCTL_SEND_LIP, chan)) {
489 				retval = EIO;
490 			} else {
491 				retval = 0;
492 			}
493 			ISP_UNLOCK(isp);
494 		}
495 		break;
496 	case ISP_FC_GETDINFO:
497 	{
498 		struct isp_fc_device *ifc = (struct isp_fc_device *) addr;
499 		fcportdb_t *lp;
500 
501 		if (IS_SCSI(isp)) {
502 			break;
503 		}
504 		if (ifc->loopid >= MAX_FC_TARG) {
505 			retval = EINVAL;
506 			break;
507 		}
508 		lp = &FCPARAM(isp, ifc->chan)->portdb[ifc->loopid];
509 		if (lp->state != FC_PORTDB_STATE_NIL) {
510 			ifc->role = (lp->prli_word3 & SVC3_ROLE_MASK) >> SVC3_ROLE_SHIFT;
511 			ifc->loopid = lp->handle;
512 			ifc->portid = lp->portid;
513 			ifc->node_wwn = lp->node_wwn;
514 			ifc->port_wwn = lp->port_wwn;
515 			retval = 0;
516 		} else {
517 			retval = ENODEV;
518 		}
519 		break;
520 	}
521 	case ISP_GET_STATS:
522 	{
523 		isp_stats_t *sp = (isp_stats_t *) addr;
524 
525 		ISP_MEMZERO(sp, sizeof (*sp));
526 		sp->isp_stat_version = ISP_STATS_VERSION;
527 		sp->isp_type = isp->isp_type;
528 		sp->isp_revision = isp->isp_revision;
529 		ISP_LOCK(isp);
530 		sp->isp_stats[ISP_INTCNT] = isp->isp_intcnt;
531 		sp->isp_stats[ISP_INTBOGUS] = isp->isp_intbogus;
532 		sp->isp_stats[ISP_INTMBOXC] = isp->isp_intmboxc;
533 		sp->isp_stats[ISP_INGOASYNC] = isp->isp_intoasync;
534 		sp->isp_stats[ISP_RSLTCCMPLT] = isp->isp_rsltccmplt;
535 		sp->isp_stats[ISP_FPHCCMCPLT] = isp->isp_fphccmplt;
536 		sp->isp_stats[ISP_RSCCHIWAT] = isp->isp_rscchiwater;
537 		sp->isp_stats[ISP_FPCCHIWAT] = isp->isp_fpcchiwater;
538 		ISP_UNLOCK(isp);
539 		retval = 0;
540 		break;
541 	}
542 	case ISP_CLR_STATS:
543 		ISP_LOCK(isp);
544 		isp->isp_intcnt = 0;
545 		isp->isp_intbogus = 0;
546 		isp->isp_intmboxc = 0;
547 		isp->isp_intoasync = 0;
548 		isp->isp_rsltccmplt = 0;
549 		isp->isp_fphccmplt = 0;
550 		isp->isp_rscchiwater = 0;
551 		isp->isp_fpcchiwater = 0;
552 		ISP_UNLOCK(isp);
553 		retval = 0;
554 		break;
555 	case ISP_FC_GETHINFO:
556 	{
557 		struct isp_hba_device *hba = (struct isp_hba_device *) addr;
558 		int chan = hba->fc_channel;
559 
560 		if (chan < 0 || chan >= isp->isp_nchan) {
561 			retval = ENXIO;
562 			break;
563 		}
564 		hba->fc_fw_major = ISP_FW_MAJORX(isp->isp_fwrev);
565 		hba->fc_fw_minor = ISP_FW_MINORX(isp->isp_fwrev);
566 		hba->fc_fw_micro = ISP_FW_MICROX(isp->isp_fwrev);
567 		hba->fc_nchannels = isp->isp_nchan;
568 		if (IS_FC(isp)) {
569 			hba->fc_nports = MAX_FC_TARG;
570 			hba->fc_speed = FCPARAM(isp, hba->fc_channel)->isp_gbspeed;
571 			hba->fc_topology = FCPARAM(isp, chan)->isp_topo + 1;
572 			hba->fc_loopid = FCPARAM(isp, chan)->isp_loopid;
573 			hba->nvram_node_wwn = FCPARAM(isp, chan)->isp_wwnn_nvram;
574 			hba->nvram_port_wwn = FCPARAM(isp, chan)->isp_wwpn_nvram;
575 			hba->active_node_wwn = FCPARAM(isp, chan)->isp_wwnn;
576 			hba->active_port_wwn = FCPARAM(isp, chan)->isp_wwpn;
577 		} else {
578 			hba->fc_nports = MAX_TARGETS;
579 			hba->fc_speed = 0;
580 			hba->fc_topology = 0;
581 			hba->nvram_node_wwn = 0ull;
582 			hba->nvram_port_wwn = 0ull;
583 			hba->active_node_wwn = 0ull;
584 			hba->active_port_wwn = 0ull;
585 		}
586 		retval = 0;
587 		break;
588 	}
589 	case ISP_TSK_MGMT:
590 	{
591 		int needmarker;
592 		struct isp_fc_tsk_mgmt *fct = (struct isp_fc_tsk_mgmt *) addr;
593 		uint16_t nphdl;
594 		mbreg_t mbs;
595 
596 		if (IS_SCSI(isp)) {
597 			break;
598 		}
599 
600 		chan = fct->chan;
601 		if (chan < 0 || chan >= isp->isp_nchan) {
602 			retval = -ENXIO;
603 			break;
604 		}
605 
606 		needmarker = retval = 0;
607 		nphdl = fct->loopid;
608 		ISP_LOCK(isp);
609 		if (IS_24XX(isp)) {
610 			uint8_t local[QENTRY_LEN];
611 			isp24xx_tmf_t *tmf;
612 			isp24xx_statusreq_t *sp;
613 			fcparam *fcp = FCPARAM(isp, chan);
614 			fcportdb_t *lp;
615 			int i;
616 
617 			for (i = 0; i < MAX_FC_TARG; i++) {
618 				lp = &fcp->portdb[i];
619 				if (lp->handle == nphdl) {
620 					break;
621 				}
622 			}
623 			if (i == MAX_FC_TARG) {
624 				retval = ENXIO;
625 				ISP_UNLOCK(isp);
626 				break;
627 			}
628 			/* XXX VALIDATE LP XXX */
629 			tmf = (isp24xx_tmf_t *) local;
630 			ISP_MEMZERO(tmf, QENTRY_LEN);
631 			tmf->tmf_header.rqs_entry_type = RQSTYPE_TSK_MGMT;
632 			tmf->tmf_header.rqs_entry_count = 1;
633 			tmf->tmf_nphdl = lp->handle;
634 			tmf->tmf_delay = 2;
635 			tmf->tmf_timeout = 2;
636 			tmf->tmf_tidlo = lp->portid;
637 			tmf->tmf_tidhi = lp->portid >> 16;
638 			tmf->tmf_vpidx = ISP_GET_VPIDX(isp, chan);
639 			tmf->tmf_lun[1] = fct->lun & 0xff;
640 			if (fct->lun >= 256) {
641 				tmf->tmf_lun[0] = 0x40 | (fct->lun >> 8);
642 			}
643 			switch (fct->action) {
644 			case IPT_CLEAR_ACA:
645 				tmf->tmf_flags = ISP24XX_TMF_CLEAR_ACA;
646 				break;
647 			case IPT_TARGET_RESET:
648 				tmf->tmf_flags = ISP24XX_TMF_TARGET_RESET;
649 				needmarker = 1;
650 				break;
651 			case IPT_LUN_RESET:
652 				tmf->tmf_flags = ISP24XX_TMF_LUN_RESET;
653 				needmarker = 1;
654 				break;
655 			case IPT_CLEAR_TASK_SET:
656 				tmf->tmf_flags = ISP24XX_TMF_CLEAR_TASK_SET;
657 				needmarker = 1;
658 				break;
659 			case IPT_ABORT_TASK_SET:
660 				tmf->tmf_flags = ISP24XX_TMF_ABORT_TASK_SET;
661 				needmarker = 1;
662 				break;
663 			default:
664 				retval = EINVAL;
665 				break;
666 			}
667 			if (retval) {
668 				ISP_UNLOCK(isp);
669 				break;
670 			}
671 			MBSINIT(&mbs, MBOX_EXEC_COMMAND_IOCB_A64, MBLOGALL, 5000000);
672 			mbs.param[1] = QENTRY_LEN;
673 			mbs.param[2] = DMA_WD1(fcp->isp_scdma);
674 			mbs.param[3] = DMA_WD0(fcp->isp_scdma);
675 			mbs.param[6] = DMA_WD3(fcp->isp_scdma);
676 			mbs.param[7] = DMA_WD2(fcp->isp_scdma);
677 
678 			if (FC_SCRATCH_ACQUIRE(isp, chan)) {
679 				ISP_UNLOCK(isp);
680 				retval = ENOMEM;
681 				break;
682 			}
683 			isp_put_24xx_tmf(isp, tmf, fcp->isp_scratch);
684 			MEMORYBARRIER(isp, SYNC_SFORDEV, 0, QENTRY_LEN, chan);
685 			sp = (isp24xx_statusreq_t *) local;
686 			sp->req_completion_status = 1;
687 			retval = isp_control(isp, ISPCTL_RUN_MBOXCMD, &mbs);
688 			MEMORYBARRIER(isp, SYNC_SFORCPU, QENTRY_LEN, QENTRY_LEN, chan);
689 			isp_get_24xx_response(isp, &((isp24xx_statusreq_t *)fcp->isp_scratch)[1], sp);
690 			FC_SCRATCH_RELEASE(isp, chan);
691 			if (retval || sp->req_completion_status != 0) {
692 				FC_SCRATCH_RELEASE(isp, chan);
693 				retval = EIO;
694 			}
695 			if (retval == 0) {
696 				if (needmarker) {
697 					fcp->sendmarker = 1;
698 				}
699 			}
700 		} else {
701 			MBSINIT(&mbs, 0, MBLOGALL, 0);
702 			if (ISP_CAP_2KLOGIN(isp) == 0) {
703 				nphdl <<= 8;
704 			}
705 			switch (fct->action) {
706 			case IPT_CLEAR_ACA:
707 				mbs.param[0] = MBOX_CLEAR_ACA;
708 				mbs.param[1] = nphdl;
709 				mbs.param[2] = fct->lun;
710 				break;
711 			case IPT_TARGET_RESET:
712 				mbs.param[0] = MBOX_TARGET_RESET;
713 				mbs.param[1] = nphdl;
714 				needmarker = 1;
715 				break;
716 			case IPT_LUN_RESET:
717 				mbs.param[0] = MBOX_LUN_RESET;
718 				mbs.param[1] = nphdl;
719 				mbs.param[2] = fct->lun;
720 				needmarker = 1;
721 				break;
722 			case IPT_CLEAR_TASK_SET:
723 				mbs.param[0] = MBOX_CLEAR_TASK_SET;
724 				mbs.param[1] = nphdl;
725 				mbs.param[2] = fct->lun;
726 				needmarker = 1;
727 				break;
728 			case IPT_ABORT_TASK_SET:
729 				mbs.param[0] = MBOX_ABORT_TASK_SET;
730 				mbs.param[1] = nphdl;
731 				mbs.param[2] = fct->lun;
732 				needmarker = 1;
733 				break;
734 			default:
735 				retval = EINVAL;
736 				break;
737 			}
738 			if (retval == 0) {
739 				if (needmarker) {
740 					FCPARAM(isp, chan)->sendmarker = 1;
741 				}
742 				retval = isp_control(isp, ISPCTL_RUN_MBOXCMD, &mbs);
743 				if (retval) {
744 					retval = EIO;
745 				}
746 			}
747 		}
748 		ISP_UNLOCK(isp);
749 		break;
750 	}
751 	default:
752 		break;
753 	}
754 	return (retval);
755 }
756 
757 static void
758 isp_intr_enable(void *arg)
759 {
760 	int chan;
761 	ispsoftc_t *isp = arg;
762 	ISP_LOCK(isp);
763 	if (IS_FC(isp)) {
764 		for (chan = 0; chan < isp->isp_nchan; chan++) {
765 			if (FCPARAM(isp, chan)->role != ISP_ROLE_NONE) {
766 				ISP_ENABLE_INTS(isp);
767 				break;
768 			}
769 		}
770 	} else {
771 		ISP_ENABLE_INTS(isp);
772 	}
773 	isp->isp_osinfo.ehook_active = 0;
774 	ISP_UNLOCK(isp);
775 	/* Release our hook so that the boot can continue. */
776 	config_intrhook_disestablish(&isp->isp_osinfo.ehook);
777 }
778 
779 /*
780  * Local Inlines
781  */
782 
783 static ISP_INLINE int isp_get_pcmd(ispsoftc_t *, union ccb *);
784 static ISP_INLINE void isp_free_pcmd(ispsoftc_t *, union ccb *);
785 
786 static ISP_INLINE int
787 isp_get_pcmd(ispsoftc_t *isp, union ccb *ccb)
788 {
789 	ISP_PCMD(ccb) = isp->isp_osinfo.pcmd_free;
790 	if (ISP_PCMD(ccb) == NULL) {
791 		return (-1);
792 	}
793 	isp->isp_osinfo.pcmd_free = ((struct isp_pcmd *)ISP_PCMD(ccb))->next;
794 	return (0);
795 }
796 
797 static ISP_INLINE void
798 isp_free_pcmd(ispsoftc_t *isp, union ccb *ccb)
799 {
800 	if (ISP_PCMD(ccb)) {
801 #ifdef	ISP_TARGET_MODE
802 		PISP_PCMD(ccb)->datalen = 0;
803 		PISP_PCMD(ccb)->totslen = 0;
804 		PISP_PCMD(ccb)->cumslen = 0;
805 		PISP_PCMD(ccb)->crn = 0;
806 #endif
807 		PISP_PCMD(ccb)->next = isp->isp_osinfo.pcmd_free;
808 		isp->isp_osinfo.pcmd_free = ISP_PCMD(ccb);
809 		ISP_PCMD(ccb) = NULL;
810 	}
811 }
812 
813 /*
814  * Put the target mode functions here, because some are inlines
815  */
816 #ifdef	ISP_TARGET_MODE
817 static ISP_INLINE int is_lun_enabled(ispsoftc_t *, int, lun_id_t);
818 static ISP_INLINE tstate_t *get_lun_statep(ispsoftc_t *, int, lun_id_t);
819 static ISP_INLINE tstate_t *get_lun_statep_from_tag(ispsoftc_t *, int, uint32_t);
820 static ISP_INLINE void rls_lun_statep(ispsoftc_t *, tstate_t *);
821 static ISP_INLINE inot_private_data_t *get_ntp_from_tagdata(ispsoftc_t *, uint32_t, uint32_t, tstate_t **);
822 static ISP_INLINE atio_private_data_t *isp_get_atpd(ispsoftc_t *, tstate_t *, uint32_t);
823 static ISP_INLINE atio_private_data_t *isp_find_atpd(ispsoftc_t *, tstate_t *, uint32_t);
824 static ISP_INLINE void isp_put_atpd(ispsoftc_t *, tstate_t *, atio_private_data_t *);
825 static ISP_INLINE inot_private_data_t *isp_get_ntpd(ispsoftc_t *, tstate_t *);
826 static ISP_INLINE inot_private_data_t *isp_find_ntpd(ispsoftc_t *, tstate_t *, uint32_t, uint32_t);
827 static ISP_INLINE void isp_put_ntpd(ispsoftc_t *, tstate_t *, inot_private_data_t *);
828 static cam_status create_lun_state(ispsoftc_t *, int, struct cam_path *, tstate_t **);
829 static void destroy_lun_state(ispsoftc_t *, tstate_t *);
830 static void isp_enable_lun(ispsoftc_t *, union ccb *);
831 static void isp_disable_lun(ispsoftc_t *, union ccb *);
832 static timeout_t isp_refire_putback_atio;
833 static timeout_t isp_refire_notify_ack;
834 static void isp_complete_ctio(union ccb *);
835 static void isp_target_putback_atio(union ccb *);
836 enum Start_Ctio_How { FROM_CAM, FROM_TIMER, FROM_SRR, FROM_CTIO_DONE };
837 static void isp_target_start_ctio(ispsoftc_t *, union ccb *, enum Start_Ctio_How);
838 static void isp_handle_platform_atio2(ispsoftc_t *, at2_entry_t *);
839 static void isp_handle_platform_atio7(ispsoftc_t *, at7_entry_t *);
840 static void isp_handle_platform_ctio(ispsoftc_t *, void *);
841 static void isp_handle_platform_notify_fc(ispsoftc_t *, in_fcentry_t *);
842 static void isp_handle_platform_notify_24xx(ispsoftc_t *, in_fcentry_24xx_t *);
843 static int isp_handle_platform_target_notify_ack(ispsoftc_t *, isp_notify_t *);
844 static void isp_handle_platform_target_tmf(ispsoftc_t *, isp_notify_t *);
845 static void isp_target_mark_aborted(ispsoftc_t *, union ccb *);
846 static void isp_target_mark_aborted_early(ispsoftc_t *, tstate_t *, uint32_t);
847 
848 static ISP_INLINE int
849 is_lun_enabled(ispsoftc_t *isp, int bus, lun_id_t lun)
850 {
851 	tstate_t *tptr;
852 	struct tslist *lhp;
853 
854 	ISP_GET_PC_ADDR(isp, bus, lun_hash[LUN_HASH_FUNC(lun)], lhp);
855 	SLIST_FOREACH(tptr, lhp, next) {
856 		if (tptr->ts_lun == lun) {
857 			return (1);
858 		}
859 	}
860 	return (0);
861 }
862 
863 static void
864 dump_tstates(ispsoftc_t *isp, int bus)
865 {
866 	int i, j;
867 	struct tslist *lhp;
868 	tstate_t *tptr = NULL;
869 
870 	if (bus >= isp->isp_nchan) {
871 		return;
872 	}
873 	for (i = 0; i < LUN_HASH_SIZE; i++) {
874 		ISP_GET_PC_ADDR(isp, bus, lun_hash[i], lhp);
875 		j = 0;
876 		SLIST_FOREACH(tptr, lhp, next) {
877 			xpt_print(tptr->owner, "[%d, %d] atio_cnt=%d inot_cnt=%d\n", i, j, tptr->atio_count, tptr->inot_count);
878 			j++;
879 		}
880 	}
881 }
882 
883 static ISP_INLINE tstate_t *
884 get_lun_statep(ispsoftc_t *isp, int bus, lun_id_t lun)
885 {
886 	tstate_t *tptr = NULL;
887 	struct tslist *lhp;
888 
889 	if (bus < isp->isp_nchan) {
890 		ISP_GET_PC_ADDR(isp, bus, lun_hash[LUN_HASH_FUNC(lun)], lhp);
891 		SLIST_FOREACH(tptr, lhp, next) {
892 			if (tptr->ts_lun == lun) {
893 				tptr->hold++;
894 				return (tptr);
895 			}
896 		}
897 	}
898 	return (NULL);
899 }
900 
901 static ISP_INLINE tstate_t *
902 get_lun_statep_from_tag(ispsoftc_t *isp, int bus, uint32_t tagval)
903 {
904 	tstate_t *tptr = NULL;
905 	atio_private_data_t *atp;
906 	struct tslist *lhp;
907 	int i;
908 
909 	if (bus < isp->isp_nchan && tagval != 0) {
910 		for (i = 0; i < LUN_HASH_SIZE; i++) {
911 			ISP_GET_PC_ADDR(isp, bus, lun_hash[i], lhp);
912 			SLIST_FOREACH(tptr, lhp, next) {
913 				atp = isp_find_atpd(isp, tptr, tagval);
914 				if (atp) {
915 					tptr->hold++;
916 					return (tptr);
917 				}
918 			}
919 		}
920 	}
921 	return (NULL);
922 }
923 
924 static ISP_INLINE inot_private_data_t *
925 get_ntp_from_tagdata(ispsoftc_t *isp, uint32_t tag_id, uint32_t seq_id, tstate_t **rslt)
926 {
927 	inot_private_data_t *ntp;
928 	tstate_t *tptr;
929 	struct tslist *lhp;
930 	int bus, i;
931 
932 	for (bus = 0; bus < isp->isp_nchan; bus++) {
933 		for (i = 0; i < LUN_HASH_SIZE; i++) {
934 			ISP_GET_PC_ADDR(isp, bus, lun_hash[i], lhp);
935 			SLIST_FOREACH(tptr, lhp, next) {
936 				ntp = isp_find_ntpd(isp, tptr, tag_id, seq_id);
937 				if (ntp) {
938 					*rslt = tptr;
939 					tptr->hold++;
940 					return (ntp);
941 				}
942 			}
943 		}
944 	}
945 	return (NULL);
946 }
947 
948 static ISP_INLINE void
949 rls_lun_statep(ispsoftc_t *isp, tstate_t *tptr)
950 {
951 	KASSERT((tptr->hold), ("tptr not held"));
952 	tptr->hold--;
953 }
954 
955 static void
956 isp_tmcmd_restart(ispsoftc_t *isp)
957 {
958 	inot_private_data_t *ntp;
959 	inot_private_data_t *restart_queue;
960 	tstate_t *tptr;
961 	union ccb *ccb;
962 	struct tslist *lhp;
963 	int bus, i;
964 
965 	for (bus = 0; bus < isp->isp_nchan; bus++) {
966 		for (i = 0; i < LUN_HASH_SIZE; i++) {
967 			ISP_GET_PC_ADDR(isp, bus, lun_hash[i], lhp);
968 			SLIST_FOREACH(tptr, lhp, next) {
969 				if ((restart_queue = tptr->restart_queue) != NULL)
970 					tptr->restart_queue = NULL;
971 				while (restart_queue) {
972 					ntp = restart_queue;
973 					restart_queue = ntp->rd.nt.nt_hba;
974 					if (IS_24XX(isp)) {
975 						isp_prt(isp, ISP_LOGTDEBUG0, "%s: restarting resrc deprived %x", __func__, ((at7_entry_t *)ntp->rd.data)->at_rxid);
976 						isp_handle_platform_atio7(isp, (at7_entry_t *) ntp->rd.data);
977 					} else {
978 						isp_prt(isp, ISP_LOGTDEBUG0, "%s: restarting resrc deprived %x", __func__, ((at2_entry_t *)ntp->rd.data)->at_rxid);
979 						isp_handle_platform_atio2(isp, (at2_entry_t *) ntp->rd.data);
980 					}
981 					isp_put_ntpd(isp, tptr, ntp);
982 					if (tptr->restart_queue && restart_queue != NULL) {
983 						ntp = tptr->restart_queue;
984 						tptr->restart_queue = restart_queue;
985 						while (restart_queue->rd.nt.nt_hba) {
986 							restart_queue = restart_queue->rd.nt.nt_hba;
987 						}
988 						restart_queue->rd.nt.nt_hba = ntp;
989 						break;
990 					}
991 				}
992 				/*
993 				 * We only need to do this once per tptr
994 				 */
995 				if (!TAILQ_EMPTY(&tptr->waitq)) {
996 					ccb = (union ccb *)TAILQ_LAST(&tptr->waitq, isp_ccbq);
997 					TAILQ_REMOVE(&tptr->waitq, &ccb->ccb_h, periph_links.tqe);
998 					isp_target_start_ctio(isp, ccb, FROM_TIMER);
999 				}
1000 			}
1001 		}
1002 	}
1003 }
1004 
1005 static ISP_INLINE atio_private_data_t *
1006 isp_get_atpd(ispsoftc_t *isp, tstate_t *tptr, uint32_t tag)
1007 {
1008 	atio_private_data_t *atp;
1009 
1010 	atp = LIST_FIRST(&tptr->atfree);
1011 	if (atp) {
1012 		LIST_REMOVE(atp, next);
1013 		atp->tag = tag;
1014 		LIST_INSERT_HEAD(&tptr->atused[ATPDPHASH(tag)], atp, next);
1015 	}
1016 	return (atp);
1017 }
1018 
1019 static ISP_INLINE atio_private_data_t *
1020 isp_find_atpd(ispsoftc_t *isp, tstate_t *tptr, uint32_t tag)
1021 {
1022 	atio_private_data_t *atp;
1023 
1024 	LIST_FOREACH(atp, &tptr->atused[ATPDPHASH(tag)], next) {
1025 		if (atp->tag == tag)
1026 			return (atp);
1027 	}
1028 	return (NULL);
1029 }
1030 
1031 static ISP_INLINE void
1032 isp_put_atpd(ispsoftc_t *isp, tstate_t *tptr, atio_private_data_t *atp)
1033 {
1034 	if (atp->ests) {
1035 		isp_put_ecmd(isp, atp->ests);
1036 	}
1037 	LIST_REMOVE(atp, next);
1038 	memset(atp, 0, sizeof (*atp));
1039 	LIST_INSERT_HEAD(&tptr->atfree, atp, next);
1040 }
1041 
1042 static void
1043 isp_dump_atpd(ispsoftc_t *isp, tstate_t *tptr)
1044 {
1045 	atio_private_data_t *atp;
1046 	const char *states[8] = { "Free", "ATIO", "CAM", "CTIO", "LAST_CTIO", "PDON", "?6", "7" };
1047 
1048 	for (atp = tptr->atpool; atp < &tptr->atpool[ATPDPSIZE]; atp++) {
1049 		xpt_print(tptr->owner, "ATP: [0x%x] origdlen %u bytes_xfrd %u lun %x nphdl 0x%04x s_id 0x%06x d_id 0x%06x oxid 0x%04x state %s\n",
1050 		    atp->tag, atp->orig_datalen, atp->bytes_xfered, atp->lun, atp->nphdl, atp->sid, atp->portid, atp->oxid, states[atp->state & 0x7]);
1051 	}
1052 }
1053 
1054 
1055 static ISP_INLINE inot_private_data_t *
1056 isp_get_ntpd(ispsoftc_t *isp, tstate_t *tptr)
1057 {
1058 	inot_private_data_t *ntp;
1059 	ntp = tptr->ntfree;
1060 	if (ntp) {
1061 		tptr->ntfree = ntp->next;
1062 	}
1063 	return (ntp);
1064 }
1065 
1066 static ISP_INLINE inot_private_data_t *
1067 isp_find_ntpd(ispsoftc_t *isp, tstate_t *tptr, uint32_t tag_id, uint32_t seq_id)
1068 {
1069 	inot_private_data_t *ntp;
1070 	for (ntp = tptr->ntpool; ntp < &tptr->ntpool[ATPDPSIZE]; ntp++) {
1071 		if (ntp->rd.tag_id == tag_id && ntp->rd.seq_id == seq_id) {
1072 			return (ntp);
1073 		}
1074 	}
1075 	return (NULL);
1076 }
1077 
1078 static ISP_INLINE void
1079 isp_put_ntpd(ispsoftc_t *isp, tstate_t *tptr, inot_private_data_t *ntp)
1080 {
1081 	ntp->rd.tag_id = ntp->rd.seq_id = 0;
1082 	ntp->next = tptr->ntfree;
1083 	tptr->ntfree = ntp;
1084 }
1085 
1086 static cam_status
1087 create_lun_state(ispsoftc_t *isp, int bus, struct cam_path *path, tstate_t **rslt)
1088 {
1089 	cam_status status;
1090 	lun_id_t lun;
1091 	struct tslist *lhp;
1092 	tstate_t *tptr;
1093 	int i;
1094 
1095 	lun = xpt_path_lun_id(path);
1096 	if (lun != CAM_LUN_WILDCARD) {
1097 		if (ISP_MAX_LUNS(isp) > 0 && lun >= ISP_MAX_LUNS(isp)) {
1098 			return (CAM_LUN_INVALID);
1099 		}
1100 	}
1101 	if (is_lun_enabled(isp, bus, lun)) {
1102 		return (CAM_LUN_ALRDY_ENA);
1103 	}
1104 	tptr = malloc(sizeof (tstate_t), M_DEVBUF, M_NOWAIT|M_ZERO);
1105 	if (tptr == NULL) {
1106 		return (CAM_RESRC_UNAVAIL);
1107 	}
1108 	tptr->ts_lun = lun;
1109 	status = xpt_create_path(&tptr->owner, NULL, xpt_path_path_id(path), xpt_path_target_id(path), lun);
1110 	if (status != CAM_REQ_CMP) {
1111 		free(tptr, M_DEVBUF);
1112 		return (status);
1113 	}
1114 	SLIST_INIT(&tptr->atios);
1115 	SLIST_INIT(&tptr->inots);
1116 	TAILQ_INIT(&tptr->waitq);
1117 	LIST_INIT(&tptr->atfree);
1118 	for (i = ATPDPSIZE-1; i >= 0; i--)
1119 		LIST_INSERT_HEAD(&tptr->atfree, &tptr->atpool[i], next);
1120 	for (i = 0; i < ATPDPHASHSIZE; i++)
1121 		LIST_INIT(&tptr->atused[i]);
1122 	for (i = 0; i < ATPDPSIZE-1; i++)
1123 		tptr->ntpool[i].next = &tptr->ntpool[i+1];
1124 	tptr->ntfree = tptr->ntpool;
1125 	tptr->hold = 1;
1126 	ISP_GET_PC_ADDR(isp, bus, lun_hash[LUN_HASH_FUNC(lun)], lhp);
1127 	SLIST_INSERT_HEAD(lhp, tptr, next);
1128 	*rslt = tptr;
1129 	ISP_PATH_PRT(isp, ISP_LOGTDEBUG0, path, "created tstate\n");
1130 	return (CAM_REQ_CMP);
1131 }
1132 
1133 static ISP_INLINE void
1134 destroy_lun_state(ispsoftc_t *isp, tstate_t *tptr)
1135 {
1136 	union ccb *ccb;
1137 	struct tslist *lhp;
1138 
1139 	KASSERT((tptr->hold != 0), ("tptr is not held"));
1140 	KASSERT((tptr->hold == 1), ("tptr still held (%d)", tptr->hold));
1141 	do {
1142 		ccb = (union ccb *)SLIST_FIRST(&tptr->atios);
1143 		if (ccb) {
1144 			SLIST_REMOVE_HEAD(&tptr->atios, sim_links.sle);
1145 			ccb->ccb_h.status = CAM_REQ_ABORTED;
1146 			xpt_done(ccb);
1147 		}
1148 	} while (ccb);
1149 	do {
1150 		ccb = (union ccb *)SLIST_FIRST(&tptr->inots);
1151 		if (ccb) {
1152 			SLIST_REMOVE_HEAD(&tptr->inots, sim_links.sle);
1153 			ccb->ccb_h.status = CAM_REQ_ABORTED;
1154 			xpt_done(ccb);
1155 		}
1156 	} while (ccb);
1157 	ISP_GET_PC_ADDR(isp, cam_sim_bus(xpt_path_sim(tptr->owner)), lun_hash[LUN_HASH_FUNC(tptr->ts_lun)], lhp);
1158 	SLIST_REMOVE(lhp, tptr, tstate, next);
1159 	ISP_PATH_PRT(isp, ISP_LOGTDEBUG0, tptr->owner, "destroyed tstate\n");
1160 	xpt_free_path(tptr->owner);
1161 	free(tptr, M_DEVBUF);
1162 }
1163 
1164 static void
1165 isp_enable_lun(ispsoftc_t *isp, union ccb *ccb)
1166 {
1167 	tstate_t *tptr;
1168 	int bus;
1169 	target_id_t target;
1170 	lun_id_t lun;
1171 
1172 	if (!IS_FC(isp) || !ISP_CAP_TMODE(isp) || !ISP_CAP_SCCFW(isp)) {
1173 		xpt_print(ccb->ccb_h.path, "Target mode is not supported\n");
1174 		ccb->ccb_h.status = CAM_FUNC_NOTAVAIL;
1175 		xpt_done(ccb);
1176 		return;
1177 	}
1178 
1179 	/*
1180 	 * We only support either target and lun both wildcard
1181 	 * or target and lun both non-wildcard.
1182 	 */
1183 	bus = XS_CHANNEL(ccb);
1184 	target = ccb->ccb_h.target_id;
1185 	lun = ccb->ccb_h.target_lun;
1186 	ISP_PATH_PRT(isp, ISP_LOGTDEBUG0|ISP_LOGCONFIG, ccb->ccb_h.path,
1187 	    "enabling lun %jx\n", (uintmax_t)lun);
1188 	if ((target == CAM_TARGET_WILDCARD) != (lun == CAM_LUN_WILDCARD)) {
1189 		ccb->ccb_h.status = CAM_LUN_INVALID;
1190 		xpt_done(ccb);
1191 		return;
1192 	}
1193 
1194 	/* Create the state pointer. It should not already exist. */
1195 	tptr = get_lun_statep(isp, bus, lun);
1196 	if (tptr) {
1197 		ccb->ccb_h.status = CAM_LUN_ALRDY_ENA;
1198 		xpt_done(ccb);
1199 		return;
1200 	}
1201 	ccb->ccb_h.status = create_lun_state(isp, bus, ccb->ccb_h.path, &tptr);
1202 	if (ccb->ccb_h.status != CAM_REQ_CMP) {
1203 		xpt_done(ccb);
1204 		return;
1205 	}
1206 
1207 	rls_lun_statep(isp, tptr);
1208 	ccb->ccb_h.status = CAM_REQ_CMP;
1209 	xpt_done(ccb);
1210 }
1211 
1212 static void
1213 isp_disable_lun(ispsoftc_t *isp, union ccb *ccb)
1214 {
1215 	tstate_t *tptr = NULL;
1216 	int bus;
1217 	target_id_t target;
1218 	lun_id_t lun;
1219 
1220 	bus = XS_CHANNEL(ccb);
1221 	target = ccb->ccb_h.target_id;
1222 	lun = ccb->ccb_h.target_lun;
1223 	ISP_PATH_PRT(isp, ISP_LOGTDEBUG0|ISP_LOGCONFIG, ccb->ccb_h.path,
1224 	    "disabling lun %jx\n", (uintmax_t)lun);
1225 	if ((target == CAM_TARGET_WILDCARD) != (lun == CAM_LUN_WILDCARD)) {
1226 		ccb->ccb_h.status = CAM_LUN_INVALID;
1227 		xpt_done(ccb);
1228 		return;
1229 	}
1230 
1231 	/* Find the state pointer. */
1232 	if ((tptr = get_lun_statep(isp, bus, lun)) == NULL) {
1233 		ccb->ccb_h.status = CAM_PATH_INVALID;
1234 		xpt_done(ccb);
1235 		return;
1236 	}
1237 
1238 	destroy_lun_state(isp, tptr);
1239 	ccb->ccb_h.status = CAM_REQ_CMP;
1240 	xpt_done(ccb);
1241 }
1242 
1243 static void
1244 isp_target_start_ctio(ispsoftc_t *isp, union ccb *ccb, enum Start_Ctio_How how)
1245 {
1246 	int fctape, sendstatus, resid;
1247 	tstate_t *tptr;
1248 	fcparam *fcp;
1249 	atio_private_data_t *atp;
1250 	struct ccb_scsiio *cso;
1251 	uint32_t dmaresult, handle, xfrlen, sense_length, tmp;
1252 	uint8_t local[QENTRY_LEN];
1253 
1254 	tptr = get_lun_statep(isp, XS_CHANNEL(ccb), XS_LUN(ccb));
1255 	if (tptr == NULL) {
1256 		tptr = get_lun_statep(isp, XS_CHANNEL(ccb), CAM_LUN_WILDCARD);
1257 		if (tptr == NULL) {
1258 			isp_prt(isp, ISP_LOGERR, "%s: [0x%x] cannot find tstate pointer", __func__, ccb->csio.tag_id);
1259 			ccb->ccb_h.status = CAM_DEV_NOT_THERE;
1260 			xpt_done(ccb);
1261 			return;
1262 		}
1263 	}
1264 	isp_prt(isp, ISP_LOGTDEBUG0, "%s: ENTRY[0x%x] how %u xfrlen %u sendstatus %d sense_len %u", __func__, ccb->csio.tag_id, how, ccb->csio.dxfer_len,
1265 	    (ccb->ccb_h.flags & CAM_SEND_STATUS) != 0, ((ccb->ccb_h.flags & CAM_SEND_SENSE)? ccb->csio.sense_len : 0));
1266 
1267 	switch (how) {
1268 	case FROM_TIMER:
1269 	case FROM_CAM:
1270 		/*
1271 		 * Insert at the tail of the list, if any, waiting CTIO CCBs
1272 		 */
1273 		TAILQ_INSERT_TAIL(&tptr->waitq, &ccb->ccb_h, periph_links.tqe);
1274 		break;
1275 	case FROM_SRR:
1276 	case FROM_CTIO_DONE:
1277 		TAILQ_INSERT_HEAD(&tptr->waitq, &ccb->ccb_h, periph_links.tqe);
1278 		break;
1279 	}
1280 
1281 	while (TAILQ_FIRST(&tptr->waitq) != NULL) {
1282 		ccb = (union ccb *) TAILQ_FIRST(&tptr->waitq);
1283 		TAILQ_REMOVE(&tptr->waitq, &ccb->ccb_h, periph_links.tqe);
1284 
1285 		cso = &ccb->csio;
1286 		xfrlen = cso->dxfer_len;
1287 		if (xfrlen == 0) {
1288 			if ((ccb->ccb_h.flags & CAM_SEND_STATUS) == 0) {
1289 				ISP_PATH_PRT(isp, ISP_LOGERR, ccb->ccb_h.path, "a data transfer length of zero but no status to send is wrong\n");
1290 				ccb->ccb_h.status = CAM_REQ_INVALID;
1291 				xpt_done(ccb);
1292 				continue;
1293 			}
1294 		}
1295 
1296 		atp = isp_find_atpd(isp, tptr, cso->tag_id);
1297 		if (atp == NULL) {
1298 			isp_prt(isp, ISP_LOGERR, "%s: [0x%x] cannot find private data adjunct in %s", __func__, cso->tag_id, __func__);
1299 			isp_dump_atpd(isp, tptr);
1300 			ccb->ccb_h.status = CAM_REQ_CMP_ERR;
1301 			xpt_done(ccb);
1302 			continue;
1303 		}
1304 
1305 		/*
1306 		 * Is this command a dead duck?
1307 		 */
1308 		if (atp->dead) {
1309 			isp_prt(isp, ISP_LOGERR, "%s: [0x%x] not sending a CTIO for a dead command", __func__, cso->tag_id);
1310 			ccb->ccb_h.status = CAM_REQ_ABORTED;
1311 			xpt_done(ccb);
1312 			continue;
1313 		}
1314 
1315 		/*
1316 		 * Check to make sure we're still in target mode.
1317 		 */
1318 		fcp = FCPARAM(isp, XS_CHANNEL(ccb));
1319 		if ((fcp->role & ISP_ROLE_TARGET) == 0) {
1320 			isp_prt(isp, ISP_LOGERR, "%s: [0x%x] stopping sending a CTIO because we're no longer in target mode", __func__, cso->tag_id);
1321 			ccb->ccb_h.status = CAM_PROVIDE_FAIL;
1322 			xpt_done(ccb);
1323 			continue;
1324 		}
1325 
1326 		/*
1327 		 * We're only handling ATPD_CCB_OUTSTANDING outstanding CCB at a time (one of which
1328 		 * could be split into two CTIOs to split data and status).
1329 		 */
1330 		if (atp->ctcnt >= ATPD_CCB_OUTSTANDING) {
1331 			isp_prt(isp, ISP_LOGTINFO, "[0x%x] handling only %d CCBs at a time (flags for this ccb: 0x%x)", cso->tag_id, ATPD_CCB_OUTSTANDING, ccb->ccb_h.flags);
1332 			TAILQ_INSERT_HEAD(&tptr->waitq, &ccb->ccb_h, periph_links.tqe);
1333 			break;
1334 		}
1335 
1336 		/*
1337 		 * Does the initiator expect FC-Tape style responses?
1338 		 */
1339 		if ((atp->word3 & PRLI_WD3_RETRY) && fcp->fctape_enabled) {
1340 			fctape = 1;
1341 		} else {
1342 			fctape = 0;
1343 		}
1344 
1345 		/*
1346 		 * If we already did the data xfer portion of a CTIO that sends data
1347 		 * and status, don't do it again and do the status portion now.
1348 		 */
1349 		if (atp->sendst) {
1350 			isp_prt(isp, ISP_LOGTINFO, "[0x%x] now sending synthesized status orig_dl=%u xfered=%u bit=%u",
1351 			    cso->tag_id, atp->orig_datalen, atp->bytes_xfered, atp->bytes_in_transit);
1352 			xfrlen = 0;	/* we already did the data transfer */
1353 			atp->sendst = 0;
1354 		}
1355 		if (ccb->ccb_h.flags & CAM_SEND_STATUS) {
1356 			sendstatus = 1;
1357 		} else {
1358 			sendstatus = 0;
1359 		}
1360 
1361 		if (ccb->ccb_h.flags & CAM_SEND_SENSE) {
1362 			KASSERT((sendstatus != 0), ("how can you have CAM_SEND_SENSE w/o CAM_SEND_STATUS?"));
1363 			/*
1364 			 * Sense length is not the entire sense data structure size. Periph
1365 			 * drivers don't seem to be setting sense_len to reflect the actual
1366 			 * size. We'll peek inside to get the right amount.
1367 			 */
1368 			sense_length = cso->sense_len;
1369 
1370 			/*
1371 			 * This 'cannot' happen
1372 			 */
1373 			if (sense_length > (XCMD_SIZE - MIN_FCP_RESPONSE_SIZE)) {
1374 				sense_length = XCMD_SIZE - MIN_FCP_RESPONSE_SIZE;
1375 			}
1376 		} else {
1377 			sense_length = 0;
1378 		}
1379 
1380 		memset(local, 0, QENTRY_LEN);
1381 
1382 		/*
1383 		 * Check for overflow
1384 		 */
1385 		tmp = atp->bytes_xfered + atp->bytes_in_transit + xfrlen;
1386 		if (tmp > atp->orig_datalen) {
1387 			isp_prt(isp, ISP_LOGERR, "%s: [0x%x] data overflow by %u bytes", __func__, cso->tag_id, tmp - atp->orig_datalen);
1388 			ccb->ccb_h.status = CAM_DATA_RUN_ERR;
1389 			xpt_done(ccb);
1390 			continue;
1391 		}
1392 
1393 		if (IS_24XX(isp)) {
1394 			ct7_entry_t *cto = (ct7_entry_t *) local;
1395 
1396 			cto->ct_header.rqs_entry_type = RQSTYPE_CTIO7;
1397 			cto->ct_header.rqs_entry_count = 1;
1398 			cto->ct_header.rqs_seqno |= ATPD_SEQ_NOTIFY_CAM;
1399 			ATPD_SET_SEQNO(cto, atp);
1400 			cto->ct_nphdl = atp->nphdl;
1401 			cto->ct_rxid = atp->tag;
1402 			cto->ct_iid_lo = atp->portid;
1403 			cto->ct_iid_hi = atp->portid >> 16;
1404 			cto->ct_oxid = atp->oxid;
1405 			cto->ct_vpidx = ISP_GET_VPIDX(isp, XS_CHANNEL(ccb));
1406 			cto->ct_timeout = 120;
1407 			cto->ct_flags = atp->tattr << CT7_TASK_ATTR_SHIFT;
1408 
1409 			/*
1410 			 * Mode 1, status, no data. Only possible when we are sending status, have
1411 			 * no data to transfer, and any sense data can fit into a ct7_entry_t.
1412 			 *
1413 			 * Mode 2, status, no data. We have to use this in the case that
1414 			 * the sense data won't fit into a ct7_entry_t.
1415 			 *
1416 			 */
1417 			if (sendstatus && xfrlen == 0) {
1418 				cto->ct_flags |= CT7_SENDSTATUS | CT7_NO_DATA;
1419 				resid = atp->orig_datalen - atp->bytes_xfered - atp->bytes_in_transit;
1420 				if (sense_length <= MAXRESPLEN_24XX) {
1421 					if (resid < 0) {
1422 						cto->ct_resid = -resid;
1423 					} else if (resid > 0) {
1424 						cto->ct_resid = resid;
1425 					}
1426 					cto->ct_flags |= CT7_FLAG_MODE1;
1427 					cto->ct_scsi_status = cso->scsi_status;
1428 					if (resid < 0) {
1429 						cto->ct_scsi_status |= (FCP_RESID_OVERFLOW << 8);
1430 					} else if (resid > 0) {
1431 						cto->ct_scsi_status |= (FCP_RESID_UNDERFLOW << 8);
1432 					}
1433 					if (fctape) {
1434 						cto->ct_flags |= CT7_CONFIRM|CT7_EXPLCT_CONF;
1435 					}
1436 					if (sense_length) {
1437 						cto->ct_scsi_status |= (FCP_SNSLEN_VALID << 8);
1438 						cto->rsp.m1.ct_resplen = cto->ct_senselen = sense_length;
1439 						memcpy(cto->rsp.m1.ct_resp, &cso->sense_data, sense_length);
1440 					}
1441 				} else {
1442 					bus_addr_t addr;
1443 					char buf[XCMD_SIZE];
1444 					fcp_rsp_iu_t *rp;
1445 
1446 					if (atp->ests == NULL) {
1447 						atp->ests = isp_get_ecmd(isp);
1448 						if (atp->ests == NULL) {
1449 							TAILQ_INSERT_HEAD(&tptr->waitq, &ccb->ccb_h, periph_links.tqe);
1450 							break;
1451 						}
1452 					}
1453 					memset(buf, 0, sizeof (buf));
1454 					rp = (fcp_rsp_iu_t *)buf;
1455 					if (fctape) {
1456 						cto->ct_flags |= CT7_CONFIRM|CT7_EXPLCT_CONF;
1457 						rp->fcp_rsp_bits |= FCP_CONF_REQ;
1458 					}
1459 					cto->ct_flags |= CT7_FLAG_MODE2;
1460 	        			rp->fcp_rsp_scsi_status = cso->scsi_status;
1461 					if (resid < 0) {
1462 						rp->fcp_rsp_resid = -resid;
1463 						rp->fcp_rsp_bits |= FCP_RESID_OVERFLOW;
1464 					} else if (resid > 0) {
1465 						rp->fcp_rsp_resid = resid;
1466 						rp->fcp_rsp_bits |= FCP_RESID_UNDERFLOW;
1467 					}
1468 					if (sense_length) {
1469 	        				rp->fcp_rsp_snslen = sense_length;
1470 						cto->ct_senselen = sense_length;
1471 						rp->fcp_rsp_bits |= FCP_SNSLEN_VALID;
1472 						isp_put_fcp_rsp_iu(isp, rp, atp->ests);
1473 						memcpy(((fcp_rsp_iu_t *)atp->ests)->fcp_rsp_extra, &cso->sense_data, sense_length);
1474 					} else {
1475 						isp_put_fcp_rsp_iu(isp, rp, atp->ests);
1476 					}
1477 					if (isp->isp_dblev & ISP_LOGTDEBUG1) {
1478 						isp_print_bytes(isp, "FCP Response Frame After Swizzling", MIN_FCP_RESPONSE_SIZE + sense_length, atp->ests);
1479 					}
1480 					addr = isp->isp_osinfo.ecmd_dma;
1481 					addr += ((((isp_ecmd_t *)atp->ests) - isp->isp_osinfo.ecmd_base) * XCMD_SIZE);
1482 					isp_prt(isp, ISP_LOGTDEBUG0, "%s: ests base %p vaddr %p ecmd_dma %jx addr %jx len %u", __func__, isp->isp_osinfo.ecmd_base, atp->ests,
1483 					    (uintmax_t) isp->isp_osinfo.ecmd_dma, (uintmax_t)addr, MIN_FCP_RESPONSE_SIZE + sense_length);
1484 					cto->rsp.m2.ct_datalen = MIN_FCP_RESPONSE_SIZE + sense_length;
1485 					cto->rsp.m2.ct_fcp_rsp_iudata.ds_base = DMA_LO32(addr);
1486 					cto->rsp.m2.ct_fcp_rsp_iudata.ds_basehi = DMA_HI32(addr);
1487 					cto->rsp.m2.ct_fcp_rsp_iudata.ds_count = MIN_FCP_RESPONSE_SIZE + sense_length;
1488 				}
1489 				if (sense_length) {
1490 					isp_prt(isp, ISP_LOGTDEBUG0, "%s: CTIO7[0x%x] seq %u nc %d CDB0=%x sstatus=0x%x flags=0x%x resid=%d slen %u sense: %x %x/%x/%x", __func__,
1491 					    cto->ct_rxid, ATPD_GET_SEQNO(cto), ATPD_GET_NCAM(cto), atp->cdb0, cto->ct_scsi_status, cto->ct_flags, cto->ct_resid, sense_length,
1492 					    cso->sense_data.error_code, cso->sense_data.sense_buf[1], cso->sense_data.sense_buf[11], cso->sense_data.sense_buf[12]);
1493 				} else {
1494 					isp_prt(isp, ISP_LOGDEBUG0, "%s: CTIO7[0x%x] seq %u nc %d CDB0=%x sstatus=0x%x flags=0x%x resid=%d", __func__,
1495 					    cto->ct_rxid, ATPD_GET_SEQNO(cto), ATPD_GET_NCAM(cto), atp->cdb0, cto->ct_scsi_status, cto->ct_flags, cto->ct_resid);
1496 				}
1497 				atp->state = ATPD_STATE_LAST_CTIO;
1498 			}
1499 
1500 			/*
1501 			 * Mode 0 data transfers, *possibly* with status.
1502 			 */
1503 			if (xfrlen != 0) {
1504 				cto->ct_flags |= CT7_FLAG_MODE0;
1505 				if ((cso->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
1506 					cto->ct_flags |= CT7_DATA_IN;
1507 				} else {
1508 					cto->ct_flags |= CT7_DATA_OUT;
1509 				}
1510 
1511 				cto->rsp.m0.reloff = atp->bytes_xfered + atp->bytes_in_transit;
1512 				cto->rsp.m0.ct_xfrlen = xfrlen;
1513 
1514 #ifdef	DEBUG
1515 				if (ISP_FC_PC(isp, XS_CHANNEL(ccb))->inject_lost_data_frame && xfrlen > ISP_FC_PC(isp, XS_CHANNEL(ccb))->inject_lost_data_frame) {
1516 					isp_prt(isp, ISP_LOGWARN, "%s: truncating data frame with xfrlen %d to %d", __func__, xfrlen, xfrlen - (xfrlen >> 2));
1517 					ISP_FC_PC(isp, XS_CHANNEL(ccb))->inject_lost_data_frame = 0;
1518 					cto->rsp.m0.ct_xfrlen -= xfrlen >> 2;
1519 				}
1520 #endif
1521 				if (sendstatus) {
1522 					resid = atp->orig_datalen - atp->bytes_xfered - xfrlen;
1523 					if (cso->scsi_status == SCSI_STATUS_OK && resid == 0 /* && fctape == 0 */) {
1524 						cto->ct_flags |= CT7_SENDSTATUS;
1525 						atp->state = ATPD_STATE_LAST_CTIO;
1526 						if (fctape) {
1527 							cto->ct_flags |= CT7_CONFIRM|CT7_EXPLCT_CONF;
1528 						}
1529 					} else {
1530 						atp->sendst = 1;	/* send status later */
1531 						cto->ct_header.rqs_seqno &= ~ATPD_SEQ_NOTIFY_CAM;
1532 						atp->state = ATPD_STATE_CTIO;
1533 					}
1534 				} else {
1535 					atp->state = ATPD_STATE_CTIO;
1536 				}
1537 				isp_prt(isp, ISP_LOGTDEBUG0, "%s: CTIO7[0x%x] seq %u nc %d CDB0=%x sstatus=0x%x flags=0x%x xfrlen=%u off=%u", __func__,
1538 				    cto->ct_rxid, ATPD_GET_SEQNO(cto), ATPD_GET_NCAM(cto), atp->cdb0, cto->ct_scsi_status, cto->ct_flags, xfrlen, atp->bytes_xfered);
1539 			}
1540 		} else {
1541 			ct2_entry_t *cto = (ct2_entry_t *) local;
1542 
1543 			if (isp->isp_osinfo.sixtyfourbit)
1544 				cto->ct_header.rqs_entry_type = RQSTYPE_CTIO3;
1545 			else
1546 				cto->ct_header.rqs_entry_type = RQSTYPE_CTIO2;
1547 			cto->ct_header.rqs_entry_count = 1;
1548 			cto->ct_header.rqs_seqno |= ATPD_SEQ_NOTIFY_CAM;
1549 			ATPD_SET_SEQNO(cto, atp);
1550 			if (ISP_CAP_2KLOGIN(isp)) {
1551 				((ct2e_entry_t *)cto)->ct_iid = atp->nphdl;
1552 			} else {
1553 				cto->ct_iid = atp->nphdl;
1554 				if (ISP_CAP_SCCFW(isp) == 0) {
1555 					cto->ct_lun = ccb->ccb_h.target_lun;
1556 				}
1557 			}
1558 			cto->ct_timeout = 10;
1559 			cto->ct_rxid = cso->tag_id;
1560 
1561 			/*
1562 			 * Mode 1, status, no data. Only possible when we are sending status, have
1563 			 * no data to transfer, and the sense length can fit in the ct7_entry.
1564 			 *
1565 			 * Mode 2, status, no data. We have to use this in the case the response
1566 			 * length won't fit into a ct2_entry_t.
1567 			 *
1568 			 * We'll fill out this structure with information as if this were a
1569 			 * Mode 1. The hardware layer will create the Mode 2 FCP RSP IU as
1570 			 * needed based upon this.
1571 			 */
1572 			if (sendstatus && xfrlen == 0) {
1573 				cto->ct_flags |= CT2_SENDSTATUS | CT2_NO_DATA;
1574 				resid = atp->orig_datalen - atp->bytes_xfered - atp->bytes_in_transit;
1575 				if (sense_length <= MAXRESPLEN) {
1576 					if (resid < 0) {
1577 						cto->ct_resid = -resid;
1578 					} else if (resid > 0) {
1579 						cto->ct_resid = resid;
1580 					}
1581 					cto->ct_flags |= CT2_FLAG_MODE1;
1582 					cto->rsp.m1.ct_scsi_status = cso->scsi_status;
1583 					if (resid < 0) {
1584 						cto->rsp.m1.ct_scsi_status |= CT2_DATA_OVER;
1585 					} else if (resid > 0) {
1586 						cto->rsp.m1.ct_scsi_status |= CT2_DATA_UNDER;
1587 					}
1588 					if (fctape) {
1589 						cto->ct_flags |= CT2_CONFIRM;
1590 					}
1591 					if (sense_length) {
1592 						cto->rsp.m1.ct_scsi_status |= CT2_SNSLEN_VALID;
1593 						cto->rsp.m1.ct_resplen = cto->rsp.m1.ct_senselen = sense_length;
1594 						memcpy(cto->rsp.m1.ct_resp, &cso->sense_data, sense_length);
1595 					}
1596 				} else {
1597 					bus_addr_t addr;
1598 					char buf[XCMD_SIZE];
1599 					fcp_rsp_iu_t *rp;
1600 
1601 					if (atp->ests == NULL) {
1602 						atp->ests = isp_get_ecmd(isp);
1603 						if (atp->ests == NULL) {
1604 							TAILQ_INSERT_HEAD(&tptr->waitq, &ccb->ccb_h, periph_links.tqe);
1605 							break;
1606 						}
1607 					}
1608 					memset(buf, 0, sizeof (buf));
1609 					rp = (fcp_rsp_iu_t *)buf;
1610 					if (fctape) {
1611 						cto->ct_flags |= CT2_CONFIRM;
1612 						rp->fcp_rsp_bits |= FCP_CONF_REQ;
1613 					}
1614 					cto->ct_flags |= CT2_FLAG_MODE2;
1615 	        			rp->fcp_rsp_scsi_status = cso->scsi_status;
1616 					if (resid < 0) {
1617 						rp->fcp_rsp_resid = -resid;
1618 						rp->fcp_rsp_bits |= FCP_RESID_OVERFLOW;
1619 					} else if (resid > 0) {
1620 						rp->fcp_rsp_resid = resid;
1621 						rp->fcp_rsp_bits |= FCP_RESID_UNDERFLOW;
1622 					}
1623 					if (sense_length) {
1624 	        				rp->fcp_rsp_snslen = sense_length;
1625 						rp->fcp_rsp_bits |= FCP_SNSLEN_VALID;
1626 						isp_put_fcp_rsp_iu(isp, rp, atp->ests);
1627 						memcpy(((fcp_rsp_iu_t *)atp->ests)->fcp_rsp_extra, &cso->sense_data, sense_length);
1628 					} else {
1629 						isp_put_fcp_rsp_iu(isp, rp, atp->ests);
1630 					}
1631 					if (isp->isp_dblev & ISP_LOGTDEBUG1) {
1632 						isp_print_bytes(isp, "FCP Response Frame After Swizzling", MIN_FCP_RESPONSE_SIZE + sense_length, atp->ests);
1633 					}
1634 					addr = isp->isp_osinfo.ecmd_dma;
1635 					addr += ((((isp_ecmd_t *)atp->ests) - isp->isp_osinfo.ecmd_base) * XCMD_SIZE);
1636 					isp_prt(isp, ISP_LOGTDEBUG0, "%s: ests base %p vaddr %p ecmd_dma %jx addr %jx len %u", __func__, isp->isp_osinfo.ecmd_base, atp->ests,
1637 					    (uintmax_t) isp->isp_osinfo.ecmd_dma, (uintmax_t)addr, MIN_FCP_RESPONSE_SIZE + sense_length);
1638 					cto->rsp.m2.ct_datalen = MIN_FCP_RESPONSE_SIZE + sense_length;
1639 					if (isp->isp_osinfo.sixtyfourbit) {
1640 						cto->rsp.m2.u.ct_fcp_rsp_iudata_64.ds_base = DMA_LO32(addr);
1641 						cto->rsp.m2.u.ct_fcp_rsp_iudata_64.ds_basehi = DMA_HI32(addr);
1642 						cto->rsp.m2.u.ct_fcp_rsp_iudata_64.ds_count = MIN_FCP_RESPONSE_SIZE + sense_length;
1643 					} else {
1644 						cto->rsp.m2.u.ct_fcp_rsp_iudata_32.ds_base = DMA_LO32(addr);
1645 						cto->rsp.m2.u.ct_fcp_rsp_iudata_32.ds_count = MIN_FCP_RESPONSE_SIZE + sense_length;
1646 					}
1647 				}
1648 				if (sense_length) {
1649 					isp_prt(isp, ISP_LOGTDEBUG0, "%s: CTIO2[0x%x] seq %u nc %d CDB0=%x sstatus=0x%x flags=0x%x resid=%d sense: %x %x/%x/%x", __func__,
1650 					    cto->ct_rxid, ATPD_GET_SEQNO(cto), ATPD_GET_NCAM(cto), atp->cdb0, cso->scsi_status, cto->ct_flags, cto->ct_resid,
1651 					    cso->sense_data.error_code, cso->sense_data.sense_buf[1], cso->sense_data.sense_buf[11], cso->sense_data.sense_buf[12]);
1652 				} else {
1653 					isp_prt(isp, ISP_LOGTDEBUG0, "%s: CTIO2[0x%x] seq %u nc %d CDB0=%x sstatus=0x%x flags=0x%x resid=%d", __func__, cto->ct_rxid,
1654 					    ATPD_GET_SEQNO(cto), ATPD_GET_NCAM(cto), atp->cdb0, cso->scsi_status, cto->ct_flags, cto->ct_resid);
1655 				}
1656 				atp->state = ATPD_STATE_LAST_CTIO;
1657 			}
1658 
1659 			if (xfrlen != 0) {
1660 				cto->ct_flags |= CT2_FLAG_MODE0;
1661 				if ((cso->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
1662 					cto->ct_flags |= CT2_DATA_IN;
1663 				} else {
1664 					cto->ct_flags |= CT2_DATA_OUT;
1665 				}
1666 
1667 				cto->ct_reloff = atp->bytes_xfered + atp->bytes_in_transit;
1668 				cto->rsp.m0.ct_xfrlen = xfrlen;
1669 
1670 				if (sendstatus) {
1671 					resid = atp->orig_datalen - atp->bytes_xfered - xfrlen;
1672 					if (cso->scsi_status == SCSI_STATUS_OK && resid == 0 /*&& fctape == 0*/) {
1673 						cto->ct_flags |= CT2_SENDSTATUS;
1674 						atp->state = ATPD_STATE_LAST_CTIO;
1675 						if (fctape) {
1676 							cto->ct_flags |= CT2_CONFIRM;
1677 						}
1678 					} else {
1679 						atp->sendst = 1;	/* send status later */
1680 						cto->ct_header.rqs_seqno &= ~ATPD_SEQ_NOTIFY_CAM;
1681 						atp->state = ATPD_STATE_CTIO;
1682 					}
1683 				} else {
1684 					atp->state = ATPD_STATE_CTIO;
1685 				}
1686 			}
1687 			isp_prt(isp, ISP_LOGTDEBUG0, "%s: CTIO2[%x] seq %u nc %d CDB0=%x scsi status %x flags %x resid %d xfrlen %u offset %u", __func__, cto->ct_rxid,
1688 			    ATPD_GET_SEQNO(cto), ATPD_GET_NCAM(cto), atp->cdb0, cso->scsi_status, cto->ct_flags, cto->ct_resid, cso->dxfer_len, atp->bytes_xfered);
1689 		}
1690 
1691 		if (isp_get_pcmd(isp, ccb)) {
1692 			ISP_PATH_PRT(isp, ISP_LOGWARN, ccb->ccb_h.path, "out of PCMDs\n");
1693 			TAILQ_INSERT_HEAD(&tptr->waitq, &ccb->ccb_h, periph_links.tqe);
1694 			break;
1695 		}
1696 		if (isp_allocate_xs_tgt(isp, ccb, &handle)) {
1697 			ISP_PATH_PRT(isp, ISP_LOGWARN, ccb->ccb_h.path, "No XFLIST pointers for %s\n", __func__);
1698 			TAILQ_INSERT_HEAD(&tptr->waitq, &ccb->ccb_h, periph_links.tqe);
1699 			isp_free_pcmd(isp, ccb);
1700 			break;
1701 		}
1702 		atp->bytes_in_transit += xfrlen;
1703 		PISP_PCMD(ccb)->datalen = xfrlen;
1704 
1705 
1706 		/*
1707 		 * Call the dma setup routines for this entry (and any subsequent
1708 		 * CTIOs) if there's data to move, and then tell the f/w it's got
1709 		 * new things to play with. As with isp_start's usage of DMA setup,
1710 		 * any swizzling is done in the machine dependent layer. Because
1711 		 * of this, we put the request onto the queue area first in native
1712 		 * format.
1713 		 */
1714 
1715 		if (IS_24XX(isp)) {
1716 			ct7_entry_t *cto = (ct7_entry_t *) local;
1717 			cto->ct_syshandle = handle;
1718 		} else {
1719 			ct2_entry_t *cto = (ct2_entry_t *) local;
1720 			cto->ct_syshandle = handle;
1721 		}
1722 
1723 		dmaresult = ISP_DMASETUP(isp, cso, (ispreq_t *) local);
1724 		if (dmaresult != CMD_QUEUED) {
1725 			isp_destroy_tgt_handle(isp, handle);
1726 			isp_free_pcmd(isp, ccb);
1727 			if (dmaresult == CMD_EAGAIN) {
1728 				TAILQ_INSERT_HEAD(&tptr->waitq, &ccb->ccb_h, periph_links.tqe);
1729 				break;
1730 			}
1731 			ccb->ccb_h.status = CAM_REQ_CMP_ERR;
1732 			xpt_done(ccb);
1733 			continue;
1734 		}
1735 		isp->isp_nactive++;
1736 		ccb->ccb_h.status = CAM_REQ_INPROG | CAM_SIM_QUEUED;
1737 		if (xfrlen) {
1738 			ccb->ccb_h.spriv_field0 = atp->bytes_xfered;
1739 		} else {
1740 			ccb->ccb_h.spriv_field0 = ~0;
1741 		}
1742 		atp->ctcnt++;
1743 		atp->seqno++;
1744 	}
1745 	rls_lun_statep(isp, tptr);
1746 }
1747 
1748 static void
1749 isp_refire_putback_atio(void *arg)
1750 {
1751 	union ccb *ccb = arg;
1752 
1753 	ISP_ASSERT_LOCKED((ispsoftc_t *)XS_ISP(ccb));
1754 	isp_target_putback_atio(ccb);
1755 }
1756 
1757 static void
1758 isp_refire_notify_ack(void *arg)
1759 {
1760 	isp_tna_t *tp  = arg;
1761 	ispsoftc_t *isp = tp->isp;
1762 
1763 	ISP_ASSERT_LOCKED(isp);
1764 	if (isp_notify_ack(isp, tp->not)) {
1765 		callout_schedule(&tp->timer, 5);
1766 	} else {
1767 		free(tp, M_DEVBUF);
1768 	}
1769 }
1770 
1771 
1772 static void
1773 isp_target_putback_atio(union ccb *ccb)
1774 {
1775 	ispsoftc_t *isp;
1776 	struct ccb_scsiio *cso;
1777 	void *qe;
1778 	at2_entry_t local, *at = &local;
1779 
1780 	isp = XS_ISP(ccb);
1781 
1782 	qe = isp_getrqentry(isp);
1783 	if (qe == NULL) {
1784 		xpt_print(ccb->ccb_h.path,
1785 		    "%s: Request Queue Overflow\n", __func__);
1786 		callout_reset(&PISP_PCMD(ccb)->wdog, 10,
1787 		    isp_refire_putback_atio, ccb);
1788 		return;
1789 	}
1790 	memset(qe, 0, QENTRY_LEN);
1791 	cso = &ccb->csio;
1792 	ISP_MEMZERO(at, sizeof (at2_entry_t));
1793 	at->at_header.rqs_entry_type = RQSTYPE_ATIO2;
1794 	at->at_header.rqs_entry_count = 1;
1795 	if (ISP_CAP_SCCFW(isp)) {
1796 		at->at_scclun = (uint16_t) ccb->ccb_h.target_lun;
1797 #if __FreeBSD_version < 1000700
1798 		if (at->at_scclun >= 256)
1799 			at->at_scclun |= 0x4000;
1800 #endif
1801 	} else {
1802 		at->at_lun = (uint8_t) ccb->ccb_h.target_lun;
1803 	}
1804 	at->at_status = CT_OK;
1805 	at->at_rxid = cso->tag_id;
1806 	at->at_iid = cso->ccb_h.target_id;
1807 	isp_put_atio2(isp, at, qe);
1808 	ISP_TDQE(isp, "isp_target_putback_atio", isp->isp_reqidx, qe);
1809 	ISP_SYNC_REQUEST(isp);
1810 	isp_complete_ctio(ccb);
1811 }
1812 
1813 static void
1814 isp_complete_ctio(union ccb *ccb)
1815 {
1816 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_INPROG) {
1817 		ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
1818 		xpt_done(ccb);
1819 	}
1820 }
1821 
1822 static void
1823 isp_handle_platform_atio2(ispsoftc_t *isp, at2_entry_t *aep)
1824 {
1825 	fcparam *fcp;
1826 	lun_id_t lun;
1827 	fcportdb_t *lp;
1828 	tstate_t *tptr;
1829 	struct ccb_accept_tio *atiop;
1830 	uint16_t nphdl;
1831 	atio_private_data_t *atp;
1832 	inot_private_data_t *ntp;
1833 
1834 	/*
1835 	 * The firmware status (except for the QLTM_SVALID bit)
1836 	 * indicates why this ATIO was sent to us.
1837 	 *
1838 	 * If QLTM_SVALID is set, the firmware has recommended Sense Data.
1839 	 */
1840 	if ((aep->at_status & ~QLTM_SVALID) != AT_CDB) {
1841 		isp_prt(isp, ISP_LOGWARN, "bogus atio (0x%x) leaked to platform", aep->at_status);
1842 		isp_endcmd(isp, aep, SCSI_STATUS_BUSY, 0);
1843 		return;
1844 	}
1845 
1846 	fcp = FCPARAM(isp, 0);
1847 	if (ISP_CAP_SCCFW(isp)) {
1848 		lun = aep->at_scclun;
1849 #if __FreeBSD_version < 1000700
1850 		lun &= 0x3fff;
1851 #endif
1852 	} else {
1853 		lun = aep->at_lun;
1854 	}
1855 	if (ISP_CAP_2KLOGIN(isp)) {
1856 		nphdl = ((at2e_entry_t *)aep)->at_iid;
1857 	} else {
1858 		nphdl = aep->at_iid;
1859 	}
1860 	tptr = get_lun_statep(isp, 0, lun);
1861 	if (tptr == NULL) {
1862 		tptr = get_lun_statep(isp, 0, CAM_LUN_WILDCARD);
1863 		if (tptr == NULL) {
1864 			isp_prt(isp, ISP_LOGWARN, "%s: [0x%x] no state pointer for lun %jx or wildcard", __func__, aep->at_rxid, (uintmax_t)lun);
1865 			if (lun == 0) {
1866 				isp_endcmd(isp, aep, SCSI_STATUS_BUSY, 0);
1867 			} else {
1868 				isp_endcmd(isp, aep, SCSI_STATUS_CHECK_COND | ECMD_SVALID | (0x5 << 12) | (0x25 << 16), 0);
1869 			}
1870 			return;
1871 		}
1872 	}
1873 
1874 	/*
1875 	 * Start any commands pending resources first.
1876 	 */
1877 	if (tptr->restart_queue) {
1878 		inot_private_data_t *restart_queue = tptr->restart_queue;
1879 		tptr->restart_queue = NULL;
1880 		while (restart_queue) {
1881 			ntp = restart_queue;
1882 			restart_queue = ntp->rd.nt.nt_hba;
1883 			isp_prt(isp, ISP_LOGTDEBUG0, "%s: restarting resrc deprived %x", __func__, ((at2_entry_t *)ntp->rd.data)->at_rxid);
1884 			isp_handle_platform_atio2(isp, (at2_entry_t *) ntp->rd.data);
1885 			isp_put_ntpd(isp, tptr, ntp);
1886 			/*
1887 			 * If a recursion caused the restart queue to start to fill again,
1888 			 * stop and splice the new list on top of the old list and restore
1889 			 * it and go to noresrc.
1890 			 */
1891 			if (tptr->restart_queue) {
1892 				ntp = tptr->restart_queue;
1893 				tptr->restart_queue = restart_queue;
1894 				while (restart_queue->rd.nt.nt_hba) {
1895 					restart_queue = restart_queue->rd.nt.nt_hba;
1896 				}
1897 				restart_queue->rd.nt.nt_hba = ntp;
1898 				goto noresrc;
1899 			}
1900 		}
1901 	}
1902 
1903 	atiop = (struct ccb_accept_tio *) SLIST_FIRST(&tptr->atios);
1904 	if (atiop == NULL) {
1905 		goto noresrc;
1906 	}
1907 
1908 	atp = isp_get_atpd(isp, tptr, aep->at_rxid);
1909 	if (atp == NULL) {
1910 		goto noresrc;
1911 	}
1912 
1913 	atp->state = ATPD_STATE_ATIO;
1914 	SLIST_REMOVE_HEAD(&tptr->atios, sim_links.sle);
1915 	tptr->atio_count--;
1916 	isp_prt(isp, ISP_LOGTDEBUG2, "Take FREE ATIO count now %d", tptr->atio_count);
1917 	atiop->ccb_h.target_id = fcp->isp_loopid;
1918 	atiop->ccb_h.target_lun = lun;
1919 
1920 	/*
1921 	 * We don't get 'suggested' sense data as we do with SCSI cards.
1922 	 */
1923 	atiop->sense_len = 0;
1924 
1925 	/*
1926 	 * If we're not in the port database, add ourselves.
1927 	 */
1928 	if (IS_2100(isp))
1929 		atiop->init_id = nphdl;
1930 	else {
1931 		if ((isp_find_pdb_by_handle(isp, 0, nphdl, &lp) == 0 ||
1932 		     lp->state == FC_PORTDB_STATE_ZOMBIE)) {
1933 			uint64_t wwpn =
1934 				(((uint64_t) aep->at_wwpn[0]) << 48) |
1935 				(((uint64_t) aep->at_wwpn[1]) << 32) |
1936 				(((uint64_t) aep->at_wwpn[2]) << 16) |
1937 				(((uint64_t) aep->at_wwpn[3]) <<  0);
1938 			isp_add_wwn_entry(isp, 0, wwpn, INI_NONE,
1939 			    nphdl, PORT_ANY, 0);
1940 			if (fcp->isp_loopstate > LOOP_LTEST_DONE)
1941 				fcp->isp_loopstate = LOOP_LTEST_DONE;
1942 			isp_async(isp, ISPASYNC_CHANGE_NOTIFY, 0,
1943 			    ISPASYNC_CHANGE_PDB, nphdl, 0x06, 0xff);
1944 			isp_find_pdb_by_handle(isp, 0, nphdl, &lp);
1945 		}
1946 		atiop->init_id = FC_PORTDB_TGT(isp, 0, lp);
1947 	}
1948 	atiop->cdb_len = ATIO2_CDBLEN;
1949 	ISP_MEMCPY(atiop->cdb_io.cdb_bytes, aep->at_cdb, ATIO2_CDBLEN);
1950 	atiop->ccb_h.status = CAM_CDB_RECVD;
1951 	atiop->tag_id = atp->tag;
1952 	switch (aep->at_taskflags & ATIO2_TC_ATTR_MASK) {
1953 	case ATIO2_TC_ATTR_SIMPLEQ:
1954 		atiop->ccb_h.flags |= CAM_TAG_ACTION_VALID;
1955 		atiop->tag_action = MSG_SIMPLE_Q_TAG;
1956 		break;
1957 	case ATIO2_TC_ATTR_HEADOFQ:
1958 		atiop->ccb_h.flags |= CAM_TAG_ACTION_VALID;
1959 		atiop->tag_action = MSG_HEAD_OF_Q_TAG;
1960 		break;
1961 	case ATIO2_TC_ATTR_ORDERED:
1962 		atiop->ccb_h.flags |= CAM_TAG_ACTION_VALID;
1963 		atiop->tag_action = MSG_ORDERED_Q_TAG;
1964 		break;
1965 	case ATIO2_TC_ATTR_ACAQ:		/* ?? */
1966 	case ATIO2_TC_ATTR_UNTAGGED:
1967 	default:
1968 		atiop->tag_action = 0;
1969 		break;
1970 	}
1971 
1972 	atp->orig_datalen = aep->at_datalen;
1973 	atp->bytes_xfered = 0;
1974 	atp->lun = lun;
1975 	atp->nphdl = nphdl;
1976 	atp->sid = PORT_ANY;
1977 	atp->oxid = aep->at_oxid;
1978 	atp->cdb0 = aep->at_cdb[0];
1979 	atp->tattr = aep->at_taskflags & ATIO2_TC_ATTR_MASK;
1980 	atp->state = ATPD_STATE_CAM;
1981 	xpt_done((union ccb *)atiop);
1982 	isp_prt(isp, ISP_LOGTDEBUG0, "ATIO2[0x%x] CDB=0x%x lun %jx datalen %u", aep->at_rxid, atp->cdb0, (uintmax_t)lun, atp->orig_datalen);
1983 	rls_lun_statep(isp, tptr);
1984 	return;
1985 noresrc:
1986 	ntp = isp_get_ntpd(isp, tptr);
1987 	if (ntp == NULL) {
1988 		rls_lun_statep(isp, tptr);
1989 		isp_endcmd(isp, aep, nphdl, 0, SCSI_STATUS_BUSY, 0);
1990 		return;
1991 	}
1992 	memcpy(ntp->rd.data, aep, QENTRY_LEN);
1993 	ntp->rd.nt.nt_hba = tptr->restart_queue;
1994 	tptr->restart_queue = ntp;
1995 	rls_lun_statep(isp, tptr);
1996 }
1997 
1998 static void
1999 isp_handle_platform_atio7(ispsoftc_t *isp, at7_entry_t *aep)
2000 {
2001 	int cdbxlen;
2002 	lun_id_t lun;
2003 	uint16_t chan, nphdl = NIL_HANDLE;
2004 	uint32_t did, sid;
2005 	fcportdb_t *lp;
2006 	tstate_t *tptr;
2007 	struct ccb_accept_tio *atiop;
2008 	atio_private_data_t *atp = NULL;
2009 	atio_private_data_t *oatp;
2010 	inot_private_data_t *ntp;
2011 
2012 	did = (aep->at_hdr.d_id[0] << 16) | (aep->at_hdr.d_id[1] << 8) | aep->at_hdr.d_id[2];
2013 	sid = (aep->at_hdr.s_id[0] << 16) | (aep->at_hdr.s_id[1] << 8) | aep->at_hdr.s_id[2];
2014 #if __FreeBSD_version >= 1000700
2015 	lun = CAM_EXTLUN_BYTE_SWIZZLE(be64dec(aep->at_cmnd.fcp_cmnd_lun));
2016 #else
2017 	lun = (aep->at_cmnd.fcp_cmnd_lun[0] & 0x3f << 8) |
2018 	    aep->at_cmnd.fcp_cmnd_lun[1];
2019 #endif
2020 
2021 	/*
2022 	 * Find the N-port handle, and Virtual Port Index for this command.
2023 	 *
2024 	 * If we can't, we're somewhat in trouble because we can't actually respond w/o that information.
2025 	 * We also, as a matter of course, need to know the WWN of the initiator too.
2026 	 */
2027 	if (ISP_CAP_MULTI_ID(isp) && isp->isp_nchan > 1) {
2028 		/*
2029 		 * Find the right channel based upon D_ID
2030 		 */
2031 		isp_find_chan_by_did(isp, did, &chan);
2032 
2033 		if (chan == ISP_NOCHAN) {
2034 			NANOTIME_T now;
2035 
2036 			/*
2037 			 * If we don't recognizer our own D_DID, terminate the exchange, unless we're within 2 seconds of startup
2038 			 * It's a bit tricky here as we need to stash this command *somewhere*.
2039 			 */
2040 			GET_NANOTIME(&now);
2041 			if (NANOTIME_SUB(&isp->isp_init_time, &now) > 2000000000ULL) {
2042 				isp_prt(isp, ISP_LOGWARN, "%s: [RX_ID 0x%x] D_ID %x not found on any channel- dropping", __func__, aep->at_rxid, did);
2043 				isp_endcmd(isp, aep, NIL_HANDLE, ISP_NOCHAN, ECMD_TERMINATE, 0);
2044 				return;
2045 			}
2046 			tptr = get_lun_statep(isp, 0, 0);
2047 			if (tptr == NULL) {
2048 				tptr = get_lun_statep(isp, 0, CAM_LUN_WILDCARD);
2049 				if (tptr == NULL) {
2050 					isp_prt(isp, ISP_LOGWARN, "%s: [RX_ID 0x%x] D_ID %x not found on any channel and no tptr- dropping", __func__, aep->at_rxid, did);
2051 					isp_endcmd(isp, aep, NIL_HANDLE, ISP_NOCHAN, ECMD_TERMINATE, 0);
2052 					return;
2053 				}
2054 			}
2055 			isp_prt(isp, ISP_LOGWARN, "%s: [RX_ID 0x%x] D_ID %x not found on any channel- deferring", __func__, aep->at_rxid, did);
2056 			goto noresrc;
2057 		}
2058 		isp_prt(isp, ISP_LOGTDEBUG0, "%s: [RX_ID 0x%x] D_ID 0x%06x found on Chan %d for S_ID 0x%06x", __func__, aep->at_rxid, did, chan, sid);
2059 	} else {
2060 		chan = 0;
2061 	}
2062 
2063 	/*
2064 	 * Find the PDB entry for this initiator
2065 	 */
2066 	if (isp_find_pdb_by_portid(isp, chan, sid, &lp) == 0) {
2067 		/*
2068 		 * If we're not in the port database terminate the exchange.
2069 		 */
2070 		isp_prt(isp, ISP_LOGTINFO, "%s: [RX_ID 0x%x] D_ID 0x%06x found on Chan %d for S_ID 0x%06x wasn't in PDB already",
2071 		    __func__, aep->at_rxid, did, chan, sid);
2072 		isp_dump_portdb(isp, chan);
2073 		isp_endcmd(isp, aep, NIL_HANDLE, chan, ECMD_TERMINATE, 0);
2074 		return;
2075 	}
2076 	nphdl = lp->handle;
2077 
2078 	/*
2079 	 * Get the tstate pointer
2080 	 */
2081 	tptr = get_lun_statep(isp, chan, lun);
2082 	if (tptr == NULL) {
2083 		tptr = get_lun_statep(isp, chan, CAM_LUN_WILDCARD);
2084 		if (tptr == NULL) {
2085 			isp_prt(isp, ISP_LOGWARN,
2086 			    "%s: [0x%x] no state pointer for lun %jx or wildcard",
2087 			    __func__, aep->at_rxid, (uintmax_t)lun);
2088 			if (lun == 0) {
2089 				isp_endcmd(isp, aep, nphdl, SCSI_STATUS_BUSY, 0);
2090 			} else {
2091 				isp_endcmd(isp, aep, nphdl, chan, SCSI_STATUS_CHECK_COND | ECMD_SVALID | (0x5 << 12) | (0x25 << 16), 0);
2092 			}
2093 			return;
2094 		}
2095 	}
2096 
2097 	/*
2098 	 * Start any commands pending resources first.
2099 	 */
2100 	if (tptr->restart_queue) {
2101 		inot_private_data_t *restart_queue = tptr->restart_queue;
2102 		tptr->restart_queue = NULL;
2103 		while (restart_queue) {
2104 			ntp = restart_queue;
2105 			restart_queue = ntp->rd.nt.nt_hba;
2106 			isp_prt(isp, ISP_LOGTDEBUG0, "%s: restarting resrc deprived %x", __func__, ((at7_entry_t *)ntp->rd.data)->at_rxid);
2107 			isp_handle_platform_atio7(isp, (at7_entry_t *) ntp->rd.data);
2108 			isp_put_ntpd(isp, tptr, ntp);
2109 			/*
2110 			 * If a recursion caused the restart queue to start to fill again,
2111 			 * stop and splice the new list on top of the old list and restore
2112 			 * it and go to noresrc.
2113 			 */
2114 			if (tptr->restart_queue) {
2115 				isp_prt(isp, ISP_LOGTDEBUG0, "%s: restart queue refilling", __func__);
2116 				if (restart_queue) {
2117 					ntp = tptr->restart_queue;
2118 					tptr->restart_queue = restart_queue;
2119 					while (restart_queue->rd.nt.nt_hba) {
2120 						restart_queue = restart_queue->rd.nt.nt_hba;
2121 					}
2122 					restart_queue->rd.nt.nt_hba = ntp;
2123 				}
2124 				goto noresrc;
2125 			}
2126 		}
2127 	}
2128 
2129 	/*
2130 	 * If the f/w is out of resources, just send a BUSY status back.
2131 	 */
2132 	if (aep->at_rxid == AT7_NORESRC_RXID) {
2133 		rls_lun_statep(isp, tptr);
2134 		isp_endcmd(isp, aep, nphdl, chan, SCSI_BUSY, 0);
2135 		return;
2136 	}
2137 
2138 	/*
2139 	 * If we're out of resources, just send a BUSY status back.
2140 	 */
2141 	atiop = (struct ccb_accept_tio *) SLIST_FIRST(&tptr->atios);
2142 	if (atiop == NULL) {
2143 		isp_prt(isp, ISP_LOGTDEBUG0, "[0x%x] out of atios", aep->at_rxid);
2144 		goto noresrc;
2145 	}
2146 
2147 	oatp = isp_find_atpd(isp, tptr, aep->at_rxid);
2148 	if (oatp) {
2149 		isp_prt(isp, ISP_LOGTDEBUG0, "[0x%x] tag wraparound in isp_handle_platforms_atio7 (N-Port Handle 0x%04x S_ID 0x%04x OX_ID 0x%04x) oatp state %d",
2150 		    aep->at_rxid, nphdl, sid, aep->at_hdr.ox_id, oatp->state);
2151 		/*
2152 		 * It's not a "no resource" condition- but we can treat it like one
2153 		 */
2154 		goto noresrc;
2155 	}
2156 	atp = isp_get_atpd(isp, tptr, aep->at_rxid);
2157 	if (atp == NULL) {
2158 		isp_prt(isp, ISP_LOGTDEBUG0, "[0x%x] out of atps", aep->at_rxid);
2159 		goto noresrc;
2160 	}
2161 	atp->word3 = lp->prli_word3;
2162 	atp->state = ATPD_STATE_ATIO;
2163 	SLIST_REMOVE_HEAD(&tptr->atios, sim_links.sle);
2164 	tptr->atio_count--;
2165 	ISP_PATH_PRT(isp, ISP_LOGTDEBUG2, atiop->ccb_h.path, "Take FREE ATIO count now %d\n", tptr->atio_count);
2166 	atiop->init_id = FC_PORTDB_TGT(isp, chan, lp);
2167 	atiop->ccb_h.target_id = FCPARAM(isp, chan)->isp_loopid;
2168 	atiop->ccb_h.target_lun = lun;
2169 	atiop->sense_len = 0;
2170 	cdbxlen = aep->at_cmnd.fcp_cmnd_alen_datadir >> FCP_CMND_ADDTL_CDBLEN_SHIFT;
2171 	if (cdbxlen) {
2172 		isp_prt(isp, ISP_LOGWARN, "additional CDBLEN ignored");
2173 	}
2174 	cdbxlen = sizeof (aep->at_cmnd.cdb_dl.sf.fcp_cmnd_cdb);
2175 	ISP_MEMCPY(atiop->cdb_io.cdb_bytes, aep->at_cmnd.cdb_dl.sf.fcp_cmnd_cdb, cdbxlen);
2176 	atiop->cdb_len = cdbxlen;
2177 	atiop->ccb_h.status = CAM_CDB_RECVD;
2178 	atiop->tag_id = atp->tag;
2179 	switch (aep->at_cmnd.fcp_cmnd_task_attribute & FCP_CMND_TASK_ATTR_MASK) {
2180 	case FCP_CMND_TASK_ATTR_SIMPLE:
2181 		atiop->ccb_h.flags |= CAM_TAG_ACTION_VALID;
2182 		atiop->tag_action = MSG_SIMPLE_Q_TAG;
2183 		break;
2184 	case FCP_CMND_TASK_ATTR_HEAD:
2185 		atiop->ccb_h.flags |= CAM_TAG_ACTION_VALID;
2186 		atiop->tag_action = MSG_HEAD_OF_Q_TAG;
2187 		break;
2188 	case FCP_CMND_TASK_ATTR_ORDERED:
2189 		atiop->ccb_h.flags |= CAM_TAG_ACTION_VALID;
2190 		atiop->tag_action = MSG_ORDERED_Q_TAG;
2191 		break;
2192 	default:
2193 		/* FALLTHROUGH */
2194 	case FCP_CMND_TASK_ATTR_ACA:
2195 	case FCP_CMND_TASK_ATTR_UNTAGGED:
2196 		atiop->tag_action = 0;
2197 		break;
2198 	}
2199 	atp->orig_datalen = aep->at_cmnd.cdb_dl.sf.fcp_cmnd_dl;
2200 	atp->bytes_xfered = 0;
2201 	atp->lun = lun;
2202 	atp->nphdl = nphdl;
2203 	atp->portid = sid;
2204 	atp->oxid = aep->at_hdr.ox_id;
2205 	atp->rxid = aep->at_hdr.rx_id;
2206 	atp->cdb0 = atiop->cdb_io.cdb_bytes[0];
2207 	atp->tattr = aep->at_cmnd.fcp_cmnd_task_attribute & FCP_CMND_TASK_ATTR_MASK;
2208 	atp->state = ATPD_STATE_CAM;
2209 	isp_prt(isp, ISP_LOGTDEBUG0, "ATIO7[0x%x] CDB=0x%x lun %jx datalen %u",
2210 	    aep->at_rxid, atp->cdb0, (uintmax_t)lun, atp->orig_datalen);
2211 	xpt_done((union ccb *)atiop);
2212 	rls_lun_statep(isp, tptr);
2213 	return;
2214 noresrc:
2215 	if (atp) {
2216 		isp_put_atpd(isp, tptr, atp);
2217 	}
2218 	ntp = isp_get_ntpd(isp, tptr);
2219 	if (ntp == NULL) {
2220 		rls_lun_statep(isp, tptr);
2221 		isp_endcmd(isp, aep, nphdl, chan, SCSI_STATUS_BUSY, 0);
2222 		return;
2223 	}
2224 	memcpy(ntp->rd.data, aep, QENTRY_LEN);
2225 	ntp->rd.nt.nt_hba = tptr->restart_queue;
2226 	tptr->restart_queue = ntp;
2227 	rls_lun_statep(isp, tptr);
2228 }
2229 
2230 
2231 /*
2232  * Handle starting an SRR (sequence retransmit request)
2233  * We get here when we've gotten the immediate notify
2234  * and the return of all outstanding CTIOs for this
2235  * transaction.
2236  */
2237 static void
2238 isp_handle_srr_start(ispsoftc_t *isp, tstate_t *tptr, atio_private_data_t *atp)
2239 {
2240 	in_fcentry_24xx_t *inot;
2241 	uint32_t srr_off, ccb_off, ccb_len, ccb_end;
2242 	union ccb *ccb;
2243 
2244 	inot = (in_fcentry_24xx_t *)atp->srr;
2245 	srr_off = inot->in_srr_reloff_lo | (inot->in_srr_reloff_hi << 16);
2246 	ccb = atp->srr_ccb;
2247 	atp->srr_ccb = NULL;
2248 	atp->nsrr++;
2249 	if (ccb == NULL) {
2250 		isp_prt(isp, ISP_LOGWARN, "SRR[0x%x] null ccb", atp->tag);
2251 		goto fail;
2252 	}
2253 
2254 	ccb_off = ccb->ccb_h.spriv_field0;
2255 	ccb_len = ccb->csio.dxfer_len;
2256         ccb_end = (ccb_off == ~0)? ~0 : ccb_off + ccb_len;
2257 
2258 	switch (inot->in_srr_iu) {
2259 	case R_CTL_INFO_SOLICITED_DATA:
2260 		/*
2261 		 * We have to restart a FCP_DATA data out transaction
2262 		 */
2263 		atp->sendst = 0;
2264 		atp->bytes_xfered = srr_off;
2265 		if (ccb_len == 0) {
2266 			isp_prt(isp, ISP_LOGWARN, "SRR[0x%x] SRR offset 0x%x but current CCB doesn't transfer data", atp->tag, srr_off);
2267 			goto mdp;
2268 		}
2269  		if (srr_off < ccb_off || ccb_off > srr_off + ccb_len) {
2270 			isp_prt(isp, ISP_LOGWARN, "SRR[0x%x] SRR offset 0x%x not covered by current CCB data range [0x%x..0x%x]", atp->tag, srr_off, ccb_off, ccb_end);
2271 			goto mdp;
2272 		}
2273 		isp_prt(isp, ISP_LOGWARN, "SRR[0x%x] SRR offset 0x%x covered by current CCB data range [0x%x..0x%x]", atp->tag, srr_off, ccb_off, ccb_end);
2274 		break;
2275 	case R_CTL_INFO_COMMAND_STATUS:
2276 		isp_prt(isp, ISP_LOGTINFO, "SRR[0x%x] Got an FCP RSP SRR- resending status", atp->tag);
2277 		atp->sendst = 1;
2278 		/*
2279 		 * We have to restart a FCP_RSP IU transaction
2280 		 */
2281 		break;
2282 	case R_CTL_INFO_DATA_DESCRIPTOR:
2283 		/*
2284 		 * We have to restart an FCP DATA in transaction
2285 		 */
2286 		isp_prt(isp, ISP_LOGWARN, "Got an FCP DATA IN SRR- dropping");
2287 		goto fail;
2288 
2289 	default:
2290 		isp_prt(isp, ISP_LOGWARN, "Got an unknown information (%x) SRR- dropping", inot->in_srr_iu);
2291 		goto fail;
2292 	}
2293 
2294 	/*
2295 	 * We can't do anything until this is acked, so we might as well start it now.
2296 	 * We aren't going to do the usual asynchronous ack issue because we need
2297 	 * to make sure this gets on the wire first.
2298 	 */
2299 	if (isp_notify_ack(isp, inot)) {
2300 		isp_prt(isp, ISP_LOGWARN, "could not push positive ack for SRR- you lose");
2301 		goto fail;
2302 	}
2303 	isp_target_start_ctio(isp, ccb, FROM_SRR);
2304 	return;
2305 fail:
2306 	inot->in_reserved = 1;
2307 	isp_async(isp, ISPASYNC_TARGET_NOTIFY_ACK, inot);
2308 	ccb->ccb_h.status &= ~CAM_STATUS_MASK;
2309 	ccb->ccb_h.status |= CAM_REQ_CMP_ERR;
2310 	isp_complete_ctio(ccb);
2311 	return;
2312 mdp:
2313 	if (isp_notify_ack(isp, inot)) {
2314 		isp_prt(isp, ISP_LOGWARN, "could not push positive ack for SRR- you lose");
2315 		goto fail;
2316 	}
2317 	ccb->ccb_h.status &= ~CAM_STATUS_MASK;
2318 	ccb->ccb_h.status = CAM_MESSAGE_RECV;
2319 	/*
2320 	 * This is not a strict interpretation of MDP, but it's close
2321 	 */
2322 	ccb->csio.msg_ptr = &ccb->csio.sense_data.sense_buf[SSD_FULL_SIZE - 16];
2323 	ccb->csio.msg_len = 7;
2324 	ccb->csio.msg_ptr[0] = MSG_EXTENDED;
2325 	ccb->csio.msg_ptr[1] = 5;
2326 	ccb->csio.msg_ptr[2] = 0;	/* modify data pointer */
2327 	ccb->csio.msg_ptr[3] = srr_off >> 24;
2328 	ccb->csio.msg_ptr[4] = srr_off >> 16;
2329 	ccb->csio.msg_ptr[5] = srr_off >> 8;
2330 	ccb->csio.msg_ptr[6] = srr_off;
2331 	isp_complete_ctio(ccb);
2332 }
2333 
2334 
2335 static void
2336 isp_handle_srr_notify(ispsoftc_t *isp, void *inot_raw)
2337 {
2338 	tstate_t *tptr;
2339 	in_fcentry_24xx_t *inot = inot_raw;
2340 	atio_private_data_t *atp;
2341 	uint32_t tag = inot->in_rxid;
2342 	uint32_t bus = inot->in_vpidx;
2343 
2344 	if (!IS_24XX(isp)) {
2345 		isp_async(isp, ISPASYNC_TARGET_NOTIFY_ACK, inot_raw);
2346 		return;
2347 	}
2348 
2349 	tptr = get_lun_statep_from_tag(isp, bus, tag);
2350 	if (tptr == NULL) {
2351 		isp_prt(isp, ISP_LOGERR, "%s: cannot find tptr for tag %x in SRR Notify", __func__, tag);
2352 		isp_async(isp, ISPASYNC_TARGET_NOTIFY_ACK, inot);
2353 		return;
2354 	}
2355 	atp = isp_find_atpd(isp, tptr, tag);
2356 	if (atp == NULL) {
2357 		rls_lun_statep(isp, tptr);
2358 		isp_prt(isp, ISP_LOGERR, "%s: cannot find adjunct for %x in SRR Notify", __func__, tag);
2359 		isp_async(isp, ISPASYNC_TARGET_NOTIFY_ACK, inot);
2360 		return;
2361 	}
2362 	atp->srr_notify_rcvd = 1;
2363 	memcpy(atp->srr, inot, sizeof (atp->srr));
2364 	isp_prt(isp, ISP_LOGTINFO /* ISP_LOGTDEBUG0 */, "SRR[0x%x] inot->in_rxid flags 0x%x srr_iu=%x reloff 0x%x", inot->in_rxid, inot->in_flags, inot->in_srr_iu,
2365 	    inot->in_srr_reloff_lo | (inot->in_srr_reloff_hi << 16));
2366 	if (atp->srr_ccb)
2367 		isp_handle_srr_start(isp, tptr, atp);
2368 	rls_lun_statep(isp, tptr);
2369 }
2370 
2371 static void
2372 isp_handle_platform_ctio(ispsoftc_t *isp, void *arg)
2373 {
2374 	union ccb *ccb;
2375 	int sentstatus = 0, ok = 0, notify_cam = 0, resid = 0, failure = 0;
2376 	tstate_t *tptr = NULL;
2377 	atio_private_data_t *atp = NULL;
2378 	int bus;
2379 	uint32_t handle, moved_data = 0, data_requested;
2380 
2381 	handle = ((ct2_entry_t *)arg)->ct_syshandle;
2382 	ccb = isp_find_xs_tgt(isp, handle);
2383 	if (ccb == NULL) {
2384 		isp_print_bytes(isp, "null ccb in isp_handle_platform_ctio", QENTRY_LEN, arg);
2385 		return;
2386 	}
2387 	isp_destroy_tgt_handle(isp, handle);
2388 	data_requested = PISP_PCMD(ccb)->datalen;
2389 	isp_free_pcmd(isp, ccb);
2390 	if (isp->isp_nactive) {
2391 		isp->isp_nactive--;
2392 	}
2393 
2394 	bus = XS_CHANNEL(ccb);
2395 	tptr = get_lun_statep(isp, bus, XS_LUN(ccb));
2396 	if (tptr == NULL) {
2397 		tptr = get_lun_statep(isp, bus, CAM_LUN_WILDCARD);
2398 	}
2399 	if (tptr == NULL) {
2400 		isp_prt(isp, ISP_LOGERR, "%s: cannot find tptr for tag %x after I/O", __func__, ccb->csio.tag_id);
2401 		return;
2402 	}
2403 
2404 	if (IS_24XX(isp)) {
2405 		atp = isp_find_atpd(isp, tptr, ((ct7_entry_t *)arg)->ct_rxid);
2406 	} else {
2407 		atp = isp_find_atpd(isp, tptr, ((ct2_entry_t *)arg)->ct_rxid);
2408 	}
2409 	if (atp == NULL) {
2410 		/*
2411 		 * XXX: isp_clear_commands() generates fake CTIO with zero
2412 		 * ct_rxid value, filling only ct_syshandle.  Workaround
2413 		 * that using tag_id from the CCB, pointed by ct_syshandle.
2414 		 */
2415 		atp = isp_find_atpd(isp, tptr, ccb->csio.tag_id);
2416 	}
2417 	if (atp == NULL) {
2418 		rls_lun_statep(isp, tptr);
2419 		isp_prt(isp, ISP_LOGERR, "%s: cannot find adjunct for %x after I/O", __func__, ccb->csio.tag_id);
2420 		return;
2421 	}
2422 	KASSERT((atp->ctcnt > 0), ("ctio count not greater than zero"));
2423 	atp->bytes_in_transit -= data_requested;
2424 	atp->ctcnt -= 1;
2425 	ccb->ccb_h.status &= ~CAM_STATUS_MASK;
2426 
2427 	if (IS_24XX(isp)) {
2428 		ct7_entry_t *ct = arg;
2429 
2430 		if (ct->ct_nphdl == CT7_SRR) {
2431 			atp->srr_ccb = ccb;
2432 			if (atp->srr_notify_rcvd)
2433 				isp_handle_srr_start(isp, tptr, atp);
2434 			rls_lun_statep(isp, tptr);
2435 			return;
2436 		}
2437 		if (ct->ct_nphdl == CT_HBA_RESET) {
2438 			failure = CAM_UNREC_HBA_ERROR;
2439 		} else {
2440 			sentstatus = ct->ct_flags & CT7_SENDSTATUS;
2441 			ok = (ct->ct_nphdl == CT7_OK);
2442 			notify_cam = (ct->ct_header.rqs_seqno & ATPD_SEQ_NOTIFY_CAM) != 0;
2443 			if ((ct->ct_flags & CT7_DATAMASK) != CT7_NO_DATA) {
2444 				resid = ct->ct_resid;
2445 				moved_data = data_requested - resid;
2446 			}
2447 		}
2448 		isp_prt(isp, ok? ISP_LOGTDEBUG0 : ISP_LOGWARN, "%s: CTIO7[%x] seq %u nc %d sts 0x%x flg 0x%x sns %d resid %d %s", __func__, ct->ct_rxid, ATPD_GET_SEQNO(ct),
2449 		   notify_cam, ct->ct_nphdl, ct->ct_flags, (ccb->ccb_h.status & CAM_SENT_SENSE) != 0, resid, sentstatus? "FIN" : "MID");
2450 	} else {
2451 		ct2_entry_t *ct = arg;
2452 		if (ct->ct_status == CT_SRR) {
2453 			atp->srr_ccb = ccb;
2454 			if (atp->srr_notify_rcvd)
2455 				isp_handle_srr_start(isp, tptr, atp);
2456 			rls_lun_statep(isp, tptr);
2457 			isp_target_putback_atio(ccb);
2458 			return;
2459 		}
2460 		if (ct->ct_status == CT_HBA_RESET) {
2461 			failure = CAM_UNREC_HBA_ERROR;
2462 		} else {
2463 			sentstatus = ct->ct_flags & CT2_SENDSTATUS;
2464 			ok = (ct->ct_status & ~QLTM_SVALID) == CT_OK;
2465 			notify_cam = (ct->ct_header.rqs_seqno & ATPD_SEQ_NOTIFY_CAM) != 0;
2466 			if ((ct->ct_flags & CT2_DATAMASK) != CT2_NO_DATA) {
2467 				resid = ct->ct_resid;
2468 				moved_data = data_requested - resid;
2469 			}
2470 		}
2471 		isp_prt(isp, ok? ISP_LOGTDEBUG0 : ISP_LOGWARN, "%s: CTIO2[%x] seq %u nc %d sts 0x%x flg 0x%x sns %d resid %d %s", __func__, ct->ct_rxid, ATPD_GET_SEQNO(ct),
2472 		    notify_cam, ct->ct_status, ct->ct_flags, (ccb->ccb_h.status & CAM_SENT_SENSE) != 0, resid, sentstatus? "FIN" : "MID");
2473 	}
2474 	if (ok) {
2475 		if (moved_data) {
2476 			atp->bytes_xfered += moved_data;
2477 			ccb->csio.resid = atp->orig_datalen - atp->bytes_xfered - atp->bytes_in_transit;
2478 		}
2479 		if (sentstatus && (ccb->ccb_h.flags & CAM_SEND_SENSE)) {
2480 			ccb->ccb_h.status |= CAM_SENT_SENSE;
2481 		}
2482 		ccb->ccb_h.status |= CAM_REQ_CMP;
2483 	} else {
2484 		notify_cam = 1;
2485 		if (failure == CAM_UNREC_HBA_ERROR)
2486 			ccb->ccb_h.status |= CAM_UNREC_HBA_ERROR;
2487 		else
2488 			ccb->ccb_h.status |= CAM_REQ_CMP_ERR;
2489 	}
2490 	atp->state = ATPD_STATE_PDON;
2491 	rls_lun_statep(isp, tptr);
2492 
2493 	/*
2494 	 * We never *not* notify CAM when there has been any error (ok == 0),
2495 	 * so we never need to do an ATIO putback if we're not notifying CAM.
2496 	 */
2497 	isp_prt(isp, ISP_LOGTDEBUG0, "%s CTIO[0x%x] done (ok=%d nc=%d nowsendstatus=%d ccb ss=%d)",
2498 	    (sentstatus)? "  FINAL " : "MIDTERM ", atp->tag, ok, notify_cam, atp->sendst, (ccb->ccb_h.flags & CAM_SEND_STATUS) != 0);
2499 	if (notify_cam == 0) {
2500 		if (atp->sendst) {
2501 			isp_target_start_ctio(isp, ccb, FROM_CTIO_DONE);
2502 		}
2503 		return;
2504 	}
2505 
2506 	/*
2507 	 * We're telling CAM we're done with this CTIO transaction.
2508 	 *
2509 	 * 24XX cards never need an ATIO put back.
2510 	 *
2511 	 * Other cards need one put back only on error.
2512 	 * In the latter case, a timeout will re-fire
2513 	 * and try again in case we didn't have
2514 	 * queue resources to do so at first. In any case,
2515 	 * once the putback is done we do the completion
2516 	 * call.
2517 	 */
2518 	if (ok || IS_24XX(isp)) {
2519 		isp_complete_ctio(ccb);
2520 	} else {
2521 		isp_target_putback_atio(ccb);
2522 	}
2523 }
2524 
2525 static void
2526 isp_handle_platform_notify_fc(ispsoftc_t *isp, in_fcentry_t *inp)
2527 {
2528 	int needack = 1;
2529 	switch (inp->in_status) {
2530 	case IN_PORT_LOGOUT:
2531 		/*
2532 		 * XXX: Need to delete this initiator's WWN from the database
2533 		 * XXX: Need to send this LOGOUT upstream
2534 		 */
2535 		isp_prt(isp, ISP_LOGWARN, "port logout of S_ID 0x%x", inp->in_iid);
2536 		break;
2537 	case IN_PORT_CHANGED:
2538 		isp_prt(isp, ISP_LOGWARN, "port changed for S_ID 0x%x", inp->in_iid);
2539 		break;
2540 	case IN_GLOBAL_LOGO:
2541 		isp_del_all_wwn_entries(isp, 0);
2542 		isp_prt(isp, ISP_LOGINFO, "all ports logged out");
2543 		break;
2544 	case IN_ABORT_TASK:
2545 	{
2546 		tstate_t *tptr;
2547 		uint16_t nphdl, lun;
2548 		uint32_t sid;
2549 		uint64_t wwn;
2550 		atio_private_data_t *atp;
2551 		fcportdb_t *lp;
2552 		struct ccb_immediate_notify *inot = NULL;
2553 
2554 		if (ISP_CAP_SCCFW(isp)) {
2555 			lun = inp->in_scclun;
2556 #if __FreeBSD_version < 1000700
2557 			lun &= 0x3fff;
2558 #endif
2559 		} else {
2560 			lun = inp->in_lun;
2561 		}
2562 		if (ISP_CAP_2KLOGIN(isp)) {
2563 			nphdl = ((in_fcentry_e_t *)inp)->in_iid;
2564 		} else {
2565 			nphdl = inp->in_iid;
2566 		}
2567 		if (isp_find_pdb_by_handle(isp, 0, nphdl, &lp)) {
2568 			wwn = lp->port_wwn;
2569 			sid = lp->portid;
2570 		} else {
2571 			wwn = INI_ANY;
2572 			sid = PORT_ANY;
2573 		}
2574 		tptr = get_lun_statep(isp, 0, lun);
2575 		if (tptr == NULL) {
2576 			tptr = get_lun_statep(isp, 0, CAM_LUN_WILDCARD);
2577 			if (tptr == NULL) {
2578 				isp_prt(isp, ISP_LOGWARN, "ABORT TASK for lun %x, but no tstate", lun);
2579 				return;
2580 			}
2581 		}
2582 		atp = isp_find_atpd(isp, tptr, inp->in_seqid);
2583 
2584 		if (atp) {
2585 			inot = (struct ccb_immediate_notify *) SLIST_FIRST(&tptr->inots);
2586 			isp_prt(isp, ISP_LOGTDEBUG0, "ABORT TASK RX_ID %x WWN 0x%016llx state %d", inp->in_seqid, (unsigned long long) wwn, atp->state);
2587 			if (inot) {
2588 				tptr->inot_count--;
2589 				SLIST_REMOVE_HEAD(&tptr->inots, sim_links.sle);
2590 				ISP_PATH_PRT(isp, ISP_LOGTDEBUG2, inot->ccb_h.path, "%s: Take FREE INOT count now %d\n", __func__, tptr->inot_count);
2591 			} else {
2592 				ISP_PATH_PRT(isp, ISP_LOGWARN, tptr->owner, "out of INOT structures\n");
2593 			}
2594 		} else {
2595 			ISP_PATH_PRT(isp, ISP_LOGWARN, tptr->owner, "abort task RX_ID %x from wwn 0x%016llx, state unknown\n", inp->in_seqid, wwn);
2596 		}
2597 		if (inot) {
2598 			isp_notify_t tmp, *nt = &tmp;
2599 			ISP_MEMZERO(nt, sizeof (isp_notify_t));
2600     			nt->nt_hba = isp;
2601 			nt->nt_tgt = FCPARAM(isp, 0)->isp_wwpn;
2602 			nt->nt_wwn = wwn;
2603 			nt->nt_nphdl = nphdl;
2604 			nt->nt_sid = sid;
2605 			nt->nt_did = PORT_ANY;
2606     			nt->nt_lun = lun;
2607             		nt->nt_need_ack = 1;
2608     			nt->nt_channel = 0;
2609     			nt->nt_ncode = NT_ABORT_TASK;
2610     			nt->nt_lreserved = inot;
2611 			isp_handle_platform_target_tmf(isp, nt);
2612 			needack = 0;
2613 		}
2614 		rls_lun_statep(isp, tptr);
2615 		break;
2616 	}
2617 	default:
2618 		break;
2619 	}
2620 	if (needack) {
2621 		isp_async(isp, ISPASYNC_TARGET_NOTIFY_ACK, inp);
2622 	}
2623 }
2624 
2625 static void
2626 isp_handle_platform_notify_24xx(ispsoftc_t *isp, in_fcentry_24xx_t *inot)
2627 {
2628 	uint16_t nphdl;
2629 	uint16_t prli_options = 0;
2630 	uint32_t portid;
2631 	fcportdb_t *lp;
2632 	char *msg = NULL;
2633 	uint8_t *ptr = (uint8_t *)inot;
2634 	uint64_t wwpn = INI_NONE, wwnn = INI_NONE;
2635 
2636 	nphdl = inot->in_nphdl;
2637 	if (nphdl != NIL_HANDLE) {
2638 		portid = inot->in_portid_hi << 16 | inot->in_portid_lo;
2639 	} else {
2640 		portid = PORT_ANY;
2641 	}
2642 
2643 	switch (inot->in_status) {
2644 	case IN24XX_ELS_RCVD:
2645 	{
2646 		char buf[16];
2647 		int chan = ISP_GET_VPIDX(isp, inot->in_vpidx);
2648 
2649 		/*
2650 		 * Note that we're just getting notification that an ELS was received
2651 		 * (possibly with some associated information sent upstream). This is
2652 		 * *not* the same as being given the ELS frame to accept or reject.
2653 		 */
2654 		switch (inot->in_status_subcode) {
2655 		case LOGO:
2656 			msg = "LOGO";
2657 			wwpn = be64dec(&ptr[IN24XX_PLOGI_WWPN_OFF]);
2658 			isp_del_wwn_entry(isp, chan, wwpn, nphdl, portid);
2659 			break;
2660 		case PRLO:
2661 			msg = "PRLO";
2662 			break;
2663 		case PLOGI:
2664 			msg = "PLOGI";
2665 			wwnn = be64dec(&ptr[IN24XX_PLOGI_WWNN_OFF]);
2666 			wwpn = be64dec(&ptr[IN24XX_PLOGI_WWPN_OFF]);
2667 			isp_add_wwn_entry(isp, chan, wwpn, wwnn,
2668 			    nphdl, portid, prli_options);
2669 			break;
2670 		case PRLI:
2671 			msg = "PRLI";
2672 			prli_options = inot->in_prli_options;
2673 			if (inot->in_flags & IN24XX_FLAG_PN_NN_VALID)
2674 				wwnn = be64dec(&ptr[IN24XX_PRLI_WWNN_OFF]);
2675 			wwpn = be64dec(&ptr[IN24XX_PRLI_WWPN_OFF]);
2676 			isp_add_wwn_entry(isp, chan, wwpn, wwnn,
2677 			    nphdl, portid, prli_options);
2678 			break;
2679 		case PDISC:
2680 			msg = "PDISC";
2681 			break;
2682 		case ADISC:
2683 			msg = "ADISC";
2684 			break;
2685 		default:
2686 			ISP_SNPRINTF(buf, sizeof (buf), "ELS 0x%x", inot->in_status_subcode);
2687 			msg = buf;
2688 			break;
2689 		}
2690 		if (inot->in_flags & IN24XX_FLAG_PUREX_IOCB) {
2691 			isp_prt(isp, ISP_LOGERR, "%s Chan %d ELS N-port handle %x PortID 0x%06x marked as needing a PUREX response", msg, chan, nphdl, portid);
2692 			break;
2693 		}
2694 		isp_prt(isp, ISP_LOGTDEBUG0, "%s Chan %d ELS N-port handle %x PortID 0x%06x RX_ID 0x%x OX_ID 0x%x", msg, chan, nphdl, portid,
2695 		    inot->in_rxid, inot->in_oxid);
2696 		isp_async(isp, ISPASYNC_TARGET_NOTIFY_ACK, inot);
2697 		break;
2698 	}
2699 
2700 	case IN24XX_PORT_LOGOUT:
2701 		msg = "PORT LOGOUT";
2702 		if (isp_find_pdb_by_handle(isp, ISP_GET_VPIDX(isp, inot->in_vpidx), nphdl, &lp)) {
2703 			isp_del_wwn_entry(isp, ISP_GET_VPIDX(isp, inot->in_vpidx), lp->port_wwn, nphdl, lp->portid);
2704 		}
2705 		/* FALLTHROUGH */
2706 	case IN24XX_PORT_CHANGED:
2707 		if (msg == NULL)
2708 			msg = "PORT CHANGED";
2709 		/* FALLTHROUGH */
2710 	case IN24XX_LIP_RESET:
2711 		if (msg == NULL)
2712 			msg = "LIP RESET";
2713 		isp_prt(isp, ISP_LOGINFO, "Chan %d %s (sub-status 0x%x) for N-port handle 0x%x", ISP_GET_VPIDX(isp, inot->in_vpidx), msg, inot->in_status_subcode, nphdl);
2714 
2715 		/*
2716 		 * All subcodes here are irrelevant. What is relevant
2717 		 * is that we need to terminate all active commands from
2718 		 * this initiator (known by N-port handle).
2719 		 */
2720 		/* XXX IMPLEMENT XXX */
2721 		isp_async(isp, ISPASYNC_TARGET_NOTIFY_ACK, inot);
2722 		break;
2723 
2724 	case IN24XX_SRR_RCVD:
2725 #ifdef	ISP_TARGET_MODE
2726 		isp_handle_srr_notify(isp, inot);
2727 		break;
2728 #else
2729 		if (msg == NULL)
2730 			msg = "SRR RCVD";
2731 		/* FALLTHROUGH */
2732 #endif
2733 	case IN24XX_LINK_RESET:
2734 		if (msg == NULL)
2735 			msg = "LINK RESET";
2736 	case IN24XX_LINK_FAILED:
2737 		if (msg == NULL)
2738 			msg = "LINK FAILED";
2739 	default:
2740 		isp_prt(isp, ISP_LOGWARN, "Chan %d %s", ISP_GET_VPIDX(isp, inot->in_vpidx), msg);
2741 		isp_async(isp, ISPASYNC_TARGET_NOTIFY_ACK, inot);
2742 		break;
2743 	}
2744 }
2745 
2746 static int
2747 isp_handle_platform_target_notify_ack(ispsoftc_t *isp, isp_notify_t *mp)
2748 {
2749 
2750 	if (isp->isp_state != ISP_RUNSTATE) {
2751 		isp_prt(isp, ISP_LOGTINFO, "Notify Code 0x%x (qevalid=%d) acked- h/w not ready (dropping)", mp->nt_ncode, mp->nt_lreserved != NULL);
2752 		return (0);
2753 	}
2754 
2755 	/*
2756 	 * This case is for a Task Management Function, which shows up as an ATIO7 entry.
2757 	 */
2758 	if (IS_24XX(isp) && mp->nt_lreserved && ((isphdr_t *)mp->nt_lreserved)->rqs_entry_type == RQSTYPE_ATIO) {
2759 		ct7_entry_t local, *cto = &local;
2760 		at7_entry_t *aep = (at7_entry_t *)mp->nt_lreserved;
2761 		fcportdb_t *lp;
2762 		uint32_t sid;
2763 		uint16_t nphdl;
2764 
2765 		sid = (aep->at_hdr.s_id[0] << 16) | (aep->at_hdr.s_id[1] << 8) | aep->at_hdr.s_id[2];
2766 		if (isp_find_pdb_by_portid(isp, mp->nt_channel, sid, &lp)) {
2767 			nphdl = lp->handle;
2768 		} else {
2769 			nphdl = NIL_HANDLE;
2770 		}
2771 		ISP_MEMZERO(&local, sizeof (local));
2772 		cto->ct_header.rqs_entry_type = RQSTYPE_CTIO7;
2773 		cto->ct_header.rqs_entry_count = 1;
2774 		cto->ct_nphdl = nphdl;
2775 		cto->ct_rxid = aep->at_rxid;
2776 		cto->ct_vpidx = mp->nt_channel;
2777 		cto->ct_iid_lo = sid;
2778 		cto->ct_iid_hi = sid >> 16;
2779 		cto->ct_oxid = aep->at_hdr.ox_id;
2780 		cto->ct_flags = CT7_SENDSTATUS|CT7_NOACK|CT7_NO_DATA|CT7_FLAG_MODE1;
2781 		cto->ct_flags |= (aep->at_ta_len >> 12) << CT7_TASK_ATTR_SHIFT;
2782 		return (isp_target_put_entry(isp, &local));
2783 	}
2784 
2785 	/*
2786 	 * This case is for a responding to an ABTS frame
2787 	 */
2788 	if (IS_24XX(isp) && mp->nt_lreserved && ((isphdr_t *)mp->nt_lreserved)->rqs_entry_type == RQSTYPE_ABTS_RCVD) {
2789 
2790 		/*
2791 		 * Overload nt_need_ack here to mark whether we've terminated the associated command.
2792 		 */
2793 		if (mp->nt_need_ack) {
2794 			uint8_t storage[QENTRY_LEN];
2795 			ct7_entry_t *cto = (ct7_entry_t *) storage;
2796 			abts_t *abts = (abts_t *)mp->nt_lreserved;
2797 
2798 			ISP_MEMZERO(cto, sizeof (ct7_entry_t));
2799 			isp_prt(isp, ISP_LOGTDEBUG0, "%s: [%x] terminating after ABTS received", __func__, abts->abts_rxid_task);
2800 			cto->ct_header.rqs_entry_type = RQSTYPE_CTIO7;
2801 			cto->ct_header.rqs_entry_count = 1;
2802 			cto->ct_nphdl = mp->nt_nphdl;
2803 			cto->ct_rxid = abts->abts_rxid_task;
2804 			cto->ct_iid_lo = mp->nt_sid;
2805 			cto->ct_iid_hi = mp->nt_sid >> 16;
2806 			cto->ct_oxid = abts->abts_ox_id;
2807 			cto->ct_vpidx = mp->nt_channel;
2808 			cto->ct_flags = CT7_NOACK|CT7_TERMINATE;
2809 			if (isp_target_put_entry(isp, cto)) {
2810 				return (ENOMEM);
2811 			}
2812 			mp->nt_need_ack = 0;
2813 		}
2814 		if (isp_acknak_abts(isp, mp->nt_lreserved, 0) == ENOMEM) {
2815 			return (ENOMEM);
2816 		} else {
2817 			return (0);
2818 		}
2819 	}
2820 
2821 	/*
2822 	 * Handle logout cases here
2823 	 */
2824 	if (mp->nt_ncode == NT_GLOBAL_LOGOUT) {
2825 		isp_del_all_wwn_entries(isp, mp->nt_channel);
2826 	}
2827 
2828 	if (mp->nt_ncode == NT_LOGOUT) {
2829 		if (!IS_2100(isp) && IS_FC(isp)) {
2830 			isp_del_wwn_entries(isp, mp);
2831 		}
2832 	}
2833 
2834 	/*
2835 	 * General purpose acknowledgement
2836 	 */
2837 	if (mp->nt_need_ack) {
2838 		isp_prt(isp, ISP_LOGTINFO, "Notify Code 0x%x (qevalid=%d) being acked", mp->nt_ncode, mp->nt_lreserved != NULL);
2839 		/*
2840 		 * Don't need to use the guaranteed send because the caller can retry
2841 		 */
2842 		return (isp_notify_ack(isp, mp->nt_lreserved));
2843 	}
2844 	return (0);
2845 }
2846 
2847 /*
2848  * Handle task management functions.
2849  *
2850  * We show up here with a notify structure filled out.
2851  *
2852  * The nt_lreserved tag points to the original queue entry
2853  */
2854 static void
2855 isp_handle_platform_target_tmf(ispsoftc_t *isp, isp_notify_t *notify)
2856 {
2857 	tstate_t *tptr;
2858 	fcportdb_t *lp;
2859 	struct ccb_immediate_notify *inot;
2860 	inot_private_data_t *ntp = NULL;
2861 	lun_id_t lun;
2862 
2863 	isp_prt(isp, ISP_LOGTDEBUG0, "%s: code 0x%x sid  0x%x tagval 0x%016llx chan %d lun 0x%x", __func__, notify->nt_ncode,
2864 	    notify->nt_sid, (unsigned long long) notify->nt_tagval, notify->nt_channel, notify->nt_lun);
2865 	/*
2866 	 * NB: This assignment is necessary because of tricky type conversion.
2867 	 * XXX: This is tricky and I need to check this. If the lun isn't known
2868 	 * XXX: for the task management function, it does not of necessity follow
2869 	 * XXX: that it should go up stream to the wildcard listener.
2870 	 */
2871 	if (notify->nt_lun == LUN_ANY) {
2872 		lun = CAM_LUN_WILDCARD;
2873 	} else {
2874 		lun = notify->nt_lun;
2875 	}
2876 	tptr = get_lun_statep(isp, notify->nt_channel, lun);
2877 	if (tptr == NULL) {
2878 		tptr = get_lun_statep(isp, notify->nt_channel, CAM_LUN_WILDCARD);
2879 		if (tptr == NULL) {
2880 			isp_prt(isp, ISP_LOGWARN, "%s: no state pointer found for chan %d lun %#jx", __func__, notify->nt_channel, (uintmax_t)lun);
2881 			goto bad;
2882 		}
2883 	}
2884 	inot = (struct ccb_immediate_notify *) SLIST_FIRST(&tptr->inots);
2885 	if (inot == NULL) {
2886 		isp_prt(isp, ISP_LOGWARN, "%s: out of immediate notify structures for chan %d lun %#jx", __func__, notify->nt_channel, (uintmax_t)lun);
2887 		goto bad;
2888 	}
2889 
2890 	if (isp_find_pdb_by_portid(isp, notify->nt_channel, notify->nt_sid, &lp) == 0 &&
2891 	    isp_find_pdb_by_handle(isp, notify->nt_channel, notify->nt_nphdl, &lp) == 0) {
2892 		inot->initiator_id = CAM_TARGET_WILDCARD;
2893 	} else {
2894 		inot->initiator_id = FC_PORTDB_TGT(isp, notify->nt_channel, lp);
2895 	}
2896 	inot->seq_id = notify->nt_tagval;
2897 	inot->tag_id = notify->nt_tagval >> 32;
2898 
2899 	switch (notify->nt_ncode) {
2900 	case NT_ABORT_TASK:
2901 		isp_target_mark_aborted_early(isp, tptr, inot->tag_id);
2902 		inot->arg = MSG_ABORT_TASK;
2903 		break;
2904 	case NT_ABORT_TASK_SET:
2905 		isp_target_mark_aborted_early(isp, tptr, TAG_ANY);
2906 		inot->arg = MSG_ABORT_TASK_SET;
2907 		break;
2908 	case NT_CLEAR_ACA:
2909 		inot->arg = MSG_CLEAR_ACA;
2910 		break;
2911 	case NT_CLEAR_TASK_SET:
2912 		inot->arg = MSG_CLEAR_TASK_SET;
2913 		break;
2914 	case NT_LUN_RESET:
2915 		inot->arg = MSG_LOGICAL_UNIT_RESET;
2916 		break;
2917 	case NT_TARGET_RESET:
2918 		inot->arg = MSG_TARGET_RESET;
2919 		break;
2920 	case NT_QUERY_TASK_SET:
2921 		inot->arg = MSG_QUERY_TASK_SET;
2922 		break;
2923 	case NT_QUERY_ASYNC_EVENT:
2924 		inot->arg = MSG_QUERY_ASYNC_EVENT;
2925 		break;
2926 	default:
2927 		isp_prt(isp, ISP_LOGWARN, "%s: unknown TMF code 0x%x for chan %d lun %#jx", __func__, notify->nt_ncode, notify->nt_channel, (uintmax_t)lun);
2928 		goto bad;
2929 	}
2930 
2931 	ntp = isp_get_ntpd(isp, tptr);
2932 	if (ntp == NULL) {
2933 		isp_prt(isp, ISP_LOGWARN, "%s: out of inotify private structures", __func__);
2934 		goto bad;
2935 	}
2936 	ISP_MEMCPY(&ntp->rd.nt, notify, sizeof (isp_notify_t));
2937 	if (notify->nt_lreserved) {
2938 		ISP_MEMCPY(&ntp->rd.data, notify->nt_lreserved, QENTRY_LEN);
2939 		ntp->rd.nt.nt_lreserved = &ntp->rd.data;
2940 	}
2941 	ntp->rd.seq_id = notify->nt_tagval;
2942 	ntp->rd.tag_id = notify->nt_tagval >> 32;
2943 
2944 	tptr->inot_count--;
2945 	SLIST_REMOVE_HEAD(&tptr->inots, sim_links.sle);
2946 	rls_lun_statep(isp, tptr);
2947 	ISP_PATH_PRT(isp, ISP_LOGTDEBUG2, inot->ccb_h.path, "%s: Take FREE INOT count now %d\n", __func__, tptr->inot_count);
2948 	inot->ccb_h.status = CAM_MESSAGE_RECV;
2949 	xpt_done((union ccb *)inot);
2950 	return;
2951 bad:
2952 	if (tptr) {
2953 		rls_lun_statep(isp, tptr);
2954 	}
2955 	if (notify->nt_need_ack && notify->nt_lreserved) {
2956 		if (((isphdr_t *)notify->nt_lreserved)->rqs_entry_type == RQSTYPE_ABTS_RCVD) {
2957 			if (isp_acknak_abts(isp, notify->nt_lreserved, ENOMEM)) {
2958 				isp_prt(isp, ISP_LOGWARN, "you lose- unable to send an ACKNAK");
2959 			}
2960 		} else {
2961 			isp_async(isp, ISPASYNC_TARGET_NOTIFY_ACK, notify->nt_lreserved);
2962 		}
2963 	}
2964 }
2965 
2966 /*
2967  * Find the associated private data and mark it as dead so
2968  * we don't try to work on it any further.
2969  */
2970 static void
2971 isp_target_mark_aborted(ispsoftc_t *isp, union ccb *ccb)
2972 {
2973 	tstate_t *tptr;
2974 	atio_private_data_t *atp;
2975 	union ccb *accb = ccb->cab.abort_ccb;
2976 
2977 	tptr = get_lun_statep(isp, XS_CHANNEL(accb), XS_LUN(accb));
2978 	if (tptr == NULL) {
2979 		tptr = get_lun_statep(isp, XS_CHANNEL(accb), CAM_LUN_WILDCARD);
2980 		if (tptr == NULL) {
2981 			ccb->ccb_h.status = CAM_REQ_INVALID;
2982 			return;
2983 		}
2984 	}
2985 
2986 	atp = isp_find_atpd(isp, tptr, accb->atio.tag_id);
2987 	if (atp == NULL) {
2988 		ccb->ccb_h.status = CAM_REQ_INVALID;
2989 	} else {
2990 		atp->dead = 1;
2991 		ccb->ccb_h.status = CAM_REQ_CMP;
2992 	}
2993 	rls_lun_statep(isp, tptr);
2994 }
2995 
2996 static void
2997 isp_target_mark_aborted_early(ispsoftc_t *isp, tstate_t *tptr, uint32_t tag_id)
2998 {
2999 	atio_private_data_t *atp;
3000 	inot_private_data_t *restart_queue = tptr->restart_queue;
3001 
3002 	/*
3003 	 * First, clean any commands pending restart
3004 	 */
3005 	tptr->restart_queue = NULL;
3006 	while (restart_queue) {
3007 		uint32_t this_tag_id;
3008 		inot_private_data_t *ntp = restart_queue;
3009 
3010 		restart_queue = ntp->rd.nt.nt_hba;
3011 
3012 		if (IS_24XX(isp)) {
3013 			this_tag_id = ((at7_entry_t *)ntp->rd.data)->at_rxid;
3014 		} else {
3015 			this_tag_id = ((at2_entry_t *)ntp->rd.data)->at_rxid;
3016 		}
3017 		if ((uint64_t)tag_id == TAG_ANY || tag_id == this_tag_id) {
3018 			isp_put_ntpd(isp, tptr, ntp);
3019 		} else {
3020 			ntp->rd.nt.nt_hba = tptr->restart_queue;
3021 			tptr->restart_queue = ntp;
3022 		}
3023 	}
3024 
3025 	/*
3026 	 * Now mark other ones dead as well.
3027 	 */
3028 	for (atp = tptr->atpool; atp < &tptr->atpool[ATPDPSIZE]; atp++) {
3029 		if ((uint64_t)tag_id == TAG_ANY || atp->tag == tag_id) {
3030 			atp->dead = 1;
3031 		}
3032 	}
3033 }
3034 #endif
3035 
3036 static void
3037 isp_cam_async(void *cbarg, uint32_t code, struct cam_path *path, void *arg)
3038 {
3039 	struct cam_sim *sim;
3040 	int bus, tgt;
3041 	ispsoftc_t *isp;
3042 
3043 	sim = (struct cam_sim *)cbarg;
3044 	isp = (ispsoftc_t *) cam_sim_softc(sim);
3045 	bus = cam_sim_bus(sim);
3046 	tgt = xpt_path_target_id(path);
3047 
3048 	switch (code) {
3049 	case AC_LOST_DEVICE:
3050 		if (IS_SCSI(isp)) {
3051 			uint16_t oflags, nflags;
3052 			sdparam *sdp = SDPARAM(isp, bus);
3053 
3054 			if (tgt >= 0) {
3055 				nflags = sdp->isp_devparam[tgt].nvrm_flags;
3056 				nflags &= DPARM_SAFE_DFLT;
3057 				if (isp->isp_loaded_fw) {
3058 					nflags |= DPARM_NARROW | DPARM_ASYNC;
3059 				}
3060 				oflags = sdp->isp_devparam[tgt].goal_flags;
3061 				sdp->isp_devparam[tgt].goal_flags = nflags;
3062 				sdp->isp_devparam[tgt].dev_update = 1;
3063 				sdp->update = 1;
3064 				(void) isp_control(isp, ISPCTL_UPDATE_PARAMS, bus);
3065 				sdp->isp_devparam[tgt].goal_flags = oflags;
3066 			}
3067 		}
3068 		break;
3069 	default:
3070 		isp_prt(isp, ISP_LOGWARN, "isp_cam_async: Code 0x%x", code);
3071 		break;
3072 	}
3073 }
3074 
3075 static void
3076 isp_poll(struct cam_sim *sim)
3077 {
3078 	ispsoftc_t *isp = cam_sim_softc(sim);
3079 	uint16_t isr, sema, info;
3080 
3081 	if (ISP_READ_ISR(isp, &isr, &sema, &info))
3082 		isp_intr(isp, isr, sema, info);
3083 }
3084 
3085 
3086 static void
3087 isp_watchdog(void *arg)
3088 {
3089 	struct ccb_scsiio *xs = arg;
3090 	ispsoftc_t *isp;
3091 	uint32_t ohandle = ISP_HANDLE_FREE, handle;
3092 
3093 	isp = XS_ISP(xs);
3094 
3095 	handle = isp_find_handle(isp, xs);
3096 
3097 	/*
3098 	 * Hand crank the interrupt code just to be sure the command isn't stuck somewhere.
3099 	 */
3100 	if (handle != ISP_HANDLE_FREE) {
3101 		uint16_t isr, sema, info;
3102 		if (ISP_READ_ISR(isp, &isr, &sema, &info) != 0)
3103 			isp_intr(isp, isr, sema, info);
3104 		ohandle = handle;
3105 		handle = isp_find_handle(isp, xs);
3106 	}
3107 	if (handle != ISP_HANDLE_FREE) {
3108 		/*
3109 		 * Try and make sure the command is really dead before
3110 		 * we release the handle (and DMA resources) for reuse.
3111 		 *
3112 		 * If we are successful in aborting the command then
3113 		 * we're done here because we'll get the command returned
3114 		 * back separately.
3115 		 */
3116 		if (isp_control(isp, ISPCTL_ABORT_CMD, xs) == 0) {
3117 			return;
3118 		}
3119 
3120 		/*
3121 		 * Note that after calling the above, the command may in
3122 		 * fact have been completed.
3123 		 */
3124 		xs = isp_find_xs(isp, handle);
3125 
3126 		/*
3127 		 * If the command no longer exists, then we won't
3128 		 * be able to find the xs again with this handle.
3129 		 */
3130 		if (xs == NULL) {
3131 			return;
3132 		}
3133 
3134 		/*
3135 		 * After this point, the command is really dead.
3136 		 */
3137 		if (XS_XFRLEN(xs)) {
3138 			ISP_DMAFREE(isp, xs, handle);
3139 		}
3140 		isp_destroy_handle(isp, handle);
3141 		isp_prt(isp, ISP_LOGERR, "%s: timeout for handle 0x%x", __func__, handle);
3142 		xs->ccb_h.status &= ~CAM_STATUS_MASK;
3143 		xs->ccb_h.status |= CAM_CMD_TIMEOUT;
3144 		isp_prt_endcmd(isp, xs);
3145 		isp_done(xs);
3146 	} else {
3147 		if (ohandle != ISP_HANDLE_FREE) {
3148 			isp_prt(isp, ISP_LOGWARN, "%s: timeout for handle 0x%x, recovered during interrupt", __func__, ohandle);
3149 		} else {
3150 			isp_prt(isp, ISP_LOGWARN, "%s: timeout for handle already free", __func__);
3151 		}
3152 	}
3153 }
3154 
3155 static void
3156 isp_make_here(ispsoftc_t *isp, fcportdb_t *fcp, int chan, int tgt)
3157 {
3158 	union ccb *ccb;
3159 	struct isp_fc *fc = ISP_FC_PC(isp, chan);
3160 
3161 	/*
3162 	 * Allocate a CCB, create a wildcard path for this target and schedule a rescan.
3163 	 */
3164 	ccb = xpt_alloc_ccb_nowait();
3165 	if (ccb == NULL) {
3166 		isp_prt(isp, ISP_LOGWARN, "Chan %d unable to alloc CCB for rescan", chan);
3167 		return;
3168 	}
3169 	if (xpt_create_path(&ccb->ccb_h.path, NULL, cam_sim_path(fc->sim),
3170 	    tgt, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
3171 		isp_prt(isp, ISP_LOGWARN, "unable to create path for rescan");
3172 		xpt_free_ccb(ccb);
3173 		return;
3174 	}
3175 	xpt_rescan(ccb);
3176 }
3177 
3178 static void
3179 isp_make_gone(ispsoftc_t *isp, fcportdb_t *fcp, int chan, int tgt)
3180 {
3181 	struct cam_path *tp;
3182 	struct isp_fc *fc = ISP_FC_PC(isp, chan);
3183 
3184 	if (xpt_create_path(&tp, NULL, cam_sim_path(fc->sim), tgt, CAM_LUN_WILDCARD) == CAM_REQ_CMP) {
3185 		xpt_async(AC_LOST_DEVICE, tp, NULL);
3186 		xpt_free_path(tp);
3187 	}
3188 }
3189 
3190 /*
3191  * Gone Device Timer Function- when we have decided that a device has gone
3192  * away, we wait a specific period of time prior to telling the OS it has
3193  * gone away.
3194  *
3195  * This timer function fires once a second and then scans the port database
3196  * for devices that are marked dead but still have a virtual target assigned.
3197  * We decrement a counter for that port database entry, and when it hits zero,
3198  * we tell the OS the device has gone away.
3199  */
3200 static void
3201 isp_gdt(void *arg)
3202 {
3203 	struct isp_fc *fc = arg;
3204 	taskqueue_enqueue(taskqueue_thread, &fc->gtask);
3205 }
3206 
3207 static void
3208 isp_gdt_task(void *arg, int pending)
3209 {
3210 	struct isp_fc *fc = arg;
3211 	ispsoftc_t *isp = fc->isp;
3212 	int chan = fc - isp->isp_osinfo.pc.fc;
3213 	fcportdb_t *lp;
3214 	struct ac_contract ac;
3215 	struct ac_device_changed *adc;
3216 	int dbidx, more_to_do = 0;
3217 
3218 	ISP_LOCK(isp);
3219 	isp_prt(isp, ISP_LOGDEBUG0, "Chan %d GDT timer expired", chan);
3220 	for (dbidx = 0; dbidx < MAX_FC_TARG; dbidx++) {
3221 		lp = &FCPARAM(isp, chan)->portdb[dbidx];
3222 
3223 		if (lp->state != FC_PORTDB_STATE_ZOMBIE) {
3224 			continue;
3225 		}
3226 		if (lp->gone_timer != 0) {
3227 			lp->gone_timer -= 1;
3228 			more_to_do++;
3229 			continue;
3230 		}
3231 		isp_prt(isp, ISP_LOGCONFIG, prom3, chan, dbidx, lp->portid, "Gone Device Timeout");
3232 		if (lp->is_target) {
3233 			lp->is_target = 0;
3234 			isp_make_gone(isp, lp, chan, dbidx);
3235 		}
3236 		if (lp->is_initiator) {
3237 			lp->is_initiator = 0;
3238 			ac.contract_number = AC_CONTRACT_DEV_CHG;
3239 			adc = (struct ac_device_changed *) ac.contract_data;
3240 			adc->wwpn = lp->port_wwn;
3241 			adc->port = lp->portid;
3242 			adc->target = dbidx;
3243 			adc->arrived = 0;
3244 			xpt_async(AC_CONTRACT, fc->path, &ac);
3245 		}
3246 		lp->state = FC_PORTDB_STATE_NIL;
3247 	}
3248 	if (fc->ready) {
3249 		if (more_to_do) {
3250 			callout_reset(&fc->gdt, hz, isp_gdt, fc);
3251 		} else {
3252 			callout_deactivate(&fc->gdt);
3253 			isp_prt(isp, ISP_LOG_SANCFG, "Chan %d Stopping Gone Device Timer @ %lu", chan, (unsigned long) time_uptime);
3254 		}
3255 	}
3256 	ISP_UNLOCK(isp);
3257 }
3258 
3259 /*
3260  * When loop goes down we remember the time and freeze CAM command queue.
3261  * During some time period we are trying to reprobe the loop.  But if we
3262  * fail, we tell the OS that devices have gone away and drop the freeze.
3263  *
3264  * We don't clear the devices out of our port database because, when loop
3265  * come back up, we have to do some actual cleanup with the chip at that
3266  * point (implicit PLOGO, e.g., to get the chip's port database state right).
3267  */
3268 static void
3269 isp_loop_changed(ispsoftc_t *isp, int chan)
3270 {
3271 	fcparam *fcp = FCPARAM(isp, chan);
3272 	struct isp_fc *fc = ISP_FC_PC(isp, chan);
3273 
3274 	if (fc->loop_down_time)
3275 		return;
3276 	isp_prt(isp, ISP_LOG_SANCFG|ISP_LOGDEBUG0, "Chan %d Loop changed", chan);
3277 	if (fcp->role & ISP_ROLE_INITIATOR)
3278 		isp_freeze_loopdown(isp, chan);
3279 	fc->loop_dead = 0;
3280 	fc->loop_down_time = time_uptime;
3281 	wakeup(fc);
3282 }
3283 
3284 static void
3285 isp_loop_up(ispsoftc_t *isp, int chan)
3286 {
3287 	struct isp_fc *fc = ISP_FC_PC(isp, chan);
3288 
3289 	isp_prt(isp, ISP_LOG_SANCFG|ISP_LOGDEBUG0, "Chan %d Loop is up", chan);
3290 	fc->loop_seen_once = 1;
3291 	fc->loop_dead = 0;
3292 	fc->loop_down_time = 0;
3293 	isp_unfreeze_loopdown(isp, chan);
3294 }
3295 
3296 static void
3297 isp_loop_dead(ispsoftc_t *isp, int chan)
3298 {
3299 	fcparam *fcp = FCPARAM(isp, chan);
3300 	struct isp_fc *fc = ISP_FC_PC(isp, chan);
3301 	fcportdb_t *lp;
3302 	struct ac_contract ac;
3303 	struct ac_device_changed *adc;
3304 	int dbidx, i;
3305 
3306 	isp_prt(isp, ISP_LOG_SANCFG|ISP_LOGDEBUG0, "Chan %d Loop is dead", chan);
3307 
3308 	/*
3309 	 * Notify to the OS all targets who we now consider have departed.
3310 	 */
3311 	for (dbidx = 0; dbidx < MAX_FC_TARG; dbidx++) {
3312 		lp = &fcp->portdb[dbidx];
3313 
3314 		if (lp->state == FC_PORTDB_STATE_NIL)
3315 			continue;
3316 
3317 		/*
3318 		 * XXX: CLEAN UP AND COMPLETE ANY PENDING COMMANDS FIRST!
3319 		 */
3320 		for (i = 0; i < isp->isp_maxcmds; i++) {
3321 			struct ccb_scsiio *xs;
3322 
3323 			if (!ISP_VALID_HANDLE(isp, isp->isp_xflist[i].handle)) {
3324 				continue;
3325 			}
3326 			if ((xs = isp->isp_xflist[i].cmd) == NULL) {
3327 				continue;
3328                         }
3329 			if (dbidx != XS_TGT(xs)) {
3330 				continue;
3331 			}
3332 			isp_prt(isp, ISP_LOGWARN, "command handle 0x%x for %d.%d.%jx orphaned by loop down timeout",
3333 			    isp->isp_xflist[i].handle, chan, XS_TGT(xs),
3334 			    (uintmax_t)XS_LUN(xs));
3335 		}
3336 
3337 		isp_prt(isp, ISP_LOGCONFIG, prom3, chan, dbidx, lp->portid, "Loop Down Timeout");
3338 		if (lp->is_target) {
3339 			lp->is_target = 0;
3340 			isp_make_gone(isp, lp, chan, dbidx);
3341 		}
3342 		if (lp->is_initiator) {
3343 			lp->is_initiator = 0;
3344 			ac.contract_number = AC_CONTRACT_DEV_CHG;
3345 			adc = (struct ac_device_changed *) ac.contract_data;
3346 			adc->wwpn = lp->port_wwn;
3347 			adc->port = lp->portid;
3348 			adc->target = dbidx;
3349 			adc->arrived = 0;
3350 			xpt_async(AC_CONTRACT, fc->path, &ac);
3351 		}
3352 	}
3353 
3354 	isp_unfreeze_loopdown(isp, chan);
3355 	fc->loop_dead = 1;
3356 	fc->loop_down_time = 0;
3357 }
3358 
3359 static void
3360 isp_kthread(void *arg)
3361 {
3362 	struct isp_fc *fc = arg;
3363 	ispsoftc_t *isp = fc->isp;
3364 	int chan = fc - isp->isp_osinfo.pc.fc;
3365 	int slp = 0, d;
3366 	int lb, lim;
3367 
3368 	mtx_lock(&isp->isp_osinfo.lock);
3369 
3370 	while (isp->isp_osinfo.is_exiting == 0) {
3371 		isp_prt(isp, ISP_LOG_SANCFG|ISP_LOGDEBUG0,
3372 		    "Chan %d Checking FC state", chan);
3373 		lb = isp_fc_runstate(isp, chan, 250000);
3374 		isp_prt(isp, ISP_LOG_SANCFG|ISP_LOGDEBUG0,
3375 		    "Chan %d FC got to %s state", chan,
3376 		    isp_fc_loop_statename(lb));
3377 
3378 		/*
3379 		 * Our action is different based upon whether we're supporting
3380 		 * Initiator mode or not. If we are, we might freeze the simq
3381 		 * when loop is down and set all sorts of different delays to
3382 		 * check again.
3383 		 *
3384 		 * If not, we simply just wait for loop to come up.
3385 		 */
3386 		if (lb == LOOP_READY || lb < 0) {
3387 			slp = 0;
3388 		} else {
3389 			/*
3390 			 * If we've never seen loop up and we've waited longer
3391 			 * than quickboot time, or we've seen loop up but we've
3392 			 * waited longer than loop_down_limit, give up and go
3393 			 * to sleep until loop comes up.
3394 			 */
3395 			if (fc->loop_seen_once == 0)
3396 				lim = isp_quickboot_time;
3397 			else
3398 				lim = fc->loop_down_limit;
3399 			d = time_uptime - fc->loop_down_time;
3400 			if (d >= lim)
3401 				slp = 0;
3402 			else if (d < 10)
3403 				slp = 1;
3404 			else if (d < 30)
3405 				slp = 5;
3406 			else if (d < 60)
3407 				slp = 10;
3408 			else if (d < 120)
3409 				slp = 20;
3410 			else
3411 				slp = 30;
3412 		}
3413 
3414 		if (slp == 0) {
3415 			if (lb == LOOP_READY)
3416 				isp_loop_up(isp, chan);
3417 			else
3418 				isp_loop_dead(isp, chan);
3419 		}
3420 
3421 		isp_prt(isp, ISP_LOG_SANCFG|ISP_LOGDEBUG0,
3422 		    "Chan %d sleep for %d seconds", chan, slp);
3423 		msleep(fc, &isp->isp_osinfo.lock, PRIBIO, "ispf", slp * hz);
3424 	}
3425 	fc->num_threads -= 1;
3426 	mtx_unlock(&isp->isp_osinfo.lock);
3427 	kthread_exit();
3428 }
3429 
3430 static void
3431 isp_action(struct cam_sim *sim, union ccb *ccb)
3432 {
3433 	int bus, tgt, ts, error;
3434 	ispsoftc_t *isp;
3435 	struct ccb_trans_settings *cts;
3436 
3437 	CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_TRACE, ("isp_action\n"));
3438 
3439 	isp = (ispsoftc_t *)cam_sim_softc(sim);
3440 	mtx_assert(&isp->isp_lock, MA_OWNED);
3441 	isp_prt(isp, ISP_LOGDEBUG2, "isp_action code %x", ccb->ccb_h.func_code);
3442 	ISP_PCMD(ccb) = NULL;
3443 
3444 	switch (ccb->ccb_h.func_code) {
3445 	case XPT_SCSI_IO:	/* Execute the requested I/O operation */
3446 		bus = XS_CHANNEL(ccb);
3447 		/*
3448 		 * Do a couple of preliminary checks...
3449 		 */
3450 		if ((ccb->ccb_h.flags & CAM_CDB_POINTER) != 0) {
3451 			if ((ccb->ccb_h.flags & CAM_CDB_PHYS) != 0) {
3452 				ccb->ccb_h.status = CAM_REQ_INVALID;
3453 				isp_done((struct ccb_scsiio *) ccb);
3454 				break;
3455 			}
3456 		}
3457 		ccb->csio.req_map = NULL;
3458 #ifdef	DIAGNOSTIC
3459 		if (ccb->ccb_h.target_id >= ISP_MAX_TARGETS(isp)) {
3460 			xpt_print(ccb->ccb_h.path, "invalid target\n");
3461 			ccb->ccb_h.status = CAM_PATH_INVALID;
3462 		} else if (ISP_MAX_LUNS(isp) > 0 &&
3463 		    ccb->ccb_h.target_lun >= ISP_MAX_LUNS(isp)) {
3464 			xpt_print(ccb->ccb_h.path, "invalid lun\n");
3465 			ccb->ccb_h.status = CAM_PATH_INVALID;
3466 		}
3467 		if (ccb->ccb_h.status == CAM_PATH_INVALID) {
3468 			xpt_done(ccb);
3469 			break;
3470 		}
3471 #endif
3472 		ccb->csio.scsi_status = SCSI_STATUS_OK;
3473 		if (isp_get_pcmd(isp, ccb)) {
3474 			isp_prt(isp, ISP_LOGWARN, "out of PCMDs");
3475 			cam_freeze_devq(ccb->ccb_h.path);
3476 			cam_release_devq(ccb->ccb_h.path, RELSIM_RELEASE_AFTER_TIMEOUT, 0, 250, 0);
3477 			ccb->ccb_h.status = CAM_REQUEUE_REQ;
3478 			xpt_done(ccb);
3479 			break;
3480 		}
3481 		error = isp_start((XS_T *) ccb);
3482 		switch (error) {
3483 		case CMD_QUEUED:
3484 			ccb->ccb_h.status |= CAM_SIM_QUEUED;
3485 			if (ccb->ccb_h.timeout == CAM_TIME_INFINITY) {
3486 				break;
3487 			}
3488 			ts = ccb->ccb_h.timeout;
3489 			if (ts == CAM_TIME_DEFAULT) {
3490 				ts = 60*1000;
3491 			}
3492 			ts = isp_mstohz(ts);
3493 			callout_reset(&PISP_PCMD(ccb)->wdog, ts, isp_watchdog, ccb);
3494 			break;
3495 		case CMD_RQLATER:
3496 			/*
3497 			 * We get this result if the loop isn't ready
3498 			 * or if the device in question has gone zombie.
3499 			 */
3500 			if (ISP_FC_PC(isp, bus)->loop_dead) {
3501 				isp_prt(isp, ISP_LOGDEBUG0,
3502 				    "%d.%jx loop is dead",
3503 				    XS_TGT(ccb), (uintmax_t)XS_LUN(ccb));
3504 				ccb->ccb_h.status = CAM_SEL_TIMEOUT;
3505 				isp_done((struct ccb_scsiio *) ccb);
3506 				break;
3507 			}
3508 			isp_prt(isp, ISP_LOGDEBUG0, "%d.%jx retry later",
3509 			    XS_TGT(ccb), (uintmax_t)XS_LUN(ccb));
3510 			cam_freeze_devq(ccb->ccb_h.path);
3511 			cam_release_devq(ccb->ccb_h.path, RELSIM_RELEASE_AFTER_TIMEOUT, 0, 1000, 0);
3512 			ccb->ccb_h.status = CAM_REQUEUE_REQ;
3513 			isp_free_pcmd(isp, ccb);
3514 			xpt_done(ccb);
3515 			break;
3516 		case CMD_EAGAIN:
3517 			isp_free_pcmd(isp, ccb);
3518 			cam_freeze_devq(ccb->ccb_h.path);
3519 			cam_release_devq(ccb->ccb_h.path, RELSIM_RELEASE_AFTER_TIMEOUT, 0, 100, 0);
3520 			ccb->ccb_h.status = CAM_REQUEUE_REQ;
3521 			xpt_done(ccb);
3522 			break;
3523 		case CMD_COMPLETE:
3524 			isp_done((struct ccb_scsiio *) ccb);
3525 			break;
3526 		default:
3527 			isp_prt(isp, ISP_LOGERR, "What's this? 0x%x at %d in file %s", error, __LINE__, __FILE__);
3528 			ccb->ccb_h.status = CAM_REQUEUE_REQ;
3529 			isp_free_pcmd(isp, ccb);
3530 			xpt_done(ccb);
3531 		}
3532 		break;
3533 
3534 #ifdef	ISP_TARGET_MODE
3535 	case XPT_EN_LUN:		/* Enable/Disable LUN as a target */
3536 		if (ccb->cel.enable) {
3537 			isp_enable_lun(isp, ccb);
3538 		} else {
3539 			isp_disable_lun(isp, ccb);
3540 		}
3541 		break;
3542 	case XPT_IMMED_NOTIFY:
3543 	case XPT_IMMEDIATE_NOTIFY:	/* Add Immediate Notify Resource */
3544 	case XPT_ACCEPT_TARGET_IO:	/* Add Accept Target IO Resource */
3545 	{
3546 		tstate_t *tptr = get_lun_statep(isp, XS_CHANNEL(ccb), ccb->ccb_h.target_lun);
3547 		if (tptr == NULL) {
3548 			tptr = get_lun_statep(isp, XS_CHANNEL(ccb), CAM_LUN_WILDCARD);
3549 		}
3550 		if (tptr == NULL) {
3551 			const char *str;
3552 			uint32_t tag;
3553 
3554 			if (ccb->ccb_h.func_code == XPT_IMMEDIATE_NOTIFY) {
3555 				str = "XPT_IMMEDIATE_NOTIFY";
3556 				tag = ccb->cin1.seq_id;
3557 			} else {
3558 				tag = ccb->atio.tag_id;
3559 				str = "XPT_ACCEPT_TARGET_IO";
3560 			}
3561 			ISP_PATH_PRT(isp, ISP_LOGWARN, ccb->ccb_h.path, "%s: [0x%x] no state pointer found for %s\n", __func__, tag, str);
3562 			dump_tstates(isp, XS_CHANNEL(ccb));
3563 			ccb->ccb_h.status = CAM_DEV_NOT_THERE;
3564 			break;
3565 		}
3566 		ccb->ccb_h.spriv_field0 = 0;
3567 		ccb->ccb_h.spriv_ptr1 = isp;
3568 
3569 		if (ccb->ccb_h.func_code == XPT_ACCEPT_TARGET_IO) {
3570 			if (ccb->atio.tag_id) {
3571 				atio_private_data_t *atp = isp_find_atpd(isp, tptr, ccb->atio.tag_id);
3572 				if (atp) {
3573 					isp_put_atpd(isp, tptr, atp);
3574 				}
3575 			}
3576 			tptr->atio_count++;
3577 			SLIST_INSERT_HEAD(&tptr->atios, &ccb->ccb_h, sim_links.sle);
3578 			ISP_PATH_PRT(isp, ISP_LOGTDEBUG2, ccb->ccb_h.path, "Put FREE ATIO (tag id 0x%x), count now %d\n",
3579 			    ccb->atio.tag_id, tptr->atio_count);
3580 			ccb->atio.tag_id = 0;
3581 		} else if (ccb->ccb_h.func_code == XPT_IMMEDIATE_NOTIFY) {
3582 			if (ccb->cin1.tag_id) {
3583 				inot_private_data_t *ntp = isp_find_ntpd(isp, tptr, ccb->cin1.tag_id, ccb->cin1.seq_id);
3584 				if (ntp) {
3585 					isp_put_ntpd(isp, tptr, ntp);
3586 				}
3587 			}
3588 			tptr->inot_count++;
3589 			SLIST_INSERT_HEAD(&tptr->inots, &ccb->ccb_h, sim_links.sle);
3590 			ISP_PATH_PRT(isp, ISP_LOGTDEBUG2, ccb->ccb_h.path, "Put FREE INOT, (seq id 0x%x) count now %d\n",
3591 			    ccb->cin1.seq_id, tptr->inot_count);
3592 			ccb->cin1.seq_id = 0;
3593 		} else if (ccb->ccb_h.func_code == XPT_IMMED_NOTIFY) {
3594 			tptr->inot_count++;
3595 			SLIST_INSERT_HEAD(&tptr->inots, &ccb->ccb_h, sim_links.sle);
3596 			ISP_PATH_PRT(isp, ISP_LOGTDEBUG2, ccb->ccb_h.path, "Put FREE INOT, (seq id 0x%x) count now %d\n",
3597 			    ccb->cin1.seq_id, tptr->inot_count);
3598 			ccb->cin1.seq_id = 0;
3599 		}
3600 		rls_lun_statep(isp, tptr);
3601 		ccb->ccb_h.status = CAM_REQ_INPROG;
3602 		break;
3603 	}
3604 	case XPT_NOTIFY_ACK:
3605 		ccb->ccb_h.status = CAM_REQ_CMP_ERR;
3606 		break;
3607 	case XPT_NOTIFY_ACKNOWLEDGE:		/* notify ack */
3608 	{
3609 		tstate_t *tptr;
3610 		inot_private_data_t *ntp;
3611 
3612 		/*
3613 		 * XXX: Because we cannot guarantee that the path information in the notify acknowledge ccb
3614 		 * XXX: matches that for the immediate notify, we have to *search* for the notify structure
3615 		 */
3616 		/*
3617 		 * All the relevant path information is in the associated immediate notify
3618 		 */
3619 		ISP_PATH_PRT(isp, ISP_LOGTDEBUG0, ccb->ccb_h.path, "%s: [0x%x] NOTIFY ACKNOWLEDGE for 0x%x seen\n", __func__, ccb->cna2.tag_id, ccb->cna2.seq_id);
3620 		ntp = get_ntp_from_tagdata(isp, ccb->cna2.tag_id, ccb->cna2.seq_id, &tptr);
3621 		if (ntp == NULL) {
3622 			ISP_PATH_PRT(isp, ISP_LOGWARN, ccb->ccb_h.path, "%s: [0x%x] XPT_NOTIFY_ACKNOWLEDGE of 0x%x cannot find ntp private data\n", __func__,
3623 			     ccb->cna2.tag_id, ccb->cna2.seq_id);
3624 			ccb->ccb_h.status = CAM_DEV_NOT_THERE;
3625 			xpt_done(ccb);
3626 			break;
3627 		}
3628 		if (isp_handle_platform_target_notify_ack(isp, &ntp->rd.nt)) {
3629 			rls_lun_statep(isp, tptr);
3630 			cam_freeze_devq(ccb->ccb_h.path);
3631 			cam_release_devq(ccb->ccb_h.path, RELSIM_RELEASE_AFTER_TIMEOUT, 0, 1000, 0);
3632 			ccb->ccb_h.status &= ~CAM_STATUS_MASK;
3633 			ccb->ccb_h.status |= CAM_REQUEUE_REQ;
3634 			break;
3635 		}
3636 		isp_put_ntpd(isp, tptr, ntp);
3637 		rls_lun_statep(isp, tptr);
3638 		ccb->ccb_h.status = CAM_REQ_CMP;
3639 		ISP_PATH_PRT(isp, ISP_LOGTDEBUG0, ccb->ccb_h.path, "%s: [0x%x] calling xpt_done for tag 0x%x\n", __func__, ccb->cna2.tag_id, ccb->cna2.seq_id);
3640 		xpt_done(ccb);
3641 		break;
3642 	}
3643 	case XPT_CONT_TARGET_IO:
3644 		isp_target_start_ctio(isp, ccb, FROM_CAM);
3645 		break;
3646 #endif
3647 	case XPT_RESET_DEV:		/* BDR the specified SCSI device */
3648 		bus = cam_sim_bus(xpt_path_sim(ccb->ccb_h.path));
3649 		tgt = ccb->ccb_h.target_id;
3650 		tgt |= (bus << 16);
3651 
3652 		error = isp_control(isp, ISPCTL_RESET_DEV, bus, tgt);
3653 		if (error) {
3654 			ccb->ccb_h.status = CAM_REQ_CMP_ERR;
3655 		} else {
3656 			/*
3657 			 * If we have a FC device, reset the Command
3658 			 * Reference Number, because the target will expect
3659 			 * that we re-start the CRN at 1 after a reset.
3660 			 */
3661 			if (IS_FC(isp))
3662 				isp_fcp_reset_crn(isp, bus, tgt, /*tgt_set*/ 1);
3663 
3664 			ccb->ccb_h.status = CAM_REQ_CMP;
3665 		}
3666 		xpt_done(ccb);
3667 		break;
3668 	case XPT_ABORT:			/* Abort the specified CCB */
3669 	{
3670 		union ccb *accb = ccb->cab.abort_ccb;
3671 		switch (accb->ccb_h.func_code) {
3672 #ifdef	ISP_TARGET_MODE
3673 		case XPT_ACCEPT_TARGET_IO:
3674 			isp_target_mark_aborted(isp, ccb);
3675 			break;
3676 #endif
3677 		case XPT_SCSI_IO:
3678 			error = isp_control(isp, ISPCTL_ABORT_CMD, accb);
3679 			if (error) {
3680 				ccb->ccb_h.status = CAM_UA_ABORT;
3681 			} else {
3682 				ccb->ccb_h.status = CAM_REQ_CMP;
3683 			}
3684 			break;
3685 		default:
3686 			ccb->ccb_h.status = CAM_REQ_INVALID;
3687 			break;
3688 		}
3689 		/*
3690 		 * This is not a queued CCB, so the caller expects it to be
3691 		 * complete when control is returned.
3692 		 */
3693 		break;
3694 	}
3695 #define	IS_CURRENT_SETTINGS(c)	(c->type == CTS_TYPE_CURRENT_SETTINGS)
3696 	case XPT_SET_TRAN_SETTINGS:	/* Nexus Settings */
3697 		cts = &ccb->cts;
3698 		if (!IS_CURRENT_SETTINGS(cts)) {
3699 			ccb->ccb_h.status = CAM_REQ_INVALID;
3700 			xpt_done(ccb);
3701 			break;
3702 		}
3703 		tgt = cts->ccb_h.target_id;
3704 		bus = cam_sim_bus(xpt_path_sim(cts->ccb_h.path));
3705 		if (IS_SCSI(isp)) {
3706 			struct ccb_trans_settings_scsi *scsi = &cts->proto_specific.scsi;
3707 			struct ccb_trans_settings_spi *spi = &cts->xport_specific.spi;
3708 			sdparam *sdp = SDPARAM(isp, bus);
3709 			uint16_t *dptr;
3710 
3711 			if (spi->valid == 0 && scsi->valid == 0) {
3712 				ccb->ccb_h.status = CAM_REQ_CMP;
3713 				xpt_done(ccb);
3714 				break;
3715 			}
3716 
3717 			/*
3718 			 * We always update (internally) from goal_flags
3719 			 * so any request to change settings just gets
3720 			 * vectored to that location.
3721 			 */
3722 			dptr = &sdp->isp_devparam[tgt].goal_flags;
3723 
3724 			if ((spi->valid & CTS_SPI_VALID_DISC) != 0) {
3725 				if ((spi->flags & CTS_SPI_FLAGS_DISC_ENB) != 0)
3726 					*dptr |= DPARM_DISC;
3727 				else
3728 					*dptr &= ~DPARM_DISC;
3729 			}
3730 
3731 			if ((scsi->valid & CTS_SCSI_VALID_TQ) != 0) {
3732 				if ((scsi->flags & CTS_SCSI_FLAGS_TAG_ENB) != 0)
3733 					*dptr |= DPARM_TQING;
3734 				else
3735 					*dptr &= ~DPARM_TQING;
3736 			}
3737 
3738 			if ((spi->valid & CTS_SPI_VALID_BUS_WIDTH) != 0) {
3739 				if (spi->bus_width == MSG_EXT_WDTR_BUS_16_BIT)
3740 					*dptr |= DPARM_WIDE;
3741 				else
3742 					*dptr &= ~DPARM_WIDE;
3743 			}
3744 
3745 			/*
3746 			 * XXX: FIX ME
3747 			 */
3748 			if ((spi->valid & CTS_SPI_VALID_SYNC_OFFSET) && (spi->valid & CTS_SPI_VALID_SYNC_RATE) && (spi->sync_period && spi->sync_offset)) {
3749 				*dptr |= DPARM_SYNC;
3750 				/*
3751 				 * XXX: CHECK FOR LEGALITY
3752 				 */
3753 				sdp->isp_devparam[tgt].goal_period = spi->sync_period;
3754 				sdp->isp_devparam[tgt].goal_offset = spi->sync_offset;
3755 			} else {
3756 				*dptr &= ~DPARM_SYNC;
3757 			}
3758 			isp_prt(isp, ISP_LOGDEBUG0, "SET (%d.%d.%jx) to flags %x off %x per %x", bus, tgt, (uintmax_t)cts->ccb_h.target_lun, sdp->isp_devparam[tgt].goal_flags,
3759 			    sdp->isp_devparam[tgt].goal_offset, sdp->isp_devparam[tgt].goal_period);
3760 			sdp->isp_devparam[tgt].dev_update = 1;
3761 			sdp->update = 1;
3762 		}
3763 		ccb->ccb_h.status = CAM_REQ_CMP;
3764 		xpt_done(ccb);
3765 		break;
3766 	case XPT_GET_TRAN_SETTINGS:
3767 		cts = &ccb->cts;
3768 		tgt = cts->ccb_h.target_id;
3769 		bus = cam_sim_bus(xpt_path_sim(cts->ccb_h.path));
3770 		if (IS_FC(isp)) {
3771 			fcparam *fcp = FCPARAM(isp, bus);
3772 			struct ccb_trans_settings_scsi *scsi = &cts->proto_specific.scsi;
3773 			struct ccb_trans_settings_fc *fc = &cts->xport_specific.fc;
3774 
3775 			cts->protocol = PROTO_SCSI;
3776 			cts->protocol_version = SCSI_REV_2;
3777 			cts->transport = XPORT_FC;
3778 			cts->transport_version = 0;
3779 
3780 			scsi->valid = CTS_SCSI_VALID_TQ;
3781 			scsi->flags = CTS_SCSI_FLAGS_TAG_ENB;
3782 			fc->valid = CTS_FC_VALID_SPEED;
3783 			fc->bitrate = 100000;
3784 			fc->bitrate *= fcp->isp_gbspeed;
3785 			if (tgt < MAX_FC_TARG) {
3786 				fcportdb_t *lp = &fcp->portdb[tgt];
3787 				fc->wwnn = lp->node_wwn;
3788 				fc->wwpn = lp->port_wwn;
3789 				fc->port = lp->portid;
3790 				fc->valid |= CTS_FC_VALID_WWNN | CTS_FC_VALID_WWPN | CTS_FC_VALID_PORT;
3791 			}
3792 		} else {
3793 			struct ccb_trans_settings_scsi *scsi = &cts->proto_specific.scsi;
3794 			struct ccb_trans_settings_spi *spi = &cts->xport_specific.spi;
3795 			sdparam *sdp = SDPARAM(isp, bus);
3796 			uint16_t dval, pval, oval;
3797 
3798 			if (IS_CURRENT_SETTINGS(cts)) {
3799 				sdp->isp_devparam[tgt].dev_refresh = 1;
3800 				sdp->update = 1;
3801 				(void) isp_control(isp, ISPCTL_UPDATE_PARAMS, bus);
3802 				dval = sdp->isp_devparam[tgt].actv_flags;
3803 				oval = sdp->isp_devparam[tgt].actv_offset;
3804 				pval = sdp->isp_devparam[tgt].actv_period;
3805 			} else {
3806 				dval = sdp->isp_devparam[tgt].nvrm_flags;
3807 				oval = sdp->isp_devparam[tgt].nvrm_offset;
3808 				pval = sdp->isp_devparam[tgt].nvrm_period;
3809 			}
3810 
3811 			cts->protocol = PROTO_SCSI;
3812 			cts->protocol_version = SCSI_REV_2;
3813 			cts->transport = XPORT_SPI;
3814 			cts->transport_version = 2;
3815 
3816 			spi->valid = 0;
3817 			scsi->valid = 0;
3818 			spi->flags = 0;
3819 			scsi->flags = 0;
3820 			if (dval & DPARM_DISC) {
3821 				spi->flags |= CTS_SPI_FLAGS_DISC_ENB;
3822 			}
3823 			if ((dval & DPARM_SYNC) && oval && pval) {
3824 				spi->sync_offset = oval;
3825 				spi->sync_period = pval;
3826 			} else {
3827 				spi->sync_offset = 0;
3828 				spi->sync_period = 0;
3829 			}
3830 			spi->valid |= CTS_SPI_VALID_SYNC_OFFSET;
3831 			spi->valid |= CTS_SPI_VALID_SYNC_RATE;
3832 			spi->valid |= CTS_SPI_VALID_BUS_WIDTH;
3833 			if (dval & DPARM_WIDE) {
3834 				spi->bus_width = MSG_EXT_WDTR_BUS_16_BIT;
3835 			} else {
3836 				spi->bus_width = MSG_EXT_WDTR_BUS_8_BIT;
3837 			}
3838 			if (cts->ccb_h.target_lun != CAM_LUN_WILDCARD) {
3839 				scsi->valid = CTS_SCSI_VALID_TQ;
3840 				if (dval & DPARM_TQING) {
3841 					scsi->flags |= CTS_SCSI_FLAGS_TAG_ENB;
3842 				}
3843 				spi->valid |= CTS_SPI_VALID_DISC;
3844 			}
3845 			isp_prt(isp, ISP_LOGDEBUG0, "GET %s (%d.%d.%jx) to flags %x off %x per %x", IS_CURRENT_SETTINGS(cts)? "ACTIVE" : "NVRAM",
3846 			    bus, tgt, (uintmax_t)cts->ccb_h.target_lun, dval, oval, pval);
3847 		}
3848 		ccb->ccb_h.status = CAM_REQ_CMP;
3849 		xpt_done(ccb);
3850 		break;
3851 
3852 	case XPT_CALC_GEOMETRY:
3853 		cam_calc_geometry(&ccb->ccg, 1);
3854 		xpt_done(ccb);
3855 		break;
3856 
3857 	case XPT_RESET_BUS:		/* Reset the specified bus */
3858 		bus = cam_sim_bus(sim);
3859 		error = isp_control(isp, ISPCTL_RESET_BUS, bus);
3860 		if (error) {
3861 			ccb->ccb_h.status = CAM_REQ_CMP_ERR;
3862 			xpt_done(ccb);
3863 			break;
3864 		}
3865 		if (bootverbose) {
3866 			xpt_print(ccb->ccb_h.path, "reset bus on channel %d\n", bus);
3867 		}
3868 		if (IS_FC(isp)) {
3869 			xpt_async(AC_BUS_RESET, ISP_FC_PC(isp, bus)->path, 0);
3870 		} else {
3871 			xpt_async(AC_BUS_RESET, ISP_SPI_PC(isp, bus)->path, 0);
3872 		}
3873 		ccb->ccb_h.status = CAM_REQ_CMP;
3874 		xpt_done(ccb);
3875 		break;
3876 
3877 	case XPT_TERM_IO:		/* Terminate the I/O process */
3878 		ccb->ccb_h.status = CAM_REQ_INVALID;
3879 		xpt_done(ccb);
3880 		break;
3881 
3882 	case XPT_SET_SIM_KNOB:		/* Set SIM knobs */
3883 	{
3884 		struct ccb_sim_knob *kp = &ccb->knob;
3885 		fcparam *fcp;
3886 
3887 		if (!IS_FC(isp)) {
3888 			ccb->ccb_h.status = CAM_REQ_INVALID;
3889 			xpt_done(ccb);
3890 			break;
3891 		}
3892 
3893 		bus = cam_sim_bus(xpt_path_sim(kp->ccb_h.path));
3894 		fcp = FCPARAM(isp, bus);
3895 
3896 		if (kp->xport_specific.fc.valid & KNOB_VALID_ADDRESS) {
3897 			fcp->isp_wwnn = ISP_FC_PC(isp, bus)->def_wwnn = kp->xport_specific.fc.wwnn;
3898 			fcp->isp_wwpn = ISP_FC_PC(isp, bus)->def_wwpn = kp->xport_specific.fc.wwpn;
3899 			isp_prt(isp, ISP_LOGALL, "Setting Channel %d wwns to 0x%jx 0x%jx", bus, fcp->isp_wwnn, fcp->isp_wwpn);
3900 		}
3901 		ccb->ccb_h.status = CAM_REQ_CMP;
3902 		if (kp->xport_specific.fc.valid & KNOB_VALID_ROLE) {
3903 			int rchange = 0;
3904 			int newrole = 0;
3905 
3906 			switch (kp->xport_specific.fc.role) {
3907 			case KNOB_ROLE_NONE:
3908 				if (fcp->role != ISP_ROLE_NONE) {
3909 					rchange = 1;
3910 					newrole = ISP_ROLE_NONE;
3911 				}
3912 				break;
3913 			case KNOB_ROLE_TARGET:
3914 				if (fcp->role != ISP_ROLE_TARGET) {
3915 					rchange = 1;
3916 					newrole = ISP_ROLE_TARGET;
3917 				}
3918 				break;
3919 			case KNOB_ROLE_INITIATOR:
3920 				if (fcp->role != ISP_ROLE_INITIATOR) {
3921 					rchange = 1;
3922 					newrole = ISP_ROLE_INITIATOR;
3923 				}
3924 				break;
3925 			case KNOB_ROLE_BOTH:
3926 				if (fcp->role != ISP_ROLE_BOTH) {
3927 					rchange = 1;
3928 					newrole = ISP_ROLE_BOTH;
3929 				}
3930 				break;
3931 			}
3932 			if (rchange) {
3933 				ISP_PATH_PRT(isp, ISP_LOGCONFIG, ccb->ccb_h.path, "changing role on from %d to %d\n", fcp->role, newrole);
3934 				if (isp_control(isp, ISPCTL_CHANGE_ROLE,
3935 				    bus, newrole) != 0) {
3936 					ccb->ccb_h.status = CAM_REQ_CMP_ERR;
3937 					xpt_done(ccb);
3938 					break;
3939 				}
3940 			}
3941 		}
3942 		xpt_done(ccb);
3943 		break;
3944 	}
3945 	case XPT_GET_SIM_KNOB:		/* Get SIM knobs */
3946 	{
3947 		struct ccb_sim_knob *kp = &ccb->knob;
3948 
3949 		if (IS_FC(isp)) {
3950 			fcparam *fcp;
3951 
3952 			bus = cam_sim_bus(xpt_path_sim(kp->ccb_h.path));
3953 			fcp = FCPARAM(isp, bus);
3954 
3955 			kp->xport_specific.fc.wwnn = fcp->isp_wwnn;
3956 			kp->xport_specific.fc.wwpn = fcp->isp_wwpn;
3957 			switch (fcp->role) {
3958 			case ISP_ROLE_NONE:
3959 				kp->xport_specific.fc.role = KNOB_ROLE_NONE;
3960 				break;
3961 			case ISP_ROLE_TARGET:
3962 				kp->xport_specific.fc.role = KNOB_ROLE_TARGET;
3963 				break;
3964 			case ISP_ROLE_INITIATOR:
3965 				kp->xport_specific.fc.role = KNOB_ROLE_INITIATOR;
3966 				break;
3967 			case ISP_ROLE_BOTH:
3968 				kp->xport_specific.fc.role = KNOB_ROLE_BOTH;
3969 				break;
3970 			}
3971 			kp->xport_specific.fc.valid = KNOB_VALID_ADDRESS | KNOB_VALID_ROLE;
3972 			ccb->ccb_h.status = CAM_REQ_CMP;
3973 		} else {
3974 			ccb->ccb_h.status = CAM_REQ_INVALID;
3975 		}
3976 		xpt_done(ccb);
3977 		break;
3978 	}
3979 	case XPT_PATH_INQ:		/* Path routing inquiry */
3980 	{
3981 		struct ccb_pathinq *cpi = &ccb->cpi;
3982 
3983 		cpi->version_num = 1;
3984 #ifdef	ISP_TARGET_MODE
3985 		if (IS_FC(isp) && ISP_CAP_TMODE(isp) && ISP_CAP_SCCFW(isp))
3986 			cpi->target_sprt = PIT_PROCESSOR | PIT_DISCONNECT | PIT_TERM_IO;
3987 		else
3988 #endif
3989 			cpi->target_sprt = 0;
3990 		cpi->hba_eng_cnt = 0;
3991 		cpi->max_target = ISP_MAX_TARGETS(isp) - 1;
3992 		cpi->max_lun = ISP_MAX_LUNS(isp) == 0 ?
3993 		    255 : ISP_MAX_LUNS(isp) - 1;
3994 		cpi->bus_id = cam_sim_bus(sim);
3995 		if (isp->isp_osinfo.sixtyfourbit)
3996 			cpi->maxio = (ISP_NSEG64_MAX - 1) * PAGE_SIZE;
3997 		else
3998 			cpi->maxio = (ISP_NSEG_MAX - 1) * PAGE_SIZE;
3999 
4000 		bus = cam_sim_bus(xpt_path_sim(cpi->ccb_h.path));
4001 		if (IS_FC(isp)) {
4002 			fcparam *fcp = FCPARAM(isp, bus);
4003 
4004 			cpi->hba_misc = PIM_NOBUSRESET | PIM_UNMAPPED;
4005 #if __FreeBSD_version >= 1000700
4006 			cpi->hba_misc |= PIM_EXTLUNS;
4007 #endif
4008 #if __FreeBSD_version >= 1000039
4009 			cpi->hba_misc |= PIM_NOSCAN;
4010 #endif
4011 
4012 			/*
4013 			 * Because our loop ID can shift from time to time,
4014 			 * make our initiator ID out of range of our bus.
4015 			 */
4016 			cpi->initiator_id = cpi->max_target + 1;
4017 
4018 			/*
4019 			 * Set base transfer capabilities for Fibre Channel, for this HBA.
4020 			 */
4021 			if (IS_25XX(isp)) {
4022 				cpi->base_transfer_speed = 8000000;
4023 			} else if (IS_24XX(isp)) {
4024 				cpi->base_transfer_speed = 4000000;
4025 			} else if (IS_23XX(isp)) {
4026 				cpi->base_transfer_speed = 2000000;
4027 			} else {
4028 				cpi->base_transfer_speed = 1000000;
4029 			}
4030 			cpi->hba_inquiry = PI_TAG_ABLE;
4031 			cpi->transport = XPORT_FC;
4032 			cpi->transport_version = 0;
4033 			cpi->xport_specific.fc.wwnn = fcp->isp_wwnn;
4034 			cpi->xport_specific.fc.wwpn = fcp->isp_wwpn;
4035 			cpi->xport_specific.fc.port = fcp->isp_portid;
4036 			cpi->xport_specific.fc.bitrate = fcp->isp_gbspeed * 1000;
4037 		} else {
4038 			sdparam *sdp = SDPARAM(isp, bus);
4039 			cpi->hba_inquiry = PI_SDTR_ABLE|PI_TAG_ABLE|PI_WIDE_16;
4040 			cpi->hba_misc = PIM_UNMAPPED;
4041 			cpi->initiator_id = sdp->isp_initiator_id;
4042 			cpi->base_transfer_speed = 3300;
4043 			cpi->transport = XPORT_SPI;
4044 			cpi->transport_version = 2;
4045 		}
4046 		cpi->protocol = PROTO_SCSI;
4047 		cpi->protocol_version = SCSI_REV_2;
4048 		strncpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
4049 		strncpy(cpi->hba_vid, "Qlogic", HBA_IDLEN);
4050 		strncpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
4051 		cpi->unit_number = cam_sim_unit(sim);
4052 		cpi->ccb_h.status = CAM_REQ_CMP;
4053 		xpt_done(ccb);
4054 		break;
4055 	}
4056 	default:
4057 		ccb->ccb_h.status = CAM_REQ_INVALID;
4058 		xpt_done(ccb);
4059 		break;
4060 	}
4061 }
4062 
4063 #define	ISPDDB	(CAM_DEBUG_INFO|CAM_DEBUG_TRACE|CAM_DEBUG_CDB)
4064 
4065 void
4066 isp_done(XS_T *sccb)
4067 {
4068 	ispsoftc_t *isp = XS_ISP(sccb);
4069 	uint32_t status;
4070 
4071 	if (XS_NOERR(sccb))
4072 		XS_SETERR(sccb, CAM_REQ_CMP);
4073 
4074 	if ((sccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP && (sccb->scsi_status != SCSI_STATUS_OK)) {
4075 		sccb->ccb_h.status &= ~CAM_STATUS_MASK;
4076 		if ((sccb->scsi_status == SCSI_STATUS_CHECK_COND) && (sccb->ccb_h.status & CAM_AUTOSNS_VALID) == 0) {
4077 			sccb->ccb_h.status |= CAM_AUTOSENSE_FAIL;
4078 		} else {
4079 			sccb->ccb_h.status |= CAM_SCSI_STATUS_ERROR;
4080 		}
4081 	}
4082 
4083 	sccb->ccb_h.status &= ~CAM_SIM_QUEUED;
4084 	status = sccb->ccb_h.status & CAM_STATUS_MASK;
4085 	if (status != CAM_REQ_CMP) {
4086 		if (status != CAM_SEL_TIMEOUT)
4087 			isp_prt(isp, ISP_LOGDEBUG0,
4088 			    "target %d lun %jx CAM status 0x%x SCSI status 0x%x",
4089 			    XS_TGT(sccb), (uintmax_t)XS_LUN(sccb),
4090 			    sccb->ccb_h.status, sccb->scsi_status);
4091 		else if ((IS_FC(isp))
4092 		      && (XS_TGT(sccb) < MAX_FC_TARG)) {
4093 			fcparam *fcp;
4094 
4095 			fcp = FCPARAM(isp, XS_CHANNEL(sccb));
4096 			fcp->portdb[XS_TGT(sccb)].is_target = 0;
4097 		}
4098 		if ((sccb->ccb_h.status & CAM_DEV_QFRZN) == 0) {
4099 			sccb->ccb_h.status |= CAM_DEV_QFRZN;
4100 			xpt_freeze_devq(sccb->ccb_h.path, 1);
4101 		}
4102 	}
4103 
4104 	if ((CAM_DEBUGGED(sccb->ccb_h.path, ISPDDB)) && (sccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
4105 		xpt_print(sccb->ccb_h.path, "cam completion status 0x%x\n", sccb->ccb_h.status);
4106 	}
4107 
4108 	if (ISP_PCMD(sccb)) {
4109 		if (callout_active(&PISP_PCMD(sccb)->wdog))
4110 			callout_stop(&PISP_PCMD(sccb)->wdog);
4111 		isp_free_pcmd(isp, (union ccb *) sccb);
4112 	}
4113 	xpt_done((union ccb *) sccb);
4114 }
4115 
4116 void
4117 isp_async(ispsoftc_t *isp, ispasync_t cmd, ...)
4118 {
4119 	int bus;
4120 	static const char prom[] = "Chan %d [%d] WWPN 0x%16jx PortID 0x%06x handle 0x%x %s %s";
4121 	char buf[64];
4122 	char *msg = NULL;
4123 	target_id_t tgt;
4124 	fcportdb_t *lp;
4125 	struct isp_fc *fc;
4126 	struct cam_path *tmppath;
4127 	struct ac_contract ac;
4128 	struct ac_device_changed *adc;
4129 	va_list ap;
4130 
4131 	switch (cmd) {
4132 	case ISPASYNC_NEW_TGT_PARAMS:
4133 	{
4134 		struct ccb_trans_settings_scsi *scsi;
4135 		struct ccb_trans_settings_spi *spi;
4136 		int flags, tgt;
4137 		sdparam *sdp;
4138 		struct ccb_trans_settings cts;
4139 
4140 		memset(&cts, 0, sizeof (struct ccb_trans_settings));
4141 
4142 		va_start(ap, cmd);
4143 		bus = va_arg(ap, int);
4144 		tgt = va_arg(ap, int);
4145 		va_end(ap);
4146 		sdp = SDPARAM(isp, bus);
4147 
4148 		if (xpt_create_path(&tmppath, NULL, cam_sim_path(ISP_SPI_PC(isp, bus)->sim), tgt, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
4149 			isp_prt(isp, ISP_LOGWARN, "isp_async cannot make temp path for %d.%d", tgt, bus);
4150 			break;
4151 		}
4152 		flags = sdp->isp_devparam[tgt].actv_flags;
4153 		cts.type = CTS_TYPE_CURRENT_SETTINGS;
4154 		cts.protocol = PROTO_SCSI;
4155 		cts.transport = XPORT_SPI;
4156 
4157 		scsi = &cts.proto_specific.scsi;
4158 		spi = &cts.xport_specific.spi;
4159 
4160 		if (flags & DPARM_TQING) {
4161 			scsi->valid |= CTS_SCSI_VALID_TQ;
4162 			scsi->flags |= CTS_SCSI_FLAGS_TAG_ENB;
4163 		}
4164 
4165 		if (flags & DPARM_DISC) {
4166 			spi->valid |= CTS_SPI_VALID_DISC;
4167 			spi->flags |= CTS_SPI_FLAGS_DISC_ENB;
4168 		}
4169 		spi->flags |= CTS_SPI_VALID_BUS_WIDTH;
4170 		if (flags & DPARM_WIDE) {
4171 			spi->bus_width = MSG_EXT_WDTR_BUS_16_BIT;
4172 		} else {
4173 			spi->bus_width = MSG_EXT_WDTR_BUS_8_BIT;
4174 		}
4175 		if (flags & DPARM_SYNC) {
4176 			spi->valid |= CTS_SPI_VALID_SYNC_RATE;
4177 			spi->valid |= CTS_SPI_VALID_SYNC_OFFSET;
4178 			spi->sync_period = sdp->isp_devparam[tgt].actv_period;
4179 			spi->sync_offset = sdp->isp_devparam[tgt].actv_offset;
4180 		}
4181 		isp_prt(isp, ISP_LOGDEBUG2, "NEW_TGT_PARAMS bus %d tgt %d period %x offset %x flags %x", bus, tgt, sdp->isp_devparam[tgt].actv_period, sdp->isp_devparam[tgt].actv_offset, flags);
4182 		xpt_setup_ccb(&cts.ccb_h, tmppath, 1);
4183 		xpt_async(AC_TRANSFER_NEG, tmppath, &cts);
4184 		xpt_free_path(tmppath);
4185 		break;
4186 	}
4187 	case ISPASYNC_BUS_RESET:
4188 	{
4189 		va_start(ap, cmd);
4190 		bus = va_arg(ap, int);
4191 		va_end(ap);
4192 		isp_prt(isp, ISP_LOGINFO, "SCSI bus reset on bus %d detected", bus);
4193 		if (IS_FC(isp)) {
4194 			xpt_async(AC_BUS_RESET, ISP_FC_PC(isp, bus)->path, NULL);
4195 		} else {
4196 			xpt_async(AC_BUS_RESET, ISP_SPI_PC(isp, bus)->path, NULL);
4197 		}
4198 		break;
4199 	}
4200 	case ISPASYNC_LIP:
4201 		if (msg == NULL)
4202 			msg = "LIP Received";
4203 		/* FALLTHROUGH */
4204 	case ISPASYNC_LOOP_RESET:
4205 		if (msg == NULL)
4206 			msg = "LOOP Reset";
4207 		/* FALLTHROUGH */
4208 	case ISPASYNC_LOOP_DOWN:
4209 		if (msg == NULL)
4210 			msg = "LOOP Down";
4211 		va_start(ap, cmd);
4212 		bus = va_arg(ap, int);
4213 		va_end(ap);
4214 		isp_fcp_reset_crn(isp, bus, /*tgt*/0, /*tgt_set*/ 0);
4215 		isp_loop_changed(isp, bus);
4216 		isp_prt(isp, ISP_LOGINFO, "Chan %d %s", bus, msg);
4217 		break;
4218 	case ISPASYNC_LOOP_UP:
4219 		va_start(ap, cmd);
4220 		bus = va_arg(ap, int);
4221 		va_end(ap);
4222 		isp_loop_changed(isp, bus);
4223 		isp_prt(isp, ISP_LOGINFO, "Chan %d Loop UP", bus);
4224 		break;
4225 	case ISPASYNC_DEV_ARRIVED:
4226 		va_start(ap, cmd);
4227 		bus = va_arg(ap, int);
4228 		lp = va_arg(ap, fcportdb_t *);
4229 		va_end(ap);
4230 		fc = ISP_FC_PC(isp, bus);
4231 		tgt = FC_PORTDB_TGT(isp, bus, lp);
4232 		isp_gen_role_str(buf, sizeof (buf), lp->prli_word3);
4233 		isp_prt(isp, ISP_LOGCONFIG, prom, bus, tgt, lp->port_wwn, lp->portid, lp->handle, buf, "arrived");
4234 		if ((FCPARAM(isp, bus)->role & ISP_ROLE_INITIATOR) &&
4235 		    (lp->prli_word3 & PRLI_WD3_TARGET_FUNCTION)) {
4236 			lp->is_target = 1;
4237 			isp_fcp_reset_crn(isp, bus, tgt, /*tgt_set*/ 1);
4238 			isp_make_here(isp, lp, bus, tgt);
4239 		}
4240 		if ((FCPARAM(isp, bus)->role & ISP_ROLE_TARGET) &&
4241 		    (lp->prli_word3 & PRLI_WD3_INITIATOR_FUNCTION)) {
4242 			lp->is_initiator = 1;
4243 			ac.contract_number = AC_CONTRACT_DEV_CHG;
4244 			adc = (struct ac_device_changed *) ac.contract_data;
4245 			adc->wwpn = lp->port_wwn;
4246 			adc->port = lp->portid;
4247 			adc->target = tgt;
4248 			adc->arrived = 1;
4249 			xpt_async(AC_CONTRACT, fc->path, &ac);
4250 		}
4251 		break;
4252 	case ISPASYNC_DEV_CHANGED:
4253 		va_start(ap, cmd);
4254 		bus = va_arg(ap, int);
4255 		lp = va_arg(ap, fcportdb_t *);
4256 		va_end(ap);
4257 		fc = ISP_FC_PC(isp, bus);
4258 		tgt = FC_PORTDB_TGT(isp, bus, lp);
4259 		isp_gen_role_str(buf, sizeof (buf), lp->new_prli_word3);
4260 		isp_prt(isp, ISP_LOGCONFIG, prom, bus, tgt, lp->port_wwn, lp->new_portid, lp->handle, buf, "changed");
4261 changed:
4262 		if (lp->is_target !=
4263 		    ((FCPARAM(isp, bus)->role & ISP_ROLE_INITIATOR) &&
4264 		     (lp->new_prli_word3 & PRLI_WD3_TARGET_FUNCTION))) {
4265 			lp->is_target = !lp->is_target;
4266 			if (lp->is_target) {
4267 				isp_fcp_reset_crn(isp, bus, tgt, /*tgt_set*/ 1);
4268 				isp_make_here(isp, lp, bus, tgt);
4269 			} else {
4270 				isp_make_gone(isp, lp, bus, tgt);
4271 				isp_fcp_reset_crn(isp, bus, tgt, /*tgt_set*/ 1);
4272 			}
4273 		}
4274 		if (lp->is_initiator !=
4275 		    ((FCPARAM(isp, bus)->role & ISP_ROLE_TARGET) &&
4276 		     (lp->new_prli_word3 & PRLI_WD3_INITIATOR_FUNCTION))) {
4277 			lp->is_initiator = !lp->is_initiator;
4278 			ac.contract_number = AC_CONTRACT_DEV_CHG;
4279 			adc = (struct ac_device_changed *) ac.contract_data;
4280 			adc->wwpn = lp->port_wwn;
4281 			adc->port = lp->portid;
4282 			adc->target = tgt;
4283 			adc->arrived = lp->is_initiator;
4284 			xpt_async(AC_CONTRACT, fc->path, &ac);
4285 		}
4286 		break;
4287 	case ISPASYNC_DEV_STAYED:
4288 		va_start(ap, cmd);
4289 		bus = va_arg(ap, int);
4290 		lp = va_arg(ap, fcportdb_t *);
4291 		va_end(ap);
4292 		fc = ISP_FC_PC(isp, bus);
4293 		tgt = FC_PORTDB_TGT(isp, bus, lp);
4294 		isp_gen_role_str(buf, sizeof (buf), lp->prli_word3);
4295 		isp_prt(isp, ISP_LOGCONFIG, prom, bus, tgt, lp->port_wwn, lp->portid, lp->handle, buf, "stayed");
4296 		goto changed;
4297 	case ISPASYNC_DEV_GONE:
4298 		va_start(ap, cmd);
4299 		bus = va_arg(ap, int);
4300 		lp = va_arg(ap, fcportdb_t *);
4301 		va_end(ap);
4302 		fc = ISP_FC_PC(isp, bus);
4303 		tgt = FC_PORTDB_TGT(isp, bus, lp);
4304 		/*
4305 		 * If this has a virtual target or initiator set the isp_gdt
4306 		 * timer running on it to delay its departure.
4307 		 */
4308 		isp_gen_role_str(buf, sizeof (buf), lp->prli_word3);
4309 		if (lp->is_target || lp->is_initiator) {
4310 			lp->state = FC_PORTDB_STATE_ZOMBIE;
4311 			lp->gone_timer = fc->gone_device_time;
4312 			isp_prt(isp, ISP_LOGCONFIG, prom, bus, tgt, lp->port_wwn, lp->portid, lp->handle, buf, "gone zombie");
4313 			if (fc->ready && !callout_active(&fc->gdt)) {
4314 				isp_prt(isp, ISP_LOG_SANCFG|ISP_LOGDEBUG0, "Chan %d Starting Gone Device Timer with %u seconds time now %lu", bus, lp->gone_timer, (unsigned long)time_uptime);
4315 				callout_reset(&fc->gdt, hz, isp_gdt, fc);
4316 			}
4317 			break;
4318 		}
4319 		isp_prt(isp, ISP_LOGCONFIG, prom, bus, tgt, lp->port_wwn, lp->portid, lp->handle, buf, "gone");
4320 		break;
4321 	case ISPASYNC_CHANGE_NOTIFY:
4322 	{
4323 		char *msg;
4324 		int evt, nphdl, nlstate, portid, reason;
4325 
4326 		va_start(ap, cmd);
4327 		bus = va_arg(ap, int);
4328 		evt = va_arg(ap, int);
4329 		if (evt == ISPASYNC_CHANGE_PDB) {
4330 			nphdl = va_arg(ap, int);
4331 			nlstate = va_arg(ap, int);
4332 			reason = va_arg(ap, int);
4333 		} else if (evt == ISPASYNC_CHANGE_SNS) {
4334 			portid = va_arg(ap, int);
4335 		} else {
4336 			nphdl = NIL_HANDLE;
4337 			nlstate = reason = 0;
4338 		}
4339 		va_end(ap);
4340 		fc = ISP_FC_PC(isp, bus);
4341 
4342 		if (evt == ISPASYNC_CHANGE_PDB) {
4343 			msg = "Port Database Changed";
4344 			isp_prt(isp, ISP_LOGINFO,
4345 			    "Chan %d %s (nphdl 0x%x state 0x%x reason 0x%x)",
4346 			    bus, msg, nphdl, nlstate, reason);
4347 		} else if (evt == ISPASYNC_CHANGE_SNS) {
4348 			msg = "Name Server Database Changed";
4349 			isp_prt(isp, ISP_LOGINFO, "Chan %d %s (PortID 0x%06x)",
4350 			    bus, msg, portid);
4351 		} else {
4352 			msg = "Other Change Notify";
4353 			isp_prt(isp, ISP_LOGINFO, "Chan %d %s", bus, msg);
4354 		}
4355 		isp_loop_changed(isp, bus);
4356 		break;
4357 	}
4358 #ifdef	ISP_TARGET_MODE
4359 	case ISPASYNC_TARGET_NOTIFY:
4360 	{
4361 		isp_notify_t *notify;
4362 		va_start(ap, cmd);
4363 		notify = va_arg(ap, isp_notify_t *);
4364 		va_end(ap);
4365 		switch (notify->nt_ncode) {
4366 		case NT_ABORT_TASK:
4367 		case NT_ABORT_TASK_SET:
4368 		case NT_CLEAR_ACA:
4369 		case NT_CLEAR_TASK_SET:
4370 		case NT_LUN_RESET:
4371 		case NT_TARGET_RESET:
4372 		case NT_QUERY_TASK_SET:
4373 		case NT_QUERY_ASYNC_EVENT:
4374 			/*
4375 			 * These are task management functions.
4376 			 */
4377 			isp_handle_platform_target_tmf(isp, notify);
4378 			break;
4379 		case NT_BUS_RESET:
4380 		case NT_LIP_RESET:
4381 		case NT_LINK_UP:
4382 		case NT_LINK_DOWN:
4383 		case NT_HBA_RESET:
4384 			/*
4385 			 * No action need be taken here.
4386 			 */
4387 			break;
4388 		case NT_GLOBAL_LOGOUT:
4389 		case NT_LOGOUT:
4390 			/*
4391 			 * This is device arrival/departure notification
4392 			 */
4393 			isp_handle_platform_target_notify_ack(isp, notify);
4394 			break;
4395 		default:
4396 			isp_prt(isp, ISP_LOGALL, "target notify code 0x%x", notify->nt_ncode);
4397 			isp_handle_platform_target_notify_ack(isp, notify);
4398 			break;
4399 		}
4400 		break;
4401 	}
4402 	case ISPASYNC_TARGET_NOTIFY_ACK:
4403 	{
4404 		void *inot;
4405 		va_start(ap, cmd);
4406 		inot = va_arg(ap, void *);
4407 		va_end(ap);
4408 		if (isp_notify_ack(isp, inot)) {
4409 			isp_tna_t *tp = malloc(sizeof (*tp), M_DEVBUF, M_NOWAIT);
4410 			if (tp) {
4411 				tp->isp = isp;
4412 				if (inot) {
4413 					memcpy(tp->data, inot, sizeof (tp->data));
4414 					tp->not = tp->data;
4415 				} else {
4416 					tp->not = NULL;
4417 				}
4418 				callout_init_mtx(&tp->timer, &isp->isp_lock, 0);
4419 				callout_reset(&tp->timer, 5,
4420 				    isp_refire_notify_ack, tp);
4421 			} else {
4422 				isp_prt(isp, ISP_LOGERR, "you lose- cannot allocate a notify refire");
4423 			}
4424 		}
4425 		break;
4426 	}
4427 	case ISPASYNC_TARGET_ACTION:
4428 	{
4429 		isphdr_t *hp;
4430 
4431 		va_start(ap, cmd);
4432 		hp = va_arg(ap, isphdr_t *);
4433 		va_end(ap);
4434 		switch (hp->rqs_entry_type) {
4435 		default:
4436 			isp_prt(isp, ISP_LOGWARN, "%s: unhandled target action 0x%x", __func__, hp->rqs_entry_type);
4437 			break;
4438 		case RQSTYPE_NOTIFY:
4439 			if (IS_24XX(isp)) {
4440 				isp_handle_platform_notify_24xx(isp, (in_fcentry_24xx_t *) hp);
4441 			} else {
4442 				isp_handle_platform_notify_fc(isp, (in_fcentry_t *) hp);
4443 			}
4444 			break;
4445 		case RQSTYPE_ATIO:
4446 			isp_handle_platform_atio7(isp, (at7_entry_t *) hp);
4447 			break;
4448 		case RQSTYPE_ATIO2:
4449 			isp_handle_platform_atio2(isp, (at2_entry_t *) hp);
4450 			break;
4451 		case RQSTYPE_CTIO7:
4452 		case RQSTYPE_CTIO3:
4453 		case RQSTYPE_CTIO2:
4454 		case RQSTYPE_CTIO:
4455 			isp_handle_platform_ctio(isp, hp);
4456 			break;
4457 		case RQSTYPE_ABTS_RCVD:
4458 		{
4459 			abts_t *abts = (abts_t *)hp;
4460 			isp_notify_t notify, *nt = &notify;
4461 			tstate_t *tptr;
4462 			fcportdb_t *lp;
4463 			uint16_t chan;
4464 			uint32_t sid, did;
4465 
4466 			did = (abts->abts_did_hi << 16) | abts->abts_did_lo;
4467 			sid = (abts->abts_sid_hi << 16) | abts->abts_sid_lo;
4468 			ISP_MEMZERO(nt, sizeof (isp_notify_t));
4469 
4470 			nt->nt_hba = isp;
4471 			nt->nt_did = did;
4472 			nt->nt_nphdl = abts->abts_nphdl;
4473 			nt->nt_sid = sid;
4474 			isp_find_chan_by_did(isp, did, &chan);
4475 			if (chan == ISP_NOCHAN) {
4476 				nt->nt_tgt = TGT_ANY;
4477 			} else {
4478 				nt->nt_tgt = FCPARAM(isp, chan)->isp_wwpn;
4479 				if (isp_find_pdb_by_handle(isp, chan, abts->abts_nphdl, &lp)) {
4480 					nt->nt_wwn = lp->port_wwn;
4481 				} else {
4482 					nt->nt_wwn = INI_ANY;
4483 				}
4484 			}
4485 			/*
4486 			 * Try hard to find the lun for this command.
4487 			 */
4488 			tptr = get_lun_statep_from_tag(isp, chan, abts->abts_rxid_task);
4489 			if (tptr) {
4490 				nt->nt_lun = tptr->ts_lun;
4491 				rls_lun_statep(isp, tptr);
4492 			} else {
4493 				nt->nt_lun = LUN_ANY;
4494 			}
4495 			nt->nt_need_ack = 1;
4496 			nt->nt_tagval = abts->abts_rxid_task;
4497 			nt->nt_tagval |= (((uint64_t) abts->abts_rxid_abts) << 32);
4498 			if (abts->abts_rxid_task == ISP24XX_NO_TASK) {
4499 				isp_prt(isp, ISP_LOGTINFO, "[0x%x] ABTS from N-Port handle 0x%x Port 0x%06x has no task id (rx_id 0x%04x ox_id 0x%04x)",
4500 				    abts->abts_rxid_abts, abts->abts_nphdl, sid, abts->abts_rx_id, abts->abts_ox_id);
4501 			} else {
4502 				isp_prt(isp, ISP_LOGTINFO, "[0x%x] ABTS from N-Port handle 0x%x Port 0x%06x for task 0x%x (rx_id 0x%04x ox_id 0x%04x)",
4503 				    abts->abts_rxid_abts, abts->abts_nphdl, sid, abts->abts_rxid_task, abts->abts_rx_id, abts->abts_ox_id);
4504 			}
4505 			nt->nt_channel = chan;
4506 			nt->nt_ncode = NT_ABORT_TASK;
4507 			nt->nt_lreserved = hp;
4508 			isp_handle_platform_target_tmf(isp, nt);
4509 			break;
4510 		}
4511 		}
4512 		break;
4513 	}
4514 #endif
4515 	case ISPASYNC_FW_CRASH:
4516 	{
4517 		uint16_t mbox1, mbox6;
4518 		mbox1 = ISP_READ(isp, OUTMAILBOX1);
4519 		if (IS_DUALBUS(isp)) {
4520 			mbox6 = ISP_READ(isp, OUTMAILBOX6);
4521 		} else {
4522 			mbox6 = 0;
4523 		}
4524 		isp_prt(isp, ISP_LOGERR, "Internal Firmware Error on bus %d @ RISC Address 0x%x", mbox6, mbox1);
4525 		mbox1 = isp->isp_osinfo.mbox_sleep_ok;
4526 		isp->isp_osinfo.mbox_sleep_ok = 0;
4527 		isp_reinit(isp, 1);
4528 		isp->isp_osinfo.mbox_sleep_ok = mbox1;
4529 		isp_async(isp, ISPASYNC_FW_RESTARTED, NULL);
4530 		break;
4531 	}
4532 	default:
4533 		isp_prt(isp, ISP_LOGERR, "unknown isp_async event %d", cmd);
4534 		break;
4535 	}
4536 }
4537 
4538 
4539 /*
4540  * Locks are held before coming here.
4541  */
4542 void
4543 isp_uninit(ispsoftc_t *isp)
4544 {
4545 	if (IS_24XX(isp)) {
4546 		ISP_WRITE(isp, BIU2400_HCCR, HCCR_2400_CMD_RESET);
4547 	} else {
4548 		ISP_WRITE(isp, HCCR, HCCR_CMD_RESET);
4549 	}
4550 	ISP_DISABLE_INTS(isp);
4551 }
4552 
4553 /*
4554  * When we want to get the 'default' WWNs (when lacking NVRAM), we pick them
4555  * up from our platform default (defww{p|n}n) and morph them based upon
4556  * channel.
4557  *
4558  * When we want to get the 'active' WWNs, we get NVRAM WWNs and then morph them
4559  * based upon channel.
4560  */
4561 
4562 uint64_t
4563 isp_default_wwn(ispsoftc_t * isp, int chan, int isactive, int iswwnn)
4564 {
4565 	uint64_t seed;
4566 	struct isp_fc *fc = ISP_FC_PC(isp, chan);
4567 
4568 	/*
4569 	 * If we're asking for a active WWN, the default overrides get
4570 	 * returned, otherwise the NVRAM value is picked.
4571 	 *
4572 	 * If we're asking for a default WWN, we just pick the default override.
4573 	 */
4574 	if (isactive) {
4575 		seed = iswwnn ? fc->def_wwnn : fc->def_wwpn;
4576 		if (seed) {
4577 			return (seed);
4578 		}
4579 		seed = iswwnn ? FCPARAM(isp, chan)->isp_wwnn_nvram : FCPARAM(isp, chan)->isp_wwpn_nvram;
4580 		if (seed) {
4581 			return (seed);
4582 		}
4583 		return (0x400000007F000009ull);
4584 	}
4585 
4586 	seed = iswwnn ? fc->def_wwnn : fc->def_wwpn;
4587 
4588 	/*
4589 	 * For channel zero just return what we have. For either ACTIVE or
4590 	 * DEFAULT cases, we depend on default override of NVRAM values for
4591 	 * channel zero.
4592 	 */
4593 	if (chan == 0) {
4594 		return (seed);
4595 	}
4596 
4597 	/*
4598 	 * For other channels, we are doing one of three things:
4599 	 *
4600 	 * 1. If what we have now is non-zero, return it. Otherwise we morph
4601 	 * values from channel 0. 2. If we're here for a WWPN we synthesize
4602 	 * it if Channel 0's wwpn has a type 2 NAA. 3. If we're here for a
4603 	 * WWNN we synthesize it if Channel 0's wwnn has a type 2 NAA.
4604 	 */
4605 
4606 	if (seed) {
4607 		return (seed);
4608 	}
4609 	seed = iswwnn ? ISP_FC_PC(isp, 0)->def_wwnn : ISP_FC_PC(isp, 0)->def_wwpn;
4610 	if (seed == 0)
4611 		seed = iswwnn ? FCPARAM(isp, 0)->isp_wwnn_nvram : FCPARAM(isp, 0)->isp_wwpn_nvram;
4612 
4613 	if (((seed >> 60) & 0xf) == 2) {
4614 		/*
4615 		 * The type 2 NAA fields for QLogic cards appear be laid out
4616 		 * thusly:
4617 		 *
4618 		 * bits 63..60 NAA == 2 bits 59..57 unused/zero bit 56
4619 		 * port (1) or node (0) WWN distinguishor bit 48
4620 		 * physical port on dual-port chips (23XX/24XX)
4621 		 *
4622 		 * This is somewhat nutty, particularly since bit 48 is
4623 		 * irrelevant as they assign separate serial numbers to
4624 		 * different physical ports anyway.
4625 		 *
4626 		 * We'll stick our channel number plus one first into bits
4627 		 * 57..59 and thence into bits 52..55 which allows for 8 bits
4628 		 * of channel which is comfortably more than our maximum
4629 		 * (126) now.
4630 		 */
4631 		seed &= ~0x0FF0000000000000ULL;
4632 		if (iswwnn == 0) {
4633 			seed |= ((uint64_t) (chan + 1) & 0xf) << 56;
4634 			seed |= ((uint64_t) ((chan + 1) >> 4) & 0xf) << 52;
4635 		}
4636 	} else {
4637 		seed = 0;
4638 	}
4639 	return (seed);
4640 }
4641 
4642 void
4643 isp_prt(ispsoftc_t *isp, int level, const char *fmt, ...)
4644 {
4645 	int loc;
4646 	char lbuf[200];
4647 	va_list ap;
4648 
4649 	if (level != ISP_LOGALL && (level & isp->isp_dblev) == 0) {
4650 		return;
4651 	}
4652 	snprintf(lbuf, sizeof (lbuf), "%s: ", device_get_nameunit(isp->isp_dev));
4653 	loc = strlen(lbuf);
4654 	va_start(ap, fmt);
4655 	vsnprintf(&lbuf[loc], sizeof (lbuf) - loc - 1, fmt, ap);
4656 	va_end(ap);
4657 	printf("%s\n", lbuf);
4658 }
4659 
4660 void
4661 isp_xs_prt(ispsoftc_t *isp, XS_T *xs, int level, const char *fmt, ...)
4662 {
4663 	va_list ap;
4664 	if (level != ISP_LOGALL && (level & isp->isp_dblev) == 0) {
4665 		return;
4666 	}
4667 	xpt_print_path(xs->ccb_h.path);
4668 	va_start(ap, fmt);
4669 	vprintf(fmt, ap);
4670 	va_end(ap);
4671 	printf("\n");
4672 }
4673 
4674 uint64_t
4675 isp_nanotime_sub(struct timespec *b, struct timespec *a)
4676 {
4677 	uint64_t elapsed;
4678 	struct timespec x = *b;
4679 	timespecsub(&x, a);
4680 	elapsed = GET_NANOSEC(&x);
4681 	if (elapsed == 0)
4682 		elapsed++;
4683 	return (elapsed);
4684 }
4685 
4686 int
4687 isp_mbox_acquire(ispsoftc_t *isp)
4688 {
4689 	if (isp->isp_osinfo.mboxbsy) {
4690 		return (1);
4691 	} else {
4692 		isp->isp_osinfo.mboxcmd_done = 0;
4693 		isp->isp_osinfo.mboxbsy = 1;
4694 		return (0);
4695 	}
4696 }
4697 
4698 void
4699 isp_mbox_wait_complete(ispsoftc_t *isp, mbreg_t *mbp)
4700 {
4701 	unsigned int usecs = mbp->timeout;
4702 	unsigned int max, olim, ilim;
4703 
4704 	if (usecs == 0) {
4705 		usecs = MBCMD_DEFAULT_TIMEOUT;
4706 	}
4707 	max = isp->isp_mbxwrk0 + 1;
4708 
4709 	if (isp->isp_osinfo.mbox_sleep_ok) {
4710 		unsigned int ms = (usecs + 999) / 1000;
4711 
4712 		isp->isp_osinfo.mbox_sleep_ok = 0;
4713 		isp->isp_osinfo.mbox_sleeping = 1;
4714 		for (olim = 0; olim < max; olim++) {
4715 			msleep(&isp->isp_mbxworkp, &isp->isp_osinfo.lock, PRIBIO, "ispmbx_sleep", isp_mstohz(ms));
4716 			if (isp->isp_osinfo.mboxcmd_done) {
4717 				break;
4718 			}
4719 		}
4720 		isp->isp_osinfo.mbox_sleep_ok = 1;
4721 		isp->isp_osinfo.mbox_sleeping = 0;
4722 	} else {
4723 		for (olim = 0; olim < max; olim++) {
4724 			for (ilim = 0; ilim < usecs; ilim += 100) {
4725 				uint16_t isr, sema, info;
4726 				if (isp->isp_osinfo.mboxcmd_done) {
4727 					break;
4728 				}
4729 				if (ISP_READ_ISR(isp, &isr, &sema, &info)) {
4730 					isp_intr(isp, isr, sema, info);
4731 					if (isp->isp_osinfo.mboxcmd_done) {
4732 						break;
4733 					}
4734 				}
4735 				ISP_DELAY(100);
4736 			}
4737 			if (isp->isp_osinfo.mboxcmd_done) {
4738 				break;
4739 			}
4740 		}
4741 	}
4742 	if (isp->isp_osinfo.mboxcmd_done == 0) {
4743 		isp_prt(isp, ISP_LOGWARN, "%s Mailbox Command (0x%x) Timeout (%uus) (started @ %s:%d)",
4744 		    isp->isp_osinfo.mbox_sleep_ok? "Interrupting" : "Polled", isp->isp_lastmbxcmd, usecs, mbp->func, mbp->lineno);
4745 		mbp->param[0] = MBOX_TIMEOUT;
4746 		isp->isp_osinfo.mboxcmd_done = 1;
4747 	}
4748 }
4749 
4750 void
4751 isp_mbox_notify_done(ispsoftc_t *isp)
4752 {
4753 	if (isp->isp_osinfo.mbox_sleeping) {
4754 		wakeup(&isp->isp_mbxworkp);
4755 	}
4756 	isp->isp_osinfo.mboxcmd_done = 1;
4757 }
4758 
4759 void
4760 isp_mbox_release(ispsoftc_t *isp)
4761 {
4762 	isp->isp_osinfo.mboxbsy = 0;
4763 }
4764 
4765 int
4766 isp_fc_scratch_acquire(ispsoftc_t *isp, int chan)
4767 {
4768 	int ret = 0;
4769 	if (isp->isp_osinfo.pc.fc[chan].fcbsy) {
4770 		ret = -1;
4771 	} else {
4772 		isp->isp_osinfo.pc.fc[chan].fcbsy = 1;
4773 	}
4774 	return (ret);
4775 }
4776 
4777 int
4778 isp_mstohz(int ms)
4779 {
4780 	int hz;
4781 	struct timeval t;
4782 	t.tv_sec = ms / 1000;
4783 	t.tv_usec = (ms % 1000) * 1000;
4784 	hz = tvtohz(&t);
4785 	if (hz < 0) {
4786 		hz = 0x7fffffff;
4787 	}
4788 	if (hz == 0) {
4789 		hz = 1;
4790 	}
4791 	return (hz);
4792 }
4793 
4794 void
4795 isp_platform_intr(void *arg)
4796 {
4797 	ispsoftc_t *isp = arg;
4798 	uint16_t isr, sema, info;
4799 
4800 	ISP_LOCK(isp);
4801 	isp->isp_intcnt++;
4802 	if (ISP_READ_ISR(isp, &isr, &sema, &info))
4803 		isp_intr(isp, isr, sema, info);
4804 	else
4805 		isp->isp_intbogus++;
4806 	ISP_UNLOCK(isp);
4807 }
4808 
4809 void
4810 isp_common_dmateardown(ispsoftc_t *isp, struct ccb_scsiio *csio, uint32_t hdl)
4811 {
4812 	if ((csio->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
4813 		bus_dmamap_sync(isp->isp_osinfo.dmat, PISP_PCMD(csio)->dmap, BUS_DMASYNC_POSTREAD);
4814 	} else {
4815 		bus_dmamap_sync(isp->isp_osinfo.dmat, PISP_PCMD(csio)->dmap, BUS_DMASYNC_POSTWRITE);
4816 	}
4817 	bus_dmamap_unload(isp->isp_osinfo.dmat, PISP_PCMD(csio)->dmap);
4818 }
4819 
4820 /*
4821  * Reset the command reference number for all LUNs on a specific target
4822  * (needed when a target arrives again) or for all targets on a port
4823  * (needed for events like a LIP).
4824  */
4825 void
4826 isp_fcp_reset_crn(ispsoftc_t *isp, int chan, uint32_t tgt, int tgt_set)
4827 {
4828 	struct isp_fc *fc = ISP_FC_PC(isp, chan);
4829 	struct isp_nexus *nxp;
4830 	int i;
4831 
4832 	if (tgt_set == 0)
4833 		isp_prt(isp, ISP_LOGDEBUG0,
4834 		    "Chan %d resetting CRN on all targets", chan);
4835 	else
4836 		isp_prt(isp, ISP_LOGDEBUG0,
4837 		    "Chan %d resetting CRN on target %u", chan, tgt);
4838 
4839 	for (i = 0; i < NEXUS_HASH_WIDTH; i++) {
4840 		for (nxp = fc->nexus_hash[i]; nxp != NULL; nxp = nxp->next) {
4841 			if (tgt_set == 0 || tgt == nxp->tgt)
4842 				nxp->crnseed = 0;
4843 		}
4844 	}
4845 }
4846 
4847 int
4848 isp_fcp_next_crn(ispsoftc_t *isp, uint8_t *crnp, XS_T *cmd)
4849 {
4850 	lun_id_t lun;
4851 	uint32_t chan, tgt;
4852 	struct isp_fc *fc;
4853 	struct isp_nexus *nxp;
4854 	int idx;
4855 
4856 	if (IS_2100(isp))
4857 		return (0);
4858 
4859 	chan = XS_CHANNEL(cmd);
4860 	tgt = XS_TGT(cmd);
4861 	lun = XS_LUN(cmd);
4862 	fc = &isp->isp_osinfo.pc.fc[chan];
4863 	idx = NEXUS_HASH(tgt, lun);
4864 	nxp = fc->nexus_hash[idx];
4865 
4866 	while (nxp) {
4867 		if (nxp->tgt == tgt && nxp->lun == lun)
4868 			break;
4869 		nxp = nxp->next;
4870 	}
4871 	if (nxp == NULL) {
4872 		nxp = fc->nexus_free_list;
4873 		if (nxp == NULL) {
4874 			nxp = malloc(sizeof (struct isp_nexus), M_DEVBUF, M_ZERO|M_NOWAIT);
4875 			if (nxp == NULL) {
4876 				return (-1);
4877 			}
4878 		} else {
4879 			fc->nexus_free_list = nxp->next;
4880 		}
4881 		nxp->tgt = tgt;
4882 		nxp->lun = lun;
4883 		nxp->next = fc->nexus_hash[idx];
4884 		fc->nexus_hash[idx] = nxp;
4885 	}
4886 	if (nxp->crnseed == 0)
4887 		nxp->crnseed = 1;
4888 	PISP_PCMD(cmd)->crn = nxp->crnseed;
4889 	*crnp = nxp->crnseed++;
4890 	return (0);
4891 }
4892 
4893 /*
4894  * We enter with the lock held
4895  */
4896 void
4897 isp_timer(void *arg)
4898 {
4899 	ispsoftc_t *isp = arg;
4900 #ifdef	ISP_TARGET_MODE
4901 	isp_tmcmd_restart(isp);
4902 #endif
4903 	callout_reset(&isp->isp_osinfo.tmo, isp_timer_count, isp_timer, isp);
4904 }
4905 
4906 isp_ecmd_t *
4907 isp_get_ecmd(ispsoftc_t *isp)
4908 {
4909 	isp_ecmd_t *ecmd = isp->isp_osinfo.ecmd_free;
4910 	if (ecmd) {
4911 		isp->isp_osinfo.ecmd_free = ecmd->next;
4912 	}
4913 	return (ecmd);
4914 }
4915 
4916 void
4917 isp_put_ecmd(ispsoftc_t *isp, isp_ecmd_t *ecmd)
4918 {
4919 	ecmd->next = isp->isp_osinfo.ecmd_free;
4920 	isp->isp_osinfo.ecmd_free = ecmd;
4921 }
4922