source: rtems-libbsd/freebsd/kern/subr_bus.c @ 03d4faf

4.115-freebsd-12freebsd-9.3
Last change on this file since 03d4faf was 03d4faf, checked in by Joel Sherrill <joel.sherrill@…>, on Mar 8, 2012 at 2:56:25 PM

Begin to trim rtems/ from include file paths - start with freebsd

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