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