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