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