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