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