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