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