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