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