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