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