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