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