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