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