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