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