xref: /freebsd/sys/dev/isp/isp_freebsd.c (revision d4ae33f0721c1b170fe37d97e395228ffcfb3f80)
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 #include <dev/isp/isp_freebsd.h>
33 #include <sys/unistd.h>
34 #include <sys/kthread.h>
35 #include <sys/conf.h>
36 #include <sys/module.h>
37 #include <sys/ioccom.h>
38 #include <dev/isp/isp_ioctl.h>
39 #include <sys/devicestat.h>
40 #include <cam/cam_periph.h>
41 #include <cam/cam_xpt_periph.h>
42 
43 #if	__FreeBSD_version < 800002
44 #define	THREAD_CREATE	kthread_create
45 #else
46 #define	THREAD_CREATE	kproc_create
47 #endif
48 
49 MODULE_VERSION(isp, 1);
50 MODULE_DEPEND(isp, cam, 1, 1, 1);
51 int isp_announced = 0;
52 int isp_fabric_hysteresis = 5;
53 int isp_loop_down_limit = 60;	/* default loop down limit */
54 int isp_change_is_bad = 0;	/* "changed" devices are bad */
55 int isp_quickboot_time = 7;	/* don't wait more than N secs for loop up */
56 int isp_gone_device_time = 30;	/* grace time before reporting device lost */
57 int isp_autoconfig = 1;		/* automatically attach/detach devices */
58 static const char prom3[] = "Chan %d PortID 0x%06x Departed from Target %u because of %s";
59 static const char rqo[] = "%s: Request Queue Overflow\n";
60 
61 static void isp_freeze_loopdown(ispsoftc_t *, int, char *);
62 static d_ioctl_t ispioctl;
63 static void isp_intr_enable(void *);
64 static void isp_cam_async(void *, uint32_t, struct cam_path *, void *);
65 static void isp_poll(struct cam_sim *);
66 static timeout_t isp_watchdog;
67 static timeout_t isp_gdt;
68 static task_fn_t isp_gdt_task;
69 static timeout_t isp_ldt;
70 static task_fn_t isp_ldt_task;
71 static void isp_kthread(void *);
72 static void isp_action(struct cam_sim *, union ccb *);
73 #ifdef	ISP_INTERNAL_TARGET
74 static void isp_target_thread_pi(void *);
75 static void isp_target_thread_fc(void *);
76 #endif
77 static int isp_timer_count;
78 static void isp_timer(void *);
79 
80 static struct cdevsw isp_cdevsw = {
81 	.d_version =	D_VERSION,
82 	.d_ioctl =	ispioctl,
83 	.d_name =	"isp",
84 };
85 
86 static int
87 isp_attach_chan(ispsoftc_t *isp, struct cam_devq *devq, int chan)
88 {
89 	struct ccb_setasync csa;
90 	struct cam_sim *sim;
91 	struct cam_path *path;
92 
93 	/*
94 	 * Construct our SIM entry.
95 	 */
96 	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);
97 
98 	if (sim == NULL) {
99 		return (ENOMEM);
100 	}
101 
102 	ISP_LOCK(isp);
103 	if (xpt_bus_register(sim, isp->isp_dev, chan) != CAM_SUCCESS) {
104 		ISP_UNLOCK(isp);
105 		cam_sim_free(sim, FALSE);
106 		return (EIO);
107 	}
108 	ISP_UNLOCK(isp);
109 	if (xpt_create_path(&path, NULL, cam_sim_path(sim), CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
110 		ISP_LOCK(isp);
111 		xpt_bus_deregister(cam_sim_path(sim));
112 		ISP_UNLOCK(isp);
113 		cam_sim_free(sim, FALSE);
114 		return (ENXIO);
115 	}
116 	xpt_setup_ccb(&csa.ccb_h, path, 5);
117 	csa.ccb_h.func_code = XPT_SASYNC_CB;
118 	csa.event_enable = AC_LOST_DEVICE;
119 	csa.callback = isp_cam_async;
120 	csa.callback_arg = sim;
121 
122 	ISP_LOCK(isp);
123 	xpt_action((union ccb *)&csa);
124 	ISP_UNLOCK(isp);
125 
126 	if (IS_SCSI(isp)) {
127 		struct isp_spi *spi = ISP_SPI_PC(isp, chan);
128 		spi->sim = sim;
129 		spi->path = path;
130 #ifdef	ISP_INTERNAL_TARGET
131 		ISP_SET_PC(isp, chan, proc_active, 1);
132 		if (THREAD_CREATE(isp_target_thread_pi, spi, &spi->target_proc, 0, 0, "%s: isp_test_tgt%d", device_get_nameunit(isp->isp_osinfo.dev), chan)) {
133 			ISP_SET_PC(isp, chan, proc_active, 0);
134 			isp_prt(isp, ISP_LOGERR, "cannot create test target thread");
135 		}
136 #endif
137 	} else {
138 		fcparam *fcp = FCPARAM(isp, chan);
139 		struct isp_fc *fc = ISP_FC_PC(isp, chan);
140 
141 		ISP_LOCK(isp);
142 		fc->sim = sim;
143 		fc->path = path;
144 		fc->isp = isp;
145 		fc->ready = 1;
146 
147 		callout_init_mtx(&fc->ldt, &isp->isp_osinfo.lock, 0);
148 		callout_init_mtx(&fc->gdt, &isp->isp_osinfo.lock, 0);
149 		TASK_INIT(&fc->ltask, 1, isp_ldt_task, fc);
150 		TASK_INIT(&fc->gtask, 1, isp_gdt_task, fc);
151 
152 		/*
153 		 * We start by being "loop down" if we have an initiator role
154 		 */
155 		if (fcp->role & ISP_ROLE_INITIATOR) {
156 			isp_freeze_loopdown(isp, chan, "isp_attach");
157 			callout_reset(&fc->ldt, isp_quickboot_time * hz, isp_ldt, fc);
158 			isp_prt(isp, ISP_LOG_SANCFG|ISP_LOGDEBUG0, "Starting Initial Loop Down Timer @ %lu", (unsigned long) time_uptime);
159 		}
160 		ISP_UNLOCK(isp);
161 		if (THREAD_CREATE(isp_kthread, fc, &fc->kproc, 0, 0, "%s: fc_thrd%d", device_get_nameunit(isp->isp_osinfo.dev), chan)) {
162 			xpt_free_path(fc->path);
163 			ISP_LOCK(isp);
164 			if (callout_active(&fc->ldt))
165 				callout_stop(&fc->ldt);
166 			xpt_bus_deregister(cam_sim_path(fc->sim));
167 			ISP_UNLOCK(isp);
168 			cam_sim_free(fc->sim, FALSE);
169 			return (ENOMEM);
170 		}
171 #ifdef	ISP_INTERNAL_TARGET
172 		ISP_SET_PC(isp, chan, proc_active, 1);
173 		if (THREAD_CREATE(isp_target_thread_fc, fc, &fc->target_proc, 0, 0, "%s: isp_test_tgt%d", device_get_nameunit(isp->isp_osinfo.dev), chan)) {
174 			ISP_SET_PC(isp, chan, proc_active, 0);
175 			isp_prt(isp, ISP_LOGERR, "cannot create test target thread");
176 		}
177 #endif
178 		if (chan == 0) {
179 			struct sysctl_ctx_list *ctx = device_get_sysctl_ctx(isp->isp_osinfo.dev);
180 			struct sysctl_oid *tree = device_get_sysctl_tree(isp->isp_osinfo.dev);
181 			SYSCTL_ADD_QUAD(ctx, SYSCTL_CHILDREN(tree), OID_AUTO, "wwnn", CTLFLAG_RD, &FCPARAM(isp, 0)->isp_wwnn, "World Wide Node Name");
182 			SYSCTL_ADD_QUAD(ctx, SYSCTL_CHILDREN(tree), OID_AUTO, "wwpn", CTLFLAG_RD, &FCPARAM(isp, 0)->isp_wwpn, "World Wide Port Name");
183 			SYSCTL_ADD_UINT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO, "loop_down_limit", CTLFLAG_RW, &ISP_FC_PC(isp, 0)->loop_down_limit, 0, "Loop Down Limit");
184 			SYSCTL_ADD_UINT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO, "gone_device_time", CTLFLAG_RW, &ISP_FC_PC(isp, 0)->gone_device_time, 0, "Gone Device Time");
185 #if defined(ISP_TARGET_MODE) && defined(DEBUG)
186 			SYSCTL_ADD_UINT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO, "inject_lost_data_frame", CTLFLAG_RW, &ISP_FC_PC(isp, 0)->inject_lost_data_frame, 0, "Cause a Lost Frame on a Read");
187 #endif
188 		}
189 	}
190 	return (0);
191 }
192 
193 int
194 isp_attach(ispsoftc_t *isp)
195 {
196 	const char *nu = device_get_nameunit(isp->isp_osinfo.dev);
197 	int du = device_get_unit(isp->isp_dev);
198 	int chan;
199 
200 	isp->isp_osinfo.ehook.ich_func = isp_intr_enable;
201 	isp->isp_osinfo.ehook.ich_arg = isp;
202 	/*
203 	 * Haha. Set this first, because if we're loaded as a module isp_intr_enable
204 	 * will be called right awawy, which will clear isp_osinfo.ehook_active,
205 	 * which would be unwise to then set again later.
206 	 */
207 	isp->isp_osinfo.ehook_active = 1;
208 	if (config_intrhook_establish(&isp->isp_osinfo.ehook) != 0) {
209 		isp_prt(isp, ISP_LOGERR, "could not establish interrupt enable hook");
210 		return (-EIO);
211 	}
212 
213 	/*
214 	 * Create the device queue for our SIM(s).
215 	 */
216 	isp->isp_osinfo.devq = cam_simq_alloc(isp->isp_maxcmds);
217 	if (isp->isp_osinfo.devq == NULL) {
218 		config_intrhook_disestablish(&isp->isp_osinfo.ehook);
219 		return (EIO);
220 	}
221 
222 	for (chan = 0; chan < isp->isp_nchan; chan++) {
223 		if (isp_attach_chan(isp, isp->isp_osinfo.devq, chan)) {
224 			goto unwind;
225 		}
226 	}
227 
228 	callout_init_mtx(&isp->isp_osinfo.tmo, &isp->isp_osinfo.lock, 0);
229 	isp_timer_count = hz >> 2;
230 	callout_reset(&isp->isp_osinfo.tmo, isp_timer_count, isp_timer, isp);
231 	isp->isp_osinfo.timer_active = 1;
232 
233 	isp->isp_osinfo.cdev = make_dev(&isp_cdevsw, du, UID_ROOT, GID_OPERATOR, 0600, "%s", nu);
234 	if (isp->isp_osinfo.cdev) {
235 		isp->isp_osinfo.cdev->si_drv1 = isp;
236 	}
237 	return (0);
238 
239 unwind:
240 	while (--chan >= 0) {
241 		struct cam_sim *sim;
242 		struct cam_path *path;
243 		if (IS_FC(isp)) {
244 			sim = ISP_FC_PC(isp, chan)->sim;
245 			path = ISP_FC_PC(isp, chan)->path;
246 		} else {
247 			sim = ISP_SPI_PC(isp, chan)->sim;
248 			path = ISP_SPI_PC(isp, chan)->path;
249 		}
250 		xpt_free_path(path);
251 		ISP_LOCK(isp);
252 		xpt_bus_deregister(cam_sim_path(sim));
253 		ISP_UNLOCK(isp);
254 		cam_sim_free(sim, FALSE);
255 	}
256 	if (isp->isp_osinfo.ehook_active) {
257 		config_intrhook_disestablish(&isp->isp_osinfo.ehook);
258 		isp->isp_osinfo.ehook_active = 0;
259 	}
260 	if (isp->isp_osinfo.cdev) {
261 		destroy_dev(isp->isp_osinfo.cdev);
262 		isp->isp_osinfo.cdev = NULL;
263 	}
264 	cam_simq_free(isp->isp_osinfo.devq);
265 	isp->isp_osinfo.devq = NULL;
266 	return (-1);
267 }
268 
269 int
270 isp_detach(ispsoftc_t *isp)
271 {
272 	struct cam_sim *sim;
273 	struct cam_path *path;
274 	struct ccb_setasync csa;
275 	int chan;
276 
277 	ISP_LOCK(isp);
278 	for (chan = isp->isp_nchan - 1; chan >= 0; chan -= 1) {
279 		if (IS_FC(isp)) {
280 			sim = ISP_FC_PC(isp, chan)->sim;
281 			path = ISP_FC_PC(isp, chan)->path;
282 		} else {
283 			sim = ISP_SPI_PC(isp, chan)->sim;
284 			path = ISP_SPI_PC(isp, chan)->path;
285 		}
286 		if (sim->refcount > 2) {
287 			ISP_UNLOCK(isp);
288 			return (EBUSY);
289 		}
290 	}
291 	if (isp->isp_osinfo.timer_active) {
292 		callout_stop(&isp->isp_osinfo.tmo);
293 		isp->isp_osinfo.timer_active = 0;
294 	}
295 	for (chan = isp->isp_nchan - 1; chan >= 0; chan -= 1) {
296 		if (IS_FC(isp)) {
297 			sim = ISP_FC_PC(isp, chan)->sim;
298 			path = ISP_FC_PC(isp, chan)->path;
299 		} else {
300 			sim = ISP_SPI_PC(isp, chan)->sim;
301 			path = ISP_SPI_PC(isp, chan)->path;
302 		}
303 		xpt_setup_ccb(&csa.ccb_h, path, 5);
304 		csa.ccb_h.func_code = XPT_SASYNC_CB;
305 		csa.event_enable = 0;
306 		csa.callback = isp_cam_async;
307 		csa.callback_arg = sim;
308 		ISP_LOCK(isp);
309 		xpt_action((union ccb *)&csa);
310 		ISP_UNLOCK(isp);
311 		xpt_free_path(path);
312 		xpt_bus_deregister(cam_sim_path(sim));
313 		cam_sim_free(sim, FALSE);
314 	}
315 	ISP_UNLOCK(isp);
316 	if (isp->isp_osinfo.cdev) {
317 		destroy_dev(isp->isp_osinfo.cdev);
318 		isp->isp_osinfo.cdev = NULL;
319 	}
320 	if (isp->isp_osinfo.ehook_active) {
321 		config_intrhook_disestablish(&isp->isp_osinfo.ehook);
322 		isp->isp_osinfo.ehook_active = 0;
323 	}
324 	if (isp->isp_osinfo.devq != NULL) {
325 		cam_simq_free(isp->isp_osinfo.devq);
326 		isp->isp_osinfo.devq = NULL;
327 	}
328 	return (0);
329 }
330 
331 static void
332 isp_freeze_loopdown(ispsoftc_t *isp, int chan, char *msg)
333 {
334 	if (IS_FC(isp)) {
335 		struct isp_fc *fc = ISP_FC_PC(isp, chan);
336 		if (fc->simqfrozen == 0) {
337 			isp_prt(isp, ISP_LOGDEBUG0, "%s: freeze simq (loopdown) chan %d", msg, chan);
338 			fc->simqfrozen = SIMQFRZ_LOOPDOWN;
339 			xpt_freeze_simq(fc->sim, 1);
340 		} else {
341 			isp_prt(isp, ISP_LOGDEBUG0, "%s: mark frozen (loopdown) chan %d", msg, chan);
342 			fc->simqfrozen |= SIMQFRZ_LOOPDOWN;
343 		}
344 	}
345 }
346 
347 static void
348 isp_unfreeze_loopdown(ispsoftc_t *isp, int chan)
349 {
350 	if (IS_FC(isp)) {
351 		struct isp_fc *fc = ISP_FC_PC(isp, chan);
352 		int wasfrozen = fc->simqfrozen & SIMQFRZ_LOOPDOWN;
353 		fc->simqfrozen &= ~SIMQFRZ_LOOPDOWN;
354 		if (wasfrozen && fc->simqfrozen == 0) {
355 			isp_prt(isp, ISP_LOG_SANCFG|ISP_LOGDEBUG0, "%s: Chan %d releasing simq", __func__, chan);
356 			xpt_release_simq(fc->sim, 1);
357 		}
358 	}
359 }
360 
361 
362 static int
363 ispioctl(struct cdev *dev, u_long c, caddr_t addr, int flags, struct thread *td)
364 {
365 	ispsoftc_t *isp;
366 	int nr, chan, retval = ENOTTY;
367 
368 	isp = dev->si_drv1;
369 
370 	switch (c) {
371 	case ISP_SDBLEV:
372 	{
373 		int olddblev = isp->isp_dblev;
374 		isp->isp_dblev = *(int *)addr;
375 		*(int *)addr = olddblev;
376 		retval = 0;
377 		break;
378 	}
379 	case ISP_GETROLE:
380 		chan = *(int *)addr;
381 		if (chan < 0 || chan >= isp->isp_nchan) {
382 			retval = -ENXIO;
383 			break;
384 		}
385 		if (IS_FC(isp)) {
386 			*(int *)addr = FCPARAM(isp, chan)->role;
387 		} else {
388 			*(int *)addr = SDPARAM(isp, chan)->role;
389 		}
390 		retval = 0;
391 		break;
392 	case ISP_SETROLE:
393 		nr = *(int *)addr;
394 		chan = nr >> 8;
395 		if (chan < 0 || chan >= isp->isp_nchan) {
396 			retval = -ENXIO;
397 			break;
398 		}
399 		nr &= 0xff;
400 		if (nr & ~(ISP_ROLE_INITIATOR|ISP_ROLE_TARGET)) {
401 			retval = EINVAL;
402 			break;
403 		}
404 		if (IS_FC(isp)) {
405 			/*
406 			 * We don't really support dual role at present on FC cards.
407 			 *
408 			 * We should, but a bunch of things are currently broken,
409 			 * so don't allow it.
410 			 */
411 			if (nr == ISP_ROLE_BOTH) {
412 				isp_prt(isp, ISP_LOGERR, "cannot support dual role at present");
413 				retval = EINVAL;
414 				break;
415 			}
416 			*(int *)addr = FCPARAM(isp, chan)->role;
417 #ifdef	ISP_INTERNAL_TARGET
418 			ISP_LOCK(isp);
419 			retval = isp_fc_change_role(isp, chan, nr);
420 			ISP_UNLOCK(isp);
421 #else
422 			FCPARAM(isp, chan)->role = nr;
423 #endif
424 		} else {
425 			*(int *)addr = SDPARAM(isp, chan)->role;
426 			SDPARAM(isp, chan)->role = nr;
427 		}
428 		retval = 0;
429 		break;
430 
431 	case ISP_RESETHBA:
432 		ISP_LOCK(isp);
433 #ifdef	ISP_TARGET_MODE
434 		isp_del_all_wwn_entries(isp, ISP_NOCHAN);
435 #endif
436 		isp_reinit(isp, 0);
437 		ISP_UNLOCK(isp);
438 		retval = 0;
439 		break;
440 
441 	case ISP_RESCAN:
442 		if (IS_FC(isp)) {
443 			chan = *(int *)addr;
444 			if (chan < 0 || chan >= isp->isp_nchan) {
445 				retval = -ENXIO;
446 				break;
447 			}
448 			ISP_LOCK(isp);
449 			if (isp_fc_runstate(isp, chan, 5 * 1000000)) {
450 				retval = EIO;
451 			} else {
452 				retval = 0;
453 			}
454 			ISP_UNLOCK(isp);
455 		}
456 		break;
457 
458 	case ISP_FC_LIP:
459 		if (IS_FC(isp)) {
460 			chan = *(int *)addr;
461 			if (chan < 0 || chan >= isp->isp_nchan) {
462 				retval = -ENXIO;
463 				break;
464 			}
465 			ISP_LOCK(isp);
466 			if (isp_control(isp, ISPCTL_SEND_LIP, chan)) {
467 				retval = EIO;
468 			} else {
469 				retval = 0;
470 			}
471 			ISP_UNLOCK(isp);
472 		}
473 		break;
474 	case ISP_FC_GETDINFO:
475 	{
476 		struct isp_fc_device *ifc = (struct isp_fc_device *) addr;
477 		fcportdb_t *lp;
478 
479 		if (IS_SCSI(isp)) {
480 			break;
481 		}
482 		if (ifc->loopid >= MAX_FC_TARG) {
483 			retval = EINVAL;
484 			break;
485 		}
486 		lp = &FCPARAM(isp, ifc->chan)->portdb[ifc->loopid];
487 		if (lp->state == FC_PORTDB_STATE_VALID || lp->target_mode) {
488 			ifc->role = (lp->prli_word3 & SVC3_ROLE_MASK) >> SVC3_ROLE_SHIFT;
489 			ifc->loopid = lp->handle;
490 			ifc->portid = lp->portid;
491 			ifc->node_wwn = lp->node_wwn;
492 			ifc->port_wwn = lp->port_wwn;
493 			retval = 0;
494 		} else {
495 			retval = ENODEV;
496 		}
497 		break;
498 	}
499 	case ISP_GET_STATS:
500 	{
501 		isp_stats_t *sp = (isp_stats_t *) addr;
502 
503 		ISP_MEMZERO(sp, sizeof (*sp));
504 		sp->isp_stat_version = ISP_STATS_VERSION;
505 		sp->isp_type = isp->isp_type;
506 		sp->isp_revision = isp->isp_revision;
507 		ISP_LOCK(isp);
508 		sp->isp_stats[ISP_INTCNT] = isp->isp_intcnt;
509 		sp->isp_stats[ISP_INTBOGUS] = isp->isp_intbogus;
510 		sp->isp_stats[ISP_INTMBOXC] = isp->isp_intmboxc;
511 		sp->isp_stats[ISP_INGOASYNC] = isp->isp_intoasync;
512 		sp->isp_stats[ISP_RSLTCCMPLT] = isp->isp_rsltccmplt;
513 		sp->isp_stats[ISP_FPHCCMCPLT] = isp->isp_fphccmplt;
514 		sp->isp_stats[ISP_RSCCHIWAT] = isp->isp_rscchiwater;
515 		sp->isp_stats[ISP_FPCCHIWAT] = isp->isp_fpcchiwater;
516 		ISP_UNLOCK(isp);
517 		retval = 0;
518 		break;
519 	}
520 	case ISP_CLR_STATS:
521 		ISP_LOCK(isp);
522 		isp->isp_intcnt = 0;
523 		isp->isp_intbogus = 0;
524 		isp->isp_intmboxc = 0;
525 		isp->isp_intoasync = 0;
526 		isp->isp_rsltccmplt = 0;
527 		isp->isp_fphccmplt = 0;
528 		isp->isp_rscchiwater = 0;
529 		isp->isp_fpcchiwater = 0;
530 		ISP_UNLOCK(isp);
531 		retval = 0;
532 		break;
533 	case ISP_FC_GETHINFO:
534 	{
535 		struct isp_hba_device *hba = (struct isp_hba_device *) addr;
536 		int chan = hba->fc_channel;
537 
538 		if (chan < 0 || chan >= isp->isp_nchan) {
539 			retval = ENXIO;
540 			break;
541 		}
542 		hba->fc_fw_major = ISP_FW_MAJORX(isp->isp_fwrev);
543 		hba->fc_fw_minor = ISP_FW_MINORX(isp->isp_fwrev);
544 		hba->fc_fw_micro = ISP_FW_MICROX(isp->isp_fwrev);
545 		hba->fc_nchannels = isp->isp_nchan;
546 		if (IS_FC(isp)) {
547 			hba->fc_nports = MAX_FC_TARG;
548 			hba->fc_speed = FCPARAM(isp, hba->fc_channel)->isp_gbspeed;
549 			hba->fc_topology = FCPARAM(isp, chan)->isp_topo + 1;
550 			hba->fc_loopid = FCPARAM(isp, chan)->isp_loopid;
551 			hba->nvram_node_wwn = FCPARAM(isp, chan)->isp_wwnn_nvram;
552 			hba->nvram_port_wwn = FCPARAM(isp, chan)->isp_wwpn_nvram;
553 			hba->active_node_wwn = FCPARAM(isp, chan)->isp_wwnn;
554 			hba->active_port_wwn = FCPARAM(isp, chan)->isp_wwpn;
555 		} else {
556 			hba->fc_nports = MAX_TARGETS;
557 			hba->fc_speed = 0;
558 			hba->fc_topology = 0;
559 			hba->nvram_node_wwn = 0ull;
560 			hba->nvram_port_wwn = 0ull;
561 			hba->active_node_wwn = 0ull;
562 			hba->active_port_wwn = 0ull;
563 		}
564 		retval = 0;
565 		break;
566 	}
567 	case ISP_TSK_MGMT:
568 	{
569 		int needmarker;
570 		struct isp_fc_tsk_mgmt *fct = (struct isp_fc_tsk_mgmt *) addr;
571 		uint16_t loopid;
572 		mbreg_t mbs;
573 
574 		if (IS_SCSI(isp)) {
575 			break;
576 		}
577 
578 		chan = fct->chan;
579 		if (chan < 0 || chan >= isp->isp_nchan) {
580 			retval = -ENXIO;
581 			break;
582 		}
583 
584 		needmarker = retval = 0;
585 		loopid = fct->loopid;
586 		ISP_LOCK(isp);
587 		if (IS_24XX(isp)) {
588 			uint8_t local[QENTRY_LEN];
589 			isp24xx_tmf_t *tmf;
590 			isp24xx_statusreq_t *sp;
591 			fcparam *fcp = FCPARAM(isp, chan);
592 			fcportdb_t *lp;
593 			int i;
594 
595 			for (i = 0; i < MAX_FC_TARG; i++) {
596 				lp = &fcp->portdb[i];
597 				if (lp->handle == loopid) {
598 					break;
599 				}
600 			}
601 			if (i == MAX_FC_TARG) {
602 				retval = ENXIO;
603 				ISP_UNLOCK(isp);
604 				break;
605 			}
606 			/* XXX VALIDATE LP XXX */
607 			tmf = (isp24xx_tmf_t *) local;
608 			ISP_MEMZERO(tmf, QENTRY_LEN);
609 			tmf->tmf_header.rqs_entry_type = RQSTYPE_TSK_MGMT;
610 			tmf->tmf_header.rqs_entry_count = 1;
611 			tmf->tmf_nphdl = lp->handle;
612 			tmf->tmf_delay = 2;
613 			tmf->tmf_timeout = 2;
614 			tmf->tmf_tidlo = lp->portid;
615 			tmf->tmf_tidhi = lp->portid >> 16;
616 			tmf->tmf_vpidx = ISP_GET_VPIDX(isp, chan);
617 			tmf->tmf_lun[1] = fct->lun & 0xff;
618 			if (fct->lun >= 256) {
619 				tmf->tmf_lun[0] = 0x40 | (fct->lun >> 8);
620 			}
621 			switch (fct->action) {
622 			case IPT_CLEAR_ACA:
623 				tmf->tmf_flags = ISP24XX_TMF_CLEAR_ACA;
624 				break;
625 			case IPT_TARGET_RESET:
626 				tmf->tmf_flags = ISP24XX_TMF_TARGET_RESET;
627 				needmarker = 1;
628 				break;
629 			case IPT_LUN_RESET:
630 				tmf->tmf_flags = ISP24XX_TMF_LUN_RESET;
631 				needmarker = 1;
632 				break;
633 			case IPT_CLEAR_TASK_SET:
634 				tmf->tmf_flags = ISP24XX_TMF_CLEAR_TASK_SET;
635 				needmarker = 1;
636 				break;
637 			case IPT_ABORT_TASK_SET:
638 				tmf->tmf_flags = ISP24XX_TMF_ABORT_TASK_SET;
639 				needmarker = 1;
640 				break;
641 			default:
642 				retval = EINVAL;
643 				break;
644 			}
645 			if (retval) {
646 				ISP_UNLOCK(isp);
647 				break;
648 			}
649 			MBSINIT(&mbs, MBOX_EXEC_COMMAND_IOCB_A64, MBLOGALL, 5000000);
650 			mbs.param[1] = QENTRY_LEN;
651 			mbs.param[2] = DMA_WD1(fcp->isp_scdma);
652 			mbs.param[3] = DMA_WD0(fcp->isp_scdma);
653 			mbs.param[6] = DMA_WD3(fcp->isp_scdma);
654 			mbs.param[7] = DMA_WD2(fcp->isp_scdma);
655 
656 			if (FC_SCRATCH_ACQUIRE(isp, chan)) {
657 				ISP_UNLOCK(isp);
658 				retval = ENOMEM;
659 				break;
660 			}
661 			isp_put_24xx_tmf(isp, tmf, fcp->isp_scratch);
662 			MEMORYBARRIER(isp, SYNC_SFORDEV, 0, QENTRY_LEN, chan);
663 			sp = (isp24xx_statusreq_t *) local;
664 			sp->req_completion_status = 1;
665 			retval = isp_control(isp, ISPCTL_RUN_MBOXCMD, &mbs);
666 			MEMORYBARRIER(isp, SYNC_SFORCPU, QENTRY_LEN, QENTRY_LEN, chan);
667 			isp_get_24xx_response(isp, &((isp24xx_statusreq_t *)fcp->isp_scratch)[1], sp);
668 			FC_SCRATCH_RELEASE(isp, chan);
669 			if (retval || sp->req_completion_status != 0) {
670 				FC_SCRATCH_RELEASE(isp, chan);
671 				retval = EIO;
672 			}
673 			if (retval == 0) {
674 				if (needmarker) {
675 					fcp->sendmarker = 1;
676 				}
677 			}
678 		} else {
679 			MBSINIT(&mbs, 0, MBLOGALL, 0);
680 			if (ISP_CAP_2KLOGIN(isp) == 0) {
681 				loopid <<= 8;
682 			}
683 			switch (fct->action) {
684 			case IPT_CLEAR_ACA:
685 				mbs.param[0] = MBOX_CLEAR_ACA;
686 				mbs.param[1] = loopid;
687 				mbs.param[2] = fct->lun;
688 				break;
689 			case IPT_TARGET_RESET:
690 				mbs.param[0] = MBOX_TARGET_RESET;
691 				mbs.param[1] = loopid;
692 				needmarker = 1;
693 				break;
694 			case IPT_LUN_RESET:
695 				mbs.param[0] = MBOX_LUN_RESET;
696 				mbs.param[1] = loopid;
697 				mbs.param[2] = fct->lun;
698 				needmarker = 1;
699 				break;
700 			case IPT_CLEAR_TASK_SET:
701 				mbs.param[0] = MBOX_CLEAR_TASK_SET;
702 				mbs.param[1] = loopid;
703 				mbs.param[2] = fct->lun;
704 				needmarker = 1;
705 				break;
706 			case IPT_ABORT_TASK_SET:
707 				mbs.param[0] = MBOX_ABORT_TASK_SET;
708 				mbs.param[1] = loopid;
709 				mbs.param[2] = fct->lun;
710 				needmarker = 1;
711 				break;
712 			default:
713 				retval = EINVAL;
714 				break;
715 			}
716 			if (retval == 0) {
717 				if (needmarker) {
718 					FCPARAM(isp, chan)->sendmarker = 1;
719 				}
720 				retval = isp_control(isp, ISPCTL_RUN_MBOXCMD, &mbs);
721 				if (retval) {
722 					retval = EIO;
723 				}
724 			}
725 		}
726 		ISP_UNLOCK(isp);
727 		break;
728 	}
729 	default:
730 		break;
731 	}
732 	return (retval);
733 }
734 
735 static void
736 isp_intr_enable(void *arg)
737 {
738 	int chan;
739 	ispsoftc_t *isp = arg;
740 	ISP_LOCK(isp);
741 	for (chan = 0; chan < isp->isp_nchan; chan++) {
742 		if (IS_FC(isp)) {
743 			if (FCPARAM(isp, chan)->role != ISP_ROLE_NONE) {
744 				ISP_ENABLE_INTS(isp);
745 				break;
746 			}
747 		} else {
748 			if (SDPARAM(isp, chan)->role != ISP_ROLE_NONE) {
749 				ISP_ENABLE_INTS(isp);
750 				break;
751 			}
752 		}
753 	}
754 	isp->isp_osinfo.ehook_active = 0;
755 	ISP_UNLOCK(isp);
756 	/* Release our hook so that the boot can continue. */
757 	config_intrhook_disestablish(&isp->isp_osinfo.ehook);
758 }
759 
760 /*
761  * Local Inlines
762  */
763 
764 static ISP_INLINE int isp_get_pcmd(ispsoftc_t *, union ccb *);
765 static ISP_INLINE void isp_free_pcmd(ispsoftc_t *, union ccb *);
766 
767 static ISP_INLINE int
768 isp_get_pcmd(ispsoftc_t *isp, union ccb *ccb)
769 {
770 	ISP_PCMD(ccb) = isp->isp_osinfo.pcmd_free;
771 	if (ISP_PCMD(ccb) == NULL) {
772 		return (-1);
773 	}
774 	isp->isp_osinfo.pcmd_free = ((struct isp_pcmd *)ISP_PCMD(ccb))->next;
775 	return (0);
776 }
777 
778 static ISP_INLINE void
779 isp_free_pcmd(ispsoftc_t *isp, union ccb *ccb)
780 {
781 	if (ISP_PCMD(ccb)) {
782 #ifdef	ISP_TARGET_MODE
783 		PISP_PCMD(ccb)->datalen = 0;
784 		PISP_PCMD(ccb)->totslen = 0;
785 		PISP_PCMD(ccb)->cumslen = 0;
786 		PISP_PCMD(ccb)->crn = 0;
787 #endif
788 		PISP_PCMD(ccb)->next = isp->isp_osinfo.pcmd_free;
789 		isp->isp_osinfo.pcmd_free = ISP_PCMD(ccb);
790 		ISP_PCMD(ccb) = NULL;
791 	}
792 }
793 
794 /*
795  * Put the target mode functions here, because some are inlines
796  */
797 #ifdef	ISP_TARGET_MODE
798 static ISP_INLINE void isp_tmlock(ispsoftc_t *, const char *);
799 static ISP_INLINE void isp_tmunlk(ispsoftc_t *);
800 static ISP_INLINE int is_any_lun_enabled(ispsoftc_t *, int);
801 static ISP_INLINE int is_lun_enabled(ispsoftc_t *, int, lun_id_t);
802 static ISP_INLINE tstate_t *get_lun_statep(ispsoftc_t *, int, lun_id_t);
803 static ISP_INLINE tstate_t *get_lun_statep_from_tag(ispsoftc_t *, int, uint32_t);
804 static ISP_INLINE void rls_lun_statep(ispsoftc_t *, tstate_t *);
805 static ISP_INLINE inot_private_data_t *get_ntp_from_tagdata(ispsoftc_t *, uint32_t, uint32_t, tstate_t **);
806 static ISP_INLINE atio_private_data_t *isp_get_atpd(ispsoftc_t *, tstate_t *, uint32_t);
807 static ISP_INLINE atio_private_data_t *isp_find_atpd(ispsoftc_t *, tstate_t *, uint32_t);
808 static ISP_INLINE void isp_put_atpd(ispsoftc_t *, tstate_t *, atio_private_data_t *);
809 static ISP_INLINE inot_private_data_t *isp_get_ntpd(ispsoftc_t *, tstate_t *);
810 static ISP_INLINE inot_private_data_t *isp_find_ntpd(ispsoftc_t *, tstate_t *, uint32_t, uint32_t);
811 static ISP_INLINE void isp_put_ntpd(ispsoftc_t *, tstate_t *, inot_private_data_t *);
812 static cam_status create_lun_state(ispsoftc_t *, int, struct cam_path *, tstate_t **);
813 static void destroy_lun_state(ispsoftc_t *, tstate_t *);
814 static void isp_enable_lun(ispsoftc_t *, union ccb *);
815 static cam_status isp_enable_deferred_luns(ispsoftc_t *, int);
816 static cam_status isp_enable_deferred(ispsoftc_t *, int, lun_id_t);
817 static void isp_disable_lun(ispsoftc_t *, union ccb *);
818 static int isp_enable_target_mode(ispsoftc_t *, int);
819 static int isp_disable_target_mode(ispsoftc_t *, int);
820 static void isp_ledone(ispsoftc_t *, lun_entry_t *);
821 static timeout_t isp_refire_putback_atio;
822 static timeout_t isp_refire_notify_ack;
823 static void isp_complete_ctio(union ccb *);
824 static void isp_target_putback_atio(union ccb *);
825 enum Start_Ctio_How { FROM_CAM, FROM_TIMER, FROM_SRR, FROM_CTIO_DONE };
826 static void isp_target_start_ctio(ispsoftc_t *, union ccb *, enum Start_Ctio_How);
827 static void isp_handle_platform_atio(ispsoftc_t *, at_entry_t *);
828 static void isp_handle_platform_atio2(ispsoftc_t *, at2_entry_t *);
829 static void isp_handle_platform_atio7(ispsoftc_t *, at7_entry_t *);
830 static void isp_handle_platform_ctio(ispsoftc_t *, void *);
831 static void isp_handle_platform_notify_scsi(ispsoftc_t *, in_entry_t *);
832 static void isp_handle_platform_notify_fc(ispsoftc_t *, in_fcentry_t *);
833 static void isp_handle_platform_notify_24xx(ispsoftc_t *, in_fcentry_24xx_t *);
834 static int isp_handle_platform_target_notify_ack(ispsoftc_t *, isp_notify_t *);
835 static void isp_handle_platform_target_tmf(ispsoftc_t *, isp_notify_t *);
836 static void isp_target_mark_aborted(ispsoftc_t *, union ccb *);
837 static void isp_target_mark_aborted_early(ispsoftc_t *, tstate_t *, uint32_t);
838 
839 static ISP_INLINE void
840 isp_tmlock(ispsoftc_t *isp, const char *msg)
841 {
842 	while (isp->isp_osinfo.tmbusy) {
843 		isp->isp_osinfo.tmwanted = 1;
844 		mtx_sleep(isp, &isp->isp_lock, PRIBIO, msg, 0);
845 	}
846 	isp->isp_osinfo.tmbusy = 1;
847 }
848 
849 static ISP_INLINE void
850 isp_tmunlk(ispsoftc_t *isp)
851 {
852 	isp->isp_osinfo.tmbusy = 0;
853 	if (isp->isp_osinfo.tmwanted) {
854 		isp->isp_osinfo.tmwanted = 0;
855 		wakeup(isp);
856 	}
857 }
858 
859 static ISP_INLINE int
860 is_any_lun_enabled(ispsoftc_t *isp, int bus)
861 {
862 	struct tslist *lhp;
863 	int i;
864 
865 	for (i = 0; i < LUN_HASH_SIZE; i++) {
866 		ISP_GET_PC_ADDR(isp, bus, lun_hash[i], lhp);
867 		if (SLIST_FIRST(lhp))
868 			return (1);
869 	}
870 	return (0);
871 }
872 
873 static ISP_INLINE int
874 is_lun_enabled(ispsoftc_t *isp, int bus, lun_id_t lun)
875 {
876 	tstate_t *tptr;
877 	struct tslist *lhp;
878 
879 	ISP_GET_PC_ADDR(isp, bus, lun_hash[LUN_HASH_FUNC(lun)], lhp);
880 	SLIST_FOREACH(tptr, lhp, next) {
881 		if (xpt_path_lun_id(tptr->owner) == lun) {
882 			return (1);
883 		}
884 	}
885 	return (0);
886 }
887 
888 static void
889 dump_tstates(ispsoftc_t *isp, int bus)
890 {
891 	int i, j;
892 	struct tslist *lhp;
893 	tstate_t *tptr = NULL;
894 
895 	if (bus >= isp->isp_nchan) {
896 		return;
897 	}
898 	for (i = 0; i < LUN_HASH_SIZE; i++) {
899 		ISP_GET_PC_ADDR(isp, bus, lun_hash[i], lhp);
900 		j = 0;
901 		SLIST_FOREACH(tptr, lhp, next) {
902 			xpt_print(tptr->owner, "[%d, %d] atio_cnt=%d inot_cnt=%d\n", i, j, tptr->atio_count, tptr->inot_count);
903 			j++;
904 		}
905 	}
906 }
907 
908 static ISP_INLINE tstate_t *
909 get_lun_statep(ispsoftc_t *isp, int bus, lun_id_t lun)
910 {
911 	tstate_t *tptr = NULL;
912 	struct tslist *lhp;
913 	int i;
914 
915 	if (bus < isp->isp_nchan) {
916 		for (i = 0; i < LUN_HASH_SIZE; i++) {
917 			ISP_GET_PC_ADDR(isp, bus, lun_hash[i], lhp);
918 			SLIST_FOREACH(tptr, lhp, next) {
919 				if (xpt_path_lun_id(tptr->owner) == lun) {
920 					tptr->hold++;
921 					return (tptr);
922 				}
923 			}
924 		}
925 	}
926 	return (NULL);
927 }
928 
929 static ISP_INLINE tstate_t *
930 get_lun_statep_from_tag(ispsoftc_t *isp, int bus, uint32_t tagval)
931 {
932 	tstate_t *tptr = NULL;
933 	atio_private_data_t *atp;
934 	struct tslist *lhp;
935 	int i;
936 
937 	if (bus < isp->isp_nchan && tagval != 0) {
938 		for (i = 0; i < LUN_HASH_SIZE; i++) {
939 			ISP_GET_PC_ADDR(isp, bus, lun_hash[i], lhp);
940 			SLIST_FOREACH(tptr, lhp, next) {
941 				atp = isp_find_atpd(isp, tptr, tagval);
942 				if (atp) {
943 					tptr->hold++;
944 					return (tptr);
945 				}
946 			}
947 		}
948 	}
949 	return (NULL);
950 }
951 
952 static ISP_INLINE inot_private_data_t *
953 get_ntp_from_tagdata(ispsoftc_t *isp, uint32_t tag_id, uint32_t seq_id, tstate_t **rslt)
954 {
955 	inot_private_data_t *ntp;
956 	tstate_t *tptr;
957 	struct tslist *lhp;
958 	int bus, i;
959 
960 	for (bus = 0; bus < isp->isp_nchan; bus++) {
961 		for (i = 0; i < LUN_HASH_SIZE; i++) {
962 			ISP_GET_PC_ADDR(isp, bus, lun_hash[i], lhp);
963 			SLIST_FOREACH(tptr, lhp, next) {
964 				ntp = isp_find_ntpd(isp, tptr, tag_id, seq_id);
965 				if (ntp) {
966 					*rslt = tptr;
967 					tptr->hold++;
968 					return (ntp);
969 				}
970 			}
971 		}
972 	}
973 	return (NULL);
974 }
975 
976 static ISP_INLINE void
977 rls_lun_statep(ispsoftc_t *isp, tstate_t *tptr)
978 {
979 	KASSERT((tptr->hold), ("tptr not held"));
980 	tptr->hold--;
981 }
982 
983 static void
984 isp_tmcmd_restart(ispsoftc_t *isp)
985 {
986 	inot_private_data_t *ntp;
987 	inot_private_data_t *restart_queue;
988 	tstate_t *tptr;
989 	union ccb *ccb;
990 	struct tslist *lhp;
991 	int bus, i;
992 
993 	for (bus = 0; bus < isp->isp_nchan; bus++) {
994 		for (i = 0; i < LUN_HASH_SIZE; i++) {
995 			ISP_GET_PC_ADDR(isp, bus, lun_hash[i], lhp);
996 			SLIST_FOREACH(tptr, lhp, next) {
997 				if ((restart_queue = tptr->restart_queue) != NULL)
998 					tptr->restart_queue = NULL;
999 				while (restart_queue) {
1000 					ntp = restart_queue;
1001 					restart_queue = ntp->rd.nt.nt_hba;
1002 					if (IS_24XX(isp)) {
1003 						isp_prt(isp, ISP_LOGTDEBUG0, "%s: restarting resrc deprived %x", __func__, ((at7_entry_t *)ntp->rd.data)->at_rxid);
1004 						isp_handle_platform_atio7(isp, (at7_entry_t *) ntp->rd.data);
1005 					} else {
1006 						isp_prt(isp, ISP_LOGTDEBUG0, "%s: restarting resrc deprived %x", __func__, ((at2_entry_t *)ntp->rd.data)->at_rxid);
1007 						isp_handle_platform_atio2(isp, (at2_entry_t *) ntp->rd.data);
1008 					}
1009 					isp_put_ntpd(isp, tptr, ntp);
1010 					if (tptr->restart_queue && restart_queue != NULL) {
1011 						ntp = tptr->restart_queue;
1012 						tptr->restart_queue = restart_queue;
1013 						while (restart_queue->rd.nt.nt_hba) {
1014 							restart_queue = restart_queue->rd.nt.nt_hba;
1015 						}
1016 						restart_queue->rd.nt.nt_hba = ntp;
1017 						break;
1018 					}
1019 				}
1020 				/*
1021 				 * We only need to do this once per tptr
1022 				 */
1023 				if (!TAILQ_EMPTY(&tptr->waitq)) {
1024 					ccb = (union ccb *)TAILQ_LAST(&tptr->waitq, isp_ccbq);
1025 					TAILQ_REMOVE(&tptr->waitq, &ccb->ccb_h, periph_links.tqe);
1026 					isp_target_start_ctio(isp, ccb, FROM_TIMER);
1027 				}
1028 			}
1029 		}
1030 	}
1031 }
1032 
1033 static ISP_INLINE atio_private_data_t *
1034 isp_get_atpd(ispsoftc_t *isp, tstate_t *tptr, uint32_t tag)
1035 {
1036 	atio_private_data_t *atp;
1037 
1038 	atp = LIST_FIRST(&tptr->atfree);
1039 	if (atp) {
1040 		LIST_REMOVE(atp, next);
1041 		atp->tag = tag;
1042 		LIST_INSERT_HEAD(&tptr->atused[ATPDPHASH(tag)], atp, next);
1043 	}
1044 	return (atp);
1045 }
1046 
1047 static ISP_INLINE atio_private_data_t *
1048 isp_find_atpd(ispsoftc_t *isp, tstate_t *tptr, uint32_t tag)
1049 {
1050 	atio_private_data_t *atp;
1051 
1052 	LIST_FOREACH(atp, &tptr->atused[ATPDPHASH(tag)], next) {
1053 		if (atp->tag == tag)
1054 			return (atp);
1055 	}
1056 	return (NULL);
1057 }
1058 
1059 static ISP_INLINE void
1060 isp_put_atpd(ispsoftc_t *isp, tstate_t *tptr, atio_private_data_t *atp)
1061 {
1062 	if (atp->ests) {
1063 		isp_put_ecmd(isp, atp->ests);
1064 	}
1065 	LIST_REMOVE(atp, next);
1066 	memset(atp, 0, sizeof (*atp));
1067 	LIST_INSERT_HEAD(&tptr->atfree, atp, next);
1068 }
1069 
1070 static void
1071 isp_dump_atpd(ispsoftc_t *isp, tstate_t *tptr)
1072 {
1073 	atio_private_data_t *atp;
1074 	const char *states[8] = { "Free", "ATIO", "CAM", "CTIO", "LAST_CTIO", "PDON", "?6", "7" };
1075 
1076 	for (atp = tptr->atpool; atp < &tptr->atpool[ATPDPSIZE]; atp++) {
1077 		xpt_print(tptr->owner, "ATP: [0x%x] origdlen %u bytes_xfrd %u lun %u nphdl 0x%04x s_id 0x%06x d_id 0x%06x oxid 0x%04x state %s\n",
1078 		    atp->tag, atp->orig_datalen, atp->bytes_xfered, atp->lun, atp->nphdl, atp->sid, atp->portid, atp->oxid, states[atp->state & 0x7]);
1079 	}
1080 }
1081 
1082 
1083 static ISP_INLINE inot_private_data_t *
1084 isp_get_ntpd(ispsoftc_t *isp, tstate_t *tptr)
1085 {
1086 	inot_private_data_t *ntp;
1087 	ntp = tptr->ntfree;
1088 	if (ntp) {
1089 		tptr->ntfree = ntp->next;
1090 	}
1091 	return (ntp);
1092 }
1093 
1094 static ISP_INLINE inot_private_data_t *
1095 isp_find_ntpd(ispsoftc_t *isp, tstate_t *tptr, uint32_t tag_id, uint32_t seq_id)
1096 {
1097 	inot_private_data_t *ntp;
1098 	for (ntp = tptr->ntpool; ntp < &tptr->ntpool[ATPDPSIZE]; ntp++) {
1099 		if (ntp->rd.tag_id == tag_id && ntp->rd.seq_id == seq_id) {
1100 			return (ntp);
1101 		}
1102 	}
1103 	return (NULL);
1104 }
1105 
1106 static ISP_INLINE void
1107 isp_put_ntpd(ispsoftc_t *isp, tstate_t *tptr, inot_private_data_t *ntp)
1108 {
1109 	ntp->rd.tag_id = ntp->rd.seq_id = 0;
1110 	ntp->next = tptr->ntfree;
1111 	tptr->ntfree = ntp;
1112 }
1113 
1114 static cam_status
1115 create_lun_state(ispsoftc_t *isp, int bus, struct cam_path *path, tstate_t **rslt)
1116 {
1117 	cam_status status;
1118 	lun_id_t lun;
1119 	struct tslist *lhp;
1120 	tstate_t *tptr;
1121 	int i;
1122 
1123 	lun = xpt_path_lun_id(path);
1124 	if (lun != CAM_LUN_WILDCARD) {
1125 		if (lun >= ISP_MAX_LUNS(isp)) {
1126 			return (CAM_LUN_INVALID);
1127 		}
1128 	}
1129 	if (is_lun_enabled(isp, bus, lun)) {
1130 		return (CAM_LUN_ALRDY_ENA);
1131 	}
1132 	tptr = malloc(sizeof (tstate_t), M_DEVBUF, M_NOWAIT|M_ZERO);
1133 	if (tptr == NULL) {
1134 		return (CAM_RESRC_UNAVAIL);
1135 	}
1136 	status = xpt_create_path(&tptr->owner, NULL, xpt_path_path_id(path), xpt_path_target_id(path), lun);
1137 	if (status != CAM_REQ_CMP) {
1138 		free(tptr, M_DEVBUF);
1139 		return (status);
1140 	}
1141 	SLIST_INIT(&tptr->atios);
1142 	SLIST_INIT(&tptr->inots);
1143 	TAILQ_INIT(&tptr->waitq);
1144 	LIST_INIT(&tptr->atfree);
1145 	for (i = ATPDPSIZE-1; i >= 0; i--)
1146 		LIST_INSERT_HEAD(&tptr->atfree, &tptr->atpool[i], next);
1147 	for (i = 0; i < ATPDPHASHSIZE; i++)
1148 		LIST_INIT(&tptr->atused[i]);
1149 	for (i = 0; i < ATPDPSIZE-1; i++)
1150 		tptr->ntpool[i].next = &tptr->ntpool[i+1];
1151 	tptr->ntfree = tptr->ntpool;
1152 	tptr->hold = 1;
1153 	ISP_GET_PC_ADDR(isp, bus, lun_hash[LUN_HASH_FUNC(xpt_path_lun_id(tptr->owner))], lhp);
1154 	SLIST_INSERT_HEAD(lhp, tptr, next);
1155 	*rslt = tptr;
1156 	ISP_PATH_PRT(isp, ISP_LOGTDEBUG0, path, "created tstate\n");
1157 	return (CAM_REQ_CMP);
1158 }
1159 
1160 static ISP_INLINE void
1161 destroy_lun_state(ispsoftc_t *isp, tstate_t *tptr)
1162 {
1163 	union ccb *ccb;
1164 	struct tslist *lhp;
1165 
1166 	KASSERT((tptr->hold != 0), ("tptr is not held"));
1167 	KASSERT((tptr->hold == 1), ("tptr still held (%d)", tptr->hold));
1168 	do {
1169 		ccb = (union ccb *)SLIST_FIRST(&tptr->atios);
1170 		if (ccb) {
1171 			SLIST_REMOVE_HEAD(&tptr->atios, sim_links.sle);
1172 			ccb->ccb_h.status = CAM_REQ_ABORTED;
1173 			xpt_done(ccb);
1174 		}
1175 	} while (ccb);
1176 	do {
1177 		ccb = (union ccb *)SLIST_FIRST(&tptr->inots);
1178 		if (ccb) {
1179 			SLIST_REMOVE_HEAD(&tptr->inots, sim_links.sle);
1180 			ccb->ccb_h.status = CAM_REQ_ABORTED;
1181 			xpt_done(ccb);
1182 		}
1183 	} while (ccb);
1184 	ISP_GET_PC_ADDR(isp, cam_sim_bus(xpt_path_sim(tptr->owner)), lun_hash[LUN_HASH_FUNC(xpt_path_lun_id(tptr->owner))], lhp);
1185 	SLIST_REMOVE(lhp, tptr, tstate, next);
1186 	ISP_PATH_PRT(isp, ISP_LOGTDEBUG0, tptr->owner, "destroyed tstate\n");
1187 	xpt_free_path(tptr->owner);
1188 	free(tptr, M_DEVBUF);
1189 }
1190 
1191 /*
1192  * Enable a lun.
1193  */
1194 static void
1195 isp_enable_lun(ispsoftc_t *isp, union ccb *ccb)
1196 {
1197 	tstate_t *tptr = NULL;
1198 	int bus, tm_enabled, target_role;
1199 	target_id_t target;
1200 	lun_id_t lun;
1201 
1202 
1203 	/*
1204 	 * We only support either a wildcard target/lun or a target ID of zero and a non-wildcard lun
1205 	 */
1206 	bus = XS_CHANNEL(ccb);
1207 	target = ccb->ccb_h.target_id;
1208 	lun = ccb->ccb_h.target_lun;
1209 	ISP_PATH_PRT(isp, ISP_LOGTDEBUG0|ISP_LOGCONFIG, ccb->ccb_h.path, "enabling lun %u\n", lun);
1210 	if (target != CAM_TARGET_WILDCARD && target != 0) {
1211 		ccb->ccb_h.status = CAM_TID_INVALID;
1212 		xpt_done(ccb);
1213 		return;
1214 	}
1215 	if (target == CAM_TARGET_WILDCARD && lun != CAM_LUN_WILDCARD) {
1216 		ccb->ccb_h.status = CAM_LUN_INVALID;
1217 		xpt_done(ccb);
1218 		return;
1219 	}
1220 
1221 	if (target != CAM_TARGET_WILDCARD && lun == CAM_LUN_WILDCARD) {
1222 		ccb->ccb_h.status = CAM_LUN_INVALID;
1223 		xpt_done(ccb);
1224 		return;
1225 	}
1226 	if (isp->isp_dblev & ISP_LOGTDEBUG0) {
1227 		xpt_print(ccb->ccb_h.path, "enabling lun 0x%x on channel %d\n", lun, bus);
1228 	}
1229 
1230 	/*
1231 	 * Wait until we're not busy with the lun enables subsystem
1232 	 */
1233 	isp_tmlock(isp, "isp_enable_lun");
1234 
1235 	/*
1236 	 * This is as a good a place as any to check f/w capabilities.
1237 	 */
1238 
1239 	if (IS_FC(isp)) {
1240 		if (ISP_CAP_TMODE(isp) == 0) {
1241 			xpt_print(ccb->ccb_h.path, "firmware does not support target mode\n");
1242 			ccb->ccb_h.status = CAM_FUNC_NOTAVAIL;
1243 			goto done;
1244 		}
1245 		/*
1246 		 * We *could* handle non-SCCLUN f/w, but we'd have to
1247 		 * dork with our already fragile enable/disable code.
1248 		 */
1249 		if (ISP_CAP_SCCFW(isp) == 0) {
1250 			xpt_print(ccb->ccb_h.path, "firmware not SCCLUN capable\n");
1251 			ccb->ccb_h.status = CAM_FUNC_NOTAVAIL;
1252 			goto done;
1253 		}
1254 
1255 		target_role = (FCPARAM(isp, bus)->role & ISP_ROLE_TARGET) != 0;
1256 
1257 	} else {
1258 		target_role = (SDPARAM(isp, bus)->role & ISP_ROLE_TARGET) != 0;
1259 	}
1260 
1261 	/*
1262 	 * Create the state pointer.
1263 	 * It should not already exist.
1264 	 */
1265 	tptr = get_lun_statep(isp, bus, lun);
1266 	if (tptr) {
1267 		ccb->ccb_h.status = CAM_LUN_ALRDY_ENA;
1268 		goto done;
1269 	}
1270 	ccb->ccb_h.status = create_lun_state(isp, bus, ccb->ccb_h.path, &tptr);
1271 	if (ccb->ccb_h.status != CAM_REQ_CMP) {
1272 		goto done;
1273 	}
1274 
1275 	/*
1276 	 * We have a tricky maneuver to perform here.
1277 	 *
1278 	 * If target mode isn't already enabled here,
1279 	 * *and* our current role includes target mode,
1280 	 * we enable target mode here.
1281 	 *
1282 	 */
1283 	ISP_GET_PC(isp, bus, tm_enabled, tm_enabled);
1284 	if (tm_enabled == 0 && target_role != 0) {
1285 		if (isp_enable_target_mode(isp, bus)) {
1286 			ccb->ccb_h.status = CAM_REQ_CMP_ERR;
1287 			destroy_lun_state(isp, tptr);
1288 			tptr = NULL;
1289 			goto done;
1290 		}
1291 		tm_enabled = 1;
1292 	}
1293 
1294 	/*
1295 	 * Now check to see whether this bus is in target mode already.
1296 	 *
1297 	 * If not, a later role change into target mode will finish the job.
1298 	 */
1299 	if (tm_enabled == 0) {
1300 		ISP_SET_PC(isp, bus, tm_enable_defer, 1);
1301 		ccb->ccb_h.status = CAM_REQ_CMP;
1302 		xpt_print(ccb->ccb_h.path, "Target Mode not enabled yet- lun enable deferred\n");
1303 		goto done1;
1304 	}
1305 
1306 	/*
1307 	 * Enable the lun.
1308 	 */
1309 	ccb->ccb_h.status = isp_enable_deferred(isp, bus, lun);
1310 
1311 done:
1312 	if (ccb->ccb_h.status != CAM_REQ_CMP)  {
1313 		if (tptr) {
1314 			destroy_lun_state(isp, tptr);
1315 			tptr = NULL;
1316 		}
1317 	} else {
1318 		tptr->enabled = 1;
1319 	}
1320 done1:
1321 	if (tptr) {
1322 		rls_lun_statep(isp, tptr);
1323 	}
1324 
1325 	/*
1326 	 * And we're outta here....
1327 	 */
1328 	isp_tmunlk(isp);
1329 	xpt_done(ccb);
1330 }
1331 
1332 static cam_status
1333 isp_enable_deferred_luns(ispsoftc_t *isp, int bus)
1334 {
1335 	tstate_t *tptr = NULL;
1336 	struct tslist *lhp;
1337 	int i, n;
1338 
1339 
1340 	ISP_GET_PC(isp, bus, tm_enabled, i);
1341 	if (i == 1) {
1342 		return (CAM_REQ_CMP);
1343 	}
1344 	ISP_GET_PC(isp, bus, tm_enable_defer, i);
1345 	if (i == 0) {
1346 		return (CAM_REQ_CMP);
1347 	}
1348 	/*
1349 	 * If this succeeds, it will set tm_enable
1350 	 */
1351 	if (isp_enable_target_mode(isp, bus)) {
1352 		return (CAM_REQ_CMP_ERR);
1353 	}
1354 	isp_tmlock(isp, "isp_enable_deferred_luns");
1355 	for (n = i = 0; i < LUN_HASH_SIZE; i++) {
1356 		ISP_GET_PC_ADDR(isp, bus, lun_hash[i], lhp);
1357 		SLIST_FOREACH(tptr, lhp, next) {
1358 			tptr->hold++;
1359 			if (tptr->enabled == 0) {
1360 				if (isp_enable_deferred(isp, bus, xpt_path_lun_id(tptr->owner)) == CAM_REQ_CMP) {
1361 					tptr->enabled = 1;
1362 					n++;
1363 				}
1364 			} else {
1365 				n++;
1366 			}
1367 			tptr->hold--;
1368 		}
1369 	}
1370 	isp_tmunlk(isp);
1371 	if (n == 0) {
1372 		return (CAM_REQ_CMP_ERR);
1373 	}
1374 	ISP_SET_PC(isp, bus, tm_enable_defer, 0);
1375 	return (CAM_REQ_CMP);
1376 }
1377 
1378 static cam_status
1379 isp_enable_deferred(ispsoftc_t *isp, int bus, lun_id_t lun)
1380 {
1381 	cam_status status;
1382 	int luns_already_enabled;
1383 
1384 	ISP_GET_PC(isp, bus, tm_luns_enabled, luns_already_enabled);
1385 	isp_prt(isp, ISP_LOGTINFO, "%s: bus %d lun %jx luns_enabled %d", __func__, bus, (uintmax_t)lun, luns_already_enabled);
1386 	if (IS_24XX(isp) || (IS_FC(isp) && luns_already_enabled)) {
1387 		status = CAM_REQ_CMP;
1388 	} else {
1389 		int cmd_cnt, not_cnt;
1390 
1391 		if (IS_23XX(isp)) {
1392 			cmd_cnt = DFLT_CMND_CNT;
1393 			not_cnt = DFLT_INOT_CNT;
1394 		} else {
1395 			cmd_cnt = 64;
1396 			not_cnt = 8;
1397 		}
1398 		status = CAM_REQ_INPROG;
1399 		isp->isp_osinfo.rptr = &status;
1400 		if (isp_lun_cmd(isp, RQSTYPE_ENABLE_LUN, bus, lun == CAM_LUN_WILDCARD? 0 : lun, cmd_cnt, not_cnt)) {
1401 			status = CAM_RESRC_UNAVAIL;
1402 		} else {
1403 			mtx_sleep(&status, &isp->isp_lock, PRIBIO, "isp_enable_deferred", 0);
1404 		}
1405 		isp->isp_osinfo.rptr = NULL;
1406 	}
1407 	if (status == CAM_REQ_CMP) {
1408 		ISP_SET_PC(isp, bus, tm_luns_enabled, 1);
1409 		isp_prt(isp, ISP_LOGCONFIG|ISP_LOGTINFO, "bus %d lun %jx now enabled for target mode", bus, (uintmax_t)lun);
1410 	}
1411 	return (status);
1412 }
1413 
1414 static void
1415 isp_disable_lun(ispsoftc_t *isp, union ccb *ccb)
1416 {
1417 	tstate_t *tptr = NULL;
1418 	int bus;
1419 	cam_status status;
1420 	target_id_t target;
1421 	lun_id_t lun;
1422 
1423 	bus = XS_CHANNEL(ccb);
1424 	target = ccb->ccb_h.target_id;
1425 	lun = ccb->ccb_h.target_lun;
1426 	ISP_PATH_PRT(isp, ISP_LOGTDEBUG0|ISP_LOGCONFIG, ccb->ccb_h.path, "disabling lun %u\n", lun);
1427 	if (target != CAM_TARGET_WILDCARD && target != 0) {
1428 		ccb->ccb_h.status = CAM_TID_INVALID;
1429 		xpt_done(ccb);
1430 		return;
1431 	}
1432 
1433 	if (target == CAM_TARGET_WILDCARD && lun != CAM_LUN_WILDCARD) {
1434 		ccb->ccb_h.status = CAM_LUN_INVALID;
1435 		xpt_done(ccb);
1436 		return;
1437 	}
1438 
1439 	if (target != CAM_TARGET_WILDCARD && lun == CAM_LUN_WILDCARD) {
1440 		ccb->ccb_h.status = CAM_LUN_INVALID;
1441 		xpt_done(ccb);
1442 		return;
1443 	}
1444 
1445 	/*
1446 	 * See if we're busy disabling a lun now.
1447 	 */
1448 	isp_tmlock(isp, "isp_disable_lun");
1449 	status = CAM_REQ_INPROG;
1450 
1451 	/*
1452 	 * Find the state pointer.
1453 	 */
1454 	if ((tptr = get_lun_statep(isp, bus, lun)) == NULL) {
1455 		status = CAM_PATH_INVALID;
1456 		goto done;
1457 	}
1458 
1459 	/*
1460 	 * If we're a 24XX card, we're done.
1461 	 */
1462 	if (IS_24XX(isp)) {
1463 		status = CAM_REQ_CMP;
1464 		goto done;
1465 	}
1466 
1467 	/*
1468 	 * For SCC FW, we only deal with lun zero.
1469 	 */
1470 	if (IS_FC(isp) && lun > 0) {
1471 		status = CAM_REQ_CMP;
1472 		goto done;
1473 	}
1474 	isp->isp_osinfo.rptr = &status;
1475 	if (isp_lun_cmd(isp, RQSTYPE_ENABLE_LUN, bus, lun, 0, 0)) {
1476 		status = CAM_RESRC_UNAVAIL;
1477 	} else {
1478 		mtx_sleep(ccb, &isp->isp_lock, PRIBIO, "isp_disable_lun", 0);
1479 	}
1480 	isp->isp_osinfo.rptr = NULL;
1481 done:
1482 	if (status == CAM_REQ_CMP) {
1483 		tptr->enabled = 0;
1484 		/*
1485 		 * If we have no more luns enabled for this bus,
1486 		 * delete all tracked wwns for it (if we are FC),
1487 		 * and disable target mode.
1488 		 */
1489 		if (is_any_lun_enabled(isp, bus) == 0) {
1490 			isp_del_all_wwn_entries(isp, bus);
1491 			if (isp_disable_target_mode(isp, bus)) {
1492 				status = CAM_REQ_CMP_ERR;
1493 			}
1494 		}
1495 	}
1496 	ccb->ccb_h.status = status;
1497 	if (status == CAM_REQ_CMP) {
1498 		destroy_lun_state(isp, tptr);
1499 		xpt_print(ccb->ccb_h.path, "lun now disabled for target mode\n");
1500 	} else {
1501 		if (tptr)
1502 			rls_lun_statep(isp, tptr);
1503 	}
1504 	isp_tmunlk(isp);
1505 	xpt_done(ccb);
1506 }
1507 
1508 static int
1509 isp_enable_target_mode(ispsoftc_t *isp, int bus)
1510 {
1511 	int tm_enabled;
1512 
1513 	ISP_GET_PC(isp, bus, tm_enabled, tm_enabled);
1514 	if (tm_enabled != 0) {
1515 		return (0);
1516 	}
1517 	if (IS_SCSI(isp)) {
1518 		mbreg_t mbs;
1519 		MBSINIT(&mbs, MBOX_ENABLE_TARGET_MODE, MBLOGALL, 0);
1520 		mbs.param[0] = MBOX_ENABLE_TARGET_MODE;
1521 		mbs.param[1] = ENABLE_TARGET_FLAG|ENABLE_TQING_FLAG;
1522 		mbs.param[2] = bus << 7;
1523 		if (isp_control(isp, ISPCTL_RUN_MBOXCMD, &mbs) < 0 || mbs.param[0] != MBOX_COMMAND_COMPLETE) {
1524 			isp_prt(isp, ISP_LOGERR, "Unable to enable Target Role on Bus %d", bus);
1525 			return (EIO);
1526 		}
1527 	}
1528 	ISP_SET_PC(isp, bus, tm_enabled, 1);
1529 	isp_prt(isp, ISP_LOGINFO, "Target Role enabled on Bus %d", bus);
1530 	return (0);
1531 }
1532 
1533 static int
1534 isp_disable_target_mode(ispsoftc_t *isp, int bus)
1535 {
1536 	int tm_enabled;
1537 
1538 	ISP_GET_PC(isp, bus, tm_enabled, tm_enabled);
1539 	if (tm_enabled == 0) {
1540 		return (0);
1541 	}
1542 	if (IS_SCSI(isp)) {
1543 		mbreg_t mbs;
1544 		MBSINIT(&mbs, MBOX_ENABLE_TARGET_MODE, MBLOGALL, 0);
1545 		mbs.param[2] = bus << 7;
1546 		if (isp_control(isp, ISPCTL_RUN_MBOXCMD, &mbs) < 0 || mbs.param[0] != MBOX_COMMAND_COMPLETE) {
1547 			isp_prt(isp, ISP_LOGERR, "Unable to disable Target Role on Bus %d", bus);
1548 			return (EIO);
1549 		}
1550 	}
1551 	ISP_SET_PC(isp, bus, tm_enabled, 0);
1552 	isp_prt(isp, ISP_LOGINFO, "Target Role disabled on Bus %d", bus);
1553 	return (0);
1554 }
1555 
1556 static void
1557 isp_ledone(ispsoftc_t *isp, lun_entry_t *lep)
1558 {
1559 	uint32_t *rptr;
1560 
1561 	rptr = isp->isp_osinfo.rptr;
1562 	if (lep->le_status != LUN_OK) {
1563 		isp_prt(isp, ISP_LOGERR, "ENABLE/MODIFY LUN returned 0x%x", lep->le_status);
1564 		if (rptr) {
1565 			*rptr = CAM_REQ_CMP_ERR;
1566 			wakeup_one(rptr);
1567 		}
1568 	} else {
1569 		if (rptr) {
1570 			*rptr = CAM_REQ_CMP;
1571 			wakeup_one(rptr);
1572 		}
1573 	}
1574 }
1575 
1576 static void
1577 isp_target_start_ctio(ispsoftc_t *isp, union ccb *ccb, enum Start_Ctio_How how)
1578 {
1579 	int fctape, sendstatus, resid;
1580 	tstate_t *tptr;
1581 	fcparam *fcp;
1582 	atio_private_data_t *atp;
1583 	struct ccb_scsiio *cso;
1584 	uint32_t dmaresult, handle, xfrlen, sense_length, tmp;
1585 	uint8_t local[QENTRY_LEN];
1586 
1587 	tptr = get_lun_statep(isp, XS_CHANNEL(ccb), XS_LUN(ccb));
1588 	if (tptr == NULL) {
1589 		tptr = get_lun_statep(isp, XS_CHANNEL(ccb), CAM_LUN_WILDCARD);
1590 		if (tptr == NULL) {
1591 			isp_prt(isp, ISP_LOGERR, "%s: [0x%x] cannot find tstate pointer", __func__, ccb->csio.tag_id);
1592 			ccb->ccb_h.status = CAM_DEV_NOT_THERE;
1593 			xpt_done(ccb);
1594 			return;
1595 		}
1596 	}
1597 	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,
1598 	    (ccb->ccb_h.flags & CAM_SEND_STATUS) != 0, ((ccb->ccb_h.flags & CAM_SEND_SENSE)? ccb->csio.sense_len : 0));
1599 
1600 	switch (how) {
1601 	case FROM_TIMER:
1602 	case FROM_CAM:
1603 		/*
1604 		 * Insert at the tail of the list, if any, waiting CTIO CCBs
1605 		 */
1606 		TAILQ_INSERT_TAIL(&tptr->waitq, &ccb->ccb_h, periph_links.tqe);
1607 		break;
1608 	case FROM_SRR:
1609 	case FROM_CTIO_DONE:
1610 		TAILQ_INSERT_HEAD(&tptr->waitq, &ccb->ccb_h, periph_links.tqe);
1611 		break;
1612 	}
1613 
1614 	while (TAILQ_FIRST(&tptr->waitq) != NULL) {
1615 		ccb = (union ccb *) TAILQ_FIRST(&tptr->waitq);
1616 		TAILQ_REMOVE(&tptr->waitq, &ccb->ccb_h, periph_links.tqe);
1617 
1618 		cso = &ccb->csio;
1619 		xfrlen = cso->dxfer_len;
1620 		if (xfrlen == 0) {
1621 			if ((ccb->ccb_h.flags & CAM_SEND_STATUS) == 0) {
1622 				ISP_PATH_PRT(isp, ISP_LOGERR, ccb->ccb_h.path, "a data transfer length of zero but no status to send is wrong\n");
1623 				ccb->ccb_h.status = CAM_REQ_INVALID;
1624 				xpt_done(ccb);
1625 				continue;
1626 			}
1627 		}
1628 
1629 		atp = isp_find_atpd(isp, tptr, cso->tag_id);
1630 		if (atp == NULL) {
1631 			isp_prt(isp, ISP_LOGERR, "%s: [0x%x] cannot find private data adjunct in %s", __func__, cso->tag_id, __func__);
1632 			isp_dump_atpd(isp, tptr);
1633 			ccb->ccb_h.status = CAM_REQ_CMP_ERR;
1634 			xpt_done(ccb);
1635 			continue;
1636 		}
1637 
1638 		/*
1639 		 * Is this command a dead duck?
1640 		 */
1641 		if (atp->dead) {
1642 			isp_prt(isp, ISP_LOGERR, "%s: [0x%x] not sending a CTIO for a dead command", __func__, cso->tag_id);
1643 			ccb->ccb_h.status = CAM_REQ_ABORTED;
1644 			xpt_done(ccb);
1645 			continue;
1646 		}
1647 
1648 		/*
1649 		 * Check to make sure we're still in target mode.
1650 		 */
1651 		fcp = FCPARAM(isp, XS_CHANNEL(ccb));
1652 		if ((fcp->role & ISP_ROLE_TARGET) == 0) {
1653 			isp_prt(isp, ISP_LOGERR, "%s: [0x%x] stopping sending a CTIO because we're no longer in target mode", __func__, cso->tag_id);
1654 			ccb->ccb_h.status = CAM_PROVIDE_FAIL;
1655 			xpt_done(ccb);
1656 			continue;
1657 		}
1658 
1659 		/*
1660 		 * We're only handling ATPD_CCB_OUTSTANDING outstanding CCB at a time (one of which
1661 		 * could be split into two CTIOs to split data and status).
1662 		 */
1663 		if (atp->ctcnt >= ATPD_CCB_OUTSTANDING) {
1664 			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);
1665 			TAILQ_INSERT_HEAD(&tptr->waitq, &ccb->ccb_h, periph_links.tqe);
1666 			break;
1667 		}
1668 
1669 		/*
1670 		 * Does the initiator expect FC-Tape style responses?
1671 		 */
1672 		if ((atp->word3 & PRLI_WD3_RETRY) && fcp->fctape_enabled) {
1673 			fctape = 1;
1674 		} else {
1675 			fctape = 0;
1676 		}
1677 
1678 		/*
1679 		 * If we already did the data xfer portion of a CTIO that sends data
1680 		 * and status, don't do it again and do the status portion now.
1681 		 */
1682 		if (atp->sendst) {
1683 			isp_prt(isp, ISP_LOGTINFO, "[0x%x] now sending synthesized status orig_dl=%u xfered=%u bit=%u",
1684 			    cso->tag_id, atp->orig_datalen, atp->bytes_xfered, atp->bytes_in_transit);
1685 			xfrlen = 0;	/* we already did the data transfer */
1686 			atp->sendst = 0;
1687 		}
1688 		if (ccb->ccb_h.flags & CAM_SEND_STATUS) {
1689 			sendstatus = 1;
1690 		} else {
1691 			sendstatus = 0;
1692 		}
1693 
1694 		if (ccb->ccb_h.flags & CAM_SEND_SENSE) {
1695 			KASSERT((sendstatus != 0), ("how can you have CAM_SEND_SENSE w/o CAM_SEND_STATUS?"));
1696 			/*
1697 			 * Sense length is not the entire sense data structure size. Periph
1698 			 * drivers don't seem to be setting sense_len to reflect the actual
1699 			 * size. We'll peek inside to get the right amount.
1700 			 */
1701 			sense_length = cso->sense_len;
1702 
1703 			/*
1704 			 * This 'cannot' happen
1705 			 */
1706 			if (sense_length > (XCMD_SIZE - MIN_FCP_RESPONSE_SIZE)) {
1707 				sense_length = XCMD_SIZE - MIN_FCP_RESPONSE_SIZE;
1708 			}
1709 		} else {
1710 			sense_length = 0;
1711 		}
1712 
1713 		memset(local, 0, QENTRY_LEN);
1714 
1715 		/*
1716 		 * Check for overflow
1717 		 */
1718 		tmp = atp->bytes_xfered + atp->bytes_in_transit + xfrlen;
1719 		if (tmp > atp->orig_datalen) {
1720 			isp_prt(isp, ISP_LOGERR, "%s: [0x%x] data overflow by %u bytes", __func__, cso->tag_id, tmp - atp->orig_datalen);
1721 			ccb->ccb_h.status = CAM_DATA_RUN_ERR;
1722 			xpt_done(ccb);
1723 			continue;
1724 		}
1725 
1726 		if (IS_24XX(isp)) {
1727 			ct7_entry_t *cto = (ct7_entry_t *) local;
1728 
1729 			cto->ct_header.rqs_entry_type = RQSTYPE_CTIO7;
1730 			cto->ct_header.rqs_entry_count = 1;
1731 			cto->ct_header.rqs_seqno |= ATPD_SEQ_NOTIFY_CAM;
1732 			ATPD_SET_SEQNO(cto, atp);
1733 			cto->ct_nphdl = atp->nphdl;
1734 			cto->ct_rxid = atp->tag;
1735 			cto->ct_iid_lo = atp->portid;
1736 			cto->ct_iid_hi = atp->portid >> 16;
1737 			cto->ct_oxid = atp->oxid;
1738 			cto->ct_vpidx = ISP_GET_VPIDX(isp, XS_CHANNEL(ccb));
1739 			cto->ct_timeout = 120;
1740 			cto->ct_flags = atp->tattr << CT7_TASK_ATTR_SHIFT;
1741 
1742 			/*
1743 			 * Mode 1, status, no data. Only possible when we are sending status, have
1744 			 * no data to transfer, and any sense data can fit into a ct7_entry_t.
1745 			 *
1746 			 * Mode 2, status, no data. We have to use this in the case that
1747 			 * the sense data won't fit into a ct7_entry_t.
1748 			 *
1749 			 */
1750 			if (sendstatus && xfrlen == 0) {
1751 				cto->ct_flags |= CT7_SENDSTATUS | CT7_NO_DATA;
1752 				resid = atp->orig_datalen - atp->bytes_xfered - atp->bytes_in_transit;
1753 				if (sense_length <= MAXRESPLEN_24XX) {
1754 					if (resid < 0) {
1755 						cto->ct_resid = -resid;
1756 					} else if (resid > 0) {
1757 						cto->ct_resid = resid;
1758 					}
1759 					cto->ct_flags |= CT7_FLAG_MODE1;
1760 					cto->ct_scsi_status = cso->scsi_status;
1761 					if (resid < 0) {
1762 						cto->ct_scsi_status |= (FCP_RESID_OVERFLOW << 8);
1763 					} else if (resid > 0) {
1764 						cto->ct_scsi_status |= (FCP_RESID_UNDERFLOW << 8);
1765 					}
1766 					if (fctape) {
1767 						cto->ct_flags |= CT7_CONFIRM|CT7_EXPLCT_CONF;
1768 					}
1769 					if (sense_length) {
1770 						cto->ct_scsi_status |= (FCP_SNSLEN_VALID << 8);
1771 						cto->rsp.m1.ct_resplen = cto->ct_senselen = sense_length;
1772 						memcpy(cto->rsp.m1.ct_resp, &cso->sense_data, sense_length);
1773 					}
1774 				} else {
1775 					bus_addr_t addr;
1776 					char buf[XCMD_SIZE];
1777 					fcp_rsp_iu_t *rp;
1778 
1779 					if (atp->ests == NULL) {
1780 						atp->ests = isp_get_ecmd(isp);
1781 						if (atp->ests == NULL) {
1782 							TAILQ_INSERT_HEAD(&tptr->waitq, &ccb->ccb_h, periph_links.tqe);
1783 							break;
1784 						}
1785 					}
1786 					memset(buf, 0, sizeof (buf));
1787 					rp = (fcp_rsp_iu_t *)buf;
1788 					if (fctape) {
1789 						cto->ct_flags |= CT7_CONFIRM|CT7_EXPLCT_CONF;
1790 						rp->fcp_rsp_bits |= FCP_CONF_REQ;
1791 					}
1792 					cto->ct_flags |= CT7_FLAG_MODE2;
1793 	        			rp->fcp_rsp_scsi_status = cso->scsi_status;
1794 					if (resid < 0) {
1795 						rp->fcp_rsp_resid = -resid;
1796 						rp->fcp_rsp_bits |= FCP_RESID_OVERFLOW;
1797 					} else if (resid > 0) {
1798 						rp->fcp_rsp_resid = resid;
1799 						rp->fcp_rsp_bits |= FCP_RESID_UNDERFLOW;
1800 					}
1801 					if (sense_length) {
1802 	        				rp->fcp_rsp_snslen = sense_length;
1803 						cto->ct_senselen = sense_length;
1804 						rp->fcp_rsp_bits |= FCP_SNSLEN_VALID;
1805 						isp_put_fcp_rsp_iu(isp, rp, atp->ests);
1806 						memcpy(((fcp_rsp_iu_t *)atp->ests)->fcp_rsp_extra, &cso->sense_data, sense_length);
1807 					} else {
1808 						isp_put_fcp_rsp_iu(isp, rp, atp->ests);
1809 					}
1810 					if (isp->isp_dblev & ISP_LOGTDEBUG1) {
1811 						isp_print_bytes(isp, "FCP Response Frame After Swizzling", MIN_FCP_RESPONSE_SIZE + sense_length, atp->ests);
1812 					}
1813 					addr = isp->isp_osinfo.ecmd_dma;
1814 					addr += ((((isp_ecmd_t *)atp->ests) - isp->isp_osinfo.ecmd_base) * XCMD_SIZE);
1815 					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,
1816 					    (uintmax_t) isp->isp_osinfo.ecmd_dma, (uintmax_t)addr, MIN_FCP_RESPONSE_SIZE + sense_length);
1817 					cto->rsp.m2.ct_datalen = MIN_FCP_RESPONSE_SIZE + sense_length;
1818 					cto->rsp.m2.ct_fcp_rsp_iudata.ds_base = DMA_LO32(addr);
1819 					cto->rsp.m2.ct_fcp_rsp_iudata.ds_basehi = DMA_HI32(addr);
1820 					cto->rsp.m2.ct_fcp_rsp_iudata.ds_count = MIN_FCP_RESPONSE_SIZE + sense_length;
1821 				}
1822 				if (sense_length) {
1823 					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__,
1824 					    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,
1825 					    cso->sense_data.error_code, cso->sense_data.sense_buf[1], cso->sense_data.sense_buf[11], cso->sense_data.sense_buf[12]);
1826 				} else {
1827 					isp_prt(isp, ISP_LOGDEBUG0, "%s: CTIO7[0x%x] seq %u nc %d CDB0=%x sstatus=0x%x flags=0x%x resid=%d", __func__,
1828 					    cto->ct_rxid, ATPD_GET_SEQNO(cto), ATPD_GET_NCAM(cto), atp->cdb0, cto->ct_scsi_status, cto->ct_flags, cto->ct_resid);
1829 				}
1830 				atp->state = ATPD_STATE_LAST_CTIO;
1831 			}
1832 
1833 			/*
1834 			 * Mode 0 data transfers, *possibly* with status.
1835 			 */
1836 			if (xfrlen != 0) {
1837 				cto->ct_flags |= CT7_FLAG_MODE0;
1838 				if ((cso->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
1839 					cto->ct_flags |= CT7_DATA_IN;
1840 				} else {
1841 					cto->ct_flags |= CT7_DATA_OUT;
1842 				}
1843 
1844 				cto->rsp.m0.reloff = atp->bytes_xfered + atp->bytes_in_transit;
1845 				cto->rsp.m0.ct_xfrlen = xfrlen;
1846 
1847 #ifdef	DEBUG
1848 				if (ISP_FC_PC(isp, XS_CHANNEL(ccb))->inject_lost_data_frame && xfrlen > ISP_FC_PC(isp, XS_CHANNEL(ccb))->inject_lost_data_frame) {
1849 					isp_prt(isp, ISP_LOGWARN, "%s: truncating data frame with xfrlen %d to %d", __func__, xfrlen, xfrlen - (xfrlen >> 2));
1850 					ISP_FC_PC(isp, XS_CHANNEL(ccb))->inject_lost_data_frame = 0;
1851 					cto->rsp.m0.ct_xfrlen -= xfrlen >> 2;
1852 				}
1853 #endif
1854 				if (sendstatus) {
1855 					resid = atp->orig_datalen - atp->bytes_xfered - xfrlen;
1856 					if (cso->scsi_status == SCSI_STATUS_OK && resid == 0 /* && fctape == 0 */) {
1857 						cto->ct_flags |= CT7_SENDSTATUS;
1858 						atp->state = ATPD_STATE_LAST_CTIO;
1859 						if (fctape) {
1860 							cto->ct_flags |= CT7_CONFIRM|CT7_EXPLCT_CONF;
1861 						}
1862 					} else {
1863 						atp->sendst = 1;	/* send status later */
1864 						cto->ct_header.rqs_seqno &= ~ATPD_SEQ_NOTIFY_CAM;
1865 						atp->state = ATPD_STATE_CTIO;
1866 					}
1867 				} else {
1868 					atp->state = ATPD_STATE_CTIO;
1869 				}
1870 				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__,
1871 				    cto->ct_rxid, ATPD_GET_SEQNO(cto), ATPD_GET_NCAM(cto), atp->cdb0, cto->ct_scsi_status, cto->ct_flags, xfrlen, atp->bytes_xfered);
1872 			}
1873 		} else if (IS_FC(isp)) {
1874 			ct2_entry_t *cto = (ct2_entry_t *) local;
1875 
1876 			if (isp->isp_osinfo.sixtyfourbit)
1877 				cto->ct_header.rqs_entry_type = RQSTYPE_CTIO3;
1878 			else
1879 				cto->ct_header.rqs_entry_type = RQSTYPE_CTIO2;
1880 			cto->ct_header.rqs_entry_count = 1;
1881 			cto->ct_header.rqs_seqno |= ATPD_SEQ_NOTIFY_CAM;
1882 			ATPD_SET_SEQNO(cto, atp);
1883 			if (ISP_CAP_2KLOGIN(isp) == 0) {
1884 				((ct2e_entry_t *)cto)->ct_iid = cso->init_id;
1885 			} else {
1886 				cto->ct_iid = cso->init_id;
1887 				if (ISP_CAP_SCCFW(isp) == 0) {
1888 					cto->ct_lun = ccb->ccb_h.target_lun;
1889 				}
1890 			}
1891 			cto->ct_timeout = 10;
1892 			cto->ct_rxid = cso->tag_id;
1893 
1894 			/*
1895 			 * Mode 1, status, no data. Only possible when we are sending status, have
1896 			 * no data to transfer, and the sense length can fit in the ct7_entry.
1897 			 *
1898 			 * Mode 2, status, no data. We have to use this in the case the response
1899 			 * length won't fit into a ct2_entry_t.
1900 			 *
1901 			 * We'll fill out this structure with information as if this were a
1902 			 * Mode 1. The hardware layer will create the Mode 2 FCP RSP IU as
1903 			 * needed based upon this.
1904 			 */
1905 			if (sendstatus && xfrlen == 0) {
1906 				cto->ct_flags |= CT2_SENDSTATUS | CT2_NO_DATA;
1907 				resid = atp->orig_datalen - atp->bytes_xfered - atp->bytes_in_transit;
1908 				if (sense_length <= MAXRESPLEN) {
1909 					if (resid < 0) {
1910 						cto->ct_resid = -resid;
1911 					} else if (resid > 0) {
1912 						cto->ct_resid = resid;
1913 					}
1914 					cto->ct_flags |= CT2_FLAG_MODE1;
1915 					cto->rsp.m1.ct_scsi_status = cso->scsi_status;
1916 					if (resid < 0) {
1917 						cto->rsp.m1.ct_scsi_status |= CT2_DATA_OVER;
1918 					} else if (resid > 0) {
1919 						cto->rsp.m1.ct_scsi_status |= CT2_DATA_UNDER;
1920 					}
1921 					if (fctape) {
1922 						cto->ct_flags |= CT2_CONFIRM;
1923 					}
1924 					if (sense_length) {
1925 						cto->rsp.m1.ct_scsi_status |= CT2_SNSLEN_VALID;
1926 						cto->rsp.m1.ct_resplen = cto->rsp.m1.ct_senselen = sense_length;
1927 						memcpy(cto->rsp.m1.ct_resp, &cso->sense_data, sense_length);
1928 					}
1929 				} else {
1930 					bus_addr_t addr;
1931 					char buf[XCMD_SIZE];
1932 					fcp_rsp_iu_t *rp;
1933 
1934 					if (atp->ests == NULL) {
1935 						atp->ests = isp_get_ecmd(isp);
1936 						if (atp->ests == NULL) {
1937 							TAILQ_INSERT_HEAD(&tptr->waitq, &ccb->ccb_h, periph_links.tqe);
1938 							break;
1939 						}
1940 					}
1941 					memset(buf, 0, sizeof (buf));
1942 					rp = (fcp_rsp_iu_t *)buf;
1943 					if (fctape) {
1944 						cto->ct_flags |= CT2_CONFIRM;
1945 						rp->fcp_rsp_bits |= FCP_CONF_REQ;
1946 					}
1947 					cto->ct_flags |= CT2_FLAG_MODE2;
1948 	        			rp->fcp_rsp_scsi_status = cso->scsi_status;
1949 					if (resid < 0) {
1950 						rp->fcp_rsp_resid = -resid;
1951 						rp->fcp_rsp_bits |= FCP_RESID_OVERFLOW;
1952 					} else if (resid > 0) {
1953 						rp->fcp_rsp_resid = resid;
1954 						rp->fcp_rsp_bits |= FCP_RESID_UNDERFLOW;
1955 					}
1956 					if (sense_length) {
1957 	        				rp->fcp_rsp_snslen = sense_length;
1958 						rp->fcp_rsp_bits |= FCP_SNSLEN_VALID;
1959 						isp_put_fcp_rsp_iu(isp, rp, atp->ests);
1960 						memcpy(((fcp_rsp_iu_t *)atp->ests)->fcp_rsp_extra, &cso->sense_data, sense_length);
1961 					} else {
1962 						isp_put_fcp_rsp_iu(isp, rp, atp->ests);
1963 					}
1964 					if (isp->isp_dblev & ISP_LOGTDEBUG1) {
1965 						isp_print_bytes(isp, "FCP Response Frame After Swizzling", MIN_FCP_RESPONSE_SIZE + sense_length, atp->ests);
1966 					}
1967 					addr = isp->isp_osinfo.ecmd_dma;
1968 					addr += ((((isp_ecmd_t *)atp->ests) - isp->isp_osinfo.ecmd_base) * XCMD_SIZE);
1969 					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,
1970 					    (uintmax_t) isp->isp_osinfo.ecmd_dma, (uintmax_t)addr, MIN_FCP_RESPONSE_SIZE + sense_length);
1971 					cto->rsp.m2.ct_datalen = MIN_FCP_RESPONSE_SIZE + sense_length;
1972 					if (isp->isp_osinfo.sixtyfourbit) {
1973 						cto->rsp.m2.u.ct_fcp_rsp_iudata_64.ds_base = DMA_LO32(addr);
1974 						cto->rsp.m2.u.ct_fcp_rsp_iudata_64.ds_basehi = DMA_HI32(addr);
1975 						cto->rsp.m2.u.ct_fcp_rsp_iudata_64.ds_count = MIN_FCP_RESPONSE_SIZE + sense_length;
1976 					} else {
1977 						cto->rsp.m2.u.ct_fcp_rsp_iudata_32.ds_base = DMA_LO32(addr);
1978 						cto->rsp.m2.u.ct_fcp_rsp_iudata_32.ds_count = MIN_FCP_RESPONSE_SIZE + sense_length;
1979 					}
1980 				}
1981 				if (sense_length) {
1982 					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__,
1983 					    cto->ct_rxid, ATPD_GET_SEQNO(cto), ATPD_GET_NCAM(cto), atp->cdb0, cso->scsi_status, cto->ct_flags, cto->ct_resid,
1984 					    cso->sense_data.error_code, cso->sense_data.sense_buf[1], cso->sense_data.sense_buf[11], cso->sense_data.sense_buf[12]);
1985 				} else {
1986 					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,
1987 					    ATPD_GET_SEQNO(cto), ATPD_GET_NCAM(cto), atp->cdb0, cso->scsi_status, cto->ct_flags, cto->ct_resid);
1988 				}
1989 				atp->state = ATPD_STATE_LAST_CTIO;
1990 			}
1991 
1992 			if (xfrlen != 0) {
1993 				cto->ct_flags |= CT2_FLAG_MODE0;
1994 				if ((cso->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
1995 					cto->ct_flags |= CT2_DATA_IN;
1996 				} else {
1997 					cto->ct_flags |= CT2_DATA_OUT;
1998 				}
1999 
2000 				cto->ct_reloff = atp->bytes_xfered + atp->bytes_in_transit;
2001 				cto->rsp.m0.ct_xfrlen = xfrlen;
2002 
2003 				if (sendstatus) {
2004 					resid = atp->orig_datalen - atp->bytes_xfered - xfrlen;
2005 					if (cso->scsi_status == SCSI_STATUS_OK && resid == 0 /*&& fctape == 0*/) {
2006 						cto->ct_flags |= CT2_SENDSTATUS;
2007 						atp->state = ATPD_STATE_LAST_CTIO;
2008 						if (fctape) {
2009 							cto->ct_flags |= CT2_CONFIRM;
2010 						}
2011 					} else {
2012 						atp->sendst = 1;	/* send status later */
2013 						cto->ct_header.rqs_seqno &= ~ATPD_SEQ_NOTIFY_CAM;
2014 						atp->state = ATPD_STATE_CTIO;
2015 					}
2016 				} else {
2017 					atp->state = ATPD_STATE_CTIO;
2018 				}
2019 			}
2020 			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,
2021 			    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);
2022 		} else {
2023 			ct_entry_t *cto = (ct_entry_t *) local;
2024 
2025 			cto->ct_header.rqs_entry_type = RQSTYPE_CTIO;
2026 			cto->ct_header.rqs_entry_count = 1;
2027 			cto->ct_header.rqs_seqno |= ATPD_SEQ_NOTIFY_CAM;
2028 			ATPD_SET_SEQNO(cto, atp);
2029 			cto->ct_iid = cso->init_id;
2030 			cto->ct_iid |= XS_CHANNEL(ccb) << 7;
2031 			cto->ct_tgt = ccb->ccb_h.target_id;
2032 			cto->ct_lun = ccb->ccb_h.target_lun;
2033 			cto->ct_fwhandle = cso->tag_id;
2034 			if (atp->rxid) {
2035 				cto->ct_tag_val = atp->rxid;
2036 				cto->ct_flags |= CT_TQAE;
2037 			}
2038 			if (ccb->ccb_h.flags & CAM_DIS_DISCONNECT) {
2039 				cto->ct_flags |= CT_NODISC;
2040 			}
2041 			if (cso->dxfer_len == 0) {
2042 				cto->ct_flags |= CT_NO_DATA;
2043 			} else if ((cso->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
2044 				cto->ct_flags |= CT_DATA_IN;
2045 			} else {
2046 				cto->ct_flags |= CT_DATA_OUT;
2047 			}
2048 			if (ccb->ccb_h.flags & CAM_SEND_STATUS) {
2049 				cto->ct_flags |= CT_SENDSTATUS|CT_CCINCR;
2050 				cto->ct_scsi_status = cso->scsi_status;
2051 				cto->ct_resid = atp->orig_datalen - atp->bytes_xfered - atp->bytes_in_transit - xfrlen;
2052 				isp_prt(isp, ISP_LOGTDEBUG0, "%s: CTIO[%x] seq %u nc %d scsi status %x resid %d tag_id %x", __func__,
2053 				    cto->ct_fwhandle, ATPD_GET_SEQNO(cto), ATPD_GET_NCAM(cto), cso->scsi_status, cso->resid, cso->tag_id);
2054 			}
2055 			ccb->ccb_h.flags &= ~CAM_SEND_SENSE;
2056 			cto->ct_timeout = 10;
2057 		}
2058 
2059 		if (isp_get_pcmd(isp, ccb)) {
2060 			ISP_PATH_PRT(isp, ISP_LOGWARN, ccb->ccb_h.path, "out of PCMDs\n");
2061 			TAILQ_INSERT_HEAD(&tptr->waitq, &ccb->ccb_h, periph_links.tqe);
2062 			break;
2063 		}
2064 		if (isp_allocate_xs_tgt(isp, ccb, &handle)) {
2065 			ISP_PATH_PRT(isp, ISP_LOGWARN, ccb->ccb_h.path, "No XFLIST pointers for %s\n", __func__);
2066 			TAILQ_INSERT_HEAD(&tptr->waitq, &ccb->ccb_h, periph_links.tqe);
2067 			isp_free_pcmd(isp, ccb);
2068 			break;
2069 		}
2070 		atp->bytes_in_transit += xfrlen;
2071 		PISP_PCMD(ccb)->datalen = xfrlen;
2072 
2073 
2074 		/*
2075 		 * Call the dma setup routines for this entry (and any subsequent
2076 		 * CTIOs) if there's data to move, and then tell the f/w it's got
2077 		 * new things to play with. As with isp_start's usage of DMA setup,
2078 		 * any swizzling is done in the machine dependent layer. Because
2079 		 * of this, we put the request onto the queue area first in native
2080 		 * format.
2081 		 */
2082 
2083 		if (IS_24XX(isp)) {
2084 			ct7_entry_t *cto = (ct7_entry_t *) local;
2085 			cto->ct_syshandle = handle;
2086 		} else if (IS_FC(isp)) {
2087 			ct2_entry_t *cto = (ct2_entry_t *) local;
2088 			cto->ct_syshandle = handle;
2089 		} else {
2090 			ct_entry_t *cto = (ct_entry_t *) local;
2091 			cto->ct_syshandle = handle;
2092 		}
2093 
2094 		dmaresult = ISP_DMASETUP(isp, cso, (ispreq_t *) local);
2095 		if (dmaresult != CMD_QUEUED) {
2096 			isp_destroy_tgt_handle(isp, handle);
2097 			isp_free_pcmd(isp, ccb);
2098 			if (dmaresult == CMD_EAGAIN) {
2099 				TAILQ_INSERT_HEAD(&tptr->waitq, &ccb->ccb_h, periph_links.tqe);
2100 				break;
2101 			}
2102 			ccb->ccb_h.status = CAM_REQ_CMP_ERR;
2103 			xpt_done(ccb);
2104 			continue;
2105 		}
2106 		isp->isp_nactive++;
2107 		ccb->ccb_h.status = CAM_REQ_INPROG | CAM_SIM_QUEUED;
2108 		if (xfrlen) {
2109 			ccb->ccb_h.spriv_field0 = atp->bytes_xfered;
2110 		} else {
2111 			ccb->ccb_h.spriv_field0 = ~0;
2112 		}
2113 		atp->ctcnt++;
2114 		atp->seqno++;
2115 	}
2116 	rls_lun_statep(isp, tptr);
2117 }
2118 
2119 static void
2120 isp_refire_putback_atio(void *arg)
2121 {
2122 	union ccb *ccb = arg;
2123 	ispsoftc_t *isp = XS_ISP(ccb);
2124 	ISP_LOCK(isp);
2125 	isp_target_putback_atio(ccb);
2126 	ISP_UNLOCK(isp);
2127 }
2128 
2129 static void
2130 isp_refire_notify_ack(void *arg)
2131 {
2132 	isp_tna_t *tp  = arg;
2133 	ispsoftc_t *isp = tp->isp;
2134 	ISP_LOCK(isp);
2135 	if (isp_notify_ack(isp, tp->not)) {
2136 		(void) timeout(isp_refire_notify_ack, tp, 5);
2137 	} else {
2138 		free(tp, M_DEVBUF);
2139 	}
2140 	ISP_UNLOCK(isp);
2141 }
2142 
2143 
2144 static void
2145 isp_target_putback_atio(union ccb *ccb)
2146 {
2147 	ispsoftc_t *isp;
2148 	struct ccb_scsiio *cso;
2149 	void *qe;
2150 
2151 	isp = XS_ISP(ccb);
2152 
2153 	qe = isp_getrqentry(isp);
2154 	if (qe == NULL) {
2155 		xpt_print(ccb->ccb_h.path, rqo, __func__);
2156 		(void) timeout(isp_refire_putback_atio, ccb, 10);
2157 		return;
2158 	}
2159 	memset(qe, 0, QENTRY_LEN);
2160 	cso = &ccb->csio;
2161 	if (IS_FC(isp)) {
2162 		at2_entry_t local, *at = &local;
2163 		ISP_MEMZERO(at, sizeof (at2_entry_t));
2164 		at->at_header.rqs_entry_type = RQSTYPE_ATIO2;
2165 		at->at_header.rqs_entry_count = 1;
2166 		if (ISP_CAP_SCCFW(isp)) {
2167 			at->at_scclun = (uint16_t) ccb->ccb_h.target_lun;
2168 		} else {
2169 			at->at_lun = (uint8_t) ccb->ccb_h.target_lun;
2170 		}
2171 		at->at_status = CT_OK;
2172 		at->at_rxid = cso->tag_id;
2173 		at->at_iid = cso->ccb_h.target_id;
2174 		isp_put_atio2(isp, at, qe);
2175 	} else {
2176 		at_entry_t local, *at = &local;
2177 		ISP_MEMZERO(at, sizeof (at_entry_t));
2178 		at->at_header.rqs_entry_type = RQSTYPE_ATIO;
2179 		at->at_header.rqs_entry_count = 1;
2180 		at->at_iid = cso->init_id;
2181 		at->at_iid |= XS_CHANNEL(ccb) << 7;
2182 		at->at_tgt = cso->ccb_h.target_id;
2183 		at->at_lun = cso->ccb_h.target_lun;
2184 		at->at_status = CT_OK;
2185 		at->at_tag_val = AT_GET_TAG(cso->tag_id);
2186 		at->at_handle = AT_GET_HANDLE(cso->tag_id);
2187 		isp_put_atio(isp, at, qe);
2188 	}
2189 	ISP_TDQE(isp, "isp_target_putback_atio", isp->isp_reqidx, qe);
2190 	ISP_SYNC_REQUEST(isp);
2191 	isp_complete_ctio(ccb);
2192 }
2193 
2194 static void
2195 isp_complete_ctio(union ccb *ccb)
2196 {
2197 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_INPROG) {
2198 		ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
2199 		xpt_done(ccb);
2200 	}
2201 }
2202 
2203 /*
2204  * Handle ATIO stuff that the generic code can't.
2205  * This means handling CDBs.
2206  */
2207 
2208 static void
2209 isp_handle_platform_atio(ispsoftc_t *isp, at_entry_t *aep)
2210 {
2211 	tstate_t *tptr;
2212 	int status, bus;
2213 	struct ccb_accept_tio *atiop;
2214 	atio_private_data_t *atp;
2215 
2216 	/*
2217 	 * The firmware status (except for the QLTM_SVALID bit)
2218 	 * indicates why this ATIO was sent to us.
2219 	 *
2220 	 * If QLTM_SVALID is set, the firmware has recommended Sense Data.
2221 	 *
2222 	 * If the DISCONNECTS DISABLED bit is set in the flags field,
2223 	 * we're still connected on the SCSI bus.
2224 	 */
2225 	status = aep->at_status;
2226 	if ((status & ~QLTM_SVALID) == AT_PHASE_ERROR) {
2227 		/*
2228 		 * Bus Phase Sequence error. We should have sense data
2229 		 * suggested by the f/w. I'm not sure quite yet what
2230 		 * to do about this for CAM.
2231 		 */
2232 		isp_prt(isp, ISP_LOGWARN, "PHASE ERROR");
2233 		isp_endcmd(isp, aep, SCSI_STATUS_BUSY, 0);
2234 		return;
2235 	}
2236 	if ((status & ~QLTM_SVALID) != AT_CDB) {
2237 		isp_prt(isp, ISP_LOGWARN, "bad atio (0x%x) leaked to platform", status);
2238 		isp_endcmd(isp, aep, SCSI_STATUS_BUSY, 0);
2239 		return;
2240 	}
2241 
2242 	bus = GET_BUS_VAL(aep->at_iid);
2243 	tptr = get_lun_statep(isp, bus, aep->at_lun);
2244 	if (tptr == NULL) {
2245 		tptr = get_lun_statep(isp, bus, CAM_LUN_WILDCARD);
2246 		if (tptr == NULL) {
2247 			/*
2248 			 * Because we can't autofeed sense data back with
2249 			 * a command for parallel SCSI, we can't give back
2250 			 * a CHECK CONDITION. We'll give back a BUSY status
2251 			 * instead. This works out okay because the only
2252 			 * time we should, in fact, get this, is in the
2253 			 * case that somebody configured us without the
2254 			 * blackhole driver, so they get what they deserve.
2255 			 */
2256 			isp_endcmd(isp, aep, SCSI_STATUS_BUSY, 0);
2257 			return;
2258 		}
2259 	}
2260 
2261 	atp = isp_get_atpd(isp, tptr, aep->at_handle);
2262 	atiop = (struct ccb_accept_tio *) SLIST_FIRST(&tptr->atios);
2263 	if (atiop == NULL || atp == NULL) {
2264 		/*
2265 		 * Because we can't autofeed sense data back with
2266 		 * a command for parallel SCSI, we can't give back
2267 		 * a CHECK CONDITION. We'll give back a QUEUE FULL status
2268 		 * instead. This works out okay because the only time we
2269 		 * should, in fact, get this, is in the case that we've
2270 		 * run out of ATIOS.
2271 		 */
2272 		xpt_print(tptr->owner, "no %s for lun %d from initiator %d\n", (atp == NULL && atiop == NULL)? "ATIOs *or* ATPS" :
2273 		    ((atp == NULL)? "ATPs" : "ATIOs"), aep->at_lun, aep->at_iid);
2274 		isp_endcmd(isp, aep, SCSI_STATUS_BUSY, 0);
2275 		if (atp) {
2276 			isp_put_atpd(isp, tptr, atp);
2277 		}
2278 		rls_lun_statep(isp, tptr);
2279 		return;
2280 	}
2281 	atp->rxid = aep->at_tag_val;
2282 	atp->state = ATPD_STATE_ATIO;
2283 	SLIST_REMOVE_HEAD(&tptr->atios, sim_links.sle);
2284 	tptr->atio_count--;
2285 	ISP_PATH_PRT(isp, ISP_LOGTDEBUG2, atiop->ccb_h.path, "Take FREE ATIO count now %d\n", tptr->atio_count);
2286 	atiop->ccb_h.target_id = aep->at_tgt;
2287 	atiop->ccb_h.target_lun = aep->at_lun;
2288 	if (aep->at_flags & AT_NODISC) {
2289 		atiop->ccb_h.flags |= CAM_DIS_DISCONNECT;
2290 	} else {
2291 		atiop->ccb_h.flags &= ~CAM_DIS_DISCONNECT;
2292 	}
2293 
2294 	if (status & QLTM_SVALID) {
2295 		size_t amt = ISP_MIN(QLTM_SENSELEN, sizeof (atiop->sense_data));
2296 		atiop->sense_len = amt;
2297 		ISP_MEMCPY(&atiop->sense_data, aep->at_sense, amt);
2298 	} else {
2299 		atiop->sense_len = 0;
2300 	}
2301 
2302 	atiop->init_id = GET_IID_VAL(aep->at_iid);
2303 	atiop->cdb_len = aep->at_cdblen;
2304 	ISP_MEMCPY(atiop->cdb_io.cdb_bytes, aep->at_cdb, aep->at_cdblen);
2305 	atiop->ccb_h.status = CAM_CDB_RECVD;
2306 	/*
2307 	 * Construct a tag 'id' based upon tag value (which may be 0..255)
2308 	 * and the handle (which we have to preserve).
2309 	 */
2310 	atiop->tag_id = atp->tag;
2311 	if (aep->at_flags & AT_TQAE) {
2312 		atiop->tag_action = aep->at_tag_type;
2313 		atiop->ccb_h.status |= CAM_TAG_ACTION_VALID;
2314 	}
2315 	atp->orig_datalen = 0;
2316 	atp->bytes_xfered = 0;
2317 	atp->lun = aep->at_lun;
2318 	atp->nphdl = aep->at_iid;
2319 	atp->portid = PORT_NONE;
2320 	atp->oxid = 0;
2321 	atp->cdb0 = atiop->cdb_io.cdb_bytes[0];
2322 	atp->tattr = aep->at_tag_type;
2323 	atp->state = ATPD_STATE_CAM;
2324 	isp_prt(isp, ISP_LOGTDEBUG0, "ATIO[0x%x] CDB=0x%x lun %d", aep->at_tag_val, atp->cdb0, atp->lun);
2325 	rls_lun_statep(isp, tptr);
2326 }
2327 
2328 static void
2329 isp_handle_platform_atio2(ispsoftc_t *isp, at2_entry_t *aep)
2330 {
2331 	lun_id_t lun;
2332 	fcportdb_t *lp;
2333 	tstate_t *tptr;
2334 	struct ccb_accept_tio *atiop;
2335 	uint16_t nphdl;
2336 	atio_private_data_t *atp;
2337 	inot_private_data_t *ntp;
2338 
2339 	/*
2340 	 * The firmware status (except for the QLTM_SVALID bit)
2341 	 * indicates why this ATIO was sent to us.
2342 	 *
2343 	 * If QLTM_SVALID is set, the firmware has recommended Sense Data.
2344 	 */
2345 	if ((aep->at_status & ~QLTM_SVALID) != AT_CDB) {
2346 		isp_prt(isp, ISP_LOGWARN, "bogus atio (0x%x) leaked to platform", aep->at_status);
2347 		isp_endcmd(isp, aep, SCSI_STATUS_BUSY, 0);
2348 		return;
2349 	}
2350 
2351 	if (ISP_CAP_SCCFW(isp)) {
2352 		lun = aep->at_scclun;
2353 	} else {
2354 		lun = aep->at_lun;
2355 	}
2356 	if (ISP_CAP_2KLOGIN(isp)) {
2357 		nphdl = ((at2e_entry_t *)aep)->at_iid;
2358 	} else {
2359 		nphdl = aep->at_iid;
2360 	}
2361 	tptr = get_lun_statep(isp, 0, lun);
2362 	if (tptr == NULL) {
2363 		tptr = get_lun_statep(isp, 0, CAM_LUN_WILDCARD);
2364 		if (tptr == NULL) {
2365 			isp_prt(isp, ISP_LOGWARN, "%s: [0x%x] no state pointer for lun %jx or wildcard", __func__, aep->at_rxid, (uintmax_t)lun);
2366 			if (lun == 0) {
2367 				isp_endcmd(isp, aep, SCSI_STATUS_BUSY, 0);
2368 			} else {
2369 				isp_endcmd(isp, aep, SCSI_STATUS_CHECK_COND | ECMD_SVALID | (0x5 << 12) | (0x25 << 16), 0);
2370 			}
2371 			return;
2372 		}
2373 	}
2374 
2375 	/*
2376 	 * Start any commands pending resources first.
2377 	 */
2378 	if (tptr->restart_queue) {
2379 		inot_private_data_t *restart_queue = tptr->restart_queue;
2380 		tptr->restart_queue = NULL;
2381 		while (restart_queue) {
2382 			ntp = restart_queue;
2383 			restart_queue = ntp->rd.nt.nt_hba;
2384 			isp_prt(isp, ISP_LOGTDEBUG0, "%s: restarting resrc deprived %x", __func__, ((at2_entry_t *)ntp->rd.data)->at_rxid);
2385 			isp_handle_platform_atio2(isp, (at2_entry_t *) ntp->rd.data);
2386 			isp_put_ntpd(isp, tptr, ntp);
2387 			/*
2388 			 * If a recursion caused the restart queue to start to fill again,
2389 			 * stop and splice the new list on top of the old list and restore
2390 			 * it and go to noresrc.
2391 			 */
2392 			if (tptr->restart_queue) {
2393 				ntp = tptr->restart_queue;
2394 				tptr->restart_queue = restart_queue;
2395 				while (restart_queue->rd.nt.nt_hba) {
2396 					restart_queue = restart_queue->rd.nt.nt_hba;
2397 				}
2398 				restart_queue->rd.nt.nt_hba = ntp;
2399 				goto noresrc;
2400 			}
2401 		}
2402 	}
2403 
2404 	atiop = (struct ccb_accept_tio *) SLIST_FIRST(&tptr->atios);
2405 	if (atiop == NULL) {
2406 		goto noresrc;
2407 	}
2408 
2409 	atp = isp_get_atpd(isp, tptr, aep->at_rxid);
2410 	if (atp == NULL) {
2411 		goto noresrc;
2412 	}
2413 
2414 	atp->state = ATPD_STATE_ATIO;
2415 	SLIST_REMOVE_HEAD(&tptr->atios, sim_links.sle);
2416 	tptr->atio_count--;
2417 	isp_prt(isp, ISP_LOGTDEBUG2, "Take FREE ATIO count now %d", tptr->atio_count);
2418 	atiop->ccb_h.target_id = FCPARAM(isp, 0)->isp_loopid;
2419 	atiop->ccb_h.target_lun = lun;
2420 
2421 	/*
2422 	 * We don't get 'suggested' sense data as we do with SCSI cards.
2423 	 */
2424 	atiop->sense_len = 0;
2425 	if (ISP_CAP_2KLOGIN(isp)) {
2426 		/*
2427 		 * NB: We could not possibly have 2K logins if we
2428 		 * NB: also did not have SCC FW.
2429 		 */
2430 		atiop->init_id = ((at2e_entry_t *)aep)->at_iid;
2431 	} else {
2432 		atiop->init_id = aep->at_iid;
2433 	}
2434 
2435 	/*
2436 	 * If we're not in the port database, add ourselves.
2437 	 */
2438 	if (!IS_2100(isp) && isp_find_pdb_by_loopid(isp, 0, atiop->init_id, &lp) == 0) {
2439     		uint64_t iid =
2440 			(((uint64_t) aep->at_wwpn[0]) << 48) |
2441 			(((uint64_t) aep->at_wwpn[1]) << 32) |
2442 			(((uint64_t) aep->at_wwpn[2]) << 16) |
2443 			(((uint64_t) aep->at_wwpn[3]) <<  0);
2444 		/*
2445 		 * However, make sure we delete ourselves if otherwise
2446 		 * we were there but at a different loop id.
2447 		 */
2448 		if (isp_find_pdb_by_wwn(isp, 0, iid, &lp)) {
2449 			isp_del_wwn_entry(isp, 0, iid, lp->handle, lp->portid);
2450 		}
2451 		isp_add_wwn_entry(isp, 0, iid, atiop->init_id, PORT_ANY, 0);
2452 	}
2453 	atiop->cdb_len = ATIO2_CDBLEN;
2454 	ISP_MEMCPY(atiop->cdb_io.cdb_bytes, aep->at_cdb, ATIO2_CDBLEN);
2455 	atiop->ccb_h.status = CAM_CDB_RECVD;
2456 	atiop->tag_id = atp->tag;
2457 	switch (aep->at_taskflags & ATIO2_TC_ATTR_MASK) {
2458 	case ATIO2_TC_ATTR_SIMPLEQ:
2459 		atiop->ccb_h.flags |= CAM_TAG_ACTION_VALID;
2460 		atiop->tag_action = MSG_SIMPLE_Q_TAG;
2461 		break;
2462 	case ATIO2_TC_ATTR_HEADOFQ:
2463 		atiop->ccb_h.flags |= CAM_TAG_ACTION_VALID;
2464 		atiop->tag_action = MSG_HEAD_OF_Q_TAG;
2465 		break;
2466 	case ATIO2_TC_ATTR_ORDERED:
2467 		atiop->ccb_h.flags |= CAM_TAG_ACTION_VALID;
2468 		atiop->tag_action = MSG_ORDERED_Q_TAG;
2469 		break;
2470 	case ATIO2_TC_ATTR_ACAQ:		/* ?? */
2471 	case ATIO2_TC_ATTR_UNTAGGED:
2472 	default:
2473 		atiop->tag_action = 0;
2474 		break;
2475 	}
2476 
2477 	atp->orig_datalen = aep->at_datalen;
2478 	atp->bytes_xfered = 0;
2479 	atp->lun = lun;
2480 	atp->nphdl = atiop->init_id;
2481 	atp->sid = PORT_ANY;
2482 	atp->oxid = aep->at_oxid;
2483 	atp->cdb0 = aep->at_cdb[0];
2484 	atp->tattr = aep->at_taskflags & ATIO2_TC_ATTR_MASK;
2485 	atp->state = ATPD_STATE_CAM;
2486 	xpt_done((union ccb *)atiop);
2487 	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);
2488 	rls_lun_statep(isp, tptr);
2489 	return;
2490 noresrc:
2491 	ntp = isp_get_ntpd(isp, tptr);
2492 	if (ntp == NULL) {
2493 		rls_lun_statep(isp, tptr);
2494 		isp_endcmd(isp, aep, nphdl, 0, SCSI_STATUS_BUSY, 0);
2495 		return;
2496 	}
2497 	memcpy(ntp->rd.data, aep, QENTRY_LEN);
2498 	ntp->rd.nt.nt_hba = tptr->restart_queue;
2499 	tptr->restart_queue = ntp;
2500 	rls_lun_statep(isp, tptr);
2501 }
2502 
2503 static void
2504 isp_handle_platform_atio7(ispsoftc_t *isp, at7_entry_t *aep)
2505 {
2506 	int cdbxlen;
2507 	uint16_t lun, chan, nphdl = NIL_HANDLE;
2508 	uint32_t did, sid;
2509 	uint64_t wwn = INI_NONE;
2510 	fcportdb_t *lp;
2511 	tstate_t *tptr;
2512 	struct ccb_accept_tio *atiop;
2513 	atio_private_data_t *atp = NULL;
2514 	atio_private_data_t *oatp;
2515 	inot_private_data_t *ntp;
2516 
2517 	did = (aep->at_hdr.d_id[0] << 16) | (aep->at_hdr.d_id[1] << 8) | aep->at_hdr.d_id[2];
2518 	sid = (aep->at_hdr.s_id[0] << 16) | (aep->at_hdr.s_id[1] << 8) | aep->at_hdr.s_id[2];
2519 	lun = (aep->at_cmnd.fcp_cmnd_lun[0] << 8) | aep->at_cmnd.fcp_cmnd_lun[1];
2520 
2521 	/*
2522 	 * Find the N-port handle, and Virtual Port Index for this command.
2523 	 *
2524 	 * If we can't, we're somewhat in trouble because we can't actually respond w/o that information.
2525 	 * We also, as a matter of course, need to know the WWN of the initiator too.
2526 	 */
2527 	if (ISP_CAP_MULTI_ID(isp)) {
2528 		/*
2529 		 * Find the right channel based upon D_ID
2530 		 */
2531 		isp_find_chan_by_did(isp, did, &chan);
2532 
2533 		if (chan == ISP_NOCHAN) {
2534 			NANOTIME_T now;
2535 
2536 			/*
2537 			 * If we don't recognizer our own D_DID, terminate the exchange, unless we're within 2 seconds of startup
2538 			 * It's a bit tricky here as we need to stash this command *somewhere*.
2539 			 */
2540 			GET_NANOTIME(&now);
2541 			if (NANOTIME_SUB(&isp->isp_init_time, &now) > 2000000000ULL) {
2542 				isp_prt(isp, ISP_LOGWARN, "%s: [RX_ID 0x%x] D_ID %x not found on any channel- dropping", __func__, aep->at_rxid, did);
2543 				isp_endcmd(isp, aep, NIL_HANDLE, ISP_NOCHAN, ECMD_TERMINATE, 0);
2544 				return;
2545 			}
2546 			tptr = get_lun_statep(isp, 0, 0);
2547 			if (tptr == NULL) {
2548 				tptr = get_lun_statep(isp, 0, CAM_LUN_WILDCARD);
2549 				if (tptr == NULL) {
2550 					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);
2551 					isp_endcmd(isp, aep, NIL_HANDLE, ISP_NOCHAN, ECMD_TERMINATE, 0);
2552 					return;
2553 				}
2554 			}
2555 			isp_prt(isp, ISP_LOGWARN, "%s: [RX_ID 0x%x] D_ID %x not found on any channel- deferring", __func__, aep->at_rxid, did);
2556 			goto noresrc;
2557 		}
2558 		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);
2559 	} else {
2560 		chan = 0;
2561 	}
2562 
2563 	/*
2564 	 * Find the PDB entry for this initiator
2565 	 */
2566 	if (isp_find_pdb_by_sid(isp, chan, sid, &lp) == 0) {
2567 		/*
2568 		 * If we're not in the port database terminate the exchange.
2569 		 */
2570 		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",
2571 		    __func__, aep->at_rxid, did, chan, sid);
2572 		isp_endcmd(isp, aep, NIL_HANDLE, chan, ECMD_TERMINATE, 0);
2573 		return;
2574 	}
2575 	nphdl = lp->handle;
2576 	wwn = lp->port_wwn;
2577 
2578 	/*
2579 	 * Get the tstate pointer
2580 	 */
2581 	tptr = get_lun_statep(isp, chan, lun);
2582 	if (tptr == NULL) {
2583 		tptr = get_lun_statep(isp, chan, CAM_LUN_WILDCARD);
2584 		if (tptr == NULL) {
2585 			isp_prt(isp, ISP_LOGWARN, "%s: [0x%x] no state pointer for lun %d or wildcard", __func__, aep->at_rxid, lun);
2586 			if (lun == 0) {
2587 				isp_endcmd(isp, aep, nphdl, SCSI_STATUS_BUSY, 0);
2588 			} else {
2589 				isp_endcmd(isp, aep, nphdl, chan, SCSI_STATUS_CHECK_COND | ECMD_SVALID | (0x5 << 12) | (0x25 << 16), 0);
2590 			}
2591 			return;
2592 		}
2593 	}
2594 
2595 	/*
2596 	 * Start any commands pending resources first.
2597 	 */
2598 	if (tptr->restart_queue) {
2599 		inot_private_data_t *restart_queue = tptr->restart_queue;
2600 		tptr->restart_queue = NULL;
2601 		while (restart_queue) {
2602 			ntp = restart_queue;
2603 			restart_queue = ntp->rd.nt.nt_hba;
2604 			isp_prt(isp, ISP_LOGTDEBUG0, "%s: restarting resrc deprived %x", __func__, ((at7_entry_t *)ntp->rd.data)->at_rxid);
2605 			isp_handle_platform_atio7(isp, (at7_entry_t *) ntp->rd.data);
2606 			isp_put_ntpd(isp, tptr, ntp);
2607 			/*
2608 			 * If a recursion caused the restart queue to start to fill again,
2609 			 * stop and splice the new list on top of the old list and restore
2610 			 * it and go to noresrc.
2611 			 */
2612 			if (tptr->restart_queue) {
2613 				isp_prt(isp, ISP_LOGTDEBUG0, "%s: restart queue refilling", __func__);
2614 				if (restart_queue) {
2615 					ntp = tptr->restart_queue;
2616 					tptr->restart_queue = restart_queue;
2617 					while (restart_queue->rd.nt.nt_hba) {
2618 						restart_queue = restart_queue->rd.nt.nt_hba;
2619 					}
2620 					restart_queue->rd.nt.nt_hba = ntp;
2621 				}
2622 				goto noresrc;
2623 			}
2624 		}
2625 	}
2626 
2627 	/*
2628 	 * If the f/w is out of resources, just send a BUSY status back.
2629 	 */
2630 	if (aep->at_rxid == AT7_NORESRC_RXID) {
2631 		rls_lun_statep(isp, tptr);
2632 		isp_endcmd(isp, aep, nphdl, chan, SCSI_BUSY, 0);
2633 		return;
2634 	}
2635 
2636 	/*
2637 	 * If we're out of resources, just send a BUSY status back.
2638 	 */
2639 	atiop = (struct ccb_accept_tio *) SLIST_FIRST(&tptr->atios);
2640 	if (atiop == NULL) {
2641 		isp_prt(isp, ISP_LOGTDEBUG0, "[0x%x] out of atios", aep->at_rxid);
2642 		goto noresrc;
2643 	}
2644 
2645 	oatp = isp_find_atpd(isp, tptr, aep->at_rxid);
2646 	if (oatp) {
2647 		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",
2648 		    aep->at_rxid, nphdl, sid, aep->at_hdr.ox_id, oatp->state);
2649 		/*
2650 		 * It's not a "no resource" condition- but we can treat it like one
2651 		 */
2652 		goto noresrc;
2653 	}
2654 	atp = isp_get_atpd(isp, tptr, aep->at_rxid);
2655 	if (atp == NULL) {
2656 		isp_prt(isp, ISP_LOGTDEBUG0, "[0x%x] out of atps", aep->at_rxid);
2657 		goto noresrc;
2658 	}
2659 	atp->word3 = lp->prli_word3;
2660 	atp->state = ATPD_STATE_ATIO;
2661 	SLIST_REMOVE_HEAD(&tptr->atios, sim_links.sle);
2662 	tptr->atio_count--;
2663 	ISP_PATH_PRT(isp, ISP_LOGTDEBUG2, atiop->ccb_h.path, "Take FREE ATIO count now %d\n", tptr->atio_count);
2664 	atiop->init_id = nphdl;
2665 	atiop->ccb_h.target_id = FCPARAM(isp, chan)->isp_loopid;
2666 	atiop->ccb_h.target_lun = lun;
2667 	atiop->sense_len = 0;
2668 	cdbxlen = aep->at_cmnd.fcp_cmnd_alen_datadir >> FCP_CMND_ADDTL_CDBLEN_SHIFT;
2669 	if (cdbxlen) {
2670 		isp_prt(isp, ISP_LOGWARN, "additional CDBLEN ignored");
2671 	}
2672 	cdbxlen = sizeof (aep->at_cmnd.cdb_dl.sf.fcp_cmnd_cdb);
2673 	ISP_MEMCPY(atiop->cdb_io.cdb_bytes, aep->at_cmnd.cdb_dl.sf.fcp_cmnd_cdb, cdbxlen);
2674 	atiop->cdb_len = cdbxlen;
2675 	atiop->ccb_h.status = CAM_CDB_RECVD;
2676 	atiop->tag_id = atp->tag;
2677 	switch (aep->at_cmnd.fcp_cmnd_task_attribute & FCP_CMND_TASK_ATTR_MASK) {
2678 	case FCP_CMND_TASK_ATTR_SIMPLE:
2679 		atiop->ccb_h.flags |= CAM_TAG_ACTION_VALID;
2680 		atiop->tag_action = MSG_SIMPLE_Q_TAG;
2681 		break;
2682 	case FCP_CMND_TASK_ATTR_HEAD:
2683 		atiop->ccb_h.flags |= CAM_TAG_ACTION_VALID;
2684 		atiop->tag_action = MSG_HEAD_OF_Q_TAG;
2685 		break;
2686 	case FCP_CMND_TASK_ATTR_ORDERED:
2687 		atiop->ccb_h.flags |= CAM_TAG_ACTION_VALID;
2688 		atiop->tag_action = MSG_ORDERED_Q_TAG;
2689 		break;
2690 	default:
2691 		/* FALLTHROUGH */
2692 	case FCP_CMND_TASK_ATTR_ACA:
2693 	case FCP_CMND_TASK_ATTR_UNTAGGED:
2694 		atiop->tag_action = 0;
2695 		break;
2696 	}
2697 	atp->orig_datalen = aep->at_cmnd.cdb_dl.sf.fcp_cmnd_dl;
2698 	atp->bytes_xfered = 0;
2699 	atp->lun = lun;
2700 	atp->nphdl = nphdl;
2701 	atp->portid = sid;
2702 	atp->oxid = aep->at_hdr.ox_id;
2703 	atp->rxid = aep->at_hdr.rx_id;
2704 	atp->cdb0 = atiop->cdb_io.cdb_bytes[0];
2705 	atp->tattr = aep->at_cmnd.fcp_cmnd_task_attribute & FCP_CMND_TASK_ATTR_MASK;
2706 	atp->state = ATPD_STATE_CAM;
2707 	isp_prt(isp, ISP_LOGTDEBUG0, "ATIO7[0x%x] CDB=0x%x lun %d datalen %u", aep->at_rxid, atp->cdb0, lun, atp->orig_datalen);
2708 	xpt_done((union ccb *)atiop);
2709 	rls_lun_statep(isp, tptr);
2710 	return;
2711 noresrc:
2712 	if (atp) {
2713 		isp_put_atpd(isp, tptr, atp);
2714 	}
2715 	ntp = isp_get_ntpd(isp, tptr);
2716 	if (ntp == NULL) {
2717 		rls_lun_statep(isp, tptr);
2718 		isp_endcmd(isp, aep, nphdl, chan, SCSI_STATUS_BUSY, 0);
2719 		return;
2720 	}
2721 	memcpy(ntp->rd.data, aep, QENTRY_LEN);
2722 	ntp->rd.nt.nt_hba = tptr->restart_queue;
2723 	tptr->restart_queue = ntp;
2724 	rls_lun_statep(isp, tptr);
2725 }
2726 
2727 
2728 /*
2729  * Handle starting an SRR (sequence retransmit request)
2730  * We get here when we've gotten the immediate notify
2731  * and the return of all outstanding CTIOs for this
2732  * transaction.
2733  */
2734 static void
2735 isp_handle_srr_start(ispsoftc_t *isp, tstate_t *tptr, atio_private_data_t *atp)
2736 {
2737 	in_fcentry_24xx_t *inot;
2738 	uint32_t srr_off, ccb_off, ccb_len, ccb_end;
2739 	union ccb *ccb;
2740 
2741 	inot = (in_fcentry_24xx_t *)atp->srr;
2742 	srr_off = inot->in_srr_reloff_lo | (inot->in_srr_reloff_hi << 16);
2743 	ccb = atp->srr_ccb;
2744 	atp->srr_ccb = NULL;
2745 	atp->nsrr++;
2746 	if (ccb == NULL) {
2747 		isp_prt(isp, ISP_LOGWARN, "SRR[0x%x] null ccb", atp->tag);
2748 		goto fail;
2749 	}
2750 
2751 	ccb_off = ccb->ccb_h.spriv_field0;
2752 	ccb_len = ccb->csio.dxfer_len;
2753         ccb_end = (ccb_off == ~0)? ~0 : ccb_off + ccb_len;
2754 
2755 	switch (inot->in_srr_iu) {
2756 	case R_CTL_INFO_SOLICITED_DATA:
2757 		/*
2758 		 * We have to restart a FCP_DATA data out transaction
2759 		 */
2760 		atp->sendst = 0;
2761 		atp->bytes_xfered = srr_off;
2762 		if (ccb_len == 0) {
2763 			isp_prt(isp, ISP_LOGWARN, "SRR[0x%x] SRR offset 0x%x but current CCB doesn't transfer data", atp->tag, srr_off);
2764 			goto mdp;
2765 		}
2766  		if (srr_off < ccb_off || ccb_off > srr_off + ccb_len) {
2767 			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);
2768 			goto mdp;
2769 		}
2770 		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);
2771 		break;
2772 	case R_CTL_INFO_COMMAND_STATUS:
2773 		isp_prt(isp, ISP_LOGTINFO, "SRR[0x%x] Got an FCP RSP SRR- resending status", atp->tag);
2774 		atp->sendst = 1;
2775 		/*
2776 		 * We have to restart a FCP_RSP IU transaction
2777 		 */
2778 		break;
2779 	case R_CTL_INFO_DATA_DESCRIPTOR:
2780 		/*
2781 		 * We have to restart an FCP DATA in transaction
2782 		 */
2783 		isp_prt(isp, ISP_LOGWARN, "Got an FCP DATA IN SRR- dropping");
2784 		goto fail;
2785 
2786 	default:
2787 		isp_prt(isp, ISP_LOGWARN, "Got an unknown information (%x) SRR- dropping", inot->in_srr_iu);
2788 		goto fail;
2789 	}
2790 
2791 	/*
2792 	 * We can't do anything until this is acked, so we might as well start it now.
2793 	 * We aren't going to do the usual asynchronous ack issue because we need
2794 	 * to make sure this gets on the wire first.
2795 	 */
2796 	if (isp_notify_ack(isp, inot)) {
2797 		isp_prt(isp, ISP_LOGWARN, "could not push positive ack for SRR- you lose");
2798 		goto fail;
2799 	}
2800 	isp_target_start_ctio(isp, ccb, FROM_SRR);
2801 	return;
2802 fail:
2803 	inot->in_reserved = 1;
2804 	isp_async(isp, ISPASYNC_TARGET_NOTIFY_ACK, inot);
2805 	ccb->ccb_h.status &= ~CAM_STATUS_MASK;
2806 	ccb->ccb_h.status |= CAM_REQ_CMP_ERR;
2807 	isp_complete_ctio(ccb);
2808 	return;
2809 mdp:
2810 	if (isp_notify_ack(isp, inot)) {
2811 		isp_prt(isp, ISP_LOGWARN, "could not push positive ack for SRR- you lose");
2812 		goto fail;
2813 	}
2814 	ccb->ccb_h.status &= ~CAM_STATUS_MASK;
2815 	ccb->ccb_h.status = CAM_MESSAGE_RECV;
2816 	/*
2817 	 * This is not a strict interpretation of MDP, but it's close
2818 	 */
2819 	ccb->csio.msg_ptr = &ccb->csio.sense_data.sense_buf[SSD_FULL_SIZE - 16];
2820 	ccb->csio.msg_len = 7;
2821 	ccb->csio.msg_ptr[0] = MSG_EXTENDED;
2822 	ccb->csio.msg_ptr[1] = 5;
2823 	ccb->csio.msg_ptr[2] = 0;	/* modify data pointer */
2824 	ccb->csio.msg_ptr[3] = srr_off >> 24;
2825 	ccb->csio.msg_ptr[4] = srr_off >> 16;
2826 	ccb->csio.msg_ptr[5] = srr_off >> 8;
2827 	ccb->csio.msg_ptr[6] = srr_off;
2828 	isp_complete_ctio(ccb);
2829 }
2830 
2831 
2832 static void
2833 isp_handle_srr_notify(ispsoftc_t *isp, void *inot_raw)
2834 {
2835 	tstate_t *tptr;
2836 	in_fcentry_24xx_t *inot = inot_raw;
2837 	atio_private_data_t *atp;
2838 	uint32_t tag = inot->in_rxid;
2839 	uint32_t bus = inot->in_vpidx;
2840 
2841 	if (!IS_24XX(isp)) {
2842 		isp_async(isp, ISPASYNC_TARGET_NOTIFY_ACK, inot_raw);
2843 		return;
2844 	}
2845 
2846 	tptr = get_lun_statep_from_tag(isp, bus, tag);
2847 	if (tptr == NULL) {
2848 		isp_prt(isp, ISP_LOGERR, "%s: cannot find tptr for tag %x in SRR Notify", __func__, tag);
2849 		isp_async(isp, ISPASYNC_TARGET_NOTIFY_ACK, inot);
2850 		return;
2851 	}
2852 	atp = isp_find_atpd(isp, tptr, tag);
2853 	if (atp == NULL) {
2854 		rls_lun_statep(isp, tptr);
2855 		isp_prt(isp, ISP_LOGERR, "%s: cannot find adjunct for %x in SRR Notify", __func__, tag);
2856 		isp_async(isp, ISPASYNC_TARGET_NOTIFY_ACK, inot);
2857 		return;
2858 	}
2859 	atp->srr_notify_rcvd = 1;
2860 	memcpy(atp->srr, inot, sizeof (atp->srr));
2861 	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,
2862 	    inot->in_srr_reloff_lo | (inot->in_srr_reloff_hi << 16));
2863 	if (atp->srr_ccb)
2864 		isp_handle_srr_start(isp, tptr, atp);
2865 	rls_lun_statep(isp, tptr);
2866 }
2867 
2868 static void
2869 isp_handle_platform_ctio(ispsoftc_t *isp, void *arg)
2870 {
2871 	union ccb *ccb;
2872 	int sentstatus = 0, ok = 0, notify_cam = 0, resid = 0, failure = 0;
2873 	tstate_t *tptr = NULL;
2874 	atio_private_data_t *atp = NULL;
2875 	int bus;
2876 	uint32_t handle, moved_data = 0, data_requested;
2877 
2878 	/*
2879 	 * CTIO handles are 16 bits.
2880 	 * CTIO2 and CTIO7 are 32 bits.
2881 	 */
2882 
2883 	if (IS_SCSI(isp)) {
2884 		handle = ((ct_entry_t *)arg)->ct_syshandle;
2885 	} else {
2886 		handle = ((ct2_entry_t *)arg)->ct_syshandle;
2887 	}
2888 	ccb = isp_find_xs_tgt(isp, handle);
2889 	if (ccb == NULL) {
2890 		isp_print_bytes(isp, "null ccb in isp_handle_platform_ctio", QENTRY_LEN, arg);
2891 		return;
2892 	}
2893 	isp_destroy_tgt_handle(isp, handle);
2894 	data_requested = PISP_PCMD(ccb)->datalen;
2895 	isp_free_pcmd(isp, ccb);
2896 	if (isp->isp_nactive) {
2897 		isp->isp_nactive--;
2898 	}
2899 
2900 	bus = XS_CHANNEL(ccb);
2901 	tptr = get_lun_statep(isp, bus, XS_LUN(ccb));
2902 	if (tptr == NULL) {
2903 		tptr = get_lun_statep(isp, bus, CAM_LUN_WILDCARD);
2904 	}
2905 	if (tptr == NULL) {
2906 		isp_prt(isp, ISP_LOGERR, "%s: cannot find tptr for tag %x after I/O", __func__, ccb->csio.tag_id);
2907 		return;
2908 	}
2909 
2910 	if (IS_24XX(isp)) {
2911 		atp = isp_find_atpd(isp, tptr, ((ct7_entry_t *)arg)->ct_rxid);
2912 	} else if (IS_FC(isp)) {
2913 		atp = isp_find_atpd(isp, tptr, ((ct2_entry_t *)arg)->ct_rxid);
2914 	} else {
2915 		atp = isp_find_atpd(isp, tptr, ((ct_entry_t *)arg)->ct_fwhandle);
2916 	}
2917 	if (atp == NULL) {
2918 		rls_lun_statep(isp, tptr);
2919 		isp_prt(isp, ISP_LOGERR, "%s: cannot find adjunct for %x after I/O", __func__, ccb->csio.tag_id);
2920 		return;
2921 	}
2922 	KASSERT((atp->ctcnt > 0), ("ctio count not greater than zero"));
2923 	atp->bytes_in_transit -= data_requested;
2924 	atp->ctcnt -= 1;
2925 	ccb->ccb_h.status &= ~CAM_STATUS_MASK;
2926 
2927 	if (IS_24XX(isp)) {
2928 		ct7_entry_t *ct = arg;
2929 
2930 		if (ct->ct_nphdl == CT7_SRR) {
2931 			atp->srr_ccb = ccb;
2932 			if (atp->srr_notify_rcvd)
2933 				isp_handle_srr_start(isp, tptr, atp);
2934 			rls_lun_statep(isp, tptr);
2935 			return;
2936 		}
2937 		if (ct->ct_nphdl == CT_HBA_RESET) {
2938 			failure = CAM_UNREC_HBA_ERROR;
2939 		} else {
2940 			sentstatus = ct->ct_flags & CT7_SENDSTATUS;
2941 			ok = (ct->ct_nphdl == CT7_OK);
2942 			notify_cam = (ct->ct_header.rqs_seqno & ATPD_SEQ_NOTIFY_CAM) != 0;
2943 			if ((ct->ct_flags & CT7_DATAMASK) != CT7_NO_DATA) {
2944 				resid = ct->ct_resid;
2945 				moved_data = data_requested - resid;
2946 			}
2947 		}
2948 		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),
2949 		   notify_cam, ct->ct_nphdl, ct->ct_flags, (ccb->ccb_h.status & CAM_SENT_SENSE) != 0, resid, sentstatus? "FIN" : "MID");
2950 	} else if (IS_FC(isp)) {
2951 		ct2_entry_t *ct = arg;
2952 		if (ct->ct_status == CT_SRR) {
2953 			atp->srr_ccb = ccb;
2954 			if (atp->srr_notify_rcvd)
2955 				isp_handle_srr_start(isp, tptr, atp);
2956 			rls_lun_statep(isp, tptr);
2957 			isp_target_putback_atio(ccb);
2958 			return;
2959 		}
2960 		if (ct->ct_status == CT_HBA_RESET) {
2961 			failure = CAM_UNREC_HBA_ERROR;
2962 		} else {
2963 			sentstatus = ct->ct_flags & CT2_SENDSTATUS;
2964 			ok = (ct->ct_status & ~QLTM_SVALID) == CT_OK;
2965 			notify_cam = (ct->ct_header.rqs_seqno & ATPD_SEQ_NOTIFY_CAM) != 0;
2966 			if ((ct->ct_flags & CT2_DATAMASK) != CT2_NO_DATA) {
2967 				resid = ct->ct_resid;
2968 				moved_data = data_requested - resid;
2969 			}
2970 		}
2971 		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),
2972 		    notify_cam, ct->ct_status, ct->ct_flags, (ccb->ccb_h.status & CAM_SENT_SENSE) != 0, resid, sentstatus? "FIN" : "MID");
2973 	} else {
2974 		ct_entry_t *ct = arg;
2975 
2976 		if (ct->ct_status == (CT_HBA_RESET & 0xff)) {
2977 			failure = CAM_UNREC_HBA_ERROR;
2978 		} else {
2979 			sentstatus = ct->ct_flags & CT_SENDSTATUS;
2980 			ok = (ct->ct_status  & ~QLTM_SVALID) == CT_OK;
2981 			notify_cam = (ct->ct_header.rqs_seqno & ATPD_SEQ_NOTIFY_CAM) != 0;
2982 		}
2983 		if ((ct->ct_flags & CT_DATAMASK) != CT_NO_DATA) {
2984 			resid = ct->ct_resid;
2985 			moved_data = data_requested - resid;
2986 		}
2987 		isp_prt(isp, ISP_LOGTDEBUG0, "%s: CTIO[%x] seq %u nc %d tag %x S_ID 0x%x lun %d sts %x flg %x resid %d %s", __func__, ct->ct_fwhandle, ATPD_GET_SEQNO(ct),
2988 		    notify_cam, ct->ct_tag_val, ct->ct_iid, ct->ct_lun, ct->ct_status, ct->ct_flags, resid, sentstatus? "FIN" : "MID");
2989 	}
2990 	if (ok) {
2991 		if (moved_data) {
2992 			atp->bytes_xfered += moved_data;
2993 			ccb->csio.resid = atp->orig_datalen - atp->bytes_xfered - atp->bytes_in_transit;
2994 		}
2995 		if (sentstatus && (ccb->ccb_h.flags & CAM_SEND_SENSE)) {
2996 			ccb->ccb_h.status |= CAM_SENT_SENSE;
2997 		}
2998 		ccb->ccb_h.status |= CAM_REQ_CMP;
2999 	} else {
3000 		notify_cam = 1;
3001 		if (failure == CAM_UNREC_HBA_ERROR)
3002 			ccb->ccb_h.status |= CAM_UNREC_HBA_ERROR;
3003 		else
3004 			ccb->ccb_h.status |= CAM_REQ_CMP_ERR;
3005 	}
3006 	atp->state = ATPD_STATE_PDON;
3007 	rls_lun_statep(isp, tptr);
3008 
3009 	/*
3010 	 * We never *not* notify CAM when there has been any error (ok == 0),
3011 	 * so we never need to do an ATIO putback if we're not notifying CAM.
3012 	 */
3013 	isp_prt(isp, ISP_LOGTDEBUG0, "%s CTIO[0x%x] done (ok=%d nc=%d nowsendstatus=%d ccb ss=%d)",
3014 	    (sentstatus)? "  FINAL " : "MIDTERM ", atp->tag, ok, notify_cam, atp->sendst, (ccb->ccb_h.flags & CAM_SEND_STATUS) != 0);
3015 	if (notify_cam == 0) {
3016 		if (atp->sendst) {
3017 			isp_target_start_ctio(isp, ccb, FROM_CTIO_DONE);
3018 		}
3019 		return;
3020 	}
3021 
3022 	/*
3023 	 * We're telling CAM we're done with this CTIO transaction.
3024 	 *
3025 	 * 24XX cards never need an ATIO put back.
3026 	 *
3027 	 * Other cards need one put back only on error.
3028 	 * In the latter case, a timeout will re-fire
3029 	 * and try again in case we didn't have
3030 	 * queue resources to do so at first. In any case,
3031 	 * once the putback is done we do the completion
3032 	 * call.
3033 	 */
3034 	if (ok || IS_24XX(isp)) {
3035 		isp_complete_ctio(ccb);
3036 	} else {
3037 		isp_target_putback_atio(ccb);
3038 	}
3039 }
3040 
3041 static void
3042 isp_handle_platform_notify_scsi(ispsoftc_t *isp, in_entry_t *inot)
3043 {
3044 	isp_async(isp, ISPASYNC_TARGET_NOTIFY_ACK, inot);
3045 }
3046 
3047 static void
3048 isp_handle_platform_notify_fc(ispsoftc_t *isp, in_fcentry_t *inp)
3049 {
3050 	int needack = 1;
3051 	switch (inp->in_status) {
3052 	case IN_PORT_LOGOUT:
3053 		/*
3054 		 * XXX: Need to delete this initiator's WWN from the database
3055 		 * XXX: Need to send this LOGOUT upstream
3056 		 */
3057 		isp_prt(isp, ISP_LOGWARN, "port logout of S_ID 0x%x", inp->in_iid);
3058 		break;
3059 	case IN_PORT_CHANGED:
3060 		isp_prt(isp, ISP_LOGWARN, "port changed for S_ID 0x%x", inp->in_iid);
3061 		break;
3062 	case IN_GLOBAL_LOGO:
3063 		isp_del_all_wwn_entries(isp, 0);
3064 		isp_prt(isp, ISP_LOGINFO, "all ports logged out");
3065 		break;
3066 	case IN_ABORT_TASK:
3067 	{
3068 		tstate_t *tptr;
3069 		uint16_t lun;
3070 		uint32_t loopid;
3071 		uint64_t wwn;
3072 		atio_private_data_t *atp;
3073 		fcportdb_t *lp;
3074 		struct ccb_immediate_notify *inot = NULL;
3075 
3076 		if (ISP_CAP_SCCFW(isp)) {
3077 			lun = inp->in_scclun;
3078 		} else {
3079 			lun = inp->in_lun;
3080 		}
3081 		if (ISP_CAP_2KLOGIN(isp)) {
3082 			loopid = ((in_fcentry_e_t *)inp)->in_iid;
3083 		} else {
3084 			loopid = inp->in_iid;
3085 		}
3086 		if (isp_find_pdb_by_loopid(isp, 0, loopid, &lp)) {
3087 			wwn = lp->port_wwn;
3088 		} else {
3089 			wwn = INI_ANY;
3090 		}
3091 		tptr = get_lun_statep(isp, 0, lun);
3092 		if (tptr == NULL) {
3093 			tptr = get_lun_statep(isp, 0, CAM_LUN_WILDCARD);
3094 			if (tptr == NULL) {
3095 				isp_prt(isp, ISP_LOGWARN, "ABORT TASK for lun %u- but no tstate", lun);
3096 				return;
3097 			}
3098 		}
3099 		atp = isp_find_atpd(isp, tptr, inp->in_seqid);
3100 
3101 		if (atp) {
3102 			inot = (struct ccb_immediate_notify *) SLIST_FIRST(&tptr->inots);
3103 			isp_prt(isp, ISP_LOGTDEBUG0, "ABORT TASK RX_ID %x WWN 0x%016llx state %d", inp->in_seqid, (unsigned long long) wwn, atp->state);
3104 			if (inot) {
3105 				tptr->inot_count--;
3106 				SLIST_REMOVE_HEAD(&tptr->inots, sim_links.sle);
3107 				ISP_PATH_PRT(isp, ISP_LOGTDEBUG2, inot->ccb_h.path, "%s: Take FREE INOT count now %d\n", __func__, tptr->inot_count);
3108 			} else {
3109 				ISP_PATH_PRT(isp, ISP_LOGWARN, tptr->owner, "out of INOT structures\n");
3110 			}
3111 		} else {
3112 			ISP_PATH_PRT(isp, ISP_LOGWARN, tptr->owner, "abort task RX_ID %x from wwn 0x%016llx, state unknown\n", inp->in_seqid, wwn);
3113 		}
3114 		if (inot) {
3115 			isp_notify_t tmp, *nt = &tmp;
3116 			ISP_MEMZERO(nt, sizeof (isp_notify_t));
3117     			nt->nt_hba = isp;
3118 			nt->nt_tgt = FCPARAM(isp, 0)->isp_wwpn;
3119 			nt->nt_wwn = wwn;
3120 			nt->nt_nphdl = loopid;
3121 			nt->nt_sid = PORT_ANY;
3122 			nt->nt_did = PORT_ANY;
3123     			nt->nt_lun = lun;
3124             		nt->nt_need_ack = 1;
3125     			nt->nt_channel = 0;
3126     			nt->nt_ncode = NT_ABORT_TASK;
3127     			nt->nt_lreserved = inot;
3128 			isp_handle_platform_target_tmf(isp, nt);
3129 			needack = 0;
3130 		}
3131 		rls_lun_statep(isp, tptr);
3132 		break;
3133 	}
3134 	default:
3135 		break;
3136 	}
3137 	if (needack) {
3138 		isp_async(isp, ISPASYNC_TARGET_NOTIFY_ACK, inp);
3139 	}
3140 }
3141 
3142 static void
3143 isp_handle_platform_notify_24xx(ispsoftc_t *isp, in_fcentry_24xx_t *inot)
3144 {
3145 	uint16_t nphdl;
3146 	uint16_t prli_options = 0;
3147 	uint32_t portid;
3148 	fcportdb_t *lp;
3149 	uint8_t *ptr = NULL;
3150 	uint64_t wwn;
3151 
3152 	nphdl = inot->in_nphdl;
3153 	if (nphdl != NIL_HANDLE) {
3154 		portid = inot->in_portid_hi << 16 | inot->in_portid_lo;
3155 	} else {
3156 		portid = PORT_ANY;
3157 	}
3158 
3159 	switch (inot->in_status) {
3160 	case IN24XX_ELS_RCVD:
3161 	{
3162 		char buf[16], *msg;
3163 		int chan = ISP_GET_VPIDX(isp, inot->in_vpidx);
3164 
3165 		/*
3166 		 * Note that we're just getting notification that an ELS was received
3167 		 * (possibly with some associated information sent upstream). This is
3168 		 * *not* the same as being given the ELS frame to accept or reject.
3169 		 */
3170 		switch (inot->in_status_subcode) {
3171 		case LOGO:
3172 			msg = "LOGO";
3173 			if (ISP_FW_NEWER_THAN(isp, 4, 0, 25)) {
3174 				ptr = (uint8_t *)inot;  /* point to unswizzled entry! */
3175 				wwn =	(((uint64_t) ptr[IN24XX_LOGO_WWPN_OFF])   << 56) |
3176 					(((uint64_t) ptr[IN24XX_LOGO_WWPN_OFF+1]) << 48) |
3177 					(((uint64_t) ptr[IN24XX_LOGO_WWPN_OFF+2]) << 40) |
3178 					(((uint64_t) ptr[IN24XX_LOGO_WWPN_OFF+3]) << 32) |
3179 					(((uint64_t) ptr[IN24XX_LOGO_WWPN_OFF+4]) << 24) |
3180 					(((uint64_t) ptr[IN24XX_LOGO_WWPN_OFF+5]) << 16) |
3181 					(((uint64_t) ptr[IN24XX_LOGO_WWPN_OFF+6]) <<  8) |
3182 					(((uint64_t) ptr[IN24XX_LOGO_WWPN_OFF+7]));
3183 			} else {
3184 				wwn = INI_ANY;
3185 			}
3186 			isp_del_wwn_entry(isp, chan, wwn, nphdl, portid);
3187 			break;
3188 		case PRLO:
3189 			msg = "PRLO";
3190 			break;
3191 		case PLOGI:
3192 		case PRLI:
3193 			/*
3194 			 * Treat PRLI the same as PLOGI and make a database entry for it.
3195 			 */
3196 			if (inot->in_status_subcode == PLOGI) {
3197 				msg = "PLOGI";
3198 			} else {
3199 				prli_options = inot->in_prli_options;
3200 				msg = "PRLI";
3201 			}
3202 			if (ISP_FW_NEWER_THAN(isp, 4, 0, 25)) {
3203 				ptr = (uint8_t *)inot;  /* point to unswizzled entry! */
3204 				wwn =	(((uint64_t) ptr[IN24XX_PLOGI_WWPN_OFF])   << 56) |
3205 					(((uint64_t) ptr[IN24XX_PLOGI_WWPN_OFF+1]) << 48) |
3206 					(((uint64_t) ptr[IN24XX_PLOGI_WWPN_OFF+2]) << 40) |
3207 					(((uint64_t) ptr[IN24XX_PLOGI_WWPN_OFF+3]) << 32) |
3208 					(((uint64_t) ptr[IN24XX_PLOGI_WWPN_OFF+4]) << 24) |
3209 					(((uint64_t) ptr[IN24XX_PLOGI_WWPN_OFF+5]) << 16) |
3210 					(((uint64_t) ptr[IN24XX_PLOGI_WWPN_OFF+6]) <<  8) |
3211 					(((uint64_t) ptr[IN24XX_PLOGI_WWPN_OFF+7]));
3212 			} else {
3213 				wwn = INI_NONE;
3214 			}
3215 			isp_add_wwn_entry(isp, chan, wwn, nphdl, portid, prli_options);
3216 			break;
3217 		case PDISC:
3218 			msg = "PDISC";
3219 			break;
3220 		case ADISC:
3221 			msg = "ADISC";
3222 			break;
3223 		default:
3224 			ISP_SNPRINTF(buf, sizeof (buf), "ELS 0x%x", inot->in_status_subcode);
3225 			msg = buf;
3226 			break;
3227 		}
3228 		if (inot->in_flags & IN24XX_FLAG_PUREX_IOCB) {
3229 			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);
3230 			break;
3231 		}
3232 		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,
3233 		    inot->in_rxid, inot->in_oxid);
3234 		isp_async(isp, ISPASYNC_TARGET_NOTIFY_ACK, inot);
3235 		break;
3236 	}
3237 
3238 	case IN24XX_PORT_LOGOUT:
3239 		ptr = "PORT LOGOUT";
3240 		if (isp_find_pdb_by_loopid(isp, ISP_GET_VPIDX(isp, inot->in_vpidx), nphdl, &lp)) {
3241 			isp_del_wwn_entry(isp, ISP_GET_VPIDX(isp, inot->in_vpidx), lp->port_wwn, nphdl, lp->portid);
3242 		}
3243 		/* FALLTHROUGH */
3244 	case IN24XX_PORT_CHANGED:
3245 		if (ptr == NULL) {
3246 			ptr = "PORT CHANGED";
3247 		}
3248 		/* FALLTHROUGH */
3249 	case IN24XX_LIP_RESET:
3250 		if (ptr == NULL) {
3251 			ptr = "LIP RESET";
3252 		}
3253 		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), ptr, inot->in_status_subcode, nphdl);
3254 
3255 		/*
3256 		 * All subcodes here are irrelevant. What is relevant
3257 		 * is that we need to terminate all active commands from
3258 		 * this initiator (known by N-port handle).
3259 		 */
3260 		/* XXX IMPLEMENT XXX */
3261 		isp_async(isp, ISPASYNC_TARGET_NOTIFY_ACK, inot);
3262 		break;
3263 
3264 	case IN24XX_SRR_RCVD:
3265 #ifdef	ISP_TARGET_MODE
3266 		isp_handle_srr_notify(isp, inot);
3267 		break;
3268 #else
3269 		if (ptr == NULL) {
3270 			ptr = "SRR RCVD";
3271 		}
3272 		/* FALLTHROUGH */
3273 #endif
3274 	case IN24XX_LINK_RESET:
3275 		if (ptr == NULL) {
3276 			ptr = "LINK RESET";
3277 		}
3278 	case IN24XX_LINK_FAILED:
3279 		if (ptr == NULL) {
3280 			ptr = "LINK FAILED";
3281 		}
3282 	default:
3283 		isp_prt(isp, ISP_LOGWARN, "Chan %d %s", ISP_GET_VPIDX(isp, inot->in_vpidx), ptr);
3284 		isp_async(isp, ISPASYNC_TARGET_NOTIFY_ACK, inot);
3285 		break;
3286 	}
3287 }
3288 
3289 static int
3290 isp_handle_platform_target_notify_ack(ispsoftc_t *isp, isp_notify_t *mp)
3291 {
3292 
3293 	if (isp->isp_state != ISP_RUNSTATE) {
3294 		isp_prt(isp, ISP_LOGTINFO, "Notify Code 0x%x (qevalid=%d) acked- h/w not ready (dropping)", mp->nt_ncode, mp->nt_lreserved != NULL);
3295 		return (0);
3296 	}
3297 
3298 	/*
3299 	 * This case is for a Task Management Function, which shows up as an ATIO7 entry.
3300 	 */
3301 	if (IS_24XX(isp) && mp->nt_lreserved && ((isphdr_t *)mp->nt_lreserved)->rqs_entry_type == RQSTYPE_ATIO) {
3302 		ct7_entry_t local, *cto = &local;
3303 		at7_entry_t *aep = (at7_entry_t *)mp->nt_lreserved;
3304 		fcportdb_t *lp;
3305 		uint32_t sid;
3306 		uint16_t nphdl;
3307 
3308 		sid = (aep->at_hdr.s_id[0] << 16) | (aep->at_hdr.s_id[1] << 8) | aep->at_hdr.s_id[2];
3309 		if (isp_find_pdb_by_sid(isp, mp->nt_channel, sid, &lp)) {
3310 			nphdl = lp->handle;
3311 		} else {
3312 			nphdl = NIL_HANDLE;
3313 		}
3314 		ISP_MEMZERO(&local, sizeof (local));
3315 		cto->ct_header.rqs_entry_type = RQSTYPE_CTIO7;
3316 		cto->ct_header.rqs_entry_count = 1;
3317 		cto->ct_nphdl = nphdl;
3318 		cto->ct_rxid = aep->at_rxid;
3319 		cto->ct_vpidx = mp->nt_channel;
3320 		cto->ct_iid_lo = sid;
3321 		cto->ct_iid_hi = sid >> 16;
3322 		cto->ct_oxid = aep->at_hdr.ox_id;
3323 		cto->ct_flags = CT7_SENDSTATUS|CT7_NOACK|CT7_NO_DATA|CT7_FLAG_MODE1;
3324 		cto->ct_flags |= (aep->at_ta_len >> 12) << CT7_TASK_ATTR_SHIFT;
3325 		return (isp_target_put_entry(isp, &local));
3326 	}
3327 
3328 	/*
3329 	 * This case is for a responding to an ABTS frame
3330 	 */
3331 	if (IS_24XX(isp) && mp->nt_lreserved && ((isphdr_t *)mp->nt_lreserved)->rqs_entry_type == RQSTYPE_ABTS_RCVD) {
3332 
3333 		/*
3334 		 * Overload nt_need_ack here to mark whether we've terminated the associated command.
3335 		 */
3336 		if (mp->nt_need_ack) {
3337 			uint8_t storage[QENTRY_LEN];
3338 			ct7_entry_t *cto = (ct7_entry_t *) storage;
3339 			abts_t *abts = (abts_t *)mp->nt_lreserved;
3340 
3341 			ISP_MEMZERO(cto, sizeof (ct7_entry_t));
3342 			isp_prt(isp, ISP_LOGTDEBUG0, "%s: [%x] terminating after ABTS received", __func__, abts->abts_rxid_task);
3343 			cto->ct_header.rqs_entry_type = RQSTYPE_CTIO7;
3344 			cto->ct_header.rqs_entry_count = 1;
3345 			cto->ct_nphdl = mp->nt_nphdl;
3346 			cto->ct_rxid = abts->abts_rxid_task;
3347 			cto->ct_iid_lo = mp->nt_sid;
3348 			cto->ct_iid_hi = mp->nt_sid >> 16;
3349 			cto->ct_oxid = abts->abts_ox_id;
3350 			cto->ct_vpidx = mp->nt_channel;
3351 			cto->ct_flags = CT7_NOACK|CT7_TERMINATE;
3352 			if (isp_target_put_entry(isp, cto)) {
3353 				return (ENOMEM);
3354 			}
3355 			mp->nt_need_ack = 0;
3356 		}
3357 		if (isp_acknak_abts(isp, mp->nt_lreserved, 0) == ENOMEM) {
3358 			return (ENOMEM);
3359 		} else {
3360 			return (0);
3361 		}
3362 	}
3363 
3364 	/*
3365 	 * Handle logout cases here
3366 	 */
3367 	if (mp->nt_ncode == NT_GLOBAL_LOGOUT) {
3368 		isp_del_all_wwn_entries(isp, mp->nt_channel);
3369 	}
3370 
3371 	if (mp->nt_ncode == NT_LOGOUT) {
3372 		if (!IS_2100(isp) && IS_FC(isp)) {
3373 			isp_del_wwn_entries(isp, mp);
3374 		}
3375 	}
3376 
3377 	/*
3378 	 * General purpose acknowledgement
3379 	 */
3380 	if (mp->nt_need_ack) {
3381 		isp_prt(isp, ISP_LOGTINFO, "Notify Code 0x%x (qevalid=%d) being acked", mp->nt_ncode, mp->nt_lreserved != NULL);
3382 		/*
3383 		 * Don't need to use the guaranteed send because the caller can retry
3384 		 */
3385 		return (isp_notify_ack(isp, mp->nt_lreserved));
3386 	}
3387 	return (0);
3388 }
3389 
3390 /*
3391  * Handle task management functions.
3392  *
3393  * We show up here with a notify structure filled out.
3394  *
3395  * The nt_lreserved tag points to the original queue entry
3396  */
3397 static void
3398 isp_handle_platform_target_tmf(ispsoftc_t *isp, isp_notify_t *notify)
3399 {
3400 	tstate_t *tptr;
3401 	fcportdb_t *lp;
3402 	struct ccb_immediate_notify *inot;
3403 	inot_private_data_t *ntp = NULL;
3404 	lun_id_t lun;
3405 
3406 	isp_prt(isp, ISP_LOGTDEBUG0, "%s: code 0x%x sid  0x%x tagval 0x%016llx chan %d lun 0x%x", __func__, notify->nt_ncode,
3407 	    notify->nt_sid, (unsigned long long) notify->nt_tagval, notify->nt_channel, notify->nt_lun);
3408 	/*
3409 	 * NB: This assignment is necessary because of tricky type conversion.
3410 	 * XXX: This is tricky and I need to check this. If the lun isn't known
3411 	 * XXX: for the task management function, it does not of necessity follow
3412 	 * XXX: that it should go up stream to the wildcard listener.
3413 	 */
3414 	if (notify->nt_lun == LUN_ANY) {
3415 		lun = CAM_LUN_WILDCARD;
3416 	} else {
3417 		lun = notify->nt_lun;
3418 	}
3419 	tptr = get_lun_statep(isp, notify->nt_channel, lun);
3420 	if (tptr == NULL) {
3421 		tptr = get_lun_statep(isp, notify->nt_channel, CAM_LUN_WILDCARD);
3422 		if (tptr == NULL) {
3423 			isp_prt(isp, ISP_LOGWARN, "%s: no state pointer found for chan %d lun %#jx", __func__, notify->nt_channel, (uintmax_t)lun);
3424 			goto bad;
3425 		}
3426 	}
3427 	inot = (struct ccb_immediate_notify *) SLIST_FIRST(&tptr->inots);
3428 	if (inot == NULL) {
3429 		isp_prt(isp, ISP_LOGWARN, "%s: out of immediate notify structures for chan %d lun %#jx", __func__, notify->nt_channel, (uintmax_t)lun);
3430 		goto bad;
3431 	}
3432 
3433 	if (isp_find_pdb_by_sid(isp, notify->nt_channel, notify->nt_sid, &lp) == 0) {
3434 		inot->initiator_id = CAM_TARGET_WILDCARD;
3435 	} else {
3436 		inot->initiator_id = lp->handle;
3437 	}
3438 	inot->seq_id = notify->nt_tagval;
3439 	inot->tag_id = notify->nt_tagval >> 32;
3440 
3441 	switch (notify->nt_ncode) {
3442 	case NT_ABORT_TASK:
3443 		isp_target_mark_aborted_early(isp, tptr, inot->tag_id);
3444 		inot->arg = MSG_ABORT_TASK;
3445 		break;
3446 	case NT_ABORT_TASK_SET:
3447 		isp_target_mark_aborted_early(isp, tptr, TAG_ANY);
3448 		inot->arg = MSG_ABORT_TASK_SET;
3449 		break;
3450 	case NT_CLEAR_ACA:
3451 		inot->arg = MSG_CLEAR_ACA;
3452 		break;
3453 	case NT_CLEAR_TASK_SET:
3454 		inot->arg = MSG_CLEAR_TASK_SET;
3455 		break;
3456 	case NT_LUN_RESET:
3457 		inot->arg = MSG_LOGICAL_UNIT_RESET;
3458 		break;
3459 	case NT_TARGET_RESET:
3460 		inot->arg = MSG_TARGET_RESET;
3461 		break;
3462 	default:
3463 		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);
3464 		goto bad;
3465 	}
3466 
3467 	ntp = isp_get_ntpd(isp, tptr);
3468 	if (ntp == NULL) {
3469 		isp_prt(isp, ISP_LOGWARN, "%s: out of inotify private structures", __func__);
3470 		goto bad;
3471 	}
3472 	ISP_MEMCPY(&ntp->rd.nt, notify, sizeof (isp_notify_t));
3473 	if (notify->nt_lreserved) {
3474 		ISP_MEMCPY(&ntp->rd.data, notify->nt_lreserved, QENTRY_LEN);
3475 		ntp->rd.nt.nt_lreserved = &ntp->rd.data;
3476 	}
3477 	ntp->rd.seq_id = notify->nt_tagval;
3478 	ntp->rd.tag_id = notify->nt_tagval >> 32;
3479 
3480 	tptr->inot_count--;
3481 	SLIST_REMOVE_HEAD(&tptr->inots, sim_links.sle);
3482 	rls_lun_statep(isp, tptr);
3483 	ISP_PATH_PRT(isp, ISP_LOGTDEBUG2, inot->ccb_h.path, "%s: Take FREE INOT count now %d\n", __func__, tptr->inot_count);
3484 	inot->ccb_h.status = CAM_MESSAGE_RECV;
3485 	xpt_done((union ccb *)inot);
3486 	return;
3487 bad:
3488 	if (tptr) {
3489 		rls_lun_statep(isp, tptr);
3490 	}
3491 	if (notify->nt_need_ack && notify->nt_lreserved) {
3492 		if (((isphdr_t *)notify->nt_lreserved)->rqs_entry_type == RQSTYPE_ABTS_RCVD) {
3493 			if (isp_acknak_abts(isp, notify->nt_lreserved, ENOMEM)) {
3494 				isp_prt(isp, ISP_LOGWARN, "you lose- unable to send an ACKNAK");
3495 			}
3496 		} else {
3497 			isp_async(isp, ISPASYNC_TARGET_NOTIFY_ACK, notify->nt_lreserved);
3498 		}
3499 	}
3500 }
3501 
3502 /*
3503  * Find the associated private data and mark it as dead so
3504  * we don't try to work on it any further.
3505  */
3506 static void
3507 isp_target_mark_aborted(ispsoftc_t *isp, union ccb *ccb)
3508 {
3509 	tstate_t *tptr;
3510 	atio_private_data_t *atp;
3511 	union ccb *accb = ccb->cab.abort_ccb;
3512 
3513 	tptr = get_lun_statep(isp, XS_CHANNEL(accb), XS_LUN(accb));
3514 	if (tptr == NULL) {
3515 		tptr = get_lun_statep(isp, XS_CHANNEL(accb), CAM_LUN_WILDCARD);
3516 		if (tptr == NULL) {
3517 			ccb->ccb_h.status = CAM_REQ_INVALID;
3518 			return;
3519 		}
3520 	}
3521 
3522 	atp = isp_find_atpd(isp, tptr, accb->atio.tag_id);
3523 	if (atp == NULL) {
3524 		ccb->ccb_h.status = CAM_REQ_INVALID;
3525 	} else {
3526 		atp->dead = 1;
3527 		ccb->ccb_h.status = CAM_REQ_CMP;
3528 	}
3529 	rls_lun_statep(isp, tptr);
3530 }
3531 
3532 static void
3533 isp_target_mark_aborted_early(ispsoftc_t *isp, tstate_t *tptr, uint32_t tag_id)
3534 {
3535 	atio_private_data_t *atp;
3536 	inot_private_data_t *restart_queue = tptr->restart_queue;
3537 
3538 	/*
3539 	 * First, clean any commands pending restart
3540 	 */
3541 	tptr->restart_queue = NULL;
3542 	while (restart_queue) {
3543 		uint32_t this_tag_id;
3544 		inot_private_data_t *ntp = restart_queue;
3545 
3546 		restart_queue = ntp->rd.nt.nt_hba;
3547 
3548 		if (IS_24XX(isp)) {
3549 			this_tag_id = ((at7_entry_t *)ntp->rd.data)->at_rxid;
3550 		} else {
3551 			this_tag_id = ((at2_entry_t *)ntp->rd.data)->at_rxid;
3552 		}
3553 		if ((uint64_t)tag_id == TAG_ANY || tag_id == this_tag_id) {
3554 			isp_put_ntpd(isp, tptr, ntp);
3555 		} else {
3556 			ntp->rd.nt.nt_hba = tptr->restart_queue;
3557 			tptr->restart_queue = ntp;
3558 		}
3559 	}
3560 
3561 	/*
3562 	 * Now mark other ones dead as well.
3563 	 */
3564 	for (atp = tptr->atpool; atp < &tptr->atpool[ATPDPSIZE]; atp++) {
3565 		if ((uint64_t)tag_id == TAG_ANY || atp->tag == tag_id) {
3566 			atp->dead = 1;
3567 		}
3568 	}
3569 }
3570 
3571 
3572 #ifdef	ISP_INTERNAL_TARGET
3573 //#define	ISP_SEPARATE_STATUS	1
3574 #define	ISP_MULTI_CCBS		1
3575 #if defined(ISP_MULTI_CCBS) && !defined(ISP_SEPARATE_STATUS)
3576 #define	ISP_SEPARATE_STATUS 1
3577 #endif
3578 
3579 typedef struct periph_private_data_t {
3580 	union ccb *ccb;			/* original ATIO or Immediate Notify */
3581 	unsigned long	offset;		/* current offset */
3582 	int		sequence;	/* current CTIO sequence */
3583 	int		ctio_cnt;	/* current # of ctio's outstanding */
3584 	int
3585 		status_sent	: 1,
3586 		on_queue	: 1;	/* on restart queue */
3587 } ppd_t;
3588 /*
3589  * Each ATIO we allocate will have periph private data associated with it
3590  * that maintains per-command state. This private to each ATIO.
3591  */
3592 #define	ATIO_PPD(ccb)		((ppd_t *)(((struct ccb_hdr *)ccb)->ppriv_ptr0))
3593 /*
3594  * Each CTIO we send downstream will get a pointer to the ATIO itself
3595  * so that on completion we can retrieve that pointer.
3596  */
3597 #define	ccb_atio		ppriv_ptr1
3598 #define	ccb_inot		ppriv_ptr1
3599 
3600 /*
3601  * Each CTIO we send downstream will contain a sequence number
3602  */
3603 #define	CTIO_SEQ(ccb)		ccb->ccb_h.ppriv_field0
3604 
3605 #define	MAX_ISP_TARG_TRANSFER	(2 << 20)
3606 #define	NISP_TARG_CMDS		64
3607 #define	NISP_TARG_NOTIFIES	64
3608 #define	DISK_SHIFT		9
3609 #define	JUNK_SIZE		256
3610 #define	MULTI_CCB_DATA_LIM	8192
3611 //#define	MULTI_CCB_DATA_CNT	64
3612 #define	MULTI_CCB_DATA_CNT	8
3613 
3614 extern u_int vm_kmem_size;
3615 static int ca;
3616 static uint32_t disk_size;
3617 static uint8_t *disk_data = NULL;
3618 static uint8_t *junk_data;
3619 static MALLOC_DEFINE(M_ISPTARG, "ISPTARG", "ISP TARGET data");
3620 struct isptarg_softc {
3621 	/* CCBs (CTIOs, ATIOs, INOTs) pending on the controller */
3622 	struct isp_ccbq		work_queue;
3623 	struct isp_ccbq		rework_queue;
3624 	struct isp_ccbq		running_queue;
3625 	struct isp_ccbq		inot_queue;
3626 	struct cam_periph       *periph;
3627 	struct cam_path	 	*path;
3628 	ispsoftc_t		*isp;
3629 };
3630 static periph_ctor_t	isptargctor;
3631 static periph_dtor_t	isptargdtor;
3632 static periph_start_t	isptargstart;
3633 static periph_init_t	isptarginit;
3634 static void		isptarg_done(struct cam_periph *, union ccb *);
3635 static void		isptargasync(void *, u_int32_t, struct cam_path *, void *);
3636 
3637 
3638 static int isptarg_rwparm(uint8_t *, uint8_t *, uint64_t, uint32_t, uint8_t **, uint32_t *, int *);
3639 
3640 static struct periph_driver isptargdriver =
3641 {
3642 	isptarginit, "isptarg", TAILQ_HEAD_INITIALIZER(isptargdriver.units), 0
3643 };
3644 
3645 static void
3646 isptarginit(void)
3647 {
3648 }
3649 
3650 static void
3651 isptargnotify(ispsoftc_t *isp, union ccb *iccb, struct ccb_immediate_notify *inot)
3652 {
3653 	struct ccb_notify_acknowledge *ack = &iccb->cna2;
3654 
3655 	ISP_PATH_PRT(isp, ISP_LOGTDEBUG0, inot->ccb_h.path, "%s: [0x%x] immediate notify for 0x%x from 0x%x status 0x%x arg 0x%x\n", __func__,
3656 	    inot->tag_id, inot->initiator_id, inot->seq_id, inot->ccb_h.status, inot->arg);
3657 	ack->ccb_h.func_code = XPT_NOTIFY_ACKNOWLEDGE;
3658 	ack->ccb_h.flags = 0;
3659 	ack->ccb_h.retry_count = 0;
3660 	ack->ccb_h.cbfcnp = isptarg_done;
3661 	ack->ccb_h.timeout = 0;
3662 	ack->ccb_h.ccb_inot = inot;
3663 	ack->tag_id = inot->tag_id;
3664 	ack->seq_id = inot->seq_id;
3665 	ack->initiator_id = inot->initiator_id;
3666 	xpt_action(iccb);
3667 }
3668 
3669 static void
3670 isptargstart(struct cam_periph *periph, union ccb *iccb)
3671 {
3672 	const uint8_t niliqd[SHORT_INQUIRY_LENGTH] = {
3673 		0x7f, 0x0, 0x5, 0x2, 32, 0, 0, 0x32,
3674 		'F', 'R', 'E', 'E', 'B', 'S', 'D', ' ',
3675 		'S', 'C', 'S', 'I', ' ', 'N', 'U', 'L',
3676 		'L', ' ', 'D', 'E', 'V', 'I', 'C', 'E',
3677 		'0', '0', '0', '1'
3678 	};
3679 	const uint8_t iqd[SHORT_INQUIRY_LENGTH] = {
3680 		0, 0x0, 0x5, 0x2, 32, 0, 0, 0x32,
3681 		'F', 'R', 'E', 'E', 'B', 'S', 'D', ' ',
3682 		'S', 'C', 'S', 'I', ' ', 'M', 'E', 'M',
3683 		'O', 'R', 'Y', ' ', 'D', 'I', 'S', 'K',
3684 		'0', '0', '0', '1'
3685 	};
3686 	int r, i, more = 0, last, is_data_cmd = 0, is_write;
3687 	char *queue;
3688 	struct isptarg_softc *softc = periph->softc;
3689 	struct ccb_scsiio *csio;
3690 	lun_id_t return_lun;
3691 	struct ccb_accept_tio *atio;
3692 	uint8_t *cdb, *ptr, status;
3693 	uint8_t *data_ptr;
3694 	uint32_t data_len, flags;
3695 	struct ccb_hdr *ccbh;
3696 
3697 	mtx_assert(periph->sim->mtx, MA_OWNED);
3698 	ISP_PATH_PRT(softc->isp, ISP_LOGTDEBUG1, iccb->ccb_h.path, "%s: function code 0x%x INOTQ=%c WORKQ=%c REWORKQ=%c\n", __func__, iccb->ccb_h.func_code,
3699 	    TAILQ_FIRST(&softc->inot_queue)? 'y' : 'n', TAILQ_FIRST(&softc->work_queue)? 'y' : 'n', TAILQ_FIRST(&softc->rework_queue)? 'y' : 'n');
3700 	/*
3701 	 * Check for immediate notifies first
3702 	 */
3703 	ccbh = TAILQ_FIRST(&softc->inot_queue);
3704 	if (ccbh) {
3705 		TAILQ_REMOVE(&softc->inot_queue, ccbh, periph_links.tqe);
3706 		if (TAILQ_FIRST(&softc->inot_queue) || TAILQ_FIRST(&softc->work_queue) || TAILQ_FIRST(&softc->rework_queue)) {
3707 			xpt_schedule(periph, 1);
3708 		}
3709 		isptargnotify(softc->isp, iccb, (struct ccb_immediate_notify *)ccbh);
3710 		return;
3711 	}
3712 
3713 	/*
3714 	 * Check the rework (continuation) work queue first.
3715 	 */
3716 	ccbh = TAILQ_FIRST(&softc->rework_queue);
3717 	if (ccbh) {
3718 		atio = (struct ccb_accept_tio *)ccbh;
3719 		TAILQ_REMOVE(&softc->rework_queue, ccbh, periph_links.tqe);
3720 		more = TAILQ_FIRST(&softc->work_queue) || TAILQ_FIRST(&softc->rework_queue);
3721 		queue = "rework";
3722 	} else {
3723 		ccbh = TAILQ_FIRST(&softc->work_queue);
3724 		if (ccbh == NULL) {
3725 			xpt_release_ccb(iccb);
3726 			return;
3727 		}
3728 		atio = (struct ccb_accept_tio *)ccbh;
3729 		TAILQ_REMOVE(&softc->work_queue, ccbh, periph_links.tqe);
3730 		more = TAILQ_FIRST(&softc->work_queue) != NULL;
3731 		queue = "work";
3732 	}
3733 	ATIO_PPD(atio)->on_queue = 0;
3734 
3735 	if (atio->tag_id == 0xffffffff || atio->ccb_h.func_code != XPT_ACCEPT_TARGET_IO) {
3736 		panic("BAD ATIO");
3737 	}
3738 
3739 	data_len = is_write = 0;
3740 	data_ptr = NULL;
3741 	csio = &iccb->csio;
3742 	status = SCSI_STATUS_OK;
3743 	flags = CAM_SEND_STATUS;
3744 	memset(&atio->sense_data, 0, sizeof (atio->sense_data));
3745 	cdb = atio->cdb_io.cdb_bytes;
3746 	ISP_PATH_PRT(softc->isp, ISP_LOGTDEBUG0, ccbh->path, "%s: [0x%x] processing ATIO from %s queue initiator 0x%x CDB=0x%x data_offset=%u\n", __func__, atio->tag_id,
3747 	    queue, atio->init_id, cdb[0], ATIO_PPD(atio)->offset);
3748 
3749 	return_lun = XS_LUN(atio);
3750 	if (return_lun != 0) {
3751 		xpt_print(atio->ccb_h.path, "[0x%x] Non-Zero Lun %d: cdb0=0x%x\n", atio->tag_id, return_lun, cdb[0]);
3752 		if (cdb[0] != INQUIRY && cdb[0] != REPORT_LUNS && cdb[0] != REQUEST_SENSE) {
3753 			status = SCSI_STATUS_CHECK_COND;
3754 			SDFIXED(atio->sense_data)->error_code = SSD_ERRCODE_VALID|SSD_CURRENT_ERROR;
3755 			SDFIXED(atio->sense_data)->flags = SSD_KEY_ILLEGAL_REQUEST;
3756 			SDFIXED(atio->sense_data)->add_sense_code = 0x25;	/* LOGICAL UNIT NOT SUPPORTED */
3757 			atio->sense_len = SSD_MIN_SIZE;
3758 		}
3759 		return_lun = CAM_LUN_WILDCARD;
3760 	}
3761 
3762 	switch (cdb[0]) {
3763 	case REQUEST_SENSE:
3764 		flags |= CAM_DIR_IN;
3765 		data_len = sizeof (atio->sense_data);
3766 		junk_data[0] = SSD_ERRCODE_VALID|SSD_CURRENT_ERROR|SSD_KEY_NO_SENSE;
3767 		memset(junk_data+1, 0, data_len-1);
3768 		if (data_len > cdb[4]) {
3769 			data_len = cdb[4];
3770 		}
3771 		if (data_len) {
3772 			data_ptr = junk_data;
3773 		}
3774 		break;
3775 	case WRITE_6:
3776 	case WRITE_10:
3777 	case WRITE_12:
3778 	case WRITE_16:
3779 		is_write = 1;
3780 		/* FALLTHROUGH */
3781 	case READ_6:
3782 	case READ_10:
3783 	case READ_12:
3784 	case READ_16:
3785 		is_data_cmd = 1;
3786 		r = isptarg_rwparm(cdb, disk_data, disk_size, ATIO_PPD(atio)->offset, &data_ptr, &data_len, &last);
3787 		if (r != 0) {
3788 			status = SCSI_STATUS_CHECK_COND;
3789 			SDFIXED(atio->sense_data)->error_code = SSD_ERRCODE_VALID|SSD_CURRENT_ERROR;
3790 			SDFIXED(atio->sense_data)->flags = SSD_KEY_ILLEGAL_REQUEST;
3791 			if (r == -1) {
3792 				SDFIXED(atio->sense_data)->add_sense_code = 0x21;	/* LOGICAL BLOCK ADDRESS OUT OF RANGE */
3793 			} else {
3794 				SDFIXED(atio->sense_data)->add_sense_code = 0x20;	/* INVALID COMMAND OPERATION CODE */
3795 			}
3796 			atio->sense_len = SSD_MIN_SIZE;
3797 		} else {
3798 #ifdef	ISP_SEPARATE_STATUS
3799 			if (last && data_len) {
3800 				last = 0;
3801 			}
3802 #endif
3803 			if (last == 0) {
3804 				flags &= ~CAM_SEND_STATUS;
3805 			}
3806 			if (data_len) {
3807 				ATIO_PPD(atio)->offset += data_len;
3808 				if (is_write)
3809 					flags |= CAM_DIR_OUT;
3810 				else
3811 					flags |= CAM_DIR_IN;
3812 			} else {
3813 				flags |= CAM_DIR_NONE;
3814 			}
3815 		}
3816 		break;
3817 	case INQUIRY:
3818 		flags |= CAM_DIR_IN;
3819 		if (cdb[1] || cdb[2] || cdb[3]) {
3820 			status = SCSI_STATUS_CHECK_COND;
3821 			SDFIXED(atio->sense_data)->error_code = SSD_ERRCODE_VALID|SSD_CURRENT_ERROR;
3822 			SDFIXED(atio->sense_data)->flags = SSD_KEY_UNIT_ATTENTION;
3823 			SDFIXED(atio->sense_data)->add_sense_code = 0x24;	/* INVALID FIELD IN CDB */
3824 			atio->sense_len = SSD_MIN_SIZE;
3825 			break;
3826 		}
3827 		data_len = sizeof (iqd);
3828 		if (data_len > cdb[4]) {
3829 			data_len = cdb[4];
3830 		}
3831 		if (data_len) {
3832 			if (XS_LUN(iccb) != 0) {
3833 				memcpy(junk_data, niliqd, sizeof (iqd));
3834 			} else {
3835 				memcpy(junk_data, iqd, sizeof (iqd));
3836 			}
3837 			data_ptr = junk_data;
3838 		}
3839 		break;
3840 	case TEST_UNIT_READY:
3841 		flags |= CAM_DIR_NONE;
3842 		if (ca) {
3843 			ca = 0;
3844 			status = SCSI_STATUS_CHECK_COND;
3845 			SDFIXED(atio->sense_data)->error_code = SSD_ERRCODE_VALID|SSD_CURRENT_ERROR;
3846 			SDFIXED(atio->sense_data)->flags = SSD_KEY_UNIT_ATTENTION;
3847 			SDFIXED(atio->sense_data)->add_sense_code = 0x29;	/* POWER ON, RESET, OR BUS DEVICE RESET OCCURRED */
3848 			atio->sense_len = SSD_MIN_SIZE;
3849 		}
3850 		break;
3851 	case SYNCHRONIZE_CACHE:
3852 	case START_STOP:
3853 	case RESERVE:
3854 	case RELEASE:
3855 	case VERIFY_10:
3856 		flags |= CAM_DIR_NONE;
3857 		break;
3858 
3859 	case READ_CAPACITY:
3860 		flags |= CAM_DIR_IN;
3861 		if (cdb[2] || cdb[3] || cdb[4] || cdb[5]) {
3862 			status = SCSI_STATUS_CHECK_COND;
3863 			SDFIXED(atio->sense_data)->error_code = SSD_ERRCODE_VALID|SSD_CURRENT_ERROR;
3864 			SDFIXED(atio->sense_data)->flags = SSD_KEY_ILLEGAL_REQUEST;
3865 			SDFIXED(atio->sense_data)->add_sense_code =  0x24;	/* INVALID FIELD IN CDB */
3866 			atio->sense_len = SSD_MIN_SIZE;
3867 			break;
3868 		}
3869 		if (cdb[8] & 0x1) { /* PMI */
3870 			junk_data[0] = 0xff;
3871 			junk_data[1] = 0xff;
3872 			junk_data[2] = 0xff;
3873 			junk_data[3] = 0xff;
3874 		} else {
3875 			uint64_t last_blk = (disk_size >> DISK_SHIFT) - 1;
3876 			if (last_blk < 0xffffffffULL) {
3877 			    junk_data[0] = (last_blk >> 24) & 0xff;
3878 			    junk_data[1] = (last_blk >> 16) & 0xff;
3879 			    junk_data[2] = (last_blk >>  8) & 0xff;
3880 			    junk_data[3] = (last_blk) & 0xff;
3881 			} else {
3882 			    junk_data[0] = 0xff;
3883 			    junk_data[1] = 0xff;
3884 			    junk_data[2] = 0xff;
3885 			    junk_data[3] = 0xff;
3886 			}
3887 		}
3888 		junk_data[4] = ((1 << DISK_SHIFT) >> 24) & 0xff;
3889 		junk_data[5] = ((1 << DISK_SHIFT) >> 16) & 0xff;
3890 		junk_data[6] = ((1 << DISK_SHIFT) >>  8) & 0xff;
3891 		junk_data[7] = ((1 << DISK_SHIFT)) & 0xff;
3892 		data_ptr = junk_data;
3893 		data_len = 8;
3894 		break;
3895 	case REPORT_LUNS:
3896 		flags |= CAM_DIR_IN;
3897 		memset(junk_data, 0, JUNK_SIZE);
3898 		junk_data[0] = (1 << 3) >> 24;
3899 		junk_data[1] = (1 << 3) >> 16;
3900 		junk_data[2] = (1 << 3) >> 8;
3901 		junk_data[3] = (1 << 3);
3902 		ptr = NULL;
3903 		for (i = 0; i < 1; i++) {
3904 			ptr = &junk_data[8 + (i << 3)];
3905 			if (i >= 256) {
3906 				ptr[0] = 0x40 | ((i >> 8) & 0x3f);
3907 			}
3908 			ptr[1] = i;
3909 		}
3910 		data_ptr = junk_data;
3911 		data_len = (ptr + 8) - junk_data;
3912 		break;
3913 
3914 	default:
3915 		flags |= CAM_DIR_NONE;
3916 		status = SCSI_STATUS_CHECK_COND;
3917 		SDFIXED(atio->sense_data)->error_code = SSD_ERRCODE_VALID|SSD_CURRENT_ERROR;
3918 		SDFIXED(atio->sense_data)->flags = SSD_KEY_ILLEGAL_REQUEST;
3919 		SDFIXED(atio->sense_data)->add_sense_code = 0x20;	/* INVALID COMMAND OPERATION CODE */
3920 		atio->sense_len = SSD_MIN_SIZE;
3921 		break;
3922 	}
3923 
3924 	/*
3925 	 * If we are done with the transaction, tell the
3926 	 * controller to send status and perform a CMD_CMPLT.
3927 	 * If we have associated sense data, see if we can
3928 	 * send that too.
3929 	 */
3930 	if (status == SCSI_STATUS_CHECK_COND) {
3931 		flags |= CAM_SEND_SENSE;
3932 		csio->sense_len = atio->sense_len;
3933 		csio->sense_data = atio->sense_data;
3934 		flags &= ~CAM_DIR_MASK;
3935 		data_len = 0;
3936 		data_ptr = NULL;
3937 	}
3938 	cam_fill_ctio(csio, 0, isptarg_done, flags, MSG_SIMPLE_Q_TAG, atio->tag_id, atio->init_id, status, data_ptr, data_len, 30 * hz);
3939 	iccb->ccb_h.target_id = atio->ccb_h.target_id;
3940 	iccb->ccb_h.target_lun = return_lun;
3941 	iccb->ccb_h.ccb_atio = atio;
3942 	CTIO_SEQ(iccb) = ATIO_PPD(atio)->sequence++;
3943 	ATIO_PPD(atio)->ctio_cnt++;
3944 	if (flags & CAM_SEND_STATUS) {
3945 		KASSERT((ATIO_PPD(atio)->status_sent == 0), ("we have already sent status for 0x%x in %s", atio->tag_id, __func__));
3946 		ATIO_PPD(atio)->status_sent = 1;
3947 	}
3948 	ISP_PATH_PRT(softc->isp, ISP_LOGTDEBUG0, atio->ccb_h.path, "%s: sending downstream for  0x%x sequence %u len %u flags %x\n", __func__, atio->tag_id, CTIO_SEQ(iccb), data_len, flags);
3949 	xpt_action(iccb);
3950 
3951 	if ((atio->ccb_h.status & CAM_DEV_QFRZN) != 0) {
3952 		cam_release_devq(periph->path, 0, 0, 0, 0);
3953 		atio->ccb_h.status &= ~CAM_DEV_QFRZN;
3954 	}
3955 #ifdef	ISP_MULTI_CCBS
3956 	if (is_data_cmd && ATIO_PPD(atio)->status_sent == 0 && ATIO_PPD(atio)->ctio_cnt < MULTI_CCB_DATA_CNT && ATIO_PPD(atio)->on_queue == 0) {
3957 		ISP_PATH_PRT(softc->isp, ISP_LOGTDEBUG0, atio->ccb_h.path, "%s: more still to do for 0x%x\n", __func__, atio->tag_id);
3958 		TAILQ_INSERT_TAIL(&softc->rework_queue, &atio->ccb_h, periph_links.tqe);
3959 		ATIO_PPD(atio)->on_queue = 1;
3960 		more = 1;
3961 	}
3962 #endif
3963 	if (more) {
3964 		xpt_schedule(periph, 1);
3965 	}
3966 }
3967 
3968 static cam_status
3969 isptargctor(struct cam_periph *periph, void *arg)
3970 {
3971 	struct isptarg_softc *softc;
3972 
3973 	softc = (struct isptarg_softc *)arg;
3974 	periph->softc = softc;
3975 	softc->periph = periph;
3976 	softc->path = periph->path;
3977 	ISP_PATH_PRT(softc->isp, ISP_LOGTDEBUG1, periph->path, "%s called\n", __func__);
3978 	return (CAM_REQ_CMP);
3979 }
3980 
3981 static void
3982 isptargdtor(struct cam_periph *periph)
3983 {
3984 	struct isptarg_softc *softc;
3985 	softc = (struct isptarg_softc *)periph->softc;
3986 	ISP_PATH_PRT(softc->isp, ISP_LOGTDEBUG1, periph->path, "%s called\n", __func__);
3987 	softc->periph = NULL;
3988 	softc->path = NULL;
3989 	periph->softc = NULL;
3990 }
3991 
3992 static void
3993 isptarg_done(struct cam_periph *periph, union ccb *ccb)
3994 {
3995 	struct isptarg_softc *softc;
3996 	ispsoftc_t *isp;
3997 	uint32_t newoff;
3998 	struct ccb_accept_tio *atio;
3999 	struct ccb_immediate_notify *inot;
4000 	cam_status status;
4001 
4002 	softc = (struct isptarg_softc *)periph->softc;
4003 	isp = softc->isp;
4004 	status = ccb->ccb_h.status & CAM_STATUS_MASK;
4005 
4006 	switch (ccb->ccb_h.func_code) {
4007 	case XPT_ACCEPT_TARGET_IO:
4008 		atio = (struct ccb_accept_tio *) ccb;
4009 		ISP_PATH_PRT(isp, ISP_LOGTDEBUG0, ccb->ccb_h.path, "[0x%x] ATIO seen in %s\n", atio->tag_id, __func__);
4010 		memset(ATIO_PPD(atio), 0, sizeof (ppd_t));
4011 		TAILQ_INSERT_TAIL(&softc->work_queue, &ccb->ccb_h, periph_links.tqe);
4012 		ATIO_PPD(atio)->on_queue = 1;
4013 		xpt_schedule(periph, 1);
4014 		break;
4015 	case XPT_IMMEDIATE_NOTIFY:
4016 		inot = (struct ccb_immediate_notify *) ccb;
4017 		ISP_PATH_PRT(isp, ISP_LOGTDEBUG0, ccb->ccb_h.path, "[0x%x] INOT for 0x%x seen in %s\n", inot->tag_id, inot->seq_id, __func__);
4018 		TAILQ_INSERT_TAIL(&softc->inot_queue, &ccb->ccb_h, periph_links.tqe);
4019 		xpt_schedule(periph, 1);
4020 		break;
4021 	case XPT_CONT_TARGET_IO:
4022 		atio = ccb->ccb_h.ccb_atio;
4023 		KASSERT((ATIO_PPD(atio)->ctio_cnt != 0), ("ctio zero when finishing a CTIO"));
4024 		ATIO_PPD(atio)->ctio_cnt--;
4025 		if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
4026 			switch (ccb->ccb_h.status & CAM_STATUS_MASK) {
4027 			case CAM_MESSAGE_RECV:
4028 				newoff = (ccb->csio.msg_ptr[3] << 24) | (ccb->csio.msg_ptr[4] << 16) | (ccb->csio.msg_ptr[5] << 8) | (ccb->csio.msg_ptr[6]);
4029 				ISP_PATH_PRT(isp, ISP_LOGWARN, ccb->ccb_h.path, "[0x%x] got message to return to reset offset to 0x%x at sequence %u\n", atio->tag_id, newoff, CTIO_SEQ(ccb));
4030 				ATIO_PPD(atio)->offset = newoff;
4031 				ATIO_PPD(atio)->status_sent = 0;
4032 				if (ATIO_PPD(atio)->on_queue == 0) {
4033 					TAILQ_INSERT_TAIL(&softc->rework_queue, &atio->ccb_h, periph_links.tqe);
4034 					ATIO_PPD(atio)->on_queue = 1;
4035 				}
4036 				xpt_schedule(periph, 1);
4037 				break;
4038 			default:
4039 				cam_error_print(ccb, CAM_ESF_ALL, CAM_EPF_ALL);
4040 				xpt_action((union ccb *)atio);
4041 				break;
4042 			}
4043 		} else if ((ccb->ccb_h.flags & CAM_SEND_STATUS) == 0) {
4044 			ISP_PATH_PRT(isp, ISP_LOGTDEBUG0, ccb->ccb_h.path, "[0x%x] MID CTIO sequence %u seen in %s\n", atio->tag_id, CTIO_SEQ(ccb), __func__);
4045 			if (ATIO_PPD(atio)->status_sent == 0 && ATIO_PPD(atio)->on_queue == 0) {
4046 				TAILQ_INSERT_TAIL(&softc->rework_queue, &atio->ccb_h, periph_links.tqe);
4047 				ATIO_PPD(atio)->on_queue = 1;
4048 			}
4049 			xpt_schedule(periph, 1);
4050 		} else {
4051 			KASSERT((ATIO_PPD(atio)->ctio_cnt == 0), ("ctio count still %d when we think we've sent the STATUS ctio", ATIO_PPD(atio)->ctio_cnt));
4052 			ISP_PATH_PRT(isp, ISP_LOGTDEBUG0, ccb->ccb_h.path, "[0x%x] FINAL CTIO sequence %u seen in %s\n", atio->tag_id, CTIO_SEQ(ccb), __func__);
4053 			xpt_action((union ccb *)atio);
4054 		}
4055 		if ((ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
4056 			cam_release_devq(ccb->ccb_h.path, 0, 0, 0, 0);
4057 			ccb->ccb_h.status &= ~CAM_DEV_QFRZN;
4058 		}
4059 		xpt_release_ccb(ccb);
4060 		break;
4061 	case XPT_NOTIFY_ACKNOWLEDGE:
4062 		if ((ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
4063 			cam_release_devq(ccb->ccb_h.path, 0, 0, 0, 0);
4064 			ccb->ccb_h.status &= ~CAM_DEV_QFRZN;
4065 		}
4066 		inot = ccb->ccb_h.ccb_inot;
4067 		ISP_PATH_PRT(isp, ISP_LOGTDEBUG1, inot->ccb_h.path, "[0x%x] recycle notify for tag 0x%x\n", inot->tag_id, inot->seq_id);
4068 		xpt_release_ccb(ccb);
4069 		xpt_action((union ccb *)inot);
4070 		break;
4071 	default:
4072 		xpt_print(ccb->ccb_h.path, "unexpected code 0x%x\n", ccb->ccb_h.func_code);
4073 		break;
4074 	}
4075 }
4076 
4077 static void
4078 isptargasync(void *callback_arg, u_int32_t code, struct cam_path *path, void *arg)
4079 {
4080 	struct ac_contract *acp = arg;
4081 	struct ac_device_changed *fc = (struct ac_device_changed *) acp->contract_data;
4082 
4083 	if (code != AC_CONTRACT) {
4084 		return;
4085 	}
4086 	xpt_print(path, "0x%016llx Port ID 0x%06x %s\n", (unsigned long long) fc->wwpn, fc->port, fc->arrived? "arrived" : "departed");
4087 }
4088 
4089 static void
4090 isp_target_thread(ispsoftc_t *isp, int chan)
4091 {
4092 	union ccb *ccb = NULL;
4093 	int i;
4094 	void *wchan;
4095 	cam_status status;
4096 	struct isptarg_softc *softc = NULL;
4097 	struct cam_periph *periph = NULL, *wperiph = NULL;
4098 	struct cam_path *path, *wpath;
4099 	struct cam_sim *sim;
4100 
4101 	if (disk_data == NULL) {
4102 		disk_size = roundup2(vm_kmem_size >> 1, (1ULL << 20));
4103 		if (disk_size < (50 << 20)) {
4104 			disk_size = 50 << 20;
4105 		}
4106 		disk_data = malloc(disk_size, M_ISPTARG, M_WAITOK | M_ZERO);
4107 		if (disk_data == NULL) {
4108 			isp_prt(isp, ISP_LOGERR, "%s: could not allocate disk data", __func__);
4109 			goto out;
4110 		}
4111 		isp_prt(isp, ISP_LOGINFO, "allocated a %ju MiB disk", (uintmax_t) (disk_size >> 20));
4112 	}
4113 	junk_data = malloc(JUNK_SIZE, M_ISPTARG, M_WAITOK | M_ZERO);
4114 	if (junk_data == NULL) {
4115 		isp_prt(isp, ISP_LOGERR, "%s: could not allocate junk", __func__);
4116 		goto out;
4117 	}
4118 
4119 
4120 	softc = malloc(sizeof (*softc), M_ISPTARG, M_WAITOK | M_ZERO);
4121 	if (softc == NULL) {
4122 		isp_prt(isp, ISP_LOGERR, "%s: could not allocate softc", __func__);
4123 		goto out;
4124 	}
4125 	TAILQ_INIT(&softc->work_queue);
4126 	TAILQ_INIT(&softc->rework_queue);
4127 	TAILQ_INIT(&softc->running_queue);
4128 	TAILQ_INIT(&softc->inot_queue);
4129 	softc->isp = isp;
4130 
4131 	periphdriver_register(&isptargdriver);
4132 	ISP_GET_PC(isp, chan, sim, sim);
4133 	ISP_GET_PC(isp, chan, path,  path);
4134 	status = xpt_create_path(&wpath, NULL, cam_sim_path(sim), CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
4135 	if (status != CAM_REQ_CMP) {
4136 		isp_prt(isp, ISP_LOGERR, "%s: could not allocate wildcard path", __func__);
4137 		return;
4138 	}
4139 	status = xpt_create_path(&path, NULL, cam_sim_path(sim), 0, 0);
4140 	if (status != CAM_REQ_CMP) {
4141 		xpt_free_path(wpath);
4142 		isp_prt(isp, ISP_LOGERR, "%s: could not allocate path", __func__);
4143 		return;
4144 	}
4145 
4146 	ISP_LOCK(isp);
4147 	status = cam_periph_alloc(isptargctor, NULL, isptargdtor, isptargstart, "isptarg", CAM_PERIPH_BIO, wpath, NULL, 0, softc);
4148 	if (status != CAM_REQ_CMP) {
4149 		ISP_UNLOCK(isp);
4150 		isp_prt(isp, ISP_LOGERR, "%s: cam_periph_alloc for wildcard failed", __func__);
4151 		goto out;
4152 	}
4153 	wperiph = cam_periph_find(wpath, "isptarg");
4154 	if (wperiph == NULL) {
4155 		ISP_UNLOCK(isp);
4156 		isp_prt(isp, ISP_LOGERR, "%s: wildcard periph already allocated but doesn't exist", __func__);
4157 		goto out;
4158 	}
4159 
4160 	status = cam_periph_alloc(isptargctor, NULL, isptargdtor, isptargstart, "isptarg", CAM_PERIPH_BIO, path, NULL, 0, softc);
4161 	if (status != CAM_REQ_CMP) {
4162 		ISP_UNLOCK(isp);
4163 		isp_prt(isp, ISP_LOGERR, "%s: cam_periph_alloc failed", __func__);
4164 		goto out;
4165 	}
4166 
4167 	periph = cam_periph_find(path, "isptarg");
4168 	if (periph == NULL) {
4169 		ISP_UNLOCK(isp);
4170 		isp_prt(isp, ISP_LOGERR, "%s: periph already allocated but doesn't exist", __func__);
4171 		goto out;
4172 	}
4173 
4174 	status = xpt_register_async(AC_CONTRACT, isptargasync, isp, wpath);
4175 	if (status != CAM_REQ_CMP) {
4176 		ISP_UNLOCK(isp);
4177 		isp_prt(isp, ISP_LOGERR, "%s: xpt_register_async failed", __func__);
4178 		goto out;
4179 	}
4180 
4181 	ISP_UNLOCK(isp);
4182 
4183 	ccb = xpt_alloc_ccb();
4184 
4185 	/*
4186 	 * Make sure role is none.
4187 	 */
4188 	xpt_setup_ccb(&ccb->ccb_h, periph->path, 10);
4189 	ccb->ccb_h.func_code = XPT_SET_SIM_KNOB;
4190 	ccb->knob.xport_specific.fc.role = KNOB_ROLE_NONE;
4191 	ccb->knob.xport_specific.fc.valid = KNOB_VALID_ROLE;
4192 
4193 	ISP_LOCK(isp);
4194 	xpt_action(ccb);
4195 	ISP_UNLOCK(isp);
4196 
4197 	/*
4198 	 * Now enable luns
4199 	 */
4200 	xpt_setup_ccb(&ccb->ccb_h, periph->path, 10);
4201 	ccb->ccb_h.func_code = XPT_EN_LUN;
4202 	ccb->cel.enable = 1;
4203 	ISP_LOCK(isp);
4204 	xpt_action(ccb);
4205 	ISP_UNLOCK(isp);
4206 	if (ccb->ccb_h.status != CAM_REQ_CMP) {
4207 		xpt_free_ccb(ccb);
4208 		xpt_print(periph->path, "failed to enable lun (0x%x)\n", ccb->ccb_h.status);
4209 		goto out;
4210 	}
4211 
4212 	xpt_setup_ccb(&ccb->ccb_h, wperiph->path, 10);
4213 	ccb->ccb_h.func_code = XPT_EN_LUN;
4214 	ccb->cel.enable = 1;
4215 	ISP_LOCK(isp);
4216 	xpt_action(ccb);
4217 	ISP_UNLOCK(isp);
4218 	if (ccb->ccb_h.status != CAM_REQ_CMP) {
4219 		xpt_free_ccb(ccb);
4220 		xpt_print(wperiph->path, "failed to enable lun (0x%x)\n", ccb->ccb_h.status);
4221 		goto out;
4222 	}
4223 	xpt_free_ccb(ccb);
4224 
4225 	/*
4226 	 * Add resources
4227 	 */
4228 	ISP_GET_PC_ADDR(isp, chan, target_proc, wchan);
4229 	for (i = 0; i < 4; i++) {
4230 		ccb = malloc(sizeof (*ccb), M_ISPTARG, M_WAITOK | M_ZERO);
4231 		xpt_setup_ccb(&ccb->ccb_h, wperiph->path, 1);
4232 		ccb->ccb_h.func_code = XPT_ACCEPT_TARGET_IO;
4233 		ccb->ccb_h.cbfcnp = isptarg_done;
4234 		ccb->ccb_h.ppriv_ptr0 = malloc(sizeof (ppd_t), M_ISPTARG, M_WAITOK | M_ZERO);
4235 		ISP_LOCK(isp);
4236 		xpt_action(ccb);
4237 		ISP_UNLOCK(isp);
4238 	}
4239 	for (i = 0; i < NISP_TARG_CMDS; i++) {
4240 		ccb = malloc(sizeof (*ccb), M_ISPTARG, M_WAITOK | M_ZERO);
4241 		xpt_setup_ccb(&ccb->ccb_h, periph->path, 1);
4242 		ccb->ccb_h.func_code = XPT_ACCEPT_TARGET_IO;
4243 		ccb->ccb_h.cbfcnp = isptarg_done;
4244 		ccb->ccb_h.ppriv_ptr0 = malloc(sizeof (ppd_t), M_ISPTARG, M_WAITOK | M_ZERO);
4245 		ISP_LOCK(isp);
4246 		xpt_action(ccb);
4247 		ISP_UNLOCK(isp);
4248 	}
4249 	for (i = 0; i < 4; i++) {
4250 		ccb = malloc(sizeof (*ccb), M_ISPTARG, M_WAITOK | M_ZERO);
4251 		xpt_setup_ccb(&ccb->ccb_h, wperiph->path, 1);
4252 		ccb->ccb_h.func_code = XPT_IMMEDIATE_NOTIFY;
4253 		ccb->ccb_h.cbfcnp = isptarg_done;
4254 		ISP_LOCK(isp);
4255 		xpt_action(ccb);
4256 		ISP_UNLOCK(isp);
4257 	}
4258 	for (i = 0; i < NISP_TARG_NOTIFIES; i++) {
4259 		ccb = malloc(sizeof (*ccb), M_ISPTARG, M_WAITOK | M_ZERO);
4260 		xpt_setup_ccb(&ccb->ccb_h, periph->path, 1);
4261 		ccb->ccb_h.func_code = XPT_IMMEDIATE_NOTIFY;
4262 		ccb->ccb_h.cbfcnp = isptarg_done;
4263 		ISP_LOCK(isp);
4264 		xpt_action(ccb);
4265 		ISP_UNLOCK(isp);
4266 	}
4267 
4268 	/*
4269 	 * Now turn it all back on
4270 	 */
4271 	xpt_setup_ccb(&ccb->ccb_h, periph->path, 10);
4272 	ccb->ccb_h.func_code = XPT_SET_SIM_KNOB;
4273 	ccb->knob.xport_specific.fc.valid = KNOB_VALID_ROLE;
4274 	ccb->knob.xport_specific.fc.role = KNOB_ROLE_TARGET;
4275 	ISP_LOCK(isp);
4276 	xpt_action(ccb);
4277 	ISP_UNLOCK(isp);
4278 
4279 	/*
4280 	 * Okay, while things are still active, sleep...
4281 	 */
4282 	ISP_LOCK(isp);
4283 	for (;;) {
4284 		ISP_GET_PC(isp, chan, proc_active, i);
4285 		if (i == 0) {
4286 			break;
4287 		}
4288 		msleep(wchan, &isp->isp_lock, PUSER, "tsnooze", 0);
4289 	}
4290 	ISP_UNLOCK(isp);
4291 
4292 out:
4293 	if (wperiph) {
4294 		cam_periph_invalidate(wperiph);
4295 	}
4296 	if (periph) {
4297 		cam_periph_invalidate(periph);
4298 	}
4299 	if (junk_data) {
4300 		free(junk_data, M_ISPTARG);
4301 	}
4302 	if (disk_data) {
4303 		free(disk_data, M_ISPTARG);
4304 	}
4305 	if (softc) {
4306 		free(softc, M_ISPTARG);
4307 	}
4308 	xpt_free_path(path);
4309 	xpt_free_path(wpath);
4310 }
4311 
4312 static void
4313 isp_target_thread_pi(void *arg)
4314 {
4315 	struct isp_spi *pi = arg;
4316 	isp_target_thread(cam_sim_softc(pi->sim), cam_sim_bus(pi->sim));
4317 }
4318 
4319 static void
4320 isp_target_thread_fc(void *arg)
4321 {
4322 	struct isp_fc *fc = arg;
4323 	isp_target_thread(cam_sim_softc(fc->sim), cam_sim_bus(fc->sim));
4324 }
4325 
4326 static int
4327 isptarg_rwparm(uint8_t *cdb, uint8_t *dp, uint64_t dl, uint32_t offset, uint8_t **kp, uint32_t *tl, int *lp)
4328 {
4329 	uint32_t cnt, curcnt;
4330 	uint64_t lba;
4331 
4332 	switch (cdb[0]) {
4333 	case WRITE_16:
4334 	case READ_16:
4335 		cnt =	(((uint32_t)cdb[10]) <<  24) |
4336 			(((uint32_t)cdb[11]) <<  16) |
4337 			(((uint32_t)cdb[12]) <<   8) |
4338 			((uint32_t)cdb[13]);
4339 
4340 		lba =	(((uint64_t)cdb[2]) << 56) |
4341 			(((uint64_t)cdb[3]) << 48) |
4342 			(((uint64_t)cdb[4]) << 40) |
4343 			(((uint64_t)cdb[5]) << 32) |
4344 			(((uint64_t)cdb[6]) << 24) |
4345 			(((uint64_t)cdb[7]) << 16) |
4346 			(((uint64_t)cdb[8]) <<  8) |
4347 			((uint64_t)cdb[9]);
4348 		break;
4349 	case WRITE_12:
4350 	case READ_12:
4351 		cnt =	(((uint32_t)cdb[6]) <<  16) |
4352 			(((uint32_t)cdb[7]) <<   8) |
4353 			((u_int32_t)cdb[8]);
4354 
4355 		lba =	(((uint32_t)cdb[2]) << 24) |
4356 			(((uint32_t)cdb[3]) << 16) |
4357 			(((uint32_t)cdb[4]) <<  8) |
4358 			((uint32_t)cdb[5]);
4359 		break;
4360 	case WRITE_10:
4361 	case READ_10:
4362 		cnt =	(((uint32_t)cdb[7]) <<  8) |
4363 			((u_int32_t)cdb[8]);
4364 
4365 		lba =	(((uint32_t)cdb[2]) << 24) |
4366 			(((uint32_t)cdb[3]) << 16) |
4367 			(((uint32_t)cdb[4]) <<  8) |
4368 			((uint32_t)cdb[5]);
4369 		break;
4370 	case WRITE_6:
4371 	case READ_6:
4372 		cnt = cdb[4];
4373 		if (cnt == 0) {
4374 			cnt = 256;
4375 		}
4376 		lba =	(((uint32_t)cdb[1] & 0x1f) << 16) |
4377 			(((uint32_t)cdb[2]) << 8) |
4378 			((uint32_t)cdb[3]);
4379 		break;
4380 	default:
4381 		return (-1);
4382 	}
4383 
4384 	cnt <<= DISK_SHIFT;
4385 	lba <<= DISK_SHIFT;
4386 
4387 	if (offset == cnt) {
4388 		*lp = 1;
4389 		return (0);
4390 	}
4391 
4392 	if (lba + cnt > dl) {
4393 		return (-2);
4394 	}
4395 
4396 	curcnt = MAX_ISP_TARG_TRANSFER;
4397 	if (offset + curcnt >= cnt) {
4398 		curcnt = cnt - offset;
4399 		*lp = 1;
4400 	} else {
4401 		*lp = 0;
4402 	}
4403 #ifdef	ISP_MULTI_CCBS
4404 	if (curcnt > MULTI_CCB_DATA_LIM)
4405 		curcnt = MULTI_CCB_DATA_LIM;
4406 #endif
4407 	*tl = curcnt;
4408 	*kp = &dp[lba + offset];
4409 	return (0);
4410 }
4411 
4412 #endif
4413 #endif
4414 
4415 static void
4416 isp_cam_async(void *cbarg, uint32_t code, struct cam_path *path, void *arg)
4417 {
4418 	struct cam_sim *sim;
4419 	int bus, tgt;
4420 	ispsoftc_t *isp;
4421 
4422 	sim = (struct cam_sim *)cbarg;
4423 	isp = (ispsoftc_t *) cam_sim_softc(sim);
4424 	bus = cam_sim_bus(sim);
4425 	tgt = xpt_path_target_id(path);
4426 
4427 	switch (code) {
4428 	case AC_LOST_DEVICE:
4429 		if (IS_SCSI(isp)) {
4430 			uint16_t oflags, nflags;
4431 			sdparam *sdp = SDPARAM(isp, bus);
4432 
4433 			if (tgt >= 0) {
4434 				nflags = sdp->isp_devparam[tgt].nvrm_flags;
4435 #ifndef	ISP_TARGET_MODE
4436 				nflags &= DPARM_SAFE_DFLT;
4437 				if (isp->isp_loaded_fw) {
4438 					nflags |= DPARM_NARROW | DPARM_ASYNC;
4439 				}
4440 #else
4441 				nflags = DPARM_DEFAULT;
4442 #endif
4443 				oflags = sdp->isp_devparam[tgt].goal_flags;
4444 				sdp->isp_devparam[tgt].goal_flags = nflags;
4445 				sdp->isp_devparam[tgt].dev_update = 1;
4446 				sdp->update = 1;
4447 				(void) isp_control(isp, ISPCTL_UPDATE_PARAMS, bus);
4448 				sdp->isp_devparam[tgt].goal_flags = oflags;
4449 			}
4450 		}
4451 		break;
4452 	default:
4453 		isp_prt(isp, ISP_LOGWARN, "isp_cam_async: Code 0x%x", code);
4454 		break;
4455 	}
4456 }
4457 
4458 static void
4459 isp_poll(struct cam_sim *sim)
4460 {
4461 	ispsoftc_t *isp = cam_sim_softc(sim);
4462 	uint32_t isr;
4463 	uint16_t sema, mbox;
4464 
4465 	if (ISP_READ_ISR(isp, &isr, &sema, &mbox)) {
4466 		isp_intr(isp, isr, sema, mbox);
4467 	}
4468 }
4469 
4470 
4471 static void
4472 isp_watchdog(void *arg)
4473 {
4474 	struct ccb_scsiio *xs = arg;
4475 	ispsoftc_t *isp;
4476 	uint32_t ohandle = ISP_HANDLE_FREE, handle;
4477 
4478 	isp = XS_ISP(xs);
4479 
4480 	handle = isp_find_handle(isp, xs);
4481 
4482 	/*
4483 	 * Hand crank the interrupt code just to be sure the command isn't stuck somewhere.
4484 	 */
4485 	if (handle != ISP_HANDLE_FREE) {
4486 		uint32_t isr;
4487 		uint16_t sema, mbox;
4488 		if (ISP_READ_ISR(isp, &isr, &sema, &mbox) != 0) {
4489 			isp_intr(isp, isr, sema, mbox);
4490 		}
4491 		ohandle = handle;
4492 		handle = isp_find_handle(isp, xs);
4493 	}
4494 	if (handle != ISP_HANDLE_FREE) {
4495 		/*
4496 		 * Try and make sure the command is really dead before
4497 		 * we release the handle (and DMA resources) for reuse.
4498 		 *
4499 		 * If we are successful in aborting the command then
4500 		 * we're done here because we'll get the command returned
4501 		 * back separately.
4502 		 */
4503 		if (isp_control(isp, ISPCTL_ABORT_CMD, xs) == 0) {
4504 			return;
4505 		}
4506 
4507 		/*
4508 		 * Note that after calling the above, the command may in
4509 		 * fact have been completed.
4510 		 */
4511 		xs = isp_find_xs(isp, handle);
4512 
4513 		/*
4514 		 * If the command no longer exists, then we won't
4515 		 * be able to find the xs again with this handle.
4516 		 */
4517 		if (xs == NULL) {
4518 			return;
4519 		}
4520 
4521 		/*
4522 		 * After this point, the command is really dead.
4523 		 */
4524 		if (XS_XFRLEN(xs)) {
4525 			ISP_DMAFREE(isp, xs, handle);
4526 		}
4527 		isp_destroy_handle(isp, handle);
4528 		isp_prt(isp, ISP_LOGERR, "%s: timeout for handle 0x%x", __func__, handle);
4529 		xs->ccb_h.status &= ~CAM_STATUS_MASK;
4530 		xs->ccb_h.status |= CAM_CMD_TIMEOUT;
4531 		isp_prt_endcmd(isp, xs);
4532 		isp_done(xs);
4533 	} else {
4534 		if (ohandle != ISP_HANDLE_FREE) {
4535 			isp_prt(isp, ISP_LOGWARN, "%s: timeout for handle 0x%x, recovered during interrupt", __func__, ohandle);
4536 		} else {
4537 			isp_prt(isp, ISP_LOGWARN, "%s: timeout for handle already free", __func__);
4538 		}
4539 	}
4540 }
4541 
4542 static void
4543 isp_make_here(ispsoftc_t *isp, int chan, int tgt)
4544 {
4545 	union ccb *ccb;
4546 	struct isp_fc *fc = ISP_FC_PC(isp, chan);
4547 
4548 	if (isp_autoconfig == 0) {
4549 		return;
4550 	}
4551 
4552 	/*
4553 	 * Allocate a CCB, create a wildcard path for this target and schedule a rescan.
4554 	 */
4555 	ccb = xpt_alloc_ccb_nowait();
4556 	if (ccb == NULL) {
4557 		isp_prt(isp, ISP_LOGWARN, "Chan %d unable to alloc CCB for rescan", chan);
4558 		return;
4559 	}
4560 	if (xpt_create_path(&ccb->ccb_h.path, NULL, cam_sim_path(fc->sim),
4561 	    tgt, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
4562 		isp_prt(isp, ISP_LOGWARN, "unable to create path for rescan");
4563 		xpt_free_ccb(ccb);
4564 		return;
4565 	}
4566 	xpt_rescan(ccb);
4567 }
4568 
4569 static void
4570 isp_make_gone(ispsoftc_t *isp, int chan, int tgt)
4571 {
4572 	struct cam_path *tp;
4573 	struct isp_fc *fc = ISP_FC_PC(isp, chan);
4574 
4575 	if (isp_autoconfig == 0) {
4576 		return;
4577 	}
4578 	if (xpt_create_path(&tp, NULL, cam_sim_path(fc->sim), tgt, CAM_LUN_WILDCARD) == CAM_REQ_CMP) {
4579 		xpt_async(AC_LOST_DEVICE, tp, NULL);
4580 		xpt_free_path(tp);
4581 	}
4582 }
4583 
4584 /*
4585  * Gone Device Timer Function- when we have decided that a device has gone
4586  * away, we wait a specific period of time prior to telling the OS it has
4587  * gone away.
4588  *
4589  * This timer function fires once a second and then scans the port database
4590  * for devices that are marked dead but still have a virtual target assigned.
4591  * We decrement a counter for that port database entry, and when it hits zero,
4592  * we tell the OS the device has gone away.
4593  */
4594 static void
4595 isp_gdt(void *arg)
4596 {
4597 	struct isp_fc *fc = arg;
4598 	taskqueue_enqueue(taskqueue_thread, &fc->gtask);
4599 }
4600 
4601 static void
4602 isp_gdt_task(void *arg, int pending)
4603 {
4604 	struct isp_fc *fc = arg;
4605 	ispsoftc_t *isp = fc->isp;
4606 	int chan = fc - isp->isp_osinfo.pc.fc;
4607 	fcportdb_t *lp;
4608 	int dbidx, tgt, more_to_do = 0;
4609 
4610 	ISP_LOCK(isp);
4611 	isp_prt(isp, ISP_LOGDEBUG0, "Chan %d GDT timer expired", chan);
4612 	for (dbidx = 0; dbidx < MAX_FC_TARG; dbidx++) {
4613 		lp = &FCPARAM(isp, chan)->portdb[dbidx];
4614 
4615 		if (lp->state != FC_PORTDB_STATE_ZOMBIE) {
4616 			continue;
4617 		}
4618 		if (lp->dev_map_idx == 0 || lp->target_mode) {
4619 			continue;
4620 		}
4621 		if (lp->gone_timer != 0) {
4622 			isp_prt(isp, ISP_LOG_SANCFG, "%s: Chan %d more to do for target %u (timer=%u)", __func__, chan, lp->dev_map_idx - 1, lp->gone_timer);
4623 			lp->gone_timer -= 1;
4624 			more_to_do++;
4625 			continue;
4626 		}
4627 		tgt = lp->dev_map_idx - 1;
4628 		FCPARAM(isp, chan)->isp_dev_map[tgt] = 0;
4629 		lp->dev_map_idx = 0;
4630 		lp->state = FC_PORTDB_STATE_NIL;
4631 		isp_prt(isp, ISP_LOGCONFIG, prom3, chan, lp->portid, tgt, "Gone Device Timeout");
4632 		isp_make_gone(isp, chan, tgt);
4633 	}
4634 	if (fc->ready) {
4635 		if (more_to_do) {
4636 			callout_reset(&fc->gdt, hz, isp_gdt, fc);
4637 		} else {
4638 			callout_deactivate(&fc->gdt);
4639 			isp_prt(isp, ISP_LOG_SANCFG, "Chan %d Stopping Gone Device Timer @ %lu", chan, (unsigned long) time_uptime);
4640 		}
4641 	}
4642 	ISP_UNLOCK(isp);
4643 }
4644 
4645 /*
4646  * Loop Down Timer Function- when loop goes down, a timer is started and
4647  * and after it expires we come here and take all probational devices that
4648  * the OS knows about and the tell the OS that they've gone away.
4649  *
4650  * We don't clear the devices out of our port database because, when loop
4651  * come back up, we have to do some actual cleanup with the chip at that
4652  * point (implicit PLOGO, e.g., to get the chip's port database state right).
4653  */
4654 static void
4655 isp_ldt(void *arg)
4656 {
4657 	struct isp_fc *fc = arg;
4658 	taskqueue_enqueue(taskqueue_thread, &fc->ltask);
4659 }
4660 
4661 static void
4662 isp_ldt_task(void *arg, int pending)
4663 {
4664 	struct isp_fc *fc = arg;
4665 	ispsoftc_t *isp = fc->isp;
4666 	int chan = fc - isp->isp_osinfo.pc.fc;
4667 	fcportdb_t *lp;
4668 	int dbidx, tgt, i;
4669 
4670 	ISP_LOCK(isp);
4671 	isp_prt(isp, ISP_LOG_SANCFG|ISP_LOGDEBUG0, "Chan %d Loop Down Timer expired @ %lu", chan, (unsigned long) time_uptime);
4672 	callout_deactivate(&fc->ldt);
4673 
4674 	/*
4675 	 * Notify to the OS all targets who we now consider have departed.
4676 	 */
4677 	for (dbidx = 0; dbidx < MAX_FC_TARG; dbidx++) {
4678 		lp = &FCPARAM(isp, chan)->portdb[dbidx];
4679 
4680 		if (lp->state != FC_PORTDB_STATE_PROBATIONAL) {
4681 			continue;
4682 		}
4683 		if (lp->dev_map_idx == 0 || lp->target_mode) {
4684 			continue;
4685 		}
4686 
4687 		/*
4688 		 * XXX: CLEAN UP AND COMPLETE ANY PENDING COMMANDS FIRST!
4689 		 */
4690 
4691 
4692 		for (i = 0; i < isp->isp_maxcmds; i++) {
4693 			struct ccb_scsiio *xs;
4694 
4695 			if (!ISP_VALID_HANDLE(isp, isp->isp_xflist[i].handle)) {
4696 				continue;
4697 			}
4698 			if ((xs = isp->isp_xflist[i].cmd) == NULL) {
4699 				continue;
4700                         }
4701 			if (dbidx != (FCPARAM(isp, chan)->isp_dev_map[XS_TGT(xs)] - 1)) {
4702 				continue;
4703 			}
4704 			isp_prt(isp, ISP_LOGWARN, "command handle 0x%x for %d.%d.%d orphaned by loop down timeout",
4705 			    isp->isp_xflist[i].handle, chan, XS_TGT(xs), XS_LUN(xs));
4706 		}
4707 
4708 		/*
4709 		 * Mark that we've announced that this device is gone....
4710 		 */
4711 		lp->announced = 1;
4712 
4713 		/*
4714 		 * but *don't* change the state of the entry. Just clear
4715 		 * any target id stuff and announce to CAM that the
4716 		 * device is gone. This way any necessary PLOGO stuff
4717 		 * will happen when loop comes back up.
4718 		 */
4719 
4720 		tgt = lp->dev_map_idx - 1;
4721 		FCPARAM(isp, chan)->isp_dev_map[tgt] = 0;
4722 		lp->dev_map_idx = 0;
4723 		lp->state = FC_PORTDB_STATE_NIL;
4724 		isp_prt(isp, ISP_LOGCONFIG, prom3, chan, lp->portid, tgt, "Loop Down Timeout");
4725 		isp_make_gone(isp, chan, tgt);
4726 	}
4727 
4728 	if (FCPARAM(isp, chan)->role & ISP_ROLE_INITIATOR) {
4729 		isp_unfreeze_loopdown(isp, chan);
4730 	}
4731 	/*
4732 	 * The loop down timer has expired. Wake up the kthread
4733 	 * to notice that fact (or make it false).
4734 	 */
4735 	fc->loop_dead = 1;
4736 	fc->loop_down_time = fc->loop_down_limit+1;
4737 	wakeup(fc);
4738 	ISP_UNLOCK(isp);
4739 }
4740 
4741 static void
4742 isp_kthread(void *arg)
4743 {
4744 	struct isp_fc *fc = arg;
4745 	ispsoftc_t *isp = fc->isp;
4746 	int chan = fc - isp->isp_osinfo.pc.fc;
4747 	int slp = 0;
4748 
4749 	mtx_lock(&isp->isp_osinfo.lock);
4750 
4751 	for (;;) {
4752 		int lb, lim;
4753 
4754 		isp_prt(isp, ISP_LOG_SANCFG|ISP_LOGDEBUG0, "%s: Chan %d checking FC state", __func__, chan);
4755 		lb = isp_fc_runstate(isp, chan, 250000);
4756 
4757 		/*
4758 		 * Our action is different based upon whether we're supporting
4759 		 * Initiator mode or not. If we are, we might freeze the simq
4760 		 * when loop is down and set all sorts of different delays to
4761 		 * check again.
4762 		 *
4763 		 * If not, we simply just wait for loop to come up.
4764 		 */
4765 		if (lb && (FCPARAM(isp, chan)->role & ISP_ROLE_INITIATOR)) {
4766 			/*
4767 			 * Increment loop down time by the last sleep interval
4768 			 */
4769 			fc->loop_down_time += slp;
4770 
4771 			if (lb < 0) {
4772 				isp_prt(isp, ISP_LOG_SANCFG|ISP_LOGDEBUG0, "%s: Chan %d FC loop not up (down count %d)", __func__, chan, fc->loop_down_time);
4773 			} else {
4774 				isp_prt(isp, ISP_LOG_SANCFG|ISP_LOGDEBUG0, "%s: Chan %d FC got to %d (down count %d)", __func__, chan, lb, fc->loop_down_time);
4775 			}
4776 
4777 			/*
4778 			 * If we've never seen loop up and we've waited longer
4779 			 * than quickboot time, or we've seen loop up but we've
4780 			 * waited longer than loop_down_limit, give up and go
4781 			 * to sleep until loop comes up.
4782 			 */
4783 			if (FCPARAM(isp, chan)->loop_seen_once == 0) {
4784 				lim = isp_quickboot_time;
4785 			} else {
4786 				lim = fc->loop_down_limit;
4787 			}
4788 			if (fc->loop_down_time >= lim) {
4789 				isp_freeze_loopdown(isp, chan, "loop limit hit");
4790 				slp = 0;
4791 			} else if (fc->loop_down_time < 10) {
4792 				slp = 1;
4793 			} else if (fc->loop_down_time < 30) {
4794 				slp = 5;
4795 			} else if (fc->loop_down_time < 60) {
4796 				slp = 10;
4797 			} else if (fc->loop_down_time < 120) {
4798 				slp = 20;
4799 			} else {
4800 				slp = 30;
4801 			}
4802 
4803 		} else if (lb) {
4804 			isp_prt(isp, ISP_LOG_SANCFG|ISP_LOGDEBUG0, "%s: Chan %d FC Loop Down", __func__, chan);
4805 			fc->loop_down_time += slp;
4806 			if (fc->loop_down_time > 300)
4807 				slp = 0;
4808 			else
4809 				slp = 60;
4810 		} else {
4811 			isp_prt(isp, ISP_LOG_SANCFG|ISP_LOGDEBUG0, "%s: Chan %d FC state OK", __func__, chan);
4812 			fc->loop_down_time = 0;
4813 			slp = 0;
4814 		}
4815 
4816 
4817 		/*
4818 		 * If this is past the first loop up or the loop is dead and if we'd frozen the simq, unfreeze it
4819 		 * now so that CAM can start sending us commands.
4820 		 *
4821 		 * If the FC state isn't okay yet, they'll hit that in isp_start which will freeze the queue again
4822 		 * or kill the commands, as appropriate.
4823 		 */
4824 
4825 		if (FCPARAM(isp, chan)->loop_seen_once || fc->loop_dead) {
4826 			isp_unfreeze_loopdown(isp, chan);
4827 		}
4828 
4829 		isp_prt(isp, ISP_LOG_SANCFG|ISP_LOGDEBUG0, "%s: Chan %d sleep time %d", __func__, chan, slp);
4830 
4831 		msleep(fc, &isp->isp_osinfo.lock, PRIBIO, "ispf", slp * hz);
4832 
4833 		/*
4834 		 * If slp is zero, we're waking up for the first time after
4835 		 * things have been okay. In this case, we set a deferral state
4836 		 * for all commands and delay hysteresis seconds before starting
4837 		 * the FC state evaluation. This gives the loop/fabric a chance
4838 		 * to settle.
4839 		 */
4840 		if (slp == 0 && fc->hysteresis) {
4841 			isp_prt(isp, ISP_LOG_SANCFG|ISP_LOGDEBUG0, "%s: Chan %d sleep hysteresis ticks %d", __func__, chan, fc->hysteresis * hz);
4842 			mtx_unlock(&isp->isp_osinfo.lock);
4843 			pause("ispt", fc->hysteresis * hz);
4844 			mtx_lock(&isp->isp_osinfo.lock);
4845 		}
4846 	}
4847 	mtx_unlock(&isp->isp_osinfo.lock);
4848 }
4849 
4850 static void
4851 isp_action(struct cam_sim *sim, union ccb *ccb)
4852 {
4853 	int bus, tgt, ts, error, lim;
4854 	ispsoftc_t *isp;
4855 	struct ccb_trans_settings *cts;
4856 
4857 	CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_TRACE, ("isp_action\n"));
4858 
4859 	isp = (ispsoftc_t *)cam_sim_softc(sim);
4860 	mtx_assert(&isp->isp_lock, MA_OWNED);
4861 
4862 	if (isp->isp_state != ISP_RUNSTATE && ccb->ccb_h.func_code == XPT_SCSI_IO) {
4863 		isp_init(isp);
4864 		if (isp->isp_state != ISP_INITSTATE) {
4865 			/*
4866 			 * Lie. Say it was a selection timeout.
4867 			 */
4868 			ccb->ccb_h.status = CAM_SEL_TIMEOUT | CAM_DEV_QFRZN;
4869 			xpt_freeze_devq(ccb->ccb_h.path, 1);
4870 			xpt_done(ccb);
4871 			return;
4872 		}
4873 		isp->isp_state = ISP_RUNSTATE;
4874 	}
4875 	isp_prt(isp, ISP_LOGDEBUG2, "isp_action code %x", ccb->ccb_h.func_code);
4876 	ISP_PCMD(ccb) = NULL;
4877 
4878 	switch (ccb->ccb_h.func_code) {
4879 	case XPT_SCSI_IO:	/* Execute the requested I/O operation */
4880 		bus = XS_CHANNEL(ccb);
4881 		/*
4882 		 * Do a couple of preliminary checks...
4883 		 */
4884 		if ((ccb->ccb_h.flags & CAM_CDB_POINTER) != 0) {
4885 			if ((ccb->ccb_h.flags & CAM_CDB_PHYS) != 0) {
4886 				ccb->ccb_h.status = CAM_REQ_INVALID;
4887 				xpt_done(ccb);
4888 				break;
4889 			}
4890 		}
4891 		ccb->csio.req_map = NULL;
4892 #ifdef	DIAGNOSTIC
4893 		if (ccb->ccb_h.target_id > (ISP_MAX_TARGETS(isp) - 1)) {
4894 			xpt_print(ccb->ccb_h.path, "invalid target\n");
4895 			ccb->ccb_h.status = CAM_PATH_INVALID;
4896 		} else if (ccb->ccb_h.target_lun > (ISP_MAX_LUNS(isp) - 1)) {
4897 			xpt_print(ccb->ccb_h.path, "invalid lun\n");
4898 			ccb->ccb_h.status = CAM_PATH_INVALID;
4899 		}
4900 		if (ccb->ccb_h.status == CAM_PATH_INVALID) {
4901 			xpt_done(ccb);
4902 			break;
4903 		}
4904 #endif
4905 		ccb->csio.scsi_status = SCSI_STATUS_OK;
4906 		if (isp_get_pcmd(isp, ccb)) {
4907 			isp_prt(isp, ISP_LOGWARN, "out of PCMDs");
4908 			cam_freeze_devq(ccb->ccb_h.path);
4909 			cam_release_devq(ccb->ccb_h.path, RELSIM_RELEASE_AFTER_TIMEOUT, 0, 250, 0);
4910 			xpt_done(ccb);
4911 			break;
4912 		}
4913 		error = isp_start((XS_T *) ccb);
4914 		switch (error) {
4915 		case CMD_QUEUED:
4916 			ccb->ccb_h.status |= CAM_SIM_QUEUED;
4917 			if (ccb->ccb_h.timeout == CAM_TIME_INFINITY) {
4918 				break;
4919 			}
4920 			ts = ccb->ccb_h.timeout;
4921 			if (ts == CAM_TIME_DEFAULT) {
4922 				ts = 60*1000;
4923 			}
4924 			ts = isp_mstohz(ts);
4925 			callout_reset(&PISP_PCMD(ccb)->wdog, ts, isp_watchdog, ccb);
4926 			break;
4927 		case CMD_RQLATER:
4928 			/*
4929 			 * We get this result for FC devices if the loop state isn't ready yet
4930 			 * or if the device in question has gone zombie on us.
4931 			 *
4932 			 * If we've never seen Loop UP at all, we requeue this request and wait
4933 			 * for the initial loop up delay to expire.
4934 			 */
4935 			lim = ISP_FC_PC(isp, bus)->loop_down_limit;
4936 			if (FCPARAM(isp, bus)->loop_seen_once == 0 || ISP_FC_PC(isp, bus)->loop_down_time >= lim) {
4937 				if (FCPARAM(isp, bus)->loop_seen_once == 0) {
4938 					isp_prt(isp, ISP_LOGDEBUG0, "%d.%d loop not seen yet @ %lu", XS_TGT(ccb), XS_LUN(ccb), (unsigned long) time_uptime);
4939 				} else {
4940 					isp_prt(isp, ISP_LOGDEBUG0, "%d.%d downtime (%d) > lim (%d)", XS_TGT(ccb), XS_LUN(ccb), ISP_FC_PC(isp, bus)->loop_down_time, lim);
4941 				}
4942 				ccb->ccb_h.status = CAM_SEL_TIMEOUT|CAM_DEV_QFRZN;
4943 				xpt_freeze_devq(ccb->ccb_h.path, 1);
4944 				isp_free_pcmd(isp, ccb);
4945 				xpt_done(ccb);
4946 				break;
4947 			}
4948 			isp_prt(isp, ISP_LOGDEBUG0, "%d.%d retry later", XS_TGT(ccb), XS_LUN(ccb));
4949 			cam_freeze_devq(ccb->ccb_h.path);
4950 			cam_release_devq(ccb->ccb_h.path, RELSIM_RELEASE_AFTER_TIMEOUT, 0, 1000, 0);
4951 			ccb->ccb_h.status = CAM_REQUEUE_REQ;
4952 			isp_free_pcmd(isp, ccb);
4953 			xpt_done(ccb);
4954 			break;
4955 		case CMD_EAGAIN:
4956 			isp_free_pcmd(isp, ccb);
4957 			cam_freeze_devq(ccb->ccb_h.path);
4958 			cam_release_devq(ccb->ccb_h.path, RELSIM_RELEASE_AFTER_TIMEOUT, 0, 100, 0);
4959 			ccb->ccb_h.status = CAM_REQUEUE_REQ;
4960 			xpt_done(ccb);
4961 			break;
4962 		case CMD_COMPLETE:
4963 			isp_done((struct ccb_scsiio *) ccb);
4964 			break;
4965 		default:
4966 			isp_prt(isp, ISP_LOGERR, "What's this? 0x%x at %d in file %s", error, __LINE__, __FILE__);
4967 			ccb->ccb_h.status = CAM_REQUEUE_REQ;
4968 			isp_free_pcmd(isp, ccb);
4969 			xpt_done(ccb);
4970 		}
4971 		break;
4972 
4973 #ifdef	ISP_TARGET_MODE
4974 	case XPT_EN_LUN:		/* Enable/Disable LUN as a target */
4975 		if (ccb->cel.enable) {
4976 			isp_enable_lun(isp, ccb);
4977 		} else {
4978 			isp_disable_lun(isp, ccb);
4979 		}
4980 		break;
4981 	case XPT_IMMED_NOTIFY:
4982 	case XPT_IMMEDIATE_NOTIFY:	/* Add Immediate Notify Resource */
4983 	case XPT_ACCEPT_TARGET_IO:	/* Add Accept Target IO Resource */
4984 	{
4985 		tstate_t *tptr = get_lun_statep(isp, XS_CHANNEL(ccb), ccb->ccb_h.target_lun);
4986 		if (tptr == NULL) {
4987 			tptr = get_lun_statep(isp, XS_CHANNEL(ccb), CAM_LUN_WILDCARD);
4988 		}
4989 		if (tptr == NULL) {
4990 			const char *str;
4991 			uint32_t tag;
4992 
4993 			if (ccb->ccb_h.func_code == XPT_IMMEDIATE_NOTIFY) {
4994 				str = "XPT_IMMEDIATE_NOTIFY";
4995 				tag = ccb->cin1.seq_id;
4996 			} else {
4997 				tag = ccb->atio.tag_id;
4998 				str = "XPT_ACCEPT_TARGET_IO";
4999 			}
5000 			ISP_PATH_PRT(isp, ISP_LOGWARN, ccb->ccb_h.path, "%s: [0x%x] no state pointer found for %s\n", __func__, tag, str);
5001 			dump_tstates(isp, XS_CHANNEL(ccb));
5002 			ccb->ccb_h.status = CAM_DEV_NOT_THERE;
5003 			break;
5004 		}
5005 		ccb->ccb_h.spriv_field0 = 0;
5006 		ccb->ccb_h.spriv_ptr1 = isp;
5007 
5008 		if (ccb->ccb_h.func_code == XPT_ACCEPT_TARGET_IO) {
5009 			if (ccb->atio.tag_id) {
5010 				atio_private_data_t *atp = isp_find_atpd(isp, tptr, ccb->atio.tag_id);
5011 				if (atp) {
5012 					isp_put_atpd(isp, tptr, atp);
5013 				}
5014 			}
5015 			tptr->atio_count++;
5016 			SLIST_INSERT_HEAD(&tptr->atios, &ccb->ccb_h, sim_links.sle);
5017 			ISP_PATH_PRT(isp, ISP_LOGTDEBUG2, ccb->ccb_h.path, "Put FREE ATIO (tag id 0x%x), count now %d\n",
5018 			    ccb->atio.tag_id, tptr->atio_count);
5019 			ccb->atio.tag_id = 0;
5020 		} else if (ccb->ccb_h.func_code == XPT_IMMEDIATE_NOTIFY) {
5021 			if (ccb->cin1.tag_id) {
5022 				inot_private_data_t *ntp = isp_find_ntpd(isp, tptr, ccb->cin1.tag_id, ccb->cin1.seq_id);
5023 				if (ntp) {
5024 					isp_put_ntpd(isp, tptr, ntp);
5025 				}
5026 			}
5027 			tptr->inot_count++;
5028 			SLIST_INSERT_HEAD(&tptr->inots, &ccb->ccb_h, sim_links.sle);
5029 			ISP_PATH_PRT(isp, ISP_LOGTDEBUG2, ccb->ccb_h.path, "Put FREE INOT, (seq id 0x%x) count now %d\n",
5030 			    ccb->cin1.seq_id, tptr->inot_count);
5031 			ccb->cin1.seq_id = 0;
5032 		} else if (ccb->ccb_h.func_code == XPT_IMMED_NOTIFY) {
5033 			tptr->inot_count++;
5034 			SLIST_INSERT_HEAD(&tptr->inots, &ccb->ccb_h, sim_links.sle);
5035 			ISP_PATH_PRT(isp, ISP_LOGTDEBUG2, ccb->ccb_h.path, "Put FREE INOT, (seq id 0x%x) count now %d\n",
5036 			    ccb->cin1.seq_id, tptr->inot_count);
5037 			ccb->cin1.seq_id = 0;
5038 		}
5039 		rls_lun_statep(isp, tptr);
5040 		ccb->ccb_h.status = CAM_REQ_INPROG;
5041 		break;
5042 	}
5043 	case XPT_NOTIFY_ACK:
5044 		ccb->ccb_h.status = CAM_REQ_CMP_ERR;
5045 		break;
5046 	case XPT_NOTIFY_ACKNOWLEDGE:		/* notify ack */
5047 	{
5048 		tstate_t *tptr;
5049 		inot_private_data_t *ntp;
5050 
5051 		/*
5052 		 * XXX: Because we cannot guarantee that the path information in the notify acknowledge ccb
5053 		 * XXX: matches that for the immediate notify, we have to *search* for the notify structure
5054 		 */
5055 		/*
5056 		 * All the relevant path information is in the associated immediate notify
5057 		 */
5058 		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);
5059 		ntp = get_ntp_from_tagdata(isp, ccb->cna2.tag_id, ccb->cna2.seq_id, &tptr);
5060 		if (ntp == NULL) {
5061 			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__,
5062 			     ccb->cna2.tag_id, ccb->cna2.seq_id);
5063 			ccb->ccb_h.status = CAM_DEV_NOT_THERE;
5064 			xpt_done(ccb);
5065 			break;
5066 		}
5067 		if (isp_handle_platform_target_notify_ack(isp, &ntp->rd.nt)) {
5068 			rls_lun_statep(isp, tptr);
5069 			cam_freeze_devq(ccb->ccb_h.path);
5070 			cam_release_devq(ccb->ccb_h.path, RELSIM_RELEASE_AFTER_TIMEOUT, 0, 1000, 0);
5071 			ccb->ccb_h.status &= ~CAM_STATUS_MASK;
5072 			ccb->ccb_h.status |= CAM_REQUEUE_REQ;
5073 			break;
5074 		}
5075 		isp_put_ntpd(isp, tptr, ntp);
5076 		rls_lun_statep(isp, tptr);
5077 		ccb->ccb_h.status = CAM_REQ_CMP;
5078 		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);
5079 		xpt_done(ccb);
5080 		break;
5081 	}
5082 	case XPT_CONT_TARGET_IO:
5083 		isp_target_start_ctio(isp, ccb, FROM_CAM);
5084 		break;
5085 #endif
5086 	case XPT_RESET_DEV:		/* BDR the specified SCSI device */
5087 
5088 		bus = cam_sim_bus(xpt_path_sim(ccb->ccb_h.path));
5089 		tgt = ccb->ccb_h.target_id;
5090 		tgt |= (bus << 16);
5091 
5092 		error = isp_control(isp, ISPCTL_RESET_DEV, bus, tgt);
5093 		if (error) {
5094 			ccb->ccb_h.status = CAM_REQ_CMP_ERR;
5095 		} else {
5096 			ccb->ccb_h.status = CAM_REQ_CMP;
5097 		}
5098 		xpt_done(ccb);
5099 		break;
5100 	case XPT_ABORT:			/* Abort the specified CCB */
5101 	{
5102 		union ccb *accb = ccb->cab.abort_ccb;
5103 		switch (accb->ccb_h.func_code) {
5104 #ifdef	ISP_TARGET_MODE
5105 		case XPT_ACCEPT_TARGET_IO:
5106 			isp_target_mark_aborted(isp, ccb);
5107 			break;
5108 #endif
5109 		case XPT_SCSI_IO:
5110 			error = isp_control(isp, ISPCTL_ABORT_CMD, ccb);
5111 			if (error) {
5112 				ccb->ccb_h.status = CAM_UA_ABORT;
5113 			} else {
5114 				ccb->ccb_h.status = CAM_REQ_CMP;
5115 			}
5116 			break;
5117 		default:
5118 			ccb->ccb_h.status = CAM_REQ_INVALID;
5119 			break;
5120 		}
5121 		/*
5122 		 * This is not a queued CCB, so the caller expects it to be
5123 		 * complete when control is returned.
5124 		 */
5125 		break;
5126 	}
5127 #define	IS_CURRENT_SETTINGS(c)	(c->type == CTS_TYPE_CURRENT_SETTINGS)
5128 	case XPT_SET_TRAN_SETTINGS:	/* Nexus Settings */
5129 		cts = &ccb->cts;
5130 		if (!IS_CURRENT_SETTINGS(cts)) {
5131 			ccb->ccb_h.status = CAM_REQ_INVALID;
5132 			xpt_done(ccb);
5133 			break;
5134 		}
5135 		tgt = cts->ccb_h.target_id;
5136 		bus = cam_sim_bus(xpt_path_sim(cts->ccb_h.path));
5137 		if (IS_SCSI(isp)) {
5138 			struct ccb_trans_settings_scsi *scsi = &cts->proto_specific.scsi;
5139 			struct ccb_trans_settings_spi *spi = &cts->xport_specific.spi;
5140 			sdparam *sdp = SDPARAM(isp, bus);
5141 			uint16_t *dptr;
5142 
5143 			if (spi->valid == 0 && scsi->valid == 0) {
5144 				ccb->ccb_h.status = CAM_REQ_CMP;
5145 				xpt_done(ccb);
5146 				break;
5147 			}
5148 
5149 			/*
5150 			 * We always update (internally) from goal_flags
5151 			 * so any request to change settings just gets
5152 			 * vectored to that location.
5153 			 */
5154 			dptr = &sdp->isp_devparam[tgt].goal_flags;
5155 
5156 			if ((spi->valid & CTS_SPI_VALID_DISC) != 0) {
5157 				if ((spi->flags & CTS_SPI_FLAGS_DISC_ENB) != 0)
5158 					*dptr |= DPARM_DISC;
5159 				else
5160 					*dptr &= ~DPARM_DISC;
5161 			}
5162 
5163 			if ((scsi->valid & CTS_SCSI_VALID_TQ) != 0) {
5164 				if ((scsi->flags & CTS_SCSI_FLAGS_TAG_ENB) != 0)
5165 					*dptr |= DPARM_TQING;
5166 				else
5167 					*dptr &= ~DPARM_TQING;
5168 			}
5169 
5170 			if ((spi->valid & CTS_SPI_VALID_BUS_WIDTH) != 0) {
5171 				if (spi->bus_width == MSG_EXT_WDTR_BUS_16_BIT)
5172 					*dptr |= DPARM_WIDE;
5173 				else
5174 					*dptr &= ~DPARM_WIDE;
5175 			}
5176 
5177 			/*
5178 			 * XXX: FIX ME
5179 			 */
5180 			if ((spi->valid & CTS_SPI_VALID_SYNC_OFFSET) && (spi->valid & CTS_SPI_VALID_SYNC_RATE) && (spi->sync_period && spi->sync_offset)) {
5181 				*dptr |= DPARM_SYNC;
5182 				/*
5183 				 * XXX: CHECK FOR LEGALITY
5184 				 */
5185 				sdp->isp_devparam[tgt].goal_period = spi->sync_period;
5186 				sdp->isp_devparam[tgt].goal_offset = spi->sync_offset;
5187 			} else {
5188 				*dptr &= ~DPARM_SYNC;
5189 			}
5190 			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,
5191 			    sdp->isp_devparam[tgt].goal_offset, sdp->isp_devparam[tgt].goal_period);
5192 			sdp->isp_devparam[tgt].dev_update = 1;
5193 			sdp->update = 1;
5194 		}
5195 		ccb->ccb_h.status = CAM_REQ_CMP;
5196 		xpt_done(ccb);
5197 		break;
5198 	case XPT_GET_TRAN_SETTINGS:
5199 		cts = &ccb->cts;
5200 		tgt = cts->ccb_h.target_id;
5201 		bus = cam_sim_bus(xpt_path_sim(cts->ccb_h.path));
5202 		if (IS_FC(isp)) {
5203 			fcparam *fcp = FCPARAM(isp, bus);
5204 			struct ccb_trans_settings_scsi *scsi = &cts->proto_specific.scsi;
5205 			struct ccb_trans_settings_fc *fc = &cts->xport_specific.fc;
5206 			unsigned int hdlidx;
5207 
5208 			cts->protocol = PROTO_SCSI;
5209 			cts->protocol_version = SCSI_REV_2;
5210 			cts->transport = XPORT_FC;
5211 			cts->transport_version = 0;
5212 
5213 			scsi->valid = CTS_SCSI_VALID_TQ;
5214 			scsi->flags = CTS_SCSI_FLAGS_TAG_ENB;
5215 			fc->valid = CTS_FC_VALID_SPEED;
5216 			fc->bitrate = 100000;
5217 			fc->bitrate *= fcp->isp_gbspeed;
5218 			hdlidx = fcp->isp_dev_map[tgt] - 1;
5219 			if (hdlidx < MAX_FC_TARG) {
5220 				fcportdb_t *lp = &fcp->portdb[hdlidx];
5221 				fc->wwnn = lp->node_wwn;
5222 				fc->wwpn = lp->port_wwn;
5223 				fc->port = lp->portid;
5224 				fc->valid |= CTS_FC_VALID_WWNN | CTS_FC_VALID_WWPN | CTS_FC_VALID_PORT;
5225 			}
5226 		} else {
5227 			struct ccb_trans_settings_scsi *scsi = &cts->proto_specific.scsi;
5228 			struct ccb_trans_settings_spi *spi = &cts->xport_specific.spi;
5229 			sdparam *sdp = SDPARAM(isp, bus);
5230 			uint16_t dval, pval, oval;
5231 
5232 			if (IS_CURRENT_SETTINGS(cts)) {
5233 				sdp->isp_devparam[tgt].dev_refresh = 1;
5234 				sdp->update = 1;
5235 				(void) isp_control(isp, ISPCTL_UPDATE_PARAMS, bus);
5236 				dval = sdp->isp_devparam[tgt].actv_flags;
5237 				oval = sdp->isp_devparam[tgt].actv_offset;
5238 				pval = sdp->isp_devparam[tgt].actv_period;
5239 			} else {
5240 				dval = sdp->isp_devparam[tgt].nvrm_flags;
5241 				oval = sdp->isp_devparam[tgt].nvrm_offset;
5242 				pval = sdp->isp_devparam[tgt].nvrm_period;
5243 			}
5244 
5245 			cts->protocol = PROTO_SCSI;
5246 			cts->protocol_version = SCSI_REV_2;
5247 			cts->transport = XPORT_SPI;
5248 			cts->transport_version = 2;
5249 
5250 			spi->valid = 0;
5251 			scsi->valid = 0;
5252 			spi->flags = 0;
5253 			scsi->flags = 0;
5254 			if (dval & DPARM_DISC) {
5255 				spi->flags |= CTS_SPI_FLAGS_DISC_ENB;
5256 			}
5257 			if ((dval & DPARM_SYNC) && oval && pval) {
5258 				spi->sync_offset = oval;
5259 				spi->sync_period = pval;
5260 			} else {
5261 				spi->sync_offset = 0;
5262 				spi->sync_period = 0;
5263 			}
5264 			spi->valid |= CTS_SPI_VALID_SYNC_OFFSET;
5265 			spi->valid |= CTS_SPI_VALID_SYNC_RATE;
5266 			spi->valid |= CTS_SPI_VALID_BUS_WIDTH;
5267 			if (dval & DPARM_WIDE) {
5268 				spi->bus_width = MSG_EXT_WDTR_BUS_16_BIT;
5269 			} else {
5270 				spi->bus_width = MSG_EXT_WDTR_BUS_8_BIT;
5271 			}
5272 			if (cts->ccb_h.target_lun != CAM_LUN_WILDCARD) {
5273 				scsi->valid = CTS_SCSI_VALID_TQ;
5274 				if (dval & DPARM_TQING) {
5275 					scsi->flags |= CTS_SCSI_FLAGS_TAG_ENB;
5276 				}
5277 				spi->valid |= CTS_SPI_VALID_DISC;
5278 			}
5279 			isp_prt(isp, ISP_LOGDEBUG0, "GET %s (%d.%d.%jx) to flags %x off %x per %x", IS_CURRENT_SETTINGS(cts)? "ACTIVE" : "NVRAM",
5280 			    bus, tgt, (uintmax_t)cts->ccb_h.target_lun, dval, oval, pval);
5281 		}
5282 		ccb->ccb_h.status = CAM_REQ_CMP;
5283 		xpt_done(ccb);
5284 		break;
5285 
5286 	case XPT_CALC_GEOMETRY:
5287 		cam_calc_geometry(&ccb->ccg, 1);
5288 		xpt_done(ccb);
5289 		break;
5290 
5291 	case XPT_RESET_BUS:		/* Reset the specified bus */
5292 		bus = cam_sim_bus(sim);
5293 		error = isp_control(isp, ISPCTL_RESET_BUS, bus);
5294 		if (error) {
5295 			ccb->ccb_h.status = CAM_REQ_CMP_ERR;
5296 			xpt_done(ccb);
5297 			break;
5298 		}
5299 		if (bootverbose) {
5300 			xpt_print(ccb->ccb_h.path, "reset bus on channel %d\n", bus);
5301 		}
5302 		if (IS_FC(isp)) {
5303 			xpt_async(AC_BUS_RESET, ISP_FC_PC(isp, bus)->path, 0);
5304 		} else {
5305 			xpt_async(AC_BUS_RESET, ISP_SPI_PC(isp, bus)->path, 0);
5306 		}
5307 		ccb->ccb_h.status = CAM_REQ_CMP;
5308 		xpt_done(ccb);
5309 		break;
5310 
5311 	case XPT_TERM_IO:		/* Terminate the I/O process */
5312 		ccb->ccb_h.status = CAM_REQ_INVALID;
5313 		xpt_done(ccb);
5314 		break;
5315 
5316 	case XPT_SET_SIM_KNOB:		/* Set SIM knobs */
5317 	{
5318 		struct ccb_sim_knob *kp = &ccb->knob;
5319 		fcparam *fcp;
5320 
5321 		if (!IS_FC(isp)) {
5322 			ccb->ccb_h.status = CAM_REQ_INVALID;
5323 			xpt_done(ccb);
5324 			break;
5325 		}
5326 
5327 		bus = cam_sim_bus(xpt_path_sim(kp->ccb_h.path));
5328 		fcp = FCPARAM(isp, bus);
5329 
5330 		if (kp->xport_specific.fc.valid & KNOB_VALID_ADDRESS) {
5331 			fcp->isp_wwnn = ISP_FC_PC(isp, bus)->def_wwnn = kp->xport_specific.fc.wwnn;
5332 			fcp->isp_wwpn = ISP_FC_PC(isp, bus)->def_wwpn = kp->xport_specific.fc.wwpn;
5333 			isp_prt(isp, ISP_LOGALL, "Setting Channel %d wwns to 0x%jx 0x%jx", bus, fcp->isp_wwnn, fcp->isp_wwpn);
5334 		}
5335 		ccb->ccb_h.status = CAM_REQ_CMP;
5336 		if (kp->xport_specific.fc.valid & KNOB_VALID_ROLE) {
5337 			int rchange = 0;
5338 			int newrole = 0;
5339 
5340 			switch (kp->xport_specific.fc.role) {
5341 			case KNOB_ROLE_NONE:
5342 				if (fcp->role != ISP_ROLE_NONE) {
5343 					rchange = 1;
5344 					newrole = ISP_ROLE_NONE;
5345 				}
5346 				break;
5347 			case KNOB_ROLE_TARGET:
5348 				if (fcp->role != ISP_ROLE_TARGET) {
5349 					rchange = 1;
5350 					newrole = ISP_ROLE_TARGET;
5351 				}
5352 				break;
5353 			case KNOB_ROLE_INITIATOR:
5354 				if (fcp->role != ISP_ROLE_INITIATOR) {
5355 					rchange = 1;
5356 					newrole = ISP_ROLE_INITIATOR;
5357 				}
5358 				break;
5359 			case KNOB_ROLE_BOTH:
5360 #if 0
5361 				if (fcp->role != ISP_ROLE_BOTH) {
5362 					rchange = 1;
5363 					newrole = ISP_ROLE_BOTH;
5364 				}
5365 #else
5366 				/*
5367 				 * We don't really support dual role at present on FC cards.
5368 				 *
5369 				 * We should, but a bunch of things are currently broken,
5370 				 * so don't allow it.
5371 				 */
5372 				isp_prt(isp, ISP_LOGERR, "cannot support dual role at present");
5373 				ccb->ccb_h.status = CAM_REQ_INVALID;
5374 #endif
5375 				break;
5376 			}
5377 			if (rchange) {
5378 				ISP_PATH_PRT(isp, ISP_LOGCONFIG, ccb->ccb_h.path, "changing role on from %d to %d\n", fcp->role, newrole);
5379 #ifdef	ISP_TARGET_MODE
5380 				ISP_SET_PC(isp, bus, tm_enabled, 0);
5381 				ISP_SET_PC(isp, bus, tm_luns_enabled, 0);
5382 #endif
5383 				if (isp_fc_change_role(isp, bus, newrole) != 0) {
5384 					ccb->ccb_h.status = CAM_REQ_CMP_ERR;
5385 					xpt_done(ccb);
5386 					break;
5387 				}
5388 #ifdef	ISP_TARGET_MODE
5389 				if (newrole == ISP_ROLE_TARGET || newrole == ISP_ROLE_BOTH) {
5390 					/*
5391 					 * Give the new role a chance to complain and settle
5392 					 */
5393 					msleep(isp, &isp->isp_lock, PRIBIO, "taking a breather", 2);
5394 					ccb->ccb_h.status = isp_enable_deferred_luns(isp, bus);
5395 				}
5396 #endif
5397 			}
5398 		}
5399 		xpt_done(ccb);
5400 		break;
5401 	}
5402 	case XPT_GET_SIM_KNOB:		/* Get SIM knobs */
5403 	{
5404 		struct ccb_sim_knob *kp = &ccb->knob;
5405 
5406 		if (IS_FC(isp)) {
5407 			fcparam *fcp;
5408 
5409 			bus = cam_sim_bus(xpt_path_sim(kp->ccb_h.path));
5410 			fcp = FCPARAM(isp, bus);
5411 
5412 			kp->xport_specific.fc.wwnn = fcp->isp_wwnn;
5413 			kp->xport_specific.fc.wwpn = fcp->isp_wwpn;
5414 			switch (fcp->role) {
5415 			case ISP_ROLE_NONE:
5416 				kp->xport_specific.fc.role = KNOB_ROLE_NONE;
5417 				break;
5418 			case ISP_ROLE_TARGET:
5419 				kp->xport_specific.fc.role = KNOB_ROLE_TARGET;
5420 				break;
5421 			case ISP_ROLE_INITIATOR:
5422 				kp->xport_specific.fc.role = KNOB_ROLE_INITIATOR;
5423 				break;
5424 			case ISP_ROLE_BOTH:
5425 				kp->xport_specific.fc.role = KNOB_ROLE_BOTH;
5426 				break;
5427 			}
5428 			kp->xport_specific.fc.valid = KNOB_VALID_ADDRESS | KNOB_VALID_ROLE;
5429 			ccb->ccb_h.status = CAM_REQ_CMP;
5430 		} else {
5431 			ccb->ccb_h.status = CAM_REQ_INVALID;
5432 		}
5433 		xpt_done(ccb);
5434 		break;
5435 	}
5436 	case XPT_PATH_INQ:		/* Path routing inquiry */
5437 	{
5438 		struct ccb_pathinq *cpi = &ccb->cpi;
5439 
5440 		cpi->version_num = 1;
5441 #ifdef	ISP_TARGET_MODE
5442 		cpi->target_sprt = PIT_PROCESSOR | PIT_DISCONNECT | PIT_TERM_IO;
5443 #else
5444 		cpi->target_sprt = 0;
5445 #endif
5446 		cpi->hba_eng_cnt = 0;
5447 		cpi->max_target = ISP_MAX_TARGETS(isp) - 1;
5448 		cpi->max_lun = ISP_MAX_LUNS(isp) - 1;
5449 		cpi->bus_id = cam_sim_bus(sim);
5450 		if (isp->isp_osinfo.sixtyfourbit)
5451 			cpi->maxio = (ISP_NSEG64_MAX - 1) * PAGE_SIZE;
5452 		else
5453 			cpi->maxio = (ISP_NSEG_MAX - 1) * PAGE_SIZE;
5454 
5455 		bus = cam_sim_bus(xpt_path_sim(cpi->ccb_h.path));
5456 		if (IS_FC(isp)) {
5457 			fcparam *fcp = FCPARAM(isp, bus);
5458 
5459 			cpi->hba_misc = PIM_NOBUSRESET | PIM_UNMAPPED;
5460 
5461 			/*
5462 			 * Because our loop ID can shift from time to time,
5463 			 * make our initiator ID out of range of our bus.
5464 			 */
5465 			cpi->initiator_id = cpi->max_target + 1;
5466 
5467 			/*
5468 			 * Set base transfer capabilities for Fibre Channel, for this HBA.
5469 			 */
5470 			if (IS_25XX(isp)) {
5471 				cpi->base_transfer_speed = 8000000;
5472 			} else if (IS_24XX(isp)) {
5473 				cpi->base_transfer_speed = 4000000;
5474 			} else if (IS_23XX(isp)) {
5475 				cpi->base_transfer_speed = 2000000;
5476 			} else {
5477 				cpi->base_transfer_speed = 1000000;
5478 			}
5479 			cpi->hba_inquiry = PI_TAG_ABLE;
5480 			cpi->transport = XPORT_FC;
5481 			cpi->transport_version = 0;
5482 			cpi->xport_specific.fc.wwnn = fcp->isp_wwnn;
5483 			cpi->xport_specific.fc.wwpn = fcp->isp_wwpn;
5484 			cpi->xport_specific.fc.port = fcp->isp_portid;
5485 			cpi->xport_specific.fc.bitrate = fcp->isp_gbspeed * 1000;
5486 		} else {
5487 			sdparam *sdp = SDPARAM(isp, bus);
5488 			cpi->hba_inquiry = PI_SDTR_ABLE|PI_TAG_ABLE|PI_WIDE_16;
5489 			cpi->hba_misc = PIM_UNMAPPED;
5490 			cpi->initiator_id = sdp->isp_initiator_id;
5491 			cpi->base_transfer_speed = 3300;
5492 			cpi->transport = XPORT_SPI;
5493 			cpi->transport_version = 2;
5494 		}
5495 		cpi->protocol = PROTO_SCSI;
5496 		cpi->protocol_version = SCSI_REV_2;
5497 		strncpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
5498 		strncpy(cpi->hba_vid, "Qlogic", HBA_IDLEN);
5499 		strncpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
5500 		cpi->unit_number = cam_sim_unit(sim);
5501 		cpi->ccb_h.status = CAM_REQ_CMP;
5502 		xpt_done(ccb);
5503 		break;
5504 	}
5505 	default:
5506 		ccb->ccb_h.status = CAM_REQ_INVALID;
5507 		xpt_done(ccb);
5508 		break;
5509 	}
5510 }
5511 
5512 #define	ISPDDB	(CAM_DEBUG_INFO|CAM_DEBUG_TRACE|CAM_DEBUG_CDB)
5513 
5514 void
5515 isp_done(XS_T *sccb)
5516 {
5517 	ispsoftc_t *isp = XS_ISP(sccb);
5518 	uint32_t status;
5519 
5520 	if (XS_NOERR(sccb))
5521 		XS_SETERR(sccb, CAM_REQ_CMP);
5522 
5523 	if ((sccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP && (sccb->scsi_status != SCSI_STATUS_OK)) {
5524 		sccb->ccb_h.status &= ~CAM_STATUS_MASK;
5525 		if ((sccb->scsi_status == SCSI_STATUS_CHECK_COND) && (sccb->ccb_h.status & CAM_AUTOSNS_VALID) == 0) {
5526 			sccb->ccb_h.status |= CAM_AUTOSENSE_FAIL;
5527 		} else {
5528 			sccb->ccb_h.status |= CAM_SCSI_STATUS_ERROR;
5529 		}
5530 	}
5531 
5532 	sccb->ccb_h.status &= ~CAM_SIM_QUEUED;
5533 	status = sccb->ccb_h.status & CAM_STATUS_MASK;
5534 	if (status != CAM_REQ_CMP) {
5535 		if (status != CAM_SEL_TIMEOUT)
5536 			isp_prt(isp, ISP_LOGDEBUG0, "target %d lun %d CAM status 0x%x SCSI status 0x%x", XS_TGT(sccb), XS_LUN(sccb), sccb->ccb_h.status, sccb->scsi_status);
5537 		if ((sccb->ccb_h.status & CAM_DEV_QFRZN) == 0) {
5538 			sccb->ccb_h.status |= CAM_DEV_QFRZN;
5539 			xpt_freeze_devq(sccb->ccb_h.path, 1);
5540 		}
5541 	}
5542 
5543 	if ((CAM_DEBUGGED(sccb->ccb_h.path, ISPDDB)) && (sccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
5544 		xpt_print(sccb->ccb_h.path, "cam completion status 0x%x\n", sccb->ccb_h.status);
5545 	}
5546 
5547 	if (callout_active(&PISP_PCMD(sccb)->wdog))
5548 		callout_stop(&PISP_PCMD(sccb)->wdog);
5549 	isp_free_pcmd(isp, (union ccb *) sccb);
5550 	xpt_done((union ccb *) sccb);
5551 }
5552 
5553 void
5554 isp_async(ispsoftc_t *isp, ispasync_t cmd, ...)
5555 {
5556 	int bus;
5557 	static const char prom0[] = "Chan %d PortID 0x%06x handle 0x%x %s %s WWPN 0x%08x%08x";
5558 	static const char prom2[] = "Chan %d PortID 0x%06x handle 0x%x %s %s tgt %u WWPN 0x%08x%08x";
5559 	char buf[64];
5560 	char *msg = NULL;
5561 	target_id_t tgt;
5562 	fcportdb_t *lp;
5563 	struct isp_fc *fc;
5564 	struct cam_path *tmppath;
5565 	va_list ap;
5566 
5567 	switch (cmd) {
5568 	case ISPASYNC_NEW_TGT_PARAMS:
5569 	{
5570 		struct ccb_trans_settings_scsi *scsi;
5571 		struct ccb_trans_settings_spi *spi;
5572 		int flags, tgt;
5573 		sdparam *sdp;
5574 		struct ccb_trans_settings cts;
5575 
5576 		memset(&cts, 0, sizeof (struct ccb_trans_settings));
5577 
5578 		va_start(ap, cmd);
5579 		bus = va_arg(ap, int);
5580 		tgt = va_arg(ap, int);
5581 		va_end(ap);
5582 		sdp = SDPARAM(isp, bus);
5583 
5584 		if (xpt_create_path(&tmppath, NULL, cam_sim_path(ISP_SPI_PC(isp, bus)->sim), tgt, CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
5585 			isp_prt(isp, ISP_LOGWARN, "isp_async cannot make temp path for %d.%d", tgt, bus);
5586 			break;
5587 		}
5588 		flags = sdp->isp_devparam[tgt].actv_flags;
5589 		cts.type = CTS_TYPE_CURRENT_SETTINGS;
5590 		cts.protocol = PROTO_SCSI;
5591 		cts.transport = XPORT_SPI;
5592 
5593 		scsi = &cts.proto_specific.scsi;
5594 		spi = &cts.xport_specific.spi;
5595 
5596 		if (flags & DPARM_TQING) {
5597 			scsi->valid |= CTS_SCSI_VALID_TQ;
5598 			scsi->flags |= CTS_SCSI_FLAGS_TAG_ENB;
5599 		}
5600 
5601 		if (flags & DPARM_DISC) {
5602 			spi->valid |= CTS_SPI_VALID_DISC;
5603 			spi->flags |= CTS_SPI_FLAGS_DISC_ENB;
5604 		}
5605 		spi->flags |= CTS_SPI_VALID_BUS_WIDTH;
5606 		if (flags & DPARM_WIDE) {
5607 			spi->bus_width = MSG_EXT_WDTR_BUS_16_BIT;
5608 		} else {
5609 			spi->bus_width = MSG_EXT_WDTR_BUS_8_BIT;
5610 		}
5611 		if (flags & DPARM_SYNC) {
5612 			spi->valid |= CTS_SPI_VALID_SYNC_RATE;
5613 			spi->valid |= CTS_SPI_VALID_SYNC_OFFSET;
5614 			spi->sync_period = sdp->isp_devparam[tgt].actv_period;
5615 			spi->sync_offset = sdp->isp_devparam[tgt].actv_offset;
5616 		}
5617 		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);
5618 		xpt_setup_ccb(&cts.ccb_h, tmppath, 1);
5619 		xpt_async(AC_TRANSFER_NEG, tmppath, &cts);
5620 		xpt_free_path(tmppath);
5621 		break;
5622 	}
5623 	case ISPASYNC_BUS_RESET:
5624 	{
5625 		va_start(ap, cmd);
5626 		bus = va_arg(ap, int);
5627 		va_end(ap);
5628 		isp_prt(isp, ISP_LOGINFO, "SCSI bus reset on bus %d detected", bus);
5629 		if (IS_FC(isp)) {
5630 			xpt_async(AC_BUS_RESET, ISP_FC_PC(isp, bus)->path, NULL);
5631 		} else {
5632 			xpt_async(AC_BUS_RESET, ISP_SPI_PC(isp, bus)->path, NULL);
5633 		}
5634 		break;
5635 	}
5636 	case ISPASYNC_LIP:
5637 		if (msg == NULL) {
5638 			msg = "LIP Received";
5639 		}
5640 		/* FALLTHROUGH */
5641 	case ISPASYNC_LOOP_RESET:
5642 		if (msg == NULL) {
5643 			msg = "LOOP Reset";
5644 		}
5645 		/* FALLTHROUGH */
5646 	case ISPASYNC_LOOP_DOWN:
5647 	{
5648 		if (msg == NULL) {
5649 			msg = "LOOP Down";
5650 		}
5651 		va_start(ap, cmd);
5652 		bus = va_arg(ap, int);
5653 		va_end(ap);
5654 
5655 		FCPARAM(isp, bus)->link_active = 0;
5656 
5657 		fc = ISP_FC_PC(isp, bus);
5658 		if (cmd == ISPASYNC_LOOP_DOWN && fc->ready) {
5659 			/*
5660 			 * We don't do any simq freezing if we are only in target mode
5661 			 */
5662 			if (FCPARAM(isp, bus)->role & ISP_ROLE_INITIATOR) {
5663 				if (fc->path) {
5664 					isp_freeze_loopdown(isp, bus, msg);
5665 				}
5666 				if (!callout_active(&fc->ldt)) {
5667 					callout_reset(&fc->ldt, fc->loop_down_limit * hz, isp_ldt, fc);
5668 					isp_prt(isp, ISP_LOG_SANCFG|ISP_LOGDEBUG0, "Starting Loop Down Timer @ %lu", (unsigned long) time_uptime);
5669 				}
5670 			}
5671 		}
5672 		isp_prt(isp, ISP_LOGINFO, "Chan %d: %s", bus, msg);
5673 		break;
5674 	}
5675 	case ISPASYNC_LOOP_UP:
5676 		va_start(ap, cmd);
5677 		bus = va_arg(ap, int);
5678 		va_end(ap);
5679 		fc = ISP_FC_PC(isp, bus);
5680 		/*
5681 		 * Now we just note that Loop has come up. We don't
5682 		 * actually do anything because we're waiting for a
5683 		 * Change Notify before activating the FC cleanup
5684 		 * thread to look at the state of the loop again.
5685 		 */
5686 		FCPARAM(isp, bus)->link_active = 1;
5687 		fc->loop_dead = 0;
5688 		fc->loop_down_time = 0;
5689 		isp_prt(isp, ISP_LOGINFO, "Chan %d Loop UP", bus);
5690 		break;
5691 	case ISPASYNC_DEV_ARRIVED:
5692 		va_start(ap, cmd);
5693 		bus = va_arg(ap, int);
5694 		lp = va_arg(ap, fcportdb_t *);
5695 		va_end(ap);
5696 		fc = ISP_FC_PC(isp, bus);
5697 		lp->announced = 0;
5698 		lp->gone_timer = 0;
5699 		if ((FCPARAM(isp, bus)->role & ISP_ROLE_INITIATOR) && (lp->prli_word3 & PRLI_WD3_TARGET_FUNCTION)) {
5700 			int dbidx = lp - FCPARAM(isp, bus)->portdb;
5701 			int i;
5702 
5703 			for (i = 0; i < MAX_FC_TARG; i++) {
5704 				if (i >= FL_ID && i <= SNS_ID) {
5705 					continue;
5706 				}
5707 				if (FCPARAM(isp, bus)->isp_dev_map[i] == 0) {
5708 					break;
5709 				}
5710 			}
5711 			if (i < MAX_FC_TARG) {
5712 				FCPARAM(isp, bus)->isp_dev_map[i] = dbidx + 1;
5713 				lp->dev_map_idx = i + 1;
5714 			} else {
5715 				isp_prt(isp, ISP_LOGWARN, "out of target ids");
5716 				isp_dump_portdb(isp, bus);
5717 			}
5718 		}
5719 		isp_gen_role_str(buf, sizeof (buf), lp->prli_word3);
5720 		if (lp->dev_map_idx) {
5721 			tgt = lp->dev_map_idx - 1;
5722 			isp_prt(isp, ISP_LOGCONFIG, prom2, bus, lp->portid, lp->handle, buf, "arrived at", tgt, (uint32_t) (lp->port_wwn >> 32), (uint32_t) lp->port_wwn);
5723 			isp_make_here(isp, bus, tgt);
5724 		} else {
5725 			isp_prt(isp, ISP_LOGCONFIG, prom0, bus, lp->portid, lp->handle, buf, "arrived", (uint32_t) (lp->port_wwn >> 32), (uint32_t) lp->port_wwn);
5726 		}
5727 		break;
5728 	case ISPASYNC_DEV_CHANGED:
5729 		va_start(ap, cmd);
5730 		bus = va_arg(ap, int);
5731 		lp = va_arg(ap, fcportdb_t *);
5732 		va_end(ap);
5733 		fc = ISP_FC_PC(isp, bus);
5734 		lp->announced = 0;
5735 		lp->gone_timer = 0;
5736 		if (isp_change_is_bad) {
5737 			lp->state = FC_PORTDB_STATE_NIL;
5738 			if (lp->dev_map_idx) {
5739 				tgt = lp->dev_map_idx - 1;
5740 				FCPARAM(isp, bus)->isp_dev_map[tgt] = 0;
5741 				lp->dev_map_idx = 0;
5742 				isp_prt(isp, ISP_LOGCONFIG, prom3, bus, lp->portid, tgt, "change is bad");
5743 				isp_make_gone(isp, bus, tgt);
5744 			} else {
5745 				isp_gen_role_str(buf, sizeof (buf), lp->prli_word3);
5746 				isp_prt(isp, ISP_LOGCONFIG, prom0, bus, lp->portid, lp->handle, buf, "changed and departed",
5747 				    (uint32_t) (lp->port_wwn >> 32), (uint32_t) lp->port_wwn);
5748 			}
5749 		} else {
5750 			lp->portid = lp->new_portid;
5751 			lp->prli_word3 = lp->new_prli_word3;
5752 			isp_gen_role_str(buf, sizeof (buf), lp->prli_word3);
5753 			if (lp->dev_map_idx) {
5754 				int t = lp->dev_map_idx - 1;
5755 				FCPARAM(isp, bus)->isp_dev_map[t] = (lp - FCPARAM(isp, bus)->portdb) + 1;
5756 				tgt = lp->dev_map_idx - 1;
5757 				isp_prt(isp, ISP_LOGCONFIG, prom2, bus, lp->portid, lp->handle, buf, "changed at", tgt,
5758 				    (uint32_t) (lp->port_wwn >> 32), (uint32_t) lp->port_wwn);
5759 			} else {
5760 				isp_prt(isp, ISP_LOGCONFIG, prom0, bus, lp->portid, lp->handle, buf, "changed", (uint32_t) (lp->port_wwn >> 32), (uint32_t) lp->port_wwn);
5761 			}
5762 		}
5763 		break;
5764 	case ISPASYNC_DEV_STAYED:
5765 		va_start(ap, cmd);
5766 		bus = va_arg(ap, int);
5767 		lp = va_arg(ap, fcportdb_t *);
5768 		va_end(ap);
5769 		isp_gen_role_str(buf, sizeof (buf), lp->prli_word3);
5770 		if (lp->dev_map_idx) {
5771 			tgt = lp->dev_map_idx - 1;
5772 			isp_prt(isp, ISP_LOGCONFIG, prom2, bus, lp->portid, lp->handle, buf, "stayed at", tgt,
5773 		    	    (uint32_t) (lp->port_wwn >> 32), (uint32_t) lp->port_wwn);
5774 		} else {
5775 			isp_prt(isp, ISP_LOGCONFIG, prom0, bus, lp->portid, lp->handle, buf, "stayed",
5776 		    	    (uint32_t) (lp->port_wwn >> 32), (uint32_t) lp->port_wwn);
5777 		}
5778 		break;
5779 	case ISPASYNC_DEV_GONE:
5780 		va_start(ap, cmd);
5781 		bus = va_arg(ap, int);
5782 		lp = va_arg(ap, fcportdb_t *);
5783 		va_end(ap);
5784 		fc = ISP_FC_PC(isp, bus);
5785 		/*
5786 		 * If this has a virtual target and we haven't marked it
5787 		 * that we're going to have isp_gdt tell the OS it's gone,
5788 		 * set the isp_gdt timer running on it.
5789 		 *
5790 		 * If it isn't marked that isp_gdt is going to get rid of it,
5791 		 * announce that it's gone.
5792 		 *
5793 		 */
5794 		isp_gen_role_str(buf, sizeof (buf), lp->prli_word3);
5795 		if (lp->dev_map_idx && lp->announced == 0) {
5796 			lp->announced = 1;
5797 			lp->state = FC_PORTDB_STATE_ZOMBIE;
5798 			lp->gone_timer = ISP_FC_PC(isp, bus)->gone_device_time;
5799 			if (fc->ready && !callout_active(&fc->gdt)) {
5800 				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);
5801 				callout_reset(&fc->gdt, hz, isp_gdt, fc);
5802 			}
5803 			tgt = lp->dev_map_idx - 1;
5804 			isp_prt(isp, ISP_LOGCONFIG, prom2, bus, lp->portid, lp->handle, buf, "gone zombie at", tgt, (uint32_t) (lp->port_wwn >> 32), (uint32_t) lp->port_wwn);
5805 		} else if (lp->announced == 0) {
5806 			isp_prt(isp, ISP_LOGCONFIG, prom0, bus, lp->portid, lp->handle, buf, "departed", (uint32_t) (lp->port_wwn >> 32), (uint32_t) lp->port_wwn);
5807 		}
5808 		break;
5809 	case ISPASYNC_CHANGE_NOTIFY:
5810 	{
5811 		char *msg;
5812 		int evt, nphdl, nlstate, reason;
5813 
5814 		va_start(ap, cmd);
5815 		bus = va_arg(ap, int);
5816 		evt = va_arg(ap, int);
5817 		if (IS_24XX(isp) && evt == ISPASYNC_CHANGE_PDB) {
5818 			nphdl = va_arg(ap, int);
5819 			nlstate = va_arg(ap, int);
5820 			reason = va_arg(ap, int);
5821 		} else {
5822 			nphdl = NIL_HANDLE;
5823 			nlstate = reason = 0;
5824 		}
5825 		va_end(ap);
5826 		fc = ISP_FC_PC(isp, bus);
5827 
5828 		if (evt == ISPASYNC_CHANGE_PDB) {
5829 			msg = "Chan %d Port Database Changed";
5830 		} else if (evt == ISPASYNC_CHANGE_SNS) {
5831 			msg = "Chan %d Name Server Database Changed";
5832 		} else {
5833 			msg = "Chan %d Other Change Notify";
5834 		}
5835 
5836 		/*
5837 		 * If the loop down timer is running, cancel it.
5838 		 */
5839 		if (fc->ready && callout_active(&fc->ldt)) {
5840 			isp_prt(isp, ISP_LOG_SANCFG|ISP_LOGDEBUG0, "Stopping Loop Down Timer @ %lu", (unsigned long) time_uptime);
5841 			callout_stop(&fc->ldt);
5842 		}
5843 		isp_prt(isp, ISP_LOGINFO, msg, bus);
5844 		if (FCPARAM(isp, bus)->role & ISP_ROLE_INITIATOR) {
5845 			isp_freeze_loopdown(isp, bus, msg);
5846 		}
5847 		wakeup(fc);
5848 		break;
5849 	}
5850 #ifdef	ISP_TARGET_MODE
5851 	case ISPASYNC_TARGET_NOTIFY:
5852 	{
5853 		isp_notify_t *notify;
5854 		va_start(ap, cmd);
5855 		notify = va_arg(ap, isp_notify_t *);
5856 		va_end(ap);
5857 		switch (notify->nt_ncode) {
5858 		case NT_ABORT_TASK:
5859 		case NT_ABORT_TASK_SET:
5860 		case NT_CLEAR_ACA:
5861 		case NT_CLEAR_TASK_SET:
5862 		case NT_LUN_RESET:
5863 		case NT_TARGET_RESET:
5864 			/*
5865 			 * These are task management functions.
5866 			 */
5867 			isp_handle_platform_target_tmf(isp, notify);
5868 			break;
5869 		case NT_BUS_RESET:
5870 		case NT_LIP_RESET:
5871 		case NT_LINK_UP:
5872 		case NT_LINK_DOWN:
5873 			/*
5874 			 * No action need be taken here.
5875 			 */
5876 			break;
5877 		case NT_HBA_RESET:
5878 			isp_del_all_wwn_entries(isp, ISP_NOCHAN);
5879 			break;
5880 		case NT_GLOBAL_LOGOUT:
5881 		case NT_LOGOUT:
5882 			/*
5883 			 * This is device arrival/departure notification
5884 			 */
5885 			isp_handle_platform_target_notify_ack(isp, notify);
5886 			break;
5887 		case NT_ARRIVED:
5888 		{
5889 			struct ac_contract ac;
5890 			struct ac_device_changed *fc;
5891 
5892 			ac.contract_number = AC_CONTRACT_DEV_CHG;
5893 			fc = (struct ac_device_changed *) ac.contract_data;
5894 			fc->wwpn = notify->nt_wwn;
5895 			fc->port = notify->nt_sid;
5896 			fc->target = notify->nt_nphdl;
5897 			fc->arrived = 1;
5898 			xpt_async(AC_CONTRACT, ISP_FC_PC(isp, notify->nt_channel)->path, &ac);
5899 			break;
5900 		}
5901 		case NT_DEPARTED:
5902 		{
5903 			struct ac_contract ac;
5904 			struct ac_device_changed *fc;
5905 
5906 			ac.contract_number = AC_CONTRACT_DEV_CHG;
5907 			fc = (struct ac_device_changed *) ac.contract_data;
5908 			fc->wwpn = notify->nt_wwn;
5909 			fc->port = notify->nt_sid;
5910 			fc->target = notify->nt_nphdl;
5911 			fc->arrived = 0;
5912 			xpt_async(AC_CONTRACT, ISP_FC_PC(isp, notify->nt_channel)->path, &ac);
5913 			break;
5914 		}
5915 		default:
5916 			isp_prt(isp, ISP_LOGALL, "target notify code 0x%x", notify->nt_ncode);
5917 			isp_handle_platform_target_notify_ack(isp, notify);
5918 			break;
5919 		}
5920 		break;
5921 	}
5922 	case ISPASYNC_TARGET_NOTIFY_ACK:
5923 	{
5924 		void *inot;
5925 		va_start(ap, cmd);
5926 		inot = va_arg(ap, void *);
5927 		va_end(ap);
5928 		if (isp_notify_ack(isp, inot)) {
5929 			isp_tna_t *tp = malloc(sizeof (*tp), M_DEVBUF, M_NOWAIT);
5930 			if (tp) {
5931 				tp->isp = isp;
5932 				if (inot) {
5933 					memcpy(tp->data, inot, sizeof (tp->data));
5934 					tp->not = tp->data;
5935 				} else {
5936 					tp->not = NULL;
5937 				}
5938 				(void) timeout(isp_refire_notify_ack, tp, 5);
5939 			} else {
5940 				isp_prt(isp, ISP_LOGERR, "you lose- cannot allocate a notify refire");
5941 			}
5942 		}
5943 		break;
5944 	}
5945 	case ISPASYNC_TARGET_ACTION:
5946 	{
5947 		isphdr_t *hp;
5948 
5949 		va_start(ap, cmd);
5950 		hp = va_arg(ap, isphdr_t *);
5951 		va_end(ap);
5952 		switch (hp->rqs_entry_type) {
5953 		default:
5954 			isp_prt(isp, ISP_LOGWARN, "%s: unhandled target action 0x%x", __func__, hp->rqs_entry_type);
5955 			break;
5956 		case RQSTYPE_NOTIFY:
5957 			if (IS_SCSI(isp)) {
5958 				isp_handle_platform_notify_scsi(isp, (in_entry_t *) hp);
5959 			} else if (IS_24XX(isp)) {
5960 				isp_handle_platform_notify_24xx(isp, (in_fcentry_24xx_t *) hp);
5961 			} else {
5962 				isp_handle_platform_notify_fc(isp, (in_fcentry_t *) hp);
5963 			}
5964 			break;
5965 		case RQSTYPE_ATIO:
5966 			if (IS_24XX(isp)) {
5967 				isp_handle_platform_atio7(isp, (at7_entry_t *) hp);
5968 			} else {
5969 				isp_handle_platform_atio(isp, (at_entry_t *) hp);
5970 			}
5971 			break;
5972 		case RQSTYPE_ATIO2:
5973 			isp_handle_platform_atio2(isp, (at2_entry_t *) hp);
5974 			break;
5975 		case RQSTYPE_CTIO7:
5976 		case RQSTYPE_CTIO3:
5977 		case RQSTYPE_CTIO2:
5978 		case RQSTYPE_CTIO:
5979 			isp_handle_platform_ctio(isp, hp);
5980 			break;
5981 		case RQSTYPE_ABTS_RCVD:
5982 		{
5983 			abts_t *abts = (abts_t *)hp;
5984 			isp_notify_t notify, *nt = &notify;
5985 			tstate_t *tptr;
5986 			fcportdb_t *lp;
5987 			uint16_t chan;
5988 			uint32_t sid, did;
5989 
5990 			did = (abts->abts_did_hi << 16) | abts->abts_did_lo;
5991 			sid = (abts->abts_sid_hi << 16) | abts->abts_sid_lo;
5992 			ISP_MEMZERO(nt, sizeof (isp_notify_t));
5993 
5994 			nt->nt_hba = isp;
5995 			nt->nt_did = did;
5996 			nt->nt_nphdl = abts->abts_nphdl;
5997 			nt->nt_sid = sid;
5998 			isp_find_chan_by_did(isp, did, &chan);
5999 			if (chan == ISP_NOCHAN) {
6000 				nt->nt_tgt = TGT_ANY;
6001 			} else {
6002 				nt->nt_tgt = FCPARAM(isp, chan)->isp_wwpn;
6003 				if (isp_find_pdb_by_loopid(isp, chan, abts->abts_nphdl, &lp)) {
6004 					nt->nt_wwn = lp->port_wwn;
6005 				} else {
6006 					nt->nt_wwn = INI_ANY;
6007 				}
6008 			}
6009 			/*
6010 			 * Try hard to find the lun for this command.
6011 			 */
6012 			tptr = get_lun_statep_from_tag(isp, chan, abts->abts_rxid_task);
6013 			if (tptr) {
6014 				nt->nt_lun = xpt_path_lun_id(tptr->owner);
6015 				rls_lun_statep(isp, tptr);
6016 			} else {
6017 				nt->nt_lun = LUN_ANY;
6018 			}
6019 			nt->nt_need_ack = 1;
6020 			nt->nt_tagval = abts->abts_rxid_task;
6021 			nt->nt_tagval |= (((uint64_t) abts->abts_rxid_abts) << 32);
6022 			if (abts->abts_rxid_task == ISP24XX_NO_TASK) {
6023 				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)",
6024 				    abts->abts_rxid_abts, abts->abts_nphdl, sid, abts->abts_rx_id, abts->abts_ox_id);
6025 			} else {
6026 				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)",
6027 				    abts->abts_rxid_abts, abts->abts_nphdl, sid, abts->abts_rxid_task, abts->abts_rx_id, abts->abts_ox_id);
6028 			}
6029 			nt->nt_channel = chan;
6030 			nt->nt_ncode = NT_ABORT_TASK;
6031 			nt->nt_lreserved = hp;
6032 			isp_handle_platform_target_tmf(isp, nt);
6033 			break;
6034 		}
6035 		case RQSTYPE_ENABLE_LUN:
6036 		case RQSTYPE_MODIFY_LUN:
6037 			isp_ledone(isp, (lun_entry_t *) hp);
6038 			break;
6039 		}
6040 		break;
6041 	}
6042 #endif
6043 	case ISPASYNC_FW_CRASH:
6044 	{
6045 		uint16_t mbox1, mbox6;
6046 		mbox1 = ISP_READ(isp, OUTMAILBOX1);
6047 		if (IS_DUALBUS(isp)) {
6048 			mbox6 = ISP_READ(isp, OUTMAILBOX6);
6049 		} else {
6050 			mbox6 = 0;
6051 		}
6052 		isp_prt(isp, ISP_LOGERR, "Internal Firmware Error on bus %d @ RISC Address 0x%x", mbox6, mbox1);
6053 		mbox1 = isp->isp_osinfo.mbox_sleep_ok;
6054 		isp->isp_osinfo.mbox_sleep_ok = 0;
6055 		isp_reinit(isp, 1);
6056 		isp->isp_osinfo.mbox_sleep_ok = mbox1;
6057 		isp_async(isp, ISPASYNC_FW_RESTARTED, NULL);
6058 		break;
6059 	}
6060 	default:
6061 		isp_prt(isp, ISP_LOGERR, "unknown isp_async event %d", cmd);
6062 		break;
6063 	}
6064 }
6065 
6066 
6067 /*
6068  * Locks are held before coming here.
6069  */
6070 void
6071 isp_uninit(ispsoftc_t *isp)
6072 {
6073 	if (IS_24XX(isp)) {
6074 		ISP_WRITE(isp, BIU2400_HCCR, HCCR_2400_CMD_RESET);
6075 	} else {
6076 		ISP_WRITE(isp, HCCR, HCCR_CMD_RESET);
6077 	}
6078 	ISP_DISABLE_INTS(isp);
6079 }
6080 
6081 /*
6082  * When we want to get the 'default' WWNs (when lacking NVRAM), we pick them
6083  * up from our platform default (defww{p|n}n) and morph them based upon
6084  * channel.
6085  *
6086  * When we want to get the 'active' WWNs, we get NVRAM WWNs and then morph them
6087  * based upon channel.
6088  */
6089 
6090 uint64_t
6091 isp_default_wwn(ispsoftc_t * isp, int chan, int isactive, int iswwnn)
6092 {
6093 	uint64_t seed;
6094 	struct isp_fc *fc = ISP_FC_PC(isp, chan);
6095 
6096 	/*
6097 	 * If we're asking for a active WWN, the default overrides get
6098 	 * returned, otherwise the NVRAM value is picked.
6099 	 *
6100 	 * If we're asking for a default WWN, we just pick the default override.
6101 	 */
6102 	if (isactive) {
6103 		seed = iswwnn ? fc->def_wwnn : fc->def_wwpn;
6104 		if (seed) {
6105 			return (seed);
6106 		}
6107 		seed = iswwnn ? FCPARAM(isp, chan)->isp_wwnn_nvram : FCPARAM(isp, chan)->isp_wwpn_nvram;
6108 		if (seed) {
6109 			return (seed);
6110 		}
6111 		return (0x400000007F000009ull);
6112 	} else {
6113 		seed = iswwnn ? fc->def_wwnn : fc->def_wwpn;
6114 	}
6115 
6116 
6117 	/*
6118 	 * For channel zero just return what we have. For either ACTIVE or
6119 	 * DEFAULT cases, we depend on default override of NVRAM values for
6120 	 * channel zero.
6121 	 */
6122 	if (chan == 0) {
6123 		return (seed);
6124 	}
6125 
6126 	/*
6127 	 * For other channels, we are doing one of three things:
6128 	 *
6129 	 * 1. If what we have now is non-zero, return it. Otherwise we morph
6130 	 * values from channel 0. 2. If we're here for a WWPN we synthesize
6131 	 * it if Channel 0's wwpn has a type 2 NAA. 3. If we're here for a
6132 	 * WWNN we synthesize it if Channel 0's wwnn has a type 2 NAA.
6133 	 */
6134 
6135 	if (seed) {
6136 		return (seed);
6137 	}
6138 	if (isactive) {
6139 		seed = iswwnn ? FCPARAM(isp, 0)->isp_wwnn_nvram : FCPARAM(isp, 0)->isp_wwpn_nvram;
6140 	} else {
6141 		seed = iswwnn ? ISP_FC_PC(isp, 0)->def_wwnn : ISP_FC_PC(isp, 0)->def_wwpn;
6142 	}
6143 
6144 	if (((seed >> 60) & 0xf) == 2) {
6145 		/*
6146 		 * The type 2 NAA fields for QLogic cards appear be laid out
6147 		 * thusly:
6148 		 *
6149 		 * bits 63..60 NAA == 2 bits 59..57 unused/zero bit 56
6150 		 * port (1) or node (0) WWN distinguishor bit 48
6151 		 * physical port on dual-port chips (23XX/24XX)
6152 		 *
6153 		 * This is somewhat nutty, particularly since bit 48 is
6154 		 * irrelevant as they assign separate serial numbers to
6155 		 * different physical ports anyway.
6156 		 *
6157 		 * We'll stick our channel number plus one first into bits
6158 		 * 57..59 and thence into bits 52..55 which allows for 8 bits
6159 		 * of channel which is comfortably more than our maximum
6160 		 * (126) now.
6161 		 */
6162 		seed &= ~0x0FF0000000000000ULL;
6163 		if (iswwnn == 0) {
6164 			seed |= ((uint64_t) (chan + 1) & 0xf) << 56;
6165 			seed |= ((uint64_t) ((chan + 1) >> 4) & 0xf) << 52;
6166 		}
6167 	} else {
6168 		seed = 0;
6169 	}
6170 	return (seed);
6171 }
6172 
6173 void
6174 isp_prt(ispsoftc_t *isp, int level, const char *fmt, ...)
6175 {
6176 	int loc;
6177 	char lbuf[200];
6178 	va_list ap;
6179 
6180 	if (level != ISP_LOGALL && (level & isp->isp_dblev) == 0) {
6181 		return;
6182 	}
6183 	snprintf(lbuf, sizeof (lbuf), "%s: ", device_get_nameunit(isp->isp_dev));
6184 	loc = strlen(lbuf);
6185 	va_start(ap, fmt);
6186 	vsnprintf(&lbuf[loc], sizeof (lbuf) - loc - 1, fmt, ap);
6187 	va_end(ap);
6188 	printf("%s\n", lbuf);
6189 }
6190 
6191 void
6192 isp_xs_prt(ispsoftc_t *isp, XS_T *xs, int level, const char *fmt, ...)
6193 {
6194 	va_list ap;
6195 	if (level != ISP_LOGALL && (level & isp->isp_dblev) == 0) {
6196 		return;
6197 	}
6198 	xpt_print_path(xs->ccb_h.path);
6199 	va_start(ap, fmt);
6200 	vprintf(fmt, ap);
6201 	va_end(ap);
6202 	printf("\n");
6203 }
6204 
6205 uint64_t
6206 isp_nanotime_sub(struct timespec *b, struct timespec *a)
6207 {
6208 	uint64_t elapsed;
6209 	struct timespec x = *b;
6210 	timespecsub(&x, a);
6211 	elapsed = GET_NANOSEC(&x);
6212 	if (elapsed == 0)
6213 		elapsed++;
6214 	return (elapsed);
6215 }
6216 
6217 int
6218 isp_mbox_acquire(ispsoftc_t *isp)
6219 {
6220 	if (isp->isp_osinfo.mboxbsy) {
6221 		return (1);
6222 	} else {
6223 		isp->isp_osinfo.mboxcmd_done = 0;
6224 		isp->isp_osinfo.mboxbsy = 1;
6225 		return (0);
6226 	}
6227 }
6228 
6229 void
6230 isp_mbox_wait_complete(ispsoftc_t *isp, mbreg_t *mbp)
6231 {
6232 	unsigned int usecs = mbp->timeout;
6233 	unsigned int max, olim, ilim;
6234 
6235 	if (usecs == 0) {
6236 		usecs = MBCMD_DEFAULT_TIMEOUT;
6237 	}
6238 	max = isp->isp_mbxwrk0 + 1;
6239 
6240 	if (isp->isp_osinfo.mbox_sleep_ok) {
6241 		unsigned int ms = (usecs + 999) / 1000;
6242 
6243 		isp->isp_osinfo.mbox_sleep_ok = 0;
6244 		isp->isp_osinfo.mbox_sleeping = 1;
6245 		for (olim = 0; olim < max; olim++) {
6246 			msleep(&isp->isp_mbxworkp, &isp->isp_osinfo.lock, PRIBIO, "ispmbx_sleep", isp_mstohz(ms));
6247 			if (isp->isp_osinfo.mboxcmd_done) {
6248 				break;
6249 			}
6250 		}
6251 		isp->isp_osinfo.mbox_sleep_ok = 1;
6252 		isp->isp_osinfo.mbox_sleeping = 0;
6253 	} else {
6254 		for (olim = 0; olim < max; olim++) {
6255 			for (ilim = 0; ilim < usecs; ilim += 100) {
6256 				uint32_t isr;
6257 				uint16_t sema, mbox;
6258 				if (isp->isp_osinfo.mboxcmd_done) {
6259 					break;
6260 				}
6261 				if (ISP_READ_ISR(isp, &isr, &sema, &mbox)) {
6262 					isp_intr(isp, isr, sema, mbox);
6263 					if (isp->isp_osinfo.mboxcmd_done) {
6264 						break;
6265 					}
6266 				}
6267 				ISP_DELAY(100);
6268 			}
6269 			if (isp->isp_osinfo.mboxcmd_done) {
6270 				break;
6271 			}
6272 		}
6273 	}
6274 	if (isp->isp_osinfo.mboxcmd_done == 0) {
6275 		isp_prt(isp, ISP_LOGWARN, "%s Mailbox Command (0x%x) Timeout (%uus) (started @ %s:%d)",
6276 		    isp->isp_osinfo.mbox_sleep_ok? "Interrupting" : "Polled", isp->isp_lastmbxcmd, usecs, mbp->func, mbp->lineno);
6277 		mbp->param[0] = MBOX_TIMEOUT;
6278 		isp->isp_osinfo.mboxcmd_done = 1;
6279 	}
6280 }
6281 
6282 void
6283 isp_mbox_notify_done(ispsoftc_t *isp)
6284 {
6285 	if (isp->isp_osinfo.mbox_sleeping) {
6286 		wakeup(&isp->isp_mbxworkp);
6287 	}
6288 	isp->isp_osinfo.mboxcmd_done = 1;
6289 }
6290 
6291 void
6292 isp_mbox_release(ispsoftc_t *isp)
6293 {
6294 	isp->isp_osinfo.mboxbsy = 0;
6295 }
6296 
6297 int
6298 isp_fc_scratch_acquire(ispsoftc_t *isp, int chan)
6299 {
6300 	int ret = 0;
6301 	if (isp->isp_osinfo.pc.fc[chan].fcbsy) {
6302 		ret = -1;
6303 	} else {
6304 		isp->isp_osinfo.pc.fc[chan].fcbsy = 1;
6305 	}
6306 	return (ret);
6307 }
6308 
6309 int
6310 isp_mstohz(int ms)
6311 {
6312 	int hz;
6313 	struct timeval t;
6314 	t.tv_sec = ms / 1000;
6315 	t.tv_usec = (ms % 1000) * 1000;
6316 	hz = tvtohz(&t);
6317 	if (hz < 0) {
6318 		hz = 0x7fffffff;
6319 	}
6320 	if (hz == 0) {
6321 		hz = 1;
6322 	}
6323 	return (hz);
6324 }
6325 
6326 void
6327 isp_platform_intr(void *arg)
6328 {
6329 	ispsoftc_t *isp = arg;
6330 	uint32_t isr;
6331 	uint16_t sema, mbox;
6332 
6333 	ISP_LOCK(isp);
6334 	isp->isp_intcnt++;
6335 	if (ISP_READ_ISR(isp, &isr, &sema, &mbox) == 0) {
6336 		isp->isp_intbogus++;
6337 	} else {
6338 		isp_intr(isp, isr, sema, mbox);
6339 	}
6340 	ISP_UNLOCK(isp);
6341 }
6342 
6343 void
6344 isp_common_dmateardown(ispsoftc_t *isp, struct ccb_scsiio *csio, uint32_t hdl)
6345 {
6346 	if ((csio->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
6347 		bus_dmamap_sync(isp->isp_osinfo.dmat, PISP_PCMD(csio)->dmap, BUS_DMASYNC_POSTREAD);
6348 	} else {
6349 		bus_dmamap_sync(isp->isp_osinfo.dmat, PISP_PCMD(csio)->dmap, BUS_DMASYNC_POSTWRITE);
6350 	}
6351 	bus_dmamap_unload(isp->isp_osinfo.dmat, PISP_PCMD(csio)->dmap);
6352 }
6353 
6354 int
6355 isp_fcp_next_crn(ispsoftc_t *isp, uint8_t *crnp, XS_T *cmd)
6356 {
6357 	uint32_t chan, tgt, lun;
6358 	struct isp_fc *fc;
6359 	struct isp_nexus *nxp;
6360 	int idx;
6361 
6362 	if (isp->isp_type < ISP_HA_FC_2300)
6363 		return (0);
6364 
6365 	chan = XS_CHANNEL(cmd);
6366 	tgt = XS_TGT(cmd);
6367 	lun = XS_LUN(cmd);
6368 	fc = &isp->isp_osinfo.pc.fc[chan];
6369 	idx = NEXUS_HASH(tgt, lun);
6370 	nxp = fc->nexus_hash[idx];
6371 
6372 	while (nxp) {
6373 		if (nxp->tgt == tgt && nxp->lun == lun)
6374 			break;
6375 		nxp = nxp->next;
6376 	}
6377 	if (nxp == NULL) {
6378 		nxp = fc->nexus_free_list;
6379 		if (nxp == NULL) {
6380 			nxp = malloc(sizeof (struct isp_nexus), M_DEVBUF, M_ZERO|M_NOWAIT);
6381 			if (nxp == NULL) {
6382 				return (-1);
6383 			}
6384 		} else {
6385 			fc->nexus_free_list = nxp->next;
6386 		}
6387 		nxp->tgt = tgt;
6388 		nxp->lun = lun;
6389 		nxp->next = fc->nexus_hash[idx];
6390 		fc->nexus_hash[idx] = nxp;
6391 	}
6392 	if (nxp) {
6393 		if (nxp->crnseed == 0)
6394 			nxp->crnseed = 1;
6395 		if (cmd)
6396 			PISP_PCMD(cmd)->crn = nxp->crnseed;
6397 		*crnp = nxp->crnseed++;
6398 		return (0);
6399 	}
6400 	return (-1);
6401 }
6402 
6403 /*
6404  * We enter with the lock held
6405  */
6406 void
6407 isp_timer(void *arg)
6408 {
6409 	ispsoftc_t *isp = arg;
6410 #ifdef	ISP_TARGET_MODE
6411 	isp_tmcmd_restart(isp);
6412 #endif
6413 	callout_reset(&isp->isp_osinfo.tmo, isp_timer_count, isp_timer, isp);
6414 }
6415 
6416 isp_ecmd_t *
6417 isp_get_ecmd(ispsoftc_t *isp)
6418 {
6419 	isp_ecmd_t *ecmd = isp->isp_osinfo.ecmd_free;
6420 	if (ecmd) {
6421 		isp->isp_osinfo.ecmd_free = ecmd->next;
6422 	}
6423 	return (ecmd);
6424 }
6425 
6426 void
6427 isp_put_ecmd(ispsoftc_t *isp, isp_ecmd_t *ecmd)
6428 {
6429 	ecmd->next = isp->isp_osinfo.ecmd_free;
6430 	isp->isp_osinfo.ecmd_free = ecmd;
6431 }
6432