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