1/*-
2 * Copyright (c) 2008, 2009 Silicon Graphics International Corp.
3 * Copyright (c) 2014-2015 Alexander Motin <mav@FreeBSD.org>
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 * 1. Redistributions of source code must retain the above copyright
10 *    notice, this list of conditions, and the following disclaimer,
11 *    without modification.
12 * 2. Redistributions in binary form must reproduce at minimum a disclaimer
13 *    substantially similar to the "NO WARRANTY" disclaimer below
14 *    ("Disclaimer") and any redistribution must be conditioned upon
15 *    including a substantially similar Disclaimer requirement for further
16 *    binary redistribution.
17 *
18 * NO WARRANTY
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
27 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
28 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGES.
30 *
31 * $Id: //depot/users/kenm/FreeBSD-test2/sys/cam/ctl/scsi_ctl.c#4 $
32 */
33/*
34 * Peripheral driver interface between CAM and CTL (CAM Target Layer).
35 *
36 * Author: Ken Merry <ken@FreeBSD.org>
37 */
38
39#include <sys/cdefs.h>
40__FBSDID("$FreeBSD: stable/11/sys/cam/ctl/scsi_ctl.c 322423 2017-08-12 10:22:18Z mav $");
41
42#include <sys/param.h>
43#include <sys/queue.h>
44#include <sys/systm.h>
45#include <sys/kernel.h>
46#include <sys/lock.h>
47#include <sys/mutex.h>
48#include <sys/condvar.h>
49#include <sys/malloc.h>
50#include <sys/bus.h>
51#include <sys/endian.h>
52#include <sys/sbuf.h>
53#include <sys/sysctl.h>
54#include <sys/types.h>
55#include <sys/systm.h>
56#include <sys/taskqueue.h>
57#include <machine/bus.h>
58
59#include <cam/cam.h>
60#include <cam/cam_ccb.h>
61#include <cam/cam_periph.h>
62#include <cam/cam_queue.h>
63#include <cam/cam_xpt_periph.h>
64#include <cam/cam_debug.h>
65#include <cam/cam_sim.h>
66#include <cam/cam_xpt.h>
67
68#include <cam/scsi/scsi_all.h>
69#include <cam/scsi/scsi_message.h>
70
71#include <cam/ctl/ctl_io.h>
72#include <cam/ctl/ctl.h>
73#include <cam/ctl/ctl_frontend.h>
74#include <cam/ctl/ctl_util.h>
75#include <cam/ctl/ctl_error.h>
76
77struct ctlfe_softc {
78	struct ctl_port	port;
79	path_id_t	path_id;
80	target_id_t	target_id;
81	uint32_t	hba_misc;
82	u_int		maxio;
83	struct cam_sim *sim;
84	char		port_name[DEV_IDLEN];
85	struct mtx	lun_softc_mtx;
86	STAILQ_HEAD(, ctlfe_lun_softc) lun_softc_list;
87	STAILQ_ENTRY(ctlfe_softc) links;
88};
89
90STAILQ_HEAD(, ctlfe_softc) ctlfe_softc_list;
91struct mtx ctlfe_list_mtx;
92static char ctlfe_mtx_desc[] = "ctlfelist";
93
94typedef enum {
95	CTLFE_LUN_NONE		= 0x00,
96	CTLFE_LUN_WILDCARD	= 0x01
97} ctlfe_lun_flags;
98
99struct ctlfe_lun_softc {
100	struct ctlfe_softc *parent_softc;
101	struct cam_periph *periph;
102	ctlfe_lun_flags flags;
103	int	 ctios_sent;		/* Number of active CTIOs */
104	int	 refcount;		/* Number of active xpt_action() */
105	int	 atios_alloced;		/* Number of ATIOs not freed */
106	int	 inots_alloced;		/* Number of INOTs not freed */
107	struct task	refdrain_task;
108	STAILQ_HEAD(, ccb_hdr) work_queue;
109	LIST_HEAD(, ccb_hdr) atio_list;	/* List of ATIOs queued to SIM. */
110	LIST_HEAD(, ccb_hdr) inot_list;	/* List of INOTs queued to SIM. */
111	STAILQ_ENTRY(ctlfe_lun_softc) links;
112};
113
114typedef enum {
115	CTLFE_CMD_NONE		= 0x00,
116	CTLFE_CMD_PIECEWISE	= 0x01
117} ctlfe_cmd_flags;
118
119struct ctlfe_cmd_info {
120	int cur_transfer_index;
121	size_t cur_transfer_off;
122	ctlfe_cmd_flags flags;
123	/*
124	 * XXX KDM struct bus_dma_segment is 8 bytes on i386, and 16
125	 * bytes on amd64.  So with 32 elements, this is 256 bytes on
126	 * i386 and 512 bytes on amd64.
127	 */
128#define CTLFE_MAX_SEGS	32
129	bus_dma_segment_t cam_sglist[CTLFE_MAX_SEGS];
130};
131
132/*
133 * When we register the adapter/bus, request that this many ctl_ios be
134 * allocated.  This should be the maximum supported by the adapter, but we
135 * currently don't have a way to get that back from the path inquiry.
136 * XXX KDM add that to the path inquiry.
137 */
138#define	CTLFE_REQ_CTL_IO	4096
139/*
140 * Number of Accept Target I/O CCBs to allocate and queue down to the
141 * adapter per LUN.
142 * XXX KDM should this be controlled by CTL?
143 */
144#define	CTLFE_ATIO_PER_LUN	1024
145/*
146 * Number of Immediate Notify CCBs (used for aborts, resets, etc.) to
147 * allocate and queue down to the adapter per LUN.
148 * XXX KDM should this be controlled by CTL?
149 */
150#define	CTLFE_IN_PER_LUN	1024
151
152/*
153 * Timeout (in seconds) on CTIO CCB doing DMA or sending status
154 */
155#define	CTLFE_TIMEOUT	5
156
157/*
158 * Turn this on to enable extra debugging prints.
159 */
160#if 0
161#define	CTLFE_DEBUG
162#endif
163
164MALLOC_DEFINE(M_CTLFE, "CAM CTL FE", "CAM CTL FE interface");
165
166#define	io_ptr		ppriv_ptr0
167
168/* This is only used in the CTIO */
169#define	ccb_atio	ppriv_ptr1
170
171#define PRIV_CCB(io)	((io)->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptrs[0])
172#define PRIV_INFO(io)	((io)->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptrs[1])
173
174static int		ctlfeinitialize(void);
175static int		ctlfeshutdown(void);
176static periph_init_t	ctlfeperiphinit;
177static periph_deinit_t	ctlfeperiphdeinit;
178static void		ctlfeasync(void *callback_arg, uint32_t code,
179				   struct cam_path *path, void *arg);
180static periph_ctor_t	ctlferegister;
181static periph_oninv_t	ctlfeoninvalidate;
182static periph_dtor_t	ctlfecleanup;
183static periph_start_t	ctlfestart;
184static void		ctlfedone(struct cam_periph *periph,
185				  union ccb *done_ccb);
186
187static void 		ctlfe_onoffline(void *arg, int online);
188static void 		ctlfe_online(void *arg);
189static void 		ctlfe_offline(void *arg);
190static int 		ctlfe_lun_enable(void *arg, int lun_id);
191static int 		ctlfe_lun_disable(void *arg, int lun_id);
192static void		ctlfe_dump_sim(struct cam_sim *sim);
193static void		ctlfe_dump_queue(struct ctlfe_lun_softc *softc);
194static void 		ctlfe_datamove(union ctl_io *io);
195static void 		ctlfe_done(union ctl_io *io);
196static void 		ctlfe_dump(void);
197static void		ctlfe_free_ccb(struct cam_periph *periph,
198			    union ccb *ccb);
199static void		ctlfe_requeue_ccb(struct cam_periph *periph,
200			    union ccb *ccb, int unlock);
201
202static struct periph_driver ctlfe_driver =
203{
204	ctlfeperiphinit, "ctl",
205	TAILQ_HEAD_INITIALIZER(ctlfe_driver.units), /*generation*/ 0,
206	CAM_PERIPH_DRV_EARLY,
207	ctlfeperiphdeinit
208};
209
210static struct ctl_frontend ctlfe_frontend =
211{
212	.name = "camtgt",
213	.init = ctlfeinitialize,
214	.fe_dump = ctlfe_dump,
215	.shutdown = ctlfeshutdown,
216};
217CTL_FRONTEND_DECLARE(ctlfe, ctlfe_frontend);
218
219static int
220ctlfeinitialize(void)
221{
222
223	STAILQ_INIT(&ctlfe_softc_list);
224	mtx_init(&ctlfe_list_mtx, ctlfe_mtx_desc, NULL, MTX_DEF);
225	periphdriver_register(&ctlfe_driver);
226	return (0);
227}
228
229static int
230ctlfeshutdown(void)
231{
232	int error;
233
234	error = periphdriver_unregister(&ctlfe_driver);
235	if (error != 0)
236		return (error);
237	mtx_destroy(&ctlfe_list_mtx);
238	return (0);
239}
240
241static void
242ctlfeperiphinit(void)
243{
244	cam_status status;
245
246	status = xpt_register_async(AC_PATH_REGISTERED | AC_PATH_DEREGISTERED |
247				    AC_CONTRACT, ctlfeasync, NULL, NULL);
248	if (status != CAM_REQ_CMP) {
249		printf("ctl: Failed to attach async callback due to CAM "
250		       "status 0x%x!\n", status);
251	}
252}
253
254static int
255ctlfeperiphdeinit(void)
256{
257
258	/* XXX: It would be good to tear down active ports here. */
259	if (!TAILQ_EMPTY(&ctlfe_driver.units))
260		return (EBUSY);
261	xpt_register_async(0, ctlfeasync, NULL, NULL);
262	return (0);
263}
264
265static void
266ctlfeasync(void *callback_arg, uint32_t code, struct cam_path *path, void *arg)
267{
268	struct ctlfe_softc *softc;
269
270#ifdef CTLFEDEBUG
271	printf("%s: entered\n", __func__);
272#endif
273
274	mtx_lock(&ctlfe_list_mtx);
275	STAILQ_FOREACH(softc, &ctlfe_softc_list, links) {
276		if (softc->path_id == xpt_path_path_id(path))
277			break;
278	}
279	mtx_unlock(&ctlfe_list_mtx);
280
281	/*
282	 * When a new path gets registered, and it is capable of target
283	 * mode, go ahead and attach.  Later on, we may need to be more
284	 * selective, but for now this will be sufficient.
285 	 */
286	switch (code) {
287	case AC_PATH_REGISTERED: {
288		struct ctl_port *port;
289		struct ccb_pathinq *cpi;
290		int retval;
291
292		cpi = (struct ccb_pathinq *)arg;
293
294		/* Don't attach if it doesn't support target mode */
295		if ((cpi->target_sprt & PIT_PROCESSOR) == 0) {
296#ifdef CTLFEDEBUG
297			printf("%s: SIM %s%d doesn't support target mode\n",
298			       __func__, cpi->dev_name, cpi->unit_number);
299#endif
300			break;
301		}
302
303		if (softc != NULL) {
304#ifdef CTLFEDEBUG
305			printf("%s: CTL port for CAM path %u already exists\n",
306			       __func__, xpt_path_path_id(path));
307#endif
308			break;
309		}
310
311		/*
312		 * We're in an interrupt context here, so we have to
313		 * use M_NOWAIT.  Of course this means trouble if we
314		 * can't allocate memory.
315		 */
316		softc = malloc(sizeof(*softc), M_CTLFE, M_NOWAIT | M_ZERO);
317		if (softc == NULL) {
318			printf("%s: unable to malloc %zd bytes for softc\n",
319			       __func__, sizeof(*softc));
320			return;
321		}
322
323		softc->path_id = cpi->ccb_h.path_id;
324		softc->target_id = cpi->initiator_id;
325		softc->sim = xpt_path_sim(path);
326		softc->hba_misc = cpi->hba_misc;
327		if (cpi->maxio != 0)
328			softc->maxio = cpi->maxio;
329		else
330			softc->maxio = DFLTPHYS;
331		mtx_init(&softc->lun_softc_mtx, "LUN softc mtx", NULL, MTX_DEF);
332		STAILQ_INIT(&softc->lun_softc_list);
333
334		port = &softc->port;
335		port->frontend = &ctlfe_frontend;
336
337		/*
338		 * XXX KDM should we be more accurate here ?
339		 */
340		if (cpi->transport == XPORT_FC)
341			port->port_type = CTL_PORT_FC;
342		else if (cpi->transport == XPORT_SAS)
343			port->port_type = CTL_PORT_SAS;
344		else
345			port->port_type = CTL_PORT_SCSI;
346
347		/* XXX KDM what should the real number be here? */
348		port->num_requested_ctl_io = CTLFE_REQ_CTL_IO;
349		snprintf(softc->port_name, sizeof(softc->port_name),
350			 "%s%d", cpi->dev_name, cpi->unit_number);
351		/*
352		 * XXX KDM it would be nice to allocate storage in the
353		 * frontend structure itself.
354	 	 */
355		port->port_name = softc->port_name;
356		port->physical_port = cpi->bus_id;
357		port->virtual_port = 0;
358		port->port_online = ctlfe_online;
359		port->port_offline = ctlfe_offline;
360		port->onoff_arg = softc;
361		port->lun_enable = ctlfe_lun_enable;
362		port->lun_disable = ctlfe_lun_disable;
363		port->targ_lun_arg = softc;
364		port->fe_datamove = ctlfe_datamove;
365		port->fe_done = ctlfe_done;
366		/*
367		 * XXX KDM the path inquiry doesn't give us the maximum
368		 * number of targets supported.
369		 */
370		port->max_targets = cpi->max_target;
371		port->max_target_id = cpi->max_target;
372		port->targ_port = -1;
373
374		retval = ctl_port_register(port);
375		if (retval != 0) {
376			printf("%s: ctl_port_register() failed with "
377			       "error %d!\n", __func__, retval);
378			mtx_destroy(&softc->lun_softc_mtx);
379			free(softc, M_CTLFE);
380			break;
381		} else {
382			mtx_lock(&ctlfe_list_mtx);
383			STAILQ_INSERT_TAIL(&ctlfe_softc_list, softc, links);
384			mtx_unlock(&ctlfe_list_mtx);
385		}
386
387		break;
388	}
389	case AC_PATH_DEREGISTERED: {
390
391		if (softc != NULL) {
392			/*
393			 * XXX KDM are we certain at this point that there
394			 * are no outstanding commands for this frontend?
395			 */
396			mtx_lock(&ctlfe_list_mtx);
397			STAILQ_REMOVE(&ctlfe_softc_list, softc, ctlfe_softc,
398			    links);
399			mtx_unlock(&ctlfe_list_mtx);
400			ctl_port_deregister(&softc->port);
401			mtx_destroy(&softc->lun_softc_mtx);
402			free(softc, M_CTLFE);
403		}
404		break;
405	}
406	case AC_CONTRACT: {
407		struct ac_contract *ac;
408
409		ac = (struct ac_contract *)arg;
410
411		switch (ac->contract_number) {
412		case AC_CONTRACT_DEV_CHG: {
413			struct ac_device_changed *dev_chg;
414			int retval;
415
416			dev_chg = (struct ac_device_changed *)ac->contract_data;
417
418			printf("%s: WWPN %#jx port 0x%06x path %u target %u %s\n",
419			       __func__, dev_chg->wwpn, dev_chg->port,
420			       xpt_path_path_id(path), dev_chg->target,
421			       (dev_chg->arrived == 0) ?  "left" : "arrived");
422
423			if (softc == NULL) {
424				printf("%s: CTL port for CAM path %u not "
425				       "found!\n", __func__,
426				       xpt_path_path_id(path));
427				break;
428			}
429			if (dev_chg->arrived != 0) {
430				retval = ctl_add_initiator(&softc->port,
431				    dev_chg->target, dev_chg->wwpn, NULL);
432			} else {
433				retval = ctl_remove_initiator(&softc->port,
434				    dev_chg->target);
435			}
436
437			if (retval < 0) {
438				printf("%s: could not %s port %d iid %u "
439				       "WWPN %#jx!\n", __func__,
440				       (dev_chg->arrived != 0) ? "add" :
441				       "remove", softc->port.targ_port,
442				       dev_chg->target,
443				       (uintmax_t)dev_chg->wwpn);
444			}
445			break;
446		}
447		default:
448			printf("%s: unsupported contract number %ju\n",
449			       __func__, (uintmax_t)ac->contract_number);
450			break;
451		}
452		break;
453	}
454	default:
455		break;
456	}
457}
458
459static cam_status
460ctlferegister(struct cam_periph *periph, void *arg)
461{
462	struct ctlfe_softc *bus_softc;
463	struct ctlfe_lun_softc *softc;
464	union ccb ccb;
465	cam_status status;
466	int i;
467
468	softc = (struct ctlfe_lun_softc *)arg;
469	bus_softc = softc->parent_softc;
470
471	STAILQ_INIT(&softc->work_queue);
472	LIST_INIT(&softc->atio_list);
473	LIST_INIT(&softc->inot_list);
474	softc->periph = periph;
475	periph->softc = softc;
476
477	/* Increase device openings to maximum for the SIM. */
478	if (bus_softc->sim->max_tagged_dev_openings >
479	    bus_softc->sim->max_dev_openings) {
480		cam_release_devq(periph->path,
481		    /*relsim_flags*/RELSIM_ADJUST_OPENINGS,
482		    /*openings*/bus_softc->sim->max_tagged_dev_openings,
483		    /*timeout*/0,
484		    /*getcount_only*/1);
485	}
486
487	xpt_setup_ccb(&ccb.ccb_h, periph->path, CAM_PRIORITY_NONE);
488	ccb.ccb_h.func_code = XPT_EN_LUN;
489	ccb.cel.grp6_len = 0;
490	ccb.cel.grp7_len = 0;
491	ccb.cel.enable = 1;
492	xpt_action(&ccb);
493	status = (ccb.ccb_h.status & CAM_STATUS_MASK);
494	if (status != CAM_REQ_CMP) {
495		xpt_print(periph->path, "%s: Enable LUN failed, status 0x%x\n",
496			  __func__, ccb.ccb_h.status);
497		return (status);
498	}
499
500	status = CAM_REQ_CMP;
501
502	for (i = 0; i < CTLFE_ATIO_PER_LUN; i++) {
503		union ccb *new_ccb;
504		union ctl_io *new_io;
505		struct ctlfe_cmd_info *cmd_info;
506
507		new_ccb = (union ccb *)malloc(sizeof(*new_ccb), M_CTLFE,
508					      M_ZERO|M_NOWAIT);
509		if (new_ccb == NULL) {
510			status = CAM_RESRC_UNAVAIL;
511			break;
512		}
513		new_io = ctl_alloc_io_nowait(bus_softc->port.ctl_pool_ref);
514		if (new_io == NULL) {
515			free(new_ccb, M_CTLFE);
516			status = CAM_RESRC_UNAVAIL;
517			break;
518		}
519		cmd_info = malloc(sizeof(*cmd_info), M_CTLFE,
520		    M_ZERO | M_NOWAIT);
521		if (cmd_info == NULL) {
522			ctl_free_io(new_io);
523			free(new_ccb, M_CTLFE);
524			status = CAM_RESRC_UNAVAIL;
525			break;
526		}
527		PRIV_INFO(new_io) = cmd_info;
528		softc->atios_alloced++;
529		new_ccb->ccb_h.io_ptr = new_io;
530		LIST_INSERT_HEAD(&softc->atio_list, &new_ccb->ccb_h, periph_links.le);
531
532		xpt_setup_ccb(&new_ccb->ccb_h, periph->path, CAM_PRIORITY_NONE);
533		new_ccb->ccb_h.func_code = XPT_ACCEPT_TARGET_IO;
534		new_ccb->ccb_h.cbfcnp = ctlfedone;
535		new_ccb->ccb_h.flags |= CAM_UNLOCKED;
536		xpt_action(new_ccb);
537		status = new_ccb->ccb_h.status;
538		if ((status & CAM_STATUS_MASK) != CAM_REQ_INPROG) {
539			free(cmd_info, M_CTLFE);
540			ctl_free_io(new_io);
541			free(new_ccb, M_CTLFE);
542			break;
543		}
544	}
545
546	status = cam_periph_acquire(periph);
547	if ((status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
548		xpt_print(periph->path, "%s: could not acquire reference "
549			  "count, status = %#x\n", __func__, status);
550		return (status);
551	}
552
553	if (i == 0) {
554		xpt_print(periph->path, "%s: could not allocate ATIO CCBs, "
555			  "status 0x%x\n", __func__, status);
556		return (CAM_REQ_CMP_ERR);
557	}
558
559	for (i = 0; i < CTLFE_IN_PER_LUN; i++) {
560		union ccb *new_ccb;
561		union ctl_io *new_io;
562
563		new_ccb = (union ccb *)malloc(sizeof(*new_ccb), M_CTLFE,
564					      M_ZERO|M_NOWAIT);
565		if (new_ccb == NULL) {
566			status = CAM_RESRC_UNAVAIL;
567			break;
568		}
569		new_io = ctl_alloc_io_nowait(bus_softc->port.ctl_pool_ref);
570		if (new_io == NULL) {
571			free(new_ccb, M_CTLFE);
572			status = CAM_RESRC_UNAVAIL;
573			break;
574		}
575		softc->inots_alloced++;
576		new_ccb->ccb_h.io_ptr = new_io;
577		LIST_INSERT_HEAD(&softc->inot_list, &new_ccb->ccb_h, periph_links.le);
578
579		xpt_setup_ccb(&new_ccb->ccb_h, periph->path, CAM_PRIORITY_NONE);
580		new_ccb->ccb_h.func_code = XPT_IMMEDIATE_NOTIFY;
581		new_ccb->ccb_h.cbfcnp = ctlfedone;
582		new_ccb->ccb_h.flags |= CAM_UNLOCKED;
583		xpt_action(new_ccb);
584		status = new_ccb->ccb_h.status;
585		if ((status & CAM_STATUS_MASK) != CAM_REQ_INPROG) {
586			/*
587			 * Note that we don't free the CCB here.  If the
588			 * status is not CAM_REQ_INPROG, then we're
589			 * probably talking to a SIM that says it is
590			 * target-capable but doesn't support the
591			 * XPT_IMMEDIATE_NOTIFY CCB.  i.e. it supports the
592			 * older API.  In that case, it'll call xpt_done()
593			 * on the CCB, and we need to free it in our done
594			 * routine as a result.
595			 */
596			break;
597		}
598	}
599	if ((i == 0)
600	 || (status != CAM_REQ_INPROG)) {
601		xpt_print(periph->path, "%s: could not allocate immediate "
602			  "notify CCBs, status 0x%x\n", __func__, status);
603		return (CAM_REQ_CMP_ERR);
604	}
605	mtx_lock(&bus_softc->lun_softc_mtx);
606	STAILQ_INSERT_TAIL(&bus_softc->lun_softc_list, softc, links);
607	mtx_unlock(&bus_softc->lun_softc_mtx);
608	return (CAM_REQ_CMP);
609}
610
611static void
612ctlfeoninvalidate(struct cam_periph *periph)
613{
614	struct ctlfe_lun_softc *softc = (struct ctlfe_lun_softc *)periph->softc;
615	struct ctlfe_softc *bus_softc;
616	union ccb ccb;
617	struct ccb_hdr *hdr;
618	cam_status status;
619
620	/* Abort all ATIOs and INOTs queued to SIM. */
621	xpt_setup_ccb(&ccb.ccb_h, periph->path, CAM_PRIORITY_NONE);
622	ccb.ccb_h.func_code = XPT_ABORT;
623	LIST_FOREACH(hdr, &softc->atio_list, periph_links.le) {
624		ccb.cab.abort_ccb = (union ccb *)hdr;
625		xpt_action(&ccb);
626	}
627	LIST_FOREACH(hdr, &softc->inot_list, periph_links.le) {
628		ccb.cab.abort_ccb = (union ccb *)hdr;
629		xpt_action(&ccb);
630	}
631
632	/* Disable the LUN in SIM. */
633	ccb.ccb_h.func_code = XPT_EN_LUN;
634	ccb.cel.grp6_len = 0;
635	ccb.cel.grp7_len = 0;
636	ccb.cel.enable = 0;
637	xpt_action(&ccb);
638	status = (ccb.ccb_h.status & CAM_STATUS_MASK);
639	if (status != CAM_REQ_CMP) {
640		xpt_print(periph->path, "%s: Disable LUN failed, status 0x%x\n",
641			  __func__, ccb.ccb_h.status);
642		/*
643		 * XXX KDM what do we do now?
644		 */
645	}
646
647	bus_softc = softc->parent_softc;
648	mtx_lock(&bus_softc->lun_softc_mtx);
649	STAILQ_REMOVE(&bus_softc->lun_softc_list, softc, ctlfe_lun_softc, links);
650	mtx_unlock(&bus_softc->lun_softc_mtx);
651}
652
653static void
654ctlfecleanup(struct cam_periph *periph)
655{
656	struct ctlfe_lun_softc *softc;
657
658	softc = (struct ctlfe_lun_softc *)periph->softc;
659
660	KASSERT(softc->ctios_sent == 0, ("%s: ctios_sent %d != 0",
661	    __func__, softc->ctios_sent));
662	KASSERT(softc->refcount == 0, ("%s: refcount %d != 0",
663	    __func__, softc->refcount));
664	KASSERT(softc->atios_alloced == 0, ("%s: atios_alloced %d != 0",
665	    __func__, softc->atios_alloced));
666	KASSERT(softc->inots_alloced == 0, ("%s: inots_alloced %d != 0",
667	    __func__, softc->inots_alloced));
668
669	free(softc, M_CTLFE);
670}
671
672static void
673ctlfedata(struct ctlfe_lun_softc *softc, union ctl_io *io,
674    ccb_flags *flags, uint8_t **data_ptr, uint32_t *dxfer_len,
675    u_int16_t *sglist_cnt)
676{
677	struct ctlfe_softc *bus_softc;
678	struct ctlfe_cmd_info *cmd_info;
679	struct ctl_sg_entry *ctl_sglist;
680	bus_dma_segment_t *cam_sglist;
681	size_t off;
682	int i, idx;
683
684	cmd_info = PRIV_INFO(io);
685	bus_softc = softc->parent_softc;
686
687	/*
688	 * Set the direction, relative to the initiator.
689	 */
690	*flags &= ~CAM_DIR_MASK;
691	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
692		*flags |= CAM_DIR_IN;
693	else
694		*flags |= CAM_DIR_OUT;
695
696	*flags &= ~CAM_DATA_MASK;
697	idx = cmd_info->cur_transfer_index;
698	off = cmd_info->cur_transfer_off;
699	cmd_info->flags &= ~CTLFE_CMD_PIECEWISE;
700	if (io->scsiio.kern_sg_entries == 0) {	/* No S/G list. */
701
702		/* One time shift for SRR offset. */
703		off += io->scsiio.ext_data_filled;
704		io->scsiio.ext_data_filled = 0;
705
706		*data_ptr = io->scsiio.kern_data_ptr + off;
707		if (io->scsiio.kern_data_len - off <= bus_softc->maxio) {
708			*dxfer_len = io->scsiio.kern_data_len - off;
709		} else {
710			*dxfer_len = bus_softc->maxio;
711			cmd_info->cur_transfer_off += bus_softc->maxio;
712			cmd_info->flags |= CTLFE_CMD_PIECEWISE;
713		}
714		*sglist_cnt = 0;
715
716		if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR)
717			*flags |= CAM_DATA_PADDR;
718		else
719			*flags |= CAM_DATA_VADDR;
720	} else {	/* S/G list with physical or virtual pointers. */
721		ctl_sglist = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
722
723		/* One time shift for SRR offset. */
724		while (io->scsiio.ext_data_filled >= ctl_sglist[idx].len - off) {
725			io->scsiio.ext_data_filled -= ctl_sglist[idx].len - off;
726			idx++;
727			off = 0;
728		}
729		off += io->scsiio.ext_data_filled;
730		io->scsiio.ext_data_filled = 0;
731
732		cam_sglist = cmd_info->cam_sglist;
733		*dxfer_len = 0;
734		for (i = 0; i < io->scsiio.kern_sg_entries - idx; i++) {
735			cam_sglist[i].ds_addr = (bus_addr_t)ctl_sglist[i + idx].addr + off;
736			if (ctl_sglist[i + idx].len - off <= bus_softc->maxio - *dxfer_len) {
737				cam_sglist[i].ds_len = ctl_sglist[idx + i].len - off;
738				*dxfer_len += cam_sglist[i].ds_len;
739			} else {
740				cam_sglist[i].ds_len = bus_softc->maxio - *dxfer_len;
741				cmd_info->cur_transfer_index = idx + i;
742				cmd_info->cur_transfer_off = cam_sglist[i].ds_len + off;
743				cmd_info->flags |= CTLFE_CMD_PIECEWISE;
744				*dxfer_len += cam_sglist[i].ds_len;
745				if (ctl_sglist[i].len != 0)
746					i++;
747				break;
748			}
749			if (i == (CTLFE_MAX_SEGS - 1) &&
750			    idx + i < (io->scsiio.kern_sg_entries - 1)) {
751				cmd_info->cur_transfer_index = idx + i + 1;
752				cmd_info->cur_transfer_off = 0;
753				cmd_info->flags |= CTLFE_CMD_PIECEWISE;
754				i++;
755				break;
756			}
757			off = 0;
758		}
759		*sglist_cnt = i;
760		if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR)
761			*flags |= CAM_DATA_SG_PADDR;
762		else
763			*flags |= CAM_DATA_SG;
764		*data_ptr = (uint8_t *)cam_sglist;
765	}
766}
767
768static void
769ctlfestart(struct cam_periph *periph, union ccb *start_ccb)
770{
771	struct ctlfe_lun_softc *softc;
772	struct ctlfe_cmd_info *cmd_info;
773	struct ccb_hdr *ccb_h;
774	struct ccb_accept_tio *atio;
775	struct ccb_scsiio *csio;
776	uint8_t *data_ptr;
777	uint32_t dxfer_len;
778	ccb_flags flags;
779	union ctl_io *io;
780	uint8_t scsi_status;
781
782	softc = (struct ctlfe_lun_softc *)periph->softc;
783
784next:
785	/* Take the ATIO off the work queue */
786	ccb_h = STAILQ_FIRST(&softc->work_queue);
787	if (ccb_h == NULL) {
788		xpt_release_ccb(start_ccb);
789		return;
790	}
791	STAILQ_REMOVE_HEAD(&softc->work_queue, periph_links.stqe);
792	atio = (struct ccb_accept_tio *)ccb_h;
793	io = (union ctl_io *)ccb_h->io_ptr;
794	csio = &start_ccb->csio;
795
796	flags = atio->ccb_h.flags &
797		(CAM_DIS_DISCONNECT|CAM_TAG_ACTION_VALID|CAM_DIR_MASK);
798	cmd_info = PRIV_INFO(io);
799	cmd_info->cur_transfer_index = 0;
800	cmd_info->cur_transfer_off = 0;
801	cmd_info->flags = 0;
802
803	if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED) {
804		/*
805		 * Datamove call, we need to setup the S/G list.
806		 */
807		ctlfedata(softc, io, &flags, &data_ptr, &dxfer_len,
808		    &csio->sglist_cnt);
809	} else {
810		/*
811		 * We're done, send status back.
812		 */
813		if ((io->io_hdr.flags & CTL_FLAG_ABORT) &&
814		    (io->io_hdr.flags & CTL_FLAG_ABORT_STATUS) == 0) {
815			io->io_hdr.flags &= ~CTL_FLAG_STATUS_QUEUED;
816
817			/* Tell the SIM that we've aborted this ATIO */
818#ifdef CTLFEDEBUG
819			printf("%s: tag %04x abort\n", __func__, atio->tag_id);
820#endif
821			KASSERT(atio->ccb_h.func_code == XPT_ACCEPT_TARGET_IO,
822			    ("func_code %#x is not ATIO", atio->ccb_h.func_code));
823			start_ccb->ccb_h.func_code = XPT_ABORT;
824			start_ccb->cab.abort_ccb = (union ccb *)atio;
825			xpt_action(start_ccb);
826
827			ctlfe_requeue_ccb(periph, (union ccb *)atio,
828			    /* unlock */0);
829
830			/* XPT_ABORT is not queued, so we can take next I/O. */
831			goto next;
832		}
833		data_ptr = NULL;
834		dxfer_len = 0;
835		csio->sglist_cnt = 0;
836	}
837	scsi_status = 0;
838	if ((io->io_hdr.flags & CTL_FLAG_STATUS_QUEUED) &&
839	    (cmd_info->flags & CTLFE_CMD_PIECEWISE) == 0 &&
840	    ((io->io_hdr.flags & CTL_FLAG_DMA_QUEUED) == 0 ||
841	     io->io_hdr.status == CTL_SUCCESS)) {
842		flags |= CAM_SEND_STATUS;
843		scsi_status = io->scsiio.scsi_status;
844		csio->sense_len = io->scsiio.sense_len;
845#ifdef CTLFEDEBUG
846		printf("%s: tag %04x status %x\n", __func__,
847		       atio->tag_id, io->io_hdr.status);
848#endif
849		if (csio->sense_len != 0) {
850			csio->sense_data = io->scsiio.sense_data;
851			flags |= CAM_SEND_SENSE;
852		}
853	}
854
855#ifdef CTLFEDEBUG
856	printf("%s: %s: tag %04x flags %x ptr %p len %u\n", __func__,
857	       (flags & CAM_SEND_STATUS) ? "done" : "datamove",
858	       atio->tag_id, flags, data_ptr, dxfer_len);
859#endif
860
861	/*
862	 * Valid combinations:
863	 *  - CAM_SEND_STATUS, CAM_DATA_SG = 0, dxfer_len = 0,
864	 *    sglist_cnt = 0
865	 *  - CAM_SEND_STATUS = 0, CAM_DATA_SG = 0, dxfer_len != 0,
866	 *    sglist_cnt = 0
867	 *  - CAM_SEND_STATUS = 0, CAM_DATA_SG, dxfer_len != 0,
868	 *    sglist_cnt != 0
869	 */
870#ifdef CTLFEDEBUG
871	if (((flags & CAM_SEND_STATUS)
872	  && (((flags & CAM_DATA_SG) != 0)
873	   || (dxfer_len != 0)
874	   || (csio->sglist_cnt != 0)))
875	 || (((flags & CAM_SEND_STATUS) == 0)
876	  && (dxfer_len == 0))
877	 || ((flags & CAM_DATA_SG)
878	  && (csio->sglist_cnt == 0))
879	 || (((flags & CAM_DATA_SG) == 0)
880	  && (csio->sglist_cnt != 0))) {
881		printf("%s: tag %04x cdb %02x flags %#x dxfer_len "
882		       "%d sg %u\n", __func__, atio->tag_id,
883		       atio_cdb_ptr(atio)[0], flags, dxfer_len,
884		       csio->sglist_cnt);
885		printf("%s: tag %04x io status %#x\n", __func__,
886		       atio->tag_id, io->io_hdr.status);
887	}
888#endif
889	cam_fill_ctio(csio,
890		      /*retries*/ 2,
891		      ctlfedone,
892		      flags,
893		      (flags & CAM_TAG_ACTION_VALID) ? MSG_SIMPLE_Q_TAG : 0,
894		      atio->tag_id,
895		      atio->init_id,
896		      scsi_status,
897		      /*data_ptr*/ data_ptr,
898		      /*dxfer_len*/ dxfer_len,
899		      /*timeout*/ CTLFE_TIMEOUT * 1000);
900	start_ccb->ccb_h.flags |= CAM_UNLOCKED;
901	start_ccb->ccb_h.ccb_atio = atio;
902	if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
903		io->io_hdr.flags |= CTL_FLAG_DMA_INPROG;
904	io->io_hdr.flags &= ~(CTL_FLAG_DMA_QUEUED | CTL_FLAG_STATUS_QUEUED);
905
906	softc->ctios_sent++;
907	softc->refcount++;
908	cam_periph_unlock(periph);
909	xpt_action(start_ccb);
910	cam_periph_lock(periph);
911	softc->refcount--;
912
913	/*
914	 * If we still have work to do, ask for another CCB.
915	 */
916	if (!STAILQ_EMPTY(&softc->work_queue))
917		xpt_schedule(periph, CAM_PRIORITY_NORMAL);
918}
919
920static void
921ctlfe_drain(void *context, int pending)
922{
923	struct cam_periph *periph = context;
924	struct ctlfe_lun_softc *softc = periph->softc;
925
926	cam_periph_lock(periph);
927	while (softc->refcount != 0) {
928		cam_periph_sleep(periph, &softc->refcount, PRIBIO,
929		    "ctlfe_drain", 1);
930	}
931	cam_periph_unlock(periph);
932	cam_periph_release(periph);
933}
934
935static void
936ctlfe_free_ccb(struct cam_periph *periph, union ccb *ccb)
937{
938	struct ctlfe_lun_softc *softc;
939	union ctl_io *io;
940	struct ctlfe_cmd_info *cmd_info;
941
942	softc = (struct ctlfe_lun_softc *)periph->softc;
943	io = ccb->ccb_h.io_ptr;
944
945	switch (ccb->ccb_h.func_code) {
946	case XPT_ACCEPT_TARGET_IO:
947		softc->atios_alloced--;
948		cmd_info = PRIV_INFO(io);
949		free(cmd_info, M_CTLFE);
950		break;
951	case XPT_IMMEDIATE_NOTIFY:
952	case XPT_NOTIFY_ACKNOWLEDGE:
953		softc->inots_alloced--;
954		break;
955	default:
956		break;
957	}
958
959	ctl_free_io(io);
960	free(ccb, M_CTLFE);
961
962	KASSERT(softc->atios_alloced >= 0, ("%s: atios_alloced %d < 0",
963	    __func__, softc->atios_alloced));
964	KASSERT(softc->inots_alloced >= 0, ("%s: inots_alloced %d < 0",
965	    __func__, softc->inots_alloced));
966
967	/*
968	 * If we have received all of our CCBs, we can release our
969	 * reference on the peripheral driver.  It will probably go away
970	 * now.
971	 */
972	if (softc->atios_alloced == 0 && softc->inots_alloced == 0) {
973		if (softc->refcount == 0) {
974			cam_periph_release_locked(periph);
975		} else {
976			TASK_INIT(&softc->refdrain_task, 0, ctlfe_drain, periph);
977			taskqueue_enqueue(taskqueue_thread,
978			    &softc->refdrain_task);
979		}
980	}
981}
982
983/*
984 * Send the ATIO/INOT back to the SIM, or free it if periph was invalidated.
985 */
986static void
987ctlfe_requeue_ccb(struct cam_periph *periph, union ccb *ccb, int unlock)
988{
989	struct ctlfe_lun_softc *softc;
990	struct mtx *mtx;
991
992	if (periph->flags & CAM_PERIPH_INVALID) {
993		mtx = cam_periph_mtx(periph);
994		ctlfe_free_ccb(periph, ccb);
995		if (unlock)
996			mtx_unlock(mtx);
997		return;
998	}
999	softc = (struct ctlfe_lun_softc *)periph->softc;
1000	if (ccb->ccb_h.func_code == XPT_ACCEPT_TARGET_IO)
1001		LIST_INSERT_HEAD(&softc->atio_list, &ccb->ccb_h, periph_links.le);
1002	else
1003		LIST_INSERT_HEAD(&softc->inot_list, &ccb->ccb_h, periph_links.le);
1004	if (unlock)
1005		cam_periph_unlock(periph);
1006
1007	/*
1008	 * For a wildcard attachment, commands can come in with a specific
1009	 * target/lun.  Reset the target and LUN fields back to the wildcard
1010	 * values before we send them back down to the SIM.
1011	 */
1012	xpt_setup_ccb_flags(&ccb->ccb_h, periph->path, CAM_PRIORITY_NONE,
1013	    ccb->ccb_h.flags);
1014
1015	xpt_action(ccb);
1016}
1017
1018static int
1019ctlfe_adjust_cdb(struct ccb_accept_tio *atio, uint32_t offset)
1020{
1021	uint64_t lba;
1022	uint32_t num_blocks, nbc;
1023	uint8_t *cmdbyt = atio_cdb_ptr(atio);
1024
1025	nbc = offset >> 9;	/* ASSUMING 512 BYTE BLOCKS */
1026
1027	switch (cmdbyt[0]) {
1028	case READ_6:
1029	case WRITE_6:
1030	{
1031		struct scsi_rw_6 *cdb = (struct scsi_rw_6 *)cmdbyt;
1032		lba = scsi_3btoul(cdb->addr);
1033		lba &= 0x1fffff;
1034		num_blocks = cdb->length;
1035		if (num_blocks == 0)
1036			num_blocks = 256;
1037		lba += nbc;
1038		num_blocks -= nbc;
1039		scsi_ulto3b(lba, cdb->addr);
1040		cdb->length = num_blocks;
1041		break;
1042	}
1043	case READ_10:
1044	case WRITE_10:
1045	{
1046		struct scsi_rw_10 *cdb = (struct scsi_rw_10 *)cmdbyt;
1047		lba = scsi_4btoul(cdb->addr);
1048		num_blocks = scsi_2btoul(cdb->length);
1049		lba += nbc;
1050		num_blocks -= nbc;
1051		scsi_ulto4b(lba, cdb->addr);
1052		scsi_ulto2b(num_blocks, cdb->length);
1053		break;
1054	}
1055	case READ_12:
1056	case WRITE_12:
1057	{
1058		struct scsi_rw_12 *cdb = (struct scsi_rw_12 *)cmdbyt;
1059		lba = scsi_4btoul(cdb->addr);
1060		num_blocks = scsi_4btoul(cdb->length);
1061		lba += nbc;
1062		num_blocks -= nbc;
1063		scsi_ulto4b(lba, cdb->addr);
1064		scsi_ulto4b(num_blocks, cdb->length);
1065		break;
1066	}
1067	case READ_16:
1068	case WRITE_16:
1069	{
1070		struct scsi_rw_16 *cdb = (struct scsi_rw_16 *)cmdbyt;
1071		lba = scsi_8btou64(cdb->addr);
1072		num_blocks = scsi_4btoul(cdb->length);
1073		lba += nbc;
1074		num_blocks -= nbc;
1075		scsi_u64to8b(lba, cdb->addr);
1076		scsi_ulto4b(num_blocks, cdb->length);
1077		break;
1078	}
1079	default:
1080		return -1;
1081	}
1082	return (0);
1083}
1084
1085static void
1086ctlfedone(struct cam_periph *periph, union ccb *done_ccb)
1087{
1088	struct ctlfe_lun_softc *softc;
1089	struct ctlfe_softc *bus_softc;
1090	struct ctlfe_cmd_info *cmd_info;
1091	struct ccb_accept_tio *atio = NULL;
1092	union ctl_io *io = NULL;
1093	struct mtx *mtx;
1094	cam_status status;
1095
1096	KASSERT((done_ccb->ccb_h.flags & CAM_UNLOCKED) != 0,
1097	    ("CCB in ctlfedone() without CAM_UNLOCKED flag"));
1098#ifdef CTLFE_DEBUG
1099	printf("%s: entered, func_code = %#x\n", __func__,
1100	       done_ccb->ccb_h.func_code);
1101#endif
1102
1103	/*
1104	 * At this point CTL has no known use case for device queue freezes.
1105	 * In case some SIM think different -- drop its freeze right here.
1106	 */
1107	if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
1108		cam_release_devq(periph->path,
1109				 /*relsim_flags*/0,
1110				 /*reduction*/0,
1111				 /*timeout*/0,
1112				 /*getcount_only*/0);
1113		done_ccb->ccb_h.status &= ~CAM_DEV_QFRZN;
1114	}
1115
1116	softc = (struct ctlfe_lun_softc *)periph->softc;
1117	bus_softc = softc->parent_softc;
1118	mtx = cam_periph_mtx(periph);
1119	mtx_lock(mtx);
1120
1121	switch (done_ccb->ccb_h.func_code) {
1122	case XPT_ACCEPT_TARGET_IO: {
1123
1124		LIST_REMOVE(&done_ccb->ccb_h, periph_links.le);
1125		atio = &done_ccb->atio;
1126		status = atio->ccb_h.status & CAM_STATUS_MASK;
1127		if (status != CAM_CDB_RECVD) {
1128			ctlfe_free_ccb(periph, done_ccb);
1129			goto out;
1130		}
1131
1132 resubmit:
1133		/*
1134		 * Allocate a ctl_io, pass it to CTL, and wait for the
1135		 * datamove or done.
1136		 */
1137		mtx_unlock(mtx);
1138		io = done_ccb->ccb_h.io_ptr;
1139		cmd_info = PRIV_INFO(io);
1140		ctl_zero_io(io);
1141
1142		/* Save pointers on both sides */
1143		PRIV_CCB(io) = done_ccb;
1144		PRIV_INFO(io) = cmd_info;
1145		done_ccb->ccb_h.io_ptr = io;
1146
1147		/*
1148		 * Only SCSI I/O comes down this path, resets, etc. come
1149		 * down the immediate notify path below.
1150		 */
1151		io->io_hdr.io_type = CTL_IO_SCSI;
1152		io->io_hdr.nexus.initid = atio->init_id;
1153		io->io_hdr.nexus.targ_port = bus_softc->port.targ_port;
1154		if (bus_softc->hba_misc & PIM_EXTLUNS) {
1155			io->io_hdr.nexus.targ_lun = ctl_decode_lun(
1156			    CAM_EXTLUN_BYTE_SWIZZLE(atio->ccb_h.target_lun));
1157		} else {
1158			io->io_hdr.nexus.targ_lun = atio->ccb_h.target_lun;
1159		}
1160		io->scsiio.tag_num = atio->tag_id;
1161		switch (atio->tag_action) {
1162		case CAM_TAG_ACTION_NONE:
1163			io->scsiio.tag_type = CTL_TAG_UNTAGGED;
1164			break;
1165		case MSG_SIMPLE_TASK:
1166			io->scsiio.tag_type = CTL_TAG_SIMPLE;
1167			break;
1168		case MSG_HEAD_OF_QUEUE_TASK:
1169        		io->scsiio.tag_type = CTL_TAG_HEAD_OF_QUEUE;
1170			break;
1171		case MSG_ORDERED_TASK:
1172        		io->scsiio.tag_type = CTL_TAG_ORDERED;
1173			break;
1174		case MSG_ACA_TASK:
1175			io->scsiio.tag_type = CTL_TAG_ACA;
1176			break;
1177		default:
1178			io->scsiio.tag_type = CTL_TAG_UNTAGGED;
1179			printf("%s: unhandled tag type %#x!!\n", __func__,
1180			       atio->tag_action);
1181			break;
1182		}
1183		if (atio->cdb_len > sizeof(io->scsiio.cdb)) {
1184			printf("%s: WARNING: CDB len %d > ctl_io space %zd\n",
1185			       __func__, atio->cdb_len, sizeof(io->scsiio.cdb));
1186		}
1187		io->scsiio.cdb_len = min(atio->cdb_len, sizeof(io->scsiio.cdb));
1188		bcopy(atio_cdb_ptr(atio), io->scsiio.cdb, io->scsiio.cdb_len);
1189
1190#ifdef CTLFEDEBUG
1191		printf("%s: %u:%u:%u: tag %04x CDB %02x\n", __func__,
1192		        io->io_hdr.nexus.initid,
1193		        io->io_hdr.nexus.targ_port,
1194		        io->io_hdr.nexus.targ_lun,
1195			io->scsiio.tag_num, io->scsiio.cdb[0]);
1196#endif
1197
1198		ctl_queue(io);
1199		return;
1200	}
1201	case XPT_CONT_TARGET_IO: {
1202		int srr = 0;
1203		uint32_t srr_off = 0;
1204
1205		atio = (struct ccb_accept_tio *)done_ccb->ccb_h.ccb_atio;
1206		io = (union ctl_io *)atio->ccb_h.io_ptr;
1207
1208		softc->ctios_sent--;
1209#ifdef CTLFEDEBUG
1210		printf("%s: got XPT_CONT_TARGET_IO tag %#x flags %#x\n",
1211		       __func__, atio->tag_id, done_ccb->ccb_h.flags);
1212#endif
1213		/*
1214		 * Handle SRR case were the data pointer is pushed back hack
1215		 */
1216		if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_MESSAGE_RECV
1217		    && done_ccb->csio.msg_ptr != NULL
1218		    && done_ccb->csio.msg_ptr[0] == MSG_EXTENDED
1219		    && done_ccb->csio.msg_ptr[1] == 5
1220       		    && done_ccb->csio.msg_ptr[2] == 0) {
1221			srr = 1;
1222			srr_off =
1223			    (done_ccb->csio.msg_ptr[3] << 24)
1224			    | (done_ccb->csio.msg_ptr[4] << 16)
1225			    | (done_ccb->csio.msg_ptr[5] << 8)
1226			    | (done_ccb->csio.msg_ptr[6]);
1227		}
1228
1229		/*
1230		 * If we have an SRR and we're still sending data, we
1231		 * should be able to adjust offsets and cycle again.
1232		 * It is possible only if offset is from this datamove.
1233		 */
1234		if (srr && (io->io_hdr.flags & CTL_FLAG_DMA_INPROG) &&
1235		    srr_off >= io->scsiio.kern_rel_offset &&
1236		    srr_off < io->scsiio.kern_rel_offset +
1237		     io->scsiio.kern_data_len) {
1238			io->scsiio.kern_data_resid =
1239			    io->scsiio.kern_rel_offset +
1240			    io->scsiio.kern_data_len - srr_off;
1241			io->scsiio.ext_data_filled = srr_off;
1242			io->scsiio.io_hdr.status = CTL_STATUS_NONE;
1243			io->io_hdr.flags |= CTL_FLAG_DMA_QUEUED;
1244			xpt_release_ccb(done_ccb);
1245			STAILQ_INSERT_HEAD(&softc->work_queue, &atio->ccb_h,
1246					  periph_links.stqe);
1247			xpt_schedule(periph, CAM_PRIORITY_NORMAL);
1248			break;
1249		}
1250
1251		/*
1252		 * If status was being sent, the back end data is now history.
1253		 * Hack it up and resubmit a new command with the CDB adjusted.
1254		 * If the SIM does the right thing, all of the resid math
1255		 * should work.
1256		 */
1257		if (srr && (io->io_hdr.flags & CTL_FLAG_DMA_INPROG) == 0) {
1258			xpt_release_ccb(done_ccb);
1259			if (ctlfe_adjust_cdb(atio, srr_off) == 0) {
1260				done_ccb = (union ccb *)atio;
1261				goto resubmit;
1262			}
1263			/*
1264			 * Fall through to doom....
1265			 */
1266		}
1267
1268		if ((done_ccb->ccb_h.flags & CAM_SEND_STATUS) &&
1269		    (done_ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP)
1270			io->io_hdr.flags |= CTL_FLAG_STATUS_SENT;
1271
1272		/*
1273		 * If we were sending status back to the initiator, free up
1274		 * resources.  If we were doing a datamove, call the
1275		 * datamove done routine.
1276		 */
1277		if ((io->io_hdr.flags & CTL_FLAG_DMA_INPROG) == 0) {
1278			/*
1279			 * If we asked to send sense data but it wasn't sent,
1280			 * queue the I/O back to CTL for later REQUEST SENSE.
1281			 */
1282			if ((done_ccb->ccb_h.flags & CAM_SEND_SENSE) != 0 &&
1283			    (done_ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP &&
1284			    (done_ccb->ccb_h.status & CAM_SENT_SENSE) == 0 &&
1285			    (io = ctl_alloc_io_nowait(bus_softc->port.ctl_pool_ref)) != NULL) {
1286				PRIV_INFO(io) = PRIV_INFO(
1287				    (union ctl_io *)atio->ccb_h.io_ptr);
1288				ctl_queue_sense(atio->ccb_h.io_ptr);
1289				atio->ccb_h.io_ptr = io;
1290			}
1291
1292			/* Abort ATIO if CTIO sending status has failed. */
1293			if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) !=
1294			    CAM_REQ_CMP) {
1295				done_ccb->ccb_h.func_code = XPT_ABORT;
1296				done_ccb->cab.abort_ccb = (union ccb *)atio;
1297				xpt_action(done_ccb);
1298			}
1299
1300			xpt_release_ccb(done_ccb);
1301			ctlfe_requeue_ccb(periph, (union ccb *)atio,
1302			    /* unlock */1);
1303			return;
1304		} else {
1305			struct ctlfe_cmd_info *cmd_info;
1306			struct ccb_scsiio *csio;
1307
1308			csio = &done_ccb->csio;
1309			cmd_info = PRIV_INFO(io);
1310
1311			io->io_hdr.flags &= ~CTL_FLAG_DMA_INPROG;
1312
1313			/*
1314			 * Translate CAM status to CTL status.  Success
1315			 * does not change the overall, ctl_io status.  In
1316			 * that case we just set port_status to 0.  If we
1317			 * have a failure, though, set a data phase error
1318			 * for the overall ctl_io.
1319			 */
1320			switch (done_ccb->ccb_h.status & CAM_STATUS_MASK) {
1321			case CAM_REQ_CMP:
1322				io->scsiio.kern_data_resid -=
1323				    csio->dxfer_len - csio->resid;
1324				io->io_hdr.port_status = 0;
1325				break;
1326			default:
1327				/*
1328				 * XXX KDM we probably need to figure out a
1329				 * standard set of errors that the SIM
1330				 * drivers should return in the event of a
1331				 * data transfer failure.  A data phase
1332				 * error will at least point the user to a
1333				 * data transfer error of some sort.
1334				 * Hopefully the SIM printed out some
1335				 * additional information to give the user
1336				 * a clue what happened.
1337				 */
1338				io->io_hdr.port_status = 0xbad1;
1339				ctl_set_data_phase_error(&io->scsiio);
1340				/*
1341				 * XXX KDM figure out residual.
1342				 */
1343				break;
1344			}
1345			/*
1346			 * If we had to break this S/G list into multiple
1347			 * pieces, figure out where we are in the list, and
1348			 * continue sending pieces if necessary.
1349			 */
1350			if ((cmd_info->flags & CTLFE_CMD_PIECEWISE) &&
1351			    io->io_hdr.port_status == 0 && csio->resid == 0) {
1352				ccb_flags flags;
1353				uint8_t *data_ptr;
1354				uint32_t dxfer_len;
1355
1356				flags = atio->ccb_h.flags &
1357					(CAM_DIS_DISCONNECT|
1358					 CAM_TAG_ACTION_VALID);
1359
1360				ctlfedata(softc, io, &flags, &data_ptr,
1361				    &dxfer_len, &csio->sglist_cnt);
1362
1363				if (((flags & CAM_SEND_STATUS) == 0)
1364				 && (dxfer_len == 0)) {
1365					printf("%s: tag %04x no status or "
1366					       "len cdb = %02x\n", __func__,
1367					       atio->tag_id,
1368					       atio_cdb_ptr(atio)[0]);
1369					printf("%s: tag %04x io status %#x\n",
1370					       __func__, atio->tag_id,
1371					       io->io_hdr.status);
1372				}
1373
1374				cam_fill_ctio(csio,
1375					      /*retries*/ 2,
1376					      ctlfedone,
1377					      flags,
1378					      (flags & CAM_TAG_ACTION_VALID) ?
1379					       MSG_SIMPLE_Q_TAG : 0,
1380					      atio->tag_id,
1381					      atio->init_id,
1382					      0,
1383					      /*data_ptr*/ data_ptr,
1384					      /*dxfer_len*/ dxfer_len,
1385					      CTLFE_TIMEOUT * 1000);
1386
1387				csio->ccb_h.flags |= CAM_UNLOCKED;
1388				csio->resid = 0;
1389				csio->ccb_h.ccb_atio = atio;
1390				io->io_hdr.flags |= CTL_FLAG_DMA_INPROG;
1391				softc->ctios_sent++;
1392				mtx_unlock(mtx);
1393				xpt_action((union ccb *)csio);
1394			} else {
1395				/*
1396				 * Release the CTIO.  The ATIO will be sent back
1397				 * down to the SIM once we send status.
1398				 */
1399				xpt_release_ccb(done_ccb);
1400				mtx_unlock(mtx);
1401
1402				/* Call the backend move done callback */
1403				io->scsiio.be_move_done(io);
1404			}
1405			return;
1406		}
1407		break;
1408	}
1409	case XPT_IMMEDIATE_NOTIFY: {
1410		union ctl_io *io;
1411		struct ccb_immediate_notify *inot;
1412		int send_ctl_io;
1413
1414		LIST_REMOVE(&done_ccb->ccb_h, periph_links.le);
1415		inot = &done_ccb->cin1;
1416		io = done_ccb->ccb_h.io_ptr;
1417		ctl_zero_io(io);
1418
1419		send_ctl_io = 1;
1420
1421		io->io_hdr.io_type = CTL_IO_TASK;
1422		PRIV_CCB(io) = done_ccb;
1423		inot->ccb_h.io_ptr = io;
1424		io->io_hdr.nexus.initid = inot->initiator_id;
1425		io->io_hdr.nexus.targ_port = bus_softc->port.targ_port;
1426		if (bus_softc->hba_misc & PIM_EXTLUNS) {
1427			io->io_hdr.nexus.targ_lun = ctl_decode_lun(
1428			    CAM_EXTLUN_BYTE_SWIZZLE(inot->ccb_h.target_lun));
1429		} else {
1430			io->io_hdr.nexus.targ_lun = inot->ccb_h.target_lun;
1431		}
1432		/* XXX KDM should this be the tag_id? */
1433		io->taskio.tag_num = inot->seq_id;
1434
1435		status = inot->ccb_h.status & CAM_STATUS_MASK;
1436		switch (status) {
1437		case CAM_SCSI_BUS_RESET:
1438			io->taskio.task_action = CTL_TASK_BUS_RESET;
1439			break;
1440		case CAM_BDR_SENT:
1441			io->taskio.task_action = CTL_TASK_TARGET_RESET;
1442			break;
1443		case CAM_MESSAGE_RECV:
1444			switch (inot->arg) {
1445			case MSG_ABORT_TASK_SET:
1446				io->taskio.task_action =
1447				    CTL_TASK_ABORT_TASK_SET;
1448				break;
1449			case MSG_TARGET_RESET:
1450				io->taskio.task_action = CTL_TASK_TARGET_RESET;
1451				break;
1452			case MSG_ABORT_TASK:
1453				io->taskio.task_action = CTL_TASK_ABORT_TASK;
1454				break;
1455			case MSG_LOGICAL_UNIT_RESET:
1456				io->taskio.task_action = CTL_TASK_LUN_RESET;
1457				break;
1458			case MSG_CLEAR_TASK_SET:
1459				io->taskio.task_action =
1460				    CTL_TASK_CLEAR_TASK_SET;
1461				break;
1462			case MSG_CLEAR_ACA:
1463				io->taskio.task_action = CTL_TASK_CLEAR_ACA;
1464				break;
1465			case MSG_QUERY_TASK:
1466				io->taskio.task_action = CTL_TASK_QUERY_TASK;
1467				break;
1468			case MSG_QUERY_TASK_SET:
1469				io->taskio.task_action =
1470				    CTL_TASK_QUERY_TASK_SET;
1471				break;
1472			case MSG_QUERY_ASYNC_EVENT:
1473				io->taskio.task_action =
1474				    CTL_TASK_QUERY_ASYNC_EVENT;
1475				break;
1476			case MSG_NOOP:
1477				send_ctl_io = 0;
1478				break;
1479			default:
1480				xpt_print(periph->path,
1481				    "%s: unsupported INOT message 0x%x\n",
1482				    __func__, inot->arg);
1483				send_ctl_io = 0;
1484				break;
1485			}
1486			break;
1487		default:
1488			xpt_print(periph->path,
1489			    "%s: unsupported INOT status 0x%x\n",
1490			    __func__, status);
1491			/* FALLTHROUGH */
1492		case CAM_REQ_ABORTED:
1493		case CAM_REQ_INVALID:
1494		case CAM_DEV_NOT_THERE:
1495		case CAM_PROVIDE_FAIL:
1496			ctlfe_free_ccb(periph, done_ccb);
1497			goto out;
1498		}
1499		if (send_ctl_io != 0) {
1500			ctl_queue(io);
1501		} else {
1502			done_ccb->ccb_h.status = CAM_REQ_INPROG;
1503			done_ccb->ccb_h.func_code = XPT_NOTIFY_ACKNOWLEDGE;
1504			xpt_action(done_ccb);
1505		}
1506		break;
1507	}
1508	case XPT_NOTIFY_ACKNOWLEDGE:
1509		/* Queue this back down to the SIM as an immediate notify. */
1510		done_ccb->ccb_h.status = CAM_REQ_INPROG;
1511		done_ccb->ccb_h.func_code = XPT_IMMEDIATE_NOTIFY;
1512		ctlfe_requeue_ccb(periph, done_ccb, /* unlock */1);
1513		return;
1514	case XPT_SET_SIM_KNOB:
1515	case XPT_GET_SIM_KNOB:
1516	case XPT_GET_SIM_KNOB_OLD:
1517		break;
1518	default:
1519		panic("%s: unexpected CCB type %#x", __func__,
1520		      done_ccb->ccb_h.func_code);
1521		break;
1522	}
1523
1524out:
1525	mtx_unlock(mtx);
1526}
1527
1528static void
1529ctlfe_onoffline(void *arg, int online)
1530{
1531	struct ctlfe_softc *bus_softc = arg;
1532	union ccb *ccb;
1533	cam_status status;
1534	struct cam_path *path;
1535	int set_wwnn = 0;
1536
1537	status = xpt_create_path(&path, /*periph*/ NULL, bus_softc->path_id,
1538	    CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
1539	if (status != CAM_REQ_CMP) {
1540		printf("%s: unable to create path!\n", __func__);
1541		return;
1542	}
1543	ccb = xpt_alloc_ccb();
1544	xpt_setup_ccb(&ccb->ccb_h, path, CAM_PRIORITY_NONE);
1545	ccb->ccb_h.func_code = XPT_GET_SIM_KNOB;
1546	xpt_action(ccb);
1547
1548	/* Check whether we should change WWNs. */
1549	if (online != 0) {
1550		if ((ccb->knob.xport_specific.valid & KNOB_VALID_ADDRESS) != 0){
1551			printf("%s: %s current WWNN %#jx\n", __func__,
1552			       bus_softc->port_name,
1553			       ccb->knob.xport_specific.fc.wwnn);
1554			printf("%s: %s current WWPN %#jx\n", __func__,
1555			       bus_softc->port_name,
1556			       ccb->knob.xport_specific.fc.wwpn);
1557
1558			/*
1559			 * If the user has specified a WWNN/WWPN, send them
1560			 * down to the SIM.  Otherwise, record what the SIM
1561			 * has reported.
1562			 */
1563			if (bus_softc->port.wwnn != 0 && bus_softc->port.wwnn
1564			    != ccb->knob.xport_specific.fc.wwnn) {
1565				ccb->knob.xport_specific.fc.wwnn =
1566				    bus_softc->port.wwnn;
1567				set_wwnn = 1;
1568			} else {
1569				ctl_port_set_wwns(&bus_softc->port,
1570				    true, ccb->knob.xport_specific.fc.wwnn,
1571				    false, 0);
1572			}
1573			if (bus_softc->port.wwpn != 0 && bus_softc->port.wwpn
1574			     != ccb->knob.xport_specific.fc.wwpn) {
1575				ccb->knob.xport_specific.fc.wwpn =
1576				    bus_softc->port.wwpn;
1577				set_wwnn = 1;
1578			} else {
1579				ctl_port_set_wwns(&bus_softc->port,
1580				    false, 0,
1581				    true, ccb->knob.xport_specific.fc.wwpn);
1582			}
1583		} else {
1584			printf("%s: %s has no valid WWNN/WWPN\n", __func__,
1585			       bus_softc->port_name);
1586			if (bus_softc->port.wwnn != 0) {
1587				ccb->knob.xport_specific.fc.wwnn =
1588				    bus_softc->port.wwnn;
1589				set_wwnn = 1;
1590			}
1591			if (bus_softc->port.wwpn != 0) {
1592				ccb->knob.xport_specific.fc.wwpn =
1593				    bus_softc->port.wwpn;
1594				set_wwnn = 1;
1595			}
1596		}
1597	}
1598	if (set_wwnn) {
1599		ccb->ccb_h.func_code = XPT_SET_SIM_KNOB;
1600		ccb->knob.xport_specific.valid = KNOB_VALID_ADDRESS;
1601		xpt_action(ccb);
1602		if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1603			printf("%s: %s (path id %d) failed set WWNs: %#x\n",
1604			    __func__, bus_softc->port_name, bus_softc->path_id,
1605			    ccb->ccb_h.status);
1606		} else {
1607			printf("%s: %s new WWNN %#jx\n", __func__,
1608			       bus_softc->port_name,
1609			       ccb->knob.xport_specific.fc.wwnn);
1610			printf("%s: %s new WWPN %#jx\n", __func__,
1611			       bus_softc->port_name,
1612			       ccb->knob.xport_specific.fc.wwpn);
1613		}
1614	}
1615
1616	/* Check whether we should change role. */
1617	if ((ccb->knob.xport_specific.valid & KNOB_VALID_ROLE) == 0 ||
1618	    ((online != 0) ^
1619	    ((ccb->knob.xport_specific.fc.role & KNOB_ROLE_TARGET) != 0)) != 0) {
1620		ccb->ccb_h.func_code = XPT_SET_SIM_KNOB;
1621		ccb->knob.xport_specific.valid = KNOB_VALID_ROLE;
1622		if (online)
1623			ccb->knob.xport_specific.fc.role |= KNOB_ROLE_TARGET;
1624		else
1625			ccb->knob.xport_specific.fc.role &= ~KNOB_ROLE_TARGET;
1626		xpt_action(ccb);
1627		if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1628			printf("%s: %s (path id %d) failed %s target role: %#x\n",
1629			    __func__, bus_softc->port_name, bus_softc->path_id,
1630			    online ? "enable" : "disable", ccb->ccb_h.status);
1631		} else {
1632			printf("%s: %s (path id %d) target role %s succeeded\n",
1633			    __func__, bus_softc->port_name, bus_softc->path_id,
1634			    online ? "enable" : "disable");
1635		}
1636	}
1637
1638	xpt_free_path(path);
1639	xpt_free_ccb(ccb);
1640}
1641
1642static void
1643ctlfe_online(void *arg)
1644{
1645	struct ctlfe_softc *bus_softc;
1646	struct cam_path *path;
1647	cam_status status;
1648	struct ctlfe_lun_softc *lun_softc;
1649	struct cam_periph *periph;
1650
1651	bus_softc = (struct ctlfe_softc *)arg;
1652
1653	/*
1654	 * Create the wildcard LUN before bringing the port online.
1655	 */
1656	status = xpt_create_path(&path, /*periph*/ NULL,
1657				 bus_softc->path_id, CAM_TARGET_WILDCARD,
1658				 CAM_LUN_WILDCARD);
1659	if (status != CAM_REQ_CMP) {
1660		printf("%s: unable to create path for wildcard periph\n",
1661				__func__);
1662		return;
1663	}
1664
1665	lun_softc = malloc(sizeof(*lun_softc), M_CTLFE, M_WAITOK | M_ZERO);
1666
1667	xpt_path_lock(path);
1668	periph = cam_periph_find(path, "ctl");
1669	if (periph != NULL) {
1670		/* We've already got a periph, no need to alloc a new one. */
1671		xpt_path_unlock(path);
1672		xpt_free_path(path);
1673		free(lun_softc, M_CTLFE);
1674		return;
1675	}
1676	lun_softc->parent_softc = bus_softc;
1677	lun_softc->flags |= CTLFE_LUN_WILDCARD;
1678
1679	status = cam_periph_alloc(ctlferegister,
1680				  ctlfeoninvalidate,
1681				  ctlfecleanup,
1682				  ctlfestart,
1683				  "ctl",
1684				  CAM_PERIPH_BIO,
1685				  path,
1686				  ctlfeasync,
1687				  0,
1688				  lun_softc);
1689
1690	if ((status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1691		const struct cam_status_entry *entry;
1692
1693		entry = cam_fetch_status_entry(status);
1694		printf("%s: CAM error %s (%#x) returned from "
1695		       "cam_periph_alloc()\n", __func__, (entry != NULL) ?
1696		       entry->status_text : "Unknown", status);
1697		free(lun_softc, M_CTLFE);
1698	}
1699
1700	xpt_path_unlock(path);
1701	ctlfe_onoffline(arg, /*online*/ 1);
1702	xpt_free_path(path);
1703}
1704
1705static void
1706ctlfe_offline(void *arg)
1707{
1708	struct ctlfe_softc *bus_softc;
1709	struct cam_path *path;
1710	cam_status status;
1711	struct cam_periph *periph;
1712
1713	bus_softc = (struct ctlfe_softc *)arg;
1714
1715	ctlfe_onoffline(arg, /*online*/ 0);
1716
1717	/*
1718	 * Disable the wildcard LUN for this port now that we have taken
1719	 * the port offline.
1720	 */
1721	status = xpt_create_path(&path, /*periph*/ NULL,
1722				 bus_softc->path_id, CAM_TARGET_WILDCARD,
1723				 CAM_LUN_WILDCARD);
1724	if (status != CAM_REQ_CMP) {
1725		printf("%s: unable to create path for wildcard periph\n",
1726		       __func__);
1727		return;
1728	}
1729	xpt_path_lock(path);
1730	if ((periph = cam_periph_find(path, "ctl")) != NULL)
1731		cam_periph_invalidate(periph);
1732	xpt_path_unlock(path);
1733	xpt_free_path(path);
1734}
1735
1736/*
1737 * This will get called to enable a LUN on every bus that is attached to
1738 * CTL.  So we only need to create a path/periph for this particular bus.
1739 */
1740static int
1741ctlfe_lun_enable(void *arg, int lun_id)
1742{
1743	struct ctlfe_softc *bus_softc;
1744	struct ctlfe_lun_softc *softc;
1745	struct cam_path *path;
1746	struct cam_periph *periph;
1747	cam_status status;
1748
1749	bus_softc = (struct ctlfe_softc *)arg;
1750	if (bus_softc->hba_misc & PIM_EXTLUNS)
1751		lun_id = CAM_EXTLUN_BYTE_SWIZZLE(ctl_encode_lun(lun_id));
1752
1753	status = xpt_create_path(&path, /*periph*/ NULL,
1754	    bus_softc->path_id, bus_softc->target_id, lun_id);
1755	/* XXX KDM need some way to return status to CTL here? */
1756	if (status != CAM_REQ_CMP) {
1757		printf("%s: could not create path, status %#x\n", __func__,
1758		       status);
1759		return (1);
1760	}
1761
1762	softc = malloc(sizeof(*softc), M_CTLFE, M_WAITOK | M_ZERO);
1763	xpt_path_lock(path);
1764	periph = cam_periph_find(path, "ctl");
1765	if (periph != NULL) {
1766		/* We've already got a periph, no need to alloc a new one. */
1767		xpt_path_unlock(path);
1768		xpt_free_path(path);
1769		free(softc, M_CTLFE);
1770		return (0);
1771	}
1772	softc->parent_softc = bus_softc;
1773
1774	status = cam_periph_alloc(ctlferegister,
1775				  ctlfeoninvalidate,
1776				  ctlfecleanup,
1777				  ctlfestart,
1778				  "ctl",
1779				  CAM_PERIPH_BIO,
1780				  path,
1781				  ctlfeasync,
1782				  0,
1783				  softc);
1784
1785	if ((status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1786		const struct cam_status_entry *entry;
1787
1788		entry = cam_fetch_status_entry(status);
1789		printf("%s: CAM error %s (%#x) returned from "
1790		       "cam_periph_alloc()\n", __func__, (entry != NULL) ?
1791		       entry->status_text : "Unknown", status);
1792		free(softc, M_CTLFE);
1793	}
1794
1795	xpt_path_unlock(path);
1796	xpt_free_path(path);
1797	return (0);
1798}
1799
1800/*
1801 * This will get called when the user removes a LUN to disable that LUN
1802 * on every bus that is attached to CTL.
1803 */
1804static int
1805ctlfe_lun_disable(void *arg, int lun_id)
1806{
1807	struct ctlfe_softc *softc;
1808	struct ctlfe_lun_softc *lun_softc;
1809
1810	softc = (struct ctlfe_softc *)arg;
1811	if (softc->hba_misc & PIM_EXTLUNS)
1812		lun_id = CAM_EXTLUN_BYTE_SWIZZLE(ctl_encode_lun(lun_id));
1813
1814	mtx_lock(&softc->lun_softc_mtx);
1815	STAILQ_FOREACH(lun_softc, &softc->lun_softc_list, links) {
1816		struct cam_path *path;
1817
1818		path = lun_softc->periph->path;
1819
1820		if ((xpt_path_target_id(path) == softc->target_id)
1821		 && (xpt_path_lun_id(path) == lun_id)) {
1822			break;
1823		}
1824	}
1825	if (lun_softc == NULL) {
1826		mtx_unlock(&softc->lun_softc_mtx);
1827		printf("%s: can't find lun %d\n", __func__, lun_id);
1828		return (1);
1829	}
1830	cam_periph_acquire(lun_softc->periph);
1831	mtx_unlock(&softc->lun_softc_mtx);
1832
1833	cam_periph_lock(lun_softc->periph);
1834	cam_periph_invalidate(lun_softc->periph);
1835	cam_periph_unlock(lun_softc->periph);
1836	cam_periph_release(lun_softc->periph);
1837	return (0);
1838}
1839
1840static void
1841ctlfe_dump_sim(struct cam_sim *sim)
1842{
1843
1844	printf("%s%d: max dev openings: %d, max tagged dev openings: %d\n",
1845	    sim->sim_name, sim->unit_number, sim->max_dev_openings,
1846	    sim->max_tagged_dev_openings);
1847}
1848
1849/*
1850 * Assumes that the SIM lock is held.
1851 */
1852static void
1853ctlfe_dump_queue(struct ctlfe_lun_softc *softc)
1854{
1855	struct cam_periph *periph = softc->periph;
1856	struct ccb_hdr *hdr;
1857	struct ccb_getdevstats cgds;
1858	int num_items;
1859
1860	xpt_setup_ccb(&cgds.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
1861	cgds.ccb_h.func_code = XPT_GDEV_STATS;
1862	xpt_action((union ccb *)&cgds);
1863	if ((cgds.ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
1864		xpt_print(periph->path, "devq: openings %d, active %d, "
1865		    "allocated %d, queued %d, held %d\n",
1866		    cgds.dev_openings, cgds.dev_active, cgds.allocated,
1867		    cgds.queued, cgds.held);
1868	}
1869
1870	num_items = 0;
1871
1872	STAILQ_FOREACH(hdr, &softc->work_queue, periph_links.stqe) {
1873		union ctl_io *io = hdr->io_ptr;
1874
1875		num_items++;
1876
1877		/*
1878		 * Only regular SCSI I/O is put on the work
1879		 * queue, so we can print sense here.  There may be no
1880		 * sense if it's no the queue for a DMA, but this serves to
1881		 * print out the CCB as well.
1882		 *
1883		 * XXX KDM switch this over to scsi_sense_print() when
1884		 * CTL is merged in with CAM.
1885		 */
1886		ctl_io_error_print(io, NULL);
1887
1888		/*
1889		 * Print DMA status if we are DMA_QUEUED.
1890		 */
1891		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED) {
1892			xpt_print(periph->path,
1893			    "Total %u, Current %u, Resid %u\n",
1894			    io->scsiio.kern_total_len,
1895			    io->scsiio.kern_data_len,
1896			    io->scsiio.kern_data_resid);
1897		}
1898	}
1899
1900	xpt_print(periph->path, "%d requests waiting for CCBs\n", num_items);
1901	xpt_print(periph->path, "%d CTIOs outstanding\n", softc->ctios_sent);
1902}
1903
1904/*
1905 * Datamove/done routine called by CTL.  Put ourselves on the queue to
1906 * receive a CCB from CAM so we can queue the continue I/O request down
1907 * to the adapter.
1908 */
1909static void
1910ctlfe_datamove(union ctl_io *io)
1911{
1912	union ccb *ccb;
1913	struct cam_periph *periph;
1914	struct ctlfe_lun_softc *softc;
1915
1916	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
1917	    ("Unexpected io_type (%d) in ctlfe_datamove", io->io_hdr.io_type));
1918
1919	io->scsiio.ext_data_filled = 0;
1920	ccb = PRIV_CCB(io);
1921	periph = xpt_path_periph(ccb->ccb_h.path);
1922	cam_periph_lock(periph);
1923	softc = (struct ctlfe_lun_softc *)periph->softc;
1924	io->io_hdr.flags |= CTL_FLAG_DMA_QUEUED;
1925	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE)
1926		io->io_hdr.flags |= CTL_FLAG_STATUS_QUEUED;
1927	STAILQ_INSERT_TAIL(&softc->work_queue, &ccb->ccb_h,
1928			  periph_links.stqe);
1929	xpt_schedule(periph, CAM_PRIORITY_NORMAL);
1930	cam_periph_unlock(periph);
1931}
1932
1933static void
1934ctlfe_done(union ctl_io *io)
1935{
1936	union ccb *ccb;
1937	struct cam_periph *periph;
1938	struct ctlfe_lun_softc *softc;
1939
1940	ccb = PRIV_CCB(io);
1941	periph = xpt_path_periph(ccb->ccb_h.path);
1942	cam_periph_lock(periph);
1943	softc = (struct ctlfe_lun_softc *)periph->softc;
1944
1945	if (io->io_hdr.io_type == CTL_IO_TASK) {
1946		/*
1947		 * Send the notify acknowledge down to the SIM, to let it
1948		 * know we processed the task management command.
1949		 */
1950		ccb->ccb_h.status = CAM_REQ_INPROG;
1951		ccb->ccb_h.func_code = XPT_NOTIFY_ACKNOWLEDGE;
1952		switch (io->taskio.task_status) {
1953		case CTL_TASK_FUNCTION_COMPLETE:
1954			ccb->cna2.arg = CAM_RSP_TMF_COMPLETE;
1955			break;
1956		case CTL_TASK_FUNCTION_SUCCEEDED:
1957			ccb->cna2.arg = CAM_RSP_TMF_SUCCEEDED;
1958			ccb->ccb_h.flags |= CAM_SEND_STATUS;
1959			break;
1960		case CTL_TASK_FUNCTION_REJECTED:
1961			ccb->cna2.arg = CAM_RSP_TMF_REJECTED;
1962			ccb->ccb_h.flags |= CAM_SEND_STATUS;
1963			break;
1964		case CTL_TASK_LUN_DOES_NOT_EXIST:
1965			ccb->cna2.arg = CAM_RSP_TMF_INCORRECT_LUN;
1966			ccb->ccb_h.flags |= CAM_SEND_STATUS;
1967			break;
1968		case CTL_TASK_FUNCTION_NOT_SUPPORTED:
1969			ccb->cna2.arg = CAM_RSP_TMF_FAILED;
1970			ccb->ccb_h.flags |= CAM_SEND_STATUS;
1971			break;
1972		}
1973		ccb->cna2.arg |= scsi_3btoul(io->taskio.task_resp) << 8;
1974		xpt_action(ccb);
1975	} else if (io->io_hdr.flags & CTL_FLAG_STATUS_SENT) {
1976		ctlfe_requeue_ccb(periph, ccb, /* unlock */1);
1977		return;
1978	} else {
1979		io->io_hdr.flags |= CTL_FLAG_STATUS_QUEUED;
1980		STAILQ_INSERT_TAIL(&softc->work_queue, &ccb->ccb_h,
1981				  periph_links.stqe);
1982		xpt_schedule(periph, CAM_PRIORITY_NORMAL);
1983	}
1984
1985	cam_periph_unlock(periph);
1986}
1987
1988static void
1989ctlfe_dump(void)
1990{
1991	struct ctlfe_softc *bus_softc;
1992	struct ctlfe_lun_softc *lun_softc;
1993
1994	STAILQ_FOREACH(bus_softc, &ctlfe_softc_list, links) {
1995		ctlfe_dump_sim(bus_softc->sim);
1996		STAILQ_FOREACH(lun_softc, &bus_softc->lun_softc_list, links)
1997			ctlfe_dump_queue(lun_softc);
1998	}
1999}
2000