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