Home | History | Annotate | Line # | Download | only in kern
subr_autoconf.c revision 1.76
      1 /* $NetBSD: subr_autoconf.c,v 1.76 2002/10/04 01:50:53 thorpej 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. All advertising materials mentioning features or use of this software
     59  *    must display the following acknowledgement:
     60  *	This product includes software developed by the University of
     61  *	California, Berkeley and its contributors.
     62  * 4. Neither the name of the University nor the names of its contributors
     63  *    may be used to endorse or promote products derived from this software
     64  *    without specific prior written permission.
     65  *
     66  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     67  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     68  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     69  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     70  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     71  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     72  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     73  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     74  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     75  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     76  * SUCH DAMAGE.
     77  *
     78  * from: Header: subr_autoconf.c,v 1.12 93/02/01 19:31:48 torek Exp  (LBL)
     79  *
     80  *	@(#)subr_autoconf.c	8.3 (Berkeley) 5/17/94
     81  */
     82 
     83 #include <sys/cdefs.h>
     84 __KERNEL_RCSID(0, "$NetBSD: subr_autoconf.c,v 1.76 2002/10/04 01:50:53 thorpej Exp $");
     85 
     86 #include "opt_ddb.h"
     87 
     88 #include <sys/param.h>
     89 #include <sys/device.h>
     90 #include <sys/malloc.h>
     91 #include <sys/systm.h>
     92 #include <sys/kernel.h>
     93 #include <sys/errno.h>
     94 #include <sys/proc.h>
     95 #include <machine/limits.h>
     96 
     97 #include "opt_userconf.h"
     98 #ifdef USERCONF
     99 #include <sys/userconf.h>
    100 #include <sys/reboot.h>
    101 #endif
    102 
    103 /*
    104  * Autoconfiguration subroutines.
    105  */
    106 
    107 /*
    108  * ioconf.c exports exactly two names: cfdata and cfroots.  All system
    109  * devices and drivers are found via these tables.
    110  */
    111 extern struct cfdata cfdata[];
    112 extern short cfroots[];
    113 
    114 /*
    115  * List of all cfdriver structures.  We use this to detect duplicates
    116  * when other cfdrivers are loaded.
    117  */
    118 struct cfdriverlist allcfdrivers = LIST_HEAD_INITIALIZER(&allcfdrivers);
    119 extern struct cfdriver * const cfdriver_list_initial[];
    120 
    121 /*
    122  * Initial list of cfattach's.
    123  */
    124 extern const struct cfattachinit cfattachinit[];
    125 
    126 /*
    127  * List of cfdata tables.  We always have one such list -- the one
    128  * built statically when the kernel was configured.
    129  */
    130 struct cftablelist allcftables;
    131 static struct cftable initcftable;
    132 
    133 #define	ROOT ((struct device *)NULL)
    134 
    135 struct matchinfo {
    136 	cfmatch_t fn;
    137 	struct	device *parent;
    138 	void	*aux;
    139 	struct	cfdata *match;
    140 	int	pri;
    141 };
    142 
    143 static char *number(char *, int);
    144 static void mapply(struct matchinfo *, struct cfdata *);
    145 
    146 struct deferred_config {
    147 	TAILQ_ENTRY(deferred_config) dc_queue;
    148 	struct device *dc_dev;
    149 	void (*dc_func)(struct device *);
    150 };
    151 
    152 TAILQ_HEAD(deferred_config_head, deferred_config);
    153 
    154 struct deferred_config_head deferred_config_queue;
    155 struct deferred_config_head interrupt_config_queue;
    156 
    157 static void config_process_deferred(struct deferred_config_head *,
    158 	struct device *);
    159 
    160 /* Hooks to finalize configuration once all real devices have been found. */
    161 struct finalize_hook {
    162 	TAILQ_ENTRY(finalize_hook) f_list;
    163 	int (*f_func)(struct device *);
    164 	struct device *f_dev;
    165 };
    166 static TAILQ_HEAD(, finalize_hook) config_finalize_list;
    167 static int config_finalize_done;
    168 
    169 /* list of all devices */
    170 struct devicelist alldevs;
    171 
    172 /* list of all events */
    173 struct evcntlist allevents = TAILQ_HEAD_INITIALIZER(allevents);
    174 
    175 __volatile int config_pending;		/* semaphore for mountroot */
    176 
    177 #define	STREQ(s1, s2)			\
    178 	(*(s1) == *(s2) && strcmp((s1), (s2)) == 0)
    179 
    180 static int config_initialized;		/* config_init() has been called. */
    181 
    182 /*
    183  * Initialize the autoconfiguration data structures.  Normally this
    184  * is done by configure(), but some platforms need to do this very
    185  * early (to e.g. initialize the console).
    186  */
    187 void
    188 config_init(void)
    189 {
    190 	const struct cfattachinit *cfai;
    191 	int i, j;
    192 
    193 	if (config_initialized)
    194 		return;
    195 
    196 	/* allcfdrivers is statically initialized. */
    197 	for (i = 0; cfdriver_list_initial[i] != NULL; i++) {
    198 		if (config_cfdriver_attach(cfdriver_list_initial[i]) != 0)
    199 			panic("configure: duplicate `%s' drivers",
    200 			    cfdriver_list_initial[i]->cd_name);
    201 	}
    202 
    203 	for (cfai = &cfattachinit[0]; cfai->cfai_name != NULL; cfai++) {
    204 		for (j = 0; cfai->cfai_list[j] != NULL; j++) {
    205 			if (config_cfattach_attach(cfai->cfai_name,
    206 						   cfai->cfai_list[j]) != 0)
    207 				panic("configure: duplicate `%s' attachment "
    208 				    "of `%s' driver",
    209 				    cfai->cfai_list[j]->ca_name,
    210 				    cfai->cfai_name);
    211 		}
    212 	}
    213 
    214 	TAILQ_INIT(&allcftables);
    215 	initcftable.ct_cfdata = cfdata;
    216 	TAILQ_INSERT_TAIL(&allcftables, &initcftable, ct_list);
    217 
    218 	TAILQ_INIT(&deferred_config_queue);
    219 	TAILQ_INIT(&interrupt_config_queue);
    220 	TAILQ_INIT(&config_finalize_list);
    221 	TAILQ_INIT(&alldevs);
    222 
    223 	config_initialized = 1;
    224 }
    225 
    226 /*
    227  * Configure the system's hardware.
    228  */
    229 void
    230 configure(void)
    231 {
    232 
    233 	/* Initialize data structures. */
    234 	config_init();
    235 
    236 #ifdef USERCONF
    237 	if (boothowto & RB_USERCONF)
    238 		user_config();
    239 #endif
    240 
    241 	/*
    242 	 * Do the machine-dependent portion of autoconfiguration.  This
    243 	 * sets the configuration machinery here in motion by "finding"
    244 	 * the root bus.  When this function returns, we expect interrupts
    245 	 * to be enabled.
    246 	 */
    247 	cpu_configure();
    248 
    249 	/*
    250 	 * Now that we've found all the hardware, start the real time
    251 	 * and statistics clocks.
    252 	 */
    253 	initclocks();
    254 
    255 	cold = 0;	/* clocks are running, we're warm now! */
    256 
    257 	/*
    258 	 * Now callback to finish configuration for devices which want
    259 	 * to do this once interrupts are enabled.
    260 	 */
    261 	config_process_deferred(&interrupt_config_queue, NULL);
    262 }
    263 
    264 /*
    265  * Add a cfdriver to the system.
    266  */
    267 int
    268 config_cfdriver_attach(struct cfdriver *cd)
    269 {
    270 	struct cfdriver *lcd;
    271 
    272 	/* Make sure this driver isn't already in the system. */
    273 	LIST_FOREACH(lcd, &allcfdrivers, cd_list) {
    274 		if (STREQ(lcd->cd_name, cd->cd_name))
    275 			return (EEXIST);
    276 	}
    277 
    278 	LIST_INIT(&cd->cd_attach);
    279 	LIST_INSERT_HEAD(&allcfdrivers, cd, cd_list);
    280 
    281 	return (0);
    282 }
    283 
    284 /*
    285  * Remove a cfdriver from the system.
    286  */
    287 int
    288 config_cfdriver_detach(struct cfdriver *cd)
    289 {
    290 	int i;
    291 
    292 	/* Make sure there are no active instances. */
    293 	for (i = 0; i < cd->cd_ndevs; i++) {
    294 		if (cd->cd_devs[i] != NULL)
    295 			return (EBUSY);
    296 	}
    297 
    298 	/* ...and no attachments loaded. */
    299 	if (LIST_EMPTY(&cd->cd_attach) == 0)
    300 		return (EBUSY);
    301 
    302 	LIST_REMOVE(cd, cd_list);
    303 
    304 	KASSERT(cd->cd_devs == NULL);
    305 
    306 	return (0);
    307 }
    308 
    309 /*
    310  * Look up a cfdriver by name.
    311  */
    312 static struct cfdriver *
    313 config_cfdriver_lookup(const char *name)
    314 {
    315 	struct cfdriver *cd;
    316 
    317 	LIST_FOREACH(cd, &allcfdrivers, cd_list) {
    318 		if (STREQ(cd->cd_name, name))
    319 			return (cd);
    320 	}
    321 
    322 	return (NULL);
    323 }
    324 
    325 /*
    326  * Add a cfattach to the specified driver.
    327  */
    328 int
    329 config_cfattach_attach(const char *driver, struct cfattach *ca)
    330 {
    331 	struct cfattach *lca;
    332 	struct cfdriver *cd;
    333 
    334 	cd = config_cfdriver_lookup(driver);
    335 	if (cd == NULL)
    336 		return (ESRCH);
    337 
    338 	/* Make sure this attachment isn't already on this driver. */
    339 	LIST_FOREACH(lca, &cd->cd_attach, ca_list) {
    340 		if (STREQ(lca->ca_name, ca->ca_name))
    341 			return (EEXIST);
    342 	}
    343 
    344 	LIST_INSERT_HEAD(&cd->cd_attach, ca, ca_list);
    345 
    346 	return (0);
    347 }
    348 
    349 /*
    350  * Remove a cfattach from the specified driver.
    351  */
    352 int
    353 config_cfattach_detach(const char *driver, struct cfattach *ca)
    354 {
    355 	struct cfdriver *cd;
    356 	struct device *dev;
    357 	int i;
    358 
    359 	cd = config_cfdriver_lookup(driver);
    360 	if (cd == NULL)
    361 		return (ESRCH);
    362 
    363 	/* Make sure there are no active instances. */
    364 	for (i = 0; i < cd->cd_ndevs; i++) {
    365 		if ((dev = cd->cd_devs[i]) == NULL)
    366 			continue;
    367 		if (STREQ(dev->dv_cfdata->cf_atname, ca->ca_name))
    368 			return (EBUSY);
    369 	}
    370 
    371 	LIST_REMOVE(ca, ca_list);
    372 
    373 	return (0);
    374 }
    375 
    376 /*
    377  * Look up a cfattach by name.
    378  */
    379 static struct cfattach *
    380 config_cfattach_lookup_cd(struct cfdriver *cd, const char *atname)
    381 {
    382 	struct cfattach *ca;
    383 
    384 	LIST_FOREACH(ca, &cd->cd_attach, ca_list) {
    385 		if (STREQ(ca->ca_name, atname))
    386 			return (ca);
    387 	}
    388 
    389 	return (NULL);
    390 }
    391 
    392 /*
    393  * Look up a cfattach by driver/attachment name.
    394  */
    395 struct cfattach *
    396 config_cfattach_lookup(const char *name, const char *atname)
    397 {
    398 	struct cfdriver *cd;
    399 
    400 	cd = config_cfdriver_lookup(name);
    401 	if (cd == NULL)
    402 		return (NULL);
    403 
    404 	return (config_cfattach_lookup_cd(cd, atname));
    405 }
    406 
    407 /*
    408  * Apply the matching function and choose the best.  This is used
    409  * a few times and we want to keep the code small.
    410  */
    411 static void
    412 mapply(struct matchinfo *m, struct cfdata *cf)
    413 {
    414 	int pri;
    415 
    416 	if (m->fn != NULL)
    417 		pri = (*m->fn)(m->parent, cf, m->aux);
    418 	else {
    419 		struct cfattach *ca;
    420 
    421 		ca = config_cfattach_lookup(cf->cf_name, cf->cf_atname);
    422 		if (ca == NULL) {
    423 			/* No attachment for this entry, oh well. */
    424 			return;
    425 		}
    426 	        if (ca->ca_match == NULL) {
    427 			panic("mapply: no match function for '%s' attachment "
    428 			    "of '%s'", cf->cf_atname, cf->cf_name);
    429 		}
    430 		pri = (*ca->ca_match)(m->parent, cf, m->aux);
    431 	}
    432 	if (pri > m->pri) {
    433 		m->match = cf;
    434 		m->pri = pri;
    435 	}
    436 }
    437 
    438 /*
    439  * Determine if `parent' is a potential parent for a device spec based
    440  * on `cfp'.
    441  */
    442 static int
    443 cfparent_match(struct device *parent, const struct cfparent *cfp)
    444 {
    445 	struct cfdriver *pcd;
    446 	const char * const *cpp;
    447 	const char *cp;
    448 
    449 	/* We don't match root nodes here. */
    450 	if (cfp == NULL)
    451 		return (0);
    452 
    453 	pcd = config_cfdriver_lookup(parent->dv_cfdata->cf_name);
    454 	KASSERT(pcd != NULL);
    455 
    456 	/*
    457 	 * First, ensure this parent has the correct interface
    458 	 * attribute.
    459 	 */
    460 	if (pcd->cd_attrs == NULL)
    461 		return (0);	/* no interface attributes -> no children */
    462 	for (cpp = pcd->cd_attrs; (cp = *cpp) != NULL; cpp++) {
    463 		if (STREQ(cp, cfp->cfp_iattr)) {
    464 			/* Match. */
    465 			break;
    466 		}
    467 	}
    468 	if (cp == NULL)
    469 		return (0);	/* doesn't carry the req'd attribute */
    470 
    471 	/*
    472 	 * If no specific parent device instance was specified (i.e.
    473 	 * we're attaching to the attribute only), we're done!
    474 	 */
    475 	if (cfp->cfp_parent == NULL)
    476 		return (1);
    477 
    478 	/*
    479 	 * Check the parent device's name.
    480 	 */
    481 	if (STREQ(pcd->cd_name, cfp->cfp_parent) == 0)
    482 		return (0);	/* not the same parent */
    483 
    484 	/*
    485 	 * Make sure the unit number matches.
    486 	 */
    487 	if (cfp->cfp_unit == -1 ||	/* wildcard */
    488 	    cfp->cfp_unit == parent->dv_unit)
    489 		return (1);
    490 
    491 	/* Unit numbers don't match. */
    492 	return (0);
    493 }
    494 
    495 /*
    496  * Invoke the "match" routine for a cfdata entry on behalf of
    497  * an external caller, usually a "submatch" routine.
    498  */
    499 int
    500 config_match(struct device *parent, struct cfdata *cf, void *aux)
    501 {
    502 	struct cfattach *ca;
    503 
    504 	ca = config_cfattach_lookup(cf->cf_name, cf->cf_atname);
    505 	if (ca == NULL) {
    506 		/* No attachment for this entry, oh well. */
    507 		return (0);
    508 	}
    509 
    510 	return ((*ca->ca_match)(parent, cf, aux));
    511 }
    512 
    513 /*
    514  * Iterate over all potential children of some device, calling the given
    515  * function (default being the child's match function) for each one.
    516  * Nonzero returns are matches; the highest value returned is considered
    517  * the best match.  Return the `found child' if we got a match, or NULL
    518  * otherwise.  The `aux' pointer is simply passed on through.
    519  *
    520  * Note that this function is designed so that it can be used to apply
    521  * an arbitrary function to all potential children (its return value
    522  * can be ignored).
    523  */
    524 struct cfdata *
    525 config_search(cfmatch_t fn, struct device *parent, void *aux)
    526 {
    527 	struct cftable *ct;
    528 	struct cfdata *cf;
    529 	struct matchinfo m;
    530 
    531 	KASSERT(config_initialized);
    532 
    533 	m.fn = fn;
    534 	m.parent = parent;
    535 	m.aux = aux;
    536 	m.match = NULL;
    537 	m.pri = 0;
    538 
    539 	TAILQ_FOREACH(ct, &allcftables, ct_list) {
    540 		for (cf = ct->ct_cfdata; cf->cf_name; cf++) {
    541 			/*
    542 			 * Skip cf if no longer eligible, otherwise scan
    543 			 * through parents for one matching `parent', and
    544 			 * try match function.
    545 			 */
    546 			if (cf->cf_fstate == FSTATE_FOUND)
    547 				continue;
    548 			if (cf->cf_fstate == FSTATE_DNOTFOUND ||
    549 			    cf->cf_fstate == FSTATE_DSTAR)
    550 				continue;
    551 			if (cfparent_match(parent, cf->cf_pspec))
    552 				mapply(&m, cf);
    553 		}
    554 	}
    555 	return (m.match);
    556 }
    557 
    558 /*
    559  * Find the given root device.
    560  * This is much like config_search, but there is no parent.
    561  * Don't bother with multiple cfdata tables; the root node
    562  * must always be in the initial table.
    563  */
    564 struct cfdata *
    565 config_rootsearch(cfmatch_t fn, const char *rootname, void *aux)
    566 {
    567 	struct cfdata *cf;
    568 	short *p;
    569 	struct matchinfo m;
    570 
    571 	m.fn = fn;
    572 	m.parent = ROOT;
    573 	m.aux = aux;
    574 	m.match = NULL;
    575 	m.pri = 0;
    576 	/*
    577 	 * Look at root entries for matching name.  We do not bother
    578 	 * with found-state here since only one root should ever be
    579 	 * searched (and it must be done first).
    580 	 */
    581 	for (p = cfroots; *p >= 0; p++) {
    582 		cf = &cfdata[*p];
    583 		if (strcmp(cf->cf_name, rootname) == 0)
    584 			mapply(&m, cf);
    585 	}
    586 	return (m.match);
    587 }
    588 
    589 static const char *msgs[3] = { "", " not configured\n", " unsupported\n" };
    590 
    591 /*
    592  * The given `aux' argument describes a device that has been found
    593  * on the given parent, but not necessarily configured.  Locate the
    594  * configuration data for that device (using the submatch function
    595  * provided, or using candidates' cd_match configuration driver
    596  * functions) and attach it, and return true.  If the device was
    597  * not configured, call the given `print' function and return 0.
    598  */
    599 struct device *
    600 config_found_sm(struct device *parent, void *aux, cfprint_t print,
    601     cfmatch_t submatch)
    602 {
    603 	struct cfdata *cf;
    604 
    605 	if ((cf = config_search(submatch, parent, aux)) != NULL)
    606 		return (config_attach(parent, cf, aux, print));
    607 	if (print)
    608 		printf("%s", msgs[(*print)(aux, parent->dv_xname)]);
    609 	return (NULL);
    610 }
    611 
    612 /*
    613  * As above, but for root devices.
    614  */
    615 struct device *
    616 config_rootfound(const char *rootname, void *aux)
    617 {
    618 	struct cfdata *cf;
    619 
    620 	if ((cf = config_rootsearch((cfmatch_t)NULL, rootname, aux)) != NULL)
    621 		return (config_attach(ROOT, cf, aux, (cfprint_t)NULL));
    622 	printf("root device %s not configured\n", rootname);
    623 	return (NULL);
    624 }
    625 
    626 /* just like sprintf(buf, "%d") except that it works from the end */
    627 static char *
    628 number(char *ep, int n)
    629 {
    630 
    631 	*--ep = 0;
    632 	while (n >= 10) {
    633 		*--ep = (n % 10) + '0';
    634 		n /= 10;
    635 	}
    636 	*--ep = n + '0';
    637 	return (ep);
    638 }
    639 
    640 /*
    641  * Expand the size of the cd_devs array if necessary.
    642  */
    643 void
    644 config_makeroom(int n, struct cfdriver *cd)
    645 {
    646 	int old, new;
    647 	void **nsp;
    648 
    649 	if (n < cd->cd_ndevs)
    650 		return;
    651 
    652 	/*
    653 	 * Need to expand the array.
    654 	 */
    655 	old = cd->cd_ndevs;
    656 	if (old == 0)
    657 		new = MINALLOCSIZE / sizeof(void *);
    658 	else
    659 		new = old * 2;
    660 	while (new <= n)
    661 		new *= 2;
    662 	cd->cd_ndevs = new;
    663 	nsp = malloc(new * sizeof(void *), M_DEVBUF,
    664 	    cold ? M_NOWAIT : M_WAITOK);
    665 	if (nsp == NULL)
    666 		panic("config_attach: %sing dev array",
    667 		    old != 0 ? "expand" : "creat");
    668 	memset(nsp + old, 0, (new - old) * sizeof(void *));
    669 	if (old != 0) {
    670 		memcpy(nsp, cd->cd_devs, old * sizeof(void *));
    671 		free(cd->cd_devs, M_DEVBUF);
    672 	}
    673 	cd->cd_devs = nsp;
    674 }
    675 
    676 /*
    677  * Attach a found device.  Allocates memory for device variables.
    678  */
    679 struct device *
    680 config_attach(struct device *parent, struct cfdata *cf, void *aux,
    681 	cfprint_t print)
    682 {
    683 	struct device *dev;
    684 	struct cftable *ct;
    685 	struct cfdriver *cd;
    686 	struct cfattach *ca;
    687 	size_t lname, lunit;
    688 	const char *xunit;
    689 	int myunit;
    690 	char num[10];
    691 
    692 	cd = config_cfdriver_lookup(cf->cf_name);
    693 	KASSERT(cd != NULL);
    694 
    695 	ca = config_cfattach_lookup_cd(cd, cf->cf_atname);
    696 	KASSERT(ca != NULL);
    697 
    698 	if (ca->ca_devsize < sizeof(struct device))
    699 		panic("config_attach");
    700 
    701 #ifndef __BROKEN_CONFIG_UNIT_USAGE
    702 	if (cf->cf_fstate == FSTATE_STAR) {
    703 		for (myunit = cf->cf_unit; myunit < cd->cd_ndevs; myunit++)
    704 			if (cd->cd_devs[myunit] == NULL)
    705 				break;
    706 		/*
    707 		 * myunit is now the unit of the first NULL device pointer,
    708 		 * or max(cd->cd_ndevs,cf->cf_unit).
    709 		 */
    710 	} else {
    711 		myunit = cf->cf_unit;
    712 		KASSERT(cf->cf_fstate == FSTATE_NOTFOUND);
    713 		cf->cf_fstate = FSTATE_FOUND;
    714 	}
    715 #else
    716 	myunit = cf->cf_unit;
    717 	if (cf->cf_fstate == FSTATE_STAR)
    718 		cf->cf_unit++;
    719 	else {
    720 		KASSERT(cf->cf_fstate == FSTATE_NOTFOUND);
    721 		cf->cf_fstate = FSTATE_FOUND;
    722 	}
    723 #endif /* ! __BROKEN_CONFIG_UNIT_USAGE */
    724 
    725 	/* compute length of name and decimal expansion of unit number */
    726 	lname = strlen(cd->cd_name);
    727 	xunit = number(&num[sizeof(num)], myunit);
    728 	lunit = &num[sizeof(num)] - xunit;
    729 	if (lname + lunit > sizeof(dev->dv_xname))
    730 		panic("config_attach: device name too long");
    731 
    732 	/* get memory for all device vars */
    733 	dev = (struct device *)malloc(ca->ca_devsize, M_DEVBUF,
    734 	    cold ? M_NOWAIT : M_WAITOK);
    735 	if (!dev)
    736 	    panic("config_attach: memory allocation for device softc failed");
    737 	memset(dev, 0, ca->ca_devsize);
    738 	TAILQ_INSERT_TAIL(&alldevs, dev, dv_list);	/* link up */
    739 	dev->dv_class = cd->cd_class;
    740 	dev->dv_cfdata = cf;
    741 	dev->dv_cfdriver = cd;
    742 	dev->dv_cfattach = ca;
    743 	dev->dv_unit = myunit;
    744 	memcpy(dev->dv_xname, cd->cd_name, lname);
    745 	memcpy(dev->dv_xname + lname, xunit, lunit);
    746 	dev->dv_parent = parent;
    747 	dev->dv_flags = DVF_ACTIVE;	/* always initially active */
    748 
    749 	if (parent == ROOT)
    750 		printf("%s (root)", dev->dv_xname);
    751 	else {
    752 		printf("%s at %s", dev->dv_xname, parent->dv_xname);
    753 		if (print)
    754 			(void) (*print)(aux, NULL);
    755 	}
    756 
    757 	/* put this device in the devices array */
    758 	config_makeroom(dev->dv_unit, cd);
    759 	if (cd->cd_devs[dev->dv_unit])
    760 		panic("config_attach: duplicate %s", dev->dv_xname);
    761 	cd->cd_devs[dev->dv_unit] = dev;
    762 
    763 	/*
    764 	 * Before attaching, clobber any unfound devices that are
    765 	 * otherwise identical.
    766 	 */
    767 	TAILQ_FOREACH(ct, &allcftables, ct_list) {
    768 		for (cf = ct->ct_cfdata; cf->cf_name; cf++) {
    769 			if (STREQ(cf->cf_name, cd->cd_name) &&
    770 			    cf->cf_unit == dev->dv_unit) {
    771 				if (cf->cf_fstate == FSTATE_NOTFOUND)
    772 					cf->cf_fstate = FSTATE_FOUND;
    773 #ifdef __BROKEN_CONFIG_UNIT_USAGE
    774 				/*
    775 				 * Bump the unit number on all starred cfdata
    776 				 * entries for this device.
    777 				 */
    778 				if (cf->cf_fstate == FSTATE_STAR)
    779 					cf->cf_unit++;
    780 #endif /* __BROKEN_CONFIG_UNIT_USAGE */
    781 			}
    782 		}
    783 	}
    784 #ifdef __HAVE_DEVICE_REGISTER
    785 	device_register(dev, aux);
    786 #endif
    787 	(*ca->ca_attach)(parent, dev, aux);
    788 	config_process_deferred(&deferred_config_queue, dev);
    789 	return (dev);
    790 }
    791 
    792 /*
    793  * Detach a device.  Optionally forced (e.g. because of hardware
    794  * removal) and quiet.  Returns zero if successful, non-zero
    795  * (an error code) otherwise.
    796  *
    797  * Note that this code wants to be run from a process context, so
    798  * that the detach can sleep to allow processes which have a device
    799  * open to run and unwind their stacks.
    800  */
    801 int
    802 config_detach(struct device *dev, int flags)
    803 {
    804 	struct cftable *ct;
    805 	struct cfdata *cf;
    806 	const struct cfattach *ca;
    807 	struct cfdriver *cd;
    808 #ifdef DIAGNOSTIC
    809 	struct device *d;
    810 #endif
    811 	int rv = 0, i;
    812 
    813 	cf = dev->dv_cfdata;
    814 #ifdef DIAGNOSTIC
    815 	if (cf->cf_fstate != FSTATE_FOUND && cf->cf_fstate != FSTATE_STAR)
    816 		panic("config_detach: bad device fstate");
    817 #endif
    818 	cd = config_cfdriver_lookup(cf->cf_name);
    819 	KASSERT(cd != NULL);
    820 
    821 	ca = config_cfattach_lookup_cd(cd, cf->cf_atname);
    822 	KASSERT(ca != NULL);
    823 
    824 	/*
    825 	 * Ensure the device is deactivated.  If the device doesn't
    826 	 * have an activation entry point, we allow DVF_ACTIVE to
    827 	 * remain set.  Otherwise, if DVF_ACTIVE is still set, the
    828 	 * device is busy, and the detach fails.
    829 	 */
    830 	if (ca->ca_activate != NULL)
    831 		rv = config_deactivate(dev);
    832 
    833 	/*
    834 	 * Try to detach the device.  If that's not possible, then
    835 	 * we either panic() (for the forced but failed case), or
    836 	 * return an error.
    837 	 */
    838 	if (rv == 0) {
    839 		if (ca->ca_detach != NULL)
    840 			rv = (*ca->ca_detach)(dev, flags);
    841 		else
    842 			rv = EOPNOTSUPP;
    843 	}
    844 	if (rv != 0) {
    845 		if ((flags & DETACH_FORCE) == 0)
    846 			return (rv);
    847 		else
    848 			panic("config_detach: forced detach of %s failed (%d)",
    849 			    dev->dv_xname, rv);
    850 	}
    851 
    852 	/*
    853 	 * The device has now been successfully detached.
    854 	 */
    855 
    856 #ifdef DIAGNOSTIC
    857 	/*
    858 	 * Sanity: If you're successfully detached, you should have no
    859 	 * children.  (Note that because children must be attached
    860 	 * after parents, we only need to search the latter part of
    861 	 * the list.)
    862 	 */
    863 	for (d = TAILQ_NEXT(dev, dv_list); d != NULL;
    864 	    d = TAILQ_NEXT(d, dv_list)) {
    865 		if (d->dv_parent == dev) {
    866 			printf("config_detach: detached device %s"
    867 			    " has children %s\n", dev->dv_xname, d->dv_xname);
    868 			panic("config_detach");
    869 		}
    870 	}
    871 #endif
    872 
    873 	/*
    874 	 * Mark cfdata to show that the unit can be reused, if possible.
    875 	 */
    876 	TAILQ_FOREACH(ct, &allcftables, ct_list) {
    877 		for (cf = ct->ct_cfdata; cf->cf_name; cf++) {
    878 			if (STREQ(cf->cf_name, cd->cd_name)) {
    879 				if (cf->cf_fstate == FSTATE_FOUND &&
    880 				    cf->cf_unit == dev->dv_unit)
    881 					cf->cf_fstate = FSTATE_NOTFOUND;
    882 #ifdef __BROKEN_CONFIG_UNIT_USAGE
    883 				/*
    884 				 * Note that we can only re-use a starred
    885 				 * unit number if the unit being detached
    886 				 * had the last assigned unit number.
    887 				 */
    888 				if (cf->cf_fstate == FSTATE_STAR &&
    889 				    cf->cf_unit == dev->dv_unit + 1)
    890 					cf->cf_unit--;
    891 #endif /* __BROKEN_CONFIG_UNIT_USAGE */
    892 			}
    893 		}
    894 	}
    895 
    896 	/*
    897 	 * Unlink from device list.
    898 	 */
    899 	TAILQ_REMOVE(&alldevs, dev, dv_list);
    900 
    901 	/*
    902 	 * Remove from cfdriver's array, tell the world, and free softc.
    903 	 */
    904 	cd->cd_devs[dev->dv_unit] = NULL;
    905 	if ((flags & DETACH_QUIET) == 0)
    906 		printf("%s detached\n", dev->dv_xname);
    907 	free(dev, M_DEVBUF);
    908 
    909 	/*
    910 	 * If the device now has no units in use, deallocate its softc array.
    911 	 */
    912 	for (i = 0; i < cd->cd_ndevs; i++)
    913 		if (cd->cd_devs[i] != NULL)
    914 			break;
    915 	if (i == cd->cd_ndevs) {		/* nothing found; deallocate */
    916 		free(cd->cd_devs, M_DEVBUF);
    917 		cd->cd_devs = NULL;
    918 		cd->cd_ndevs = 0;
    919 	}
    920 
    921 	/*
    922 	 * Return success.
    923 	 */
    924 	return (0);
    925 }
    926 
    927 int
    928 config_activate(struct device *dev)
    929 {
    930 	const struct cfattach *ca = dev->dv_cfattach;
    931 	int rv = 0, oflags = dev->dv_flags;
    932 
    933 	if (ca->ca_activate == NULL)
    934 		return (EOPNOTSUPP);
    935 
    936 	if ((dev->dv_flags & DVF_ACTIVE) == 0) {
    937 		dev->dv_flags |= DVF_ACTIVE;
    938 		rv = (*ca->ca_activate)(dev, DVACT_ACTIVATE);
    939 		if (rv)
    940 			dev->dv_flags = oflags;
    941 	}
    942 	return (rv);
    943 }
    944 
    945 int
    946 config_deactivate(struct device *dev)
    947 {
    948 	const struct cfattach *ca = dev->dv_cfattach;
    949 	int rv = 0, oflags = dev->dv_flags;
    950 
    951 	if (ca->ca_activate == NULL)
    952 		return (EOPNOTSUPP);
    953 
    954 	if (dev->dv_flags & DVF_ACTIVE) {
    955 		dev->dv_flags &= ~DVF_ACTIVE;
    956 		rv = (*ca->ca_activate)(dev, DVACT_DEACTIVATE);
    957 		if (rv)
    958 			dev->dv_flags = oflags;
    959 	}
    960 	return (rv);
    961 }
    962 
    963 /*
    964  * Defer the configuration of the specified device until all
    965  * of its parent's devices have been attached.
    966  */
    967 void
    968 config_defer(struct device *dev, void (*func)(struct device *))
    969 {
    970 	struct deferred_config *dc;
    971 
    972 	if (dev->dv_parent == NULL)
    973 		panic("config_defer: can't defer config of a root device");
    974 
    975 #ifdef DIAGNOSTIC
    976 	for (dc = TAILQ_FIRST(&deferred_config_queue); dc != NULL;
    977 	     dc = TAILQ_NEXT(dc, dc_queue)) {
    978 		if (dc->dc_dev == dev)
    979 			panic("config_defer: deferred twice");
    980 	}
    981 #endif
    982 
    983 	dc = malloc(sizeof(*dc), M_DEVBUF, cold ? M_NOWAIT : M_WAITOK);
    984 	if (dc == NULL)
    985 		panic("config_defer: unable to allocate callback");
    986 
    987 	dc->dc_dev = dev;
    988 	dc->dc_func = func;
    989 	TAILQ_INSERT_TAIL(&deferred_config_queue, dc, dc_queue);
    990 	config_pending_incr();
    991 }
    992 
    993 /*
    994  * Defer some autoconfiguration for a device until after interrupts
    995  * are enabled.
    996  */
    997 void
    998 config_interrupts(struct device *dev, void (*func)(struct device *))
    999 {
   1000 	struct deferred_config *dc;
   1001 
   1002 	/*
   1003 	 * If interrupts are enabled, callback now.
   1004 	 */
   1005 	if (cold == 0) {
   1006 		(*func)(dev);
   1007 		return;
   1008 	}
   1009 
   1010 #ifdef DIAGNOSTIC
   1011 	for (dc = TAILQ_FIRST(&interrupt_config_queue); dc != NULL;
   1012 	     dc = TAILQ_NEXT(dc, dc_queue)) {
   1013 		if (dc->dc_dev == dev)
   1014 			panic("config_interrupts: deferred twice");
   1015 	}
   1016 #endif
   1017 
   1018 	dc = malloc(sizeof(*dc), M_DEVBUF, cold ? M_NOWAIT : M_WAITOK);
   1019 	if (dc == NULL)
   1020 		panic("config_interrupts: unable to allocate callback");
   1021 
   1022 	dc->dc_dev = dev;
   1023 	dc->dc_func = func;
   1024 	TAILQ_INSERT_TAIL(&interrupt_config_queue, dc, dc_queue);
   1025 	config_pending_incr();
   1026 }
   1027 
   1028 /*
   1029  * Process a deferred configuration queue.
   1030  */
   1031 static void
   1032 config_process_deferred(struct deferred_config_head *queue,
   1033     struct device *parent)
   1034 {
   1035 	struct deferred_config *dc, *ndc;
   1036 
   1037 	for (dc = TAILQ_FIRST(queue); dc != NULL; dc = ndc) {
   1038 		ndc = TAILQ_NEXT(dc, dc_queue);
   1039 		if (parent == NULL || dc->dc_dev->dv_parent == parent) {
   1040 			TAILQ_REMOVE(queue, dc, dc_queue);
   1041 			(*dc->dc_func)(dc->dc_dev);
   1042 			free(dc, M_DEVBUF);
   1043 			config_pending_decr();
   1044 		}
   1045 	}
   1046 }
   1047 
   1048 /*
   1049  * Manipulate the config_pending semaphore.
   1050  */
   1051 void
   1052 config_pending_incr(void)
   1053 {
   1054 
   1055 	config_pending++;
   1056 }
   1057 
   1058 void
   1059 config_pending_decr(void)
   1060 {
   1061 
   1062 #ifdef DIAGNOSTIC
   1063 	if (config_pending == 0)
   1064 		panic("config_pending_decr: config_pending == 0");
   1065 #endif
   1066 	config_pending--;
   1067 	if (config_pending == 0)
   1068 		wakeup((void *)&config_pending);
   1069 }
   1070 
   1071 /*
   1072  * Register a "finalization" routine.  Finalization routines are
   1073  * called iteratively once all real devices have been found during
   1074  * autoconfiguration, for as long as any one finalizer has done
   1075  * any work.
   1076  */
   1077 int
   1078 config_finalize_register(struct device *dev, int (*fn)(struct device *))
   1079 {
   1080 	struct finalize_hook *f;
   1081 
   1082 	/*
   1083 	 * If finalization has already been done, invoke the
   1084 	 * callback function now.
   1085 	 */
   1086 	if (config_finalize_done) {
   1087 		while ((*fn)(dev) != 0)
   1088 			/* loop */ ;
   1089 	}
   1090 
   1091 	/* Ensure this isn't already on the list. */
   1092 	TAILQ_FOREACH(f, &config_finalize_list, f_list) {
   1093 		if (f->f_func == fn && f->f_dev == dev)
   1094 			return (EEXIST);
   1095 	}
   1096 
   1097 	f = malloc(sizeof(*f), M_TEMP, M_WAITOK);
   1098 	f->f_func = fn;
   1099 	f->f_dev = dev;
   1100 	TAILQ_INSERT_TAIL(&config_finalize_list, f, f_list);
   1101 
   1102 	return (0);
   1103 }
   1104 
   1105 void
   1106 config_finalize(void)
   1107 {
   1108 	struct finalize_hook *f;
   1109 	int rv;
   1110 
   1111 	/* Run the hooks until none of them does any work. */
   1112 	do {
   1113 		rv = 0;
   1114 		TAILQ_FOREACH(f, &config_finalize_list, f_list)
   1115 			rv |= (*f->f_func)(f->f_dev);
   1116 	} while (rv != 0);
   1117 
   1118 	config_finalize_done = 1;
   1119 
   1120 	/* Now free all the hooks. */
   1121 	while ((f = TAILQ_FIRST(&config_finalize_list)) != NULL) {
   1122 		TAILQ_REMOVE(&config_finalize_list, f, f_list);
   1123 		free(f, M_TEMP);
   1124 	}
   1125 }
   1126 
   1127 /*
   1128  * Attach a statically-initialized event.  The type and string pointers
   1129  * are already set up.
   1130  */
   1131 void
   1132 evcnt_attach_static(struct evcnt *ev)
   1133 {
   1134 	int len;
   1135 
   1136 	len = strlen(ev->ev_group);
   1137 #ifdef DIAGNOSTIC
   1138 	if (len >= EVCNT_STRING_MAX)		/* ..._MAX includes NUL */
   1139 		panic("evcnt_attach_static: group length (%s)", ev->ev_group);
   1140 #endif
   1141 	ev->ev_grouplen = len;
   1142 
   1143 	len = strlen(ev->ev_name);
   1144 #ifdef DIAGNOSTIC
   1145 	if (len >= EVCNT_STRING_MAX)		/* ..._MAX includes NUL */
   1146 		panic("evcnt_attach_static: name length (%s)", ev->ev_name);
   1147 #endif
   1148 	ev->ev_namelen = len;
   1149 
   1150 	TAILQ_INSERT_TAIL(&allevents, ev, ev_list);
   1151 }
   1152 
   1153 /*
   1154  * Attach a dynamically-initialized event.  Zero it, set up the type
   1155  * and string pointers and then act like it was statically initialized.
   1156  */
   1157 void
   1158 evcnt_attach_dynamic(struct evcnt *ev, int type, const struct evcnt *parent,
   1159     const char *group, const char *name)
   1160 {
   1161 
   1162 	memset(ev, 0, sizeof *ev);
   1163 	ev->ev_type = type;
   1164 	ev->ev_parent = parent;
   1165 	ev->ev_group = group;
   1166 	ev->ev_name = name;
   1167 	evcnt_attach_static(ev);
   1168 }
   1169 
   1170 /*
   1171  * Detach an event.
   1172  */
   1173 void
   1174 evcnt_detach(struct evcnt *ev)
   1175 {
   1176 
   1177 	TAILQ_REMOVE(&allevents, ev, ev_list);
   1178 }
   1179 
   1180 #ifdef DDB
   1181 void
   1182 event_print(int full, void (*pr)(const char *, ...))
   1183 {
   1184 	struct evcnt *evp;
   1185 
   1186 	TAILQ_FOREACH(evp, &allevents, ev_list) {
   1187 		if (evp->ev_count == 0 && !full)
   1188 			continue;
   1189 
   1190 		(*pr)("evcnt type %d: %s %s = %lld\n", evp->ev_type,
   1191 		    evp->ev_group, evp->ev_name, evp->ev_count);
   1192 	}
   1193 }
   1194 #endif /* DDB */
   1195