subr_autoconf.c revision 1.293 1 /* $NetBSD: subr_autoconf.c,v 1.293 2022/02/05 15:17:40 martin 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.293 2022/02/05 15:17:40 martin Exp $");
81
82 #ifdef _KERNEL_OPT
83 #include "opt_ddb.h"
84 #include "drvctl.h"
85 #endif
86
87 #include <sys/param.h>
88 #include <sys/device.h>
89 #include <sys/disklabel.h>
90 #include <sys/conf.h>
91 #include <sys/kauth.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/mount.h>
102 #include <sys/namei.h>
103 #include <sys/unistd.h>
104 #include <sys/fcntl.h>
105 #include <sys/lockf.h>
106 #include <sys/callout.h>
107 #include <sys/devmon.h>
108 #include <sys/cpu.h>
109 #include <sys/sysctl.h>
110 #include <sys/stdarg.h>
111
112 #include <sys/disk.h>
113
114 #include <sys/rndsource.h>
115
116 #include <machine/limits.h>
117
118 /*
119 * Autoconfiguration subroutines.
120 */
121
122 /*
123 * Device autoconfiguration timings are mixed into the entropy pool.
124 */
125 static krndsource_t rnd_autoconf_source;
126
127 /*
128 * ioconf.c exports exactly two names: cfdata and cfroots. All system
129 * devices and drivers are found via these tables.
130 */
131 extern struct cfdata cfdata[];
132 extern const short cfroots[];
133
134 /*
135 * List of all cfdriver structures. We use this to detect duplicates
136 * when other cfdrivers are loaded.
137 */
138 struct cfdriverlist allcfdrivers = LIST_HEAD_INITIALIZER(&allcfdrivers);
139 extern struct cfdriver * const cfdriver_list_initial[];
140
141 /*
142 * Initial list of cfattach's.
143 */
144 extern const struct cfattachinit cfattachinit[];
145
146 /*
147 * List of cfdata tables. We always have one such list -- the one
148 * built statically when the kernel was configured.
149 */
150 struct cftablelist allcftables = TAILQ_HEAD_INITIALIZER(allcftables);
151 static struct cftable initcftable;
152
153 #define ROOT ((device_t)NULL)
154
155 struct matchinfo {
156 cfsubmatch_t fn;
157 device_t parent;
158 const int *locs;
159 void *aux;
160 struct cfdata *match;
161 int pri;
162 };
163
164 struct alldevs_foray {
165 int af_s;
166 struct devicelist af_garbage;
167 };
168
169 /*
170 * Internal version of the cfargs structure; all versions are
171 * canonicalized to this.
172 */
173 struct cfargs_internal {
174 union {
175 cfsubmatch_t submatch;/* submatch function (direct config) */
176 cfsearch_t search; /* search function (indirect config) */
177 };
178 const char * iattr; /* interface attribute */
179 const int * locators; /* locators array */
180 devhandle_t devhandle; /* devhandle_t (by value) */
181 };
182
183 static char *number(char *, int);
184 static void mapply(struct matchinfo *, cfdata_t);
185 static void config_devdelete(device_t);
186 static void config_devunlink(device_t, struct devicelist *);
187 static void config_makeroom(int, struct cfdriver *);
188 static void config_devlink(device_t);
189 static void config_alldevs_enter(struct alldevs_foray *);
190 static void config_alldevs_exit(struct alldevs_foray *);
191 static void config_add_attrib_dict(device_t);
192 static device_t config_attach_internal(device_t, cfdata_t, void *,
193 cfprint_t, const struct cfargs_internal *);
194
195 static void config_collect_garbage(struct devicelist *);
196 static void config_dump_garbage(struct devicelist *);
197
198 static void pmflock_debug(device_t, const char *, int);
199
200 static device_t deviter_next1(deviter_t *);
201 static void deviter_reinit(deviter_t *);
202
203 struct deferred_config {
204 TAILQ_ENTRY(deferred_config) dc_queue;
205 device_t dc_dev;
206 void (*dc_func)(device_t);
207 };
208
209 TAILQ_HEAD(deferred_config_head, deferred_config);
210
211 static struct deferred_config_head deferred_config_queue =
212 TAILQ_HEAD_INITIALIZER(deferred_config_queue);
213 static struct deferred_config_head interrupt_config_queue =
214 TAILQ_HEAD_INITIALIZER(interrupt_config_queue);
215 static int interrupt_config_threads = 8;
216 static struct deferred_config_head mountroot_config_queue =
217 TAILQ_HEAD_INITIALIZER(mountroot_config_queue);
218 static int mountroot_config_threads = 2;
219 static lwp_t **mountroot_config_lwpids;
220 static size_t mountroot_config_lwpids_size;
221 bool root_is_mounted = false;
222
223 static void config_process_deferred(struct deferred_config_head *, device_t);
224
225 /* Hooks to finalize configuration once all real devices have been found. */
226 struct finalize_hook {
227 TAILQ_ENTRY(finalize_hook) f_list;
228 int (*f_func)(device_t);
229 device_t f_dev;
230 };
231 static TAILQ_HEAD(, finalize_hook) config_finalize_list =
232 TAILQ_HEAD_INITIALIZER(config_finalize_list);
233 static int config_finalize_done;
234
235 /* list of all devices */
236 static struct devicelist alldevs = TAILQ_HEAD_INITIALIZER(alldevs);
237 static kmutex_t alldevs_lock __cacheline_aligned;
238 static devgen_t alldevs_gen = 1;
239 static int alldevs_nread = 0;
240 static int alldevs_nwrite = 0;
241 static bool alldevs_garbage = false;
242
243 static struct devicelist config_pending =
244 TAILQ_HEAD_INITIALIZER(config_pending);
245 static kmutex_t config_misc_lock;
246 static kcondvar_t config_misc_cv;
247
248 static bool detachall = false;
249
250 #define STREQ(s1, s2) \
251 (*(s1) == *(s2) && strcmp((s1), (s2)) == 0)
252
253 static bool config_initialized = false; /* config_init() has been called. */
254
255 static int config_do_twiddle;
256 static callout_t config_twiddle_ch;
257
258 static void sysctl_detach_setup(struct sysctllog **);
259
260 int no_devmon_insert(const char *, prop_dictionary_t);
261 int (*devmon_insert_vec)(const char *, prop_dictionary_t) = no_devmon_insert;
262
263 typedef int (*cfdriver_fn)(struct cfdriver *);
264 static int
265 frob_cfdrivervec(struct cfdriver * const *cfdriverv,
266 cfdriver_fn drv_do, cfdriver_fn drv_undo,
267 const char *style, bool dopanic)
268 {
269 void (*pr)(const char *, ...) __printflike(1, 2) =
270 dopanic ? panic : printf;
271 int i, error = 0, e2 __diagused;
272
273 for (i = 0; cfdriverv[i] != NULL; i++) {
274 if ((error = drv_do(cfdriverv[i])) != 0) {
275 pr("configure: `%s' driver %s failed: %d",
276 cfdriverv[i]->cd_name, style, error);
277 goto bad;
278 }
279 }
280
281 KASSERT(error == 0);
282 return 0;
283
284 bad:
285 printf("\n");
286 for (i--; i >= 0; i--) {
287 e2 = drv_undo(cfdriverv[i]);
288 KASSERT(e2 == 0);
289 }
290
291 return error;
292 }
293
294 typedef int (*cfattach_fn)(const char *, struct cfattach *);
295 static int
296 frob_cfattachvec(const struct cfattachinit *cfattachv,
297 cfattach_fn att_do, cfattach_fn att_undo,
298 const char *style, bool dopanic)
299 {
300 const struct cfattachinit *cfai = NULL;
301 void (*pr)(const char *, ...) __printflike(1, 2) =
302 dopanic ? panic : printf;
303 int j = 0, error = 0, e2 __diagused;
304
305 for (cfai = &cfattachv[0]; cfai->cfai_name != NULL; cfai++) {
306 for (j = 0; cfai->cfai_list[j] != NULL; j++) {
307 if ((error = att_do(cfai->cfai_name,
308 cfai->cfai_list[j])) != 0) {
309 pr("configure: attachment `%s' "
310 "of `%s' driver %s failed: %d",
311 cfai->cfai_list[j]->ca_name,
312 cfai->cfai_name, style, error);
313 goto bad;
314 }
315 }
316 }
317
318 KASSERT(error == 0);
319 return 0;
320
321 bad:
322 /*
323 * Rollback in reverse order. dunno if super-important, but
324 * do that anyway. Although the code looks a little like
325 * someone did a little integration (in the math sense).
326 */
327 printf("\n");
328 if (cfai) {
329 bool last;
330
331 for (last = false; last == false; ) {
332 if (cfai == &cfattachv[0])
333 last = true;
334 for (j--; j >= 0; j--) {
335 e2 = att_undo(cfai->cfai_name,
336 cfai->cfai_list[j]);
337 KASSERT(e2 == 0);
338 }
339 if (!last) {
340 cfai--;
341 for (j = 0; cfai->cfai_list[j] != NULL; j++)
342 ;
343 }
344 }
345 }
346
347 return error;
348 }
349
350 /*
351 * Initialize the autoconfiguration data structures. Normally this
352 * is done by configure(), but some platforms need to do this very
353 * early (to e.g. initialize the console).
354 */
355 void
356 config_init(void)
357 {
358
359 KASSERT(config_initialized == false);
360
361 mutex_init(&alldevs_lock, MUTEX_DEFAULT, IPL_VM);
362
363 mutex_init(&config_misc_lock, MUTEX_DEFAULT, IPL_NONE);
364 cv_init(&config_misc_cv, "cfgmisc");
365
366 callout_init(&config_twiddle_ch, CALLOUT_MPSAFE);
367
368 frob_cfdrivervec(cfdriver_list_initial,
369 config_cfdriver_attach, NULL, "bootstrap", true);
370 frob_cfattachvec(cfattachinit,
371 config_cfattach_attach, NULL, "bootstrap", true);
372
373 initcftable.ct_cfdata = cfdata;
374 TAILQ_INSERT_TAIL(&allcftables, &initcftable, ct_list);
375
376 rnd_attach_source(&rnd_autoconf_source, "autoconf", RND_TYPE_UNKNOWN,
377 RND_FLAG_COLLECT_TIME);
378
379 config_initialized = true;
380 }
381
382 /*
383 * Init or fini drivers and attachments. Either all or none
384 * are processed (via rollback). It would be nice if this were
385 * atomic to outside consumers, but with the current state of
386 * locking ...
387 */
388 int
389 config_init_component(struct cfdriver * const *cfdriverv,
390 const struct cfattachinit *cfattachv, struct cfdata *cfdatav)
391 {
392 int error;
393
394 KERNEL_LOCK(1, NULL);
395
396 if ((error = frob_cfdrivervec(cfdriverv,
397 config_cfdriver_attach, config_cfdriver_detach, "init", false))!= 0)
398 goto out;
399 if ((error = frob_cfattachvec(cfattachv,
400 config_cfattach_attach, config_cfattach_detach,
401 "init", false)) != 0) {
402 frob_cfdrivervec(cfdriverv,
403 config_cfdriver_detach, NULL, "init rollback", true);
404 goto out;
405 }
406 if ((error = config_cfdata_attach(cfdatav, 1)) != 0) {
407 frob_cfattachvec(cfattachv,
408 config_cfattach_detach, NULL, "init rollback", true);
409 frob_cfdrivervec(cfdriverv,
410 config_cfdriver_detach, NULL, "init rollback", true);
411 goto out;
412 }
413
414 /* Success! */
415 error = 0;
416
417 out: KERNEL_UNLOCK_ONE(NULL);
418 return error;
419 }
420
421 int
422 config_fini_component(struct cfdriver * const *cfdriverv,
423 const struct cfattachinit *cfattachv, struct cfdata *cfdatav)
424 {
425 int error;
426
427 KERNEL_LOCK(1, NULL);
428
429 if ((error = config_cfdata_detach(cfdatav)) != 0)
430 goto out;
431 if ((error = frob_cfattachvec(cfattachv,
432 config_cfattach_detach, config_cfattach_attach,
433 "fini", false)) != 0) {
434 if (config_cfdata_attach(cfdatav, 0) != 0)
435 panic("config_cfdata fini rollback failed");
436 goto out;
437 }
438 if ((error = frob_cfdrivervec(cfdriverv,
439 config_cfdriver_detach, config_cfdriver_attach,
440 "fini", false)) != 0) {
441 frob_cfattachvec(cfattachv,
442 config_cfattach_attach, NULL, "fini rollback", true);
443 if (config_cfdata_attach(cfdatav, 0) != 0)
444 panic("config_cfdata fini rollback failed");
445 goto out;
446 }
447
448 /* Success! */
449 error = 0;
450
451 out: KERNEL_UNLOCK_ONE(NULL);
452 return error;
453 }
454
455 void
456 config_init_mi(void)
457 {
458
459 if (!config_initialized)
460 config_init();
461
462 sysctl_detach_setup(NULL);
463 }
464
465 void
466 config_deferred(device_t dev)
467 {
468
469 KASSERT(KERNEL_LOCKED_P());
470
471 config_process_deferred(&deferred_config_queue, dev);
472 config_process_deferred(&interrupt_config_queue, dev);
473 config_process_deferred(&mountroot_config_queue, dev);
474 }
475
476 static void
477 config_interrupts_thread(void *cookie)
478 {
479 struct deferred_config *dc;
480 device_t dev;
481
482 mutex_enter(&config_misc_lock);
483 while ((dc = TAILQ_FIRST(&interrupt_config_queue)) != NULL) {
484 TAILQ_REMOVE(&interrupt_config_queue, dc, dc_queue);
485 mutex_exit(&config_misc_lock);
486
487 dev = dc->dc_dev;
488 (*dc->dc_func)(dev);
489 if (!device_pmf_is_registered(dev))
490 aprint_debug_dev(dev,
491 "WARNING: power management not supported\n");
492 config_pending_decr(dev);
493 kmem_free(dc, sizeof(*dc));
494
495 mutex_enter(&config_misc_lock);
496 }
497 mutex_exit(&config_misc_lock);
498
499 kthread_exit(0);
500 }
501
502 void
503 config_create_interruptthreads(void)
504 {
505 int i;
506
507 for (i = 0; i < interrupt_config_threads; i++) {
508 (void)kthread_create(PRI_NONE, 0/*XXXSMP */, NULL,
509 config_interrupts_thread, NULL, NULL, "configintr");
510 }
511 }
512
513 static void
514 config_mountroot_thread(void *cookie)
515 {
516 struct deferred_config *dc;
517
518 mutex_enter(&config_misc_lock);
519 while ((dc = TAILQ_FIRST(&mountroot_config_queue)) != NULL) {
520 TAILQ_REMOVE(&mountroot_config_queue, dc, dc_queue);
521 mutex_exit(&config_misc_lock);
522
523 (*dc->dc_func)(dc->dc_dev);
524 kmem_free(dc, sizeof(*dc));
525
526 mutex_enter(&config_misc_lock);
527 }
528 mutex_exit(&config_misc_lock);
529
530 kthread_exit(0);
531 }
532
533 void
534 config_create_mountrootthreads(void)
535 {
536 int i;
537
538 if (!root_is_mounted)
539 root_is_mounted = true;
540
541 mountroot_config_lwpids_size = sizeof(mountroot_config_lwpids) *
542 mountroot_config_threads;
543 mountroot_config_lwpids = kmem_alloc(mountroot_config_lwpids_size,
544 KM_NOSLEEP);
545 KASSERT(mountroot_config_lwpids);
546 for (i = 0; i < mountroot_config_threads; i++) {
547 mountroot_config_lwpids[i] = 0;
548 (void)kthread_create(PRI_NONE, KTHREAD_MUSTJOIN/* XXXSMP */,
549 NULL, config_mountroot_thread, NULL,
550 &mountroot_config_lwpids[i],
551 "configroot");
552 }
553 }
554
555 void
556 config_finalize_mountroot(void)
557 {
558 int i, error;
559
560 for (i = 0; i < mountroot_config_threads; i++) {
561 if (mountroot_config_lwpids[i] == 0)
562 continue;
563
564 error = kthread_join(mountroot_config_lwpids[i]);
565 if (error)
566 printf("%s: thread %x joined with error %d\n",
567 __func__, i, error);
568 }
569 kmem_free(mountroot_config_lwpids, mountroot_config_lwpids_size);
570 }
571
572 /*
573 * Announce device attach/detach to userland listeners.
574 */
575
576 int
577 no_devmon_insert(const char *name, prop_dictionary_t p)
578 {
579
580 return ENODEV;
581 }
582
583 static void
584 devmon_report_device(device_t dev, bool isattach)
585 {
586 prop_dictionary_t ev, dict = device_properties(dev);
587 const char *parent;
588 const char *what;
589 const char *where;
590 device_t pdev = device_parent(dev);
591
592 /* If currently no drvctl device, just return */
593 if (devmon_insert_vec == no_devmon_insert)
594 return;
595
596 ev = prop_dictionary_create();
597 if (ev == NULL)
598 return;
599
600 what = (isattach ? "device-attach" : "device-detach");
601 parent = (pdev == NULL ? "root" : device_xname(pdev));
602 if (prop_dictionary_get_string(dict, "location", &where)) {
603 prop_dictionary_set_string(ev, "location", where);
604 aprint_debug("ev: %s %s at %s in [%s]\n",
605 what, device_xname(dev), parent, where);
606 }
607 if (!prop_dictionary_set_string(ev, "device", device_xname(dev)) ||
608 !prop_dictionary_set_string(ev, "parent", parent)) {
609 prop_object_release(ev);
610 return;
611 }
612
613 if ((*devmon_insert_vec)(what, ev) != 0)
614 prop_object_release(ev);
615 }
616
617 /*
618 * Add a cfdriver to the system.
619 */
620 int
621 config_cfdriver_attach(struct cfdriver *cd)
622 {
623 struct cfdriver *lcd;
624
625 /* Make sure this driver isn't already in the system. */
626 LIST_FOREACH(lcd, &allcfdrivers, cd_list) {
627 if (STREQ(lcd->cd_name, cd->cd_name))
628 return EEXIST;
629 }
630
631 LIST_INIT(&cd->cd_attach);
632 LIST_INSERT_HEAD(&allcfdrivers, cd, cd_list);
633
634 return 0;
635 }
636
637 /*
638 * Remove a cfdriver from the system.
639 */
640 int
641 config_cfdriver_detach(struct cfdriver *cd)
642 {
643 struct alldevs_foray af;
644 int i, rc = 0;
645
646 config_alldevs_enter(&af);
647 /* Make sure there are no active instances. */
648 for (i = 0; i < cd->cd_ndevs; i++) {
649 if (cd->cd_devs[i] != NULL) {
650 rc = EBUSY;
651 break;
652 }
653 }
654 config_alldevs_exit(&af);
655
656 if (rc != 0)
657 return rc;
658
659 /* ...and no attachments loaded. */
660 if (LIST_EMPTY(&cd->cd_attach) == 0)
661 return EBUSY;
662
663 LIST_REMOVE(cd, cd_list);
664
665 KASSERT(cd->cd_devs == NULL);
666
667 return 0;
668 }
669
670 /*
671 * Look up a cfdriver by name.
672 */
673 struct cfdriver *
674 config_cfdriver_lookup(const char *name)
675 {
676 struct cfdriver *cd;
677
678 LIST_FOREACH(cd, &allcfdrivers, cd_list) {
679 if (STREQ(cd->cd_name, name))
680 return cd;
681 }
682
683 return NULL;
684 }
685
686 /*
687 * Add a cfattach to the specified driver.
688 */
689 int
690 config_cfattach_attach(const char *driver, struct cfattach *ca)
691 {
692 struct cfattach *lca;
693 struct cfdriver *cd;
694
695 cd = config_cfdriver_lookup(driver);
696 if (cd == NULL)
697 return ESRCH;
698
699 /* Make sure this attachment isn't already on this driver. */
700 LIST_FOREACH(lca, &cd->cd_attach, ca_list) {
701 if (STREQ(lca->ca_name, ca->ca_name))
702 return EEXIST;
703 }
704
705 LIST_INSERT_HEAD(&cd->cd_attach, ca, ca_list);
706
707 return 0;
708 }
709
710 /*
711 * Remove a cfattach from the specified driver.
712 */
713 int
714 config_cfattach_detach(const char *driver, struct cfattach *ca)
715 {
716 struct alldevs_foray af;
717 struct cfdriver *cd;
718 device_t dev;
719 int i, rc = 0;
720
721 cd = config_cfdriver_lookup(driver);
722 if (cd == NULL)
723 return ESRCH;
724
725 config_alldevs_enter(&af);
726 /* Make sure there are no active instances. */
727 for (i = 0; i < cd->cd_ndevs; i++) {
728 if ((dev = cd->cd_devs[i]) == NULL)
729 continue;
730 if (dev->dv_cfattach == ca) {
731 rc = EBUSY;
732 break;
733 }
734 }
735 config_alldevs_exit(&af);
736
737 if (rc != 0)
738 return rc;
739
740 LIST_REMOVE(ca, ca_list);
741
742 return 0;
743 }
744
745 /*
746 * Look up a cfattach by name.
747 */
748 static struct cfattach *
749 config_cfattach_lookup_cd(struct cfdriver *cd, const char *atname)
750 {
751 struct cfattach *ca;
752
753 LIST_FOREACH(ca, &cd->cd_attach, ca_list) {
754 if (STREQ(ca->ca_name, atname))
755 return ca;
756 }
757
758 return NULL;
759 }
760
761 /*
762 * Look up a cfattach by driver/attachment name.
763 */
764 struct cfattach *
765 config_cfattach_lookup(const char *name, const char *atname)
766 {
767 struct cfdriver *cd;
768
769 cd = config_cfdriver_lookup(name);
770 if (cd == NULL)
771 return NULL;
772
773 return config_cfattach_lookup_cd(cd, atname);
774 }
775
776 /*
777 * Apply the matching function and choose the best. This is used
778 * a few times and we want to keep the code small.
779 */
780 static void
781 mapply(struct matchinfo *m, cfdata_t cf)
782 {
783 int pri;
784
785 if (m->fn != NULL) {
786 pri = (*m->fn)(m->parent, cf, m->locs, m->aux);
787 } else {
788 pri = config_match(m->parent, cf, m->aux);
789 }
790 if (pri > m->pri) {
791 m->match = cf;
792 m->pri = pri;
793 }
794 }
795
796 int
797 config_stdsubmatch(device_t parent, cfdata_t cf, const int *locs, void *aux)
798 {
799 const struct cfiattrdata *ci;
800 const struct cflocdesc *cl;
801 int nlocs, i;
802
803 ci = cfiattr_lookup(cfdata_ifattr(cf), parent->dv_cfdriver);
804 KASSERT(ci);
805 nlocs = ci->ci_loclen;
806 KASSERT(!nlocs || locs);
807 for (i = 0; i < nlocs; i++) {
808 cl = &ci->ci_locdesc[i];
809 if (cl->cld_defaultstr != NULL &&
810 cf->cf_loc[i] == cl->cld_default)
811 continue;
812 if (cf->cf_loc[i] == locs[i])
813 continue;
814 return 0;
815 }
816
817 return config_match(parent, cf, aux);
818 }
819
820 /*
821 * Helper function: check whether the driver supports the interface attribute
822 * and return its descriptor structure.
823 */
824 static const struct cfiattrdata *
825 cfdriver_get_iattr(const struct cfdriver *cd, const char *ia)
826 {
827 const struct cfiattrdata * const *cpp;
828
829 if (cd->cd_attrs == NULL)
830 return 0;
831
832 for (cpp = cd->cd_attrs; *cpp; cpp++) {
833 if (STREQ((*cpp)->ci_name, ia)) {
834 /* Match. */
835 return *cpp;
836 }
837 }
838 return 0;
839 }
840
841 #ifdef DIAGNOSTIC
842 static int
843 cfdriver_iattr_count(const struct cfdriver *cd)
844 {
845 const struct cfiattrdata * const *cpp;
846 int i;
847
848 if (cd->cd_attrs == NULL)
849 return 0;
850
851 for (i = 0, cpp = cd->cd_attrs; *cpp; cpp++) {
852 i++;
853 }
854 return i;
855 }
856 #endif
857
858 /*
859 * Lookup an interface attribute description by name.
860 * If the driver is given, consider only its supported attributes.
861 */
862 const struct cfiattrdata *
863 cfiattr_lookup(const char *name, const struct cfdriver *cd)
864 {
865 const struct cfdriver *d;
866 const struct cfiattrdata *ia;
867
868 if (cd)
869 return cfdriver_get_iattr(cd, name);
870
871 LIST_FOREACH(d, &allcfdrivers, cd_list) {
872 ia = cfdriver_get_iattr(d, name);
873 if (ia)
874 return ia;
875 }
876 return 0;
877 }
878
879 /*
880 * Determine if `parent' is a potential parent for a device spec based
881 * on `cfp'.
882 */
883 static int
884 cfparent_match(const device_t parent, const struct cfparent *cfp)
885 {
886 struct cfdriver *pcd;
887
888 /* We don't match root nodes here. */
889 if (cfp == NULL)
890 return 0;
891
892 pcd = parent->dv_cfdriver;
893 KASSERT(pcd != NULL);
894
895 /*
896 * First, ensure this parent has the correct interface
897 * attribute.
898 */
899 if (!cfdriver_get_iattr(pcd, cfp->cfp_iattr))
900 return 0;
901
902 /*
903 * If no specific parent device instance was specified (i.e.
904 * we're attaching to the attribute only), we're done!
905 */
906 if (cfp->cfp_parent == NULL)
907 return 1;
908
909 /*
910 * Check the parent device's name.
911 */
912 if (STREQ(pcd->cd_name, cfp->cfp_parent) == 0)
913 return 0; /* not the same parent */
914
915 /*
916 * Make sure the unit number matches.
917 */
918 if (cfp->cfp_unit == DVUNIT_ANY || /* wildcard */
919 cfp->cfp_unit == parent->dv_unit)
920 return 1;
921
922 /* Unit numbers don't match. */
923 return 0;
924 }
925
926 /*
927 * Helper for config_cfdata_attach(): check all devices whether it could be
928 * parent any attachment in the config data table passed, and rescan.
929 */
930 static void
931 rescan_with_cfdata(const struct cfdata *cf)
932 {
933 device_t d;
934 const struct cfdata *cf1;
935 deviter_t di;
936
937 KASSERT(KERNEL_LOCKED_P());
938
939 /*
940 * "alldevs" is likely longer than a modules's cfdata, so make it
941 * the outer loop.
942 */
943 for (d = deviter_first(&di, 0); d != NULL; d = deviter_next(&di)) {
944
945 if (!(d->dv_cfattach->ca_rescan))
946 continue;
947
948 for (cf1 = cf; cf1->cf_name; cf1++) {
949
950 if (!cfparent_match(d, cf1->cf_pspec))
951 continue;
952
953 (*d->dv_cfattach->ca_rescan)(d,
954 cfdata_ifattr(cf1), cf1->cf_loc);
955
956 config_deferred(d);
957 }
958 }
959 deviter_release(&di);
960 }
961
962 /*
963 * Attach a supplemental config data table and rescan potential
964 * parent devices if required.
965 */
966 int
967 config_cfdata_attach(cfdata_t cf, int scannow)
968 {
969 struct cftable *ct;
970
971 KERNEL_LOCK(1, NULL);
972
973 ct = kmem_alloc(sizeof(*ct), KM_SLEEP);
974 ct->ct_cfdata = cf;
975 TAILQ_INSERT_TAIL(&allcftables, ct, ct_list);
976
977 if (scannow)
978 rescan_with_cfdata(cf);
979
980 KERNEL_UNLOCK_ONE(NULL);
981
982 return 0;
983 }
984
985 /*
986 * Helper for config_cfdata_detach: check whether a device is
987 * found through any attachment in the config data table.
988 */
989 static int
990 dev_in_cfdata(device_t d, cfdata_t cf)
991 {
992 const struct cfdata *cf1;
993
994 for (cf1 = cf; cf1->cf_name; cf1++)
995 if (d->dv_cfdata == cf1)
996 return 1;
997
998 return 0;
999 }
1000
1001 /*
1002 * Detach a supplemental config data table. Detach all devices found
1003 * through that table (and thus keeping references to it) before.
1004 */
1005 int
1006 config_cfdata_detach(cfdata_t cf)
1007 {
1008 device_t d;
1009 int error = 0;
1010 struct cftable *ct;
1011 deviter_t di;
1012
1013 KERNEL_LOCK(1, NULL);
1014
1015 for (d = deviter_first(&di, DEVITER_F_RW); d != NULL;
1016 d = deviter_next(&di)) {
1017 if (!dev_in_cfdata(d, cf))
1018 continue;
1019 if ((error = config_detach(d, 0)) != 0)
1020 break;
1021 }
1022 deviter_release(&di);
1023 if (error) {
1024 aprint_error_dev(d, "unable to detach instance\n");
1025 goto out;
1026 }
1027
1028 TAILQ_FOREACH(ct, &allcftables, ct_list) {
1029 if (ct->ct_cfdata == cf) {
1030 TAILQ_REMOVE(&allcftables, ct, ct_list);
1031 kmem_free(ct, sizeof(*ct));
1032 error = 0;
1033 goto out;
1034 }
1035 }
1036
1037 /* not found -- shouldn't happen */
1038 error = EINVAL;
1039
1040 out: KERNEL_UNLOCK_ONE(NULL);
1041 return error;
1042 }
1043
1044 /*
1045 * Invoke the "match" routine for a cfdata entry on behalf of
1046 * an external caller, usually a direct config "submatch" routine.
1047 */
1048 int
1049 config_match(device_t parent, cfdata_t cf, void *aux)
1050 {
1051 struct cfattach *ca;
1052
1053 KASSERT(KERNEL_LOCKED_P());
1054
1055 ca = config_cfattach_lookup(cf->cf_name, cf->cf_atname);
1056 if (ca == NULL) {
1057 /* No attachment for this entry, oh well. */
1058 return 0;
1059 }
1060
1061 return (*ca->ca_match)(parent, cf, aux);
1062 }
1063
1064 /*
1065 * Invoke the "probe" routine for a cfdata entry on behalf of
1066 * an external caller, usually an indirect config "search" routine.
1067 */
1068 int
1069 config_probe(device_t parent, cfdata_t cf, void *aux)
1070 {
1071 /*
1072 * This is currently a synonym for config_match(), but this
1073 * is an implementation detail; "match" and "probe" routines
1074 * have different behaviors.
1075 *
1076 * XXX config_probe() should return a bool, because there is
1077 * XXX no match score for probe -- it's either there or it's
1078 * XXX not, but some ports abuse the return value as a way
1079 * XXX to attach "critical" devices before "non-critical"
1080 * XXX devices.
1081 */
1082 return config_match(parent, cf, aux);
1083 }
1084
1085 static struct cfargs_internal *
1086 cfargs_canonicalize(const struct cfargs * const cfargs,
1087 struct cfargs_internal * const store)
1088 {
1089 struct cfargs_internal *args = store;
1090
1091 memset(args, 0, sizeof(*args));
1092
1093 /* If none specified, are all-NULL pointers are good. */
1094 if (cfargs == NULL) {
1095 return args;
1096 }
1097
1098 /*
1099 * Only one arguments version is recognized at this time.
1100 */
1101 if (cfargs->cfargs_version != CFARGS_VERSION) {
1102 panic("cfargs_canonicalize: unknown version %lu\n",
1103 (unsigned long)cfargs->cfargs_version);
1104 }
1105
1106 /*
1107 * submatch and search are mutually-exclusive.
1108 */
1109 if (cfargs->submatch != NULL && cfargs->search != NULL) {
1110 panic("cfargs_canonicalize: submatch and search are "
1111 "mutually-exclusive");
1112 }
1113 if (cfargs->submatch != NULL) {
1114 args->submatch = cfargs->submatch;
1115 } else if (cfargs->search != NULL) {
1116 args->search = cfargs->search;
1117 }
1118
1119 args->iattr = cfargs->iattr;
1120 args->locators = cfargs->locators;
1121 args->devhandle = cfargs->devhandle;
1122
1123 return args;
1124 }
1125
1126 /*
1127 * Iterate over all potential children of some device, calling the given
1128 * function (default being the child's match function) for each one.
1129 * Nonzero returns are matches; the highest value returned is considered
1130 * the best match. Return the `found child' if we got a match, or NULL
1131 * otherwise. The `aux' pointer is simply passed on through.
1132 *
1133 * Note that this function is designed so that it can be used to apply
1134 * an arbitrary function to all potential children (its return value
1135 * can be ignored).
1136 */
1137 static cfdata_t
1138 config_search_internal(device_t parent, void *aux,
1139 const struct cfargs_internal * const args)
1140 {
1141 struct cftable *ct;
1142 cfdata_t cf;
1143 struct matchinfo m;
1144
1145 KASSERT(config_initialized);
1146 KASSERT(!args->iattr ||
1147 cfdriver_get_iattr(parent->dv_cfdriver, args->iattr));
1148 KASSERT(args->iattr ||
1149 cfdriver_iattr_count(parent->dv_cfdriver) < 2);
1150
1151 m.fn = args->submatch; /* N.B. union */
1152 m.parent = parent;
1153 m.locs = args->locators;
1154 m.aux = aux;
1155 m.match = NULL;
1156 m.pri = 0;
1157
1158 TAILQ_FOREACH(ct, &allcftables, ct_list) {
1159 for (cf = ct->ct_cfdata; cf->cf_name; cf++) {
1160
1161 /* We don't match root nodes here. */
1162 if (!cf->cf_pspec)
1163 continue;
1164
1165 /*
1166 * Skip cf if no longer eligible, otherwise scan
1167 * through parents for one matching `parent', and
1168 * try match function.
1169 */
1170 if (cf->cf_fstate == FSTATE_FOUND)
1171 continue;
1172 if (cf->cf_fstate == FSTATE_DNOTFOUND ||
1173 cf->cf_fstate == FSTATE_DSTAR)
1174 continue;
1175
1176 /*
1177 * If an interface attribute was specified,
1178 * consider only children which attach to
1179 * that attribute.
1180 */
1181 if (args->iattr != NULL &&
1182 !STREQ(args->iattr, cfdata_ifattr(cf)))
1183 continue;
1184
1185 if (cfparent_match(parent, cf->cf_pspec))
1186 mapply(&m, cf);
1187 }
1188 }
1189 return m.match;
1190 }
1191
1192 cfdata_t
1193 config_search(device_t parent, void *aux, const struct cfargs *cfargs)
1194 {
1195 cfdata_t cf;
1196 struct cfargs_internal store;
1197
1198 cf = config_search_internal(parent, aux,
1199 cfargs_canonicalize(cfargs, &store));
1200
1201 return cf;
1202 }
1203
1204 /*
1205 * Find the given root device.
1206 * This is much like config_search, but there is no parent.
1207 * Don't bother with multiple cfdata tables; the root node
1208 * must always be in the initial table.
1209 */
1210 cfdata_t
1211 config_rootsearch(cfsubmatch_t fn, const char *rootname, void *aux)
1212 {
1213 cfdata_t cf;
1214 const short *p;
1215 struct matchinfo m;
1216
1217 m.fn = fn;
1218 m.parent = ROOT;
1219 m.aux = aux;
1220 m.match = NULL;
1221 m.pri = 0;
1222 m.locs = 0;
1223 /*
1224 * Look at root entries for matching name. We do not bother
1225 * with found-state here since only one root should ever be
1226 * searched (and it must be done first).
1227 */
1228 for (p = cfroots; *p >= 0; p++) {
1229 cf = &cfdata[*p];
1230 if (strcmp(cf->cf_name, rootname) == 0)
1231 mapply(&m, cf);
1232 }
1233 return m.match;
1234 }
1235
1236 static const char * const msgs[] = {
1237 [QUIET] = "",
1238 [UNCONF] = " not configured\n",
1239 [UNSUPP] = " unsupported\n",
1240 };
1241
1242 /*
1243 * The given `aux' argument describes a device that has been found
1244 * on the given parent, but not necessarily configured. Locate the
1245 * configuration data for that device (using the submatch function
1246 * provided, or using candidates' cd_match configuration driver
1247 * functions) and attach it, and return its device_t. If the device was
1248 * not configured, call the given `print' function and return NULL.
1249 */
1250 device_t
1251 config_found(device_t parent, void *aux, cfprint_t print,
1252 const struct cfargs * const cfargs)
1253 {
1254 cfdata_t cf;
1255 struct cfargs_internal store;
1256 const struct cfargs_internal * const args =
1257 cfargs_canonicalize(cfargs, &store);
1258
1259 cf = config_search_internal(parent, aux, args);
1260 if (cf != NULL) {
1261 return config_attach_internal(parent, cf, aux, print, args);
1262 }
1263
1264 if (print) {
1265 if (config_do_twiddle && cold)
1266 twiddle();
1267
1268 const int pret = (*print)(aux, device_xname(parent));
1269 KASSERT(pret >= 0);
1270 KASSERT(pret < __arraycount(msgs));
1271 KASSERT(msgs[pret] != NULL);
1272 aprint_normal("%s", msgs[pret]);
1273 }
1274
1275 /*
1276 * This has the effect of mixing in a single timestamp to the
1277 * entropy pool. Experiments indicate the estimator will almost
1278 * always attribute one bit of entropy to this sample; analysis
1279 * of device attach/detach timestamps on FreeBSD indicates 4
1280 * bits of entropy/sample so this seems appropriately conservative.
1281 */
1282 rnd_add_uint32(&rnd_autoconf_source, 0);
1283 return NULL;
1284 }
1285
1286 /*
1287 * As above, but for root devices.
1288 */
1289 device_t
1290 config_rootfound(const char *rootname, void *aux)
1291 {
1292 cfdata_t cf;
1293 device_t dev = NULL;
1294
1295 KERNEL_LOCK(1, NULL);
1296 if ((cf = config_rootsearch(NULL, rootname, aux)) != NULL)
1297 dev = config_attach(ROOT, cf, aux, NULL, CFARGS_NONE);
1298 else
1299 aprint_error("root device %s not configured\n", rootname);
1300 KERNEL_UNLOCK_ONE(NULL);
1301 return dev;
1302 }
1303
1304 /* just like sprintf(buf, "%d") except that it works from the end */
1305 static char *
1306 number(char *ep, int n)
1307 {
1308
1309 *--ep = 0;
1310 while (n >= 10) {
1311 *--ep = (n % 10) + '0';
1312 n /= 10;
1313 }
1314 *--ep = n + '0';
1315 return ep;
1316 }
1317
1318 /*
1319 * Expand the size of the cd_devs array if necessary.
1320 *
1321 * The caller must hold alldevs_lock. config_makeroom() may release and
1322 * re-acquire alldevs_lock, so callers should re-check conditions such
1323 * as alldevs_nwrite == 0 and alldevs_nread == 0 when config_makeroom()
1324 * returns.
1325 */
1326 static void
1327 config_makeroom(int n, struct cfdriver *cd)
1328 {
1329 int ondevs, nndevs;
1330 device_t *osp, *nsp;
1331
1332 KASSERT(mutex_owned(&alldevs_lock));
1333 alldevs_nwrite++;
1334
1335 for (nndevs = MAX(4, cd->cd_ndevs); nndevs <= n; nndevs += nndevs)
1336 ;
1337
1338 while (n >= cd->cd_ndevs) {
1339 /*
1340 * Need to expand the array.
1341 */
1342 ondevs = cd->cd_ndevs;
1343 osp = cd->cd_devs;
1344
1345 /*
1346 * Release alldevs_lock around allocation, which may
1347 * sleep.
1348 */
1349 mutex_exit(&alldevs_lock);
1350 nsp = kmem_alloc(sizeof(device_t) * nndevs, KM_SLEEP);
1351 mutex_enter(&alldevs_lock);
1352
1353 /*
1354 * If another thread moved the array while we did
1355 * not hold alldevs_lock, try again.
1356 */
1357 if (cd->cd_devs != osp) {
1358 mutex_exit(&alldevs_lock);
1359 kmem_free(nsp, sizeof(device_t) * nndevs);
1360 mutex_enter(&alldevs_lock);
1361 continue;
1362 }
1363
1364 memset(nsp + ondevs, 0, sizeof(device_t) * (nndevs - ondevs));
1365 if (ondevs != 0)
1366 memcpy(nsp, cd->cd_devs, sizeof(device_t) * ondevs);
1367
1368 cd->cd_ndevs = nndevs;
1369 cd->cd_devs = nsp;
1370 if (ondevs != 0) {
1371 mutex_exit(&alldevs_lock);
1372 kmem_free(osp, sizeof(device_t) * ondevs);
1373 mutex_enter(&alldevs_lock);
1374 }
1375 }
1376 KASSERT(mutex_owned(&alldevs_lock));
1377 alldevs_nwrite--;
1378 }
1379
1380 /*
1381 * Put dev into the devices list.
1382 */
1383 static void
1384 config_devlink(device_t dev)
1385 {
1386
1387 mutex_enter(&alldevs_lock);
1388
1389 KASSERT(device_cfdriver(dev)->cd_devs[dev->dv_unit] == dev);
1390
1391 dev->dv_add_gen = alldevs_gen;
1392 /* It is safe to add a device to the tail of the list while
1393 * readers and writers are in the list.
1394 */
1395 TAILQ_INSERT_TAIL(&alldevs, dev, dv_list);
1396 mutex_exit(&alldevs_lock);
1397 }
1398
1399 static void
1400 config_devfree(device_t dev)
1401 {
1402
1403 KASSERT(dev->dv_flags & DVF_PRIV_ALLOC);
1404 KASSERTMSG(dev->dv_pending == 0, "%d", dev->dv_pending);
1405
1406 if (dev->dv_cfattach->ca_devsize > 0)
1407 kmem_free(dev->dv_private, dev->dv_cfattach->ca_devsize);
1408 kmem_free(dev, sizeof(*dev));
1409 }
1410
1411 /*
1412 * Caller must hold alldevs_lock.
1413 */
1414 static void
1415 config_devunlink(device_t dev, struct devicelist *garbage)
1416 {
1417 struct device_garbage *dg = &dev->dv_garbage;
1418 cfdriver_t cd = device_cfdriver(dev);
1419 int i;
1420
1421 KASSERT(mutex_owned(&alldevs_lock));
1422 KASSERTMSG(dev->dv_pending == 0, "%d", dev->dv_pending);
1423
1424 /* Unlink from device list. Link to garbage list. */
1425 TAILQ_REMOVE(&alldevs, dev, dv_list);
1426 TAILQ_INSERT_TAIL(garbage, dev, dv_list);
1427
1428 /* Remove from cfdriver's array. */
1429 cd->cd_devs[dev->dv_unit] = NULL;
1430
1431 /*
1432 * If the device now has no units in use, unlink its softc array.
1433 */
1434 for (i = 0; i < cd->cd_ndevs; i++) {
1435 if (cd->cd_devs[i] != NULL)
1436 break;
1437 }
1438 /* Nothing found. Unlink, now. Deallocate, later. */
1439 if (i == cd->cd_ndevs) {
1440 dg->dg_ndevs = cd->cd_ndevs;
1441 dg->dg_devs = cd->cd_devs;
1442 cd->cd_devs = NULL;
1443 cd->cd_ndevs = 0;
1444 }
1445 }
1446
1447 static void
1448 config_devdelete(device_t dev)
1449 {
1450 struct device_garbage *dg = &dev->dv_garbage;
1451 device_lock_t dvl = device_getlock(dev);
1452
1453 KASSERTMSG(dev->dv_pending == 0, "%d", dev->dv_pending);
1454
1455 if (dg->dg_devs != NULL)
1456 kmem_free(dg->dg_devs, sizeof(device_t) * dg->dg_ndevs);
1457
1458 cv_destroy(&dvl->dvl_cv);
1459 mutex_destroy(&dvl->dvl_mtx);
1460
1461 KASSERT(dev->dv_properties != NULL);
1462 prop_object_release(dev->dv_properties);
1463
1464 if (dev->dv_activity_handlers)
1465 panic("%s with registered handlers", __func__);
1466
1467 if (dev->dv_locators) {
1468 size_t amount = *--dev->dv_locators;
1469 kmem_free(dev->dv_locators, amount);
1470 }
1471
1472 config_devfree(dev);
1473 }
1474
1475 static int
1476 config_unit_nextfree(cfdriver_t cd, cfdata_t cf)
1477 {
1478 int unit;
1479
1480 if (cf->cf_fstate == FSTATE_STAR) {
1481 for (unit = cf->cf_unit; unit < cd->cd_ndevs; unit++)
1482 if (cd->cd_devs[unit] == NULL)
1483 break;
1484 /*
1485 * unit is now the unit of the first NULL device pointer,
1486 * or max(cd->cd_ndevs,cf->cf_unit).
1487 */
1488 } else {
1489 unit = cf->cf_unit;
1490 if (unit < cd->cd_ndevs && cd->cd_devs[unit] != NULL)
1491 unit = -1;
1492 }
1493 return unit;
1494 }
1495
1496 static int
1497 config_unit_alloc(device_t dev, cfdriver_t cd, cfdata_t cf)
1498 {
1499 struct alldevs_foray af;
1500 int unit;
1501
1502 config_alldevs_enter(&af);
1503 for (;;) {
1504 unit = config_unit_nextfree(cd, cf);
1505 if (unit == -1)
1506 break;
1507 if (unit < cd->cd_ndevs) {
1508 cd->cd_devs[unit] = dev;
1509 dev->dv_unit = unit;
1510 break;
1511 }
1512 config_makeroom(unit, cd);
1513 }
1514 config_alldevs_exit(&af);
1515
1516 return unit;
1517 }
1518
1519 static device_t
1520 config_devalloc(const device_t parent, const cfdata_t cf,
1521 const struct cfargs_internal * const args)
1522 {
1523 cfdriver_t cd;
1524 cfattach_t ca;
1525 size_t lname, lunit;
1526 const char *xunit;
1527 int myunit;
1528 char num[10];
1529 device_t dev;
1530 void *dev_private;
1531 const struct cfiattrdata *ia;
1532 device_lock_t dvl;
1533
1534 cd = config_cfdriver_lookup(cf->cf_name);
1535 if (cd == NULL)
1536 return NULL;
1537
1538 ca = config_cfattach_lookup_cd(cd, cf->cf_atname);
1539 if (ca == NULL)
1540 return NULL;
1541
1542 /* get memory for all device vars */
1543 KASSERT(ca->ca_flags & DVF_PRIV_ALLOC);
1544 if (ca->ca_devsize > 0) {
1545 dev_private = kmem_zalloc(ca->ca_devsize, KM_SLEEP);
1546 } else {
1547 dev_private = NULL;
1548 }
1549 dev = kmem_zalloc(sizeof(*dev), KM_SLEEP);
1550
1551 dev->dv_handle = args->devhandle;
1552
1553 dev->dv_class = cd->cd_class;
1554 dev->dv_cfdata = cf;
1555 dev->dv_cfdriver = cd;
1556 dev->dv_cfattach = ca;
1557 dev->dv_activity_count = 0;
1558 dev->dv_activity_handlers = NULL;
1559 dev->dv_private = dev_private;
1560 dev->dv_flags = ca->ca_flags; /* inherit flags from class */
1561
1562 myunit = config_unit_alloc(dev, cd, cf);
1563 if (myunit == -1) {
1564 config_devfree(dev);
1565 return NULL;
1566 }
1567
1568 /* compute length of name and decimal expansion of unit number */
1569 lname = strlen(cd->cd_name);
1570 xunit = number(&num[sizeof(num)], myunit);
1571 lunit = &num[sizeof(num)] - xunit;
1572 if (lname + lunit > sizeof(dev->dv_xname))
1573 panic("config_devalloc: device name too long");
1574
1575 dvl = device_getlock(dev);
1576
1577 mutex_init(&dvl->dvl_mtx, MUTEX_DEFAULT, IPL_NONE);
1578 cv_init(&dvl->dvl_cv, "pmfsusp");
1579
1580 memcpy(dev->dv_xname, cd->cd_name, lname);
1581 memcpy(dev->dv_xname + lname, xunit, lunit);
1582 dev->dv_parent = parent;
1583 if (parent != NULL)
1584 dev->dv_depth = parent->dv_depth + 1;
1585 else
1586 dev->dv_depth = 0;
1587 dev->dv_flags |= DVF_ACTIVE; /* always initially active */
1588 if (args->locators) {
1589 KASSERT(parent); /* no locators at root */
1590 ia = cfiattr_lookup(cfdata_ifattr(cf), parent->dv_cfdriver);
1591 dev->dv_locators =
1592 kmem_alloc(sizeof(int) * (ia->ci_loclen + 1), KM_SLEEP);
1593 *dev->dv_locators++ = sizeof(int) * (ia->ci_loclen + 1);
1594 memcpy(dev->dv_locators, args->locators,
1595 sizeof(int) * ia->ci_loclen);
1596 }
1597 dev->dv_properties = prop_dictionary_create();
1598 KASSERT(dev->dv_properties != NULL);
1599
1600 prop_dictionary_set_string_nocopy(dev->dv_properties,
1601 "device-driver", dev->dv_cfdriver->cd_name);
1602 prop_dictionary_set_uint16(dev->dv_properties,
1603 "device-unit", dev->dv_unit);
1604 if (parent != NULL) {
1605 prop_dictionary_set_string(dev->dv_properties,
1606 "device-parent", device_xname(parent));
1607 }
1608
1609 if (dev->dv_cfdriver->cd_attrs != NULL)
1610 config_add_attrib_dict(dev);
1611
1612 return dev;
1613 }
1614
1615 /*
1616 * Create an array of device attach attributes and add it
1617 * to the device's dv_properties dictionary.
1618 *
1619 * <key>interface-attributes</key>
1620 * <array>
1621 * <dict>
1622 * <key>attribute-name</key>
1623 * <string>foo</string>
1624 * <key>locators</key>
1625 * <array>
1626 * <dict>
1627 * <key>loc-name</key>
1628 * <string>foo-loc1</string>
1629 * </dict>
1630 * <dict>
1631 * <key>loc-name</key>
1632 * <string>foo-loc2</string>
1633 * <key>default</key>
1634 * <string>foo-loc2-default</string>
1635 * </dict>
1636 * ...
1637 * </array>
1638 * </dict>
1639 * ...
1640 * </array>
1641 */
1642
1643 static void
1644 config_add_attrib_dict(device_t dev)
1645 {
1646 int i, j;
1647 const struct cfiattrdata *ci;
1648 prop_dictionary_t attr_dict, loc_dict;
1649 prop_array_t attr_array, loc_array;
1650
1651 if ((attr_array = prop_array_create()) == NULL)
1652 return;
1653
1654 for (i = 0; ; i++) {
1655 if ((ci = dev->dv_cfdriver->cd_attrs[i]) == NULL)
1656 break;
1657 if ((attr_dict = prop_dictionary_create()) == NULL)
1658 break;
1659 prop_dictionary_set_string_nocopy(attr_dict, "attribute-name",
1660 ci->ci_name);
1661
1662 /* Create an array of the locator names and defaults */
1663
1664 if (ci->ci_loclen != 0 &&
1665 (loc_array = prop_array_create()) != NULL) {
1666 for (j = 0; j < ci->ci_loclen; j++) {
1667 loc_dict = prop_dictionary_create();
1668 if (loc_dict == NULL)
1669 continue;
1670 prop_dictionary_set_string_nocopy(loc_dict,
1671 "loc-name", ci->ci_locdesc[j].cld_name);
1672 if (ci->ci_locdesc[j].cld_defaultstr != NULL)
1673 prop_dictionary_set_string_nocopy(
1674 loc_dict, "default",
1675 ci->ci_locdesc[j].cld_defaultstr);
1676 prop_array_set(loc_array, j, loc_dict);
1677 prop_object_release(loc_dict);
1678 }
1679 prop_dictionary_set_and_rel(attr_dict, "locators",
1680 loc_array);
1681 }
1682 prop_array_add(attr_array, attr_dict);
1683 prop_object_release(attr_dict);
1684 }
1685 if (i == 0)
1686 prop_object_release(attr_array);
1687 else
1688 prop_dictionary_set_and_rel(dev->dv_properties,
1689 "interface-attributes", attr_array);
1690
1691 return;
1692 }
1693
1694 /*
1695 * Attach a found device.
1696 */
1697 static device_t
1698 config_attach_internal(device_t parent, cfdata_t cf, void *aux, cfprint_t print,
1699 const struct cfargs_internal * const args)
1700 {
1701 device_t dev;
1702 struct cftable *ct;
1703 const char *drvname;
1704 bool deferred;
1705
1706 KASSERT(KERNEL_LOCKED_P());
1707
1708 dev = config_devalloc(parent, cf, args);
1709 if (!dev)
1710 panic("config_attach: allocation of device softc failed");
1711
1712 /* XXX redundant - see below? */
1713 if (cf->cf_fstate != FSTATE_STAR) {
1714 KASSERT(cf->cf_fstate == FSTATE_NOTFOUND);
1715 cf->cf_fstate = FSTATE_FOUND;
1716 }
1717
1718 config_devlink(dev);
1719
1720 if (config_do_twiddle && cold)
1721 twiddle();
1722 else
1723 aprint_naive("Found ");
1724 /*
1725 * We want the next two printfs for normal, verbose, and quiet,
1726 * but not silent (in which case, we're twiddling, instead).
1727 */
1728 if (parent == ROOT) {
1729 aprint_naive("%s (root)", device_xname(dev));
1730 aprint_normal("%s (root)", device_xname(dev));
1731 } else {
1732 aprint_naive("%s at %s", device_xname(dev),
1733 device_xname(parent));
1734 aprint_normal("%s at %s", device_xname(dev),
1735 device_xname(parent));
1736 if (print)
1737 (void) (*print)(aux, NULL);
1738 }
1739
1740 /*
1741 * Before attaching, clobber any unfound devices that are
1742 * otherwise identical.
1743 * XXX code above is redundant?
1744 */
1745 drvname = dev->dv_cfdriver->cd_name;
1746 TAILQ_FOREACH(ct, &allcftables, ct_list) {
1747 for (cf = ct->ct_cfdata; cf->cf_name; cf++) {
1748 if (STREQ(cf->cf_name, drvname) &&
1749 cf->cf_unit == dev->dv_unit) {
1750 if (cf->cf_fstate == FSTATE_NOTFOUND)
1751 cf->cf_fstate = FSTATE_FOUND;
1752 }
1753 }
1754 }
1755 device_register(dev, aux);
1756
1757 /* Let userland know */
1758 devmon_report_device(dev, true);
1759
1760 config_pending_incr(dev);
1761 (*dev->dv_cfattach->ca_attach)(parent, dev, aux);
1762 config_pending_decr(dev);
1763
1764 mutex_enter(&config_misc_lock);
1765 deferred = (dev->dv_pending != 0);
1766 mutex_exit(&config_misc_lock);
1767
1768 if (!deferred && !device_pmf_is_registered(dev))
1769 aprint_debug_dev(dev,
1770 "WARNING: power management not supported\n");
1771
1772 config_process_deferred(&deferred_config_queue, dev);
1773
1774 device_register_post_config(dev, aux);
1775 return dev;
1776 }
1777
1778 device_t
1779 config_attach(device_t parent, cfdata_t cf, void *aux, cfprint_t print,
1780 const struct cfargs *cfargs)
1781 {
1782 struct cfargs_internal store;
1783
1784 KASSERT(KERNEL_LOCKED_P());
1785
1786 return config_attach_internal(parent, cf, aux, print,
1787 cfargs_canonicalize(cfargs, &store));
1788 }
1789
1790 /*
1791 * As above, but for pseudo-devices. Pseudo-devices attached in this
1792 * way are silently inserted into the device tree, and their children
1793 * attached.
1794 *
1795 * Note that because pseudo-devices are attached silently, any information
1796 * the attach routine wishes to print should be prefixed with the device
1797 * name by the attach routine.
1798 */
1799 device_t
1800 config_attach_pseudo(cfdata_t cf)
1801 {
1802 device_t dev;
1803
1804 KERNEL_LOCK(1, NULL);
1805
1806 struct cfargs_internal args = { };
1807 dev = config_devalloc(ROOT, cf, &args);
1808 if (!dev)
1809 goto out;
1810
1811 /* XXX mark busy in cfdata */
1812
1813 if (cf->cf_fstate != FSTATE_STAR) {
1814 KASSERT(cf->cf_fstate == FSTATE_NOTFOUND);
1815 cf->cf_fstate = FSTATE_FOUND;
1816 }
1817
1818 config_devlink(dev);
1819
1820 #if 0 /* XXXJRT not yet */
1821 device_register(dev, NULL); /* like a root node */
1822 #endif
1823
1824 /* Let userland know */
1825 devmon_report_device(dev, true);
1826
1827 config_pending_incr(dev);
1828 (*dev->dv_cfattach->ca_attach)(ROOT, dev, NULL);
1829 config_pending_decr(dev);
1830
1831 config_process_deferred(&deferred_config_queue, dev);
1832
1833 out: KERNEL_UNLOCK_ONE(NULL);
1834 return dev;
1835 }
1836
1837 /*
1838 * Caller must hold alldevs_lock.
1839 */
1840 static void
1841 config_collect_garbage(struct devicelist *garbage)
1842 {
1843 device_t dv;
1844
1845 KASSERT(!cpu_intr_p());
1846 KASSERT(!cpu_softintr_p());
1847 KASSERT(mutex_owned(&alldevs_lock));
1848
1849 while (alldevs_nwrite == 0 && alldevs_nread == 0 && alldevs_garbage) {
1850 TAILQ_FOREACH(dv, &alldevs, dv_list) {
1851 if (dv->dv_del_gen != 0)
1852 break;
1853 }
1854 if (dv == NULL) {
1855 alldevs_garbage = false;
1856 break;
1857 }
1858 config_devunlink(dv, garbage);
1859 }
1860 KASSERT(mutex_owned(&alldevs_lock));
1861 }
1862
1863 static void
1864 config_dump_garbage(struct devicelist *garbage)
1865 {
1866 device_t dv;
1867
1868 while ((dv = TAILQ_FIRST(garbage)) != NULL) {
1869 TAILQ_REMOVE(garbage, dv, dv_list);
1870 config_devdelete(dv);
1871 }
1872 }
1873
1874 static int
1875 config_detach_enter(device_t dev)
1876 {
1877 int error;
1878
1879 mutex_enter(&config_misc_lock);
1880 for (;;) {
1881 if (dev->dv_pending == 0 && dev->dv_detaching == NULL) {
1882 dev->dv_detaching = curlwp;
1883 error = 0;
1884 break;
1885 }
1886 KASSERTMSG(dev->dv_detaching != curlwp,
1887 "recursively detaching %s", device_xname(dev));
1888 error = cv_wait_sig(&config_misc_cv, &config_misc_lock);
1889 if (error)
1890 break;
1891 }
1892 KASSERT(error || dev->dv_detaching == curlwp);
1893 mutex_exit(&config_misc_lock);
1894
1895 return error;
1896 }
1897
1898 static void
1899 config_detach_exit(device_t dev)
1900 {
1901
1902 mutex_enter(&config_misc_lock);
1903 KASSERT(dev->dv_detaching == curlwp);
1904 dev->dv_detaching = NULL;
1905 cv_broadcast(&config_misc_cv);
1906 mutex_exit(&config_misc_lock);
1907 }
1908
1909 /*
1910 * Detach a device. Optionally forced (e.g. because of hardware
1911 * removal) and quiet. Returns zero if successful, non-zero
1912 * (an error code) otherwise.
1913 *
1914 * Note that this code wants to be run from a process context, so
1915 * that the detach can sleep to allow processes which have a device
1916 * open to run and unwind their stacks.
1917 */
1918 int
1919 config_detach(device_t dev, int flags)
1920 {
1921 struct alldevs_foray af;
1922 struct cftable *ct;
1923 cfdata_t cf;
1924 const struct cfattach *ca;
1925 struct cfdriver *cd;
1926 device_t d __diagused;
1927 int rv = 0;
1928
1929 KERNEL_LOCK(1, NULL);
1930
1931 cf = dev->dv_cfdata;
1932 KASSERTMSG((cf == NULL || cf->cf_fstate == FSTATE_FOUND ||
1933 cf->cf_fstate == FSTATE_STAR),
1934 "config_detach: %s: bad device fstate: %d",
1935 device_xname(dev), cf ? cf->cf_fstate : -1);
1936
1937 cd = dev->dv_cfdriver;
1938 KASSERT(cd != NULL);
1939
1940 ca = dev->dv_cfattach;
1941 KASSERT(ca != NULL);
1942
1943 /*
1944 * Only one detach at a time, please -- and not until fully
1945 * attached.
1946 */
1947 rv = config_detach_enter(dev);
1948 if (rv) {
1949 KERNEL_UNLOCK_ONE(NULL);
1950 return rv;
1951 }
1952
1953 mutex_enter(&alldevs_lock);
1954 if (dev->dv_del_gen != 0) {
1955 mutex_exit(&alldevs_lock);
1956 #ifdef DIAGNOSTIC
1957 printf("%s: %s is already detached\n", __func__,
1958 device_xname(dev));
1959 #endif /* DIAGNOSTIC */
1960 config_detach_exit(dev);
1961 KERNEL_UNLOCK_ONE(NULL);
1962 return ENOENT;
1963 }
1964 alldevs_nwrite++;
1965 mutex_exit(&alldevs_lock);
1966
1967 if (!detachall &&
1968 (flags & (DETACH_SHUTDOWN|DETACH_FORCE)) == DETACH_SHUTDOWN &&
1969 (dev->dv_flags & DVF_DETACH_SHUTDOWN) == 0) {
1970 rv = EOPNOTSUPP;
1971 } else if (ca->ca_detach != NULL) {
1972 rv = (*ca->ca_detach)(dev, flags);
1973 } else
1974 rv = EOPNOTSUPP;
1975
1976 /*
1977 * If it was not possible to detach the device, then we either
1978 * panic() (for the forced but failed case), or return an error.
1979 *
1980 * If it was possible to detach the device, ensure that the
1981 * device is deactivated.
1982 */
1983 if (rv == 0)
1984 dev->dv_flags &= ~DVF_ACTIVE;
1985 else if ((flags & DETACH_FORCE) == 0)
1986 goto out;
1987 else {
1988 panic("config_detach: forced detach of %s failed (%d)",
1989 device_xname(dev), rv);
1990 }
1991
1992 /*
1993 * The device has now been successfully detached.
1994 */
1995
1996 /* Let userland know */
1997 devmon_report_device(dev, false);
1998
1999 #ifdef DIAGNOSTIC
2000 /*
2001 * Sanity: If you're successfully detached, you should have no
2002 * children. (Note that because children must be attached
2003 * after parents, we only need to search the latter part of
2004 * the list.)
2005 */
2006 mutex_enter(&alldevs_lock);
2007 for (d = TAILQ_NEXT(dev, dv_list); d != NULL;
2008 d = TAILQ_NEXT(d, dv_list)) {
2009 if (d->dv_parent == dev && d->dv_del_gen == 0) {
2010 printf("config_detach: detached device %s"
2011 " has children %s\n", device_xname(dev),
2012 device_xname(d));
2013 panic("config_detach");
2014 }
2015 }
2016 mutex_exit(&alldevs_lock);
2017 #endif
2018
2019 /* notify the parent that the child is gone */
2020 if (dev->dv_parent) {
2021 device_t p = dev->dv_parent;
2022 if (p->dv_cfattach->ca_childdetached)
2023 (*p->dv_cfattach->ca_childdetached)(p, dev);
2024 }
2025
2026 /*
2027 * Mark cfdata to show that the unit can be reused, if possible.
2028 */
2029 TAILQ_FOREACH(ct, &allcftables, ct_list) {
2030 for (cf = ct->ct_cfdata; cf->cf_name; cf++) {
2031 if (STREQ(cf->cf_name, cd->cd_name)) {
2032 if (cf->cf_fstate == FSTATE_FOUND &&
2033 cf->cf_unit == dev->dv_unit)
2034 cf->cf_fstate = FSTATE_NOTFOUND;
2035 }
2036 }
2037 }
2038
2039 if (dev->dv_cfdata != NULL && (flags & DETACH_QUIET) == 0)
2040 aprint_normal_dev(dev, "detached\n");
2041
2042 out:
2043 config_detach_exit(dev);
2044
2045 config_alldevs_enter(&af);
2046 KASSERT(alldevs_nwrite != 0);
2047 --alldevs_nwrite;
2048 if (rv == 0 && dev->dv_del_gen == 0) {
2049 if (alldevs_nwrite == 0 && alldevs_nread == 0)
2050 config_devunlink(dev, &af.af_garbage);
2051 else {
2052 dev->dv_del_gen = alldevs_gen;
2053 alldevs_garbage = true;
2054 }
2055 }
2056 config_alldevs_exit(&af);
2057
2058 KERNEL_UNLOCK_ONE(NULL);
2059
2060 return rv;
2061 }
2062
2063 int
2064 config_detach_children(device_t parent, int flags)
2065 {
2066 device_t dv;
2067 deviter_t di;
2068 int error = 0;
2069
2070 KASSERT(KERNEL_LOCKED_P());
2071
2072 for (dv = deviter_first(&di, DEVITER_F_RW); dv != NULL;
2073 dv = deviter_next(&di)) {
2074 if (device_parent(dv) != parent)
2075 continue;
2076 if ((error = config_detach(dv, flags)) != 0)
2077 break;
2078 }
2079 deviter_release(&di);
2080 return error;
2081 }
2082
2083 device_t
2084 shutdown_first(struct shutdown_state *s)
2085 {
2086 if (!s->initialized) {
2087 deviter_init(&s->di, DEVITER_F_SHUTDOWN|DEVITER_F_LEAVES_FIRST);
2088 s->initialized = true;
2089 }
2090 return shutdown_next(s);
2091 }
2092
2093 device_t
2094 shutdown_next(struct shutdown_state *s)
2095 {
2096 device_t dv;
2097
2098 while ((dv = deviter_next(&s->di)) != NULL && !device_is_active(dv))
2099 ;
2100
2101 if (dv == NULL)
2102 s->initialized = false;
2103
2104 return dv;
2105 }
2106
2107 bool
2108 config_detach_all(int how)
2109 {
2110 static struct shutdown_state s;
2111 device_t curdev;
2112 bool progress = false;
2113 int flags;
2114
2115 KERNEL_LOCK(1, NULL);
2116
2117 if ((how & (RB_NOSYNC|RB_DUMP)) != 0)
2118 goto out;
2119
2120 if ((how & RB_POWERDOWN) == RB_POWERDOWN)
2121 flags = DETACH_SHUTDOWN | DETACH_POWEROFF;
2122 else
2123 flags = DETACH_SHUTDOWN;
2124
2125 for (curdev = shutdown_first(&s); curdev != NULL;
2126 curdev = shutdown_next(&s)) {
2127 aprint_debug(" detaching %s, ", device_xname(curdev));
2128 if (config_detach(curdev, flags) == 0) {
2129 progress = true;
2130 aprint_debug("success.");
2131 } else
2132 aprint_debug("failed.");
2133 }
2134
2135 out: KERNEL_UNLOCK_ONE(NULL);
2136 return progress;
2137 }
2138
2139 static bool
2140 device_is_ancestor_of(device_t ancestor, device_t descendant)
2141 {
2142 device_t dv;
2143
2144 for (dv = descendant; dv != NULL; dv = device_parent(dv)) {
2145 if (device_parent(dv) == ancestor)
2146 return true;
2147 }
2148 return false;
2149 }
2150
2151 int
2152 config_deactivate(device_t dev)
2153 {
2154 deviter_t di;
2155 const struct cfattach *ca;
2156 device_t descendant;
2157 int s, rv = 0, oflags;
2158
2159 for (descendant = deviter_first(&di, DEVITER_F_ROOT_FIRST);
2160 descendant != NULL;
2161 descendant = deviter_next(&di)) {
2162 if (dev != descendant &&
2163 !device_is_ancestor_of(dev, descendant))
2164 continue;
2165
2166 if ((descendant->dv_flags & DVF_ACTIVE) == 0)
2167 continue;
2168
2169 ca = descendant->dv_cfattach;
2170 oflags = descendant->dv_flags;
2171
2172 descendant->dv_flags &= ~DVF_ACTIVE;
2173 if (ca->ca_activate == NULL)
2174 continue;
2175 s = splhigh();
2176 rv = (*ca->ca_activate)(descendant, DVACT_DEACTIVATE);
2177 splx(s);
2178 if (rv != 0)
2179 descendant->dv_flags = oflags;
2180 }
2181 deviter_release(&di);
2182 return rv;
2183 }
2184
2185 /*
2186 * Defer the configuration of the specified device until all
2187 * of its parent's devices have been attached.
2188 */
2189 void
2190 config_defer(device_t dev, void (*func)(device_t))
2191 {
2192 struct deferred_config *dc;
2193
2194 if (dev->dv_parent == NULL)
2195 panic("config_defer: can't defer config of a root device");
2196
2197 dc = kmem_alloc(sizeof(*dc), KM_SLEEP);
2198
2199 config_pending_incr(dev);
2200
2201 mutex_enter(&config_misc_lock);
2202 #ifdef DIAGNOSTIC
2203 struct deferred_config *odc;
2204 TAILQ_FOREACH(odc, &deferred_config_queue, dc_queue) {
2205 if (odc->dc_dev == dev)
2206 panic("config_defer: deferred twice");
2207 }
2208 #endif
2209 dc->dc_dev = dev;
2210 dc->dc_func = func;
2211 TAILQ_INSERT_TAIL(&deferred_config_queue, dc, dc_queue);
2212 mutex_exit(&config_misc_lock);
2213 }
2214
2215 /*
2216 * Defer some autoconfiguration for a device until after interrupts
2217 * are enabled.
2218 */
2219 void
2220 config_interrupts(device_t dev, void (*func)(device_t))
2221 {
2222 struct deferred_config *dc;
2223
2224 /*
2225 * If interrupts are enabled, callback now.
2226 */
2227 if (cold == 0) {
2228 (*func)(dev);
2229 return;
2230 }
2231
2232 dc = kmem_alloc(sizeof(*dc), KM_SLEEP);
2233
2234 config_pending_incr(dev);
2235
2236 mutex_enter(&config_misc_lock);
2237 #ifdef DIAGNOSTIC
2238 struct deferred_config *odc;
2239 TAILQ_FOREACH(odc, &interrupt_config_queue, dc_queue) {
2240 if (odc->dc_dev == dev)
2241 panic("config_interrupts: deferred twice");
2242 }
2243 #endif
2244 dc->dc_dev = dev;
2245 dc->dc_func = func;
2246 TAILQ_INSERT_TAIL(&interrupt_config_queue, dc, dc_queue);
2247 mutex_exit(&config_misc_lock);
2248 }
2249
2250 /*
2251 * Defer some autoconfiguration for a device until after root file system
2252 * is mounted (to load firmware etc).
2253 */
2254 void
2255 config_mountroot(device_t dev, void (*func)(device_t))
2256 {
2257 struct deferred_config *dc;
2258
2259 /*
2260 * If root file system is mounted, callback now.
2261 */
2262 if (root_is_mounted) {
2263 (*func)(dev);
2264 return;
2265 }
2266
2267 dc = kmem_alloc(sizeof(*dc), KM_SLEEP);
2268
2269 mutex_enter(&config_misc_lock);
2270 #ifdef DIAGNOSTIC
2271 struct deferred_config *odc;
2272 TAILQ_FOREACH(odc, &mountroot_config_queue, dc_queue) {
2273 if (odc->dc_dev == dev)
2274 panic("%s: deferred twice", __func__);
2275 }
2276 #endif
2277
2278 dc->dc_dev = dev;
2279 dc->dc_func = func;
2280 TAILQ_INSERT_TAIL(&mountroot_config_queue, dc, dc_queue);
2281 mutex_exit(&config_misc_lock);
2282 }
2283
2284 /*
2285 * Process a deferred configuration queue.
2286 */
2287 static void
2288 config_process_deferred(struct deferred_config_head *queue, device_t parent)
2289 {
2290 struct deferred_config *dc;
2291
2292 KASSERT(KERNEL_LOCKED_P());
2293
2294 mutex_enter(&config_misc_lock);
2295 dc = TAILQ_FIRST(queue);
2296 while (dc) {
2297 if (parent == NULL || dc->dc_dev->dv_parent == parent) {
2298 TAILQ_REMOVE(queue, dc, dc_queue);
2299 mutex_exit(&config_misc_lock);
2300
2301 (*dc->dc_func)(dc->dc_dev);
2302 config_pending_decr(dc->dc_dev);
2303 kmem_free(dc, sizeof(*dc));
2304
2305 mutex_enter(&config_misc_lock);
2306 /* Restart, queue might have changed */
2307 dc = TAILQ_FIRST(queue);
2308 } else {
2309 dc = TAILQ_NEXT(dc, dc_queue);
2310 }
2311 }
2312 mutex_exit(&config_misc_lock);
2313 }
2314
2315 /*
2316 * Manipulate the config_pending semaphore.
2317 */
2318 void
2319 config_pending_incr(device_t dev)
2320 {
2321
2322 mutex_enter(&config_misc_lock);
2323 KASSERTMSG(dev->dv_pending < INT_MAX,
2324 "%s: excess config_pending_incr", device_xname(dev));
2325 if (dev->dv_pending++ == 0)
2326 TAILQ_INSERT_TAIL(&config_pending, dev, dv_pending_list);
2327 #ifdef DEBUG_AUTOCONF
2328 printf("%s: %s %d\n", __func__, device_xname(dev), dev->dv_pending);
2329 #endif
2330 mutex_exit(&config_misc_lock);
2331 }
2332
2333 void
2334 config_pending_decr(device_t dev)
2335 {
2336
2337 mutex_enter(&config_misc_lock);
2338 KASSERTMSG(dev->dv_pending > 0,
2339 "%s: excess config_pending_decr", device_xname(dev));
2340 if (--dev->dv_pending == 0) {
2341 TAILQ_REMOVE(&config_pending, dev, dv_pending_list);
2342 cv_broadcast(&config_misc_cv);
2343 }
2344 #ifdef DEBUG_AUTOCONF
2345 printf("%s: %s %d\n", __func__, device_xname(dev), dev->dv_pending);
2346 #endif
2347 mutex_exit(&config_misc_lock);
2348 }
2349
2350 /*
2351 * Register a "finalization" routine. Finalization routines are
2352 * called iteratively once all real devices have been found during
2353 * autoconfiguration, for as long as any one finalizer has done
2354 * any work.
2355 */
2356 int
2357 config_finalize_register(device_t dev, int (*fn)(device_t))
2358 {
2359 struct finalize_hook *f;
2360 int error = 0;
2361
2362 KERNEL_LOCK(1, NULL);
2363
2364 /*
2365 * If finalization has already been done, invoke the
2366 * callback function now.
2367 */
2368 if (config_finalize_done) {
2369 while ((*fn)(dev) != 0)
2370 /* loop */ ;
2371 goto out;
2372 }
2373
2374 /* Ensure this isn't already on the list. */
2375 TAILQ_FOREACH(f, &config_finalize_list, f_list) {
2376 if (f->f_func == fn && f->f_dev == dev) {
2377 error = EEXIST;
2378 goto out;
2379 }
2380 }
2381
2382 f = kmem_alloc(sizeof(*f), KM_SLEEP);
2383 f->f_func = fn;
2384 f->f_dev = dev;
2385 TAILQ_INSERT_TAIL(&config_finalize_list, f, f_list);
2386
2387 /* Success! */
2388 error = 0;
2389
2390 out: KERNEL_UNLOCK_ONE(NULL);
2391 return error;
2392 }
2393
2394 void
2395 config_finalize(void)
2396 {
2397 struct finalize_hook *f;
2398 struct pdevinit *pdev;
2399 extern struct pdevinit pdevinit[];
2400 int errcnt, rv;
2401
2402 /*
2403 * Now that device driver threads have been created, wait for
2404 * them to finish any deferred autoconfiguration.
2405 */
2406 mutex_enter(&config_misc_lock);
2407 while (!TAILQ_EMPTY(&config_pending)) {
2408 device_t dev;
2409 int error;
2410
2411 error = cv_timedwait(&config_misc_cv, &config_misc_lock,
2412 mstohz(1000));
2413 if (error == EWOULDBLOCK) {
2414 aprint_debug("waiting for devices:");
2415 TAILQ_FOREACH(dev, &config_pending, dv_pending_list)
2416 aprint_debug(" %s", device_xname(dev));
2417 aprint_debug("\n");
2418 }
2419 }
2420 mutex_exit(&config_misc_lock);
2421
2422 KERNEL_LOCK(1, NULL);
2423
2424 /* Attach pseudo-devices. */
2425 for (pdev = pdevinit; pdev->pdev_attach != NULL; pdev++)
2426 (*pdev->pdev_attach)(pdev->pdev_count);
2427
2428 /* Run the hooks until none of them does any work. */
2429 do {
2430 rv = 0;
2431 TAILQ_FOREACH(f, &config_finalize_list, f_list)
2432 rv |= (*f->f_func)(f->f_dev);
2433 } while (rv != 0);
2434
2435 config_finalize_done = 1;
2436
2437 /* Now free all the hooks. */
2438 while ((f = TAILQ_FIRST(&config_finalize_list)) != NULL) {
2439 TAILQ_REMOVE(&config_finalize_list, f, f_list);
2440 kmem_free(f, sizeof(*f));
2441 }
2442
2443 KERNEL_UNLOCK_ONE(NULL);
2444
2445 errcnt = aprint_get_error_count();
2446 if ((boothowto & (AB_QUIET|AB_SILENT)) != 0 &&
2447 (boothowto & AB_VERBOSE) == 0) {
2448 mutex_enter(&config_misc_lock);
2449 if (config_do_twiddle) {
2450 config_do_twiddle = 0;
2451 printf_nolog(" done.\n");
2452 }
2453 mutex_exit(&config_misc_lock);
2454 }
2455 if (errcnt != 0) {
2456 printf("WARNING: %d error%s while detecting hardware; "
2457 "check system log.\n", errcnt,
2458 errcnt == 1 ? "" : "s");
2459 }
2460 }
2461
2462 void
2463 config_twiddle_init(void)
2464 {
2465
2466 if ((boothowto & (AB_SILENT|AB_VERBOSE)) == AB_SILENT) {
2467 config_do_twiddle = 1;
2468 }
2469 callout_setfunc(&config_twiddle_ch, config_twiddle_fn, NULL);
2470 }
2471
2472 void
2473 config_twiddle_fn(void *cookie)
2474 {
2475
2476 mutex_enter(&config_misc_lock);
2477 if (config_do_twiddle) {
2478 twiddle();
2479 callout_schedule(&config_twiddle_ch, mstohz(100));
2480 }
2481 mutex_exit(&config_misc_lock);
2482 }
2483
2484 static void
2485 config_alldevs_enter(struct alldevs_foray *af)
2486 {
2487 TAILQ_INIT(&af->af_garbage);
2488 mutex_enter(&alldevs_lock);
2489 config_collect_garbage(&af->af_garbage);
2490 }
2491
2492 static void
2493 config_alldevs_exit(struct alldevs_foray *af)
2494 {
2495 mutex_exit(&alldevs_lock);
2496 config_dump_garbage(&af->af_garbage);
2497 }
2498
2499 /*
2500 * device_lookup:
2501 *
2502 * Look up a device instance for a given driver.
2503 */
2504 device_t
2505 device_lookup(cfdriver_t cd, int unit)
2506 {
2507 device_t dv;
2508
2509 mutex_enter(&alldevs_lock);
2510 if (unit < 0 || unit >= cd->cd_ndevs)
2511 dv = NULL;
2512 else if ((dv = cd->cd_devs[unit]) != NULL && dv->dv_del_gen != 0)
2513 dv = NULL;
2514 mutex_exit(&alldevs_lock);
2515
2516 return dv;
2517 }
2518
2519 /*
2520 * device_lookup_private:
2521 *
2522 * Look up a softc instance for a given driver.
2523 */
2524 void *
2525 device_lookup_private(cfdriver_t cd, int unit)
2526 {
2527
2528 return device_private(device_lookup(cd, unit));
2529 }
2530
2531 /*
2532 * device_find_by_xname:
2533 *
2534 * Returns the device of the given name or NULL if it doesn't exist.
2535 */
2536 device_t
2537 device_find_by_xname(const char *name)
2538 {
2539 device_t dv;
2540 deviter_t di;
2541
2542 for (dv = deviter_first(&di, 0); dv != NULL; dv = deviter_next(&di)) {
2543 if (strcmp(device_xname(dv), name) == 0)
2544 break;
2545 }
2546 deviter_release(&di);
2547
2548 return dv;
2549 }
2550
2551 /*
2552 * device_find_by_driver_unit:
2553 *
2554 * Returns the device of the given driver name and unit or
2555 * NULL if it doesn't exist.
2556 */
2557 device_t
2558 device_find_by_driver_unit(const char *name, int unit)
2559 {
2560 struct cfdriver *cd;
2561
2562 if ((cd = config_cfdriver_lookup(name)) == NULL)
2563 return NULL;
2564 return device_lookup(cd, unit);
2565 }
2566
2567 static bool
2568 match_strcmp(const char * const s1, const char * const s2)
2569 {
2570 return strcmp(s1, s2) == 0;
2571 }
2572
2573 static bool
2574 match_pmatch(const char * const s1, const char * const s2)
2575 {
2576 return pmatch(s1, s2, NULL) == 2;
2577 }
2578
2579 static bool
2580 strarray_match_internal(const char ** const strings,
2581 unsigned int const nstrings, const char * const str,
2582 unsigned int * const indexp,
2583 bool (*match_fn)(const char *, const char *))
2584 {
2585 unsigned int i;
2586
2587 if (strings == NULL || nstrings == 0) {
2588 return false;
2589 }
2590
2591 for (i = 0; i < nstrings; i++) {
2592 if ((*match_fn)(strings[i], str)) {
2593 *indexp = i;
2594 return true;
2595 }
2596 }
2597
2598 return false;
2599 }
2600
2601 static int
2602 strarray_match(const char ** const strings, unsigned int const nstrings,
2603 const char * const str)
2604 {
2605 unsigned int idx;
2606
2607 if (strarray_match_internal(strings, nstrings, str, &idx,
2608 match_strcmp)) {
2609 return (int)(nstrings - idx);
2610 }
2611 return 0;
2612 }
2613
2614 static int
2615 strarray_pmatch(const char ** const strings, unsigned int const nstrings,
2616 const char * const pattern)
2617 {
2618 unsigned int idx;
2619
2620 if (strarray_match_internal(strings, nstrings, pattern, &idx,
2621 match_pmatch)) {
2622 return (int)(nstrings - idx);
2623 }
2624 return 0;
2625 }
2626
2627 static int
2628 device_compatible_match_strarray_internal(
2629 const char **device_compats, int ndevice_compats,
2630 const struct device_compatible_entry *driver_compats,
2631 const struct device_compatible_entry **matching_entryp,
2632 int (*match_fn)(const char **, unsigned int, const char *))
2633 {
2634 const struct device_compatible_entry *dce = NULL;
2635 int rv;
2636
2637 if (ndevice_compats == 0 || device_compats == NULL ||
2638 driver_compats == NULL)
2639 return 0;
2640
2641 for (dce = driver_compats; dce->compat != NULL; dce++) {
2642 rv = (*match_fn)(device_compats, ndevice_compats, dce->compat);
2643 if (rv != 0) {
2644 if (matching_entryp != NULL) {
2645 *matching_entryp = dce;
2646 }
2647 return rv;
2648 }
2649 }
2650 return 0;
2651 }
2652
2653 /*
2654 * device_compatible_match:
2655 *
2656 * Match a driver's "compatible" data against a device's
2657 * "compatible" strings. Returns resulted weighted by
2658 * which device "compatible" string was matched.
2659 */
2660 int
2661 device_compatible_match(const char **device_compats, int ndevice_compats,
2662 const struct device_compatible_entry *driver_compats)
2663 {
2664 return device_compatible_match_strarray_internal(device_compats,
2665 ndevice_compats, driver_compats, NULL, strarray_match);
2666 }
2667
2668 /*
2669 * device_compatible_pmatch:
2670 *
2671 * Like device_compatible_match(), but uses pmatch(9) to compare
2672 * the device "compatible" strings against patterns in the
2673 * driver's "compatible" data.
2674 */
2675 int
2676 device_compatible_pmatch(const char **device_compats, int ndevice_compats,
2677 const struct device_compatible_entry *driver_compats)
2678 {
2679 return device_compatible_match_strarray_internal(device_compats,
2680 ndevice_compats, driver_compats, NULL, strarray_pmatch);
2681 }
2682
2683 static int
2684 device_compatible_match_strlist_internal(
2685 const char * const device_compats, size_t const device_compatsize,
2686 const struct device_compatible_entry *driver_compats,
2687 const struct device_compatible_entry **matching_entryp,
2688 int (*match_fn)(const char *, size_t, const char *))
2689 {
2690 const struct device_compatible_entry *dce = NULL;
2691 int rv;
2692
2693 if (device_compats == NULL || device_compatsize == 0 ||
2694 driver_compats == NULL)
2695 return 0;
2696
2697 for (dce = driver_compats; dce->compat != NULL; dce++) {
2698 rv = (*match_fn)(device_compats, device_compatsize,
2699 dce->compat);
2700 if (rv != 0) {
2701 if (matching_entryp != NULL) {
2702 *matching_entryp = dce;
2703 }
2704 return rv;
2705 }
2706 }
2707 return 0;
2708 }
2709
2710 /*
2711 * device_compatible_match_strlist:
2712 *
2713 * Like device_compatible_match(), but take the device
2714 * "compatible" strings as an OpenFirmware-style string
2715 * list.
2716 */
2717 int
2718 device_compatible_match_strlist(
2719 const char * const device_compats, size_t const device_compatsize,
2720 const struct device_compatible_entry *driver_compats)
2721 {
2722 return device_compatible_match_strlist_internal(device_compats,
2723 device_compatsize, driver_compats, NULL, strlist_match);
2724 }
2725
2726 /*
2727 * device_compatible_pmatch_strlist:
2728 *
2729 * Like device_compatible_pmatch(), but take the device
2730 * "compatible" strings as an OpenFirmware-style string
2731 * list.
2732 */
2733 int
2734 device_compatible_pmatch_strlist(
2735 const char * const device_compats, size_t const device_compatsize,
2736 const struct device_compatible_entry *driver_compats)
2737 {
2738 return device_compatible_match_strlist_internal(device_compats,
2739 device_compatsize, driver_compats, NULL, strlist_pmatch);
2740 }
2741
2742 static int
2743 device_compatible_match_id_internal(
2744 uintptr_t const id, uintptr_t const mask, uintptr_t const sentinel_id,
2745 const struct device_compatible_entry *driver_compats,
2746 const struct device_compatible_entry **matching_entryp)
2747 {
2748 const struct device_compatible_entry *dce = NULL;
2749
2750 if (mask == 0)
2751 return 0;
2752
2753 for (dce = driver_compats; dce->id != sentinel_id; dce++) {
2754 if ((id & mask) == dce->id) {
2755 if (matching_entryp != NULL) {
2756 *matching_entryp = dce;
2757 }
2758 return 1;
2759 }
2760 }
2761 return 0;
2762 }
2763
2764 /*
2765 * device_compatible_match_id:
2766 *
2767 * Like device_compatible_match(), but takes a single
2768 * unsigned integer device ID.
2769 */
2770 int
2771 device_compatible_match_id(
2772 uintptr_t const id, uintptr_t const sentinel_id,
2773 const struct device_compatible_entry *driver_compats)
2774 {
2775 return device_compatible_match_id_internal(id, (uintptr_t)-1,
2776 sentinel_id, driver_compats, NULL);
2777 }
2778
2779 /*
2780 * device_compatible_lookup:
2781 *
2782 * Look up and return the device_compatible_entry, using the
2783 * same matching criteria used by device_compatible_match().
2784 */
2785 const struct device_compatible_entry *
2786 device_compatible_lookup(const char **device_compats, int ndevice_compats,
2787 const struct device_compatible_entry *driver_compats)
2788 {
2789 const struct device_compatible_entry *dce;
2790
2791 if (device_compatible_match_strarray_internal(device_compats,
2792 ndevice_compats, driver_compats, &dce, strarray_match)) {
2793 return dce;
2794 }
2795 return NULL;
2796 }
2797
2798 /*
2799 * device_compatible_plookup:
2800 *
2801 * Look up and return the device_compatible_entry, using the
2802 * same matching criteria used by device_compatible_pmatch().
2803 */
2804 const struct device_compatible_entry *
2805 device_compatible_plookup(const char **device_compats, int ndevice_compats,
2806 const struct device_compatible_entry *driver_compats)
2807 {
2808 const struct device_compatible_entry *dce;
2809
2810 if (device_compatible_match_strarray_internal(device_compats,
2811 ndevice_compats, driver_compats, &dce, strarray_pmatch)) {
2812 return dce;
2813 }
2814 return NULL;
2815 }
2816
2817 /*
2818 * device_compatible_lookup_strlist:
2819 *
2820 * Like device_compatible_lookup(), but take the device
2821 * "compatible" strings as an OpenFirmware-style string
2822 * list.
2823 */
2824 const struct device_compatible_entry *
2825 device_compatible_lookup_strlist(
2826 const char * const device_compats, size_t const device_compatsize,
2827 const struct device_compatible_entry *driver_compats)
2828 {
2829 const struct device_compatible_entry *dce;
2830
2831 if (device_compatible_match_strlist_internal(device_compats,
2832 device_compatsize, driver_compats, &dce, strlist_match)) {
2833 return dce;
2834 }
2835 return NULL;
2836 }
2837
2838 /*
2839 * device_compatible_plookup_strlist:
2840 *
2841 * Like device_compatible_plookup(), but take the device
2842 * "compatible" strings as an OpenFirmware-style string
2843 * list.
2844 */
2845 const struct device_compatible_entry *
2846 device_compatible_plookup_strlist(
2847 const char * const device_compats, size_t const device_compatsize,
2848 const struct device_compatible_entry *driver_compats)
2849 {
2850 const struct device_compatible_entry *dce;
2851
2852 if (device_compatible_match_strlist_internal(device_compats,
2853 device_compatsize, driver_compats, &dce, strlist_pmatch)) {
2854 return dce;
2855 }
2856 return NULL;
2857 }
2858
2859 /*
2860 * device_compatible_lookup_id:
2861 *
2862 * Like device_compatible_lookup(), but takes a single
2863 * unsigned integer device ID.
2864 */
2865 const struct device_compatible_entry *
2866 device_compatible_lookup_id(
2867 uintptr_t const id, uintptr_t const sentinel_id,
2868 const struct device_compatible_entry *driver_compats)
2869 {
2870 const struct device_compatible_entry *dce;
2871
2872 if (device_compatible_match_id_internal(id, (uintptr_t)-1,
2873 sentinel_id, driver_compats, &dce)) {
2874 return dce;
2875 }
2876 return NULL;
2877 }
2878
2879 /*
2880 * Power management related functions.
2881 */
2882
2883 bool
2884 device_pmf_is_registered(device_t dev)
2885 {
2886 return (dev->dv_flags & DVF_POWER_HANDLERS) != 0;
2887 }
2888
2889 bool
2890 device_pmf_driver_suspend(device_t dev, const pmf_qual_t *qual)
2891 {
2892 if ((dev->dv_flags & DVF_DRIVER_SUSPENDED) != 0)
2893 return true;
2894 if ((dev->dv_flags & DVF_CLASS_SUSPENDED) == 0)
2895 return false;
2896 if (pmf_qual_depth(qual) <= DEVACT_LEVEL_DRIVER &&
2897 dev->dv_driver_suspend != NULL &&
2898 !(*dev->dv_driver_suspend)(dev, qual))
2899 return false;
2900
2901 dev->dv_flags |= DVF_DRIVER_SUSPENDED;
2902 return true;
2903 }
2904
2905 bool
2906 device_pmf_driver_resume(device_t dev, const pmf_qual_t *qual)
2907 {
2908 if ((dev->dv_flags & DVF_DRIVER_SUSPENDED) == 0)
2909 return true;
2910 if ((dev->dv_flags & DVF_BUS_SUSPENDED) != 0)
2911 return false;
2912 if (pmf_qual_depth(qual) <= DEVACT_LEVEL_DRIVER &&
2913 dev->dv_driver_resume != NULL &&
2914 !(*dev->dv_driver_resume)(dev, qual))
2915 return false;
2916
2917 dev->dv_flags &= ~DVF_DRIVER_SUSPENDED;
2918 return true;
2919 }
2920
2921 bool
2922 device_pmf_driver_shutdown(device_t dev, int how)
2923 {
2924
2925 if (*dev->dv_driver_shutdown != NULL &&
2926 !(*dev->dv_driver_shutdown)(dev, how))
2927 return false;
2928 return true;
2929 }
2930
2931 bool
2932 device_pmf_driver_register(device_t dev,
2933 bool (*suspend)(device_t, const pmf_qual_t *),
2934 bool (*resume)(device_t, const pmf_qual_t *),
2935 bool (*shutdown)(device_t, int))
2936 {
2937 dev->dv_driver_suspend = suspend;
2938 dev->dv_driver_resume = resume;
2939 dev->dv_driver_shutdown = shutdown;
2940 dev->dv_flags |= DVF_POWER_HANDLERS;
2941 return true;
2942 }
2943
2944 void
2945 device_pmf_driver_deregister(device_t dev)
2946 {
2947 device_lock_t dvl = device_getlock(dev);
2948
2949 dev->dv_driver_suspend = NULL;
2950 dev->dv_driver_resume = NULL;
2951
2952 mutex_enter(&dvl->dvl_mtx);
2953 dev->dv_flags &= ~DVF_POWER_HANDLERS;
2954 while (dvl->dvl_nlock > 0 || dvl->dvl_nwait > 0) {
2955 /* Wake a thread that waits for the lock. That
2956 * thread will fail to acquire the lock, and then
2957 * it will wake the next thread that waits for the
2958 * lock, or else it will wake us.
2959 */
2960 cv_signal(&dvl->dvl_cv);
2961 pmflock_debug(dev, __func__, __LINE__);
2962 cv_wait(&dvl->dvl_cv, &dvl->dvl_mtx);
2963 pmflock_debug(dev, __func__, __LINE__);
2964 }
2965 mutex_exit(&dvl->dvl_mtx);
2966 }
2967
2968 bool
2969 device_pmf_driver_child_register(device_t dev)
2970 {
2971 device_t parent = device_parent(dev);
2972
2973 if (parent == NULL || parent->dv_driver_child_register == NULL)
2974 return true;
2975 return (*parent->dv_driver_child_register)(dev);
2976 }
2977
2978 void
2979 device_pmf_driver_set_child_register(device_t dev,
2980 bool (*child_register)(device_t))
2981 {
2982 dev->dv_driver_child_register = child_register;
2983 }
2984
2985 static void
2986 pmflock_debug(device_t dev, const char *func, int line)
2987 {
2988 #ifdef PMFLOCK_DEBUG
2989 device_lock_t dvl = device_getlock(dev);
2990 const char *curlwp_name;
2991
2992 if (curlwp->l_name != NULL)
2993 curlwp_name = curlwp->l_name;
2994 else
2995 curlwp_name = curlwp->l_proc->p_comm;
2996
2997 aprint_debug_dev(dev,
2998 "%s.%d, %s dvl_nlock %d dvl_nwait %d dv_flags %x\n", func, line,
2999 curlwp_name, dvl->dvl_nlock, dvl->dvl_nwait, dev->dv_flags);
3000 #endif /* PMFLOCK_DEBUG */
3001 }
3002
3003 static bool
3004 device_pmf_lock1(device_t dev)
3005 {
3006 device_lock_t dvl = device_getlock(dev);
3007
3008 while (device_pmf_is_registered(dev) &&
3009 dvl->dvl_nlock > 0 && dvl->dvl_holder != curlwp) {
3010 dvl->dvl_nwait++;
3011 pmflock_debug(dev, __func__, __LINE__);
3012 cv_wait(&dvl->dvl_cv, &dvl->dvl_mtx);
3013 pmflock_debug(dev, __func__, __LINE__);
3014 dvl->dvl_nwait--;
3015 }
3016 if (!device_pmf_is_registered(dev)) {
3017 pmflock_debug(dev, __func__, __LINE__);
3018 /* We could not acquire the lock, but some other thread may
3019 * wait for it, also. Wake that thread.
3020 */
3021 cv_signal(&dvl->dvl_cv);
3022 return false;
3023 }
3024 dvl->dvl_nlock++;
3025 dvl->dvl_holder = curlwp;
3026 pmflock_debug(dev, __func__, __LINE__);
3027 return true;
3028 }
3029
3030 bool
3031 device_pmf_lock(device_t dev)
3032 {
3033 bool rc;
3034 device_lock_t dvl = device_getlock(dev);
3035
3036 mutex_enter(&dvl->dvl_mtx);
3037 rc = device_pmf_lock1(dev);
3038 mutex_exit(&dvl->dvl_mtx);
3039
3040 return rc;
3041 }
3042
3043 void
3044 device_pmf_unlock(device_t dev)
3045 {
3046 device_lock_t dvl = device_getlock(dev);
3047
3048 KASSERT(dvl->dvl_nlock > 0);
3049 mutex_enter(&dvl->dvl_mtx);
3050 if (--dvl->dvl_nlock == 0)
3051 dvl->dvl_holder = NULL;
3052 cv_signal(&dvl->dvl_cv);
3053 pmflock_debug(dev, __func__, __LINE__);
3054 mutex_exit(&dvl->dvl_mtx);
3055 }
3056
3057 device_lock_t
3058 device_getlock(device_t dev)
3059 {
3060 return &dev->dv_lock;
3061 }
3062
3063 void *
3064 device_pmf_bus_private(device_t dev)
3065 {
3066 return dev->dv_bus_private;
3067 }
3068
3069 bool
3070 device_pmf_bus_suspend(device_t dev, const pmf_qual_t *qual)
3071 {
3072 if ((dev->dv_flags & DVF_BUS_SUSPENDED) != 0)
3073 return true;
3074 if ((dev->dv_flags & DVF_CLASS_SUSPENDED) == 0 ||
3075 (dev->dv_flags & DVF_DRIVER_SUSPENDED) == 0)
3076 return false;
3077 if (pmf_qual_depth(qual) <= DEVACT_LEVEL_BUS &&
3078 dev->dv_bus_suspend != NULL &&
3079 !(*dev->dv_bus_suspend)(dev, qual))
3080 return false;
3081
3082 dev->dv_flags |= DVF_BUS_SUSPENDED;
3083 return true;
3084 }
3085
3086 bool
3087 device_pmf_bus_resume(device_t dev, const pmf_qual_t *qual)
3088 {
3089 if ((dev->dv_flags & DVF_BUS_SUSPENDED) == 0)
3090 return true;
3091 if (pmf_qual_depth(qual) <= DEVACT_LEVEL_BUS &&
3092 dev->dv_bus_resume != NULL &&
3093 !(*dev->dv_bus_resume)(dev, qual))
3094 return false;
3095
3096 dev->dv_flags &= ~DVF_BUS_SUSPENDED;
3097 return true;
3098 }
3099
3100 bool
3101 device_pmf_bus_shutdown(device_t dev, int how)
3102 {
3103
3104 if (*dev->dv_bus_shutdown != NULL &&
3105 !(*dev->dv_bus_shutdown)(dev, how))
3106 return false;
3107 return true;
3108 }
3109
3110 void
3111 device_pmf_bus_register(device_t dev, void *priv,
3112 bool (*suspend)(device_t, const pmf_qual_t *),
3113 bool (*resume)(device_t, const pmf_qual_t *),
3114 bool (*shutdown)(device_t, int), void (*deregister)(device_t))
3115 {
3116 dev->dv_bus_private = priv;
3117 dev->dv_bus_resume = resume;
3118 dev->dv_bus_suspend = suspend;
3119 dev->dv_bus_shutdown = shutdown;
3120 dev->dv_bus_deregister = deregister;
3121 }
3122
3123 void
3124 device_pmf_bus_deregister(device_t dev)
3125 {
3126 if (dev->dv_bus_deregister == NULL)
3127 return;
3128 (*dev->dv_bus_deregister)(dev);
3129 dev->dv_bus_private = NULL;
3130 dev->dv_bus_suspend = NULL;
3131 dev->dv_bus_resume = NULL;
3132 dev->dv_bus_deregister = NULL;
3133 }
3134
3135 void *
3136 device_pmf_class_private(device_t dev)
3137 {
3138 return dev->dv_class_private;
3139 }
3140
3141 bool
3142 device_pmf_class_suspend(device_t dev, const pmf_qual_t *qual)
3143 {
3144 if ((dev->dv_flags & DVF_CLASS_SUSPENDED) != 0)
3145 return true;
3146 if (pmf_qual_depth(qual) <= DEVACT_LEVEL_CLASS &&
3147 dev->dv_class_suspend != NULL &&
3148 !(*dev->dv_class_suspend)(dev, qual))
3149 return false;
3150
3151 dev->dv_flags |= DVF_CLASS_SUSPENDED;
3152 return true;
3153 }
3154
3155 bool
3156 device_pmf_class_resume(device_t dev, const pmf_qual_t *qual)
3157 {
3158 if ((dev->dv_flags & DVF_CLASS_SUSPENDED) == 0)
3159 return true;
3160 if ((dev->dv_flags & DVF_BUS_SUSPENDED) != 0 ||
3161 (dev->dv_flags & DVF_DRIVER_SUSPENDED) != 0)
3162 return false;
3163 if (pmf_qual_depth(qual) <= DEVACT_LEVEL_CLASS &&
3164 dev->dv_class_resume != NULL &&
3165 !(*dev->dv_class_resume)(dev, qual))
3166 return false;
3167
3168 dev->dv_flags &= ~DVF_CLASS_SUSPENDED;
3169 return true;
3170 }
3171
3172 void
3173 device_pmf_class_register(device_t dev, void *priv,
3174 bool (*suspend)(device_t, const pmf_qual_t *),
3175 bool (*resume)(device_t, const pmf_qual_t *),
3176 void (*deregister)(device_t))
3177 {
3178 dev->dv_class_private = priv;
3179 dev->dv_class_suspend = suspend;
3180 dev->dv_class_resume = resume;
3181 dev->dv_class_deregister = deregister;
3182 }
3183
3184 void
3185 device_pmf_class_deregister(device_t dev)
3186 {
3187 if (dev->dv_class_deregister == NULL)
3188 return;
3189 (*dev->dv_class_deregister)(dev);
3190 dev->dv_class_private = NULL;
3191 dev->dv_class_suspend = NULL;
3192 dev->dv_class_resume = NULL;
3193 dev->dv_class_deregister = NULL;
3194 }
3195
3196 bool
3197 device_active(device_t dev, devactive_t type)
3198 {
3199 size_t i;
3200
3201 if (dev->dv_activity_count == 0)
3202 return false;
3203
3204 for (i = 0; i < dev->dv_activity_count; ++i) {
3205 if (dev->dv_activity_handlers[i] == NULL)
3206 break;
3207 (*dev->dv_activity_handlers[i])(dev, type);
3208 }
3209
3210 return true;
3211 }
3212
3213 bool
3214 device_active_register(device_t dev, void (*handler)(device_t, devactive_t))
3215 {
3216 void (**new_handlers)(device_t, devactive_t);
3217 void (**old_handlers)(device_t, devactive_t);
3218 size_t i, old_size, new_size;
3219 int s;
3220
3221 old_handlers = dev->dv_activity_handlers;
3222 old_size = dev->dv_activity_count;
3223
3224 KASSERT(old_size == 0 || old_handlers != NULL);
3225
3226 for (i = 0; i < old_size; ++i) {
3227 KASSERT(old_handlers[i] != handler);
3228 if (old_handlers[i] == NULL) {
3229 old_handlers[i] = handler;
3230 return true;
3231 }
3232 }
3233
3234 new_size = old_size + 4;
3235 new_handlers = kmem_alloc(sizeof(void *) * new_size, KM_SLEEP);
3236
3237 for (i = 0; i < old_size; ++i)
3238 new_handlers[i] = old_handlers[i];
3239 new_handlers[old_size] = handler;
3240 for (i = old_size+1; i < new_size; ++i)
3241 new_handlers[i] = NULL;
3242
3243 s = splhigh();
3244 dev->dv_activity_count = new_size;
3245 dev->dv_activity_handlers = new_handlers;
3246 splx(s);
3247
3248 if (old_size > 0)
3249 kmem_free(old_handlers, sizeof(void *) * old_size);
3250
3251 return true;
3252 }
3253
3254 void
3255 device_active_deregister(device_t dev, void (*handler)(device_t, devactive_t))
3256 {
3257 void (**old_handlers)(device_t, devactive_t);
3258 size_t i, old_size;
3259 int s;
3260
3261 old_handlers = dev->dv_activity_handlers;
3262 old_size = dev->dv_activity_count;
3263
3264 for (i = 0; i < old_size; ++i) {
3265 if (old_handlers[i] == handler)
3266 break;
3267 if (old_handlers[i] == NULL)
3268 return; /* XXX panic? */
3269 }
3270
3271 if (i == old_size)
3272 return; /* XXX panic? */
3273
3274 for (; i < old_size - 1; ++i) {
3275 if ((old_handlers[i] = old_handlers[i + 1]) != NULL)
3276 continue;
3277
3278 if (i == 0) {
3279 s = splhigh();
3280 dev->dv_activity_count = 0;
3281 dev->dv_activity_handlers = NULL;
3282 splx(s);
3283 kmem_free(old_handlers, sizeof(void *) * old_size);
3284 }
3285 return;
3286 }
3287 old_handlers[i] = NULL;
3288 }
3289
3290 /* Return true iff the device_t `dev' exists at generation `gen'. */
3291 static bool
3292 device_exists_at(device_t dv, devgen_t gen)
3293 {
3294 return (dv->dv_del_gen == 0 || dv->dv_del_gen > gen) &&
3295 dv->dv_add_gen <= gen;
3296 }
3297
3298 static bool
3299 deviter_visits(const deviter_t *di, device_t dv)
3300 {
3301 return device_exists_at(dv, di->di_gen);
3302 }
3303
3304 /*
3305 * Device Iteration
3306 *
3307 * deviter_t: a device iterator. Holds state for a "walk" visiting
3308 * each device_t's in the device tree.
3309 *
3310 * deviter_init(di, flags): initialize the device iterator `di'
3311 * to "walk" the device tree. deviter_next(di) will return
3312 * the first device_t in the device tree, or NULL if there are
3313 * no devices.
3314 *
3315 * `flags' is one or more of DEVITER_F_RW, indicating that the
3316 * caller intends to modify the device tree by calling
3317 * config_detach(9) on devices in the order that the iterator
3318 * returns them; DEVITER_F_ROOT_FIRST, asking for the devices
3319 * nearest the "root" of the device tree to be returned, first;
3320 * DEVITER_F_LEAVES_FIRST, asking for the devices furthest from
3321 * the root of the device tree, first; and DEVITER_F_SHUTDOWN,
3322 * indicating both that deviter_init() should not respect any
3323 * locks on the device tree, and that deviter_next(di) may run
3324 * in more than one LWP before the walk has finished.
3325 *
3326 * Only one DEVITER_F_RW iterator may be in the device tree at
3327 * once.
3328 *
3329 * DEVITER_F_SHUTDOWN implies DEVITER_F_RW.
3330 *
3331 * Results are undefined if the flags DEVITER_F_ROOT_FIRST and
3332 * DEVITER_F_LEAVES_FIRST are used in combination.
3333 *
3334 * deviter_first(di, flags): initialize the device iterator `di'
3335 * and return the first device_t in the device tree, or NULL
3336 * if there are no devices. The statement
3337 *
3338 * dv = deviter_first(di);
3339 *
3340 * is shorthand for
3341 *
3342 * deviter_init(di);
3343 * dv = deviter_next(di);
3344 *
3345 * deviter_next(di): return the next device_t in the device tree,
3346 * or NULL if there are no more devices. deviter_next(di)
3347 * is undefined if `di' was not initialized with deviter_init() or
3348 * deviter_first().
3349 *
3350 * deviter_release(di): stops iteration (subsequent calls to
3351 * deviter_next() will return NULL), releases any locks and
3352 * resources held by the device iterator.
3353 *
3354 * Device iteration does not return device_t's in any particular
3355 * order. An iterator will never return the same device_t twice.
3356 * Device iteration is guaranteed to complete---i.e., if deviter_next(di)
3357 * is called repeatedly on the same `di', it will eventually return
3358 * NULL. It is ok to attach/detach devices during device iteration.
3359 */
3360 void
3361 deviter_init(deviter_t *di, deviter_flags_t flags)
3362 {
3363 device_t dv;
3364
3365 memset(di, 0, sizeof(*di));
3366
3367 if ((flags & DEVITER_F_SHUTDOWN) != 0)
3368 flags |= DEVITER_F_RW;
3369
3370 mutex_enter(&alldevs_lock);
3371 if ((flags & DEVITER_F_RW) != 0)
3372 alldevs_nwrite++;
3373 else
3374 alldevs_nread++;
3375 di->di_gen = alldevs_gen++;
3376 di->di_flags = flags;
3377
3378 switch (di->di_flags & (DEVITER_F_LEAVES_FIRST|DEVITER_F_ROOT_FIRST)) {
3379 case DEVITER_F_LEAVES_FIRST:
3380 TAILQ_FOREACH(dv, &alldevs, dv_list) {
3381 if (!deviter_visits(di, dv))
3382 continue;
3383 di->di_curdepth = MAX(di->di_curdepth, dv->dv_depth);
3384 }
3385 break;
3386 case DEVITER_F_ROOT_FIRST:
3387 TAILQ_FOREACH(dv, &alldevs, dv_list) {
3388 if (!deviter_visits(di, dv))
3389 continue;
3390 di->di_maxdepth = MAX(di->di_maxdepth, dv->dv_depth);
3391 }
3392 break;
3393 default:
3394 break;
3395 }
3396
3397 deviter_reinit(di);
3398 mutex_exit(&alldevs_lock);
3399 }
3400
3401 static void
3402 deviter_reinit(deviter_t *di)
3403 {
3404
3405 KASSERT(mutex_owned(&alldevs_lock));
3406 if ((di->di_flags & DEVITER_F_RW) != 0)
3407 di->di_prev = TAILQ_LAST(&alldevs, devicelist);
3408 else
3409 di->di_prev = TAILQ_FIRST(&alldevs);
3410 }
3411
3412 device_t
3413 deviter_first(deviter_t *di, deviter_flags_t flags)
3414 {
3415
3416 deviter_init(di, flags);
3417 return deviter_next(di);
3418 }
3419
3420 static device_t
3421 deviter_next2(deviter_t *di)
3422 {
3423 device_t dv;
3424
3425 KASSERT(mutex_owned(&alldevs_lock));
3426
3427 dv = di->di_prev;
3428
3429 if (dv == NULL)
3430 return NULL;
3431
3432 if ((di->di_flags & DEVITER_F_RW) != 0)
3433 di->di_prev = TAILQ_PREV(dv, devicelist, dv_list);
3434 else
3435 di->di_prev = TAILQ_NEXT(dv, dv_list);
3436
3437 return dv;
3438 }
3439
3440 static device_t
3441 deviter_next1(deviter_t *di)
3442 {
3443 device_t dv;
3444
3445 KASSERT(mutex_owned(&alldevs_lock));
3446
3447 do {
3448 dv = deviter_next2(di);
3449 } while (dv != NULL && !deviter_visits(di, dv));
3450
3451 return dv;
3452 }
3453
3454 device_t
3455 deviter_next(deviter_t *di)
3456 {
3457 device_t dv = NULL;
3458
3459 mutex_enter(&alldevs_lock);
3460 switch (di->di_flags & (DEVITER_F_LEAVES_FIRST|DEVITER_F_ROOT_FIRST)) {
3461 case 0:
3462 dv = deviter_next1(di);
3463 break;
3464 case DEVITER_F_LEAVES_FIRST:
3465 while (di->di_curdepth >= 0) {
3466 if ((dv = deviter_next1(di)) == NULL) {
3467 di->di_curdepth--;
3468 deviter_reinit(di);
3469 } else if (dv->dv_depth == di->di_curdepth)
3470 break;
3471 }
3472 break;
3473 case DEVITER_F_ROOT_FIRST:
3474 while (di->di_curdepth <= di->di_maxdepth) {
3475 if ((dv = deviter_next1(di)) == NULL) {
3476 di->di_curdepth++;
3477 deviter_reinit(di);
3478 } else if (dv->dv_depth == di->di_curdepth)
3479 break;
3480 }
3481 break;
3482 default:
3483 break;
3484 }
3485 mutex_exit(&alldevs_lock);
3486
3487 return dv;
3488 }
3489
3490 void
3491 deviter_release(deviter_t *di)
3492 {
3493 bool rw = (di->di_flags & DEVITER_F_RW) != 0;
3494
3495 mutex_enter(&alldevs_lock);
3496 if (rw)
3497 --alldevs_nwrite;
3498 else
3499 --alldevs_nread;
3500 /* XXX wake a garbage-collection thread */
3501 mutex_exit(&alldevs_lock);
3502 }
3503
3504 const char *
3505 cfdata_ifattr(const struct cfdata *cf)
3506 {
3507 return cf->cf_pspec->cfp_iattr;
3508 }
3509
3510 bool
3511 ifattr_match(const char *snull, const char *t)
3512 {
3513 return (snull == NULL) || strcmp(snull, t) == 0;
3514 }
3515
3516 void
3517 null_childdetached(device_t self, device_t child)
3518 {
3519 /* do nothing */
3520 }
3521
3522 static void
3523 sysctl_detach_setup(struct sysctllog **clog)
3524 {
3525
3526 sysctl_createv(clog, 0, NULL, NULL,
3527 CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
3528 CTLTYPE_BOOL, "detachall",
3529 SYSCTL_DESCR("Detach all devices at shutdown"),
3530 NULL, 0, &detachall, 0,
3531 CTL_KERN, CTL_CREATE, CTL_EOL);
3532 }
3533