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