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