subr_bus.c revision 105166
1/*-
2 * Copyright (c) 1997,1998 Doug Rabson
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 *
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24 * SUCH DAMAGE.
25 *
26 * $FreeBSD: head/sys/kern/subr_bus.c 105166 2002-10-15 18:56:13Z phk $
27 */
28
29#include "opt_bus.h"
30
31#include <sys/param.h>
32#include <sys/conf.h>
33#include <sys/filio.h>
34#include <sys/lock.h>
35#include <sys/kernel.h>
36#include <sys/kobj.h>
37#include <sys/malloc.h>
38#include <sys/module.h>
39#include <sys/mutex.h>
40#include <sys/poll.h>
41#include <sys/proc.h>
42#include <sys/condvar.h>
43#include <sys/queue.h>
44#include <machine/bus.h>
45#include <sys/rman.h>
46#include <sys/selinfo.h>
47#include <sys/signalvar.h>
48#include <sys/sysctl.h>
49#include <sys/systm.h>
50#include <sys/uio.h>
51#include <sys/bus.h>
52
53#include <machine/stdarg.h>
54
55#include <vm/uma.h>
56
57/*
58 * Used to attach drivers to devclasses.
59 */
60typedef struct driverlink *driverlink_t;
61struct driverlink {
62    driver_t	*driver;
63    TAILQ_ENTRY(driverlink) link;	/* list of drivers in devclass */
64};
65
66/*
67 * Forward declarations
68 */
69typedef TAILQ_HEAD(devclass_list, devclass) devclass_list_t;
70typedef TAILQ_HEAD(driver_list, driverlink) driver_list_t;
71typedef TAILQ_HEAD(device_list, device) device_list_t;
72
73struct devclass {
74	TAILQ_ENTRY(devclass) link;
75	driver_list_t	drivers;     /* bus devclasses store drivers for bus */
76	char		*name;
77	device_t	*devices;	/* array of devices indexed by unit */
78	int		maxunit;	/* size of devices array */
79};
80
81/*
82 * Implementation of device.
83 */
84struct device {
85	/*
86	 * A device is a kernel object. The first field must be the
87	 * current ops table for the object.
88	 */
89	KOBJ_FIELDS;
90
91	/*
92	 * Device hierarchy.
93	 */
94	TAILQ_ENTRY(device)	link;		/* list of devices in parent */
95	TAILQ_ENTRY(device)	devlink;	/* global device list membership */
96	device_t	parent;
97	device_list_t	children;	/* list of subordinate devices */
98
99	/*
100	 * Details of this device.
101	 */
102	driver_t	*driver;
103	devclass_t	devclass;	/* device class which we are in */
104	int		unit;
105	char*		nameunit;	/* name+unit e.g. foodev0 */
106	char*		desc;		/* driver specific description */
107	int		busy;		/* count of calls to device_busy() */
108	device_state_t	state;
109	u_int32_t	devflags;  /* api level flags for device_get_flags() */
110	u_short		flags;
111#define	DF_ENABLED	1	/* device should be probed/attached */
112#define	DF_FIXEDCLASS	2	/* devclass specified at create time */
113#define	DF_WILDCARD	4	/* unit was originally wildcard */
114#define	DF_DESCMALLOCED	8	/* description was malloced */
115#define	DF_QUIET	16	/* don't print verbose attach message */
116#define	DF_DONENOMATCH	32	/* don't execute DEVICE_NOMATCH again */
117#define	DF_EXTERNALSOFTC 64	/* softc not allocated by us */
118	u_char	order;		/* order from device_add_child_ordered() */
119	u_char	pad;
120	void	*ivars;
121	void	*softc;
122};
123
124struct device_op_desc {
125	unsigned int	offset;	/* offset in driver ops */
126	struct method*	method;	/* internal method implementation */
127	devop_t		deflt;	/* default implementation */
128	const char*	name;	/* unique name (for registration) */
129};
130
131static MALLOC_DEFINE(M_BUS, "bus", "Bus data structures");
132
133#ifdef BUS_DEBUG
134
135static int bus_debug = 1;
136TUNABLE_INT("bus.debug", &bus_debug);
137SYSCTL_INT(_debug, OID_AUTO, bus_debug, CTLFLAG_RW, &bus_debug, 0,
138    "Debug bus code");
139
140#define PDEBUG(a)	if (bus_debug) {printf("%s:%d: ", __func__, __LINE__), printf a; printf("\n");}
141#define DEVICENAME(d)	((d)? device_get_name(d): "no device")
142#define DRIVERNAME(d)	((d)? d->name : "no driver")
143#define DEVCLANAME(d)	((d)? d->name : "no devclass")
144
145/* Produce the indenting, indent*2 spaces plus a '.' ahead of that to
146 * prevent syslog from deleting initial spaces
147 */
148#define indentprintf(p)	do { int iJ; printf("."); for (iJ=0; iJ<indent; iJ++) printf("  "); printf p ; } while (0)
149
150static void print_device_short(device_t dev, int indent);
151static void print_device(device_t dev, int indent);
152void print_device_tree_short(device_t dev, int indent);
153void print_device_tree(device_t dev, int indent);
154static void print_driver_short(driver_t *driver, int indent);
155static void print_driver(driver_t *driver, int indent);
156static void print_driver_list(driver_list_t drivers, int indent);
157static void print_devclass_short(devclass_t dc, int indent);
158static void print_devclass(devclass_t dc, int indent);
159void print_devclass_list_short(void);
160void print_devclass_list(void);
161
162#else
163/* Make the compiler ignore the function calls */
164#define PDEBUG(a)			/* nop */
165#define DEVICENAME(d)			/* nop */
166#define DRIVERNAME(d)			/* nop */
167#define DEVCLANAME(d)			/* nop */
168
169#define print_device_short(d,i)		/* nop */
170#define print_device(d,i)		/* nop */
171#define print_device_tree_short(d,i)	/* nop */
172#define print_device_tree(d,i)		/* nop */
173#define print_driver_short(d,i)		/* nop */
174#define print_driver(d,i)		/* nop */
175#define print_driver_list(d,i)		/* nop */
176#define print_devclass_short(d,i)	/* nop */
177#define print_devclass(d,i)		/* nop */
178#define print_devclass_list_short()	/* nop */
179#define print_devclass_list()		/* nop */
180#endif
181
182/*
183 * /dev/devctl implementation
184 */
185
186/*
187 * This design allows only one reader for /dev/devctl.  This is not desirable
188 * in the long run, but will get a lot of hair out of this implementation.
189 * Maybe we should make this device a clonable device.
190 *
191 * Also note: we specifically do not attach a device to the device_t tree
192 * to avoid potential chicken and egg problems.  One could argue that all
193 * of this belongs to the root node.  One could also further argue that the
194 * sysctl interface that we have not might more properly be a ioctl
195 * interface, but at this stage of the game, I'm not inclinde to rock that
196 * boat.
197 *
198 * I'm also not sure that the SIGIO support is done correctly or not, as
199 * I copied it from a driver that had SIGIO support that likely hasn't been
200 * tested since 3.4 or 2.2.8!
201 */
202
203static d_open_t		devopen;
204static d_close_t	devclose;
205static d_read_t		devread;
206static d_ioctl_t	devioctl;
207static d_poll_t		devpoll;
208
209#define CDEV_MAJOR 173
210static struct cdevsw dev_cdevsw = {
211	/* open */	devopen,
212	/* close */	devclose,
213	/* read */	devread,
214	/* write */	nowrite,
215	/* ioctl */	devioctl,
216	/* poll */	devpoll,
217	/* mmap */	nommap,
218	/* strategy */	nostrategy,
219	/* name */	"devctl",
220	/* maj */	CDEV_MAJOR,
221	/* dump */	nodump,
222	/* psize */	nopsize,
223	/* flags */	0,
224};
225
226struct dev_event_info
227{
228	char *dei_data;
229	TAILQ_ENTRY(dev_event_info) dei_link;
230};
231
232TAILQ_HEAD(devq, dev_event_info);
233
234struct dev_softc
235{
236	int	inuse;
237	int 	nonblock;
238	int	async;
239	struct mtx mtx;
240	struct cv cv;
241	struct selinfo sel;
242	struct devq devq;
243	d_thread_t *async_td;
244} devsoftc;
245
246dev_t		devctl_dev;
247
248static void
249devinit(void)
250{
251	devctl_dev = make_dev(&dev_cdevsw, 0, 0, 0, 0644, "devctl");
252	mtx_init(&devsoftc.mtx, "dev mtx", "devd", MTX_DEF);
253	cv_init(&devsoftc.cv, "dev cv");
254	TAILQ_INIT(&devsoftc.devq);
255}
256
257static int
258devopen(dev_t dev, int oflags, int devtype, d_thread_t *td)
259{
260	if (devsoftc.inuse)
261		return (EBUSY);
262	/* move to init */
263	devsoftc.inuse = 1;
264	return (0);
265}
266
267static int
268devclose(dev_t dev, int fflag, int devtype, d_thread_t *td)
269{
270	struct dev_event_info *n1;
271
272	devsoftc.inuse = 0;
273	mtx_lock(&devsoftc.mtx);
274	cv_broadcast(&devsoftc.cv);
275	/*
276	 * See note in devread.  If we deside to keep data until read, then
277	 * remove the following while loop. XXX
278	 */
279	while (!TAILQ_EMPTY(&devsoftc.devq)) {
280		n1 = TAILQ_FIRST(&devsoftc.devq);
281		TAILQ_REMOVE(&devsoftc.devq, n1, dei_link);
282		free(n1->dei_data, M_BUS);
283		free(n1, M_BUS);
284	}
285	mtx_unlock(&devsoftc.mtx);
286
287	return (0);
288}
289
290/*
291 * The read channel for this device is used to report changes to
292 * userland in realtime.  We are required to free the data as well as
293 * the n1 object because we allocate them separately.  Also note that
294 * we return one record at a time.  If you try to read this device a
295 * character at a time, you will loose the rest of the data.  Listening
296 * programs are expected to cope.
297 */
298static int
299devread(dev_t dev, struct uio *uio, int ioflag)
300{
301	struct dev_event_info *n1;
302	int rv;
303
304	mtx_lock(&devsoftc.mtx);
305	while (TAILQ_EMPTY(&devsoftc.devq)) {
306		if (devsoftc.nonblock) {
307			mtx_unlock(&devsoftc.mtx);
308			return (EAGAIN);
309		}
310		rv = cv_wait_sig(&devsoftc.cv, &devsoftc.mtx);
311		if (rv) {
312			/*
313			 * Need to translate ERESTART to EINTR here? -- jake
314			 */
315			mtx_unlock(&devsoftc.mtx);
316			return (rv);
317		}
318	}
319	n1 = TAILQ_FIRST(&devsoftc.devq);
320	TAILQ_REMOVE(&devsoftc.devq, n1, dei_link);
321	mtx_unlock(&devsoftc.mtx);
322	rv = uiomove(n1->dei_data, strlen(n1->dei_data), uio);
323	free(n1->dei_data, M_BUS);
324	free(n1, M_BUS);
325	return (rv);
326}
327
328static	int
329devioctl(dev_t dev, u_long cmd, caddr_t data, int fflag, d_thread_t *td)
330{
331	switch (cmd) {
332
333	case FIONBIO:
334		if (*(int*)data)
335			devsoftc.nonblock = 1;
336		else
337			devsoftc.nonblock = 0;
338		return (0);
339	case FIOASYNC:
340		if (*(int*)data) {
341			devsoftc.async = 1;
342			devsoftc.async_td = td;
343		}
344		else {
345			devsoftc.async = 0;
346			devsoftc.async_td = NULL;
347		}
348		return (0);
349
350		/* (un)Support for other fcntl() calls. */
351	case FIOCLEX:
352	case FIONCLEX:
353	case FIONREAD:
354	case FIOSETOWN:
355	case FIOGETOWN:
356	default:
357		break;
358	}
359	return (ENOTTY);
360}
361
362static	int
363devpoll(dev_t dev, int events, d_thread_t *td)
364{
365	int	revents = 0;
366
367	if (events & (POLLIN | POLLRDNORM))
368		revents |= events & (POLLIN | POLLRDNORM);
369
370	if (events & (POLLOUT | POLLWRNORM))
371		revents |= events & (POLLOUT | POLLWRNORM);
372
373	mtx_lock(&devsoftc.mtx);
374	if (events & POLLRDBAND)
375		if (!TAILQ_EMPTY(&devsoftc.devq))
376			revents |= POLLRDBAND;
377	mtx_unlock(&devsoftc.mtx);
378
379	if (revents == 0)
380		selrecord(td, &devsoftc.sel);
381
382	return (revents);
383}
384
385/*
386 * Common routine that tries to make sending messages as easy as possible.
387 * We allocate memory for the data, copy strings into that, but do not
388 * free it unless there's an error.  The dequeue part of the driver should
389 * free the data.  We do not send any data if there is no listeners on the
390 * /dev/devctl device.  We assume that on startup, any program that wishes
391 * to do things based on devices that have attached before it starts will
392 * query the tree to find out its current state.  This decision may
393 * be revisited if there are difficulties determining if one should do an
394 * action or not (eg, are all actions that the listening program idempotent
395 * or not).  This may also open up races as well (say if the listener
396 * dies just before a device goes away, and is run again just after, no
397 * detach action would happen).  The flip side would be that we'd need to
398 * limit the size of the queue because otherwise if no listener is running
399 * then we'd have unbounded growth.  Most systems have less than 100 (maybe
400 * even less than 50) devices, so maybe a limit of 200 or 300 wouldn't be
401 * too horrible. XXX
402 */
403static void
404devaddq(const char *type, const char *what, device_t dev)
405{
406	struct dev_event_info *n1 = NULL;
407	char *data = NULL;
408	char *loc;
409	const char *parstr;
410
411	if (!devsoftc.inuse)
412		return;
413	n1 = malloc(sizeof(*n1), M_BUS, M_NOWAIT);
414	if (n1 == NULL)
415		goto bad;
416	data = malloc(1024, M_BUS, M_NOWAIT);
417	if (data == NULL)
418		goto bad;
419	loc = malloc(1024, M_BUS, M_NOWAIT);
420	if (loc == NULL)
421		goto bad;
422	*loc = '\0';
423	bus_child_location_str(dev, loc, 1024);
424	if (device_get_parent(dev) == NULL)
425		parstr = ".";	/* Or '/' ? */
426	else
427		parstr = device_get_nameunit(device_get_parent(dev));
428	snprintf(data, 1024, "%s%s at %s on %s\n", type, what, loc, parstr);
429	free(loc, M_BUS);
430	n1->dei_data = data;
431	mtx_lock(&devsoftc.mtx);
432	TAILQ_INSERT_TAIL(&devsoftc.devq, n1, dei_link);
433	cv_broadcast(&devsoftc.cv);
434	mtx_unlock(&devsoftc.mtx);
435	selwakeup(&devsoftc.sel);
436	if (devsoftc.async_td)
437		psignal(devsoftc.async_td->td_proc, SIGIO);
438	return;
439bad:;
440	free(data, M_BUS);
441	free(n1, M_BUS);
442	return;
443}
444
445/*
446 * A device was added to the tree.  We are called just after it successfully
447 * attaches (that is, probe and attach success for this device).  No call
448 * is made if a device is merely parented into the tree.  See devnomatch
449 * if probe fails.  If attach fails, no notification is sent (but maybe
450 * we should have a different message for this).
451 */
452static void
453devadded(device_t dev)
454{
455	devaddq("+", device_get_nameunit(dev), dev);
456}
457
458/*
459 * A device was removed from the tree.  We are called just before this
460 * happens.
461 */
462static void
463devremoved(device_t dev)
464{
465	devaddq("-", device_get_nameunit(dev), dev);
466}
467
468/*
469 * Called when there's no match for this device.  This is only called
470 * the first time that no match happens, so we don't keep getitng this
471 * message.  Should that prove to be undesirable, we can change it.
472 * This is called when all drivers that can attach to a given bus
473 * decline to accept this device.  Other errrors may not be detected.
474 */
475static void
476devnomatch(device_t dev)
477{
478	char *pnp = NULL;
479
480	pnp = malloc(1024, M_BUS, M_NOWAIT);
481	if (pnp == NULL)
482		return;
483	*pnp = '\0';
484	bus_child_pnpinfo_str(dev, pnp, 1024);
485	devaddq("?", pnp, dev);
486	free(pnp, M_BUS);
487	return;
488}
489
490/* End of /dev/devctl code */
491
492TAILQ_HEAD(,device)	bus_data_devices;
493static int bus_data_generation = 1;
494
495kobj_method_t null_methods[] = {
496	{ 0, 0 }
497};
498
499DEFINE_CLASS(null, null_methods, 0);
500
501/*
502 * Devclass implementation
503 */
504
505static devclass_list_t devclasses = TAILQ_HEAD_INITIALIZER(devclasses);
506
507static devclass_t
508devclass_find_internal(const char *classname, int create)
509{
510	devclass_t dc;
511
512	PDEBUG(("looking for %s", classname));
513	if (!classname)
514		return (NULL);
515
516	TAILQ_FOREACH(dc, &devclasses, link) {
517		if (!strcmp(dc->name, classname))
518			return (dc);
519	}
520
521	PDEBUG(("%s not found%s", classname, (create? ", creating": "")));
522	if (create) {
523		dc = malloc(sizeof(struct devclass) + strlen(classname) + 1,
524		    M_BUS, M_NOWAIT|M_ZERO);
525		if (!dc)
526			return (NULL);
527		dc->name = (char*) (dc + 1);
528		strcpy(dc->name, classname);
529		TAILQ_INIT(&dc->drivers);
530		TAILQ_INSERT_TAIL(&devclasses, dc, link);
531
532		bus_data_generation_update();
533	}
534
535	return (dc);
536}
537
538devclass_t
539devclass_create(const char *classname)
540{
541	return (devclass_find_internal(classname, TRUE));
542}
543
544devclass_t
545devclass_find(const char *classname)
546{
547	return (devclass_find_internal(classname, FALSE));
548}
549
550int
551devclass_add_driver(devclass_t dc, driver_t *driver)
552{
553	driverlink_t dl;
554	int i;
555
556	PDEBUG(("%s", DRIVERNAME(driver)));
557
558	dl = malloc(sizeof *dl, M_BUS, M_NOWAIT|M_ZERO);
559	if (!dl)
560		return (ENOMEM);
561
562	/*
563	 * Compile the driver's methods. Also increase the reference count
564	 * so that the class doesn't get freed when the last instance
565	 * goes. This means we can safely use static methods and avoids a
566	 * double-free in devclass_delete_driver.
567	 */
568	kobj_class_compile((kobj_class_t) driver);
569
570	/*
571	 * Make sure the devclass which the driver is implementing exists.
572	 */
573	devclass_find_internal(driver->name, TRUE);
574
575	dl->driver = driver;
576	TAILQ_INSERT_TAIL(&dc->drivers, dl, link);
577	driver->refs++;
578
579	/*
580	 * Call BUS_DRIVER_ADDED for any existing busses in this class.
581	 */
582	for (i = 0; i < dc->maxunit; i++)
583		if (dc->devices[i])
584			BUS_DRIVER_ADDED(dc->devices[i], driver);
585
586	bus_data_generation_update();
587	return (0);
588}
589
590int
591devclass_delete_driver(devclass_t busclass, driver_t *driver)
592{
593	devclass_t dc = devclass_find(driver->name);
594	driverlink_t dl;
595	device_t dev;
596	int i;
597	int error;
598
599	PDEBUG(("%s from devclass %s", driver->name, DEVCLANAME(busclass)));
600
601	if (!dc)
602		return (0);
603
604	/*
605	 * Find the link structure in the bus' list of drivers.
606	 */
607	TAILQ_FOREACH(dl, &busclass->drivers, link) {
608		if (dl->driver == driver)
609			break;
610	}
611
612	if (!dl) {
613		PDEBUG(("%s not found in %s list", driver->name,
614		    busclass->name));
615		return (ENOENT);
616	}
617
618	/*
619	 * Disassociate from any devices.  We iterate through all the
620	 * devices in the devclass of the driver and detach any which are
621	 * using the driver and which have a parent in the devclass which
622	 * we are deleting from.
623	 *
624	 * Note that since a driver can be in multiple devclasses, we
625	 * should not detach devices which are not children of devices in
626	 * the affected devclass.
627	 */
628	for (i = 0; i < dc->maxunit; i++) {
629		if (dc->devices[i]) {
630			dev = dc->devices[i];
631			if (dev->driver == driver && dev->parent &&
632			    dev->parent->devclass == busclass) {
633				if ((error = device_detach(dev)) != 0)
634					return (error);
635				device_set_driver(dev, NULL);
636			}
637		}
638	}
639
640	TAILQ_REMOVE(&busclass->drivers, dl, link);
641	free(dl, M_BUS);
642
643	driver->refs--;
644	if (driver->refs == 0)
645		kobj_class_free((kobj_class_t) driver);
646
647	bus_data_generation_update();
648	return (0);
649}
650
651static driverlink_t
652devclass_find_driver_internal(devclass_t dc, const char *classname)
653{
654	driverlink_t dl;
655
656	PDEBUG(("%s in devclass %s", classname, DEVCLANAME(dc)));
657
658	TAILQ_FOREACH(dl, &dc->drivers, link) {
659		if (!strcmp(dl->driver->name, classname))
660			return (dl);
661	}
662
663	PDEBUG(("not found"));
664	return (NULL);
665}
666
667driver_t *
668devclass_find_driver(devclass_t dc, const char *classname)
669{
670	driverlink_t dl;
671
672	dl = devclass_find_driver_internal(dc, classname);
673	if (dl)
674		return (dl->driver);
675	return (NULL);
676}
677
678const char *
679devclass_get_name(devclass_t dc)
680{
681	return (dc->name);
682}
683
684device_t
685devclass_get_device(devclass_t dc, int unit)
686{
687	if (dc == NULL || unit < 0 || unit >= dc->maxunit)
688		return (NULL);
689	return (dc->devices[unit]);
690}
691
692void *
693devclass_get_softc(devclass_t dc, int unit)
694{
695	device_t dev;
696
697	dev = devclass_get_device(dc, unit);
698	if (!dev)
699		return (NULL);
700
701	return (device_get_softc(dev));
702}
703
704int
705devclass_get_devices(devclass_t dc, device_t **devlistp, int *devcountp)
706{
707	int i;
708	int count;
709	device_t *list;
710
711	count = 0;
712	for (i = 0; i < dc->maxunit; i++)
713		if (dc->devices[i])
714			count++;
715
716	list = malloc(count * sizeof(device_t), M_TEMP, M_NOWAIT|M_ZERO);
717	if (!list)
718		return (ENOMEM);
719
720	count = 0;
721	for (i = 0; i < dc->maxunit; i++) {
722		if (dc->devices[i]) {
723			list[count] = dc->devices[i];
724			count++;
725		}
726	}
727
728	*devlistp = list;
729	*devcountp = count;
730
731	return (0);
732}
733
734int
735devclass_get_maxunit(devclass_t dc)
736{
737	return (dc->maxunit);
738}
739
740int
741devclass_find_free_unit(devclass_t dc, int unit)
742{
743	if (dc == NULL)
744		return (unit);
745	while (unit < dc->maxunit && dc->devices[unit] != NULL)
746		unit++;
747	return (unit);
748}
749
750static int
751devclass_alloc_unit(devclass_t dc, int *unitp)
752{
753	int unit = *unitp;
754
755	PDEBUG(("unit %d in devclass %s", unit, DEVCLANAME(dc)));
756
757	/* If we were given a wired unit number, check for existing device */
758	/* XXX imp XXX */
759	if (unit != -1) {
760		if (unit >= 0 && unit < dc->maxunit &&
761		    dc->devices[unit] != NULL) {
762			if (bootverbose)
763				printf("%s: %s%d already exists; skipping it\n",
764				    dc->name, dc->name, *unitp);
765			return (EEXIST);
766		}
767	} else {
768		/* Unwired device, find the next available slot for it */
769		unit = 0;
770		while (unit < dc->maxunit && dc->devices[unit] != NULL)
771			unit++;
772	}
773
774	/*
775	 * We've selected a unit beyond the length of the table, so let's
776	 * extend the table to make room for all units up to and including
777	 * this one.
778	 */
779	if (unit >= dc->maxunit) {
780		device_t *newlist;
781		int newsize;
782
783		newsize = roundup((unit + 1), MINALLOCSIZE / sizeof(device_t));
784		newlist = malloc(sizeof(device_t) * newsize, M_BUS, M_NOWAIT);
785		if (!newlist)
786			return (ENOMEM);
787		bcopy(dc->devices, newlist, sizeof(device_t) * dc->maxunit);
788		bzero(newlist + dc->maxunit,
789		    sizeof(device_t) * (newsize - dc->maxunit));
790		if (dc->devices)
791			free(dc->devices, M_BUS);
792		dc->devices = newlist;
793		dc->maxunit = newsize;
794	}
795	PDEBUG(("now: unit %d in devclass %s", unit, DEVCLANAME(dc)));
796
797	*unitp = unit;
798	return (0);
799}
800
801static int
802devclass_add_device(devclass_t dc, device_t dev)
803{
804	int buflen, error;
805
806	PDEBUG(("%s in devclass %s", DEVICENAME(dev), DEVCLANAME(dc)));
807
808	buflen = snprintf(NULL, 0, "%s%d$", dc->name, dev->unit);
809	if (buflen < 0)
810		return (ENOMEM);
811	dev->nameunit = malloc(buflen, M_BUS, M_NOWAIT|M_ZERO);
812	if (!dev->nameunit)
813		return (ENOMEM);
814
815	if ((error = devclass_alloc_unit(dc, &dev->unit)) != 0) {
816		free(dev->nameunit, M_BUS);
817		dev->nameunit = NULL;
818		return (error);
819	}
820	dc->devices[dev->unit] = dev;
821	dev->devclass = dc;
822	snprintf(dev->nameunit, buflen, "%s%d", dc->name, dev->unit);
823
824	return (0);
825}
826
827static int
828devclass_delete_device(devclass_t dc, device_t dev)
829{
830	if (!dc || !dev)
831		return (0);
832
833	PDEBUG(("%s in devclass %s", DEVICENAME(dev), DEVCLANAME(dc)));
834
835	if (dev->devclass != dc || dc->devices[dev->unit] != dev)
836		panic("devclass_delete_device: inconsistent device class");
837	dc->devices[dev->unit] = NULL;
838	if (dev->flags & DF_WILDCARD)
839		dev->unit = -1;
840	dev->devclass = NULL;
841	free(dev->nameunit, M_BUS);
842	dev->nameunit = NULL;
843
844	return (0);
845}
846
847static device_t
848make_device(device_t parent, const char *name, int unit)
849{
850	device_t dev;
851	devclass_t dc;
852
853	PDEBUG(("%s at %s as unit %d", name, DEVICENAME(parent), unit));
854
855	if (name) {
856		dc = devclass_find_internal(name, TRUE);
857		if (!dc) {
858			printf("make_device: can't find device class %s\n",
859			    name);
860			return (NULL);
861		}
862	} else {
863		dc = NULL;
864	}
865
866	dev = malloc(sizeof(struct device), M_BUS, M_NOWAIT|M_ZERO);
867	if (!dev)
868		return (NULL);
869
870	dev->parent = parent;
871	TAILQ_INIT(&dev->children);
872	kobj_init((kobj_t) dev, &null_class);
873	dev->driver = NULL;
874	dev->devclass = NULL;
875	dev->unit = unit;
876	dev->nameunit = NULL;
877	dev->desc = NULL;
878	dev->busy = 0;
879	dev->devflags = 0;
880	dev->flags = DF_ENABLED;
881	dev->order = 0;
882	if (unit == -1)
883		dev->flags |= DF_WILDCARD;
884	if (name) {
885		dev->flags |= DF_FIXEDCLASS;
886		if (devclass_add_device(dc, dev)) {
887			kobj_delete((kobj_t) dev, M_BUS);
888			return (NULL);
889		}
890	}
891	dev->ivars = NULL;
892	dev->softc = NULL;
893
894	dev->state = DS_NOTPRESENT;
895
896	TAILQ_INSERT_TAIL(&bus_data_devices, dev, devlink);
897	bus_data_generation_update();
898
899	return (dev);
900}
901
902static int
903device_print_child(device_t dev, device_t child)
904{
905	int retval = 0;
906
907	if (device_is_alive(child))
908		retval += BUS_PRINT_CHILD(dev, child);
909	else
910		retval += device_printf(child, " not found\n");
911
912	return (retval);
913}
914
915device_t
916device_add_child(device_t dev, const char *name, int unit)
917{
918	return (device_add_child_ordered(dev, 0, name, unit));
919}
920
921device_t
922device_add_child_ordered(device_t dev, int order, const char *name, int unit)
923{
924	device_t child;
925	device_t place;
926
927	PDEBUG(("%s at %s with order %d as unit %d",
928	    name, DEVICENAME(dev), order, unit));
929
930	child = make_device(dev, name, unit);
931	if (child == NULL)
932		return (child);
933	child->order = order;
934
935	TAILQ_FOREACH(place, &dev->children, link) {
936		if (place->order > order)
937			break;
938	}
939
940	if (place) {
941		/*
942		 * The device 'place' is the first device whose order is
943		 * greater than the new child.
944		 */
945		TAILQ_INSERT_BEFORE(place, child, link);
946	} else {
947		/*
948		 * The new child's order is greater or equal to the order of
949		 * any existing device. Add the child to the tail of the list.
950		 */
951		TAILQ_INSERT_TAIL(&dev->children, child, link);
952	}
953
954	bus_data_generation_update();
955	return (child);
956}
957
958int
959device_delete_child(device_t dev, device_t child)
960{
961	int error;
962	device_t grandchild;
963
964	PDEBUG(("%s from %s", DEVICENAME(child), DEVICENAME(dev)));
965
966	/* remove children first */
967	while ( (grandchild = TAILQ_FIRST(&child->children)) ) {
968		error = device_delete_child(child, grandchild);
969		if (error)
970			return (error);
971	}
972
973	if ((error = device_detach(child)) != 0)
974		return (error);
975	if (child->devclass)
976		devclass_delete_device(child->devclass, child);
977	TAILQ_REMOVE(&dev->children, child, link);
978	TAILQ_REMOVE(&bus_data_devices, child, devlink);
979	device_set_desc(child, NULL);
980	free(child, M_BUS);
981
982	bus_data_generation_update();
983	return (0);
984}
985
986/*
987 * Find only devices attached to this bus.
988 */
989device_t
990device_find_child(device_t dev, const char *classname, int unit)
991{
992	devclass_t dc;
993	device_t child;
994
995	dc = devclass_find(classname);
996	if (!dc)
997		return (NULL);
998
999	child = devclass_get_device(dc, unit);
1000	if (child && child->parent == dev)
1001		return (child);
1002	return (NULL);
1003}
1004
1005static driverlink_t
1006first_matching_driver(devclass_t dc, device_t dev)
1007{
1008	if (dev->devclass)
1009		return (devclass_find_driver_internal(dc, dev->devclass->name));
1010	return (TAILQ_FIRST(&dc->drivers));
1011}
1012
1013static driverlink_t
1014next_matching_driver(devclass_t dc, device_t dev, driverlink_t last)
1015{
1016	if (dev->devclass) {
1017		driverlink_t dl;
1018		for (dl = TAILQ_NEXT(last, link); dl; dl = TAILQ_NEXT(dl, link))
1019			if (!strcmp(dev->devclass->name, dl->driver->name))
1020				return (dl);
1021		return (NULL);
1022	}
1023	return (TAILQ_NEXT(last, link));
1024}
1025
1026static int
1027device_probe_child(device_t dev, device_t child)
1028{
1029	devclass_t dc;
1030	driverlink_t best = 0;
1031	driverlink_t dl;
1032	int result, pri = 0;
1033	int hasclass = (child->devclass != 0);
1034
1035	dc = dev->devclass;
1036	if (!dc)
1037		panic("device_probe_child: parent device has no devclass");
1038
1039	if (child->state == DS_ALIVE)
1040		return (0);
1041
1042	for (dl = first_matching_driver(dc, child);
1043	     dl;
1044	     dl = next_matching_driver(dc, child, dl)) {
1045		PDEBUG(("Trying %s", DRIVERNAME(dl->driver)));
1046		device_set_driver(child, dl->driver);
1047		if (!hasclass)
1048			device_set_devclass(child, dl->driver->name);
1049		result = DEVICE_PROBE(child);
1050		if (!hasclass)
1051			device_set_devclass(child, 0);
1052
1053		/*
1054		 * If the driver returns SUCCESS, there can be no higher match
1055		 * for this device.
1056		 */
1057		if (result == 0) {
1058			best = dl;
1059			pri = 0;
1060			break;
1061		}
1062
1063		/*
1064		 * The driver returned an error so it certainly doesn't match.
1065		 */
1066		if (result > 0) {
1067			device_set_driver(child, 0);
1068			continue;
1069		}
1070
1071		/*
1072		 * A priority lower than SUCCESS, remember the best matching
1073		 * driver. Initialise the value of pri for the first match.
1074		 */
1075		if (best == 0 || result > pri) {
1076			best = dl;
1077			pri = result;
1078			continue;
1079		}
1080	}
1081
1082	/*
1083	 * If we found a driver, change state and initialise the devclass.
1084	 */
1085	if (best) {
1086		if (!child->devclass)
1087			device_set_devclass(child, best->driver->name);
1088		device_set_driver(child, best->driver);
1089		if (pri < 0) {
1090			/*
1091			 * A bit bogus. Call the probe method again to make
1092			 * sure that we have the right description.
1093			 */
1094			DEVICE_PROBE(child);
1095		}
1096		child->state = DS_ALIVE;
1097
1098		bus_data_generation_update();
1099		return (0);
1100	}
1101
1102	return (ENXIO);
1103}
1104
1105device_t
1106device_get_parent(device_t dev)
1107{
1108	return (dev->parent);
1109}
1110
1111int
1112device_get_children(device_t dev, device_t **devlistp, int *devcountp)
1113{
1114	int count;
1115	device_t child;
1116	device_t *list;
1117
1118	count = 0;
1119	TAILQ_FOREACH(child, &dev->children, link) {
1120		count++;
1121	}
1122
1123	list = malloc(count * sizeof(device_t), M_TEMP, M_NOWAIT|M_ZERO);
1124	if (!list)
1125		return (ENOMEM);
1126
1127	count = 0;
1128	TAILQ_FOREACH(child, &dev->children, link) {
1129		list[count] = child;
1130		count++;
1131	}
1132
1133	*devlistp = list;
1134	*devcountp = count;
1135
1136	return (0);
1137}
1138
1139driver_t *
1140device_get_driver(device_t dev)
1141{
1142	return (dev->driver);
1143}
1144
1145devclass_t
1146device_get_devclass(device_t dev)
1147{
1148	return (dev->devclass);
1149}
1150
1151const char *
1152device_get_name(device_t dev)
1153{
1154	if (dev->devclass)
1155		return (devclass_get_name(dev->devclass));
1156	return (NULL);
1157}
1158
1159const char *
1160device_get_nameunit(device_t dev)
1161{
1162	return (dev->nameunit);
1163}
1164
1165int
1166device_get_unit(device_t dev)
1167{
1168	return (dev->unit);
1169}
1170
1171const char *
1172device_get_desc(device_t dev)
1173{
1174	return (dev->desc);
1175}
1176
1177u_int32_t
1178device_get_flags(device_t dev)
1179{
1180	return (dev->devflags);
1181}
1182
1183int
1184device_print_prettyname(device_t dev)
1185{
1186	const char *name = device_get_name(dev);
1187
1188	if (name == 0)
1189		return (printf("unknown: "));
1190	return (printf("%s%d: ", name, device_get_unit(dev)));
1191}
1192
1193int
1194device_printf(device_t dev, const char * fmt, ...)
1195{
1196	va_list ap;
1197	int retval;
1198
1199	retval = device_print_prettyname(dev);
1200	va_start(ap, fmt);
1201	retval += vprintf(fmt, ap);
1202	va_end(ap);
1203	return (retval);
1204}
1205
1206static void
1207device_set_desc_internal(device_t dev, const char* desc, int copy)
1208{
1209	if (dev->desc && (dev->flags & DF_DESCMALLOCED)) {
1210		free(dev->desc, M_BUS);
1211		dev->flags &= ~DF_DESCMALLOCED;
1212		dev->desc = NULL;
1213	}
1214
1215	if (copy && desc) {
1216		dev->desc = malloc(strlen(desc) + 1, M_BUS, M_NOWAIT);
1217		if (dev->desc) {
1218			strcpy(dev->desc, desc);
1219			dev->flags |= DF_DESCMALLOCED;
1220		}
1221	} else {
1222		/* Avoid a -Wcast-qual warning */
1223		dev->desc = (char *)(uintptr_t) desc;
1224	}
1225
1226	bus_data_generation_update();
1227}
1228
1229void
1230device_set_desc(device_t dev, const char* desc)
1231{
1232	device_set_desc_internal(dev, desc, FALSE);
1233}
1234
1235void
1236device_set_desc_copy(device_t dev, const char* desc)
1237{
1238	device_set_desc_internal(dev, desc, TRUE);
1239}
1240
1241void
1242device_set_flags(device_t dev, u_int32_t flags)
1243{
1244	dev->devflags = flags;
1245}
1246
1247void *
1248device_get_softc(device_t dev)
1249{
1250	return (dev->softc);
1251}
1252
1253void
1254device_set_softc(device_t dev, void *softc)
1255{
1256	if (dev->softc && !(dev->flags & DF_EXTERNALSOFTC))
1257		free(dev->softc, M_BUS);
1258	dev->softc = softc;
1259	if (dev->softc)
1260		dev->flags |= DF_EXTERNALSOFTC;
1261	else
1262		dev->flags &= ~DF_EXTERNALSOFTC;
1263}
1264
1265void *
1266device_get_ivars(device_t dev)
1267{
1268
1269	KASSERT(dev != NULL, ("device_get_ivars(NULL, ...)"));
1270	return (dev->ivars);
1271}
1272
1273void
1274device_set_ivars(device_t dev, void * ivars)
1275{
1276
1277	KASSERT(dev != NULL, ("device_set_ivars(NULL, ...)"));
1278	dev->ivars = ivars;
1279}
1280
1281device_state_t
1282device_get_state(device_t dev)
1283{
1284	return (dev->state);
1285}
1286
1287void
1288device_enable(device_t dev)
1289{
1290	dev->flags |= DF_ENABLED;
1291}
1292
1293void
1294device_disable(device_t dev)
1295{
1296	dev->flags &= ~DF_ENABLED;
1297}
1298
1299void
1300device_busy(device_t dev)
1301{
1302	if (dev->state < DS_ATTACHED)
1303		panic("device_busy: called for unattached device");
1304	if (dev->busy == 0 && dev->parent)
1305		device_busy(dev->parent);
1306	dev->busy++;
1307	dev->state = DS_BUSY;
1308}
1309
1310void
1311device_unbusy(device_t dev)
1312{
1313	if (dev->state != DS_BUSY)
1314		panic("device_unbusy: called for non-busy device");
1315	dev->busy--;
1316	if (dev->busy == 0) {
1317		if (dev->parent)
1318			device_unbusy(dev->parent);
1319		dev->state = DS_ATTACHED;
1320	}
1321}
1322
1323void
1324device_quiet(device_t dev)
1325{
1326	dev->flags |= DF_QUIET;
1327}
1328
1329void
1330device_verbose(device_t dev)
1331{
1332	dev->flags &= ~DF_QUIET;
1333}
1334
1335int
1336device_is_quiet(device_t dev)
1337{
1338	return ((dev->flags & DF_QUIET) != 0);
1339}
1340
1341int
1342device_is_enabled(device_t dev)
1343{
1344	return ((dev->flags & DF_ENABLED) != 0);
1345}
1346
1347int
1348device_is_alive(device_t dev)
1349{
1350	return (dev->state >= DS_ALIVE);
1351}
1352
1353int
1354device_set_devclass(device_t dev, const char *classname)
1355{
1356	devclass_t dc;
1357	int error;
1358
1359	if (!classname) {
1360		if (dev->devclass)
1361			devclass_delete_device(dev->devclass, dev);
1362		return (0);
1363	}
1364
1365	if (dev->devclass) {
1366		printf("device_set_devclass: device class already set\n");
1367		return (EINVAL);
1368	}
1369
1370	dc = devclass_find_internal(classname, TRUE);
1371	if (!dc)
1372		return (ENOMEM);
1373
1374	error = devclass_add_device(dc, dev);
1375
1376	bus_data_generation_update();
1377	return (error);
1378}
1379
1380int
1381device_set_driver(device_t dev, driver_t *driver)
1382{
1383	if (dev->state >= DS_ATTACHED)
1384		return (EBUSY);
1385
1386	if (dev->driver == driver)
1387		return (0);
1388
1389	if (dev->softc && !(dev->flags & DF_EXTERNALSOFTC)) {
1390		free(dev->softc, M_BUS);
1391		dev->softc = NULL;
1392	}
1393	kobj_delete((kobj_t) dev, 0);
1394	dev->driver = driver;
1395	if (driver) {
1396		kobj_init((kobj_t) dev, (kobj_class_t) driver);
1397		if (!(dev->flags & DF_EXTERNALSOFTC) && driver->size > 0) {
1398			dev->softc = malloc(driver->size, M_BUS,
1399			    M_NOWAIT | M_ZERO);
1400			if (!dev->softc) {
1401				kobj_init((kobj_t) dev, &null_class);
1402				dev->driver = NULL;
1403				return (ENOMEM);
1404			}
1405		}
1406	} else {
1407		kobj_init((kobj_t) dev, &null_class);
1408	}
1409
1410	bus_data_generation_update();
1411	return (0);
1412}
1413
1414int
1415device_probe_and_attach(device_t dev)
1416{
1417	device_t bus = dev->parent;
1418	int error = 0;
1419	int hasclass = (dev->devclass != 0);
1420
1421	if (dev->state >= DS_ALIVE)
1422		return (0);
1423
1424	if (dev->flags & DF_ENABLED) {
1425		error = device_probe_child(bus, dev);
1426		if (!error) {
1427			if (!device_is_quiet(dev))
1428				device_print_child(bus, dev);
1429			error = DEVICE_ATTACH(dev);
1430			if (!error) {
1431				dev->state = DS_ATTACHED;
1432				devadded(dev);
1433			} else {
1434				printf("device_probe_and_attach: %s%d attach returned %d\n",
1435				    dev->driver->name, dev->unit, error);
1436				/* Unset the class; set in device_probe_child */
1437				if (!hasclass)
1438					device_set_devclass(dev, 0);
1439				device_set_driver(dev, NULL);
1440				dev->state = DS_NOTPRESENT;
1441			}
1442		} else {
1443			if (!(dev->flags & DF_DONENOMATCH)) {
1444				BUS_PROBE_NOMATCH(bus, dev);
1445				devnomatch(dev);
1446				dev->flags |= DF_DONENOMATCH;
1447			}
1448		}
1449	} else {
1450		if (bootverbose) {
1451			device_print_prettyname(dev);
1452			printf("not probed (disabled)\n");
1453		}
1454	}
1455
1456	return (error);
1457}
1458
1459int
1460device_detach(device_t dev)
1461{
1462	int error;
1463
1464	PDEBUG(("%s", DEVICENAME(dev)));
1465	if (dev->state == DS_BUSY)
1466		return (EBUSY);
1467	if (dev->state != DS_ATTACHED)
1468		return (0);
1469
1470	if ((error = DEVICE_DETACH(dev)) != 0)
1471		return (error);
1472	devremoved(dev);
1473	device_printf(dev, "detached\n");
1474	if (dev->parent)
1475		BUS_CHILD_DETACHED(dev->parent, dev);
1476
1477	if (!(dev->flags & DF_FIXEDCLASS))
1478		devclass_delete_device(dev->devclass, dev);
1479
1480	dev->state = DS_NOTPRESENT;
1481	device_set_driver(dev, NULL);
1482
1483	return (0);
1484}
1485
1486int
1487device_shutdown(device_t dev)
1488{
1489	if (dev->state < DS_ATTACHED)
1490		return (0);
1491	return (DEVICE_SHUTDOWN(dev));
1492}
1493
1494int
1495device_set_unit(device_t dev, int unit)
1496{
1497	devclass_t dc;
1498	int err;
1499
1500	dc = device_get_devclass(dev);
1501	if (unit < dc->maxunit && dc->devices[unit])
1502		return (EBUSY);
1503	err = devclass_delete_device(dc, dev);
1504	if (err)
1505		return (err);
1506	dev->unit = unit;
1507	err = devclass_add_device(dc, dev);
1508	if (err)
1509		return (err);
1510
1511	bus_data_generation_update();
1512	return (0);
1513}
1514
1515/*======================================*/
1516/*
1517 * Some useful method implementations to make life easier for bus drivers.
1518 */
1519
1520void
1521resource_list_init(struct resource_list *rl)
1522{
1523	SLIST_INIT(rl);
1524}
1525
1526void
1527resource_list_free(struct resource_list *rl)
1528{
1529	struct resource_list_entry *rle;
1530
1531	while ((rle = SLIST_FIRST(rl)) != NULL) {
1532		if (rle->res)
1533			panic("resource_list_free: resource entry is busy");
1534		SLIST_REMOVE_HEAD(rl, link);
1535		free(rle, M_BUS);
1536	}
1537}
1538
1539int
1540resource_list_add_next(struct resource_list *rl, int type, u_long start,
1541    u_long end, u_long count)
1542{
1543	int rid;
1544
1545	rid = 0;
1546	while (resource_list_find(rl, type, rid) != NULL)
1547		rid++;
1548	resource_list_add(rl, type, rid, start, end, count);
1549	return (rid);
1550}
1551
1552void
1553resource_list_add(struct resource_list *rl, int type, int rid,
1554    u_long start, u_long end, u_long count)
1555{
1556	struct resource_list_entry *rle;
1557
1558	rle = resource_list_find(rl, type, rid);
1559	if (!rle) {
1560		rle = malloc(sizeof(struct resource_list_entry), M_BUS,
1561		    M_NOWAIT);
1562		if (!rle)
1563			panic("resource_list_add: can't record entry");
1564		SLIST_INSERT_HEAD(rl, rle, link);
1565		rle->type = type;
1566		rle->rid = rid;
1567		rle->res = NULL;
1568	}
1569
1570	if (rle->res)
1571		panic("resource_list_add: resource entry is busy");
1572
1573	rle->start = start;
1574	rle->end = end;
1575	rle->count = count;
1576}
1577
1578struct resource_list_entry *
1579resource_list_find(struct resource_list *rl, int type, int rid)
1580{
1581	struct resource_list_entry *rle;
1582
1583	SLIST_FOREACH(rle, rl, link) {
1584		if (rle->type == type && rle->rid == rid)
1585			return (rle);
1586	}
1587	return (NULL);
1588}
1589
1590void
1591resource_list_delete(struct resource_list *rl, int type, int rid)
1592{
1593	struct resource_list_entry *rle = resource_list_find(rl, type, rid);
1594
1595	if (rle) {
1596		if (rle->res != NULL)
1597			panic("resource_list_delete: resource has not been released");
1598		SLIST_REMOVE(rl, rle, resource_list_entry, link);
1599		free(rle, M_BUS);
1600	}
1601}
1602
1603struct resource *
1604resource_list_alloc(struct resource_list *rl, device_t bus, device_t child,
1605    int type, int *rid, u_long start, u_long end, u_long count, u_int flags)
1606{
1607	struct resource_list_entry *rle = 0;
1608	int passthrough = (device_get_parent(child) != bus);
1609	int isdefault = (start == 0UL && end == ~0UL);
1610
1611	if (passthrough) {
1612		return (BUS_ALLOC_RESOURCE(device_get_parent(bus), child,
1613		    type, rid, start, end, count, flags));
1614	}
1615
1616	rle = resource_list_find(rl, type, *rid);
1617
1618	if (!rle)
1619		return (NULL);		/* no resource of that type/rid */
1620
1621	if (rle->res)
1622		panic("resource_list_alloc: resource entry is busy");
1623
1624	if (isdefault) {
1625		start = rle->start;
1626		count = ulmax(count, rle->count);
1627		end = ulmax(rle->end, start + count - 1);
1628	}
1629
1630	rle->res = BUS_ALLOC_RESOURCE(device_get_parent(bus), child,
1631	    type, rid, start, end, count, flags);
1632
1633	/*
1634	 * Record the new range.
1635	 */
1636	if (rle->res) {
1637		rle->start = rman_get_start(rle->res);
1638		rle->end = rman_get_end(rle->res);
1639		rle->count = count;
1640	}
1641
1642	return (rle->res);
1643}
1644
1645int
1646resource_list_release(struct resource_list *rl, device_t bus, device_t child,
1647    int type, int rid, struct resource *res)
1648{
1649	struct resource_list_entry *rle = 0;
1650	int passthrough = (device_get_parent(child) != bus);
1651	int error;
1652
1653	if (passthrough) {
1654		return (BUS_RELEASE_RESOURCE(device_get_parent(bus), child,
1655		    type, rid, res));
1656	}
1657
1658	rle = resource_list_find(rl, type, rid);
1659
1660	if (!rle)
1661		panic("resource_list_release: can't find resource");
1662	if (!rle->res)
1663		panic("resource_list_release: resource entry is not busy");
1664
1665	error = BUS_RELEASE_RESOURCE(device_get_parent(bus), child,
1666	    type, rid, res);
1667	if (error)
1668		return (error);
1669
1670	rle->res = NULL;
1671	return (0);
1672}
1673
1674int
1675resource_list_print_type(struct resource_list *rl, const char *name, int type,
1676    const char *format)
1677{
1678	struct resource_list_entry *rle;
1679	int printed, retval;
1680
1681	printed = 0;
1682	retval = 0;
1683	/* Yes, this is kinda cheating */
1684	SLIST_FOREACH(rle, rl, link) {
1685		if (rle->type == type) {
1686			if (printed == 0)
1687				retval += printf(" %s ", name);
1688			else
1689				retval += printf(",");
1690			printed++;
1691			retval += printf(format, rle->start);
1692			if (rle->count > 1) {
1693				retval += printf("-");
1694				retval += printf(format, rle->start +
1695						 rle->count - 1);
1696			}
1697		}
1698	}
1699	return (retval);
1700}
1701
1702/*
1703 * Call DEVICE_IDENTIFY for each driver.
1704 */
1705int
1706bus_generic_probe(device_t dev)
1707{
1708	devclass_t dc = dev->devclass;
1709	driverlink_t dl;
1710
1711	TAILQ_FOREACH(dl, &dc->drivers, link) {
1712		DEVICE_IDENTIFY(dl->driver, dev);
1713	}
1714
1715	return (0);
1716}
1717
1718int
1719bus_generic_attach(device_t dev)
1720{
1721	device_t child;
1722
1723	TAILQ_FOREACH(child, &dev->children, link) {
1724		device_probe_and_attach(child);
1725	}
1726
1727	return (0);
1728}
1729
1730int
1731bus_generic_detach(device_t dev)
1732{
1733	device_t child;
1734	int error;
1735
1736	if (dev->state != DS_ATTACHED)
1737		return (EBUSY);
1738
1739	TAILQ_FOREACH(child, &dev->children, link) {
1740		if ((error = device_detach(child)) != 0)
1741			return (error);
1742	}
1743
1744	return (0);
1745}
1746
1747int
1748bus_generic_shutdown(device_t dev)
1749{
1750	device_t child;
1751
1752	TAILQ_FOREACH(child, &dev->children, link) {
1753		device_shutdown(child);
1754	}
1755
1756	return (0);
1757}
1758
1759int
1760bus_generic_suspend(device_t dev)
1761{
1762	int		error;
1763	device_t	child, child2;
1764
1765	TAILQ_FOREACH(child, &dev->children, link) {
1766		error = DEVICE_SUSPEND(child);
1767		if (error) {
1768			for (child2 = TAILQ_FIRST(&dev->children);
1769			     child2 && child2 != child;
1770			     child2 = TAILQ_NEXT(child2, link))
1771				DEVICE_RESUME(child2);
1772			return (error);
1773		}
1774	}
1775	return (0);
1776}
1777
1778int
1779bus_generic_resume(device_t dev)
1780{
1781	device_t	child;
1782
1783	TAILQ_FOREACH(child, &dev->children, link) {
1784		DEVICE_RESUME(child);
1785		/* if resume fails, there's nothing we can usefully do... */
1786	}
1787	return (0);
1788}
1789
1790int
1791bus_print_child_header (device_t dev, device_t child)
1792{
1793	int	retval = 0;
1794
1795	if (device_get_desc(child)) {
1796		retval += device_printf(child, "<%s>", device_get_desc(child));
1797	} else {
1798		retval += printf("%s", device_get_nameunit(child));
1799	}
1800
1801	return (retval);
1802}
1803
1804int
1805bus_print_child_footer (device_t dev, device_t child)
1806{
1807	return (printf(" on %s\n", device_get_nameunit(dev)));
1808}
1809
1810int
1811bus_generic_print_child(device_t dev, device_t child)
1812{
1813	int	retval = 0;
1814
1815	retval += bus_print_child_header(dev, child);
1816	retval += bus_print_child_footer(dev, child);
1817
1818	return (retval);
1819}
1820
1821int
1822bus_generic_read_ivar(device_t dev, device_t child, int index,
1823    uintptr_t * result)
1824{
1825	return (ENOENT);
1826}
1827
1828int
1829bus_generic_write_ivar(device_t dev, device_t child, int index,
1830    uintptr_t value)
1831{
1832	return (ENOENT);
1833}
1834
1835struct resource_list *
1836bus_generic_get_resource_list (device_t dev, device_t child)
1837{
1838	return (NULL);
1839}
1840
1841void
1842bus_generic_driver_added(device_t dev, driver_t *driver)
1843{
1844	device_t child;
1845
1846	DEVICE_IDENTIFY(driver, dev);
1847	TAILQ_FOREACH(child, &dev->children, link) {
1848		if (child->state == DS_NOTPRESENT)
1849			device_probe_and_attach(child);
1850	}
1851}
1852
1853int
1854bus_generic_setup_intr(device_t dev, device_t child, struct resource *irq,
1855    int flags, driver_intr_t *intr, void *arg, void **cookiep)
1856{
1857	/* Propagate up the bus hierarchy until someone handles it. */
1858	if (dev->parent)
1859		return (BUS_SETUP_INTR(dev->parent, child, irq, flags,
1860		    intr, arg, cookiep));
1861	return (EINVAL);
1862}
1863
1864int
1865bus_generic_teardown_intr(device_t dev, device_t child, struct resource *irq,
1866    void *cookie)
1867{
1868	/* Propagate up the bus hierarchy until someone handles it. */
1869	if (dev->parent)
1870		return (BUS_TEARDOWN_INTR(dev->parent, child, irq, cookie));
1871	return (EINVAL);
1872}
1873
1874struct resource *
1875bus_generic_alloc_resource(device_t dev, device_t child, int type, int *rid,
1876    u_long start, u_long end, u_long count, u_int flags)
1877{
1878	/* Propagate up the bus hierarchy until someone handles it. */
1879	if (dev->parent)
1880		return (BUS_ALLOC_RESOURCE(dev->parent, child, type, rid,
1881		    start, end, count, flags));
1882	return (NULL);
1883}
1884
1885int
1886bus_generic_release_resource(device_t dev, device_t child, int type, int rid,
1887    struct resource *r)
1888{
1889	/* Propagate up the bus hierarchy until someone handles it. */
1890	if (dev->parent)
1891		return (BUS_RELEASE_RESOURCE(dev->parent, child, type, rid,
1892		    r));
1893	return (EINVAL);
1894}
1895
1896int
1897bus_generic_activate_resource(device_t dev, device_t child, int type, int rid,
1898    struct resource *r)
1899{
1900	/* Propagate up the bus hierarchy until someone handles it. */
1901	if (dev->parent)
1902		return (BUS_ACTIVATE_RESOURCE(dev->parent, child, type, rid,
1903		    r));
1904	return (EINVAL);
1905}
1906
1907int
1908bus_generic_deactivate_resource(device_t dev, device_t child, int type,
1909    int rid, struct resource *r)
1910{
1911	/* Propagate up the bus hierarchy until someone handles it. */
1912	if (dev->parent)
1913		return (BUS_DEACTIVATE_RESOURCE(dev->parent, child, type, rid,
1914		    r));
1915	return (EINVAL);
1916}
1917
1918int
1919bus_generic_rl_get_resource (device_t dev, device_t child, int type, int rid,
1920    u_long *startp, u_long *countp)
1921{
1922	struct resource_list *		rl = NULL;
1923	struct resource_list_entry *	rle = NULL;
1924
1925	rl = BUS_GET_RESOURCE_LIST(dev, child);
1926	if (!rl)
1927		return (EINVAL);
1928
1929	rle = resource_list_find(rl, type, rid);
1930	if (!rle)
1931		return (ENOENT);
1932
1933	if (startp)
1934		*startp = rle->start;
1935	if (countp)
1936		*countp = rle->count;
1937
1938	return (0);
1939}
1940
1941int
1942bus_generic_rl_set_resource (device_t dev, device_t child, int type, int rid,
1943    u_long start, u_long count)
1944{
1945	struct resource_list *		rl = NULL;
1946
1947	rl = BUS_GET_RESOURCE_LIST(dev, child);
1948	if (!rl)
1949		return (EINVAL);
1950
1951	resource_list_add(rl, type, rid, start, (start + count - 1), count);
1952
1953	return (0);
1954}
1955
1956void
1957bus_generic_rl_delete_resource (device_t dev, device_t child, int type, int rid)
1958{
1959	struct resource_list *		rl = NULL;
1960
1961	rl = BUS_GET_RESOURCE_LIST(dev, child);
1962	if (!rl)
1963		return;
1964
1965	resource_list_delete(rl, type, rid);
1966
1967	return;
1968}
1969
1970int
1971bus_generic_rl_release_resource (device_t dev, device_t child, int type,
1972    int rid, struct resource *r)
1973{
1974	struct resource_list *		rl = NULL;
1975
1976	rl = BUS_GET_RESOURCE_LIST(dev, child);
1977	if (!rl)
1978		return (EINVAL);
1979
1980	return (resource_list_release(rl, dev, child, type, rid, r));
1981}
1982
1983struct resource *
1984bus_generic_rl_alloc_resource (device_t dev, device_t child, int type,
1985    int *rid, u_long start, u_long end, u_long count, u_int flags)
1986{
1987	struct resource_list *		rl = NULL;
1988
1989	rl = BUS_GET_RESOURCE_LIST(dev, child);
1990	if (!rl)
1991		return (NULL);
1992
1993	return (resource_list_alloc(rl, dev, child, type, rid,
1994	    start, end, count, flags));
1995}
1996
1997int
1998bus_generic_child_present(device_t bus, device_t child)
1999{
2000	return (BUS_CHILD_PRESENT(device_get_parent(bus), bus));
2001}
2002
2003/*
2004 * Some convenience functions to make it easier for drivers to use the
2005 * resource-management functions.  All these really do is hide the
2006 * indirection through the parent's method table, making for slightly
2007 * less-wordy code.  In the future, it might make sense for this code
2008 * to maintain some sort of a list of resources allocated by each device.
2009 */
2010struct resource *
2011bus_alloc_resource(device_t dev, int type, int *rid, u_long start, u_long end,
2012    u_long count, u_int flags)
2013{
2014	if (dev->parent == 0)
2015		return (0);
2016	return (BUS_ALLOC_RESOURCE(dev->parent, dev, type, rid, start, end,
2017	    count, flags));
2018}
2019
2020int
2021bus_activate_resource(device_t dev, int type, int rid, struct resource *r)
2022{
2023	if (dev->parent == 0)
2024		return (EINVAL);
2025	return (BUS_ACTIVATE_RESOURCE(dev->parent, dev, type, rid, r));
2026}
2027
2028int
2029bus_deactivate_resource(device_t dev, int type, int rid, struct resource *r)
2030{
2031	if (dev->parent == 0)
2032		return (EINVAL);
2033	return (BUS_DEACTIVATE_RESOURCE(dev->parent, dev, type, rid, r));
2034}
2035
2036int
2037bus_release_resource(device_t dev, int type, int rid, struct resource *r)
2038{
2039	if (dev->parent == 0)
2040		return (EINVAL);
2041	return (BUS_RELEASE_RESOURCE(dev->parent, dev, type, rid, r));
2042}
2043
2044int
2045bus_setup_intr(device_t dev, struct resource *r, int flags,
2046    driver_intr_t handler, void *arg, void **cookiep)
2047{
2048	if (dev->parent == 0)
2049		return (EINVAL);
2050	return (BUS_SETUP_INTR(dev->parent, dev, r, flags,
2051	    handler, arg, cookiep));
2052}
2053
2054int
2055bus_teardown_intr(device_t dev, struct resource *r, void *cookie)
2056{
2057	if (dev->parent == 0)
2058		return (EINVAL);
2059	return (BUS_TEARDOWN_INTR(dev->parent, dev, r, cookie));
2060}
2061
2062int
2063bus_set_resource(device_t dev, int type, int rid,
2064    u_long start, u_long count)
2065{
2066	return (BUS_SET_RESOURCE(device_get_parent(dev), dev, type, rid,
2067	    start, count));
2068}
2069
2070int
2071bus_get_resource(device_t dev, int type, int rid,
2072    u_long *startp, u_long *countp)
2073{
2074	return (BUS_GET_RESOURCE(device_get_parent(dev), dev, type, rid,
2075	    startp, countp));
2076}
2077
2078u_long
2079bus_get_resource_start(device_t dev, int type, int rid)
2080{
2081	u_long start, count;
2082	int error;
2083
2084	error = BUS_GET_RESOURCE(device_get_parent(dev), dev, type, rid,
2085	    &start, &count);
2086	if (error)
2087		return (0);
2088	return (start);
2089}
2090
2091u_long
2092bus_get_resource_count(device_t dev, int type, int rid)
2093{
2094	u_long start, count;
2095	int error;
2096
2097	error = BUS_GET_RESOURCE(device_get_parent(dev), dev, type, rid,
2098	    &start, &count);
2099	if (error)
2100		return (0);
2101	return (count);
2102}
2103
2104void
2105bus_delete_resource(device_t dev, int type, int rid)
2106{
2107	BUS_DELETE_RESOURCE(device_get_parent(dev), dev, type, rid);
2108}
2109
2110int
2111bus_child_present(device_t child)
2112{
2113	return (BUS_CHILD_PRESENT(device_get_parent(child), child));
2114}
2115
2116int
2117bus_child_pnpinfo_str(device_t child, char *buf, size_t buflen)
2118{
2119	device_t parent;
2120
2121	parent = device_get_parent(child);
2122	if (parent == NULL) {
2123		*buf = '\0';
2124		return (0);
2125	}
2126	return (BUS_CHILD_PNPINFO_STR(parent, child, buf, buflen));
2127}
2128
2129int
2130bus_child_location_str(device_t child, char *buf, size_t buflen)
2131{
2132	device_t parent;
2133
2134	parent = device_get_parent(child);
2135	if (parent == NULL) {
2136		*buf = '\0';
2137		return (0);
2138	}
2139	return (BUS_CHILD_LOCATION_STR(parent, child, buf, buflen));
2140}
2141
2142static int
2143root_print_child(device_t dev, device_t child)
2144{
2145	int	retval = 0;
2146
2147	retval += bus_print_child_header(dev, child);
2148	retval += printf("\n");
2149
2150	return (retval);
2151}
2152
2153static int
2154root_setup_intr(device_t dev, device_t child, driver_intr_t *intr, void *arg,
2155    void **cookiep)
2156{
2157	/*
2158	 * If an interrupt mapping gets to here something bad has happened.
2159	 */
2160	panic("root_setup_intr");
2161}
2162
2163/*
2164 * If we get here, assume that the device is permanant and really is
2165 * present in the system.  Removable bus drivers are expected to intercept
2166 * this call long before it gets here.  We return -1 so that drivers that
2167 * really care can check vs -1 or some ERRNO returned higher in the food
2168 * chain.
2169 */
2170static int
2171root_child_present(device_t dev, device_t child)
2172{
2173	return (-1);
2174}
2175
2176static kobj_method_t root_methods[] = {
2177	/* Device interface */
2178	KOBJMETHOD(device_shutdown,	bus_generic_shutdown),
2179	KOBJMETHOD(device_suspend,	bus_generic_suspend),
2180	KOBJMETHOD(device_resume,	bus_generic_resume),
2181
2182	/* Bus interface */
2183	KOBJMETHOD(bus_print_child,	root_print_child),
2184	KOBJMETHOD(bus_read_ivar,	bus_generic_read_ivar),
2185	KOBJMETHOD(bus_write_ivar,	bus_generic_write_ivar),
2186	KOBJMETHOD(bus_setup_intr,	root_setup_intr),
2187	KOBJMETHOD(bus_child_present,	root_child_present),
2188
2189	{ 0, 0 }
2190};
2191
2192static driver_t root_driver = {
2193	"root",
2194	root_methods,
2195	1,			/* no softc */
2196};
2197
2198device_t	root_bus;
2199devclass_t	root_devclass;
2200
2201static int
2202root_bus_module_handler(module_t mod, int what, void* arg)
2203{
2204	switch (what) {
2205	case MOD_LOAD:
2206		TAILQ_INIT(&bus_data_devices);
2207		kobj_class_compile((kobj_class_t) &root_driver);
2208		root_bus = make_device(NULL, "root", 0);
2209		root_bus->desc = "System root bus";
2210		kobj_init((kobj_t) root_bus, (kobj_class_t) &root_driver);
2211		root_bus->driver = &root_driver;
2212		root_bus->state = DS_ATTACHED;
2213		root_devclass = devclass_find_internal("root", FALSE);
2214		devinit();
2215		return (0);
2216
2217	case MOD_SHUTDOWN:
2218		device_shutdown(root_bus);
2219		return (0);
2220	}
2221
2222	return (0);
2223}
2224
2225static moduledata_t root_bus_mod = {
2226	"rootbus",
2227	root_bus_module_handler,
2228	0
2229};
2230DECLARE_MODULE(rootbus, root_bus_mod, SI_SUB_DRIVERS, SI_ORDER_FIRST);
2231
2232void
2233root_bus_configure(void)
2234{
2235	device_t dev;
2236
2237	PDEBUG(("."));
2238
2239	TAILQ_FOREACH(dev, &root_bus->children, link) {
2240		device_probe_and_attach(dev);
2241	}
2242}
2243
2244int
2245driver_module_handler(module_t mod, int what, void *arg)
2246{
2247	int error, i;
2248	struct driver_module_data *dmd;
2249	devclass_t bus_devclass;
2250
2251	dmd = (struct driver_module_data *)arg;
2252	bus_devclass = devclass_find_internal(dmd->dmd_busname, TRUE);
2253	error = 0;
2254
2255	switch (what) {
2256	case MOD_LOAD:
2257		if (dmd->dmd_chainevh)
2258			error = dmd->dmd_chainevh(mod,what,dmd->dmd_chainarg);
2259
2260		for (i = 0; !error && i < dmd->dmd_ndrivers; i++) {
2261			PDEBUG(("Loading module: driver %s on bus %s",
2262			    DRIVERNAME(dmd->dmd_drivers[i]), dmd->dmd_busname));
2263			error = devclass_add_driver(bus_devclass,
2264			    dmd->dmd_drivers[i]);
2265		}
2266		if (error)
2267			break;
2268
2269		/*
2270		 * The drivers loaded in this way are assumed to all
2271		 * implement the same devclass.
2272		 */
2273		*dmd->dmd_devclass =
2274		    devclass_find_internal(dmd->dmd_drivers[0]->name, TRUE);
2275		break;
2276
2277	case MOD_UNLOAD:
2278		for (i = 0; !error && i < dmd->dmd_ndrivers; i++) {
2279			PDEBUG(("Unloading module: driver %s from bus %s",
2280			    DRIVERNAME(dmd->dmd_drivers[i]),
2281			    dmd->dmd_busname));
2282			error = devclass_delete_driver(bus_devclass,
2283			    dmd->dmd_drivers[i]);
2284		}
2285
2286		if (!error && dmd->dmd_chainevh)
2287			error = dmd->dmd_chainevh(mod,what,dmd->dmd_chainarg);
2288		break;
2289	}
2290
2291	return (error);
2292}
2293
2294#ifdef BUS_DEBUG
2295
2296/* the _short versions avoid iteration by not calling anything that prints
2297 * more than oneliners. I love oneliners.
2298 */
2299
2300static void
2301print_device_short(device_t dev, int indent)
2302{
2303	if (!dev)
2304		return;
2305
2306	indentprintf(("device %d: <%s> %sparent,%schildren,%s%s%s%s,%sivars,%ssoftc,busy=%d\n",
2307	    dev->unit, dev->desc,
2308	    (dev->parent? "":"no "),
2309	    (TAILQ_EMPTY(&dev->children)? "no ":""),
2310	    (dev->flags&DF_ENABLED? "enabled,":"disabled,"),
2311	    (dev->flags&DF_FIXEDCLASS? "fixed,":""),
2312	    (dev->flags&DF_WILDCARD? "wildcard,":""),
2313	    (dev->flags&DF_DESCMALLOCED? "descmalloced,":""),
2314	    (dev->ivars? "":"no "),
2315	    (dev->softc? "":"no "),
2316	    dev->busy));
2317}
2318
2319static void
2320print_device(device_t dev, int indent)
2321{
2322	if (!dev)
2323		return;
2324
2325	print_device_short(dev, indent);
2326
2327	indentprintf(("Parent:\n"));
2328	print_device_short(dev->parent, indent+1);
2329	indentprintf(("Driver:\n"));
2330	print_driver_short(dev->driver, indent+1);
2331	indentprintf(("Devclass:\n"));
2332	print_devclass_short(dev->devclass, indent+1);
2333}
2334
2335void
2336print_device_tree_short(device_t dev, int indent)
2337/* print the device and all its children (indented) */
2338{
2339	device_t child;
2340
2341	if (!dev)
2342		return;
2343
2344	print_device_short(dev, indent);
2345
2346	TAILQ_FOREACH(child, &dev->children, link) {
2347		print_device_tree_short(child, indent+1);
2348	}
2349}
2350
2351void
2352print_device_tree(device_t dev, int indent)
2353/* print the device and all its children (indented) */
2354{
2355	device_t child;
2356
2357	if (!dev)
2358		return;
2359
2360	print_device(dev, indent);
2361
2362	TAILQ_FOREACH(child, &dev->children, link) {
2363		print_device_tree(child, indent+1);
2364	}
2365}
2366
2367static void
2368print_driver_short(driver_t *driver, int indent)
2369{
2370	if (!driver)
2371		return;
2372
2373	indentprintf(("driver %s: softc size = %d\n",
2374	    driver->name, driver->size));
2375}
2376
2377static void
2378print_driver(driver_t *driver, int indent)
2379{
2380	if (!driver)
2381		return;
2382
2383	print_driver_short(driver, indent);
2384}
2385
2386
2387static void
2388print_driver_list(driver_list_t drivers, int indent)
2389{
2390	driverlink_t driver;
2391
2392	TAILQ_FOREACH(driver, &drivers, link) {
2393		print_driver(driver->driver, indent);
2394	}
2395}
2396
2397static void
2398print_devclass_short(devclass_t dc, int indent)
2399{
2400	if ( !dc )
2401		return;
2402
2403	indentprintf(("devclass %s: max units = %d\n", dc->name, dc->maxunit));
2404}
2405
2406static void
2407print_devclass(devclass_t dc, int indent)
2408{
2409	int i;
2410
2411	if ( !dc )
2412		return;
2413
2414	print_devclass_short(dc, indent);
2415	indentprintf(("Drivers:\n"));
2416	print_driver_list(dc->drivers, indent+1);
2417
2418	indentprintf(("Devices:\n"));
2419	for (i = 0; i < dc->maxunit; i++)
2420		if (dc->devices[i])
2421			print_device(dc->devices[i], indent+1);
2422}
2423
2424void
2425print_devclass_list_short(void)
2426{
2427	devclass_t dc;
2428
2429	printf("Short listing of devclasses, drivers & devices:\n");
2430	TAILQ_FOREACH(dc, &devclasses, link) {
2431		print_devclass_short(dc, 0);
2432	}
2433}
2434
2435void
2436print_devclass_list(void)
2437{
2438	devclass_t dc;
2439
2440	printf("Full listing of devclasses, drivers & devices:\n");
2441	TAILQ_FOREACH(dc, &devclasses, link) {
2442		print_devclass(dc, 0);
2443	}
2444}
2445
2446#endif
2447
2448/*
2449 * User-space access to the device tree.
2450 *
2451 * We implement a small set of nodes:
2452 *
2453 * hw.bus			Single integer read method to obtain the
2454 *				current generation count.
2455 * hw.bus.devices		Reads the entire device tree in flat space.
2456 * hw.bus.rman			Resource manager interface
2457 *
2458 * We might like to add the ability to scan devclasses and/or drivers to
2459 * determine what else is currently loaded/available.
2460 */
2461SYSCTL_NODE(_hw, OID_AUTO, bus, CTLFLAG_RW, NULL, NULL);
2462
2463static int
2464sysctl_bus(SYSCTL_HANDLER_ARGS)
2465{
2466	struct u_businfo	ubus;
2467
2468	ubus.ub_version = BUS_USER_VERSION;
2469	ubus.ub_generation = bus_data_generation;
2470
2471	return (SYSCTL_OUT(req, &ubus, sizeof(ubus)));
2472}
2473SYSCTL_NODE(_hw_bus, OID_AUTO, info, CTLFLAG_RW, sysctl_bus,
2474    "bus-related data");
2475
2476static int
2477sysctl_devices(SYSCTL_HANDLER_ARGS)
2478{
2479	int			*name = (int *)arg1;
2480	u_int			namelen = arg2;
2481	int			index;
2482	struct device		*dev;
2483	struct u_device		udev;	/* XXX this is a bit big */
2484	int			error;
2485
2486	if (namelen != 2)
2487		return (EINVAL);
2488
2489	if (bus_data_generation_check(name[0]))
2490		return (EINVAL);
2491
2492	index = name[1];
2493
2494	/*
2495	 * Scan the list of devices, looking for the requested index.
2496	 */
2497	TAILQ_FOREACH(dev, &bus_data_devices, devlink) {
2498		if (index-- == 0)
2499			break;
2500	}
2501	if (dev == NULL)
2502		return (ENOENT);
2503
2504	/*
2505	 * Populate the return array.
2506	 */
2507	udev.dv_handle = (uintptr_t)dev;
2508	udev.dv_parent = (uintptr_t)dev->parent;
2509	if (dev->nameunit == NULL)
2510		udev.dv_name[0] = '\0';
2511	else
2512		strlcpy(udev.dv_name, dev->nameunit, sizeof(udev.dv_name));
2513
2514	if (dev->desc == NULL)
2515		udev.dv_desc[0] = '\0';
2516	else
2517		strlcpy(udev.dv_desc, dev->desc, sizeof(udev.dv_desc));
2518	if (dev->driver == NULL || dev->driver->name == NULL)
2519		udev.dv_drivername[0] = '\0';
2520	else
2521		strlcpy(udev.dv_drivername, dev->driver->name,
2522		    sizeof(udev.dv_drivername));
2523	udev.dv_pnpinfo[0] = '\0';
2524	udev.dv_location[0] = '\0';
2525	bus_child_pnpinfo_str(dev, udev.dv_pnpinfo, sizeof(udev.dv_pnpinfo));
2526	bus_child_location_str(dev, udev.dv_location, sizeof(udev.dv_location));
2527	udev.dv_devflags = dev->devflags;
2528	udev.dv_flags = dev->flags;
2529	udev.dv_state = dev->state;
2530	error = SYSCTL_OUT(req, &udev, sizeof(udev));
2531	return (error);
2532}
2533
2534SYSCTL_NODE(_hw_bus, OID_AUTO, devices, CTLFLAG_RD, sysctl_devices,
2535    "system device tree");
2536
2537/*
2538 * Sysctl interface for scanning the resource lists.
2539 *
2540 * We take two input parameters; the index into the list of resource
2541 * managers, and the resource offset into the list.
2542 */
2543static int
2544sysctl_rman(SYSCTL_HANDLER_ARGS)
2545{
2546	int			*name = (int *)arg1;
2547	u_int			namelen = arg2;
2548	int			rman_idx, res_idx;
2549	struct rman		*rm;
2550	struct resource		*res;
2551	struct u_rman		urm;
2552	struct u_resource	ures;
2553	int			error;
2554
2555	if (namelen != 3)
2556		return (EINVAL);
2557
2558	if (bus_data_generation_check(name[0]))
2559		return (EINVAL);
2560	rman_idx = name[1];
2561	res_idx = name[2];
2562
2563	/*
2564	 * Find the indexed resource manager
2565	 */
2566	TAILQ_FOREACH(rm, &rman_head, rm_link) {
2567		if (rman_idx-- == 0)
2568			break;
2569	}
2570	if (rm == NULL)
2571		return (ENOENT);
2572
2573	/*
2574	 * If the resource index is -1, we want details on the
2575	 * resource manager.
2576	 */
2577	if (res_idx == -1) {
2578		urm.rm_handle = (uintptr_t)rm;
2579		strlcpy(urm.rm_descr, rm->rm_descr, RM_TEXTLEN);
2580		urm.rm_start = rm->rm_start;
2581		urm.rm_size = rm->rm_end - rm->rm_start + 1;
2582		urm.rm_type = rm->rm_type;
2583
2584		error = SYSCTL_OUT(req, &urm, sizeof(urm));
2585		return (error);
2586	}
2587
2588	/*
2589	 * Find the indexed resource and return it.
2590	 */
2591	TAILQ_FOREACH(res, &rm->rm_list, r_link) {
2592		if (res_idx-- == 0) {
2593			ures.r_handle = (uintptr_t)res;
2594			ures.r_parent = (uintptr_t)res->r_rm;
2595			ures.r_device = (uintptr_t)res->r_dev;
2596			if (res->r_dev != NULL) {
2597				if (device_get_name(res->r_dev) != NULL) {
2598					snprintf(ures.r_devname, RM_TEXTLEN,
2599					    "%s%d",
2600					    device_get_name(res->r_dev),
2601					    device_get_unit(res->r_dev));
2602				} else {
2603					strlcpy(ures.r_devname, "nomatch",
2604					    RM_TEXTLEN);
2605				}
2606			} else {
2607				ures.r_devname[0] = '\0';
2608			}
2609			ures.r_start = res->r_start;
2610			ures.r_size = res->r_end - res->r_start + 1;
2611			ures.r_flags = res->r_flags;
2612
2613			error = SYSCTL_OUT(req, &ures, sizeof(ures));
2614			return (error);
2615		}
2616	}
2617	return (ENOENT);
2618}
2619
2620SYSCTL_NODE(_hw_bus, OID_AUTO, rman, CTLFLAG_RD, sysctl_rman,
2621    "kernel resource manager");
2622
2623int
2624bus_data_generation_check(int generation)
2625{
2626	if (generation != bus_data_generation)
2627		return (1);
2628
2629	/* XXX generate optimised lists here? */
2630	return (0);
2631}
2632
2633void
2634bus_data_generation_update(void)
2635{
2636	bus_data_generation++;
2637}
2638