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