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