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