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