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