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