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