xref: /freebsd/sys/cam/cam_xpt.c (revision 2710751bc309af25c6dea1171781678258e83840)
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 int
1088 xpt_getattr(char *buf, size_t len, const char *attr, struct cam_path *path)
1089 {
1090 	int ret = -1;
1091 	struct ccb_dev_advinfo cdai;
1092 
1093 	mtx_assert(path->bus->sim->mtx, MA_OWNED);
1094 
1095 	memset(&cdai, 0, sizeof(cdai));
1096 	xpt_setup_ccb(&cdai.ccb_h, path, CAM_PRIORITY_NORMAL);
1097 	cdai.ccb_h.func_code = XPT_DEV_ADVINFO;
1098 	cdai.bufsiz = len;
1099 
1100 	if (!strcmp(attr, "GEOM::ident"))
1101 		cdai.buftype = CDAI_TYPE_SERIAL_NUM;
1102 	else if (!strcmp(attr, "GEOM::physpath"))
1103 		cdai.buftype = CDAI_TYPE_PHYS_PATH;
1104 	else
1105 		goto out;
1106 
1107 	cdai.buf = malloc(cdai.bufsiz, M_CAMXPT, M_NOWAIT|M_ZERO);
1108 	if (cdai.buf == NULL) {
1109 		ret = ENOMEM;
1110 		goto out;
1111 	}
1112 	xpt_action((union ccb *)&cdai); /* can only be synchronous */
1113 	if ((cdai.ccb_h.status & CAM_DEV_QFRZN) != 0)
1114 		cam_release_devq(cdai.ccb_h.path, 0, 0, 0, FALSE);
1115 	if (cdai.provsiz == 0)
1116 		goto out;
1117 	ret = 0;
1118 	if (strlcpy(buf, cdai.buf, len) >= len)
1119 		ret = EFAULT;
1120 
1121 out:
1122 	if (cdai.buf != NULL)
1123 		free(cdai.buf, M_CAMXPT);
1124 	return ret;
1125 }
1126 
1127 static dev_match_ret
1128 xptbusmatch(struct dev_match_pattern *patterns, u_int num_patterns,
1129 	    struct cam_eb *bus)
1130 {
1131 	dev_match_ret retval;
1132 	int i;
1133 
1134 	retval = DM_RET_NONE;
1135 
1136 	/*
1137 	 * If we aren't given something to match against, that's an error.
1138 	 */
1139 	if (bus == NULL)
1140 		return(DM_RET_ERROR);
1141 
1142 	/*
1143 	 * If there are no match entries, then this bus matches no
1144 	 * matter what.
1145 	 */
1146 	if ((patterns == NULL) || (num_patterns == 0))
1147 		return(DM_RET_DESCEND | DM_RET_COPY);
1148 
1149 	for (i = 0; i < num_patterns; i++) {
1150 		struct bus_match_pattern *cur_pattern;
1151 
1152 		/*
1153 		 * If the pattern in question isn't for a bus node, we
1154 		 * aren't interested.  However, we do indicate to the
1155 		 * calling routine that we should continue descending the
1156 		 * tree, since the user wants to match against lower-level
1157 		 * EDT elements.
1158 		 */
1159 		if (patterns[i].type != DEV_MATCH_BUS) {
1160 			if ((retval & DM_RET_ACTION_MASK) == DM_RET_NONE)
1161 				retval |= DM_RET_DESCEND;
1162 			continue;
1163 		}
1164 
1165 		cur_pattern = &patterns[i].pattern.bus_pattern;
1166 
1167 		/*
1168 		 * If they want to match any bus node, we give them any
1169 		 * device node.
1170 		 */
1171 		if (cur_pattern->flags == BUS_MATCH_ANY) {
1172 			/* set the copy flag */
1173 			retval |= DM_RET_COPY;
1174 
1175 			/*
1176 			 * If we've already decided on an action, go ahead
1177 			 * and return.
1178 			 */
1179 			if ((retval & DM_RET_ACTION_MASK) != DM_RET_NONE)
1180 				return(retval);
1181 		}
1182 
1183 		/*
1184 		 * Not sure why someone would do this...
1185 		 */
1186 		if (cur_pattern->flags == BUS_MATCH_NONE)
1187 			continue;
1188 
1189 		if (((cur_pattern->flags & BUS_MATCH_PATH) != 0)
1190 		 && (cur_pattern->path_id != bus->path_id))
1191 			continue;
1192 
1193 		if (((cur_pattern->flags & BUS_MATCH_BUS_ID) != 0)
1194 		 && (cur_pattern->bus_id != bus->sim->bus_id))
1195 			continue;
1196 
1197 		if (((cur_pattern->flags & BUS_MATCH_UNIT) != 0)
1198 		 && (cur_pattern->unit_number != bus->sim->unit_number))
1199 			continue;
1200 
1201 		if (((cur_pattern->flags & BUS_MATCH_NAME) != 0)
1202 		 && (strncmp(cur_pattern->dev_name, bus->sim->sim_name,
1203 			     DEV_IDLEN) != 0))
1204 			continue;
1205 
1206 		/*
1207 		 * If we get to this point, the user definitely wants
1208 		 * information on this bus.  So tell the caller to copy the
1209 		 * data out.
1210 		 */
1211 		retval |= DM_RET_COPY;
1212 
1213 		/*
1214 		 * If the return action has been set to descend, then we
1215 		 * know that we've already seen a non-bus matching
1216 		 * expression, therefore we need to further descend the tree.
1217 		 * This won't change by continuing around the loop, so we
1218 		 * go ahead and return.  If we haven't seen a non-bus
1219 		 * matching expression, we keep going around the loop until
1220 		 * we exhaust the matching expressions.  We'll set the stop
1221 		 * flag once we fall out of the loop.
1222 		 */
1223 		if ((retval & DM_RET_ACTION_MASK) == DM_RET_DESCEND)
1224 			return(retval);
1225 	}
1226 
1227 	/*
1228 	 * If the return action hasn't been set to descend yet, that means
1229 	 * we haven't seen anything other than bus matching patterns.  So
1230 	 * tell the caller to stop descending the tree -- the user doesn't
1231 	 * want to match against lower level tree elements.
1232 	 */
1233 	if ((retval & DM_RET_ACTION_MASK) == DM_RET_NONE)
1234 		retval |= DM_RET_STOP;
1235 
1236 	return(retval);
1237 }
1238 
1239 static dev_match_ret
1240 xptdevicematch(struct dev_match_pattern *patterns, u_int num_patterns,
1241 	       struct cam_ed *device)
1242 {
1243 	dev_match_ret retval;
1244 	int i;
1245 
1246 	retval = DM_RET_NONE;
1247 
1248 	/*
1249 	 * If we aren't given something to match against, that's an error.
1250 	 */
1251 	if (device == NULL)
1252 		return(DM_RET_ERROR);
1253 
1254 	/*
1255 	 * If there are no match entries, then this device matches no
1256 	 * matter what.
1257 	 */
1258 	if ((patterns == NULL) || (num_patterns == 0))
1259 		return(DM_RET_DESCEND | DM_RET_COPY);
1260 
1261 	for (i = 0; i < num_patterns; i++) {
1262 		struct device_match_pattern *cur_pattern;
1263 		struct scsi_vpd_device_id *device_id_page;
1264 
1265 		/*
1266 		 * If the pattern in question isn't for a device node, we
1267 		 * aren't interested.
1268 		 */
1269 		if (patterns[i].type != DEV_MATCH_DEVICE) {
1270 			if ((patterns[i].type == DEV_MATCH_PERIPH)
1271 			 && ((retval & DM_RET_ACTION_MASK) == DM_RET_NONE))
1272 				retval |= DM_RET_DESCEND;
1273 			continue;
1274 		}
1275 
1276 		cur_pattern = &patterns[i].pattern.device_pattern;
1277 
1278 		/* Error out if mutually exclusive options are specified. */
1279 		if ((cur_pattern->flags & (DEV_MATCH_INQUIRY|DEV_MATCH_DEVID))
1280 		 == (DEV_MATCH_INQUIRY|DEV_MATCH_DEVID))
1281 			return(DM_RET_ERROR);
1282 
1283 		/*
1284 		 * If they want to match any device node, we give them any
1285 		 * device node.
1286 		 */
1287 		if (cur_pattern->flags == DEV_MATCH_ANY)
1288 			goto copy_dev_node;
1289 
1290 		/*
1291 		 * Not sure why someone would do this...
1292 		 */
1293 		if (cur_pattern->flags == DEV_MATCH_NONE)
1294 			continue;
1295 
1296 		if (((cur_pattern->flags & DEV_MATCH_PATH) != 0)
1297 		 && (cur_pattern->path_id != device->target->bus->path_id))
1298 			continue;
1299 
1300 		if (((cur_pattern->flags & DEV_MATCH_TARGET) != 0)
1301 		 && (cur_pattern->target_id != device->target->target_id))
1302 			continue;
1303 
1304 		if (((cur_pattern->flags & DEV_MATCH_LUN) != 0)
1305 		 && (cur_pattern->target_lun != device->lun_id))
1306 			continue;
1307 
1308 		if (((cur_pattern->flags & DEV_MATCH_INQUIRY) != 0)
1309 		 && (cam_quirkmatch((caddr_t)&device->inq_data,
1310 				    (caddr_t)&cur_pattern->data.inq_pat,
1311 				    1, sizeof(cur_pattern->data.inq_pat),
1312 				    scsi_static_inquiry_match) == NULL))
1313 			continue;
1314 
1315 		device_id_page = (struct scsi_vpd_device_id *)device->device_id;
1316 		if (((cur_pattern->flags & DEV_MATCH_DEVID) != 0)
1317 		 && (device->device_id_len < SVPD_DEVICE_ID_HDR_LEN
1318 		  || scsi_devid_match((uint8_t *)device_id_page->desc_list,
1319 				      device->device_id_len
1320 				    - SVPD_DEVICE_ID_HDR_LEN,
1321 				      cur_pattern->data.devid_pat.id,
1322 				      cur_pattern->data.devid_pat.id_len) != 0))
1323 			continue;
1324 
1325 copy_dev_node:
1326 		/*
1327 		 * If we get to this point, the user definitely wants
1328 		 * information on this device.  So tell the caller to copy
1329 		 * the data out.
1330 		 */
1331 		retval |= DM_RET_COPY;
1332 
1333 		/*
1334 		 * If the return action has been set to descend, then we
1335 		 * know that we've already seen a peripheral matching
1336 		 * expression, therefore we need to further descend the tree.
1337 		 * This won't change by continuing around the loop, so we
1338 		 * go ahead and return.  If we haven't seen a peripheral
1339 		 * matching expression, we keep going around the loop until
1340 		 * we exhaust the matching expressions.  We'll set the stop
1341 		 * flag once we fall out of the loop.
1342 		 */
1343 		if ((retval & DM_RET_ACTION_MASK) == DM_RET_DESCEND)
1344 			return(retval);
1345 	}
1346 
1347 	/*
1348 	 * If the return action hasn't been set to descend yet, that means
1349 	 * we haven't seen any peripheral matching patterns.  So tell the
1350 	 * caller to stop descending the tree -- the user doesn't want to
1351 	 * match against lower level tree elements.
1352 	 */
1353 	if ((retval & DM_RET_ACTION_MASK) == DM_RET_NONE)
1354 		retval |= DM_RET_STOP;
1355 
1356 	return(retval);
1357 }
1358 
1359 /*
1360  * Match a single peripheral against any number of match patterns.
1361  */
1362 static dev_match_ret
1363 xptperiphmatch(struct dev_match_pattern *patterns, u_int num_patterns,
1364 	       struct cam_periph *periph)
1365 {
1366 	dev_match_ret retval;
1367 	int i;
1368 
1369 	/*
1370 	 * If we aren't given something to match against, that's an error.
1371 	 */
1372 	if (periph == NULL)
1373 		return(DM_RET_ERROR);
1374 
1375 	/*
1376 	 * If there are no match entries, then this peripheral matches no
1377 	 * matter what.
1378 	 */
1379 	if ((patterns == NULL) || (num_patterns == 0))
1380 		return(DM_RET_STOP | DM_RET_COPY);
1381 
1382 	/*
1383 	 * There aren't any nodes below a peripheral node, so there's no
1384 	 * reason to descend the tree any further.
1385 	 */
1386 	retval = DM_RET_STOP;
1387 
1388 	for (i = 0; i < num_patterns; i++) {
1389 		struct periph_match_pattern *cur_pattern;
1390 
1391 		/*
1392 		 * If the pattern in question isn't for a peripheral, we
1393 		 * aren't interested.
1394 		 */
1395 		if (patterns[i].type != DEV_MATCH_PERIPH)
1396 			continue;
1397 
1398 		cur_pattern = &patterns[i].pattern.periph_pattern;
1399 
1400 		/*
1401 		 * If they want to match on anything, then we will do so.
1402 		 */
1403 		if (cur_pattern->flags == PERIPH_MATCH_ANY) {
1404 			/* set the copy flag */
1405 			retval |= DM_RET_COPY;
1406 
1407 			/*
1408 			 * We've already set the return action to stop,
1409 			 * since there are no nodes below peripherals in
1410 			 * the tree.
1411 			 */
1412 			return(retval);
1413 		}
1414 
1415 		/*
1416 		 * Not sure why someone would do this...
1417 		 */
1418 		if (cur_pattern->flags == PERIPH_MATCH_NONE)
1419 			continue;
1420 
1421 		if (((cur_pattern->flags & PERIPH_MATCH_PATH) != 0)
1422 		 && (cur_pattern->path_id != periph->path->bus->path_id))
1423 			continue;
1424 
1425 		/*
1426 		 * For the target and lun id's, we have to make sure the
1427 		 * target and lun pointers aren't NULL.  The xpt peripheral
1428 		 * has a wildcard target and device.
1429 		 */
1430 		if (((cur_pattern->flags & PERIPH_MATCH_TARGET) != 0)
1431 		 && ((periph->path->target == NULL)
1432 		 ||(cur_pattern->target_id != periph->path->target->target_id)))
1433 			continue;
1434 
1435 		if (((cur_pattern->flags & PERIPH_MATCH_LUN) != 0)
1436 		 && ((periph->path->device == NULL)
1437 		 || (cur_pattern->target_lun != periph->path->device->lun_id)))
1438 			continue;
1439 
1440 		if (((cur_pattern->flags & PERIPH_MATCH_UNIT) != 0)
1441 		 && (cur_pattern->unit_number != periph->unit_number))
1442 			continue;
1443 
1444 		if (((cur_pattern->flags & PERIPH_MATCH_NAME) != 0)
1445 		 && (strncmp(cur_pattern->periph_name, periph->periph_name,
1446 			     DEV_IDLEN) != 0))
1447 			continue;
1448 
1449 		/*
1450 		 * If we get to this point, the user definitely wants
1451 		 * information on this peripheral.  So tell the caller to
1452 		 * copy the data out.
1453 		 */
1454 		retval |= DM_RET_COPY;
1455 
1456 		/*
1457 		 * The return action has already been set to stop, since
1458 		 * peripherals don't have any nodes below them in the EDT.
1459 		 */
1460 		return(retval);
1461 	}
1462 
1463 	/*
1464 	 * If we get to this point, the peripheral that was passed in
1465 	 * doesn't match any of the patterns.
1466 	 */
1467 	return(retval);
1468 }
1469 
1470 static int
1471 xptedtbusfunc(struct cam_eb *bus, void *arg)
1472 {
1473 	struct ccb_dev_match *cdm;
1474 	dev_match_ret retval;
1475 
1476 	cdm = (struct ccb_dev_match *)arg;
1477 
1478 	/*
1479 	 * If our position is for something deeper in the tree, that means
1480 	 * that we've already seen this node.  So, we keep going down.
1481 	 */
1482 	if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
1483 	 && (cdm->pos.cookie.bus == bus)
1484 	 && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
1485 	 && (cdm->pos.cookie.target != NULL))
1486 		retval = DM_RET_DESCEND;
1487 	else
1488 		retval = xptbusmatch(cdm->patterns, cdm->num_patterns, bus);
1489 
1490 	/*
1491 	 * If we got an error, bail out of the search.
1492 	 */
1493 	if ((retval & DM_RET_ACTION_MASK) == DM_RET_ERROR) {
1494 		cdm->status = CAM_DEV_MATCH_ERROR;
1495 		return(0);
1496 	}
1497 
1498 	/*
1499 	 * If the copy flag is set, copy this bus out.
1500 	 */
1501 	if (retval & DM_RET_COPY) {
1502 		int spaceleft, j;
1503 
1504 		spaceleft = cdm->match_buf_len - (cdm->num_matches *
1505 			sizeof(struct dev_match_result));
1506 
1507 		/*
1508 		 * If we don't have enough space to put in another
1509 		 * match result, save our position and tell the
1510 		 * user there are more devices to check.
1511 		 */
1512 		if (spaceleft < sizeof(struct dev_match_result)) {
1513 			bzero(&cdm->pos, sizeof(cdm->pos));
1514 			cdm->pos.position_type =
1515 				CAM_DEV_POS_EDT | CAM_DEV_POS_BUS;
1516 
1517 			cdm->pos.cookie.bus = bus;
1518 			cdm->pos.generations[CAM_BUS_GENERATION]=
1519 				xsoftc.bus_generation;
1520 			cdm->status = CAM_DEV_MATCH_MORE;
1521 			return(0);
1522 		}
1523 		j = cdm->num_matches;
1524 		cdm->num_matches++;
1525 		cdm->matches[j].type = DEV_MATCH_BUS;
1526 		cdm->matches[j].result.bus_result.path_id = bus->path_id;
1527 		cdm->matches[j].result.bus_result.bus_id = bus->sim->bus_id;
1528 		cdm->matches[j].result.bus_result.unit_number =
1529 			bus->sim->unit_number;
1530 		strncpy(cdm->matches[j].result.bus_result.dev_name,
1531 			bus->sim->sim_name, DEV_IDLEN);
1532 	}
1533 
1534 	/*
1535 	 * If the user is only interested in busses, there's no
1536 	 * reason to descend to the next level in the tree.
1537 	 */
1538 	if ((retval & DM_RET_ACTION_MASK) == DM_RET_STOP)
1539 		return(1);
1540 
1541 	/*
1542 	 * If there is a target generation recorded, check it to
1543 	 * make sure the target list hasn't changed.
1544 	 */
1545 	if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
1546 	 && (bus == cdm->pos.cookie.bus)
1547 	 && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
1548 	 && (cdm->pos.generations[CAM_TARGET_GENERATION] != 0)
1549 	 && (cdm->pos.generations[CAM_TARGET_GENERATION] !=
1550 	     bus->generation)) {
1551 		cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
1552 		return(0);
1553 	}
1554 
1555 	if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
1556 	 && (cdm->pos.cookie.bus == bus)
1557 	 && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
1558 	 && (cdm->pos.cookie.target != NULL))
1559 		return(xpttargettraverse(bus,
1560 					(struct cam_et *)cdm->pos.cookie.target,
1561 					 xptedttargetfunc, arg));
1562 	else
1563 		return(xpttargettraverse(bus, NULL, xptedttargetfunc, arg));
1564 }
1565 
1566 static int
1567 xptedttargetfunc(struct cam_et *target, void *arg)
1568 {
1569 	struct ccb_dev_match *cdm;
1570 
1571 	cdm = (struct ccb_dev_match *)arg;
1572 
1573 	/*
1574 	 * If there is a device list generation recorded, check it to
1575 	 * make sure the device list hasn't changed.
1576 	 */
1577 	if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
1578 	 && (cdm->pos.cookie.bus == target->bus)
1579 	 && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
1580 	 && (cdm->pos.cookie.target == target)
1581 	 && (cdm->pos.position_type & CAM_DEV_POS_DEVICE)
1582 	 && (cdm->pos.generations[CAM_DEV_GENERATION] != 0)
1583 	 && (cdm->pos.generations[CAM_DEV_GENERATION] !=
1584 	     target->generation)) {
1585 		cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
1586 		return(0);
1587 	}
1588 
1589 	if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
1590 	 && (cdm->pos.cookie.bus == target->bus)
1591 	 && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
1592 	 && (cdm->pos.cookie.target == target)
1593 	 && (cdm->pos.position_type & CAM_DEV_POS_DEVICE)
1594 	 && (cdm->pos.cookie.device != NULL))
1595 		return(xptdevicetraverse(target,
1596 					(struct cam_ed *)cdm->pos.cookie.device,
1597 					 xptedtdevicefunc, arg));
1598 	else
1599 		return(xptdevicetraverse(target, NULL, xptedtdevicefunc, arg));
1600 }
1601 
1602 static int
1603 xptedtdevicefunc(struct cam_ed *device, void *arg)
1604 {
1605 
1606 	struct ccb_dev_match *cdm;
1607 	dev_match_ret retval;
1608 
1609 	cdm = (struct ccb_dev_match *)arg;
1610 
1611 	/*
1612 	 * If our position is for something deeper in the tree, that means
1613 	 * that we've already seen this node.  So, we keep going down.
1614 	 */
1615 	if ((cdm->pos.position_type & CAM_DEV_POS_DEVICE)
1616 	 && (cdm->pos.cookie.device == device)
1617 	 && (cdm->pos.position_type & CAM_DEV_POS_PERIPH)
1618 	 && (cdm->pos.cookie.periph != NULL))
1619 		retval = DM_RET_DESCEND;
1620 	else
1621 		retval = xptdevicematch(cdm->patterns, cdm->num_patterns,
1622 					device);
1623 
1624 	if ((retval & DM_RET_ACTION_MASK) == DM_RET_ERROR) {
1625 		cdm->status = CAM_DEV_MATCH_ERROR;
1626 		return(0);
1627 	}
1628 
1629 	/*
1630 	 * If the copy flag is set, copy this device out.
1631 	 */
1632 	if (retval & DM_RET_COPY) {
1633 		int spaceleft, j;
1634 
1635 		spaceleft = cdm->match_buf_len - (cdm->num_matches *
1636 			sizeof(struct dev_match_result));
1637 
1638 		/*
1639 		 * If we don't have enough space to put in another
1640 		 * match result, save our position and tell the
1641 		 * user there are more devices to check.
1642 		 */
1643 		if (spaceleft < sizeof(struct dev_match_result)) {
1644 			bzero(&cdm->pos, sizeof(cdm->pos));
1645 			cdm->pos.position_type =
1646 				CAM_DEV_POS_EDT | CAM_DEV_POS_BUS |
1647 				CAM_DEV_POS_TARGET | CAM_DEV_POS_DEVICE;
1648 
1649 			cdm->pos.cookie.bus = device->target->bus;
1650 			cdm->pos.generations[CAM_BUS_GENERATION]=
1651 				xsoftc.bus_generation;
1652 			cdm->pos.cookie.target = device->target;
1653 			cdm->pos.generations[CAM_TARGET_GENERATION] =
1654 				device->target->bus->generation;
1655 			cdm->pos.cookie.device = device;
1656 			cdm->pos.generations[CAM_DEV_GENERATION] =
1657 				device->target->generation;
1658 			cdm->status = CAM_DEV_MATCH_MORE;
1659 			return(0);
1660 		}
1661 		j = cdm->num_matches;
1662 		cdm->num_matches++;
1663 		cdm->matches[j].type = DEV_MATCH_DEVICE;
1664 		cdm->matches[j].result.device_result.path_id =
1665 			device->target->bus->path_id;
1666 		cdm->matches[j].result.device_result.target_id =
1667 			device->target->target_id;
1668 		cdm->matches[j].result.device_result.target_lun =
1669 			device->lun_id;
1670 		cdm->matches[j].result.device_result.protocol =
1671 			device->protocol;
1672 		bcopy(&device->inq_data,
1673 		      &cdm->matches[j].result.device_result.inq_data,
1674 		      sizeof(struct scsi_inquiry_data));
1675 		bcopy(&device->ident_data,
1676 		      &cdm->matches[j].result.device_result.ident_data,
1677 		      sizeof(struct ata_params));
1678 
1679 		/* Let the user know whether this device is unconfigured */
1680 		if (device->flags & CAM_DEV_UNCONFIGURED)
1681 			cdm->matches[j].result.device_result.flags =
1682 				DEV_RESULT_UNCONFIGURED;
1683 		else
1684 			cdm->matches[j].result.device_result.flags =
1685 				DEV_RESULT_NOFLAG;
1686 	}
1687 
1688 	/*
1689 	 * If the user isn't interested in peripherals, don't descend
1690 	 * the tree any further.
1691 	 */
1692 	if ((retval & DM_RET_ACTION_MASK) == DM_RET_STOP)
1693 		return(1);
1694 
1695 	/*
1696 	 * If there is a peripheral list generation recorded, make sure
1697 	 * it hasn't changed.
1698 	 */
1699 	if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
1700 	 && (device->target->bus == cdm->pos.cookie.bus)
1701 	 && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
1702 	 && (device->target == cdm->pos.cookie.target)
1703 	 && (cdm->pos.position_type & CAM_DEV_POS_DEVICE)
1704 	 && (device == cdm->pos.cookie.device)
1705 	 && (cdm->pos.position_type & CAM_DEV_POS_PERIPH)
1706 	 && (cdm->pos.generations[CAM_PERIPH_GENERATION] != 0)
1707 	 && (cdm->pos.generations[CAM_PERIPH_GENERATION] !=
1708 	     device->generation)){
1709 		cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
1710 		return(0);
1711 	}
1712 
1713 	if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
1714 	 && (cdm->pos.cookie.bus == device->target->bus)
1715 	 && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
1716 	 && (cdm->pos.cookie.target == device->target)
1717 	 && (cdm->pos.position_type & CAM_DEV_POS_DEVICE)
1718 	 && (cdm->pos.cookie.device == device)
1719 	 && (cdm->pos.position_type & CAM_DEV_POS_PERIPH)
1720 	 && (cdm->pos.cookie.periph != NULL))
1721 		return(xptperiphtraverse(device,
1722 				(struct cam_periph *)cdm->pos.cookie.periph,
1723 				xptedtperiphfunc, arg));
1724 	else
1725 		return(xptperiphtraverse(device, NULL, xptedtperiphfunc, arg));
1726 }
1727 
1728 static int
1729 xptedtperiphfunc(struct cam_periph *periph, void *arg)
1730 {
1731 	struct ccb_dev_match *cdm;
1732 	dev_match_ret retval;
1733 
1734 	cdm = (struct ccb_dev_match *)arg;
1735 
1736 	retval = xptperiphmatch(cdm->patterns, cdm->num_patterns, periph);
1737 
1738 	if ((retval & DM_RET_ACTION_MASK) == DM_RET_ERROR) {
1739 		cdm->status = CAM_DEV_MATCH_ERROR;
1740 		return(0);
1741 	}
1742 
1743 	/*
1744 	 * If the copy flag is set, copy this peripheral out.
1745 	 */
1746 	if (retval & DM_RET_COPY) {
1747 		int spaceleft, j;
1748 
1749 		spaceleft = cdm->match_buf_len - (cdm->num_matches *
1750 			sizeof(struct dev_match_result));
1751 
1752 		/*
1753 		 * If we don't have enough space to put in another
1754 		 * match result, save our position and tell the
1755 		 * user there are more devices to check.
1756 		 */
1757 		if (spaceleft < sizeof(struct dev_match_result)) {
1758 			bzero(&cdm->pos, sizeof(cdm->pos));
1759 			cdm->pos.position_type =
1760 				CAM_DEV_POS_EDT | CAM_DEV_POS_BUS |
1761 				CAM_DEV_POS_TARGET | CAM_DEV_POS_DEVICE |
1762 				CAM_DEV_POS_PERIPH;
1763 
1764 			cdm->pos.cookie.bus = periph->path->bus;
1765 			cdm->pos.generations[CAM_BUS_GENERATION]=
1766 				xsoftc.bus_generation;
1767 			cdm->pos.cookie.target = periph->path->target;
1768 			cdm->pos.generations[CAM_TARGET_GENERATION] =
1769 				periph->path->bus->generation;
1770 			cdm->pos.cookie.device = periph->path->device;
1771 			cdm->pos.generations[CAM_DEV_GENERATION] =
1772 				periph->path->target->generation;
1773 			cdm->pos.cookie.periph = periph;
1774 			cdm->pos.generations[CAM_PERIPH_GENERATION] =
1775 				periph->path->device->generation;
1776 			cdm->status = CAM_DEV_MATCH_MORE;
1777 			return(0);
1778 		}
1779 
1780 		j = cdm->num_matches;
1781 		cdm->num_matches++;
1782 		cdm->matches[j].type = DEV_MATCH_PERIPH;
1783 		cdm->matches[j].result.periph_result.path_id =
1784 			periph->path->bus->path_id;
1785 		cdm->matches[j].result.periph_result.target_id =
1786 			periph->path->target->target_id;
1787 		cdm->matches[j].result.periph_result.target_lun =
1788 			periph->path->device->lun_id;
1789 		cdm->matches[j].result.periph_result.unit_number =
1790 			periph->unit_number;
1791 		strncpy(cdm->matches[j].result.periph_result.periph_name,
1792 			periph->periph_name, DEV_IDLEN);
1793 	}
1794 
1795 	return(1);
1796 }
1797 
1798 static int
1799 xptedtmatch(struct ccb_dev_match *cdm)
1800 {
1801 	int ret;
1802 
1803 	cdm->num_matches = 0;
1804 
1805 	/*
1806 	 * Check the bus list generation.  If it has changed, the user
1807 	 * needs to reset everything and start over.
1808 	 */
1809 	if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
1810 	 && (cdm->pos.generations[CAM_BUS_GENERATION] != 0)
1811 	 && (cdm->pos.generations[CAM_BUS_GENERATION] != xsoftc.bus_generation)) {
1812 		cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
1813 		return(0);
1814 	}
1815 
1816 	if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
1817 	 && (cdm->pos.cookie.bus != NULL))
1818 		ret = xptbustraverse((struct cam_eb *)cdm->pos.cookie.bus,
1819 				     xptedtbusfunc, cdm);
1820 	else
1821 		ret = xptbustraverse(NULL, xptedtbusfunc, cdm);
1822 
1823 	/*
1824 	 * If we get back 0, that means that we had to stop before fully
1825 	 * traversing the EDT.  It also means that one of the subroutines
1826 	 * has set the status field to the proper value.  If we get back 1,
1827 	 * we've fully traversed the EDT and copied out any matching entries.
1828 	 */
1829 	if (ret == 1)
1830 		cdm->status = CAM_DEV_MATCH_LAST;
1831 
1832 	return(ret);
1833 }
1834 
1835 static int
1836 xptplistpdrvfunc(struct periph_driver **pdrv, void *arg)
1837 {
1838 	struct ccb_dev_match *cdm;
1839 
1840 	cdm = (struct ccb_dev_match *)arg;
1841 
1842 	if ((cdm->pos.position_type & CAM_DEV_POS_PDPTR)
1843 	 && (cdm->pos.cookie.pdrv == pdrv)
1844 	 && (cdm->pos.position_type & CAM_DEV_POS_PERIPH)
1845 	 && (cdm->pos.generations[CAM_PERIPH_GENERATION] != 0)
1846 	 && (cdm->pos.generations[CAM_PERIPH_GENERATION] !=
1847 	     (*pdrv)->generation)) {
1848 		cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
1849 		return(0);
1850 	}
1851 
1852 	if ((cdm->pos.position_type & CAM_DEV_POS_PDPTR)
1853 	 && (cdm->pos.cookie.pdrv == pdrv)
1854 	 && (cdm->pos.position_type & CAM_DEV_POS_PERIPH)
1855 	 && (cdm->pos.cookie.periph != NULL))
1856 		return(xptpdperiphtraverse(pdrv,
1857 				(struct cam_periph *)cdm->pos.cookie.periph,
1858 				xptplistperiphfunc, arg));
1859 	else
1860 		return(xptpdperiphtraverse(pdrv, NULL,xptplistperiphfunc, arg));
1861 }
1862 
1863 static int
1864 xptplistperiphfunc(struct cam_periph *periph, void *arg)
1865 {
1866 	struct ccb_dev_match *cdm;
1867 	dev_match_ret retval;
1868 
1869 	cdm = (struct ccb_dev_match *)arg;
1870 
1871 	retval = xptperiphmatch(cdm->patterns, cdm->num_patterns, periph);
1872 
1873 	if ((retval & DM_RET_ACTION_MASK) == DM_RET_ERROR) {
1874 		cdm->status = CAM_DEV_MATCH_ERROR;
1875 		return(0);
1876 	}
1877 
1878 	/*
1879 	 * If the copy flag is set, copy this peripheral out.
1880 	 */
1881 	if (retval & DM_RET_COPY) {
1882 		int spaceleft, j;
1883 
1884 		spaceleft = cdm->match_buf_len - (cdm->num_matches *
1885 			sizeof(struct dev_match_result));
1886 
1887 		/*
1888 		 * If we don't have enough space to put in another
1889 		 * match result, save our position and tell the
1890 		 * user there are more devices to check.
1891 		 */
1892 		if (spaceleft < sizeof(struct dev_match_result)) {
1893 			struct periph_driver **pdrv;
1894 
1895 			pdrv = NULL;
1896 			bzero(&cdm->pos, sizeof(cdm->pos));
1897 			cdm->pos.position_type =
1898 				CAM_DEV_POS_PDRV | CAM_DEV_POS_PDPTR |
1899 				CAM_DEV_POS_PERIPH;
1900 
1901 			/*
1902 			 * This may look a bit non-sensical, but it is
1903 			 * actually quite logical.  There are very few
1904 			 * peripheral drivers, and bloating every peripheral
1905 			 * structure with a pointer back to its parent
1906 			 * peripheral driver linker set entry would cost
1907 			 * more in the long run than doing this quick lookup.
1908 			 */
1909 			for (pdrv = periph_drivers; *pdrv != NULL; pdrv++) {
1910 				if (strcmp((*pdrv)->driver_name,
1911 				    periph->periph_name) == 0)
1912 					break;
1913 			}
1914 
1915 			if (*pdrv == NULL) {
1916 				cdm->status = CAM_DEV_MATCH_ERROR;
1917 				return(0);
1918 			}
1919 
1920 			cdm->pos.cookie.pdrv = pdrv;
1921 			/*
1922 			 * The periph generation slot does double duty, as
1923 			 * does the periph pointer slot.  They are used for
1924 			 * both edt and pdrv lookups and positioning.
1925 			 */
1926 			cdm->pos.cookie.periph = periph;
1927 			cdm->pos.generations[CAM_PERIPH_GENERATION] =
1928 				(*pdrv)->generation;
1929 			cdm->status = CAM_DEV_MATCH_MORE;
1930 			return(0);
1931 		}
1932 
1933 		j = cdm->num_matches;
1934 		cdm->num_matches++;
1935 		cdm->matches[j].type = DEV_MATCH_PERIPH;
1936 		cdm->matches[j].result.periph_result.path_id =
1937 			periph->path->bus->path_id;
1938 
1939 		/*
1940 		 * The transport layer peripheral doesn't have a target or
1941 		 * lun.
1942 		 */
1943 		if (periph->path->target)
1944 			cdm->matches[j].result.periph_result.target_id =
1945 				periph->path->target->target_id;
1946 		else
1947 			cdm->matches[j].result.periph_result.target_id = -1;
1948 
1949 		if (periph->path->device)
1950 			cdm->matches[j].result.periph_result.target_lun =
1951 				periph->path->device->lun_id;
1952 		else
1953 			cdm->matches[j].result.periph_result.target_lun = -1;
1954 
1955 		cdm->matches[j].result.periph_result.unit_number =
1956 			periph->unit_number;
1957 		strncpy(cdm->matches[j].result.periph_result.periph_name,
1958 			periph->periph_name, DEV_IDLEN);
1959 	}
1960 
1961 	return(1);
1962 }
1963 
1964 static int
1965 xptperiphlistmatch(struct ccb_dev_match *cdm)
1966 {
1967 	int ret;
1968 
1969 	cdm->num_matches = 0;
1970 
1971 	/*
1972 	 * At this point in the edt traversal function, we check the bus
1973 	 * list generation to make sure that no busses have been added or
1974 	 * removed since the user last sent a XPT_DEV_MATCH ccb through.
1975 	 * For the peripheral driver list traversal function, however, we
1976 	 * don't have to worry about new peripheral driver types coming or
1977 	 * going; they're in a linker set, and therefore can't change
1978 	 * without a recompile.
1979 	 */
1980 
1981 	if ((cdm->pos.position_type & CAM_DEV_POS_PDPTR)
1982 	 && (cdm->pos.cookie.pdrv != NULL))
1983 		ret = xptpdrvtraverse(
1984 				(struct periph_driver **)cdm->pos.cookie.pdrv,
1985 				xptplistpdrvfunc, cdm);
1986 	else
1987 		ret = xptpdrvtraverse(NULL, xptplistpdrvfunc, cdm);
1988 
1989 	/*
1990 	 * If we get back 0, that means that we had to stop before fully
1991 	 * traversing the peripheral driver tree.  It also means that one of
1992 	 * the subroutines has set the status field to the proper value.  If
1993 	 * we get back 1, we've fully traversed the EDT and copied out any
1994 	 * matching entries.
1995 	 */
1996 	if (ret == 1)
1997 		cdm->status = CAM_DEV_MATCH_LAST;
1998 
1999 	return(ret);
2000 }
2001 
2002 static int
2003 xptbustraverse(struct cam_eb *start_bus, xpt_busfunc_t *tr_func, void *arg)
2004 {
2005 	struct cam_eb *bus, *next_bus;
2006 	int retval;
2007 
2008 	retval = 1;
2009 
2010 	xpt_lock_buses();
2011 	for (bus = (start_bus ? start_bus : TAILQ_FIRST(&xsoftc.xpt_busses));
2012 	     bus != NULL;
2013 	     bus = next_bus) {
2014 
2015 		bus->refcount++;
2016 
2017 		/*
2018 		 * XXX The locking here is obviously very complex.  We
2019 		 * should work to simplify it.
2020 		 */
2021 		xpt_unlock_buses();
2022 		CAM_SIM_LOCK(bus->sim);
2023 		retval = tr_func(bus, arg);
2024 		CAM_SIM_UNLOCK(bus->sim);
2025 
2026 		xpt_lock_buses();
2027 		next_bus = TAILQ_NEXT(bus, links);
2028 		xpt_unlock_buses();
2029 
2030 		xpt_release_bus(bus);
2031 
2032 		if (retval == 0)
2033 			return(retval);
2034 		xpt_lock_buses();
2035 	}
2036 	xpt_unlock_buses();
2037 
2038 	return(retval);
2039 }
2040 
2041 static int
2042 xpttargettraverse(struct cam_eb *bus, struct cam_et *start_target,
2043 		  xpt_targetfunc_t *tr_func, void *arg)
2044 {
2045 	struct cam_et *target, *next_target;
2046 	int retval;
2047 
2048 	mtx_assert(bus->sim->mtx, MA_OWNED);
2049 	retval = 1;
2050 	for (target = (start_target ? start_target :
2051 		       TAILQ_FIRST(&bus->et_entries));
2052 	     target != NULL; target = next_target) {
2053 
2054 		target->refcount++;
2055 
2056 		retval = tr_func(target, arg);
2057 
2058 		next_target = TAILQ_NEXT(target, links);
2059 
2060 		xpt_release_target(target);
2061 
2062 		if (retval == 0)
2063 			return(retval);
2064 	}
2065 
2066 	return(retval);
2067 }
2068 
2069 static int
2070 xptdevicetraverse(struct cam_et *target, struct cam_ed *start_device,
2071 		  xpt_devicefunc_t *tr_func, void *arg)
2072 {
2073 	struct cam_ed *device, *next_device;
2074 	int retval;
2075 
2076 	mtx_assert(target->bus->sim->mtx, MA_OWNED);
2077 	retval = 1;
2078 	for (device = (start_device ? start_device :
2079 		       TAILQ_FIRST(&target->ed_entries));
2080 	     device != NULL;
2081 	     device = next_device) {
2082 
2083 		/*
2084 		 * Hold a reference so the current device does not go away
2085 		 * on us.
2086 		 */
2087 		device->refcount++;
2088 
2089 		retval = tr_func(device, arg);
2090 
2091 		/*
2092 		 * Grab our next pointer before we release the current
2093 		 * device.
2094 		 */
2095 		next_device = TAILQ_NEXT(device, links);
2096 
2097 		xpt_release_device(device);
2098 
2099 		if (retval == 0)
2100 			return(retval);
2101 	}
2102 
2103 	return(retval);
2104 }
2105 
2106 static int
2107 xptperiphtraverse(struct cam_ed *device, struct cam_periph *start_periph,
2108 		  xpt_periphfunc_t *tr_func, void *arg)
2109 {
2110 	struct cam_periph *periph, *next_periph;
2111 	int retval;
2112 
2113 	retval = 1;
2114 
2115 	mtx_assert(device->sim->mtx, MA_OWNED);
2116 	xpt_lock_buses();
2117 	for (periph = (start_periph ? start_periph :
2118 		       SLIST_FIRST(&device->periphs));
2119 	     periph != NULL;
2120 	     periph = next_periph) {
2121 
2122 
2123 		/*
2124 		 * In this case, we want to show peripherals that have been
2125 		 * invalidated, but not peripherals that are scheduled to
2126 		 * be freed.  So instead of calling cam_periph_acquire(),
2127 		 * which will fail if the periph has been invalidated, we
2128 		 * just check for the free flag here.  If it is in the
2129 		 * process of being freed, we skip to the next periph.
2130 		 */
2131 		if (periph->flags & CAM_PERIPH_FREE) {
2132 			next_periph = SLIST_NEXT(periph, periph_links);
2133 			continue;
2134 		}
2135 
2136 		/*
2137 		 * Acquire a reference to this periph while we call the
2138 		 * traversal function, so it can't go away.
2139 		 */
2140 		periph->refcount++;
2141 
2142 		retval = tr_func(periph, arg);
2143 
2144 		/*
2145 		 * Grab the next peripheral before we release this one, so
2146 		 * our next pointer is still valid.
2147 		 */
2148 		next_periph = SLIST_NEXT(periph, periph_links);
2149 
2150 		cam_periph_release_locked_buses(periph);
2151 
2152 		if (retval == 0)
2153 			goto bailout_done;
2154 	}
2155 
2156 bailout_done:
2157 
2158 	xpt_unlock_buses();
2159 
2160 	return(retval);
2161 }
2162 
2163 static int
2164 xptpdrvtraverse(struct periph_driver **start_pdrv,
2165 		xpt_pdrvfunc_t *tr_func, void *arg)
2166 {
2167 	struct periph_driver **pdrv;
2168 	int retval;
2169 
2170 	retval = 1;
2171 
2172 	/*
2173 	 * We don't traverse the peripheral driver list like we do the
2174 	 * other lists, because it is a linker set, and therefore cannot be
2175 	 * changed during runtime.  If the peripheral driver list is ever
2176 	 * re-done to be something other than a linker set (i.e. it can
2177 	 * change while the system is running), the list traversal should
2178 	 * be modified to work like the other traversal functions.
2179 	 */
2180 	for (pdrv = (start_pdrv ? start_pdrv : periph_drivers);
2181 	     *pdrv != NULL; pdrv++) {
2182 		retval = tr_func(pdrv, arg);
2183 
2184 		if (retval == 0)
2185 			return(retval);
2186 	}
2187 
2188 	return(retval);
2189 }
2190 
2191 static int
2192 xptpdperiphtraverse(struct periph_driver **pdrv,
2193 		    struct cam_periph *start_periph,
2194 		    xpt_periphfunc_t *tr_func, void *arg)
2195 {
2196 	struct cam_periph *periph, *next_periph;
2197 	struct cam_sim *sim;
2198 	int retval;
2199 
2200 	retval = 1;
2201 
2202 	xpt_lock_buses();
2203 	for (periph = (start_periph ? start_periph :
2204 	     TAILQ_FIRST(&(*pdrv)->units)); periph != NULL;
2205 	     periph = next_periph) {
2206 
2207 
2208 		/*
2209 		 * In this case, we want to show peripherals that have been
2210 		 * invalidated, but not peripherals that are scheduled to
2211 		 * be freed.  So instead of calling cam_periph_acquire(),
2212 		 * which will fail if the periph has been invalidated, we
2213 		 * just check for the free flag here.  If it is free, we
2214 		 * skip to the next periph.
2215 		 */
2216 		if (periph->flags & CAM_PERIPH_FREE) {
2217 			next_periph = TAILQ_NEXT(periph, unit_links);
2218 			continue;
2219 		}
2220 
2221 		/*
2222 		 * Acquire a reference to this periph while we call the
2223 		 * traversal function, so it can't go away.
2224 		 */
2225 		periph->refcount++;
2226 		sim = periph->sim;
2227 		xpt_unlock_buses();
2228 		CAM_SIM_LOCK(sim);
2229 		xpt_lock_buses();
2230 		retval = tr_func(periph, arg);
2231 
2232 		/*
2233 		 * Grab the next peripheral before we release this one, so
2234 		 * our next pointer is still valid.
2235 		 */
2236 		next_periph = TAILQ_NEXT(periph, unit_links);
2237 
2238 		cam_periph_release_locked_buses(periph);
2239 		CAM_SIM_UNLOCK(sim);
2240 
2241 		if (retval == 0)
2242 			goto bailout_done;
2243 	}
2244 bailout_done:
2245 
2246 	xpt_unlock_buses();
2247 
2248 	return(retval);
2249 }
2250 
2251 static int
2252 xptdefbusfunc(struct cam_eb *bus, void *arg)
2253 {
2254 	struct xpt_traverse_config *tr_config;
2255 
2256 	tr_config = (struct xpt_traverse_config *)arg;
2257 
2258 	if (tr_config->depth == XPT_DEPTH_BUS) {
2259 		xpt_busfunc_t *tr_func;
2260 
2261 		tr_func = (xpt_busfunc_t *)tr_config->tr_func;
2262 
2263 		return(tr_func(bus, tr_config->tr_arg));
2264 	} else
2265 		return(xpttargettraverse(bus, NULL, xptdeftargetfunc, arg));
2266 }
2267 
2268 static int
2269 xptdeftargetfunc(struct cam_et *target, void *arg)
2270 {
2271 	struct xpt_traverse_config *tr_config;
2272 
2273 	tr_config = (struct xpt_traverse_config *)arg;
2274 
2275 	if (tr_config->depth == XPT_DEPTH_TARGET) {
2276 		xpt_targetfunc_t *tr_func;
2277 
2278 		tr_func = (xpt_targetfunc_t *)tr_config->tr_func;
2279 
2280 		return(tr_func(target, tr_config->tr_arg));
2281 	} else
2282 		return(xptdevicetraverse(target, NULL, xptdefdevicefunc, arg));
2283 }
2284 
2285 static int
2286 xptdefdevicefunc(struct cam_ed *device, void *arg)
2287 {
2288 	struct xpt_traverse_config *tr_config;
2289 
2290 	tr_config = (struct xpt_traverse_config *)arg;
2291 
2292 	if (tr_config->depth == XPT_DEPTH_DEVICE) {
2293 		xpt_devicefunc_t *tr_func;
2294 
2295 		tr_func = (xpt_devicefunc_t *)tr_config->tr_func;
2296 
2297 		return(tr_func(device, tr_config->tr_arg));
2298 	} else
2299 		return(xptperiphtraverse(device, NULL, xptdefperiphfunc, arg));
2300 }
2301 
2302 static int
2303 xptdefperiphfunc(struct cam_periph *periph, void *arg)
2304 {
2305 	struct xpt_traverse_config *tr_config;
2306 	xpt_periphfunc_t *tr_func;
2307 
2308 	tr_config = (struct xpt_traverse_config *)arg;
2309 
2310 	tr_func = (xpt_periphfunc_t *)tr_config->tr_func;
2311 
2312 	/*
2313 	 * Unlike the other default functions, we don't check for depth
2314 	 * here.  The peripheral driver level is the last level in the EDT,
2315 	 * so if we're here, we should execute the function in question.
2316 	 */
2317 	return(tr_func(periph, tr_config->tr_arg));
2318 }
2319 
2320 /*
2321  * Execute the given function for every bus in the EDT.
2322  */
2323 static int
2324 xpt_for_all_busses(xpt_busfunc_t *tr_func, void *arg)
2325 {
2326 	struct xpt_traverse_config tr_config;
2327 
2328 	tr_config.depth = XPT_DEPTH_BUS;
2329 	tr_config.tr_func = tr_func;
2330 	tr_config.tr_arg = arg;
2331 
2332 	return(xptbustraverse(NULL, xptdefbusfunc, &tr_config));
2333 }
2334 
2335 /*
2336  * Execute the given function for every device in the EDT.
2337  */
2338 static int
2339 xpt_for_all_devices(xpt_devicefunc_t *tr_func, void *arg)
2340 {
2341 	struct xpt_traverse_config tr_config;
2342 
2343 	tr_config.depth = XPT_DEPTH_DEVICE;
2344 	tr_config.tr_func = tr_func;
2345 	tr_config.tr_arg = arg;
2346 
2347 	return(xptbustraverse(NULL, xptdefbusfunc, &tr_config));
2348 }
2349 
2350 static int
2351 xptsetasyncfunc(struct cam_ed *device, void *arg)
2352 {
2353 	struct cam_path path;
2354 	struct ccb_getdev cgd;
2355 	struct ccb_setasync *csa = (struct ccb_setasync *)arg;
2356 
2357 	/*
2358 	 * Don't report unconfigured devices (Wildcard devs,
2359 	 * devices only for target mode, device instances
2360 	 * that have been invalidated but are waiting for
2361 	 * their last reference count to be released).
2362 	 */
2363 	if ((device->flags & CAM_DEV_UNCONFIGURED) != 0)
2364 		return (1);
2365 
2366 	xpt_compile_path(&path,
2367 			 NULL,
2368 			 device->target->bus->path_id,
2369 			 device->target->target_id,
2370 			 device->lun_id);
2371 	xpt_setup_ccb(&cgd.ccb_h, &path, CAM_PRIORITY_NORMAL);
2372 	cgd.ccb_h.func_code = XPT_GDEV_TYPE;
2373 	xpt_action((union ccb *)&cgd);
2374 	csa->callback(csa->callback_arg,
2375 			    AC_FOUND_DEVICE,
2376 			    &path, &cgd);
2377 	xpt_release_path(&path);
2378 
2379 	return(1);
2380 }
2381 
2382 static int
2383 xptsetasyncbusfunc(struct cam_eb *bus, void *arg)
2384 {
2385 	struct cam_path path;
2386 	struct ccb_pathinq cpi;
2387 	struct ccb_setasync *csa = (struct ccb_setasync *)arg;
2388 
2389 	xpt_compile_path(&path, /*periph*/NULL,
2390 			 bus->sim->path_id,
2391 			 CAM_TARGET_WILDCARD,
2392 			 CAM_LUN_WILDCARD);
2393 	xpt_setup_ccb(&cpi.ccb_h, &path, CAM_PRIORITY_NORMAL);
2394 	cpi.ccb_h.func_code = XPT_PATH_INQ;
2395 	xpt_action((union ccb *)&cpi);
2396 	csa->callback(csa->callback_arg,
2397 			    AC_PATH_REGISTERED,
2398 			    &path, &cpi);
2399 	xpt_release_path(&path);
2400 
2401 	return(1);
2402 }
2403 
2404 void
2405 xpt_action(union ccb *start_ccb)
2406 {
2407 
2408 	CAM_DEBUG(start_ccb->ccb_h.path, CAM_DEBUG_TRACE, ("xpt_action\n"));
2409 
2410 	start_ccb->ccb_h.status = CAM_REQ_INPROG;
2411 	(*(start_ccb->ccb_h.path->bus->xport->action))(start_ccb);
2412 }
2413 
2414 void
2415 xpt_action_default(union ccb *start_ccb)
2416 {
2417 	struct cam_path *path;
2418 
2419 	path = start_ccb->ccb_h.path;
2420 	CAM_DEBUG(path, CAM_DEBUG_TRACE, ("xpt_action_default\n"));
2421 
2422 	switch (start_ccb->ccb_h.func_code) {
2423 	case XPT_SCSI_IO:
2424 	{
2425 		struct cam_ed *device;
2426 
2427 		/*
2428 		 * For the sake of compatibility with SCSI-1
2429 		 * devices that may not understand the identify
2430 		 * message, we include lun information in the
2431 		 * second byte of all commands.  SCSI-1 specifies
2432 		 * that luns are a 3 bit value and reserves only 3
2433 		 * bits for lun information in the CDB.  Later
2434 		 * revisions of the SCSI spec allow for more than 8
2435 		 * luns, but have deprecated lun information in the
2436 		 * CDB.  So, if the lun won't fit, we must omit.
2437 		 *
2438 		 * Also be aware that during initial probing for devices,
2439 		 * the inquiry information is unknown but initialized to 0.
2440 		 * This means that this code will be exercised while probing
2441 		 * devices with an ANSI revision greater than 2.
2442 		 */
2443 		device = path->device;
2444 		if (device->protocol_version <= SCSI_REV_2
2445 		 && start_ccb->ccb_h.target_lun < 8
2446 		 && (start_ccb->ccb_h.flags & CAM_CDB_POINTER) == 0) {
2447 
2448 			start_ccb->csio.cdb_io.cdb_bytes[1] |=
2449 			    start_ccb->ccb_h.target_lun << 5;
2450 		}
2451 		start_ccb->csio.scsi_status = SCSI_STATUS_OK;
2452 	}
2453 	/* FALLTHROUGH */
2454 	case XPT_TARGET_IO:
2455 	case XPT_CONT_TARGET_IO:
2456 		start_ccb->csio.sense_resid = 0;
2457 		start_ccb->csio.resid = 0;
2458 		/* FALLTHROUGH */
2459 	case XPT_ATA_IO:
2460 		if (start_ccb->ccb_h.func_code == XPT_ATA_IO)
2461 			start_ccb->ataio.resid = 0;
2462 		/* FALLTHROUGH */
2463 	case XPT_RESET_DEV:
2464 	case XPT_ENG_EXEC:
2465 	case XPT_SMP_IO:
2466 		cam_ccbq_insert_ccb(&path->device->ccbq, start_ccb);
2467 		if (xpt_schedule_devq(path->bus->sim->devq, path->device))
2468 			xpt_run_devq(path->bus->sim->devq);
2469 		break;
2470 	case XPT_CALC_GEOMETRY:
2471 	{
2472 		struct cam_sim *sim;
2473 
2474 		/* Filter out garbage */
2475 		if (start_ccb->ccg.block_size == 0
2476 		 || start_ccb->ccg.volume_size == 0) {
2477 			start_ccb->ccg.cylinders = 0;
2478 			start_ccb->ccg.heads = 0;
2479 			start_ccb->ccg.secs_per_track = 0;
2480 			start_ccb->ccb_h.status = CAM_REQ_CMP;
2481 			break;
2482 		}
2483 #if defined(PC98) || defined(__sparc64__)
2484 		/*
2485 		 * In a PC-98 system, geometry translation depens on
2486 		 * the "real" device geometry obtained from mode page 4.
2487 		 * SCSI geometry translation is performed in the
2488 		 * initialization routine of the SCSI BIOS and the result
2489 		 * stored in host memory.  If the translation is available
2490 		 * in host memory, use it.  If not, rely on the default
2491 		 * translation the device driver performs.
2492 		 * For sparc64, we may need adjust the geometry of large
2493 		 * disks in order to fit the limitations of the 16-bit
2494 		 * fields of the VTOC8 disk label.
2495 		 */
2496 		if (scsi_da_bios_params(&start_ccb->ccg) != 0) {
2497 			start_ccb->ccb_h.status = CAM_REQ_CMP;
2498 			break;
2499 		}
2500 #endif
2501 		sim = path->bus->sim;
2502 		(*(sim->sim_action))(sim, start_ccb);
2503 		break;
2504 	}
2505 	case XPT_ABORT:
2506 	{
2507 		union ccb* abort_ccb;
2508 
2509 		abort_ccb = start_ccb->cab.abort_ccb;
2510 		if (XPT_FC_IS_DEV_QUEUED(abort_ccb)) {
2511 
2512 			if (abort_ccb->ccb_h.pinfo.index >= 0) {
2513 				struct cam_ccbq *ccbq;
2514 				struct cam_ed *device;
2515 
2516 				device = abort_ccb->ccb_h.path->device;
2517 				ccbq = &device->ccbq;
2518 				cam_ccbq_remove_ccb(ccbq, abort_ccb);
2519 				abort_ccb->ccb_h.status =
2520 				    CAM_REQ_ABORTED|CAM_DEV_QFRZN;
2521 				xpt_freeze_devq(abort_ccb->ccb_h.path, 1);
2522 				xpt_done(abort_ccb);
2523 				start_ccb->ccb_h.status = CAM_REQ_CMP;
2524 				break;
2525 			}
2526 			if (abort_ccb->ccb_h.pinfo.index == CAM_UNQUEUED_INDEX
2527 			 && (abort_ccb->ccb_h.status & CAM_SIM_QUEUED) == 0) {
2528 				/*
2529 				 * We've caught this ccb en route to
2530 				 * the SIM.  Flag it for abort and the
2531 				 * SIM will do so just before starting
2532 				 * real work on the CCB.
2533 				 */
2534 				abort_ccb->ccb_h.status =
2535 				    CAM_REQ_ABORTED|CAM_DEV_QFRZN;
2536 				xpt_freeze_devq(abort_ccb->ccb_h.path, 1);
2537 				start_ccb->ccb_h.status = CAM_REQ_CMP;
2538 				break;
2539 			}
2540 		}
2541 		if (XPT_FC_IS_QUEUED(abort_ccb)
2542 		 && (abort_ccb->ccb_h.pinfo.index == CAM_DONEQ_INDEX)) {
2543 			/*
2544 			 * It's already completed but waiting
2545 			 * for our SWI to get to it.
2546 			 */
2547 			start_ccb->ccb_h.status = CAM_UA_ABORT;
2548 			break;
2549 		}
2550 		/*
2551 		 * If we weren't able to take care of the abort request
2552 		 * in the XPT, pass the request down to the SIM for processing.
2553 		 */
2554 	}
2555 	/* FALLTHROUGH */
2556 	case XPT_ACCEPT_TARGET_IO:
2557 	case XPT_EN_LUN:
2558 	case XPT_IMMED_NOTIFY:
2559 	case XPT_NOTIFY_ACK:
2560 	case XPT_RESET_BUS:
2561 	case XPT_IMMEDIATE_NOTIFY:
2562 	case XPT_NOTIFY_ACKNOWLEDGE:
2563 	case XPT_GET_SIM_KNOB:
2564 	case XPT_SET_SIM_KNOB:
2565 	{
2566 		struct cam_sim *sim;
2567 
2568 		sim = path->bus->sim;
2569 		(*(sim->sim_action))(sim, start_ccb);
2570 		break;
2571 	}
2572 	case XPT_PATH_INQ:
2573 	{
2574 		struct cam_sim *sim;
2575 
2576 		sim = path->bus->sim;
2577 		(*(sim->sim_action))(sim, start_ccb);
2578 		break;
2579 	}
2580 	case XPT_PATH_STATS:
2581 		start_ccb->cpis.last_reset = path->bus->last_reset;
2582 		start_ccb->ccb_h.status = CAM_REQ_CMP;
2583 		break;
2584 	case XPT_GDEV_TYPE:
2585 	{
2586 		struct cam_ed *dev;
2587 
2588 		dev = path->device;
2589 		if ((dev->flags & CAM_DEV_UNCONFIGURED) != 0) {
2590 			start_ccb->ccb_h.status = CAM_DEV_NOT_THERE;
2591 		} else {
2592 			struct ccb_getdev *cgd;
2593 
2594 			cgd = &start_ccb->cgd;
2595 			cgd->protocol = dev->protocol;
2596 			cgd->inq_data = dev->inq_data;
2597 			cgd->ident_data = dev->ident_data;
2598 			cgd->inq_flags = dev->inq_flags;
2599 			cgd->ccb_h.status = CAM_REQ_CMP;
2600 			cgd->serial_num_len = dev->serial_num_len;
2601 			if ((dev->serial_num_len > 0)
2602 			 && (dev->serial_num != NULL))
2603 				bcopy(dev->serial_num, cgd->serial_num,
2604 				      dev->serial_num_len);
2605 		}
2606 		break;
2607 	}
2608 	case XPT_GDEV_STATS:
2609 	{
2610 		struct cam_ed *dev;
2611 
2612 		dev = path->device;
2613 		if ((dev->flags & CAM_DEV_UNCONFIGURED) != 0) {
2614 			start_ccb->ccb_h.status = CAM_DEV_NOT_THERE;
2615 		} else {
2616 			struct ccb_getdevstats *cgds;
2617 			struct cam_eb *bus;
2618 			struct cam_et *tar;
2619 
2620 			cgds = &start_ccb->cgds;
2621 			bus = path->bus;
2622 			tar = path->target;
2623 			cgds->dev_openings = dev->ccbq.dev_openings;
2624 			cgds->dev_active = dev->ccbq.dev_active;
2625 			cgds->devq_openings = dev->ccbq.devq_openings;
2626 			cgds->devq_queued = dev->ccbq.queue.entries;
2627 			cgds->held = dev->ccbq.held;
2628 			cgds->last_reset = tar->last_reset;
2629 			cgds->maxtags = dev->maxtags;
2630 			cgds->mintags = dev->mintags;
2631 			if (timevalcmp(&tar->last_reset, &bus->last_reset, <))
2632 				cgds->last_reset = bus->last_reset;
2633 			cgds->ccb_h.status = CAM_REQ_CMP;
2634 		}
2635 		break;
2636 	}
2637 	case XPT_GDEVLIST:
2638 	{
2639 		struct cam_periph	*nperiph;
2640 		struct periph_list	*periph_head;
2641 		struct ccb_getdevlist	*cgdl;
2642 		u_int			i;
2643 		struct cam_ed		*device;
2644 		int			found;
2645 
2646 
2647 		found = 0;
2648 
2649 		/*
2650 		 * Don't want anyone mucking with our data.
2651 		 */
2652 		device = path->device;
2653 		periph_head = &device->periphs;
2654 		cgdl = &start_ccb->cgdl;
2655 
2656 		/*
2657 		 * Check and see if the list has changed since the user
2658 		 * last requested a list member.  If so, tell them that the
2659 		 * list has changed, and therefore they need to start over
2660 		 * from the beginning.
2661 		 */
2662 		if ((cgdl->index != 0) &&
2663 		    (cgdl->generation != device->generation)) {
2664 			cgdl->status = CAM_GDEVLIST_LIST_CHANGED;
2665 			break;
2666 		}
2667 
2668 		/*
2669 		 * Traverse the list of peripherals and attempt to find
2670 		 * the requested peripheral.
2671 		 */
2672 		for (nperiph = SLIST_FIRST(periph_head), i = 0;
2673 		     (nperiph != NULL) && (i <= cgdl->index);
2674 		     nperiph = SLIST_NEXT(nperiph, periph_links), i++) {
2675 			if (i == cgdl->index) {
2676 				strncpy(cgdl->periph_name,
2677 					nperiph->periph_name,
2678 					DEV_IDLEN);
2679 				cgdl->unit_number = nperiph->unit_number;
2680 				found = 1;
2681 			}
2682 		}
2683 		if (found == 0) {
2684 			cgdl->status = CAM_GDEVLIST_ERROR;
2685 			break;
2686 		}
2687 
2688 		if (nperiph == NULL)
2689 			cgdl->status = CAM_GDEVLIST_LAST_DEVICE;
2690 		else
2691 			cgdl->status = CAM_GDEVLIST_MORE_DEVS;
2692 
2693 		cgdl->index++;
2694 		cgdl->generation = device->generation;
2695 
2696 		cgdl->ccb_h.status = CAM_REQ_CMP;
2697 		break;
2698 	}
2699 	case XPT_DEV_MATCH:
2700 	{
2701 		dev_pos_type position_type;
2702 		struct ccb_dev_match *cdm;
2703 
2704 		cdm = &start_ccb->cdm;
2705 
2706 		/*
2707 		 * There are two ways of getting at information in the EDT.
2708 		 * The first way is via the primary EDT tree.  It starts
2709 		 * with a list of busses, then a list of targets on a bus,
2710 		 * then devices/luns on a target, and then peripherals on a
2711 		 * device/lun.  The "other" way is by the peripheral driver
2712 		 * lists.  The peripheral driver lists are organized by
2713 		 * peripheral driver.  (obviously)  So it makes sense to
2714 		 * use the peripheral driver list if the user is looking
2715 		 * for something like "da1", or all "da" devices.  If the
2716 		 * user is looking for something on a particular bus/target
2717 		 * or lun, it's generally better to go through the EDT tree.
2718 		 */
2719 
2720 		if (cdm->pos.position_type != CAM_DEV_POS_NONE)
2721 			position_type = cdm->pos.position_type;
2722 		else {
2723 			u_int i;
2724 
2725 			position_type = CAM_DEV_POS_NONE;
2726 
2727 			for (i = 0; i < cdm->num_patterns; i++) {
2728 				if ((cdm->patterns[i].type == DEV_MATCH_BUS)
2729 				 ||(cdm->patterns[i].type == DEV_MATCH_DEVICE)){
2730 					position_type = CAM_DEV_POS_EDT;
2731 					break;
2732 				}
2733 			}
2734 
2735 			if (cdm->num_patterns == 0)
2736 				position_type = CAM_DEV_POS_EDT;
2737 			else if (position_type == CAM_DEV_POS_NONE)
2738 				position_type = CAM_DEV_POS_PDRV;
2739 		}
2740 
2741 		/*
2742 		 * Note that we drop the SIM lock here, because the EDT
2743 		 * traversal code needs to do its own locking.
2744 		 */
2745 		CAM_SIM_UNLOCK(xpt_path_sim(cdm->ccb_h.path));
2746 		switch(position_type & CAM_DEV_POS_TYPEMASK) {
2747 		case CAM_DEV_POS_EDT:
2748 			xptedtmatch(cdm);
2749 			break;
2750 		case CAM_DEV_POS_PDRV:
2751 			xptperiphlistmatch(cdm);
2752 			break;
2753 		default:
2754 			cdm->status = CAM_DEV_MATCH_ERROR;
2755 			break;
2756 		}
2757 		CAM_SIM_LOCK(xpt_path_sim(cdm->ccb_h.path));
2758 
2759 		if (cdm->status == CAM_DEV_MATCH_ERROR)
2760 			start_ccb->ccb_h.status = CAM_REQ_CMP_ERR;
2761 		else
2762 			start_ccb->ccb_h.status = CAM_REQ_CMP;
2763 
2764 		break;
2765 	}
2766 	case XPT_SASYNC_CB:
2767 	{
2768 		struct ccb_setasync *csa;
2769 		struct async_node *cur_entry;
2770 		struct async_list *async_head;
2771 		u_int32_t added;
2772 
2773 		csa = &start_ccb->csa;
2774 		added = csa->event_enable;
2775 		async_head = &path->device->asyncs;
2776 
2777 		/*
2778 		 * If there is already an entry for us, simply
2779 		 * update it.
2780 		 */
2781 		cur_entry = SLIST_FIRST(async_head);
2782 		while (cur_entry != NULL) {
2783 			if ((cur_entry->callback_arg == csa->callback_arg)
2784 			 && (cur_entry->callback == csa->callback))
2785 				break;
2786 			cur_entry = SLIST_NEXT(cur_entry, links);
2787 		}
2788 
2789 		if (cur_entry != NULL) {
2790 		 	/*
2791 			 * If the request has no flags set,
2792 			 * remove the entry.
2793 			 */
2794 			added &= ~cur_entry->event_enable;
2795 			if (csa->event_enable == 0) {
2796 				SLIST_REMOVE(async_head, cur_entry,
2797 					     async_node, links);
2798 				xpt_release_device(path->device);
2799 				free(cur_entry, M_CAMXPT);
2800 			} else {
2801 				cur_entry->event_enable = csa->event_enable;
2802 			}
2803 			csa->event_enable = added;
2804 		} else {
2805 			cur_entry = malloc(sizeof(*cur_entry), M_CAMXPT,
2806 					   M_NOWAIT);
2807 			if (cur_entry == NULL) {
2808 				csa->ccb_h.status = CAM_RESRC_UNAVAIL;
2809 				break;
2810 			}
2811 			cur_entry->event_enable = csa->event_enable;
2812 			cur_entry->callback_arg = csa->callback_arg;
2813 			cur_entry->callback = csa->callback;
2814 			SLIST_INSERT_HEAD(async_head, cur_entry, links);
2815 			xpt_acquire_device(path->device);
2816 		}
2817 		start_ccb->ccb_h.status = CAM_REQ_CMP;
2818 		break;
2819 	}
2820 	case XPT_REL_SIMQ:
2821 	{
2822 		struct ccb_relsim *crs;
2823 		struct cam_ed *dev;
2824 
2825 		crs = &start_ccb->crs;
2826 		dev = path->device;
2827 		if (dev == NULL) {
2828 
2829 			crs->ccb_h.status = CAM_DEV_NOT_THERE;
2830 			break;
2831 		}
2832 
2833 		if ((crs->release_flags & RELSIM_ADJUST_OPENINGS) != 0) {
2834 
2835 			/* Don't ever go below one opening */
2836 			if (crs->openings > 0) {
2837 				xpt_dev_ccbq_resize(path, crs->openings);
2838 				if (bootverbose) {
2839 					xpt_print(path,
2840 					    "number of openings is now %d\n",
2841 					    crs->openings);
2842 				}
2843 			}
2844 		}
2845 
2846 		if ((crs->release_flags & RELSIM_RELEASE_AFTER_TIMEOUT) != 0) {
2847 
2848 			if ((dev->flags & CAM_DEV_REL_TIMEOUT_PENDING) != 0) {
2849 
2850 				/*
2851 				 * Just extend the old timeout and decrement
2852 				 * the freeze count so that a single timeout
2853 				 * is sufficient for releasing the queue.
2854 				 */
2855 				start_ccb->ccb_h.flags &= ~CAM_DEV_QFREEZE;
2856 				callout_stop(&dev->callout);
2857 			} else {
2858 
2859 				start_ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
2860 			}
2861 
2862 			callout_reset(&dev->callout,
2863 			    (crs->release_timeout * hz) / 1000,
2864 			    xpt_release_devq_timeout, dev);
2865 
2866 			dev->flags |= CAM_DEV_REL_TIMEOUT_PENDING;
2867 
2868 		}
2869 
2870 		if ((crs->release_flags & RELSIM_RELEASE_AFTER_CMDCMPLT) != 0) {
2871 
2872 			if ((dev->flags & CAM_DEV_REL_ON_COMPLETE) != 0) {
2873 				/*
2874 				 * Decrement the freeze count so that a single
2875 				 * completion is still sufficient to unfreeze
2876 				 * the queue.
2877 				 */
2878 				start_ccb->ccb_h.flags &= ~CAM_DEV_QFREEZE;
2879 			} else {
2880 
2881 				dev->flags |= CAM_DEV_REL_ON_COMPLETE;
2882 				start_ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
2883 			}
2884 		}
2885 
2886 		if ((crs->release_flags & RELSIM_RELEASE_AFTER_QEMPTY) != 0) {
2887 
2888 			if ((dev->flags & CAM_DEV_REL_ON_QUEUE_EMPTY) != 0
2889 			 || (dev->ccbq.dev_active == 0)) {
2890 
2891 				start_ccb->ccb_h.flags &= ~CAM_DEV_QFREEZE;
2892 			} else {
2893 
2894 				dev->flags |= CAM_DEV_REL_ON_QUEUE_EMPTY;
2895 				start_ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
2896 			}
2897 		}
2898 
2899 		if ((start_ccb->ccb_h.flags & CAM_DEV_QFREEZE) == 0)
2900 			xpt_release_devq(path, /*count*/1, /*run_queue*/TRUE);
2901 		start_ccb->crs.qfrozen_cnt = dev->ccbq.queue.qfrozen_cnt;
2902 		start_ccb->ccb_h.status = CAM_REQ_CMP;
2903 		break;
2904 	}
2905 	case XPT_DEBUG: {
2906 		struct cam_path *oldpath;
2907 		struct cam_sim *oldsim;
2908 
2909 		/* Check that all request bits are supported. */
2910 		if (start_ccb->cdbg.flags & ~(CAM_DEBUG_COMPILE)) {
2911 			start_ccb->ccb_h.status = CAM_FUNC_NOTAVAIL;
2912 			break;
2913 		}
2914 
2915 		cam_dflags = CAM_DEBUG_NONE;
2916 		if (cam_dpath != NULL) {
2917 			/* To release the old path we must hold proper lock. */
2918 			oldpath = cam_dpath;
2919 			cam_dpath = NULL;
2920 			oldsim = xpt_path_sim(oldpath);
2921 			CAM_SIM_UNLOCK(xpt_path_sim(start_ccb->ccb_h.path));
2922 			CAM_SIM_LOCK(oldsim);
2923 			xpt_free_path(oldpath);
2924 			CAM_SIM_UNLOCK(oldsim);
2925 			CAM_SIM_LOCK(xpt_path_sim(start_ccb->ccb_h.path));
2926 		}
2927 		if (start_ccb->cdbg.flags != CAM_DEBUG_NONE) {
2928 			if (xpt_create_path(&cam_dpath, NULL,
2929 					    start_ccb->ccb_h.path_id,
2930 					    start_ccb->ccb_h.target_id,
2931 					    start_ccb->ccb_h.target_lun) !=
2932 					    CAM_REQ_CMP) {
2933 				start_ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
2934 			} else {
2935 				cam_dflags = start_ccb->cdbg.flags;
2936 				start_ccb->ccb_h.status = CAM_REQ_CMP;
2937 				xpt_print(cam_dpath, "debugging flags now %x\n",
2938 				    cam_dflags);
2939 			}
2940 		} else
2941 			start_ccb->ccb_h.status = CAM_REQ_CMP;
2942 		break;
2943 	}
2944 	case XPT_NOOP:
2945 		if ((start_ccb->ccb_h.flags & CAM_DEV_QFREEZE) != 0)
2946 			xpt_freeze_devq(path, 1);
2947 		start_ccb->ccb_h.status = CAM_REQ_CMP;
2948 		break;
2949 	default:
2950 	case XPT_SDEV_TYPE:
2951 	case XPT_TERM_IO:
2952 	case XPT_ENG_INQ:
2953 		/* XXX Implement */
2954 		printf("%s: CCB type %#x not supported\n", __func__,
2955 		       start_ccb->ccb_h.func_code);
2956 		start_ccb->ccb_h.status = CAM_PROVIDE_FAIL;
2957 		if (start_ccb->ccb_h.func_code & XPT_FC_DEV_QUEUED) {
2958 			xpt_done(start_ccb);
2959 		}
2960 		break;
2961 	}
2962 }
2963 
2964 void
2965 xpt_polled_action(union ccb *start_ccb)
2966 {
2967 	u_int32_t timeout;
2968 	struct	  cam_sim *sim;
2969 	struct	  cam_devq *devq;
2970 	struct	  cam_ed *dev;
2971 
2972 
2973 	timeout = start_ccb->ccb_h.timeout * 10;
2974 	sim = start_ccb->ccb_h.path->bus->sim;
2975 	devq = sim->devq;
2976 	dev = start_ccb->ccb_h.path->device;
2977 
2978 	mtx_assert(sim->mtx, MA_OWNED);
2979 
2980 	/* Don't use ISR for this SIM while polling. */
2981 	sim->flags |= CAM_SIM_POLLED;
2982 
2983 	/*
2984 	 * Steal an opening so that no other queued requests
2985 	 * can get it before us while we simulate interrupts.
2986 	 */
2987 	dev->ccbq.devq_openings--;
2988 	dev->ccbq.dev_openings--;
2989 
2990 	while(((devq != NULL && devq->send_openings <= 0) ||
2991 	   dev->ccbq.dev_openings < 0) && (--timeout > 0)) {
2992 		DELAY(100);
2993 		(*(sim->sim_poll))(sim);
2994 		camisr_runqueue(&sim->sim_doneq);
2995 	}
2996 
2997 	dev->ccbq.devq_openings++;
2998 	dev->ccbq.dev_openings++;
2999 
3000 	if (timeout != 0) {
3001 		xpt_action(start_ccb);
3002 		while(--timeout > 0) {
3003 			(*(sim->sim_poll))(sim);
3004 			camisr_runqueue(&sim->sim_doneq);
3005 			if ((start_ccb->ccb_h.status  & CAM_STATUS_MASK)
3006 			    != CAM_REQ_INPROG)
3007 				break;
3008 			DELAY(100);
3009 		}
3010 		if (timeout == 0) {
3011 			/*
3012 			 * XXX Is it worth adding a sim_timeout entry
3013 			 * point so we can attempt recovery?  If
3014 			 * this is only used for dumps, I don't think
3015 			 * it is.
3016 			 */
3017 			start_ccb->ccb_h.status = CAM_CMD_TIMEOUT;
3018 		}
3019 	} else {
3020 		start_ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
3021 	}
3022 
3023 	/* We will use CAM ISR for this SIM again. */
3024 	sim->flags &= ~CAM_SIM_POLLED;
3025 }
3026 
3027 /*
3028  * Schedule a peripheral driver to receive a ccb when it's
3029  * target device has space for more transactions.
3030  */
3031 void
3032 xpt_schedule(struct cam_periph *perph, u_int32_t new_priority)
3033 {
3034 	struct cam_ed *device;
3035 	int runq = 0;
3036 
3037 	mtx_assert(perph->sim->mtx, MA_OWNED);
3038 
3039 	CAM_DEBUG(perph->path, CAM_DEBUG_TRACE, ("xpt_schedule\n"));
3040 	device = perph->path->device;
3041 	if (periph_is_queued(perph)) {
3042 		/* Simply reorder based on new priority */
3043 		CAM_DEBUG(perph->path, CAM_DEBUG_SUBTRACE,
3044 			  ("   change priority to %d\n", new_priority));
3045 		if (new_priority < perph->pinfo.priority) {
3046 			camq_change_priority(&device->drvq,
3047 					     perph->pinfo.index,
3048 					     new_priority);
3049 			runq = 1;
3050 		}
3051 	} else {
3052 		/* New entry on the queue */
3053 		CAM_DEBUG(perph->path, CAM_DEBUG_SUBTRACE,
3054 			  ("   added periph to queue\n"));
3055 		perph->pinfo.priority = new_priority;
3056 		perph->pinfo.generation = ++device->drvq.generation;
3057 		camq_insert(&device->drvq, &perph->pinfo);
3058 		runq = 1;
3059 	}
3060 	if (runq != 0) {
3061 		CAM_DEBUG(perph->path, CAM_DEBUG_SUBTRACE,
3062 			  ("   calling xpt_run_dev_allocq\n"));
3063 		xpt_run_dev_allocq(device);
3064 	}
3065 }
3066 
3067 
3068 /*
3069  * Schedule a device to run on a given queue.
3070  * If the device was inserted as a new entry on the queue,
3071  * return 1 meaning the device queue should be run. If we
3072  * were already queued, implying someone else has already
3073  * started the queue, return 0 so the caller doesn't attempt
3074  * to run the queue.
3075  */
3076 int
3077 xpt_schedule_dev(struct camq *queue, cam_pinfo *pinfo,
3078 		 u_int32_t new_priority)
3079 {
3080 	int retval;
3081 	u_int32_t old_priority;
3082 
3083 	CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_schedule_dev\n"));
3084 
3085 	old_priority = pinfo->priority;
3086 
3087 	/*
3088 	 * Are we already queued?
3089 	 */
3090 	if (pinfo->index != CAM_UNQUEUED_INDEX) {
3091 		/* Simply reorder based on new priority */
3092 		if (new_priority < old_priority) {
3093 			camq_change_priority(queue, pinfo->index,
3094 					     new_priority);
3095 			CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3096 					("changed priority to %d\n",
3097 					 new_priority));
3098 			retval = 1;
3099 		} else
3100 			retval = 0;
3101 	} else {
3102 		/* New entry on the queue */
3103 		if (new_priority < old_priority)
3104 			pinfo->priority = new_priority;
3105 
3106 		CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3107 				("Inserting onto queue\n"));
3108 		pinfo->generation = ++queue->generation;
3109 		camq_insert(queue, pinfo);
3110 		retval = 1;
3111 	}
3112 	return (retval);
3113 }
3114 
3115 static void
3116 xpt_run_dev_allocq(struct cam_ed *device)
3117 {
3118 	struct camq	*drvq;
3119 
3120 	if (device->ccbq.devq_allocating)
3121 		return;
3122 	device->ccbq.devq_allocating = 1;
3123 	CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_run_dev_allocq(%p)\n", device));
3124 	drvq = &device->drvq;
3125 	while ((drvq->entries > 0) &&
3126 	    (device->ccbq.devq_openings > 0 ||
3127 	     CAMQ_GET_PRIO(drvq) <= CAM_PRIORITY_OOB) &&
3128 	    (device->ccbq.queue.qfrozen_cnt == 0)) {
3129 		union	ccb *work_ccb;
3130 		struct	cam_periph *drv;
3131 
3132 		KASSERT(drvq->entries > 0, ("xpt_run_dev_allocq: "
3133 		    "Device on queue without any work to do"));
3134 		if ((work_ccb = xpt_get_ccb(device)) != NULL) {
3135 			drv = (struct cam_periph*)camq_remove(drvq, CAMQ_HEAD);
3136 			xpt_setup_ccb(&work_ccb->ccb_h, drv->path,
3137 				      drv->pinfo.priority);
3138 			CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3139 					("calling periph start\n"));
3140 			drv->periph_start(drv, work_ccb);
3141 		} else {
3142 			/*
3143 			 * Malloc failure in alloc_ccb
3144 			 */
3145 			/*
3146 			 * XXX add us to a list to be run from free_ccb
3147 			 * if we don't have any ccbs active on this
3148 			 * device queue otherwise we may never get run
3149 			 * again.
3150 			 */
3151 			break;
3152 		}
3153 	}
3154 	device->ccbq.devq_allocating = 0;
3155 }
3156 
3157 static void
3158 xpt_run_devq(struct cam_devq *devq)
3159 {
3160 	char cdb_str[(SCSI_MAX_CDBLEN * 3) + 1];
3161 
3162 	CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_run_devq\n"));
3163 
3164 	devq->send_queue.qfrozen_cnt++;
3165 	while ((devq->send_queue.entries > 0)
3166 	    && (devq->send_openings > 0)
3167 	    && (devq->send_queue.qfrozen_cnt <= 1)) {
3168 		struct	cam_ed_qinfo *qinfo;
3169 		struct	cam_ed *device;
3170 		union ccb *work_ccb;
3171 		struct	cam_sim *sim;
3172 
3173 		qinfo = (struct cam_ed_qinfo *)camq_remove(&devq->send_queue,
3174 							   CAMQ_HEAD);
3175 		device = qinfo->device;
3176 		CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
3177 				("running device %p\n", device));
3178 
3179 		work_ccb = cam_ccbq_peek_ccb(&device->ccbq, CAMQ_HEAD);
3180 		if (work_ccb == NULL) {
3181 			printf("device on run queue with no ccbs???\n");
3182 			continue;
3183 		}
3184 
3185 		if ((work_ccb->ccb_h.flags & CAM_HIGH_POWER) != 0) {
3186 
3187 			mtx_lock(&xsoftc.xpt_lock);
3188 		 	if (xsoftc.num_highpower <= 0) {
3189 				/*
3190 				 * We got a high power command, but we
3191 				 * don't have any available slots.  Freeze
3192 				 * the device queue until we have a slot
3193 				 * available.
3194 				 */
3195 				xpt_freeze_devq(work_ccb->ccb_h.path, 1);
3196 				STAILQ_INSERT_TAIL(&xsoftc.highpowerq,
3197 						   &work_ccb->ccb_h,
3198 						   xpt_links.stqe);
3199 
3200 				mtx_unlock(&xsoftc.xpt_lock);
3201 				continue;
3202 			} else {
3203 				/*
3204 				 * Consume a high power slot while
3205 				 * this ccb runs.
3206 				 */
3207 				xsoftc.num_highpower--;
3208 			}
3209 			mtx_unlock(&xsoftc.xpt_lock);
3210 		}
3211 		cam_ccbq_remove_ccb(&device->ccbq, work_ccb);
3212 		cam_ccbq_send_ccb(&device->ccbq, work_ccb);
3213 
3214 		devq->send_openings--;
3215 		devq->send_active++;
3216 
3217 		xpt_schedule_devq(devq, device);
3218 
3219 		if ((work_ccb->ccb_h.flags & CAM_DEV_QFREEZE) != 0) {
3220 			/*
3221 			 * The client wants to freeze the queue
3222 			 * after this CCB is sent.
3223 			 */
3224 			xpt_freeze_devq(work_ccb->ccb_h.path, 1);
3225 		}
3226 
3227 		/* In Target mode, the peripheral driver knows best... */
3228 		if (work_ccb->ccb_h.func_code == XPT_SCSI_IO) {
3229 			if ((device->inq_flags & SID_CmdQue) != 0
3230 			 && work_ccb->csio.tag_action != CAM_TAG_ACTION_NONE)
3231 				work_ccb->ccb_h.flags |= CAM_TAG_ACTION_VALID;
3232 			else
3233 				/*
3234 				 * Clear this in case of a retried CCB that
3235 				 * failed due to a rejected tag.
3236 				 */
3237 				work_ccb->ccb_h.flags &= ~CAM_TAG_ACTION_VALID;
3238 		}
3239 
3240 		switch (work_ccb->ccb_h.func_code) {
3241 		case XPT_SCSI_IO:
3242 			CAM_DEBUG(work_ccb->ccb_h.path,
3243 			    CAM_DEBUG_CDB,("%s. CDB: %s\n",
3244 			     scsi_op_desc(work_ccb->csio.cdb_io.cdb_bytes[0],
3245 					  &device->inq_data),
3246 			     scsi_cdb_string(work_ccb->csio.cdb_io.cdb_bytes,
3247 					     cdb_str, sizeof(cdb_str))));
3248 			break;
3249 		case XPT_ATA_IO:
3250 			CAM_DEBUG(work_ccb->ccb_h.path,
3251 			    CAM_DEBUG_CDB,("%s. ACB: %s\n",
3252 			     ata_op_string(&work_ccb->ataio.cmd),
3253 			     ata_cmd_string(&work_ccb->ataio.cmd,
3254 					    cdb_str, sizeof(cdb_str))));
3255 			break;
3256 		default:
3257 			break;
3258 		}
3259 
3260 		/*
3261 		 * Device queues can be shared among multiple sim instances
3262 		 * that reside on different busses.  Use the SIM in the queue
3263 		 * CCB's path, rather than the one in the bus that was passed
3264 		 * into this function.
3265 		 */
3266 		sim = work_ccb->ccb_h.path->bus->sim;
3267 		(*(sim->sim_action))(sim, work_ccb);
3268 	}
3269 	devq->send_queue.qfrozen_cnt--;
3270 }
3271 
3272 /*
3273  * This function merges stuff from the slave ccb into the master ccb, while
3274  * keeping important fields in the master ccb constant.
3275  */
3276 void
3277 xpt_merge_ccb(union ccb *master_ccb, union ccb *slave_ccb)
3278 {
3279 
3280 	/*
3281 	 * Pull fields that are valid for peripheral drivers to set
3282 	 * into the master CCB along with the CCB "payload".
3283 	 */
3284 	master_ccb->ccb_h.retry_count = slave_ccb->ccb_h.retry_count;
3285 	master_ccb->ccb_h.func_code = slave_ccb->ccb_h.func_code;
3286 	master_ccb->ccb_h.timeout = slave_ccb->ccb_h.timeout;
3287 	master_ccb->ccb_h.flags = slave_ccb->ccb_h.flags;
3288 	bcopy(&(&slave_ccb->ccb_h)[1], &(&master_ccb->ccb_h)[1],
3289 	      sizeof(union ccb) - sizeof(struct ccb_hdr));
3290 }
3291 
3292 void
3293 xpt_setup_ccb(struct ccb_hdr *ccb_h, struct cam_path *path, u_int32_t priority)
3294 {
3295 
3296 	CAM_DEBUG(path, CAM_DEBUG_TRACE, ("xpt_setup_ccb\n"));
3297 	ccb_h->pinfo.priority = priority;
3298 	ccb_h->path = path;
3299 	ccb_h->path_id = path->bus->path_id;
3300 	if (path->target)
3301 		ccb_h->target_id = path->target->target_id;
3302 	else
3303 		ccb_h->target_id = CAM_TARGET_WILDCARD;
3304 	if (path->device) {
3305 		ccb_h->target_lun = path->device->lun_id;
3306 		ccb_h->pinfo.generation = ++path->device->ccbq.queue.generation;
3307 	} else {
3308 		ccb_h->target_lun = CAM_TARGET_WILDCARD;
3309 	}
3310 	ccb_h->pinfo.index = CAM_UNQUEUED_INDEX;
3311 	ccb_h->flags = 0;
3312 }
3313 
3314 /* Path manipulation functions */
3315 cam_status
3316 xpt_create_path(struct cam_path **new_path_ptr, struct cam_periph *perph,
3317 		path_id_t path_id, target_id_t target_id, lun_id_t lun_id)
3318 {
3319 	struct	   cam_path *path;
3320 	cam_status status;
3321 
3322 	path = (struct cam_path *)malloc(sizeof(*path), M_CAMPATH, M_NOWAIT);
3323 
3324 	if (path == NULL) {
3325 		status = CAM_RESRC_UNAVAIL;
3326 		return(status);
3327 	}
3328 	status = xpt_compile_path(path, perph, path_id, target_id, lun_id);
3329 	if (status != CAM_REQ_CMP) {
3330 		free(path, M_CAMPATH);
3331 		path = NULL;
3332 	}
3333 	*new_path_ptr = path;
3334 	return (status);
3335 }
3336 
3337 cam_status
3338 xpt_create_path_unlocked(struct cam_path **new_path_ptr,
3339 			 struct cam_periph *periph, path_id_t path_id,
3340 			 target_id_t target_id, lun_id_t lun_id)
3341 {
3342 	struct	   cam_path *path;
3343 	struct	   cam_eb *bus = NULL;
3344 	cam_status status;
3345 
3346 	path = (struct cam_path *)malloc(sizeof(*path), M_CAMPATH, M_WAITOK);
3347 
3348 	bus = xpt_find_bus(path_id);
3349 	if (bus != NULL)
3350 		CAM_SIM_LOCK(bus->sim);
3351 	status = xpt_compile_path(path, periph, path_id, target_id, lun_id);
3352 	if (bus != NULL) {
3353 		CAM_SIM_UNLOCK(bus->sim);
3354 		xpt_release_bus(bus);
3355 	}
3356 	if (status != CAM_REQ_CMP) {
3357 		free(path, M_CAMPATH);
3358 		path = NULL;
3359 	}
3360 	*new_path_ptr = path;
3361 	return (status);
3362 }
3363 
3364 cam_status
3365 xpt_compile_path(struct cam_path *new_path, struct cam_periph *perph,
3366 		 path_id_t path_id, target_id_t target_id, lun_id_t lun_id)
3367 {
3368 	struct	     cam_eb *bus;
3369 	struct	     cam_et *target;
3370 	struct	     cam_ed *device;
3371 	cam_status   status;
3372 
3373 	status = CAM_REQ_CMP;	/* Completed without error */
3374 	target = NULL;		/* Wildcarded */
3375 	device = NULL;		/* Wildcarded */
3376 
3377 	/*
3378 	 * We will potentially modify the EDT, so block interrupts
3379 	 * that may attempt to create cam paths.
3380 	 */
3381 	bus = xpt_find_bus(path_id);
3382 	if (bus == NULL) {
3383 		status = CAM_PATH_INVALID;
3384 	} else {
3385 		target = xpt_find_target(bus, target_id);
3386 		if (target == NULL) {
3387 			/* Create one */
3388 			struct cam_et *new_target;
3389 
3390 			new_target = xpt_alloc_target(bus, target_id);
3391 			if (new_target == NULL) {
3392 				status = CAM_RESRC_UNAVAIL;
3393 			} else {
3394 				target = new_target;
3395 			}
3396 		}
3397 		if (target != NULL) {
3398 			device = xpt_find_device(target, lun_id);
3399 			if (device == NULL) {
3400 				/* Create one */
3401 				struct cam_ed *new_device;
3402 
3403 				new_device =
3404 				    (*(bus->xport->alloc_device))(bus,
3405 								      target,
3406 								      lun_id);
3407 				if (new_device == NULL) {
3408 					status = CAM_RESRC_UNAVAIL;
3409 				} else {
3410 					device = new_device;
3411 				}
3412 			}
3413 		}
3414 	}
3415 
3416 	/*
3417 	 * Only touch the user's data if we are successful.
3418 	 */
3419 	if (status == CAM_REQ_CMP) {
3420 		new_path->periph = perph;
3421 		new_path->bus = bus;
3422 		new_path->target = target;
3423 		new_path->device = device;
3424 		CAM_DEBUG(new_path, CAM_DEBUG_TRACE, ("xpt_compile_path\n"));
3425 	} else {
3426 		if (device != NULL)
3427 			xpt_release_device(device);
3428 		if (target != NULL)
3429 			xpt_release_target(target);
3430 		if (bus != NULL)
3431 			xpt_release_bus(bus);
3432 	}
3433 	return (status);
3434 }
3435 
3436 void
3437 xpt_release_path(struct cam_path *path)
3438 {
3439 	CAM_DEBUG(path, CAM_DEBUG_TRACE, ("xpt_release_path\n"));
3440 	if (path->device != NULL) {
3441 		xpt_release_device(path->device);
3442 		path->device = NULL;
3443 	}
3444 	if (path->target != NULL) {
3445 		xpt_release_target(path->target);
3446 		path->target = NULL;
3447 	}
3448 	if (path->bus != NULL) {
3449 		xpt_release_bus(path->bus);
3450 		path->bus = NULL;
3451 	}
3452 }
3453 
3454 void
3455 xpt_free_path(struct cam_path *path)
3456 {
3457 
3458 	CAM_DEBUG(path, CAM_DEBUG_TRACE, ("xpt_free_path\n"));
3459 	xpt_release_path(path);
3460 	free(path, M_CAMPATH);
3461 }
3462 
3463 void
3464 xpt_path_counts(struct cam_path *path, uint32_t *bus_ref,
3465     uint32_t *periph_ref, uint32_t *target_ref, uint32_t *device_ref)
3466 {
3467 
3468 	xpt_lock_buses();
3469 	if (bus_ref) {
3470 		if (path->bus)
3471 			*bus_ref = path->bus->refcount;
3472 		else
3473 			*bus_ref = 0;
3474 	}
3475 	if (periph_ref) {
3476 		if (path->periph)
3477 			*periph_ref = path->periph->refcount;
3478 		else
3479 			*periph_ref = 0;
3480 	}
3481 	xpt_unlock_buses();
3482 	if (target_ref) {
3483 		if (path->target)
3484 			*target_ref = path->target->refcount;
3485 		else
3486 			*target_ref = 0;
3487 	}
3488 	if (device_ref) {
3489 		if (path->device)
3490 			*device_ref = path->device->refcount;
3491 		else
3492 			*device_ref = 0;
3493 	}
3494 }
3495 
3496 /*
3497  * Return -1 for failure, 0 for exact match, 1 for match with wildcards
3498  * in path1, 2 for match with wildcards in path2.
3499  */
3500 int
3501 xpt_path_comp(struct cam_path *path1, struct cam_path *path2)
3502 {
3503 	int retval = 0;
3504 
3505 	if (path1->bus != path2->bus) {
3506 		if (path1->bus->path_id == CAM_BUS_WILDCARD)
3507 			retval = 1;
3508 		else if (path2->bus->path_id == CAM_BUS_WILDCARD)
3509 			retval = 2;
3510 		else
3511 			return (-1);
3512 	}
3513 	if (path1->target != path2->target) {
3514 		if (path1->target->target_id == CAM_TARGET_WILDCARD) {
3515 			if (retval == 0)
3516 				retval = 1;
3517 		} else if (path2->target->target_id == CAM_TARGET_WILDCARD)
3518 			retval = 2;
3519 		else
3520 			return (-1);
3521 	}
3522 	if (path1->device != path2->device) {
3523 		if (path1->device->lun_id == CAM_LUN_WILDCARD) {
3524 			if (retval == 0)
3525 				retval = 1;
3526 		} else if (path2->device->lun_id == CAM_LUN_WILDCARD)
3527 			retval = 2;
3528 		else
3529 			return (-1);
3530 	}
3531 	return (retval);
3532 }
3533 
3534 void
3535 xpt_print_path(struct cam_path *path)
3536 {
3537 
3538 	if (path == NULL)
3539 		printf("(nopath): ");
3540 	else {
3541 		if (path->periph != NULL)
3542 			printf("(%s%d:", path->periph->periph_name,
3543 			       path->periph->unit_number);
3544 		else
3545 			printf("(noperiph:");
3546 
3547 		if (path->bus != NULL)
3548 			printf("%s%d:%d:", path->bus->sim->sim_name,
3549 			       path->bus->sim->unit_number,
3550 			       path->bus->sim->bus_id);
3551 		else
3552 			printf("nobus:");
3553 
3554 		if (path->target != NULL)
3555 			printf("%d:", path->target->target_id);
3556 		else
3557 			printf("X:");
3558 
3559 		if (path->device != NULL)
3560 			printf("%d): ", path->device->lun_id);
3561 		else
3562 			printf("X): ");
3563 	}
3564 }
3565 
3566 void
3567 xpt_print(struct cam_path *path, const char *fmt, ...)
3568 {
3569 	va_list ap;
3570 	xpt_print_path(path);
3571 	va_start(ap, fmt);
3572 	vprintf(fmt, ap);
3573 	va_end(ap);
3574 }
3575 
3576 int
3577 xpt_path_string(struct cam_path *path, char *str, size_t str_len)
3578 {
3579 	struct sbuf sb;
3580 
3581 #ifdef INVARIANTS
3582 	if (path != NULL && path->bus != NULL)
3583 		mtx_assert(path->bus->sim->mtx, MA_OWNED);
3584 #endif
3585 
3586 	sbuf_new(&sb, str, str_len, 0);
3587 
3588 	if (path == NULL)
3589 		sbuf_printf(&sb, "(nopath): ");
3590 	else {
3591 		if (path->periph != NULL)
3592 			sbuf_printf(&sb, "(%s%d:", path->periph->periph_name,
3593 				    path->periph->unit_number);
3594 		else
3595 			sbuf_printf(&sb, "(noperiph:");
3596 
3597 		if (path->bus != NULL)
3598 			sbuf_printf(&sb, "%s%d:%d:", path->bus->sim->sim_name,
3599 				    path->bus->sim->unit_number,
3600 				    path->bus->sim->bus_id);
3601 		else
3602 			sbuf_printf(&sb, "nobus:");
3603 
3604 		if (path->target != NULL)
3605 			sbuf_printf(&sb, "%d:", path->target->target_id);
3606 		else
3607 			sbuf_printf(&sb, "X:");
3608 
3609 		if (path->device != NULL)
3610 			sbuf_printf(&sb, "%d): ", path->device->lun_id);
3611 		else
3612 			sbuf_printf(&sb, "X): ");
3613 	}
3614 	sbuf_finish(&sb);
3615 
3616 	return(sbuf_len(&sb));
3617 }
3618 
3619 path_id_t
3620 xpt_path_path_id(struct cam_path *path)
3621 {
3622 	return(path->bus->path_id);
3623 }
3624 
3625 target_id_t
3626 xpt_path_target_id(struct cam_path *path)
3627 {
3628 	if (path->target != NULL)
3629 		return (path->target->target_id);
3630 	else
3631 		return (CAM_TARGET_WILDCARD);
3632 }
3633 
3634 lun_id_t
3635 xpt_path_lun_id(struct cam_path *path)
3636 {
3637 	if (path->device != NULL)
3638 		return (path->device->lun_id);
3639 	else
3640 		return (CAM_LUN_WILDCARD);
3641 }
3642 
3643 struct cam_sim *
3644 xpt_path_sim(struct cam_path *path)
3645 {
3646 
3647 	return (path->bus->sim);
3648 }
3649 
3650 struct cam_periph*
3651 xpt_path_periph(struct cam_path *path)
3652 {
3653 	mtx_assert(path->bus->sim->mtx, MA_OWNED);
3654 
3655 	return (path->periph);
3656 }
3657 
3658 int
3659 xpt_path_legacy_ata_id(struct cam_path *path)
3660 {
3661 	struct cam_eb *bus;
3662 	int bus_id;
3663 
3664 	if ((strcmp(path->bus->sim->sim_name, "ata") != 0) &&
3665 	    strcmp(path->bus->sim->sim_name, "ahcich") != 0 &&
3666 	    strcmp(path->bus->sim->sim_name, "mvsch") != 0 &&
3667 	    strcmp(path->bus->sim->sim_name, "siisch") != 0)
3668 		return (-1);
3669 
3670 	if (strcmp(path->bus->sim->sim_name, "ata") == 0 &&
3671 	    path->bus->sim->unit_number < 2) {
3672 		bus_id = path->bus->sim->unit_number;
3673 	} else {
3674 		bus_id = 2;
3675 		xpt_lock_buses();
3676 		TAILQ_FOREACH(bus, &xsoftc.xpt_busses, links) {
3677 			if (bus == path->bus)
3678 				break;
3679 			if ((strcmp(bus->sim->sim_name, "ata") == 0 &&
3680 			     bus->sim->unit_number >= 2) ||
3681 			    strcmp(bus->sim->sim_name, "ahcich") == 0 ||
3682 			    strcmp(bus->sim->sim_name, "mvsch") == 0 ||
3683 			    strcmp(bus->sim->sim_name, "siisch") == 0)
3684 				bus_id++;
3685 		}
3686 		xpt_unlock_buses();
3687 	}
3688 	if (path->target != NULL) {
3689 		if (path->target->target_id < 2)
3690 			return (bus_id * 2 + path->target->target_id);
3691 		else
3692 			return (-1);
3693 	} else
3694 		return (bus_id * 2);
3695 }
3696 
3697 /*
3698  * Release a CAM control block for the caller.  Remit the cost of the structure
3699  * to the device referenced by the path.  If the this device had no 'credits'
3700  * and peripheral drivers have registered async callbacks for this notification
3701  * call them now.
3702  */
3703 void
3704 xpt_release_ccb(union ccb *free_ccb)
3705 {
3706 	struct	 cam_path *path;
3707 	struct	 cam_ed *device;
3708 	struct	 cam_eb *bus;
3709 	struct   cam_sim *sim;
3710 
3711 	CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_release_ccb\n"));
3712 	path = free_ccb->ccb_h.path;
3713 	device = path->device;
3714 	bus = path->bus;
3715 	sim = bus->sim;
3716 
3717 	mtx_assert(sim->mtx, MA_OWNED);
3718 
3719 	cam_ccbq_release_opening(&device->ccbq);
3720 	if (device->flags & CAM_DEV_RESIZE_QUEUE_NEEDED) {
3721 		device->flags &= ~CAM_DEV_RESIZE_QUEUE_NEEDED;
3722 		cam_ccbq_resize(&device->ccbq,
3723 		    device->ccbq.dev_openings + device->ccbq.dev_active);
3724 	}
3725 	if (sim->ccb_count > sim->max_ccbs) {
3726 		xpt_free_ccb(free_ccb);
3727 		sim->ccb_count--;
3728 	} else {
3729 		SLIST_INSERT_HEAD(&sim->ccb_freeq, &free_ccb->ccb_h,
3730 		    xpt_links.sle);
3731 	}
3732 	xpt_run_dev_allocq(device);
3733 }
3734 
3735 /* Functions accessed by SIM drivers */
3736 
3737 static struct xpt_xport xport_default = {
3738 	.alloc_device = xpt_alloc_device_default,
3739 	.action = xpt_action_default,
3740 	.async = xpt_dev_async_default,
3741 };
3742 
3743 /*
3744  * A sim structure, listing the SIM entry points and instance
3745  * identification info is passed to xpt_bus_register to hook the SIM
3746  * into the CAM framework.  xpt_bus_register creates a cam_eb entry
3747  * for this new bus and places it in the array of busses and assigns
3748  * it a path_id.  The path_id may be influenced by "hard wiring"
3749  * information specified by the user.  Once interrupt services are
3750  * available, the bus will be probed.
3751  */
3752 int32_t
3753 xpt_bus_register(struct cam_sim *sim, device_t parent, u_int32_t bus)
3754 {
3755 	struct cam_eb *new_bus;
3756 	struct cam_eb *old_bus;
3757 	struct ccb_pathinq cpi;
3758 	struct cam_path *path;
3759 	cam_status status;
3760 
3761 	mtx_assert(sim->mtx, MA_OWNED);
3762 
3763 	sim->bus_id = bus;
3764 	new_bus = (struct cam_eb *)malloc(sizeof(*new_bus),
3765 					  M_CAMXPT, M_NOWAIT);
3766 	if (new_bus == NULL) {
3767 		/* Couldn't satisfy request */
3768 		return (CAM_RESRC_UNAVAIL);
3769 	}
3770 	if (strcmp(sim->sim_name, "xpt") != 0) {
3771 		sim->path_id =
3772 		    xptpathid(sim->sim_name, sim->unit_number, sim->bus_id);
3773 	}
3774 
3775 	TAILQ_INIT(&new_bus->et_entries);
3776 	new_bus->path_id = sim->path_id;
3777 	cam_sim_hold(sim);
3778 	new_bus->sim = sim;
3779 	timevalclear(&new_bus->last_reset);
3780 	new_bus->flags = 0;
3781 	new_bus->refcount = 1;	/* Held until a bus_deregister event */
3782 	new_bus->generation = 0;
3783 
3784 	xpt_lock_buses();
3785 	old_bus = TAILQ_FIRST(&xsoftc.xpt_busses);
3786 	while (old_bus != NULL
3787 	    && old_bus->path_id < new_bus->path_id)
3788 		old_bus = TAILQ_NEXT(old_bus, links);
3789 	if (old_bus != NULL)
3790 		TAILQ_INSERT_BEFORE(old_bus, new_bus, links);
3791 	else
3792 		TAILQ_INSERT_TAIL(&xsoftc.xpt_busses, new_bus, links);
3793 	xsoftc.bus_generation++;
3794 	xpt_unlock_buses();
3795 
3796 	/*
3797 	 * Set a default transport so that a PATH_INQ can be issued to
3798 	 * the SIM.  This will then allow for probing and attaching of
3799 	 * a more appropriate transport.
3800 	 */
3801 	new_bus->xport = &xport_default;
3802 
3803 	status = xpt_create_path(&path, /*periph*/NULL, sim->path_id,
3804 				  CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
3805 	if (status != CAM_REQ_CMP) {
3806 		xpt_release_bus(new_bus);
3807 		free(path, M_CAMXPT);
3808 		return (CAM_RESRC_UNAVAIL);
3809 	}
3810 
3811 	xpt_setup_ccb(&cpi.ccb_h, path, CAM_PRIORITY_NORMAL);
3812 	cpi.ccb_h.func_code = XPT_PATH_INQ;
3813 	xpt_action((union ccb *)&cpi);
3814 
3815 	if (cpi.ccb_h.status == CAM_REQ_CMP) {
3816 		switch (cpi.transport) {
3817 		case XPORT_SPI:
3818 		case XPORT_SAS:
3819 		case XPORT_FC:
3820 		case XPORT_USB:
3821 		case XPORT_ISCSI:
3822 		case XPORT_PPB:
3823 			new_bus->xport = scsi_get_xport();
3824 			break;
3825 		case XPORT_ATA:
3826 		case XPORT_SATA:
3827 			new_bus->xport = ata_get_xport();
3828 			break;
3829 		default:
3830 			new_bus->xport = &xport_default;
3831 			break;
3832 		}
3833 	}
3834 
3835 	/* Notify interested parties */
3836 	if (sim->path_id != CAM_XPT_PATH_ID) {
3837 		union	ccb *scan_ccb;
3838 
3839 		xpt_async(AC_PATH_REGISTERED, path, &cpi);
3840 		/* Initiate bus rescan. */
3841 		scan_ccb = xpt_alloc_ccb_nowait();
3842 		scan_ccb->ccb_h.path = path;
3843 		scan_ccb->ccb_h.func_code = XPT_SCAN_BUS;
3844 		scan_ccb->crcn.flags = 0;
3845 		xpt_rescan(scan_ccb);
3846 	} else
3847 		xpt_free_path(path);
3848 	return (CAM_SUCCESS);
3849 }
3850 
3851 int32_t
3852 xpt_bus_deregister(path_id_t pathid)
3853 {
3854 	struct cam_path bus_path;
3855 	cam_status status;
3856 
3857 	status = xpt_compile_path(&bus_path, NULL, pathid,
3858 				  CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
3859 	if (status != CAM_REQ_CMP)
3860 		return (status);
3861 
3862 	xpt_async(AC_LOST_DEVICE, &bus_path, NULL);
3863 	xpt_async(AC_PATH_DEREGISTERED, &bus_path, NULL);
3864 
3865 	/* Release the reference count held while registered. */
3866 	xpt_release_bus(bus_path.bus);
3867 	xpt_release_path(&bus_path);
3868 
3869 	return (CAM_REQ_CMP);
3870 }
3871 
3872 static path_id_t
3873 xptnextfreepathid(void)
3874 {
3875 	struct cam_eb *bus;
3876 	path_id_t pathid;
3877 	const char *strval;
3878 
3879 	pathid = 0;
3880 	xpt_lock_buses();
3881 	bus = TAILQ_FIRST(&xsoftc.xpt_busses);
3882 retry:
3883 	/* Find an unoccupied pathid */
3884 	while (bus != NULL && bus->path_id <= pathid) {
3885 		if (bus->path_id == pathid)
3886 			pathid++;
3887 		bus = TAILQ_NEXT(bus, links);
3888 	}
3889 	xpt_unlock_buses();
3890 
3891 	/*
3892 	 * Ensure that this pathid is not reserved for
3893 	 * a bus that may be registered in the future.
3894 	 */
3895 	if (resource_string_value("scbus", pathid, "at", &strval) == 0) {
3896 		++pathid;
3897 		/* Start the search over */
3898 		xpt_lock_buses();
3899 		goto retry;
3900 	}
3901 	return (pathid);
3902 }
3903 
3904 static path_id_t
3905 xptpathid(const char *sim_name, int sim_unit, int sim_bus)
3906 {
3907 	path_id_t pathid;
3908 	int i, dunit, val;
3909 	char buf[32];
3910 	const char *dname;
3911 
3912 	pathid = CAM_XPT_PATH_ID;
3913 	snprintf(buf, sizeof(buf), "%s%d", sim_name, sim_unit);
3914 	i = 0;
3915 	while ((resource_find_match(&i, &dname, &dunit, "at", buf)) == 0) {
3916 		if (strcmp(dname, "scbus")) {
3917 			/* Avoid a bit of foot shooting. */
3918 			continue;
3919 		}
3920 		if (dunit < 0)		/* unwired?! */
3921 			continue;
3922 		if (resource_int_value("scbus", dunit, "bus", &val) == 0) {
3923 			if (sim_bus == val) {
3924 				pathid = dunit;
3925 				break;
3926 			}
3927 		} else if (sim_bus == 0) {
3928 			/* Unspecified matches bus 0 */
3929 			pathid = dunit;
3930 			break;
3931 		} else {
3932 			printf("Ambiguous scbus configuration for %s%d "
3933 			       "bus %d, cannot wire down.  The kernel "
3934 			       "config entry for scbus%d should "
3935 			       "specify a controller bus.\n"
3936 			       "Scbus will be assigned dynamically.\n",
3937 			       sim_name, sim_unit, sim_bus, dunit);
3938 			break;
3939 		}
3940 	}
3941 
3942 	if (pathid == CAM_XPT_PATH_ID)
3943 		pathid = xptnextfreepathid();
3944 	return (pathid);
3945 }
3946 
3947 static const char *
3948 xpt_async_string(u_int32_t async_code)
3949 {
3950 
3951 	switch (async_code) {
3952 	case AC_BUS_RESET: return ("AC_BUS_RESET");
3953 	case AC_UNSOL_RESEL: return ("AC_UNSOL_RESEL");
3954 	case AC_SCSI_AEN: return ("AC_SCSI_AEN");
3955 	case AC_SENT_BDR: return ("AC_SENT_BDR");
3956 	case AC_PATH_REGISTERED: return ("AC_PATH_REGISTERED");
3957 	case AC_PATH_DEREGISTERED: return ("AC_PATH_DEREGISTERED");
3958 	case AC_FOUND_DEVICE: return ("AC_FOUND_DEVICE");
3959 	case AC_LOST_DEVICE: return ("AC_LOST_DEVICE");
3960 	case AC_TRANSFER_NEG: return ("AC_TRANSFER_NEG");
3961 	case AC_INQ_CHANGED: return ("AC_INQ_CHANGED");
3962 	case AC_GETDEV_CHANGED: return ("AC_GETDEV_CHANGED");
3963 	case AC_CONTRACT: return ("AC_CONTRACT");
3964 	case AC_ADVINFO_CHANGED: return ("AC_ADVINFO_CHANGED");
3965 	case AC_UNIT_ATTENTION: return ("AC_UNIT_ATTENTION");
3966 	}
3967 	return ("AC_UNKNOWN");
3968 }
3969 
3970 void
3971 xpt_async(u_int32_t async_code, struct cam_path *path, void *async_arg)
3972 {
3973 	struct cam_eb *bus;
3974 	struct cam_et *target, *next_target;
3975 	struct cam_ed *device, *next_device;
3976 
3977 	mtx_assert(path->bus->sim->mtx, MA_OWNED);
3978 	CAM_DEBUG(path, CAM_DEBUG_TRACE | CAM_DEBUG_INFO,
3979 	    ("xpt_async(%s)\n", xpt_async_string(async_code)));
3980 
3981 	/*
3982 	 * Most async events come from a CAM interrupt context.  In
3983 	 * a few cases, the error recovery code at the peripheral layer,
3984 	 * which may run from our SWI or a process context, may signal
3985 	 * deferred events with a call to xpt_async.
3986 	 */
3987 
3988 	bus = path->bus;
3989 
3990 	if (async_code == AC_BUS_RESET) {
3991 		/* Update our notion of when the last reset occurred */
3992 		microtime(&bus->last_reset);
3993 	}
3994 
3995 	for (target = TAILQ_FIRST(&bus->et_entries);
3996 	     target != NULL;
3997 	     target = next_target) {
3998 
3999 		next_target = TAILQ_NEXT(target, links);
4000 
4001 		if (path->target != target
4002 		 && path->target->target_id != CAM_TARGET_WILDCARD
4003 		 && target->target_id != CAM_TARGET_WILDCARD)
4004 			continue;
4005 
4006 		if (async_code == AC_SENT_BDR) {
4007 			/* Update our notion of when the last reset occurred */
4008 			microtime(&path->target->last_reset);
4009 		}
4010 
4011 		for (device = TAILQ_FIRST(&target->ed_entries);
4012 		     device != NULL;
4013 		     device = next_device) {
4014 
4015 			next_device = TAILQ_NEXT(device, links);
4016 
4017 			if (path->device != device
4018 			 && path->device->lun_id != CAM_LUN_WILDCARD
4019 			 && device->lun_id != CAM_LUN_WILDCARD)
4020 				continue;
4021 			/*
4022 			 * The async callback could free the device.
4023 			 * If it is a broadcast async, it doesn't hold
4024 			 * device reference, so take our own reference.
4025 			 */
4026 			xpt_acquire_device(device);
4027 			(*(bus->xport->async))(async_code, bus,
4028 					       target, device,
4029 					       async_arg);
4030 
4031 			xpt_async_bcast(&device->asyncs, async_code,
4032 					path, async_arg);
4033 			xpt_release_device(device);
4034 		}
4035 	}
4036 
4037 	/*
4038 	 * If this wasn't a fully wildcarded async, tell all
4039 	 * clients that want all async events.
4040 	 */
4041 	if (bus != xpt_periph->path->bus)
4042 		xpt_async_bcast(&xpt_periph->path->device->asyncs, async_code,
4043 				path, async_arg);
4044 }
4045 
4046 static void
4047 xpt_async_bcast(struct async_list *async_head,
4048 		u_int32_t async_code,
4049 		struct cam_path *path, void *async_arg)
4050 {
4051 	struct async_node *cur_entry;
4052 
4053 	cur_entry = SLIST_FIRST(async_head);
4054 	while (cur_entry != NULL) {
4055 		struct async_node *next_entry;
4056 		/*
4057 		 * Grab the next list entry before we call the current
4058 		 * entry's callback.  This is because the callback function
4059 		 * can delete its async callback entry.
4060 		 */
4061 		next_entry = SLIST_NEXT(cur_entry, links);
4062 		if ((cur_entry->event_enable & async_code) != 0)
4063 			cur_entry->callback(cur_entry->callback_arg,
4064 					    async_code, path,
4065 					    async_arg);
4066 		cur_entry = next_entry;
4067 	}
4068 }
4069 
4070 static void
4071 xpt_dev_async_default(u_int32_t async_code, struct cam_eb *bus,
4072 		      struct cam_et *target, struct cam_ed *device,
4073 		      void *async_arg)
4074 {
4075 	printf("%s called\n", __func__);
4076 }
4077 
4078 u_int32_t
4079 xpt_freeze_devq(struct cam_path *path, u_int count)
4080 {
4081 	struct cam_ed *dev = path->device;
4082 
4083 	mtx_assert(path->bus->sim->mtx, MA_OWNED);
4084 	dev->ccbq.queue.qfrozen_cnt += count;
4085 	/* Remove frozen device from sendq. */
4086 	if (device_is_queued(dev)) {
4087 		camq_remove(&dev->sim->devq->send_queue,
4088 		    dev->devq_entry.pinfo.index);
4089 	}
4090 	return (dev->ccbq.queue.qfrozen_cnt);
4091 }
4092 
4093 u_int32_t
4094 xpt_freeze_simq(struct cam_sim *sim, u_int count)
4095 {
4096 
4097 	mtx_assert(sim->mtx, MA_OWNED);
4098 	sim->devq->send_queue.qfrozen_cnt += count;
4099 	return (sim->devq->send_queue.qfrozen_cnt);
4100 }
4101 
4102 static void
4103 xpt_release_devq_timeout(void *arg)
4104 {
4105 	struct cam_ed *device;
4106 
4107 	device = (struct cam_ed *)arg;
4108 	xpt_release_devq_device(device, /*count*/1, /*run_queue*/TRUE);
4109 }
4110 
4111 void
4112 xpt_release_devq(struct cam_path *path, u_int count, int run_queue)
4113 {
4114 
4115 	mtx_assert(path->bus->sim->mtx, MA_OWNED);
4116 	xpt_release_devq_device(path->device, count, run_queue);
4117 }
4118 
4119 void
4120 xpt_release_devq_device(struct cam_ed *dev, u_int count, int run_queue)
4121 {
4122 
4123 	if (count > dev->ccbq.queue.qfrozen_cnt) {
4124 #ifdef INVARIANTS
4125 		printf("xpt_release_devq(): requested %u > present %u\n",
4126 		    count, dev->ccbq.queue.qfrozen_cnt);
4127 #endif
4128 		count = dev->ccbq.queue.qfrozen_cnt;
4129 	}
4130 	dev->ccbq.queue.qfrozen_cnt -= count;
4131 	if (dev->ccbq.queue.qfrozen_cnt == 0) {
4132 		/*
4133 		 * No longer need to wait for a successful
4134 		 * command completion.
4135 		 */
4136 		dev->flags &= ~CAM_DEV_REL_ON_COMPLETE;
4137 		/*
4138 		 * Remove any timeouts that might be scheduled
4139 		 * to release this queue.
4140 		 */
4141 		if ((dev->flags & CAM_DEV_REL_TIMEOUT_PENDING) != 0) {
4142 			callout_stop(&dev->callout);
4143 			dev->flags &= ~CAM_DEV_REL_TIMEOUT_PENDING;
4144 		}
4145 		xpt_run_dev_allocq(dev);
4146 		if (run_queue == 0)
4147 			return;
4148 		/*
4149 		 * Now that we are unfrozen schedule the
4150 		 * device so any pending transactions are
4151 		 * run.
4152 		 */
4153 		if (xpt_schedule_devq(dev->sim->devq, dev))
4154 			xpt_run_devq(dev->sim->devq);
4155 	}
4156 }
4157 
4158 void
4159 xpt_release_simq(struct cam_sim *sim, int run_queue)
4160 {
4161 	struct	camq *sendq;
4162 
4163 	mtx_assert(sim->mtx, MA_OWNED);
4164 	sendq = &(sim->devq->send_queue);
4165 	if (sendq->qfrozen_cnt <= 0) {
4166 #ifdef INVARIANTS
4167 		printf("xpt_release_simq: requested 1 > present %u\n",
4168 		    sendq->qfrozen_cnt);
4169 #endif
4170 	} else
4171 		sendq->qfrozen_cnt--;
4172 	if (sendq->qfrozen_cnt == 0) {
4173 		/*
4174 		 * If there is a timeout scheduled to release this
4175 		 * sim queue, remove it.  The queue frozen count is
4176 		 * already at 0.
4177 		 */
4178 		if ((sim->flags & CAM_SIM_REL_TIMEOUT_PENDING) != 0){
4179 			callout_stop(&sim->callout);
4180 			sim->flags &= ~CAM_SIM_REL_TIMEOUT_PENDING;
4181 		}
4182 		if (run_queue) {
4183 			/*
4184 			 * Now that we are unfrozen run the send queue.
4185 			 */
4186 			xpt_run_devq(sim->devq);
4187 		}
4188 	}
4189 }
4190 
4191 /*
4192  * XXX Appears to be unused.
4193  */
4194 static void
4195 xpt_release_simq_timeout(void *arg)
4196 {
4197 	struct cam_sim *sim;
4198 
4199 	sim = (struct cam_sim *)arg;
4200 	xpt_release_simq(sim, /* run_queue */ TRUE);
4201 }
4202 
4203 void
4204 xpt_done(union ccb *done_ccb)
4205 {
4206 	struct cam_sim *sim;
4207 	int	first;
4208 
4209 	CAM_DEBUG(done_ccb->ccb_h.path, CAM_DEBUG_TRACE, ("xpt_done\n"));
4210 	if ((done_ccb->ccb_h.func_code & XPT_FC_QUEUED) != 0) {
4211 		/*
4212 		 * Queue up the request for handling by our SWI handler
4213 		 * any of the "non-immediate" type of ccbs.
4214 		 */
4215 		sim = done_ccb->ccb_h.path->bus->sim;
4216 		TAILQ_INSERT_TAIL(&sim->sim_doneq, &done_ccb->ccb_h,
4217 		    sim_links.tqe);
4218 		done_ccb->ccb_h.pinfo.index = CAM_DONEQ_INDEX;
4219 		if ((sim->flags & (CAM_SIM_ON_DONEQ | CAM_SIM_POLLED |
4220 		    CAM_SIM_BATCH)) == 0) {
4221 			mtx_lock(&cam_simq_lock);
4222 			first = TAILQ_EMPTY(&cam_simq);
4223 			TAILQ_INSERT_TAIL(&cam_simq, sim, links);
4224 			mtx_unlock(&cam_simq_lock);
4225 			sim->flags |= CAM_SIM_ON_DONEQ;
4226 			if (first)
4227 				swi_sched(cambio_ih, 0);
4228 		}
4229 	}
4230 }
4231 
4232 void
4233 xpt_batch_start(struct cam_sim *sim)
4234 {
4235 
4236 	KASSERT((sim->flags & CAM_SIM_BATCH) == 0, ("Batch flag already set"));
4237 	sim->flags |= CAM_SIM_BATCH;
4238 }
4239 
4240 void
4241 xpt_batch_done(struct cam_sim *sim)
4242 {
4243 
4244 	KASSERT((sim->flags & CAM_SIM_BATCH) != 0, ("Batch flag was not set"));
4245 	sim->flags &= ~CAM_SIM_BATCH;
4246 	if (!TAILQ_EMPTY(&sim->sim_doneq) &&
4247 	    (sim->flags & CAM_SIM_ON_DONEQ) == 0)
4248 		camisr_runqueue(&sim->sim_doneq);
4249 }
4250 
4251 union ccb *
4252 xpt_alloc_ccb()
4253 {
4254 	union ccb *new_ccb;
4255 
4256 	new_ccb = malloc(sizeof(*new_ccb), M_CAMCCB, M_ZERO|M_WAITOK);
4257 	return (new_ccb);
4258 }
4259 
4260 union ccb *
4261 xpt_alloc_ccb_nowait()
4262 {
4263 	union ccb *new_ccb;
4264 
4265 	new_ccb = malloc(sizeof(*new_ccb), M_CAMCCB, M_ZERO|M_NOWAIT);
4266 	return (new_ccb);
4267 }
4268 
4269 void
4270 xpt_free_ccb(union ccb *free_ccb)
4271 {
4272 	free(free_ccb, M_CAMCCB);
4273 }
4274 
4275 
4276 
4277 /* Private XPT functions */
4278 
4279 /*
4280  * Get a CAM control block for the caller. Charge the structure to the device
4281  * referenced by the path.  If the this device has no 'credits' then the
4282  * device already has the maximum number of outstanding operations under way
4283  * and we return NULL. If we don't have sufficient resources to allocate more
4284  * ccbs, we also return NULL.
4285  */
4286 static union ccb *
4287 xpt_get_ccb(struct cam_ed *device)
4288 {
4289 	union ccb *new_ccb;
4290 	struct cam_sim *sim;
4291 
4292 	sim = device->sim;
4293 	if ((new_ccb = (union ccb *)SLIST_FIRST(&sim->ccb_freeq)) == NULL) {
4294 		new_ccb = xpt_alloc_ccb_nowait();
4295                 if (new_ccb == NULL) {
4296 			return (NULL);
4297 		}
4298 		if ((sim->flags & CAM_SIM_MPSAFE) == 0)
4299 			callout_handle_init(&new_ccb->ccb_h.timeout_ch);
4300 		SLIST_INSERT_HEAD(&sim->ccb_freeq, &new_ccb->ccb_h,
4301 				  xpt_links.sle);
4302 		sim->ccb_count++;
4303 	}
4304 	cam_ccbq_take_opening(&device->ccbq);
4305 	SLIST_REMOVE_HEAD(&sim->ccb_freeq, xpt_links.sle);
4306 	return (new_ccb);
4307 }
4308 
4309 static void
4310 xpt_release_bus(struct cam_eb *bus)
4311 {
4312 
4313 	xpt_lock_buses();
4314 	KASSERT(bus->refcount >= 1, ("bus->refcount >= 1"));
4315 	if (--bus->refcount > 0) {
4316 		xpt_unlock_buses();
4317 		return;
4318 	}
4319 	KASSERT(TAILQ_EMPTY(&bus->et_entries),
4320 	    ("refcount is zero, but target list is not empty"));
4321 	TAILQ_REMOVE(&xsoftc.xpt_busses, bus, links);
4322 	xsoftc.bus_generation++;
4323 	xpt_unlock_buses();
4324 	cam_sim_release(bus->sim);
4325 	free(bus, M_CAMXPT);
4326 }
4327 
4328 static struct cam_et *
4329 xpt_alloc_target(struct cam_eb *bus, target_id_t target_id)
4330 {
4331 	struct cam_et *cur_target, *target;
4332 
4333 	mtx_assert(bus->sim->mtx, MA_OWNED);
4334 	target = (struct cam_et *)malloc(sizeof(*target), M_CAMXPT,
4335 					 M_NOWAIT|M_ZERO);
4336 	if (target == NULL)
4337 		return (NULL);
4338 
4339 	TAILQ_INIT(&target->ed_entries);
4340 	target->bus = bus;
4341 	target->target_id = target_id;
4342 	target->refcount = 1;
4343 	target->generation = 0;
4344 	target->luns = NULL;
4345 	timevalclear(&target->last_reset);
4346 	/*
4347 	 * Hold a reference to our parent bus so it
4348 	 * will not go away before we do.
4349 	 */
4350 	xpt_lock_buses();
4351 	bus->refcount++;
4352 	xpt_unlock_buses();
4353 
4354 	/* Insertion sort into our bus's target list */
4355 	cur_target = TAILQ_FIRST(&bus->et_entries);
4356 	while (cur_target != NULL && cur_target->target_id < target_id)
4357 		cur_target = TAILQ_NEXT(cur_target, links);
4358 	if (cur_target != NULL) {
4359 		TAILQ_INSERT_BEFORE(cur_target, target, links);
4360 	} else {
4361 		TAILQ_INSERT_TAIL(&bus->et_entries, target, links);
4362 	}
4363 	bus->generation++;
4364 	return (target);
4365 }
4366 
4367 static void
4368 xpt_release_target(struct cam_et *target)
4369 {
4370 
4371 	mtx_assert(target->bus->sim->mtx, MA_OWNED);
4372 	if (--target->refcount > 0)
4373 		return;
4374 	KASSERT(TAILQ_EMPTY(&target->ed_entries),
4375 	    ("refcount is zero, but device list is not empty"));
4376 	TAILQ_REMOVE(&target->bus->et_entries, target, links);
4377 	target->bus->generation++;
4378 	xpt_release_bus(target->bus);
4379 	if (target->luns)
4380 		free(target->luns, M_CAMXPT);
4381 	free(target, M_CAMXPT);
4382 }
4383 
4384 static struct cam_ed *
4385 xpt_alloc_device_default(struct cam_eb *bus, struct cam_et *target,
4386 			 lun_id_t lun_id)
4387 {
4388 	struct cam_ed *device;
4389 
4390 	device = xpt_alloc_device(bus, target, lun_id);
4391 	if (device == NULL)
4392 		return (NULL);
4393 
4394 	device->mintags = 1;
4395 	device->maxtags = 1;
4396 	bus->sim->max_ccbs += device->ccbq.devq_openings;
4397 	return (device);
4398 }
4399 
4400 struct cam_ed *
4401 xpt_alloc_device(struct cam_eb *bus, struct cam_et *target, lun_id_t lun_id)
4402 {
4403 	struct cam_ed	*cur_device, *device;
4404 	struct cam_devq	*devq;
4405 	cam_status status;
4406 
4407 	mtx_assert(target->bus->sim->mtx, MA_OWNED);
4408 	/* Make space for us in the device queue on our bus */
4409 	devq = bus->sim->devq;
4410 	status = cam_devq_resize(devq, devq->send_queue.array_size + 1);
4411 	if (status != CAM_REQ_CMP)
4412 		return (NULL);
4413 
4414 	device = (struct cam_ed *)malloc(sizeof(*device),
4415 					 M_CAMDEV, M_NOWAIT|M_ZERO);
4416 	if (device == NULL)
4417 		return (NULL);
4418 
4419 	cam_init_pinfo(&device->devq_entry.pinfo);
4420 	device->devq_entry.device = device;
4421 	device->target = target;
4422 	device->lun_id = lun_id;
4423 	device->sim = bus->sim;
4424 	/* Initialize our queues */
4425 	if (camq_init(&device->drvq, 0) != 0) {
4426 		free(device, M_CAMDEV);
4427 		return (NULL);
4428 	}
4429 	if (cam_ccbq_init(&device->ccbq,
4430 			  bus->sim->max_dev_openings) != 0) {
4431 		camq_fini(&device->drvq);
4432 		free(device, M_CAMDEV);
4433 		return (NULL);
4434 	}
4435 	SLIST_INIT(&device->asyncs);
4436 	SLIST_INIT(&device->periphs);
4437 	device->generation = 0;
4438 	device->flags = CAM_DEV_UNCONFIGURED;
4439 	device->tag_delay_count = 0;
4440 	device->tag_saved_openings = 0;
4441 	device->refcount = 1;
4442 	callout_init_mtx(&device->callout, bus->sim->mtx, 0);
4443 
4444 	cur_device = TAILQ_FIRST(&target->ed_entries);
4445 	while (cur_device != NULL && cur_device->lun_id < lun_id)
4446 		cur_device = TAILQ_NEXT(cur_device, links);
4447 	if (cur_device != NULL)
4448 		TAILQ_INSERT_BEFORE(cur_device, device, links);
4449 	else
4450 		TAILQ_INSERT_TAIL(&target->ed_entries, device, links);
4451 	target->refcount++;
4452 	target->generation++;
4453 	return (device);
4454 }
4455 
4456 void
4457 xpt_acquire_device(struct cam_ed *device)
4458 {
4459 
4460 	mtx_assert(device->sim->mtx, MA_OWNED);
4461 	device->refcount++;
4462 }
4463 
4464 void
4465 xpt_release_device(struct cam_ed *device)
4466 {
4467 	struct cam_devq *devq;
4468 
4469 	mtx_assert(device->sim->mtx, MA_OWNED);
4470 	if (--device->refcount > 0)
4471 		return;
4472 
4473 	KASSERT(SLIST_EMPTY(&device->periphs),
4474 	    ("refcount is zero, but periphs list is not empty"));
4475 	if (device->devq_entry.pinfo.index != CAM_UNQUEUED_INDEX)
4476 		panic("Removing device while still queued for ccbs");
4477 
4478 	if ((device->flags & CAM_DEV_REL_TIMEOUT_PENDING) != 0)
4479 		callout_stop(&device->callout);
4480 
4481 	TAILQ_REMOVE(&device->target->ed_entries, device,links);
4482 	device->target->generation++;
4483 	device->target->bus->sim->max_ccbs -= device->ccbq.devq_openings;
4484 	/* Release our slot in the devq */
4485 	devq = device->target->bus->sim->devq;
4486 	cam_devq_resize(devq, devq->send_queue.array_size - 1);
4487 	camq_fini(&device->drvq);
4488 	cam_ccbq_fini(&device->ccbq);
4489 	/*
4490 	 * Free allocated memory.  free(9) does nothing if the
4491 	 * supplied pointer is NULL, so it is safe to call without
4492 	 * checking.
4493 	 */
4494 	free(device->supported_vpds, M_CAMXPT);
4495 	free(device->device_id, M_CAMXPT);
4496 	free(device->physpath, M_CAMXPT);
4497 	free(device->rcap_buf, M_CAMXPT);
4498 	free(device->serial_num, M_CAMXPT);
4499 
4500 	xpt_release_target(device->target);
4501 	free(device, M_CAMDEV);
4502 }
4503 
4504 u_int32_t
4505 xpt_dev_ccbq_resize(struct cam_path *path, int newopenings)
4506 {
4507 	int	diff;
4508 	int	result;
4509 	struct	cam_ed *dev;
4510 
4511 	dev = path->device;
4512 
4513 	diff = newopenings - (dev->ccbq.dev_active + dev->ccbq.dev_openings);
4514 	result = cam_ccbq_resize(&dev->ccbq, newopenings);
4515 	if (result == CAM_REQ_CMP && (diff < 0)) {
4516 		dev->flags |= CAM_DEV_RESIZE_QUEUE_NEEDED;
4517 	}
4518 	if ((dev->flags & CAM_DEV_TAG_AFTER_COUNT) != 0
4519 	 || (dev->inq_flags & SID_CmdQue) != 0)
4520 		dev->tag_saved_openings = newopenings;
4521 	/* Adjust the global limit */
4522 	dev->sim->max_ccbs += diff;
4523 	return (result);
4524 }
4525 
4526 static struct cam_eb *
4527 xpt_find_bus(path_id_t path_id)
4528 {
4529 	struct cam_eb *bus;
4530 
4531 	xpt_lock_buses();
4532 	for (bus = TAILQ_FIRST(&xsoftc.xpt_busses);
4533 	     bus != NULL;
4534 	     bus = TAILQ_NEXT(bus, links)) {
4535 		if (bus->path_id == path_id) {
4536 			bus->refcount++;
4537 			break;
4538 		}
4539 	}
4540 	xpt_unlock_buses();
4541 	return (bus);
4542 }
4543 
4544 static struct cam_et *
4545 xpt_find_target(struct cam_eb *bus, target_id_t	target_id)
4546 {
4547 	struct cam_et *target;
4548 
4549 	mtx_assert(bus->sim->mtx, MA_OWNED);
4550 	for (target = TAILQ_FIRST(&bus->et_entries);
4551 	     target != NULL;
4552 	     target = TAILQ_NEXT(target, links)) {
4553 		if (target->target_id == target_id) {
4554 			target->refcount++;
4555 			break;
4556 		}
4557 	}
4558 	return (target);
4559 }
4560 
4561 static struct cam_ed *
4562 xpt_find_device(struct cam_et *target, lun_id_t lun_id)
4563 {
4564 	struct cam_ed *device;
4565 
4566 	mtx_assert(target->bus->sim->mtx, MA_OWNED);
4567 	for (device = TAILQ_FIRST(&target->ed_entries);
4568 	     device != NULL;
4569 	     device = TAILQ_NEXT(device, links)) {
4570 		if (device->lun_id == lun_id) {
4571 			device->refcount++;
4572 			break;
4573 		}
4574 	}
4575 	return (device);
4576 }
4577 
4578 void
4579 xpt_start_tags(struct cam_path *path)
4580 {
4581 	struct ccb_relsim crs;
4582 	struct cam_ed *device;
4583 	struct cam_sim *sim;
4584 	int    newopenings;
4585 
4586 	device = path->device;
4587 	sim = path->bus->sim;
4588 	device->flags &= ~CAM_DEV_TAG_AFTER_COUNT;
4589 	xpt_freeze_devq(path, /*count*/1);
4590 	device->inq_flags |= SID_CmdQue;
4591 	if (device->tag_saved_openings != 0)
4592 		newopenings = device->tag_saved_openings;
4593 	else
4594 		newopenings = min(device->maxtags,
4595 				  sim->max_tagged_dev_openings);
4596 	xpt_dev_ccbq_resize(path, newopenings);
4597 	xpt_async(AC_GETDEV_CHANGED, path, NULL);
4598 	xpt_setup_ccb(&crs.ccb_h, path, CAM_PRIORITY_NORMAL);
4599 	crs.ccb_h.func_code = XPT_REL_SIMQ;
4600 	crs.release_flags = RELSIM_RELEASE_AFTER_QEMPTY;
4601 	crs.openings
4602 	    = crs.release_timeout
4603 	    = crs.qfrozen_cnt
4604 	    = 0;
4605 	xpt_action((union ccb *)&crs);
4606 }
4607 
4608 void
4609 xpt_stop_tags(struct cam_path *path)
4610 {
4611 	struct ccb_relsim crs;
4612 	struct cam_ed *device;
4613 	struct cam_sim *sim;
4614 
4615 	device = path->device;
4616 	sim = path->bus->sim;
4617 	device->flags &= ~CAM_DEV_TAG_AFTER_COUNT;
4618 	device->tag_delay_count = 0;
4619 	xpt_freeze_devq(path, /*count*/1);
4620 	device->inq_flags &= ~SID_CmdQue;
4621 	xpt_dev_ccbq_resize(path, sim->max_dev_openings);
4622 	xpt_async(AC_GETDEV_CHANGED, path, NULL);
4623 	xpt_setup_ccb(&crs.ccb_h, path, CAM_PRIORITY_NORMAL);
4624 	crs.ccb_h.func_code = XPT_REL_SIMQ;
4625 	crs.release_flags = RELSIM_RELEASE_AFTER_QEMPTY;
4626 	crs.openings
4627 	    = crs.release_timeout
4628 	    = crs.qfrozen_cnt
4629 	    = 0;
4630 	xpt_action((union ccb *)&crs);
4631 }
4632 
4633 static void
4634 xpt_boot_delay(void *arg)
4635 {
4636 
4637 	xpt_release_boot();
4638 }
4639 
4640 static void
4641 xpt_config(void *arg)
4642 {
4643 	/*
4644 	 * Now that interrupts are enabled, go find our devices
4645 	 */
4646 
4647 	/* Setup debugging path */
4648 	if (cam_dflags != CAM_DEBUG_NONE) {
4649 		if (xpt_create_path_unlocked(&cam_dpath, NULL,
4650 				    CAM_DEBUG_BUS, CAM_DEBUG_TARGET,
4651 				    CAM_DEBUG_LUN) != CAM_REQ_CMP) {
4652 			printf("xpt_config: xpt_create_path() failed for debug"
4653 			       " target %d:%d:%d, debugging disabled\n",
4654 			       CAM_DEBUG_BUS, CAM_DEBUG_TARGET, CAM_DEBUG_LUN);
4655 			cam_dflags = CAM_DEBUG_NONE;
4656 		}
4657 	} else
4658 		cam_dpath = NULL;
4659 
4660 	periphdriver_init(1);
4661 	xpt_hold_boot();
4662 	callout_init(&xsoftc.boot_callout, 1);
4663 	callout_reset(&xsoftc.boot_callout, hz * xsoftc.boot_delay / 1000,
4664 	    xpt_boot_delay, NULL);
4665 	/* Fire up rescan thread. */
4666 	if (kproc_create(xpt_scanner_thread, NULL, NULL, 0, 0, "xpt_thrd")) {
4667 		printf("xpt_config: failed to create rescan thread.\n");
4668 	}
4669 }
4670 
4671 void
4672 xpt_hold_boot(void)
4673 {
4674 	xpt_lock_buses();
4675 	xsoftc.buses_to_config++;
4676 	xpt_unlock_buses();
4677 }
4678 
4679 void
4680 xpt_release_boot(void)
4681 {
4682 	xpt_lock_buses();
4683 	xsoftc.buses_to_config--;
4684 	if (xsoftc.buses_to_config == 0 && xsoftc.buses_config_done == 0) {
4685 		struct	xpt_task *task;
4686 
4687 		xsoftc.buses_config_done = 1;
4688 		xpt_unlock_buses();
4689 		/* Call manually because we don't have any busses */
4690 		task = malloc(sizeof(struct xpt_task), M_CAMXPT, M_NOWAIT);
4691 		if (task != NULL) {
4692 			TASK_INIT(&task->task, 0, xpt_finishconfig_task, task);
4693 			taskqueue_enqueue(taskqueue_thread, &task->task);
4694 		}
4695 	} else
4696 		xpt_unlock_buses();
4697 }
4698 
4699 /*
4700  * If the given device only has one peripheral attached to it, and if that
4701  * peripheral is the passthrough driver, announce it.  This insures that the
4702  * user sees some sort of announcement for every peripheral in their system.
4703  */
4704 static int
4705 xptpassannouncefunc(struct cam_ed *device, void *arg)
4706 {
4707 	struct cam_periph *periph;
4708 	int i;
4709 
4710 	for (periph = SLIST_FIRST(&device->periphs), i = 0; periph != NULL;
4711 	     periph = SLIST_NEXT(periph, periph_links), i++);
4712 
4713 	periph = SLIST_FIRST(&device->periphs);
4714 	if ((i == 1)
4715 	 && (strncmp(periph->periph_name, "pass", 4) == 0))
4716 		xpt_announce_periph(periph, NULL);
4717 
4718 	return(1);
4719 }
4720 
4721 static void
4722 xpt_finishconfig_task(void *context, int pending)
4723 {
4724 
4725 	periphdriver_init(2);
4726 	/*
4727 	 * Check for devices with no "standard" peripheral driver
4728 	 * attached.  For any devices like that, announce the
4729 	 * passthrough driver so the user will see something.
4730 	 */
4731 	if (!bootverbose)
4732 		xpt_for_all_devices(xptpassannouncefunc, NULL);
4733 
4734 	/* Release our hook so that the boot can continue. */
4735 	config_intrhook_disestablish(xsoftc.xpt_config_hook);
4736 	free(xsoftc.xpt_config_hook, M_CAMXPT);
4737 	xsoftc.xpt_config_hook = NULL;
4738 
4739 	free(context, M_CAMXPT);
4740 }
4741 
4742 cam_status
4743 xpt_register_async(int event, ac_callback_t *cbfunc, void *cbarg,
4744 		   struct cam_path *path)
4745 {
4746 	struct ccb_setasync csa;
4747 	cam_status status;
4748 	int xptpath = 0;
4749 
4750 	if (path == NULL) {
4751 		mtx_lock(&xsoftc.xpt_lock);
4752 		status = xpt_create_path(&path, /*periph*/NULL, CAM_XPT_PATH_ID,
4753 					 CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
4754 		if (status != CAM_REQ_CMP) {
4755 			mtx_unlock(&xsoftc.xpt_lock);
4756 			return (status);
4757 		}
4758 		xptpath = 1;
4759 	}
4760 
4761 	xpt_setup_ccb(&csa.ccb_h, path, CAM_PRIORITY_NORMAL);
4762 	csa.ccb_h.func_code = XPT_SASYNC_CB;
4763 	csa.event_enable = event;
4764 	csa.callback = cbfunc;
4765 	csa.callback_arg = cbarg;
4766 	xpt_action((union ccb *)&csa);
4767 	status = csa.ccb_h.status;
4768 
4769 	if (xptpath) {
4770 		xpt_free_path(path);
4771 		mtx_unlock(&xsoftc.xpt_lock);
4772 	}
4773 
4774 	if ((status == CAM_REQ_CMP) &&
4775 	    (csa.event_enable & AC_FOUND_DEVICE)) {
4776 		/*
4777 		 * Get this peripheral up to date with all
4778 		 * the currently existing devices.
4779 		 */
4780 		xpt_for_all_devices(xptsetasyncfunc, &csa);
4781 	}
4782 	if ((status == CAM_REQ_CMP) &&
4783 	    (csa.event_enable & AC_PATH_REGISTERED)) {
4784 		/*
4785 		 * Get this peripheral up to date with all
4786 		 * the currently existing busses.
4787 		 */
4788 		xpt_for_all_busses(xptsetasyncbusfunc, &csa);
4789 	}
4790 
4791 	return (status);
4792 }
4793 
4794 static void
4795 xptaction(struct cam_sim *sim, union ccb *work_ccb)
4796 {
4797 	CAM_DEBUG(work_ccb->ccb_h.path, CAM_DEBUG_TRACE, ("xptaction\n"));
4798 
4799 	switch (work_ccb->ccb_h.func_code) {
4800 	/* Common cases first */
4801 	case XPT_PATH_INQ:		/* Path routing inquiry */
4802 	{
4803 		struct ccb_pathinq *cpi;
4804 
4805 		cpi = &work_ccb->cpi;
4806 		cpi->version_num = 1; /* XXX??? */
4807 		cpi->hba_inquiry = 0;
4808 		cpi->target_sprt = 0;
4809 		cpi->hba_misc = 0;
4810 		cpi->hba_eng_cnt = 0;
4811 		cpi->max_target = 0;
4812 		cpi->max_lun = 0;
4813 		cpi->initiator_id = 0;
4814 		strncpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
4815 		strncpy(cpi->hba_vid, "", HBA_IDLEN);
4816 		strncpy(cpi->dev_name, sim->sim_name, DEV_IDLEN);
4817 		cpi->unit_number = sim->unit_number;
4818 		cpi->bus_id = sim->bus_id;
4819 		cpi->base_transfer_speed = 0;
4820 		cpi->protocol = PROTO_UNSPECIFIED;
4821 		cpi->protocol_version = PROTO_VERSION_UNSPECIFIED;
4822 		cpi->transport = XPORT_UNSPECIFIED;
4823 		cpi->transport_version = XPORT_VERSION_UNSPECIFIED;
4824 		cpi->ccb_h.status = CAM_REQ_CMP;
4825 		xpt_done(work_ccb);
4826 		break;
4827 	}
4828 	default:
4829 		work_ccb->ccb_h.status = CAM_REQ_INVALID;
4830 		xpt_done(work_ccb);
4831 		break;
4832 	}
4833 }
4834 
4835 /*
4836  * The xpt as a "controller" has no interrupt sources, so polling
4837  * is a no-op.
4838  */
4839 static void
4840 xptpoll(struct cam_sim *sim)
4841 {
4842 }
4843 
4844 void
4845 xpt_lock_buses(void)
4846 {
4847 	mtx_lock(&xsoftc.xpt_topo_lock);
4848 }
4849 
4850 void
4851 xpt_unlock_buses(void)
4852 {
4853 	mtx_unlock(&xsoftc.xpt_topo_lock);
4854 }
4855 
4856 static void
4857 camisr(void *dummy)
4858 {
4859 	cam_simq_t queue;
4860 	struct cam_sim *sim;
4861 
4862 	mtx_lock(&cam_simq_lock);
4863 	TAILQ_INIT(&queue);
4864 	while (!TAILQ_EMPTY(&cam_simq)) {
4865 		TAILQ_CONCAT(&queue, &cam_simq, links);
4866 		mtx_unlock(&cam_simq_lock);
4867 
4868 		while ((sim = TAILQ_FIRST(&queue)) != NULL) {
4869 			TAILQ_REMOVE(&queue, sim, links);
4870 			CAM_SIM_LOCK(sim);
4871 			camisr_runqueue(&sim->sim_doneq);
4872 			sim->flags &= ~CAM_SIM_ON_DONEQ;
4873 			CAM_SIM_UNLOCK(sim);
4874 		}
4875 		mtx_lock(&cam_simq_lock);
4876 	}
4877 	mtx_unlock(&cam_simq_lock);
4878 }
4879 
4880 static void
4881 camisr_runqueue(void *V_queue)
4882 {
4883 	cam_isrq_t *queue = V_queue;
4884 	struct	ccb_hdr *ccb_h;
4885 
4886 	while ((ccb_h = TAILQ_FIRST(queue)) != NULL) {
4887 		int	runq;
4888 
4889 		TAILQ_REMOVE(queue, ccb_h, sim_links.tqe);
4890 		ccb_h->pinfo.index = CAM_UNQUEUED_INDEX;
4891 
4892 		CAM_DEBUG(ccb_h->path, CAM_DEBUG_TRACE,
4893 			  ("camisr\n"));
4894 
4895 		runq = FALSE;
4896 
4897 		if (ccb_h->flags & CAM_HIGH_POWER) {
4898 			struct highpowerlist	*hphead;
4899 			union ccb		*send_ccb;
4900 
4901 			mtx_lock(&xsoftc.xpt_lock);
4902 			hphead = &xsoftc.highpowerq;
4903 
4904 			send_ccb = (union ccb *)STAILQ_FIRST(hphead);
4905 
4906 			/*
4907 			 * Increment the count since this command is done.
4908 			 */
4909 			xsoftc.num_highpower++;
4910 
4911 			/*
4912 			 * Any high powered commands queued up?
4913 			 */
4914 			if (send_ccb != NULL) {
4915 
4916 				STAILQ_REMOVE_HEAD(hphead, xpt_links.stqe);
4917 				mtx_unlock(&xsoftc.xpt_lock);
4918 
4919 				xpt_release_devq(send_ccb->ccb_h.path,
4920 						 /*count*/1, /*runqueue*/TRUE);
4921 			} else
4922 				mtx_unlock(&xsoftc.xpt_lock);
4923 		}
4924 
4925 		if ((ccb_h->func_code & XPT_FC_USER_CCB) == 0) {
4926 			struct cam_ed *dev;
4927 
4928 			dev = ccb_h->path->device;
4929 
4930 			cam_ccbq_ccb_done(&dev->ccbq, (union ccb *)ccb_h);
4931 			ccb_h->path->bus->sim->devq->send_active--;
4932 			ccb_h->path->bus->sim->devq->send_openings++;
4933 			runq = TRUE;
4934 
4935 			if (((dev->flags & CAM_DEV_REL_ON_QUEUE_EMPTY) != 0
4936 			  && (dev->ccbq.dev_active == 0))) {
4937 				dev->flags &= ~CAM_DEV_REL_ON_QUEUE_EMPTY;
4938 				xpt_release_devq(ccb_h->path, /*count*/1,
4939 						 /*run_queue*/FALSE);
4940 			}
4941 
4942 			if (((dev->flags & CAM_DEV_REL_ON_COMPLETE) != 0
4943 			  && (ccb_h->status&CAM_STATUS_MASK) != CAM_REQUEUE_REQ)) {
4944 				dev->flags &= ~CAM_DEV_REL_ON_COMPLETE;
4945 				xpt_release_devq(ccb_h->path, /*count*/1,
4946 						 /*run_queue*/FALSE);
4947 			}
4948 
4949 			if ((dev->flags & CAM_DEV_TAG_AFTER_COUNT) != 0
4950 			 && (--dev->tag_delay_count == 0))
4951 				xpt_start_tags(ccb_h->path);
4952 			if (!device_is_queued(dev)) {
4953 				(void)xpt_schedule_devq(
4954 				    ccb_h->path->bus->sim->devq, dev);
4955 			}
4956 		}
4957 
4958 		if (ccb_h->status & CAM_RELEASE_SIMQ) {
4959 			xpt_release_simq(ccb_h->path->bus->sim,
4960 					 /*run_queue*/TRUE);
4961 			ccb_h->status &= ~CAM_RELEASE_SIMQ;
4962 			runq = FALSE;
4963 		}
4964 
4965 		if ((ccb_h->flags & CAM_DEV_QFRZDIS)
4966 		 && (ccb_h->status & CAM_DEV_QFRZN)) {
4967 			xpt_release_devq(ccb_h->path, /*count*/1,
4968 					 /*run_queue*/TRUE);
4969 			ccb_h->status &= ~CAM_DEV_QFRZN;
4970 		} else if (runq) {
4971 			xpt_run_devq(ccb_h->path->bus->sim->devq);
4972 		}
4973 
4974 		/* Call the peripheral driver's callback */
4975 		(*ccb_h->cbfcnp)(ccb_h->path->periph, (union ccb *)ccb_h);
4976 	}
4977 }
4978