xref: /netbsd-src/sys/kern/subr_autoconf.c (revision c505c4429840c353a86d4eb53b5e2bfc0092264e)
1 /* $NetBSD: subr_autoconf.c,v 1.208 2010/06/26 06:43:13 tsutsui 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.208 2010/06/26 06:43:13 tsutsui 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 	}
837 	deviter_release(&di);
838 }
839 
840 /*
841  * Attach a supplemental config data table and rescan potential
842  * parent devices if required.
843  */
844 int
845 config_cfdata_attach(cfdata_t cf, int scannow)
846 {
847 	struct cftable *ct;
848 
849 	ct = kmem_alloc(sizeof(*ct), KM_SLEEP);
850 	ct->ct_cfdata = cf;
851 	TAILQ_INSERT_TAIL(&allcftables, ct, ct_list);
852 
853 	if (scannow)
854 		rescan_with_cfdata(cf);
855 
856 	return 0;
857 }
858 
859 /*
860  * Helper for config_cfdata_detach: check whether a device is
861  * found through any attachment in the config data table.
862  */
863 static int
864 dev_in_cfdata(const struct device *d, const struct cfdata *cf)
865 {
866 	const struct cfdata *cf1;
867 
868 	for (cf1 = cf; cf1->cf_name; cf1++)
869 		if (d->dv_cfdata == cf1)
870 			return 1;
871 
872 	return 0;
873 }
874 
875 /*
876  * Detach a supplemental config data table. Detach all devices found
877  * through that table (and thus keeping references to it) before.
878  */
879 int
880 config_cfdata_detach(cfdata_t cf)
881 {
882 	device_t d;
883 	int error = 0;
884 	struct cftable *ct;
885 	deviter_t di;
886 
887 	for (d = deviter_first(&di, DEVITER_F_RW); d != NULL;
888 	     d = deviter_next(&di)) {
889 		if (!dev_in_cfdata(d, cf))
890 			continue;
891 		if ((error = config_detach(d, 0)) != 0)
892 			break;
893 	}
894 	deviter_release(&di);
895 	if (error) {
896 		aprint_error_dev(d, "unable to detach instance\n");
897 		return error;
898 	}
899 
900 	TAILQ_FOREACH(ct, &allcftables, ct_list) {
901 		if (ct->ct_cfdata == cf) {
902 			TAILQ_REMOVE(&allcftables, ct, ct_list);
903 			kmem_free(ct, sizeof(*ct));
904 			return 0;
905 		}
906 	}
907 
908 	/* not found -- shouldn't happen */
909 	return EINVAL;
910 }
911 
912 /*
913  * Invoke the "match" routine for a cfdata entry on behalf of
914  * an external caller, usually a "submatch" routine.
915  */
916 int
917 config_match(device_t parent, cfdata_t cf, void *aux)
918 {
919 	struct cfattach *ca;
920 
921 	ca = config_cfattach_lookup(cf->cf_name, cf->cf_atname);
922 	if (ca == NULL) {
923 		/* No attachment for this entry, oh well. */
924 		return 0;
925 	}
926 
927 	return (*ca->ca_match)(parent, cf, aux);
928 }
929 
930 /*
931  * Iterate over all potential children of some device, calling the given
932  * function (default being the child's match function) for each one.
933  * Nonzero returns are matches; the highest value returned is considered
934  * the best match.  Return the `found child' if we got a match, or NULL
935  * otherwise.  The `aux' pointer is simply passed on through.
936  *
937  * Note that this function is designed so that it can be used to apply
938  * an arbitrary function to all potential children (its return value
939  * can be ignored).
940  */
941 cfdata_t
942 config_search_loc(cfsubmatch_t fn, device_t parent,
943 		  const char *ifattr, const int *locs, void *aux)
944 {
945 	struct cftable *ct;
946 	cfdata_t cf;
947 	struct matchinfo m;
948 
949 	KASSERT(config_initialized);
950 	KASSERT(!ifattr || cfdriver_get_iattr(parent->dv_cfdriver, ifattr));
951 
952 	m.fn = fn;
953 	m.parent = parent;
954 	m.locs = locs;
955 	m.aux = aux;
956 	m.match = NULL;
957 	m.pri = 0;
958 
959 	TAILQ_FOREACH(ct, &allcftables, ct_list) {
960 		for (cf = ct->ct_cfdata; cf->cf_name; cf++) {
961 
962 			/* We don't match root nodes here. */
963 			if (!cf->cf_pspec)
964 				continue;
965 
966 			/*
967 			 * Skip cf if no longer eligible, otherwise scan
968 			 * through parents for one matching `parent', and
969 			 * try match function.
970 			 */
971 			if (cf->cf_fstate == FSTATE_FOUND)
972 				continue;
973 			if (cf->cf_fstate == FSTATE_DNOTFOUND ||
974 			    cf->cf_fstate == FSTATE_DSTAR)
975 				continue;
976 
977 			/*
978 			 * If an interface attribute was specified,
979 			 * consider only children which attach to
980 			 * that attribute.
981 			 */
982 			if (ifattr && !STREQ(ifattr, cfdata_ifattr(cf)))
983 				continue;
984 
985 			if (cfparent_match(parent, cf->cf_pspec))
986 				mapply(&m, cf);
987 		}
988 	}
989 	return m.match;
990 }
991 
992 cfdata_t
993 config_search_ia(cfsubmatch_t fn, device_t parent, const char *ifattr,
994     void *aux)
995 {
996 
997 	return config_search_loc(fn, parent, ifattr, NULL, aux);
998 }
999 
1000 /*
1001  * Find the given root device.
1002  * This is much like config_search, but there is no parent.
1003  * Don't bother with multiple cfdata tables; the root node
1004  * must always be in the initial table.
1005  */
1006 cfdata_t
1007 config_rootsearch(cfsubmatch_t fn, const char *rootname, void *aux)
1008 {
1009 	cfdata_t cf;
1010 	const short *p;
1011 	struct matchinfo m;
1012 
1013 	m.fn = fn;
1014 	m.parent = ROOT;
1015 	m.aux = aux;
1016 	m.match = NULL;
1017 	m.pri = 0;
1018 	m.locs = 0;
1019 	/*
1020 	 * Look at root entries for matching name.  We do not bother
1021 	 * with found-state here since only one root should ever be
1022 	 * searched (and it must be done first).
1023 	 */
1024 	for (p = cfroots; *p >= 0; p++) {
1025 		cf = &cfdata[*p];
1026 		if (strcmp(cf->cf_name, rootname) == 0)
1027 			mapply(&m, cf);
1028 	}
1029 	return m.match;
1030 }
1031 
1032 static const char * const msgs[3] = { "", " not configured\n", " unsupported\n" };
1033 
1034 /*
1035  * The given `aux' argument describes a device that has been found
1036  * on the given parent, but not necessarily configured.  Locate the
1037  * configuration data for that device (using the submatch function
1038  * provided, or using candidates' cd_match configuration driver
1039  * functions) and attach it, and return true.  If the device was
1040  * not configured, call the given `print' function and return 0.
1041  */
1042 device_t
1043 config_found_sm_loc(device_t parent,
1044 		const char *ifattr, const int *locs, void *aux,
1045 		cfprint_t print, cfsubmatch_t submatch)
1046 {
1047 	cfdata_t cf;
1048 
1049 #if defined(SPLASHSCREEN) && defined(SPLASHSCREEN_PROGRESS)
1050 	if (splash_progress_state)
1051 		splash_progress_update(splash_progress_state);
1052 #endif
1053 
1054 	if ((cf = config_search_loc(submatch, parent, ifattr, locs, aux)))
1055 		return(config_attach_loc(parent, cf, locs, aux, print));
1056 	if (print) {
1057 		if (config_do_twiddle && cold)
1058 			twiddle();
1059 		aprint_normal("%s", msgs[(*print)(aux, device_xname(parent))]);
1060 	}
1061 
1062 #if defined(SPLASHSCREEN) && defined(SPLASHSCREEN_PROGRESS)
1063 	if (splash_progress_state)
1064 		splash_progress_update(splash_progress_state);
1065 #endif
1066 
1067 	return NULL;
1068 }
1069 
1070 device_t
1071 config_found_ia(device_t parent, const char *ifattr, void *aux,
1072     cfprint_t print)
1073 {
1074 
1075 	return config_found_sm_loc(parent, ifattr, NULL, aux, print, NULL);
1076 }
1077 
1078 device_t
1079 config_found(device_t parent, void *aux, cfprint_t print)
1080 {
1081 
1082 	return config_found_sm_loc(parent, NULL, NULL, aux, print, NULL);
1083 }
1084 
1085 /*
1086  * As above, but for root devices.
1087  */
1088 device_t
1089 config_rootfound(const char *rootname, void *aux)
1090 {
1091 	cfdata_t cf;
1092 
1093 	if ((cf = config_rootsearch((cfsubmatch_t)NULL, rootname, aux)) != NULL)
1094 		return config_attach(ROOT, cf, aux, (cfprint_t)NULL);
1095 	aprint_error("root device %s not configured\n", rootname);
1096 	return NULL;
1097 }
1098 
1099 /* just like sprintf(buf, "%d") except that it works from the end */
1100 static char *
1101 number(char *ep, int n)
1102 {
1103 
1104 	*--ep = 0;
1105 	while (n >= 10) {
1106 		*--ep = (n % 10) + '0';
1107 		n /= 10;
1108 	}
1109 	*--ep = n + '0';
1110 	return ep;
1111 }
1112 
1113 /*
1114  * Expand the size of the cd_devs array if necessary.
1115  *
1116  * The caller must hold alldevs_mtx. config_makeroom() may release and
1117  * re-acquire alldevs_mtx, so callers should re-check conditions such
1118  * as alldevs_nwrite == 0 and alldevs_nread == 0 when config_makeroom()
1119  * returns.
1120  */
1121 static void
1122 config_makeroom(int n, struct cfdriver *cd)
1123 {
1124 	int old, new;
1125 	device_t *osp, *nsp;
1126 
1127 	alldevs_nwrite++;
1128 
1129 	for (new = MAX(4, cd->cd_ndevs); new <= n; new += new)
1130 		;
1131 
1132 	while (n >= cd->cd_ndevs) {
1133 		/*
1134 		 * Need to expand the array.
1135 		 */
1136 		old = cd->cd_ndevs;
1137 		osp = cd->cd_devs;
1138 
1139 		/* Release alldevs_mtx around allocation, which may
1140 		 * sleep.
1141 		 */
1142 		mutex_exit(&alldevs_mtx);
1143 		nsp = kmem_alloc(sizeof(device_t[new]), KM_SLEEP);
1144 		if (nsp == NULL)
1145 			panic("%s: could not expand cd_devs", __func__);
1146 		mutex_enter(&alldevs_mtx);
1147 
1148 		/* If another thread moved the array while we did
1149 		 * not hold alldevs_mtx, try again.
1150 		 */
1151 		if (cd->cd_devs != osp) {
1152 			mutex_exit(&alldevs_mtx);
1153 			kmem_free(nsp, sizeof(device_t[new]));
1154 			mutex_enter(&alldevs_mtx);
1155 			continue;
1156 		}
1157 
1158 		memset(nsp + old, 0, sizeof(device_t[new - old]));
1159 		if (old != 0)
1160 			memcpy(nsp, cd->cd_devs, sizeof(device_t[old]));
1161 
1162 		cd->cd_ndevs = new;
1163 		cd->cd_devs = nsp;
1164 		if (old != 0) {
1165 			mutex_exit(&alldevs_mtx);
1166 			kmem_free(osp, sizeof(device_t[old]));
1167 			mutex_enter(&alldevs_mtx);
1168 		}
1169 	}
1170 	alldevs_nwrite--;
1171 }
1172 
1173 /*
1174  * Put dev into the devices list.
1175  */
1176 static void
1177 config_devlink(device_t dev)
1178 {
1179 	int s;
1180 
1181 	s = config_alldevs_lock();
1182 
1183 	KASSERT(device_cfdriver(dev)->cd_devs[dev->dv_unit] == dev);
1184 
1185 	dev->dv_add_gen = alldevs_gen;
1186 	/* It is safe to add a device to the tail of the list while
1187 	 * readers and writers are in the list.
1188 	 */
1189 	TAILQ_INSERT_TAIL(&alldevs, dev, dv_list);
1190 	config_alldevs_unlock(s);
1191 }
1192 
1193 static void
1194 config_devfree(device_t dev)
1195 {
1196 	int priv = (dev->dv_flags & DVF_PRIV_ALLOC);
1197 
1198 	if (dev->dv_cfattach->ca_devsize > 0)
1199 		kmem_free(dev->dv_private, dev->dv_cfattach->ca_devsize);
1200 	if (priv)
1201 		kmem_free(dev, sizeof(*dev));
1202 }
1203 
1204 /*
1205  * Caller must hold alldevs_mtx.
1206  */
1207 static void
1208 config_devunlink(device_t dev, struct devicelist *garbage)
1209 {
1210 	struct device_garbage *dg = &dev->dv_garbage;
1211 	cfdriver_t cd = device_cfdriver(dev);
1212 	int i;
1213 
1214 	KASSERT(mutex_owned(&alldevs_mtx));
1215 
1216  	/* Unlink from device list.  Link to garbage list. */
1217 	TAILQ_REMOVE(&alldevs, dev, dv_list);
1218 	TAILQ_INSERT_TAIL(garbage, dev, dv_list);
1219 
1220 	/* Remove from cfdriver's array. */
1221 	cd->cd_devs[dev->dv_unit] = NULL;
1222 
1223 	/*
1224 	 * If the device now has no units in use, unlink its softc array.
1225 	 */
1226 	for (i = 0; i < cd->cd_ndevs; i++) {
1227 		if (cd->cd_devs[i] != NULL)
1228 			break;
1229 	}
1230 	/* Nothing found.  Unlink, now.  Deallocate, later. */
1231 	if (i == cd->cd_ndevs) {
1232 		dg->dg_ndevs = cd->cd_ndevs;
1233 		dg->dg_devs = cd->cd_devs;
1234 		cd->cd_devs = NULL;
1235 		cd->cd_ndevs = 0;
1236 	}
1237 }
1238 
1239 static void
1240 config_devdelete(device_t dev)
1241 {
1242 	struct device_garbage *dg = &dev->dv_garbage;
1243 	device_lock_t dvl = device_getlock(dev);
1244 
1245 	if (dg->dg_devs != NULL)
1246 		kmem_free(dg->dg_devs, sizeof(device_t[dg->dg_ndevs]));
1247 
1248 	cv_destroy(&dvl->dvl_cv);
1249 	mutex_destroy(&dvl->dvl_mtx);
1250 
1251 	KASSERT(dev->dv_properties != NULL);
1252 	prop_object_release(dev->dv_properties);
1253 
1254 	if (dev->dv_activity_handlers)
1255 		panic("%s with registered handlers", __func__);
1256 
1257 	if (dev->dv_locators) {
1258 		size_t amount = *--dev->dv_locators;
1259 		kmem_free(dev->dv_locators, amount);
1260 	}
1261 
1262 	config_devfree(dev);
1263 }
1264 
1265 static int
1266 config_unit_nextfree(cfdriver_t cd, cfdata_t cf)
1267 {
1268 	int unit;
1269 
1270 	if (cf->cf_fstate == FSTATE_STAR) {
1271 		for (unit = cf->cf_unit; unit < cd->cd_ndevs; unit++)
1272 			if (cd->cd_devs[unit] == NULL)
1273 				break;
1274 		/*
1275 		 * unit is now the unit of the first NULL device pointer,
1276 		 * or max(cd->cd_ndevs,cf->cf_unit).
1277 		 */
1278 	} else {
1279 		unit = cf->cf_unit;
1280 		if (unit < cd->cd_ndevs && cd->cd_devs[unit] != NULL)
1281 			unit = -1;
1282 	}
1283 	return unit;
1284 }
1285 
1286 static int
1287 config_unit_alloc(device_t dev, cfdriver_t cd, cfdata_t cf)
1288 {
1289 	struct alldevs_foray af;
1290 	int unit;
1291 
1292 	config_alldevs_enter(&af);
1293 	for (;;) {
1294 		unit = config_unit_nextfree(cd, cf);
1295 		if (unit == -1)
1296 			break;
1297 		if (unit < cd->cd_ndevs) {
1298 			cd->cd_devs[unit] = dev;
1299 			dev->dv_unit = unit;
1300 			break;
1301 		}
1302 		config_makeroom(unit, cd);
1303 	}
1304 	config_alldevs_exit(&af);
1305 
1306 	return unit;
1307 }
1308 
1309 static device_t
1310 config_devalloc(const device_t parent, const cfdata_t cf, const int *locs)
1311 {
1312 	cfdriver_t cd;
1313 	cfattach_t ca;
1314 	size_t lname, lunit;
1315 	const char *xunit;
1316 	int myunit;
1317 	char num[10];
1318 	device_t dev;
1319 	void *dev_private;
1320 	const struct cfiattrdata *ia;
1321 	device_lock_t dvl;
1322 
1323 	cd = config_cfdriver_lookup(cf->cf_name);
1324 	if (cd == NULL)
1325 		return NULL;
1326 
1327 	ca = config_cfattach_lookup_cd(cd, cf->cf_atname);
1328 	if (ca == NULL)
1329 		return NULL;
1330 
1331 	if ((ca->ca_flags & DVF_PRIV_ALLOC) == 0 &&
1332 	    ca->ca_devsize < sizeof(struct device))
1333 		panic("config_devalloc: %s", cf->cf_atname);
1334 
1335 	/* get memory for all device vars */
1336 	KASSERT((ca->ca_flags & DVF_PRIV_ALLOC) || ca->ca_devsize >= sizeof(struct device));
1337 	if (ca->ca_devsize > 0) {
1338 		dev_private = kmem_zalloc(ca->ca_devsize, KM_SLEEP);
1339 		if (dev_private == NULL)
1340 			panic("config_devalloc: memory allocation for device softc failed");
1341 	} else {
1342 		KASSERT(ca->ca_flags & DVF_PRIV_ALLOC);
1343 		dev_private = NULL;
1344 	}
1345 
1346 	if ((ca->ca_flags & DVF_PRIV_ALLOC) != 0) {
1347 		dev = kmem_zalloc(sizeof(*dev), KM_SLEEP);
1348 	} else {
1349 		dev = dev_private;
1350 	}
1351 	if (dev == NULL)
1352 		panic("config_devalloc: memory allocation for device_t failed");
1353 
1354 	dev->dv_class = cd->cd_class;
1355 	dev->dv_cfdata = cf;
1356 	dev->dv_cfdriver = cd;
1357 	dev->dv_cfattach = ca;
1358 	dev->dv_activity_count = 0;
1359 	dev->dv_activity_handlers = NULL;
1360 	dev->dv_private = dev_private;
1361 	dev->dv_flags = ca->ca_flags;	/* inherit flags from class */
1362 
1363 	myunit = config_unit_alloc(dev, cd, cf);
1364 	if (myunit == -1) {
1365 		config_devfree(dev);
1366 		return NULL;
1367 	}
1368 
1369 	/* compute length of name and decimal expansion of unit number */
1370 	lname = strlen(cd->cd_name);
1371 	xunit = number(&num[sizeof(num)], myunit);
1372 	lunit = &num[sizeof(num)] - xunit;
1373 	if (lname + lunit > sizeof(dev->dv_xname))
1374 		panic("config_devalloc: device name too long");
1375 
1376 	dvl = device_getlock(dev);
1377 
1378 	mutex_init(&dvl->dvl_mtx, MUTEX_DEFAULT, IPL_NONE);
1379 	cv_init(&dvl->dvl_cv, "pmfsusp");
1380 
1381 	memcpy(dev->dv_xname, cd->cd_name, lname);
1382 	memcpy(dev->dv_xname + lname, xunit, lunit);
1383 	dev->dv_parent = parent;
1384 	if (parent != NULL)
1385 		dev->dv_depth = parent->dv_depth + 1;
1386 	else
1387 		dev->dv_depth = 0;
1388 	dev->dv_flags |= DVF_ACTIVE;	/* always initially active */
1389 	if (locs) {
1390 		KASSERT(parent); /* no locators at root */
1391 		ia = cfiattr_lookup(cfdata_ifattr(cf), parent->dv_cfdriver);
1392 		dev->dv_locators =
1393 		    kmem_alloc(sizeof(int [ia->ci_loclen + 1]), KM_SLEEP);
1394 		*dev->dv_locators++ = sizeof(int [ia->ci_loclen + 1]);
1395 		memcpy(dev->dv_locators, locs, sizeof(int [ia->ci_loclen]));
1396 	}
1397 	dev->dv_properties = prop_dictionary_create();
1398 	KASSERT(dev->dv_properties != NULL);
1399 
1400 	prop_dictionary_set_cstring_nocopy(dev->dv_properties,
1401 	    "device-driver", dev->dv_cfdriver->cd_name);
1402 	prop_dictionary_set_uint16(dev->dv_properties,
1403 	    "device-unit", dev->dv_unit);
1404 
1405 	return dev;
1406 }
1407 
1408 /*
1409  * Attach a found device.
1410  */
1411 device_t
1412 config_attach_loc(device_t parent, cfdata_t cf,
1413 	const int *locs, void *aux, cfprint_t print)
1414 {
1415 	device_t dev;
1416 	struct cftable *ct;
1417 	const char *drvname;
1418 
1419 #if defined(SPLASHSCREEN) && defined(SPLASHSCREEN_PROGRESS)
1420 	if (splash_progress_state)
1421 		splash_progress_update(splash_progress_state);
1422 #endif
1423 
1424 	dev = config_devalloc(parent, cf, locs);
1425 	if (!dev)
1426 		panic("config_attach: allocation of device softc failed");
1427 
1428 	/* XXX redundant - see below? */
1429 	if (cf->cf_fstate != FSTATE_STAR) {
1430 		KASSERT(cf->cf_fstate == FSTATE_NOTFOUND);
1431 		cf->cf_fstate = FSTATE_FOUND;
1432 	}
1433 
1434 	config_devlink(dev);
1435 
1436 	if (config_do_twiddle && cold)
1437 		twiddle();
1438 	else
1439 		aprint_naive("Found ");
1440 	/*
1441 	 * We want the next two printfs for normal, verbose, and quiet,
1442 	 * but not silent (in which case, we're twiddling, instead).
1443 	 */
1444 	if (parent == ROOT) {
1445 		aprint_naive("%s (root)", device_xname(dev));
1446 		aprint_normal("%s (root)", device_xname(dev));
1447 	} else {
1448 		aprint_naive("%s at %s", device_xname(dev), device_xname(parent));
1449 		aprint_normal("%s at %s", device_xname(dev), device_xname(parent));
1450 		if (print)
1451 			(void) (*print)(aux, NULL);
1452 	}
1453 
1454 	/*
1455 	 * Before attaching, clobber any unfound devices that are
1456 	 * otherwise identical.
1457 	 * XXX code above is redundant?
1458 	 */
1459 	drvname = dev->dv_cfdriver->cd_name;
1460 	TAILQ_FOREACH(ct, &allcftables, ct_list) {
1461 		for (cf = ct->ct_cfdata; cf->cf_name; cf++) {
1462 			if (STREQ(cf->cf_name, drvname) &&
1463 			    cf->cf_unit == dev->dv_unit) {
1464 				if (cf->cf_fstate == FSTATE_NOTFOUND)
1465 					cf->cf_fstate = FSTATE_FOUND;
1466 			}
1467 		}
1468 	}
1469 #ifdef __HAVE_DEVICE_REGISTER
1470 	device_register(dev, aux);
1471 #endif
1472 
1473 	/* Let userland know */
1474 	devmon_report_device(dev, true);
1475 
1476 #if defined(SPLASHSCREEN) && defined(SPLASHSCREEN_PROGRESS)
1477 	if (splash_progress_state)
1478 		splash_progress_update(splash_progress_state);
1479 #endif
1480 	(*dev->dv_cfattach->ca_attach)(parent, dev, aux);
1481 #if defined(SPLASHSCREEN) && defined(SPLASHSCREEN_PROGRESS)
1482 	if (splash_progress_state)
1483 		splash_progress_update(splash_progress_state);
1484 #endif
1485 
1486 	if (!device_pmf_is_registered(dev))
1487 		aprint_debug_dev(dev, "WARNING: power management not supported\n");
1488 
1489 	config_process_deferred(&deferred_config_queue, dev);
1490 
1491 #ifdef __HAVE_DEVICE_REGISTER_POSTCONFIG
1492 	device_register_post_config(dev, aux);
1493 #endif
1494 	return dev;
1495 }
1496 
1497 device_t
1498 config_attach(device_t parent, cfdata_t cf, void *aux, cfprint_t print)
1499 {
1500 
1501 	return config_attach_loc(parent, cf, NULL, aux, print);
1502 }
1503 
1504 /*
1505  * As above, but for pseudo-devices.  Pseudo-devices attached in this
1506  * way are silently inserted into the device tree, and their children
1507  * attached.
1508  *
1509  * Note that because pseudo-devices are attached silently, any information
1510  * the attach routine wishes to print should be prefixed with the device
1511  * name by the attach routine.
1512  */
1513 device_t
1514 config_attach_pseudo(cfdata_t cf)
1515 {
1516 	device_t dev;
1517 
1518 	dev = config_devalloc(ROOT, cf, NULL);
1519 	if (!dev)
1520 		return NULL;
1521 
1522 	/* XXX mark busy in cfdata */
1523 
1524 	if (cf->cf_fstate != FSTATE_STAR) {
1525 		KASSERT(cf->cf_fstate == FSTATE_NOTFOUND);
1526 		cf->cf_fstate = FSTATE_FOUND;
1527 	}
1528 
1529 	config_devlink(dev);
1530 
1531 #if 0	/* XXXJRT not yet */
1532 #ifdef __HAVE_DEVICE_REGISTER
1533 	device_register(dev, NULL);	/* like a root node */
1534 #endif
1535 #endif
1536 	(*dev->dv_cfattach->ca_attach)(ROOT, dev, NULL);
1537 	config_process_deferred(&deferred_config_queue, dev);
1538 	return dev;
1539 }
1540 
1541 /*
1542  * Caller must hold alldevs_mtx.
1543  */
1544 static void
1545 config_collect_garbage(struct devicelist *garbage)
1546 {
1547 	device_t dv;
1548 
1549 	KASSERT(!cpu_intr_p());
1550 	KASSERT(!cpu_softintr_p());
1551 	KASSERT(mutex_owned(&alldevs_mtx));
1552 
1553 	while (alldevs_nwrite == 0 && alldevs_nread == 0 && alldevs_garbage) {
1554 		TAILQ_FOREACH(dv, &alldevs, dv_list) {
1555 			if (dv->dv_del_gen != 0)
1556 				break;
1557 		}
1558 		if (dv == NULL) {
1559 			alldevs_garbage = false;
1560 			break;
1561 		}
1562 		config_devunlink(dv, garbage);
1563 	}
1564 	KASSERT(mutex_owned(&alldevs_mtx));
1565 }
1566 
1567 static void
1568 config_dump_garbage(struct devicelist *garbage)
1569 {
1570 	device_t dv;
1571 
1572 	while ((dv = TAILQ_FIRST(garbage)) != NULL) {
1573 		TAILQ_REMOVE(garbage, dv, dv_list);
1574 		config_devdelete(dv);
1575 	}
1576 }
1577 
1578 /*
1579  * Detach a device.  Optionally forced (e.g. because of hardware
1580  * removal) and quiet.  Returns zero if successful, non-zero
1581  * (an error code) otherwise.
1582  *
1583  * Note that this code wants to be run from a process context, so
1584  * that the detach can sleep to allow processes which have a device
1585  * open to run and unwind their stacks.
1586  */
1587 int
1588 config_detach(device_t dev, int flags)
1589 {
1590 	struct alldevs_foray af;
1591 	struct cftable *ct;
1592 	cfdata_t cf;
1593 	const struct cfattach *ca;
1594 	struct cfdriver *cd;
1595 #ifdef DIAGNOSTIC
1596 	device_t d;
1597 #endif
1598 	int rv = 0, s;
1599 
1600 #ifdef DIAGNOSTIC
1601 	cf = dev->dv_cfdata;
1602 	if (cf != NULL && cf->cf_fstate != FSTATE_FOUND &&
1603 	    cf->cf_fstate != FSTATE_STAR)
1604 		panic("config_detach: %s: bad device fstate %d",
1605 		    device_xname(dev), cf ? cf->cf_fstate : -1);
1606 #endif
1607 	cd = dev->dv_cfdriver;
1608 	KASSERT(cd != NULL);
1609 
1610 	ca = dev->dv_cfattach;
1611 	KASSERT(ca != NULL);
1612 
1613 	s = config_alldevs_lock();
1614 	if (dev->dv_del_gen != 0) {
1615 		config_alldevs_unlock(s);
1616 #ifdef DIAGNOSTIC
1617 		printf("%s: %s is already detached\n", __func__,
1618 		    device_xname(dev));
1619 #endif /* DIAGNOSTIC */
1620 		return ENOENT;
1621 	}
1622 	alldevs_nwrite++;
1623 	config_alldevs_unlock(s);
1624 
1625 	if (!detachall &&
1626 	    (flags & (DETACH_SHUTDOWN|DETACH_FORCE)) == DETACH_SHUTDOWN &&
1627 	    (dev->dv_flags & DVF_DETACH_SHUTDOWN) == 0) {
1628 		rv = EOPNOTSUPP;
1629 	} else if (ca->ca_detach != NULL) {
1630 		rv = (*ca->ca_detach)(dev, flags);
1631 	} else
1632 		rv = EOPNOTSUPP;
1633 
1634 	/*
1635 	 * If it was not possible to detach the device, then we either
1636 	 * panic() (for the forced but failed case), or return an error.
1637 	 *
1638 	 * If it was possible to detach the device, ensure that the
1639 	 * device is deactivated.
1640 	 */
1641 	if (rv == 0)
1642 		dev->dv_flags &= ~DVF_ACTIVE;
1643 	else if ((flags & DETACH_FORCE) == 0)
1644 		goto out;
1645 	else {
1646 		panic("config_detach: forced detach of %s failed (%d)",
1647 		    device_xname(dev), rv);
1648 	}
1649 
1650 	/*
1651 	 * The device has now been successfully detached.
1652 	 */
1653 
1654 	/* Let userland know */
1655 	devmon_report_device(dev, false);
1656 
1657 #ifdef DIAGNOSTIC
1658 	/*
1659 	 * Sanity: If you're successfully detached, you should have no
1660 	 * children.  (Note that because children must be attached
1661 	 * after parents, we only need to search the latter part of
1662 	 * the list.)
1663 	 */
1664 	for (d = TAILQ_NEXT(dev, dv_list); d != NULL;
1665 	    d = TAILQ_NEXT(d, dv_list)) {
1666 		if (d->dv_parent == dev && d->dv_del_gen == 0) {
1667 			printf("config_detach: detached device %s"
1668 			    " has children %s\n", device_xname(dev), device_xname(d));
1669 			panic("config_detach");
1670 		}
1671 	}
1672 #endif
1673 
1674 	/* notify the parent that the child is gone */
1675 	if (dev->dv_parent) {
1676 		device_t p = dev->dv_parent;
1677 		if (p->dv_cfattach->ca_childdetached)
1678 			(*p->dv_cfattach->ca_childdetached)(p, dev);
1679 	}
1680 
1681 	/*
1682 	 * Mark cfdata to show that the unit can be reused, if possible.
1683 	 */
1684 	TAILQ_FOREACH(ct, &allcftables, ct_list) {
1685 		for (cf = ct->ct_cfdata; cf->cf_name; cf++) {
1686 			if (STREQ(cf->cf_name, cd->cd_name)) {
1687 				if (cf->cf_fstate == FSTATE_FOUND &&
1688 				    cf->cf_unit == dev->dv_unit)
1689 					cf->cf_fstate = FSTATE_NOTFOUND;
1690 			}
1691 		}
1692 	}
1693 
1694 	if (dev->dv_cfdata != NULL && (flags & DETACH_QUIET) == 0)
1695 		aprint_normal_dev(dev, "detached\n");
1696 
1697 out:
1698 	config_alldevs_enter(&af);
1699 	KASSERT(alldevs_nwrite != 0);
1700 	--alldevs_nwrite;
1701 	if (rv == 0 && dev->dv_del_gen == 0)
1702 		config_devunlink(dev, &af.af_garbage);
1703 	config_alldevs_exit(&af);
1704 
1705 	return rv;
1706 }
1707 
1708 int
1709 config_detach_children(device_t parent, int flags)
1710 {
1711 	device_t dv;
1712 	deviter_t di;
1713 	int error = 0;
1714 
1715 	for (dv = deviter_first(&di, DEVITER_F_RW); dv != NULL;
1716 	     dv = deviter_next(&di)) {
1717 		if (device_parent(dv) != parent)
1718 			continue;
1719 		if ((error = config_detach(dv, flags)) != 0)
1720 			break;
1721 	}
1722 	deviter_release(&di);
1723 	return error;
1724 }
1725 
1726 device_t
1727 shutdown_first(struct shutdown_state *s)
1728 {
1729 	if (!s->initialized) {
1730 		deviter_init(&s->di, DEVITER_F_SHUTDOWN|DEVITER_F_LEAVES_FIRST);
1731 		s->initialized = true;
1732 	}
1733 	return shutdown_next(s);
1734 }
1735 
1736 device_t
1737 shutdown_next(struct shutdown_state *s)
1738 {
1739 	device_t dv;
1740 
1741 	while ((dv = deviter_next(&s->di)) != NULL && !device_is_active(dv))
1742 		;
1743 
1744 	if (dv == NULL)
1745 		s->initialized = false;
1746 
1747 	return dv;
1748 }
1749 
1750 bool
1751 config_detach_all(int how)
1752 {
1753 	static struct shutdown_state s;
1754 	device_t curdev;
1755 	bool progress = false;
1756 
1757 	if ((how & RB_NOSYNC) != 0)
1758 		return false;
1759 
1760 	for (curdev = shutdown_first(&s); curdev != NULL;
1761 	     curdev = shutdown_next(&s)) {
1762 		aprint_debug(" detaching %s, ", device_xname(curdev));
1763 		if (config_detach(curdev, DETACH_SHUTDOWN) == 0) {
1764 			progress = true;
1765 			aprint_debug("success.");
1766 		} else
1767 			aprint_debug("failed.");
1768 	}
1769 	return progress;
1770 }
1771 
1772 static bool
1773 device_is_ancestor_of(device_t ancestor, device_t descendant)
1774 {
1775 	device_t dv;
1776 
1777 	for (dv = descendant; dv != NULL; dv = device_parent(dv)) {
1778 		if (device_parent(dv) == ancestor)
1779 			return true;
1780 	}
1781 	return false;
1782 }
1783 
1784 int
1785 config_deactivate(device_t dev)
1786 {
1787 	deviter_t di;
1788 	const struct cfattach *ca;
1789 	device_t descendant;
1790 	int s, rv = 0, oflags;
1791 
1792 	for (descendant = deviter_first(&di, DEVITER_F_ROOT_FIRST);
1793 	     descendant != NULL;
1794 	     descendant = deviter_next(&di)) {
1795 		if (dev != descendant &&
1796 		    !device_is_ancestor_of(dev, descendant))
1797 			continue;
1798 
1799 		if ((descendant->dv_flags & DVF_ACTIVE) == 0)
1800 			continue;
1801 
1802 		ca = descendant->dv_cfattach;
1803 		oflags = descendant->dv_flags;
1804 
1805 		descendant->dv_flags &= ~DVF_ACTIVE;
1806 		if (ca->ca_activate == NULL)
1807 			continue;
1808 		s = splhigh();
1809 		rv = (*ca->ca_activate)(descendant, DVACT_DEACTIVATE);
1810 		splx(s);
1811 		if (rv != 0)
1812 			descendant->dv_flags = oflags;
1813 	}
1814 	deviter_release(&di);
1815 	return rv;
1816 }
1817 
1818 /*
1819  * Defer the configuration of the specified device until all
1820  * of its parent's devices have been attached.
1821  */
1822 void
1823 config_defer(device_t dev, void (*func)(device_t))
1824 {
1825 	struct deferred_config *dc;
1826 
1827 	if (dev->dv_parent == NULL)
1828 		panic("config_defer: can't defer config of a root device");
1829 
1830 #ifdef DIAGNOSTIC
1831 	TAILQ_FOREACH(dc, &deferred_config_queue, dc_queue) {
1832 		if (dc->dc_dev == dev)
1833 			panic("config_defer: deferred twice");
1834 	}
1835 #endif
1836 
1837 	dc = kmem_alloc(sizeof(*dc), KM_SLEEP);
1838 	if (dc == NULL)
1839 		panic("config_defer: unable to allocate callback");
1840 
1841 	dc->dc_dev = dev;
1842 	dc->dc_func = func;
1843 	TAILQ_INSERT_TAIL(&deferred_config_queue, dc, dc_queue);
1844 	config_pending_incr();
1845 }
1846 
1847 /*
1848  * Defer some autoconfiguration for a device until after interrupts
1849  * are enabled.
1850  */
1851 void
1852 config_interrupts(device_t dev, void (*func)(device_t))
1853 {
1854 	struct deferred_config *dc;
1855 
1856 	/*
1857 	 * If interrupts are enabled, callback now.
1858 	 */
1859 	if (cold == 0) {
1860 		(*func)(dev);
1861 		return;
1862 	}
1863 
1864 #ifdef DIAGNOSTIC
1865 	TAILQ_FOREACH(dc, &interrupt_config_queue, dc_queue) {
1866 		if (dc->dc_dev == dev)
1867 			panic("config_interrupts: deferred twice");
1868 	}
1869 #endif
1870 
1871 	dc = kmem_alloc(sizeof(*dc), KM_SLEEP);
1872 	if (dc == NULL)
1873 		panic("config_interrupts: unable to allocate callback");
1874 
1875 	dc->dc_dev = dev;
1876 	dc->dc_func = func;
1877 	TAILQ_INSERT_TAIL(&interrupt_config_queue, dc, dc_queue);
1878 	config_pending_incr();
1879 }
1880 
1881 /*
1882  * Defer some autoconfiguration for a device until after root file system
1883  * is mounted (to load firmware etc).
1884  */
1885 void
1886 config_mountroot(device_t dev, void (*func)(device_t))
1887 {
1888 	struct deferred_config *dc;
1889 
1890 	/*
1891 	 * If root file system is mounted, callback now.
1892 	 */
1893 	if (root_is_mounted) {
1894 		(*func)(dev);
1895 		return;
1896 	}
1897 
1898 #ifdef DIAGNOSTIC
1899 	TAILQ_FOREACH(dc, &mountroot_config_queue, dc_queue) {
1900 		if (dc->dc_dev == dev)
1901 			panic("%s: deferred twice", __func__);
1902 	}
1903 #endif
1904 
1905 	dc = kmem_alloc(sizeof(*dc), KM_SLEEP);
1906 	if (dc == NULL)
1907 		panic("%s: unable to allocate callback", __func__);
1908 
1909 	dc->dc_dev = dev;
1910 	dc->dc_func = func;
1911 	TAILQ_INSERT_TAIL(&mountroot_config_queue, dc, dc_queue);
1912 }
1913 
1914 /*
1915  * Process a deferred configuration queue.
1916  */
1917 static void
1918 config_process_deferred(struct deferred_config_head *queue,
1919     device_t parent)
1920 {
1921 	struct deferred_config *dc, *ndc;
1922 
1923 	for (dc = TAILQ_FIRST(queue); dc != NULL; dc = ndc) {
1924 		ndc = TAILQ_NEXT(dc, dc_queue);
1925 		if (parent == NULL || dc->dc_dev->dv_parent == parent) {
1926 			TAILQ_REMOVE(queue, dc, dc_queue);
1927 			(*dc->dc_func)(dc->dc_dev);
1928 			kmem_free(dc, sizeof(*dc));
1929 			config_pending_decr();
1930 		}
1931 	}
1932 }
1933 
1934 /*
1935  * Manipulate the config_pending semaphore.
1936  */
1937 void
1938 config_pending_incr(void)
1939 {
1940 
1941 	mutex_enter(&config_misc_lock);
1942 	config_pending++;
1943 	mutex_exit(&config_misc_lock);
1944 }
1945 
1946 void
1947 config_pending_decr(void)
1948 {
1949 
1950 #ifdef DIAGNOSTIC
1951 	if (config_pending == 0)
1952 		panic("config_pending_decr: config_pending == 0");
1953 #endif
1954 	mutex_enter(&config_misc_lock);
1955 	config_pending--;
1956 	if (config_pending == 0)
1957 		cv_broadcast(&config_misc_cv);
1958 	mutex_exit(&config_misc_lock);
1959 }
1960 
1961 /*
1962  * Register a "finalization" routine.  Finalization routines are
1963  * called iteratively once all real devices have been found during
1964  * autoconfiguration, for as long as any one finalizer has done
1965  * any work.
1966  */
1967 int
1968 config_finalize_register(device_t dev, int (*fn)(device_t))
1969 {
1970 	struct finalize_hook *f;
1971 
1972 	/*
1973 	 * If finalization has already been done, invoke the
1974 	 * callback function now.
1975 	 */
1976 	if (config_finalize_done) {
1977 		while ((*fn)(dev) != 0)
1978 			/* loop */ ;
1979 	}
1980 
1981 	/* Ensure this isn't already on the list. */
1982 	TAILQ_FOREACH(f, &config_finalize_list, f_list) {
1983 		if (f->f_func == fn && f->f_dev == dev)
1984 			return EEXIST;
1985 	}
1986 
1987 	f = kmem_alloc(sizeof(*f), KM_SLEEP);
1988 	f->f_func = fn;
1989 	f->f_dev = dev;
1990 	TAILQ_INSERT_TAIL(&config_finalize_list, f, f_list);
1991 
1992 	return 0;
1993 }
1994 
1995 void
1996 config_finalize(void)
1997 {
1998 	struct finalize_hook *f;
1999 	struct pdevinit *pdev;
2000 	extern struct pdevinit pdevinit[];
2001 	int errcnt, rv;
2002 
2003 	/*
2004 	 * Now that device driver threads have been created, wait for
2005 	 * them to finish any deferred autoconfiguration.
2006 	 */
2007 	mutex_enter(&config_misc_lock);
2008 	while (config_pending != 0)
2009 		cv_wait(&config_misc_cv, &config_misc_lock);
2010 	mutex_exit(&config_misc_lock);
2011 
2012 	KERNEL_LOCK(1, NULL);
2013 
2014 	/* Attach pseudo-devices. */
2015 	for (pdev = pdevinit; pdev->pdev_attach != NULL; pdev++)
2016 		(*pdev->pdev_attach)(pdev->pdev_count);
2017 
2018 	/* Run the hooks until none of them does any work. */
2019 	do {
2020 		rv = 0;
2021 		TAILQ_FOREACH(f, &config_finalize_list, f_list)
2022 			rv |= (*f->f_func)(f->f_dev);
2023 	} while (rv != 0);
2024 
2025 	config_finalize_done = 1;
2026 
2027 	/* Now free all the hooks. */
2028 	while ((f = TAILQ_FIRST(&config_finalize_list)) != NULL) {
2029 		TAILQ_REMOVE(&config_finalize_list, f, f_list);
2030 		kmem_free(f, sizeof(*f));
2031 	}
2032 
2033 	KERNEL_UNLOCK_ONE(NULL);
2034 
2035 	errcnt = aprint_get_error_count();
2036 	if ((boothowto & (AB_QUIET|AB_SILENT)) != 0 &&
2037 	    (boothowto & AB_VERBOSE) == 0) {
2038 		mutex_enter(&config_misc_lock);
2039 		if (config_do_twiddle) {
2040 			config_do_twiddle = 0;
2041 			printf_nolog(" done.\n");
2042 		}
2043 		mutex_exit(&config_misc_lock);
2044 		if (errcnt != 0) {
2045 			printf("WARNING: %d error%s while detecting hardware; "
2046 			    "check system log.\n", errcnt,
2047 			    errcnt == 1 ? "" : "s");
2048 		}
2049 	}
2050 }
2051 
2052 void
2053 config_twiddle_init()
2054 {
2055 
2056 	if ((boothowto & (AB_SILENT|AB_VERBOSE)) == AB_SILENT) {
2057 		config_do_twiddle = 1;
2058 	}
2059 	callout_setfunc(&config_twiddle_ch, config_twiddle_fn, NULL);
2060 }
2061 
2062 void
2063 config_twiddle_fn(void *cookie)
2064 {
2065 
2066 	mutex_enter(&config_misc_lock);
2067 	if (config_do_twiddle) {
2068 		twiddle();
2069 		callout_schedule(&config_twiddle_ch, mstohz(100));
2070 	}
2071 	mutex_exit(&config_misc_lock);
2072 }
2073 
2074 static int
2075 config_alldevs_lock(void)
2076 {
2077 	mutex_enter(&alldevs_mtx);
2078 	return 0;
2079 }
2080 
2081 static void
2082 config_alldevs_enter(struct alldevs_foray *af)
2083 {
2084 	TAILQ_INIT(&af->af_garbage);
2085 	af->af_s = config_alldevs_lock();
2086 	config_collect_garbage(&af->af_garbage);
2087 }
2088 
2089 static void
2090 config_alldevs_exit(struct alldevs_foray *af)
2091 {
2092 	config_alldevs_unlock(af->af_s);
2093 	config_dump_garbage(&af->af_garbage);
2094 }
2095 
2096 /*ARGSUSED*/
2097 static void
2098 config_alldevs_unlock(int s)
2099 {
2100 	mutex_exit(&alldevs_mtx);
2101 }
2102 
2103 /*
2104  * device_lookup:
2105  *
2106  *	Look up a device instance for a given driver.
2107  */
2108 device_t
2109 device_lookup(cfdriver_t cd, int unit)
2110 {
2111 	device_t dv;
2112 	int s;
2113 
2114 	s = config_alldevs_lock();
2115 	KASSERT(mutex_owned(&alldevs_mtx));
2116 	if (unit < 0 || unit >= cd->cd_ndevs)
2117 		dv = NULL;
2118 	else if ((dv = cd->cd_devs[unit]) != NULL && dv->dv_del_gen != 0)
2119 		dv = NULL;
2120 	config_alldevs_unlock(s);
2121 
2122 	return dv;
2123 }
2124 
2125 /*
2126  * device_lookup_private:
2127  *
2128  *	Look up a softc instance for a given driver.
2129  */
2130 void *
2131 device_lookup_private(cfdriver_t cd, int unit)
2132 {
2133 
2134 	return device_private(device_lookup(cd, unit));
2135 }
2136 
2137 /*
2138  * device_find_by_xname:
2139  *
2140  *	Returns the device of the given name or NULL if it doesn't exist.
2141  */
2142 device_t
2143 device_find_by_xname(const char *name)
2144 {
2145 	device_t dv;
2146 	deviter_t di;
2147 
2148 	for (dv = deviter_first(&di, 0); dv != NULL; dv = deviter_next(&di)) {
2149 		if (strcmp(device_xname(dv), name) == 0)
2150 			break;
2151 	}
2152 	deviter_release(&di);
2153 
2154 	return dv;
2155 }
2156 
2157 /*
2158  * device_find_by_driver_unit:
2159  *
2160  *	Returns the device of the given driver name and unit or
2161  *	NULL if it doesn't exist.
2162  */
2163 device_t
2164 device_find_by_driver_unit(const char *name, int unit)
2165 {
2166 	struct cfdriver *cd;
2167 
2168 	if ((cd = config_cfdriver_lookup(name)) == NULL)
2169 		return NULL;
2170 	return device_lookup(cd, unit);
2171 }
2172 
2173 /*
2174  * Power management related functions.
2175  */
2176 
2177 bool
2178 device_pmf_is_registered(device_t dev)
2179 {
2180 	return (dev->dv_flags & DVF_POWER_HANDLERS) != 0;
2181 }
2182 
2183 bool
2184 device_pmf_driver_suspend(device_t dev, const pmf_qual_t *qual)
2185 {
2186 	if ((dev->dv_flags & DVF_DRIVER_SUSPENDED) != 0)
2187 		return true;
2188 	if ((dev->dv_flags & DVF_CLASS_SUSPENDED) == 0)
2189 		return false;
2190 	if (pmf_qual_depth(qual) <= DEVACT_LEVEL_DRIVER &&
2191 	    dev->dv_driver_suspend != NULL &&
2192 	    !(*dev->dv_driver_suspend)(dev, qual))
2193 		return false;
2194 
2195 	dev->dv_flags |= DVF_DRIVER_SUSPENDED;
2196 	return true;
2197 }
2198 
2199 bool
2200 device_pmf_driver_resume(device_t dev, const pmf_qual_t *qual)
2201 {
2202 	if ((dev->dv_flags & DVF_DRIVER_SUSPENDED) == 0)
2203 		return true;
2204 	if ((dev->dv_flags & DVF_BUS_SUSPENDED) != 0)
2205 		return false;
2206 	if (pmf_qual_depth(qual) <= DEVACT_LEVEL_DRIVER &&
2207 	    dev->dv_driver_resume != NULL &&
2208 	    !(*dev->dv_driver_resume)(dev, qual))
2209 		return false;
2210 
2211 	dev->dv_flags &= ~DVF_DRIVER_SUSPENDED;
2212 	return true;
2213 }
2214 
2215 bool
2216 device_pmf_driver_shutdown(device_t dev, int how)
2217 {
2218 
2219 	if (*dev->dv_driver_shutdown != NULL &&
2220 	    !(*dev->dv_driver_shutdown)(dev, how))
2221 		return false;
2222 	return true;
2223 }
2224 
2225 bool
2226 device_pmf_driver_register(device_t dev,
2227     bool (*suspend)(device_t, const pmf_qual_t *),
2228     bool (*resume)(device_t, const pmf_qual_t *),
2229     bool (*shutdown)(device_t, int))
2230 {
2231 	dev->dv_driver_suspend = suspend;
2232 	dev->dv_driver_resume = resume;
2233 	dev->dv_driver_shutdown = shutdown;
2234 	dev->dv_flags |= DVF_POWER_HANDLERS;
2235 	return true;
2236 }
2237 
2238 static const char *
2239 curlwp_name(void)
2240 {
2241 	if (curlwp->l_name != NULL)
2242 		return curlwp->l_name;
2243 	else
2244 		return curlwp->l_proc->p_comm;
2245 }
2246 
2247 void
2248 device_pmf_driver_deregister(device_t dev)
2249 {
2250 	device_lock_t dvl = device_getlock(dev);
2251 
2252 	dev->dv_driver_suspend = NULL;
2253 	dev->dv_driver_resume = NULL;
2254 
2255 	mutex_enter(&dvl->dvl_mtx);
2256 	dev->dv_flags &= ~DVF_POWER_HANDLERS;
2257 	while (dvl->dvl_nlock > 0 || dvl->dvl_nwait > 0) {
2258 		/* Wake a thread that waits for the lock.  That
2259 		 * thread will fail to acquire the lock, and then
2260 		 * it will wake the next thread that waits for the
2261 		 * lock, or else it will wake us.
2262 		 */
2263 		cv_signal(&dvl->dvl_cv);
2264 		pmflock_debug(dev, __func__, __LINE__);
2265 		cv_wait(&dvl->dvl_cv, &dvl->dvl_mtx);
2266 		pmflock_debug(dev, __func__, __LINE__);
2267 	}
2268 	mutex_exit(&dvl->dvl_mtx);
2269 }
2270 
2271 bool
2272 device_pmf_driver_child_register(device_t dev)
2273 {
2274 	device_t parent = device_parent(dev);
2275 
2276 	if (parent == NULL || parent->dv_driver_child_register == NULL)
2277 		return true;
2278 	return (*parent->dv_driver_child_register)(dev);
2279 }
2280 
2281 void
2282 device_pmf_driver_set_child_register(device_t dev,
2283     bool (*child_register)(device_t))
2284 {
2285 	dev->dv_driver_child_register = child_register;
2286 }
2287 
2288 static void
2289 pmflock_debug(device_t dev, const char *func, int line)
2290 {
2291 	device_lock_t dvl = device_getlock(dev);
2292 
2293 	aprint_debug_dev(dev, "%s.%d, %s dvl_nlock %d dvl_nwait %d dv_flags %x\n",
2294 	    func, line, curlwp_name(), dvl->dvl_nlock, dvl->dvl_nwait,
2295 	    dev->dv_flags);
2296 }
2297 
2298 static bool
2299 device_pmf_lock1(device_t dev)
2300 {
2301 	device_lock_t dvl = device_getlock(dev);
2302 
2303 	while (device_pmf_is_registered(dev) &&
2304 	    dvl->dvl_nlock > 0 && dvl->dvl_holder != curlwp) {
2305 		dvl->dvl_nwait++;
2306 		pmflock_debug(dev, __func__, __LINE__);
2307 		cv_wait(&dvl->dvl_cv, &dvl->dvl_mtx);
2308 		pmflock_debug(dev, __func__, __LINE__);
2309 		dvl->dvl_nwait--;
2310 	}
2311 	if (!device_pmf_is_registered(dev)) {
2312 		pmflock_debug(dev, __func__, __LINE__);
2313 		/* We could not acquire the lock, but some other thread may
2314 		 * wait for it, also.  Wake that thread.
2315 		 */
2316 		cv_signal(&dvl->dvl_cv);
2317 		return false;
2318 	}
2319 	dvl->dvl_nlock++;
2320 	dvl->dvl_holder = curlwp;
2321 	pmflock_debug(dev, __func__, __LINE__);
2322 	return true;
2323 }
2324 
2325 bool
2326 device_pmf_lock(device_t dev)
2327 {
2328 	bool rc;
2329 	device_lock_t dvl = device_getlock(dev);
2330 
2331 	mutex_enter(&dvl->dvl_mtx);
2332 	rc = device_pmf_lock1(dev);
2333 	mutex_exit(&dvl->dvl_mtx);
2334 
2335 	return rc;
2336 }
2337 
2338 void
2339 device_pmf_unlock(device_t dev)
2340 {
2341 	device_lock_t dvl = device_getlock(dev);
2342 
2343 	KASSERT(dvl->dvl_nlock > 0);
2344 	mutex_enter(&dvl->dvl_mtx);
2345 	if (--dvl->dvl_nlock == 0)
2346 		dvl->dvl_holder = NULL;
2347 	cv_signal(&dvl->dvl_cv);
2348 	pmflock_debug(dev, __func__, __LINE__);
2349 	mutex_exit(&dvl->dvl_mtx);
2350 }
2351 
2352 device_lock_t
2353 device_getlock(device_t dev)
2354 {
2355 	return &dev->dv_lock;
2356 }
2357 
2358 void *
2359 device_pmf_bus_private(device_t dev)
2360 {
2361 	return dev->dv_bus_private;
2362 }
2363 
2364 bool
2365 device_pmf_bus_suspend(device_t dev, const pmf_qual_t *qual)
2366 {
2367 	if ((dev->dv_flags & DVF_BUS_SUSPENDED) != 0)
2368 		return true;
2369 	if ((dev->dv_flags & DVF_CLASS_SUSPENDED) == 0 ||
2370 	    (dev->dv_flags & DVF_DRIVER_SUSPENDED) == 0)
2371 		return false;
2372 	if (pmf_qual_depth(qual) <= DEVACT_LEVEL_BUS &&
2373 	    dev->dv_bus_suspend != NULL &&
2374 	    !(*dev->dv_bus_suspend)(dev, qual))
2375 		return false;
2376 
2377 	dev->dv_flags |= DVF_BUS_SUSPENDED;
2378 	return true;
2379 }
2380 
2381 bool
2382 device_pmf_bus_resume(device_t dev, const pmf_qual_t *qual)
2383 {
2384 	if ((dev->dv_flags & DVF_BUS_SUSPENDED) == 0)
2385 		return true;
2386 	if (pmf_qual_depth(qual) <= DEVACT_LEVEL_BUS &&
2387 	    dev->dv_bus_resume != NULL &&
2388 	    !(*dev->dv_bus_resume)(dev, qual))
2389 		return false;
2390 
2391 	dev->dv_flags &= ~DVF_BUS_SUSPENDED;
2392 	return true;
2393 }
2394 
2395 bool
2396 device_pmf_bus_shutdown(device_t dev, int how)
2397 {
2398 
2399 	if (*dev->dv_bus_shutdown != NULL &&
2400 	    !(*dev->dv_bus_shutdown)(dev, how))
2401 		return false;
2402 	return true;
2403 }
2404 
2405 void
2406 device_pmf_bus_register(device_t dev, void *priv,
2407     bool (*suspend)(device_t, const pmf_qual_t *),
2408     bool (*resume)(device_t, const pmf_qual_t *),
2409     bool (*shutdown)(device_t, int), void (*deregister)(device_t))
2410 {
2411 	dev->dv_bus_private = priv;
2412 	dev->dv_bus_resume = resume;
2413 	dev->dv_bus_suspend = suspend;
2414 	dev->dv_bus_shutdown = shutdown;
2415 	dev->dv_bus_deregister = deregister;
2416 }
2417 
2418 void
2419 device_pmf_bus_deregister(device_t dev)
2420 {
2421 	if (dev->dv_bus_deregister == NULL)
2422 		return;
2423 	(*dev->dv_bus_deregister)(dev);
2424 	dev->dv_bus_private = NULL;
2425 	dev->dv_bus_suspend = NULL;
2426 	dev->dv_bus_resume = NULL;
2427 	dev->dv_bus_deregister = NULL;
2428 }
2429 
2430 void *
2431 device_pmf_class_private(device_t dev)
2432 {
2433 	return dev->dv_class_private;
2434 }
2435 
2436 bool
2437 device_pmf_class_suspend(device_t dev, const pmf_qual_t *qual)
2438 {
2439 	if ((dev->dv_flags & DVF_CLASS_SUSPENDED) != 0)
2440 		return true;
2441 	if (pmf_qual_depth(qual) <= DEVACT_LEVEL_CLASS &&
2442 	    dev->dv_class_suspend != NULL &&
2443 	    !(*dev->dv_class_suspend)(dev, qual))
2444 		return false;
2445 
2446 	dev->dv_flags |= DVF_CLASS_SUSPENDED;
2447 	return true;
2448 }
2449 
2450 bool
2451 device_pmf_class_resume(device_t dev, const pmf_qual_t *qual)
2452 {
2453 	if ((dev->dv_flags & DVF_CLASS_SUSPENDED) == 0)
2454 		return true;
2455 	if ((dev->dv_flags & DVF_BUS_SUSPENDED) != 0 ||
2456 	    (dev->dv_flags & DVF_DRIVER_SUSPENDED) != 0)
2457 		return false;
2458 	if (pmf_qual_depth(qual) <= DEVACT_LEVEL_CLASS &&
2459 	    dev->dv_class_resume != NULL &&
2460 	    !(*dev->dv_class_resume)(dev, qual))
2461 		return false;
2462 
2463 	dev->dv_flags &= ~DVF_CLASS_SUSPENDED;
2464 	return true;
2465 }
2466 
2467 void
2468 device_pmf_class_register(device_t dev, void *priv,
2469     bool (*suspend)(device_t, const pmf_qual_t *),
2470     bool (*resume)(device_t, const pmf_qual_t *),
2471     void (*deregister)(device_t))
2472 {
2473 	dev->dv_class_private = priv;
2474 	dev->dv_class_suspend = suspend;
2475 	dev->dv_class_resume = resume;
2476 	dev->dv_class_deregister = deregister;
2477 }
2478 
2479 void
2480 device_pmf_class_deregister(device_t dev)
2481 {
2482 	if (dev->dv_class_deregister == NULL)
2483 		return;
2484 	(*dev->dv_class_deregister)(dev);
2485 	dev->dv_class_private = NULL;
2486 	dev->dv_class_suspend = NULL;
2487 	dev->dv_class_resume = NULL;
2488 	dev->dv_class_deregister = NULL;
2489 }
2490 
2491 bool
2492 device_active(device_t dev, devactive_t type)
2493 {
2494 	size_t i;
2495 
2496 	if (dev->dv_activity_count == 0)
2497 		return false;
2498 
2499 	for (i = 0; i < dev->dv_activity_count; ++i) {
2500 		if (dev->dv_activity_handlers[i] == NULL)
2501 			break;
2502 		(*dev->dv_activity_handlers[i])(dev, type);
2503 	}
2504 
2505 	return true;
2506 }
2507 
2508 bool
2509 device_active_register(device_t dev, void (*handler)(device_t, devactive_t))
2510 {
2511 	void (**new_handlers)(device_t, devactive_t);
2512 	void (**old_handlers)(device_t, devactive_t);
2513 	size_t i, old_size, new_size;
2514 	int s;
2515 
2516 	old_handlers = dev->dv_activity_handlers;
2517 	old_size = dev->dv_activity_count;
2518 
2519 	for (i = 0; i < old_size; ++i) {
2520 		KASSERT(old_handlers[i] != handler);
2521 		if (old_handlers[i] == NULL) {
2522 			old_handlers[i] = handler;
2523 			return true;
2524 		}
2525 	}
2526 
2527 	new_size = old_size + 4;
2528 	new_handlers = kmem_alloc(sizeof(void *[new_size]), KM_SLEEP);
2529 
2530 	memcpy(new_handlers, old_handlers, sizeof(void *[old_size]));
2531 	new_handlers[old_size] = handler;
2532 	memset(new_handlers + old_size + 1, 0,
2533 	    sizeof(int [new_size - (old_size+1)]));
2534 
2535 	s = splhigh();
2536 	dev->dv_activity_count = new_size;
2537 	dev->dv_activity_handlers = new_handlers;
2538 	splx(s);
2539 
2540 	if (old_handlers != NULL)
2541 		kmem_free(old_handlers, sizeof(void * [old_size]));
2542 
2543 	return true;
2544 }
2545 
2546 void
2547 device_active_deregister(device_t dev, void (*handler)(device_t, devactive_t))
2548 {
2549 	void (**old_handlers)(device_t, devactive_t);
2550 	size_t i, old_size;
2551 	int s;
2552 
2553 	old_handlers = dev->dv_activity_handlers;
2554 	old_size = dev->dv_activity_count;
2555 
2556 	for (i = 0; i < old_size; ++i) {
2557 		if (old_handlers[i] == handler)
2558 			break;
2559 		if (old_handlers[i] == NULL)
2560 			return; /* XXX panic? */
2561 	}
2562 
2563 	if (i == old_size)
2564 		return; /* XXX panic? */
2565 
2566 	for (; i < old_size - 1; ++i) {
2567 		if ((old_handlers[i] = old_handlers[i + 1]) != NULL)
2568 			continue;
2569 
2570 		if (i == 0) {
2571 			s = splhigh();
2572 			dev->dv_activity_count = 0;
2573 			dev->dv_activity_handlers = NULL;
2574 			splx(s);
2575 			kmem_free(old_handlers, sizeof(void *[old_size]));
2576 		}
2577 		return;
2578 	}
2579 	old_handlers[i] = NULL;
2580 }
2581 
2582 /* Return true iff the device_t `dev' exists at generation `gen'. */
2583 static bool
2584 device_exists_at(device_t dv, devgen_t gen)
2585 {
2586 	return (dv->dv_del_gen == 0 || dv->dv_del_gen > gen) &&
2587 	    dv->dv_add_gen <= gen;
2588 }
2589 
2590 static bool
2591 deviter_visits(const deviter_t *di, device_t dv)
2592 {
2593 	return device_exists_at(dv, di->di_gen);
2594 }
2595 
2596 /*
2597  * Device Iteration
2598  *
2599  * deviter_t: a device iterator.  Holds state for a "walk" visiting
2600  *     each device_t's in the device tree.
2601  *
2602  * deviter_init(di, flags): initialize the device iterator `di'
2603  *     to "walk" the device tree.  deviter_next(di) will return
2604  *     the first device_t in the device tree, or NULL if there are
2605  *     no devices.
2606  *
2607  *     `flags' is one or more of DEVITER_F_RW, indicating that the
2608  *     caller intends to modify the device tree by calling
2609  *     config_detach(9) on devices in the order that the iterator
2610  *     returns them; DEVITER_F_ROOT_FIRST, asking for the devices
2611  *     nearest the "root" of the device tree to be returned, first;
2612  *     DEVITER_F_LEAVES_FIRST, asking for the devices furthest from
2613  *     the root of the device tree, first; and DEVITER_F_SHUTDOWN,
2614  *     indicating both that deviter_init() should not respect any
2615  *     locks on the device tree, and that deviter_next(di) may run
2616  *     in more than one LWP before the walk has finished.
2617  *
2618  *     Only one DEVITER_F_RW iterator may be in the device tree at
2619  *     once.
2620  *
2621  *     DEVITER_F_SHUTDOWN implies DEVITER_F_RW.
2622  *
2623  *     Results are undefined if the flags DEVITER_F_ROOT_FIRST and
2624  *     DEVITER_F_LEAVES_FIRST are used in combination.
2625  *
2626  * deviter_first(di, flags): initialize the device iterator `di'
2627  *     and return the first device_t in the device tree, or NULL
2628  *     if there are no devices.  The statement
2629  *
2630  *         dv = deviter_first(di);
2631  *
2632  *     is shorthand for
2633  *
2634  *         deviter_init(di);
2635  *         dv = deviter_next(di);
2636  *
2637  * deviter_next(di): return the next device_t in the device tree,
2638  *     or NULL if there are no more devices.  deviter_next(di)
2639  *     is undefined if `di' was not initialized with deviter_init() or
2640  *     deviter_first().
2641  *
2642  * deviter_release(di): stops iteration (subsequent calls to
2643  *     deviter_next() will return NULL), releases any locks and
2644  *     resources held by the device iterator.
2645  *
2646  * Device iteration does not return device_t's in any particular
2647  * order.  An iterator will never return the same device_t twice.
2648  * Device iteration is guaranteed to complete---i.e., if deviter_next(di)
2649  * is called repeatedly on the same `di', it will eventually return
2650  * NULL.  It is ok to attach/detach devices during device iteration.
2651  */
2652 void
2653 deviter_init(deviter_t *di, deviter_flags_t flags)
2654 {
2655 	device_t dv;
2656 	int s;
2657 
2658 	memset(di, 0, sizeof(*di));
2659 
2660 	s = config_alldevs_lock();
2661 	if ((flags & DEVITER_F_SHUTDOWN) != 0)
2662 		flags |= DEVITER_F_RW;
2663 
2664 	if ((flags & DEVITER_F_RW) != 0)
2665 		alldevs_nwrite++;
2666 	else
2667 		alldevs_nread++;
2668 	di->di_gen = alldevs_gen++;
2669 	config_alldevs_unlock(s);
2670 
2671 	di->di_flags = flags;
2672 
2673 	switch (di->di_flags & (DEVITER_F_LEAVES_FIRST|DEVITER_F_ROOT_FIRST)) {
2674 	case DEVITER_F_LEAVES_FIRST:
2675 		TAILQ_FOREACH(dv, &alldevs, dv_list) {
2676 			if (!deviter_visits(di, dv))
2677 				continue;
2678 			di->di_curdepth = MAX(di->di_curdepth, dv->dv_depth);
2679 		}
2680 		break;
2681 	case DEVITER_F_ROOT_FIRST:
2682 		TAILQ_FOREACH(dv, &alldevs, dv_list) {
2683 			if (!deviter_visits(di, dv))
2684 				continue;
2685 			di->di_maxdepth = MAX(di->di_maxdepth, dv->dv_depth);
2686 		}
2687 		break;
2688 	default:
2689 		break;
2690 	}
2691 
2692 	deviter_reinit(di);
2693 }
2694 
2695 static void
2696 deviter_reinit(deviter_t *di)
2697 {
2698 	if ((di->di_flags & DEVITER_F_RW) != 0)
2699 		di->di_prev = TAILQ_LAST(&alldevs, devicelist);
2700 	else
2701 		di->di_prev = TAILQ_FIRST(&alldevs);
2702 }
2703 
2704 device_t
2705 deviter_first(deviter_t *di, deviter_flags_t flags)
2706 {
2707 	deviter_init(di, flags);
2708 	return deviter_next(di);
2709 }
2710 
2711 static device_t
2712 deviter_next2(deviter_t *di)
2713 {
2714 	device_t dv;
2715 
2716 	dv = di->di_prev;
2717 
2718 	if (dv == NULL)
2719 		return NULL;
2720 
2721 	if ((di->di_flags & DEVITER_F_RW) != 0)
2722 		di->di_prev = TAILQ_PREV(dv, devicelist, dv_list);
2723 	else
2724 		di->di_prev = TAILQ_NEXT(dv, dv_list);
2725 
2726 	return dv;
2727 }
2728 
2729 static device_t
2730 deviter_next1(deviter_t *di)
2731 {
2732 	device_t dv;
2733 
2734 	do {
2735 		dv = deviter_next2(di);
2736 	} while (dv != NULL && !deviter_visits(di, dv));
2737 
2738 	return dv;
2739 }
2740 
2741 device_t
2742 deviter_next(deviter_t *di)
2743 {
2744 	device_t dv = NULL;
2745 
2746 	switch (di->di_flags & (DEVITER_F_LEAVES_FIRST|DEVITER_F_ROOT_FIRST)) {
2747 	case 0:
2748 		return deviter_next1(di);
2749 	case DEVITER_F_LEAVES_FIRST:
2750 		while (di->di_curdepth >= 0) {
2751 			if ((dv = deviter_next1(di)) == NULL) {
2752 				di->di_curdepth--;
2753 				deviter_reinit(di);
2754 			} else if (dv->dv_depth == di->di_curdepth)
2755 				break;
2756 		}
2757 		return dv;
2758 	case DEVITER_F_ROOT_FIRST:
2759 		while (di->di_curdepth <= di->di_maxdepth) {
2760 			if ((dv = deviter_next1(di)) == NULL) {
2761 				di->di_curdepth++;
2762 				deviter_reinit(di);
2763 			} else if (dv->dv_depth == di->di_curdepth)
2764 				break;
2765 		}
2766 		return dv;
2767 	default:
2768 		return NULL;
2769 	}
2770 }
2771 
2772 void
2773 deviter_release(deviter_t *di)
2774 {
2775 	bool rw = (di->di_flags & DEVITER_F_RW) != 0;
2776 	int s;
2777 
2778 	s = config_alldevs_lock();
2779 	if (rw)
2780 		--alldevs_nwrite;
2781 	else
2782 		--alldevs_nread;
2783 	/* XXX wake a garbage-collection thread */
2784 	config_alldevs_unlock(s);
2785 }
2786 
2787 const char *
2788 cfdata_ifattr(const struct cfdata *cf)
2789 {
2790 	return cf->cf_pspec->cfp_iattr;
2791 }
2792 
2793 bool
2794 ifattr_match(const char *snull, const char *t)
2795 {
2796 	return (snull == NULL) || strcmp(snull, t) == 0;
2797 }
2798 
2799 void
2800 null_childdetached(device_t self, device_t child)
2801 {
2802 	/* do nothing */
2803 }
2804 
2805 static void
2806 sysctl_detach_setup(struct sysctllog **clog)
2807 {
2808 	const struct sysctlnode *node = NULL;
2809 
2810 	sysctl_createv(clog, 0, NULL, &node,
2811 		CTLFLAG_PERMANENT,
2812 		CTLTYPE_NODE, "kern", NULL,
2813 		NULL, 0, NULL, 0,
2814 		CTL_KERN, CTL_EOL);
2815 
2816 	if (node == NULL)
2817 		return;
2818 
2819 	sysctl_createv(clog, 0, &node, NULL,
2820 		CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
2821 		CTLTYPE_BOOL, "detachall",
2822 		SYSCTL_DESCR("Detach all devices at shutdown"),
2823 		NULL, 0, &detachall, 0,
2824 		CTL_CREATE, CTL_EOL);
2825 }
2826