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