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