xref: /freebsd/sys/cam/cam_xpt.c (revision ca86bcf2531c7b149c95244a67853d44323e7855)
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 cam_ed *dev;
2728 
2729 		dev = path->device;
2730 		if ((dev->flags & CAM_DEV_UNCONFIGURED) != 0) {
2731 			start_ccb->ccb_h.status = CAM_DEV_NOT_THERE;
2732 		} else {
2733 			struct ccb_getdevstats *cgds;
2734 			struct cam_eb *bus;
2735 			struct cam_et *tar;
2736 			struct cam_devq *devq;
2737 
2738 			cgds = &start_ccb->cgds;
2739 			bus = path->bus;
2740 			tar = path->target;
2741 			devq = bus->sim->devq;
2742 			mtx_lock(&devq->send_mtx);
2743 			cgds->dev_openings = dev->ccbq.dev_openings;
2744 			cgds->dev_active = dev->ccbq.dev_active;
2745 			cgds->allocated = dev->ccbq.allocated;
2746 			cgds->queued = cam_ccbq_pending_ccb_count(&dev->ccbq);
2747 			cgds->held = cgds->allocated - cgds->dev_active -
2748 			    cgds->queued;
2749 			cgds->last_reset = tar->last_reset;
2750 			cgds->maxtags = dev->maxtags;
2751 			cgds->mintags = dev->mintags;
2752 			if (timevalcmp(&tar->last_reset, &bus->last_reset, <))
2753 				cgds->last_reset = bus->last_reset;
2754 			mtx_unlock(&devq->send_mtx);
2755 			cgds->ccb_h.status = CAM_REQ_CMP;
2756 		}
2757 		break;
2758 	}
2759 	case XPT_GDEVLIST:
2760 	{
2761 		struct cam_periph	*nperiph;
2762 		struct periph_list	*periph_head;
2763 		struct ccb_getdevlist	*cgdl;
2764 		u_int			i;
2765 		struct cam_ed		*device;
2766 		int			found;
2767 
2768 
2769 		found = 0;
2770 
2771 		/*
2772 		 * Don't want anyone mucking with our data.
2773 		 */
2774 		device = path->device;
2775 		periph_head = &device->periphs;
2776 		cgdl = &start_ccb->cgdl;
2777 
2778 		/*
2779 		 * Check and see if the list has changed since the user
2780 		 * last requested a list member.  If so, tell them that the
2781 		 * list has changed, and therefore they need to start over
2782 		 * from the beginning.
2783 		 */
2784 		if ((cgdl->index != 0) &&
2785 		    (cgdl->generation != device->generation)) {
2786 			cgdl->status = CAM_GDEVLIST_LIST_CHANGED;
2787 			break;
2788 		}
2789 
2790 		/*
2791 		 * Traverse the list of peripherals and attempt to find
2792 		 * the requested peripheral.
2793 		 */
2794 		for (nperiph = SLIST_FIRST(periph_head), i = 0;
2795 		     (nperiph != NULL) && (i <= cgdl->index);
2796 		     nperiph = SLIST_NEXT(nperiph, periph_links), i++) {
2797 			if (i == cgdl->index) {
2798 				strncpy(cgdl->periph_name,
2799 					nperiph->periph_name,
2800 					DEV_IDLEN);
2801 				cgdl->unit_number = nperiph->unit_number;
2802 				found = 1;
2803 			}
2804 		}
2805 		if (found == 0) {
2806 			cgdl->status = CAM_GDEVLIST_ERROR;
2807 			break;
2808 		}
2809 
2810 		if (nperiph == NULL)
2811 			cgdl->status = CAM_GDEVLIST_LAST_DEVICE;
2812 		else
2813 			cgdl->status = CAM_GDEVLIST_MORE_DEVS;
2814 
2815 		cgdl->index++;
2816 		cgdl->generation = device->generation;
2817 
2818 		cgdl->ccb_h.status = CAM_REQ_CMP;
2819 		break;
2820 	}
2821 	case XPT_DEV_MATCH:
2822 	{
2823 		dev_pos_type position_type;
2824 		struct ccb_dev_match *cdm;
2825 
2826 		cdm = &start_ccb->cdm;
2827 
2828 		/*
2829 		 * There are two ways of getting at information in the EDT.
2830 		 * The first way is via the primary EDT tree.  It starts
2831 		 * with a list of buses, then a list of targets on a bus,
2832 		 * then devices/luns on a target, and then peripherals on a
2833 		 * device/lun.  The "other" way is by the peripheral driver
2834 		 * lists.  The peripheral driver lists are organized by
2835 		 * peripheral driver.  (obviously)  So it makes sense to
2836 		 * use the peripheral driver list if the user is looking
2837 		 * for something like "da1", or all "da" devices.  If the
2838 		 * user is looking for something on a particular bus/target
2839 		 * or lun, it's generally better to go through the EDT tree.
2840 		 */
2841 
2842 		if (cdm->pos.position_type != CAM_DEV_POS_NONE)
2843 			position_type = cdm->pos.position_type;
2844 		else {
2845 			u_int i;
2846 
2847 			position_type = CAM_DEV_POS_NONE;
2848 
2849 			for (i = 0; i < cdm->num_patterns; i++) {
2850 				if ((cdm->patterns[i].type == DEV_MATCH_BUS)
2851 				 ||(cdm->patterns[i].type == DEV_MATCH_DEVICE)){
2852 					position_type = CAM_DEV_POS_EDT;
2853 					break;
2854 				}
2855 			}
2856 
2857 			if (cdm->num_patterns == 0)
2858 				position_type = CAM_DEV_POS_EDT;
2859 			else if (position_type == CAM_DEV_POS_NONE)
2860 				position_type = CAM_DEV_POS_PDRV;
2861 		}
2862 
2863 		switch(position_type & CAM_DEV_POS_TYPEMASK) {
2864 		case CAM_DEV_POS_EDT:
2865 			xptedtmatch(cdm);
2866 			break;
2867 		case CAM_DEV_POS_PDRV:
2868 			xptperiphlistmatch(cdm);
2869 			break;
2870 		default:
2871 			cdm->status = CAM_DEV_MATCH_ERROR;
2872 			break;
2873 		}
2874 
2875 		if (cdm->status == CAM_DEV_MATCH_ERROR)
2876 			start_ccb->ccb_h.status = CAM_REQ_CMP_ERR;
2877 		else
2878 			start_ccb->ccb_h.status = CAM_REQ_CMP;
2879 
2880 		break;
2881 	}
2882 	case XPT_SASYNC_CB:
2883 	{
2884 		struct ccb_setasync *csa;
2885 		struct async_node *cur_entry;
2886 		struct async_list *async_head;
2887 		u_int32_t added;
2888 
2889 		csa = &start_ccb->csa;
2890 		added = csa->event_enable;
2891 		async_head = &path->device->asyncs;
2892 
2893 		/*
2894 		 * If there is already an entry for us, simply
2895 		 * update it.
2896 		 */
2897 		cur_entry = SLIST_FIRST(async_head);
2898 		while (cur_entry != NULL) {
2899 			if ((cur_entry->callback_arg == csa->callback_arg)
2900 			 && (cur_entry->callback == csa->callback))
2901 				break;
2902 			cur_entry = SLIST_NEXT(cur_entry, links);
2903 		}
2904 
2905 		if (cur_entry != NULL) {
2906 		 	/*
2907 			 * If the request has no flags set,
2908 			 * remove the entry.
2909 			 */
2910 			added &= ~cur_entry->event_enable;
2911 			if (csa->event_enable == 0) {
2912 				SLIST_REMOVE(async_head, cur_entry,
2913 					     async_node, links);
2914 				xpt_release_device(path->device);
2915 				free(cur_entry, M_CAMXPT);
2916 			} else {
2917 				cur_entry->event_enable = csa->event_enable;
2918 			}
2919 			csa->event_enable = added;
2920 		} else {
2921 			cur_entry = malloc(sizeof(*cur_entry), M_CAMXPT,
2922 					   M_NOWAIT);
2923 			if (cur_entry == NULL) {
2924 				csa->ccb_h.status = CAM_RESRC_UNAVAIL;
2925 				break;
2926 			}
2927 			cur_entry->event_enable = csa->event_enable;
2928 			cur_entry->event_lock =
2929 			    mtx_owned(path->bus->sim->mtx) ? 1 : 0;
2930 			cur_entry->callback_arg = csa->callback_arg;
2931 			cur_entry->callback = csa->callback;
2932 			SLIST_INSERT_HEAD(async_head, cur_entry, links);
2933 			xpt_acquire_device(path->device);
2934 		}
2935 		start_ccb->ccb_h.status = CAM_REQ_CMP;
2936 		break;
2937 	}
2938 	case XPT_REL_SIMQ:
2939 	{
2940 		struct ccb_relsim *crs;
2941 		struct cam_ed *dev;
2942 
2943 		crs = &start_ccb->crs;
2944 		dev = path->device;
2945 		if (dev == NULL) {
2946 
2947 			crs->ccb_h.status = CAM_DEV_NOT_THERE;
2948 			break;
2949 		}
2950 
2951 		if ((crs->release_flags & RELSIM_ADJUST_OPENINGS) != 0) {
2952 
2953 			/* Don't ever go below one opening */
2954 			if (crs->openings > 0) {
2955 				xpt_dev_ccbq_resize(path, crs->openings);
2956 				if (bootverbose) {
2957 					xpt_print(path,
2958 					    "number of openings is now %d\n",
2959 					    crs->openings);
2960 				}
2961 			}
2962 		}
2963 
2964 		mtx_lock(&dev->sim->devq->send_mtx);
2965 		if ((crs->release_flags & RELSIM_RELEASE_AFTER_TIMEOUT) != 0) {
2966 
2967 			if ((dev->flags & CAM_DEV_REL_TIMEOUT_PENDING) != 0) {
2968 
2969 				/*
2970 				 * Just extend the old timeout and decrement
2971 				 * the freeze count so that a single timeout
2972 				 * is sufficient for releasing the queue.
2973 				 */
2974 				start_ccb->ccb_h.flags &= ~CAM_DEV_QFREEZE;
2975 				callout_stop(&dev->callout);
2976 			} else {
2977 
2978 				start_ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
2979 			}
2980 
2981 			callout_reset_sbt(&dev->callout,
2982 			    SBT_1MS * crs->release_timeout, 0,
2983 			    xpt_release_devq_timeout, dev, 0);
2984 
2985 			dev->flags |= CAM_DEV_REL_TIMEOUT_PENDING;
2986 
2987 		}
2988 
2989 		if ((crs->release_flags & RELSIM_RELEASE_AFTER_CMDCMPLT) != 0) {
2990 
2991 			if ((dev->flags & CAM_DEV_REL_ON_COMPLETE) != 0) {
2992 				/*
2993 				 * Decrement the freeze count so that a single
2994 				 * completion is still sufficient to unfreeze
2995 				 * the queue.
2996 				 */
2997 				start_ccb->ccb_h.flags &= ~CAM_DEV_QFREEZE;
2998 			} else {
2999 
3000 				dev->flags |= CAM_DEV_REL_ON_COMPLETE;
3001 				start_ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
3002 			}
3003 		}
3004 
3005 		if ((crs->release_flags & RELSIM_RELEASE_AFTER_QEMPTY) != 0) {
3006 
3007 			if ((dev->flags & CAM_DEV_REL_ON_QUEUE_EMPTY) != 0
3008 			 || (dev->ccbq.dev_active == 0)) {
3009 
3010 				start_ccb->ccb_h.flags &= ~CAM_DEV_QFREEZE;
3011 			} else {
3012 
3013 				dev->flags |= CAM_DEV_REL_ON_QUEUE_EMPTY;
3014 				start_ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
3015 			}
3016 		}
3017 		mtx_unlock(&dev->sim->devq->send_mtx);
3018 
3019 		if ((start_ccb->ccb_h.flags & CAM_DEV_QFREEZE) == 0)
3020 			xpt_release_devq(path, /*count*/1, /*run_queue*/TRUE);
3021 		start_ccb->crs.qfrozen_cnt = dev->ccbq.queue.qfrozen_cnt;
3022 		start_ccb->ccb_h.status = CAM_REQ_CMP;
3023 		break;
3024 	}
3025 	case XPT_DEBUG: {
3026 		struct cam_path *oldpath;
3027 
3028 		/* Check that all request bits are supported. */
3029 		if (start_ccb->cdbg.flags & ~(CAM_DEBUG_COMPILE)) {
3030 			start_ccb->ccb_h.status = CAM_FUNC_NOTAVAIL;
3031 			break;
3032 		}
3033 
3034 		cam_dflags = CAM_DEBUG_NONE;
3035 		if (cam_dpath != NULL) {
3036 			oldpath = cam_dpath;
3037 			cam_dpath = NULL;
3038 			xpt_free_path(oldpath);
3039 		}
3040 		if (start_ccb->cdbg.flags != CAM_DEBUG_NONE) {
3041 			if (xpt_create_path(&cam_dpath, NULL,
3042 					    start_ccb->ccb_h.path_id,
3043 					    start_ccb->ccb_h.target_id,
3044 					    start_ccb->ccb_h.target_lun) !=
3045 					    CAM_REQ_CMP) {
3046 				start_ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
3047 			} else {
3048 				cam_dflags = start_ccb->cdbg.flags;
3049 				start_ccb->ccb_h.status = CAM_REQ_CMP;
3050 				xpt_print(cam_dpath, "debugging flags now %x\n",
3051 				    cam_dflags);
3052 			}
3053 		} else
3054 			start_ccb->ccb_h.status = CAM_REQ_CMP;
3055 		break;
3056 	}
3057 	case XPT_NOOP:
3058 		if ((start_ccb->ccb_h.flags & CAM_DEV_QFREEZE) != 0)
3059 			xpt_freeze_devq(path, 1);
3060 		start_ccb->ccb_h.status = CAM_REQ_CMP;
3061 		break;
3062 	case XPT_REPROBE_LUN:
3063 		xpt_async(AC_INQ_CHANGED, path, NULL);
3064 		start_ccb->ccb_h.status = CAM_REQ_CMP;
3065 		xpt_done(start_ccb);
3066 		break;
3067 	default:
3068 	case XPT_SDEV_TYPE:
3069 	case XPT_TERM_IO:
3070 	case XPT_ENG_INQ:
3071 		/* XXX Implement */
3072 		xpt_print(start_ccb->ccb_h.path,
3073 		    "%s: CCB type %#x %s not supported\n", __func__,
3074 		    start_ccb->ccb_h.func_code,
3075 		    xpt_action_name(start_ccb->ccb_h.func_code));
3076 		start_ccb->ccb_h.status = CAM_PROVIDE_FAIL;
3077 		if (start_ccb->ccb_h.func_code & XPT_FC_DEV_QUEUED) {
3078 			xpt_done(start_ccb);
3079 		}
3080 		break;
3081 	}
3082 	CAM_DEBUG(path, CAM_DEBUG_TRACE,
3083 	    ("xpt_action_default: func= %#x %s status %#x\n",
3084 		start_ccb->ccb_h.func_code,
3085  		xpt_action_name(start_ccb->ccb_h.func_code),
3086 		start_ccb->ccb_h.status));
3087 }
3088 
3089 void
3090 xpt_polled_action(union ccb *start_ccb)
3091 {
3092 	u_int32_t timeout;
3093 	struct	  cam_sim *sim;
3094 	struct	  cam_devq *devq;
3095 	struct	  cam_ed *dev;
3096 
3097 	timeout = start_ccb->ccb_h.timeout * 10;
3098 	sim = start_ccb->ccb_h.path->bus->sim;
3099 	devq = sim->devq;
3100 	dev = start_ccb->ccb_h.path->device;
3101 
3102 	mtx_unlock(&dev->device_mtx);
3103 
3104 	/*
3105 	 * Steal an opening so that no other queued requests
3106 	 * can get it before us while we simulate interrupts.
3107 	 */
3108 	mtx_lock(&devq->send_mtx);
3109 	dev->ccbq.dev_openings--;
3110 	while((devq->send_openings <= 0 || dev->ccbq.dev_openings < 0) &&
3111 	    (--timeout > 0)) {
3112 		mtx_unlock(&devq->send_mtx);
3113 		DELAY(100);
3114 		CAM_SIM_LOCK(sim);
3115 		(*(sim->sim_poll))(sim);
3116 		CAM_SIM_UNLOCK(sim);
3117 		camisr_runqueue();
3118 		mtx_lock(&devq->send_mtx);
3119 	}
3120 	dev->ccbq.dev_openings++;
3121 	mtx_unlock(&devq->send_mtx);
3122 
3123 	if (timeout != 0) {
3124 		xpt_action(start_ccb);
3125 		while(--timeout > 0) {
3126 			CAM_SIM_LOCK(sim);
3127 			(*(sim->sim_poll))(sim);
3128 			CAM_SIM_UNLOCK(sim);
3129 			camisr_runqueue();
3130 			if ((start_ccb->ccb_h.status  & CAM_STATUS_MASK)
3131 			    != CAM_REQ_INPROG)
3132 				break;
3133 			DELAY(100);
3134 		}
3135 		if (timeout == 0) {
3136 			/*
3137 			 * XXX Is it worth adding a sim_timeout entry
3138 			 * point so we can attempt recovery?  If
3139 			 * this is only used for dumps, I don't think
3140 			 * it is.
3141 			 */
3142 			start_ccb->ccb_h.status = CAM_CMD_TIMEOUT;
3143 		}
3144 	} else {
3145 		start_ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
3146 	}
3147 
3148 	mtx_lock(&dev->device_mtx);
3149 }
3150 
3151 /*
3152  * Schedule a peripheral driver to receive a ccb when its
3153  * target device has space for more transactions.
3154  */
3155 void
3156 xpt_schedule(struct cam_periph *periph, u_int32_t new_priority)
3157 {
3158 
3159 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("xpt_schedule\n"));
3160 	cam_periph_assert(periph, MA_OWNED);
3161 	if (new_priority < periph->scheduled_priority) {
3162 		periph->scheduled_priority = new_priority;
3163 		xpt_run_allocq(periph, 0);
3164 	}
3165 }
3166 
3167 
3168 /*
3169  * Schedule a device to run on a given queue.
3170  * If the device was inserted as a new entry on the queue,
3171  * return 1 meaning the device queue should be run. If we
3172  * were already queued, implying someone else has already
3173  * started the queue, return 0 so the caller doesn't attempt
3174  * to run the queue.
3175  */
3176 static int
3177 xpt_schedule_dev(struct camq *queue, cam_pinfo *pinfo,
3178 		 u_int32_t new_priority)
3179 {
3180 	int retval;
3181 	u_int32_t old_priority;
3182 
3183 	CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_schedule_dev\n"));
3184 
3185 	old_priority = pinfo->priority;
3186 
3187 	/*
3188 	 * Are we already queued?
3189 	 */
3190 	if (pinfo->index != CAM_UNQUEUED_INDEX) {
3191 		/* Simply reorder based on new priority */
3192 		if (new_priority < old_priority) {
3193 			camq_change_priority(queue, pinfo->index,
3194 					     new_priority);
3195 			CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3196 					("changed priority to %d\n",
3197 					 new_priority));
3198 			retval = 1;
3199 		} else
3200 			retval = 0;
3201 	} else {
3202 		/* New entry on the queue */
3203 		if (new_priority < old_priority)
3204 			pinfo->priority = new_priority;
3205 
3206 		CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3207 				("Inserting onto queue\n"));
3208 		pinfo->generation = ++queue->generation;
3209 		camq_insert(queue, pinfo);
3210 		retval = 1;
3211 	}
3212 	return (retval);
3213 }
3214 
3215 static void
3216 xpt_run_allocq_task(void *context, int pending)
3217 {
3218 	struct cam_periph *periph = context;
3219 
3220 	cam_periph_lock(periph);
3221 	periph->flags &= ~CAM_PERIPH_RUN_TASK;
3222 	xpt_run_allocq(periph, 1);
3223 	cam_periph_unlock(periph);
3224 	cam_periph_release(periph);
3225 }
3226 
3227 static void
3228 xpt_run_allocq(struct cam_periph *periph, int sleep)
3229 {
3230 	struct cam_ed	*device;
3231 	union ccb	*ccb;
3232 	uint32_t	 prio;
3233 
3234 	cam_periph_assert(periph, MA_OWNED);
3235 	if (periph->periph_allocating)
3236 		return;
3237 	periph->periph_allocating = 1;
3238 	CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_run_allocq(%p)\n", periph));
3239 	device = periph->path->device;
3240 	ccb = NULL;
3241 restart:
3242 	while ((prio = min(periph->scheduled_priority,
3243 	    periph->immediate_priority)) != CAM_PRIORITY_NONE &&
3244 	    (periph->periph_allocated - (ccb != NULL ? 1 : 0) <
3245 	     device->ccbq.total_openings || prio <= CAM_PRIORITY_OOB)) {
3246 
3247 		if (ccb == NULL &&
3248 		    (ccb = xpt_get_ccb_nowait(periph)) == NULL) {
3249 			if (sleep) {
3250 				ccb = xpt_get_ccb(periph);
3251 				goto restart;
3252 			}
3253 			if (periph->flags & CAM_PERIPH_RUN_TASK)
3254 				break;
3255 			cam_periph_doacquire(periph);
3256 			periph->flags |= CAM_PERIPH_RUN_TASK;
3257 			taskqueue_enqueue(xsoftc.xpt_taskq,
3258 			    &periph->periph_run_task);
3259 			break;
3260 		}
3261 		xpt_setup_ccb(&ccb->ccb_h, periph->path, prio);
3262 		if (prio == periph->immediate_priority) {
3263 			periph->immediate_priority = CAM_PRIORITY_NONE;
3264 			CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3265 					("waking cam_periph_getccb()\n"));
3266 			SLIST_INSERT_HEAD(&periph->ccb_list, &ccb->ccb_h,
3267 					  periph_links.sle);
3268 			wakeup(&periph->ccb_list);
3269 		} else {
3270 			periph->scheduled_priority = CAM_PRIORITY_NONE;
3271 			CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3272 					("calling periph_start()\n"));
3273 			periph->periph_start(periph, ccb);
3274 		}
3275 		ccb = NULL;
3276 	}
3277 	if (ccb != NULL)
3278 		xpt_release_ccb(ccb);
3279 	periph->periph_allocating = 0;
3280 }
3281 
3282 static void
3283 xpt_run_devq(struct cam_devq *devq)
3284 {
3285 	int lock;
3286 
3287 	CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_run_devq\n"));
3288 
3289 	devq->send_queue.qfrozen_cnt++;
3290 	while ((devq->send_queue.entries > 0)
3291 	    && (devq->send_openings > 0)
3292 	    && (devq->send_queue.qfrozen_cnt <= 1)) {
3293 		struct	cam_ed *device;
3294 		union ccb *work_ccb;
3295 		struct	cam_sim *sim;
3296 		struct xpt_proto *proto;
3297 
3298 		device = (struct cam_ed *)camq_remove(&devq->send_queue,
3299 							   CAMQ_HEAD);
3300 		CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3301 				("running device %p\n", device));
3302 
3303 		work_ccb = cam_ccbq_peek_ccb(&device->ccbq, CAMQ_HEAD);
3304 		if (work_ccb == NULL) {
3305 			printf("device on run queue with no ccbs???\n");
3306 			continue;
3307 		}
3308 
3309 		if ((work_ccb->ccb_h.flags & CAM_HIGH_POWER) != 0) {
3310 
3311 			mtx_lock(&xsoftc.xpt_highpower_lock);
3312 		 	if (xsoftc.num_highpower <= 0) {
3313 				/*
3314 				 * We got a high power command, but we
3315 				 * don't have any available slots.  Freeze
3316 				 * the device queue until we have a slot
3317 				 * available.
3318 				 */
3319 				xpt_freeze_devq_device(device, 1);
3320 				STAILQ_INSERT_TAIL(&xsoftc.highpowerq, device,
3321 						   highpowerq_entry);
3322 
3323 				mtx_unlock(&xsoftc.xpt_highpower_lock);
3324 				continue;
3325 			} else {
3326 				/*
3327 				 * Consume a high power slot while
3328 				 * this ccb runs.
3329 				 */
3330 				xsoftc.num_highpower--;
3331 			}
3332 			mtx_unlock(&xsoftc.xpt_highpower_lock);
3333 		}
3334 		cam_ccbq_remove_ccb(&device->ccbq, work_ccb);
3335 		cam_ccbq_send_ccb(&device->ccbq, work_ccb);
3336 		devq->send_openings--;
3337 		devq->send_active++;
3338 		xpt_schedule_devq(devq, device);
3339 		mtx_unlock(&devq->send_mtx);
3340 
3341 		if ((work_ccb->ccb_h.flags & CAM_DEV_QFREEZE) != 0) {
3342 			/*
3343 			 * The client wants to freeze the queue
3344 			 * after this CCB is sent.
3345 			 */
3346 			xpt_freeze_devq(work_ccb->ccb_h.path, 1);
3347 		}
3348 
3349 		/* In Target mode, the peripheral driver knows best... */
3350 		if (work_ccb->ccb_h.func_code == XPT_SCSI_IO) {
3351 			if ((device->inq_flags & SID_CmdQue) != 0
3352 			 && work_ccb->csio.tag_action != CAM_TAG_ACTION_NONE)
3353 				work_ccb->ccb_h.flags |= CAM_TAG_ACTION_VALID;
3354 			else
3355 				/*
3356 				 * Clear this in case of a retried CCB that
3357 				 * failed due to a rejected tag.
3358 				 */
3359 				work_ccb->ccb_h.flags &= ~CAM_TAG_ACTION_VALID;
3360 		}
3361 
3362 		KASSERT(device == work_ccb->ccb_h.path->device,
3363 		    ("device (%p) / path->device (%p) mismatch",
3364 			device, work_ccb->ccb_h.path->device));
3365 		proto = xpt_proto_find(device->protocol);
3366 		if (proto && proto->ops->debug_out)
3367 			proto->ops->debug_out(work_ccb);
3368 
3369 		/*
3370 		 * Device queues can be shared among multiple SIM instances
3371 		 * that reside on different buses.  Use the SIM from the
3372 		 * queued device, rather than the one from the calling bus.
3373 		 */
3374 		sim = device->sim;
3375 		lock = (mtx_owned(sim->mtx) == 0);
3376 		if (lock)
3377 			CAM_SIM_LOCK(sim);
3378 		work_ccb->ccb_h.qos.sim_data = sbinuptime(); // xxx uintprt_t too small 32bit platforms
3379 		(*(sim->sim_action))(sim, work_ccb);
3380 		if (lock)
3381 			CAM_SIM_UNLOCK(sim);
3382 		mtx_lock(&devq->send_mtx);
3383 	}
3384 	devq->send_queue.qfrozen_cnt--;
3385 }
3386 
3387 /*
3388  * This function merges stuff from the slave ccb into the master ccb, while
3389  * keeping important fields in the master ccb constant.
3390  */
3391 void
3392 xpt_merge_ccb(union ccb *master_ccb, union ccb *slave_ccb)
3393 {
3394 
3395 	/*
3396 	 * Pull fields that are valid for peripheral drivers to set
3397 	 * into the master CCB along with the CCB "payload".
3398 	 */
3399 	master_ccb->ccb_h.retry_count = slave_ccb->ccb_h.retry_count;
3400 	master_ccb->ccb_h.func_code = slave_ccb->ccb_h.func_code;
3401 	master_ccb->ccb_h.timeout = slave_ccb->ccb_h.timeout;
3402 	master_ccb->ccb_h.flags = slave_ccb->ccb_h.flags;
3403 	bcopy(&(&slave_ccb->ccb_h)[1], &(&master_ccb->ccb_h)[1],
3404 	      sizeof(union ccb) - sizeof(struct ccb_hdr));
3405 }
3406 
3407 void
3408 xpt_setup_ccb_flags(struct ccb_hdr *ccb_h, struct cam_path *path,
3409 		    u_int32_t priority, u_int32_t flags)
3410 {
3411 
3412 	CAM_DEBUG(path, CAM_DEBUG_TRACE, ("xpt_setup_ccb\n"));
3413 	ccb_h->pinfo.priority = priority;
3414 	ccb_h->path = path;
3415 	ccb_h->path_id = path->bus->path_id;
3416 	if (path->target)
3417 		ccb_h->target_id = path->target->target_id;
3418 	else
3419 		ccb_h->target_id = CAM_TARGET_WILDCARD;
3420 	if (path->device) {
3421 		ccb_h->target_lun = path->device->lun_id;
3422 		ccb_h->pinfo.generation = ++path->device->ccbq.queue.generation;
3423 	} else {
3424 		ccb_h->target_lun = CAM_TARGET_WILDCARD;
3425 	}
3426 	ccb_h->pinfo.index = CAM_UNQUEUED_INDEX;
3427 	ccb_h->flags = flags;
3428 	ccb_h->xflags = 0;
3429 }
3430 
3431 void
3432 xpt_setup_ccb(struct ccb_hdr *ccb_h, struct cam_path *path, u_int32_t priority)
3433 {
3434 	xpt_setup_ccb_flags(ccb_h, path, priority, /*flags*/ 0);
3435 }
3436 
3437 /* Path manipulation functions */
3438 cam_status
3439 xpt_create_path(struct cam_path **new_path_ptr, struct cam_periph *perph,
3440 		path_id_t path_id, target_id_t target_id, lun_id_t lun_id)
3441 {
3442 	struct	   cam_path *path;
3443 	cam_status status;
3444 
3445 	path = (struct cam_path *)malloc(sizeof(*path), M_CAMPATH, M_NOWAIT);
3446 
3447 	if (path == NULL) {
3448 		status = CAM_RESRC_UNAVAIL;
3449 		return(status);
3450 	}
3451 	status = xpt_compile_path(path, perph, path_id, target_id, lun_id);
3452 	if (status != CAM_REQ_CMP) {
3453 		free(path, M_CAMPATH);
3454 		path = NULL;
3455 	}
3456 	*new_path_ptr = path;
3457 	return (status);
3458 }
3459 
3460 cam_status
3461 xpt_create_path_unlocked(struct cam_path **new_path_ptr,
3462 			 struct cam_periph *periph, path_id_t path_id,
3463 			 target_id_t target_id, lun_id_t lun_id)
3464 {
3465 
3466 	return (xpt_create_path(new_path_ptr, periph, path_id, target_id,
3467 	    lun_id));
3468 }
3469 
3470 cam_status
3471 xpt_compile_path(struct cam_path *new_path, struct cam_periph *perph,
3472 		 path_id_t path_id, target_id_t target_id, lun_id_t lun_id)
3473 {
3474 	struct	     cam_eb *bus;
3475 	struct	     cam_et *target;
3476 	struct	     cam_ed *device;
3477 	cam_status   status;
3478 
3479 	status = CAM_REQ_CMP;	/* Completed without error */
3480 	target = NULL;		/* Wildcarded */
3481 	device = NULL;		/* Wildcarded */
3482 
3483 	/*
3484 	 * We will potentially modify the EDT, so block interrupts
3485 	 * that may attempt to create cam paths.
3486 	 */
3487 	bus = xpt_find_bus(path_id);
3488 	if (bus == NULL) {
3489 		status = CAM_PATH_INVALID;
3490 	} else {
3491 		xpt_lock_buses();
3492 		mtx_lock(&bus->eb_mtx);
3493 		target = xpt_find_target(bus, target_id);
3494 		if (target == NULL) {
3495 			/* Create one */
3496 			struct cam_et *new_target;
3497 
3498 			new_target = xpt_alloc_target(bus, target_id);
3499 			if (new_target == NULL) {
3500 				status = CAM_RESRC_UNAVAIL;
3501 			} else {
3502 				target = new_target;
3503 			}
3504 		}
3505 		xpt_unlock_buses();
3506 		if (target != NULL) {
3507 			device = xpt_find_device(target, lun_id);
3508 			if (device == NULL) {
3509 				/* Create one */
3510 				struct cam_ed *new_device;
3511 
3512 				new_device =
3513 				    (*(bus->xport->ops->alloc_device))(bus,
3514 								       target,
3515 								       lun_id);
3516 				if (new_device == NULL) {
3517 					status = CAM_RESRC_UNAVAIL;
3518 				} else {
3519 					device = new_device;
3520 				}
3521 			}
3522 		}
3523 		mtx_unlock(&bus->eb_mtx);
3524 	}
3525 
3526 	/*
3527 	 * Only touch the user's data if we are successful.
3528 	 */
3529 	if (status == CAM_REQ_CMP) {
3530 		new_path->periph = perph;
3531 		new_path->bus = bus;
3532 		new_path->target = target;
3533 		new_path->device = device;
3534 		CAM_DEBUG(new_path, CAM_DEBUG_TRACE, ("xpt_compile_path\n"));
3535 	} else {
3536 		if (device != NULL)
3537 			xpt_release_device(device);
3538 		if (target != NULL)
3539 			xpt_release_target(target);
3540 		if (bus != NULL)
3541 			xpt_release_bus(bus);
3542 	}
3543 	return (status);
3544 }
3545 
3546 cam_status
3547 xpt_clone_path(struct cam_path **new_path_ptr, struct cam_path *path)
3548 {
3549 	struct	   cam_path *new_path;
3550 
3551 	new_path = (struct cam_path *)malloc(sizeof(*path), M_CAMPATH, M_NOWAIT);
3552 	if (new_path == NULL)
3553 		return(CAM_RESRC_UNAVAIL);
3554 	xpt_copy_path(new_path, path);
3555 	*new_path_ptr = new_path;
3556 	return (CAM_REQ_CMP);
3557 }
3558 
3559 void
3560 xpt_copy_path(struct cam_path *new_path, struct cam_path *path)
3561 {
3562 
3563 	*new_path = *path;
3564 	if (path->bus != NULL)
3565 		xpt_acquire_bus(path->bus);
3566 	if (path->target != NULL)
3567 		xpt_acquire_target(path->target);
3568 	if (path->device != NULL)
3569 		xpt_acquire_device(path->device);
3570 }
3571 
3572 void
3573 xpt_release_path(struct cam_path *path)
3574 {
3575 	CAM_DEBUG(path, CAM_DEBUG_TRACE, ("xpt_release_path\n"));
3576 	if (path->device != NULL) {
3577 		xpt_release_device(path->device);
3578 		path->device = NULL;
3579 	}
3580 	if (path->target != NULL) {
3581 		xpt_release_target(path->target);
3582 		path->target = NULL;
3583 	}
3584 	if (path->bus != NULL) {
3585 		xpt_release_bus(path->bus);
3586 		path->bus = NULL;
3587 	}
3588 }
3589 
3590 void
3591 xpt_free_path(struct cam_path *path)
3592 {
3593 
3594 	CAM_DEBUG(path, CAM_DEBUG_TRACE, ("xpt_free_path\n"));
3595 	xpt_release_path(path);
3596 	free(path, M_CAMPATH);
3597 }
3598 
3599 void
3600 xpt_path_counts(struct cam_path *path, uint32_t *bus_ref,
3601     uint32_t *periph_ref, uint32_t *target_ref, uint32_t *device_ref)
3602 {
3603 
3604 	xpt_lock_buses();
3605 	if (bus_ref) {
3606 		if (path->bus)
3607 			*bus_ref = path->bus->refcount;
3608 		else
3609 			*bus_ref = 0;
3610 	}
3611 	if (periph_ref) {
3612 		if (path->periph)
3613 			*periph_ref = path->periph->refcount;
3614 		else
3615 			*periph_ref = 0;
3616 	}
3617 	xpt_unlock_buses();
3618 	if (target_ref) {
3619 		if (path->target)
3620 			*target_ref = path->target->refcount;
3621 		else
3622 			*target_ref = 0;
3623 	}
3624 	if (device_ref) {
3625 		if (path->device)
3626 			*device_ref = path->device->refcount;
3627 		else
3628 			*device_ref = 0;
3629 	}
3630 }
3631 
3632 /*
3633  * Return -1 for failure, 0 for exact match, 1 for match with wildcards
3634  * in path1, 2 for match with wildcards in path2.
3635  */
3636 int
3637 xpt_path_comp(struct cam_path *path1, struct cam_path *path2)
3638 {
3639 	int retval = 0;
3640 
3641 	if (path1->bus != path2->bus) {
3642 		if (path1->bus->path_id == CAM_BUS_WILDCARD)
3643 			retval = 1;
3644 		else if (path2->bus->path_id == CAM_BUS_WILDCARD)
3645 			retval = 2;
3646 		else
3647 			return (-1);
3648 	}
3649 	if (path1->target != path2->target) {
3650 		if (path1->target->target_id == CAM_TARGET_WILDCARD) {
3651 			if (retval == 0)
3652 				retval = 1;
3653 		} else if (path2->target->target_id == CAM_TARGET_WILDCARD)
3654 			retval = 2;
3655 		else
3656 			return (-1);
3657 	}
3658 	if (path1->device != path2->device) {
3659 		if (path1->device->lun_id == CAM_LUN_WILDCARD) {
3660 			if (retval == 0)
3661 				retval = 1;
3662 		} else if (path2->device->lun_id == CAM_LUN_WILDCARD)
3663 			retval = 2;
3664 		else
3665 			return (-1);
3666 	}
3667 	return (retval);
3668 }
3669 
3670 int
3671 xpt_path_comp_dev(struct cam_path *path, struct cam_ed *dev)
3672 {
3673 	int retval = 0;
3674 
3675 	if (path->bus != dev->target->bus) {
3676 		if (path->bus->path_id == CAM_BUS_WILDCARD)
3677 			retval = 1;
3678 		else if (dev->target->bus->path_id == CAM_BUS_WILDCARD)
3679 			retval = 2;
3680 		else
3681 			return (-1);
3682 	}
3683 	if (path->target != dev->target) {
3684 		if (path->target->target_id == CAM_TARGET_WILDCARD) {
3685 			if (retval == 0)
3686 				retval = 1;
3687 		} else if (dev->target->target_id == CAM_TARGET_WILDCARD)
3688 			retval = 2;
3689 		else
3690 			return (-1);
3691 	}
3692 	if (path->device != dev) {
3693 		if (path->device->lun_id == CAM_LUN_WILDCARD) {
3694 			if (retval == 0)
3695 				retval = 1;
3696 		} else if (dev->lun_id == CAM_LUN_WILDCARD)
3697 			retval = 2;
3698 		else
3699 			return (-1);
3700 	}
3701 	return (retval);
3702 }
3703 
3704 void
3705 xpt_print_path(struct cam_path *path)
3706 {
3707 	struct sbuf sb;
3708 	char buffer[XPT_PRINT_LEN];
3709 
3710 	sbuf_new(&sb, buffer, XPT_PRINT_LEN, SBUF_FIXEDLEN);
3711 	xpt_path_sbuf(path, &sb);
3712 	sbuf_finish(&sb);
3713 	printf("%s", sbuf_data(&sb));
3714 	sbuf_delete(&sb);
3715 }
3716 
3717 void
3718 xpt_print_device(struct cam_ed *device)
3719 {
3720 
3721 	if (device == NULL)
3722 		printf("(nopath): ");
3723 	else {
3724 		printf("(noperiph:%s%d:%d:%d:%jx): ", device->sim->sim_name,
3725 		       device->sim->unit_number,
3726 		       device->sim->bus_id,
3727 		       device->target->target_id,
3728 		       (uintmax_t)device->lun_id);
3729 	}
3730 }
3731 
3732 void
3733 xpt_print(struct cam_path *path, const char *fmt, ...)
3734 {
3735 	va_list ap;
3736 	struct sbuf sb;
3737 	char buffer[XPT_PRINT_LEN];
3738 
3739 	sbuf_new(&sb, buffer, XPT_PRINT_LEN, SBUF_FIXEDLEN);
3740 
3741 	xpt_path_sbuf(path, &sb);
3742 	va_start(ap, fmt);
3743 	sbuf_vprintf(&sb, fmt, ap);
3744 	va_end(ap);
3745 
3746 	sbuf_finish(&sb);
3747 	printf("%s", sbuf_data(&sb));
3748 	sbuf_delete(&sb);
3749 }
3750 
3751 int
3752 xpt_path_string(struct cam_path *path, char *str, size_t str_len)
3753 {
3754 	struct sbuf sb;
3755 	int len;
3756 
3757 	sbuf_new(&sb, str, str_len, 0);
3758 	len = xpt_path_sbuf(path, &sb);
3759 	sbuf_finish(&sb);
3760 	return (len);
3761 }
3762 
3763 int
3764 xpt_path_sbuf(struct cam_path *path, struct sbuf *sb)
3765 {
3766 
3767 	if (path == NULL)
3768 		sbuf_printf(sb, "(nopath): ");
3769 	else {
3770 		if (path->periph != NULL)
3771 			sbuf_printf(sb, "(%s%d:", path->periph->periph_name,
3772 				    path->periph->unit_number);
3773 		else
3774 			sbuf_printf(sb, "(noperiph:");
3775 
3776 		if (path->bus != NULL)
3777 			sbuf_printf(sb, "%s%d:%d:", path->bus->sim->sim_name,
3778 				    path->bus->sim->unit_number,
3779 				    path->bus->sim->bus_id);
3780 		else
3781 			sbuf_printf(sb, "nobus:");
3782 
3783 		if (path->target != NULL)
3784 			sbuf_printf(sb, "%d:", path->target->target_id);
3785 		else
3786 			sbuf_printf(sb, "X:");
3787 
3788 		if (path->device != NULL)
3789 			sbuf_printf(sb, "%jx): ",
3790 			    (uintmax_t)path->device->lun_id);
3791 		else
3792 			sbuf_printf(sb, "X): ");
3793 	}
3794 
3795 	return(sbuf_len(sb));
3796 }
3797 
3798 path_id_t
3799 xpt_path_path_id(struct cam_path *path)
3800 {
3801 	return(path->bus->path_id);
3802 }
3803 
3804 target_id_t
3805 xpt_path_target_id(struct cam_path *path)
3806 {
3807 	if (path->target != NULL)
3808 		return (path->target->target_id);
3809 	else
3810 		return (CAM_TARGET_WILDCARD);
3811 }
3812 
3813 lun_id_t
3814 xpt_path_lun_id(struct cam_path *path)
3815 {
3816 	if (path->device != NULL)
3817 		return (path->device->lun_id);
3818 	else
3819 		return (CAM_LUN_WILDCARD);
3820 }
3821 
3822 struct cam_sim *
3823 xpt_path_sim(struct cam_path *path)
3824 {
3825 
3826 	return (path->bus->sim);
3827 }
3828 
3829 struct cam_periph*
3830 xpt_path_periph(struct cam_path *path)
3831 {
3832 
3833 	return (path->periph);
3834 }
3835 
3836 /*
3837  * Release a CAM control block for the caller.  Remit the cost of the structure
3838  * to the device referenced by the path.  If the this device had no 'credits'
3839  * and peripheral drivers have registered async callbacks for this notification
3840  * call them now.
3841  */
3842 void
3843 xpt_release_ccb(union ccb *free_ccb)
3844 {
3845 	struct	 cam_ed *device;
3846 	struct	 cam_periph *periph;
3847 
3848 	CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_release_ccb\n"));
3849 	xpt_path_assert(free_ccb->ccb_h.path, MA_OWNED);
3850 	device = free_ccb->ccb_h.path->device;
3851 	periph = free_ccb->ccb_h.path->periph;
3852 
3853 	xpt_free_ccb(free_ccb);
3854 	periph->periph_allocated--;
3855 	cam_ccbq_release_opening(&device->ccbq);
3856 	xpt_run_allocq(periph, 0);
3857 }
3858 
3859 /* Functions accessed by SIM drivers */
3860 
3861 static struct xpt_xport_ops xport_default_ops = {
3862 	.alloc_device = xpt_alloc_device_default,
3863 	.action = xpt_action_default,
3864 	.async = xpt_dev_async_default,
3865 };
3866 static struct xpt_xport xport_default = {
3867 	.xport = XPORT_UNKNOWN,
3868 	.name = "unknown",
3869 	.ops = &xport_default_ops,
3870 };
3871 
3872 CAM_XPT_XPORT(xport_default);
3873 
3874 /*
3875  * A sim structure, listing the SIM entry points and instance
3876  * identification info is passed to xpt_bus_register to hook the SIM
3877  * into the CAM framework.  xpt_bus_register creates a cam_eb entry
3878  * for this new bus and places it in the array of buses and assigns
3879  * it a path_id.  The path_id may be influenced by "hard wiring"
3880  * information specified by the user.  Once interrupt services are
3881  * available, the bus will be probed.
3882  */
3883 int32_t
3884 xpt_bus_register(struct cam_sim *sim, device_t parent, u_int32_t bus)
3885 {
3886 	struct cam_eb *new_bus;
3887 	struct cam_eb *old_bus;
3888 	struct ccb_pathinq cpi;
3889 	struct cam_path *path;
3890 	cam_status status;
3891 
3892 	mtx_assert(sim->mtx, MA_OWNED);
3893 
3894 	sim->bus_id = bus;
3895 	new_bus = (struct cam_eb *)malloc(sizeof(*new_bus),
3896 					  M_CAMXPT, M_NOWAIT|M_ZERO);
3897 	if (new_bus == NULL) {
3898 		/* Couldn't satisfy request */
3899 		return (CAM_RESRC_UNAVAIL);
3900 	}
3901 
3902 	mtx_init(&new_bus->eb_mtx, "CAM bus lock", NULL, MTX_DEF);
3903 	TAILQ_INIT(&new_bus->et_entries);
3904 	cam_sim_hold(sim);
3905 	new_bus->sim = sim;
3906 	timevalclear(&new_bus->last_reset);
3907 	new_bus->flags = 0;
3908 	new_bus->refcount = 1;	/* Held until a bus_deregister event */
3909 	new_bus->generation = 0;
3910 
3911 	xpt_lock_buses();
3912 	sim->path_id = new_bus->path_id =
3913 	    xptpathid(sim->sim_name, sim->unit_number, sim->bus_id);
3914 	old_bus = TAILQ_FIRST(&xsoftc.xpt_busses);
3915 	while (old_bus != NULL
3916 	    && old_bus->path_id < new_bus->path_id)
3917 		old_bus = TAILQ_NEXT(old_bus, links);
3918 	if (old_bus != NULL)
3919 		TAILQ_INSERT_BEFORE(old_bus, new_bus, links);
3920 	else
3921 		TAILQ_INSERT_TAIL(&xsoftc.xpt_busses, new_bus, links);
3922 	xsoftc.bus_generation++;
3923 	xpt_unlock_buses();
3924 
3925 	/*
3926 	 * Set a default transport so that a PATH_INQ can be issued to
3927 	 * the SIM.  This will then allow for probing and attaching of
3928 	 * a more appropriate transport.
3929 	 */
3930 	new_bus->xport = &xport_default;
3931 
3932 	status = xpt_create_path(&path, /*periph*/NULL, sim->path_id,
3933 				  CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
3934 	if (status != CAM_REQ_CMP) {
3935 		xpt_release_bus(new_bus);
3936 		free(path, M_CAMXPT);
3937 		return (CAM_RESRC_UNAVAIL);
3938 	}
3939 
3940 	xpt_setup_ccb(&cpi.ccb_h, path, CAM_PRIORITY_NORMAL);
3941 	cpi.ccb_h.func_code = XPT_PATH_INQ;
3942 	xpt_action((union ccb *)&cpi);
3943 
3944 	if (cpi.ccb_h.status == CAM_REQ_CMP) {
3945 		struct xpt_xport **xpt;
3946 
3947 		SET_FOREACH(xpt, cam_xpt_xport_set) {
3948 			if ((*xpt)->xport == cpi.transport) {
3949 				new_bus->xport = *xpt;
3950 				break;
3951 			}
3952 		}
3953 		if (new_bus->xport == NULL) {
3954 			xpt_print(path,
3955 			    "No transport found for %d\n", cpi.transport);
3956 			xpt_release_bus(new_bus);
3957 			free(path, M_CAMXPT);
3958 			return (CAM_RESRC_UNAVAIL);
3959 		}
3960 	}
3961 
3962 	/* Notify interested parties */
3963 	if (sim->path_id != CAM_XPT_PATH_ID) {
3964 
3965 		xpt_async(AC_PATH_REGISTERED, path, &cpi);
3966 		if ((cpi.hba_misc & PIM_NOSCAN) == 0) {
3967 			union	ccb *scan_ccb;
3968 
3969 			/* Initiate bus rescan. */
3970 			scan_ccb = xpt_alloc_ccb_nowait();
3971 			if (scan_ccb != NULL) {
3972 				scan_ccb->ccb_h.path = path;
3973 				scan_ccb->ccb_h.func_code = XPT_SCAN_BUS;
3974 				scan_ccb->crcn.flags = 0;
3975 				xpt_rescan(scan_ccb);
3976 			} else {
3977 				xpt_print(path,
3978 					  "Can't allocate CCB to scan bus\n");
3979 				xpt_free_path(path);
3980 			}
3981 		} else
3982 			xpt_free_path(path);
3983 	} else
3984 		xpt_free_path(path);
3985 	return (CAM_SUCCESS);
3986 }
3987 
3988 int32_t
3989 xpt_bus_deregister(path_id_t pathid)
3990 {
3991 	struct cam_path bus_path;
3992 	cam_status status;
3993 
3994 	status = xpt_compile_path(&bus_path, NULL, pathid,
3995 				  CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
3996 	if (status != CAM_REQ_CMP)
3997 		return (status);
3998 
3999 	xpt_async(AC_LOST_DEVICE, &bus_path, NULL);
4000 	xpt_async(AC_PATH_DEREGISTERED, &bus_path, NULL);
4001 
4002 	/* Release the reference count held while registered. */
4003 	xpt_release_bus(bus_path.bus);
4004 	xpt_release_path(&bus_path);
4005 
4006 	return (CAM_REQ_CMP);
4007 }
4008 
4009 static path_id_t
4010 xptnextfreepathid(void)
4011 {
4012 	struct cam_eb *bus;
4013 	path_id_t pathid;
4014 	const char *strval;
4015 
4016 	mtx_assert(&xsoftc.xpt_topo_lock, MA_OWNED);
4017 	pathid = 0;
4018 	bus = TAILQ_FIRST(&xsoftc.xpt_busses);
4019 retry:
4020 	/* Find an unoccupied pathid */
4021 	while (bus != NULL && bus->path_id <= pathid) {
4022 		if (bus->path_id == pathid)
4023 			pathid++;
4024 		bus = TAILQ_NEXT(bus, links);
4025 	}
4026 
4027 	/*
4028 	 * Ensure that this pathid is not reserved for
4029 	 * a bus that may be registered in the future.
4030 	 */
4031 	if (resource_string_value("scbus", pathid, "at", &strval) == 0) {
4032 		++pathid;
4033 		/* Start the search over */
4034 		goto retry;
4035 	}
4036 	return (pathid);
4037 }
4038 
4039 static path_id_t
4040 xptpathid(const char *sim_name, int sim_unit, int sim_bus)
4041 {
4042 	path_id_t pathid;
4043 	int i, dunit, val;
4044 	char buf[32];
4045 	const char *dname;
4046 
4047 	pathid = CAM_XPT_PATH_ID;
4048 	snprintf(buf, sizeof(buf), "%s%d", sim_name, sim_unit);
4049 	if (strcmp(buf, "xpt0") == 0 && sim_bus == 0)
4050 		return (pathid);
4051 	i = 0;
4052 	while ((resource_find_match(&i, &dname, &dunit, "at", buf)) == 0) {
4053 		if (strcmp(dname, "scbus")) {
4054 			/* Avoid a bit of foot shooting. */
4055 			continue;
4056 		}
4057 		if (dunit < 0)		/* unwired?! */
4058 			continue;
4059 		if (resource_int_value("scbus", dunit, "bus", &val) == 0) {
4060 			if (sim_bus == val) {
4061 				pathid = dunit;
4062 				break;
4063 			}
4064 		} else if (sim_bus == 0) {
4065 			/* Unspecified matches bus 0 */
4066 			pathid = dunit;
4067 			break;
4068 		} else {
4069 			printf("Ambiguous scbus configuration for %s%d "
4070 			       "bus %d, cannot wire down.  The kernel "
4071 			       "config entry for scbus%d should "
4072 			       "specify a controller bus.\n"
4073 			       "Scbus will be assigned dynamically.\n",
4074 			       sim_name, sim_unit, sim_bus, dunit);
4075 			break;
4076 		}
4077 	}
4078 
4079 	if (pathid == CAM_XPT_PATH_ID)
4080 		pathid = xptnextfreepathid();
4081 	return (pathid);
4082 }
4083 
4084 static const char *
4085 xpt_async_string(u_int32_t async_code)
4086 {
4087 
4088 	switch (async_code) {
4089 	case AC_BUS_RESET: return ("AC_BUS_RESET");
4090 	case AC_UNSOL_RESEL: return ("AC_UNSOL_RESEL");
4091 	case AC_SCSI_AEN: return ("AC_SCSI_AEN");
4092 	case AC_SENT_BDR: return ("AC_SENT_BDR");
4093 	case AC_PATH_REGISTERED: return ("AC_PATH_REGISTERED");
4094 	case AC_PATH_DEREGISTERED: return ("AC_PATH_DEREGISTERED");
4095 	case AC_FOUND_DEVICE: return ("AC_FOUND_DEVICE");
4096 	case AC_LOST_DEVICE: return ("AC_LOST_DEVICE");
4097 	case AC_TRANSFER_NEG: return ("AC_TRANSFER_NEG");
4098 	case AC_INQ_CHANGED: return ("AC_INQ_CHANGED");
4099 	case AC_GETDEV_CHANGED: return ("AC_GETDEV_CHANGED");
4100 	case AC_CONTRACT: return ("AC_CONTRACT");
4101 	case AC_ADVINFO_CHANGED: return ("AC_ADVINFO_CHANGED");
4102 	case AC_UNIT_ATTENTION: return ("AC_UNIT_ATTENTION");
4103 	}
4104 	return ("AC_UNKNOWN");
4105 }
4106 
4107 static int
4108 xpt_async_size(u_int32_t async_code)
4109 {
4110 
4111 	switch (async_code) {
4112 	case AC_BUS_RESET: return (0);
4113 	case AC_UNSOL_RESEL: return (0);
4114 	case AC_SCSI_AEN: return (0);
4115 	case AC_SENT_BDR: return (0);
4116 	case AC_PATH_REGISTERED: return (sizeof(struct ccb_pathinq));
4117 	case AC_PATH_DEREGISTERED: return (0);
4118 	case AC_FOUND_DEVICE: return (sizeof(struct ccb_getdev));
4119 	case AC_LOST_DEVICE: return (0);
4120 	case AC_TRANSFER_NEG: return (sizeof(struct ccb_trans_settings));
4121 	case AC_INQ_CHANGED: return (0);
4122 	case AC_GETDEV_CHANGED: return (0);
4123 	case AC_CONTRACT: return (sizeof(struct ac_contract));
4124 	case AC_ADVINFO_CHANGED: return (-1);
4125 	case AC_UNIT_ATTENTION: return (sizeof(struct ccb_scsiio));
4126 	}
4127 	return (0);
4128 }
4129 
4130 static int
4131 xpt_async_process_dev(struct cam_ed *device, void *arg)
4132 {
4133 	union ccb *ccb = arg;
4134 	struct cam_path *path = ccb->ccb_h.path;
4135 	void *async_arg = ccb->casync.async_arg_ptr;
4136 	u_int32_t async_code = ccb->casync.async_code;
4137 	int relock;
4138 
4139 	if (path->device != device
4140 	 && path->device->lun_id != CAM_LUN_WILDCARD
4141 	 && device->lun_id != CAM_LUN_WILDCARD)
4142 		return (1);
4143 
4144 	/*
4145 	 * The async callback could free the device.
4146 	 * If it is a broadcast async, it doesn't hold
4147 	 * device reference, so take our own reference.
4148 	 */
4149 	xpt_acquire_device(device);
4150 
4151 	/*
4152 	 * If async for specific device is to be delivered to
4153 	 * the wildcard client, take the specific device lock.
4154 	 * XXX: We may need a way for client to specify it.
4155 	 */
4156 	if ((device->lun_id == CAM_LUN_WILDCARD &&
4157 	     path->device->lun_id != CAM_LUN_WILDCARD) ||
4158 	    (device->target->target_id == CAM_TARGET_WILDCARD &&
4159 	     path->target->target_id != CAM_TARGET_WILDCARD) ||
4160 	    (device->target->bus->path_id == CAM_BUS_WILDCARD &&
4161 	     path->target->bus->path_id != CAM_BUS_WILDCARD)) {
4162 		mtx_unlock(&device->device_mtx);
4163 		xpt_path_lock(path);
4164 		relock = 1;
4165 	} else
4166 		relock = 0;
4167 
4168 	(*(device->target->bus->xport->ops->async))(async_code,
4169 	    device->target->bus, device->target, device, async_arg);
4170 	xpt_async_bcast(&device->asyncs, async_code, path, async_arg);
4171 
4172 	if (relock) {
4173 		xpt_path_unlock(path);
4174 		mtx_lock(&device->device_mtx);
4175 	}
4176 	xpt_release_device(device);
4177 	return (1);
4178 }
4179 
4180 static int
4181 xpt_async_process_tgt(struct cam_et *target, void *arg)
4182 {
4183 	union ccb *ccb = arg;
4184 	struct cam_path *path = ccb->ccb_h.path;
4185 
4186 	if (path->target != target
4187 	 && path->target->target_id != CAM_TARGET_WILDCARD
4188 	 && target->target_id != CAM_TARGET_WILDCARD)
4189 		return (1);
4190 
4191 	if (ccb->casync.async_code == AC_SENT_BDR) {
4192 		/* Update our notion of when the last reset occurred */
4193 		microtime(&target->last_reset);
4194 	}
4195 
4196 	return (xptdevicetraverse(target, NULL, xpt_async_process_dev, ccb));
4197 }
4198 
4199 static void
4200 xpt_async_process(struct cam_periph *periph, union ccb *ccb)
4201 {
4202 	struct cam_eb *bus;
4203 	struct cam_path *path;
4204 	void *async_arg;
4205 	u_int32_t async_code;
4206 
4207 	path = ccb->ccb_h.path;
4208 	async_code = ccb->casync.async_code;
4209 	async_arg = ccb->casync.async_arg_ptr;
4210 	CAM_DEBUG(path, CAM_DEBUG_TRACE | CAM_DEBUG_INFO,
4211 	    ("xpt_async(%s)\n", xpt_async_string(async_code)));
4212 	bus = path->bus;
4213 
4214 	if (async_code == AC_BUS_RESET) {
4215 		/* Update our notion of when the last reset occurred */
4216 		microtime(&bus->last_reset);
4217 	}
4218 
4219 	xpttargettraverse(bus, NULL, xpt_async_process_tgt, ccb);
4220 
4221 	/*
4222 	 * If this wasn't a fully wildcarded async, tell all
4223 	 * clients that want all async events.
4224 	 */
4225 	if (bus != xpt_periph->path->bus) {
4226 		xpt_path_lock(xpt_periph->path);
4227 		xpt_async_process_dev(xpt_periph->path->device, ccb);
4228 		xpt_path_unlock(xpt_periph->path);
4229 	}
4230 
4231 	if (path->device != NULL && path->device->lun_id != CAM_LUN_WILDCARD)
4232 		xpt_release_devq(path, 1, TRUE);
4233 	else
4234 		xpt_release_simq(path->bus->sim, TRUE);
4235 	if (ccb->casync.async_arg_size > 0)
4236 		free(async_arg, M_CAMXPT);
4237 	xpt_free_path(path);
4238 	xpt_free_ccb(ccb);
4239 }
4240 
4241 static void
4242 xpt_async_bcast(struct async_list *async_head,
4243 		u_int32_t async_code,
4244 		struct cam_path *path, void *async_arg)
4245 {
4246 	struct async_node *cur_entry;
4247 	int lock;
4248 
4249 	cur_entry = SLIST_FIRST(async_head);
4250 	while (cur_entry != NULL) {
4251 		struct async_node *next_entry;
4252 		/*
4253 		 * Grab the next list entry before we call the current
4254 		 * entry's callback.  This is because the callback function
4255 		 * can delete its async callback entry.
4256 		 */
4257 		next_entry = SLIST_NEXT(cur_entry, links);
4258 		if ((cur_entry->event_enable & async_code) != 0) {
4259 			lock = cur_entry->event_lock;
4260 			if (lock)
4261 				CAM_SIM_LOCK(path->device->sim);
4262 			cur_entry->callback(cur_entry->callback_arg,
4263 					    async_code, path,
4264 					    async_arg);
4265 			if (lock)
4266 				CAM_SIM_UNLOCK(path->device->sim);
4267 		}
4268 		cur_entry = next_entry;
4269 	}
4270 }
4271 
4272 void
4273 xpt_async(u_int32_t async_code, struct cam_path *path, void *async_arg)
4274 {
4275 	union ccb *ccb;
4276 	int size;
4277 
4278 	ccb = xpt_alloc_ccb_nowait();
4279 	if (ccb == NULL) {
4280 		xpt_print(path, "Can't allocate CCB to send %s\n",
4281 		    xpt_async_string(async_code));
4282 		return;
4283 	}
4284 
4285 	if (xpt_clone_path(&ccb->ccb_h.path, path) != CAM_REQ_CMP) {
4286 		xpt_print(path, "Can't allocate path to send %s\n",
4287 		    xpt_async_string(async_code));
4288 		xpt_free_ccb(ccb);
4289 		return;
4290 	}
4291 	ccb->ccb_h.path->periph = NULL;
4292 	ccb->ccb_h.func_code = XPT_ASYNC;
4293 	ccb->ccb_h.cbfcnp = xpt_async_process;
4294 	ccb->ccb_h.flags |= CAM_UNLOCKED;
4295 	ccb->casync.async_code = async_code;
4296 	ccb->casync.async_arg_size = 0;
4297 	size = xpt_async_size(async_code);
4298 	CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_TRACE,
4299 	    ("xpt_async: func %#x %s aync_code %d %s\n",
4300 		ccb->ccb_h.func_code,
4301 		xpt_action_name(ccb->ccb_h.func_code),
4302 		async_code,
4303 		xpt_async_string(async_code)));
4304 	if (size > 0 && async_arg != NULL) {
4305 		ccb->casync.async_arg_ptr = malloc(size, M_CAMXPT, M_NOWAIT);
4306 		if (ccb->casync.async_arg_ptr == NULL) {
4307 			xpt_print(path, "Can't allocate argument to send %s\n",
4308 			    xpt_async_string(async_code));
4309 			xpt_free_path(ccb->ccb_h.path);
4310 			xpt_free_ccb(ccb);
4311 			return;
4312 		}
4313 		memcpy(ccb->casync.async_arg_ptr, async_arg, size);
4314 		ccb->casync.async_arg_size = size;
4315 	} else if (size < 0) {
4316 		ccb->casync.async_arg_ptr = async_arg;
4317 		ccb->casync.async_arg_size = size;
4318 	}
4319 	if (path->device != NULL && path->device->lun_id != CAM_LUN_WILDCARD)
4320 		xpt_freeze_devq(path, 1);
4321 	else
4322 		xpt_freeze_simq(path->bus->sim, 1);
4323 	xpt_done(ccb);
4324 }
4325 
4326 static void
4327 xpt_dev_async_default(u_int32_t async_code, struct cam_eb *bus,
4328 		      struct cam_et *target, struct cam_ed *device,
4329 		      void *async_arg)
4330 {
4331 
4332 	/*
4333 	 * We only need to handle events for real devices.
4334 	 */
4335 	if (target->target_id == CAM_TARGET_WILDCARD
4336 	 || device->lun_id == CAM_LUN_WILDCARD)
4337 		return;
4338 
4339 	printf("%s called\n", __func__);
4340 }
4341 
4342 static uint32_t
4343 xpt_freeze_devq_device(struct cam_ed *dev, u_int count)
4344 {
4345 	struct cam_devq	*devq;
4346 	uint32_t freeze;
4347 
4348 	devq = dev->sim->devq;
4349 	mtx_assert(&devq->send_mtx, MA_OWNED);
4350 	CAM_DEBUG_DEV(dev, CAM_DEBUG_TRACE,
4351 	    ("xpt_freeze_devq_device(%d) %u->%u\n", count,
4352 	    dev->ccbq.queue.qfrozen_cnt, dev->ccbq.queue.qfrozen_cnt + count));
4353 	freeze = (dev->ccbq.queue.qfrozen_cnt += count);
4354 	/* Remove frozen device from sendq. */
4355 	if (device_is_queued(dev))
4356 		camq_remove(&devq->send_queue, dev->devq_entry.index);
4357 	return (freeze);
4358 }
4359 
4360 u_int32_t
4361 xpt_freeze_devq(struct cam_path *path, u_int count)
4362 {
4363 	struct cam_ed	*dev = path->device;
4364 	struct cam_devq	*devq;
4365 	uint32_t	 freeze;
4366 
4367 	devq = dev->sim->devq;
4368 	mtx_lock(&devq->send_mtx);
4369 	CAM_DEBUG(path, CAM_DEBUG_TRACE, ("xpt_freeze_devq(%d)\n", count));
4370 	freeze = xpt_freeze_devq_device(dev, count);
4371 	mtx_unlock(&devq->send_mtx);
4372 	return (freeze);
4373 }
4374 
4375 u_int32_t
4376 xpt_freeze_simq(struct cam_sim *sim, u_int count)
4377 {
4378 	struct cam_devq	*devq;
4379 	uint32_t	 freeze;
4380 
4381 	devq = sim->devq;
4382 	mtx_lock(&devq->send_mtx);
4383 	freeze = (devq->send_queue.qfrozen_cnt += count);
4384 	mtx_unlock(&devq->send_mtx);
4385 	return (freeze);
4386 }
4387 
4388 static void
4389 xpt_release_devq_timeout(void *arg)
4390 {
4391 	struct cam_ed *dev;
4392 	struct cam_devq *devq;
4393 
4394 	dev = (struct cam_ed *)arg;
4395 	CAM_DEBUG_DEV(dev, CAM_DEBUG_TRACE, ("xpt_release_devq_timeout\n"));
4396 	devq = dev->sim->devq;
4397 	mtx_assert(&devq->send_mtx, MA_OWNED);
4398 	if (xpt_release_devq_device(dev, /*count*/1, /*run_queue*/TRUE))
4399 		xpt_run_devq(devq);
4400 }
4401 
4402 void
4403 xpt_release_devq(struct cam_path *path, u_int count, int run_queue)
4404 {
4405 	struct cam_ed *dev;
4406 	struct cam_devq *devq;
4407 
4408 	CAM_DEBUG(path, CAM_DEBUG_TRACE, ("xpt_release_devq(%d, %d)\n",
4409 	    count, run_queue));
4410 	dev = path->device;
4411 	devq = dev->sim->devq;
4412 	mtx_lock(&devq->send_mtx);
4413 	if (xpt_release_devq_device(dev, count, run_queue))
4414 		xpt_run_devq(dev->sim->devq);
4415 	mtx_unlock(&devq->send_mtx);
4416 }
4417 
4418 static int
4419 xpt_release_devq_device(struct cam_ed *dev, u_int count, int run_queue)
4420 {
4421 
4422 	mtx_assert(&dev->sim->devq->send_mtx, MA_OWNED);
4423 	CAM_DEBUG_DEV(dev, CAM_DEBUG_TRACE,
4424 	    ("xpt_release_devq_device(%d, %d) %u->%u\n", count, run_queue,
4425 	    dev->ccbq.queue.qfrozen_cnt, dev->ccbq.queue.qfrozen_cnt - count));
4426 	if (count > dev->ccbq.queue.qfrozen_cnt) {
4427 #ifdef INVARIANTS
4428 		printf("xpt_release_devq(): requested %u > present %u\n",
4429 		    count, dev->ccbq.queue.qfrozen_cnt);
4430 #endif
4431 		count = dev->ccbq.queue.qfrozen_cnt;
4432 	}
4433 	dev->ccbq.queue.qfrozen_cnt -= count;
4434 	if (dev->ccbq.queue.qfrozen_cnt == 0) {
4435 		/*
4436 		 * No longer need to wait for a successful
4437 		 * command completion.
4438 		 */
4439 		dev->flags &= ~CAM_DEV_REL_ON_COMPLETE;
4440 		/*
4441 		 * Remove any timeouts that might be scheduled
4442 		 * to release this queue.
4443 		 */
4444 		if ((dev->flags & CAM_DEV_REL_TIMEOUT_PENDING) != 0) {
4445 			callout_stop(&dev->callout);
4446 			dev->flags &= ~CAM_DEV_REL_TIMEOUT_PENDING;
4447 		}
4448 		/*
4449 		 * Now that we are unfrozen schedule the
4450 		 * device so any pending transactions are
4451 		 * run.
4452 		 */
4453 		xpt_schedule_devq(dev->sim->devq, dev);
4454 	} else
4455 		run_queue = 0;
4456 	return (run_queue);
4457 }
4458 
4459 void
4460 xpt_release_simq(struct cam_sim *sim, int run_queue)
4461 {
4462 	struct cam_devq	*devq;
4463 
4464 	devq = sim->devq;
4465 	mtx_lock(&devq->send_mtx);
4466 	if (devq->send_queue.qfrozen_cnt <= 0) {
4467 #ifdef INVARIANTS
4468 		printf("xpt_release_simq: requested 1 > present %u\n",
4469 		    devq->send_queue.qfrozen_cnt);
4470 #endif
4471 	} else
4472 		devq->send_queue.qfrozen_cnt--;
4473 	if (devq->send_queue.qfrozen_cnt == 0) {
4474 		/*
4475 		 * If there is a timeout scheduled to release this
4476 		 * sim queue, remove it.  The queue frozen count is
4477 		 * already at 0.
4478 		 */
4479 		if ((sim->flags & CAM_SIM_REL_TIMEOUT_PENDING) != 0){
4480 			callout_stop(&sim->callout);
4481 			sim->flags &= ~CAM_SIM_REL_TIMEOUT_PENDING;
4482 		}
4483 		if (run_queue) {
4484 			/*
4485 			 * Now that we are unfrozen run the send queue.
4486 			 */
4487 			xpt_run_devq(sim->devq);
4488 		}
4489 	}
4490 	mtx_unlock(&devq->send_mtx);
4491 }
4492 
4493 /*
4494  * XXX Appears to be unused.
4495  */
4496 static void
4497 xpt_release_simq_timeout(void *arg)
4498 {
4499 	struct cam_sim *sim;
4500 
4501 	sim = (struct cam_sim *)arg;
4502 	xpt_release_simq(sim, /* run_queue */ TRUE);
4503 }
4504 
4505 void
4506 xpt_done(union ccb *done_ccb)
4507 {
4508 	struct cam_doneq *queue;
4509 	int	run, hash;
4510 
4511 #if defined(BUF_TRACKING) || defined(FULL_BUF_TRACKING)
4512 	if (done_ccb->ccb_h.func_code == XPT_SCSI_IO &&
4513 	    done_ccb->csio.bio != NULL)
4514 		biotrack(done_ccb->csio.bio, __func__);
4515 #endif
4516 
4517 	CAM_DEBUG(done_ccb->ccb_h.path, CAM_DEBUG_TRACE,
4518 	    ("xpt_done: func= %#x %s status %#x\n",
4519 		done_ccb->ccb_h.func_code,
4520 		xpt_action_name(done_ccb->ccb_h.func_code),
4521 		done_ccb->ccb_h.status));
4522 	if ((done_ccb->ccb_h.func_code & XPT_FC_QUEUED) == 0)
4523 		return;
4524 
4525 	/* Store the time the ccb was in the sim */
4526 	done_ccb->ccb_h.qos.sim_data = sbinuptime() - done_ccb->ccb_h.qos.sim_data;
4527 	hash = (done_ccb->ccb_h.path_id + done_ccb->ccb_h.target_id +
4528 	    done_ccb->ccb_h.target_lun) % cam_num_doneqs;
4529 	queue = &cam_doneqs[hash];
4530 	mtx_lock(&queue->cam_doneq_mtx);
4531 	run = (queue->cam_doneq_sleep && STAILQ_EMPTY(&queue->cam_doneq));
4532 	STAILQ_INSERT_TAIL(&queue->cam_doneq, &done_ccb->ccb_h, sim_links.stqe);
4533 	done_ccb->ccb_h.pinfo.index = CAM_DONEQ_INDEX;
4534 	mtx_unlock(&queue->cam_doneq_mtx);
4535 	if (run)
4536 		wakeup(&queue->cam_doneq);
4537 }
4538 
4539 void
4540 xpt_done_direct(union ccb *done_ccb)
4541 {
4542 
4543 	CAM_DEBUG(done_ccb->ccb_h.path, CAM_DEBUG_TRACE,
4544 	    ("xpt_done_direct: status %#x\n", done_ccb->ccb_h.status));
4545 	if ((done_ccb->ccb_h.func_code & XPT_FC_QUEUED) == 0)
4546 		return;
4547 
4548 	/* Store the time the ccb was in the sim */
4549 	done_ccb->ccb_h.qos.sim_data = sbinuptime() - done_ccb->ccb_h.qos.sim_data;
4550 	xpt_done_process(&done_ccb->ccb_h);
4551 }
4552 
4553 union ccb *
4554 xpt_alloc_ccb()
4555 {
4556 	union ccb *new_ccb;
4557 
4558 	new_ccb = malloc(sizeof(*new_ccb), M_CAMCCB, M_ZERO|M_WAITOK);
4559 	return (new_ccb);
4560 }
4561 
4562 union ccb *
4563 xpt_alloc_ccb_nowait()
4564 {
4565 	union ccb *new_ccb;
4566 
4567 	new_ccb = malloc(sizeof(*new_ccb), M_CAMCCB, M_ZERO|M_NOWAIT);
4568 	return (new_ccb);
4569 }
4570 
4571 void
4572 xpt_free_ccb(union ccb *free_ccb)
4573 {
4574 	free(free_ccb, M_CAMCCB);
4575 }
4576 
4577 
4578 
4579 /* Private XPT functions */
4580 
4581 /*
4582  * Get a CAM control block for the caller. Charge the structure to the device
4583  * referenced by the path.  If we don't have sufficient resources to allocate
4584  * more ccbs, we return NULL.
4585  */
4586 static union ccb *
4587 xpt_get_ccb_nowait(struct cam_periph *periph)
4588 {
4589 	union ccb *new_ccb;
4590 
4591 	new_ccb = malloc(sizeof(*new_ccb), M_CAMCCB, M_ZERO|M_NOWAIT);
4592 	if (new_ccb == NULL)
4593 		return (NULL);
4594 	periph->periph_allocated++;
4595 	cam_ccbq_take_opening(&periph->path->device->ccbq);
4596 	return (new_ccb);
4597 }
4598 
4599 static union ccb *
4600 xpt_get_ccb(struct cam_periph *periph)
4601 {
4602 	union ccb *new_ccb;
4603 
4604 	cam_periph_unlock(periph);
4605 	new_ccb = malloc(sizeof(*new_ccb), M_CAMCCB, M_ZERO|M_WAITOK);
4606 	cam_periph_lock(periph);
4607 	periph->periph_allocated++;
4608 	cam_ccbq_take_opening(&periph->path->device->ccbq);
4609 	return (new_ccb);
4610 }
4611 
4612 union ccb *
4613 cam_periph_getccb(struct cam_periph *periph, u_int32_t priority)
4614 {
4615 	struct ccb_hdr *ccb_h;
4616 
4617 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("cam_periph_getccb\n"));
4618 	cam_periph_assert(periph, MA_OWNED);
4619 	while ((ccb_h = SLIST_FIRST(&periph->ccb_list)) == NULL ||
4620 	    ccb_h->pinfo.priority != priority) {
4621 		if (priority < periph->immediate_priority) {
4622 			periph->immediate_priority = priority;
4623 			xpt_run_allocq(periph, 0);
4624 		} else
4625 			cam_periph_sleep(periph, &periph->ccb_list, PRIBIO,
4626 			    "cgticb", 0);
4627 	}
4628 	SLIST_REMOVE_HEAD(&periph->ccb_list, periph_links.sle);
4629 	return ((union ccb *)ccb_h);
4630 }
4631 
4632 static void
4633 xpt_acquire_bus(struct cam_eb *bus)
4634 {
4635 
4636 	xpt_lock_buses();
4637 	bus->refcount++;
4638 	xpt_unlock_buses();
4639 }
4640 
4641 static void
4642 xpt_release_bus(struct cam_eb *bus)
4643 {
4644 
4645 	xpt_lock_buses();
4646 	KASSERT(bus->refcount >= 1, ("bus->refcount >= 1"));
4647 	if (--bus->refcount > 0) {
4648 		xpt_unlock_buses();
4649 		return;
4650 	}
4651 	TAILQ_REMOVE(&xsoftc.xpt_busses, bus, links);
4652 	xsoftc.bus_generation++;
4653 	xpt_unlock_buses();
4654 	KASSERT(TAILQ_EMPTY(&bus->et_entries),
4655 	    ("destroying bus, but target list is not empty"));
4656 	cam_sim_release(bus->sim);
4657 	mtx_destroy(&bus->eb_mtx);
4658 	free(bus, M_CAMXPT);
4659 }
4660 
4661 static struct cam_et *
4662 xpt_alloc_target(struct cam_eb *bus, target_id_t target_id)
4663 {
4664 	struct cam_et *cur_target, *target;
4665 
4666 	mtx_assert(&xsoftc.xpt_topo_lock, MA_OWNED);
4667 	mtx_assert(&bus->eb_mtx, MA_OWNED);
4668 	target = (struct cam_et *)malloc(sizeof(*target), M_CAMXPT,
4669 					 M_NOWAIT|M_ZERO);
4670 	if (target == NULL)
4671 		return (NULL);
4672 
4673 	TAILQ_INIT(&target->ed_entries);
4674 	target->bus = bus;
4675 	target->target_id = target_id;
4676 	target->refcount = 1;
4677 	target->generation = 0;
4678 	target->luns = NULL;
4679 	mtx_init(&target->luns_mtx, "CAM LUNs lock", NULL, MTX_DEF);
4680 	timevalclear(&target->last_reset);
4681 	/*
4682 	 * Hold a reference to our parent bus so it
4683 	 * will not go away before we do.
4684 	 */
4685 	bus->refcount++;
4686 
4687 	/* Insertion sort into our bus's target list */
4688 	cur_target = TAILQ_FIRST(&bus->et_entries);
4689 	while (cur_target != NULL && cur_target->target_id < target_id)
4690 		cur_target = TAILQ_NEXT(cur_target, links);
4691 	if (cur_target != NULL) {
4692 		TAILQ_INSERT_BEFORE(cur_target, target, links);
4693 	} else {
4694 		TAILQ_INSERT_TAIL(&bus->et_entries, target, links);
4695 	}
4696 	bus->generation++;
4697 	return (target);
4698 }
4699 
4700 static void
4701 xpt_acquire_target(struct cam_et *target)
4702 {
4703 	struct cam_eb *bus = target->bus;
4704 
4705 	mtx_lock(&bus->eb_mtx);
4706 	target->refcount++;
4707 	mtx_unlock(&bus->eb_mtx);
4708 }
4709 
4710 static void
4711 xpt_release_target(struct cam_et *target)
4712 {
4713 	struct cam_eb *bus = target->bus;
4714 
4715 	mtx_lock(&bus->eb_mtx);
4716 	if (--target->refcount > 0) {
4717 		mtx_unlock(&bus->eb_mtx);
4718 		return;
4719 	}
4720 	TAILQ_REMOVE(&bus->et_entries, target, links);
4721 	bus->generation++;
4722 	mtx_unlock(&bus->eb_mtx);
4723 	KASSERT(TAILQ_EMPTY(&target->ed_entries),
4724 	    ("destroying target, but device list is not empty"));
4725 	xpt_release_bus(bus);
4726 	mtx_destroy(&target->luns_mtx);
4727 	if (target->luns)
4728 		free(target->luns, M_CAMXPT);
4729 	free(target, M_CAMXPT);
4730 }
4731 
4732 static struct cam_ed *
4733 xpt_alloc_device_default(struct cam_eb *bus, struct cam_et *target,
4734 			 lun_id_t lun_id)
4735 {
4736 	struct cam_ed *device;
4737 
4738 	device = xpt_alloc_device(bus, target, lun_id);
4739 	if (device == NULL)
4740 		return (NULL);
4741 
4742 	device->mintags = 1;
4743 	device->maxtags = 1;
4744 	return (device);
4745 }
4746 
4747 static void
4748 xpt_destroy_device(void *context, int pending)
4749 {
4750 	struct cam_ed	*device = context;
4751 
4752 	mtx_lock(&device->device_mtx);
4753 	mtx_destroy(&device->device_mtx);
4754 	free(device, M_CAMDEV);
4755 }
4756 
4757 struct cam_ed *
4758 xpt_alloc_device(struct cam_eb *bus, struct cam_et *target, lun_id_t lun_id)
4759 {
4760 	struct cam_ed	*cur_device, *device;
4761 	struct cam_devq	*devq;
4762 	cam_status status;
4763 
4764 	mtx_assert(&bus->eb_mtx, MA_OWNED);
4765 	/* Make space for us in the device queue on our bus */
4766 	devq = bus->sim->devq;
4767 	mtx_lock(&devq->send_mtx);
4768 	status = cam_devq_resize(devq, devq->send_queue.array_size + 1);
4769 	mtx_unlock(&devq->send_mtx);
4770 	if (status != CAM_REQ_CMP)
4771 		return (NULL);
4772 
4773 	device = (struct cam_ed *)malloc(sizeof(*device),
4774 					 M_CAMDEV, M_NOWAIT|M_ZERO);
4775 	if (device == NULL)
4776 		return (NULL);
4777 
4778 	cam_init_pinfo(&device->devq_entry);
4779 	device->target = target;
4780 	device->lun_id = lun_id;
4781 	device->sim = bus->sim;
4782 	if (cam_ccbq_init(&device->ccbq,
4783 			  bus->sim->max_dev_openings) != 0) {
4784 		free(device, M_CAMDEV);
4785 		return (NULL);
4786 	}
4787 	SLIST_INIT(&device->asyncs);
4788 	SLIST_INIT(&device->periphs);
4789 	device->generation = 0;
4790 	device->flags = CAM_DEV_UNCONFIGURED;
4791 	device->tag_delay_count = 0;
4792 	device->tag_saved_openings = 0;
4793 	device->refcount = 1;
4794 	mtx_init(&device->device_mtx, "CAM device lock", NULL, MTX_DEF);
4795 	callout_init_mtx(&device->callout, &devq->send_mtx, 0);
4796 	TASK_INIT(&device->device_destroy_task, 0, xpt_destroy_device, device);
4797 	/*
4798 	 * Hold a reference to our parent bus so it
4799 	 * will not go away before we do.
4800 	 */
4801 	target->refcount++;
4802 
4803 	cur_device = TAILQ_FIRST(&target->ed_entries);
4804 	while (cur_device != NULL && cur_device->lun_id < lun_id)
4805 		cur_device = TAILQ_NEXT(cur_device, links);
4806 	if (cur_device != NULL)
4807 		TAILQ_INSERT_BEFORE(cur_device, device, links);
4808 	else
4809 		TAILQ_INSERT_TAIL(&target->ed_entries, device, links);
4810 	target->generation++;
4811 	return (device);
4812 }
4813 
4814 void
4815 xpt_acquire_device(struct cam_ed *device)
4816 {
4817 	struct cam_eb *bus = device->target->bus;
4818 
4819 	mtx_lock(&bus->eb_mtx);
4820 	device->refcount++;
4821 	mtx_unlock(&bus->eb_mtx);
4822 }
4823 
4824 void
4825 xpt_release_device(struct cam_ed *device)
4826 {
4827 	struct cam_eb *bus = device->target->bus;
4828 	struct cam_devq *devq;
4829 
4830 	mtx_lock(&bus->eb_mtx);
4831 	if (--device->refcount > 0) {
4832 		mtx_unlock(&bus->eb_mtx);
4833 		return;
4834 	}
4835 
4836 	TAILQ_REMOVE(&device->target->ed_entries, device,links);
4837 	device->target->generation++;
4838 	mtx_unlock(&bus->eb_mtx);
4839 
4840 	/* Release our slot in the devq */
4841 	devq = bus->sim->devq;
4842 	mtx_lock(&devq->send_mtx);
4843 	cam_devq_resize(devq, devq->send_queue.array_size - 1);
4844 	mtx_unlock(&devq->send_mtx);
4845 
4846 	KASSERT(SLIST_EMPTY(&device->periphs),
4847 	    ("destroying device, but periphs list is not empty"));
4848 	KASSERT(device->devq_entry.index == CAM_UNQUEUED_INDEX,
4849 	    ("destroying device while still queued for ccbs"));
4850 
4851 	if ((device->flags & CAM_DEV_REL_TIMEOUT_PENDING) != 0)
4852 		callout_stop(&device->callout);
4853 
4854 	xpt_release_target(device->target);
4855 
4856 	cam_ccbq_fini(&device->ccbq);
4857 	/*
4858 	 * Free allocated memory.  free(9) does nothing if the
4859 	 * supplied pointer is NULL, so it is safe to call without
4860 	 * checking.
4861 	 */
4862 	free(device->supported_vpds, M_CAMXPT);
4863 	free(device->device_id, M_CAMXPT);
4864 	free(device->ext_inq, M_CAMXPT);
4865 	free(device->physpath, M_CAMXPT);
4866 	free(device->rcap_buf, M_CAMXPT);
4867 	free(device->serial_num, M_CAMXPT);
4868 	taskqueue_enqueue(xsoftc.xpt_taskq, &device->device_destroy_task);
4869 }
4870 
4871 u_int32_t
4872 xpt_dev_ccbq_resize(struct cam_path *path, int newopenings)
4873 {
4874 	int	result;
4875 	struct	cam_ed *dev;
4876 
4877 	dev = path->device;
4878 	mtx_lock(&dev->sim->devq->send_mtx);
4879 	result = cam_ccbq_resize(&dev->ccbq, newopenings);
4880 	mtx_unlock(&dev->sim->devq->send_mtx);
4881 	if ((dev->flags & CAM_DEV_TAG_AFTER_COUNT) != 0
4882 	 || (dev->inq_flags & SID_CmdQue) != 0)
4883 		dev->tag_saved_openings = newopenings;
4884 	return (result);
4885 }
4886 
4887 static struct cam_eb *
4888 xpt_find_bus(path_id_t path_id)
4889 {
4890 	struct cam_eb *bus;
4891 
4892 	xpt_lock_buses();
4893 	for (bus = TAILQ_FIRST(&xsoftc.xpt_busses);
4894 	     bus != NULL;
4895 	     bus = TAILQ_NEXT(bus, links)) {
4896 		if (bus->path_id == path_id) {
4897 			bus->refcount++;
4898 			break;
4899 		}
4900 	}
4901 	xpt_unlock_buses();
4902 	return (bus);
4903 }
4904 
4905 static struct cam_et *
4906 xpt_find_target(struct cam_eb *bus, target_id_t	target_id)
4907 {
4908 	struct cam_et *target;
4909 
4910 	mtx_assert(&bus->eb_mtx, MA_OWNED);
4911 	for (target = TAILQ_FIRST(&bus->et_entries);
4912 	     target != NULL;
4913 	     target = TAILQ_NEXT(target, links)) {
4914 		if (target->target_id == target_id) {
4915 			target->refcount++;
4916 			break;
4917 		}
4918 	}
4919 	return (target);
4920 }
4921 
4922 static struct cam_ed *
4923 xpt_find_device(struct cam_et *target, lun_id_t lun_id)
4924 {
4925 	struct cam_ed *device;
4926 
4927 	mtx_assert(&target->bus->eb_mtx, MA_OWNED);
4928 	for (device = TAILQ_FIRST(&target->ed_entries);
4929 	     device != NULL;
4930 	     device = TAILQ_NEXT(device, links)) {
4931 		if (device->lun_id == lun_id) {
4932 			device->refcount++;
4933 			break;
4934 		}
4935 	}
4936 	return (device);
4937 }
4938 
4939 void
4940 xpt_start_tags(struct cam_path *path)
4941 {
4942 	struct ccb_relsim crs;
4943 	struct cam_ed *device;
4944 	struct cam_sim *sim;
4945 	int    newopenings;
4946 
4947 	device = path->device;
4948 	sim = path->bus->sim;
4949 	device->flags &= ~CAM_DEV_TAG_AFTER_COUNT;
4950 	xpt_freeze_devq(path, /*count*/1);
4951 	device->inq_flags |= SID_CmdQue;
4952 	if (device->tag_saved_openings != 0)
4953 		newopenings = device->tag_saved_openings;
4954 	else
4955 		newopenings = min(device->maxtags,
4956 				  sim->max_tagged_dev_openings);
4957 	xpt_dev_ccbq_resize(path, newopenings);
4958 	xpt_async(AC_GETDEV_CHANGED, path, NULL);
4959 	xpt_setup_ccb(&crs.ccb_h, path, CAM_PRIORITY_NORMAL);
4960 	crs.ccb_h.func_code = XPT_REL_SIMQ;
4961 	crs.release_flags = RELSIM_RELEASE_AFTER_QEMPTY;
4962 	crs.openings
4963 	    = crs.release_timeout
4964 	    = crs.qfrozen_cnt
4965 	    = 0;
4966 	xpt_action((union ccb *)&crs);
4967 }
4968 
4969 void
4970 xpt_stop_tags(struct cam_path *path)
4971 {
4972 	struct ccb_relsim crs;
4973 	struct cam_ed *device;
4974 	struct cam_sim *sim;
4975 
4976 	device = path->device;
4977 	sim = path->bus->sim;
4978 	device->flags &= ~CAM_DEV_TAG_AFTER_COUNT;
4979 	device->tag_delay_count = 0;
4980 	xpt_freeze_devq(path, /*count*/1);
4981 	device->inq_flags &= ~SID_CmdQue;
4982 	xpt_dev_ccbq_resize(path, sim->max_dev_openings);
4983 	xpt_async(AC_GETDEV_CHANGED, path, NULL);
4984 	xpt_setup_ccb(&crs.ccb_h, path, CAM_PRIORITY_NORMAL);
4985 	crs.ccb_h.func_code = XPT_REL_SIMQ;
4986 	crs.release_flags = RELSIM_RELEASE_AFTER_QEMPTY;
4987 	crs.openings
4988 	    = crs.release_timeout
4989 	    = crs.qfrozen_cnt
4990 	    = 0;
4991 	xpt_action((union ccb *)&crs);
4992 }
4993 
4994 static void
4995 xpt_boot_delay(void *arg)
4996 {
4997 
4998 	xpt_release_boot();
4999 }
5000 
5001 static void
5002 xpt_config(void *arg)
5003 {
5004 	/*
5005 	 * Now that interrupts are enabled, go find our devices
5006 	 */
5007 	if (taskqueue_start_threads(&xsoftc.xpt_taskq, 1, PRIBIO, "CAM taskq"))
5008 		printf("xpt_config: failed to create taskqueue thread.\n");
5009 
5010 	/* Setup debugging path */
5011 	if (cam_dflags != CAM_DEBUG_NONE) {
5012 		if (xpt_create_path(&cam_dpath, NULL,
5013 				    CAM_DEBUG_BUS, CAM_DEBUG_TARGET,
5014 				    CAM_DEBUG_LUN) != CAM_REQ_CMP) {
5015 			printf("xpt_config: xpt_create_path() failed for debug"
5016 			       " target %d:%d:%d, debugging disabled\n",
5017 			       CAM_DEBUG_BUS, CAM_DEBUG_TARGET, CAM_DEBUG_LUN);
5018 			cam_dflags = CAM_DEBUG_NONE;
5019 		}
5020 	} else
5021 		cam_dpath = NULL;
5022 
5023 	periphdriver_init(1);
5024 	xpt_hold_boot();
5025 	callout_init(&xsoftc.boot_callout, 1);
5026 	callout_reset_sbt(&xsoftc.boot_callout, SBT_1MS * xsoftc.boot_delay, 0,
5027 	    xpt_boot_delay, NULL, 0);
5028 	/* Fire up rescan thread. */
5029 	if (kproc_kthread_add(xpt_scanner_thread, NULL, &cam_proc, NULL, 0, 0,
5030 	    "cam", "scanner")) {
5031 		printf("xpt_config: failed to create rescan thread.\n");
5032 	}
5033 }
5034 
5035 void
5036 xpt_hold_boot(void)
5037 {
5038 	xpt_lock_buses();
5039 	xsoftc.buses_to_config++;
5040 	xpt_unlock_buses();
5041 }
5042 
5043 void
5044 xpt_release_boot(void)
5045 {
5046 	xpt_lock_buses();
5047 	xsoftc.buses_to_config--;
5048 	if (xsoftc.buses_to_config == 0 && xsoftc.buses_config_done == 0) {
5049 		struct	xpt_task *task;
5050 
5051 		xsoftc.buses_config_done = 1;
5052 		xpt_unlock_buses();
5053 		/* Call manually because we don't have any buses */
5054 		task = malloc(sizeof(struct xpt_task), M_CAMXPT, M_NOWAIT);
5055 		if (task != NULL) {
5056 			TASK_INIT(&task->task, 0, xpt_finishconfig_task, task);
5057 			taskqueue_enqueue(taskqueue_thread, &task->task);
5058 		}
5059 	} else
5060 		xpt_unlock_buses();
5061 }
5062 
5063 /*
5064  * If the given device only has one peripheral attached to it, and if that
5065  * peripheral is the passthrough driver, announce it.  This insures that the
5066  * user sees some sort of announcement for every peripheral in their system.
5067  */
5068 static int
5069 xptpassannouncefunc(struct cam_ed *device, void *arg)
5070 {
5071 	struct cam_periph *periph;
5072 	int i;
5073 
5074 	for (periph = SLIST_FIRST(&device->periphs), i = 0; periph != NULL;
5075 	     periph = SLIST_NEXT(periph, periph_links), i++);
5076 
5077 	periph = SLIST_FIRST(&device->periphs);
5078 	if ((i == 1)
5079 	 && (strncmp(periph->periph_name, "pass", 4) == 0))
5080 		xpt_announce_periph(periph, NULL);
5081 
5082 	return(1);
5083 }
5084 
5085 static void
5086 xpt_finishconfig_task(void *context, int pending)
5087 {
5088 
5089 	periphdriver_init(2);
5090 	/*
5091 	 * Check for devices with no "standard" peripheral driver
5092 	 * attached.  For any devices like that, announce the
5093 	 * passthrough driver so the user will see something.
5094 	 */
5095 	if (!bootverbose)
5096 		xpt_for_all_devices(xptpassannouncefunc, NULL);
5097 
5098 	/* Release our hook so that the boot can continue. */
5099 	config_intrhook_disestablish(xsoftc.xpt_config_hook);
5100 	free(xsoftc.xpt_config_hook, M_CAMXPT);
5101 	xsoftc.xpt_config_hook = NULL;
5102 
5103 	free(context, M_CAMXPT);
5104 }
5105 
5106 cam_status
5107 xpt_register_async(int event, ac_callback_t *cbfunc, void *cbarg,
5108 		   struct cam_path *path)
5109 {
5110 	struct ccb_setasync csa;
5111 	cam_status status;
5112 	int xptpath = 0;
5113 
5114 	if (path == NULL) {
5115 		status = xpt_create_path(&path, /*periph*/NULL, CAM_XPT_PATH_ID,
5116 					 CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
5117 		if (status != CAM_REQ_CMP)
5118 			return (status);
5119 		xpt_path_lock(path);
5120 		xptpath = 1;
5121 	}
5122 
5123 	xpt_setup_ccb(&csa.ccb_h, path, CAM_PRIORITY_NORMAL);
5124 	csa.ccb_h.func_code = XPT_SASYNC_CB;
5125 	csa.event_enable = event;
5126 	csa.callback = cbfunc;
5127 	csa.callback_arg = cbarg;
5128 	xpt_action((union ccb *)&csa);
5129 	status = csa.ccb_h.status;
5130 
5131 	CAM_DEBUG(csa.ccb_h.path, CAM_DEBUG_TRACE,
5132 	    ("xpt_register_async: func %p\n", cbfunc));
5133 
5134 	if (xptpath) {
5135 		xpt_path_unlock(path);
5136 		xpt_free_path(path);
5137 	}
5138 
5139 	if ((status == CAM_REQ_CMP) &&
5140 	    (csa.event_enable & AC_FOUND_DEVICE)) {
5141 		/*
5142 		 * Get this peripheral up to date with all
5143 		 * the currently existing devices.
5144 		 */
5145 		xpt_for_all_devices(xptsetasyncfunc, &csa);
5146 	}
5147 	if ((status == CAM_REQ_CMP) &&
5148 	    (csa.event_enable & AC_PATH_REGISTERED)) {
5149 		/*
5150 		 * Get this peripheral up to date with all
5151 		 * the currently existing buses.
5152 		 */
5153 		xpt_for_all_busses(xptsetasyncbusfunc, &csa);
5154 	}
5155 
5156 	return (status);
5157 }
5158 
5159 static void
5160 xptaction(struct cam_sim *sim, union ccb *work_ccb)
5161 {
5162 	CAM_DEBUG(work_ccb->ccb_h.path, CAM_DEBUG_TRACE, ("xptaction\n"));
5163 
5164 	switch (work_ccb->ccb_h.func_code) {
5165 	/* Common cases first */
5166 	case XPT_PATH_INQ:		/* Path routing inquiry */
5167 	{
5168 		struct ccb_pathinq *cpi;
5169 
5170 		cpi = &work_ccb->cpi;
5171 		cpi->version_num = 1; /* XXX??? */
5172 		cpi->hba_inquiry = 0;
5173 		cpi->target_sprt = 0;
5174 		cpi->hba_misc = 0;
5175 		cpi->hba_eng_cnt = 0;
5176 		cpi->max_target = 0;
5177 		cpi->max_lun = 0;
5178 		cpi->initiator_id = 0;
5179 		strlcpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
5180 		strlcpy(cpi->hba_vid, "", HBA_IDLEN);
5181 		strlcpy(cpi->dev_name, sim->sim_name, DEV_IDLEN);
5182 		cpi->unit_number = sim->unit_number;
5183 		cpi->bus_id = sim->bus_id;
5184 		cpi->base_transfer_speed = 0;
5185 		cpi->protocol = PROTO_UNSPECIFIED;
5186 		cpi->protocol_version = PROTO_VERSION_UNSPECIFIED;
5187 		cpi->transport = XPORT_UNSPECIFIED;
5188 		cpi->transport_version = XPORT_VERSION_UNSPECIFIED;
5189 		cpi->ccb_h.status = CAM_REQ_CMP;
5190 		xpt_done(work_ccb);
5191 		break;
5192 	}
5193 	default:
5194 		work_ccb->ccb_h.status = CAM_REQ_INVALID;
5195 		xpt_done(work_ccb);
5196 		break;
5197 	}
5198 }
5199 
5200 /*
5201  * The xpt as a "controller" has no interrupt sources, so polling
5202  * is a no-op.
5203  */
5204 static void
5205 xptpoll(struct cam_sim *sim)
5206 {
5207 }
5208 
5209 void
5210 xpt_lock_buses(void)
5211 {
5212 	mtx_lock(&xsoftc.xpt_topo_lock);
5213 }
5214 
5215 void
5216 xpt_unlock_buses(void)
5217 {
5218 	mtx_unlock(&xsoftc.xpt_topo_lock);
5219 }
5220 
5221 struct mtx *
5222 xpt_path_mtx(struct cam_path *path)
5223 {
5224 
5225 	return (&path->device->device_mtx);
5226 }
5227 
5228 static void
5229 xpt_done_process(struct ccb_hdr *ccb_h)
5230 {
5231 	struct cam_sim *sim;
5232 	struct cam_devq *devq;
5233 	struct mtx *mtx = NULL;
5234 
5235 #if defined(BUF_TRACKING) || defined(FULL_BUF_TRACKING)
5236 	struct ccb_scsiio *csio;
5237 
5238 	if (ccb_h->func_code == XPT_SCSI_IO) {
5239 		csio = &((union ccb *)ccb_h)->csio;
5240 		if (csio->bio != NULL)
5241 			biotrack(csio->bio, __func__);
5242 	}
5243 #endif
5244 
5245 	if (ccb_h->flags & CAM_HIGH_POWER) {
5246 		struct highpowerlist	*hphead;
5247 		struct cam_ed		*device;
5248 
5249 		mtx_lock(&xsoftc.xpt_highpower_lock);
5250 		hphead = &xsoftc.highpowerq;
5251 
5252 		device = STAILQ_FIRST(hphead);
5253 
5254 		/*
5255 		 * Increment the count since this command is done.
5256 		 */
5257 		xsoftc.num_highpower++;
5258 
5259 		/*
5260 		 * Any high powered commands queued up?
5261 		 */
5262 		if (device != NULL) {
5263 
5264 			STAILQ_REMOVE_HEAD(hphead, highpowerq_entry);
5265 			mtx_unlock(&xsoftc.xpt_highpower_lock);
5266 
5267 			mtx_lock(&device->sim->devq->send_mtx);
5268 			xpt_release_devq_device(device,
5269 					 /*count*/1, /*runqueue*/TRUE);
5270 			mtx_unlock(&device->sim->devq->send_mtx);
5271 		} else
5272 			mtx_unlock(&xsoftc.xpt_highpower_lock);
5273 	}
5274 
5275 	sim = ccb_h->path->bus->sim;
5276 
5277 	if (ccb_h->status & CAM_RELEASE_SIMQ) {
5278 		xpt_release_simq(sim, /*run_queue*/FALSE);
5279 		ccb_h->status &= ~CAM_RELEASE_SIMQ;
5280 	}
5281 
5282 	if ((ccb_h->flags & CAM_DEV_QFRZDIS)
5283 	 && (ccb_h->status & CAM_DEV_QFRZN)) {
5284 		xpt_release_devq(ccb_h->path, /*count*/1, /*run_queue*/TRUE);
5285 		ccb_h->status &= ~CAM_DEV_QFRZN;
5286 	}
5287 
5288 	devq = sim->devq;
5289 	if ((ccb_h->func_code & XPT_FC_USER_CCB) == 0) {
5290 		struct cam_ed *dev = ccb_h->path->device;
5291 
5292 		mtx_lock(&devq->send_mtx);
5293 		devq->send_active--;
5294 		devq->send_openings++;
5295 		cam_ccbq_ccb_done(&dev->ccbq, (union ccb *)ccb_h);
5296 
5297 		if (((dev->flags & CAM_DEV_REL_ON_QUEUE_EMPTY) != 0
5298 		  && (dev->ccbq.dev_active == 0))) {
5299 			dev->flags &= ~CAM_DEV_REL_ON_QUEUE_EMPTY;
5300 			xpt_release_devq_device(dev, /*count*/1,
5301 					 /*run_queue*/FALSE);
5302 		}
5303 
5304 		if (((dev->flags & CAM_DEV_REL_ON_COMPLETE) != 0
5305 		  && (ccb_h->status&CAM_STATUS_MASK) != CAM_REQUEUE_REQ)) {
5306 			dev->flags &= ~CAM_DEV_REL_ON_COMPLETE;
5307 			xpt_release_devq_device(dev, /*count*/1,
5308 					 /*run_queue*/FALSE);
5309 		}
5310 
5311 		if (!device_is_queued(dev))
5312 			(void)xpt_schedule_devq(devq, dev);
5313 		xpt_run_devq(devq);
5314 		mtx_unlock(&devq->send_mtx);
5315 
5316 		if ((dev->flags & CAM_DEV_TAG_AFTER_COUNT) != 0) {
5317 			mtx = xpt_path_mtx(ccb_h->path);
5318 			mtx_lock(mtx);
5319 
5320 			if ((dev->flags & CAM_DEV_TAG_AFTER_COUNT) != 0
5321 			 && (--dev->tag_delay_count == 0))
5322 				xpt_start_tags(ccb_h->path);
5323 		}
5324 	}
5325 
5326 	if ((ccb_h->flags & CAM_UNLOCKED) == 0) {
5327 		if (mtx == NULL) {
5328 			mtx = xpt_path_mtx(ccb_h->path);
5329 			mtx_lock(mtx);
5330 		}
5331 	} else {
5332 		if (mtx != NULL) {
5333 			mtx_unlock(mtx);
5334 			mtx = NULL;
5335 		}
5336 	}
5337 
5338 	/* Call the peripheral driver's callback */
5339 	ccb_h->pinfo.index = CAM_UNQUEUED_INDEX;
5340 	(*ccb_h->cbfcnp)(ccb_h->path->periph, (union ccb *)ccb_h);
5341 	if (mtx != NULL)
5342 		mtx_unlock(mtx);
5343 }
5344 
5345 void
5346 xpt_done_td(void *arg)
5347 {
5348 	struct cam_doneq *queue = arg;
5349 	struct ccb_hdr *ccb_h;
5350 	STAILQ_HEAD(, ccb_hdr)	doneq;
5351 
5352 	STAILQ_INIT(&doneq);
5353 	mtx_lock(&queue->cam_doneq_mtx);
5354 	while (1) {
5355 		while (STAILQ_EMPTY(&queue->cam_doneq)) {
5356 			queue->cam_doneq_sleep = 1;
5357 			msleep(&queue->cam_doneq, &queue->cam_doneq_mtx,
5358 			    PRIBIO, "-", 0);
5359 			queue->cam_doneq_sleep = 0;
5360 		}
5361 		STAILQ_CONCAT(&doneq, &queue->cam_doneq);
5362 		mtx_unlock(&queue->cam_doneq_mtx);
5363 
5364 		THREAD_NO_SLEEPING();
5365 		while ((ccb_h = STAILQ_FIRST(&doneq)) != NULL) {
5366 			STAILQ_REMOVE_HEAD(&doneq, sim_links.stqe);
5367 			xpt_done_process(ccb_h);
5368 		}
5369 		THREAD_SLEEPING_OK();
5370 
5371 		mtx_lock(&queue->cam_doneq_mtx);
5372 	}
5373 }
5374 
5375 static void
5376 camisr_runqueue(void)
5377 {
5378 	struct	ccb_hdr *ccb_h;
5379 	struct cam_doneq *queue;
5380 	int i;
5381 
5382 	/* Process global queues. */
5383 	for (i = 0; i < cam_num_doneqs; i++) {
5384 		queue = &cam_doneqs[i];
5385 		mtx_lock(&queue->cam_doneq_mtx);
5386 		while ((ccb_h = STAILQ_FIRST(&queue->cam_doneq)) != NULL) {
5387 			STAILQ_REMOVE_HEAD(&queue->cam_doneq, sim_links.stqe);
5388 			mtx_unlock(&queue->cam_doneq_mtx);
5389 			xpt_done_process(ccb_h);
5390 			mtx_lock(&queue->cam_doneq_mtx);
5391 		}
5392 		mtx_unlock(&queue->cam_doneq_mtx);
5393 	}
5394 }
5395 
5396 struct kv
5397 {
5398 	uint32_t v;
5399 	const char *name;
5400 };
5401 
5402 static struct kv map[] = {
5403 	{ XPT_NOOP, "XPT_NOOP" },
5404 	{ XPT_SCSI_IO, "XPT_SCSI_IO" },
5405 	{ XPT_GDEV_TYPE, "XPT_GDEV_TYPE" },
5406 	{ XPT_GDEVLIST, "XPT_GDEVLIST" },
5407 	{ XPT_PATH_INQ, "XPT_PATH_INQ" },
5408 	{ XPT_REL_SIMQ, "XPT_REL_SIMQ" },
5409 	{ XPT_SASYNC_CB, "XPT_SASYNC_CB" },
5410 	{ XPT_SDEV_TYPE, "XPT_SDEV_TYPE" },
5411 	{ XPT_SCAN_BUS, "XPT_SCAN_BUS" },
5412 	{ XPT_DEV_MATCH, "XPT_DEV_MATCH" },
5413 	{ XPT_DEBUG, "XPT_DEBUG" },
5414 	{ XPT_PATH_STATS, "XPT_PATH_STATS" },
5415 	{ XPT_GDEV_STATS, "XPT_GDEV_STATS" },
5416 	{ XPT_DEV_ADVINFO, "XPT_DEV_ADVINFO" },
5417 	{ XPT_ASYNC, "XPT_ASYNC" },
5418 	{ XPT_ABORT, "XPT_ABORT" },
5419 	{ XPT_RESET_BUS, "XPT_RESET_BUS" },
5420 	{ XPT_RESET_DEV, "XPT_RESET_DEV" },
5421 	{ XPT_TERM_IO, "XPT_TERM_IO" },
5422 	{ XPT_SCAN_LUN, "XPT_SCAN_LUN" },
5423 	{ XPT_GET_TRAN_SETTINGS, "XPT_GET_TRAN_SETTINGS" },
5424 	{ XPT_SET_TRAN_SETTINGS, "XPT_SET_TRAN_SETTINGS" },
5425 	{ XPT_CALC_GEOMETRY, "XPT_CALC_GEOMETRY" },
5426 	{ XPT_ATA_IO, "XPT_ATA_IO" },
5427 	{ XPT_GET_SIM_KNOB, "XPT_GET_SIM_KNOB" },
5428 	{ XPT_SET_SIM_KNOB, "XPT_SET_SIM_KNOB" },
5429 	{ XPT_NVME_IO, "XPT_NVME_IO" },
5430 	{ XPT_MMCSD_IO, "XPT_MMCSD_IO" },
5431 	{ XPT_SMP_IO, "XPT_SMP_IO" },
5432 	{ XPT_SCAN_TGT, "XPT_SCAN_TGT" },
5433 	{ XPT_ENG_INQ, "XPT_ENG_INQ" },
5434 	{ XPT_ENG_EXEC, "XPT_ENG_EXEC" },
5435 	{ XPT_EN_LUN, "XPT_EN_LUN" },
5436 	{ XPT_TARGET_IO, "XPT_TARGET_IO" },
5437 	{ XPT_ACCEPT_TARGET_IO, "XPT_ACCEPT_TARGET_IO" },
5438 	{ XPT_CONT_TARGET_IO, "XPT_CONT_TARGET_IO" },
5439 	{ XPT_IMMED_NOTIFY, "XPT_IMMED_NOTIFY" },
5440 	{ XPT_NOTIFY_ACK, "XPT_NOTIFY_ACK" },
5441 	{ XPT_IMMEDIATE_NOTIFY, "XPT_IMMEDIATE_NOTIFY" },
5442 	{ XPT_NOTIFY_ACKNOWLEDGE, "XPT_NOTIFY_ACKNOWLEDGE" },
5443 	{ 0, 0 }
5444 };
5445 
5446 static const char *
5447 xpt_action_name(uint32_t action)
5448 {
5449 	static char buffer[32];	/* Only for unknown messages -- racy */
5450 	struct kv *walker = map;
5451 
5452 	while (walker->name != NULL) {
5453 		if (walker->v == action)
5454 			return (walker->name);
5455 		walker++;
5456 	}
5457 
5458 	snprintf(buffer, sizeof(buffer), "%#x", action);
5459 	return (buffer);
5460 }
5461