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