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