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