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