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