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