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