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