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