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