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