subr_autoconf.c revision 1.278.2.1 1 /* $NetBSD: subr_autoconf.c,v 1.278.2.1 2021/05/13 00:47:32 thorpej 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.278.2.1 2021/05/13 00:47:32 thorpej 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
1289 if ((cf = config_rootsearch(NULL, rootname, aux)) != NULL)
1290 return config_attach(ROOT, cf, aux, NULL, CFARG_EOL);
1291 aprint_error("root device %s not configured\n", rootname);
1292 return NULL;
1293 }
1294
1295 /* just like sprintf(buf, "%d") except that it works from the end */
1296 static char *
1297 number(char *ep, int n)
1298 {
1299
1300 *--ep = 0;
1301 while (n >= 10) {
1302 *--ep = (n % 10) + '0';
1303 n /= 10;
1304 }
1305 *--ep = n + '0';
1306 return ep;
1307 }
1308
1309 /*
1310 * Expand the size of the cd_devs array if necessary.
1311 *
1312 * The caller must hold alldevs_lock. config_makeroom() may release and
1313 * re-acquire alldevs_lock, so callers should re-check conditions such
1314 * as alldevs_nwrite == 0 and alldevs_nread == 0 when config_makeroom()
1315 * returns.
1316 */
1317 static void
1318 config_makeroom(int n, struct cfdriver *cd)
1319 {
1320 int ondevs, nndevs;
1321 device_t *osp, *nsp;
1322
1323 KASSERT(mutex_owned(&alldevs_lock));
1324 alldevs_nwrite++;
1325
1326 for (nndevs = MAX(4, cd->cd_ndevs); nndevs <= n; nndevs += nndevs)
1327 ;
1328
1329 while (n >= cd->cd_ndevs) {
1330 /*
1331 * Need to expand the array.
1332 */
1333 ondevs = cd->cd_ndevs;
1334 osp = cd->cd_devs;
1335
1336 /*
1337 * Release alldevs_lock around allocation, which may
1338 * sleep.
1339 */
1340 mutex_exit(&alldevs_lock);
1341 nsp = kmem_alloc(sizeof(device_t) * nndevs, KM_SLEEP);
1342 mutex_enter(&alldevs_lock);
1343
1344 /*
1345 * If another thread moved the array while we did
1346 * not hold alldevs_lock, try again.
1347 */
1348 if (cd->cd_devs != osp) {
1349 mutex_exit(&alldevs_lock);
1350 kmem_free(nsp, sizeof(device_t) * nndevs);
1351 mutex_enter(&alldevs_lock);
1352 continue;
1353 }
1354
1355 memset(nsp + ondevs, 0, sizeof(device_t) * (nndevs - ondevs));
1356 if (ondevs != 0)
1357 memcpy(nsp, cd->cd_devs, sizeof(device_t) * ondevs);
1358
1359 cd->cd_ndevs = nndevs;
1360 cd->cd_devs = nsp;
1361 if (ondevs != 0) {
1362 mutex_exit(&alldevs_lock);
1363 kmem_free(osp, sizeof(device_t) * ondevs);
1364 mutex_enter(&alldevs_lock);
1365 }
1366 }
1367 KASSERT(mutex_owned(&alldevs_lock));
1368 alldevs_nwrite--;
1369 }
1370
1371 /*
1372 * Put dev into the devices list.
1373 */
1374 static void
1375 config_devlink(device_t dev)
1376 {
1377
1378 mutex_enter(&alldevs_lock);
1379
1380 KASSERT(device_cfdriver(dev)->cd_devs[dev->dv_unit] == dev);
1381
1382 dev->dv_add_gen = alldevs_gen;
1383 /* It is safe to add a device to the tail of the list while
1384 * readers and writers are in the list.
1385 */
1386 TAILQ_INSERT_TAIL(&alldevs, dev, dv_list);
1387 mutex_exit(&alldevs_lock);
1388 }
1389
1390 static void
1391 config_devfree(device_t dev)
1392 {
1393 KASSERT(dev->dv_flags & DVF_PRIV_ALLOC);
1394
1395 if (dev->dv_cfattach->ca_devsize > 0)
1396 kmem_free(dev->dv_private, dev->dv_cfattach->ca_devsize);
1397 kmem_free(dev, sizeof(*dev));
1398 }
1399
1400 /*
1401 * Caller must hold alldevs_lock.
1402 */
1403 static void
1404 config_devunlink(device_t dev, struct devicelist *garbage)
1405 {
1406 struct device_garbage *dg = &dev->dv_garbage;
1407 cfdriver_t cd = device_cfdriver(dev);
1408 int i;
1409
1410 KASSERT(mutex_owned(&alldevs_lock));
1411
1412 /* Unlink from device list. Link to garbage list. */
1413 TAILQ_REMOVE(&alldevs, dev, dv_list);
1414 TAILQ_INSERT_TAIL(garbage, dev, dv_list);
1415
1416 /* Remove from cfdriver's array. */
1417 cd->cd_devs[dev->dv_unit] = NULL;
1418
1419 /*
1420 * If the device now has no units in use, unlink its softc array.
1421 */
1422 for (i = 0; i < cd->cd_ndevs; i++) {
1423 if (cd->cd_devs[i] != NULL)
1424 break;
1425 }
1426 /* Nothing found. Unlink, now. Deallocate, later. */
1427 if (i == cd->cd_ndevs) {
1428 dg->dg_ndevs = cd->cd_ndevs;
1429 dg->dg_devs = cd->cd_devs;
1430 cd->cd_devs = NULL;
1431 cd->cd_ndevs = 0;
1432 }
1433 }
1434
1435 static void
1436 config_devdelete(device_t dev)
1437 {
1438 struct device_garbage *dg = &dev->dv_garbage;
1439 device_lock_t dvl = device_getlock(dev);
1440
1441 if (dg->dg_devs != NULL)
1442 kmem_free(dg->dg_devs, sizeof(device_t) * dg->dg_ndevs);
1443
1444 cv_destroy(&dvl->dvl_cv);
1445 mutex_destroy(&dvl->dvl_mtx);
1446
1447 KASSERT(dev->dv_properties != NULL);
1448 prop_object_release(dev->dv_properties);
1449
1450 if (dev->dv_activity_handlers)
1451 panic("%s with registered handlers", __func__);
1452
1453 if (dev->dv_locators) {
1454 size_t amount = *--dev->dv_locators;
1455 kmem_free(dev->dv_locators, amount);
1456 }
1457
1458 config_devfree(dev);
1459 }
1460
1461 static int
1462 config_unit_nextfree(cfdriver_t cd, cfdata_t cf)
1463 {
1464 int unit;
1465
1466 if (cf->cf_fstate == FSTATE_STAR) {
1467 for (unit = cf->cf_unit; unit < cd->cd_ndevs; unit++)
1468 if (cd->cd_devs[unit] == NULL)
1469 break;
1470 /*
1471 * unit is now the unit of the first NULL device pointer,
1472 * or max(cd->cd_ndevs,cf->cf_unit).
1473 */
1474 } else {
1475 unit = cf->cf_unit;
1476 if (unit < cd->cd_ndevs && cd->cd_devs[unit] != NULL)
1477 unit = -1;
1478 }
1479 return unit;
1480 }
1481
1482 static int
1483 config_unit_alloc(device_t dev, cfdriver_t cd, cfdata_t cf)
1484 {
1485 struct alldevs_foray af;
1486 int unit;
1487
1488 config_alldevs_enter(&af);
1489 for (;;) {
1490 unit = config_unit_nextfree(cd, cf);
1491 if (unit == -1)
1492 break;
1493 if (unit < cd->cd_ndevs) {
1494 cd->cd_devs[unit] = dev;
1495 dev->dv_unit = unit;
1496 break;
1497 }
1498 config_makeroom(unit, cd);
1499 }
1500 config_alldevs_exit(&af);
1501
1502 return unit;
1503 }
1504
1505 static device_t
1506 config_vdevalloc(const device_t parent, const cfdata_t cf, cfarg_t tag,
1507 va_list ap)
1508 {
1509 cfdriver_t cd;
1510 cfattach_t ca;
1511 size_t lname, lunit;
1512 const char *xunit;
1513 int myunit;
1514 char num[10];
1515 device_t dev;
1516 void *dev_private;
1517 const struct cfiattrdata *ia;
1518 device_lock_t dvl;
1519 const int *locs;
1520
1521 cd = config_cfdriver_lookup(cf->cf_name);
1522 if (cd == NULL)
1523 return NULL;
1524
1525 ca = config_cfattach_lookup_cd(cd, cf->cf_atname);
1526 if (ca == NULL)
1527 return NULL;
1528
1529 /* get memory for all device vars */
1530 KASSERT(ca->ca_flags & DVF_PRIV_ALLOC);
1531 if (ca->ca_devsize > 0) {
1532 dev_private = kmem_zalloc(ca->ca_devsize, KM_SLEEP);
1533 } else {
1534 dev_private = NULL;
1535 }
1536 dev = kmem_zalloc(sizeof(*dev), KM_SLEEP);
1537
1538 /*
1539 * If a handle was supplied to config_attach(), we'll get it
1540 * assigned automatically here. If not, then we'll get the
1541 * default invalid handle.
1542 */
1543 config_get_cfargs(tag, NULL, NULL, &locs, &dev->dv_handle, ap);
1544
1545 dev->dv_class = cd->cd_class;
1546 dev->dv_cfdata = cf;
1547 dev->dv_cfdriver = cd;
1548 dev->dv_cfattach = ca;
1549 dev->dv_activity_count = 0;
1550 dev->dv_activity_handlers = NULL;
1551 dev->dv_private = dev_private;
1552 dev->dv_flags = ca->ca_flags; /* inherit flags from class */
1553
1554 myunit = config_unit_alloc(dev, cd, cf);
1555 if (myunit == -1) {
1556 config_devfree(dev);
1557 return NULL;
1558 }
1559
1560 /* compute length of name and decimal expansion of unit number */
1561 lname = strlen(cd->cd_name);
1562 xunit = number(&num[sizeof(num)], myunit);
1563 lunit = &num[sizeof(num)] - xunit;
1564 if (lname + lunit > sizeof(dev->dv_xname))
1565 panic("config_vdevalloc: device name too long");
1566
1567 dvl = device_getlock(dev);
1568
1569 mutex_init(&dvl->dvl_mtx, MUTEX_DEFAULT, IPL_NONE);
1570 cv_init(&dvl->dvl_cv, "pmfsusp");
1571
1572 memcpy(dev->dv_xname, cd->cd_name, lname);
1573 memcpy(dev->dv_xname + lname, xunit, lunit);
1574 dev->dv_parent = parent;
1575 if (parent != NULL)
1576 dev->dv_depth = parent->dv_depth + 1;
1577 else
1578 dev->dv_depth = 0;
1579 dev->dv_flags |= DVF_ACTIVE; /* always initially active */
1580 if (locs) {
1581 KASSERT(parent); /* no locators at root */
1582 ia = cfiattr_lookup(cfdata_ifattr(cf), parent->dv_cfdriver);
1583 dev->dv_locators =
1584 kmem_alloc(sizeof(int) * (ia->ci_loclen + 1), KM_SLEEP);
1585 *dev->dv_locators++ = sizeof(int) * (ia->ci_loclen + 1);
1586 memcpy(dev->dv_locators, locs, sizeof(int) * ia->ci_loclen);
1587 }
1588 dev->dv_properties = prop_dictionary_create();
1589 KASSERT(dev->dv_properties != NULL);
1590
1591 prop_dictionary_set_string_nocopy(dev->dv_properties,
1592 "device-driver", dev->dv_cfdriver->cd_name);
1593 prop_dictionary_set_uint16(dev->dv_properties,
1594 "device-unit", dev->dv_unit);
1595 if (parent != NULL) {
1596 prop_dictionary_set_string(dev->dv_properties,
1597 "device-parent", device_xname(parent));
1598 }
1599
1600 if (dev->dv_cfdriver->cd_attrs != NULL)
1601 config_add_attrib_dict(dev);
1602
1603 return dev;
1604 }
1605
1606 static device_t
1607 config_devalloc(const device_t parent, const cfdata_t cf, cfarg_t tag, ...)
1608 {
1609 device_t dev;
1610 va_list ap;
1611
1612 va_start(ap, tag);
1613 dev = config_vdevalloc(parent, cf, tag, ap);
1614 va_end(ap);
1615
1616 return dev;
1617 }
1618
1619 /*
1620 * Create an array of device attach attributes and add it
1621 * to the device's dv_properties dictionary.
1622 *
1623 * <key>interface-attributes</key>
1624 * <array>
1625 * <dict>
1626 * <key>attribute-name</key>
1627 * <string>foo</string>
1628 * <key>locators</key>
1629 * <array>
1630 * <dict>
1631 * <key>loc-name</key>
1632 * <string>foo-loc1</string>
1633 * </dict>
1634 * <dict>
1635 * <key>loc-name</key>
1636 * <string>foo-loc2</string>
1637 * <key>default</key>
1638 * <string>foo-loc2-default</string>
1639 * </dict>
1640 * ...
1641 * </array>
1642 * </dict>
1643 * ...
1644 * </array>
1645 */
1646
1647 static void
1648 config_add_attrib_dict(device_t dev)
1649 {
1650 int i, j;
1651 const struct cfiattrdata *ci;
1652 prop_dictionary_t attr_dict, loc_dict;
1653 prop_array_t attr_array, loc_array;
1654
1655 if ((attr_array = prop_array_create()) == NULL)
1656 return;
1657
1658 for (i = 0; ; i++) {
1659 if ((ci = dev->dv_cfdriver->cd_attrs[i]) == NULL)
1660 break;
1661 if ((attr_dict = prop_dictionary_create()) == NULL)
1662 break;
1663 prop_dictionary_set_string_nocopy(attr_dict, "attribute-name",
1664 ci->ci_name);
1665
1666 /* Create an array of the locator names and defaults */
1667
1668 if (ci->ci_loclen != 0 &&
1669 (loc_array = prop_array_create()) != NULL) {
1670 for (j = 0; j < ci->ci_loclen; j++) {
1671 loc_dict = prop_dictionary_create();
1672 if (loc_dict == NULL)
1673 continue;
1674 prop_dictionary_set_string_nocopy(loc_dict,
1675 "loc-name", ci->ci_locdesc[j].cld_name);
1676 if (ci->ci_locdesc[j].cld_defaultstr != NULL)
1677 prop_dictionary_set_string_nocopy(
1678 loc_dict, "default",
1679 ci->ci_locdesc[j].cld_defaultstr);
1680 prop_array_set(loc_array, j, loc_dict);
1681 prop_object_release(loc_dict);
1682 }
1683 prop_dictionary_set_and_rel(attr_dict, "locators",
1684 loc_array);
1685 }
1686 prop_array_add(attr_array, attr_dict);
1687 prop_object_release(attr_dict);
1688 }
1689 if (i == 0)
1690 prop_object_release(attr_array);
1691 else
1692 prop_dictionary_set_and_rel(dev->dv_properties,
1693 "interface-attributes", attr_array);
1694
1695 return;
1696 }
1697
1698 /*
1699 * Attach a found device.
1700 */
1701 device_t
1702 config_vattach(device_t parent, cfdata_t cf, void *aux, cfprint_t print,
1703 cfarg_t tag, va_list ap)
1704 {
1705 device_t dev;
1706 struct cftable *ct;
1707 const char *drvname;
1708
1709 dev = config_vdevalloc(parent, cf, tag, ap);
1710 if (!dev)
1711 panic("config_attach: allocation of device softc failed");
1712
1713 /* XXX redundant - see below? */
1714 if (cf->cf_fstate != FSTATE_STAR) {
1715 KASSERT(cf->cf_fstate == FSTATE_NOTFOUND);
1716 cf->cf_fstate = FSTATE_FOUND;
1717 }
1718
1719 config_devlink(dev);
1720
1721 if (config_do_twiddle && cold)
1722 twiddle();
1723 else
1724 aprint_naive("Found ");
1725 /*
1726 * We want the next two printfs for normal, verbose, and quiet,
1727 * but not silent (in which case, we're twiddling, instead).
1728 */
1729 if (parent == ROOT) {
1730 aprint_naive("%s (root)", device_xname(dev));
1731 aprint_normal("%s (root)", device_xname(dev));
1732 } else {
1733 aprint_naive("%s at %s", device_xname(dev),
1734 device_xname(parent));
1735 aprint_normal("%s at %s", device_xname(dev),
1736 device_xname(parent));
1737 if (print)
1738 (void) (*print)(aux, NULL);
1739 }
1740
1741 /*
1742 * Before attaching, clobber any unfound devices that are
1743 * otherwise identical.
1744 * XXX code above is redundant?
1745 */
1746 drvname = dev->dv_cfdriver->cd_name;
1747 TAILQ_FOREACH(ct, &allcftables, ct_list) {
1748 for (cf = ct->ct_cfdata; cf->cf_name; cf++) {
1749 if (STREQ(cf->cf_name, drvname) &&
1750 cf->cf_unit == dev->dv_unit) {
1751 if (cf->cf_fstate == FSTATE_NOTFOUND)
1752 cf->cf_fstate = FSTATE_FOUND;
1753 }
1754 }
1755 }
1756 device_register(dev, aux);
1757
1758 /* Let userland know */
1759 devmon_report_device(dev, true);
1760
1761 (*dev->dv_cfattach->ca_attach)(parent, dev, aux);
1762
1763 if (((dev->dv_flags & DVF_ATTACH_INPROGRESS) == 0)
1764 && !device_pmf_is_registered(dev))
1765 aprint_debug_dev(dev,
1766 "WARNING: power management not supported\n");
1767
1768 config_process_deferred(&deferred_config_queue, dev);
1769
1770 device_register_post_config(dev, aux);
1771 return dev;
1772 }
1773
1774 device_t
1775 config_attach(device_t parent, cfdata_t cf, void *aux, cfprint_t print,
1776 cfarg_t tag, ...)
1777 {
1778 device_t dev;
1779 va_list ap;
1780
1781 va_start(ap, tag);
1782 dev = config_vattach(parent, cf, aux, print, tag, ap);
1783 va_end(ap);
1784
1785 return dev;
1786 }
1787
1788 /*
1789 * As above, but for pseudo-devices. Pseudo-devices attached in this
1790 * way are silently inserted into the device tree, and their children
1791 * attached.
1792 *
1793 * Note that because pseudo-devices are attached silently, any information
1794 * the attach routine wishes to print should be prefixed with the device
1795 * name by the attach routine.
1796 */
1797 device_t
1798 config_attach_pseudo(cfdata_t cf)
1799 {
1800 device_t dev;
1801
1802 dev = config_devalloc(ROOT, cf, CFARG_EOL);
1803 if (!dev)
1804 return NULL;
1805
1806 /* XXX mark busy in cfdata */
1807
1808 if (cf->cf_fstate != FSTATE_STAR) {
1809 KASSERT(cf->cf_fstate == FSTATE_NOTFOUND);
1810 cf->cf_fstate = FSTATE_FOUND;
1811 }
1812
1813 config_devlink(dev);
1814
1815 #if 0 /* XXXJRT not yet */
1816 device_register(dev, NULL); /* like a root node */
1817 #endif
1818
1819 /* Let userland know */
1820 devmon_report_device(dev, true);
1821
1822 (*dev->dv_cfattach->ca_attach)(ROOT, dev, NULL);
1823
1824 config_process_deferred(&deferred_config_queue, dev);
1825 return dev;
1826 }
1827
1828 /*
1829 * Caller must hold alldevs_lock.
1830 */
1831 static void
1832 config_collect_garbage(struct devicelist *garbage)
1833 {
1834 device_t dv;
1835
1836 KASSERT(!cpu_intr_p());
1837 KASSERT(!cpu_softintr_p());
1838 KASSERT(mutex_owned(&alldevs_lock));
1839
1840 while (alldevs_nwrite == 0 && alldevs_nread == 0 && alldevs_garbage) {
1841 TAILQ_FOREACH(dv, &alldevs, dv_list) {
1842 if (dv->dv_del_gen != 0)
1843 break;
1844 }
1845 if (dv == NULL) {
1846 alldevs_garbage = false;
1847 break;
1848 }
1849 config_devunlink(dv, garbage);
1850 }
1851 KASSERT(mutex_owned(&alldevs_lock));
1852 }
1853
1854 static void
1855 config_dump_garbage(struct devicelist *garbage)
1856 {
1857 device_t dv;
1858
1859 while ((dv = TAILQ_FIRST(garbage)) != NULL) {
1860 TAILQ_REMOVE(garbage, dv, dv_list);
1861 config_devdelete(dv);
1862 }
1863 }
1864
1865 /*
1866 * Detach a device. Optionally forced (e.g. because of hardware
1867 * removal) and quiet. Returns zero if successful, non-zero
1868 * (an error code) otherwise.
1869 *
1870 * Note that this code wants to be run from a process context, so
1871 * that the detach can sleep to allow processes which have a device
1872 * open to run and unwind their stacks.
1873 */
1874 int
1875 config_detach(device_t dev, int flags)
1876 {
1877 struct alldevs_foray af;
1878 struct cftable *ct;
1879 cfdata_t cf;
1880 const struct cfattach *ca;
1881 struct cfdriver *cd;
1882 device_t d __diagused;
1883 int rv = 0;
1884
1885 cf = dev->dv_cfdata;
1886 KASSERTMSG((cf == NULL || cf->cf_fstate == FSTATE_FOUND ||
1887 cf->cf_fstate == FSTATE_STAR),
1888 "config_detach: %s: bad device fstate: %d",
1889 device_xname(dev), cf ? cf->cf_fstate : -1);
1890
1891 cd = dev->dv_cfdriver;
1892 KASSERT(cd != NULL);
1893
1894 ca = dev->dv_cfattach;
1895 KASSERT(ca != NULL);
1896
1897 mutex_enter(&alldevs_lock);
1898 if (dev->dv_del_gen != 0) {
1899 mutex_exit(&alldevs_lock);
1900 #ifdef DIAGNOSTIC
1901 printf("%s: %s is already detached\n", __func__,
1902 device_xname(dev));
1903 #endif /* DIAGNOSTIC */
1904 return ENOENT;
1905 }
1906 alldevs_nwrite++;
1907 mutex_exit(&alldevs_lock);
1908
1909 if (!detachall &&
1910 (flags & (DETACH_SHUTDOWN|DETACH_FORCE)) == DETACH_SHUTDOWN &&
1911 (dev->dv_flags & DVF_DETACH_SHUTDOWN) == 0) {
1912 rv = EOPNOTSUPP;
1913 } else if (ca->ca_detach != NULL) {
1914 rv = (*ca->ca_detach)(dev, flags);
1915 } else
1916 rv = EOPNOTSUPP;
1917
1918 /*
1919 * If it was not possible to detach the device, then we either
1920 * panic() (for the forced but failed case), or return an error.
1921 *
1922 * If it was possible to detach the device, ensure that the
1923 * device is deactivated.
1924 */
1925 if (rv == 0)
1926 dev->dv_flags &= ~DVF_ACTIVE;
1927 else if ((flags & DETACH_FORCE) == 0)
1928 goto out;
1929 else {
1930 panic("config_detach: forced detach of %s failed (%d)",
1931 device_xname(dev), rv);
1932 }
1933
1934 /*
1935 * The device has now been successfully detached.
1936 */
1937
1938 /* Let userland know */
1939 devmon_report_device(dev, false);
1940
1941 #ifdef DIAGNOSTIC
1942 /*
1943 * Sanity: If you're successfully detached, you should have no
1944 * children. (Note that because children must be attached
1945 * after parents, we only need to search the latter part of
1946 * the list.)
1947 */
1948 for (d = TAILQ_NEXT(dev, dv_list); d != NULL;
1949 d = TAILQ_NEXT(d, dv_list)) {
1950 if (d->dv_parent == dev && d->dv_del_gen == 0) {
1951 printf("config_detach: detached device %s"
1952 " has children %s\n", device_xname(dev),
1953 device_xname(d));
1954 panic("config_detach");
1955 }
1956 }
1957 #endif
1958
1959 /* notify the parent that the child is gone */
1960 if (dev->dv_parent) {
1961 device_t p = dev->dv_parent;
1962 if (p->dv_cfattach->ca_childdetached)
1963 (*p->dv_cfattach->ca_childdetached)(p, dev);
1964 }
1965
1966 /*
1967 * Mark cfdata to show that the unit can be reused, if possible.
1968 */
1969 TAILQ_FOREACH(ct, &allcftables, ct_list) {
1970 for (cf = ct->ct_cfdata; cf->cf_name; cf++) {
1971 if (STREQ(cf->cf_name, cd->cd_name)) {
1972 if (cf->cf_fstate == FSTATE_FOUND &&
1973 cf->cf_unit == dev->dv_unit)
1974 cf->cf_fstate = FSTATE_NOTFOUND;
1975 }
1976 }
1977 }
1978
1979 if (dev->dv_cfdata != NULL && (flags & DETACH_QUIET) == 0)
1980 aprint_normal_dev(dev, "detached\n");
1981
1982 out:
1983 config_alldevs_enter(&af);
1984 KASSERT(alldevs_nwrite != 0);
1985 --alldevs_nwrite;
1986 if (rv == 0 && dev->dv_del_gen == 0) {
1987 if (alldevs_nwrite == 0 && alldevs_nread == 0)
1988 config_devunlink(dev, &af.af_garbage);
1989 else {
1990 dev->dv_del_gen = alldevs_gen;
1991 alldevs_garbage = true;
1992 }
1993 }
1994 config_alldevs_exit(&af);
1995
1996 return rv;
1997 }
1998
1999 int
2000 config_detach_children(device_t parent, int flags)
2001 {
2002 device_t dv;
2003 deviter_t di;
2004 int error = 0;
2005
2006 for (dv = deviter_first(&di, DEVITER_F_RW); dv != NULL;
2007 dv = deviter_next(&di)) {
2008 if (device_parent(dv) != parent)
2009 continue;
2010 if ((error = config_detach(dv, flags)) != 0)
2011 break;
2012 }
2013 deviter_release(&di);
2014 return error;
2015 }
2016
2017 device_t
2018 shutdown_first(struct shutdown_state *s)
2019 {
2020 if (!s->initialized) {
2021 deviter_init(&s->di, DEVITER_F_SHUTDOWN|DEVITER_F_LEAVES_FIRST);
2022 s->initialized = true;
2023 }
2024 return shutdown_next(s);
2025 }
2026
2027 device_t
2028 shutdown_next(struct shutdown_state *s)
2029 {
2030 device_t dv;
2031
2032 while ((dv = deviter_next(&s->di)) != NULL && !device_is_active(dv))
2033 ;
2034
2035 if (dv == NULL)
2036 s->initialized = false;
2037
2038 return dv;
2039 }
2040
2041 bool
2042 config_detach_all(int how)
2043 {
2044 static struct shutdown_state s;
2045 device_t curdev;
2046 bool progress = false;
2047 int flags;
2048
2049 if ((how & (RB_NOSYNC|RB_DUMP)) != 0)
2050 return false;
2051
2052 if ((how & RB_POWERDOWN) == RB_POWERDOWN)
2053 flags = DETACH_SHUTDOWN | DETACH_POWEROFF;
2054 else
2055 flags = DETACH_SHUTDOWN;
2056
2057 for (curdev = shutdown_first(&s); curdev != NULL;
2058 curdev = shutdown_next(&s)) {
2059 aprint_debug(" detaching %s, ", device_xname(curdev));
2060 if (config_detach(curdev, flags) == 0) {
2061 progress = true;
2062 aprint_debug("success.");
2063 } else
2064 aprint_debug("failed.");
2065 }
2066 return progress;
2067 }
2068
2069 static bool
2070 device_is_ancestor_of(device_t ancestor, device_t descendant)
2071 {
2072 device_t dv;
2073
2074 for (dv = descendant; dv != NULL; dv = device_parent(dv)) {
2075 if (device_parent(dv) == ancestor)
2076 return true;
2077 }
2078 return false;
2079 }
2080
2081 int
2082 config_deactivate(device_t dev)
2083 {
2084 deviter_t di;
2085 const struct cfattach *ca;
2086 device_t descendant;
2087 int s, rv = 0, oflags;
2088
2089 for (descendant = deviter_first(&di, DEVITER_F_ROOT_FIRST);
2090 descendant != NULL;
2091 descendant = deviter_next(&di)) {
2092 if (dev != descendant &&
2093 !device_is_ancestor_of(dev, descendant))
2094 continue;
2095
2096 if ((descendant->dv_flags & DVF_ACTIVE) == 0)
2097 continue;
2098
2099 ca = descendant->dv_cfattach;
2100 oflags = descendant->dv_flags;
2101
2102 descendant->dv_flags &= ~DVF_ACTIVE;
2103 if (ca->ca_activate == NULL)
2104 continue;
2105 s = splhigh();
2106 rv = (*ca->ca_activate)(descendant, DVACT_DEACTIVATE);
2107 splx(s);
2108 if (rv != 0)
2109 descendant->dv_flags = oflags;
2110 }
2111 deviter_release(&di);
2112 return rv;
2113 }
2114
2115 /*
2116 * Defer the configuration of the specified device until all
2117 * of its parent's devices have been attached.
2118 */
2119 void
2120 config_defer(device_t dev, void (*func)(device_t))
2121 {
2122 struct deferred_config *dc;
2123
2124 if (dev->dv_parent == NULL)
2125 panic("config_defer: can't defer config of a root device");
2126
2127 dc = kmem_alloc(sizeof(*dc), KM_SLEEP);
2128
2129 config_pending_incr(dev);
2130
2131 mutex_enter(&config_misc_lock);
2132 #ifdef DIAGNOSTIC
2133 struct deferred_config *odc;
2134 TAILQ_FOREACH(odc, &deferred_config_queue, dc_queue) {
2135 if (odc->dc_dev == dev)
2136 panic("config_defer: deferred twice");
2137 }
2138 #endif
2139 dc->dc_dev = dev;
2140 dc->dc_func = func;
2141 TAILQ_INSERT_TAIL(&deferred_config_queue, dc, dc_queue);
2142 mutex_exit(&config_misc_lock);
2143 }
2144
2145 /*
2146 * Defer some autoconfiguration for a device until after interrupts
2147 * are enabled.
2148 */
2149 void
2150 config_interrupts(device_t dev, void (*func)(device_t))
2151 {
2152 struct deferred_config *dc;
2153
2154 /*
2155 * If interrupts are enabled, callback now.
2156 */
2157 if (cold == 0) {
2158 (*func)(dev);
2159 return;
2160 }
2161
2162 dc = kmem_alloc(sizeof(*dc), KM_SLEEP);
2163
2164 config_pending_incr(dev);
2165
2166 mutex_enter(&config_misc_lock);
2167 #ifdef DIAGNOSTIC
2168 struct deferred_config *odc;
2169 TAILQ_FOREACH(odc, &interrupt_config_queue, dc_queue) {
2170 if (odc->dc_dev == dev)
2171 panic("config_interrupts: deferred twice");
2172 }
2173 #endif
2174 dc->dc_dev = dev;
2175 dc->dc_func = func;
2176 TAILQ_INSERT_TAIL(&interrupt_config_queue, dc, dc_queue);
2177 dev->dv_flags |= DVF_ATTACH_INPROGRESS;
2178 mutex_exit(&config_misc_lock);
2179 }
2180
2181 /*
2182 * Defer some autoconfiguration for a device until after root file system
2183 * is mounted (to load firmware etc).
2184 */
2185 void
2186 config_mountroot(device_t dev, void (*func)(device_t))
2187 {
2188 struct deferred_config *dc;
2189
2190 /*
2191 * If root file system is mounted, callback now.
2192 */
2193 if (root_is_mounted) {
2194 (*func)(dev);
2195 return;
2196 }
2197
2198 dc = kmem_alloc(sizeof(*dc), KM_SLEEP);
2199
2200 mutex_enter(&config_misc_lock);
2201 #ifdef DIAGNOSTIC
2202 struct deferred_config *odc;
2203 TAILQ_FOREACH(odc, &mountroot_config_queue, dc_queue) {
2204 if (odc->dc_dev == dev)
2205 panic("%s: deferred twice", __func__);
2206 }
2207 #endif
2208
2209 dc->dc_dev = dev;
2210 dc->dc_func = func;
2211 TAILQ_INSERT_TAIL(&mountroot_config_queue, dc, dc_queue);
2212 mutex_exit(&config_misc_lock);
2213 }
2214
2215 /*
2216 * Process a deferred configuration queue.
2217 */
2218 static void
2219 config_process_deferred(struct deferred_config_head *queue, device_t parent)
2220 {
2221 struct deferred_config *dc;
2222
2223 mutex_enter(&config_misc_lock);
2224 dc = TAILQ_FIRST(queue);
2225 while (dc) {
2226 if (parent == NULL || dc->dc_dev->dv_parent == parent) {
2227 TAILQ_REMOVE(queue, dc, dc_queue);
2228 mutex_exit(&config_misc_lock);
2229
2230 (*dc->dc_func)(dc->dc_dev);
2231 config_pending_decr(dc->dc_dev);
2232 kmem_free(dc, sizeof(*dc));
2233
2234 mutex_enter(&config_misc_lock);
2235 /* Restart, queue might have changed */
2236 dc = TAILQ_FIRST(queue);
2237 } else {
2238 dc = TAILQ_NEXT(dc, dc_queue);
2239 }
2240 }
2241 mutex_exit(&config_misc_lock);
2242 }
2243
2244 /*
2245 * Manipulate the config_pending semaphore.
2246 */
2247 void
2248 config_pending_incr(device_t dev)
2249 {
2250
2251 mutex_enter(&config_misc_lock);
2252 KASSERTMSG(dev->dv_pending < INT_MAX,
2253 "%s: excess config_pending_incr", device_xname(dev));
2254 if (dev->dv_pending++ == 0)
2255 TAILQ_INSERT_TAIL(&config_pending, dev, dv_pending_list);
2256 #ifdef DEBUG_AUTOCONF
2257 printf("%s: %s %d\n", __func__, device_xname(dev), dev->dv_pending);
2258 #endif
2259 mutex_exit(&config_misc_lock);
2260 }
2261
2262 void
2263 config_pending_decr(device_t dev)
2264 {
2265
2266 mutex_enter(&config_misc_lock);
2267 KASSERTMSG(dev->dv_pending > 0,
2268 "%s: excess config_pending_decr", device_xname(dev));
2269 if (--dev->dv_pending == 0)
2270 TAILQ_REMOVE(&config_pending, dev, dv_pending_list);
2271 #ifdef DEBUG_AUTOCONF
2272 printf("%s: %s %d\n", __func__, device_xname(dev), dev->dv_pending);
2273 #endif
2274 if (TAILQ_EMPTY(&config_pending))
2275 cv_broadcast(&config_misc_cv);
2276 mutex_exit(&config_misc_lock);
2277 }
2278
2279 /*
2280 * Register a "finalization" routine. Finalization routines are
2281 * called iteratively once all real devices have been found during
2282 * autoconfiguration, for as long as any one finalizer has done
2283 * any work.
2284 */
2285 int
2286 config_finalize_register(device_t dev, int (*fn)(device_t))
2287 {
2288 struct finalize_hook *f;
2289
2290 /*
2291 * If finalization has already been done, invoke the
2292 * callback function now.
2293 */
2294 if (config_finalize_done) {
2295 while ((*fn)(dev) != 0)
2296 /* loop */ ;
2297 return 0;
2298 }
2299
2300 /* Ensure this isn't already on the list. */
2301 TAILQ_FOREACH(f, &config_finalize_list, f_list) {
2302 if (f->f_func == fn && f->f_dev == dev)
2303 return EEXIST;
2304 }
2305
2306 f = kmem_alloc(sizeof(*f), KM_SLEEP);
2307 f->f_func = fn;
2308 f->f_dev = dev;
2309 TAILQ_INSERT_TAIL(&config_finalize_list, f, f_list);
2310
2311 return 0;
2312 }
2313
2314 void
2315 config_finalize(void)
2316 {
2317 struct finalize_hook *f;
2318 struct pdevinit *pdev;
2319 extern struct pdevinit pdevinit[];
2320 int errcnt, rv;
2321
2322 /*
2323 * Now that device driver threads have been created, wait for
2324 * them to finish any deferred autoconfiguration.
2325 */
2326 mutex_enter(&config_misc_lock);
2327 while (!TAILQ_EMPTY(&config_pending)) {
2328 device_t dev;
2329 TAILQ_FOREACH(dev, &config_pending, dv_pending_list)
2330 aprint_debug_dev(dev, "holding up boot\n");
2331 cv_wait(&config_misc_cv, &config_misc_lock);
2332 }
2333 mutex_exit(&config_misc_lock);
2334
2335 KERNEL_LOCK(1, NULL);
2336
2337 /* Attach pseudo-devices. */
2338 for (pdev = pdevinit; pdev->pdev_attach != NULL; pdev++)
2339 (*pdev->pdev_attach)(pdev->pdev_count);
2340
2341 /* Run the hooks until none of them does any work. */
2342 do {
2343 rv = 0;
2344 TAILQ_FOREACH(f, &config_finalize_list, f_list)
2345 rv |= (*f->f_func)(f->f_dev);
2346 } while (rv != 0);
2347
2348 config_finalize_done = 1;
2349
2350 /* Now free all the hooks. */
2351 while ((f = TAILQ_FIRST(&config_finalize_list)) != NULL) {
2352 TAILQ_REMOVE(&config_finalize_list, f, f_list);
2353 kmem_free(f, sizeof(*f));
2354 }
2355
2356 KERNEL_UNLOCK_ONE(NULL);
2357
2358 errcnt = aprint_get_error_count();
2359 if ((boothowto & (AB_QUIET|AB_SILENT)) != 0 &&
2360 (boothowto & AB_VERBOSE) == 0) {
2361 mutex_enter(&config_misc_lock);
2362 if (config_do_twiddle) {
2363 config_do_twiddle = 0;
2364 printf_nolog(" done.\n");
2365 }
2366 mutex_exit(&config_misc_lock);
2367 }
2368 if (errcnt != 0) {
2369 printf("WARNING: %d error%s while detecting hardware; "
2370 "check system log.\n", errcnt,
2371 errcnt == 1 ? "" : "s");
2372 }
2373 }
2374
2375 void
2376 config_twiddle_init(void)
2377 {
2378
2379 if ((boothowto & (AB_SILENT|AB_VERBOSE)) == AB_SILENT) {
2380 config_do_twiddle = 1;
2381 }
2382 callout_setfunc(&config_twiddle_ch, config_twiddle_fn, NULL);
2383 }
2384
2385 void
2386 config_twiddle_fn(void *cookie)
2387 {
2388
2389 mutex_enter(&config_misc_lock);
2390 if (config_do_twiddle) {
2391 twiddle();
2392 callout_schedule(&config_twiddle_ch, mstohz(100));
2393 }
2394 mutex_exit(&config_misc_lock);
2395 }
2396
2397 static void
2398 config_alldevs_enter(struct alldevs_foray *af)
2399 {
2400 TAILQ_INIT(&af->af_garbage);
2401 mutex_enter(&alldevs_lock);
2402 config_collect_garbage(&af->af_garbage);
2403 }
2404
2405 static void
2406 config_alldevs_exit(struct alldevs_foray *af)
2407 {
2408 mutex_exit(&alldevs_lock);
2409 config_dump_garbage(&af->af_garbage);
2410 }
2411
2412 /*
2413 * device_lookup:
2414 *
2415 * Look up a device instance for a given driver.
2416 */
2417 device_t
2418 device_lookup(cfdriver_t cd, int unit)
2419 {
2420 device_t dv;
2421
2422 mutex_enter(&alldevs_lock);
2423 if (unit < 0 || unit >= cd->cd_ndevs)
2424 dv = NULL;
2425 else if ((dv = cd->cd_devs[unit]) != NULL && dv->dv_del_gen != 0)
2426 dv = NULL;
2427 mutex_exit(&alldevs_lock);
2428
2429 return dv;
2430 }
2431
2432 /*
2433 * device_lookup_private:
2434 *
2435 * Look up a softc instance for a given driver.
2436 */
2437 void *
2438 device_lookup_private(cfdriver_t cd, int unit)
2439 {
2440
2441 return device_private(device_lookup(cd, unit));
2442 }
2443
2444 /*
2445 * device_find_by_xname:
2446 *
2447 * Returns the device of the given name or NULL if it doesn't exist.
2448 */
2449 device_t
2450 device_find_by_xname(const char *name)
2451 {
2452 device_t dv;
2453 deviter_t di;
2454
2455 for (dv = deviter_first(&di, 0); dv != NULL; dv = deviter_next(&di)) {
2456 if (strcmp(device_xname(dv), name) == 0)
2457 break;
2458 }
2459 deviter_release(&di);
2460
2461 return dv;
2462 }
2463
2464 /*
2465 * device_find_by_driver_unit:
2466 *
2467 * Returns the device of the given driver name and unit or
2468 * NULL if it doesn't exist.
2469 */
2470 device_t
2471 device_find_by_driver_unit(const char *name, int unit)
2472 {
2473 struct cfdriver *cd;
2474
2475 if ((cd = config_cfdriver_lookup(name)) == NULL)
2476 return NULL;
2477 return device_lookup(cd, unit);
2478 }
2479
2480 static bool
2481 match_strcmp(const char * const s1, const char * const s2)
2482 {
2483 return strcmp(s1, s2) == 0;
2484 }
2485
2486 static bool
2487 match_pmatch(const char * const s1, const char * const s2)
2488 {
2489 return pmatch(s1, s2, NULL) == 2;
2490 }
2491
2492 static bool
2493 strarray_match_internal(const char ** const strings,
2494 unsigned int const nstrings, const char * const str,
2495 unsigned int * const indexp,
2496 bool (*match_fn)(const char *, const char *))
2497 {
2498 unsigned int i;
2499
2500 if (strings == NULL || nstrings == 0) {
2501 return false;
2502 }
2503
2504 for (i = 0; i < nstrings; i++) {
2505 if ((*match_fn)(strings[i], str)) {
2506 *indexp = i;
2507 return true;
2508 }
2509 }
2510
2511 return false;
2512 }
2513
2514 static int
2515 strarray_match(const char ** const strings, unsigned int const nstrings,
2516 const char * const str)
2517 {
2518 unsigned int idx;
2519
2520 if (strarray_match_internal(strings, nstrings, str, &idx,
2521 match_strcmp)) {
2522 return (int)(nstrings - idx);
2523 }
2524 return 0;
2525 }
2526
2527 static int
2528 strarray_pmatch(const char ** const strings, unsigned int const nstrings,
2529 const char * const pattern)
2530 {
2531 unsigned int idx;
2532
2533 if (strarray_match_internal(strings, nstrings, pattern, &idx,
2534 match_pmatch)) {
2535 return (int)(nstrings - idx);
2536 }
2537 return 0;
2538 }
2539
2540 static int
2541 device_compatible_match_strarray_internal(
2542 const char **device_compats, int ndevice_compats,
2543 const struct device_compatible_entry *driver_compats,
2544 const struct device_compatible_entry **matching_entryp,
2545 int (*match_fn)(const char **, unsigned int, const char *))
2546 {
2547 const struct device_compatible_entry *dce = NULL;
2548 int rv;
2549
2550 if (ndevice_compats == 0 || device_compats == NULL ||
2551 driver_compats == NULL)
2552 return 0;
2553
2554 for (dce = driver_compats; dce->compat != NULL; dce++) {
2555 rv = (*match_fn)(device_compats, ndevice_compats, dce->compat);
2556 if (rv != 0) {
2557 if (matching_entryp != NULL) {
2558 *matching_entryp = dce;
2559 }
2560 return rv;
2561 }
2562 }
2563 return 0;
2564 }
2565
2566 /*
2567 * device_compatible_match:
2568 *
2569 * Match a driver's "compatible" data against a device's
2570 * "compatible" strings. Returns resulted weighted by
2571 * which device "compatible" string was matched.
2572 */
2573 int
2574 device_compatible_match(const char **device_compats, int ndevice_compats,
2575 const struct device_compatible_entry *driver_compats)
2576 {
2577 return device_compatible_match_strarray_internal(device_compats,
2578 ndevice_compats, driver_compats, NULL, strarray_match);
2579 }
2580
2581 /*
2582 * device_compatible_pmatch:
2583 *
2584 * Like device_compatible_match(), but uses pmatch(9) to compare
2585 * the device "compatible" strings against patterns in the
2586 * driver's "compatible" data.
2587 */
2588 int
2589 device_compatible_pmatch(const char **device_compats, int ndevice_compats,
2590 const struct device_compatible_entry *driver_compats)
2591 {
2592 return device_compatible_match_strarray_internal(device_compats,
2593 ndevice_compats, driver_compats, NULL, strarray_pmatch);
2594 }
2595
2596 static int
2597 device_compatible_match_strlist_internal(
2598 const char * const device_compats, size_t const device_compatsize,
2599 const struct device_compatible_entry *driver_compats,
2600 const struct device_compatible_entry **matching_entryp,
2601 int (*match_fn)(const char *, size_t, const char *))
2602 {
2603 const struct device_compatible_entry *dce = NULL;
2604 int rv;
2605
2606 if (device_compats == NULL || device_compatsize == 0 ||
2607 driver_compats == NULL)
2608 return 0;
2609
2610 for (dce = driver_compats; dce->compat != NULL; dce++) {
2611 rv = (*match_fn)(device_compats, device_compatsize,
2612 dce->compat);
2613 if (rv != 0) {
2614 if (matching_entryp != NULL) {
2615 *matching_entryp = dce;
2616 }
2617 return rv;
2618 }
2619 }
2620 return 0;
2621 }
2622
2623 /*
2624 * device_compatible_match_strlist:
2625 *
2626 * Like device_compatible_match(), but take the device
2627 * "compatible" strings as an OpenFirmware-style string
2628 * list.
2629 */
2630 int
2631 device_compatible_match_strlist(
2632 const char * const device_compats, size_t const device_compatsize,
2633 const struct device_compatible_entry *driver_compats)
2634 {
2635 return device_compatible_match_strlist_internal(device_compats,
2636 device_compatsize, driver_compats, NULL, strlist_match);
2637 }
2638
2639 /*
2640 * device_compatible_pmatch_strlist:
2641 *
2642 * Like device_compatible_pmatch(), but take the device
2643 * "compatible" strings as an OpenFirmware-style string
2644 * list.
2645 */
2646 int
2647 device_compatible_pmatch_strlist(
2648 const char * const device_compats, size_t const device_compatsize,
2649 const struct device_compatible_entry *driver_compats)
2650 {
2651 return device_compatible_match_strlist_internal(device_compats,
2652 device_compatsize, driver_compats, NULL, strlist_pmatch);
2653 }
2654
2655 static int
2656 device_compatible_match_id_internal(
2657 uintptr_t const id, uintptr_t const mask, uintptr_t const sentinel_id,
2658 const struct device_compatible_entry *driver_compats,
2659 const struct device_compatible_entry **matching_entryp)
2660 {
2661 const struct device_compatible_entry *dce = NULL;
2662
2663 if (mask == 0)
2664 return 0;
2665
2666 for (dce = driver_compats; dce->id != sentinel_id; dce++) {
2667 if ((id & mask) == dce->id) {
2668 if (matching_entryp != NULL) {
2669 *matching_entryp = dce;
2670 }
2671 return 1;
2672 }
2673 }
2674 return 0;
2675 }
2676
2677 /*
2678 * device_compatible_match_id:
2679 *
2680 * Like device_compatible_match(), but takes a single
2681 * unsigned integer device ID.
2682 */
2683 int
2684 device_compatible_match_id(
2685 uintptr_t const id, uintptr_t const sentinel_id,
2686 const struct device_compatible_entry *driver_compats)
2687 {
2688 return device_compatible_match_id_internal(id, (uintptr_t)-1,
2689 sentinel_id, driver_compats, NULL);
2690 }
2691
2692 /*
2693 * device_compatible_lookup:
2694 *
2695 * Look up and return the device_compatible_entry, using the
2696 * same matching criteria used by device_compatible_match().
2697 */
2698 const struct device_compatible_entry *
2699 device_compatible_lookup(const char **device_compats, int ndevice_compats,
2700 const struct device_compatible_entry *driver_compats)
2701 {
2702 const struct device_compatible_entry *dce;
2703
2704 if (device_compatible_match_strarray_internal(device_compats,
2705 ndevice_compats, driver_compats, &dce, strarray_match)) {
2706 return dce;
2707 }
2708 return NULL;
2709 }
2710
2711 /*
2712 * device_compatible_plookup:
2713 *
2714 * Look up and return the device_compatible_entry, using the
2715 * same matching criteria used by device_compatible_pmatch().
2716 */
2717 const struct device_compatible_entry *
2718 device_compatible_plookup(const char **device_compats, int ndevice_compats,
2719 const struct device_compatible_entry *driver_compats)
2720 {
2721 const struct device_compatible_entry *dce;
2722
2723 if (device_compatible_match_strarray_internal(device_compats,
2724 ndevice_compats, driver_compats, &dce, strarray_pmatch)) {
2725 return dce;
2726 }
2727 return NULL;
2728 }
2729
2730 /*
2731 * device_compatible_lookup_strlist:
2732 *
2733 * Like device_compatible_lookup(), but take the device
2734 * "compatible" strings as an OpenFirmware-style string
2735 * list.
2736 */
2737 const struct device_compatible_entry *
2738 device_compatible_lookup_strlist(
2739 const char * const device_compats, size_t const device_compatsize,
2740 const struct device_compatible_entry *driver_compats)
2741 {
2742 const struct device_compatible_entry *dce;
2743
2744 if (device_compatible_match_strlist_internal(device_compats,
2745 device_compatsize, driver_compats, &dce, strlist_match)) {
2746 return dce;
2747 }
2748 return NULL;
2749 }
2750
2751 /*
2752 * device_compatible_plookup_strlist:
2753 *
2754 * Like device_compatible_plookup(), but take the device
2755 * "compatible" strings as an OpenFirmware-style string
2756 * list.
2757 */
2758 const struct device_compatible_entry *
2759 device_compatible_plookup_strlist(
2760 const char * const device_compats, size_t const device_compatsize,
2761 const struct device_compatible_entry *driver_compats)
2762 {
2763 const struct device_compatible_entry *dce;
2764
2765 if (device_compatible_match_strlist_internal(device_compats,
2766 device_compatsize, driver_compats, &dce, strlist_pmatch)) {
2767 return dce;
2768 }
2769 return NULL;
2770 }
2771
2772 /*
2773 * device_compatible_lookup_id:
2774 *
2775 * Like device_compatible_lookup(), but takes a single
2776 * unsigned integer device ID.
2777 */
2778 const struct device_compatible_entry *
2779 device_compatible_lookup_id(
2780 uintptr_t const id, uintptr_t const sentinel_id,
2781 const struct device_compatible_entry *driver_compats)
2782 {
2783 const struct device_compatible_entry *dce;
2784
2785 if (device_compatible_match_id_internal(id, (uintptr_t)-1,
2786 sentinel_id, driver_compats, &dce)) {
2787 return dce;
2788 }
2789 return NULL;
2790 }
2791
2792 /*
2793 * Power management related functions.
2794 */
2795
2796 bool
2797 device_pmf_is_registered(device_t dev)
2798 {
2799 return (dev->dv_flags & DVF_POWER_HANDLERS) != 0;
2800 }
2801
2802 bool
2803 device_pmf_driver_suspend(device_t dev, const pmf_qual_t *qual)
2804 {
2805 if ((dev->dv_flags & DVF_DRIVER_SUSPENDED) != 0)
2806 return true;
2807 if ((dev->dv_flags & DVF_CLASS_SUSPENDED) == 0)
2808 return false;
2809 if (pmf_qual_depth(qual) <= DEVACT_LEVEL_DRIVER &&
2810 dev->dv_driver_suspend != NULL &&
2811 !(*dev->dv_driver_suspend)(dev, qual))
2812 return false;
2813
2814 dev->dv_flags |= DVF_DRIVER_SUSPENDED;
2815 return true;
2816 }
2817
2818 bool
2819 device_pmf_driver_resume(device_t dev, const pmf_qual_t *qual)
2820 {
2821 if ((dev->dv_flags & DVF_DRIVER_SUSPENDED) == 0)
2822 return true;
2823 if ((dev->dv_flags & DVF_BUS_SUSPENDED) != 0)
2824 return false;
2825 if (pmf_qual_depth(qual) <= DEVACT_LEVEL_DRIVER &&
2826 dev->dv_driver_resume != NULL &&
2827 !(*dev->dv_driver_resume)(dev, qual))
2828 return false;
2829
2830 dev->dv_flags &= ~DVF_DRIVER_SUSPENDED;
2831 return true;
2832 }
2833
2834 bool
2835 device_pmf_driver_shutdown(device_t dev, int how)
2836 {
2837
2838 if (*dev->dv_driver_shutdown != NULL &&
2839 !(*dev->dv_driver_shutdown)(dev, how))
2840 return false;
2841 return true;
2842 }
2843
2844 bool
2845 device_pmf_driver_register(device_t dev,
2846 bool (*suspend)(device_t, const pmf_qual_t *),
2847 bool (*resume)(device_t, const pmf_qual_t *),
2848 bool (*shutdown)(device_t, int))
2849 {
2850 dev->dv_driver_suspend = suspend;
2851 dev->dv_driver_resume = resume;
2852 dev->dv_driver_shutdown = shutdown;
2853 dev->dv_flags |= DVF_POWER_HANDLERS;
2854 return true;
2855 }
2856
2857 static const char *
2858 curlwp_name(void)
2859 {
2860 if (curlwp->l_name != NULL)
2861 return curlwp->l_name;
2862 else
2863 return curlwp->l_proc->p_comm;
2864 }
2865
2866 void
2867 device_pmf_driver_deregister(device_t dev)
2868 {
2869 device_lock_t dvl = device_getlock(dev);
2870
2871 dev->dv_driver_suspend = NULL;
2872 dev->dv_driver_resume = NULL;
2873
2874 mutex_enter(&dvl->dvl_mtx);
2875 dev->dv_flags &= ~DVF_POWER_HANDLERS;
2876 while (dvl->dvl_nlock > 0 || dvl->dvl_nwait > 0) {
2877 /* Wake a thread that waits for the lock. That
2878 * thread will fail to acquire the lock, and then
2879 * it will wake the next thread that waits for the
2880 * lock, or else it will wake us.
2881 */
2882 cv_signal(&dvl->dvl_cv);
2883 pmflock_debug(dev, __func__, __LINE__);
2884 cv_wait(&dvl->dvl_cv, &dvl->dvl_mtx);
2885 pmflock_debug(dev, __func__, __LINE__);
2886 }
2887 mutex_exit(&dvl->dvl_mtx);
2888 }
2889
2890 bool
2891 device_pmf_driver_child_register(device_t dev)
2892 {
2893 device_t parent = device_parent(dev);
2894
2895 if (parent == NULL || parent->dv_driver_child_register == NULL)
2896 return true;
2897 return (*parent->dv_driver_child_register)(dev);
2898 }
2899
2900 void
2901 device_pmf_driver_set_child_register(device_t dev,
2902 bool (*child_register)(device_t))
2903 {
2904 dev->dv_driver_child_register = child_register;
2905 }
2906
2907 static void
2908 pmflock_debug(device_t dev, const char *func, int line)
2909 {
2910 device_lock_t dvl = device_getlock(dev);
2911
2912 aprint_debug_dev(dev,
2913 "%s.%d, %s dvl_nlock %d dvl_nwait %d dv_flags %x\n", func, line,
2914 curlwp_name(), dvl->dvl_nlock, dvl->dvl_nwait, dev->dv_flags);
2915 }
2916
2917 static bool
2918 device_pmf_lock1(device_t dev)
2919 {
2920 device_lock_t dvl = device_getlock(dev);
2921
2922 while (device_pmf_is_registered(dev) &&
2923 dvl->dvl_nlock > 0 && dvl->dvl_holder != curlwp) {
2924 dvl->dvl_nwait++;
2925 pmflock_debug(dev, __func__, __LINE__);
2926 cv_wait(&dvl->dvl_cv, &dvl->dvl_mtx);
2927 pmflock_debug(dev, __func__, __LINE__);
2928 dvl->dvl_nwait--;
2929 }
2930 if (!device_pmf_is_registered(dev)) {
2931 pmflock_debug(dev, __func__, __LINE__);
2932 /* We could not acquire the lock, but some other thread may
2933 * wait for it, also. Wake that thread.
2934 */
2935 cv_signal(&dvl->dvl_cv);
2936 return false;
2937 }
2938 dvl->dvl_nlock++;
2939 dvl->dvl_holder = curlwp;
2940 pmflock_debug(dev, __func__, __LINE__);
2941 return true;
2942 }
2943
2944 bool
2945 device_pmf_lock(device_t dev)
2946 {
2947 bool rc;
2948 device_lock_t dvl = device_getlock(dev);
2949
2950 mutex_enter(&dvl->dvl_mtx);
2951 rc = device_pmf_lock1(dev);
2952 mutex_exit(&dvl->dvl_mtx);
2953
2954 return rc;
2955 }
2956
2957 void
2958 device_pmf_unlock(device_t dev)
2959 {
2960 device_lock_t dvl = device_getlock(dev);
2961
2962 KASSERT(dvl->dvl_nlock > 0);
2963 mutex_enter(&dvl->dvl_mtx);
2964 if (--dvl->dvl_nlock == 0)
2965 dvl->dvl_holder = NULL;
2966 cv_signal(&dvl->dvl_cv);
2967 pmflock_debug(dev, __func__, __LINE__);
2968 mutex_exit(&dvl->dvl_mtx);
2969 }
2970
2971 device_lock_t
2972 device_getlock(device_t dev)
2973 {
2974 return &dev->dv_lock;
2975 }
2976
2977 void *
2978 device_pmf_bus_private(device_t dev)
2979 {
2980 return dev->dv_bus_private;
2981 }
2982
2983 bool
2984 device_pmf_bus_suspend(device_t dev, const pmf_qual_t *qual)
2985 {
2986 if ((dev->dv_flags & DVF_BUS_SUSPENDED) != 0)
2987 return true;
2988 if ((dev->dv_flags & DVF_CLASS_SUSPENDED) == 0 ||
2989 (dev->dv_flags & DVF_DRIVER_SUSPENDED) == 0)
2990 return false;
2991 if (pmf_qual_depth(qual) <= DEVACT_LEVEL_BUS &&
2992 dev->dv_bus_suspend != NULL &&
2993 !(*dev->dv_bus_suspend)(dev, qual))
2994 return false;
2995
2996 dev->dv_flags |= DVF_BUS_SUSPENDED;
2997 return true;
2998 }
2999
3000 bool
3001 device_pmf_bus_resume(device_t dev, const pmf_qual_t *qual)
3002 {
3003 if ((dev->dv_flags & DVF_BUS_SUSPENDED) == 0)
3004 return true;
3005 if (pmf_qual_depth(qual) <= DEVACT_LEVEL_BUS &&
3006 dev->dv_bus_resume != NULL &&
3007 !(*dev->dv_bus_resume)(dev, qual))
3008 return false;
3009
3010 dev->dv_flags &= ~DVF_BUS_SUSPENDED;
3011 return true;
3012 }
3013
3014 bool
3015 device_pmf_bus_shutdown(device_t dev, int how)
3016 {
3017
3018 if (*dev->dv_bus_shutdown != NULL &&
3019 !(*dev->dv_bus_shutdown)(dev, how))
3020 return false;
3021 return true;
3022 }
3023
3024 void
3025 device_pmf_bus_register(device_t dev, void *priv,
3026 bool (*suspend)(device_t, const pmf_qual_t *),
3027 bool (*resume)(device_t, const pmf_qual_t *),
3028 bool (*shutdown)(device_t, int), void (*deregister)(device_t))
3029 {
3030 dev->dv_bus_private = priv;
3031 dev->dv_bus_resume = resume;
3032 dev->dv_bus_suspend = suspend;
3033 dev->dv_bus_shutdown = shutdown;
3034 dev->dv_bus_deregister = deregister;
3035 }
3036
3037 void
3038 device_pmf_bus_deregister(device_t dev)
3039 {
3040 if (dev->dv_bus_deregister == NULL)
3041 return;
3042 (*dev->dv_bus_deregister)(dev);
3043 dev->dv_bus_private = NULL;
3044 dev->dv_bus_suspend = NULL;
3045 dev->dv_bus_resume = NULL;
3046 dev->dv_bus_deregister = NULL;
3047 }
3048
3049 void *
3050 device_pmf_class_private(device_t dev)
3051 {
3052 return dev->dv_class_private;
3053 }
3054
3055 bool
3056 device_pmf_class_suspend(device_t dev, const pmf_qual_t *qual)
3057 {
3058 if ((dev->dv_flags & DVF_CLASS_SUSPENDED) != 0)
3059 return true;
3060 if (pmf_qual_depth(qual) <= DEVACT_LEVEL_CLASS &&
3061 dev->dv_class_suspend != NULL &&
3062 !(*dev->dv_class_suspend)(dev, qual))
3063 return false;
3064
3065 dev->dv_flags |= DVF_CLASS_SUSPENDED;
3066 return true;
3067 }
3068
3069 bool
3070 device_pmf_class_resume(device_t dev, const pmf_qual_t *qual)
3071 {
3072 if ((dev->dv_flags & DVF_CLASS_SUSPENDED) == 0)
3073 return true;
3074 if ((dev->dv_flags & DVF_BUS_SUSPENDED) != 0 ||
3075 (dev->dv_flags & DVF_DRIVER_SUSPENDED) != 0)
3076 return false;
3077 if (pmf_qual_depth(qual) <= DEVACT_LEVEL_CLASS &&
3078 dev->dv_class_resume != NULL &&
3079 !(*dev->dv_class_resume)(dev, qual))
3080 return false;
3081
3082 dev->dv_flags &= ~DVF_CLASS_SUSPENDED;
3083 return true;
3084 }
3085
3086 void
3087 device_pmf_class_register(device_t dev, void *priv,
3088 bool (*suspend)(device_t, const pmf_qual_t *),
3089 bool (*resume)(device_t, const pmf_qual_t *),
3090 void (*deregister)(device_t))
3091 {
3092 dev->dv_class_private = priv;
3093 dev->dv_class_suspend = suspend;
3094 dev->dv_class_resume = resume;
3095 dev->dv_class_deregister = deregister;
3096 }
3097
3098 void
3099 device_pmf_class_deregister(device_t dev)
3100 {
3101 if (dev->dv_class_deregister == NULL)
3102 return;
3103 (*dev->dv_class_deregister)(dev);
3104 dev->dv_class_private = NULL;
3105 dev->dv_class_suspend = NULL;
3106 dev->dv_class_resume = NULL;
3107 dev->dv_class_deregister = NULL;
3108 }
3109
3110 bool
3111 device_active(device_t dev, devactive_t type)
3112 {
3113 size_t i;
3114
3115 if (dev->dv_activity_count == 0)
3116 return false;
3117
3118 for (i = 0; i < dev->dv_activity_count; ++i) {
3119 if (dev->dv_activity_handlers[i] == NULL)
3120 break;
3121 (*dev->dv_activity_handlers[i])(dev, type);
3122 }
3123
3124 return true;
3125 }
3126
3127 bool
3128 device_active_register(device_t dev, void (*handler)(device_t, devactive_t))
3129 {
3130 void (**new_handlers)(device_t, devactive_t);
3131 void (**old_handlers)(device_t, devactive_t);
3132 size_t i, old_size, new_size;
3133 int s;
3134
3135 old_handlers = dev->dv_activity_handlers;
3136 old_size = dev->dv_activity_count;
3137
3138 KASSERT(old_size == 0 || old_handlers != NULL);
3139
3140 for (i = 0; i < old_size; ++i) {
3141 KASSERT(old_handlers[i] != handler);
3142 if (old_handlers[i] == NULL) {
3143 old_handlers[i] = handler;
3144 return true;
3145 }
3146 }
3147
3148 new_size = old_size + 4;
3149 new_handlers = kmem_alloc(sizeof(void *) * new_size, KM_SLEEP);
3150
3151 for (i = 0; i < old_size; ++i)
3152 new_handlers[i] = old_handlers[i];
3153 new_handlers[old_size] = handler;
3154 for (i = old_size+1; i < new_size; ++i)
3155 new_handlers[i] = NULL;
3156
3157 s = splhigh();
3158 dev->dv_activity_count = new_size;
3159 dev->dv_activity_handlers = new_handlers;
3160 splx(s);
3161
3162 if (old_size > 0)
3163 kmem_free(old_handlers, sizeof(void *) * old_size);
3164
3165 return true;
3166 }
3167
3168 void
3169 device_active_deregister(device_t dev, void (*handler)(device_t, devactive_t))
3170 {
3171 void (**old_handlers)(device_t, devactive_t);
3172 size_t i, old_size;
3173 int s;
3174
3175 old_handlers = dev->dv_activity_handlers;
3176 old_size = dev->dv_activity_count;
3177
3178 for (i = 0; i < old_size; ++i) {
3179 if (old_handlers[i] == handler)
3180 break;
3181 if (old_handlers[i] == NULL)
3182 return; /* XXX panic? */
3183 }
3184
3185 if (i == old_size)
3186 return; /* XXX panic? */
3187
3188 for (; i < old_size - 1; ++i) {
3189 if ((old_handlers[i] = old_handlers[i + 1]) != NULL)
3190 continue;
3191
3192 if (i == 0) {
3193 s = splhigh();
3194 dev->dv_activity_count = 0;
3195 dev->dv_activity_handlers = NULL;
3196 splx(s);
3197 kmem_free(old_handlers, sizeof(void *) * old_size);
3198 }
3199 return;
3200 }
3201 old_handlers[i] = NULL;
3202 }
3203
3204 /* Return true iff the device_t `dev' exists at generation `gen'. */
3205 static bool
3206 device_exists_at(device_t dv, devgen_t gen)
3207 {
3208 return (dv->dv_del_gen == 0 || dv->dv_del_gen > gen) &&
3209 dv->dv_add_gen <= gen;
3210 }
3211
3212 static bool
3213 deviter_visits(const deviter_t *di, device_t dv)
3214 {
3215 return device_exists_at(dv, di->di_gen);
3216 }
3217
3218 /*
3219 * Device Iteration
3220 *
3221 * deviter_t: a device iterator. Holds state for a "walk" visiting
3222 * each device_t's in the device tree.
3223 *
3224 * deviter_init(di, flags): initialize the device iterator `di'
3225 * to "walk" the device tree. deviter_next(di) will return
3226 * the first device_t in the device tree, or NULL if there are
3227 * no devices.
3228 *
3229 * `flags' is one or more of DEVITER_F_RW, indicating that the
3230 * caller intends to modify the device tree by calling
3231 * config_detach(9) on devices in the order that the iterator
3232 * returns them; DEVITER_F_ROOT_FIRST, asking for the devices
3233 * nearest the "root" of the device tree to be returned, first;
3234 * DEVITER_F_LEAVES_FIRST, asking for the devices furthest from
3235 * the root of the device tree, first; and DEVITER_F_SHUTDOWN,
3236 * indicating both that deviter_init() should not respect any
3237 * locks on the device tree, and that deviter_next(di) may run
3238 * in more than one LWP before the walk has finished.
3239 *
3240 * Only one DEVITER_F_RW iterator may be in the device tree at
3241 * once.
3242 *
3243 * DEVITER_F_SHUTDOWN implies DEVITER_F_RW.
3244 *
3245 * Results are undefined if the flags DEVITER_F_ROOT_FIRST and
3246 * DEVITER_F_LEAVES_FIRST are used in combination.
3247 *
3248 * deviter_first(di, flags): initialize the device iterator `di'
3249 * and return the first device_t in the device tree, or NULL
3250 * if there are no devices. The statement
3251 *
3252 * dv = deviter_first(di);
3253 *
3254 * is shorthand for
3255 *
3256 * deviter_init(di);
3257 * dv = deviter_next(di);
3258 *
3259 * deviter_next(di): return the next device_t in the device tree,
3260 * or NULL if there are no more devices. deviter_next(di)
3261 * is undefined if `di' was not initialized with deviter_init() or
3262 * deviter_first().
3263 *
3264 * deviter_release(di): stops iteration (subsequent calls to
3265 * deviter_next() will return NULL), releases any locks and
3266 * resources held by the device iterator.
3267 *
3268 * Device iteration does not return device_t's in any particular
3269 * order. An iterator will never return the same device_t twice.
3270 * Device iteration is guaranteed to complete---i.e., if deviter_next(di)
3271 * is called repeatedly on the same `di', it will eventually return
3272 * NULL. It is ok to attach/detach devices during device iteration.
3273 */
3274 void
3275 deviter_init(deviter_t *di, deviter_flags_t flags)
3276 {
3277 device_t dv;
3278
3279 memset(di, 0, sizeof(*di));
3280
3281 if ((flags & DEVITER_F_SHUTDOWN) != 0)
3282 flags |= DEVITER_F_RW;
3283
3284 mutex_enter(&alldevs_lock);
3285 if ((flags & DEVITER_F_RW) != 0)
3286 alldevs_nwrite++;
3287 else
3288 alldevs_nread++;
3289 di->di_gen = alldevs_gen++;
3290 di->di_flags = flags;
3291
3292 switch (di->di_flags & (DEVITER_F_LEAVES_FIRST|DEVITER_F_ROOT_FIRST)) {
3293 case DEVITER_F_LEAVES_FIRST:
3294 TAILQ_FOREACH(dv, &alldevs, dv_list) {
3295 if (!deviter_visits(di, dv))
3296 continue;
3297 di->di_curdepth = MAX(di->di_curdepth, dv->dv_depth);
3298 }
3299 break;
3300 case DEVITER_F_ROOT_FIRST:
3301 TAILQ_FOREACH(dv, &alldevs, dv_list) {
3302 if (!deviter_visits(di, dv))
3303 continue;
3304 di->di_maxdepth = MAX(di->di_maxdepth, dv->dv_depth);
3305 }
3306 break;
3307 default:
3308 break;
3309 }
3310
3311 deviter_reinit(di);
3312 mutex_exit(&alldevs_lock);
3313 }
3314
3315 static void
3316 deviter_reinit(deviter_t *di)
3317 {
3318
3319 KASSERT(mutex_owned(&alldevs_lock));
3320 if ((di->di_flags & DEVITER_F_RW) != 0)
3321 di->di_prev = TAILQ_LAST(&alldevs, devicelist);
3322 else
3323 di->di_prev = TAILQ_FIRST(&alldevs);
3324 }
3325
3326 device_t
3327 deviter_first(deviter_t *di, deviter_flags_t flags)
3328 {
3329
3330 deviter_init(di, flags);
3331 return deviter_next(di);
3332 }
3333
3334 static device_t
3335 deviter_next2(deviter_t *di)
3336 {
3337 device_t dv;
3338
3339 KASSERT(mutex_owned(&alldevs_lock));
3340
3341 dv = di->di_prev;
3342
3343 if (dv == NULL)
3344 return NULL;
3345
3346 if ((di->di_flags & DEVITER_F_RW) != 0)
3347 di->di_prev = TAILQ_PREV(dv, devicelist, dv_list);
3348 else
3349 di->di_prev = TAILQ_NEXT(dv, dv_list);
3350
3351 return dv;
3352 }
3353
3354 static device_t
3355 deviter_next1(deviter_t *di)
3356 {
3357 device_t dv;
3358
3359 KASSERT(mutex_owned(&alldevs_lock));
3360
3361 do {
3362 dv = deviter_next2(di);
3363 } while (dv != NULL && !deviter_visits(di, dv));
3364
3365 return dv;
3366 }
3367
3368 device_t
3369 deviter_next(deviter_t *di)
3370 {
3371 device_t dv = NULL;
3372
3373 mutex_enter(&alldevs_lock);
3374 switch (di->di_flags & (DEVITER_F_LEAVES_FIRST|DEVITER_F_ROOT_FIRST)) {
3375 case 0:
3376 dv = deviter_next1(di);
3377 break;
3378 case DEVITER_F_LEAVES_FIRST:
3379 while (di->di_curdepth >= 0) {
3380 if ((dv = deviter_next1(di)) == NULL) {
3381 di->di_curdepth--;
3382 deviter_reinit(di);
3383 } else if (dv->dv_depth == di->di_curdepth)
3384 break;
3385 }
3386 break;
3387 case DEVITER_F_ROOT_FIRST:
3388 while (di->di_curdepth <= di->di_maxdepth) {
3389 if ((dv = deviter_next1(di)) == NULL) {
3390 di->di_curdepth++;
3391 deviter_reinit(di);
3392 } else if (dv->dv_depth == di->di_curdepth)
3393 break;
3394 }
3395 break;
3396 default:
3397 break;
3398 }
3399 mutex_exit(&alldevs_lock);
3400
3401 return dv;
3402 }
3403
3404 void
3405 deviter_release(deviter_t *di)
3406 {
3407 bool rw = (di->di_flags & DEVITER_F_RW) != 0;
3408
3409 mutex_enter(&alldevs_lock);
3410 if (rw)
3411 --alldevs_nwrite;
3412 else
3413 --alldevs_nread;
3414 /* XXX wake a garbage-collection thread */
3415 mutex_exit(&alldevs_lock);
3416 }
3417
3418 const char *
3419 cfdata_ifattr(const struct cfdata *cf)
3420 {
3421 return cf->cf_pspec->cfp_iattr;
3422 }
3423
3424 bool
3425 ifattr_match(const char *snull, const char *t)
3426 {
3427 return (snull == NULL) || strcmp(snull, t) == 0;
3428 }
3429
3430 void
3431 null_childdetached(device_t self, device_t child)
3432 {
3433 /* do nothing */
3434 }
3435
3436 static void
3437 sysctl_detach_setup(struct sysctllog **clog)
3438 {
3439
3440 sysctl_createv(clog, 0, NULL, NULL,
3441 CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
3442 CTLTYPE_BOOL, "detachall",
3443 SYSCTL_DESCR("Detach all devices at shutdown"),
3444 NULL, 0, &detachall, 0,
3445 CTL_KERN, CTL_CREATE, CTL_EOL);
3446 }
3447