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