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