xref: /dflybsd-src/sys/kern/subr_bus.c (revision cb772f36f3b1a772fad83bb0b968776358491a21)
1 /*
2  * Copyright (c) 1997,1998 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  * $FreeBSD: src/sys/kern/subr_bus.c,v 1.54.2.9 2002/10/10 15:13:32 jhb Exp $
27  * $DragonFly: src/sys/kern/subr_bus.c,v 1.46 2008/10/03 00:26:21 hasso Exp $
28  */
29 
30 #include "opt_bus.h"
31 
32 #include <sys/param.h>
33 #include <sys/queue.h>
34 #include <sys/malloc.h>
35 #include <sys/kernel.h>
36 #include <sys/module.h>
37 #include <sys/kobj.h>
38 #include <sys/bus_private.h>
39 #include <sys/sysctl.h>
40 #include <sys/systm.h>
41 #include <sys/bus.h>
42 #include <sys/rman.h>
43 #include <sys/device.h>
44 #include <sys/lock.h>
45 #include <sys/conf.h>
46 #include <sys/selinfo.h>
47 #include <sys/uio.h>
48 #include <sys/filio.h>
49 #include <sys/event.h>
50 #include <sys/signalvar.h>
51 
52 #include <machine/stdarg.h>	/* for device_printf() */
53 
54 #include <sys/thread2.h>
55 #include <sys/mplock2.h>
56 
57 SYSCTL_NODE(_hw, OID_AUTO, bus, CTLFLAG_RW, NULL, NULL);
58 
59 MALLOC_DEFINE(M_BUS, "bus", "Bus data structures");
60 
61 #ifdef BUS_DEBUG
62 #define PDEBUG(a)	(kprintf("%s:%d: ", __func__, __LINE__), kprintf a, kprintf("\n"))
63 #define DEVICENAME(d)	((d)? device_get_name(d): "no device")
64 #define DRIVERNAME(d)	((d)? d->name : "no driver")
65 #define DEVCLANAME(d)	((d)? d->name : "no devclass")
66 
67 /* Produce the indenting, indent*2 spaces plus a '.' ahead of that to
68  * prevent syslog from deleting initial spaces
69  */
70 #define indentprintf(p)	do { int iJ; kprintf("."); for (iJ=0; iJ<indent; iJ++) kprintf("  "); kprintf p ; } while(0)
71 
72 static void	print_device_short(device_t dev, int indent);
73 static void	print_device(device_t dev, int indent);
74 void		print_device_tree_short(device_t dev, int indent);
75 void		print_device_tree(device_t dev, int indent);
76 static void	print_driver_short(driver_t *driver, int indent);
77 static void	print_driver(driver_t *driver, int indent);
78 static void	print_driver_list(driver_list_t drivers, int indent);
79 static void	print_devclass_short(devclass_t dc, int indent);
80 static void	print_devclass(devclass_t dc, int indent);
81 void		print_devclass_list_short(void);
82 void		print_devclass_list(void);
83 
84 #else
85 /* Make the compiler ignore the function calls */
86 #define PDEBUG(a)			/* nop */
87 #define DEVICENAME(d)			/* nop */
88 #define DRIVERNAME(d)			/* nop */
89 #define DEVCLANAME(d)			/* nop */
90 
91 #define print_device_short(d,i)		/* nop */
92 #define print_device(d,i)		/* nop */
93 #define print_device_tree_short(d,i)	/* nop */
94 #define print_device_tree(d,i)		/* nop */
95 #define print_driver_short(d,i)		/* nop */
96 #define print_driver(d,i)		/* nop */
97 #define print_driver_list(d,i)		/* nop */
98 #define print_devclass_short(d,i)	/* nop */
99 #define print_devclass(d,i)		/* nop */
100 #define print_devclass_list_short()	/* nop */
101 #define print_devclass_list()		/* nop */
102 #endif
103 
104 static void	device_attach_async(device_t dev);
105 static void	device_attach_thread(void *arg);
106 static int	device_doattach(device_t dev);
107 
108 static int do_async_attach = 0;
109 static int numasyncthreads;
110 TUNABLE_INT("kern.do_async_attach", &do_async_attach);
111 
112 /*
113  * /dev/devctl implementation
114  */
115 
116 /*
117  * This design allows only one reader for /dev/devctl.  This is not desirable
118  * in the long run, but will get a lot of hair out of this implementation.
119  * Maybe we should make this device a clonable device.
120  *
121  * Also note: we specifically do not attach a device to the device_t tree
122  * to avoid potential chicken and egg problems.  One could argue that all
123  * of this belongs to the root node.  One could also further argue that the
124  * sysctl interface that we have not might more properly be an ioctl
125  * interface, but at this stage of the game, I'm not inclined to rock that
126  * boat.
127  *
128  * I'm also not sure that the SIGIO support is done correctly or not, as
129  * I copied it from a driver that had SIGIO support that likely hasn't been
130  * tested since 3.4 or 2.2.8!
131  */
132 
133 static int sysctl_devctl_disable(SYSCTL_HANDLER_ARGS);
134 static int devctl_disable = 0;
135 TUNABLE_INT("hw.bus.devctl_disable", &devctl_disable);
136 SYSCTL_PROC(_hw_bus, OID_AUTO, devctl_disable, CTLTYPE_INT | CTLFLAG_RW, 0, 0,
137     sysctl_devctl_disable, "I", "devctl disable");
138 
139 #define	CDEV_MAJOR	188
140 
141 static d_open_t		devopen;
142 static d_close_t	devclose;
143 static d_read_t		devread;
144 static d_ioctl_t	devioctl;
145 static d_kqfilter_t	devkqfilter;
146 
147 static struct dev_ops devctl_ops = {
148 	{ "devctl", CDEV_MAJOR, 0 },
149 	.d_open =	devopen,
150 	.d_close =	devclose,
151 	.d_read =	devread,
152 	.d_ioctl =	devioctl,
153 	.d_kqfilter =	devkqfilter
154 };
155 
156 struct dev_event_info
157 {
158 	char *dei_data;
159 	TAILQ_ENTRY(dev_event_info) dei_link;
160 };
161 
162 TAILQ_HEAD(devq, dev_event_info);
163 
164 static struct dev_softc
165 {
166 	int	inuse;
167 	int	nonblock;
168 	struct lock lock;
169 	struct selinfo sel;
170 	struct devq devq;
171 	struct proc *async_proc;
172 } devsoftc;
173 
174 static void
175 devinit(void)
176 {
177 	make_dev(&devctl_ops, 0, UID_ROOT, GID_WHEEL, 0600, "devctl");
178 	lockinit(&devsoftc.lock, "dev mtx", 0, 0);
179 	TAILQ_INIT(&devsoftc.devq);
180 }
181 
182 static int
183 devopen(struct dev_open_args *ap)
184 {
185 	if (devsoftc.inuse)
186 		return (EBUSY);
187 	/* move to init */
188 	devsoftc.inuse = 1;
189 	devsoftc.nonblock = 0;
190 	devsoftc.async_proc = NULL;
191 	return (0);
192 }
193 
194 static int
195 devclose(struct dev_close_args *ap)
196 {
197 	devsoftc.inuse = 0;
198 	lockmgr(&devsoftc.lock, LK_EXCLUSIVE);
199 	wakeup(&devsoftc);
200 	lockmgr(&devsoftc.lock, LK_RELEASE);
201 
202 	return (0);
203 }
204 
205 /*
206  * The read channel for this device is used to report changes to
207  * userland in realtime.  We are required to free the data as well as
208  * the n1 object because we allocate them separately.  Also note that
209  * we return one record at a time.  If you try to read this device a
210  * character at a time, you will lose the rest of the data.  Listening
211  * programs are expected to cope.
212  */
213 static int
214 devread(struct dev_read_args *ap)
215 {
216 	struct uio *uio = ap->a_uio;
217 	struct dev_event_info *n1;
218 	int rv;
219 
220 	lockmgr(&devsoftc.lock, LK_EXCLUSIVE);
221 	while (TAILQ_EMPTY(&devsoftc.devq)) {
222 		if (devsoftc.nonblock) {
223 			lockmgr(&devsoftc.lock, LK_RELEASE);
224 			return (EAGAIN);
225 		}
226 		tsleep_interlock(&devsoftc, PCATCH);
227 		lockmgr(&devsoftc.lock, LK_RELEASE);
228 		rv = tsleep(&devsoftc, PCATCH | PINTERLOCKED, "devctl", 0);
229 		lockmgr(&devsoftc.lock, LK_EXCLUSIVE);
230 		if (rv) {
231 			/*
232 			 * Need to translate ERESTART to EINTR here? -- jake
233 			 */
234 			lockmgr(&devsoftc.lock, LK_RELEASE);
235 			return (rv);
236 		}
237 	}
238 	n1 = TAILQ_FIRST(&devsoftc.devq);
239 	TAILQ_REMOVE(&devsoftc.devq, n1, dei_link);
240 	lockmgr(&devsoftc.lock, LK_RELEASE);
241 	rv = uiomove(n1->dei_data, strlen(n1->dei_data), uio);
242 	kfree(n1->dei_data, M_BUS);
243 	kfree(n1, M_BUS);
244 	return (rv);
245 }
246 
247 static	int
248 devioctl(struct dev_ioctl_args *ap)
249 {
250 	switch (ap->a_cmd) {
251 
252 	case FIONBIO:
253 		if (*(int*)ap->a_data)
254 			devsoftc.nonblock = 1;
255 		else
256 			devsoftc.nonblock = 0;
257 		return (0);
258 	case FIOASYNC:
259 		if (*(int*)ap->a_data)
260 			devsoftc.async_proc = curproc;
261 		else
262 			devsoftc.async_proc = NULL;
263 		return (0);
264 
265 		/* (un)Support for other fcntl() calls. */
266 	case FIOCLEX:
267 	case FIONCLEX:
268 	case FIONREAD:
269 	case FIOSETOWN:
270 	case FIOGETOWN:
271 	default:
272 		break;
273 	}
274 	return (ENOTTY);
275 }
276 
277 static void dev_filter_detach(struct knote *);
278 static int dev_filter_read(struct knote *, long);
279 
280 static struct filterops dev_filtops =
281 	{ 1, NULL, dev_filter_detach, dev_filter_read };
282 
283 static int
284 devkqfilter(struct dev_kqfilter_args *ap)
285 {
286 	struct knote *kn = ap->a_kn;
287 	struct klist *klist;
288 
289 	ap->a_result = 0;
290 	lockmgr(&devsoftc.lock, LK_EXCLUSIVE);
291 
292 	switch (kn->kn_filter) {
293 	case EVFILT_READ:
294 		kn->kn_fop = &dev_filtops;
295 		break;
296 	default:
297 		ap->a_result = EOPNOTSUPP;
298 		lockmgr(&devsoftc.lock, LK_RELEASE);
299 		return (0);
300 	}
301 
302 	crit_enter();
303 	klist = &devsoftc.sel.si_note;
304 	SLIST_INSERT_HEAD(klist, kn, kn_selnext);
305 	crit_exit();
306 
307 	lockmgr(&devsoftc.lock, LK_RELEASE);
308 
309 	return (0);
310 }
311 
312 static void
313 dev_filter_detach(struct knote *kn)
314 {
315 	struct klist *klist;
316 
317 	lockmgr(&devsoftc.lock, LK_EXCLUSIVE);
318 	crit_enter();
319 	klist = &devsoftc.sel.si_note;
320 	SLIST_INSERT_HEAD(klist, kn, kn_selnext);
321 	crit_exit();
322 	lockmgr(&devsoftc.lock, LK_RELEASE);
323 }
324 
325 static int
326 dev_filter_read(struct knote *kn, long hint)
327 {
328 	int ready = 0;
329 
330 	lockmgr(&devsoftc.lock, LK_EXCLUSIVE);
331 	if (!TAILQ_EMPTY(&devsoftc.devq))
332 		ready = 1;
333 	lockmgr(&devsoftc.lock, LK_RELEASE);
334 
335 	return (ready);
336 }
337 
338 
339 /**
340  * @brief Return whether the userland process is running
341  */
342 boolean_t
343 devctl_process_running(void)
344 {
345 	return (devsoftc.inuse == 1);
346 }
347 
348 /**
349  * @brief Queue data to be read from the devctl device
350  *
351  * Generic interface to queue data to the devctl device.  It is
352  * assumed that @p data is properly formatted.  It is further assumed
353  * that @p data is allocated using the M_BUS malloc type.
354  */
355 void
356 devctl_queue_data(char *data)
357 {
358 	struct dev_event_info *n1 = NULL;
359 	struct proc *p;
360 
361 	n1 = kmalloc(sizeof(*n1), M_BUS, M_NOWAIT);
362 	if (n1 == NULL)
363 		return;
364 	n1->dei_data = data;
365 	lockmgr(&devsoftc.lock, LK_EXCLUSIVE);
366 	TAILQ_INSERT_TAIL(&devsoftc.devq, n1, dei_link);
367 	wakeup(&devsoftc);
368 	lockmgr(&devsoftc.lock, LK_RELEASE);
369 	get_mplock();	/* XXX */
370 	KNOTE(&devsoftc.sel.si_note, 0);
371 	rel_mplock();	/* XXX */
372 	p = devsoftc.async_proc;
373 	if (p != NULL)
374 		ksignal(p, SIGIO);
375 }
376 
377 /**
378  * @brief Send a 'notification' to userland, using standard ways
379  */
380 void
381 devctl_notify(const char *system, const char *subsystem, const char *type,
382     const char *data)
383 {
384 	int len = 0;
385 	char *msg;
386 
387 	if (system == NULL)
388 		return;		/* BOGUS!  Must specify system. */
389 	if (subsystem == NULL)
390 		return;		/* BOGUS!  Must specify subsystem. */
391 	if (type == NULL)
392 		return;		/* BOGUS!  Must specify type. */
393 	len += strlen(" system=") + strlen(system);
394 	len += strlen(" subsystem=") + strlen(subsystem);
395 	len += strlen(" type=") + strlen(type);
396 	/* add in the data message plus newline. */
397 	if (data != NULL)
398 		len += strlen(data);
399 	len += 3;	/* '!', '\n', and NUL */
400 	msg = kmalloc(len, M_BUS, M_NOWAIT);
401 	if (msg == NULL)
402 		return;		/* Drop it on the floor */
403 	if (data != NULL)
404 		ksnprintf(msg, len, "!system=%s subsystem=%s type=%s %s\n",
405 		    system, subsystem, type, data);
406 	else
407 		ksnprintf(msg, len, "!system=%s subsystem=%s type=%s\n",
408 		    system, subsystem, type);
409 	devctl_queue_data(msg);
410 }
411 
412 /*
413  * Common routine that tries to make sending messages as easy as possible.
414  * We allocate memory for the data, copy strings into that, but do not
415  * free it unless there's an error.  The dequeue part of the driver should
416  * free the data.  We don't send data when the device is disabled.  We do
417  * send data, even when we have no listeners, because we wish to avoid
418  * races relating to startup and restart of listening applications.
419  *
420  * devaddq is designed to string together the type of event, with the
421  * object of that event, plus the plug and play info and location info
422  * for that event.  This is likely most useful for devices, but less
423  * useful for other consumers of this interface.  Those should use
424  * the devctl_queue_data() interface instead.
425  */
426 static void
427 devaddq(const char *type, const char *what, device_t dev)
428 {
429 	char *data = NULL;
430 	char *loc = NULL;
431 	char *pnp = NULL;
432 	const char *parstr;
433 
434 	if (devctl_disable)
435 		return;
436 	data = kmalloc(1024, M_BUS, M_NOWAIT);
437 	if (data == NULL)
438 		goto bad;
439 
440 	/* get the bus specific location of this device */
441 	loc = kmalloc(1024, M_BUS, M_NOWAIT);
442 	if (loc == NULL)
443 		goto bad;
444 	*loc = '\0';
445 	bus_child_location_str(dev, loc, 1024);
446 
447 	/* Get the bus specific pnp info of this device */
448 	pnp = kmalloc(1024, M_BUS, M_NOWAIT);
449 	if (pnp == NULL)
450 		goto bad;
451 	*pnp = '\0';
452 	bus_child_pnpinfo_str(dev, pnp, 1024);
453 
454 	/* Get the parent of this device, or / if high enough in the tree. */
455 	if (device_get_parent(dev) == NULL)
456 		parstr = ".";	/* Or '/' ? */
457 	else
458 		parstr = device_get_nameunit(device_get_parent(dev));
459 	/* String it all together. */
460 	ksnprintf(data, 1024, "%s%s at %s %s on %s\n", type, what, loc, pnp,
461 	  parstr);
462 	kfree(loc, M_BUS);
463 	kfree(pnp, M_BUS);
464 	devctl_queue_data(data);
465 	return;
466 bad:
467 	kfree(pnp, M_BUS);
468 	kfree(loc, M_BUS);
469 	kfree(data, M_BUS);
470 	return;
471 }
472 
473 /*
474  * A device was added to the tree.  We are called just after it successfully
475  * attaches (that is, probe and attach success for this device).  No call
476  * is made if a device is merely parented into the tree.  See devnomatch
477  * if probe fails.  If attach fails, no notification is sent (but maybe
478  * we should have a different message for this).
479  */
480 static void
481 devadded(device_t dev)
482 {
483 	char *pnp = NULL;
484 	char *tmp = NULL;
485 
486 	pnp = kmalloc(1024, M_BUS, M_NOWAIT);
487 	if (pnp == NULL)
488 		goto fail;
489 	tmp = kmalloc(1024, M_BUS, M_NOWAIT);
490 	if (tmp == NULL)
491 		goto fail;
492 	*pnp = '\0';
493 	bus_child_pnpinfo_str(dev, pnp, 1024);
494 	ksnprintf(tmp, 1024, "%s %s", device_get_nameunit(dev), pnp);
495 	devaddq("+", tmp, dev);
496 fail:
497 	if (pnp != NULL)
498 		kfree(pnp, M_BUS);
499 	if (tmp != NULL)
500 		kfree(tmp, M_BUS);
501 	return;
502 }
503 
504 /*
505  * A device was removed from the tree.  We are called just before this
506  * happens.
507  */
508 static void
509 devremoved(device_t dev)
510 {
511 	char *pnp = NULL;
512 	char *tmp = NULL;
513 
514 	pnp = kmalloc(1024, M_BUS, M_NOWAIT);
515 	if (pnp == NULL)
516 		goto fail;
517 	tmp = kmalloc(1024, M_BUS, M_NOWAIT);
518 	if (tmp == NULL)
519 		goto fail;
520 	*pnp = '\0';
521 	bus_child_pnpinfo_str(dev, pnp, 1024);
522 	ksnprintf(tmp, 1024, "%s %s", device_get_nameunit(dev), pnp);
523 	devaddq("-", tmp, dev);
524 fail:
525 	if (pnp != NULL)
526 		kfree(pnp, M_BUS);
527 	if (tmp != NULL)
528 		kfree(tmp, M_BUS);
529 	return;
530 }
531 
532 /*
533  * Called when there's no match for this device.  This is only called
534  * the first time that no match happens, so we don't keep getitng this
535  * message.  Should that prove to be undesirable, we can change it.
536  * This is called when all drivers that can attach to a given bus
537  * decline to accept this device.  Other errrors may not be detected.
538  */
539 static void
540 devnomatch(device_t dev)
541 {
542 	devaddq("?", "", dev);
543 }
544 
545 static int
546 sysctl_devctl_disable(SYSCTL_HANDLER_ARGS)
547 {
548 	struct dev_event_info *n1;
549 	int dis, error;
550 
551 	dis = devctl_disable;
552 	error = sysctl_handle_int(oidp, &dis, 0, req);
553 	if (error || !req->newptr)
554 		return (error);
555 	lockmgr(&devsoftc.lock, LK_EXCLUSIVE);
556 	devctl_disable = dis;
557 	if (dis) {
558 		while (!TAILQ_EMPTY(&devsoftc.devq)) {
559 			n1 = TAILQ_FIRST(&devsoftc.devq);
560 			TAILQ_REMOVE(&devsoftc.devq, n1, dei_link);
561 			kfree(n1->dei_data, M_BUS);
562 			kfree(n1, M_BUS);
563 		}
564 	}
565 	lockmgr(&devsoftc.lock, LK_RELEASE);
566 	return (0);
567 }
568 
569 /* End of /dev/devctl code */
570 
571 TAILQ_HEAD(,device)	bus_data_devices;
572 static int bus_data_generation = 1;
573 
574 kobj_method_t null_methods[] = {
575 	{ 0, 0 }
576 };
577 
578 DEFINE_CLASS(null, null_methods, 0);
579 
580 /*
581  * Devclass implementation
582  */
583 
584 static devclass_list_t devclasses = TAILQ_HEAD_INITIALIZER(devclasses);
585 
586 static devclass_t
587 devclass_find_internal(const char *classname, const char *parentname,
588 		       int create)
589 {
590 	devclass_t dc;
591 
592 	PDEBUG(("looking for %s", classname));
593 	if (classname == NULL)
594 		return(NULL);
595 
596 	TAILQ_FOREACH(dc, &devclasses, link)
597 		if (!strcmp(dc->name, classname))
598 			break;
599 
600 	if (create && !dc) {
601 		PDEBUG(("creating %s", classname));
602 		dc = kmalloc(sizeof(struct devclass) + strlen(classname) + 1,
603 			    M_BUS, M_INTWAIT | M_ZERO);
604 		if (!dc)
605 			return(NULL);
606 		dc->parent = NULL;
607 		dc->name = (char*) (dc + 1);
608 		strcpy(dc->name, classname);
609 		dc->devices = NULL;
610 		dc->maxunit = 0;
611 		TAILQ_INIT(&dc->drivers);
612 		TAILQ_INSERT_TAIL(&devclasses, dc, link);
613 
614 		bus_data_generation_update();
615 
616 	}
617 	if (parentname && dc && !dc->parent)
618 		dc->parent = devclass_find_internal(parentname, NULL, FALSE);
619 
620 	return(dc);
621 }
622 
623 devclass_t
624 devclass_create(const char *classname)
625 {
626 	return(devclass_find_internal(classname, NULL, TRUE));
627 }
628 
629 devclass_t
630 devclass_find(const char *classname)
631 {
632 	return(devclass_find_internal(classname, NULL, FALSE));
633 }
634 
635 device_t
636 devclass_find_unit(const char *classname, int unit)
637 {
638 	devclass_t dc;
639 
640 	if ((dc = devclass_find(classname)) != NULL)
641 	    return(devclass_get_device(dc, unit));
642 	return (NULL);
643 }
644 
645 int
646 devclass_add_driver(devclass_t dc, driver_t *driver)
647 {
648 	driverlink_t dl;
649 	device_t dev;
650 	int i;
651 
652 	PDEBUG(("%s", DRIVERNAME(driver)));
653 
654 	dl = kmalloc(sizeof *dl, M_BUS, M_INTWAIT | M_ZERO);
655 	if (!dl)
656 		return(ENOMEM);
657 
658 	/*
659 	 * Compile the driver's methods. Also increase the reference count
660 	 * so that the class doesn't get freed when the last instance
661 	 * goes. This means we can safely use static methods and avoids a
662 	 * double-free in devclass_delete_driver.
663 	 */
664 	kobj_class_instantiate(driver);
665 
666 	/*
667 	 * Make sure the devclass which the driver is implementing exists.
668 	 */
669 	devclass_find_internal(driver->name, NULL, TRUE);
670 
671 	dl->driver = driver;
672 	TAILQ_INSERT_TAIL(&dc->drivers, dl, link);
673 
674 	/*
675 	 * Call BUS_DRIVER_ADDED for any existing busses in this class,
676 	 * but only if the bus has already been attached (otherwise we
677 	 * might probe too early).
678 	 *
679 	 * This is what will cause a newly loaded module to be associated
680 	 * with hardware.  bus_generic_driver_added() is typically what ends
681 	 * up being called.
682 	 */
683 	for (i = 0; i < dc->maxunit; i++) {
684 		if ((dev = dc->devices[i]) != NULL) {
685 			if (dev->state >= DS_ATTACHED)
686 				BUS_DRIVER_ADDED(dev, driver);
687 		}
688 	}
689 
690 	bus_data_generation_update();
691 	return(0);
692 }
693 
694 int
695 devclass_delete_driver(devclass_t busclass, driver_t *driver)
696 {
697 	devclass_t dc = devclass_find(driver->name);
698 	driverlink_t dl;
699 	device_t dev;
700 	int i;
701 	int error;
702 
703 	PDEBUG(("%s from devclass %s", driver->name, DEVCLANAME(busclass)));
704 
705 	if (!dc)
706 		return(0);
707 
708 	/*
709 	 * Find the link structure in the bus' list of drivers.
710 	 */
711 	TAILQ_FOREACH(dl, &busclass->drivers, link)
712 		if (dl->driver == driver)
713 			break;
714 
715 	if (!dl) {
716 		PDEBUG(("%s not found in %s list", driver->name, busclass->name));
717 		return(ENOENT);
718 	}
719 
720 	/*
721 	 * Disassociate from any devices.  We iterate through all the
722 	 * devices in the devclass of the driver and detach any which are
723 	 * using the driver and which have a parent in the devclass which
724 	 * we are deleting from.
725 	 *
726 	 * Note that since a driver can be in multiple devclasses, we
727 	 * should not detach devices which are not children of devices in
728 	 * the affected devclass.
729 	 */
730 	for (i = 0; i < dc->maxunit; i++)
731 		if (dc->devices[i]) {
732 			dev = dc->devices[i];
733 			if (dev->driver == driver && dev->parent &&
734 			    dev->parent->devclass == busclass) {
735 				if ((error = device_detach(dev)) != 0)
736 					return(error);
737 				device_set_driver(dev, NULL);
738 		    	}
739 		}
740 
741 	TAILQ_REMOVE(&busclass->drivers, dl, link);
742 	kfree(dl, M_BUS);
743 
744 	kobj_class_uninstantiate(driver);
745 
746 	bus_data_generation_update();
747 	return(0);
748 }
749 
750 static driverlink_t
751 devclass_find_driver_internal(devclass_t dc, const char *classname)
752 {
753 	driverlink_t dl;
754 
755 	PDEBUG(("%s in devclass %s", classname, DEVCLANAME(dc)));
756 
757 	TAILQ_FOREACH(dl, &dc->drivers, link)
758 		if (!strcmp(dl->driver->name, classname))
759 			return(dl);
760 
761 	PDEBUG(("not found"));
762 	return(NULL);
763 }
764 
765 kobj_class_t
766 devclass_find_driver(devclass_t dc, const char *classname)
767 {
768 	driverlink_t dl;
769 
770 	dl = devclass_find_driver_internal(dc, classname);
771 	if (dl)
772 		return(dl->driver);
773 	else
774 		return(NULL);
775 }
776 
777 const char *
778 devclass_get_name(devclass_t dc)
779 {
780 	return(dc->name);
781 }
782 
783 device_t
784 devclass_get_device(devclass_t dc, int unit)
785 {
786 	if (dc == NULL || unit < 0 || unit >= dc->maxunit)
787 		return(NULL);
788 	return(dc->devices[unit]);
789 }
790 
791 void *
792 devclass_get_softc(devclass_t dc, int unit)
793 {
794 	device_t dev;
795 
796 	dev = devclass_get_device(dc, unit);
797 	if (!dev)
798 		return(NULL);
799 
800 	return(device_get_softc(dev));
801 }
802 
803 int
804 devclass_get_devices(devclass_t dc, device_t **devlistp, int *devcountp)
805 {
806 	int i;
807 	int count;
808 	device_t *list;
809 
810 	count = 0;
811 	for (i = 0; i < dc->maxunit; i++)
812 		if (dc->devices[i])
813 			count++;
814 
815 	list = kmalloc(count * sizeof(device_t), M_TEMP, M_INTWAIT | M_ZERO);
816 	if (list == NULL)
817 		return(ENOMEM);
818 
819 	count = 0;
820 	for (i = 0; i < dc->maxunit; i++)
821 		if (dc->devices[i]) {
822 			list[count] = dc->devices[i];
823 			count++;
824 		}
825 
826 	*devlistp = list;
827 	*devcountp = count;
828 
829 	return(0);
830 }
831 
832 /**
833  * @brief Get a list of drivers in the devclass
834  *
835  * An array containing a list of pointers to all the drivers in the
836  * given devclass is allocated and returned in @p *listp.  The number
837  * of drivers in the array is returned in @p *countp. The caller should
838  * free the array using @c free(p, M_TEMP).
839  *
840  * @param dc            the devclass to examine
841  * @param listp         gives location for array pointer return value
842  * @param countp        gives location for number of array elements
843  *                      return value
844  *
845  * @retval 0            success
846  * @retval ENOMEM       the array allocation failed
847  */
848 int
849 devclass_get_drivers(devclass_t dc, driver_t ***listp, int *countp)
850 {
851         driverlink_t dl;
852         driver_t **list;
853         int count;
854 
855         count = 0;
856         TAILQ_FOREACH(dl, &dc->drivers, link)
857                 count++;
858         list = kmalloc(count * sizeof(driver_t *), M_TEMP, M_NOWAIT);
859         if (list == NULL)
860                 return (ENOMEM);
861 
862         count = 0;
863         TAILQ_FOREACH(dl, &dc->drivers, link) {
864                 list[count] = dl->driver;
865                 count++;
866         }
867         *listp = list;
868         *countp = count;
869 
870         return (0);
871 }
872 
873 /**
874  * @brief Get the number of devices in a devclass
875  *
876  * @param dc		the devclass to examine
877  */
878 int
879 devclass_get_count(devclass_t dc)
880 {
881 	int count, i;
882 
883 	count = 0;
884 	for (i = 0; i < dc->maxunit; i++)
885 		if (dc->devices[i])
886 			count++;
887 	return (count);
888 }
889 
890 int
891 devclass_get_maxunit(devclass_t dc)
892 {
893 	return(dc->maxunit);
894 }
895 
896 void
897 devclass_set_parent(devclass_t dc, devclass_t pdc)
898 {
899         dc->parent = pdc;
900 }
901 
902 devclass_t
903 devclass_get_parent(devclass_t dc)
904 {
905 	return(dc->parent);
906 }
907 
908 static int
909 devclass_alloc_unit(devclass_t dc, int *unitp)
910 {
911 	int unit = *unitp;
912 
913 	PDEBUG(("unit %d in devclass %s", unit, DEVCLANAME(dc)));
914 
915 	/* If we have been given a wired unit number, check for existing device */
916 	if (unit != -1) {
917 		if (unit >= 0 && unit < dc->maxunit &&
918 		    dc->devices[unit] != NULL) {
919 			if (bootverbose)
920 				kprintf("%s-: %s%d exists, using next available unit number\n",
921 				       dc->name, dc->name, unit);
922 			/* find the next available slot */
923 			while (++unit < dc->maxunit && dc->devices[unit] != NULL)
924 				;
925 		}
926 	} else {
927 		/* Unwired device, find the next available slot for it */
928 		unit = 0;
929 		while (unit < dc->maxunit && dc->devices[unit] != NULL)
930 			unit++;
931 	}
932 
933 	/*
934 	 * We've selected a unit beyond the length of the table, so let's
935 	 * extend the table to make room for all units up to and including
936 	 * this one.
937 	 */
938 	if (unit >= dc->maxunit) {
939 		device_t *newlist;
940 		int newsize;
941 
942 		newsize = roundup((unit + 1), MINALLOCSIZE / sizeof(device_t));
943 		newlist = kmalloc(sizeof(device_t) * newsize, M_BUS,
944 				 M_INTWAIT | M_ZERO);
945 		if (newlist == NULL)
946 			return(ENOMEM);
947 		bcopy(dc->devices, newlist, sizeof(device_t) * dc->maxunit);
948 		if (dc->devices)
949 			kfree(dc->devices, M_BUS);
950 		dc->devices = newlist;
951 		dc->maxunit = newsize;
952 	}
953 	PDEBUG(("now: unit %d in devclass %s", unit, DEVCLANAME(dc)));
954 
955 	*unitp = unit;
956 	return(0);
957 }
958 
959 static int
960 devclass_add_device(devclass_t dc, device_t dev)
961 {
962 	int buflen, error;
963 
964 	PDEBUG(("%s in devclass %s", DEVICENAME(dev), DEVCLANAME(dc)));
965 
966 	buflen = strlen(dc->name) + 5;
967 	dev->nameunit = kmalloc(buflen, M_BUS, M_INTWAIT | M_ZERO);
968 	if (!dev->nameunit)
969 		return(ENOMEM);
970 
971 	if ((error = devclass_alloc_unit(dc, &dev->unit)) != 0) {
972 		kfree(dev->nameunit, M_BUS);
973 		dev->nameunit = NULL;
974 		return(error);
975 	}
976 	dc->devices[dev->unit] = dev;
977 	dev->devclass = dc;
978 	ksnprintf(dev->nameunit, buflen, "%s%d", dc->name, dev->unit);
979 
980 	return(0);
981 }
982 
983 static int
984 devclass_delete_device(devclass_t dc, device_t dev)
985 {
986 	if (!dc || !dev)
987 		return(0);
988 
989 	PDEBUG(("%s in devclass %s", DEVICENAME(dev), DEVCLANAME(dc)));
990 
991 	if (dev->devclass != dc || dc->devices[dev->unit] != dev)
992 		panic("devclass_delete_device: inconsistent device class");
993 	dc->devices[dev->unit] = NULL;
994 	if (dev->flags & DF_WILDCARD)
995 		dev->unit = -1;
996 	dev->devclass = NULL;
997 	kfree(dev->nameunit, M_BUS);
998 	dev->nameunit = NULL;
999 
1000 	return(0);
1001 }
1002 
1003 static device_t
1004 make_device(device_t parent, const char *name, int unit)
1005 {
1006 	device_t dev;
1007 	devclass_t dc;
1008 
1009 	PDEBUG(("%s at %s as unit %d", name, DEVICENAME(parent), unit));
1010 
1011 	if (name != NULL) {
1012 		dc = devclass_find_internal(name, NULL, TRUE);
1013 		if (!dc) {
1014 			kprintf("make_device: can't find device class %s\n", name);
1015 			return(NULL);
1016 		}
1017 	} else
1018 		dc = NULL;
1019 
1020 	dev = kmalloc(sizeof(struct device), M_BUS, M_INTWAIT | M_ZERO);
1021 	if (!dev)
1022 		return(0);
1023 
1024 	dev->parent = parent;
1025 	TAILQ_INIT(&dev->children);
1026 	kobj_init((kobj_t) dev, &null_class);
1027 	dev->driver = NULL;
1028 	dev->devclass = NULL;
1029 	dev->unit = unit;
1030 	dev->nameunit = NULL;
1031 	dev->desc = NULL;
1032 	dev->busy = 0;
1033 	dev->devflags = 0;
1034 	dev->flags = DF_ENABLED;
1035 	dev->order = 0;
1036 	if (unit == -1)
1037 		dev->flags |= DF_WILDCARD;
1038 	if (name) {
1039 		dev->flags |= DF_FIXEDCLASS;
1040 		if (devclass_add_device(dc, dev) != 0) {
1041 			kobj_delete((kobj_t)dev, M_BUS);
1042 			return(NULL);
1043 		}
1044     	}
1045 	dev->ivars = NULL;
1046 	dev->softc = NULL;
1047 
1048 	dev->state = DS_NOTPRESENT;
1049 
1050 	TAILQ_INSERT_TAIL(&bus_data_devices, dev, devlink);
1051 	bus_data_generation_update();
1052 
1053 	return(dev);
1054 }
1055 
1056 static int
1057 device_print_child(device_t dev, device_t child)
1058 {
1059 	int retval = 0;
1060 
1061 	if (device_is_alive(child))
1062 		retval += BUS_PRINT_CHILD(dev, child);
1063 	else
1064 		retval += device_printf(child, " not found\n");
1065 
1066 	return(retval);
1067 }
1068 
1069 device_t
1070 device_add_child(device_t dev, const char *name, int unit)
1071 {
1072 	return device_add_child_ordered(dev, 0, name, unit);
1073 }
1074 
1075 device_t
1076 device_add_child_ordered(device_t dev, int order, const char *name, int unit)
1077 {
1078 	device_t child;
1079 	device_t place;
1080 
1081 	PDEBUG(("%s at %s with order %d as unit %d", name, DEVICENAME(dev),
1082 		order, unit));
1083 
1084 	child = make_device(dev, name, unit);
1085 	if (child == NULL)
1086 		return child;
1087 	child->order = order;
1088 
1089 	TAILQ_FOREACH(place, &dev->children, link)
1090 		if (place->order > order)
1091 			break;
1092 
1093 	if (place) {
1094 		/*
1095 		 * The device 'place' is the first device whose order is
1096 		 * greater than the new child.
1097 		 */
1098 		TAILQ_INSERT_BEFORE(place, child, link);
1099 	} else {
1100 		/*
1101 		 * The new child's order is greater or equal to the order of
1102 		 * any existing device. Add the child to the tail of the list.
1103 		 */
1104 		TAILQ_INSERT_TAIL(&dev->children, child, link);
1105     	}
1106 
1107 	bus_data_generation_update();
1108 	return(child);
1109 }
1110 
1111 int
1112 device_delete_child(device_t dev, device_t child)
1113 {
1114 	int error;
1115 	device_t grandchild;
1116 
1117 	PDEBUG(("%s from %s", DEVICENAME(child), DEVICENAME(dev)));
1118 
1119 	/* remove children first */
1120 	while ( (grandchild = TAILQ_FIRST(&child->children)) ) {
1121         	error = device_delete_child(child, grandchild);
1122 		if (error)
1123 			return(error);
1124 	}
1125 
1126 	if ((error = device_detach(child)) != 0)
1127 		return(error);
1128 	if (child->devclass)
1129 		devclass_delete_device(child->devclass, child);
1130 	TAILQ_REMOVE(&dev->children, child, link);
1131 	TAILQ_REMOVE(&bus_data_devices, child, devlink);
1132 	device_set_desc(child, NULL);
1133 	kobj_delete((kobj_t)child, M_BUS);
1134 
1135 	bus_data_generation_update();
1136 	return(0);
1137 }
1138 
1139 /**
1140  * @brief Find a device given a unit number
1141  *
1142  * This is similar to devclass_get_devices() but only searches for
1143  * devices which have @p dev as a parent.
1144  *
1145  * @param dev		the parent device to search
1146  * @param unit		the unit number to search for.  If the unit is -1,
1147  *			return the first child of @p dev which has name
1148  *			@p classname (that is, the one with the lowest unit.)
1149  *
1150  * @returns		the device with the given unit number or @c
1151  *			NULL if there is no such device
1152  */
1153 device_t
1154 device_find_child(device_t dev, const char *classname, int unit)
1155 {
1156 	devclass_t dc;
1157 	device_t child;
1158 
1159 	dc = devclass_find(classname);
1160 	if (!dc)
1161 		return(NULL);
1162 
1163 	if (unit != -1) {
1164 		child = devclass_get_device(dc, unit);
1165 		if (child && child->parent == dev)
1166 			return (child);
1167 	} else {
1168 		for (unit = 0; unit < devclass_get_maxunit(dc); unit++) {
1169 			child = devclass_get_device(dc, unit);
1170 			if (child && child->parent == dev)
1171 				return (child);
1172 		}
1173 	}
1174 	return(NULL);
1175 }
1176 
1177 static driverlink_t
1178 first_matching_driver(devclass_t dc, device_t dev)
1179 {
1180 	if (dev->devclass)
1181 		return(devclass_find_driver_internal(dc, dev->devclass->name));
1182 	else
1183 		return(TAILQ_FIRST(&dc->drivers));
1184 }
1185 
1186 static driverlink_t
1187 next_matching_driver(devclass_t dc, device_t dev, driverlink_t last)
1188 {
1189 	if (dev->devclass) {
1190 		driverlink_t dl;
1191 		for (dl = TAILQ_NEXT(last, link); dl; dl = TAILQ_NEXT(dl, link))
1192 			if (!strcmp(dev->devclass->name, dl->driver->name))
1193 				return(dl);
1194 		return(NULL);
1195 	} else
1196 		return(TAILQ_NEXT(last, link));
1197 }
1198 
1199 static int
1200 device_probe_child(device_t dev, device_t child)
1201 {
1202 	devclass_t dc;
1203 	driverlink_t best = 0;
1204 	driverlink_t dl;
1205 	int result, pri = 0;
1206 	int hasclass = (child->devclass != 0);
1207 
1208 	dc = dev->devclass;
1209 	if (!dc)
1210 		panic("device_probe_child: parent device has no devclass");
1211 
1212 	if (child->state == DS_ALIVE)
1213 		return(0);
1214 
1215 	for (; dc; dc = dc->parent) {
1216     		for (dl = first_matching_driver(dc, child); dl;
1217 		     dl = next_matching_driver(dc, child, dl)) {
1218 			PDEBUG(("Trying %s", DRIVERNAME(dl->driver)));
1219 			device_set_driver(child, dl->driver);
1220 			if (!hasclass)
1221 				device_set_devclass(child, dl->driver->name);
1222 			result = DEVICE_PROBE(child);
1223 			if (!hasclass)
1224 				device_set_devclass(child, 0);
1225 
1226 			/*
1227 			 * If the driver returns SUCCESS, there can be
1228 			 * no higher match for this device.
1229 			 */
1230 			if (result == 0) {
1231 				best = dl;
1232 				pri = 0;
1233 				break;
1234 			}
1235 
1236 			/*
1237 			 * The driver returned an error so it
1238 			 * certainly doesn't match.
1239 			 */
1240 			if (result > 0) {
1241 				device_set_driver(child, 0);
1242 				continue;
1243 			}
1244 
1245 			/*
1246 			 * A priority lower than SUCCESS, remember the
1247 			 * best matching driver. Initialise the value
1248 			 * of pri for the first match.
1249 			 */
1250 			if (best == 0 || result > pri) {
1251 				best = dl;
1252 				pri = result;
1253 				continue;
1254 			}
1255 	        }
1256 		/*
1257 	         * If we have unambiguous match in this devclass,
1258 	         * don't look in the parent.
1259 	         */
1260 	        if (best && pri == 0)
1261 	    	        break;
1262 	}
1263 
1264 	/*
1265 	 * If we found a driver, change state and initialise the devclass.
1266 	 */
1267 	if (best) {
1268 		if (!child->devclass)
1269 			device_set_devclass(child, best->driver->name);
1270 		device_set_driver(child, best->driver);
1271 		if (pri < 0) {
1272 			/*
1273 			 * A bit bogus. Call the probe method again to make
1274 			 * sure that we have the right description.
1275 			 */
1276 			DEVICE_PROBE(child);
1277 		}
1278 
1279 		bus_data_generation_update();
1280 		child->state = DS_ALIVE;
1281 		return(0);
1282 	}
1283 
1284 	return(ENXIO);
1285 }
1286 
1287 device_t
1288 device_get_parent(device_t dev)
1289 {
1290 	return dev->parent;
1291 }
1292 
1293 int
1294 device_get_children(device_t dev, device_t **devlistp, int *devcountp)
1295 {
1296 	int count;
1297 	device_t child;
1298 	device_t *list;
1299 
1300 	count = 0;
1301 	TAILQ_FOREACH(child, &dev->children, link)
1302 		count++;
1303 
1304 	list = kmalloc(count * sizeof(device_t), M_TEMP, M_INTWAIT | M_ZERO);
1305 	if (!list)
1306 		return(ENOMEM);
1307 
1308 	count = 0;
1309 	TAILQ_FOREACH(child, &dev->children, link) {
1310 		list[count] = child;
1311 		count++;
1312 	}
1313 
1314 	*devlistp = list;
1315 	*devcountp = count;
1316 
1317 	return(0);
1318 }
1319 
1320 driver_t *
1321 device_get_driver(device_t dev)
1322 {
1323 	return(dev->driver);
1324 }
1325 
1326 devclass_t
1327 device_get_devclass(device_t dev)
1328 {
1329 	return(dev->devclass);
1330 }
1331 
1332 const char *
1333 device_get_name(device_t dev)
1334 {
1335 	if (dev->devclass)
1336 		return devclass_get_name(dev->devclass);
1337 	return(NULL);
1338 }
1339 
1340 const char *
1341 device_get_nameunit(device_t dev)
1342 {
1343 	return(dev->nameunit);
1344 }
1345 
1346 int
1347 device_get_unit(device_t dev)
1348 {
1349 	return(dev->unit);
1350 }
1351 
1352 const char *
1353 device_get_desc(device_t dev)
1354 {
1355 	return(dev->desc);
1356 }
1357 
1358 uint32_t
1359 device_get_flags(device_t dev)
1360 {
1361 	return(dev->devflags);
1362 }
1363 
1364 int
1365 device_print_prettyname(device_t dev)
1366 {
1367 	const char *name = device_get_name(dev);
1368 
1369 	if (name == 0)
1370 		return kprintf("unknown: ");
1371 	else
1372 		return kprintf("%s%d: ", name, device_get_unit(dev));
1373 }
1374 
1375 int
1376 device_printf(device_t dev, const char * fmt, ...)
1377 {
1378 	__va_list ap;
1379 	int retval;
1380 
1381 	retval = device_print_prettyname(dev);
1382 	__va_start(ap, fmt);
1383 	retval += kvprintf(fmt, ap);
1384 	__va_end(ap);
1385 	return retval;
1386 }
1387 
1388 static void
1389 device_set_desc_internal(device_t dev, const char* desc, int copy)
1390 {
1391 	if (dev->desc && (dev->flags & DF_DESCMALLOCED)) {
1392 		kfree(dev->desc, M_BUS);
1393 		dev->flags &= ~DF_DESCMALLOCED;
1394 		dev->desc = NULL;
1395 	}
1396 
1397 	if (copy && desc) {
1398 		dev->desc = kmalloc(strlen(desc) + 1, M_BUS, M_INTWAIT);
1399 		if (dev->desc) {
1400 			strcpy(dev->desc, desc);
1401 			dev->flags |= DF_DESCMALLOCED;
1402 		}
1403 	} else {
1404 		/* Avoid a -Wcast-qual warning */
1405 		dev->desc = (char *)(uintptr_t) desc;
1406 	}
1407 
1408 	bus_data_generation_update();
1409 }
1410 
1411 void
1412 device_set_desc(device_t dev, const char* desc)
1413 {
1414 	device_set_desc_internal(dev, desc, FALSE);
1415 }
1416 
1417 void
1418 device_set_desc_copy(device_t dev, const char* desc)
1419 {
1420 	device_set_desc_internal(dev, desc, TRUE);
1421 }
1422 
1423 void
1424 device_set_flags(device_t dev, uint32_t flags)
1425 {
1426 	dev->devflags = flags;
1427 }
1428 
1429 void *
1430 device_get_softc(device_t dev)
1431 {
1432 	return dev->softc;
1433 }
1434 
1435 void
1436 device_set_softc(device_t dev, void *softc)
1437 {
1438 	if (dev->softc && !(dev->flags & DF_EXTERNALSOFTC))
1439 		kfree(dev->softc, M_BUS);
1440 	dev->softc = softc;
1441 	if (dev->softc)
1442 		dev->flags |= DF_EXTERNALSOFTC;
1443 	else
1444 		dev->flags &= ~DF_EXTERNALSOFTC;
1445 }
1446 
1447 void
1448 device_set_async_attach(device_t dev, int enable)
1449 {
1450 	if (enable)
1451 		dev->flags |= DF_ASYNCPROBE;
1452 	else
1453 		dev->flags &= ~DF_ASYNCPROBE;
1454 }
1455 
1456 void *
1457 device_get_ivars(device_t dev)
1458 {
1459 	return dev->ivars;
1460 }
1461 
1462 void
1463 device_set_ivars(device_t dev, void * ivars)
1464 {
1465 	if (!dev)
1466 		return;
1467 
1468 	dev->ivars = ivars;
1469 }
1470 
1471 device_state_t
1472 device_get_state(device_t dev)
1473 {
1474 	return(dev->state);
1475 }
1476 
1477 void
1478 device_enable(device_t dev)
1479 {
1480 	dev->flags |= DF_ENABLED;
1481 }
1482 
1483 void
1484 device_disable(device_t dev)
1485 {
1486 	dev->flags &= ~DF_ENABLED;
1487 }
1488 
1489 /*
1490  * YYY cannot block
1491  */
1492 void
1493 device_busy(device_t dev)
1494 {
1495 	if (dev->state < DS_ATTACHED)
1496 		panic("device_busy: called for unattached device");
1497 	if (dev->busy == 0 && dev->parent)
1498 		device_busy(dev->parent);
1499 	dev->busy++;
1500 	dev->state = DS_BUSY;
1501 }
1502 
1503 /*
1504  * YYY cannot block
1505  */
1506 void
1507 device_unbusy(device_t dev)
1508 {
1509 	if (dev->state != DS_BUSY)
1510 		panic("device_unbusy: called for non-busy device");
1511 	dev->busy--;
1512 	if (dev->busy == 0) {
1513 		if (dev->parent)
1514 			device_unbusy(dev->parent);
1515 		dev->state = DS_ATTACHED;
1516 	}
1517 }
1518 
1519 void
1520 device_quiet(device_t dev)
1521 {
1522 	dev->flags |= DF_QUIET;
1523 }
1524 
1525 void
1526 device_verbose(device_t dev)
1527 {
1528 	dev->flags &= ~DF_QUIET;
1529 }
1530 
1531 int
1532 device_is_quiet(device_t dev)
1533 {
1534 	return((dev->flags & DF_QUIET) != 0);
1535 }
1536 
1537 int
1538 device_is_enabled(device_t dev)
1539 {
1540 	return((dev->flags & DF_ENABLED) != 0);
1541 }
1542 
1543 int
1544 device_is_alive(device_t dev)
1545 {
1546 	return(dev->state >= DS_ALIVE);
1547 }
1548 
1549 int
1550 device_is_attached(device_t dev)
1551 {
1552 	return(dev->state >= DS_ATTACHED);
1553 }
1554 
1555 int
1556 device_set_devclass(device_t dev, const char *classname)
1557 {
1558 	devclass_t dc;
1559 	int error;
1560 
1561 	if (!classname) {
1562 		if (dev->devclass)
1563 			devclass_delete_device(dev->devclass, dev);
1564 		return(0);
1565 	}
1566 
1567 	if (dev->devclass) {
1568 		kprintf("device_set_devclass: device class already set\n");
1569 		return(EINVAL);
1570 	}
1571 
1572 	dc = devclass_find_internal(classname, NULL, TRUE);
1573 	if (!dc)
1574 		return(ENOMEM);
1575 
1576 	error = devclass_add_device(dc, dev);
1577 
1578 	bus_data_generation_update();
1579 	return(error);
1580 }
1581 
1582 int
1583 device_set_driver(device_t dev, driver_t *driver)
1584 {
1585 	if (dev->state >= DS_ATTACHED)
1586 		return(EBUSY);
1587 
1588 	if (dev->driver == driver)
1589 		return(0);
1590 
1591 	if (dev->softc && !(dev->flags & DF_EXTERNALSOFTC)) {
1592 		kfree(dev->softc, M_BUS);
1593 		dev->softc = NULL;
1594 	}
1595 	kobj_delete((kobj_t) dev, 0);
1596 	dev->driver = driver;
1597 	if (driver) {
1598 		kobj_init((kobj_t) dev, (kobj_class_t) driver);
1599 		if (!(dev->flags & DF_EXTERNALSOFTC)) {
1600 			dev->softc = kmalloc(driver->size, M_BUS,
1601 					    M_INTWAIT | M_ZERO);
1602 			if (!dev->softc) {
1603 				kobj_delete((kobj_t)dev, 0);
1604 				kobj_init((kobj_t) dev, &null_class);
1605 				dev->driver = NULL;
1606 				return(ENOMEM);
1607 	    		}
1608 		}
1609 	} else {
1610 		kobj_init((kobj_t) dev, &null_class);
1611 	}
1612 
1613 	bus_data_generation_update();
1614 	return(0);
1615 }
1616 
1617 int
1618 device_probe_and_attach(device_t dev)
1619 {
1620 	device_t bus = dev->parent;
1621 	int error = 0;
1622 
1623 	if (dev->state >= DS_ALIVE)
1624 		return(0);
1625 
1626 	if ((dev->flags & DF_ENABLED) == 0) {
1627 		if (bootverbose) {
1628 			device_print_prettyname(dev);
1629 			kprintf("not probed (disabled)\n");
1630 		}
1631 		return(0);
1632 	}
1633 
1634 	error = device_probe_child(bus, dev);
1635 	if (error) {
1636 		if (!(dev->flags & DF_DONENOMATCH)) {
1637 			BUS_PROBE_NOMATCH(bus, dev);
1638 			devnomatch(dev);
1639 			dev->flags |= DF_DONENOMATCH;
1640 		}
1641 		return(error);
1642 	}
1643 
1644 	/*
1645 	 * Output the exact device chain prior to the attach in case the
1646 	 * system locks up during attach, and generate the full info after
1647 	 * the attach so correct irq and other information is displayed.
1648 	 */
1649 	if (bootverbose && !device_is_quiet(dev)) {
1650 		device_t tmp;
1651 
1652 		kprintf("%s", device_get_nameunit(dev));
1653 		for (tmp = dev->parent; tmp; tmp = tmp->parent)
1654 			kprintf(".%s", device_get_nameunit(tmp));
1655 		kprintf("\n");
1656 	}
1657 	if (!device_is_quiet(dev))
1658 		device_print_child(bus, dev);
1659 	if ((dev->flags & DF_ASYNCPROBE) && do_async_attach) {
1660 		kprintf("%s: probing asynchronously\n",
1661 			device_get_nameunit(dev));
1662 		dev->state = DS_INPROGRESS;
1663 		device_attach_async(dev);
1664 		error = 0;
1665 	} else {
1666 		error = device_doattach(dev);
1667 	}
1668 	return(error);
1669 }
1670 
1671 /*
1672  * Device is known to be alive, do the attach asynchronously.
1673  *
1674  * The MP lock is held by all threads.
1675  */
1676 static void
1677 device_attach_async(device_t dev)
1678 {
1679 	thread_t td;
1680 
1681 	atomic_add_int(&numasyncthreads, 1);
1682 	lwkt_create(device_attach_thread, dev, &td, NULL,
1683 		    0, 0, (dev->desc ? dev->desc : "devattach"));
1684 }
1685 
1686 static void
1687 device_attach_thread(void *arg)
1688 {
1689 	device_t dev = arg;
1690 
1691 	(void)device_doattach(dev);
1692 	atomic_subtract_int(&numasyncthreads, 1);
1693 	wakeup(&numasyncthreads);
1694 }
1695 
1696 /*
1697  * Device is known to be alive, do the attach (synchronous or asynchronous)
1698  */
1699 static int
1700 device_doattach(device_t dev)
1701 {
1702 	device_t bus = dev->parent;
1703 	int hasclass = (dev->devclass != 0);
1704 	int error;
1705 
1706 	error = DEVICE_ATTACH(dev);
1707 	if (error == 0) {
1708 		dev->state = DS_ATTACHED;
1709 		if (bootverbose && !device_is_quiet(dev))
1710 			device_print_child(bus, dev);
1711 		devadded(dev);
1712 	} else {
1713 		kprintf("device_probe_and_attach: %s%d attach returned %d\n",
1714 		       dev->driver->name, dev->unit, error);
1715 		/* Unset the class that was set in device_probe_child */
1716 		if (!hasclass)
1717 			device_set_devclass(dev, 0);
1718 		device_set_driver(dev, NULL);
1719 		dev->state = DS_NOTPRESENT;
1720 	}
1721 	return(error);
1722 }
1723 
1724 int
1725 device_detach(device_t dev)
1726 {
1727 	int error;
1728 
1729 	PDEBUG(("%s", DEVICENAME(dev)));
1730 	if (dev->state == DS_BUSY)
1731 		return(EBUSY);
1732 	if (dev->state != DS_ATTACHED)
1733 		return(0);
1734 
1735 	if ((error = DEVICE_DETACH(dev)) != 0)
1736 		return(error);
1737 	devremoved(dev);
1738 	device_printf(dev, "detached\n");
1739 	if (dev->parent)
1740 		BUS_CHILD_DETACHED(dev->parent, dev);
1741 
1742 	if (!(dev->flags & DF_FIXEDCLASS))
1743 		devclass_delete_device(dev->devclass, dev);
1744 
1745 	dev->state = DS_NOTPRESENT;
1746 	device_set_driver(dev, NULL);
1747 
1748 	return(0);
1749 }
1750 
1751 int
1752 device_shutdown(device_t dev)
1753 {
1754 	if (dev->state < DS_ATTACHED)
1755 		return 0;
1756 	PDEBUG(("%s", DEVICENAME(dev)));
1757 	return DEVICE_SHUTDOWN(dev);
1758 }
1759 
1760 int
1761 device_set_unit(device_t dev, int unit)
1762 {
1763 	devclass_t dc;
1764 	int err;
1765 
1766 	dc = device_get_devclass(dev);
1767 	if (unit < dc->maxunit && dc->devices[unit])
1768 		return(EBUSY);
1769 	err = devclass_delete_device(dc, dev);
1770 	if (err)
1771 		return(err);
1772 	dev->unit = unit;
1773 	err = devclass_add_device(dc, dev);
1774 	if (err)
1775 		return(err);
1776 
1777 	bus_data_generation_update();
1778 	return(0);
1779 }
1780 
1781 /*======================================*/
1782 /*
1783  * Access functions for device resources.
1784  */
1785 
1786 /* Supplied by config(8) in ioconf.c */
1787 extern struct config_device config_devtab[];
1788 extern int devtab_count;
1789 
1790 /* Runtime version */
1791 struct config_device *devtab = config_devtab;
1792 
1793 static int
1794 resource_new_name(const char *name, int unit)
1795 {
1796 	struct config_device *new;
1797 
1798 	new = kmalloc((devtab_count + 1) * sizeof(*new), M_TEMP,
1799 		     M_INTWAIT | M_ZERO);
1800 	if (new == NULL)
1801 		return(-1);
1802 	if (devtab && devtab_count > 0)
1803 		bcopy(devtab, new, devtab_count * sizeof(*new));
1804 	new[devtab_count].name = kmalloc(strlen(name) + 1, M_TEMP, M_INTWAIT);
1805 	if (new[devtab_count].name == NULL) {
1806 		kfree(new, M_TEMP);
1807 		return(-1);
1808 	}
1809 	strcpy(new[devtab_count].name, name);
1810 	new[devtab_count].unit = unit;
1811 	new[devtab_count].resource_count = 0;
1812 	new[devtab_count].resources = NULL;
1813 	if (devtab && devtab != config_devtab)
1814 		kfree(devtab, M_TEMP);
1815 	devtab = new;
1816 	return devtab_count++;
1817 }
1818 
1819 static int
1820 resource_new_resname(int j, const char *resname, resource_type type)
1821 {
1822 	struct config_resource *new;
1823 	int i;
1824 
1825 	i = devtab[j].resource_count;
1826 	new = kmalloc((i + 1) * sizeof(*new), M_TEMP, M_INTWAIT | M_ZERO);
1827 	if (new == NULL)
1828 		return(-1);
1829 	if (devtab[j].resources && i > 0)
1830 		bcopy(devtab[j].resources, new, i * sizeof(*new));
1831 	new[i].name = kmalloc(strlen(resname) + 1, M_TEMP, M_INTWAIT);
1832 	if (new[i].name == NULL) {
1833 		kfree(new, M_TEMP);
1834 		return(-1);
1835 	}
1836 	strcpy(new[i].name, resname);
1837 	new[i].type = type;
1838 	if (devtab[j].resources)
1839 		kfree(devtab[j].resources, M_TEMP);
1840 	devtab[j].resources = new;
1841 	devtab[j].resource_count = i + 1;
1842 	return(i);
1843 }
1844 
1845 static int
1846 resource_match_string(int i, const char *resname, const char *value)
1847 {
1848 	int j;
1849 	struct config_resource *res;
1850 
1851 	for (j = 0, res = devtab[i].resources;
1852 	     j < devtab[i].resource_count; j++, res++)
1853 		if (!strcmp(res->name, resname)
1854 		    && res->type == RES_STRING
1855 		    && !strcmp(res->u.stringval, value))
1856 			return(j);
1857 	return(-1);
1858 }
1859 
1860 static int
1861 resource_find(const char *name, int unit, const char *resname,
1862 	      struct config_resource **result)
1863 {
1864 	int i, j;
1865 	struct config_resource *res;
1866 
1867 	/*
1868 	 * First check specific instances, then generic.
1869 	 */
1870 	for (i = 0; i < devtab_count; i++) {
1871 		if (devtab[i].unit < 0)
1872 			continue;
1873 		if (!strcmp(devtab[i].name, name) && devtab[i].unit == unit) {
1874 			res = devtab[i].resources;
1875 			for (j = 0; j < devtab[i].resource_count; j++, res++)
1876 				if (!strcmp(res->name, resname)) {
1877 					*result = res;
1878 					return(0);
1879 				}
1880 		}
1881 	}
1882 	for (i = 0; i < devtab_count; i++) {
1883 		if (devtab[i].unit >= 0)
1884 			continue;
1885 		/* XXX should this `&& devtab[i].unit == unit' be here? */
1886 		/* XXX if so, then the generic match does nothing */
1887 		if (!strcmp(devtab[i].name, name) && devtab[i].unit == unit) {
1888 			res = devtab[i].resources;
1889 			for (j = 0; j < devtab[i].resource_count; j++, res++)
1890 				if (!strcmp(res->name, resname)) {
1891 					*result = res;
1892 					return(0);
1893 				}
1894 		}
1895 	}
1896 	return(ENOENT);
1897 }
1898 
1899 int
1900 resource_int_value(const char *name, int unit, const char *resname, int *result)
1901 {
1902 	int error;
1903 	struct config_resource *res;
1904 
1905 	if ((error = resource_find(name, unit, resname, &res)) != 0)
1906 		return(error);
1907 	if (res->type != RES_INT)
1908 		return(EFTYPE);
1909 	*result = res->u.intval;
1910 	return(0);
1911 }
1912 
1913 int
1914 resource_long_value(const char *name, int unit, const char *resname,
1915 		    long *result)
1916 {
1917 	int error;
1918 	struct config_resource *res;
1919 
1920 	if ((error = resource_find(name, unit, resname, &res)) != 0)
1921 		return(error);
1922 	if (res->type != RES_LONG)
1923 		return(EFTYPE);
1924 	*result = res->u.longval;
1925 	return(0);
1926 }
1927 
1928 int
1929 resource_string_value(const char *name, int unit, const char *resname,
1930 		      char **result)
1931 {
1932 	int error;
1933 	struct config_resource *res;
1934 
1935 	if ((error = resource_find(name, unit, resname, &res)) != 0)
1936 		return(error);
1937 	if (res->type != RES_STRING)
1938 		return(EFTYPE);
1939 	*result = res->u.stringval;
1940 	return(0);
1941 }
1942 
1943 int
1944 resource_query_string(int i, const char *resname, const char *value)
1945 {
1946 	if (i < 0)
1947 		i = 0;
1948 	else
1949 		i = i + 1;
1950 	for (; i < devtab_count; i++)
1951 		if (resource_match_string(i, resname, value) >= 0)
1952 			return(i);
1953 	return(-1);
1954 }
1955 
1956 int
1957 resource_locate(int i, const char *resname)
1958 {
1959 	if (i < 0)
1960 		i = 0;
1961 	else
1962 		i = i + 1;
1963 	for (; i < devtab_count; i++)
1964 		if (!strcmp(devtab[i].name, resname))
1965 			return(i);
1966 	return(-1);
1967 }
1968 
1969 int
1970 resource_count(void)
1971 {
1972 	return(devtab_count);
1973 }
1974 
1975 char *
1976 resource_query_name(int i)
1977 {
1978 	return(devtab[i].name);
1979 }
1980 
1981 int
1982 resource_query_unit(int i)
1983 {
1984 	return(devtab[i].unit);
1985 }
1986 
1987 static int
1988 resource_create(const char *name, int unit, const char *resname,
1989 		resource_type type, struct config_resource **result)
1990 {
1991 	int i, j;
1992 	struct config_resource *res = NULL;
1993 
1994 	for (i = 0; i < devtab_count; i++)
1995 		if (!strcmp(devtab[i].name, name) && devtab[i].unit == unit) {
1996 			res = devtab[i].resources;
1997 			break;
1998 		}
1999 	if (res == NULL) {
2000 		i = resource_new_name(name, unit);
2001 		if (i < 0)
2002 			return(ENOMEM);
2003 		res = devtab[i].resources;
2004 	}
2005 	for (j = 0; j < devtab[i].resource_count; j++, res++)
2006 		if (!strcmp(res->name, resname)) {
2007 			*result = res;
2008 			return(0);
2009 		}
2010 	j = resource_new_resname(i, resname, type);
2011 	if (j < 0)
2012 		return(ENOMEM);
2013 	res = &devtab[i].resources[j];
2014 	*result = res;
2015 	return(0);
2016 }
2017 
2018 int
2019 resource_set_int(const char *name, int unit, const char *resname, int value)
2020 {
2021 	int error;
2022 	struct config_resource *res;
2023 
2024 	error = resource_create(name, unit, resname, RES_INT, &res);
2025 	if (error)
2026 		return(error);
2027 	if (res->type != RES_INT)
2028 		return(EFTYPE);
2029 	res->u.intval = value;
2030 	return(0);
2031 }
2032 
2033 int
2034 resource_set_long(const char *name, int unit, const char *resname, long value)
2035 {
2036 	int error;
2037 	struct config_resource *res;
2038 
2039 	error = resource_create(name, unit, resname, RES_LONG, &res);
2040 	if (error)
2041 		return(error);
2042 	if (res->type != RES_LONG)
2043 		return(EFTYPE);
2044 	res->u.longval = value;
2045 	return(0);
2046 }
2047 
2048 int
2049 resource_set_string(const char *name, int unit, const char *resname,
2050 		    const char *value)
2051 {
2052 	int error;
2053 	struct config_resource *res;
2054 
2055 	error = resource_create(name, unit, resname, RES_STRING, &res);
2056 	if (error)
2057 		return(error);
2058 	if (res->type != RES_STRING)
2059 		return(EFTYPE);
2060 	if (res->u.stringval)
2061 		kfree(res->u.stringval, M_TEMP);
2062 	res->u.stringval = kmalloc(strlen(value) + 1, M_TEMP, M_INTWAIT);
2063 	if (res->u.stringval == NULL)
2064 		return(ENOMEM);
2065 	strcpy(res->u.stringval, value);
2066 	return(0);
2067 }
2068 
2069 static void
2070 resource_cfgload(void *dummy __unused)
2071 {
2072 	struct config_resource *res, *cfgres;
2073 	int i, j;
2074 	int error;
2075 	char *name, *resname;
2076 	int unit;
2077 	resource_type type;
2078 	char *stringval;
2079 	int config_devtab_count;
2080 
2081 	config_devtab_count = devtab_count;
2082 	devtab = NULL;
2083 	devtab_count = 0;
2084 
2085 	for (i = 0; i < config_devtab_count; i++) {
2086 		name = config_devtab[i].name;
2087 		unit = config_devtab[i].unit;
2088 
2089 		for (j = 0; j < config_devtab[i].resource_count; j++) {
2090 			cfgres = config_devtab[i].resources;
2091 			resname = cfgres[j].name;
2092 			type = cfgres[j].type;
2093 			error = resource_create(name, unit, resname, type,
2094 						&res);
2095 			if (error) {
2096 				kprintf("create resource %s%d: error %d\n",
2097 					name, unit, error);
2098 				continue;
2099 			}
2100 			if (res->type != type) {
2101 				kprintf("type mismatch %s%d: %d != %d\n",
2102 					name, unit, res->type, type);
2103 				continue;
2104 			}
2105 			switch (type) {
2106 			case RES_INT:
2107 				res->u.intval = cfgres[j].u.intval;
2108 				break;
2109 			case RES_LONG:
2110 				res->u.longval = cfgres[j].u.longval;
2111 				break;
2112 			case RES_STRING:
2113 				if (res->u.stringval)
2114 					kfree(res->u.stringval, M_TEMP);
2115 				stringval = cfgres[j].u.stringval;
2116 				res->u.stringval = kmalloc(strlen(stringval) + 1,
2117 							  M_TEMP, M_INTWAIT);
2118 				if (res->u.stringval == NULL)
2119 					break;
2120 				strcpy(res->u.stringval, stringval);
2121 				break;
2122 			default:
2123 				panic("unknown resource type %d", type);
2124 			}
2125 		}
2126 	}
2127 }
2128 SYSINIT(cfgload, SI_BOOT1_POST, SI_ORDER_ANY + 50, resource_cfgload, 0)
2129 
2130 
2131 /*======================================*/
2132 /*
2133  * Some useful method implementations to make life easier for bus drivers.
2134  */
2135 
2136 void
2137 resource_list_init(struct resource_list *rl)
2138 {
2139 	SLIST_INIT(rl);
2140 }
2141 
2142 void
2143 resource_list_free(struct resource_list *rl)
2144 {
2145 	struct resource_list_entry *rle;
2146 
2147 	while ((rle = SLIST_FIRST(rl)) != NULL) {
2148 		if (rle->res)
2149 			panic("resource_list_free: resource entry is busy");
2150 		SLIST_REMOVE_HEAD(rl, link);
2151 		kfree(rle, M_BUS);
2152 	}
2153 }
2154 
2155 void
2156 resource_list_add(struct resource_list *rl,
2157 		  int type, int rid,
2158 		  u_long start, u_long end, u_long count)
2159 {
2160 	struct resource_list_entry *rle;
2161 
2162 	rle = resource_list_find(rl, type, rid);
2163 	if (rle == NULL) {
2164 		rle = kmalloc(sizeof(struct resource_list_entry), M_BUS,
2165 			     M_INTWAIT);
2166 		if (!rle)
2167 			panic("resource_list_add: can't record entry");
2168 		SLIST_INSERT_HEAD(rl, rle, link);
2169 		rle->type = type;
2170 		rle->rid = rid;
2171 		rle->res = NULL;
2172 	}
2173 
2174 	if (rle->res)
2175 		panic("resource_list_add: resource entry is busy");
2176 
2177 	rle->start = start;
2178 	rle->end = end;
2179 	rle->count = count;
2180 }
2181 
2182 struct resource_list_entry*
2183 resource_list_find(struct resource_list *rl,
2184 		   int type, int rid)
2185 {
2186 	struct resource_list_entry *rle;
2187 
2188 	SLIST_FOREACH(rle, rl, link)
2189 		if (rle->type == type && rle->rid == rid)
2190 			return(rle);
2191 	return(NULL);
2192 }
2193 
2194 void
2195 resource_list_delete(struct resource_list *rl,
2196 		     int type, int rid)
2197 {
2198 	struct resource_list_entry *rle = resource_list_find(rl, type, rid);
2199 
2200 	if (rle) {
2201 		if (rle->res != NULL)
2202 			panic("resource_list_delete: resource has not been released");
2203 		SLIST_REMOVE(rl, rle, resource_list_entry, link);
2204 		kfree(rle, M_BUS);
2205 	}
2206 }
2207 
2208 struct resource *
2209 resource_list_alloc(struct resource_list *rl,
2210 		    device_t bus, device_t child,
2211 		    int type, int *rid,
2212 		    u_long start, u_long end,
2213 		    u_long count, u_int flags)
2214 {
2215 	struct resource_list_entry *rle = 0;
2216 	int passthrough = (device_get_parent(child) != bus);
2217 	int isdefault = (start == 0UL && end == ~0UL);
2218 
2219 	if (passthrough) {
2220 		return(BUS_ALLOC_RESOURCE(device_get_parent(bus), child,
2221 					  type, rid,
2222 					  start, end, count, flags));
2223 	}
2224 
2225 	rle = resource_list_find(rl, type, *rid);
2226 
2227 	if (!rle)
2228 		return(0);		/* no resource of that type/rid */
2229 
2230 	if (rle->res)
2231 		panic("resource_list_alloc: resource entry is busy");
2232 
2233 	if (isdefault) {
2234 		start = rle->start;
2235 		count = max(count, rle->count);
2236 		end = max(rle->end, start + count - 1);
2237 	}
2238 
2239 	rle->res = BUS_ALLOC_RESOURCE(device_get_parent(bus), child,
2240 				      type, rid, start, end, count, flags);
2241 
2242 	/*
2243 	 * Record the new range.
2244 	 */
2245 	if (rle->res) {
2246 		rle->start = rman_get_start(rle->res);
2247 		rle->end = rman_get_end(rle->res);
2248 		rle->count = count;
2249 	}
2250 
2251 	return(rle->res);
2252 }
2253 
2254 int
2255 resource_list_release(struct resource_list *rl,
2256 		      device_t bus, device_t child,
2257 		      int type, int rid, struct resource *res)
2258 {
2259 	struct resource_list_entry *rle = 0;
2260 	int passthrough = (device_get_parent(child) != bus);
2261 	int error;
2262 
2263 	if (passthrough) {
2264 		return(BUS_RELEASE_RESOURCE(device_get_parent(bus), child,
2265 					    type, rid, res));
2266 	}
2267 
2268 	rle = resource_list_find(rl, type, rid);
2269 
2270 	if (!rle)
2271 		panic("resource_list_release: can't find resource");
2272 	if (!rle->res)
2273 		panic("resource_list_release: resource entry is not busy");
2274 
2275 	error = BUS_RELEASE_RESOURCE(device_get_parent(bus), child,
2276 				     type, rid, res);
2277 	if (error)
2278 		return(error);
2279 
2280 	rle->res = NULL;
2281 	return(0);
2282 }
2283 
2284 int
2285 resource_list_print_type(struct resource_list *rl, const char *name, int type,
2286 			 const char *format)
2287 {
2288 	struct resource_list_entry *rle;
2289 	int printed, retval;
2290 
2291 	printed = 0;
2292 	retval = 0;
2293 	/* Yes, this is kinda cheating */
2294 	SLIST_FOREACH(rle, rl, link) {
2295 		if (rle->type == type) {
2296 			if (printed == 0)
2297 				retval += kprintf(" %s ", name);
2298 			else
2299 				retval += kprintf(",");
2300 			printed++;
2301 			retval += kprintf(format, rle->start);
2302 			if (rle->count > 1) {
2303 				retval += kprintf("-");
2304 				retval += kprintf(format, rle->start +
2305 						 rle->count - 1);
2306 			}
2307 		}
2308 	}
2309 	return(retval);
2310 }
2311 
2312 /*
2313  * Generic driver/device identify functions.  These will install a device
2314  * rendezvous point under the parent using the same name as the driver
2315  * name, which will at a later time be probed and attached.
2316  *
2317  * These functions are used when the parent does not 'scan' its bus for
2318  * matching devices, or for the particular devices using these functions,
2319  * or when the device is a pseudo or synthesized device (such as can be
2320  * found under firewire and ppbus).
2321  */
2322 int
2323 bus_generic_identify(driver_t *driver, device_t parent)
2324 {
2325 	if (parent->state == DS_ATTACHED)
2326 		return (0);
2327 	BUS_ADD_CHILD(parent, parent, 0, driver->name, -1);
2328 	return (0);
2329 }
2330 
2331 int
2332 bus_generic_identify_sameunit(driver_t *driver, device_t parent)
2333 {
2334 	if (parent->state == DS_ATTACHED)
2335 		return (0);
2336 	BUS_ADD_CHILD(parent, parent, 0, driver->name, device_get_unit(parent));
2337 	return (0);
2338 }
2339 
2340 /*
2341  * Call DEVICE_IDENTIFY for each driver.
2342  */
2343 int
2344 bus_generic_probe(device_t dev)
2345 {
2346 	devclass_t dc = dev->devclass;
2347 	driverlink_t dl;
2348 
2349 	TAILQ_FOREACH(dl, &dc->drivers, link) {
2350 		DEVICE_IDENTIFY(dl->driver, dev);
2351 	}
2352 
2353 	return(0);
2354 }
2355 
2356 /*
2357  * This is an aweful hack due to the isa bus and autoconf code not
2358  * probing the ISA devices until after everything else has configured.
2359  * The ISA bus did a dummy attach long ago so we have to set it back
2360  * to an earlier state so the probe thinks its the initial probe and
2361  * not a bus rescan.
2362  *
2363  * XXX remove by properly defering the ISA bus scan.
2364  */
2365 int
2366 bus_generic_probe_hack(device_t dev)
2367 {
2368 	if (dev->state == DS_ATTACHED) {
2369 		dev->state = DS_ALIVE;
2370 		bus_generic_probe(dev);
2371 		dev->state = DS_ATTACHED;
2372 	}
2373 	return (0);
2374 }
2375 
2376 int
2377 bus_generic_attach(device_t dev)
2378 {
2379 	device_t child;
2380 
2381 	TAILQ_FOREACH(child, &dev->children, link) {
2382 		device_probe_and_attach(child);
2383 	}
2384 
2385 	return(0);
2386 }
2387 
2388 int
2389 bus_generic_detach(device_t dev)
2390 {
2391 	device_t child;
2392 	int error;
2393 
2394 	if (dev->state != DS_ATTACHED)
2395 		return(EBUSY);
2396 
2397 	TAILQ_FOREACH(child, &dev->children, link)
2398 		if ((error = device_detach(child)) != 0)
2399 			return(error);
2400 
2401 	return 0;
2402 }
2403 
2404 int
2405 bus_generic_shutdown(device_t dev)
2406 {
2407 	device_t child;
2408 
2409 	TAILQ_FOREACH(child, &dev->children, link)
2410 		device_shutdown(child);
2411 
2412 	return(0);
2413 }
2414 
2415 int
2416 bus_generic_suspend(device_t dev)
2417 {
2418 	int error;
2419 	device_t child, child2;
2420 
2421 	TAILQ_FOREACH(child, &dev->children, link) {
2422 		error = DEVICE_SUSPEND(child);
2423 		if (error) {
2424 			for (child2 = TAILQ_FIRST(&dev->children);
2425 			     child2 && child2 != child;
2426 			     child2 = TAILQ_NEXT(child2, link))
2427 				DEVICE_RESUME(child2);
2428 			return(error);
2429 		}
2430 	}
2431 	return(0);
2432 }
2433 
2434 int
2435 bus_generic_resume(device_t dev)
2436 {
2437 	device_t child;
2438 
2439 	TAILQ_FOREACH(child, &dev->children, link)
2440 		DEVICE_RESUME(child);
2441 		/* if resume fails, there's nothing we can usefully do... */
2442 
2443 	return(0);
2444 }
2445 
2446 int
2447 bus_print_child_header(device_t dev, device_t child)
2448 {
2449 	int retval = 0;
2450 
2451 	if (device_get_desc(child))
2452 		retval += device_printf(child, "<%s>", device_get_desc(child));
2453 	else
2454 		retval += kprintf("%s", device_get_nameunit(child));
2455 	if (bootverbose) {
2456 		if (child->state != DS_ATTACHED)
2457 			kprintf(" [tentative]");
2458 		else
2459 			kprintf(" [attached!]");
2460 	}
2461 	return(retval);
2462 }
2463 
2464 int
2465 bus_print_child_footer(device_t dev, device_t child)
2466 {
2467 	return(kprintf(" on %s\n", device_get_nameunit(dev)));
2468 }
2469 
2470 device_t
2471 bus_generic_add_child(device_t dev, device_t child, int order,
2472 		      const char *name, int unit)
2473 {
2474 	if (dev->parent)
2475 		dev = BUS_ADD_CHILD(dev->parent, child, order, name, unit);
2476 	else
2477 		dev = device_add_child_ordered(child, order, name, unit);
2478 	return(dev);
2479 
2480 }
2481 
2482 int
2483 bus_generic_print_child(device_t dev, device_t child)
2484 {
2485 	int retval = 0;
2486 
2487 	retval += bus_print_child_header(dev, child);
2488 	retval += bus_print_child_footer(dev, child);
2489 
2490 	return(retval);
2491 }
2492 
2493 int
2494 bus_generic_read_ivar(device_t dev, device_t child, int index,
2495 		      uintptr_t * result)
2496 {
2497 	int error;
2498 
2499 	if (dev->parent)
2500 		error = BUS_READ_IVAR(dev->parent, child, index, result);
2501 	else
2502 		error = ENOENT;
2503 	return (error);
2504 }
2505 
2506 int
2507 bus_generic_write_ivar(device_t dev, device_t child, int index,
2508 		       uintptr_t value)
2509 {
2510 	int error;
2511 
2512 	if (dev->parent)
2513 		error = BUS_WRITE_IVAR(dev->parent, child, index, value);
2514 	else
2515 		error = ENOENT;
2516 	return (error);
2517 }
2518 
2519 /*
2520  * Resource list are used for iterations, do not recurse.
2521  */
2522 struct resource_list *
2523 bus_generic_get_resource_list(device_t dev, device_t child)
2524 {
2525 	return (NULL);
2526 }
2527 
2528 void
2529 bus_generic_driver_added(device_t dev, driver_t *driver)
2530 {
2531 	device_t child;
2532 
2533 	DEVICE_IDENTIFY(driver, dev);
2534 	TAILQ_FOREACH(child, &dev->children, link) {
2535 		if (child->state == DS_NOTPRESENT)
2536 			device_probe_and_attach(child);
2537 	}
2538 }
2539 
2540 int
2541 bus_generic_setup_intr(device_t dev, device_t child, struct resource *irq,
2542 		       int flags, driver_intr_t *intr, void *arg,
2543 		       void **cookiep, lwkt_serialize_t serializer)
2544 {
2545 	/* Propagate up the bus hierarchy until someone handles it. */
2546 	if (dev->parent)
2547 		return(BUS_SETUP_INTR(dev->parent, child, irq, flags,
2548 				      intr, arg, cookiep, serializer));
2549 	else
2550 		return(EINVAL);
2551 }
2552 
2553 int
2554 bus_generic_teardown_intr(device_t dev, device_t child, struct resource *irq,
2555 			  void *cookie)
2556 {
2557 	/* Propagate up the bus hierarchy until someone handles it. */
2558 	if (dev->parent)
2559 		return(BUS_TEARDOWN_INTR(dev->parent, child, irq, cookie));
2560 	else
2561 		return(EINVAL);
2562 }
2563 
2564 int
2565 bus_generic_disable_intr(device_t dev, device_t child, void *cookie)
2566 {
2567 	if (dev->parent)
2568 		return(BUS_DISABLE_INTR(dev->parent, child, cookie));
2569 	else
2570 		return(0);
2571 }
2572 
2573 void
2574 bus_generic_enable_intr(device_t dev, device_t child, void *cookie)
2575 {
2576 	if (dev->parent)
2577 		BUS_ENABLE_INTR(dev->parent, child, cookie);
2578 }
2579 
2580 int
2581 bus_generic_config_intr(device_t dev, device_t child, int irq, enum intr_trigger trig,
2582     enum intr_polarity pol)
2583 {
2584 	/* Propagate up the bus hierarchy until someone handles it. */
2585 	if (dev->parent)
2586 		return(BUS_CONFIG_INTR(dev->parent, child, irq, trig, pol));
2587 	else
2588 		return(EINVAL);
2589 }
2590 
2591 struct resource *
2592 bus_generic_alloc_resource(device_t dev, device_t child, int type, int *rid,
2593 			   u_long start, u_long end, u_long count, u_int flags)
2594 {
2595 	/* Propagate up the bus hierarchy until someone handles it. */
2596 	if (dev->parent)
2597 		return(BUS_ALLOC_RESOURCE(dev->parent, child, type, rid,
2598 					   start, end, count, flags));
2599 	else
2600 		return(NULL);
2601 }
2602 
2603 int
2604 bus_generic_release_resource(device_t dev, device_t child, int type, int rid,
2605 			     struct resource *r)
2606 {
2607 	/* Propagate up the bus hierarchy until someone handles it. */
2608 	if (dev->parent)
2609 		return(BUS_RELEASE_RESOURCE(dev->parent, child, type, rid, r));
2610 	else
2611 		return(EINVAL);
2612 }
2613 
2614 int
2615 bus_generic_activate_resource(device_t dev, device_t child, int type, int rid,
2616 			      struct resource *r)
2617 {
2618 	/* Propagate up the bus hierarchy until someone handles it. */
2619 	if (dev->parent)
2620 		return(BUS_ACTIVATE_RESOURCE(dev->parent, child, type, rid, r));
2621 	else
2622 		return(EINVAL);
2623 }
2624 
2625 int
2626 bus_generic_deactivate_resource(device_t dev, device_t child, int type,
2627 				int rid, struct resource *r)
2628 {
2629 	/* Propagate up the bus hierarchy until someone handles it. */
2630 	if (dev->parent)
2631 		return(BUS_DEACTIVATE_RESOURCE(dev->parent, child, type, rid,
2632 					       r));
2633 	else
2634 		return(EINVAL);
2635 }
2636 
2637 int
2638 bus_generic_get_resource(device_t dev, device_t child, int type, int rid,
2639 			 u_long *startp, u_long *countp)
2640 {
2641 	int error;
2642 
2643 	error = ENOENT;
2644 	if (dev->parent) {
2645 		error = BUS_GET_RESOURCE(dev->parent, child, type, rid,
2646 					 startp, countp);
2647 	}
2648 	return (error);
2649 }
2650 
2651 int
2652 bus_generic_set_resource(device_t dev, device_t child, int type, int rid,
2653 			u_long start, u_long count)
2654 {
2655 	int error;
2656 
2657 	error = EINVAL;
2658 	if (dev->parent) {
2659 		error = BUS_SET_RESOURCE(dev->parent, child, type, rid,
2660 					 start, count);
2661 	}
2662 	return (error);
2663 }
2664 
2665 void
2666 bus_generic_delete_resource(device_t dev, device_t child, int type, int rid)
2667 {
2668 	if (dev->parent)
2669 		BUS_DELETE_RESOURCE(dev, child, type, rid);
2670 }
2671 
2672 int
2673 bus_generic_rl_get_resource(device_t dev, device_t child, int type, int rid,
2674     u_long *startp, u_long *countp)
2675 {
2676 	struct resource_list *rl = NULL;
2677 	struct resource_list_entry *rle = NULL;
2678 
2679 	rl = BUS_GET_RESOURCE_LIST(dev, child);
2680 	if (!rl)
2681 		return(EINVAL);
2682 
2683 	rle = resource_list_find(rl, type, rid);
2684 	if (!rle)
2685 		return(ENOENT);
2686 
2687 	if (startp)
2688 		*startp = rle->start;
2689 	if (countp)
2690 		*countp = rle->count;
2691 
2692 	return(0);
2693 }
2694 
2695 int
2696 bus_generic_rl_set_resource(device_t dev, device_t child, int type, int rid,
2697     u_long start, u_long count)
2698 {
2699 	struct resource_list *rl = NULL;
2700 
2701 	rl = BUS_GET_RESOURCE_LIST(dev, child);
2702 	if (!rl)
2703 		return(EINVAL);
2704 
2705 	resource_list_add(rl, type, rid, start, (start + count - 1), count);
2706 
2707 	return(0);
2708 }
2709 
2710 void
2711 bus_generic_rl_delete_resource(device_t dev, device_t child, int type, int rid)
2712 {
2713 	struct resource_list *rl = NULL;
2714 
2715 	rl = BUS_GET_RESOURCE_LIST(dev, child);
2716 	if (!rl)
2717 		return;
2718 
2719 	resource_list_delete(rl, type, rid);
2720 }
2721 
2722 int
2723 bus_generic_rl_release_resource(device_t dev, device_t child, int type,
2724     int rid, struct resource *r)
2725 {
2726 	struct resource_list *rl = NULL;
2727 
2728 	rl = BUS_GET_RESOURCE_LIST(dev, child);
2729 	if (!rl)
2730 		return(EINVAL);
2731 
2732 	return(resource_list_release(rl, dev, child, type, rid, r));
2733 }
2734 
2735 struct resource *
2736 bus_generic_rl_alloc_resource(device_t dev, device_t child, int type,
2737     int *rid, u_long start, u_long end, u_long count, u_int flags)
2738 {
2739 	struct resource_list *rl = NULL;
2740 
2741 	rl = BUS_GET_RESOURCE_LIST(dev, child);
2742 	if (!rl)
2743 		return(NULL);
2744 
2745 	return(resource_list_alloc(rl, dev, child, type, rid,
2746 	    start, end, count, flags));
2747 }
2748 
2749 int
2750 bus_generic_child_present(device_t bus, device_t child)
2751 {
2752 	return(BUS_CHILD_PRESENT(device_get_parent(bus), bus));
2753 }
2754 
2755 
2756 /*
2757  * Some convenience functions to make it easier for drivers to use the
2758  * resource-management functions.  All these really do is hide the
2759  * indirection through the parent's method table, making for slightly
2760  * less-wordy code.  In the future, it might make sense for this code
2761  * to maintain some sort of a list of resources allocated by each device.
2762  */
2763 int
2764 bus_alloc_resources(device_t dev, struct resource_spec *rs,
2765     struct resource **res)
2766 {
2767 	int i;
2768 
2769 	for (i = 0; rs[i].type != -1; i++)
2770 	        res[i] = NULL;
2771 	for (i = 0; rs[i].type != -1; i++) {
2772 		res[i] = bus_alloc_resource_any(dev,
2773 		    rs[i].type, &rs[i].rid, rs[i].flags);
2774 		if (res[i] == NULL) {
2775 			bus_release_resources(dev, rs, res);
2776 			return (ENXIO);
2777 		}
2778 	}
2779 	return (0);
2780 }
2781 
2782 void
2783 bus_release_resources(device_t dev, const struct resource_spec *rs,
2784     struct resource **res)
2785 {
2786 	int i;
2787 
2788 	for (i = 0; rs[i].type != -1; i++)
2789 		if (res[i] != NULL) {
2790 			bus_release_resource(
2791 			    dev, rs[i].type, rs[i].rid, res[i]);
2792 			res[i] = NULL;
2793 		}
2794 }
2795 
2796 struct resource *
2797 bus_alloc_resource(device_t dev, int type, int *rid, u_long start, u_long end,
2798 		   u_long count, u_int flags)
2799 {
2800 	if (dev->parent == 0)
2801 		return(0);
2802 	return(BUS_ALLOC_RESOURCE(dev->parent, dev, type, rid, start, end,
2803 				  count, flags));
2804 }
2805 
2806 int
2807 bus_activate_resource(device_t dev, int type, int rid, struct resource *r)
2808 {
2809 	if (dev->parent == 0)
2810 		return(EINVAL);
2811 	return(BUS_ACTIVATE_RESOURCE(dev->parent, dev, type, rid, r));
2812 }
2813 
2814 int
2815 bus_deactivate_resource(device_t dev, int type, int rid, struct resource *r)
2816 {
2817 	if (dev->parent == 0)
2818 		return(EINVAL);
2819 	return(BUS_DEACTIVATE_RESOURCE(dev->parent, dev, type, rid, r));
2820 }
2821 
2822 int
2823 bus_release_resource(device_t dev, int type, int rid, struct resource *r)
2824 {
2825 	if (dev->parent == 0)
2826 		return(EINVAL);
2827 	return(BUS_RELEASE_RESOURCE(dev->parent, dev, type, rid, r));
2828 }
2829 
2830 int
2831 bus_setup_intr(device_t dev, struct resource *r, int flags,
2832 	       driver_intr_t handler, void *arg,
2833 	       void **cookiep, lwkt_serialize_t serializer)
2834 {
2835 	if (dev->parent == 0)
2836 		return(EINVAL);
2837 	return(BUS_SETUP_INTR(dev->parent, dev, r, flags, handler, arg,
2838 			      cookiep, serializer));
2839 }
2840 
2841 int
2842 bus_teardown_intr(device_t dev, struct resource *r, void *cookie)
2843 {
2844 	if (dev->parent == 0)
2845 		return(EINVAL);
2846 	return(BUS_TEARDOWN_INTR(dev->parent, dev, r, cookie));
2847 }
2848 
2849 void
2850 bus_enable_intr(device_t dev, void *cookie)
2851 {
2852 	if (dev->parent)
2853 		BUS_ENABLE_INTR(dev->parent, dev, cookie);
2854 }
2855 
2856 int
2857 bus_disable_intr(device_t dev, void *cookie)
2858 {
2859 	if (dev->parent)
2860 		return(BUS_DISABLE_INTR(dev->parent, dev, cookie));
2861 	else
2862 		return(0);
2863 }
2864 
2865 int
2866 bus_set_resource(device_t dev, int type, int rid,
2867 		 u_long start, u_long count)
2868 {
2869 	return(BUS_SET_RESOURCE(device_get_parent(dev), dev, type, rid,
2870 				start, count));
2871 }
2872 
2873 int
2874 bus_get_resource(device_t dev, int type, int rid,
2875 		 u_long *startp, u_long *countp)
2876 {
2877 	return(BUS_GET_RESOURCE(device_get_parent(dev), dev, type, rid,
2878 				startp, countp));
2879 }
2880 
2881 u_long
2882 bus_get_resource_start(device_t dev, int type, int rid)
2883 {
2884 	u_long start, count;
2885 	int error;
2886 
2887 	error = BUS_GET_RESOURCE(device_get_parent(dev), dev, type, rid,
2888 				 &start, &count);
2889 	if (error)
2890 		return(0);
2891 	return(start);
2892 }
2893 
2894 u_long
2895 bus_get_resource_count(device_t dev, int type, int rid)
2896 {
2897 	u_long start, count;
2898 	int error;
2899 
2900 	error = BUS_GET_RESOURCE(device_get_parent(dev), dev, type, rid,
2901 				 &start, &count);
2902 	if (error)
2903 		return(0);
2904 	return(count);
2905 }
2906 
2907 void
2908 bus_delete_resource(device_t dev, int type, int rid)
2909 {
2910 	BUS_DELETE_RESOURCE(device_get_parent(dev), dev, type, rid);
2911 }
2912 
2913 int
2914 bus_child_present(device_t child)
2915 {
2916 	return (BUS_CHILD_PRESENT(device_get_parent(child), child));
2917 }
2918 
2919 int
2920 bus_child_pnpinfo_str(device_t child, char *buf, size_t buflen)
2921 {
2922 	device_t parent;
2923 
2924 	parent = device_get_parent(child);
2925 	if (parent == NULL) {
2926 		*buf = '\0';
2927 		return (0);
2928 	}
2929 	return (BUS_CHILD_PNPINFO_STR(parent, child, buf, buflen));
2930 }
2931 
2932 int
2933 bus_child_location_str(device_t child, char *buf, size_t buflen)
2934 {
2935 	device_t parent;
2936 
2937 	parent = device_get_parent(child);
2938 	if (parent == NULL) {
2939 		*buf = '\0';
2940 		return (0);
2941 	}
2942 	return (BUS_CHILD_LOCATION_STR(parent, child, buf, buflen));
2943 }
2944 
2945 static int
2946 root_print_child(device_t dev, device_t child)
2947 {
2948 	return(0);
2949 }
2950 
2951 static int
2952 root_setup_intr(device_t dev, device_t child, driver_intr_t *intr, void *arg,
2953 		void **cookiep, lwkt_serialize_t serializer)
2954 {
2955 	/*
2956 	 * If an interrupt mapping gets to here something bad has happened.
2957 	 */
2958 	panic("root_setup_intr");
2959 }
2960 
2961 /*
2962  * If we get here, assume that the device is permanant and really is
2963  * present in the system.  Removable bus drivers are expected to intercept
2964  * this call long before it gets here.  We return -1 so that drivers that
2965  * really care can check vs -1 or some ERRNO returned higher in the food
2966  * chain.
2967  */
2968 static int
2969 root_child_present(device_t dev, device_t child)
2970 {
2971 	return(-1);
2972 }
2973 
2974 /*
2975  * XXX NOTE! other defaults may be set in bus_if.m
2976  */
2977 static kobj_method_t root_methods[] = {
2978 	/* Device interface */
2979 	KOBJMETHOD(device_shutdown,	bus_generic_shutdown),
2980 	KOBJMETHOD(device_suspend,	bus_generic_suspend),
2981 	KOBJMETHOD(device_resume,	bus_generic_resume),
2982 
2983 	/* Bus interface */
2984 	KOBJMETHOD(bus_add_child,	bus_generic_add_child),
2985 	KOBJMETHOD(bus_print_child,	root_print_child),
2986 	KOBJMETHOD(bus_read_ivar,	bus_generic_read_ivar),
2987 	KOBJMETHOD(bus_write_ivar,	bus_generic_write_ivar),
2988 	KOBJMETHOD(bus_setup_intr,	root_setup_intr),
2989 	KOBJMETHOD(bus_child_present,   root_child_present),
2990 
2991 	{ 0, 0 }
2992 };
2993 
2994 static driver_t root_driver = {
2995 	"root",
2996 	root_methods,
2997 	1,			/* no softc */
2998 };
2999 
3000 device_t	root_bus;
3001 devclass_t	root_devclass;
3002 
3003 static int
3004 root_bus_module_handler(module_t mod, int what, void* arg)
3005 {
3006 	switch (what) {
3007 	case MOD_LOAD:
3008 		TAILQ_INIT(&bus_data_devices);
3009 		root_bus = make_device(NULL, "root", 0);
3010 		root_bus->desc = "System root bus";
3011 		kobj_init((kobj_t) root_bus, (kobj_class_t) &root_driver);
3012 		root_bus->driver = &root_driver;
3013 		root_bus->state = DS_ALIVE;
3014 		root_devclass = devclass_find_internal("root", NULL, FALSE);
3015 		devinit();
3016 		return(0);
3017 
3018 	case MOD_SHUTDOWN:
3019 		device_shutdown(root_bus);
3020 		return(0);
3021 	default:
3022 		return(0);
3023 	}
3024 }
3025 
3026 static moduledata_t root_bus_mod = {
3027 	"rootbus",
3028 	root_bus_module_handler,
3029 	0
3030 };
3031 DECLARE_MODULE(rootbus, root_bus_mod, SI_SUB_DRIVERS, SI_ORDER_FIRST);
3032 
3033 void
3034 root_bus_configure(void)
3035 {
3036 	int warncount;
3037 	device_t dev;
3038 
3039 	PDEBUG(("."));
3040 
3041 	/*
3042 	 * handle device_identify based device attachments to the root_bus
3043 	 * (typically nexus).
3044 	 */
3045 	bus_generic_probe(root_bus);
3046 
3047 	/*
3048 	 * Probe and attach the devices under root_bus.
3049 	 */
3050 	TAILQ_FOREACH(dev, &root_bus->children, link) {
3051 		device_probe_and_attach(dev);
3052 	}
3053 
3054 	/*
3055 	 * Wait for all asynchronous attaches to complete.  If we don't
3056 	 * our legacy ISA bus scan could steal device unit numbers or
3057 	 * even I/O ports.
3058 	 */
3059 	warncount = 10;
3060 	if (numasyncthreads)
3061 		kprintf("Waiting for async drivers to attach\n");
3062 	while (numasyncthreads > 0) {
3063 		if (tsleep(&numasyncthreads, 0, "rootbus", hz) == EWOULDBLOCK)
3064 			--warncount;
3065 		if (warncount == 0) {
3066 			kprintf("Warning: Still waiting for %d "
3067 				"drivers to attach\n", numasyncthreads);
3068 		} else if (warncount == -30) {
3069 			kprintf("Giving up on %d drivers\n", numasyncthreads);
3070 			break;
3071 		}
3072 	}
3073 	root_bus->state = DS_ATTACHED;
3074 }
3075 
3076 int
3077 driver_module_handler(module_t mod, int what, void *arg)
3078 {
3079 	int error;
3080 	struct driver_module_data *dmd;
3081 	devclass_t bus_devclass;
3082 	kobj_class_t driver;
3083         const char *parentname;
3084 
3085 	dmd = (struct driver_module_data *)arg;
3086 	bus_devclass = devclass_find_internal(dmd->dmd_busname, NULL, TRUE);
3087 	error = 0;
3088 
3089 	switch (what) {
3090 	case MOD_LOAD:
3091 		if (dmd->dmd_chainevh)
3092 			error = dmd->dmd_chainevh(mod,what,dmd->dmd_chainarg);
3093 
3094 		driver = dmd->dmd_driver;
3095 		PDEBUG(("Loading module: driver %s on bus %s",
3096 		        DRIVERNAME(driver), dmd->dmd_busname));
3097 
3098 		/*
3099 		 * If the driver has any base classes, make the
3100 		 * devclass inherit from the devclass of the driver's
3101 		 * first base class. This will allow the system to
3102 		 * search for drivers in both devclasses for children
3103 		 * of a device using this driver.
3104 		 */
3105 		if (driver->baseclasses)
3106 			parentname = driver->baseclasses[0]->name;
3107 		else
3108 			parentname = NULL;
3109 		*dmd->dmd_devclass = devclass_find_internal(driver->name,
3110 							    parentname, TRUE);
3111 
3112 		error = devclass_add_driver(bus_devclass, driver);
3113 		if (error)
3114 			break;
3115 		break;
3116 
3117 	case MOD_UNLOAD:
3118 		PDEBUG(("Unloading module: driver %s from bus %s",
3119 			DRIVERNAME(dmd->dmd_driver), dmd->dmd_busname));
3120 		error = devclass_delete_driver(bus_devclass, dmd->dmd_driver);
3121 
3122 		if (!error && dmd->dmd_chainevh)
3123 			error = dmd->dmd_chainevh(mod,what,dmd->dmd_chainarg);
3124 		break;
3125 	}
3126 
3127 	return (error);
3128 }
3129 
3130 #ifdef BUS_DEBUG
3131 
3132 /*
3133  * The _short versions avoid iteration by not calling anything that prints
3134  * more than oneliners. I love oneliners.
3135  */
3136 
3137 static void
3138 print_device_short(device_t dev, int indent)
3139 {
3140 	if (!dev)
3141 		return;
3142 
3143 	indentprintf(("device %d: <%s> %sparent,%schildren,%s%s%s%s,%sivars,%ssoftc,busy=%d\n",
3144 		      dev->unit, dev->desc,
3145 		      (dev->parent? "":"no "),
3146 		      (TAILQ_EMPTY(&dev->children)? "no ":""),
3147 		      (dev->flags&DF_ENABLED? "enabled,":"disabled,"),
3148 		      (dev->flags&DF_FIXEDCLASS? "fixed,":""),
3149 		      (dev->flags&DF_WILDCARD? "wildcard,":""),
3150 		      (dev->flags&DF_DESCMALLOCED? "descmalloced,":""),
3151 		      (dev->ivars? "":"no "),
3152 		      (dev->softc? "":"no "),
3153 		      dev->busy));
3154 }
3155 
3156 static void
3157 print_device(device_t dev, int indent)
3158 {
3159 	if (!dev)
3160 		return;
3161 
3162 	print_device_short(dev, indent);
3163 
3164 	indentprintf(("Parent:\n"));
3165 	print_device_short(dev->parent, indent+1);
3166 	indentprintf(("Driver:\n"));
3167 	print_driver_short(dev->driver, indent+1);
3168 	indentprintf(("Devclass:\n"));
3169 	print_devclass_short(dev->devclass, indent+1);
3170 }
3171 
3172 /*
3173  * Print the device and all its children (indented).
3174  */
3175 void
3176 print_device_tree_short(device_t dev, int indent)
3177 {
3178 	device_t child;
3179 
3180 	if (!dev)
3181 		return;
3182 
3183 	print_device_short(dev, indent);
3184 
3185 	TAILQ_FOREACH(child, &dev->children, link)
3186 		print_device_tree_short(child, indent+1);
3187 }
3188 
3189 /*
3190  * Print the device and all its children (indented).
3191  */
3192 void
3193 print_device_tree(device_t dev, int indent)
3194 {
3195 	device_t child;
3196 
3197 	if (!dev)
3198 		return;
3199 
3200 	print_device(dev, indent);
3201 
3202 	TAILQ_FOREACH(child, &dev->children, link)
3203 		print_device_tree(child, indent+1);
3204 }
3205 
3206 static void
3207 print_driver_short(driver_t *driver, int indent)
3208 {
3209 	if (!driver)
3210 		return;
3211 
3212 	indentprintf(("driver %s: softc size = %zu\n",
3213 		      driver->name, driver->size));
3214 }
3215 
3216 static void
3217 print_driver(driver_t *driver, int indent)
3218 {
3219 	if (!driver)
3220 		return;
3221 
3222 	print_driver_short(driver, indent);
3223 }
3224 
3225 
3226 static void
3227 print_driver_list(driver_list_t drivers, int indent)
3228 {
3229 	driverlink_t driver;
3230 
3231 	TAILQ_FOREACH(driver, &drivers, link)
3232 		print_driver(driver->driver, indent);
3233 }
3234 
3235 static void
3236 print_devclass_short(devclass_t dc, int indent)
3237 {
3238 	if (!dc)
3239 		return;
3240 
3241 	indentprintf(("devclass %s: max units = %d\n", dc->name, dc->maxunit));
3242 }
3243 
3244 static void
3245 print_devclass(devclass_t dc, int indent)
3246 {
3247 	int i;
3248 
3249 	if (!dc)
3250 		return;
3251 
3252 	print_devclass_short(dc, indent);
3253 	indentprintf(("Drivers:\n"));
3254 	print_driver_list(dc->drivers, indent+1);
3255 
3256 	indentprintf(("Devices:\n"));
3257 	for (i = 0; i < dc->maxunit; i++)
3258 		if (dc->devices[i])
3259 			print_device(dc->devices[i], indent+1);
3260 }
3261 
3262 void
3263 print_devclass_list_short(void)
3264 {
3265 	devclass_t dc;
3266 
3267 	kprintf("Short listing of devclasses, drivers & devices:\n");
3268 	TAILQ_FOREACH(dc, &devclasses, link) {
3269 		print_devclass_short(dc, 0);
3270 	}
3271 }
3272 
3273 void
3274 print_devclass_list(void)
3275 {
3276 	devclass_t dc;
3277 
3278 	kprintf("Full listing of devclasses, drivers & devices:\n");
3279 	TAILQ_FOREACH(dc, &devclasses, link) {
3280 		print_devclass(dc, 0);
3281 	}
3282 }
3283 
3284 #endif
3285 
3286 /*
3287  * Check to see if a device is disabled via a disabled hint.
3288  */
3289 int
3290 resource_disabled(const char *name, int unit)
3291 {
3292 	int error, value;
3293 
3294 	error = resource_int_value(name, unit, "disabled", &value);
3295 	if (error)
3296 	       return(0);
3297 	return(value);
3298 }
3299 
3300 /*
3301  * User-space access to the device tree.
3302  *
3303  * We implement a small set of nodes:
3304  *
3305  * hw.bus			Single integer read method to obtain the
3306  *				current generation count.
3307  * hw.bus.devices		Reads the entire device tree in flat space.
3308  * hw.bus.rman			Resource manager interface
3309  *
3310  * We might like to add the ability to scan devclasses and/or drivers to
3311  * determine what else is currently loaded/available.
3312  */
3313 
3314 static int
3315 sysctl_bus(SYSCTL_HANDLER_ARGS)
3316 {
3317 	struct u_businfo	ubus;
3318 
3319 	ubus.ub_version = BUS_USER_VERSION;
3320 	ubus.ub_generation = bus_data_generation;
3321 
3322 	return (SYSCTL_OUT(req, &ubus, sizeof(ubus)));
3323 }
3324 SYSCTL_NODE(_hw_bus, OID_AUTO, info, CTLFLAG_RW, sysctl_bus,
3325     "bus-related data");
3326 
3327 static int
3328 sysctl_devices(SYSCTL_HANDLER_ARGS)
3329 {
3330 	int			*name = (int *)arg1;
3331 	u_int			namelen = arg2;
3332 	int			index;
3333 	struct device		*dev;
3334 	struct u_device		udev;	/* XXX this is a bit big */
3335 	int			error;
3336 
3337 	if (namelen != 2)
3338 		return (EINVAL);
3339 
3340 	if (bus_data_generation_check(name[0]))
3341 		return (EINVAL);
3342 
3343 	index = name[1];
3344 
3345 	/*
3346 	 * Scan the list of devices, looking for the requested index.
3347 	 */
3348 	TAILQ_FOREACH(dev, &bus_data_devices, devlink) {
3349 		if (index-- == 0)
3350 			break;
3351 	}
3352 	if (dev == NULL)
3353 		return (ENOENT);
3354 
3355 	/*
3356 	 * Populate the return array.
3357 	 */
3358 	bzero(&udev, sizeof(udev));
3359 	udev.dv_handle = (uintptr_t)dev;
3360 	udev.dv_parent = (uintptr_t)dev->parent;
3361 	if (dev->nameunit != NULL)
3362 		strlcpy(udev.dv_name, dev->nameunit, sizeof(udev.dv_name));
3363 	if (dev->desc != NULL)
3364 		strlcpy(udev.dv_desc, dev->desc, sizeof(udev.dv_desc));
3365 	if (dev->driver != NULL && dev->driver->name != NULL)
3366 		strlcpy(udev.dv_drivername, dev->driver->name,
3367 		    sizeof(udev.dv_drivername));
3368 	bus_child_pnpinfo_str(dev, udev.dv_pnpinfo, sizeof(udev.dv_pnpinfo));
3369 	bus_child_location_str(dev, udev.dv_location, sizeof(udev.dv_location));
3370 	udev.dv_devflags = dev->devflags;
3371 	udev.dv_flags = dev->flags;
3372 	udev.dv_state = dev->state;
3373 	error = SYSCTL_OUT(req, &udev, sizeof(udev));
3374 	return (error);
3375 }
3376 
3377 SYSCTL_NODE(_hw_bus, OID_AUTO, devices, CTLFLAG_RD, sysctl_devices,
3378     "system device tree");
3379 
3380 int
3381 bus_data_generation_check(int generation)
3382 {
3383 	if (generation != bus_data_generation)
3384 		return (1);
3385 
3386 	/* XXX generate optimised lists here? */
3387 	return (0);
3388 }
3389 
3390 void
3391 bus_data_generation_update(void)
3392 {
3393 	bus_data_generation++;
3394 }
3395