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