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