subr_bus.c revision 144628
1/*-
2 * Copyright (c) 1997,1998,2003 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 144628 2005-04-04 15:37:59Z njl $");
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);
59SYSCTL_NODE(, OID_AUTO, dev, CTLFLAG_RW, NULL, NULL);
60
61/*
62 * Used to attach drivers to devclasses.
63 */
64typedef struct driverlink *driverlink_t;
65struct driverlink {
66	kobj_class_t	driver;
67	TAILQ_ENTRY(driverlink) link;	/* list of drivers in devclass */
68};
69
70/*
71 * Forward declarations
72 */
73typedef TAILQ_HEAD(devclass_list, devclass) devclass_list_t;
74typedef TAILQ_HEAD(driver_list, driverlink) driver_list_t;
75typedef TAILQ_HEAD(device_list, device) device_list_t;
76
77struct devclass {
78	TAILQ_ENTRY(devclass) link;
79	devclass_t	parent;		/* parent in devclass hierarchy */
80	driver_list_t	drivers;     /* bus devclasses store drivers for bus */
81	char		*name;
82	device_t	*devices;	/* array of devices indexed by unit */
83	int		maxunit;	/* size of devices array */
84
85	struct sysctl_ctx_list sysctl_ctx;
86	struct sysctl_oid *sysctl_tree;
87};
88
89/**
90 * @brief Implementation of device.
91 */
92struct device {
93	/*
94	 * A device is a kernel object. The first field must be the
95	 * current ops table for the object.
96	 */
97	KOBJ_FIELDS;
98
99	/*
100	 * Device hierarchy.
101	 */
102	TAILQ_ENTRY(device)	link;	/**< list of devices in parent */
103	TAILQ_ENTRY(device)	devlink; /**< global device list membership */
104	device_t	parent;		/**< parent of this device  */
105	device_list_t	children;	/**< list of child devices */
106
107	/*
108	 * Details of this device.
109	 */
110	driver_t	*driver;	/**< current driver */
111	devclass_t	devclass;	/**< current device class */
112	int		unit;		/**< current unit number */
113	char*		nameunit;	/**< name+unit e.g. foodev0 */
114	char*		desc;		/**< driver specific description */
115	int		busy;		/**< count of calls to device_busy() */
116	device_state_t	state;		/**< current device state  */
117	u_int32_t	devflags;	/**< api level flags for device_get_flags() */
118	u_short		flags;		/**< internal device flags  */
119#define	DF_ENABLED	1		/* device should be probed/attached */
120#define	DF_FIXEDCLASS	2		/* devclass specified at create time */
121#define	DF_WILDCARD	4		/* unit was originally wildcard */
122#define	DF_DESCMALLOCED	8		/* description was malloced */
123#define	DF_QUIET	16		/* don't print verbose attach message */
124#define	DF_DONENOMATCH	32		/* don't execute DEVICE_NOMATCH again */
125#define	DF_EXTERNALSOFTC 64		/* softc not allocated by us */
126#define	DF_REBID	128		/* Can rebid after attach */
127	u_char	order;			/**< order from device_add_child_ordered() */
128	u_char	pad;
129	void	*ivars;			/**< instance variables  */
130	void	*softc;			/**< current driver's variables  */
131
132	struct sysctl_ctx_list sysctl_ctx; /**< state for sysctl variables  */
133	struct sysctl_oid *sysctl_tree;	/**< state for sysctl variables */
134};
135
136static MALLOC_DEFINE(M_BUS, "bus", "Bus data structures");
137static MALLOC_DEFINE(M_BUS_SC, "bus-sc", "Bus data structures, softc");
138
139#ifdef BUS_DEBUG
140
141static int bus_debug = 1;
142TUNABLE_INT("bus.debug", &bus_debug);
143SYSCTL_INT(_debug, OID_AUTO, bus_debug, CTLFLAG_RW, &bus_debug, 0,
144    "Debug bus code");
145
146#define PDEBUG(a)	if (bus_debug) {printf("%s:%d: ", __func__, __LINE__), printf a; printf("\n");}
147#define DEVICENAME(d)	((d)? device_get_name(d): "no device")
148#define DRIVERNAME(d)	((d)? d->name : "no driver")
149#define DEVCLANAME(d)	((d)? d->name : "no devclass")
150
151/**
152 * Produce the indenting, indent*2 spaces plus a '.' ahead of that to
153 * prevent syslog from deleting initial spaces
154 */
155#define indentprintf(p)	do { int iJ; printf("."); for (iJ=0; iJ<indent; iJ++) printf("  "); printf p ; } while (0)
156
157static void print_device_short(device_t dev, int indent);
158static void print_device(device_t dev, int indent);
159void print_device_tree_short(device_t dev, int indent);
160void print_device_tree(device_t dev, int indent);
161static void print_driver_short(driver_t *driver, int indent);
162static void print_driver(driver_t *driver, int indent);
163static void print_driver_list(driver_list_t drivers, int indent);
164static void print_devclass_short(devclass_t dc, int indent);
165static void print_devclass(devclass_t dc, int indent);
166void print_devclass_list_short(void);
167void print_devclass_list(void);
168
169#else
170/* Make the compiler ignore the function calls */
171#define PDEBUG(a)			/* nop */
172#define DEVICENAME(d)			/* nop */
173#define DRIVERNAME(d)			/* nop */
174#define DEVCLANAME(d)			/* nop */
175
176#define print_device_short(d,i)		/* nop */
177#define print_device(d,i)		/* nop */
178#define print_device_tree_short(d,i)	/* nop */
179#define print_device_tree(d,i)		/* nop */
180#define print_driver_short(d,i)		/* nop */
181#define print_driver(d,i)		/* nop */
182#define print_driver_list(d,i)		/* nop */
183#define print_devclass_short(d,i)	/* nop */
184#define print_devclass(d,i)		/* nop */
185#define print_devclass_list_short()	/* nop */
186#define print_devclass_list()		/* nop */
187#endif
188
189/*
190 * dev sysctl tree
191 */
192
193enum {
194	DEVCLASS_SYSCTL_PARENT,
195};
196
197static int
198devclass_sysctl_handler(SYSCTL_HANDLER_ARGS)
199{
200	devclass_t dc = (devclass_t)arg1;
201	const char *value;
202
203	switch (arg2) {
204	case DEVCLASS_SYSCTL_PARENT:
205		value = dc->parent ? dc->parent->name : "";
206		break;
207	default:
208		return (EINVAL);
209	}
210	return (SYSCTL_OUT(req, value, strlen(value)));
211}
212
213static void
214devclass_sysctl_init(devclass_t dc)
215{
216
217	if (dc->sysctl_tree != NULL)
218		return;
219	sysctl_ctx_init(&dc->sysctl_ctx);
220	dc->sysctl_tree = SYSCTL_ADD_NODE(&dc->sysctl_ctx,
221	    SYSCTL_STATIC_CHILDREN(_dev), OID_AUTO, dc->name,
222	    CTLFLAG_RD, 0, "");
223	SYSCTL_ADD_PROC(&dc->sysctl_ctx, SYSCTL_CHILDREN(dc->sysctl_tree),
224	    OID_AUTO, "%parent", CTLFLAG_RD,
225	    dc, DEVCLASS_SYSCTL_PARENT, devclass_sysctl_handler, "A",
226	    "parent class");
227}
228
229enum {
230	DEVICE_SYSCTL_DESC,
231	DEVICE_SYSCTL_DRIVER,
232	DEVICE_SYSCTL_LOCATION,
233	DEVICE_SYSCTL_PNPINFO,
234	DEVICE_SYSCTL_PARENT,
235};
236
237static int
238device_sysctl_handler(SYSCTL_HANDLER_ARGS)
239{
240	device_t dev = (device_t)arg1;
241	const char *value;
242	char *buf;
243	int error;
244
245	buf = NULL;
246	switch (arg2) {
247	case DEVICE_SYSCTL_DESC:
248		value = dev->desc ? dev->desc : "";
249		break;
250	case DEVICE_SYSCTL_DRIVER:
251		value = dev->driver ? dev->driver->name : "";
252		break;
253	case DEVICE_SYSCTL_LOCATION:
254		value = buf = malloc(1024, M_BUS, M_WAITOK | M_ZERO);
255		bus_child_location_str(dev, buf, 1024);
256		break;
257	case DEVICE_SYSCTL_PNPINFO:
258		value = buf = malloc(1024, M_BUS, M_WAITOK | M_ZERO);
259		bus_child_pnpinfo_str(dev, buf, 1024);
260		break;
261	case DEVICE_SYSCTL_PARENT:
262		value = dev->parent ? dev->parent->nameunit : "";
263		break;
264	default:
265		return (EINVAL);
266	}
267	error = SYSCTL_OUT(req, value, strlen(value));
268	if (buf != NULL)
269		free(buf, M_BUS);
270	return (error);
271}
272
273static void
274device_sysctl_init(device_t dev)
275{
276	devclass_t dc = dev->devclass;
277
278	if (dev->sysctl_tree != NULL)
279		return;
280	devclass_sysctl_init(dc);
281	sysctl_ctx_init(&dev->sysctl_ctx);
282	dev->sysctl_tree = SYSCTL_ADD_NODE(&dev->sysctl_ctx,
283	    SYSCTL_CHILDREN(dc->sysctl_tree), OID_AUTO,
284	    dev->nameunit + strlen(dc->name),
285	    CTLFLAG_RD, 0, "");
286	SYSCTL_ADD_PROC(&dev->sysctl_ctx, SYSCTL_CHILDREN(dev->sysctl_tree),
287	    OID_AUTO, "%desc", CTLFLAG_RD,
288	    dev, DEVICE_SYSCTL_DESC, device_sysctl_handler, "A",
289	    "device description");
290	SYSCTL_ADD_PROC(&dev->sysctl_ctx, SYSCTL_CHILDREN(dev->sysctl_tree),
291	    OID_AUTO, "%driver", CTLFLAG_RD,
292	    dev, DEVICE_SYSCTL_DRIVER, device_sysctl_handler, "A",
293	    "device driver name");
294	SYSCTL_ADD_PROC(&dev->sysctl_ctx, SYSCTL_CHILDREN(dev->sysctl_tree),
295	    OID_AUTO, "%location", CTLFLAG_RD,
296	    dev, DEVICE_SYSCTL_LOCATION, device_sysctl_handler, "A",
297	    "device location relative to parent");
298	SYSCTL_ADD_PROC(&dev->sysctl_ctx, SYSCTL_CHILDREN(dev->sysctl_tree),
299	    OID_AUTO, "%pnpinfo", CTLFLAG_RD,
300	    dev, DEVICE_SYSCTL_PNPINFO, device_sysctl_handler, "A",
301	    "device identification");
302	SYSCTL_ADD_PROC(&dev->sysctl_ctx, SYSCTL_CHILDREN(dev->sysctl_tree),
303	    OID_AUTO, "%parent", CTLFLAG_RD,
304	    dev, DEVICE_SYSCTL_PARENT, device_sysctl_handler, "A",
305	    "parent device");
306}
307
308static void
309device_sysctl_fini(device_t dev)
310{
311	if (dev->sysctl_tree == NULL)
312		return;
313	sysctl_ctx_free(&dev->sysctl_ctx);
314	dev->sysctl_tree = NULL;
315}
316
317/*
318 * /dev/devctl implementation
319 */
320
321/*
322 * This design allows only one reader for /dev/devctl.  This is not desirable
323 * in the long run, but will get a lot of hair out of this implementation.
324 * Maybe we should make this device a clonable device.
325 *
326 * Also note: we specifically do not attach a device to the device_t tree
327 * to avoid potential chicken and egg problems.  One could argue that all
328 * of this belongs to the root node.  One could also further argue that the
329 * sysctl interface that we have not might more properly be an ioctl
330 * interface, but at this stage of the game, I'm not inclined to rock that
331 * boat.
332 *
333 * I'm also not sure that the SIGIO support is done correctly or not, as
334 * I copied it from a driver that had SIGIO support that likely hasn't been
335 * tested since 3.4 or 2.2.8!
336 */
337
338static int sysctl_devctl_disable(SYSCTL_HANDLER_ARGS);
339static int devctl_disable = 0;
340TUNABLE_INT("hw.bus.devctl_disable", &devctl_disable);
341SYSCTL_PROC(_hw_bus, OID_AUTO, devctl_disable, CTLTYPE_INT | CTLFLAG_RW, 0, 0,
342    sysctl_devctl_disable, "I", "devctl disable");
343
344static d_open_t		devopen;
345static d_close_t	devclose;
346static d_read_t		devread;
347static d_ioctl_t	devioctl;
348static d_poll_t		devpoll;
349
350static struct cdevsw dev_cdevsw = {
351	.d_version =	D_VERSION,
352	.d_flags =	D_NEEDGIANT,
353	.d_open =	devopen,
354	.d_close =	devclose,
355	.d_read =	devread,
356	.d_ioctl =	devioctl,
357	.d_poll =	devpoll,
358	.d_name =	"devctl",
359};
360
361struct dev_event_info
362{
363	char *dei_data;
364	TAILQ_ENTRY(dev_event_info) dei_link;
365};
366
367TAILQ_HEAD(devq, dev_event_info);
368
369static struct dev_softc
370{
371	int	inuse;
372	int	nonblock;
373	struct mtx mtx;
374	struct cv cv;
375	struct selinfo sel;
376	struct devq devq;
377	struct proc *async_proc;
378} devsoftc;
379
380static struct cdev *devctl_dev;
381
382static void
383devinit(void)
384{
385	devctl_dev = make_dev(&dev_cdevsw, 0, UID_ROOT, GID_WHEEL, 0600,
386	    "devctl");
387	mtx_init(&devsoftc.mtx, "dev mtx", "devd", MTX_DEF);
388	cv_init(&devsoftc.cv, "dev cv");
389	TAILQ_INIT(&devsoftc.devq);
390}
391
392static int
393devopen(struct cdev *dev, int oflags, int devtype, d_thread_t *td)
394{
395	if (devsoftc.inuse)
396		return (EBUSY);
397	/* move to init */
398	devsoftc.inuse = 1;
399	devsoftc.nonblock = 0;
400	devsoftc.async_proc = NULL;
401	return (0);
402}
403
404static int
405devclose(struct cdev *dev, int fflag, int devtype, d_thread_t *td)
406{
407	devsoftc.inuse = 0;
408	mtx_lock(&devsoftc.mtx);
409	cv_broadcast(&devsoftc.cv);
410	mtx_unlock(&devsoftc.mtx);
411
412	return (0);
413}
414
415/*
416 * The read channel for this device is used to report changes to
417 * userland in realtime.  We are required to free the data as well as
418 * the n1 object because we allocate them separately.  Also note that
419 * we return one record at a time.  If you try to read this device a
420 * character at a time, you will loose the rest of the data.  Listening
421 * programs are expected to cope.
422 */
423static int
424devread(struct cdev *dev, struct uio *uio, int ioflag)
425{
426	struct dev_event_info *n1;
427	int rv;
428
429	mtx_lock(&devsoftc.mtx);
430	while (TAILQ_EMPTY(&devsoftc.devq)) {
431		if (devsoftc.nonblock) {
432			mtx_unlock(&devsoftc.mtx);
433			return (EAGAIN);
434		}
435		rv = cv_wait_sig(&devsoftc.cv, &devsoftc.mtx);
436		if (rv) {
437			/*
438			 * Need to translate ERESTART to EINTR here? -- jake
439			 */
440			mtx_unlock(&devsoftc.mtx);
441			return (rv);
442		}
443	}
444	n1 = TAILQ_FIRST(&devsoftc.devq);
445	TAILQ_REMOVE(&devsoftc.devq, n1, dei_link);
446	mtx_unlock(&devsoftc.mtx);
447	rv = uiomove(n1->dei_data, strlen(n1->dei_data), uio);
448	free(n1->dei_data, M_BUS);
449	free(n1, M_BUS);
450	return (rv);
451}
452
453static	int
454devioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag, d_thread_t *td)
455{
456	switch (cmd) {
457
458	case FIONBIO:
459		if (*(int*)data)
460			devsoftc.nonblock = 1;
461		else
462			devsoftc.nonblock = 0;
463		return (0);
464	case FIOASYNC:
465		if (*(int*)data)
466			devsoftc.async_proc = td->td_proc;
467		else
468			devsoftc.async_proc = NULL;
469		return (0);
470
471		/* (un)Support for other fcntl() calls. */
472	case FIOCLEX:
473	case FIONCLEX:
474	case FIONREAD:
475	case FIOSETOWN:
476	case FIOGETOWN:
477	default:
478		break;
479	}
480	return (ENOTTY);
481}
482
483static	int
484devpoll(struct cdev *dev, int events, d_thread_t *td)
485{
486	int	revents = 0;
487
488	mtx_lock(&devsoftc.mtx);
489	if (events & (POLLIN | POLLRDNORM)) {
490		if (!TAILQ_EMPTY(&devsoftc.devq))
491			revents = events & (POLLIN | POLLRDNORM);
492		else
493			selrecord(td, &devsoftc.sel);
494	}
495	mtx_unlock(&devsoftc.mtx);
496
497	return (revents);
498}
499
500/**
501 * @brief Queue data to be read from the devctl device
502 *
503 * Generic interface to queue data to the devctl device.  It is
504 * assumed that @p data is properly formatted.  It is further assumed
505 * that @p data is allocated using the M_BUS malloc type.
506 */
507void
508devctl_queue_data(char *data)
509{
510	struct dev_event_info *n1 = NULL;
511	struct proc *p;
512
513	n1 = malloc(sizeof(*n1), M_BUS, M_NOWAIT);
514	if (n1 == NULL)
515		return;
516	n1->dei_data = data;
517	mtx_lock(&devsoftc.mtx);
518	TAILQ_INSERT_TAIL(&devsoftc.devq, n1, dei_link);
519	cv_broadcast(&devsoftc.cv);
520	mtx_unlock(&devsoftc.mtx);
521	selwakeup(&devsoftc.sel);
522	p = devsoftc.async_proc;
523	if (p != NULL) {
524		PROC_LOCK(p);
525		psignal(p, SIGIO);
526		PROC_UNLOCK(p);
527	}
528}
529
530/**
531 * @brief Send a 'notification' to userland, using standard ways
532 */
533void
534devctl_notify(const char *system, const char *subsystem, const char *type,
535    const char *data)
536{
537	int len = 0;
538	char *msg;
539
540	if (system == NULL)
541		return;		/* BOGUS!  Must specify system. */
542	if (subsystem == NULL)
543		return;		/* BOGUS!  Must specify subsystem. */
544	if (type == NULL)
545		return;		/* BOGUS!  Must specify type. */
546	len += strlen(" system=") + strlen(system);
547	len += strlen(" subsystem=") + strlen(subsystem);
548	len += strlen(" type=") + strlen(type);
549	/* add in the data message plus newline. */
550	if (data != NULL)
551		len += strlen(data);
552	len += 3;	/* '!', '\n', and NUL */
553	msg = malloc(len, M_BUS, M_NOWAIT);
554	if (msg == NULL)
555		return;		/* Drop it on the floor */
556	snprintf(msg, len, "!system=%s subsystem=%s type=%s %s\n", system,
557	    subsystem, type, data);
558	devctl_queue_data(msg);
559}
560
561/*
562 * Common routine that tries to make sending messages as easy as possible.
563 * We allocate memory for the data, copy strings into that, but do not
564 * free it unless there's an error.  The dequeue part of the driver should
565 * free the data.  We don't send data when the device is disabled.  We do
566 * send data, even when we have no listeners, because we wish to avoid
567 * races relating to startup and restart of listening applications.
568 *
569 * devaddq is designed to string together the type of event, with the
570 * object of that event, plus the plug and play info and location info
571 * for that event.  This is likely most useful for devices, but less
572 * useful for other consumers of this interface.  Those should use
573 * the devctl_queue_data() interface instead.
574 */
575static void
576devaddq(const char *type, const char *what, device_t dev)
577{
578	char *data = NULL;
579	char *loc = NULL;
580	char *pnp = NULL;
581	const char *parstr;
582
583	if (devctl_disable)
584		return;
585	data = malloc(1024, M_BUS, M_NOWAIT);
586	if (data == NULL)
587		goto bad;
588
589	/* get the bus specific location of this device */
590	loc = malloc(1024, M_BUS, M_NOWAIT);
591	if (loc == NULL)
592		goto bad;
593	*loc = '\0';
594	bus_child_location_str(dev, loc, 1024);
595
596	/* Get the bus specific pnp info of this device */
597	pnp = malloc(1024, M_BUS, M_NOWAIT);
598	if (pnp == NULL)
599		goto bad;
600	*pnp = '\0';
601	bus_child_pnpinfo_str(dev, pnp, 1024);
602
603	/* Get the parent of this device, or / if high enough in the tree. */
604	if (device_get_parent(dev) == NULL)
605		parstr = ".";	/* Or '/' ? */
606	else
607		parstr = device_get_nameunit(device_get_parent(dev));
608	/* String it all together. */
609	snprintf(data, 1024, "%s%s at %s %s on %s\n", type, what, loc, pnp,
610	  parstr);
611	free(loc, M_BUS);
612	free(pnp, M_BUS);
613	devctl_queue_data(data);
614	return;
615bad:
616	free(pnp, M_BUS);
617	free(loc, M_BUS);
618	free(data, M_BUS);
619	return;
620}
621
622/*
623 * A device was added to the tree.  We are called just after it successfully
624 * attaches (that is, probe and attach success for this device).  No call
625 * is made if a device is merely parented into the tree.  See devnomatch
626 * if probe fails.  If attach fails, no notification is sent (but maybe
627 * we should have a different message for this).
628 */
629static void
630devadded(device_t dev)
631{
632	char *pnp = NULL;
633	char *tmp = NULL;
634
635	pnp = malloc(1024, M_BUS, M_NOWAIT);
636	if (pnp == NULL)
637		goto fail;
638	tmp = malloc(1024, M_BUS, M_NOWAIT);
639	if (tmp == NULL)
640		goto fail;
641	*pnp = '\0';
642	bus_child_pnpinfo_str(dev, pnp, 1024);
643	snprintf(tmp, 1024, "%s %s", device_get_nameunit(dev), pnp);
644	devaddq("+", tmp, dev);
645fail:
646	if (pnp != NULL)
647		free(pnp, M_BUS);
648	if (tmp != NULL)
649		free(tmp, M_BUS);
650	return;
651}
652
653/*
654 * A device was removed from the tree.  We are called just before this
655 * happens.
656 */
657static void
658devremoved(device_t dev)
659{
660	char *pnp = NULL;
661	char *tmp = NULL;
662
663	pnp = malloc(1024, M_BUS, M_NOWAIT);
664	if (pnp == NULL)
665		goto fail;
666	tmp = malloc(1024, M_BUS, M_NOWAIT);
667	if (tmp == NULL)
668		goto fail;
669	*pnp = '\0';
670	bus_child_pnpinfo_str(dev, pnp, 1024);
671	snprintf(tmp, 1024, "%s %s", device_get_nameunit(dev), pnp);
672	devaddq("-", tmp, dev);
673fail:
674	if (pnp != NULL)
675		free(pnp, M_BUS);
676	if (tmp != NULL)
677		free(tmp, M_BUS);
678	return;
679}
680
681/*
682 * Called when there's no match for this device.  This is only called
683 * the first time that no match happens, so we don't keep getitng this
684 * message.  Should that prove to be undesirable, we can change it.
685 * This is called when all drivers that can attach to a given bus
686 * decline to accept this device.  Other errrors may not be detected.
687 */
688static void
689devnomatch(device_t dev)
690{
691	devaddq("?", "", dev);
692}
693
694static int
695sysctl_devctl_disable(SYSCTL_HANDLER_ARGS)
696{
697	struct dev_event_info *n1;
698	int dis, error;
699
700	dis = devctl_disable;
701	error = sysctl_handle_int(oidp, &dis, 0, req);
702	if (error || !req->newptr)
703		return (error);
704	mtx_lock(&devsoftc.mtx);
705	devctl_disable = dis;
706	if (dis) {
707		while (!TAILQ_EMPTY(&devsoftc.devq)) {
708			n1 = TAILQ_FIRST(&devsoftc.devq);
709			TAILQ_REMOVE(&devsoftc.devq, n1, dei_link);
710			free(n1->dei_data, M_BUS);
711			free(n1, M_BUS);
712		}
713	}
714	mtx_unlock(&devsoftc.mtx);
715	return (0);
716}
717
718/* End of /dev/devctl code */
719
720TAILQ_HEAD(,device)	bus_data_devices;
721static int bus_data_generation = 1;
722
723kobj_method_t null_methods[] = {
724	{ 0, 0 }
725};
726
727DEFINE_CLASS(null, null_methods, 0);
728
729/*
730 * Devclass implementation
731 */
732
733static devclass_list_t devclasses = TAILQ_HEAD_INITIALIZER(devclasses);
734
735
736/**
737 * @internal
738 * @brief Find or create a device class
739 *
740 * If a device class with the name @p classname exists, return it,
741 * otherwise if @p create is non-zero create and return a new device
742 * class.
743 *
744 * If @p parentname is non-NULL, the parent of the devclass is set to
745 * the devclass of that name.
746 *
747 * @param classname	the devclass name to find or create
748 * @param parentname	the parent devclass name or @c NULL
749 * @param create	non-zero to create a devclass
750 */
751static devclass_t
752devclass_find_internal(const char *classname, const char *parentname,
753		       int create)
754{
755	devclass_t dc;
756
757	PDEBUG(("looking for %s", classname));
758	if (!classname)
759		return (NULL);
760
761	TAILQ_FOREACH(dc, &devclasses, link) {
762		if (!strcmp(dc->name, classname))
763			break;
764	}
765
766	if (create && !dc) {
767		PDEBUG(("creating %s", classname));
768		dc = malloc(sizeof(struct devclass) + strlen(classname) + 1,
769		    M_BUS, M_NOWAIT|M_ZERO);
770		if (!dc)
771			return (NULL);
772		dc->parent = NULL;
773		dc->name = (char*) (dc + 1);
774		strcpy(dc->name, classname);
775		TAILQ_INIT(&dc->drivers);
776		TAILQ_INSERT_TAIL(&devclasses, dc, link);
777
778		bus_data_generation_update();
779	}
780	if (parentname && dc && !dc->parent) {
781		dc->parent = devclass_find_internal(parentname, 0, FALSE);
782	}
783
784	return (dc);
785}
786
787/**
788 * @brief Create a device class
789 *
790 * If a device class with the name @p classname exists, return it,
791 * otherwise create and return a new device class.
792 *
793 * @param classname	the devclass name to find or create
794 */
795devclass_t
796devclass_create(const char *classname)
797{
798	return (devclass_find_internal(classname, 0, TRUE));
799}
800
801/**
802 * @brief Find a device class
803 *
804 * If a device class with the name @p classname exists, return it,
805 * otherwise return @c NULL.
806 *
807 * @param classname	the devclass name to find
808 */
809devclass_t
810devclass_find(const char *classname)
811{
812	return (devclass_find_internal(classname, 0, FALSE));
813}
814
815/**
816 * @brief Add a device driver to a device class
817 *
818 * Add a device driver to a devclass. This is normally called
819 * automatically by DRIVER_MODULE(). The BUS_DRIVER_ADDED() method of
820 * all devices in the devclass will be called to allow them to attempt
821 * to re-probe any unmatched children.
822 *
823 * @param dc		the devclass to edit
824 * @param driver	the driver to register
825 */
826int
827devclass_add_driver(devclass_t dc, driver_t *driver)
828{
829	driverlink_t dl;
830	int i;
831
832	PDEBUG(("%s", DRIVERNAME(driver)));
833
834	dl = malloc(sizeof *dl, M_BUS, M_NOWAIT|M_ZERO);
835	if (!dl)
836		return (ENOMEM);
837
838	/*
839	 * Compile the driver's methods. Also increase the reference count
840	 * so that the class doesn't get freed when the last instance
841	 * goes. This means we can safely use static methods and avoids a
842	 * double-free in devclass_delete_driver.
843	 */
844	kobj_class_compile((kobj_class_t) driver);
845
846	/*
847	 * Make sure the devclass which the driver is implementing exists.
848	 */
849	devclass_find_internal(driver->name, 0, TRUE);
850
851	dl->driver = driver;
852	TAILQ_INSERT_TAIL(&dc->drivers, dl, link);
853	driver->refs++;		/* XXX: kobj_mtx */
854
855	/*
856	 * Call BUS_DRIVER_ADDED for any existing busses in this class.
857	 */
858	for (i = 0; i < dc->maxunit; i++)
859		if (dc->devices[i])
860			BUS_DRIVER_ADDED(dc->devices[i], driver);
861
862	bus_data_generation_update();
863	return (0);
864}
865
866/**
867 * @brief Delete a device driver from a device class
868 *
869 * Delete a device driver from a devclass. This is normally called
870 * automatically by DRIVER_MODULE().
871 *
872 * If the driver is currently attached to any devices,
873 * devclass_delete_driver() will first attempt to detach from each
874 * device. If one of the detach calls fails, the driver will not be
875 * deleted.
876 *
877 * @param dc		the devclass to edit
878 * @param driver	the driver to unregister
879 */
880int
881devclass_delete_driver(devclass_t busclass, driver_t *driver)
882{
883	devclass_t dc = devclass_find(driver->name);
884	driverlink_t dl;
885	device_t dev;
886	int i;
887	int error;
888
889	PDEBUG(("%s from devclass %s", driver->name, DEVCLANAME(busclass)));
890
891	if (!dc)
892		return (0);
893
894	/*
895	 * Find the link structure in the bus' list of drivers.
896	 */
897	TAILQ_FOREACH(dl, &busclass->drivers, link) {
898		if (dl->driver == driver)
899			break;
900	}
901
902	if (!dl) {
903		PDEBUG(("%s not found in %s list", driver->name,
904		    busclass->name));
905		return (ENOENT);
906	}
907
908	/*
909	 * Disassociate from any devices.  We iterate through all the
910	 * devices in the devclass of the driver and detach any which are
911	 * using the driver and which have a parent in the devclass which
912	 * we are deleting from.
913	 *
914	 * Note that since a driver can be in multiple devclasses, we
915	 * should not detach devices which are not children of devices in
916	 * the affected devclass.
917	 */
918	for (i = 0; i < dc->maxunit; i++) {
919		if (dc->devices[i]) {
920			dev = dc->devices[i];
921			if (dev->driver == driver && dev->parent &&
922			    dev->parent->devclass == busclass) {
923				if ((error = device_detach(dev)) != 0)
924					return (error);
925				device_set_driver(dev, NULL);
926			}
927		}
928	}
929
930	TAILQ_REMOVE(&busclass->drivers, dl, link);
931	free(dl, M_BUS);
932
933	/* XXX: kobj_mtx */
934	driver->refs--;
935	if (driver->refs == 0)
936		kobj_class_free((kobj_class_t) driver);
937
938	bus_data_generation_update();
939	return (0);
940}
941
942/**
943 * @brief Quiesces a set of device drivers from a device class
944 *
945 * Quiesce a device driver from a devclass. This is normally called
946 * automatically by DRIVER_MODULE().
947 *
948 * If the driver is currently attached to any devices,
949 * devclass_quiesece_driver() will first attempt to quiesce each
950 * device.
951 *
952 * @param dc		the devclass to edit
953 * @param driver	the driver to unregister
954 */
955int
956devclass_quiesce_driver(devclass_t busclass, driver_t *driver)
957{
958	devclass_t dc = devclass_find(driver->name);
959	driverlink_t dl;
960	device_t dev;
961	int i;
962	int error;
963
964	PDEBUG(("%s from devclass %s", driver->name, DEVCLANAME(busclass)));
965
966	if (!dc)
967		return (0);
968
969	/*
970	 * Find the link structure in the bus' list of drivers.
971	 */
972	TAILQ_FOREACH(dl, &busclass->drivers, link) {
973		if (dl->driver == driver)
974			break;
975	}
976
977	if (!dl) {
978		PDEBUG(("%s not found in %s list", driver->name,
979		    busclass->name));
980		return (ENOENT);
981	}
982
983	/*
984	 * Quiesce all devices.  We iterate through all the devices in
985	 * the devclass of the driver and quiesce any which are using
986	 * the driver and which have a parent in the devclass which we
987	 * are quiescing.
988	 *
989	 * Note that since a driver can be in multiple devclasses, we
990	 * should not quiesce devices which are not children of
991	 * devices in the affected devclass.
992	 */
993	for (i = 0; i < dc->maxunit; i++) {
994		if (dc->devices[i]) {
995			dev = dc->devices[i];
996			if (dev->driver == driver && dev->parent &&
997			    dev->parent->devclass == busclass) {
998				if ((error = device_quiesce(dev)) != 0)
999					return (error);
1000			}
1001		}
1002	}
1003
1004	return (0);
1005}
1006
1007/**
1008 * @internal
1009 */
1010static driverlink_t
1011devclass_find_driver_internal(devclass_t dc, const char *classname)
1012{
1013	driverlink_t dl;
1014
1015	PDEBUG(("%s in devclass %s", classname, DEVCLANAME(dc)));
1016
1017	TAILQ_FOREACH(dl, &dc->drivers, link) {
1018		if (!strcmp(dl->driver->name, classname))
1019			return (dl);
1020	}
1021
1022	PDEBUG(("not found"));
1023	return (NULL);
1024}
1025
1026/**
1027 * @brief Search a devclass for a driver
1028 *
1029 * This function searches the devclass's list of drivers and returns
1030 * the first driver whose name is @p classname or @c NULL if there is
1031 * no driver of that name.
1032 *
1033 * @param dc		the devclass to search
1034 * @param classname	the driver name to search for
1035 */
1036kobj_class_t
1037devclass_find_driver(devclass_t dc, const char *classname)
1038{
1039	driverlink_t dl;
1040
1041	dl = devclass_find_driver_internal(dc, classname);
1042	if (dl)
1043		return (dl->driver);
1044	return (NULL);
1045}
1046
1047/**
1048 * @brief Return the name of the devclass
1049 */
1050const char *
1051devclass_get_name(devclass_t dc)
1052{
1053	return (dc->name);
1054}
1055
1056/**
1057 * @brief Find a device given a unit number
1058 *
1059 * @param dc		the devclass to search
1060 * @param unit		the unit number to search for
1061 *
1062 * @returns		the device with the given unit number or @c
1063 *			NULL if there is no such device
1064 */
1065device_t
1066devclass_get_device(devclass_t dc, int unit)
1067{
1068	if (dc == NULL || unit < 0 || unit >= dc->maxunit)
1069		return (NULL);
1070	return (dc->devices[unit]);
1071}
1072
1073/**
1074 * @brief Find the softc field of a device given a unit number
1075 *
1076 * @param dc		the devclass to search
1077 * @param unit		the unit number to search for
1078 *
1079 * @returns		the softc field of the device with the given
1080 *			unit number or @c NULL if there is no such
1081 *			device
1082 */
1083void *
1084devclass_get_softc(devclass_t dc, int unit)
1085{
1086	device_t dev;
1087
1088	dev = devclass_get_device(dc, unit);
1089	if (!dev)
1090		return (NULL);
1091
1092	return (device_get_softc(dev));
1093}
1094
1095/**
1096 * @brief Get a list of devices in the devclass
1097 *
1098 * An array containing a list of all the devices in the given devclass
1099 * is allocated and returned in @p *devlistp. The number of devices
1100 * in the array is returned in @p *devcountp. The caller should free
1101 * the array using @c free(p, M_TEMP).
1102 *
1103 * @param dc		the devclass to examine
1104 * @param devlistp	points at location for array pointer return
1105 *			value
1106 * @param devcountp	points at location for array size return value
1107 *
1108 * @retval 0		success
1109 * @retval ENOMEM	the array allocation failed
1110 */
1111int
1112devclass_get_devices(devclass_t dc, device_t **devlistp, int *devcountp)
1113{
1114	int count, i;
1115	device_t *list;
1116
1117	count = devclass_get_count(dc);
1118	list = malloc(count * sizeof(device_t), M_TEMP, M_NOWAIT|M_ZERO);
1119	if (!list)
1120		return (ENOMEM);
1121
1122	count = 0;
1123	for (i = 0; i < dc->maxunit; i++) {
1124		if (dc->devices[i]) {
1125			list[count] = dc->devices[i];
1126			count++;
1127		}
1128	}
1129
1130	*devlistp = list;
1131	*devcountp = count;
1132
1133	return (0);
1134}
1135
1136/**
1137 * @brief Get a list of drivers in the devclass
1138 *
1139 * An array containing a list of pointers to all the drivers in the
1140 * given devclass is allocated and returned in @p *listp.  The number
1141 * of drivers in the array is returned in @p *countp. The caller should
1142 * free the array using @c free(p, M_TEMP).
1143 *
1144 * @param dc		the devclass to examine
1145 * @param listp		gives location for array pointer return value
1146 * @param countp	gives location for number of array elements
1147 *			return value
1148 *
1149 * @retval 0		success
1150 * @retval ENOMEM	the array allocation failed
1151 */
1152int
1153devclass_get_drivers(devclass_t dc, driver_t ***listp, int *countp)
1154{
1155	driverlink_t dl;
1156	driver_t **list;
1157	int count;
1158
1159	count = 0;
1160	TAILQ_FOREACH(dl, &dc->drivers, link)
1161		count++;
1162	list = malloc(count * sizeof(driver_t *), M_TEMP, M_NOWAIT);
1163	if (list == NULL)
1164		return (ENOMEM);
1165
1166	count = 0;
1167	TAILQ_FOREACH(dl, &dc->drivers, link) {
1168		list[count] = dl->driver;
1169		count++;
1170	}
1171	*listp = list;
1172	*countp = count;
1173
1174	return (0);
1175}
1176
1177/**
1178 * @brief Get the number of devices in a devclass
1179 *
1180 * @param dc		the devclass to examine
1181 */
1182int
1183devclass_get_count(devclass_t dc)
1184{
1185	int count, i;
1186
1187	count = 0;
1188	for (i = 0; i < dc->maxunit; i++)
1189		if (dc->devices[i])
1190			count++;
1191	return (count);
1192}
1193
1194/**
1195 * @brief Get the maximum unit number used in a devclass
1196 *
1197 * Note that this is one greater than the highest currently-allocated
1198 * unit.
1199 *
1200 * @param dc		the devclass to examine
1201 */
1202int
1203devclass_get_maxunit(devclass_t dc)
1204{
1205	return (dc->maxunit);
1206}
1207
1208/**
1209 * @brief Find a free unit number in a devclass
1210 *
1211 * This function searches for the first unused unit number greater
1212 * that or equal to @p unit.
1213 *
1214 * @param dc		the devclass to examine
1215 * @param unit		the first unit number to check
1216 */
1217int
1218devclass_find_free_unit(devclass_t dc, int unit)
1219{
1220	if (dc == NULL)
1221		return (unit);
1222	while (unit < dc->maxunit && dc->devices[unit] != NULL)
1223		unit++;
1224	return (unit);
1225}
1226
1227/**
1228 * @brief Set the parent of a devclass
1229 *
1230 * The parent class is normally initialised automatically by
1231 * DRIVER_MODULE().
1232 *
1233 * @param dc		the devclass to edit
1234 * @param pdc		the new parent devclass
1235 */
1236void
1237devclass_set_parent(devclass_t dc, devclass_t pdc)
1238{
1239	dc->parent = pdc;
1240}
1241
1242/**
1243 * @brief Get the parent of a devclass
1244 *
1245 * @param dc		the devclass to examine
1246 */
1247devclass_t
1248devclass_get_parent(devclass_t dc)
1249{
1250	return (dc->parent);
1251}
1252
1253struct sysctl_ctx_list *
1254devclass_get_sysctl_ctx(devclass_t dc)
1255{
1256	return (&dc->sysctl_ctx);
1257}
1258
1259struct sysctl_oid *
1260devclass_get_sysctl_tree(devclass_t dc)
1261{
1262	return (dc->sysctl_tree);
1263}
1264
1265/**
1266 * @internal
1267 * @brief Allocate a unit number
1268 *
1269 * On entry, @p *unitp is the desired unit number (or @c -1 if any
1270 * will do). The allocated unit number is returned in @p *unitp.
1271
1272 * @param dc		the devclass to allocate from
1273 * @param unitp		points at the location for the allocated unit
1274 *			number
1275 *
1276 * @retval 0		success
1277 * @retval EEXIST	the requested unit number is already allocated
1278 * @retval ENOMEM	memory allocation failure
1279 */
1280static int
1281devclass_alloc_unit(devclass_t dc, int *unitp)
1282{
1283	int unit = *unitp;
1284
1285	PDEBUG(("unit %d in devclass %s", unit, DEVCLANAME(dc)));
1286
1287	/* If we were given a wired unit number, check for existing device */
1288	/* XXX imp XXX */
1289	if (unit != -1) {
1290		if (unit >= 0 && unit < dc->maxunit &&
1291		    dc->devices[unit] != NULL) {
1292			if (bootverbose)
1293				printf("%s: %s%d already exists; skipping it\n",
1294				    dc->name, dc->name, *unitp);
1295			return (EEXIST);
1296		}
1297	} else {
1298		/* Unwired device, find the next available slot for it */
1299		unit = 0;
1300		while (unit < dc->maxunit && dc->devices[unit] != NULL)
1301			unit++;
1302	}
1303
1304	/*
1305	 * We've selected a unit beyond the length of the table, so let's
1306	 * extend the table to make room for all units up to and including
1307	 * this one.
1308	 */
1309	if (unit >= dc->maxunit) {
1310		device_t *newlist;
1311		int newsize;
1312
1313		newsize = roundup((unit + 1), MINALLOCSIZE / sizeof(device_t));
1314		newlist = malloc(sizeof(device_t) * newsize, M_BUS, M_NOWAIT);
1315		if (!newlist)
1316			return (ENOMEM);
1317		bcopy(dc->devices, newlist, sizeof(device_t) * dc->maxunit);
1318		bzero(newlist + dc->maxunit,
1319		    sizeof(device_t) * (newsize - dc->maxunit));
1320		if (dc->devices)
1321			free(dc->devices, M_BUS);
1322		dc->devices = newlist;
1323		dc->maxunit = newsize;
1324	}
1325	PDEBUG(("now: unit %d in devclass %s", unit, DEVCLANAME(dc)));
1326
1327	*unitp = unit;
1328	return (0);
1329}
1330
1331/**
1332 * @internal
1333 * @brief Add a device to a devclass
1334 *
1335 * A unit number is allocated for the device (using the device's
1336 * preferred unit number if any) and the device is registered in the
1337 * devclass. This allows the device to be looked up by its unit
1338 * number, e.g. by decoding a dev_t minor number.
1339 *
1340 * @param dc		the devclass to add to
1341 * @param dev		the device to add
1342 *
1343 * @retval 0		success
1344 * @retval EEXIST	the requested unit number is already allocated
1345 * @retval ENOMEM	memory allocation failure
1346 */
1347static int
1348devclass_add_device(devclass_t dc, device_t dev)
1349{
1350	int buflen, error;
1351
1352	PDEBUG(("%s in devclass %s", DEVICENAME(dev), DEVCLANAME(dc)));
1353
1354	buflen = snprintf(NULL, 0, "%s%d$", dc->name, dev->unit);
1355	if (buflen < 0)
1356		return (ENOMEM);
1357	dev->nameunit = malloc(buflen, M_BUS, M_NOWAIT|M_ZERO);
1358	if (!dev->nameunit)
1359		return (ENOMEM);
1360
1361	if ((error = devclass_alloc_unit(dc, &dev->unit)) != 0) {
1362		free(dev->nameunit, M_BUS);
1363		dev->nameunit = NULL;
1364		return (error);
1365	}
1366	dc->devices[dev->unit] = dev;
1367	dev->devclass = dc;
1368	snprintf(dev->nameunit, buflen, "%s%d", dc->name, dev->unit);
1369
1370	return (0);
1371}
1372
1373/**
1374 * @internal
1375 * @brief Delete a device from a devclass
1376 *
1377 * The device is removed from the devclass's device list and its unit
1378 * number is freed.
1379
1380 * @param dc		the devclass to delete from
1381 * @param dev		the device to delete
1382 *
1383 * @retval 0		success
1384 */
1385static int
1386devclass_delete_device(devclass_t dc, device_t dev)
1387{
1388	if (!dc || !dev)
1389		return (0);
1390
1391	PDEBUG(("%s in devclass %s", DEVICENAME(dev), DEVCLANAME(dc)));
1392
1393	if (dev->devclass != dc || dc->devices[dev->unit] != dev)
1394		panic("devclass_delete_device: inconsistent device class");
1395	dc->devices[dev->unit] = NULL;
1396	if (dev->flags & DF_WILDCARD)
1397		dev->unit = -1;
1398	dev->devclass = NULL;
1399	free(dev->nameunit, M_BUS);
1400	dev->nameunit = NULL;
1401
1402	return (0);
1403}
1404
1405/**
1406 * @internal
1407 * @brief Make a new device and add it as a child of @p parent
1408 *
1409 * @param parent	the parent of the new device
1410 * @param name		the devclass name of the new device or @c NULL
1411 *			to leave the devclass unspecified
1412 * @parem unit		the unit number of the new device of @c -1 to
1413 *			leave the unit number unspecified
1414 *
1415 * @returns the new device
1416 */
1417static device_t
1418make_device(device_t parent, const char *name, int unit)
1419{
1420	device_t dev;
1421	devclass_t dc;
1422
1423	PDEBUG(("%s at %s as unit %d", name, DEVICENAME(parent), unit));
1424
1425	if (name) {
1426		dc = devclass_find_internal(name, 0, TRUE);
1427		if (!dc) {
1428			printf("make_device: can't find device class %s\n",
1429			    name);
1430			return (NULL);
1431		}
1432	} else {
1433		dc = NULL;
1434	}
1435
1436	dev = malloc(sizeof(struct device), M_BUS, M_NOWAIT|M_ZERO);
1437	if (!dev)
1438		return (NULL);
1439
1440	dev->parent = parent;
1441	TAILQ_INIT(&dev->children);
1442	kobj_init((kobj_t) dev, &null_class);
1443	dev->driver = NULL;
1444	dev->devclass = NULL;
1445	dev->unit = unit;
1446	dev->nameunit = NULL;
1447	dev->desc = NULL;
1448	dev->busy = 0;
1449	dev->devflags = 0;
1450	dev->flags = DF_ENABLED;
1451	dev->order = 0;
1452	if (unit == -1)
1453		dev->flags |= DF_WILDCARD;
1454	if (name) {
1455		dev->flags |= DF_FIXEDCLASS;
1456		if (devclass_add_device(dc, dev)) {
1457			kobj_delete((kobj_t) dev, M_BUS);
1458			return (NULL);
1459		}
1460	}
1461	dev->ivars = NULL;
1462	dev->softc = NULL;
1463
1464	dev->state = DS_NOTPRESENT;
1465
1466	TAILQ_INSERT_TAIL(&bus_data_devices, dev, devlink);
1467	bus_data_generation_update();
1468
1469	return (dev);
1470}
1471
1472/**
1473 * @internal
1474 * @brief Print a description of a device.
1475 */
1476static int
1477device_print_child(device_t dev, device_t child)
1478{
1479	int retval = 0;
1480
1481	if (device_is_alive(child))
1482		retval += BUS_PRINT_CHILD(dev, child);
1483	else
1484		retval += device_printf(child, " not found\n");
1485
1486	return (retval);
1487}
1488
1489/**
1490 * @brief Create a new device
1491 *
1492 * This creates a new device and adds it as a child of an existing
1493 * parent device. The new device will be added after the last existing
1494 * child with order zero.
1495 *
1496 * @param dev		the device which will be the parent of the
1497 *			new child device
1498 * @param name		devclass name for new device or @c NULL if not
1499 *			specified
1500 * @param unit		unit number for new device or @c -1 if not
1501 *			specified
1502 *
1503 * @returns		the new device
1504 */
1505device_t
1506device_add_child(device_t dev, const char *name, int unit)
1507{
1508	return (device_add_child_ordered(dev, 0, name, unit));
1509}
1510
1511/**
1512 * @brief Create a new device
1513 *
1514 * This creates a new device and adds it as a child of an existing
1515 * parent device. The new device will be added after the last existing
1516 * child with the same order.
1517 *
1518 * @param dev		the device which will be the parent of the
1519 *			new child device
1520 * @param order		a value which is used to partially sort the
1521 *			children of @p dev - devices created using
1522 *			lower values of @p order appear first in @p
1523 *			dev's list of children
1524 * @param name		devclass name for new device or @c NULL if not
1525 *			specified
1526 * @param unit		unit number for new device or @c -1 if not
1527 *			specified
1528 *
1529 * @returns		the new device
1530 */
1531device_t
1532device_add_child_ordered(device_t dev, int order, const char *name, int unit)
1533{
1534	device_t child;
1535	device_t place;
1536
1537	PDEBUG(("%s at %s with order %d as unit %d",
1538	    name, DEVICENAME(dev), order, unit));
1539
1540	child = make_device(dev, name, unit);
1541	if (child == NULL)
1542		return (child);
1543	child->order = order;
1544
1545	TAILQ_FOREACH(place, &dev->children, link) {
1546		if (place->order > order)
1547			break;
1548	}
1549
1550	if (place) {
1551		/*
1552		 * The device 'place' is the first device whose order is
1553		 * greater than the new child.
1554		 */
1555		TAILQ_INSERT_BEFORE(place, child, link);
1556	} else {
1557		/*
1558		 * The new child's order is greater or equal to the order of
1559		 * any existing device. Add the child to the tail of the list.
1560		 */
1561		TAILQ_INSERT_TAIL(&dev->children, child, link);
1562	}
1563
1564	bus_data_generation_update();
1565	return (child);
1566}
1567
1568/**
1569 * @brief Delete a device
1570 *
1571 * This function deletes a device along with all of its children. If
1572 * the device currently has a driver attached to it, the device is
1573 * detached first using device_detach().
1574 *
1575 * @param dev		the parent device
1576 * @param child		the device to delete
1577 *
1578 * @retval 0		success
1579 * @retval non-zero	a unit error code describing the error
1580 */
1581int
1582device_delete_child(device_t dev, device_t child)
1583{
1584	int error;
1585	device_t grandchild;
1586
1587	PDEBUG(("%s from %s", DEVICENAME(child), DEVICENAME(dev)));
1588
1589	/* remove children first */
1590	while ( (grandchild = TAILQ_FIRST(&child->children)) ) {
1591		error = device_delete_child(child, grandchild);
1592		if (error)
1593			return (error);
1594	}
1595
1596	if ((error = device_detach(child)) != 0)
1597		return (error);
1598	if (child->devclass)
1599		devclass_delete_device(child->devclass, child);
1600	TAILQ_REMOVE(&dev->children, child, link);
1601	TAILQ_REMOVE(&bus_data_devices, child, devlink);
1602	kobj_delete((kobj_t) child, M_BUS);
1603
1604	bus_data_generation_update();
1605	return (0);
1606}
1607
1608/**
1609 * @brief Find a device given a unit number
1610 *
1611 * This is similar to devclass_get_devices() but only searches for
1612 * devices which have @p dev as a parent.
1613 *
1614 * @param dev		the parent device to search
1615 * @param unit		the unit number to search for.  If the unit is -1,
1616 *			return the first child of @p dev which has name
1617 *			@p classname (that is, the one with the lowest unit.)
1618 *
1619 * @returns		the device with the given unit number or @c
1620 *			NULL if there is no such device
1621 */
1622device_t
1623device_find_child(device_t dev, const char *classname, int unit)
1624{
1625	devclass_t dc;
1626	device_t child;
1627
1628	dc = devclass_find(classname);
1629	if (!dc)
1630		return (NULL);
1631
1632	if (unit != -1) {
1633		child = devclass_get_device(dc, unit);
1634		if (child && child->parent == dev)
1635			return (child);
1636	} else {
1637		for (unit = 0; unit < devclass_get_maxunit(dc); unit++) {
1638			child = devclass_get_device(dc, unit);
1639			if (child && child->parent == dev)
1640				return (child);
1641		}
1642	}
1643	return (NULL);
1644}
1645
1646/**
1647 * @internal
1648 */
1649static driverlink_t
1650first_matching_driver(devclass_t dc, device_t dev)
1651{
1652	if (dev->devclass)
1653		return (devclass_find_driver_internal(dc, dev->devclass->name));
1654	return (TAILQ_FIRST(&dc->drivers));
1655}
1656
1657/**
1658 * @internal
1659 */
1660static driverlink_t
1661next_matching_driver(devclass_t dc, device_t dev, driverlink_t last)
1662{
1663	if (dev->devclass) {
1664		driverlink_t dl;
1665		for (dl = TAILQ_NEXT(last, link); dl; dl = TAILQ_NEXT(dl, link))
1666			if (!strcmp(dev->devclass->name, dl->driver->name))
1667				return (dl);
1668		return (NULL);
1669	}
1670	return (TAILQ_NEXT(last, link));
1671}
1672
1673/**
1674 * @internal
1675 */
1676static int
1677device_probe_child(device_t dev, device_t child)
1678{
1679	devclass_t dc;
1680	driverlink_t best = 0;
1681	driverlink_t dl;
1682	int result, pri = 0;
1683	int hasclass = (child->devclass != 0);
1684
1685	GIANT_REQUIRED;
1686
1687	dc = dev->devclass;
1688	if (!dc)
1689		panic("device_probe_child: parent device has no devclass");
1690
1691	/*
1692	 * If the state is already probed, then return.  However, don't
1693	 * return if we can rebid this object.
1694	 */
1695	if (child->state == DS_ALIVE && (child->flags & DF_REBID) == 0)
1696		return (0);
1697
1698	for (; dc; dc = dc->parent) {
1699		for (dl = first_matching_driver(dc, child);
1700		     dl;
1701		     dl = next_matching_driver(dc, child, dl)) {
1702			PDEBUG(("Trying %s", DRIVERNAME(dl->driver)));
1703			device_set_driver(child, dl->driver);
1704			if (!hasclass)
1705				device_set_devclass(child, dl->driver->name);
1706
1707			/* Fetch any flags for the device before probing. */
1708			resource_int_value(dl->driver->name, child->unit,
1709			    "flags", &child->devflags);
1710
1711			result = DEVICE_PROBE(child);
1712
1713			/* Reset flags and devclass before the next probe. */
1714			child->devflags = 0;
1715			if (!hasclass)
1716				device_set_devclass(child, 0);
1717
1718			/*
1719			 * If the driver returns SUCCESS, there can be
1720			 * no higher match for this device.
1721			 */
1722			if (result == 0) {
1723				best = dl;
1724				pri = 0;
1725				break;
1726			}
1727
1728			/*
1729			 * The driver returned an error so it
1730			 * certainly doesn't match.
1731			 */
1732			if (result > 0) {
1733				device_set_driver(child, 0);
1734				continue;
1735			}
1736
1737			/*
1738			 * A priority lower than SUCCESS, remember the
1739			 * best matching driver. Initialise the value
1740			 * of pri for the first match.
1741			 */
1742			if (best == 0 || result > pri) {
1743				best = dl;
1744				pri = result;
1745				continue;
1746			}
1747		}
1748		/*
1749		 * If we have an unambiguous match in this devclass,
1750		 * don't look in the parent.
1751		 */
1752		if (best && pri == 0)
1753			break;
1754	}
1755
1756	/*
1757	 * If we found a driver, change state and initialise the devclass.
1758	 */
1759	/* XXX What happens if we rebid and got no best? */
1760	if (best) {
1761		/*
1762		 * If this device was atached, and we were asked to
1763		 * rescan, and it is a different driver, then we have
1764		 * to detach the old driver and reattach this new one.
1765		 * Note, we don't have to check for DF_REBID here
1766		 * because if the state is > DS_ALIVE, we know it must
1767		 * be.
1768		 *
1769		 * This assumes that all DF_REBID drivers can have
1770		 * their probe routine called at any time and that
1771		 * they are idempotent as well as completely benign in
1772		 * normal operations.
1773		 *
1774		 * We also have to make sure that the detach
1775		 * succeeded, otherwise we fail the operation (or
1776		 * maybe it should just fail silently?  I'm torn).
1777		 */
1778		if (child->state > DS_ALIVE && best->driver != child->driver)
1779			if ((result = device_detach(dev)) != 0)
1780				return (result);
1781
1782		/* Set the winning driver, devclass, and flags. */
1783		if (!child->devclass)
1784			device_set_devclass(child, best->driver->name);
1785		device_set_driver(child, best->driver);
1786		resource_int_value(best->driver->name, child->unit,
1787		    "flags", &child->devflags);
1788
1789		if (pri < 0) {
1790			/*
1791			 * A bit bogus. Call the probe method again to make
1792			 * sure that we have the right description.
1793			 */
1794			DEVICE_PROBE(child);
1795#if 0
1796			child->flags |= DF_REBID;
1797#endif
1798		} else
1799			child->flags &= ~DF_REBID;
1800		child->state = DS_ALIVE;
1801
1802		bus_data_generation_update();
1803		return (0);
1804	}
1805
1806	return (ENXIO);
1807}
1808
1809/**
1810 * @brief Return the parent of a device
1811 */
1812device_t
1813device_get_parent(device_t dev)
1814{
1815	return (dev->parent);
1816}
1817
1818/**
1819 * @brief Get a list of children of a device
1820 *
1821 * An array containing a list of all the children of the given device
1822 * is allocated and returned in @p *devlistp. The number of devices
1823 * in the array is returned in @p *devcountp. The caller should free
1824 * the array using @c free(p, M_TEMP).
1825 *
1826 * @param dev		the device to examine
1827 * @param devlistp	points at location for array pointer return
1828 *			value
1829 * @param devcountp	points at location for array size return value
1830 *
1831 * @retval 0		success
1832 * @retval ENOMEM	the array allocation failed
1833 */
1834int
1835device_get_children(device_t dev, device_t **devlistp, int *devcountp)
1836{
1837	int count;
1838	device_t child;
1839	device_t *list;
1840
1841	count = 0;
1842	TAILQ_FOREACH(child, &dev->children, link) {
1843		count++;
1844	}
1845
1846	list = malloc(count * sizeof(device_t), M_TEMP, M_NOWAIT|M_ZERO);
1847	if (!list)
1848		return (ENOMEM);
1849
1850	count = 0;
1851	TAILQ_FOREACH(child, &dev->children, link) {
1852		list[count] = child;
1853		count++;
1854	}
1855
1856	*devlistp = list;
1857	*devcountp = count;
1858
1859	return (0);
1860}
1861
1862/**
1863 * @brief Return the current driver for the device or @c NULL if there
1864 * is no driver currently attached
1865 */
1866driver_t *
1867device_get_driver(device_t dev)
1868{
1869	return (dev->driver);
1870}
1871
1872/**
1873 * @brief Return the current devclass for the device or @c NULL if
1874 * there is none.
1875 */
1876devclass_t
1877device_get_devclass(device_t dev)
1878{
1879	return (dev->devclass);
1880}
1881
1882/**
1883 * @brief Return the name of the device's devclass or @c NULL if there
1884 * is none.
1885 */
1886const char *
1887device_get_name(device_t dev)
1888{
1889	if (dev != NULL && dev->devclass)
1890		return (devclass_get_name(dev->devclass));
1891	return (NULL);
1892}
1893
1894/**
1895 * @brief Return a string containing the device's devclass name
1896 * followed by an ascii representation of the device's unit number
1897 * (e.g. @c "foo2").
1898 */
1899const char *
1900device_get_nameunit(device_t dev)
1901{
1902	return (dev->nameunit);
1903}
1904
1905/**
1906 * @brief Return the device's unit number.
1907 */
1908int
1909device_get_unit(device_t dev)
1910{
1911	return (dev->unit);
1912}
1913
1914/**
1915 * @brief Return the device's description string
1916 */
1917const char *
1918device_get_desc(device_t dev)
1919{
1920	return (dev->desc);
1921}
1922
1923/**
1924 * @brief Return the device's flags
1925 */
1926u_int32_t
1927device_get_flags(device_t dev)
1928{
1929	return (dev->devflags);
1930}
1931
1932struct sysctl_ctx_list *
1933device_get_sysctl_ctx(device_t dev)
1934{
1935	return (&dev->sysctl_ctx);
1936}
1937
1938struct sysctl_oid *
1939device_get_sysctl_tree(device_t dev)
1940{
1941	return (dev->sysctl_tree);
1942}
1943
1944/**
1945 * @brief Print the name of the device followed by a colon and a space
1946 *
1947 * @returns the number of characters printed
1948 */
1949int
1950device_print_prettyname(device_t dev)
1951{
1952	const char *name = device_get_name(dev);
1953
1954	if (name == 0)
1955		return (printf("unknown: "));
1956	return (printf("%s%d: ", name, device_get_unit(dev)));
1957}
1958
1959/**
1960 * @brief Print the name of the device followed by a colon, a space
1961 * and the result of calling vprintf() with the value of @p fmt and
1962 * the following arguments.
1963 *
1964 * @returns the number of characters printed
1965 */
1966int
1967device_printf(device_t dev, const char * fmt, ...)
1968{
1969	va_list ap;
1970	int retval;
1971
1972	retval = device_print_prettyname(dev);
1973	va_start(ap, fmt);
1974	retval += vprintf(fmt, ap);
1975	va_end(ap);
1976	return (retval);
1977}
1978
1979/**
1980 * @internal
1981 */
1982static void
1983device_set_desc_internal(device_t dev, const char* desc, int copy)
1984{
1985	if (dev->desc && (dev->flags & DF_DESCMALLOCED)) {
1986		free(dev->desc, M_BUS);
1987		dev->flags &= ~DF_DESCMALLOCED;
1988		dev->desc = NULL;
1989	}
1990
1991	if (copy && desc) {
1992		dev->desc = malloc(strlen(desc) + 1, M_BUS, M_NOWAIT);
1993		if (dev->desc) {
1994			strcpy(dev->desc, desc);
1995			dev->flags |= DF_DESCMALLOCED;
1996		}
1997	} else {
1998		/* Avoid a -Wcast-qual warning */
1999		dev->desc = (char *)(uintptr_t) desc;
2000	}
2001
2002	bus_data_generation_update();
2003}
2004
2005/**
2006 * @brief Set the device's description
2007 *
2008 * The value of @c desc should be a string constant that will not
2009 * change (at least until the description is changed in a subsequent
2010 * call to device_set_desc() or device_set_desc_copy()).
2011 */
2012void
2013device_set_desc(device_t dev, const char* desc)
2014{
2015	device_set_desc_internal(dev, desc, FALSE);
2016}
2017
2018/**
2019 * @brief Set the device's description
2020 *
2021 * The string pointed to by @c desc is copied. Use this function if
2022 * the device description is generated, (e.g. with sprintf()).
2023 */
2024void
2025device_set_desc_copy(device_t dev, const char* desc)
2026{
2027	device_set_desc_internal(dev, desc, TRUE);
2028}
2029
2030/**
2031 * @brief Set the device's flags
2032 */
2033void
2034device_set_flags(device_t dev, u_int32_t flags)
2035{
2036	dev->devflags = flags;
2037}
2038
2039/**
2040 * @brief Return the device's softc field
2041 *
2042 * The softc is allocated and zeroed when a driver is attached, based
2043 * on the size field of the driver.
2044 */
2045void *
2046device_get_softc(device_t dev)
2047{
2048	return (dev->softc);
2049}
2050
2051/**
2052 * @brief Set the device's softc field
2053 *
2054 * Most drivers do not need to use this since the softc is allocated
2055 * automatically when the driver is attached.
2056 */
2057void
2058device_set_softc(device_t dev, void *softc)
2059{
2060	if (dev->softc && !(dev->flags & DF_EXTERNALSOFTC))
2061		free(dev->softc, M_BUS_SC);
2062	dev->softc = softc;
2063	if (dev->softc)
2064		dev->flags |= DF_EXTERNALSOFTC;
2065	else
2066		dev->flags &= ~DF_EXTERNALSOFTC;
2067}
2068
2069/**
2070 * @brief Get the device's ivars field
2071 *
2072 * The ivars field is used by the parent device to store per-device
2073 * state (e.g. the physical location of the device or a list of
2074 * resources).
2075 */
2076void *
2077device_get_ivars(device_t dev)
2078{
2079
2080	KASSERT(dev != NULL, ("device_get_ivars(NULL, ...)"));
2081	return (dev->ivars);
2082}
2083
2084/**
2085 * @brief Set the device's ivars field
2086 */
2087void
2088device_set_ivars(device_t dev, void * ivars)
2089{
2090
2091	KASSERT(dev != NULL, ("device_set_ivars(NULL, ...)"));
2092	dev->ivars = ivars;
2093}
2094
2095/**
2096 * @brief Return the device's state
2097 */
2098device_state_t
2099device_get_state(device_t dev)
2100{
2101	return (dev->state);
2102}
2103
2104/**
2105 * @brief Set the DF_ENABLED flag for the device
2106 */
2107void
2108device_enable(device_t dev)
2109{
2110	dev->flags |= DF_ENABLED;
2111}
2112
2113/**
2114 * @brief Clear the DF_ENABLED flag for the device
2115 */
2116void
2117device_disable(device_t dev)
2118{
2119	dev->flags &= ~DF_ENABLED;
2120}
2121
2122/**
2123 * @brief Increment the busy counter for the device
2124 */
2125void
2126device_busy(device_t dev)
2127{
2128	if (dev->state < DS_ATTACHED)
2129		panic("device_busy: called for unattached device");
2130	if (dev->busy == 0 && dev->parent)
2131		device_busy(dev->parent);
2132	dev->busy++;
2133	dev->state = DS_BUSY;
2134}
2135
2136/**
2137 * @brief Decrement the busy counter for the device
2138 */
2139void
2140device_unbusy(device_t dev)
2141{
2142	if (dev->state != DS_BUSY)
2143		panic("device_unbusy: called for non-busy device %s",
2144		    device_get_nameunit(dev));
2145	dev->busy--;
2146	if (dev->busy == 0) {
2147		if (dev->parent)
2148			device_unbusy(dev->parent);
2149		dev->state = DS_ATTACHED;
2150	}
2151}
2152
2153/**
2154 * @brief Set the DF_QUIET flag for the device
2155 */
2156void
2157device_quiet(device_t dev)
2158{
2159	dev->flags |= DF_QUIET;
2160}
2161
2162/**
2163 * @brief Clear the DF_QUIET flag for the device
2164 */
2165void
2166device_verbose(device_t dev)
2167{
2168	dev->flags &= ~DF_QUIET;
2169}
2170
2171/**
2172 * @brief Return non-zero if the DF_QUIET flag is set on the device
2173 */
2174int
2175device_is_quiet(device_t dev)
2176{
2177	return ((dev->flags & DF_QUIET) != 0);
2178}
2179
2180/**
2181 * @brief Return non-zero if the DF_ENABLED flag is set on the device
2182 */
2183int
2184device_is_enabled(device_t dev)
2185{
2186	return ((dev->flags & DF_ENABLED) != 0);
2187}
2188
2189/**
2190 * @brief Return non-zero if the device was successfully probed
2191 */
2192int
2193device_is_alive(device_t dev)
2194{
2195	return (dev->state >= DS_ALIVE);
2196}
2197
2198/**
2199 * @brief Return non-zero if the device currently has a driver
2200 * attached to it
2201 */
2202int
2203device_is_attached(device_t dev)
2204{
2205	return (dev->state >= DS_ATTACHED);
2206}
2207
2208/**
2209 * @brief Set the devclass of a device
2210 * @see devclass_add_device().
2211 */
2212int
2213device_set_devclass(device_t dev, const char *classname)
2214{
2215	devclass_t dc;
2216	int error;
2217
2218	if (!classname) {
2219		if (dev->devclass)
2220			devclass_delete_device(dev->devclass, dev);
2221		return (0);
2222	}
2223
2224	if (dev->devclass) {
2225		printf("device_set_devclass: device class already set\n");
2226		return (EINVAL);
2227	}
2228
2229	dc = devclass_find_internal(classname, 0, TRUE);
2230	if (!dc)
2231		return (ENOMEM);
2232
2233	error = devclass_add_device(dc, dev);
2234
2235	bus_data_generation_update();
2236	return (error);
2237}
2238
2239/**
2240 * @brief Set the driver of a device
2241 *
2242 * @retval 0		success
2243 * @retval EBUSY	the device already has a driver attached
2244 * @retval ENOMEM	a memory allocation failure occurred
2245 */
2246int
2247device_set_driver(device_t dev, driver_t *driver)
2248{
2249	if (dev->state >= DS_ATTACHED)
2250		return (EBUSY);
2251
2252	if (dev->driver == driver)
2253		return (0);
2254
2255	if (dev->softc && !(dev->flags & DF_EXTERNALSOFTC)) {
2256		free(dev->softc, M_BUS_SC);
2257		dev->softc = NULL;
2258	}
2259	kobj_delete((kobj_t) dev, 0);
2260	dev->driver = driver;
2261	if (driver) {
2262		kobj_init((kobj_t) dev, (kobj_class_t) driver);
2263		if (!(dev->flags & DF_EXTERNALSOFTC) && driver->size > 0) {
2264			dev->softc = malloc(driver->size, M_BUS_SC,
2265			    M_NOWAIT | M_ZERO);
2266			if (!dev->softc) {
2267				kobj_delete((kobj_t) dev, 0);
2268				kobj_init((kobj_t) dev, &null_class);
2269				dev->driver = NULL;
2270				return (ENOMEM);
2271			}
2272		}
2273	} else {
2274		kobj_init((kobj_t) dev, &null_class);
2275	}
2276
2277	bus_data_generation_update();
2278	return (0);
2279}
2280
2281/**
2282 * @brief Probe a device and attach a driver if possible
2283 *
2284 * This function is the core of the device autoconfiguration
2285 * system. Its purpose is to select a suitable driver for a device and
2286 * then call that driver to initialise the hardware appropriately. The
2287 * driver is selected by calling the DEVICE_PROBE() method of a set of
2288 * candidate drivers and then choosing the driver which returned the
2289 * best value. This driver is then attached to the device using
2290 * device_attach().
2291 *
2292 * The set of suitable drivers is taken from the list of drivers in
2293 * the parent device's devclass. If the device was originally created
2294 * with a specific class name (see device_add_child()), only drivers
2295 * with that name are probed, otherwise all drivers in the devclass
2296 * are probed. If no drivers return successful probe values in the
2297 * parent devclass, the search continues in the parent of that
2298 * devclass (see devclass_get_parent()) if any.
2299 *
2300 * @param dev		the device to initialise
2301 *
2302 * @retval 0		success
2303 * @retval ENXIO	no driver was found
2304 * @retval ENOMEM	memory allocation failure
2305 * @retval non-zero	some other unix error code
2306 */
2307int
2308device_probe_and_attach(device_t dev)
2309{
2310	int error;
2311
2312	GIANT_REQUIRED;
2313
2314	if (dev->state >= DS_ALIVE && (dev->flags & DF_REBID) == 0)
2315		return (0);
2316
2317	if (!(dev->flags & DF_ENABLED)) {
2318		if (bootverbose && device_get_name(dev) != NULL) {
2319			device_print_prettyname(dev);
2320			printf("not probed (disabled)\n");
2321		}
2322		return (0);
2323	}
2324	if ((error = device_probe_child(dev->parent, dev)) != 0) {
2325		if (!(dev->flags & DF_DONENOMATCH)) {
2326			BUS_PROBE_NOMATCH(dev->parent, dev);
2327			devnomatch(dev);
2328			dev->flags |= DF_DONENOMATCH;
2329		}
2330		return (error);
2331	}
2332	error = device_attach(dev);
2333
2334	return (error);
2335}
2336
2337/**
2338 * @brief Attach a device driver to a device
2339 *
2340 * This function is a wrapper around the DEVICE_ATTACH() driver
2341 * method. In addition to calling DEVICE_ATTACH(), it initialises the
2342 * device's sysctl tree, optionally prints a description of the device
2343 * and queues a notification event for user-based device management
2344 * services.
2345 *
2346 * Normally this function is only called internally from
2347 * device_probe_and_attach().
2348 *
2349 * @param dev		the device to initialise
2350 *
2351 * @retval 0		success
2352 * @retval ENXIO	no driver was found
2353 * @retval ENOMEM	memory allocation failure
2354 * @retval non-zero	some other unix error code
2355 */
2356int
2357device_attach(device_t dev)
2358{
2359	int error;
2360
2361	device_sysctl_init(dev);
2362	if (!device_is_quiet(dev))
2363		device_print_child(dev->parent, dev);
2364	if ((error = DEVICE_ATTACH(dev)) != 0) {
2365		printf("device_attach: %s%d attach returned %d\n",
2366		    dev->driver->name, dev->unit, error);
2367		/* Unset the class; set in device_probe_child */
2368		if (dev->devclass == 0)
2369			device_set_devclass(dev, 0);
2370		device_set_driver(dev, NULL);
2371		device_sysctl_fini(dev);
2372		dev->state = DS_NOTPRESENT;
2373		return (error);
2374	}
2375	dev->state = DS_ATTACHED;
2376	devadded(dev);
2377	return (0);
2378}
2379
2380/**
2381 * @brief Detach a driver from a device
2382 *
2383 * This function is a wrapper around the DEVICE_DETACH() driver
2384 * method. If the call to DEVICE_DETACH() succeeds, it calls
2385 * BUS_CHILD_DETACHED() for the parent of @p dev, queues a
2386 * notification event for user-based device management services and
2387 * cleans up the device's sysctl tree.
2388 *
2389 * @param dev		the device to un-initialise
2390 *
2391 * @retval 0		success
2392 * @retval ENXIO	no driver was found
2393 * @retval ENOMEM	memory allocation failure
2394 * @retval non-zero	some other unix error code
2395 */
2396int
2397device_detach(device_t dev)
2398{
2399	int error;
2400
2401	GIANT_REQUIRED;
2402
2403	PDEBUG(("%s", DEVICENAME(dev)));
2404	if (dev->state == DS_BUSY)
2405		return (EBUSY);
2406	if (dev->state != DS_ATTACHED)
2407		return (0);
2408
2409	if ((error = DEVICE_DETACH(dev)) != 0)
2410		return (error);
2411	devremoved(dev);
2412	device_printf(dev, "detached\n");
2413	if (dev->parent)
2414		BUS_CHILD_DETACHED(dev->parent, dev);
2415
2416	if (!(dev->flags & DF_FIXEDCLASS))
2417		devclass_delete_device(dev->devclass, dev);
2418
2419	dev->state = DS_NOTPRESENT;
2420	device_set_driver(dev, NULL);
2421	device_set_desc(dev, NULL);
2422	device_sysctl_fini(dev);
2423
2424	return (0);
2425}
2426
2427/**
2428 * @brief Tells a driver to quiesce itself.
2429 *
2430 * This function is a wrapper around the DEVICE_QUIESCE() driver
2431 * method. If the call to DEVICE_QUIESCE() succeeds.
2432 *
2433 * @param dev		the device to quiesce
2434 *
2435 * @retval 0		success
2436 * @retval ENXIO	no driver was found
2437 * @retval ENOMEM	memory allocation failure
2438 * @retval non-zero	some other unix error code
2439 */
2440int
2441device_quiesce(device_t dev)
2442{
2443
2444	PDEBUG(("%s", DEVICENAME(dev)));
2445	if (dev->state == DS_BUSY)
2446		return (EBUSY);
2447	if (dev->state != DS_ATTACHED)
2448		return (0);
2449
2450	return (DEVICE_QUIESCE(dev));
2451}
2452
2453/**
2454 * @brief Notify a device of system shutdown
2455 *
2456 * This function calls the DEVICE_SHUTDOWN() driver method if the
2457 * device currently has an attached driver.
2458 *
2459 * @returns the value returned by DEVICE_SHUTDOWN()
2460 */
2461int
2462device_shutdown(device_t dev)
2463{
2464	if (dev->state < DS_ATTACHED)
2465		return (0);
2466	return (DEVICE_SHUTDOWN(dev));
2467}
2468
2469/**
2470 * @brief Set the unit number of a device
2471 *
2472 * This function can be used to override the unit number used for a
2473 * device (e.g. to wire a device to a pre-configured unit number).
2474 */
2475int
2476device_set_unit(device_t dev, int unit)
2477{
2478	devclass_t dc;
2479	int err;
2480
2481	dc = device_get_devclass(dev);
2482	if (unit < dc->maxunit && dc->devices[unit])
2483		return (EBUSY);
2484	err = devclass_delete_device(dc, dev);
2485	if (err)
2486		return (err);
2487	dev->unit = unit;
2488	err = devclass_add_device(dc, dev);
2489	if (err)
2490		return (err);
2491
2492	bus_data_generation_update();
2493	return (0);
2494}
2495
2496/*======================================*/
2497/*
2498 * Some useful method implementations to make life easier for bus drivers.
2499 */
2500
2501/**
2502 * @brief Initialise a resource list.
2503 *
2504 * @param rl		the resource list to initialise
2505 */
2506void
2507resource_list_init(struct resource_list *rl)
2508{
2509	STAILQ_INIT(rl);
2510}
2511
2512/**
2513 * @brief Reclaim memory used by a resource list.
2514 *
2515 * This function frees the memory for all resource entries on the list
2516 * (if any).
2517 *
2518 * @param rl		the resource list to free
2519 */
2520void
2521resource_list_free(struct resource_list *rl)
2522{
2523	struct resource_list_entry *rle;
2524
2525	while ((rle = STAILQ_FIRST(rl)) != NULL) {
2526		if (rle->res)
2527			panic("resource_list_free: resource entry is busy");
2528		STAILQ_REMOVE_HEAD(rl, link);
2529		free(rle, M_BUS);
2530	}
2531}
2532
2533/**
2534 * @brief Add a resource entry.
2535 *
2536 * This function adds a resource entry using the given @p type, @p
2537 * start, @p end and @p count values. A rid value is chosen by
2538 * searching sequentially for the first unused rid starting at zero.
2539 *
2540 * @param rl		the resource list to edit
2541 * @param type		the resource entry type (e.g. SYS_RES_MEMORY)
2542 * @param start		the start address of the resource
2543 * @param end		the end address of the resource
2544 * @param count		XXX end-start+1
2545 */
2546int
2547resource_list_add_next(struct resource_list *rl, int type, u_long start,
2548    u_long end, u_long count)
2549{
2550	int rid;
2551
2552	rid = 0;
2553	while (resource_list_find(rl, type, rid) != NULL)
2554		rid++;
2555	resource_list_add(rl, type, rid, start, end, count);
2556	return (rid);
2557}
2558
2559/**
2560 * @brief Add or modify a resource entry.
2561 *
2562 * If an existing entry exists with the same type and rid, it will be
2563 * modified using the given values of @p start, @p end and @p
2564 * count. If no entry exists, a new one will be created using the
2565 * given values.
2566 *
2567 * @param rl		the resource list to edit
2568 * @param type		the resource entry type (e.g. SYS_RES_MEMORY)
2569 * @param rid		the resource identifier
2570 * @param start		the start address of the resource
2571 * @param end		the end address of the resource
2572 * @param count		XXX end-start+1
2573 */
2574void
2575resource_list_add(struct resource_list *rl, int type, int rid,
2576    u_long start, u_long end, u_long count)
2577{
2578	struct resource_list_entry *rle;
2579
2580	rle = resource_list_find(rl, type, rid);
2581	if (!rle) {
2582		rle = malloc(sizeof(struct resource_list_entry), M_BUS,
2583		    M_NOWAIT);
2584		if (!rle)
2585			panic("resource_list_add: can't record entry");
2586		STAILQ_INSERT_TAIL(rl, rle, link);
2587		rle->type = type;
2588		rle->rid = rid;
2589		rle->res = NULL;
2590	}
2591
2592	if (rle->res)
2593		panic("resource_list_add: resource entry is busy");
2594
2595	rle->start = start;
2596	rle->end = end;
2597	rle->count = count;
2598}
2599
2600/**
2601 * @brief Find a resource entry by type and rid.
2602 *
2603 * @param rl		the resource list to search
2604 * @param type		the resource entry type (e.g. SYS_RES_MEMORY)
2605 * @param rid		the resource identifier
2606 *
2607 * @returns the resource entry pointer or NULL if there is no such
2608 * entry.
2609 */
2610struct resource_list_entry *
2611resource_list_find(struct resource_list *rl, int type, int rid)
2612{
2613	struct resource_list_entry *rle;
2614
2615	STAILQ_FOREACH(rle, rl, link) {
2616		if (rle->type == type && rle->rid == rid)
2617			return (rle);
2618	}
2619	return (NULL);
2620}
2621
2622/**
2623 * @brief Delete a resource entry.
2624 *
2625 * @param rl		the resource list to edit
2626 * @param type		the resource entry type (e.g. SYS_RES_MEMORY)
2627 * @param rid		the resource identifier
2628 */
2629void
2630resource_list_delete(struct resource_list *rl, int type, int rid)
2631{
2632	struct resource_list_entry *rle = resource_list_find(rl, type, rid);
2633
2634	if (rle) {
2635		if (rle->res != NULL)
2636			panic("resource_list_delete: resource has not been released");
2637		STAILQ_REMOVE(rl, rle, resource_list_entry, link);
2638		free(rle, M_BUS);
2639	}
2640}
2641
2642/**
2643 * @brief Helper function for implementing BUS_ALLOC_RESOURCE()
2644 *
2645 * Implement BUS_ALLOC_RESOURCE() by looking up a resource from the list
2646 * and passing the allocation up to the parent of @p bus. This assumes
2647 * that the first entry of @c device_get_ivars(child) is a struct
2648 * resource_list. This also handles 'passthrough' allocations where a
2649 * child is a remote descendant of bus by passing the allocation up to
2650 * the parent of bus.
2651 *
2652 * Typically, a bus driver would store a list of child resources
2653 * somewhere in the child device's ivars (see device_get_ivars()) and
2654 * its implementation of BUS_ALLOC_RESOURCE() would find that list and
2655 * then call resource_list_alloc() to perform the allocation.
2656 *
2657 * @param rl		the resource list to allocate from
2658 * @param bus		the parent device of @p child
2659 * @param child		the device which is requesting an allocation
2660 * @param type		the type of resource to allocate
2661 * @param rid		a pointer to the resource identifier
2662 * @param start		hint at the start of the resource range - pass
2663 *			@c 0UL for any start address
2664 * @param end		hint at the end of the resource range - pass
2665 *			@c ~0UL for any end address
2666 * @param count		hint at the size of range required - pass @c 1
2667 *			for any size
2668 * @param flags		any extra flags to control the resource
2669 *			allocation - see @c RF_XXX flags in
2670 *			<sys/rman.h> for details
2671 *
2672 * @returns		the resource which was allocated or @c NULL if no
2673 *			resource could be allocated
2674 */
2675struct resource *
2676resource_list_alloc(struct resource_list *rl, device_t bus, device_t child,
2677    int type, int *rid, u_long start, u_long end, u_long count, u_int flags)
2678{
2679	struct resource_list_entry *rle = 0;
2680	int passthrough = (device_get_parent(child) != bus);
2681	int isdefault = (start == 0UL && end == ~0UL);
2682
2683	if (passthrough) {
2684		return (BUS_ALLOC_RESOURCE(device_get_parent(bus), child,
2685		    type, rid, start, end, count, flags));
2686	}
2687
2688	rle = resource_list_find(rl, type, *rid);
2689
2690	if (!rle)
2691		return (NULL);		/* no resource of that type/rid */
2692
2693	if (rle->res)
2694		panic("resource_list_alloc: resource entry is busy");
2695
2696	if (isdefault) {
2697		start = rle->start;
2698		count = ulmax(count, rle->count);
2699		end = ulmax(rle->end, start + count - 1);
2700	}
2701
2702	rle->res = BUS_ALLOC_RESOURCE(device_get_parent(bus), child,
2703	    type, rid, start, end, count, flags);
2704
2705	/*
2706	 * Record the new range.
2707	 */
2708	if (rle->res) {
2709		rle->start = rman_get_start(rle->res);
2710		rle->end = rman_get_end(rle->res);
2711		rle->count = count;
2712	}
2713
2714	return (rle->res);
2715}
2716
2717/**
2718 * @brief Helper function for implementing BUS_RELEASE_RESOURCE()
2719 *
2720 * Implement BUS_RELEASE_RESOURCE() using a resource list. Normally
2721 * used with resource_list_alloc().
2722 *
2723 * @param rl		the resource list which was allocated from
2724 * @param bus		the parent device of @p child
2725 * @param child		the device which is requesting a release
2726 * @param type		the type of resource to allocate
2727 * @param rid		the resource identifier
2728 * @param res		the resource to release
2729 *
2730 * @retval 0		success
2731 * @retval non-zero	a standard unix error code indicating what
2732 *			error condition prevented the operation
2733 */
2734int
2735resource_list_release(struct resource_list *rl, device_t bus, device_t child,
2736    int type, int rid, struct resource *res)
2737{
2738	struct resource_list_entry *rle = 0;
2739	int passthrough = (device_get_parent(child) != bus);
2740	int error;
2741
2742	if (passthrough) {
2743		return (BUS_RELEASE_RESOURCE(device_get_parent(bus), child,
2744		    type, rid, res));
2745	}
2746
2747	rle = resource_list_find(rl, type, rid);
2748
2749	if (!rle)
2750		panic("resource_list_release: can't find resource");
2751	if (!rle->res)
2752		panic("resource_list_release: resource entry is not busy");
2753
2754	error = BUS_RELEASE_RESOURCE(device_get_parent(bus), child,
2755	    type, rid, res);
2756	if (error)
2757		return (error);
2758
2759	rle->res = NULL;
2760	return (0);
2761}
2762
2763/**
2764 * @brief Print a description of resources in a resource list
2765 *
2766 * Print all resources of a specified type, for use in BUS_PRINT_CHILD().
2767 * The name is printed if at least one resource of the given type is available.
2768 * The format is used to print resource start and end.
2769 *
2770 * @param rl		the resource list to print
2771 * @param name		the name of @p type, e.g. @c "memory"
2772 * @param type		type type of resource entry to print
2773 * @param format	printf(9) format string to print resource
2774 *			start and end values
2775 *
2776 * @returns		the number of characters printed
2777 */
2778int
2779resource_list_print_type(struct resource_list *rl, const char *name, int type,
2780    const char *format)
2781{
2782	struct resource_list_entry *rle;
2783	int printed, retval;
2784
2785	printed = 0;
2786	retval = 0;
2787	/* Yes, this is kinda cheating */
2788	STAILQ_FOREACH(rle, rl, link) {
2789		if (rle->type == type) {
2790			if (printed == 0)
2791				retval += printf(" %s ", name);
2792			else
2793				retval += printf(",");
2794			printed++;
2795			retval += printf(format, rle->start);
2796			if (rle->count > 1) {
2797				retval += printf("-");
2798				retval += printf(format, rle->start +
2799						 rle->count - 1);
2800			}
2801		}
2802	}
2803	return (retval);
2804}
2805
2806/**
2807 * @brief Helper function for implementing DEVICE_PROBE()
2808 *
2809 * This function can be used to help implement the DEVICE_PROBE() for
2810 * a bus (i.e. a device which has other devices attached to it). It
2811 * calls the DEVICE_IDENTIFY() method of each driver in the device's
2812 * devclass.
2813 */
2814int
2815bus_generic_probe(device_t dev)
2816{
2817	devclass_t dc = dev->devclass;
2818	driverlink_t dl;
2819
2820	TAILQ_FOREACH(dl, &dc->drivers, link) {
2821		DEVICE_IDENTIFY(dl->driver, dev);
2822	}
2823
2824	return (0);
2825}
2826
2827/**
2828 * @brief Helper function for implementing DEVICE_ATTACH()
2829 *
2830 * This function can be used to help implement the DEVICE_ATTACH() for
2831 * a bus. It calls device_probe_and_attach() for each of the device's
2832 * children.
2833 */
2834int
2835bus_generic_attach(device_t dev)
2836{
2837	device_t child;
2838
2839	TAILQ_FOREACH(child, &dev->children, link) {
2840		device_probe_and_attach(child);
2841	}
2842
2843	return (0);
2844}
2845
2846/**
2847 * @brief Helper function for implementing DEVICE_DETACH()
2848 *
2849 * This function can be used to help implement the DEVICE_DETACH() for
2850 * a bus. It calls device_detach() for each of the device's
2851 * children.
2852 */
2853int
2854bus_generic_detach(device_t dev)
2855{
2856	device_t child;
2857	int error;
2858
2859	if (dev->state != DS_ATTACHED)
2860		return (EBUSY);
2861
2862	TAILQ_FOREACH(child, &dev->children, link) {
2863		if ((error = device_detach(child)) != 0)
2864			return (error);
2865	}
2866
2867	return (0);
2868}
2869
2870/**
2871 * @brief Helper function for implementing DEVICE_SHUTDOWN()
2872 *
2873 * This function can be used to help implement the DEVICE_SHUTDOWN()
2874 * for a bus. It calls device_shutdown() for each of the device's
2875 * children.
2876 */
2877int
2878bus_generic_shutdown(device_t dev)
2879{
2880	device_t child;
2881
2882	TAILQ_FOREACH(child, &dev->children, link) {
2883		device_shutdown(child);
2884	}
2885
2886	return (0);
2887}
2888
2889/**
2890 * @brief Helper function for implementing DEVICE_SUSPEND()
2891 *
2892 * This function can be used to help implement the DEVICE_SUSPEND()
2893 * for a bus. It calls DEVICE_SUSPEND() for each of the device's
2894 * children. If any call to DEVICE_SUSPEND() fails, the suspend
2895 * operation is aborted and any devices which were suspended are
2896 * resumed immediately by calling their DEVICE_RESUME() methods.
2897 */
2898int
2899bus_generic_suspend(device_t dev)
2900{
2901	int		error;
2902	device_t	child, child2;
2903
2904	TAILQ_FOREACH(child, &dev->children, link) {
2905		error = DEVICE_SUSPEND(child);
2906		if (error) {
2907			for (child2 = TAILQ_FIRST(&dev->children);
2908			     child2 && child2 != child;
2909			     child2 = TAILQ_NEXT(child2, link))
2910				DEVICE_RESUME(child2);
2911			return (error);
2912		}
2913	}
2914	return (0);
2915}
2916
2917/**
2918 * @brief Helper function for implementing DEVICE_RESUME()
2919 *
2920 * This function can be used to help implement the DEVICE_RESUME() for
2921 * a bus. It calls DEVICE_RESUME() on each of the device's children.
2922 */
2923int
2924bus_generic_resume(device_t dev)
2925{
2926	device_t	child;
2927
2928	TAILQ_FOREACH(child, &dev->children, link) {
2929		DEVICE_RESUME(child);
2930		/* if resume fails, there's nothing we can usefully do... */
2931	}
2932	return (0);
2933}
2934
2935/**
2936 * @brief Helper function for implementing BUS_PRINT_CHILD().
2937 *
2938 * This function prints the first part of the ascii representation of
2939 * @p child, including its name, unit and description (if any - see
2940 * device_set_desc()).
2941 *
2942 * @returns the number of characters printed
2943 */
2944int
2945bus_print_child_header(device_t dev, device_t child)
2946{
2947	int	retval = 0;
2948
2949	if (device_get_desc(child)) {
2950		retval += device_printf(child, "<%s>", device_get_desc(child));
2951	} else {
2952		retval += printf("%s", device_get_nameunit(child));
2953	}
2954
2955	return (retval);
2956}
2957
2958/**
2959 * @brief Helper function for implementing BUS_PRINT_CHILD().
2960 *
2961 * This function prints the last part of the ascii representation of
2962 * @p child, which consists of the string @c " on " followed by the
2963 * name and unit of the @p dev.
2964 *
2965 * @returns the number of characters printed
2966 */
2967int
2968bus_print_child_footer(device_t dev, device_t child)
2969{
2970	return (printf(" on %s\n", device_get_nameunit(dev)));
2971}
2972
2973/**
2974 * @brief Helper function for implementing BUS_PRINT_CHILD().
2975 *
2976 * This function simply calls bus_print_child_header() followed by
2977 * bus_print_child_footer().
2978 *
2979 * @returns the number of characters printed
2980 */
2981int
2982bus_generic_print_child(device_t dev, device_t child)
2983{
2984	int	retval = 0;
2985
2986	retval += bus_print_child_header(dev, child);
2987	retval += bus_print_child_footer(dev, child);
2988
2989	return (retval);
2990}
2991
2992/**
2993 * @brief Stub function for implementing BUS_READ_IVAR().
2994 *
2995 * @returns ENOENT
2996 */
2997int
2998bus_generic_read_ivar(device_t dev, device_t child, int index,
2999    uintptr_t * result)
3000{
3001	return (ENOENT);
3002}
3003
3004/**
3005 * @brief Stub function for implementing BUS_WRITE_IVAR().
3006 *
3007 * @returns ENOENT
3008 */
3009int
3010bus_generic_write_ivar(device_t dev, device_t child, int index,
3011    uintptr_t value)
3012{
3013	return (ENOENT);
3014}
3015
3016/**
3017 * @brief Stub function for implementing BUS_GET_RESOURCE_LIST().
3018 *
3019 * @returns NULL
3020 */
3021struct resource_list *
3022bus_generic_get_resource_list(device_t dev, device_t child)
3023{
3024	return (NULL);
3025}
3026
3027/**
3028 * @brief Helper function for implementing BUS_DRIVER_ADDED().
3029 *
3030 * This implementation of BUS_DRIVER_ADDED() simply calls the driver's
3031 * DEVICE_IDENTIFY() method to allow it to add new children to the bus
3032 * and then calls device_probe_and_attach() for each unattached child.
3033 */
3034void
3035bus_generic_driver_added(device_t dev, driver_t *driver)
3036{
3037	device_t child;
3038
3039	DEVICE_IDENTIFY(driver, dev);
3040	TAILQ_FOREACH(child, &dev->children, link) {
3041		if (child->state == DS_NOTPRESENT ||
3042		    (child->flags & DF_REBID))
3043			device_probe_and_attach(child);
3044	}
3045}
3046
3047/**
3048 * @brief Helper function for implementing BUS_SETUP_INTR().
3049 *
3050 * This simple implementation of BUS_SETUP_INTR() simply calls the
3051 * BUS_SETUP_INTR() method of the parent of @p dev.
3052 */
3053int
3054bus_generic_setup_intr(device_t dev, device_t child, struct resource *irq,
3055    int flags, driver_intr_t *intr, void *arg, void **cookiep)
3056{
3057	/* Propagate up the bus hierarchy until someone handles it. */
3058	if (dev->parent)
3059		return (BUS_SETUP_INTR(dev->parent, child, irq, flags,
3060		    intr, arg, cookiep));
3061	return (EINVAL);
3062}
3063
3064/**
3065 * @brief Helper function for implementing BUS_TEARDOWN_INTR().
3066 *
3067 * This simple implementation of BUS_TEARDOWN_INTR() simply calls the
3068 * BUS_TEARDOWN_INTR() method of the parent of @p dev.
3069 */
3070int
3071bus_generic_teardown_intr(device_t dev, device_t child, struct resource *irq,
3072    void *cookie)
3073{
3074	/* Propagate up the bus hierarchy until someone handles it. */
3075	if (dev->parent)
3076		return (BUS_TEARDOWN_INTR(dev->parent, child, irq, cookie));
3077	return (EINVAL);
3078}
3079
3080/**
3081 * @brief Helper function for implementing BUS_ALLOC_RESOURCE().
3082 *
3083 * This simple implementation of BUS_ALLOC_RESOURCE() simply calls the
3084 * BUS_ALLOC_RESOURCE() method of the parent of @p dev.
3085 */
3086struct resource *
3087bus_generic_alloc_resource(device_t dev, device_t child, int type, int *rid,
3088    u_long start, u_long end, u_long count, u_int flags)
3089{
3090	/* Propagate up the bus hierarchy until someone handles it. */
3091	if (dev->parent)
3092		return (BUS_ALLOC_RESOURCE(dev->parent, child, type, rid,
3093		    start, end, count, flags));
3094	return (NULL);
3095}
3096
3097/**
3098 * @brief Helper function for implementing BUS_RELEASE_RESOURCE().
3099 *
3100 * This simple implementation of BUS_RELEASE_RESOURCE() simply calls the
3101 * BUS_RELEASE_RESOURCE() method of the parent of @p dev.
3102 */
3103int
3104bus_generic_release_resource(device_t dev, device_t child, int type, int rid,
3105    struct resource *r)
3106{
3107	/* Propagate up the bus hierarchy until someone handles it. */
3108	if (dev->parent)
3109		return (BUS_RELEASE_RESOURCE(dev->parent, child, type, rid,
3110		    r));
3111	return (EINVAL);
3112}
3113
3114/**
3115 * @brief Helper function for implementing BUS_ACTIVATE_RESOURCE().
3116 *
3117 * This simple implementation of BUS_ACTIVATE_RESOURCE() simply calls the
3118 * BUS_ACTIVATE_RESOURCE() method of the parent of @p dev.
3119 */
3120int
3121bus_generic_activate_resource(device_t dev, device_t child, int type, int rid,
3122    struct resource *r)
3123{
3124	/* Propagate up the bus hierarchy until someone handles it. */
3125	if (dev->parent)
3126		return (BUS_ACTIVATE_RESOURCE(dev->parent, child, type, rid,
3127		    r));
3128	return (EINVAL);
3129}
3130
3131/**
3132 * @brief Helper function for implementing BUS_DEACTIVATE_RESOURCE().
3133 *
3134 * This simple implementation of BUS_DEACTIVATE_RESOURCE() simply calls the
3135 * BUS_DEACTIVATE_RESOURCE() method of the parent of @p dev.
3136 */
3137int
3138bus_generic_deactivate_resource(device_t dev, device_t child, int type,
3139    int rid, struct resource *r)
3140{
3141	/* Propagate up the bus hierarchy until someone handles it. */
3142	if (dev->parent)
3143		return (BUS_DEACTIVATE_RESOURCE(dev->parent, child, type, rid,
3144		    r));
3145	return (EINVAL);
3146}
3147
3148/**
3149 * @brief Helper function for implementing BUS_CONFIG_INTR().
3150 *
3151 * This simple implementation of BUS_CONFIG_INTR() simply calls the
3152 * BUS_CONFIG_INTR() method of the parent of @p dev.
3153 */
3154int
3155bus_generic_config_intr(device_t dev, int irq, enum intr_trigger trig,
3156    enum intr_polarity pol)
3157{
3158
3159	/* Propagate up the bus hierarchy until someone handles it. */
3160	if (dev->parent)
3161		return (BUS_CONFIG_INTR(dev->parent, irq, trig, pol));
3162	return (EINVAL);
3163}
3164
3165/**
3166 * @brief Helper function for implementing BUS_GET_RESOURCE().
3167 *
3168 * This implementation of BUS_GET_RESOURCE() uses the
3169 * resource_list_find() function to do most of the work. It calls
3170 * BUS_GET_RESOURCE_LIST() to find a suitable resource list to
3171 * search.
3172 */
3173int
3174bus_generic_rl_get_resource(device_t dev, device_t child, int type, int rid,
3175    u_long *startp, u_long *countp)
3176{
3177	struct resource_list *		rl = NULL;
3178	struct resource_list_entry *	rle = NULL;
3179
3180	rl = BUS_GET_RESOURCE_LIST(dev, child);
3181	if (!rl)
3182		return (EINVAL);
3183
3184	rle = resource_list_find(rl, type, rid);
3185	if (!rle)
3186		return (ENOENT);
3187
3188	if (startp)
3189		*startp = rle->start;
3190	if (countp)
3191		*countp = rle->count;
3192
3193	return (0);
3194}
3195
3196/**
3197 * @brief Helper function for implementing BUS_SET_RESOURCE().
3198 *
3199 * This implementation of BUS_SET_RESOURCE() uses the
3200 * resource_list_add() function to do most of the work. It calls
3201 * BUS_GET_RESOURCE_LIST() to find a suitable resource list to
3202 * edit.
3203 */
3204int
3205bus_generic_rl_set_resource(device_t dev, device_t child, int type, int rid,
3206    u_long start, u_long count)
3207{
3208	struct resource_list *		rl = NULL;
3209
3210	rl = BUS_GET_RESOURCE_LIST(dev, child);
3211	if (!rl)
3212		return (EINVAL);
3213
3214	resource_list_add(rl, type, rid, start, (start + count - 1), count);
3215
3216	return (0);
3217}
3218
3219/**
3220 * @brief Helper function for implementing BUS_DELETE_RESOURCE().
3221 *
3222 * This implementation of BUS_DELETE_RESOURCE() uses the
3223 * resource_list_delete() function to do most of the work. It calls
3224 * BUS_GET_RESOURCE_LIST() to find a suitable resource list to
3225 * edit.
3226 */
3227void
3228bus_generic_rl_delete_resource(device_t dev, device_t child, int type, int rid)
3229{
3230	struct resource_list *		rl = NULL;
3231
3232	rl = BUS_GET_RESOURCE_LIST(dev, child);
3233	if (!rl)
3234		return;
3235
3236	resource_list_delete(rl, type, rid);
3237
3238	return;
3239}
3240
3241/**
3242 * @brief Helper function for implementing BUS_RELEASE_RESOURCE().
3243 *
3244 * This implementation of BUS_RELEASE_RESOURCE() uses the
3245 * resource_list_release() function to do most of the work. It calls
3246 * BUS_GET_RESOURCE_LIST() to find a suitable resource list.
3247 */
3248int
3249bus_generic_rl_release_resource(device_t dev, device_t child, int type,
3250    int rid, struct resource *r)
3251{
3252	struct resource_list *		rl = NULL;
3253
3254	rl = BUS_GET_RESOURCE_LIST(dev, child);
3255	if (!rl)
3256		return (EINVAL);
3257
3258	return (resource_list_release(rl, dev, child, type, rid, r));
3259}
3260
3261/**
3262 * @brief Helper function for implementing BUS_ALLOC_RESOURCE().
3263 *
3264 * This implementation of BUS_ALLOC_RESOURCE() uses the
3265 * resource_list_alloc() function to do most of the work. It calls
3266 * BUS_GET_RESOURCE_LIST() to find a suitable resource list.
3267 */
3268struct resource *
3269bus_generic_rl_alloc_resource(device_t dev, device_t child, int type,
3270    int *rid, u_long start, u_long end, u_long count, u_int flags)
3271{
3272	struct resource_list *		rl = NULL;
3273
3274	rl = BUS_GET_RESOURCE_LIST(dev, child);
3275	if (!rl)
3276		return (NULL);
3277
3278	return (resource_list_alloc(rl, dev, child, type, rid,
3279	    start, end, count, flags));
3280}
3281
3282/**
3283 * @brief Helper function for implementing BUS_CHILD_PRESENT().
3284 *
3285 * This simple implementation of BUS_CHILD_PRESENT() simply calls the
3286 * BUS_CHILD_PRESENT() method of the parent of @p dev.
3287 */
3288int
3289bus_generic_child_present(device_t dev, device_t child)
3290{
3291	return (BUS_CHILD_PRESENT(device_get_parent(dev), dev));
3292}
3293
3294/*
3295 * Some convenience functions to make it easier for drivers to use the
3296 * resource-management functions.  All these really do is hide the
3297 * indirection through the parent's method table, making for slightly
3298 * less-wordy code.  In the future, it might make sense for this code
3299 * to maintain some sort of a list of resources allocated by each device.
3300 */
3301
3302/**
3303 * @brief Wrapper function for BUS_ALLOC_RESOURCE().
3304 *
3305 * This function simply calls the BUS_ALLOC_RESOURCE() method of the
3306 * parent of @p dev.
3307 */
3308struct resource *
3309bus_alloc_resource(device_t dev, int type, int *rid, u_long start, u_long end,
3310    u_long count, u_int flags)
3311{
3312	if (dev->parent == 0)
3313		return (0);
3314	return (BUS_ALLOC_RESOURCE(dev->parent, dev, type, rid, start, end,
3315	    count, flags));
3316}
3317
3318/**
3319 * @brief Wrapper function for BUS_ACTIVATE_RESOURCE().
3320 *
3321 * This function simply calls the BUS_ACTIVATE_RESOURCE() method of the
3322 * parent of @p dev.
3323 */
3324int
3325bus_activate_resource(device_t dev, int type, int rid, struct resource *r)
3326{
3327	if (dev->parent == 0)
3328		return (EINVAL);
3329	return (BUS_ACTIVATE_RESOURCE(dev->parent, dev, type, rid, r));
3330}
3331
3332/**
3333 * @brief Wrapper function for BUS_DEACTIVATE_RESOURCE().
3334 *
3335 * This function simply calls the BUS_DEACTIVATE_RESOURCE() method of the
3336 * parent of @p dev.
3337 */
3338int
3339bus_deactivate_resource(device_t dev, int type, int rid, struct resource *r)
3340{
3341	if (dev->parent == 0)
3342		return (EINVAL);
3343	return (BUS_DEACTIVATE_RESOURCE(dev->parent, dev, type, rid, r));
3344}
3345
3346/**
3347 * @brief Wrapper function for BUS_RELEASE_RESOURCE().
3348 *
3349 * This function simply calls the BUS_RELEASE_RESOURCE() method of the
3350 * parent of @p dev.
3351 */
3352int
3353bus_release_resource(device_t dev, int type, int rid, struct resource *r)
3354{
3355	if (dev->parent == 0)
3356		return (EINVAL);
3357	return (BUS_RELEASE_RESOURCE(dev->parent, dev, type, rid, r));
3358}
3359
3360/**
3361 * @brief Wrapper function for BUS_SETUP_INTR().
3362 *
3363 * This function simply calls the BUS_SETUP_INTR() method of the
3364 * parent of @p dev.
3365 */
3366int
3367bus_setup_intr(device_t dev, struct resource *r, int flags,
3368    driver_intr_t handler, void *arg, void **cookiep)
3369{
3370	int error;
3371
3372	if (dev->parent != 0) {
3373		if ((flags &~ INTR_ENTROPY) == (INTR_TYPE_NET | INTR_MPSAFE) &&
3374		    !debug_mpsafenet)
3375			flags &= ~INTR_MPSAFE;
3376		error = BUS_SETUP_INTR(dev->parent, dev, r, flags,
3377		    handler, arg, cookiep);
3378		if (error == 0) {
3379			if (!(flags & (INTR_MPSAFE | INTR_FAST)))
3380				device_printf(dev, "[GIANT-LOCKED]\n");
3381			if (bootverbose && (flags & INTR_MPSAFE))
3382				device_printf(dev, "[MPSAFE]\n");
3383			if (flags & INTR_FAST)
3384				device_printf(dev, "[FAST]\n");
3385		}
3386	} else
3387		error = EINVAL;
3388	return (error);
3389}
3390
3391/**
3392 * @brief Wrapper function for BUS_TEARDOWN_INTR().
3393 *
3394 * This function simply calls the BUS_TEARDOWN_INTR() method of the
3395 * parent of @p dev.
3396 */
3397int
3398bus_teardown_intr(device_t dev, struct resource *r, void *cookie)
3399{
3400	if (dev->parent == 0)
3401		return (EINVAL);
3402	return (BUS_TEARDOWN_INTR(dev->parent, dev, r, cookie));
3403}
3404
3405/**
3406 * @brief Wrapper function for BUS_SET_RESOURCE().
3407 *
3408 * This function simply calls the BUS_SET_RESOURCE() method of the
3409 * parent of @p dev.
3410 */
3411int
3412bus_set_resource(device_t dev, int type, int rid,
3413    u_long start, u_long count)
3414{
3415	return (BUS_SET_RESOURCE(device_get_parent(dev), dev, type, rid,
3416	    start, count));
3417}
3418
3419/**
3420 * @brief Wrapper function for BUS_GET_RESOURCE().
3421 *
3422 * This function simply calls the BUS_GET_RESOURCE() method of the
3423 * parent of @p dev.
3424 */
3425int
3426bus_get_resource(device_t dev, int type, int rid,
3427    u_long *startp, u_long *countp)
3428{
3429	return (BUS_GET_RESOURCE(device_get_parent(dev), dev, type, rid,
3430	    startp, countp));
3431}
3432
3433/**
3434 * @brief Wrapper function for BUS_GET_RESOURCE().
3435 *
3436 * This function simply calls the BUS_GET_RESOURCE() method of the
3437 * parent of @p dev and returns the start value.
3438 */
3439u_long
3440bus_get_resource_start(device_t dev, int type, int rid)
3441{
3442	u_long start, count;
3443	int error;
3444
3445	error = BUS_GET_RESOURCE(device_get_parent(dev), dev, type, rid,
3446	    &start, &count);
3447	if (error)
3448		return (0);
3449	return (start);
3450}
3451
3452/**
3453 * @brief Wrapper function for BUS_GET_RESOURCE().
3454 *
3455 * This function simply calls the BUS_GET_RESOURCE() method of the
3456 * parent of @p dev and returns the count value.
3457 */
3458u_long
3459bus_get_resource_count(device_t dev, int type, int rid)
3460{
3461	u_long start, count;
3462	int error;
3463
3464	error = BUS_GET_RESOURCE(device_get_parent(dev), dev, type, rid,
3465	    &start, &count);
3466	if (error)
3467		return (0);
3468	return (count);
3469}
3470
3471/**
3472 * @brief Wrapper function for BUS_DELETE_RESOURCE().
3473 *
3474 * This function simply calls the BUS_DELETE_RESOURCE() method of the
3475 * parent of @p dev.
3476 */
3477void
3478bus_delete_resource(device_t dev, int type, int rid)
3479{
3480	BUS_DELETE_RESOURCE(device_get_parent(dev), dev, type, rid);
3481}
3482
3483/**
3484 * @brief Wrapper function for BUS_CHILD_PRESENT().
3485 *
3486 * This function simply calls the BUS_CHILD_PRESENT() method of the
3487 * parent of @p dev.
3488 */
3489int
3490bus_child_present(device_t child)
3491{
3492	return (BUS_CHILD_PRESENT(device_get_parent(child), child));
3493}
3494
3495/**
3496 * @brief Wrapper function for BUS_CHILD_PNPINFO_STR().
3497 *
3498 * This function simply calls the BUS_CHILD_PNPINFO_STR() method of the
3499 * parent of @p dev.
3500 */
3501int
3502bus_child_pnpinfo_str(device_t child, char *buf, size_t buflen)
3503{
3504	device_t parent;
3505
3506	parent = device_get_parent(child);
3507	if (parent == NULL) {
3508		*buf = '\0';
3509		return (0);
3510	}
3511	return (BUS_CHILD_PNPINFO_STR(parent, child, buf, buflen));
3512}
3513
3514/**
3515 * @brief Wrapper function for BUS_CHILD_LOCATION_STR().
3516 *
3517 * This function simply calls the BUS_CHILD_LOCATION_STR() method of the
3518 * parent of @p dev.
3519 */
3520int
3521bus_child_location_str(device_t child, char *buf, size_t buflen)
3522{
3523	device_t parent;
3524
3525	parent = device_get_parent(child);
3526	if (parent == NULL) {
3527		*buf = '\0';
3528		return (0);
3529	}
3530	return (BUS_CHILD_LOCATION_STR(parent, child, buf, buflen));
3531}
3532
3533static int
3534root_print_child(device_t dev, device_t child)
3535{
3536	int	retval = 0;
3537
3538	retval += bus_print_child_header(dev, child);
3539	retval += printf("\n");
3540
3541	return (retval);
3542}
3543
3544static int
3545root_setup_intr(device_t dev, device_t child, driver_intr_t *intr, void *arg,
3546    void **cookiep)
3547{
3548	/*
3549	 * If an interrupt mapping gets to here something bad has happened.
3550	 */
3551	panic("root_setup_intr");
3552}
3553
3554/*
3555 * If we get here, assume that the device is permanant and really is
3556 * present in the system.  Removable bus drivers are expected to intercept
3557 * this call long before it gets here.  We return -1 so that drivers that
3558 * really care can check vs -1 or some ERRNO returned higher in the food
3559 * chain.
3560 */
3561static int
3562root_child_present(device_t dev, device_t child)
3563{
3564	return (-1);
3565}
3566
3567static kobj_method_t root_methods[] = {
3568	/* Device interface */
3569	KOBJMETHOD(device_shutdown,	bus_generic_shutdown),
3570	KOBJMETHOD(device_suspend,	bus_generic_suspend),
3571	KOBJMETHOD(device_resume,	bus_generic_resume),
3572
3573	/* Bus interface */
3574	KOBJMETHOD(bus_print_child,	root_print_child),
3575	KOBJMETHOD(bus_read_ivar,	bus_generic_read_ivar),
3576	KOBJMETHOD(bus_write_ivar,	bus_generic_write_ivar),
3577	KOBJMETHOD(bus_setup_intr,	root_setup_intr),
3578	KOBJMETHOD(bus_child_present,	root_child_present),
3579
3580	{ 0, 0 }
3581};
3582
3583static driver_t root_driver = {
3584	"root",
3585	root_methods,
3586	1,			/* no softc */
3587};
3588
3589device_t	root_bus;
3590devclass_t	root_devclass;
3591
3592static int
3593root_bus_module_handler(module_t mod, int what, void* arg)
3594{
3595	switch (what) {
3596	case MOD_LOAD:
3597		TAILQ_INIT(&bus_data_devices);
3598		kobj_class_compile((kobj_class_t) &root_driver);
3599		root_bus = make_device(NULL, "root", 0);
3600		root_bus->desc = "System root bus";
3601		kobj_init((kobj_t) root_bus, (kobj_class_t) &root_driver);
3602		root_bus->driver = &root_driver;
3603		root_bus->state = DS_ATTACHED;
3604		root_devclass = devclass_find_internal("root", 0, FALSE);
3605		devinit();
3606		return (0);
3607
3608	case MOD_SHUTDOWN:
3609		device_shutdown(root_bus);
3610		return (0);
3611	default:
3612		return (EOPNOTSUPP);
3613	}
3614
3615	return (0);
3616}
3617
3618static moduledata_t root_bus_mod = {
3619	"rootbus",
3620	root_bus_module_handler,
3621	0
3622};
3623DECLARE_MODULE(rootbus, root_bus_mod, SI_SUB_DRIVERS, SI_ORDER_FIRST);
3624
3625/**
3626 * @brief Automatically configure devices
3627 *
3628 * This function begins the autoconfiguration process by calling
3629 * device_probe_and_attach() for each child of the @c root0 device.
3630 */
3631void
3632root_bus_configure(void)
3633{
3634	device_t dev;
3635
3636	PDEBUG(("."));
3637
3638	TAILQ_FOREACH(dev, &root_bus->children, link) {
3639		device_probe_and_attach(dev);
3640	}
3641}
3642
3643/**
3644 * @brief Module handler for registering device drivers
3645 *
3646 * This module handler is used to automatically register device
3647 * drivers when modules are loaded. If @p what is MOD_LOAD, it calls
3648 * devclass_add_driver() for the driver described by the
3649 * driver_module_data structure pointed to by @p arg
3650 */
3651int
3652driver_module_handler(module_t mod, int what, void *arg)
3653{
3654	int error;
3655	struct driver_module_data *dmd;
3656	devclass_t bus_devclass;
3657	kobj_class_t driver;
3658
3659	dmd = (struct driver_module_data *)arg;
3660	bus_devclass = devclass_find_internal(dmd->dmd_busname, 0, TRUE);
3661	error = 0;
3662
3663	switch (what) {
3664	case MOD_LOAD:
3665		if (dmd->dmd_chainevh)
3666			error = dmd->dmd_chainevh(mod,what,dmd->dmd_chainarg);
3667
3668		driver = dmd->dmd_driver;
3669		PDEBUG(("Loading module: driver %s on bus %s",
3670		    DRIVERNAME(driver), dmd->dmd_busname));
3671		error = devclass_add_driver(bus_devclass, driver);
3672		if (error)
3673			break;
3674
3675		/*
3676		 * If the driver has any base classes, make the
3677		 * devclass inherit from the devclass of the driver's
3678		 * first base class. This will allow the system to
3679		 * search for drivers in both devclasses for children
3680		 * of a device using this driver.
3681		 */
3682		if (driver->baseclasses) {
3683			const char *parentname;
3684			parentname = driver->baseclasses[0]->name;
3685			*dmd->dmd_devclass =
3686				devclass_find_internal(driver->name,
3687				    parentname, TRUE);
3688		} else {
3689			*dmd->dmd_devclass =
3690				devclass_find_internal(driver->name, 0, TRUE);
3691		}
3692		break;
3693
3694	case MOD_UNLOAD:
3695		PDEBUG(("Unloading module: driver %s from bus %s",
3696		    DRIVERNAME(dmd->dmd_driver),
3697		    dmd->dmd_busname));
3698		error = devclass_delete_driver(bus_devclass,
3699		    dmd->dmd_driver);
3700
3701		if (!error && dmd->dmd_chainevh)
3702			error = dmd->dmd_chainevh(mod,what,dmd->dmd_chainarg);
3703		break;
3704	case MOD_QUIESCE:
3705		PDEBUG(("Quiesce module: driver %s from bus %s",
3706		    DRIVERNAME(dmd->dmd_driver),
3707		    dmd->dmd_busname));
3708		error = devclass_quiesce_driver(bus_devclass,
3709		    dmd->dmd_driver);
3710
3711		if (!error && dmd->dmd_chainevh)
3712			error = dmd->dmd_chainevh(mod,what,dmd->dmd_chainarg);
3713		break;
3714	default:
3715		error = EOPNOTSUPP;
3716		break;
3717	}
3718
3719	return (error);
3720}
3721
3722#ifdef BUS_DEBUG
3723
3724/* the _short versions avoid iteration by not calling anything that prints
3725 * more than oneliners. I love oneliners.
3726 */
3727
3728static void
3729print_device_short(device_t dev, int indent)
3730{
3731	if (!dev)
3732		return;
3733
3734	indentprintf(("device %d: <%s> %sparent,%schildren,%s%s%s%s%s,%sivars,%ssoftc,busy=%d\n",
3735	    dev->unit, dev->desc,
3736	    (dev->parent? "":"no "),
3737	    (TAILQ_EMPTY(&dev->children)? "no ":""),
3738	    (dev->flags&DF_ENABLED? "enabled,":"disabled,"),
3739	    (dev->flags&DF_FIXEDCLASS? "fixed,":""),
3740	    (dev->flags&DF_WILDCARD? "wildcard,":""),
3741	    (dev->flags&DF_DESCMALLOCED? "descmalloced,":""),
3742	    (dev->flags&DF_REBID? "rebiddable,":""),
3743	    (dev->ivars? "":"no "),
3744	    (dev->softc? "":"no "),
3745	    dev->busy));
3746}
3747
3748static void
3749print_device(device_t dev, int indent)
3750{
3751	if (!dev)
3752		return;
3753
3754	print_device_short(dev, indent);
3755
3756	indentprintf(("Parent:\n"));
3757	print_device_short(dev->parent, indent+1);
3758	indentprintf(("Driver:\n"));
3759	print_driver_short(dev->driver, indent+1);
3760	indentprintf(("Devclass:\n"));
3761	print_devclass_short(dev->devclass, indent+1);
3762}
3763
3764void
3765print_device_tree_short(device_t dev, int indent)
3766/* print the device and all its children (indented) */
3767{
3768	device_t child;
3769
3770	if (!dev)
3771		return;
3772
3773	print_device_short(dev, indent);
3774
3775	TAILQ_FOREACH(child, &dev->children, link) {
3776		print_device_tree_short(child, indent+1);
3777	}
3778}
3779
3780void
3781print_device_tree(device_t dev, int indent)
3782/* print the device and all its children (indented) */
3783{
3784	device_t child;
3785
3786	if (!dev)
3787		return;
3788
3789	print_device(dev, indent);
3790
3791	TAILQ_FOREACH(child, &dev->children, link) {
3792		print_device_tree(child, indent+1);
3793	}
3794}
3795
3796static void
3797print_driver_short(driver_t *driver, int indent)
3798{
3799	if (!driver)
3800		return;
3801
3802	indentprintf(("driver %s: softc size = %zd\n",
3803	    driver->name, driver->size));
3804}
3805
3806static void
3807print_driver(driver_t *driver, int indent)
3808{
3809	if (!driver)
3810		return;
3811
3812	print_driver_short(driver, indent);
3813}
3814
3815
3816static void
3817print_driver_list(driver_list_t drivers, int indent)
3818{
3819	driverlink_t driver;
3820
3821	TAILQ_FOREACH(driver, &drivers, link) {
3822		print_driver(driver->driver, indent);
3823	}
3824}
3825
3826static void
3827print_devclass_short(devclass_t dc, int indent)
3828{
3829	if ( !dc )
3830		return;
3831
3832	indentprintf(("devclass %s: max units = %d\n", dc->name, dc->maxunit));
3833}
3834
3835static void
3836print_devclass(devclass_t dc, int indent)
3837{
3838	int i;
3839
3840	if ( !dc )
3841		return;
3842
3843	print_devclass_short(dc, indent);
3844	indentprintf(("Drivers:\n"));
3845	print_driver_list(dc->drivers, indent+1);
3846
3847	indentprintf(("Devices:\n"));
3848	for (i = 0; i < dc->maxunit; i++)
3849		if (dc->devices[i])
3850			print_device(dc->devices[i], indent+1);
3851}
3852
3853void
3854print_devclass_list_short(void)
3855{
3856	devclass_t dc;
3857
3858	printf("Short listing of devclasses, drivers & devices:\n");
3859	TAILQ_FOREACH(dc, &devclasses, link) {
3860		print_devclass_short(dc, 0);
3861	}
3862}
3863
3864void
3865print_devclass_list(void)
3866{
3867	devclass_t dc;
3868
3869	printf("Full listing of devclasses, drivers & devices:\n");
3870	TAILQ_FOREACH(dc, &devclasses, link) {
3871		print_devclass(dc, 0);
3872	}
3873}
3874
3875#endif
3876
3877/*
3878 * User-space access to the device tree.
3879 *
3880 * We implement a small set of nodes:
3881 *
3882 * hw.bus			Single integer read method to obtain the
3883 *				current generation count.
3884 * hw.bus.devices		Reads the entire device tree in flat space.
3885 * hw.bus.rman			Resource manager interface
3886 *
3887 * We might like to add the ability to scan devclasses and/or drivers to
3888 * determine what else is currently loaded/available.
3889 */
3890
3891static int
3892sysctl_bus(SYSCTL_HANDLER_ARGS)
3893{
3894	struct u_businfo	ubus;
3895
3896	ubus.ub_version = BUS_USER_VERSION;
3897	ubus.ub_generation = bus_data_generation;
3898
3899	return (SYSCTL_OUT(req, &ubus, sizeof(ubus)));
3900}
3901SYSCTL_NODE(_hw_bus, OID_AUTO, info, CTLFLAG_RW, sysctl_bus,
3902    "bus-related data");
3903
3904static int
3905sysctl_devices(SYSCTL_HANDLER_ARGS)
3906{
3907	int			*name = (int *)arg1;
3908	u_int			namelen = arg2;
3909	int			index;
3910	struct device		*dev;
3911	struct u_device		udev;	/* XXX this is a bit big */
3912	int			error;
3913
3914	if (namelen != 2)
3915		return (EINVAL);
3916
3917	if (bus_data_generation_check(name[0]))
3918		return (EINVAL);
3919
3920	index = name[1];
3921
3922	/*
3923	 * Scan the list of devices, looking for the requested index.
3924	 */
3925	TAILQ_FOREACH(dev, &bus_data_devices, devlink) {
3926		if (index-- == 0)
3927			break;
3928	}
3929	if (dev == NULL)
3930		return (ENOENT);
3931
3932	/*
3933	 * Populate the return array.
3934	 */
3935	udev.dv_handle = (uintptr_t)dev;
3936	udev.dv_parent = (uintptr_t)dev->parent;
3937	if (dev->nameunit == NULL)
3938		udev.dv_name[0] = '\0';
3939	else
3940		strlcpy(udev.dv_name, dev->nameunit, sizeof(udev.dv_name));
3941
3942	if (dev->desc == NULL)
3943		udev.dv_desc[0] = '\0';
3944	else
3945		strlcpy(udev.dv_desc, dev->desc, sizeof(udev.dv_desc));
3946	if (dev->driver == NULL || dev->driver->name == NULL)
3947		udev.dv_drivername[0] = '\0';
3948	else
3949		strlcpy(udev.dv_drivername, dev->driver->name,
3950		    sizeof(udev.dv_drivername));
3951	udev.dv_pnpinfo[0] = '\0';
3952	udev.dv_location[0] = '\0';
3953	bus_child_pnpinfo_str(dev, udev.dv_pnpinfo, sizeof(udev.dv_pnpinfo));
3954	bus_child_location_str(dev, udev.dv_location, sizeof(udev.dv_location));
3955	udev.dv_devflags = dev->devflags;
3956	udev.dv_flags = dev->flags;
3957	udev.dv_state = dev->state;
3958	error = SYSCTL_OUT(req, &udev, sizeof(udev));
3959	return (error);
3960}
3961
3962SYSCTL_NODE(_hw_bus, OID_AUTO, devices, CTLFLAG_RD, sysctl_devices,
3963    "system device tree");
3964
3965int
3966bus_data_generation_check(int generation)
3967{
3968	if (generation != bus_data_generation)
3969		return (1);
3970
3971	/* XXX generate optimised lists here? */
3972	return (0);
3973}
3974
3975void
3976bus_data_generation_update(void)
3977{
3978	bus_data_generation++;
3979}
3980
3981int
3982bus_free_resource(device_t dev, int type, struct resource *r)
3983{
3984	if (r == NULL)
3985		return (0);
3986	return (bus_release_resource(dev, type, rman_get_rid(r), r));
3987}
3988