Home | History | Annotate | Line # | Download | only in kern
subr_autoconf.c revision 1.62.6.1
      1 /* $NetBSD: subr_autoconf.c,v 1.62.6.1 2002/03/22 18:29:52 eeh 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.62.6.1 2002/03/22 18:29:52 eeh 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 <sys/properties.h>
     96 #include <machine/limits.h>
     97 
     98 #include "opt_userconf.h"
     99 #ifdef USERCONF
    100 #include <sys/userconf.h>
    101 #include <sys/reboot.h>
    102 #endif
    103 
    104 /*
    105  * Autoconfiguration subroutines.
    106  */
    107 
    108 static struct device *dev_create(struct device *, ssize_t, int);
    109 
    110 /*
    111  * ioconf.c exports exactly two names: cfdata and cfroots.  All system
    112  * devices and drivers are found via these tables.
    113  */
    114 extern struct cfdata cfdata[];
    115 extern short cfroots[];
    116 
    117 #define	ROOT ((struct device *)NULL)
    118 
    119 struct matchinfo {
    120 	cfmatch_t fn;
    121 	struct	device *parent;
    122 	void	*aux;
    123 	struct	cfdata *match;
    124 	int	pri;
    125 };
    126 
    127 static char *number(char *, int);
    128 static void mapply(struct matchinfo *, struct cfdata *, struct device *);
    129 static void locset(struct device *, struct cfdata *);
    130 static void locrm(struct device *, struct cfdata *);
    131 
    132 struct deferred_config {
    133 	TAILQ_ENTRY(deferred_config) dc_queue;
    134 	struct device *dc_dev;
    135 	void (*dc_func)(struct device *);
    136 };
    137 
    138 TAILQ_HEAD(deferred_config_head, deferred_config);
    139 
    140 struct deferred_config_head deferred_config_queue;
    141 struct deferred_config_head interrupt_config_queue;
    142 
    143 static void config_process_deferred(struct deferred_config_head *,
    144 	struct device *);
    145 
    146 /* list of all devices */
    147 struct devicelist alldevs;
    148 
    149 /* list of all events */
    150 struct evcntlist allevents = TAILQ_HEAD_INITIALIZER(allevents);
    151 
    152 __volatile int config_pending;		/* semaphore for mountroot */
    153 
    154 /* device properties database */
    155 static propdb_t devpropdb;
    156 
    157 /*
    158  * Configure the system's hardware.
    159  */
    160 void
    161 configure(void)
    162 {
    163 
    164 	TAILQ_INIT(&deferred_config_queue);
    165 	TAILQ_INIT(&interrupt_config_queue);
    166 	TAILQ_INIT(&alldevs);
    167 
    168 	devpropdb = propdb_create("devprop");
    169 
    170 #ifdef USERCONF
    171 	if (boothowto & RB_USERCONF)
    172 		user_config();
    173 #endif
    174 
    175 	/*
    176 	 * Do the machine-dependent portion of autoconfiguration.  This
    177 	 * sets the configuration machinery here in motion by "finding"
    178 	 * the root bus.  When this function returns, we expect interrupts
    179 	 * to be enabled.
    180 	 */
    181 	cpu_configure();
    182 
    183 	/*
    184 	 * Now that we've found all the hardware, start the real time
    185 	 * and statistics clocks.
    186 	 */
    187 	initclocks();
    188 
    189 	cold = 0;	/* clocks are running, we're warm now! */
    190 
    191 	/*
    192 	 * Now callback to finish configuration for devices which want
    193 	 * to do this once interrupts are enabled.
    194 	 */
    195 	config_process_deferred(&interrupt_config_queue, NULL);
    196 }
    197 
    198 /*
    199  * Set locators as properties on device node.
    200  */
    201 static void
    202 locset(struct device *d, struct cfdata *cf)
    203 {
    204 	int i;
    205 	int type = PROP_CONST|PROP_INT;
    206 	char buf[32];
    207 
    208 	for (i=0; cf->cf_locnames[i]; i++) {
    209 		sprintf(buf, "loc-%s", cf->cf_locnames[i]);
    210 		dev_setprop(d, buf, &cf->cf_loc[i],
    211 			    sizeof(int), type, (!cold));
    212 	}
    213 }
    214 
    215 /*
    216  * Remove locator properties from device node.
    217  */
    218 static void
    219 locrm(struct device *d, struct cfdata *cf)
    220 {
    221 	int i;
    222 	char buf[32];
    223 
    224 	for (i=0; cf->cf_locnames[i]; i++) {
    225 		sprintf(buf, "loc-%s", cf->cf_locnames[i]);
    226 		dev_delprop(d, buf);
    227 	}
    228 }
    229 
    230 /*
    231  * Apply the matching function and choose the best.  This is used
    232  * a few times and we want to keep the code small.
    233  */
    234 static void
    235 mapply(struct matchinfo *m, struct cfdata *cf, struct device *child)
    236 {
    237 	int pri;
    238 	void *aux = m->aux;
    239 
    240 	if ((ssize_t)cf->cf_attach->ca_devsize < 0) {
    241 		/* New-style device driver */
    242 		if (!child)
    243 			panic("mapply: no device for new-style driver\n");
    244 		locset(child, cf);
    245 		child->dv_private = aux;
    246 		aux = child;
    247 	}
    248 	if (m->fn != NULL)
    249 		/* Someday the submatch function should use properties too. */
    250 		pri = (*m->fn)(m->parent, cf, m->aux);
    251 	else {
    252 	        if (cf->cf_attach->ca_match == NULL) {
    253 			panic("mapply: no match function for '%s' device\n",
    254 			    cf->cf_driver->cd_name);
    255 		}
    256 		pri = (*cf->cf_attach->ca_match)(m->parent, cf, aux);
    257 	}
    258 	if (pri > m->pri) {
    259 		m->match = cf;
    260 		m->pri = pri;
    261 	}
    262 	if (child) {
    263 		locrm(child, cf);
    264 		child->dv_private = NULL;
    265 	}
    266 }
    267 
    268 /*
    269  * Iterate over all potential children of some device, calling the given
    270  * function (default being the child's match function) for each one.
    271  * Nonzero returns are matches; the highest value returned is considered
    272  * the best match.  Return the `found child' if we got a match, or NULL
    273  * otherwise.  The `aux' pointer is simply passed on through.
    274  *
    275  * Note that this function is designed so that it can be used to apply
    276  * an arbitrary function to all potential children (its return value
    277  * can be ignored).
    278  */
    279 struct cfdata *
    280 config_search_ad(cfmatch_t fn, struct device *parent, void *aux,
    281 		 struct device *child)
    282 {
    283 	struct cfdata *cf;
    284 	short *p;
    285 	struct matchinfo m;
    286 
    287 	m.fn = fn;
    288 	m.parent = parent;
    289 	m.aux = aux;
    290 	m.match = NULL;
    291 	m.pri = 0;
    292 
    293 	for (cf = cfdata; cf->cf_driver; cf++) {
    294 		/*
    295 		 * Skip cf if no longer eligible, otherwise scan through
    296 		 * parents for one matching `parent', and try match function.
    297 		 */
    298 		if (cf->cf_fstate == FSTATE_FOUND)
    299 			continue;
    300 		for (p = cf->cf_parents; *p >= 0; p++)
    301 			if (parent->dv_cfdata == &cfdata[*p])
    302 				mapply(&m, cf, child);
    303 	}
    304 	return (m.match);
    305 }
    306 
    307 /*
    308  * Find the given root device.
    309  * This is much like config_search, but there is no parent.
    310  */
    311 struct cfdata *
    312 config_rootsearch_ad(cfmatch_t fn, const char *rootname, void *aux,
    313 		     struct device *root)
    314 {
    315 	struct cfdata *cf;
    316 	short *p;
    317 	struct matchinfo m;
    318 
    319 	m.fn = fn;
    320 	m.parent = ROOT;
    321 	m.aux = aux;
    322 	m.match = NULL;
    323 	m.pri = 0;
    324 	/*
    325 	 * Look at root entries for matching name.  We do not bother
    326 	 * with found-state here since only one root should ever be
    327 	 * searched (and it must be done first).
    328 	 */
    329 	for (p = cfroots; *p >= 0; p++) {
    330 		cf = &cfdata[*p];
    331 		if (strcmp(cf->cf_driver->cd_name, rootname) == 0)
    332 			mapply(&m, cf, root);
    333 	}
    334 	return (m.match);
    335 }
    336 
    337 static const char *msgs[3] = { "", " not configured\n", " unsupported\n" };
    338 
    339 /*
    340  * The given `aux' argument describes a device that has been found
    341  * on the given parent, but not necessarily configured.  Locate the
    342  * configuration data for that device (using the submatch function
    343  * provided, or using candidates' cd_match configuration driver
    344  * functions) and attach it, and return true.  If the device was
    345  * not configured, call the given `print' function and return 0.
    346  */
    347 struct device *
    348 config_found_sad(struct device *parent, void *aux, cfprint_t print,
    349     cfmatch_t submatch, struct device *d)
    350 {
    351 	struct cfdata *cf;
    352 
    353 	/*
    354 	 * Creating the dummy device here is really optional.  But
    355 	 * it allows old-style bus drivers to attach new-style children.
    356 	 */
    357 	if (!d) d = dev_create(ROOT, 0, cold ? M_NOWAIT : M_WAITOK);
    358 	if ((cf = config_search_ad(submatch, parent, aux, d)) != NULL)
    359 		return (config_attach_ad(parent, cf, aux, print, d));
    360 	if (print)
    361 		printf("%s", msgs[(*print)(aux, parent->dv_xname)]);
    362 	return (NULL);
    363 }
    364 
    365 /*
    366  * As above, but for root devices.
    367  */
    368 struct device *
    369 config_rootfound(const char *rootname, void *aux)
    370 {
    371 	struct cfdata *cf;
    372 	struct device *root;
    373 
    374 	root = dev_create(ROOT, 0, cold ? M_NOWAIT : M_WAITOK);
    375 	if ((cf = config_rootsearch_ad((cfmatch_t)NULL, rootname, aux, root)) != NULL)
    376 		return (config_attach_ad(ROOT, cf, aux, (cfprint_t)NULL, root));
    377 	printf("root device %s not configured\n", rootname);
    378 	return (NULL);
    379 }
    380 
    381 /* just like sprintf(buf, "%d") except that it works from the end */
    382 static char *
    383 number(char *ep, int n)
    384 {
    385 
    386 	*--ep = 0;
    387 	while (n >= 10) {
    388 		*--ep = (n % 10) + '0';
    389 		n /= 10;
    390 	}
    391 	*--ep = n + '0';
    392 	return (ep);
    393 }
    394 
    395 /*
    396  * Allocate an empty device node.  If `parent' is provided then the
    397  * new node is attached to the tree under `parent'.  If `size'
    398  * is provided, then the new device node is allocated to be that
    399  * size.
    400  */
    401 static struct device *
    402 dev_create(struct device *parent, ssize_t size, int wait) {
    403 	struct device * dev;
    404 
    405 	/* get memory for all device vars */
    406 	if (size == 0)
    407 		size = sizeof(struct device);
    408 	dev = (struct device *)malloc(size, M_DEVBUF, wait);
    409 	if (!dev)
    410 	    panic("dev_create: memory allocation for device failed");
    411 	memset(dev, 0, size);
    412 	TAILQ_INSERT_TAIL(&alldevs, dev, dv_list);	/* link up */
    413 	dev->dv_class = DV_EMPTY;
    414 	if (parent)
    415 		dev->dv_parent = parent;
    416 	return (dev);
    417 }
    418 
    419 /*
    420  * Expand the size of the cd_devs array if necessary.
    421  */
    422 void
    423 config_makeroom(int n, struct cfdriver *cd)
    424 {
    425 	int old, new;
    426 	void **nsp;
    427 
    428 	if (n < cd->cd_ndevs)
    429 		return;
    430 
    431 	/*
    432 	 * Need to expand the array.
    433 	 */
    434 	old = cd->cd_ndevs;
    435 	if (old == 0)
    436 		new = MINALLOCSIZE / sizeof(void *);
    437 	else
    438 		new = old * 2;
    439 	while (new <= n)
    440 		new *= 2;
    441 	cd->cd_ndevs = new;
    442 	nsp = malloc(new * sizeof(void *), M_DEVBUF,
    443 	    cold ? M_NOWAIT : M_WAITOK);
    444 	if (nsp == NULL)
    445 		panic("config_attach: %sing dev array",
    446 		    old != 0 ? "expand" : "creat");
    447 	memset(nsp + old, 0, (new - old) * sizeof(void *));
    448 	if (old != 0) {
    449 		memcpy(nsp, cd->cd_devs, old * sizeof(void *));
    450 		free(cd->cd_devs, M_DEVBUF);
    451 	}
    452 	cd->cd_devs = nsp;
    453 }
    454 
    455 /*
    456  * Attach a found device.  Allocates memory for device variables.
    457  */
    458 struct device *
    459 config_attach_ad(struct device *parent, struct cfdata *cf, void *aux,
    460 	cfprint_t print, struct device *propdev)
    461 {
    462 	struct device *dev;
    463 	struct cfdriver *cd;
    464 	struct cfattach *ca;
    465 	size_t lname, lunit;
    466 	ssize_t softsize;
    467 	const char *xunit;
    468 	int myunit;
    469 	char num[10];
    470 
    471 	cd = cf->cf_driver;
    472 	ca = cf->cf_attach;
    473 	softsize = ca->ca_devsize;
    474 
    475 #ifndef __BROKEN_CONFIG_UNIT_USAGE
    476 	if (cf->cf_fstate == FSTATE_STAR) {
    477 		for (myunit = cf->cf_unit; myunit < cd->cd_ndevs; myunit++)
    478 			if (cd->cd_devs[myunit] == NULL)
    479 				break;
    480 		/*
    481 		 * myunit is now the unit of the first NULL device pointer,
    482 		 * or max(cd->cd_ndevs,cf->cf_unit).
    483 		 */
    484 	} else {
    485 		myunit = cf->cf_unit;
    486 #else /* __BROKEN_CONFIG_UNIT_USAGE */
    487 	myunit = cf->cf_unit;
    488 	if (cf->cf_fstate == FSTATE_STAR)
    489 		cf->cf_unit++;
    490 	else {
    491 #endif /* __BROKEN_CONFIG_UNIT_USAGE */
    492 		KASSERT(cf->cf_fstate == FSTATE_NOTFOUND);
    493 		cf->cf_fstate = FSTATE_FOUND;
    494 	}
    495 
    496 	/* compute length of name and decimal expansion of unit number */
    497 	lname = strlen(cd->cd_name);
    498 	xunit = number(&num[sizeof(num)], myunit);
    499 	lunit = &num[sizeof(num)] - xunit;
    500 	if (lname + lunit >= sizeof(dev->dv_xname))
    501 		panic("config_attach: device name too long");
    502 
    503 	/* get memory for all device vars */
    504 	if (softsize < 0) {
    505 		/* New-style device */
    506 		if (propdev) {
    507 			/* Great, we can use the propdev. */
    508 			dev = propdev;
    509 		} else {
    510 			dev = dev_create(parent, 0, cold ? M_NOWAIT : M_WAITOK);
    511 			if (!dev)
    512 				panic("config_attach: memory allocation for device failed");
    513 		}
    514 		if (softsize < 0) softsize = -softsize;
    515 		if (softsize < sizeof(struct device)) panic("config_attach");
    516 		dev->dv_private = malloc(softsize, M_DEVBUF,
    517 					 cold ? M_NOWAIT : M_WAITOK);
    518 		if (!dev->dv_private)
    519 			panic("config_attach: memory allocation for device softc failed");
    520 		memset(dev->dv_private, 0, softsize);
    521 		dev->dv_flags |= DVF_SOFTC;
    522 	} else {
    523 		dev = (struct device *)malloc(softsize, M_DEVBUF,
    524 					      cold ? M_NOWAIT : M_WAITOK);
    525 		if (!dev)
    526 			panic("config_attach: memory allocation for device softc failed");
    527 		memset(dev, 0, softsize);
    528 		TAILQ_INSERT_TAIL(&alldevs, dev, dv_list);	/* link up */
    529 		dev->dv_private = dev;		/* Point private to ourself... */
    530 	}
    531 	dev->dv_class = cd->cd_class;
    532 	dev->dv_cfdata = cf;
    533 	dev->dv_unit = myunit;
    534 	memcpy(dev->dv_xname, cd->cd_name, lname);
    535 	memcpy(dev->dv_xname + lname, xunit, lunit);
    536 	dev->dv_parent = parent;
    537 	dev->dv_flags |= DVF_ACTIVE;	/* always initially active */
    538 	if (propdev && propdev != dev) {
    539 		/* Inherit (steal) properties from dummy device */
    540 		dev_copyprops(propdev, dev, (!cold));
    541 		dev_delprop(propdev, NULL);
    542 		/* destroy propdev */
    543 		config_detach(propdev, 0);
    544 	}
    545 
    546 	if (parent == ROOT)
    547 		printf("%s (root)", dev->dv_xname);
    548 	else {
    549 		printf("%s at %s", dev->dv_xname, parent->dv_xname);
    550 		if (print)
    551 			(void) (*print)(aux, NULL);
    552 	}
    553 
    554 	/* put this device in the devices array */
    555 	config_makeroom(dev->dv_unit, cd);
    556 	if (cd->cd_devs[dev->dv_unit])
    557 		panic("config_attach: duplicate %s", dev->dv_xname);
    558 	cd->cd_devs[dev->dv_unit] = dev;
    559 
    560 	/*
    561 	 * Before attaching, clobber any unfound devices that are
    562 	 * otherwise identical.
    563 	 */
    564 #ifdef __BROKEN_CONFIG_UNIT_USAGE
    565 	/* bump the unit number on all starred cfdata for this device. */
    566 #endif /* __BROKEN_CONFIG_UNIT_USAGE */
    567 	for (cf = cfdata; cf->cf_driver; cf++)
    568 		if (cf->cf_driver == cd && cf->cf_unit == dev->dv_unit) {
    569 			if (cf->cf_fstate == FSTATE_NOTFOUND)
    570 				cf->cf_fstate = FSTATE_FOUND;
    571 #ifdef __BROKEN_CONFIG_UNIT_USAGE
    572 			if (cf->cf_fstate == FSTATE_STAR)
    573 				cf->cf_unit++;
    574 #endif /* __BROKEN_CONFIG_UNIT_USAGE */
    575 		}
    576 #ifdef __HAVE_DEVICE_REGISTER
    577 	device_register(dev, aux);
    578 #endif
    579 	(*ca->ca_attach)(parent, dev, aux);
    580 	config_process_deferred(&deferred_config_queue, dev);
    581 	return (dev);
    582 }
    583 
    584 /*
    585  * Detach a device.  Optionally forced (e.g. because of hardware
    586  * removal) and quiet.  Returns zero if successful, non-zero
    587  * (an error code) otherwise.
    588  *
    589  * Note that this code wants to be run from a process context, so
    590  * that the detach can sleep to allow processes which have a device
    591  * open to run and unwind their stacks.
    592  */
    593 int
    594 config_detach(struct device *dev, int flags)
    595 {
    596 	struct cfdata *cf;
    597 	struct cfattach *ca;
    598 	struct cfdriver *cd;
    599 #ifdef DIAGNOSTIC
    600 	struct device *d;
    601 #endif
    602 	int rv = 0, i;
    603 
    604 	if (dev->dv_class == DV_EMPTY) {
    605 		/*
    606 		 * The device is a dummy that never fully attached.
    607 		 * Simply remove it from the global list and free it.
    608 		 */
    609 		TAILQ_REMOVE(&alldevs, dev, dv_list);
    610 		dev_delprop(dev, NULL);
    611 		if (dev->dv_flags & DVF_SOFTC)
    612 			/* Separately allocated softc */
    613 			free(dev->dv_private, M_DEVBUF);
    614 		free(dev, M_DEVBUF);
    615 		return (0);
    616 	}
    617 
    618 	cf = dev->dv_cfdata;
    619 #ifdef DIAGNOSTIC
    620 	if (cf->cf_fstate != FSTATE_FOUND && cf->cf_fstate != FSTATE_STAR)
    621 		panic("config_detach: bad device fstate");
    622 #endif
    623 	ca = cf->cf_attach;
    624 	cd = cf->cf_driver;
    625 
    626 	/*
    627 	 * Ensure the device is deactivated.  If the device doesn't
    628 	 * have an activation entry point, we allow DVF_ACTIVE to
    629 	 * remain set.  Otherwise, if DVF_ACTIVE is still set, the
    630 	 * device is busy, and the detach fails.
    631 	 */
    632 	if (ca->ca_activate != NULL)
    633 		rv = config_deactivate(dev);
    634 
    635 	/*
    636 	 * Try to detach the device.  If that's not possible, then
    637 	 * we either panic() (for the forced but failed case), or
    638 	 * return an error.
    639 	 */
    640 	if (rv == 0) {
    641 		if (ca->ca_detach != NULL)
    642 			rv = (*ca->ca_detach)(dev, flags);
    643 		else
    644 			rv = EOPNOTSUPP;
    645 	}
    646 	if (rv != 0) {
    647 		if ((flags & DETACH_FORCE) == 0)
    648 			return (rv);
    649 		else
    650 			panic("config_detach: forced detach of %s failed (%d)",
    651 			      dev->dv_xname, rv);
    652 	}
    653 
    654 	/*
    655 	 * The device has now been successfully detached.
    656 	 */
    657 
    658 #ifdef DIAGNOSTIC
    659 	/*
    660 	 * Sanity: If you're successfully detached, you should have no
    661 	 * children.  (Note that because children must be attached
    662 	 * after parents, we only need to search the latter part of
    663 	 * the list.)
    664 	 */
    665 	for (d = TAILQ_NEXT(dev, dv_list); d != NULL;
    666 	     d = TAILQ_NEXT(d, dv_list)) {
    667 		if (d->dv_parent == dev) {
    668 			printf("config_detach: detached device %s"
    669 			       " has children %s\n", dev->dv_xname, d->dv_xname);
    670 			panic("config_detach");
    671 		}
    672 	}
    673 #endif
    674 
    675 	/*
    676 	 * Mark cfdata to show that the unit can be reused, if possible.
    677 	 */
    678 #ifdef __BROKEN_CONFIG_UNIT_USAGE
    679 	/*
    680 	 * Note that we can only re-use a starred unit number if the unit
    681 	 * being detached had the last assigned unit number.
    682 	 */
    683 #endif /* __BROKEN_CONFIG_UNIT_USAGE */
    684 	for (cf = cfdata; cf->cf_driver; cf++) {
    685 		if (cf->cf_driver == cd) {
    686 			if (cf->cf_fstate == FSTATE_FOUND &&
    687 			    cf->cf_unit == dev->dv_unit)
    688 				cf->cf_fstate = FSTATE_NOTFOUND;
    689 #ifdef __BROKEN_CONFIG_UNIT_USAGE
    690 			if (cf->cf_fstate == FSTATE_STAR &&
    691 			    cf->cf_unit == dev->dv_unit + 1)
    692 				cf->cf_unit--;
    693 #endif /* __BROKEN_CONFIG_UNIT_USAGE */
    694 		}
    695 	}
    696 
    697 	/*
    698 	 * Unlink from device list.
    699 	 */
    700 	TAILQ_REMOVE(&alldevs, dev, dv_list);
    701 
    702 	/*
    703 	 * Remove from cfdriver's array, tell the world, and free softc.
    704 	 */
    705 	if (cd) {
    706 		cd->cd_devs[dev->dv_unit] = NULL;
    707 		if ((flags & DETACH_QUIET) == 0)
    708 			printf("%s detached\n", dev->dv_xname);
    709 	}
    710 	dev_delprop(dev, NULL);
    711 	if (dev->dv_flags & DVF_SOFTC)
    712 		/* Separately allocated softc */
    713 		free(dev->dv_private, M_DEVBUF);
    714 	free(dev, M_DEVBUF);
    715 
    716 	/*
    717 	 * If the device now has no units in use, deallocate its softc array.
    718 	 */
    719 	for (i = 0; i < cd->cd_ndevs; i++)
    720 		if (cd->cd_devs[i] != NULL)
    721 			break;
    722 	if (i == cd->cd_ndevs) {		/* nothing found; deallocate */
    723 		free(cd->cd_devs, M_DEVBUF);
    724 		cd->cd_devs = NULL;
    725 		cd->cd_ndevs = 0;
    726 	}
    727 
    728 	/*
    729 	 * Return success.
    730 	 */
    731 	return (0);
    732 }
    733 
    734 int
    735 config_activate(struct device *dev)
    736 {
    737 	struct cfattach *ca = dev->dv_cfdata->cf_attach;
    738 	int rv = 0, oflags = dev->dv_flags;
    739 
    740 	if (ca->ca_activate == NULL)
    741 		return (EOPNOTSUPP);
    742 
    743 	if ((dev->dv_flags & DVF_ACTIVE) == 0) {
    744 		dev->dv_flags |= DVF_ACTIVE;
    745 		rv = (*ca->ca_activate)(dev, DVACT_ACTIVATE);
    746 		if (rv)
    747 			dev->dv_flags = oflags;
    748 	}
    749 	return (rv);
    750 }
    751 
    752 int
    753 config_deactivate(struct device *dev)
    754 {
    755 	struct cfattach *ca = dev->dv_cfdata->cf_attach;
    756 	int rv = 0, oflags = dev->dv_flags;
    757 
    758 	if (ca->ca_activate == NULL)
    759 		return (EOPNOTSUPP);
    760 
    761 	if (dev->dv_flags & DVF_ACTIVE) {
    762 		dev->dv_flags &= ~DVF_ACTIVE;
    763 		rv = (*ca->ca_activate)(dev, DVACT_DEACTIVATE);
    764 		if (rv)
    765 			dev->dv_flags = oflags;
    766 	}
    767 	return (rv);
    768 }
    769 
    770 /*
    771  * Defer the configuration of the specified device until all
    772  * of its parent's devices have been attached.
    773  */
    774 void
    775 config_defer(struct device *dev, void (*func)(struct device *))
    776 {
    777 	struct deferred_config *dc;
    778 
    779 	if (dev->dv_parent == NULL)
    780 		panic("config_defer: can't defer config of a root device");
    781 
    782 #ifdef DIAGNOSTIC
    783 	for (dc = TAILQ_FIRST(&deferred_config_queue); dc != NULL;
    784 	     dc = TAILQ_NEXT(dc, dc_queue)) {
    785 		if (dc->dc_dev == dev)
    786 			panic("config_defer: deferred twice");
    787 	}
    788 #endif
    789 
    790 	dc = malloc(sizeof(*dc), M_DEVBUF, cold ? M_NOWAIT : M_WAITOK);
    791 	if (dc == NULL)
    792 		panic("config_defer: unable to allocate callback");
    793 
    794 	dc->dc_dev = dev;
    795 	dc->dc_func = func;
    796 	TAILQ_INSERT_TAIL(&deferred_config_queue, dc, dc_queue);
    797 	config_pending_incr();
    798 }
    799 
    800 /*
    801  * Defer some autoconfiguration for a device until after interrupts
    802  * are enabled.
    803  */
    804 void
    805 config_interrupts(struct device *dev, void (*func)(struct device *))
    806 {
    807 	struct deferred_config *dc;
    808 
    809 	/*
    810 	 * If interrupts are enabled, callback now.
    811 	 */
    812 	if (cold == 0) {
    813 		(*func)(dev);
    814 		return;
    815 	}
    816 
    817 #ifdef DIAGNOSTIC
    818 	for (dc = TAILQ_FIRST(&interrupt_config_queue); dc != NULL;
    819 	     dc = TAILQ_NEXT(dc, dc_queue)) {
    820 		if (dc->dc_dev == dev)
    821 			panic("config_interrupts: deferred twice");
    822 	}
    823 #endif
    824 
    825 	dc = malloc(sizeof(*dc), M_DEVBUF, cold ? M_NOWAIT : M_WAITOK);
    826 	if (dc == NULL)
    827 		panic("config_interrupts: unable to allocate callback");
    828 
    829 	dc->dc_dev = dev;
    830 	dc->dc_func = func;
    831 	TAILQ_INSERT_TAIL(&interrupt_config_queue, dc, dc_queue);
    832 	config_pending_incr();
    833 }
    834 
    835 /*
    836  * Process a deferred configuration queue.
    837  */
    838 static void
    839 config_process_deferred(struct deferred_config_head *queue,
    840     struct device *parent)
    841 {
    842 	struct deferred_config *dc, *ndc;
    843 
    844 	for (dc = TAILQ_FIRST(queue); dc != NULL; dc = ndc) {
    845 		ndc = TAILQ_NEXT(dc, dc_queue);
    846 		if (parent == NULL || dc->dc_dev->dv_parent == parent) {
    847 			TAILQ_REMOVE(queue, dc, dc_queue);
    848 			(*dc->dc_func)(dc->dc_dev);
    849 			free(dc, M_DEVBUF);
    850 			config_pending_decr();
    851 		}
    852 	}
    853 }
    854 
    855 /*
    856  * Manipulate the config_pending semaphore.
    857  */
    858 void
    859 config_pending_incr(void)
    860 {
    861 
    862 	config_pending++;
    863 }
    864 
    865 void
    866 config_pending_decr(void)
    867 {
    868 
    869 #ifdef DIAGNOSTIC
    870 	if (config_pending == 0)
    871 		panic("config_pending_decr: config_pending == 0");
    872 #endif
    873 	config_pending--;
    874 	if (config_pending == 0)
    875 		wakeup((void *)&config_pending);
    876 }
    877 
    878 /*
    879  * Attach a statically-initialized event.  The type and string pointers
    880  * are already set up.
    881  */
    882 void
    883 evcnt_attach_static(struct evcnt *ev)
    884 {
    885 	int len;
    886 
    887 	len = strlen(ev->ev_group);
    888 #ifdef DIAGNOSTIC
    889 	if (len >= EVCNT_STRING_MAX)		/* ..._MAX includes NUL */
    890 		panic("evcnt_attach_static: group length (%s)", ev->ev_group);
    891 #endif
    892 	ev->ev_grouplen = len;
    893 
    894 	len = strlen(ev->ev_name);
    895 #ifdef DIAGNOSTIC
    896 	if (len >= EVCNT_STRING_MAX)		/* ..._MAX includes NUL */
    897 		panic("evcnt_attach_static: name length (%s)", ev->ev_name);
    898 #endif
    899 	ev->ev_namelen = len;
    900 
    901 	TAILQ_INSERT_TAIL(&allevents, ev, ev_list);
    902 }
    903 
    904 /*
    905  * Attach a dynamically-initialized event.  Zero it, set up the type
    906  * and string pointers and then act like it was statically initialized.
    907  */
    908 void
    909 evcnt_attach_dynamic(struct evcnt *ev, int type, const struct evcnt *parent,
    910     const char *group, const char *name)
    911 {
    912 
    913 	memset(ev, 0, sizeof *ev);
    914 	ev->ev_type = type;
    915 	ev->ev_parent = parent;
    916 	ev->ev_group = group;
    917 	ev->ev_name = name;
    918 	evcnt_attach_static(ev);
    919 }
    920 
    921 /*
    922  * Detach an event.
    923  */
    924 void
    925 evcnt_detach(struct evcnt *ev)
    926 {
    927 
    928 	TAILQ_REMOVE(&allevents, ev, ev_list);
    929 }
    930 
    931 /*
    932  * Device property management routines.
    933  */
    934 #ifdef DEBUG
    935 int devprop_debug = 0;
    936 #endif
    937 
    938 /*
    939  * Create a dummy device you can attach properties to.
    940  */
    941 struct device *
    942 dev_config_create(struct device *parent, int wait)
    943 {
    944 	struct device *dev;
    945 
    946 	dev = dev_create(parent, 0, wait ? M_WAITOK : M_NOWAIT);
    947 	return (dev);
    948 }
    949 
    950 
    951 int
    952 dev_setprop(struct device *dev, const char *name, void *val,
    953 			size_t len, int type, int wait)
    954 {
    955 #ifdef DEBUG
    956 	if (devprop_debug)
    957 		printf("dev_setprop(%p, %s, %p %s, %ld, %x, %d)\n",
    958 		       dev, name, val, (PROP_TYPE(type) == PROP_STRING) ?
    959 		       (char *)val : "", len, type, wait);
    960 #endif
    961 
    962 	return (prop_set(devpropdb, dev, name, val, len, type, wait));
    963 }
    964 
    965 size_t
    966 dev_getprop(struct device *dev, const char *name, void *val,
    967 			size_t len, int *type, int search)
    968 {
    969 	ssize_t rv;
    970 
    971 #ifdef DEBUG
    972 	if (devprop_debug) {
    973 		printf("dev_getprop(%p, %s, %p, %ld, %p, %d)\n",
    974 		       dev, name, val, len, type, search);
    975 	}
    976 #endif
    977 	rv = prop_get(devpropdb, dev, name, val, len, type);
    978 	if (rv == -1) {
    979 		/* Not found -- try md_getprop */
    980 		rv = dev_mdgetprop(dev->dv_parent, name, val,
    981 			len, type);
    982 	}
    983 	if ((rv == -1) && search) {
    984 		if (dev->dv_parent)
    985 			/* Tail recursion -- there should be no stack growth. */
    986 			return (dev_getprop(dev->dv_parent, name,
    987 					    val, len, type, search));
    988 	}
    989 #ifdef DEBUG
    990 	if (devprop_debug && (rv == -1)) {
    991 		printf("%s no found\n", name);
    992 	}
    993 #endif
    994 	return (rv);
    995 }
    996 
    997 int
    998 dev_delprop(struct device *dev, const char *name)
    999 {
   1000 
   1001 #ifdef DEBUG_N
   1002 	if (devprop_debug)
   1003 		printf("dev_delprop(%p, %s, %x)\n", dev, name);
   1004 #endif
   1005 	return (prop_delete(devpropdb, dev, name));
   1006 }
   1007 
   1008 
   1009 int
   1010 dev_copyprops(struct device *src, struct device *dest, int wait)
   1011 {
   1012 	return (prop_copy(devpropdb, src, dest, wait));
   1013 }
   1014 
   1015 #ifdef DDB
   1016 void
   1017 event_print(int full, void (*pr)(const char *, ...))
   1018 {
   1019 	struct evcnt *evp;
   1020 
   1021 	TAILQ_FOREACH(evp, &allevents, ev_list) {
   1022 		if (evp->ev_count == 0 && !full)
   1023 			continue;
   1024 
   1025 		(*pr)("evcnt type %d: %s %s = %lld\n", evp->ev_type,
   1026 		    evp->ev_group, evp->ev_name, evp->ev_count);
   1027 	}
   1028 }
   1029 #endif /* DDB */
   1030