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