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