Home | History | Annotate | Line # | Download | only in kern
subr_autoconf.c revision 1.252.4.4
      1 /* $NetBSD: subr_autoconf.c,v 1.252.4.4 2017/05/17 01:44:18 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.4 2017/05/17 01:44:18 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  * Also note that config_attach_pseudo() returns with a localcount
   1659  * reference held on the device_t.  It is the caller's responsibility
   1660  * to release this reference.
   1661  */
   1662 device_t
   1663 config_attach_pseudo(cfdata_t cf)
   1664 {
   1665 	device_t dev;
   1666 
   1667 	dev = config_devalloc(ROOT, cf, NULL);
   1668 	if (!dev)
   1669 		return NULL;
   1670 
   1671 	/* XXX mark busy in cfdata */
   1672 
   1673 	if (cf->cf_fstate != FSTATE_STAR) {
   1674 		KASSERT(cf->cf_fstate == FSTATE_NOTFOUND);
   1675 		cf->cf_fstate = FSTATE_FOUND;
   1676 	}
   1677 
   1678 	config_devlink(dev);
   1679 
   1680 #if 0	/* XXXJRT not yet */
   1681 	device_register(dev, NULL);	/* like a root node */
   1682 #endif
   1683 
   1684 	/* Grab a reference to the device */
   1685 	device_acquire(dev);
   1686 
   1687 	/* Let userland know */
   1688 	devmon_report_device(dev, true);
   1689 
   1690 	(*dev->dv_cfattach->ca_attach)(ROOT, dev, NULL);
   1691 
   1692 	config_process_deferred(&deferred_config_queue, dev);
   1693 	return dev;
   1694 }
   1695 
   1696 /*
   1697  * Caller must hold alldevs.lock.
   1698  */
   1699 static void
   1700 config_collect_garbage(struct devicelist *garbage)
   1701 {
   1702 	device_t dv;
   1703 
   1704 	KASSERT(!cpu_intr_p());
   1705 	KASSERT(!cpu_softintr_p());
   1706 	KASSERT(mutex_owned(&alldevs.lock));
   1707 
   1708 	while (alldevs.nwrite == 0 && alldevs.nread == 0 && alldevs.garbage) {
   1709 		TAILQ_FOREACH(dv, &alldevs.list, dv_list) {
   1710 			if (dv->dv_del_gen != 0)
   1711 				break;
   1712 		}
   1713 		if (dv == NULL) {
   1714 			alldevs.garbage = false;
   1715 			break;
   1716 		}
   1717 		config_devunlink(dv, garbage);
   1718 	}
   1719 	KASSERT(mutex_owned(&alldevs.lock));
   1720 }
   1721 
   1722 static void
   1723 config_dump_garbage(struct devicelist *garbage)
   1724 {
   1725 	device_t dv;
   1726 
   1727 	while ((dv = TAILQ_FIRST(garbage)) != NULL) {
   1728 		TAILQ_REMOVE(garbage, dv, dv_list);
   1729 		config_devdelete(dv);
   1730 	}
   1731 }
   1732 
   1733 /*
   1734  * Acquire a reference to a device, and then detach it.
   1735  */
   1736 int
   1737 config_detach(device_t dev, int flags)
   1738 {
   1739 
   1740 	device_acquire(dev);
   1741 	return config_detach_release(dev, flags);
   1742 }
   1743 
   1744 /*
   1745  * Detach a device.  Optionally forced (e.g. because of hardware
   1746  * removal) and quiet.  Returns zero if successful, non-zero
   1747  * (an error code) otherwise.
   1748  *
   1749  * Note that this code wants to be run from a process context, so
   1750  * that the detach can sleep to allow processes which have a device
   1751  * open to run and unwind their stacks.
   1752  *
   1753  * Also note that this code requires that the caller have acquired
   1754  * a reference to the device; callers that have not been updated
   1755  * for localcount should instead call config_detach().  The reference
   1756  * is released in all cases.
   1757  */
   1758 int
   1759 config_detach_release(device_t dev, int flags)
   1760 {
   1761 	struct alldevs_foray af;
   1762 	struct cftable *ct;
   1763 	cfdata_t cf;
   1764 	const struct cfattach *ca;
   1765 	struct cfdriver *cd;
   1766 	device_t d __diagused;
   1767 	int rv = 0;
   1768 
   1769 	cf = dev->dv_cfdata;
   1770 	KASSERTMSG((cf == NULL || cf->cf_fstate == FSTATE_FOUND ||
   1771 		cf->cf_fstate == FSTATE_STAR),
   1772 	    "config_detach: %s: bad device fstate: %d",
   1773 	    device_xname(dev), cf ? cf->cf_fstate : -1);
   1774 
   1775 	cd = dev->dv_cfdriver;
   1776 	KASSERT(cd != NULL);
   1777 
   1778 	ca = dev->dv_cfattach;
   1779 	KASSERT(ca != NULL);
   1780 
   1781 	mutex_enter(&alldevs.lock);
   1782 	if (dev->dv_del_gen != 0) {
   1783 		mutex_exit(&alldevs.lock);
   1784 #ifdef DIAGNOSTIC
   1785 		printf("%s: %s is already detached\n", __func__,
   1786 		    device_xname(dev));
   1787 #endif /* DIAGNOSTIC */
   1788 		device_release(dev);
   1789 		return ENOENT;
   1790 	}
   1791 	alldevs.nwrite++;
   1792 	mutex_exit(&alldevs.lock);
   1793 
   1794 	if (!detachall &&
   1795 	    (flags & (DETACH_SHUTDOWN|DETACH_FORCE)) == DETACH_SHUTDOWN &&
   1796 	    (dev->dv_flags & DVF_DETACH_SHUTDOWN) == 0) {
   1797 		rv = EOPNOTSUPP;
   1798 	} else if (ca->ca_detach != NULL) {
   1799 		rv = (*ca->ca_detach)(dev, flags);
   1800 	} else
   1801 		rv = EOPNOTSUPP;
   1802 
   1803 	/*
   1804 	 * If it was not possible to detach the device, then we either
   1805 	 * panic() (for the forced but failed case), or return an error.
   1806 	 *
   1807 	 * If it was possible to detach the device, ensure that the
   1808 	 * device is deactivated.
   1809 	 */
   1810 	if (rv == 0)
   1811 		dev->dv_flags &= ~DVF_ACTIVE;
   1812 	else if ((flags & DETACH_FORCE) == 0)
   1813 		goto out;
   1814 	else {
   1815 		panic("config_detach: forced detach of %s failed (%d)",
   1816 		    device_xname(dev), rv);
   1817 	}
   1818 
   1819 	/*
   1820 	 * The device has now been successfully detached.
   1821 	 */
   1822 
   1823 	/* Let userland know */
   1824 	devmon_report_device(dev, false);
   1825 
   1826 #ifdef DIAGNOSTIC
   1827 	/*
   1828 	 * Sanity: If you're successfully detached, you should have no
   1829 	 * children.  (Note that because children must be attached
   1830 	 * after parents, we only need to search the latter part of
   1831 	 * the list.)
   1832 	 */
   1833 	for (d = TAILQ_NEXT(dev, dv_list); d != NULL;
   1834 	    d = TAILQ_NEXT(d, dv_list)) {
   1835 		if (d->dv_parent == dev && d->dv_del_gen == 0) {
   1836 			printf("config_detach: detached device %s"
   1837 			    " has children %s\n", device_xname(dev),
   1838 			    device_xname(d));
   1839 			panic("config_detach");
   1840 		}
   1841 	}
   1842 #endif
   1843 
   1844 	/* notify the parent that the child is gone */
   1845 	if (dev->dv_parent) {
   1846 		device_t p = dev->dv_parent;
   1847 		if (p->dv_cfattach->ca_childdetached)
   1848 			(*p->dv_cfattach->ca_childdetached)(p, dev);
   1849 	}
   1850 
   1851 	/*
   1852 	 * Mark cfdata to show that the unit can be reused, if possible.
   1853 	 */
   1854 	TAILQ_FOREACH(ct, &allcftables, ct_list) {
   1855 		for (cf = ct->ct_cfdata; cf->cf_name; cf++) {
   1856 			if (STREQ(cf->cf_name, cd->cd_name)) {
   1857 				if (cf->cf_fstate == FSTATE_FOUND &&
   1858 				    cf->cf_unit == dev->dv_unit)
   1859 					cf->cf_fstate = FSTATE_NOTFOUND;
   1860 			}
   1861 		}
   1862 	}
   1863 
   1864 	if (dev->dv_cfdata != NULL && (flags & DETACH_QUIET) == 0)
   1865 		aprint_normal_dev(dev, "detached\n");
   1866 
   1867 out:
   1868 	config_alldevs_enter(&af);
   1869 	KASSERT(alldevs.nwrite != 0);
   1870 	--alldevs.nwrite;
   1871 	if (rv == 0 && dev->dv_del_gen == 0) {
   1872 		if (alldevs.nwrite == 0 && alldevs.nread == 0)
   1873 			config_devunlink(dev, &af.af_garbage);
   1874 		else {
   1875 			dev->dv_del_gen = alldevs.gen;
   1876 			alldevs.garbage = true;
   1877 		}
   1878 	}
   1879 	config_alldevs_exit(&af);
   1880 	if (rv != 0)
   1881 		device_release(dev);
   1882 
   1883 	return rv;
   1884 }
   1885 
   1886 int
   1887 config_detach_children(device_t parent, int flags)
   1888 {
   1889 	device_t dv;
   1890 	deviter_t di;
   1891 	int error = 0;
   1892 
   1893 	for (dv = deviter_first(&di, DEVITER_F_RW); dv != NULL;
   1894 	     dv = deviter_next(&di)) {
   1895 		if (device_parent(dv) != parent)
   1896 			continue;
   1897 		if ((error = config_detach(dv, flags)) != 0)
   1898 			break;
   1899 	}
   1900 	deviter_release(&di);
   1901 	return error;
   1902 }
   1903 
   1904 device_t
   1905 shutdown_first(struct shutdown_state *s)
   1906 {
   1907 	if (!s->initialized) {
   1908 		deviter_init(&s->di, DEVITER_F_SHUTDOWN|DEVITER_F_LEAVES_FIRST);
   1909 		s->initialized = true;
   1910 	}
   1911 	return shutdown_next(s);
   1912 }
   1913 
   1914 device_t
   1915 shutdown_next(struct shutdown_state *s)
   1916 {
   1917 	device_t dv;
   1918 
   1919 	while ((dv = deviter_next(&s->di)) != NULL && !device_is_active(dv))
   1920 		;
   1921 
   1922 	if (dv == NULL)
   1923 		s->initialized = false;
   1924 
   1925 	return dv;
   1926 }
   1927 
   1928 bool
   1929 config_detach_all(int how)
   1930 {
   1931 	static struct shutdown_state s;
   1932 	device_t curdev;
   1933 	bool progress = false;
   1934 	int flags;
   1935 
   1936 	if ((how & (RB_NOSYNC|RB_DUMP)) != 0)
   1937 		return false;
   1938 
   1939 	if ((how & RB_POWERDOWN) == RB_POWERDOWN)
   1940 		flags = DETACH_SHUTDOWN | DETACH_POWEROFF;
   1941 	else
   1942 		flags = DETACH_SHUTDOWN;
   1943 
   1944 	for (curdev = shutdown_first(&s); curdev != NULL;
   1945 	     curdev = shutdown_next(&s)) {
   1946 		aprint_debug(" detaching %s, ", device_xname(curdev));
   1947 		if (config_detach(curdev, flags) == 0) {
   1948 			progress = true;
   1949 			aprint_debug("success.");
   1950 		} else
   1951 			aprint_debug("failed.");
   1952 	}
   1953 	return progress;
   1954 }
   1955 
   1956 static bool
   1957 device_is_ancestor_of(device_t ancestor, device_t descendant)
   1958 {
   1959 	device_t dv;
   1960 
   1961 	for (dv = descendant; dv != NULL; dv = device_parent(dv)) {
   1962 		if (device_parent(dv) == ancestor)
   1963 			return true;
   1964 	}
   1965 	return false;
   1966 }
   1967 
   1968 int
   1969 config_deactivate(device_t dev)
   1970 {
   1971 	deviter_t di;
   1972 	const struct cfattach *ca;
   1973 	device_t descendant;
   1974 	int s, rv = 0, oflags;
   1975 
   1976 	for (descendant = deviter_first(&di, DEVITER_F_ROOT_FIRST);
   1977 	     descendant != NULL;
   1978 	     descendant = deviter_next(&di)) {
   1979 		if (dev != descendant &&
   1980 		    !device_is_ancestor_of(dev, descendant))
   1981 			continue;
   1982 
   1983 		if ((descendant->dv_flags & DVF_ACTIVE) == 0)
   1984 			continue;
   1985 
   1986 		ca = descendant->dv_cfattach;
   1987 		oflags = descendant->dv_flags;
   1988 
   1989 		descendant->dv_flags &= ~DVF_ACTIVE;
   1990 		if (ca->ca_activate == NULL)
   1991 			continue;
   1992 		s = splhigh();
   1993 		rv = (*ca->ca_activate)(descendant, DVACT_DEACTIVATE);
   1994 		splx(s);
   1995 		if (rv != 0)
   1996 			descendant->dv_flags = oflags;
   1997 	}
   1998 	deviter_release(&di);
   1999 	return rv;
   2000 }
   2001 
   2002 /*
   2003  * Defer the configuration of the specified device until all
   2004  * of its parent's devices have been attached.
   2005  */
   2006 void
   2007 config_defer(device_t dev, void (*func)(device_t))
   2008 {
   2009 	struct deferred_config *dc;
   2010 
   2011 	if (dev->dv_parent == NULL)
   2012 		panic("config_defer: can't defer config of a root device");
   2013 
   2014 #ifdef DIAGNOSTIC
   2015 	TAILQ_FOREACH(dc, &deferred_config_queue, dc_queue) {
   2016 		if (dc->dc_dev == dev)
   2017 			panic("config_defer: deferred twice");
   2018 	}
   2019 #endif
   2020 
   2021 	dc = kmem_alloc(sizeof(*dc), KM_SLEEP);
   2022 	if (dc == NULL)
   2023 		panic("config_defer: unable to allocate callback");
   2024 
   2025 	dc->dc_dev = dev;
   2026 	dc->dc_func = func;
   2027 	TAILQ_INSERT_TAIL(&deferred_config_queue, dc, dc_queue);
   2028 	config_pending_incr(dev);
   2029 }
   2030 
   2031 /*
   2032  * Defer some autoconfiguration for a device until after interrupts
   2033  * are enabled.
   2034  */
   2035 void
   2036 config_interrupts(device_t dev, void (*func)(device_t))
   2037 {
   2038 	struct deferred_config *dc;
   2039 
   2040 	/*
   2041 	 * If interrupts are enabled, callback now.
   2042 	 */
   2043 	if (cold == 0) {
   2044 		(*func)(dev);
   2045 		return;
   2046 	}
   2047 
   2048 #ifdef DIAGNOSTIC
   2049 	TAILQ_FOREACH(dc, &interrupt_config_queue, dc_queue) {
   2050 		if (dc->dc_dev == dev)
   2051 			panic("config_interrupts: deferred twice");
   2052 	}
   2053 #endif
   2054 
   2055 	dc = kmem_alloc(sizeof(*dc), KM_SLEEP);
   2056 	if (dc == NULL)
   2057 		panic("config_interrupts: unable to allocate callback");
   2058 
   2059 	dc->dc_dev = dev;
   2060 	dc->dc_func = func;
   2061 	TAILQ_INSERT_TAIL(&interrupt_config_queue, dc, dc_queue);
   2062 	config_pending_incr(dev);
   2063 }
   2064 
   2065 /*
   2066  * Defer some autoconfiguration for a device until after root file system
   2067  * is mounted (to load firmware etc).
   2068  */
   2069 void
   2070 config_mountroot(device_t dev, void (*func)(device_t))
   2071 {
   2072 	struct deferred_config *dc;
   2073 
   2074 	/*
   2075 	 * If root file system is mounted, callback now.
   2076 	 */
   2077 	if (root_is_mounted) {
   2078 		(*func)(dev);
   2079 		return;
   2080 	}
   2081 
   2082 #ifdef DIAGNOSTIC
   2083 	TAILQ_FOREACH(dc, &mountroot_config_queue, dc_queue) {
   2084 		if (dc->dc_dev == dev)
   2085 			panic("%s: deferred twice", __func__);
   2086 	}
   2087 #endif
   2088 
   2089 	dc = kmem_alloc(sizeof(*dc), KM_SLEEP);
   2090 	if (dc == NULL)
   2091 		panic("%s: unable to allocate callback", __func__);
   2092 
   2093 	dc->dc_dev = dev;
   2094 	dc->dc_func = func;
   2095 	TAILQ_INSERT_TAIL(&mountroot_config_queue, dc, dc_queue);
   2096 }
   2097 
   2098 /*
   2099  * Process a deferred configuration queue.
   2100  */
   2101 static void
   2102 config_process_deferred(struct deferred_config_head *queue, device_t parent)
   2103 {
   2104 	struct deferred_config *dc, *ndc;
   2105 
   2106 	for (dc = TAILQ_FIRST(queue); dc != NULL; dc = ndc) {
   2107 		ndc = TAILQ_NEXT(dc, dc_queue);
   2108 		if (parent == NULL || dc->dc_dev->dv_parent == parent) {
   2109 			TAILQ_REMOVE(queue, dc, dc_queue);
   2110 			(*dc->dc_func)(dc->dc_dev);
   2111 			config_pending_decr(dc->dc_dev);
   2112 			kmem_free(dc, sizeof(*dc));
   2113 		}
   2114 	}
   2115 }
   2116 
   2117 /*
   2118  * Manipulate the config_pending semaphore.
   2119  */
   2120 void
   2121 config_pending_incr(device_t dev)
   2122 {
   2123 
   2124 	mutex_enter(&config_misc_lock);
   2125 	config_pending++;
   2126 #ifdef DEBUG_AUTOCONF
   2127 	printf("%s: %s %d\n", __func__, device_xname(dev), config_pending);
   2128 #endif
   2129 	mutex_exit(&config_misc_lock);
   2130 }
   2131 
   2132 void
   2133 config_pending_decr(device_t dev)
   2134 {
   2135 
   2136 	KASSERT(0 < config_pending);
   2137 	mutex_enter(&config_misc_lock);
   2138 	config_pending--;
   2139 #ifdef DEBUG_AUTOCONF
   2140 	printf("%s: %s %d\n", __func__, device_xname(dev), config_pending);
   2141 #endif
   2142 	if (config_pending == 0)
   2143 		cv_broadcast(&config_misc_cv);
   2144 	mutex_exit(&config_misc_lock);
   2145 }
   2146 
   2147 /*
   2148  * Register a "finalization" routine.  Finalization routines are
   2149  * called iteratively once all real devices have been found during
   2150  * autoconfiguration, for as long as any one finalizer has done
   2151  * any work.
   2152  */
   2153 int
   2154 config_finalize_register(device_t dev, int (*fn)(device_t))
   2155 {
   2156 	struct finalize_hook *f;
   2157 
   2158 	/*
   2159 	 * If finalization has already been done, invoke the
   2160 	 * callback function now.
   2161 	 */
   2162 	if (config_finalize_done) {
   2163 		while ((*fn)(dev) != 0)
   2164 			/* loop */ ;
   2165 		return 0;
   2166 	}
   2167 
   2168 	/* Ensure this isn't already on the list. */
   2169 	TAILQ_FOREACH(f, &config_finalize_list, f_list) {
   2170 		if (f->f_func == fn && f->f_dev == dev)
   2171 			return EEXIST;
   2172 	}
   2173 
   2174 	f = kmem_alloc(sizeof(*f), KM_SLEEP);
   2175 	f->f_func = fn;
   2176 	f->f_dev = dev;
   2177 	TAILQ_INSERT_TAIL(&config_finalize_list, f, f_list);
   2178 
   2179 	return 0;
   2180 }
   2181 
   2182 void
   2183 config_finalize(void)
   2184 {
   2185 	struct finalize_hook *f;
   2186 	struct pdevinit *pdev;
   2187 	extern struct pdevinit pdevinit[];
   2188 	int errcnt, rv;
   2189 
   2190 	/*
   2191 	 * Now that device driver threads have been created, wait for
   2192 	 * them to finish any deferred autoconfiguration.
   2193 	 */
   2194 	mutex_enter(&config_misc_lock);
   2195 	while (config_pending != 0)
   2196 		cv_wait(&config_misc_cv, &config_misc_lock);
   2197 	mutex_exit(&config_misc_lock);
   2198 
   2199 	KERNEL_LOCK(1, NULL);
   2200 
   2201 	/* Attach pseudo-devices. */
   2202 	for (pdev = pdevinit; pdev->pdev_attach != NULL; pdev++)
   2203 		(*pdev->pdev_attach)(pdev->pdev_count);
   2204 
   2205 	/* Run the hooks until none of them does any work. */
   2206 	do {
   2207 		rv = 0;
   2208 		TAILQ_FOREACH(f, &config_finalize_list, f_list)
   2209 			rv |= (*f->f_func)(f->f_dev);
   2210 	} while (rv != 0);
   2211 
   2212 	config_finalize_done = 1;
   2213 
   2214 	/* Now free all the hooks. */
   2215 	while ((f = TAILQ_FIRST(&config_finalize_list)) != NULL) {
   2216 		TAILQ_REMOVE(&config_finalize_list, f, f_list);
   2217 		kmem_free(f, sizeof(*f));
   2218 	}
   2219 
   2220 	KERNEL_UNLOCK_ONE(NULL);
   2221 
   2222 	errcnt = aprint_get_error_count();
   2223 	if ((boothowto & (AB_QUIET|AB_SILENT)) != 0 &&
   2224 	    (boothowto & AB_VERBOSE) == 0) {
   2225 		mutex_enter(&config_misc_lock);
   2226 		if (config_do_twiddle) {
   2227 			config_do_twiddle = 0;
   2228 			printf_nolog(" done.\n");
   2229 		}
   2230 		mutex_exit(&config_misc_lock);
   2231 	}
   2232 	if (errcnt != 0) {
   2233 		printf("WARNING: %d error%s while detecting hardware; "
   2234 		    "check system log.\n", errcnt,
   2235 		    errcnt == 1 ? "" : "s");
   2236 	}
   2237 }
   2238 
   2239 void
   2240 config_twiddle_init(void)
   2241 {
   2242 
   2243 	if ((boothowto & (AB_SILENT|AB_VERBOSE)) == AB_SILENT) {
   2244 		config_do_twiddle = 1;
   2245 	}
   2246 	callout_setfunc(&config_twiddle_ch, config_twiddle_fn, NULL);
   2247 }
   2248 
   2249 void
   2250 config_twiddle_fn(void *cookie)
   2251 {
   2252 
   2253 	mutex_enter(&config_misc_lock);
   2254 	if (config_do_twiddle) {
   2255 		twiddle();
   2256 		callout_schedule(&config_twiddle_ch, mstohz(100));
   2257 	}
   2258 	mutex_exit(&config_misc_lock);
   2259 }
   2260 
   2261 static void
   2262 config_alldevs_enter(struct alldevs_foray *af)
   2263 {
   2264 	TAILQ_INIT(&af->af_garbage);
   2265 	mutex_enter(&alldevs.lock);
   2266 	config_collect_garbage(&af->af_garbage);
   2267 }
   2268 
   2269 static void
   2270 config_alldevs_exit(struct alldevs_foray *af)
   2271 {
   2272 	mutex_exit(&alldevs.lock);
   2273 	config_dump_garbage(&af->af_garbage);
   2274 }
   2275 
   2276 /*
   2277  * device_acquire:
   2278  *
   2279  *	Acquire a reference to the device.
   2280  */
   2281 void
   2282 device_acquire(device_t dv)
   2283 {
   2284 
   2285 	localcount_acquire(&dv->dv_localcnt);
   2286 }
   2287 
   2288 /*
   2289  * device_lookup:
   2290  *
   2291  *	Look up a device instance for a given driver.
   2292  */
   2293 device_t
   2294 device_lookup(cfdriver_t cd, int unit)
   2295 {
   2296 	device_t dv;
   2297 
   2298 	mutex_enter(&alldevs.lock);
   2299 	if (unit < 0 || unit >= cd->cd_ndevs)
   2300 		dv = NULL;
   2301 	else if ((dv = cd->cd_devs[unit]) != NULL && dv->dv_del_gen != 0)
   2302 		dv = NULL;
   2303 	mutex_exit(&alldevs.lock);
   2304 
   2305 	return dv;
   2306 }
   2307 
   2308 /*
   2309  * device_lookup_acquire:
   2310  *
   2311  *	Look up a device instance for a given driver and
   2312  *	hold a reference to the device.
   2313  */
   2314 device_t
   2315 device_lookup_acquire(cfdriver_t cd, int unit)
   2316 {
   2317 	device_t dv;
   2318 
   2319 	mutex_enter(&alldevs.lock);
   2320 	if (unit < 0 || unit >= cd->cd_ndevs)
   2321 		dv = NULL;
   2322 	else if ((dv = cd->cd_devs[unit]) != NULL && dv->dv_del_gen != 0)
   2323 		dv = NULL;
   2324 	if (dv != NULL)
   2325 		device_acquire(dv);
   2326 	mutex_exit(&alldevs.lock);
   2327 
   2328 	return dv;
   2329 }
   2330 
   2331 /*
   2332  * device_release:
   2333  *
   2334  *	Release the reference that was created by an earlier call to
   2335  *	device_acquire() or device_lookup_acquire().
   2336  */
   2337 void
   2338 device_release(device_t dv)
   2339 {
   2340 
   2341 	localcount_release(&dv->dv_localcnt, &config_drain_cv,
   2342 	    &alldevs.lock);
   2343 }
   2344 
   2345 /*
   2346  * device_lookup_private:
   2347  *
   2348  *	Look up a softc instance for a given driver.
   2349  */
   2350 void *
   2351 device_lookup_private(cfdriver_t cd, int unit)
   2352 {
   2353 
   2354 	return device_private(device_lookup(cd, unit));
   2355 }
   2356 
   2357 /*
   2358  * device_lookup_private_acquire:
   2359  *
   2360  *	Look up the softc and acquire a reference to the device so it
   2361  *	won't disappear.  Note that the caller must ensure that it is
   2362  *	capable of calling device_release() at some later point in
   2363  *	time, thus the returned private data must contain some data
   2364  *	to locate the original device.  Thus the private data must be
   2365  *	present, not NULL!  If this cannot be guaranteed, the caller
   2366  *	should use device_lookup_acquire() in order to retain the
   2367  *	device_t pointer.
   2368  */
   2369 void *
   2370 device_lookup_private_acquire(cfdriver_t cd, int unit)
   2371 {
   2372 	device_t dv;
   2373 	void *p;
   2374 
   2375 	dv = device_lookup_acquire(cd, unit);
   2376 	p = device_private(dv);
   2377 	KASSERTMSG(p != NULL || dv == NULL,
   2378 	    "%s: device %s has no private data", __func__, cd->cd_name);
   2379 	return p;
   2380 }
   2381 
   2382 /*
   2383  * device_find_by_xname:
   2384  *
   2385  *	Returns the device of the given name or NULL if it doesn't exist.
   2386  */
   2387 device_t
   2388 device_find_by_xname(const char *name)
   2389 {
   2390 	device_t dv;
   2391 	deviter_t di;
   2392 
   2393 	for (dv = deviter_first(&di, 0); dv != NULL; dv = deviter_next(&di)) {
   2394 		if (strcmp(device_xname(dv), name) == 0)
   2395 			break;
   2396 	}
   2397 	deviter_release(&di);
   2398 
   2399 	return dv;
   2400 }
   2401 
   2402 /*
   2403  * device_find_by_driver_unit:
   2404  *
   2405  *	Returns the device of the given driver name and unit or
   2406  *	NULL if it doesn't exist.
   2407  */
   2408 device_t
   2409 device_find_by_driver_unit(const char *name, int unit)
   2410 {
   2411 	struct cfdriver *cd;
   2412 
   2413 	if ((cd = config_cfdriver_lookup(name)) == NULL)
   2414 		return NULL;
   2415 	return device_lookup(cd, unit);
   2416 }
   2417 
   2418 /*
   2419  * device_find_by_driver_unit_acquire:
   2420  *
   2421  *	Returns the device of the given driver name and unit or
   2422  *	NULL if it doesn't exist.  If driver is found, it's
   2423  *	reference count is incremented so it won't go away.
   2424  */
   2425 device_t
   2426 device_find_by_driver_unit_acquire(const char *name, int unit)
   2427 {
   2428 	struct cfdriver *cd;
   2429 
   2430 	if ((cd = config_cfdriver_lookup(name)) == NULL)
   2431 		return NULL;
   2432 	return device_lookup_acquire(cd, unit);
   2433 }
   2434 
   2435 /*
   2436  * Power management related functions.
   2437  */
   2438 
   2439 bool
   2440 device_pmf_is_registered(device_t dev)
   2441 {
   2442 	return (dev->dv_flags & DVF_POWER_HANDLERS) != 0;
   2443 }
   2444 
   2445 bool
   2446 device_pmf_driver_suspend(device_t dev, const pmf_qual_t *qual)
   2447 {
   2448 	if ((dev->dv_flags & DVF_DRIVER_SUSPENDED) != 0)
   2449 		return true;
   2450 	if ((dev->dv_flags & DVF_CLASS_SUSPENDED) == 0)
   2451 		return false;
   2452 	if (pmf_qual_depth(qual) <= DEVACT_LEVEL_DRIVER &&
   2453 	    dev->dv_driver_suspend != NULL &&
   2454 	    !(*dev->dv_driver_suspend)(dev, qual))
   2455 		return false;
   2456 
   2457 	dev->dv_flags |= DVF_DRIVER_SUSPENDED;
   2458 	return true;
   2459 }
   2460 
   2461 bool
   2462 device_pmf_driver_resume(device_t dev, const pmf_qual_t *qual)
   2463 {
   2464 	if ((dev->dv_flags & DVF_DRIVER_SUSPENDED) == 0)
   2465 		return true;
   2466 	if ((dev->dv_flags & DVF_BUS_SUSPENDED) != 0)
   2467 		return false;
   2468 	if (pmf_qual_depth(qual) <= DEVACT_LEVEL_DRIVER &&
   2469 	    dev->dv_driver_resume != NULL &&
   2470 	    !(*dev->dv_driver_resume)(dev, qual))
   2471 		return false;
   2472 
   2473 	dev->dv_flags &= ~DVF_DRIVER_SUSPENDED;
   2474 	return true;
   2475 }
   2476 
   2477 bool
   2478 device_pmf_driver_shutdown(device_t dev, int how)
   2479 {
   2480 
   2481 	if (*dev->dv_driver_shutdown != NULL &&
   2482 	    !(*dev->dv_driver_shutdown)(dev, how))
   2483 		return false;
   2484 	return true;
   2485 }
   2486 
   2487 bool
   2488 device_pmf_driver_register(device_t dev,
   2489     bool (*suspend)(device_t, const pmf_qual_t *),
   2490     bool (*resume)(device_t, const pmf_qual_t *),
   2491     bool (*shutdown)(device_t, int))
   2492 {
   2493 	dev->dv_driver_suspend = suspend;
   2494 	dev->dv_driver_resume = resume;
   2495 	dev->dv_driver_shutdown = shutdown;
   2496 	dev->dv_flags |= DVF_POWER_HANDLERS;
   2497 	return true;
   2498 }
   2499 
   2500 static const char *
   2501 curlwp_name(void)
   2502 {
   2503 	if (curlwp->l_name != NULL)
   2504 		return curlwp->l_name;
   2505 	else
   2506 		return curlwp->l_proc->p_comm;
   2507 }
   2508 
   2509 void
   2510 device_pmf_driver_deregister(device_t dev)
   2511 {
   2512 	device_lock_t dvl = device_getlock(dev);
   2513 
   2514 	dev->dv_driver_suspend = NULL;
   2515 	dev->dv_driver_resume = NULL;
   2516 
   2517 	mutex_enter(&dvl->dvl_mtx);
   2518 	dev->dv_flags &= ~DVF_POWER_HANDLERS;
   2519 	while (dvl->dvl_nlock > 0 || dvl->dvl_nwait > 0) {
   2520 		/* Wake a thread that waits for the lock.  That
   2521 		 * thread will fail to acquire the lock, and then
   2522 		 * it will wake the next thread that waits for the
   2523 		 * lock, or else it will wake us.
   2524 		 */
   2525 		cv_signal(&dvl->dvl_cv);
   2526 		pmflock_debug(dev, __func__, __LINE__);
   2527 		cv_wait(&dvl->dvl_cv, &dvl->dvl_mtx);
   2528 		pmflock_debug(dev, __func__, __LINE__);
   2529 	}
   2530 	mutex_exit(&dvl->dvl_mtx);
   2531 }
   2532 
   2533 bool
   2534 device_pmf_driver_child_register(device_t dev)
   2535 {
   2536 	device_t parent = device_parent(dev);
   2537 
   2538 	if (parent == NULL || parent->dv_driver_child_register == NULL)
   2539 		return true;
   2540 	return (*parent->dv_driver_child_register)(dev);
   2541 }
   2542 
   2543 void
   2544 device_pmf_driver_set_child_register(device_t dev,
   2545     bool (*child_register)(device_t))
   2546 {
   2547 	dev->dv_driver_child_register = child_register;
   2548 }
   2549 
   2550 static void
   2551 pmflock_debug(device_t dev, const char *func, int line)
   2552 {
   2553 	device_lock_t dvl = device_getlock(dev);
   2554 
   2555 	aprint_debug_dev(dev,
   2556 	    "%s.%d, %s dvl_nlock %d dvl_nwait %d dv_flags %x\n", func, line,
   2557 	    curlwp_name(), dvl->dvl_nlock, dvl->dvl_nwait, dev->dv_flags);
   2558 }
   2559 
   2560 static bool
   2561 device_pmf_lock1(device_t dev)
   2562 {
   2563 	device_lock_t dvl = device_getlock(dev);
   2564 
   2565 	while (device_pmf_is_registered(dev) &&
   2566 	    dvl->dvl_nlock > 0 && dvl->dvl_holder != curlwp) {
   2567 		dvl->dvl_nwait++;
   2568 		pmflock_debug(dev, __func__, __LINE__);
   2569 		cv_wait(&dvl->dvl_cv, &dvl->dvl_mtx);
   2570 		pmflock_debug(dev, __func__, __LINE__);
   2571 		dvl->dvl_nwait--;
   2572 	}
   2573 	if (!device_pmf_is_registered(dev)) {
   2574 		pmflock_debug(dev, __func__, __LINE__);
   2575 		/* We could not acquire the lock, but some other thread may
   2576 		 * wait for it, also.  Wake that thread.
   2577 		 */
   2578 		cv_signal(&dvl->dvl_cv);
   2579 		return false;
   2580 	}
   2581 	dvl->dvl_nlock++;
   2582 	dvl->dvl_holder = curlwp;
   2583 	pmflock_debug(dev, __func__, __LINE__);
   2584 	return true;
   2585 }
   2586 
   2587 bool
   2588 device_pmf_lock(device_t dev)
   2589 {
   2590 	bool rc;
   2591 	device_lock_t dvl = device_getlock(dev);
   2592 
   2593 	mutex_enter(&dvl->dvl_mtx);
   2594 	rc = device_pmf_lock1(dev);
   2595 	mutex_exit(&dvl->dvl_mtx);
   2596 
   2597 	return rc;
   2598 }
   2599 
   2600 void
   2601 device_pmf_unlock(device_t dev)
   2602 {
   2603 	device_lock_t dvl = device_getlock(dev);
   2604 
   2605 	KASSERT(dvl->dvl_nlock > 0);
   2606 	mutex_enter(&dvl->dvl_mtx);
   2607 	if (--dvl->dvl_nlock == 0)
   2608 		dvl->dvl_holder = NULL;
   2609 	cv_signal(&dvl->dvl_cv);
   2610 	pmflock_debug(dev, __func__, __LINE__);
   2611 	mutex_exit(&dvl->dvl_mtx);
   2612 }
   2613 
   2614 device_lock_t
   2615 device_getlock(device_t dev)
   2616 {
   2617 	return &dev->dv_lock;
   2618 }
   2619 
   2620 void *
   2621 device_pmf_bus_private(device_t dev)
   2622 {
   2623 	return dev->dv_bus_private;
   2624 }
   2625 
   2626 bool
   2627 device_pmf_bus_suspend(device_t dev, const pmf_qual_t *qual)
   2628 {
   2629 	if ((dev->dv_flags & DVF_BUS_SUSPENDED) != 0)
   2630 		return true;
   2631 	if ((dev->dv_flags & DVF_CLASS_SUSPENDED) == 0 ||
   2632 	    (dev->dv_flags & DVF_DRIVER_SUSPENDED) == 0)
   2633 		return false;
   2634 	if (pmf_qual_depth(qual) <= DEVACT_LEVEL_BUS &&
   2635 	    dev->dv_bus_suspend != NULL &&
   2636 	    !(*dev->dv_bus_suspend)(dev, qual))
   2637 		return false;
   2638 
   2639 	dev->dv_flags |= DVF_BUS_SUSPENDED;
   2640 	return true;
   2641 }
   2642 
   2643 bool
   2644 device_pmf_bus_resume(device_t dev, const pmf_qual_t *qual)
   2645 {
   2646 	if ((dev->dv_flags & DVF_BUS_SUSPENDED) == 0)
   2647 		return true;
   2648 	if (pmf_qual_depth(qual) <= DEVACT_LEVEL_BUS &&
   2649 	    dev->dv_bus_resume != NULL &&
   2650 	    !(*dev->dv_bus_resume)(dev, qual))
   2651 		return false;
   2652 
   2653 	dev->dv_flags &= ~DVF_BUS_SUSPENDED;
   2654 	return true;
   2655 }
   2656 
   2657 bool
   2658 device_pmf_bus_shutdown(device_t dev, int how)
   2659 {
   2660 
   2661 	if (*dev->dv_bus_shutdown != NULL &&
   2662 	    !(*dev->dv_bus_shutdown)(dev, how))
   2663 		return false;
   2664 	return true;
   2665 }
   2666 
   2667 void
   2668 device_pmf_bus_register(device_t dev, void *priv,
   2669     bool (*suspend)(device_t, const pmf_qual_t *),
   2670     bool (*resume)(device_t, const pmf_qual_t *),
   2671     bool (*shutdown)(device_t, int), void (*deregister)(device_t))
   2672 {
   2673 	dev->dv_bus_private = priv;
   2674 	dev->dv_bus_resume = resume;
   2675 	dev->dv_bus_suspend = suspend;
   2676 	dev->dv_bus_shutdown = shutdown;
   2677 	dev->dv_bus_deregister = deregister;
   2678 }
   2679 
   2680 void
   2681 device_pmf_bus_deregister(device_t dev)
   2682 {
   2683 	if (dev->dv_bus_deregister == NULL)
   2684 		return;
   2685 	(*dev->dv_bus_deregister)(dev);
   2686 	dev->dv_bus_private = NULL;
   2687 	dev->dv_bus_suspend = NULL;
   2688 	dev->dv_bus_resume = NULL;
   2689 	dev->dv_bus_deregister = NULL;
   2690 }
   2691 
   2692 void *
   2693 device_pmf_class_private(device_t dev)
   2694 {
   2695 	return dev->dv_class_private;
   2696 }
   2697 
   2698 bool
   2699 device_pmf_class_suspend(device_t dev, const pmf_qual_t *qual)
   2700 {
   2701 	if ((dev->dv_flags & DVF_CLASS_SUSPENDED) != 0)
   2702 		return true;
   2703 	if (pmf_qual_depth(qual) <= DEVACT_LEVEL_CLASS &&
   2704 	    dev->dv_class_suspend != NULL &&
   2705 	    !(*dev->dv_class_suspend)(dev, qual))
   2706 		return false;
   2707 
   2708 	dev->dv_flags |= DVF_CLASS_SUSPENDED;
   2709 	return true;
   2710 }
   2711 
   2712 bool
   2713 device_pmf_class_resume(device_t dev, const pmf_qual_t *qual)
   2714 {
   2715 	if ((dev->dv_flags & DVF_CLASS_SUSPENDED) == 0)
   2716 		return true;
   2717 	if ((dev->dv_flags & DVF_BUS_SUSPENDED) != 0 ||
   2718 	    (dev->dv_flags & DVF_DRIVER_SUSPENDED) != 0)
   2719 		return false;
   2720 	if (pmf_qual_depth(qual) <= DEVACT_LEVEL_CLASS &&
   2721 	    dev->dv_class_resume != NULL &&
   2722 	    !(*dev->dv_class_resume)(dev, qual))
   2723 		return false;
   2724 
   2725 	dev->dv_flags &= ~DVF_CLASS_SUSPENDED;
   2726 	return true;
   2727 }
   2728 
   2729 void
   2730 device_pmf_class_register(device_t dev, void *priv,
   2731     bool (*suspend)(device_t, const pmf_qual_t *),
   2732     bool (*resume)(device_t, const pmf_qual_t *),
   2733     void (*deregister)(device_t))
   2734 {
   2735 	dev->dv_class_private = priv;
   2736 	dev->dv_class_suspend = suspend;
   2737 	dev->dv_class_resume = resume;
   2738 	dev->dv_class_deregister = deregister;
   2739 }
   2740 
   2741 void
   2742 device_pmf_class_deregister(device_t dev)
   2743 {
   2744 	if (dev->dv_class_deregister == NULL)
   2745 		return;
   2746 	(*dev->dv_class_deregister)(dev);
   2747 	dev->dv_class_private = NULL;
   2748 	dev->dv_class_suspend = NULL;
   2749 	dev->dv_class_resume = NULL;
   2750 	dev->dv_class_deregister = NULL;
   2751 }
   2752 
   2753 bool
   2754 device_active(device_t dev, devactive_t type)
   2755 {
   2756 	size_t i;
   2757 
   2758 	if (dev->dv_activity_count == 0)
   2759 		return false;
   2760 
   2761 	for (i = 0; i < dev->dv_activity_count; ++i) {
   2762 		if (dev->dv_activity_handlers[i] == NULL)
   2763 			break;
   2764 		(*dev->dv_activity_handlers[i])(dev, type);
   2765 	}
   2766 
   2767 	return true;
   2768 }
   2769 
   2770 bool
   2771 device_active_register(device_t dev, void (*handler)(device_t, devactive_t))
   2772 {
   2773 	void (**new_handlers)(device_t, devactive_t);
   2774 	void (**old_handlers)(device_t, devactive_t);
   2775 	size_t i, old_size, new_size;
   2776 	int s;
   2777 
   2778 	old_handlers = dev->dv_activity_handlers;
   2779 	old_size = dev->dv_activity_count;
   2780 
   2781 	KASSERT(old_size == 0 || old_handlers != NULL);
   2782 
   2783 	for (i = 0; i < old_size; ++i) {
   2784 		KASSERT(old_handlers[i] != handler);
   2785 		if (old_handlers[i] == NULL) {
   2786 			old_handlers[i] = handler;
   2787 			return true;
   2788 		}
   2789 	}
   2790 
   2791 	new_size = old_size + 4;
   2792 	new_handlers = kmem_alloc(sizeof(void *[new_size]), KM_SLEEP);
   2793 
   2794 	for (i = 0; i < old_size; ++i)
   2795 		new_handlers[i] = old_handlers[i];
   2796 	new_handlers[old_size] = handler;
   2797 	for (i = old_size+1; i < new_size; ++i)
   2798 		new_handlers[i] = NULL;
   2799 
   2800 	s = splhigh();
   2801 	dev->dv_activity_count = new_size;
   2802 	dev->dv_activity_handlers = new_handlers;
   2803 	splx(s);
   2804 
   2805 	if (old_size > 0)
   2806 		kmem_free(old_handlers, sizeof(void * [old_size]));
   2807 
   2808 	return true;
   2809 }
   2810 
   2811 void
   2812 device_active_deregister(device_t dev, void (*handler)(device_t, devactive_t))
   2813 {
   2814 	void (**old_handlers)(device_t, devactive_t);
   2815 	size_t i, old_size;
   2816 	int s;
   2817 
   2818 	old_handlers = dev->dv_activity_handlers;
   2819 	old_size = dev->dv_activity_count;
   2820 
   2821 	for (i = 0; i < old_size; ++i) {
   2822 		if (old_handlers[i] == handler)
   2823 			break;
   2824 		if (old_handlers[i] == NULL)
   2825 			return; /* XXX panic? */
   2826 	}
   2827 
   2828 	if (i == old_size)
   2829 		return; /* XXX panic? */
   2830 
   2831 	for (; i < old_size - 1; ++i) {
   2832 		if ((old_handlers[i] = old_handlers[i + 1]) != NULL)
   2833 			continue;
   2834 
   2835 		if (i == 0) {
   2836 			s = splhigh();
   2837 			dev->dv_activity_count = 0;
   2838 			dev->dv_activity_handlers = NULL;
   2839 			splx(s);
   2840 			kmem_free(old_handlers, sizeof(void *[old_size]));
   2841 		}
   2842 		return;
   2843 	}
   2844 	old_handlers[i] = NULL;
   2845 }
   2846 
   2847 /* Return true iff the device_t `dev' exists at generation `gen'. */
   2848 static bool
   2849 device_exists_at(device_t dv, devgen_t gen)
   2850 {
   2851 	return (dv->dv_del_gen == 0 || dv->dv_del_gen > gen) &&
   2852 	    dv->dv_add_gen <= gen;
   2853 }
   2854 
   2855 static bool
   2856 deviter_visits(const deviter_t *di, device_t dv)
   2857 {
   2858 	return device_exists_at(dv, di->di_gen);
   2859 }
   2860 
   2861 /*
   2862  * Device Iteration
   2863  *
   2864  * deviter_t: a device iterator.  Holds state for a "walk" visiting
   2865  *     each device_t's in the device tree.
   2866  *
   2867  * deviter_init(di, flags): initialize the device iterator `di'
   2868  *     to "walk" the device tree.  deviter_next(di) will return
   2869  *     the first device_t in the device tree, or NULL if there are
   2870  *     no devices.
   2871  *
   2872  *     `flags' is one or more of DEVITER_F_RW, indicating that the
   2873  *     caller intends to modify the device tree by calling
   2874  *     config_detach(9) on devices in the order that the iterator
   2875  *     returns them; DEVITER_F_ROOT_FIRST, asking for the devices
   2876  *     nearest the "root" of the device tree to be returned, first;
   2877  *     DEVITER_F_LEAVES_FIRST, asking for the devices furthest from
   2878  *     the root of the device tree, first; and DEVITER_F_SHUTDOWN,
   2879  *     indicating both that deviter_init() should not respect any
   2880  *     locks on the device tree, and that deviter_next(di) may run
   2881  *     in more than one LWP before the walk has finished.
   2882  *
   2883  *     Only one DEVITER_F_RW iterator may be in the device tree at
   2884  *     once.
   2885  *
   2886  *     DEVITER_F_SHUTDOWN implies DEVITER_F_RW.
   2887  *
   2888  *     Results are undefined if the flags DEVITER_F_ROOT_FIRST and
   2889  *     DEVITER_F_LEAVES_FIRST are used in combination.
   2890  *
   2891  * deviter_first(di, flags): initialize the device iterator `di'
   2892  *     and return the first device_t in the device tree, or NULL
   2893  *     if there are no devices.  The statement
   2894  *
   2895  *         dv = deviter_first(di);
   2896  *
   2897  *     is shorthand for
   2898  *
   2899  *         deviter_init(di);
   2900  *         dv = deviter_next(di);
   2901  *
   2902  * deviter_next(di): return the next device_t in the device tree,
   2903  *     or NULL if there are no more devices.  deviter_next(di)
   2904  *     is undefined if `di' was not initialized with deviter_init() or
   2905  *     deviter_first().
   2906  *
   2907  * deviter_release(di): stops iteration (subsequent calls to
   2908  *     deviter_next() will return NULL), releases any locks and
   2909  *     resources held by the device iterator.
   2910  *
   2911  * Device iteration does not return device_t's in any particular
   2912  * order.  An iterator will never return the same device_t twice.
   2913  * Device iteration is guaranteed to complete---i.e., if deviter_next(di)
   2914  * is called repeatedly on the same `di', it will eventually return
   2915  * NULL.  It is ok to attach/detach devices during device iteration.
   2916  */
   2917 void
   2918 deviter_init(deviter_t *di, deviter_flags_t flags)
   2919 {
   2920 	device_t dv;
   2921 
   2922 	memset(di, 0, sizeof(*di));
   2923 
   2924 	if ((flags & DEVITER_F_SHUTDOWN) != 0)
   2925 		flags |= DEVITER_F_RW;
   2926 
   2927 	mutex_enter(&alldevs.lock);
   2928 	if ((flags & DEVITER_F_RW) != 0)
   2929 		alldevs.nwrite++;
   2930 	else
   2931 		alldevs.nread++;
   2932 	di->di_gen = alldevs.gen++;
   2933 	di->di_flags = flags;
   2934 
   2935 	switch (di->di_flags & (DEVITER_F_LEAVES_FIRST|DEVITER_F_ROOT_FIRST)) {
   2936 	case DEVITER_F_LEAVES_FIRST:
   2937 		TAILQ_FOREACH(dv, &alldevs.list, dv_list) {
   2938 			if (!deviter_visits(di, dv))
   2939 				continue;
   2940 			di->di_curdepth = MAX(di->di_curdepth, dv->dv_depth);
   2941 		}
   2942 		break;
   2943 	case DEVITER_F_ROOT_FIRST:
   2944 		TAILQ_FOREACH(dv, &alldevs.list, dv_list) {
   2945 			if (!deviter_visits(di, dv))
   2946 				continue;
   2947 			di->di_maxdepth = MAX(di->di_maxdepth, dv->dv_depth);
   2948 		}
   2949 		break;
   2950 	default:
   2951 		break;
   2952 	}
   2953 
   2954 	deviter_reinit(di);
   2955 	mutex_exit(&alldevs.lock);
   2956 }
   2957 
   2958 static void
   2959 deviter_reinit(deviter_t *di)
   2960 {
   2961 
   2962 	KASSERT(mutex_owned(&alldevs.lock));
   2963 	if ((di->di_flags & DEVITER_F_RW) != 0)
   2964 		di->di_prev = TAILQ_LAST(&alldevs.list, devicelist);
   2965 	else
   2966 		di->di_prev = TAILQ_FIRST(&alldevs.list);
   2967 }
   2968 
   2969 device_t
   2970 deviter_first(deviter_t *di, deviter_flags_t flags)
   2971 {
   2972 
   2973 	deviter_init(di, flags);
   2974 	return deviter_next(di);
   2975 }
   2976 
   2977 static device_t
   2978 deviter_next2(deviter_t *di)
   2979 {
   2980 	device_t dv;
   2981 
   2982 	KASSERT(mutex_owned(&alldevs.lock));
   2983 
   2984 	dv = di->di_prev;
   2985 
   2986 	if (dv == NULL)
   2987 		return NULL;
   2988 
   2989 	if ((di->di_flags & DEVITER_F_RW) != 0)
   2990 		di->di_prev = TAILQ_PREV(dv, devicelist, dv_list);
   2991 	else
   2992 		di->di_prev = TAILQ_NEXT(dv, dv_list);
   2993 
   2994 	return dv;
   2995 }
   2996 
   2997 static device_t
   2998 deviter_next1(deviter_t *di)
   2999 {
   3000 	device_t dv;
   3001 
   3002 	KASSERT(mutex_owned(&alldevs.lock));
   3003 
   3004 	do {
   3005 		dv = deviter_next2(di);
   3006 	} while (dv != NULL && !deviter_visits(di, dv));
   3007 
   3008 	return dv;
   3009 }
   3010 
   3011 device_t
   3012 deviter_next(deviter_t *di)
   3013 {
   3014 	device_t dv = NULL;
   3015 
   3016 	mutex_enter(&alldevs.lock);
   3017 	switch (di->di_flags & (DEVITER_F_LEAVES_FIRST|DEVITER_F_ROOT_FIRST)) {
   3018 	case 0:
   3019 		dv = deviter_next1(di);
   3020 		break;
   3021 	case DEVITER_F_LEAVES_FIRST:
   3022 		while (di->di_curdepth >= 0) {
   3023 			if ((dv = deviter_next1(di)) == NULL) {
   3024 				di->di_curdepth--;
   3025 				deviter_reinit(di);
   3026 			} else if (dv->dv_depth == di->di_curdepth)
   3027 				break;
   3028 		}
   3029 		break;
   3030 	case DEVITER_F_ROOT_FIRST:
   3031 		while (di->di_curdepth <= di->di_maxdepth) {
   3032 			if ((dv = deviter_next1(di)) == NULL) {
   3033 				di->di_curdepth++;
   3034 				deviter_reinit(di);
   3035 			} else if (dv->dv_depth == di->di_curdepth)
   3036 				break;
   3037 		}
   3038 		break;
   3039 	default:
   3040 		break;
   3041 	}
   3042 	mutex_exit(&alldevs.lock);
   3043 
   3044 	return dv;
   3045 }
   3046 
   3047 void
   3048 deviter_release(deviter_t *di)
   3049 {
   3050 	bool rw = (di->di_flags & DEVITER_F_RW) != 0;
   3051 
   3052 	mutex_enter(&alldevs.lock);
   3053 	if (rw)
   3054 		--alldevs.nwrite;
   3055 	else
   3056 		--alldevs.nread;
   3057 	/* XXX wake a garbage-collection thread */
   3058 	mutex_exit(&alldevs.lock);
   3059 }
   3060 
   3061 const char *
   3062 cfdata_ifattr(const struct cfdata *cf)
   3063 {
   3064 	return cf->cf_pspec->cfp_iattr;
   3065 }
   3066 
   3067 bool
   3068 ifattr_match(const char *snull, const char *t)
   3069 {
   3070 	return (snull == NULL) || strcmp(snull, t) == 0;
   3071 }
   3072 
   3073 void
   3074 null_childdetached(device_t self, device_t child)
   3075 {
   3076 	/* do nothing */
   3077 }
   3078 
   3079 static void
   3080 sysctl_detach_setup(struct sysctllog **clog)
   3081 {
   3082 
   3083 	sysctl_createv(clog, 0, NULL, NULL,
   3084 		CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
   3085 		CTLTYPE_BOOL, "detachall",
   3086 		SYSCTL_DESCR("Detach all devices at shutdown"),
   3087 		NULL, 0, &detachall, 0,
   3088 		CTL_KERN, CTL_CREATE, CTL_EOL);
   3089 }
   3090