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