]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/subr_bus.c
Update nvi to 2.2.0
[FreeBSD/FreeBSD.git] / sys / kern / subr_bus.c
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 1997,1998,2003 Doug Rabson
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31
32 #include "opt_bus.h"
33 #include "opt_ddb.h"
34
35 #include <sys/param.h>
36 #include <sys/conf.h>
37 #include <sys/domainset.h>
38 #include <sys/eventhandler.h>
39 #include <sys/filio.h>
40 #include <sys/lock.h>
41 #include <sys/kernel.h>
42 #include <sys/kobj.h>
43 #include <sys/limits.h>
44 #include <sys/malloc.h>
45 #include <sys/module.h>
46 #include <sys/mutex.h>
47 #include <sys/poll.h>
48 #include <sys/priv.h>
49 #include <sys/proc.h>
50 #include <sys/condvar.h>
51 #include <sys/queue.h>
52 #include <machine/bus.h>
53 #include <sys/random.h>
54 #include <sys/rman.h>
55 #include <sys/sbuf.h>
56 #include <sys/selinfo.h>
57 #include <sys/signalvar.h>
58 #include <sys/smp.h>
59 #include <sys/sysctl.h>
60 #include <sys/systm.h>
61 #include <sys/uio.h>
62 #include <sys/bus.h>
63 #include <sys/cpuset.h>
64
65 #include <net/vnet.h>
66
67 #include <machine/cpu.h>
68 #include <machine/stdarg.h>
69
70 #include <vm/uma.h>
71 #include <vm/vm.h>
72
73 #include <ddb/ddb.h>
74
75 SYSCTL_NODE(_hw, OID_AUTO, bus, CTLFLAG_RW | CTLFLAG_MPSAFE, NULL,
76     NULL);
77 SYSCTL_ROOT_NODE(OID_AUTO, dev, CTLFLAG_RW | CTLFLAG_MPSAFE, NULL,
78     NULL);
79
80 /*
81  * Used to attach drivers to devclasses.
82  */
83 typedef struct driverlink *driverlink_t;
84 struct driverlink {
85         kobj_class_t    driver;
86         TAILQ_ENTRY(driverlink) link;   /* list of drivers in devclass */
87         int             pass;
88         int             flags;
89 #define DL_DEFERRED_PROBE       1       /* Probe deferred on this */
90         TAILQ_ENTRY(driverlink) passlink;
91 };
92
93 /*
94  * Forward declarations
95  */
96 typedef TAILQ_HEAD(devclass_list, devclass) devclass_list_t;
97 typedef TAILQ_HEAD(driver_list, driverlink) driver_list_t;
98 typedef TAILQ_HEAD(device_list, device) device_list_t;
99
100 struct devclass {
101         TAILQ_ENTRY(devclass) link;
102         devclass_t      parent;         /* parent in devclass hierarchy */
103         driver_list_t   drivers;     /* bus devclasses store drivers for bus */
104         char            *name;
105         device_t        *devices;       /* array of devices indexed by unit */
106         int             maxunit;        /* size of devices array */
107         int             flags;
108 #define DC_HAS_CHILDREN         1
109
110         struct sysctl_ctx_list sysctl_ctx;
111         struct sysctl_oid *sysctl_tree;
112 };
113
114 /**
115  * @brief Implementation of device.
116  */
117 struct device {
118         /*
119          * A device is a kernel object. The first field must be the
120          * current ops table for the object.
121          */
122         KOBJ_FIELDS;
123
124         /*
125          * Device hierarchy.
126          */
127         TAILQ_ENTRY(device)     link;   /**< list of devices in parent */
128         TAILQ_ENTRY(device)     devlink; /**< global device list membership */
129         device_t        parent;         /**< parent of this device  */
130         device_list_t   children;       /**< list of child devices */
131
132         /*
133          * Details of this device.
134          */
135         driver_t        *driver;        /**< current driver */
136         devclass_t      devclass;       /**< current device class */
137         int             unit;           /**< current unit number */
138         char*           nameunit;       /**< name+unit e.g. foodev0 */
139         char*           desc;           /**< driver specific description */
140         int             busy;           /**< count of calls to device_busy() */
141         device_state_t  state;          /**< current device state  */
142         uint32_t        devflags;       /**< api level flags for device_get_flags() */
143         u_int           flags;          /**< internal device flags  */
144         u_int   order;                  /**< order from device_add_child_ordered() */
145         void    *ivars;                 /**< instance variables  */
146         void    *softc;                 /**< current driver's variables  */
147
148         struct sysctl_ctx_list sysctl_ctx; /**< state for sysctl variables  */
149         struct sysctl_oid *sysctl_tree; /**< state for sysctl variables */
150 };
151
152 static MALLOC_DEFINE(M_BUS, "bus", "Bus data structures");
153 static MALLOC_DEFINE(M_BUS_SC, "bus-sc", "Bus data structures, softc");
154
155 EVENTHANDLER_LIST_DEFINE(device_attach);
156 EVENTHANDLER_LIST_DEFINE(device_detach);
157 EVENTHANDLER_LIST_DEFINE(dev_lookup);
158
159 static int bus_child_location_sb(device_t child, struct sbuf *sb);
160 static int bus_child_pnpinfo_sb(device_t child, struct sbuf *sb);
161 static void devctl2_init(void);
162 static bool device_frozen;
163
164 #define DRIVERNAME(d)   ((d)? d->name : "no driver")
165 #define DEVCLANAME(d)   ((d)? d->name : "no devclass")
166
167 #ifdef BUS_DEBUG
168
169 static int bus_debug = 1;
170 SYSCTL_INT(_debug, OID_AUTO, bus_debug, CTLFLAG_RWTUN, &bus_debug, 0,
171     "Bus debug level");
172 #define PDEBUG(a)       if (bus_debug) {printf("%s:%d: ", __func__, __LINE__), printf a; printf("\n");}
173 #define DEVICENAME(d)   ((d)? device_get_name(d): "no device")
174
175 /**
176  * Produce the indenting, indent*2 spaces plus a '.' ahead of that to
177  * prevent syslog from deleting initial spaces
178  */
179 #define indentprintf(p) do { int iJ; printf("."); for (iJ=0; iJ<indent; iJ++) printf("  "); printf p ; } while (0)
180
181 static void print_device_short(device_t dev, int indent);
182 static void print_device(device_t dev, int indent);
183 void print_device_tree_short(device_t dev, int indent);
184 void print_device_tree(device_t dev, int indent);
185 static void print_driver_short(driver_t *driver, int indent);
186 static void print_driver(driver_t *driver, int indent);
187 static void print_driver_list(driver_list_t drivers, int indent);
188 static void print_devclass_short(devclass_t dc, int indent);
189 static void print_devclass(devclass_t dc, int indent);
190 void print_devclass_list_short(void);
191 void print_devclass_list(void);
192
193 #else
194 /* Make the compiler ignore the function calls */
195 #define PDEBUG(a)                       /* nop */
196 #define DEVICENAME(d)                   /* nop */
197
198 #define print_device_short(d,i)         /* nop */
199 #define print_device(d,i)               /* nop */
200 #define print_device_tree_short(d,i)    /* nop */
201 #define print_device_tree(d,i)          /* nop */
202 #define print_driver_short(d,i)         /* nop */
203 #define print_driver(d,i)               /* nop */
204 #define print_driver_list(d,i)          /* nop */
205 #define print_devclass_short(d,i)       /* nop */
206 #define print_devclass(d,i)             /* nop */
207 #define print_devclass_list_short()     /* nop */
208 #define print_devclass_list()           /* nop */
209 #endif
210
211 /*
212  * dev sysctl tree
213  */
214
215 enum {
216         DEVCLASS_SYSCTL_PARENT,
217 };
218
219 static int
220 devclass_sysctl_handler(SYSCTL_HANDLER_ARGS)
221 {
222         devclass_t dc = (devclass_t)arg1;
223         const char *value;
224
225         switch (arg2) {
226         case DEVCLASS_SYSCTL_PARENT:
227                 value = dc->parent ? dc->parent->name : "";
228                 break;
229         default:
230                 return (EINVAL);
231         }
232         return (SYSCTL_OUT_STR(req, value));
233 }
234
235 static void
236 devclass_sysctl_init(devclass_t dc)
237 {
238         if (dc->sysctl_tree != NULL)
239                 return;
240         sysctl_ctx_init(&dc->sysctl_ctx);
241         dc->sysctl_tree = SYSCTL_ADD_NODE(&dc->sysctl_ctx,
242             SYSCTL_STATIC_CHILDREN(_dev), OID_AUTO, dc->name,
243             CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
244         SYSCTL_ADD_PROC(&dc->sysctl_ctx, SYSCTL_CHILDREN(dc->sysctl_tree),
245             OID_AUTO, "%parent",
246             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_NEEDGIANT,
247             dc, DEVCLASS_SYSCTL_PARENT, devclass_sysctl_handler, "A",
248             "parent class");
249 }
250
251 enum {
252         DEVICE_SYSCTL_DESC,
253         DEVICE_SYSCTL_DRIVER,
254         DEVICE_SYSCTL_LOCATION,
255         DEVICE_SYSCTL_PNPINFO,
256         DEVICE_SYSCTL_PARENT,
257 };
258
259 static int
260 device_sysctl_handler(SYSCTL_HANDLER_ARGS)
261 {
262         struct sbuf sb;
263         device_t dev = (device_t)arg1;
264         int error;
265
266         sbuf_new_for_sysctl(&sb, NULL, 1024, req);
267         sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
268         switch (arg2) {
269         case DEVICE_SYSCTL_DESC:
270                 sbuf_cat(&sb, dev->desc ? dev->desc : "");
271                 break;
272         case DEVICE_SYSCTL_DRIVER:
273                 sbuf_cat(&sb, dev->driver ? dev->driver->name : "");
274                 break;
275         case DEVICE_SYSCTL_LOCATION:
276                 bus_child_location_sb(dev, &sb);
277                 break;
278         case DEVICE_SYSCTL_PNPINFO:
279                 bus_child_pnpinfo_sb(dev, &sb);
280                 break;
281         case DEVICE_SYSCTL_PARENT:
282                 sbuf_cat(&sb, dev->parent ? dev->parent->nameunit : "");
283                 break;
284         default:
285                 sbuf_delete(&sb);
286                 return (EINVAL);
287         }
288         error = sbuf_finish(&sb);
289         sbuf_delete(&sb);
290         return (error);
291 }
292
293 static void
294 device_sysctl_init(device_t dev)
295 {
296         devclass_t dc = dev->devclass;
297         int domain;
298
299         if (dev->sysctl_tree != NULL)
300                 return;
301         devclass_sysctl_init(dc);
302         sysctl_ctx_init(&dev->sysctl_ctx);
303         dev->sysctl_tree = SYSCTL_ADD_NODE_WITH_LABEL(&dev->sysctl_ctx,
304             SYSCTL_CHILDREN(dc->sysctl_tree), OID_AUTO,
305             dev->nameunit + strlen(dc->name),
306             CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "", "device_index");
307         SYSCTL_ADD_PROC(&dev->sysctl_ctx, SYSCTL_CHILDREN(dev->sysctl_tree),
308             OID_AUTO, "%desc", CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_NEEDGIANT,
309             dev, DEVICE_SYSCTL_DESC, device_sysctl_handler, "A",
310             "device description");
311         SYSCTL_ADD_PROC(&dev->sysctl_ctx, SYSCTL_CHILDREN(dev->sysctl_tree),
312             OID_AUTO, "%driver",
313             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_NEEDGIANT,
314             dev, DEVICE_SYSCTL_DRIVER, device_sysctl_handler, "A",
315             "device driver name");
316         SYSCTL_ADD_PROC(&dev->sysctl_ctx, SYSCTL_CHILDREN(dev->sysctl_tree),
317             OID_AUTO, "%location",
318             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_NEEDGIANT,
319             dev, DEVICE_SYSCTL_LOCATION, device_sysctl_handler, "A",
320             "device location relative to parent");
321         SYSCTL_ADD_PROC(&dev->sysctl_ctx, SYSCTL_CHILDREN(dev->sysctl_tree),
322             OID_AUTO, "%pnpinfo",
323             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_NEEDGIANT,
324             dev, DEVICE_SYSCTL_PNPINFO, device_sysctl_handler, "A",
325             "device identification");
326         SYSCTL_ADD_PROC(&dev->sysctl_ctx, SYSCTL_CHILDREN(dev->sysctl_tree),
327             OID_AUTO, "%parent",
328             CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_NEEDGIANT,
329             dev, DEVICE_SYSCTL_PARENT, device_sysctl_handler, "A",
330             "parent device");
331         if (bus_get_domain(dev, &domain) == 0)
332                 SYSCTL_ADD_INT(&dev->sysctl_ctx,
333                     SYSCTL_CHILDREN(dev->sysctl_tree), OID_AUTO, "%domain",
334                     CTLFLAG_RD, NULL, domain, "NUMA domain");
335 }
336
337 static void
338 device_sysctl_update(device_t dev)
339 {
340         devclass_t dc = dev->devclass;
341
342         if (dev->sysctl_tree == NULL)
343                 return;
344         sysctl_rename_oid(dev->sysctl_tree, dev->nameunit + strlen(dc->name));
345 }
346
347 static void
348 device_sysctl_fini(device_t dev)
349 {
350         if (dev->sysctl_tree == NULL)
351                 return;
352         sysctl_ctx_free(&dev->sysctl_ctx);
353         dev->sysctl_tree = NULL;
354 }
355
356 /*
357  * /dev/devctl implementation
358  */
359
360 /*
361  * This design allows only one reader for /dev/devctl.  This is not desirable
362  * in the long run, but will get a lot of hair out of this implementation.
363  * Maybe we should make this device a clonable device.
364  *
365  * Also note: we specifically do not attach a device to the device_t tree
366  * to avoid potential chicken and egg problems.  One could argue that all
367  * of this belongs to the root node.
368  */
369
370 #define DEVCTL_DEFAULT_QUEUE_LEN 1000
371 static int sysctl_devctl_queue(SYSCTL_HANDLER_ARGS);
372 static int devctl_queue_length = DEVCTL_DEFAULT_QUEUE_LEN;
373 SYSCTL_PROC(_hw_bus, OID_AUTO, devctl_queue, CTLTYPE_INT | CTLFLAG_RWTUN |
374     CTLFLAG_MPSAFE, NULL, 0, sysctl_devctl_queue, "I", "devctl queue length");
375
376 static d_open_t         devopen;
377 static d_close_t        devclose;
378 static d_read_t         devread;
379 static d_ioctl_t        devioctl;
380 static d_poll_t         devpoll;
381 static d_kqfilter_t     devkqfilter;
382
383 static struct cdevsw dev_cdevsw = {
384         .d_version =    D_VERSION,
385         .d_open =       devopen,
386         .d_close =      devclose,
387         .d_read =       devread,
388         .d_ioctl =      devioctl,
389         .d_poll =       devpoll,
390         .d_kqfilter =   devkqfilter,
391         .d_name =       "devctl",
392 };
393
394 #define DEVCTL_BUFFER (1024 - sizeof(void *))
395 struct dev_event_info {
396         STAILQ_ENTRY(dev_event_info) dei_link;
397         char dei_data[DEVCTL_BUFFER];
398 };
399
400 STAILQ_HEAD(devq, dev_event_info);
401
402 static struct dev_softc {
403         int             inuse;
404         int             nonblock;
405         int             queued;
406         int             async;
407         struct mtx      mtx;
408         struct cv       cv;
409         struct selinfo  sel;
410         struct devq     devq;
411         struct sigio    *sigio;
412         uma_zone_t      zone;
413 } devsoftc;
414
415 static void     filt_devctl_detach(struct knote *kn);
416 static int      filt_devctl_read(struct knote *kn, long hint);
417
418 struct filterops devctl_rfiltops = {
419         .f_isfd = 1,
420         .f_detach = filt_devctl_detach,
421         .f_event = filt_devctl_read,
422 };
423
424 static struct cdev *devctl_dev;
425
426 static void
427 devinit(void)
428 {
429         devctl_dev = make_dev_credf(MAKEDEV_ETERNAL, &dev_cdevsw, 0, NULL,
430             UID_ROOT, GID_WHEEL, 0600, "devctl");
431         mtx_init(&devsoftc.mtx, "dev mtx", "devd", MTX_DEF);
432         cv_init(&devsoftc.cv, "dev cv");
433         STAILQ_INIT(&devsoftc.devq);
434         knlist_init_mtx(&devsoftc.sel.si_note, &devsoftc.mtx);
435         if (devctl_queue_length > 0) {
436                 devsoftc.zone = uma_zcreate("DEVCTL", sizeof(struct dev_event_info),
437                     NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
438                 uma_prealloc(devsoftc.zone, devctl_queue_length);
439         }
440         devctl2_init();
441 }
442
443 static int
444 devopen(struct cdev *dev, int oflags, int devtype, struct thread *td)
445 {
446         mtx_lock(&devsoftc.mtx);
447         if (devsoftc.inuse) {
448                 mtx_unlock(&devsoftc.mtx);
449                 return (EBUSY);
450         }
451         /* move to init */
452         devsoftc.inuse = 1;
453         mtx_unlock(&devsoftc.mtx);
454         return (0);
455 }
456
457 static int
458 devclose(struct cdev *dev, int fflag, int devtype, struct thread *td)
459 {
460         mtx_lock(&devsoftc.mtx);
461         devsoftc.inuse = 0;
462         devsoftc.nonblock = 0;
463         devsoftc.async = 0;
464         cv_broadcast(&devsoftc.cv);
465         funsetown(&devsoftc.sigio);
466         mtx_unlock(&devsoftc.mtx);
467         return (0);
468 }
469
470 /*
471  * The read channel for this device is used to report changes to
472  * userland in realtime.  We are required to free the data as well as
473  * the n1 object because we allocate them separately.  Also note that
474  * we return one record at a time.  If you try to read this device a
475  * character at a time, you will lose the rest of the data.  Listening
476  * programs are expected to cope.
477  */
478 static int
479 devread(struct cdev *dev, struct uio *uio, int ioflag)
480 {
481         struct dev_event_info *n1;
482         int rv;
483
484         mtx_lock(&devsoftc.mtx);
485         while (STAILQ_EMPTY(&devsoftc.devq)) {
486                 if (devsoftc.nonblock) {
487                         mtx_unlock(&devsoftc.mtx);
488                         return (EAGAIN);
489                 }
490                 rv = cv_wait_sig(&devsoftc.cv, &devsoftc.mtx);
491                 if (rv) {
492                         /*
493                          * Need to translate ERESTART to EINTR here? -- jake
494                          */
495                         mtx_unlock(&devsoftc.mtx);
496                         return (rv);
497                 }
498         }
499         n1 = STAILQ_FIRST(&devsoftc.devq);
500         STAILQ_REMOVE_HEAD(&devsoftc.devq, dei_link);
501         devsoftc.queued--;
502         mtx_unlock(&devsoftc.mtx);
503         rv = uiomove(n1->dei_data, strlen(n1->dei_data), uio);
504         uma_zfree(devsoftc.zone, n1);
505         return (rv);
506 }
507
508 static  int
509 devioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag, struct thread *td)
510 {
511         switch (cmd) {
512         case FIONBIO:
513                 if (*(int*)data)
514                         devsoftc.nonblock = 1;
515                 else
516                         devsoftc.nonblock = 0;
517                 return (0);
518         case FIOASYNC:
519                 if (*(int*)data)
520                         devsoftc.async = 1;
521                 else
522                         devsoftc.async = 0;
523                 return (0);
524         case FIOSETOWN:
525                 return fsetown(*(int *)data, &devsoftc.sigio);
526         case FIOGETOWN:
527                 *(int *)data = fgetown(&devsoftc.sigio);
528                 return (0);
529
530                 /* (un)Support for other fcntl() calls. */
531         case FIOCLEX:
532         case FIONCLEX:
533         case FIONREAD:
534         default:
535                 break;
536         }
537         return (ENOTTY);
538 }
539
540 static  int
541 devpoll(struct cdev *dev, int events, struct thread *td)
542 {
543         int     revents = 0;
544
545         mtx_lock(&devsoftc.mtx);
546         if (events & (POLLIN | POLLRDNORM)) {
547                 if (!STAILQ_EMPTY(&devsoftc.devq))
548                         revents = events & (POLLIN | POLLRDNORM);
549                 else
550                         selrecord(td, &devsoftc.sel);
551         }
552         mtx_unlock(&devsoftc.mtx);
553
554         return (revents);
555 }
556
557 static int
558 devkqfilter(struct cdev *dev, struct knote *kn)
559 {
560         int error;
561
562         if (kn->kn_filter == EVFILT_READ) {
563                 kn->kn_fop = &devctl_rfiltops;
564                 knlist_add(&devsoftc.sel.si_note, kn, 0);
565                 error = 0;
566         } else
567                 error = EINVAL;
568         return (error);
569 }
570
571 static void
572 filt_devctl_detach(struct knote *kn)
573 {
574         knlist_remove(&devsoftc.sel.si_note, kn, 0);
575 }
576
577 static int
578 filt_devctl_read(struct knote *kn, long hint)
579 {
580         kn->kn_data = devsoftc.queued;
581         return (kn->kn_data != 0);
582 }
583
584 /**
585  * @brief Return whether the userland process is running
586  */
587 boolean_t
588 devctl_process_running(void)
589 {
590         return (devsoftc.inuse == 1);
591 }
592
593 static struct dev_event_info *
594 devctl_alloc_dei(void)
595 {
596         struct dev_event_info *dei = NULL;
597
598         mtx_lock(&devsoftc.mtx);
599         if (devctl_queue_length == 0)
600                 goto out;
601         if (devctl_queue_length == devsoftc.queued) {
602                 dei = STAILQ_FIRST(&devsoftc.devq);
603                 STAILQ_REMOVE_HEAD(&devsoftc.devq, dei_link);
604                 devsoftc.queued--;
605         } else {
606                 /* dei can't be NULL -- we know we have at least one in the zone */
607                 dei = uma_zalloc(devsoftc.zone, M_NOWAIT);
608                 MPASS(dei != NULL);
609         }
610         *dei->dei_data = '\0';
611 out:
612         mtx_unlock(&devsoftc.mtx);
613         return (dei);
614 }
615
616 static struct dev_event_info *
617 devctl_alloc_dei_sb(struct sbuf *sb)
618 {
619         struct dev_event_info *dei;
620
621         dei = devctl_alloc_dei();
622         if (dei != NULL)
623                 sbuf_new(sb, dei->dei_data, sizeof(dei->dei_data), SBUF_FIXEDLEN);
624         return (dei);
625 }
626
627 static void
628 devctl_free_dei(struct dev_event_info *dei)
629 {
630         uma_zfree(devsoftc.zone, dei);
631 }
632
633 static void
634 devctl_queue(struct dev_event_info *dei)
635 {
636         mtx_lock(&devsoftc.mtx);
637         STAILQ_INSERT_TAIL(&devsoftc.devq, dei, dei_link);
638         devsoftc.queued++;
639         cv_broadcast(&devsoftc.cv);
640         KNOTE_LOCKED(&devsoftc.sel.si_note, 0);
641         mtx_unlock(&devsoftc.mtx);
642         selwakeup(&devsoftc.sel);
643         if (devsoftc.async && devsoftc.sigio != NULL)
644                 pgsigio(&devsoftc.sigio, SIGIO, 0);
645 }
646
647 /**
648  * @brief Send a 'notification' to userland, using standard ways
649  */
650 void
651 devctl_notify(const char *system, const char *subsystem, const char *type,
652     const char *data)
653 {
654         struct dev_event_info *dei;
655         struct sbuf sb;
656
657         if (system == NULL || subsystem == NULL || type == NULL)
658                 return;
659         dei = devctl_alloc_dei_sb(&sb);
660         if (dei == NULL)
661                 return;
662         sbuf_cpy(&sb, "!system=");
663         sbuf_cat(&sb, system);
664         sbuf_cat(&sb, " subsystem=");
665         sbuf_cat(&sb, subsystem);
666         sbuf_cat(&sb, " type=");
667         sbuf_cat(&sb, type);
668         if (data != NULL) {
669                 sbuf_putc(&sb, ' ');
670                 sbuf_cat(&sb, data);
671         }
672         sbuf_putc(&sb, '\n');
673         if (sbuf_finish(&sb) != 0)
674                 devctl_free_dei(dei);   /* overflow -> drop it */
675         else
676                 devctl_queue(dei);
677 }
678
679 /*
680  * Common routine that tries to make sending messages as easy as possible.
681  * We allocate memory for the data, copy strings into that, but do not
682  * free it unless there's an error.  The dequeue part of the driver should
683  * free the data.  We don't send data when the device is disabled.  We do
684  * send data, even when we have no listeners, because we wish to avoid
685  * races relating to startup and restart of listening applications.
686  *
687  * devaddq is designed to string together the type of event, with the
688  * object of that event, plus the plug and play info and location info
689  * for that event.  This is likely most useful for devices, but less
690  * useful for other consumers of this interface.  Those should use
691  * the devctl_notify() interface instead.
692  *
693  * Output: 
694  *      ${type}${what} at $(location dev) $(pnp-info dev) on $(parent dev)
695  */
696 static void
697 devaddq(const char *type, const char *what, device_t dev)
698 {
699         struct dev_event_info *dei;
700         const char *parstr;
701         struct sbuf sb;
702
703         dei = devctl_alloc_dei_sb(&sb);
704         if (dei == NULL)
705                 return;
706         sbuf_cpy(&sb, type);
707         sbuf_cat(&sb, what);
708         sbuf_cat(&sb, " at ");
709
710         /* Add in the location */
711         bus_child_location_sb(dev, &sb);
712         sbuf_putc(&sb, ' ');
713
714         /* Add in pnpinfo */
715         bus_child_pnpinfo_sb(dev, &sb);
716
717         /* Get the parent of this device, or / if high enough in the tree. */
718         if (device_get_parent(dev) == NULL)
719                 parstr = ".";   /* Or '/' ? */
720         else
721                 parstr = device_get_nameunit(device_get_parent(dev));
722         sbuf_cat(&sb, " on ");
723         sbuf_cat(&sb, parstr);
724         sbuf_putc(&sb, '\n');
725         if (sbuf_finish(&sb) != 0)
726                 goto bad;
727         devctl_queue(dei);
728         return;
729 bad:
730         devctl_free_dei(dei);
731 }
732
733 /*
734  * A device was added to the tree.  We are called just after it successfully
735  * attaches (that is, probe and attach success for this device).  No call
736  * is made if a device is merely parented into the tree.  See devnomatch
737  * if probe fails.  If attach fails, no notification is sent (but maybe
738  * we should have a different message for this).
739  */
740 static void
741 devadded(device_t dev)
742 {
743         devaddq("+", device_get_nameunit(dev), dev);
744 }
745
746 /*
747  * A device was removed from the tree.  We are called just before this
748  * happens.
749  */
750 static void
751 devremoved(device_t dev)
752 {
753         devaddq("-", device_get_nameunit(dev), dev);
754 }
755
756 /*
757  * Called when there's no match for this device.  This is only called
758  * the first time that no match happens, so we don't keep getting this
759  * message.  Should that prove to be undesirable, we can change it.
760  * This is called when all drivers that can attach to a given bus
761  * decline to accept this device.  Other errors may not be detected.
762  */
763 static void
764 devnomatch(device_t dev)
765 {
766         devaddq("?", "", dev);
767 }
768
769 static int
770 sysctl_devctl_queue(SYSCTL_HANDLER_ARGS)
771 {
772         int q, error;
773
774         q = devctl_queue_length;
775         error = sysctl_handle_int(oidp, &q, 0, req);
776         if (error || !req->newptr)
777                 return (error);
778         if (q < 0)
779                 return (EINVAL);
780
781         /*
782          * When set as a tunable, we've not yet initialized the mutex.
783          * It is safe to just assign to devctl_queue_length and return
784          * as we're racing no one. We'll use whatever value set in
785          * devinit.
786          */
787         if (!mtx_initialized(&devsoftc.mtx)) {
788                 devctl_queue_length = q;
789                 return (0);
790         }
791
792         /*
793          * XXX It's hard to grow or shrink the UMA zone. Only allow
794          * disabling the queue size for the moment until underlying
795          * UMA issues can be sorted out.
796          */
797         if (q != 0)
798                 return (EINVAL);
799         if (q == devctl_queue_length)
800                 return (0);
801         mtx_lock(&devsoftc.mtx);
802         devctl_queue_length = 0;
803         uma_zdestroy(devsoftc.zone);
804         devsoftc.zone = 0;
805         mtx_unlock(&devsoftc.mtx);
806         return (0);
807 }
808
809 /**
810  * @brief safely quotes strings that might have double quotes in them.
811  *
812  * The devctl protocol relies on quoted strings having matching quotes.
813  * This routine quotes any internal quotes so the resulting string
814  * is safe to pass to snprintf to construct, for example pnp info strings.
815  *
816  * @param sb    sbuf to place the characters into
817  * @param src   Original buffer.
818  */
819 void
820 devctl_safe_quote_sb(struct sbuf *sb, const char *src)
821 {
822         while (*src != '\0') {
823                 if (*src == '"' || *src == '\\')
824                         sbuf_putc(sb, '\\');
825                 sbuf_putc(sb, *src++);
826         }
827 }
828
829 /* End of /dev/devctl code */
830
831 static TAILQ_HEAD(,device)      bus_data_devices;
832 static int bus_data_generation = 1;
833
834 static kobj_method_t null_methods[] = {
835         KOBJMETHOD_END
836 };
837
838 DEFINE_CLASS(null, null_methods, 0);
839
840 /*
841  * Bus pass implementation
842  */
843
844 static driver_list_t passes = TAILQ_HEAD_INITIALIZER(passes);
845 int bus_current_pass = BUS_PASS_ROOT;
846
847 /**
848  * @internal
849  * @brief Register the pass level of a new driver attachment
850  *
851  * Register a new driver attachment's pass level.  If no driver
852  * attachment with the same pass level has been added, then @p new
853  * will be added to the global passes list.
854  *
855  * @param new           the new driver attachment
856  */
857 static void
858 driver_register_pass(struct driverlink *new)
859 {
860         struct driverlink *dl;
861
862         /* We only consider pass numbers during boot. */
863         if (bus_current_pass == BUS_PASS_DEFAULT)
864                 return;
865
866         /*
867          * Walk the passes list.  If we already know about this pass
868          * then there is nothing to do.  If we don't, then insert this
869          * driver link into the list.
870          */
871         TAILQ_FOREACH(dl, &passes, passlink) {
872                 if (dl->pass < new->pass)
873                         continue;
874                 if (dl->pass == new->pass)
875                         return;
876                 TAILQ_INSERT_BEFORE(dl, new, passlink);
877                 return;
878         }
879         TAILQ_INSERT_TAIL(&passes, new, passlink);
880 }
881
882 /**
883  * @brief Raise the current bus pass
884  *
885  * Raise the current bus pass level to @p pass.  Call the BUS_NEW_PASS()
886  * method on the root bus to kick off a new device tree scan for each
887  * new pass level that has at least one driver.
888  */
889 void
890 bus_set_pass(int pass)
891 {
892         struct driverlink *dl;
893
894         if (bus_current_pass > pass)
895                 panic("Attempt to lower bus pass level");
896
897         TAILQ_FOREACH(dl, &passes, passlink) {
898                 /* Skip pass values below the current pass level. */
899                 if (dl->pass <= bus_current_pass)
900                         continue;
901
902                 /*
903                  * Bail once we hit a driver with a pass level that is
904                  * too high.
905                  */
906                 if (dl->pass > pass)
907                         break;
908
909                 /*
910                  * Raise the pass level to the next level and rescan
911                  * the tree.
912                  */
913                 bus_current_pass = dl->pass;
914                 BUS_NEW_PASS(root_bus);
915         }
916
917         /*
918          * If there isn't a driver registered for the requested pass,
919          * then bus_current_pass might still be less than 'pass'.  Set
920          * it to 'pass' in that case.
921          */
922         if (bus_current_pass < pass)
923                 bus_current_pass = pass;
924         KASSERT(bus_current_pass == pass, ("Failed to update bus pass level"));
925 }
926
927 /*
928  * Devclass implementation
929  */
930
931 static devclass_list_t devclasses = TAILQ_HEAD_INITIALIZER(devclasses);
932
933 /**
934  * @internal
935  * @brief Find or create a device class
936  *
937  * If a device class with the name @p classname exists, return it,
938  * otherwise if @p create is non-zero create and return a new device
939  * class.
940  *
941  * If @p parentname is non-NULL, the parent of the devclass is set to
942  * the devclass of that name.
943  *
944  * @param classname     the devclass name to find or create
945  * @param parentname    the parent devclass name or @c NULL
946  * @param create        non-zero to create a devclass
947  */
948 static devclass_t
949 devclass_find_internal(const char *classname, const char *parentname,
950                        int create)
951 {
952         devclass_t dc;
953
954         PDEBUG(("looking for %s", classname));
955         if (!classname)
956                 return (NULL);
957
958         TAILQ_FOREACH(dc, &devclasses, link) {
959                 if (!strcmp(dc->name, classname))
960                         break;
961         }
962
963         if (create && !dc) {
964                 PDEBUG(("creating %s", classname));
965                 dc = malloc(sizeof(struct devclass) + strlen(classname) + 1,
966                     M_BUS, M_NOWAIT | M_ZERO);
967                 if (!dc)
968                         return (NULL);
969                 dc->parent = NULL;
970                 dc->name = (char*) (dc + 1);
971                 strcpy(dc->name, classname);
972                 TAILQ_INIT(&dc->drivers);
973                 TAILQ_INSERT_TAIL(&devclasses, dc, link);
974
975                 bus_data_generation_update();
976         }
977
978         /*
979          * If a parent class is specified, then set that as our parent so
980          * that this devclass will support drivers for the parent class as
981          * well.  If the parent class has the same name don't do this though
982          * as it creates a cycle that can trigger an infinite loop in
983          * device_probe_child() if a device exists for which there is no
984          * suitable driver.
985          */
986         if (parentname && dc && !dc->parent &&
987             strcmp(classname, parentname) != 0) {
988                 dc->parent = devclass_find_internal(parentname, NULL, TRUE);
989                 dc->parent->flags |= DC_HAS_CHILDREN;
990         }
991
992         return (dc);
993 }
994
995 /**
996  * @brief Create a device class
997  *
998  * If a device class with the name @p classname exists, return it,
999  * otherwise create and return a new device class.
1000  *
1001  * @param classname     the devclass name to find or create
1002  */
1003 devclass_t
1004 devclass_create(const char *classname)
1005 {
1006         return (devclass_find_internal(classname, NULL, TRUE));
1007 }
1008
1009 /**
1010  * @brief Find a device class
1011  *
1012  * If a device class with the name @p classname exists, return it,
1013  * otherwise return @c NULL.
1014  *
1015  * @param classname     the devclass name to find
1016  */
1017 devclass_t
1018 devclass_find(const char *classname)
1019 {
1020         return (devclass_find_internal(classname, NULL, FALSE));
1021 }
1022
1023 /**
1024  * @brief Register that a device driver has been added to a devclass
1025  *
1026  * Register that a device driver has been added to a devclass.  This
1027  * is called by devclass_add_driver to accomplish the recursive
1028  * notification of all the children classes of dc, as well as dc.
1029  * Each layer will have BUS_DRIVER_ADDED() called for all instances of
1030  * the devclass.
1031  *
1032  * We do a full search here of the devclass list at each iteration
1033  * level to save storing children-lists in the devclass structure.  If
1034  * we ever move beyond a few dozen devices doing this, we may need to
1035  * reevaluate...
1036  *
1037  * @param dc            the devclass to edit
1038  * @param driver        the driver that was just added
1039  */
1040 static void
1041 devclass_driver_added(devclass_t dc, driver_t *driver)
1042 {
1043         devclass_t parent;
1044         int i;
1045
1046         /*
1047          * Call BUS_DRIVER_ADDED for any existing buses in this class.
1048          */
1049         for (i = 0; i < dc->maxunit; i++)
1050                 if (dc->devices[i] && device_is_attached(dc->devices[i]))
1051                         BUS_DRIVER_ADDED(dc->devices[i], driver);
1052
1053         /*
1054          * Walk through the children classes.  Since we only keep a
1055          * single parent pointer around, we walk the entire list of
1056          * devclasses looking for children.  We set the
1057          * DC_HAS_CHILDREN flag when a child devclass is created on
1058          * the parent, so we only walk the list for those devclasses
1059          * that have children.
1060          */
1061         if (!(dc->flags & DC_HAS_CHILDREN))
1062                 return;
1063         parent = dc;
1064         TAILQ_FOREACH(dc, &devclasses, link) {
1065                 if (dc->parent == parent)
1066                         devclass_driver_added(dc, driver);
1067         }
1068 }
1069
1070 /**
1071  * @brief Add a device driver to a device class
1072  *
1073  * Add a device driver to a devclass. This is normally called
1074  * automatically by DRIVER_MODULE(). The BUS_DRIVER_ADDED() method of
1075  * all devices in the devclass will be called to allow them to attempt
1076  * to re-probe any unmatched children.
1077  *
1078  * @param dc            the devclass to edit
1079  * @param driver        the driver to register
1080  */
1081 int
1082 devclass_add_driver(devclass_t dc, driver_t *driver, int pass, devclass_t *dcp)
1083 {
1084         driverlink_t dl;
1085         const char *parentname;
1086
1087         PDEBUG(("%s", DRIVERNAME(driver)));
1088
1089         /* Don't allow invalid pass values. */
1090         if (pass <= BUS_PASS_ROOT)
1091                 return (EINVAL);
1092
1093         dl = malloc(sizeof *dl, M_BUS, M_NOWAIT|M_ZERO);
1094         if (!dl)
1095                 return (ENOMEM);
1096
1097         /*
1098          * Compile the driver's methods. Also increase the reference count
1099          * so that the class doesn't get freed when the last instance
1100          * goes. This means we can safely use static methods and avoids a
1101          * double-free in devclass_delete_driver.
1102          */
1103         kobj_class_compile((kobj_class_t) driver);
1104
1105         /*
1106          * If the driver has any base classes, make the
1107          * devclass inherit from the devclass of the driver's
1108          * first base class. This will allow the system to
1109          * search for drivers in both devclasses for children
1110          * of a device using this driver.
1111          */
1112         if (driver->baseclasses)
1113                 parentname = driver->baseclasses[0]->name;
1114         else
1115                 parentname = NULL;
1116         *dcp = devclass_find_internal(driver->name, parentname, TRUE);
1117
1118         dl->driver = driver;
1119         TAILQ_INSERT_TAIL(&dc->drivers, dl, link);
1120         driver->refs++;         /* XXX: kobj_mtx */
1121         dl->pass = pass;
1122         driver_register_pass(dl);
1123
1124         if (device_frozen) {
1125                 dl->flags |= DL_DEFERRED_PROBE;
1126         } else {
1127                 devclass_driver_added(dc, driver);
1128         }
1129         bus_data_generation_update();
1130         return (0);
1131 }
1132
1133 /**
1134  * @brief Register that a device driver has been deleted from a devclass
1135  *
1136  * Register that a device driver has been removed from a devclass.
1137  * This is called by devclass_delete_driver to accomplish the
1138  * recursive notification of all the children classes of busclass, as
1139  * well as busclass.  Each layer will attempt to detach the driver
1140  * from any devices that are children of the bus's devclass.  The function
1141  * will return an error if a device fails to detach.
1142  *
1143  * We do a full search here of the devclass list at each iteration
1144  * level to save storing children-lists in the devclass structure.  If
1145  * we ever move beyond a few dozen devices doing this, we may need to
1146  * reevaluate...
1147  *
1148  * @param busclass      the devclass of the parent bus
1149  * @param dc            the devclass of the driver being deleted
1150  * @param driver        the driver being deleted
1151  */
1152 static int
1153 devclass_driver_deleted(devclass_t busclass, devclass_t dc, driver_t *driver)
1154 {
1155         devclass_t parent;
1156         device_t dev;
1157         int error, i;
1158
1159         /*
1160          * Disassociate from any devices.  We iterate through all the
1161          * devices in the devclass of the driver and detach any which are
1162          * using the driver and which have a parent in the devclass which
1163          * we are deleting from.
1164          *
1165          * Note that since a driver can be in multiple devclasses, we
1166          * should not detach devices which are not children of devices in
1167          * the affected devclass.
1168          *
1169          * If we're frozen, we don't generate NOMATCH events. Mark to
1170          * generate later.
1171          */
1172         for (i = 0; i < dc->maxunit; i++) {
1173                 if (dc->devices[i]) {
1174                         dev = dc->devices[i];
1175                         if (dev->driver == driver && dev->parent &&
1176                             dev->parent->devclass == busclass) {
1177                                 if ((error = device_detach(dev)) != 0)
1178                                         return (error);
1179                                 if (device_frozen) {
1180                                         dev->flags &= ~DF_DONENOMATCH;
1181                                         dev->flags |= DF_NEEDNOMATCH;
1182                                 } else {
1183                                         BUS_PROBE_NOMATCH(dev->parent, dev);
1184                                         devnomatch(dev);
1185                                         dev->flags |= DF_DONENOMATCH;
1186                                 }
1187                         }
1188                 }
1189         }
1190
1191         /*
1192          * Walk through the children classes.  Since we only keep a
1193          * single parent pointer around, we walk the entire list of
1194          * devclasses looking for children.  We set the
1195          * DC_HAS_CHILDREN flag when a child devclass is created on
1196          * the parent, so we only walk the list for those devclasses
1197          * that have children.
1198          */
1199         if (!(busclass->flags & DC_HAS_CHILDREN))
1200                 return (0);
1201         parent = busclass;
1202         TAILQ_FOREACH(busclass, &devclasses, link) {
1203                 if (busclass->parent == parent) {
1204                         error = devclass_driver_deleted(busclass, dc, driver);
1205                         if (error)
1206                                 return (error);
1207                 }
1208         }
1209         return (0);
1210 }
1211
1212 /**
1213  * @brief Delete a device driver from a device class
1214  *
1215  * Delete a device driver from a devclass. This is normally called
1216  * automatically by DRIVER_MODULE().
1217  *
1218  * If the driver is currently attached to any devices,
1219  * devclass_delete_driver() will first attempt to detach from each
1220  * device. If one of the detach calls fails, the driver will not be
1221  * deleted.
1222  *
1223  * @param dc            the devclass to edit
1224  * @param driver        the driver to unregister
1225  */
1226 int
1227 devclass_delete_driver(devclass_t busclass, driver_t *driver)
1228 {
1229         devclass_t dc = devclass_find(driver->name);
1230         driverlink_t dl;
1231         int error;
1232
1233         PDEBUG(("%s from devclass %s", driver->name, DEVCLANAME(busclass)));
1234
1235         if (!dc)
1236                 return (0);
1237
1238         /*
1239          * Find the link structure in the bus' list of drivers.
1240          */
1241         TAILQ_FOREACH(dl, &busclass->drivers, link) {
1242                 if (dl->driver == driver)
1243                         break;
1244         }
1245
1246         if (!dl) {
1247                 PDEBUG(("%s not found in %s list", driver->name,
1248                     busclass->name));
1249                 return (ENOENT);
1250         }
1251
1252         error = devclass_driver_deleted(busclass, dc, driver);
1253         if (error != 0)
1254                 return (error);
1255
1256         TAILQ_REMOVE(&busclass->drivers, dl, link);
1257         free(dl, M_BUS);
1258
1259         /* XXX: kobj_mtx */
1260         driver->refs--;
1261         if (driver->refs == 0)
1262                 kobj_class_free((kobj_class_t) driver);
1263
1264         bus_data_generation_update();
1265         return (0);
1266 }
1267
1268 /**
1269  * @brief Quiesces a set of device drivers from a device class
1270  *
1271  * Quiesce a device driver from a devclass. This is normally called
1272  * automatically by DRIVER_MODULE().
1273  *
1274  * If the driver is currently attached to any devices,
1275  * devclass_quiesece_driver() will first attempt to quiesce each
1276  * device.
1277  *
1278  * @param dc            the devclass to edit
1279  * @param driver        the driver to unregister
1280  */
1281 static int
1282 devclass_quiesce_driver(devclass_t busclass, driver_t *driver)
1283 {
1284         devclass_t dc = devclass_find(driver->name);
1285         driverlink_t dl;
1286         device_t dev;
1287         int i;
1288         int error;
1289
1290         PDEBUG(("%s from devclass %s", driver->name, DEVCLANAME(busclass)));
1291
1292         if (!dc)
1293                 return (0);
1294
1295         /*
1296          * Find the link structure in the bus' list of drivers.
1297          */
1298         TAILQ_FOREACH(dl, &busclass->drivers, link) {
1299                 if (dl->driver == driver)
1300                         break;
1301         }
1302
1303         if (!dl) {
1304                 PDEBUG(("%s not found in %s list", driver->name,
1305                     busclass->name));
1306                 return (ENOENT);
1307         }
1308
1309         /*
1310          * Quiesce all devices.  We iterate through all the devices in
1311          * the devclass of the driver and quiesce any which are using
1312          * the driver and which have a parent in the devclass which we
1313          * are quiescing.
1314          *
1315          * Note that since a driver can be in multiple devclasses, we
1316          * should not quiesce devices which are not children of
1317          * devices in the affected devclass.
1318          */
1319         for (i = 0; i < dc->maxunit; i++) {
1320                 if (dc->devices[i]) {
1321                         dev = dc->devices[i];
1322                         if (dev->driver == driver && dev->parent &&
1323                             dev->parent->devclass == busclass) {
1324                                 if ((error = device_quiesce(dev)) != 0)
1325                                         return (error);
1326                         }
1327                 }
1328         }
1329
1330         return (0);
1331 }
1332
1333 /**
1334  * @internal
1335  */
1336 static driverlink_t
1337 devclass_find_driver_internal(devclass_t dc, const char *classname)
1338 {
1339         driverlink_t dl;
1340
1341         PDEBUG(("%s in devclass %s", classname, DEVCLANAME(dc)));
1342
1343         TAILQ_FOREACH(dl, &dc->drivers, link) {
1344                 if (!strcmp(dl->driver->name, classname))
1345                         return (dl);
1346         }
1347
1348         PDEBUG(("not found"));
1349         return (NULL);
1350 }
1351
1352 /**
1353  * @brief Return the name of the devclass
1354  */
1355 const char *
1356 devclass_get_name(devclass_t dc)
1357 {
1358         return (dc->name);
1359 }
1360
1361 /**
1362  * @brief Find a device given a unit number
1363  *
1364  * @param dc            the devclass to search
1365  * @param unit          the unit number to search for
1366  *
1367  * @returns             the device with the given unit number or @c
1368  *                      NULL if there is no such device
1369  */
1370 device_t
1371 devclass_get_device(devclass_t dc, int unit)
1372 {
1373         if (dc == NULL || unit < 0 || unit >= dc->maxunit)
1374                 return (NULL);
1375         return (dc->devices[unit]);
1376 }
1377
1378 /**
1379  * @brief Find the softc field of a device given a unit number
1380  *
1381  * @param dc            the devclass to search
1382  * @param unit          the unit number to search for
1383  *
1384  * @returns             the softc field of the device with the given
1385  *                      unit number or @c NULL if there is no such
1386  *                      device
1387  */
1388 void *
1389 devclass_get_softc(devclass_t dc, int unit)
1390 {
1391         device_t dev;
1392
1393         dev = devclass_get_device(dc, unit);
1394         if (!dev)
1395                 return (NULL);
1396
1397         return (device_get_softc(dev));
1398 }
1399
1400 /**
1401  * @brief Get a list of devices in the devclass
1402  *
1403  * An array containing a list of all the devices in the given devclass
1404  * is allocated and returned in @p *devlistp. The number of devices
1405  * in the array is returned in @p *devcountp. The caller should free
1406  * the array using @c free(p, M_TEMP), even if @p *devcountp is 0.
1407  *
1408  * @param dc            the devclass to examine
1409  * @param devlistp      points at location for array pointer return
1410  *                      value
1411  * @param devcountp     points at location for array size return value
1412  *
1413  * @retval 0            success
1414  * @retval ENOMEM       the array allocation failed
1415  */
1416 int
1417 devclass_get_devices(devclass_t dc, device_t **devlistp, int *devcountp)
1418 {
1419         int count, i;
1420         device_t *list;
1421
1422         count = devclass_get_count(dc);
1423         list = malloc(count * sizeof(device_t), M_TEMP, M_NOWAIT|M_ZERO);
1424         if (!list)
1425                 return (ENOMEM);
1426
1427         count = 0;
1428         for (i = 0; i < dc->maxunit; i++) {
1429                 if (dc->devices[i]) {
1430                         list[count] = dc->devices[i];
1431                         count++;
1432                 }
1433         }
1434
1435         *devlistp = list;
1436         *devcountp = count;
1437
1438         return (0);
1439 }
1440
1441 /**
1442  * @brief Get a list of drivers in the devclass
1443  *
1444  * An array containing a list of pointers to all the drivers in the
1445  * given devclass is allocated and returned in @p *listp.  The number
1446  * of drivers in the array is returned in @p *countp. The caller should
1447  * free the array using @c free(p, M_TEMP).
1448  *
1449  * @param dc            the devclass to examine
1450  * @param listp         gives location for array pointer return value
1451  * @param countp        gives location for number of array elements
1452  *                      return value
1453  *
1454  * @retval 0            success
1455  * @retval ENOMEM       the array allocation failed
1456  */
1457 int
1458 devclass_get_drivers(devclass_t dc, driver_t ***listp, int *countp)
1459 {
1460         driverlink_t dl;
1461         driver_t **list;
1462         int count;
1463
1464         count = 0;
1465         TAILQ_FOREACH(dl, &dc->drivers, link)
1466                 count++;
1467         list = malloc(count * sizeof(driver_t *), M_TEMP, M_NOWAIT);
1468         if (list == NULL)
1469                 return (ENOMEM);
1470
1471         count = 0;
1472         TAILQ_FOREACH(dl, &dc->drivers, link) {
1473                 list[count] = dl->driver;
1474                 count++;
1475         }
1476         *listp = list;
1477         *countp = count;
1478
1479         return (0);
1480 }
1481
1482 /**
1483  * @brief Get the number of devices in a devclass
1484  *
1485  * @param dc            the devclass to examine
1486  */
1487 int
1488 devclass_get_count(devclass_t dc)
1489 {
1490         int count, i;
1491
1492         count = 0;
1493         for (i = 0; i < dc->maxunit; i++)
1494                 if (dc->devices[i])
1495                         count++;
1496         return (count);
1497 }
1498
1499 /**
1500  * @brief Get the maximum unit number used in a devclass
1501  *
1502  * Note that this is one greater than the highest currently-allocated
1503  * unit.  If a null devclass_t is passed in, -1 is returned to indicate
1504  * that not even the devclass has been allocated yet.
1505  *
1506  * @param dc            the devclass to examine
1507  */
1508 int
1509 devclass_get_maxunit(devclass_t dc)
1510 {
1511         if (dc == NULL)
1512                 return (-1);
1513         return (dc->maxunit);
1514 }
1515
1516 /**
1517  * @brief Find a free unit number in a devclass
1518  *
1519  * This function searches for the first unused unit number greater
1520  * that or equal to @p unit.
1521  *
1522  * @param dc            the devclass to examine
1523  * @param unit          the first unit number to check
1524  */
1525 int
1526 devclass_find_free_unit(devclass_t dc, int unit)
1527 {
1528         if (dc == NULL)
1529                 return (unit);
1530         while (unit < dc->maxunit && dc->devices[unit] != NULL)
1531                 unit++;
1532         return (unit);
1533 }
1534
1535 /**
1536  * @brief Set the parent of a devclass
1537  *
1538  * The parent class is normally initialised automatically by
1539  * DRIVER_MODULE().
1540  *
1541  * @param dc            the devclass to edit
1542  * @param pdc           the new parent devclass
1543  */
1544 void
1545 devclass_set_parent(devclass_t dc, devclass_t pdc)
1546 {
1547         dc->parent = pdc;
1548 }
1549
1550 /**
1551  * @brief Get the parent of a devclass
1552  *
1553  * @param dc            the devclass to examine
1554  */
1555 devclass_t
1556 devclass_get_parent(devclass_t dc)
1557 {
1558         return (dc->parent);
1559 }
1560
1561 struct sysctl_ctx_list *
1562 devclass_get_sysctl_ctx(devclass_t dc)
1563 {
1564         return (&dc->sysctl_ctx);
1565 }
1566
1567 struct sysctl_oid *
1568 devclass_get_sysctl_tree(devclass_t dc)
1569 {
1570         return (dc->sysctl_tree);
1571 }
1572
1573 /**
1574  * @internal
1575  * @brief Allocate a unit number
1576  *
1577  * On entry, @p *unitp is the desired unit number (or @c -1 if any
1578  * will do). The allocated unit number is returned in @p *unitp.
1579
1580  * @param dc            the devclass to allocate from
1581  * @param unitp         points at the location for the allocated unit
1582  *                      number
1583  *
1584  * @retval 0            success
1585  * @retval EEXIST       the requested unit number is already allocated
1586  * @retval ENOMEM       memory allocation failure
1587  */
1588 static int
1589 devclass_alloc_unit(devclass_t dc, device_t dev, int *unitp)
1590 {
1591         const char *s;
1592         int unit = *unitp;
1593
1594         PDEBUG(("unit %d in devclass %s", unit, DEVCLANAME(dc)));
1595
1596         /* Ask the parent bus if it wants to wire this device. */
1597         if (unit == -1)
1598                 BUS_HINT_DEVICE_UNIT(device_get_parent(dev), dev, dc->name,
1599                     &unit);
1600
1601         /* If we were given a wired unit number, check for existing device */
1602         /* XXX imp XXX */
1603         if (unit != -1) {
1604                 if (unit >= 0 && unit < dc->maxunit &&
1605                     dc->devices[unit] != NULL) {
1606                         if (bootverbose)
1607                                 printf("%s: %s%d already exists; skipping it\n",
1608                                     dc->name, dc->name, *unitp);
1609                         return (EEXIST);
1610                 }
1611         } else {
1612                 /* Unwired device, find the next available slot for it */
1613                 unit = 0;
1614                 for (unit = 0;; unit++) {
1615                         /* If there is an "at" hint for a unit then skip it. */
1616                         if (resource_string_value(dc->name, unit, "at", &s) ==
1617                             0)
1618                                 continue;
1619
1620                         /* If this device slot is already in use, skip it. */
1621                         if (unit < dc->maxunit && dc->devices[unit] != NULL)
1622                                 continue;
1623
1624                         break;
1625                 }
1626         }
1627
1628         /*
1629          * We've selected a unit beyond the length of the table, so let's
1630          * extend the table to make room for all units up to and including
1631          * this one.
1632          */
1633         if (unit >= dc->maxunit) {
1634                 device_t *newlist, *oldlist;
1635                 int newsize;
1636
1637                 oldlist = dc->devices;
1638                 newsize = roundup((unit + 1),
1639                     MAX(1, MINALLOCSIZE / sizeof(device_t)));
1640                 newlist = malloc(sizeof(device_t) * newsize, M_BUS, M_NOWAIT);
1641                 if (!newlist)
1642                         return (ENOMEM);
1643                 if (oldlist != NULL)
1644                         bcopy(oldlist, newlist, sizeof(device_t) * dc->maxunit);
1645                 bzero(newlist + dc->maxunit,
1646                     sizeof(device_t) * (newsize - dc->maxunit));
1647                 dc->devices = newlist;
1648                 dc->maxunit = newsize;
1649                 if (oldlist != NULL)
1650                         free(oldlist, M_BUS);
1651         }
1652         PDEBUG(("now: unit %d in devclass %s", unit, DEVCLANAME(dc)));
1653
1654         *unitp = unit;
1655         return (0);
1656 }
1657
1658 /**
1659  * @internal
1660  * @brief Add a device to a devclass
1661  *
1662  * A unit number is allocated for the device (using the device's
1663  * preferred unit number if any) and the device is registered in the
1664  * devclass. This allows the device to be looked up by its unit
1665  * number, e.g. by decoding a dev_t minor number.
1666  *
1667  * @param dc            the devclass to add to
1668  * @param dev           the device to add
1669  *
1670  * @retval 0            success
1671  * @retval EEXIST       the requested unit number is already allocated
1672  * @retval ENOMEM       memory allocation failure
1673  */
1674 static int
1675 devclass_add_device(devclass_t dc, device_t dev)
1676 {
1677         int buflen, error;
1678
1679         PDEBUG(("%s in devclass %s", DEVICENAME(dev), DEVCLANAME(dc)));
1680
1681         buflen = snprintf(NULL, 0, "%s%d$", dc->name, INT_MAX);
1682         if (buflen < 0)
1683                 return (ENOMEM);
1684         dev->nameunit = malloc(buflen, M_BUS, M_NOWAIT|M_ZERO);
1685         if (!dev->nameunit)
1686                 return (ENOMEM);
1687
1688         if ((error = devclass_alloc_unit(dc, dev, &dev->unit)) != 0) {
1689                 free(dev->nameunit, M_BUS);
1690                 dev->nameunit = NULL;
1691                 return (error);
1692         }
1693         dc->devices[dev->unit] = dev;
1694         dev->devclass = dc;
1695         snprintf(dev->nameunit, buflen, "%s%d", dc->name, dev->unit);
1696
1697         return (0);
1698 }
1699
1700 /**
1701  * @internal
1702  * @brief Delete a device from a devclass
1703  *
1704  * The device is removed from the devclass's device list and its unit
1705  * number is freed.
1706
1707  * @param dc            the devclass to delete from
1708  * @param dev           the device to delete
1709  *
1710  * @retval 0            success
1711  */
1712 static int
1713 devclass_delete_device(devclass_t dc, device_t dev)
1714 {
1715         if (!dc || !dev)
1716                 return (0);
1717
1718         PDEBUG(("%s in devclass %s", DEVICENAME(dev), DEVCLANAME(dc)));
1719
1720         if (dev->devclass != dc || dc->devices[dev->unit] != dev)
1721                 panic("devclass_delete_device: inconsistent device class");
1722         dc->devices[dev->unit] = NULL;
1723         if (dev->flags & DF_WILDCARD)
1724                 dev->unit = -1;
1725         dev->devclass = NULL;
1726         free(dev->nameunit, M_BUS);
1727         dev->nameunit = NULL;
1728
1729         return (0);
1730 }
1731
1732 /**
1733  * @internal
1734  * @brief Make a new device and add it as a child of @p parent
1735  *
1736  * @param parent        the parent of the new device
1737  * @param name          the devclass name of the new device or @c NULL
1738  *                      to leave the devclass unspecified
1739  * @parem unit          the unit number of the new device of @c -1 to
1740  *                      leave the unit number unspecified
1741  *
1742  * @returns the new device
1743  */
1744 static device_t
1745 make_device(device_t parent, const char *name, int unit)
1746 {
1747         device_t dev;
1748         devclass_t dc;
1749
1750         PDEBUG(("%s at %s as unit %d", name, DEVICENAME(parent), unit));
1751
1752         if (name) {
1753                 dc = devclass_find_internal(name, NULL, TRUE);
1754                 if (!dc) {
1755                         printf("make_device: can't find device class %s\n",
1756                             name);
1757                         return (NULL);
1758                 }
1759         } else {
1760                 dc = NULL;
1761         }
1762
1763         dev = malloc(sizeof(*dev), M_BUS, M_NOWAIT|M_ZERO);
1764         if (!dev)
1765                 return (NULL);
1766
1767         dev->parent = parent;
1768         TAILQ_INIT(&dev->children);
1769         kobj_init((kobj_t) dev, &null_class);
1770         dev->driver = NULL;
1771         dev->devclass = NULL;
1772         dev->unit = unit;
1773         dev->nameunit = NULL;
1774         dev->desc = NULL;
1775         dev->busy = 0;
1776         dev->devflags = 0;
1777         dev->flags = DF_ENABLED;
1778         dev->order = 0;
1779         if (unit == -1)
1780                 dev->flags |= DF_WILDCARD;
1781         if (name) {
1782                 dev->flags |= DF_FIXEDCLASS;
1783                 if (devclass_add_device(dc, dev)) {
1784                         kobj_delete((kobj_t) dev, M_BUS);
1785                         return (NULL);
1786                 }
1787         }
1788         if (parent != NULL && device_has_quiet_children(parent))
1789                 dev->flags |= DF_QUIET | DF_QUIET_CHILDREN;
1790         dev->ivars = NULL;
1791         dev->softc = NULL;
1792
1793         dev->state = DS_NOTPRESENT;
1794
1795         TAILQ_INSERT_TAIL(&bus_data_devices, dev, devlink);
1796         bus_data_generation_update();
1797
1798         return (dev);
1799 }
1800
1801 /**
1802  * @internal
1803  * @brief Print a description of a device.
1804  */
1805 static int
1806 device_print_child(device_t dev, device_t child)
1807 {
1808         int retval = 0;
1809
1810         if (device_is_alive(child))
1811                 retval += BUS_PRINT_CHILD(dev, child);
1812         else
1813                 retval += device_printf(child, " not found\n");
1814
1815         return (retval);
1816 }
1817
1818 /**
1819  * @brief Create a new device
1820  *
1821  * This creates a new device and adds it as a child of an existing
1822  * parent device. The new device will be added after the last existing
1823  * child with order zero.
1824  *
1825  * @param dev           the device which will be the parent of the
1826  *                      new child device
1827  * @param name          devclass name for new device or @c NULL if not
1828  *                      specified
1829  * @param unit          unit number for new device or @c -1 if not
1830  *                      specified
1831  *
1832  * @returns             the new device
1833  */
1834 device_t
1835 device_add_child(device_t dev, const char *name, int unit)
1836 {
1837         return (device_add_child_ordered(dev, 0, name, unit));
1838 }
1839
1840 /**
1841  * @brief Create a new device
1842  *
1843  * This creates a new device and adds it as a child of an existing
1844  * parent device. The new device will be added after the last existing
1845  * child with the same order.
1846  *
1847  * @param dev           the device which will be the parent of the
1848  *                      new child device
1849  * @param order         a value which is used to partially sort the
1850  *                      children of @p dev - devices created using
1851  *                      lower values of @p order appear first in @p
1852  *                      dev's list of children
1853  * @param name          devclass name for new device or @c NULL if not
1854  *                      specified
1855  * @param unit          unit number for new device or @c -1 if not
1856  *                      specified
1857  *
1858  * @returns             the new device
1859  */
1860 device_t
1861 device_add_child_ordered(device_t dev, u_int order, const char *name, int unit)
1862 {
1863         device_t child;
1864         device_t place;
1865
1866         PDEBUG(("%s at %s with order %u as unit %d",
1867             name, DEVICENAME(dev), order, unit));
1868         KASSERT(name != NULL || unit == -1,
1869             ("child device with wildcard name and specific unit number"));
1870
1871         child = make_device(dev, name, unit);
1872         if (child == NULL)
1873                 return (child);
1874         child->order = order;
1875
1876         TAILQ_FOREACH(place, &dev->children, link) {
1877                 if (place->order > order)
1878                         break;
1879         }
1880
1881         if (place) {
1882                 /*
1883                  * The device 'place' is the first device whose order is
1884                  * greater than the new child.
1885                  */
1886                 TAILQ_INSERT_BEFORE(place, child, link);
1887         } else {
1888                 /*
1889                  * The new child's order is greater or equal to the order of
1890                  * any existing device. Add the child to the tail of the list.
1891                  */
1892                 TAILQ_INSERT_TAIL(&dev->children, child, link);
1893         }
1894
1895         bus_data_generation_update();
1896         return (child);
1897 }
1898
1899 /**
1900  * @brief Delete a device
1901  *
1902  * This function deletes a device along with all of its children. If
1903  * the device currently has a driver attached to it, the device is
1904  * detached first using device_detach().
1905  *
1906  * @param dev           the parent device
1907  * @param child         the device to delete
1908  *
1909  * @retval 0            success
1910  * @retval non-zero     a unit error code describing the error
1911  */
1912 int
1913 device_delete_child(device_t dev, device_t child)
1914 {
1915         int error;
1916         device_t grandchild;
1917
1918         PDEBUG(("%s from %s", DEVICENAME(child), DEVICENAME(dev)));
1919
1920         /* detach parent before deleting children, if any */
1921         if ((error = device_detach(child)) != 0)
1922                 return (error);
1923
1924         /* remove children second */
1925         while ((grandchild = TAILQ_FIRST(&child->children)) != NULL) {
1926                 error = device_delete_child(child, grandchild);
1927                 if (error)
1928                         return (error);
1929         }
1930
1931         if (child->devclass)
1932                 devclass_delete_device(child->devclass, child);
1933         if (child->parent)
1934                 BUS_CHILD_DELETED(dev, child);
1935         TAILQ_REMOVE(&dev->children, child, link);
1936         TAILQ_REMOVE(&bus_data_devices, child, devlink);
1937         kobj_delete((kobj_t) child, M_BUS);
1938
1939         bus_data_generation_update();
1940         return (0);
1941 }
1942
1943 /**
1944  * @brief Delete all children devices of the given device, if any.
1945  *
1946  * This function deletes all children devices of the given device, if
1947  * any, using the device_delete_child() function for each device it
1948  * finds. If a child device cannot be deleted, this function will
1949  * return an error code.
1950  *
1951  * @param dev           the parent device
1952  *
1953  * @retval 0            success
1954  * @retval non-zero     a device would not detach
1955  */
1956 int
1957 device_delete_children(device_t dev)
1958 {
1959         device_t child;
1960         int error;
1961
1962         PDEBUG(("Deleting all children of %s", DEVICENAME(dev)));
1963
1964         error = 0;
1965
1966         while ((child = TAILQ_FIRST(&dev->children)) != NULL) {
1967                 error = device_delete_child(dev, child);
1968                 if (error) {
1969                         PDEBUG(("Failed deleting %s", DEVICENAME(child)));
1970                         break;
1971                 }
1972         }
1973         return (error);
1974 }
1975
1976 /**
1977  * @brief Find a device given a unit number
1978  *
1979  * This is similar to devclass_get_devices() but only searches for
1980  * devices which have @p dev as a parent.
1981  *
1982  * @param dev           the parent device to search
1983  * @param unit          the unit number to search for.  If the unit is -1,
1984  *                      return the first child of @p dev which has name
1985  *                      @p classname (that is, the one with the lowest unit.)
1986  *
1987  * @returns             the device with the given unit number or @c
1988  *                      NULL if there is no such device
1989  */
1990 device_t
1991 device_find_child(device_t dev, const char *classname, int unit)
1992 {
1993         devclass_t dc;
1994         device_t child;
1995
1996         dc = devclass_find(classname);
1997         if (!dc)
1998                 return (NULL);
1999
2000         if (unit != -1) {
2001                 child = devclass_get_device(dc, unit);
2002                 if (child && child->parent == dev)
2003                         return (child);
2004         } else {
2005                 for (unit = 0; unit < devclass_get_maxunit(dc); unit++) {
2006                         child = devclass_get_device(dc, unit);
2007                         if (child && child->parent == dev)
2008                                 return (child);
2009                 }
2010         }
2011         return (NULL);
2012 }
2013
2014 /**
2015  * @internal
2016  */
2017 static driverlink_t
2018 first_matching_driver(devclass_t dc, device_t dev)
2019 {
2020         if (dev->devclass)
2021                 return (devclass_find_driver_internal(dc, dev->devclass->name));
2022         return (TAILQ_FIRST(&dc->drivers));
2023 }
2024
2025 /**
2026  * @internal
2027  */
2028 static driverlink_t
2029 next_matching_driver(devclass_t dc, device_t dev, driverlink_t last)
2030 {
2031         if (dev->devclass) {
2032                 driverlink_t dl;
2033                 for (dl = TAILQ_NEXT(last, link); dl; dl = TAILQ_NEXT(dl, link))
2034                         if (!strcmp(dev->devclass->name, dl->driver->name))
2035                                 return (dl);
2036                 return (NULL);
2037         }
2038         return (TAILQ_NEXT(last, link));
2039 }
2040
2041 /**
2042  * @internal
2043  */
2044 int
2045 device_probe_child(device_t dev, device_t child)
2046 {
2047         devclass_t dc;
2048         driverlink_t best = NULL;
2049         driverlink_t dl;
2050         int result, pri = 0;
2051         int hasclass = (child->devclass != NULL);
2052
2053         GIANT_REQUIRED;
2054
2055         dc = dev->devclass;
2056         if (!dc)
2057                 panic("device_probe_child: parent device has no devclass");
2058
2059         /*
2060          * If the state is already probed, then return.  However, don't
2061          * return if we can rebid this object.
2062          */
2063         if (child->state == DS_ALIVE && (child->flags & DF_REBID) == 0)
2064                 return (0);
2065
2066         for (; dc; dc = dc->parent) {
2067                 for (dl = first_matching_driver(dc, child);
2068                      dl;
2069                      dl = next_matching_driver(dc, child, dl)) {
2070                         /* If this driver's pass is too high, then ignore it. */
2071                         if (dl->pass > bus_current_pass)
2072                                 continue;
2073
2074                         PDEBUG(("Trying %s", DRIVERNAME(dl->driver)));
2075                         result = device_set_driver(child, dl->driver);
2076                         if (result == ENOMEM)
2077                                 return (result);
2078                         else if (result != 0)
2079                                 continue;
2080                         if (!hasclass) {
2081                                 if (device_set_devclass(child,
2082                                     dl->driver->name) != 0) {
2083                                         char const * devname =
2084                                             device_get_name(child);
2085                                         if (devname == NULL)
2086                                                 devname = "(unknown)";
2087                                         printf("driver bug: Unable to set "
2088                                             "devclass (class: %s "
2089                                             "devname: %s)\n",
2090                                             dl->driver->name,
2091                                             devname);
2092                                         (void)device_set_driver(child, NULL);
2093                                         continue;
2094                                 }
2095                         }
2096
2097                         /* Fetch any flags for the device before probing. */
2098                         resource_int_value(dl->driver->name, child->unit,
2099                             "flags", &child->devflags);
2100
2101                         result = DEVICE_PROBE(child);
2102
2103                         /* Reset flags and devclass before the next probe. */
2104                         child->devflags = 0;
2105                         if (!hasclass)
2106                                 (void)device_set_devclass(child, NULL);
2107
2108                         /*
2109                          * If the driver returns SUCCESS, there can be
2110                          * no higher match for this device.
2111                          */
2112                         if (result == 0) {
2113                                 best = dl;
2114                                 pri = 0;
2115                                 break;
2116                         }
2117
2118                         /*
2119                          * Reset DF_QUIET in case this driver doesn't
2120                          * end up as the best driver.
2121                          */
2122                         device_verbose(child);
2123
2124                         /*
2125                          * Probes that return BUS_PROBE_NOWILDCARD or lower
2126                          * only match on devices whose driver was explicitly
2127                          * specified.
2128                          */
2129                         if (result <= BUS_PROBE_NOWILDCARD &&
2130                             !(child->flags & DF_FIXEDCLASS)) {
2131                                 result = ENXIO;
2132                         }
2133
2134                         /*
2135                          * The driver returned an error so it
2136                          * certainly doesn't match.
2137                          */
2138                         if (result > 0) {
2139                                 (void)device_set_driver(child, NULL);
2140                                 continue;
2141                         }
2142
2143                         /*
2144                          * A priority lower than SUCCESS, remember the
2145                          * best matching driver. Initialise the value
2146                          * of pri for the first match.
2147                          */
2148                         if (best == NULL || result > pri) {
2149                                 best = dl;
2150                                 pri = result;
2151                                 continue;
2152                         }
2153                 }
2154                 /*
2155                  * If we have an unambiguous match in this devclass,
2156                  * don't look in the parent.
2157                  */
2158                 if (best && pri == 0)
2159                         break;
2160         }
2161
2162         /*
2163          * If we found a driver, change state and initialise the devclass.
2164          */
2165         /* XXX What happens if we rebid and got no best? */
2166         if (best) {
2167                 /*
2168                  * If this device was attached, and we were asked to
2169                  * rescan, and it is a different driver, then we have
2170                  * to detach the old driver and reattach this new one.
2171                  * Note, we don't have to check for DF_REBID here
2172                  * because if the state is > DS_ALIVE, we know it must
2173                  * be.
2174                  *
2175                  * This assumes that all DF_REBID drivers can have
2176                  * their probe routine called at any time and that
2177                  * they are idempotent as well as completely benign in
2178                  * normal operations.
2179                  *
2180                  * We also have to make sure that the detach
2181                  * succeeded, otherwise we fail the operation (or
2182                  * maybe it should just fail silently?  I'm torn).
2183                  */
2184                 if (child->state > DS_ALIVE && best->driver != child->driver)
2185                         if ((result = device_detach(dev)) != 0)
2186                                 return (result);
2187
2188                 /* Set the winning driver, devclass, and flags. */
2189                 if (!child->devclass) {
2190                         result = device_set_devclass(child, best->driver->name);
2191                         if (result != 0)
2192                                 return (result);
2193                 }
2194                 result = device_set_driver(child, best->driver);
2195                 if (result != 0)
2196                         return (result);
2197                 resource_int_value(best->driver->name, child->unit,
2198                     "flags", &child->devflags);
2199
2200                 if (pri < 0) {
2201                         /*
2202                          * A bit bogus. Call the probe method again to make
2203                          * sure that we have the right description.
2204                          */
2205                         DEVICE_PROBE(child);
2206 #if 0
2207                         child->flags |= DF_REBID;
2208 #endif
2209                 } else
2210                         child->flags &= ~DF_REBID;
2211                 child->state = DS_ALIVE;
2212
2213                 bus_data_generation_update();
2214                 return (0);
2215         }
2216
2217         return (ENXIO);
2218 }
2219
2220 /**
2221  * @brief Return the parent of a device
2222  */
2223 device_t
2224 device_get_parent(device_t dev)
2225 {
2226         return (dev->parent);
2227 }
2228
2229 /**
2230  * @brief Get a list of children of a device
2231  *
2232  * An array containing a list of all the children of the given device
2233  * is allocated and returned in @p *devlistp. The number of devices
2234  * in the array is returned in @p *devcountp. The caller should free
2235  * the array using @c free(p, M_TEMP).
2236  *
2237  * @param dev           the device to examine
2238  * @param devlistp      points at location for array pointer return
2239  *                      value
2240  * @param devcountp     points at location for array size return value
2241  *
2242  * @retval 0            success
2243  * @retval ENOMEM       the array allocation failed
2244  */
2245 int
2246 device_get_children(device_t dev, device_t **devlistp, int *devcountp)
2247 {
2248         int count;
2249         device_t child;
2250         device_t *list;
2251
2252         count = 0;
2253         TAILQ_FOREACH(child, &dev->children, link) {
2254                 count++;
2255         }
2256         if (count == 0) {
2257                 *devlistp = NULL;
2258                 *devcountp = 0;
2259                 return (0);
2260         }
2261
2262         list = malloc(count * sizeof(device_t), M_TEMP, M_NOWAIT|M_ZERO);
2263         if (!list)
2264                 return (ENOMEM);
2265
2266         count = 0;
2267         TAILQ_FOREACH(child, &dev->children, link) {
2268                 list[count] = child;
2269                 count++;
2270         }
2271
2272         *devlistp = list;
2273         *devcountp = count;
2274
2275         return (0);
2276 }
2277
2278 /**
2279  * @brief Return the current driver for the device or @c NULL if there
2280  * is no driver currently attached
2281  */
2282 driver_t *
2283 device_get_driver(device_t dev)
2284 {
2285         return (dev->driver);
2286 }
2287
2288 /**
2289  * @brief Return the current devclass for the device or @c NULL if
2290  * there is none.
2291  */
2292 devclass_t
2293 device_get_devclass(device_t dev)
2294 {
2295         return (dev->devclass);
2296 }
2297
2298 /**
2299  * @brief Return the name of the device's devclass or @c NULL if there
2300  * is none.
2301  */
2302 const char *
2303 device_get_name(device_t dev)
2304 {
2305         if (dev != NULL && dev->devclass)
2306                 return (devclass_get_name(dev->devclass));
2307         return (NULL);
2308 }
2309
2310 /**
2311  * @brief Return a string containing the device's devclass name
2312  * followed by an ascii representation of the device's unit number
2313  * (e.g. @c "foo2").
2314  */
2315 const char *
2316 device_get_nameunit(device_t dev)
2317 {
2318         return (dev->nameunit);
2319 }
2320
2321 /**
2322  * @brief Return the device's unit number.
2323  */
2324 int
2325 device_get_unit(device_t dev)
2326 {
2327         return (dev->unit);
2328 }
2329
2330 /**
2331  * @brief Return the device's description string
2332  */
2333 const char *
2334 device_get_desc(device_t dev)
2335 {
2336         return (dev->desc);
2337 }
2338
2339 /**
2340  * @brief Return the device's flags
2341  */
2342 uint32_t
2343 device_get_flags(device_t dev)
2344 {
2345         return (dev->devflags);
2346 }
2347
2348 struct sysctl_ctx_list *
2349 device_get_sysctl_ctx(device_t dev)
2350 {
2351         return (&dev->sysctl_ctx);
2352 }
2353
2354 struct sysctl_oid *
2355 device_get_sysctl_tree(device_t dev)
2356 {
2357         return (dev->sysctl_tree);
2358 }
2359
2360 /**
2361  * @brief Print the name of the device followed by a colon and a space
2362  *
2363  * @returns the number of characters printed
2364  */
2365 int
2366 device_print_prettyname(device_t dev)
2367 {
2368         const char *name = device_get_name(dev);
2369
2370         if (name == NULL)
2371                 return (printf("unknown: "));
2372         return (printf("%s%d: ", name, device_get_unit(dev)));
2373 }
2374
2375 /**
2376  * @brief Print the name of the device followed by a colon, a space
2377  * and the result of calling vprintf() with the value of @p fmt and
2378  * the following arguments.
2379  *
2380  * @returns the number of characters printed
2381  */
2382 int
2383 device_printf(device_t dev, const char * fmt, ...)
2384 {
2385         char buf[128];
2386         struct sbuf sb;
2387         const char *name;
2388         va_list ap;
2389         size_t retval;
2390
2391         retval = 0;
2392
2393         sbuf_new(&sb, buf, sizeof(buf), SBUF_FIXEDLEN);
2394         sbuf_set_drain(&sb, sbuf_printf_drain, &retval);
2395
2396         name = device_get_name(dev);
2397
2398         if (name == NULL)
2399                 sbuf_cat(&sb, "unknown: ");
2400         else
2401                 sbuf_printf(&sb, "%s%d: ", name, device_get_unit(dev));
2402
2403         va_start(ap, fmt);
2404         sbuf_vprintf(&sb, fmt, ap);
2405         va_end(ap);
2406
2407         sbuf_finish(&sb);
2408         sbuf_delete(&sb);
2409
2410         return (retval);
2411 }
2412
2413 /**
2414  * @internal
2415  */
2416 static void
2417 device_set_desc_internal(device_t dev, const char* desc, int copy)
2418 {
2419         if (dev->desc && (dev->flags & DF_DESCMALLOCED)) {
2420                 free(dev->desc, M_BUS);
2421                 dev->flags &= ~DF_DESCMALLOCED;
2422                 dev->desc = NULL;
2423         }
2424
2425         if (copy && desc) {
2426                 dev->desc = malloc(strlen(desc) + 1, M_BUS, M_NOWAIT);
2427                 if (dev->desc) {
2428                         strcpy(dev->desc, desc);
2429                         dev->flags |= DF_DESCMALLOCED;
2430                 }
2431         } else {
2432                 /* Avoid a -Wcast-qual warning */
2433                 dev->desc = (char *)(uintptr_t) desc;
2434         }
2435
2436         bus_data_generation_update();
2437 }
2438
2439 /**
2440  * @brief Set the device's description
2441  *
2442  * The value of @c desc should be a string constant that will not
2443  * change (at least until the description is changed in a subsequent
2444  * call to device_set_desc() or device_set_desc_copy()).
2445  */
2446 void
2447 device_set_desc(device_t dev, const char* desc)
2448 {
2449         device_set_desc_internal(dev, desc, FALSE);
2450 }
2451
2452 /**
2453  * @brief Set the device's description
2454  *
2455  * The string pointed to by @c desc is copied. Use this function if
2456  * the device description is generated, (e.g. with sprintf()).
2457  */
2458 void
2459 device_set_desc_copy(device_t dev, const char* desc)
2460 {
2461         device_set_desc_internal(dev, desc, TRUE);
2462 }
2463
2464 /**
2465  * @brief Set the device's flags
2466  */
2467 void
2468 device_set_flags(device_t dev, uint32_t flags)
2469 {
2470         dev->devflags = flags;
2471 }
2472
2473 /**
2474  * @brief Return the device's softc field
2475  *
2476  * The softc is allocated and zeroed when a driver is attached, based
2477  * on the size field of the driver.
2478  */
2479 void *
2480 device_get_softc(device_t dev)
2481 {
2482         return (dev->softc);
2483 }
2484
2485 /**
2486  * @brief Set the device's softc field
2487  *
2488  * Most drivers do not need to use this since the softc is allocated
2489  * automatically when the driver is attached.
2490  */
2491 void
2492 device_set_softc(device_t dev, void *softc)
2493 {
2494         if (dev->softc && !(dev->flags & DF_EXTERNALSOFTC))
2495                 free(dev->softc, M_BUS_SC);
2496         dev->softc = softc;
2497         if (dev->softc)
2498                 dev->flags |= DF_EXTERNALSOFTC;
2499         else
2500                 dev->flags &= ~DF_EXTERNALSOFTC;
2501 }
2502
2503 /**
2504  * @brief Free claimed softc
2505  *
2506  * Most drivers do not need to use this since the softc is freed
2507  * automatically when the driver is detached.
2508  */
2509 void
2510 device_free_softc(void *softc)
2511 {
2512         free(softc, M_BUS_SC);
2513 }
2514
2515 /**
2516  * @brief Claim softc
2517  *
2518  * This function can be used to let the driver free the automatically
2519  * allocated softc using "device_free_softc()". This function is
2520  * useful when the driver is refcounting the softc and the softc
2521  * cannot be freed when the "device_detach" method is called.
2522  */
2523 void
2524 device_claim_softc(device_t dev)
2525 {
2526         if (dev->softc)
2527                 dev->flags |= DF_EXTERNALSOFTC;
2528         else
2529                 dev->flags &= ~DF_EXTERNALSOFTC;
2530 }
2531
2532 /**
2533  * @brief Get the device's ivars field
2534  *
2535  * The ivars field is used by the parent device to store per-device
2536  * state (e.g. the physical location of the device or a list of
2537  * resources).
2538  */
2539 void *
2540 device_get_ivars(device_t dev)
2541 {
2542         KASSERT(dev != NULL, ("device_get_ivars(NULL, ...)"));
2543         return (dev->ivars);
2544 }
2545
2546 /**
2547  * @brief Set the device's ivars field
2548  */
2549 void
2550 device_set_ivars(device_t dev, void * ivars)
2551 {
2552         KASSERT(dev != NULL, ("device_set_ivars(NULL, ...)"));
2553         dev->ivars = ivars;
2554 }
2555
2556 /**
2557  * @brief Return the device's state
2558  */
2559 device_state_t
2560 device_get_state(device_t dev)
2561 {
2562         return (dev->state);
2563 }
2564
2565 /**
2566  * @brief Set the DF_ENABLED flag for the device
2567  */
2568 void
2569 device_enable(device_t dev)
2570 {
2571         dev->flags |= DF_ENABLED;
2572 }
2573
2574 /**
2575  * @brief Clear the DF_ENABLED flag for the device
2576  */
2577 void
2578 device_disable(device_t dev)
2579 {
2580         dev->flags &= ~DF_ENABLED;
2581 }
2582
2583 /**
2584  * @brief Increment the busy counter for the device
2585  */
2586 void
2587 device_busy(device_t dev)
2588 {
2589         if (dev->state < DS_ATTACHING)
2590                 panic("device_busy: called for unattached device");
2591         if (dev->busy == 0 && dev->parent)
2592                 device_busy(dev->parent);
2593         dev->busy++;
2594         if (dev->state == DS_ATTACHED)
2595                 dev->state = DS_BUSY;
2596 }
2597
2598 /**
2599  * @brief Decrement the busy counter for the device
2600  */
2601 void
2602 device_unbusy(device_t dev)
2603 {
2604         if (dev->busy != 0 && dev->state != DS_BUSY &&
2605             dev->state != DS_ATTACHING)
2606                 panic("device_unbusy: called for non-busy device %s",
2607                     device_get_nameunit(dev));
2608         dev->busy--;
2609         if (dev->busy == 0) {
2610                 if (dev->parent)
2611                         device_unbusy(dev->parent);
2612                 if (dev->state == DS_BUSY)
2613                         dev->state = DS_ATTACHED;
2614         }
2615 }
2616
2617 /**
2618  * @brief Set the DF_QUIET flag for the device
2619  */
2620 void
2621 device_quiet(device_t dev)
2622 {
2623         dev->flags |= DF_QUIET;
2624 }
2625
2626 /**
2627  * @brief Set the DF_QUIET_CHILDREN flag for the device
2628  */
2629 void
2630 device_quiet_children(device_t dev)
2631 {
2632         dev->flags |= DF_QUIET_CHILDREN;
2633 }
2634
2635 /**
2636  * @brief Clear the DF_QUIET flag for the device
2637  */
2638 void
2639 device_verbose(device_t dev)
2640 {
2641         dev->flags &= ~DF_QUIET;
2642 }
2643
2644 /**
2645  * @brief Return non-zero if the DF_QUIET_CHIDLREN flag is set on the device
2646  */
2647 int
2648 device_has_quiet_children(device_t dev)
2649 {
2650         return ((dev->flags & DF_QUIET_CHILDREN) != 0);
2651 }
2652
2653 /**
2654  * @brief Return non-zero if the DF_QUIET flag is set on the device
2655  */
2656 int
2657 device_is_quiet(device_t dev)
2658 {
2659         return ((dev->flags & DF_QUIET) != 0);
2660 }
2661
2662 /**
2663  * @brief Return non-zero if the DF_ENABLED flag is set on the device
2664  */
2665 int
2666 device_is_enabled(device_t dev)
2667 {
2668         return ((dev->flags & DF_ENABLED) != 0);
2669 }
2670
2671 /**
2672  * @brief Return non-zero if the device was successfully probed
2673  */
2674 int
2675 device_is_alive(device_t dev)
2676 {
2677         return (dev->state >= DS_ALIVE);
2678 }
2679
2680 /**
2681  * @brief Return non-zero if the device currently has a driver
2682  * attached to it
2683  */
2684 int
2685 device_is_attached(device_t dev)
2686 {
2687         return (dev->state >= DS_ATTACHED);
2688 }
2689
2690 /**
2691  * @brief Return non-zero if the device is currently suspended.
2692  */
2693 int
2694 device_is_suspended(device_t dev)
2695 {
2696         return ((dev->flags & DF_SUSPENDED) != 0);
2697 }
2698
2699 /**
2700  * @brief Set the devclass of a device
2701  * @see devclass_add_device().
2702  */
2703 int
2704 device_set_devclass(device_t dev, const char *classname)
2705 {
2706         devclass_t dc;
2707         int error;
2708
2709         if (!classname) {
2710                 if (dev->devclass)
2711                         devclass_delete_device(dev->devclass, dev);
2712                 return (0);
2713         }
2714
2715         if (dev->devclass) {
2716                 printf("device_set_devclass: device class already set\n");
2717                 return (EINVAL);
2718         }
2719
2720         dc = devclass_find_internal(classname, NULL, TRUE);
2721         if (!dc)
2722                 return (ENOMEM);
2723
2724         error = devclass_add_device(dc, dev);
2725
2726         bus_data_generation_update();
2727         return (error);
2728 }
2729
2730 /**
2731  * @brief Set the devclass of a device and mark the devclass fixed.
2732  * @see device_set_devclass()
2733  */
2734 int
2735 device_set_devclass_fixed(device_t dev, const char *classname)
2736 {
2737         int error;
2738
2739         if (classname == NULL)
2740                 return (EINVAL);
2741
2742         error = device_set_devclass(dev, classname);
2743         if (error)
2744                 return (error);
2745         dev->flags |= DF_FIXEDCLASS;
2746         return (0);
2747 }
2748
2749 /**
2750  * @brief Query the device to determine if it's of a fixed devclass
2751  * @see device_set_devclass_fixed()
2752  */
2753 bool
2754 device_is_devclass_fixed(device_t dev)
2755 {
2756         return ((dev->flags & DF_FIXEDCLASS) != 0);
2757 }
2758
2759 /**
2760  * @brief Set the driver of a device
2761  *
2762  * @retval 0            success
2763  * @retval EBUSY        the device already has a driver attached
2764  * @retval ENOMEM       a memory allocation failure occurred
2765  */
2766 int
2767 device_set_driver(device_t dev, driver_t *driver)
2768 {
2769         int domain;
2770         struct domainset *policy;
2771
2772         if (dev->state >= DS_ATTACHED)
2773                 return (EBUSY);
2774
2775         if (dev->driver == driver)
2776                 return (0);
2777
2778         if (dev->softc && !(dev->flags & DF_EXTERNALSOFTC)) {
2779                 free(dev->softc, M_BUS_SC);
2780                 dev->softc = NULL;
2781         }
2782         device_set_desc(dev, NULL);
2783         kobj_delete((kobj_t) dev, NULL);
2784         dev->driver = driver;
2785         if (driver) {
2786                 kobj_init((kobj_t) dev, (kobj_class_t) driver);
2787                 if (!(dev->flags & DF_EXTERNALSOFTC) && driver->size > 0) {
2788                         if (bus_get_domain(dev, &domain) == 0)
2789                                 policy = DOMAINSET_PREF(domain);
2790                         else
2791                                 policy = DOMAINSET_RR();
2792                         dev->softc = malloc_domainset(driver->size, M_BUS_SC,
2793                             policy, M_NOWAIT | M_ZERO);
2794                         if (!dev->softc) {
2795                                 kobj_delete((kobj_t) dev, NULL);
2796                                 kobj_init((kobj_t) dev, &null_class);
2797                                 dev->driver = NULL;
2798                                 return (ENOMEM);
2799                         }
2800                 }
2801         } else {
2802                 kobj_init((kobj_t) dev, &null_class);
2803         }
2804
2805         bus_data_generation_update();
2806         return (0);
2807 }
2808
2809 /**
2810  * @brief Probe a device, and return this status.
2811  *
2812  * This function is the core of the device autoconfiguration
2813  * system. Its purpose is to select a suitable driver for a device and
2814  * then call that driver to initialise the hardware appropriately. The
2815  * driver is selected by calling the DEVICE_PROBE() method of a set of
2816  * candidate drivers and then choosing the driver which returned the
2817  * best value. This driver is then attached to the device using
2818  * device_attach().
2819  *
2820  * The set of suitable drivers is taken from the list of drivers in
2821  * the parent device's devclass. If the device was originally created
2822  * with a specific class name (see device_add_child()), only drivers
2823  * with that name are probed, otherwise all drivers in the devclass
2824  * are probed. If no drivers return successful probe values in the
2825  * parent devclass, the search continues in the parent of that
2826  * devclass (see devclass_get_parent()) if any.
2827  *
2828  * @param dev           the device to initialise
2829  *
2830  * @retval 0            success
2831  * @retval ENXIO        no driver was found
2832  * @retval ENOMEM       memory allocation failure
2833  * @retval non-zero     some other unix error code
2834  * @retval -1           Device already attached
2835  */
2836 int
2837 device_probe(device_t dev)
2838 {
2839         int error;
2840
2841         GIANT_REQUIRED;
2842
2843         if (dev->state >= DS_ALIVE && (dev->flags & DF_REBID) == 0)
2844                 return (-1);
2845
2846         if (!(dev->flags & DF_ENABLED)) {
2847                 if (bootverbose && device_get_name(dev) != NULL) {
2848                         device_print_prettyname(dev);
2849                         printf("not probed (disabled)\n");
2850                 }
2851                 return (-1);
2852         }
2853         if ((error = device_probe_child(dev->parent, dev)) != 0) {
2854                 if (bus_current_pass == BUS_PASS_DEFAULT &&
2855                     !(dev->flags & DF_DONENOMATCH)) {
2856                         BUS_PROBE_NOMATCH(dev->parent, dev);
2857                         devnomatch(dev);
2858                         dev->flags |= DF_DONENOMATCH;
2859                 }
2860                 return (error);
2861         }
2862         return (0);
2863 }
2864
2865 /**
2866  * @brief Probe a device and attach a driver if possible
2867  *
2868  * calls device_probe() and attaches if that was successful.
2869  */
2870 int
2871 device_probe_and_attach(device_t dev)
2872 {
2873         int error;
2874
2875         GIANT_REQUIRED;
2876
2877         error = device_probe(dev);
2878         if (error == -1)
2879                 return (0);
2880         else if (error != 0)
2881                 return (error);
2882
2883         CURVNET_SET_QUIET(vnet0);
2884         error = device_attach(dev);
2885         CURVNET_RESTORE();
2886         return error;
2887 }
2888
2889 /**
2890  * @brief Attach a device driver to a device
2891  *
2892  * This function is a wrapper around the DEVICE_ATTACH() driver
2893  * method. In addition to calling DEVICE_ATTACH(), it initialises the
2894  * device's sysctl tree, optionally prints a description of the device
2895  * and queues a notification event for user-based device management
2896  * services.
2897  *
2898  * Normally this function is only called internally from
2899  * device_probe_and_attach().
2900  *
2901  * @param dev           the device to initialise
2902  *
2903  * @retval 0            success
2904  * @retval ENXIO        no driver was found
2905  * @retval ENOMEM       memory allocation failure
2906  * @retval non-zero     some other unix error code
2907  */
2908 int
2909 device_attach(device_t dev)
2910 {
2911         uint64_t attachtime;
2912         uint16_t attachentropy;
2913         int error;
2914
2915         if (resource_disabled(dev->driver->name, dev->unit)) {
2916                 device_disable(dev);
2917                 if (bootverbose)
2918                          device_printf(dev, "disabled via hints entry\n");
2919                 return (ENXIO);
2920         }
2921
2922         device_sysctl_init(dev);
2923         if (!device_is_quiet(dev))
2924                 device_print_child(dev->parent, dev);
2925         attachtime = get_cyclecount();
2926         dev->state = DS_ATTACHING;
2927         if ((error = DEVICE_ATTACH(dev)) != 0) {
2928                 printf("device_attach: %s%d attach returned %d\n",
2929                     dev->driver->name, dev->unit, error);
2930                 if (!(dev->flags & DF_FIXEDCLASS))
2931                         devclass_delete_device(dev->devclass, dev);
2932                 (void)device_set_driver(dev, NULL);
2933                 device_sysctl_fini(dev);
2934                 KASSERT(dev->busy == 0, ("attach failed but busy"));
2935                 dev->state = DS_NOTPRESENT;
2936                 return (error);
2937         }
2938         dev->flags |= DF_ATTACHED_ONCE;
2939         /* We only need the low bits of this time, but ranges from tens to thousands
2940          * have been seen, so keep 2 bytes' worth.
2941          */
2942         attachentropy = (uint16_t)(get_cyclecount() - attachtime);
2943         random_harvest_direct(&attachentropy, sizeof(attachentropy), RANDOM_ATTACH);
2944         device_sysctl_update(dev);
2945         if (dev->busy)
2946                 dev->state = DS_BUSY;
2947         else
2948                 dev->state = DS_ATTACHED;
2949         dev->flags &= ~DF_DONENOMATCH;
2950         EVENTHANDLER_DIRECT_INVOKE(device_attach, dev);
2951         devadded(dev);
2952         return (0);
2953 }
2954
2955 /**
2956  * @brief Detach a driver from a device
2957  *
2958  * This function is a wrapper around the DEVICE_DETACH() driver
2959  * method. If the call to DEVICE_DETACH() succeeds, it calls
2960  * BUS_CHILD_DETACHED() for the parent of @p dev, queues a
2961  * notification event for user-based device management services and
2962  * cleans up the device's sysctl tree.
2963  *
2964  * @param dev           the device to un-initialise
2965  *
2966  * @retval 0            success
2967  * @retval ENXIO        no driver was found
2968  * @retval ENOMEM       memory allocation failure
2969  * @retval non-zero     some other unix error code
2970  */
2971 int
2972 device_detach(device_t dev)
2973 {
2974         int error;
2975
2976         GIANT_REQUIRED;
2977
2978         PDEBUG(("%s", DEVICENAME(dev)));
2979         if (dev->state == DS_BUSY)
2980                 return (EBUSY);
2981         if (dev->state == DS_ATTACHING) {
2982                 device_printf(dev, "device in attaching state! Deferring detach.\n");
2983                 return (EBUSY);
2984         }
2985         if (dev->state != DS_ATTACHED)
2986                 return (0);
2987
2988         EVENTHANDLER_DIRECT_INVOKE(device_detach, dev, EVHDEV_DETACH_BEGIN);
2989         if ((error = DEVICE_DETACH(dev)) != 0) {
2990                 EVENTHANDLER_DIRECT_INVOKE(device_detach, dev,
2991                     EVHDEV_DETACH_FAILED);
2992                 return (error);
2993         } else {
2994                 EVENTHANDLER_DIRECT_INVOKE(device_detach, dev,
2995                     EVHDEV_DETACH_COMPLETE);
2996         }
2997         devremoved(dev);
2998         if (!device_is_quiet(dev))
2999                 device_printf(dev, "detached\n");
3000         if (dev->parent)
3001                 BUS_CHILD_DETACHED(dev->parent, dev);
3002
3003         if (!(dev->flags & DF_FIXEDCLASS))
3004                 devclass_delete_device(dev->devclass, dev);
3005
3006         device_verbose(dev);
3007         dev->state = DS_NOTPRESENT;
3008         (void)device_set_driver(dev, NULL);
3009         device_sysctl_fini(dev);
3010
3011         return (0);
3012 }
3013
3014 /**
3015  * @brief Tells a driver to quiesce itself.
3016  *
3017  * This function is a wrapper around the DEVICE_QUIESCE() driver
3018  * method. If the call to DEVICE_QUIESCE() succeeds.
3019  *
3020  * @param dev           the device to quiesce
3021  *
3022  * @retval 0            success
3023  * @retval ENXIO        no driver was found
3024  * @retval ENOMEM       memory allocation failure
3025  * @retval non-zero     some other unix error code
3026  */
3027 int
3028 device_quiesce(device_t dev)
3029 {
3030         PDEBUG(("%s", DEVICENAME(dev)));
3031         if (dev->state == DS_BUSY)
3032                 return (EBUSY);
3033         if (dev->state != DS_ATTACHED)
3034                 return (0);
3035
3036         return (DEVICE_QUIESCE(dev));
3037 }
3038
3039 /**
3040  * @brief Notify a device of system shutdown
3041  *
3042  * This function calls the DEVICE_SHUTDOWN() driver method if the
3043  * device currently has an attached driver.
3044  *
3045  * @returns the value returned by DEVICE_SHUTDOWN()
3046  */
3047 int
3048 device_shutdown(device_t dev)
3049 {
3050         if (dev->state < DS_ATTACHED)
3051                 return (0);
3052         return (DEVICE_SHUTDOWN(dev));
3053 }
3054
3055 /**
3056  * @brief Set the unit number of a device
3057  *
3058  * This function can be used to override the unit number used for a
3059  * device (e.g. to wire a device to a pre-configured unit number).
3060  */
3061 int
3062 device_set_unit(device_t dev, int unit)
3063 {
3064         devclass_t dc;
3065         int err;
3066
3067         dc = device_get_devclass(dev);
3068         if (unit < dc->maxunit && dc->devices[unit])
3069                 return (EBUSY);
3070         err = devclass_delete_device(dc, dev);
3071         if (err)
3072                 return (err);
3073         dev->unit = unit;
3074         err = devclass_add_device(dc, dev);
3075         if (err)
3076                 return (err);
3077
3078         bus_data_generation_update();
3079         return (0);
3080 }
3081
3082 /*======================================*/
3083 /*
3084  * Some useful method implementations to make life easier for bus drivers.
3085  */
3086
3087 void
3088 resource_init_map_request_impl(struct resource_map_request *args, size_t sz)
3089 {
3090         bzero(args, sz);
3091         args->size = sz;
3092         args->memattr = VM_MEMATTR_UNCACHEABLE;
3093 }
3094
3095 /**
3096  * @brief Initialise a resource list.
3097  *
3098  * @param rl            the resource list to initialise
3099  */
3100 void
3101 resource_list_init(struct resource_list *rl)
3102 {
3103         STAILQ_INIT(rl);
3104 }
3105
3106 /**
3107  * @brief Reclaim memory used by a resource list.
3108  *
3109  * This function frees the memory for all resource entries on the list
3110  * (if any).
3111  *
3112  * @param rl            the resource list to free
3113  */
3114 void
3115 resource_list_free(struct resource_list *rl)
3116 {
3117         struct resource_list_entry *rle;
3118
3119         while ((rle = STAILQ_FIRST(rl)) != NULL) {
3120                 if (rle->res)
3121                         panic("resource_list_free: resource entry is busy");
3122                 STAILQ_REMOVE_HEAD(rl, link);
3123                 free(rle, M_BUS);
3124         }
3125 }
3126
3127 /**
3128  * @brief Add a resource entry.
3129  *
3130  * This function adds a resource entry using the given @p type, @p
3131  * start, @p end and @p count values. A rid value is chosen by
3132  * searching sequentially for the first unused rid starting at zero.
3133  *
3134  * @param rl            the resource list to edit
3135  * @param type          the resource entry type (e.g. SYS_RES_MEMORY)
3136  * @param start         the start address of the resource
3137  * @param end           the end address of the resource
3138  * @param count         XXX end-start+1
3139  */
3140 int
3141 resource_list_add_next(struct resource_list *rl, int type, rman_res_t start,
3142     rman_res_t end, rman_res_t count)
3143 {
3144         int rid;
3145
3146         rid = 0;
3147         while (resource_list_find(rl, type, rid) != NULL)
3148                 rid++;
3149         resource_list_add(rl, type, rid, start, end, count);
3150         return (rid);
3151 }
3152
3153 /**
3154  * @brief Add or modify a resource entry.
3155  *
3156  * If an existing entry exists with the same type and rid, it will be
3157  * modified using the given values of @p start, @p end and @p
3158  * count. If no entry exists, a new one will be created using the
3159  * given values.  The resource list entry that matches is then returned.
3160  *
3161  * @param rl            the resource list to edit
3162  * @param type          the resource entry type (e.g. SYS_RES_MEMORY)
3163  * @param rid           the resource identifier
3164  * @param start         the start address of the resource
3165  * @param end           the end address of the resource
3166  * @param count         XXX end-start+1
3167  */
3168 struct resource_list_entry *
3169 resource_list_add(struct resource_list *rl, int type, int rid,
3170     rman_res_t start, rman_res_t end, rman_res_t count)
3171 {
3172         struct resource_list_entry *rle;
3173
3174         rle = resource_list_find(rl, type, rid);
3175         if (!rle) {
3176                 rle = malloc(sizeof(struct resource_list_entry), M_BUS,
3177                     M_NOWAIT);
3178                 if (!rle)
3179                         panic("resource_list_add: can't record entry");
3180                 STAILQ_INSERT_TAIL(rl, rle, link);
3181                 rle->type = type;
3182                 rle->rid = rid;
3183                 rle->res = NULL;
3184                 rle->flags = 0;
3185         }
3186
3187         if (rle->res)
3188                 panic("resource_list_add: resource entry is busy");
3189
3190         rle->start = start;
3191         rle->end = end;
3192         rle->count = count;
3193         return (rle);
3194 }
3195
3196 /**
3197  * @brief Determine if a resource entry is busy.
3198  *
3199  * Returns true if a resource entry is busy meaning that it has an
3200  * associated resource that is not an unallocated "reserved" resource.
3201  *
3202  * @param rl            the resource list to search
3203  * @param type          the resource entry type (e.g. SYS_RES_MEMORY)
3204  * @param rid           the resource identifier
3205  *
3206  * @returns Non-zero if the entry is busy, zero otherwise.
3207  */
3208 int
3209 resource_list_busy(struct resource_list *rl, int type, int rid)
3210 {
3211         struct resource_list_entry *rle;
3212
3213         rle = resource_list_find(rl, type, rid);
3214         if (rle == NULL || rle->res == NULL)
3215                 return (0);
3216         if ((rle->flags & (RLE_RESERVED | RLE_ALLOCATED)) == RLE_RESERVED) {
3217                 KASSERT(!(rman_get_flags(rle->res) & RF_ACTIVE),
3218                     ("reserved resource is active"));
3219                 return (0);
3220         }
3221         return (1);
3222 }
3223
3224 /**
3225  * @brief Determine if a resource entry is reserved.
3226  *
3227  * Returns true if a resource entry is reserved meaning that it has an
3228  * associated "reserved" resource.  The resource can either be
3229  * allocated or unallocated.
3230  *
3231  * @param rl            the resource list to search
3232  * @param type          the resource entry type (e.g. SYS_RES_MEMORY)
3233  * @param rid           the resource identifier
3234  *
3235  * @returns Non-zero if the entry is reserved, zero otherwise.
3236  */
3237 int
3238 resource_list_reserved(struct resource_list *rl, int type, int rid)
3239 {
3240         struct resource_list_entry *rle;
3241
3242         rle = resource_list_find(rl, type, rid);
3243         if (rle != NULL && rle->flags & RLE_RESERVED)
3244                 return (1);
3245         return (0);
3246 }
3247
3248 /**
3249  * @brief Find a resource entry by type and rid.
3250  *
3251  * @param rl            the resource list to search
3252  * @param type          the resource entry type (e.g. SYS_RES_MEMORY)
3253  * @param rid           the resource identifier
3254  *
3255  * @returns the resource entry pointer or NULL if there is no such
3256  * entry.
3257  */
3258 struct resource_list_entry *
3259 resource_list_find(struct resource_list *rl, int type, int rid)
3260 {
3261         struct resource_list_entry *rle;
3262
3263         STAILQ_FOREACH(rle, rl, link) {
3264                 if (rle->type == type && rle->rid == rid)
3265                         return (rle);
3266         }
3267         return (NULL);
3268 }
3269
3270 /**
3271  * @brief Delete a resource entry.
3272  *
3273  * @param rl            the resource list to edit
3274  * @param type          the resource entry type (e.g. SYS_RES_MEMORY)
3275  * @param rid           the resource identifier
3276  */
3277 void
3278 resource_list_delete(struct resource_list *rl, int type, int rid)
3279 {
3280         struct resource_list_entry *rle = resource_list_find(rl, type, rid);
3281
3282         if (rle) {
3283                 if (rle->res != NULL)
3284                         panic("resource_list_delete: resource has not been released");
3285                 STAILQ_REMOVE(rl, rle, resource_list_entry, link);
3286                 free(rle, M_BUS);
3287         }
3288 }
3289
3290 /**
3291  * @brief Allocate a reserved resource
3292  *
3293  * This can be used by buses to force the allocation of resources
3294  * that are always active in the system even if they are not allocated
3295  * by a driver (e.g. PCI BARs).  This function is usually called when
3296  * adding a new child to the bus.  The resource is allocated from the
3297  * parent bus when it is reserved.  The resource list entry is marked
3298  * with RLE_RESERVED to note that it is a reserved resource.
3299  *
3300  * Subsequent attempts to allocate the resource with
3301  * resource_list_alloc() will succeed the first time and will set
3302  * RLE_ALLOCATED to note that it has been allocated.  When a reserved
3303  * resource that has been allocated is released with
3304  * resource_list_release() the resource RLE_ALLOCATED is cleared, but
3305  * the actual resource remains allocated.  The resource can be released to
3306  * the parent bus by calling resource_list_unreserve().
3307  *
3308  * @param rl            the resource list to allocate from
3309  * @param bus           the parent device of @p child
3310  * @param child         the device for which the resource is being reserved
3311  * @param type          the type of resource to allocate
3312  * @param rid           a pointer to the resource identifier
3313  * @param start         hint at the start of the resource range - pass
3314  *                      @c 0 for any start address
3315  * @param end           hint at the end of the resource range - pass
3316  *                      @c ~0 for any end address
3317  * @param count         hint at the size of range required - pass @c 1
3318  *                      for any size
3319  * @param flags         any extra flags to control the resource
3320  *                      allocation - see @c RF_XXX flags in
3321  *                      <sys/rman.h> for details
3322  *
3323  * @returns             the resource which was allocated or @c NULL if no
3324  *                      resource could be allocated
3325  */
3326 struct resource *
3327 resource_list_reserve(struct resource_list *rl, device_t bus, device_t child,
3328     int type, int *rid, rman_res_t start, rman_res_t end, rman_res_t count, u_int flags)
3329 {
3330         struct resource_list_entry *rle = NULL;
3331         int passthrough = (device_get_parent(child) != bus);
3332         struct resource *r;
3333
3334         if (passthrough)
3335                 panic(
3336     "resource_list_reserve() should only be called for direct children");
3337         if (flags & RF_ACTIVE)
3338                 panic(
3339     "resource_list_reserve() should only reserve inactive resources");
3340
3341         r = resource_list_alloc(rl, bus, child, type, rid, start, end, count,
3342             flags);
3343         if (r != NULL) {
3344                 rle = resource_list_find(rl, type, *rid);
3345                 rle->flags |= RLE_RESERVED;
3346         }
3347         return (r);
3348 }
3349
3350 /**
3351  * @brief Helper function for implementing BUS_ALLOC_RESOURCE()
3352  *
3353  * Implement BUS_ALLOC_RESOURCE() by looking up a resource from the list
3354  * and passing the allocation up to the parent of @p bus. This assumes
3355  * that the first entry of @c device_get_ivars(child) is a struct
3356  * resource_list. This also handles 'passthrough' allocations where a
3357  * child is a remote descendant of bus by passing the allocation up to
3358  * the parent of bus.
3359  *
3360  * Typically, a bus driver would store a list of child resources
3361  * somewhere in the child device's ivars (see device_get_ivars()) and
3362  * its implementation of BUS_ALLOC_RESOURCE() would find that list and
3363  * then call resource_list_alloc() to perform the allocation.
3364  *
3365  * @param rl            the resource list to allocate from
3366  * @param bus           the parent device of @p child
3367  * @param child         the device which is requesting an allocation
3368  * @param type          the type of resource to allocate
3369  * @param rid           a pointer to the resource identifier
3370  * @param start         hint at the start of the resource range - pass
3371  *                      @c 0 for any start address
3372  * @param end           hint at the end of the resource range - pass
3373  *                      @c ~0 for any end address
3374  * @param count         hint at the size of range required - pass @c 1
3375  *                      for any size
3376  * @param flags         any extra flags to control the resource
3377  *                      allocation - see @c RF_XXX flags in
3378  *                      <sys/rman.h> for details
3379  *
3380  * @returns             the resource which was allocated or @c NULL if no
3381  *                      resource could be allocated
3382  */
3383 struct resource *
3384 resource_list_alloc(struct resource_list *rl, device_t bus, device_t child,
3385     int type, int *rid, rman_res_t start, rman_res_t end, rman_res_t count, u_int flags)
3386 {
3387         struct resource_list_entry *rle = NULL;
3388         int passthrough = (device_get_parent(child) != bus);
3389         int isdefault = RMAN_IS_DEFAULT_RANGE(start, end);
3390
3391         if (passthrough) {
3392                 return (BUS_ALLOC_RESOURCE(device_get_parent(bus), child,
3393                     type, rid, start, end, count, flags));
3394         }
3395
3396         rle = resource_list_find(rl, type, *rid);
3397
3398         if (!rle)
3399                 return (NULL);          /* no resource of that type/rid */
3400
3401         if (rle->res) {
3402                 if (rle->flags & RLE_RESERVED) {
3403                         if (rle->flags & RLE_ALLOCATED)
3404                                 return (NULL);
3405                         if ((flags & RF_ACTIVE) &&
3406                             bus_activate_resource(child, type, *rid,
3407                             rle->res) != 0)
3408                                 return (NULL);
3409                         rle->flags |= RLE_ALLOCATED;
3410                         return (rle->res);
3411                 }
3412                 device_printf(bus,
3413                     "resource entry %#x type %d for child %s is busy\n", *rid,
3414                     type, device_get_nameunit(child));
3415                 return (NULL);
3416         }
3417
3418         if (isdefault) {
3419                 start = rle->start;
3420                 count = ulmax(count, rle->count);
3421                 end = ulmax(rle->end, start + count - 1);
3422         }
3423
3424         rle->res = BUS_ALLOC_RESOURCE(device_get_parent(bus), child,
3425             type, rid, start, end, count, flags);
3426
3427         /*
3428          * Record the new range.
3429          */
3430         if (rle->res) {
3431                 rle->start = rman_get_start(rle->res);
3432                 rle->end = rman_get_end(rle->res);
3433                 rle->count = count;
3434         }
3435
3436         return (rle->res);
3437 }
3438
3439 /**
3440  * @brief Helper function for implementing BUS_RELEASE_RESOURCE()
3441  *
3442  * Implement BUS_RELEASE_RESOURCE() using a resource list. Normally
3443  * used with resource_list_alloc().
3444  *
3445  * @param rl            the resource list which was allocated from
3446  * @param bus           the parent device of @p child
3447  * @param child         the device which is requesting a release
3448  * @param type          the type of resource to release
3449  * @param rid           the resource identifier
3450  * @param res           the resource to release
3451  *
3452  * @retval 0            success
3453  * @retval non-zero     a standard unix error code indicating what
3454  *                      error condition prevented the operation
3455  */
3456 int
3457 resource_list_release(struct resource_list *rl, device_t bus, device_t child,
3458     int type, int rid, struct resource *res)
3459 {
3460         struct resource_list_entry *rle = NULL;
3461         int passthrough = (device_get_parent(child) != bus);
3462         int error;
3463
3464         if (passthrough) {
3465                 return (BUS_RELEASE_RESOURCE(device_get_parent(bus), child,
3466                     type, rid, res));
3467         }
3468
3469         rle = resource_list_find(rl, type, rid);
3470
3471         if (!rle)
3472                 panic("resource_list_release: can't find resource");
3473         if (!rle->res)
3474                 panic("resource_list_release: resource entry is not busy");
3475         if (rle->flags & RLE_RESERVED) {
3476                 if (rle->flags & RLE_ALLOCATED) {
3477                         if (rman_get_flags(res) & RF_ACTIVE) {
3478                                 error = bus_deactivate_resource(child, type,
3479                                     rid, res);
3480                                 if (error)
3481                                         return (error);
3482                         }
3483                         rle->flags &= ~RLE_ALLOCATED;
3484                         return (0);
3485                 }
3486                 return (EINVAL);
3487         }
3488
3489         error = BUS_RELEASE_RESOURCE(device_get_parent(bus), child,
3490             type, rid, res);
3491         if (error)
3492                 return (error);
3493
3494         rle->res = NULL;
3495         return (0);
3496 }
3497
3498 /**
3499  * @brief Release all active resources of a given type
3500  *
3501  * Release all active resources of a specified type.  This is intended
3502  * to be used to cleanup resources leaked by a driver after detach or
3503  * a failed attach.
3504  *
3505  * @param rl            the resource list which was allocated from
3506  * @param bus           the parent device of @p child
3507  * @param child         the device whose active resources are being released
3508  * @param type          the type of resources to release
3509  *
3510  * @retval 0            success
3511  * @retval EBUSY        at least one resource was active
3512  */
3513 int
3514 resource_list_release_active(struct resource_list *rl, device_t bus,
3515     device_t child, int type)
3516 {
3517         struct resource_list_entry *rle;
3518         int error, retval;
3519
3520         retval = 0;
3521         STAILQ_FOREACH(rle, rl, link) {
3522                 if (rle->type != type)
3523                         continue;
3524                 if (rle->res == NULL)
3525                         continue;
3526                 if ((rle->flags & (RLE_RESERVED | RLE_ALLOCATED)) ==
3527                     RLE_RESERVED)
3528                         continue;
3529                 retval = EBUSY;
3530                 error = resource_list_release(rl, bus, child, type,
3531                     rman_get_rid(rle->res), rle->res);
3532                 if (error != 0)
3533                         device_printf(bus,
3534                             "Failed to release active resource: %d\n", error);
3535         }
3536         return (retval);
3537 }
3538
3539 /**
3540  * @brief Fully release a reserved resource
3541  *
3542  * Fully releases a resource reserved via resource_list_reserve().
3543  *
3544  * @param rl            the resource list which was allocated from
3545  * @param bus           the parent device of @p child
3546  * @param child         the device whose reserved resource is being released
3547  * @param type          the type of resource to release
3548  * @param rid           the resource identifier
3549  * @param res           the resource to release
3550  *
3551  * @retval 0            success
3552  * @retval non-zero     a standard unix error code indicating what
3553  *                      error condition prevented the operation
3554  */
3555 int
3556 resource_list_unreserve(struct resource_list *rl, device_t bus, device_t child,
3557     int type, int rid)
3558 {
3559         struct resource_list_entry *rle = NULL;
3560         int passthrough = (device_get_parent(child) != bus);
3561
3562         if (passthrough)
3563                 panic(
3564     "resource_list_unreserve() should only be called for direct children");
3565
3566         rle = resource_list_find(rl, type, rid);
3567
3568         if (!rle)
3569                 panic("resource_list_unreserve: can't find resource");
3570         if (!(rle->flags & RLE_RESERVED))
3571                 return (EINVAL);
3572         if (rle->flags & RLE_ALLOCATED)
3573                 return (EBUSY);
3574         rle->flags &= ~RLE_RESERVED;
3575         return (resource_list_release(rl, bus, child, type, rid, rle->res));
3576 }
3577
3578 /**
3579  * @brief Print a description of resources in a resource list
3580  *
3581  * Print all resources of a specified type, for use in BUS_PRINT_CHILD().
3582  * The name is printed if at least one resource of the given type is available.
3583  * The format is used to print resource start and end.
3584  *
3585  * @param rl            the resource list to print
3586  * @param name          the name of @p type, e.g. @c "memory"
3587  * @param type          type type of resource entry to print
3588  * @param format        printf(9) format string to print resource
3589  *                      start and end values
3590  *
3591  * @returns             the number of characters printed
3592  */
3593 int
3594 resource_list_print_type(struct resource_list *rl, const char *name, int type,
3595     const char *format)
3596 {
3597         struct resource_list_entry *rle;
3598         int printed, retval;
3599
3600         printed = 0;
3601         retval = 0;
3602         /* Yes, this is kinda cheating */
3603         STAILQ_FOREACH(rle, rl, link) {
3604                 if (rle->type == type) {
3605                         if (printed == 0)
3606                                 retval += printf(" %s ", name);
3607                         else
3608                                 retval += printf(",");
3609                         printed++;
3610                         retval += printf(format, rle->start);
3611                         if (rle->count > 1) {
3612                                 retval += printf("-");
3613                                 retval += printf(format, rle->start +
3614                                                  rle->count - 1);
3615                         }
3616                 }
3617         }
3618         return (retval);
3619 }
3620
3621 /**
3622  * @brief Releases all the resources in a list.
3623  *
3624  * @param rl            The resource list to purge.
3625  *
3626  * @returns             nothing
3627  */
3628 void
3629 resource_list_purge(struct resource_list *rl)
3630 {
3631         struct resource_list_entry *rle;
3632
3633         while ((rle = STAILQ_FIRST(rl)) != NULL) {
3634                 if (rle->res)
3635                         bus_release_resource(rman_get_device(rle->res),
3636                             rle->type, rle->rid, rle->res);
3637                 STAILQ_REMOVE_HEAD(rl, link);
3638                 free(rle, M_BUS);
3639         }
3640 }
3641
3642 device_t
3643 bus_generic_add_child(device_t dev, u_int order, const char *name, int unit)
3644 {
3645         return (device_add_child_ordered(dev, order, name, unit));
3646 }
3647
3648 /**
3649  * @brief Helper function for implementing DEVICE_PROBE()
3650  *
3651  * This function can be used to help implement the DEVICE_PROBE() for
3652  * a bus (i.e. a device which has other devices attached to it). It
3653  * calls the DEVICE_IDENTIFY() method of each driver in the device's
3654  * devclass.
3655  */
3656 int
3657 bus_generic_probe(device_t dev)
3658 {
3659         devclass_t dc = dev->devclass;
3660         driverlink_t dl;
3661
3662         TAILQ_FOREACH(dl, &dc->drivers, link) {
3663                 /*
3664                  * If this driver's pass is too high, then ignore it.
3665                  * For most drivers in the default pass, this will
3666                  * never be true.  For early-pass drivers they will
3667                  * only call the identify routines of eligible drivers
3668                  * when this routine is called.  Drivers for later
3669                  * passes should have their identify routines called
3670                  * on early-pass buses during BUS_NEW_PASS().
3671                  */
3672                 if (dl->pass > bus_current_pass)
3673                         continue;
3674                 DEVICE_IDENTIFY(dl->driver, dev);
3675         }
3676
3677         return (0);
3678 }
3679
3680 /**
3681  * @brief Helper function for implementing DEVICE_ATTACH()
3682  *
3683  * This function can be used to help implement the DEVICE_ATTACH() for
3684  * a bus. It calls device_probe_and_attach() for each of the device's
3685  * children.
3686  */
3687 int
3688 bus_generic_attach(device_t dev)
3689 {
3690         device_t child;
3691
3692         TAILQ_FOREACH(child, &dev->children, link) {
3693                 device_probe_and_attach(child);
3694         }
3695
3696         return (0);
3697 }
3698
3699 /**
3700  * @brief Helper function for delaying attaching children
3701  *
3702  * Many buses can't run transactions on the bus which children need to probe and
3703  * attach until after interrupts and/or timers are running.  This function
3704  * delays their attach until interrupts and timers are enabled.
3705  */
3706 int
3707 bus_delayed_attach_children(device_t dev)
3708 {
3709         /* Probe and attach the bus children when interrupts are available */
3710         config_intrhook_oneshot((ich_func_t)bus_generic_attach, dev);
3711
3712         return (0);
3713 }
3714
3715 /**
3716  * @brief Helper function for implementing DEVICE_DETACH()
3717  *
3718  * This function can be used to help implement the DEVICE_DETACH() for
3719  * a bus. It calls device_detach() for each of the device's
3720  * children.
3721  */
3722 int
3723 bus_generic_detach(device_t dev)
3724 {
3725         device_t child;
3726         int error;
3727
3728         if (dev->state != DS_ATTACHED)
3729                 return (EBUSY);
3730
3731         /*
3732          * Detach children in the reverse order.
3733          * See bus_generic_suspend for details.
3734          */
3735         TAILQ_FOREACH_REVERSE(child, &dev->children, device_list, link) {
3736                 if ((error = device_detach(child)) != 0)
3737                         return (error);
3738         }
3739
3740         return (0);
3741 }
3742
3743 /**
3744  * @brief Helper function for implementing DEVICE_SHUTDOWN()
3745  *
3746  * This function can be used to help implement the DEVICE_SHUTDOWN()
3747  * for a bus. It calls device_shutdown() for each of the device's
3748  * children.
3749  */
3750 int
3751 bus_generic_shutdown(device_t dev)
3752 {
3753         device_t child;
3754
3755         /*
3756          * Shut down children in the reverse order.
3757          * See bus_generic_suspend for details.
3758          */
3759         TAILQ_FOREACH_REVERSE(child, &dev->children, device_list, link) {
3760                 device_shutdown(child);
3761         }
3762
3763         return (0);
3764 }
3765
3766 /**
3767  * @brief Default function for suspending a child device.
3768  *
3769  * This function is to be used by a bus's DEVICE_SUSPEND_CHILD().
3770  */
3771 int
3772 bus_generic_suspend_child(device_t dev, device_t child)
3773 {
3774         int     error;
3775
3776         error = DEVICE_SUSPEND(child);
3777
3778         if (error == 0)
3779                 child->flags |= DF_SUSPENDED;
3780
3781         return (error);
3782 }
3783
3784 /**
3785  * @brief Default function for resuming a child device.
3786  *
3787  * This function is to be used by a bus's DEVICE_RESUME_CHILD().
3788  */
3789 int
3790 bus_generic_resume_child(device_t dev, device_t child)
3791 {
3792         DEVICE_RESUME(child);
3793         child->flags &= ~DF_SUSPENDED;
3794
3795         return (0);
3796 }
3797
3798 /**
3799  * @brief Helper function for implementing DEVICE_SUSPEND()
3800  *
3801  * This function can be used to help implement the DEVICE_SUSPEND()
3802  * for a bus. It calls DEVICE_SUSPEND() for each of the device's
3803  * children. If any call to DEVICE_SUSPEND() fails, the suspend
3804  * operation is aborted and any devices which were suspended are
3805  * resumed immediately by calling their DEVICE_RESUME() methods.
3806  */
3807 int
3808 bus_generic_suspend(device_t dev)
3809 {
3810         int             error;
3811         device_t        child;
3812
3813         /*
3814          * Suspend children in the reverse order.
3815          * For most buses all children are equal, so the order does not matter.
3816          * Other buses, such as acpi, carefully order their child devices to
3817          * express implicit dependencies between them.  For such buses it is
3818          * safer to bring down devices in the reverse order.
3819          */
3820         TAILQ_FOREACH_REVERSE(child, &dev->children, device_list, link) {
3821                 error = BUS_SUSPEND_CHILD(dev, child);
3822                 if (error != 0) {
3823                         child = TAILQ_NEXT(child, link);
3824                         if (child != NULL) {
3825                                 TAILQ_FOREACH_FROM(child, &dev->children, link)
3826                                         BUS_RESUME_CHILD(dev, child);
3827                         }
3828                         return (error);
3829                 }
3830         }
3831         return (0);
3832 }
3833
3834 /**
3835  * @brief Helper function for implementing DEVICE_RESUME()
3836  *
3837  * This function can be used to help implement the DEVICE_RESUME() for
3838  * a bus. It calls DEVICE_RESUME() on each of the device's children.
3839  */
3840 int
3841 bus_generic_resume(device_t dev)
3842 {
3843         device_t        child;
3844
3845         TAILQ_FOREACH(child, &dev->children, link) {
3846                 BUS_RESUME_CHILD(dev, child);
3847                 /* if resume fails, there's nothing we can usefully do... */
3848         }
3849         return (0);
3850 }
3851
3852 /**
3853  * @brief Helper function for implementing BUS_RESET_POST
3854  *
3855  * Bus can use this function to implement common operations of
3856  * re-attaching or resuming the children after the bus itself was
3857  * reset, and after restoring bus-unique state of children.
3858  *
3859  * @param dev   The bus
3860  * #param flags DEVF_RESET_*
3861  */
3862 int
3863 bus_helper_reset_post(device_t dev, int flags)
3864 {
3865         device_t child;
3866         int error, error1;
3867
3868         error = 0;
3869         TAILQ_FOREACH(child, &dev->children,link) {
3870                 BUS_RESET_POST(dev, child);
3871                 error1 = (flags & DEVF_RESET_DETACH) != 0 ?
3872                     device_probe_and_attach(child) :
3873                     BUS_RESUME_CHILD(dev, child);
3874                 if (error == 0 && error1 != 0)
3875                         error = error1;
3876         }
3877         return (error);
3878 }
3879
3880 static void
3881 bus_helper_reset_prepare_rollback(device_t dev, device_t child, int flags)
3882 {
3883         child = TAILQ_NEXT(child, link);
3884         if (child == NULL)
3885                 return;
3886         TAILQ_FOREACH_FROM(child, &dev->children,link) {
3887                 BUS_RESET_POST(dev, child);
3888                 if ((flags & DEVF_RESET_DETACH) != 0)
3889                         device_probe_and_attach(child);
3890                 else
3891                         BUS_RESUME_CHILD(dev, child);
3892         }
3893 }
3894
3895 /**
3896  * @brief Helper function for implementing BUS_RESET_PREPARE
3897  *
3898  * Bus can use this function to implement common operations of
3899  * detaching or suspending the children before the bus itself is
3900  * reset, and then save bus-unique state of children that must
3901  * persists around reset.
3902  *
3903  * @param dev   The bus
3904  * #param flags DEVF_RESET_*
3905  */
3906 int
3907 bus_helper_reset_prepare(device_t dev, int flags)
3908 {
3909         device_t child;
3910         int error;
3911
3912         if (dev->state != DS_ATTACHED)
3913                 return (EBUSY);
3914
3915         TAILQ_FOREACH_REVERSE(child, &dev->children, device_list, link) {
3916                 if ((flags & DEVF_RESET_DETACH) != 0) {
3917                         error = device_get_state(child) == DS_ATTACHED ?
3918                             device_detach(child) : 0;
3919                 } else {
3920                         error = BUS_SUSPEND_CHILD(dev, child);
3921                 }
3922                 if (error == 0) {
3923                         error = BUS_RESET_PREPARE(dev, child);
3924                         if (error != 0) {
3925                                 if ((flags & DEVF_RESET_DETACH) != 0)
3926                                         device_probe_and_attach(child);
3927                                 else
3928                                         BUS_RESUME_CHILD(dev, child);
3929                         }
3930                 }
3931                 if (error != 0) {
3932                         bus_helper_reset_prepare_rollback(dev, child, flags);
3933                         return (error);
3934                 }
3935         }
3936         return (0);
3937 }
3938
3939 /**
3940  * @brief Helper function for implementing BUS_PRINT_CHILD().
3941  *
3942  * This function prints the first part of the ascii representation of
3943  * @p child, including its name, unit and description (if any - see
3944  * device_set_desc()).
3945  *
3946  * @returns the number of characters printed
3947  */
3948 int
3949 bus_print_child_header(device_t dev, device_t child)
3950 {
3951         int     retval = 0;
3952
3953         if (device_get_desc(child)) {
3954                 retval += device_printf(child, "<%s>", device_get_desc(child));
3955         } else {
3956                 retval += printf("%s", device_get_nameunit(child));
3957         }
3958
3959         return (retval);
3960 }
3961
3962 /**
3963  * @brief Helper function for implementing BUS_PRINT_CHILD().
3964  *
3965  * This function prints the last part of the ascii representation of
3966  * @p child, which consists of the string @c " on " followed by the
3967  * name and unit of the @p dev.
3968  *
3969  * @returns the number of characters printed
3970  */
3971 int
3972 bus_print_child_footer(device_t dev, device_t child)
3973 {
3974         return (printf(" on %s\n", device_get_nameunit(dev)));
3975 }
3976
3977 /**
3978  * @brief Helper function for implementing BUS_PRINT_CHILD().
3979  *
3980  * This function prints out the VM domain for the given device.
3981  *
3982  * @returns the number of characters printed
3983  */
3984 int
3985 bus_print_child_domain(device_t dev, device_t child)
3986 {
3987         int domain;
3988
3989         /* No domain? Don't print anything */
3990         if (BUS_GET_DOMAIN(dev, child, &domain) != 0)
3991                 return (0);
3992
3993         return (printf(" numa-domain %d", domain));
3994 }
3995
3996 /**
3997  * @brief Helper function for implementing BUS_PRINT_CHILD().
3998  *
3999  * This function simply calls bus_print_child_header() followed by
4000  * bus_print_child_footer().
4001  *
4002  * @returns the number of characters printed
4003  */
4004 int
4005 bus_generic_print_child(device_t dev, device_t child)
4006 {
4007         int     retval = 0;
4008
4009         retval += bus_print_child_header(dev, child);
4010         retval += bus_print_child_domain(dev, child);
4011         retval += bus_print_child_footer(dev, child);
4012
4013         return (retval);
4014 }
4015
4016 /**
4017  * @brief Stub function for implementing BUS_READ_IVAR().
4018  *
4019  * @returns ENOENT
4020  */
4021 int
4022 bus_generic_read_ivar(device_t dev, device_t child, int index,
4023     uintptr_t * result)
4024 {
4025         return (ENOENT);
4026 }
4027
4028 /**
4029  * @brief Stub function for implementing BUS_WRITE_IVAR().
4030  *
4031  * @returns ENOENT
4032  */
4033 int
4034 bus_generic_write_ivar(device_t dev, device_t child, int index,
4035     uintptr_t value)
4036 {
4037         return (ENOENT);
4038 }
4039
4040 /**
4041  * @brief Stub function for implementing BUS_GET_RESOURCE_LIST().
4042  *
4043  * @returns NULL
4044  */
4045 struct resource_list *
4046 bus_generic_get_resource_list(device_t dev, device_t child)
4047 {
4048         return (NULL);
4049 }
4050
4051 /**
4052  * @brief Helper function for implementing BUS_DRIVER_ADDED().
4053  *
4054  * This implementation of BUS_DRIVER_ADDED() simply calls the driver's
4055  * DEVICE_IDENTIFY() method to allow it to add new children to the bus
4056  * and then calls device_probe_and_attach() for each unattached child.
4057  */
4058 void
4059 bus_generic_driver_added(device_t dev, driver_t *driver)
4060 {
4061         device_t child;
4062
4063         DEVICE_IDENTIFY(driver, dev);
4064         TAILQ_FOREACH(child, &dev->children, link) {
4065                 if (child->state == DS_NOTPRESENT ||
4066                     (child->flags & DF_REBID))
4067                         device_probe_and_attach(child);
4068         }
4069 }
4070
4071 /**
4072  * @brief Helper function for implementing BUS_NEW_PASS().
4073  *
4074  * This implementing of BUS_NEW_PASS() first calls the identify
4075  * routines for any drivers that probe at the current pass.  Then it
4076  * walks the list of devices for this bus.  If a device is already
4077  * attached, then it calls BUS_NEW_PASS() on that device.  If the
4078  * device is not already attached, it attempts to attach a driver to
4079  * it.
4080  */
4081 void
4082 bus_generic_new_pass(device_t dev)
4083 {
4084         driverlink_t dl;
4085         devclass_t dc;
4086         device_t child;
4087
4088         dc = dev->devclass;
4089         TAILQ_FOREACH(dl, &dc->drivers, link) {
4090                 if (dl->pass == bus_current_pass)
4091                         DEVICE_IDENTIFY(dl->driver, dev);
4092         }
4093         TAILQ_FOREACH(child, &dev->children, link) {
4094                 if (child->state >= DS_ATTACHED)
4095                         BUS_NEW_PASS(child);
4096                 else if (child->state == DS_NOTPRESENT)
4097                         device_probe_and_attach(child);
4098         }
4099 }
4100
4101 /**
4102  * @brief Helper function for implementing BUS_SETUP_INTR().
4103  *
4104  * This simple implementation of BUS_SETUP_INTR() simply calls the
4105  * BUS_SETUP_INTR() method of the parent of @p dev.
4106  */
4107 int
4108 bus_generic_setup_intr(device_t dev, device_t child, struct resource *irq,
4109     int flags, driver_filter_t *filter, driver_intr_t *intr, void *arg,
4110     void **cookiep)
4111 {
4112         /* Propagate up the bus hierarchy until someone handles it. */
4113         if (dev->parent)
4114                 return (BUS_SETUP_INTR(dev->parent, child, irq, flags,
4115                     filter, intr, arg, cookiep));
4116         return (EINVAL);
4117 }
4118
4119 /**
4120  * @brief Helper function for implementing BUS_TEARDOWN_INTR().
4121  *
4122  * This simple implementation of BUS_TEARDOWN_INTR() simply calls the
4123  * BUS_TEARDOWN_INTR() method of the parent of @p dev.
4124  */
4125 int
4126 bus_generic_teardown_intr(device_t dev, device_t child, struct resource *irq,
4127     void *cookie)
4128 {
4129         /* Propagate up the bus hierarchy until someone handles it. */
4130         if (dev->parent)
4131                 return (BUS_TEARDOWN_INTR(dev->parent, child, irq, cookie));
4132         return (EINVAL);
4133 }
4134
4135 /**
4136  * @brief Helper function for implementing BUS_SUSPEND_INTR().
4137  *
4138  * This simple implementation of BUS_SUSPEND_INTR() simply calls the
4139  * BUS_SUSPEND_INTR() method of the parent of @p dev.
4140  */
4141 int
4142 bus_generic_suspend_intr(device_t dev, device_t child, struct resource *irq)
4143 {
4144         /* Propagate up the bus hierarchy until someone handles it. */
4145         if (dev->parent)
4146                 return (BUS_SUSPEND_INTR(dev->parent, child, irq));
4147         return (EINVAL);
4148 }
4149
4150 /**
4151  * @brief Helper function for implementing BUS_RESUME_INTR().
4152  *
4153  * This simple implementation of BUS_RESUME_INTR() simply calls the
4154  * BUS_RESUME_INTR() method of the parent of @p dev.
4155  */
4156 int
4157 bus_generic_resume_intr(device_t dev, device_t child, struct resource *irq)
4158 {
4159         /* Propagate up the bus hierarchy until someone handles it. */
4160         if (dev->parent)
4161                 return (BUS_RESUME_INTR(dev->parent, child, irq));
4162         return (EINVAL);
4163 }
4164
4165 /**
4166  * @brief Helper function for implementing BUS_ADJUST_RESOURCE().
4167  *
4168  * This simple implementation of BUS_ADJUST_RESOURCE() simply calls the
4169  * BUS_ADJUST_RESOURCE() method of the parent of @p dev.
4170  */
4171 int
4172 bus_generic_adjust_resource(device_t dev, device_t child, int type,
4173     struct resource *r, rman_res_t start, rman_res_t end)
4174 {
4175         /* Propagate up the bus hierarchy until someone handles it. */
4176         if (dev->parent)
4177                 return (BUS_ADJUST_RESOURCE(dev->parent, child, type, r, start,
4178                     end));
4179         return (EINVAL);
4180 }
4181
4182 /**
4183  * @brief Helper function for implementing BUS_ALLOC_RESOURCE().
4184  *
4185  * This simple implementation of BUS_ALLOC_RESOURCE() simply calls the
4186  * BUS_ALLOC_RESOURCE() method of the parent of @p dev.
4187  */
4188 struct resource *
4189 bus_generic_alloc_resource(device_t dev, device_t child, int type, int *rid,
4190     rman_res_t start, rman_res_t end, rman_res_t count, u_int flags)
4191 {
4192         /* Propagate up the bus hierarchy until someone handles it. */
4193         if (dev->parent)
4194                 return (BUS_ALLOC_RESOURCE(dev->parent, child, type, rid,
4195                     start, end, count, flags));
4196         return (NULL);
4197 }
4198
4199 /**
4200  * @brief Helper function for implementing BUS_RELEASE_RESOURCE().
4201  *
4202  * This simple implementation of BUS_RELEASE_RESOURCE() simply calls the
4203  * BUS_RELEASE_RESOURCE() method of the parent of @p dev.
4204  */
4205 int
4206 bus_generic_release_resource(device_t dev, device_t child, int type, int rid,
4207     struct resource *r)
4208 {
4209         /* Propagate up the bus hierarchy until someone handles it. */
4210         if (dev->parent)
4211                 return (BUS_RELEASE_RESOURCE(dev->parent, child, type, rid,
4212                     r));
4213         return (EINVAL);
4214 }
4215
4216 /**
4217  * @brief Helper function for implementing BUS_ACTIVATE_RESOURCE().
4218  *
4219  * This simple implementation of BUS_ACTIVATE_RESOURCE() simply calls the
4220  * BUS_ACTIVATE_RESOURCE() method of the parent of @p dev.
4221  */
4222 int
4223 bus_generic_activate_resource(device_t dev, device_t child, int type, int rid,
4224     struct resource *r)
4225 {
4226         /* Propagate up the bus hierarchy until someone handles it. */
4227         if (dev->parent)
4228                 return (BUS_ACTIVATE_RESOURCE(dev->parent, child, type, rid,
4229                     r));
4230         return (EINVAL);
4231 }
4232
4233 /**
4234  * @brief Helper function for implementing BUS_DEACTIVATE_RESOURCE().
4235  *
4236  * This simple implementation of BUS_DEACTIVATE_RESOURCE() simply calls the
4237  * BUS_DEACTIVATE_RESOURCE() method of the parent of @p dev.
4238  */
4239 int
4240 bus_generic_deactivate_resource(device_t dev, device_t child, int type,
4241     int rid, struct resource *r)
4242 {
4243         /* Propagate up the bus hierarchy until someone handles it. */
4244         if (dev->parent)
4245                 return (BUS_DEACTIVATE_RESOURCE(dev->parent, child, type, rid,
4246                     r));
4247         return (EINVAL);
4248 }
4249
4250 /**
4251  * @brief Helper function for implementing BUS_MAP_RESOURCE().
4252  *
4253  * This simple implementation of BUS_MAP_RESOURCE() simply calls the
4254  * BUS_MAP_RESOURCE() method of the parent of @p dev.
4255  */
4256 int
4257 bus_generic_map_resource(device_t dev, device_t child, int type,
4258     struct resource *r, struct resource_map_request *args,
4259     struct resource_map *map)
4260 {
4261         /* Propagate up the bus hierarchy until someone handles it. */
4262         if (dev->parent)
4263                 return (BUS_MAP_RESOURCE(dev->parent, child, type, r, args,
4264                     map));
4265         return (EINVAL);
4266 }
4267
4268 /**
4269  * @brief Helper function for implementing BUS_UNMAP_RESOURCE().
4270  *
4271  * This simple implementation of BUS_UNMAP_RESOURCE() simply calls the
4272  * BUS_UNMAP_RESOURCE() method of the parent of @p dev.
4273  */
4274 int
4275 bus_generic_unmap_resource(device_t dev, device_t child, int type,
4276     struct resource *r, struct resource_map *map)
4277 {
4278         /* Propagate up the bus hierarchy until someone handles it. */
4279         if (dev->parent)
4280                 return (BUS_UNMAP_RESOURCE(dev->parent, child, type, r, map));
4281         return (EINVAL);
4282 }
4283
4284 /**
4285  * @brief Helper function for implementing BUS_BIND_INTR().
4286  *
4287  * This simple implementation of BUS_BIND_INTR() simply calls the
4288  * BUS_BIND_INTR() method of the parent of @p dev.
4289  */
4290 int
4291 bus_generic_bind_intr(device_t dev, device_t child, struct resource *irq,
4292     int cpu)
4293 {
4294         /* Propagate up the bus hierarchy until someone handles it. */
4295         if (dev->parent)
4296                 return (BUS_BIND_INTR(dev->parent, child, irq, cpu));
4297         return (EINVAL);
4298 }
4299
4300 /**
4301  * @brief Helper function for implementing BUS_CONFIG_INTR().
4302  *
4303  * This simple implementation of BUS_CONFIG_INTR() simply calls the
4304  * BUS_CONFIG_INTR() method of the parent of @p dev.
4305  */
4306 int
4307 bus_generic_config_intr(device_t dev, int irq, enum intr_trigger trig,
4308     enum intr_polarity pol)
4309 {
4310         /* Propagate up the bus hierarchy until someone handles it. */
4311         if (dev->parent)
4312                 return (BUS_CONFIG_INTR(dev->parent, irq, trig, pol));
4313         return (EINVAL);
4314 }
4315
4316 /**
4317  * @brief Helper function for implementing BUS_DESCRIBE_INTR().
4318  *
4319  * This simple implementation of BUS_DESCRIBE_INTR() simply calls the
4320  * BUS_DESCRIBE_INTR() method of the parent of @p dev.
4321  */
4322 int
4323 bus_generic_describe_intr(device_t dev, device_t child, struct resource *irq,
4324     void *cookie, const char *descr)
4325 {
4326         /* Propagate up the bus hierarchy until someone handles it. */
4327         if (dev->parent)
4328                 return (BUS_DESCRIBE_INTR(dev->parent, child, irq, cookie,
4329                     descr));
4330         return (EINVAL);
4331 }
4332
4333 /**
4334  * @brief Helper function for implementing BUS_GET_CPUS().
4335  *
4336  * This simple implementation of BUS_GET_CPUS() simply calls the
4337  * BUS_GET_CPUS() method of the parent of @p dev.
4338  */
4339 int
4340 bus_generic_get_cpus(device_t dev, device_t child, enum cpu_sets op,
4341     size_t setsize, cpuset_t *cpuset)
4342 {
4343         /* Propagate up the bus hierarchy until someone handles it. */
4344         if (dev->parent != NULL)
4345                 return (BUS_GET_CPUS(dev->parent, child, op, setsize, cpuset));
4346         return (EINVAL);
4347 }
4348
4349 /**
4350  * @brief Helper function for implementing BUS_GET_DMA_TAG().
4351  *
4352  * This simple implementation of BUS_GET_DMA_TAG() simply calls the
4353  * BUS_GET_DMA_TAG() method of the parent of @p dev.
4354  */
4355 bus_dma_tag_t
4356 bus_generic_get_dma_tag(device_t dev, device_t child)
4357 {
4358         /* Propagate up the bus hierarchy until someone handles it. */
4359         if (dev->parent != NULL)
4360                 return (BUS_GET_DMA_TAG(dev->parent, child));
4361         return (NULL);
4362 }
4363
4364 /**
4365  * @brief Helper function for implementing BUS_GET_BUS_TAG().
4366  *
4367  * This simple implementation of BUS_GET_BUS_TAG() simply calls the
4368  * BUS_GET_BUS_TAG() method of the parent of @p dev.
4369  */
4370 bus_space_tag_t
4371 bus_generic_get_bus_tag(device_t dev, device_t child)
4372 {
4373         /* Propagate up the bus hierarchy until someone handles it. */
4374         if (dev->parent != NULL)
4375                 return (BUS_GET_BUS_TAG(dev->parent, child));
4376         return ((bus_space_tag_t)0);
4377 }
4378
4379 /**
4380  * @brief Helper function for implementing BUS_GET_RESOURCE().
4381  *
4382  * This implementation of BUS_GET_RESOURCE() uses the
4383  * resource_list_find() function to do most of the work. It calls
4384  * BUS_GET_RESOURCE_LIST() to find a suitable resource list to
4385  * search.
4386  */
4387 int
4388 bus_generic_rl_get_resource(device_t dev, device_t child, int type, int rid,
4389     rman_res_t *startp, rman_res_t *countp)
4390 {
4391         struct resource_list *          rl = NULL;
4392         struct resource_list_entry *    rle = NULL;
4393
4394         rl = BUS_GET_RESOURCE_LIST(dev, child);
4395         if (!rl)
4396                 return (EINVAL);
4397
4398         rle = resource_list_find(rl, type, rid);
4399         if (!rle)
4400                 return (ENOENT);
4401
4402         if (startp)
4403                 *startp = rle->start;
4404         if (countp)
4405                 *countp = rle->count;
4406
4407         return (0);
4408 }
4409
4410 /**
4411  * @brief Helper function for implementing BUS_SET_RESOURCE().
4412  *
4413  * This implementation of BUS_SET_RESOURCE() uses the
4414  * resource_list_add() function to do most of the work. It calls
4415  * BUS_GET_RESOURCE_LIST() to find a suitable resource list to
4416  * edit.
4417  */
4418 int
4419 bus_generic_rl_set_resource(device_t dev, device_t child, int type, int rid,
4420     rman_res_t start, rman_res_t count)
4421 {
4422         struct resource_list *          rl = NULL;
4423
4424         rl = BUS_GET_RESOURCE_LIST(dev, child);
4425         if (!rl)
4426                 return (EINVAL);
4427
4428         resource_list_add(rl, type, rid, start, (start + count - 1), count);
4429
4430         return (0);
4431 }
4432
4433 /**
4434  * @brief Helper function for implementing BUS_DELETE_RESOURCE().
4435  *
4436  * This implementation of BUS_DELETE_RESOURCE() uses the
4437  * resource_list_delete() function to do most of the work. It calls
4438  * BUS_GET_RESOURCE_LIST() to find a suitable resource list to
4439  * edit.
4440  */
4441 void
4442 bus_generic_rl_delete_resource(device_t dev, device_t child, int type, int rid)
4443 {
4444         struct resource_list *          rl = NULL;
4445
4446         rl = BUS_GET_RESOURCE_LIST(dev, child);
4447         if (!rl)
4448                 return;
4449
4450         resource_list_delete(rl, type, rid);
4451
4452         return;
4453 }
4454
4455 /**
4456  * @brief Helper function for implementing BUS_RELEASE_RESOURCE().
4457  *
4458  * This implementation of BUS_RELEASE_RESOURCE() uses the
4459  * resource_list_release() function to do most of the work. It calls
4460  * BUS_GET_RESOURCE_LIST() to find a suitable resource list.
4461  */
4462 int
4463 bus_generic_rl_release_resource(device_t dev, device_t child, int type,
4464     int rid, struct resource *r)
4465 {
4466         struct resource_list *          rl = NULL;
4467
4468         if (device_get_parent(child) != dev)
4469                 return (BUS_RELEASE_RESOURCE(device_get_parent(dev), child,
4470                     type, rid, r));
4471
4472         rl = BUS_GET_RESOURCE_LIST(dev, child);
4473         if (!rl)
4474                 return (EINVAL);
4475
4476         return (resource_list_release(rl, dev, child, type, rid, r));
4477 }
4478
4479 /**
4480  * @brief Helper function for implementing BUS_ALLOC_RESOURCE().
4481  *
4482  * This implementation of BUS_ALLOC_RESOURCE() uses the
4483  * resource_list_alloc() function to do most of the work. It calls
4484  * BUS_GET_RESOURCE_LIST() to find a suitable resource list.
4485  */
4486 struct resource *
4487 bus_generic_rl_alloc_resource(device_t dev, device_t child, int type,
4488     int *rid, rman_res_t start, rman_res_t end, rman_res_t count, u_int flags)
4489 {
4490         struct resource_list *          rl = NULL;
4491
4492         if (device_get_parent(child) != dev)
4493                 return (BUS_ALLOC_RESOURCE(device_get_parent(dev), child,
4494                     type, rid, start, end, count, flags));
4495
4496         rl = BUS_GET_RESOURCE_LIST(dev, child);
4497         if (!rl)
4498                 return (NULL);
4499
4500         return (resource_list_alloc(rl, dev, child, type, rid,
4501             start, end, count, flags));
4502 }
4503
4504 /**
4505  * @brief Helper function for implementing BUS_CHILD_PRESENT().
4506  *
4507  * This simple implementation of BUS_CHILD_PRESENT() simply calls the
4508  * BUS_CHILD_PRESENT() method of the parent of @p dev.
4509  */
4510 int
4511 bus_generic_child_present(device_t dev, device_t child)
4512 {
4513         return (BUS_CHILD_PRESENT(device_get_parent(dev), dev));
4514 }
4515
4516 int
4517 bus_generic_get_domain(device_t dev, device_t child, int *domain)
4518 {
4519         if (dev->parent)
4520                 return (BUS_GET_DOMAIN(dev->parent, dev, domain));
4521
4522         return (ENOENT);
4523 }
4524
4525 /**
4526  * @brief Helper function for implementing BUS_RESCAN().
4527  *
4528  * This null implementation of BUS_RESCAN() always fails to indicate
4529  * the bus does not support rescanning.
4530  */
4531 int
4532 bus_null_rescan(device_t dev)
4533 {
4534         return (ENXIO);
4535 }
4536
4537 /*
4538  * Some convenience functions to make it easier for drivers to use the
4539  * resource-management functions.  All these really do is hide the
4540  * indirection through the parent's method table, making for slightly
4541  * less-wordy code.  In the future, it might make sense for this code
4542  * to maintain some sort of a list of resources allocated by each device.
4543  */
4544
4545 int
4546 bus_alloc_resources(device_t dev, struct resource_spec *rs,
4547     struct resource **res)
4548 {
4549         int i;
4550
4551         for (i = 0; rs[i].type != -1; i++)
4552                 res[i] = NULL;
4553         for (i = 0; rs[i].type != -1; i++) {
4554                 res[i] = bus_alloc_resource_any(dev,
4555                     rs[i].type, &rs[i].rid, rs[i].flags);
4556                 if (res[i] == NULL && !(rs[i].flags & RF_OPTIONAL)) {
4557                         bus_release_resources(dev, rs, res);
4558                         return (ENXIO);
4559                 }
4560         }
4561         return (0);
4562 }
4563
4564 void
4565 bus_release_resources(device_t dev, const struct resource_spec *rs,
4566     struct resource **res)
4567 {
4568         int i;
4569
4570         for (i = 0; rs[i].type != -1; i++)
4571                 if (res[i] != NULL) {
4572                         bus_release_resource(
4573                             dev, rs[i].type, rs[i].rid, res[i]);
4574                         res[i] = NULL;
4575                 }
4576 }
4577
4578 /**
4579  * @brief Wrapper function for BUS_ALLOC_RESOURCE().
4580  *
4581  * This function simply calls the BUS_ALLOC_RESOURCE() method of the
4582  * parent of @p dev.
4583  */
4584 struct resource *
4585 bus_alloc_resource(device_t dev, int type, int *rid, rman_res_t start,
4586     rman_res_t end, rman_res_t count, u_int flags)
4587 {
4588         struct resource *res;
4589
4590         if (dev->parent == NULL)
4591                 return (NULL);
4592         res = BUS_ALLOC_RESOURCE(dev->parent, dev, type, rid, start, end,
4593             count, flags);
4594         return (res);
4595 }
4596
4597 /**
4598  * @brief Wrapper function for BUS_ADJUST_RESOURCE().
4599  *
4600  * This function simply calls the BUS_ADJUST_RESOURCE() method of the
4601  * parent of @p dev.
4602  */
4603 int
4604 bus_adjust_resource(device_t dev, int type, struct resource *r, rman_res_t start,
4605     rman_res_t end)
4606 {
4607         if (dev->parent == NULL)
4608                 return (EINVAL);
4609         return (BUS_ADJUST_RESOURCE(dev->parent, dev, type, r, start, end));
4610 }
4611
4612 /**
4613  * @brief Wrapper function for BUS_ACTIVATE_RESOURCE().
4614  *
4615  * This function simply calls the BUS_ACTIVATE_RESOURCE() method of the
4616  * parent of @p dev.
4617  */
4618 int
4619 bus_activate_resource(device_t dev, int type, int rid, struct resource *r)
4620 {
4621         if (dev->parent == NULL)
4622                 return (EINVAL);
4623         return (BUS_ACTIVATE_RESOURCE(dev->parent, dev, type, rid, r));
4624 }
4625
4626 /**
4627  * @brief Wrapper function for BUS_DEACTIVATE_RESOURCE().
4628  *
4629  * This function simply calls the BUS_DEACTIVATE_RESOURCE() method of the
4630  * parent of @p dev.
4631  */
4632 int
4633 bus_deactivate_resource(device_t dev, int type, int rid, struct resource *r)
4634 {
4635         if (dev->parent == NULL)
4636                 return (EINVAL);
4637         return (BUS_DEACTIVATE_RESOURCE(dev->parent, dev, type, rid, r));
4638 }
4639
4640 /**
4641  * @brief Wrapper function for BUS_MAP_RESOURCE().
4642  *
4643  * This function simply calls the BUS_MAP_RESOURCE() method of the
4644  * parent of @p dev.
4645  */
4646 int
4647 bus_map_resource(device_t dev, int type, struct resource *r,
4648     struct resource_map_request *args, struct resource_map *map)
4649 {
4650         if (dev->parent == NULL)
4651                 return (EINVAL);
4652         return (BUS_MAP_RESOURCE(dev->parent, dev, type, r, args, map));
4653 }
4654
4655 /**
4656  * @brief Wrapper function for BUS_UNMAP_RESOURCE().
4657  *
4658  * This function simply calls the BUS_UNMAP_RESOURCE() method of the
4659  * parent of @p dev.
4660  */
4661 int
4662 bus_unmap_resource(device_t dev, int type, struct resource *r,
4663     struct resource_map *map)
4664 {
4665         if (dev->parent == NULL)
4666                 return (EINVAL);
4667         return (BUS_UNMAP_RESOURCE(dev->parent, dev, type, r, map));
4668 }
4669
4670 /**
4671  * @brief Wrapper function for BUS_RELEASE_RESOURCE().
4672  *
4673  * This function simply calls the BUS_RELEASE_RESOURCE() method of the
4674  * parent of @p dev.
4675  */
4676 int
4677 bus_release_resource(device_t dev, int type, int rid, struct resource *r)
4678 {
4679         int rv;
4680
4681         if (dev->parent == NULL)
4682                 return (EINVAL);
4683         rv = BUS_RELEASE_RESOURCE(dev->parent, dev, type, rid, r);
4684         return (rv);
4685 }
4686
4687 /**
4688  * @brief Wrapper function for BUS_SETUP_INTR().
4689  *
4690  * This function simply calls the BUS_SETUP_INTR() method of the
4691  * parent of @p dev.
4692  */
4693 int
4694 bus_setup_intr(device_t dev, struct resource *r, int flags,
4695     driver_filter_t filter, driver_intr_t handler, void *arg, void **cookiep)
4696 {
4697         int error;
4698
4699         if (dev->parent == NULL)
4700                 return (EINVAL);
4701         error = BUS_SETUP_INTR(dev->parent, dev, r, flags, filter, handler,
4702             arg, cookiep);
4703         if (error != 0)
4704                 return (error);
4705         if (handler != NULL && !(flags & INTR_MPSAFE))
4706                 device_printf(dev, "[GIANT-LOCKED]\n");
4707         return (0);
4708 }
4709
4710 /**
4711  * @brief Wrapper function for BUS_TEARDOWN_INTR().
4712  *
4713  * This function simply calls the BUS_TEARDOWN_INTR() method of the
4714  * parent of @p dev.
4715  */
4716 int
4717 bus_teardown_intr(device_t dev, struct resource *r, void *cookie)
4718 {
4719         if (dev->parent == NULL)
4720                 return (EINVAL);
4721         return (BUS_TEARDOWN_INTR(dev->parent, dev, r, cookie));
4722 }
4723
4724 /**
4725  * @brief Wrapper function for BUS_SUSPEND_INTR().
4726  *
4727  * This function simply calls the BUS_SUSPEND_INTR() method of the
4728  * parent of @p dev.
4729  */
4730 int
4731 bus_suspend_intr(device_t dev, struct resource *r)
4732 {
4733         if (dev->parent == NULL)
4734                 return (EINVAL);
4735         return (BUS_SUSPEND_INTR(dev->parent, dev, r));
4736 }
4737
4738 /**
4739  * @brief Wrapper function for BUS_RESUME_INTR().
4740  *
4741  * This function simply calls the BUS_RESUME_INTR() method of the
4742  * parent of @p dev.
4743  */
4744 int
4745 bus_resume_intr(device_t dev, struct resource *r)
4746 {
4747         if (dev->parent == NULL)
4748                 return (EINVAL);
4749         return (BUS_RESUME_INTR(dev->parent, dev, r));
4750 }
4751
4752 /**
4753  * @brief Wrapper function for BUS_BIND_INTR().
4754  *
4755  * This function simply calls the BUS_BIND_INTR() method of the
4756  * parent of @p dev.
4757  */
4758 int
4759 bus_bind_intr(device_t dev, struct resource *r, int cpu)
4760 {
4761         if (dev->parent == NULL)
4762                 return (EINVAL);
4763         return (BUS_BIND_INTR(dev->parent, dev, r, cpu));
4764 }
4765
4766 /**
4767  * @brief Wrapper function for BUS_DESCRIBE_INTR().
4768  *
4769  * This function first formats the requested description into a
4770  * temporary buffer and then calls the BUS_DESCRIBE_INTR() method of
4771  * the parent of @p dev.
4772  */
4773 int
4774 bus_describe_intr(device_t dev, struct resource *irq, void *cookie,
4775     const char *fmt, ...)
4776 {
4777         va_list ap;
4778         char descr[MAXCOMLEN + 1];
4779
4780         if (dev->parent == NULL)
4781                 return (EINVAL);
4782         va_start(ap, fmt);
4783         vsnprintf(descr, sizeof(descr), fmt, ap);
4784         va_end(ap);
4785         return (BUS_DESCRIBE_INTR(dev->parent, dev, irq, cookie, descr));
4786 }
4787
4788 /**
4789  * @brief Wrapper function for BUS_SET_RESOURCE().
4790  *
4791  * This function simply calls the BUS_SET_RESOURCE() method of the
4792  * parent of @p dev.
4793  */
4794 int
4795 bus_set_resource(device_t dev, int type, int rid,
4796     rman_res_t start, rman_res_t count)
4797 {
4798         return (BUS_SET_RESOURCE(device_get_parent(dev), dev, type, rid,
4799             start, count));
4800 }
4801
4802 /**
4803  * @brief Wrapper function for BUS_GET_RESOURCE().
4804  *
4805  * This function simply calls the BUS_GET_RESOURCE() method of the
4806  * parent of @p dev.
4807  */
4808 int
4809 bus_get_resource(device_t dev, int type, int rid,
4810     rman_res_t *startp, rman_res_t *countp)
4811 {
4812         return (BUS_GET_RESOURCE(device_get_parent(dev), dev, type, rid,
4813             startp, countp));
4814 }
4815
4816 /**
4817  * @brief Wrapper function for BUS_GET_RESOURCE().
4818  *
4819  * This function simply calls the BUS_GET_RESOURCE() method of the
4820  * parent of @p dev and returns the start value.
4821  */
4822 rman_res_t
4823 bus_get_resource_start(device_t dev, int type, int rid)
4824 {
4825         rman_res_t start;
4826         rman_res_t count;
4827         int error;
4828
4829         error = BUS_GET_RESOURCE(device_get_parent(dev), dev, type, rid,
4830             &start, &count);
4831         if (error)
4832                 return (0);
4833         return (start);
4834 }
4835
4836 /**
4837  * @brief Wrapper function for BUS_GET_RESOURCE().
4838  *
4839  * This function simply calls the BUS_GET_RESOURCE() method of the
4840  * parent of @p dev and returns the count value.
4841  */
4842 rman_res_t
4843 bus_get_resource_count(device_t dev, int type, int rid)
4844 {
4845         rman_res_t start;
4846         rman_res_t count;
4847         int error;
4848
4849         error = BUS_GET_RESOURCE(device_get_parent(dev), dev, type, rid,
4850             &start, &count);
4851         if (error)
4852                 return (0);
4853         return (count);
4854 }
4855
4856 /**
4857  * @brief Wrapper function for BUS_DELETE_RESOURCE().
4858  *
4859  * This function simply calls the BUS_DELETE_RESOURCE() method of the
4860  * parent of @p dev.
4861  */
4862 void
4863 bus_delete_resource(device_t dev, int type, int rid)
4864 {
4865         BUS_DELETE_RESOURCE(device_get_parent(dev), dev, type, rid);
4866 }
4867
4868 /**
4869  * @brief Wrapper function for BUS_CHILD_PRESENT().
4870  *
4871  * This function simply calls the BUS_CHILD_PRESENT() method of the
4872  * parent of @p dev.
4873  */
4874 int
4875 bus_child_present(device_t child)
4876 {
4877         return (BUS_CHILD_PRESENT(device_get_parent(child), child));
4878 }
4879
4880 /**
4881  * @brief Wrapper function for BUS_CHILD_PNPINFO_STR().
4882  *
4883  * This function simply calls the BUS_CHILD_PNPINFO_STR() method of the
4884  * parent of @p dev.
4885  */
4886 int
4887 bus_child_pnpinfo_str(device_t child, char *buf, size_t buflen)
4888 {
4889         device_t parent;
4890
4891         parent = device_get_parent(child);
4892         if (parent == NULL) {
4893                 *buf = '\0';
4894                 return (0);
4895         }
4896         return (BUS_CHILD_PNPINFO_STR(parent, child, buf, buflen));
4897 }
4898
4899 /**
4900  * @brief Wrapper function for BUS_CHILD_LOCATION_STR().
4901  *
4902  * This function simply calls the BUS_CHILD_LOCATION_STR() method of the
4903  * parent of @p dev.
4904  */
4905 int
4906 bus_child_location_str(device_t child, char *buf, size_t buflen)
4907 {
4908         device_t parent;
4909
4910         parent = device_get_parent(child);
4911         if (parent == NULL) {
4912                 *buf = '\0';
4913                 return (0);
4914         }
4915         return (BUS_CHILD_LOCATION_STR(parent, child, buf, buflen));
4916 }
4917
4918 /**
4919  * @brief Wrapper function for bus_child_pnpinfo_str using sbuf
4920  *
4921  * A convenient wrapper frunction for bus_child_pnpinfo_str that allows
4922  * us to splat that into an sbuf. It uses unholy knowledge of sbuf to
4923  * accomplish this, however. It is an interim function until we can convert
4924  * this interface more fully.
4925  */
4926 /* Note: we reach inside of sbuf because it's API isn't rich enough to do this */
4927 #define SPACE(s)        ((s)->s_size - (s)->s_len)
4928 #define EOB(s)          ((s)->s_buf + (s)->s_len)
4929
4930 static int
4931 bus_child_pnpinfo_sb(device_t dev, struct sbuf *sb)
4932 {
4933         char *p;
4934         size_t space;
4935
4936         MPASS((sb->s_flags & SBUF_INCLUDENUL) == 0);
4937         if (sb->s_error != 0)
4938                 return (-1);
4939         p = EOB(sb);
4940         *p = '\0';      /* sbuf buffer isn't NUL terminated until sbuf_finish() */
4941         space = SPACE(sb);
4942         if (space <= 1) {
4943                 sb->s_error = ENOMEM;
4944                 return (-1);
4945         }
4946         bus_child_pnpinfo_str(dev, p, space);
4947         sb->s_len += strlen(p);
4948         return (0);
4949 }
4950
4951 /**
4952  * @brief Wrapper function for bus_child_pnpinfo_str using sbuf
4953  *
4954  * A convenient wrapper frunction for bus_child_pnpinfo_str that allows
4955  * us to splat that into an sbuf. It uses unholy knowledge of sbuf to
4956  * accomplish this, however. It is an interim function until we can convert
4957  * this interface more fully.
4958  */
4959 static int
4960 bus_child_location_sb(device_t dev, struct sbuf *sb)
4961 {
4962         char *p;
4963         size_t space;
4964
4965         MPASS((sb->s_flags & SBUF_INCLUDENUL) == 0);
4966         if (sb->s_error != 0)
4967                 return (-1);
4968         p = EOB(sb);
4969         *p = '\0';      /* sbuf buffer isn't NUL terminated until sbuf_finish() */
4970         space = SPACE(sb);
4971         if (space <= 1) {
4972                 sb->s_error = ENOMEM;
4973                 return (-1);
4974         }
4975         bus_child_location_str(dev, p, space);
4976         sb->s_len += strlen(p);
4977         return (0);
4978 }
4979 #undef SPACE
4980 #undef EOB
4981
4982 /**
4983  * @brief Wrapper function for BUS_GET_CPUS().
4984  *
4985  * This function simply calls the BUS_GET_CPUS() method of the
4986  * parent of @p dev.
4987  */
4988 int
4989 bus_get_cpus(device_t dev, enum cpu_sets op, size_t setsize, cpuset_t *cpuset)
4990 {
4991         device_t parent;
4992
4993         parent = device_get_parent(dev);
4994         if (parent == NULL)
4995                 return (EINVAL);
4996         return (BUS_GET_CPUS(parent, dev, op, setsize, cpuset));
4997 }
4998
4999 /**
5000  * @brief Wrapper function for BUS_GET_DMA_TAG().
5001  *
5002  * This function simply calls the BUS_GET_DMA_TAG() method of the
5003  * parent of @p dev.
5004  */
5005 bus_dma_tag_t
5006 bus_get_dma_tag(device_t dev)
5007 {
5008         device_t parent;
5009
5010         parent = device_get_parent(dev);
5011         if (parent == NULL)
5012                 return (NULL);
5013         return (BUS_GET_DMA_TAG(parent, dev));
5014 }
5015
5016 /**
5017  * @brief Wrapper function for BUS_GET_BUS_TAG().
5018  *
5019  * This function simply calls the BUS_GET_BUS_TAG() method of the
5020  * parent of @p dev.
5021  */
5022 bus_space_tag_t
5023 bus_get_bus_tag(device_t dev)
5024 {
5025         device_t parent;
5026
5027         parent = device_get_parent(dev);
5028         if (parent == NULL)
5029                 return ((bus_space_tag_t)0);
5030         return (BUS_GET_BUS_TAG(parent, dev));
5031 }
5032
5033 /**
5034  * @brief Wrapper function for BUS_GET_DOMAIN().
5035  *
5036  * This function simply calls the BUS_GET_DOMAIN() method of the
5037  * parent of @p dev.
5038  */
5039 int
5040 bus_get_domain(device_t dev, int *domain)
5041 {
5042         return (BUS_GET_DOMAIN(device_get_parent(dev), dev, domain));
5043 }
5044
5045 /* Resume all devices and then notify userland that we're up again. */
5046 static int
5047 root_resume(device_t dev)
5048 {
5049         int error;
5050
5051         error = bus_generic_resume(dev);
5052         if (error == 0) {
5053                 devctl_notify("kern", "power", "resume", NULL); /* Deprecated gone in 14 */
5054                 devctl_notify("kernel", "power", "resume", NULL);
5055         }
5056         return (error);
5057 }
5058
5059 static int
5060 root_print_child(device_t dev, device_t child)
5061 {
5062         int     retval = 0;
5063
5064         retval += bus_print_child_header(dev, child);
5065         retval += printf("\n");
5066
5067         return (retval);
5068 }
5069
5070 static int
5071 root_setup_intr(device_t dev, device_t child, struct resource *irq, int flags,
5072     driver_filter_t *filter, driver_intr_t *intr, void *arg, void **cookiep)
5073 {
5074         /*
5075          * If an interrupt mapping gets to here something bad has happened.
5076          */
5077         panic("root_setup_intr");
5078 }
5079
5080 /*
5081  * If we get here, assume that the device is permanent and really is
5082  * present in the system.  Removable bus drivers are expected to intercept
5083  * this call long before it gets here.  We return -1 so that drivers that
5084  * really care can check vs -1 or some ERRNO returned higher in the food
5085  * chain.
5086  */
5087 static int
5088 root_child_present(device_t dev, device_t child)
5089 {
5090         return (-1);
5091 }
5092
5093 static int
5094 root_get_cpus(device_t dev, device_t child, enum cpu_sets op, size_t setsize,
5095     cpuset_t *cpuset)
5096 {
5097         switch (op) {
5098         case INTR_CPUS:
5099                 /* Default to returning the set of all CPUs. */
5100                 if (setsize != sizeof(cpuset_t))
5101                         return (EINVAL);
5102                 *cpuset = all_cpus;
5103                 return (0);
5104         default:
5105                 return (EINVAL);
5106         }
5107 }
5108
5109 static kobj_method_t root_methods[] = {
5110         /* Device interface */
5111         KOBJMETHOD(device_shutdown,     bus_generic_shutdown),
5112         KOBJMETHOD(device_suspend,      bus_generic_suspend),
5113         KOBJMETHOD(device_resume,       root_resume),
5114
5115         /* Bus interface */
5116         KOBJMETHOD(bus_print_child,     root_print_child),
5117         KOBJMETHOD(bus_read_ivar,       bus_generic_read_ivar),
5118         KOBJMETHOD(bus_write_ivar,      bus_generic_write_ivar),
5119         KOBJMETHOD(bus_setup_intr,      root_setup_intr),
5120         KOBJMETHOD(bus_child_present,   root_child_present),
5121         KOBJMETHOD(bus_get_cpus,        root_get_cpus),
5122
5123         KOBJMETHOD_END
5124 };
5125
5126 static driver_t root_driver = {
5127         "root",
5128         root_methods,
5129         1,                      /* no softc */
5130 };
5131
5132 device_t        root_bus;
5133 devclass_t      root_devclass;
5134
5135 static int
5136 root_bus_module_handler(module_t mod, int what, void* arg)
5137 {
5138         switch (what) {
5139         case MOD_LOAD:
5140                 TAILQ_INIT(&bus_data_devices);
5141                 kobj_class_compile((kobj_class_t) &root_driver);
5142                 root_bus = make_device(NULL, "root", 0);
5143                 root_bus->desc = "System root bus";
5144                 kobj_init((kobj_t) root_bus, (kobj_class_t) &root_driver);
5145                 root_bus->driver = &root_driver;
5146                 root_bus->state = DS_ATTACHED;
5147                 root_devclass = devclass_find_internal("root", NULL, FALSE);
5148                 devinit();
5149                 return (0);
5150
5151         case MOD_SHUTDOWN:
5152                 device_shutdown(root_bus);
5153                 return (0);
5154         default:
5155                 return (EOPNOTSUPP);
5156         }
5157
5158         return (0);
5159 }
5160
5161 static moduledata_t root_bus_mod = {
5162         "rootbus",
5163         root_bus_module_handler,
5164         NULL
5165 };
5166 DECLARE_MODULE(rootbus, root_bus_mod, SI_SUB_DRIVERS, SI_ORDER_FIRST);
5167
5168 /**
5169  * @brief Automatically configure devices
5170  *
5171  * This function begins the autoconfiguration process by calling
5172  * device_probe_and_attach() for each child of the @c root0 device.
5173  */
5174 void
5175 root_bus_configure(void)
5176 {
5177         PDEBUG(("."));
5178
5179         /* Eventually this will be split up, but this is sufficient for now. */
5180         bus_set_pass(BUS_PASS_DEFAULT);
5181 }
5182
5183 /**
5184  * @brief Module handler for registering device drivers
5185  *
5186  * This module handler is used to automatically register device
5187  * drivers when modules are loaded. If @p what is MOD_LOAD, it calls
5188  * devclass_add_driver() for the driver described by the
5189  * driver_module_data structure pointed to by @p arg
5190  */
5191 int
5192 driver_module_handler(module_t mod, int what, void *arg)
5193 {
5194         struct driver_module_data *dmd;
5195         devclass_t bus_devclass;
5196         kobj_class_t driver;
5197         int error, pass;
5198
5199         dmd = (struct driver_module_data *)arg;
5200         bus_devclass = devclass_find_internal(dmd->dmd_busname, NULL, TRUE);
5201         error = 0;
5202
5203         switch (what) {
5204         case MOD_LOAD:
5205                 if (dmd->dmd_chainevh)
5206                         error = dmd->dmd_chainevh(mod,what,dmd->dmd_chainarg);
5207
5208                 pass = dmd->dmd_pass;
5209                 driver = dmd->dmd_driver;
5210                 PDEBUG(("Loading module: driver %s on bus %s (pass %d)",
5211                     DRIVERNAME(driver), dmd->dmd_busname, pass));
5212                 error = devclass_add_driver(bus_devclass, driver, pass,
5213                     dmd->dmd_devclass);
5214                 break;
5215
5216         case MOD_UNLOAD:
5217                 PDEBUG(("Unloading module: driver %s from bus %s",
5218                     DRIVERNAME(dmd->dmd_driver),
5219                     dmd->dmd_busname));
5220                 error = devclass_delete_driver(bus_devclass,
5221                     dmd->dmd_driver);
5222
5223                 if (!error && dmd->dmd_chainevh)
5224                         error = dmd->dmd_chainevh(mod,what,dmd->dmd_chainarg);
5225                 break;
5226         case MOD_QUIESCE:
5227                 PDEBUG(("Quiesce module: driver %s from bus %s",
5228                     DRIVERNAME(dmd->dmd_driver),
5229                     dmd->dmd_busname));
5230                 error = devclass_quiesce_driver(bus_devclass,
5231                     dmd->dmd_driver);
5232
5233                 if (!error && dmd->dmd_chainevh)
5234                         error = dmd->dmd_chainevh(mod,what,dmd->dmd_chainarg);
5235                 break;
5236         default:
5237                 error = EOPNOTSUPP;
5238                 break;
5239         }
5240
5241         return (error);
5242 }
5243
5244 /**
5245  * @brief Enumerate all hinted devices for this bus.
5246  *
5247  * Walks through the hints for this bus and calls the bus_hinted_child
5248  * routine for each one it fines.  It searches first for the specific
5249  * bus that's being probed for hinted children (eg isa0), and then for
5250  * generic children (eg isa).
5251  *
5252  * @param       dev     bus device to enumerate
5253  */
5254 void
5255 bus_enumerate_hinted_children(device_t bus)
5256 {
5257         int i;
5258         const char *dname, *busname;
5259         int dunit;
5260
5261         /*
5262          * enumerate all devices on the specific bus
5263          */
5264         busname = device_get_nameunit(bus);
5265         i = 0;
5266         while (resource_find_match(&i, &dname, &dunit, "at", busname) == 0)
5267                 BUS_HINTED_CHILD(bus, dname, dunit);
5268
5269         /*
5270          * and all the generic ones.
5271          */
5272         busname = device_get_name(bus);
5273         i = 0;
5274         while (resource_find_match(&i, &dname, &dunit, "at", busname) == 0)
5275                 BUS_HINTED_CHILD(bus, dname, dunit);
5276 }
5277
5278 #ifdef BUS_DEBUG
5279
5280 /* the _short versions avoid iteration by not calling anything that prints
5281  * more than oneliners. I love oneliners.
5282  */
5283
5284 static void
5285 print_device_short(device_t dev, int indent)
5286 {
5287         if (!dev)
5288                 return;
5289
5290         indentprintf(("device %d: <%s> %sparent,%schildren,%s%s%s%s%s%s,%sivars,%ssoftc,busy=%d\n",
5291             dev->unit, dev->desc,
5292             (dev->parent? "":"no "),
5293             (TAILQ_EMPTY(&dev->children)? "no ":""),
5294             (dev->flags&DF_ENABLED? "enabled,":"disabled,"),
5295             (dev->flags&DF_FIXEDCLASS? "fixed,":""),
5296             (dev->flags&DF_WILDCARD? "wildcard,":""),
5297             (dev->flags&DF_DESCMALLOCED? "descmalloced,":""),
5298             (dev->flags&DF_REBID? "rebiddable,":""),
5299             (dev->flags&DF_SUSPENDED? "suspended,":""),
5300             (dev->ivars? "":"no "),
5301             (dev->softc? "":"no "),
5302             dev->busy));
5303 }
5304
5305 static void
5306 print_device(device_t dev, int indent)
5307 {
5308         if (!dev)
5309                 return;
5310
5311         print_device_short(dev, indent);
5312
5313         indentprintf(("Parent:\n"));
5314         print_device_short(dev->parent, indent+1);
5315         indentprintf(("Driver:\n"));
5316         print_driver_short(dev->driver, indent+1);
5317         indentprintf(("Devclass:\n"));
5318         print_devclass_short(dev->devclass, indent+1);
5319 }
5320
5321 void
5322 print_device_tree_short(device_t dev, int indent)
5323 /* print the device and all its children (indented) */
5324 {
5325         device_t child;
5326
5327         if (!dev)
5328                 return;
5329
5330         print_device_short(dev, indent);
5331
5332         TAILQ_FOREACH(child, &dev->children, link) {
5333                 print_device_tree_short(child, indent+1);
5334         }
5335 }
5336
5337 void
5338 print_device_tree(device_t dev, int indent)
5339 /* print the device and all its children (indented) */
5340 {
5341         device_t child;
5342
5343         if (!dev)
5344                 return;
5345
5346         print_device(dev, indent);
5347
5348         TAILQ_FOREACH(child, &dev->children, link) {
5349                 print_device_tree(child, indent+1);
5350         }
5351 }
5352
5353 static void
5354 print_driver_short(driver_t *driver, int indent)
5355 {
5356         if (!driver)
5357                 return;
5358
5359         indentprintf(("driver %s: softc size = %zd\n",
5360             driver->name, driver->size));
5361 }
5362
5363 static void
5364 print_driver(driver_t *driver, int indent)
5365 {
5366         if (!driver)
5367                 return;
5368
5369         print_driver_short(driver, indent);
5370 }
5371
5372 static void
5373 print_driver_list(driver_list_t drivers, int indent)
5374 {
5375         driverlink_t driver;
5376
5377         TAILQ_FOREACH(driver, &drivers, link) {
5378                 print_driver(driver->driver, indent);
5379         }
5380 }
5381
5382 static void
5383 print_devclass_short(devclass_t dc, int indent)
5384 {
5385         if ( !dc )
5386                 return;
5387
5388         indentprintf(("devclass %s: max units = %d\n", dc->name, dc->maxunit));
5389 }
5390
5391 static void
5392 print_devclass(devclass_t dc, int indent)
5393 {
5394         int i;
5395
5396         if ( !dc )
5397                 return;
5398
5399         print_devclass_short(dc, indent);
5400         indentprintf(("Drivers:\n"));
5401         print_driver_list(dc->drivers, indent+1);
5402
5403         indentprintf(("Devices:\n"));
5404         for (i = 0; i < dc->maxunit; i++)
5405                 if (dc->devices[i])
5406                         print_device(dc->devices[i], indent+1);
5407 }
5408
5409 void
5410 print_devclass_list_short(void)
5411 {
5412         devclass_t dc;
5413
5414         printf("Short listing of devclasses, drivers & devices:\n");
5415         TAILQ_FOREACH(dc, &devclasses, link) {
5416                 print_devclass_short(dc, 0);
5417         }
5418 }
5419
5420 void
5421 print_devclass_list(void)
5422 {
5423         devclass_t dc;
5424
5425         printf("Full listing of devclasses, drivers & devices:\n");
5426         TAILQ_FOREACH(dc, &devclasses, link) {
5427                 print_devclass(dc, 0);
5428         }
5429 }
5430
5431 #endif
5432
5433 /*
5434  * User-space access to the device tree.
5435  *
5436  * We implement a small set of nodes:
5437  *
5438  * hw.bus                       Single integer read method to obtain the
5439  *                              current generation count.
5440  * hw.bus.devices               Reads the entire device tree in flat space.
5441  * hw.bus.rman                  Resource manager interface
5442  *
5443  * We might like to add the ability to scan devclasses and/or drivers to
5444  * determine what else is currently loaded/available.
5445  */
5446
5447 static int
5448 sysctl_bus_info(SYSCTL_HANDLER_ARGS)
5449 {
5450         struct u_businfo        ubus;
5451
5452         ubus.ub_version = BUS_USER_VERSION;
5453         ubus.ub_generation = bus_data_generation;
5454
5455         return (SYSCTL_OUT(req, &ubus, sizeof(ubus)));
5456 }
5457 SYSCTL_PROC(_hw_bus, OID_AUTO, info, CTLTYPE_STRUCT | CTLFLAG_RD |
5458     CTLFLAG_MPSAFE, NULL, 0, sysctl_bus_info, "S,u_businfo",
5459     "bus-related data");
5460
5461 static int
5462 sysctl_devices(SYSCTL_HANDLER_ARGS)
5463 {
5464         struct sbuf             sb;
5465         int                     *name = (int *)arg1;
5466         u_int                   namelen = arg2;
5467         int                     index;
5468         device_t                dev;
5469         struct u_device         *udev;
5470         int                     error;
5471
5472         if (namelen != 2)
5473                 return (EINVAL);
5474
5475         if (bus_data_generation_check(name[0]))
5476                 return (EINVAL);
5477
5478         index = name[1];
5479
5480         /*
5481          * Scan the list of devices, looking for the requested index.
5482          */
5483         TAILQ_FOREACH(dev, &bus_data_devices, devlink) {
5484                 if (index-- == 0)
5485                         break;
5486         }
5487         if (dev == NULL)
5488                 return (ENOENT);
5489
5490         /*
5491          * Populate the return item, careful not to overflow the buffer.
5492          */
5493         udev = malloc(sizeof(*udev), M_BUS, M_WAITOK | M_ZERO);
5494         if (udev == NULL)
5495                 return (ENOMEM);
5496         udev->dv_handle = (uintptr_t)dev;
5497         udev->dv_parent = (uintptr_t)dev->parent;
5498         udev->dv_devflags = dev->devflags;
5499         udev->dv_flags = dev->flags;
5500         udev->dv_state = dev->state;
5501         sbuf_new(&sb, udev->dv_fields, sizeof(udev->dv_fields), SBUF_FIXEDLEN);
5502         if (dev->nameunit != NULL)
5503                 sbuf_cat(&sb, dev->nameunit);
5504         else
5505                 sbuf_putc(&sb, '\0');
5506         sbuf_putc(&sb, '\0');
5507         if (dev->desc != NULL)
5508                 sbuf_cat(&sb, dev->desc);
5509         else
5510                 sbuf_putc(&sb, '\0');
5511         sbuf_putc(&sb, '\0');
5512         if (dev->driver != NULL)
5513                 sbuf_cat(&sb, dev->driver->name);
5514         else
5515                 sbuf_putc(&sb, '\0');
5516         sbuf_putc(&sb, '\0');
5517         bus_child_pnpinfo_sb(dev, &sb);
5518         sbuf_putc(&sb, '\0');
5519         bus_child_location_sb(dev, &sb);
5520         sbuf_putc(&sb, '\0');
5521         error = sbuf_finish(&sb);
5522         if (error == 0)
5523                 error = SYSCTL_OUT(req, udev, sizeof(*udev));
5524         sbuf_delete(&sb);
5525         free(udev, M_BUS);
5526         return (error);
5527 }
5528
5529 SYSCTL_NODE(_hw_bus, OID_AUTO, devices,
5530     CTLFLAG_RD | CTLFLAG_NEEDGIANT, sysctl_devices,
5531     "system device tree");
5532
5533 int
5534 bus_data_generation_check(int generation)
5535 {
5536         if (generation != bus_data_generation)
5537                 return (1);
5538
5539         /* XXX generate optimised lists here? */
5540         return (0);
5541 }
5542
5543 void
5544 bus_data_generation_update(void)
5545 {
5546         atomic_add_int(&bus_data_generation, 1);
5547 }
5548
5549 int
5550 bus_free_resource(device_t dev, int type, struct resource *r)
5551 {
5552         if (r == NULL)
5553                 return (0);
5554         return (bus_release_resource(dev, type, rman_get_rid(r), r));
5555 }
5556
5557 device_t
5558 device_lookup_by_name(const char *name)
5559 {
5560         device_t dev;
5561
5562         TAILQ_FOREACH(dev, &bus_data_devices, devlink) {
5563                 if (dev->nameunit != NULL && strcmp(dev->nameunit, name) == 0)
5564                         return (dev);
5565         }
5566         return (NULL);
5567 }
5568
5569 /*
5570  * /dev/devctl2 implementation.  The existing /dev/devctl device has
5571  * implicit semantics on open, so it could not be reused for this.
5572  * Another option would be to call this /dev/bus?
5573  */
5574 static int
5575 find_device(struct devreq *req, device_t *devp)
5576 {
5577         device_t dev;
5578
5579         /*
5580          * First, ensure that the name is nul terminated.
5581          */
5582         if (memchr(req->dr_name, '\0', sizeof(req->dr_name)) == NULL)
5583                 return (EINVAL);
5584
5585         /*
5586          * Second, try to find an attached device whose name matches
5587          * 'name'.
5588          */
5589         dev = device_lookup_by_name(req->dr_name);
5590         if (dev != NULL) {
5591                 *devp = dev;
5592                 return (0);
5593         }
5594
5595         /* Finally, give device enumerators a chance. */
5596         dev = NULL;
5597         EVENTHANDLER_DIRECT_INVOKE(dev_lookup, req->dr_name, &dev);
5598         if (dev == NULL)
5599                 return (ENOENT);
5600         *devp = dev;
5601         return (0);
5602 }
5603
5604 static bool
5605 driver_exists(device_t bus, const char *driver)
5606 {
5607         devclass_t dc;
5608
5609         for (dc = bus->devclass; dc != NULL; dc = dc->parent) {
5610                 if (devclass_find_driver_internal(dc, driver) != NULL)
5611                         return (true);
5612         }
5613         return (false);
5614 }
5615
5616 static void
5617 device_gen_nomatch(device_t dev)
5618 {
5619         device_t child;
5620
5621         if (dev->flags & DF_NEEDNOMATCH &&
5622             dev->state == DS_NOTPRESENT) {
5623                 BUS_PROBE_NOMATCH(dev->parent, dev);
5624                 devnomatch(dev);
5625                 dev->flags |= DF_DONENOMATCH;
5626         }
5627         dev->flags &= ~DF_NEEDNOMATCH;
5628         TAILQ_FOREACH(child, &dev->children, link) {
5629                 device_gen_nomatch(child);
5630         }
5631 }
5632
5633 static void
5634 device_do_deferred_actions(void)
5635 {
5636         devclass_t dc;
5637         driverlink_t dl;
5638
5639         /*
5640          * Walk through the devclasses to find all the drivers we've tagged as
5641          * deferred during the freeze and call the driver added routines. They
5642          * have already been added to the lists in the background, so the driver
5643          * added routines that trigger a probe will have all the right bidders
5644          * for the probe auction.
5645          */
5646         TAILQ_FOREACH(dc, &devclasses, link) {
5647                 TAILQ_FOREACH(dl, &dc->drivers, link) {
5648                         if (dl->flags & DL_DEFERRED_PROBE) {
5649                                 devclass_driver_added(dc, dl->driver);
5650                                 dl->flags &= ~DL_DEFERRED_PROBE;
5651                         }
5652                 }
5653         }
5654
5655         /*
5656          * We also defer no-match events during a freeze. Walk the tree and
5657          * generate all the pent-up events that are still relevant.
5658          */
5659         device_gen_nomatch(root_bus);
5660         bus_data_generation_update();
5661 }
5662
5663 static int
5664 devctl2_ioctl(struct cdev *cdev, u_long cmd, caddr_t data, int fflag,
5665     struct thread *td)
5666 {
5667         struct devreq *req;
5668         device_t dev;
5669         int error, old;
5670
5671         /* Locate the device to control. */
5672         mtx_lock(&Giant);
5673         req = (struct devreq *)data;
5674         switch (cmd) {
5675         case DEV_ATTACH:
5676         case DEV_DETACH:
5677         case DEV_ENABLE:
5678         case DEV_DISABLE:
5679         case DEV_SUSPEND:
5680         case DEV_RESUME:
5681         case DEV_SET_DRIVER:
5682         case DEV_CLEAR_DRIVER:
5683         case DEV_RESCAN:
5684         case DEV_DELETE:
5685         case DEV_RESET:
5686                 error = priv_check(td, PRIV_DRIVER);
5687                 if (error == 0)
5688                         error = find_device(req, &dev);
5689                 break;
5690         case DEV_FREEZE:
5691         case DEV_THAW:
5692                 error = priv_check(td, PRIV_DRIVER);
5693                 break;
5694         default:
5695                 error = ENOTTY;
5696                 break;
5697         }
5698         if (error) {
5699                 mtx_unlock(&Giant);
5700                 return (error);
5701         }
5702
5703         /* Perform the requested operation. */
5704         switch (cmd) {
5705         case DEV_ATTACH:
5706                 if (device_is_attached(dev) && (dev->flags & DF_REBID) == 0)
5707                         error = EBUSY;
5708                 else if (!device_is_enabled(dev))
5709                         error = ENXIO;
5710                 else
5711                         error = device_probe_and_attach(dev);
5712                 break;
5713         case DEV_DETACH:
5714                 if (!device_is_attached(dev)) {
5715                         error = ENXIO;
5716                         break;
5717                 }
5718                 if (!(req->dr_flags & DEVF_FORCE_DETACH)) {
5719                         error = device_quiesce(dev);
5720                         if (error)
5721                                 break;
5722                 }
5723                 error = device_detach(dev);
5724                 break;
5725         case DEV_ENABLE:
5726                 if (device_is_enabled(dev)) {
5727                         error = EBUSY;
5728                         break;
5729                 }
5730
5731                 /*
5732                  * If the device has been probed but not attached (e.g.
5733                  * when it has been disabled by a loader hint), just
5734                  * attach the device rather than doing a full probe.
5735                  */
5736                 device_enable(dev);
5737                 if (device_is_alive(dev)) {
5738                         /*
5739                          * If the device was disabled via a hint, clear
5740                          * the hint.
5741                          */
5742                         if (resource_disabled(dev->driver->name, dev->unit))
5743                                 resource_unset_value(dev->driver->name,
5744                                     dev->unit, "disabled");
5745                         error = device_attach(dev);
5746                 } else
5747                         error = device_probe_and_attach(dev);
5748                 break;
5749         case DEV_DISABLE:
5750                 if (!device_is_enabled(dev)) {
5751                         error = ENXIO;
5752                         break;
5753                 }
5754
5755                 if (!(req->dr_flags & DEVF_FORCE_DETACH)) {
5756                         error = device_quiesce(dev);
5757                         if (error)
5758                                 break;
5759                 }
5760
5761                 /*
5762                  * Force DF_FIXEDCLASS on around detach to preserve
5763                  * the existing name.
5764                  */
5765                 old = dev->flags;
5766                 dev->flags |= DF_FIXEDCLASS;
5767                 error = device_detach(dev);
5768                 if (!(old & DF_FIXEDCLASS))
5769                         dev->flags &= ~DF_FIXEDCLASS;
5770                 if (error == 0)
5771                         device_disable(dev);
5772                 break;
5773         case DEV_SUSPEND:
5774                 if (device_is_suspended(dev)) {
5775                         error = EBUSY;
5776                         break;
5777                 }
5778                 if (device_get_parent(dev) == NULL) {
5779                         error = EINVAL;
5780                         break;
5781                 }
5782                 error = BUS_SUSPEND_CHILD(device_get_parent(dev), dev);
5783                 break;
5784         case DEV_RESUME:
5785                 if (!device_is_suspended(dev)) {
5786                         error = EINVAL;
5787                         break;
5788                 }
5789                 if (device_get_parent(dev) == NULL) {
5790                         error = EINVAL;
5791                         break;
5792                 }
5793                 error = BUS_RESUME_CHILD(device_get_parent(dev), dev);
5794                 break;
5795         case DEV_SET_DRIVER: {
5796                 devclass_t dc;
5797                 char driver[128];
5798
5799                 error = copyinstr(req->dr_data, driver, sizeof(driver), NULL);
5800                 if (error)
5801                         break;
5802                 if (driver[0] == '\0') {
5803                         error = EINVAL;
5804                         break;
5805                 }
5806                 if (dev->devclass != NULL &&
5807                     strcmp(driver, dev->devclass->name) == 0)
5808                         /* XXX: Could possibly force DF_FIXEDCLASS on? */
5809                         break;
5810
5811                 /*
5812                  * Scan drivers for this device's bus looking for at
5813                  * least one matching driver.
5814                  */
5815                 if (dev->parent == NULL) {
5816                         error = EINVAL;
5817                         break;
5818                 }
5819                 if (!driver_exists(dev->parent, driver)) {
5820                         error = ENOENT;
5821                         break;
5822                 }
5823                 dc = devclass_create(driver);
5824                 if (dc == NULL) {
5825                         error = ENOMEM;
5826                         break;
5827                 }
5828
5829                 /* Detach device if necessary. */
5830                 if (device_is_attached(dev)) {
5831                         if (req->dr_flags & DEVF_SET_DRIVER_DETACH)
5832                                 error = device_detach(dev);
5833                         else
5834                                 error = EBUSY;
5835                         if (error)
5836                                 break;
5837                 }
5838
5839                 /* Clear any previously-fixed device class and unit. */
5840                 if (dev->flags & DF_FIXEDCLASS)
5841                         devclass_delete_device(dev->devclass, dev);
5842                 dev->flags |= DF_WILDCARD;
5843                 dev->unit = -1;
5844
5845                 /* Force the new device class. */
5846                 error = devclass_add_device(dc, dev);
5847                 if (error)
5848                         break;
5849                 dev->flags |= DF_FIXEDCLASS;
5850                 error = device_probe_and_attach(dev);
5851                 break;
5852         }
5853         case DEV_CLEAR_DRIVER:
5854                 if (!(dev->flags & DF_FIXEDCLASS)) {
5855                         error = 0;
5856                         break;
5857                 }
5858                 if (device_is_attached(dev)) {
5859                         if (req->dr_flags & DEVF_CLEAR_DRIVER_DETACH)
5860                                 error = device_detach(dev);
5861                         else
5862                                 error = EBUSY;
5863                         if (error)
5864                                 break;
5865                 }
5866
5867                 dev->flags &= ~DF_FIXEDCLASS;
5868                 dev->flags |= DF_WILDCARD;
5869                 devclass_delete_device(dev->devclass, dev);
5870                 error = device_probe_and_attach(dev);
5871                 break;
5872         case DEV_RESCAN:
5873                 if (!device_is_attached(dev)) {
5874                         error = ENXIO;
5875                         break;
5876                 }
5877                 error = BUS_RESCAN(dev);
5878                 break;
5879         case DEV_DELETE: {
5880                 device_t parent;
5881
5882                 parent = device_get_parent(dev);
5883                 if (parent == NULL) {
5884                         error = EINVAL;
5885                         break;
5886                 }
5887                 if (!(req->dr_flags & DEVF_FORCE_DELETE)) {
5888                         if (bus_child_present(dev) != 0) {
5889                                 error = EBUSY;
5890                                 break;
5891                         }
5892                 }
5893                 
5894                 error = device_delete_child(parent, dev);
5895                 break;
5896         }
5897         case DEV_FREEZE:
5898                 if (device_frozen)
5899                         error = EBUSY;
5900                 else
5901                         device_frozen = true;
5902                 break;
5903         case DEV_THAW:
5904                 if (!device_frozen)
5905                         error = EBUSY;
5906                 else {
5907                         device_do_deferred_actions();
5908                         device_frozen = false;
5909                 }
5910                 break;
5911         case DEV_RESET:
5912                 if ((req->dr_flags & ~(DEVF_RESET_DETACH)) != 0) {
5913                         error = EINVAL;
5914                         break;
5915                 }
5916                 error = BUS_RESET_CHILD(device_get_parent(dev), dev,
5917                     req->dr_flags);
5918                 break;
5919         }
5920         mtx_unlock(&Giant);
5921         return (error);
5922 }
5923
5924 static struct cdevsw devctl2_cdevsw = {
5925         .d_version =    D_VERSION,
5926         .d_ioctl =      devctl2_ioctl,
5927         .d_name =       "devctl2",
5928 };
5929
5930 static void
5931 devctl2_init(void)
5932 {
5933         make_dev_credf(MAKEDEV_ETERNAL, &devctl2_cdevsw, 0, NULL,
5934             UID_ROOT, GID_WHEEL, 0600, "devctl2");
5935 }
5936
5937 /*
5938  * APIs to manage deprecation and obsolescence.
5939  */
5940 static int obsolete_panic = 0;
5941 SYSCTL_INT(_debug, OID_AUTO, obsolete_panic, CTLFLAG_RWTUN, &obsolete_panic, 0,
5942     "Panic when obsolete features are used (0 = never, 1 = if osbolete, "
5943     "2 = if deprecated)");
5944
5945 static void
5946 gone_panic(int major, int running, const char *msg)
5947 {
5948         switch (obsolete_panic)
5949         {
5950         case 0:
5951                 return;
5952         case 1:
5953                 if (running < major)
5954                         return;
5955                 /* FALLTHROUGH */
5956         default:
5957                 panic("%s", msg);
5958         }
5959 }
5960
5961 void
5962 _gone_in(int major, const char *msg)
5963 {
5964         gone_panic(major, P_OSREL_MAJOR(__FreeBSD_version), msg);
5965         if (P_OSREL_MAJOR(__FreeBSD_version) >= major)
5966                 printf("Obsolete code will be removed soon: %s\n", msg);
5967         else
5968                 printf("Deprecated code (to be removed in FreeBSD %d): %s\n",
5969                     major, msg);
5970 }
5971
5972 void
5973 _gone_in_dev(device_t dev, int major, const char *msg)
5974 {
5975         gone_panic(major, P_OSREL_MAJOR(__FreeBSD_version), msg);
5976         if (P_OSREL_MAJOR(__FreeBSD_version) >= major)
5977                 device_printf(dev,
5978                     "Obsolete code will be removed soon: %s\n", msg);
5979         else
5980                 device_printf(dev,
5981                     "Deprecated code (to be removed in FreeBSD %d): %s\n",
5982                     major, msg);
5983 }
5984
5985 #ifdef DDB
5986 DB_SHOW_COMMAND(device, db_show_device)
5987 {
5988         device_t dev;
5989
5990         if (!have_addr)
5991                 return;
5992
5993         dev = (device_t)addr;
5994
5995         db_printf("name:    %s\n", device_get_nameunit(dev));
5996         db_printf("  driver:  %s\n", DRIVERNAME(dev->driver));
5997         db_printf("  class:   %s\n", DEVCLANAME(dev->devclass));
5998         db_printf("  addr:    %p\n", dev);
5999         db_printf("  parent:  %p\n", dev->parent);
6000         db_printf("  softc:   %p\n", dev->softc);
6001         db_printf("  ivars:   %p\n", dev->ivars);
6002 }
6003
6004 DB_SHOW_ALL_COMMAND(devices, db_show_all_devices)
6005 {
6006         device_t dev;
6007
6008         TAILQ_FOREACH(dev, &bus_data_devices, devlink) {
6009                 db_show_device((db_expr_t)dev, true, count, modif);
6010         }
6011 }
6012 #endif