scsi_ctl.c revision 288792
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 288792 2015-10-05 10:56:04Z 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		port->targ_port = -1;
404
405		/*
406		 * XXX KDM need to figure out whether we're the master or
407		 * slave.
408		 */
409#ifdef CTLFEDEBUG
410		printf("%s: calling ctl_port_register() for %s%d\n",
411		       __func__, cpi->dev_name, cpi->unit_number);
412#endif
413		retval = ctl_port_register(port);
414		if (retval != 0) {
415			printf("%s: ctl_port_register() failed with "
416			       "error %d!\n", __func__, retval);
417			mtx_destroy(&softc->lun_softc_mtx);
418			free(softc, M_CTLFE);
419			break;
420		} else {
421			mtx_lock(&ctlfe_list_mtx);
422			STAILQ_INSERT_TAIL(&ctlfe_softc_list, softc, links);
423			mtx_unlock(&ctlfe_list_mtx);
424		}
425
426		break;
427	}
428	case AC_PATH_DEREGISTERED: {
429
430		if (softc != NULL) {
431			/*
432			 * XXX KDM are we certain at this point that there
433			 * are no outstanding commands for this frontend?
434			 */
435			mtx_lock(&ctlfe_list_mtx);
436			STAILQ_REMOVE(&ctlfe_softc_list, softc, ctlfe_softc,
437			    links);
438			mtx_unlock(&ctlfe_list_mtx);
439			ctl_port_deregister(&softc->port);
440			mtx_destroy(&softc->lun_softc_mtx);
441			free(softc, M_CTLFE);
442		}
443		break;
444	}
445	case AC_CONTRACT: {
446		struct ac_contract *ac;
447
448		ac = (struct ac_contract *)arg;
449
450		switch (ac->contract_number) {
451		case AC_CONTRACT_DEV_CHG: {
452			struct ac_device_changed *dev_chg;
453			int retval;
454
455			dev_chg = (struct ac_device_changed *)ac->contract_data;
456
457			printf("%s: WWPN %#jx port 0x%06x path %u target %u %s\n",
458			       __func__, dev_chg->wwpn, dev_chg->port,
459			       xpt_path_path_id(path), dev_chg->target,
460			       (dev_chg->arrived == 0) ?  "left" : "arrived");
461
462			if (softc == NULL) {
463				printf("%s: CTL port for CAM path %u not "
464				       "found!\n", __func__,
465				       xpt_path_path_id(path));
466				break;
467			}
468			if (dev_chg->arrived != 0) {
469				retval = ctl_add_initiator(&softc->port,
470				    dev_chg->target, dev_chg->wwpn, NULL);
471			} else {
472				retval = ctl_remove_initiator(&softc->port,
473				    dev_chg->target);
474			}
475
476			if (retval < 0) {
477				printf("%s: could not %s port %d iid %u "
478				       "WWPN %#jx!\n", __func__,
479				       (dev_chg->arrived != 0) ? "add" :
480				       "remove", softc->port.targ_port,
481				       dev_chg->target,
482				       (uintmax_t)dev_chg->wwpn);
483			}
484			break;
485		}
486		default:
487			printf("%s: unsupported contract number %ju\n",
488			       __func__, (uintmax_t)ac->contract_number);
489			break;
490		}
491		break;
492	}
493	default:
494		break;
495	}
496}
497
498static cam_status
499ctlferegister(struct cam_periph *periph, void *arg)
500{
501	struct ctlfe_softc *bus_softc;
502	struct ctlfe_lun_softc *softc;
503	union ccb en_lun_ccb;
504	cam_status status;
505	int i;
506
507	softc = (struct ctlfe_lun_softc *)arg;
508	bus_softc = softc->parent_softc;
509
510	TAILQ_INIT(&softc->work_queue);
511	softc->periph = periph;
512	periph->softc = softc;
513
514	xpt_setup_ccb(&en_lun_ccb.ccb_h, periph->path, CAM_PRIORITY_NONE);
515	en_lun_ccb.ccb_h.func_code = XPT_EN_LUN;
516	en_lun_ccb.cel.grp6_len = 0;
517	en_lun_ccb.cel.grp7_len = 0;
518	en_lun_ccb.cel.enable = 1;
519	xpt_action(&en_lun_ccb);
520	status = (en_lun_ccb.ccb_h.status & CAM_STATUS_MASK);
521	if (status != CAM_REQ_CMP) {
522		xpt_print(periph->path, "%s: Enable LUN failed, status 0x%x\n",
523			  __func__, en_lun_ccb.ccb_h.status);
524		return (status);
525	}
526
527	status = CAM_REQ_CMP;
528
529	for (i = 0; i < CTLFE_ATIO_PER_LUN; i++) {
530		union ccb *new_ccb;
531		union ctl_io *new_io;
532		struct ctlfe_cmd_info *cmd_info;
533
534		new_ccb = (union ccb *)malloc(sizeof(*new_ccb), M_CTLFE,
535					      M_ZERO|M_NOWAIT);
536		if (new_ccb == NULL) {
537			status = CAM_RESRC_UNAVAIL;
538			break;
539		}
540		new_io = ctl_alloc_io_nowait(bus_softc->port.ctl_pool_ref);
541		if (new_io == NULL) {
542			free(new_ccb, M_CTLFE);
543			status = CAM_RESRC_UNAVAIL;
544			break;
545		}
546		cmd_info = malloc(sizeof(*cmd_info), M_CTLFE,
547		    M_ZERO | M_NOWAIT);
548		if (cmd_info == NULL) {
549			ctl_free_io(new_io);
550			free(new_ccb, M_CTLFE);
551			status = CAM_RESRC_UNAVAIL;
552			break;
553		}
554		new_io->io_hdr.ctl_private[CTL_PRIV_FRONTEND2].ptr = cmd_info;
555		softc->atios_alloced++;
556		new_ccb->ccb_h.io_ptr = new_io;
557
558		xpt_setup_ccb(&new_ccb->ccb_h, periph->path, /*priority*/ 1);
559		new_ccb->ccb_h.func_code = XPT_ACCEPT_TARGET_IO;
560		new_ccb->ccb_h.cbfcnp = ctlfedone;
561		new_ccb->ccb_h.flags |= CAM_UNLOCKED;
562		xpt_action(new_ccb);
563		status = new_ccb->ccb_h.status;
564		if ((status & CAM_STATUS_MASK) != CAM_REQ_INPROG) {
565			free(cmd_info, M_CTLFE);
566			ctl_free_io(new_io);
567			free(new_ccb, M_CTLFE);
568			break;
569		}
570	}
571
572	status = cam_periph_acquire(periph);
573	if ((status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
574		xpt_print(periph->path, "%s: could not acquire reference "
575			  "count, status = %#x\n", __func__, status);
576		return (status);
577	}
578
579	if (i == 0) {
580		xpt_print(periph->path, "%s: could not allocate ATIO CCBs, "
581			  "status 0x%x\n", __func__, status);
582		return (CAM_REQ_CMP_ERR);
583	}
584
585	for (i = 0; i < CTLFE_IN_PER_LUN; i++) {
586		union ccb *new_ccb;
587		union ctl_io *new_io;
588
589		new_ccb = (union ccb *)malloc(sizeof(*new_ccb), M_CTLFE,
590					      M_ZERO|M_NOWAIT);
591		if (new_ccb == NULL) {
592			status = CAM_RESRC_UNAVAIL;
593			break;
594		}
595		new_io = ctl_alloc_io_nowait(bus_softc->port.ctl_pool_ref);
596		if (new_io == NULL) {
597			free(new_ccb, M_CTLFE);
598			status = CAM_RESRC_UNAVAIL;
599			break;
600		}
601		softc->inots_alloced++;
602		new_ccb->ccb_h.io_ptr = new_io;
603
604		xpt_setup_ccb(&new_ccb->ccb_h, periph->path, /*priority*/ 1);
605		new_ccb->ccb_h.func_code = XPT_IMMEDIATE_NOTIFY;
606		new_ccb->ccb_h.cbfcnp = ctlfedone;
607		new_ccb->ccb_h.flags |= CAM_UNLOCKED;
608		xpt_action(new_ccb);
609		status = new_ccb->ccb_h.status;
610		if ((status & CAM_STATUS_MASK) != CAM_REQ_INPROG) {
611			/*
612			 * Note that we don't free the CCB here.  If the
613			 * status is not CAM_REQ_INPROG, then we're
614			 * probably talking to a SIM that says it is
615			 * target-capable but doesn't support the
616			 * XPT_IMMEDIATE_NOTIFY CCB.  i.e. it supports the
617			 * older API.  In that case, it'll call xpt_done()
618			 * on the CCB, and we need to free it in our done
619			 * routine as a result.
620			 */
621			break;
622		}
623	}
624	if ((i == 0)
625	 || (status != CAM_REQ_INPROG)) {
626		xpt_print(periph->path, "%s: could not allocate immediate "
627			  "notify CCBs, status 0x%x\n", __func__, status);
628		return (CAM_REQ_CMP_ERR);
629	}
630	mtx_lock(&bus_softc->lun_softc_mtx);
631	STAILQ_INSERT_TAIL(&bus_softc->lun_softc_list, softc, links);
632	mtx_unlock(&bus_softc->lun_softc_mtx);
633	return (CAM_REQ_CMP);
634}
635
636static void
637ctlfeoninvalidate(struct cam_periph *periph)
638{
639	union ccb en_lun_ccb;
640	cam_status status;
641	struct ctlfe_softc *bus_softc;
642	struct ctlfe_lun_softc *softc;
643
644	softc = (struct ctlfe_lun_softc *)periph->softc;
645
646	xpt_setup_ccb(&en_lun_ccb.ccb_h, periph->path, CAM_PRIORITY_NONE);
647	en_lun_ccb.ccb_h.func_code = XPT_EN_LUN;
648	en_lun_ccb.cel.grp6_len = 0;
649	en_lun_ccb.cel.grp7_len = 0;
650	en_lun_ccb.cel.enable = 0;
651	xpt_action(&en_lun_ccb);
652	status = (en_lun_ccb.ccb_h.status & CAM_STATUS_MASK);
653	if (status != CAM_REQ_CMP) {
654		xpt_print(periph->path, "%s: Disable LUN failed, status 0x%x\n",
655			  __func__, en_lun_ccb.ccb_h.status);
656		/*
657		 * XXX KDM what do we do now?
658		 */
659	}
660
661	bus_softc = softc->parent_softc;
662	mtx_lock(&bus_softc->lun_softc_mtx);
663	STAILQ_REMOVE(&bus_softc->lun_softc_list, softc, ctlfe_lun_softc, links);
664	mtx_unlock(&bus_softc->lun_softc_mtx);
665}
666
667static void
668ctlfecleanup(struct cam_periph *periph)
669{
670	struct ctlfe_lun_softc *softc;
671
672	softc = (struct ctlfe_lun_softc *)periph->softc;
673
674	KASSERT(softc->ccbs_freed == softc->ccbs_alloced, ("%s: "
675		"ccbs_freed %ju != ccbs_alloced %ju", __func__,
676		softc->ccbs_freed, softc->ccbs_alloced));
677	KASSERT(softc->ctios_returned == softc->ctios_sent, ("%s: "
678		"ctios_returned %ju != ctios_sent %ju", __func__,
679		softc->ctios_returned, softc->ctios_sent));
680	KASSERT(softc->atios_freed == softc->atios_alloced, ("%s: "
681		"atios_freed %ju != atios_alloced %ju", __func__,
682		softc->atios_freed, softc->atios_alloced));
683	KASSERT(softc->inots_freed == softc->inots_alloced, ("%s: "
684		"inots_freed %ju != inots_alloced %ju", __func__,
685		softc->inots_freed, softc->inots_alloced));
686
687	free(softc, M_CTLFE);
688}
689
690static void
691ctlfedata(struct ctlfe_lun_softc *softc, union ctl_io *io,
692    ccb_flags *flags, uint8_t **data_ptr, uint32_t *dxfer_len,
693    u_int16_t *sglist_cnt)
694{
695	struct ctlfe_softc *bus_softc;
696	struct ctlfe_cmd_info *cmd_info;
697	struct ctl_sg_entry *ctl_sglist;
698	bus_dma_segment_t *cam_sglist;
699	size_t off;
700	int i, idx;
701
702	cmd_info = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND2].ptr;
703	bus_softc = softc->parent_softc;
704
705	/*
706	 * Set the direction, relative to the initiator.
707	 */
708	*flags &= ~CAM_DIR_MASK;
709	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
710		*flags |= CAM_DIR_IN;
711	else
712		*flags |= CAM_DIR_OUT;
713
714	*flags &= ~CAM_DATA_MASK;
715	idx = cmd_info->cur_transfer_index;
716	off = cmd_info->cur_transfer_off;
717	cmd_info->flags &= ~CTLFE_CMD_PIECEWISE;
718	if (io->scsiio.kern_sg_entries == 0) {
719		/* No S/G list. */
720		*data_ptr = io->scsiio.kern_data_ptr + off;
721		if (io->scsiio.kern_data_len - off <= bus_softc->maxio) {
722			*dxfer_len = io->scsiio.kern_data_len - off;
723		} else {
724			*dxfer_len = bus_softc->maxio;
725			cmd_info->cur_transfer_index = -1;
726			cmd_info->cur_transfer_off = bus_softc->maxio;
727			cmd_info->flags |= CTLFE_CMD_PIECEWISE;
728		}
729		*sglist_cnt = 0;
730
731		if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR)
732			*flags |= CAM_DATA_PADDR;
733		else
734			*flags |= CAM_DATA_VADDR;
735	} else {
736		/* S/G list with physical or virtual pointers. */
737		ctl_sglist = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
738		cam_sglist = cmd_info->cam_sglist;
739		*dxfer_len = 0;
740		for (i = 0; i < io->scsiio.kern_sg_entries - idx; i++) {
741			cam_sglist[i].ds_addr = (bus_addr_t)ctl_sglist[i + idx].addr + off;
742			if (ctl_sglist[i + idx].len - off <= bus_softc->maxio - *dxfer_len) {
743				cam_sglist[i].ds_len = ctl_sglist[idx + i].len - off;
744				*dxfer_len += cam_sglist[i].ds_len;
745			} else {
746				cam_sglist[i].ds_len = bus_softc->maxio - *dxfer_len;
747				cmd_info->cur_transfer_index = idx + i;
748				cmd_info->cur_transfer_off = cam_sglist[i].ds_len + off;
749				cmd_info->flags |= CTLFE_CMD_PIECEWISE;
750				*dxfer_len += cam_sglist[i].ds_len;
751				if (ctl_sglist[i].len != 0)
752					i++;
753				break;
754			}
755			if (i == (CTLFE_MAX_SEGS - 1) &&
756			    idx + i < (io->scsiio.kern_sg_entries - 1)) {
757				cmd_info->cur_transfer_index = idx + i + 1;
758				cmd_info->cur_transfer_off = 0;
759				cmd_info->flags |= CTLFE_CMD_PIECEWISE;
760				i++;
761				break;
762			}
763			off = 0;
764		}
765		*sglist_cnt = i;
766		if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR)
767			*flags |= CAM_DATA_SG_PADDR;
768		else
769			*flags |= CAM_DATA_SG;
770		*data_ptr = (uint8_t *)cam_sglist;
771	}
772}
773
774static void
775ctlfestart(struct cam_periph *periph, union ccb *start_ccb)
776{
777	struct ctlfe_lun_softc *softc;
778	struct ctlfe_cmd_info *cmd_info;
779	struct ccb_hdr *ccb_h;
780	struct ccb_accept_tio *atio;
781	struct ccb_scsiio *csio;
782	uint8_t *data_ptr;
783	uint32_t dxfer_len;
784	ccb_flags flags;
785	union ctl_io *io;
786	uint8_t scsi_status;
787
788	softc = (struct ctlfe_lun_softc *)periph->softc;
789	softc->ccbs_alloced++;
790
791	ccb_h = TAILQ_FIRST(&softc->work_queue);
792	if (ccb_h == NULL) {
793		softc->ccbs_freed++;
794		xpt_release_ccb(start_ccb);
795		return;
796	}
797
798	/* Take the ATIO off the work queue */
799	TAILQ_REMOVE(&softc->work_queue, ccb_h, periph_links.tqe);
800	atio = (struct ccb_accept_tio *)ccb_h;
801	io = (union ctl_io *)ccb_h->io_ptr;
802	csio = &start_ccb->csio;
803
804	flags = atio->ccb_h.flags &
805		(CAM_DIS_DISCONNECT|CAM_TAG_ACTION_VALID|CAM_DIR_MASK);
806	cmd_info = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND2].ptr;
807	cmd_info->cur_transfer_index = 0;
808	cmd_info->cur_transfer_off = 0;
809	cmd_info->flags = 0;
810
811	if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED) {
812		/*
813		 * Datamove call, we need to setup the S/G list.
814		 */
815		scsi_status = 0;
816		csio->cdb_len = atio->cdb_len;
817		ctlfedata(softc, io, &flags, &data_ptr, &dxfer_len,
818		    &csio->sglist_cnt);
819		io->scsiio.ext_data_filled += dxfer_len;
820		if (io->scsiio.ext_data_filled > io->scsiio.kern_total_len) {
821			xpt_print(periph->path, "%s: tag 0x%04x "
822				  "fill len %u > total %u\n",
823				  __func__, io->scsiio.tag_num,
824				  io->scsiio.ext_data_filled,
825				  io->scsiio.kern_total_len);
826		}
827	} else {
828		/*
829		 * We're done, send status back.
830		 */
831		if ((io->io_hdr.flags & CTL_FLAG_ABORT) &&
832		    (io->io_hdr.flags & CTL_FLAG_ABORT_STATUS) == 0) {
833			io->io_hdr.flags &= ~CTL_FLAG_STATUS_QUEUED;
834
835			/*
836			 * If this command was aborted, we don't
837			 * need to send status back to the SIM.
838			 * Just free the CTIO and ctl_io, and
839			 * recycle the ATIO back to the SIM.
840			 */
841			xpt_print(periph->path, "%s: aborted "
842				  "command 0x%04x discarded\n",
843				  __func__, io->scsiio.tag_num);
844			/*
845			 * For a wildcard attachment, commands can
846			 * come in with a specific target/lun.  Reset
847			 * the target and LUN fields back to the
848			 * wildcard values before we send them back
849			 * down to the SIM.  The SIM has a wildcard
850			 * LUN enabled, not whatever target/lun
851			 * these happened to be.
852			 */
853			if (softc->flags & CTLFE_LUN_WILDCARD) {
854				atio->ccb_h.target_id = CAM_TARGET_WILDCARD;
855				atio->ccb_h.target_lun = CAM_LUN_WILDCARD;
856			}
857
858			if (atio->ccb_h.func_code != XPT_ACCEPT_TARGET_IO) {
859				xpt_print(periph->path, "%s: func_code "
860					  "is %#x\n", __func__,
861					  atio->ccb_h.func_code);
862			}
863			start_ccb->ccb_h.func_code = XPT_ABORT;
864			start_ccb->cab.abort_ccb = (union ccb *)atio;
865
866			/* Tell the SIM that we've aborted this ATIO */
867			xpt_action(start_ccb);
868			softc->ccbs_freed++;
869			xpt_release_ccb(start_ccb);
870
871			/*
872			 * Send the ATIO back down to the SIM.
873			 */
874			xpt_action((union ccb *)atio);
875
876			/*
877			 * If we still have work to do, ask for
878			 * another CCB.  Otherwise, deactivate our
879			 * callout.
880			 */
881			if (!TAILQ_EMPTY(&softc->work_queue))
882				xpt_schedule(periph, /*priority*/ 1);
883			return;
884		}
885		data_ptr = NULL;
886		dxfer_len = 0;
887		csio->sglist_cnt = 0;
888		scsi_status = 0;
889	}
890	if ((io->io_hdr.flags & CTL_FLAG_STATUS_QUEUED) &&
891	    (cmd_info->flags & CTLFE_CMD_PIECEWISE) == 0 &&
892	    ((io->io_hdr.flags & CTL_FLAG_DMA_QUEUED) == 0 ||
893	     io->io_hdr.status == CTL_SUCCESS)) {
894		flags |= CAM_SEND_STATUS;
895		scsi_status = io->scsiio.scsi_status;
896		csio->sense_len = io->scsiio.sense_len;
897#ifdef CTLFEDEBUG
898		printf("%s: tag %04x status %x\n", __func__,
899		       atio->tag_id, io->io_hdr.status);
900#endif
901		if (csio->sense_len != 0) {
902			csio->sense_data = io->scsiio.sense_data;
903			flags |= CAM_SEND_SENSE;
904		} else if (scsi_status == SCSI_STATUS_CHECK_COND) {
905			xpt_print(periph->path, "%s: check condition "
906				  "with no sense\n", __func__);
907		}
908	}
909
910#ifdef CTLFEDEBUG
911	printf("%s: %s: tag %04x flags %x ptr %p len %u\n", __func__,
912	       (flags & CAM_SEND_STATUS) ? "done" : "datamove",
913	       atio->tag_id, flags, data_ptr, dxfer_len);
914#endif
915
916	/*
917	 * Valid combinations:
918	 *  - CAM_SEND_STATUS, CAM_DATA_SG = 0, dxfer_len = 0,
919	 *    sglist_cnt = 0
920	 *  - CAM_SEND_STATUS = 0, CAM_DATA_SG = 0, dxfer_len != 0,
921	 *    sglist_cnt = 0
922	 *  - CAM_SEND_STATUS = 0, CAM_DATA_SG, dxfer_len != 0,
923	 *    sglist_cnt != 0
924	 */
925#ifdef CTLFEDEBUG
926	if (((flags & CAM_SEND_STATUS)
927	  && (((flags & CAM_DATA_SG) != 0)
928	   || (dxfer_len != 0)
929	   || (csio->sglist_cnt != 0)))
930	 || (((flags & CAM_SEND_STATUS) == 0)
931	  && (dxfer_len == 0))
932	 || ((flags & CAM_DATA_SG)
933	  && (csio->sglist_cnt == 0))
934	 || (((flags & CAM_DATA_SG) == 0)
935	  && (csio->sglist_cnt != 0))) {
936		printf("%s: tag %04x cdb %02x flags %#x dxfer_len "
937		       "%d sg %u\n", __func__, atio->tag_id,
938		       atio->cdb_io.cdb_bytes[0], flags, dxfer_len,
939		       csio->sglist_cnt);
940		printf("%s: tag %04x io status %#x\n", __func__,
941		       atio->tag_id, io->io_hdr.status);
942	}
943#endif
944	cam_fill_ctio(csio,
945		      /*retries*/ 2,
946		      ctlfedone,
947		      flags,
948		      (flags & CAM_TAG_ACTION_VALID) ? MSG_SIMPLE_Q_TAG : 0,
949		      atio->tag_id,
950		      atio->init_id,
951		      scsi_status,
952		      /*data_ptr*/ data_ptr,
953		      /*dxfer_len*/ dxfer_len,
954		      /*timeout*/ 5 * 1000);
955	start_ccb->ccb_h.flags |= CAM_UNLOCKED;
956	start_ccb->ccb_h.ccb_atio = atio;
957	if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
958		io->io_hdr.flags |= CTL_FLAG_DMA_INPROG;
959	io->io_hdr.flags &= ~(CTL_FLAG_DMA_QUEUED | CTL_FLAG_STATUS_QUEUED);
960
961	softc->ctios_sent++;
962
963	cam_periph_unlock(periph);
964	xpt_action(start_ccb);
965	cam_periph_lock(periph);
966
967	/*
968	 * If we still have work to do, ask for another CCB.
969	 */
970	if (!TAILQ_EMPTY(&softc->work_queue))
971		xpt_schedule(periph, /*priority*/ 1);
972}
973
974static void
975ctlfe_free_ccb(struct cam_periph *periph, union ccb *ccb)
976{
977	struct ctlfe_lun_softc *softc;
978	union ctl_io *io;
979	struct ctlfe_cmd_info *cmd_info;
980
981	softc = (struct ctlfe_lun_softc *)periph->softc;
982	io = ccb->ccb_h.io_ptr;
983
984	switch (ccb->ccb_h.func_code) {
985	case XPT_ACCEPT_TARGET_IO:
986		softc->atios_freed++;
987		cmd_info = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND2].ptr;
988		free(cmd_info, M_CTLFE);
989		break;
990	case XPT_IMMEDIATE_NOTIFY:
991	case XPT_NOTIFY_ACKNOWLEDGE:
992		softc->inots_freed++;
993		break;
994	default:
995		break;
996	}
997
998	ctl_free_io(io);
999	free(ccb, M_CTLFE);
1000
1001	KASSERT(softc->atios_freed <= softc->atios_alloced, ("%s: "
1002		"atios_freed %ju > atios_alloced %ju", __func__,
1003		softc->atios_freed, softc->atios_alloced));
1004	KASSERT(softc->inots_freed <= softc->inots_alloced, ("%s: "
1005		"inots_freed %ju > inots_alloced %ju", __func__,
1006		softc->inots_freed, softc->inots_alloced));
1007
1008	/*
1009	 * If we have received all of our CCBs, we can release our
1010	 * reference on the peripheral driver.  It will probably go away
1011	 * now.
1012	 */
1013	if ((softc->atios_freed == softc->atios_alloced)
1014	 && (softc->inots_freed == softc->inots_alloced)) {
1015		cam_periph_release_locked(periph);
1016	}
1017}
1018
1019static int
1020ctlfe_adjust_cdb(struct ccb_accept_tio *atio, uint32_t offset)
1021{
1022	uint64_t lba;
1023	uint32_t num_blocks, nbc;
1024	uint8_t *cmdbyt = (atio->ccb_h.flags & CAM_CDB_POINTER)?
1025	    atio->cdb_io.cdb_ptr : atio->cdb_io.cdb_bytes;
1026
1027	nbc = offset >> 9;	/* ASSUMING 512 BYTE BLOCKS */
1028
1029	switch (cmdbyt[0]) {
1030	case READ_6:
1031	case WRITE_6:
1032	{
1033		struct scsi_rw_6 *cdb = (struct scsi_rw_6 *)cmdbyt;
1034		lba = scsi_3btoul(cdb->addr);
1035		lba &= 0x1fffff;
1036		num_blocks = cdb->length;
1037		if (num_blocks == 0)
1038			num_blocks = 256;
1039		lba += nbc;
1040		num_blocks -= nbc;
1041		scsi_ulto3b(lba, cdb->addr);
1042		cdb->length = num_blocks;
1043		break;
1044	}
1045	case READ_10:
1046	case WRITE_10:
1047	{
1048		struct scsi_rw_10 *cdb = (struct scsi_rw_10 *)cmdbyt;
1049		lba = scsi_4btoul(cdb->addr);
1050		num_blocks = scsi_2btoul(cdb->length);
1051		lba += nbc;
1052		num_blocks -= nbc;
1053		scsi_ulto4b(lba, cdb->addr);
1054		scsi_ulto2b(num_blocks, cdb->length);
1055		break;
1056	}
1057	case READ_12:
1058	case WRITE_12:
1059	{
1060		struct scsi_rw_12 *cdb = (struct scsi_rw_12 *)cmdbyt;
1061		lba = scsi_4btoul(cdb->addr);
1062		num_blocks = scsi_4btoul(cdb->length);
1063		lba += nbc;
1064		num_blocks -= nbc;
1065		scsi_ulto4b(lba, cdb->addr);
1066		scsi_ulto4b(num_blocks, cdb->length);
1067		break;
1068	}
1069	case READ_16:
1070	case WRITE_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