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