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