scsi_ctl.c revision 275882
138061Smsmith/*-
255939Snsouch * Copyright (c) 2008, 2009 Silicon Graphics International Corp.
370608Snsouch * All rights reserved.
438061Smsmith *
538061Smsmith * Redistribution and use in source and binary forms, with or without
638061Smsmith * modification, are permitted provided that the following conditions
738061Smsmith * are met:
838061Smsmith * 1. Redistributions of source code must retain the above copyright
938061Smsmith *    notice, this list of conditions, and the following disclaimer,
1038061Smsmith *    without modification.
1138061Smsmith * 2. Redistributions in binary form must reproduce at minimum a disclaimer
1238061Smsmith *    substantially similar to the "NO WARRANTY" disclaimer below
1338061Smsmith *    ("Disclaimer") and any redistribution must be conditioned upon
1438061Smsmith *    including a substantially similar Disclaimer requirement for further
1538061Smsmith *    binary redistribution.
1638061Smsmith *
1738061Smsmith * NO WARRANTY
1838061Smsmith * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
1938061Smsmith * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
2038061Smsmith * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
2138061Smsmith * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
2238061Smsmith * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2338061Smsmith * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2438061Smsmith * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2538061Smsmith * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
2638061Smsmith * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
2738061Smsmith * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
2838061Smsmith * POSSIBILITY OF SUCH DAMAGES.
2938061Smsmith *
30119418Sobrien * $Id: //depot/users/kenm/FreeBSD-test2/sys/cam/ctl/scsi_ctl.c#4 $
31119418Sobrien */
32119418Sobrien/*
3355205Speter * Peripheral driver interface between CAM and CTL (CAM Target Layer).
3438061Smsmith *
3538061Smsmith * Author: Ken Merry <ken@FreeBSD.org>
3655939Snsouch */
3755939Snsouch
3838061Smsmith#include <sys/cdefs.h>
3938061Smsmith__FBSDID("$FreeBSD: stable/10/sys/cam/ctl/scsi_ctl.c 275882 2014-12-18 08:26:11Z mav $");
4038061Smsmith
4155205Speter#include <sys/param.h>
4238061Smsmith#include <sys/queue.h>
4342475Snsouch#include <sys/systm.h>
4442475Snsouch#include <sys/kernel.h>
4555939Snsouch#include <sys/lock.h>
4638061Smsmith#include <sys/mutex.h>
4738061Smsmith#include <sys/condvar.h>
4838061Smsmith#include <sys/malloc.h>
4938061Smsmith#include <sys/bus.h>
5055939Snsouch#include <sys/endian.h>
5155939Snsouch#include <sys/sbuf.h>
5238061Smsmith#include <sys/sysctl.h>
5338061Smsmith#include <sys/types.h>
5438061Smsmith#include <sys/systm.h>
5538061Smsmith#include <machine/bus.h>
5638061Smsmith
5738061Smsmith#include <cam/cam.h>
5838061Smsmith#include <cam/cam_ccb.h>
5938061Smsmith#include <cam/cam_periph.h>
6038061Smsmith#include <cam/cam_queue.h>
6138061Smsmith#include <cam/cam_xpt_periph.h>
6238061Smsmith#include <cam/cam_debug.h>
6338061Smsmith#include <cam/cam_sim.h>
6438061Smsmith#include <cam/cam_xpt.h>
6538061Smsmith
6638061Smsmith#include <cam/scsi/scsi_all.h>
6738061Smsmith#include <cam/scsi/scsi_message.h>
6838061Smsmith
6938061Smsmith#include <cam/ctl/ctl_io.h>
7038061Smsmith#include <cam/ctl/ctl.h>
7138061Smsmith#include <cam/ctl/ctl_frontend.h>
7238061Smsmith#include <cam/ctl/ctl_util.h>
7338061Smsmith#include <cam/ctl/ctl_error.h>
7438061Smsmith
7538061Smsmithstruct ctlfe_softc {
7638061Smsmith	struct ctl_port port;
7738061Smsmith	path_id_t path_id;
7838061Smsmith	u_int	maxio;
7938061Smsmith	struct cam_sim *sim;
8038061Smsmith	char port_name[DEV_IDLEN];
8138061Smsmith	struct mtx lun_softc_mtx;
8238061Smsmith	STAILQ_HEAD(, ctlfe_lun_softc) lun_softc_list;
8338061Smsmith	STAILQ_ENTRY(ctlfe_softc) links;
8439134Snsouch};
8539134Snsouch
8638061SmsmithSTAILQ_HEAD(, ctlfe_softc) ctlfe_softc_list;
8738061Smsmithstruct mtx ctlfe_list_mtx;
8838061Smsmithstatic char ctlfe_mtx_desc[] = "ctlfelist";
8938061Smsmith#ifdef CTLFE_INIT_ENABLE
9038061Smsmithstatic int ctlfe_max_targets = 1;
9138061Smsmithstatic int ctlfe_num_targets = 0;
9238061Smsmith#endif
9338061Smsmith
9438061Smsmithtypedef enum {
9538061Smsmith	CTLFE_LUN_NONE		= 0x00,
9638061Smsmith	CTLFE_LUN_WILDCARD	= 0x01
9738061Smsmith} ctlfe_lun_flags;
9838061Smsmith
9978645Snsouchstruct ctlfe_lun_softc {
10078645Snsouch	struct ctlfe_softc *parent_softc;
10178645Snsouch	struct cam_periph *periph;
10278645Snsouch	ctlfe_lun_flags flags;
10378645Snsouch	uint64_t ccbs_alloced;
10478645Snsouch	uint64_t ccbs_freed;
10578645Snsouch	uint64_t ctios_sent;
10678645Snsouch	uint64_t ctios_returned;
10778645Snsouch	uint64_t atios_sent;
10878645Snsouch	uint64_t atios_returned;
10978645Snsouch	uint64_t inots_sent;
11078645Snsouch	uint64_t inots_returned;
11178645Snsouch	/* bus_dma_tag_t dma_tag; */
11278645Snsouch	TAILQ_HEAD(, ccb_hdr) work_queue;
11378645Snsouch	STAILQ_ENTRY(ctlfe_lun_softc) links;
11439134Snsouch};
11539134Snsouch
11639134Snsouchtypedef enum {
11739134Snsouch	CTLFE_CMD_NONE		= 0x00,
11845342Speter	CTLFE_CMD_PIECEWISE	= 0x01
11939134Snsouch} ctlfe_cmd_flags;
12045342Speter
12139134Snsouch/*
12239134Snsouch * The size limit of this structure is CTL_PORT_PRIV_SIZE, from ctl_io.h.
12339134Snsouch * Currently that is 600 bytes.
12439134Snsouch */
12539134Snsouchstruct ctlfe_lun_cmd_info {
12638061Smsmith	int cur_transfer_index;
12738061Smsmith	size_t cur_transfer_off;
12838061Smsmith	ctlfe_cmd_flags flags;
12938061Smsmith	/*
13038061Smsmith	 * XXX KDM struct bus_dma_segment is 8 bytes on i386, and 16
13138061Smsmith	 * bytes on amd64.  So with 32 elements, this is 256 bytes on
13238061Smsmith	 * i386 and 512 bytes on amd64.
13339134Snsouch	 */
13439134Snsouch#define CTLFE_MAX_SEGS	32
13538061Smsmith	bus_dma_segment_t cam_sglist[CTLFE_MAX_SEGS];
13638061Smsmith};
13738061SmsmithCTASSERT(sizeof(struct ctlfe_lun_cmd_info) <= CTL_PORT_PRIV_SIZE);
13838061Smsmith
13938061Smsmith/*
14038061Smsmith * When we register the adapter/bus, request that this many ctl_ios be
14138061Smsmith * allocated.  This should be the maximum supported by the adapter, but we
14239134Snsouch * currently don't have a way to get that back from the path inquiry.
14338061Smsmith * XXX KDM add that to the path inquiry.
14438061Smsmith */
14538061Smsmith#define	CTLFE_REQ_CTL_IO	4096
14638061Smsmith/*
14739134Snsouch * Number of Accept Target I/O CCBs to allocate and queue down to the
14838061Smsmith * adapter per LUN.
14938061Smsmith * XXX KDM should this be controlled by CTL?
15038061Smsmith */
15138061Smsmith#define	CTLFE_ATIO_PER_LUN	1024
15239134Snsouch/*
15338061Smsmith * Number of Immediate Notify CCBs (used for aborts, resets, etc.) to
15438061Smsmith * allocate and queue down to the adapter per LUN.
15538061Smsmith * XXX KDM should this be controlled by CTL?
15638061Smsmith */
15738061Smsmith#define	CTLFE_IN_PER_LUN	1024
15838061Smsmith
15938061Smsmith/*
16038061Smsmith * Timeout (in seconds) on CTIO CCB allocation for doing a DMA or sending
16138061Smsmith * status to the initiator.  The SIM is expected to have its own timeouts,
16238061Smsmith * so we're not putting this timeout around the CCB execution time.  The
16338061Smsmith * SIM should timeout and let us know if it has an issue.
16438061Smsmith */
16538061Smsmith#define	CTLFE_DMA_TIMEOUT	60
16638061Smsmith
16738061Smsmith/*
16838061Smsmith * Turn this on to enable extra debugging prints.
16938061Smsmith */
17038061Smsmith#if 0
17138061Smsmith#define	CTLFE_DEBUG
17238061Smsmith#endif
17378645Snsouch
17478645Snsouch/*
17578645Snsouch * Use randomly assigned WWNN/WWPN values.  This is to work around an issue
17678645Snsouch * in the FreeBSD initiator that makes it unable to rescan the target if
17738061Smsmith * the target gets rebooted and the WWNN/WWPN stay the same.
17838061Smsmith */
17938061Smsmith#if 0
18038061Smsmith#define	RANDOM_WWNN
18138061Smsmith#endif
18238061Smsmith
18338061SmsmithMALLOC_DEFINE(M_CTLFE, "CAM CTL FE", "CAM CTL FE interface");
18478645Snsouch
18578645Snsouch#define	io_ptr		ppriv_ptr0
18678645Snsouch
18778645Snsouch/* This is only used in the CTIO */
18878645Snsouch#define	ccb_atio	ppriv_ptr1
18978645Snsouch
19078645Snsouchint			ctlfeinitialize(void);
19178645Snsouchvoid			ctlfeshutdown(void);
19278645Snsouchstatic periph_init_t	ctlfeperiphinit;
19378645Snsouchstatic void		ctlfeasync(void *callback_arg, uint32_t code,
19478645Snsouch				   struct cam_path *path, void *arg);
19578645Snsouchstatic periph_ctor_t	ctlferegister;
19678645Snsouchstatic periph_oninv_t	ctlfeoninvalidate;
19778645Snsouchstatic periph_dtor_t	ctlfecleanup;
19838061Smsmithstatic periph_start_t	ctlfestart;
19938061Smsmithstatic void		ctlfedone(struct cam_periph *periph,
20038061Smsmith				  union ccb *done_ccb);
20138061Smsmith
20239134Snsouchstatic void 		ctlfe_onoffline(void *arg, int online);
20338061Smsmithstatic void 		ctlfe_online(void *arg);
20438061Smsmithstatic void 		ctlfe_offline(void *arg);
20538061Smsmithstatic int 		ctlfe_lun_enable(void *arg, struct ctl_id targ_id,
20638061Smsmith					 int lun_id);
20738061Smsmithstatic int 		ctlfe_lun_disable(void *arg, struct ctl_id targ_id,
20838061Smsmith					  int lun_id);
20943433Snsouchstatic void		ctlfe_dump_sim(struct cam_sim *sim);
21038061Smsmithstatic void		ctlfe_dump_queue(struct ctlfe_lun_softc *softc);
21138061Smsmithstatic void 		ctlfe_datamove(union ctl_io *io);
21238061Smsmithstatic void 		ctlfe_done(union ctl_io *io);
21338061Smsmithstatic void 		ctlfe_dump(void);
21438061Smsmith
21538061Smsmithstatic struct periph_driver ctlfe_driver =
21638061Smsmith{
21738061Smsmith	ctlfeperiphinit, "ctl",
21839134Snsouch	TAILQ_HEAD_INITIALIZER(ctlfe_driver.units), /*generation*/ 0,
21938061Smsmith	CAM_PERIPH_DRV_EARLY
22038061Smsmith};
22138061Smsmith
22238061Smsmithstatic struct ctl_frontend ctlfe_frontend =
22338061Smsmith{
22438061Smsmith	.name = "camtgt",
22543433Snsouch	.init = ctlfeinitialize,
22638061Smsmith	.fe_dump = ctlfe_dump,
22738061Smsmith	.shutdown = ctlfeshutdown,
22838061Smsmith};
22938061SmsmithCTL_FRONTEND_DECLARE(ctlfe, ctlfe_frontend);
23038061Smsmith
23138061Smsmithextern struct ctl_softc *control_softc;
23239134Snsouch
23338061Smsmithvoid
23438061Smsmithctlfeshutdown(void)
23538061Smsmith{
23643433Snsouch	return;
23743433Snsouch}
23843433Snsouch
23938061Smsmithint
24038061Smsmithctlfeinitialize(void)
24138061Smsmith{
24238061Smsmith
24338061Smsmith	STAILQ_INIT(&ctlfe_softc_list);
24438061Smsmith	mtx_init(&ctlfe_list_mtx, ctlfe_mtx_desc, NULL, MTX_DEF);
24538061Smsmith	periphdriver_register(&ctlfe_driver);
24638061Smsmith	return (0);
24739134Snsouch}
24838061Smsmith
24938061Smsmithvoid
25038061Smsmithctlfeperiphinit(void)
25143433Snsouch{
25243433Snsouch	cam_status status;
25343433Snsouch
25438061Smsmith	status = xpt_register_async(AC_PATH_REGISTERED | AC_PATH_DEREGISTERED |
25538061Smsmith				    AC_CONTRACT, ctlfeasync, NULL, NULL);
25638061Smsmith	if (status != CAM_REQ_CMP) {
25738061Smsmith		printf("ctl: Failed to attach async callback due to CAM "
25838061Smsmith		       "status 0x%x!\n", status);
25938061Smsmith	}
26038061Smsmith}
26138061Smsmith
26239134Snsouchstatic void
26339134Snsouchctlfeasync(void *callback_arg, uint32_t code, struct cam_path *path, void *arg)
26439134Snsouch{
26539134Snsouch	struct ctlfe_softc *softc;
26643433Snsouch
26739134Snsouch#ifdef CTLFEDEBUG
26843433Snsouch	printf("%s: entered\n", __func__);
26939134Snsouch#endif
27039520Snsouch
27139134Snsouch	mtx_lock(&ctlfe_list_mtx);
27239520Snsouch	STAILQ_FOREACH(softc, &ctlfe_softc_list, links) {
27339134Snsouch		if (softc->path_id == xpt_path_path_id(path))
27439134Snsouch			break;
27538061Smsmith	}
27638061Smsmith	mtx_unlock(&ctlfe_list_mtx);
27738061Smsmith
27855939Snsouch	/*
27938061Smsmith	 * When a new path gets registered, and it is capable of target
28038061Smsmith	 * mode, go ahead and attach.  Later on, we may need to be more
28155939Snsouch	 * selective, but for now this will be sufficient.
28255939Snsouch 	 */
28338061Smsmith	switch (code) {
28438061Smsmith	case AC_PATH_REGISTERED: {
28538061Smsmith		struct ctl_port *port;
28638061Smsmith		struct ccb_pathinq *cpi;
28738061Smsmith		int retval;
28838061Smsmith
28938061Smsmith		cpi = (struct ccb_pathinq *)arg;
29038061Smsmith
29155939Snsouch		/* Don't attach if it doesn't support target mode */
29238061Smsmith		if ((cpi->target_sprt & PIT_PROCESSOR) == 0) {
29338061Smsmith#ifdef CTLFEDEBUG
29438061Smsmith			printf("%s: SIM %s%d doesn't support target mode\n",
29555939Snsouch			       __func__, cpi->dev_name, cpi->unit_number);
29642475Snsouch#endif
29742475Snsouch			break;
29887599Sobrien		}
29942475Snsouch
30038061Smsmith		if (softc != NULL) {
30142475Snsouch#ifdef CTLFEDEBUG
30238061Smsmith			printf("%s: CTL port for CAM path %u already exists\n",
30355939Snsouch			       __func__, xpt_path_path_id(path));
30455939Snsouch#endif
30538061Smsmith			break;
30655939Snsouch		}
30738061Smsmith
30838061Smsmith#ifdef CTLFE_INIT_ENABLE
30938061Smsmith		if (ctlfe_num_targets >= ctlfe_max_targets) {
31038061Smsmith			union ccb *ccb;
31138061Smsmith
31239134Snsouch			ccb = (union ccb *)malloc(sizeof(*ccb), M_TEMP,
31338061Smsmith						  M_NOWAIT | M_ZERO);
31439134Snsouch			if (ccb == NULL) {
31538061Smsmith				printf("%s: unable to malloc CCB!\n", __func__);
31639134Snsouch				return;
31739134Snsouch			}
31838061Smsmith			xpt_setup_ccb(&ccb->ccb_h, path, CAM_PRIORITY_NONE);
31955939Snsouch
32039134Snsouch			ccb->ccb_h.func_code = XPT_SET_SIM_KNOB;
32138061Smsmith			ccb->knob.xport_specific.valid = KNOB_VALID_ROLE;
32239134Snsouch			ccb->knob.xport_specific.fc.role = KNOB_ROLE_INITIATOR;
32338061Smsmith
32439134Snsouch			xpt_action(ccb);
32538061Smsmith
32639134Snsouch			if ((ccb->ccb_h.status & CAM_STATUS_MASK) !=
32739134Snsouch			     CAM_REQ_CMP) {
32839134Snsouch				printf("%s: SIM %s%d (path id %d) initiator "
32939134Snsouch				       "enable failed with status %#x\n",
33039134Snsouch				       __func__, cpi->dev_name,
33139134Snsouch				       cpi->unit_number, cpi->ccb_h.path_id,
33238061Smsmith				       ccb->ccb_h.status);
33339134Snsouch			} else {
33455939Snsouch				printf("%s: SIM %s%d (path id %d) initiator "
33539134Snsouch				       "enable succeeded\n",
33639134Snsouch				       __func__, cpi->dev_name,
33738061Smsmith				       cpi->unit_number, cpi->ccb_h.path_id);
33838061Smsmith			}
33938061Smsmith
34039134Snsouch			free(ccb, M_TEMP);
34138061Smsmith
34239134Snsouch			break;
34339134Snsouch		} else {
34438061Smsmith			ctlfe_num_targets++;
34555939Snsouch		}
34639134Snsouch
34738061Smsmith		printf("%s: ctlfe_num_targets = %d\n", __func__,
34855939Snsouch		       ctlfe_num_targets);
34938061Smsmith#endif /* CTLFE_INIT_ENABLE */
35039134Snsouch
35138061Smsmith		/*
35238061Smsmith		 * We're in an interrupt context here, so we have to
35338061Smsmith		 * use M_NOWAIT.  Of course this means trouble if we
35438061Smsmith		 * can't allocate memory.
35538061Smsmith		 */
35638061Smsmith		softc = malloc(sizeof(*softc), M_CTLFE, M_NOWAIT | M_ZERO);
35738061Smsmith		if (softc == NULL) {
35839134Snsouch			printf("%s: unable to malloc %zd bytes for softc\n",
35938061Smsmith			       __func__, sizeof(*softc));
36038061Smsmith			return;
36155939Snsouch		}
36239520Snsouch
36338061Smsmith		softc->path_id = cpi->ccb_h.path_id;
36439520Snsouch		softc->sim = xpt_path_sim(path);
36555939Snsouch		if (cpi->maxio != 0)
36639520Snsouch			softc->maxio = cpi->maxio;
36739520Snsouch		else
36878645Snsouch			softc->maxio = DFLTPHYS;
36955939Snsouch		mtx_init(&softc->lun_softc_mtx, "LUN softc mtx", NULL, MTX_DEF);
37039520Snsouch		STAILQ_INIT(&softc->lun_softc_list);
37170608Snsouch
37270608Snsouch		port = &softc->port;
37370608Snsouch		port->frontend = &ctlfe_frontend;
37470608Snsouch
37555939Snsouch		/*
37670608Snsouch		 * XXX KDM should we be more accurate here ?
37739520Snsouch		 */
37870608Snsouch		if (cpi->transport == XPORT_FC)
37970608Snsouch			port->port_type = CTL_PORT_FC;
38070608Snsouch		else if (cpi->transport == XPORT_SAS)
38139520Snsouch			port->port_type = CTL_PORT_SAS;
38270608Snsouch		else
38370608Snsouch			port->port_type = CTL_PORT_SCSI;
38470608Snsouch
38570608Snsouch		/* XXX KDM what should the real number be here? */
38670608Snsouch		port->num_requested_ctl_io = 4096;
38739520Snsouch		snprintf(softc->port_name, sizeof(softc->port_name),
38870608Snsouch			 "%s%d", cpi->dev_name, cpi->unit_number);
38970608Snsouch		/*
39070608Snsouch		 * XXX KDM it would be nice to allocate storage in the
39170608Snsouch		 * frontend structure itself.
39270608Snsouch	 	 */
39370608Snsouch		port->port_name = softc->port_name;
39470608Snsouch		port->physical_port = cpi->bus_id;
39570608Snsouch		port->virtual_port = 0;
39670608Snsouch		port->port_online = ctlfe_online;
39770608Snsouch		port->port_offline = ctlfe_offline;
39855939Snsouch		port->onoff_arg = softc;
39970608Snsouch		port->lun_enable = ctlfe_lun_enable;
40070608Snsouch		port->lun_disable = ctlfe_lun_disable;
40139520Snsouch		port->targ_lun_arg = softc;
402184130Sjhb		port->fe_datamove = ctlfe_datamove;
403184130Sjhb		port->fe_done = ctlfe_done;
40439520Snsouch		/*
40539520Snsouch		 * XXX KDM the path inquiry doesn't give us the maximum
40655939Snsouch		 * number of targets supported.
40739520Snsouch		 */
40839520Snsouch		port->max_targets = cpi->max_target;
40939520Snsouch		port->max_target_id = cpi->max_target;
41070608Snsouch
41170608Snsouch		/*
41238061Smsmith		 * XXX KDM need to figure out whether we're the master or
41338061Smsmith		 * slave.
41438061Smsmith		 */
41538061Smsmith#ifdef CTLFEDEBUG
41638061Smsmith		printf("%s: calling ctl_port_register() for %s%d\n",
41755939Snsouch		       __func__, cpi->dev_name, cpi->unit_number);
41838061Smsmith#endif
41939134Snsouch		retval = ctl_port_register(port);
42039134Snsouch		if (retval != 0) {
42170608Snsouch			printf("%s: ctl_port_register() failed with "
42239520Snsouch			       "error %d!\n", __func__, retval);
423184130Sjhb			mtx_destroy(&softc->lun_softc_mtx);
424184130Sjhb			free(softc, M_CTLFE);
42539520Snsouch			break;
42639520Snsouch		} else {
42738061Smsmith			mtx_lock(&ctlfe_list_mtx);
42855939Snsouch			STAILQ_INSERT_TAIL(&ctlfe_softc_list, softc, links);
42938061Smsmith			mtx_unlock(&ctlfe_list_mtx);
43039520Snsouch		}
43139520Snsouch
43255939Snsouch		break;
43339520Snsouch	}
43438061Smsmith	case AC_PATH_DEREGISTERED: {
43538061Smsmith
43638061Smsmith		if (softc != NULL) {
43738061Smsmith			/*
43838061Smsmith			 * XXX KDM are we certain at this point that there
43938061Smsmith			 * are no outstanding commands for this frontend?
44038061Smsmith			 */
44138061Smsmith			mtx_lock(&ctlfe_list_mtx);
44255939Snsouch			STAILQ_REMOVE(&ctlfe_softc_list, softc, ctlfe_softc,
44338061Smsmith			    links);
44438061Smsmith			mtx_unlock(&ctlfe_list_mtx);
44555939Snsouch			ctl_port_deregister(&softc->port);
44645342Speter			mtx_destroy(&softc->lun_softc_mtx);
44738061Smsmith			free(softc, M_CTLFE);
44855939Snsouch		}
44938061Smsmith		break;
45038061Smsmith	}
45138061Smsmith	case AC_CONTRACT: {
45238061Smsmith		struct ac_contract *ac;
45338061Smsmith
45438061Smsmith		ac = (struct ac_contract *)arg;
45538061Smsmith
45638061Smsmith		switch (ac->contract_number) {
45738061Smsmith		case AC_CONTRACT_DEV_CHG: {
45838061Smsmith			struct ac_device_changed *dev_chg;
45955939Snsouch			int retval;
46038061Smsmith
46138061Smsmith			dev_chg = (struct ac_device_changed *)ac->contract_data;
46255939Snsouch
46345342Speter			printf("%s: WWPN %#jx port 0x%06x path %u target %u %s\n",
46438061Smsmith			       __func__, dev_chg->wwpn, dev_chg->port,
46555939Snsouch			       xpt_path_path_id(path), dev_chg->target,
46638061Smsmith			       (dev_chg->arrived == 0) ?  "left" : "arrived");
46738061Smsmith
46838061Smsmith			if (softc == NULL) {
46938061Smsmith				printf("%s: CTL port for CAM path %u not "
47038061Smsmith				       "found!\n", __func__,
47138061Smsmith				       xpt_path_path_id(path));
47238061Smsmith				break;
47355939Snsouch			}
47438061Smsmith			if (dev_chg->arrived != 0) {
47538061Smsmith				retval = ctl_add_initiator(&softc->port,
47638061Smsmith				    dev_chg->target, dev_chg->wwpn, NULL);
47738061Smsmith			} else {
47838061Smsmith				retval = ctl_remove_initiator(&softc->port,
47938061Smsmith				    dev_chg->target);
48038061Smsmith			}
48138061Smsmith
48238061Smsmith			if (retval < 0) {
48338061Smsmith				printf("%s: could not %s port %d iid %u "
48438061Smsmith				       "WWPN %#jx!\n", __func__,
48538061Smsmith				       (dev_chg->arrived != 0) ? "add" :
48638061Smsmith				       "remove", softc->port.targ_port,
48738061Smsmith				       dev_chg->target,
48838061Smsmith				       (uintmax_t)dev_chg->wwpn);
48938061Smsmith			}
49038061Smsmith			break;
49138061Smsmith		}
49243433Snsouch		default:
49343433Snsouch			printf("%s: unsupported contract number %ju\n",
49438061Smsmith			       __func__, (uintmax_t)ac->contract_number);
49538061Smsmith			break;
49638061Smsmith		}
49738061Smsmith		break;
49838061Smsmith	}
49938061Smsmith	default:
50038061Smsmith		break;
50138061Smsmith	}
50238061Smsmith}
50355939Snsouch
50438061Smsmithstatic cam_status
50538061Smsmithctlferegister(struct cam_periph *periph, void *arg)
50638061Smsmith{
50738061Smsmith	struct ctlfe_softc *bus_softc;
50838061Smsmith	struct ctlfe_lun_softc *softc;
50938061Smsmith	union ccb en_lun_ccb;
51038061Smsmith	cam_status status;
51138061Smsmith	int i;
51238061Smsmith
51338061Smsmith	softc = (struct ctlfe_lun_softc *)arg;
51438061Smsmith	bus_softc = softc->parent_softc;
51538061Smsmith
51638061Smsmith	TAILQ_INIT(&softc->work_queue);
51738061Smsmith	softc->periph = periph;
51838061Smsmith	periph->softc = softc;
51938061Smsmith
52038061Smsmith	xpt_setup_ccb(&en_lun_ccb.ccb_h, periph->path, CAM_PRIORITY_NONE);
52178645Snsouch	en_lun_ccb.ccb_h.func_code = XPT_EN_LUN;
52278645Snsouch	en_lun_ccb.cel.grp6_len = 0;
52355939Snsouch	en_lun_ccb.cel.grp7_len = 0;
52478645Snsouch	en_lun_ccb.cel.enable = 1;
52538061Smsmith	xpt_action(&en_lun_ccb);
52638061Smsmith	status = (en_lun_ccb.ccb_h.status & CAM_STATUS_MASK);
52755939Snsouch	if (status != CAM_REQ_CMP) {
52838061Smsmith		xpt_print(periph->path, "%s: Enable LUN failed, status 0x%x\n",
52938061Smsmith			  __func__, en_lun_ccb.ccb_h.status);
53055939Snsouch		return (status);
53138061Smsmith	}
53238061Smsmith
53338061Smsmith	status = CAM_REQ_CMP;
53438061Smsmith
53538061Smsmith	for (i = 0; i < CTLFE_ATIO_PER_LUN; i++) {
53638061Smsmith		union ccb *new_ccb;
53738061Smsmith		union ctl_io *new_io;
53838061Smsmith
53938061Smsmith		new_ccb = (union ccb *)malloc(sizeof(*new_ccb), M_CTLFE,
54038061Smsmith					      M_ZERO|M_NOWAIT);
54178645Snsouch		if (new_ccb == NULL) {
54278645Snsouch			status = CAM_RESRC_UNAVAIL;
54378645Snsouch			break;
54478645Snsouch		}
54578645Snsouch		new_io = ctl_alloc_io_nowait(bus_softc->port.ctl_pool_ref);
54678645Snsouch		if (new_io == NULL) {
54778645Snsouch			free(new_ccb, M_CTLFE);
54878645Snsouch			status = CAM_RESRC_UNAVAIL;
54978645Snsouch			break;
55078645Snsouch		}
55138061Smsmith		new_ccb->ccb_h.io_ptr = new_io;
55238061Smsmith
55338061Smsmith		xpt_setup_ccb(&new_ccb->ccb_h, periph->path, /*priority*/ 1);
55438061Smsmith		new_ccb->ccb_h.func_code = XPT_ACCEPT_TARGET_IO;
55538061Smsmith		new_ccb->ccb_h.cbfcnp = ctlfedone;
55638061Smsmith		new_ccb->ccb_h.flags |= CAM_UNLOCKED;
55738061Smsmith		xpt_action(new_ccb);
55838061Smsmith		softc->atios_sent++;
55955939Snsouch		status = new_ccb->ccb_h.status;
56055939Snsouch		if ((status & CAM_STATUS_MASK) != CAM_REQ_INPROG) {
56138061Smsmith			ctl_free_io(new_io);
56255939Snsouch			free(new_ccb, M_CTLFE);
56338061Smsmith			break;
56438061Smsmith		}
56555939Snsouch	}
56638061Smsmith
56739134Snsouch	status = cam_periph_acquire(periph);
56839134Snsouch	if ((status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
56939134Snsouch		xpt_print(periph->path, "%s: could not acquire reference "
57039134Snsouch			  "count, status = %#x\n", __func__, status);
57139134Snsouch		return (status);
57238061Smsmith	}
57355939Snsouch
57455939Snsouch	if (i == 0) {
57538061Smsmith		xpt_print(periph->path, "%s: could not allocate ATIO CCBs, "
57638061Smsmith			  "status 0x%x\n", __func__, status);
57755939Snsouch		return (CAM_REQ_CMP_ERR);
57838061Smsmith	}
57938061Smsmith
58038061Smsmith	for (i = 0; i < CTLFE_IN_PER_LUN; i++) {
58138061Smsmith		union ccb *new_ccb;
58238061Smsmith		union ctl_io *new_io;
58338061Smsmith
58438061Smsmith		new_ccb = (union ccb *)malloc(sizeof(*new_ccb), M_CTLFE,
58538061Smsmith					      M_ZERO|M_NOWAIT);
58638061Smsmith		if (new_ccb == NULL) {
58738061Smsmith			status = CAM_RESRC_UNAVAIL;
58838061Smsmith			break;
58978645Snsouch		}
59055939Snsouch		new_io = ctl_alloc_io_nowait(bus_softc->port.ctl_pool_ref);
59170608Snsouch		if (new_io == NULL) {
59238061Smsmith			free(new_ccb, M_CTLFE);
59338061Smsmith			status = CAM_RESRC_UNAVAIL;
59438061Smsmith			break;
59538061Smsmith		}
59638061Smsmith		new_ccb->ccb_h.io_ptr = new_io;
59755939Snsouch
59838061Smsmith		xpt_setup_ccb(&new_ccb->ccb_h, periph->path, /*priority*/ 1);
59938061Smsmith		new_ccb->ccb_h.func_code = XPT_IMMEDIATE_NOTIFY;
60038061Smsmith		new_ccb->ccb_h.cbfcnp = ctlfedone;
60138061Smsmith		new_ccb->ccb_h.flags |= CAM_UNLOCKED;
60238061Smsmith		xpt_action(new_ccb);
60378645Snsouch		softc->inots_sent++;
60478645Snsouch		status = new_ccb->ccb_h.status;
60578645Snsouch		if ((status & CAM_STATUS_MASK) != CAM_REQ_INPROG) {
60678645Snsouch			/*
60778645Snsouch			 * Note that we don't free the CCB here.  If the
60838061Smsmith			 * status is not CAM_REQ_INPROG, then we're
60938061Smsmith			 * probably talking to a SIM that says it is
61038061Smsmith			 * target-capable but doesn't support the
61138061Smsmith			 * XPT_IMMEDIATE_NOTIFY CCB.  i.e. it supports the
61270608Snsouch			 * older API.  In that case, it'll call xpt_done()
61370608Snsouch			 * on the CCB, and we need to free it in our done
61438061Smsmith			 * routine as a result.
61570608Snsouch			 */
61670608Snsouch			break;
61770608Snsouch		}
61870608Snsouch	}
61970608Snsouch	if ((i == 0)
620184130Sjhb	 || (status != CAM_REQ_INPROG)) {
62170608Snsouch		xpt_print(periph->path, "%s: could not allocate immediate "
62270608Snsouch			  "notify CCBs, status 0x%x\n", __func__, status);
62355939Snsouch		return (CAM_REQ_CMP_ERR);
62455939Snsouch	}
625184130Sjhb	mtx_lock(&bus_softc->lun_softc_mtx);
62670608Snsouch	STAILQ_INSERT_TAIL(&bus_softc->lun_softc_list, softc, links);
62770608Snsouch	mtx_unlock(&bus_softc->lun_softc_mtx);
62870608Snsouch	return (CAM_REQ_CMP);
62970608Snsouch}
630184130Sjhb
63170608Snsouchstatic void
63270608Snsouchctlfeoninvalidate(struct cam_periph *periph)
63370608Snsouch{
63438061Smsmith	union ccb en_lun_ccb;
63538061Smsmith	cam_status status;
63655939Snsouch	struct ctlfe_softc *bus_softc;
63738061Smsmith	struct ctlfe_lun_softc *softc;
63870608Snsouch
63970608Snsouch	softc = (struct ctlfe_lun_softc *)periph->softc;
64038061Smsmith
64138061Smsmith	xpt_setup_ccb(&en_lun_ccb.ccb_h, periph->path, CAM_PRIORITY_NONE);
64238061Smsmith	en_lun_ccb.ccb_h.func_code = XPT_EN_LUN;
64338061Smsmith	en_lun_ccb.cel.grp6_len = 0;
64438061Smsmith	en_lun_ccb.cel.grp7_len = 0;
64538061Smsmith	en_lun_ccb.cel.enable = 0;
64638061Smsmith	xpt_action(&en_lun_ccb);
64738061Smsmith	status = (en_lun_ccb.ccb_h.status & CAM_STATUS_MASK);
64838061Smsmith	if (status != CAM_REQ_CMP) {
64938061Smsmith		xpt_print(periph->path, "%s: Disable LUN failed, status 0x%x\n",
65039520Snsouch			  __func__, en_lun_ccb.ccb_h.status);
65142475Snsouch		/*
65242475Snsouch		 * XXX KDM what do we do now?
65387599Sobrien		 */
65442475Snsouch	}
65538061Smsmith	xpt_print(periph->path, "LUN removed, %ju ATIOs outstanding, %ju "
65638061Smsmith		  "INOTs outstanding, %d refs\n", softc->atios_sent -
65738061Smsmith		  softc->atios_returned, softc->inots_sent -
65838061Smsmith		  softc->inots_returned, periph->refcount);
65938061Smsmith
66038061Smsmith	bus_softc = softc->parent_softc;
66138061Smsmith	mtx_lock(&bus_softc->lun_softc_mtx);
66238061Smsmith	STAILQ_REMOVE(&bus_softc->lun_softc_list, softc, ctlfe_lun_softc, links);
66338061Smsmith	mtx_unlock(&bus_softc->lun_softc_mtx);
66438061Smsmith}
66538061Smsmith
66638061Smsmithstatic void
66738061Smsmithctlfecleanup(struct cam_periph *periph)
66838061Smsmith{
66938061Smsmith	struct ctlfe_lun_softc *softc;
67038061Smsmith
67138061Smsmith	xpt_print(periph->path, "%s: Called\n", __func__);
67238061Smsmith
67338061Smsmith	softc = (struct ctlfe_lun_softc *)periph->softc;
67438061Smsmith
67538061Smsmith	/*
67638061Smsmith	 * XXX KDM is there anything else that needs to be done here?
67738061Smsmith	 */
67838061Smsmith
67938061Smsmith	free(softc, M_CTLFE);
68055939Snsouch}
68138061Smsmith
68238061Smsmithstatic void
68338061Smsmithctlfedata(struct ctlfe_lun_softc *softc, union ctl_io *io,
68438061Smsmith    ccb_flags *flags, uint8_t **data_ptr, uint32_t *dxfer_len,
68538061Smsmith    u_int16_t *sglist_cnt)
68638061Smsmith{
68738061Smsmith	struct ctlfe_softc *bus_softc;
68838061Smsmith	struct ctlfe_lun_cmd_info *cmd_info;
68938061Smsmith	struct ctl_sg_entry *ctl_sglist;
69038061Smsmith	bus_dma_segment_t *cam_sglist;
69138061Smsmith	size_t off;
69238061Smsmith	int i, idx;
69338061Smsmith
69438061Smsmith	cmd_info = (struct ctlfe_lun_cmd_info *)io->io_hdr.port_priv;
69538061Smsmith	bus_softc = softc->parent_softc;
69638061Smsmith
69739520Snsouch	/*
69838061Smsmith	 * Set the direction, relative to the initiator.
69938061Smsmith	 */
70038061Smsmith	*flags &= ~CAM_DIR_MASK;
70138061Smsmith	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
70238061Smsmith		*flags |= CAM_DIR_IN;
70338061Smsmith	else
70438061Smsmith		*flags |= CAM_DIR_OUT;
70538061Smsmith
70638061Smsmith	*flags &= ~CAM_DATA_MASK;
70738061Smsmith	idx = cmd_info->cur_transfer_index;
70838061Smsmith	off = cmd_info->cur_transfer_off;
70955939Snsouch	cmd_info->flags &= ~CTLFE_CMD_PIECEWISE;
71038061Smsmith	if (io->scsiio.kern_sg_entries == 0) {
71138061Smsmith		/* No S/G list. */
71238061Smsmith		*data_ptr = io->scsiio.kern_data_ptr + off;
71338061Smsmith		if (io->scsiio.kern_data_len - off <= bus_softc->maxio) {
71438061Smsmith			*dxfer_len = io->scsiio.kern_data_len - off;
71538061Smsmith		} else {
71638061Smsmith			*dxfer_len = bus_softc->maxio;
71738061Smsmith			cmd_info->cur_transfer_index = -1;
71838061Smsmith			cmd_info->cur_transfer_off = bus_softc->maxio;
71938061Smsmith			cmd_info->flags |= CTLFE_CMD_PIECEWISE;
72038061Smsmith		}
72138061Smsmith		*sglist_cnt = 0;
72238061Smsmith
72338061Smsmith		if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR)
72438061Smsmith			*flags |= CAM_DATA_PADDR;
72538061Smsmith		else
72638061Smsmith			*flags |= CAM_DATA_VADDR;
72738061Smsmith	} else {
72838061Smsmith		/* S/G list with physical or virtual pointers. */
72938061Smsmith		ctl_sglist = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
73038061Smsmith		cam_sglist = cmd_info->cam_sglist;
73138061Smsmith		*dxfer_len = 0;
73238061Smsmith		for (i = 0; i < io->scsiio.kern_sg_entries - idx; i++) {
73338061Smsmith			cam_sglist[i].ds_addr = (bus_addr_t)ctl_sglist[i + idx].addr + off;
73438061Smsmith			if (ctl_sglist[i + idx].len - off <= bus_softc->maxio - *dxfer_len) {
73538061Smsmith				cam_sglist[i].ds_len = ctl_sglist[idx + i].len - off;
73638061Smsmith				*dxfer_len += cam_sglist[i].ds_len;
73738061Smsmith			} else {
73838061Smsmith				cam_sglist[i].ds_len = bus_softc->maxio - *dxfer_len;
73938061Smsmith				cmd_info->cur_transfer_index = idx + i;
74038061Smsmith				cmd_info->cur_transfer_off = cam_sglist[i].ds_len + off;
74138061Smsmith				cmd_info->flags |= CTLFE_CMD_PIECEWISE;
74239520Snsouch				*dxfer_len += cam_sglist[i].ds_len;
74339520Snsouch				if (ctl_sglist[i].len != 0)
74439520Snsouch					i++;
74555939Snsouch				break;
74639520Snsouch			}
74739520Snsouch			if (i == (CTLFE_MAX_SEGS - 1) &&
74839520Snsouch			    idx + i < (io->scsiio.kern_sg_entries - 1)) {
74939520Snsouch				cmd_info->cur_transfer_index = idx + i + 1;
75039520Snsouch				cmd_info->cur_transfer_off = 0;
75138061Smsmith				cmd_info->flags |= CTLFE_CMD_PIECEWISE;
75238061Smsmith				i++;
75338061Smsmith				break;
75438061Smsmith			}
75538061Smsmith			off = 0;
75638061Smsmith		}
75738061Smsmith		*sglist_cnt = i;
75838061Smsmith		if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR)
75938061Smsmith			*flags |= CAM_DATA_SG_PADDR;
76038061Smsmith		else
76138061Smsmith			*flags |= CAM_DATA_SG;
76238061Smsmith		*data_ptr = (uint8_t *)cam_sglist;
76338061Smsmith	}
76438061Smsmith}
76538061Smsmith
76638061Smsmithstatic void
76738061Smsmithctlfestart(struct cam_periph *periph, union ccb *start_ccb)
76838061Smsmith{
76938061Smsmith	struct ctlfe_lun_softc *softc;
77038061Smsmith	struct ctlfe_lun_cmd_info *cmd_info;
77138061Smsmith	struct ccb_hdr *ccb_h;
77238061Smsmith	struct ccb_accept_tio *atio;
77338061Smsmith	struct ccb_scsiio *csio;
77438061Smsmith	uint8_t *data_ptr;
77538061Smsmith	uint32_t dxfer_len;
77638061Smsmith	ccb_flags flags;
77738061Smsmith	union ctl_io *io;
77838061Smsmith	uint8_t scsi_status;
77938061Smsmith
78038061Smsmith	softc = (struct ctlfe_lun_softc *)periph->softc;
78138061Smsmith	softc->ccbs_alloced++;
782
783	ccb_h = TAILQ_FIRST(&softc->work_queue);
784	if (ccb_h == NULL) {
785		softc->ccbs_freed++;
786		xpt_release_ccb(start_ccb);
787		return;
788	}
789
790	/* Take the ATIO off the work queue */
791	TAILQ_REMOVE(&softc->work_queue, ccb_h, periph_links.tqe);
792	atio = (struct ccb_accept_tio *)ccb_h;
793	io = (union ctl_io *)ccb_h->io_ptr;
794	csio = &start_ccb->csio;
795
796	flags = atio->ccb_h.flags &
797		(CAM_DIS_DISCONNECT|CAM_TAG_ACTION_VALID|CAM_DIR_MASK);
798	cmd_info = (struct ctlfe_lun_cmd_info *)io->io_hdr.port_priv;
799	cmd_info->cur_transfer_index = 0;
800	cmd_info->cur_transfer_off = 0;
801	cmd_info->flags = 0;
802
803	if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED) {
804		/*
805		 * Datamove call, we need to setup the S/G list.
806		 */
807		scsi_status = 0;
808		csio->cdb_len = atio->cdb_len;
809		ctlfedata(softc, io, &flags, &data_ptr, &dxfer_len,
810		    &csio->sglist_cnt);
811		io->scsiio.ext_data_filled += dxfer_len;
812		if (io->scsiio.ext_data_filled > io->scsiio.kern_total_len) {
813			xpt_print(periph->path, "%s: tag 0x%04x "
814				  "fill len %u > total %u\n",
815				  __func__, io->scsiio.tag_num,
816				  io->scsiio.ext_data_filled,
817				  io->scsiio.kern_total_len);
818		}
819	} else {
820		/*
821		 * We're done, send status back.
822		 */
823		if ((io->io_hdr.flags & CTL_FLAG_ABORT) &&
824		    (io->io_hdr.flags & CTL_FLAG_ABORT_STATUS) == 0) {
825			io->io_hdr.flags &= ~CTL_FLAG_STATUS_QUEUED;
826
827			/*
828			 * If this command was aborted, we don't
829			 * need to send status back to the SIM.
830			 * Just free the CTIO and ctl_io, and
831			 * recycle the ATIO back to the SIM.
832			 */
833			xpt_print(periph->path, "%s: aborted "
834				  "command 0x%04x discarded\n",
835				  __func__, io->scsiio.tag_num);
836			/*
837			 * For a wildcard attachment, commands can
838			 * come in with a specific target/lun.  Reset
839			 * the target and LUN fields back to the
840			 * wildcard values before we send them back
841			 * down to the SIM.  The SIM has a wildcard
842			 * LUN enabled, not whatever target/lun
843			 * these happened to be.
844			 */
845			if (softc->flags & CTLFE_LUN_WILDCARD) {
846				atio->ccb_h.target_id = CAM_TARGET_WILDCARD;
847				atio->ccb_h.target_lun = CAM_LUN_WILDCARD;
848			}
849
850			if ((atio->ccb_h.status & CAM_DEV_QFRZN) != 0) {
851				cam_release_devq(periph->path,
852						 /*relsim_flags*/0,
853						 /*reduction*/0,
854						 /*timeout*/0,
855						 /*getcount_only*/0);
856				atio->ccb_h.status &= ~CAM_DEV_QFRZN;
857			}
858
859			if (atio->ccb_h.func_code != XPT_ACCEPT_TARGET_IO) {
860				xpt_print(periph->path, "%s: func_code "
861					  "is %#x\n", __func__,
862					  atio->ccb_h.func_code);
863			}
864			start_ccb->ccb_h.func_code = XPT_ABORT;
865			start_ccb->cab.abort_ccb = (union ccb *)atio;
866
867			/* Tell the SIM that we've aborted this ATIO */
868			xpt_action(start_ccb);
869			softc->ccbs_freed++;
870			xpt_release_ccb(start_ccb);
871
872			/*
873			 * Send the ATIO back down to the SIM.
874			 */
875			xpt_action((union ccb *)atio);
876			softc->atios_sent++;
877
878			/*
879			 * If we still have work to do, ask for
880			 * another CCB.  Otherwise, deactivate our
881			 * callout.
882			 */
883			if (!TAILQ_EMPTY(&softc->work_queue))
884				xpt_schedule(periph, /*priority*/ 1);
885			return;
886		}
887		data_ptr = NULL;
888		dxfer_len = 0;
889		csio->sglist_cnt = 0;
890		scsi_status = 0;
891	}
892	if ((io->io_hdr.flags & CTL_FLAG_STATUS_QUEUED) &&
893	    (cmd_info->flags & CTLFE_CMD_PIECEWISE) == 0 &&
894	    ((io->io_hdr.flags & CTL_FLAG_DMA_QUEUED) == 0 ||
895	     io->io_hdr.status == CTL_SUCCESS)) {
896		io->io_hdr.flags |= CTL_FLAG_STATUS_SENT;
897		flags |= CAM_SEND_STATUS;
898		scsi_status = io->scsiio.scsi_status;
899		csio->sense_len = io->scsiio.sense_len;
900#ifdef CTLFEDEBUG
901		printf("%s: tag %04x status %x\n", __func__,
902		       atio->tag_id, io->io_hdr.status);
903#endif
904		if (csio->sense_len != 0) {
905			csio->sense_data = io->scsiio.sense_data;
906			flags |= CAM_SEND_SENSE;
907		} else if (scsi_status == SCSI_STATUS_CHECK_COND) {
908			xpt_print(periph->path, "%s: check condition "
909				  "with no sense\n", __func__);
910		}
911	}
912
913#ifdef CTLFEDEBUG
914	printf("%s: %s: tag %04x flags %x ptr %p len %u\n", __func__,
915	       (flags & CAM_SEND_STATUS) ? "done" : "datamove",
916	       atio->tag_id, flags, data_ptr, dxfer_len);
917#endif
918
919	/*
920	 * Valid combinations:
921	 *  - CAM_SEND_STATUS, CAM_DATA_SG = 0, dxfer_len = 0,
922	 *    sglist_cnt = 0
923	 *  - CAM_SEND_STATUS = 0, CAM_DATA_SG = 0, dxfer_len != 0,
924	 *    sglist_cnt = 0
925	 *  - CAM_SEND_STATUS = 0, CAM_DATA_SG, dxfer_len != 0,
926	 *    sglist_cnt != 0
927	 */
928#ifdef CTLFEDEBUG
929	if (((flags & CAM_SEND_STATUS)
930	  && (((flags & CAM_DATA_SG) != 0)
931	   || (dxfer_len != 0)
932	   || (csio->sglist_cnt != 0)))
933	 || (((flags & CAM_SEND_STATUS) == 0)
934	  && (dxfer_len == 0))
935	 || ((flags & CAM_DATA_SG)
936	  && (csio->sglist_cnt == 0))
937	 || (((flags & CAM_DATA_SG) == 0)
938	  && (csio->sglist_cnt != 0))) {
939		printf("%s: tag %04x cdb %02x flags %#x dxfer_len "
940		       "%d sg %u\n", __func__, atio->tag_id,
941		       atio->cdb_io.cdb_bytes[0], flags, dxfer_len,
942		       csio->sglist_cnt);
943		printf("%s: tag %04x io status %#x\n", __func__,
944		       atio->tag_id, io->io_hdr.status);
945	}
946#endif
947	cam_fill_ctio(csio,
948		      /*retries*/ 2,
949		      ctlfedone,
950		      flags,
951		      (flags & CAM_TAG_ACTION_VALID) ? MSG_SIMPLE_Q_TAG : 0,
952		      atio->tag_id,
953		      atio->init_id,
954		      scsi_status,
955		      /*data_ptr*/ data_ptr,
956		      /*dxfer_len*/ dxfer_len,
957		      /*timeout*/ 5 * 1000);
958	start_ccb->ccb_h.flags |= CAM_UNLOCKED;
959	start_ccb->ccb_h.ccb_atio = atio;
960	if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
961		io->io_hdr.flags |= CTL_FLAG_DMA_INPROG;
962	io->io_hdr.flags &= ~(CTL_FLAG_DMA_QUEUED | CTL_FLAG_STATUS_QUEUED);
963
964	softc->ctios_sent++;
965
966	cam_periph_unlock(periph);
967	xpt_action(start_ccb);
968	cam_periph_lock(periph);
969
970	if ((atio->ccb_h.status & CAM_DEV_QFRZN) != 0) {
971		cam_release_devq(periph->path,
972				 /*relsim_flags*/0,
973				 /*reduction*/0,
974				 /*timeout*/0,
975				 /*getcount_only*/0);
976		atio->ccb_h.status &= ~CAM_DEV_QFRZN;
977	}
978
979	/*
980	 * If we still have work to do, ask for another CCB.
981	 */
982	if (!TAILQ_EMPTY(&softc->work_queue))
983		xpt_schedule(periph, /*priority*/ 1);
984}
985
986static void
987ctlfe_free_ccb(struct cam_periph *periph, union ccb *ccb)
988{
989	struct ctlfe_lun_softc *softc;
990
991	softc = (struct ctlfe_lun_softc *)periph->softc;
992
993	switch (ccb->ccb_h.func_code) {
994	case XPT_ACCEPT_TARGET_IO:
995		softc->atios_returned++;
996		break;
997	case XPT_IMMEDIATE_NOTIFY:
998	case XPT_NOTIFY_ACKNOWLEDGE:
999		softc->inots_returned++;
1000		break;
1001	default:
1002		break;
1003	}
1004
1005	ctl_free_io(ccb->ccb_h.io_ptr);
1006	free(ccb, M_CTLFE);
1007
1008	KASSERT(softc->atios_returned <= softc->atios_sent, ("%s: "
1009		"atios_returned %ju > atios_sent %ju", __func__,
1010		softc->atios_returned, softc->atios_sent));
1011	KASSERT(softc->inots_returned <= softc->inots_sent, ("%s: "
1012		"inots_returned %ju > inots_sent %ju", __func__,
1013		softc->inots_returned, softc->inots_sent));
1014
1015	/*
1016	 * If we have received all of our CCBs, we can release our
1017	 * reference on the peripheral driver.  It will probably go away
1018	 * now.
1019	 */
1020	if ((softc->atios_returned == softc->atios_sent)
1021	 && (softc->inots_returned == softc->inots_sent)) {
1022		cam_periph_release_locked(periph);
1023	}
1024}
1025
1026static int
1027ctlfe_adjust_cdb(struct ccb_accept_tio *atio, uint32_t offset)
1028{
1029	uint64_t lba;
1030	uint32_t num_blocks, nbc;
1031	uint8_t *cmdbyt = (atio->ccb_h.flags & CAM_CDB_POINTER)?
1032	    atio->cdb_io.cdb_ptr : atio->cdb_io.cdb_bytes;
1033
1034	nbc = offset >> 9;	/* ASSUMING 512 BYTE BLOCKS */
1035
1036	switch (cmdbyt[0]) {
1037	case READ_6:
1038	case WRITE_6:
1039	{
1040		struct scsi_rw_6 *cdb = (struct scsi_rw_6 *)cmdbyt;
1041		lba = scsi_3btoul(cdb->addr);
1042		lba &= 0x1fffff;
1043		num_blocks = cdb->length;
1044		if (num_blocks == 0)
1045			num_blocks = 256;
1046		lba += nbc;
1047		num_blocks -= nbc;
1048		scsi_ulto3b(lba, cdb->addr);
1049		cdb->length = num_blocks;
1050		break;
1051	}
1052	case READ_10:
1053	case WRITE_10:
1054	{
1055		struct scsi_rw_10 *cdb = (struct scsi_rw_10 *)cmdbyt;
1056		lba = scsi_4btoul(cdb->addr);
1057		num_blocks = scsi_2btoul(cdb->length);
1058		lba += nbc;
1059		num_blocks -= nbc;
1060		scsi_ulto4b(lba, cdb->addr);
1061		scsi_ulto2b(num_blocks, cdb->length);
1062		break;
1063	}
1064	case READ_12:
1065	case WRITE_12:
1066	{
1067		struct scsi_rw_12 *cdb = (struct scsi_rw_12 *)cmdbyt;
1068		lba = scsi_4btoul(cdb->addr);
1069		num_blocks = scsi_4btoul(cdb->length);
1070		lba += nbc;
1071		num_blocks -= nbc;
1072		scsi_ulto4b(lba, cdb->addr);
1073		scsi_ulto4b(num_blocks, cdb->length);
1074		break;
1075	}
1076	case READ_16:
1077	case WRITE_16:
1078	case WRITE_ATOMIC_16:
1079	{
1080		struct scsi_rw_16 *cdb = (struct scsi_rw_16 *)cmdbyt;
1081		lba = scsi_8btou64(cdb->addr);
1082		num_blocks = scsi_4btoul(cdb->length);
1083		lba += nbc;
1084		num_blocks -= nbc;
1085		scsi_u64to8b(lba, cdb->addr);
1086		scsi_ulto4b(num_blocks, cdb->length);
1087		break;
1088	}
1089	default:
1090		return -1;
1091	}
1092	return (0);
1093}
1094
1095static void
1096ctlfedone(struct cam_periph *periph, union ccb *done_ccb)
1097{
1098	struct ctlfe_lun_softc *softc;
1099	struct ctlfe_softc *bus_softc;
1100	struct ccb_accept_tio *atio = NULL;
1101	union ctl_io *io = NULL;
1102	struct mtx *mtx;
1103
1104	KASSERT((done_ccb->ccb_h.flags & CAM_UNLOCKED) != 0,
1105	    ("CCB in ctlfedone() without CAM_UNLOCKED flag"));
1106#ifdef CTLFE_DEBUG
1107	printf("%s: entered, func_code = %#x\n", __func__,
1108	       done_ccb->ccb_h.func_code);
1109#endif
1110
1111	softc = (struct ctlfe_lun_softc *)periph->softc;
1112	bus_softc = softc->parent_softc;
1113	mtx = cam_periph_mtx(periph);
1114	mtx_lock(mtx);
1115
1116	/*
1117	 * If the peripheral is invalid, ATIOs and immediate notify CCBs
1118	 * need to be freed.  Most of the ATIOs and INOTs that come back
1119	 * will be CCBs that are being returned from the SIM as a result of
1120	 * our disabling the LUN.
1121	 *
1122	 * Other CCB types are handled in their respective cases below.
1123	 */
1124	if (periph->flags & CAM_PERIPH_INVALID) {
1125		switch (done_ccb->ccb_h.func_code) {
1126		case XPT_ACCEPT_TARGET_IO:
1127		case XPT_IMMEDIATE_NOTIFY:
1128		case XPT_NOTIFY_ACKNOWLEDGE:
1129			ctlfe_free_ccb(periph, done_ccb);
1130			goto out;
1131		default:
1132			break;
1133		}
1134
1135	}
1136	switch (done_ccb->ccb_h.func_code) {
1137	case XPT_ACCEPT_TARGET_IO: {
1138
1139		atio = &done_ccb->atio;
1140
1141		softc->atios_returned++;
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		ctl_zero_io(io);
1151
1152		/* Save pointers on both sides */
1153		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = done_ccb;
1154		done_ccb->ccb_h.io_ptr = io;
1155
1156		/*
1157		 * Only SCSI I/O comes down this path, resets, etc. come
1158		 * down the immediate notify path below.
1159		 */
1160		io->io_hdr.io_type = CTL_IO_SCSI;
1161		io->io_hdr.nexus.initid.id = atio->init_id;
1162		io->io_hdr.nexus.targ_port = bus_softc->port.targ_port;
1163		io->io_hdr.nexus.targ_target.id = atio->ccb_h.target_id;
1164		io->io_hdr.nexus.targ_lun = atio->ccb_h.target_lun;
1165		io->scsiio.tag_num = atio->tag_id;
1166		switch (atio->tag_action) {
1167		case CAM_TAG_ACTION_NONE:
1168			io->scsiio.tag_type = CTL_TAG_UNTAGGED;
1169			break;
1170		case MSG_SIMPLE_TASK:
1171			io->scsiio.tag_type = CTL_TAG_SIMPLE;
1172			break;
1173		case MSG_HEAD_OF_QUEUE_TASK:
1174        		io->scsiio.tag_type = CTL_TAG_HEAD_OF_QUEUE;
1175			break;
1176		case MSG_ORDERED_TASK:
1177        		io->scsiio.tag_type = CTL_TAG_ORDERED;
1178			break;
1179		case MSG_ACA_TASK:
1180			io->scsiio.tag_type = CTL_TAG_ACA;
1181			break;
1182		default:
1183			io->scsiio.tag_type = CTL_TAG_UNTAGGED;
1184			printf("%s: unhandled tag type %#x!!\n", __func__,
1185			       atio->tag_action);
1186			break;
1187		}
1188		if (atio->cdb_len > sizeof(io->scsiio.cdb)) {
1189			printf("%s: WARNING: CDB len %d > ctl_io space %zd\n",
1190			       __func__, atio->cdb_len, sizeof(io->scsiio.cdb));
1191		}
1192		io->scsiio.cdb_len = min(atio->cdb_len, sizeof(io->scsiio.cdb));
1193		bcopy(atio->cdb_io.cdb_bytes, io->scsiio.cdb,
1194		      io->scsiio.cdb_len);
1195
1196#ifdef CTLFEDEBUG
1197		printf("%s: %ju:%d:%ju:%d: tag %04x CDB %02x\n", __func__,
1198		        (uintmax_t)io->io_hdr.nexus.initid.id,
1199		        io->io_hdr.nexus.targ_port,
1200		        (uintmax_t)io->io_hdr.nexus.targ_target.id,
1201		        io->io_hdr.nexus.targ_lun,
1202			io->scsiio.tag_num, io->scsiio.cdb[0]);
1203#endif
1204
1205		ctl_queue(io);
1206		return;
1207	}
1208	case XPT_CONT_TARGET_IO: {
1209		int srr = 0;
1210		uint32_t srr_off = 0;
1211
1212		atio = (struct ccb_accept_tio *)done_ccb->ccb_h.ccb_atio;
1213		io = (union ctl_io *)atio->ccb_h.io_ptr;
1214
1215		softc->ctios_returned++;
1216#ifdef CTLFEDEBUG
1217		printf("%s: got XPT_CONT_TARGET_IO tag %#x flags %#x\n",
1218		       __func__, atio->tag_id, done_ccb->ccb_h.flags);
1219#endif
1220		/*
1221		 * Handle SRR case were the data pointer is pushed back hack
1222		 */
1223		if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_MESSAGE_RECV
1224		    && done_ccb->csio.msg_ptr != NULL
1225		    && done_ccb->csio.msg_ptr[0] == MSG_EXTENDED
1226		    && done_ccb->csio.msg_ptr[1] == 5
1227       		    && done_ccb->csio.msg_ptr[2] == 0) {
1228			srr = 1;
1229			srr_off =
1230			    (done_ccb->csio.msg_ptr[3] << 24)
1231			    | (done_ccb->csio.msg_ptr[4] << 16)
1232			    | (done_ccb->csio.msg_ptr[5] << 8)
1233			    | (done_ccb->csio.msg_ptr[6]);
1234		}
1235
1236		if (srr && (io->io_hdr.flags & CTL_FLAG_DMA_INPROG) == 0) {
1237			/*
1238			 * If status was being sent, the back end data is now
1239			 * history. Hack it up and resubmit a new command with
1240			 * the CDB adjusted. If the SIM does the right thing,
1241			 * all of the resid math should work.
1242			 */
1243			softc->ccbs_freed++;
1244			xpt_release_ccb(done_ccb);
1245			if (ctlfe_adjust_cdb(atio, srr_off) == 0) {
1246				done_ccb = (union ccb *)atio;
1247				goto resubmit;
1248			}
1249			/*
1250			 * Fall through to doom....
1251			 */
1252		} else if (srr) {
1253			/*
1254			 * If we have an srr and we're still sending data, we
1255			 * should be able to adjust offsets and cycle again.
1256			 */
1257			io->scsiio.kern_rel_offset =
1258			    io->scsiio.ext_data_filled = srr_off;
1259			io->scsiio.ext_data_len = io->scsiio.kern_total_len -
1260			    io->scsiio.kern_rel_offset;
1261			softc->ccbs_freed++;
1262			io->scsiio.io_hdr.status = CTL_STATUS_NONE;
1263			xpt_release_ccb(done_ccb);
1264			TAILQ_INSERT_HEAD(&softc->work_queue, &atio->ccb_h,
1265					  periph_links.tqe);
1266			xpt_schedule(periph, /*priority*/ 1);
1267			break;
1268		}
1269
1270		/*
1271		 * If we were sending status back to the initiator, free up
1272		 * resources.  If we were doing a datamove, call the
1273		 * datamove done routine.
1274		 */
1275		if ((io->io_hdr.flags & CTL_FLAG_DMA_INPROG) == 0) {
1276			softc->ccbs_freed++;
1277			xpt_release_ccb(done_ccb);
1278			/*
1279			 * For a wildcard attachment, commands can come in
1280			 * with a specific target/lun.  Reset the target
1281			 * and LUN fields back to the wildcard values before
1282			 * we send them back down to the SIM.  The SIM has
1283			 * a wildcard LUN enabled, not whatever target/lun
1284			 * these happened to be.
1285			 */
1286			if (softc->flags & CTLFE_LUN_WILDCARD) {
1287				atio->ccb_h.target_id = CAM_TARGET_WILDCARD;
1288				atio->ccb_h.target_lun = CAM_LUN_WILDCARD;
1289			}
1290			if (periph->flags & CAM_PERIPH_INVALID) {
1291				ctlfe_free_ccb(periph, (union ccb *)atio);
1292			} else {
1293				softc->atios_sent++;
1294				mtx_unlock(mtx);
1295				xpt_action((union ccb *)atio);
1296				return;
1297			}
1298		} else {
1299			struct ctlfe_lun_cmd_info *cmd_info;
1300			struct ccb_scsiio *csio;
1301
1302			csio = &done_ccb->csio;
1303			cmd_info = (struct ctlfe_lun_cmd_info *)
1304				io->io_hdr.port_priv;
1305
1306			io->io_hdr.flags &= ~CTL_FLAG_DMA_INPROG;
1307
1308			io->scsiio.ext_data_len += csio->dxfer_len;
1309			if (io->scsiio.ext_data_len >
1310			    io->scsiio.kern_total_len) {
1311				xpt_print(periph->path, "%s: tag 0x%04x "
1312					  "done len %u > total %u sent %u\n",
1313					  __func__, io->scsiio.tag_num,
1314					  io->scsiio.ext_data_len,
1315					  io->scsiio.kern_total_len,
1316					  io->scsiio.ext_data_filled);
1317			}
1318			/*
1319			 * Translate CAM status to CTL status.  Success
1320			 * does not change the overall, ctl_io status.  In
1321			 * that case we just set port_status to 0.  If we
1322			 * have a failure, though, set a data phase error
1323			 * for the overall ctl_io.
1324			 */
1325			switch (done_ccb->ccb_h.status & CAM_STATUS_MASK) {
1326			case CAM_REQ_CMP:
1327				io->io_hdr.port_status = 0;
1328				break;
1329			default:
1330				/*
1331				 * XXX KDM we probably need to figure out a
1332				 * standard set of errors that the SIM
1333				 * drivers should return in the event of a
1334				 * data transfer failure.  A data phase
1335				 * error will at least point the user to a
1336				 * data transfer error of some sort.
1337				 * Hopefully the SIM printed out some
1338				 * additional information to give the user
1339				 * a clue what happened.
1340				 */
1341				io->io_hdr.port_status = 0xbad1;
1342				ctl_set_data_phase_error(&io->scsiio);
1343				/*
1344				 * XXX KDM figure out residual.
1345				 */
1346				break;
1347			}
1348			/*
1349			 * If we had to break this S/G list into multiple
1350			 * pieces, figure out where we are in the list, and
1351			 * continue sending pieces if necessary.
1352			 */
1353			if ((cmd_info->flags & CTLFE_CMD_PIECEWISE)
1354			 && (io->io_hdr.port_status == 0)) {
1355				ccb_flags flags;
1356				uint8_t scsi_status;
1357				uint8_t *data_ptr;
1358				uint32_t dxfer_len;
1359
1360				flags = atio->ccb_h.flags &
1361					(CAM_DIS_DISCONNECT|
1362					 CAM_TAG_ACTION_VALID);
1363
1364				ctlfedata(softc, io, &flags, &data_ptr,
1365				    &dxfer_len, &csio->sglist_cnt);
1366
1367				scsi_status = 0;
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_io.cdb_bytes[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					      scsi_status,
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				softc->ccbs_freed++;
1406				xpt_release_ccb(done_ccb);
1407				mtx_unlock(mtx);
1408
1409				/* Call the backend move done callback */
1410				io->scsiio.be_move_done(io);
1411			}
1412			return;
1413		}
1414		break;
1415	}
1416	case XPT_IMMEDIATE_NOTIFY: {
1417		union ctl_io *io;
1418		struct ccb_immediate_notify *inot;
1419		cam_status status;
1420		int frozen, send_ctl_io;
1421
1422		inot = &done_ccb->cin1;
1423
1424		softc->inots_returned++;
1425
1426		frozen = (done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0;
1427
1428		printf("%s: got XPT_IMMEDIATE_NOTIFY status %#x tag %#x "
1429		       "seq %#x\n", __func__, inot->ccb_h.status,
1430		       inot->tag_id, inot->seq_id);
1431
1432		io = done_ccb->ccb_h.io_ptr;
1433		ctl_zero_io(io);
1434
1435		send_ctl_io = 1;
1436
1437		io->io_hdr.io_type = CTL_IO_TASK;
1438		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr =done_ccb;
1439		inot->ccb_h.io_ptr = io;
1440		io->io_hdr.nexus.initid.id = inot->initiator_id;
1441		io->io_hdr.nexus.targ_port = bus_softc->port.targ_port;
1442		io->io_hdr.nexus.targ_target.id = inot->ccb_h.target_id;
1443		io->io_hdr.nexus.targ_lun = inot->ccb_h.target_lun;
1444		/* XXX KDM should this be the tag_id? */
1445		io->taskio.tag_num = inot->seq_id;
1446
1447		status = inot->ccb_h.status & CAM_STATUS_MASK;
1448		switch (status) {
1449		case CAM_SCSI_BUS_RESET:
1450			io->taskio.task_action = CTL_TASK_BUS_RESET;
1451			break;
1452		case CAM_BDR_SENT:
1453			io->taskio.task_action = CTL_TASK_TARGET_RESET;
1454			break;
1455		case CAM_MESSAGE_RECV:
1456			switch (inot->arg) {
1457			case MSG_ABORT_TASK_SET:
1458				io->taskio.task_action =
1459				    CTL_TASK_ABORT_TASK_SET;
1460				break;
1461			case MSG_TARGET_RESET:
1462				io->taskio.task_action =
1463					CTL_TASK_TARGET_RESET;
1464				break;
1465			case MSG_ABORT_TASK:
1466				io->taskio.task_action =
1467					CTL_TASK_ABORT_TASK;
1468				break;
1469			case MSG_LOGICAL_UNIT_RESET:
1470				io->taskio.task_action =
1471					CTL_TASK_LUN_RESET;
1472				break;
1473			case MSG_CLEAR_TASK_SET:
1474				io->taskio.task_action =
1475					CTL_TASK_CLEAR_TASK_SET;
1476				break;
1477			case MSG_CLEAR_ACA:
1478				io->taskio.task_action =
1479					CTL_TASK_CLEAR_ACA;
1480				break;
1481			case MSG_NOOP:
1482				send_ctl_io = 0;
1483				break;
1484			default:
1485				xpt_print(periph->path,
1486					  "%s: unsupported message 0x%x\n",
1487					  __func__, inot->arg);
1488				send_ctl_io = 0;
1489				break;
1490			}
1491			break;
1492		case CAM_REQ_ABORTED:
1493			/*
1494			 * This request was sent back by the driver.
1495			 * XXX KDM what do we do here?
1496			 */
1497			send_ctl_io = 0;
1498			break;
1499		case CAM_REQ_INVALID:
1500		case CAM_PROVIDE_FAIL:
1501		default:
1502			/*
1503			 * We should only get here if we're talking
1504			 * to a talking to a SIM that is target
1505			 * capable but supports the old API.  In
1506			 * that case, we need to just free the CCB.
1507			 * If we actually send a notify acknowledge,
1508			 * it will send that back with an error as
1509			 * well.
1510			 */
1511
1512			if ((status != CAM_REQ_INVALID)
1513			 && (status != CAM_PROVIDE_FAIL))
1514				xpt_print(periph->path,
1515					  "%s: unsupported CAM status 0x%x\n",
1516					  __func__, status);
1517
1518			ctlfe_free_ccb(periph, done_ccb);
1519
1520			goto out;
1521		}
1522		if (send_ctl_io != 0) {
1523			ctl_queue(io);
1524		} else {
1525			done_ccb->ccb_h.status = CAM_REQ_INPROG;
1526			done_ccb->ccb_h.func_code = XPT_NOTIFY_ACKNOWLEDGE;
1527			xpt_action(done_ccb);
1528		}
1529
1530		if (frozen != 0) {
1531			cam_release_devq(periph->path,
1532					 /*relsim_flags*/ 0,
1533					 /*opening reduction*/ 0,
1534					 /*timeout*/ 0,
1535					 /*getcount_only*/ 0);
1536		}
1537		break;
1538	}
1539	case XPT_NOTIFY_ACKNOWLEDGE:
1540		/*
1541		 * Queue this back down to the SIM as an immediate notify.
1542		 */
1543		done_ccb->ccb_h.func_code = XPT_IMMEDIATE_NOTIFY;
1544		xpt_action(done_ccb);
1545		softc->inots_sent++;
1546		break;
1547	case XPT_SET_SIM_KNOB:
1548	case XPT_GET_SIM_KNOB:
1549		break;
1550	default:
1551		panic("%s: unexpected CCB type %#x", __func__,
1552		      done_ccb->ccb_h.func_code);
1553		break;
1554	}
1555
1556out:
1557	mtx_unlock(mtx);
1558}
1559
1560static void
1561ctlfe_onoffline(void *arg, int online)
1562{
1563	struct ctlfe_softc *bus_softc;
1564	union ccb *ccb;
1565	cam_status status;
1566	struct cam_path *path;
1567	int set_wwnn;
1568
1569	bus_softc = (struct ctlfe_softc *)arg;
1570
1571	set_wwnn = 0;
1572
1573	status = xpt_create_path(&path, /*periph*/ NULL, bus_softc->path_id,
1574		CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
1575	if (status != CAM_REQ_CMP) {
1576		printf("%s: unable to create path!\n", __func__);
1577		return;
1578	}
1579	ccb = xpt_alloc_ccb();
1580	xpt_setup_ccb(&ccb->ccb_h, path, CAM_PRIORITY_NONE);
1581
1582	/*
1583	 * Copan WWN format:
1584	 *
1585	 * Bits 63-60:	0x5		NAA, IEEE registered name
1586	 * Bits 59-36:	0x000ED5	IEEE Company name assigned to Copan
1587	 * Bits 35-12:			Copan SSN (Sequential Serial Number)
1588	 * Bits 11-8:			Type of port:
1589	 *					1 == N-Port
1590	 *					2 == F-Port
1591	 *					3 == NL-Port
1592	 * Bits 7-0:			0 == Node Name, >0 == Port Number
1593	 */
1594
1595	if (online != 0) {
1596
1597		ccb->ccb_h.func_code = XPT_GET_SIM_KNOB;
1598
1599
1600		xpt_action(ccb);
1601
1602
1603		if ((ccb->knob.xport_specific.valid & KNOB_VALID_ADDRESS) != 0){
1604#ifdef RANDOM_WWNN
1605			uint64_t random_bits;
1606#endif
1607
1608			printf("%s: %s current WWNN %#jx\n", __func__,
1609			       bus_softc->port_name,
1610			       ccb->knob.xport_specific.fc.wwnn);
1611			printf("%s: %s current WWPN %#jx\n", __func__,
1612			       bus_softc->port_name,
1613			       ccb->knob.xport_specific.fc.wwpn);
1614
1615#ifdef RANDOM_WWNN
1616			arc4rand(&random_bits, sizeof(random_bits), 0);
1617#endif
1618
1619			/*
1620			 * XXX KDM this is a bit of a kludge for now.  We
1621			 * take the current WWNN/WWPN from the card, and
1622			 * replace the company identifier and the NL-Port
1623			 * indicator and the port number (for the WWPN).
1624			 * This should be replaced later with ddb_GetWWNN,
1625			 * or possibly a more centralized scheme.  (It
1626			 * would be nice to have the WWNN/WWPN for each
1627			 * port stored in the ctl_port structure.)
1628			 */
1629#ifdef RANDOM_WWNN
1630			ccb->knob.xport_specific.fc.wwnn =
1631				(random_bits &
1632				0x0000000fffffff00ULL) |
1633				/* Company ID */ 0x5000ED5000000000ULL |
1634				/* NL-Port */    0x0300;
1635			ccb->knob.xport_specific.fc.wwpn =
1636				(random_bits &
1637				0x0000000fffffff00ULL) |
1638				/* Company ID */ 0x5000ED5000000000ULL |
1639				/* NL-Port */    0x3000 |
1640				/* Port Num */ (bus_softc->port.targ_port & 0xff);
1641
1642			/*
1643			 * This is a bit of an API break/reversal, but if
1644			 * we're doing the random WWNN that's a little
1645			 * different anyway.  So record what we're actually
1646			 * using with the frontend code so it's reported
1647			 * accurately.
1648			 */
1649			ctl_port_set_wwns(&bus_softc->port,
1650			    true, ccb->knob.xport_specific.fc.wwnn,
1651			    true, ccb->knob.xport_specific.fc.wwpn);
1652			set_wwnn = 1;
1653#else /* RANDOM_WWNN */
1654			/*
1655			 * If the user has specified a WWNN/WWPN, send them
1656			 * down to the SIM.  Otherwise, record what the SIM
1657			 * has reported.
1658			 */
1659			if ((bus_softc->port.wwnn != 0)
1660			 && (bus_softc->port.wwpn != 0)) {
1661				ccb->knob.xport_specific.fc.wwnn =
1662					bus_softc->port.wwnn;
1663				ccb->knob.xport_specific.fc.wwpn =
1664					bus_softc->port.wwpn;
1665				set_wwnn = 1;
1666			} else {
1667				ctl_port_set_wwns(&bus_softc->port,
1668				    true, ccb->knob.xport_specific.fc.wwnn,
1669				    true, ccb->knob.xport_specific.fc.wwpn);
1670			}
1671#endif /* RANDOM_WWNN */
1672
1673
1674			if (set_wwnn != 0) {
1675				printf("%s: %s new WWNN %#jx\n", __func__,
1676				       bus_softc->port_name,
1677				ccb->knob.xport_specific.fc.wwnn);
1678				printf("%s: %s new WWPN %#jx\n", __func__,
1679				       bus_softc->port_name,
1680				       ccb->knob.xport_specific.fc.wwpn);
1681			}
1682		} else {
1683			printf("%s: %s has no valid WWNN/WWPN\n", __func__,
1684			       bus_softc->port_name);
1685		}
1686	}
1687	ccb->ccb_h.func_code = XPT_SET_SIM_KNOB;
1688	ccb->knob.xport_specific.valid = KNOB_VALID_ROLE;
1689	if (set_wwnn != 0)
1690		ccb->knob.xport_specific.valid |= KNOB_VALID_ADDRESS;
1691
1692	if (online != 0)
1693		ccb->knob.xport_specific.fc.role = KNOB_ROLE_TARGET;
1694	else
1695		ccb->knob.xport_specific.fc.role = KNOB_ROLE_NONE;
1696
1697	xpt_action(ccb);
1698
1699	if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1700		printf("%s: SIM %s (path id %d) target %s failed with "
1701		       "status %#x\n",
1702		       __func__, bus_softc->port_name, bus_softc->path_id,
1703		       (online != 0) ? "enable" : "disable",
1704		       ccb->ccb_h.status);
1705	} else {
1706		printf("%s: SIM %s (path id %d) target %s succeeded\n",
1707		       __func__, bus_softc->port_name, bus_softc->path_id,
1708		       (online != 0) ? "enable" : "disable");
1709	}
1710
1711	xpt_free_path(path);
1712	xpt_free_ccb(ccb);
1713}
1714
1715static void
1716ctlfe_online(void *arg)
1717{
1718	struct ctlfe_softc *bus_softc;
1719	struct cam_path *path;
1720	cam_status status;
1721	struct ctlfe_lun_softc *lun_softc;
1722	struct cam_periph *periph;
1723
1724	bus_softc = (struct ctlfe_softc *)arg;
1725
1726	/*
1727	 * Create the wildcard LUN before bringing the port online.
1728	 */
1729	status = xpt_create_path(&path, /*periph*/ NULL,
1730				 bus_softc->path_id, CAM_TARGET_WILDCARD,
1731				 CAM_LUN_WILDCARD);
1732	if (status != CAM_REQ_CMP) {
1733		printf("%s: unable to create path for wildcard periph\n",
1734				__func__);
1735		return;
1736	}
1737
1738	lun_softc = malloc(sizeof(*lun_softc), M_CTLFE, M_WAITOK | M_ZERO);
1739
1740	xpt_path_lock(path);
1741	periph = cam_periph_find(path, "ctl");
1742	if (periph != NULL) {
1743		/* We've already got a periph, no need to alloc a new one. */
1744		xpt_path_unlock(path);
1745		xpt_free_path(path);
1746		free(lun_softc, M_CTLFE);
1747		return;
1748	}
1749	lun_softc->parent_softc = bus_softc;
1750	lun_softc->flags |= CTLFE_LUN_WILDCARD;
1751
1752	status = cam_periph_alloc(ctlferegister,
1753				  ctlfeoninvalidate,
1754				  ctlfecleanup,
1755				  ctlfestart,
1756				  "ctl",
1757				  CAM_PERIPH_BIO,
1758				  path,
1759				  ctlfeasync,
1760				  0,
1761				  lun_softc);
1762
1763	if ((status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1764		const struct cam_status_entry *entry;
1765
1766		entry = cam_fetch_status_entry(status);
1767		printf("%s: CAM error %s (%#x) returned from "
1768		       "cam_periph_alloc()\n", __func__, (entry != NULL) ?
1769		       entry->status_text : "Unknown", status);
1770		free(lun_softc, M_CTLFE);
1771	}
1772
1773	xpt_path_unlock(path);
1774	ctlfe_onoffline(arg, /*online*/ 1);
1775	xpt_free_path(path);
1776}
1777
1778static void
1779ctlfe_offline(void *arg)
1780{
1781	struct ctlfe_softc *bus_softc;
1782	struct cam_path *path;
1783	cam_status status;
1784	struct cam_periph *periph;
1785
1786	bus_softc = (struct ctlfe_softc *)arg;
1787
1788	ctlfe_onoffline(arg, /*online*/ 0);
1789
1790	/*
1791	 * Disable the wildcard LUN for this port now that we have taken
1792	 * the port offline.
1793	 */
1794	status = xpt_create_path(&path, /*periph*/ NULL,
1795				 bus_softc->path_id, CAM_TARGET_WILDCARD,
1796				 CAM_LUN_WILDCARD);
1797	if (status != CAM_REQ_CMP) {
1798		printf("%s: unable to create path for wildcard periph\n",
1799		       __func__);
1800		return;
1801	}
1802	xpt_path_lock(path);
1803	if ((periph = cam_periph_find(path, "ctl")) != NULL)
1804		cam_periph_invalidate(periph);
1805	xpt_path_unlock(path);
1806	xpt_free_path(path);
1807}
1808
1809/*
1810 * This will get called to enable a LUN on every bus that is attached to
1811 * CTL.  So we only need to create a path/periph for this particular bus.
1812 */
1813static int
1814ctlfe_lun_enable(void *arg, struct ctl_id targ_id, int lun_id)
1815{
1816	struct ctlfe_softc *bus_softc;
1817	struct ctlfe_lun_softc *softc;
1818	struct cam_path *path;
1819	struct cam_periph *periph;
1820	cam_status status;
1821
1822	bus_softc = (struct ctlfe_softc *)arg;
1823
1824	status = xpt_create_path(&path, /*periph*/ NULL,
1825				  bus_softc->path_id,
1826				  targ_id.id, lun_id);
1827	/* XXX KDM need some way to return status to CTL here? */
1828	if (status != CAM_REQ_CMP) {
1829		printf("%s: could not create path, status %#x\n", __func__,
1830		       status);
1831		return (1);
1832	}
1833
1834	softc = malloc(sizeof(*softc), M_CTLFE, M_WAITOK | M_ZERO);
1835	xpt_path_lock(path);
1836	periph = cam_periph_find(path, "ctl");
1837	if (periph != NULL) {
1838		/* We've already got a periph, no need to alloc a new one. */
1839		xpt_path_unlock(path);
1840		xpt_free_path(path);
1841		free(softc, M_CTLFE);
1842		return (0);
1843	}
1844	softc->parent_softc = bus_softc;
1845
1846	status = cam_periph_alloc(ctlferegister,
1847				  ctlfeoninvalidate,
1848				  ctlfecleanup,
1849				  ctlfestart,
1850				  "ctl",
1851				  CAM_PERIPH_BIO,
1852				  path,
1853				  ctlfeasync,
1854				  0,
1855				  softc);
1856
1857	if ((status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1858		const struct cam_status_entry *entry;
1859
1860		entry = cam_fetch_status_entry(status);
1861		printf("%s: CAM error %s (%#x) returned from "
1862		       "cam_periph_alloc()\n", __func__, (entry != NULL) ?
1863		       entry->status_text : "Unknown", status);
1864		free(softc, M_CTLFE);
1865	}
1866
1867	xpt_path_unlock(path);
1868	xpt_free_path(path);
1869	return (0);
1870}
1871
1872/*
1873 * This will get called when the user removes a LUN to disable that LUN
1874 * on every bus that is attached to CTL.
1875 */
1876static int
1877ctlfe_lun_disable(void *arg, struct ctl_id targ_id, int lun_id)
1878{
1879	struct ctlfe_softc *softc;
1880	struct ctlfe_lun_softc *lun_softc;
1881
1882	softc = (struct ctlfe_softc *)arg;
1883
1884	mtx_lock(&softc->lun_softc_mtx);
1885	STAILQ_FOREACH(lun_softc, &softc->lun_softc_list, links) {
1886		struct cam_path *path;
1887
1888		path = lun_softc->periph->path;
1889
1890		if ((xpt_path_target_id(path) == targ_id.id)
1891		 && (xpt_path_lun_id(path) == lun_id)) {
1892			break;
1893		}
1894	}
1895	if (lun_softc == NULL) {
1896		mtx_unlock(&softc->lun_softc_mtx);
1897		printf("%s: can't find target %d lun %d\n", __func__,
1898		       targ_id.id, lun_id);
1899		return (1);
1900	}
1901	cam_periph_acquire(lun_softc->periph);
1902	mtx_unlock(&softc->lun_softc_mtx);
1903
1904	cam_periph_lock(lun_softc->periph);
1905	cam_periph_invalidate(lun_softc->periph);
1906	cam_periph_unlock(lun_softc->periph);
1907	cam_periph_release(lun_softc->periph);
1908	return (0);
1909}
1910
1911static void
1912ctlfe_dump_sim(struct cam_sim *sim)
1913{
1914
1915	printf("%s%d: max tagged openings: %d, max dev openings: %d\n",
1916	       sim->sim_name, sim->unit_number,
1917	       sim->max_tagged_dev_openings, sim->max_dev_openings);
1918}
1919
1920/*
1921 * Assumes that the SIM lock is held.
1922 */
1923static void
1924ctlfe_dump_queue(struct ctlfe_lun_softc *softc)
1925{
1926	struct ccb_hdr *hdr;
1927	struct cam_periph *periph;
1928	int num_items;
1929
1930	periph = softc->periph;
1931	num_items = 0;
1932
1933	TAILQ_FOREACH(hdr, &softc->work_queue, periph_links.tqe) {
1934		union ctl_io *io = hdr->io_ptr;
1935
1936		num_items++;
1937
1938		/*
1939		 * Only regular SCSI I/O is put on the work
1940		 * queue, so we can print sense here.  There may be no
1941		 * sense if it's no the queue for a DMA, but this serves to
1942		 * print out the CCB as well.
1943		 *
1944		 * XXX KDM switch this over to scsi_sense_print() when
1945		 * CTL is merged in with CAM.
1946		 */
1947		ctl_io_error_print(io, NULL);
1948
1949		/*
1950		 * Print DMA status if we are DMA_QUEUED.
1951		 */
1952		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED) {
1953			xpt_print(periph->path,
1954			    "Total %u, Current %u, Resid %u\n",
1955			    io->scsiio.kern_total_len,
1956			    io->scsiio.kern_data_len,
1957			    io->scsiio.kern_data_resid);
1958		}
1959	}
1960
1961	xpt_print(periph->path, "%d requests total waiting for CCBs\n",
1962		  num_items);
1963	xpt_print(periph->path, "%ju CCBs outstanding (%ju allocated, %ju "
1964		  "freed)\n", (uintmax_t)(softc->ccbs_alloced -
1965		  softc->ccbs_freed), (uintmax_t)softc->ccbs_alloced,
1966		  (uintmax_t)softc->ccbs_freed);
1967	xpt_print(periph->path, "%ju CTIOs outstanding (%ju sent, %ju "
1968		  "returned\n", (uintmax_t)(softc->ctios_sent -
1969		  softc->ctios_returned), softc->ctios_sent,
1970		  softc->ctios_returned);
1971}
1972
1973/*
1974 * Datamove/done routine called by CTL.  Put ourselves on the queue to
1975 * receive a CCB from CAM so we can queue the continue I/O request down
1976 * to the adapter.
1977 */
1978static void
1979ctlfe_datamove(union ctl_io *io)
1980{
1981	union ccb *ccb;
1982	struct cam_periph *periph;
1983	struct ctlfe_lun_softc *softc;
1984
1985	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
1986	    ("Unexpected io_type (%d) in ctlfe_datamove", io->io_hdr.io_type));
1987
1988	ccb = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
1989	periph = xpt_path_periph(ccb->ccb_h.path);
1990	cam_periph_lock(periph);
1991	softc = (struct ctlfe_lun_softc *)periph->softc;
1992	io->io_hdr.flags |= CTL_FLAG_DMA_QUEUED;
1993	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE)
1994		io->io_hdr.flags |= CTL_FLAG_STATUS_QUEUED;
1995	TAILQ_INSERT_TAIL(&softc->work_queue, &ccb->ccb_h,
1996			  periph_links.tqe);
1997	xpt_schedule(periph, /*priority*/ 1);
1998	cam_periph_unlock(periph);
1999}
2000
2001static void
2002ctlfe_done(union ctl_io *io)
2003{
2004	union ccb *ccb;
2005	struct cam_periph *periph;
2006	struct ctlfe_lun_softc *softc;
2007
2008	ccb = io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2009	periph = xpt_path_periph(ccb->ccb_h.path);
2010	cam_periph_lock(periph);
2011	softc = (struct ctlfe_lun_softc *)periph->softc;
2012
2013	if (io->io_hdr.io_type == CTL_IO_TASK) {
2014		/*
2015		 * Task management commands don't require any further
2016		 * communication back to the adapter.  Requeue the CCB
2017		 * to the adapter, and free the CTL I/O.
2018		 */
2019		xpt_print(ccb->ccb_h.path, "%s: returning task I/O "
2020			  "tag %#x seq %#x\n", __func__,
2021			  ccb->cin1.tag_id, ccb->cin1.seq_id);
2022		/*
2023		 * Send the notify acknowledge down to the SIM, to let it
2024		 * know we processed the task management command.
2025		 */
2026		ccb->ccb_h.status = CAM_REQ_INPROG;
2027		ccb->ccb_h.func_code = XPT_NOTIFY_ACKNOWLEDGE;
2028		xpt_action(ccb);
2029	} else if (io->io_hdr.flags & CTL_FLAG_STATUS_SENT) {
2030		if (softc->flags & CTLFE_LUN_WILDCARD) {
2031			ccb->ccb_h.target_id = CAM_TARGET_WILDCARD;
2032			ccb->ccb_h.target_lun = CAM_LUN_WILDCARD;
2033		}
2034		if (periph->flags & CAM_PERIPH_INVALID) {
2035			ctlfe_free_ccb(periph, ccb);
2036		} else {
2037			softc->atios_sent++;
2038			cam_periph_unlock(periph);
2039			xpt_action(ccb);
2040			return;
2041		}
2042	} else {
2043		io->io_hdr.flags |= CTL_FLAG_STATUS_QUEUED;
2044		TAILQ_INSERT_TAIL(&softc->work_queue, &ccb->ccb_h,
2045				  periph_links.tqe);
2046		xpt_schedule(periph, /*priority*/ 1);
2047	}
2048
2049	cam_periph_unlock(periph);
2050}
2051
2052static void
2053ctlfe_dump(void)
2054{
2055	struct ctlfe_softc *bus_softc;
2056	struct ctlfe_lun_softc *lun_softc;
2057
2058	STAILQ_FOREACH(bus_softc, &ctlfe_softc_list, links) {
2059		ctlfe_dump_sim(bus_softc->sim);
2060		STAILQ_FOREACH(lun_softc, &bus_softc->lun_softc_list, links)
2061			ctlfe_dump_queue(lun_softc);
2062	}
2063}
2064