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