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