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