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