Home | History | Annotate | Line # | Download | only in kern
subr_autoconf.c revision 1.77
      1 /* $NetBSD: subr_autoconf.c,v 1.77 2002/10/09 02:59:55 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.77 2002/10/09 02:59:55 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 (dev->dv_cfattach == ca)
    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 = parent->dv_cfdriver;
    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 == DVUNIT_ANY ||	/* 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  * As above, but for pseudo-devices.  Pseudo-devices attached in this
    794  * way are silently inserted into the device tree, and their children
    795  * attached.
    796  *
    797  * Note that because pseudo-devices are attached silently, any information
    798  * the attach routine wishes to print should be prefixed with the device
    799  * name by the attach routine.
    800  */
    801 struct device *
    802 config_attach_pseudo(const char *name, int unit)
    803 {
    804 	struct device *dev;
    805 	struct cfdriver *cd;
    806 	struct cfattach *ca;
    807 	size_t lname, lunit;
    808 	const char *xunit;
    809 	int myunit;
    810 	char num[10];
    811 
    812 	cd = config_cfdriver_lookup(name);
    813 	if (cd == NULL)
    814 		return (NULL);
    815 
    816 	ca = config_cfattach_lookup_cd(cd, name);
    817 	if (ca == NULL)
    818 		return (NULL);
    819 
    820 	if (ca->ca_devsize < sizeof(struct device))
    821 		panic("config_attach_pseudo");
    822 
    823 	if (unit == DVUNIT_ANY) {
    824 		for (myunit = 0; myunit < cd->cd_ndevs; myunit++)
    825 			if (cd->cd_devs[myunit] == NULL)
    826 				break;
    827 		/*
    828 		 * myunit is now the unit of the first NULL device pointer.
    829 		 */
    830 	} else {
    831 		myunit = unit;
    832 		if (myunit < cd->cd_ndevs && cd->cd_devs[myunit] != NULL)
    833 			return (NULL);
    834 	}
    835 
    836 	/* compute length of name and decimal expansion of unit number */
    837 	lname = strlen(cd->cd_name);
    838 	xunit = number(&num[sizeof(num)], myunit);
    839 	lunit = &num[sizeof(num)] - xunit;
    840 	if (lname + lunit > sizeof(dev->dv_xname))
    841 		panic("config_attach_pseudo: device name too long");
    842 
    843 	/* get memory for all device vars */
    844 	dev = (struct device *)malloc(ca->ca_devsize, M_DEVBUF,
    845 	    cold ? M_NOWAIT : M_WAITOK);
    846 	if (!dev)
    847 		panic("config_attach_pseudo: memory allocation for device "
    848 		    "softc failed");
    849 	memset(dev, 0, ca->ca_devsize);
    850 	TAILQ_INSERT_TAIL(&alldevs, dev, dv_list);	/* link up */
    851 	dev->dv_class = cd->cd_class;
    852 	dev->dv_cfdata = NULL;
    853 	dev->dv_cfdriver = cd;
    854 	dev->dv_cfattach = ca;
    855 	dev->dv_unit = myunit;
    856 	memcpy(dev->dv_xname, cd->cd_name, lname);
    857 	memcpy(dev->dv_xname + lname, xunit, lunit);
    858 	dev->dv_parent = ROOT;
    859 	dev->dv_flags = DVF_ACTIVE;	/* always initially active */
    860 
    861 	/* put this device in the devices array */
    862 	config_makeroom(dev->dv_unit, cd);
    863 	if (cd->cd_devs[dev->dv_unit])
    864 		panic("config_attach_pseudo: duplicate %s", dev->dv_xname);
    865 	cd->cd_devs[dev->dv_unit] = dev;
    866 
    867 #if 0	/* XXXJRT not yet */
    868 #ifdef __HAVE_DEVICE_REGISTER
    869 	device_register(dev, NULL);	/* like a root node */
    870 #endif
    871 #endif
    872 	(*ca->ca_attach)(ROOT, dev, NULL);
    873 	config_process_deferred(&deferred_config_queue, dev);
    874 	return (dev);
    875 }
    876 
    877 /*
    878  * Detach a device.  Optionally forced (e.g. because of hardware
    879  * removal) and quiet.  Returns zero if successful, non-zero
    880  * (an error code) otherwise.
    881  *
    882  * Note that this code wants to be run from a process context, so
    883  * that the detach can sleep to allow processes which have a device
    884  * open to run and unwind their stacks.
    885  */
    886 int
    887 config_detach(struct device *dev, int flags)
    888 {
    889 	struct cftable *ct;
    890 	struct cfdata *cf;
    891 	const struct cfattach *ca;
    892 	struct cfdriver *cd;
    893 #ifdef DIAGNOSTIC
    894 	struct device *d;
    895 #endif
    896 	int rv = 0, i;
    897 
    898 #ifdef DIAGNOSTIC
    899 	if (dev->dv_cfdata != NULL &&
    900 	    dev->dv_cfdata->cf_fstate != FSTATE_FOUND &&
    901 	    dev->dv_cfdata->cf_fstate != FSTATE_STAR)
    902 		panic("config_detach: bad device fstate");
    903 #endif
    904 	cd = dev->dv_cfdriver;
    905 	KASSERT(cd != NULL);
    906 
    907 	ca = dev->dv_cfattach;
    908 	KASSERT(ca != NULL);
    909 
    910 	/*
    911 	 * Ensure the device is deactivated.  If the device doesn't
    912 	 * have an activation entry point, we allow DVF_ACTIVE to
    913 	 * remain set.  Otherwise, if DVF_ACTIVE is still set, the
    914 	 * device is busy, and the detach fails.
    915 	 */
    916 	if (ca->ca_activate != NULL)
    917 		rv = config_deactivate(dev);
    918 
    919 	/*
    920 	 * Try to detach the device.  If that's not possible, then
    921 	 * we either panic() (for the forced but failed case), or
    922 	 * return an error.
    923 	 */
    924 	if (rv == 0) {
    925 		if (ca->ca_detach != NULL)
    926 			rv = (*ca->ca_detach)(dev, flags);
    927 		else
    928 			rv = EOPNOTSUPP;
    929 	}
    930 	if (rv != 0) {
    931 		if ((flags & DETACH_FORCE) == 0)
    932 			return (rv);
    933 		else
    934 			panic("config_detach: forced detach of %s failed (%d)",
    935 			    dev->dv_xname, rv);
    936 	}
    937 
    938 	/*
    939 	 * The device has now been successfully detached.
    940 	 */
    941 
    942 #ifdef DIAGNOSTIC
    943 	/*
    944 	 * Sanity: If you're successfully detached, you should have no
    945 	 * children.  (Note that because children must be attached
    946 	 * after parents, we only need to search the latter part of
    947 	 * the list.)
    948 	 */
    949 	for (d = TAILQ_NEXT(dev, dv_list); d != NULL;
    950 	    d = TAILQ_NEXT(d, dv_list)) {
    951 		if (d->dv_parent == dev) {
    952 			printf("config_detach: detached device %s"
    953 			    " has children %s\n", dev->dv_xname, d->dv_xname);
    954 			panic("config_detach");
    955 		}
    956 	}
    957 #endif
    958 
    959 	/*
    960 	 * Mark cfdata to show that the unit can be reused, if possible.
    961 	 */
    962 	TAILQ_FOREACH(ct, &allcftables, ct_list) {
    963 		for (cf = ct->ct_cfdata; cf->cf_name; cf++) {
    964 			if (STREQ(cf->cf_name, cd->cd_name)) {
    965 				if (cf->cf_fstate == FSTATE_FOUND &&
    966 				    cf->cf_unit == dev->dv_unit)
    967 					cf->cf_fstate = FSTATE_NOTFOUND;
    968 #ifdef __BROKEN_CONFIG_UNIT_USAGE
    969 				/*
    970 				 * Note that we can only re-use a starred
    971 				 * unit number if the unit being detached
    972 				 * had the last assigned unit number.
    973 				 */
    974 				if (cf->cf_fstate == FSTATE_STAR &&
    975 				    cf->cf_unit == dev->dv_unit + 1)
    976 					cf->cf_unit--;
    977 #endif /* __BROKEN_CONFIG_UNIT_USAGE */
    978 			}
    979 		}
    980 	}
    981 
    982 	/*
    983 	 * Unlink from device list.
    984 	 */
    985 	TAILQ_REMOVE(&alldevs, dev, dv_list);
    986 
    987 	/*
    988 	 * Remove from cfdriver's array, tell the world (unless it was
    989 	 * a pseudo-device), and free softc.
    990 	 */
    991 	cd->cd_devs[dev->dv_unit] = NULL;
    992 	if (dev->dv_cfdata != NULL && (flags & DETACH_QUIET) == 0)
    993 		printf("%s detached\n", dev->dv_xname);
    994 	free(dev, M_DEVBUF);
    995 
    996 	/*
    997 	 * If the device now has no units in use, deallocate its softc array.
    998 	 */
    999 	for (i = 0; i < cd->cd_ndevs; i++)
   1000 		if (cd->cd_devs[i] != NULL)
   1001 			break;
   1002 	if (i == cd->cd_ndevs) {		/* nothing found; deallocate */
   1003 		free(cd->cd_devs, M_DEVBUF);
   1004 		cd->cd_devs = NULL;
   1005 		cd->cd_ndevs = 0;
   1006 	}
   1007 
   1008 	/*
   1009 	 * Return success.
   1010 	 */
   1011 	return (0);
   1012 }
   1013 
   1014 int
   1015 config_activate(struct device *dev)
   1016 {
   1017 	const struct cfattach *ca = dev->dv_cfattach;
   1018 	int rv = 0, oflags = dev->dv_flags;
   1019 
   1020 	if (ca->ca_activate == NULL)
   1021 		return (EOPNOTSUPP);
   1022 
   1023 	if ((dev->dv_flags & DVF_ACTIVE) == 0) {
   1024 		dev->dv_flags |= DVF_ACTIVE;
   1025 		rv = (*ca->ca_activate)(dev, DVACT_ACTIVATE);
   1026 		if (rv)
   1027 			dev->dv_flags = oflags;
   1028 	}
   1029 	return (rv);
   1030 }
   1031 
   1032 int
   1033 config_deactivate(struct device *dev)
   1034 {
   1035 	const struct cfattach *ca = dev->dv_cfattach;
   1036 	int rv = 0, oflags = dev->dv_flags;
   1037 
   1038 	if (ca->ca_activate == NULL)
   1039 		return (EOPNOTSUPP);
   1040 
   1041 	if (dev->dv_flags & DVF_ACTIVE) {
   1042 		dev->dv_flags &= ~DVF_ACTIVE;
   1043 		rv = (*ca->ca_activate)(dev, DVACT_DEACTIVATE);
   1044 		if (rv)
   1045 			dev->dv_flags = oflags;
   1046 	}
   1047 	return (rv);
   1048 }
   1049 
   1050 /*
   1051  * Defer the configuration of the specified device until all
   1052  * of its parent's devices have been attached.
   1053  */
   1054 void
   1055 config_defer(struct device *dev, void (*func)(struct device *))
   1056 {
   1057 	struct deferred_config *dc;
   1058 
   1059 	if (dev->dv_parent == NULL)
   1060 		panic("config_defer: can't defer config of a root device");
   1061 
   1062 #ifdef DIAGNOSTIC
   1063 	for (dc = TAILQ_FIRST(&deferred_config_queue); dc != NULL;
   1064 	     dc = TAILQ_NEXT(dc, dc_queue)) {
   1065 		if (dc->dc_dev == dev)
   1066 			panic("config_defer: deferred twice");
   1067 	}
   1068 #endif
   1069 
   1070 	dc = malloc(sizeof(*dc), M_DEVBUF, cold ? M_NOWAIT : M_WAITOK);
   1071 	if (dc == NULL)
   1072 		panic("config_defer: unable to allocate callback");
   1073 
   1074 	dc->dc_dev = dev;
   1075 	dc->dc_func = func;
   1076 	TAILQ_INSERT_TAIL(&deferred_config_queue, dc, dc_queue);
   1077 	config_pending_incr();
   1078 }
   1079 
   1080 /*
   1081  * Defer some autoconfiguration for a device until after interrupts
   1082  * are enabled.
   1083  */
   1084 void
   1085 config_interrupts(struct device *dev, void (*func)(struct device *))
   1086 {
   1087 	struct deferred_config *dc;
   1088 
   1089 	/*
   1090 	 * If interrupts are enabled, callback now.
   1091 	 */
   1092 	if (cold == 0) {
   1093 		(*func)(dev);
   1094 		return;
   1095 	}
   1096 
   1097 #ifdef DIAGNOSTIC
   1098 	for (dc = TAILQ_FIRST(&interrupt_config_queue); dc != NULL;
   1099 	     dc = TAILQ_NEXT(dc, dc_queue)) {
   1100 		if (dc->dc_dev == dev)
   1101 			panic("config_interrupts: deferred twice");
   1102 	}
   1103 #endif
   1104 
   1105 	dc = malloc(sizeof(*dc), M_DEVBUF, cold ? M_NOWAIT : M_WAITOK);
   1106 	if (dc == NULL)
   1107 		panic("config_interrupts: unable to allocate callback");
   1108 
   1109 	dc->dc_dev = dev;
   1110 	dc->dc_func = func;
   1111 	TAILQ_INSERT_TAIL(&interrupt_config_queue, dc, dc_queue);
   1112 	config_pending_incr();
   1113 }
   1114 
   1115 /*
   1116  * Process a deferred configuration queue.
   1117  */
   1118 static void
   1119 config_process_deferred(struct deferred_config_head *queue,
   1120     struct device *parent)
   1121 {
   1122 	struct deferred_config *dc, *ndc;
   1123 
   1124 	for (dc = TAILQ_FIRST(queue); dc != NULL; dc = ndc) {
   1125 		ndc = TAILQ_NEXT(dc, dc_queue);
   1126 		if (parent == NULL || dc->dc_dev->dv_parent == parent) {
   1127 			TAILQ_REMOVE(queue, dc, dc_queue);
   1128 			(*dc->dc_func)(dc->dc_dev);
   1129 			free(dc, M_DEVBUF);
   1130 			config_pending_decr();
   1131 		}
   1132 	}
   1133 }
   1134 
   1135 /*
   1136  * Manipulate the config_pending semaphore.
   1137  */
   1138 void
   1139 config_pending_incr(void)
   1140 {
   1141 
   1142 	config_pending++;
   1143 }
   1144 
   1145 void
   1146 config_pending_decr(void)
   1147 {
   1148 
   1149 #ifdef DIAGNOSTIC
   1150 	if (config_pending == 0)
   1151 		panic("config_pending_decr: config_pending == 0");
   1152 #endif
   1153 	config_pending--;
   1154 	if (config_pending == 0)
   1155 		wakeup((void *)&config_pending);
   1156 }
   1157 
   1158 /*
   1159  * Register a "finalization" routine.  Finalization routines are
   1160  * called iteratively once all real devices have been found during
   1161  * autoconfiguration, for as long as any one finalizer has done
   1162  * any work.
   1163  */
   1164 int
   1165 config_finalize_register(struct device *dev, int (*fn)(struct device *))
   1166 {
   1167 	struct finalize_hook *f;
   1168 
   1169 	/*
   1170 	 * If finalization has already been done, invoke the
   1171 	 * callback function now.
   1172 	 */
   1173 	if (config_finalize_done) {
   1174 		while ((*fn)(dev) != 0)
   1175 			/* loop */ ;
   1176 	}
   1177 
   1178 	/* Ensure this isn't already on the list. */
   1179 	TAILQ_FOREACH(f, &config_finalize_list, f_list) {
   1180 		if (f->f_func == fn && f->f_dev == dev)
   1181 			return (EEXIST);
   1182 	}
   1183 
   1184 	f = malloc(sizeof(*f), M_TEMP, M_WAITOK);
   1185 	f->f_func = fn;
   1186 	f->f_dev = dev;
   1187 	TAILQ_INSERT_TAIL(&config_finalize_list, f, f_list);
   1188 
   1189 	return (0);
   1190 }
   1191 
   1192 void
   1193 config_finalize(void)
   1194 {
   1195 	struct finalize_hook *f;
   1196 	int rv;
   1197 
   1198 	/* Run the hooks until none of them does any work. */
   1199 	do {
   1200 		rv = 0;
   1201 		TAILQ_FOREACH(f, &config_finalize_list, f_list)
   1202 			rv |= (*f->f_func)(f->f_dev);
   1203 	} while (rv != 0);
   1204 
   1205 	config_finalize_done = 1;
   1206 
   1207 	/* Now free all the hooks. */
   1208 	while ((f = TAILQ_FIRST(&config_finalize_list)) != NULL) {
   1209 		TAILQ_REMOVE(&config_finalize_list, f, f_list);
   1210 		free(f, M_TEMP);
   1211 	}
   1212 }
   1213 
   1214 /*
   1215  * Attach a statically-initialized event.  The type and string pointers
   1216  * are already set up.
   1217  */
   1218 void
   1219 evcnt_attach_static(struct evcnt *ev)
   1220 {
   1221 	int len;
   1222 
   1223 	len = strlen(ev->ev_group);
   1224 #ifdef DIAGNOSTIC
   1225 	if (len >= EVCNT_STRING_MAX)		/* ..._MAX includes NUL */
   1226 		panic("evcnt_attach_static: group length (%s)", ev->ev_group);
   1227 #endif
   1228 	ev->ev_grouplen = len;
   1229 
   1230 	len = strlen(ev->ev_name);
   1231 #ifdef DIAGNOSTIC
   1232 	if (len >= EVCNT_STRING_MAX)		/* ..._MAX includes NUL */
   1233 		panic("evcnt_attach_static: name length (%s)", ev->ev_name);
   1234 #endif
   1235 	ev->ev_namelen = len;
   1236 
   1237 	TAILQ_INSERT_TAIL(&allevents, ev, ev_list);
   1238 }
   1239 
   1240 /*
   1241  * Attach a dynamically-initialized event.  Zero it, set up the type
   1242  * and string pointers and then act like it was statically initialized.
   1243  */
   1244 void
   1245 evcnt_attach_dynamic(struct evcnt *ev, int type, const struct evcnt *parent,
   1246     const char *group, const char *name)
   1247 {
   1248 
   1249 	memset(ev, 0, sizeof *ev);
   1250 	ev->ev_type = type;
   1251 	ev->ev_parent = parent;
   1252 	ev->ev_group = group;
   1253 	ev->ev_name = name;
   1254 	evcnt_attach_static(ev);
   1255 }
   1256 
   1257 /*
   1258  * Detach an event.
   1259  */
   1260 void
   1261 evcnt_detach(struct evcnt *ev)
   1262 {
   1263 
   1264 	TAILQ_REMOVE(&allevents, ev, ev_list);
   1265 }
   1266 
   1267 #ifdef DDB
   1268 void
   1269 event_print(int full, void (*pr)(const char *, ...))
   1270 {
   1271 	struct evcnt *evp;
   1272 
   1273 	TAILQ_FOREACH(evp, &allevents, ev_list) {
   1274 		if (evp->ev_count == 0 && !full)
   1275 			continue;
   1276 
   1277 		(*pr)("evcnt type %d: %s %s = %lld\n", evp->ev_type,
   1278 		    evp->ev_group, evp->ev_name, evp->ev_count);
   1279 	}
   1280 }
   1281 #endif /* DDB */
   1282