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