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