Home | History | Annotate | Line # | Download | only in kern
subr_autoconf.c revision 1.220
      1 /* $NetBSD: subr_autoconf.c,v 1.220 2011/08/31 18:31:02 plunky 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.220 2011/08/31 18:31:02 plunky 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 its device_t.  If the device was
   1034  * not configured, call the given `print' function and return NULL.
   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(NULL, rootname, aux)) != NULL)
   1078 		return config_attach(ROOT, cf, aux, 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 (%zu < %zu)", cf->cf_atname,
   1318 		    ca->ca_devsize, sizeof(struct device));
   1319 
   1320 	/* get memory for all device vars */
   1321 	KASSERT((ca->ca_flags & DVF_PRIV_ALLOC) || ca->ca_devsize >= sizeof(struct device));
   1322 	if (ca->ca_devsize > 0) {
   1323 		dev_private = kmem_zalloc(ca->ca_devsize, KM_SLEEP);
   1324 		if (dev_private == NULL)
   1325 			panic("config_devalloc: memory allocation for device softc failed");
   1326 	} else {
   1327 		KASSERT(ca->ca_flags & DVF_PRIV_ALLOC);
   1328 		dev_private = NULL;
   1329 	}
   1330 
   1331 	if ((ca->ca_flags & DVF_PRIV_ALLOC) != 0) {
   1332 		dev = kmem_zalloc(sizeof(*dev), KM_SLEEP);
   1333 	} else {
   1334 		dev = dev_private;
   1335 #ifdef DIAGNOSTIC
   1336 		printf("%s has not been converted to device_t\n", cd->cd_name);
   1337 #endif
   1338 	}
   1339 	if (dev == NULL)
   1340 		panic("config_devalloc: memory allocation for device_t failed");
   1341 
   1342 	dev->dv_class = cd->cd_class;
   1343 	dev->dv_cfdata = cf;
   1344 	dev->dv_cfdriver = cd;
   1345 	dev->dv_cfattach = ca;
   1346 	dev->dv_activity_count = 0;
   1347 	dev->dv_activity_handlers = NULL;
   1348 	dev->dv_private = dev_private;
   1349 	dev->dv_flags = ca->ca_flags;	/* inherit flags from class */
   1350 
   1351 	myunit = config_unit_alloc(dev, cd, cf);
   1352 	if (myunit == -1) {
   1353 		config_devfree(dev);
   1354 		return NULL;
   1355 	}
   1356 
   1357 	/* compute length of name and decimal expansion of unit number */
   1358 	lname = strlen(cd->cd_name);
   1359 	xunit = number(&num[sizeof(num)], myunit);
   1360 	lunit = &num[sizeof(num)] - xunit;
   1361 	if (lname + lunit > sizeof(dev->dv_xname))
   1362 		panic("config_devalloc: device name too long");
   1363 
   1364 	dvl = device_getlock(dev);
   1365 
   1366 	mutex_init(&dvl->dvl_mtx, MUTEX_DEFAULT, IPL_NONE);
   1367 	cv_init(&dvl->dvl_cv, "pmfsusp");
   1368 
   1369 	memcpy(dev->dv_xname, cd->cd_name, lname);
   1370 	memcpy(dev->dv_xname + lname, xunit, lunit);
   1371 	dev->dv_parent = parent;
   1372 	if (parent != NULL)
   1373 		dev->dv_depth = parent->dv_depth + 1;
   1374 	else
   1375 		dev->dv_depth = 0;
   1376 	dev->dv_flags |= DVF_ACTIVE;	/* always initially active */
   1377 	if (locs) {
   1378 		KASSERT(parent); /* no locators at root */
   1379 		ia = cfiattr_lookup(cfdata_ifattr(cf), parent->dv_cfdriver);
   1380 		dev->dv_locators =
   1381 		    kmem_alloc(sizeof(int [ia->ci_loclen + 1]), KM_SLEEP);
   1382 		*dev->dv_locators++ = sizeof(int [ia->ci_loclen + 1]);
   1383 		memcpy(dev->dv_locators, locs, sizeof(int [ia->ci_loclen]));
   1384 	}
   1385 	dev->dv_properties = prop_dictionary_create();
   1386 	KASSERT(dev->dv_properties != NULL);
   1387 
   1388 	prop_dictionary_set_cstring_nocopy(dev->dv_properties,
   1389 	    "device-driver", dev->dv_cfdriver->cd_name);
   1390 	prop_dictionary_set_uint16(dev->dv_properties,
   1391 	    "device-unit", dev->dv_unit);
   1392 
   1393 	return dev;
   1394 }
   1395 
   1396 /*
   1397  * Attach a found device.
   1398  */
   1399 device_t
   1400 config_attach_loc(device_t parent, cfdata_t cf,
   1401 	const int *locs, void *aux, cfprint_t print)
   1402 {
   1403 	device_t dev;
   1404 	struct cftable *ct;
   1405 	const char *drvname;
   1406 
   1407 	dev = config_devalloc(parent, cf, locs);
   1408 	if (!dev)
   1409 		panic("config_attach: allocation of device softc failed");
   1410 
   1411 	/* XXX redundant - see below? */
   1412 	if (cf->cf_fstate != FSTATE_STAR) {
   1413 		KASSERT(cf->cf_fstate == FSTATE_NOTFOUND);
   1414 		cf->cf_fstate = FSTATE_FOUND;
   1415 	}
   1416 
   1417 	config_devlink(dev);
   1418 
   1419 	if (config_do_twiddle && cold)
   1420 		twiddle();
   1421 	else
   1422 		aprint_naive("Found ");
   1423 	/*
   1424 	 * We want the next two printfs for normal, verbose, and quiet,
   1425 	 * but not silent (in which case, we're twiddling, instead).
   1426 	 */
   1427 	if (parent == ROOT) {
   1428 		aprint_naive("%s (root)", device_xname(dev));
   1429 		aprint_normal("%s (root)", device_xname(dev));
   1430 	} else {
   1431 		aprint_naive("%s at %s", device_xname(dev), device_xname(parent));
   1432 		aprint_normal("%s at %s", device_xname(dev), device_xname(parent));
   1433 		if (print)
   1434 			(void) (*print)(aux, NULL);
   1435 	}
   1436 
   1437 	/*
   1438 	 * Before attaching, clobber any unfound devices that are
   1439 	 * otherwise identical.
   1440 	 * XXX code above is redundant?
   1441 	 */
   1442 	drvname = dev->dv_cfdriver->cd_name;
   1443 	TAILQ_FOREACH(ct, &allcftables, ct_list) {
   1444 		for (cf = ct->ct_cfdata; cf->cf_name; cf++) {
   1445 			if (STREQ(cf->cf_name, drvname) &&
   1446 			    cf->cf_unit == dev->dv_unit) {
   1447 				if (cf->cf_fstate == FSTATE_NOTFOUND)
   1448 					cf->cf_fstate = FSTATE_FOUND;
   1449 			}
   1450 		}
   1451 	}
   1452 	device_register(dev, aux);
   1453 
   1454 	/* Let userland know */
   1455 	devmon_report_device(dev, true);
   1456 
   1457 	(*dev->dv_cfattach->ca_attach)(parent, dev, aux);
   1458 
   1459 	if (!device_pmf_is_registered(dev))
   1460 		aprint_debug_dev(dev, "WARNING: power management not supported\n");
   1461 
   1462 	config_process_deferred(&deferred_config_queue, dev);
   1463 
   1464 	device_register_post_config(dev, aux);
   1465 	return dev;
   1466 }
   1467 
   1468 device_t
   1469 config_attach(device_t parent, cfdata_t cf, void *aux, cfprint_t print)
   1470 {
   1471 
   1472 	return config_attach_loc(parent, cf, NULL, aux, print);
   1473 }
   1474 
   1475 /*
   1476  * As above, but for pseudo-devices.  Pseudo-devices attached in this
   1477  * way are silently inserted into the device tree, and their children
   1478  * attached.
   1479  *
   1480  * Note that because pseudo-devices are attached silently, any information
   1481  * the attach routine wishes to print should be prefixed with the device
   1482  * name by the attach routine.
   1483  */
   1484 device_t
   1485 config_attach_pseudo(cfdata_t cf)
   1486 {
   1487 	device_t dev;
   1488 
   1489 	dev = config_devalloc(ROOT, cf, NULL);
   1490 	if (!dev)
   1491 		return NULL;
   1492 
   1493 	/* XXX mark busy in cfdata */
   1494 
   1495 	if (cf->cf_fstate != FSTATE_STAR) {
   1496 		KASSERT(cf->cf_fstate == FSTATE_NOTFOUND);
   1497 		cf->cf_fstate = FSTATE_FOUND;
   1498 	}
   1499 
   1500 	config_devlink(dev);
   1501 
   1502 #if 0	/* XXXJRT not yet */
   1503 	device_register(dev, NULL);	/* like a root node */
   1504 #endif
   1505 	(*dev->dv_cfattach->ca_attach)(ROOT, dev, NULL);
   1506 	config_process_deferred(&deferred_config_queue, dev);
   1507 	return dev;
   1508 }
   1509 
   1510 /*
   1511  * Caller must hold alldevs_mtx.
   1512  */
   1513 static void
   1514 config_collect_garbage(struct devicelist *garbage)
   1515 {
   1516 	device_t dv;
   1517 
   1518 	KASSERT(!cpu_intr_p());
   1519 	KASSERT(!cpu_softintr_p());
   1520 	KASSERT(mutex_owned(&alldevs_mtx));
   1521 
   1522 	while (alldevs_nwrite == 0 && alldevs_nread == 0 && alldevs_garbage) {
   1523 		TAILQ_FOREACH(dv, &alldevs, dv_list) {
   1524 			if (dv->dv_del_gen != 0)
   1525 				break;
   1526 		}
   1527 		if (dv == NULL) {
   1528 			alldevs_garbage = false;
   1529 			break;
   1530 		}
   1531 		config_devunlink(dv, garbage);
   1532 	}
   1533 	KASSERT(mutex_owned(&alldevs_mtx));
   1534 }
   1535 
   1536 static void
   1537 config_dump_garbage(struct devicelist *garbage)
   1538 {
   1539 	device_t dv;
   1540 
   1541 	while ((dv = TAILQ_FIRST(garbage)) != NULL) {
   1542 		TAILQ_REMOVE(garbage, dv, dv_list);
   1543 		config_devdelete(dv);
   1544 	}
   1545 }
   1546 
   1547 /*
   1548  * Detach a device.  Optionally forced (e.g. because of hardware
   1549  * removal) and quiet.  Returns zero if successful, non-zero
   1550  * (an error code) otherwise.
   1551  *
   1552  * Note that this code wants to be run from a process context, so
   1553  * that the detach can sleep to allow processes which have a device
   1554  * open to run and unwind their stacks.
   1555  */
   1556 int
   1557 config_detach(device_t dev, int flags)
   1558 {
   1559 	struct alldevs_foray af;
   1560 	struct cftable *ct;
   1561 	cfdata_t cf;
   1562 	const struct cfattach *ca;
   1563 	struct cfdriver *cd;
   1564 #ifdef DIAGNOSTIC
   1565 	device_t d;
   1566 #endif
   1567 	int rv = 0, s;
   1568 
   1569 #ifdef DIAGNOSTIC
   1570 	cf = dev->dv_cfdata;
   1571 	if (cf != NULL && cf->cf_fstate != FSTATE_FOUND &&
   1572 	    cf->cf_fstate != FSTATE_STAR)
   1573 		panic("config_detach: %s: bad device fstate %d",
   1574 		    device_xname(dev), cf ? cf->cf_fstate : -1);
   1575 #endif
   1576 	cd = dev->dv_cfdriver;
   1577 	KASSERT(cd != NULL);
   1578 
   1579 	ca = dev->dv_cfattach;
   1580 	KASSERT(ca != NULL);
   1581 
   1582 	s = config_alldevs_lock();
   1583 	if (dev->dv_del_gen != 0) {
   1584 		config_alldevs_unlock(s);
   1585 #ifdef DIAGNOSTIC
   1586 		printf("%s: %s is already detached\n", __func__,
   1587 		    device_xname(dev));
   1588 #endif /* DIAGNOSTIC */
   1589 		return ENOENT;
   1590 	}
   1591 	alldevs_nwrite++;
   1592 	config_alldevs_unlock(s);
   1593 
   1594 	if (!detachall &&
   1595 	    (flags & (DETACH_SHUTDOWN|DETACH_FORCE)) == DETACH_SHUTDOWN &&
   1596 	    (dev->dv_flags & DVF_DETACH_SHUTDOWN) == 0) {
   1597 		rv = EOPNOTSUPP;
   1598 	} else if (ca->ca_detach != NULL) {
   1599 		rv = (*ca->ca_detach)(dev, flags);
   1600 	} else
   1601 		rv = EOPNOTSUPP;
   1602 
   1603 	/*
   1604 	 * If it was not possible to detach the device, then we either
   1605 	 * panic() (for the forced but failed case), or return an error.
   1606 	 *
   1607 	 * If it was possible to detach the device, ensure that the
   1608 	 * device is deactivated.
   1609 	 */
   1610 	if (rv == 0)
   1611 		dev->dv_flags &= ~DVF_ACTIVE;
   1612 	else if ((flags & DETACH_FORCE) == 0)
   1613 		goto out;
   1614 	else {
   1615 		panic("config_detach: forced detach of %s failed (%d)",
   1616 		    device_xname(dev), rv);
   1617 	}
   1618 
   1619 	/*
   1620 	 * The device has now been successfully detached.
   1621 	 */
   1622 
   1623 	/* Let userland know */
   1624 	devmon_report_device(dev, false);
   1625 
   1626 #ifdef DIAGNOSTIC
   1627 	/*
   1628 	 * Sanity: If you're successfully detached, you should have no
   1629 	 * children.  (Note that because children must be attached
   1630 	 * after parents, we only need to search the latter part of
   1631 	 * the list.)
   1632 	 */
   1633 	for (d = TAILQ_NEXT(dev, dv_list); d != NULL;
   1634 	    d = TAILQ_NEXT(d, dv_list)) {
   1635 		if (d->dv_parent == dev && d->dv_del_gen == 0) {
   1636 			printf("config_detach: detached device %s"
   1637 			    " has children %s\n", device_xname(dev), device_xname(d));
   1638 			panic("config_detach");
   1639 		}
   1640 	}
   1641 #endif
   1642 
   1643 	/* notify the parent that the child is gone */
   1644 	if (dev->dv_parent) {
   1645 		device_t p = dev->dv_parent;
   1646 		if (p->dv_cfattach->ca_childdetached)
   1647 			(*p->dv_cfattach->ca_childdetached)(p, dev);
   1648 	}
   1649 
   1650 	/*
   1651 	 * Mark cfdata to show that the unit can be reused, if possible.
   1652 	 */
   1653 	TAILQ_FOREACH(ct, &allcftables, ct_list) {
   1654 		for (cf = ct->ct_cfdata; cf->cf_name; cf++) {
   1655 			if (STREQ(cf->cf_name, cd->cd_name)) {
   1656 				if (cf->cf_fstate == FSTATE_FOUND &&
   1657 				    cf->cf_unit == dev->dv_unit)
   1658 					cf->cf_fstate = FSTATE_NOTFOUND;
   1659 			}
   1660 		}
   1661 	}
   1662 
   1663 	if (dev->dv_cfdata != NULL && (flags & DETACH_QUIET) == 0)
   1664 		aprint_normal_dev(dev, "detached\n");
   1665 
   1666 out:
   1667 	config_alldevs_enter(&af);
   1668 	KASSERT(alldevs_nwrite != 0);
   1669 	--alldevs_nwrite;
   1670 	if (rv == 0 && dev->dv_del_gen == 0) {
   1671 		if (alldevs_nwrite == 0 && alldevs_nread == 0)
   1672 			config_devunlink(dev, &af.af_garbage);
   1673 		else {
   1674 			dev->dv_del_gen = alldevs_gen;
   1675 			alldevs_garbage = true;
   1676 		}
   1677 	}
   1678 	config_alldevs_exit(&af);
   1679 
   1680 	return rv;
   1681 }
   1682 
   1683 int
   1684 config_detach_children(device_t parent, int flags)
   1685 {
   1686 	device_t dv;
   1687 	deviter_t di;
   1688 	int error = 0;
   1689 
   1690 	for (dv = deviter_first(&di, DEVITER_F_RW); dv != NULL;
   1691 	     dv = deviter_next(&di)) {
   1692 		if (device_parent(dv) != parent)
   1693 			continue;
   1694 		if ((error = config_detach(dv, flags)) != 0)
   1695 			break;
   1696 	}
   1697 	deviter_release(&di);
   1698 	return error;
   1699 }
   1700 
   1701 device_t
   1702 shutdown_first(struct shutdown_state *s)
   1703 {
   1704 	if (!s->initialized) {
   1705 		deviter_init(&s->di, DEVITER_F_SHUTDOWN|DEVITER_F_LEAVES_FIRST);
   1706 		s->initialized = true;
   1707 	}
   1708 	return shutdown_next(s);
   1709 }
   1710 
   1711 device_t
   1712 shutdown_next(struct shutdown_state *s)
   1713 {
   1714 	device_t dv;
   1715 
   1716 	while ((dv = deviter_next(&s->di)) != NULL && !device_is_active(dv))
   1717 		;
   1718 
   1719 	if (dv == NULL)
   1720 		s->initialized = false;
   1721 
   1722 	return dv;
   1723 }
   1724 
   1725 bool
   1726 config_detach_all(int how)
   1727 {
   1728 	static struct shutdown_state s;
   1729 	device_t curdev;
   1730 	bool progress = false;
   1731 
   1732 	if ((how & RB_NOSYNC) != 0)
   1733 		return false;
   1734 
   1735 	for (curdev = shutdown_first(&s); curdev != NULL;
   1736 	     curdev = shutdown_next(&s)) {
   1737 		aprint_debug(" detaching %s, ", device_xname(curdev));
   1738 		if (config_detach(curdev, DETACH_SHUTDOWN) == 0) {
   1739 			progress = true;
   1740 			aprint_debug("success.");
   1741 		} else
   1742 			aprint_debug("failed.");
   1743 	}
   1744 	return progress;
   1745 }
   1746 
   1747 static bool
   1748 device_is_ancestor_of(device_t ancestor, device_t descendant)
   1749 {
   1750 	device_t dv;
   1751 
   1752 	for (dv = descendant; dv != NULL; dv = device_parent(dv)) {
   1753 		if (device_parent(dv) == ancestor)
   1754 			return true;
   1755 	}
   1756 	return false;
   1757 }
   1758 
   1759 int
   1760 config_deactivate(device_t dev)
   1761 {
   1762 	deviter_t di;
   1763 	const struct cfattach *ca;
   1764 	device_t descendant;
   1765 	int s, rv = 0, oflags;
   1766 
   1767 	for (descendant = deviter_first(&di, DEVITER_F_ROOT_FIRST);
   1768 	     descendant != NULL;
   1769 	     descendant = deviter_next(&di)) {
   1770 		if (dev != descendant &&
   1771 		    !device_is_ancestor_of(dev, descendant))
   1772 			continue;
   1773 
   1774 		if ((descendant->dv_flags & DVF_ACTIVE) == 0)
   1775 			continue;
   1776 
   1777 		ca = descendant->dv_cfattach;
   1778 		oflags = descendant->dv_flags;
   1779 
   1780 		descendant->dv_flags &= ~DVF_ACTIVE;
   1781 		if (ca->ca_activate == NULL)
   1782 			continue;
   1783 		s = splhigh();
   1784 		rv = (*ca->ca_activate)(descendant, DVACT_DEACTIVATE);
   1785 		splx(s);
   1786 		if (rv != 0)
   1787 			descendant->dv_flags = oflags;
   1788 	}
   1789 	deviter_release(&di);
   1790 	return rv;
   1791 }
   1792 
   1793 /*
   1794  * Defer the configuration of the specified device until all
   1795  * of its parent's devices have been attached.
   1796  */
   1797 void
   1798 config_defer(device_t dev, void (*func)(device_t))
   1799 {
   1800 	struct deferred_config *dc;
   1801 
   1802 	if (dev->dv_parent == NULL)
   1803 		panic("config_defer: can't defer config of a root device");
   1804 
   1805 #ifdef DIAGNOSTIC
   1806 	TAILQ_FOREACH(dc, &deferred_config_queue, dc_queue) {
   1807 		if (dc->dc_dev == dev)
   1808 			panic("config_defer: deferred twice");
   1809 	}
   1810 #endif
   1811 
   1812 	dc = kmem_alloc(sizeof(*dc), KM_SLEEP);
   1813 	if (dc == NULL)
   1814 		panic("config_defer: unable to allocate callback");
   1815 
   1816 	dc->dc_dev = dev;
   1817 	dc->dc_func = func;
   1818 	TAILQ_INSERT_TAIL(&deferred_config_queue, dc, dc_queue);
   1819 	config_pending_incr();
   1820 }
   1821 
   1822 /*
   1823  * Defer some autoconfiguration for a device until after interrupts
   1824  * are enabled.
   1825  */
   1826 void
   1827 config_interrupts(device_t dev, void (*func)(device_t))
   1828 {
   1829 	struct deferred_config *dc;
   1830 
   1831 	/*
   1832 	 * If interrupts are enabled, callback now.
   1833 	 */
   1834 	if (cold == 0) {
   1835 		(*func)(dev);
   1836 		return;
   1837 	}
   1838 
   1839 #ifdef DIAGNOSTIC
   1840 	TAILQ_FOREACH(dc, &interrupt_config_queue, dc_queue) {
   1841 		if (dc->dc_dev == dev)
   1842 			panic("config_interrupts: deferred twice");
   1843 	}
   1844 #endif
   1845 
   1846 	dc = kmem_alloc(sizeof(*dc), KM_SLEEP);
   1847 	if (dc == NULL)
   1848 		panic("config_interrupts: unable to allocate callback");
   1849 
   1850 	dc->dc_dev = dev;
   1851 	dc->dc_func = func;
   1852 	TAILQ_INSERT_TAIL(&interrupt_config_queue, dc, dc_queue);
   1853 	config_pending_incr();
   1854 }
   1855 
   1856 /*
   1857  * Defer some autoconfiguration for a device until after root file system
   1858  * is mounted (to load firmware etc).
   1859  */
   1860 void
   1861 config_mountroot(device_t dev, void (*func)(device_t))
   1862 {
   1863 	struct deferred_config *dc;
   1864 
   1865 	/*
   1866 	 * If root file system is mounted, callback now.
   1867 	 */
   1868 	if (root_is_mounted) {
   1869 		(*func)(dev);
   1870 		return;
   1871 	}
   1872 
   1873 #ifdef DIAGNOSTIC
   1874 	TAILQ_FOREACH(dc, &mountroot_config_queue, dc_queue) {
   1875 		if (dc->dc_dev == dev)
   1876 			panic("%s: deferred twice", __func__);
   1877 	}
   1878 #endif
   1879 
   1880 	dc = kmem_alloc(sizeof(*dc), KM_SLEEP);
   1881 	if (dc == NULL)
   1882 		panic("%s: unable to allocate callback", __func__);
   1883 
   1884 	dc->dc_dev = dev;
   1885 	dc->dc_func = func;
   1886 	TAILQ_INSERT_TAIL(&mountroot_config_queue, dc, dc_queue);
   1887 }
   1888 
   1889 /*
   1890  * Process a deferred configuration queue.
   1891  */
   1892 static void
   1893 config_process_deferred(struct deferred_config_head *queue,
   1894     device_t parent)
   1895 {
   1896 	struct deferred_config *dc, *ndc;
   1897 
   1898 	for (dc = TAILQ_FIRST(queue); dc != NULL; dc = ndc) {
   1899 		ndc = TAILQ_NEXT(dc, dc_queue);
   1900 		if (parent == NULL || dc->dc_dev->dv_parent == parent) {
   1901 			TAILQ_REMOVE(queue, dc, dc_queue);
   1902 			(*dc->dc_func)(dc->dc_dev);
   1903 			kmem_free(dc, sizeof(*dc));
   1904 			config_pending_decr();
   1905 		}
   1906 	}
   1907 }
   1908 
   1909 /*
   1910  * Manipulate the config_pending semaphore.
   1911  */
   1912 void
   1913 config_pending_incr(void)
   1914 {
   1915 
   1916 	mutex_enter(&config_misc_lock);
   1917 	config_pending++;
   1918 	mutex_exit(&config_misc_lock);
   1919 }
   1920 
   1921 void
   1922 config_pending_decr(void)
   1923 {
   1924 
   1925 #ifdef DIAGNOSTIC
   1926 	if (config_pending == 0)
   1927 		panic("config_pending_decr: config_pending == 0");
   1928 #endif
   1929 	mutex_enter(&config_misc_lock);
   1930 	config_pending--;
   1931 	if (config_pending == 0)
   1932 		cv_broadcast(&config_misc_cv);
   1933 	mutex_exit(&config_misc_lock);
   1934 }
   1935 
   1936 /*
   1937  * Register a "finalization" routine.  Finalization routines are
   1938  * called iteratively once all real devices have been found during
   1939  * autoconfiguration, for as long as any one finalizer has done
   1940  * any work.
   1941  */
   1942 int
   1943 config_finalize_register(device_t dev, int (*fn)(device_t))
   1944 {
   1945 	struct finalize_hook *f;
   1946 
   1947 	/*
   1948 	 * If finalization has already been done, invoke the
   1949 	 * callback function now.
   1950 	 */
   1951 	if (config_finalize_done) {
   1952 		while ((*fn)(dev) != 0)
   1953 			/* loop */ ;
   1954 	}
   1955 
   1956 	/* Ensure this isn't already on the list. */
   1957 	TAILQ_FOREACH(f, &config_finalize_list, f_list) {
   1958 		if (f->f_func == fn && f->f_dev == dev)
   1959 			return EEXIST;
   1960 	}
   1961 
   1962 	f = kmem_alloc(sizeof(*f), KM_SLEEP);
   1963 	f->f_func = fn;
   1964 	f->f_dev = dev;
   1965 	TAILQ_INSERT_TAIL(&config_finalize_list, f, f_list);
   1966 
   1967 	return 0;
   1968 }
   1969 
   1970 void
   1971 config_finalize(void)
   1972 {
   1973 	struct finalize_hook *f;
   1974 	struct pdevinit *pdev;
   1975 	extern struct pdevinit pdevinit[];
   1976 	int errcnt, rv;
   1977 
   1978 	/*
   1979 	 * Now that device driver threads have been created, wait for
   1980 	 * them to finish any deferred autoconfiguration.
   1981 	 */
   1982 	mutex_enter(&config_misc_lock);
   1983 	while (config_pending != 0)
   1984 		cv_wait(&config_misc_cv, &config_misc_lock);
   1985 	mutex_exit(&config_misc_lock);
   1986 
   1987 	KERNEL_LOCK(1, NULL);
   1988 
   1989 	/* Attach pseudo-devices. */
   1990 	for (pdev = pdevinit; pdev->pdev_attach != NULL; pdev++)
   1991 		(*pdev->pdev_attach)(pdev->pdev_count);
   1992 
   1993 	/* Run the hooks until none of them does any work. */
   1994 	do {
   1995 		rv = 0;
   1996 		TAILQ_FOREACH(f, &config_finalize_list, f_list)
   1997 			rv |= (*f->f_func)(f->f_dev);
   1998 	} while (rv != 0);
   1999 
   2000 	config_finalize_done = 1;
   2001 
   2002 	/* Now free all the hooks. */
   2003 	while ((f = TAILQ_FIRST(&config_finalize_list)) != NULL) {
   2004 		TAILQ_REMOVE(&config_finalize_list, f, f_list);
   2005 		kmem_free(f, sizeof(*f));
   2006 	}
   2007 
   2008 	KERNEL_UNLOCK_ONE(NULL);
   2009 
   2010 	errcnt = aprint_get_error_count();
   2011 	if ((boothowto & (AB_QUIET|AB_SILENT)) != 0 &&
   2012 	    (boothowto & AB_VERBOSE) == 0) {
   2013 		mutex_enter(&config_misc_lock);
   2014 		if (config_do_twiddle) {
   2015 			config_do_twiddle = 0;
   2016 			printf_nolog(" done.\n");
   2017 		}
   2018 		mutex_exit(&config_misc_lock);
   2019 		if (errcnt != 0) {
   2020 			printf("WARNING: %d error%s while detecting hardware; "
   2021 			    "check system log.\n", errcnt,
   2022 			    errcnt == 1 ? "" : "s");
   2023 		}
   2024 	}
   2025 }
   2026 
   2027 void
   2028 config_twiddle_init()
   2029 {
   2030 
   2031 	if ((boothowto & (AB_SILENT|AB_VERBOSE)) == AB_SILENT) {
   2032 		config_do_twiddle = 1;
   2033 	}
   2034 	callout_setfunc(&config_twiddle_ch, config_twiddle_fn, NULL);
   2035 }
   2036 
   2037 void
   2038 config_twiddle_fn(void *cookie)
   2039 {
   2040 
   2041 	mutex_enter(&config_misc_lock);
   2042 	if (config_do_twiddle) {
   2043 		twiddle();
   2044 		callout_schedule(&config_twiddle_ch, mstohz(100));
   2045 	}
   2046 	mutex_exit(&config_misc_lock);
   2047 }
   2048 
   2049 static int
   2050 config_alldevs_lock(void)
   2051 {
   2052 	mutex_enter(&alldevs_mtx);
   2053 	return 0;
   2054 }
   2055 
   2056 static void
   2057 config_alldevs_enter(struct alldevs_foray *af)
   2058 {
   2059 	TAILQ_INIT(&af->af_garbage);
   2060 	af->af_s = config_alldevs_lock();
   2061 	config_collect_garbage(&af->af_garbage);
   2062 }
   2063 
   2064 static void
   2065 config_alldevs_exit(struct alldevs_foray *af)
   2066 {
   2067 	config_alldevs_unlock(af->af_s);
   2068 	config_dump_garbage(&af->af_garbage);
   2069 }
   2070 
   2071 /*ARGSUSED*/
   2072 static void
   2073 config_alldevs_unlock(int s)
   2074 {
   2075 	mutex_exit(&alldevs_mtx);
   2076 }
   2077 
   2078 /*
   2079  * device_lookup:
   2080  *
   2081  *	Look up a device instance for a given driver.
   2082  */
   2083 device_t
   2084 device_lookup(cfdriver_t cd, int unit)
   2085 {
   2086 	device_t dv;
   2087 	int s;
   2088 
   2089 	s = config_alldevs_lock();
   2090 	KASSERT(mutex_owned(&alldevs_mtx));
   2091 	if (unit < 0 || unit >= cd->cd_ndevs)
   2092 		dv = NULL;
   2093 	else if ((dv = cd->cd_devs[unit]) != NULL && dv->dv_del_gen != 0)
   2094 		dv = NULL;
   2095 	config_alldevs_unlock(s);
   2096 
   2097 	return dv;
   2098 }
   2099 
   2100 /*
   2101  * device_lookup_private:
   2102  *
   2103  *	Look up a softc instance for a given driver.
   2104  */
   2105 void *
   2106 device_lookup_private(cfdriver_t cd, int unit)
   2107 {
   2108 
   2109 	return device_private(device_lookup(cd, unit));
   2110 }
   2111 
   2112 /*
   2113  * device_find_by_xname:
   2114  *
   2115  *	Returns the device of the given name or NULL if it doesn't exist.
   2116  */
   2117 device_t
   2118 device_find_by_xname(const char *name)
   2119 {
   2120 	device_t dv;
   2121 	deviter_t di;
   2122 
   2123 	for (dv = deviter_first(&di, 0); dv != NULL; dv = deviter_next(&di)) {
   2124 		if (strcmp(device_xname(dv), name) == 0)
   2125 			break;
   2126 	}
   2127 	deviter_release(&di);
   2128 
   2129 	return dv;
   2130 }
   2131 
   2132 /*
   2133  * device_find_by_driver_unit:
   2134  *
   2135  *	Returns the device of the given driver name and unit or
   2136  *	NULL if it doesn't exist.
   2137  */
   2138 device_t
   2139 device_find_by_driver_unit(const char *name, int unit)
   2140 {
   2141 	struct cfdriver *cd;
   2142 
   2143 	if ((cd = config_cfdriver_lookup(name)) == NULL)
   2144 		return NULL;
   2145 	return device_lookup(cd, unit);
   2146 }
   2147 
   2148 /*
   2149  * Power management related functions.
   2150  */
   2151 
   2152 bool
   2153 device_pmf_is_registered(device_t dev)
   2154 {
   2155 	return (dev->dv_flags & DVF_POWER_HANDLERS) != 0;
   2156 }
   2157 
   2158 bool
   2159 device_pmf_driver_suspend(device_t dev, const pmf_qual_t *qual)
   2160 {
   2161 	if ((dev->dv_flags & DVF_DRIVER_SUSPENDED) != 0)
   2162 		return true;
   2163 	if ((dev->dv_flags & DVF_CLASS_SUSPENDED) == 0)
   2164 		return false;
   2165 	if (pmf_qual_depth(qual) <= DEVACT_LEVEL_DRIVER &&
   2166 	    dev->dv_driver_suspend != NULL &&
   2167 	    !(*dev->dv_driver_suspend)(dev, qual))
   2168 		return false;
   2169 
   2170 	dev->dv_flags |= DVF_DRIVER_SUSPENDED;
   2171 	return true;
   2172 }
   2173 
   2174 bool
   2175 device_pmf_driver_resume(device_t dev, const pmf_qual_t *qual)
   2176 {
   2177 	if ((dev->dv_flags & DVF_DRIVER_SUSPENDED) == 0)
   2178 		return true;
   2179 	if ((dev->dv_flags & DVF_BUS_SUSPENDED) != 0)
   2180 		return false;
   2181 	if (pmf_qual_depth(qual) <= DEVACT_LEVEL_DRIVER &&
   2182 	    dev->dv_driver_resume != NULL &&
   2183 	    !(*dev->dv_driver_resume)(dev, qual))
   2184 		return false;
   2185 
   2186 	dev->dv_flags &= ~DVF_DRIVER_SUSPENDED;
   2187 	return true;
   2188 }
   2189 
   2190 bool
   2191 device_pmf_driver_shutdown(device_t dev, int how)
   2192 {
   2193 
   2194 	if (*dev->dv_driver_shutdown != NULL &&
   2195 	    !(*dev->dv_driver_shutdown)(dev, how))
   2196 		return false;
   2197 	return true;
   2198 }
   2199 
   2200 bool
   2201 device_pmf_driver_register(device_t dev,
   2202     bool (*suspend)(device_t, const pmf_qual_t *),
   2203     bool (*resume)(device_t, const pmf_qual_t *),
   2204     bool (*shutdown)(device_t, int))
   2205 {
   2206 	dev->dv_driver_suspend = suspend;
   2207 	dev->dv_driver_resume = resume;
   2208 	dev->dv_driver_shutdown = shutdown;
   2209 	dev->dv_flags |= DVF_POWER_HANDLERS;
   2210 	return true;
   2211 }
   2212 
   2213 static const char *
   2214 curlwp_name(void)
   2215 {
   2216 	if (curlwp->l_name != NULL)
   2217 		return curlwp->l_name;
   2218 	else
   2219 		return curlwp->l_proc->p_comm;
   2220 }
   2221 
   2222 void
   2223 device_pmf_driver_deregister(device_t dev)
   2224 {
   2225 	device_lock_t dvl = device_getlock(dev);
   2226 
   2227 	dev->dv_driver_suspend = NULL;
   2228 	dev->dv_driver_resume = NULL;
   2229 
   2230 	mutex_enter(&dvl->dvl_mtx);
   2231 	dev->dv_flags &= ~DVF_POWER_HANDLERS;
   2232 	while (dvl->dvl_nlock > 0 || dvl->dvl_nwait > 0) {
   2233 		/* Wake a thread that waits for the lock.  That
   2234 		 * thread will fail to acquire the lock, and then
   2235 		 * it will wake the next thread that waits for the
   2236 		 * lock, or else it will wake us.
   2237 		 */
   2238 		cv_signal(&dvl->dvl_cv);
   2239 		pmflock_debug(dev, __func__, __LINE__);
   2240 		cv_wait(&dvl->dvl_cv, &dvl->dvl_mtx);
   2241 		pmflock_debug(dev, __func__, __LINE__);
   2242 	}
   2243 	mutex_exit(&dvl->dvl_mtx);
   2244 }
   2245 
   2246 bool
   2247 device_pmf_driver_child_register(device_t dev)
   2248 {
   2249 	device_t parent = device_parent(dev);
   2250 
   2251 	if (parent == NULL || parent->dv_driver_child_register == NULL)
   2252 		return true;
   2253 	return (*parent->dv_driver_child_register)(dev);
   2254 }
   2255 
   2256 void
   2257 device_pmf_driver_set_child_register(device_t dev,
   2258     bool (*child_register)(device_t))
   2259 {
   2260 	dev->dv_driver_child_register = child_register;
   2261 }
   2262 
   2263 static void
   2264 pmflock_debug(device_t dev, const char *func, int line)
   2265 {
   2266 	device_lock_t dvl = device_getlock(dev);
   2267 
   2268 	aprint_debug_dev(dev, "%s.%d, %s dvl_nlock %d dvl_nwait %d dv_flags %x\n",
   2269 	    func, line, curlwp_name(), dvl->dvl_nlock, dvl->dvl_nwait,
   2270 	    dev->dv_flags);
   2271 }
   2272 
   2273 static bool
   2274 device_pmf_lock1(device_t dev)
   2275 {
   2276 	device_lock_t dvl = device_getlock(dev);
   2277 
   2278 	while (device_pmf_is_registered(dev) &&
   2279 	    dvl->dvl_nlock > 0 && dvl->dvl_holder != curlwp) {
   2280 		dvl->dvl_nwait++;
   2281 		pmflock_debug(dev, __func__, __LINE__);
   2282 		cv_wait(&dvl->dvl_cv, &dvl->dvl_mtx);
   2283 		pmflock_debug(dev, __func__, __LINE__);
   2284 		dvl->dvl_nwait--;
   2285 	}
   2286 	if (!device_pmf_is_registered(dev)) {
   2287 		pmflock_debug(dev, __func__, __LINE__);
   2288 		/* We could not acquire the lock, but some other thread may
   2289 		 * wait for it, also.  Wake that thread.
   2290 		 */
   2291 		cv_signal(&dvl->dvl_cv);
   2292 		return false;
   2293 	}
   2294 	dvl->dvl_nlock++;
   2295 	dvl->dvl_holder = curlwp;
   2296 	pmflock_debug(dev, __func__, __LINE__);
   2297 	return true;
   2298 }
   2299 
   2300 bool
   2301 device_pmf_lock(device_t dev)
   2302 {
   2303 	bool rc;
   2304 	device_lock_t dvl = device_getlock(dev);
   2305 
   2306 	mutex_enter(&dvl->dvl_mtx);
   2307 	rc = device_pmf_lock1(dev);
   2308 	mutex_exit(&dvl->dvl_mtx);
   2309 
   2310 	return rc;
   2311 }
   2312 
   2313 void
   2314 device_pmf_unlock(device_t dev)
   2315 {
   2316 	device_lock_t dvl = device_getlock(dev);
   2317 
   2318 	KASSERT(dvl->dvl_nlock > 0);
   2319 	mutex_enter(&dvl->dvl_mtx);
   2320 	if (--dvl->dvl_nlock == 0)
   2321 		dvl->dvl_holder = NULL;
   2322 	cv_signal(&dvl->dvl_cv);
   2323 	pmflock_debug(dev, __func__, __LINE__);
   2324 	mutex_exit(&dvl->dvl_mtx);
   2325 }
   2326 
   2327 device_lock_t
   2328 device_getlock(device_t dev)
   2329 {
   2330 	return &dev->dv_lock;
   2331 }
   2332 
   2333 void *
   2334 device_pmf_bus_private(device_t dev)
   2335 {
   2336 	return dev->dv_bus_private;
   2337 }
   2338 
   2339 bool
   2340 device_pmf_bus_suspend(device_t dev, const pmf_qual_t *qual)
   2341 {
   2342 	if ((dev->dv_flags & DVF_BUS_SUSPENDED) != 0)
   2343 		return true;
   2344 	if ((dev->dv_flags & DVF_CLASS_SUSPENDED) == 0 ||
   2345 	    (dev->dv_flags & DVF_DRIVER_SUSPENDED) == 0)
   2346 		return false;
   2347 	if (pmf_qual_depth(qual) <= DEVACT_LEVEL_BUS &&
   2348 	    dev->dv_bus_suspend != NULL &&
   2349 	    !(*dev->dv_bus_suspend)(dev, qual))
   2350 		return false;
   2351 
   2352 	dev->dv_flags |= DVF_BUS_SUSPENDED;
   2353 	return true;
   2354 }
   2355 
   2356 bool
   2357 device_pmf_bus_resume(device_t dev, const pmf_qual_t *qual)
   2358 {
   2359 	if ((dev->dv_flags & DVF_BUS_SUSPENDED) == 0)
   2360 		return true;
   2361 	if (pmf_qual_depth(qual) <= DEVACT_LEVEL_BUS &&
   2362 	    dev->dv_bus_resume != NULL &&
   2363 	    !(*dev->dv_bus_resume)(dev, qual))
   2364 		return false;
   2365 
   2366 	dev->dv_flags &= ~DVF_BUS_SUSPENDED;
   2367 	return true;
   2368 }
   2369 
   2370 bool
   2371 device_pmf_bus_shutdown(device_t dev, int how)
   2372 {
   2373 
   2374 	if (*dev->dv_bus_shutdown != NULL &&
   2375 	    !(*dev->dv_bus_shutdown)(dev, how))
   2376 		return false;
   2377 	return true;
   2378 }
   2379 
   2380 void
   2381 device_pmf_bus_register(device_t dev, void *priv,
   2382     bool (*suspend)(device_t, const pmf_qual_t *),
   2383     bool (*resume)(device_t, const pmf_qual_t *),
   2384     bool (*shutdown)(device_t, int), void (*deregister)(device_t))
   2385 {
   2386 	dev->dv_bus_private = priv;
   2387 	dev->dv_bus_resume = resume;
   2388 	dev->dv_bus_suspend = suspend;
   2389 	dev->dv_bus_shutdown = shutdown;
   2390 	dev->dv_bus_deregister = deregister;
   2391 }
   2392 
   2393 void
   2394 device_pmf_bus_deregister(device_t dev)
   2395 {
   2396 	if (dev->dv_bus_deregister == NULL)
   2397 		return;
   2398 	(*dev->dv_bus_deregister)(dev);
   2399 	dev->dv_bus_private = NULL;
   2400 	dev->dv_bus_suspend = NULL;
   2401 	dev->dv_bus_resume = NULL;
   2402 	dev->dv_bus_deregister = NULL;
   2403 }
   2404 
   2405 void *
   2406 device_pmf_class_private(device_t dev)
   2407 {
   2408 	return dev->dv_class_private;
   2409 }
   2410 
   2411 bool
   2412 device_pmf_class_suspend(device_t dev, const pmf_qual_t *qual)
   2413 {
   2414 	if ((dev->dv_flags & DVF_CLASS_SUSPENDED) != 0)
   2415 		return true;
   2416 	if (pmf_qual_depth(qual) <= DEVACT_LEVEL_CLASS &&
   2417 	    dev->dv_class_suspend != NULL &&
   2418 	    !(*dev->dv_class_suspend)(dev, qual))
   2419 		return false;
   2420 
   2421 	dev->dv_flags |= DVF_CLASS_SUSPENDED;
   2422 	return true;
   2423 }
   2424 
   2425 bool
   2426 device_pmf_class_resume(device_t dev, const pmf_qual_t *qual)
   2427 {
   2428 	if ((dev->dv_flags & DVF_CLASS_SUSPENDED) == 0)
   2429 		return true;
   2430 	if ((dev->dv_flags & DVF_BUS_SUSPENDED) != 0 ||
   2431 	    (dev->dv_flags & DVF_DRIVER_SUSPENDED) != 0)
   2432 		return false;
   2433 	if (pmf_qual_depth(qual) <= DEVACT_LEVEL_CLASS &&
   2434 	    dev->dv_class_resume != NULL &&
   2435 	    !(*dev->dv_class_resume)(dev, qual))
   2436 		return false;
   2437 
   2438 	dev->dv_flags &= ~DVF_CLASS_SUSPENDED;
   2439 	return true;
   2440 }
   2441 
   2442 void
   2443 device_pmf_class_register(device_t dev, void *priv,
   2444     bool (*suspend)(device_t, const pmf_qual_t *),
   2445     bool (*resume)(device_t, const pmf_qual_t *),
   2446     void (*deregister)(device_t))
   2447 {
   2448 	dev->dv_class_private = priv;
   2449 	dev->dv_class_suspend = suspend;
   2450 	dev->dv_class_resume = resume;
   2451 	dev->dv_class_deregister = deregister;
   2452 }
   2453 
   2454 void
   2455 device_pmf_class_deregister(device_t dev)
   2456 {
   2457 	if (dev->dv_class_deregister == NULL)
   2458 		return;
   2459 	(*dev->dv_class_deregister)(dev);
   2460 	dev->dv_class_private = NULL;
   2461 	dev->dv_class_suspend = NULL;
   2462 	dev->dv_class_resume = NULL;
   2463 	dev->dv_class_deregister = NULL;
   2464 }
   2465 
   2466 bool
   2467 device_active(device_t dev, devactive_t type)
   2468 {
   2469 	size_t i;
   2470 
   2471 	if (dev->dv_activity_count == 0)
   2472 		return false;
   2473 
   2474 	for (i = 0; i < dev->dv_activity_count; ++i) {
   2475 		if (dev->dv_activity_handlers[i] == NULL)
   2476 			break;
   2477 		(*dev->dv_activity_handlers[i])(dev, type);
   2478 	}
   2479 
   2480 	return true;
   2481 }
   2482 
   2483 bool
   2484 device_active_register(device_t dev, void (*handler)(device_t, devactive_t))
   2485 {
   2486 	void (**new_handlers)(device_t, devactive_t);
   2487 	void (**old_handlers)(device_t, devactive_t);
   2488 	size_t i, old_size, new_size;
   2489 	int s;
   2490 
   2491 	old_handlers = dev->dv_activity_handlers;
   2492 	old_size = dev->dv_activity_count;
   2493 
   2494 	for (i = 0; i < old_size; ++i) {
   2495 		KASSERT(old_handlers[i] != handler);
   2496 		if (old_handlers[i] == NULL) {
   2497 			old_handlers[i] = handler;
   2498 			return true;
   2499 		}
   2500 	}
   2501 
   2502 	new_size = old_size + 4;
   2503 	new_handlers = kmem_alloc(sizeof(void *[new_size]), KM_SLEEP);
   2504 
   2505 	memcpy(new_handlers, old_handlers, sizeof(void *[old_size]));
   2506 	new_handlers[old_size] = handler;
   2507 	memset(new_handlers + old_size + 1, 0,
   2508 	    sizeof(int [new_size - (old_size+1)]));
   2509 
   2510 	s = splhigh();
   2511 	dev->dv_activity_count = new_size;
   2512 	dev->dv_activity_handlers = new_handlers;
   2513 	splx(s);
   2514 
   2515 	if (old_handlers != NULL)
   2516 		kmem_free(old_handlers, sizeof(void * [old_size]));
   2517 
   2518 	return true;
   2519 }
   2520 
   2521 void
   2522 device_active_deregister(device_t dev, void (*handler)(device_t, devactive_t))
   2523 {
   2524 	void (**old_handlers)(device_t, devactive_t);
   2525 	size_t i, old_size;
   2526 	int s;
   2527 
   2528 	old_handlers = dev->dv_activity_handlers;
   2529 	old_size = dev->dv_activity_count;
   2530 
   2531 	for (i = 0; i < old_size; ++i) {
   2532 		if (old_handlers[i] == handler)
   2533 			break;
   2534 		if (old_handlers[i] == NULL)
   2535 			return; /* XXX panic? */
   2536 	}
   2537 
   2538 	if (i == old_size)
   2539 		return; /* XXX panic? */
   2540 
   2541 	for (; i < old_size - 1; ++i) {
   2542 		if ((old_handlers[i] = old_handlers[i + 1]) != NULL)
   2543 			continue;
   2544 
   2545 		if (i == 0) {
   2546 			s = splhigh();
   2547 			dev->dv_activity_count = 0;
   2548 			dev->dv_activity_handlers = NULL;
   2549 			splx(s);
   2550 			kmem_free(old_handlers, sizeof(void *[old_size]));
   2551 		}
   2552 		return;
   2553 	}
   2554 	old_handlers[i] = NULL;
   2555 }
   2556 
   2557 /* Return true iff the device_t `dev' exists at generation `gen'. */
   2558 static bool
   2559 device_exists_at(device_t dv, devgen_t gen)
   2560 {
   2561 	return (dv->dv_del_gen == 0 || dv->dv_del_gen > gen) &&
   2562 	    dv->dv_add_gen <= gen;
   2563 }
   2564 
   2565 static bool
   2566 deviter_visits(const deviter_t *di, device_t dv)
   2567 {
   2568 	return device_exists_at(dv, di->di_gen);
   2569 }
   2570 
   2571 /*
   2572  * Device Iteration
   2573  *
   2574  * deviter_t: a device iterator.  Holds state for a "walk" visiting
   2575  *     each device_t's in the device tree.
   2576  *
   2577  * deviter_init(di, flags): initialize the device iterator `di'
   2578  *     to "walk" the device tree.  deviter_next(di) will return
   2579  *     the first device_t in the device tree, or NULL if there are
   2580  *     no devices.
   2581  *
   2582  *     `flags' is one or more of DEVITER_F_RW, indicating that the
   2583  *     caller intends to modify the device tree by calling
   2584  *     config_detach(9) on devices in the order that the iterator
   2585  *     returns them; DEVITER_F_ROOT_FIRST, asking for the devices
   2586  *     nearest the "root" of the device tree to be returned, first;
   2587  *     DEVITER_F_LEAVES_FIRST, asking for the devices furthest from
   2588  *     the root of the device tree, first; and DEVITER_F_SHUTDOWN,
   2589  *     indicating both that deviter_init() should not respect any
   2590  *     locks on the device tree, and that deviter_next(di) may run
   2591  *     in more than one LWP before the walk has finished.
   2592  *
   2593  *     Only one DEVITER_F_RW iterator may be in the device tree at
   2594  *     once.
   2595  *
   2596  *     DEVITER_F_SHUTDOWN implies DEVITER_F_RW.
   2597  *
   2598  *     Results are undefined if the flags DEVITER_F_ROOT_FIRST and
   2599  *     DEVITER_F_LEAVES_FIRST are used in combination.
   2600  *
   2601  * deviter_first(di, flags): initialize the device iterator `di'
   2602  *     and return the first device_t in the device tree, or NULL
   2603  *     if there are no devices.  The statement
   2604  *
   2605  *         dv = deviter_first(di);
   2606  *
   2607  *     is shorthand for
   2608  *
   2609  *         deviter_init(di);
   2610  *         dv = deviter_next(di);
   2611  *
   2612  * deviter_next(di): return the next device_t in the device tree,
   2613  *     or NULL if there are no more devices.  deviter_next(di)
   2614  *     is undefined if `di' was not initialized with deviter_init() or
   2615  *     deviter_first().
   2616  *
   2617  * deviter_release(di): stops iteration (subsequent calls to
   2618  *     deviter_next() will return NULL), releases any locks and
   2619  *     resources held by the device iterator.
   2620  *
   2621  * Device iteration does not return device_t's in any particular
   2622  * order.  An iterator will never return the same device_t twice.
   2623  * Device iteration is guaranteed to complete---i.e., if deviter_next(di)
   2624  * is called repeatedly on the same `di', it will eventually return
   2625  * NULL.  It is ok to attach/detach devices during device iteration.
   2626  */
   2627 void
   2628 deviter_init(deviter_t *di, deviter_flags_t flags)
   2629 {
   2630 	device_t dv;
   2631 	int s;
   2632 
   2633 	memset(di, 0, sizeof(*di));
   2634 
   2635 	s = config_alldevs_lock();
   2636 	if ((flags & DEVITER_F_SHUTDOWN) != 0)
   2637 		flags |= DEVITER_F_RW;
   2638 
   2639 	if ((flags & DEVITER_F_RW) != 0)
   2640 		alldevs_nwrite++;
   2641 	else
   2642 		alldevs_nread++;
   2643 	di->di_gen = alldevs_gen++;
   2644 	config_alldevs_unlock(s);
   2645 
   2646 	di->di_flags = flags;
   2647 
   2648 	switch (di->di_flags & (DEVITER_F_LEAVES_FIRST|DEVITER_F_ROOT_FIRST)) {
   2649 	case DEVITER_F_LEAVES_FIRST:
   2650 		TAILQ_FOREACH(dv, &alldevs, dv_list) {
   2651 			if (!deviter_visits(di, dv))
   2652 				continue;
   2653 			di->di_curdepth = MAX(di->di_curdepth, dv->dv_depth);
   2654 		}
   2655 		break;
   2656 	case DEVITER_F_ROOT_FIRST:
   2657 		TAILQ_FOREACH(dv, &alldevs, dv_list) {
   2658 			if (!deviter_visits(di, dv))
   2659 				continue;
   2660 			di->di_maxdepth = MAX(di->di_maxdepth, dv->dv_depth);
   2661 		}
   2662 		break;
   2663 	default:
   2664 		break;
   2665 	}
   2666 
   2667 	deviter_reinit(di);
   2668 }
   2669 
   2670 static void
   2671 deviter_reinit(deviter_t *di)
   2672 {
   2673 	if ((di->di_flags & DEVITER_F_RW) != 0)
   2674 		di->di_prev = TAILQ_LAST(&alldevs, devicelist);
   2675 	else
   2676 		di->di_prev = TAILQ_FIRST(&alldevs);
   2677 }
   2678 
   2679 device_t
   2680 deviter_first(deviter_t *di, deviter_flags_t flags)
   2681 {
   2682 	deviter_init(di, flags);
   2683 	return deviter_next(di);
   2684 }
   2685 
   2686 static device_t
   2687 deviter_next2(deviter_t *di)
   2688 {
   2689 	device_t dv;
   2690 
   2691 	dv = di->di_prev;
   2692 
   2693 	if (dv == NULL)
   2694 		return NULL;
   2695 
   2696 	if ((di->di_flags & DEVITER_F_RW) != 0)
   2697 		di->di_prev = TAILQ_PREV(dv, devicelist, dv_list);
   2698 	else
   2699 		di->di_prev = TAILQ_NEXT(dv, dv_list);
   2700 
   2701 	return dv;
   2702 }
   2703 
   2704 static device_t
   2705 deviter_next1(deviter_t *di)
   2706 {
   2707 	device_t dv;
   2708 
   2709 	do {
   2710 		dv = deviter_next2(di);
   2711 	} while (dv != NULL && !deviter_visits(di, dv));
   2712 
   2713 	return dv;
   2714 }
   2715 
   2716 device_t
   2717 deviter_next(deviter_t *di)
   2718 {
   2719 	device_t dv = NULL;
   2720 
   2721 	switch (di->di_flags & (DEVITER_F_LEAVES_FIRST|DEVITER_F_ROOT_FIRST)) {
   2722 	case 0:
   2723 		return deviter_next1(di);
   2724 	case DEVITER_F_LEAVES_FIRST:
   2725 		while (di->di_curdepth >= 0) {
   2726 			if ((dv = deviter_next1(di)) == NULL) {
   2727 				di->di_curdepth--;
   2728 				deviter_reinit(di);
   2729 			} else if (dv->dv_depth == di->di_curdepth)
   2730 				break;
   2731 		}
   2732 		return dv;
   2733 	case DEVITER_F_ROOT_FIRST:
   2734 		while (di->di_curdepth <= di->di_maxdepth) {
   2735 			if ((dv = deviter_next1(di)) == NULL) {
   2736 				di->di_curdepth++;
   2737 				deviter_reinit(di);
   2738 			} else if (dv->dv_depth == di->di_curdepth)
   2739 				break;
   2740 		}
   2741 		return dv;
   2742 	default:
   2743 		return NULL;
   2744 	}
   2745 }
   2746 
   2747 void
   2748 deviter_release(deviter_t *di)
   2749 {
   2750 	bool rw = (di->di_flags & DEVITER_F_RW) != 0;
   2751 	int s;
   2752 
   2753 	s = config_alldevs_lock();
   2754 	if (rw)
   2755 		--alldevs_nwrite;
   2756 	else
   2757 		--alldevs_nread;
   2758 	/* XXX wake a garbage-collection thread */
   2759 	config_alldevs_unlock(s);
   2760 }
   2761 
   2762 const char *
   2763 cfdata_ifattr(const struct cfdata *cf)
   2764 {
   2765 	return cf->cf_pspec->cfp_iattr;
   2766 }
   2767 
   2768 bool
   2769 ifattr_match(const char *snull, const char *t)
   2770 {
   2771 	return (snull == NULL) || strcmp(snull, t) == 0;
   2772 }
   2773 
   2774 void
   2775 null_childdetached(device_t self, device_t child)
   2776 {
   2777 	/* do nothing */
   2778 }
   2779 
   2780 static void
   2781 sysctl_detach_setup(struct sysctllog **clog)
   2782 {
   2783 	const struct sysctlnode *node = NULL;
   2784 
   2785 	sysctl_createv(clog, 0, NULL, &node,
   2786 		CTLFLAG_PERMANENT,
   2787 		CTLTYPE_NODE, "kern", NULL,
   2788 		NULL, 0, NULL, 0,
   2789 		CTL_KERN, CTL_EOL);
   2790 
   2791 	if (node == NULL)
   2792 		return;
   2793 
   2794 	sysctl_createv(clog, 0, &node, NULL,
   2795 		CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
   2796 		CTLTYPE_BOOL, "detachall",
   2797 		SYSCTL_DESCR("Detach all devices at shutdown"),
   2798 		NULL, 0, &detachall, 0,
   2799 		CTL_CREATE, CTL_EOL);
   2800 }
   2801