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