scsi_ctl.c revision 314745
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 314745 2017-03-06 06:29:42Z 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			/* Abort ATIO if CTIO sending status has failed. */
1292			if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) !=
1293			    CAM_REQ_CMP) {
1294				done_ccb->ccb_h.func_code = XPT_ABORT;
1295				done_ccb->cab.abort_ccb = (union ccb *)atio;
1296				xpt_action(done_ccb);
1297			}
1298
1299			softc->ccbs_freed++;
1300			xpt_release_ccb(done_ccb);
1301			ctlfe_requeue_ccb(periph, (union ccb *)atio,
1302			    /* unlock */1);
1303			return;
1304		} else {
1305			struct ctlfe_cmd_info *cmd_info;
1306			struct ccb_scsiio *csio;
1307
1308			csio = &done_ccb->csio;
1309			cmd_info = PRIV_INFO(io);
1310
1311			io->io_hdr.flags &= ~CTL_FLAG_DMA_INPROG;
1312
1313			/*
1314			 * Translate CAM status to CTL status.  Success
1315			 * does not change the overall, ctl_io status.  In
1316			 * that case we just set port_status to 0.  If we
1317			 * have a failure, though, set a data phase error
1318			 * for the overall ctl_io.
1319			 */
1320			switch (done_ccb->ccb_h.status & CAM_STATUS_MASK) {
1321			case CAM_REQ_CMP:
1322				io->scsiio.kern_data_resid -= csio->dxfer_len;
1323				io->io_hdr.port_status = 0;
1324				break;
1325			default:
1326				/*
1327				 * XXX KDM we probably need to figure out a
1328				 * standard set of errors that the SIM
1329				 * drivers should return in the event of a
1330				 * data transfer failure.  A data phase
1331				 * error will at least point the user to a
1332				 * data transfer error of some sort.
1333				 * Hopefully the SIM printed out some
1334				 * additional information to give the user
1335				 * a clue what happened.
1336				 */
1337				io->io_hdr.port_status = 0xbad1;
1338				ctl_set_data_phase_error(&io->scsiio);
1339				/*
1340				 * XXX KDM figure out residual.
1341				 */
1342				break;
1343			}
1344			/*
1345			 * If we had to break this S/G list into multiple
1346			 * pieces, figure out where we are in the list, and
1347			 * continue sending pieces if necessary.
1348			 */
1349			if ((cmd_info->flags & CTLFE_CMD_PIECEWISE)
1350			 && (io->io_hdr.port_status == 0)) {
1351				ccb_flags flags;
1352				uint8_t *data_ptr;
1353				uint32_t dxfer_len;
1354
1355				flags = atio->ccb_h.flags &
1356					(CAM_DIS_DISCONNECT|
1357					 CAM_TAG_ACTION_VALID);
1358
1359				ctlfedata(softc, io, &flags, &data_ptr,
1360				    &dxfer_len, &csio->sglist_cnt);
1361
1362				if (((flags & CAM_SEND_STATUS) == 0)
1363				 && (dxfer_len == 0)) {
1364					printf("%s: tag %04x no status or "
1365					       "len cdb = %02x\n", __func__,
1366					       atio->tag_id,
1367					       atio_cdb_ptr(atio)[0]);
1368					printf("%s: tag %04x io status %#x\n",
1369					       __func__, atio->tag_id,
1370					       io->io_hdr.status);
1371				}
1372
1373				cam_fill_ctio(csio,
1374					      /*retries*/ 2,
1375					      ctlfedone,
1376					      flags,
1377					      (flags & CAM_TAG_ACTION_VALID) ?
1378					       MSG_SIMPLE_Q_TAG : 0,
1379					      atio->tag_id,
1380					      atio->init_id,
1381					      0,
1382					      /*data_ptr*/ data_ptr,
1383					      /*dxfer_len*/ dxfer_len,
1384					      /*timeout*/ 5 * 1000);
1385
1386				csio->ccb_h.flags |= CAM_UNLOCKED;
1387				csio->resid = 0;
1388				csio->ccb_h.ccb_atio = atio;
1389				io->io_hdr.flags |= CTL_FLAG_DMA_INPROG;
1390				softc->ctios_sent++;
1391				mtx_unlock(mtx);
1392				xpt_action((union ccb *)csio);
1393			} else {
1394				/*
1395				 * Release the CTIO.  The ATIO will be sent back
1396				 * down to the SIM once we send status.
1397				 */
1398				softc->ccbs_freed++;
1399				xpt_release_ccb(done_ccb);
1400				mtx_unlock(mtx);
1401
1402				/* Call the backend move done callback */
1403				io->scsiio.be_move_done(io);
1404			}
1405			return;
1406		}
1407		break;
1408	}
1409	case XPT_IMMEDIATE_NOTIFY: {
1410		union ctl_io *io;
1411		struct ccb_immediate_notify *inot;
1412		int send_ctl_io;
1413
1414		inot = &done_ccb->cin1;
1415		io = done_ccb->ccb_h.io_ptr;
1416		ctl_zero_io(io);
1417
1418		send_ctl_io = 1;
1419
1420		io->io_hdr.io_type = CTL_IO_TASK;
1421		PRIV_CCB(io) = done_ccb;
1422		inot->ccb_h.io_ptr = io;
1423		io->io_hdr.nexus.initid = inot->initiator_id;
1424		io->io_hdr.nexus.targ_port = bus_softc->port.targ_port;
1425		if (bus_softc->hba_misc & PIM_EXTLUNS) {
1426			io->io_hdr.nexus.targ_lun = ctl_decode_lun(
1427			    CAM_EXTLUN_BYTE_SWIZZLE(inot->ccb_h.target_lun));
1428		} else {
1429			io->io_hdr.nexus.targ_lun = inot->ccb_h.target_lun;
1430		}
1431		/* XXX KDM should this be the tag_id? */
1432		io->taskio.tag_num = inot->seq_id;
1433
1434		status = inot->ccb_h.status & CAM_STATUS_MASK;
1435		switch (status) {
1436		case CAM_SCSI_BUS_RESET:
1437			io->taskio.task_action = CTL_TASK_BUS_RESET;
1438			break;
1439		case CAM_BDR_SENT:
1440			io->taskio.task_action = CTL_TASK_TARGET_RESET;
1441			break;
1442		case CAM_MESSAGE_RECV:
1443			switch (inot->arg) {
1444			case MSG_ABORT_TASK_SET:
1445				io->taskio.task_action =
1446				    CTL_TASK_ABORT_TASK_SET;
1447				break;
1448			case MSG_TARGET_RESET:
1449				io->taskio.task_action = CTL_TASK_TARGET_RESET;
1450				break;
1451			case MSG_ABORT_TASK:
1452				io->taskio.task_action = CTL_TASK_ABORT_TASK;
1453				break;
1454			case MSG_LOGICAL_UNIT_RESET:
1455				io->taskio.task_action = CTL_TASK_LUN_RESET;
1456				break;
1457			case MSG_CLEAR_TASK_SET:
1458				io->taskio.task_action =
1459				    CTL_TASK_CLEAR_TASK_SET;
1460				break;
1461			case MSG_CLEAR_ACA:
1462				io->taskio.task_action = CTL_TASK_CLEAR_ACA;
1463				break;
1464			case MSG_QUERY_TASK:
1465				io->taskio.task_action = CTL_TASK_QUERY_TASK;
1466				break;
1467			case MSG_QUERY_TASK_SET:
1468				io->taskio.task_action =
1469				    CTL_TASK_QUERY_TASK_SET;
1470				break;
1471			case MSG_QUERY_ASYNC_EVENT:
1472				io->taskio.task_action =
1473				    CTL_TASK_QUERY_ASYNC_EVENT;
1474				break;
1475			case MSG_NOOP:
1476				send_ctl_io = 0;
1477				break;
1478			default:
1479				xpt_print(periph->path,
1480				    "%s: unsupported INOT message 0x%x\n",
1481				    __func__, inot->arg);
1482				send_ctl_io = 0;
1483				break;
1484			}
1485			break;
1486		default:
1487			xpt_print(periph->path,
1488			    "%s: unsupported INOT status 0x%x\n",
1489			    __func__, status);
1490			/* FALLTHROUGH */
1491		case CAM_REQ_ABORTED:
1492		case CAM_REQ_INVALID:
1493		case CAM_DEV_NOT_THERE:
1494		case CAM_PROVIDE_FAIL:
1495			ctlfe_free_ccb(periph, done_ccb);
1496			goto out;
1497		}
1498		if (send_ctl_io != 0) {
1499			ctl_queue(io);
1500		} else {
1501			done_ccb->ccb_h.status = CAM_REQ_INPROG;
1502			done_ccb->ccb_h.func_code = XPT_NOTIFY_ACKNOWLEDGE;
1503			xpt_action(done_ccb);
1504		}
1505		break;
1506	}
1507	case XPT_NOTIFY_ACKNOWLEDGE:
1508		/* Queue this back down to the SIM as an immediate notify. */
1509		done_ccb->ccb_h.status = CAM_REQ_INPROG;
1510		done_ccb->ccb_h.func_code = XPT_IMMEDIATE_NOTIFY;
1511		ctlfe_requeue_ccb(periph, done_ccb, /* unlock */1);
1512		return;
1513	case XPT_SET_SIM_KNOB:
1514	case XPT_GET_SIM_KNOB:
1515		break;
1516	default:
1517		panic("%s: unexpected CCB type %#x", __func__,
1518		      done_ccb->ccb_h.func_code);
1519		break;
1520	}
1521
1522out:
1523	mtx_unlock(mtx);
1524}
1525
1526static void
1527ctlfe_onoffline(void *arg, int online)
1528{
1529	struct ctlfe_softc *bus_softc;
1530	union ccb *ccb;
1531	cam_status status;
1532	struct cam_path *path;
1533	int set_wwnn;
1534
1535	bus_softc = (struct ctlfe_softc *)arg;
1536
1537	set_wwnn = 0;
1538
1539	status = xpt_create_path(&path, /*periph*/ NULL, bus_softc->path_id,
1540		CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
1541	if (status != CAM_REQ_CMP) {
1542		printf("%s: unable to create path!\n", __func__);
1543		return;
1544	}
1545	ccb = xpt_alloc_ccb();
1546	xpt_setup_ccb(&ccb->ccb_h, path, CAM_PRIORITY_NONE);
1547	ccb->ccb_h.func_code = XPT_GET_SIM_KNOB;
1548	xpt_action(ccb);
1549
1550	/*
1551	 * Copan WWN format:
1552	 *
1553	 * Bits 63-60:	0x5		NAA, IEEE registered name
1554	 * Bits 59-36:	0x000ED5	IEEE Company name assigned to Copan
1555	 * Bits 35-12:			Copan SSN (Sequential Serial Number)
1556	 * Bits 11-8:			Type of port:
1557	 *					1 == N-Port
1558	 *					2 == F-Port
1559	 *					3 == NL-Port
1560	 * Bits 7-0:			0 == Node Name, >0 == Port Number
1561	 */
1562	if (online != 0) {
1563		if ((ccb->knob.xport_specific.valid & KNOB_VALID_ADDRESS) != 0){
1564#ifdef RANDOM_WWNN
1565			uint64_t random_bits;
1566#endif
1567
1568			printf("%s: %s current WWNN %#jx\n", __func__,
1569			       bus_softc->port_name,
1570			       ccb->knob.xport_specific.fc.wwnn);
1571			printf("%s: %s current WWPN %#jx\n", __func__,
1572			       bus_softc->port_name,
1573			       ccb->knob.xport_specific.fc.wwpn);
1574
1575#ifdef RANDOM_WWNN
1576			arc4rand(&random_bits, sizeof(random_bits), 0);
1577#endif
1578
1579			/*
1580			 * XXX KDM this is a bit of a kludge for now.  We
1581			 * take the current WWNN/WWPN from the card, and
1582			 * replace the company identifier and the NL-Port
1583			 * indicator and the port number (for the WWPN).
1584			 * This should be replaced later with ddb_GetWWNN,
1585			 * or possibly a more centralized scheme.  (It
1586			 * would be nice to have the WWNN/WWPN for each
1587			 * port stored in the ctl_port structure.)
1588			 */
1589#ifdef RANDOM_WWNN
1590			ccb->knob.xport_specific.fc.wwnn =
1591				(random_bits &
1592				0x0000000fffffff00ULL) |
1593				/* Company ID */ 0x5000ED5000000000ULL |
1594				/* NL-Port */    0x0300;
1595			ccb->knob.xport_specific.fc.wwpn =
1596				(random_bits &
1597				0x0000000fffffff00ULL) |
1598				/* Company ID */ 0x5000ED5000000000ULL |
1599				/* NL-Port */    0x3000 |
1600				/* Port Num */ (bus_softc->port.targ_port & 0xff);
1601
1602			/*
1603			 * This is a bit of an API break/reversal, but if
1604			 * we're doing the random WWNN that's a little
1605			 * different anyway.  So record what we're actually
1606			 * using with the frontend code so it's reported
1607			 * accurately.
1608			 */
1609			ctl_port_set_wwns(&bus_softc->port,
1610			    true, ccb->knob.xport_specific.fc.wwnn,
1611			    true, ccb->knob.xport_specific.fc.wwpn);
1612			set_wwnn = 1;
1613#else /* RANDOM_WWNN */
1614			/*
1615			 * If the user has specified a WWNN/WWPN, send them
1616			 * down to the SIM.  Otherwise, record what the SIM
1617			 * has reported.
1618			 */
1619			if (bus_softc->port.wwnn != 0 && bus_softc->port.wwnn
1620			    != ccb->knob.xport_specific.fc.wwnn) {
1621				ccb->knob.xport_specific.fc.wwnn =
1622				    bus_softc->port.wwnn;
1623				set_wwnn = 1;
1624			} else {
1625				ctl_port_set_wwns(&bus_softc->port,
1626				    true, ccb->knob.xport_specific.fc.wwnn,
1627				    false, 0);
1628			}
1629			if (bus_softc->port.wwpn != 0 && bus_softc->port.wwpn
1630			     != ccb->knob.xport_specific.fc.wwpn) {
1631				ccb->knob.xport_specific.fc.wwpn =
1632				    bus_softc->port.wwpn;
1633				set_wwnn = 1;
1634			} else {
1635				ctl_port_set_wwns(&bus_softc->port,
1636				    false, 0,
1637				    true, ccb->knob.xport_specific.fc.wwpn);
1638			}
1639#endif /* RANDOM_WWNN */
1640
1641
1642			if (set_wwnn != 0) {
1643				printf("%s: %s new WWNN %#jx\n", __func__,
1644				       bus_softc->port_name,
1645				ccb->knob.xport_specific.fc.wwnn);
1646				printf("%s: %s new WWPN %#jx\n", __func__,
1647				       bus_softc->port_name,
1648				       ccb->knob.xport_specific.fc.wwpn);
1649			}
1650		} else {
1651			printf("%s: %s has no valid WWNN/WWPN\n", __func__,
1652			       bus_softc->port_name);
1653		}
1654	}
1655	ccb->ccb_h.func_code = XPT_SET_SIM_KNOB;
1656	ccb->knob.xport_specific.valid = KNOB_VALID_ROLE;
1657	if (set_wwnn != 0)
1658		ccb->knob.xport_specific.valid |= KNOB_VALID_ADDRESS;
1659
1660	if (online != 0)
1661		ccb->knob.xport_specific.fc.role |= KNOB_ROLE_TARGET;
1662	else
1663		ccb->knob.xport_specific.fc.role &= ~KNOB_ROLE_TARGET;
1664
1665	xpt_action(ccb);
1666
1667	if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1668		printf("%s: SIM %s (path id %d) target %s failed with "
1669		       "status %#x\n",
1670		       __func__, bus_softc->port_name, bus_softc->path_id,
1671		       (online != 0) ? "enable" : "disable",
1672		       ccb->ccb_h.status);
1673	} else {
1674		printf("%s: SIM %s (path id %d) target %s succeeded\n",
1675		       __func__, bus_softc->port_name, bus_softc->path_id,
1676		       (online != 0) ? "enable" : "disable");
1677	}
1678
1679	xpt_free_path(path);
1680	xpt_free_ccb(ccb);
1681}
1682
1683static void
1684ctlfe_online(void *arg)
1685{
1686	struct ctlfe_softc *bus_softc;
1687	struct cam_path *path;
1688	cam_status status;
1689	struct ctlfe_lun_softc *lun_softc;
1690	struct cam_periph *periph;
1691
1692	bus_softc = (struct ctlfe_softc *)arg;
1693
1694	/*
1695	 * Create the wildcard LUN before bringing the port online.
1696	 */
1697	status = xpt_create_path(&path, /*periph*/ NULL,
1698				 bus_softc->path_id, CAM_TARGET_WILDCARD,
1699				 CAM_LUN_WILDCARD);
1700	if (status != CAM_REQ_CMP) {
1701		printf("%s: unable to create path for wildcard periph\n",
1702				__func__);
1703		return;
1704	}
1705
1706	lun_softc = malloc(sizeof(*lun_softc), M_CTLFE, M_WAITOK | M_ZERO);
1707
1708	xpt_path_lock(path);
1709	periph = cam_periph_find(path, "ctl");
1710	if (periph != NULL) {
1711		/* We've already got a periph, no need to alloc a new one. */
1712		xpt_path_unlock(path);
1713		xpt_free_path(path);
1714		free(lun_softc, M_CTLFE);
1715		return;
1716	}
1717	lun_softc->parent_softc = bus_softc;
1718	lun_softc->flags |= CTLFE_LUN_WILDCARD;
1719
1720	status = cam_periph_alloc(ctlferegister,
1721				  ctlfeoninvalidate,
1722				  ctlfecleanup,
1723				  ctlfestart,
1724				  "ctl",
1725				  CAM_PERIPH_BIO,
1726				  path,
1727				  ctlfeasync,
1728				  0,
1729				  lun_softc);
1730
1731	if ((status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1732		const struct cam_status_entry *entry;
1733
1734		entry = cam_fetch_status_entry(status);
1735		printf("%s: CAM error %s (%#x) returned from "
1736		       "cam_periph_alloc()\n", __func__, (entry != NULL) ?
1737		       entry->status_text : "Unknown", status);
1738		free(lun_softc, M_CTLFE);
1739	}
1740
1741	xpt_path_unlock(path);
1742	ctlfe_onoffline(arg, /*online*/ 1);
1743	xpt_free_path(path);
1744}
1745
1746static void
1747ctlfe_offline(void *arg)
1748{
1749	struct ctlfe_softc *bus_softc;
1750	struct cam_path *path;
1751	cam_status status;
1752	struct cam_periph *periph;
1753
1754	bus_softc = (struct ctlfe_softc *)arg;
1755
1756	ctlfe_onoffline(arg, /*online*/ 0);
1757
1758	/*
1759	 * Disable the wildcard LUN for this port now that we have taken
1760	 * the port offline.
1761	 */
1762	status = xpt_create_path(&path, /*periph*/ NULL,
1763				 bus_softc->path_id, CAM_TARGET_WILDCARD,
1764				 CAM_LUN_WILDCARD);
1765	if (status != CAM_REQ_CMP) {
1766		printf("%s: unable to create path for wildcard periph\n",
1767		       __func__);
1768		return;
1769	}
1770	xpt_path_lock(path);
1771	if ((periph = cam_periph_find(path, "ctl")) != NULL)
1772		cam_periph_invalidate(periph);
1773	xpt_path_unlock(path);
1774	xpt_free_path(path);
1775}
1776
1777/*
1778 * This will get called to enable a LUN on every bus that is attached to
1779 * CTL.  So we only need to create a path/periph for this particular bus.
1780 */
1781static int
1782ctlfe_lun_enable(void *arg, int lun_id)
1783{
1784	struct ctlfe_softc *bus_softc;
1785	struct ctlfe_lun_softc *softc;
1786	struct cam_path *path;
1787	struct cam_periph *periph;
1788	cam_status status;
1789
1790	bus_softc = (struct ctlfe_softc *)arg;
1791	if (bus_softc->hba_misc & PIM_EXTLUNS)
1792		lun_id = CAM_EXTLUN_BYTE_SWIZZLE(ctl_encode_lun(lun_id));
1793
1794	status = xpt_create_path(&path, /*periph*/ NULL,
1795	    bus_softc->path_id, bus_softc->target_id, lun_id);
1796	/* XXX KDM need some way to return status to CTL here? */
1797	if (status != CAM_REQ_CMP) {
1798		printf("%s: could not create path, status %#x\n", __func__,
1799		       status);
1800		return (1);
1801	}
1802
1803	softc = malloc(sizeof(*softc), M_CTLFE, M_WAITOK | M_ZERO);
1804	xpt_path_lock(path);
1805	periph = cam_periph_find(path, "ctl");
1806	if (periph != NULL) {
1807		/* We've already got a periph, no need to alloc a new one. */
1808		xpt_path_unlock(path);
1809		xpt_free_path(path);
1810		free(softc, M_CTLFE);
1811		return (0);
1812	}
1813	softc->parent_softc = bus_softc;
1814
1815	status = cam_periph_alloc(ctlferegister,
1816				  ctlfeoninvalidate,
1817				  ctlfecleanup,
1818				  ctlfestart,
1819				  "ctl",
1820				  CAM_PERIPH_BIO,
1821				  path,
1822				  ctlfeasync,
1823				  0,
1824				  softc);
1825
1826	if ((status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1827		const struct cam_status_entry *entry;
1828
1829		entry = cam_fetch_status_entry(status);
1830		printf("%s: CAM error %s (%#x) returned from "
1831		       "cam_periph_alloc()\n", __func__, (entry != NULL) ?
1832		       entry->status_text : "Unknown", status);
1833		free(softc, M_CTLFE);
1834	}
1835
1836	xpt_path_unlock(path);
1837	xpt_free_path(path);
1838	return (0);
1839}
1840
1841/*
1842 * This will get called when the user removes a LUN to disable that LUN
1843 * on every bus that is attached to CTL.
1844 */
1845static int
1846ctlfe_lun_disable(void *arg, int lun_id)
1847{
1848	struct ctlfe_softc *softc;
1849	struct ctlfe_lun_softc *lun_softc;
1850
1851	softc = (struct ctlfe_softc *)arg;
1852	if (softc->hba_misc & PIM_EXTLUNS)
1853		lun_id = CAM_EXTLUN_BYTE_SWIZZLE(ctl_encode_lun(lun_id));
1854
1855	mtx_lock(&softc->lun_softc_mtx);
1856	STAILQ_FOREACH(lun_softc, &softc->lun_softc_list, links) {
1857		struct cam_path *path;
1858
1859		path = lun_softc->periph->path;
1860
1861		if ((xpt_path_target_id(path) == softc->target_id)
1862		 && (xpt_path_lun_id(path) == lun_id)) {
1863			break;
1864		}
1865	}
1866	if (lun_softc == NULL) {
1867		mtx_unlock(&softc->lun_softc_mtx);
1868		printf("%s: can't find lun %d\n", __func__, lun_id);
1869		return (1);
1870	}
1871	cam_periph_acquire(lun_softc->periph);
1872	mtx_unlock(&softc->lun_softc_mtx);
1873
1874	cam_periph_lock(lun_softc->periph);
1875	cam_periph_invalidate(lun_softc->periph);
1876	cam_periph_unlock(lun_softc->periph);
1877	cam_periph_release(lun_softc->periph);
1878	return (0);
1879}
1880
1881static void
1882ctlfe_dump_sim(struct cam_sim *sim)
1883{
1884
1885	printf("%s%d: max tagged openings: %d, max dev openings: %d\n",
1886	       sim->sim_name, sim->unit_number,
1887	       sim->max_tagged_dev_openings, sim->max_dev_openings);
1888}
1889
1890/*
1891 * Assumes that the SIM lock is held.
1892 */
1893static void
1894ctlfe_dump_queue(struct ctlfe_lun_softc *softc)
1895{
1896	struct ccb_hdr *hdr;
1897	struct cam_periph *periph;
1898	int num_items;
1899
1900	periph = softc->periph;
1901	num_items = 0;
1902
1903	TAILQ_FOREACH(hdr, &softc->work_queue, periph_links.tqe) {
1904		union ctl_io *io = hdr->io_ptr;
1905
1906		num_items++;
1907
1908		/*
1909		 * Only regular SCSI I/O is put on the work
1910		 * queue, so we can print sense here.  There may be no
1911		 * sense if it's no the queue for a DMA, but this serves to
1912		 * print out the CCB as well.
1913		 *
1914		 * XXX KDM switch this over to scsi_sense_print() when
1915		 * CTL is merged in with CAM.
1916		 */
1917		ctl_io_error_print(io, NULL);
1918
1919		/*
1920		 * Print DMA status if we are DMA_QUEUED.
1921		 */
1922		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED) {
1923			xpt_print(periph->path,
1924			    "Total %u, Current %u, Resid %u\n",
1925			    io->scsiio.kern_total_len,
1926			    io->scsiio.kern_data_len,
1927			    io->scsiio.kern_data_resid);
1928		}
1929	}
1930
1931	xpt_print(periph->path, "%d requests total waiting for CCBs\n",
1932		  num_items);
1933	xpt_print(periph->path, "%ju CCBs outstanding (%ju allocated, %ju "
1934		  "freed)\n", (uintmax_t)(softc->ccbs_alloced -
1935		  softc->ccbs_freed), (uintmax_t)softc->ccbs_alloced,
1936		  (uintmax_t)softc->ccbs_freed);
1937	xpt_print(periph->path, "%ju CTIOs outstanding (%ju sent, %ju "
1938		  "returned\n", (uintmax_t)(softc->ctios_sent -
1939		  softc->ctios_returned), softc->ctios_sent,
1940		  softc->ctios_returned);
1941}
1942
1943/*
1944 * Datamove/done routine called by CTL.  Put ourselves on the queue to
1945 * receive a CCB from CAM so we can queue the continue I/O request down
1946 * to the adapter.
1947 */
1948static void
1949ctlfe_datamove(union ctl_io *io)
1950{
1951	union ccb *ccb;
1952	struct cam_periph *periph;
1953	struct ctlfe_lun_softc *softc;
1954
1955	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
1956	    ("Unexpected io_type (%d) in ctlfe_datamove", io->io_hdr.io_type));
1957
1958	io->scsiio.ext_data_filled = 0;
1959	ccb = PRIV_CCB(io);
1960	periph = xpt_path_periph(ccb->ccb_h.path);
1961	cam_periph_lock(periph);
1962	softc = (struct ctlfe_lun_softc *)periph->softc;
1963	io->io_hdr.flags |= CTL_FLAG_DMA_QUEUED;
1964	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE)
1965		io->io_hdr.flags |= CTL_FLAG_STATUS_QUEUED;
1966	TAILQ_INSERT_TAIL(&softc->work_queue, &ccb->ccb_h,
1967			  periph_links.tqe);
1968	xpt_schedule(periph, /*priority*/ 1);
1969	cam_periph_unlock(periph);
1970}
1971
1972static void
1973ctlfe_done(union ctl_io *io)
1974{
1975	union ccb *ccb;
1976	struct cam_periph *periph;
1977	struct ctlfe_lun_softc *softc;
1978
1979	ccb = PRIV_CCB(io);
1980	periph = xpt_path_periph(ccb->ccb_h.path);
1981	cam_periph_lock(periph);
1982	softc = (struct ctlfe_lun_softc *)periph->softc;
1983
1984	if (io->io_hdr.io_type == CTL_IO_TASK) {
1985		/*
1986		 * Send the notify acknowledge down to the SIM, to let it
1987		 * know we processed the task management command.
1988		 */
1989		ccb->ccb_h.status = CAM_REQ_INPROG;
1990		ccb->ccb_h.func_code = XPT_NOTIFY_ACKNOWLEDGE;
1991		switch (io->taskio.task_status) {
1992		case CTL_TASK_FUNCTION_COMPLETE:
1993			ccb->cna2.arg = CAM_RSP_TMF_COMPLETE;
1994			break;
1995		case CTL_TASK_FUNCTION_SUCCEEDED:
1996			ccb->cna2.arg = CAM_RSP_TMF_SUCCEEDED;
1997			ccb->ccb_h.flags |= CAM_SEND_STATUS;
1998			break;
1999		case CTL_TASK_FUNCTION_REJECTED:
2000			ccb->cna2.arg = CAM_RSP_TMF_REJECTED;
2001			ccb->ccb_h.flags |= CAM_SEND_STATUS;
2002			break;
2003		case CTL_TASK_LUN_DOES_NOT_EXIST:
2004			ccb->cna2.arg = CAM_RSP_TMF_INCORRECT_LUN;
2005			ccb->ccb_h.flags |= CAM_SEND_STATUS;
2006			break;
2007		case CTL_TASK_FUNCTION_NOT_SUPPORTED:
2008			ccb->cna2.arg = CAM_RSP_TMF_FAILED;
2009			ccb->ccb_h.flags |= CAM_SEND_STATUS;
2010			break;
2011		}
2012		ccb->cna2.arg |= scsi_3btoul(io->taskio.task_resp) << 8;
2013		xpt_action(ccb);
2014	} else if (io->io_hdr.flags & CTL_FLAG_STATUS_SENT) {
2015		ctlfe_requeue_ccb(periph, ccb, /* unlock */1);
2016		return;
2017	} else {
2018		io->io_hdr.flags |= CTL_FLAG_STATUS_QUEUED;
2019		TAILQ_INSERT_TAIL(&softc->work_queue, &ccb->ccb_h,
2020				  periph_links.tqe);
2021		xpt_schedule(periph, /*priority*/ 1);
2022	}
2023
2024	cam_periph_unlock(periph);
2025}
2026
2027static void
2028ctlfe_dump(void)
2029{
2030	struct ctlfe_softc *bus_softc;
2031	struct ctlfe_lun_softc *lun_softc;
2032
2033	STAILQ_FOREACH(bus_softc, &ctlfe_softc_list, links) {
2034		ctlfe_dump_sim(bus_softc->sim);
2035		STAILQ_FOREACH(lun_softc, &bus_softc->lun_softc_list, links)
2036			ctlfe_dump_queue(lun_softc);
2037	}
2038}
2039