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