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