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