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