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