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