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