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