subr_bus.c revision 47608
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 *	$Id: subr_bus.c,v 1.28 1999/05/28 09:25:10 dfr Exp $
27 */
28
29#include <sys/param.h>
30#include <sys/queue.h>
31#include <sys/malloc.h>
32#include <sys/kernel.h>
33#include <sys/module.h>
34#include <sys/sysctl.h>
35#include <sys/bus_private.h>
36#include <sys/systm.h>
37#include <machine/bus.h>
38#include <sys/rman.h>
39#include <machine/stdarg.h>	/* for device_printf() */
40
41#include "opt_bus.h"
42
43#ifdef BUS_DEBUG
44#define PDEBUG(a)	(printf(__FUNCTION__ ":%d: ", __LINE__), printf a, printf("\n"))
45#define DEVICENAME(d)	((d)? device_get_name(d): "no device")
46#define DRIVERNAME(d)	((d)? d->name : "no driver")
47#define DEVCLANAME(d)	((d)? d->name : "no devclass")
48
49/* Produce the indenting, indent*2 spaces plus a '.' ahead of that to
50 * prevent syslog from deleting initial spaces
51 */
52#define indentprintf(p)	do { int iJ; printf("."); for (iJ=0; iJ<indent; iJ++) printf("  "); printf p ; } while(0)
53
54static void print_method_list(device_method_t *m, int indent);
55static void print_device_ops(device_ops_t ops, int indent);
56static void print_device_short(device_t dev, int indent);
57static void print_device(device_t dev, int indent);
58void print_device_tree_short(device_t dev, int indent);
59void print_device_tree(device_t dev, int indent);
60static void print_driver_short(driver_t *driver, int indent);
61static void print_driver(driver_t *driver, int indent);
62static void print_driver_list(driver_list_t drivers, int indent);
63static void print_devclass_short(devclass_t dc, int indent);
64static void print_devclass(devclass_t dc, int indent);
65void print_devclass_list_short(void);
66void print_devclass_list(void);
67
68#else
69/* Make the compiler ignore the function calls */
70#define PDEBUG(a)			/* nop */
71#define DEVICENAME(d)			/* nop */
72#define DRIVERNAME(d)			/* nop */
73#define DEVCLANAME(d)			/* nop */
74
75#define print_method_list(m,i)		/* nop */
76#define print_device_ops(o,i)		/* nop */
77#define print_device_short(d,i)		/* nop */
78#define print_device(d,i)		/* nop */
79#define print_device_tree_short(d,i)	/* nop */
80#define print_device_tree(d,i)		/* nop */
81#define print_driver_short(d,i)		/* nop */
82#define print_driver(d,i)		/* nop */
83#define print_driver_list(d,i)		/* nop */
84#define print_devclass_short(d,i)	/* nop */
85#define print_devclass(d,i)		/* nop */
86#define print_devclass_list_short()	/* nop */
87#define print_devclass_list()		/* nop */
88#endif
89
90#ifdef DEVICE_SYSCTLS
91static void device_register_oids(device_t dev);
92static void device_unregister_oids(device_t dev);
93#endif
94
95/*
96 * Method table handling
97 */
98static int error_method(void);
99static int next_method_offset = 1;
100
101LIST_HEAD(methodlist, method) methods;
102struct method {
103    LIST_ENTRY(method) link;	/* linked list of methods */
104    int offset;			/* offset in method table */
105    int refs;			/* count of device_op_desc users */
106    devop_t deflt;		/* default implementation */
107    char* name;			/* unique name of method */
108};
109
110static void
111register_method(struct device_op_desc *desc)
112{
113    struct method* m;
114
115    if (desc->method) {
116	desc->method->refs++;
117	return;
118    }
119
120    /*
121     * Make sure that desc->deflt is always valid to simplify dispatch.
122     */
123    if (!desc->deflt)
124	desc->deflt = error_method;
125
126    for (m = LIST_FIRST(&methods); m; m = LIST_NEXT(m, link)) {
127	if (!strcmp(m->name, desc->name)) {
128	    desc->offset = m->offset;
129	    desc->method = m;
130	    m->refs++;
131	    PDEBUG(("methods %x has the same name, %s, with offset %d",
132		    m, desc->name, desc->offset));
133	    return;
134	}
135    }
136
137    m = (struct method *) malloc(sizeof(struct method)
138				 + strlen(desc->name) + 1,
139				 M_DEVBUF, M_NOWAIT);
140    if (!m)
141	    panic("register_method: out of memory");
142    bzero(m, sizeof(struct method) + strlen(desc->name) + 1);
143    m->offset = next_method_offset++;
144    m->refs = 1;
145    m->deflt = desc->deflt;
146    m->name = (char*) (m + 1);
147    strcpy(m->name, desc->name);
148    LIST_INSERT_HEAD(&methods, m, link);
149
150    desc->offset = m->offset;
151    desc->method = m;
152}
153
154static void
155unregister_method(struct device_op_desc *desc)
156{
157    struct method *m = desc->method;
158    m->refs--;
159    if (m->refs == 0) {
160	LIST_REMOVE(m, link);
161	free(m, M_DEVBUF);
162    }
163    desc->method = 0;
164}
165
166static int error_method(void)
167{
168    return ENXIO;
169}
170
171static struct device_ops null_ops = {
172    1,
173    { error_method }
174};
175
176static void
177compile_methods(driver_t *driver)
178{
179    device_ops_t ops;
180    struct device_method *m;
181    struct method *cm;
182    int i;
183
184    /*
185     * First register any methods which need it.
186     */
187    for (i = 0, m = driver->methods; m->desc; i++, m++)
188	register_method(m->desc);
189
190    /*
191     * Then allocate the compiled op table.
192     */
193    ops = malloc(sizeof(struct device_ops) + (next_method_offset-1) * sizeof(devop_t),
194		 M_DEVBUF, M_NOWAIT);
195    if (!ops)
196	panic("compile_methods: out of memory");
197    bzero(ops, sizeof(struct device_ops) + (next_method_offset-1) * sizeof(devop_t));
198
199    ops->maxoffset = next_method_offset;
200    /* Fill in default methods and then overwrite with driver methods */
201    for (i = 0; i < next_method_offset; i++)
202	ops->methods[i] = error_method;
203    for (cm = LIST_FIRST(&methods); cm; cm = LIST_NEXT(cm, link)) {
204	if (cm->deflt)
205	    ops->methods[cm->offset] = cm->deflt;
206    }
207    for (i = 0, m = driver->methods; m->desc; i++, m++)
208	ops->methods[m->desc->offset] = m->func;
209    PDEBUG(("%s has %d method%s, wasting %d bytes",
210    		DRIVERNAME(driver), i, (i==1?"":"s"),
211		(next_method_offset-i)*sizeof(devop_t)));
212
213    driver->ops = ops;
214}
215
216static void
217free_methods(driver_t *driver)
218{
219    int i;
220    struct device_method *m;
221
222    /*
223     * Unregister any methods which are no longer used.
224     */
225    for (i = 0, m = driver->methods; m->desc; i++, m++)
226	unregister_method(m->desc);
227
228    /*
229     * Free memory and clean up.
230     */
231    free(driver->ops, M_DEVBUF);
232    driver->ops = 0;
233}
234
235/*
236 * Devclass implementation
237 */
238
239static devclass_list_t devclasses = TAILQ_HEAD_INITIALIZER(devclasses);
240
241static devclass_t
242devclass_find_internal(const char *classname, int create)
243{
244    devclass_t dc;
245
246    PDEBUG(("looking for %s", classname));
247    if (!classname)
248	return NULL;
249
250    for (dc = TAILQ_FIRST(&devclasses); dc; dc = TAILQ_NEXT(dc, link))
251	if (!strcmp(dc->name, classname))
252	    return dc;
253
254    PDEBUG(("%s not found%s", classname, (create? ", creating": "")));
255    if (create) {
256	dc = malloc(sizeof(struct devclass) + strlen(classname) + 1,
257		    M_DEVBUF, M_NOWAIT);
258	if (!dc)
259	    return NULL;
260	bzero(dc, sizeof(struct devclass) + strlen(classname) + 1);
261	dc->name = (char*) (dc + 1);
262	strcpy(dc->name, classname);
263	dc->devices = NULL;
264	dc->maxunit = 0;
265	dc->nextunit = 0;
266	TAILQ_INIT(&dc->drivers);
267	TAILQ_INSERT_TAIL(&devclasses, dc, link);
268    }
269
270    return dc;
271}
272
273devclass_t
274devclass_create(const char *classname)
275{
276    return devclass_find_internal(classname, TRUE);
277}
278
279devclass_t
280devclass_find(const char *classname)
281{
282    return devclass_find_internal(classname, FALSE);
283}
284
285int
286devclass_add_driver(devclass_t dc, driver_t *driver)
287{
288    driverlink_t dl;
289    int i;
290
291    PDEBUG(("%s", DRIVERNAME(driver)));
292
293    dl = malloc(sizeof *dl, M_DEVBUF, M_NOWAIT);
294    if (!dl)
295	return ENOMEM;
296    bzero(dl, sizeof *dl);
297
298    /*
299     * Compile the driver's methods.
300     */
301    if (!driver->ops)
302	compile_methods(driver);
303
304    /*
305     * Make sure the devclass which the driver is implementing exists.
306     */
307    devclass_find_internal(driver->name, TRUE);
308
309    dl->driver = driver;
310    TAILQ_INSERT_TAIL(&dc->drivers, dl, link);
311    driver->refs++;
312
313    /*
314     * Call BUS_DRIVER_ADDED for any existing busses in this class.
315     */
316    for (i = 0; i < dc->maxunit; i++)
317	if (dc->devices[i])
318	    BUS_DRIVER_ADDED(dc->devices[i], driver);
319
320    return 0;
321}
322
323int
324devclass_delete_driver(devclass_t busclass, driver_t *driver)
325{
326    devclass_t dc = devclass_find(driver->name);
327    driverlink_t dl;
328    device_t dev;
329    int i;
330    int error;
331
332    PDEBUG(("%s from devclass %s", driver->name, DEVCLANAME(busclass)));
333
334    if (!dc)
335	return 0;
336
337    /*
338     * Find the link structure in the bus' list of drivers.
339     */
340    for (dl = TAILQ_FIRST(&busclass->drivers); dl;
341	 dl = TAILQ_NEXT(dl, link)) {
342	if (dl->driver == driver)
343	    break;
344    }
345
346    if (!dl) {
347	PDEBUG(("%s not found in %s list", driver->name, busclass->name));
348	return ENOENT;
349    }
350
351    /*
352     * Disassociate from any devices.  We iterate through all the
353     * devices in the devclass of the driver and detach any which are
354     * using the driver and which have a parent in the devclass which
355     * we are deleting from.
356     *
357     * Note that since a driver can be in multiple devclasses, we
358     * should not detach devices which are not children of devices in
359     * the affected devclass.
360     */
361    for (i = 0; i < dc->maxunit; i++) {
362	if (dc->devices[i]) {
363	    dev = dc->devices[i];
364	    if (dev->driver == driver
365		&& dev->parent && dev->parent->devclass == busclass) {
366		if ((error = device_detach(dev)) != 0)
367		    return error;
368		device_set_driver(dev, NULL);
369	    }
370	}
371    }
372
373    TAILQ_REMOVE(&busclass->drivers, dl, link);
374    free(dl, M_DEVBUF);
375
376    driver->refs--;
377    if (driver->refs == 0)
378	free_methods(driver);
379
380    return 0;
381}
382
383static driverlink_t
384devclass_find_driver_internal(devclass_t dc, const char *classname)
385{
386    driverlink_t dl;
387
388    PDEBUG(("%s in devclass %s", classname, DEVCLANAME(dc)));
389
390    for (dl = TAILQ_FIRST(&dc->drivers); dl; dl = TAILQ_NEXT(dl, link)) {
391	if (!strcmp(dl->driver->name, classname))
392	    return dl;
393    }
394
395    PDEBUG(("not found"));
396    return NULL;
397}
398
399driver_t *
400devclass_find_driver(devclass_t dc, const char *classname)
401{
402    driverlink_t dl;
403
404    dl = devclass_find_driver_internal(dc, classname);
405    if (dl)
406	return dl->driver;
407    else
408	return NULL;
409}
410
411const char *
412devclass_get_name(devclass_t dc)
413{
414    return dc->name;
415}
416
417device_t
418devclass_get_device(devclass_t dc, int unit)
419{
420    if (dc == NULL || unit < 0 || unit >= dc->maxunit)
421	return NULL;
422    return dc->devices[unit];
423}
424
425void *
426devclass_get_softc(devclass_t dc, int unit)
427{
428    device_t dev;
429
430    if (unit < 0 || unit >= dc->maxunit)
431	return NULL;
432    dev = dc->devices[unit];
433    if (!dev || dev->state < DS_ATTACHED)
434	return NULL;
435    return dev->softc;
436}
437
438int
439devclass_get_devices(devclass_t dc, device_t **devlistp, int *devcountp)
440{
441    int i;
442    int count;
443    device_t *list;
444
445    count = 0;
446    for (i = 0; i < dc->maxunit; i++)
447	if (dc->devices[i])
448	    count++;
449
450    list = malloc(count * sizeof(device_t), M_TEMP, M_NOWAIT);
451    if (!list)
452	return ENOMEM;
453    bzero(list, count * sizeof(device_t));
454
455    count = 0;
456    for (i = 0; i < dc->maxunit; i++)
457	if (dc->devices[i]) {
458	    list[count] = dc->devices[i];
459	    count++;
460	}
461
462    *devlistp = list;
463    *devcountp = count;
464
465    return 0;
466}
467
468int
469devclass_get_maxunit(devclass_t dc)
470{
471    return dc->maxunit;
472}
473
474static int
475devclass_alloc_unit(devclass_t dc, int *unitp)
476{
477    int unit = *unitp;
478
479    PDEBUG(("unit %d in devclass %s", unit, DEVCLANAME(dc)));
480
481    /*
482     * If we have been given a wired unit number, check for existing
483     * device.
484     */
485    if (unit != -1) {
486	device_t dev;
487	dev = devclass_get_device(dc, unit);
488	if (dev) {
489	    printf("devclass_alloc_unit: %s%d already exists, using next available unit number\n", dc->name, unit);
490	    unit = -1;
491	}
492    }
493
494    if (unit == -1) {
495	unit = dc->nextunit;
496	dc->nextunit++;
497    } else if (dc->nextunit <= unit)
498	dc->nextunit = unit + 1;
499
500    if (unit >= dc->maxunit) {
501	device_t *newlist;
502	int newsize;
503
504	newsize = (dc->maxunit ? 2 * dc->maxunit
505		   : MINALLOCSIZE / sizeof(device_t));
506	newlist = malloc(sizeof(device_t) * newsize, M_DEVBUF, M_NOWAIT);
507	if (!newlist)
508	    return ENOMEM;
509	bcopy(dc->devices, newlist, sizeof(device_t) * dc->maxunit);
510	bzero(newlist + dc->maxunit,
511	      sizeof(device_t) * (newsize - dc->maxunit));
512	if (dc->devices)
513	    free(dc->devices, M_DEVBUF);
514	dc->devices = newlist;
515	dc->maxunit = newsize;
516    }
517    PDEBUG(("now: unit %d in devclass %s", unit, DEVCLANAME(dc)));
518
519    *unitp = unit;
520    return 0;
521}
522
523static int
524devclass_add_device(devclass_t dc, device_t dev)
525{
526    int buflen, error;
527
528    PDEBUG(("%s in devclass %s", DEVICENAME(dev), DEVCLANAME(dc)));
529
530    buflen = strlen(dc->name) + 5;
531    dev->nameunit = malloc(buflen, M_DEVBUF, M_NOWAIT);
532    if (!dev->nameunit)
533	return ENOMEM;
534    bzero(dev->nameunit, buflen);
535
536    if ((error = devclass_alloc_unit(dc, &dev->unit)) != 0) {
537	free(dev->nameunit, M_DEVBUF);
538	dev->nameunit = NULL;
539	return error;
540    }
541    dc->devices[dev->unit] = dev;
542    dev->devclass = dc;
543    snprintf(dev->nameunit, buflen, "%s%d", dc->name, dev->unit);
544
545#ifdef DEVICE_SYSCTLS
546    device_register_oids(dev);
547#endif
548
549    return 0;
550}
551
552static int
553devclass_delete_device(devclass_t dc, device_t dev)
554{
555    if (!dc || !dev)
556	return 0;
557
558    PDEBUG(("%s in devclass %s", DEVICENAME(dev), DEVCLANAME(dc)));
559
560    if (dev->devclass != dc
561	|| dc->devices[dev->unit] != dev)
562	panic("devclass_delete_device: inconsistent device class");
563    dc->devices[dev->unit] = NULL;
564    if (dev->flags & DF_WILDCARD)
565	dev->unit = -1;
566    dev->devclass = NULL;
567    free(dev->nameunit, M_DEVBUF);
568    dev->nameunit = NULL;
569    while (dc->nextunit > 0 && dc->devices[dc->nextunit - 1] == NULL)
570	dc->nextunit--;
571
572#ifdef DEVICE_SYSCTLS
573    device_unregister_oids(dev);
574#endif
575
576    return 0;
577}
578
579static device_t
580make_device(device_t parent, const char *name,
581	    int unit, void *ivars)
582{
583    device_t dev;
584    devclass_t dc;
585
586    PDEBUG(("%s at %s as unit %d with%s ivars",
587    	    name, DEVICENAME(parent), unit, (ivars? "":"out")));
588
589    if (name) {
590	dc = devclass_find_internal(name, TRUE);
591	if (!dc) {
592	    printf("make_device: can't find device class %s\n", name);
593	    return NULL;
594	}
595    } else
596	dc = NULL;
597
598    dev = malloc(sizeof(struct device), M_DEVBUF, M_NOWAIT);
599    if (!dev)
600	return 0;
601    bzero(dev, sizeof(struct device));
602
603    dev->parent = parent;
604    TAILQ_INIT(&dev->children);
605    dev->ops = &null_ops;
606    dev->driver = NULL;
607    dev->devclass = NULL;
608    dev->unit = unit;
609    dev->nameunit = NULL;
610    dev->desc = NULL;
611    dev->busy = 0;
612    dev->flags = DF_ENABLED;
613    dev->order = 0;
614    if (unit == -1)
615	dev->flags |= DF_WILDCARD;
616    if (name) {
617	dev->flags |= DF_FIXEDCLASS;
618	devclass_add_device(dc, dev);
619    }
620    dev->ivars = ivars;
621    dev->softc = NULL;
622
623    dev->state = DS_NOTPRESENT;
624
625    return dev;
626}
627
628static void
629device_print_child(device_t dev, device_t child)
630{
631    printf("%s%d", device_get_name(child), device_get_unit(child));
632    if (device_is_alive(child)) {
633	if (device_get_desc(child))
634	    printf(": <%s>", device_get_desc(child));
635	BUS_PRINT_CHILD(dev, child);
636    } else
637	printf(" not found");
638    printf("\n");
639}
640
641device_t
642device_add_child(device_t dev, const char *name, int unit, void *ivars)
643{
644    return device_add_child_ordered(dev, 0, name, unit, ivars);
645}
646
647device_t
648device_add_child_ordered(device_t dev, int order,
649			 const char *name, int unit, void *ivars)
650{
651    device_t child;
652    device_t place;
653
654    PDEBUG(("%s at %s with order %d as unit %d with%s ivars",
655    	    name, DEVICENAME(dev), order, unit, (ivars? "":"out")));
656
657    child = make_device(dev, name, unit, ivars);
658    if (child == NULL)
659	return child;
660    child->order = order;
661
662    TAILQ_FOREACH(place, &dev->children, link)
663	if (place->order > order)
664	    break;
665
666    if (place) {
667	/*
668	 * The device 'place' is the first device whose order is
669	 * greater than the new child.
670	 */
671	TAILQ_INSERT_BEFORE(place, child, link);
672    } else {
673	/*
674	 * The new child's order is greater or equal to the order of
675	 * any existing device. Add the child to the tail of the list.
676	 */
677	TAILQ_INSERT_TAIL(&dev->children, child, link);
678    }
679
680    return child;
681}
682
683int
684device_delete_child(device_t dev, device_t child)
685{
686    int error;
687    device_t grandchild;
688
689    PDEBUG(("%s from %s", DEVICENAME(child), DEVICENAME(dev)));
690
691    /* remove children first */
692    while ( (grandchild = TAILQ_FIRST(&child->children)) ) {
693        error = device_delete_child(child, grandchild);
694	if (error)
695	    return error;
696    }
697
698    if ((error = device_detach(child)) != 0)
699	return error;
700    if (child->devclass)
701	devclass_delete_device(child->devclass, child);
702    TAILQ_REMOVE(&dev->children, child, link);
703    device_set_desc(child, NULL);
704    free(child, M_DEVBUF);
705
706    return 0;
707}
708
709/*
710 * Find only devices attached to this bus.
711 */
712device_t
713device_find_child(device_t dev, const char *classname, int unit)
714{
715    devclass_t dc;
716    device_t child;
717
718    dc = devclass_find(classname);
719    if (!dc)
720	return NULL;
721
722    child = devclass_get_device(dc, unit);
723    if (child && child->parent == dev)
724	return child;
725    return NULL;
726}
727
728static driverlink_t
729first_matching_driver(devclass_t dc, device_t dev)
730{
731    if (dev->devclass)
732	return devclass_find_driver_internal(dc, dev->devclass->name);
733    else
734	return TAILQ_FIRST(&dc->drivers);
735}
736
737static driverlink_t
738next_matching_driver(devclass_t dc, device_t dev, driverlink_t last)
739{
740    if (dev->devclass) {
741	driverlink_t dl;
742	for (dl = TAILQ_NEXT(last, link); dl; dl = TAILQ_NEXT(dl, link))
743	    if (!strcmp(dev->devclass->name, dl->driver->name))
744		return dl;
745	return NULL;
746    } else
747	return TAILQ_NEXT(last, link);
748}
749
750static int
751device_probe_child(device_t dev, device_t child)
752{
753    devclass_t dc;
754    driverlink_t best = 0;
755    driverlink_t dl;
756    int result, pri = 0;
757
758    dc = dev->devclass;
759    if (dc == NULL)
760	panic("device_probe_child: parent device has no devclass");
761
762    if (child->state == DS_ALIVE)
763	return 0;
764
765    for (dl = first_matching_driver(dc, child);
766	 dl;
767	 dl = next_matching_driver(dc, child, dl)) {
768	PDEBUG(("Trying %s", DRIVERNAME(dl->driver)));
769	device_set_driver(child, dl->driver);
770	result = DEVICE_PROBE(child);
771
772	/*
773	 * If the driver returns SUCCESS, there can be no higher match
774	 * for this device.
775	 */
776	if (result == 0) {
777	    best = dl;
778	    pri = 0;
779	    break;
780	}
781
782	/*
783	 * The driver returned an error so it certainly doesn't match.
784	 */
785	if (result > 0)
786	    continue;
787
788	/*
789	 * A priority lower than SUCCESS, remember the best matching
790	 * driver. Initialise the value of pri for the first match.
791	 */
792	if (best == 0 || result > pri) {
793	    best = dl;
794	    pri = result;
795	    continue;
796	}
797    }
798
799    /*
800     * If we found a driver, change state and initialise the devclass.
801     */
802    if (best) {
803	if (!child->devclass)
804	    device_set_devclass(child, best->driver->name);
805	device_set_driver(child, best->driver);
806	if (pri < 0) {
807	    /*
808	     * A bit bogus. Call the probe method again to make sure
809	     * that we have the right description.
810	     */
811	    DEVICE_PROBE(child);
812	}
813	child->state = DS_ALIVE;
814	return 0;
815    }
816
817    return ENXIO;
818}
819
820device_t
821device_get_parent(device_t dev)
822{
823    return dev->parent;
824}
825
826int
827device_get_children(device_t dev, device_t **devlistp, int *devcountp)
828{
829    int count;
830    device_t child;
831    device_t *list;
832
833    count = 0;
834    for (child = TAILQ_FIRST(&dev->children); child;
835	 child = TAILQ_NEXT(child, link))
836	count++;
837
838    list = malloc(count * sizeof(device_t), M_TEMP, M_NOWAIT);
839    if (!list)
840	return ENOMEM;
841    bzero(list, count * sizeof(device_t));
842
843    count = 0;
844    for (child = TAILQ_FIRST(&dev->children); child;
845	 child = TAILQ_NEXT(child, link)) {
846	list[count] = child;
847	count++;
848    }
849
850    *devlistp = list;
851    *devcountp = count;
852
853    return 0;
854}
855
856driver_t *
857device_get_driver(device_t dev)
858{
859    return dev->driver;
860}
861
862devclass_t
863device_get_devclass(device_t dev)
864{
865    return dev->devclass;
866}
867
868const char *
869device_get_name(device_t dev)
870{
871    if (dev->devclass)
872	return devclass_get_name(dev->devclass);
873    return NULL;
874}
875
876const char *
877device_get_nameunit(device_t dev)
878{
879    return dev->nameunit;
880}
881
882int
883device_get_unit(device_t dev)
884{
885    return dev->unit;
886}
887
888const char *
889device_get_desc(device_t dev)
890{
891    return dev->desc;
892}
893
894void
895device_print_prettyname(device_t dev)
896{
897	const char *name = device_get_name(dev);
898
899	if (name == 0)
900		name = "(no driver assigned)";
901	printf("%s%d: ", name, device_get_unit(dev));
902}
903
904void
905device_printf(device_t dev, const char * fmt, ...)
906{
907	va_list ap;
908
909	device_print_prettyname(dev);
910	va_start(ap, fmt);
911	vprintf(fmt, ap);
912	va_end(ap);
913}
914
915static void
916device_set_desc_internal(device_t dev, const char* desc, int copy)
917{
918    if (dev->desc && (dev->flags & DF_DESCMALLOCED)) {
919	free(dev->desc, M_DEVBUF);
920	dev->flags &= ~DF_DESCMALLOCED;
921	dev->desc = NULL;
922    }
923
924    if (copy && desc) {
925	dev->desc = malloc(strlen(desc) + 1, M_DEVBUF, M_NOWAIT);
926	if (dev->desc) {
927	    strcpy(dev->desc, desc);
928	    dev->flags |= DF_DESCMALLOCED;
929	}
930    } else
931	/* Avoid a -Wcast-qual warning */
932	dev->desc = (char *)(uintptr_t) desc;
933
934#ifdef DEVICE_SYSCTLS
935    {
936	struct sysctl_oid *oid = &dev->oid[1];
937	oid->oid_arg1 = dev->desc ? dev->desc : "";
938	oid->oid_arg2 = dev->desc ? strlen(dev->desc) : 0;
939    }
940#endif
941}
942
943void
944device_set_desc(device_t dev, const char* desc)
945{
946    device_set_desc_internal(dev, desc, FALSE);
947}
948
949void
950device_set_desc_copy(device_t dev, const char* desc)
951{
952    device_set_desc_internal(dev, desc, TRUE);
953}
954
955void *
956device_get_softc(device_t dev)
957{
958    return dev->softc;
959}
960
961void *
962device_get_ivars(device_t dev)
963{
964    return dev->ivars;
965}
966
967device_state_t
968device_get_state(device_t dev)
969{
970    return dev->state;
971}
972
973void
974device_enable(device_t dev)
975{
976    dev->flags |= DF_ENABLED;
977}
978
979void
980device_disable(device_t dev)
981{
982    dev->flags &= ~DF_ENABLED;
983}
984
985void
986device_busy(device_t dev)
987{
988    if (dev->state < DS_ATTACHED)
989	panic("device_busy: called for unattached device");
990    if (dev->busy == 0 && dev->parent)
991	device_busy(dev->parent);
992    dev->busy++;
993    dev->state = DS_BUSY;
994}
995
996void
997device_unbusy(device_t dev)
998{
999    if (dev->state != DS_BUSY)
1000	panic("device_unbusy: called for non-busy device");
1001    dev->busy--;
1002    if (dev->busy == 0) {
1003	if (dev->parent)
1004	    device_unbusy(dev->parent);
1005	dev->state = DS_ATTACHED;
1006    }
1007}
1008
1009void
1010device_quiet(device_t dev)
1011{
1012    dev->flags |= DF_QUIET;
1013}
1014
1015void
1016device_verbose(device_t dev)
1017{
1018    dev->flags &= ~DF_QUIET;
1019}
1020
1021int
1022device_is_quiet(device_t dev)
1023{
1024    return (dev->flags & DF_QUIET) != 0;
1025}
1026
1027int
1028device_is_enabled(device_t dev)
1029{
1030    return (dev->flags & DF_ENABLED) != 0;
1031}
1032
1033int
1034device_is_alive(device_t dev)
1035{
1036    return dev->state >= DS_ALIVE;
1037}
1038
1039int
1040device_set_devclass(device_t dev, const char *classname)
1041{
1042    devclass_t dc;
1043
1044    if (dev->devclass) {
1045	printf("device_set_devclass: device class already set\n");
1046	return EINVAL;
1047    }
1048
1049    dc = devclass_find_internal(classname, TRUE);
1050    if (!dc)
1051	return ENOMEM;
1052
1053    return devclass_add_device(dc, dev);
1054}
1055
1056int
1057device_set_driver(device_t dev, driver_t *driver)
1058{
1059    if (dev->state >= DS_ATTACHED)
1060	return EBUSY;
1061
1062    if (dev->driver == driver)
1063	return 0;
1064
1065    if (dev->softc) {
1066	free(dev->softc, M_DEVBUF);
1067	dev->softc = NULL;
1068    }
1069    dev->ops = &null_ops;
1070    dev->driver = driver;
1071    if (driver) {
1072	dev->ops = driver->ops;
1073	dev->softc = malloc(driver->softc, M_DEVBUF, M_NOWAIT);
1074	if (!dev->softc) {
1075	    dev->ops = &null_ops;
1076	    dev->driver = NULL;
1077	    return ENOMEM;
1078	}
1079	bzero(dev->softc, driver->softc);
1080    }
1081    return 0;
1082}
1083
1084int
1085device_probe_and_attach(device_t dev)
1086{
1087    device_t bus = dev->parent;
1088    int error = 0;
1089
1090    if (dev->state >= DS_ALIVE)
1091	return 0;
1092
1093    if (dev->flags & DF_ENABLED) {
1094	error = device_probe_child(bus, dev);
1095	if (!error) {
1096	    if (!device_is_quiet(dev))
1097		device_print_child(bus, dev);
1098	    error = DEVICE_ATTACH(dev);
1099	    if (!error)
1100		dev->state = DS_ATTACHED;
1101	    else {
1102		printf("device_probe_and_attach: %s%d attach returned %d\n",
1103		       dev->driver->name, dev->unit, error);
1104		device_set_driver(dev, NULL);
1105		dev->state = DS_NOTPRESENT;
1106	    }
1107	}
1108    } else {
1109	    device_print_prettyname(dev);
1110	    printf("not probed (disabled)\n");
1111    }
1112
1113    return error;
1114}
1115
1116int
1117device_detach(device_t dev)
1118{
1119    int error;
1120
1121    PDEBUG(("%s", DEVICENAME(dev)));
1122    if (dev->state == DS_BUSY)
1123	return EBUSY;
1124    if (dev->state != DS_ATTACHED)
1125	return 0;
1126
1127    if ((error = DEVICE_DETACH(dev)) != 0)
1128	return error;
1129    if (dev->parent)
1130	BUS_CHILD_DETACHED(dev->parent, dev);
1131
1132    if (!(dev->flags & DF_FIXEDCLASS))
1133	devclass_delete_device(dev->devclass, dev);
1134
1135    dev->state = DS_NOTPRESENT;
1136    device_set_driver(dev, NULL);
1137
1138    return 0;
1139}
1140
1141int
1142device_shutdown(device_t dev)
1143{
1144    if (dev->state < DS_ATTACHED)
1145	return 0;
1146    return DEVICE_SHUTDOWN(dev);
1147}
1148
1149#ifdef DEVICE_SYSCTLS
1150
1151/*
1152 * Sysctl nodes for devices.
1153 */
1154
1155SYSCTL_NODE(_hw, OID_AUTO, devices, CTLFLAG_RW, 0, "A list of all devices");
1156
1157static int
1158sysctl_handle_children SYSCTL_HANDLER_ARGS
1159{
1160    device_t dev = arg1;
1161    device_t child;
1162    int first = 1, error = 0;
1163
1164    for (child = TAILQ_FIRST(&dev->children); child;
1165	 child = TAILQ_NEXT(child, link)) {
1166	if (child->nameunit) {
1167	    if (!first) {
1168		error = SYSCTL_OUT(req, ",", 1);
1169		if (error) return error;
1170	    } else {
1171		first = 0;
1172	    }
1173	    error = SYSCTL_OUT(req, child->nameunit, strlen(child->nameunit));
1174	    if (error) return error;
1175	}
1176    }
1177
1178    error = SYSCTL_OUT(req, "", 1);
1179
1180    return error;
1181}
1182
1183static int
1184sysctl_handle_state SYSCTL_HANDLER_ARGS
1185{
1186    device_t dev = arg1;
1187
1188    switch (dev->state) {
1189    case DS_NOTPRESENT:
1190	return SYSCTL_OUT(req, "notpresent", sizeof("notpresent"));
1191    case DS_ALIVE:
1192	return SYSCTL_OUT(req, "alive", sizeof("alive"));
1193    case DS_ATTACHED:
1194	return SYSCTL_OUT(req, "attached", sizeof("attached"));
1195    case DS_BUSY:
1196	return SYSCTL_OUT(req, "busy", sizeof("busy"));
1197    }
1198
1199    return 0;
1200}
1201
1202static void
1203device_register_oids(device_t dev)
1204{
1205    struct sysctl_oid* oid;
1206
1207    oid = &dev->oid[0];
1208    bzero(oid, sizeof(*oid));
1209    oid->oid_parent = &sysctl__hw_devices_children;
1210    oid->oid_number = OID_AUTO;
1211    oid->oid_kind = CTLTYPE_NODE | CTLFLAG_RW;
1212    oid->oid_arg1 = &dev->oidlist[0];
1213    oid->oid_arg2 = 0;
1214    oid->oid_name = dev->nameunit;
1215    oid->oid_handler = 0;
1216    oid->oid_fmt = "N";
1217    SLIST_INIT(&dev->oidlist[0]);
1218    sysctl_register_oid(oid);
1219
1220    oid = &dev->oid[1];
1221    bzero(oid, sizeof(*oid));
1222    oid->oid_parent = &dev->oidlist[0];
1223    oid->oid_number = OID_AUTO;
1224    oid->oid_kind = CTLTYPE_STRING | CTLFLAG_RD;
1225    oid->oid_arg1 = dev->desc ? dev->desc : "";
1226    oid->oid_arg2 = dev->desc ? strlen(dev->desc) : 0;
1227    oid->oid_name = "desc";
1228    oid->oid_handler = sysctl_handle_string;
1229    oid->oid_fmt = "A";
1230    sysctl_register_oid(oid);
1231
1232    oid = &dev->oid[2];
1233    bzero(oid, sizeof(*oid));
1234    oid->oid_parent = &dev->oidlist[0];
1235    oid->oid_number = OID_AUTO;
1236    oid->oid_kind = CTLTYPE_INT | CTLFLAG_RD;
1237    oid->oid_arg1 = dev;
1238    oid->oid_arg2 = 0;
1239    oid->oid_name = "children";
1240    oid->oid_handler = sysctl_handle_children;
1241    oid->oid_fmt = "A";
1242    sysctl_register_oid(oid);
1243
1244    oid = &dev->oid[3];
1245    bzero(oid, sizeof(*oid));
1246    oid->oid_parent = &dev->oidlist[0];
1247    oid->oid_number = OID_AUTO;
1248    oid->oid_kind = CTLTYPE_INT | CTLFLAG_RD;
1249    oid->oid_arg1 = dev;
1250    oid->oid_arg2 = 0;
1251    oid->oid_name = "state";
1252    oid->oid_handler = sysctl_handle_state;
1253    oid->oid_fmt = "A";
1254    sysctl_register_oid(oid);
1255}
1256
1257static void
1258device_unregister_oids(device_t dev)
1259{
1260    sysctl_unregister_oid(&dev->oid[0]);
1261    sysctl_unregister_oid(&dev->oid[1]);
1262    sysctl_unregister_oid(&dev->oid[2]);
1263}
1264
1265#endif
1266
1267/*======================================*/
1268/*
1269 * Access functions for device resources.
1270 */
1271
1272/* Supplied by config(8) in ioconf.c */
1273extern struct config_device config_devtab[];
1274extern int devtab_count;
1275
1276/* Runtime version */
1277struct config_device *devtab = config_devtab;
1278
1279static int
1280resource_new_name(char *name, int unit)
1281{
1282	struct config_device *new;
1283
1284	new = malloc((devtab_count + 1) * sizeof(*new), M_TEMP, M_NOWAIT);
1285	if (new == NULL)
1286		return -1;
1287	if (devtab && devtab_count > 0)
1288		bcopy(devtab, new, devtab_count * sizeof(*new));
1289	bzero(&new[devtab_count], sizeof(*new));
1290	new[devtab_count].name = malloc(strlen(name) + 1, M_TEMP, M_NOWAIT);
1291	if (new[devtab_count].name == NULL) {
1292		free(new, M_TEMP);
1293		return -1;
1294	}
1295	strcpy(new[devtab_count].name, name);
1296	new[devtab_count].unit = unit;
1297	new[devtab_count].resource_count = 0;
1298	new[devtab_count].resources = NULL;
1299	devtab = new;
1300	return devtab_count++;
1301}
1302
1303static int
1304resource_new_resname(int j, char *resname, resource_type type)
1305{
1306	struct config_resource *new;
1307	int i;
1308
1309	i = devtab[j].resource_count;
1310	new = malloc((i + 1) * sizeof(*new), M_TEMP, M_NOWAIT);
1311	if (new == NULL)
1312		return -1;
1313	if (devtab[j].resources && i > 0)
1314		bcopy(devtab[j].resources, new, i * sizeof(*new));
1315	bzero(&new[i], sizeof(*new));
1316	new[i].name = malloc(strlen(resname) + 1, M_TEMP, M_NOWAIT);
1317	if (new[i].name == NULL) {
1318		free(new, M_TEMP);
1319		return -1;
1320	}
1321	strcpy(new[i].name, resname);
1322	new[i].type = type;
1323	if (devtab[j].resources)
1324		free(devtab[j].resources, M_TEMP);
1325	devtab[j].resources = new;
1326	devtab[j].resource_count = i + 1;
1327	return i;
1328}
1329
1330static int
1331resource_match_string(int i, char *resname, char *value)
1332{
1333	int j;
1334	struct config_resource *res;
1335
1336	for (j = 0, res = devtab[i].resources;
1337	     j < devtab[i].resource_count; j++, res++)
1338		if (!strcmp(res->name, resname)
1339		    && res->type == RES_STRING
1340		    && !strcmp(res->u.stringval, value))
1341			return j;
1342	return -1;
1343}
1344
1345static int
1346resource_find(const char *name, int unit, char *resname,
1347	      struct config_resource **result)
1348{
1349	int i, j;
1350	struct config_resource *res;
1351
1352	/*
1353	 * First check specific instances, then generic.
1354	 */
1355	for (i = 0; i < devtab_count; i++) {
1356		if (devtab[i].unit < 0)
1357			continue;
1358		if (!strcmp(devtab[i].name, name) && devtab[i].unit == unit) {
1359			res = devtab[i].resources;
1360			for (j = 0; j < devtab[i].resource_count; j++, res++)
1361				if (!strcmp(res->name, resname)) {
1362					*result = res;
1363					return 0;
1364				}
1365		}
1366	}
1367	for (i = 0; i < devtab_count; i++) {
1368		if (devtab[i].unit >= 0)
1369			continue;
1370		/* XXX should this `&& devtab[i].unit == unit' be here? */
1371		/* XXX if so, then the generic match does nothing */
1372		if (!strcmp(devtab[i].name, name) && devtab[i].unit == unit) {
1373			res = devtab[i].resources;
1374			for (j = 0; j < devtab[i].resource_count; j++, res++)
1375				if (!strcmp(res->name, resname)) {
1376					*result = res;
1377					return 0;
1378				}
1379		}
1380	}
1381	return ENOENT;
1382}
1383
1384int
1385resource_int_value(const char *name, int unit, char *resname, int *result)
1386{
1387	int error;
1388	struct config_resource *res;
1389
1390	if ((error = resource_find(name, unit, resname, &res)) != 0)
1391		return error;
1392	if (res->type != RES_INT)
1393		return EFTYPE;
1394	*result = res->u.intval;
1395	return 0;
1396}
1397
1398int
1399resource_long_value(const char *name, int unit, char *resname, long *result)
1400{
1401	int error;
1402	struct config_resource *res;
1403
1404	if ((error = resource_find(name, unit, resname, &res)) != 0)
1405		return error;
1406	if (res->type != RES_LONG)
1407		return EFTYPE;
1408	*result = res->u.longval;
1409	return 0;
1410}
1411
1412int
1413resource_string_value(const char *name, int unit, char *resname, char **result)
1414{
1415	int error;
1416	struct config_resource *res;
1417
1418	if ((error = resource_find(name, unit, resname, &res)) != 0)
1419		return error;
1420	if (res->type != RES_STRING)
1421		return EFTYPE;
1422	*result = res->u.stringval;
1423	return 0;
1424}
1425
1426int
1427resource_query_string(int i, char *resname, char *value)
1428{
1429	if (i < 0)
1430		i = 0;
1431	else
1432		i = i + 1;
1433	for (; i < devtab_count; i++)
1434		if (resource_match_string(i, resname, value) >= 0)
1435			return i;
1436	return -1;
1437}
1438
1439int
1440resource_locate(int i, char *resname)
1441{
1442	if (i < 0)
1443		i = 0;
1444	else
1445		i = i + 1;
1446	for (; i < devtab_count; i++)
1447		if (!strcmp(devtab[i].name, resname))
1448			return i;
1449	return -1;
1450}
1451
1452int
1453resource_count(void)
1454{
1455	return devtab_count;
1456}
1457
1458char *
1459resource_query_name(int i)
1460{
1461	return devtab[i].name;
1462}
1463
1464int
1465resource_query_unit(int i)
1466{
1467	return devtab[i].unit;
1468}
1469
1470static int
1471resource_create(char *name, int unit, char *resname, resource_type type,
1472		struct config_resource **result)
1473{
1474	int i, j;
1475	struct config_resource *res = NULL;
1476
1477	for (i = 0; i < devtab_count; i++) {
1478		if (!strcmp(devtab[i].name, name) && devtab[i].unit == unit) {
1479			res = devtab[i].resources;
1480			break;
1481		}
1482	}
1483	if (res == NULL) {
1484		i = resource_new_name(name, unit);
1485		if (i < 0)
1486			return ENOMEM;
1487		res = devtab[i].resources;
1488	}
1489	for (j = 0; j < devtab[i].resource_count; j++, res++) {
1490		if (!strcmp(res->name, resname)) {
1491			*result = res;
1492			return 0;
1493		}
1494	}
1495	j = resource_new_resname(i, resname, type);
1496	if (j < 0)
1497		return ENOMEM;
1498	res = &devtab[i].resources[j];
1499	*result = res;
1500	return 0;
1501}
1502
1503int
1504resource_set_int(char *name, int unit, char *resname, int value)
1505{
1506	int error;
1507	struct config_resource *res;
1508
1509	error = resource_create(name, unit, resname, RES_INT, &res);
1510	if (error)
1511		return error;
1512	if (res->type != RES_INT)
1513		return EFTYPE;
1514	res->u.intval = value;
1515	return 0;
1516}
1517
1518int
1519resource_set_long(char *name, int unit, char *resname, long value)
1520{
1521	int error;
1522	struct config_resource *res;
1523
1524	error = resource_create(name, unit, resname, RES_LONG, &res);
1525	if (error)
1526		return error;
1527	if (res->type != RES_LONG)
1528		return EFTYPE;
1529	res->u.longval = value;
1530	return 0;
1531}
1532
1533int
1534resource_set_string(char *name, int unit, char *resname, char *value)
1535{
1536	int error;
1537	struct config_resource *res;
1538
1539	error = resource_create(name, unit, resname, RES_STRING, &res);
1540	if (error)
1541		return error;
1542	if (res->type != RES_STRING)
1543		return EFTYPE;
1544	if (res->u.stringval)
1545		free(res->u.stringval, M_TEMP);
1546	res->u.stringval = malloc(strlen(value) + 1, M_TEMP, M_NOWAIT);
1547	if (res->u.stringval == NULL)
1548		return ENOMEM;
1549	strcpy(res->u.stringval, value);
1550	return 0;
1551}
1552
1553
1554static void
1555resource_cfgload(void *dummy __unused)
1556{
1557	struct config_resource *res, *cfgres;
1558	int i, j;
1559	int error;
1560	char *name, *resname;
1561	int unit;
1562	resource_type type;
1563	char *stringval;
1564	int config_devtab_count;
1565
1566	config_devtab_count = devtab_count;
1567	devtab = NULL;
1568	devtab_count = 0;
1569
1570	for (i = 0; i < config_devtab_count; i++) {
1571		name = config_devtab[i].name;
1572		unit = config_devtab[i].unit;
1573
1574		for (j = 0; j < config_devtab[i].resource_count; j++) {
1575			cfgres = config_devtab[i].resources;
1576			resname = cfgres[j].name;
1577			type = cfgres[j].type;
1578			error = resource_create(name, unit, resname, type,
1579						&res);
1580			if (error) {
1581				printf("create resource %s%d: error %d\n",
1582					name, unit, error);
1583				continue;
1584			}
1585			if (res->type != type) {
1586				printf("type mismatch %s%d: %d != %d\n",
1587					name, unit, res->type, type);
1588				continue;
1589			}
1590			switch (type) {
1591			case RES_INT:
1592				res->u.intval = cfgres[j].u.intval;
1593				break;
1594			case RES_LONG:
1595				res->u.longval = cfgres[j].u.longval;
1596				break;
1597			case RES_STRING:
1598				if (res->u.stringval)
1599					free(res->u.stringval, M_TEMP);
1600				stringval = cfgres[j].u.stringval;
1601				res->u.stringval = malloc(strlen(stringval) + 1,
1602							  M_TEMP, M_NOWAIT);
1603				if (res->u.stringval == NULL)
1604					break;
1605				strcpy(res->u.stringval, stringval);
1606				break;
1607			default:
1608				panic("unknown resource type %d\n", type);
1609			}
1610		}
1611	}
1612}
1613SYSINIT(cfgload, SI_SUB_KMEM, SI_ORDER_ANY + 50, resource_cfgload, 0)
1614
1615
1616/*======================================*/
1617/*
1618 * Some useful method implementations to make life easier for bus drivers.
1619 */
1620
1621void
1622resource_list_init(struct resource_list *rl)
1623{
1624	SLIST_INIT(rl);
1625}
1626
1627void
1628resource_list_free(struct resource_list *rl)
1629{
1630    struct resource_list_entry *rle;
1631
1632    while ((rle = SLIST_FIRST(rl)) != NULL) {
1633	if (rle->res)
1634	    panic("resource_list_free: resource entry is busy");
1635	SLIST_REMOVE_HEAD(rl, link);
1636	free(rle, M_DEVBUF);
1637    }
1638}
1639
1640void
1641resource_list_add(struct resource_list *rl,
1642		  int type, int rid,
1643		  u_long start, u_long end, u_long count)
1644{
1645    struct resource_list_entry *rle;
1646
1647    rle = resource_list_find(rl, type, rid);
1648    if (!rle) {
1649	rle = malloc(sizeof(struct resource_list_entry), M_DEVBUF, M_NOWAIT);
1650	if (!rle)
1651	    panic("resource_list_add: can't record entry");
1652	SLIST_INSERT_HEAD(rl, rle, link);
1653	rle->type = type;
1654	rle->rid = rid;
1655	rle->res = NULL;
1656    }
1657
1658    if (rle->res)
1659	panic("resource_list_add: resource entry is busy");
1660
1661    rle->start = start;
1662    rle->end = end;
1663    rle->count = count;
1664}
1665
1666struct resource_list_entry*
1667resource_list_find(struct resource_list *rl,
1668		   int type, int rid)
1669{
1670    struct resource_list_entry *rle;
1671
1672    SLIST_FOREACH(rle, rl, link)
1673	if (rle->type == type && rle->rid == rid)
1674	    return rle;
1675    return NULL;
1676}
1677
1678void
1679resource_list_delete(struct resource_list *rl,
1680		     int type, int rid)
1681{
1682    struct resource_list_entry *rle = resource_list_find(rl, type, rid);
1683
1684    if (rle) {
1685	SLIST_REMOVE(rl, rle, resource_list_entry, link);
1686	free(rle, M_DEVBUF);
1687    }
1688}
1689
1690struct resource *
1691resource_list_alloc(device_t bus, device_t child,
1692		    int type, int *rid,
1693		    u_long start, u_long end,
1694		    u_long count, u_int flags)
1695{
1696    struct resource_list *rl;
1697    struct resource_list_entry *rle = 0;
1698    int passthrough = (device_get_parent(child) != bus);
1699    int isdefault = (start == 0UL && end == ~0UL);
1700
1701    if (passthrough) {
1702	return BUS_ALLOC_RESOURCE(device_get_parent(bus), child,
1703				  type, rid,
1704				  start, end, count, flags);
1705    }
1706
1707    rl = device_get_ivars(child);
1708    rle = resource_list_find(rl, type, *rid);
1709
1710    if (!rle)
1711	return 0;		/* no resource of that type/rid */
1712    if (rle->res)
1713	panic("resource_list_alloc: resource entry is busy");
1714
1715    if (isdefault) {
1716	start = rle->start;
1717	count = max(count, rle->count);
1718	end = max(rle->end, start + count - 1);
1719    }
1720
1721    rle->res = BUS_ALLOC_RESOURCE(device_get_parent(bus), child,
1722				  type, rid, start, end, count, flags);
1723
1724    /*
1725     * Record the new range.
1726     */
1727    if (rle->res) {
1728	    rle->start = rman_get_start(rle->res);
1729	    rle->end = rman_get_end(rle->res);
1730	    rle->count = count;
1731    }
1732
1733    return rle->res;
1734}
1735
1736int
1737resource_list_release(device_t bus, device_t child,
1738		      int type, int rid, struct resource *res)
1739{
1740    struct resource_list *rl;
1741    struct resource_list_entry *rle = 0;
1742    int passthrough = (device_get_parent(child) != bus);
1743    int error;
1744
1745    if (passthrough) {
1746	return BUS_RELEASE_RESOURCE(device_get_parent(bus), child,
1747				    type, rid, res);
1748    }
1749
1750    rl = device_get_ivars(child);
1751    rle = resource_list_find(rl, type, rid);
1752
1753    if (!rle)
1754	panic("resource_list_release: can't find resource");
1755    if (!rle->res)
1756	panic("resource_list_release: resource entry is not busy");
1757
1758    error = BUS_RELEASE_RESOURCE(device_get_parent(bus), child,
1759				 type, rid, res);
1760    if (error)
1761	return error;
1762
1763    rle->res = NULL;
1764    return 0;
1765}
1766
1767/*
1768 * Call DEVICE_IDENTIFY for each driver.
1769 */
1770int
1771bus_generic_probe(device_t dev)
1772{
1773    devclass_t dc = dev->devclass;
1774    driverlink_t dl;
1775
1776    for (dl = TAILQ_FIRST(&dc->drivers); dl; dl = TAILQ_NEXT(dl, link))
1777	DEVICE_IDENTIFY(dl->driver, dev);
1778
1779    return 0;
1780}
1781
1782int
1783bus_generic_attach(device_t dev)
1784{
1785    device_t child;
1786
1787    for (child = TAILQ_FIRST(&dev->children);
1788	 child; child = TAILQ_NEXT(child, link))
1789	device_probe_and_attach(child);
1790
1791    return 0;
1792}
1793
1794int
1795bus_generic_detach(device_t dev)
1796{
1797    device_t child;
1798    int error;
1799
1800    if (dev->state != DS_ATTACHED)
1801	return EBUSY;
1802
1803    for (child = TAILQ_FIRST(&dev->children);
1804	 child; child = TAILQ_NEXT(child, link))
1805	if ((error = device_detach(child)) != 0)
1806	    return error;
1807
1808    return 0;
1809}
1810
1811int
1812bus_generic_shutdown(device_t dev)
1813{
1814    device_t child;
1815
1816    for (child = TAILQ_FIRST(&dev->children);
1817	 child; child = TAILQ_NEXT(child, link))
1818	device_shutdown(child);
1819
1820    return 0;
1821}
1822
1823int
1824bus_generic_suspend(device_t dev)
1825{
1826	int		error;
1827	device_t	child, child2;
1828
1829	for (child = TAILQ_FIRST(&dev->children);
1830	     child; child = TAILQ_NEXT(child, link)) {
1831		error = DEVICE_SUSPEND(child);
1832		if (error) {
1833			for (child2 = TAILQ_FIRST(&dev->children);
1834			     child2 && child2 != child;
1835			     child2 = TAILQ_NEXT(child2, link))
1836				DEVICE_RESUME(child2);
1837			return (error);
1838		}
1839	}
1840	return 0;
1841}
1842
1843int
1844bus_generic_resume(device_t dev)
1845{
1846	device_t	child;
1847
1848	for (child = TAILQ_FIRST(&dev->children);
1849	     child; child = TAILQ_NEXT(child, link)) {
1850		DEVICE_RESUME(child);
1851		/* if resume fails, there's nothing we can usefully do... */
1852	}
1853	return 0;
1854}
1855
1856void
1857bus_generic_print_child(device_t dev, device_t child)
1858{
1859	printf(" on %s%d", device_get_name(dev), device_get_unit(dev));
1860}
1861
1862int
1863bus_generic_read_ivar(device_t dev, device_t child, int index,
1864		      uintptr_t * result)
1865{
1866    return ENOENT;
1867}
1868
1869int
1870bus_generic_write_ivar(device_t dev, device_t child, int index,
1871		       uintptr_t value)
1872{
1873    return ENOENT;
1874}
1875
1876void
1877bus_generic_driver_added(device_t dev, driver_t *driver)
1878{
1879    device_t child;
1880
1881    for (child = TAILQ_FIRST(&dev->children);
1882	 child; child = TAILQ_NEXT(child, link))
1883	if (child->state == DS_NOTPRESENT)
1884	    device_probe_and_attach(child);
1885}
1886
1887int
1888bus_generic_setup_intr(device_t dev, device_t child, struct resource *irq,
1889		       int flags, driver_intr_t *intr, void *arg,
1890		       void **cookiep)
1891{
1892	/* Propagate up the bus hierarchy until someone handles it. */
1893	if (dev->parent)
1894		return (BUS_SETUP_INTR(dev->parent, child, irq, flags,
1895				       intr, arg, cookiep));
1896	else
1897		return (EINVAL);
1898}
1899
1900int
1901bus_generic_teardown_intr(device_t dev, device_t child, struct resource *irq,
1902			  void *cookie)
1903{
1904	/* Propagate up the bus hierarchy until someone handles it. */
1905	if (dev->parent)
1906		return (BUS_TEARDOWN_INTR(dev->parent, child, irq, cookie));
1907	else
1908		return (EINVAL);
1909}
1910
1911struct resource *
1912bus_generic_alloc_resource(device_t dev, device_t child, int type, int *rid,
1913			   u_long start, u_long end, u_long count, u_int flags)
1914{
1915	/* Propagate up the bus hierarchy until someone handles it. */
1916	if (dev->parent)
1917		return (BUS_ALLOC_RESOURCE(dev->parent, child, type, rid,
1918					   start, end, count, flags));
1919	else
1920		return (NULL);
1921}
1922
1923int
1924bus_generic_release_resource(device_t dev, device_t child, int type, int rid,
1925			     struct resource *r)
1926{
1927	/* Propagate up the bus hierarchy until someone handles it. */
1928	if (dev->parent)
1929		return (BUS_RELEASE_RESOURCE(dev->parent, child, type, rid,
1930					     r));
1931	else
1932		return (EINVAL);
1933}
1934
1935int
1936bus_generic_activate_resource(device_t dev, device_t child, int type, int rid,
1937			      struct resource *r)
1938{
1939	/* Propagate up the bus hierarchy until someone handles it. */
1940	if (dev->parent)
1941		return (BUS_ACTIVATE_RESOURCE(dev->parent, child, type, rid,
1942					      r));
1943	else
1944		return (EINVAL);
1945}
1946
1947int
1948bus_generic_deactivate_resource(device_t dev, device_t child, int type,
1949				int rid, struct resource *r)
1950{
1951	/* Propagate up the bus hierarchy until someone handles it. */
1952	if (dev->parent)
1953		return (BUS_DEACTIVATE_RESOURCE(dev->parent, child, type, rid,
1954						r));
1955	else
1956		return (EINVAL);
1957}
1958
1959/*
1960 * Some convenience functions to make it easier for drivers to use the
1961 * resource-management functions.  All these really do is hide the
1962 * indirection through the parent's method table, making for slightly
1963 * less-wordy code.  In the future, it might make sense for this code
1964 * to maintain some sort of a list of resources allocated by each device.
1965 */
1966struct resource *
1967bus_alloc_resource(device_t dev, int type, int *rid, u_long start, u_long end,
1968		   u_long count, u_int flags)
1969{
1970	if (dev->parent == 0)
1971		return (0);
1972	return (BUS_ALLOC_RESOURCE(dev->parent, dev, type, rid, start, end,
1973				   count, flags));
1974}
1975
1976int
1977bus_activate_resource(device_t dev, int type, int rid, struct resource *r)
1978{
1979	if (dev->parent == 0)
1980		return (EINVAL);
1981	return (BUS_ACTIVATE_RESOURCE(dev->parent, dev, type, rid, r));
1982}
1983
1984int
1985bus_deactivate_resource(device_t dev, int type, int rid, struct resource *r)
1986{
1987	if (dev->parent == 0)
1988		return (EINVAL);
1989	return (BUS_DEACTIVATE_RESOURCE(dev->parent, dev, type, rid, r));
1990}
1991
1992int
1993bus_release_resource(device_t dev, int type, int rid, struct resource *r)
1994{
1995	if (dev->parent == 0)
1996		return (EINVAL);
1997	return (BUS_RELEASE_RESOURCE(dev->parent, dev,
1998				     type, rid, r));
1999}
2000
2001int
2002bus_setup_intr(device_t dev, struct resource *r, int flags,
2003	       driver_intr_t handler, void *arg, void **cookiep)
2004{
2005	if (dev->parent == 0)
2006		return (EINVAL);
2007	return (BUS_SETUP_INTR(dev->parent, dev, r, flags,
2008			       handler, arg, cookiep));
2009}
2010
2011int
2012bus_teardown_intr(device_t dev, struct resource *r, void *cookie)
2013{
2014	if (dev->parent == 0)
2015		return (EINVAL);
2016	return (BUS_TEARDOWN_INTR(dev->parent, dev, r, cookie));
2017}
2018
2019static void
2020root_print_child(device_t dev, device_t child)
2021{
2022}
2023
2024static int
2025root_setup_intr(device_t dev, device_t child, driver_intr_t *intr, void *arg,
2026		void **cookiep)
2027{
2028	/*
2029	 * If an interrupt mapping gets to here something bad has happened.
2030	 */
2031	panic("root_setup_intr");
2032}
2033
2034static device_method_t root_methods[] = {
2035	/* Device interface */
2036	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
2037	DEVMETHOD(device_suspend,	bus_generic_suspend),
2038	DEVMETHOD(device_resume,	bus_generic_resume),
2039
2040	/* Bus interface */
2041	DEVMETHOD(bus_print_child,	root_print_child),
2042	DEVMETHOD(bus_read_ivar,	bus_generic_read_ivar),
2043	DEVMETHOD(bus_write_ivar,	bus_generic_write_ivar),
2044	DEVMETHOD(bus_setup_intr,	root_setup_intr),
2045
2046	{ 0, 0 }
2047};
2048
2049static driver_t root_driver = {
2050	"root",
2051	root_methods,
2052	1,			/* no softc */
2053};
2054
2055device_t	root_bus;
2056devclass_t	root_devclass;
2057
2058static int
2059root_bus_module_handler(module_t mod, int what, void* arg)
2060{
2061    switch (what) {
2062    case MOD_LOAD:
2063	compile_methods(&root_driver);
2064	root_bus = make_device(NULL, "root", 0, NULL);
2065	root_bus->desc = "System root bus";
2066	root_bus->ops = root_driver.ops;
2067	root_bus->driver = &root_driver;
2068	root_bus->state = DS_ATTACHED;
2069	root_devclass = devclass_find_internal("root", FALSE);
2070	return 0;
2071
2072    case MOD_SHUTDOWN:
2073	device_shutdown(root_bus);
2074	return 0;
2075    }
2076
2077    return 0;
2078}
2079
2080static moduledata_t root_bus_mod = {
2081	"rootbus",
2082	root_bus_module_handler,
2083	0
2084};
2085DECLARE_MODULE(rootbus, root_bus_mod, SI_SUB_DRIVERS, SI_ORDER_FIRST);
2086
2087void
2088root_bus_configure(void)
2089{
2090    device_t dev;
2091
2092    PDEBUG(("."));
2093
2094    for (dev = TAILQ_FIRST(&root_bus->children); dev;
2095	 dev = TAILQ_NEXT(dev, link)) {
2096	device_probe_and_attach(dev);
2097    }
2098}
2099
2100int
2101driver_module_handler(module_t mod, int what, void *arg)
2102{
2103	int error, i;
2104	struct driver_module_data *dmd;
2105	devclass_t bus_devclass;
2106
2107	dmd = (struct driver_module_data *)arg;
2108	bus_devclass = devclass_find_internal(dmd->dmd_busname, TRUE);
2109	error = 0;
2110
2111	switch (what) {
2112	case MOD_LOAD:
2113		for (i = 0; !error && i < dmd->dmd_ndrivers; i++) {
2114			PDEBUG(("Loading module: driver %s on bus %s",
2115				DRIVERNAME(dmd->dmd_drivers[i]),
2116				dmd->dmd_busname));
2117			error = devclass_add_driver(bus_devclass,
2118						    dmd->dmd_drivers[i]);
2119		}
2120		if (error)
2121			break;
2122
2123		/*
2124		 * The drivers loaded in this way are assumed to all
2125		 * implement the same devclass.
2126		 */
2127		*dmd->dmd_devclass =
2128			devclass_find_internal(dmd->dmd_drivers[0]->name,
2129					       TRUE);
2130		break;
2131
2132	case MOD_UNLOAD:
2133		for (i = 0; !error && i < dmd->dmd_ndrivers; i++) {
2134			PDEBUG(("Unloading module: driver %s from bus %s",
2135				DRIVERNAME(dmd->dmd_drivers[i]),
2136				dmd->dmd_busname));
2137			error = devclass_delete_driver(bus_devclass,
2138						       dmd->dmd_drivers[i]);
2139		}
2140		break;
2141	}
2142
2143	if (!error && dmd->dmd_chainevh)
2144		error = dmd->dmd_chainevh(mod, what, dmd->dmd_chainarg);
2145	return (error);
2146}
2147
2148#ifdef BUS_DEBUG
2149
2150/* the _short versions avoid iteration by not calling anything that prints
2151 * more than oneliners. I love oneliners.
2152 */
2153
2154static void
2155print_method_list(device_method_t *m, int indent)
2156{
2157	int i;
2158
2159	if (!m)
2160		return;
2161
2162	for (i = 0; m->desc; i++, m++)
2163		indentprintf(("method %d: %s, offset=%d\n",
2164			i, m->desc->name, m->desc->offset));
2165}
2166
2167static void
2168print_device_ops(device_ops_t ops, int indent)
2169{
2170	int i;
2171	int count = 0;
2172
2173	if (!ops)
2174		return;
2175
2176	/* we present a list of the methods that are pointing to the
2177	 * error_method, but ignore the 0'th elements; it is always
2178	 * error_method.
2179	 */
2180	for (i = 1; i < ops->maxoffset; i++) {
2181		if (ops->methods[i] == error_method) {
2182			if (count == 0)
2183				indentprintf(("error_method:"));
2184			printf(" %d", i);
2185			count++;
2186		}
2187	}
2188	if (count)
2189		printf("\n");
2190
2191	indentprintf(("(%d method%s, %d valid, %d error_method%s)\n",
2192		ops->maxoffset-1, (ops->maxoffset-1 == 1? "":"s"),
2193		ops->maxoffset-1-count,
2194		count, (count == 1? "":"'s")));
2195}
2196
2197static void
2198print_device_short(device_t dev, int indent)
2199{
2200	if (!dev)
2201		return;
2202
2203	indentprintf(("device %d: <%s> %sparent,%schildren,%s%s%s%sivars,%ssoftc,busy=%d\n",
2204		dev->unit, dev->desc,
2205		(dev->parent? "":"no "),
2206		(TAILQ_EMPTY(&dev->children)? "no ":""),
2207		(dev->flags&DF_ENABLED? "enabled,":"disabled,"),
2208		(dev->flags&DF_FIXEDCLASS? "fixed,":""),
2209		(dev->flags&DF_WILDCARD? "wildcard,":""),
2210		(dev->flags&DF_DESCMALLOCED? "descmalloced,":""),
2211		(dev->ivars? "":"no "),
2212		(dev->softc? "":"no "),
2213		dev->busy));
2214}
2215
2216static void
2217print_device(device_t dev, int indent)
2218{
2219	if (!dev)
2220		return;
2221
2222	print_device_short(dev, indent);
2223
2224	indentprintf(("Parent:\n"));
2225	print_device_short(dev->parent, indent+1);
2226	indentprintf(("Methods:\n"));
2227	print_device_ops(dev->ops, indent+1);
2228	indentprintf(("Driver:\n"));
2229	print_driver_short(dev->driver, indent+1);
2230	indentprintf(("Devclass:\n"));
2231	print_devclass_short(dev->devclass, indent+1);
2232}
2233
2234void
2235print_device_tree_short(device_t dev, int indent)
2236/* print the device and all its children (indented) */
2237{
2238	device_t child;
2239
2240	if (!dev)
2241		return;
2242
2243	print_device_short(dev, indent);
2244
2245	for (child = TAILQ_FIRST(&dev->children); child;
2246		 child = TAILQ_NEXT(child, link))
2247		print_device_tree_short(child, indent+1);
2248}
2249
2250void
2251print_device_tree(device_t dev, int indent)
2252/* print the device and all its children (indented) */
2253{
2254	device_t child;
2255
2256	if (!dev)
2257		return;
2258
2259	print_device(dev, indent);
2260
2261	for (child = TAILQ_FIRST(&dev->children); child;
2262		 child = TAILQ_NEXT(child, link))
2263		print_device_tree(child, indent+1);
2264}
2265
2266static void
2267print_driver_short(driver_t *driver, int indent)
2268{
2269	if (!driver)
2270		return;
2271
2272	indentprintf(("driver %s: type = %s%s%s%s, softc size = %d\n",
2273		driver->name,
2274		/* yes, I know this looks silly, but going to bed at
2275		 * two o'clock and having to get up at 7:30 again is silly
2276		 * as well. As is sticking your head in a bucket of water.
2277		 */
2278		(driver->type == DRIVER_TYPE_TTY? "tty":""),
2279		(driver->type == DRIVER_TYPE_BIO? "bio":""),
2280		(driver->type == DRIVER_TYPE_NET? "net":""),
2281		(driver->type == DRIVER_TYPE_MISC? "misc":""),
2282		driver->softc));
2283}
2284
2285static void
2286print_driver(driver_t *driver, int indent)
2287{
2288	if (!driver)
2289		return;
2290
2291	print_driver_short(driver, indent);
2292	indentprintf(("Methods:\n"));
2293	print_method_list(driver->methods, indent+1);
2294	indentprintf(("Operations:\n"));
2295	print_device_ops(driver->ops, indent+1);
2296}
2297
2298
2299static void
2300print_driver_list(driver_list_t drivers, int indent)
2301{
2302	driver_t *driver;
2303
2304	for (driver = TAILQ_FIRST(&drivers); driver;
2305	     driver = TAILQ_NEXT(driver, link))
2306		print_driver(driver, indent);
2307}
2308
2309static void
2310print_devclass_short(devclass_t dc, int indent)
2311{
2312	if ( !dc )
2313		return;
2314
2315	indentprintf(("devclass %s: max units = %d, next unit = %d\n",
2316		dc->name, dc->maxunit, dc->nextunit));
2317}
2318
2319static void
2320print_devclass(devclass_t dc, int indent)
2321{
2322	int i;
2323
2324	if ( !dc )
2325		return;
2326
2327	print_devclass_short(dc, indent);
2328	indentprintf(("Drivers:\n"));
2329	print_driver_list(dc->drivers, indent+1);
2330
2331	indentprintf(("Devices:\n"));
2332	for (i = 0; i < dc->maxunit; i++)
2333		if (dc->devices[i])
2334			print_device(dc->devices[i], indent+1);
2335}
2336
2337void
2338print_devclass_list_short(void)
2339{
2340	devclass_t dc;
2341
2342	printf("Short listing of devclasses, drivers & devices:\n");
2343	for (dc = TAILQ_FIRST(&devclasses); dc; dc = TAILQ_NEXT(dc, link))
2344		print_devclass_short(dc, 0);
2345}
2346
2347void
2348print_devclass_list(void)
2349{
2350	devclass_t dc;
2351
2352	printf("Full listing of devclasses, drivers & devices:\n");
2353	for (dc = TAILQ_FIRST(&devclasses); dc; dc = TAILQ_NEXT(dc, link))
2354		print_devclass(dc, 0);
2355}
2356
2357#endif
2358