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