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