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