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