subr_autoconf.c revision 1.187 1 /* $NetBSD: subr_autoconf.c,v 1.187 2009/11/12 19:10:30 dyoung Exp $ */
2
3 /*
4 * Copyright (c) 1996, 2000 Christopher G. Demetriou
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. All advertising materials mentioning features or use of this software
16 * must display the following acknowledgement:
17 * This product includes software developed for the
18 * NetBSD Project. See http://www.NetBSD.org/ for
19 * information about NetBSD.
20 * 4. The name of the author may not be used to endorse or promote products
21 * derived from this software without specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
24 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
25 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
26 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
27 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
28 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
30 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
32 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33 *
34 * --(license Id: LICENSE.proto,v 1.1 2000/06/13 21:40:26 cgd Exp )--
35 */
36
37 /*
38 * Copyright (c) 1992, 1993
39 * The Regents of the University of California. All rights reserved.
40 *
41 * This software was developed by the Computer Systems Engineering group
42 * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
43 * contributed to Berkeley.
44 *
45 * All advertising materials mentioning features or use of this software
46 * must display the following acknowledgement:
47 * This product includes software developed by the University of
48 * California, Lawrence Berkeley Laboratories.
49 *
50 * Redistribution and use in source and binary forms, with or without
51 * modification, are permitted provided that the following conditions
52 * are met:
53 * 1. Redistributions of source code must retain the above copyright
54 * notice, this list of conditions and the following disclaimer.
55 * 2. Redistributions in binary form must reproduce the above copyright
56 * notice, this list of conditions and the following disclaimer in the
57 * documentation and/or other materials provided with the distribution.
58 * 3. Neither the name of the University nor the names of its contributors
59 * may be used to endorse or promote products derived from this software
60 * without specific prior written permission.
61 *
62 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
63 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
64 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
65 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
66 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
67 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
68 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
69 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
70 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
71 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
72 * SUCH DAMAGE.
73 *
74 * from: Header: subr_autoconf.c,v 1.12 93/02/01 19:31:48 torek Exp (LBL)
75 *
76 * @(#)subr_autoconf.c 8.3 (Berkeley) 5/17/94
77 */
78
79 #include <sys/cdefs.h>
80 __KERNEL_RCSID(0, "$NetBSD: subr_autoconf.c,v 1.187 2009/11/12 19:10:30 dyoung Exp $");
81
82 #ifdef _KERNEL_OPT
83 #include "opt_ddb.h"
84 #endif
85
86 #include <sys/param.h>
87 #include <sys/device.h>
88 #include <sys/disklabel.h>
89 #include <sys/conf.h>
90 #include <sys/kauth.h>
91 #include <sys/malloc.h>
92 #include <sys/kmem.h>
93 #include <sys/systm.h>
94 #include <sys/kernel.h>
95 #include <sys/errno.h>
96 #include <sys/proc.h>
97 #include <sys/reboot.h>
98 #include <sys/kthread.h>
99 #include <sys/buf.h>
100 #include <sys/dirent.h>
101 #include <sys/vnode.h>
102 #include <sys/mount.h>
103 #include <sys/namei.h>
104 #include <sys/unistd.h>
105 #include <sys/fcntl.h>
106 #include <sys/lockf.h>
107 #include <sys/callout.h>
108 #include <sys/devmon.h>
109 #include <sys/cpu.h>
110 #include <sys/sysctl.h>
111
112 #include <sys/disk.h>
113
114 #include <machine/limits.h>
115
116 #if defined(__i386__) && defined(_KERNEL_OPT)
117 #include "opt_splash.h"
118 #if defined(SPLASHSCREEN) && defined(SPLASHSCREEN_PROGRESS)
119 #include <dev/splash/splash.h>
120 extern struct splash_progress *splash_progress_state;
121 #endif
122 #endif
123
124 /*
125 * Autoconfiguration subroutines.
126 */
127
128 /*
129 * ioconf.c exports exactly two names: cfdata and cfroots. All system
130 * devices and drivers are found via these tables.
131 */
132 extern struct cfdata cfdata[];
133 extern const short cfroots[];
134
135 /*
136 * List of all cfdriver structures. We use this to detect duplicates
137 * when other cfdrivers are loaded.
138 */
139 struct cfdriverlist allcfdrivers = LIST_HEAD_INITIALIZER(&allcfdrivers);
140 extern struct cfdriver * const cfdriver_list_initial[];
141
142 /*
143 * Initial list of cfattach's.
144 */
145 extern const struct cfattachinit cfattachinit[];
146
147 /*
148 * List of cfdata tables. We always have one such list -- the one
149 * built statically when the kernel was configured.
150 */
151 struct cftablelist allcftables = TAILQ_HEAD_INITIALIZER(allcftables);
152 static struct cftable initcftable;
153
154 #define ROOT ((device_t)NULL)
155
156 struct matchinfo {
157 cfsubmatch_t fn;
158 struct device *parent;
159 const int *locs;
160 void *aux;
161 struct cfdata *match;
162 int pri;
163 };
164
165 static char *number(char *, int);
166 static void mapply(struct matchinfo *, cfdata_t);
167 static device_t config_devalloc(const device_t, const cfdata_t, const int *);
168 static void config_devdelete(device_t);
169 static void config_makeroom(int, struct cfdriver *);
170 static void config_devlink(device_t);
171 static void config_alldevs_unlock(int);
172 static int config_alldevs_lock(void);
173
174 static void config_collect_garbage(void);
175
176 static void pmflock_debug(device_t, const char *, int);
177
178 static device_t deviter_next1(deviter_t *);
179 static void deviter_reinit(deviter_t *);
180
181 struct deferred_config {
182 TAILQ_ENTRY(deferred_config) dc_queue;
183 device_t dc_dev;
184 void (*dc_func)(device_t);
185 };
186
187 TAILQ_HEAD(deferred_config_head, deferred_config);
188
189 struct deferred_config_head deferred_config_queue =
190 TAILQ_HEAD_INITIALIZER(deferred_config_queue);
191 struct deferred_config_head interrupt_config_queue =
192 TAILQ_HEAD_INITIALIZER(interrupt_config_queue);
193 int interrupt_config_threads = 8;
194
195 static void config_process_deferred(struct deferred_config_head *, device_t);
196
197 /* Hooks to finalize configuration once all real devices have been found. */
198 struct finalize_hook {
199 TAILQ_ENTRY(finalize_hook) f_list;
200 int (*f_func)(device_t);
201 device_t f_dev;
202 };
203 static TAILQ_HEAD(, finalize_hook) config_finalize_list =
204 TAILQ_HEAD_INITIALIZER(config_finalize_list);
205 static int config_finalize_done;
206
207 /* list of all devices */
208 static struct devicelist alldevs = TAILQ_HEAD_INITIALIZER(alldevs);
209 static kmutex_t alldevs_mtx;
210 static volatile bool alldevs_garbage = false;
211 static volatile devgen_t alldevs_gen = 1;
212 static volatile int alldevs_nread = 0;
213 static volatile int alldevs_nwrite = 0;
214
215 static int config_pending; /* semaphore for mountroot */
216 static kmutex_t config_misc_lock;
217 static kcondvar_t config_misc_cv;
218
219 static int detachall = 0;
220
221 #define STREQ(s1, s2) \
222 (*(s1) == *(s2) && strcmp((s1), (s2)) == 0)
223
224 static bool config_initialized = false; /* config_init() has been called. */
225
226 static int config_do_twiddle;
227 static callout_t config_twiddle_ch;
228
229 static void sysctl_detach_setup(struct sysctllog **);
230
231 /*
232 * Initialize the autoconfiguration data structures. Normally this
233 * is done by configure(), but some platforms need to do this very
234 * early (to e.g. initialize the console).
235 */
236 void
237 config_init(void)
238 {
239 const struct cfattachinit *cfai;
240 int i, j;
241
242 KASSERT(config_initialized == false);
243
244 mutex_init(&alldevs_mtx, MUTEX_DEFAULT, IPL_HIGH);
245
246 mutex_init(&config_misc_lock, MUTEX_DEFAULT, IPL_NONE);
247 cv_init(&config_misc_cv, "cfgmisc");
248
249 callout_init(&config_twiddle_ch, CALLOUT_MPSAFE);
250
251 /* allcfdrivers is statically initialized. */
252 for (i = 0; cfdriver_list_initial[i] != NULL; i++) {
253 if (config_cfdriver_attach(cfdriver_list_initial[i]) != 0)
254 panic("configure: duplicate `%s' drivers",
255 cfdriver_list_initial[i]->cd_name);
256 }
257
258 for (cfai = &cfattachinit[0]; cfai->cfai_name != NULL; cfai++) {
259 for (j = 0; cfai->cfai_list[j] != NULL; j++) {
260 if (config_cfattach_attach(cfai->cfai_name,
261 cfai->cfai_list[j]) != 0)
262 panic("configure: duplicate `%s' attachment "
263 "of `%s' driver",
264 cfai->cfai_list[j]->ca_name,
265 cfai->cfai_name);
266 }
267 }
268
269 initcftable.ct_cfdata = cfdata;
270 TAILQ_INSERT_TAIL(&allcftables, &initcftable, ct_list);
271
272 config_initialized = true;
273 }
274
275 void
276 config_init_mi(void)
277 {
278
279 if (!config_initialized)
280 config_init();
281
282 sysctl_detach_setup(NULL);
283 }
284
285 void
286 config_deferred(device_t dev)
287 {
288 config_process_deferred(&deferred_config_queue, dev);
289 config_process_deferred(&interrupt_config_queue, dev);
290 }
291
292 static void
293 config_interrupts_thread(void *cookie)
294 {
295 struct deferred_config *dc;
296
297 while ((dc = TAILQ_FIRST(&interrupt_config_queue)) != NULL) {
298 TAILQ_REMOVE(&interrupt_config_queue, dc, dc_queue);
299 (*dc->dc_func)(dc->dc_dev);
300 kmem_free(dc, sizeof(*dc));
301 config_pending_decr();
302 }
303 kthread_exit(0);
304 }
305
306 void
307 config_create_interruptthreads()
308 {
309 int i;
310
311 for (i = 0; i < interrupt_config_threads; i++) {
312 (void)kthread_create(PRI_NONE, 0, NULL,
313 config_interrupts_thread, NULL, NULL, "config");
314 }
315 }
316
317 /*
318 * Announce device attach/detach to userland listeners.
319 */
320 static void
321 devmon_report_device(device_t dev, bool isattach)
322 {
323 #if NDRVCTL > 0
324 prop_dictionary_t ev;
325 const char *parent;
326 const char *what;
327 device_t pdev = device_parent(dev);
328
329 ev = prop_dictionary_create();
330 if (ev == NULL)
331 return;
332
333 what = (isattach ? "device-attach" : "device-detach");
334 parent = (pdev == NULL ? "root" : device_xname(pdev));
335 if (!prop_dictionary_set_cstring(ev, "device", device_xname(dev)) ||
336 !prop_dictionary_set_cstring(ev, "parent", parent)) {
337 prop_object_release(ev);
338 return;
339 }
340
341 devmon_insert(what, ev);
342 #endif
343 }
344
345 /*
346 * Add a cfdriver to the system.
347 */
348 int
349 config_cfdriver_attach(struct cfdriver *cd)
350 {
351 struct cfdriver *lcd;
352
353 /* Make sure this driver isn't already in the system. */
354 LIST_FOREACH(lcd, &allcfdrivers, cd_list) {
355 if (STREQ(lcd->cd_name, cd->cd_name))
356 return EEXIST;
357 }
358
359 LIST_INIT(&cd->cd_attach);
360 LIST_INSERT_HEAD(&allcfdrivers, cd, cd_list);
361
362 return 0;
363 }
364
365 /*
366 * Remove a cfdriver from the system.
367 */
368 int
369 config_cfdriver_detach(struct cfdriver *cd)
370 {
371 int i, rc = 0, s;
372
373 s = config_alldevs_lock();
374 config_collect_garbage();
375 /* Make sure there are no active instances. */
376 for (i = 0; i < cd->cd_ndevs; i++) {
377 if (cd->cd_devs[i] != NULL) {
378 rc = EBUSY;
379 break;
380 }
381 }
382 config_alldevs_unlock(s);
383
384 if (rc != 0)
385 return rc;
386
387 /* ...and no attachments loaded. */
388 if (LIST_EMPTY(&cd->cd_attach) == 0)
389 return EBUSY;
390
391 LIST_REMOVE(cd, cd_list);
392
393 KASSERT(cd->cd_devs == NULL);
394
395 return 0;
396 }
397
398 /*
399 * Look up a cfdriver by name.
400 */
401 struct cfdriver *
402 config_cfdriver_lookup(const char *name)
403 {
404 struct cfdriver *cd;
405
406 LIST_FOREACH(cd, &allcfdrivers, cd_list) {
407 if (STREQ(cd->cd_name, name))
408 return cd;
409 }
410
411 return NULL;
412 }
413
414 /*
415 * Add a cfattach to the specified driver.
416 */
417 int
418 config_cfattach_attach(const char *driver, struct cfattach *ca)
419 {
420 struct cfattach *lca;
421 struct cfdriver *cd;
422
423 cd = config_cfdriver_lookup(driver);
424 if (cd == NULL)
425 return ESRCH;
426
427 /* Make sure this attachment isn't already on this driver. */
428 LIST_FOREACH(lca, &cd->cd_attach, ca_list) {
429 if (STREQ(lca->ca_name, ca->ca_name))
430 return EEXIST;
431 }
432
433 LIST_INSERT_HEAD(&cd->cd_attach, ca, ca_list);
434
435 return 0;
436 }
437
438 /*
439 * Remove a cfattach from the specified driver.
440 */
441 int
442 config_cfattach_detach(const char *driver, struct cfattach *ca)
443 {
444 struct cfdriver *cd;
445 device_t dev;
446 int i, rc = 0, s;
447
448 cd = config_cfdriver_lookup(driver);
449 if (cd == NULL)
450 return ESRCH;
451
452 s = config_alldevs_lock();
453 config_collect_garbage();
454 /* Make sure there are no active instances. */
455 for (i = 0; i < cd->cd_ndevs; i++) {
456 if ((dev = cd->cd_devs[i]) == NULL)
457 continue;
458 if (dev->dv_cfattach == ca) {
459 rc = EBUSY;
460 break;
461 }
462 }
463 config_alldevs_unlock(s);
464
465 if (rc != 0)
466 return rc;
467
468 LIST_REMOVE(ca, ca_list);
469
470 return 0;
471 }
472
473 /*
474 * Look up a cfattach by name.
475 */
476 static struct cfattach *
477 config_cfattach_lookup_cd(struct cfdriver *cd, const char *atname)
478 {
479 struct cfattach *ca;
480
481 LIST_FOREACH(ca, &cd->cd_attach, ca_list) {
482 if (STREQ(ca->ca_name, atname))
483 return ca;
484 }
485
486 return NULL;
487 }
488
489 /*
490 * Look up a cfattach by driver/attachment name.
491 */
492 struct cfattach *
493 config_cfattach_lookup(const char *name, const char *atname)
494 {
495 struct cfdriver *cd;
496
497 cd = config_cfdriver_lookup(name);
498 if (cd == NULL)
499 return NULL;
500
501 return config_cfattach_lookup_cd(cd, atname);
502 }
503
504 /*
505 * Apply the matching function and choose the best. This is used
506 * a few times and we want to keep the code small.
507 */
508 static void
509 mapply(struct matchinfo *m, cfdata_t cf)
510 {
511 int pri;
512
513 if (m->fn != NULL) {
514 pri = (*m->fn)(m->parent, cf, m->locs, m->aux);
515 } else {
516 pri = config_match(m->parent, cf, m->aux);
517 }
518 if (pri > m->pri) {
519 m->match = cf;
520 m->pri = pri;
521 }
522 }
523
524 int
525 config_stdsubmatch(device_t parent, cfdata_t cf, const int *locs, void *aux)
526 {
527 const struct cfiattrdata *ci;
528 const struct cflocdesc *cl;
529 int nlocs, i;
530
531 ci = cfiattr_lookup(cf->cf_pspec->cfp_iattr, parent->dv_cfdriver);
532 KASSERT(ci);
533 nlocs = ci->ci_loclen;
534 KASSERT(!nlocs || locs);
535 for (i = 0; i < nlocs; i++) {
536 cl = &ci->ci_locdesc[i];
537 /* !cld_defaultstr means no default value */
538 if ((!(cl->cld_defaultstr)
539 || (cf->cf_loc[i] != cl->cld_default))
540 && cf->cf_loc[i] != locs[i])
541 return 0;
542 }
543
544 return config_match(parent, cf, aux);
545 }
546
547 /*
548 * Helper function: check whether the driver supports the interface attribute
549 * and return its descriptor structure.
550 */
551 static const struct cfiattrdata *
552 cfdriver_get_iattr(const struct cfdriver *cd, const char *ia)
553 {
554 const struct cfiattrdata * const *cpp;
555
556 if (cd->cd_attrs == NULL)
557 return 0;
558
559 for (cpp = cd->cd_attrs; *cpp; cpp++) {
560 if (STREQ((*cpp)->ci_name, ia)) {
561 /* Match. */
562 return *cpp;
563 }
564 }
565 return 0;
566 }
567
568 /*
569 * Lookup an interface attribute description by name.
570 * If the driver is given, consider only its supported attributes.
571 */
572 const struct cfiattrdata *
573 cfiattr_lookup(const char *name, const struct cfdriver *cd)
574 {
575 const struct cfdriver *d;
576 const struct cfiattrdata *ia;
577
578 if (cd)
579 return cfdriver_get_iattr(cd, name);
580
581 LIST_FOREACH(d, &allcfdrivers, cd_list) {
582 ia = cfdriver_get_iattr(d, name);
583 if (ia)
584 return ia;
585 }
586 return 0;
587 }
588
589 /*
590 * Determine if `parent' is a potential parent for a device spec based
591 * on `cfp'.
592 */
593 static int
594 cfparent_match(const device_t parent, const struct cfparent *cfp)
595 {
596 struct cfdriver *pcd;
597
598 /* We don't match root nodes here. */
599 if (cfp == NULL)
600 return 0;
601
602 pcd = parent->dv_cfdriver;
603 KASSERT(pcd != NULL);
604
605 /*
606 * First, ensure this parent has the correct interface
607 * attribute.
608 */
609 if (!cfdriver_get_iattr(pcd, cfp->cfp_iattr))
610 return 0;
611
612 /*
613 * If no specific parent device instance was specified (i.e.
614 * we're attaching to the attribute only), we're done!
615 */
616 if (cfp->cfp_parent == NULL)
617 return 1;
618
619 /*
620 * Check the parent device's name.
621 */
622 if (STREQ(pcd->cd_name, cfp->cfp_parent) == 0)
623 return 0; /* not the same parent */
624
625 /*
626 * Make sure the unit number matches.
627 */
628 if (cfp->cfp_unit == DVUNIT_ANY || /* wildcard */
629 cfp->cfp_unit == parent->dv_unit)
630 return 1;
631
632 /* Unit numbers don't match. */
633 return 0;
634 }
635
636 /*
637 * Helper for config_cfdata_attach(): check all devices whether it could be
638 * parent any attachment in the config data table passed, and rescan.
639 */
640 static void
641 rescan_with_cfdata(const struct cfdata *cf)
642 {
643 device_t d;
644 const struct cfdata *cf1;
645 deviter_t di;
646
647
648 /*
649 * "alldevs" is likely longer than a modules's cfdata, so make it
650 * the outer loop.
651 */
652 for (d = deviter_first(&di, 0); d != NULL; d = deviter_next(&di)) {
653
654 if (!(d->dv_cfattach->ca_rescan))
655 continue;
656
657 for (cf1 = cf; cf1->cf_name; cf1++) {
658
659 if (!cfparent_match(d, cf1->cf_pspec))
660 continue;
661
662 (*d->dv_cfattach->ca_rescan)(d,
663 cf1->cf_pspec->cfp_iattr, cf1->cf_loc);
664 }
665 }
666 deviter_release(&di);
667 }
668
669 /*
670 * Attach a supplemental config data table and rescan potential
671 * parent devices if required.
672 */
673 int
674 config_cfdata_attach(cfdata_t cf, int scannow)
675 {
676 struct cftable *ct;
677
678 ct = kmem_alloc(sizeof(*ct), KM_SLEEP);
679 ct->ct_cfdata = cf;
680 TAILQ_INSERT_TAIL(&allcftables, ct, ct_list);
681
682 if (scannow)
683 rescan_with_cfdata(cf);
684
685 return 0;
686 }
687
688 /*
689 * Helper for config_cfdata_detach: check whether a device is
690 * found through any attachment in the config data table.
691 */
692 static int
693 dev_in_cfdata(const struct device *d, const struct cfdata *cf)
694 {
695 const struct cfdata *cf1;
696
697 for (cf1 = cf; cf1->cf_name; cf1++)
698 if (d->dv_cfdata == cf1)
699 return 1;
700
701 return 0;
702 }
703
704 /*
705 * Detach a supplemental config data table. Detach all devices found
706 * through that table (and thus keeping references to it) before.
707 */
708 int
709 config_cfdata_detach(cfdata_t cf)
710 {
711 device_t d;
712 int error = 0;
713 struct cftable *ct;
714 deviter_t di;
715
716 for (d = deviter_first(&di, DEVITER_F_RW); d != NULL;
717 d = deviter_next(&di)) {
718 if (!dev_in_cfdata(d, cf))
719 continue;
720 if ((error = config_detach(d, 0)) != 0)
721 break;
722 }
723 deviter_release(&di);
724 if (error) {
725 aprint_error_dev(d, "unable to detach instance\n");
726 return error;
727 }
728
729 TAILQ_FOREACH(ct, &allcftables, ct_list) {
730 if (ct->ct_cfdata == cf) {
731 TAILQ_REMOVE(&allcftables, ct, ct_list);
732 kmem_free(ct, sizeof(*ct));
733 return 0;
734 }
735 }
736
737 /* not found -- shouldn't happen */
738 return EINVAL;
739 }
740
741 /*
742 * Invoke the "match" routine for a cfdata entry on behalf of
743 * an external caller, usually a "submatch" routine.
744 */
745 int
746 config_match(device_t parent, cfdata_t cf, void *aux)
747 {
748 struct cfattach *ca;
749
750 ca = config_cfattach_lookup(cf->cf_name, cf->cf_atname);
751 if (ca == NULL) {
752 /* No attachment for this entry, oh well. */
753 return 0;
754 }
755
756 return (*ca->ca_match)(parent, cf, aux);
757 }
758
759 /*
760 * Iterate over all potential children of some device, calling the given
761 * function (default being the child's match function) for each one.
762 * Nonzero returns are matches; the highest value returned is considered
763 * the best match. Return the `found child' if we got a match, or NULL
764 * otherwise. The `aux' pointer is simply passed on through.
765 *
766 * Note that this function is designed so that it can be used to apply
767 * an arbitrary function to all potential children (its return value
768 * can be ignored).
769 */
770 cfdata_t
771 config_search_loc(cfsubmatch_t fn, device_t parent,
772 const char *ifattr, const int *locs, void *aux)
773 {
774 struct cftable *ct;
775 cfdata_t cf;
776 struct matchinfo m;
777
778 KASSERT(config_initialized);
779 KASSERT(!ifattr || cfdriver_get_iattr(parent->dv_cfdriver, ifattr));
780
781 m.fn = fn;
782 m.parent = parent;
783 m.locs = locs;
784 m.aux = aux;
785 m.match = NULL;
786 m.pri = 0;
787
788 TAILQ_FOREACH(ct, &allcftables, ct_list) {
789 for (cf = ct->ct_cfdata; cf->cf_name; cf++) {
790
791 /* We don't match root nodes here. */
792 if (!cf->cf_pspec)
793 continue;
794
795 /*
796 * Skip cf if no longer eligible, otherwise scan
797 * through parents for one matching `parent', and
798 * try match function.
799 */
800 if (cf->cf_fstate == FSTATE_FOUND)
801 continue;
802 if (cf->cf_fstate == FSTATE_DNOTFOUND ||
803 cf->cf_fstate == FSTATE_DSTAR)
804 continue;
805
806 /*
807 * If an interface attribute was specified,
808 * consider only children which attach to
809 * that attribute.
810 */
811 if (ifattr && !STREQ(ifattr, cf->cf_pspec->cfp_iattr))
812 continue;
813
814 if (cfparent_match(parent, cf->cf_pspec))
815 mapply(&m, cf);
816 }
817 }
818 return m.match;
819 }
820
821 cfdata_t
822 config_search_ia(cfsubmatch_t fn, device_t parent, const char *ifattr,
823 void *aux)
824 {
825
826 return config_search_loc(fn, parent, ifattr, NULL, aux);
827 }
828
829 /*
830 * Find the given root device.
831 * This is much like config_search, but there is no parent.
832 * Don't bother with multiple cfdata tables; the root node
833 * must always be in the initial table.
834 */
835 cfdata_t
836 config_rootsearch(cfsubmatch_t fn, const char *rootname, void *aux)
837 {
838 cfdata_t cf;
839 const short *p;
840 struct matchinfo m;
841
842 m.fn = fn;
843 m.parent = ROOT;
844 m.aux = aux;
845 m.match = NULL;
846 m.pri = 0;
847 m.locs = 0;
848 /*
849 * Look at root entries for matching name. We do not bother
850 * with found-state here since only one root should ever be
851 * searched (and it must be done first).
852 */
853 for (p = cfroots; *p >= 0; p++) {
854 cf = &cfdata[*p];
855 if (strcmp(cf->cf_name, rootname) == 0)
856 mapply(&m, cf);
857 }
858 return m.match;
859 }
860
861 static const char * const msgs[3] = { "", " not configured\n", " unsupported\n" };
862
863 /*
864 * The given `aux' argument describes a device that has been found
865 * on the given parent, but not necessarily configured. Locate the
866 * configuration data for that device (using the submatch function
867 * provided, or using candidates' cd_match configuration driver
868 * functions) and attach it, and return true. If the device was
869 * not configured, call the given `print' function and return 0.
870 */
871 device_t
872 config_found_sm_loc(device_t parent,
873 const char *ifattr, const int *locs, void *aux,
874 cfprint_t print, cfsubmatch_t submatch)
875 {
876 cfdata_t cf;
877
878 #if defined(SPLASHSCREEN) && defined(SPLASHSCREEN_PROGRESS)
879 if (splash_progress_state)
880 splash_progress_update(splash_progress_state);
881 #endif
882
883 if ((cf = config_search_loc(submatch, parent, ifattr, locs, aux)))
884 return(config_attach_loc(parent, cf, locs, aux, print));
885 if (print) {
886 if (config_do_twiddle && cold)
887 twiddle();
888 aprint_normal("%s", msgs[(*print)(aux, device_xname(parent))]);
889 }
890
891 #if defined(SPLASHSCREEN) && defined(SPLASHSCREEN_PROGRESS)
892 if (splash_progress_state)
893 splash_progress_update(splash_progress_state);
894 #endif
895
896 return NULL;
897 }
898
899 device_t
900 config_found_ia(device_t parent, const char *ifattr, void *aux,
901 cfprint_t print)
902 {
903
904 return config_found_sm_loc(parent, ifattr, NULL, aux, print, NULL);
905 }
906
907 device_t
908 config_found(device_t parent, void *aux, cfprint_t print)
909 {
910
911 return config_found_sm_loc(parent, NULL, NULL, aux, print, NULL);
912 }
913
914 /*
915 * As above, but for root devices.
916 */
917 device_t
918 config_rootfound(const char *rootname, void *aux)
919 {
920 cfdata_t cf;
921
922 if ((cf = config_rootsearch((cfsubmatch_t)NULL, rootname, aux)) != NULL)
923 return config_attach(ROOT, cf, aux, (cfprint_t)NULL);
924 aprint_error("root device %s not configured\n", rootname);
925 return NULL;
926 }
927
928 /* just like sprintf(buf, "%d") except that it works from the end */
929 static char *
930 number(char *ep, int n)
931 {
932
933 *--ep = 0;
934 while (n >= 10) {
935 *--ep = (n % 10) + '0';
936 n /= 10;
937 }
938 *--ep = n + '0';
939 return ep;
940 }
941
942 /*
943 * Expand the size of the cd_devs array if necessary.
944 *
945 * The caller must hold alldevs_mtx. config_makeroom() may release and
946 * re-acquire alldevs_mtx, so callers should re-check conditions such
947 * as alldevs_nwrite == 0 and alldevs_nread == 0 when config_makeroom()
948 * returns.
949 */
950 static void
951 config_makeroom(int n, struct cfdriver *cd)
952 {
953 int old, new;
954 device_t *nsp;
955
956 alldevs_nwrite++;
957 mutex_exit(&alldevs_mtx);
958
959 if (n < cd->cd_ndevs)
960 goto out;
961
962 /*
963 * Need to expand the array.
964 */
965 old = cd->cd_ndevs;
966 if (old == 0)
967 new = 4;
968 else
969 new = old * 2;
970 while (new <= n)
971 new *= 2;
972 nsp = kmem_alloc(sizeof(device_t [new]), KM_SLEEP);
973 if (nsp == NULL)
974 panic("config_attach: %sing dev array",
975 old != 0 ? "expand" : "creat");
976 memset(nsp + old, 0, sizeof(device_t [new - old]));
977 if (old != 0) {
978 memcpy(nsp, cd->cd_devs, sizeof(device_t [old]));
979 kmem_free(cd->cd_devs, sizeof(device_t [old]));
980 }
981 cd->cd_ndevs = new;
982 cd->cd_devs = nsp;
983 out:
984 mutex_enter(&alldevs_mtx);
985 alldevs_nwrite--;
986 }
987
988 static void
989 config_devlink(device_t dev)
990 {
991 struct cfdriver *cd = dev->dv_cfdriver;
992 int s;
993
994 /* put this device in the devices array */
995 s = config_alldevs_lock();
996 config_makeroom(dev->dv_unit, cd);
997 if (cd->cd_devs[dev->dv_unit])
998 panic("config_attach: duplicate %s", device_xname(dev));
999 cd->cd_devs[dev->dv_unit] = dev;
1000
1001 /* It is safe to add a device to the tail of the list while
1002 * readers and writers are in the list.
1003 */
1004 dev->dv_add_gen = alldevs_gen;
1005 TAILQ_INSERT_TAIL(&alldevs, dev, dv_list); /* link up */
1006 config_alldevs_unlock(s);
1007 }
1008
1009 /*
1010 * Caller must hold alldevs_mtx. config_devdelete() may release and
1011 * re-acquire alldevs_mtx, so callers should re-check conditions such as
1012 * alldevs_nwrite == 0 && alldevs_nread == 0 after config_devdelete()
1013 * returns.
1014 */
1015 static void
1016 config_devdelete(device_t dev)
1017 {
1018 device_lock_t dvl = device_getlock(dev);
1019 int priv = (dev->dv_flags & DVF_PRIV_ALLOC);
1020 struct cfdriver *cd = dev->dv_cfdriver;
1021 device_t *devs = NULL;
1022 int i, ndevs = 0;
1023
1024 KASSERT(mutex_owned(&alldevs_mtx));
1025
1026 /* Unlink from device list. */
1027 TAILQ_REMOVE(&alldevs, dev, dv_list);
1028
1029 /* Remove from cfdriver's array. */
1030 cd->cd_devs[dev->dv_unit] = NULL;
1031
1032 /*
1033 * If the device now has no units in use, deallocate its softc array.
1034 */
1035 for (i = 0; i < cd->cd_ndevs; i++) {
1036 if (cd->cd_devs[i] != NULL)
1037 break;
1038 }
1039 /* nothing found. unlink, now. deallocate below. */
1040 if (i == cd->cd_ndevs) {
1041 ndevs = cd->cd_ndevs;
1042 devs = cd->cd_devs;
1043 cd->cd_devs = NULL;
1044 cd->cd_ndevs = 0;
1045 }
1046
1047 mutex_exit(&alldevs_mtx);
1048
1049 KASSERT(!mutex_owned(&alldevs_mtx));
1050
1051 if (devs != NULL)
1052 kmem_free(devs, sizeof(device_t [ndevs]));
1053
1054 cv_destroy(&dvl->dvl_cv);
1055 mutex_destroy(&dvl->dvl_mtx);
1056
1057 KASSERT(dev->dv_properties != NULL);
1058 prop_object_release(dev->dv_properties);
1059
1060 if (dev->dv_activity_handlers)
1061 panic("%s with registered handlers", __func__);
1062
1063 if (dev->dv_locators) {
1064 size_t amount = *--dev->dv_locators;
1065 kmem_free(dev->dv_locators, amount);
1066 }
1067
1068 if (dev->dv_cfattach->ca_devsize > 0)
1069 kmem_free(dev->dv_private, dev->dv_cfattach->ca_devsize);
1070 if (priv)
1071 kmem_free(dev, sizeof(*dev));
1072
1073 KASSERT(!mutex_owned(&alldevs_mtx));
1074
1075 mutex_enter(&alldevs_mtx);
1076 }
1077
1078 static device_t
1079 config_devalloc(const device_t parent, const cfdata_t cf, const int *locs)
1080 {
1081 struct cfdriver *cd;
1082 struct cfattach *ca;
1083 size_t lname, lunit;
1084 const char *xunit;
1085 int myunit, s;
1086 char num[10];
1087 device_t dev;
1088 void *dev_private;
1089 const struct cfiattrdata *ia;
1090 device_lock_t dvl;
1091
1092 cd = config_cfdriver_lookup(cf->cf_name);
1093 if (cd == NULL)
1094 return NULL;
1095
1096 ca = config_cfattach_lookup_cd(cd, cf->cf_atname);
1097 if (ca == NULL)
1098 return NULL;
1099
1100 if ((ca->ca_flags & DVF_PRIV_ALLOC) == 0 &&
1101 ca->ca_devsize < sizeof(struct device))
1102 panic("config_devalloc: %s", cf->cf_atname);
1103
1104 #ifndef __BROKEN_CONFIG_UNIT_USAGE
1105 s = config_alldevs_lock();
1106 config_collect_garbage();
1107 if (cf->cf_fstate == FSTATE_STAR) {
1108 for (myunit = cf->cf_unit; myunit < cd->cd_ndevs; myunit++)
1109 if (cd->cd_devs[myunit] == NULL)
1110 break;
1111 /*
1112 * myunit is now the unit of the first NULL device pointer,
1113 * or max(cd->cd_ndevs,cf->cf_unit).
1114 */
1115 } else {
1116 myunit = cf->cf_unit;
1117 if (myunit < cd->cd_ndevs && cd->cd_devs[myunit] != NULL)
1118 myunit = -1;
1119 }
1120 config_alldevs_unlock(s);
1121 if (myunit == -1)
1122 return NULL;
1123 #else
1124 myunit = cf->cf_unit;
1125 #endif /* ! __BROKEN_CONFIG_UNIT_USAGE */
1126
1127 /* compute length of name and decimal expansion of unit number */
1128 lname = strlen(cd->cd_name);
1129 xunit = number(&num[sizeof(num)], myunit);
1130 lunit = &num[sizeof(num)] - xunit;
1131 if (lname + lunit > sizeof(dev->dv_xname))
1132 panic("config_devalloc: device name too long");
1133
1134 /* get memory for all device vars */
1135 KASSERT((ca->ca_flags & DVF_PRIV_ALLOC) || ca->ca_devsize >= sizeof(struct device));
1136 if (ca->ca_devsize > 0) {
1137 dev_private = kmem_zalloc(ca->ca_devsize, KM_SLEEP);
1138 if (dev_private == NULL)
1139 panic("config_devalloc: memory allocation for device softc failed");
1140 } else {
1141 KASSERT(ca->ca_flags & DVF_PRIV_ALLOC);
1142 dev_private = NULL;
1143 }
1144
1145 if ((ca->ca_flags & DVF_PRIV_ALLOC) != 0) {
1146 dev = kmem_zalloc(sizeof(*dev), KM_SLEEP);
1147 } else {
1148 dev = dev_private;
1149 }
1150 if (dev == NULL)
1151 panic("config_devalloc: memory allocation for device_t failed");
1152
1153 dvl = device_getlock(dev);
1154
1155 mutex_init(&dvl->dvl_mtx, MUTEX_DEFAULT, IPL_NONE);
1156 cv_init(&dvl->dvl_cv, "pmfsusp");
1157
1158 dev->dv_class = cd->cd_class;
1159 dev->dv_cfdata = cf;
1160 dev->dv_cfdriver = cd;
1161 dev->dv_cfattach = ca;
1162 dev->dv_unit = myunit;
1163 dev->dv_activity_count = 0;
1164 dev->dv_activity_handlers = NULL;
1165 dev->dv_private = dev_private;
1166 memcpy(dev->dv_xname, cd->cd_name, lname);
1167 memcpy(dev->dv_xname + lname, xunit, lunit);
1168 dev->dv_parent = parent;
1169 if (parent != NULL)
1170 dev->dv_depth = parent->dv_depth + 1;
1171 else
1172 dev->dv_depth = 0;
1173 dev->dv_flags = DVF_ACTIVE; /* always initially active */
1174 dev->dv_flags |= ca->ca_flags; /* inherit flags from class */
1175 if (locs) {
1176 KASSERT(parent); /* no locators at root */
1177 ia = cfiattr_lookup(cf->cf_pspec->cfp_iattr,
1178 parent->dv_cfdriver);
1179 dev->dv_locators =
1180 kmem_alloc(sizeof(int [ia->ci_loclen + 1]), KM_SLEEP);
1181 *dev->dv_locators++ = sizeof(int [ia->ci_loclen + 1]);
1182 memcpy(dev->dv_locators, locs, sizeof(int [ia->ci_loclen]));
1183 }
1184 dev->dv_properties = prop_dictionary_create();
1185 KASSERT(dev->dv_properties != NULL);
1186
1187 prop_dictionary_set_cstring_nocopy(dev->dv_properties,
1188 "device-driver", dev->dv_cfdriver->cd_name);
1189 prop_dictionary_set_uint16(dev->dv_properties,
1190 "device-unit", dev->dv_unit);
1191
1192 return dev;
1193 }
1194
1195 /*
1196 * Attach a found device.
1197 */
1198 device_t
1199 config_attach_loc(device_t parent, cfdata_t cf,
1200 const int *locs, void *aux, cfprint_t print)
1201 {
1202 device_t dev;
1203 struct cftable *ct;
1204 const char *drvname;
1205
1206 #if defined(SPLASHSCREEN) && defined(SPLASHSCREEN_PROGRESS)
1207 if (splash_progress_state)
1208 splash_progress_update(splash_progress_state);
1209 #endif
1210
1211 dev = config_devalloc(parent, cf, locs);
1212 if (!dev)
1213 panic("config_attach: allocation of device softc failed");
1214
1215 /* XXX redundant - see below? */
1216 if (cf->cf_fstate != FSTATE_STAR) {
1217 KASSERT(cf->cf_fstate == FSTATE_NOTFOUND);
1218 cf->cf_fstate = FSTATE_FOUND;
1219 }
1220 #ifdef __BROKEN_CONFIG_UNIT_USAGE
1221 else
1222 cf->cf_unit++;
1223 #endif
1224
1225 config_devlink(dev);
1226
1227 if (config_do_twiddle && cold)
1228 twiddle();
1229 else
1230 aprint_naive("Found ");
1231 /*
1232 * We want the next two printfs for normal, verbose, and quiet,
1233 * but not silent (in which case, we're twiddling, instead).
1234 */
1235 if (parent == ROOT) {
1236 aprint_naive("%s (root)", device_xname(dev));
1237 aprint_normal("%s (root)", device_xname(dev));
1238 } else {
1239 aprint_naive("%s at %s", device_xname(dev), device_xname(parent));
1240 aprint_normal("%s at %s", device_xname(dev), device_xname(parent));
1241 if (print)
1242 (void) (*print)(aux, NULL);
1243 }
1244
1245 /*
1246 * Before attaching, clobber any unfound devices that are
1247 * otherwise identical.
1248 * XXX code above is redundant?
1249 */
1250 drvname = dev->dv_cfdriver->cd_name;
1251 TAILQ_FOREACH(ct, &allcftables, ct_list) {
1252 for (cf = ct->ct_cfdata; cf->cf_name; cf++) {
1253 if (STREQ(cf->cf_name, drvname) &&
1254 cf->cf_unit == dev->dv_unit) {
1255 if (cf->cf_fstate == FSTATE_NOTFOUND)
1256 cf->cf_fstate = FSTATE_FOUND;
1257 #ifdef __BROKEN_CONFIG_UNIT_USAGE
1258 /*
1259 * Bump the unit number on all starred cfdata
1260 * entries for this device.
1261 */
1262 if (cf->cf_fstate == FSTATE_STAR)
1263 cf->cf_unit++;
1264 #endif /* __BROKEN_CONFIG_UNIT_USAGE */
1265 }
1266 }
1267 }
1268 #ifdef __HAVE_DEVICE_REGISTER
1269 device_register(dev, aux);
1270 #endif
1271
1272 /* Let userland know */
1273 devmon_report_device(dev, true);
1274
1275 #if defined(SPLASHSCREEN) && defined(SPLASHSCREEN_PROGRESS)
1276 if (splash_progress_state)
1277 splash_progress_update(splash_progress_state);
1278 #endif
1279 (*dev->dv_cfattach->ca_attach)(parent, dev, aux);
1280 #if defined(SPLASHSCREEN) && defined(SPLASHSCREEN_PROGRESS)
1281 if (splash_progress_state)
1282 splash_progress_update(splash_progress_state);
1283 #endif
1284
1285 if (!device_pmf_is_registered(dev))
1286 aprint_debug_dev(dev, "WARNING: power management not supported\n");
1287
1288 config_process_deferred(&deferred_config_queue, dev);
1289 return dev;
1290 }
1291
1292 device_t
1293 config_attach(device_t parent, cfdata_t cf, void *aux, cfprint_t print)
1294 {
1295
1296 return config_attach_loc(parent, cf, NULL, aux, print);
1297 }
1298
1299 /*
1300 * As above, but for pseudo-devices. Pseudo-devices attached in this
1301 * way are silently inserted into the device tree, and their children
1302 * attached.
1303 *
1304 * Note that because pseudo-devices are attached silently, any information
1305 * the attach routine wishes to print should be prefixed with the device
1306 * name by the attach routine.
1307 */
1308 device_t
1309 config_attach_pseudo(cfdata_t cf)
1310 {
1311 device_t dev;
1312
1313 dev = config_devalloc(ROOT, cf, NULL);
1314 if (!dev)
1315 return NULL;
1316
1317 /* XXX mark busy in cfdata */
1318
1319 if (cf->cf_fstate != FSTATE_STAR) {
1320 KASSERT(cf->cf_fstate == FSTATE_NOTFOUND);
1321 cf->cf_fstate = FSTATE_FOUND;
1322 }
1323
1324 config_devlink(dev);
1325
1326 #if 0 /* XXXJRT not yet */
1327 #ifdef __HAVE_DEVICE_REGISTER
1328 device_register(dev, NULL); /* like a root node */
1329 #endif
1330 #endif
1331 (*dev->dv_cfattach->ca_attach)(ROOT, dev, NULL);
1332 config_process_deferred(&deferred_config_queue, dev);
1333 return dev;
1334 }
1335
1336 /*
1337 * Caller must hold alldevs_mtx. config_collect_garbage() may
1338 * release and re-acquire alldevs_mtx, so callers should re-check
1339 * conditions such as alldevs_nwrite == 0 && alldevs_nread == 0 after
1340 * config_collect_garbage() returns.
1341 */
1342 static void
1343 config_collect_garbage(void)
1344 {
1345 device_t dv;
1346
1347 KASSERT(mutex_owned(&alldevs_mtx));
1348
1349 while (alldevs_nwrite == 0 && alldevs_nread == 0 && alldevs_garbage) {
1350 TAILQ_FOREACH(dv, &alldevs, dv_list) {
1351 if (dv->dv_del_gen != 0)
1352 break;
1353 }
1354 if (dv == NULL) {
1355 alldevs_garbage = false;
1356 break;
1357 }
1358 config_devdelete(dv);
1359 }
1360 KASSERT(mutex_owned(&alldevs_mtx));
1361 }
1362
1363 /*
1364 * Detach a device. Optionally forced (e.g. because of hardware
1365 * removal) and quiet. Returns zero if successful, non-zero
1366 * (an error code) otherwise.
1367 *
1368 * Note that this code wants to be run from a process context, so
1369 * that the detach can sleep to allow processes which have a device
1370 * open to run and unwind their stacks.
1371 */
1372 int
1373 config_detach(device_t dev, int flags)
1374 {
1375 struct cftable *ct;
1376 cfdata_t cf;
1377 const struct cfattach *ca;
1378 struct cfdriver *cd;
1379 #ifdef DIAGNOSTIC
1380 device_t d;
1381 #endif
1382 int rv = 0, s;
1383
1384 #ifdef DIAGNOSTIC
1385 cf = dev->dv_cfdata;
1386 if (cf != NULL && cf->cf_fstate != FSTATE_FOUND &&
1387 cf->cf_fstate != FSTATE_STAR)
1388 panic("config_detach: %s: bad device fstate %d",
1389 device_xname(dev), cf ? cf->cf_fstate : -1);
1390 #endif
1391 cd = dev->dv_cfdriver;
1392 KASSERT(cd != NULL);
1393
1394 ca = dev->dv_cfattach;
1395 KASSERT(ca != NULL);
1396
1397 s = config_alldevs_lock();
1398 if (dev->dv_del_gen != 0) {
1399 config_alldevs_unlock(s);
1400 #ifdef DIAGNOSTIC
1401 printf("%s: %s is already detached\n", __func__,
1402 device_xname(dev));
1403 #endif /* DIAGNOSTIC */
1404 return ENOENT;
1405 }
1406 alldevs_nwrite++;
1407 config_alldevs_unlock(s);
1408
1409 if (!detachall &&
1410 (flags & (DETACH_SHUTDOWN|DETACH_FORCE)) == DETACH_SHUTDOWN &&
1411 (dev->dv_flags & DVF_DETACH_SHUTDOWN) == 0) {
1412 rv = EOPNOTSUPP;
1413 } else if (ca->ca_detach != NULL) {
1414 rv = (*ca->ca_detach)(dev, flags);
1415 } else
1416 rv = EOPNOTSUPP;
1417
1418 /*
1419 * If it was not possible to detach the device, then we either
1420 * panic() (for the forced but failed case), or return an error.
1421 *
1422 * If it was possible to detach the device, ensure that the
1423 * device is deactivated.
1424 */
1425 if (rv == 0)
1426 dev->dv_flags &= ~DVF_ACTIVE;
1427 else if ((flags & DETACH_FORCE) == 0)
1428 goto out;
1429 else {
1430 panic("config_detach: forced detach of %s failed (%d)",
1431 device_xname(dev), rv);
1432 }
1433
1434 /*
1435 * The device has now been successfully detached.
1436 */
1437
1438 /* Let userland know */
1439 devmon_report_device(dev, false);
1440
1441 #ifdef DIAGNOSTIC
1442 /*
1443 * Sanity: If you're successfully detached, you should have no
1444 * children. (Note that because children must be attached
1445 * after parents, we only need to search the latter part of
1446 * the list.)
1447 */
1448 for (d = TAILQ_NEXT(dev, dv_list); d != NULL;
1449 d = TAILQ_NEXT(d, dv_list)) {
1450 if (d->dv_parent == dev && d->dv_del_gen == 0) {
1451 printf("config_detach: detached device %s"
1452 " has children %s\n", device_xname(dev), device_xname(d));
1453 panic("config_detach");
1454 }
1455 }
1456 #endif
1457
1458 /* notify the parent that the child is gone */
1459 if (dev->dv_parent) {
1460 device_t p = dev->dv_parent;
1461 if (p->dv_cfattach->ca_childdetached)
1462 (*p->dv_cfattach->ca_childdetached)(p, dev);
1463 }
1464
1465 /*
1466 * Mark cfdata to show that the unit can be reused, if possible.
1467 */
1468 TAILQ_FOREACH(ct, &allcftables, ct_list) {
1469 for (cf = ct->ct_cfdata; cf->cf_name; cf++) {
1470 if (STREQ(cf->cf_name, cd->cd_name)) {
1471 if (cf->cf_fstate == FSTATE_FOUND &&
1472 cf->cf_unit == dev->dv_unit)
1473 cf->cf_fstate = FSTATE_NOTFOUND;
1474 #ifdef __BROKEN_CONFIG_UNIT_USAGE
1475 /*
1476 * Note that we can only re-use a starred
1477 * unit number if the unit being detached
1478 * had the last assigned unit number.
1479 */
1480 if (cf->cf_fstate == FSTATE_STAR &&
1481 cf->cf_unit == dev->dv_unit + 1)
1482 cf->cf_unit--;
1483 #endif /* __BROKEN_CONFIG_UNIT_USAGE */
1484 }
1485 }
1486 }
1487
1488 if (dev->dv_cfdata != NULL && (flags & DETACH_QUIET) == 0)
1489 aprint_normal_dev(dev, "detached\n");
1490
1491 out:
1492 s = config_alldevs_lock();
1493 KASSERT(alldevs_nwrite != 0);
1494 --alldevs_nwrite;
1495 if (rv != 0)
1496 ;
1497 else if (dev->dv_del_gen != 0)
1498 ;
1499 else {
1500 dev->dv_del_gen = alldevs_gen;
1501 alldevs_garbage = true;
1502 }
1503 config_collect_garbage();
1504 config_alldevs_unlock(s);
1505
1506 return rv;
1507 }
1508
1509 int
1510 config_detach_children(device_t parent, int flags)
1511 {
1512 device_t dv;
1513 deviter_t di;
1514 int error = 0;
1515
1516 for (dv = deviter_first(&di, DEVITER_F_RW); dv != NULL;
1517 dv = deviter_next(&di)) {
1518 if (device_parent(dv) != parent)
1519 continue;
1520 if ((error = config_detach(dv, flags)) != 0)
1521 break;
1522 }
1523 deviter_release(&di);
1524 return error;
1525 }
1526
1527 device_t
1528 shutdown_first(struct shutdown_state *s)
1529 {
1530 if (!s->initialized) {
1531 deviter_init(&s->di, DEVITER_F_SHUTDOWN|DEVITER_F_LEAVES_FIRST);
1532 s->initialized = true;
1533 }
1534 return shutdown_next(s);
1535 }
1536
1537 device_t
1538 shutdown_next(struct shutdown_state *s)
1539 {
1540 device_t dv;
1541
1542 while ((dv = deviter_next(&s->di)) != NULL && !device_is_active(dv))
1543 ;
1544
1545 if (dv == NULL)
1546 s->initialized = false;
1547
1548 return dv;
1549 }
1550
1551 bool
1552 config_detach_all(int how)
1553 {
1554 static struct shutdown_state s;
1555 device_t curdev;
1556 bool progress = false;
1557
1558 if ((how & RB_NOSYNC) != 0)
1559 return false;
1560
1561 for (curdev = shutdown_first(&s); curdev != NULL;
1562 curdev = shutdown_next(&s)) {
1563 aprint_debug(" detaching %s, ", device_xname(curdev));
1564 if (config_detach(curdev, DETACH_SHUTDOWN) == 0) {
1565 progress = true;
1566 aprint_debug("success.");
1567 } else
1568 aprint_debug("failed.");
1569 }
1570 return progress;
1571 }
1572
1573 static bool
1574 device_is_ancestor_of(device_t ancestor, device_t descendant)
1575 {
1576 device_t dv;
1577
1578 for (dv = descendant; dv != NULL; dv = device_parent(dv)) {
1579 if (device_parent(dv) == ancestor)
1580 return true;
1581 }
1582 return false;
1583 }
1584
1585 int
1586 config_deactivate(device_t dev)
1587 {
1588 deviter_t di;
1589 const struct cfattach *ca;
1590 device_t descendant;
1591 int s, rv = 0, oflags;
1592
1593 for (descendant = deviter_first(&di, DEVITER_F_ROOT_FIRST);
1594 descendant != NULL;
1595 descendant = deviter_next(&di)) {
1596 if (dev != descendant &&
1597 !device_is_ancestor_of(dev, descendant))
1598 continue;
1599
1600 if ((descendant->dv_flags & DVF_ACTIVE) == 0)
1601 continue;
1602
1603 ca = descendant->dv_cfattach;
1604 oflags = descendant->dv_flags;
1605
1606 descendant->dv_flags &= ~DVF_ACTIVE;
1607 if (ca->ca_activate == NULL)
1608 continue;
1609 s = splhigh();
1610 rv = (*ca->ca_activate)(descendant, DVACT_DEACTIVATE);
1611 splx(s);
1612 if (rv != 0)
1613 descendant->dv_flags = oflags;
1614 }
1615 deviter_release(&di);
1616 return rv;
1617 }
1618
1619 /*
1620 * Defer the configuration of the specified device until all
1621 * of its parent's devices have been attached.
1622 */
1623 void
1624 config_defer(device_t dev, void (*func)(device_t))
1625 {
1626 struct deferred_config *dc;
1627
1628 if (dev->dv_parent == NULL)
1629 panic("config_defer: can't defer config of a root device");
1630
1631 #ifdef DIAGNOSTIC
1632 for (dc = TAILQ_FIRST(&deferred_config_queue); dc != NULL;
1633 dc = TAILQ_NEXT(dc, dc_queue)) {
1634 if (dc->dc_dev == dev)
1635 panic("config_defer: deferred twice");
1636 }
1637 #endif
1638
1639 dc = kmem_alloc(sizeof(*dc), KM_SLEEP);
1640 if (dc == NULL)
1641 panic("config_defer: unable to allocate callback");
1642
1643 dc->dc_dev = dev;
1644 dc->dc_func = func;
1645 TAILQ_INSERT_TAIL(&deferred_config_queue, dc, dc_queue);
1646 config_pending_incr();
1647 }
1648
1649 /*
1650 * Defer some autoconfiguration for a device until after interrupts
1651 * are enabled.
1652 */
1653 void
1654 config_interrupts(device_t dev, void (*func)(device_t))
1655 {
1656 struct deferred_config *dc;
1657
1658 /*
1659 * If interrupts are enabled, callback now.
1660 */
1661 if (cold == 0) {
1662 (*func)(dev);
1663 return;
1664 }
1665
1666 #ifdef DIAGNOSTIC
1667 for (dc = TAILQ_FIRST(&interrupt_config_queue); dc != NULL;
1668 dc = TAILQ_NEXT(dc, dc_queue)) {
1669 if (dc->dc_dev == dev)
1670 panic("config_interrupts: deferred twice");
1671 }
1672 #endif
1673
1674 dc = kmem_alloc(sizeof(*dc), KM_SLEEP);
1675 if (dc == NULL)
1676 panic("config_interrupts: unable to allocate callback");
1677
1678 dc->dc_dev = dev;
1679 dc->dc_func = func;
1680 TAILQ_INSERT_TAIL(&interrupt_config_queue, dc, dc_queue);
1681 config_pending_incr();
1682 }
1683
1684 /*
1685 * Process a deferred configuration queue.
1686 */
1687 static void
1688 config_process_deferred(struct deferred_config_head *queue,
1689 device_t parent)
1690 {
1691 struct deferred_config *dc, *ndc;
1692
1693 for (dc = TAILQ_FIRST(queue); dc != NULL; dc = ndc) {
1694 ndc = TAILQ_NEXT(dc, dc_queue);
1695 if (parent == NULL || dc->dc_dev->dv_parent == parent) {
1696 TAILQ_REMOVE(queue, dc, dc_queue);
1697 (*dc->dc_func)(dc->dc_dev);
1698 kmem_free(dc, sizeof(*dc));
1699 config_pending_decr();
1700 }
1701 }
1702 }
1703
1704 /*
1705 * Manipulate the config_pending semaphore.
1706 */
1707 void
1708 config_pending_incr(void)
1709 {
1710
1711 mutex_enter(&config_misc_lock);
1712 config_pending++;
1713 mutex_exit(&config_misc_lock);
1714 }
1715
1716 void
1717 config_pending_decr(void)
1718 {
1719
1720 #ifdef DIAGNOSTIC
1721 if (config_pending == 0)
1722 panic("config_pending_decr: config_pending == 0");
1723 #endif
1724 mutex_enter(&config_misc_lock);
1725 config_pending--;
1726 if (config_pending == 0)
1727 cv_broadcast(&config_misc_cv);
1728 mutex_exit(&config_misc_lock);
1729 }
1730
1731 /*
1732 * Register a "finalization" routine. Finalization routines are
1733 * called iteratively once all real devices have been found during
1734 * autoconfiguration, for as long as any one finalizer has done
1735 * any work.
1736 */
1737 int
1738 config_finalize_register(device_t dev, int (*fn)(device_t))
1739 {
1740 struct finalize_hook *f;
1741
1742 /*
1743 * If finalization has already been done, invoke the
1744 * callback function now.
1745 */
1746 if (config_finalize_done) {
1747 while ((*fn)(dev) != 0)
1748 /* loop */ ;
1749 }
1750
1751 /* Ensure this isn't already on the list. */
1752 TAILQ_FOREACH(f, &config_finalize_list, f_list) {
1753 if (f->f_func == fn && f->f_dev == dev)
1754 return EEXIST;
1755 }
1756
1757 f = kmem_alloc(sizeof(*f), KM_SLEEP);
1758 f->f_func = fn;
1759 f->f_dev = dev;
1760 TAILQ_INSERT_TAIL(&config_finalize_list, f, f_list);
1761
1762 return 0;
1763 }
1764
1765 void
1766 config_finalize(void)
1767 {
1768 struct finalize_hook *f;
1769 struct pdevinit *pdev;
1770 extern struct pdevinit pdevinit[];
1771 int errcnt, rv;
1772
1773 /*
1774 * Now that device driver threads have been created, wait for
1775 * them to finish any deferred autoconfiguration.
1776 */
1777 mutex_enter(&config_misc_lock);
1778 while (config_pending != 0)
1779 cv_wait(&config_misc_cv, &config_misc_lock);
1780 mutex_exit(&config_misc_lock);
1781
1782 KERNEL_LOCK(1, NULL);
1783
1784 /* Attach pseudo-devices. */
1785 for (pdev = pdevinit; pdev->pdev_attach != NULL; pdev++)
1786 (*pdev->pdev_attach)(pdev->pdev_count);
1787
1788 /* Run the hooks until none of them does any work. */
1789 do {
1790 rv = 0;
1791 TAILQ_FOREACH(f, &config_finalize_list, f_list)
1792 rv |= (*f->f_func)(f->f_dev);
1793 } while (rv != 0);
1794
1795 config_finalize_done = 1;
1796
1797 /* Now free all the hooks. */
1798 while ((f = TAILQ_FIRST(&config_finalize_list)) != NULL) {
1799 TAILQ_REMOVE(&config_finalize_list, f, f_list);
1800 kmem_free(f, sizeof(*f));
1801 }
1802
1803 KERNEL_UNLOCK_ONE(NULL);
1804
1805 errcnt = aprint_get_error_count();
1806 if ((boothowto & (AB_QUIET|AB_SILENT)) != 0 &&
1807 (boothowto & AB_VERBOSE) == 0) {
1808 mutex_enter(&config_misc_lock);
1809 if (config_do_twiddle) {
1810 config_do_twiddle = 0;
1811 printf_nolog(" done.\n");
1812 }
1813 mutex_exit(&config_misc_lock);
1814 if (errcnt != 0) {
1815 printf("WARNING: %d error%s while detecting hardware; "
1816 "check system log.\n", errcnt,
1817 errcnt == 1 ? "" : "s");
1818 }
1819 }
1820 }
1821
1822 void
1823 config_twiddle_init()
1824 {
1825
1826 if ((boothowto & (AB_SILENT|AB_VERBOSE)) == AB_SILENT) {
1827 config_do_twiddle = 1;
1828 }
1829 callout_setfunc(&config_twiddle_ch, config_twiddle_fn, NULL);
1830 }
1831
1832 void
1833 config_twiddle_fn(void *cookie)
1834 {
1835
1836 mutex_enter(&config_misc_lock);
1837 if (config_do_twiddle) {
1838 twiddle();
1839 callout_schedule(&config_twiddle_ch, mstohz(100));
1840 }
1841 mutex_exit(&config_misc_lock);
1842 }
1843
1844 static int
1845 config_alldevs_lock(void)
1846 {
1847 int s;
1848
1849 s = splhigh();
1850 mutex_enter(&alldevs_mtx);
1851 return s;
1852 }
1853
1854 static void
1855 config_alldevs_unlock(int s)
1856 {
1857 mutex_exit(&alldevs_mtx);
1858 splx(s);
1859 }
1860
1861 /*
1862 * device_lookup:
1863 *
1864 * Look up a device instance for a given driver.
1865 */
1866 device_t
1867 device_lookup(cfdriver_t cd, int unit)
1868 {
1869 device_t dv;
1870 int s;
1871
1872 s = config_alldevs_lock();
1873 config_collect_garbage();
1874 KASSERT(mutex_owned(&alldevs_mtx));
1875 if (unit < 0 || unit >= cd->cd_ndevs)
1876 dv = NULL;
1877 else
1878 dv = cd->cd_devs[unit];
1879 config_alldevs_unlock(s);
1880
1881 KASSERT(!mutex_owned(&alldevs_mtx));
1882 return dv;
1883 }
1884
1885 /*
1886 * device_lookup:
1887 *
1888 * Look up a device instance for a given driver.
1889 */
1890 void *
1891 device_lookup_private(cfdriver_t cd, int unit)
1892 {
1893 device_t dv;
1894 int s;
1895 void *priv;
1896
1897 s = config_alldevs_lock();
1898 config_collect_garbage();
1899 KASSERT(mutex_owned(&alldevs_mtx));
1900 if (unit < 0 || unit >= cd->cd_ndevs)
1901 priv = NULL;
1902 else if ((dv = cd->cd_devs[unit]) == NULL)
1903 priv = NULL;
1904 else
1905 priv = dv->dv_private;
1906 config_alldevs_unlock(s);
1907
1908 KASSERT(!mutex_owned(&alldevs_mtx));
1909 return priv;
1910 }
1911
1912 /*
1913 * Accessor functions for the device_t type.
1914 */
1915 devclass_t
1916 device_class(device_t dev)
1917 {
1918
1919 return dev->dv_class;
1920 }
1921
1922 cfdata_t
1923 device_cfdata(device_t dev)
1924 {
1925
1926 return dev->dv_cfdata;
1927 }
1928
1929 cfdriver_t
1930 device_cfdriver(device_t dev)
1931 {
1932
1933 return dev->dv_cfdriver;
1934 }
1935
1936 cfattach_t
1937 device_cfattach(device_t dev)
1938 {
1939
1940 return dev->dv_cfattach;
1941 }
1942
1943 int
1944 device_unit(device_t dev)
1945 {
1946
1947 return dev->dv_unit;
1948 }
1949
1950 const char *
1951 device_xname(device_t dev)
1952 {
1953
1954 return dev->dv_xname;
1955 }
1956
1957 device_t
1958 device_parent(device_t dev)
1959 {
1960
1961 return dev->dv_parent;
1962 }
1963
1964 bool
1965 device_activation(device_t dev, devact_level_t level)
1966 {
1967 int active_flags;
1968
1969 active_flags = DVF_ACTIVE;
1970 switch (level) {
1971 case DEVACT_LEVEL_FULL:
1972 active_flags |= DVF_CLASS_SUSPENDED;
1973 /*FALLTHROUGH*/
1974 case DEVACT_LEVEL_DRIVER:
1975 active_flags |= DVF_DRIVER_SUSPENDED;
1976 /*FALLTHROUGH*/
1977 case DEVACT_LEVEL_BUS:
1978 active_flags |= DVF_BUS_SUSPENDED;
1979 break;
1980 }
1981
1982 return (dev->dv_flags & active_flags) == DVF_ACTIVE;
1983 }
1984
1985 bool
1986 device_is_active(device_t dev)
1987 {
1988 int active_flags;
1989
1990 active_flags = DVF_ACTIVE;
1991 active_flags |= DVF_CLASS_SUSPENDED;
1992 active_flags |= DVF_DRIVER_SUSPENDED;
1993 active_flags |= DVF_BUS_SUSPENDED;
1994
1995 return (dev->dv_flags & active_flags) == DVF_ACTIVE;
1996 }
1997
1998 bool
1999 device_is_enabled(device_t dev)
2000 {
2001 return (dev->dv_flags & DVF_ACTIVE) == DVF_ACTIVE;
2002 }
2003
2004 bool
2005 device_has_power(device_t dev)
2006 {
2007 int active_flags;
2008
2009 active_flags = DVF_ACTIVE | DVF_BUS_SUSPENDED;
2010
2011 return (dev->dv_flags & active_flags) == DVF_ACTIVE;
2012 }
2013
2014 int
2015 device_locator(device_t dev, u_int locnum)
2016 {
2017
2018 KASSERT(dev->dv_locators != NULL);
2019 return dev->dv_locators[locnum];
2020 }
2021
2022 void *
2023 device_private(device_t dev)
2024 {
2025
2026 /*
2027 * The reason why device_private(NULL) is allowed is to simplify the
2028 * work of a lot of userspace request handlers (i.e., c/bdev
2029 * handlers) which grab cfdriver_t->cd_units[n].
2030 * It avoids having them test for it to be NULL and only then calling
2031 * device_private.
2032 */
2033 return dev == NULL ? NULL : dev->dv_private;
2034 }
2035
2036 prop_dictionary_t
2037 device_properties(device_t dev)
2038 {
2039
2040 return dev->dv_properties;
2041 }
2042
2043 /*
2044 * device_is_a:
2045 *
2046 * Returns true if the device is an instance of the specified
2047 * driver.
2048 */
2049 bool
2050 device_is_a(device_t dev, const char *dname)
2051 {
2052
2053 return strcmp(dev->dv_cfdriver->cd_name, dname) == 0;
2054 }
2055
2056 /*
2057 * device_find_by_xname:
2058 *
2059 * Returns the device of the given name or NULL if it doesn't exist.
2060 */
2061 device_t
2062 device_find_by_xname(const char *name)
2063 {
2064 device_t dv;
2065 deviter_t di;
2066
2067 for (dv = deviter_first(&di, 0); dv != NULL; dv = deviter_next(&di)) {
2068 if (strcmp(device_xname(dv), name) == 0)
2069 break;
2070 }
2071 deviter_release(&di);
2072
2073 return dv;
2074 }
2075
2076 /*
2077 * device_find_by_driver_unit:
2078 *
2079 * Returns the device of the given driver name and unit or
2080 * NULL if it doesn't exist.
2081 */
2082 device_t
2083 device_find_by_driver_unit(const char *name, int unit)
2084 {
2085 struct cfdriver *cd;
2086
2087 if ((cd = config_cfdriver_lookup(name)) == NULL)
2088 return NULL;
2089 return device_lookup(cd, unit);
2090 }
2091
2092 /*
2093 * Power management related functions.
2094 */
2095
2096 bool
2097 device_pmf_is_registered(device_t dev)
2098 {
2099 return (dev->dv_flags & DVF_POWER_HANDLERS) != 0;
2100 }
2101
2102 bool
2103 device_pmf_driver_suspend(device_t dev PMF_FN_ARGS)
2104 {
2105 if ((dev->dv_flags & DVF_DRIVER_SUSPENDED) != 0)
2106 return true;
2107 if ((dev->dv_flags & DVF_CLASS_SUSPENDED) == 0)
2108 return false;
2109 if (pmf_qual_depth(PMF_FN_CALL1) <= DEVACT_LEVEL_DRIVER &&
2110 dev->dv_driver_suspend != NULL &&
2111 !(*dev->dv_driver_suspend)(dev PMF_FN_CALL))
2112 return false;
2113
2114 dev->dv_flags |= DVF_DRIVER_SUSPENDED;
2115 return true;
2116 }
2117
2118 bool
2119 device_pmf_driver_resume(device_t dev PMF_FN_ARGS)
2120 {
2121 if ((dev->dv_flags & DVF_DRIVER_SUSPENDED) == 0)
2122 return true;
2123 if ((dev->dv_flags & DVF_BUS_SUSPENDED) != 0)
2124 return false;
2125 if (pmf_qual_depth(PMF_FN_CALL1) <= DEVACT_LEVEL_DRIVER &&
2126 dev->dv_driver_resume != NULL &&
2127 !(*dev->dv_driver_resume)(dev PMF_FN_CALL))
2128 return false;
2129
2130 dev->dv_flags &= ~DVF_DRIVER_SUSPENDED;
2131 return true;
2132 }
2133
2134 bool
2135 device_pmf_driver_shutdown(device_t dev, int how)
2136 {
2137
2138 if (*dev->dv_driver_shutdown != NULL &&
2139 !(*dev->dv_driver_shutdown)(dev, how))
2140 return false;
2141 return true;
2142 }
2143
2144 bool
2145 device_pmf_driver_register(device_t dev,
2146 bool (*suspend)(device_t PMF_FN_PROTO),
2147 bool (*resume)(device_t PMF_FN_PROTO),
2148 bool (*shutdown)(device_t, int))
2149 {
2150 dev->dv_driver_suspend = suspend;
2151 dev->dv_driver_resume = resume;
2152 dev->dv_driver_shutdown = shutdown;
2153 dev->dv_flags |= DVF_POWER_HANDLERS;
2154 return true;
2155 }
2156
2157 static const char *
2158 curlwp_name(void)
2159 {
2160 if (curlwp->l_name != NULL)
2161 return curlwp->l_name;
2162 else
2163 return curlwp->l_proc->p_comm;
2164 }
2165
2166 void
2167 device_pmf_driver_deregister(device_t dev)
2168 {
2169 device_lock_t dvl = device_getlock(dev);
2170
2171 dev->dv_driver_suspend = NULL;
2172 dev->dv_driver_resume = NULL;
2173
2174 mutex_enter(&dvl->dvl_mtx);
2175 dev->dv_flags &= ~DVF_POWER_HANDLERS;
2176 while (dvl->dvl_nlock > 0 || dvl->dvl_nwait > 0) {
2177 /* Wake a thread that waits for the lock. That
2178 * thread will fail to acquire the lock, and then
2179 * it will wake the next thread that waits for the
2180 * lock, or else it will wake us.
2181 */
2182 cv_signal(&dvl->dvl_cv);
2183 pmflock_debug(dev, __func__, __LINE__);
2184 cv_wait(&dvl->dvl_cv, &dvl->dvl_mtx);
2185 pmflock_debug(dev, __func__, __LINE__);
2186 }
2187 mutex_exit(&dvl->dvl_mtx);
2188 }
2189
2190 bool
2191 device_pmf_driver_child_register(device_t dev)
2192 {
2193 device_t parent = device_parent(dev);
2194
2195 if (parent == NULL || parent->dv_driver_child_register == NULL)
2196 return true;
2197 return (*parent->dv_driver_child_register)(dev);
2198 }
2199
2200 void
2201 device_pmf_driver_set_child_register(device_t dev,
2202 bool (*child_register)(device_t))
2203 {
2204 dev->dv_driver_child_register = child_register;
2205 }
2206
2207 static void
2208 pmflock_debug(device_t dev, const char *func, int line)
2209 {
2210 device_lock_t dvl = device_getlock(dev);
2211
2212 aprint_debug_dev(dev, "%s.%d, %s dvl_nlock %d dvl_nwait %d dv_flags %x\n",
2213 func, line, curlwp_name(), dvl->dvl_nlock, dvl->dvl_nwait,
2214 dev->dv_flags);
2215 }
2216
2217 static bool
2218 device_pmf_lock1(device_t dev)
2219 {
2220 device_lock_t dvl = device_getlock(dev);
2221
2222 while (device_pmf_is_registered(dev) &&
2223 dvl->dvl_nlock > 0 && dvl->dvl_holder != curlwp) {
2224 dvl->dvl_nwait++;
2225 pmflock_debug(dev, __func__, __LINE__);
2226 cv_wait(&dvl->dvl_cv, &dvl->dvl_mtx);
2227 pmflock_debug(dev, __func__, __LINE__);
2228 dvl->dvl_nwait--;
2229 }
2230 if (!device_pmf_is_registered(dev)) {
2231 pmflock_debug(dev, __func__, __LINE__);
2232 /* We could not acquire the lock, but some other thread may
2233 * wait for it, also. Wake that thread.
2234 */
2235 cv_signal(&dvl->dvl_cv);
2236 return false;
2237 }
2238 dvl->dvl_nlock++;
2239 dvl->dvl_holder = curlwp;
2240 pmflock_debug(dev, __func__, __LINE__);
2241 return true;
2242 }
2243
2244 bool
2245 device_pmf_lock(device_t dev)
2246 {
2247 bool rc;
2248 device_lock_t dvl = device_getlock(dev);
2249
2250 mutex_enter(&dvl->dvl_mtx);
2251 rc = device_pmf_lock1(dev);
2252 mutex_exit(&dvl->dvl_mtx);
2253
2254 return rc;
2255 }
2256
2257 void
2258 device_pmf_unlock(device_t dev)
2259 {
2260 device_lock_t dvl = device_getlock(dev);
2261
2262 KASSERT(dvl->dvl_nlock > 0);
2263 mutex_enter(&dvl->dvl_mtx);
2264 if (--dvl->dvl_nlock == 0)
2265 dvl->dvl_holder = NULL;
2266 cv_signal(&dvl->dvl_cv);
2267 pmflock_debug(dev, __func__, __LINE__);
2268 mutex_exit(&dvl->dvl_mtx);
2269 }
2270
2271 device_lock_t
2272 device_getlock(device_t dev)
2273 {
2274 return &dev->dv_lock;
2275 }
2276
2277 void *
2278 device_pmf_bus_private(device_t dev)
2279 {
2280 return dev->dv_bus_private;
2281 }
2282
2283 bool
2284 device_pmf_bus_suspend(device_t dev PMF_FN_ARGS)
2285 {
2286 if ((dev->dv_flags & DVF_BUS_SUSPENDED) != 0)
2287 return true;
2288 if ((dev->dv_flags & DVF_CLASS_SUSPENDED) == 0 ||
2289 (dev->dv_flags & DVF_DRIVER_SUSPENDED) == 0)
2290 return false;
2291 if (pmf_qual_depth(PMF_FN_CALL1) <= DEVACT_LEVEL_BUS &&
2292 dev->dv_bus_suspend != NULL &&
2293 !(*dev->dv_bus_suspend)(dev PMF_FN_CALL))
2294 return false;
2295
2296 dev->dv_flags |= DVF_BUS_SUSPENDED;
2297 return true;
2298 }
2299
2300 bool
2301 device_pmf_bus_resume(device_t dev PMF_FN_ARGS)
2302 {
2303 if ((dev->dv_flags & DVF_BUS_SUSPENDED) == 0)
2304 return true;
2305 if (pmf_qual_depth(PMF_FN_CALL1) <= DEVACT_LEVEL_BUS &&
2306 dev->dv_bus_resume != NULL &&
2307 !(*dev->dv_bus_resume)(dev PMF_FN_CALL))
2308 return false;
2309
2310 dev->dv_flags &= ~DVF_BUS_SUSPENDED;
2311 return true;
2312 }
2313
2314 bool
2315 device_pmf_bus_shutdown(device_t dev, int how)
2316 {
2317
2318 if (*dev->dv_bus_shutdown != NULL &&
2319 !(*dev->dv_bus_shutdown)(dev, how))
2320 return false;
2321 return true;
2322 }
2323
2324 void
2325 device_pmf_bus_register(device_t dev, void *priv,
2326 bool (*suspend)(device_t PMF_FN_PROTO),
2327 bool (*resume)(device_t PMF_FN_PROTO),
2328 bool (*shutdown)(device_t, int), void (*deregister)(device_t))
2329 {
2330 dev->dv_bus_private = priv;
2331 dev->dv_bus_resume = resume;
2332 dev->dv_bus_suspend = suspend;
2333 dev->dv_bus_shutdown = shutdown;
2334 dev->dv_bus_deregister = deregister;
2335 }
2336
2337 void
2338 device_pmf_bus_deregister(device_t dev)
2339 {
2340 if (dev->dv_bus_deregister == NULL)
2341 return;
2342 (*dev->dv_bus_deregister)(dev);
2343 dev->dv_bus_private = NULL;
2344 dev->dv_bus_suspend = NULL;
2345 dev->dv_bus_resume = NULL;
2346 dev->dv_bus_deregister = NULL;
2347 }
2348
2349 void *
2350 device_pmf_class_private(device_t dev)
2351 {
2352 return dev->dv_class_private;
2353 }
2354
2355 bool
2356 device_pmf_class_suspend(device_t dev PMF_FN_ARGS)
2357 {
2358 if ((dev->dv_flags & DVF_CLASS_SUSPENDED) != 0)
2359 return true;
2360 if (pmf_qual_depth(PMF_FN_CALL1) <= DEVACT_LEVEL_CLASS &&
2361 dev->dv_class_suspend != NULL &&
2362 !(*dev->dv_class_suspend)(dev PMF_FN_CALL))
2363 return false;
2364
2365 dev->dv_flags |= DVF_CLASS_SUSPENDED;
2366 return true;
2367 }
2368
2369 bool
2370 device_pmf_class_resume(device_t dev PMF_FN_ARGS)
2371 {
2372 if ((dev->dv_flags & DVF_CLASS_SUSPENDED) == 0)
2373 return true;
2374 if ((dev->dv_flags & DVF_BUS_SUSPENDED) != 0 ||
2375 (dev->dv_flags & DVF_DRIVER_SUSPENDED) != 0)
2376 return false;
2377 if (pmf_qual_depth(PMF_FN_CALL1) <= DEVACT_LEVEL_CLASS &&
2378 dev->dv_class_resume != NULL &&
2379 !(*dev->dv_class_resume)(dev PMF_FN_CALL))
2380 return false;
2381
2382 dev->dv_flags &= ~DVF_CLASS_SUSPENDED;
2383 return true;
2384 }
2385
2386 void
2387 device_pmf_class_register(device_t dev, void *priv,
2388 bool (*suspend)(device_t PMF_FN_PROTO),
2389 bool (*resume)(device_t PMF_FN_PROTO),
2390 void (*deregister)(device_t))
2391 {
2392 dev->dv_class_private = priv;
2393 dev->dv_class_suspend = suspend;
2394 dev->dv_class_resume = resume;
2395 dev->dv_class_deregister = deregister;
2396 }
2397
2398 void
2399 device_pmf_class_deregister(device_t dev)
2400 {
2401 if (dev->dv_class_deregister == NULL)
2402 return;
2403 (*dev->dv_class_deregister)(dev);
2404 dev->dv_class_private = NULL;
2405 dev->dv_class_suspend = NULL;
2406 dev->dv_class_resume = NULL;
2407 dev->dv_class_deregister = NULL;
2408 }
2409
2410 bool
2411 device_active(device_t dev, devactive_t type)
2412 {
2413 size_t i;
2414
2415 if (dev->dv_activity_count == 0)
2416 return false;
2417
2418 for (i = 0; i < dev->dv_activity_count; ++i) {
2419 if (dev->dv_activity_handlers[i] == NULL)
2420 break;
2421 (*dev->dv_activity_handlers[i])(dev, type);
2422 }
2423
2424 return true;
2425 }
2426
2427 bool
2428 device_active_register(device_t dev, void (*handler)(device_t, devactive_t))
2429 {
2430 void (**new_handlers)(device_t, devactive_t);
2431 void (**old_handlers)(device_t, devactive_t);
2432 size_t i, old_size, new_size;
2433 int s;
2434
2435 old_handlers = dev->dv_activity_handlers;
2436 old_size = dev->dv_activity_count;
2437
2438 for (i = 0; i < old_size; ++i) {
2439 KASSERT(old_handlers[i] != handler);
2440 if (old_handlers[i] == NULL) {
2441 old_handlers[i] = handler;
2442 return true;
2443 }
2444 }
2445
2446 new_size = old_size + 4;
2447 new_handlers = kmem_alloc(sizeof(void *[new_size]), KM_SLEEP);
2448
2449 memcpy(new_handlers, old_handlers, sizeof(void *[old_size]));
2450 new_handlers[old_size] = handler;
2451 memset(new_handlers + old_size + 1, 0,
2452 sizeof(int [new_size - (old_size+1)]));
2453
2454 s = splhigh();
2455 dev->dv_activity_count = new_size;
2456 dev->dv_activity_handlers = new_handlers;
2457 splx(s);
2458
2459 if (old_handlers != NULL)
2460 kmem_free(old_handlers, sizeof(void * [old_size]));
2461
2462 return true;
2463 }
2464
2465 void
2466 device_active_deregister(device_t dev, void (*handler)(device_t, devactive_t))
2467 {
2468 void (**old_handlers)(device_t, devactive_t);
2469 size_t i, old_size;
2470 int s;
2471
2472 old_handlers = dev->dv_activity_handlers;
2473 old_size = dev->dv_activity_count;
2474
2475 for (i = 0; i < old_size; ++i) {
2476 if (old_handlers[i] == handler)
2477 break;
2478 if (old_handlers[i] == NULL)
2479 return; /* XXX panic? */
2480 }
2481
2482 if (i == old_size)
2483 return; /* XXX panic? */
2484
2485 for (; i < old_size - 1; ++i) {
2486 if ((old_handlers[i] = old_handlers[i + 1]) != NULL)
2487 continue;
2488
2489 if (i == 0) {
2490 s = splhigh();
2491 dev->dv_activity_count = 0;
2492 dev->dv_activity_handlers = NULL;
2493 splx(s);
2494 kmem_free(old_handlers, sizeof(void *[old_size]));
2495 }
2496 return;
2497 }
2498 old_handlers[i] = NULL;
2499 }
2500
2501 /* Return true iff the device_t `dev' exists at generation `gen'. */
2502 static bool
2503 device_exists_at(device_t dv, devgen_t gen)
2504 {
2505 return (dv->dv_del_gen == 0 || dv->dv_del_gen > gen) &&
2506 dv->dv_add_gen <= gen;
2507 }
2508
2509 static bool
2510 deviter_visits(const deviter_t *di, device_t dv)
2511 {
2512 return device_exists_at(dv, di->di_gen);
2513 }
2514
2515 /*
2516 * Device Iteration
2517 *
2518 * deviter_t: a device iterator. Holds state for a "walk" visiting
2519 * each device_t's in the device tree.
2520 *
2521 * deviter_init(di, flags): initialize the device iterator `di'
2522 * to "walk" the device tree. deviter_next(di) will return
2523 * the first device_t in the device tree, or NULL if there are
2524 * no devices.
2525 *
2526 * `flags' is one or more of DEVITER_F_RW, indicating that the
2527 * caller intends to modify the device tree by calling
2528 * config_detach(9) on devices in the order that the iterator
2529 * returns them; DEVITER_F_ROOT_FIRST, asking for the devices
2530 * nearest the "root" of the device tree to be returned, first;
2531 * DEVITER_F_LEAVES_FIRST, asking for the devices furthest from
2532 * the root of the device tree, first; and DEVITER_F_SHUTDOWN,
2533 * indicating both that deviter_init() should not respect any
2534 * locks on the device tree, and that deviter_next(di) may run
2535 * in more than one LWP before the walk has finished.
2536 *
2537 * Only one DEVITER_F_RW iterator may be in the device tree at
2538 * once.
2539 *
2540 * DEVITER_F_SHUTDOWN implies DEVITER_F_RW.
2541 *
2542 * Results are undefined if the flags DEVITER_F_ROOT_FIRST and
2543 * DEVITER_F_LEAVES_FIRST are used in combination.
2544 *
2545 * deviter_first(di, flags): initialize the device iterator `di'
2546 * and return the first device_t in the device tree, or NULL
2547 * if there are no devices. The statement
2548 *
2549 * dv = deviter_first(di);
2550 *
2551 * is shorthand for
2552 *
2553 * deviter_init(di);
2554 * dv = deviter_next(di);
2555 *
2556 * deviter_next(di): return the next device_t in the device tree,
2557 * or NULL if there are no more devices. deviter_next(di)
2558 * is undefined if `di' was not initialized with deviter_init() or
2559 * deviter_first().
2560 *
2561 * deviter_release(di): stops iteration (subsequent calls to
2562 * deviter_next() will return NULL), releases any locks and
2563 * resources held by the device iterator.
2564 *
2565 * Device iteration does not return device_t's in any particular
2566 * order. An iterator will never return the same device_t twice.
2567 * Device iteration is guaranteed to complete---i.e., if deviter_next(di)
2568 * is called repeatedly on the same `di', it will eventually return
2569 * NULL. It is ok to attach/detach devices during device iteration.
2570 */
2571 void
2572 deviter_init(deviter_t *di, deviter_flags_t flags)
2573 {
2574 device_t dv;
2575 int s;
2576
2577 memset(di, 0, sizeof(*di));
2578
2579 s = config_alldevs_lock();
2580 if ((flags & DEVITER_F_SHUTDOWN) != 0)
2581 flags |= DEVITER_F_RW;
2582
2583 if ((flags & DEVITER_F_RW) != 0)
2584 alldevs_nwrite++;
2585 else
2586 alldevs_nread++;
2587 di->di_gen = alldevs_gen++;
2588 config_alldevs_unlock(s);
2589
2590 di->di_flags = flags;
2591
2592 switch (di->di_flags & (DEVITER_F_LEAVES_FIRST|DEVITER_F_ROOT_FIRST)) {
2593 case DEVITER_F_LEAVES_FIRST:
2594 TAILQ_FOREACH(dv, &alldevs, dv_list) {
2595 if (!deviter_visits(di, dv))
2596 continue;
2597 di->di_curdepth = MAX(di->di_curdepth, dv->dv_depth);
2598 }
2599 break;
2600 case DEVITER_F_ROOT_FIRST:
2601 TAILQ_FOREACH(dv, &alldevs, dv_list) {
2602 if (!deviter_visits(di, dv))
2603 continue;
2604 di->di_maxdepth = MAX(di->di_maxdepth, dv->dv_depth);
2605 }
2606 break;
2607 default:
2608 break;
2609 }
2610
2611 deviter_reinit(di);
2612 }
2613
2614 static void
2615 deviter_reinit(deviter_t *di)
2616 {
2617 if ((di->di_flags & DEVITER_F_RW) != 0)
2618 di->di_prev = TAILQ_LAST(&alldevs, devicelist);
2619 else
2620 di->di_prev = TAILQ_FIRST(&alldevs);
2621 }
2622
2623 device_t
2624 deviter_first(deviter_t *di, deviter_flags_t flags)
2625 {
2626 deviter_init(di, flags);
2627 return deviter_next(di);
2628 }
2629
2630 static device_t
2631 deviter_next2(deviter_t *di)
2632 {
2633 device_t dv;
2634
2635 dv = di->di_prev;
2636
2637 if (dv == NULL)
2638 ;
2639 else if ((di->di_flags & DEVITER_F_RW) != 0)
2640 di->di_prev = TAILQ_PREV(dv, devicelist, dv_list);
2641 else
2642 di->di_prev = TAILQ_NEXT(dv, dv_list);
2643
2644 return dv;
2645 }
2646
2647 static device_t
2648 deviter_next1(deviter_t *di)
2649 {
2650 device_t dv;
2651
2652 do {
2653 dv = deviter_next2(di);
2654 } while (dv != NULL && !deviter_visits(di, dv));
2655
2656 return dv;
2657 }
2658
2659 device_t
2660 deviter_next(deviter_t *di)
2661 {
2662 device_t dv = NULL;
2663
2664 switch (di->di_flags & (DEVITER_F_LEAVES_FIRST|DEVITER_F_ROOT_FIRST)) {
2665 case 0:
2666 return deviter_next1(di);
2667 case DEVITER_F_LEAVES_FIRST:
2668 while (di->di_curdepth >= 0) {
2669 if ((dv = deviter_next1(di)) == NULL) {
2670 di->di_curdepth--;
2671 deviter_reinit(di);
2672 } else if (dv->dv_depth == di->di_curdepth)
2673 break;
2674 }
2675 return dv;
2676 case DEVITER_F_ROOT_FIRST:
2677 while (di->di_curdepth <= di->di_maxdepth) {
2678 if ((dv = deviter_next1(di)) == NULL) {
2679 di->di_curdepth++;
2680 deviter_reinit(di);
2681 } else if (dv->dv_depth == di->di_curdepth)
2682 break;
2683 }
2684 return dv;
2685 default:
2686 return NULL;
2687 }
2688 }
2689
2690 void
2691 deviter_release(deviter_t *di)
2692 {
2693 bool rw = (di->di_flags & DEVITER_F_RW) != 0;
2694 int s;
2695
2696 s = config_alldevs_lock();
2697 if (rw)
2698 --alldevs_nwrite;
2699 else
2700 --alldevs_nread;
2701 /* XXX wake a garbage-collection thread */
2702 config_alldevs_unlock(s);
2703 }
2704
2705 static void
2706 sysctl_detach_setup(struct sysctllog **clog)
2707 {
2708 const struct sysctlnode *node = NULL;
2709
2710 sysctl_createv(clog, 0, NULL, &node,
2711 CTLFLAG_PERMANENT,
2712 CTLTYPE_NODE, "kern", NULL,
2713 NULL, 0, NULL, 0,
2714 CTL_KERN, CTL_EOL);
2715
2716 if (node == NULL)
2717 return;
2718
2719 sysctl_createv(clog, 0, &node, NULL,
2720 CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
2721 CTLTYPE_INT, "detachall",
2722 SYSCTL_DESCR("Detach all devices at shutdown"),
2723 NULL, 0, &detachall, 0,
2724 CTL_CREATE, CTL_EOL);
2725 }
2726