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