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