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