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