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