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