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