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