xref: /freebsd/sys/cam/cam_xpt.c (revision 38069501)
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_iosched.h>
59 #include <cam/cam_periph.h>
60 #include <cam/cam_queue.h>
61 #include <cam/cam_sim.h>
62 #include <cam/cam_xpt.h>
63 #include <cam/cam_xpt_sim.h>
64 #include <cam/cam_xpt_periph.h>
65 #include <cam/cam_xpt_internal.h>
66 #include <cam/cam_debug.h>
67 #include <cam/cam_compat.h>
68 
69 #include <cam/scsi/scsi_all.h>
70 #include <cam/scsi/scsi_message.h>
71 #include <cam/scsi/scsi_pass.h>
72 
73 #include <machine/md_var.h>	/* geometry translation */
74 #include <machine/stdarg.h>	/* for xpt_print below */
75 
76 #include "opt_cam.h"
77 
78 /* Wild guess based on not wanting to grow the stack too much */
79 #define XPT_PRINT_MAXLEN	512
80 #ifdef PRINTF_BUFR_SIZE
81 #define XPT_PRINT_LEN	PRINTF_BUFR_SIZE
82 #else
83 #define XPT_PRINT_LEN	128
84 #endif
85 _Static_assert(XPT_PRINT_LEN <= XPT_PRINT_MAXLEN, "XPT_PRINT_LEN is too large");
86 
87 /*
88  * This is the maximum number of high powered commands (e.g. start unit)
89  * that can be outstanding at a particular time.
90  */
91 #ifndef CAM_MAX_HIGHPOWER
92 #define CAM_MAX_HIGHPOWER  4
93 #endif
94 
95 /* Datastructures internal to the xpt layer */
96 MALLOC_DEFINE(M_CAMXPT, "CAM XPT", "CAM XPT buffers");
97 MALLOC_DEFINE(M_CAMDEV, "CAM DEV", "CAM devices");
98 MALLOC_DEFINE(M_CAMCCB, "CAM CCB", "CAM CCBs");
99 MALLOC_DEFINE(M_CAMPATH, "CAM path", "CAM paths");
100 
101 /* Object for defering XPT actions to a taskqueue */
102 struct xpt_task {
103 	struct task	task;
104 	void		*data1;
105 	uintptr_t	data2;
106 };
107 
108 struct xpt_softc {
109 	uint32_t		xpt_generation;
110 
111 	/* number of high powered commands that can go through right now */
112 	struct mtx		xpt_highpower_lock;
113 	STAILQ_HEAD(highpowerlist, cam_ed)	highpowerq;
114 	int			num_highpower;
115 
116 	/* queue for handling async rescan requests. */
117 	TAILQ_HEAD(, ccb_hdr) ccb_scanq;
118 	int buses_to_config;
119 	int buses_config_done;
120 	int announce_nosbuf;
121 
122 	/*
123 	 * Registered buses
124 	 *
125 	 * N.B., "busses" is an archaic spelling of "buses".  In new code
126 	 * "buses" is preferred.
127 	 */
128 	TAILQ_HEAD(,cam_eb)	xpt_busses;
129 	u_int			bus_generation;
130 
131 	struct intr_config_hook	*xpt_config_hook;
132 
133 	int			boot_delay;
134 	struct callout 		boot_callout;
135 
136 	struct mtx		xpt_topo_lock;
137 	struct mtx		xpt_lock;
138 	struct taskqueue	*xpt_taskq;
139 };
140 
141 typedef enum {
142 	DM_RET_COPY		= 0x01,
143 	DM_RET_FLAG_MASK	= 0x0f,
144 	DM_RET_NONE		= 0x00,
145 	DM_RET_STOP		= 0x10,
146 	DM_RET_DESCEND		= 0x20,
147 	DM_RET_ERROR		= 0x30,
148 	DM_RET_ACTION_MASK	= 0xf0
149 } dev_match_ret;
150 
151 typedef enum {
152 	XPT_DEPTH_BUS,
153 	XPT_DEPTH_TARGET,
154 	XPT_DEPTH_DEVICE,
155 	XPT_DEPTH_PERIPH
156 } xpt_traverse_depth;
157 
158 struct xpt_traverse_config {
159 	xpt_traverse_depth	depth;
160 	void			*tr_func;
161 	void			*tr_arg;
162 };
163 
164 typedef	int	xpt_busfunc_t (struct cam_eb *bus, void *arg);
165 typedef	int	xpt_targetfunc_t (struct cam_et *target, void *arg);
166 typedef	int	xpt_devicefunc_t (struct cam_ed *device, void *arg);
167 typedef	int	xpt_periphfunc_t (struct cam_periph *periph, void *arg);
168 typedef int	xpt_pdrvfunc_t (struct periph_driver **pdrv, void *arg);
169 
170 /* Transport layer configuration information */
171 static struct xpt_softc xsoftc;
172 
173 MTX_SYSINIT(xpt_topo_init, &xsoftc.xpt_topo_lock, "XPT topology lock", MTX_DEF);
174 
175 SYSCTL_INT(_kern_cam, OID_AUTO, boot_delay, CTLFLAG_RDTUN,
176            &xsoftc.boot_delay, 0, "Bus registration wait time");
177 SYSCTL_UINT(_kern_cam, OID_AUTO, xpt_generation, CTLFLAG_RD,
178 	    &xsoftc.xpt_generation, 0, "CAM peripheral generation count");
179 SYSCTL_INT(_kern_cam, OID_AUTO, announce_nosbuf, CTLFLAG_RWTUN,
180 	    &xsoftc.announce_nosbuf, 0, "Don't use sbuf for announcements");
181 
182 struct cam_doneq {
183 	struct mtx_padalign	cam_doneq_mtx;
184 	STAILQ_HEAD(, ccb_hdr)	cam_doneq;
185 	int			cam_doneq_sleep;
186 };
187 
188 static struct cam_doneq cam_doneqs[MAXCPU];
189 static int cam_num_doneqs;
190 static struct proc *cam_proc;
191 
192 SYSCTL_INT(_kern_cam, OID_AUTO, num_doneqs, CTLFLAG_RDTUN,
193            &cam_num_doneqs, 0, "Number of completion queues/threads");
194 
195 struct cam_periph *xpt_periph;
196 
197 static periph_init_t xpt_periph_init;
198 
199 static struct periph_driver xpt_driver =
200 {
201 	xpt_periph_init, "xpt",
202 	TAILQ_HEAD_INITIALIZER(xpt_driver.units), /* generation */ 0,
203 	CAM_PERIPH_DRV_EARLY
204 };
205 
206 PERIPHDRIVER_DECLARE(xpt, xpt_driver);
207 
208 static d_open_t xptopen;
209 static d_close_t xptclose;
210 static d_ioctl_t xptioctl;
211 static d_ioctl_t xptdoioctl;
212 
213 static struct cdevsw xpt_cdevsw = {
214 	.d_version =	D_VERSION,
215 	.d_flags =	0,
216 	.d_open =	xptopen,
217 	.d_close =	xptclose,
218 	.d_ioctl =	xptioctl,
219 	.d_name =	"xpt",
220 };
221 
222 /* Storage for debugging datastructures */
223 struct cam_path *cam_dpath;
224 u_int32_t cam_dflags = CAM_DEBUG_FLAGS;
225 SYSCTL_UINT(_kern_cam, OID_AUTO, dflags, CTLFLAG_RWTUN,
226 	&cam_dflags, 0, "Enabled debug flags");
227 u_int32_t cam_debug_delay = CAM_DEBUG_DELAY;
228 SYSCTL_UINT(_kern_cam, OID_AUTO, debug_delay, CTLFLAG_RWTUN,
229 	&cam_debug_delay, 0, "Delay in us after each debug message");
230 
231 /* Our boot-time initialization hook */
232 static int cam_module_event_handler(module_t, int /*modeventtype_t*/, void *);
233 
234 static moduledata_t cam_moduledata = {
235 	"cam",
236 	cam_module_event_handler,
237 	NULL
238 };
239 
240 static int	xpt_init(void *);
241 
242 DECLARE_MODULE(cam, cam_moduledata, SI_SUB_CONFIGURE, SI_ORDER_SECOND);
243 MODULE_VERSION(cam, 1);
244 
245 
246 static void		xpt_async_bcast(struct async_list *async_head,
247 					u_int32_t async_code,
248 					struct cam_path *path,
249 					void *async_arg);
250 static path_id_t xptnextfreepathid(void);
251 static path_id_t xptpathid(const char *sim_name, int sim_unit, int sim_bus);
252 static union ccb *xpt_get_ccb(struct cam_periph *periph);
253 static union ccb *xpt_get_ccb_nowait(struct cam_periph *periph);
254 static void	 xpt_run_allocq(struct cam_periph *periph, int sleep);
255 static void	 xpt_run_allocq_task(void *context, int pending);
256 static void	 xpt_run_devq(struct cam_devq *devq);
257 static timeout_t xpt_release_devq_timeout;
258 static void	 xpt_release_simq_timeout(void *arg) __unused;
259 static void	 xpt_acquire_bus(struct cam_eb *bus);
260 static void	 xpt_release_bus(struct cam_eb *bus);
261 static uint32_t	 xpt_freeze_devq_device(struct cam_ed *dev, u_int count);
262 static int	 xpt_release_devq_device(struct cam_ed *dev, u_int count,
263 		    int run_queue);
264 static struct cam_et*
265 		 xpt_alloc_target(struct cam_eb *bus, target_id_t target_id);
266 static void	 xpt_acquire_target(struct cam_et *target);
267 static void	 xpt_release_target(struct cam_et *target);
268 static struct cam_eb*
269 		 xpt_find_bus(path_id_t path_id);
270 static struct cam_et*
271 		 xpt_find_target(struct cam_eb *bus, target_id_t target_id);
272 static struct cam_ed*
273 		 xpt_find_device(struct cam_et *target, lun_id_t lun_id);
274 static void	 xpt_config(void *arg);
275 static int	 xpt_schedule_dev(struct camq *queue, cam_pinfo *dev_pinfo,
276 				 u_int32_t new_priority);
277 static xpt_devicefunc_t xptpassannouncefunc;
278 static void	 xptaction(struct cam_sim *sim, union ccb *work_ccb);
279 static void	 xptpoll(struct cam_sim *sim);
280 static void	 camisr_runqueue(void);
281 static void	 xpt_done_process(struct ccb_hdr *ccb_h);
282 static void	 xpt_done_td(void *);
283 static dev_match_ret	xptbusmatch(struct dev_match_pattern *patterns,
284 				    u_int num_patterns, struct cam_eb *bus);
285 static dev_match_ret	xptdevicematch(struct dev_match_pattern *patterns,
286 				       u_int num_patterns,
287 				       struct cam_ed *device);
288 static dev_match_ret	xptperiphmatch(struct dev_match_pattern *patterns,
289 				       u_int num_patterns,
290 				       struct cam_periph *periph);
291 static xpt_busfunc_t	xptedtbusfunc;
292 static xpt_targetfunc_t	xptedttargetfunc;
293 static xpt_devicefunc_t	xptedtdevicefunc;
294 static xpt_periphfunc_t	xptedtperiphfunc;
295 static xpt_pdrvfunc_t	xptplistpdrvfunc;
296 static xpt_periphfunc_t	xptplistperiphfunc;
297 static int		xptedtmatch(struct ccb_dev_match *cdm);
298 static int		xptperiphlistmatch(struct ccb_dev_match *cdm);
299 static int		xptbustraverse(struct cam_eb *start_bus,
300 				       xpt_busfunc_t *tr_func, void *arg);
301 static int		xpttargettraverse(struct cam_eb *bus,
302 					  struct cam_et *start_target,
303 					  xpt_targetfunc_t *tr_func, void *arg);
304 static int		xptdevicetraverse(struct cam_et *target,
305 					  struct cam_ed *start_device,
306 					  xpt_devicefunc_t *tr_func, void *arg);
307 static int		xptperiphtraverse(struct cam_ed *device,
308 					  struct cam_periph *start_periph,
309 					  xpt_periphfunc_t *tr_func, void *arg);
310 static int		xptpdrvtraverse(struct periph_driver **start_pdrv,
311 					xpt_pdrvfunc_t *tr_func, void *arg);
312 static int		xptpdperiphtraverse(struct periph_driver **pdrv,
313 					    struct cam_periph *start_periph,
314 					    xpt_periphfunc_t *tr_func,
315 					    void *arg);
316 static xpt_busfunc_t	xptdefbusfunc;
317 static xpt_targetfunc_t	xptdeftargetfunc;
318 static xpt_devicefunc_t	xptdefdevicefunc;
319 static xpt_periphfunc_t	xptdefperiphfunc;
320 static void		xpt_finishconfig_task(void *context, int pending);
321 static void		xpt_dev_async_default(u_int32_t async_code,
322 					      struct cam_eb *bus,
323 					      struct cam_et *target,
324 					      struct cam_ed *device,
325 					      void *async_arg);
326 static struct cam_ed *	xpt_alloc_device_default(struct cam_eb *bus,
327 						 struct cam_et *target,
328 						 lun_id_t lun_id);
329 static xpt_devicefunc_t	xptsetasyncfunc;
330 static xpt_busfunc_t	xptsetasyncbusfunc;
331 static cam_status	xptregister(struct cam_periph *periph,
332 				    void *arg);
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 		bcopy(&device->mmc_ident_data,
1909 		      &cdm->matches[j].result.device_result.mmc_ident_data,
1910 		      sizeof(struct mmc_params));
1911 
1912 		/* Let the user know whether this device is unconfigured */
1913 		if (device->flags & CAM_DEV_UNCONFIGURED)
1914 			cdm->matches[j].result.device_result.flags =
1915 				DEV_RESULT_UNCONFIGURED;
1916 		else
1917 			cdm->matches[j].result.device_result.flags =
1918 				DEV_RESULT_NOFLAG;
1919 	}
1920 
1921 	/*
1922 	 * If the user isn't interested in peripherals, don't descend
1923 	 * the tree any further.
1924 	 */
1925 	if ((retval & DM_RET_ACTION_MASK) == DM_RET_STOP)
1926 		return(1);
1927 
1928 	/*
1929 	 * If there is a peripheral list generation recorded, make sure
1930 	 * it hasn't changed.
1931 	 */
1932 	xpt_lock_buses();
1933 	mtx_lock(&bus->eb_mtx);
1934 	if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
1935 	 && (cdm->pos.cookie.bus == bus)
1936 	 && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
1937 	 && (cdm->pos.cookie.target == device->target)
1938 	 && (cdm->pos.position_type & CAM_DEV_POS_DEVICE)
1939 	 && (cdm->pos.cookie.device == device)
1940 	 && (cdm->pos.position_type & CAM_DEV_POS_PERIPH)
1941 	 && (cdm->pos.cookie.periph != NULL)) {
1942 		if (cdm->pos.generations[CAM_PERIPH_GENERATION] !=
1943 		    device->generation) {
1944 			mtx_unlock(&bus->eb_mtx);
1945 			xpt_unlock_buses();
1946 			cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
1947 			return(0);
1948 		}
1949 		periph = (struct cam_periph *)cdm->pos.cookie.periph;
1950 		periph->refcount++;
1951 	} else
1952 		periph = NULL;
1953 	mtx_unlock(&bus->eb_mtx);
1954 	xpt_unlock_buses();
1955 
1956 	return (xptperiphtraverse(device, periph, xptedtperiphfunc, arg));
1957 }
1958 
1959 static int
1960 xptedtperiphfunc(struct cam_periph *periph, void *arg)
1961 {
1962 	struct ccb_dev_match *cdm;
1963 	dev_match_ret retval;
1964 
1965 	cdm = (struct ccb_dev_match *)arg;
1966 
1967 	retval = xptperiphmatch(cdm->patterns, cdm->num_patterns, periph);
1968 
1969 	if ((retval & DM_RET_ACTION_MASK) == DM_RET_ERROR) {
1970 		cdm->status = CAM_DEV_MATCH_ERROR;
1971 		return(0);
1972 	}
1973 
1974 	/*
1975 	 * If the copy flag is set, copy this peripheral out.
1976 	 */
1977 	if (retval & DM_RET_COPY) {
1978 		int spaceleft, j;
1979 
1980 		spaceleft = cdm->match_buf_len - (cdm->num_matches *
1981 			sizeof(struct dev_match_result));
1982 
1983 		/*
1984 		 * If we don't have enough space to put in another
1985 		 * match result, save our position and tell the
1986 		 * user there are more devices to check.
1987 		 */
1988 		if (spaceleft < sizeof(struct dev_match_result)) {
1989 			bzero(&cdm->pos, sizeof(cdm->pos));
1990 			cdm->pos.position_type =
1991 				CAM_DEV_POS_EDT | CAM_DEV_POS_BUS |
1992 				CAM_DEV_POS_TARGET | CAM_DEV_POS_DEVICE |
1993 				CAM_DEV_POS_PERIPH;
1994 
1995 			cdm->pos.cookie.bus = periph->path->bus;
1996 			cdm->pos.generations[CAM_BUS_GENERATION]=
1997 				xsoftc.bus_generation;
1998 			cdm->pos.cookie.target = periph->path->target;
1999 			cdm->pos.generations[CAM_TARGET_GENERATION] =
2000 				periph->path->bus->generation;
2001 			cdm->pos.cookie.device = periph->path->device;
2002 			cdm->pos.generations[CAM_DEV_GENERATION] =
2003 				periph->path->target->generation;
2004 			cdm->pos.cookie.periph = periph;
2005 			cdm->pos.generations[CAM_PERIPH_GENERATION] =
2006 				periph->path->device->generation;
2007 			cdm->status = CAM_DEV_MATCH_MORE;
2008 			return(0);
2009 		}
2010 
2011 		j = cdm->num_matches;
2012 		cdm->num_matches++;
2013 		cdm->matches[j].type = DEV_MATCH_PERIPH;
2014 		cdm->matches[j].result.periph_result.path_id =
2015 			periph->path->bus->path_id;
2016 		cdm->matches[j].result.periph_result.target_id =
2017 			periph->path->target->target_id;
2018 		cdm->matches[j].result.periph_result.target_lun =
2019 			periph->path->device->lun_id;
2020 		cdm->matches[j].result.periph_result.unit_number =
2021 			periph->unit_number;
2022 		strncpy(cdm->matches[j].result.periph_result.periph_name,
2023 			periph->periph_name, DEV_IDLEN);
2024 	}
2025 
2026 	return(1);
2027 }
2028 
2029 static int
2030 xptedtmatch(struct ccb_dev_match *cdm)
2031 {
2032 	struct cam_eb *bus;
2033 	int ret;
2034 
2035 	cdm->num_matches = 0;
2036 
2037 	/*
2038 	 * Check the bus list generation.  If it has changed, the user
2039 	 * needs to reset everything and start over.
2040 	 */
2041 	xpt_lock_buses();
2042 	if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
2043 	 && (cdm->pos.cookie.bus != NULL)) {
2044 		if (cdm->pos.generations[CAM_BUS_GENERATION] !=
2045 		    xsoftc.bus_generation) {
2046 			xpt_unlock_buses();
2047 			cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
2048 			return(0);
2049 		}
2050 		bus = (struct cam_eb *)cdm->pos.cookie.bus;
2051 		bus->refcount++;
2052 	} else
2053 		bus = NULL;
2054 	xpt_unlock_buses();
2055 
2056 	ret = xptbustraverse(bus, xptedtbusfunc, cdm);
2057 
2058 	/*
2059 	 * If we get back 0, that means that we had to stop before fully
2060 	 * traversing the EDT.  It also means that one of the subroutines
2061 	 * has set the status field to the proper value.  If we get back 1,
2062 	 * we've fully traversed the EDT and copied out any matching entries.
2063 	 */
2064 	if (ret == 1)
2065 		cdm->status = CAM_DEV_MATCH_LAST;
2066 
2067 	return(ret);
2068 }
2069 
2070 static int
2071 xptplistpdrvfunc(struct periph_driver **pdrv, void *arg)
2072 {
2073 	struct cam_periph *periph;
2074 	struct ccb_dev_match *cdm;
2075 
2076 	cdm = (struct ccb_dev_match *)arg;
2077 
2078 	xpt_lock_buses();
2079 	if ((cdm->pos.position_type & CAM_DEV_POS_PDPTR)
2080 	 && (cdm->pos.cookie.pdrv == pdrv)
2081 	 && (cdm->pos.position_type & CAM_DEV_POS_PERIPH)
2082 	 && (cdm->pos.cookie.periph != NULL)) {
2083 		if (cdm->pos.generations[CAM_PERIPH_GENERATION] !=
2084 		    (*pdrv)->generation) {
2085 			xpt_unlock_buses();
2086 			cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
2087 			return(0);
2088 		}
2089 		periph = (struct cam_periph *)cdm->pos.cookie.periph;
2090 		periph->refcount++;
2091 	} else
2092 		periph = NULL;
2093 	xpt_unlock_buses();
2094 
2095 	return (xptpdperiphtraverse(pdrv, periph, xptplistperiphfunc, arg));
2096 }
2097 
2098 static int
2099 xptplistperiphfunc(struct cam_periph *periph, void *arg)
2100 {
2101 	struct ccb_dev_match *cdm;
2102 	dev_match_ret retval;
2103 
2104 	cdm = (struct ccb_dev_match *)arg;
2105 
2106 	retval = xptperiphmatch(cdm->patterns, cdm->num_patterns, periph);
2107 
2108 	if ((retval & DM_RET_ACTION_MASK) == DM_RET_ERROR) {
2109 		cdm->status = CAM_DEV_MATCH_ERROR;
2110 		return(0);
2111 	}
2112 
2113 	/*
2114 	 * If the copy flag is set, copy this peripheral out.
2115 	 */
2116 	if (retval & DM_RET_COPY) {
2117 		int spaceleft, j;
2118 
2119 		spaceleft = cdm->match_buf_len - (cdm->num_matches *
2120 			sizeof(struct dev_match_result));
2121 
2122 		/*
2123 		 * If we don't have enough space to put in another
2124 		 * match result, save our position and tell the
2125 		 * user there are more devices to check.
2126 		 */
2127 		if (spaceleft < sizeof(struct dev_match_result)) {
2128 			struct periph_driver **pdrv;
2129 
2130 			pdrv = NULL;
2131 			bzero(&cdm->pos, sizeof(cdm->pos));
2132 			cdm->pos.position_type =
2133 				CAM_DEV_POS_PDRV | CAM_DEV_POS_PDPTR |
2134 				CAM_DEV_POS_PERIPH;
2135 
2136 			/*
2137 			 * This may look a bit non-sensical, but it is
2138 			 * actually quite logical.  There are very few
2139 			 * peripheral drivers, and bloating every peripheral
2140 			 * structure with a pointer back to its parent
2141 			 * peripheral driver linker set entry would cost
2142 			 * more in the long run than doing this quick lookup.
2143 			 */
2144 			for (pdrv = periph_drivers; *pdrv != NULL; pdrv++) {
2145 				if (strcmp((*pdrv)->driver_name,
2146 				    periph->periph_name) == 0)
2147 					break;
2148 			}
2149 
2150 			if (*pdrv == NULL) {
2151 				cdm->status = CAM_DEV_MATCH_ERROR;
2152 				return(0);
2153 			}
2154 
2155 			cdm->pos.cookie.pdrv = pdrv;
2156 			/*
2157 			 * The periph generation slot does double duty, as
2158 			 * does the periph pointer slot.  They are used for
2159 			 * both edt and pdrv lookups and positioning.
2160 			 */
2161 			cdm->pos.cookie.periph = periph;
2162 			cdm->pos.generations[CAM_PERIPH_GENERATION] =
2163 				(*pdrv)->generation;
2164 			cdm->status = CAM_DEV_MATCH_MORE;
2165 			return(0);
2166 		}
2167 
2168 		j = cdm->num_matches;
2169 		cdm->num_matches++;
2170 		cdm->matches[j].type = DEV_MATCH_PERIPH;
2171 		cdm->matches[j].result.periph_result.path_id =
2172 			periph->path->bus->path_id;
2173 
2174 		/*
2175 		 * The transport layer peripheral doesn't have a target or
2176 		 * lun.
2177 		 */
2178 		if (periph->path->target)
2179 			cdm->matches[j].result.periph_result.target_id =
2180 				periph->path->target->target_id;
2181 		else
2182 			cdm->matches[j].result.periph_result.target_id =
2183 				CAM_TARGET_WILDCARD;
2184 
2185 		if (periph->path->device)
2186 			cdm->matches[j].result.periph_result.target_lun =
2187 				periph->path->device->lun_id;
2188 		else
2189 			cdm->matches[j].result.periph_result.target_lun =
2190 				CAM_LUN_WILDCARD;
2191 
2192 		cdm->matches[j].result.periph_result.unit_number =
2193 			periph->unit_number;
2194 		strncpy(cdm->matches[j].result.periph_result.periph_name,
2195 			periph->periph_name, DEV_IDLEN);
2196 	}
2197 
2198 	return(1);
2199 }
2200 
2201 static int
2202 xptperiphlistmatch(struct ccb_dev_match *cdm)
2203 {
2204 	int ret;
2205 
2206 	cdm->num_matches = 0;
2207 
2208 	/*
2209 	 * At this point in the edt traversal function, we check the bus
2210 	 * list generation to make sure that no buses have been added or
2211 	 * removed since the user last sent a XPT_DEV_MATCH ccb through.
2212 	 * For the peripheral driver list traversal function, however, we
2213 	 * don't have to worry about new peripheral driver types coming or
2214 	 * going; they're in a linker set, and therefore can't change
2215 	 * without a recompile.
2216 	 */
2217 
2218 	if ((cdm->pos.position_type & CAM_DEV_POS_PDPTR)
2219 	 && (cdm->pos.cookie.pdrv != NULL))
2220 		ret = xptpdrvtraverse(
2221 				(struct periph_driver **)cdm->pos.cookie.pdrv,
2222 				xptplistpdrvfunc, cdm);
2223 	else
2224 		ret = xptpdrvtraverse(NULL, xptplistpdrvfunc, cdm);
2225 
2226 	/*
2227 	 * If we get back 0, that means that we had to stop before fully
2228 	 * traversing the peripheral driver tree.  It also means that one of
2229 	 * the subroutines has set the status field to the proper value.  If
2230 	 * we get back 1, we've fully traversed the EDT and copied out any
2231 	 * matching entries.
2232 	 */
2233 	if (ret == 1)
2234 		cdm->status = CAM_DEV_MATCH_LAST;
2235 
2236 	return(ret);
2237 }
2238 
2239 static int
2240 xptbustraverse(struct cam_eb *start_bus, xpt_busfunc_t *tr_func, void *arg)
2241 {
2242 	struct cam_eb *bus, *next_bus;
2243 	int retval;
2244 
2245 	retval = 1;
2246 	if (start_bus)
2247 		bus = start_bus;
2248 	else {
2249 		xpt_lock_buses();
2250 		bus = TAILQ_FIRST(&xsoftc.xpt_busses);
2251 		if (bus == NULL) {
2252 			xpt_unlock_buses();
2253 			return (retval);
2254 		}
2255 		bus->refcount++;
2256 		xpt_unlock_buses();
2257 	}
2258 	for (; bus != NULL; bus = next_bus) {
2259 		retval = tr_func(bus, arg);
2260 		if (retval == 0) {
2261 			xpt_release_bus(bus);
2262 			break;
2263 		}
2264 		xpt_lock_buses();
2265 		next_bus = TAILQ_NEXT(bus, links);
2266 		if (next_bus)
2267 			next_bus->refcount++;
2268 		xpt_unlock_buses();
2269 		xpt_release_bus(bus);
2270 	}
2271 	return(retval);
2272 }
2273 
2274 static int
2275 xpttargettraverse(struct cam_eb *bus, struct cam_et *start_target,
2276 		  xpt_targetfunc_t *tr_func, void *arg)
2277 {
2278 	struct cam_et *target, *next_target;
2279 	int retval;
2280 
2281 	retval = 1;
2282 	if (start_target)
2283 		target = start_target;
2284 	else {
2285 		mtx_lock(&bus->eb_mtx);
2286 		target = TAILQ_FIRST(&bus->et_entries);
2287 		if (target == NULL) {
2288 			mtx_unlock(&bus->eb_mtx);
2289 			return (retval);
2290 		}
2291 		target->refcount++;
2292 		mtx_unlock(&bus->eb_mtx);
2293 	}
2294 	for (; target != NULL; target = next_target) {
2295 		retval = tr_func(target, arg);
2296 		if (retval == 0) {
2297 			xpt_release_target(target);
2298 			break;
2299 		}
2300 		mtx_lock(&bus->eb_mtx);
2301 		next_target = TAILQ_NEXT(target, links);
2302 		if (next_target)
2303 			next_target->refcount++;
2304 		mtx_unlock(&bus->eb_mtx);
2305 		xpt_release_target(target);
2306 	}
2307 	return(retval);
2308 }
2309 
2310 static int
2311 xptdevicetraverse(struct cam_et *target, struct cam_ed *start_device,
2312 		  xpt_devicefunc_t *tr_func, void *arg)
2313 {
2314 	struct cam_eb *bus;
2315 	struct cam_ed *device, *next_device;
2316 	int retval;
2317 
2318 	retval = 1;
2319 	bus = target->bus;
2320 	if (start_device)
2321 		device = start_device;
2322 	else {
2323 		mtx_lock(&bus->eb_mtx);
2324 		device = TAILQ_FIRST(&target->ed_entries);
2325 		if (device == NULL) {
2326 			mtx_unlock(&bus->eb_mtx);
2327 			return (retval);
2328 		}
2329 		device->refcount++;
2330 		mtx_unlock(&bus->eb_mtx);
2331 	}
2332 	for (; device != NULL; device = next_device) {
2333 		mtx_lock(&device->device_mtx);
2334 		retval = tr_func(device, arg);
2335 		mtx_unlock(&device->device_mtx);
2336 		if (retval == 0) {
2337 			xpt_release_device(device);
2338 			break;
2339 		}
2340 		mtx_lock(&bus->eb_mtx);
2341 		next_device = TAILQ_NEXT(device, links);
2342 		if (next_device)
2343 			next_device->refcount++;
2344 		mtx_unlock(&bus->eb_mtx);
2345 		xpt_release_device(device);
2346 	}
2347 	return(retval);
2348 }
2349 
2350 static int
2351 xptperiphtraverse(struct cam_ed *device, struct cam_periph *start_periph,
2352 		  xpt_periphfunc_t *tr_func, void *arg)
2353 {
2354 	struct cam_eb *bus;
2355 	struct cam_periph *periph, *next_periph;
2356 	int retval;
2357 
2358 	retval = 1;
2359 
2360 	bus = device->target->bus;
2361 	if (start_periph)
2362 		periph = start_periph;
2363 	else {
2364 		xpt_lock_buses();
2365 		mtx_lock(&bus->eb_mtx);
2366 		periph = SLIST_FIRST(&device->periphs);
2367 		while (periph != NULL && (periph->flags & CAM_PERIPH_FREE) != 0)
2368 			periph = SLIST_NEXT(periph, periph_links);
2369 		if (periph == NULL) {
2370 			mtx_unlock(&bus->eb_mtx);
2371 			xpt_unlock_buses();
2372 			return (retval);
2373 		}
2374 		periph->refcount++;
2375 		mtx_unlock(&bus->eb_mtx);
2376 		xpt_unlock_buses();
2377 	}
2378 	for (; periph != NULL; periph = next_periph) {
2379 		retval = tr_func(periph, arg);
2380 		if (retval == 0) {
2381 			cam_periph_release_locked(periph);
2382 			break;
2383 		}
2384 		xpt_lock_buses();
2385 		mtx_lock(&bus->eb_mtx);
2386 		next_periph = SLIST_NEXT(periph, periph_links);
2387 		while (next_periph != NULL &&
2388 		    (next_periph->flags & CAM_PERIPH_FREE) != 0)
2389 			next_periph = SLIST_NEXT(next_periph, periph_links);
2390 		if (next_periph)
2391 			next_periph->refcount++;
2392 		mtx_unlock(&bus->eb_mtx);
2393 		xpt_unlock_buses();
2394 		cam_periph_release_locked(periph);
2395 	}
2396 	return(retval);
2397 }
2398 
2399 static int
2400 xptpdrvtraverse(struct periph_driver **start_pdrv,
2401 		xpt_pdrvfunc_t *tr_func, void *arg)
2402 {
2403 	struct periph_driver **pdrv;
2404 	int retval;
2405 
2406 	retval = 1;
2407 
2408 	/*
2409 	 * We don't traverse the peripheral driver list like we do the
2410 	 * other lists, because it is a linker set, and therefore cannot be
2411 	 * changed during runtime.  If the peripheral driver list is ever
2412 	 * re-done to be something other than a linker set (i.e. it can
2413 	 * change while the system is running), the list traversal should
2414 	 * be modified to work like the other traversal functions.
2415 	 */
2416 	for (pdrv = (start_pdrv ? start_pdrv : periph_drivers);
2417 	     *pdrv != NULL; pdrv++) {
2418 		retval = tr_func(pdrv, arg);
2419 
2420 		if (retval == 0)
2421 			return(retval);
2422 	}
2423 
2424 	return(retval);
2425 }
2426 
2427 static int
2428 xptpdperiphtraverse(struct periph_driver **pdrv,
2429 		    struct cam_periph *start_periph,
2430 		    xpt_periphfunc_t *tr_func, void *arg)
2431 {
2432 	struct cam_periph *periph, *next_periph;
2433 	int retval;
2434 
2435 	retval = 1;
2436 
2437 	if (start_periph)
2438 		periph = start_periph;
2439 	else {
2440 		xpt_lock_buses();
2441 		periph = TAILQ_FIRST(&(*pdrv)->units);
2442 		while (periph != NULL && (periph->flags & CAM_PERIPH_FREE) != 0)
2443 			periph = TAILQ_NEXT(periph, unit_links);
2444 		if (periph == NULL) {
2445 			xpt_unlock_buses();
2446 			return (retval);
2447 		}
2448 		periph->refcount++;
2449 		xpt_unlock_buses();
2450 	}
2451 	for (; periph != NULL; periph = next_periph) {
2452 		cam_periph_lock(periph);
2453 		retval = tr_func(periph, arg);
2454 		cam_periph_unlock(periph);
2455 		if (retval == 0) {
2456 			cam_periph_release(periph);
2457 			break;
2458 		}
2459 		xpt_lock_buses();
2460 		next_periph = TAILQ_NEXT(periph, unit_links);
2461 		while (next_periph != NULL &&
2462 		    (next_periph->flags & CAM_PERIPH_FREE) != 0)
2463 			next_periph = TAILQ_NEXT(next_periph, unit_links);
2464 		if (next_periph)
2465 			next_periph->refcount++;
2466 		xpt_unlock_buses();
2467 		cam_periph_release(periph);
2468 	}
2469 	return(retval);
2470 }
2471 
2472 static int
2473 xptdefbusfunc(struct cam_eb *bus, void *arg)
2474 {
2475 	struct xpt_traverse_config *tr_config;
2476 
2477 	tr_config = (struct xpt_traverse_config *)arg;
2478 
2479 	if (tr_config->depth == XPT_DEPTH_BUS) {
2480 		xpt_busfunc_t *tr_func;
2481 
2482 		tr_func = (xpt_busfunc_t *)tr_config->tr_func;
2483 
2484 		return(tr_func(bus, tr_config->tr_arg));
2485 	} else
2486 		return(xpttargettraverse(bus, NULL, xptdeftargetfunc, arg));
2487 }
2488 
2489 static int
2490 xptdeftargetfunc(struct cam_et *target, void *arg)
2491 {
2492 	struct xpt_traverse_config *tr_config;
2493 
2494 	tr_config = (struct xpt_traverse_config *)arg;
2495 
2496 	if (tr_config->depth == XPT_DEPTH_TARGET) {
2497 		xpt_targetfunc_t *tr_func;
2498 
2499 		tr_func = (xpt_targetfunc_t *)tr_config->tr_func;
2500 
2501 		return(tr_func(target, tr_config->tr_arg));
2502 	} else
2503 		return(xptdevicetraverse(target, NULL, xptdefdevicefunc, arg));
2504 }
2505 
2506 static int
2507 xptdefdevicefunc(struct cam_ed *device, void *arg)
2508 {
2509 	struct xpt_traverse_config *tr_config;
2510 
2511 	tr_config = (struct xpt_traverse_config *)arg;
2512 
2513 	if (tr_config->depth == XPT_DEPTH_DEVICE) {
2514 		xpt_devicefunc_t *tr_func;
2515 
2516 		tr_func = (xpt_devicefunc_t *)tr_config->tr_func;
2517 
2518 		return(tr_func(device, tr_config->tr_arg));
2519 	} else
2520 		return(xptperiphtraverse(device, NULL, xptdefperiphfunc, arg));
2521 }
2522 
2523 static int
2524 xptdefperiphfunc(struct cam_periph *periph, void *arg)
2525 {
2526 	struct xpt_traverse_config *tr_config;
2527 	xpt_periphfunc_t *tr_func;
2528 
2529 	tr_config = (struct xpt_traverse_config *)arg;
2530 
2531 	tr_func = (xpt_periphfunc_t *)tr_config->tr_func;
2532 
2533 	/*
2534 	 * Unlike the other default functions, we don't check for depth
2535 	 * here.  The peripheral driver level is the last level in the EDT,
2536 	 * so if we're here, we should execute the function in question.
2537 	 */
2538 	return(tr_func(periph, tr_config->tr_arg));
2539 }
2540 
2541 /*
2542  * Execute the given function for every bus in the EDT.
2543  */
2544 static int
2545 xpt_for_all_busses(xpt_busfunc_t *tr_func, void *arg)
2546 {
2547 	struct xpt_traverse_config tr_config;
2548 
2549 	tr_config.depth = XPT_DEPTH_BUS;
2550 	tr_config.tr_func = tr_func;
2551 	tr_config.tr_arg = arg;
2552 
2553 	return(xptbustraverse(NULL, xptdefbusfunc, &tr_config));
2554 }
2555 
2556 /*
2557  * Execute the given function for every device in the EDT.
2558  */
2559 static int
2560 xpt_for_all_devices(xpt_devicefunc_t *tr_func, void *arg)
2561 {
2562 	struct xpt_traverse_config tr_config;
2563 
2564 	tr_config.depth = XPT_DEPTH_DEVICE;
2565 	tr_config.tr_func = tr_func;
2566 	tr_config.tr_arg = arg;
2567 
2568 	return(xptbustraverse(NULL, xptdefbusfunc, &tr_config));
2569 }
2570 
2571 static int
2572 xptsetasyncfunc(struct cam_ed *device, void *arg)
2573 {
2574 	struct cam_path path;
2575 	struct ccb_getdev cgd;
2576 	struct ccb_setasync *csa = (struct ccb_setasync *)arg;
2577 
2578 	/*
2579 	 * Don't report unconfigured devices (Wildcard devs,
2580 	 * devices only for target mode, device instances
2581 	 * that have been invalidated but are waiting for
2582 	 * their last reference count to be released).
2583 	 */
2584 	if ((device->flags & CAM_DEV_UNCONFIGURED) != 0)
2585 		return (1);
2586 
2587 	xpt_compile_path(&path,
2588 			 NULL,
2589 			 device->target->bus->path_id,
2590 			 device->target->target_id,
2591 			 device->lun_id);
2592 	xpt_setup_ccb(&cgd.ccb_h, &path, CAM_PRIORITY_NORMAL);
2593 	cgd.ccb_h.func_code = XPT_GDEV_TYPE;
2594 	xpt_action((union ccb *)&cgd);
2595 	csa->callback(csa->callback_arg,
2596 			    AC_FOUND_DEVICE,
2597 			    &path, &cgd);
2598 	xpt_release_path(&path);
2599 
2600 	return(1);
2601 }
2602 
2603 static int
2604 xptsetasyncbusfunc(struct cam_eb *bus, void *arg)
2605 {
2606 	struct cam_path path;
2607 	struct ccb_pathinq cpi;
2608 	struct ccb_setasync *csa = (struct ccb_setasync *)arg;
2609 
2610 	xpt_compile_path(&path, /*periph*/NULL,
2611 			 bus->path_id,
2612 			 CAM_TARGET_WILDCARD,
2613 			 CAM_LUN_WILDCARD);
2614 	xpt_path_lock(&path);
2615 	xpt_setup_ccb(&cpi.ccb_h, &path, CAM_PRIORITY_NORMAL);
2616 	cpi.ccb_h.func_code = XPT_PATH_INQ;
2617 	xpt_action((union ccb *)&cpi);
2618 	csa->callback(csa->callback_arg,
2619 			    AC_PATH_REGISTERED,
2620 			    &path, &cpi);
2621 	xpt_path_unlock(&path);
2622 	xpt_release_path(&path);
2623 
2624 	return(1);
2625 }
2626 
2627 void
2628 xpt_action(union ccb *start_ccb)
2629 {
2630 
2631 	CAM_DEBUG(start_ccb->ccb_h.path, CAM_DEBUG_TRACE,
2632 	    ("xpt_action: func %#x %s\n", start_ccb->ccb_h.func_code,
2633 		xpt_action_name(start_ccb->ccb_h.func_code)));
2634 
2635 	start_ccb->ccb_h.status = CAM_REQ_INPROG;
2636 	(*(start_ccb->ccb_h.path->bus->xport->ops->action))(start_ccb);
2637 }
2638 
2639 void
2640 xpt_action_default(union ccb *start_ccb)
2641 {
2642 	struct cam_path *path;
2643 	struct cam_sim *sim;
2644 	struct mtx *mtx;
2645 
2646 	path = start_ccb->ccb_h.path;
2647 	CAM_DEBUG(path, CAM_DEBUG_TRACE,
2648 	    ("xpt_action_default: func %#x %s\n", start_ccb->ccb_h.func_code,
2649 		xpt_action_name(start_ccb->ccb_h.func_code)));
2650 
2651 	switch (start_ccb->ccb_h.func_code) {
2652 	case XPT_SCSI_IO:
2653 	{
2654 		struct cam_ed *device;
2655 
2656 		/*
2657 		 * For the sake of compatibility with SCSI-1
2658 		 * devices that may not understand the identify
2659 		 * message, we include lun information in the
2660 		 * second byte of all commands.  SCSI-1 specifies
2661 		 * that luns are a 3 bit value and reserves only 3
2662 		 * bits for lun information in the CDB.  Later
2663 		 * revisions of the SCSI spec allow for more than 8
2664 		 * luns, but have deprecated lun information in the
2665 		 * CDB.  So, if the lun won't fit, we must omit.
2666 		 *
2667 		 * Also be aware that during initial probing for devices,
2668 		 * the inquiry information is unknown but initialized to 0.
2669 		 * This means that this code will be exercised while probing
2670 		 * devices with an ANSI revision greater than 2.
2671 		 */
2672 		device = path->device;
2673 		if (device->protocol_version <= SCSI_REV_2
2674 		 && start_ccb->ccb_h.target_lun < 8
2675 		 && (start_ccb->ccb_h.flags & CAM_CDB_POINTER) == 0) {
2676 
2677 			start_ccb->csio.cdb_io.cdb_bytes[1] |=
2678 			    start_ccb->ccb_h.target_lun << 5;
2679 		}
2680 		start_ccb->csio.scsi_status = SCSI_STATUS_OK;
2681 	}
2682 	/* FALLTHROUGH */
2683 	case XPT_TARGET_IO:
2684 	case XPT_CONT_TARGET_IO:
2685 		start_ccb->csio.sense_resid = 0;
2686 		start_ccb->csio.resid = 0;
2687 		/* FALLTHROUGH */
2688 	case XPT_ATA_IO:
2689 		if (start_ccb->ccb_h.func_code == XPT_ATA_IO)
2690 			start_ccb->ataio.resid = 0;
2691 		/* FALLTHROUGH */
2692 	case XPT_NVME_IO:
2693 		/* FALLTHROUGH */
2694 	case XPT_NVME_ADMIN:
2695 		/* FALLTHROUGH */
2696 	case XPT_MMC_IO:
2697 		/* XXX just like nmve_io? */
2698 	case XPT_RESET_DEV:
2699 	case XPT_ENG_EXEC:
2700 	case XPT_SMP_IO:
2701 	{
2702 		struct cam_devq *devq;
2703 
2704 		devq = path->bus->sim->devq;
2705 		mtx_lock(&devq->send_mtx);
2706 		cam_ccbq_insert_ccb(&path->device->ccbq, start_ccb);
2707 		if (xpt_schedule_devq(devq, path->device) != 0)
2708 			xpt_run_devq(devq);
2709 		mtx_unlock(&devq->send_mtx);
2710 		break;
2711 	}
2712 	case XPT_CALC_GEOMETRY:
2713 		/* Filter out garbage */
2714 		if (start_ccb->ccg.block_size == 0
2715 		 || start_ccb->ccg.volume_size == 0) {
2716 			start_ccb->ccg.cylinders = 0;
2717 			start_ccb->ccg.heads = 0;
2718 			start_ccb->ccg.secs_per_track = 0;
2719 			start_ccb->ccb_h.status = CAM_REQ_CMP;
2720 			break;
2721 		}
2722 #if defined(__sparc64__)
2723 		/*
2724 		 * For sparc64, we may need adjust the geometry of large
2725 		 * disks in order to fit the limitations of the 16-bit
2726 		 * fields of the VTOC8 disk label.
2727 		 */
2728 		if (scsi_da_bios_params(&start_ccb->ccg) != 0) {
2729 			start_ccb->ccb_h.status = CAM_REQ_CMP;
2730 			break;
2731 		}
2732 #endif
2733 		goto call_sim;
2734 	case XPT_ABORT:
2735 	{
2736 		union ccb* abort_ccb;
2737 
2738 		abort_ccb = start_ccb->cab.abort_ccb;
2739 		if (XPT_FC_IS_DEV_QUEUED(abort_ccb)) {
2740 			struct cam_ed *device;
2741 			struct cam_devq *devq;
2742 
2743 			device = abort_ccb->ccb_h.path->device;
2744 			devq = device->sim->devq;
2745 
2746 			mtx_lock(&devq->send_mtx);
2747 			if (abort_ccb->ccb_h.pinfo.index > 0) {
2748 				cam_ccbq_remove_ccb(&device->ccbq, abort_ccb);
2749 				abort_ccb->ccb_h.status =
2750 				    CAM_REQ_ABORTED|CAM_DEV_QFRZN;
2751 				xpt_freeze_devq_device(device, 1);
2752 				mtx_unlock(&devq->send_mtx);
2753 				xpt_done(abort_ccb);
2754 				start_ccb->ccb_h.status = CAM_REQ_CMP;
2755 				break;
2756 			}
2757 			mtx_unlock(&devq->send_mtx);
2758 
2759 			if (abort_ccb->ccb_h.pinfo.index == CAM_UNQUEUED_INDEX
2760 			 && (abort_ccb->ccb_h.status & CAM_SIM_QUEUED) == 0) {
2761 				/*
2762 				 * We've caught this ccb en route to
2763 				 * the SIM.  Flag it for abort and the
2764 				 * SIM will do so just before starting
2765 				 * real work on the CCB.
2766 				 */
2767 				abort_ccb->ccb_h.status =
2768 				    CAM_REQ_ABORTED|CAM_DEV_QFRZN;
2769 				xpt_freeze_devq(abort_ccb->ccb_h.path, 1);
2770 				start_ccb->ccb_h.status = CAM_REQ_CMP;
2771 				break;
2772 			}
2773 		}
2774 		if (XPT_FC_IS_QUEUED(abort_ccb)
2775 		 && (abort_ccb->ccb_h.pinfo.index == CAM_DONEQ_INDEX)) {
2776 			/*
2777 			 * It's already completed but waiting
2778 			 * for our SWI to get to it.
2779 			 */
2780 			start_ccb->ccb_h.status = CAM_UA_ABORT;
2781 			break;
2782 		}
2783 		/*
2784 		 * If we weren't able to take care of the abort request
2785 		 * in the XPT, pass the request down to the SIM for processing.
2786 		 */
2787 	}
2788 	/* FALLTHROUGH */
2789 	case XPT_ACCEPT_TARGET_IO:
2790 	case XPT_EN_LUN:
2791 	case XPT_IMMED_NOTIFY:
2792 	case XPT_NOTIFY_ACK:
2793 	case XPT_RESET_BUS:
2794 	case XPT_IMMEDIATE_NOTIFY:
2795 	case XPT_NOTIFY_ACKNOWLEDGE:
2796 	case XPT_GET_SIM_KNOB_OLD:
2797 	case XPT_GET_SIM_KNOB:
2798 	case XPT_SET_SIM_KNOB:
2799 	case XPT_GET_TRAN_SETTINGS:
2800 	case XPT_SET_TRAN_SETTINGS:
2801 	case XPT_PATH_INQ:
2802 call_sim:
2803 		sim = path->bus->sim;
2804 		mtx = sim->mtx;
2805 		if (mtx && !mtx_owned(mtx))
2806 			mtx_lock(mtx);
2807 		else
2808 			mtx = NULL;
2809 
2810 		CAM_DEBUG(path, CAM_DEBUG_TRACE,
2811 		    ("Calling sim->sim_action(): func=%#x\n", start_ccb->ccb_h.func_code));
2812 		(*(sim->sim_action))(sim, start_ccb);
2813 		CAM_DEBUG(path, CAM_DEBUG_TRACE,
2814 		    ("sim->sim_action returned: status=%#x\n", start_ccb->ccb_h.status));
2815 		if (mtx)
2816 			mtx_unlock(mtx);
2817 		break;
2818 	case XPT_PATH_STATS:
2819 		start_ccb->cpis.last_reset = path->bus->last_reset;
2820 		start_ccb->ccb_h.status = CAM_REQ_CMP;
2821 		break;
2822 	case XPT_GDEV_TYPE:
2823 	{
2824 		struct cam_ed *dev;
2825 
2826 		dev = path->device;
2827 		if ((dev->flags & CAM_DEV_UNCONFIGURED) != 0) {
2828 			start_ccb->ccb_h.status = CAM_DEV_NOT_THERE;
2829 		} else {
2830 			struct ccb_getdev *cgd;
2831 
2832 			cgd = &start_ccb->cgd;
2833 			cgd->protocol = dev->protocol;
2834 			cgd->inq_data = dev->inq_data;
2835 			cgd->ident_data = dev->ident_data;
2836 			cgd->inq_flags = dev->inq_flags;
2837 			cgd->ccb_h.status = CAM_REQ_CMP;
2838 			cgd->serial_num_len = dev->serial_num_len;
2839 			if ((dev->serial_num_len > 0)
2840 			 && (dev->serial_num != NULL))
2841 				bcopy(dev->serial_num, cgd->serial_num,
2842 				      dev->serial_num_len);
2843 		}
2844 		break;
2845 	}
2846 	case XPT_GDEV_STATS:
2847 	{
2848 		struct ccb_getdevstats *cgds = &start_ccb->cgds;
2849 		struct cam_ed *dev = path->device;
2850 		struct cam_eb *bus = path->bus;
2851 		struct cam_et *tar = path->target;
2852 		struct cam_devq *devq = bus->sim->devq;
2853 
2854 		mtx_lock(&devq->send_mtx);
2855 		cgds->dev_openings = dev->ccbq.dev_openings;
2856 		cgds->dev_active = dev->ccbq.dev_active;
2857 		cgds->allocated = dev->ccbq.allocated;
2858 		cgds->queued = cam_ccbq_pending_ccb_count(&dev->ccbq);
2859 		cgds->held = cgds->allocated - cgds->dev_active - cgds->queued;
2860 		cgds->last_reset = tar->last_reset;
2861 		cgds->maxtags = dev->maxtags;
2862 		cgds->mintags = dev->mintags;
2863 		if (timevalcmp(&tar->last_reset, &bus->last_reset, <))
2864 			cgds->last_reset = bus->last_reset;
2865 		mtx_unlock(&devq->send_mtx);
2866 		cgds->ccb_h.status = CAM_REQ_CMP;
2867 		break;
2868 	}
2869 	case XPT_GDEVLIST:
2870 	{
2871 		struct cam_periph	*nperiph;
2872 		struct periph_list	*periph_head;
2873 		struct ccb_getdevlist	*cgdl;
2874 		u_int			i;
2875 		struct cam_ed		*device;
2876 		int			found;
2877 
2878 
2879 		found = 0;
2880 
2881 		/*
2882 		 * Don't want anyone mucking with our data.
2883 		 */
2884 		device = path->device;
2885 		periph_head = &device->periphs;
2886 		cgdl = &start_ccb->cgdl;
2887 
2888 		/*
2889 		 * Check and see if the list has changed since the user
2890 		 * last requested a list member.  If so, tell them that the
2891 		 * list has changed, and therefore they need to start over
2892 		 * from the beginning.
2893 		 */
2894 		if ((cgdl->index != 0) &&
2895 		    (cgdl->generation != device->generation)) {
2896 			cgdl->status = CAM_GDEVLIST_LIST_CHANGED;
2897 			break;
2898 		}
2899 
2900 		/*
2901 		 * Traverse the list of peripherals and attempt to find
2902 		 * the requested peripheral.
2903 		 */
2904 		for (nperiph = SLIST_FIRST(periph_head), i = 0;
2905 		     (nperiph != NULL) && (i <= cgdl->index);
2906 		     nperiph = SLIST_NEXT(nperiph, periph_links), i++) {
2907 			if (i == cgdl->index) {
2908 				strncpy(cgdl->periph_name,
2909 					nperiph->periph_name,
2910 					DEV_IDLEN);
2911 				cgdl->unit_number = nperiph->unit_number;
2912 				found = 1;
2913 			}
2914 		}
2915 		if (found == 0) {
2916 			cgdl->status = CAM_GDEVLIST_ERROR;
2917 			break;
2918 		}
2919 
2920 		if (nperiph == NULL)
2921 			cgdl->status = CAM_GDEVLIST_LAST_DEVICE;
2922 		else
2923 			cgdl->status = CAM_GDEVLIST_MORE_DEVS;
2924 
2925 		cgdl->index++;
2926 		cgdl->generation = device->generation;
2927 
2928 		cgdl->ccb_h.status = CAM_REQ_CMP;
2929 		break;
2930 	}
2931 	case XPT_DEV_MATCH:
2932 	{
2933 		dev_pos_type position_type;
2934 		struct ccb_dev_match *cdm;
2935 
2936 		cdm = &start_ccb->cdm;
2937 
2938 		/*
2939 		 * There are two ways of getting at information in the EDT.
2940 		 * The first way is via the primary EDT tree.  It starts
2941 		 * with a list of buses, then a list of targets on a bus,
2942 		 * then devices/luns on a target, and then peripherals on a
2943 		 * device/lun.  The "other" way is by the peripheral driver
2944 		 * lists.  The peripheral driver lists are organized by
2945 		 * peripheral driver.  (obviously)  So it makes sense to
2946 		 * use the peripheral driver list if the user is looking
2947 		 * for something like "da1", or all "da" devices.  If the
2948 		 * user is looking for something on a particular bus/target
2949 		 * or lun, it's generally better to go through the EDT tree.
2950 		 */
2951 
2952 		if (cdm->pos.position_type != CAM_DEV_POS_NONE)
2953 			position_type = cdm->pos.position_type;
2954 		else {
2955 			u_int i;
2956 
2957 			position_type = CAM_DEV_POS_NONE;
2958 
2959 			for (i = 0; i < cdm->num_patterns; i++) {
2960 				if ((cdm->patterns[i].type == DEV_MATCH_BUS)
2961 				 ||(cdm->patterns[i].type == DEV_MATCH_DEVICE)){
2962 					position_type = CAM_DEV_POS_EDT;
2963 					break;
2964 				}
2965 			}
2966 
2967 			if (cdm->num_patterns == 0)
2968 				position_type = CAM_DEV_POS_EDT;
2969 			else if (position_type == CAM_DEV_POS_NONE)
2970 				position_type = CAM_DEV_POS_PDRV;
2971 		}
2972 
2973 		switch(position_type & CAM_DEV_POS_TYPEMASK) {
2974 		case CAM_DEV_POS_EDT:
2975 			xptedtmatch(cdm);
2976 			break;
2977 		case CAM_DEV_POS_PDRV:
2978 			xptperiphlistmatch(cdm);
2979 			break;
2980 		default:
2981 			cdm->status = CAM_DEV_MATCH_ERROR;
2982 			break;
2983 		}
2984 
2985 		if (cdm->status == CAM_DEV_MATCH_ERROR)
2986 			start_ccb->ccb_h.status = CAM_REQ_CMP_ERR;
2987 		else
2988 			start_ccb->ccb_h.status = CAM_REQ_CMP;
2989 
2990 		break;
2991 	}
2992 	case XPT_SASYNC_CB:
2993 	{
2994 		struct ccb_setasync *csa;
2995 		struct async_node *cur_entry;
2996 		struct async_list *async_head;
2997 		u_int32_t added;
2998 
2999 		csa = &start_ccb->csa;
3000 		added = csa->event_enable;
3001 		async_head = &path->device->asyncs;
3002 
3003 		/*
3004 		 * If there is already an entry for us, simply
3005 		 * update it.
3006 		 */
3007 		cur_entry = SLIST_FIRST(async_head);
3008 		while (cur_entry != NULL) {
3009 			if ((cur_entry->callback_arg == csa->callback_arg)
3010 			 && (cur_entry->callback == csa->callback))
3011 				break;
3012 			cur_entry = SLIST_NEXT(cur_entry, links);
3013 		}
3014 
3015 		if (cur_entry != NULL) {
3016 		 	/*
3017 			 * If the request has no flags set,
3018 			 * remove the entry.
3019 			 */
3020 			added &= ~cur_entry->event_enable;
3021 			if (csa->event_enable == 0) {
3022 				SLIST_REMOVE(async_head, cur_entry,
3023 					     async_node, links);
3024 				xpt_release_device(path->device);
3025 				free(cur_entry, M_CAMXPT);
3026 			} else {
3027 				cur_entry->event_enable = csa->event_enable;
3028 			}
3029 			csa->event_enable = added;
3030 		} else {
3031 			cur_entry = malloc(sizeof(*cur_entry), M_CAMXPT,
3032 					   M_NOWAIT);
3033 			if (cur_entry == NULL) {
3034 				csa->ccb_h.status = CAM_RESRC_UNAVAIL;
3035 				break;
3036 			}
3037 			cur_entry->event_enable = csa->event_enable;
3038 			cur_entry->event_lock = (path->bus->sim->mtx &&
3039 			    mtx_owned(path->bus->sim->mtx)) ? 1 : 0;
3040 			cur_entry->callback_arg = csa->callback_arg;
3041 			cur_entry->callback = csa->callback;
3042 			SLIST_INSERT_HEAD(async_head, cur_entry, links);
3043 			xpt_acquire_device(path->device);
3044 		}
3045 		start_ccb->ccb_h.status = CAM_REQ_CMP;
3046 		break;
3047 	}
3048 	case XPT_REL_SIMQ:
3049 	{
3050 		struct ccb_relsim *crs;
3051 		struct cam_ed *dev;
3052 
3053 		crs = &start_ccb->crs;
3054 		dev = path->device;
3055 		if (dev == NULL) {
3056 
3057 			crs->ccb_h.status = CAM_DEV_NOT_THERE;
3058 			break;
3059 		}
3060 
3061 		if ((crs->release_flags & RELSIM_ADJUST_OPENINGS) != 0) {
3062 
3063 			/* Don't ever go below one opening */
3064 			if (crs->openings > 0) {
3065 				xpt_dev_ccbq_resize(path, crs->openings);
3066 				if (bootverbose) {
3067 					xpt_print(path,
3068 					    "number of openings is now %d\n",
3069 					    crs->openings);
3070 				}
3071 			}
3072 		}
3073 
3074 		mtx_lock(&dev->sim->devq->send_mtx);
3075 		if ((crs->release_flags & RELSIM_RELEASE_AFTER_TIMEOUT) != 0) {
3076 
3077 			if ((dev->flags & CAM_DEV_REL_TIMEOUT_PENDING) != 0) {
3078 
3079 				/*
3080 				 * Just extend the old timeout and decrement
3081 				 * the freeze count so that a single timeout
3082 				 * is sufficient for releasing the queue.
3083 				 */
3084 				start_ccb->ccb_h.flags &= ~CAM_DEV_QFREEZE;
3085 				callout_stop(&dev->callout);
3086 			} else {
3087 
3088 				start_ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
3089 			}
3090 
3091 			callout_reset_sbt(&dev->callout,
3092 			    SBT_1MS * crs->release_timeout, 0,
3093 			    xpt_release_devq_timeout, dev, 0);
3094 
3095 			dev->flags |= CAM_DEV_REL_TIMEOUT_PENDING;
3096 
3097 		}
3098 
3099 		if ((crs->release_flags & RELSIM_RELEASE_AFTER_CMDCMPLT) != 0) {
3100 
3101 			if ((dev->flags & CAM_DEV_REL_ON_COMPLETE) != 0) {
3102 				/*
3103 				 * Decrement the freeze count so that a single
3104 				 * completion is still sufficient to unfreeze
3105 				 * the queue.
3106 				 */
3107 				start_ccb->ccb_h.flags &= ~CAM_DEV_QFREEZE;
3108 			} else {
3109 
3110 				dev->flags |= CAM_DEV_REL_ON_COMPLETE;
3111 				start_ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
3112 			}
3113 		}
3114 
3115 		if ((crs->release_flags & RELSIM_RELEASE_AFTER_QEMPTY) != 0) {
3116 
3117 			if ((dev->flags & CAM_DEV_REL_ON_QUEUE_EMPTY) != 0
3118 			 || (dev->ccbq.dev_active == 0)) {
3119 
3120 				start_ccb->ccb_h.flags &= ~CAM_DEV_QFREEZE;
3121 			} else {
3122 
3123 				dev->flags |= CAM_DEV_REL_ON_QUEUE_EMPTY;
3124 				start_ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
3125 			}
3126 		}
3127 		mtx_unlock(&dev->sim->devq->send_mtx);
3128 
3129 		if ((start_ccb->ccb_h.flags & CAM_DEV_QFREEZE) == 0)
3130 			xpt_release_devq(path, /*count*/1, /*run_queue*/TRUE);
3131 		start_ccb->crs.qfrozen_cnt = dev->ccbq.queue.qfrozen_cnt;
3132 		start_ccb->ccb_h.status = CAM_REQ_CMP;
3133 		break;
3134 	}
3135 	case XPT_DEBUG: {
3136 		struct cam_path *oldpath;
3137 
3138 		/* Check that all request bits are supported. */
3139 		if (start_ccb->cdbg.flags & ~(CAM_DEBUG_COMPILE)) {
3140 			start_ccb->ccb_h.status = CAM_FUNC_NOTAVAIL;
3141 			break;
3142 		}
3143 
3144 		cam_dflags = CAM_DEBUG_NONE;
3145 		if (cam_dpath != NULL) {
3146 			oldpath = cam_dpath;
3147 			cam_dpath = NULL;
3148 			xpt_free_path(oldpath);
3149 		}
3150 		if (start_ccb->cdbg.flags != CAM_DEBUG_NONE) {
3151 			if (xpt_create_path(&cam_dpath, NULL,
3152 					    start_ccb->ccb_h.path_id,
3153 					    start_ccb->ccb_h.target_id,
3154 					    start_ccb->ccb_h.target_lun) !=
3155 					    CAM_REQ_CMP) {
3156 				start_ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
3157 			} else {
3158 				cam_dflags = start_ccb->cdbg.flags;
3159 				start_ccb->ccb_h.status = CAM_REQ_CMP;
3160 				xpt_print(cam_dpath, "debugging flags now %x\n",
3161 				    cam_dflags);
3162 			}
3163 		} else
3164 			start_ccb->ccb_h.status = CAM_REQ_CMP;
3165 		break;
3166 	}
3167 	case XPT_NOOP:
3168 		if ((start_ccb->ccb_h.flags & CAM_DEV_QFREEZE) != 0)
3169 			xpt_freeze_devq(path, 1);
3170 		start_ccb->ccb_h.status = CAM_REQ_CMP;
3171 		break;
3172 	case XPT_REPROBE_LUN:
3173 		xpt_async(AC_INQ_CHANGED, path, NULL);
3174 		start_ccb->ccb_h.status = CAM_REQ_CMP;
3175 		xpt_done(start_ccb);
3176 		break;
3177 	default:
3178 	case XPT_SDEV_TYPE:
3179 	case XPT_TERM_IO:
3180 	case XPT_ENG_INQ:
3181 		/* XXX Implement */
3182 		xpt_print(start_ccb->ccb_h.path,
3183 		    "%s: CCB type %#x %s not supported\n", __func__,
3184 		    start_ccb->ccb_h.func_code,
3185 		    xpt_action_name(start_ccb->ccb_h.func_code));
3186 		start_ccb->ccb_h.status = CAM_PROVIDE_FAIL;
3187 		if (start_ccb->ccb_h.func_code & XPT_FC_DEV_QUEUED) {
3188 			xpt_done(start_ccb);
3189 		}
3190 		break;
3191 	}
3192 	CAM_DEBUG(path, CAM_DEBUG_TRACE,
3193 	    ("xpt_action_default: func= %#x %s status %#x\n",
3194 		start_ccb->ccb_h.func_code,
3195  		xpt_action_name(start_ccb->ccb_h.func_code),
3196 		start_ccb->ccb_h.status));
3197 }
3198 
3199 void
3200 xpt_polled_action(union ccb *start_ccb)
3201 {
3202 	u_int32_t timeout;
3203 	struct	  cam_sim *sim;
3204 	struct	  cam_devq *devq;
3205 	struct	  cam_ed *dev;
3206 	struct mtx *mtx;
3207 
3208 	timeout = start_ccb->ccb_h.timeout * 10;
3209 	sim = start_ccb->ccb_h.path->bus->sim;
3210 	devq = sim->devq;
3211 	mtx = sim->mtx;
3212 	dev = start_ccb->ccb_h.path->device;
3213 
3214 	mtx_unlock(&dev->device_mtx);
3215 
3216 	/*
3217 	 * Steal an opening so that no other queued requests
3218 	 * can get it before us while we simulate interrupts.
3219 	 */
3220 	mtx_lock(&devq->send_mtx);
3221 	dev->ccbq.dev_openings--;
3222 	while((devq->send_openings <= 0 || dev->ccbq.dev_openings < 0) &&
3223 	    (--timeout > 0)) {
3224 		mtx_unlock(&devq->send_mtx);
3225 		DELAY(100);
3226 		if (mtx)
3227 			mtx_lock(mtx);
3228 		(*(sim->sim_poll))(sim);
3229 		if (mtx)
3230 			mtx_unlock(mtx);
3231 		camisr_runqueue();
3232 		mtx_lock(&devq->send_mtx);
3233 	}
3234 	dev->ccbq.dev_openings++;
3235 	mtx_unlock(&devq->send_mtx);
3236 
3237 	if (timeout != 0) {
3238 		xpt_action(start_ccb);
3239 		while(--timeout > 0) {
3240 			if (mtx)
3241 				mtx_lock(mtx);
3242 			(*(sim->sim_poll))(sim);
3243 			if (mtx)
3244 				mtx_unlock(mtx);
3245 			camisr_runqueue();
3246 			if ((start_ccb->ccb_h.status  & CAM_STATUS_MASK)
3247 			    != CAM_REQ_INPROG)
3248 				break;
3249 			DELAY(100);
3250 		}
3251 		if (timeout == 0) {
3252 			/*
3253 			 * XXX Is it worth adding a sim_timeout entry
3254 			 * point so we can attempt recovery?  If
3255 			 * this is only used for dumps, I don't think
3256 			 * it is.
3257 			 */
3258 			start_ccb->ccb_h.status = CAM_CMD_TIMEOUT;
3259 		}
3260 	} else {
3261 		start_ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
3262 	}
3263 
3264 	mtx_lock(&dev->device_mtx);
3265 }
3266 
3267 /*
3268  * Schedule a peripheral driver to receive a ccb when its
3269  * target device has space for more transactions.
3270  */
3271 void
3272 xpt_schedule(struct cam_periph *periph, u_int32_t new_priority)
3273 {
3274 
3275 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("xpt_schedule\n"));
3276 	cam_periph_assert(periph, MA_OWNED);
3277 	if (new_priority < periph->scheduled_priority) {
3278 		periph->scheduled_priority = new_priority;
3279 		xpt_run_allocq(periph, 0);
3280 	}
3281 }
3282 
3283 
3284 /*
3285  * Schedule a device to run on a given queue.
3286  * If the device was inserted as a new entry on the queue,
3287  * return 1 meaning the device queue should be run. If we
3288  * were already queued, implying someone else has already
3289  * started the queue, return 0 so the caller doesn't attempt
3290  * to run the queue.
3291  */
3292 static int
3293 xpt_schedule_dev(struct camq *queue, cam_pinfo *pinfo,
3294 		 u_int32_t new_priority)
3295 {
3296 	int retval;
3297 	u_int32_t old_priority;
3298 
3299 	CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_schedule_dev\n"));
3300 
3301 	old_priority = pinfo->priority;
3302 
3303 	/*
3304 	 * Are we already queued?
3305 	 */
3306 	if (pinfo->index != CAM_UNQUEUED_INDEX) {
3307 		/* Simply reorder based on new priority */
3308 		if (new_priority < old_priority) {
3309 			camq_change_priority(queue, pinfo->index,
3310 					     new_priority);
3311 			CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3312 					("changed priority to %d\n",
3313 					 new_priority));
3314 			retval = 1;
3315 		} else
3316 			retval = 0;
3317 	} else {
3318 		/* New entry on the queue */
3319 		if (new_priority < old_priority)
3320 			pinfo->priority = new_priority;
3321 
3322 		CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3323 				("Inserting onto queue\n"));
3324 		pinfo->generation = ++queue->generation;
3325 		camq_insert(queue, pinfo);
3326 		retval = 1;
3327 	}
3328 	return (retval);
3329 }
3330 
3331 static void
3332 xpt_run_allocq_task(void *context, int pending)
3333 {
3334 	struct cam_periph *periph = context;
3335 
3336 	cam_periph_lock(periph);
3337 	periph->flags &= ~CAM_PERIPH_RUN_TASK;
3338 	xpt_run_allocq(periph, 1);
3339 	cam_periph_unlock(periph);
3340 	cam_periph_release(periph);
3341 }
3342 
3343 static void
3344 xpt_run_allocq(struct cam_periph *periph, int sleep)
3345 {
3346 	struct cam_ed	*device;
3347 	union ccb	*ccb;
3348 	uint32_t	 prio;
3349 
3350 	cam_periph_assert(periph, MA_OWNED);
3351 	if (periph->periph_allocating)
3352 		return;
3353 	periph->periph_allocating = 1;
3354 	CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_run_allocq(%p)\n", periph));
3355 	device = periph->path->device;
3356 	ccb = NULL;
3357 restart:
3358 	while ((prio = min(periph->scheduled_priority,
3359 	    periph->immediate_priority)) != CAM_PRIORITY_NONE &&
3360 	    (periph->periph_allocated - (ccb != NULL ? 1 : 0) <
3361 	     device->ccbq.total_openings || prio <= CAM_PRIORITY_OOB)) {
3362 
3363 		if (ccb == NULL &&
3364 		    (ccb = xpt_get_ccb_nowait(periph)) == NULL) {
3365 			if (sleep) {
3366 				ccb = xpt_get_ccb(periph);
3367 				goto restart;
3368 			}
3369 			if (periph->flags & CAM_PERIPH_RUN_TASK)
3370 				break;
3371 			cam_periph_doacquire(periph);
3372 			periph->flags |= CAM_PERIPH_RUN_TASK;
3373 			taskqueue_enqueue(xsoftc.xpt_taskq,
3374 			    &periph->periph_run_task);
3375 			break;
3376 		}
3377 		xpt_setup_ccb(&ccb->ccb_h, periph->path, prio);
3378 		if (prio == periph->immediate_priority) {
3379 			periph->immediate_priority = CAM_PRIORITY_NONE;
3380 			CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3381 					("waking cam_periph_getccb()\n"));
3382 			SLIST_INSERT_HEAD(&periph->ccb_list, &ccb->ccb_h,
3383 					  periph_links.sle);
3384 			wakeup(&periph->ccb_list);
3385 		} else {
3386 			periph->scheduled_priority = CAM_PRIORITY_NONE;
3387 			CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3388 					("calling periph_start()\n"));
3389 			periph->periph_start(periph, ccb);
3390 		}
3391 		ccb = NULL;
3392 	}
3393 	if (ccb != NULL)
3394 		xpt_release_ccb(ccb);
3395 	periph->periph_allocating = 0;
3396 }
3397 
3398 static void
3399 xpt_run_devq(struct cam_devq *devq)
3400 {
3401 	struct mtx *mtx;
3402 
3403 	CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_run_devq\n"));
3404 
3405 	devq->send_queue.qfrozen_cnt++;
3406 	while ((devq->send_queue.entries > 0)
3407 	    && (devq->send_openings > 0)
3408 	    && (devq->send_queue.qfrozen_cnt <= 1)) {
3409 		struct	cam_ed *device;
3410 		union ccb *work_ccb;
3411 		struct	cam_sim *sim;
3412 		struct xpt_proto *proto;
3413 
3414 		device = (struct cam_ed *)camq_remove(&devq->send_queue,
3415 							   CAMQ_HEAD);
3416 		CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3417 				("running device %p\n", device));
3418 
3419 		work_ccb = cam_ccbq_peek_ccb(&device->ccbq, CAMQ_HEAD);
3420 		if (work_ccb == NULL) {
3421 			printf("device on run queue with no ccbs???\n");
3422 			continue;
3423 		}
3424 
3425 		if ((work_ccb->ccb_h.flags & CAM_HIGH_POWER) != 0) {
3426 
3427 			mtx_lock(&xsoftc.xpt_highpower_lock);
3428 		 	if (xsoftc.num_highpower <= 0) {
3429 				/*
3430 				 * We got a high power command, but we
3431 				 * don't have any available slots.  Freeze
3432 				 * the device queue until we have a slot
3433 				 * available.
3434 				 */
3435 				xpt_freeze_devq_device(device, 1);
3436 				STAILQ_INSERT_TAIL(&xsoftc.highpowerq, device,
3437 						   highpowerq_entry);
3438 
3439 				mtx_unlock(&xsoftc.xpt_highpower_lock);
3440 				continue;
3441 			} else {
3442 				/*
3443 				 * Consume a high power slot while
3444 				 * this ccb runs.
3445 				 */
3446 				xsoftc.num_highpower--;
3447 			}
3448 			mtx_unlock(&xsoftc.xpt_highpower_lock);
3449 		}
3450 		cam_ccbq_remove_ccb(&device->ccbq, work_ccb);
3451 		cam_ccbq_send_ccb(&device->ccbq, work_ccb);
3452 		devq->send_openings--;
3453 		devq->send_active++;
3454 		xpt_schedule_devq(devq, device);
3455 		mtx_unlock(&devq->send_mtx);
3456 
3457 		if ((work_ccb->ccb_h.flags & CAM_DEV_QFREEZE) != 0) {
3458 			/*
3459 			 * The client wants to freeze the queue
3460 			 * after this CCB is sent.
3461 			 */
3462 			xpt_freeze_devq(work_ccb->ccb_h.path, 1);
3463 		}
3464 
3465 		/* In Target mode, the peripheral driver knows best... */
3466 		if (work_ccb->ccb_h.func_code == XPT_SCSI_IO) {
3467 			if ((device->inq_flags & SID_CmdQue) != 0
3468 			 && work_ccb->csio.tag_action != CAM_TAG_ACTION_NONE)
3469 				work_ccb->ccb_h.flags |= CAM_TAG_ACTION_VALID;
3470 			else
3471 				/*
3472 				 * Clear this in case of a retried CCB that
3473 				 * failed due to a rejected tag.
3474 				 */
3475 				work_ccb->ccb_h.flags &= ~CAM_TAG_ACTION_VALID;
3476 		}
3477 
3478 		KASSERT(device == work_ccb->ccb_h.path->device,
3479 		    ("device (%p) / path->device (%p) mismatch",
3480 			device, work_ccb->ccb_h.path->device));
3481 		proto = xpt_proto_find(device->protocol);
3482 		if (proto && proto->ops->debug_out)
3483 			proto->ops->debug_out(work_ccb);
3484 
3485 		/*
3486 		 * Device queues can be shared among multiple SIM instances
3487 		 * that reside on different buses.  Use the SIM from the
3488 		 * queued device, rather than the one from the calling bus.
3489 		 */
3490 		sim = device->sim;
3491 		mtx = sim->mtx;
3492 		if (mtx && !mtx_owned(mtx))
3493 			mtx_lock(mtx);
3494 		else
3495 			mtx = NULL;
3496 		work_ccb->ccb_h.qos.periph_data = cam_iosched_now();
3497 		(*(sim->sim_action))(sim, work_ccb);
3498 		if (mtx)
3499 			mtx_unlock(mtx);
3500 		mtx_lock(&devq->send_mtx);
3501 	}
3502 	devq->send_queue.qfrozen_cnt--;
3503 }
3504 
3505 /*
3506  * This function merges stuff from the slave ccb into the master ccb, while
3507  * keeping important fields in the master ccb constant.
3508  */
3509 void
3510 xpt_merge_ccb(union ccb *master_ccb, union ccb *slave_ccb)
3511 {
3512 
3513 	/*
3514 	 * Pull fields that are valid for peripheral drivers to set
3515 	 * into the master CCB along with the CCB "payload".
3516 	 */
3517 	master_ccb->ccb_h.retry_count = slave_ccb->ccb_h.retry_count;
3518 	master_ccb->ccb_h.func_code = slave_ccb->ccb_h.func_code;
3519 	master_ccb->ccb_h.timeout = slave_ccb->ccb_h.timeout;
3520 	master_ccb->ccb_h.flags = slave_ccb->ccb_h.flags;
3521 	bcopy(&(&slave_ccb->ccb_h)[1], &(&master_ccb->ccb_h)[1],
3522 	      sizeof(union ccb) - sizeof(struct ccb_hdr));
3523 }
3524 
3525 void
3526 xpt_setup_ccb_flags(struct ccb_hdr *ccb_h, struct cam_path *path,
3527 		    u_int32_t priority, u_int32_t flags)
3528 {
3529 
3530 	CAM_DEBUG(path, CAM_DEBUG_TRACE, ("xpt_setup_ccb\n"));
3531 	ccb_h->pinfo.priority = priority;
3532 	ccb_h->path = path;
3533 	ccb_h->path_id = path->bus->path_id;
3534 	if (path->target)
3535 		ccb_h->target_id = path->target->target_id;
3536 	else
3537 		ccb_h->target_id = CAM_TARGET_WILDCARD;
3538 	if (path->device) {
3539 		ccb_h->target_lun = path->device->lun_id;
3540 		ccb_h->pinfo.generation = ++path->device->ccbq.queue.generation;
3541 	} else {
3542 		ccb_h->target_lun = CAM_TARGET_WILDCARD;
3543 	}
3544 	ccb_h->pinfo.index = CAM_UNQUEUED_INDEX;
3545 	ccb_h->flags = flags;
3546 	ccb_h->xflags = 0;
3547 }
3548 
3549 void
3550 xpt_setup_ccb(struct ccb_hdr *ccb_h, struct cam_path *path, u_int32_t priority)
3551 {
3552 	xpt_setup_ccb_flags(ccb_h, path, priority, /*flags*/ 0);
3553 }
3554 
3555 /* Path manipulation functions */
3556 cam_status
3557 xpt_create_path(struct cam_path **new_path_ptr, struct cam_periph *perph,
3558 		path_id_t path_id, target_id_t target_id, lun_id_t lun_id)
3559 {
3560 	struct	   cam_path *path;
3561 	cam_status status;
3562 
3563 	path = (struct cam_path *)malloc(sizeof(*path), M_CAMPATH, M_NOWAIT);
3564 
3565 	if (path == NULL) {
3566 		status = CAM_RESRC_UNAVAIL;
3567 		return(status);
3568 	}
3569 	status = xpt_compile_path(path, perph, path_id, target_id, lun_id);
3570 	if (status != CAM_REQ_CMP) {
3571 		free(path, M_CAMPATH);
3572 		path = NULL;
3573 	}
3574 	*new_path_ptr = path;
3575 	return (status);
3576 }
3577 
3578 cam_status
3579 xpt_create_path_unlocked(struct cam_path **new_path_ptr,
3580 			 struct cam_periph *periph, path_id_t path_id,
3581 			 target_id_t target_id, lun_id_t lun_id)
3582 {
3583 
3584 	return (xpt_create_path(new_path_ptr, periph, path_id, target_id,
3585 	    lun_id));
3586 }
3587 
3588 cam_status
3589 xpt_compile_path(struct cam_path *new_path, struct cam_periph *perph,
3590 		 path_id_t path_id, target_id_t target_id, lun_id_t lun_id)
3591 {
3592 	struct	     cam_eb *bus;
3593 	struct	     cam_et *target;
3594 	struct	     cam_ed *device;
3595 	cam_status   status;
3596 
3597 	status = CAM_REQ_CMP;	/* Completed without error */
3598 	target = NULL;		/* Wildcarded */
3599 	device = NULL;		/* Wildcarded */
3600 
3601 	/*
3602 	 * We will potentially modify the EDT, so block interrupts
3603 	 * that may attempt to create cam paths.
3604 	 */
3605 	bus = xpt_find_bus(path_id);
3606 	if (bus == NULL) {
3607 		status = CAM_PATH_INVALID;
3608 	} else {
3609 		xpt_lock_buses();
3610 		mtx_lock(&bus->eb_mtx);
3611 		target = xpt_find_target(bus, target_id);
3612 		if (target == NULL) {
3613 			/* Create one */
3614 			struct cam_et *new_target;
3615 
3616 			new_target = xpt_alloc_target(bus, target_id);
3617 			if (new_target == NULL) {
3618 				status = CAM_RESRC_UNAVAIL;
3619 			} else {
3620 				target = new_target;
3621 			}
3622 		}
3623 		xpt_unlock_buses();
3624 		if (target != NULL) {
3625 			device = xpt_find_device(target, lun_id);
3626 			if (device == NULL) {
3627 				/* Create one */
3628 				struct cam_ed *new_device;
3629 
3630 				new_device =
3631 				    (*(bus->xport->ops->alloc_device))(bus,
3632 								       target,
3633 								       lun_id);
3634 				if (new_device == NULL) {
3635 					status = CAM_RESRC_UNAVAIL;
3636 				} else {
3637 					device = new_device;
3638 				}
3639 			}
3640 		}
3641 		mtx_unlock(&bus->eb_mtx);
3642 	}
3643 
3644 	/*
3645 	 * Only touch the user's data if we are successful.
3646 	 */
3647 	if (status == CAM_REQ_CMP) {
3648 		new_path->periph = perph;
3649 		new_path->bus = bus;
3650 		new_path->target = target;
3651 		new_path->device = device;
3652 		CAM_DEBUG(new_path, CAM_DEBUG_TRACE, ("xpt_compile_path\n"));
3653 	} else {
3654 		if (device != NULL)
3655 			xpt_release_device(device);
3656 		if (target != NULL)
3657 			xpt_release_target(target);
3658 		if (bus != NULL)
3659 			xpt_release_bus(bus);
3660 	}
3661 	return (status);
3662 }
3663 
3664 cam_status
3665 xpt_clone_path(struct cam_path **new_path_ptr, struct cam_path *path)
3666 {
3667 	struct	   cam_path *new_path;
3668 
3669 	new_path = (struct cam_path *)malloc(sizeof(*path), M_CAMPATH, M_NOWAIT);
3670 	if (new_path == NULL)
3671 		return(CAM_RESRC_UNAVAIL);
3672 	xpt_copy_path(new_path, path);
3673 	*new_path_ptr = new_path;
3674 	return (CAM_REQ_CMP);
3675 }
3676 
3677 void
3678 xpt_copy_path(struct cam_path *new_path, struct cam_path *path)
3679 {
3680 
3681 	*new_path = *path;
3682 	if (path->bus != NULL)
3683 		xpt_acquire_bus(path->bus);
3684 	if (path->target != NULL)
3685 		xpt_acquire_target(path->target);
3686 	if (path->device != NULL)
3687 		xpt_acquire_device(path->device);
3688 }
3689 
3690 void
3691 xpt_release_path(struct cam_path *path)
3692 {
3693 	CAM_DEBUG(path, CAM_DEBUG_TRACE, ("xpt_release_path\n"));
3694 	if (path->device != NULL) {
3695 		xpt_release_device(path->device);
3696 		path->device = NULL;
3697 	}
3698 	if (path->target != NULL) {
3699 		xpt_release_target(path->target);
3700 		path->target = NULL;
3701 	}
3702 	if (path->bus != NULL) {
3703 		xpt_release_bus(path->bus);
3704 		path->bus = NULL;
3705 	}
3706 }
3707 
3708 void
3709 xpt_free_path(struct cam_path *path)
3710 {
3711 
3712 	CAM_DEBUG(path, CAM_DEBUG_TRACE, ("xpt_free_path\n"));
3713 	xpt_release_path(path);
3714 	free(path, M_CAMPATH);
3715 }
3716 
3717 void
3718 xpt_path_counts(struct cam_path *path, uint32_t *bus_ref,
3719     uint32_t *periph_ref, uint32_t *target_ref, uint32_t *device_ref)
3720 {
3721 
3722 	xpt_lock_buses();
3723 	if (bus_ref) {
3724 		if (path->bus)
3725 			*bus_ref = path->bus->refcount;
3726 		else
3727 			*bus_ref = 0;
3728 	}
3729 	if (periph_ref) {
3730 		if (path->periph)
3731 			*periph_ref = path->periph->refcount;
3732 		else
3733 			*periph_ref = 0;
3734 	}
3735 	xpt_unlock_buses();
3736 	if (target_ref) {
3737 		if (path->target)
3738 			*target_ref = path->target->refcount;
3739 		else
3740 			*target_ref = 0;
3741 	}
3742 	if (device_ref) {
3743 		if (path->device)
3744 			*device_ref = path->device->refcount;
3745 		else
3746 			*device_ref = 0;
3747 	}
3748 }
3749 
3750 /*
3751  * Return -1 for failure, 0 for exact match, 1 for match with wildcards
3752  * in path1, 2 for match with wildcards in path2.
3753  */
3754 int
3755 xpt_path_comp(struct cam_path *path1, struct cam_path *path2)
3756 {
3757 	int retval = 0;
3758 
3759 	if (path1->bus != path2->bus) {
3760 		if (path1->bus->path_id == CAM_BUS_WILDCARD)
3761 			retval = 1;
3762 		else if (path2->bus->path_id == CAM_BUS_WILDCARD)
3763 			retval = 2;
3764 		else
3765 			return (-1);
3766 	}
3767 	if (path1->target != path2->target) {
3768 		if (path1->target->target_id == CAM_TARGET_WILDCARD) {
3769 			if (retval == 0)
3770 				retval = 1;
3771 		} else if (path2->target->target_id == CAM_TARGET_WILDCARD)
3772 			retval = 2;
3773 		else
3774 			return (-1);
3775 	}
3776 	if (path1->device != path2->device) {
3777 		if (path1->device->lun_id == CAM_LUN_WILDCARD) {
3778 			if (retval == 0)
3779 				retval = 1;
3780 		} else if (path2->device->lun_id == CAM_LUN_WILDCARD)
3781 			retval = 2;
3782 		else
3783 			return (-1);
3784 	}
3785 	return (retval);
3786 }
3787 
3788 int
3789 xpt_path_comp_dev(struct cam_path *path, struct cam_ed *dev)
3790 {
3791 	int retval = 0;
3792 
3793 	if (path->bus != dev->target->bus) {
3794 		if (path->bus->path_id == CAM_BUS_WILDCARD)
3795 			retval = 1;
3796 		else if (dev->target->bus->path_id == CAM_BUS_WILDCARD)
3797 			retval = 2;
3798 		else
3799 			return (-1);
3800 	}
3801 	if (path->target != dev->target) {
3802 		if (path->target->target_id == CAM_TARGET_WILDCARD) {
3803 			if (retval == 0)
3804 				retval = 1;
3805 		} else if (dev->target->target_id == CAM_TARGET_WILDCARD)
3806 			retval = 2;
3807 		else
3808 			return (-1);
3809 	}
3810 	if (path->device != dev) {
3811 		if (path->device->lun_id == CAM_LUN_WILDCARD) {
3812 			if (retval == 0)
3813 				retval = 1;
3814 		} else if (dev->lun_id == CAM_LUN_WILDCARD)
3815 			retval = 2;
3816 		else
3817 			return (-1);
3818 	}
3819 	return (retval);
3820 }
3821 
3822 void
3823 xpt_print_path(struct cam_path *path)
3824 {
3825 	struct sbuf sb;
3826 	char buffer[XPT_PRINT_LEN];
3827 
3828 	sbuf_new(&sb, buffer, XPT_PRINT_LEN, SBUF_FIXEDLEN);
3829 	xpt_path_sbuf(path, &sb);
3830 	sbuf_finish(&sb);
3831 	printf("%s", sbuf_data(&sb));
3832 	sbuf_delete(&sb);
3833 }
3834 
3835 void
3836 xpt_print_device(struct cam_ed *device)
3837 {
3838 
3839 	if (device == NULL)
3840 		printf("(nopath): ");
3841 	else {
3842 		printf("(noperiph:%s%d:%d:%d:%jx): ", device->sim->sim_name,
3843 		       device->sim->unit_number,
3844 		       device->sim->bus_id,
3845 		       device->target->target_id,
3846 		       (uintmax_t)device->lun_id);
3847 	}
3848 }
3849 
3850 void
3851 xpt_print(struct cam_path *path, const char *fmt, ...)
3852 {
3853 	va_list ap;
3854 	struct sbuf sb;
3855 	char buffer[XPT_PRINT_LEN];
3856 
3857 	sbuf_new(&sb, buffer, XPT_PRINT_LEN, SBUF_FIXEDLEN);
3858 
3859 	xpt_path_sbuf(path, &sb);
3860 	va_start(ap, fmt);
3861 	sbuf_vprintf(&sb, fmt, ap);
3862 	va_end(ap);
3863 
3864 	sbuf_finish(&sb);
3865 	printf("%s", sbuf_data(&sb));
3866 	sbuf_delete(&sb);
3867 }
3868 
3869 int
3870 xpt_path_string(struct cam_path *path, char *str, size_t str_len)
3871 {
3872 	struct sbuf sb;
3873 	int len;
3874 
3875 	sbuf_new(&sb, str, str_len, 0);
3876 	len = xpt_path_sbuf(path, &sb);
3877 	sbuf_finish(&sb);
3878 	return (len);
3879 }
3880 
3881 int
3882 xpt_path_sbuf(struct cam_path *path, struct sbuf *sb)
3883 {
3884 
3885 	if (path == NULL)
3886 		sbuf_printf(sb, "(nopath): ");
3887 	else {
3888 		if (path->periph != NULL)
3889 			sbuf_printf(sb, "(%s%d:", path->periph->periph_name,
3890 				    path->periph->unit_number);
3891 		else
3892 			sbuf_printf(sb, "(noperiph:");
3893 
3894 		if (path->bus != NULL)
3895 			sbuf_printf(sb, "%s%d:%d:", path->bus->sim->sim_name,
3896 				    path->bus->sim->unit_number,
3897 				    path->bus->sim->bus_id);
3898 		else
3899 			sbuf_printf(sb, "nobus:");
3900 
3901 		if (path->target != NULL)
3902 			sbuf_printf(sb, "%d:", path->target->target_id);
3903 		else
3904 			sbuf_printf(sb, "X:");
3905 
3906 		if (path->device != NULL)
3907 			sbuf_printf(sb, "%jx): ",
3908 			    (uintmax_t)path->device->lun_id);
3909 		else
3910 			sbuf_printf(sb, "X): ");
3911 	}
3912 
3913 	return(sbuf_len(sb));
3914 }
3915 
3916 path_id_t
3917 xpt_path_path_id(struct cam_path *path)
3918 {
3919 	return(path->bus->path_id);
3920 }
3921 
3922 target_id_t
3923 xpt_path_target_id(struct cam_path *path)
3924 {
3925 	if (path->target != NULL)
3926 		return (path->target->target_id);
3927 	else
3928 		return (CAM_TARGET_WILDCARD);
3929 }
3930 
3931 lun_id_t
3932 xpt_path_lun_id(struct cam_path *path)
3933 {
3934 	if (path->device != NULL)
3935 		return (path->device->lun_id);
3936 	else
3937 		return (CAM_LUN_WILDCARD);
3938 }
3939 
3940 struct cam_sim *
3941 xpt_path_sim(struct cam_path *path)
3942 {
3943 
3944 	return (path->bus->sim);
3945 }
3946 
3947 struct cam_periph*
3948 xpt_path_periph(struct cam_path *path)
3949 {
3950 
3951 	return (path->periph);
3952 }
3953 
3954 /*
3955  * Release a CAM control block for the caller.  Remit the cost of the structure
3956  * to the device referenced by the path.  If the this device had no 'credits'
3957  * and peripheral drivers have registered async callbacks for this notification
3958  * call them now.
3959  */
3960 void
3961 xpt_release_ccb(union ccb *free_ccb)
3962 {
3963 	struct	 cam_ed *device;
3964 	struct	 cam_periph *periph;
3965 
3966 	CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_release_ccb\n"));
3967 	xpt_path_assert(free_ccb->ccb_h.path, MA_OWNED);
3968 	device = free_ccb->ccb_h.path->device;
3969 	periph = free_ccb->ccb_h.path->periph;
3970 
3971 	xpt_free_ccb(free_ccb);
3972 	periph->periph_allocated--;
3973 	cam_ccbq_release_opening(&device->ccbq);
3974 	xpt_run_allocq(periph, 0);
3975 }
3976 
3977 /* Functions accessed by SIM drivers */
3978 
3979 static struct xpt_xport_ops xport_default_ops = {
3980 	.alloc_device = xpt_alloc_device_default,
3981 	.action = xpt_action_default,
3982 	.async = xpt_dev_async_default,
3983 };
3984 static struct xpt_xport xport_default = {
3985 	.xport = XPORT_UNKNOWN,
3986 	.name = "unknown",
3987 	.ops = &xport_default_ops,
3988 };
3989 
3990 CAM_XPT_XPORT(xport_default);
3991 
3992 /*
3993  * A sim structure, listing the SIM entry points and instance
3994  * identification info is passed to xpt_bus_register to hook the SIM
3995  * into the CAM framework.  xpt_bus_register creates a cam_eb entry
3996  * for this new bus and places it in the array of buses and assigns
3997  * it a path_id.  The path_id may be influenced by "hard wiring"
3998  * information specified by the user.  Once interrupt services are
3999  * available, the bus will be probed.
4000  */
4001 int32_t
4002 xpt_bus_register(struct cam_sim *sim, device_t parent, u_int32_t bus)
4003 {
4004 	struct cam_eb *new_bus;
4005 	struct cam_eb *old_bus;
4006 	struct ccb_pathinq cpi;
4007 	struct cam_path *path;
4008 	cam_status status;
4009 
4010 	sim->bus_id = bus;
4011 	new_bus = (struct cam_eb *)malloc(sizeof(*new_bus),
4012 					  M_CAMXPT, M_NOWAIT|M_ZERO);
4013 	if (new_bus == NULL) {
4014 		/* Couldn't satisfy request */
4015 		return (CAM_RESRC_UNAVAIL);
4016 	}
4017 
4018 	mtx_init(&new_bus->eb_mtx, "CAM bus lock", NULL, MTX_DEF);
4019 	TAILQ_INIT(&new_bus->et_entries);
4020 	cam_sim_hold(sim);
4021 	new_bus->sim = sim;
4022 	timevalclear(&new_bus->last_reset);
4023 	new_bus->flags = 0;
4024 	new_bus->refcount = 1;	/* Held until a bus_deregister event */
4025 	new_bus->generation = 0;
4026 
4027 	xpt_lock_buses();
4028 	sim->path_id = new_bus->path_id =
4029 	    xptpathid(sim->sim_name, sim->unit_number, sim->bus_id);
4030 	old_bus = TAILQ_FIRST(&xsoftc.xpt_busses);
4031 	while (old_bus != NULL
4032 	    && old_bus->path_id < new_bus->path_id)
4033 		old_bus = TAILQ_NEXT(old_bus, links);
4034 	if (old_bus != NULL)
4035 		TAILQ_INSERT_BEFORE(old_bus, new_bus, links);
4036 	else
4037 		TAILQ_INSERT_TAIL(&xsoftc.xpt_busses, new_bus, links);
4038 	xsoftc.bus_generation++;
4039 	xpt_unlock_buses();
4040 
4041 	/*
4042 	 * Set a default transport so that a PATH_INQ can be issued to
4043 	 * the SIM.  This will then allow for probing and attaching of
4044 	 * a more appropriate transport.
4045 	 */
4046 	new_bus->xport = &xport_default;
4047 
4048 	status = xpt_create_path(&path, /*periph*/NULL, sim->path_id,
4049 				  CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
4050 	if (status != CAM_REQ_CMP) {
4051 		xpt_release_bus(new_bus);
4052 		free(path, M_CAMXPT);
4053 		return (CAM_RESRC_UNAVAIL);
4054 	}
4055 
4056 	xpt_setup_ccb(&cpi.ccb_h, path, CAM_PRIORITY_NORMAL);
4057 	cpi.ccb_h.func_code = XPT_PATH_INQ;
4058 	xpt_action((union ccb *)&cpi);
4059 
4060 	if (cpi.ccb_h.status == CAM_REQ_CMP) {
4061 		struct xpt_xport **xpt;
4062 
4063 		SET_FOREACH(xpt, cam_xpt_xport_set) {
4064 			if ((*xpt)->xport == cpi.transport) {
4065 				new_bus->xport = *xpt;
4066 				break;
4067 			}
4068 		}
4069 		if (new_bus->xport == NULL) {
4070 			xpt_print(path,
4071 			    "No transport found for %d\n", cpi.transport);
4072 			xpt_release_bus(new_bus);
4073 			free(path, M_CAMXPT);
4074 			return (CAM_RESRC_UNAVAIL);
4075 		}
4076 	}
4077 
4078 	/* Notify interested parties */
4079 	if (sim->path_id != CAM_XPT_PATH_ID) {
4080 
4081 		xpt_async(AC_PATH_REGISTERED, path, &cpi);
4082 		if ((cpi.hba_misc & PIM_NOSCAN) == 0) {
4083 			union	ccb *scan_ccb;
4084 
4085 			/* Initiate bus rescan. */
4086 			scan_ccb = xpt_alloc_ccb_nowait();
4087 			if (scan_ccb != NULL) {
4088 				scan_ccb->ccb_h.path = path;
4089 				scan_ccb->ccb_h.func_code = XPT_SCAN_BUS;
4090 				scan_ccb->crcn.flags = 0;
4091 				xpt_rescan(scan_ccb);
4092 			} else {
4093 				xpt_print(path,
4094 					  "Can't allocate CCB to scan bus\n");
4095 				xpt_free_path(path);
4096 			}
4097 		} else
4098 			xpt_free_path(path);
4099 	} else
4100 		xpt_free_path(path);
4101 	return (CAM_SUCCESS);
4102 }
4103 
4104 int32_t
4105 xpt_bus_deregister(path_id_t pathid)
4106 {
4107 	struct cam_path bus_path;
4108 	cam_status status;
4109 
4110 	status = xpt_compile_path(&bus_path, NULL, pathid,
4111 				  CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
4112 	if (status != CAM_REQ_CMP)
4113 		return (status);
4114 
4115 	xpt_async(AC_LOST_DEVICE, &bus_path, NULL);
4116 	xpt_async(AC_PATH_DEREGISTERED, &bus_path, NULL);
4117 
4118 	/* Release the reference count held while registered. */
4119 	xpt_release_bus(bus_path.bus);
4120 	xpt_release_path(&bus_path);
4121 
4122 	return (CAM_REQ_CMP);
4123 }
4124 
4125 static path_id_t
4126 xptnextfreepathid(void)
4127 {
4128 	struct cam_eb *bus;
4129 	path_id_t pathid;
4130 	const char *strval;
4131 
4132 	mtx_assert(&xsoftc.xpt_topo_lock, MA_OWNED);
4133 	pathid = 0;
4134 	bus = TAILQ_FIRST(&xsoftc.xpt_busses);
4135 retry:
4136 	/* Find an unoccupied pathid */
4137 	while (bus != NULL && bus->path_id <= pathid) {
4138 		if (bus->path_id == pathid)
4139 			pathid++;
4140 		bus = TAILQ_NEXT(bus, links);
4141 	}
4142 
4143 	/*
4144 	 * Ensure that this pathid is not reserved for
4145 	 * a bus that may be registered in the future.
4146 	 */
4147 	if (resource_string_value("scbus", pathid, "at", &strval) == 0) {
4148 		++pathid;
4149 		/* Start the search over */
4150 		goto retry;
4151 	}
4152 	return (pathid);
4153 }
4154 
4155 static path_id_t
4156 xptpathid(const char *sim_name, int sim_unit, int sim_bus)
4157 {
4158 	path_id_t pathid;
4159 	int i, dunit, val;
4160 	char buf[32];
4161 	const char *dname;
4162 
4163 	pathid = CAM_XPT_PATH_ID;
4164 	snprintf(buf, sizeof(buf), "%s%d", sim_name, sim_unit);
4165 	if (strcmp(buf, "xpt0") == 0 && sim_bus == 0)
4166 		return (pathid);
4167 	i = 0;
4168 	while ((resource_find_match(&i, &dname, &dunit, "at", buf)) == 0) {
4169 		if (strcmp(dname, "scbus")) {
4170 			/* Avoid a bit of foot shooting. */
4171 			continue;
4172 		}
4173 		if (dunit < 0)		/* unwired?! */
4174 			continue;
4175 		if (resource_int_value("scbus", dunit, "bus", &val) == 0) {
4176 			if (sim_bus == val) {
4177 				pathid = dunit;
4178 				break;
4179 			}
4180 		} else if (sim_bus == 0) {
4181 			/* Unspecified matches bus 0 */
4182 			pathid = dunit;
4183 			break;
4184 		} else {
4185 			printf("Ambiguous scbus configuration for %s%d "
4186 			       "bus %d, cannot wire down.  The kernel "
4187 			       "config entry for scbus%d should "
4188 			       "specify a controller bus.\n"
4189 			       "Scbus will be assigned dynamically.\n",
4190 			       sim_name, sim_unit, sim_bus, dunit);
4191 			break;
4192 		}
4193 	}
4194 
4195 	if (pathid == CAM_XPT_PATH_ID)
4196 		pathid = xptnextfreepathid();
4197 	return (pathid);
4198 }
4199 
4200 static const char *
4201 xpt_async_string(u_int32_t async_code)
4202 {
4203 
4204 	switch (async_code) {
4205 	case AC_BUS_RESET: return ("AC_BUS_RESET");
4206 	case AC_UNSOL_RESEL: return ("AC_UNSOL_RESEL");
4207 	case AC_SCSI_AEN: return ("AC_SCSI_AEN");
4208 	case AC_SENT_BDR: return ("AC_SENT_BDR");
4209 	case AC_PATH_REGISTERED: return ("AC_PATH_REGISTERED");
4210 	case AC_PATH_DEREGISTERED: return ("AC_PATH_DEREGISTERED");
4211 	case AC_FOUND_DEVICE: return ("AC_FOUND_DEVICE");
4212 	case AC_LOST_DEVICE: return ("AC_LOST_DEVICE");
4213 	case AC_TRANSFER_NEG: return ("AC_TRANSFER_NEG");
4214 	case AC_INQ_CHANGED: return ("AC_INQ_CHANGED");
4215 	case AC_GETDEV_CHANGED: return ("AC_GETDEV_CHANGED");
4216 	case AC_CONTRACT: return ("AC_CONTRACT");
4217 	case AC_ADVINFO_CHANGED: return ("AC_ADVINFO_CHANGED");
4218 	case AC_UNIT_ATTENTION: return ("AC_UNIT_ATTENTION");
4219 	}
4220 	return ("AC_UNKNOWN");
4221 }
4222 
4223 static int
4224 xpt_async_size(u_int32_t async_code)
4225 {
4226 
4227 	switch (async_code) {
4228 	case AC_BUS_RESET: return (0);
4229 	case AC_UNSOL_RESEL: return (0);
4230 	case AC_SCSI_AEN: return (0);
4231 	case AC_SENT_BDR: return (0);
4232 	case AC_PATH_REGISTERED: return (sizeof(struct ccb_pathinq));
4233 	case AC_PATH_DEREGISTERED: return (0);
4234 	case AC_FOUND_DEVICE: return (sizeof(struct ccb_getdev));
4235 	case AC_LOST_DEVICE: return (0);
4236 	case AC_TRANSFER_NEG: return (sizeof(struct ccb_trans_settings));
4237 	case AC_INQ_CHANGED: return (0);
4238 	case AC_GETDEV_CHANGED: return (0);
4239 	case AC_CONTRACT: return (sizeof(struct ac_contract));
4240 	case AC_ADVINFO_CHANGED: return (-1);
4241 	case AC_UNIT_ATTENTION: return (sizeof(struct ccb_scsiio));
4242 	}
4243 	return (0);
4244 }
4245 
4246 static int
4247 xpt_async_process_dev(struct cam_ed *device, void *arg)
4248 {
4249 	union ccb *ccb = arg;
4250 	struct cam_path *path = ccb->ccb_h.path;
4251 	void *async_arg = ccb->casync.async_arg_ptr;
4252 	u_int32_t async_code = ccb->casync.async_code;
4253 	int relock;
4254 
4255 	if (path->device != device
4256 	 && path->device->lun_id != CAM_LUN_WILDCARD
4257 	 && device->lun_id != CAM_LUN_WILDCARD)
4258 		return (1);
4259 
4260 	/*
4261 	 * The async callback could free the device.
4262 	 * If it is a broadcast async, it doesn't hold
4263 	 * device reference, so take our own reference.
4264 	 */
4265 	xpt_acquire_device(device);
4266 
4267 	/*
4268 	 * If async for specific device is to be delivered to
4269 	 * the wildcard client, take the specific device lock.
4270 	 * XXX: We may need a way for client to specify it.
4271 	 */
4272 	if ((device->lun_id == CAM_LUN_WILDCARD &&
4273 	     path->device->lun_id != CAM_LUN_WILDCARD) ||
4274 	    (device->target->target_id == CAM_TARGET_WILDCARD &&
4275 	     path->target->target_id != CAM_TARGET_WILDCARD) ||
4276 	    (device->target->bus->path_id == CAM_BUS_WILDCARD &&
4277 	     path->target->bus->path_id != CAM_BUS_WILDCARD)) {
4278 		mtx_unlock(&device->device_mtx);
4279 		xpt_path_lock(path);
4280 		relock = 1;
4281 	} else
4282 		relock = 0;
4283 
4284 	(*(device->target->bus->xport->ops->async))(async_code,
4285 	    device->target->bus, device->target, device, async_arg);
4286 	xpt_async_bcast(&device->asyncs, async_code, path, async_arg);
4287 
4288 	if (relock) {
4289 		xpt_path_unlock(path);
4290 		mtx_lock(&device->device_mtx);
4291 	}
4292 	xpt_release_device(device);
4293 	return (1);
4294 }
4295 
4296 static int
4297 xpt_async_process_tgt(struct cam_et *target, void *arg)
4298 {
4299 	union ccb *ccb = arg;
4300 	struct cam_path *path = ccb->ccb_h.path;
4301 
4302 	if (path->target != target
4303 	 && path->target->target_id != CAM_TARGET_WILDCARD
4304 	 && target->target_id != CAM_TARGET_WILDCARD)
4305 		return (1);
4306 
4307 	if (ccb->casync.async_code == AC_SENT_BDR) {
4308 		/* Update our notion of when the last reset occurred */
4309 		microtime(&target->last_reset);
4310 	}
4311 
4312 	return (xptdevicetraverse(target, NULL, xpt_async_process_dev, ccb));
4313 }
4314 
4315 static void
4316 xpt_async_process(struct cam_periph *periph, union ccb *ccb)
4317 {
4318 	struct cam_eb *bus;
4319 	struct cam_path *path;
4320 	void *async_arg;
4321 	u_int32_t async_code;
4322 
4323 	path = ccb->ccb_h.path;
4324 	async_code = ccb->casync.async_code;
4325 	async_arg = ccb->casync.async_arg_ptr;
4326 	CAM_DEBUG(path, CAM_DEBUG_TRACE | CAM_DEBUG_INFO,
4327 	    ("xpt_async(%s)\n", xpt_async_string(async_code)));
4328 	bus = path->bus;
4329 
4330 	if (async_code == AC_BUS_RESET) {
4331 		/* Update our notion of when the last reset occurred */
4332 		microtime(&bus->last_reset);
4333 	}
4334 
4335 	xpttargettraverse(bus, NULL, xpt_async_process_tgt, ccb);
4336 
4337 	/*
4338 	 * If this wasn't a fully wildcarded async, tell all
4339 	 * clients that want all async events.
4340 	 */
4341 	if (bus != xpt_periph->path->bus) {
4342 		xpt_path_lock(xpt_periph->path);
4343 		xpt_async_process_dev(xpt_periph->path->device, ccb);
4344 		xpt_path_unlock(xpt_periph->path);
4345 	}
4346 
4347 	if (path->device != NULL && path->device->lun_id != CAM_LUN_WILDCARD)
4348 		xpt_release_devq(path, 1, TRUE);
4349 	else
4350 		xpt_release_simq(path->bus->sim, TRUE);
4351 	if (ccb->casync.async_arg_size > 0)
4352 		free(async_arg, M_CAMXPT);
4353 	xpt_free_path(path);
4354 	xpt_free_ccb(ccb);
4355 }
4356 
4357 static void
4358 xpt_async_bcast(struct async_list *async_head,
4359 		u_int32_t async_code,
4360 		struct cam_path *path, void *async_arg)
4361 {
4362 	struct async_node *cur_entry;
4363 	struct mtx *mtx;
4364 
4365 	cur_entry = SLIST_FIRST(async_head);
4366 	while (cur_entry != NULL) {
4367 		struct async_node *next_entry;
4368 		/*
4369 		 * Grab the next list entry before we call the current
4370 		 * entry's callback.  This is because the callback function
4371 		 * can delete its async callback entry.
4372 		 */
4373 		next_entry = SLIST_NEXT(cur_entry, links);
4374 		if ((cur_entry->event_enable & async_code) != 0) {
4375 			mtx = cur_entry->event_lock ?
4376 			    path->device->sim->mtx : NULL;
4377 			if (mtx)
4378 				mtx_lock(mtx);
4379 			cur_entry->callback(cur_entry->callback_arg,
4380 					    async_code, path,
4381 					    async_arg);
4382 			if (mtx)
4383 				mtx_unlock(mtx);
4384 		}
4385 		cur_entry = next_entry;
4386 	}
4387 }
4388 
4389 void
4390 xpt_async(u_int32_t async_code, struct cam_path *path, void *async_arg)
4391 {
4392 	union ccb *ccb;
4393 	int size;
4394 
4395 	ccb = xpt_alloc_ccb_nowait();
4396 	if (ccb == NULL) {
4397 		xpt_print(path, "Can't allocate CCB to send %s\n",
4398 		    xpt_async_string(async_code));
4399 		return;
4400 	}
4401 
4402 	if (xpt_clone_path(&ccb->ccb_h.path, path) != CAM_REQ_CMP) {
4403 		xpt_print(path, "Can't allocate path to send %s\n",
4404 		    xpt_async_string(async_code));
4405 		xpt_free_ccb(ccb);
4406 		return;
4407 	}
4408 	ccb->ccb_h.path->periph = NULL;
4409 	ccb->ccb_h.func_code = XPT_ASYNC;
4410 	ccb->ccb_h.cbfcnp = xpt_async_process;
4411 	ccb->ccb_h.flags |= CAM_UNLOCKED;
4412 	ccb->casync.async_code = async_code;
4413 	ccb->casync.async_arg_size = 0;
4414 	size = xpt_async_size(async_code);
4415 	CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_TRACE,
4416 	    ("xpt_async: func %#x %s aync_code %d %s\n",
4417 		ccb->ccb_h.func_code,
4418 		xpt_action_name(ccb->ccb_h.func_code),
4419 		async_code,
4420 		xpt_async_string(async_code)));
4421 	if (size > 0 && async_arg != NULL) {
4422 		ccb->casync.async_arg_ptr = malloc(size, M_CAMXPT, M_NOWAIT);
4423 		if (ccb->casync.async_arg_ptr == NULL) {
4424 			xpt_print(path, "Can't allocate argument to send %s\n",
4425 			    xpt_async_string(async_code));
4426 			xpt_free_path(ccb->ccb_h.path);
4427 			xpt_free_ccb(ccb);
4428 			return;
4429 		}
4430 		memcpy(ccb->casync.async_arg_ptr, async_arg, size);
4431 		ccb->casync.async_arg_size = size;
4432 	} else if (size < 0) {
4433 		ccb->casync.async_arg_ptr = async_arg;
4434 		ccb->casync.async_arg_size = size;
4435 	}
4436 	if (path->device != NULL && path->device->lun_id != CAM_LUN_WILDCARD)
4437 		xpt_freeze_devq(path, 1);
4438 	else
4439 		xpt_freeze_simq(path->bus->sim, 1);
4440 	xpt_done(ccb);
4441 }
4442 
4443 static void
4444 xpt_dev_async_default(u_int32_t async_code, struct cam_eb *bus,
4445 		      struct cam_et *target, struct cam_ed *device,
4446 		      void *async_arg)
4447 {
4448 
4449 	/*
4450 	 * We only need to handle events for real devices.
4451 	 */
4452 	if (target->target_id == CAM_TARGET_WILDCARD
4453 	 || device->lun_id == CAM_LUN_WILDCARD)
4454 		return;
4455 
4456 	printf("%s called\n", __func__);
4457 }
4458 
4459 static uint32_t
4460 xpt_freeze_devq_device(struct cam_ed *dev, u_int count)
4461 {
4462 	struct cam_devq	*devq;
4463 	uint32_t freeze;
4464 
4465 	devq = dev->sim->devq;
4466 	mtx_assert(&devq->send_mtx, MA_OWNED);
4467 	CAM_DEBUG_DEV(dev, CAM_DEBUG_TRACE,
4468 	    ("xpt_freeze_devq_device(%d) %u->%u\n", count,
4469 	    dev->ccbq.queue.qfrozen_cnt, dev->ccbq.queue.qfrozen_cnt + count));
4470 	freeze = (dev->ccbq.queue.qfrozen_cnt += count);
4471 	/* Remove frozen device from sendq. */
4472 	if (device_is_queued(dev))
4473 		camq_remove(&devq->send_queue, dev->devq_entry.index);
4474 	return (freeze);
4475 }
4476 
4477 u_int32_t
4478 xpt_freeze_devq(struct cam_path *path, u_int count)
4479 {
4480 	struct cam_ed	*dev = path->device;
4481 	struct cam_devq	*devq;
4482 	uint32_t	 freeze;
4483 
4484 	devq = dev->sim->devq;
4485 	mtx_lock(&devq->send_mtx);
4486 	CAM_DEBUG(path, CAM_DEBUG_TRACE, ("xpt_freeze_devq(%d)\n", count));
4487 	freeze = xpt_freeze_devq_device(dev, count);
4488 	mtx_unlock(&devq->send_mtx);
4489 	return (freeze);
4490 }
4491 
4492 u_int32_t
4493 xpt_freeze_simq(struct cam_sim *sim, u_int count)
4494 {
4495 	struct cam_devq	*devq;
4496 	uint32_t	 freeze;
4497 
4498 	devq = sim->devq;
4499 	mtx_lock(&devq->send_mtx);
4500 	freeze = (devq->send_queue.qfrozen_cnt += count);
4501 	mtx_unlock(&devq->send_mtx);
4502 	return (freeze);
4503 }
4504 
4505 static void
4506 xpt_release_devq_timeout(void *arg)
4507 {
4508 	struct cam_ed *dev;
4509 	struct cam_devq *devq;
4510 
4511 	dev = (struct cam_ed *)arg;
4512 	CAM_DEBUG_DEV(dev, CAM_DEBUG_TRACE, ("xpt_release_devq_timeout\n"));
4513 	devq = dev->sim->devq;
4514 	mtx_assert(&devq->send_mtx, MA_OWNED);
4515 	if (xpt_release_devq_device(dev, /*count*/1, /*run_queue*/TRUE))
4516 		xpt_run_devq(devq);
4517 }
4518 
4519 void
4520 xpt_release_devq(struct cam_path *path, u_int count, int run_queue)
4521 {
4522 	struct cam_ed *dev;
4523 	struct cam_devq *devq;
4524 
4525 	CAM_DEBUG(path, CAM_DEBUG_TRACE, ("xpt_release_devq(%d, %d)\n",
4526 	    count, run_queue));
4527 	dev = path->device;
4528 	devq = dev->sim->devq;
4529 	mtx_lock(&devq->send_mtx);
4530 	if (xpt_release_devq_device(dev, count, run_queue))
4531 		xpt_run_devq(dev->sim->devq);
4532 	mtx_unlock(&devq->send_mtx);
4533 }
4534 
4535 static int
4536 xpt_release_devq_device(struct cam_ed *dev, u_int count, int run_queue)
4537 {
4538 
4539 	mtx_assert(&dev->sim->devq->send_mtx, MA_OWNED);
4540 	CAM_DEBUG_DEV(dev, CAM_DEBUG_TRACE,
4541 	    ("xpt_release_devq_device(%d, %d) %u->%u\n", count, run_queue,
4542 	    dev->ccbq.queue.qfrozen_cnt, dev->ccbq.queue.qfrozen_cnt - count));
4543 	if (count > dev->ccbq.queue.qfrozen_cnt) {
4544 #ifdef INVARIANTS
4545 		printf("xpt_release_devq(): requested %u > present %u\n",
4546 		    count, dev->ccbq.queue.qfrozen_cnt);
4547 #endif
4548 		count = dev->ccbq.queue.qfrozen_cnt;
4549 	}
4550 	dev->ccbq.queue.qfrozen_cnt -= count;
4551 	if (dev->ccbq.queue.qfrozen_cnt == 0) {
4552 		/*
4553 		 * No longer need to wait for a successful
4554 		 * command completion.
4555 		 */
4556 		dev->flags &= ~CAM_DEV_REL_ON_COMPLETE;
4557 		/*
4558 		 * Remove any timeouts that might be scheduled
4559 		 * to release this queue.
4560 		 */
4561 		if ((dev->flags & CAM_DEV_REL_TIMEOUT_PENDING) != 0) {
4562 			callout_stop(&dev->callout);
4563 			dev->flags &= ~CAM_DEV_REL_TIMEOUT_PENDING;
4564 		}
4565 		/*
4566 		 * Now that we are unfrozen schedule the
4567 		 * device so any pending transactions are
4568 		 * run.
4569 		 */
4570 		xpt_schedule_devq(dev->sim->devq, dev);
4571 	} else
4572 		run_queue = 0;
4573 	return (run_queue);
4574 }
4575 
4576 void
4577 xpt_release_simq(struct cam_sim *sim, int run_queue)
4578 {
4579 	struct cam_devq	*devq;
4580 
4581 	devq = sim->devq;
4582 	mtx_lock(&devq->send_mtx);
4583 	if (devq->send_queue.qfrozen_cnt <= 0) {
4584 #ifdef INVARIANTS
4585 		printf("xpt_release_simq: requested 1 > present %u\n",
4586 		    devq->send_queue.qfrozen_cnt);
4587 #endif
4588 	} else
4589 		devq->send_queue.qfrozen_cnt--;
4590 	if (devq->send_queue.qfrozen_cnt == 0) {
4591 		/*
4592 		 * If there is a timeout scheduled to release this
4593 		 * sim queue, remove it.  The queue frozen count is
4594 		 * already at 0.
4595 		 */
4596 		if ((sim->flags & CAM_SIM_REL_TIMEOUT_PENDING) != 0){
4597 			callout_stop(&sim->callout);
4598 			sim->flags &= ~CAM_SIM_REL_TIMEOUT_PENDING;
4599 		}
4600 		if (run_queue) {
4601 			/*
4602 			 * Now that we are unfrozen run the send queue.
4603 			 */
4604 			xpt_run_devq(sim->devq);
4605 		}
4606 	}
4607 	mtx_unlock(&devq->send_mtx);
4608 }
4609 
4610 /*
4611  * XXX Appears to be unused.
4612  */
4613 static void
4614 xpt_release_simq_timeout(void *arg)
4615 {
4616 	struct cam_sim *sim;
4617 
4618 	sim = (struct cam_sim *)arg;
4619 	xpt_release_simq(sim, /* run_queue */ TRUE);
4620 }
4621 
4622 void
4623 xpt_done(union ccb *done_ccb)
4624 {
4625 	struct cam_doneq *queue;
4626 	int	run, hash;
4627 
4628 #if defined(BUF_TRACKING) || defined(FULL_BUF_TRACKING)
4629 	if (done_ccb->ccb_h.func_code == XPT_SCSI_IO &&
4630 	    done_ccb->csio.bio != NULL)
4631 		biotrack(done_ccb->csio.bio, __func__);
4632 #endif
4633 
4634 	CAM_DEBUG(done_ccb->ccb_h.path, CAM_DEBUG_TRACE,
4635 	    ("xpt_done: func= %#x %s status %#x\n",
4636 		done_ccb->ccb_h.func_code,
4637 		xpt_action_name(done_ccb->ccb_h.func_code),
4638 		done_ccb->ccb_h.status));
4639 	if ((done_ccb->ccb_h.func_code & XPT_FC_QUEUED) == 0)
4640 		return;
4641 
4642 	/* Store the time the ccb was in the sim */
4643 	done_ccb->ccb_h.qos.periph_data = cam_iosched_delta_t(done_ccb->ccb_h.qos.periph_data);
4644 	hash = (done_ccb->ccb_h.path_id + done_ccb->ccb_h.target_id +
4645 	    done_ccb->ccb_h.target_lun) % cam_num_doneqs;
4646 	queue = &cam_doneqs[hash];
4647 	mtx_lock(&queue->cam_doneq_mtx);
4648 	run = (queue->cam_doneq_sleep && STAILQ_EMPTY(&queue->cam_doneq));
4649 	STAILQ_INSERT_TAIL(&queue->cam_doneq, &done_ccb->ccb_h, sim_links.stqe);
4650 	done_ccb->ccb_h.pinfo.index = CAM_DONEQ_INDEX;
4651 	mtx_unlock(&queue->cam_doneq_mtx);
4652 	if (run)
4653 		wakeup(&queue->cam_doneq);
4654 }
4655 
4656 void
4657 xpt_done_direct(union ccb *done_ccb)
4658 {
4659 
4660 	CAM_DEBUG(done_ccb->ccb_h.path, CAM_DEBUG_TRACE,
4661 	    ("xpt_done_direct: status %#x\n", done_ccb->ccb_h.status));
4662 	if ((done_ccb->ccb_h.func_code & XPT_FC_QUEUED) == 0)
4663 		return;
4664 
4665 	/* Store the time the ccb was in the sim */
4666 	done_ccb->ccb_h.qos.periph_data = cam_iosched_delta_t(done_ccb->ccb_h.qos.periph_data);
4667 	xpt_done_process(&done_ccb->ccb_h);
4668 }
4669 
4670 union ccb *
4671 xpt_alloc_ccb()
4672 {
4673 	union ccb *new_ccb;
4674 
4675 	new_ccb = malloc(sizeof(*new_ccb), M_CAMCCB, M_ZERO|M_WAITOK);
4676 	return (new_ccb);
4677 }
4678 
4679 union ccb *
4680 xpt_alloc_ccb_nowait()
4681 {
4682 	union ccb *new_ccb;
4683 
4684 	new_ccb = malloc(sizeof(*new_ccb), M_CAMCCB, M_ZERO|M_NOWAIT);
4685 	return (new_ccb);
4686 }
4687 
4688 void
4689 xpt_free_ccb(union ccb *free_ccb)
4690 {
4691 	free(free_ccb, M_CAMCCB);
4692 }
4693 
4694 
4695 
4696 /* Private XPT functions */
4697 
4698 /*
4699  * Get a CAM control block for the caller. Charge the structure to the device
4700  * referenced by the path.  If we don't have sufficient resources to allocate
4701  * more ccbs, we return NULL.
4702  */
4703 static union ccb *
4704 xpt_get_ccb_nowait(struct cam_periph *periph)
4705 {
4706 	union ccb *new_ccb;
4707 
4708 	new_ccb = malloc(sizeof(*new_ccb), M_CAMCCB, M_ZERO|M_NOWAIT);
4709 	if (new_ccb == NULL)
4710 		return (NULL);
4711 	periph->periph_allocated++;
4712 	cam_ccbq_take_opening(&periph->path->device->ccbq);
4713 	return (new_ccb);
4714 }
4715 
4716 static union ccb *
4717 xpt_get_ccb(struct cam_periph *periph)
4718 {
4719 	union ccb *new_ccb;
4720 
4721 	cam_periph_unlock(periph);
4722 	new_ccb = malloc(sizeof(*new_ccb), M_CAMCCB, M_ZERO|M_WAITOK);
4723 	cam_periph_lock(periph);
4724 	periph->periph_allocated++;
4725 	cam_ccbq_take_opening(&periph->path->device->ccbq);
4726 	return (new_ccb);
4727 }
4728 
4729 union ccb *
4730 cam_periph_getccb(struct cam_periph *periph, u_int32_t priority)
4731 {
4732 	struct ccb_hdr *ccb_h;
4733 
4734 	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("cam_periph_getccb\n"));
4735 	cam_periph_assert(periph, MA_OWNED);
4736 	while ((ccb_h = SLIST_FIRST(&periph->ccb_list)) == NULL ||
4737 	    ccb_h->pinfo.priority != priority) {
4738 		if (priority < periph->immediate_priority) {
4739 			periph->immediate_priority = priority;
4740 			xpt_run_allocq(periph, 0);
4741 		} else
4742 			cam_periph_sleep(periph, &periph->ccb_list, PRIBIO,
4743 			    "cgticb", 0);
4744 	}
4745 	SLIST_REMOVE_HEAD(&periph->ccb_list, periph_links.sle);
4746 	return ((union ccb *)ccb_h);
4747 }
4748 
4749 static void
4750 xpt_acquire_bus(struct cam_eb *bus)
4751 {
4752 
4753 	xpt_lock_buses();
4754 	bus->refcount++;
4755 	xpt_unlock_buses();
4756 }
4757 
4758 static void
4759 xpt_release_bus(struct cam_eb *bus)
4760 {
4761 
4762 	xpt_lock_buses();
4763 	KASSERT(bus->refcount >= 1, ("bus->refcount >= 1"));
4764 	if (--bus->refcount > 0) {
4765 		xpt_unlock_buses();
4766 		return;
4767 	}
4768 	TAILQ_REMOVE(&xsoftc.xpt_busses, bus, links);
4769 	xsoftc.bus_generation++;
4770 	xpt_unlock_buses();
4771 	KASSERT(TAILQ_EMPTY(&bus->et_entries),
4772 	    ("destroying bus, but target list is not empty"));
4773 	cam_sim_release(bus->sim);
4774 	mtx_destroy(&bus->eb_mtx);
4775 	free(bus, M_CAMXPT);
4776 }
4777 
4778 static struct cam_et *
4779 xpt_alloc_target(struct cam_eb *bus, target_id_t target_id)
4780 {
4781 	struct cam_et *cur_target, *target;
4782 
4783 	mtx_assert(&xsoftc.xpt_topo_lock, MA_OWNED);
4784 	mtx_assert(&bus->eb_mtx, MA_OWNED);
4785 	target = (struct cam_et *)malloc(sizeof(*target), M_CAMXPT,
4786 					 M_NOWAIT|M_ZERO);
4787 	if (target == NULL)
4788 		return (NULL);
4789 
4790 	TAILQ_INIT(&target->ed_entries);
4791 	target->bus = bus;
4792 	target->target_id = target_id;
4793 	target->refcount = 1;
4794 	target->generation = 0;
4795 	target->luns = NULL;
4796 	mtx_init(&target->luns_mtx, "CAM LUNs lock", NULL, MTX_DEF);
4797 	timevalclear(&target->last_reset);
4798 	/*
4799 	 * Hold a reference to our parent bus so it
4800 	 * will not go away before we do.
4801 	 */
4802 	bus->refcount++;
4803 
4804 	/* Insertion sort into our bus's target list */
4805 	cur_target = TAILQ_FIRST(&bus->et_entries);
4806 	while (cur_target != NULL && cur_target->target_id < target_id)
4807 		cur_target = TAILQ_NEXT(cur_target, links);
4808 	if (cur_target != NULL) {
4809 		TAILQ_INSERT_BEFORE(cur_target, target, links);
4810 	} else {
4811 		TAILQ_INSERT_TAIL(&bus->et_entries, target, links);
4812 	}
4813 	bus->generation++;
4814 	return (target);
4815 }
4816 
4817 static void
4818 xpt_acquire_target(struct cam_et *target)
4819 {
4820 	struct cam_eb *bus = target->bus;
4821 
4822 	mtx_lock(&bus->eb_mtx);
4823 	target->refcount++;
4824 	mtx_unlock(&bus->eb_mtx);
4825 }
4826 
4827 static void
4828 xpt_release_target(struct cam_et *target)
4829 {
4830 	struct cam_eb *bus = target->bus;
4831 
4832 	mtx_lock(&bus->eb_mtx);
4833 	if (--target->refcount > 0) {
4834 		mtx_unlock(&bus->eb_mtx);
4835 		return;
4836 	}
4837 	TAILQ_REMOVE(&bus->et_entries, target, links);
4838 	bus->generation++;
4839 	mtx_unlock(&bus->eb_mtx);
4840 	KASSERT(TAILQ_EMPTY(&target->ed_entries),
4841 	    ("destroying target, but device list is not empty"));
4842 	xpt_release_bus(bus);
4843 	mtx_destroy(&target->luns_mtx);
4844 	if (target->luns)
4845 		free(target->luns, M_CAMXPT);
4846 	free(target, M_CAMXPT);
4847 }
4848 
4849 static struct cam_ed *
4850 xpt_alloc_device_default(struct cam_eb *bus, struct cam_et *target,
4851 			 lun_id_t lun_id)
4852 {
4853 	struct cam_ed *device;
4854 
4855 	device = xpt_alloc_device(bus, target, lun_id);
4856 	if (device == NULL)
4857 		return (NULL);
4858 
4859 	device->mintags = 1;
4860 	device->maxtags = 1;
4861 	return (device);
4862 }
4863 
4864 static void
4865 xpt_destroy_device(void *context, int pending)
4866 {
4867 	struct cam_ed	*device = context;
4868 
4869 	mtx_lock(&device->device_mtx);
4870 	mtx_destroy(&device->device_mtx);
4871 	free(device, M_CAMDEV);
4872 }
4873 
4874 struct cam_ed *
4875 xpt_alloc_device(struct cam_eb *bus, struct cam_et *target, lun_id_t lun_id)
4876 {
4877 	struct cam_ed	*cur_device, *device;
4878 	struct cam_devq	*devq;
4879 	cam_status status;
4880 
4881 	mtx_assert(&bus->eb_mtx, MA_OWNED);
4882 	/* Make space for us in the device queue on our bus */
4883 	devq = bus->sim->devq;
4884 	mtx_lock(&devq->send_mtx);
4885 	status = cam_devq_resize(devq, devq->send_queue.array_size + 1);
4886 	mtx_unlock(&devq->send_mtx);
4887 	if (status != CAM_REQ_CMP)
4888 		return (NULL);
4889 
4890 	device = (struct cam_ed *)malloc(sizeof(*device),
4891 					 M_CAMDEV, M_NOWAIT|M_ZERO);
4892 	if (device == NULL)
4893 		return (NULL);
4894 
4895 	cam_init_pinfo(&device->devq_entry);
4896 	device->target = target;
4897 	device->lun_id = lun_id;
4898 	device->sim = bus->sim;
4899 	if (cam_ccbq_init(&device->ccbq,
4900 			  bus->sim->max_dev_openings) != 0) {
4901 		free(device, M_CAMDEV);
4902 		return (NULL);
4903 	}
4904 	SLIST_INIT(&device->asyncs);
4905 	SLIST_INIT(&device->periphs);
4906 	device->generation = 0;
4907 	device->flags = CAM_DEV_UNCONFIGURED;
4908 	device->tag_delay_count = 0;
4909 	device->tag_saved_openings = 0;
4910 	device->refcount = 1;
4911 	mtx_init(&device->device_mtx, "CAM device lock", NULL, MTX_DEF);
4912 	callout_init_mtx(&device->callout, &devq->send_mtx, 0);
4913 	TASK_INIT(&device->device_destroy_task, 0, xpt_destroy_device, device);
4914 	/*
4915 	 * Hold a reference to our parent bus so it
4916 	 * will not go away before we do.
4917 	 */
4918 	target->refcount++;
4919 
4920 	cur_device = TAILQ_FIRST(&target->ed_entries);
4921 	while (cur_device != NULL && cur_device->lun_id < lun_id)
4922 		cur_device = TAILQ_NEXT(cur_device, links);
4923 	if (cur_device != NULL)
4924 		TAILQ_INSERT_BEFORE(cur_device, device, links);
4925 	else
4926 		TAILQ_INSERT_TAIL(&target->ed_entries, device, links);
4927 	target->generation++;
4928 	return (device);
4929 }
4930 
4931 void
4932 xpt_acquire_device(struct cam_ed *device)
4933 {
4934 	struct cam_eb *bus = device->target->bus;
4935 
4936 	mtx_lock(&bus->eb_mtx);
4937 	device->refcount++;
4938 	mtx_unlock(&bus->eb_mtx);
4939 }
4940 
4941 void
4942 xpt_release_device(struct cam_ed *device)
4943 {
4944 	struct cam_eb *bus = device->target->bus;
4945 	struct cam_devq *devq;
4946 
4947 	mtx_lock(&bus->eb_mtx);
4948 	if (--device->refcount > 0) {
4949 		mtx_unlock(&bus->eb_mtx);
4950 		return;
4951 	}
4952 
4953 	TAILQ_REMOVE(&device->target->ed_entries, device,links);
4954 	device->target->generation++;
4955 	mtx_unlock(&bus->eb_mtx);
4956 
4957 	/* Release our slot in the devq */
4958 	devq = bus->sim->devq;
4959 	mtx_lock(&devq->send_mtx);
4960 	cam_devq_resize(devq, devq->send_queue.array_size - 1);
4961 	mtx_unlock(&devq->send_mtx);
4962 
4963 	KASSERT(SLIST_EMPTY(&device->periphs),
4964 	    ("destroying device, but periphs list is not empty"));
4965 	KASSERT(device->devq_entry.index == CAM_UNQUEUED_INDEX,
4966 	    ("destroying device while still queued for ccbs"));
4967 
4968 	if ((device->flags & CAM_DEV_REL_TIMEOUT_PENDING) != 0)
4969 		callout_stop(&device->callout);
4970 
4971 	xpt_release_target(device->target);
4972 
4973 	cam_ccbq_fini(&device->ccbq);
4974 	/*
4975 	 * Free allocated memory.  free(9) does nothing if the
4976 	 * supplied pointer is NULL, so it is safe to call without
4977 	 * checking.
4978 	 */
4979 	free(device->supported_vpds, M_CAMXPT);
4980 	free(device->device_id, M_CAMXPT);
4981 	free(device->ext_inq, M_CAMXPT);
4982 	free(device->physpath, M_CAMXPT);
4983 	free(device->rcap_buf, M_CAMXPT);
4984 	free(device->serial_num, M_CAMXPT);
4985 	taskqueue_enqueue(xsoftc.xpt_taskq, &device->device_destroy_task);
4986 }
4987 
4988 u_int32_t
4989 xpt_dev_ccbq_resize(struct cam_path *path, int newopenings)
4990 {
4991 	int	result;
4992 	struct	cam_ed *dev;
4993 
4994 	dev = path->device;
4995 	mtx_lock(&dev->sim->devq->send_mtx);
4996 	result = cam_ccbq_resize(&dev->ccbq, newopenings);
4997 	mtx_unlock(&dev->sim->devq->send_mtx);
4998 	if ((dev->flags & CAM_DEV_TAG_AFTER_COUNT) != 0
4999 	 || (dev->inq_flags & SID_CmdQue) != 0)
5000 		dev->tag_saved_openings = newopenings;
5001 	return (result);
5002 }
5003 
5004 static struct cam_eb *
5005 xpt_find_bus(path_id_t path_id)
5006 {
5007 	struct cam_eb *bus;
5008 
5009 	xpt_lock_buses();
5010 	for (bus = TAILQ_FIRST(&xsoftc.xpt_busses);
5011 	     bus != NULL;
5012 	     bus = TAILQ_NEXT(bus, links)) {
5013 		if (bus->path_id == path_id) {
5014 			bus->refcount++;
5015 			break;
5016 		}
5017 	}
5018 	xpt_unlock_buses();
5019 	return (bus);
5020 }
5021 
5022 static struct cam_et *
5023 xpt_find_target(struct cam_eb *bus, target_id_t	target_id)
5024 {
5025 	struct cam_et *target;
5026 
5027 	mtx_assert(&bus->eb_mtx, MA_OWNED);
5028 	for (target = TAILQ_FIRST(&bus->et_entries);
5029 	     target != NULL;
5030 	     target = TAILQ_NEXT(target, links)) {
5031 		if (target->target_id == target_id) {
5032 			target->refcount++;
5033 			break;
5034 		}
5035 	}
5036 	return (target);
5037 }
5038 
5039 static struct cam_ed *
5040 xpt_find_device(struct cam_et *target, lun_id_t lun_id)
5041 {
5042 	struct cam_ed *device;
5043 
5044 	mtx_assert(&target->bus->eb_mtx, MA_OWNED);
5045 	for (device = TAILQ_FIRST(&target->ed_entries);
5046 	     device != NULL;
5047 	     device = TAILQ_NEXT(device, links)) {
5048 		if (device->lun_id == lun_id) {
5049 			device->refcount++;
5050 			break;
5051 		}
5052 	}
5053 	return (device);
5054 }
5055 
5056 void
5057 xpt_start_tags(struct cam_path *path)
5058 {
5059 	struct ccb_relsim crs;
5060 	struct cam_ed *device;
5061 	struct cam_sim *sim;
5062 	int    newopenings;
5063 
5064 	device = path->device;
5065 	sim = path->bus->sim;
5066 	device->flags &= ~CAM_DEV_TAG_AFTER_COUNT;
5067 	xpt_freeze_devq(path, /*count*/1);
5068 	device->inq_flags |= SID_CmdQue;
5069 	if (device->tag_saved_openings != 0)
5070 		newopenings = device->tag_saved_openings;
5071 	else
5072 		newopenings = min(device->maxtags,
5073 				  sim->max_tagged_dev_openings);
5074 	xpt_dev_ccbq_resize(path, newopenings);
5075 	xpt_async(AC_GETDEV_CHANGED, path, NULL);
5076 	xpt_setup_ccb(&crs.ccb_h, path, CAM_PRIORITY_NORMAL);
5077 	crs.ccb_h.func_code = XPT_REL_SIMQ;
5078 	crs.release_flags = RELSIM_RELEASE_AFTER_QEMPTY;
5079 	crs.openings
5080 	    = crs.release_timeout
5081 	    = crs.qfrozen_cnt
5082 	    = 0;
5083 	xpt_action((union ccb *)&crs);
5084 }
5085 
5086 void
5087 xpt_stop_tags(struct cam_path *path)
5088 {
5089 	struct ccb_relsim crs;
5090 	struct cam_ed *device;
5091 	struct cam_sim *sim;
5092 
5093 	device = path->device;
5094 	sim = path->bus->sim;
5095 	device->flags &= ~CAM_DEV_TAG_AFTER_COUNT;
5096 	device->tag_delay_count = 0;
5097 	xpt_freeze_devq(path, /*count*/1);
5098 	device->inq_flags &= ~SID_CmdQue;
5099 	xpt_dev_ccbq_resize(path, sim->max_dev_openings);
5100 	xpt_async(AC_GETDEV_CHANGED, path, NULL);
5101 	xpt_setup_ccb(&crs.ccb_h, path, CAM_PRIORITY_NORMAL);
5102 	crs.ccb_h.func_code = XPT_REL_SIMQ;
5103 	crs.release_flags = RELSIM_RELEASE_AFTER_QEMPTY;
5104 	crs.openings
5105 	    = crs.release_timeout
5106 	    = crs.qfrozen_cnt
5107 	    = 0;
5108 	xpt_action((union ccb *)&crs);
5109 }
5110 
5111 static void
5112 xpt_boot_delay(void *arg)
5113 {
5114 
5115 	xpt_release_boot();
5116 }
5117 
5118 static void
5119 xpt_config(void *arg)
5120 {
5121 	/*
5122 	 * Now that interrupts are enabled, go find our devices
5123 	 */
5124 	if (taskqueue_start_threads(&xsoftc.xpt_taskq, 1, PRIBIO, "CAM taskq"))
5125 		printf("xpt_config: failed to create taskqueue thread.\n");
5126 
5127 	/* Setup debugging path */
5128 	if (cam_dflags != CAM_DEBUG_NONE) {
5129 		if (xpt_create_path(&cam_dpath, NULL,
5130 				    CAM_DEBUG_BUS, CAM_DEBUG_TARGET,
5131 				    CAM_DEBUG_LUN) != CAM_REQ_CMP) {
5132 			printf("xpt_config: xpt_create_path() failed for debug"
5133 			       " target %d:%d:%d, debugging disabled\n",
5134 			       CAM_DEBUG_BUS, CAM_DEBUG_TARGET, CAM_DEBUG_LUN);
5135 			cam_dflags = CAM_DEBUG_NONE;
5136 		}
5137 	} else
5138 		cam_dpath = NULL;
5139 
5140 	periphdriver_init(1);
5141 	xpt_hold_boot();
5142 	callout_init(&xsoftc.boot_callout, 1);
5143 	callout_reset_sbt(&xsoftc.boot_callout, SBT_1MS * xsoftc.boot_delay, 0,
5144 	    xpt_boot_delay, NULL, 0);
5145 	/* Fire up rescan thread. */
5146 	if (kproc_kthread_add(xpt_scanner_thread, NULL, &cam_proc, NULL, 0, 0,
5147 	    "cam", "scanner")) {
5148 		printf("xpt_config: failed to create rescan thread.\n");
5149 	}
5150 }
5151 
5152 void
5153 xpt_hold_boot(void)
5154 {
5155 	xpt_lock_buses();
5156 	xsoftc.buses_to_config++;
5157 	xpt_unlock_buses();
5158 }
5159 
5160 void
5161 xpt_release_boot(void)
5162 {
5163 	xpt_lock_buses();
5164 	xsoftc.buses_to_config--;
5165 	if (xsoftc.buses_to_config == 0 && xsoftc.buses_config_done == 0) {
5166 		struct	xpt_task *task;
5167 
5168 		xsoftc.buses_config_done = 1;
5169 		xpt_unlock_buses();
5170 		/* Call manually because we don't have any buses */
5171 		task = malloc(sizeof(struct xpt_task), M_CAMXPT, M_NOWAIT);
5172 		if (task != NULL) {
5173 			TASK_INIT(&task->task, 0, xpt_finishconfig_task, task);
5174 			taskqueue_enqueue(taskqueue_thread, &task->task);
5175 		}
5176 	} else
5177 		xpt_unlock_buses();
5178 }
5179 
5180 /*
5181  * If the given device only has one peripheral attached to it, and if that
5182  * peripheral is the passthrough driver, announce it.  This insures that the
5183  * user sees some sort of announcement for every peripheral in their system.
5184  */
5185 static int
5186 xptpassannouncefunc(struct cam_ed *device, void *arg)
5187 {
5188 	struct cam_periph *periph;
5189 	int i;
5190 
5191 	for (periph = SLIST_FIRST(&device->periphs), i = 0; periph != NULL;
5192 	     periph = SLIST_NEXT(periph, periph_links), i++);
5193 
5194 	periph = SLIST_FIRST(&device->periphs);
5195 	if ((i == 1)
5196 	 && (strncmp(periph->periph_name, "pass", 4) == 0))
5197 		xpt_announce_periph(periph, NULL);
5198 
5199 	return(1);
5200 }
5201 
5202 static void
5203 xpt_finishconfig_task(void *context, int pending)
5204 {
5205 
5206 	periphdriver_init(2);
5207 	/*
5208 	 * Check for devices with no "standard" peripheral driver
5209 	 * attached.  For any devices like that, announce the
5210 	 * passthrough driver so the user will see something.
5211 	 */
5212 	if (!bootverbose)
5213 		xpt_for_all_devices(xptpassannouncefunc, NULL);
5214 
5215 	/* Release our hook so that the boot can continue. */
5216 	config_intrhook_disestablish(xsoftc.xpt_config_hook);
5217 	free(xsoftc.xpt_config_hook, M_CAMXPT);
5218 	xsoftc.xpt_config_hook = NULL;
5219 
5220 	free(context, M_CAMXPT);
5221 }
5222 
5223 cam_status
5224 xpt_register_async(int event, ac_callback_t *cbfunc, void *cbarg,
5225 		   struct cam_path *path)
5226 {
5227 	struct ccb_setasync csa;
5228 	cam_status status;
5229 	int xptpath = 0;
5230 
5231 	if (path == NULL) {
5232 		status = xpt_create_path(&path, /*periph*/NULL, CAM_XPT_PATH_ID,
5233 					 CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
5234 		if (status != CAM_REQ_CMP)
5235 			return (status);
5236 		xpt_path_lock(path);
5237 		xptpath = 1;
5238 	}
5239 
5240 	xpt_setup_ccb(&csa.ccb_h, path, CAM_PRIORITY_NORMAL);
5241 	csa.ccb_h.func_code = XPT_SASYNC_CB;
5242 	csa.event_enable = event;
5243 	csa.callback = cbfunc;
5244 	csa.callback_arg = cbarg;
5245 	xpt_action((union ccb *)&csa);
5246 	status = csa.ccb_h.status;
5247 
5248 	CAM_DEBUG(csa.ccb_h.path, CAM_DEBUG_TRACE,
5249 	    ("xpt_register_async: func %p\n", cbfunc));
5250 
5251 	if (xptpath) {
5252 		xpt_path_unlock(path);
5253 		xpt_free_path(path);
5254 	}
5255 
5256 	if ((status == CAM_REQ_CMP) &&
5257 	    (csa.event_enable & AC_FOUND_DEVICE)) {
5258 		/*
5259 		 * Get this peripheral up to date with all
5260 		 * the currently existing devices.
5261 		 */
5262 		xpt_for_all_devices(xptsetasyncfunc, &csa);
5263 	}
5264 	if ((status == CAM_REQ_CMP) &&
5265 	    (csa.event_enable & AC_PATH_REGISTERED)) {
5266 		/*
5267 		 * Get this peripheral up to date with all
5268 		 * the currently existing buses.
5269 		 */
5270 		xpt_for_all_busses(xptsetasyncbusfunc, &csa);
5271 	}
5272 
5273 	return (status);
5274 }
5275 
5276 static void
5277 xptaction(struct cam_sim *sim, union ccb *work_ccb)
5278 {
5279 	CAM_DEBUG(work_ccb->ccb_h.path, CAM_DEBUG_TRACE, ("xptaction\n"));
5280 
5281 	switch (work_ccb->ccb_h.func_code) {
5282 	/* Common cases first */
5283 	case XPT_PATH_INQ:		/* Path routing inquiry */
5284 	{
5285 		struct ccb_pathinq *cpi;
5286 
5287 		cpi = &work_ccb->cpi;
5288 		cpi->version_num = 1; /* XXX??? */
5289 		cpi->hba_inquiry = 0;
5290 		cpi->target_sprt = 0;
5291 		cpi->hba_misc = 0;
5292 		cpi->hba_eng_cnt = 0;
5293 		cpi->max_target = 0;
5294 		cpi->max_lun = 0;
5295 		cpi->initiator_id = 0;
5296 		strlcpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
5297 		strlcpy(cpi->hba_vid, "", HBA_IDLEN);
5298 		strlcpy(cpi->dev_name, sim->sim_name, DEV_IDLEN);
5299 		cpi->unit_number = sim->unit_number;
5300 		cpi->bus_id = sim->bus_id;
5301 		cpi->base_transfer_speed = 0;
5302 		cpi->protocol = PROTO_UNSPECIFIED;
5303 		cpi->protocol_version = PROTO_VERSION_UNSPECIFIED;
5304 		cpi->transport = XPORT_UNSPECIFIED;
5305 		cpi->transport_version = XPORT_VERSION_UNSPECIFIED;
5306 		cpi->ccb_h.status = CAM_REQ_CMP;
5307 		xpt_done(work_ccb);
5308 		break;
5309 	}
5310 	default:
5311 		work_ccb->ccb_h.status = CAM_REQ_INVALID;
5312 		xpt_done(work_ccb);
5313 		break;
5314 	}
5315 }
5316 
5317 /*
5318  * The xpt as a "controller" has no interrupt sources, so polling
5319  * is a no-op.
5320  */
5321 static void
5322 xptpoll(struct cam_sim *sim)
5323 {
5324 }
5325 
5326 void
5327 xpt_lock_buses(void)
5328 {
5329 	mtx_lock(&xsoftc.xpt_topo_lock);
5330 }
5331 
5332 void
5333 xpt_unlock_buses(void)
5334 {
5335 	mtx_unlock(&xsoftc.xpt_topo_lock);
5336 }
5337 
5338 struct mtx *
5339 xpt_path_mtx(struct cam_path *path)
5340 {
5341 
5342 	return (&path->device->device_mtx);
5343 }
5344 
5345 static void
5346 xpt_done_process(struct ccb_hdr *ccb_h)
5347 {
5348 	struct cam_sim *sim;
5349 	struct cam_devq *devq;
5350 	struct mtx *mtx = NULL;
5351 
5352 #if defined(BUF_TRACKING) || defined(FULL_BUF_TRACKING)
5353 	struct ccb_scsiio *csio;
5354 
5355 	if (ccb_h->func_code == XPT_SCSI_IO) {
5356 		csio = &((union ccb *)ccb_h)->csio;
5357 		if (csio->bio != NULL)
5358 			biotrack(csio->bio, __func__);
5359 	}
5360 #endif
5361 
5362 	if (ccb_h->flags & CAM_HIGH_POWER) {
5363 		struct highpowerlist	*hphead;
5364 		struct cam_ed		*device;
5365 
5366 		mtx_lock(&xsoftc.xpt_highpower_lock);
5367 		hphead = &xsoftc.highpowerq;
5368 
5369 		device = STAILQ_FIRST(hphead);
5370 
5371 		/*
5372 		 * Increment the count since this command is done.
5373 		 */
5374 		xsoftc.num_highpower++;
5375 
5376 		/*
5377 		 * Any high powered commands queued up?
5378 		 */
5379 		if (device != NULL) {
5380 
5381 			STAILQ_REMOVE_HEAD(hphead, highpowerq_entry);
5382 			mtx_unlock(&xsoftc.xpt_highpower_lock);
5383 
5384 			mtx_lock(&device->sim->devq->send_mtx);
5385 			xpt_release_devq_device(device,
5386 					 /*count*/1, /*runqueue*/TRUE);
5387 			mtx_unlock(&device->sim->devq->send_mtx);
5388 		} else
5389 			mtx_unlock(&xsoftc.xpt_highpower_lock);
5390 	}
5391 
5392 	sim = ccb_h->path->bus->sim;
5393 
5394 	if (ccb_h->status & CAM_RELEASE_SIMQ) {
5395 		xpt_release_simq(sim, /*run_queue*/FALSE);
5396 		ccb_h->status &= ~CAM_RELEASE_SIMQ;
5397 	}
5398 
5399 	if ((ccb_h->flags & CAM_DEV_QFRZDIS)
5400 	 && (ccb_h->status & CAM_DEV_QFRZN)) {
5401 		xpt_release_devq(ccb_h->path, /*count*/1, /*run_queue*/TRUE);
5402 		ccb_h->status &= ~CAM_DEV_QFRZN;
5403 	}
5404 
5405 	devq = sim->devq;
5406 	if ((ccb_h->func_code & XPT_FC_USER_CCB) == 0) {
5407 		struct cam_ed *dev = ccb_h->path->device;
5408 
5409 		mtx_lock(&devq->send_mtx);
5410 		devq->send_active--;
5411 		devq->send_openings++;
5412 		cam_ccbq_ccb_done(&dev->ccbq, (union ccb *)ccb_h);
5413 
5414 		if (((dev->flags & CAM_DEV_REL_ON_QUEUE_EMPTY) != 0
5415 		  && (dev->ccbq.dev_active == 0))) {
5416 			dev->flags &= ~CAM_DEV_REL_ON_QUEUE_EMPTY;
5417 			xpt_release_devq_device(dev, /*count*/1,
5418 					 /*run_queue*/FALSE);
5419 		}
5420 
5421 		if (((dev->flags & CAM_DEV_REL_ON_COMPLETE) != 0
5422 		  && (ccb_h->status&CAM_STATUS_MASK) != CAM_REQUEUE_REQ)) {
5423 			dev->flags &= ~CAM_DEV_REL_ON_COMPLETE;
5424 			xpt_release_devq_device(dev, /*count*/1,
5425 					 /*run_queue*/FALSE);
5426 		}
5427 
5428 		if (!device_is_queued(dev))
5429 			(void)xpt_schedule_devq(devq, dev);
5430 		xpt_run_devq(devq);
5431 		mtx_unlock(&devq->send_mtx);
5432 
5433 		if ((dev->flags & CAM_DEV_TAG_AFTER_COUNT) != 0) {
5434 			mtx = xpt_path_mtx(ccb_h->path);
5435 			mtx_lock(mtx);
5436 
5437 			if ((dev->flags & CAM_DEV_TAG_AFTER_COUNT) != 0
5438 			 && (--dev->tag_delay_count == 0))
5439 				xpt_start_tags(ccb_h->path);
5440 		}
5441 	}
5442 
5443 	if ((ccb_h->flags & CAM_UNLOCKED) == 0) {
5444 		if (mtx == NULL) {
5445 			mtx = xpt_path_mtx(ccb_h->path);
5446 			mtx_lock(mtx);
5447 		}
5448 	} else {
5449 		if (mtx != NULL) {
5450 			mtx_unlock(mtx);
5451 			mtx = NULL;
5452 		}
5453 	}
5454 
5455 	/* Call the peripheral driver's callback */
5456 	ccb_h->pinfo.index = CAM_UNQUEUED_INDEX;
5457 	(*ccb_h->cbfcnp)(ccb_h->path->periph, (union ccb *)ccb_h);
5458 	if (mtx != NULL)
5459 		mtx_unlock(mtx);
5460 }
5461 
5462 void
5463 xpt_done_td(void *arg)
5464 {
5465 	struct cam_doneq *queue = arg;
5466 	struct ccb_hdr *ccb_h;
5467 	STAILQ_HEAD(, ccb_hdr)	doneq;
5468 
5469 	STAILQ_INIT(&doneq);
5470 	mtx_lock(&queue->cam_doneq_mtx);
5471 	while (1) {
5472 		while (STAILQ_EMPTY(&queue->cam_doneq)) {
5473 			queue->cam_doneq_sleep = 1;
5474 			msleep(&queue->cam_doneq, &queue->cam_doneq_mtx,
5475 			    PRIBIO, "-", 0);
5476 			queue->cam_doneq_sleep = 0;
5477 		}
5478 		STAILQ_CONCAT(&doneq, &queue->cam_doneq);
5479 		mtx_unlock(&queue->cam_doneq_mtx);
5480 
5481 		THREAD_NO_SLEEPING();
5482 		while ((ccb_h = STAILQ_FIRST(&doneq)) != NULL) {
5483 			STAILQ_REMOVE_HEAD(&doneq, sim_links.stqe);
5484 			xpt_done_process(ccb_h);
5485 		}
5486 		THREAD_SLEEPING_OK();
5487 
5488 		mtx_lock(&queue->cam_doneq_mtx);
5489 	}
5490 }
5491 
5492 static void
5493 camisr_runqueue(void)
5494 {
5495 	struct	ccb_hdr *ccb_h;
5496 	struct cam_doneq *queue;
5497 	int i;
5498 
5499 	/* Process global queues. */
5500 	for (i = 0; i < cam_num_doneqs; i++) {
5501 		queue = &cam_doneqs[i];
5502 		mtx_lock(&queue->cam_doneq_mtx);
5503 		while ((ccb_h = STAILQ_FIRST(&queue->cam_doneq)) != NULL) {
5504 			STAILQ_REMOVE_HEAD(&queue->cam_doneq, sim_links.stqe);
5505 			mtx_unlock(&queue->cam_doneq_mtx);
5506 			xpt_done_process(ccb_h);
5507 			mtx_lock(&queue->cam_doneq_mtx);
5508 		}
5509 		mtx_unlock(&queue->cam_doneq_mtx);
5510 	}
5511 }
5512 
5513 struct kv
5514 {
5515 	uint32_t v;
5516 	const char *name;
5517 };
5518 
5519 static struct kv map[] = {
5520 	{ XPT_NOOP, "XPT_NOOP" },
5521 	{ XPT_SCSI_IO, "XPT_SCSI_IO" },
5522 	{ XPT_GDEV_TYPE, "XPT_GDEV_TYPE" },
5523 	{ XPT_GDEVLIST, "XPT_GDEVLIST" },
5524 	{ XPT_PATH_INQ, "XPT_PATH_INQ" },
5525 	{ XPT_REL_SIMQ, "XPT_REL_SIMQ" },
5526 	{ XPT_SASYNC_CB, "XPT_SASYNC_CB" },
5527 	{ XPT_SDEV_TYPE, "XPT_SDEV_TYPE" },
5528 	{ XPT_SCAN_BUS, "XPT_SCAN_BUS" },
5529 	{ XPT_DEV_MATCH, "XPT_DEV_MATCH" },
5530 	{ XPT_DEBUG, "XPT_DEBUG" },
5531 	{ XPT_PATH_STATS, "XPT_PATH_STATS" },
5532 	{ XPT_GDEV_STATS, "XPT_GDEV_STATS" },
5533 	{ XPT_DEV_ADVINFO, "XPT_DEV_ADVINFO" },
5534 	{ XPT_ASYNC, "XPT_ASYNC" },
5535 	{ XPT_ABORT, "XPT_ABORT" },
5536 	{ XPT_RESET_BUS, "XPT_RESET_BUS" },
5537 	{ XPT_RESET_DEV, "XPT_RESET_DEV" },
5538 	{ XPT_TERM_IO, "XPT_TERM_IO" },
5539 	{ XPT_SCAN_LUN, "XPT_SCAN_LUN" },
5540 	{ XPT_GET_TRAN_SETTINGS, "XPT_GET_TRAN_SETTINGS" },
5541 	{ XPT_SET_TRAN_SETTINGS, "XPT_SET_TRAN_SETTINGS" },
5542 	{ XPT_CALC_GEOMETRY, "XPT_CALC_GEOMETRY" },
5543 	{ XPT_ATA_IO, "XPT_ATA_IO" },
5544 	{ XPT_GET_SIM_KNOB, "XPT_GET_SIM_KNOB" },
5545 	{ XPT_SET_SIM_KNOB, "XPT_SET_SIM_KNOB" },
5546 	{ XPT_NVME_IO, "XPT_NVME_IO" },
5547 	{ XPT_MMC_IO, "XPT_MMC_IO" },
5548 	{ XPT_SMP_IO, "XPT_SMP_IO" },
5549 	{ XPT_SCAN_TGT, "XPT_SCAN_TGT" },
5550 	{ XPT_NVME_ADMIN, "XPT_NVME_ADMIN" },
5551 	{ XPT_ENG_INQ, "XPT_ENG_INQ" },
5552 	{ XPT_ENG_EXEC, "XPT_ENG_EXEC" },
5553 	{ XPT_EN_LUN, "XPT_EN_LUN" },
5554 	{ XPT_TARGET_IO, "XPT_TARGET_IO" },
5555 	{ XPT_ACCEPT_TARGET_IO, "XPT_ACCEPT_TARGET_IO" },
5556 	{ XPT_CONT_TARGET_IO, "XPT_CONT_TARGET_IO" },
5557 	{ XPT_IMMED_NOTIFY, "XPT_IMMED_NOTIFY" },
5558 	{ XPT_NOTIFY_ACK, "XPT_NOTIFY_ACK" },
5559 	{ XPT_IMMEDIATE_NOTIFY, "XPT_IMMEDIATE_NOTIFY" },
5560 	{ XPT_NOTIFY_ACKNOWLEDGE, "XPT_NOTIFY_ACKNOWLEDGE" },
5561 	{ 0, 0 }
5562 };
5563 
5564 const char *
5565 xpt_action_name(uint32_t action)
5566 {
5567 	static char buffer[32];	/* Only for unknown messages -- racy */
5568 	struct kv *walker = map;
5569 
5570 	while (walker->name != NULL) {
5571 		if (walker->v == action)
5572 			return (walker->name);
5573 		walker++;
5574 	}
5575 
5576 	snprintf(buffer, sizeof(buffer), "%#x", action);
5577 	return (buffer);
5578 }
5579