kern_module.c revision 1.140 1 /* $NetBSD: kern_module.c,v 1.140 2019/12/12 16:36:25 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.140 2019/12/12 16:36:25 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/module_hook.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 struct vm_map *module_map;
62 const char *module_machine;
63 char module_base[MODULE_BASE_SIZE];
64
65 struct modlist module_list = TAILQ_HEAD_INITIALIZER(module_list);
66 struct modlist module_builtins = TAILQ_HEAD_INITIALIZER(module_builtins);
67 static struct modlist module_bootlist = TAILQ_HEAD_INITIALIZER(module_bootlist);
68
69 struct module_callbacks {
70 TAILQ_ENTRY(module_callbacks) modcb_list;
71 void (*modcb_load)(struct module *);
72 void (*modcb_unload)(struct module *);
73 };
74 TAILQ_HEAD(modcblist, module_callbacks);
75 static struct modcblist modcblist;
76
77 static module_t *module_netbsd;
78 static const modinfo_t module_netbsd_modinfo = {
79 .mi_version = __NetBSD_Version__,
80 .mi_class = MODULE_CLASS_MISC,
81 .mi_name = "netbsd"
82 };
83
84 static module_t *module_active;
85 bool module_verbose_on;
86 #ifdef MODULAR_DEFAULT_AUTOLOAD
87 bool module_autoload_on = true;
88 #else
89 bool module_autoload_on = false;
90 #endif
91 u_int module_count;
92 u_int module_builtinlist;
93 u_int module_autotime = 10;
94 u_int module_gen = 1;
95 static kcondvar_t module_thread_cv;
96 static kmutex_t module_thread_lock;
97 static int module_thread_ticks;
98 int (*module_load_vfs_vec)(const char *, int, bool, module_t *,
99 prop_dictionary_t *) = (void *)eopnotsupp;
100
101 static kauth_listener_t module_listener;
102
103 static specificdata_domain_t module_specificdata_domain;
104
105 /* Ensure that the kernel's link set isn't empty. */
106 static modinfo_t module_dummy;
107 __link_set_add_rodata(modules, module_dummy);
108
109 static module_t *module_newmodule(modsrc_t);
110 static void module_free(module_t *);
111 static void module_require_force(module_t *);
112 static int module_do_load(const char *, bool, int, prop_dictionary_t,
113 module_t **, modclass_t modclass, bool);
114 static int module_do_unload(const char *, bool);
115 static int module_do_builtin(const module_t *, const char *, module_t **,
116 prop_dictionary_t);
117 static int module_fetch_info(module_t *);
118 static void module_thread(void *);
119
120 static module_t *module_lookup(const char *);
121 static void module_enqueue(module_t *);
122
123 static bool module_merge_dicts(prop_dictionary_t, const prop_dictionary_t);
124
125 static void sysctl_module_setup(void);
126 static int sysctl_module_autotime(SYSCTLFN_PROTO);
127
128 static void module_callback_load(struct module *);
129 static void module_callback_unload(struct module *);
130
131 /* Locking/synchronization stuff for module hooks */
132
133 kmutex_t module_hook_mtx;
134 kcondvar_t module_hook_cv;
135 pserialize_t module_hook_psz;
136
137 #define MODULE_CLASS_MATCH(mi, modclass) \
138 ((modclass) == MODULE_CLASS_ANY || (modclass) == (mi)->mi_class)
139
140 static void
141 module_incompat(const modinfo_t *mi, int modclass)
142 {
143 module_error("incompatible module class for `%s' (%d != %d)",
144 mi->mi_name, modclass, mi->mi_class);
145 }
146
147 struct module *
148 module_kernel(void)
149 {
150
151 return module_netbsd;
152 }
153
154 /*
155 * module_error:
156 *
157 * Utility function: log an error.
158 */
159 void
160 module_error(const char *fmt, ...)
161 {
162 va_list ap;
163
164 va_start(ap, fmt);
165 printf("WARNING: module error: ");
166 vprintf(fmt, ap);
167 printf("\n");
168 va_end(ap);
169 }
170
171 /*
172 * module_print:
173 *
174 * Utility function: log verbose output.
175 */
176 void
177 module_print(const char *fmt, ...)
178 {
179 va_list ap;
180
181 if (module_verbose_on) {
182 va_start(ap, fmt);
183 printf("DEBUG: module: ");
184 vprintf(fmt, ap);
185 printf("\n");
186 va_end(ap);
187 }
188 }
189
190 /*
191 * module_name:
192 *
193 * Utility function: return the module's name.
194 */
195 const char *
196 module_name(struct module *mod)
197 {
198
199 return mod->mod_info->mi_name;
200 }
201
202 /*
203 * module_source:
204 *
205 * Utility function: return the module's source.
206 */
207 modsrc_t
208 module_source(struct module *mod)
209 {
210
211 return mod->mod_source;
212 }
213
214 static int
215 module_listener_cb(kauth_cred_t cred, kauth_action_t action, void *cookie,
216 void *arg0, void *arg1, void *arg2, void *arg3)
217 {
218 int result;
219
220 result = KAUTH_RESULT_DEFER;
221
222 if (action != KAUTH_SYSTEM_MODULE)
223 return result;
224
225 if ((uintptr_t)arg2 != 0) /* autoload */
226 result = KAUTH_RESULT_ALLOW;
227
228 return result;
229 }
230
231 /*
232 * Allocate a new module_t
233 */
234 static module_t *
235 module_newmodule(modsrc_t source)
236 {
237 module_t *mod;
238
239 mod = kmem_zalloc(sizeof(*mod), KM_SLEEP);
240 mod->mod_source = source;
241 specificdata_init(module_specificdata_domain, &mod->mod_sdref);
242 return mod;
243 }
244
245 /*
246 * Free a module_t
247 */
248 static void
249 module_free(module_t *mod)
250 {
251
252 specificdata_fini(module_specificdata_domain, &mod->mod_sdref);
253 if (mod->mod_required)
254 kmem_free(mod->mod_required, mod->mod_arequired *
255 sizeof(module_t *));
256 kmem_free(mod, sizeof(*mod));
257 }
258
259 /*
260 * Require the -f (force) flag to load a module
261 */
262 static void
263 module_require_force(struct module *mod)
264 {
265 SET(mod->mod_flags, MODFLG_MUST_FORCE);
266 }
267
268 /*
269 * Add modules to the builtin list. This can done at boottime or
270 * at runtime if the module is linked into the kernel with an
271 * external linker. All or none of the input will be handled.
272 * Optionally, the modules can be initialized. If they are not
273 * initialized, module_init_class() or module_load() can be used
274 * later, but these are not guaranteed to give atomic results.
275 */
276 int
277 module_builtin_add(modinfo_t *const *mip, size_t nmodinfo, bool init)
278 {
279 struct module **modp = NULL, *mod_iter;
280 int rv = 0, i, mipskip;
281
282 if (init) {
283 rv = kauth_authorize_system(kauth_cred_get(),
284 KAUTH_SYSTEM_MODULE, 0, (void *)(uintptr_t)MODCTL_LOAD,
285 (void *)(uintptr_t)1, NULL);
286 if (rv) {
287 return rv;
288 }
289 }
290
291 for (i = 0, mipskip = 0; i < nmodinfo; i++) {
292 if (mip[i] == &module_dummy) {
293 KASSERT(nmodinfo > 0);
294 nmodinfo--;
295 }
296 }
297 if (nmodinfo == 0)
298 return 0;
299
300 modp = kmem_zalloc(sizeof(*modp) * nmodinfo, KM_SLEEP);
301 for (i = 0, mipskip = 0; i < nmodinfo; i++) {
302 if (mip[i+mipskip] == &module_dummy) {
303 mipskip++;
304 continue;
305 }
306 modp[i] = module_newmodule(MODULE_SOURCE_KERNEL);
307 modp[i]->mod_info = mip[i+mipskip];
308 }
309 kernconfig_lock();
310
311 /* do this in three stages for error recovery and atomicity */
312
313 /* first check for presence */
314 for (i = 0; i < nmodinfo; i++) {
315 TAILQ_FOREACH(mod_iter, &module_builtins, mod_chain) {
316 if (strcmp(mod_iter->mod_info->mi_name,
317 modp[i]->mod_info->mi_name) == 0)
318 break;
319 }
320 if (mod_iter) {
321 rv = EEXIST;
322 goto out;
323 }
324
325 if (module_lookup(modp[i]->mod_info->mi_name) != NULL) {
326 rv = EEXIST;
327 goto out;
328 }
329 }
330
331 /* then add to list */
332 for (i = 0; i < nmodinfo; i++) {
333 TAILQ_INSERT_TAIL(&module_builtins, modp[i], mod_chain);
334 module_builtinlist++;
335 }
336
337 /* finally, init (if required) */
338 if (init) {
339 for (i = 0; i < nmodinfo; i++) {
340 rv = module_do_builtin(modp[i],
341 modp[i]->mod_info->mi_name, NULL, NULL);
342 /* throw in the towel, recovery hard & not worth it */
343 if (rv)
344 panic("%s: builtin module \"%s\" init failed:"
345 " %d", __func__,
346 modp[i]->mod_info->mi_name, rv);
347 }
348 }
349
350 out:
351 kernconfig_unlock();
352 if (rv != 0) {
353 for (i = 0; i < nmodinfo; i++) {
354 if (modp[i])
355 module_free(modp[i]);
356 }
357 }
358 kmem_free(modp, sizeof(*modp) * nmodinfo);
359 return rv;
360 }
361
362 /*
363 * Optionally fini and remove builtin module from the kernel.
364 * Note: the module will now be unreachable except via mi && builtin_add.
365 */
366 int
367 module_builtin_remove(modinfo_t *mi, bool fini)
368 {
369 struct module *mod;
370 int rv = 0;
371
372 if (fini) {
373 rv = kauth_authorize_system(kauth_cred_get(),
374 KAUTH_SYSTEM_MODULE, 0, (void *)(uintptr_t)MODCTL_UNLOAD,
375 NULL, NULL);
376 if (rv)
377 return rv;
378
379 kernconfig_lock();
380 rv = module_do_unload(mi->mi_name, true);
381 if (rv) {
382 goto out;
383 }
384 } else {
385 kernconfig_lock();
386 }
387 TAILQ_FOREACH(mod, &module_builtins, mod_chain) {
388 if (strcmp(mod->mod_info->mi_name, mi->mi_name) == 0)
389 break;
390 }
391 if (mod) {
392 TAILQ_REMOVE(&module_builtins, mod, mod_chain);
393 module_builtinlist--;
394 } else {
395 KASSERT(fini == false);
396 rv = ENOENT;
397 }
398
399 out:
400 kernconfig_unlock();
401 return rv;
402 }
403
404 /*
405 * module_init:
406 *
407 * Initialize the module subsystem.
408 */
409 void
410 module_init(void)
411 {
412 __link_set_decl(modules, modinfo_t);
413 extern struct vm_map *module_map;
414 modinfo_t *const *mip;
415 int rv;
416
417 if (module_map == NULL) {
418 module_map = kernel_map;
419 }
420 cv_init(&module_thread_cv, "mod_unld");
421 mutex_init(&module_thread_lock, MUTEX_DEFAULT, IPL_NONE);
422 TAILQ_INIT(&modcblist);
423
424 #ifdef MODULAR /* XXX */
425 module_init_md();
426 #endif
427
428 if (!module_machine)
429 module_machine = machine;
430 #if __NetBSD_Version__ / 1000000 % 100 == 99 /* -current */
431 snprintf(module_base, sizeof(module_base), "/stand/%s/%s/modules",
432 module_machine, osrelease);
433 #else /* release */
434 snprintf(module_base, sizeof(module_base), "/stand/%s/%d.%d/modules",
435 module_machine, __NetBSD_Version__ / 100000000,
436 __NetBSD_Version__ / 1000000 % 100);
437 #endif
438
439 module_listener = kauth_listen_scope(KAUTH_SCOPE_SYSTEM,
440 module_listener_cb, NULL);
441
442 __link_set_foreach(mip, modules) {
443 if ((rv = module_builtin_add(mip, 1, false)) != 0)
444 module_error("builtin %s failed: %d\n",
445 (*mip)->mi_name, rv);
446 }
447
448 sysctl_module_setup();
449 module_specificdata_domain = specificdata_domain_create();
450
451 module_netbsd = module_newmodule(MODULE_SOURCE_KERNEL);
452 module_netbsd->mod_refcnt = 1;
453 module_netbsd->mod_info = &module_netbsd_modinfo;
454
455 mutex_init(&module_hook_mtx, MUTEX_DEFAULT, IPL_NONE);
456 cv_init(&module_hook_cv, "mod_hook");
457 module_hook_psz = pserialize_create();
458 }
459
460 /*
461 * module_start_unload_thread:
462 *
463 * Start the auto unload kthread.
464 */
465 void
466 module_start_unload_thread(void)
467 {
468 int error;
469
470 error = kthread_create(PRI_VM, KTHREAD_MPSAFE, NULL, module_thread,
471 NULL, NULL, "modunload");
472 if (error != 0)
473 panic("%s: %d", __func__, error);
474 }
475
476 /*
477 * module_builtin_require_force
478 *
479 * Require MODCTL_MUST_FORCE to load any built-in modules that have
480 * not yet been initialized
481 */
482 void
483 module_builtin_require_force(void)
484 {
485 module_t *mod;
486
487 kernconfig_lock();
488 TAILQ_FOREACH(mod, &module_builtins, mod_chain) {
489 module_require_force(mod);
490 }
491 kernconfig_unlock();
492 }
493
494 static struct sysctllog *module_sysctllog;
495
496 static int
497 sysctl_module_autotime(SYSCTLFN_ARGS)
498 {
499 struct sysctlnode node;
500 int t, error;
501
502 t = *(int *)rnode->sysctl_data;
503
504 node = *rnode;
505 node.sysctl_data = &t;
506 error = sysctl_lookup(SYSCTLFN_CALL(&node));
507 if (error || newp == NULL)
508 return (error);
509
510 if (t < 0)
511 return (EINVAL);
512
513 *(int *)rnode->sysctl_data = t;
514 return (0);
515 }
516
517 static void
518 sysctl_module_setup(void)
519 {
520 const struct sysctlnode *node = NULL;
521
522 sysctl_createv(&module_sysctllog, 0, NULL, &node,
523 CTLFLAG_PERMANENT,
524 CTLTYPE_NODE, "module",
525 SYSCTL_DESCR("Module options"),
526 NULL, 0, NULL, 0,
527 CTL_KERN, CTL_CREATE, CTL_EOL);
528
529 if (node == NULL)
530 return;
531
532 sysctl_createv(&module_sysctllog, 0, &node, NULL,
533 CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
534 CTLTYPE_BOOL, "autoload",
535 SYSCTL_DESCR("Enable automatic load of modules"),
536 NULL, 0, &module_autoload_on, 0,
537 CTL_CREATE, CTL_EOL);
538 sysctl_createv(&module_sysctllog, 0, &node, NULL,
539 CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
540 CTLTYPE_BOOL, "verbose",
541 SYSCTL_DESCR("Enable verbose output"),
542 NULL, 0, &module_verbose_on, 0,
543 CTL_CREATE, CTL_EOL);
544 sysctl_createv(&module_sysctllog, 0, &node, NULL,
545 CTLFLAG_PERMANENT | CTLFLAG_READONLY,
546 CTLTYPE_STRING, "path",
547 SYSCTL_DESCR("Default module load path"),
548 NULL, 0, module_base, 0,
549 CTL_CREATE, CTL_EOL);
550 sysctl_createv(&module_sysctllog, 0, &node, NULL,
551 CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
552 CTLTYPE_INT, "autotime",
553 SYSCTL_DESCR("Auto-unload delay"),
554 sysctl_module_autotime, 0, &module_autotime, 0,
555 CTL_CREATE, CTL_EOL);
556 }
557
558 /*
559 * module_init_class:
560 *
561 * Initialize all built-in and pre-loaded modules of the
562 * specified class.
563 */
564 void
565 module_init_class(modclass_t modclass)
566 {
567 TAILQ_HEAD(, module) bi_fail = TAILQ_HEAD_INITIALIZER(bi_fail);
568 module_t *mod;
569 modinfo_t *mi;
570
571 kernconfig_lock();
572 /*
573 * Builtins first. These will not depend on pre-loaded modules
574 * (because the kernel would not link).
575 */
576 do {
577 TAILQ_FOREACH(mod, &module_builtins, mod_chain) {
578 mi = mod->mod_info;
579 if (!MODULE_CLASS_MATCH(mi, modclass))
580 continue;
581 /*
582 * If initializing a builtin module fails, don't try
583 * to load it again. But keep it around and queue it
584 * on the builtins list after we're done with module
585 * init. Don't set it to MODFLG_MUST_FORCE in case a
586 * future attempt to initialize can be successful.
587 * (If the module has previously been set to
588 * MODFLG_MUST_FORCE, don't try to override that!)
589 */
590 if (ISSET(mod->mod_flags, MODFLG_MUST_FORCE) ||
591 module_do_builtin(mod, mi->mi_name, NULL,
592 NULL) != 0) {
593 TAILQ_REMOVE(&module_builtins, mod, mod_chain);
594 TAILQ_INSERT_TAIL(&bi_fail, mod, mod_chain);
595 }
596 break;
597 }
598 } while (mod != NULL);
599
600 /*
601 * Now preloaded modules. These will be pulled off the
602 * list as we call module_do_load();
603 */
604 do {
605 TAILQ_FOREACH(mod, &module_bootlist, mod_chain) {
606 mi = mod->mod_info;
607 if (!MODULE_CLASS_MATCH(mi, modclass))
608 continue;
609 module_do_load(mi->mi_name, false, 0, NULL, NULL,
610 modclass, false);
611 break;
612 }
613 } while (mod != NULL);
614
615 /* return failed builtin modules to builtin list */
616 while ((mod = TAILQ_FIRST(&bi_fail)) != NULL) {
617 TAILQ_REMOVE(&bi_fail, mod, mod_chain);
618 TAILQ_INSERT_TAIL(&module_builtins, mod, mod_chain);
619 }
620
621 kernconfig_unlock();
622 }
623
624 /*
625 * module_compatible:
626 *
627 * Return true if the two supplied kernel versions are said to
628 * have the same binary interface for kernel code. The entire
629 * version is signficant for the development tree (-current),
630 * major and minor versions are significant for official
631 * releases of the system.
632 */
633 bool
634 module_compatible(int v1, int v2)
635 {
636
637 #if __NetBSD_Version__ / 1000000 % 100 == 99 /* -current */
638 return v1 == v2;
639 #else /* release */
640 return abs(v1 - v2) < 10000;
641 #endif
642 }
643
644 /*
645 * module_load:
646 *
647 * Load a single module from the file system.
648 */
649 int
650 module_load(const char *filename, int flags, prop_dictionary_t props,
651 modclass_t modclass)
652 {
653 module_t *mod;
654 int error;
655
656 /* Test if we already have the module loaded before
657 * authorizing so we have the opportunity to return EEXIST. */
658 kernconfig_lock();
659 mod = module_lookup(filename);
660 if (mod != NULL) {
661 module_print("%s module `%s' already loaded",
662 "requested", filename);
663 error = EEXIST;
664 goto out;
665 }
666
667 /* Authorize. */
668 error = kauth_authorize_system(kauth_cred_get(), KAUTH_SYSTEM_MODULE,
669 0, (void *)(uintptr_t)MODCTL_LOAD, NULL, NULL);
670 if (error != 0)
671 goto out;
672
673 error = module_do_load(filename, false, flags, props, NULL, modclass,
674 false);
675
676 out:
677 kernconfig_unlock();
678 return error;
679 }
680
681 /*
682 * module_autoload:
683 *
684 * Load a single module from the file system, system initiated.
685 */
686 int
687 module_autoload(const char *filename, modclass_t modclass)
688 {
689 int error;
690
691 kernconfig_lock();
692
693 /* Nothing if the user has disabled it. */
694 if (!module_autoload_on) {
695 kernconfig_unlock();
696 return EPERM;
697 }
698
699 /* Disallow path separators and magic symlinks. */
700 if (strchr(filename, '/') != NULL || strchr(filename, '@') != NULL ||
701 strchr(filename, '.') != NULL) {
702 kernconfig_unlock();
703 return EPERM;
704 }
705
706 /* Authorize. */
707 error = kauth_authorize_system(kauth_cred_get(), KAUTH_SYSTEM_MODULE,
708 0, (void *)(uintptr_t)MODCTL_LOAD, (void *)(uintptr_t)1, NULL);
709
710 if (error == 0)
711 error = module_do_load(filename, false, 0, NULL, NULL, modclass,
712 true);
713
714 kernconfig_unlock();
715 return error;
716 }
717
718 /*
719 * module_unload:
720 *
721 * Find and unload a module by name.
722 */
723 int
724 module_unload(const char *name)
725 {
726 int error;
727
728 /* Authorize. */
729 error = kauth_authorize_system(kauth_cred_get(), KAUTH_SYSTEM_MODULE,
730 0, (void *)(uintptr_t)MODCTL_UNLOAD, NULL, NULL);
731 if (error != 0) {
732 return error;
733 }
734
735 kernconfig_lock();
736 error = module_do_unload(name, true);
737 kernconfig_unlock();
738
739 return error;
740 }
741
742 /*
743 * module_lookup:
744 *
745 * Look up a module by name.
746 */
747 module_t *
748 module_lookup(const char *name)
749 {
750 module_t *mod;
751
752 KASSERT(kernconfig_is_held());
753
754 TAILQ_FOREACH(mod, &module_list, mod_chain) {
755 if (strcmp(mod->mod_info->mi_name, name) == 0)
756 break;
757 }
758
759 return mod;
760 }
761
762 /*
763 * module_hold:
764 *
765 * Add a single reference to a module. It's the caller's
766 * responsibility to ensure that the reference is dropped
767 * later.
768 */
769 void
770 module_hold(module_t *mod)
771 {
772
773 kernconfig_lock();
774 mod->mod_refcnt++;
775 kernconfig_unlock();
776 }
777
778 /*
779 * module_rele:
780 *
781 * Release a reference acquired with module_hold().
782 */
783 void
784 module_rele(module_t *mod)
785 {
786
787 kernconfig_lock();
788 KASSERT(mod->mod_refcnt > 0);
789 mod->mod_refcnt--;
790 kernconfig_unlock();
791 }
792
793 /*
794 * module_enqueue:
795 *
796 * Put a module onto the global list and update counters.
797 */
798 void
799 module_enqueue(module_t *mod)
800 {
801 int i;
802
803 KASSERT(kernconfig_is_held());
804
805 /*
806 * Put new entry at the head of the queue so autounload can unload
807 * requisite modules with only one pass through the queue.
808 */
809 TAILQ_INSERT_HEAD(&module_list, mod, mod_chain);
810 if (mod->mod_nrequired) {
811
812 /* Add references to the requisite modules. */
813 for (i = 0; i < mod->mod_nrequired; i++) {
814 KASSERT((*mod->mod_required)[i] != NULL);
815 (*mod->mod_required)[i]->mod_refcnt++;
816 }
817 }
818 module_count++;
819 module_gen++;
820 }
821
822 /*
823 * Our array of required module pointers starts with zero entries. If we
824 * need to add a new entry, and the list is already full, we reallocate a
825 * larger array, adding MAXMODDEPS entries.
826 */
827 static void
828 alloc_required(module_t *mod)
829 {
830 module_t *(*new)[], *(*old)[];
831 int areq;
832 int i;
833
834 if (mod->mod_nrequired >= mod->mod_arequired) {
835 areq = mod->mod_arequired + MAXMODDEPS;
836 old = mod->mod_required;
837 new = kmem_zalloc(areq * sizeof(module_t *), KM_SLEEP);
838 for (i = 0; i < mod->mod_arequired; i++)
839 (*new)[i] = (*old)[i];
840 mod->mod_required = new;
841 if (old)
842 kmem_free(old, mod->mod_arequired * sizeof(module_t *));
843 mod->mod_arequired = areq;
844 }
845 }
846
847 /*
848 * module_do_builtin:
849 *
850 * Initialize a module from the list of modules that are
851 * already linked into the kernel.
852 */
853 static int
854 module_do_builtin(const module_t *pmod, const char *name, module_t **modp,
855 prop_dictionary_t props)
856 {
857 const char *p, *s;
858 char buf[MAXMODNAME];
859 modinfo_t *mi = NULL;
860 module_t *mod, *mod2, *mod_loaded, *prev_active;
861 size_t len;
862 int error;
863
864 KASSERT(kernconfig_is_held());
865
866 /*
867 * Search the list to see if we have a module by this name.
868 */
869 TAILQ_FOREACH(mod, &module_builtins, mod_chain) {
870 if (strcmp(mod->mod_info->mi_name, name) == 0) {
871 mi = mod->mod_info;
872 break;
873 }
874 }
875
876 /*
877 * Check to see if already loaded. This might happen if we
878 * were already loaded as a dependency.
879 */
880 if ((mod_loaded = module_lookup(name)) != NULL) {
881 KASSERT(mod == NULL);
882 if (modp)
883 *modp = mod_loaded;
884 return 0;
885 }
886
887 /* Note! This is from TAILQ, not immediate above */
888 if (mi == NULL) {
889 /*
890 * XXX: We'd like to panic here, but currently in some
891 * cases (such as nfsserver + nfs), the dependee can be
892 * succesfully linked without the dependencies.
893 */
894 module_error("built-in module %s can't find builtin "
895 "dependency `%s'", pmod->mod_info->mi_name, name);
896 return ENOENT;
897 }
898
899 /*
900 * Initialize pre-requisites.
901 */
902 KASSERT(mod->mod_required == NULL);
903 KASSERT(mod->mod_arequired == 0);
904 KASSERT(mod->mod_nrequired == 0);
905 if (mi->mi_required != NULL) {
906 for (s = mi->mi_required; *s != '\0'; s = p) {
907 if (*s == ',')
908 s++;
909 p = s;
910 while (*p != '\0' && *p != ',')
911 p++;
912 len = uimin(p - s + 1, sizeof(buf));
913 strlcpy(buf, s, len);
914 if (buf[0] == '\0')
915 break;
916 alloc_required(mod);
917 error = module_do_builtin(mod, buf, &mod2, NULL);
918 if (error != 0) {
919 module_error("built-in module %s prerequisite "
920 "%s failed, error %d", name, buf, error);
921 goto fail;
922 }
923 (*mod->mod_required)[mod->mod_nrequired++] = mod2;
924 }
925 }
926
927 /*
928 * Try to initialize the module.
929 */
930 prev_active = module_active;
931 module_active = mod;
932 error = (*mi->mi_modcmd)(MODULE_CMD_INIT, props);
933 module_active = prev_active;
934 if (error != 0) {
935 module_error("built-in module %s failed its MODULE_CMD_INIT, "
936 "error %d", mi->mi_name, error);
937 goto fail;
938 }
939
940 /* load always succeeds after this point */
941
942 TAILQ_REMOVE(&module_builtins, mod, mod_chain);
943 module_builtinlist--;
944 if (modp != NULL) {
945 *modp = mod;
946 }
947 module_enqueue(mod);
948 return 0;
949
950 fail:
951 if (mod->mod_required)
952 kmem_free(mod->mod_required, mod->mod_arequired *
953 sizeof(module_t *));
954 mod->mod_arequired = 0;
955 mod->mod_nrequired = 0;
956 mod->mod_required = NULL;
957 return error;
958 }
959
960 /*
961 * module_load_sysctl
962 *
963 * Check to see if a non-builtin module has any SYSCTL_SETUP() routine(s)
964 * registered. If so, call it (them).
965 */
966
967 static void
968 module_load_sysctl(module_t *mod)
969 {
970 void (**ls_funcp)(struct sysctllog **);
971 void *ls_start;
972 size_t ls_size, count;
973 int error;
974
975 /*
976 * Built-in modules don't have a mod_kobj so we cannot search
977 * for their link_set_sysctl_funcs
978 */
979 if (mod->mod_source == MODULE_SOURCE_KERNEL)
980 return;
981
982 error = kobj_find_section(mod->mod_kobj, "link_set_sysctl_funcs",
983 &ls_start, &ls_size);
984 if (error == 0) {
985 count = ls_size / sizeof(ls_start);
986 ls_funcp = ls_start;
987 while (count--) {
988 (**ls_funcp)(&mod->mod_sysctllog);
989 ls_funcp++;
990 }
991 }
992 else
993 error = 0; /* no setup funcs registered */
994 }
995
996 /*
997 * module_do_load:
998 *
999 * Helper routine: load a module from the file system, or one
1000 * pushed by the boot loader.
1001 */
1002 static int
1003 module_do_load(const char *name, bool isdep, int flags,
1004 prop_dictionary_t props, module_t **modp, modclass_t modclass,
1005 bool autoload)
1006 {
1007 /* The pending list for this level of recursion */
1008 TAILQ_HEAD(pending_t, module);
1009 struct pending_t *pending;
1010 struct pending_t new_pending = TAILQ_HEAD_INITIALIZER(new_pending);
1011
1012 /* The stack of pending lists */
1013 static SLIST_HEAD(pend_head, pend_entry) pend_stack =
1014 SLIST_HEAD_INITIALIZER(pend_stack);
1015 struct pend_entry {
1016 SLIST_ENTRY(pend_entry) pe_entry;
1017 struct pending_t *pe_pending;
1018 } my_pend_entry;
1019
1020 modinfo_t *mi;
1021 module_t *mod, *mod2, *prev_active;
1022 prop_dictionary_t filedict;
1023 char buf[MAXMODNAME];
1024 const char *s, *p;
1025 int error;
1026 size_t len;
1027
1028 KASSERT(kernconfig_is_held());
1029
1030 filedict = NULL;
1031 error = 0;
1032
1033 /*
1034 * Set up the pending list for this entry. If this is an
1035 * internal entry (for a dependency), then use the same list
1036 * as for the outer call; otherwise, it's an external entry
1037 * (possibly recursive, ie a module's xxx_modcmd(init, ...)
1038 * routine called us), so use the locally allocated list. In
1039 * either case, add it to our stack.
1040 */
1041 if (isdep) {
1042 KASSERT(SLIST_FIRST(&pend_stack) != NULL);
1043 pending = SLIST_FIRST(&pend_stack)->pe_pending;
1044 } else
1045 pending = &new_pending;
1046 my_pend_entry.pe_pending = pending;
1047 SLIST_INSERT_HEAD(&pend_stack, &my_pend_entry, pe_entry);
1048
1049 /*
1050 * Search the list of disabled builtins first.
1051 */
1052 TAILQ_FOREACH(mod, &module_builtins, mod_chain) {
1053 if (strcmp(mod->mod_info->mi_name, name) == 0) {
1054 break;
1055 }
1056 }
1057 if (mod) {
1058 if (ISSET(mod->mod_flags, MODFLG_MUST_FORCE) &&
1059 !ISSET(flags, MODCTL_LOAD_FORCE)) {
1060 if (!autoload) {
1061 module_error("use -f to reinstate "
1062 "builtin module `%s'", name);
1063 }
1064 SLIST_REMOVE_HEAD(&pend_stack, pe_entry);
1065 return EPERM;
1066 } else {
1067 SLIST_REMOVE_HEAD(&pend_stack, pe_entry);
1068 error = module_do_builtin(mod, name, modp, props);
1069 return error;
1070 }
1071 }
1072
1073 /*
1074 * Load the module and link. Before going to the file system,
1075 * scan the list of modules loaded by the boot loader.
1076 */
1077 TAILQ_FOREACH(mod, &module_bootlist, mod_chain) {
1078 if (strcmp(mod->mod_info->mi_name, name) == 0) {
1079 TAILQ_REMOVE(&module_bootlist, mod, mod_chain);
1080 break;
1081 }
1082 }
1083 if (mod != NULL) {
1084 TAILQ_INSERT_TAIL(pending, mod, mod_chain);
1085 } else {
1086 /*
1087 * Check to see if module is already present.
1088 */
1089 mod = module_lookup(name);
1090 if (mod != NULL) {
1091 if (modp != NULL) {
1092 *modp = mod;
1093 }
1094 module_print("%s module `%s' already loaded",
1095 isdep ? "dependent" : "requested", name);
1096 SLIST_REMOVE_HEAD(&pend_stack, pe_entry);
1097 return EEXIST;
1098 }
1099
1100 mod = module_newmodule(MODULE_SOURCE_FILESYS);
1101 if (mod == NULL) {
1102 module_error("out of memory for `%s'", name);
1103 SLIST_REMOVE_HEAD(&pend_stack, pe_entry);
1104 return ENOMEM;
1105 }
1106
1107 error = module_load_vfs_vec(name, flags, autoload, mod,
1108 &filedict);
1109 if (error != 0) {
1110 #ifdef DEBUG
1111 /*
1112 * The exec class of modules contains a list of
1113 * modules that is the union of all the modules
1114 * available for each architecture, so we don't
1115 * print an error if they are missing.
1116 */
1117 if ((modclass != MODULE_CLASS_EXEC || error != ENOENT)
1118 && root_device != NULL)
1119 module_error("vfs load failed for `%s', "
1120 "error %d", name, error);
1121 #endif
1122 SLIST_REMOVE_HEAD(&pend_stack, pe_entry);
1123 module_free(mod);
1124 return error;
1125 }
1126 TAILQ_INSERT_TAIL(pending, mod, mod_chain);
1127
1128 error = module_fetch_info(mod);
1129 if (error != 0) {
1130 module_error("cannot fetch info for `%s', error %d",
1131 name, error);
1132 goto fail;
1133 }
1134 }
1135
1136 /*
1137 * Check compatibility.
1138 */
1139 mi = mod->mod_info;
1140 if (strnlen(mi->mi_name, MAXMODNAME) >= MAXMODNAME) {
1141 error = EINVAL;
1142 module_error("module name `%s' longer than %d", mi->mi_name,
1143 MAXMODNAME);
1144 goto fail;
1145 }
1146 if (mi->mi_class <= MODULE_CLASS_ANY ||
1147 mi->mi_class >= MODULE_CLASS_MAX) {
1148 error = EINVAL;
1149 module_error("module `%s' has invalid class %d",
1150 mi->mi_name, mi->mi_class);
1151 goto fail;
1152 }
1153 if (!module_compatible(mi->mi_version, __NetBSD_Version__)) {
1154 module_error("module `%s' built for `%d', system `%d'",
1155 mi->mi_name, mi->mi_version, __NetBSD_Version__);
1156 if (ISSET(flags, MODCTL_LOAD_FORCE)) {
1157 module_error("forced load, system may be unstable");
1158 } else {
1159 error = EPROGMISMATCH;
1160 goto fail;
1161 }
1162 }
1163
1164 /*
1165 * If a specific kind of module was requested, ensure that we have
1166 * a match.
1167 */
1168 if (!MODULE_CLASS_MATCH(mi, modclass)) {
1169 module_incompat(mi, modclass);
1170 error = ENOENT;
1171 goto fail;
1172 }
1173
1174 /*
1175 * If loading a dependency, `name' is a plain module name.
1176 * The name must match.
1177 */
1178 if (isdep && strcmp(mi->mi_name, name) != 0) {
1179 module_error("dependency name mismatch (`%s' != `%s')",
1180 name, mi->mi_name);
1181 error = ENOENT;
1182 goto fail;
1183 }
1184
1185 /*
1186 * If we loaded a module from the filesystem, check the actual
1187 * module name (from the modinfo_t) to ensure another module
1188 * with the same name doesn't already exist. (There's no
1189 * guarantee the filename will match the module name, and the
1190 * dup-symbols check may not be sufficient.)
1191 */
1192 if (mod->mod_source == MODULE_SOURCE_FILESYS) {
1193 mod2 = module_lookup(mod->mod_info->mi_name);
1194 if ( mod2 && mod2 != mod) {
1195 module_error("module with name `%s' already loaded",
1196 mod2->mod_info->mi_name);
1197 error = EEXIST;
1198 if (modp != NULL)
1199 *modp = mod2;
1200 goto fail;
1201 }
1202 }
1203
1204 /*
1205 * Block circular dependencies.
1206 */
1207 TAILQ_FOREACH(mod2, pending, mod_chain) {
1208 if (mod == mod2) {
1209 continue;
1210 }
1211 if (strcmp(mod2->mod_info->mi_name, mi->mi_name) == 0) {
1212 error = EDEADLK;
1213 module_error("circular dependency detected for `%s'",
1214 mi->mi_name);
1215 goto fail;
1216 }
1217 }
1218
1219 /*
1220 * Now try to load any requisite modules.
1221 */
1222 if (mi->mi_required != NULL) {
1223 mod->mod_arequired = 0;
1224 for (s = mi->mi_required; *s != '\0'; s = p) {
1225 if (*s == ',')
1226 s++;
1227 p = s;
1228 while (*p != '\0' && *p != ',')
1229 p++;
1230 len = p - s + 1;
1231 if (len >= MAXMODNAME) {
1232 error = EINVAL;
1233 module_error("required module name `%s' "
1234 "longer than %d", mi->mi_required,
1235 MAXMODNAME);
1236 goto fail;
1237 }
1238 strlcpy(buf, s, len);
1239 if (buf[0] == '\0')
1240 break;
1241 alloc_required(mod);
1242 if (strcmp(buf, mi->mi_name) == 0) {
1243 error = EDEADLK;
1244 module_error("self-dependency detected for "
1245 "`%s'", mi->mi_name);
1246 goto fail;
1247 }
1248 error = module_do_load(buf, true, flags, NULL,
1249 &mod2, MODULE_CLASS_ANY, true);
1250 if (error != 0 && error != EEXIST) {
1251 module_error("recursive load failed for `%s' "
1252 "(`%s' required), error %d", mi->mi_name,
1253 buf, error);
1254 goto fail;
1255 }
1256 (*mod->mod_required)[mod->mod_nrequired++] = mod2;
1257 }
1258 }
1259
1260 /*
1261 * We loaded all needed modules successfully: perform global
1262 * relocations and initialize.
1263 */
1264 {
1265 char xname[MAXMODNAME];
1266
1267 /*
1268 * In case of error the entire module is gone, so we
1269 * need to save its name for possible error report.
1270 */
1271
1272 strlcpy(xname, mi->mi_name, MAXMODNAME);
1273 error = kobj_affix(mod->mod_kobj, mi->mi_name);
1274 if (error != 0) {
1275 module_error("unable to affix module `%s', error %d",
1276 xname, error);
1277 goto fail2;
1278 }
1279 }
1280
1281 if (filedict) {
1282 if (!module_merge_dicts(filedict, props)) {
1283 module_error("module properties failed for %s", name);
1284 error = EINVAL;
1285 goto fail;
1286 }
1287 }
1288
1289 prev_active = module_active;
1290 module_active = mod;
1291 error = (*mi->mi_modcmd)(MODULE_CMD_INIT, filedict ? filedict : props);
1292 module_active = prev_active;
1293 if (filedict) {
1294 prop_object_release(filedict);
1295 filedict = NULL;
1296 }
1297 if (error != 0) {
1298 module_error("modcmd(CMD_INIT) failed for `%s', error %d",
1299 mi->mi_name, error);
1300 goto fail;
1301 }
1302
1303 /*
1304 * If a recursive load already added a module with the same
1305 * name, abort.
1306 */
1307 mod2 = module_lookup(mi->mi_name);
1308 if (mod2 && mod2 != mod) {
1309 module_error("recursive load causes duplicate module `%s'",
1310 mi->mi_name);
1311 error = EEXIST;
1312 goto fail1;
1313 }
1314
1315 module_load_sysctl(mod); /* Set-up module's sysctl if any */
1316
1317 /*
1318 * Good, the module loaded successfully. Put it onto the
1319 * list and add references to its requisite modules.
1320 */
1321 TAILQ_REMOVE(pending, mod, mod_chain);
1322 module_enqueue(mod);
1323 if (modp != NULL) {
1324 *modp = mod;
1325 }
1326 if (autoload && module_autotime > 0) {
1327 /*
1328 * Arrange to try unloading the module after
1329 * a short delay unless auto-unload is disabled.
1330 */
1331 mod->mod_autotime = time_second + module_autotime;
1332 SET(mod->mod_flags, MODFLG_AUTO_LOADED);
1333 module_thread_kick();
1334 }
1335 SLIST_REMOVE_HEAD(&pend_stack, pe_entry);
1336 module_print("module `%s' loaded successfully", mi->mi_name);
1337 module_callback_load(mod);
1338 return 0;
1339
1340 fail1:
1341 (*mi->mi_modcmd)(MODULE_CMD_FINI, NULL);
1342 fail:
1343 kobj_unload(mod->mod_kobj);
1344 fail2:
1345 if (filedict != NULL) {
1346 prop_object_release(filedict);
1347 filedict = NULL;
1348 }
1349 TAILQ_REMOVE(pending, mod, mod_chain);
1350 SLIST_REMOVE_HEAD(&pend_stack, pe_entry);
1351 module_free(mod);
1352 return error;
1353 }
1354
1355 /*
1356 * module_do_unload:
1357 *
1358 * Helper routine: do the dirty work of unloading a module.
1359 */
1360 static int
1361 module_do_unload(const char *name, bool load_requires_force)
1362 {
1363 module_t *mod, *prev_active;
1364 int error;
1365 u_int i;
1366
1367 KASSERT(kernconfig_is_held());
1368 KASSERT(name != NULL);
1369
1370 module_print("unload requested for '%s' (%s)", name,
1371 load_requires_force ? "TRUE" : "FALSE");
1372 mod = module_lookup(name);
1373 if (mod == NULL) {
1374 module_error("module `%s' not found", name);
1375 return ENOENT;
1376 }
1377 if (mod->mod_refcnt != 0) {
1378 module_print("module `%s' busy (%d refs)", name,
1379 mod->mod_refcnt);
1380 return EBUSY;
1381 }
1382
1383 /*
1384 * Builtin secmodels are there to stay.
1385 */
1386 if (mod->mod_source == MODULE_SOURCE_KERNEL &&
1387 mod->mod_info->mi_class == MODULE_CLASS_SECMODEL) {
1388 module_print("cannot unload built-in secmodel module `%s'",
1389 name);
1390 return EPERM;
1391 }
1392
1393 prev_active = module_active;
1394 module_active = mod;
1395 module_callback_unload(mod);
1396
1397 /*
1398 * If there were any registered SYSCTL_SETUP funcs, make sure
1399 * we release the sysctl entries
1400 */
1401 if (mod->mod_sysctllog) {
1402 sysctl_teardown(&mod->mod_sysctllog);
1403 }
1404 error = (*mod->mod_info->mi_modcmd)(MODULE_CMD_FINI, NULL);
1405 module_active = prev_active;
1406 if (error != 0) {
1407 module_load_sysctl(mod); /* re-enable sysctl stuff */
1408 module_print("cannot unload module `%s' error=%d", name,
1409 error);
1410 return error;
1411 }
1412 module_count--;
1413 TAILQ_REMOVE(&module_list, mod, mod_chain);
1414 for (i = 0; i < mod->mod_nrequired; i++) {
1415 (*mod->mod_required)[i]->mod_refcnt--;
1416 }
1417 module_print("unloaded module `%s'", name);
1418 if (mod->mod_kobj != NULL) {
1419 kobj_unload(mod->mod_kobj);
1420 }
1421 if (mod->mod_source == MODULE_SOURCE_KERNEL) {
1422 if (mod->mod_required != NULL) {
1423 /*
1424 * release "required" resources - will be re-parsed
1425 * if the module is re-enabled
1426 */
1427 kmem_free(mod->mod_required,
1428 mod->mod_arequired * sizeof(module_t *));
1429 mod->mod_nrequired = 0;
1430 mod->mod_arequired = 0;
1431 mod->mod_required = NULL;
1432 }
1433 if (load_requires_force)
1434 module_require_force(mod);
1435 TAILQ_INSERT_TAIL(&module_builtins, mod, mod_chain);
1436 module_builtinlist++;
1437 } else {
1438 module_free(mod);
1439 }
1440 module_gen++;
1441
1442 return 0;
1443 }
1444
1445 /*
1446 * module_prime:
1447 *
1448 * Push a module loaded by the bootloader onto our internal
1449 * list.
1450 */
1451 int
1452 module_prime(const char *name, void *base, size_t size)
1453 {
1454 __link_set_decl(modules, modinfo_t);
1455 modinfo_t *const *mip;
1456 module_t *mod;
1457 int error;
1458
1459 /* Check for module name same as a built-in module */
1460
1461 __link_set_foreach(mip, modules) {
1462 if (*mip == &module_dummy)
1463 continue;
1464 if (strcmp((*mip)->mi_name, name) == 0) {
1465 module_error("module `%s' pushed by boot loader "
1466 "already exists", name);
1467 return EEXIST;
1468 }
1469 }
1470
1471 /* Also eliminate duplicate boolist entries */
1472
1473 TAILQ_FOREACH(mod, &module_bootlist, mod_chain) {
1474 if (strcmp(mod->mod_info->mi_name, name) == 0) {
1475 module_error("duplicate bootlist entry for module "
1476 "`%s'", name);
1477 return EEXIST;
1478 }
1479 }
1480
1481 mod = module_newmodule(MODULE_SOURCE_BOOT);
1482 if (mod == NULL) {
1483 return ENOMEM;
1484 }
1485
1486 error = kobj_load_mem(&mod->mod_kobj, name, base, size);
1487 if (error != 0) {
1488 module_free(mod);
1489 module_error("unable to load `%s' pushed by boot loader, "
1490 "error %d", name, error);
1491 return error;
1492 }
1493 error = module_fetch_info(mod);
1494 if (error != 0) {
1495 kobj_unload(mod->mod_kobj);
1496 module_free(mod);
1497 module_error("unable to fetch_info for `%s' pushed by boot "
1498 "loader, error %d", name, error);
1499 return error;
1500 }
1501
1502 TAILQ_INSERT_TAIL(&module_bootlist, mod, mod_chain);
1503
1504 return 0;
1505 }
1506
1507 /*
1508 * module_fetch_into:
1509 *
1510 * Fetch modinfo record from a loaded module.
1511 */
1512 static int
1513 module_fetch_info(module_t *mod)
1514 {
1515 int error;
1516 void *addr;
1517 size_t size;
1518
1519 /*
1520 * Find module info record and check compatibility.
1521 */
1522 error = kobj_find_section(mod->mod_kobj, "link_set_modules",
1523 &addr, &size);
1524 if (error != 0) {
1525 module_error("`link_set_modules' section not present, "
1526 "error %d", error);
1527 return error;
1528 }
1529 if (size != sizeof(modinfo_t **)) {
1530 module_error("`link_set_modules' section wrong size "
1531 "(got %zu, wanted %zu)", size, sizeof(modinfo_t **));
1532 return ENOEXEC;
1533 }
1534 mod->mod_info = *(modinfo_t **)addr;
1535
1536 return 0;
1537 }
1538
1539 /*
1540 * module_find_section:
1541 *
1542 * Allows a module that is being initialized to look up a section
1543 * within its ELF object.
1544 */
1545 int
1546 module_find_section(const char *name, void **addr, size_t *size)
1547 {
1548
1549 KASSERT(kernconfig_is_held());
1550 KASSERT(module_active != NULL);
1551
1552 return kobj_find_section(module_active->mod_kobj, name, addr, size);
1553 }
1554
1555 /*
1556 * module_thread:
1557 *
1558 * Automatically unload modules. We try once to unload autoloaded
1559 * modules after module_autotime seconds. If the system is under
1560 * severe memory pressure, we'll try unloading all modules, else if
1561 * module_autotime is zero, we don't try to unload, even if the
1562 * module was previously scheduled for unload.
1563 */
1564 static void
1565 module_thread(void *cookie)
1566 {
1567 module_t *mod, *next;
1568 modinfo_t *mi;
1569 int error;
1570
1571 for (;;) {
1572 kernconfig_lock();
1573 for (mod = TAILQ_FIRST(&module_list); mod != NULL; mod = next) {
1574 next = TAILQ_NEXT(mod, mod_chain);
1575
1576 /* skip built-in modules */
1577 if (mod->mod_source == MODULE_SOURCE_KERNEL)
1578 continue;
1579 /* skip modules that weren't auto-loaded */
1580 if (!ISSET(mod->mod_flags, MODFLG_AUTO_LOADED))
1581 continue;
1582
1583 if (uvmexp.free < uvmexp.freemin) {
1584 module_thread_ticks = hz;
1585 } else if (module_autotime == 0 ||
1586 mod->mod_autotime == 0) {
1587 continue;
1588 } else if (time_second < mod->mod_autotime) {
1589 module_thread_ticks = hz;
1590 continue;
1591 } else {
1592 mod->mod_autotime = 0;
1593 }
1594
1595 /*
1596 * If this module wants to avoid autounload then
1597 * skip it. Some modules can ping-pong in and out
1598 * because their use is transient but often.
1599 * Example: exec_script.
1600 */
1601 mi = mod->mod_info;
1602 error = (*mi->mi_modcmd)(MODULE_CMD_AUTOUNLOAD, NULL);
1603 if (error == 0 || error == ENOTTY) {
1604 (void)module_do_unload(mi->mi_name, false);
1605 } else
1606 module_print("module `%s' declined to be "
1607 "auto-unloaded error=%d", mi->mi_name,
1608 error);
1609 }
1610 kernconfig_unlock();
1611
1612 mutex_enter(&module_thread_lock);
1613 (void)cv_timedwait(&module_thread_cv, &module_thread_lock,
1614 module_thread_ticks);
1615 module_thread_ticks = 0;
1616 mutex_exit(&module_thread_lock);
1617 }
1618 }
1619
1620 /*
1621 * module_thread:
1622 *
1623 * Kick the module thread into action, perhaps because the
1624 * system is low on memory.
1625 */
1626 void
1627 module_thread_kick(void)
1628 {
1629
1630 mutex_enter(&module_thread_lock);
1631 module_thread_ticks = hz;
1632 cv_broadcast(&module_thread_cv);
1633 mutex_exit(&module_thread_lock);
1634 }
1635
1636 #ifdef DDB
1637 /*
1638 * module_whatis:
1639 *
1640 * Helper routine for DDB.
1641 */
1642 void
1643 module_whatis(uintptr_t addr, void (*pr)(const char *, ...))
1644 {
1645 module_t *mod;
1646 size_t msize;
1647 vaddr_t maddr;
1648
1649 TAILQ_FOREACH(mod, &module_list, mod_chain) {
1650 if (mod->mod_kobj == NULL) {
1651 continue;
1652 }
1653 if (kobj_stat(mod->mod_kobj, &maddr, &msize) != 0)
1654 continue;
1655 if (addr < maddr || addr >= maddr + msize) {
1656 continue;
1657 }
1658 (*pr)("%p is %p+%zu, in kernel module `%s'\n",
1659 (void *)addr, (void *)maddr,
1660 (size_t)(addr - maddr), mod->mod_info->mi_name);
1661 }
1662 }
1663
1664 /*
1665 * module_print_list:
1666 *
1667 * Helper routine for DDB.
1668 */
1669 void
1670 module_print_list(void (*pr)(const char *, ...))
1671 {
1672 const char *src;
1673 module_t *mod;
1674 size_t msize;
1675 vaddr_t maddr;
1676
1677 (*pr)("%16s %16s %8s %8s\n", "NAME", "TEXT/DATA", "SIZE", "SOURCE");
1678
1679 TAILQ_FOREACH(mod, &module_list, mod_chain) {
1680 switch (mod->mod_source) {
1681 case MODULE_SOURCE_KERNEL:
1682 src = "builtin";
1683 break;
1684 case MODULE_SOURCE_FILESYS:
1685 src = "filesys";
1686 break;
1687 case MODULE_SOURCE_BOOT:
1688 src = "boot";
1689 break;
1690 default:
1691 src = "unknown";
1692 break;
1693 }
1694 if (mod->mod_kobj == NULL) {
1695 maddr = 0;
1696 msize = 0;
1697 } else if (kobj_stat(mod->mod_kobj, &maddr, &msize) != 0)
1698 continue;
1699 (*pr)("%16s %16lx %8ld %8s\n", mod->mod_info->mi_name,
1700 (long)maddr, (long)msize, src);
1701 }
1702 }
1703 #endif /* DDB */
1704
1705 static bool
1706 module_merge_dicts(prop_dictionary_t existing_dict,
1707 const prop_dictionary_t new_dict)
1708 {
1709 prop_dictionary_keysym_t props_keysym;
1710 prop_object_iterator_t props_iter;
1711 prop_object_t props_obj;
1712 const char *props_key;
1713 bool error;
1714
1715 if (new_dict == NULL) { /* nothing to merge */
1716 return true;
1717 }
1718
1719 error = false;
1720 props_iter = prop_dictionary_iterator(new_dict);
1721 if (props_iter == NULL) {
1722 return false;
1723 }
1724
1725 while ((props_obj = prop_object_iterator_next(props_iter)) != NULL) {
1726 props_keysym = (prop_dictionary_keysym_t)props_obj;
1727 props_key = prop_dictionary_keysym_cstring_nocopy(props_keysym);
1728 props_obj = prop_dictionary_get_keysym(new_dict, props_keysym);
1729 if ((props_obj == NULL) || !prop_dictionary_set(existing_dict,
1730 props_key, props_obj)) {
1731 error = true;
1732 goto out;
1733 }
1734 }
1735 error = false;
1736
1737 out:
1738 prop_object_iterator_release(props_iter);
1739
1740 return !error;
1741 }
1742
1743 /*
1744 * module_specific_key_create:
1745 *
1746 * Create a key for subsystem module-specific data.
1747 */
1748 specificdata_key_t
1749 module_specific_key_create(specificdata_key_t *keyp, specificdata_dtor_t dtor)
1750 {
1751
1752 return specificdata_key_create(module_specificdata_domain, keyp, dtor);
1753 }
1754
1755 /*
1756 * module_specific_key_delete:
1757 *
1758 * Delete a key for subsystem module-specific data.
1759 */
1760 void
1761 module_specific_key_delete(specificdata_key_t key)
1762 {
1763
1764 return specificdata_key_delete(module_specificdata_domain, key);
1765 }
1766
1767 /*
1768 * module_getspecific:
1769 *
1770 * Return module-specific data corresponding to the specified key.
1771 */
1772 void *
1773 module_getspecific(module_t *mod, specificdata_key_t key)
1774 {
1775
1776 return specificdata_getspecific(module_specificdata_domain,
1777 &mod->mod_sdref, key);
1778 }
1779
1780 /*
1781 * module_setspecific:
1782 *
1783 * Set module-specific data corresponding to the specified key.
1784 */
1785 void
1786 module_setspecific(module_t *mod, specificdata_key_t key, void *data)
1787 {
1788
1789 specificdata_setspecific(module_specificdata_domain,
1790 &mod->mod_sdref, key, data);
1791 }
1792
1793 /*
1794 * module_register_callbacks:
1795 *
1796 * Register a new set of callbacks to be called on module load/unload.
1797 * Call the load callback on each existing module.
1798 * Return an opaque handle for unregistering these later.
1799 */
1800 void *
1801 module_register_callbacks(void (*load)(struct module *),
1802 void (*unload)(struct module *))
1803 {
1804 struct module_callbacks *modcb;
1805 struct module *mod;
1806
1807 modcb = kmem_alloc(sizeof(*modcb), KM_SLEEP);
1808 modcb->modcb_load = load;
1809 modcb->modcb_unload = unload;
1810
1811 kernconfig_lock();
1812 TAILQ_INSERT_TAIL(&modcblist, modcb, modcb_list);
1813 TAILQ_FOREACH(mod, &module_list, mod_chain)
1814 load(mod);
1815 kernconfig_unlock();
1816
1817 return modcb;
1818 }
1819
1820 /*
1821 * module_unregister_callbacks:
1822 *
1823 * Unregister a previously-registered set of module load/unload callbacks.
1824 * Call the unload callback on each existing module.
1825 */
1826 void
1827 module_unregister_callbacks(void *opaque)
1828 {
1829 struct module_callbacks *modcb;
1830 struct module *mod;
1831
1832 modcb = opaque;
1833 kernconfig_lock();
1834 TAILQ_FOREACH(mod, &module_list, mod_chain)
1835 modcb->modcb_unload(mod);
1836 TAILQ_REMOVE(&modcblist, modcb, modcb_list);
1837 kernconfig_unlock();
1838 kmem_free(modcb, sizeof(*modcb));
1839 }
1840
1841 /*
1842 * module_callback_load:
1843 *
1844 * Helper routine: call all load callbacks on a module being loaded.
1845 */
1846 static void
1847 module_callback_load(struct module *mod)
1848 {
1849 struct module_callbacks *modcb;
1850
1851 TAILQ_FOREACH(modcb, &modcblist, modcb_list) {
1852 modcb->modcb_load(mod);
1853 }
1854 }
1855
1856 /*
1857 * module_callback_unload:
1858 *
1859 * Helper routine: call all unload callbacks on a module being unloaded.
1860 */
1861 static void
1862 module_callback_unload(struct module *mod)
1863 {
1864 struct module_callbacks *modcb;
1865
1866 TAILQ_FOREACH(modcb, &modcblist, modcb_list) {
1867 modcb->modcb_unload(mod);
1868 }
1869 }
1870