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