xref: /netbsd-src/sys/kern/subr_autoconf.c (revision 267197ec1eebfcb9810ea27a89625b6ddf68e3e7)
1 /* $NetBSD: subr_autoconf.c,v 1.131 2008/02/12 17:30:59 joerg Exp $ */
2 
3 /*
4  * Copyright (c) 1996, 2000 Christopher G. Demetriou
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. All advertising materials mentioning features or use of this software
16  *    must display the following acknowledgement:
17  *          This product includes software developed for the
18  *          NetBSD Project.  See http://www.NetBSD.org/ for
19  *          information about NetBSD.
20  * 4. The name of the author may not be used to endorse or promote products
21  *    derived from this software without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
24  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
25  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
26  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
27  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
28  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
30  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
32  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33  *
34  * --(license Id: LICENSE.proto,v 1.1 2000/06/13 21:40:26 cgd Exp )--
35  */
36 
37 /*
38  * Copyright (c) 1992, 1993
39  *	The Regents of the University of California.  All rights reserved.
40  *
41  * This software was developed by the Computer Systems Engineering group
42  * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
43  * contributed to Berkeley.
44  *
45  * All advertising materials mentioning features or use of this software
46  * must display the following acknowledgement:
47  *	This product includes software developed by the University of
48  *	California, Lawrence Berkeley Laboratories.
49  *
50  * Redistribution and use in source and binary forms, with or without
51  * modification, are permitted provided that the following conditions
52  * are met:
53  * 1. Redistributions of source code must retain the above copyright
54  *    notice, this list of conditions and the following disclaimer.
55  * 2. Redistributions in binary form must reproduce the above copyright
56  *    notice, this list of conditions and the following disclaimer in the
57  *    documentation and/or other materials provided with the distribution.
58  * 3. Neither the name of the University nor the names of its contributors
59  *    may be used to endorse or promote products derived from this software
60  *    without specific prior written permission.
61  *
62  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
63  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
64  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
65  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
66  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
67  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
68  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
69  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
70  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
71  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
72  * SUCH DAMAGE.
73  *
74  * from: Header: subr_autoconf.c,v 1.12 93/02/01 19:31:48 torek Exp  (LBL)
75  *
76  *	@(#)subr_autoconf.c	8.3 (Berkeley) 5/17/94
77  */
78 
79 #include <sys/cdefs.h>
80 __KERNEL_RCSID(0, "$NetBSD: subr_autoconf.c,v 1.131 2008/02/12 17:30:59 joerg Exp $");
81 
82 #include "opt_multiprocessor.h"
83 #include "opt_ddb.h"
84 
85 #include <sys/param.h>
86 #include <sys/device.h>
87 #include <sys/disklabel.h>
88 #include <sys/conf.h>
89 #include <sys/kauth.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/reboot.h>
96 
97 #include <sys/buf.h>
98 #include <sys/dirent.h>
99 #include <sys/vnode.h>
100 #include <sys/mount.h>
101 #include <sys/namei.h>
102 #include <sys/unistd.h>
103 #include <sys/fcntl.h>
104 #include <sys/lockf.h>
105 #include <sys/callout.h>
106 
107 #include <sys/disk.h>
108 
109 #include <machine/limits.h>
110 
111 #include "opt_userconf.h"
112 #ifdef USERCONF
113 #include <sys/userconf.h>
114 #endif
115 
116 #ifdef __i386__
117 #include "opt_splash.h"
118 #if defined(SPLASHSCREEN) && defined(SPLASHSCREEN_PROGRESS)
119 #include <dev/splash/splash.h>
120 extern struct splash_progress *splash_progress_state;
121 #endif
122 #endif
123 
124 /*
125  * Autoconfiguration subroutines.
126  */
127 
128 /*
129  * ioconf.c exports exactly two names: cfdata and cfroots.  All system
130  * devices and drivers are found via these tables.
131  */
132 extern struct cfdata cfdata[];
133 extern const short cfroots[];
134 
135 /*
136  * List of all cfdriver structures.  We use this to detect duplicates
137  * when other cfdrivers are loaded.
138  */
139 struct cfdriverlist allcfdrivers = LIST_HEAD_INITIALIZER(&allcfdrivers);
140 extern struct cfdriver * const cfdriver_list_initial[];
141 
142 /*
143  * Initial list of cfattach's.
144  */
145 extern const struct cfattachinit cfattachinit[];
146 
147 /*
148  * List of cfdata tables.  We always have one such list -- the one
149  * built statically when the kernel was configured.
150  */
151 struct cftablelist allcftables = TAILQ_HEAD_INITIALIZER(allcftables);
152 static struct cftable initcftable;
153 
154 #define	ROOT ((device_t)NULL)
155 
156 struct matchinfo {
157 	cfsubmatch_t fn;
158 	struct	device *parent;
159 	const int *locs;
160 	void	*aux;
161 	struct	cfdata *match;
162 	int	pri;
163 };
164 
165 static char *number(char *, int);
166 static void mapply(struct matchinfo *, cfdata_t);
167 static device_t config_devalloc(const device_t, const cfdata_t, const int *);
168 static void config_devdealloc(device_t);
169 static void config_makeroom(int, struct cfdriver *);
170 static void config_devlink(device_t);
171 static void config_devunlink(device_t);
172 
173 struct deferred_config {
174 	TAILQ_ENTRY(deferred_config) dc_queue;
175 	device_t dc_dev;
176 	void (*dc_func)(device_t);
177 };
178 
179 TAILQ_HEAD(deferred_config_head, deferred_config);
180 
181 struct deferred_config_head deferred_config_queue =
182 	TAILQ_HEAD_INITIALIZER(deferred_config_queue);
183 struct deferred_config_head interrupt_config_queue =
184 	TAILQ_HEAD_INITIALIZER(interrupt_config_queue);
185 
186 static void config_process_deferred(struct deferred_config_head *, device_t);
187 
188 /* Hooks to finalize configuration once all real devices have been found. */
189 struct finalize_hook {
190 	TAILQ_ENTRY(finalize_hook) f_list;
191 	int (*f_func)(device_t);
192 	device_t f_dev;
193 };
194 static TAILQ_HEAD(, finalize_hook) config_finalize_list =
195 	TAILQ_HEAD_INITIALIZER(config_finalize_list);
196 static int config_finalize_done;
197 
198 /* list of all devices */
199 struct devicelist alldevs = TAILQ_HEAD_INITIALIZER(alldevs);
200 
201 volatile int config_pending;		/* semaphore for mountroot */
202 
203 #define	STREQ(s1, s2)			\
204 	(*(s1) == *(s2) && strcmp((s1), (s2)) == 0)
205 
206 static int config_initialized;		/* config_init() has been called. */
207 
208 static int config_do_twiddle;
209 
210 struct vnode *
211 opendisk(struct device *dv)
212 {
213 	int bmajor, bminor;
214 	struct vnode *tmpvn;
215 	int error;
216 	dev_t dev;
217 
218 	/*
219 	 * Lookup major number for disk block device.
220 	 */
221 	bmajor = devsw_name2blk(device_xname(dv), NULL, 0);
222 	if (bmajor == -1)
223 		return NULL;
224 
225 	bminor = minor(device_unit(dv));
226 	/*
227 	 * Fake a temporary vnode for the disk, open it, and read
228 	 * and hash the sectors.
229 	 */
230 	dev = device_is_a(dv, "dk") ? makedev(bmajor, bminor) :
231 	    MAKEDISKDEV(bmajor, bminor, RAW_PART);
232 	if (bdevvp(dev, &tmpvn))
233 		panic("%s: can't alloc vnode for %s", __func__,
234 		    device_xname(dv));
235 	error = VOP_OPEN(tmpvn, FREAD, NOCRED);
236 	if (error) {
237 #ifndef DEBUG
238 		/*
239 		 * Ignore errors caused by missing device, partition,
240 		 * or medium.
241 		 */
242 		if (error != ENXIO && error != ENODEV)
243 #endif
244 			printf("%s: can't open dev %s (%d)\n",
245 			    __func__, device_xname(dv), error);
246 		vput(tmpvn);
247 		return NULL;
248 	}
249 
250 	return tmpvn;
251 }
252 
253 int
254 config_handle_wedges(struct device *dv, int par)
255 {
256 	struct dkwedge_list wl;
257 	struct dkwedge_info *wi;
258 	struct vnode *vn;
259 	char diskname[16];
260 	int i, error;
261 
262 	if ((vn = opendisk(dv)) == NULL)
263 		return -1;
264 
265 	wl.dkwl_bufsize = sizeof(*wi) * 16;
266 	wl.dkwl_buf = wi = malloc(wl.dkwl_bufsize, M_TEMP, M_WAITOK);
267 
268 	error = VOP_IOCTL(vn, DIOCLWEDGES, &wl, FREAD, NOCRED);
269 	VOP_CLOSE(vn, FREAD, NOCRED);
270 	vput(vn);
271 	if (error) {
272 #ifdef DEBUG_WEDGE
273 		printf("%s: List wedges returned %d\n",
274 		    device_xname(dv), error);
275 #endif
276 		free(wi, M_TEMP);
277 		return -1;
278 	}
279 
280 #ifdef DEBUG_WEDGE
281 	printf("%s: Returned %u(%u) wedges\n", device_xname(dv),
282 	    wl.dkwl_nwedges, wl.dkwl_ncopied);
283 #endif
284 	snprintf(diskname, sizeof(diskname), "%s%c", device_xname(dv),
285 	    par + 'a');
286 
287 	for (i = 0; i < wl.dkwl_ncopied; i++) {
288 #ifdef DEBUG_WEDGE
289 		printf("%s: Looking for %s in %s\n",
290 		    device_xname(dv), diskname, wi[i].dkw_wname);
291 #endif
292 		if (strcmp(wi[i].dkw_wname, diskname) == 0)
293 			break;
294 	}
295 
296 	if (i == wl.dkwl_ncopied) {
297 #ifdef DEBUG_WEDGE
298 		printf("%s: Cannot find wedge with parent %s\n",
299 		    device_xname(dv), diskname);
300 #endif
301 		free(wi, M_TEMP);
302 		return -1;
303 	}
304 
305 #ifdef DEBUG_WEDGE
306 	printf("%s: Setting boot wedge %s (%s) at %llu %llu\n",
307 		device_xname(dv), wi[i].dkw_devname, wi[i].dkw_wname,
308 		(unsigned long long)wi[i].dkw_offset,
309 		(unsigned long long)wi[i].dkw_size);
310 #endif
311 	dkwedge_set_bootwedge(dv, wi[i].dkw_offset, wi[i].dkw_size);
312 	free(wi, M_TEMP);
313 	return 0;
314 }
315 
316 /*
317  * Initialize the autoconfiguration data structures.  Normally this
318  * is done by configure(), but some platforms need to do this very
319  * early (to e.g. initialize the console).
320  */
321 void
322 config_init(void)
323 {
324 	const struct cfattachinit *cfai;
325 	int i, j;
326 
327 	if (config_initialized)
328 		return;
329 
330 	/* allcfdrivers is statically initialized. */
331 	for (i = 0; cfdriver_list_initial[i] != NULL; i++) {
332 		if (config_cfdriver_attach(cfdriver_list_initial[i]) != 0)
333 			panic("configure: duplicate `%s' drivers",
334 			    cfdriver_list_initial[i]->cd_name);
335 	}
336 
337 	for (cfai = &cfattachinit[0]; cfai->cfai_name != NULL; cfai++) {
338 		for (j = 0; cfai->cfai_list[j] != NULL; j++) {
339 			if (config_cfattach_attach(cfai->cfai_name,
340 						   cfai->cfai_list[j]) != 0)
341 				panic("configure: duplicate `%s' attachment "
342 				    "of `%s' driver",
343 				    cfai->cfai_list[j]->ca_name,
344 				    cfai->cfai_name);
345 		}
346 	}
347 
348 	initcftable.ct_cfdata = cfdata;
349 	TAILQ_INSERT_TAIL(&allcftables, &initcftable, ct_list);
350 
351 	config_initialized = 1;
352 }
353 
354 void
355 config_deferred(device_t dev)
356 {
357 	config_process_deferred(&deferred_config_queue, dev);
358 	config_process_deferred(&interrupt_config_queue, dev);
359 }
360 
361 /*
362  * Configure the system's hardware.
363  */
364 void
365 configure(void)
366 {
367 	int errcnt;
368 
369 	/* Initialize data structures. */
370 	config_init();
371 	pmf_init();
372 
373 #ifdef USERCONF
374 	if (boothowto & RB_USERCONF)
375 		user_config();
376 #endif
377 
378 	if ((boothowto & (AB_SILENT|AB_VERBOSE)) == AB_SILENT) {
379 		config_do_twiddle = 1;
380 		printf_nolog("Detecting hardware...");
381 	}
382 
383 	/*
384 	 * Do the machine-dependent portion of autoconfiguration.  This
385 	 * sets the configuration machinery here in motion by "finding"
386 	 * the root bus.  When this function returns, we expect interrupts
387 	 * to be enabled.
388 	 */
389 	cpu_configure();
390 
391 	/* Initialize callouts, part 2. */
392 	callout_startup2();
393 
394 	/*
395 	 * Now that we've found all the hardware, start the real time
396 	 * and statistics clocks.
397 	 */
398 	initclocks();
399 
400 	cold = 0;	/* clocks are running, we're warm now! */
401 
402 	/* Boot the secondary processors. */
403 	mp_online = true;
404 #if defined(MULTIPROCESSOR)
405 	cpu_boot_secondary_processors();
406 #endif
407 
408 	/*
409 	 * Now callback to finish configuration for devices which want
410 	 * to do this once interrupts are enabled.
411 	 */
412 	config_process_deferred(&interrupt_config_queue, NULL);
413 
414 	errcnt = aprint_get_error_count();
415 	if ((boothowto & (AB_QUIET|AB_SILENT)) != 0 &&
416 	    (boothowto & AB_VERBOSE) == 0) {
417 		if (config_do_twiddle) {
418 			config_do_twiddle = 0;
419 			printf_nolog("done.\n");
420 		}
421 		if (errcnt != 0) {
422 			printf("WARNING: %d error%s while detecting hardware; "
423 			    "check system log.\n", errcnt,
424 			    errcnt == 1 ? "" : "s");
425 		}
426 	}
427 }
428 
429 /*
430  * Add a cfdriver to the system.
431  */
432 int
433 config_cfdriver_attach(struct cfdriver *cd)
434 {
435 	struct cfdriver *lcd;
436 
437 	/* Make sure this driver isn't already in the system. */
438 	LIST_FOREACH(lcd, &allcfdrivers, cd_list) {
439 		if (STREQ(lcd->cd_name, cd->cd_name))
440 			return (EEXIST);
441 	}
442 
443 	LIST_INIT(&cd->cd_attach);
444 	LIST_INSERT_HEAD(&allcfdrivers, cd, cd_list);
445 
446 	return (0);
447 }
448 
449 /*
450  * Remove a cfdriver from the system.
451  */
452 int
453 config_cfdriver_detach(struct cfdriver *cd)
454 {
455 	int i;
456 
457 	/* Make sure there are no active instances. */
458 	for (i = 0; i < cd->cd_ndevs; i++) {
459 		if (cd->cd_devs[i] != NULL)
460 			return (EBUSY);
461 	}
462 
463 	/* ...and no attachments loaded. */
464 	if (LIST_EMPTY(&cd->cd_attach) == 0)
465 		return (EBUSY);
466 
467 	LIST_REMOVE(cd, cd_list);
468 
469 	KASSERT(cd->cd_devs == NULL);
470 
471 	return (0);
472 }
473 
474 /*
475  * Look up a cfdriver by name.
476  */
477 struct cfdriver *
478 config_cfdriver_lookup(const char *name)
479 {
480 	struct cfdriver *cd;
481 
482 	LIST_FOREACH(cd, &allcfdrivers, cd_list) {
483 		if (STREQ(cd->cd_name, name))
484 			return (cd);
485 	}
486 
487 	return (NULL);
488 }
489 
490 /*
491  * Add a cfattach to the specified driver.
492  */
493 int
494 config_cfattach_attach(const char *driver, struct cfattach *ca)
495 {
496 	struct cfattach *lca;
497 	struct cfdriver *cd;
498 
499 	cd = config_cfdriver_lookup(driver);
500 	if (cd == NULL)
501 		return (ESRCH);
502 
503 	/* Make sure this attachment isn't already on this driver. */
504 	LIST_FOREACH(lca, &cd->cd_attach, ca_list) {
505 		if (STREQ(lca->ca_name, ca->ca_name))
506 			return (EEXIST);
507 	}
508 
509 	LIST_INSERT_HEAD(&cd->cd_attach, ca, ca_list);
510 
511 	return (0);
512 }
513 
514 /*
515  * Remove a cfattach from the specified driver.
516  */
517 int
518 config_cfattach_detach(const char *driver, struct cfattach *ca)
519 {
520 	struct cfdriver *cd;
521 	device_t dev;
522 	int i;
523 
524 	cd = config_cfdriver_lookup(driver);
525 	if (cd == NULL)
526 		return (ESRCH);
527 
528 	/* Make sure there are no active instances. */
529 	for (i = 0; i < cd->cd_ndevs; i++) {
530 		if ((dev = cd->cd_devs[i]) == NULL)
531 			continue;
532 		if (dev->dv_cfattach == ca)
533 			return (EBUSY);
534 	}
535 
536 	LIST_REMOVE(ca, ca_list);
537 
538 	return (0);
539 }
540 
541 /*
542  * Look up a cfattach by name.
543  */
544 static struct cfattach *
545 config_cfattach_lookup_cd(struct cfdriver *cd, const char *atname)
546 {
547 	struct cfattach *ca;
548 
549 	LIST_FOREACH(ca, &cd->cd_attach, ca_list) {
550 		if (STREQ(ca->ca_name, atname))
551 			return (ca);
552 	}
553 
554 	return (NULL);
555 }
556 
557 /*
558  * Look up a cfattach by driver/attachment name.
559  */
560 struct cfattach *
561 config_cfattach_lookup(const char *name, const char *atname)
562 {
563 	struct cfdriver *cd;
564 
565 	cd = config_cfdriver_lookup(name);
566 	if (cd == NULL)
567 		return (NULL);
568 
569 	return (config_cfattach_lookup_cd(cd, atname));
570 }
571 
572 /*
573  * Apply the matching function and choose the best.  This is used
574  * a few times and we want to keep the code small.
575  */
576 static void
577 mapply(struct matchinfo *m, cfdata_t cf)
578 {
579 	int pri;
580 
581 	if (m->fn != NULL) {
582 		pri = (*m->fn)(m->parent, cf, m->locs, m->aux);
583 	} else {
584 		pri = config_match(m->parent, cf, m->aux);
585 	}
586 	if (pri > m->pri) {
587 		m->match = cf;
588 		m->pri = pri;
589 	}
590 }
591 
592 int
593 config_stdsubmatch(device_t parent, cfdata_t cf, const int *locs, void *aux)
594 {
595 	const struct cfiattrdata *ci;
596 	const struct cflocdesc *cl;
597 	int nlocs, i;
598 
599 	ci = cfiattr_lookup(cf->cf_pspec->cfp_iattr, parent->dv_cfdriver);
600 	KASSERT(ci);
601 	nlocs = ci->ci_loclen;
602 	for (i = 0; i < nlocs; i++) {
603 		cl = &ci->ci_locdesc[i];
604 		/* !cld_defaultstr means no default value */
605 		if ((!(cl->cld_defaultstr)
606 		     || (cf->cf_loc[i] != cl->cld_default))
607 		    && cf->cf_loc[i] != locs[i])
608 			return (0);
609 	}
610 
611 	return (config_match(parent, cf, aux));
612 }
613 
614 /*
615  * Helper function: check whether the driver supports the interface attribute
616  * and return its descriptor structure.
617  */
618 static const struct cfiattrdata *
619 cfdriver_get_iattr(const struct cfdriver *cd, const char *ia)
620 {
621 	const struct cfiattrdata * const *cpp;
622 
623 	if (cd->cd_attrs == NULL)
624 		return (0);
625 
626 	for (cpp = cd->cd_attrs; *cpp; cpp++) {
627 		if (STREQ((*cpp)->ci_name, ia)) {
628 			/* Match. */
629 			return (*cpp);
630 		}
631 	}
632 	return (0);
633 }
634 
635 /*
636  * Lookup an interface attribute description by name.
637  * If the driver is given, consider only its supported attributes.
638  */
639 const struct cfiattrdata *
640 cfiattr_lookup(const char *name, const struct cfdriver *cd)
641 {
642 	const struct cfdriver *d;
643 	const struct cfiattrdata *ia;
644 
645 	if (cd)
646 		return (cfdriver_get_iattr(cd, name));
647 
648 	LIST_FOREACH(d, &allcfdrivers, cd_list) {
649 		ia = cfdriver_get_iattr(d, name);
650 		if (ia)
651 			return (ia);
652 	}
653 	return (0);
654 }
655 
656 /*
657  * Determine if `parent' is a potential parent for a device spec based
658  * on `cfp'.
659  */
660 static int
661 cfparent_match(const device_t parent, const struct cfparent *cfp)
662 {
663 	struct cfdriver *pcd;
664 
665 	/* We don't match root nodes here. */
666 	if (cfp == NULL)
667 		return (0);
668 
669 	pcd = parent->dv_cfdriver;
670 	KASSERT(pcd != NULL);
671 
672 	/*
673 	 * First, ensure this parent has the correct interface
674 	 * attribute.
675 	 */
676 	if (!cfdriver_get_iattr(pcd, cfp->cfp_iattr))
677 		return (0);
678 
679 	/*
680 	 * If no specific parent device instance was specified (i.e.
681 	 * we're attaching to the attribute only), we're done!
682 	 */
683 	if (cfp->cfp_parent == NULL)
684 		return (1);
685 
686 	/*
687 	 * Check the parent device's name.
688 	 */
689 	if (STREQ(pcd->cd_name, cfp->cfp_parent) == 0)
690 		return (0);	/* not the same parent */
691 
692 	/*
693 	 * Make sure the unit number matches.
694 	 */
695 	if (cfp->cfp_unit == DVUNIT_ANY ||	/* wildcard */
696 	    cfp->cfp_unit == parent->dv_unit)
697 		return (1);
698 
699 	/* Unit numbers don't match. */
700 	return (0);
701 }
702 
703 /*
704  * Helper for config_cfdata_attach(): check all devices whether it could be
705  * parent any attachment in the config data table passed, and rescan.
706  */
707 static void
708 rescan_with_cfdata(const struct cfdata *cf)
709 {
710 	device_t d;
711 	const struct cfdata *cf1;
712 
713 	/*
714 	 * "alldevs" is likely longer than an LKM's cfdata, so make it
715 	 * the outer loop.
716 	 */
717 	TAILQ_FOREACH(d, &alldevs, dv_list) {
718 
719 		if (!(d->dv_cfattach->ca_rescan))
720 			continue;
721 
722 		for (cf1 = cf; cf1->cf_name; cf1++) {
723 
724 			if (!cfparent_match(d, cf1->cf_pspec))
725 				continue;
726 
727 			(*d->dv_cfattach->ca_rescan)(d,
728 				cf1->cf_pspec->cfp_iattr, cf1->cf_loc);
729 		}
730 	}
731 }
732 
733 /*
734  * Attach a supplemental config data table and rescan potential
735  * parent devices if required.
736  */
737 int
738 config_cfdata_attach(cfdata_t cf, int scannow)
739 {
740 	struct cftable *ct;
741 
742 	ct = malloc(sizeof(struct cftable), M_DEVBUF, M_WAITOK);
743 	ct->ct_cfdata = cf;
744 	TAILQ_INSERT_TAIL(&allcftables, ct, ct_list);
745 
746 	if (scannow)
747 		rescan_with_cfdata(cf);
748 
749 	return (0);
750 }
751 
752 /*
753  * Helper for config_cfdata_detach: check whether a device is
754  * found through any attachment in the config data table.
755  */
756 static int
757 dev_in_cfdata(const struct device *d, const struct cfdata *cf)
758 {
759 	const struct cfdata *cf1;
760 
761 	for (cf1 = cf; cf1->cf_name; cf1++)
762 		if (d->dv_cfdata == cf1)
763 			return (1);
764 
765 	return (0);
766 }
767 
768 /*
769  * Detach a supplemental config data table. Detach all devices found
770  * through that table (and thus keeping references to it) before.
771  */
772 int
773 config_cfdata_detach(cfdata_t cf)
774 {
775 	device_t d;
776 	int error;
777 	struct cftable *ct;
778 
779 again:
780 	TAILQ_FOREACH(d, &alldevs, dv_list) {
781 		if (dev_in_cfdata(d, cf)) {
782 			error = config_detach(d, 0);
783 			if (error) {
784 				aprint_error("%s: unable to detach instance\n",
785 					d->dv_xname);
786 				return (error);
787 			}
788 			goto again;
789 		}
790 	}
791 
792 	TAILQ_FOREACH(ct, &allcftables, ct_list) {
793 		if (ct->ct_cfdata == cf) {
794 			TAILQ_REMOVE(&allcftables, ct, ct_list);
795 			free(ct, M_DEVBUF);
796 			return (0);
797 		}
798 	}
799 
800 	/* not found -- shouldn't happen */
801 	return (EINVAL);
802 }
803 
804 /*
805  * Invoke the "match" routine for a cfdata entry on behalf of
806  * an external caller, usually a "submatch" routine.
807  */
808 int
809 config_match(device_t parent, cfdata_t cf, void *aux)
810 {
811 	struct cfattach *ca;
812 
813 	ca = config_cfattach_lookup(cf->cf_name, cf->cf_atname);
814 	if (ca == NULL) {
815 		/* No attachment for this entry, oh well. */
816 		return (0);
817 	}
818 
819 	return ((*ca->ca_match)(parent, cf, aux));
820 }
821 
822 /*
823  * Iterate over all potential children of some device, calling the given
824  * function (default being the child's match function) for each one.
825  * Nonzero returns are matches; the highest value returned is considered
826  * the best match.  Return the `found child' if we got a match, or NULL
827  * otherwise.  The `aux' pointer is simply passed on through.
828  *
829  * Note that this function is designed so that it can be used to apply
830  * an arbitrary function to all potential children (its return value
831  * can be ignored).
832  */
833 cfdata_t
834 config_search_loc(cfsubmatch_t fn, device_t parent,
835 		  const char *ifattr, const int *locs, void *aux)
836 {
837 	struct cftable *ct;
838 	cfdata_t cf;
839 	struct matchinfo m;
840 
841 	KASSERT(config_initialized);
842 	KASSERT(!ifattr || cfdriver_get_iattr(parent->dv_cfdriver, ifattr));
843 
844 	m.fn = fn;
845 	m.parent = parent;
846 	m.locs = locs;
847 	m.aux = aux;
848 	m.match = NULL;
849 	m.pri = 0;
850 
851 	TAILQ_FOREACH(ct, &allcftables, ct_list) {
852 		for (cf = ct->ct_cfdata; cf->cf_name; cf++) {
853 
854 			/* We don't match root nodes here. */
855 			if (!cf->cf_pspec)
856 				continue;
857 
858 			/*
859 			 * Skip cf if no longer eligible, otherwise scan
860 			 * through parents for one matching `parent', and
861 			 * try match function.
862 			 */
863 			if (cf->cf_fstate == FSTATE_FOUND)
864 				continue;
865 			if (cf->cf_fstate == FSTATE_DNOTFOUND ||
866 			    cf->cf_fstate == FSTATE_DSTAR)
867 				continue;
868 
869 			/*
870 			 * If an interface attribute was specified,
871 			 * consider only children which attach to
872 			 * that attribute.
873 			 */
874 			if (ifattr && !STREQ(ifattr, cf->cf_pspec->cfp_iattr))
875 				continue;
876 
877 			if (cfparent_match(parent, cf->cf_pspec))
878 				mapply(&m, cf);
879 		}
880 	}
881 	return (m.match);
882 }
883 
884 cfdata_t
885 config_search_ia(cfsubmatch_t fn, device_t parent, const char *ifattr,
886     void *aux)
887 {
888 
889 	return (config_search_loc(fn, parent, ifattr, NULL, aux));
890 }
891 
892 /*
893  * Find the given root device.
894  * This is much like config_search, but there is no parent.
895  * Don't bother with multiple cfdata tables; the root node
896  * must always be in the initial table.
897  */
898 cfdata_t
899 config_rootsearch(cfsubmatch_t fn, const char *rootname, void *aux)
900 {
901 	cfdata_t cf;
902 	const short *p;
903 	struct matchinfo m;
904 
905 	m.fn = fn;
906 	m.parent = ROOT;
907 	m.aux = aux;
908 	m.match = NULL;
909 	m.pri = 0;
910 	m.locs = 0;
911 	/*
912 	 * Look at root entries for matching name.  We do not bother
913 	 * with found-state here since only one root should ever be
914 	 * searched (and it must be done first).
915 	 */
916 	for (p = cfroots; *p >= 0; p++) {
917 		cf = &cfdata[*p];
918 		if (strcmp(cf->cf_name, rootname) == 0)
919 			mapply(&m, cf);
920 	}
921 	return (m.match);
922 }
923 
924 static const char * const msgs[3] = { "", " not configured\n", " unsupported\n" };
925 
926 /*
927  * The given `aux' argument describes a device that has been found
928  * on the given parent, but not necessarily configured.  Locate the
929  * configuration data for that device (using the submatch function
930  * provided, or using candidates' cd_match configuration driver
931  * functions) and attach it, and return true.  If the device was
932  * not configured, call the given `print' function and return 0.
933  */
934 device_t
935 config_found_sm_loc(device_t parent,
936 		const char *ifattr, const int *locs, void *aux,
937 		cfprint_t print, cfsubmatch_t submatch)
938 {
939 	cfdata_t cf;
940 
941 #if defined(SPLASHSCREEN) && defined(SPLASHSCREEN_PROGRESS)
942 	if (splash_progress_state)
943 		splash_progress_update(splash_progress_state);
944 #endif
945 
946 	if ((cf = config_search_loc(submatch, parent, ifattr, locs, aux)))
947 		return(config_attach_loc(parent, cf, locs, aux, print));
948 	if (print) {
949 		if (config_do_twiddle)
950 			twiddle();
951 		aprint_normal("%s", msgs[(*print)(aux, parent->dv_xname)]);
952 	}
953 
954 #if defined(SPLASHSCREEN) && defined(SPLASHSCREEN_PROGRESS)
955 	if (splash_progress_state)
956 		splash_progress_update(splash_progress_state);
957 #endif
958 
959 	return (NULL);
960 }
961 
962 device_t
963 config_found_ia(device_t parent, const char *ifattr, void *aux,
964     cfprint_t print)
965 {
966 
967 	return (config_found_sm_loc(parent, ifattr, NULL, aux, print, NULL));
968 }
969 
970 device_t
971 config_found(device_t parent, void *aux, cfprint_t print)
972 {
973 
974 	return (config_found_sm_loc(parent, NULL, NULL, aux, print, NULL));
975 }
976 
977 /*
978  * As above, but for root devices.
979  */
980 device_t
981 config_rootfound(const char *rootname, void *aux)
982 {
983 	cfdata_t cf;
984 
985 	if ((cf = config_rootsearch((cfsubmatch_t)NULL, rootname, aux)) != NULL)
986 		return (config_attach(ROOT, cf, aux, (cfprint_t)NULL));
987 	aprint_error("root device %s not configured\n", rootname);
988 	return (NULL);
989 }
990 
991 /* just like sprintf(buf, "%d") except that it works from the end */
992 static char *
993 number(char *ep, int n)
994 {
995 
996 	*--ep = 0;
997 	while (n >= 10) {
998 		*--ep = (n % 10) + '0';
999 		n /= 10;
1000 	}
1001 	*--ep = n + '0';
1002 	return (ep);
1003 }
1004 
1005 /*
1006  * Expand the size of the cd_devs array if necessary.
1007  */
1008 static void
1009 config_makeroom(int n, struct cfdriver *cd)
1010 {
1011 	int old, new;
1012 	void **nsp;
1013 
1014 	if (n < cd->cd_ndevs)
1015 		return;
1016 
1017 	/*
1018 	 * Need to expand the array.
1019 	 */
1020 	old = cd->cd_ndevs;
1021 	if (old == 0)
1022 		new = 4;
1023 	else
1024 		new = old * 2;
1025 	while (new <= n)
1026 		new *= 2;
1027 	cd->cd_ndevs = new;
1028 	nsp = malloc(new * sizeof(void *), M_DEVBUF,
1029 	    cold ? M_NOWAIT : M_WAITOK);
1030 	if (nsp == NULL)
1031 		panic("config_attach: %sing dev array",
1032 		    old != 0 ? "expand" : "creat");
1033 	memset(nsp + old, 0, (new - old) * sizeof(void *));
1034 	if (old != 0) {
1035 		memcpy(nsp, cd->cd_devs, old * sizeof(void *));
1036 		free(cd->cd_devs, M_DEVBUF);
1037 	}
1038 	cd->cd_devs = nsp;
1039 }
1040 
1041 static void
1042 config_devlink(device_t dev)
1043 {
1044 	struct cfdriver *cd = dev->dv_cfdriver;
1045 
1046 	/* put this device in the devices array */
1047 	config_makeroom(dev->dv_unit, cd);
1048 	if (cd->cd_devs[dev->dv_unit])
1049 		panic("config_attach: duplicate %s", dev->dv_xname);
1050 	cd->cd_devs[dev->dv_unit] = dev;
1051 
1052 	TAILQ_INSERT_TAIL(&alldevs, dev, dv_list);	/* link up */
1053 }
1054 
1055 static void
1056 config_devunlink(device_t dev)
1057 {
1058 	struct cfdriver *cd = dev->dv_cfdriver;
1059 	int i;
1060 
1061 	/* Unlink from device list. */
1062 	TAILQ_REMOVE(&alldevs, dev, dv_list);
1063 
1064 	/* Remove from cfdriver's array. */
1065 	cd->cd_devs[dev->dv_unit] = NULL;
1066 
1067 	/*
1068 	 * If the device now has no units in use, deallocate its softc array.
1069 	 */
1070 	for (i = 0; i < cd->cd_ndevs; i++)
1071 		if (cd->cd_devs[i] != NULL)
1072 			break;
1073 	if (i == cd->cd_ndevs) {		/* nothing found; deallocate */
1074 		free(cd->cd_devs, M_DEVBUF);
1075 		cd->cd_devs = NULL;
1076 		cd->cd_ndevs = 0;
1077 	}
1078 }
1079 
1080 static device_t
1081 config_devalloc(const device_t parent, const cfdata_t cf, const int *locs)
1082 {
1083 	struct cfdriver *cd;
1084 	struct cfattach *ca;
1085 	size_t lname, lunit;
1086 	const char *xunit;
1087 	int myunit;
1088 	char num[10];
1089 	device_t dev;
1090 	void *dev_private;
1091 	const struct cfiattrdata *ia;
1092 
1093 	cd = config_cfdriver_lookup(cf->cf_name);
1094 	if (cd == NULL)
1095 		return (NULL);
1096 
1097 	ca = config_cfattach_lookup_cd(cd, cf->cf_atname);
1098 	if (ca == NULL)
1099 		return (NULL);
1100 
1101 	if ((ca->ca_flags & DVF_PRIV_ALLOC) == 0 &&
1102 	    ca->ca_devsize < sizeof(struct device))
1103 		panic("config_devalloc");
1104 
1105 #ifndef __BROKEN_CONFIG_UNIT_USAGE
1106 	if (cf->cf_fstate == FSTATE_STAR) {
1107 		for (myunit = cf->cf_unit; myunit < cd->cd_ndevs; myunit++)
1108 			if (cd->cd_devs[myunit] == NULL)
1109 				break;
1110 		/*
1111 		 * myunit is now the unit of the first NULL device pointer,
1112 		 * or max(cd->cd_ndevs,cf->cf_unit).
1113 		 */
1114 	} else {
1115 		myunit = cf->cf_unit;
1116 		if (myunit < cd->cd_ndevs && cd->cd_devs[myunit] != NULL)
1117 			return (NULL);
1118 	}
1119 #else
1120 	myunit = cf->cf_unit;
1121 #endif /* ! __BROKEN_CONFIG_UNIT_USAGE */
1122 
1123 	/* compute length of name and decimal expansion of unit number */
1124 	lname = strlen(cd->cd_name);
1125 	xunit = number(&num[sizeof(num)], myunit);
1126 	lunit = &num[sizeof(num)] - xunit;
1127 	if (lname + lunit > sizeof(dev->dv_xname))
1128 		panic("config_devalloc: device name too long");
1129 
1130 	/* get memory for all device vars */
1131 	dev_private = malloc(ca->ca_devsize, M_DEVBUF,
1132 			     M_ZERO | (cold ? M_NOWAIT : M_WAITOK));
1133 	if (dev_private == NULL)
1134 		panic("config_devalloc: memory allocation for device softc failed");
1135 
1136 	if ((ca->ca_flags & DVF_PRIV_ALLOC) != 0) {
1137 		dev = malloc(sizeof(struct device), M_DEVBUF,
1138 			     M_ZERO | (cold ? M_NOWAIT : M_WAITOK));
1139 	} else {
1140 		dev = dev_private;
1141 	}
1142 	if (dev == NULL)
1143 		panic("config_devalloc: memory allocation for device_t failed");
1144 
1145 	dev->dv_class = cd->cd_class;
1146 	dev->dv_cfdata = cf;
1147 	dev->dv_cfdriver = cd;
1148 	dev->dv_cfattach = ca;
1149 	dev->dv_unit = myunit;
1150 	dev->dv_activity_count = 0;
1151 	dev->dv_activity_handlers = NULL;
1152 	dev->dv_private = dev_private;
1153 	memcpy(dev->dv_xname, cd->cd_name, lname);
1154 	memcpy(dev->dv_xname + lname, xunit, lunit);
1155 	dev->dv_parent = parent;
1156 	if (parent != NULL)
1157 		dev->dv_depth = parent->dv_depth + 1;
1158 	else
1159 		dev->dv_depth = 0;
1160 	dev->dv_flags = DVF_ACTIVE;	/* always initially active */
1161 	dev->dv_flags |= ca->ca_flags;	/* inherit flags from class */
1162 	if (locs) {
1163 		KASSERT(parent); /* no locators at root */
1164 		ia = cfiattr_lookup(cf->cf_pspec->cfp_iattr,
1165 				    parent->dv_cfdriver);
1166 		dev->dv_locators = malloc(ia->ci_loclen * sizeof(int),
1167 					  M_DEVBUF, cold ? M_NOWAIT : M_WAITOK);
1168 		memcpy(dev->dv_locators, locs, ia->ci_loclen * sizeof(int));
1169 	}
1170 	dev->dv_properties = prop_dictionary_create();
1171 	KASSERT(dev->dv_properties != NULL);
1172 
1173 	return (dev);
1174 }
1175 
1176 static void
1177 config_devdealloc(device_t dev)
1178 {
1179 
1180 	KASSERT(dev->dv_properties != NULL);
1181 	prop_object_release(dev->dv_properties);
1182 
1183 	if (dev->dv_activity_handlers)
1184 		panic("config_devdealloc with registered handlers");
1185 
1186 	if (dev->dv_locators)
1187 		free(dev->dv_locators, M_DEVBUF);
1188 
1189 	if ((dev->dv_flags & DVF_PRIV_ALLOC) != 0)
1190 		free(dev->dv_private, M_DEVBUF);
1191 
1192 	free(dev, M_DEVBUF);
1193 }
1194 
1195 /*
1196  * Attach a found device.
1197  */
1198 device_t
1199 config_attach_loc(device_t parent, cfdata_t cf,
1200 	const int *locs, void *aux, cfprint_t print)
1201 {
1202 	device_t dev;
1203 	struct cftable *ct;
1204 	const char *drvname;
1205 
1206 #if defined(SPLASHSCREEN) && defined(SPLASHSCREEN_PROGRESS)
1207 	if (splash_progress_state)
1208 		splash_progress_update(splash_progress_state);
1209 #endif
1210 
1211 	dev = config_devalloc(parent, cf, locs);
1212 	if (!dev)
1213 		panic("config_attach: allocation of device softc failed");
1214 
1215 	/* XXX redundant - see below? */
1216 	if (cf->cf_fstate != FSTATE_STAR) {
1217 		KASSERT(cf->cf_fstate == FSTATE_NOTFOUND);
1218 		cf->cf_fstate = FSTATE_FOUND;
1219 	}
1220 #ifdef __BROKEN_CONFIG_UNIT_USAGE
1221 	  else
1222 		cf->cf_unit++;
1223 #endif
1224 
1225 	config_devlink(dev);
1226 
1227 	if (config_do_twiddle)
1228 		twiddle();
1229 	else
1230 		aprint_naive("Found ");
1231 	/*
1232 	 * We want the next two printfs for normal, verbose, and quiet,
1233 	 * but not silent (in which case, we're twiddling, instead).
1234 	 */
1235 	if (parent == ROOT) {
1236 		aprint_naive("%s (root)", dev->dv_xname);
1237 		aprint_normal("%s (root)", dev->dv_xname);
1238 	} else {
1239 		aprint_naive("%s at %s", dev->dv_xname, parent->dv_xname);
1240 		aprint_normal("%s at %s", dev->dv_xname, parent->dv_xname);
1241 		if (print)
1242 			(void) (*print)(aux, NULL);
1243 	}
1244 
1245 	/*
1246 	 * Before attaching, clobber any unfound devices that are
1247 	 * otherwise identical.
1248 	 * XXX code above is redundant?
1249 	 */
1250 	drvname = dev->dv_cfdriver->cd_name;
1251 	TAILQ_FOREACH(ct, &allcftables, ct_list) {
1252 		for (cf = ct->ct_cfdata; cf->cf_name; cf++) {
1253 			if (STREQ(cf->cf_name, drvname) &&
1254 			    cf->cf_unit == dev->dv_unit) {
1255 				if (cf->cf_fstate == FSTATE_NOTFOUND)
1256 					cf->cf_fstate = FSTATE_FOUND;
1257 #ifdef __BROKEN_CONFIG_UNIT_USAGE
1258 				/*
1259 				 * Bump the unit number on all starred cfdata
1260 				 * entries for this device.
1261 				 */
1262 				if (cf->cf_fstate == FSTATE_STAR)
1263 					cf->cf_unit++;
1264 #endif /* __BROKEN_CONFIG_UNIT_USAGE */
1265 			}
1266 		}
1267 	}
1268 #ifdef __HAVE_DEVICE_REGISTER
1269 	device_register(dev, aux);
1270 #endif
1271 
1272 #if defined(SPLASHSCREEN) && defined(SPLASHSCREEN_PROGRESS)
1273 	if (splash_progress_state)
1274 		splash_progress_update(splash_progress_state);
1275 #endif
1276 	(*dev->dv_cfattach->ca_attach)(parent, dev, aux);
1277 #if defined(SPLASHSCREEN) && defined(SPLASHSCREEN_PROGRESS)
1278 	if (splash_progress_state)
1279 		splash_progress_update(splash_progress_state);
1280 #endif
1281 
1282 	if (!device_pmf_is_registered(dev))
1283 		aprint_debug_dev(dev, "WARNING: power management not supported\n");
1284 
1285 	config_process_deferred(&deferred_config_queue, dev);
1286 	return (dev);
1287 }
1288 
1289 device_t
1290 config_attach(device_t parent, cfdata_t cf, void *aux, cfprint_t print)
1291 {
1292 
1293 	return (config_attach_loc(parent, cf, NULL, aux, print));
1294 }
1295 
1296 /*
1297  * As above, but for pseudo-devices.  Pseudo-devices attached in this
1298  * way are silently inserted into the device tree, and their children
1299  * attached.
1300  *
1301  * Note that because pseudo-devices are attached silently, any information
1302  * the attach routine wishes to print should be prefixed with the device
1303  * name by the attach routine.
1304  */
1305 device_t
1306 config_attach_pseudo(cfdata_t cf)
1307 {
1308 	device_t dev;
1309 
1310 	dev = config_devalloc(ROOT, cf, NULL);
1311 	if (!dev)
1312 		return (NULL);
1313 
1314 	/* XXX mark busy in cfdata */
1315 
1316 	config_devlink(dev);
1317 
1318 #if 0	/* XXXJRT not yet */
1319 #ifdef __HAVE_DEVICE_REGISTER
1320 	device_register(dev, NULL);	/* like a root node */
1321 #endif
1322 #endif
1323 	(*dev->dv_cfattach->ca_attach)(ROOT, dev, NULL);
1324 	config_process_deferred(&deferred_config_queue, dev);
1325 	return (dev);
1326 }
1327 
1328 /*
1329  * Detach a device.  Optionally forced (e.g. because of hardware
1330  * removal) and quiet.  Returns zero if successful, non-zero
1331  * (an error code) otherwise.
1332  *
1333  * Note that this code wants to be run from a process context, so
1334  * that the detach can sleep to allow processes which have a device
1335  * open to run and unwind their stacks.
1336  */
1337 int
1338 config_detach(device_t dev, int flags)
1339 {
1340 	struct cftable *ct;
1341 	cfdata_t cf;
1342 	const struct cfattach *ca;
1343 	struct cfdriver *cd;
1344 #ifdef DIAGNOSTIC
1345 	device_t d;
1346 #endif
1347 	int rv = 0;
1348 
1349 #ifdef DIAGNOSTIC
1350 	if (dev->dv_cfdata != NULL &&
1351 	    dev->dv_cfdata->cf_fstate != FSTATE_FOUND &&
1352 	    dev->dv_cfdata->cf_fstate != FSTATE_STAR)
1353 		panic("config_detach: bad device fstate");
1354 #endif
1355 	cd = dev->dv_cfdriver;
1356 	KASSERT(cd != NULL);
1357 
1358 	ca = dev->dv_cfattach;
1359 	KASSERT(ca != NULL);
1360 
1361 	/*
1362 	 * Ensure the device is deactivated.  If the device doesn't
1363 	 * have an activation entry point, we allow DVF_ACTIVE to
1364 	 * remain set.  Otherwise, if DVF_ACTIVE is still set, the
1365 	 * device is busy, and the detach fails.
1366 	 */
1367 	if (ca->ca_activate != NULL)
1368 		rv = config_deactivate(dev);
1369 
1370 	/*
1371 	 * Try to detach the device.  If that's not possible, then
1372 	 * we either panic() (for the forced but failed case), or
1373 	 * return an error.
1374 	 */
1375 	if (rv == 0) {
1376 		if (ca->ca_detach != NULL)
1377 			rv = (*ca->ca_detach)(dev, flags);
1378 		else
1379 			rv = EOPNOTSUPP;
1380 	}
1381 	if (rv != 0) {
1382 		if ((flags & DETACH_FORCE) == 0)
1383 			return (rv);
1384 		else
1385 			panic("config_detach: forced detach of %s failed (%d)",
1386 			    dev->dv_xname, rv);
1387 	}
1388 
1389 	/*
1390 	 * The device has now been successfully detached.
1391 	 */
1392 
1393 #ifdef DIAGNOSTIC
1394 	/*
1395 	 * Sanity: If you're successfully detached, you should have no
1396 	 * children.  (Note that because children must be attached
1397 	 * after parents, we only need to search the latter part of
1398 	 * the list.)
1399 	 */
1400 	for (d = TAILQ_NEXT(dev, dv_list); d != NULL;
1401 	    d = TAILQ_NEXT(d, dv_list)) {
1402 		if (d->dv_parent == dev) {
1403 			printf("config_detach: detached device %s"
1404 			    " has children %s\n", dev->dv_xname, d->dv_xname);
1405 			panic("config_detach");
1406 		}
1407 	}
1408 #endif
1409 
1410 	/* notify the parent that the child is gone */
1411 	if (dev->dv_parent) {
1412 		device_t p = dev->dv_parent;
1413 		if (p->dv_cfattach->ca_childdetached)
1414 			(*p->dv_cfattach->ca_childdetached)(p, dev);
1415 	}
1416 
1417 	/*
1418 	 * Mark cfdata to show that the unit can be reused, if possible.
1419 	 */
1420 	TAILQ_FOREACH(ct, &allcftables, ct_list) {
1421 		for (cf = ct->ct_cfdata; cf->cf_name; cf++) {
1422 			if (STREQ(cf->cf_name, cd->cd_name)) {
1423 				if (cf->cf_fstate == FSTATE_FOUND &&
1424 				    cf->cf_unit == dev->dv_unit)
1425 					cf->cf_fstate = FSTATE_NOTFOUND;
1426 #ifdef __BROKEN_CONFIG_UNIT_USAGE
1427 				/*
1428 				 * Note that we can only re-use a starred
1429 				 * unit number if the unit being detached
1430 				 * had the last assigned unit number.
1431 				 */
1432 				if (cf->cf_fstate == FSTATE_STAR &&
1433 				    cf->cf_unit == dev->dv_unit + 1)
1434 					cf->cf_unit--;
1435 #endif /* __BROKEN_CONFIG_UNIT_USAGE */
1436 			}
1437 		}
1438 	}
1439 
1440 	config_devunlink(dev);
1441 
1442 	if (dev->dv_cfdata != NULL && (flags & DETACH_QUIET) == 0)
1443 		aprint_normal("%s detached\n", dev->dv_xname);
1444 
1445 	config_devdealloc(dev);
1446 
1447 	return (0);
1448 }
1449 
1450 int
1451 config_detach_children(device_t parent, int flags)
1452 {
1453 	device_t dv;
1454 	int progress, error = 0;
1455 
1456 	/*
1457 	 * config_detach() can work recursively, thus it can
1458 	 * delete any number of devices from the linked list.
1459 	 * For that reason, start over after each hit.
1460 	 */
1461 	do {
1462 		progress = 0;
1463 		TAILQ_FOREACH(dv, &alldevs, dv_list) {
1464 			if (device_parent(dv) != parent)
1465 				continue;
1466 			progress++;
1467 			error = config_detach(dv, flags);
1468 			break;
1469 		}
1470 	} while (progress && !error);
1471 	return error;
1472 }
1473 
1474 int
1475 config_activate(device_t dev)
1476 {
1477 	const struct cfattach *ca = dev->dv_cfattach;
1478 	int rv = 0, oflags = dev->dv_flags;
1479 
1480 	if (ca->ca_activate == NULL)
1481 		return (EOPNOTSUPP);
1482 
1483 	if ((dev->dv_flags & DVF_ACTIVE) == 0) {
1484 		dev->dv_flags |= DVF_ACTIVE;
1485 		rv = (*ca->ca_activate)(dev, DVACT_ACTIVATE);
1486 		if (rv)
1487 			dev->dv_flags = oflags;
1488 	}
1489 	return (rv);
1490 }
1491 
1492 int
1493 config_deactivate(device_t dev)
1494 {
1495 	const struct cfattach *ca = dev->dv_cfattach;
1496 	int rv = 0, oflags = dev->dv_flags;
1497 
1498 	if (ca->ca_activate == NULL)
1499 		return (EOPNOTSUPP);
1500 
1501 	if (dev->dv_flags & DVF_ACTIVE) {
1502 		dev->dv_flags &= ~DVF_ACTIVE;
1503 		rv = (*ca->ca_activate)(dev, DVACT_DEACTIVATE);
1504 		if (rv)
1505 			dev->dv_flags = oflags;
1506 	}
1507 	return (rv);
1508 }
1509 
1510 /*
1511  * Defer the configuration of the specified device until all
1512  * of its parent's devices have been attached.
1513  */
1514 void
1515 config_defer(device_t dev, void (*func)(device_t))
1516 {
1517 	struct deferred_config *dc;
1518 
1519 	if (dev->dv_parent == NULL)
1520 		panic("config_defer: can't defer config of a root device");
1521 
1522 #ifdef DIAGNOSTIC
1523 	for (dc = TAILQ_FIRST(&deferred_config_queue); dc != NULL;
1524 	     dc = TAILQ_NEXT(dc, dc_queue)) {
1525 		if (dc->dc_dev == dev)
1526 			panic("config_defer: deferred twice");
1527 	}
1528 #endif
1529 
1530 	dc = malloc(sizeof(*dc), M_DEVBUF, cold ? M_NOWAIT : M_WAITOK);
1531 	if (dc == NULL)
1532 		panic("config_defer: unable to allocate callback");
1533 
1534 	dc->dc_dev = dev;
1535 	dc->dc_func = func;
1536 	TAILQ_INSERT_TAIL(&deferred_config_queue, dc, dc_queue);
1537 	config_pending_incr();
1538 }
1539 
1540 /*
1541  * Defer some autoconfiguration for a device until after interrupts
1542  * are enabled.
1543  */
1544 void
1545 config_interrupts(device_t dev, void (*func)(device_t))
1546 {
1547 	struct deferred_config *dc;
1548 
1549 	/*
1550 	 * If interrupts are enabled, callback now.
1551 	 */
1552 	if (cold == 0) {
1553 		(*func)(dev);
1554 		return;
1555 	}
1556 
1557 #ifdef DIAGNOSTIC
1558 	for (dc = TAILQ_FIRST(&interrupt_config_queue); dc != NULL;
1559 	     dc = TAILQ_NEXT(dc, dc_queue)) {
1560 		if (dc->dc_dev == dev)
1561 			panic("config_interrupts: deferred twice");
1562 	}
1563 #endif
1564 
1565 	dc = malloc(sizeof(*dc), M_DEVBUF, cold ? M_NOWAIT : M_WAITOK);
1566 	if (dc == NULL)
1567 		panic("config_interrupts: unable to allocate callback");
1568 
1569 	dc->dc_dev = dev;
1570 	dc->dc_func = func;
1571 	TAILQ_INSERT_TAIL(&interrupt_config_queue, dc, dc_queue);
1572 	config_pending_incr();
1573 }
1574 
1575 /*
1576  * Process a deferred configuration queue.
1577  */
1578 static void
1579 config_process_deferred(struct deferred_config_head *queue,
1580     device_t parent)
1581 {
1582 	struct deferred_config *dc, *ndc;
1583 
1584 	for (dc = TAILQ_FIRST(queue); dc != NULL; dc = ndc) {
1585 		ndc = TAILQ_NEXT(dc, dc_queue);
1586 		if (parent == NULL || dc->dc_dev->dv_parent == parent) {
1587 			TAILQ_REMOVE(queue, dc, dc_queue);
1588 			(*dc->dc_func)(dc->dc_dev);
1589 			free(dc, M_DEVBUF);
1590 			config_pending_decr();
1591 		}
1592 	}
1593 }
1594 
1595 /*
1596  * Manipulate the config_pending semaphore.
1597  */
1598 void
1599 config_pending_incr(void)
1600 {
1601 
1602 	config_pending++;
1603 }
1604 
1605 void
1606 config_pending_decr(void)
1607 {
1608 
1609 #ifdef DIAGNOSTIC
1610 	if (config_pending == 0)
1611 		panic("config_pending_decr: config_pending == 0");
1612 #endif
1613 	config_pending--;
1614 	if (config_pending == 0)
1615 		wakeup(&config_pending);
1616 }
1617 
1618 /*
1619  * Register a "finalization" routine.  Finalization routines are
1620  * called iteratively once all real devices have been found during
1621  * autoconfiguration, for as long as any one finalizer has done
1622  * any work.
1623  */
1624 int
1625 config_finalize_register(device_t dev, int (*fn)(device_t))
1626 {
1627 	struct finalize_hook *f;
1628 
1629 	/*
1630 	 * If finalization has already been done, invoke the
1631 	 * callback function now.
1632 	 */
1633 	if (config_finalize_done) {
1634 		while ((*fn)(dev) != 0)
1635 			/* loop */ ;
1636 	}
1637 
1638 	/* Ensure this isn't already on the list. */
1639 	TAILQ_FOREACH(f, &config_finalize_list, f_list) {
1640 		if (f->f_func == fn && f->f_dev == dev)
1641 			return (EEXIST);
1642 	}
1643 
1644 	f = malloc(sizeof(*f), M_TEMP, M_WAITOK);
1645 	f->f_func = fn;
1646 	f->f_dev = dev;
1647 	TAILQ_INSERT_TAIL(&config_finalize_list, f, f_list);
1648 
1649 	return (0);
1650 }
1651 
1652 void
1653 config_finalize(void)
1654 {
1655 	struct finalize_hook *f;
1656 	int rv;
1657 
1658 	/* Run the hooks until none of them does any work. */
1659 	do {
1660 		rv = 0;
1661 		TAILQ_FOREACH(f, &config_finalize_list, f_list)
1662 			rv |= (*f->f_func)(f->f_dev);
1663 	} while (rv != 0);
1664 
1665 	config_finalize_done = 1;
1666 
1667 	/* Now free all the hooks. */
1668 	while ((f = TAILQ_FIRST(&config_finalize_list)) != NULL) {
1669 		TAILQ_REMOVE(&config_finalize_list, f, f_list);
1670 		free(f, M_TEMP);
1671 	}
1672 }
1673 
1674 /*
1675  * device_lookup:
1676  *
1677  *	Look up a device instance for a given driver.
1678  */
1679 void *
1680 device_lookup(cfdriver_t cd, int unit)
1681 {
1682 
1683 	if (unit < 0 || unit >= cd->cd_ndevs)
1684 		return (NULL);
1685 
1686 	return (cd->cd_devs[unit]);
1687 }
1688 
1689 /*
1690  * Accessor functions for the device_t type.
1691  */
1692 devclass_t
1693 device_class(device_t dev)
1694 {
1695 
1696 	return (dev->dv_class);
1697 }
1698 
1699 cfdata_t
1700 device_cfdata(device_t dev)
1701 {
1702 
1703 	return (dev->dv_cfdata);
1704 }
1705 
1706 cfdriver_t
1707 device_cfdriver(device_t dev)
1708 {
1709 
1710 	return (dev->dv_cfdriver);
1711 }
1712 
1713 cfattach_t
1714 device_cfattach(device_t dev)
1715 {
1716 
1717 	return (dev->dv_cfattach);
1718 }
1719 
1720 int
1721 device_unit(device_t dev)
1722 {
1723 
1724 	return (dev->dv_unit);
1725 }
1726 
1727 const char *
1728 device_xname(device_t dev)
1729 {
1730 
1731 	return (dev->dv_xname);
1732 }
1733 
1734 device_t
1735 device_parent(device_t dev)
1736 {
1737 
1738 	return (dev->dv_parent);
1739 }
1740 
1741 bool
1742 device_is_active(device_t dev)
1743 {
1744 	int active_flags;
1745 
1746 	active_flags = DVF_ACTIVE;
1747 	active_flags |= DVF_CLASS_SUSPENDED;
1748 	active_flags |= DVF_DRIVER_SUSPENDED;
1749 	active_flags |= DVF_BUS_SUSPENDED;
1750 
1751 	return ((dev->dv_flags & active_flags) == DVF_ACTIVE);
1752 }
1753 
1754 bool
1755 device_is_enabled(device_t dev)
1756 {
1757 	return (dev->dv_flags & DVF_ACTIVE) == DVF_ACTIVE;
1758 }
1759 
1760 bool
1761 device_has_power(device_t dev)
1762 {
1763 	int active_flags;
1764 
1765 	active_flags = DVF_ACTIVE | DVF_BUS_SUSPENDED;
1766 
1767 	return ((dev->dv_flags & active_flags) == DVF_ACTIVE);
1768 }
1769 
1770 int
1771 device_locator(device_t dev, u_int locnum)
1772 {
1773 
1774 	KASSERT(dev->dv_locators != NULL);
1775 	return (dev->dv_locators[locnum]);
1776 }
1777 
1778 void *
1779 device_private(device_t dev)
1780 {
1781 
1782 	return (dev->dv_private);
1783 }
1784 
1785 prop_dictionary_t
1786 device_properties(device_t dev)
1787 {
1788 
1789 	return (dev->dv_properties);
1790 }
1791 
1792 /*
1793  * device_is_a:
1794  *
1795  *	Returns true if the device is an instance of the specified
1796  *	driver.
1797  */
1798 bool
1799 device_is_a(device_t dev, const char *dname)
1800 {
1801 
1802 	return (strcmp(dev->dv_cfdriver->cd_name, dname) == 0);
1803 }
1804 
1805 /*
1806  * device_find_by_xname:
1807  *
1808  *	Returns the device of the given name or NULL if it doesn't exist.
1809  */
1810 device_t
1811 device_find_by_xname(const char *name)
1812 {
1813 	device_t dv;
1814 
1815 	TAILQ_FOREACH(dv, &alldevs, dv_list) {
1816 		if (strcmp(device_xname(dv), name) == 0)
1817 			break;
1818 	}
1819 
1820 	return dv;
1821 }
1822 
1823 /*
1824  * device_find_by_driver_unit:
1825  *
1826  *	Returns the device of the given driver name and unit or
1827  *	NULL if it doesn't exist.
1828  */
1829 device_t
1830 device_find_by_driver_unit(const char *name, int unit)
1831 {
1832 	struct cfdriver *cd;
1833 
1834 	if ((cd = config_cfdriver_lookup(name)) == NULL)
1835 		return NULL;
1836 	return device_lookup(cd, unit);
1837 }
1838 
1839 /*
1840  * Power management related functions.
1841  */
1842 
1843 bool
1844 device_pmf_is_registered(device_t dev)
1845 {
1846 	return (dev->dv_flags & DVF_POWER_HANDLERS) != 0;
1847 }
1848 
1849 bool
1850 device_pmf_driver_suspend(device_t dev)
1851 {
1852 	if ((dev->dv_flags & DVF_DRIVER_SUSPENDED) != 0)
1853 		return true;
1854 	if ((dev->dv_flags & DVF_CLASS_SUSPENDED) == 0)
1855 		return false;
1856 	if (*dev->dv_driver_suspend != NULL &&
1857 	    !(*dev->dv_driver_suspend)(dev))
1858 		return false;
1859 
1860 	dev->dv_flags |= DVF_DRIVER_SUSPENDED;
1861 	return true;
1862 }
1863 
1864 bool
1865 device_pmf_driver_resume(device_t dev)
1866 {
1867 	if ((dev->dv_flags & DVF_DRIVER_SUSPENDED) == 0)
1868 		return true;
1869 	if ((dev->dv_flags & DVF_BUS_SUSPENDED) != 0)
1870 		return false;
1871 	if (*dev->dv_driver_resume != NULL &&
1872 	    !(*dev->dv_driver_resume)(dev))
1873 		return false;
1874 
1875 	dev->dv_flags &= ~DVF_DRIVER_SUSPENDED;
1876 	return true;
1877 }
1878 
1879 void
1880 device_pmf_driver_register(device_t dev,
1881     bool (*suspend)(device_t), bool (*resume)(device_t))
1882 {
1883 	dev->dv_driver_suspend = suspend;
1884 	dev->dv_driver_resume = resume;
1885 	dev->dv_flags |= DVF_POWER_HANDLERS;
1886 }
1887 
1888 void
1889 device_pmf_driver_deregister(device_t dev)
1890 {
1891 	dev->dv_driver_suspend = NULL;
1892 	dev->dv_driver_resume = NULL;
1893 	dev->dv_flags &= ~DVF_POWER_HANDLERS;
1894 }
1895 
1896 bool
1897 device_pmf_driver_child_register(device_t dev)
1898 {
1899 	device_t parent = device_parent(dev);
1900 
1901 	if (parent == NULL || parent->dv_driver_child_register == NULL)
1902 		return true;
1903 	return (*parent->dv_driver_child_register)(dev);
1904 }
1905 
1906 void
1907 device_pmf_driver_set_child_register(device_t dev,
1908     bool (*child_register)(device_t))
1909 {
1910 	dev->dv_driver_child_register = child_register;
1911 }
1912 
1913 void *
1914 device_pmf_bus_private(device_t dev)
1915 {
1916 	return dev->dv_bus_private;
1917 }
1918 
1919 bool
1920 device_pmf_bus_suspend(device_t dev)
1921 {
1922 	if ((dev->dv_flags & DVF_BUS_SUSPENDED) != 0)
1923 		return true;
1924 	if ((dev->dv_flags & DVF_CLASS_SUSPENDED) == 0 ||
1925 	    (dev->dv_flags & DVF_DRIVER_SUSPENDED) == 0)
1926 		return false;
1927 	if (*dev->dv_bus_suspend != NULL &&
1928 	    !(*dev->dv_bus_suspend)(dev))
1929 		return false;
1930 
1931 	dev->dv_flags |= DVF_BUS_SUSPENDED;
1932 	return true;
1933 }
1934 
1935 bool
1936 device_pmf_bus_resume(device_t dev)
1937 {
1938 	if ((dev->dv_flags & DVF_BUS_SUSPENDED) == 0)
1939 		return true;
1940 	if (*dev->dv_bus_resume != NULL &&
1941 	    !(*dev->dv_bus_resume)(dev))
1942 		return false;
1943 
1944 	dev->dv_flags &= ~DVF_BUS_SUSPENDED;
1945 	return true;
1946 }
1947 
1948 void
1949 device_pmf_bus_register(device_t dev, void *priv,
1950     bool (*suspend)(device_t), bool (*resume)(device_t),
1951     void (*deregister)(device_t))
1952 {
1953 	dev->dv_bus_private = priv;
1954 	dev->dv_bus_resume = resume;
1955 	dev->dv_bus_suspend = suspend;
1956 	dev->dv_bus_deregister = deregister;
1957 }
1958 
1959 void
1960 device_pmf_bus_deregister(device_t dev)
1961 {
1962 	if (dev->dv_bus_deregister == NULL)
1963 		return;
1964 	(*dev->dv_bus_deregister)(dev);
1965 	dev->dv_bus_private = NULL;
1966 	dev->dv_bus_suspend = NULL;
1967 	dev->dv_bus_resume = NULL;
1968 	dev->dv_bus_deregister = NULL;
1969 }
1970 
1971 void *
1972 device_pmf_class_private(device_t dev)
1973 {
1974 	return dev->dv_class_private;
1975 }
1976 
1977 bool
1978 device_pmf_class_suspend(device_t dev)
1979 {
1980 	if ((dev->dv_flags & DVF_CLASS_SUSPENDED) != 0)
1981 		return true;
1982 	if (*dev->dv_class_suspend != NULL &&
1983 	    !(*dev->dv_class_suspend)(dev))
1984 		return false;
1985 
1986 	dev->dv_flags |= DVF_CLASS_SUSPENDED;
1987 	return true;
1988 }
1989 
1990 bool
1991 device_pmf_class_resume(device_t dev)
1992 {
1993 	if ((dev->dv_flags & DVF_CLASS_SUSPENDED) == 0)
1994 		return true;
1995 	if ((dev->dv_flags & DVF_BUS_SUSPENDED) != 0 ||
1996 	    (dev->dv_flags & DVF_DRIVER_SUSPENDED) != 0)
1997 		return false;
1998 	if (*dev->dv_class_resume != NULL &&
1999 	    !(*dev->dv_class_resume)(dev))
2000 		return false;
2001 
2002 	dev->dv_flags &= ~DVF_CLASS_SUSPENDED;
2003 	return true;
2004 }
2005 
2006 void
2007 device_pmf_class_register(device_t dev, void *priv,
2008     bool (*suspend)(device_t), bool (*resume)(device_t),
2009     void (*deregister)(device_t))
2010 {
2011 	dev->dv_class_private = priv;
2012 	dev->dv_class_suspend = suspend;
2013 	dev->dv_class_resume = resume;
2014 	dev->dv_class_deregister = deregister;
2015 }
2016 
2017 void
2018 device_pmf_class_deregister(device_t dev)
2019 {
2020 	if (dev->dv_class_deregister == NULL)
2021 		return;
2022 	(*dev->dv_class_deregister)(dev);
2023 	dev->dv_class_private = NULL;
2024 	dev->dv_class_suspend = NULL;
2025 	dev->dv_class_resume = NULL;
2026 	dev->dv_class_deregister = NULL;
2027 }
2028 
2029 bool
2030 device_active(device_t dev, devactive_t type)
2031 {
2032 	size_t i;
2033 
2034 	if (dev->dv_activity_count == 0)
2035 		return false;
2036 
2037 	for (i = 0; i < dev->dv_activity_count; ++i)
2038 		(*dev->dv_activity_handlers[i])(dev, type);
2039 
2040 	return true;
2041 }
2042 
2043 bool
2044 device_active_register(device_t dev, void (*handler)(device_t, devactive_t))
2045 {
2046 	void (**new_handlers)(device_t, devactive_t);
2047 	void (**old_handlers)(device_t, devactive_t);
2048 	size_t i, new_size;
2049 	int s;
2050 
2051 	old_handlers = dev->dv_activity_handlers;
2052 
2053 	for (i = 0; i < dev->dv_activity_count; ++i) {
2054 		if (old_handlers[i] == handler)
2055 			panic("Double registering of idle handlers");
2056 	}
2057 
2058 	new_size = dev->dv_activity_count + 1;
2059 	new_handlers = malloc(sizeof(void *) * new_size, M_DEVBUF, M_WAITOK);
2060 
2061 	memcpy(new_handlers, old_handlers,
2062 	    sizeof(void *) * dev->dv_activity_count);
2063 	new_handlers[new_size - 1] = handler;
2064 
2065 	s = splhigh();
2066 	dev->dv_activity_count = new_size;
2067 	dev->dv_activity_handlers = new_handlers;
2068 	splx(s);
2069 
2070 	if (old_handlers != NULL)
2071 		free(old_handlers, M_DEVBUF);
2072 
2073 	return true;
2074 }
2075 
2076 void
2077 device_active_deregister(device_t dev, void (*handler)(device_t, devactive_t))
2078 {
2079 	void (**new_handlers)(device_t, devactive_t);
2080 	void (**old_handlers)(device_t, devactive_t);
2081 	size_t i, new_size;
2082 	int s;
2083 
2084 	old_handlers = dev->dv_activity_handlers;
2085 
2086 	for (i = 0; i < dev->dv_activity_count; ++i) {
2087 		if (old_handlers[i] == handler)
2088 			break;
2089 	}
2090 
2091 	if (i == dev->dv_activity_count)
2092 		return; /* XXX panic? */
2093 
2094 	new_size = dev->dv_activity_count - 1;
2095 
2096 	if (new_size == 0) {
2097 		new_handlers = NULL;
2098 	} else {
2099 		new_handlers = malloc(sizeof(void *) * new_size, M_DEVBUF,
2100 		    M_WAITOK);
2101 		memcpy(new_handlers, old_handlers, sizeof(void *) * i);
2102 		memcpy(new_handlers + i, old_handlers + i + 1,
2103 		    sizeof(void *) * (new_size - i));
2104 	}
2105 
2106 	s = splhigh();
2107 	dev->dv_activity_count = new_size;
2108 	dev->dv_activity_handlers = new_handlers;
2109 	splx(s);
2110 
2111 	free(old_handlers, M_DEVBUF);
2112 }
2113