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