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