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