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