source: rtems-libbsd/freebsd/sys/kern/subr_bus.c @ af5333e

4.1155-freebsd-126-freebsd-12freebsd-9.3
Last change on this file since af5333e was af5333e, checked in by Sebastian Huber <sebastian.huber@…>, on 11/04/13 at 10:33:00

Update to FreeBSD 8.4

  • Property mode set to 100644
File size: 113.9 KB
Line 
1#include <machine/rtems-bsd-config.h>
2
3/*-
4 * Copyright (c) 1997,1998,2003 Doug Rabson
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 *    notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 *    notice, this list of conditions and the following disclaimer in the
14 *    documentation and/or other materials provided with the distribution.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28
29#include <sys/cdefs.h>
30__FBSDID("$FreeBSD$");
31
32#include <rtems/bsd/local/opt_bus.h>
33
34#include <rtems/bsd/sys/param.h>
35#include <sys/conf.h>
36#include <sys/filio.h>
37#include <rtems/bsd/sys/lock.h>
38#include <sys/kernel.h>
39#include <sys/kobj.h>
40#include <sys/limits.h>
41#include <sys/malloc.h>
42#include <sys/module.h>
43#include <sys/mutex.h>
44#include <sys/poll.h>
45#include <sys/proc.h>
46#include <sys/condvar.h>
47#include <sys/queue.h>
48#include <machine/bus.h>
49#include <sys/rman.h>
50#include <sys/selinfo.h>
51#include <sys/signalvar.h>
52#include <sys/sysctl.h>
53#include <sys/systm.h>
54#include <sys/uio.h>
55#include <sys/bus.h>
56#include <sys/interrupt.h>
57
58#include <machine/stdarg.h>
59
60#include <vm/uma.h>
61
62SYSCTL_NODE(_hw, OID_AUTO, bus, CTLFLAG_RW, NULL, NULL);
63SYSCTL_NODE(, OID_AUTO, dev, CTLFLAG_RW, NULL, NULL);
64
65/*
66 * Used to attach drivers to devclasses.
67 */
68typedef struct driverlink *driverlink_t;
69struct driverlink {
70        kobj_class_t    driver;
71        TAILQ_ENTRY(driverlink) link;   /* list of drivers in devclass */
72        int             pass;
73        TAILQ_ENTRY(driverlink) passlink;
74};
75
76/*
77 * Forward declarations
78 */
79typedef TAILQ_HEAD(devclass_list, devclass) devclass_list_t;
80typedef TAILQ_HEAD(driver_list, driverlink) driver_list_t;
81typedef TAILQ_HEAD(device_list, device) device_list_t;
82
83struct devclass {
84        TAILQ_ENTRY(devclass) link;
85        devclass_t      parent;         /* parent in devclass hierarchy */
86        driver_list_t   drivers;     /* bus devclasses store drivers for bus */
87        char            *name;
88        device_t        *devices;       /* array of devices indexed by unit */
89        int             maxunit;        /* size of devices array */
90        int             flags;
91#define DC_HAS_CHILDREN         1
92
93#ifndef __rtems__
94        struct sysctl_ctx_list sysctl_ctx;
95        struct sysctl_oid *sysctl_tree;
96#endif /* __rtems__ */
97};
98
99/**
100 * @brief Implementation of device.
101 */
102struct device {
103        /*
104         * A device is a kernel object. The first field must be the
105         * current ops table for the object.
106         */
107        KOBJ_FIELDS;
108
109        /*
110         * Device hierarchy.
111         */
112        TAILQ_ENTRY(device)     link;   /**< list of devices in parent */
113        TAILQ_ENTRY(device)     devlink; /**< global device list membership */
114        device_t        parent;         /**< parent of this device  */
115        device_list_t   children;       /**< list of child devices */
116
117        /*
118         * Details of this device.
119         */
120        driver_t        *driver;        /**< current driver */
121        devclass_t      devclass;       /**< current device class */
122        int             unit;           /**< current unit number */
123        char*           nameunit;       /**< name+unit e.g. foodev0 */
124        char*           desc;           /**< driver specific description */
125        int             busy;           /**< count of calls to device_busy() */
126        device_state_t  state;          /**< current device state  */
127        u_int32_t       devflags;       /**< api level flags for device_get_flags() */
128        u_int           flags;          /**< internal device flags  */
129#define DF_ENABLED      0x01            /* device should be probed/attached */
130#define DF_FIXEDCLASS   0x02            /* devclass specified at create time */
131#define DF_WILDCARD     0x04            /* unit was originally wildcard */
132#define DF_DESCMALLOCED 0x08            /* description was malloced */
133#define DF_QUIET        0x10            /* don't print verbose attach message */
134#define DF_DONENOMATCH  0x20            /* don't execute DEVICE_NOMATCH again */
135#define DF_EXTERNALSOFTC 0x40           /* softc not allocated by us */
136#define DF_REBID        0x80            /* Can rebid after attach */
137        u_int   order;                  /**< order from device_add_child_ordered() */
138        void    *ivars;                 /**< instance variables  */
139        void    *softc;                 /**< current driver's variables  */
140
141#ifndef __rtems__
142        struct sysctl_ctx_list sysctl_ctx; /**< state for sysctl variables  */
143        struct sysctl_oid *sysctl_tree; /**< state for sysctl variables */
144#endif /* __rtems__ */
145};
146
147static MALLOC_DEFINE(M_BUS, "bus", "Bus data structures");
148static MALLOC_DEFINE(M_BUS_SC, "bus-sc", "Bus data structures, softc");
149
150#ifdef BUS_DEBUG
151
152static int bus_debug = 1;
153#ifndef __rtems__
154TUNABLE_INT("bus.debug", &bus_debug);
155SYSCTL_INT(_debug, OID_AUTO, bus_debug, CTLFLAG_RW, &bus_debug, 0,
156    "Debug bus code");
157#endif /* __rtems__ */
158
159#define PDEBUG(a)       if (bus_debug) {printf("%s:%d: ", __func__, __LINE__), printf a; printf("\n");}
160#define DEVICENAME(d)   ((d)? device_get_name(d): "no device")
161#define DRIVERNAME(d)   ((d)? d->name : "no driver")
162#define DEVCLANAME(d)   ((d)? d->name : "no devclass")
163
164/**
165 * Produce the indenting, indent*2 spaces plus a '.' ahead of that to
166 * prevent syslog from deleting initial spaces
167 */
168#define indentprintf(p) do { int iJ; printf("."); for (iJ=0; iJ<indent; iJ++) printf("  "); printf p ; } while (0)
169
170static void print_device_short(device_t dev, int indent);
171static void print_device(device_t dev, int indent);
172void print_device_tree_short(device_t dev, int indent);
173void print_device_tree(device_t dev, int indent);
174static void print_driver_short(driver_t *driver, int indent);
175static void print_driver(driver_t *driver, int indent);
176static void print_driver_list(driver_list_t drivers, int indent);
177static void print_devclass_short(devclass_t dc, int indent);
178static void print_devclass(devclass_t dc, int indent);
179void print_devclass_list_short(void);
180void print_devclass_list(void);
181
182#else
183/* Make the compiler ignore the function calls */
184#define PDEBUG(a)                       /* nop */
185#define DEVICENAME(d)                   /* nop */
186#define DRIVERNAME(d)                   /* nop */
187#define DEVCLANAME(d)                   /* nop */
188
189#define print_device_short(d,i)         /* nop */
190#define print_device(d,i)               /* nop */
191#define print_device_tree_short(d,i)    /* nop */
192#define print_device_tree(d,i)          /* nop */
193#define print_driver_short(d,i)         /* nop */
194#define print_driver(d,i)               /* nop */
195#define print_driver_list(d,i)          /* nop */
196#define print_devclass_short(d,i)       /* nop */
197#define print_devclass(d,i)             /* nop */
198#define print_devclass_list_short()     /* nop */
199#define print_devclass_list()           /* nop */
200#endif
201
202#ifndef __rtems__
203/*
204 * dev sysctl tree
205 */
206
207enum {
208        DEVCLASS_SYSCTL_PARENT,
209};
210
211static int
212devclass_sysctl_handler(SYSCTL_HANDLER_ARGS)
213{
214        devclass_t dc = (devclass_t)arg1;
215        const char *value;
216
217        switch (arg2) {
218        case DEVCLASS_SYSCTL_PARENT:
219                value = dc->parent ? dc->parent->name : "";
220                break;
221        default:
222                return (EINVAL);
223        }
224        return (SYSCTL_OUT(req, value, strlen(value)));
225}
226
227static void
228devclass_sysctl_init(devclass_t dc)
229{
230
231        if (dc->sysctl_tree != NULL)
232                return;
233        sysctl_ctx_init(&dc->sysctl_ctx);
234        dc->sysctl_tree = SYSCTL_ADD_NODE(&dc->sysctl_ctx,
235            SYSCTL_STATIC_CHILDREN(_dev), OID_AUTO, dc->name,
236            CTLFLAG_RD, NULL, "");
237        SYSCTL_ADD_PROC(&dc->sysctl_ctx, SYSCTL_CHILDREN(dc->sysctl_tree),
238            OID_AUTO, "%parent", CTLFLAG_RD,
239            dc, DEVCLASS_SYSCTL_PARENT, devclass_sysctl_handler, "A",
240            "parent class");
241}
242
243enum {
244        DEVICE_SYSCTL_DESC,
245        DEVICE_SYSCTL_DRIVER,
246        DEVICE_SYSCTL_LOCATION,
247        DEVICE_SYSCTL_PNPINFO,
248        DEVICE_SYSCTL_PARENT,
249};
250
251static int
252device_sysctl_handler(SYSCTL_HANDLER_ARGS)
253{
254        device_t dev = (device_t)arg1;
255        const char *value;
256        char *buf;
257        int error;
258
259        buf = NULL;
260        switch (arg2) {
261        case DEVICE_SYSCTL_DESC:
262                value = dev->desc ? dev->desc : "";
263                break;
264        case DEVICE_SYSCTL_DRIVER:
265                value = dev->driver ? dev->driver->name : "";
266                break;
267        case DEVICE_SYSCTL_LOCATION:
268                value = buf = malloc(1024, M_BUS, M_WAITOK | M_ZERO);
269                bus_child_location_str(dev, buf, 1024);
270                break;
271        case DEVICE_SYSCTL_PNPINFO:
272                value = buf = malloc(1024, M_BUS, M_WAITOK | M_ZERO);
273                bus_child_pnpinfo_str(dev, buf, 1024);
274                break;
275        case DEVICE_SYSCTL_PARENT:
276                value = dev->parent ? dev->parent->nameunit : "";
277                break;
278        default:
279                return (EINVAL);
280        }
281        error = SYSCTL_OUT(req, value, strlen(value));
282        if (buf != NULL)
283                free(buf, M_BUS);
284        return (error);
285}
286#endif /* __rtems__ */
287
288static void
289device_sysctl_init(device_t dev)
290{
291#ifndef __rtems__
292        devclass_t dc = dev->devclass;
293
294        if (dev->sysctl_tree != NULL)
295                return;
296        devclass_sysctl_init(dc);
297        sysctl_ctx_init(&dev->sysctl_ctx);
298        dev->sysctl_tree = SYSCTL_ADD_NODE(&dev->sysctl_ctx,
299            SYSCTL_CHILDREN(dc->sysctl_tree), OID_AUTO,
300            dev->nameunit + strlen(dc->name),
301            CTLFLAG_RD, NULL, "");
302        SYSCTL_ADD_PROC(&dev->sysctl_ctx, SYSCTL_CHILDREN(dev->sysctl_tree),
303            OID_AUTO, "%desc", CTLFLAG_RD,
304            dev, DEVICE_SYSCTL_DESC, device_sysctl_handler, "A",
305            "device description");
306        SYSCTL_ADD_PROC(&dev->sysctl_ctx, SYSCTL_CHILDREN(dev->sysctl_tree),
307            OID_AUTO, "%driver", CTLFLAG_RD,
308            dev, DEVICE_SYSCTL_DRIVER, device_sysctl_handler, "A",
309            "device driver name");
310        SYSCTL_ADD_PROC(&dev->sysctl_ctx, SYSCTL_CHILDREN(dev->sysctl_tree),
311            OID_AUTO, "%location", CTLFLAG_RD,
312            dev, DEVICE_SYSCTL_LOCATION, device_sysctl_handler, "A",
313            "device location relative to parent");
314        SYSCTL_ADD_PROC(&dev->sysctl_ctx, SYSCTL_CHILDREN(dev->sysctl_tree),
315            OID_AUTO, "%pnpinfo", CTLFLAG_RD,
316            dev, DEVICE_SYSCTL_PNPINFO, device_sysctl_handler, "A",
317            "device identification");
318        SYSCTL_ADD_PROC(&dev->sysctl_ctx, SYSCTL_CHILDREN(dev->sysctl_tree),
319            OID_AUTO, "%parent", CTLFLAG_RD,
320            dev, DEVICE_SYSCTL_PARENT, device_sysctl_handler, "A",
321            "parent device");
322#endif /* __rtems__ */
323}
324
325static void
326device_sysctl_update(device_t dev)
327{
328#ifndef __rtems__
329        devclass_t dc = dev->devclass;
330
331        if (dev->sysctl_tree == NULL)
332                return;
333        sysctl_rename_oid(dev->sysctl_tree, dev->nameunit + strlen(dc->name));
334#endif /* __rtems__ */
335}
336
337static void
338device_sysctl_fini(device_t dev)
339{
340#ifndef __rtems__
341        if (dev->sysctl_tree == NULL)
342                return;
343        sysctl_ctx_free(&dev->sysctl_ctx);
344        dev->sysctl_tree = NULL;
345#endif /* __rtems__ */
346}
347
348/*
349 * /dev/devctl implementation
350 */
351
352/*
353 * This design allows only one reader for /dev/devctl.  This is not desirable
354 * in the long run, but will get a lot of hair out of this implementation.
355 * Maybe we should make this device a clonable device.
356 *
357 * Also note: we specifically do not attach a device to the device_t tree
358 * to avoid potential chicken and egg problems.  One could argue that all
359 * of this belongs to the root node.  One could also further argue that the
360 * sysctl interface that we have not might more properly be an ioctl
361 * interface, but at this stage of the game, I'm not inclined to rock that
362 * boat.
363 *
364 * I'm also not sure that the SIGIO support is done correctly or not, as
365 * I copied it from a driver that had SIGIO support that likely hasn't been
366 * tested since 3.4 or 2.2.8!
367 */
368
369#ifndef __rtems__
370/* Deprecated way to adjust queue length */
371static int sysctl_devctl_disable(SYSCTL_HANDLER_ARGS);
372/* XXX Need to support old-style tunable hw.bus.devctl_disable" */
373SYSCTL_PROC(_hw_bus, OID_AUTO, devctl_disable, CTLTYPE_INT | CTLFLAG_RW, NULL,
374    0, sysctl_devctl_disable, "I", "devctl disable -- deprecated");
375#endif /* __rtems__ */
376
377#define DEVCTL_DEFAULT_QUEUE_LEN 1000
378#ifndef __rtems__
379static int sysctl_devctl_queue(SYSCTL_HANDLER_ARGS);
380#endif /* __rtems__ */
381static int devctl_queue_length = DEVCTL_DEFAULT_QUEUE_LEN;
382#ifndef __rtems__
383TUNABLE_INT("hw.bus.devctl_queue", &devctl_queue_length);
384SYSCTL_PROC(_hw_bus, OID_AUTO, devctl_queue, CTLTYPE_INT | CTLFLAG_RW, NULL,
385    0, sysctl_devctl_queue, "I", "devctl queue length");
386
387static d_open_t         devopen;
388static d_close_t        devclose;
389static d_read_t         devread;
390static d_ioctl_t        devioctl;
391static d_poll_t         devpoll;
392
393static struct cdevsw dev_cdevsw = {
394        .d_version =    D_VERSION,
395        .d_flags =      D_NEEDGIANT,
396        .d_open =       devopen,
397        .d_close =      devclose,
398        .d_read =       devread,
399        .d_ioctl =      devioctl,
400        .d_poll =       devpoll,
401        .d_name =       "devctl",
402};
403
404struct dev_event_info
405{
406        char *dei_data;
407        TAILQ_ENTRY(dev_event_info) dei_link;
408};
409
410TAILQ_HEAD(devq, dev_event_info);
411
412static struct dev_softc
413{
414        int     inuse;
415        int     nonblock;
416        int     queued;
417        struct mtx mtx;
418        struct cv cv;
419        struct selinfo sel;
420        struct devq devq;
421        struct proc *async_proc;
422} devsoftc;
423
424static struct cdev *devctl_dev;
425#else /* __rtems__ */
426#define devctl_disable 0
427#endif /* __rtems__ */
428
429static void
430devinit(void)
431{
432#ifndef __rtems__
433        devctl_dev = make_dev_credf(MAKEDEV_ETERNAL, &dev_cdevsw, 0, NULL,
434            UID_ROOT, GID_WHEEL, 0600, "devctl");
435        mtx_init(&devsoftc.mtx, "dev mtx", "devd", MTX_DEF);
436        cv_init(&devsoftc.cv, "dev cv");
437        TAILQ_INIT(&devsoftc.devq);
438#endif /* __rtems__ */
439}
440
441#ifndef __rtems__
442static int
443devopen(struct cdev *dev, int oflags, int devtype, struct thread *td)
444{
445        if (devsoftc.inuse)
446                return (EBUSY);
447        /* move to init */
448        devsoftc.inuse = 1;
449        devsoftc.nonblock = 0;
450        devsoftc.async_proc = NULL;
451        return (0);
452}
453
454static int
455devclose(struct cdev *dev, int fflag, int devtype, struct thread *td)
456{
457        devsoftc.inuse = 0;
458        mtx_lock(&devsoftc.mtx);
459        cv_broadcast(&devsoftc.cv);
460        mtx_unlock(&devsoftc.mtx);
461        devsoftc.async_proc = NULL;
462        return (0);
463}
464
465/*
466 * The read channel for this device is used to report changes to
467 * userland in realtime.  We are required to free the data as well as
468 * the n1 object because we allocate them separately.  Also note that
469 * we return one record at a time.  If you try to read this device a
470 * character at a time, you will lose the rest of the data.  Listening
471 * programs are expected to cope.
472 */
473static int
474devread(struct cdev *dev, struct uio *uio, int ioflag)
475{
476        struct dev_event_info *n1;
477        int rv;
478
479        mtx_lock(&devsoftc.mtx);
480        while (TAILQ_EMPTY(&devsoftc.devq)) {
481                if (devsoftc.nonblock) {
482                        mtx_unlock(&devsoftc.mtx);
483                        return (EAGAIN);
484                }
485                rv = cv_wait_sig(&devsoftc.cv, &devsoftc.mtx);
486                if (rv) {
487                        /*
488                         * Need to translate ERESTART to EINTR here? -- jake
489                         */
490                        mtx_unlock(&devsoftc.mtx);
491                        return (rv);
492                }
493        }
494        n1 = TAILQ_FIRST(&devsoftc.devq);
495        TAILQ_REMOVE(&devsoftc.devq, n1, dei_link);
496        devsoftc.queued--;
497        mtx_unlock(&devsoftc.mtx);
498        rv = uiomove(n1->dei_data, strlen(n1->dei_data), uio);
499        free(n1->dei_data, M_BUS);
500        free(n1, M_BUS);
501        return (rv);
502}
503
504static  int
505devioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag, struct thread *td)
506{
507        switch (cmd) {
508
509        case FIONBIO:
510                if (*(int*)data)
511                        devsoftc.nonblock = 1;
512                else
513                        devsoftc.nonblock = 0;
514                return (0);
515        case FIOASYNC:
516                if (*(int*)data)
517                        devsoftc.async_proc = td->td_proc;
518                else
519                        devsoftc.async_proc = NULL;
520                return (0);
521
522                /* (un)Support for other fcntl() calls. */
523        case FIOCLEX:
524        case FIONCLEX:
525        case FIONREAD:
526        case FIOSETOWN:
527        case FIOGETOWN:
528        default:
529                break;
530        }
531        return (ENOTTY);
532}
533
534static  int
535devpoll(struct cdev *dev, int events, struct thread *td)
536{
537        int     revents = 0;
538
539        mtx_lock(&devsoftc.mtx);
540        if (events & (POLLIN | POLLRDNORM)) {
541                if (!TAILQ_EMPTY(&devsoftc.devq))
542                        revents = events & (POLLIN | POLLRDNORM);
543                else
544                        selrecord(td, &devsoftc.sel);
545        }
546        mtx_unlock(&devsoftc.mtx);
547
548        return (revents);
549}
550
551/**
552 * @brief Return whether the userland process is running
553 */
554boolean_t
555devctl_process_running(void)
556{
557        return (devsoftc.inuse == 1);
558}
559#endif /* __rtems__ */
560
561/**
562 * @brief Queue data to be read from the devctl device
563 *
564 * Generic interface to queue data to the devctl device.  It is
565 * assumed that @p data is properly formatted.  It is further assumed
566 * that @p data is allocated using the M_BUS malloc type.
567 */
568void
569devctl_queue_data_f(char *data, int flags)
570{
571#ifndef __rtems__
572        struct dev_event_info *n1 = NULL, *n2 = NULL;
573        struct proc *p;
574#endif /* __rtems__ */
575
576        if (strlen(data) == 0)
577                goto out;
578#ifndef __rtems__
579        if (devctl_queue_length == 0)
580                goto out;
581        n1 = malloc(sizeof(*n1), M_BUS, flags);
582        if (n1 == NULL)
583                goto out;
584        n1->dei_data = data;
585        mtx_lock(&devsoftc.mtx);
586        if (devctl_queue_length == 0) {
587                mtx_unlock(&devsoftc.mtx);
588                free(n1->dei_data, M_BUS);
589                free(n1, M_BUS);
590                return;
591        }
592        /* Leave at least one spot in the queue... */
593        while (devsoftc.queued > devctl_queue_length - 1) {
594                n2 = TAILQ_FIRST(&devsoftc.devq);
595                TAILQ_REMOVE(&devsoftc.devq, n2, dei_link);
596                free(n2->dei_data, M_BUS);
597                free(n2, M_BUS);
598                devsoftc.queued--;
599        }
600        TAILQ_INSERT_TAIL(&devsoftc.devq, n1, dei_link);
601        devsoftc.queued++;
602        cv_broadcast(&devsoftc.cv);
603        mtx_unlock(&devsoftc.mtx);
604        selwakeup(&devsoftc.sel);
605        p = devsoftc.async_proc;
606        if (p != NULL) {
607                PROC_LOCK(p);
608                psignal(p, SIGIO);
609                PROC_UNLOCK(p);
610        }
611#else /* __rtems__ */
612        printf("devctl: %s", data);
613#endif /* __rtems__ */
614out:
615        /*
616         * We have to free data on all error paths since the caller
617         * assumes it will be free'd when this item is dequeued.
618         */
619        free(data, M_BUS);
620        return;
621}
622
623void
624devctl_queue_data(char *data)
625{
626
627        devctl_queue_data_f(data, M_NOWAIT);
628}
629
630/**
631 * @brief Send a 'notification' to userland, using standard ways
632 */
633void
634devctl_notify_f(const char *system, const char *subsystem, const char *type,
635    const char *data, int flags)
636{
637        int len = 0;
638        char *msg;
639
640        if (system == NULL)
641                return;         /* BOGUS!  Must specify system. */
642        if (subsystem == NULL)
643                return;         /* BOGUS!  Must specify subsystem. */
644        if (type == NULL)
645                return;         /* BOGUS!  Must specify type. */
646        len += strlen(" system=") + strlen(system);
647        len += strlen(" subsystem=") + strlen(subsystem);
648        len += strlen(" type=") + strlen(type);
649        /* add in the data message plus newline. */
650        if (data != NULL)
651                len += strlen(data);
652        len += 3;       /* '!', '\n', and NUL */
653        msg = malloc(len, M_BUS, flags);
654        if (msg == NULL)
655                return;         /* Drop it on the floor */
656        if (data != NULL)
657                snprintf(msg, len, "!system=%s subsystem=%s type=%s %s\n",
658                    system, subsystem, type, data);
659        else
660                snprintf(msg, len, "!system=%s subsystem=%s type=%s\n",
661                    system, subsystem, type);
662        devctl_queue_data_f(msg, flags);
663}
664
665void
666devctl_notify(const char *system, const char *subsystem, const char *type,
667    const char *data)
668{
669
670        devctl_notify_f(system, subsystem, type, data, M_NOWAIT);
671}
672
673/*
674 * Common routine that tries to make sending messages as easy as possible.
675 * We allocate memory for the data, copy strings into that, but do not
676 * free it unless there's an error.  The dequeue part of the driver should
677 * free the data.  We don't send data when the device is disabled.  We do
678 * send data, even when we have no listeners, because we wish to avoid
679 * races relating to startup and restart of listening applications.
680 *
681 * devaddq is designed to string together the type of event, with the
682 * object of that event, plus the plug and play info and location info
683 * for that event.  This is likely most useful for devices, but less
684 * useful for other consumers of this interface.  Those should use
685 * the devctl_queue_data() interface instead.
686 */
687static void
688devaddq(const char *type, const char *what, device_t dev)
689{
690        char *data = NULL;
691        char *loc = NULL;
692        char *pnp = NULL;
693        const char *parstr;
694
695        if (!devctl_queue_length)/* Rare race, but lost races safely discard */
696                return;
697        data = malloc(1024, M_BUS, M_NOWAIT);
698        if (data == NULL)
699                goto bad;
700
701        /* get the bus specific location of this device */
702        loc = malloc(1024, M_BUS, M_NOWAIT);
703        if (loc == NULL)
704                goto bad;
705        *loc = '\0';
706        bus_child_location_str(dev, loc, 1024);
707
708        /* Get the bus specific pnp info of this device */
709        pnp = malloc(1024, M_BUS, M_NOWAIT);
710        if (pnp == NULL)
711                goto bad;
712        *pnp = '\0';
713        bus_child_pnpinfo_str(dev, pnp, 1024);
714
715        /* Get the parent of this device, or / if high enough in the tree. */
716        if (device_get_parent(dev) == NULL)
717                parstr = ".";   /* Or '/' ? */
718        else
719                parstr = device_get_nameunit(device_get_parent(dev));
720        /* String it all together. */
721        snprintf(data, 1024, "%s%s at %s %s on %s\n", type, what, loc, pnp,
722          parstr);
723        free(loc, M_BUS);
724        free(pnp, M_BUS);
725        devctl_queue_data(data);
726        return;
727bad:
728        free(pnp, M_BUS);
729        free(loc, M_BUS);
730        free(data, M_BUS);
731        return;
732}
733
734/*
735 * A device was added to the tree.  We are called just after it successfully
736 * attaches (that is, probe and attach success for this device).  No call
737 * is made if a device is merely parented into the tree.  See devnomatch
738 * if probe fails.  If attach fails, no notification is sent (but maybe
739 * we should have a different message for this).
740 */
741static void
742devadded(device_t dev)
743{
744        char *pnp = NULL;
745        char *tmp = NULL;
746
747        pnp = malloc(1024, M_BUS, M_NOWAIT);
748        if (pnp == NULL)
749                goto fail;
750        tmp = malloc(1024, M_BUS, M_NOWAIT);
751        if (tmp == NULL)
752                goto fail;
753        *pnp = '\0';
754        bus_child_pnpinfo_str(dev, pnp, 1024);
755        snprintf(tmp, 1024, "%s %s", device_get_nameunit(dev), pnp);
756        devaddq("+", tmp, dev);
757fail:
758        if (pnp != NULL)
759                free(pnp, M_BUS);
760        if (tmp != NULL)
761                free(tmp, M_BUS);
762        return;
763}
764
765/*
766 * A device was removed from the tree.  We are called just before this
767 * happens.
768 */
769static void
770devremoved(device_t dev)
771{
772        char *pnp = NULL;
773        char *tmp = NULL;
774
775        pnp = malloc(1024, M_BUS, M_NOWAIT);
776        if (pnp == NULL)
777                goto fail;
778        tmp = malloc(1024, M_BUS, M_NOWAIT);
779        if (tmp == NULL)
780                goto fail;
781        *pnp = '\0';
782        bus_child_pnpinfo_str(dev, pnp, 1024);
783        snprintf(tmp, 1024, "%s %s", device_get_nameunit(dev), pnp);
784        devaddq("-", tmp, dev);
785fail:
786        if (pnp != NULL)
787                free(pnp, M_BUS);
788        if (tmp != NULL)
789                free(tmp, M_BUS);
790        return;
791}
792
793/*
794 * Called when there's no match for this device.  This is only called
795 * the first time that no match happens, so we don't keep getting this
796 * message.  Should that prove to be undesirable, we can change it.
797 * This is called when all drivers that can attach to a given bus
798 * decline to accept this device.  Other errrors may not be detected.
799 */
800static void
801devnomatch(device_t dev)
802{
803        devaddq("?", "", dev);
804}
805
806#ifndef __rtems__
807static int
808sysctl_devctl_disable(SYSCTL_HANDLER_ARGS)
809{
810        struct dev_event_info *n1;
811        int dis, error;
812
813        dis = devctl_queue_length == 0;
814        error = sysctl_handle_int(oidp, &dis, 0, req);
815        if (error || !req->newptr)
816                return (error);
817        mtx_lock(&devsoftc.mtx);
818        if (dis) {
819                while (!TAILQ_EMPTY(&devsoftc.devq)) {
820                        n1 = TAILQ_FIRST(&devsoftc.devq);
821                        TAILQ_REMOVE(&devsoftc.devq, n1, dei_link);
822                        free(n1->dei_data, M_BUS);
823                        free(n1, M_BUS);
824                }
825                devsoftc.queued = 0;
826                devctl_queue_length = 0;
827        } else {
828                devctl_queue_length = DEVCTL_DEFAULT_QUEUE_LEN;
829        }
830        mtx_unlock(&devsoftc.mtx);
831        return (0);
832}
833
834static int
835sysctl_devctl_queue(SYSCTL_HANDLER_ARGS)
836{
837        struct dev_event_info *n1;
838        int q, error;
839
840        q = devctl_queue_length;
841        error = sysctl_handle_int(oidp, &q, 0, req);
842        if (error || !req->newptr)
843                return (error);
844        if (q < 0)
845                return (EINVAL);
846        mtx_lock(&devsoftc.mtx);
847        devctl_queue_length = q;
848        while (devsoftc.queued > devctl_queue_length) {
849                n1 = TAILQ_FIRST(&devsoftc.devq);
850                TAILQ_REMOVE(&devsoftc.devq, n1, dei_link);
851                free(n1->dei_data, M_BUS);
852                free(n1, M_BUS);
853                devsoftc.queued--;
854        }
855        mtx_unlock(&devsoftc.mtx);
856        return (0);
857}
858
859/* End of /dev/devctl code */
860#endif /* __rtems__ */
861
862static TAILQ_HEAD(,device)      bus_data_devices;
863static int bus_data_generation = 1;
864
865static kobj_method_t null_methods[] = {
866        KOBJMETHOD_END
867};
868
869DEFINE_CLASS(null, null_methods, 0);
870
871/*
872 * Bus pass implementation
873 */
874
875static driver_list_t passes = TAILQ_HEAD_INITIALIZER(passes);
876int bus_current_pass = BUS_PASS_ROOT;
877
878/**
879 * @internal
880 * @brief Register the pass level of a new driver attachment
881 *
882 * Register a new driver attachment's pass level.  If no driver
883 * attachment with the same pass level has been added, then @p new
884 * will be added to the global passes list.
885 *
886 * @param new           the new driver attachment
887 */
888static void
889driver_register_pass(struct driverlink *new)
890{
891        struct driverlink *dl;
892
893        /* We only consider pass numbers during boot. */
894        if (bus_current_pass == BUS_PASS_DEFAULT)
895                return;
896
897        /*
898         * Walk the passes list.  If we already know about this pass
899         * then there is nothing to do.  If we don't, then insert this
900         * driver link into the list.
901         */
902        TAILQ_FOREACH(dl, &passes, passlink) {
903                if (dl->pass < new->pass)
904                        continue;
905                if (dl->pass == new->pass)
906                        return;
907                TAILQ_INSERT_BEFORE(dl, new, passlink);
908                return;
909        }
910        TAILQ_INSERT_TAIL(&passes, new, passlink);
911}
912
913/**
914 * @brief Raise the current bus pass
915 *
916 * Raise the current bus pass level to @p pass.  Call the BUS_NEW_PASS()
917 * method on the root bus to kick off a new device tree scan for each
918 * new pass level that has at least one driver.
919 */
920void
921bus_set_pass(int pass)
922{
923        struct driverlink *dl;
924
925        if (bus_current_pass > pass)
926                panic("Attempt to lower bus pass level");
927
928        TAILQ_FOREACH(dl, &passes, passlink) {
929                /* Skip pass values below the current pass level. */
930                if (dl->pass <= bus_current_pass)
931                        continue;
932
933                /*
934                 * Bail once we hit a driver with a pass level that is
935                 * too high.
936                 */
937                if (dl->pass > pass)
938                        break;
939
940                /*
941                 * Raise the pass level to the next level and rescan
942                 * the tree.
943                 */
944                bus_current_pass = dl->pass;
945                BUS_NEW_PASS(root_bus);
946        }
947
948        /*
949         * If there isn't a driver registered for the requested pass,
950         * then bus_current_pass might still be less than 'pass'.  Set
951         * it to 'pass' in that case.
952         */
953        if (bus_current_pass < pass)
954                bus_current_pass = pass;
955        KASSERT(bus_current_pass == pass, ("Failed to update bus pass level"));
956}
957
958/*
959 * Devclass implementation
960 */
961
962static devclass_list_t devclasses = TAILQ_HEAD_INITIALIZER(devclasses);
963
964/**
965 * @internal
966 * @brief Find or create a device class
967 *
968 * If a device class with the name @p classname exists, return it,
969 * otherwise if @p create is non-zero create and return a new device
970 * class.
971 *
972 * If @p parentname is non-NULL, the parent of the devclass is set to
973 * the devclass of that name.
974 *
975 * @param classname     the devclass name to find or create
976 * @param parentname    the parent devclass name or @c NULL
977 * @param create        non-zero to create a devclass
978 */
979static devclass_t
980devclass_find_internal(const char *classname, const char *parentname,
981                       int create)
982{
983        devclass_t dc;
984
985        PDEBUG(("looking for %s", classname));
986        if (!classname)
987                return (NULL);
988
989        TAILQ_FOREACH(dc, &devclasses, link) {
990                if (!strcmp(dc->name, classname))
991                        break;
992        }
993
994        if (create && !dc) {
995                PDEBUG(("creating %s", classname));
996                dc = malloc(sizeof(struct devclass) + strlen(classname) + 1,
997                    M_BUS, M_NOWAIT | M_ZERO);
998                if (!dc)
999                        return (NULL);
1000                dc->parent = NULL;
1001                dc->name = (char*) (dc + 1);
1002                strcpy(dc->name, classname);
1003                TAILQ_INIT(&dc->drivers);
1004                TAILQ_INSERT_TAIL(&devclasses, dc, link);
1005
1006                bus_data_generation_update();
1007        }
1008
1009        /*
1010         * If a parent class is specified, then set that as our parent so
1011         * that this devclass will support drivers for the parent class as
1012         * well.  If the parent class has the same name don't do this though
1013         * as it creates a cycle that can trigger an infinite loop in
1014         * device_probe_child() if a device exists for which there is no
1015         * suitable driver.
1016         */
1017        if (parentname && dc && !dc->parent &&
1018            strcmp(classname, parentname) != 0) {
1019                dc->parent = devclass_find_internal(parentname, NULL, TRUE);
1020                dc->parent->flags |= DC_HAS_CHILDREN;
1021        }
1022
1023        return (dc);
1024}
1025
1026/**
1027 * @brief Create a device class
1028 *
1029 * If a device class with the name @p classname exists, return it,
1030 * otherwise create and return a new device class.
1031 *
1032 * @param classname     the devclass name to find or create
1033 */
1034devclass_t
1035devclass_create(const char *classname)
1036{
1037        return (devclass_find_internal(classname, NULL, TRUE));
1038}
1039
1040/**
1041 * @brief Find a device class
1042 *
1043 * If a device class with the name @p classname exists, return it,
1044 * otherwise return @c NULL.
1045 *
1046 * @param classname     the devclass name to find
1047 */
1048devclass_t
1049devclass_find(const char *classname)
1050{
1051        return (devclass_find_internal(classname, NULL, FALSE));
1052}
1053
1054/**
1055 * @brief Register that a device driver has been added to a devclass
1056 *
1057 * Register that a device driver has been added to a devclass.  This
1058 * is called by devclass_add_driver to accomplish the recursive
1059 * notification of all the children classes of dc, as well as dc.
1060 * Each layer will have BUS_DRIVER_ADDED() called for all instances of
1061 * the devclass.
1062 *
1063 * We do a full search here of the devclass list at each iteration
1064 * level to save storing children-lists in the devclass structure.  If
1065 * we ever move beyond a few dozen devices doing this, we may need to
1066 * reevaluate...
1067 *
1068 * @param dc            the devclass to edit
1069 * @param driver        the driver that was just added
1070 */
1071static void
1072devclass_driver_added(devclass_t dc, driver_t *driver)
1073{
1074        devclass_t parent;
1075        int i;
1076
1077        /*
1078         * Call BUS_DRIVER_ADDED for any existing busses in this class.
1079         */
1080        for (i = 0; i < dc->maxunit; i++)
1081                if (dc->devices[i] && device_is_attached(dc->devices[i]))
1082                        BUS_DRIVER_ADDED(dc->devices[i], driver);
1083
1084        /*
1085         * Walk through the children classes.  Since we only keep a
1086         * single parent pointer around, we walk the entire list of
1087         * devclasses looking for children.  We set the
1088         * DC_HAS_CHILDREN flag when a child devclass is created on
1089         * the parent, so we only walk the list for those devclasses
1090         * that have children.
1091         */
1092        if (!(dc->flags & DC_HAS_CHILDREN))
1093                return;
1094        parent = dc;
1095        TAILQ_FOREACH(dc, &devclasses, link) {
1096                if (dc->parent == parent)
1097                        devclass_driver_added(dc, driver);
1098        }
1099}
1100
1101/**
1102 * @brief Add a device driver to a device class
1103 *
1104 * Add a device driver to a devclass. This is normally called
1105 * automatically by DRIVER_MODULE(). The BUS_DRIVER_ADDED() method of
1106 * all devices in the devclass will be called to allow them to attempt
1107 * to re-probe any unmatched children.
1108 *
1109 * @param dc            the devclass to edit
1110 * @param driver        the driver to register
1111 */
1112static int
1113devclass_add_driver(devclass_t dc, driver_t *driver, int pass, devclass_t *dcp)
1114{
1115        driverlink_t dl;
1116        const char *parentname;
1117
1118        PDEBUG(("%s", DRIVERNAME(driver)));
1119
1120        /* Don't allow invalid pass values. */
1121        if (pass <= BUS_PASS_ROOT)
1122                return (EINVAL);
1123
1124        dl = malloc(sizeof *dl, M_BUS, M_NOWAIT|M_ZERO);
1125        if (!dl)
1126                return (ENOMEM);
1127
1128        /*
1129         * Compile the driver's methods. Also increase the reference count
1130         * so that the class doesn't get freed when the last instance
1131         * goes. This means we can safely use static methods and avoids a
1132         * double-free in devclass_delete_driver.
1133         */
1134        kobj_class_compile((kobj_class_t) driver);
1135
1136        /*
1137         * If the driver has any base classes, make the
1138         * devclass inherit from the devclass of the driver's
1139         * first base class. This will allow the system to
1140         * search for drivers in both devclasses for children
1141         * of a device using this driver.
1142         */
1143        if (driver->baseclasses)
1144                parentname = driver->baseclasses[0]->name;
1145        else
1146                parentname = NULL;
1147        *dcp = devclass_find_internal(driver->name, parentname, TRUE);
1148
1149        dl->driver = driver;
1150        TAILQ_INSERT_TAIL(&dc->drivers, dl, link);
1151        driver->refs++;         /* XXX: kobj_mtx */
1152        dl->pass = pass;
1153        driver_register_pass(dl);
1154
1155        devclass_driver_added(dc, driver);
1156        bus_data_generation_update();
1157        return (0);
1158}
1159
1160/**
1161 * @brief Register that a device driver has been deleted from a devclass
1162 *
1163 * Register that a device driver has been removed from a devclass.
1164 * This is called by devclass_delete_driver to accomplish the
1165 * recursive notification of all the children classes of busclass, as
1166 * well as busclass.  Each layer will attempt to detach the driver
1167 * from any devices that are children of the bus's devclass.  The function
1168 * will return an error if a device fails to detach.
1169 *
1170 * We do a full search here of the devclass list at each iteration
1171 * level to save storing children-lists in the devclass structure.  If
1172 * we ever move beyond a few dozen devices doing this, we may need to
1173 * reevaluate...
1174 *
1175 * @param busclass      the devclass of the parent bus
1176 * @param dc            the devclass of the driver being deleted
1177 * @param driver        the driver being deleted
1178 */
1179static int
1180devclass_driver_deleted(devclass_t busclass, devclass_t dc, driver_t *driver)
1181{
1182        devclass_t parent;
1183        device_t dev;
1184        int error, i;
1185
1186        /*
1187         * Disassociate from any devices.  We iterate through all the
1188         * devices in the devclass of the driver and detach any which are
1189         * using the driver and which have a parent in the devclass which
1190         * we are deleting from.
1191         *
1192         * Note that since a driver can be in multiple devclasses, we
1193         * should not detach devices which are not children of devices in
1194         * the affected devclass.
1195         */
1196        for (i = 0; i < dc->maxunit; i++) {
1197                if (dc->devices[i]) {
1198                        dev = dc->devices[i];
1199                        if (dev->driver == driver && dev->parent &&
1200                            dev->parent->devclass == busclass) {
1201                                if ((error = device_detach(dev)) != 0)
1202                                        return (error);
1203                                BUS_PROBE_NOMATCH(dev->parent, dev);
1204                                devnomatch(dev);
1205                                dev->flags |= DF_DONENOMATCH;
1206                        }
1207                }
1208        }
1209
1210        /*
1211         * Walk through the children classes.  Since we only keep a
1212         * single parent pointer around, we walk the entire list of
1213         * devclasses looking for children.  We set the
1214         * DC_HAS_CHILDREN flag when a child devclass is created on
1215         * the parent, so we only walk the list for those devclasses
1216         * that have children.
1217         */
1218        if (!(busclass->flags & DC_HAS_CHILDREN))
1219                return (0);
1220        parent = busclass;
1221        TAILQ_FOREACH(busclass, &devclasses, link) {
1222                if (busclass->parent == parent) {
1223                        error = devclass_driver_deleted(busclass, dc, driver);
1224                        if (error)
1225                                return (error);
1226                }
1227        }
1228        return (0);
1229}
1230
1231/**
1232 * @brief Delete a device driver from a device class
1233 *
1234 * Delete a device driver from a devclass. This is normally called
1235 * automatically by DRIVER_MODULE().
1236 *
1237 * If the driver is currently attached to any devices,
1238 * devclass_delete_driver() will first attempt to detach from each
1239 * device. If one of the detach calls fails, the driver will not be
1240 * deleted.
1241 *
1242 * @param dc            the devclass to edit
1243 * @param driver        the driver to unregister
1244 */
1245static int
1246devclass_delete_driver(devclass_t busclass, driver_t *driver)
1247{
1248        devclass_t dc = devclass_find(driver->name);
1249        driverlink_t dl;
1250        int error;
1251
1252        PDEBUG(("%s from devclass %s", driver->name, DEVCLANAME(busclass)));
1253
1254        if (!dc)
1255                return (0);
1256
1257        /*
1258         * Find the link structure in the bus' list of drivers.
1259         */
1260        TAILQ_FOREACH(dl, &busclass->drivers, link) {
1261                if (dl->driver == driver)
1262                        break;
1263        }
1264
1265        if (!dl) {
1266                PDEBUG(("%s not found in %s list", driver->name,
1267                    busclass->name));
1268                return (ENOENT);
1269        }
1270
1271        error = devclass_driver_deleted(busclass, dc, driver);
1272        if (error != 0)
1273                return (error);
1274
1275        TAILQ_REMOVE(&busclass->drivers, dl, link);
1276        free(dl, M_BUS);
1277
1278        /* XXX: kobj_mtx */
1279        driver->refs--;
1280        if (driver->refs == 0)
1281                kobj_class_free((kobj_class_t) driver);
1282
1283        bus_data_generation_update();
1284        return (0);
1285}
1286
1287/**
1288 * @brief Quiesces a set of device drivers from a device class
1289 *
1290 * Quiesce a device driver from a devclass. This is normally called
1291 * automatically by DRIVER_MODULE().
1292 *
1293 * If the driver is currently attached to any devices,
1294 * devclass_quiesece_driver() will first attempt to quiesce each
1295 * device.
1296 *
1297 * @param dc            the devclass to edit
1298 * @param driver        the driver to unregister
1299 */
1300static int
1301devclass_quiesce_driver(devclass_t busclass, driver_t *driver)
1302{
1303        devclass_t dc = devclass_find(driver->name);
1304        driverlink_t dl;
1305        device_t dev;
1306        int i;
1307        int error;
1308
1309        PDEBUG(("%s from devclass %s", driver->name, DEVCLANAME(busclass)));
1310
1311        if (!dc)
1312                return (0);
1313
1314        /*
1315         * Find the link structure in the bus' list of drivers.
1316         */
1317        TAILQ_FOREACH(dl, &busclass->drivers, link) {
1318                if (dl->driver == driver)
1319                        break;
1320        }
1321
1322        if (!dl) {
1323                PDEBUG(("%s not found in %s list", driver->name,
1324                    busclass->name));
1325                return (ENOENT);
1326        }
1327
1328        /*
1329         * Quiesce all devices.  We iterate through all the devices in
1330         * the devclass of the driver and quiesce any which are using
1331         * the driver and which have a parent in the devclass which we
1332         * are quiescing.
1333         *
1334         * Note that since a driver can be in multiple devclasses, we
1335         * should not quiesce devices which are not children of
1336         * devices in the affected devclass.
1337         */
1338        for (i = 0; i < dc->maxunit; i++) {
1339                if (dc->devices[i]) {
1340                        dev = dc->devices[i];
1341                        if (dev->driver == driver && dev->parent &&
1342                            dev->parent->devclass == busclass) {
1343                                if ((error = device_quiesce(dev)) != 0)
1344                                        return (error);
1345                        }
1346                }
1347        }
1348
1349        return (0);
1350}
1351
1352/**
1353 * @internal
1354 */
1355static driverlink_t
1356devclass_find_driver_internal(devclass_t dc, const char *classname)
1357{
1358        driverlink_t dl;
1359
1360        PDEBUG(("%s in devclass %s", classname, DEVCLANAME(dc)));
1361
1362        TAILQ_FOREACH(dl, &dc->drivers, link) {
1363                if (!strcmp(dl->driver->name, classname))
1364                        return (dl);
1365        }
1366
1367        PDEBUG(("not found"));
1368        return (NULL);
1369}
1370
1371/**
1372 * @brief Return the name of the devclass
1373 */
1374const char *
1375devclass_get_name(devclass_t dc)
1376{
1377        return (dc->name);
1378}
1379
1380/**
1381 * @brief Find a device given a unit number
1382 *
1383 * @param dc            the devclass to search
1384 * @param unit          the unit number to search for
1385 *
1386 * @returns             the device with the given unit number or @c
1387 *                      NULL if there is no such device
1388 */
1389device_t
1390devclass_get_device(devclass_t dc, int unit)
1391{
1392        if (dc == NULL || unit < 0 || unit >= dc->maxunit)
1393                return (NULL);
1394        return (dc->devices[unit]);
1395}
1396
1397/**
1398 * @brief Find the softc field of a device given a unit number
1399 *
1400 * @param dc            the devclass to search
1401 * @param unit          the unit number to search for
1402 *
1403 * @returns             the softc field of the device with the given
1404 *                      unit number or @c NULL if there is no such
1405 *                      device
1406 */
1407void *
1408devclass_get_softc(devclass_t dc, int unit)
1409{
1410        device_t dev;
1411
1412        dev = devclass_get_device(dc, unit);
1413        if (!dev)
1414                return (NULL);
1415
1416        return (device_get_softc(dev));
1417}
1418
1419/**
1420 * @brief Get a list of devices in the devclass
1421 *
1422 * An array containing a list of all the devices in the given devclass
1423 * is allocated and returned in @p *devlistp. The number of devices
1424 * in the array is returned in @p *devcountp. The caller should free
1425 * the array using @c free(p, M_TEMP), even if @p *devcountp is 0.
1426 *
1427 * @param dc            the devclass to examine
1428 * @param devlistp      points at location for array pointer return
1429 *                      value
1430 * @param devcountp     points at location for array size return value
1431 *
1432 * @retval 0            success
1433 * @retval ENOMEM       the array allocation failed
1434 */
1435int
1436devclass_get_devices(devclass_t dc, device_t **devlistp, int *devcountp)
1437{
1438        int count, i;
1439        device_t *list;
1440
1441        count = devclass_get_count(dc);
1442        list = malloc(count * sizeof(device_t), M_TEMP, M_NOWAIT|M_ZERO);
1443        if (!list)
1444                return (ENOMEM);
1445
1446        count = 0;
1447        for (i = 0; i < dc->maxunit; i++) {
1448                if (dc->devices[i]) {
1449                        list[count] = dc->devices[i];
1450                        count++;
1451                }
1452        }
1453
1454        *devlistp = list;
1455        *devcountp = count;
1456
1457        return (0);
1458}
1459
1460/**
1461 * @brief Get a list of drivers in the devclass
1462 *
1463 * An array containing a list of pointers to all the drivers in the
1464 * given devclass is allocated and returned in @p *listp.  The number
1465 * of drivers in the array is returned in @p *countp. The caller should
1466 * free the array using @c free(p, M_TEMP).
1467 *
1468 * @param dc            the devclass to examine
1469 * @param listp         gives location for array pointer return value
1470 * @param countp        gives location for number of array elements
1471 *                      return value
1472 *
1473 * @retval 0            success
1474 * @retval ENOMEM       the array allocation failed
1475 */
1476int
1477devclass_get_drivers(devclass_t dc, driver_t ***listp, int *countp)
1478{
1479        driverlink_t dl;
1480        driver_t **list;
1481        int count;
1482
1483        count = 0;
1484        TAILQ_FOREACH(dl, &dc->drivers, link)
1485                count++;
1486        list = malloc(count * sizeof(driver_t *), M_TEMP, M_NOWAIT);
1487        if (list == NULL)
1488                return (ENOMEM);
1489
1490        count = 0;
1491        TAILQ_FOREACH(dl, &dc->drivers, link) {
1492                list[count] = dl->driver;
1493                count++;
1494        }
1495        *listp = list;
1496        *countp = count;
1497
1498        return (0);
1499}
1500
1501/**
1502 * @brief Get the number of devices in a devclass
1503 *
1504 * @param dc            the devclass to examine
1505 */
1506int
1507devclass_get_count(devclass_t dc)
1508{
1509        int count, i;
1510
1511        count = 0;
1512        for (i = 0; i < dc->maxunit; i++)
1513                if (dc->devices[i])
1514                        count++;
1515        return (count);
1516}
1517
1518/**
1519 * @brief Get the maximum unit number used in a devclass
1520 *
1521 * Note that this is one greater than the highest currently-allocated
1522 * unit.  If a null devclass_t is passed in, -1 is returned to indicate
1523 * that not even the devclass has been allocated yet.
1524 *
1525 * @param dc            the devclass to examine
1526 */
1527int
1528devclass_get_maxunit(devclass_t dc)
1529{
1530        if (dc == NULL)
1531                return (-1);
1532        return (dc->maxunit);
1533}
1534
1535/**
1536 * @brief Find a free unit number in a devclass
1537 *
1538 * This function searches for the first unused unit number greater
1539 * that or equal to @p unit.
1540 *
1541 * @param dc            the devclass to examine
1542 * @param unit          the first unit number to check
1543 */
1544int
1545devclass_find_free_unit(devclass_t dc, int unit)
1546{
1547        if (dc == NULL)
1548                return (unit);
1549        while (unit < dc->maxunit && dc->devices[unit] != NULL)
1550                unit++;
1551        return (unit);
1552}
1553
1554/**
1555 * @brief Set the parent of a devclass
1556 *
1557 * The parent class is normally initialised automatically by
1558 * DRIVER_MODULE().
1559 *
1560 * @param dc            the devclass to edit
1561 * @param pdc           the new parent devclass
1562 */
1563void
1564devclass_set_parent(devclass_t dc, devclass_t pdc)
1565{
1566        dc->parent = pdc;
1567}
1568
1569/**
1570 * @brief Get the parent of a devclass
1571 *
1572 * @param dc            the devclass to examine
1573 */
1574devclass_t
1575devclass_get_parent(devclass_t dc)
1576{
1577        return (dc->parent);
1578}
1579
1580struct sysctl_ctx_list *
1581devclass_get_sysctl_ctx(devclass_t dc)
1582{
1583#ifndef __rtems__
1584        return (&dc->sysctl_ctx);
1585#else /* __rtems__ */
1586        return (NULL);
1587#endif /* __rtems__ */
1588}
1589
1590struct sysctl_oid *
1591devclass_get_sysctl_tree(devclass_t dc)
1592{
1593#ifndef __rtems__
1594        return (dc->sysctl_tree);
1595#else /* __rtems__ */
1596        return (NULL);
1597#endif /* __rtems__ */
1598}
1599
1600/**
1601 * @internal
1602 * @brief Allocate a unit number
1603 *
1604 * On entry, @p *unitp is the desired unit number (or @c -1 if any
1605 * will do). The allocated unit number is returned in @p *unitp.
1606
1607 * @param dc            the devclass to allocate from
1608 * @param unitp         points at the location for the allocated unit
1609 *                      number
1610 *
1611 * @retval 0            success
1612 * @retval EEXIST       the requested unit number is already allocated
1613 * @retval ENOMEM       memory allocation failure
1614 */
1615static int
1616devclass_alloc_unit(devclass_t dc, device_t dev, int *unitp)
1617{
1618        const char *s;
1619        int unit = *unitp;
1620
1621        PDEBUG(("unit %d in devclass %s", unit, DEVCLANAME(dc)));
1622
1623        /* Ask the parent bus if it wants to wire this device. */
1624        if (unit == -1)
1625                BUS_HINT_DEVICE_UNIT(device_get_parent(dev), dev, dc->name,
1626                    &unit);
1627
1628        /* If we were given a wired unit number, check for existing device */
1629        /* XXX imp XXX */
1630        if (unit != -1) {
1631                if (unit >= 0 && unit < dc->maxunit &&
1632                    dc->devices[unit] != NULL) {
1633                        if (bootverbose)
1634                                printf("%s: %s%d already exists; skipping it\n",
1635                                    dc->name, dc->name, *unitp);
1636                        return (EEXIST);
1637                }
1638        } else {
1639                /* Unwired device, find the next available slot for it */
1640                unit = 0;
1641                for (unit = 0;; unit++) {
1642#ifndef __rtems__
1643                        /* If there is an "at" hint for a unit then skip it. */
1644                        if (resource_string_value(dc->name, unit, "at", &s) ==
1645                            0)
1646                                continue;
1647#endif /* __rtems__ */
1648
1649                        /* If this device slot is already in use, skip it. */
1650                        if (unit < dc->maxunit && dc->devices[unit] != NULL)
1651                                continue;
1652
1653                        break;
1654                }
1655        }
1656
1657        /*
1658         * We've selected a unit beyond the length of the table, so let's
1659         * extend the table to make room for all units up to and including
1660         * this one.
1661         */
1662        if (unit >= dc->maxunit) {
1663                device_t *newlist, *oldlist;
1664                int newsize;
1665
1666                oldlist = dc->devices;
1667                newsize = roundup((unit + 1), MINALLOCSIZE / sizeof(device_t));
1668                newlist = malloc(sizeof(device_t) * newsize, M_BUS, M_NOWAIT);
1669                if (!newlist)
1670                        return (ENOMEM);
1671                if (oldlist != NULL)
1672                        bcopy(oldlist, newlist, sizeof(device_t) * dc->maxunit);
1673                bzero(newlist + dc->maxunit,
1674                    sizeof(device_t) * (newsize - dc->maxunit));
1675                dc->devices = newlist;
1676                dc->maxunit = newsize;
1677                if (oldlist != NULL)
1678                        free(oldlist, M_BUS);
1679        }
1680        PDEBUG(("now: unit %d in devclass %s", unit, DEVCLANAME(dc)));
1681
1682        *unitp = unit;
1683        return (0);
1684}
1685
1686/**
1687 * @internal
1688 * @brief Add a device to a devclass
1689 *
1690 * A unit number is allocated for the device (using the device's
1691 * preferred unit number if any) and the device is registered in the
1692 * devclass. This allows the device to be looked up by its unit
1693 * number, e.g. by decoding a dev_t minor number.
1694 *
1695 * @param dc            the devclass to add to
1696 * @param dev           the device to add
1697 *
1698 * @retval 0            success
1699 * @retval EEXIST       the requested unit number is already allocated
1700 * @retval ENOMEM       memory allocation failure
1701 */
1702static int
1703devclass_add_device(devclass_t dc, device_t dev)
1704{
1705        int buflen, error;
1706
1707        PDEBUG(("%s in devclass %s", DEVICENAME(dev), DEVCLANAME(dc)));
1708
1709        buflen = snprintf(NULL, 0, "%s%d$", dc->name, INT_MAX);
1710        if (buflen < 0)
1711                return (ENOMEM);
1712        dev->nameunit = malloc(buflen, M_BUS, M_NOWAIT|M_ZERO);
1713        if (!dev->nameunit)
1714                return (ENOMEM);
1715
1716        if ((error = devclass_alloc_unit(dc, dev, &dev->unit)) != 0) {
1717                free(dev->nameunit, M_BUS);
1718                dev->nameunit = NULL;
1719                return (error);
1720        }
1721        dc->devices[dev->unit] = dev;
1722        dev->devclass = dc;
1723        snprintf(dev->nameunit, buflen, "%s%d", dc->name, dev->unit);
1724
1725        return (0);
1726}
1727
1728/**
1729 * @internal
1730 * @brief Delete a device from a devclass
1731 *
1732 * The device is removed from the devclass's device list and its unit
1733 * number is freed.
1734
1735 * @param dc            the devclass to delete from
1736 * @param dev           the device to delete
1737 *
1738 * @retval 0            success
1739 */
1740static int
1741devclass_delete_device(devclass_t dc, device_t dev)
1742{
1743        if (!dc || !dev)
1744                return (0);
1745
1746        PDEBUG(("%s in devclass %s", DEVICENAME(dev), DEVCLANAME(dc)));
1747
1748        if (dev->devclass != dc || dc->devices[dev->unit] != dev)
1749                panic("devclass_delete_device: inconsistent device class");
1750        dc->devices[dev->unit] = NULL;
1751        if (dev->flags & DF_WILDCARD)
1752                dev->unit = -1;
1753        dev->devclass = NULL;
1754        free(dev->nameunit, M_BUS);
1755        dev->nameunit = NULL;
1756
1757        return (0);
1758}
1759
1760/**
1761 * @internal
1762 * @brief Make a new device and add it as a child of @p parent
1763 *
1764 * @param parent        the parent of the new device
1765 * @param name          the devclass name of the new device or @c NULL
1766 *                      to leave the devclass unspecified
1767 * @parem unit          the unit number of the new device of @c -1 to
1768 *                      leave the unit number unspecified
1769 *
1770 * @returns the new device
1771 */
1772static device_t
1773make_device(device_t parent, const char *name, int unit)
1774{
1775        device_t dev;
1776        devclass_t dc;
1777
1778        PDEBUG(("%s at %s as unit %d", name, DEVICENAME(parent), unit));
1779
1780        if (name) {
1781                dc = devclass_find_internal(name, NULL, TRUE);
1782                if (!dc) {
1783                        printf("make_device: can't find device class %s\n",
1784                            name);
1785                        return (NULL);
1786                }
1787        } else {
1788                dc = NULL;
1789        }
1790
1791        dev = malloc(sizeof(struct device), M_BUS, M_NOWAIT|M_ZERO);
1792        if (!dev)
1793                return (NULL);
1794
1795        dev->parent = parent;
1796        TAILQ_INIT(&dev->children);
1797        kobj_init((kobj_t) dev, &null_class);
1798        dev->driver = NULL;
1799        dev->devclass = NULL;
1800        dev->unit = unit;
1801        dev->nameunit = NULL;
1802        dev->desc = NULL;
1803        dev->busy = 0;
1804        dev->devflags = 0;
1805        dev->flags = DF_ENABLED;
1806        dev->order = 0;
1807        if (unit == -1)
1808                dev->flags |= DF_WILDCARD;
1809        if (name) {
1810                dev->flags |= DF_FIXEDCLASS;
1811                if (devclass_add_device(dc, dev)) {
1812                        kobj_delete((kobj_t) dev, M_BUS);
1813                        return (NULL);
1814                }
1815        }
1816        dev->ivars = NULL;
1817        dev->softc = NULL;
1818
1819        dev->state = DS_NOTPRESENT;
1820
1821        TAILQ_INSERT_TAIL(&bus_data_devices, dev, devlink);
1822        bus_data_generation_update();
1823
1824        return (dev);
1825}
1826
1827/**
1828 * @internal
1829 * @brief Print a description of a device.
1830 */
1831static int
1832device_print_child(device_t dev, device_t child)
1833{
1834        int retval = 0;
1835
1836        if (device_is_alive(child))
1837                retval += BUS_PRINT_CHILD(dev, child);
1838        else
1839                retval += device_printf(child, " not found\n");
1840
1841        return (retval);
1842}
1843
1844/**
1845 * @brief Create a new device
1846 *
1847 * This creates a new device and adds it as a child of an existing
1848 * parent device. The new device will be added after the last existing
1849 * child with order zero.
1850 *
1851 * @param dev           the device which will be the parent of the
1852 *                      new child device
1853 * @param name          devclass name for new device or @c NULL if not
1854 *                      specified
1855 * @param unit          unit number for new device or @c -1 if not
1856 *                      specified
1857 *
1858 * @returns             the new device
1859 */
1860device_t
1861device_add_child(device_t dev, const char *name, int unit)
1862{
1863        return (device_add_child_ordered(dev, 0, name, unit));
1864}
1865
1866/**
1867 * @brief Create a new device
1868 *
1869 * This creates a new device and adds it as a child of an existing
1870 * parent device. The new device will be added after the last existing
1871 * child with the same order.
1872 *
1873 * @param dev           the device which will be the parent of the
1874 *                      new child device
1875 * @param order         a value which is used to partially sort the
1876 *                      children of @p dev - devices created using
1877 *                      lower values of @p order appear first in @p
1878 *                      dev's list of children
1879 * @param name          devclass name for new device or @c NULL if not
1880 *                      specified
1881 * @param unit          unit number for new device or @c -1 if not
1882 *                      specified
1883 *
1884 * @returns             the new device
1885 */
1886device_t
1887device_add_child_ordered(device_t dev, u_int order, const char *name, int unit)
1888{
1889        device_t child;
1890        device_t place;
1891
1892        PDEBUG(("%s at %s with order %u as unit %d",
1893            name, DEVICENAME(dev), order, unit));
1894
1895        child = make_device(dev, name, unit);
1896        if (child == NULL)
1897                return (child);
1898        child->order = order;
1899
1900        TAILQ_FOREACH(place, &dev->children, link) {
1901                if (place->order > order)
1902                        break;
1903        }
1904
1905        if (place) {
1906                /*
1907                 * The device 'place' is the first device whose order is
1908                 * greater than the new child.
1909                 */
1910                TAILQ_INSERT_BEFORE(place, child, link);
1911        } else {
1912                /*
1913                 * The new child's order is greater or equal to the order of
1914                 * any existing device. Add the child to the tail of the list.
1915                 */
1916                TAILQ_INSERT_TAIL(&dev->children, child, link);
1917        }
1918
1919        bus_data_generation_update();
1920        return (child);
1921}
1922
1923/**
1924 * @brief Delete a device
1925 *
1926 * This function deletes a device along with all of its children. If
1927 * the device currently has a driver attached to it, the device is
1928 * detached first using device_detach().
1929 *
1930 * @param dev           the parent device
1931 * @param child         the device to delete
1932 *
1933 * @retval 0            success
1934 * @retval non-zero     a unit error code describing the error
1935 */
1936int
1937device_delete_child(device_t dev, device_t child)
1938{
1939        int error;
1940        device_t grandchild;
1941
1942        PDEBUG(("%s from %s", DEVICENAME(child), DEVICENAME(dev)));
1943
1944        /* remove children first */
1945        while ((grandchild = TAILQ_FIRST(&child->children)) != NULL) {
1946                error = device_delete_child(child, grandchild);
1947                if (error)
1948                        return (error);
1949        }
1950
1951        if ((error = device_detach(child)) != 0)
1952                return (error);
1953        if (child->devclass)
1954                devclass_delete_device(child->devclass, child);
1955        TAILQ_REMOVE(&dev->children, child, link);
1956        TAILQ_REMOVE(&bus_data_devices, child, devlink);
1957        kobj_delete((kobj_t) child, M_BUS);
1958
1959        bus_data_generation_update();
1960        return (0);
1961}
1962
1963/**
1964 * @brief Delete all children devices of the given device, if any.
1965 *
1966 * This function deletes all children devices of the given device, if
1967 * any, using the device_delete_child() function for each device it
1968 * finds. If a child device cannot be deleted, this function will
1969 * return an error code.
1970 *
1971 * @param dev           the parent device
1972 *
1973 * @retval 0            success
1974 * @retval non-zero     a device would not detach
1975 */
1976int
1977device_delete_children(device_t dev)
1978{
1979        device_t child;
1980        int error;
1981
1982        PDEBUG(("Deleting all children of %s", DEVICENAME(dev)));
1983
1984        error = 0;
1985
1986        while ((child = TAILQ_FIRST(&dev->children)) != NULL) {
1987                error = device_delete_child(dev, child);
1988                if (error) {
1989                        PDEBUG(("Failed deleting %s", DEVICENAME(child)));
1990                        break;
1991                }
1992        }
1993        return (error);
1994}
1995
1996/**
1997 * @brief Find a device given a unit number
1998 *
1999 * This is similar to devclass_get_devices() but only searches for
2000 * devices which have @p dev as a parent.
2001 *
2002 * @param dev           the parent device to search
2003 * @param unit          the unit number to search for.  If the unit is -1,
2004 *                      return the first child of @p dev which has name
2005 *                      @p classname (that is, the one with the lowest unit.)
2006 *
2007 * @returns             the device with the given unit number or @c
2008 *                      NULL if there is no such device
2009 */
2010device_t
2011device_find_child(device_t dev, const char *classname, int unit)
2012{
2013        devclass_t dc;
2014        device_t child;
2015
2016        dc = devclass_find(classname);
2017        if (!dc)
2018                return (NULL);
2019
2020        if (unit != -1) {
2021                child = devclass_get_device(dc, unit);
2022                if (child && child->parent == dev)
2023                        return (child);
2024        } else {
2025                for (unit = 0; unit < devclass_get_maxunit(dc); unit++) {
2026                        child = devclass_get_device(dc, unit);
2027                        if (child && child->parent == dev)
2028                                return (child);
2029                }
2030        }
2031        return (NULL);
2032}
2033
2034/**
2035 * @internal
2036 */
2037static driverlink_t
2038first_matching_driver(devclass_t dc, device_t dev)
2039{
2040        if (dev->devclass)
2041                return (devclass_find_driver_internal(dc, dev->devclass->name));
2042        return (TAILQ_FIRST(&dc->drivers));
2043}
2044
2045/**
2046 * @internal
2047 */
2048static driverlink_t
2049next_matching_driver(devclass_t dc, device_t dev, driverlink_t last)
2050{
2051        if (dev->devclass) {
2052                driverlink_t dl;
2053                for (dl = TAILQ_NEXT(last, link); dl; dl = TAILQ_NEXT(dl, link))
2054                        if (!strcmp(dev->devclass->name, dl->driver->name))
2055                                return (dl);
2056                return (NULL);
2057        }
2058        return (TAILQ_NEXT(last, link));
2059}
2060
2061/**
2062 * @internal
2063 */
2064int
2065device_probe_child(device_t dev, device_t child)
2066{
2067        devclass_t dc;
2068        driverlink_t best = NULL;
2069        driverlink_t dl;
2070        int result, pri = 0;
2071        int hasclass = (child->devclass != NULL);
2072
2073        GIANT_REQUIRED;
2074
2075        dc = dev->devclass;
2076        if (!dc)
2077                panic("device_probe_child: parent device has no devclass");
2078
2079        /*
2080         * If the state is already probed, then return.  However, don't
2081         * return if we can rebid this object.
2082         */
2083        if (child->state == DS_ALIVE && (child->flags & DF_REBID) == 0)
2084                return (0);
2085
2086        for (; dc; dc = dc->parent) {
2087                for (dl = first_matching_driver(dc, child);
2088                     dl;
2089                     dl = next_matching_driver(dc, child, dl)) {
2090                        /* If this driver's pass is too high, then ignore it. */
2091                        if (dl->pass > bus_current_pass)
2092                                continue;
2093
2094                        PDEBUG(("Trying %s", DRIVERNAME(dl->driver)));
2095                        result = device_set_driver(child, dl->driver);
2096                        if (result == ENOMEM)
2097                                return (result);
2098                        else if (result != 0)
2099                                continue;
2100                        if (!hasclass) {
2101                                if (device_set_devclass(child,
2102                                    dl->driver->name) != 0) {
2103                                        printf("driver bug: Unable to set "
2104                                            "devclass (devname: %s)\n",
2105                                            device_get_name(child));
2106                                        (void)device_set_driver(child, NULL);
2107                                        continue;
2108                                }
2109                        }
2110
2111#ifndef __rtems__
2112                        /* Fetch any flags for the device before probing. */
2113                        resource_int_value(dl->driver->name, child->unit,
2114                            "flags", &child->devflags);
2115#endif /* __rtems__ */
2116
2117                        result = DEVICE_PROBE(child);
2118
2119                        /* Reset flags and devclass before the next probe. */
2120                        child->devflags = 0;
2121                        if (!hasclass)
2122                                (void)device_set_devclass(child, NULL);
2123
2124                        /*
2125                         * If the driver returns SUCCESS, there can be
2126                         * no higher match for this device.
2127                         */
2128                        if (result == 0) {
2129                                best = dl;
2130                                pri = 0;
2131                                break;
2132                        }
2133
2134                        /*
2135                         * The driver returned an error so it
2136                         * certainly doesn't match.
2137                         */
2138                        if (result > 0) {
2139                                (void)device_set_driver(child, NULL);
2140                                continue;
2141                        }
2142
2143                        /*
2144                         * A priority lower than SUCCESS, remember the
2145                         * best matching driver. Initialise the value
2146                         * of pri for the first match.
2147                         */
2148                        if (best == NULL || result > pri) {
2149                                /*
2150                                 * Probes that return BUS_PROBE_NOWILDCARD
2151                                 * or lower only match when they are set
2152                                 * in stone by the parent bus.
2153                                 */
2154                                if (result <= BUS_PROBE_NOWILDCARD &&
2155                                    child->flags & DF_WILDCARD)
2156                                        continue;
2157                                best = dl;
2158                                pri = result;
2159                                continue;
2160                        }
2161                }
2162                /*
2163                 * If we have an unambiguous match in this devclass,
2164                 * don't look in the parent.
2165                 */
2166                if (best && pri == 0)
2167                        break;
2168        }
2169
2170        /*
2171         * If we found a driver, change state and initialise the devclass.
2172         */
2173        /* XXX What happens if we rebid and got no best? */
2174        if (best) {
2175                /*
2176                 * If this device was attached, and we were asked to
2177                 * rescan, and it is a different driver, then we have
2178                 * to detach the old driver and reattach this new one.
2179                 * Note, we don't have to check for DF_REBID here
2180                 * because if the state is > DS_ALIVE, we know it must
2181                 * be.
2182                 *
2183                 * This assumes that all DF_REBID drivers can have
2184                 * their probe routine called at any time and that
2185                 * they are idempotent as well as completely benign in
2186                 * normal operations.
2187                 *
2188                 * We also have to make sure that the detach
2189                 * succeeded, otherwise we fail the operation (or
2190                 * maybe it should just fail silently?  I'm torn).
2191                 */
2192                if (child->state > DS_ALIVE && best->driver != child->driver)
2193                        if ((result = device_detach(dev)) != 0)
2194                                return (result);
2195
2196                /* Set the winning driver, devclass, and flags. */
2197                if (!child->devclass) {
2198                        result = device_set_devclass(child, best->driver->name);
2199                        if (result != 0)
2200                                return (result);
2201                }
2202                result = device_set_driver(child, best->driver);
2203                if (result != 0)
2204                        return (result);
2205#ifndef __rtems__
2206                resource_int_value(best->driver->name, child->unit,
2207                    "flags", &child->devflags);
2208#endif /* __rtems__ */
2209
2210                if (pri < 0) {
2211                        /*
2212                         * A bit bogus. Call the probe method again to make
2213                         * sure that we have the right description.
2214                         */
2215                        DEVICE_PROBE(child);
2216#if 0
2217                        child->flags |= DF_REBID;
2218#endif
2219                } else
2220                        child->flags &= ~DF_REBID;
2221                child->state = DS_ALIVE;
2222
2223                bus_data_generation_update();
2224                return (0);
2225        }
2226
2227        return (ENXIO);
2228}
2229
2230/**
2231 * @brief Return the parent of a device
2232 */
2233device_t
2234device_get_parent(device_t dev)
2235{
2236        return (dev->parent);
2237}
2238
2239/**
2240 * @brief Get a list of children of a device
2241 *
2242 * An array containing a list of all the children of the given device
2243 * is allocated and returned in @p *devlistp. The number of devices
2244 * in the array is returned in @p *devcountp. The caller should free
2245 * the array using @c free(p, M_TEMP).
2246 *
2247 * @param dev           the device to examine
2248 * @param devlistp      points at location for array pointer return
2249 *                      value
2250 * @param devcountp     points at location for array size return value
2251 *
2252 * @retval 0            success
2253 * @retval ENOMEM       the array allocation failed
2254 */
2255int
2256device_get_children(device_t dev, device_t **devlistp, int *devcountp)
2257{
2258        int count;
2259        device_t child;
2260        device_t *list;
2261
2262        count = 0;
2263        TAILQ_FOREACH(child, &dev->children, link) {
2264                count++;
2265        }
2266        if (count == 0) {
2267                *devlistp = NULL;
2268                *devcountp = 0;
2269                return (0);
2270        }
2271
2272#ifdef __rtems__
2273        /* malloc(0) may return NULL */
2274        if (count != 0) {
2275#endif /* __rtems__ */
2276        list = malloc(count * sizeof(device_t), M_TEMP, M_NOWAIT|M_ZERO);
2277        if (!list)
2278                return (ENOMEM);
2279
2280        count = 0;
2281        TAILQ_FOREACH(child, &dev->children, link) {
2282                list[count] = child;
2283                count++;
2284        }
2285#ifdef __rtems__
2286        } else {
2287                list = NULL;
2288        }
2289#endif /* __rtems__ */
2290
2291        *devlistp = list;
2292        *devcountp = count;
2293
2294        return (0);
2295}
2296
2297/**
2298 * @brief Return the current driver for the device or @c NULL if there
2299 * is no driver currently attached
2300 */
2301driver_t *
2302device_get_driver(device_t dev)
2303{
2304        return (dev->driver);
2305}
2306
2307/**
2308 * @brief Return the current devclass for the device or @c NULL if
2309 * there is none.
2310 */
2311devclass_t
2312device_get_devclass(device_t dev)
2313{
2314        return (dev->devclass);
2315}
2316
2317/**
2318 * @brief Return the name of the device's devclass or @c NULL if there
2319 * is none.
2320 */
2321const char *
2322device_get_name(device_t dev)
2323{
2324        if (dev != NULL && dev->devclass)
2325                return (devclass_get_name(dev->devclass));
2326        return (NULL);
2327}
2328
2329/**
2330 * @brief Return a string containing the device's devclass name
2331 * followed by an ascii representation of the device's unit number
2332 * (e.g. @c "foo2").
2333 */
2334const char *
2335device_get_nameunit(device_t dev)
2336{
2337        return (dev->nameunit);
2338}
2339
2340/**
2341 * @brief Return the device's unit number.
2342 */
2343int
2344device_get_unit(device_t dev)
2345{
2346        return (dev->unit);
2347}
2348
2349/**
2350 * @brief Return the device's description string
2351 */
2352const char *
2353device_get_desc(device_t dev)
2354{
2355        return (dev->desc);
2356}
2357
2358/**
2359 * @brief Return the device's flags
2360 */
2361u_int32_t
2362device_get_flags(device_t dev)
2363{
2364        return (dev->devflags);
2365}
2366
2367struct sysctl_ctx_list *
2368device_get_sysctl_ctx(device_t dev)
2369{
2370#ifndef __rtems__
2371        return (&dev->sysctl_ctx);
2372#else /* __rtems__ */
2373        return (NULL);
2374#endif /* __rtems__ */
2375}
2376
2377struct sysctl_oid *
2378device_get_sysctl_tree(device_t dev)
2379{
2380#ifndef __rtems__
2381        return (dev->sysctl_tree);
2382#else /* __rtems__ */
2383        return (NULL);
2384#endif /* __rtems__ */
2385}
2386
2387/**
2388 * @brief Print the name of the device followed by a colon and a space
2389 *
2390 * @returns the number of characters printed
2391 */
2392int
2393device_print_prettyname(device_t dev)
2394{
2395        const char *name = device_get_name(dev);
2396
2397        if (name == NULL)
2398                return (printf("unknown: "));
2399        return (printf("%s%d: ", name, device_get_unit(dev)));
2400}
2401
2402/**
2403 * @brief Print the name of the device followed by a colon, a space
2404 * and the result of calling vprintf() with the value of @p fmt and
2405 * the following arguments.
2406 *
2407 * @returns the number of characters printed
2408 */
2409int
2410device_printf(device_t dev, const char * fmt, ...)
2411{
2412        va_list ap;
2413        int retval;
2414
2415        retval = device_print_prettyname(dev);
2416        va_start(ap, fmt);
2417        retval += vprintf(fmt, ap);
2418        va_end(ap);
2419        return (retval);
2420}
2421
2422/**
2423 * @internal
2424 */
2425static void
2426device_set_desc_internal(device_t dev, const char* desc, int copy)
2427{
2428        if (dev->desc && (dev->flags & DF_DESCMALLOCED)) {
2429                free(dev->desc, M_BUS);
2430                dev->flags &= ~DF_DESCMALLOCED;
2431                dev->desc = NULL;
2432        }
2433
2434        if (copy && desc) {
2435                dev->desc = malloc(strlen(desc) + 1, M_BUS, M_NOWAIT);
2436                if (dev->desc) {
2437                        strcpy(dev->desc, desc);
2438                        dev->flags |= DF_DESCMALLOCED;
2439                }
2440        } else {
2441                /* Avoid a -Wcast-qual warning */
2442                dev->desc = (char *)(uintptr_t) desc;
2443        }
2444
2445        bus_data_generation_update();
2446}
2447
2448/**
2449 * @brief Set the device's description
2450 *
2451 * The value of @c desc should be a string constant that will not
2452 * change (at least until the description is changed in a subsequent
2453 * call to device_set_desc() or device_set_desc_copy()).
2454 */
2455void
2456device_set_desc(device_t dev, const char* desc)
2457{
2458        device_set_desc_internal(dev, desc, FALSE);
2459}
2460
2461/**
2462 * @brief Set the device's description
2463 *
2464 * The string pointed to by @c desc is copied. Use this function if
2465 * the device description is generated, (e.g. with sprintf()).
2466 */
2467void
2468device_set_desc_copy(device_t dev, const char* desc)
2469{
2470        device_set_desc_internal(dev, desc, TRUE);
2471}
2472
2473/**
2474 * @brief Set the device's flags
2475 */
2476void
2477device_set_flags(device_t dev, u_int32_t flags)
2478{
2479        dev->devflags = flags;
2480}
2481
2482/**
2483 * @brief Return the device's softc field
2484 *
2485 * The softc is allocated and zeroed when a driver is attached, based
2486 * on the size field of the driver.
2487 */
2488void *
2489device_get_softc(device_t dev)
2490{
2491        return (dev->softc);
2492}
2493
2494/**
2495 * @brief Set the device's softc field
2496 *
2497 * Most drivers do not need to use this since the softc is allocated
2498 * automatically when the driver is attached.
2499 */
2500void
2501device_set_softc(device_t dev, void *softc)
2502{
2503        if (dev->softc && !(dev->flags & DF_EXTERNALSOFTC))
2504                free(dev->softc, M_BUS_SC);
2505        dev->softc = softc;
2506        if (dev->softc)
2507                dev->flags |= DF_EXTERNALSOFTC;
2508        else
2509                dev->flags &= ~DF_EXTERNALSOFTC;
2510}
2511
2512/**
2513 * @brief Get the device's ivars field
2514 *
2515 * The ivars field is used by the parent device to store per-device
2516 * state (e.g. the physical location of the device or a list of
2517 * resources).
2518 */
2519void *
2520device_get_ivars(device_t dev)
2521{
2522
2523        KASSERT(dev != NULL, ("device_get_ivars(NULL, ...)"));
2524        return (dev->ivars);
2525}
2526
2527/**
2528 * @brief Set the device's ivars field
2529 */
2530void
2531device_set_ivars(device_t dev, void * ivars)
2532{
2533
2534        KASSERT(dev != NULL, ("device_set_ivars(NULL, ...)"));
2535        dev->ivars = ivars;
2536}
2537
2538/**
2539 * @brief Return the device's state
2540 */
2541device_state_t
2542device_get_state(device_t dev)
2543{
2544        return (dev->state);
2545}
2546
2547/**
2548 * @brief Set the DF_ENABLED flag for the device
2549 */
2550void
2551device_enable(device_t dev)
2552{
2553        dev->flags |= DF_ENABLED;
2554}
2555
2556/**
2557 * @brief Clear the DF_ENABLED flag for the device
2558 */
2559void
2560device_disable(device_t dev)
2561{
2562        dev->flags &= ~DF_ENABLED;
2563}
2564
2565/**
2566 * @brief Increment the busy counter for the device
2567 */
2568void
2569device_busy(device_t dev)
2570{
2571        if (dev->state < DS_ATTACHING)
2572                panic("device_busy: called for unattached device");
2573        if (dev->busy == 0 && dev->parent)
2574                device_busy(dev->parent);
2575        dev->busy++;
2576        if (dev->state == DS_ATTACHED)
2577                dev->state = DS_BUSY;
2578}
2579
2580/**
2581 * @brief Decrement the busy counter for the device
2582 */
2583void
2584device_unbusy(device_t dev)
2585{
2586        if (dev->busy != 0 && dev->state != DS_BUSY &&
2587            dev->state != DS_ATTACHING)
2588                panic("device_unbusy: called for non-busy device %s",
2589                    device_get_nameunit(dev));
2590        dev->busy--;
2591        if (dev->busy == 0) {
2592                if (dev->parent)
2593                        device_unbusy(dev->parent);
2594                if (dev->state == DS_BUSY)
2595                        dev->state = DS_ATTACHED;
2596        }
2597}
2598
2599/**
2600 * @brief Set the DF_QUIET flag for the device
2601 */
2602void
2603device_quiet(device_t dev)
2604{
2605        dev->flags |= DF_QUIET;
2606}
2607
2608/**
2609 * @brief Clear the DF_QUIET flag for the device
2610 */
2611void
2612device_verbose(device_t dev)
2613{
2614        dev->flags &= ~DF_QUIET;
2615}
2616
2617/**
2618 * @brief Return non-zero if the DF_QUIET flag is set on the device
2619 */
2620int
2621device_is_quiet(device_t dev)
2622{
2623        return ((dev->flags & DF_QUIET) != 0);
2624}
2625
2626/**
2627 * @brief Return non-zero if the DF_ENABLED flag is set on the device
2628 */
2629int
2630device_is_enabled(device_t dev)
2631{
2632        return ((dev->flags & DF_ENABLED) != 0);
2633}
2634
2635/**
2636 * @brief Return non-zero if the device was successfully probed
2637 */
2638int
2639device_is_alive(device_t dev)
2640{
2641        return (dev->state >= DS_ALIVE);
2642}
2643
2644/**
2645 * @brief Return non-zero if the device currently has a driver
2646 * attached to it
2647 */
2648int
2649device_is_attached(device_t dev)
2650{
2651        return (dev->state >= DS_ATTACHED);
2652}
2653
2654/**
2655 * @brief Set the devclass of a device
2656 * @see devclass_add_device().
2657 */
2658int
2659device_set_devclass(device_t dev, const char *classname)
2660{
2661        devclass_t dc;
2662        int error;
2663
2664        if (!classname) {
2665                if (dev->devclass)
2666                        devclass_delete_device(dev->devclass, dev);
2667                return (0);
2668        }
2669
2670        if (dev->devclass) {
2671                printf("device_set_devclass: device class already set\n");
2672                return (EINVAL);
2673        }
2674
2675        dc = devclass_find_internal(classname, NULL, TRUE);
2676        if (!dc)
2677                return (ENOMEM);
2678
2679        error = devclass_add_device(dc, dev);
2680
2681        bus_data_generation_update();
2682        return (error);
2683}
2684
2685/**
2686 * @brief Set the driver of a device
2687 *
2688 * @retval 0            success
2689 * @retval EBUSY        the device already has a driver attached
2690 * @retval ENOMEM       a memory allocation failure occurred
2691 */
2692int
2693device_set_driver(device_t dev, driver_t *driver)
2694{
2695        if (dev->state >= DS_ATTACHED)
2696                return (EBUSY);
2697
2698        if (dev->driver == driver)
2699                return (0);
2700
2701        if (dev->softc && !(dev->flags & DF_EXTERNALSOFTC)) {
2702                free(dev->softc, M_BUS_SC);
2703                dev->softc = NULL;
2704        }
2705        device_set_desc(dev, NULL);
2706        kobj_delete((kobj_t) dev, NULL);
2707        dev->driver = driver;
2708        if (driver) {
2709                kobj_init((kobj_t) dev, (kobj_class_t) driver);
2710                if (!(dev->flags & DF_EXTERNALSOFTC) && driver->size > 0) {
2711                        dev->softc = malloc(driver->size, M_BUS_SC,
2712                            M_NOWAIT | M_ZERO);
2713                        if (!dev->softc) {
2714                                kobj_delete((kobj_t) dev, NULL);
2715                                kobj_init((kobj_t) dev, &null_class);
2716                                dev->driver = NULL;
2717                                return (ENOMEM);
2718                        }
2719                }
2720        } else {
2721                kobj_init((kobj_t) dev, &null_class);
2722        }
2723
2724        bus_data_generation_update();
2725        return (0);
2726}
2727
2728/**
2729 * @brief Probe a device, and return this status.
2730 *
2731 * This function is the core of the device autoconfiguration
2732 * system. Its purpose is to select a suitable driver for a device and
2733 * then call that driver to initialise the hardware appropriately. The
2734 * driver is selected by calling the DEVICE_PROBE() method of a set of
2735 * candidate drivers and then choosing the driver which returned the
2736 * best value. This driver is then attached to the device using
2737 * device_attach().
2738 *
2739 * The set of suitable drivers is taken from the list of drivers in
2740 * the parent device's devclass. If the device was originally created
2741 * with a specific class name (see device_add_child()), only drivers
2742 * with that name are probed, otherwise all drivers in the devclass
2743 * are probed. If no drivers return successful probe values in the
2744 * parent devclass, the search continues in the parent of that
2745 * devclass (see devclass_get_parent()) if any.
2746 *
2747 * @param dev           the device to initialise
2748 *
2749 * @retval 0            success
2750 * @retval ENXIO        no driver was found
2751 * @retval ENOMEM       memory allocation failure
2752 * @retval non-zero     some other unix error code
2753 * @retval -1           Device already attached
2754 */
2755int
2756device_probe(device_t dev)
2757{
2758        int error;
2759
2760        GIANT_REQUIRED;
2761
2762        if (dev->state >= DS_ALIVE && (dev->flags & DF_REBID) == 0)
2763                return (-1);
2764
2765        if (!(dev->flags & DF_ENABLED)) {
2766                if (bootverbose && device_get_name(dev) != NULL) {
2767                        device_print_prettyname(dev);
2768                        printf("not probed (disabled)\n");
2769                }
2770                return (-1);
2771        }
2772        if ((error = device_probe_child(dev->parent, dev)) != 0) {             
2773                if (bus_current_pass == BUS_PASS_DEFAULT &&
2774                    !(dev->flags & DF_DONENOMATCH)) {
2775                        BUS_PROBE_NOMATCH(dev->parent, dev);
2776                        devnomatch(dev);
2777                        dev->flags |= DF_DONENOMATCH;
2778                }
2779                return (error);
2780        }
2781        return (0);
2782}
2783
2784/**
2785 * @brief Probe a device and attach a driver if possible
2786 *
2787 * calls device_probe() and attaches if that was successful.
2788 */
2789int
2790device_probe_and_attach(device_t dev)
2791{
2792        int error;
2793
2794        GIANT_REQUIRED;
2795
2796        error = device_probe(dev);
2797        if (error == -1)
2798                return (0);
2799        else if (error != 0)
2800                return (error);
2801        return (device_attach(dev));
2802}
2803
2804/**
2805 * @brief Attach a device driver to a device
2806 *
2807 * This function is a wrapper around the DEVICE_ATTACH() driver
2808 * method. In addition to calling DEVICE_ATTACH(), it initialises the
2809 * device's sysctl tree, optionally prints a description of the device
2810 * and queues a notification event for user-based device management
2811 * services.
2812 *
2813 * Normally this function is only called internally from
2814 * device_probe_and_attach().
2815 *
2816 * @param dev           the device to initialise
2817 *
2818 * @retval 0            success
2819 * @retval ENXIO        no driver was found
2820 * @retval ENOMEM       memory allocation failure
2821 * @retval non-zero     some other unix error code
2822 */
2823int
2824device_attach(device_t dev)
2825{
2826        int error;
2827
2828#ifndef __rtems__
2829        if (resource_disabled(dev->driver->name, dev->unit)) {
2830                device_disable(dev);
2831                if (bootverbose)
2832                         device_printf(dev, "disabled via hints entry\n");
2833                return (ENXIO);
2834        }
2835#endif /* __rtems__ */
2836
2837        device_sysctl_init(dev);
2838        if (!device_is_quiet(dev))
2839                device_print_child(dev->parent, dev);
2840        dev->state = DS_ATTACHING;
2841        if ((error = DEVICE_ATTACH(dev)) != 0) {
2842                printf("device_attach: %s%d attach returned %d\n",
2843                    dev->driver->name, dev->unit, error);
2844                if (!(dev->flags & DF_FIXEDCLASS))
2845                        devclass_delete_device(dev->devclass, dev);
2846                (void)device_set_driver(dev, NULL);
2847                device_sysctl_fini(dev);
2848                KASSERT(dev->busy == 0, ("attach failed but busy"));
2849                dev->state = DS_NOTPRESENT;
2850                return (error);
2851        }
2852        device_sysctl_update(dev);
2853        if (dev->busy)
2854                dev->state = DS_BUSY;
2855        else
2856                dev->state = DS_ATTACHED;
2857        dev->flags &= ~DF_DONENOMATCH;
2858        devadded(dev);
2859        return (0);
2860}
2861
2862/**
2863 * @brief Detach a driver from a device
2864 *
2865 * This function is a wrapper around the DEVICE_DETACH() driver
2866 * method. If the call to DEVICE_DETACH() succeeds, it calls
2867 * BUS_CHILD_DETACHED() for the parent of @p dev, queues a
2868 * notification event for user-based device management services and
2869 * cleans up the device's sysctl tree.
2870 *
2871 * @param dev           the device to un-initialise
2872 *
2873 * @retval 0            success
2874 * @retval ENXIO        no driver was found
2875 * @retval ENOMEM       memory allocation failure
2876 * @retval non-zero     some other unix error code
2877 */
2878int
2879device_detach(device_t dev)
2880{
2881        int error;
2882
2883        GIANT_REQUIRED;
2884
2885        PDEBUG(("%s", DEVICENAME(dev)));
2886        if (dev->state == DS_BUSY)
2887                return (EBUSY);
2888        if (dev->state != DS_ATTACHED)
2889                return (0);
2890
2891        if ((error = DEVICE_DETACH(dev)) != 0)
2892                return (error);
2893        devremoved(dev);
2894        if (!device_is_quiet(dev))
2895                device_printf(dev, "detached\n");
2896        if (dev->parent)
2897                BUS_CHILD_DETACHED(dev->parent, dev);
2898
2899        if (!(dev->flags & DF_FIXEDCLASS))
2900                devclass_delete_device(dev->devclass, dev);
2901
2902        dev->state = DS_NOTPRESENT;
2903        (void)device_set_driver(dev, NULL);
2904        device_sysctl_fini(dev);
2905
2906        return (0);
2907}
2908
2909/**
2910 * @brief Tells a driver to quiesce itself.
2911 *
2912 * This function is a wrapper around the DEVICE_QUIESCE() driver
2913 * method. If the call to DEVICE_QUIESCE() succeeds.
2914 *
2915 * @param dev           the device to quiesce
2916 *
2917 * @retval 0            success
2918 * @retval ENXIO        no driver was found
2919 * @retval ENOMEM       memory allocation failure
2920 * @retval non-zero     some other unix error code
2921 */
2922int
2923device_quiesce(device_t dev)
2924{
2925
2926        PDEBUG(("%s", DEVICENAME(dev)));
2927        if (dev->state == DS_BUSY)
2928                return (EBUSY);
2929        if (dev->state != DS_ATTACHED)
2930                return (0);
2931
2932        return (DEVICE_QUIESCE(dev));
2933}
2934
2935/**
2936 * @brief Notify a device of system shutdown
2937 *
2938 * This function calls the DEVICE_SHUTDOWN() driver method if the
2939 * device currently has an attached driver.
2940 *
2941 * @returns the value returned by DEVICE_SHUTDOWN()
2942 */
2943int
2944device_shutdown(device_t dev)
2945{
2946        if (dev->state < DS_ATTACHED)
2947                return (0);
2948        return (DEVICE_SHUTDOWN(dev));
2949}
2950
2951/**
2952 * @brief Set the unit number of a device
2953 *
2954 * This function can be used to override the unit number used for a
2955 * device (e.g. to wire a device to a pre-configured unit number).
2956 */
2957int
2958device_set_unit(device_t dev, int unit)
2959{
2960        devclass_t dc;
2961        int err;
2962
2963        dc = device_get_devclass(dev);
2964        if (unit < dc->maxunit && dc->devices[unit])
2965                return (EBUSY);
2966        err = devclass_delete_device(dc, dev);
2967        if (err)
2968                return (err);
2969        dev->unit = unit;
2970        err = devclass_add_device(dc, dev);
2971        if (err)
2972                return (err);
2973
2974        bus_data_generation_update();
2975        return (0);
2976}
2977
2978/*======================================*/
2979/*
2980 * Some useful method implementations to make life easier for bus drivers.
2981 */
2982
2983/**
2984 * @brief Initialise a resource list.
2985 *
2986 * @param rl            the resource list to initialise
2987 */
2988void
2989resource_list_init(struct resource_list *rl)
2990{
2991        STAILQ_INIT(rl);
2992}
2993
2994/**
2995 * @brief Reclaim memory used by a resource list.
2996 *
2997 * This function frees the memory for all resource entries on the list
2998 * (if any).
2999 *
3000 * @param rl            the resource list to free               
3001 */
3002void
3003resource_list_free(struct resource_list *rl)
3004{
3005        struct resource_list_entry *rle;
3006
3007        while ((rle = STAILQ_FIRST(rl)) != NULL) {
3008                if (rle->res)
3009                        panic("resource_list_free: resource entry is busy");
3010                STAILQ_REMOVE_HEAD(rl, link);
3011                free(rle, M_BUS);
3012        }
3013}
3014
3015/**
3016 * @brief Add a resource entry.
3017 *
3018 * This function adds a resource entry using the given @p type, @p
3019 * start, @p end and @p count values. A rid value is chosen by
3020 * searching sequentially for the first unused rid starting at zero.
3021 *
3022 * @param rl            the resource list to edit
3023 * @param type          the resource entry type (e.g. SYS_RES_MEMORY)
3024 * @param start         the start address of the resource
3025 * @param end           the end address of the resource
3026 * @param count         XXX end-start+1
3027 */
3028int
3029resource_list_add_next(struct resource_list *rl, int type, u_long start,
3030    u_long end, u_long count)
3031{
3032        int rid;
3033
3034        rid = 0;
3035        while (resource_list_find(rl, type, rid) != NULL)
3036                rid++;
3037        resource_list_add(rl, type, rid, start, end, count);
3038        return (rid);
3039}
3040
3041/**
3042 * @brief Add or modify a resource entry.
3043 *
3044 * If an existing entry exists with the same type and rid, it will be
3045 * modified using the given values of @p start, @p end and @p
3046 * count. If no entry exists, a new one will be created using the
3047 * given values.  The resource list entry that matches is then returned.
3048 *
3049 * @param rl            the resource list to edit
3050 * @param type          the resource entry type (e.g. SYS_RES_MEMORY)
3051 * @param rid           the resource identifier
3052 * @param start         the start address of the resource
3053 * @param end           the end address of the resource
3054 * @param count         XXX end-start+1
3055 */
3056struct resource_list_entry *
3057resource_list_add(struct resource_list *rl, int type, int rid,
3058    u_long start, u_long end, u_long count)
3059{
3060        struct resource_list_entry *rle;
3061
3062        rle = resource_list_find(rl, type, rid);
3063        if (!rle) {
3064                rle = malloc(sizeof(struct resource_list_entry), M_BUS,
3065                    M_NOWAIT);
3066                if (!rle)
3067                        panic("resource_list_add: can't record entry");
3068                STAILQ_INSERT_TAIL(rl, rle, link);
3069                rle->type = type;
3070                rle->rid = rid;
3071                rle->res = NULL;
3072        }
3073
3074        if (rle->res)
3075                panic("resource_list_add: resource entry is busy");
3076
3077        rle->start = start;
3078        rle->end = end;
3079        rle->count = count;
3080        return (rle);
3081}
3082
3083/**
3084 * @brief Find a resource entry by type and rid.
3085 *
3086 * @param rl            the resource list to search
3087 * @param type          the resource entry type (e.g. SYS_RES_MEMORY)
3088 * @param rid           the resource identifier
3089 *
3090 * @returns the resource entry pointer or NULL if there is no such
3091 * entry.
3092 */
3093struct resource_list_entry *
3094resource_list_find(struct resource_list *rl, int type, int rid)
3095{
3096        struct resource_list_entry *rle;
3097
3098        STAILQ_FOREACH(rle, rl, link) {
3099                if (rle->type == type && rle->rid == rid)
3100                        return (rle);
3101        }
3102        return (NULL);
3103}
3104
3105/**
3106 * @brief Delete a resource entry.
3107 *
3108 * @param rl            the resource list to edit
3109 * @param type          the resource entry type (e.g. SYS_RES_MEMORY)
3110 * @param rid           the resource identifier
3111 */
3112void
3113resource_list_delete(struct resource_list *rl, int type, int rid)
3114{
3115        struct resource_list_entry *rle = resource_list_find(rl, type, rid);
3116
3117        if (rle) {
3118                if (rle->res != NULL)
3119                        panic("resource_list_delete: resource has not been released");
3120                STAILQ_REMOVE(rl, rle, resource_list_entry, link);
3121                free(rle, M_BUS);
3122        }
3123}
3124
3125/**
3126 * @brief Helper function for implementing BUS_ALLOC_RESOURCE()
3127 *
3128 * Implement BUS_ALLOC_RESOURCE() by looking up a resource from the list
3129 * and passing the allocation up to the parent of @p bus. This assumes
3130 * that the first entry of @c device_get_ivars(child) is a struct
3131 * resource_list. This also handles 'passthrough' allocations where a
3132 * child is a remote descendant of bus by passing the allocation up to
3133 * the parent of bus.
3134 *
3135 * Typically, a bus driver would store a list of child resources
3136 * somewhere in the child device's ivars (see device_get_ivars()) and
3137 * its implementation of BUS_ALLOC_RESOURCE() would find that list and
3138 * then call resource_list_alloc() to perform the allocation.
3139 *
3140 * @param rl            the resource list to allocate from
3141 * @param bus           the parent device of @p child
3142 * @param child         the device which is requesting an allocation
3143 * @param type          the type of resource to allocate
3144 * @param rid           a pointer to the resource identifier
3145 * @param start         hint at the start of the resource range - pass
3146 *                      @c 0UL for any start address
3147 * @param end           hint at the end of the resource range - pass
3148 *                      @c ~0UL for any end address
3149 * @param count         hint at the size of range required - pass @c 1
3150 *                      for any size
3151 * @param flags         any extra flags to control the resource
3152 *                      allocation - see @c RF_XXX flags in
3153 *                      <sys/rman.h> for details
3154 *
3155 * @returns             the resource which was allocated or @c NULL if no
3156 *                      resource could be allocated
3157 */
3158struct resource *
3159resource_list_alloc(struct resource_list *rl, device_t bus, device_t child,
3160    int type, int *rid, u_long start, u_long end, u_long count, u_int flags)
3161{
3162        struct resource_list_entry *rle = NULL;
3163        int passthrough = (device_get_parent(child) != bus);
3164        int isdefault = (start == 0UL && end == ~0UL);
3165
3166        if (passthrough) {
3167                return (BUS_ALLOC_RESOURCE(device_get_parent(bus), child,
3168                    type, rid, start, end, count, flags));
3169        }
3170
3171        rle = resource_list_find(rl, type, *rid);
3172
3173        if (!rle)
3174                return (NULL);          /* no resource of that type/rid */
3175
3176        if (rle->res)
3177                panic("resource_list_alloc: resource entry is busy");
3178
3179        if (isdefault) {
3180                start = rle->start;
3181                count = ulmax(count, rle->count);
3182                end = ulmax(rle->end, start + count - 1);
3183        }
3184
3185        rle->res = BUS_ALLOC_RESOURCE(device_get_parent(bus), child,
3186            type, rid, start, end, count, flags);
3187
3188        /*
3189         * Record the new range.
3190         */
3191        if (rle->res) {
3192                rle->start = rman_get_start(rle->res);
3193                rle->end = rman_get_end(rle->res);
3194                rle->count = count;
3195        }
3196
3197        return (rle->res);
3198}
3199
3200/**
3201 * @brief Helper function for implementing BUS_RELEASE_RESOURCE()
3202 *
3203 * Implement BUS_RELEASE_RESOURCE() using a resource list. Normally
3204 * used with resource_list_alloc().
3205 *
3206 * @param rl            the resource list which was allocated from
3207 * @param bus           the parent device of @p child
3208 * @param child         the device which is requesting a release
3209 * @param type          the type of resource to allocate
3210 * @param rid           the resource identifier
3211 * @param res           the resource to release
3212 *
3213 * @retval 0            success
3214 * @retval non-zero     a standard unix error code indicating what
3215 *                      error condition prevented the operation
3216 */
3217int
3218resource_list_release(struct resource_list *rl, device_t bus, device_t child,
3219    int type, int rid, struct resource *res)
3220{
3221        struct resource_list_entry *rle = NULL;
3222        int passthrough = (device_get_parent(child) != bus);
3223        int error;
3224
3225        if (passthrough) {
3226                return (BUS_RELEASE_RESOURCE(device_get_parent(bus), child,
3227                    type, rid, res));
3228        }
3229
3230        rle = resource_list_find(rl, type, rid);
3231
3232        if (!rle)
3233                panic("resource_list_release: can't find resource");
3234        if (!rle->res)
3235                panic("resource_list_release: resource entry is not busy");
3236
3237        error = BUS_RELEASE_RESOURCE(device_get_parent(bus), child,
3238            type, rid, res);
3239        if (error)
3240                return (error);
3241
3242        rle->res = NULL;
3243        return (0);
3244}
3245
3246/**
3247 * @brief Print a description of resources in a resource list
3248 *
3249 * Print all resources of a specified type, for use in BUS_PRINT_CHILD().
3250 * The name is printed if at least one resource of the given type is available.
3251 * The format is used to print resource start and end.
3252 *
3253 * @param rl            the resource list to print
3254 * @param name          the name of @p type, e.g. @c "memory"
3255 * @param type          type type of resource entry to print
3256 * @param format        printf(9) format string to print resource
3257 *                      start and end values
3258 *
3259 * @returns             the number of characters printed
3260 */
3261int
3262resource_list_print_type(struct resource_list *rl, const char *name, int type,
3263    const char *format)
3264{
3265        struct resource_list_entry *rle;
3266        int printed, retval;
3267
3268        printed = 0;
3269        retval = 0;
3270        /* Yes, this is kinda cheating */
3271        STAILQ_FOREACH(rle, rl, link) {
3272                if (rle->type == type) {
3273                        if (printed == 0)
3274                                retval += printf(" %s ", name);
3275                        else
3276                                retval += printf(",");
3277                        printed++;
3278                        retval += printf(format, rle->start);
3279                        if (rle->count > 1) {
3280                                retval += printf("-");
3281                                retval += printf(format, rle->start +
3282                                                 rle->count - 1);
3283                        }
3284                }
3285        }
3286        return (retval);
3287}
3288
3289/**
3290 * @brief Releases all the resources in a list.
3291 *
3292 * @param rl            The resource list to purge.
3293 *
3294 * @returns             nothing
3295 */
3296void
3297resource_list_purge(struct resource_list *rl)
3298{
3299        struct resource_list_entry *rle;
3300
3301        while ((rle = STAILQ_FIRST(rl)) != NULL) {
3302                if (rle->res)
3303                        bus_release_resource(rman_get_device(rle->res),
3304                            rle->type, rle->rid, rle->res);
3305                STAILQ_REMOVE_HEAD(rl, link);
3306                free(rle, M_BUS);
3307        }
3308}
3309
3310device_t
3311bus_generic_add_child(device_t dev, u_int order, const char *name, int unit)
3312{
3313
3314        return (device_add_child_ordered(dev, order, name, unit));
3315}
3316
3317/**
3318 * @brief Helper function for implementing DEVICE_PROBE()
3319 *
3320 * This function can be used to help implement the DEVICE_PROBE() for
3321 * a bus (i.e. a device which has other devices attached to it). It
3322 * calls the DEVICE_IDENTIFY() method of each driver in the device's
3323 * devclass.
3324 */
3325int
3326bus_generic_probe(device_t dev)
3327{
3328        devclass_t dc = dev->devclass;
3329        driverlink_t dl;
3330
3331        TAILQ_FOREACH(dl, &dc->drivers, link) {
3332                /*
3333                 * If this driver's pass is too high, then ignore it.
3334                 * For most drivers in the default pass, this will
3335                 * never be true.  For early-pass drivers they will
3336                 * only call the identify routines of eligible drivers
3337                 * when this routine is called.  Drivers for later
3338                 * passes should have their identify routines called
3339                 * on early-pass busses during BUS_NEW_PASS().
3340                 */
3341                if (dl->pass > bus_current_pass)
3342                                continue;
3343                DEVICE_IDENTIFY(dl->driver, dev);
3344        }
3345
3346        return (0);
3347}
3348
3349/**
3350 * @brief Helper function for implementing DEVICE_ATTACH()
3351 *
3352 * This function can be used to help implement the DEVICE_ATTACH() for
3353 * a bus. It calls device_probe_and_attach() for each of the device's
3354 * children.
3355 */
3356int
3357bus_generic_attach(device_t dev)
3358{
3359        device_t child;
3360
3361        TAILQ_FOREACH(child, &dev->children, link) {
3362                device_probe_and_attach(child);
3363        }
3364
3365        return (0);
3366}
3367
3368/**
3369 * @brief Helper function for implementing DEVICE_DETACH()
3370 *
3371 * This function can be used to help implement the DEVICE_DETACH() for
3372 * a bus. It calls device_detach() for each of the device's
3373 * children.
3374 */
3375int
3376bus_generic_detach(device_t dev)
3377{
3378        device_t child;
3379        int error;
3380
3381        if (dev->state != DS_ATTACHED)
3382                return (EBUSY);
3383
3384        TAILQ_FOREACH(child, &dev->children, link) {
3385                if ((error = device_detach(child)) != 0)
3386                        return (error);
3387        }
3388
3389        return (0);
3390}
3391
3392/**
3393 * @brief Helper function for implementing DEVICE_SHUTDOWN()
3394 *
3395 * This function can be used to help implement the DEVICE_SHUTDOWN()
3396 * for a bus. It calls device_shutdown() for each of the device's
3397 * children.
3398 */
3399int
3400bus_generic_shutdown(device_t dev)
3401{
3402        device_t child;
3403
3404        TAILQ_FOREACH(child, &dev->children, link) {
3405                device_shutdown(child);
3406        }
3407
3408        return (0);
3409}
3410
3411/**
3412 * @brief Helper function for implementing DEVICE_SUSPEND()
3413 *
3414 * This function can be used to help implement the DEVICE_SUSPEND()
3415 * for a bus. It calls DEVICE_SUSPEND() for each of the device's
3416 * children. If any call to DEVICE_SUSPEND() fails, the suspend
3417 * operation is aborted and any devices which were suspended are
3418 * resumed immediately by calling their DEVICE_RESUME() methods.
3419 */
3420int
3421bus_generic_suspend(device_t dev)
3422{
3423        int             error;
3424        device_t        child, child2;
3425
3426        TAILQ_FOREACH(child, &dev->children, link) {
3427                error = DEVICE_SUSPEND(child);
3428                if (error) {
3429                        for (child2 = TAILQ_FIRST(&dev->children);
3430                             child2 && child2 != child;
3431                             child2 = TAILQ_NEXT(child2, link))
3432                                DEVICE_RESUME(child2);
3433                        return (error);
3434                }
3435        }
3436        return (0);
3437}
3438
3439/**
3440 * @brief Helper function for implementing DEVICE_RESUME()
3441 *
3442 * This function can be used to help implement the DEVICE_RESUME() for
3443 * a bus. It calls DEVICE_RESUME() on each of the device's children.
3444 */
3445int
3446bus_generic_resume(device_t dev)
3447{
3448        device_t        child;
3449
3450        TAILQ_FOREACH(child, &dev->children, link) {
3451                DEVICE_RESUME(child);
3452                /* if resume fails, there's nothing we can usefully do... */
3453        }
3454        return (0);
3455}
3456
3457/**
3458 * @brief Helper function for implementing BUS_PRINT_CHILD().
3459 *
3460 * This function prints the first part of the ascii representation of
3461 * @p child, including its name, unit and description (if any - see
3462 * device_set_desc()).
3463 *
3464 * @returns the number of characters printed
3465 */
3466int
3467bus_print_child_header(device_t dev, device_t child)
3468{
3469        int     retval = 0;
3470
3471        if (device_get_desc(child)) {
3472                retval += device_printf(child, "<%s>", device_get_desc(child));
3473        } else {
3474                retval += printf("%s", device_get_nameunit(child));
3475        }
3476
3477        return (retval);
3478}
3479
3480/**
3481 * @brief Helper function for implementing BUS_PRINT_CHILD().
3482 *
3483 * This function prints the last part of the ascii representation of
3484 * @p child, which consists of the string @c " on " followed by the
3485 * name and unit of the @p dev.
3486 *
3487 * @returns the number of characters printed
3488 */
3489int
3490bus_print_child_footer(device_t dev, device_t child)
3491{
3492        return (printf(" on %s\n", device_get_nameunit(dev)));
3493}
3494
3495/**
3496 * @brief Helper function for implementing BUS_PRINT_CHILD().
3497 *
3498 * This function simply calls bus_print_child_header() followed by
3499 * bus_print_child_footer().
3500 *
3501 * @returns the number of characters printed
3502 */
3503int
3504bus_generic_print_child(device_t dev, device_t child)
3505{
3506        int     retval = 0;
3507
3508        retval += bus_print_child_header(dev, child);
3509        retval += bus_print_child_footer(dev, child);
3510
3511        return (retval);
3512}
3513
3514/**
3515 * @brief Stub function for implementing BUS_READ_IVAR().
3516 *
3517 * @returns ENOENT
3518 */
3519int
3520bus_generic_read_ivar(device_t dev, device_t child, int index,
3521    uintptr_t * result)
3522{
3523        return (ENOENT);
3524}
3525
3526/**
3527 * @brief Stub function for implementing BUS_WRITE_IVAR().
3528 *
3529 * @returns ENOENT
3530 */
3531int
3532bus_generic_write_ivar(device_t dev, device_t child, int index,
3533    uintptr_t value)
3534{
3535        return (ENOENT);
3536}
3537
3538/**
3539 * @brief Stub function for implementing BUS_GET_RESOURCE_LIST().
3540 *
3541 * @returns NULL
3542 */
3543struct resource_list *
3544bus_generic_get_resource_list(device_t dev, device_t child)
3545{
3546        return (NULL);
3547}
3548
3549/**
3550 * @brief Helper function for implementing BUS_DRIVER_ADDED().
3551 *
3552 * This implementation of BUS_DRIVER_ADDED() simply calls the driver's
3553 * DEVICE_IDENTIFY() method to allow it to add new children to the bus
3554 * and then calls device_probe_and_attach() for each unattached child.
3555 */
3556void
3557bus_generic_driver_added(device_t dev, driver_t *driver)
3558{
3559        device_t child;
3560
3561        DEVICE_IDENTIFY(driver, dev);
3562        TAILQ_FOREACH(child, &dev->children, link) {
3563                if (child->state == DS_NOTPRESENT ||
3564                    (child->flags & DF_REBID))
3565                        device_probe_and_attach(child);
3566        }
3567}
3568
3569/**
3570 * @brief Helper function for implementing BUS_NEW_PASS().
3571 *
3572 * This implementing of BUS_NEW_PASS() first calls the identify
3573 * routines for any drivers that probe at the current pass.  Then it
3574 * walks the list of devices for this bus.  If a device is already
3575 * attached, then it calls BUS_NEW_PASS() on that device.  If the
3576 * device is not already attached, it attempts to attach a driver to
3577 * it.
3578 */
3579void
3580bus_generic_new_pass(device_t dev)
3581{
3582        driverlink_t dl;
3583        devclass_t dc;
3584        device_t child;
3585
3586        dc = dev->devclass;
3587        TAILQ_FOREACH(dl, &dc->drivers, link) {
3588                if (dl->pass == bus_current_pass)
3589                        DEVICE_IDENTIFY(dl->driver, dev);
3590        }
3591        TAILQ_FOREACH(child, &dev->children, link) {
3592                if (child->state >= DS_ATTACHED)
3593                        BUS_NEW_PASS(child);
3594                else if (child->state == DS_NOTPRESENT)
3595                        device_probe_and_attach(child);
3596        }
3597}
3598
3599/**
3600 * @brief Helper function for implementing BUS_SETUP_INTR().
3601 *
3602 * This simple implementation of BUS_SETUP_INTR() simply calls the
3603 * BUS_SETUP_INTR() method of the parent of @p dev.
3604 */
3605int
3606bus_generic_setup_intr(device_t dev, device_t child, struct resource *irq,
3607    int flags, driver_filter_t *filter, driver_intr_t *intr, void *arg,
3608    void **cookiep)
3609{
3610        /* Propagate up the bus hierarchy until someone handles it. */
3611        if (dev->parent)
3612                return (BUS_SETUP_INTR(dev->parent, child, irq, flags,
3613                    filter, intr, arg, cookiep));
3614        return (EINVAL);
3615}
3616
3617/**
3618 * @brief Helper function for implementing BUS_TEARDOWN_INTR().
3619 *
3620 * This simple implementation of BUS_TEARDOWN_INTR() simply calls the
3621 * BUS_TEARDOWN_INTR() method of the parent of @p dev.
3622 */
3623int
3624bus_generic_teardown_intr(device_t dev, device_t child, struct resource *irq,
3625    void *cookie)
3626{
3627        /* Propagate up the bus hierarchy until someone handles it. */
3628        if (dev->parent)
3629                return (BUS_TEARDOWN_INTR(dev->parent, child, irq, cookie));
3630        return (EINVAL);
3631}
3632
3633/**
3634 * @brief Helper function for implementing BUS_ADJUST_RESOURCE().
3635 *
3636 * This simple implementation of BUS_ADJUST_RESOURCE() simply calls the
3637 * BUS_ADJUST_RESOURCE() method of the parent of @p dev.
3638 */
3639int
3640bus_generic_adjust_resource(device_t dev, device_t child, int type,
3641    struct resource *r, u_long start, u_long end)
3642{
3643        /* Propagate up the bus hierarchy until someone handles it. */
3644        if (dev->parent)
3645                return (BUS_ADJUST_RESOURCE(dev->parent, child, type, r, start,
3646                    end));
3647        return (EINVAL);
3648}
3649
3650/**
3651 * @brief Helper function for implementing BUS_ALLOC_RESOURCE().
3652 *
3653 * This simple implementation of BUS_ALLOC_RESOURCE() simply calls the
3654 * BUS_ALLOC_RESOURCE() method of the parent of @p dev.
3655 */
3656struct resource *
3657bus_generic_alloc_resource(device_t dev, device_t child, int type, int *rid,
3658    u_long start, u_long end, u_long count, u_int flags)
3659{
3660        /* Propagate up the bus hierarchy until someone handles it. */
3661        if (dev->parent)
3662                return (BUS_ALLOC_RESOURCE(dev->parent, child, type, rid,
3663                    start, end, count, flags));
3664        return (NULL);
3665}
3666
3667/**
3668 * @brief Helper function for implementing BUS_RELEASE_RESOURCE().
3669 *
3670 * This simple implementation of BUS_RELEASE_RESOURCE() simply calls the
3671 * BUS_RELEASE_RESOURCE() method of the parent of @p dev.
3672 */
3673int
3674bus_generic_release_resource(device_t dev, device_t child, int type, int rid,
3675    struct resource *r)
3676{
3677        /* Propagate up the bus hierarchy until someone handles it. */
3678        if (dev->parent)
3679                return (BUS_RELEASE_RESOURCE(dev->parent, child, type, rid,
3680                    r));
3681        return (EINVAL);
3682}
3683
3684/**
3685 * @brief Helper function for implementing BUS_ACTIVATE_RESOURCE().
3686 *
3687 * This simple implementation of BUS_ACTIVATE_RESOURCE() simply calls the
3688 * BUS_ACTIVATE_RESOURCE() method of the parent of @p dev.
3689 */
3690int
3691bus_generic_activate_resource(device_t dev, device_t child, int type, int rid,
3692    struct resource *r)
3693{
3694        /* Propagate up the bus hierarchy until someone handles it. */
3695        if (dev->parent)
3696                return (BUS_ACTIVATE_RESOURCE(dev->parent, child, type, rid,
3697                    r));
3698        return (EINVAL);
3699}
3700
3701/**
3702 * @brief Helper function for implementing BUS_DEACTIVATE_RESOURCE().
3703 *
3704 * This simple implementation of BUS_DEACTIVATE_RESOURCE() simply calls the
3705 * BUS_DEACTIVATE_RESOURCE() method of the parent of @p dev.
3706 */
3707int
3708bus_generic_deactivate_resource(device_t dev, device_t child, int type,
3709    int rid, struct resource *r)
3710{
3711        /* Propagate up the bus hierarchy until someone handles it. */
3712        if (dev->parent)
3713                return (BUS_DEACTIVATE_RESOURCE(dev->parent, child, type, rid,
3714                    r));
3715        return (EINVAL);
3716}
3717
3718/**
3719 * @brief Helper function for implementing BUS_BIND_INTR().
3720 *
3721 * This simple implementation of BUS_BIND_INTR() simply calls the
3722 * BUS_BIND_INTR() method of the parent of @p dev.
3723 */
3724int
3725bus_generic_bind_intr(device_t dev, device_t child, struct resource *irq,
3726    int cpu)
3727{
3728
3729        /* Propagate up the bus hierarchy until someone handles it. */
3730        if (dev->parent)
3731                return (BUS_BIND_INTR(dev->parent, child, irq, cpu));
3732        return (EINVAL);
3733}
3734
3735/**
3736 * @brief Helper function for implementing BUS_CONFIG_INTR().
3737 *
3738 * This simple implementation of BUS_CONFIG_INTR() simply calls the
3739 * BUS_CONFIG_INTR() method of the parent of @p dev.
3740 */
3741int
3742bus_generic_config_intr(device_t dev, int irq, enum intr_trigger trig,
3743    enum intr_polarity pol)
3744{
3745
3746        /* Propagate up the bus hierarchy until someone handles it. */
3747        if (dev->parent)
3748                return (BUS_CONFIG_INTR(dev->parent, irq, trig, pol));
3749        return (EINVAL);
3750}
3751
3752/**
3753 * @brief Helper function for implementing BUS_DESCRIBE_INTR().
3754 *
3755 * This simple implementation of BUS_DESCRIBE_INTR() simply calls the
3756 * BUS_DESCRIBE_INTR() method of the parent of @p dev.
3757 */
3758int
3759bus_generic_describe_intr(device_t dev, device_t child, struct resource *irq,
3760    void *cookie, const char *descr)
3761{
3762
3763        /* Propagate up the bus hierarchy until someone handles it. */
3764        if (dev->parent)
3765                return (BUS_DESCRIBE_INTR(dev->parent, child, irq, cookie,
3766                    descr));
3767        return (EINVAL);
3768}
3769
3770/**
3771 * @brief Helper function for implementing BUS_GET_DMA_TAG().
3772 *
3773 * This simple implementation of BUS_GET_DMA_TAG() simply calls the
3774 * BUS_GET_DMA_TAG() method of the parent of @p dev.
3775 */
3776bus_dma_tag_t
3777bus_generic_get_dma_tag(device_t dev, device_t child)
3778{
3779
3780        /* Propagate up the bus hierarchy until someone handles it. */
3781        if (dev->parent != NULL)
3782                return (BUS_GET_DMA_TAG(dev->parent, child));
3783        return (NULL);
3784}
3785
3786/**
3787 * @brief Helper function for implementing BUS_GET_RESOURCE().
3788 *
3789 * This implementation of BUS_GET_RESOURCE() uses the
3790 * resource_list_find() function to do most of the work. It calls
3791 * BUS_GET_RESOURCE_LIST() to find a suitable resource list to
3792 * search.
3793 */
3794int
3795bus_generic_rl_get_resource(device_t dev, device_t child, int type, int rid,
3796    u_long *startp, u_long *countp)
3797{
3798        struct resource_list *          rl = NULL;
3799        struct resource_list_entry *    rle = NULL;
3800
3801        rl = BUS_GET_RESOURCE_LIST(dev, child);
3802        if (!rl)
3803                return (EINVAL);
3804
3805        rle = resource_list_find(rl, type, rid);
3806        if (!rle)
3807                return (ENOENT);
3808
3809        if (startp)
3810                *startp = rle->start;
3811        if (countp)
3812                *countp = rle->count;
3813
3814        return (0);
3815}
3816
3817/**
3818 * @brief Helper function for implementing BUS_SET_RESOURCE().
3819 *
3820 * This implementation of BUS_SET_RESOURCE() uses the
3821 * resource_list_add() function to do most of the work. It calls
3822 * BUS_GET_RESOURCE_LIST() to find a suitable resource list to
3823 * edit.
3824 */
3825int
3826bus_generic_rl_set_resource(device_t dev, device_t child, int type, int rid,
3827    u_long start, u_long count)
3828{
3829        struct resource_list *          rl = NULL;
3830
3831        rl = BUS_GET_RESOURCE_LIST(dev, child);
3832        if (!rl)
3833                return (EINVAL);
3834
3835        resource_list_add(rl, type, rid, start, (start + count - 1), count);
3836
3837        return (0);
3838}
3839
3840/**
3841 * @brief Helper function for implementing BUS_DELETE_RESOURCE().
3842 *
3843 * This implementation of BUS_DELETE_RESOURCE() uses the
3844 * resource_list_delete() function to do most of the work. It calls
3845 * BUS_GET_RESOURCE_LIST() to find a suitable resource list to
3846 * edit.
3847 */
3848void
3849bus_generic_rl_delete_resource(device_t dev, device_t child, int type, int rid)
3850{
3851        struct resource_list *          rl = NULL;
3852
3853        rl = BUS_GET_RESOURCE_LIST(dev, child);
3854        if (!rl)
3855                return;
3856
3857        resource_list_delete(rl, type, rid);
3858
3859        return;
3860}
3861
3862/**
3863 * @brief Helper function for implementing BUS_RELEASE_RESOURCE().
3864 *
3865 * This implementation of BUS_RELEASE_RESOURCE() uses the
3866 * resource_list_release() function to do most of the work. It calls
3867 * BUS_GET_RESOURCE_LIST() to find a suitable resource list.
3868 */
3869int
3870bus_generic_rl_release_resource(device_t dev, device_t child, int type,
3871    int rid, struct resource *r)
3872{
3873        struct resource_list *          rl = NULL;
3874
3875        rl = BUS_GET_RESOURCE_LIST(dev, child);
3876        if (!rl)
3877                return (EINVAL);
3878
3879        return (resource_list_release(rl, dev, child, type, rid, r));
3880}
3881
3882/**
3883 * @brief Helper function for implementing BUS_ALLOC_RESOURCE().
3884 *
3885 * This implementation of BUS_ALLOC_RESOURCE() uses the
3886 * resource_list_alloc() function to do most of the work. It calls
3887 * BUS_GET_RESOURCE_LIST() to find a suitable resource list.
3888 */
3889struct resource *
3890bus_generic_rl_alloc_resource(device_t dev, device_t child, int type,
3891    int *rid, u_long start, u_long end, u_long count, u_int flags)
3892{
3893        struct resource_list *          rl = NULL;
3894
3895        rl = BUS_GET_RESOURCE_LIST(dev, child);
3896        if (!rl)
3897                return (NULL);
3898
3899        return (resource_list_alloc(rl, dev, child, type, rid,
3900            start, end, count, flags));
3901}
3902
3903/**
3904 * @brief Helper function for implementing BUS_CHILD_PRESENT().
3905 *
3906 * This simple implementation of BUS_CHILD_PRESENT() simply calls the
3907 * BUS_CHILD_PRESENT() method of the parent of @p dev.
3908 */
3909int
3910bus_generic_child_present(device_t dev, device_t child)
3911{
3912        return (BUS_CHILD_PRESENT(device_get_parent(dev), dev));
3913}
3914
3915/*
3916 * Some convenience functions to make it easier for drivers to use the
3917 * resource-management functions.  All these really do is hide the
3918 * indirection through the parent's method table, making for slightly
3919 * less-wordy code.  In the future, it might make sense for this code
3920 * to maintain some sort of a list of resources allocated by each device.
3921 */
3922
3923int
3924bus_alloc_resources(device_t dev, struct resource_spec *rs,
3925    struct resource **res)
3926{
3927        int i;
3928
3929        for (i = 0; rs[i].type != -1; i++)
3930                res[i] = NULL;
3931        for (i = 0; rs[i].type != -1; i++) {
3932                res[i] = bus_alloc_resource_any(dev,
3933                    rs[i].type, &rs[i].rid, rs[i].flags);
3934                if (res[i] == NULL && !(rs[i].flags & RF_OPTIONAL)) {
3935                        bus_release_resources(dev, rs, res);
3936                        return (ENXIO);
3937                }
3938        }
3939        return (0);
3940}
3941
3942void
3943bus_release_resources(device_t dev, const struct resource_spec *rs,
3944    struct resource **res)
3945{
3946        int i;
3947
3948        for (i = 0; rs[i].type != -1; i++)
3949                if (res[i] != NULL) {
3950                        bus_release_resource(
3951                            dev, rs[i].type, rs[i].rid, res[i]);
3952                        res[i] = NULL;
3953                }
3954}
3955
3956/**
3957 * @brief Wrapper function for BUS_ALLOC_RESOURCE().
3958 *
3959 * This function simply calls the BUS_ALLOC_RESOURCE() method of the
3960 * parent of @p dev.
3961 */
3962struct resource *
3963bus_alloc_resource(device_t dev, int type, int *rid, u_long start, u_long end,
3964    u_long count, u_int flags)
3965{
3966        if (dev->parent == NULL)
3967                return (NULL);
3968        return (BUS_ALLOC_RESOURCE(dev->parent, dev, type, rid, start, end,
3969            count, flags));
3970}
3971
3972/**
3973 * @brief Wrapper function for BUS_ADJUST_RESOURCE().
3974 *
3975 * This function simply calls the BUS_ADJUST_RESOURCE() method of the
3976 * parent of @p dev.
3977 */
3978int
3979bus_adjust_resource(device_t dev, int type, struct resource *r, u_long start,
3980    u_long end)
3981{
3982        if (dev->parent == NULL)
3983                return (EINVAL);
3984        return (BUS_ADJUST_RESOURCE(dev->parent, dev, type, r, start, end));
3985}
3986
3987/**
3988 * @brief Wrapper function for BUS_ACTIVATE_RESOURCE().
3989 *
3990 * This function simply calls the BUS_ACTIVATE_RESOURCE() method of the
3991 * parent of @p dev.
3992 */
3993int
3994bus_activate_resource(device_t dev, int type, int rid, struct resource *r)
3995{
3996        if (dev->parent == NULL)
3997                return (EINVAL);
3998        return (BUS_ACTIVATE_RESOURCE(dev->parent, dev, type, rid, r));
3999}
4000
4001/**
4002 * @brief Wrapper function for BUS_DEACTIVATE_RESOURCE().
4003 *
4004 * This function simply calls the BUS_DEACTIVATE_RESOURCE() method of the
4005 * parent of @p dev.
4006 */
4007int
4008bus_deactivate_resource(device_t dev, int type, int rid, struct resource *r)
4009{
4010        if (dev->parent == NULL)
4011                return (EINVAL);
4012        return (BUS_DEACTIVATE_RESOURCE(dev->parent, dev, type, rid, r));
4013}
4014
4015/**
4016 * @brief Wrapper function for BUS_RELEASE_RESOURCE().
4017 *
4018 * This function simply calls the BUS_RELEASE_RESOURCE() method of the
4019 * parent of @p dev.
4020 */
4021int
4022bus_release_resource(device_t dev, int type, int rid, struct resource *r)
4023{
4024        if (dev->parent == NULL)
4025                return (EINVAL);
4026        return (BUS_RELEASE_RESOURCE(dev->parent, dev, type, rid, r));
4027}
4028
4029/**
4030 * @brief Wrapper function for BUS_SETUP_INTR().
4031 *
4032 * This function simply calls the BUS_SETUP_INTR() method of the
4033 * parent of @p dev.
4034 */
4035int
4036bus_setup_intr(device_t dev, struct resource *r, int flags,
4037    driver_filter_t filter, driver_intr_t handler, void *arg, void **cookiep)
4038{
4039        int error;
4040
4041        if (dev->parent == NULL)
4042                return (EINVAL);
4043        error = BUS_SETUP_INTR(dev->parent, dev, r, flags, filter, handler,
4044            arg, cookiep);
4045        if (error != 0)
4046                return (error);
4047        if (handler != NULL && !(flags & INTR_MPSAFE))
4048                device_printf(dev, "[GIANT-LOCKED]\n");
4049        if (bootverbose && (flags & INTR_MPSAFE))
4050                device_printf(dev, "[MPSAFE]\n");
4051        if (filter != NULL) {
4052                if (handler == NULL)
4053                        device_printf(dev, "[FILTER]\n");
4054                else
4055                        device_printf(dev, "[FILTER+ITHREAD]\n");
4056        } else
4057                device_printf(dev, "[ITHREAD]\n");
4058        return (0);
4059}
4060
4061/**
4062 * @brief Wrapper function for BUS_TEARDOWN_INTR().
4063 *
4064 * This function simply calls the BUS_TEARDOWN_INTR() method of the
4065 * parent of @p dev.
4066 */
4067int
4068bus_teardown_intr(device_t dev, struct resource *r, void *cookie)
4069{
4070        if (dev->parent == NULL)
4071                return (EINVAL);
4072        return (BUS_TEARDOWN_INTR(dev->parent, dev, r, cookie));
4073}
4074
4075/**
4076 * @brief Wrapper function for BUS_BIND_INTR().
4077 *
4078 * This function simply calls the BUS_BIND_INTR() method of the
4079 * parent of @p dev.
4080 */
4081int
4082bus_bind_intr(device_t dev, struct resource *r, int cpu)
4083{
4084        if (dev->parent == NULL)
4085                return (EINVAL);
4086        return (BUS_BIND_INTR(dev->parent, dev, r, cpu));
4087}
4088
4089/**
4090 * @brief Wrapper function for BUS_DESCRIBE_INTR().
4091 *
4092 * This function first formats the requested description into a
4093 * temporary buffer and then calls the BUS_DESCRIBE_INTR() method of
4094 * the parent of @p dev.
4095 */
4096int
4097bus_describe_intr(device_t dev, struct resource *irq, void *cookie,
4098    const char *fmt, ...)
4099{
4100        va_list ap;
4101        char descr[MAXCOMLEN + 1];
4102
4103        if (dev->parent == NULL)
4104                return (EINVAL);
4105        va_start(ap, fmt);
4106        vsnprintf(descr, sizeof(descr), fmt, ap);
4107        va_end(ap);
4108        return (BUS_DESCRIBE_INTR(dev->parent, dev, irq, cookie, descr));
4109}
4110
4111/**
4112 * @brief Wrapper function for BUS_SET_RESOURCE().
4113 *
4114 * This function simply calls the BUS_SET_RESOURCE() method of the
4115 * parent of @p dev.
4116 */
4117int
4118bus_set_resource(device_t dev, int type, int rid,
4119    u_long start, u_long count)
4120{
4121        return (BUS_SET_RESOURCE(device_get_parent(dev), dev, type, rid,
4122            start, count));
4123}
4124
4125/**
4126 * @brief Wrapper function for BUS_GET_RESOURCE().
4127 *
4128 * This function simply calls the BUS_GET_RESOURCE() method of the
4129 * parent of @p dev.
4130 */
4131int
4132bus_get_resource(device_t dev, int type, int rid,
4133    u_long *startp, u_long *countp)
4134{
4135        return (BUS_GET_RESOURCE(device_get_parent(dev), dev, type, rid,
4136            startp, countp));
4137}
4138
4139/**
4140 * @brief Wrapper function for BUS_GET_RESOURCE().
4141 *
4142 * This function simply calls the BUS_GET_RESOURCE() method of the
4143 * parent of @p dev and returns the start value.
4144 */
4145u_long
4146bus_get_resource_start(device_t dev, int type, int rid)
4147{
4148        u_long start, count;
4149        int error;
4150
4151        error = BUS_GET_RESOURCE(device_get_parent(dev), dev, type, rid,
4152            &start, &count);
4153        if (error)
4154                return (0);
4155        return (start);
4156}
4157
4158/**
4159 * @brief Wrapper function for BUS_GET_RESOURCE().
4160 *
4161 * This function simply calls the BUS_GET_RESOURCE() method of the
4162 * parent of @p dev and returns the count value.
4163 */
4164u_long
4165bus_get_resource_count(device_t dev, int type, int rid)
4166{
4167        u_long start, count;
4168        int error;
4169
4170        error = BUS_GET_RESOURCE(device_get_parent(dev), dev, type, rid,
4171            &start, &count);
4172        if (error)
4173                return (0);
4174        return (count);
4175}
4176
4177/**
4178 * @brief Wrapper function for BUS_DELETE_RESOURCE().
4179 *
4180 * This function simply calls the BUS_DELETE_RESOURCE() method of the
4181 * parent of @p dev.
4182 */
4183void
4184bus_delete_resource(device_t dev, int type, int rid)
4185{
4186        BUS_DELETE_RESOURCE(device_get_parent(dev), dev, type, rid);
4187}
4188
4189/**
4190 * @brief Wrapper function for BUS_CHILD_PRESENT().
4191 *
4192 * This function simply calls the BUS_CHILD_PRESENT() method of the
4193 * parent of @p dev.
4194 */
4195int
4196bus_child_present(device_t child)
4197{
4198        return (BUS_CHILD_PRESENT(device_get_parent(child), child));
4199}
4200
4201/**
4202 * @brief Wrapper function for BUS_CHILD_PNPINFO_STR().
4203 *
4204 * This function simply calls the BUS_CHILD_PNPINFO_STR() method of the
4205 * parent of @p dev.
4206 */
4207int
4208bus_child_pnpinfo_str(device_t child, char *buf, size_t buflen)
4209{
4210        device_t parent;
4211
4212        parent = device_get_parent(child);
4213        if (parent == NULL) {
4214                *buf = '\0';
4215                return (0);
4216        }
4217        return (BUS_CHILD_PNPINFO_STR(parent, child, buf, buflen));
4218}
4219
4220/**
4221 * @brief Wrapper function for BUS_CHILD_LOCATION_STR().
4222 *
4223 * This function simply calls the BUS_CHILD_LOCATION_STR() method of the
4224 * parent of @p dev.
4225 */
4226int
4227bus_child_location_str(device_t child, char *buf, size_t buflen)
4228{
4229        device_t parent;
4230
4231        parent = device_get_parent(child);
4232        if (parent == NULL) {
4233                *buf = '\0';
4234                return (0);
4235        }
4236        return (BUS_CHILD_LOCATION_STR(parent, child, buf, buflen));
4237}
4238
4239/**
4240 * @brief Wrapper function for BUS_GET_DMA_TAG().
4241 *
4242 * This function simply calls the BUS_GET_DMA_TAG() method of the
4243 * parent of @p dev.
4244 */
4245bus_dma_tag_t
4246bus_get_dma_tag(device_t dev)
4247{
4248        device_t parent;
4249
4250        parent = device_get_parent(dev);
4251        if (parent == NULL)
4252                return (NULL);
4253        return (BUS_GET_DMA_TAG(parent, dev));
4254}
4255
4256/* Resume all devices and then notify userland that we're up again. */
4257static int
4258root_resume(device_t dev)
4259{
4260        int error;
4261
4262        error = bus_generic_resume(dev);
4263        if (error == 0)
4264                devctl_notify("kern", "power", "resume", NULL);
4265        return (error);
4266}
4267
4268static int
4269root_print_child(device_t dev, device_t child)
4270{
4271        int     retval = 0;
4272
4273        retval += bus_print_child_header(dev, child);
4274        retval += printf("\n");
4275
4276        return (retval);
4277}
4278
4279static int
4280root_setup_intr(device_t dev, device_t child, struct resource *irq, int flags,
4281    driver_filter_t *filter, driver_intr_t *intr, void *arg, void **cookiep)
4282{
4283        /*
4284         * If an interrupt mapping gets to here something bad has happened.
4285         */
4286        panic("root_setup_intr");
4287}
4288
4289/*
4290 * If we get here, assume that the device is permanant and really is
4291 * present in the system.  Removable bus drivers are expected to intercept
4292 * this call long before it gets here.  We return -1 so that drivers that
4293 * really care can check vs -1 or some ERRNO returned higher in the food
4294 * chain.
4295 */
4296static int
4297root_child_present(device_t dev, device_t child)
4298{
4299        return (-1);
4300}
4301
4302static kobj_method_t root_methods[] = {
4303        /* Device interface */
4304        KOBJMETHOD(device_shutdown,     bus_generic_shutdown),
4305        KOBJMETHOD(device_suspend,      bus_generic_suspend),
4306        KOBJMETHOD(device_resume,       root_resume),
4307
4308        /* Bus interface */
4309        KOBJMETHOD(bus_print_child,     root_print_child),
4310        KOBJMETHOD(bus_read_ivar,       bus_generic_read_ivar),
4311        KOBJMETHOD(bus_write_ivar,      bus_generic_write_ivar),
4312        KOBJMETHOD(bus_setup_intr,      root_setup_intr),
4313        KOBJMETHOD(bus_child_present,   root_child_present),
4314
4315        KOBJMETHOD_END
4316};
4317
4318static driver_t root_driver = {
4319        "root",
4320        root_methods,
4321        1,                      /* no softc */
4322};
4323
4324device_t        root_bus;
4325devclass_t      root_devclass;
4326
4327static int
4328root_bus_module_handler(module_t mod, int what, void* arg)
4329{
4330        switch (what) {
4331        case MOD_LOAD:
4332                TAILQ_INIT(&bus_data_devices);
4333                kobj_class_compile((kobj_class_t) &root_driver);
4334                root_bus = make_device(NULL, "root", 0);
4335                root_bus->desc = "System root bus";
4336                kobj_init((kobj_t) root_bus, (kobj_class_t) &root_driver);
4337                root_bus->driver = &root_driver;
4338                root_bus->state = DS_ATTACHED;
4339                root_devclass = devclass_find_internal("root", NULL, FALSE);
4340                devinit();
4341                return (0);
4342
4343        case MOD_SHUTDOWN:
4344                device_shutdown(root_bus);
4345                return (0);
4346        default:
4347                return (EOPNOTSUPP);
4348        }
4349
4350        return (0);
4351}
4352
4353static moduledata_t root_bus_mod = {
4354        "rootbus",
4355        root_bus_module_handler,
4356        NULL
4357};
4358DECLARE_MODULE(rootbus, root_bus_mod, SI_SUB_DRIVERS, SI_ORDER_FIRST);
4359
4360/**
4361 * @brief Automatically configure devices
4362 *
4363 * This function begins the autoconfiguration process by calling
4364 * device_probe_and_attach() for each child of the @c root0 device.
4365 */
4366void
4367root_bus_configure(void)
4368{
4369
4370        PDEBUG(("."));
4371
4372        /* Eventually this will be split up, but this is sufficient for now. */
4373        bus_set_pass(BUS_PASS_DEFAULT);
4374}
4375
4376/**
4377 * @brief Module handler for registering device drivers
4378 *
4379 * This module handler is used to automatically register device
4380 * drivers when modules are loaded. If @p what is MOD_LOAD, it calls
4381 * devclass_add_driver() for the driver described by the
4382 * driver_module_data structure pointed to by @p arg
4383 */
4384int
4385driver_module_handler(module_t mod, int what, void *arg)
4386{
4387        struct driver_module_data *dmd;
4388        devclass_t bus_devclass;
4389        kobj_class_t driver;
4390        int error, pass;
4391
4392        dmd = (struct driver_module_data *)arg;
4393        bus_devclass = devclass_find_internal(dmd->dmd_busname, NULL, TRUE);
4394        error = 0;
4395
4396        switch (what) {
4397        case MOD_LOAD:
4398                if (dmd->dmd_chainevh)
4399                        error = dmd->dmd_chainevh(mod,what,dmd->dmd_chainarg);
4400
4401                pass = dmd->dmd_pass;
4402                driver = dmd->dmd_driver;
4403                PDEBUG(("Loading module: driver %s on bus %s (pass %d)",
4404                    DRIVERNAME(driver), dmd->dmd_busname, pass));
4405                error = devclass_add_driver(bus_devclass, driver, pass,
4406                    dmd->dmd_devclass);
4407                break;
4408
4409        case MOD_UNLOAD:
4410                PDEBUG(("Unloading module: driver %s from bus %s",
4411                    DRIVERNAME(dmd->dmd_driver),
4412                    dmd->dmd_busname));
4413                error = devclass_delete_driver(bus_devclass,
4414                    dmd->dmd_driver);
4415
4416                if (!error && dmd->dmd_chainevh)
4417                        error = dmd->dmd_chainevh(mod,what,dmd->dmd_chainarg);
4418                break;
4419        case MOD_QUIESCE:
4420                PDEBUG(("Quiesce module: driver %s from bus %s",
4421                    DRIVERNAME(dmd->dmd_driver),
4422                    dmd->dmd_busname));
4423                error = devclass_quiesce_driver(bus_devclass,
4424                    dmd->dmd_driver);
4425
4426                if (!error && dmd->dmd_chainevh)
4427                        error = dmd->dmd_chainevh(mod,what,dmd->dmd_chainarg);
4428                break;
4429        default:
4430                error = EOPNOTSUPP;
4431                break;
4432        }
4433
4434        return (error);
4435}
4436
4437#ifndef __rtems__
4438/**
4439 * @brief Enumerate all hinted devices for this bus.
4440 *
4441 * Walks through the hints for this bus and calls the bus_hinted_child
4442 * routine for each one it fines.  It searches first for the specific
4443 * bus that's being probed for hinted children (eg isa0), and then for
4444 * generic children (eg isa).
4445 *
4446 * @param       dev     bus device to enumerate
4447 */
4448void
4449bus_enumerate_hinted_children(device_t bus)
4450{
4451        int i;
4452        const char *dname, *busname;
4453        int dunit;
4454
4455        /*
4456         * enumerate all devices on the specific bus
4457         */
4458        busname = device_get_nameunit(bus);
4459        i = 0;
4460        while (resource_find_match(&i, &dname, &dunit, "at", busname) == 0)
4461                BUS_HINTED_CHILD(bus, dname, dunit);
4462
4463        /*
4464         * and all the generic ones.
4465         */
4466        busname = device_get_name(bus);
4467        i = 0;
4468        while (resource_find_match(&i, &dname, &dunit, "at", busname) == 0)
4469                BUS_HINTED_CHILD(bus, dname, dunit);
4470}
4471#endif /* __rtems__ */
4472
4473#ifdef BUS_DEBUG
4474
4475/* the _short versions avoid iteration by not calling anything that prints
4476 * more than oneliners. I love oneliners.
4477 */
4478
4479static void
4480print_device_short(device_t dev, int indent)
4481{
4482        if (!dev)
4483                return;
4484
4485        indentprintf(("device %d: <%s> %sparent,%schildren,%s%s%s%s%s,%sivars,%ssoftc,busy=%d\n",
4486            dev->unit, dev->desc,
4487            (dev->parent? "":"no "),
4488            (TAILQ_EMPTY(&dev->children)? "no ":""),
4489            (dev->flags&DF_ENABLED? "enabled,":"disabled,"),
4490            (dev->flags&DF_FIXEDCLASS? "fixed,":""),
4491            (dev->flags&DF_WILDCARD? "wildcard,":""),
4492            (dev->flags&DF_DESCMALLOCED? "descmalloced,":""),
4493            (dev->flags&DF_REBID? "rebiddable,":""),
4494            (dev->ivars? "":"no "),
4495            (dev->softc? "":"no "),
4496            dev->busy));
4497}
4498
4499static void
4500print_device(device_t dev, int indent)
4501{
4502        if (!dev)
4503                return;
4504
4505        print_device_short(dev, indent);
4506
4507        indentprintf(("Parent:\n"));
4508        print_device_short(dev->parent, indent+1);
4509        indentprintf(("Driver:\n"));
4510        print_driver_short(dev->driver, indent+1);
4511        indentprintf(("Devclass:\n"));
4512        print_devclass_short(dev->devclass, indent+1);
4513}
4514
4515void
4516print_device_tree_short(device_t dev, int indent)
4517/* print the device and all its children (indented) */
4518{
4519        device_t child;
4520
4521        if (!dev)
4522                return;
4523
4524        print_device_short(dev, indent);
4525
4526        TAILQ_FOREACH(child, &dev->children, link) {
4527                print_device_tree_short(child, indent+1);
4528        }
4529}
4530
4531void
4532print_device_tree(device_t dev, int indent)
4533/* print the device and all its children (indented) */
4534{
4535        device_t child;
4536
4537        if (!dev)
4538                return;
4539
4540        print_device(dev, indent);
4541
4542        TAILQ_FOREACH(child, &dev->children, link) {
4543                print_device_tree(child, indent+1);
4544        }
4545}
4546
4547static void
4548print_driver_short(driver_t *driver, int indent)
4549{
4550        if (!driver)
4551                return;
4552
4553        indentprintf(("driver %s: softc size = %zd\n",
4554            driver->name, driver->size));
4555}
4556
4557static void
4558print_driver(driver_t *driver, int indent)
4559{
4560        if (!driver)
4561                return;
4562
4563        print_driver_short(driver, indent);
4564}
4565
4566static void
4567print_driver_list(driver_list_t drivers, int indent)
4568{
4569        driverlink_t driver;
4570
4571        TAILQ_FOREACH(driver, &drivers, link) {
4572                print_driver(driver->driver, indent);
4573        }
4574}
4575
4576static void
4577print_devclass_short(devclass_t dc, int indent)
4578{
4579        if ( !dc )
4580                return;
4581
4582        indentprintf(("devclass %s: max units = %d\n", dc->name, dc->maxunit));
4583}
4584
4585static void
4586print_devclass(devclass_t dc, int indent)
4587{
4588        int i;
4589
4590        if ( !dc )
4591                return;
4592
4593        print_devclass_short(dc, indent);
4594        indentprintf(("Drivers:\n"));
4595        print_driver_list(dc->drivers, indent+1);
4596
4597        indentprintf(("Devices:\n"));
4598        for (i = 0; i < dc->maxunit; i++)
4599                if (dc->devices[i])
4600                        print_device(dc->devices[i], indent+1);
4601}
4602
4603void
4604print_devclass_list_short(void)
4605{
4606        devclass_t dc;
4607
4608        printf("Short listing of devclasses, drivers & devices:\n");
4609        TAILQ_FOREACH(dc, &devclasses, link) {
4610                print_devclass_short(dc, 0);
4611        }
4612}
4613
4614void
4615print_devclass_list(void)
4616{
4617        devclass_t dc;
4618
4619        printf("Full listing of devclasses, drivers & devices:\n");
4620        TAILQ_FOREACH(dc, &devclasses, link) {
4621                print_devclass(dc, 0);
4622        }
4623}
4624
4625#endif
4626
4627#ifndef __rtems__
4628/*
4629 * User-space access to the device tree.
4630 *
4631 * We implement a small set of nodes:
4632 *
4633 * hw.bus                       Single integer read method to obtain the
4634 *                              current generation count.
4635 * hw.bus.devices               Reads the entire device tree in flat space.
4636 * hw.bus.rman                  Resource manager interface
4637 *
4638 * We might like to add the ability to scan devclasses and/or drivers to
4639 * determine what else is currently loaded/available.
4640 */
4641
4642static int
4643sysctl_bus(SYSCTL_HANDLER_ARGS)
4644{
4645        struct u_businfo        ubus;
4646
4647        ubus.ub_version = BUS_USER_VERSION;
4648        ubus.ub_generation = bus_data_generation;
4649
4650        return (SYSCTL_OUT(req, &ubus, sizeof(ubus)));
4651}
4652SYSCTL_NODE(_hw_bus, OID_AUTO, info, CTLFLAG_RW, sysctl_bus,
4653    "bus-related data");
4654
4655static int
4656sysctl_devices(SYSCTL_HANDLER_ARGS)
4657{
4658        int                     *name = (int *)arg1;
4659        u_int                   namelen = arg2;
4660        int                     index;
4661        struct device           *dev;
4662        struct u_device         udev;   /* XXX this is a bit big */
4663        int                     error;
4664
4665        if (namelen != 2)
4666                return (EINVAL);
4667
4668        if (bus_data_generation_check(name[0]))
4669                return (EINVAL);
4670
4671        index = name[1];
4672
4673        /*
4674         * Scan the list of devices, looking for the requested index.
4675         */
4676        TAILQ_FOREACH(dev, &bus_data_devices, devlink) {
4677                if (index-- == 0)
4678                        break;
4679        }
4680        if (dev == NULL)
4681                return (ENOENT);
4682
4683        /*
4684         * Populate the return array.
4685         */
4686        bzero(&udev, sizeof(udev));
4687        udev.dv_handle = (uintptr_t)dev;
4688        udev.dv_parent = (uintptr_t)dev->parent;
4689        if (dev->nameunit != NULL)
4690                strlcpy(udev.dv_name, dev->nameunit, sizeof(udev.dv_name));
4691        if (dev->desc != NULL)
4692                strlcpy(udev.dv_desc, dev->desc, sizeof(udev.dv_desc));
4693        if (dev->driver != NULL && dev->driver->name != NULL)
4694                strlcpy(udev.dv_drivername, dev->driver->name,
4695                    sizeof(udev.dv_drivername));
4696        bus_child_pnpinfo_str(dev, udev.dv_pnpinfo, sizeof(udev.dv_pnpinfo));
4697        bus_child_location_str(dev, udev.dv_location, sizeof(udev.dv_location));
4698        udev.dv_devflags = dev->devflags;
4699        udev.dv_flags = dev->flags;
4700        udev.dv_state = dev->state;
4701        error = SYSCTL_OUT(req, &udev, sizeof(udev));
4702        return (error);
4703}
4704
4705SYSCTL_NODE(_hw_bus, OID_AUTO, devices, CTLFLAG_RD, sysctl_devices,
4706    "system device tree");
4707#endif /* __rtems__ */
4708
4709int
4710bus_data_generation_check(int generation)
4711{
4712        if (generation != bus_data_generation)
4713                return (1);
4714
4715        /* XXX generate optimised lists here? */
4716        return (0);
4717}
4718
4719void
4720bus_data_generation_update(void)
4721{
4722        bus_data_generation++;
4723}
4724
4725#ifndef __rtems__
4726int
4727bus_free_resource(device_t dev, int type, struct resource *r)
4728{
4729        if (r == NULL)
4730                return (0);
4731        return (bus_release_resource(dev, type, rman_get_rid(r), r));
4732}
4733#endif /* __rtems__ */
Note: See TracBrowser for help on using the repository browser.