Home | History | Annotate | Line # | Download | only in kern
subr_autoconf.c revision 1.217
      1 /* $NetBSD: subr_autoconf.c,v 1.217 2011/08/02 21:23:24 jmcneill 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.217 2011/08/02 21:23:24 jmcneill 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 
    111 #include <sys/disk.h>
    112 
    113 #include <machine/limits.h>
    114 
    115 /*
    116  * Autoconfiguration subroutines.
    117  */
    118 
    119 /*
    120  * ioconf.c exports exactly two names: cfdata and cfroots.  All system
    121  * devices and drivers are found via these tables.
    122  */
    123 extern struct cfdata cfdata[];
    124 extern const short cfroots[];
    125 
    126 /*
    127  * List of all cfdriver structures.  We use this to detect duplicates
    128  * when other cfdrivers are loaded.
    129  */
    130 struct cfdriverlist allcfdrivers = LIST_HEAD_INITIALIZER(&allcfdrivers);
    131 extern struct cfdriver * const cfdriver_list_initial[];
    132 
    133 /*
    134  * Initial list of cfattach's.
    135  */
    136 extern const struct cfattachinit cfattachinit[];
    137 
    138 /*
    139  * List of cfdata tables.  We always have one such list -- the one
    140  * built statically when the kernel was configured.
    141  */
    142 struct cftablelist allcftables = TAILQ_HEAD_INITIALIZER(allcftables);
    143 static struct cftable initcftable;
    144 
    145 #define	ROOT ((device_t)NULL)
    146 
    147 struct matchinfo {
    148 	cfsubmatch_t fn;
    149 	struct	device *parent;
    150 	const int *locs;
    151 	void	*aux;
    152 	struct	cfdata *match;
    153 	int	pri;
    154 };
    155 
    156 struct alldevs_foray {
    157 	int			af_s;
    158 	struct devicelist	af_garbage;
    159 };
    160 
    161 static char *number(char *, int);
    162 static void mapply(struct matchinfo *, cfdata_t);
    163 static device_t config_devalloc(const device_t, const cfdata_t, const int *);
    164 static void config_devdelete(device_t);
    165 static void config_devunlink(device_t, struct devicelist *);
    166 static void config_makeroom(int, struct cfdriver *);
    167 static void config_devlink(device_t);
    168 static void config_alldevs_unlock(int);
    169 static int config_alldevs_lock(void);
    170 static void config_alldevs_enter(struct alldevs_foray *);
    171 static void config_alldevs_exit(struct alldevs_foray *);
    172 
    173 static void config_collect_garbage(struct devicelist *);
    174 static void config_dump_garbage(struct devicelist *);
    175 
    176 static void pmflock_debug(device_t, const char *, int);
    177 
    178 static device_t deviter_next1(deviter_t *);
    179 static void deviter_reinit(deviter_t *);
    180 
    181 struct deferred_config {
    182 	TAILQ_ENTRY(deferred_config) dc_queue;
    183 	device_t dc_dev;
    184 	void (*dc_func)(device_t);
    185 };
    186 
    187 TAILQ_HEAD(deferred_config_head, deferred_config);
    188 
    189 struct deferred_config_head deferred_config_queue =
    190 	TAILQ_HEAD_INITIALIZER(deferred_config_queue);
    191 struct deferred_config_head interrupt_config_queue =
    192 	TAILQ_HEAD_INITIALIZER(interrupt_config_queue);
    193 int interrupt_config_threads = 8;
    194 struct deferred_config_head mountroot_config_queue =
    195 	TAILQ_HEAD_INITIALIZER(mountroot_config_queue);
    196 int mountroot_config_threads = 2;
    197 static bool root_is_mounted = false;
    198 
    199 static void config_process_deferred(struct deferred_config_head *, device_t);
    200 
    201 /* Hooks to finalize configuration once all real devices have been found. */
    202 struct finalize_hook {
    203 	TAILQ_ENTRY(finalize_hook) f_list;
    204 	int (*f_func)(device_t);
    205 	device_t f_dev;
    206 };
    207 static TAILQ_HEAD(, finalize_hook) config_finalize_list =
    208 	TAILQ_HEAD_INITIALIZER(config_finalize_list);
    209 static int config_finalize_done;
    210 
    211 /* list of all devices */
    212 static struct devicelist alldevs = TAILQ_HEAD_INITIALIZER(alldevs);
    213 static kmutex_t alldevs_mtx;
    214 static volatile bool alldevs_garbage = false;
    215 static volatile devgen_t alldevs_gen = 1;
    216 static volatile int alldevs_nread = 0;
    217 static volatile int alldevs_nwrite = 0;
    218 
    219 static int config_pending;		/* semaphore for mountroot */
    220 static kmutex_t config_misc_lock;
    221 static kcondvar_t config_misc_cv;
    222 
    223 static bool detachall = false;
    224 
    225 #define	STREQ(s1, s2)			\
    226 	(*(s1) == *(s2) && strcmp((s1), (s2)) == 0)
    227 
    228 static bool config_initialized = false;	/* config_init() has been called. */
    229 
    230 static int config_do_twiddle;
    231 static callout_t config_twiddle_ch;
    232 
    233 static void sysctl_detach_setup(struct sysctllog **);
    234 
    235 typedef int (*cfdriver_fn)(struct cfdriver *);
    236 static int
    237 frob_cfdrivervec(struct cfdriver * const *cfdriverv,
    238 	cfdriver_fn drv_do, cfdriver_fn drv_undo,
    239 	const char *style, bool dopanic)
    240 {
    241 	void (*pr)(const char *, ...) = dopanic ? panic : printf;
    242 	int i = 0, error = 0, e2;
    243 
    244 	for (i = 0; cfdriverv[i] != NULL; i++) {
    245 		if ((error = drv_do(cfdriverv[i])) != 0) {
    246 			pr("configure: `%s' driver %s failed: %d",
    247 			    cfdriverv[i]->cd_name, style, error);
    248 			goto bad;
    249 		}
    250 	}
    251 
    252 	KASSERT(error == 0);
    253 	return 0;
    254 
    255  bad:
    256 	printf("\n");
    257 	for (i--; i >= 0; i--) {
    258 		e2 = drv_undo(cfdriverv[i]);
    259 		KASSERT(e2 == 0);
    260 	}
    261 
    262 	return error;
    263 }
    264 
    265 typedef int (*cfattach_fn)(const char *, struct cfattach *);
    266 static int
    267 frob_cfattachvec(const struct cfattachinit *cfattachv,
    268 	cfattach_fn att_do, cfattach_fn att_undo,
    269 	const char *style, bool dopanic)
    270 {
    271 	const struct cfattachinit *cfai = NULL;
    272 	void (*pr)(const char *, ...) = dopanic ? panic : printf;
    273 	int j = 0, error = 0, e2;
    274 
    275 	for (cfai = &cfattachv[0]; cfai->cfai_name != NULL; cfai++) {
    276 		for (j = 0; cfai->cfai_list[j] != NULL; j++) {
    277 			if ((error = att_do(cfai->cfai_name,
    278 			    cfai->cfai_list[j])) != 0) {
    279 				pr("configure: attachment `%s' "
    280 				    "of `%s' driver %s failed: %d",
    281 				    cfai->cfai_list[j]->ca_name,
    282 				    cfai->cfai_name, style, error);
    283 				goto bad;
    284 			}
    285 		}
    286 	}
    287 
    288 	KASSERT(error == 0);
    289 	return 0;
    290 
    291  bad:
    292 	/*
    293 	 * Rollback in reverse order.  dunno if super-important, but
    294 	 * do that anyway.  Although the code looks a little like
    295 	 * someone did a little integration (in the math sense).
    296 	 */
    297 	printf("\n");
    298 	if (cfai) {
    299 		bool last;
    300 
    301 		for (last = false; last == false; ) {
    302 			if (cfai == &cfattachv[0])
    303 				last = true;
    304 			for (j--; j >= 0; j--) {
    305 				e2 = att_undo(cfai->cfai_name,
    306 				    cfai->cfai_list[j]);
    307 				KASSERT(e2 == 0);
    308 			}
    309 			if (!last) {
    310 				cfai--;
    311 				for (j = 0; cfai->cfai_list[j] != NULL; j++)
    312 					;
    313 			}
    314 		}
    315 	}
    316 
    317 	return error;
    318 }
    319 
    320 /*
    321  * Initialize the autoconfiguration data structures.  Normally this
    322  * is done by configure(), but some platforms need to do this very
    323  * early (to e.g. initialize the console).
    324  */
    325 void
    326 config_init(void)
    327 {
    328 
    329 	KASSERT(config_initialized == false);
    330 
    331 	mutex_init(&alldevs_mtx, MUTEX_DEFAULT, IPL_VM);
    332 
    333 	mutex_init(&config_misc_lock, MUTEX_DEFAULT, IPL_NONE);
    334 	cv_init(&config_misc_cv, "cfgmisc");
    335 
    336 	callout_init(&config_twiddle_ch, CALLOUT_MPSAFE);
    337 
    338 	frob_cfdrivervec(cfdriver_list_initial,
    339 	    config_cfdriver_attach, NULL, "bootstrap", true);
    340 	frob_cfattachvec(cfattachinit,
    341 	    config_cfattach_attach, NULL, "bootstrap", true);
    342 
    343 	initcftable.ct_cfdata = cfdata;
    344 	TAILQ_INSERT_TAIL(&allcftables, &initcftable, ct_list);
    345 
    346 	config_initialized = true;
    347 }
    348 
    349 /*
    350  * Init or fini drivers and attachments.  Either all or none
    351  * are processed (via rollback).  It would be nice if this were
    352  * atomic to outside consumers, but with the current state of
    353  * locking ...
    354  */
    355 int
    356 config_init_component(struct cfdriver * const *cfdriverv,
    357 	const struct cfattachinit *cfattachv, struct cfdata *cfdatav)
    358 {
    359 	int error;
    360 
    361 	if ((error = frob_cfdrivervec(cfdriverv,
    362 	    config_cfdriver_attach, config_cfdriver_detach, "init", false))!= 0)
    363 		return error;
    364 	if ((error = frob_cfattachvec(cfattachv,
    365 	    config_cfattach_attach, config_cfattach_detach,
    366 	    "init", false)) != 0) {
    367 		frob_cfdrivervec(cfdriverv,
    368 	            config_cfdriver_detach, NULL, "init rollback", true);
    369 		return error;
    370 	}
    371 	if ((error = config_cfdata_attach(cfdatav, 1)) != 0) {
    372 		frob_cfattachvec(cfattachv,
    373 		    config_cfattach_detach, NULL, "init rollback", true);
    374 		frob_cfdrivervec(cfdriverv,
    375 	            config_cfdriver_detach, NULL, "init rollback", true);
    376 		return error;
    377 	}
    378 
    379 	return 0;
    380 }
    381 
    382 int
    383 config_fini_component(struct cfdriver * const *cfdriverv,
    384 	const struct cfattachinit *cfattachv, struct cfdata *cfdatav)
    385 {
    386 	int error;
    387 
    388 	if ((error = config_cfdata_detach(cfdatav)) != 0)
    389 		return error;
    390 	if ((error = frob_cfattachvec(cfattachv,
    391 	    config_cfattach_detach, config_cfattach_attach,
    392 	    "fini", false)) != 0) {
    393 		if (config_cfdata_attach(cfdatav, 0) != 0)
    394 			panic("config_cfdata fini rollback failed");
    395 		return error;
    396 	}
    397 	if ((error = frob_cfdrivervec(cfdriverv,
    398 	    config_cfdriver_detach, config_cfdriver_attach,
    399 	    "fini", false)) != 0) {
    400 		frob_cfattachvec(cfattachv,
    401 	            config_cfattach_attach, NULL, "fini rollback", true);
    402 		if (config_cfdata_attach(cfdatav, 0) != 0)
    403 			panic("config_cfdata fini rollback failed");
    404 		return error;
    405 	}
    406 
    407 	return 0;
    408 }
    409 
    410 void
    411 config_init_mi(void)
    412 {
    413 
    414 	if (!config_initialized)
    415 		config_init();
    416 
    417 	sysctl_detach_setup(NULL);
    418 }
    419 
    420 void
    421 config_deferred(device_t dev)
    422 {
    423 	config_process_deferred(&deferred_config_queue, dev);
    424 	config_process_deferred(&interrupt_config_queue, dev);
    425 	config_process_deferred(&mountroot_config_queue, dev);
    426 }
    427 
    428 static void
    429 config_interrupts_thread(void *cookie)
    430 {
    431 	struct deferred_config *dc;
    432 
    433 	while ((dc = TAILQ_FIRST(&interrupt_config_queue)) != NULL) {
    434 		TAILQ_REMOVE(&interrupt_config_queue, dc, dc_queue);
    435 		(*dc->dc_func)(dc->dc_dev);
    436 		kmem_free(dc, sizeof(*dc));
    437 		config_pending_decr();
    438 	}
    439 	kthread_exit(0);
    440 }
    441 
    442 void
    443 config_create_interruptthreads()
    444 {
    445 	int i;
    446 
    447 	for (i = 0; i < interrupt_config_threads; i++) {
    448 		(void)kthread_create(PRI_NONE, 0, NULL,
    449 		    config_interrupts_thread, NULL, NULL, "config");
    450 	}
    451 }
    452 
    453 static void
    454 config_mountroot_thread(void *cookie)
    455 {
    456 	struct deferred_config *dc;
    457 
    458 	while ((dc = TAILQ_FIRST(&mountroot_config_queue)) != NULL) {
    459 		TAILQ_REMOVE(&mountroot_config_queue, dc, dc_queue);
    460 		(*dc->dc_func)(dc->dc_dev);
    461 		kmem_free(dc, sizeof(*dc));
    462 	}
    463 	kthread_exit(0);
    464 }
    465 
    466 void
    467 config_create_mountrootthreads()
    468 {
    469 	int i;
    470 
    471 	if (!root_is_mounted)
    472 		root_is_mounted = true;
    473 
    474 	for (i = 0; i < mountroot_config_threads; i++) {
    475 		(void)kthread_create(PRI_NONE, 0, NULL,
    476 		    config_mountroot_thread, NULL, NULL, "config");
    477 	}
    478 }
    479 
    480 /*
    481  * Announce device attach/detach to userland listeners.
    482  */
    483 static void
    484 devmon_report_device(device_t dev, bool isattach)
    485 {
    486 #if NDRVCTL > 0
    487 	prop_dictionary_t ev;
    488 	const char *parent;
    489 	const char *what;
    490 	device_t pdev = device_parent(dev);
    491 
    492 	ev = prop_dictionary_create();
    493 	if (ev == NULL)
    494 		return;
    495 
    496 	what = (isattach ? "device-attach" : "device-detach");
    497 	parent = (pdev == NULL ? "root" : device_xname(pdev));
    498 	if (!prop_dictionary_set_cstring(ev, "device", device_xname(dev)) ||
    499 	    !prop_dictionary_set_cstring(ev, "parent", parent)) {
    500 		prop_object_release(ev);
    501 		return;
    502 	}
    503 
    504 	devmon_insert(what, ev);
    505 #endif
    506 }
    507 
    508 /*
    509  * Add a cfdriver to the system.
    510  */
    511 int
    512 config_cfdriver_attach(struct cfdriver *cd)
    513 {
    514 	struct cfdriver *lcd;
    515 
    516 	/* Make sure this driver isn't already in the system. */
    517 	LIST_FOREACH(lcd, &allcfdrivers, cd_list) {
    518 		if (STREQ(lcd->cd_name, cd->cd_name))
    519 			return EEXIST;
    520 	}
    521 
    522 	LIST_INIT(&cd->cd_attach);
    523 	LIST_INSERT_HEAD(&allcfdrivers, cd, cd_list);
    524 
    525 	return 0;
    526 }
    527 
    528 /*
    529  * Remove a cfdriver from the system.
    530  */
    531 int
    532 config_cfdriver_detach(struct cfdriver *cd)
    533 {
    534 	struct alldevs_foray af;
    535 	int i, rc = 0;
    536 
    537 	config_alldevs_enter(&af);
    538 	/* Make sure there are no active instances. */
    539 	for (i = 0; i < cd->cd_ndevs; i++) {
    540 		if (cd->cd_devs[i] != NULL) {
    541 			rc = EBUSY;
    542 			break;
    543 		}
    544 	}
    545 	config_alldevs_exit(&af);
    546 
    547 	if (rc != 0)
    548 		return rc;
    549 
    550 	/* ...and no attachments loaded. */
    551 	if (LIST_EMPTY(&cd->cd_attach) == 0)
    552 		return EBUSY;
    553 
    554 	LIST_REMOVE(cd, cd_list);
    555 
    556 	KASSERT(cd->cd_devs == NULL);
    557 
    558 	return 0;
    559 }
    560 
    561 /*
    562  * Look up a cfdriver by name.
    563  */
    564 struct cfdriver *
    565 config_cfdriver_lookup(const char *name)
    566 {
    567 	struct cfdriver *cd;
    568 
    569 	LIST_FOREACH(cd, &allcfdrivers, cd_list) {
    570 		if (STREQ(cd->cd_name, name))
    571 			return cd;
    572 	}
    573 
    574 	return NULL;
    575 }
    576 
    577 /*
    578  * Add a cfattach to the specified driver.
    579  */
    580 int
    581 config_cfattach_attach(const char *driver, struct cfattach *ca)
    582 {
    583 	struct cfattach *lca;
    584 	struct cfdriver *cd;
    585 
    586 	cd = config_cfdriver_lookup(driver);
    587 	if (cd == NULL)
    588 		return ESRCH;
    589 
    590 	/* Make sure this attachment isn't already on this driver. */
    591 	LIST_FOREACH(lca, &cd->cd_attach, ca_list) {
    592 		if (STREQ(lca->ca_name, ca->ca_name))
    593 			return EEXIST;
    594 	}
    595 
    596 	LIST_INSERT_HEAD(&cd->cd_attach, ca, ca_list);
    597 
    598 	return 0;
    599 }
    600 
    601 /*
    602  * Remove a cfattach from the specified driver.
    603  */
    604 int
    605 config_cfattach_detach(const char *driver, struct cfattach *ca)
    606 {
    607 	struct alldevs_foray af;
    608 	struct cfdriver *cd;
    609 	device_t dev;
    610 	int i, rc = 0;
    611 
    612 	cd = config_cfdriver_lookup(driver);
    613 	if (cd == NULL)
    614 		return ESRCH;
    615 
    616 	config_alldevs_enter(&af);
    617 	/* Make sure there are no active instances. */
    618 	for (i = 0; i < cd->cd_ndevs; i++) {
    619 		if ((dev = cd->cd_devs[i]) == NULL)
    620 			continue;
    621 		if (dev->dv_cfattach == ca) {
    622 			rc = EBUSY;
    623 			break;
    624 		}
    625 	}
    626 	config_alldevs_exit(&af);
    627 
    628 	if (rc != 0)
    629 		return rc;
    630 
    631 	LIST_REMOVE(ca, ca_list);
    632 
    633 	return 0;
    634 }
    635 
    636 /*
    637  * Look up a cfattach by name.
    638  */
    639 static struct cfattach *
    640 config_cfattach_lookup_cd(struct cfdriver *cd, const char *atname)
    641 {
    642 	struct cfattach *ca;
    643 
    644 	LIST_FOREACH(ca, &cd->cd_attach, ca_list) {
    645 		if (STREQ(ca->ca_name, atname))
    646 			return ca;
    647 	}
    648 
    649 	return NULL;
    650 }
    651 
    652 /*
    653  * Look up a cfattach by driver/attachment name.
    654  */
    655 struct cfattach *
    656 config_cfattach_lookup(const char *name, const char *atname)
    657 {
    658 	struct cfdriver *cd;
    659 
    660 	cd = config_cfdriver_lookup(name);
    661 	if (cd == NULL)
    662 		return NULL;
    663 
    664 	return config_cfattach_lookup_cd(cd, atname);
    665 }
    666 
    667 /*
    668  * Apply the matching function and choose the best.  This is used
    669  * a few times and we want to keep the code small.
    670  */
    671 static void
    672 mapply(struct matchinfo *m, cfdata_t cf)
    673 {
    674 	int pri;
    675 
    676 	if (m->fn != NULL) {
    677 		pri = (*m->fn)(m->parent, cf, m->locs, m->aux);
    678 	} else {
    679 		pri = config_match(m->parent, cf, m->aux);
    680 	}
    681 	if (pri > m->pri) {
    682 		m->match = cf;
    683 		m->pri = pri;
    684 	}
    685 }
    686 
    687 int
    688 config_stdsubmatch(device_t parent, cfdata_t cf, const int *locs, void *aux)
    689 {
    690 	const struct cfiattrdata *ci;
    691 	const struct cflocdesc *cl;
    692 	int nlocs, i;
    693 
    694 	ci = cfiattr_lookup(cfdata_ifattr(cf), parent->dv_cfdriver);
    695 	KASSERT(ci);
    696 	nlocs = ci->ci_loclen;
    697 	KASSERT(!nlocs || locs);
    698 	for (i = 0; i < nlocs; i++) {
    699 		cl = &ci->ci_locdesc[i];
    700 		/* !cld_defaultstr means no default value */
    701 		if ((!(cl->cld_defaultstr)
    702 		     || (cf->cf_loc[i] != cl->cld_default))
    703 		    && cf->cf_loc[i] != locs[i])
    704 			return 0;
    705 	}
    706 
    707 	return config_match(parent, cf, aux);
    708 }
    709 
    710 /*
    711  * Helper function: check whether the driver supports the interface attribute
    712  * and return its descriptor structure.
    713  */
    714 static const struct cfiattrdata *
    715 cfdriver_get_iattr(const struct cfdriver *cd, const char *ia)
    716 {
    717 	const struct cfiattrdata * const *cpp;
    718 
    719 	if (cd->cd_attrs == NULL)
    720 		return 0;
    721 
    722 	for (cpp = cd->cd_attrs; *cpp; cpp++) {
    723 		if (STREQ((*cpp)->ci_name, ia)) {
    724 			/* Match. */
    725 			return *cpp;
    726 		}
    727 	}
    728 	return 0;
    729 }
    730 
    731 /*
    732  * Lookup an interface attribute description by name.
    733  * If the driver is given, consider only its supported attributes.
    734  */
    735 const struct cfiattrdata *
    736 cfiattr_lookup(const char *name, const struct cfdriver *cd)
    737 {
    738 	const struct cfdriver *d;
    739 	const struct cfiattrdata *ia;
    740 
    741 	if (cd)
    742 		return cfdriver_get_iattr(cd, name);
    743 
    744 	LIST_FOREACH(d, &allcfdrivers, cd_list) {
    745 		ia = cfdriver_get_iattr(d, name);
    746 		if (ia)
    747 			return ia;
    748 	}
    749 	return 0;
    750 }
    751 
    752 /*
    753  * Determine if `parent' is a potential parent for a device spec based
    754  * on `cfp'.
    755  */
    756 static int
    757 cfparent_match(const device_t parent, const struct cfparent *cfp)
    758 {
    759 	struct cfdriver *pcd;
    760 
    761 	/* We don't match root nodes here. */
    762 	if (cfp == NULL)
    763 		return 0;
    764 
    765 	pcd = parent->dv_cfdriver;
    766 	KASSERT(pcd != NULL);
    767 
    768 	/*
    769 	 * First, ensure this parent has the correct interface
    770 	 * attribute.
    771 	 */
    772 	if (!cfdriver_get_iattr(pcd, cfp->cfp_iattr))
    773 		return 0;
    774 
    775 	/*
    776 	 * If no specific parent device instance was specified (i.e.
    777 	 * we're attaching to the attribute only), we're done!
    778 	 */
    779 	if (cfp->cfp_parent == NULL)
    780 		return 1;
    781 
    782 	/*
    783 	 * Check the parent device's name.
    784 	 */
    785 	if (STREQ(pcd->cd_name, cfp->cfp_parent) == 0)
    786 		return 0;	/* not the same parent */
    787 
    788 	/*
    789 	 * Make sure the unit number matches.
    790 	 */
    791 	if (cfp->cfp_unit == DVUNIT_ANY ||	/* wildcard */
    792 	    cfp->cfp_unit == parent->dv_unit)
    793 		return 1;
    794 
    795 	/* Unit numbers don't match. */
    796 	return 0;
    797 }
    798 
    799 /*
    800  * Helper for config_cfdata_attach(): check all devices whether it could be
    801  * parent any attachment in the config data table passed, and rescan.
    802  */
    803 static void
    804 rescan_with_cfdata(const struct cfdata *cf)
    805 {
    806 	device_t d;
    807 	const struct cfdata *cf1;
    808 	deviter_t di;
    809 
    810 
    811 	/*
    812 	 * "alldevs" is likely longer than a modules's cfdata, so make it
    813 	 * the outer loop.
    814 	 */
    815 	for (d = deviter_first(&di, 0); d != NULL; d = deviter_next(&di)) {
    816 
    817 		if (!(d->dv_cfattach->ca_rescan))
    818 			continue;
    819 
    820 		for (cf1 = cf; cf1->cf_name; cf1++) {
    821 
    822 			if (!cfparent_match(d, cf1->cf_pspec))
    823 				continue;
    824 
    825 			(*d->dv_cfattach->ca_rescan)(d,
    826 				cfdata_ifattr(cf1), cf1->cf_loc);
    827 
    828 			config_deferred(d);
    829 		}
    830 	}
    831 	deviter_release(&di);
    832 }
    833 
    834 /*
    835  * Attach a supplemental config data table and rescan potential
    836  * parent devices if required.
    837  */
    838 int
    839 config_cfdata_attach(cfdata_t cf, int scannow)
    840 {
    841 	struct cftable *ct;
    842 
    843 	ct = kmem_alloc(sizeof(*ct), KM_SLEEP);
    844 	ct->ct_cfdata = cf;
    845 	TAILQ_INSERT_TAIL(&allcftables, ct, ct_list);
    846 
    847 	if (scannow)
    848 		rescan_with_cfdata(cf);
    849 
    850 	return 0;
    851 }
    852 
    853 /*
    854  * Helper for config_cfdata_detach: check whether a device is
    855  * found through any attachment in the config data table.
    856  */
    857 static int
    858 dev_in_cfdata(const struct device *d, const struct cfdata *cf)
    859 {
    860 	const struct cfdata *cf1;
    861 
    862 	for (cf1 = cf; cf1->cf_name; cf1++)
    863 		if (d->dv_cfdata == cf1)
    864 			return 1;
    865 
    866 	return 0;
    867 }
    868 
    869 /*
    870  * Detach a supplemental config data table. Detach all devices found
    871  * through that table (and thus keeping references to it) before.
    872  */
    873 int
    874 config_cfdata_detach(cfdata_t cf)
    875 {
    876 	device_t d;
    877 	int error = 0;
    878 	struct cftable *ct;
    879 	deviter_t di;
    880 
    881 	for (d = deviter_first(&di, DEVITER_F_RW); d != NULL;
    882 	     d = deviter_next(&di)) {
    883 		if (!dev_in_cfdata(d, cf))
    884 			continue;
    885 		if ((error = config_detach(d, 0)) != 0)
    886 			break;
    887 	}
    888 	deviter_release(&di);
    889 	if (error) {
    890 		aprint_error_dev(d, "unable to detach instance\n");
    891 		return error;
    892 	}
    893 
    894 	TAILQ_FOREACH(ct, &allcftables, ct_list) {
    895 		if (ct->ct_cfdata == cf) {
    896 			TAILQ_REMOVE(&allcftables, ct, ct_list);
    897 			kmem_free(ct, sizeof(*ct));
    898 			return 0;
    899 		}
    900 	}
    901 
    902 	/* not found -- shouldn't happen */
    903 	return EINVAL;
    904 }
    905 
    906 /*
    907  * Invoke the "match" routine for a cfdata entry on behalf of
    908  * an external caller, usually a "submatch" routine.
    909  */
    910 int
    911 config_match(device_t parent, cfdata_t cf, void *aux)
    912 {
    913 	struct cfattach *ca;
    914 
    915 	ca = config_cfattach_lookup(cf->cf_name, cf->cf_atname);
    916 	if (ca == NULL) {
    917 		/* No attachment for this entry, oh well. */
    918 		return 0;
    919 	}
    920 
    921 	return (*ca->ca_match)(parent, cf, aux);
    922 }
    923 
    924 /*
    925  * Iterate over all potential children of some device, calling the given
    926  * function (default being the child's match function) for each one.
    927  * Nonzero returns are matches; the highest value returned is considered
    928  * the best match.  Return the `found child' if we got a match, or NULL
    929  * otherwise.  The `aux' pointer is simply passed on through.
    930  *
    931  * Note that this function is designed so that it can be used to apply
    932  * an arbitrary function to all potential children (its return value
    933  * can be ignored).
    934  */
    935 cfdata_t
    936 config_search_loc(cfsubmatch_t fn, device_t parent,
    937 		  const char *ifattr, const int *locs, void *aux)
    938 {
    939 	struct cftable *ct;
    940 	cfdata_t cf;
    941 	struct matchinfo m;
    942 
    943 	KASSERT(config_initialized);
    944 	KASSERT(!ifattr || cfdriver_get_iattr(parent->dv_cfdriver, ifattr));
    945 
    946 	m.fn = fn;
    947 	m.parent = parent;
    948 	m.locs = locs;
    949 	m.aux = aux;
    950 	m.match = NULL;
    951 	m.pri = 0;
    952 
    953 	TAILQ_FOREACH(ct, &allcftables, ct_list) {
    954 		for (cf = ct->ct_cfdata; cf->cf_name; cf++) {
    955 
    956 			/* We don't match root nodes here. */
    957 			if (!cf->cf_pspec)
    958 				continue;
    959 
    960 			/*
    961 			 * Skip cf if no longer eligible, otherwise scan
    962 			 * through parents for one matching `parent', and
    963 			 * try match function.
    964 			 */
    965 			if (cf->cf_fstate == FSTATE_FOUND)
    966 				continue;
    967 			if (cf->cf_fstate == FSTATE_DNOTFOUND ||
    968 			    cf->cf_fstate == FSTATE_DSTAR)
    969 				continue;
    970 
    971 			/*
    972 			 * If an interface attribute was specified,
    973 			 * consider only children which attach to
    974 			 * that attribute.
    975 			 */
    976 			if (ifattr && !STREQ(ifattr, cfdata_ifattr(cf)))
    977 				continue;
    978 
    979 			if (cfparent_match(parent, cf->cf_pspec))
    980 				mapply(&m, cf);
    981 		}
    982 	}
    983 	return m.match;
    984 }
    985 
    986 cfdata_t
    987 config_search_ia(cfsubmatch_t fn, device_t parent, const char *ifattr,
    988     void *aux)
    989 {
    990 
    991 	return config_search_loc(fn, parent, ifattr, NULL, aux);
    992 }
    993 
    994 /*
    995  * Find the given root device.
    996  * This is much like config_search, but there is no parent.
    997  * Don't bother with multiple cfdata tables; the root node
    998  * must always be in the initial table.
    999  */
   1000 cfdata_t
   1001 config_rootsearch(cfsubmatch_t fn, const char *rootname, void *aux)
   1002 {
   1003 	cfdata_t cf;
   1004 	const short *p;
   1005 	struct matchinfo m;
   1006 
   1007 	m.fn = fn;
   1008 	m.parent = ROOT;
   1009 	m.aux = aux;
   1010 	m.match = NULL;
   1011 	m.pri = 0;
   1012 	m.locs = 0;
   1013 	/*
   1014 	 * Look at root entries for matching name.  We do not bother
   1015 	 * with found-state here since only one root should ever be
   1016 	 * searched (and it must be done first).
   1017 	 */
   1018 	for (p = cfroots; *p >= 0; p++) {
   1019 		cf = &cfdata[*p];
   1020 		if (strcmp(cf->cf_name, rootname) == 0)
   1021 			mapply(&m, cf);
   1022 	}
   1023 	return m.match;
   1024 }
   1025 
   1026 static const char * const msgs[3] = { "", " not configured\n", " unsupported\n" };
   1027 
   1028 /*
   1029  * The given `aux' argument describes a device that has been found
   1030  * on the given parent, but not necessarily configured.  Locate the
   1031  * configuration data for that device (using the submatch function
   1032  * provided, or using candidates' cd_match configuration driver
   1033  * functions) and attach it, and return true.  If the device was
   1034  * not configured, call the given `print' function and return 0.
   1035  */
   1036 device_t
   1037 config_found_sm_loc(device_t parent,
   1038 		const char *ifattr, const int *locs, void *aux,
   1039 		cfprint_t print, cfsubmatch_t submatch)
   1040 {
   1041 	cfdata_t cf;
   1042 
   1043 	if ((cf = config_search_loc(submatch, parent, ifattr, locs, aux)))
   1044 		return(config_attach_loc(parent, cf, locs, aux, print));
   1045 	if (print) {
   1046 		if (config_do_twiddle && cold)
   1047 			twiddle();
   1048 		aprint_normal("%s", msgs[(*print)(aux, device_xname(parent))]);
   1049 	}
   1050 
   1051 	return NULL;
   1052 }
   1053 
   1054 device_t
   1055 config_found_ia(device_t parent, const char *ifattr, void *aux,
   1056     cfprint_t print)
   1057 {
   1058 
   1059 	return config_found_sm_loc(parent, ifattr, NULL, aux, print, NULL);
   1060 }
   1061 
   1062 device_t
   1063 config_found(device_t parent, void *aux, cfprint_t print)
   1064 {
   1065 
   1066 	return config_found_sm_loc(parent, NULL, NULL, aux, print, NULL);
   1067 }
   1068 
   1069 /*
   1070  * As above, but for root devices.
   1071  */
   1072 device_t
   1073 config_rootfound(const char *rootname, void *aux)
   1074 {
   1075 	cfdata_t cf;
   1076 
   1077 	if ((cf = config_rootsearch((cfsubmatch_t)NULL, rootname, aux)) != NULL)
   1078 		return config_attach(ROOT, cf, aux, (cfprint_t)NULL);
   1079 	aprint_error("root device %s not configured\n", rootname);
   1080 	return NULL;
   1081 }
   1082 
   1083 /* just like sprintf(buf, "%d") except that it works from the end */
   1084 static char *
   1085 number(char *ep, int n)
   1086 {
   1087 
   1088 	*--ep = 0;
   1089 	while (n >= 10) {
   1090 		*--ep = (n % 10) + '0';
   1091 		n /= 10;
   1092 	}
   1093 	*--ep = n + '0';
   1094 	return ep;
   1095 }
   1096 
   1097 /*
   1098  * Expand the size of the cd_devs array if necessary.
   1099  *
   1100  * The caller must hold alldevs_mtx. config_makeroom() may release and
   1101  * re-acquire alldevs_mtx, so callers should re-check conditions such
   1102  * as alldevs_nwrite == 0 and alldevs_nread == 0 when config_makeroom()
   1103  * returns.
   1104  */
   1105 static void
   1106 config_makeroom(int n, struct cfdriver *cd)
   1107 {
   1108 	int old, new;
   1109 	device_t *osp, *nsp;
   1110 
   1111 	alldevs_nwrite++;
   1112 
   1113 	for (new = MAX(4, cd->cd_ndevs); new <= n; new += new)
   1114 		;
   1115 
   1116 	while (n >= cd->cd_ndevs) {
   1117 		/*
   1118 		 * Need to expand the array.
   1119 		 */
   1120 		old = cd->cd_ndevs;
   1121 		osp = cd->cd_devs;
   1122 
   1123 		/* Release alldevs_mtx around allocation, which may
   1124 		 * sleep.
   1125 		 */
   1126 		mutex_exit(&alldevs_mtx);
   1127 		nsp = kmem_alloc(sizeof(device_t[new]), KM_SLEEP);
   1128 		if (nsp == NULL)
   1129 			panic("%s: could not expand cd_devs", __func__);
   1130 		mutex_enter(&alldevs_mtx);
   1131 
   1132 		/* If another thread moved the array while we did
   1133 		 * not hold alldevs_mtx, try again.
   1134 		 */
   1135 		if (cd->cd_devs != osp) {
   1136 			mutex_exit(&alldevs_mtx);
   1137 			kmem_free(nsp, sizeof(device_t[new]));
   1138 			mutex_enter(&alldevs_mtx);
   1139 			continue;
   1140 		}
   1141 
   1142 		memset(nsp + old, 0, sizeof(device_t[new - old]));
   1143 		if (old != 0)
   1144 			memcpy(nsp, cd->cd_devs, sizeof(device_t[old]));
   1145 
   1146 		cd->cd_ndevs = new;
   1147 		cd->cd_devs = nsp;
   1148 		if (old != 0) {
   1149 			mutex_exit(&alldevs_mtx);
   1150 			kmem_free(osp, sizeof(device_t[old]));
   1151 			mutex_enter(&alldevs_mtx);
   1152 		}
   1153 	}
   1154 	alldevs_nwrite--;
   1155 }
   1156 
   1157 /*
   1158  * Put dev into the devices list.
   1159  */
   1160 static void
   1161 config_devlink(device_t dev)
   1162 {
   1163 	int s;
   1164 
   1165 	s = config_alldevs_lock();
   1166 
   1167 	KASSERT(device_cfdriver(dev)->cd_devs[dev->dv_unit] == dev);
   1168 
   1169 	dev->dv_add_gen = alldevs_gen;
   1170 	/* It is safe to add a device to the tail of the list while
   1171 	 * readers and writers are in the list.
   1172 	 */
   1173 	TAILQ_INSERT_TAIL(&alldevs, dev, dv_list);
   1174 	config_alldevs_unlock(s);
   1175 }
   1176 
   1177 static void
   1178 config_devfree(device_t dev)
   1179 {
   1180 	int priv = (dev->dv_flags & DVF_PRIV_ALLOC);
   1181 
   1182 	if (dev->dv_cfattach->ca_devsize > 0)
   1183 		kmem_free(dev->dv_private, dev->dv_cfattach->ca_devsize);
   1184 	if (priv)
   1185 		kmem_free(dev, sizeof(*dev));
   1186 }
   1187 
   1188 /*
   1189  * Caller must hold alldevs_mtx.
   1190  */
   1191 static void
   1192 config_devunlink(device_t dev, struct devicelist *garbage)
   1193 {
   1194 	struct device_garbage *dg = &dev->dv_garbage;
   1195 	cfdriver_t cd = device_cfdriver(dev);
   1196 	int i;
   1197 
   1198 	KASSERT(mutex_owned(&alldevs_mtx));
   1199 
   1200  	/* Unlink from device list.  Link to garbage list. */
   1201 	TAILQ_REMOVE(&alldevs, dev, dv_list);
   1202 	TAILQ_INSERT_TAIL(garbage, dev, dv_list);
   1203 
   1204 	/* Remove from cfdriver's array. */
   1205 	cd->cd_devs[dev->dv_unit] = NULL;
   1206 
   1207 	/*
   1208 	 * If the device now has no units in use, unlink its softc array.
   1209 	 */
   1210 	for (i = 0; i < cd->cd_ndevs; i++) {
   1211 		if (cd->cd_devs[i] != NULL)
   1212 			break;
   1213 	}
   1214 	/* Nothing found.  Unlink, now.  Deallocate, later. */
   1215 	if (i == cd->cd_ndevs) {
   1216 		dg->dg_ndevs = cd->cd_ndevs;
   1217 		dg->dg_devs = cd->cd_devs;
   1218 		cd->cd_devs = NULL;
   1219 		cd->cd_ndevs = 0;
   1220 	}
   1221 }
   1222 
   1223 static void
   1224 config_devdelete(device_t dev)
   1225 {
   1226 	struct device_garbage *dg = &dev->dv_garbage;
   1227 	device_lock_t dvl = device_getlock(dev);
   1228 
   1229 	if (dg->dg_devs != NULL)
   1230 		kmem_free(dg->dg_devs, sizeof(device_t[dg->dg_ndevs]));
   1231 
   1232 	cv_destroy(&dvl->dvl_cv);
   1233 	mutex_destroy(&dvl->dvl_mtx);
   1234 
   1235 	KASSERT(dev->dv_properties != NULL);
   1236 	prop_object_release(dev->dv_properties);
   1237 
   1238 	if (dev->dv_activity_handlers)
   1239 		panic("%s with registered handlers", __func__);
   1240 
   1241 	if (dev->dv_locators) {
   1242 		size_t amount = *--dev->dv_locators;
   1243 		kmem_free(dev->dv_locators, amount);
   1244 	}
   1245 
   1246 	config_devfree(dev);
   1247 }
   1248 
   1249 static int
   1250 config_unit_nextfree(cfdriver_t cd, cfdata_t cf)
   1251 {
   1252 	int unit;
   1253 
   1254 	if (cf->cf_fstate == FSTATE_STAR) {
   1255 		for (unit = cf->cf_unit; unit < cd->cd_ndevs; unit++)
   1256 			if (cd->cd_devs[unit] == NULL)
   1257 				break;
   1258 		/*
   1259 		 * unit is now the unit of the first NULL device pointer,
   1260 		 * or max(cd->cd_ndevs,cf->cf_unit).
   1261 		 */
   1262 	} else {
   1263 		unit = cf->cf_unit;
   1264 		if (unit < cd->cd_ndevs && cd->cd_devs[unit] != NULL)
   1265 			unit = -1;
   1266 	}
   1267 	return unit;
   1268 }
   1269 
   1270 static int
   1271 config_unit_alloc(device_t dev, cfdriver_t cd, cfdata_t cf)
   1272 {
   1273 	struct alldevs_foray af;
   1274 	int unit;
   1275 
   1276 	config_alldevs_enter(&af);
   1277 	for (;;) {
   1278 		unit = config_unit_nextfree(cd, cf);
   1279 		if (unit == -1)
   1280 			break;
   1281 		if (unit < cd->cd_ndevs) {
   1282 			cd->cd_devs[unit] = dev;
   1283 			dev->dv_unit = unit;
   1284 			break;
   1285 		}
   1286 		config_makeroom(unit, cd);
   1287 	}
   1288 	config_alldevs_exit(&af);
   1289 
   1290 	return unit;
   1291 }
   1292 
   1293 static device_t
   1294 config_devalloc(const device_t parent, const cfdata_t cf, const int *locs)
   1295 {
   1296 	cfdriver_t cd;
   1297 	cfattach_t ca;
   1298 	size_t lname, lunit;
   1299 	const char *xunit;
   1300 	int myunit;
   1301 	char num[10];
   1302 	device_t dev;
   1303 	void *dev_private;
   1304 	const struct cfiattrdata *ia;
   1305 	device_lock_t dvl;
   1306 
   1307 	cd = config_cfdriver_lookup(cf->cf_name);
   1308 	if (cd == NULL)
   1309 		return NULL;
   1310 
   1311 	ca = config_cfattach_lookup_cd(cd, cf->cf_atname);
   1312 	if (ca == NULL)
   1313 		return NULL;
   1314 
   1315 	if ((ca->ca_flags & DVF_PRIV_ALLOC) == 0 &&
   1316 	    ca->ca_devsize < sizeof(struct device))
   1317 		panic("config_devalloc: %s", cf->cf_atname);
   1318 
   1319 	/* get memory for all device vars */
   1320 	KASSERT((ca->ca_flags & DVF_PRIV_ALLOC) || ca->ca_devsize >= sizeof(struct device));
   1321 	if (ca->ca_devsize > 0) {
   1322 		dev_private = kmem_zalloc(ca->ca_devsize, KM_SLEEP);
   1323 		if (dev_private == NULL)
   1324 			panic("config_devalloc: memory allocation for device softc failed");
   1325 	} else {
   1326 		KASSERT(ca->ca_flags & DVF_PRIV_ALLOC);
   1327 		dev_private = NULL;
   1328 	}
   1329 
   1330 	if ((ca->ca_flags & DVF_PRIV_ALLOC) != 0) {
   1331 		dev = kmem_zalloc(sizeof(*dev), KM_SLEEP);
   1332 	} else {
   1333 		dev = dev_private;
   1334 #ifdef DIAGNOSTIC
   1335 		printf("%s has not been converted to device_t\n", cd->cd_name);
   1336 #endif
   1337 	}
   1338 	if (dev == NULL)
   1339 		panic("config_devalloc: memory allocation for device_t failed");
   1340 
   1341 	dev->dv_class = cd->cd_class;
   1342 	dev->dv_cfdata = cf;
   1343 	dev->dv_cfdriver = cd;
   1344 	dev->dv_cfattach = ca;
   1345 	dev->dv_activity_count = 0;
   1346 	dev->dv_activity_handlers = NULL;
   1347 	dev->dv_private = dev_private;
   1348 	dev->dv_flags = ca->ca_flags;	/* inherit flags from class */
   1349 
   1350 	myunit = config_unit_alloc(dev, cd, cf);
   1351 	if (myunit == -1) {
   1352 		config_devfree(dev);
   1353 		return NULL;
   1354 	}
   1355 
   1356 	/* compute length of name and decimal expansion of unit number */
   1357 	lname = strlen(cd->cd_name);
   1358 	xunit = number(&num[sizeof(num)], myunit);
   1359 	lunit = &num[sizeof(num)] - xunit;
   1360 	if (lname + lunit > sizeof(dev->dv_xname))
   1361 		panic("config_devalloc: device name too long");
   1362 
   1363 	dvl = device_getlock(dev);
   1364 
   1365 	mutex_init(&dvl->dvl_mtx, MUTEX_DEFAULT, IPL_NONE);
   1366 	cv_init(&dvl->dvl_cv, "pmfsusp");
   1367 
   1368 	memcpy(dev->dv_xname, cd->cd_name, lname);
   1369 	memcpy(dev->dv_xname + lname, xunit, lunit);
   1370 	dev->dv_parent = parent;
   1371 	if (parent != NULL)
   1372 		dev->dv_depth = parent->dv_depth + 1;
   1373 	else
   1374 		dev->dv_depth = 0;
   1375 	dev->dv_flags |= DVF_ACTIVE;	/* always initially active */
   1376 	if (locs) {
   1377 		KASSERT(parent); /* no locators at root */
   1378 		ia = cfiattr_lookup(cfdata_ifattr(cf), parent->dv_cfdriver);
   1379 		dev->dv_locators =
   1380 		    kmem_alloc(sizeof(int [ia->ci_loclen + 1]), KM_SLEEP);
   1381 		*dev->dv_locators++ = sizeof(int [ia->ci_loclen + 1]);
   1382 		memcpy(dev->dv_locators, locs, sizeof(int [ia->ci_loclen]));
   1383 	}
   1384 	dev->dv_properties = prop_dictionary_create();
   1385 	KASSERT(dev->dv_properties != NULL);
   1386 
   1387 	prop_dictionary_set_cstring_nocopy(dev->dv_properties,
   1388 	    "device-driver", dev->dv_cfdriver->cd_name);
   1389 	prop_dictionary_set_uint16(dev->dv_properties,
   1390 	    "device-unit", dev->dv_unit);
   1391 
   1392 	return dev;
   1393 }
   1394 
   1395 /*
   1396  * Attach a found device.
   1397  */
   1398 device_t
   1399 config_attach_loc(device_t parent, cfdata_t cf,
   1400 	const int *locs, void *aux, cfprint_t print)
   1401 {
   1402 	device_t dev;
   1403 	struct cftable *ct;
   1404 	const char *drvname;
   1405 
   1406 	dev = config_devalloc(parent, cf, locs);
   1407 	if (!dev)
   1408 		panic("config_attach: allocation of device softc failed");
   1409 
   1410 	/* XXX redundant - see below? */
   1411 	if (cf->cf_fstate != FSTATE_STAR) {
   1412 		KASSERT(cf->cf_fstate == FSTATE_NOTFOUND);
   1413 		cf->cf_fstate = FSTATE_FOUND;
   1414 	}
   1415 
   1416 	config_devlink(dev);
   1417 
   1418 	if (config_do_twiddle && cold)
   1419 		twiddle();
   1420 	else
   1421 		aprint_naive("Found ");
   1422 	/*
   1423 	 * We want the next two printfs for normal, verbose, and quiet,
   1424 	 * but not silent (in which case, we're twiddling, instead).
   1425 	 */
   1426 	if (parent == ROOT) {
   1427 		aprint_naive("%s (root)", device_xname(dev));
   1428 		aprint_normal("%s (root)", device_xname(dev));
   1429 	} else {
   1430 		aprint_naive("%s at %s", device_xname(dev), device_xname(parent));
   1431 		aprint_normal("%s at %s", device_xname(dev), device_xname(parent));
   1432 		if (print)
   1433 			(void) (*print)(aux, NULL);
   1434 	}
   1435 
   1436 	/*
   1437 	 * Before attaching, clobber any unfound devices that are
   1438 	 * otherwise identical.
   1439 	 * XXX code above is redundant?
   1440 	 */
   1441 	drvname = dev->dv_cfdriver->cd_name;
   1442 	TAILQ_FOREACH(ct, &allcftables, ct_list) {
   1443 		for (cf = ct->ct_cfdata; cf->cf_name; cf++) {
   1444 			if (STREQ(cf->cf_name, drvname) &&
   1445 			    cf->cf_unit == dev->dv_unit) {
   1446 				if (cf->cf_fstate == FSTATE_NOTFOUND)
   1447 					cf->cf_fstate = FSTATE_FOUND;
   1448 			}
   1449 		}
   1450 	}
   1451 	device_register(dev, aux);
   1452 
   1453 	/* Let userland know */
   1454 	devmon_report_device(dev, true);
   1455 
   1456 	(*dev->dv_cfattach->ca_attach)(parent, dev, aux);
   1457 
   1458 	if (!device_pmf_is_registered(dev))
   1459 		aprint_debug_dev(dev, "WARNING: power management not supported\n");
   1460 
   1461 	config_process_deferred(&deferred_config_queue, dev);
   1462 
   1463 	device_register_post_config(dev, aux);
   1464 	return dev;
   1465 }
   1466 
   1467 device_t
   1468 config_attach(device_t parent, cfdata_t cf, void *aux, cfprint_t print)
   1469 {
   1470 
   1471 	return config_attach_loc(parent, cf, NULL, aux, print);
   1472 }
   1473 
   1474 /*
   1475  * As above, but for pseudo-devices.  Pseudo-devices attached in this
   1476  * way are silently inserted into the device tree, and their children
   1477  * attached.
   1478  *
   1479  * Note that because pseudo-devices are attached silently, any information
   1480  * the attach routine wishes to print should be prefixed with the device
   1481  * name by the attach routine.
   1482  */
   1483 device_t
   1484 config_attach_pseudo(cfdata_t cf)
   1485 {
   1486 	device_t dev;
   1487 
   1488 	dev = config_devalloc(ROOT, cf, NULL);
   1489 	if (!dev)
   1490 		return NULL;
   1491 
   1492 	/* XXX mark busy in cfdata */
   1493 
   1494 	if (cf->cf_fstate != FSTATE_STAR) {
   1495 		KASSERT(cf->cf_fstate == FSTATE_NOTFOUND);
   1496 		cf->cf_fstate = FSTATE_FOUND;
   1497 	}
   1498 
   1499 	config_devlink(dev);
   1500 
   1501 #if 0	/* XXXJRT not yet */
   1502 	device_register(dev, NULL);	/* like a root node */
   1503 #endif
   1504 	(*dev->dv_cfattach->ca_attach)(ROOT, dev, NULL);
   1505 	config_process_deferred(&deferred_config_queue, dev);
   1506 	return dev;
   1507 }
   1508 
   1509 /*
   1510  * Caller must hold alldevs_mtx.
   1511  */
   1512 static void
   1513 config_collect_garbage(struct devicelist *garbage)
   1514 {
   1515 	device_t dv;
   1516 
   1517 	KASSERT(!cpu_intr_p());
   1518 	KASSERT(!cpu_softintr_p());
   1519 	KASSERT(mutex_owned(&alldevs_mtx));
   1520 
   1521 	while (alldevs_nwrite == 0 && alldevs_nread == 0 && alldevs_garbage) {
   1522 		TAILQ_FOREACH(dv, &alldevs, dv_list) {
   1523 			if (dv->dv_del_gen != 0)
   1524 				break;
   1525 		}
   1526 		if (dv == NULL) {
   1527 			alldevs_garbage = false;
   1528 			break;
   1529 		}
   1530 		config_devunlink(dv, garbage);
   1531 	}
   1532 	KASSERT(mutex_owned(&alldevs_mtx));
   1533 }
   1534 
   1535 static void
   1536 config_dump_garbage(struct devicelist *garbage)
   1537 {
   1538 	device_t dv;
   1539 
   1540 	while ((dv = TAILQ_FIRST(garbage)) != NULL) {
   1541 		TAILQ_REMOVE(garbage, dv, dv_list);
   1542 		config_devdelete(dv);
   1543 	}
   1544 }
   1545 
   1546 /*
   1547  * Detach a device.  Optionally forced (e.g. because of hardware
   1548  * removal) and quiet.  Returns zero if successful, non-zero
   1549  * (an error code) otherwise.
   1550  *
   1551  * Note that this code wants to be run from a process context, so
   1552  * that the detach can sleep to allow processes which have a device
   1553  * open to run and unwind their stacks.
   1554  */
   1555 int
   1556 config_detach(device_t dev, int flags)
   1557 {
   1558 	struct alldevs_foray af;
   1559 	struct cftable *ct;
   1560 	cfdata_t cf;
   1561 	const struct cfattach *ca;
   1562 	struct cfdriver *cd;
   1563 #ifdef DIAGNOSTIC
   1564 	device_t d;
   1565 #endif
   1566 	int rv = 0, s;
   1567 
   1568 #ifdef DIAGNOSTIC
   1569 	cf = dev->dv_cfdata;
   1570 	if (cf != NULL && cf->cf_fstate != FSTATE_FOUND &&
   1571 	    cf->cf_fstate != FSTATE_STAR)
   1572 		panic("config_detach: %s: bad device fstate %d",
   1573 		    device_xname(dev), cf ? cf->cf_fstate : -1);
   1574 #endif
   1575 	cd = dev->dv_cfdriver;
   1576 	KASSERT(cd != NULL);
   1577 
   1578 	ca = dev->dv_cfattach;
   1579 	KASSERT(ca != NULL);
   1580 
   1581 	s = config_alldevs_lock();
   1582 	if (dev->dv_del_gen != 0) {
   1583 		config_alldevs_unlock(s);
   1584 #ifdef DIAGNOSTIC
   1585 		printf("%s: %s is already detached\n", __func__,
   1586 		    device_xname(dev));
   1587 #endif /* DIAGNOSTIC */
   1588 		return ENOENT;
   1589 	}
   1590 	alldevs_nwrite++;
   1591 	config_alldevs_unlock(s);
   1592 
   1593 	if (!detachall &&
   1594 	    (flags & (DETACH_SHUTDOWN|DETACH_FORCE)) == DETACH_SHUTDOWN &&
   1595 	    (dev->dv_flags & DVF_DETACH_SHUTDOWN) == 0) {
   1596 		rv = EOPNOTSUPP;
   1597 	} else if (ca->ca_detach != NULL) {
   1598 		rv = (*ca->ca_detach)(dev, flags);
   1599 	} else
   1600 		rv = EOPNOTSUPP;
   1601 
   1602 	/*
   1603 	 * If it was not possible to detach the device, then we either
   1604 	 * panic() (for the forced but failed case), or return an error.
   1605 	 *
   1606 	 * If it was possible to detach the device, ensure that the
   1607 	 * device is deactivated.
   1608 	 */
   1609 	if (rv == 0)
   1610 		dev->dv_flags &= ~DVF_ACTIVE;
   1611 	else if ((flags & DETACH_FORCE) == 0)
   1612 		goto out;
   1613 	else {
   1614 		panic("config_detach: forced detach of %s failed (%d)",
   1615 		    device_xname(dev), rv);
   1616 	}
   1617 
   1618 	/*
   1619 	 * The device has now been successfully detached.
   1620 	 */
   1621 
   1622 	/* Let userland know */
   1623 	devmon_report_device(dev, false);
   1624 
   1625 #ifdef DIAGNOSTIC
   1626 	/*
   1627 	 * Sanity: If you're successfully detached, you should have no
   1628 	 * children.  (Note that because children must be attached
   1629 	 * after parents, we only need to search the latter part of
   1630 	 * the list.)
   1631 	 */
   1632 	for (d = TAILQ_NEXT(dev, dv_list); d != NULL;
   1633 	    d = TAILQ_NEXT(d, dv_list)) {
   1634 		if (d->dv_parent == dev && d->dv_del_gen == 0) {
   1635 			printf("config_detach: detached device %s"
   1636 			    " has children %s\n", device_xname(dev), device_xname(d));
   1637 			panic("config_detach");
   1638 		}
   1639 	}
   1640 #endif
   1641 
   1642 	/* notify the parent that the child is gone */
   1643 	if (dev->dv_parent) {
   1644 		device_t p = dev->dv_parent;
   1645 		if (p->dv_cfattach->ca_childdetached)
   1646 			(*p->dv_cfattach->ca_childdetached)(p, dev);
   1647 	}
   1648 
   1649 	/*
   1650 	 * Mark cfdata to show that the unit can be reused, if possible.
   1651 	 */
   1652 	TAILQ_FOREACH(ct, &allcftables, ct_list) {
   1653 		for (cf = ct->ct_cfdata; cf->cf_name; cf++) {
   1654 			if (STREQ(cf->cf_name, cd->cd_name)) {
   1655 				if (cf->cf_fstate == FSTATE_FOUND &&
   1656 				    cf->cf_unit == dev->dv_unit)
   1657 					cf->cf_fstate = FSTATE_NOTFOUND;
   1658 			}
   1659 		}
   1660 	}
   1661 
   1662 	if (dev->dv_cfdata != NULL && (flags & DETACH_QUIET) == 0)
   1663 		aprint_normal_dev(dev, "detached\n");
   1664 
   1665 out:
   1666 	config_alldevs_enter(&af);
   1667 	KASSERT(alldevs_nwrite != 0);
   1668 	--alldevs_nwrite;
   1669 	if (rv == 0 && dev->dv_del_gen == 0) {
   1670 		if (alldevs_nwrite == 0 && alldevs_nread == 0)
   1671 			config_devunlink(dev, &af.af_garbage);
   1672 		else {
   1673 			dev->dv_del_gen = alldevs_gen;
   1674 			alldevs_garbage = true;
   1675 		}
   1676 	}
   1677 	config_alldevs_exit(&af);
   1678 
   1679 	return rv;
   1680 }
   1681 
   1682 int
   1683 config_detach_children(device_t parent, int flags)
   1684 {
   1685 	device_t dv;
   1686 	deviter_t di;
   1687 	int error = 0;
   1688 
   1689 	for (dv = deviter_first(&di, DEVITER_F_RW); dv != NULL;
   1690 	     dv = deviter_next(&di)) {
   1691 		if (device_parent(dv) != parent)
   1692 			continue;
   1693 		if ((error = config_detach(dv, flags)) != 0)
   1694 			break;
   1695 	}
   1696 	deviter_release(&di);
   1697 	return error;
   1698 }
   1699 
   1700 device_t
   1701 shutdown_first(struct shutdown_state *s)
   1702 {
   1703 	if (!s->initialized) {
   1704 		deviter_init(&s->di, DEVITER_F_SHUTDOWN|DEVITER_F_LEAVES_FIRST);
   1705 		s->initialized = true;
   1706 	}
   1707 	return shutdown_next(s);
   1708 }
   1709 
   1710 device_t
   1711 shutdown_next(struct shutdown_state *s)
   1712 {
   1713 	device_t dv;
   1714 
   1715 	while ((dv = deviter_next(&s->di)) != NULL && !device_is_active(dv))
   1716 		;
   1717 
   1718 	if (dv == NULL)
   1719 		s->initialized = false;
   1720 
   1721 	return dv;
   1722 }
   1723 
   1724 bool
   1725 config_detach_all(int how)
   1726 {
   1727 	static struct shutdown_state s;
   1728 	device_t curdev;
   1729 	bool progress = false;
   1730 
   1731 	if ((how & RB_NOSYNC) != 0)
   1732 		return false;
   1733 
   1734 	for (curdev = shutdown_first(&s); curdev != NULL;
   1735 	     curdev = shutdown_next(&s)) {
   1736 		aprint_debug(" detaching %s, ", device_xname(curdev));
   1737 		if (config_detach(curdev, DETACH_SHUTDOWN) == 0) {
   1738 			progress = true;
   1739 			aprint_debug("success.");
   1740 		} else
   1741 			aprint_debug("failed.");
   1742 	}
   1743 	return progress;
   1744 }
   1745 
   1746 static bool
   1747 device_is_ancestor_of(device_t ancestor, device_t descendant)
   1748 {
   1749 	device_t dv;
   1750 
   1751 	for (dv = descendant; dv != NULL; dv = device_parent(dv)) {
   1752 		if (device_parent(dv) == ancestor)
   1753 			return true;
   1754 	}
   1755 	return false;
   1756 }
   1757 
   1758 int
   1759 config_deactivate(device_t dev)
   1760 {
   1761 	deviter_t di;
   1762 	const struct cfattach *ca;
   1763 	device_t descendant;
   1764 	int s, rv = 0, oflags;
   1765 
   1766 	for (descendant = deviter_first(&di, DEVITER_F_ROOT_FIRST);
   1767 	     descendant != NULL;
   1768 	     descendant = deviter_next(&di)) {
   1769 		if (dev != descendant &&
   1770 		    !device_is_ancestor_of(dev, descendant))
   1771 			continue;
   1772 
   1773 		if ((descendant->dv_flags & DVF_ACTIVE) == 0)
   1774 			continue;
   1775 
   1776 		ca = descendant->dv_cfattach;
   1777 		oflags = descendant->dv_flags;
   1778 
   1779 		descendant->dv_flags &= ~DVF_ACTIVE;
   1780 		if (ca->ca_activate == NULL)
   1781 			continue;
   1782 		s = splhigh();
   1783 		rv = (*ca->ca_activate)(descendant, DVACT_DEACTIVATE);
   1784 		splx(s);
   1785 		if (rv != 0)
   1786 			descendant->dv_flags = oflags;
   1787 	}
   1788 	deviter_release(&di);
   1789 	return rv;
   1790 }
   1791 
   1792 /*
   1793  * Defer the configuration of the specified device until all
   1794  * of its parent's devices have been attached.
   1795  */
   1796 void
   1797 config_defer(device_t dev, void (*func)(device_t))
   1798 {
   1799 	struct deferred_config *dc;
   1800 
   1801 	if (dev->dv_parent == NULL)
   1802 		panic("config_defer: can't defer config of a root device");
   1803 
   1804 #ifdef DIAGNOSTIC
   1805 	TAILQ_FOREACH(dc, &deferred_config_queue, dc_queue) {
   1806 		if (dc->dc_dev == dev)
   1807 			panic("config_defer: deferred twice");
   1808 	}
   1809 #endif
   1810 
   1811 	dc = kmem_alloc(sizeof(*dc), KM_SLEEP);
   1812 	if (dc == NULL)
   1813 		panic("config_defer: unable to allocate callback");
   1814 
   1815 	dc->dc_dev = dev;
   1816 	dc->dc_func = func;
   1817 	TAILQ_INSERT_TAIL(&deferred_config_queue, dc, dc_queue);
   1818 	config_pending_incr();
   1819 }
   1820 
   1821 /*
   1822  * Defer some autoconfiguration for a device until after interrupts
   1823  * are enabled.
   1824  */
   1825 void
   1826 config_interrupts(device_t dev, void (*func)(device_t))
   1827 {
   1828 	struct deferred_config *dc;
   1829 
   1830 	/*
   1831 	 * If interrupts are enabled, callback now.
   1832 	 */
   1833 	if (cold == 0) {
   1834 		(*func)(dev);
   1835 		return;
   1836 	}
   1837 
   1838 #ifdef DIAGNOSTIC
   1839 	TAILQ_FOREACH(dc, &interrupt_config_queue, dc_queue) {
   1840 		if (dc->dc_dev == dev)
   1841 			panic("config_interrupts: deferred twice");
   1842 	}
   1843 #endif
   1844 
   1845 	dc = kmem_alloc(sizeof(*dc), KM_SLEEP);
   1846 	if (dc == NULL)
   1847 		panic("config_interrupts: unable to allocate callback");
   1848 
   1849 	dc->dc_dev = dev;
   1850 	dc->dc_func = func;
   1851 	TAILQ_INSERT_TAIL(&interrupt_config_queue, dc, dc_queue);
   1852 	config_pending_incr();
   1853 }
   1854 
   1855 /*
   1856  * Defer some autoconfiguration for a device until after root file system
   1857  * is mounted (to load firmware etc).
   1858  */
   1859 void
   1860 config_mountroot(device_t dev, void (*func)(device_t))
   1861 {
   1862 	struct deferred_config *dc;
   1863 
   1864 	/*
   1865 	 * If root file system is mounted, callback now.
   1866 	 */
   1867 	if (root_is_mounted) {
   1868 		(*func)(dev);
   1869 		return;
   1870 	}
   1871 
   1872 #ifdef DIAGNOSTIC
   1873 	TAILQ_FOREACH(dc, &mountroot_config_queue, dc_queue) {
   1874 		if (dc->dc_dev == dev)
   1875 			panic("%s: deferred twice", __func__);
   1876 	}
   1877 #endif
   1878 
   1879 	dc = kmem_alloc(sizeof(*dc), KM_SLEEP);
   1880 	if (dc == NULL)
   1881 		panic("%s: unable to allocate callback", __func__);
   1882 
   1883 	dc->dc_dev = dev;
   1884 	dc->dc_func = func;
   1885 	TAILQ_INSERT_TAIL(&mountroot_config_queue, dc, dc_queue);
   1886 }
   1887 
   1888 /*
   1889  * Process a deferred configuration queue.
   1890  */
   1891 static void
   1892 config_process_deferred(struct deferred_config_head *queue,
   1893     device_t parent)
   1894 {
   1895 	struct deferred_config *dc, *ndc;
   1896 
   1897 	for (dc = TAILQ_FIRST(queue); dc != NULL; dc = ndc) {
   1898 		ndc = TAILQ_NEXT(dc, dc_queue);
   1899 		if (parent == NULL || dc->dc_dev->dv_parent == parent) {
   1900 			TAILQ_REMOVE(queue, dc, dc_queue);
   1901 			(*dc->dc_func)(dc->dc_dev);
   1902 			kmem_free(dc, sizeof(*dc));
   1903 			config_pending_decr();
   1904 		}
   1905 	}
   1906 }
   1907 
   1908 /*
   1909  * Manipulate the config_pending semaphore.
   1910  */
   1911 void
   1912 config_pending_incr(void)
   1913 {
   1914 
   1915 	mutex_enter(&config_misc_lock);
   1916 	config_pending++;
   1917 	mutex_exit(&config_misc_lock);
   1918 }
   1919 
   1920 void
   1921 config_pending_decr(void)
   1922 {
   1923 
   1924 #ifdef DIAGNOSTIC
   1925 	if (config_pending == 0)
   1926 		panic("config_pending_decr: config_pending == 0");
   1927 #endif
   1928 	mutex_enter(&config_misc_lock);
   1929 	config_pending--;
   1930 	if (config_pending == 0)
   1931 		cv_broadcast(&config_misc_cv);
   1932 	mutex_exit(&config_misc_lock);
   1933 }
   1934 
   1935 /*
   1936  * Register a "finalization" routine.  Finalization routines are
   1937  * called iteratively once all real devices have been found during
   1938  * autoconfiguration, for as long as any one finalizer has done
   1939  * any work.
   1940  */
   1941 int
   1942 config_finalize_register(device_t dev, int (*fn)(device_t))
   1943 {
   1944 	struct finalize_hook *f;
   1945 
   1946 	/*
   1947 	 * If finalization has already been done, invoke the
   1948 	 * callback function now.
   1949 	 */
   1950 	if (config_finalize_done) {
   1951 		while ((*fn)(dev) != 0)
   1952 			/* loop */ ;
   1953 	}
   1954 
   1955 	/* Ensure this isn't already on the list. */
   1956 	TAILQ_FOREACH(f, &config_finalize_list, f_list) {
   1957 		if (f->f_func == fn && f->f_dev == dev)
   1958 			return EEXIST;
   1959 	}
   1960 
   1961 	f = kmem_alloc(sizeof(*f), KM_SLEEP);
   1962 	f->f_func = fn;
   1963 	f->f_dev = dev;
   1964 	TAILQ_INSERT_TAIL(&config_finalize_list, f, f_list);
   1965 
   1966 	return 0;
   1967 }
   1968 
   1969 void
   1970 config_finalize(void)
   1971 {
   1972 	struct finalize_hook *f;
   1973 	struct pdevinit *pdev;
   1974 	extern struct pdevinit pdevinit[];
   1975 	int errcnt, rv;
   1976 
   1977 	/*
   1978 	 * Now that device driver threads have been created, wait for
   1979 	 * them to finish any deferred autoconfiguration.
   1980 	 */
   1981 	mutex_enter(&config_misc_lock);
   1982 	while (config_pending != 0)
   1983 		cv_wait(&config_misc_cv, &config_misc_lock);
   1984 	mutex_exit(&config_misc_lock);
   1985 
   1986 	KERNEL_LOCK(1, NULL);
   1987 
   1988 	/* Attach pseudo-devices. */
   1989 	for (pdev = pdevinit; pdev->pdev_attach != NULL; pdev++)
   1990 		(*pdev->pdev_attach)(pdev->pdev_count);
   1991 
   1992 	/* Run the hooks until none of them does any work. */
   1993 	do {
   1994 		rv = 0;
   1995 		TAILQ_FOREACH(f, &config_finalize_list, f_list)
   1996 			rv |= (*f->f_func)(f->f_dev);
   1997 	} while (rv != 0);
   1998 
   1999 	config_finalize_done = 1;
   2000 
   2001 	/* Now free all the hooks. */
   2002 	while ((f = TAILQ_FIRST(&config_finalize_list)) != NULL) {
   2003 		TAILQ_REMOVE(&config_finalize_list, f, f_list);
   2004 		kmem_free(f, sizeof(*f));
   2005 	}
   2006 
   2007 	KERNEL_UNLOCK_ONE(NULL);
   2008 
   2009 	errcnt = aprint_get_error_count();
   2010 	if ((boothowto & (AB_QUIET|AB_SILENT)) != 0 &&
   2011 	    (boothowto & AB_VERBOSE) == 0) {
   2012 		mutex_enter(&config_misc_lock);
   2013 		if (config_do_twiddle) {
   2014 			config_do_twiddle = 0;
   2015 			printf_nolog(" done.\n");
   2016 		}
   2017 		mutex_exit(&config_misc_lock);
   2018 		if (errcnt != 0) {
   2019 			printf("WARNING: %d error%s while detecting hardware; "
   2020 			    "check system log.\n", errcnt,
   2021 			    errcnt == 1 ? "" : "s");
   2022 		}
   2023 	}
   2024 }
   2025 
   2026 void
   2027 config_twiddle_init()
   2028 {
   2029 
   2030 	if ((boothowto & (AB_SILENT|AB_VERBOSE)) == AB_SILENT) {
   2031 		config_do_twiddle = 1;
   2032 	}
   2033 	callout_setfunc(&config_twiddle_ch, config_twiddle_fn, NULL);
   2034 }
   2035 
   2036 void
   2037 config_twiddle_fn(void *cookie)
   2038 {
   2039 
   2040 	mutex_enter(&config_misc_lock);
   2041 	if (config_do_twiddle) {
   2042 		twiddle();
   2043 		callout_schedule(&config_twiddle_ch, mstohz(100));
   2044 	}
   2045 	mutex_exit(&config_misc_lock);
   2046 }
   2047 
   2048 static int
   2049 config_alldevs_lock(void)
   2050 {
   2051 	mutex_enter(&alldevs_mtx);
   2052 	return 0;
   2053 }
   2054 
   2055 static void
   2056 config_alldevs_enter(struct alldevs_foray *af)
   2057 {
   2058 	TAILQ_INIT(&af->af_garbage);
   2059 	af->af_s = config_alldevs_lock();
   2060 	config_collect_garbage(&af->af_garbage);
   2061 }
   2062 
   2063 static void
   2064 config_alldevs_exit(struct alldevs_foray *af)
   2065 {
   2066 	config_alldevs_unlock(af->af_s);
   2067 	config_dump_garbage(&af->af_garbage);
   2068 }
   2069 
   2070 /*ARGSUSED*/
   2071 static void
   2072 config_alldevs_unlock(int s)
   2073 {
   2074 	mutex_exit(&alldevs_mtx);
   2075 }
   2076 
   2077 /*
   2078  * device_lookup:
   2079  *
   2080  *	Look up a device instance for a given driver.
   2081  */
   2082 device_t
   2083 device_lookup(cfdriver_t cd, int unit)
   2084 {
   2085 	device_t dv;
   2086 	int s;
   2087 
   2088 	s = config_alldevs_lock();
   2089 	KASSERT(mutex_owned(&alldevs_mtx));
   2090 	if (unit < 0 || unit >= cd->cd_ndevs)
   2091 		dv = NULL;
   2092 	else if ((dv = cd->cd_devs[unit]) != NULL && dv->dv_del_gen != 0)
   2093 		dv = NULL;
   2094 	config_alldevs_unlock(s);
   2095 
   2096 	return dv;
   2097 }
   2098 
   2099 /*
   2100  * device_lookup_private:
   2101  *
   2102  *	Look up a softc instance for a given driver.
   2103  */
   2104 void *
   2105 device_lookup_private(cfdriver_t cd, int unit)
   2106 {
   2107 
   2108 	return device_private(device_lookup(cd, unit));
   2109 }
   2110 
   2111 /*
   2112  * device_find_by_xname:
   2113  *
   2114  *	Returns the device of the given name or NULL if it doesn't exist.
   2115  */
   2116 device_t
   2117 device_find_by_xname(const char *name)
   2118 {
   2119 	device_t dv;
   2120 	deviter_t di;
   2121 
   2122 	for (dv = deviter_first(&di, 0); dv != NULL; dv = deviter_next(&di)) {
   2123 		if (strcmp(device_xname(dv), name) == 0)
   2124 			break;
   2125 	}
   2126 	deviter_release(&di);
   2127 
   2128 	return dv;
   2129 }
   2130 
   2131 /*
   2132  * device_find_by_driver_unit:
   2133  *
   2134  *	Returns the device of the given driver name and unit or
   2135  *	NULL if it doesn't exist.
   2136  */
   2137 device_t
   2138 device_find_by_driver_unit(const char *name, int unit)
   2139 {
   2140 	struct cfdriver *cd;
   2141 
   2142 	if ((cd = config_cfdriver_lookup(name)) == NULL)
   2143 		return NULL;
   2144 	return device_lookup(cd, unit);
   2145 }
   2146 
   2147 /*
   2148  * Power management related functions.
   2149  */
   2150 
   2151 bool
   2152 device_pmf_is_registered(device_t dev)
   2153 {
   2154 	return (dev->dv_flags & DVF_POWER_HANDLERS) != 0;
   2155 }
   2156 
   2157 bool
   2158 device_pmf_driver_suspend(device_t dev, const pmf_qual_t *qual)
   2159 {
   2160 	if ((dev->dv_flags & DVF_DRIVER_SUSPENDED) != 0)
   2161 		return true;
   2162 	if ((dev->dv_flags & DVF_CLASS_SUSPENDED) == 0)
   2163 		return false;
   2164 	if (pmf_qual_depth(qual) <= DEVACT_LEVEL_DRIVER &&
   2165 	    dev->dv_driver_suspend != NULL &&
   2166 	    !(*dev->dv_driver_suspend)(dev, qual))
   2167 		return false;
   2168 
   2169 	dev->dv_flags |= DVF_DRIVER_SUSPENDED;
   2170 	return true;
   2171 }
   2172 
   2173 bool
   2174 device_pmf_driver_resume(device_t dev, const pmf_qual_t *qual)
   2175 {
   2176 	if ((dev->dv_flags & DVF_DRIVER_SUSPENDED) == 0)
   2177 		return true;
   2178 	if ((dev->dv_flags & DVF_BUS_SUSPENDED) != 0)
   2179 		return false;
   2180 	if (pmf_qual_depth(qual) <= DEVACT_LEVEL_DRIVER &&
   2181 	    dev->dv_driver_resume != NULL &&
   2182 	    !(*dev->dv_driver_resume)(dev, qual))
   2183 		return false;
   2184 
   2185 	dev->dv_flags &= ~DVF_DRIVER_SUSPENDED;
   2186 	return true;
   2187 }
   2188 
   2189 bool
   2190 device_pmf_driver_shutdown(device_t dev, int how)
   2191 {
   2192 
   2193 	if (*dev->dv_driver_shutdown != NULL &&
   2194 	    !(*dev->dv_driver_shutdown)(dev, how))
   2195 		return false;
   2196 	return true;
   2197 }
   2198 
   2199 bool
   2200 device_pmf_driver_register(device_t dev,
   2201     bool (*suspend)(device_t, const pmf_qual_t *),
   2202     bool (*resume)(device_t, const pmf_qual_t *),
   2203     bool (*shutdown)(device_t, int))
   2204 {
   2205 	dev->dv_driver_suspend = suspend;
   2206 	dev->dv_driver_resume = resume;
   2207 	dev->dv_driver_shutdown = shutdown;
   2208 	dev->dv_flags |= DVF_POWER_HANDLERS;
   2209 	return true;
   2210 }
   2211 
   2212 static const char *
   2213 curlwp_name(void)
   2214 {
   2215 	if (curlwp->l_name != NULL)
   2216 		return curlwp->l_name;
   2217 	else
   2218 		return curlwp->l_proc->p_comm;
   2219 }
   2220 
   2221 void
   2222 device_pmf_driver_deregister(device_t dev)
   2223 {
   2224 	device_lock_t dvl = device_getlock(dev);
   2225 
   2226 	dev->dv_driver_suspend = NULL;
   2227 	dev->dv_driver_resume = NULL;
   2228 
   2229 	mutex_enter(&dvl->dvl_mtx);
   2230 	dev->dv_flags &= ~DVF_POWER_HANDLERS;
   2231 	while (dvl->dvl_nlock > 0 || dvl->dvl_nwait > 0) {
   2232 		/* Wake a thread that waits for the lock.  That
   2233 		 * thread will fail to acquire the lock, and then
   2234 		 * it will wake the next thread that waits for the
   2235 		 * lock, or else it will wake us.
   2236 		 */
   2237 		cv_signal(&dvl->dvl_cv);
   2238 		pmflock_debug(dev, __func__, __LINE__);
   2239 		cv_wait(&dvl->dvl_cv, &dvl->dvl_mtx);
   2240 		pmflock_debug(dev, __func__, __LINE__);
   2241 	}
   2242 	mutex_exit(&dvl->dvl_mtx);
   2243 }
   2244 
   2245 bool
   2246 device_pmf_driver_child_register(device_t dev)
   2247 {
   2248 	device_t parent = device_parent(dev);
   2249 
   2250 	if (parent == NULL || parent->dv_driver_child_register == NULL)
   2251 		return true;
   2252 	return (*parent->dv_driver_child_register)(dev);
   2253 }
   2254 
   2255 void
   2256 device_pmf_driver_set_child_register(device_t dev,
   2257     bool (*child_register)(device_t))
   2258 {
   2259 	dev->dv_driver_child_register = child_register;
   2260 }
   2261 
   2262 static void
   2263 pmflock_debug(device_t dev, const char *func, int line)
   2264 {
   2265 	device_lock_t dvl = device_getlock(dev);
   2266 
   2267 	aprint_debug_dev(dev, "%s.%d, %s dvl_nlock %d dvl_nwait %d dv_flags %x\n",
   2268 	    func, line, curlwp_name(), dvl->dvl_nlock, dvl->dvl_nwait,
   2269 	    dev->dv_flags);
   2270 }
   2271 
   2272 static bool
   2273 device_pmf_lock1(device_t dev)
   2274 {
   2275 	device_lock_t dvl = device_getlock(dev);
   2276 
   2277 	while (device_pmf_is_registered(dev) &&
   2278 	    dvl->dvl_nlock > 0 && dvl->dvl_holder != curlwp) {
   2279 		dvl->dvl_nwait++;
   2280 		pmflock_debug(dev, __func__, __LINE__);
   2281 		cv_wait(&dvl->dvl_cv, &dvl->dvl_mtx);
   2282 		pmflock_debug(dev, __func__, __LINE__);
   2283 		dvl->dvl_nwait--;
   2284 	}
   2285 	if (!device_pmf_is_registered(dev)) {
   2286 		pmflock_debug(dev, __func__, __LINE__);
   2287 		/* We could not acquire the lock, but some other thread may
   2288 		 * wait for it, also.  Wake that thread.
   2289 		 */
   2290 		cv_signal(&dvl->dvl_cv);
   2291 		return false;
   2292 	}
   2293 	dvl->dvl_nlock++;
   2294 	dvl->dvl_holder = curlwp;
   2295 	pmflock_debug(dev, __func__, __LINE__);
   2296 	return true;
   2297 }
   2298 
   2299 bool
   2300 device_pmf_lock(device_t dev)
   2301 {
   2302 	bool rc;
   2303 	device_lock_t dvl = device_getlock(dev);
   2304 
   2305 	mutex_enter(&dvl->dvl_mtx);
   2306 	rc = device_pmf_lock1(dev);
   2307 	mutex_exit(&dvl->dvl_mtx);
   2308 
   2309 	return rc;
   2310 }
   2311 
   2312 void
   2313 device_pmf_unlock(device_t dev)
   2314 {
   2315 	device_lock_t dvl = device_getlock(dev);
   2316 
   2317 	KASSERT(dvl->dvl_nlock > 0);
   2318 	mutex_enter(&dvl->dvl_mtx);
   2319 	if (--dvl->dvl_nlock == 0)
   2320 		dvl->dvl_holder = NULL;
   2321 	cv_signal(&dvl->dvl_cv);
   2322 	pmflock_debug(dev, __func__, __LINE__);
   2323 	mutex_exit(&dvl->dvl_mtx);
   2324 }
   2325 
   2326 device_lock_t
   2327 device_getlock(device_t dev)
   2328 {
   2329 	return &dev->dv_lock;
   2330 }
   2331 
   2332 void *
   2333 device_pmf_bus_private(device_t dev)
   2334 {
   2335 	return dev->dv_bus_private;
   2336 }
   2337 
   2338 bool
   2339 device_pmf_bus_suspend(device_t dev, const pmf_qual_t *qual)
   2340 {
   2341 	if ((dev->dv_flags & DVF_BUS_SUSPENDED) != 0)
   2342 		return true;
   2343 	if ((dev->dv_flags & DVF_CLASS_SUSPENDED) == 0 ||
   2344 	    (dev->dv_flags & DVF_DRIVER_SUSPENDED) == 0)
   2345 		return false;
   2346 	if (pmf_qual_depth(qual) <= DEVACT_LEVEL_BUS &&
   2347 	    dev->dv_bus_suspend != NULL &&
   2348 	    !(*dev->dv_bus_suspend)(dev, qual))
   2349 		return false;
   2350 
   2351 	dev->dv_flags |= DVF_BUS_SUSPENDED;
   2352 	return true;
   2353 }
   2354 
   2355 bool
   2356 device_pmf_bus_resume(device_t dev, const pmf_qual_t *qual)
   2357 {
   2358 	if ((dev->dv_flags & DVF_BUS_SUSPENDED) == 0)
   2359 		return true;
   2360 	if (pmf_qual_depth(qual) <= DEVACT_LEVEL_BUS &&
   2361 	    dev->dv_bus_resume != NULL &&
   2362 	    !(*dev->dv_bus_resume)(dev, qual))
   2363 		return false;
   2364 
   2365 	dev->dv_flags &= ~DVF_BUS_SUSPENDED;
   2366 	return true;
   2367 }
   2368 
   2369 bool
   2370 device_pmf_bus_shutdown(device_t dev, int how)
   2371 {
   2372 
   2373 	if (*dev->dv_bus_shutdown != NULL &&
   2374 	    !(*dev->dv_bus_shutdown)(dev, how))
   2375 		return false;
   2376 	return true;
   2377 }
   2378 
   2379 void
   2380 device_pmf_bus_register(device_t dev, void *priv,
   2381     bool (*suspend)(device_t, const pmf_qual_t *),
   2382     bool (*resume)(device_t, const pmf_qual_t *),
   2383     bool (*shutdown)(device_t, int), void (*deregister)(device_t))
   2384 {
   2385 	dev->dv_bus_private = priv;
   2386 	dev->dv_bus_resume = resume;
   2387 	dev->dv_bus_suspend = suspend;
   2388 	dev->dv_bus_shutdown = shutdown;
   2389 	dev->dv_bus_deregister = deregister;
   2390 }
   2391 
   2392 void
   2393 device_pmf_bus_deregister(device_t dev)
   2394 {
   2395 	if (dev->dv_bus_deregister == NULL)
   2396 		return;
   2397 	(*dev->dv_bus_deregister)(dev);
   2398 	dev->dv_bus_private = NULL;
   2399 	dev->dv_bus_suspend = NULL;
   2400 	dev->dv_bus_resume = NULL;
   2401 	dev->dv_bus_deregister = NULL;
   2402 }
   2403 
   2404 void *
   2405 device_pmf_class_private(device_t dev)
   2406 {
   2407 	return dev->dv_class_private;
   2408 }
   2409 
   2410 bool
   2411 device_pmf_class_suspend(device_t dev, const pmf_qual_t *qual)
   2412 {
   2413 	if ((dev->dv_flags & DVF_CLASS_SUSPENDED) != 0)
   2414 		return true;
   2415 	if (pmf_qual_depth(qual) <= DEVACT_LEVEL_CLASS &&
   2416 	    dev->dv_class_suspend != NULL &&
   2417 	    !(*dev->dv_class_suspend)(dev, qual))
   2418 		return false;
   2419 
   2420 	dev->dv_flags |= DVF_CLASS_SUSPENDED;
   2421 	return true;
   2422 }
   2423 
   2424 bool
   2425 device_pmf_class_resume(device_t dev, const pmf_qual_t *qual)
   2426 {
   2427 	if ((dev->dv_flags & DVF_CLASS_SUSPENDED) == 0)
   2428 		return true;
   2429 	if ((dev->dv_flags & DVF_BUS_SUSPENDED) != 0 ||
   2430 	    (dev->dv_flags & DVF_DRIVER_SUSPENDED) != 0)
   2431 		return false;
   2432 	if (pmf_qual_depth(qual) <= DEVACT_LEVEL_CLASS &&
   2433 	    dev->dv_class_resume != NULL &&
   2434 	    !(*dev->dv_class_resume)(dev, qual))
   2435 		return false;
   2436 
   2437 	dev->dv_flags &= ~DVF_CLASS_SUSPENDED;
   2438 	return true;
   2439 }
   2440 
   2441 void
   2442 device_pmf_class_register(device_t dev, void *priv,
   2443     bool (*suspend)(device_t, const pmf_qual_t *),
   2444     bool (*resume)(device_t, const pmf_qual_t *),
   2445     void (*deregister)(device_t))
   2446 {
   2447 	dev->dv_class_private = priv;
   2448 	dev->dv_class_suspend = suspend;
   2449 	dev->dv_class_resume = resume;
   2450 	dev->dv_class_deregister = deregister;
   2451 }
   2452 
   2453 void
   2454 device_pmf_class_deregister(device_t dev)
   2455 {
   2456 	if (dev->dv_class_deregister == NULL)
   2457 		return;
   2458 	(*dev->dv_class_deregister)(dev);
   2459 	dev->dv_class_private = NULL;
   2460 	dev->dv_class_suspend = NULL;
   2461 	dev->dv_class_resume = NULL;
   2462 	dev->dv_class_deregister = NULL;
   2463 }
   2464 
   2465 bool
   2466 device_active(device_t dev, devactive_t type)
   2467 {
   2468 	size_t i;
   2469 
   2470 	if (dev->dv_activity_count == 0)
   2471 		return false;
   2472 
   2473 	for (i = 0; i < dev->dv_activity_count; ++i) {
   2474 		if (dev->dv_activity_handlers[i] == NULL)
   2475 			break;
   2476 		(*dev->dv_activity_handlers[i])(dev, type);
   2477 	}
   2478 
   2479 	return true;
   2480 }
   2481 
   2482 bool
   2483 device_active_register(device_t dev, void (*handler)(device_t, devactive_t))
   2484 {
   2485 	void (**new_handlers)(device_t, devactive_t);
   2486 	void (**old_handlers)(device_t, devactive_t);
   2487 	size_t i, old_size, new_size;
   2488 	int s;
   2489 
   2490 	old_handlers = dev->dv_activity_handlers;
   2491 	old_size = dev->dv_activity_count;
   2492 
   2493 	for (i = 0; i < old_size; ++i) {
   2494 		KASSERT(old_handlers[i] != handler);
   2495 		if (old_handlers[i] == NULL) {
   2496 			old_handlers[i] = handler;
   2497 			return true;
   2498 		}
   2499 	}
   2500 
   2501 	new_size = old_size + 4;
   2502 	new_handlers = kmem_alloc(sizeof(void *[new_size]), KM_SLEEP);
   2503 
   2504 	memcpy(new_handlers, old_handlers, sizeof(void *[old_size]));
   2505 	new_handlers[old_size] = handler;
   2506 	memset(new_handlers + old_size + 1, 0,
   2507 	    sizeof(int [new_size - (old_size+1)]));
   2508 
   2509 	s = splhigh();
   2510 	dev->dv_activity_count = new_size;
   2511 	dev->dv_activity_handlers = new_handlers;
   2512 	splx(s);
   2513 
   2514 	if (old_handlers != NULL)
   2515 		kmem_free(old_handlers, sizeof(void * [old_size]));
   2516 
   2517 	return true;
   2518 }
   2519 
   2520 void
   2521 device_active_deregister(device_t dev, void (*handler)(device_t, devactive_t))
   2522 {
   2523 	void (**old_handlers)(device_t, devactive_t);
   2524 	size_t i, old_size;
   2525 	int s;
   2526 
   2527 	old_handlers = dev->dv_activity_handlers;
   2528 	old_size = dev->dv_activity_count;
   2529 
   2530 	for (i = 0; i < old_size; ++i) {
   2531 		if (old_handlers[i] == handler)
   2532 			break;
   2533 		if (old_handlers[i] == NULL)
   2534 			return; /* XXX panic? */
   2535 	}
   2536 
   2537 	if (i == old_size)
   2538 		return; /* XXX panic? */
   2539 
   2540 	for (; i < old_size - 1; ++i) {
   2541 		if ((old_handlers[i] = old_handlers[i + 1]) != NULL)
   2542 			continue;
   2543 
   2544 		if (i == 0) {
   2545 			s = splhigh();
   2546 			dev->dv_activity_count = 0;
   2547 			dev->dv_activity_handlers = NULL;
   2548 			splx(s);
   2549 			kmem_free(old_handlers, sizeof(void *[old_size]));
   2550 		}
   2551 		return;
   2552 	}
   2553 	old_handlers[i] = NULL;
   2554 }
   2555 
   2556 /* Return true iff the device_t `dev' exists at generation `gen'. */
   2557 static bool
   2558 device_exists_at(device_t dv, devgen_t gen)
   2559 {
   2560 	return (dv->dv_del_gen == 0 || dv->dv_del_gen > gen) &&
   2561 	    dv->dv_add_gen <= gen;
   2562 }
   2563 
   2564 static bool
   2565 deviter_visits(const deviter_t *di, device_t dv)
   2566 {
   2567 	return device_exists_at(dv, di->di_gen);
   2568 }
   2569 
   2570 /*
   2571  * Device Iteration
   2572  *
   2573  * deviter_t: a device iterator.  Holds state for a "walk" visiting
   2574  *     each device_t's in the device tree.
   2575  *
   2576  * deviter_init(di, flags): initialize the device iterator `di'
   2577  *     to "walk" the device tree.  deviter_next(di) will return
   2578  *     the first device_t in the device tree, or NULL if there are
   2579  *     no devices.
   2580  *
   2581  *     `flags' is one or more of DEVITER_F_RW, indicating that the
   2582  *     caller intends to modify the device tree by calling
   2583  *     config_detach(9) on devices in the order that the iterator
   2584  *     returns them; DEVITER_F_ROOT_FIRST, asking for the devices
   2585  *     nearest the "root" of the device tree to be returned, first;
   2586  *     DEVITER_F_LEAVES_FIRST, asking for the devices furthest from
   2587  *     the root of the device tree, first; and DEVITER_F_SHUTDOWN,
   2588  *     indicating both that deviter_init() should not respect any
   2589  *     locks on the device tree, and that deviter_next(di) may run
   2590  *     in more than one LWP before the walk has finished.
   2591  *
   2592  *     Only one DEVITER_F_RW iterator may be in the device tree at
   2593  *     once.
   2594  *
   2595  *     DEVITER_F_SHUTDOWN implies DEVITER_F_RW.
   2596  *
   2597  *     Results are undefined if the flags DEVITER_F_ROOT_FIRST and
   2598  *     DEVITER_F_LEAVES_FIRST are used in combination.
   2599  *
   2600  * deviter_first(di, flags): initialize the device iterator `di'
   2601  *     and return the first device_t in the device tree, or NULL
   2602  *     if there are no devices.  The statement
   2603  *
   2604  *         dv = deviter_first(di);
   2605  *
   2606  *     is shorthand for
   2607  *
   2608  *         deviter_init(di);
   2609  *         dv = deviter_next(di);
   2610  *
   2611  * deviter_next(di): return the next device_t in the device tree,
   2612  *     or NULL if there are no more devices.  deviter_next(di)
   2613  *     is undefined if `di' was not initialized with deviter_init() or
   2614  *     deviter_first().
   2615  *
   2616  * deviter_release(di): stops iteration (subsequent calls to
   2617  *     deviter_next() will return NULL), releases any locks and
   2618  *     resources held by the device iterator.
   2619  *
   2620  * Device iteration does not return device_t's in any particular
   2621  * order.  An iterator will never return the same device_t twice.
   2622  * Device iteration is guaranteed to complete---i.e., if deviter_next(di)
   2623  * is called repeatedly on the same `di', it will eventually return
   2624  * NULL.  It is ok to attach/detach devices during device iteration.
   2625  */
   2626 void
   2627 deviter_init(deviter_t *di, deviter_flags_t flags)
   2628 {
   2629 	device_t dv;
   2630 	int s;
   2631 
   2632 	memset(di, 0, sizeof(*di));
   2633 
   2634 	s = config_alldevs_lock();
   2635 	if ((flags & DEVITER_F_SHUTDOWN) != 0)
   2636 		flags |= DEVITER_F_RW;
   2637 
   2638 	if ((flags & DEVITER_F_RW) != 0)
   2639 		alldevs_nwrite++;
   2640 	else
   2641 		alldevs_nread++;
   2642 	di->di_gen = alldevs_gen++;
   2643 	config_alldevs_unlock(s);
   2644 
   2645 	di->di_flags = flags;
   2646 
   2647 	switch (di->di_flags & (DEVITER_F_LEAVES_FIRST|DEVITER_F_ROOT_FIRST)) {
   2648 	case DEVITER_F_LEAVES_FIRST:
   2649 		TAILQ_FOREACH(dv, &alldevs, dv_list) {
   2650 			if (!deviter_visits(di, dv))
   2651 				continue;
   2652 			di->di_curdepth = MAX(di->di_curdepth, dv->dv_depth);
   2653 		}
   2654 		break;
   2655 	case DEVITER_F_ROOT_FIRST:
   2656 		TAILQ_FOREACH(dv, &alldevs, dv_list) {
   2657 			if (!deviter_visits(di, dv))
   2658 				continue;
   2659 			di->di_maxdepth = MAX(di->di_maxdepth, dv->dv_depth);
   2660 		}
   2661 		break;
   2662 	default:
   2663 		break;
   2664 	}
   2665 
   2666 	deviter_reinit(di);
   2667 }
   2668 
   2669 static void
   2670 deviter_reinit(deviter_t *di)
   2671 {
   2672 	if ((di->di_flags & DEVITER_F_RW) != 0)
   2673 		di->di_prev = TAILQ_LAST(&alldevs, devicelist);
   2674 	else
   2675 		di->di_prev = TAILQ_FIRST(&alldevs);
   2676 }
   2677 
   2678 device_t
   2679 deviter_first(deviter_t *di, deviter_flags_t flags)
   2680 {
   2681 	deviter_init(di, flags);
   2682 	return deviter_next(di);
   2683 }
   2684 
   2685 static device_t
   2686 deviter_next2(deviter_t *di)
   2687 {
   2688 	device_t dv;
   2689 
   2690 	dv = di->di_prev;
   2691 
   2692 	if (dv == NULL)
   2693 		return NULL;
   2694 
   2695 	if ((di->di_flags & DEVITER_F_RW) != 0)
   2696 		di->di_prev = TAILQ_PREV(dv, devicelist, dv_list);
   2697 	else
   2698 		di->di_prev = TAILQ_NEXT(dv, dv_list);
   2699 
   2700 	return dv;
   2701 }
   2702 
   2703 static device_t
   2704 deviter_next1(deviter_t *di)
   2705 {
   2706 	device_t dv;
   2707 
   2708 	do {
   2709 		dv = deviter_next2(di);
   2710 	} while (dv != NULL && !deviter_visits(di, dv));
   2711 
   2712 	return dv;
   2713 }
   2714 
   2715 device_t
   2716 deviter_next(deviter_t *di)
   2717 {
   2718 	device_t dv = NULL;
   2719 
   2720 	switch (di->di_flags & (DEVITER_F_LEAVES_FIRST|DEVITER_F_ROOT_FIRST)) {
   2721 	case 0:
   2722 		return deviter_next1(di);
   2723 	case DEVITER_F_LEAVES_FIRST:
   2724 		while (di->di_curdepth >= 0) {
   2725 			if ((dv = deviter_next1(di)) == NULL) {
   2726 				di->di_curdepth--;
   2727 				deviter_reinit(di);
   2728 			} else if (dv->dv_depth == di->di_curdepth)
   2729 				break;
   2730 		}
   2731 		return dv;
   2732 	case DEVITER_F_ROOT_FIRST:
   2733 		while (di->di_curdepth <= di->di_maxdepth) {
   2734 			if ((dv = deviter_next1(di)) == NULL) {
   2735 				di->di_curdepth++;
   2736 				deviter_reinit(di);
   2737 			} else if (dv->dv_depth == di->di_curdepth)
   2738 				break;
   2739 		}
   2740 		return dv;
   2741 	default:
   2742 		return NULL;
   2743 	}
   2744 }
   2745 
   2746 void
   2747 deviter_release(deviter_t *di)
   2748 {
   2749 	bool rw = (di->di_flags & DEVITER_F_RW) != 0;
   2750 	int s;
   2751 
   2752 	s = config_alldevs_lock();
   2753 	if (rw)
   2754 		--alldevs_nwrite;
   2755 	else
   2756 		--alldevs_nread;
   2757 	/* XXX wake a garbage-collection thread */
   2758 	config_alldevs_unlock(s);
   2759 }
   2760 
   2761 const char *
   2762 cfdata_ifattr(const struct cfdata *cf)
   2763 {
   2764 	return cf->cf_pspec->cfp_iattr;
   2765 }
   2766 
   2767 bool
   2768 ifattr_match(const char *snull, const char *t)
   2769 {
   2770 	return (snull == NULL) || strcmp(snull, t) == 0;
   2771 }
   2772 
   2773 void
   2774 null_childdetached(device_t self, device_t child)
   2775 {
   2776 	/* do nothing */
   2777 }
   2778 
   2779 static void
   2780 sysctl_detach_setup(struct sysctllog **clog)
   2781 {
   2782 	const struct sysctlnode *node = NULL;
   2783 
   2784 	sysctl_createv(clog, 0, NULL, &node,
   2785 		CTLFLAG_PERMANENT,
   2786 		CTLTYPE_NODE, "kern", NULL,
   2787 		NULL, 0, NULL, 0,
   2788 		CTL_KERN, CTL_EOL);
   2789 
   2790 	if (node == NULL)
   2791 		return;
   2792 
   2793 	sysctl_createv(clog, 0, &node, NULL,
   2794 		CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
   2795 		CTLTYPE_BOOL, "detachall",
   2796 		SYSCTL_DESCR("Detach all devices at shutdown"),
   2797 		NULL, 0, &detachall, 0,
   2798 		CTL_CREATE, CTL_EOL);
   2799 }
   2800