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