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