xref: /freebsd/sys/cam/cam_xpt.c (revision 83d9fd40d5cb67ff1e805523a6fae48c3389f396)
1 /*-
2  * Implementation of the Common Access Method Transport (XPT) layer.
3  *
4  * Copyright (c) 1997, 1998, 1999 Justin T. Gibbs.
5  * Copyright (c) 1997, 1998, 1999 Kenneth D. Merry.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions, and the following disclaimer,
13  *    without modification, immediately at the beginning of the file.
14  * 2. The name of the author may not be used to endorse or promote products
15  *    derived from this software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
21  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 #include "opt_printf.h"
31 
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
34 
35 #include <sys/param.h>
36 #include <sys/bio.h>
37 #include <sys/bus.h>
38 #include <sys/systm.h>
39 #include <sys/types.h>
40 #include <sys/malloc.h>
41 #include <sys/kernel.h>
42 #include <sys/time.h>
43 #include <sys/conf.h>
44 #include <sys/fcntl.h>
45 #include <sys/interrupt.h>
46 #include <sys/proc.h>
47 #include <sys/sbuf.h>
48 #include <sys/smp.h>
49 #include <sys/taskqueue.h>
50 
51 #include <sys/lock.h>
52 #include <sys/mutex.h>
53 #include <sys/sysctl.h>
54 #include <sys/kthread.h>
55 
56 #include <cam/cam.h>
57 #include <cam/cam_ccb.h>
58 #include <cam/cam_periph.h>
59 #include <cam/cam_queue.h>
60 #include <cam/cam_sim.h>
61 #include <cam/cam_xpt.h>
62 #include <cam/cam_xpt_sim.h>
63 #include <cam/cam_xpt_periph.h>
64 #include <cam/cam_xpt_internal.h>
65 #include <cam/cam_debug.h>
66 #include <cam/cam_compat.h>
67 
68 #include <cam/scsi/scsi_all.h>
69 #include <cam/scsi/scsi_message.h>
70 #include <cam/scsi/scsi_pass.h>
71 
72 #include <machine/md_var.h>	/* geometry translation */
73 #include <machine/stdarg.h>	/* for xpt_print below */
74 
75 #include "opt_cam.h"
76 
77 /* Wild guess based on not wanting to grow the stack too much */
78 #define XPT_PRINT_MAXLEN	512
79 #ifdef PRINTF_BUFR_SIZE
80 #define XPT_PRINT_LEN	PRINTF_BUFR_SIZE
81 #else
82 #define XPT_PRINT_LEN	128
83 #endif
84 _Static_assert(XPT_PRINT_LEN <= XPT_PRINT_MAXLEN, "XPT_PRINT_LEN is too large");
85 
86 /*
87  * This is the maximum number of high powered commands (e.g. start unit)
88  * that can be outstanding at a particular time.
89  */
90 #ifndef CAM_MAX_HIGHPOWER
91 #define CAM_MAX_HIGHPOWER  4
92 #endif
93 
94 /* Datastructures internal to the xpt layer */
95 MALLOC_DEFINE(M_CAMXPT, "CAM XPT", "CAM XPT buffers");
96 MALLOC_DEFINE(M_CAMDEV, "CAM DEV", "CAM devices");
97 MALLOC_DEFINE(M_CAMCCB, "CAM CCB", "CAM CCBs");
98 MALLOC_DEFINE(M_CAMPATH, "CAM path", "CAM paths");
99 
100 /* Object for defering XPT actions to a taskqueue */
101 struct xpt_task {
102 	struct task	task;
103 	void		*data1;
104 	uintptr_t	data2;
105 };
106 
107 struct xpt_softc {
108 	uint32_t		xpt_generation;
109 
110 	/* number of high powered commands that can go through right now */
111 	struct mtx		xpt_highpower_lock;
112 	STAILQ_HEAD(highpowerlist, cam_ed)	highpowerq;
113 	int			num_highpower;
114 
115 	/* queue for handling async rescan requests. */
116 	TAILQ_HEAD(, ccb_hdr) ccb_scanq;
117 	int buses_to_config;
118 	int buses_config_done;
119 
120 	/*
121 	 * Registered buses
122 	 *
123 	 * N.B., "busses" is an archaic spelling of "buses".  In new code
124 	 * "buses" is preferred.
125 	 */
126 	TAILQ_HEAD(,cam_eb)	xpt_busses;
127 	u_int			bus_generation;
128 
129 	struct intr_config_hook	*xpt_config_hook;
130 
131 	int			boot_delay;
132 	struct callout 		boot_callout;
133 
134 	struct mtx		xpt_topo_lock;
135 	struct mtx		xpt_lock;
136 	struct taskqueue	*xpt_taskq;
137 };
138 
139 typedef enum {
140 	DM_RET_COPY		= 0x01,
141 	DM_RET_FLAG_MASK	= 0x0f,
142 	DM_RET_NONE		= 0x00,
143 	DM_RET_STOP		= 0x10,
144 	DM_RET_DESCEND		= 0x20,
145 	DM_RET_ERROR		= 0x30,
146 	DM_RET_ACTION_MASK	= 0xf0
147 } dev_match_ret;
148 
149 typedef enum {
150 	XPT_DEPTH_BUS,
151 	XPT_DEPTH_TARGET,
152 	XPT_DEPTH_DEVICE,
153 	XPT_DEPTH_PERIPH
154 } xpt_traverse_depth;
155 
156 struct xpt_traverse_config {
157 	xpt_traverse_depth	depth;
158 	void			*tr_func;
159 	void			*tr_arg;
160 };
161 
162 typedef	int	xpt_busfunc_t (struct cam_eb *bus, void *arg);
163 typedef	int	xpt_targetfunc_t (struct cam_et *target, void *arg);
164 typedef	int	xpt_devicefunc_t (struct cam_ed *device, void *arg);
165 typedef	int	xpt_periphfunc_t (struct cam_periph *periph, void *arg);
166 typedef int	xpt_pdrvfunc_t (struct periph_driver **pdrv, void *arg);
167 
168 /* Transport layer configuration information */
169 static struct xpt_softc xsoftc;
170 
171 MTX_SYSINIT(xpt_topo_init, &xsoftc.xpt_topo_lock, "XPT topology lock", MTX_DEF);
172 
173 SYSCTL_INT(_kern_cam, OID_AUTO, boot_delay, CTLFLAG_RDTUN,
174            &xsoftc.boot_delay, 0, "Bus registration wait time");
175 SYSCTL_UINT(_kern_cam, OID_AUTO, xpt_generation, CTLFLAG_RD,
176 	    &xsoftc.xpt_generation, 0, "CAM peripheral generation count");
177 
178 struct cam_doneq {
179 	struct mtx_padalign	cam_doneq_mtx;
180 	STAILQ_HEAD(, ccb_hdr)	cam_doneq;
181 	int			cam_doneq_sleep;
182 };
183 
184 static struct cam_doneq cam_doneqs[MAXCPU];
185 static int cam_num_doneqs;
186 static struct proc *cam_proc;
187 
188 SYSCTL_INT(_kern_cam, OID_AUTO, num_doneqs, CTLFLAG_RDTUN,
189            &cam_num_doneqs, 0, "Number of completion queues/threads");
190 
191 struct cam_periph *xpt_periph;
192 
193 static periph_init_t xpt_periph_init;
194 
195 static struct periph_driver xpt_driver =
196 {
197 	xpt_periph_init, "xpt",
198 	TAILQ_HEAD_INITIALIZER(xpt_driver.units), /* generation */ 0,
199 	CAM_PERIPH_DRV_EARLY
200 };
201 
202 PERIPHDRIVER_DECLARE(xpt, xpt_driver);
203 
204 static d_open_t xptopen;
205 static d_close_t xptclose;
206 static d_ioctl_t xptioctl;
207 static d_ioctl_t xptdoioctl;
208 
209 static struct cdevsw xpt_cdevsw = {
210 	.d_version =	D_VERSION,
211 	.d_flags =	0,
212 	.d_open =	xptopen,
213 	.d_close =	xptclose,
214 	.d_ioctl =	xptioctl,
215 	.d_name =	"xpt",
216 };
217 
218 /* Storage for debugging datastructures */
219 struct cam_path *cam_dpath;
220 u_int32_t cam_dflags = CAM_DEBUG_FLAGS;
221 SYSCTL_UINT(_kern_cam, OID_AUTO, dflags, CTLFLAG_RWTUN,
222 	&cam_dflags, 0, "Enabled debug flags");
223 u_int32_t cam_debug_delay = CAM_DEBUG_DELAY;
224 SYSCTL_UINT(_kern_cam, OID_AUTO, debug_delay, CTLFLAG_RWTUN,
225 	&cam_debug_delay, 0, "Delay in us after each debug message");
226 
227 /* Our boot-time initialization hook */
228 static int cam_module_event_handler(module_t, int /*modeventtype_t*/, void *);
229 
230 static moduledata_t cam_moduledata = {
231 	"cam",
232 	cam_module_event_handler,
233 	NULL
234 };
235 
236 static int	xpt_init(void *);
237 
238 DECLARE_MODULE(cam, cam_moduledata, SI_SUB_CONFIGURE, SI_ORDER_SECOND);
239 MODULE_VERSION(cam, 1);
240 
241 
242 static void		xpt_async_bcast(struct async_list *async_head,
243 					u_int32_t async_code,
244 					struct cam_path *path,
245 					void *async_arg);
246 static path_id_t xptnextfreepathid(void);
247 static path_id_t xptpathid(const char *sim_name, int sim_unit, int sim_bus);
248 static union ccb *xpt_get_ccb(struct cam_periph *periph);
249 static union ccb *xpt_get_ccb_nowait(struct cam_periph *periph);
250 static void	 xpt_run_allocq(struct cam_periph *periph, int sleep);
251 static void	 xpt_run_allocq_task(void *context, int pending);
252 static void	 xpt_run_devq(struct cam_devq *devq);
253 static timeout_t xpt_release_devq_timeout;
254 static void	 xpt_release_simq_timeout(void *arg) __unused;
255 static void	 xpt_acquire_bus(struct cam_eb *bus);
256 static void	 xpt_release_bus(struct cam_eb *bus);
257 static uint32_t	 xpt_freeze_devq_device(struct cam_ed *dev, u_int count);
258 static int	 xpt_release_devq_device(struct cam_ed *dev, u_int count,
259 		    int run_queue);
260 static struct cam_et*
261 		 xpt_alloc_target(struct cam_eb *bus, target_id_t target_id);
262 static void	 xpt_acquire_target(struct cam_et *target);
263 static void	 xpt_release_target(struct cam_et *target);
264 static struct cam_eb*
265 		 xpt_find_bus(path_id_t path_id);
266 static struct cam_et*
267 		 xpt_find_target(struct cam_eb *bus, target_id_t target_id);
268 static struct cam_ed*
269 		 xpt_find_device(struct cam_et *target, lun_id_t lun_id);
270 static void	 xpt_config(void *arg);
271 static int	 xpt_schedule_dev(struct camq *queue, cam_pinfo *dev_pinfo,
272 				 u_int32_t new_priority);
273 static xpt_devicefunc_t xptpassannouncefunc;
274 static void	 xptaction(struct cam_sim *sim, union ccb *work_ccb);
275 static void	 xptpoll(struct cam_sim *sim);
276 static void	 camisr_runqueue(void);
277 static void	 xpt_done_process(struct ccb_hdr *ccb_h);
278 static void	 xpt_done_td(void *);
279 static dev_match_ret	xptbusmatch(struct dev_match_pattern *patterns,
280 				    u_int num_patterns, struct cam_eb *bus);
281 static dev_match_ret	xptdevicematch(struct dev_match_pattern *patterns,
282 				       u_int num_patterns,
283 				       struct cam_ed *device);
284 static dev_match_ret	xptperiphmatch(struct dev_match_pattern *patterns,
285 				       u_int num_patterns,
286 				       struct cam_periph *periph);
287 static xpt_busfunc_t	xptedtbusfunc;
288 static xpt_targetfunc_t	xptedttargetfunc;
289 static xpt_devicefunc_t	xptedtdevicefunc;
290 static xpt_periphfunc_t	xptedtperiphfunc;
291 static xpt_pdrvfunc_t	xptplistpdrvfunc;
292 static xpt_periphfunc_t	xptplistperiphfunc;
293 static int		xptedtmatch(struct ccb_dev_match *cdm);
294 static int		xptperiphlistmatch(struct ccb_dev_match *cdm);
295 static int		xptbustraverse(struct cam_eb *start_bus,
296 				       xpt_busfunc_t *tr_func, void *arg);
297 static int		xpttargettraverse(struct cam_eb *bus,
298 					  struct cam_et *start_target,
299 					  xpt_targetfunc_t *tr_func, void *arg);
300 static int		xptdevicetraverse(struct cam_et *target,
301 					  struct cam_ed *start_device,
302 					  xpt_devicefunc_t *tr_func, void *arg);
303 static int		xptperiphtraverse(struct cam_ed *device,
304 					  struct cam_periph *start_periph,
305 					  xpt_periphfunc_t *tr_func, void *arg);
306 static int		xptpdrvtraverse(struct periph_driver **start_pdrv,
307 					xpt_pdrvfunc_t *tr_func, void *arg);
308 static int		xptpdperiphtraverse(struct periph_driver **pdrv,
309 					    struct cam_periph *start_periph,
310 					    xpt_periphfunc_t *tr_func,
311 					    void *arg);
312 static xpt_busfunc_t	xptdefbusfunc;
313 static xpt_targetfunc_t	xptdeftargetfunc;
314 static xpt_devicefunc_t	xptdefdevicefunc;
315 static xpt_periphfunc_t	xptdefperiphfunc;
316 static void		xpt_finishconfig_task(void *context, int pending);
317 static void		xpt_dev_async_default(u_int32_t async_code,
318 					      struct cam_eb *bus,
319 					      struct cam_et *target,
320 					      struct cam_ed *device,
321 					      void *async_arg);
322 static struct cam_ed *	xpt_alloc_device_default(struct cam_eb *bus,
323 						 struct cam_et *target,
324 						 lun_id_t lun_id);
325 static xpt_devicefunc_t	xptsetasyncfunc;
326 static xpt_busfunc_t	xptsetasyncbusfunc;
327 static cam_status	xptregister(struct cam_periph *periph,
328 				    void *arg);
329 static const char *	xpt_action_name(uint32_t action);
330 static __inline int device_is_queued(struct cam_ed *device);
331 
332 static __inline int
333 xpt_schedule_devq(struct cam_devq *devq, struct cam_ed *dev)
334 {
335 	int	retval;
336 
337 	mtx_assert(&devq->send_mtx, MA_OWNED);
338 	if ((dev->ccbq.queue.entries > 0) &&
339 	    (dev->ccbq.dev_openings > 0) &&
340 	    (dev->ccbq.queue.qfrozen_cnt == 0)) {
341 		/*
342 		 * The priority of a device waiting for controller
343 		 * resources is that of the highest priority CCB
344 		 * enqueued.
345 		 */
346 		retval =
347 		    xpt_schedule_dev(&devq->send_queue,
348 				     &dev->devq_entry,
349 				     CAMQ_GET_PRIO(&dev->ccbq.queue));
350 	} else {
351 		retval = 0;
352 	}
353 	return (retval);
354 }
355 
356 static __inline int
357 device_is_queued(struct cam_ed *device)
358 {
359 	return (device->devq_entry.index != CAM_UNQUEUED_INDEX);
360 }
361 
362 static void
363 xpt_periph_init()
364 {
365 	make_dev(&xpt_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600, "xpt0");
366 }
367 
368 static int
369 xptopen(struct cdev *dev, int flags, int fmt, struct thread *td)
370 {
371 
372 	/*
373 	 * Only allow read-write access.
374 	 */
375 	if (((flags & FWRITE) == 0) || ((flags & FREAD) == 0))
376 		return(EPERM);
377 
378 	/*
379 	 * We don't allow nonblocking access.
380 	 */
381 	if ((flags & O_NONBLOCK) != 0) {
382 		printf("%s: can't do nonblocking access\n", devtoname(dev));
383 		return(ENODEV);
384 	}
385 
386 	return(0);
387 }
388 
389 static int
390 xptclose(struct cdev *dev, int flag, int fmt, struct thread *td)
391 {
392 
393 	return(0);
394 }
395 
396 /*
397  * Don't automatically grab the xpt softc lock here even though this is going
398  * through the xpt device.  The xpt device is really just a back door for
399  * accessing other devices and SIMs, so the right thing to do is to grab
400  * the appropriate SIM lock once the bus/SIM is located.
401  */
402 static int
403 xptioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag, struct thread *td)
404 {
405 	int error;
406 
407 	if ((error = xptdoioctl(dev, cmd, addr, flag, td)) == ENOTTY) {
408 		error = cam_compat_ioctl(dev, cmd, addr, flag, td, xptdoioctl);
409 	}
410 	return (error);
411 }
412 
413 static int
414 xptdoioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag, struct thread *td)
415 {
416 	int error;
417 
418 	error = 0;
419 
420 	switch(cmd) {
421 	/*
422 	 * For the transport layer CAMIOCOMMAND ioctl, we really only want
423 	 * to accept CCB types that don't quite make sense to send through a
424 	 * passthrough driver. XPT_PATH_INQ is an exception to this, as stated
425 	 * in the CAM spec.
426 	 */
427 	case CAMIOCOMMAND: {
428 		union ccb *ccb;
429 		union ccb *inccb;
430 		struct cam_eb *bus;
431 
432 		inccb = (union ccb *)addr;
433 #if defined(BUF_TRACKING) || defined(FULL_BUF_TRACKING)
434 		if (inccb->ccb_h.func_code == XPT_SCSI_IO)
435 			inccb->csio.bio = NULL;
436 #endif
437 
438 		if (inccb->ccb_h.flags & CAM_UNLOCKED)
439 			return (EINVAL);
440 
441 		bus = xpt_find_bus(inccb->ccb_h.path_id);
442 		if (bus == NULL)
443 			return (EINVAL);
444 
445 		switch (inccb->ccb_h.func_code) {
446 		case XPT_SCAN_BUS:
447 		case XPT_RESET_BUS:
448 			if (inccb->ccb_h.target_id != CAM_TARGET_WILDCARD ||
449 			    inccb->ccb_h.target_lun != CAM_LUN_WILDCARD) {
450 				xpt_release_bus(bus);
451 				return (EINVAL);
452 			}
453 			break;
454 		case XPT_SCAN_TGT:
455 			if (inccb->ccb_h.target_id == CAM_TARGET_WILDCARD ||
456 			    inccb->ccb_h.target_lun != CAM_LUN_WILDCARD) {
457 				xpt_release_bus(bus);
458 				return (EINVAL);
459 			}
460 			break;
461 		default:
462 			break;
463 		}
464 
465 		switch(inccb->ccb_h.func_code) {
466 		case XPT_SCAN_BUS:
467 		case XPT_RESET_BUS:
468 		case XPT_PATH_INQ:
469 		case XPT_ENG_INQ:
470 		case XPT_SCAN_LUN:
471 		case XPT_SCAN_TGT:
472 
473 			ccb = xpt_alloc_ccb();
474 
475 			/*
476 			 * Create a path using the bus, target, and lun the
477 			 * user passed in.
478 			 */
479 			if (xpt_create_path(&ccb->ccb_h.path, NULL,
480 					    inccb->ccb_h.path_id,
481 					    inccb->ccb_h.target_id,
482 					    inccb->ccb_h.target_lun) !=
483 					    CAM_REQ_CMP){
484 				error = EINVAL;
485 				xpt_free_ccb(ccb);
486 				break;
487 			}
488 			/* Ensure all of our fields are correct */
489 			xpt_setup_ccb(&ccb->ccb_h, ccb->ccb_h.path,
490 				      inccb->ccb_h.pinfo.priority);
491 			xpt_merge_ccb(ccb, inccb);
492 			xpt_path_lock(ccb->ccb_h.path);
493 			cam_periph_runccb(ccb, NULL, 0, 0, NULL);
494 			xpt_path_unlock(ccb->ccb_h.path);
495 			bcopy(ccb, inccb, sizeof(union ccb));
496 			xpt_free_path(ccb->ccb_h.path);
497 			xpt_free_ccb(ccb);
498 			break;
499 
500 		case XPT_DEBUG: {
501 			union ccb ccb;
502 
503 			/*
504 			 * This is an immediate CCB, so it's okay to
505 			 * allocate it on the stack.
506 			 */
507 
508 			/*
509 			 * Create a path using the bus, target, and lun the
510 			 * user passed in.
511 			 */
512 			if (xpt_create_path(&ccb.ccb_h.path, NULL,
513 					    inccb->ccb_h.path_id,
514 					    inccb->ccb_h.target_id,
515 					    inccb->ccb_h.target_lun) !=
516 					    CAM_REQ_CMP){
517 				error = EINVAL;
518 				break;
519 			}
520 			/* Ensure all of our fields are correct */
521 			xpt_setup_ccb(&ccb.ccb_h, ccb.ccb_h.path,
522 				      inccb->ccb_h.pinfo.priority);
523 			xpt_merge_ccb(&ccb, inccb);
524 			xpt_action(&ccb);
525 			bcopy(&ccb, inccb, sizeof(union ccb));
526 			xpt_free_path(ccb.ccb_h.path);
527 			break;
528 
529 		}
530 		case XPT_DEV_MATCH: {
531 			struct cam_periph_map_info mapinfo;
532 			struct cam_path *old_path;
533 
534 			/*
535 			 * We can't deal with physical addresses for this
536 			 * type of transaction.
537 			 */
538 			if ((inccb->ccb_h.flags & CAM_DATA_MASK) !=
539 			    CAM_DATA_VADDR) {
540 				error = EINVAL;
541 				break;
542 			}
543 
544 			/*
545 			 * Save this in case the caller had it set to
546 			 * something in particular.
547 			 */
548 			old_path = inccb->ccb_h.path;
549 
550 			/*
551 			 * We really don't need a path for the matching
552 			 * code.  The path is needed because of the
553 			 * debugging statements in xpt_action().  They
554 			 * assume that the CCB has a valid path.
555 			 */
556 			inccb->ccb_h.path = xpt_periph->path;
557 
558 			bzero(&mapinfo, sizeof(mapinfo));
559 
560 			/*
561 			 * Map the pattern and match buffers into kernel
562 			 * virtual address space.
563 			 */
564 			error = cam_periph_mapmem(inccb, &mapinfo, MAXPHYS);
565 
566 			if (error) {
567 				inccb->ccb_h.path = old_path;
568 				break;
569 			}
570 
571 			/*
572 			 * This is an immediate CCB, we can send it on directly.
573 			 */
574 			xpt_action(inccb);
575 
576 			/*
577 			 * Map the buffers back into user space.
578 			 */
579 			cam_periph_unmapmem(inccb, &mapinfo);
580 
581 			inccb->ccb_h.path = old_path;
582 
583 			error = 0;
584 			break;
585 		}
586 		default:
587 			error = ENOTSUP;
588 			break;
589 		}
590 		xpt_release_bus(bus);
591 		break;
592 	}
593 	/*
594 	 * This is the getpassthru ioctl. It takes a XPT_GDEVLIST ccb as input,
595 	 * with the periphal driver name and unit name filled in.  The other
596 	 * fields don't really matter as input.  The passthrough driver name
597 	 * ("pass"), and unit number are passed back in the ccb.  The current
598 	 * device generation number, and the index into the device peripheral
599 	 * driver list, and the status are also passed back.  Note that
600 	 * since we do everything in one pass, unlike the XPT_GDEVLIST ccb,
601 	 * we never return a status of CAM_GDEVLIST_LIST_CHANGED.  It is
602 	 * (or rather should be) impossible for the device peripheral driver
603 	 * list to change since we look at the whole thing in one pass, and
604 	 * we do it with lock protection.
605 	 *
606 	 */
607 	case CAMGETPASSTHRU: {
608 		union ccb *ccb;
609 		struct cam_periph *periph;
610 		struct periph_driver **p_drv;
611 		char   *name;
612 		u_int unit;
613 		int base_periph_found;
614 
615 		ccb = (union ccb *)addr;
616 		unit = ccb->cgdl.unit_number;
617 		name = ccb->cgdl.periph_name;
618 		base_periph_found = 0;
619 #if defined(BUF_TRACKING) || defined(FULL_BUF_TRACKING)
620 		if (ccb->ccb_h.func_code == XPT_SCSI_IO)
621 			ccb->csio.bio = NULL;
622 #endif
623 
624 		/*
625 		 * Sanity check -- make sure we don't get a null peripheral
626 		 * driver name.
627 		 */
628 		if (*ccb->cgdl.periph_name == '\0') {
629 			error = EINVAL;
630 			break;
631 		}
632 
633 		/* Keep the list from changing while we traverse it */
634 		xpt_lock_buses();
635 
636 		/* first find our driver in the list of drivers */
637 		for (p_drv = periph_drivers; *p_drv != NULL; p_drv++)
638 			if (strcmp((*p_drv)->driver_name, name) == 0)
639 				break;
640 
641 		if (*p_drv == NULL) {
642 			xpt_unlock_buses();
643 			ccb->ccb_h.status = CAM_REQ_CMP_ERR;
644 			ccb->cgdl.status = CAM_GDEVLIST_ERROR;
645 			*ccb->cgdl.periph_name = '\0';
646 			ccb->cgdl.unit_number = 0;
647 			error = ENOENT;
648 			break;
649 		}
650 
651 		/*
652 		 * Run through every peripheral instance of this driver
653 		 * and check to see whether it matches the unit passed
654 		 * in by the user.  If it does, get out of the loops and
655 		 * find the passthrough driver associated with that
656 		 * peripheral driver.
657 		 */
658 		for (periph = TAILQ_FIRST(&(*p_drv)->units); periph != NULL;
659 		     periph = TAILQ_NEXT(periph, unit_links)) {
660 
661 			if (periph->unit_number == unit)
662 				break;
663 		}
664 		/*
665 		 * If we found the peripheral driver that the user passed
666 		 * in, go through all of the peripheral drivers for that
667 		 * particular device and look for a passthrough driver.
668 		 */
669 		if (periph != NULL) {
670 			struct cam_ed *device;
671 			int i;
672 
673 			base_periph_found = 1;
674 			device = periph->path->device;
675 			for (i = 0, periph = SLIST_FIRST(&device->periphs);
676 			     periph != NULL;
677 			     periph = SLIST_NEXT(periph, periph_links), i++) {
678 				/*
679 				 * Check to see whether we have a
680 				 * passthrough device or not.
681 				 */
682 				if (strcmp(periph->periph_name, "pass") == 0) {
683 					/*
684 					 * Fill in the getdevlist fields.
685 					 */
686 					strcpy(ccb->cgdl.periph_name,
687 					       periph->periph_name);
688 					ccb->cgdl.unit_number =
689 						periph->unit_number;
690 					if (SLIST_NEXT(periph, periph_links))
691 						ccb->cgdl.status =
692 							CAM_GDEVLIST_MORE_DEVS;
693 					else
694 						ccb->cgdl.status =
695 						       CAM_GDEVLIST_LAST_DEVICE;
696 					ccb->cgdl.generation =
697 						device->generation;
698 					ccb->cgdl.index = i;
699 					/*
700 					 * Fill in some CCB header fields
701 					 * that the user may want.
702 					 */
703 					ccb->ccb_h.path_id =
704 						periph->path->bus->path_id;
705 					ccb->ccb_h.target_id =
706 						periph->path->target->target_id;
707 					ccb->ccb_h.target_lun =
708 						periph->path->device->lun_id;
709 					ccb->ccb_h.status = CAM_REQ_CMP;
710 					break;
711 				}
712 			}
713 		}
714 
715 		/*
716 		 * If the periph is null here, one of two things has
717 		 * happened.  The first possibility is that we couldn't
718 		 * find the unit number of the particular peripheral driver
719 		 * that the user is asking about.  e.g. the user asks for
720 		 * the passthrough driver for "da11".  We find the list of
721 		 * "da" peripherals all right, but there is no unit 11.
722 		 * The other possibility is that we went through the list
723 		 * of peripheral drivers attached to the device structure,
724 		 * but didn't find one with the name "pass".  Either way,
725 		 * we return ENOENT, since we couldn't find something.
726 		 */
727 		if (periph == NULL) {
728 			ccb->ccb_h.status = CAM_REQ_CMP_ERR;
729 			ccb->cgdl.status = CAM_GDEVLIST_ERROR;
730 			*ccb->cgdl.periph_name = '\0';
731 			ccb->cgdl.unit_number = 0;
732 			error = ENOENT;
733 			/*
734 			 * It is unfortunate that this is even necessary,
735 			 * but there are many, many clueless users out there.
736 			 * If this is true, the user is looking for the
737 			 * passthrough driver, but doesn't have one in his
738 			 * kernel.
739 			 */
740 			if (base_periph_found == 1) {
741 				printf("xptioctl: pass driver is not in the "
742 				       "kernel\n");
743 				printf("xptioctl: put \"device pass\" in "
744 				       "your kernel config file\n");
745 			}
746 		}
747 		xpt_unlock_buses();
748 		break;
749 		}
750 	default:
751 		error = ENOTTY;
752 		break;
753 	}
754 
755 	return(error);
756 }
757 
758 static int
759 cam_module_event_handler(module_t mod, int what, void *arg)
760 {
761 	int error;
762 
763 	switch (what) {
764 	case MOD_LOAD:
765 		if ((error = xpt_init(NULL)) != 0)
766 			return (error);
767 		break;
768 	case MOD_UNLOAD:
769 		return EBUSY;
770 	default:
771 		return EOPNOTSUPP;
772 	}
773 
774 	return 0;
775 }
776 
777 static struct xpt_proto *
778 xpt_proto_find(cam_proto proto)
779 {
780 	struct xpt_proto **pp;
781 
782 	SET_FOREACH(pp, cam_xpt_proto_set) {
783 		if ((*pp)->proto == proto)
784 			return *pp;
785 	}
786 
787 	return NULL;
788 }
789 
790 static void
791 xpt_rescan_done(struct cam_periph *periph, union ccb *done_ccb)
792 {
793 
794 	if (done_ccb->ccb_h.ppriv_ptr1 == NULL) {
795 		xpt_free_path(done_ccb->ccb_h.path);
796 		xpt_free_ccb(done_ccb);
797 	} else {
798 		done_ccb->ccb_h.cbfcnp = done_ccb->ccb_h.ppriv_ptr1;
799 		(*done_ccb->ccb_h.cbfcnp)(periph, done_ccb);
800 	}
801 	xpt_release_boot();
802 }
803 
804 /* thread to handle bus rescans */
805 static void
806 xpt_scanner_thread(void *dummy)
807 {
808 	union ccb	*ccb;
809 	struct cam_path	 path;
810 
811 	xpt_lock_buses();
812 	for (;;) {
813 		if (TAILQ_EMPTY(&xsoftc.ccb_scanq))
814 			msleep(&xsoftc.ccb_scanq, &xsoftc.xpt_topo_lock, PRIBIO,
815 			       "-", 0);
816 		if ((ccb = (union ccb *)TAILQ_FIRST(&xsoftc.ccb_scanq)) != NULL) {
817 			TAILQ_REMOVE(&xsoftc.ccb_scanq, &ccb->ccb_h, sim_links.tqe);
818 			xpt_unlock_buses();
819 
820 			/*
821 			 * Since lock can be dropped inside and path freed
822 			 * by completion callback even before return here,
823 			 * take our own path copy for reference.
824 			 */
825 			xpt_copy_path(&path, ccb->ccb_h.path);
826 			xpt_path_lock(&path);
827 			xpt_action(ccb);
828 			xpt_path_unlock(&path);
829 			xpt_release_path(&path);
830 
831 			xpt_lock_buses();
832 		}
833 	}
834 }
835 
836 void
837 xpt_rescan(union ccb *ccb)
838 {
839 	struct ccb_hdr *hdr;
840 
841 	/* Prepare request */
842 	if (ccb->ccb_h.path->target->target_id == CAM_TARGET_WILDCARD &&
843 	    ccb->ccb_h.path->device->lun_id == CAM_LUN_WILDCARD)
844 		ccb->ccb_h.func_code = XPT_SCAN_BUS;
845 	else if (ccb->ccb_h.path->target->target_id != CAM_TARGET_WILDCARD &&
846 	    ccb->ccb_h.path->device->lun_id == CAM_LUN_WILDCARD)
847 		ccb->ccb_h.func_code = XPT_SCAN_TGT;
848 	else if (ccb->ccb_h.path->target->target_id != CAM_TARGET_WILDCARD &&
849 	    ccb->ccb_h.path->device->lun_id != CAM_LUN_WILDCARD)
850 		ccb->ccb_h.func_code = XPT_SCAN_LUN;
851 	else {
852 		xpt_print(ccb->ccb_h.path, "illegal scan path\n");
853 		xpt_free_path(ccb->ccb_h.path);
854 		xpt_free_ccb(ccb);
855 		return;
856 	}
857 	CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_TRACE,
858 	    ("xpt_rescan: func %#x %s\n", ccb->ccb_h.func_code,
859  		xpt_action_name(ccb->ccb_h.func_code)));
860 
861 	ccb->ccb_h.ppriv_ptr1 = ccb->ccb_h.cbfcnp;
862 	ccb->ccb_h.cbfcnp = xpt_rescan_done;
863 	xpt_setup_ccb(&ccb->ccb_h, ccb->ccb_h.path, CAM_PRIORITY_XPT);
864 	/* Don't make duplicate entries for the same paths. */
865 	xpt_lock_buses();
866 	if (ccb->ccb_h.ppriv_ptr1 == NULL) {
867 		TAILQ_FOREACH(hdr, &xsoftc.ccb_scanq, sim_links.tqe) {
868 			if (xpt_path_comp(hdr->path, ccb->ccb_h.path) == 0) {
869 				wakeup(&xsoftc.ccb_scanq);
870 				xpt_unlock_buses();
871 				xpt_print(ccb->ccb_h.path, "rescan already queued\n");
872 				xpt_free_path(ccb->ccb_h.path);
873 				xpt_free_ccb(ccb);
874 				return;
875 			}
876 		}
877 	}
878 	TAILQ_INSERT_TAIL(&xsoftc.ccb_scanq, &ccb->ccb_h, sim_links.tqe);
879 	xsoftc.buses_to_config++;
880 	wakeup(&xsoftc.ccb_scanq);
881 	xpt_unlock_buses();
882 }
883 
884 /* Functions accessed by the peripheral drivers */
885 static int
886 xpt_init(void *dummy)
887 {
888 	struct cam_sim *xpt_sim;
889 	struct cam_path *path;
890 	struct cam_devq *devq;
891 	cam_status status;
892 	int error, i;
893 
894 	TAILQ_INIT(&xsoftc.xpt_busses);
895 	TAILQ_INIT(&xsoftc.ccb_scanq);
896 	STAILQ_INIT(&xsoftc.highpowerq);
897 	xsoftc.num_highpower = CAM_MAX_HIGHPOWER;
898 
899 	mtx_init(&xsoftc.xpt_lock, "XPT lock", NULL, MTX_DEF);
900 	mtx_init(&xsoftc.xpt_highpower_lock, "XPT highpower lock", NULL, MTX_DEF);
901 	xsoftc.xpt_taskq = taskqueue_create("CAM XPT task", M_WAITOK,
902 	    taskqueue_thread_enqueue, /*context*/&xsoftc.xpt_taskq);
903 
904 #ifdef CAM_BOOT_DELAY
905 	/*
906 	 * Override this value at compile time to assist our users
907 	 * who don't use loader to boot a kernel.
908 	 */
909 	xsoftc.boot_delay = CAM_BOOT_DELAY;
910 #endif
911 	/*
912 	 * The xpt layer is, itself, the equivalent of a SIM.
913 	 * Allow 16 ccbs in the ccb pool for it.  This should
914 	 * give decent parallelism when we probe buses and
915 	 * perform other XPT functions.
916 	 */
917 	devq = cam_simq_alloc(16);
918 	xpt_sim = cam_sim_alloc(xptaction,
919 				xptpoll,
920 				"xpt",
921 				/*softc*/NULL,
922 				/*unit*/0,
923 				/*mtx*/&xsoftc.xpt_lock,
924 				/*max_dev_transactions*/0,
925 				/*max_tagged_dev_transactions*/0,
926 				devq);
927 	if (xpt_sim == NULL)
928 		return (ENOMEM);
929 
930 	mtx_lock(&xsoftc.xpt_lock);
931 	if ((status = xpt_bus_register(xpt_sim, NULL, 0)) != CAM_SUCCESS) {
932 		mtx_unlock(&xsoftc.xpt_lock);
933 		printf("xpt_init: xpt_bus_register failed with status %#x,"
934 		       " failing attach\n", status);
935 		return (EINVAL);
936 	}
937 	mtx_unlock(&xsoftc.xpt_lock);
938 
939 	/*
940 	 * Looking at the XPT from the SIM layer, the XPT is
941 	 * the equivalent of a peripheral driver.  Allocate
942 	 * a peripheral driver entry for us.
943 	 */
944 	if ((status = xpt_create_path(&path, NULL, CAM_XPT_PATH_ID,
945 				      CAM_TARGET_WILDCARD,
946 				      CAM_LUN_WILDCARD)) != CAM_REQ_CMP) {
947 		printf("xpt_init: xpt_create_path failed with status %#x,"
948 		       " failing attach\n", status);
949 		return (EINVAL);
950 	}
951 	xpt_path_lock(path);
952 	cam_periph_alloc(xptregister, NULL, NULL, NULL, "xpt", CAM_PERIPH_BIO,
953 			 path, NULL, 0, xpt_sim);
954 	xpt_path_unlock(path);
955 	xpt_free_path(path);
956 
957 	if (cam_num_doneqs < 1)
958 		cam_num_doneqs = 1 + mp_ncpus / 6;
959 	else if (cam_num_doneqs > MAXCPU)
960 		cam_num_doneqs = MAXCPU;
961 	for (i = 0; i < cam_num_doneqs; i++) {
962 		mtx_init(&cam_doneqs[i].cam_doneq_mtx, "CAM doneq", NULL,
963 		    MTX_DEF);
964 		STAILQ_INIT(&cam_doneqs[i].cam_doneq);
965 		error = kproc_kthread_add(xpt_done_td, &cam_doneqs[i],
966 		    &cam_proc, NULL, 0, 0, "cam", "doneq%d", i);
967 		if (error != 0) {
968 			cam_num_doneqs = i;
969 			break;
970 		}
971 	}
972 	if (cam_num_doneqs < 1) {
973 		printf("xpt_init: Cannot init completion queues "
974 		       "- failing attach\n");
975 		return (ENOMEM);
976 	}
977 	/*
978 	 * Register a callback for when interrupts are enabled.
979 	 */
980 	xsoftc.xpt_config_hook =
981 	    (struct intr_config_hook *)malloc(sizeof(struct intr_config_hook),
982 					      M_CAMXPT, M_NOWAIT | M_ZERO);
983 	if (xsoftc.xpt_config_hook == NULL) {
984 		printf("xpt_init: Cannot malloc config hook "
985 		       "- failing attach\n");
986 		return (ENOMEM);
987 	}
988 	xsoftc.xpt_config_hook->ich_func = xpt_config;
989 	if (config_intrhook_establish(xsoftc.xpt_config_hook) != 0) {
990 		free (xsoftc.xpt_config_hook, M_CAMXPT);
991 		printf("xpt_init: config_intrhook_establish failed "
992 		       "- failing attach\n");
993 	}
994 
995 	return (0);
996 }
997 
998 static cam_status
999 xptregister(struct cam_periph *periph, void *arg)
1000 {
1001 	struct cam_sim *xpt_sim;
1002 
1003 	if (periph == NULL) {
1004 		printf("xptregister: periph was NULL!!\n");
1005 		return(CAM_REQ_CMP_ERR);
1006 	}
1007 
1008 	xpt_sim = (struct cam_sim *)arg;
1009 	xpt_sim->softc = periph;
1010 	xpt_periph = periph;
1011 	periph->softc = NULL;
1012 
1013 	return(CAM_REQ_CMP);
1014 }
1015 
1016 int32_t
1017 xpt_add_periph(struct cam_periph *periph)
1018 {
1019 	struct cam_ed *device;
1020 	int32_t	 status;
1021 
1022 	TASK_INIT(&periph->periph_run_task, 0, xpt_run_allocq_task, periph);
1023 	device = periph->path->device;
1024 	status = CAM_REQ_CMP;
1025 	if (device != NULL) {
1026 		mtx_lock(&device->target->bus->eb_mtx);
1027 		device->generation++;
1028 		SLIST_INSERT_HEAD(&device->periphs, periph, periph_links);
1029 		mtx_unlock(&device->target->bus->eb_mtx);
1030 		atomic_add_32(&xsoftc.xpt_generation, 1);
1031 	}
1032 
1033 	return (status);
1034 }
1035 
1036 void
1037 xpt_remove_periph(struct cam_periph *periph)
1038 {
1039 	struct cam_ed *device;
1040 
1041 	device = periph->path->device;
1042 	if (device != NULL) {
1043 		mtx_lock(&device->target->bus->eb_mtx);
1044 		device->generation++;
1045 		SLIST_REMOVE(&device->periphs, periph, cam_periph, periph_links);
1046 		mtx_unlock(&device->target->bus->eb_mtx);
1047 		atomic_add_32(&xsoftc.xpt_generation, 1);
1048 	}
1049 }
1050 
1051 
1052 void
1053 xpt_announce_periph(struct cam_periph *periph, char *announce_string)
1054 {
1055 	struct	cam_path *path = periph->path;
1056 	struct  xpt_proto *proto;
1057 
1058 	cam_periph_assert(periph, MA_OWNED);
1059 	periph->flags |= CAM_PERIPH_ANNOUNCED;
1060 
1061 	printf("%s%d at %s%d bus %d scbus%d target %d lun %jx\n",
1062 	       periph->periph_name, periph->unit_number,
1063 	       path->bus->sim->sim_name,
1064 	       path->bus->sim->unit_number,
1065 	       path->bus->sim->bus_id,
1066 	       path->bus->path_id,
1067 	       path->target->target_id,
1068 	       (uintmax_t)path->device->lun_id);
1069 	printf("%s%d: ", periph->periph_name, periph->unit_number);
1070 	proto = xpt_proto_find(path->device->protocol);
1071 	if (proto)
1072 		proto->ops->announce(path->device);
1073 	else
1074 		printf("%s%d: Unknown protocol device %d\n",
1075 		    periph->periph_name, periph->unit_number,
1076 		    path->device->protocol);
1077 	if (path->device->serial_num_len > 0) {
1078 		/* Don't wrap the screen  - print only the first 60 chars */
1079 		printf("%s%d: Serial Number %.60s\n", periph->periph_name,
1080 		       periph->unit_number, path->device->serial_num);
1081 	}
1082 	/* Announce transport details. */
1083 	path->bus->xport->ops->announce(periph);
1084 	/* Announce command queueing. */
1085 	if (path->device->inq_flags & SID_CmdQue
1086 	 || path->device->flags & CAM_DEV_TAG_AFTER_COUNT) {
1087 		printf("%s%d: Command Queueing enabled\n",
1088 		       periph->periph_name, periph->unit_number);
1089 	}
1090 	/* Announce caller's details if they've passed in. */
1091 	if (announce_string != NULL)
1092 		printf("%s%d: %s\n", periph->periph_name,
1093 		       periph->unit_number, announce_string);
1094 }
1095 
1096 void
1097 xpt_announce_quirks(struct cam_periph *periph, int quirks, char *bit_string)
1098 {
1099 	if (quirks != 0) {
1100 		printf("%s%d: quirks=0x%b\n", periph->periph_name,
1101 		    periph->unit_number, quirks, bit_string);
1102 	}
1103 }
1104 
1105 void
1106 xpt_denounce_periph(struct cam_periph *periph)
1107 {
1108 	struct	cam_path *path = periph->path;
1109 	struct  xpt_proto *proto;
1110 
1111 	cam_periph_assert(periph, MA_OWNED);
1112 	printf("%s%d at %s%d bus %d scbus%d target %d lun %jx\n",
1113 	       periph->periph_name, periph->unit_number,
1114 	       path->bus->sim->sim_name,
1115 	       path->bus->sim->unit_number,
1116 	       path->bus->sim->bus_id,
1117 	       path->bus->path_id,
1118 	       path->target->target_id,
1119 	       (uintmax_t)path->device->lun_id);
1120 	printf("%s%d: ", periph->periph_name, periph->unit_number);
1121 	proto = xpt_proto_find(path->device->protocol);
1122 	if (proto)
1123 		proto->ops->denounce(path->device);
1124 	else
1125 		printf("%s%d: Unknown protocol device %d\n",
1126 		    periph->periph_name, periph->unit_number,
1127 		    path->device->protocol);
1128 	if (path->device->serial_num_len > 0)
1129 		printf(" s/n %.60s", path->device->serial_num);
1130 	printf(" detached\n");
1131 }
1132 
1133 
1134 int
1135 xpt_getattr(char *buf, size_t len, const char *attr, struct cam_path *path)
1136 {
1137 	int ret = -1, l, o;
1138 	struct ccb_dev_advinfo cdai;
1139 	struct scsi_vpd_id_descriptor *idd;
1140 
1141 	xpt_path_assert(path, MA_OWNED);
1142 
1143 	memset(&cdai, 0, sizeof(cdai));
1144 	xpt_setup_ccb(&cdai.ccb_h, path, CAM_PRIORITY_NORMAL);
1145 	cdai.ccb_h.func_code = XPT_DEV_ADVINFO;
1146 	cdai.flags = CDAI_FLAG_NONE;
1147 	cdai.bufsiz = len;
1148 
1149 	if (!strcmp(attr, "GEOM::ident"))
1150 		cdai.buftype = CDAI_TYPE_SERIAL_NUM;
1151 	else if (!strcmp(attr, "GEOM::physpath"))
1152 		cdai.buftype = CDAI_TYPE_PHYS_PATH;
1153 	else if (strcmp(attr, "GEOM::lunid") == 0 ||
1154 		 strcmp(attr, "GEOM::lunname") == 0) {
1155 		cdai.buftype = CDAI_TYPE_SCSI_DEVID;
1156 		cdai.bufsiz = CAM_SCSI_DEVID_MAXLEN;
1157 	} else
1158 		goto out;
1159 
1160 	cdai.buf = malloc(cdai.bufsiz, M_CAMXPT, M_NOWAIT|M_ZERO);
1161 	if (cdai.buf == NULL) {
1162 		ret = ENOMEM;
1163 		goto out;
1164 	}
1165 	xpt_action((union ccb *)&cdai); /* can only be synchronous */
1166 	if ((cdai.ccb_h.status & CAM_DEV_QFRZN) != 0)
1167 		cam_release_devq(cdai.ccb_h.path, 0, 0, 0, FALSE);
1168 	if (cdai.provsiz == 0)
1169 		goto out;
1170 	if (cdai.buftype == CDAI_TYPE_SCSI_DEVID) {
1171 		if (strcmp(attr, "GEOM::lunid") == 0) {
1172 			idd = scsi_get_devid((struct scsi_vpd_device_id *)cdai.buf,
1173 			    cdai.provsiz, scsi_devid_is_lun_naa);
1174 			if (idd == NULL)
1175 				idd = scsi_get_devid((struct scsi_vpd_device_id *)cdai.buf,
1176 				    cdai.provsiz, scsi_devid_is_lun_eui64);
1177 			if (idd == NULL)
1178 				idd = scsi_get_devid((struct scsi_vpd_device_id *)cdai.buf,
1179 				    cdai.provsiz, scsi_devid_is_lun_uuid);
1180 			if (idd == NULL)
1181 				idd = scsi_get_devid((struct scsi_vpd_device_id *)cdai.buf,
1182 				    cdai.provsiz, scsi_devid_is_lun_md5);
1183 		} else
1184 			idd = NULL;
1185 		if (idd == NULL)
1186 			idd = scsi_get_devid((struct scsi_vpd_device_id *)cdai.buf,
1187 			    cdai.provsiz, scsi_devid_is_lun_t10);
1188 		if (idd == NULL)
1189 			idd = scsi_get_devid((struct scsi_vpd_device_id *)cdai.buf,
1190 			    cdai.provsiz, scsi_devid_is_lun_name);
1191 		if (idd == NULL)
1192 			goto out;
1193 		ret = 0;
1194 		if ((idd->proto_codeset & SVPD_ID_CODESET_MASK) == SVPD_ID_CODESET_ASCII) {
1195 			if (idd->length < len) {
1196 				for (l = 0; l < idd->length; l++)
1197 					buf[l] = idd->identifier[l] ?
1198 					    idd->identifier[l] : ' ';
1199 				buf[l] = 0;
1200 			} else
1201 				ret = EFAULT;
1202 		} else if ((idd->proto_codeset & SVPD_ID_CODESET_MASK) == SVPD_ID_CODESET_UTF8) {
1203 			l = strnlen(idd->identifier, idd->length);
1204 			if (l < len) {
1205 				bcopy(idd->identifier, buf, l);
1206 				buf[l] = 0;
1207 			} else
1208 				ret = EFAULT;
1209 		} else if ((idd->id_type & SVPD_ID_TYPE_MASK) == SVPD_ID_TYPE_UUID
1210 		    && idd->identifier[0] == 0x10) {
1211 			if ((idd->length - 2) * 2 + 4 < len) {
1212 				for (l = 2, o = 0; l < idd->length; l++) {
1213 					if (l == 6 || l == 8 || l == 10 || l == 12)
1214 					    o += sprintf(buf + o, "-");
1215 					o += sprintf(buf + o, "%02x",
1216 					    idd->identifier[l]);
1217 				}
1218 			} else
1219 				ret = EFAULT;
1220 		} else {
1221 			if (idd->length * 2 < len) {
1222 				for (l = 0; l < idd->length; l++)
1223 					sprintf(buf + l * 2, "%02x",
1224 					    idd->identifier[l]);
1225 			} else
1226 				ret = EFAULT;
1227 		}
1228 	} else {
1229 		ret = 0;
1230 		if (strlcpy(buf, cdai.buf, len) >= len)
1231 			ret = EFAULT;
1232 	}
1233 
1234 out:
1235 	if (cdai.buf != NULL)
1236 		free(cdai.buf, M_CAMXPT);
1237 	return ret;
1238 }
1239 
1240 static dev_match_ret
1241 xptbusmatch(struct dev_match_pattern *patterns, u_int num_patterns,
1242 	    struct cam_eb *bus)
1243 {
1244 	dev_match_ret retval;
1245 	u_int i;
1246 
1247 	retval = DM_RET_NONE;
1248 
1249 	/*
1250 	 * If we aren't given something to match against, that's an error.
1251 	 */
1252 	if (bus == NULL)
1253 		return(DM_RET_ERROR);
1254 
1255 	/*
1256 	 * If there are no match entries, then this bus matches no
1257 	 * matter what.
1258 	 */
1259 	if ((patterns == NULL) || (num_patterns == 0))
1260 		return(DM_RET_DESCEND | DM_RET_COPY);
1261 
1262 	for (i = 0; i < num_patterns; i++) {
1263 		struct bus_match_pattern *cur_pattern;
1264 
1265 		/*
1266 		 * If the pattern in question isn't for a bus node, we
1267 		 * aren't interested.  However, we do indicate to the
1268 		 * calling routine that we should continue descending the
1269 		 * tree, since the user wants to match against lower-level
1270 		 * EDT elements.
1271 		 */
1272 		if (patterns[i].type != DEV_MATCH_BUS) {
1273 			if ((retval & DM_RET_ACTION_MASK) == DM_RET_NONE)
1274 				retval |= DM_RET_DESCEND;
1275 			continue;
1276 		}
1277 
1278 		cur_pattern = &patterns[i].pattern.bus_pattern;
1279 
1280 		/*
1281 		 * If they want to match any bus node, we give them any
1282 		 * device node.
1283 		 */
1284 		if (cur_pattern->flags == BUS_MATCH_ANY) {
1285 			/* set the copy flag */
1286 			retval |= DM_RET_COPY;
1287 
1288 			/*
1289 			 * If we've already decided on an action, go ahead
1290 			 * and return.
1291 			 */
1292 			if ((retval & DM_RET_ACTION_MASK) != DM_RET_NONE)
1293 				return(retval);
1294 		}
1295 
1296 		/*
1297 		 * Not sure why someone would do this...
1298 		 */
1299 		if (cur_pattern->flags == BUS_MATCH_NONE)
1300 			continue;
1301 
1302 		if (((cur_pattern->flags & BUS_MATCH_PATH) != 0)
1303 		 && (cur_pattern->path_id != bus->path_id))
1304 			continue;
1305 
1306 		if (((cur_pattern->flags & BUS_MATCH_BUS_ID) != 0)
1307 		 && (cur_pattern->bus_id != bus->sim->bus_id))
1308 			continue;
1309 
1310 		if (((cur_pattern->flags & BUS_MATCH_UNIT) != 0)
1311 		 && (cur_pattern->unit_number != bus->sim->unit_number))
1312 			continue;
1313 
1314 		if (((cur_pattern->flags & BUS_MATCH_NAME) != 0)
1315 		 && (strncmp(cur_pattern->dev_name, bus->sim->sim_name,
1316 			     DEV_IDLEN) != 0))
1317 			continue;
1318 
1319 		/*
1320 		 * If we get to this point, the user definitely wants
1321 		 * information on this bus.  So tell the caller to copy the
1322 		 * data out.
1323 		 */
1324 		retval |= DM_RET_COPY;
1325 
1326 		/*
1327 		 * If the return action has been set to descend, then we
1328 		 * know that we've already seen a non-bus matching
1329 		 * expression, therefore we need to further descend the tree.
1330 		 * This won't change by continuing around the loop, so we
1331 		 * go ahead and return.  If we haven't seen a non-bus
1332 		 * matching expression, we keep going around the loop until
1333 		 * we exhaust the matching expressions.  We'll set the stop
1334 		 * flag once we fall out of the loop.
1335 		 */
1336 		if ((retval & DM_RET_ACTION_MASK) == DM_RET_DESCEND)
1337 			return(retval);
1338 	}
1339 
1340 	/*
1341 	 * If the return action hasn't been set to descend yet, that means
1342 	 * we haven't seen anything other than bus matching patterns.  So
1343 	 * tell the caller to stop descending the tree -- the user doesn't
1344 	 * want to match against lower level tree elements.
1345 	 */
1346 	if ((retval & DM_RET_ACTION_MASK) == DM_RET_NONE)
1347 		retval |= DM_RET_STOP;
1348 
1349 	return(retval);
1350 }
1351 
1352 static dev_match_ret
1353 xptdevicematch(struct dev_match_pattern *patterns, u_int num_patterns,
1354 	       struct cam_ed *device)
1355 {
1356 	dev_match_ret retval;
1357 	u_int i;
1358 
1359 	retval = DM_RET_NONE;
1360 
1361 	/*
1362 	 * If we aren't given something to match against, that's an error.
1363 	 */
1364 	if (device == NULL)
1365 		return(DM_RET_ERROR);
1366 
1367 	/*
1368 	 * If there are no match entries, then this device matches no
1369 	 * matter what.
1370 	 */
1371 	if ((patterns == NULL) || (num_patterns == 0))
1372 		return(DM_RET_DESCEND | DM_RET_COPY);
1373 
1374 	for (i = 0; i < num_patterns; i++) {
1375 		struct device_match_pattern *cur_pattern;
1376 		struct scsi_vpd_device_id *device_id_page;
1377 
1378 		/*
1379 		 * If the pattern in question isn't for a device node, we
1380 		 * aren't interested.
1381 		 */
1382 		if (patterns[i].type != DEV_MATCH_DEVICE) {
1383 			if ((patterns[i].type == DEV_MATCH_PERIPH)
1384 			 && ((retval & DM_RET_ACTION_MASK) == DM_RET_NONE))
1385 				retval |= DM_RET_DESCEND;
1386 			continue;
1387 		}
1388 
1389 		cur_pattern = &patterns[i].pattern.device_pattern;
1390 
1391 		/* Error out if mutually exclusive options are specified. */
1392 		if ((cur_pattern->flags & (DEV_MATCH_INQUIRY|DEV_MATCH_DEVID))
1393 		 == (DEV_MATCH_INQUIRY|DEV_MATCH_DEVID))
1394 			return(DM_RET_ERROR);
1395 
1396 		/*
1397 		 * If they want to match any device node, we give them any
1398 		 * device node.
1399 		 */
1400 		if (cur_pattern->flags == DEV_MATCH_ANY)
1401 			goto copy_dev_node;
1402 
1403 		/*
1404 		 * Not sure why someone would do this...
1405 		 */
1406 		if (cur_pattern->flags == DEV_MATCH_NONE)
1407 			continue;
1408 
1409 		if (((cur_pattern->flags & DEV_MATCH_PATH) != 0)
1410 		 && (cur_pattern->path_id != device->target->bus->path_id))
1411 			continue;
1412 
1413 		if (((cur_pattern->flags & DEV_MATCH_TARGET) != 0)
1414 		 && (cur_pattern->target_id != device->target->target_id))
1415 			continue;
1416 
1417 		if (((cur_pattern->flags & DEV_MATCH_LUN) != 0)
1418 		 && (cur_pattern->target_lun != device->lun_id))
1419 			continue;
1420 
1421 		if (((cur_pattern->flags & DEV_MATCH_INQUIRY) != 0)
1422 		 && (cam_quirkmatch((caddr_t)&device->inq_data,
1423 				    (caddr_t)&cur_pattern->data.inq_pat,
1424 				    1, sizeof(cur_pattern->data.inq_pat),
1425 				    scsi_static_inquiry_match) == NULL))
1426 			continue;
1427 
1428 		device_id_page = (struct scsi_vpd_device_id *)device->device_id;
1429 		if (((cur_pattern->flags & DEV_MATCH_DEVID) != 0)
1430 		 && (device->device_id_len < SVPD_DEVICE_ID_HDR_LEN
1431 		  || scsi_devid_match((uint8_t *)device_id_page->desc_list,
1432 				      device->device_id_len
1433 				    - SVPD_DEVICE_ID_HDR_LEN,
1434 				      cur_pattern->data.devid_pat.id,
1435 				      cur_pattern->data.devid_pat.id_len) != 0))
1436 			continue;
1437 
1438 copy_dev_node:
1439 		/*
1440 		 * If we get to this point, the user definitely wants
1441 		 * information on this device.  So tell the caller to copy
1442 		 * the data out.
1443 		 */
1444 		retval |= DM_RET_COPY;
1445 
1446 		/*
1447 		 * If the return action has been set to descend, then we
1448 		 * know that we've already seen a peripheral matching
1449 		 * expression, therefore we need to further descend the tree.
1450 		 * This won't change by continuing around the loop, so we
1451 		 * go ahead and return.  If we haven't seen a peripheral
1452 		 * matching expression, we keep going around the loop until
1453 		 * we exhaust the matching expressions.  We'll set the stop
1454 		 * flag once we fall out of the loop.
1455 		 */
1456 		if ((retval & DM_RET_ACTION_MASK) == DM_RET_DESCEND)
1457 			return(retval);
1458 	}
1459 
1460 	/*
1461 	 * If the return action hasn't been set to descend yet, that means
1462 	 * we haven't seen any peripheral matching patterns.  So tell the
1463 	 * caller to stop descending the tree -- the user doesn't want to
1464 	 * match against lower level tree elements.
1465 	 */
1466 	if ((retval & DM_RET_ACTION_MASK) == DM_RET_NONE)
1467 		retval |= DM_RET_STOP;
1468 
1469 	return(retval);
1470 }
1471 
1472 /*
1473  * Match a single peripheral against any number of match patterns.
1474  */
1475 static dev_match_ret
1476 xptperiphmatch(struct dev_match_pattern *patterns, u_int num_patterns,
1477 	       struct cam_periph *periph)
1478 {
1479 	dev_match_ret retval;
1480 	u_int i;
1481 
1482 	/*
1483 	 * If we aren't given something to match against, that's an error.
1484 	 */
1485 	if (periph == NULL)
1486 		return(DM_RET_ERROR);
1487 
1488 	/*
1489 	 * If there are no match entries, then this peripheral matches no
1490 	 * matter what.
1491 	 */
1492 	if ((patterns == NULL) || (num_patterns == 0))
1493 		return(DM_RET_STOP | DM_RET_COPY);
1494 
1495 	/*
1496 	 * There aren't any nodes below a peripheral node, so there's no
1497 	 * reason to descend the tree any further.
1498 	 */
1499 	retval = DM_RET_STOP;
1500 
1501 	for (i = 0; i < num_patterns; i++) {
1502 		struct periph_match_pattern *cur_pattern;
1503 
1504 		/*
1505 		 * If the pattern in question isn't for a peripheral, we
1506 		 * aren't interested.
1507 		 */
1508 		if (patterns[i].type != DEV_MATCH_PERIPH)
1509 			continue;
1510 
1511 		cur_pattern = &patterns[i].pattern.periph_pattern;
1512 
1513 		/*
1514 		 * If they want to match on anything, then we will do so.
1515 		 */
1516 		if (cur_pattern->flags == PERIPH_MATCH_ANY) {
1517 			/* set the copy flag */
1518 			retval |= DM_RET_COPY;
1519 
1520 			/*
1521 			 * We've already set the return action to stop,
1522 			 * since there are no nodes below peripherals in
1523 			 * the tree.
1524 			 */
1525 			return(retval);
1526 		}
1527 
1528 		/*
1529 		 * Not sure why someone would do this...
1530 		 */
1531 		if (cur_pattern->flags == PERIPH_MATCH_NONE)
1532 			continue;
1533 
1534 		if (((cur_pattern->flags & PERIPH_MATCH_PATH) != 0)
1535 		 && (cur_pattern->path_id != periph->path->bus->path_id))
1536 			continue;
1537 
1538 		/*
1539 		 * For the target and lun id's, we have to make sure the
1540 		 * target and lun pointers aren't NULL.  The xpt peripheral
1541 		 * has a wildcard target and device.
1542 		 */
1543 		if (((cur_pattern->flags & PERIPH_MATCH_TARGET) != 0)
1544 		 && ((periph->path->target == NULL)
1545 		 ||(cur_pattern->target_id != periph->path->target->target_id)))
1546 			continue;
1547 
1548 		if (((cur_pattern->flags & PERIPH_MATCH_LUN) != 0)
1549 		 && ((periph->path->device == NULL)
1550 		 || (cur_pattern->target_lun != periph->path->device->lun_id)))
1551 			continue;
1552 
1553 		if (((cur_pattern->flags & PERIPH_MATCH_UNIT) != 0)
1554 		 && (cur_pattern->unit_number != periph->unit_number))
1555 			continue;
1556 
1557 		if (((cur_pattern->flags & PERIPH_MATCH_NAME) != 0)
1558 		 && (strncmp(cur_pattern->periph_name, periph->periph_name,
1559 			     DEV_IDLEN) != 0))
1560 			continue;
1561 
1562 		/*
1563 		 * If we get to this point, the user definitely wants
1564 		 * information on this peripheral.  So tell the caller to
1565 		 * copy the data out.
1566 		 */
1567 		retval |= DM_RET_COPY;
1568 
1569 		/*
1570 		 * The return action has already been set to stop, since
1571 		 * peripherals don't have any nodes below them in the EDT.
1572 		 */
1573 		return(retval);
1574 	}
1575 
1576 	/*
1577 	 * If we get to this point, the peripheral that was passed in
1578 	 * doesn't match any of the patterns.
1579 	 */
1580 	return(retval);
1581 }
1582 
1583 static int
1584 xptedtbusfunc(struct cam_eb *bus, void *arg)
1585 {
1586 	struct ccb_dev_match *cdm;
1587 	struct cam_et *target;
1588 	dev_match_ret retval;
1589 
1590 	cdm = (struct ccb_dev_match *)arg;
1591 
1592 	/*
1593 	 * If our position is for something deeper in the tree, that means
1594 	 * that we've already seen this node.  So, we keep going down.
1595 	 */
1596 	if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
1597 	 && (cdm->pos.cookie.bus == bus)
1598 	 && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
1599 	 && (cdm->pos.cookie.target != NULL))
1600 		retval = DM_RET_DESCEND;
1601 	else
1602 		retval = xptbusmatch(cdm->patterns, cdm->num_patterns, bus);
1603 
1604 	/*
1605 	 * If we got an error, bail out of the search.
1606 	 */
1607 	if ((retval & DM_RET_ACTION_MASK) == DM_RET_ERROR) {
1608 		cdm->status = CAM_DEV_MATCH_ERROR;
1609 		return(0);
1610 	}
1611 
1612 	/*
1613 	 * If the copy flag is set, copy this bus out.
1614 	 */
1615 	if (retval & DM_RET_COPY) {
1616 		int spaceleft, j;
1617 
1618 		spaceleft = cdm->match_buf_len - (cdm->num_matches *
1619 			sizeof(struct dev_match_result));
1620 
1621 		/*
1622 		 * If we don't have enough space to put in another
1623 		 * match result, save our position and tell the
1624 		 * user there are more devices to check.
1625 		 */
1626 		if (spaceleft < sizeof(struct dev_match_result)) {
1627 			bzero(&cdm->pos, sizeof(cdm->pos));
1628 			cdm->pos.position_type =
1629 				CAM_DEV_POS_EDT | CAM_DEV_POS_BUS;
1630 
1631 			cdm->pos.cookie.bus = bus;
1632 			cdm->pos.generations[CAM_BUS_GENERATION]=
1633 				xsoftc.bus_generation;
1634 			cdm->status = CAM_DEV_MATCH_MORE;
1635 			return(0);
1636 		}
1637 		j = cdm->num_matches;
1638 		cdm->num_matches++;
1639 		cdm->matches[j].type = DEV_MATCH_BUS;
1640 		cdm->matches[j].result.bus_result.path_id = bus->path_id;
1641 		cdm->matches[j].result.bus_result.bus_id = bus->sim->bus_id;
1642 		cdm->matches[j].result.bus_result.unit_number =
1643 			bus->sim->unit_number;
1644 		strncpy(cdm->matches[j].result.bus_result.dev_name,
1645 			bus->sim->sim_name, DEV_IDLEN);
1646 	}
1647 
1648 	/*
1649 	 * If the user is only interested in buses, there's no
1650 	 * reason to descend to the next level in the tree.
1651 	 */
1652 	if ((retval & DM_RET_ACTION_MASK) == DM_RET_STOP)
1653 		return(1);
1654 
1655 	/*
1656 	 * If there is a target generation recorded, check it to
1657 	 * make sure the target list hasn't changed.
1658 	 */
1659 	mtx_lock(&bus->eb_mtx);
1660 	if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
1661 	 && (cdm->pos.cookie.bus == bus)
1662 	 && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
1663 	 && (cdm->pos.cookie.target != NULL)) {
1664 		if ((cdm->pos.generations[CAM_TARGET_GENERATION] !=
1665 		    bus->generation)) {
1666 			mtx_unlock(&bus->eb_mtx);
1667 			cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
1668 			return (0);
1669 		}
1670 		target = (struct cam_et *)cdm->pos.cookie.target;
1671 		target->refcount++;
1672 	} else
1673 		target = NULL;
1674 	mtx_unlock(&bus->eb_mtx);
1675 
1676 	return (xpttargettraverse(bus, target, xptedttargetfunc, arg));
1677 }
1678 
1679 static int
1680 xptedttargetfunc(struct cam_et *target, void *arg)
1681 {
1682 	struct ccb_dev_match *cdm;
1683 	struct cam_eb *bus;
1684 	struct cam_ed *device;
1685 
1686 	cdm = (struct ccb_dev_match *)arg;
1687 	bus = target->bus;
1688 
1689 	/*
1690 	 * If there is a device list generation recorded, check it to
1691 	 * make sure the device list hasn't changed.
1692 	 */
1693 	mtx_lock(&bus->eb_mtx);
1694 	if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
1695 	 && (cdm->pos.cookie.bus == bus)
1696 	 && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
1697 	 && (cdm->pos.cookie.target == target)
1698 	 && (cdm->pos.position_type & CAM_DEV_POS_DEVICE)
1699 	 && (cdm->pos.cookie.device != NULL)) {
1700 		if (cdm->pos.generations[CAM_DEV_GENERATION] !=
1701 		    target->generation) {
1702 			mtx_unlock(&bus->eb_mtx);
1703 			cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
1704 			return(0);
1705 		}
1706 		device = (struct cam_ed *)cdm->pos.cookie.device;
1707 		device->refcount++;
1708 	} else
1709 		device = NULL;
1710 	mtx_unlock(&bus->eb_mtx);
1711 
1712 	return (xptdevicetraverse(target, device, xptedtdevicefunc, arg));
1713 }
1714 
1715 static int
1716 xptedtdevicefunc(struct cam_ed *device, void *arg)
1717 {
1718 	struct cam_eb *bus;
1719 	struct cam_periph *periph;
1720 	struct ccb_dev_match *cdm;
1721 	dev_match_ret retval;
1722 
1723 	cdm = (struct ccb_dev_match *)arg;
1724 	bus = device->target->bus;
1725 
1726 	/*
1727 	 * If our position is for something deeper in the tree, that means
1728 	 * that we've already seen this node.  So, we keep going down.
1729 	 */
1730 	if ((cdm->pos.position_type & CAM_DEV_POS_DEVICE)
1731 	 && (cdm->pos.cookie.device == device)
1732 	 && (cdm->pos.position_type & CAM_DEV_POS_PERIPH)
1733 	 && (cdm->pos.cookie.periph != NULL))
1734 		retval = DM_RET_DESCEND;
1735 	else
1736 		retval = xptdevicematch(cdm->patterns, cdm->num_patterns,
1737 					device);
1738 
1739 	if ((retval & DM_RET_ACTION_MASK) == DM_RET_ERROR) {
1740 		cdm->status = CAM_DEV_MATCH_ERROR;
1741 		return(0);
1742 	}
1743 
1744 	/*
1745 	 * If the copy flag is set, copy this device out.
1746 	 */
1747 	if (retval & DM_RET_COPY) {
1748 		int spaceleft, j;
1749 
1750 		spaceleft = cdm->match_buf_len - (cdm->num_matches *
1751 			sizeof(struct dev_match_result));
1752 
1753 		/*
1754 		 * If we don't have enough space to put in another
1755 		 * match result, save our position and tell the
1756 		 * user there are more devices to check.
1757 		 */
1758 		if (spaceleft < sizeof(struct dev_match_result)) {
1759 			bzero(&cdm->pos, sizeof(cdm->pos));
1760 			cdm->pos.position_type =
1761 				CAM_DEV_POS_EDT | CAM_DEV_POS_BUS |
1762 				CAM_DEV_POS_TARGET | CAM_DEV_POS_DEVICE;
1763 
1764 			cdm->pos.cookie.bus = device->target->bus;
1765 			cdm->pos.generations[CAM_BUS_GENERATION]=
1766 				xsoftc.bus_generation;
1767 			cdm->pos.cookie.target = device->target;
1768 			cdm->pos.generations[CAM_TARGET_GENERATION] =
1769 				device->target->bus->generation;
1770 			cdm->pos.cookie.device = device;
1771 			cdm->pos.generations[CAM_DEV_GENERATION] =
1772 				device->target->generation;
1773 			cdm->status = CAM_DEV_MATCH_MORE;
1774 			return(0);
1775 		}
1776 		j = cdm->num_matches;
1777 		cdm->num_matches++;
1778 		cdm->matches[j].type = DEV_MATCH_DEVICE;
1779 		cdm->matches[j].result.device_result.path_id =
1780 			device->target->bus->path_id;
1781 		cdm->matches[j].result.device_result.target_id =
1782 			device->target->target_id;
1783 		cdm->matches[j].result.device_result.target_lun =
1784 			device->lun_id;
1785 		cdm->matches[j].result.device_result.protocol =
1786 			device->protocol;
1787 		bcopy(&device->inq_data,
1788 		      &cdm->matches[j].result.device_result.inq_data,
1789 		      sizeof(struct scsi_inquiry_data));
1790 		bcopy(&device->ident_data,
1791 		      &cdm->matches[j].result.device_result.ident_data,
1792 		      sizeof(struct ata_params));
1793 
1794 		/* Let the user know whether this device is unconfigured */
1795 		if (device->flags & CAM_DEV_UNCONFIGURED)
1796 			cdm->matches[j].result.device_result.flags =
1797 				DEV_RESULT_UNCONFIGURED;
1798 		else
1799 			cdm->matches[j].result.device_result.flags =
1800 				DEV_RESULT_NOFLAG;
1801 	}
1802 
1803 	/*
1804 	 * If the user isn't interested in peripherals, don't descend
1805 	 * the tree any further.
1806 	 */
1807 	if ((retval & DM_RET_ACTION_MASK) == DM_RET_STOP)
1808 		return(1);
1809 
1810 	/*
1811 	 * If there is a peripheral list generation recorded, make sure
1812 	 * it hasn't changed.
1813 	 */
1814 	xpt_lock_buses();
1815 	mtx_lock(&bus->eb_mtx);
1816 	if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
1817 	 && (cdm->pos.cookie.bus == bus)
1818 	 && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
1819 	 && (cdm->pos.cookie.target == device->target)
1820 	 && (cdm->pos.position_type & CAM_DEV_POS_DEVICE)
1821 	 && (cdm->pos.cookie.device == device)
1822 	 && (cdm->pos.position_type & CAM_DEV_POS_PERIPH)
1823 	 && (cdm->pos.cookie.periph != NULL)) {
1824 		if (cdm->pos.generations[CAM_PERIPH_GENERATION] !=
1825 		    device->generation) {
1826 			mtx_unlock(&bus->eb_mtx);
1827 			xpt_unlock_buses();
1828 			cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
1829 			return(0);
1830 		}
1831 		periph = (struct cam_periph *)cdm->pos.cookie.periph;
1832 		periph->refcount++;
1833 	} else
1834 		periph = NULL;
1835 	mtx_unlock(&bus->eb_mtx);
1836 	xpt_unlock_buses();
1837 
1838 	return (xptperiphtraverse(device, periph, xptedtperiphfunc, arg));
1839 }
1840 
1841 static int
1842 xptedtperiphfunc(struct cam_periph *periph, void *arg)
1843 {
1844 	struct ccb_dev_match *cdm;
1845 	dev_match_ret retval;
1846 
1847 	cdm = (struct ccb_dev_match *)arg;
1848 
1849 	retval = xptperiphmatch(cdm->patterns, cdm->num_patterns, periph);
1850 
1851 	if ((retval & DM_RET_ACTION_MASK) == DM_RET_ERROR) {
1852 		cdm->status = CAM_DEV_MATCH_ERROR;
1853 		return(0);
1854 	}
1855 
1856 	/*
1857 	 * If the copy flag is set, copy this peripheral out.
1858 	 */
1859 	if (retval & DM_RET_COPY) {
1860 		int spaceleft, j;
1861 
1862 		spaceleft = cdm->match_buf_len - (cdm->num_matches *
1863 			sizeof(struct dev_match_result));
1864 
1865 		/*
1866 		 * If we don't have enough space to put in another
1867 		 * match result, save our position and tell the
1868 		 * user there are more devices to check.
1869 		 */
1870 		if (spaceleft < sizeof(struct dev_match_result)) {
1871 			bzero(&cdm->pos, sizeof(cdm->pos));
1872 			cdm->pos.position_type =
1873 				CAM_DEV_POS_EDT | CAM_DEV_POS_BUS |
1874 				CAM_DEV_POS_TARGET | CAM_DEV_POS_DEVICE |
1875 				CAM_DEV_POS_PERIPH;
1876 
1877 			cdm->pos.cookie.bus = periph->path->bus;
1878 			cdm->pos.generations[CAM_BUS_GENERATION]=
1879 				xsoftc.bus_generation;
1880 			cdm->pos.cookie.target = periph->path->target;
1881 			cdm->pos.generations[CAM_TARGET_GENERATION] =
1882 				periph->path->bus->generation;
1883 			cdm->pos.cookie.device = periph->path->device;
1884 			cdm->pos.generations[CAM_DEV_GENERATION] =
1885 				periph->path->target->generation;
1886 			cdm->pos.cookie.periph = periph;
1887 			cdm->pos.generations[CAM_PERIPH_GENERATION] =
1888 				periph->path->device->generation;
1889 			cdm->status = CAM_DEV_MATCH_MORE;
1890 			return(0);
1891 		}
1892 
1893 		j = cdm->num_matches;
1894 		cdm->num_matches++;
1895 		cdm->matches[j].type = DEV_MATCH_PERIPH;
1896 		cdm->matches[j].result.periph_result.path_id =
1897 			periph->path->bus->path_id;
1898 		cdm->matches[j].result.periph_result.target_id =
1899 			periph->path->target->target_id;
1900 		cdm->matches[j].result.periph_result.target_lun =
1901 			periph->path->device->lun_id;
1902 		cdm->matches[j].result.periph_result.unit_number =
1903 			periph->unit_number;
1904 		strncpy(cdm->matches[j].result.periph_result.periph_name,
1905 			periph->periph_name, DEV_IDLEN);
1906 	}
1907 
1908 	return(1);
1909 }
1910 
1911 static int
1912 xptedtmatch(struct ccb_dev_match *cdm)
1913 {
1914 	struct cam_eb *bus;
1915 	int ret;
1916 
1917 	cdm->num_matches = 0;
1918 
1919 	/*
1920 	 * Check the bus list generation.  If it has changed, the user
1921 	 * needs to reset everything and start over.
1922 	 */
1923 	xpt_lock_buses();
1924 	if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
1925 	 && (cdm->pos.cookie.bus != NULL)) {
1926 		if (cdm->pos.generations[CAM_BUS_GENERATION] !=
1927 		    xsoftc.bus_generation) {
1928 			xpt_unlock_buses();
1929 			cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
1930 			return(0);
1931 		}
1932 		bus = (struct cam_eb *)cdm->pos.cookie.bus;
1933 		bus->refcount++;
1934 	} else
1935 		bus = NULL;
1936 	xpt_unlock_buses();
1937 
1938 	ret = xptbustraverse(bus, xptedtbusfunc, cdm);
1939 
1940 	/*
1941 	 * If we get back 0, that means that we had to stop before fully
1942 	 * traversing the EDT.  It also means that one of the subroutines
1943 	 * has set the status field to the proper value.  If we get back 1,
1944 	 * we've fully traversed the EDT and copied out any matching entries.
1945 	 */
1946 	if (ret == 1)
1947 		cdm->status = CAM_DEV_MATCH_LAST;
1948 
1949 	return(ret);
1950 }
1951 
1952 static int
1953 xptplistpdrvfunc(struct periph_driver **pdrv, void *arg)
1954 {
1955 	struct cam_periph *periph;
1956 	struct ccb_dev_match *cdm;
1957 
1958 	cdm = (struct ccb_dev_match *)arg;
1959 
1960 	xpt_lock_buses();
1961 	if ((cdm->pos.position_type & CAM_DEV_POS_PDPTR)
1962 	 && (cdm->pos.cookie.pdrv == pdrv)
1963 	 && (cdm->pos.position_type & CAM_DEV_POS_PERIPH)
1964 	 && (cdm->pos.cookie.periph != NULL)) {
1965 		if (cdm->pos.generations[CAM_PERIPH_GENERATION] !=
1966 		    (*pdrv)->generation) {
1967 			xpt_unlock_buses();
1968 			cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
1969 			return(0);
1970 		}
1971 		periph = (struct cam_periph *)cdm->pos.cookie.periph;
1972 		periph->refcount++;
1973 	} else
1974 		periph = NULL;
1975 	xpt_unlock_buses();
1976 
1977 	return (xptpdperiphtraverse(pdrv, periph, xptplistperiphfunc, arg));
1978 }
1979 
1980 static int
1981 xptplistperiphfunc(struct cam_periph *periph, void *arg)
1982 {
1983 	struct ccb_dev_match *cdm;
1984 	dev_match_ret retval;
1985 
1986 	cdm = (struct ccb_dev_match *)arg;
1987 
1988 	retval = xptperiphmatch(cdm->patterns, cdm->num_patterns, periph);
1989 
1990 	if ((retval & DM_RET_ACTION_MASK) == DM_RET_ERROR) {
1991 		cdm->status = CAM_DEV_MATCH_ERROR;
1992 		return(0);
1993 	}
1994 
1995 	/*
1996 	 * If the copy flag is set, copy this peripheral out.
1997 	 */
1998 	if (retval & DM_RET_COPY) {
1999 		int spaceleft, j;
2000 
2001 		spaceleft = cdm->match_buf_len - (cdm->num_matches *
2002 			sizeof(struct dev_match_result));
2003 
2004 		/*
2005 		 * If we don't have enough space to put in another
2006 		 * match result, save our position and tell the
2007 		 * user there are more devices to check.
2008 		 */
2009 		if (spaceleft < sizeof(struct dev_match_result)) {
2010 			struct periph_driver **pdrv;
2011 
2012 			pdrv = NULL;
2013 			bzero(&cdm->pos, sizeof(cdm->pos));
2014 			cdm->pos.position_type =
2015 				CAM_DEV_POS_PDRV | CAM_DEV_POS_PDPTR |
2016 				CAM_DEV_POS_PERIPH;
2017 
2018 			/*
2019 			 * This may look a bit non-sensical, but it is
2020 			 * actually quite logical.  There are very few
2021 			 * peripheral drivers, and bloating every peripheral
2022 			 * structure with a pointer back to its parent
2023 			 * peripheral driver linker set entry would cost
2024 			 * more in the long run than doing this quick lookup.
2025 			 */
2026 			for (pdrv = periph_drivers; *pdrv != NULL; pdrv++) {
2027 				if (strcmp((*pdrv)->driver_name,
2028 				    periph->periph_name) == 0)
2029 					break;
2030 			}
2031 
2032 			if (*pdrv == NULL) {
2033 				cdm->status = CAM_DEV_MATCH_ERROR;
2034 				return(0);
2035 			}
2036 
2037 			cdm->pos.cookie.pdrv = pdrv;
2038 			/*
2039 			 * The periph generation slot does double duty, as
2040 			 * does the periph pointer slot.  They are used for
2041 			 * both edt and pdrv lookups and positioning.
2042 			 */
2043 			cdm->pos.cookie.periph = periph;
2044 			cdm->pos.generations[CAM_PERIPH_GENERATION] =
2045 				(*pdrv)->generation;
2046 			cdm->status = CAM_DEV_MATCH_MORE;
2047 			return(0);
2048 		}
2049 
2050 		j = cdm->num_matches;
2051 		cdm->num_matches++;
2052 		cdm->matches[j].type = DEV_MATCH_PERIPH;
2053 		cdm->matches[j].result.periph_result.path_id =
2054 			periph->path->bus->path_id;
2055 
2056 		/*
2057 		 * The transport layer peripheral doesn't have a target or
2058 		 * lun.
2059 		 */
2060 		if (periph->path->target)
2061 			cdm->matches[j].result.periph_result.target_id =
2062 				periph->path->target->target_id;
2063 		else
2064 			cdm->matches[j].result.periph_result.target_id =
2065 				CAM_TARGET_WILDCARD;
2066 
2067 		if (periph->path->device)
2068 			cdm->matches[j].result.periph_result.target_lun =
2069 				periph->path->device->lun_id;
2070 		else
2071 			cdm->matches[j].result.periph_result.target_lun =
2072 				CAM_LUN_WILDCARD;
2073 
2074 		cdm->matches[j].result.periph_result.unit_number =
2075 			periph->unit_number;
2076 		strncpy(cdm->matches[j].result.periph_result.periph_name,
2077 			periph->periph_name, DEV_IDLEN);
2078 	}
2079 
2080 	return(1);
2081 }
2082 
2083 static int
2084 xptperiphlistmatch(struct ccb_dev_match *cdm)
2085 {
2086 	int ret;
2087 
2088 	cdm->num_matches = 0;
2089 
2090 	/*
2091 	 * At this point in the edt traversal function, we check the bus
2092 	 * list generation to make sure that no buses have been added or
2093 	 * removed since the user last sent a XPT_DEV_MATCH ccb through.
2094 	 * For the peripheral driver list traversal function, however, we
2095 	 * don't have to worry about new peripheral driver types coming or
2096 	 * going; they're in a linker set, and therefore can't change
2097 	 * without a recompile.
2098 	 */
2099 
2100 	if ((cdm->pos.position_type & CAM_DEV_POS_PDPTR)
2101 	 && (cdm->pos.cookie.pdrv != NULL))
2102 		ret = xptpdrvtraverse(
2103 				(struct periph_driver **)cdm->pos.cookie.pdrv,
2104 				xptplistpdrvfunc, cdm);
2105 	else
2106 		ret = xptpdrvtraverse(NULL, xptplistpdrvfunc, cdm);
2107 
2108 	/*
2109 	 * If we get back 0, that means that we had to stop before fully
2110 	 * traversing the peripheral driver tree.  It also means that one of
2111 	 * the subroutines has set the status field to the proper value.  If
2112 	 * we get back 1, we've fully traversed the EDT and copied out any
2113 	 * matching entries.
2114 	 */
2115 	if (ret == 1)
2116 		cdm->status = CAM_DEV_MATCH_LAST;
2117 
2118 	return(ret);
2119 }
2120 
2121 static int
2122 xptbustraverse(struct cam_eb *start_bus, xpt_busfunc_t *tr_func, void *arg)
2123 {
2124 	struct cam_eb *bus, *next_bus;
2125 	int retval;
2126 
2127 	retval = 1;
2128 	if (start_bus)
2129 		bus = start_bus;
2130 	else {
2131 		xpt_lock_buses();
2132 		bus = TAILQ_FIRST(&xsoftc.xpt_busses);
2133 		if (bus == NULL) {
2134 			xpt_unlock_buses();
2135 			return (retval);
2136 		}
2137 		bus->refcount++;
2138 		xpt_unlock_buses();
2139 	}
2140 	for (; bus != NULL; bus = next_bus) {
2141 		retval = tr_func(bus, arg);
2142 		if (retval == 0) {
2143 			xpt_release_bus(bus);
2144 			break;
2145 		}
2146 		xpt_lock_buses();
2147 		next_bus = TAILQ_NEXT(bus, links);
2148 		if (next_bus)
2149 			next_bus->refcount++;
2150 		xpt_unlock_buses();
2151 		xpt_release_bus(bus);
2152 	}
2153 	return(retval);
2154 }
2155 
2156 static int
2157 xpttargettraverse(struct cam_eb *bus, struct cam_et *start_target,
2158 		  xpt_targetfunc_t *tr_func, void *arg)
2159 {
2160 	struct cam_et *target, *next_target;
2161 	int retval;
2162 
2163 	retval = 1;
2164 	if (start_target)
2165 		target = start_target;
2166 	else {
2167 		mtx_lock(&bus->eb_mtx);
2168 		target = TAILQ_FIRST(&bus->et_entries);
2169 		if (target == NULL) {
2170 			mtx_unlock(&bus->eb_mtx);
2171 			return (retval);
2172 		}
2173 		target->refcount++;
2174 		mtx_unlock(&bus->eb_mtx);
2175 	}
2176 	for (; target != NULL; target = next_target) {
2177 		retval = tr_func(target, arg);
2178 		if (retval == 0) {
2179 			xpt_release_target(target);
2180 			break;
2181 		}
2182 		mtx_lock(&bus->eb_mtx);
2183 		next_target = TAILQ_NEXT(target, links);
2184 		if (next_target)
2185 			next_target->refcount++;
2186 		mtx_unlock(&bus->eb_mtx);
2187 		xpt_release_target(target);
2188 	}
2189 	return(retval);
2190 }
2191 
2192 static int
2193 xptdevicetraverse(struct cam_et *target, struct cam_ed *start_device,
2194 		  xpt_devicefunc_t *tr_func, void *arg)
2195 {
2196 	struct cam_eb *bus;
2197 	struct cam_ed *device, *next_device;
2198 	int retval;
2199 
2200 	retval = 1;
2201 	bus = target->bus;
2202 	if (start_device)
2203 		device = start_device;
2204 	else {
2205 		mtx_lock(&bus->eb_mtx);
2206 		device = TAILQ_FIRST(&target->ed_entries);
2207 		if (device == NULL) {
2208 			mtx_unlock(&bus->eb_mtx);
2209 			return (retval);
2210 		}
2211 		device->refcount++;
2212 		mtx_unlock(&bus->eb_mtx);
2213 	}
2214 	for (; device != NULL; device = next_device) {
2215 		mtx_lock(&device->device_mtx);
2216 		retval = tr_func(device, arg);
2217 		mtx_unlock(&device->device_mtx);
2218 		if (retval == 0) {
2219 			xpt_release_device(device);
2220 			break;
2221 		}
2222 		mtx_lock(&bus->eb_mtx);
2223 		next_device = TAILQ_NEXT(device, links);
2224 		if (next_device)
2225 			next_device->refcount++;
2226 		mtx_unlock(&bus->eb_mtx);
2227 		xpt_release_device(device);
2228 	}
2229 	return(retval);
2230 }
2231 
2232 static int
2233 xptperiphtraverse(struct cam_ed *device, struct cam_periph *start_periph,
2234 		  xpt_periphfunc_t *tr_func, void *arg)
2235 {
2236 	struct cam_eb *bus;
2237 	struct cam_periph *periph, *next_periph;
2238 	int retval;
2239 
2240 	retval = 1;
2241 
2242 	bus = device->target->bus;
2243 	if (start_periph)
2244 		periph = start_periph;
2245 	else {
2246 		xpt_lock_buses();
2247 		mtx_lock(&bus->eb_mtx);
2248 		periph = SLIST_FIRST(&device->periphs);
2249 		while (periph != NULL && (periph->flags & CAM_PERIPH_FREE) != 0)
2250 			periph = SLIST_NEXT(periph, periph_links);
2251 		if (periph == NULL) {
2252 			mtx_unlock(&bus->eb_mtx);
2253 			xpt_unlock_buses();
2254 			return (retval);
2255 		}
2256 		periph->refcount++;
2257 		mtx_unlock(&bus->eb_mtx);
2258 		xpt_unlock_buses();
2259 	}
2260 	for (; periph != NULL; periph = next_periph) {
2261 		retval = tr_func(periph, arg);
2262 		if (retval == 0) {
2263 			cam_periph_release_locked(periph);
2264 			break;
2265 		}
2266 		xpt_lock_buses();
2267 		mtx_lock(&bus->eb_mtx);
2268 		next_periph = SLIST_NEXT(periph, periph_links);
2269 		while (next_periph != NULL &&
2270 		    (next_periph->flags & CAM_PERIPH_FREE) != 0)
2271 			next_periph = SLIST_NEXT(next_periph, periph_links);
2272 		if (next_periph)
2273 			next_periph->refcount++;
2274 		mtx_unlock(&bus->eb_mtx);
2275 		xpt_unlock_buses();
2276 		cam_periph_release_locked(periph);
2277 	}
2278 	return(retval);
2279 }
2280 
2281 static int
2282 xptpdrvtraverse(struct periph_driver **start_pdrv,
2283 		xpt_pdrvfunc_t *tr_func, void *arg)
2284 {
2285 	struct periph_driver **pdrv;
2286 	int retval;
2287 
2288 	retval = 1;
2289 
2290 	/*
2291 	 * We don't traverse the peripheral driver list like we do the
2292 	 * other lists, because it is a linker set, and therefore cannot be
2293 	 * changed during runtime.  If the peripheral driver list is ever
2294 	 * re-done to be something other than a linker set (i.e. it can
2295 	 * change while the system is running), the list traversal should
2296 	 * be modified to work like the other traversal functions.
2297 	 */
2298 	for (pdrv = (start_pdrv ? start_pdrv : periph_drivers);
2299 	     *pdrv != NULL; pdrv++) {
2300 		retval = tr_func(pdrv, arg);
2301 
2302 		if (retval == 0)
2303 			return(retval);
2304 	}
2305 
2306 	return(retval);
2307 }
2308 
2309 static int
2310 xptpdperiphtraverse(struct periph_driver **pdrv,
2311 		    struct cam_periph *start_periph,
2312 		    xpt_periphfunc_t *tr_func, void *arg)
2313 {
2314 	struct cam_periph *periph, *next_periph;
2315 	int retval;
2316 
2317 	retval = 1;
2318 
2319 	if (start_periph)
2320 		periph = start_periph;
2321 	else {
2322 		xpt_lock_buses();
2323 		periph = TAILQ_FIRST(&(*pdrv)->units);
2324 		while (periph != NULL && (periph->flags & CAM_PERIPH_FREE) != 0)
2325 			periph = TAILQ_NEXT(periph, unit_links);
2326 		if (periph == NULL) {
2327 			xpt_unlock_buses();
2328 			return (retval);
2329 		}
2330 		periph->refcount++;
2331 		xpt_unlock_buses();
2332 	}
2333 	for (; periph != NULL; periph = next_periph) {
2334 		cam_periph_lock(periph);
2335 		retval = tr_func(periph, arg);
2336 		cam_periph_unlock(periph);
2337 		if (retval == 0) {
2338 			cam_periph_release(periph);
2339 			break;
2340 		}
2341 		xpt_lock_buses();
2342 		next_periph = TAILQ_NEXT(periph, unit_links);
2343 		while (next_periph != NULL &&
2344 		    (next_periph->flags & CAM_PERIPH_FREE) != 0)
2345 			next_periph = TAILQ_NEXT(next_periph, unit_links);
2346 		if (next_periph)
2347 			next_periph->refcount++;
2348 		xpt_unlock_buses();
2349 		cam_periph_release(periph);
2350 	}
2351 	return(retval);
2352 }
2353 
2354 static int
2355 xptdefbusfunc(struct cam_eb *bus, void *arg)
2356 {
2357 	struct xpt_traverse_config *tr_config;
2358 
2359 	tr_config = (struct xpt_traverse_config *)arg;
2360 
2361 	if (tr_config->depth == XPT_DEPTH_BUS) {
2362 		xpt_busfunc_t *tr_func;
2363 
2364 		tr_func = (xpt_busfunc_t *)tr_config->tr_func;
2365 
2366 		return(tr_func(bus, tr_config->tr_arg));
2367 	} else
2368 		return(xpttargettraverse(bus, NULL, xptdeftargetfunc, arg));
2369 }
2370 
2371 static int
2372 xptdeftargetfunc(struct cam_et *target, void *arg)
2373 {
2374 	struct xpt_traverse_config *tr_config;
2375 
2376 	tr_config = (struct xpt_traverse_config *)arg;
2377 
2378 	if (tr_config->depth == XPT_DEPTH_TARGET) {
2379 		xpt_targetfunc_t *tr_func;
2380 
2381 		tr_func = (xpt_targetfunc_t *)tr_config->tr_func;
2382 
2383 		return(tr_func(target, tr_config->tr_arg));
2384 	} else
2385 		return(xptdevicetraverse(target, NULL, xptdefdevicefunc, arg));
2386 }
2387 
2388 static int
2389 xptdefdevicefunc(struct cam_ed *device, void *arg)
2390 {
2391 	struct xpt_traverse_config *tr_config;
2392 
2393 	tr_config = (struct xpt_traverse_config *)arg;
2394 
2395 	if (tr_config->depth == XPT_DEPTH_DEVICE) {
2396 		xpt_devicefunc_t *tr_func;
2397 
2398 		tr_func = (xpt_devicefunc_t *)tr_config->tr_func;
2399 
2400 		return(tr_func(device, tr_config->tr_arg));
2401 	} else
2402 		return(xptperiphtraverse(device, NULL, xptdefperiphfunc, arg));
2403 }
2404 
2405 static int
2406 xptdefperiphfunc(struct cam_periph *periph, void *arg)
2407 {
2408 	struct xpt_traverse_config *tr_config;
2409 	xpt_periphfunc_t *tr_func;
2410 
2411 	tr_config = (struct xpt_traverse_config *)arg;
2412 
2413 	tr_func = (xpt_periphfunc_t *)tr_config->tr_func;
2414 
2415 	/*
2416 	 * Unlike the other default functions, we don't check for depth
2417 	 * here.  The peripheral driver level is the last level in the EDT,
2418 	 * so if we're here, we should execute the function in question.
2419 	 */
2420 	return(tr_func(periph, tr_config->tr_arg));
2421 }
2422 
2423 /*
2424  * Execute the given function for every bus in the EDT.
2425  */
2426 static int
2427 xpt_for_all_busses(xpt_busfunc_t *tr_func, void *arg)
2428 {
2429 	struct xpt_traverse_config tr_config;
2430 
2431 	tr_config.depth = XPT_DEPTH_BUS;
2432 	tr_config.tr_func = tr_func;
2433 	tr_config.tr_arg = arg;
2434 
2435 	return(xptbustraverse(NULL, xptdefbusfunc, &tr_config));
2436 }
2437 
2438 /*
2439  * Execute the given function for every device in the EDT.
2440  */
2441 static int
2442 xpt_for_all_devices(xpt_devicefunc_t *tr_func, void *arg)
2443 {
2444 	struct xpt_traverse_config tr_config;
2445 
2446 	tr_config.depth = XPT_DEPTH_DEVICE;
2447 	tr_config.tr_func = tr_func;
2448 	tr_config.tr_arg = arg;
2449 
2450 	return(xptbustraverse(NULL, xptdefbusfunc, &tr_config));
2451 }
2452 
2453 static int
2454 xptsetasyncfunc(struct cam_ed *device, void *arg)
2455 {
2456 	struct cam_path path;
2457 	struct ccb_getdev cgd;
2458 	struct ccb_setasync *csa = (struct ccb_setasync *)arg;
2459 
2460 	/*
2461 	 * Don't report unconfigured devices (Wildcard devs,
2462 	 * devices only for target mode, device instances
2463 	 * that have been invalidated but are waiting for
2464 	 * their last reference count to be released).
2465 	 */
2466 	if ((device->flags & CAM_DEV_UNCONFIGURED) != 0)
2467 		return (1);
2468 
2469 	xpt_compile_path(&path,
2470 			 NULL,
2471 			 device->target->bus->path_id,
2472 			 device->target->target_id,
2473 			 device->lun_id);
2474 	xpt_setup_ccb(&cgd.ccb_h, &path, CAM_PRIORITY_NORMAL);
2475 	cgd.ccb_h.func_code = XPT_GDEV_TYPE;
2476 	xpt_action((union ccb *)&cgd);
2477 	csa->callback(csa->callback_arg,
2478 			    AC_FOUND_DEVICE,
2479 			    &path, &cgd);
2480 	xpt_release_path(&path);
2481 
2482 	return(1);
2483 }
2484 
2485 static int
2486 xptsetasyncbusfunc(struct cam_eb *bus, void *arg)
2487 {
2488 	struct cam_path path;
2489 	struct ccb_pathinq cpi;
2490 	struct ccb_setasync *csa = (struct ccb_setasync *)arg;
2491 
2492 	xpt_compile_path(&path, /*periph*/NULL,
2493 			 bus->path_id,
2494 			 CAM_TARGET_WILDCARD,
2495 			 CAM_LUN_WILDCARD);
2496 	xpt_path_lock(&path);
2497 	xpt_setup_ccb(&cpi.ccb_h, &path, CAM_PRIORITY_NORMAL);
2498 	cpi.ccb_h.func_code = XPT_PATH_INQ;
2499 	xpt_action((union ccb *)&cpi);
2500 	csa->callback(csa->callback_arg,
2501 			    AC_PATH_REGISTERED,
2502 			    &path, &cpi);
2503 	xpt_path_unlock(&path);
2504 	xpt_release_path(&path);
2505 
2506 	return(1);
2507 }
2508 
2509 void
2510 xpt_action(union ccb *start_ccb)
2511 {
2512 
2513 	CAM_DEBUG(start_ccb->ccb_h.path, CAM_DEBUG_TRACE,
2514 	    ("xpt_action: func %#x %s\n", start_ccb->ccb_h.func_code,
2515 		xpt_action_name(start_ccb->ccb_h.func_code)));
2516 
2517 	start_ccb->ccb_h.status = CAM_REQ_INPROG;
2518 	(*(start_ccb->ccb_h.path->bus->xport->ops->action))(start_ccb);
2519 }
2520 
2521 void
2522 xpt_action_default(union ccb *start_ccb)
2523 {
2524 	struct cam_path *path;
2525 	struct cam_sim *sim;
2526 	int lock;
2527 
2528 	path = start_ccb->ccb_h.path;
2529 	CAM_DEBUG(path, CAM_DEBUG_TRACE,
2530 	    ("xpt_action_default: func %#x %s\n", start_ccb->ccb_h.func_code,
2531 		xpt_action_name(start_ccb->ccb_h.func_code)));
2532 
2533 	switch (start_ccb->ccb_h.func_code) {
2534 	case XPT_SCSI_IO:
2535 	{
2536 		struct cam_ed *device;
2537 
2538 		/*
2539 		 * For the sake of compatibility with SCSI-1
2540 		 * devices that may not understand the identify
2541 		 * message, we include lun information in the
2542 		 * second byte of all commands.  SCSI-1 specifies
2543 		 * that luns are a 3 bit value and reserves only 3
2544 		 * bits for lun information in the CDB.  Later
2545 		 * revisions of the SCSI spec allow for more than 8
2546 		 * luns, but have deprecated lun information in the
2547 		 * CDB.  So, if the lun won't fit, we must omit.
2548 		 *
2549 		 * Also be aware that during initial probing for devices,
2550 		 * the inquiry information is unknown but initialized to 0.
2551 		 * This means that this code will be exercised while probing
2552 		 * devices with an ANSI revision greater than 2.
2553 		 */
2554 		device = path->device;
2555 		if (device->protocol_version <= SCSI_REV_2
2556 		 && start_ccb->ccb_h.target_lun < 8
2557 		 && (start_ccb->ccb_h.flags & CAM_CDB_POINTER) == 0) {
2558 
2559 			start_ccb->csio.cdb_io.cdb_bytes[1] |=
2560 			    start_ccb->ccb_h.target_lun << 5;
2561 		}
2562 		start_ccb->csio.scsi_status = SCSI_STATUS_OK;
2563 	}
2564 	/* FALLTHROUGH */
2565 	case XPT_TARGET_IO:
2566 	case XPT_CONT_TARGET_IO:
2567 		start_ccb->csio.sense_resid = 0;
2568 		start_ccb->csio.resid = 0;
2569 		/* FALLTHROUGH */
2570 	case XPT_ATA_IO:
2571 		if (start_ccb->ccb_h.func_code == XPT_ATA_IO)
2572 			start_ccb->ataio.resid = 0;
2573 		/* FALLTHROUGH */
2574 	case XPT_NVME_IO:
2575 		if (start_ccb->ccb_h.func_code == XPT_NVME_IO)
2576 			start_ccb->nvmeio.resid = 0;
2577 		/* FALLTHROUGH */
2578 	case XPT_RESET_DEV:
2579 	case XPT_ENG_EXEC:
2580 	case XPT_SMP_IO:
2581 	{
2582 		struct cam_devq *devq;
2583 
2584 		devq = path->bus->sim->devq;
2585 		mtx_lock(&devq->send_mtx);
2586 		cam_ccbq_insert_ccb(&path->device->ccbq, start_ccb);
2587 		if (xpt_schedule_devq(devq, path->device) != 0)
2588 			xpt_run_devq(devq);
2589 		mtx_unlock(&devq->send_mtx);
2590 		break;
2591 	}
2592 	case XPT_CALC_GEOMETRY:
2593 		/* Filter out garbage */
2594 		if (start_ccb->ccg.block_size == 0
2595 		 || start_ccb->ccg.volume_size == 0) {
2596 			start_ccb->ccg.cylinders = 0;
2597 			start_ccb->ccg.heads = 0;
2598 			start_ccb->ccg.secs_per_track = 0;
2599 			start_ccb->ccb_h.status = CAM_REQ_CMP;
2600 			break;
2601 		}
2602 #if defined(__sparc64__)
2603 		/*
2604 		 * For sparc64, we may need adjust the geometry of large
2605 		 * disks in order to fit the limitations of the 16-bit
2606 		 * fields of the VTOC8 disk label.
2607 		 */
2608 		if (scsi_da_bios_params(&start_ccb->ccg) != 0) {
2609 			start_ccb->ccb_h.status = CAM_REQ_CMP;
2610 			break;
2611 		}
2612 #endif
2613 		goto call_sim;
2614 	case XPT_ABORT:
2615 	{
2616 		union ccb* abort_ccb;
2617 
2618 		abort_ccb = start_ccb->cab.abort_ccb;
2619 		if (XPT_FC_IS_DEV_QUEUED(abort_ccb)) {
2620 			struct cam_ed *device;
2621 			struct cam_devq *devq;
2622 
2623 			device = abort_ccb->ccb_h.path->device;
2624 			devq = device->sim->devq;
2625 
2626 			mtx_lock(&devq->send_mtx);
2627 			if (abort_ccb->ccb_h.pinfo.index > 0) {
2628 				cam_ccbq_remove_ccb(&device->ccbq, abort_ccb);
2629 				abort_ccb->ccb_h.status =
2630 				    CAM_REQ_ABORTED|CAM_DEV_QFRZN;
2631 				xpt_freeze_devq_device(device, 1);
2632 				mtx_unlock(&devq->send_mtx);
2633 				xpt_done(abort_ccb);
2634 				start_ccb->ccb_h.status = CAM_REQ_CMP;
2635 				break;
2636 			}
2637 			mtx_unlock(&devq->send_mtx);
2638 
2639 			if (abort_ccb->ccb_h.pinfo.index == CAM_UNQUEUED_INDEX
2640 			 && (abort_ccb->ccb_h.status & CAM_SIM_QUEUED) == 0) {
2641 				/*
2642 				 * We've caught this ccb en route to
2643 				 * the SIM.  Flag it for abort and the
2644 				 * SIM will do so just before starting
2645 				 * real work on the CCB.
2646 				 */
2647 				abort_ccb->ccb_h.status =
2648 				    CAM_REQ_ABORTED|CAM_DEV_QFRZN;
2649 				xpt_freeze_devq(abort_ccb->ccb_h.path, 1);
2650 				start_ccb->ccb_h.status = CAM_REQ_CMP;
2651 				break;
2652 			}
2653 		}
2654 		if (XPT_FC_IS_QUEUED(abort_ccb)
2655 		 && (abort_ccb->ccb_h.pinfo.index == CAM_DONEQ_INDEX)) {
2656 			/*
2657 			 * It's already completed but waiting
2658 			 * for our SWI to get to it.
2659 			 */
2660 			start_ccb->ccb_h.status = CAM_UA_ABORT;
2661 			break;
2662 		}
2663 		/*
2664 		 * If we weren't able to take care of the abort request
2665 		 * in the XPT, pass the request down to the SIM for processing.
2666 		 */
2667 	}
2668 	/* FALLTHROUGH */
2669 	case XPT_ACCEPT_TARGET_IO:
2670 	case XPT_EN_LUN:
2671 	case XPT_IMMED_NOTIFY:
2672 	case XPT_NOTIFY_ACK:
2673 	case XPT_RESET_BUS:
2674 	case XPT_IMMEDIATE_NOTIFY:
2675 	case XPT_NOTIFY_ACKNOWLEDGE:
2676 	case XPT_GET_SIM_KNOB_OLD:
2677 	case XPT_GET_SIM_KNOB:
2678 	case XPT_SET_SIM_KNOB:
2679 	case XPT_GET_TRAN_SETTINGS:
2680 	case XPT_SET_TRAN_SETTINGS:
2681 	case XPT_PATH_INQ:
2682 call_sim:
2683 		sim = path->bus->sim;
2684 		lock = (mtx_owned(sim->mtx) == 0);
2685 		if (lock)
2686 			CAM_SIM_LOCK(sim);
2687 		CAM_DEBUG(path, CAM_DEBUG_TRACE,
2688 		    ("sim->sim_action: func=%#x\n", start_ccb->ccb_h.func_code));
2689 		(*(sim->sim_action))(sim, start_ccb);
2690 		CAM_DEBUG(path, CAM_DEBUG_TRACE,
2691 		    ("sim->sim_action: status=%#x\n", start_ccb->ccb_h.status));
2692 		if (lock)
2693 			CAM_SIM_UNLOCK(sim);
2694 		break;
2695 	case XPT_PATH_STATS:
2696 		start_ccb->cpis.last_reset = path->bus->last_reset;
2697 		start_ccb->ccb_h.status = CAM_REQ_CMP;
2698 		break;
2699 	case XPT_GDEV_TYPE:
2700 	{
2701 		struct cam_ed *dev;
2702 
2703 		dev = path->device;
2704 		if ((dev->flags & CAM_DEV_UNCONFIGURED) != 0) {
2705 			start_ccb->ccb_h.status = CAM_DEV_NOT_THERE;
2706 		} else {
2707 			struct ccb_getdev *cgd;
2708 
2709 			cgd = &start_ccb->cgd;
2710 			cgd->protocol = dev->protocol;
2711 			cgd->inq_data = dev->inq_data;
2712 			cgd->ident_data = dev->ident_data;
2713 			cgd->inq_flags = dev->inq_flags;
2714 			cgd->nvme_data = dev->nvme_data;
2715 			cgd->nvme_cdata = dev->nvme_cdata;
2716 			cgd->ccb_h.status = CAM_REQ_CMP;
2717 			cgd->serial_num_len = dev->serial_num_len;
2718 			if ((dev->serial_num_len > 0)
2719 			 && (dev->serial_num != NULL))
2720 				bcopy(dev->serial_num, cgd->serial_num,
2721 				      dev->serial_num_len);
2722 		}
2723 		break;
2724 	}
2725 	case XPT_GDEV_STATS:
2726 	{
2727 		struct ccb_getdevstats *cgds = &start_ccb->cgds;
2728 		struct cam_ed *dev = path->device;
2729 		struct cam_eb *bus = path->bus;
2730 		struct cam_et *tar = path->target;
2731 		struct cam_devq *devq = bus->sim->devq;
2732 
2733 		mtx_lock(&devq->send_mtx);
2734 		cgds->dev_openings = dev->ccbq.dev_openings;
2735 		cgds->dev_active = dev->ccbq.dev_active;
2736 		cgds->allocated = dev->ccbq.allocated;
2737 		cgds->queued = cam_ccbq_pending_ccb_count(&dev->ccbq);
2738 		cgds->held = cgds->allocated - cgds->dev_active - cgds->queued;
2739 		cgds->last_reset = tar->last_reset;
2740 		cgds->maxtags = dev->maxtags;
2741 		cgds->mintags = dev->mintags;
2742 		if (timevalcmp(&tar->last_reset, &bus->last_reset, <))
2743 			cgds->last_reset = bus->last_reset;
2744 		mtx_unlock(&devq->send_mtx);
2745 		cgds->ccb_h.status = CAM_REQ_CMP;
2746 		break;
2747 	}
2748 	case XPT_GDEVLIST:
2749 	{
2750 		struct cam_periph	*nperiph;
2751 		struct periph_list	*periph_head;
2752 		struct ccb_getdevlist	*cgdl;
2753 		u_int			i;
2754 		struct cam_ed		*device;
2755 		int			found;
2756 
2757 
2758 		found = 0;
2759 
2760 		/*
2761 		 * Don't want anyone mucking with our data.
2762 		 */
2763 		device = path->device;
2764 		periph_head = &device->periphs;
2765 		cgdl = &start_ccb->cgdl;
2766 
2767 		/*
2768 		 * Check and see if the list has changed since the user
2769 		 * last requested a list member.  If so, tell them that the
2770 		 * list has changed, and therefore they need to start over
2771 		 * from the beginning.
2772 		 */
2773 		if ((cgdl->index != 0) &&
2774 		    (cgdl->generation != device->generation)) {
2775 			cgdl->status = CAM_GDEVLIST_LIST_CHANGED;
2776 			break;
2777 		}
2778 
2779 		/*
2780 		 * Traverse the list of peripherals and attempt to find
2781 		 * the requested peripheral.
2782 		 */
2783 		for (nperiph = SLIST_FIRST(periph_head), i = 0;
2784 		     (nperiph != NULL) && (i <= cgdl->index);
2785 		     nperiph = SLIST_NEXT(nperiph, periph_links), i++) {
2786 			if (i == cgdl->index) {
2787 				strncpy(cgdl->periph_name,
2788 					nperiph->periph_name,
2789 					DEV_IDLEN);
2790 				cgdl->unit_number = nperiph->unit_number;
2791 				found = 1;
2792 			}
2793 		}
2794 		if (found == 0) {
2795 			cgdl->status = CAM_GDEVLIST_ERROR;
2796 			break;
2797 		}
2798 
2799 		if (nperiph == NULL)
2800 			cgdl->status = CAM_GDEVLIST_LAST_DEVICE;
2801 		else
2802 			cgdl->status = CAM_GDEVLIST_MORE_DEVS;
2803 
2804 		cgdl->index++;
2805 		cgdl->generation = device->generation;
2806 
2807 		cgdl->ccb_h.status = CAM_REQ_CMP;
2808 		break;
2809 	}
2810 	case XPT_DEV_MATCH:
2811 	{
2812 		dev_pos_type position_type;
2813 		struct ccb_dev_match *cdm;
2814 
2815 		cdm = &start_ccb->cdm;
2816 
2817 		/*
2818 		 * There are two ways of getting at information in the EDT.
2819 		 * The first way is via the primary EDT tree.  It starts
2820 		 * with a list of buses, then a list of targets on a bus,
2821 		 * then devices/luns on a target, and then peripherals on a
2822 		 * device/lun.  The "other" way is by the peripheral driver
2823 		 * lists.  The peripheral driver lists are organized by
2824 		 * peripheral driver.  (obviously)  So it makes sense to
2825 		 * use the peripheral driver list if the user is looking
2826 		 * for something like "da1", or all "da" devices.  If the
2827 		 * user is looking for something on a particular bus/target
2828 		 * or lun, it's generally better to go through the EDT tree.
2829 		 */
2830 
2831 		if (cdm->pos.position_type != CAM_DEV_POS_NONE)
2832 			position_type = cdm->pos.position_type;
2833 		else {
2834 			u_int i;
2835 
2836 			position_type = CAM_DEV_POS_NONE;
2837 
2838 			for (i = 0; i < cdm->num_patterns; i++) {
2839 				if ((cdm->patterns[i].type == DEV_MATCH_BUS)
2840 				 ||(cdm->patterns[i].type == DEV_MATCH_DEVICE)){
2841 					position_type = CAM_DEV_POS_EDT;
2842 					break;
2843 				}
2844 			}
2845 
2846 			if (cdm->num_patterns == 0)
2847 				position_type = CAM_DEV_POS_EDT;
2848 			else if (position_type == CAM_DEV_POS_NONE)
2849 				position_type = CAM_DEV_POS_PDRV;
2850 		}
2851 
2852 		switch(position_type & CAM_DEV_POS_TYPEMASK) {
2853 		case CAM_DEV_POS_EDT:
2854 			xptedtmatch(cdm);
2855 			break;
2856 		case CAM_DEV_POS_PDRV:
2857 			xptperiphlistmatch(cdm);
2858 			break;
2859 		default:
2860 			cdm->status = CAM_DEV_MATCH_ERROR;
2861 			break;
2862 		}
2863 
2864 		if (cdm->status == CAM_DEV_MATCH_ERROR)
2865 			start_ccb->ccb_h.status = CAM_REQ_CMP_ERR;
2866 		else
2867 			start_ccb->ccb_h.status = CAM_REQ_CMP;
2868 
2869 		break;
2870 	}
2871 	case XPT_SASYNC_CB:
2872 	{
2873 		struct ccb_setasync *csa;
2874 		struct async_node *cur_entry;
2875 		struct async_list *async_head;
2876 		u_int32_t added;
2877 
2878 		csa = &start_ccb->csa;
2879 		added = csa->event_enable;
2880 		async_head = &path->device->asyncs;
2881 
2882 		/*
2883 		 * If there is already an entry for us, simply
2884 		 * update it.
2885 		 */
2886 		cur_entry = SLIST_FIRST(async_head);
2887 		while (cur_entry != NULL) {
2888 			if ((cur_entry->callback_arg == csa->callback_arg)
2889 			 && (cur_entry->callback == csa->callback))
2890 				break;
2891 			cur_entry = SLIST_NEXT(cur_entry, links);
2892 		}
2893 
2894 		if (cur_entry != NULL) {
2895 		 	/*
2896 			 * If the request has no flags set,
2897 			 * remove the entry.
2898 			 */
2899 			added &= ~cur_entry->event_enable;
2900 			if (csa->event_enable == 0) {
2901 				SLIST_REMOVE(async_head, cur_entry,
2902 					     async_node, links);
2903 				xpt_release_device(path->device);
2904 				free(cur_entry, M_CAMXPT);
2905 			} else {
2906 				cur_entry->event_enable = csa->event_enable;
2907 			}
2908 			csa->event_enable = added;
2909 		} else {
2910 			cur_entry = malloc(sizeof(*cur_entry), M_CAMXPT,
2911 					   M_NOWAIT);
2912 			if (cur_entry == NULL) {
2913 				csa->ccb_h.status = CAM_RESRC_UNAVAIL;
2914 				break;
2915 			}
2916 			cur_entry->event_enable = csa->event_enable;
2917 			cur_entry->event_lock =
2918 			    mtx_owned(path->bus->sim->mtx) ? 1 : 0;
2919 			cur_entry->callback_arg = csa->callback_arg;
2920 			cur_entry->callback = csa->callback;
2921 			SLIST_INSERT_HEAD(async_head, cur_entry, links);
2922 			xpt_acquire_device(path->device);
2923 		}
2924 		start_ccb->ccb_h.status = CAM_REQ_CMP;
2925 		break;
2926 	}
2927 	case XPT_REL_SIMQ:
2928 	{
2929 		struct ccb_relsim *crs;
2930 		struct cam_ed *dev;
2931 
2932 		crs = &start_ccb->crs;
2933 		dev = path->device;
2934 		if (dev == NULL) {
2935 
2936 			crs->ccb_h.status = CAM_DEV_NOT_THERE;
2937 			break;
2938 		}
2939 
2940 		if ((crs->release_flags & RELSIM_ADJUST_OPENINGS) != 0) {
2941 
2942 			/* Don't ever go below one opening */
2943 			if (crs->openings > 0) {
2944 				xpt_dev_ccbq_resize(path, crs->openings);
2945 				if (bootverbose) {
2946 					xpt_print(path,
2947 					    "number of openings is now %d\n",
2948 					    crs->openings);
2949 				}
2950 			}
2951 		}
2952 
2953 		mtx_lock(&dev->sim->devq->send_mtx);
2954 		if ((crs->release_flags & RELSIM_RELEASE_AFTER_TIMEOUT) != 0) {
2955 
2956 			if ((dev->flags & CAM_DEV_REL_TIMEOUT_PENDING) != 0) {
2957 
2958 				/*
2959 				 * Just extend the old timeout and decrement
2960 				 * the freeze count so that a single timeout
2961 				 * is sufficient for releasing the queue.
2962 				 */
2963 				start_ccb->ccb_h.flags &= ~CAM_DEV_QFREEZE;
2964 				callout_stop(&dev->callout);
2965 			} else {
2966 
2967 				start_ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
2968 			}
2969 
2970 			callout_reset_sbt(&dev->callout,
2971 			    SBT_1MS * crs->release_timeout, 0,
2972 			    xpt_release_devq_timeout, dev, 0);
2973 
2974 			dev->flags |= CAM_DEV_REL_TIMEOUT_PENDING;
2975 
2976 		}
2977 
2978 		if ((crs->release_flags & RELSIM_RELEASE_AFTER_CMDCMPLT) != 0) {
2979 
2980 			if ((dev->flags & CAM_DEV_REL_ON_COMPLETE) != 0) {
2981 				/*
2982 				 * Decrement the freeze count so that a single
2983 				 * completion is still sufficient to unfreeze
2984 				 * the queue.
2985 				 */
2986 				start_ccb->ccb_h.flags &= ~CAM_DEV_QFREEZE;
2987 			} else {
2988 
2989 				dev->flags |= CAM_DEV_REL_ON_COMPLETE;
2990 				start_ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
2991 			}
2992 		}
2993 
2994 		if ((crs->release_flags & RELSIM_RELEASE_AFTER_QEMPTY) != 0) {
2995 
2996 			if ((dev->flags & CAM_DEV_REL_ON_QUEUE_EMPTY) != 0
2997 			 || (dev->ccbq.dev_active == 0)) {
2998 
2999 				start_ccb->ccb_h.flags &= ~CAM_DEV_QFREEZE;
3000 			} else {
3001 
3002 				dev->flags |= CAM_DEV_REL_ON_QUEUE_EMPTY;
3003 				start_ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
3004 			}
3005 		}
3006 		mtx_unlock(&dev->sim->devq->send_mtx);
3007 
3008 		if ((start_ccb->ccb_h.flags & CAM_DEV_QFREEZE) == 0)
3009 			xpt_release_devq(path, /*count*/1, /*run_queue*/TRUE);
3010 		start_ccb->crs.qfrozen_cnt = dev->ccbq.queue.qfrozen_cnt;
3011 		start_ccb->ccb_h.status = CAM_REQ_CMP;
3012 		break;
3013 	}
3014 	case XPT_DEBUG: {
3015 		struct cam_path *oldpath;
3016 
3017 		/* Check that all request bits are supported. */
3018 		if (start_ccb->cdbg.flags & ~(CAM_DEBUG_COMPILE)) {
3019 			start_ccb->ccb_h.status = CAM_FUNC_NOTAVAIL;
3020 			break;
3021 		}
3022 
3023 		cam_dflags = CAM_DEBUG_NONE;
3024 		if (cam_dpath != NULL) {
3025 			oldpath = cam_dpath;
3026 			cam_dpath = NULL;
3027 			xpt_free_path(oldpath);
3028 		}
3029 		if (start_ccb->cdbg.flags != CAM_DEBUG_NONE) {
3030 			if (xpt_create_path(&cam_dpath, NULL,
3031 					    start_ccb->ccb_h.path_id,
3032 					    start_ccb->ccb_h.target_id,
3033 					    start_ccb->ccb_h.target_lun) !=
3034 					    CAM_REQ_CMP) {
3035 				start_ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
3036 			} else {
3037 				cam_dflags = start_ccb->cdbg.flags;
3038 				start_ccb->ccb_h.status = CAM_REQ_CMP;
3039 				xpt_print(cam_dpath, "debugging flags now %x\n",
3040 				    cam_dflags);
3041 			}
3042 		} else
3043 			start_ccb->ccb_h.status = CAM_REQ_CMP;
3044 		break;
3045 	}
3046 	case XPT_NOOP:
3047 		if ((start_ccb->ccb_h.flags & CAM_DEV_QFREEZE) != 0)
3048 			xpt_freeze_devq(path, 1);
3049 		start_ccb->ccb_h.status = CAM_REQ_CMP;
3050 		break;
3051 	case XPT_REPROBE_LUN:
3052 		xpt_async(AC_INQ_CHANGED, path, NULL);
3053 		start_ccb->ccb_h.status = CAM_REQ_CMP;
3054 		xpt_done(start_ccb);
3055 		break;
3056 	default:
3057 	case XPT_SDEV_TYPE:
3058 	case XPT_TERM_IO:
3059 	case XPT_ENG_INQ:
3060 		/* XXX Implement */
3061 		xpt_print(start_ccb->ccb_h.path,
3062 		    "%s: CCB type %#x %s not supported\n", __func__,
3063 		    start_ccb->ccb_h.func_code,
3064 		    xpt_action_name(start_ccb->ccb_h.func_code));
3065 		start_ccb->ccb_h.status = CAM_PROVIDE_FAIL;
3066 		if (start_ccb->ccb_h.func_code & XPT_FC_DEV_QUEUED) {
3067 			xpt_done(start_ccb);
3068 		}
3069 		break;
3070 	}
3071 	CAM_DEBUG(path, CAM_DEBUG_TRACE,
3072 	    ("xpt_action_default: func= %#x %s status %#x\n",
3073 		start_ccb->ccb_h.func_code,
3074  		xpt_action_name(start_ccb->ccb_h.func_code),
3075 		start_ccb->ccb_h.status));
3076 }
3077 
3078 void
3079 xpt_polled_action(union ccb *start_ccb)
3080 {
3081 	u_int32_t timeout;
3082 	struct	  cam_sim *sim;
3083 	struct	  cam_devq *devq;
3084 	struct	  cam_ed *dev;
3085 
3086 	timeout = start_ccb->ccb_h.timeout * 10;
3087 	sim = start_ccb->ccb_h.path->bus->sim;
3088 	devq = sim->devq;
3089 	dev = start_ccb->ccb_h.path->device;
3090 
3091 	mtx_unlock(&dev->device_mtx);
3092 
3093 	/*
3094 	 * Steal an opening so that no other queued requests
3095 	 * can get it before us while we simulate interrupts.
3096 	 */
3097 	mtx_lock(&devq->send_mtx);
3098 	dev->ccbq.dev_openings--;
3099 	while((devq->send_openings <= 0 || dev->ccbq.dev_openings < 0) &&
3100 	    (--timeout > 0)) {
3101 		mtx_unlock(&devq->send_mtx);
3102 		DELAY(100);
3103 		CAM_SIM_LOCK(sim);
3104 		(*(sim->sim_poll))(sim);
3105 		CAM_SIM_UNLOCK(sim);
3106 		camisr_runqueue();
3107 		mtx_lock(&devq->send_mtx);
3108 	}
3109 	dev->ccbq.dev_openings++;
3110 	mtx_unlock(&devq->send_mtx);
3111 
3112 	if (timeout != 0) {
3113 		xpt_action(start_ccb);
3114 		while(--timeout > 0) {
3115 			CAM_SIM_LOCK(sim);
3116 			(*(sim->sim_poll))(sim);
3117 			CAM_SIM_UNLOCK(sim);
3118 			camisr_runqueue();
3119 			if ((start_ccb->ccb_h.status  & CAM_STATUS_MASK)
3120 			    != CAM_REQ_INPROG)
3121 				break;
3122 			DELAY(100);
3123 		}
3124 		if (timeout == 0) {
3125 			/*
3126 			 * XXX Is it worth adding a sim_timeout entry
3127 			 * point so we can attempt recovery?  If
3128 			 * this is only used for dumps, I don't think
3129 			 * it is.
3130 			 */
3131 			start_ccb->ccb_h.status = CAM_CMD_TIMEOUT;
3132 		}
3133 	} else {
3134 		start_ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
3135 	}
3136 
3137 	mtx_lock(&dev->device_mtx);
3138 }
3139 
3140 /*
3141  * Schedule a peripheral driver to receive a ccb when its
3142  * target device has space for more transactions.
3143  */
3144 void
3145 xpt_schedule(struct cam_periph *periph, u_int32_t new_priority)
3146 {
3147 
3148 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("xpt_schedule\n"));
3149 	cam_periph_assert(periph, MA_OWNED);
3150 	if (new_priority < periph->scheduled_priority) {
3151 		periph->scheduled_priority = new_priority;
3152 		xpt_run_allocq(periph, 0);
3153 	}
3154 }
3155 
3156 
3157 /*
3158  * Schedule a device to run on a given queue.
3159  * If the device was inserted as a new entry on the queue,
3160  * return 1 meaning the device queue should be run. If we
3161  * were already queued, implying someone else has already
3162  * started the queue, return 0 so the caller doesn't attempt
3163  * to run the queue.
3164  */
3165 static int
3166 xpt_schedule_dev(struct camq *queue, cam_pinfo *pinfo,
3167 		 u_int32_t new_priority)
3168 {
3169 	int retval;
3170 	u_int32_t old_priority;
3171 
3172 	CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_schedule_dev\n"));
3173 
3174 	old_priority = pinfo->priority;
3175 
3176 	/*
3177 	 * Are we already queued?
3178 	 */
3179 	if (pinfo->index != CAM_UNQUEUED_INDEX) {
3180 		/* Simply reorder based on new priority */
3181 		if (new_priority < old_priority) {
3182 			camq_change_priority(queue, pinfo->index,
3183 					     new_priority);
3184 			CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3185 					("changed priority to %d\n",
3186 					 new_priority));
3187 			retval = 1;
3188 		} else
3189 			retval = 0;
3190 	} else {
3191 		/* New entry on the queue */
3192 		if (new_priority < old_priority)
3193 			pinfo->priority = new_priority;
3194 
3195 		CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3196 				("Inserting onto queue\n"));
3197 		pinfo->generation = ++queue->generation;
3198 		camq_insert(queue, pinfo);
3199 		retval = 1;
3200 	}
3201 	return (retval);
3202 }
3203 
3204 static void
3205 xpt_run_allocq_task(void *context, int pending)
3206 {
3207 	struct cam_periph *periph = context;
3208 
3209 	cam_periph_lock(periph);
3210 	periph->flags &= ~CAM_PERIPH_RUN_TASK;
3211 	xpt_run_allocq(periph, 1);
3212 	cam_periph_unlock(periph);
3213 	cam_periph_release(periph);
3214 }
3215 
3216 static void
3217 xpt_run_allocq(struct cam_periph *periph, int sleep)
3218 {
3219 	struct cam_ed	*device;
3220 	union ccb	*ccb;
3221 	uint32_t	 prio;
3222 
3223 	cam_periph_assert(periph, MA_OWNED);
3224 	if (periph->periph_allocating)
3225 		return;
3226 	periph->periph_allocating = 1;
3227 	CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_run_allocq(%p)\n", periph));
3228 	device = periph->path->device;
3229 	ccb = NULL;
3230 restart:
3231 	while ((prio = min(periph->scheduled_priority,
3232 	    periph->immediate_priority)) != CAM_PRIORITY_NONE &&
3233 	    (periph->periph_allocated - (ccb != NULL ? 1 : 0) <
3234 	     device->ccbq.total_openings || prio <= CAM_PRIORITY_OOB)) {
3235 
3236 		if (ccb == NULL &&
3237 		    (ccb = xpt_get_ccb_nowait(periph)) == NULL) {
3238 			if (sleep) {
3239 				ccb = xpt_get_ccb(periph);
3240 				goto restart;
3241 			}
3242 			if (periph->flags & CAM_PERIPH_RUN_TASK)
3243 				break;
3244 			cam_periph_doacquire(periph);
3245 			periph->flags |= CAM_PERIPH_RUN_TASK;
3246 			taskqueue_enqueue(xsoftc.xpt_taskq,
3247 			    &periph->periph_run_task);
3248 			break;
3249 		}
3250 		xpt_setup_ccb(&ccb->ccb_h, periph->path, prio);
3251 		if (prio == periph->immediate_priority) {
3252 			periph->immediate_priority = CAM_PRIORITY_NONE;
3253 			CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3254 					("waking cam_periph_getccb()\n"));
3255 			SLIST_INSERT_HEAD(&periph->ccb_list, &ccb->ccb_h,
3256 					  periph_links.sle);
3257 			wakeup(&periph->ccb_list);
3258 		} else {
3259 			periph->scheduled_priority = CAM_PRIORITY_NONE;
3260 			CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3261 					("calling periph_start()\n"));
3262 			periph->periph_start(periph, ccb);
3263 		}
3264 		ccb = NULL;
3265 	}
3266 	if (ccb != NULL)
3267 		xpt_release_ccb(ccb);
3268 	periph->periph_allocating = 0;
3269 }
3270 
3271 static void
3272 xpt_run_devq(struct cam_devq *devq)
3273 {
3274 	int lock;
3275 
3276 	CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_run_devq\n"));
3277 
3278 	devq->send_queue.qfrozen_cnt++;
3279 	while ((devq->send_queue.entries > 0)
3280 	    && (devq->send_openings > 0)
3281 	    && (devq->send_queue.qfrozen_cnt <= 1)) {
3282 		struct	cam_ed *device;
3283 		union ccb *work_ccb;
3284 		struct	cam_sim *sim;
3285 		struct xpt_proto *proto;
3286 
3287 		device = (struct cam_ed *)camq_remove(&devq->send_queue,
3288 							   CAMQ_HEAD);
3289 		CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3290 				("running device %p\n", device));
3291 
3292 		work_ccb = cam_ccbq_peek_ccb(&device->ccbq, CAMQ_HEAD);
3293 		if (work_ccb == NULL) {
3294 			printf("device on run queue with no ccbs???\n");
3295 			continue;
3296 		}
3297 
3298 		if ((work_ccb->ccb_h.flags & CAM_HIGH_POWER) != 0) {
3299 
3300 			mtx_lock(&xsoftc.xpt_highpower_lock);
3301 		 	if (xsoftc.num_highpower <= 0) {
3302 				/*
3303 				 * We got a high power command, but we
3304 				 * don't have any available slots.  Freeze
3305 				 * the device queue until we have a slot
3306 				 * available.
3307 				 */
3308 				xpt_freeze_devq_device(device, 1);
3309 				STAILQ_INSERT_TAIL(&xsoftc.highpowerq, device,
3310 						   highpowerq_entry);
3311 
3312 				mtx_unlock(&xsoftc.xpt_highpower_lock);
3313 				continue;
3314 			} else {
3315 				/*
3316 				 * Consume a high power slot while
3317 				 * this ccb runs.
3318 				 */
3319 				xsoftc.num_highpower--;
3320 			}
3321 			mtx_unlock(&xsoftc.xpt_highpower_lock);
3322 		}
3323 		cam_ccbq_remove_ccb(&device->ccbq, work_ccb);
3324 		cam_ccbq_send_ccb(&device->ccbq, work_ccb);
3325 		devq->send_openings--;
3326 		devq->send_active++;
3327 		xpt_schedule_devq(devq, device);
3328 		mtx_unlock(&devq->send_mtx);
3329 
3330 		if ((work_ccb->ccb_h.flags & CAM_DEV_QFREEZE) != 0) {
3331 			/*
3332 			 * The client wants to freeze the queue
3333 			 * after this CCB is sent.
3334 			 */
3335 			xpt_freeze_devq(work_ccb->ccb_h.path, 1);
3336 		}
3337 
3338 		/* In Target mode, the peripheral driver knows best... */
3339 		if (work_ccb->ccb_h.func_code == XPT_SCSI_IO) {
3340 			if ((device->inq_flags & SID_CmdQue) != 0
3341 			 && work_ccb->csio.tag_action != CAM_TAG_ACTION_NONE)
3342 				work_ccb->ccb_h.flags |= CAM_TAG_ACTION_VALID;
3343 			else
3344 				/*
3345 				 * Clear this in case of a retried CCB that
3346 				 * failed due to a rejected tag.
3347 				 */
3348 				work_ccb->ccb_h.flags &= ~CAM_TAG_ACTION_VALID;
3349 		}
3350 
3351 		KASSERT(device == work_ccb->ccb_h.path->device,
3352 		    ("device (%p) / path->device (%p) mismatch",
3353 			device, work_ccb->ccb_h.path->device));
3354 		proto = xpt_proto_find(device->protocol);
3355 		if (proto && proto->ops->debug_out)
3356 			proto->ops->debug_out(work_ccb);
3357 
3358 		/*
3359 		 * Device queues can be shared among multiple SIM instances
3360 		 * that reside on different buses.  Use the SIM from the
3361 		 * queued device, rather than the one from the calling bus.
3362 		 */
3363 		sim = device->sim;
3364 		lock = (mtx_owned(sim->mtx) == 0);
3365 		if (lock)
3366 			CAM_SIM_LOCK(sim);
3367 		work_ccb->ccb_h.qos.sim_data = sbinuptime(); // xxx uintprt_t too small 32bit platforms
3368 		(*(sim->sim_action))(sim, work_ccb);
3369 		if (lock)
3370 			CAM_SIM_UNLOCK(sim);
3371 		mtx_lock(&devq->send_mtx);
3372 	}
3373 	devq->send_queue.qfrozen_cnt--;
3374 }
3375 
3376 /*
3377  * This function merges stuff from the slave ccb into the master ccb, while
3378  * keeping important fields in the master ccb constant.
3379  */
3380 void
3381 xpt_merge_ccb(union ccb *master_ccb, union ccb *slave_ccb)
3382 {
3383 
3384 	/*
3385 	 * Pull fields that are valid for peripheral drivers to set
3386 	 * into the master CCB along with the CCB "payload".
3387 	 */
3388 	master_ccb->ccb_h.retry_count = slave_ccb->ccb_h.retry_count;
3389 	master_ccb->ccb_h.func_code = slave_ccb->ccb_h.func_code;
3390 	master_ccb->ccb_h.timeout = slave_ccb->ccb_h.timeout;
3391 	master_ccb->ccb_h.flags = slave_ccb->ccb_h.flags;
3392 	bcopy(&(&slave_ccb->ccb_h)[1], &(&master_ccb->ccb_h)[1],
3393 	      sizeof(union ccb) - sizeof(struct ccb_hdr));
3394 }
3395 
3396 void
3397 xpt_setup_ccb_flags(struct ccb_hdr *ccb_h, struct cam_path *path,
3398 		    u_int32_t priority, u_int32_t flags)
3399 {
3400 
3401 	CAM_DEBUG(path, CAM_DEBUG_TRACE, ("xpt_setup_ccb\n"));
3402 	ccb_h->pinfo.priority = priority;
3403 	ccb_h->path = path;
3404 	ccb_h->path_id = path->bus->path_id;
3405 	if (path->target)
3406 		ccb_h->target_id = path->target->target_id;
3407 	else
3408 		ccb_h->target_id = CAM_TARGET_WILDCARD;
3409 	if (path->device) {
3410 		ccb_h->target_lun = path->device->lun_id;
3411 		ccb_h->pinfo.generation = ++path->device->ccbq.queue.generation;
3412 	} else {
3413 		ccb_h->target_lun = CAM_TARGET_WILDCARD;
3414 	}
3415 	ccb_h->pinfo.index = CAM_UNQUEUED_INDEX;
3416 	ccb_h->flags = flags;
3417 	ccb_h->xflags = 0;
3418 }
3419 
3420 void
3421 xpt_setup_ccb(struct ccb_hdr *ccb_h, struct cam_path *path, u_int32_t priority)
3422 {
3423 	xpt_setup_ccb_flags(ccb_h, path, priority, /*flags*/ 0);
3424 }
3425 
3426 /* Path manipulation functions */
3427 cam_status
3428 xpt_create_path(struct cam_path **new_path_ptr, struct cam_periph *perph,
3429 		path_id_t path_id, target_id_t target_id, lun_id_t lun_id)
3430 {
3431 	struct	   cam_path *path;
3432 	cam_status status;
3433 
3434 	path = (struct cam_path *)malloc(sizeof(*path), M_CAMPATH, M_NOWAIT);
3435 
3436 	if (path == NULL) {
3437 		status = CAM_RESRC_UNAVAIL;
3438 		return(status);
3439 	}
3440 	status = xpt_compile_path(path, perph, path_id, target_id, lun_id);
3441 	if (status != CAM_REQ_CMP) {
3442 		free(path, M_CAMPATH);
3443 		path = NULL;
3444 	}
3445 	*new_path_ptr = path;
3446 	return (status);
3447 }
3448 
3449 cam_status
3450 xpt_create_path_unlocked(struct cam_path **new_path_ptr,
3451 			 struct cam_periph *periph, path_id_t path_id,
3452 			 target_id_t target_id, lun_id_t lun_id)
3453 {
3454 
3455 	return (xpt_create_path(new_path_ptr, periph, path_id, target_id,
3456 	    lun_id));
3457 }
3458 
3459 cam_status
3460 xpt_compile_path(struct cam_path *new_path, struct cam_periph *perph,
3461 		 path_id_t path_id, target_id_t target_id, lun_id_t lun_id)
3462 {
3463 	struct	     cam_eb *bus;
3464 	struct	     cam_et *target;
3465 	struct	     cam_ed *device;
3466 	cam_status   status;
3467 
3468 	status = CAM_REQ_CMP;	/* Completed without error */
3469 	target = NULL;		/* Wildcarded */
3470 	device = NULL;		/* Wildcarded */
3471 
3472 	/*
3473 	 * We will potentially modify the EDT, so block interrupts
3474 	 * that may attempt to create cam paths.
3475 	 */
3476 	bus = xpt_find_bus(path_id);
3477 	if (bus == NULL) {
3478 		status = CAM_PATH_INVALID;
3479 	} else {
3480 		xpt_lock_buses();
3481 		mtx_lock(&bus->eb_mtx);
3482 		target = xpt_find_target(bus, target_id);
3483 		if (target == NULL) {
3484 			/* Create one */
3485 			struct cam_et *new_target;
3486 
3487 			new_target = xpt_alloc_target(bus, target_id);
3488 			if (new_target == NULL) {
3489 				status = CAM_RESRC_UNAVAIL;
3490 			} else {
3491 				target = new_target;
3492 			}
3493 		}
3494 		xpt_unlock_buses();
3495 		if (target != NULL) {
3496 			device = xpt_find_device(target, lun_id);
3497 			if (device == NULL) {
3498 				/* Create one */
3499 				struct cam_ed *new_device;
3500 
3501 				new_device =
3502 				    (*(bus->xport->ops->alloc_device))(bus,
3503 								       target,
3504 								       lun_id);
3505 				if (new_device == NULL) {
3506 					status = CAM_RESRC_UNAVAIL;
3507 				} else {
3508 					device = new_device;
3509 				}
3510 			}
3511 		}
3512 		mtx_unlock(&bus->eb_mtx);
3513 	}
3514 
3515 	/*
3516 	 * Only touch the user's data if we are successful.
3517 	 */
3518 	if (status == CAM_REQ_CMP) {
3519 		new_path->periph = perph;
3520 		new_path->bus = bus;
3521 		new_path->target = target;
3522 		new_path->device = device;
3523 		CAM_DEBUG(new_path, CAM_DEBUG_TRACE, ("xpt_compile_path\n"));
3524 	} else {
3525 		if (device != NULL)
3526 			xpt_release_device(device);
3527 		if (target != NULL)
3528 			xpt_release_target(target);
3529 		if (bus != NULL)
3530 			xpt_release_bus(bus);
3531 	}
3532 	return (status);
3533 }
3534 
3535 cam_status
3536 xpt_clone_path(struct cam_path **new_path_ptr, struct cam_path *path)
3537 {
3538 	struct	   cam_path *new_path;
3539 
3540 	new_path = (struct cam_path *)malloc(sizeof(*path), M_CAMPATH, M_NOWAIT);
3541 	if (new_path == NULL)
3542 		return(CAM_RESRC_UNAVAIL);
3543 	xpt_copy_path(new_path, path);
3544 	*new_path_ptr = new_path;
3545 	return (CAM_REQ_CMP);
3546 }
3547 
3548 void
3549 xpt_copy_path(struct cam_path *new_path, struct cam_path *path)
3550 {
3551 
3552 	*new_path = *path;
3553 	if (path->bus != NULL)
3554 		xpt_acquire_bus(path->bus);
3555 	if (path->target != NULL)
3556 		xpt_acquire_target(path->target);
3557 	if (path->device != NULL)
3558 		xpt_acquire_device(path->device);
3559 }
3560 
3561 void
3562 xpt_release_path(struct cam_path *path)
3563 {
3564 	CAM_DEBUG(path, CAM_DEBUG_TRACE, ("xpt_release_path\n"));
3565 	if (path->device != NULL) {
3566 		xpt_release_device(path->device);
3567 		path->device = NULL;
3568 	}
3569 	if (path->target != NULL) {
3570 		xpt_release_target(path->target);
3571 		path->target = NULL;
3572 	}
3573 	if (path->bus != NULL) {
3574 		xpt_release_bus(path->bus);
3575 		path->bus = NULL;
3576 	}
3577 }
3578 
3579 void
3580 xpt_free_path(struct cam_path *path)
3581 {
3582 
3583 	CAM_DEBUG(path, CAM_DEBUG_TRACE, ("xpt_free_path\n"));
3584 	xpt_release_path(path);
3585 	free(path, M_CAMPATH);
3586 }
3587 
3588 void
3589 xpt_path_counts(struct cam_path *path, uint32_t *bus_ref,
3590     uint32_t *periph_ref, uint32_t *target_ref, uint32_t *device_ref)
3591 {
3592 
3593 	xpt_lock_buses();
3594 	if (bus_ref) {
3595 		if (path->bus)
3596 			*bus_ref = path->bus->refcount;
3597 		else
3598 			*bus_ref = 0;
3599 	}
3600 	if (periph_ref) {
3601 		if (path->periph)
3602 			*periph_ref = path->periph->refcount;
3603 		else
3604 			*periph_ref = 0;
3605 	}
3606 	xpt_unlock_buses();
3607 	if (target_ref) {
3608 		if (path->target)
3609 			*target_ref = path->target->refcount;
3610 		else
3611 			*target_ref = 0;
3612 	}
3613 	if (device_ref) {
3614 		if (path->device)
3615 			*device_ref = path->device->refcount;
3616 		else
3617 			*device_ref = 0;
3618 	}
3619 }
3620 
3621 /*
3622  * Return -1 for failure, 0 for exact match, 1 for match with wildcards
3623  * in path1, 2 for match with wildcards in path2.
3624  */
3625 int
3626 xpt_path_comp(struct cam_path *path1, struct cam_path *path2)
3627 {
3628 	int retval = 0;
3629 
3630 	if (path1->bus != path2->bus) {
3631 		if (path1->bus->path_id == CAM_BUS_WILDCARD)
3632 			retval = 1;
3633 		else if (path2->bus->path_id == CAM_BUS_WILDCARD)
3634 			retval = 2;
3635 		else
3636 			return (-1);
3637 	}
3638 	if (path1->target != path2->target) {
3639 		if (path1->target->target_id == CAM_TARGET_WILDCARD) {
3640 			if (retval == 0)
3641 				retval = 1;
3642 		} else if (path2->target->target_id == CAM_TARGET_WILDCARD)
3643 			retval = 2;
3644 		else
3645 			return (-1);
3646 	}
3647 	if (path1->device != path2->device) {
3648 		if (path1->device->lun_id == CAM_LUN_WILDCARD) {
3649 			if (retval == 0)
3650 				retval = 1;
3651 		} else if (path2->device->lun_id == CAM_LUN_WILDCARD)
3652 			retval = 2;
3653 		else
3654 			return (-1);
3655 	}
3656 	return (retval);
3657 }
3658 
3659 int
3660 xpt_path_comp_dev(struct cam_path *path, struct cam_ed *dev)
3661 {
3662 	int retval = 0;
3663 
3664 	if (path->bus != dev->target->bus) {
3665 		if (path->bus->path_id == CAM_BUS_WILDCARD)
3666 			retval = 1;
3667 		else if (dev->target->bus->path_id == CAM_BUS_WILDCARD)
3668 			retval = 2;
3669 		else
3670 			return (-1);
3671 	}
3672 	if (path->target != dev->target) {
3673 		if (path->target->target_id == CAM_TARGET_WILDCARD) {
3674 			if (retval == 0)
3675 				retval = 1;
3676 		} else if (dev->target->target_id == CAM_TARGET_WILDCARD)
3677 			retval = 2;
3678 		else
3679 			return (-1);
3680 	}
3681 	if (path->device != dev) {
3682 		if (path->device->lun_id == CAM_LUN_WILDCARD) {
3683 			if (retval == 0)
3684 				retval = 1;
3685 		} else if (dev->lun_id == CAM_LUN_WILDCARD)
3686 			retval = 2;
3687 		else
3688 			return (-1);
3689 	}
3690 	return (retval);
3691 }
3692 
3693 void
3694 xpt_print_path(struct cam_path *path)
3695 {
3696 	struct sbuf sb;
3697 	char buffer[XPT_PRINT_LEN];
3698 
3699 	sbuf_new(&sb, buffer, XPT_PRINT_LEN, SBUF_FIXEDLEN);
3700 	xpt_path_sbuf(path, &sb);
3701 	sbuf_finish(&sb);
3702 	printf("%s", sbuf_data(&sb));
3703 	sbuf_delete(&sb);
3704 }
3705 
3706 void
3707 xpt_print_device(struct cam_ed *device)
3708 {
3709 
3710 	if (device == NULL)
3711 		printf("(nopath): ");
3712 	else {
3713 		printf("(noperiph:%s%d:%d:%d:%jx): ", device->sim->sim_name,
3714 		       device->sim->unit_number,
3715 		       device->sim->bus_id,
3716 		       device->target->target_id,
3717 		       (uintmax_t)device->lun_id);
3718 	}
3719 }
3720 
3721 void
3722 xpt_print(struct cam_path *path, const char *fmt, ...)
3723 {
3724 	va_list ap;
3725 	struct sbuf sb;
3726 	char buffer[XPT_PRINT_LEN];
3727 
3728 	sbuf_new(&sb, buffer, XPT_PRINT_LEN, SBUF_FIXEDLEN);
3729 
3730 	xpt_path_sbuf(path, &sb);
3731 	va_start(ap, fmt);
3732 	sbuf_vprintf(&sb, fmt, ap);
3733 	va_end(ap);
3734 
3735 	sbuf_finish(&sb);
3736 	printf("%s", sbuf_data(&sb));
3737 	sbuf_delete(&sb);
3738 }
3739 
3740 int
3741 xpt_path_string(struct cam_path *path, char *str, size_t str_len)
3742 {
3743 	struct sbuf sb;
3744 	int len;
3745 
3746 	sbuf_new(&sb, str, str_len, 0);
3747 	len = xpt_path_sbuf(path, &sb);
3748 	sbuf_finish(&sb);
3749 	return (len);
3750 }
3751 
3752 int
3753 xpt_path_sbuf(struct cam_path *path, struct sbuf *sb)
3754 {
3755 
3756 	if (path == NULL)
3757 		sbuf_printf(sb, "(nopath): ");
3758 	else {
3759 		if (path->periph != NULL)
3760 			sbuf_printf(sb, "(%s%d:", path->periph->periph_name,
3761 				    path->periph->unit_number);
3762 		else
3763 			sbuf_printf(sb, "(noperiph:");
3764 
3765 		if (path->bus != NULL)
3766 			sbuf_printf(sb, "%s%d:%d:", path->bus->sim->sim_name,
3767 				    path->bus->sim->unit_number,
3768 				    path->bus->sim->bus_id);
3769 		else
3770 			sbuf_printf(sb, "nobus:");
3771 
3772 		if (path->target != NULL)
3773 			sbuf_printf(sb, "%d:", path->target->target_id);
3774 		else
3775 			sbuf_printf(sb, "X:");
3776 
3777 		if (path->device != NULL)
3778 			sbuf_printf(sb, "%jx): ",
3779 			    (uintmax_t)path->device->lun_id);
3780 		else
3781 			sbuf_printf(sb, "X): ");
3782 	}
3783 
3784 	return(sbuf_len(sb));
3785 }
3786 
3787 path_id_t
3788 xpt_path_path_id(struct cam_path *path)
3789 {
3790 	return(path->bus->path_id);
3791 }
3792 
3793 target_id_t
3794 xpt_path_target_id(struct cam_path *path)
3795 {
3796 	if (path->target != NULL)
3797 		return (path->target->target_id);
3798 	else
3799 		return (CAM_TARGET_WILDCARD);
3800 }
3801 
3802 lun_id_t
3803 xpt_path_lun_id(struct cam_path *path)
3804 {
3805 	if (path->device != NULL)
3806 		return (path->device->lun_id);
3807 	else
3808 		return (CAM_LUN_WILDCARD);
3809 }
3810 
3811 struct cam_sim *
3812 xpt_path_sim(struct cam_path *path)
3813 {
3814 
3815 	return (path->bus->sim);
3816 }
3817 
3818 struct cam_periph*
3819 xpt_path_periph(struct cam_path *path)
3820 {
3821 
3822 	return (path->periph);
3823 }
3824 
3825 /*
3826  * Release a CAM control block for the caller.  Remit the cost of the structure
3827  * to the device referenced by the path.  If the this device had no 'credits'
3828  * and peripheral drivers have registered async callbacks for this notification
3829  * call them now.
3830  */
3831 void
3832 xpt_release_ccb(union ccb *free_ccb)
3833 {
3834 	struct	 cam_ed *device;
3835 	struct	 cam_periph *periph;
3836 
3837 	CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_release_ccb\n"));
3838 	xpt_path_assert(free_ccb->ccb_h.path, MA_OWNED);
3839 	device = free_ccb->ccb_h.path->device;
3840 	periph = free_ccb->ccb_h.path->periph;
3841 
3842 	xpt_free_ccb(free_ccb);
3843 	periph->periph_allocated--;
3844 	cam_ccbq_release_opening(&device->ccbq);
3845 	xpt_run_allocq(periph, 0);
3846 }
3847 
3848 /* Functions accessed by SIM drivers */
3849 
3850 static struct xpt_xport_ops xport_default_ops = {
3851 	.alloc_device = xpt_alloc_device_default,
3852 	.action = xpt_action_default,
3853 	.async = xpt_dev_async_default,
3854 };
3855 static struct xpt_xport xport_default = {
3856 	.xport = XPORT_UNKNOWN,
3857 	.name = "unknown",
3858 	.ops = &xport_default_ops,
3859 };
3860 
3861 CAM_XPT_XPORT(xport_default);
3862 
3863 /*
3864  * A sim structure, listing the SIM entry points and instance
3865  * identification info is passed to xpt_bus_register to hook the SIM
3866  * into the CAM framework.  xpt_bus_register creates a cam_eb entry
3867  * for this new bus and places it in the array of buses and assigns
3868  * it a path_id.  The path_id may be influenced by "hard wiring"
3869  * information specified by the user.  Once interrupt services are
3870  * available, the bus will be probed.
3871  */
3872 int32_t
3873 xpt_bus_register(struct cam_sim *sim, device_t parent, u_int32_t bus)
3874 {
3875 	struct cam_eb *new_bus;
3876 	struct cam_eb *old_bus;
3877 	struct ccb_pathinq cpi;
3878 	struct cam_path *path;
3879 	cam_status status;
3880 
3881 	mtx_assert(sim->mtx, MA_OWNED);
3882 
3883 	sim->bus_id = bus;
3884 	new_bus = (struct cam_eb *)malloc(sizeof(*new_bus),
3885 					  M_CAMXPT, M_NOWAIT|M_ZERO);
3886 	if (new_bus == NULL) {
3887 		/* Couldn't satisfy request */
3888 		return (CAM_RESRC_UNAVAIL);
3889 	}
3890 
3891 	mtx_init(&new_bus->eb_mtx, "CAM bus lock", NULL, MTX_DEF);
3892 	TAILQ_INIT(&new_bus->et_entries);
3893 	cam_sim_hold(sim);
3894 	new_bus->sim = sim;
3895 	timevalclear(&new_bus->last_reset);
3896 	new_bus->flags = 0;
3897 	new_bus->refcount = 1;	/* Held until a bus_deregister event */
3898 	new_bus->generation = 0;
3899 
3900 	xpt_lock_buses();
3901 	sim->path_id = new_bus->path_id =
3902 	    xptpathid(sim->sim_name, sim->unit_number, sim->bus_id);
3903 	old_bus = TAILQ_FIRST(&xsoftc.xpt_busses);
3904 	while (old_bus != NULL
3905 	    && old_bus->path_id < new_bus->path_id)
3906 		old_bus = TAILQ_NEXT(old_bus, links);
3907 	if (old_bus != NULL)
3908 		TAILQ_INSERT_BEFORE(old_bus, new_bus, links);
3909 	else
3910 		TAILQ_INSERT_TAIL(&xsoftc.xpt_busses, new_bus, links);
3911 	xsoftc.bus_generation++;
3912 	xpt_unlock_buses();
3913 
3914 	/*
3915 	 * Set a default transport so that a PATH_INQ can be issued to
3916 	 * the SIM.  This will then allow for probing and attaching of
3917 	 * a more appropriate transport.
3918 	 */
3919 	new_bus->xport = &xport_default;
3920 
3921 	status = xpt_create_path(&path, /*periph*/NULL, sim->path_id,
3922 				  CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
3923 	if (status != CAM_REQ_CMP) {
3924 		xpt_release_bus(new_bus);
3925 		free(path, M_CAMXPT);
3926 		return (CAM_RESRC_UNAVAIL);
3927 	}
3928 
3929 	xpt_setup_ccb(&cpi.ccb_h, path, CAM_PRIORITY_NORMAL);
3930 	cpi.ccb_h.func_code = XPT_PATH_INQ;
3931 	xpt_action((union ccb *)&cpi);
3932 
3933 	if (cpi.ccb_h.status == CAM_REQ_CMP) {
3934 		struct xpt_xport **xpt;
3935 
3936 		SET_FOREACH(xpt, cam_xpt_xport_set) {
3937 			if ((*xpt)->xport == cpi.transport) {
3938 				new_bus->xport = *xpt;
3939 				break;
3940 			}
3941 		}
3942 		if (new_bus->xport == NULL) {
3943 			xpt_print(path,
3944 			    "No transport found for %d\n", cpi.transport);
3945 			xpt_release_bus(new_bus);
3946 			free(path, M_CAMXPT);
3947 			return (CAM_RESRC_UNAVAIL);
3948 		}
3949 	}
3950 
3951 	/* Notify interested parties */
3952 	if (sim->path_id != CAM_XPT_PATH_ID) {
3953 
3954 		xpt_async(AC_PATH_REGISTERED, path, &cpi);
3955 		if ((cpi.hba_misc & PIM_NOSCAN) == 0) {
3956 			union	ccb *scan_ccb;
3957 
3958 			/* Initiate bus rescan. */
3959 			scan_ccb = xpt_alloc_ccb_nowait();
3960 			if (scan_ccb != NULL) {
3961 				scan_ccb->ccb_h.path = path;
3962 				scan_ccb->ccb_h.func_code = XPT_SCAN_BUS;
3963 				scan_ccb->crcn.flags = 0;
3964 				xpt_rescan(scan_ccb);
3965 			} else {
3966 				xpt_print(path,
3967 					  "Can't allocate CCB to scan bus\n");
3968 				xpt_free_path(path);
3969 			}
3970 		} else
3971 			xpt_free_path(path);
3972 	} else
3973 		xpt_free_path(path);
3974 	return (CAM_SUCCESS);
3975 }
3976 
3977 int32_t
3978 xpt_bus_deregister(path_id_t pathid)
3979 {
3980 	struct cam_path bus_path;
3981 	cam_status status;
3982 
3983 	status = xpt_compile_path(&bus_path, NULL, pathid,
3984 				  CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
3985 	if (status != CAM_REQ_CMP)
3986 		return (status);
3987 
3988 	xpt_async(AC_LOST_DEVICE, &bus_path, NULL);
3989 	xpt_async(AC_PATH_DEREGISTERED, &bus_path, NULL);
3990 
3991 	/* Release the reference count held while registered. */
3992 	xpt_release_bus(bus_path.bus);
3993 	xpt_release_path(&bus_path);
3994 
3995 	return (CAM_REQ_CMP);
3996 }
3997 
3998 static path_id_t
3999 xptnextfreepathid(void)
4000 {
4001 	struct cam_eb *bus;
4002 	path_id_t pathid;
4003 	const char *strval;
4004 
4005 	mtx_assert(&xsoftc.xpt_topo_lock, MA_OWNED);
4006 	pathid = 0;
4007 	bus = TAILQ_FIRST(&xsoftc.xpt_busses);
4008 retry:
4009 	/* Find an unoccupied pathid */
4010 	while (bus != NULL && bus->path_id <= pathid) {
4011 		if (bus->path_id == pathid)
4012 			pathid++;
4013 		bus = TAILQ_NEXT(bus, links);
4014 	}
4015 
4016 	/*
4017 	 * Ensure that this pathid is not reserved for
4018 	 * a bus that may be registered in the future.
4019 	 */
4020 	if (resource_string_value("scbus", pathid, "at", &strval) == 0) {
4021 		++pathid;
4022 		/* Start the search over */
4023 		goto retry;
4024 	}
4025 	return (pathid);
4026 }
4027 
4028 static path_id_t
4029 xptpathid(const char *sim_name, int sim_unit, int sim_bus)
4030 {
4031 	path_id_t pathid;
4032 	int i, dunit, val;
4033 	char buf[32];
4034 	const char *dname;
4035 
4036 	pathid = CAM_XPT_PATH_ID;
4037 	snprintf(buf, sizeof(buf), "%s%d", sim_name, sim_unit);
4038 	if (strcmp(buf, "xpt0") == 0 && sim_bus == 0)
4039 		return (pathid);
4040 	i = 0;
4041 	while ((resource_find_match(&i, &dname, &dunit, "at", buf)) == 0) {
4042 		if (strcmp(dname, "scbus")) {
4043 			/* Avoid a bit of foot shooting. */
4044 			continue;
4045 		}
4046 		if (dunit < 0)		/* unwired?! */
4047 			continue;
4048 		if (resource_int_value("scbus", dunit, "bus", &val) == 0) {
4049 			if (sim_bus == val) {
4050 				pathid = dunit;
4051 				break;
4052 			}
4053 		} else if (sim_bus == 0) {
4054 			/* Unspecified matches bus 0 */
4055 			pathid = dunit;
4056 			break;
4057 		} else {
4058 			printf("Ambiguous scbus configuration for %s%d "
4059 			       "bus %d, cannot wire down.  The kernel "
4060 			       "config entry for scbus%d should "
4061 			       "specify a controller bus.\n"
4062 			       "Scbus will be assigned dynamically.\n",
4063 			       sim_name, sim_unit, sim_bus, dunit);
4064 			break;
4065 		}
4066 	}
4067 
4068 	if (pathid == CAM_XPT_PATH_ID)
4069 		pathid = xptnextfreepathid();
4070 	return (pathid);
4071 }
4072 
4073 static const char *
4074 xpt_async_string(u_int32_t async_code)
4075 {
4076 
4077 	switch (async_code) {
4078 	case AC_BUS_RESET: return ("AC_BUS_RESET");
4079 	case AC_UNSOL_RESEL: return ("AC_UNSOL_RESEL");
4080 	case AC_SCSI_AEN: return ("AC_SCSI_AEN");
4081 	case AC_SENT_BDR: return ("AC_SENT_BDR");
4082 	case AC_PATH_REGISTERED: return ("AC_PATH_REGISTERED");
4083 	case AC_PATH_DEREGISTERED: return ("AC_PATH_DEREGISTERED");
4084 	case AC_FOUND_DEVICE: return ("AC_FOUND_DEVICE");
4085 	case AC_LOST_DEVICE: return ("AC_LOST_DEVICE");
4086 	case AC_TRANSFER_NEG: return ("AC_TRANSFER_NEG");
4087 	case AC_INQ_CHANGED: return ("AC_INQ_CHANGED");
4088 	case AC_GETDEV_CHANGED: return ("AC_GETDEV_CHANGED");
4089 	case AC_CONTRACT: return ("AC_CONTRACT");
4090 	case AC_ADVINFO_CHANGED: return ("AC_ADVINFO_CHANGED");
4091 	case AC_UNIT_ATTENTION: return ("AC_UNIT_ATTENTION");
4092 	}
4093 	return ("AC_UNKNOWN");
4094 }
4095 
4096 static int
4097 xpt_async_size(u_int32_t async_code)
4098 {
4099 
4100 	switch (async_code) {
4101 	case AC_BUS_RESET: return (0);
4102 	case AC_UNSOL_RESEL: return (0);
4103 	case AC_SCSI_AEN: return (0);
4104 	case AC_SENT_BDR: return (0);
4105 	case AC_PATH_REGISTERED: return (sizeof(struct ccb_pathinq));
4106 	case AC_PATH_DEREGISTERED: return (0);
4107 	case AC_FOUND_DEVICE: return (sizeof(struct ccb_getdev));
4108 	case AC_LOST_DEVICE: return (0);
4109 	case AC_TRANSFER_NEG: return (sizeof(struct ccb_trans_settings));
4110 	case AC_INQ_CHANGED: return (0);
4111 	case AC_GETDEV_CHANGED: return (0);
4112 	case AC_CONTRACT: return (sizeof(struct ac_contract));
4113 	case AC_ADVINFO_CHANGED: return (-1);
4114 	case AC_UNIT_ATTENTION: return (sizeof(struct ccb_scsiio));
4115 	}
4116 	return (0);
4117 }
4118 
4119 static int
4120 xpt_async_process_dev(struct cam_ed *device, void *arg)
4121 {
4122 	union ccb *ccb = arg;
4123 	struct cam_path *path = ccb->ccb_h.path;
4124 	void *async_arg = ccb->casync.async_arg_ptr;
4125 	u_int32_t async_code = ccb->casync.async_code;
4126 	int relock;
4127 
4128 	if (path->device != device
4129 	 && path->device->lun_id != CAM_LUN_WILDCARD
4130 	 && device->lun_id != CAM_LUN_WILDCARD)
4131 		return (1);
4132 
4133 	/*
4134 	 * The async callback could free the device.
4135 	 * If it is a broadcast async, it doesn't hold
4136 	 * device reference, so take our own reference.
4137 	 */
4138 	xpt_acquire_device(device);
4139 
4140 	/*
4141 	 * If async for specific device is to be delivered to
4142 	 * the wildcard client, take the specific device lock.
4143 	 * XXX: We may need a way for client to specify it.
4144 	 */
4145 	if ((device->lun_id == CAM_LUN_WILDCARD &&
4146 	     path->device->lun_id != CAM_LUN_WILDCARD) ||
4147 	    (device->target->target_id == CAM_TARGET_WILDCARD &&
4148 	     path->target->target_id != CAM_TARGET_WILDCARD) ||
4149 	    (device->target->bus->path_id == CAM_BUS_WILDCARD &&
4150 	     path->target->bus->path_id != CAM_BUS_WILDCARD)) {
4151 		mtx_unlock(&device->device_mtx);
4152 		xpt_path_lock(path);
4153 		relock = 1;
4154 	} else
4155 		relock = 0;
4156 
4157 	(*(device->target->bus->xport->ops->async))(async_code,
4158 	    device->target->bus, device->target, device, async_arg);
4159 	xpt_async_bcast(&device->asyncs, async_code, path, async_arg);
4160 
4161 	if (relock) {
4162 		xpt_path_unlock(path);
4163 		mtx_lock(&device->device_mtx);
4164 	}
4165 	xpt_release_device(device);
4166 	return (1);
4167 }
4168 
4169 static int
4170 xpt_async_process_tgt(struct cam_et *target, void *arg)
4171 {
4172 	union ccb *ccb = arg;
4173 	struct cam_path *path = ccb->ccb_h.path;
4174 
4175 	if (path->target != target
4176 	 && path->target->target_id != CAM_TARGET_WILDCARD
4177 	 && target->target_id != CAM_TARGET_WILDCARD)
4178 		return (1);
4179 
4180 	if (ccb->casync.async_code == AC_SENT_BDR) {
4181 		/* Update our notion of when the last reset occurred */
4182 		microtime(&target->last_reset);
4183 	}
4184 
4185 	return (xptdevicetraverse(target, NULL, xpt_async_process_dev, ccb));
4186 }
4187 
4188 static void
4189 xpt_async_process(struct cam_periph *periph, union ccb *ccb)
4190 {
4191 	struct cam_eb *bus;
4192 	struct cam_path *path;
4193 	void *async_arg;
4194 	u_int32_t async_code;
4195 
4196 	path = ccb->ccb_h.path;
4197 	async_code = ccb->casync.async_code;
4198 	async_arg = ccb->casync.async_arg_ptr;
4199 	CAM_DEBUG(path, CAM_DEBUG_TRACE | CAM_DEBUG_INFO,
4200 	    ("xpt_async(%s)\n", xpt_async_string(async_code)));
4201 	bus = path->bus;
4202 
4203 	if (async_code == AC_BUS_RESET) {
4204 		/* Update our notion of when the last reset occurred */
4205 		microtime(&bus->last_reset);
4206 	}
4207 
4208 	xpttargettraverse(bus, NULL, xpt_async_process_tgt, ccb);
4209 
4210 	/*
4211 	 * If this wasn't a fully wildcarded async, tell all
4212 	 * clients that want all async events.
4213 	 */
4214 	if (bus != xpt_periph->path->bus) {
4215 		xpt_path_lock(xpt_periph->path);
4216 		xpt_async_process_dev(xpt_periph->path->device, ccb);
4217 		xpt_path_unlock(xpt_periph->path);
4218 	}
4219 
4220 	if (path->device != NULL && path->device->lun_id != CAM_LUN_WILDCARD)
4221 		xpt_release_devq(path, 1, TRUE);
4222 	else
4223 		xpt_release_simq(path->bus->sim, TRUE);
4224 	if (ccb->casync.async_arg_size > 0)
4225 		free(async_arg, M_CAMXPT);
4226 	xpt_free_path(path);
4227 	xpt_free_ccb(ccb);
4228 }
4229 
4230 static void
4231 xpt_async_bcast(struct async_list *async_head,
4232 		u_int32_t async_code,
4233 		struct cam_path *path, void *async_arg)
4234 {
4235 	struct async_node *cur_entry;
4236 	int lock;
4237 
4238 	cur_entry = SLIST_FIRST(async_head);
4239 	while (cur_entry != NULL) {
4240 		struct async_node *next_entry;
4241 		/*
4242 		 * Grab the next list entry before we call the current
4243 		 * entry's callback.  This is because the callback function
4244 		 * can delete its async callback entry.
4245 		 */
4246 		next_entry = SLIST_NEXT(cur_entry, links);
4247 		if ((cur_entry->event_enable & async_code) != 0) {
4248 			lock = cur_entry->event_lock;
4249 			if (lock)
4250 				CAM_SIM_LOCK(path->device->sim);
4251 			cur_entry->callback(cur_entry->callback_arg,
4252 					    async_code, path,
4253 					    async_arg);
4254 			if (lock)
4255 				CAM_SIM_UNLOCK(path->device->sim);
4256 		}
4257 		cur_entry = next_entry;
4258 	}
4259 }
4260 
4261 void
4262 xpt_async(u_int32_t async_code, struct cam_path *path, void *async_arg)
4263 {
4264 	union ccb *ccb;
4265 	int size;
4266 
4267 	ccb = xpt_alloc_ccb_nowait();
4268 	if (ccb == NULL) {
4269 		xpt_print(path, "Can't allocate CCB to send %s\n",
4270 		    xpt_async_string(async_code));
4271 		return;
4272 	}
4273 
4274 	if (xpt_clone_path(&ccb->ccb_h.path, path) != CAM_REQ_CMP) {
4275 		xpt_print(path, "Can't allocate path to send %s\n",
4276 		    xpt_async_string(async_code));
4277 		xpt_free_ccb(ccb);
4278 		return;
4279 	}
4280 	ccb->ccb_h.path->periph = NULL;
4281 	ccb->ccb_h.func_code = XPT_ASYNC;
4282 	ccb->ccb_h.cbfcnp = xpt_async_process;
4283 	ccb->ccb_h.flags |= CAM_UNLOCKED;
4284 	ccb->casync.async_code = async_code;
4285 	ccb->casync.async_arg_size = 0;
4286 	size = xpt_async_size(async_code);
4287 	CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_TRACE,
4288 	    ("xpt_async: func %#x %s aync_code %d %s\n",
4289 		ccb->ccb_h.func_code,
4290 		xpt_action_name(ccb->ccb_h.func_code),
4291 		async_code,
4292 		xpt_async_string(async_code)));
4293 	if (size > 0 && async_arg != NULL) {
4294 		ccb->casync.async_arg_ptr = malloc(size, M_CAMXPT, M_NOWAIT);
4295 		if (ccb->casync.async_arg_ptr == NULL) {
4296 			xpt_print(path, "Can't allocate argument to send %s\n",
4297 			    xpt_async_string(async_code));
4298 			xpt_free_path(ccb->ccb_h.path);
4299 			xpt_free_ccb(ccb);
4300 			return;
4301 		}
4302 		memcpy(ccb->casync.async_arg_ptr, async_arg, size);
4303 		ccb->casync.async_arg_size = size;
4304 	} else if (size < 0) {
4305 		ccb->casync.async_arg_ptr = async_arg;
4306 		ccb->casync.async_arg_size = size;
4307 	}
4308 	if (path->device != NULL && path->device->lun_id != CAM_LUN_WILDCARD)
4309 		xpt_freeze_devq(path, 1);
4310 	else
4311 		xpt_freeze_simq(path->bus->sim, 1);
4312 	xpt_done(ccb);
4313 }
4314 
4315 static void
4316 xpt_dev_async_default(u_int32_t async_code, struct cam_eb *bus,
4317 		      struct cam_et *target, struct cam_ed *device,
4318 		      void *async_arg)
4319 {
4320 
4321 	/*
4322 	 * We only need to handle events for real devices.
4323 	 */
4324 	if (target->target_id == CAM_TARGET_WILDCARD
4325 	 || device->lun_id == CAM_LUN_WILDCARD)
4326 		return;
4327 
4328 	printf("%s called\n", __func__);
4329 }
4330 
4331 static uint32_t
4332 xpt_freeze_devq_device(struct cam_ed *dev, u_int count)
4333 {
4334 	struct cam_devq	*devq;
4335 	uint32_t freeze;
4336 
4337 	devq = dev->sim->devq;
4338 	mtx_assert(&devq->send_mtx, MA_OWNED);
4339 	CAM_DEBUG_DEV(dev, CAM_DEBUG_TRACE,
4340 	    ("xpt_freeze_devq_device(%d) %u->%u\n", count,
4341 	    dev->ccbq.queue.qfrozen_cnt, dev->ccbq.queue.qfrozen_cnt + count));
4342 	freeze = (dev->ccbq.queue.qfrozen_cnt += count);
4343 	/* Remove frozen device from sendq. */
4344 	if (device_is_queued(dev))
4345 		camq_remove(&devq->send_queue, dev->devq_entry.index);
4346 	return (freeze);
4347 }
4348 
4349 u_int32_t
4350 xpt_freeze_devq(struct cam_path *path, u_int count)
4351 {
4352 	struct cam_ed	*dev = path->device;
4353 	struct cam_devq	*devq;
4354 	uint32_t	 freeze;
4355 
4356 	devq = dev->sim->devq;
4357 	mtx_lock(&devq->send_mtx);
4358 	CAM_DEBUG(path, CAM_DEBUG_TRACE, ("xpt_freeze_devq(%d)\n", count));
4359 	freeze = xpt_freeze_devq_device(dev, count);
4360 	mtx_unlock(&devq->send_mtx);
4361 	return (freeze);
4362 }
4363 
4364 u_int32_t
4365 xpt_freeze_simq(struct cam_sim *sim, u_int count)
4366 {
4367 	struct cam_devq	*devq;
4368 	uint32_t	 freeze;
4369 
4370 	devq = sim->devq;
4371 	mtx_lock(&devq->send_mtx);
4372 	freeze = (devq->send_queue.qfrozen_cnt += count);
4373 	mtx_unlock(&devq->send_mtx);
4374 	return (freeze);
4375 }
4376 
4377 static void
4378 xpt_release_devq_timeout(void *arg)
4379 {
4380 	struct cam_ed *dev;
4381 	struct cam_devq *devq;
4382 
4383 	dev = (struct cam_ed *)arg;
4384 	CAM_DEBUG_DEV(dev, CAM_DEBUG_TRACE, ("xpt_release_devq_timeout\n"));
4385 	devq = dev->sim->devq;
4386 	mtx_assert(&devq->send_mtx, MA_OWNED);
4387 	if (xpt_release_devq_device(dev, /*count*/1, /*run_queue*/TRUE))
4388 		xpt_run_devq(devq);
4389 }
4390 
4391 void
4392 xpt_release_devq(struct cam_path *path, u_int count, int run_queue)
4393 {
4394 	struct cam_ed *dev;
4395 	struct cam_devq *devq;
4396 
4397 	CAM_DEBUG(path, CAM_DEBUG_TRACE, ("xpt_release_devq(%d, %d)\n",
4398 	    count, run_queue));
4399 	dev = path->device;
4400 	devq = dev->sim->devq;
4401 	mtx_lock(&devq->send_mtx);
4402 	if (xpt_release_devq_device(dev, count, run_queue))
4403 		xpt_run_devq(dev->sim->devq);
4404 	mtx_unlock(&devq->send_mtx);
4405 }
4406 
4407 static int
4408 xpt_release_devq_device(struct cam_ed *dev, u_int count, int run_queue)
4409 {
4410 
4411 	mtx_assert(&dev->sim->devq->send_mtx, MA_OWNED);
4412 	CAM_DEBUG_DEV(dev, CAM_DEBUG_TRACE,
4413 	    ("xpt_release_devq_device(%d, %d) %u->%u\n", count, run_queue,
4414 	    dev->ccbq.queue.qfrozen_cnt, dev->ccbq.queue.qfrozen_cnt - count));
4415 	if (count > dev->ccbq.queue.qfrozen_cnt) {
4416 #ifdef INVARIANTS
4417 		printf("xpt_release_devq(): requested %u > present %u\n",
4418 		    count, dev->ccbq.queue.qfrozen_cnt);
4419 #endif
4420 		count = dev->ccbq.queue.qfrozen_cnt;
4421 	}
4422 	dev->ccbq.queue.qfrozen_cnt -= count;
4423 	if (dev->ccbq.queue.qfrozen_cnt == 0) {
4424 		/*
4425 		 * No longer need to wait for a successful
4426 		 * command completion.
4427 		 */
4428 		dev->flags &= ~CAM_DEV_REL_ON_COMPLETE;
4429 		/*
4430 		 * Remove any timeouts that might be scheduled
4431 		 * to release this queue.
4432 		 */
4433 		if ((dev->flags & CAM_DEV_REL_TIMEOUT_PENDING) != 0) {
4434 			callout_stop(&dev->callout);
4435 			dev->flags &= ~CAM_DEV_REL_TIMEOUT_PENDING;
4436 		}
4437 		/*
4438 		 * Now that we are unfrozen schedule the
4439 		 * device so any pending transactions are
4440 		 * run.
4441 		 */
4442 		xpt_schedule_devq(dev->sim->devq, dev);
4443 	} else
4444 		run_queue = 0;
4445 	return (run_queue);
4446 }
4447 
4448 void
4449 xpt_release_simq(struct cam_sim *sim, int run_queue)
4450 {
4451 	struct cam_devq	*devq;
4452 
4453 	devq = sim->devq;
4454 	mtx_lock(&devq->send_mtx);
4455 	if (devq->send_queue.qfrozen_cnt <= 0) {
4456 #ifdef INVARIANTS
4457 		printf("xpt_release_simq: requested 1 > present %u\n",
4458 		    devq->send_queue.qfrozen_cnt);
4459 #endif
4460 	} else
4461 		devq->send_queue.qfrozen_cnt--;
4462 	if (devq->send_queue.qfrozen_cnt == 0) {
4463 		/*
4464 		 * If there is a timeout scheduled to release this
4465 		 * sim queue, remove it.  The queue frozen count is
4466 		 * already at 0.
4467 		 */
4468 		if ((sim->flags & CAM_SIM_REL_TIMEOUT_PENDING) != 0){
4469 			callout_stop(&sim->callout);
4470 			sim->flags &= ~CAM_SIM_REL_TIMEOUT_PENDING;
4471 		}
4472 		if (run_queue) {
4473 			/*
4474 			 * Now that we are unfrozen run the send queue.
4475 			 */
4476 			xpt_run_devq(sim->devq);
4477 		}
4478 	}
4479 	mtx_unlock(&devq->send_mtx);
4480 }
4481 
4482 /*
4483  * XXX Appears to be unused.
4484  */
4485 static void
4486 xpt_release_simq_timeout(void *arg)
4487 {
4488 	struct cam_sim *sim;
4489 
4490 	sim = (struct cam_sim *)arg;
4491 	xpt_release_simq(sim, /* run_queue */ TRUE);
4492 }
4493 
4494 void
4495 xpt_done(union ccb *done_ccb)
4496 {
4497 	struct cam_doneq *queue;
4498 	int	run, hash;
4499 
4500 #if defined(BUF_TRACKING) || defined(FULL_BUF_TRACKING)
4501 	if (done_ccb->ccb_h.func_code == XPT_SCSI_IO &&
4502 	    done_ccb->csio.bio != NULL)
4503 		biotrack(done_ccb->csio.bio, __func__);
4504 #endif
4505 
4506 	CAM_DEBUG(done_ccb->ccb_h.path, CAM_DEBUG_TRACE,
4507 	    ("xpt_done: func= %#x %s status %#x\n",
4508 		done_ccb->ccb_h.func_code,
4509 		xpt_action_name(done_ccb->ccb_h.func_code),
4510 		done_ccb->ccb_h.status));
4511 	if ((done_ccb->ccb_h.func_code & XPT_FC_QUEUED) == 0)
4512 		return;
4513 
4514 	/* Store the time the ccb was in the sim */
4515 	done_ccb->ccb_h.qos.sim_data = sbinuptime() - done_ccb->ccb_h.qos.sim_data;
4516 	hash = (done_ccb->ccb_h.path_id + done_ccb->ccb_h.target_id +
4517 	    done_ccb->ccb_h.target_lun) % cam_num_doneqs;
4518 	queue = &cam_doneqs[hash];
4519 	mtx_lock(&queue->cam_doneq_mtx);
4520 	run = (queue->cam_doneq_sleep && STAILQ_EMPTY(&queue->cam_doneq));
4521 	STAILQ_INSERT_TAIL(&queue->cam_doneq, &done_ccb->ccb_h, sim_links.stqe);
4522 	done_ccb->ccb_h.pinfo.index = CAM_DONEQ_INDEX;
4523 	mtx_unlock(&queue->cam_doneq_mtx);
4524 	if (run)
4525 		wakeup(&queue->cam_doneq);
4526 }
4527 
4528 void
4529 xpt_done_direct(union ccb *done_ccb)
4530 {
4531 
4532 	CAM_DEBUG(done_ccb->ccb_h.path, CAM_DEBUG_TRACE,
4533 	    ("xpt_done_direct: status %#x\n", done_ccb->ccb_h.status));
4534 	if ((done_ccb->ccb_h.func_code & XPT_FC_QUEUED) == 0)
4535 		return;
4536 
4537 	/* Store the time the ccb was in the sim */
4538 	done_ccb->ccb_h.qos.sim_data = sbinuptime() - done_ccb->ccb_h.qos.sim_data;
4539 	xpt_done_process(&done_ccb->ccb_h);
4540 }
4541 
4542 union ccb *
4543 xpt_alloc_ccb()
4544 {
4545 	union ccb *new_ccb;
4546 
4547 	new_ccb = malloc(sizeof(*new_ccb), M_CAMCCB, M_ZERO|M_WAITOK);
4548 	return (new_ccb);
4549 }
4550 
4551 union ccb *
4552 xpt_alloc_ccb_nowait()
4553 {
4554 	union ccb *new_ccb;
4555 
4556 	new_ccb = malloc(sizeof(*new_ccb), M_CAMCCB, M_ZERO|M_NOWAIT);
4557 	return (new_ccb);
4558 }
4559 
4560 void
4561 xpt_free_ccb(union ccb *free_ccb)
4562 {
4563 	free(free_ccb, M_CAMCCB);
4564 }
4565 
4566 
4567 
4568 /* Private XPT functions */
4569 
4570 /*
4571  * Get a CAM control block for the caller. Charge the structure to the device
4572  * referenced by the path.  If we don't have sufficient resources to allocate
4573  * more ccbs, we return NULL.
4574  */
4575 static union ccb *
4576 xpt_get_ccb_nowait(struct cam_periph *periph)
4577 {
4578 	union ccb *new_ccb;
4579 
4580 	new_ccb = malloc(sizeof(*new_ccb), M_CAMCCB, M_ZERO|M_NOWAIT);
4581 	if (new_ccb == NULL)
4582 		return (NULL);
4583 	periph->periph_allocated++;
4584 	cam_ccbq_take_opening(&periph->path->device->ccbq);
4585 	return (new_ccb);
4586 }
4587 
4588 static union ccb *
4589 xpt_get_ccb(struct cam_periph *periph)
4590 {
4591 	union ccb *new_ccb;
4592 
4593 	cam_periph_unlock(periph);
4594 	new_ccb = malloc(sizeof(*new_ccb), M_CAMCCB, M_ZERO|M_WAITOK);
4595 	cam_periph_lock(periph);
4596 	periph->periph_allocated++;
4597 	cam_ccbq_take_opening(&periph->path->device->ccbq);
4598 	return (new_ccb);
4599 }
4600 
4601 union ccb *
4602 cam_periph_getccb(struct cam_periph *periph, u_int32_t priority)
4603 {
4604 	struct ccb_hdr *ccb_h;
4605 
4606 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("cam_periph_getccb\n"));
4607 	cam_periph_assert(periph, MA_OWNED);
4608 	while ((ccb_h = SLIST_FIRST(&periph->ccb_list)) == NULL ||
4609 	    ccb_h->pinfo.priority != priority) {
4610 		if (priority < periph->immediate_priority) {
4611 			periph->immediate_priority = priority;
4612 			xpt_run_allocq(periph, 0);
4613 		} else
4614 			cam_periph_sleep(periph, &periph->ccb_list, PRIBIO,
4615 			    "cgticb", 0);
4616 	}
4617 	SLIST_REMOVE_HEAD(&periph->ccb_list, periph_links.sle);
4618 	return ((union ccb *)ccb_h);
4619 }
4620 
4621 static void
4622 xpt_acquire_bus(struct cam_eb *bus)
4623 {
4624 
4625 	xpt_lock_buses();
4626 	bus->refcount++;
4627 	xpt_unlock_buses();
4628 }
4629 
4630 static void
4631 xpt_release_bus(struct cam_eb *bus)
4632 {
4633 
4634 	xpt_lock_buses();
4635 	KASSERT(bus->refcount >= 1, ("bus->refcount >= 1"));
4636 	if (--bus->refcount > 0) {
4637 		xpt_unlock_buses();
4638 		return;
4639 	}
4640 	TAILQ_REMOVE(&xsoftc.xpt_busses, bus, links);
4641 	xsoftc.bus_generation++;
4642 	xpt_unlock_buses();
4643 	KASSERT(TAILQ_EMPTY(&bus->et_entries),
4644 	    ("destroying bus, but target list is not empty"));
4645 	cam_sim_release(bus->sim);
4646 	mtx_destroy(&bus->eb_mtx);
4647 	free(bus, M_CAMXPT);
4648 }
4649 
4650 static struct cam_et *
4651 xpt_alloc_target(struct cam_eb *bus, target_id_t target_id)
4652 {
4653 	struct cam_et *cur_target, *target;
4654 
4655 	mtx_assert(&xsoftc.xpt_topo_lock, MA_OWNED);
4656 	mtx_assert(&bus->eb_mtx, MA_OWNED);
4657 	target = (struct cam_et *)malloc(sizeof(*target), M_CAMXPT,
4658 					 M_NOWAIT|M_ZERO);
4659 	if (target == NULL)
4660 		return (NULL);
4661 
4662 	TAILQ_INIT(&target->ed_entries);
4663 	target->bus = bus;
4664 	target->target_id = target_id;
4665 	target->refcount = 1;
4666 	target->generation = 0;
4667 	target->luns = NULL;
4668 	mtx_init(&target->luns_mtx, "CAM LUNs lock", NULL, MTX_DEF);
4669 	timevalclear(&target->last_reset);
4670 	/*
4671 	 * Hold a reference to our parent bus so it
4672 	 * will not go away before we do.
4673 	 */
4674 	bus->refcount++;
4675 
4676 	/* Insertion sort into our bus's target list */
4677 	cur_target = TAILQ_FIRST(&bus->et_entries);
4678 	while (cur_target != NULL && cur_target->target_id < target_id)
4679 		cur_target = TAILQ_NEXT(cur_target, links);
4680 	if (cur_target != NULL) {
4681 		TAILQ_INSERT_BEFORE(cur_target, target, links);
4682 	} else {
4683 		TAILQ_INSERT_TAIL(&bus->et_entries, target, links);
4684 	}
4685 	bus->generation++;
4686 	return (target);
4687 }
4688 
4689 static void
4690 xpt_acquire_target(struct cam_et *target)
4691 {
4692 	struct cam_eb *bus = target->bus;
4693 
4694 	mtx_lock(&bus->eb_mtx);
4695 	target->refcount++;
4696 	mtx_unlock(&bus->eb_mtx);
4697 }
4698 
4699 static void
4700 xpt_release_target(struct cam_et *target)
4701 {
4702 	struct cam_eb *bus = target->bus;
4703 
4704 	mtx_lock(&bus->eb_mtx);
4705 	if (--target->refcount > 0) {
4706 		mtx_unlock(&bus->eb_mtx);
4707 		return;
4708 	}
4709 	TAILQ_REMOVE(&bus->et_entries, target, links);
4710 	bus->generation++;
4711 	mtx_unlock(&bus->eb_mtx);
4712 	KASSERT(TAILQ_EMPTY(&target->ed_entries),
4713 	    ("destroying target, but device list is not empty"));
4714 	xpt_release_bus(bus);
4715 	mtx_destroy(&target->luns_mtx);
4716 	if (target->luns)
4717 		free(target->luns, M_CAMXPT);
4718 	free(target, M_CAMXPT);
4719 }
4720 
4721 static struct cam_ed *
4722 xpt_alloc_device_default(struct cam_eb *bus, struct cam_et *target,
4723 			 lun_id_t lun_id)
4724 {
4725 	struct cam_ed *device;
4726 
4727 	device = xpt_alloc_device(bus, target, lun_id);
4728 	if (device == NULL)
4729 		return (NULL);
4730 
4731 	device->mintags = 1;
4732 	device->maxtags = 1;
4733 	return (device);
4734 }
4735 
4736 static void
4737 xpt_destroy_device(void *context, int pending)
4738 {
4739 	struct cam_ed	*device = context;
4740 
4741 	mtx_lock(&device->device_mtx);
4742 	mtx_destroy(&device->device_mtx);
4743 	free(device, M_CAMDEV);
4744 }
4745 
4746 struct cam_ed *
4747 xpt_alloc_device(struct cam_eb *bus, struct cam_et *target, lun_id_t lun_id)
4748 {
4749 	struct cam_ed	*cur_device, *device;
4750 	struct cam_devq	*devq;
4751 	cam_status status;
4752 
4753 	mtx_assert(&bus->eb_mtx, MA_OWNED);
4754 	/* Make space for us in the device queue on our bus */
4755 	devq = bus->sim->devq;
4756 	mtx_lock(&devq->send_mtx);
4757 	status = cam_devq_resize(devq, devq->send_queue.array_size + 1);
4758 	mtx_unlock(&devq->send_mtx);
4759 	if (status != CAM_REQ_CMP)
4760 		return (NULL);
4761 
4762 	device = (struct cam_ed *)malloc(sizeof(*device),
4763 					 M_CAMDEV, M_NOWAIT|M_ZERO);
4764 	if (device == NULL)
4765 		return (NULL);
4766 
4767 	cam_init_pinfo(&device->devq_entry);
4768 	device->target = target;
4769 	device->lun_id = lun_id;
4770 	device->sim = bus->sim;
4771 	if (cam_ccbq_init(&device->ccbq,
4772 			  bus->sim->max_dev_openings) != 0) {
4773 		free(device, M_CAMDEV);
4774 		return (NULL);
4775 	}
4776 	SLIST_INIT(&device->asyncs);
4777 	SLIST_INIT(&device->periphs);
4778 	device->generation = 0;
4779 	device->flags = CAM_DEV_UNCONFIGURED;
4780 	device->tag_delay_count = 0;
4781 	device->tag_saved_openings = 0;
4782 	device->refcount = 1;
4783 	mtx_init(&device->device_mtx, "CAM device lock", NULL, MTX_DEF);
4784 	callout_init_mtx(&device->callout, &devq->send_mtx, 0);
4785 	TASK_INIT(&device->device_destroy_task, 0, xpt_destroy_device, device);
4786 	/*
4787 	 * Hold a reference to our parent bus so it
4788 	 * will not go away before we do.
4789 	 */
4790 	target->refcount++;
4791 
4792 	cur_device = TAILQ_FIRST(&target->ed_entries);
4793 	while (cur_device != NULL && cur_device->lun_id < lun_id)
4794 		cur_device = TAILQ_NEXT(cur_device, links);
4795 	if (cur_device != NULL)
4796 		TAILQ_INSERT_BEFORE(cur_device, device, links);
4797 	else
4798 		TAILQ_INSERT_TAIL(&target->ed_entries, device, links);
4799 	target->generation++;
4800 	return (device);
4801 }
4802 
4803 void
4804 xpt_acquire_device(struct cam_ed *device)
4805 {
4806 	struct cam_eb *bus = device->target->bus;
4807 
4808 	mtx_lock(&bus->eb_mtx);
4809 	device->refcount++;
4810 	mtx_unlock(&bus->eb_mtx);
4811 }
4812 
4813 void
4814 xpt_release_device(struct cam_ed *device)
4815 {
4816 	struct cam_eb *bus = device->target->bus;
4817 	struct cam_devq *devq;
4818 
4819 	mtx_lock(&bus->eb_mtx);
4820 	if (--device->refcount > 0) {
4821 		mtx_unlock(&bus->eb_mtx);
4822 		return;
4823 	}
4824 
4825 	TAILQ_REMOVE(&device->target->ed_entries, device,links);
4826 	device->target->generation++;
4827 	mtx_unlock(&bus->eb_mtx);
4828 
4829 	/* Release our slot in the devq */
4830 	devq = bus->sim->devq;
4831 	mtx_lock(&devq->send_mtx);
4832 	cam_devq_resize(devq, devq->send_queue.array_size - 1);
4833 	mtx_unlock(&devq->send_mtx);
4834 
4835 	KASSERT(SLIST_EMPTY(&device->periphs),
4836 	    ("destroying device, but periphs list is not empty"));
4837 	KASSERT(device->devq_entry.index == CAM_UNQUEUED_INDEX,
4838 	    ("destroying device while still queued for ccbs"));
4839 
4840 	if ((device->flags & CAM_DEV_REL_TIMEOUT_PENDING) != 0)
4841 		callout_stop(&device->callout);
4842 
4843 	xpt_release_target(device->target);
4844 
4845 	cam_ccbq_fini(&device->ccbq);
4846 	/*
4847 	 * Free allocated memory.  free(9) does nothing if the
4848 	 * supplied pointer is NULL, so it is safe to call without
4849 	 * checking.
4850 	 */
4851 	free(device->supported_vpds, M_CAMXPT);
4852 	free(device->device_id, M_CAMXPT);
4853 	free(device->ext_inq, M_CAMXPT);
4854 	free(device->physpath, M_CAMXPT);
4855 	free(device->rcap_buf, M_CAMXPT);
4856 	free(device->serial_num, M_CAMXPT);
4857 	taskqueue_enqueue(xsoftc.xpt_taskq, &device->device_destroy_task);
4858 }
4859 
4860 u_int32_t
4861 xpt_dev_ccbq_resize(struct cam_path *path, int newopenings)
4862 {
4863 	int	result;
4864 	struct	cam_ed *dev;
4865 
4866 	dev = path->device;
4867 	mtx_lock(&dev->sim->devq->send_mtx);
4868 	result = cam_ccbq_resize(&dev->ccbq, newopenings);
4869 	mtx_unlock(&dev->sim->devq->send_mtx);
4870 	if ((dev->flags & CAM_DEV_TAG_AFTER_COUNT) != 0
4871 	 || (dev->inq_flags & SID_CmdQue) != 0)
4872 		dev->tag_saved_openings = newopenings;
4873 	return (result);
4874 }
4875 
4876 static struct cam_eb *
4877 xpt_find_bus(path_id_t path_id)
4878 {
4879 	struct cam_eb *bus;
4880 
4881 	xpt_lock_buses();
4882 	for (bus = TAILQ_FIRST(&xsoftc.xpt_busses);
4883 	     bus != NULL;
4884 	     bus = TAILQ_NEXT(bus, links)) {
4885 		if (bus->path_id == path_id) {
4886 			bus->refcount++;
4887 			break;
4888 		}
4889 	}
4890 	xpt_unlock_buses();
4891 	return (bus);
4892 }
4893 
4894 static struct cam_et *
4895 xpt_find_target(struct cam_eb *bus, target_id_t	target_id)
4896 {
4897 	struct cam_et *target;
4898 
4899 	mtx_assert(&bus->eb_mtx, MA_OWNED);
4900 	for (target = TAILQ_FIRST(&bus->et_entries);
4901 	     target != NULL;
4902 	     target = TAILQ_NEXT(target, links)) {
4903 		if (target->target_id == target_id) {
4904 			target->refcount++;
4905 			break;
4906 		}
4907 	}
4908 	return (target);
4909 }
4910 
4911 static struct cam_ed *
4912 xpt_find_device(struct cam_et *target, lun_id_t lun_id)
4913 {
4914 	struct cam_ed *device;
4915 
4916 	mtx_assert(&target->bus->eb_mtx, MA_OWNED);
4917 	for (device = TAILQ_FIRST(&target->ed_entries);
4918 	     device != NULL;
4919 	     device = TAILQ_NEXT(device, links)) {
4920 		if (device->lun_id == lun_id) {
4921 			device->refcount++;
4922 			break;
4923 		}
4924 	}
4925 	return (device);
4926 }
4927 
4928 void
4929 xpt_start_tags(struct cam_path *path)
4930 {
4931 	struct ccb_relsim crs;
4932 	struct cam_ed *device;
4933 	struct cam_sim *sim;
4934 	int    newopenings;
4935 
4936 	device = path->device;
4937 	sim = path->bus->sim;
4938 	device->flags &= ~CAM_DEV_TAG_AFTER_COUNT;
4939 	xpt_freeze_devq(path, /*count*/1);
4940 	device->inq_flags |= SID_CmdQue;
4941 	if (device->tag_saved_openings != 0)
4942 		newopenings = device->tag_saved_openings;
4943 	else
4944 		newopenings = min(device->maxtags,
4945 				  sim->max_tagged_dev_openings);
4946 	xpt_dev_ccbq_resize(path, newopenings);
4947 	xpt_async(AC_GETDEV_CHANGED, path, NULL);
4948 	xpt_setup_ccb(&crs.ccb_h, path, CAM_PRIORITY_NORMAL);
4949 	crs.ccb_h.func_code = XPT_REL_SIMQ;
4950 	crs.release_flags = RELSIM_RELEASE_AFTER_QEMPTY;
4951 	crs.openings
4952 	    = crs.release_timeout
4953 	    = crs.qfrozen_cnt
4954 	    = 0;
4955 	xpt_action((union ccb *)&crs);
4956 }
4957 
4958 void
4959 xpt_stop_tags(struct cam_path *path)
4960 {
4961 	struct ccb_relsim crs;
4962 	struct cam_ed *device;
4963 	struct cam_sim *sim;
4964 
4965 	device = path->device;
4966 	sim = path->bus->sim;
4967 	device->flags &= ~CAM_DEV_TAG_AFTER_COUNT;
4968 	device->tag_delay_count = 0;
4969 	xpt_freeze_devq(path, /*count*/1);
4970 	device->inq_flags &= ~SID_CmdQue;
4971 	xpt_dev_ccbq_resize(path, sim->max_dev_openings);
4972 	xpt_async(AC_GETDEV_CHANGED, path, NULL);
4973 	xpt_setup_ccb(&crs.ccb_h, path, CAM_PRIORITY_NORMAL);
4974 	crs.ccb_h.func_code = XPT_REL_SIMQ;
4975 	crs.release_flags = RELSIM_RELEASE_AFTER_QEMPTY;
4976 	crs.openings
4977 	    = crs.release_timeout
4978 	    = crs.qfrozen_cnt
4979 	    = 0;
4980 	xpt_action((union ccb *)&crs);
4981 }
4982 
4983 static void
4984 xpt_boot_delay(void *arg)
4985 {
4986 
4987 	xpt_release_boot();
4988 }
4989 
4990 static void
4991 xpt_config(void *arg)
4992 {
4993 	/*
4994 	 * Now that interrupts are enabled, go find our devices
4995 	 */
4996 	if (taskqueue_start_threads(&xsoftc.xpt_taskq, 1, PRIBIO, "CAM taskq"))
4997 		printf("xpt_config: failed to create taskqueue thread.\n");
4998 
4999 	/* Setup debugging path */
5000 	if (cam_dflags != CAM_DEBUG_NONE) {
5001 		if (xpt_create_path(&cam_dpath, NULL,
5002 				    CAM_DEBUG_BUS, CAM_DEBUG_TARGET,
5003 				    CAM_DEBUG_LUN) != CAM_REQ_CMP) {
5004 			printf("xpt_config: xpt_create_path() failed for debug"
5005 			       " target %d:%d:%d, debugging disabled\n",
5006 			       CAM_DEBUG_BUS, CAM_DEBUG_TARGET, CAM_DEBUG_LUN);
5007 			cam_dflags = CAM_DEBUG_NONE;
5008 		}
5009 	} else
5010 		cam_dpath = NULL;
5011 
5012 	periphdriver_init(1);
5013 	xpt_hold_boot();
5014 	callout_init(&xsoftc.boot_callout, 1);
5015 	callout_reset_sbt(&xsoftc.boot_callout, SBT_1MS * xsoftc.boot_delay, 0,
5016 	    xpt_boot_delay, NULL, 0);
5017 	/* Fire up rescan thread. */
5018 	if (kproc_kthread_add(xpt_scanner_thread, NULL, &cam_proc, NULL, 0, 0,
5019 	    "cam", "scanner")) {
5020 		printf("xpt_config: failed to create rescan thread.\n");
5021 	}
5022 }
5023 
5024 void
5025 xpt_hold_boot(void)
5026 {
5027 	xpt_lock_buses();
5028 	xsoftc.buses_to_config++;
5029 	xpt_unlock_buses();
5030 }
5031 
5032 void
5033 xpt_release_boot(void)
5034 {
5035 	xpt_lock_buses();
5036 	xsoftc.buses_to_config--;
5037 	if (xsoftc.buses_to_config == 0 && xsoftc.buses_config_done == 0) {
5038 		struct	xpt_task *task;
5039 
5040 		xsoftc.buses_config_done = 1;
5041 		xpt_unlock_buses();
5042 		/* Call manually because we don't have any buses */
5043 		task = malloc(sizeof(struct xpt_task), M_CAMXPT, M_NOWAIT);
5044 		if (task != NULL) {
5045 			TASK_INIT(&task->task, 0, xpt_finishconfig_task, task);
5046 			taskqueue_enqueue(taskqueue_thread, &task->task);
5047 		}
5048 	} else
5049 		xpt_unlock_buses();
5050 }
5051 
5052 /*
5053  * If the given device only has one peripheral attached to it, and if that
5054  * peripheral is the passthrough driver, announce it.  This insures that the
5055  * user sees some sort of announcement for every peripheral in their system.
5056  */
5057 static int
5058 xptpassannouncefunc(struct cam_ed *device, void *arg)
5059 {
5060 	struct cam_periph *periph;
5061 	int i;
5062 
5063 	for (periph = SLIST_FIRST(&device->periphs), i = 0; periph != NULL;
5064 	     periph = SLIST_NEXT(periph, periph_links), i++);
5065 
5066 	periph = SLIST_FIRST(&device->periphs);
5067 	if ((i == 1)
5068 	 && (strncmp(periph->periph_name, "pass", 4) == 0))
5069 		xpt_announce_periph(periph, NULL);
5070 
5071 	return(1);
5072 }
5073 
5074 static void
5075 xpt_finishconfig_task(void *context, int pending)
5076 {
5077 
5078 	periphdriver_init(2);
5079 	/*
5080 	 * Check for devices with no "standard" peripheral driver
5081 	 * attached.  For any devices like that, announce the
5082 	 * passthrough driver so the user will see something.
5083 	 */
5084 	if (!bootverbose)
5085 		xpt_for_all_devices(xptpassannouncefunc, NULL);
5086 
5087 	/* Release our hook so that the boot can continue. */
5088 	config_intrhook_disestablish(xsoftc.xpt_config_hook);
5089 	free(xsoftc.xpt_config_hook, M_CAMXPT);
5090 	xsoftc.xpt_config_hook = NULL;
5091 
5092 	free(context, M_CAMXPT);
5093 }
5094 
5095 cam_status
5096 xpt_register_async(int event, ac_callback_t *cbfunc, void *cbarg,
5097 		   struct cam_path *path)
5098 {
5099 	struct ccb_setasync csa;
5100 	cam_status status;
5101 	int xptpath = 0;
5102 
5103 	if (path == NULL) {
5104 		status = xpt_create_path(&path, /*periph*/NULL, CAM_XPT_PATH_ID,
5105 					 CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
5106 		if (status != CAM_REQ_CMP)
5107 			return (status);
5108 		xpt_path_lock(path);
5109 		xptpath = 1;
5110 	}
5111 
5112 	xpt_setup_ccb(&csa.ccb_h, path, CAM_PRIORITY_NORMAL);
5113 	csa.ccb_h.func_code = XPT_SASYNC_CB;
5114 	csa.event_enable = event;
5115 	csa.callback = cbfunc;
5116 	csa.callback_arg = cbarg;
5117 	xpt_action((union ccb *)&csa);
5118 	status = csa.ccb_h.status;
5119 
5120 	CAM_DEBUG(csa.ccb_h.path, CAM_DEBUG_TRACE,
5121 	    ("xpt_register_async: func %p\n", cbfunc));
5122 
5123 	if (xptpath) {
5124 		xpt_path_unlock(path);
5125 		xpt_free_path(path);
5126 	}
5127 
5128 	if ((status == CAM_REQ_CMP) &&
5129 	    (csa.event_enable & AC_FOUND_DEVICE)) {
5130 		/*
5131 		 * Get this peripheral up to date with all
5132 		 * the currently existing devices.
5133 		 */
5134 		xpt_for_all_devices(xptsetasyncfunc, &csa);
5135 	}
5136 	if ((status == CAM_REQ_CMP) &&
5137 	    (csa.event_enable & AC_PATH_REGISTERED)) {
5138 		/*
5139 		 * Get this peripheral up to date with all
5140 		 * the currently existing buses.
5141 		 */
5142 		xpt_for_all_busses(xptsetasyncbusfunc, &csa);
5143 	}
5144 
5145 	return (status);
5146 }
5147 
5148 static void
5149 xptaction(struct cam_sim *sim, union ccb *work_ccb)
5150 {
5151 	CAM_DEBUG(work_ccb->ccb_h.path, CAM_DEBUG_TRACE, ("xptaction\n"));
5152 
5153 	switch (work_ccb->ccb_h.func_code) {
5154 	/* Common cases first */
5155 	case XPT_PATH_INQ:		/* Path routing inquiry */
5156 	{
5157 		struct ccb_pathinq *cpi;
5158 
5159 		cpi = &work_ccb->cpi;
5160 		cpi->version_num = 1; /* XXX??? */
5161 		cpi->hba_inquiry = 0;
5162 		cpi->target_sprt = 0;
5163 		cpi->hba_misc = 0;
5164 		cpi->hba_eng_cnt = 0;
5165 		cpi->max_target = 0;
5166 		cpi->max_lun = 0;
5167 		cpi->initiator_id = 0;
5168 		strlcpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
5169 		strlcpy(cpi->hba_vid, "", HBA_IDLEN);
5170 		strlcpy(cpi->dev_name, sim->sim_name, DEV_IDLEN);
5171 		cpi->unit_number = sim->unit_number;
5172 		cpi->bus_id = sim->bus_id;
5173 		cpi->base_transfer_speed = 0;
5174 		cpi->protocol = PROTO_UNSPECIFIED;
5175 		cpi->protocol_version = PROTO_VERSION_UNSPECIFIED;
5176 		cpi->transport = XPORT_UNSPECIFIED;
5177 		cpi->transport_version = XPORT_VERSION_UNSPECIFIED;
5178 		cpi->ccb_h.status = CAM_REQ_CMP;
5179 		xpt_done(work_ccb);
5180 		break;
5181 	}
5182 	default:
5183 		work_ccb->ccb_h.status = CAM_REQ_INVALID;
5184 		xpt_done(work_ccb);
5185 		break;
5186 	}
5187 }
5188 
5189 /*
5190  * The xpt as a "controller" has no interrupt sources, so polling
5191  * is a no-op.
5192  */
5193 static void
5194 xptpoll(struct cam_sim *sim)
5195 {
5196 }
5197 
5198 void
5199 xpt_lock_buses(void)
5200 {
5201 	mtx_lock(&xsoftc.xpt_topo_lock);
5202 }
5203 
5204 void
5205 xpt_unlock_buses(void)
5206 {
5207 	mtx_unlock(&xsoftc.xpt_topo_lock);
5208 }
5209 
5210 struct mtx *
5211 xpt_path_mtx(struct cam_path *path)
5212 {
5213 
5214 	return (&path->device->device_mtx);
5215 }
5216 
5217 static void
5218 xpt_done_process(struct ccb_hdr *ccb_h)
5219 {
5220 	struct cam_sim *sim;
5221 	struct cam_devq *devq;
5222 	struct mtx *mtx = NULL;
5223 
5224 #if defined(BUF_TRACKING) || defined(FULL_BUF_TRACKING)
5225 	struct ccb_scsiio *csio;
5226 
5227 	if (ccb_h->func_code == XPT_SCSI_IO) {
5228 		csio = &((union ccb *)ccb_h)->csio;
5229 		if (csio->bio != NULL)
5230 			biotrack(csio->bio, __func__);
5231 	}
5232 #endif
5233 
5234 	if (ccb_h->flags & CAM_HIGH_POWER) {
5235 		struct highpowerlist	*hphead;
5236 		struct cam_ed		*device;
5237 
5238 		mtx_lock(&xsoftc.xpt_highpower_lock);
5239 		hphead = &xsoftc.highpowerq;
5240 
5241 		device = STAILQ_FIRST(hphead);
5242 
5243 		/*
5244 		 * Increment the count since this command is done.
5245 		 */
5246 		xsoftc.num_highpower++;
5247 
5248 		/*
5249 		 * Any high powered commands queued up?
5250 		 */
5251 		if (device != NULL) {
5252 
5253 			STAILQ_REMOVE_HEAD(hphead, highpowerq_entry);
5254 			mtx_unlock(&xsoftc.xpt_highpower_lock);
5255 
5256 			mtx_lock(&device->sim->devq->send_mtx);
5257 			xpt_release_devq_device(device,
5258 					 /*count*/1, /*runqueue*/TRUE);
5259 			mtx_unlock(&device->sim->devq->send_mtx);
5260 		} else
5261 			mtx_unlock(&xsoftc.xpt_highpower_lock);
5262 	}
5263 
5264 	sim = ccb_h->path->bus->sim;
5265 
5266 	if (ccb_h->status & CAM_RELEASE_SIMQ) {
5267 		xpt_release_simq(sim, /*run_queue*/FALSE);
5268 		ccb_h->status &= ~CAM_RELEASE_SIMQ;
5269 	}
5270 
5271 	if ((ccb_h->flags & CAM_DEV_QFRZDIS)
5272 	 && (ccb_h->status & CAM_DEV_QFRZN)) {
5273 		xpt_release_devq(ccb_h->path, /*count*/1, /*run_queue*/TRUE);
5274 		ccb_h->status &= ~CAM_DEV_QFRZN;
5275 	}
5276 
5277 	devq = sim->devq;
5278 	if ((ccb_h->func_code & XPT_FC_USER_CCB) == 0) {
5279 		struct cam_ed *dev = ccb_h->path->device;
5280 
5281 		mtx_lock(&devq->send_mtx);
5282 		devq->send_active--;
5283 		devq->send_openings++;
5284 		cam_ccbq_ccb_done(&dev->ccbq, (union ccb *)ccb_h);
5285 
5286 		if (((dev->flags & CAM_DEV_REL_ON_QUEUE_EMPTY) != 0
5287 		  && (dev->ccbq.dev_active == 0))) {
5288 			dev->flags &= ~CAM_DEV_REL_ON_QUEUE_EMPTY;
5289 			xpt_release_devq_device(dev, /*count*/1,
5290 					 /*run_queue*/FALSE);
5291 		}
5292 
5293 		if (((dev->flags & CAM_DEV_REL_ON_COMPLETE) != 0
5294 		  && (ccb_h->status&CAM_STATUS_MASK) != CAM_REQUEUE_REQ)) {
5295 			dev->flags &= ~CAM_DEV_REL_ON_COMPLETE;
5296 			xpt_release_devq_device(dev, /*count*/1,
5297 					 /*run_queue*/FALSE);
5298 		}
5299 
5300 		if (!device_is_queued(dev))
5301 			(void)xpt_schedule_devq(devq, dev);
5302 		xpt_run_devq(devq);
5303 		mtx_unlock(&devq->send_mtx);
5304 
5305 		if ((dev->flags & CAM_DEV_TAG_AFTER_COUNT) != 0) {
5306 			mtx = xpt_path_mtx(ccb_h->path);
5307 			mtx_lock(mtx);
5308 
5309 			if ((dev->flags & CAM_DEV_TAG_AFTER_COUNT) != 0
5310 			 && (--dev->tag_delay_count == 0))
5311 				xpt_start_tags(ccb_h->path);
5312 		}
5313 	}
5314 
5315 	if ((ccb_h->flags & CAM_UNLOCKED) == 0) {
5316 		if (mtx == NULL) {
5317 			mtx = xpt_path_mtx(ccb_h->path);
5318 			mtx_lock(mtx);
5319 		}
5320 	} else {
5321 		if (mtx != NULL) {
5322 			mtx_unlock(mtx);
5323 			mtx = NULL;
5324 		}
5325 	}
5326 
5327 	/* Call the peripheral driver's callback */
5328 	ccb_h->pinfo.index = CAM_UNQUEUED_INDEX;
5329 	(*ccb_h->cbfcnp)(ccb_h->path->periph, (union ccb *)ccb_h);
5330 	if (mtx != NULL)
5331 		mtx_unlock(mtx);
5332 }
5333 
5334 void
5335 xpt_done_td(void *arg)
5336 {
5337 	struct cam_doneq *queue = arg;
5338 	struct ccb_hdr *ccb_h;
5339 	STAILQ_HEAD(, ccb_hdr)	doneq;
5340 
5341 	STAILQ_INIT(&doneq);
5342 	mtx_lock(&queue->cam_doneq_mtx);
5343 	while (1) {
5344 		while (STAILQ_EMPTY(&queue->cam_doneq)) {
5345 			queue->cam_doneq_sleep = 1;
5346 			msleep(&queue->cam_doneq, &queue->cam_doneq_mtx,
5347 			    PRIBIO, "-", 0);
5348 			queue->cam_doneq_sleep = 0;
5349 		}
5350 		STAILQ_CONCAT(&doneq, &queue->cam_doneq);
5351 		mtx_unlock(&queue->cam_doneq_mtx);
5352 
5353 		THREAD_NO_SLEEPING();
5354 		while ((ccb_h = STAILQ_FIRST(&doneq)) != NULL) {
5355 			STAILQ_REMOVE_HEAD(&doneq, sim_links.stqe);
5356 			xpt_done_process(ccb_h);
5357 		}
5358 		THREAD_SLEEPING_OK();
5359 
5360 		mtx_lock(&queue->cam_doneq_mtx);
5361 	}
5362 }
5363 
5364 static void
5365 camisr_runqueue(void)
5366 {
5367 	struct	ccb_hdr *ccb_h;
5368 	struct cam_doneq *queue;
5369 	int i;
5370 
5371 	/* Process global queues. */
5372 	for (i = 0; i < cam_num_doneqs; i++) {
5373 		queue = &cam_doneqs[i];
5374 		mtx_lock(&queue->cam_doneq_mtx);
5375 		while ((ccb_h = STAILQ_FIRST(&queue->cam_doneq)) != NULL) {
5376 			STAILQ_REMOVE_HEAD(&queue->cam_doneq, sim_links.stqe);
5377 			mtx_unlock(&queue->cam_doneq_mtx);
5378 			xpt_done_process(ccb_h);
5379 			mtx_lock(&queue->cam_doneq_mtx);
5380 		}
5381 		mtx_unlock(&queue->cam_doneq_mtx);
5382 	}
5383 }
5384 
5385 struct kv
5386 {
5387 	uint32_t v;
5388 	const char *name;
5389 };
5390 
5391 static struct kv map[] = {
5392 	{ XPT_NOOP, "XPT_NOOP" },
5393 	{ XPT_SCSI_IO, "XPT_SCSI_IO" },
5394 	{ XPT_GDEV_TYPE, "XPT_GDEV_TYPE" },
5395 	{ XPT_GDEVLIST, "XPT_GDEVLIST" },
5396 	{ XPT_PATH_INQ, "XPT_PATH_INQ" },
5397 	{ XPT_REL_SIMQ, "XPT_REL_SIMQ" },
5398 	{ XPT_SASYNC_CB, "XPT_SASYNC_CB" },
5399 	{ XPT_SDEV_TYPE, "XPT_SDEV_TYPE" },
5400 	{ XPT_SCAN_BUS, "XPT_SCAN_BUS" },
5401 	{ XPT_DEV_MATCH, "XPT_DEV_MATCH" },
5402 	{ XPT_DEBUG, "XPT_DEBUG" },
5403 	{ XPT_PATH_STATS, "XPT_PATH_STATS" },
5404 	{ XPT_GDEV_STATS, "XPT_GDEV_STATS" },
5405 	{ XPT_DEV_ADVINFO, "XPT_DEV_ADVINFO" },
5406 	{ XPT_ASYNC, "XPT_ASYNC" },
5407 	{ XPT_ABORT, "XPT_ABORT" },
5408 	{ XPT_RESET_BUS, "XPT_RESET_BUS" },
5409 	{ XPT_RESET_DEV, "XPT_RESET_DEV" },
5410 	{ XPT_TERM_IO, "XPT_TERM_IO" },
5411 	{ XPT_SCAN_LUN, "XPT_SCAN_LUN" },
5412 	{ XPT_GET_TRAN_SETTINGS, "XPT_GET_TRAN_SETTINGS" },
5413 	{ XPT_SET_TRAN_SETTINGS, "XPT_SET_TRAN_SETTINGS" },
5414 	{ XPT_CALC_GEOMETRY, "XPT_CALC_GEOMETRY" },
5415 	{ XPT_ATA_IO, "XPT_ATA_IO" },
5416 	{ XPT_GET_SIM_KNOB, "XPT_GET_SIM_KNOB" },
5417 	{ XPT_SET_SIM_KNOB, "XPT_SET_SIM_KNOB" },
5418 	{ XPT_NVME_IO, "XPT_NVME_IO" },
5419 	{ XPT_MMCSD_IO, "XPT_MMCSD_IO" },
5420 	{ XPT_SMP_IO, "XPT_SMP_IO" },
5421 	{ XPT_SCAN_TGT, "XPT_SCAN_TGT" },
5422 	{ XPT_ENG_INQ, "XPT_ENG_INQ" },
5423 	{ XPT_ENG_EXEC, "XPT_ENG_EXEC" },
5424 	{ XPT_EN_LUN, "XPT_EN_LUN" },
5425 	{ XPT_TARGET_IO, "XPT_TARGET_IO" },
5426 	{ XPT_ACCEPT_TARGET_IO, "XPT_ACCEPT_TARGET_IO" },
5427 	{ XPT_CONT_TARGET_IO, "XPT_CONT_TARGET_IO" },
5428 	{ XPT_IMMED_NOTIFY, "XPT_IMMED_NOTIFY" },
5429 	{ XPT_NOTIFY_ACK, "XPT_NOTIFY_ACK" },
5430 	{ XPT_IMMEDIATE_NOTIFY, "XPT_IMMEDIATE_NOTIFY" },
5431 	{ XPT_NOTIFY_ACKNOWLEDGE, "XPT_NOTIFY_ACKNOWLEDGE" },
5432 	{ 0, 0 }
5433 };
5434 
5435 static const char *
5436 xpt_action_name(uint32_t action)
5437 {
5438 	static char buffer[32];	/* Only for unknown messages -- racy */
5439 	struct kv *walker = map;
5440 
5441 	while (walker->name != NULL) {
5442 		if (walker->v == action)
5443 			return (walker->name);
5444 		walker++;
5445 	}
5446 
5447 	snprintf(buffer, sizeof(buffer), "%#x", action);
5448 	return (buffer);
5449 }
5450