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