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