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