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