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