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