scsi_ctl.c revision 314740
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 314740 2017-03-06 06:26:43Z 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	struct mtx *mtx;
1005
1006	if (periph->flags & CAM_PERIPH_INVALID) {
1007		mtx = cam_periph_mtx(periph);
1008		ctlfe_free_ccb(periph, ccb);
1009		if (unlock)
1010			mtx_unlock(mtx);
1011		return;
1012	}
1013	if (unlock)
1014		cam_periph_unlock(periph);
1015
1016	/*
1017	 * For a wildcard attachment, commands can come in with a specific
1018	 * target/lun.  Reset the target and LUN fields back to the wildcard
1019	 * values before we send them back down to the SIM.
1020	 */
1021	softc = (struct ctlfe_lun_softc *)periph->softc;
1022	if (softc->flags & CTLFE_LUN_WILDCARD) {
1023		ccb->ccb_h.target_id = CAM_TARGET_WILDCARD;
1024		ccb->ccb_h.target_lun = CAM_LUN_WILDCARD;
1025	}
1026
1027	xpt_action(ccb);
1028}
1029
1030static int
1031ctlfe_adjust_cdb(struct ccb_accept_tio *atio, uint32_t offset)
1032{
1033	uint64_t lba;
1034	uint32_t num_blocks, nbc;
1035	uint8_t *cmdbyt = atio_cdb_ptr(atio);
1036
1037	nbc = offset >> 9;	/* ASSUMING 512 BYTE BLOCKS */
1038
1039	switch (cmdbyt[0]) {
1040	case READ_6:
1041	case WRITE_6:
1042	{
1043		struct scsi_rw_6 *cdb = (struct scsi_rw_6 *)cmdbyt;
1044		lba = scsi_3btoul(cdb->addr);
1045		lba &= 0x1fffff;
1046		num_blocks = cdb->length;
1047		if (num_blocks == 0)
1048			num_blocks = 256;
1049		lba += nbc;
1050		num_blocks -= nbc;
1051		scsi_ulto3b(lba, cdb->addr);
1052		cdb->length = num_blocks;
1053		break;
1054	}
1055	case READ_10:
1056	case WRITE_10:
1057	{
1058		struct scsi_rw_10 *cdb = (struct scsi_rw_10 *)cmdbyt;
1059		lba = scsi_4btoul(cdb->addr);
1060		num_blocks = scsi_2btoul(cdb->length);
1061		lba += nbc;
1062		num_blocks -= nbc;
1063		scsi_ulto4b(lba, cdb->addr);
1064		scsi_ulto2b(num_blocks, cdb->length);
1065		break;
1066	}
1067	case READ_12:
1068	case WRITE_12:
1069	{
1070		struct scsi_rw_12 *cdb = (struct scsi_rw_12 *)cmdbyt;
1071		lba = scsi_4btoul(cdb->addr);
1072		num_blocks = scsi_4btoul(cdb->length);
1073		lba += nbc;
1074		num_blocks -= nbc;
1075		scsi_ulto4b(lba, cdb->addr);
1076		scsi_ulto4b(num_blocks, cdb->length);
1077		break;
1078	}
1079	case READ_16:
1080	case WRITE_16:
1081	{
1082		struct scsi_rw_16 *cdb = (struct scsi_rw_16 *)cmdbyt;
1083		lba = scsi_8btou64(cdb->addr);
1084		num_blocks = scsi_4btoul(cdb->length);
1085		lba += nbc;
1086		num_blocks -= nbc;
1087		scsi_u64to8b(lba, cdb->addr);
1088		scsi_ulto4b(num_blocks, cdb->length);
1089		break;
1090	}
1091	default:
1092		return -1;
1093	}
1094	return (0);
1095}
1096
1097static void
1098ctlfedone(struct cam_periph *periph, union ccb *done_ccb)
1099{
1100	struct ctlfe_lun_softc *softc;
1101	struct ctlfe_softc *bus_softc;
1102	struct ctlfe_cmd_info *cmd_info;
1103	struct ccb_accept_tio *atio = NULL;
1104	union ctl_io *io = NULL;
1105	struct mtx *mtx;
1106	cam_status status;
1107
1108	KASSERT((done_ccb->ccb_h.flags & CAM_UNLOCKED) != 0,
1109	    ("CCB in ctlfedone() without CAM_UNLOCKED flag"));
1110#ifdef CTLFE_DEBUG
1111	printf("%s: entered, func_code = %#x\n", __func__,
1112	       done_ccb->ccb_h.func_code);
1113#endif
1114
1115	/*
1116	 * At this point CTL has no known use case for device queue freezes.
1117	 * In case some SIM think different -- drop its freeze right here.
1118	 */
1119	if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
1120		cam_release_devq(periph->path,
1121				 /*relsim_flags*/0,
1122				 /*reduction*/0,
1123				 /*timeout*/0,
1124				 /*getcount_only*/0);
1125		done_ccb->ccb_h.status &= ~CAM_DEV_QFRZN;
1126	}
1127
1128	softc = (struct ctlfe_lun_softc *)periph->softc;
1129	bus_softc = softc->parent_softc;
1130	mtx = cam_periph_mtx(periph);
1131	mtx_lock(mtx);
1132
1133	switch (done_ccb->ccb_h.func_code) {
1134	case XPT_ACCEPT_TARGET_IO: {
1135
1136		atio = &done_ccb->atio;
1137		status = atio->ccb_h.status & CAM_STATUS_MASK;
1138		if (status != CAM_CDB_RECVD) {
1139			ctlfe_free_ccb(periph, done_ccb);
1140			goto out;
1141		}
1142
1143 resubmit:
1144		/*
1145		 * Allocate a ctl_io, pass it to CTL, and wait for the
1146		 * datamove or done.
1147		 */
1148		mtx_unlock(mtx);
1149		io = done_ccb->ccb_h.io_ptr;
1150		cmd_info = PRIV_INFO(io);
1151		ctl_zero_io(io);
1152
1153		/* Save pointers on both sides */
1154		PRIV_CCB(io) = done_ccb;
1155		PRIV_INFO(io) = cmd_info;
1156		done_ccb->ccb_h.io_ptr = io;
1157
1158		/*
1159		 * Only SCSI I/O comes down this path, resets, etc. come
1160		 * down the immediate notify path below.
1161		 */
1162		io->io_hdr.io_type = CTL_IO_SCSI;
1163		io->io_hdr.nexus.initid = atio->init_id;
1164		io->io_hdr.nexus.targ_port = bus_softc->port.targ_port;
1165		if (bus_softc->hba_misc & PIM_EXTLUNS) {
1166			io->io_hdr.nexus.targ_lun = ctl_decode_lun(
1167			    CAM_EXTLUN_BYTE_SWIZZLE(atio->ccb_h.target_lun));
1168		} else {
1169			io->io_hdr.nexus.targ_lun = atio->ccb_h.target_lun;
1170		}
1171		io->scsiio.tag_num = atio->tag_id;
1172		switch (atio->tag_action) {
1173		case CAM_TAG_ACTION_NONE:
1174			io->scsiio.tag_type = CTL_TAG_UNTAGGED;
1175			break;
1176		case MSG_SIMPLE_TASK:
1177			io->scsiio.tag_type = CTL_TAG_SIMPLE;
1178			break;
1179		case MSG_HEAD_OF_QUEUE_TASK:
1180        		io->scsiio.tag_type = CTL_TAG_HEAD_OF_QUEUE;
1181			break;
1182		case MSG_ORDERED_TASK:
1183        		io->scsiio.tag_type = CTL_TAG_ORDERED;
1184			break;
1185		case MSG_ACA_TASK:
1186			io->scsiio.tag_type = CTL_TAG_ACA;
1187			break;
1188		default:
1189			io->scsiio.tag_type = CTL_TAG_UNTAGGED;
1190			printf("%s: unhandled tag type %#x!!\n", __func__,
1191			       atio->tag_action);
1192			break;
1193		}
1194		if (atio->cdb_len > sizeof(io->scsiio.cdb)) {
1195			printf("%s: WARNING: CDB len %d > ctl_io space %zd\n",
1196			       __func__, atio->cdb_len, sizeof(io->scsiio.cdb));
1197		}
1198		io->scsiio.cdb_len = min(atio->cdb_len, sizeof(io->scsiio.cdb));
1199		bcopy(atio_cdb_ptr(atio), io->scsiio.cdb, 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		/*
1241		 * If we have an SRR and we're still sending data, we
1242		 * should be able to adjust offsets and cycle again.
1243		 * It is possible only if offset is from this datamove.
1244		 */
1245		if (srr && (io->io_hdr.flags & CTL_FLAG_DMA_INPROG) &&
1246		    srr_off >= io->scsiio.kern_rel_offset &&
1247		    srr_off < io->scsiio.kern_rel_offset +
1248		     io->scsiio.kern_data_len) {
1249			io->scsiio.kern_data_resid =
1250			    io->scsiio.kern_rel_offset +
1251			    io->scsiio.kern_data_len - srr_off;
1252			io->scsiio.ext_data_filled = srr_off;
1253			io->scsiio.io_hdr.status = CTL_STATUS_NONE;
1254			io->io_hdr.flags |= CTL_FLAG_DMA_QUEUED;
1255			softc->ccbs_freed++;
1256			xpt_release_ccb(done_ccb);
1257			TAILQ_INSERT_HEAD(&softc->work_queue, &atio->ccb_h,
1258					  periph_links.tqe);
1259			xpt_schedule(periph, /*priority*/ 1);
1260			break;
1261		}
1262
1263		/*
1264		 * If status was being sent, the back end data is now history.
1265		 * Hack it up and resubmit a new command with the CDB adjusted.
1266		 * If the SIM does the right thing, all of the resid math
1267		 * should work.
1268		 */
1269		if (srr && (io->io_hdr.flags & CTL_FLAG_DMA_INPROG) == 0) {
1270			softc->ccbs_freed++;
1271			xpt_release_ccb(done_ccb);
1272			if (ctlfe_adjust_cdb(atio, srr_off) == 0) {
1273				done_ccb = (union ccb *)atio;
1274				goto resubmit;
1275			}
1276			/*
1277			 * Fall through to doom....
1278			 */
1279		}
1280
1281		if ((done_ccb->ccb_h.flags & CAM_SEND_STATUS) &&
1282		    (done_ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP)
1283			io->io_hdr.flags |= CTL_FLAG_STATUS_SENT;
1284
1285		/*
1286		 * If we were sending status back to the initiator, free up
1287		 * resources.  If we were doing a datamove, call the
1288		 * datamove done routine.
1289		 */
1290		if ((io->io_hdr.flags & CTL_FLAG_DMA_INPROG) == 0) {
1291			softc->ccbs_freed++;
1292			xpt_release_ccb(done_ccb);
1293			ctlfe_requeue_ccb(periph, (union ccb *)atio,
1294			    /* unlock */1);
1295			return;
1296		} else {
1297			struct ctlfe_cmd_info *cmd_info;
1298			struct ccb_scsiio *csio;
1299
1300			csio = &done_ccb->csio;
1301			cmd_info = PRIV_INFO(io);
1302
1303			io->io_hdr.flags &= ~CTL_FLAG_DMA_INPROG;
1304
1305			/*
1306			 * Translate CAM status to CTL status.  Success
1307			 * does not change the overall, ctl_io status.  In
1308			 * that case we just set port_status to 0.  If we
1309			 * have a failure, though, set a data phase error
1310			 * for the overall ctl_io.
1311			 */
1312			switch (done_ccb->ccb_h.status & CAM_STATUS_MASK) {
1313			case CAM_REQ_CMP:
1314				io->scsiio.kern_data_resid -= csio->dxfer_len;
1315				io->io_hdr.port_status = 0;
1316				break;
1317			default:
1318				/*
1319				 * XXX KDM we probably need to figure out a
1320				 * standard set of errors that the SIM
1321				 * drivers should return in the event of a
1322				 * data transfer failure.  A data phase
1323				 * error will at least point the user to a
1324				 * data transfer error of some sort.
1325				 * Hopefully the SIM printed out some
1326				 * additional information to give the user
1327				 * a clue what happened.
1328				 */
1329				io->io_hdr.port_status = 0xbad1;
1330				ctl_set_data_phase_error(&io->scsiio);
1331				/*
1332				 * XXX KDM figure out residual.
1333				 */
1334				break;
1335			}
1336			/*
1337			 * If we had to break this S/G list into multiple
1338			 * pieces, figure out where we are in the list, and
1339			 * continue sending pieces if necessary.
1340			 */
1341			if ((cmd_info->flags & CTLFE_CMD_PIECEWISE)
1342			 && (io->io_hdr.port_status == 0)) {
1343				ccb_flags flags;
1344				uint8_t *data_ptr;
1345				uint32_t dxfer_len;
1346
1347				flags = atio->ccb_h.flags &
1348					(CAM_DIS_DISCONNECT|
1349					 CAM_TAG_ACTION_VALID);
1350
1351				ctlfedata(softc, io, &flags, &data_ptr,
1352				    &dxfer_len, &csio->sglist_cnt);
1353
1354				if (((flags & CAM_SEND_STATUS) == 0)
1355				 && (dxfer_len == 0)) {
1356					printf("%s: tag %04x no status or "
1357					       "len cdb = %02x\n", __func__,
1358					       atio->tag_id,
1359					       atio_cdb_ptr(atio)[0]);
1360					printf("%s: tag %04x io status %#x\n",
1361					       __func__, atio->tag_id,
1362					       io->io_hdr.status);
1363				}
1364
1365				cam_fill_ctio(csio,
1366					      /*retries*/ 2,
1367					      ctlfedone,
1368					      flags,
1369					      (flags & CAM_TAG_ACTION_VALID) ?
1370					       MSG_SIMPLE_Q_TAG : 0,
1371					      atio->tag_id,
1372					      atio->init_id,
1373					      0,
1374					      /*data_ptr*/ data_ptr,
1375					      /*dxfer_len*/ dxfer_len,
1376					      /*timeout*/ 5 * 1000);
1377
1378				csio->ccb_h.flags |= CAM_UNLOCKED;
1379				csio->resid = 0;
1380				csio->ccb_h.ccb_atio = atio;
1381				io->io_hdr.flags |= CTL_FLAG_DMA_INPROG;
1382				softc->ctios_sent++;
1383				mtx_unlock(mtx);
1384				xpt_action((union ccb *)csio);
1385			} else {
1386				/*
1387				 * Release the CTIO.  The ATIO will be sent back
1388				 * down to the SIM once we send status.
1389				 */
1390				softc->ccbs_freed++;
1391				xpt_release_ccb(done_ccb);
1392				mtx_unlock(mtx);
1393
1394				/* Call the backend move done callback */
1395				io->scsiio.be_move_done(io);
1396			}
1397			return;
1398		}
1399		break;
1400	}
1401	case XPT_IMMEDIATE_NOTIFY: {
1402		union ctl_io *io;
1403		struct ccb_immediate_notify *inot;
1404		int send_ctl_io;
1405
1406		inot = &done_ccb->cin1;
1407		io = done_ccb->ccb_h.io_ptr;
1408		ctl_zero_io(io);
1409
1410		send_ctl_io = 1;
1411
1412		io->io_hdr.io_type = CTL_IO_TASK;
1413		PRIV_CCB(io) = done_ccb;
1414		inot->ccb_h.io_ptr = io;
1415		io->io_hdr.nexus.initid = inot->initiator_id;
1416		io->io_hdr.nexus.targ_port = bus_softc->port.targ_port;
1417		if (bus_softc->hba_misc & PIM_EXTLUNS) {
1418			io->io_hdr.nexus.targ_lun = ctl_decode_lun(
1419			    CAM_EXTLUN_BYTE_SWIZZLE(inot->ccb_h.target_lun));
1420		} else {
1421			io->io_hdr.nexus.targ_lun = inot->ccb_h.target_lun;
1422		}
1423		/* XXX KDM should this be the tag_id? */
1424		io->taskio.tag_num = inot->seq_id;
1425
1426		status = inot->ccb_h.status & CAM_STATUS_MASK;
1427		switch (status) {
1428		case CAM_SCSI_BUS_RESET:
1429			io->taskio.task_action = CTL_TASK_BUS_RESET;
1430			break;
1431		case CAM_BDR_SENT:
1432			io->taskio.task_action = CTL_TASK_TARGET_RESET;
1433			break;
1434		case CAM_MESSAGE_RECV:
1435			switch (inot->arg) {
1436			case MSG_ABORT_TASK_SET:
1437				io->taskio.task_action =
1438				    CTL_TASK_ABORT_TASK_SET;
1439				break;
1440			case MSG_TARGET_RESET:
1441				io->taskio.task_action = CTL_TASK_TARGET_RESET;
1442				break;
1443			case MSG_ABORT_TASK:
1444				io->taskio.task_action = CTL_TASK_ABORT_TASK;
1445				break;
1446			case MSG_LOGICAL_UNIT_RESET:
1447				io->taskio.task_action = CTL_TASK_LUN_RESET;
1448				break;
1449			case MSG_CLEAR_TASK_SET:
1450				io->taskio.task_action =
1451				    CTL_TASK_CLEAR_TASK_SET;
1452				break;
1453			case MSG_CLEAR_ACA:
1454				io->taskio.task_action = CTL_TASK_CLEAR_ACA;
1455				break;
1456			case MSG_QUERY_TASK:
1457				io->taskio.task_action = CTL_TASK_QUERY_TASK;
1458				break;
1459			case MSG_QUERY_TASK_SET:
1460				io->taskio.task_action =
1461				    CTL_TASK_QUERY_TASK_SET;
1462				break;
1463			case MSG_QUERY_ASYNC_EVENT:
1464				io->taskio.task_action =
1465				    CTL_TASK_QUERY_ASYNC_EVENT;
1466				break;
1467			case MSG_NOOP:
1468				send_ctl_io = 0;
1469				break;
1470			default:
1471				xpt_print(periph->path,
1472				    "%s: unsupported INOT message 0x%x\n",
1473				    __func__, inot->arg);
1474				send_ctl_io = 0;
1475				break;
1476			}
1477			break;
1478		default:
1479			xpt_print(periph->path,
1480			    "%s: unsupported INOT status 0x%x\n",
1481			    __func__, status);
1482			/* FALLTHROUGH */
1483		case CAM_REQ_ABORTED:
1484		case CAM_REQ_INVALID:
1485		case CAM_DEV_NOT_THERE:
1486		case CAM_PROVIDE_FAIL:
1487			ctlfe_free_ccb(periph, done_ccb);
1488			goto out;
1489		}
1490		if (send_ctl_io != 0) {
1491			ctl_queue(io);
1492		} else {
1493			done_ccb->ccb_h.status = CAM_REQ_INPROG;
1494			done_ccb->ccb_h.func_code = XPT_NOTIFY_ACKNOWLEDGE;
1495			xpt_action(done_ccb);
1496		}
1497		break;
1498	}
1499	case XPT_NOTIFY_ACKNOWLEDGE:
1500		/* Queue this back down to the SIM as an immediate notify. */
1501		done_ccb->ccb_h.status = CAM_REQ_INPROG;
1502		done_ccb->ccb_h.func_code = XPT_IMMEDIATE_NOTIFY;
1503		ctlfe_requeue_ccb(periph, done_ccb, /* unlock */1);
1504		return;
1505	case XPT_SET_SIM_KNOB:
1506	case XPT_GET_SIM_KNOB:
1507		break;
1508	default:
1509		panic("%s: unexpected CCB type %#x", __func__,
1510		      done_ccb->ccb_h.func_code);
1511		break;
1512	}
1513
1514out:
1515	mtx_unlock(mtx);
1516}
1517
1518static void
1519ctlfe_onoffline(void *arg, int online)
1520{
1521	struct ctlfe_softc *bus_softc;
1522	union ccb *ccb;
1523	cam_status status;
1524	struct cam_path *path;
1525	int set_wwnn;
1526
1527	bus_softc = (struct ctlfe_softc *)arg;
1528
1529	set_wwnn = 0;
1530
1531	status = xpt_create_path(&path, /*periph*/ NULL, bus_softc->path_id,
1532		CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
1533	if (status != CAM_REQ_CMP) {
1534		printf("%s: unable to create path!\n", __func__);
1535		return;
1536	}
1537	ccb = xpt_alloc_ccb();
1538	xpt_setup_ccb(&ccb->ccb_h, path, CAM_PRIORITY_NONE);
1539	ccb->ccb_h.func_code = XPT_GET_SIM_KNOB;
1540	xpt_action(ccb);
1541
1542	/*
1543	 * Copan WWN format:
1544	 *
1545	 * Bits 63-60:	0x5		NAA, IEEE registered name
1546	 * Bits 59-36:	0x000ED5	IEEE Company name assigned to Copan
1547	 * Bits 35-12:			Copan SSN (Sequential Serial Number)
1548	 * Bits 11-8:			Type of port:
1549	 *					1 == N-Port
1550	 *					2 == F-Port
1551	 *					3 == NL-Port
1552	 * Bits 7-0:			0 == Node Name, >0 == Port Number
1553	 */
1554	if (online != 0) {
1555		if ((ccb->knob.xport_specific.valid & KNOB_VALID_ADDRESS) != 0){
1556#ifdef RANDOM_WWNN
1557			uint64_t random_bits;
1558#endif
1559
1560			printf("%s: %s current WWNN %#jx\n", __func__,
1561			       bus_softc->port_name,
1562			       ccb->knob.xport_specific.fc.wwnn);
1563			printf("%s: %s current WWPN %#jx\n", __func__,
1564			       bus_softc->port_name,
1565			       ccb->knob.xport_specific.fc.wwpn);
1566
1567#ifdef RANDOM_WWNN
1568			arc4rand(&random_bits, sizeof(random_bits), 0);
1569#endif
1570
1571			/*
1572			 * XXX KDM this is a bit of a kludge for now.  We
1573			 * take the current WWNN/WWPN from the card, and
1574			 * replace the company identifier and the NL-Port
1575			 * indicator and the port number (for the WWPN).
1576			 * This should be replaced later with ddb_GetWWNN,
1577			 * or possibly a more centralized scheme.  (It
1578			 * would be nice to have the WWNN/WWPN for each
1579			 * port stored in the ctl_port structure.)
1580			 */
1581#ifdef RANDOM_WWNN
1582			ccb->knob.xport_specific.fc.wwnn =
1583				(random_bits &
1584				0x0000000fffffff00ULL) |
1585				/* Company ID */ 0x5000ED5000000000ULL |
1586				/* NL-Port */    0x0300;
1587			ccb->knob.xport_specific.fc.wwpn =
1588				(random_bits &
1589				0x0000000fffffff00ULL) |
1590				/* Company ID */ 0x5000ED5000000000ULL |
1591				/* NL-Port */    0x3000 |
1592				/* Port Num */ (bus_softc->port.targ_port & 0xff);
1593
1594			/*
1595			 * This is a bit of an API break/reversal, but if
1596			 * we're doing the random WWNN that's a little
1597			 * different anyway.  So record what we're actually
1598			 * using with the frontend code so it's reported
1599			 * accurately.
1600			 */
1601			ctl_port_set_wwns(&bus_softc->port,
1602			    true, ccb->knob.xport_specific.fc.wwnn,
1603			    true, ccb->knob.xport_specific.fc.wwpn);
1604			set_wwnn = 1;
1605#else /* RANDOM_WWNN */
1606			/*
1607			 * If the user has specified a WWNN/WWPN, send them
1608			 * down to the SIM.  Otherwise, record what the SIM
1609			 * has reported.
1610			 */
1611			if (bus_softc->port.wwnn != 0 && bus_softc->port.wwnn
1612			    != ccb->knob.xport_specific.fc.wwnn) {
1613				ccb->knob.xport_specific.fc.wwnn =
1614				    bus_softc->port.wwnn;
1615				set_wwnn = 1;
1616			} else {
1617				ctl_port_set_wwns(&bus_softc->port,
1618				    true, ccb->knob.xport_specific.fc.wwnn,
1619				    false, 0);
1620			}
1621			if (bus_softc->port.wwpn != 0 && bus_softc->port.wwpn
1622			     != ccb->knob.xport_specific.fc.wwpn) {
1623				ccb->knob.xport_specific.fc.wwpn =
1624				    bus_softc->port.wwpn;
1625				set_wwnn = 1;
1626			} else {
1627				ctl_port_set_wwns(&bus_softc->port,
1628				    false, 0,
1629				    true, ccb->knob.xport_specific.fc.wwpn);
1630			}
1631#endif /* RANDOM_WWNN */
1632
1633
1634			if (set_wwnn != 0) {
1635				printf("%s: %s new WWNN %#jx\n", __func__,
1636				       bus_softc->port_name,
1637				ccb->knob.xport_specific.fc.wwnn);
1638				printf("%s: %s new WWPN %#jx\n", __func__,
1639				       bus_softc->port_name,
1640				       ccb->knob.xport_specific.fc.wwpn);
1641			}
1642		} else {
1643			printf("%s: %s has no valid WWNN/WWPN\n", __func__,
1644			       bus_softc->port_name);
1645		}
1646	}
1647	ccb->ccb_h.func_code = XPT_SET_SIM_KNOB;
1648	ccb->knob.xport_specific.valid = KNOB_VALID_ROLE;
1649	if (set_wwnn != 0)
1650		ccb->knob.xport_specific.valid |= KNOB_VALID_ADDRESS;
1651
1652	if (online != 0)
1653		ccb->knob.xport_specific.fc.role |= KNOB_ROLE_TARGET;
1654	else
1655		ccb->knob.xport_specific.fc.role &= ~KNOB_ROLE_TARGET;
1656
1657	xpt_action(ccb);
1658
1659	if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1660		printf("%s: SIM %s (path id %d) target %s failed with "
1661		       "status %#x\n",
1662		       __func__, bus_softc->port_name, bus_softc->path_id,
1663		       (online != 0) ? "enable" : "disable",
1664		       ccb->ccb_h.status);
1665	} else {
1666		printf("%s: SIM %s (path id %d) target %s succeeded\n",
1667		       __func__, bus_softc->port_name, bus_softc->path_id,
1668		       (online != 0) ? "enable" : "disable");
1669	}
1670
1671	xpt_free_path(path);
1672	xpt_free_ccb(ccb);
1673}
1674
1675static void
1676ctlfe_online(void *arg)
1677{
1678	struct ctlfe_softc *bus_softc;
1679	struct cam_path *path;
1680	cam_status status;
1681	struct ctlfe_lun_softc *lun_softc;
1682	struct cam_periph *periph;
1683
1684	bus_softc = (struct ctlfe_softc *)arg;
1685
1686	/*
1687	 * Create the wildcard LUN before bringing the port online.
1688	 */
1689	status = xpt_create_path(&path, /*periph*/ NULL,
1690				 bus_softc->path_id, CAM_TARGET_WILDCARD,
1691				 CAM_LUN_WILDCARD);
1692	if (status != CAM_REQ_CMP) {
1693		printf("%s: unable to create path for wildcard periph\n",
1694				__func__);
1695		return;
1696	}
1697
1698	lun_softc = malloc(sizeof(*lun_softc), M_CTLFE, M_WAITOK | M_ZERO);
1699
1700	xpt_path_lock(path);
1701	periph = cam_periph_find(path, "ctl");
1702	if (periph != NULL) {
1703		/* We've already got a periph, no need to alloc a new one. */
1704		xpt_path_unlock(path);
1705		xpt_free_path(path);
1706		free(lun_softc, M_CTLFE);
1707		return;
1708	}
1709	lun_softc->parent_softc = bus_softc;
1710	lun_softc->flags |= CTLFE_LUN_WILDCARD;
1711
1712	status = cam_periph_alloc(ctlferegister,
1713				  ctlfeoninvalidate,
1714				  ctlfecleanup,
1715				  ctlfestart,
1716				  "ctl",
1717				  CAM_PERIPH_BIO,
1718				  path,
1719				  ctlfeasync,
1720				  0,
1721				  lun_softc);
1722
1723	if ((status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1724		const struct cam_status_entry *entry;
1725
1726		entry = cam_fetch_status_entry(status);
1727		printf("%s: CAM error %s (%#x) returned from "
1728		       "cam_periph_alloc()\n", __func__, (entry != NULL) ?
1729		       entry->status_text : "Unknown", status);
1730		free(lun_softc, M_CTLFE);
1731	}
1732
1733	xpt_path_unlock(path);
1734	ctlfe_onoffline(arg, /*online*/ 1);
1735	xpt_free_path(path);
1736}
1737
1738static void
1739ctlfe_offline(void *arg)
1740{
1741	struct ctlfe_softc *bus_softc;
1742	struct cam_path *path;
1743	cam_status status;
1744	struct cam_periph *periph;
1745
1746	bus_softc = (struct ctlfe_softc *)arg;
1747
1748	ctlfe_onoffline(arg, /*online*/ 0);
1749
1750	/*
1751	 * Disable the wildcard LUN for this port now that we have taken
1752	 * the port offline.
1753	 */
1754	status = xpt_create_path(&path, /*periph*/ NULL,
1755				 bus_softc->path_id, CAM_TARGET_WILDCARD,
1756				 CAM_LUN_WILDCARD);
1757	if (status != CAM_REQ_CMP) {
1758		printf("%s: unable to create path for wildcard periph\n",
1759		       __func__);
1760		return;
1761	}
1762	xpt_path_lock(path);
1763	if ((periph = cam_periph_find(path, "ctl")) != NULL)
1764		cam_periph_invalidate(periph);
1765	xpt_path_unlock(path);
1766	xpt_free_path(path);
1767}
1768
1769/*
1770 * This will get called to enable a LUN on every bus that is attached to
1771 * CTL.  So we only need to create a path/periph for this particular bus.
1772 */
1773static int
1774ctlfe_lun_enable(void *arg, int lun_id)
1775{
1776	struct ctlfe_softc *bus_softc;
1777	struct ctlfe_lun_softc *softc;
1778	struct cam_path *path;
1779	struct cam_periph *periph;
1780	cam_status status;
1781
1782	bus_softc = (struct ctlfe_softc *)arg;
1783	if (bus_softc->hba_misc & PIM_EXTLUNS)
1784		lun_id = CAM_EXTLUN_BYTE_SWIZZLE(ctl_encode_lun(lun_id));
1785
1786	status = xpt_create_path(&path, /*periph*/ NULL,
1787	    bus_softc->path_id, bus_softc->target_id, lun_id);
1788	/* XXX KDM need some way to return status to CTL here? */
1789	if (status != CAM_REQ_CMP) {
1790		printf("%s: could not create path, status %#x\n", __func__,
1791		       status);
1792		return (1);
1793	}
1794
1795	softc = malloc(sizeof(*softc), M_CTLFE, M_WAITOK | M_ZERO);
1796	xpt_path_lock(path);
1797	periph = cam_periph_find(path, "ctl");
1798	if (periph != NULL) {
1799		/* We've already got a periph, no need to alloc a new one. */
1800		xpt_path_unlock(path);
1801		xpt_free_path(path);
1802		free(softc, M_CTLFE);
1803		return (0);
1804	}
1805	softc->parent_softc = bus_softc;
1806
1807	status = cam_periph_alloc(ctlferegister,
1808				  ctlfeoninvalidate,
1809				  ctlfecleanup,
1810				  ctlfestart,
1811				  "ctl",
1812				  CAM_PERIPH_BIO,
1813				  path,
1814				  ctlfeasync,
1815				  0,
1816				  softc);
1817
1818	if ((status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1819		const struct cam_status_entry *entry;
1820
1821		entry = cam_fetch_status_entry(status);
1822		printf("%s: CAM error %s (%#x) returned from "
1823		       "cam_periph_alloc()\n", __func__, (entry != NULL) ?
1824		       entry->status_text : "Unknown", status);
1825		free(softc, M_CTLFE);
1826	}
1827
1828	xpt_path_unlock(path);
1829	xpt_free_path(path);
1830	return (0);
1831}
1832
1833/*
1834 * This will get called when the user removes a LUN to disable that LUN
1835 * on every bus that is attached to CTL.
1836 */
1837static int
1838ctlfe_lun_disable(void *arg, int lun_id)
1839{
1840	struct ctlfe_softc *softc;
1841	struct ctlfe_lun_softc *lun_softc;
1842
1843	softc = (struct ctlfe_softc *)arg;
1844	if (softc->hba_misc & PIM_EXTLUNS)
1845		lun_id = CAM_EXTLUN_BYTE_SWIZZLE(ctl_encode_lun(lun_id));
1846
1847	mtx_lock(&softc->lun_softc_mtx);
1848	STAILQ_FOREACH(lun_softc, &softc->lun_softc_list, links) {
1849		struct cam_path *path;
1850
1851		path = lun_softc->periph->path;
1852
1853		if ((xpt_path_target_id(path) == softc->target_id)
1854		 && (xpt_path_lun_id(path) == lun_id)) {
1855			break;
1856		}
1857	}
1858	if (lun_softc == NULL) {
1859		mtx_unlock(&softc->lun_softc_mtx);
1860		printf("%s: can't find lun %d\n", __func__, lun_id);
1861		return (1);
1862	}
1863	cam_periph_acquire(lun_softc->periph);
1864	mtx_unlock(&softc->lun_softc_mtx);
1865
1866	cam_periph_lock(lun_softc->periph);
1867	cam_periph_invalidate(lun_softc->periph);
1868	cam_periph_unlock(lun_softc->periph);
1869	cam_periph_release(lun_softc->periph);
1870	return (0);
1871}
1872
1873static void
1874ctlfe_dump_sim(struct cam_sim *sim)
1875{
1876
1877	printf("%s%d: max tagged openings: %d, max dev openings: %d\n",
1878	       sim->sim_name, sim->unit_number,
1879	       sim->max_tagged_dev_openings, sim->max_dev_openings);
1880}
1881
1882/*
1883 * Assumes that the SIM lock is held.
1884 */
1885static void
1886ctlfe_dump_queue(struct ctlfe_lun_softc *softc)
1887{
1888	struct ccb_hdr *hdr;
1889	struct cam_periph *periph;
1890	int num_items;
1891
1892	periph = softc->periph;
1893	num_items = 0;
1894
1895	TAILQ_FOREACH(hdr, &softc->work_queue, periph_links.tqe) {
1896		union ctl_io *io = hdr->io_ptr;
1897
1898		num_items++;
1899
1900		/*
1901		 * Only regular SCSI I/O is put on the work
1902		 * queue, so we can print sense here.  There may be no
1903		 * sense if it's no the queue for a DMA, but this serves to
1904		 * print out the CCB as well.
1905		 *
1906		 * XXX KDM switch this over to scsi_sense_print() when
1907		 * CTL is merged in with CAM.
1908		 */
1909		ctl_io_error_print(io, NULL);
1910
1911		/*
1912		 * Print DMA status if we are DMA_QUEUED.
1913		 */
1914		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED) {
1915			xpt_print(periph->path,
1916			    "Total %u, Current %u, Resid %u\n",
1917			    io->scsiio.kern_total_len,
1918			    io->scsiio.kern_data_len,
1919			    io->scsiio.kern_data_resid);
1920		}
1921	}
1922
1923	xpt_print(periph->path, "%d requests total waiting for CCBs\n",
1924		  num_items);
1925	xpt_print(periph->path, "%ju CCBs outstanding (%ju allocated, %ju "
1926		  "freed)\n", (uintmax_t)(softc->ccbs_alloced -
1927		  softc->ccbs_freed), (uintmax_t)softc->ccbs_alloced,
1928		  (uintmax_t)softc->ccbs_freed);
1929	xpt_print(periph->path, "%ju CTIOs outstanding (%ju sent, %ju "
1930		  "returned\n", (uintmax_t)(softc->ctios_sent -
1931		  softc->ctios_returned), softc->ctios_sent,
1932		  softc->ctios_returned);
1933}
1934
1935/*
1936 * Datamove/done routine called by CTL.  Put ourselves on the queue to
1937 * receive a CCB from CAM so we can queue the continue I/O request down
1938 * to the adapter.
1939 */
1940static void
1941ctlfe_datamove(union ctl_io *io)
1942{
1943	union ccb *ccb;
1944	struct cam_periph *periph;
1945	struct ctlfe_lun_softc *softc;
1946
1947	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
1948	    ("Unexpected io_type (%d) in ctlfe_datamove", io->io_hdr.io_type));
1949
1950	io->scsiio.ext_data_filled = 0;
1951	ccb = PRIV_CCB(io);
1952	periph = xpt_path_periph(ccb->ccb_h.path);
1953	cam_periph_lock(periph);
1954	softc = (struct ctlfe_lun_softc *)periph->softc;
1955	io->io_hdr.flags |= CTL_FLAG_DMA_QUEUED;
1956	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE)
1957		io->io_hdr.flags |= CTL_FLAG_STATUS_QUEUED;
1958	TAILQ_INSERT_TAIL(&softc->work_queue, &ccb->ccb_h,
1959			  periph_links.tqe);
1960	xpt_schedule(periph, /*priority*/ 1);
1961	cam_periph_unlock(periph);
1962}
1963
1964static void
1965ctlfe_done(union ctl_io *io)
1966{
1967	union ccb *ccb;
1968	struct cam_periph *periph;
1969	struct ctlfe_lun_softc *softc;
1970
1971	ccb = PRIV_CCB(io);
1972	periph = xpt_path_periph(ccb->ccb_h.path);
1973	cam_periph_lock(periph);
1974	softc = (struct ctlfe_lun_softc *)periph->softc;
1975
1976	if (io->io_hdr.io_type == CTL_IO_TASK) {
1977		/*
1978		 * Send the notify acknowledge down to the SIM, to let it
1979		 * know we processed the task management command.
1980		 */
1981		ccb->ccb_h.status = CAM_REQ_INPROG;
1982		ccb->ccb_h.func_code = XPT_NOTIFY_ACKNOWLEDGE;
1983		switch (io->taskio.task_status) {
1984		case CTL_TASK_FUNCTION_COMPLETE:
1985			ccb->cna2.arg = CAM_RSP_TMF_COMPLETE;
1986			break;
1987		case CTL_TASK_FUNCTION_SUCCEEDED:
1988			ccb->cna2.arg = CAM_RSP_TMF_SUCCEEDED;
1989			ccb->ccb_h.flags |= CAM_SEND_STATUS;
1990			break;
1991		case CTL_TASK_FUNCTION_REJECTED:
1992			ccb->cna2.arg = CAM_RSP_TMF_REJECTED;
1993			ccb->ccb_h.flags |= CAM_SEND_STATUS;
1994			break;
1995		case CTL_TASK_LUN_DOES_NOT_EXIST:
1996			ccb->cna2.arg = CAM_RSP_TMF_INCORRECT_LUN;
1997			ccb->ccb_h.flags |= CAM_SEND_STATUS;
1998			break;
1999		case CTL_TASK_FUNCTION_NOT_SUPPORTED:
2000			ccb->cna2.arg = CAM_RSP_TMF_FAILED;
2001			ccb->ccb_h.flags |= CAM_SEND_STATUS;
2002			break;
2003		}
2004		ccb->cna2.arg |= scsi_3btoul(io->taskio.task_resp) << 8;
2005		xpt_action(ccb);
2006	} else if (io->io_hdr.flags & CTL_FLAG_STATUS_SENT) {
2007		ctlfe_requeue_ccb(periph, ccb, /* unlock */1);
2008		return;
2009	} else {
2010		io->io_hdr.flags |= CTL_FLAG_STATUS_QUEUED;
2011		TAILQ_INSERT_TAIL(&softc->work_queue, &ccb->ccb_h,
2012				  periph_links.tqe);
2013		xpt_schedule(periph, /*priority*/ 1);
2014	}
2015
2016	cam_periph_unlock(periph);
2017}
2018
2019static void
2020ctlfe_dump(void)
2021{
2022	struct ctlfe_softc *bus_softc;
2023	struct ctlfe_lun_softc *lun_softc;
2024
2025	STAILQ_FOREACH(bus_softc, &ctlfe_softc_list, links) {
2026		ctlfe_dump_sim(bus_softc->sim);
2027		STAILQ_FOREACH(lun_softc, &bus_softc->lun_softc_list, links)
2028			ctlfe_dump_queue(lun_softc);
2029	}
2030}
2031