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