kern_module.c revision 1.89 1 /* $NetBSD: kern_module.c,v 1.89 2013/03/05 03:04:00 christos Exp $ */
2
3 /*-
4 * Copyright (c) 2008 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software developed for The NetBSD Foundation
8 * by Andrew Doran.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGE.
30 */
31
32 /*
33 * Kernel module support.
34 */
35
36 #include <sys/cdefs.h>
37 __KERNEL_RCSID(0, "$NetBSD: kern_module.c,v 1.89 2013/03/05 03:04:00 christos Exp $");
38
39 #define _MODULE_INTERNAL
40
41 #ifdef _KERNEL_OPT
42 #include "opt_ddb.h"
43 #include "opt_modular.h"
44 #endif
45
46 #include <sys/param.h>
47 #include <sys/systm.h>
48 #include <sys/kernel.h>
49 #include <sys/proc.h>
50 #include <sys/kauth.h>
51 #include <sys/kobj.h>
52 #include <sys/kmem.h>
53 #include <sys/module.h>
54 #include <sys/kthread.h>
55 #include <sys/sysctl.h>
56 #include <sys/lock.h>
57
58 #include <uvm/uvm_extern.h>
59
60 struct vm_map *module_map;
61 char *module_machine;
62 char module_base[MODULE_BASE_SIZE];
63
64 struct modlist module_list = TAILQ_HEAD_INITIALIZER(module_list);
65 struct modlist module_builtins = TAILQ_HEAD_INITIALIZER(module_builtins);
66 static struct modlist module_bootlist = TAILQ_HEAD_INITIALIZER(module_bootlist);
67
68 static module_t *module_active;
69 static bool module_verbose_on;
70 static bool module_autoload_on = true;
71 u_int module_count;
72 u_int module_builtinlist;
73 u_int module_autotime = 10;
74 u_int module_gen = 1;
75 static kcondvar_t module_thread_cv;
76 static kmutex_t module_thread_lock;
77 static int module_thread_ticks;
78 int (*module_load_vfs_vec)(const char *, int, bool, module_t *,
79 prop_dictionary_t *) = (void *)eopnotsupp;
80
81 static kauth_listener_t module_listener;
82
83 /* Ensure that the kernel's link set isn't empty. */
84 static modinfo_t module_dummy;
85 __link_set_add_rodata(modules, module_dummy);
86
87 static module_t *module_newmodule(modsrc_t);
88 static void module_require_force(module_t *);
89 static int module_do_load(const char *, bool, int, prop_dictionary_t,
90 module_t **, modclass_t class, bool);
91 static int module_do_unload(const char *, bool);
92 static int module_do_builtin(const char *, module_t **, prop_dictionary_t);
93 static int module_fetch_info(module_t *);
94 static void module_thread(void *);
95
96 static module_t *module_lookup(const char *);
97 static void module_enqueue(module_t *);
98
99 static bool module_merge_dicts(prop_dictionary_t, const prop_dictionary_t);
100
101 static void sysctl_module_setup(void);
102 #define MODULE_CLASS_MATCH(mi, class) \
103 ((class) == MODULE_CLASS_ANY || (class) == (mi)->mi_class)
104
105 static void
106 module_incompat(const modinfo_t *mi, int class)
107 {
108 module_error("incompatible module class for `%s' (%d != %d)",
109 mi->mi_name, class, mi->mi_class);
110 }
111
112 /*
113 * module_error:
114 *
115 * Utility function: log an error.
116 */
117 void
118 module_error(const char *fmt, ...)
119 {
120 va_list ap;
121
122 va_start(ap, fmt);
123 printf("WARNING: module error: ");
124 vprintf(fmt, ap);
125 printf("\n");
126 va_end(ap);
127 }
128
129 /*
130 * module_print:
131 *
132 * Utility function: log verbose output.
133 */
134 void
135 module_print(const char *fmt, ...)
136 {
137 va_list ap;
138
139 if (module_verbose_on) {
140 va_start(ap, fmt);
141 printf("DEBUG: module: ");
142 vprintf(fmt, ap);
143 printf("\n");
144 va_end(ap);
145 }
146 }
147
148 static int
149 module_listener_cb(kauth_cred_t cred, kauth_action_t action, void *cookie,
150 void *arg0, void *arg1, void *arg2, void *arg3)
151 {
152 int result;
153
154 result = KAUTH_RESULT_DEFER;
155
156 if (action != KAUTH_SYSTEM_MODULE)
157 return result;
158
159 if ((uintptr_t)arg2 != 0) /* autoload */
160 result = KAUTH_RESULT_ALLOW;
161
162 return result;
163 }
164
165 /*
166 * Allocate a new module_t
167 */
168 static module_t *
169 module_newmodule(modsrc_t source)
170 {
171 module_t *mod;
172
173 mod = kmem_zalloc(sizeof(*mod), KM_SLEEP);
174 if (mod != NULL) {
175 mod->mod_source = source;
176 mod->mod_info = NULL;
177 mod->mod_flags = 0;
178 }
179 return mod;
180 }
181
182 /*
183 * Require the -f (force) flag to load a module
184 */
185 static void
186 module_require_force(struct module *mod)
187 {
188 mod->mod_flags |= MODFLG_MUST_FORCE;
189 }
190
191 /*
192 * Add modules to the builtin list. This can done at boottime or
193 * at runtime if the module is linked into the kernel with an
194 * external linker. All or none of the input will be handled.
195 * Optionally, the modules can be initialized. If they are not
196 * initialized, module_init_class() or module_load() can be used
197 * later, but these are not guaranteed to give atomic results.
198 */
199 int
200 module_builtin_add(modinfo_t *const *mip, size_t nmodinfo, bool init)
201 {
202 struct module **modp = NULL, *mod_iter;
203 int rv = 0, i, mipskip;
204
205 if (init) {
206 rv = kauth_authorize_system(kauth_cred_get(),
207 KAUTH_SYSTEM_MODULE, 0, (void *)(uintptr_t)MODCTL_LOAD,
208 (void *)(uintptr_t)1, NULL);
209 if (rv) {
210 return rv;
211 }
212 }
213
214 for (i = 0, mipskip = 0; i < nmodinfo; i++) {
215 if (mip[i] == &module_dummy) {
216 KASSERT(nmodinfo > 0);
217 nmodinfo--;
218 }
219 }
220 if (nmodinfo == 0)
221 return 0;
222
223 modp = kmem_zalloc(sizeof(*modp) * nmodinfo, KM_SLEEP);
224 for (i = 0, mipskip = 0; i < nmodinfo; i++) {
225 if (mip[i+mipskip] == &module_dummy) {
226 mipskip++;
227 continue;
228 }
229 modp[i] = module_newmodule(MODULE_SOURCE_KERNEL);
230 modp[i]->mod_info = mip[i+mipskip];
231 }
232 kernconfig_lock();
233
234 /* do this in three stages for error recovery and atomicity */
235
236 /* first check for presence */
237 for (i = 0; i < nmodinfo; i++) {
238 TAILQ_FOREACH(mod_iter, &module_builtins, mod_chain) {
239 if (strcmp(mod_iter->mod_info->mi_name,
240 modp[i]->mod_info->mi_name) == 0)
241 break;
242 }
243 if (mod_iter) {
244 rv = EEXIST;
245 goto out;
246 }
247
248 if (module_lookup(modp[i]->mod_info->mi_name) != NULL) {
249 rv = EEXIST;
250 goto out;
251 }
252 }
253
254 /* then add to list */
255 for (i = 0; i < nmodinfo; i++) {
256 TAILQ_INSERT_TAIL(&module_builtins, modp[i], mod_chain);
257 module_builtinlist++;
258 }
259
260 /* finally, init (if required) */
261 if (init) {
262 for (i = 0; i < nmodinfo; i++) {
263 rv = module_do_builtin(modp[i]->mod_info->mi_name,
264 NULL, NULL);
265 /* throw in the towel, recovery hard & not worth it */
266 if (rv)
267 panic("builtin module \"%s\" init failed: %d",
268 modp[i]->mod_info->mi_name, rv);
269 }
270 }
271
272 out:
273 kernconfig_unlock();
274 if (rv != 0) {
275 for (i = 0; i < nmodinfo; i++) {
276 if (modp[i])
277 kmem_free(modp[i], sizeof(*modp[i]));
278 }
279 }
280 kmem_free(modp, sizeof(*modp) * nmodinfo);
281 return rv;
282 }
283
284 /*
285 * Optionally fini and remove builtin module from the kernel.
286 * Note: the module will now be unreachable except via mi && builtin_add.
287 */
288 int
289 module_builtin_remove(modinfo_t *mi, bool fini)
290 {
291 struct module *mod;
292 int rv = 0;
293
294 if (fini) {
295 rv = kauth_authorize_system(kauth_cred_get(),
296 KAUTH_SYSTEM_MODULE, 0, (void *)(uintptr_t)MODCTL_UNLOAD,
297 NULL, NULL);
298 if (rv)
299 return rv;
300
301 kernconfig_lock();
302 rv = module_do_unload(mi->mi_name, true);
303 if (rv) {
304 goto out;
305 }
306 } else {
307 kernconfig_lock();
308 }
309 TAILQ_FOREACH(mod, &module_builtins, mod_chain) {
310 if (strcmp(mod->mod_info->mi_name, mi->mi_name) == 0)
311 break;
312 }
313 if (mod) {
314 TAILQ_REMOVE(&module_builtins, mod, mod_chain);
315 module_builtinlist--;
316 } else {
317 KASSERT(fini == false);
318 rv = ENOENT;
319 }
320
321 out:
322 kernconfig_unlock();
323 return rv;
324 }
325
326 /*
327 * module_init:
328 *
329 * Initialize the module subsystem.
330 */
331 void
332 module_init(void)
333 {
334 __link_set_decl(modules, modinfo_t);
335 extern struct vm_map *module_map;
336 modinfo_t *const *mip;
337 int rv;
338
339 if (module_map == NULL) {
340 module_map = kernel_map;
341 }
342 cv_init(&module_thread_cv, "mod_unld");
343 mutex_init(&module_thread_lock, MUTEX_DEFAULT, IPL_NONE);
344
345 #ifdef MODULAR /* XXX */
346 module_init_md();
347 #endif
348
349 if (!module_machine)
350 module_machine = machine;
351 #if __NetBSD_Version__ / 1000000 % 100 == 99 /* -current */
352 snprintf(module_base, sizeof(module_base), "/stand/%s/%s/modules",
353 module_machine, osrelease);
354 #else /* release */
355 snprintf(module_base, sizeof(module_base), "/stand/%s/%d.%d/modules",
356 module_machine, __NetBSD_Version__ / 100000000,
357 __NetBSD_Version__ / 1000000 % 100);
358 #endif
359
360 module_listener = kauth_listen_scope(KAUTH_SCOPE_SYSTEM,
361 module_listener_cb, NULL);
362
363 __link_set_foreach(mip, modules) {
364 if ((rv = module_builtin_add(mip, 1, false)) != 0)
365 module_error("builtin %s failed: %d\n",
366 (*mip)->mi_name, rv);
367 }
368
369 sysctl_module_setup();
370 }
371
372 /*
373 * module_start_unload_thread:
374 *
375 * Start the auto unload kthread.
376 */
377 void
378 module_start_unload_thread(void)
379 {
380 int error;
381
382 error = kthread_create(PRI_VM, KTHREAD_MPSAFE, NULL, module_thread,
383 NULL, NULL, "modunload");
384 if (error != 0)
385 panic("module_init: %d", error);
386 }
387
388 /*
389 * module_builtin_require_force
390 *
391 * Require MODCTL_MUST_FORCE to load any built-in modules that have
392 * not yet been initialized
393 */
394 void
395 module_builtin_require_force(void)
396 {
397 module_t *mod;
398
399 kernconfig_lock();
400 TAILQ_FOREACH(mod, &module_builtins, mod_chain) {
401 module_require_force(mod);
402 }
403 kernconfig_unlock();
404 }
405
406 static struct sysctllog *module_sysctllog;
407
408 static void
409 sysctl_module_setup(void)
410 {
411 const struct sysctlnode *node = NULL;
412
413 sysctl_createv(&module_sysctllog, 0, NULL, NULL,
414 CTLFLAG_PERMANENT,
415 CTLTYPE_NODE, "kern", NULL,
416 NULL, 0, NULL, 0,
417 CTL_KERN, CTL_EOL);
418 sysctl_createv(&module_sysctllog, 0, NULL, &node,
419 CTLFLAG_PERMANENT,
420 CTLTYPE_NODE, "module",
421 SYSCTL_DESCR("Module options"),
422 NULL, 0, NULL, 0,
423 CTL_KERN, CTL_CREATE, CTL_EOL);
424
425 if (node == NULL)
426 return;
427
428 sysctl_createv(&module_sysctllog, 0, &node, NULL,
429 CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
430 CTLTYPE_BOOL, "autoload",
431 SYSCTL_DESCR("Enable automatic load of modules"),
432 NULL, 0, &module_autoload_on, 0,
433 CTL_CREATE, CTL_EOL);
434 sysctl_createv(&module_sysctllog, 0, &node, NULL,
435 CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
436 CTLTYPE_BOOL, "verbose",
437 SYSCTL_DESCR("Enable verbose output"),
438 NULL, 0, &module_verbose_on, 0,
439 CTL_CREATE, CTL_EOL);
440 }
441
442 /*
443 * module_init_class:
444 *
445 * Initialize all built-in and pre-loaded modules of the
446 * specified class.
447 */
448 void
449 module_init_class(modclass_t class)
450 {
451 TAILQ_HEAD(, module) bi_fail = TAILQ_HEAD_INITIALIZER(bi_fail);
452 module_t *mod;
453 modinfo_t *mi;
454
455 kernconfig_lock();
456 /*
457 * Builtins first. These will not depend on pre-loaded modules
458 * (because the kernel would not link).
459 */
460 do {
461 TAILQ_FOREACH(mod, &module_builtins, mod_chain) {
462 mi = mod->mod_info;
463 if (!MODULE_CLASS_MATCH(mi, class))
464 continue;
465 /*
466 * If initializing a builtin module fails, don't try
467 * to load it again. But keep it around and queue it
468 * on the builtins list after we're done with module
469 * init. Don't set it to MODFLG_MUST_FORCE in case a
470 * future attempt to initialize can be successful.
471 * (If the module has previously been set to
472 * MODFLG_MUST_FORCE, don't try to override that!)
473 */
474 if (mod->mod_flags & MODFLG_MUST_FORCE ||
475 module_do_builtin(mi->mi_name, NULL, NULL) != 0) {
476 TAILQ_REMOVE(&module_builtins, mod, mod_chain);
477 TAILQ_INSERT_TAIL(&bi_fail, mod, mod_chain);
478 }
479 break;
480 }
481 } while (mod != NULL);
482
483 /*
484 * Now preloaded modules. These will be pulled off the
485 * list as we call module_do_load();
486 */
487 do {
488 TAILQ_FOREACH(mod, &module_bootlist, mod_chain) {
489 mi = mod->mod_info;
490 if (!MODULE_CLASS_MATCH(mi, class))
491 continue;
492 module_do_load(mi->mi_name, false, 0, NULL, NULL,
493 class, false);
494 break;
495 }
496 } while (mod != NULL);
497
498 /* return failed builtin modules to builtin list */
499 while ((mod = TAILQ_FIRST(&bi_fail)) != NULL) {
500 TAILQ_REMOVE(&bi_fail, mod, mod_chain);
501 TAILQ_INSERT_TAIL(&module_builtins, mod, mod_chain);
502 }
503
504 kernconfig_unlock();
505 }
506
507 /*
508 * module_compatible:
509 *
510 * Return true if the two supplied kernel versions are said to
511 * have the same binary interface for kernel code. The entire
512 * version is signficant for the development tree (-current),
513 * major and minor versions are significant for official
514 * releases of the system.
515 */
516 bool
517 module_compatible(int v1, int v2)
518 {
519
520 #if __NetBSD_Version__ / 1000000 % 100 == 99 /* -current */
521 return v1 == v2;
522 #else /* release */
523 return abs(v1 - v2) < 10000;
524 #endif
525 }
526
527 /*
528 * module_load:
529 *
530 * Load a single module from the file system.
531 */
532 int
533 module_load(const char *filename, int flags, prop_dictionary_t props,
534 modclass_t class)
535 {
536 int error;
537
538 /* Authorize. */
539 error = kauth_authorize_system(kauth_cred_get(), KAUTH_SYSTEM_MODULE,
540 0, (void *)(uintptr_t)MODCTL_LOAD, NULL, NULL);
541 if (error != 0) {
542 return error;
543 }
544
545 kernconfig_lock();
546 error = module_do_load(filename, false, flags, props, NULL, class,
547 false);
548 kernconfig_unlock();
549
550 return error;
551 }
552
553 /*
554 * module_autoload:
555 *
556 * Load a single module from the file system, system initiated.
557 */
558 int
559 module_autoload(const char *filename, modclass_t class)
560 {
561 int error;
562
563 kernconfig_lock();
564
565 /* Nothing if the user has disabled it. */
566 if (!module_autoload_on) {
567 kernconfig_unlock();
568 return EPERM;
569 }
570
571 /* Disallow path separators and magic symlinks. */
572 if (strchr(filename, '/') != NULL || strchr(filename, '@') != NULL ||
573 strchr(filename, '.') != NULL) {
574 kernconfig_unlock();
575 return EPERM;
576 }
577
578 /* Authorize. */
579 error = kauth_authorize_system(kauth_cred_get(), KAUTH_SYSTEM_MODULE,
580 0, (void *)(uintptr_t)MODCTL_LOAD, (void *)(uintptr_t)1, NULL);
581
582 if (error == 0)
583 error = module_do_load(filename, false, 0, NULL, NULL, class,
584 true);
585
586 kernconfig_unlock();
587 return error;
588 }
589
590 /*
591 * module_unload:
592 *
593 * Find and unload a module by name.
594 */
595 int
596 module_unload(const char *name)
597 {
598 int error;
599
600 /* Authorize. */
601 error = kauth_authorize_system(kauth_cred_get(), KAUTH_SYSTEM_MODULE,
602 0, (void *)(uintptr_t)MODCTL_UNLOAD, NULL, NULL);
603 if (error != 0) {
604 return error;
605 }
606
607 kernconfig_lock();
608 error = module_do_unload(name, true);
609 kernconfig_unlock();
610
611 return error;
612 }
613
614 /*
615 * module_lookup:
616 *
617 * Look up a module by name.
618 */
619 module_t *
620 module_lookup(const char *name)
621 {
622 module_t *mod;
623
624 KASSERT(kernconfig_is_held());
625
626 TAILQ_FOREACH(mod, &module_list, mod_chain) {
627 if (strcmp(mod->mod_info->mi_name, name) == 0) {
628 break;
629 }
630 }
631
632 return mod;
633 }
634
635 /*
636 * module_hold:
637 *
638 * Add a single reference to a module. It's the caller's
639 * responsibility to ensure that the reference is dropped
640 * later.
641 */
642 int
643 module_hold(const char *name)
644 {
645 module_t *mod;
646
647 kernconfig_lock();
648 mod = module_lookup(name);
649 if (mod == NULL) {
650 kernconfig_unlock();
651 return ENOENT;
652 }
653 mod->mod_refcnt++;
654 kernconfig_unlock();
655
656 return 0;
657 }
658
659 /*
660 * module_rele:
661 *
662 * Release a reference acquired with module_hold().
663 */
664 void
665 module_rele(const char *name)
666 {
667 module_t *mod;
668
669 kernconfig_lock();
670 mod = module_lookup(name);
671 if (mod == NULL) {
672 kernconfig_unlock();
673 panic("module_rele: gone");
674 }
675 mod->mod_refcnt--;
676 kernconfig_unlock();
677 }
678
679 /*
680 * module_enqueue:
681 *
682 * Put a module onto the global list and update counters.
683 */
684 void
685 module_enqueue(module_t *mod)
686 {
687 int i;
688
689 KASSERT(kernconfig_is_held());
690
691 /*
692 * If there are requisite modules, put at the head of the queue.
693 * This is so that autounload can unload requisite modules with
694 * only one pass through the queue.
695 */
696 if (mod->mod_nrequired) {
697 TAILQ_INSERT_HEAD(&module_list, mod, mod_chain);
698
699 /* Add references to the requisite modules. */
700 for (i = 0; i < mod->mod_nrequired; i++) {
701 KASSERT(mod->mod_required[i] != NULL);
702 mod->mod_required[i]->mod_refcnt++;
703 }
704 } else {
705 TAILQ_INSERT_TAIL(&module_list, mod, mod_chain);
706 }
707 module_count++;
708 module_gen++;
709 }
710
711 /*
712 * module_do_builtin:
713 *
714 * Initialize a module from the list of modules that are
715 * already linked into the kernel.
716 */
717 static int
718 module_do_builtin(const char *name, module_t **modp, prop_dictionary_t props)
719 {
720 const char *p, *s;
721 char buf[MAXMODNAME];
722 modinfo_t *mi = NULL;
723 module_t *mod, *mod2, *mod_loaded, *prev_active;
724 size_t len;
725 int error;
726
727 KASSERT(kernconfig_is_held());
728
729 /*
730 * Search the list to see if we have a module by this name.
731 */
732 TAILQ_FOREACH(mod, &module_builtins, mod_chain) {
733 if (strcmp(mod->mod_info->mi_name, name) == 0) {
734 mi = mod->mod_info;
735 break;
736 }
737 }
738
739 /*
740 * Check to see if already loaded. This might happen if we
741 * were already loaded as a dependency.
742 */
743 if ((mod_loaded = module_lookup(name)) != NULL) {
744 KASSERT(mod == NULL);
745 if (modp)
746 *modp = mod_loaded;
747 return 0;
748 }
749
750 /* Note! This is from TAILQ, not immediate above */
751 if (mi == NULL) {
752 /*
753 * XXX: We'd like to panic here, but currently in some
754 * cases (such as nfsserver + nfs), the dependee can be
755 * succesfully linked without the dependencies.
756 */
757 module_error("can't find builtin dependency `%s'", name);
758 return ENOENT;
759 }
760
761 /*
762 * Initialize pre-requisites.
763 */
764 if (mi->mi_required != NULL) {
765 for (s = mi->mi_required; *s != '\0'; s = p) {
766 if (*s == ',')
767 s++;
768 p = s;
769 while (*p != '\0' && *p != ',')
770 p++;
771 len = min(p - s + 1, sizeof(buf));
772 strlcpy(buf, s, len);
773 if (buf[0] == '\0')
774 break;
775 if (mod->mod_nrequired == MAXMODDEPS - 1) {
776 module_error("too many required modules");
777 return EINVAL;
778 }
779 error = module_do_builtin(buf, &mod2, NULL);
780 if (error != 0) {
781 return error;
782 }
783 mod->mod_required[mod->mod_nrequired++] = mod2;
784 }
785 }
786
787 /*
788 * Try to initialize the module.
789 */
790 prev_active = module_active;
791 module_active = mod;
792 error = (*mi->mi_modcmd)(MODULE_CMD_INIT, props);
793 module_active = prev_active;
794 if (error != 0) {
795 module_error("builtin module `%s' "
796 "failed to init", mi->mi_name);
797 return error;
798 }
799
800 /* load always succeeds after this point */
801
802 TAILQ_REMOVE(&module_builtins, mod, mod_chain);
803 module_builtinlist--;
804 if (modp != NULL) {
805 *modp = mod;
806 }
807 module_enqueue(mod);
808 return 0;
809 }
810
811 /*
812 * module_do_load:
813 *
814 * Helper routine: load a module from the file system, or one
815 * pushed by the boot loader.
816 */
817 static int
818 module_do_load(const char *name, bool isdep, int flags,
819 prop_dictionary_t props, module_t **modp, modclass_t class,
820 bool autoload)
821 {
822 #define MODULE_MAX_DEPTH 6
823
824 TAILQ_HEAD(pending_t, module);
825 static int depth = 0;
826 static struct pending_t *pending_lists[MODULE_MAX_DEPTH];
827 struct pending_t *pending;
828 struct pending_t new_pending = TAILQ_HEAD_INITIALIZER(new_pending);
829 modinfo_t *mi;
830 module_t *mod, *mod2, *prev_active;
831 prop_dictionary_t filedict;
832 char buf[MAXMODNAME];
833 const char *s, *p;
834 int error;
835 size_t len;
836
837 KASSERT(kernconfig_is_held());
838
839 filedict = NULL;
840 error = 0;
841
842 /*
843 * Avoid recursing too far.
844 */
845 if (++depth > MODULE_MAX_DEPTH) {
846 module_error("recursion too deep");
847 depth--;
848 return EMLINK;
849 }
850
851 /*
852 * Set up the pending list for this depth. If this is a
853 * recursive entry, then use same list as for outer call,
854 * else use the locally allocated list. In either case,
855 * remember which one we're using.
856 */
857 if (isdep) {
858 KASSERT(depth > 1);
859 pending = pending_lists[depth - 2];
860 } else
861 pending = &new_pending;
862 pending_lists[depth - 1] = pending;
863
864 /*
865 * Search the list of disabled builtins first.
866 */
867 TAILQ_FOREACH(mod, &module_builtins, mod_chain) {
868 if (strcmp(mod->mod_info->mi_name, name) == 0) {
869 break;
870 }
871 }
872 if (mod) {
873 if ((mod->mod_flags & MODFLG_MUST_FORCE) &&
874 (flags & MODCTL_LOAD_FORCE) == 0) {
875 if (!autoload) {
876 module_error("use -f to reinstate "
877 "builtin module \"%s\"", name);
878 }
879 depth--;
880 return EPERM;
881 } else {
882 error = module_do_builtin(name, modp, props);
883 depth--;
884 return error;
885 }
886 }
887
888 /*
889 * Load the module and link. Before going to the file system,
890 * scan the list of modules loaded by the boot loader.
891 */
892 TAILQ_FOREACH(mod, &module_bootlist, mod_chain) {
893 if (strcmp(mod->mod_info->mi_name, name) == 0) {
894 TAILQ_REMOVE(&module_bootlist, mod, mod_chain);
895 break;
896 }
897 }
898 if (mod != NULL) {
899 TAILQ_INSERT_TAIL(pending, mod, mod_chain);
900 } else {
901 /*
902 * If a requisite module, check to see if it is
903 * already present.
904 */
905 if (isdep) {
906 mod = module_lookup(name);
907 if (mod != NULL) {
908 if (modp != NULL) {
909 *modp = mod;
910 }
911 depth--;
912 return 0;
913 }
914 }
915 mod = module_newmodule(MODULE_SOURCE_FILESYS);
916 if (mod == NULL) {
917 module_error("out of memory for `%s'", name);
918 depth--;
919 return ENOMEM;
920 }
921
922 error = module_load_vfs_vec(name, flags, autoload, mod,
923 &filedict);
924 if (error != 0) {
925 module_error("vfs load failed %d for `%s'", error,
926 name);
927 kmem_free(mod, sizeof(*mod));
928 depth--;
929 return error;
930 }
931 TAILQ_INSERT_TAIL(pending, mod, mod_chain);
932
933 error = module_fetch_info(mod);
934 if (error != 0) {
935 module_error("cannot fetch module info for `%s'",
936 name);
937 goto fail;
938 }
939 }
940
941 /*
942 * Check compatibility.
943 */
944 mi = mod->mod_info;
945 if (strlen(mi->mi_name) >= MAXMODNAME) {
946 error = EINVAL;
947 module_error("module name `%s' too long", mi->mi_name);
948 goto fail;
949 }
950 if (!module_compatible(mi->mi_version, __NetBSD_Version__)) {
951 module_error("module `%s' built for `%d', system `%d'",
952 mi->mi_name, mi->mi_version, __NetBSD_Version__);
953 if ((flags & MODCTL_LOAD_FORCE) != 0) {
954 module_error("forced load, system may be unstable");
955 } else {
956 error = EPROGMISMATCH;
957 goto fail;
958 }
959 }
960
961 /*
962 * If a specific kind of module was requested, ensure that we have
963 * a match.
964 */
965 if (!MODULE_CLASS_MATCH(mi, class)) {
966 module_incompat(mi, class);
967 error = ENOENT;
968 goto fail;
969 }
970
971 /*
972 * If loading a dependency, `name' is a plain module name.
973 * The name must match.
974 */
975 if (isdep && strcmp(mi->mi_name, name) != 0) {
976 module_error("dependency name mismatch (`%s' != `%s')",
977 name, mi->mi_name);
978 error = ENOENT;
979 goto fail;
980 }
981
982 /*
983 * Check to see if the module is already loaded. If so, we may
984 * have been recursively called to handle a dependency, so be sure
985 * to set modp.
986 */
987 if ((mod2 = module_lookup(mi->mi_name)) != NULL) {
988 if (modp != NULL)
989 *modp = mod2;
990 module_print("module `%s' already loaded", mi->mi_name);
991 error = EEXIST;
992 goto fail;
993 }
994
995 /*
996 * Block circular dependencies.
997 */
998 TAILQ_FOREACH(mod2, pending, mod_chain) {
999 if (mod == mod2) {
1000 continue;
1001 }
1002 if (strcmp(mod2->mod_info->mi_name, mi->mi_name) == 0) {
1003 error = EDEADLK;
1004 module_error("circular dependency detected for `%s'",
1005 mi->mi_name);
1006 goto fail;
1007 }
1008 }
1009
1010 /*
1011 * Now try to load any requisite modules.
1012 */
1013 if (mi->mi_required != NULL) {
1014 for (s = mi->mi_required; *s != '\0'; s = p) {
1015 if (*s == ',')
1016 s++;
1017 p = s;
1018 while (*p != '\0' && *p != ',')
1019 p++;
1020 len = p - s + 1;
1021 if (len >= MAXMODNAME) {
1022 error = EINVAL;
1023 module_error("required module name `%s'"
1024 " too long", mi->mi_required);
1025 goto fail;
1026 }
1027 strlcpy(buf, s, len);
1028 if (buf[0] == '\0')
1029 break;
1030 if (mod->mod_nrequired == MAXMODDEPS - 1) {
1031 error = EINVAL;
1032 module_error("too many required modules (%d)",
1033 mod->mod_nrequired);
1034 goto fail;
1035 }
1036 if (strcmp(buf, mi->mi_name) == 0) {
1037 error = EDEADLK;
1038 module_error("self-dependency detected for "
1039 "`%s'", mi->mi_name);
1040 goto fail;
1041 }
1042 error = module_do_load(buf, true, flags, NULL,
1043 &mod2, MODULE_CLASS_ANY, true);
1044 if (error != 0) {
1045 module_error("recursive load failed for `%s'",
1046 mi->mi_name);
1047 goto fail;
1048 }
1049 mod->mod_required[mod->mod_nrequired++] = mod2;
1050 }
1051 }
1052
1053 /*
1054 * We loaded all needed modules successfully: perform global
1055 * relocations and initialize.
1056 */
1057 error = kobj_affix(mod->mod_kobj, mi->mi_name);
1058 if (error != 0) {
1059 /* Cannot touch 'mi' as the module is now gone. */
1060 module_error("unable to affix module `%s'", name);
1061 goto fail2;
1062 }
1063
1064 if (filedict) {
1065 if (!module_merge_dicts(filedict, props)) {
1066 module_error("module properties failed");
1067 error = EINVAL;
1068 goto fail;
1069 }
1070 }
1071 prev_active = module_active;
1072 module_active = mod;
1073 error = (*mi->mi_modcmd)(MODULE_CMD_INIT, filedict ? filedict : props);
1074 module_active = prev_active;
1075 if (filedict) {
1076 prop_object_release(filedict);
1077 filedict = NULL;
1078 }
1079 if (error != 0) {
1080 module_error("modcmd function returned error %d for `%s'",
1081 error, mi->mi_name);
1082 goto fail;
1083 }
1084
1085 /*
1086 * Good, the module loaded successfully. Put it onto the
1087 * list and add references to its requisite modules.
1088 */
1089 TAILQ_REMOVE(pending, mod, mod_chain);
1090 module_enqueue(mod);
1091 if (modp != NULL) {
1092 *modp = mod;
1093 }
1094 if (autoload) {
1095 /*
1096 * Arrange to try unloading the module after
1097 * a short delay.
1098 */
1099 mod->mod_autotime = time_second + module_autotime;
1100 mod->mod_flags |= MODFLG_AUTO_LOADED;
1101 module_thread_kick();
1102 }
1103 depth--;
1104 return 0;
1105
1106 fail:
1107 kobj_unload(mod->mod_kobj);
1108 fail2:
1109 if (filedict != NULL) {
1110 prop_object_release(filedict);
1111 filedict = NULL;
1112 }
1113 TAILQ_REMOVE(pending, mod, mod_chain);
1114 kmem_free(mod, sizeof(*mod));
1115 depth--;
1116 return error;
1117 }
1118
1119 /*
1120 * module_do_unload:
1121 *
1122 * Helper routine: do the dirty work of unloading a module.
1123 */
1124 static int
1125 module_do_unload(const char *name, bool load_requires_force)
1126 {
1127 module_t *mod, *prev_active;
1128 int error;
1129 u_int i;
1130
1131 KASSERT(kernconfig_is_held());
1132 KASSERT(name != NULL);
1133
1134 mod = module_lookup(name);
1135 if (mod == NULL) {
1136 module_error("module `%s' not found", name);
1137 return ENOENT;
1138 }
1139 if (mod->mod_refcnt != 0) {
1140 module_print("module `%s' busy", name);
1141 return EBUSY;
1142 }
1143
1144 /*
1145 * Builtin secmodels are there to stay.
1146 */
1147 if (mod->mod_source == MODULE_SOURCE_KERNEL &&
1148 mod->mod_info->mi_class == MODULE_CLASS_SECMODEL) {
1149 return EPERM;
1150 }
1151
1152 prev_active = module_active;
1153 module_active = mod;
1154 error = (*mod->mod_info->mi_modcmd)(MODULE_CMD_FINI, NULL);
1155 module_active = prev_active;
1156 if (error != 0) {
1157 module_print("cannot unload module `%s' error=%d", name,
1158 error);
1159 return error;
1160 }
1161 module_count--;
1162 TAILQ_REMOVE(&module_list, mod, mod_chain);
1163 for (i = 0; i < mod->mod_nrequired; i++) {
1164 mod->mod_required[i]->mod_refcnt--;
1165 }
1166 module_print("unloaded module `%s'", name);
1167 if (mod->mod_kobj != NULL) {
1168 kobj_unload(mod->mod_kobj);
1169 }
1170 if (mod->mod_source == MODULE_SOURCE_KERNEL) {
1171 mod->mod_nrequired = 0; /* will be re-parsed */
1172 if (load_requires_force)
1173 module_require_force(mod);
1174 TAILQ_INSERT_TAIL(&module_builtins, mod, mod_chain);
1175 module_builtinlist++;
1176 } else {
1177 kmem_free(mod, sizeof(*mod));
1178 }
1179 module_gen++;
1180
1181 return 0;
1182 }
1183
1184 /*
1185 * module_prime:
1186 *
1187 * Push a module loaded by the bootloader onto our internal
1188 * list.
1189 */
1190 int
1191 module_prime(const char *name, void *base, size_t size)
1192 {
1193 module_t *mod;
1194 int error;
1195
1196 mod = module_newmodule(MODULE_SOURCE_BOOT);
1197 if (mod == NULL) {
1198 return ENOMEM;
1199 }
1200
1201 error = kobj_load_mem(&mod->mod_kobj, name, base, size);
1202 if (error != 0) {
1203 kmem_free(mod, sizeof(*mod));
1204 module_error("unable to load object pushed by boot loader");
1205 return error;
1206 }
1207 error = module_fetch_info(mod);
1208 if (error != 0) {
1209 kobj_unload(mod->mod_kobj);
1210 kmem_free(mod, sizeof(*mod));
1211 module_error("unable to load object pushed by boot loader");
1212 return error;
1213 }
1214
1215 TAILQ_INSERT_TAIL(&module_bootlist, mod, mod_chain);
1216
1217 return 0;
1218 }
1219
1220 /*
1221 * module_fetch_into:
1222 *
1223 * Fetch modinfo record from a loaded module.
1224 */
1225 static int
1226 module_fetch_info(module_t *mod)
1227 {
1228 int error;
1229 void *addr;
1230 size_t size;
1231
1232 /*
1233 * Find module info record and check compatibility.
1234 */
1235 error = kobj_find_section(mod->mod_kobj, "link_set_modules",
1236 &addr, &size);
1237 if (error != 0) {
1238 module_error("`link_set_modules' section not present");
1239 return error;
1240 }
1241 if (size != sizeof(modinfo_t **)) {
1242 module_error("`link_set_modules' section wrong size");
1243 return ENOEXEC;
1244 }
1245 mod->mod_info = *(modinfo_t **)addr;
1246
1247 return 0;
1248 }
1249
1250 /*
1251 * module_find_section:
1252 *
1253 * Allows a module that is being initialized to look up a section
1254 * within its ELF object.
1255 */
1256 int
1257 module_find_section(const char *name, void **addr, size_t *size)
1258 {
1259
1260 KASSERT(kernconfig_is_held());
1261 KASSERT(module_active != NULL);
1262
1263 return kobj_find_section(module_active->mod_kobj, name, addr, size);
1264 }
1265
1266 /*
1267 * module_thread:
1268 *
1269 * Automatically unload modules. We try once to unload autoloaded
1270 * modules after module_autotime seconds. If the system is under
1271 * severe memory pressure, we'll try unloading all modules.
1272 */
1273 static void
1274 module_thread(void *cookie)
1275 {
1276 module_t *mod, *next;
1277 modinfo_t *mi;
1278 int error;
1279
1280 for (;;) {
1281 kernconfig_lock();
1282 for (mod = TAILQ_FIRST(&module_list); mod != NULL; mod = next) {
1283 next = TAILQ_NEXT(mod, mod_chain);
1284
1285 /* skip built-in modules */
1286 if (mod->mod_source == MODULE_SOURCE_KERNEL)
1287 continue;
1288 /* skip modules that weren't auto-loaded */
1289 if ((mod->mod_flags & MODFLG_AUTO_LOADED) == 0)
1290 continue;
1291
1292 if (uvmexp.free < uvmexp.freemin) {
1293 module_thread_ticks = hz;
1294 } else if (mod->mod_autotime == 0) {
1295 continue;
1296 } else if (time_second < mod->mod_autotime) {
1297 module_thread_ticks = hz;
1298 continue;
1299 } else {
1300 mod->mod_autotime = 0;
1301 }
1302
1303 /*
1304 * If this module wants to avoid autounload then
1305 * skip it. Some modules can ping-pong in and out
1306 * because their use is transient but often.
1307 * Example: exec_script.
1308 */
1309 mi = mod->mod_info;
1310 error = (*mi->mi_modcmd)(MODULE_CMD_AUTOUNLOAD, NULL);
1311 if (error == 0 || error == ENOTTY) {
1312 (void)module_do_unload(mi->mi_name, false);
1313 }
1314 }
1315 kernconfig_unlock();
1316
1317 mutex_enter(&module_thread_lock);
1318 (void)cv_timedwait(&module_thread_cv, &module_thread_lock,
1319 module_thread_ticks);
1320 module_thread_ticks = 0;
1321 mutex_exit(&module_thread_lock);
1322 }
1323 }
1324
1325 /*
1326 * module_thread:
1327 *
1328 * Kick the module thread into action, perhaps because the
1329 * system is low on memory.
1330 */
1331 void
1332 module_thread_kick(void)
1333 {
1334
1335 mutex_enter(&module_thread_lock);
1336 module_thread_ticks = hz;
1337 cv_broadcast(&module_thread_cv);
1338 mutex_exit(&module_thread_lock);
1339 }
1340
1341 #ifdef DDB
1342 /*
1343 * module_whatis:
1344 *
1345 * Helper routine for DDB.
1346 */
1347 void
1348 module_whatis(uintptr_t addr, void (*pr)(const char *, ...))
1349 {
1350 module_t *mod;
1351 size_t msize;
1352 vaddr_t maddr;
1353
1354 TAILQ_FOREACH(mod, &module_list, mod_chain) {
1355 if (mod->mod_kobj == NULL) {
1356 continue;
1357 }
1358 if (kobj_stat(mod->mod_kobj, &maddr, &msize) != 0)
1359 continue;
1360 if (addr < maddr || addr >= maddr + msize) {
1361 continue;
1362 }
1363 (*pr)("%p is %p+%zu, in kernel module `%s'\n",
1364 (void *)addr, (void *)maddr,
1365 (size_t)(addr - maddr), mod->mod_info->mi_name);
1366 }
1367 }
1368
1369 /*
1370 * module_print_list:
1371 *
1372 * Helper routine for DDB.
1373 */
1374 void
1375 module_print_list(void (*pr)(const char *, ...))
1376 {
1377 const char *src;
1378 module_t *mod;
1379 size_t msize;
1380 vaddr_t maddr;
1381
1382 (*pr)("%16s %16s %8s %8s\n", "NAME", "TEXT/DATA", "SIZE", "SOURCE");
1383
1384 TAILQ_FOREACH(mod, &module_list, mod_chain) {
1385 switch (mod->mod_source) {
1386 case MODULE_SOURCE_KERNEL:
1387 src = "builtin";
1388 break;
1389 case MODULE_SOURCE_FILESYS:
1390 src = "filesys";
1391 break;
1392 case MODULE_SOURCE_BOOT:
1393 src = "boot";
1394 break;
1395 default:
1396 src = "unknown";
1397 break;
1398 }
1399 if (mod->mod_kobj == NULL) {
1400 maddr = 0;
1401 msize = 0;
1402 } else if (kobj_stat(mod->mod_kobj, &maddr, &msize) != 0)
1403 continue;
1404 (*pr)("%16s %16lx %8ld %8s\n", mod->mod_info->mi_name,
1405 (long)maddr, (long)msize, src);
1406 }
1407 }
1408 #endif /* DDB */
1409
1410 static bool
1411 module_merge_dicts(prop_dictionary_t existing_dict,
1412 const prop_dictionary_t new_dict)
1413 {
1414 prop_dictionary_keysym_t props_keysym;
1415 prop_object_iterator_t props_iter;
1416 prop_object_t props_obj;
1417 const char *props_key;
1418 bool error;
1419
1420 if (new_dict == NULL) { /* nothing to merge */
1421 return true;
1422 }
1423
1424 error = false;
1425 props_iter = prop_dictionary_iterator(new_dict);
1426 if (props_iter == NULL) {
1427 return false;
1428 }
1429
1430 while ((props_obj = prop_object_iterator_next(props_iter)) != NULL) {
1431 props_keysym = (prop_dictionary_keysym_t)props_obj;
1432 props_key = prop_dictionary_keysym_cstring_nocopy(props_keysym);
1433 props_obj = prop_dictionary_get_keysym(new_dict, props_keysym);
1434 if ((props_obj == NULL) || !prop_dictionary_set(existing_dict,
1435 props_key, props_obj)) {
1436 error = true;
1437 goto out;
1438 }
1439 }
1440 error = false;
1441
1442 out:
1443 prop_object_iterator_release(props_iter);
1444
1445 return !error;
1446 }
1447