Home | History | Annotate | Line # | Download | only in kern
kern_module.c revision 1.56
      1 /*	$NetBSD: kern_module.c,v 1.56 2010/01/01 03:22:13 dholland 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.56 2010/01/01 03:22:13 dholland Exp $");
     38 
     39 #define _MODULE_INTERNAL
     40 
     41 #ifdef _KERNEL_OPT
     42 #include "opt_ddb.h"
     43 #include "opt_modular.h"
     44 #endif
     45 
     46 #include <sys/param.h>
     47 #include <sys/systm.h>
     48 #include <sys/kernel.h>
     49 #include <sys/proc.h>
     50 #include <sys/kauth.h>
     51 #include <sys/kobj.h>
     52 #include <sys/kmem.h>
     53 #include <sys/module.h>
     54 #include <sys/kauth.h>
     55 #include <sys/kthread.h>
     56 #include <sys/sysctl.h>
     57 #include <sys/lock.h>
     58 
     59 #include <uvm/uvm_extern.h>
     60 
     61 #include <machine/stdarg.h>
     62 
     63 struct vm_map *module_map;
     64 char	module_base[MODULE_BASE_SIZE];
     65 
     66 struct modlist	module_list = TAILQ_HEAD_INITIALIZER(module_list);
     67 struct modlist	module_bootlist = TAILQ_HEAD_INITIALIZER(module_bootlist);
     68 static module_t	*module_active;
     69 static int	module_verbose_on;
     70 static int	module_autoload_on = 1;
     71 u_int		module_count;
     72 kmutex_t	module_lock;
     73 u_int		module_autotime = 10;
     74 u_int		module_gen = 1;
     75 static kcondvar_t module_thread_cv;
     76 static kmutex_t module_thread_lock;
     77 static int	module_thread_ticks;
     78 
     79 static kauth_listener_t	module_listener;
     80 
     81 /* Ensure that the kernel's link set isn't empty. */
     82 static modinfo_t module_dummy;
     83 __link_set_add_rodata(modules, module_dummy);
     84 
     85 static int	module_do_load(const char *, bool, int, prop_dictionary_t,
     86 		    module_t **, modclass_t class, bool);
     87 static int	module_do_unload(const char *);
     88 static int	module_do_builtin(const char *, module_t **);
     89 static int	module_fetch_info(module_t *);
     90 static void	module_thread(void *);
     91 
     92 static bool	module_merge_dicts(prop_dictionary_t, const prop_dictionary_t);
     93 
     94 int		module_eopnotsupp(void);
     95 
     96 int
     97 module_eopnotsupp(void)
     98 {
     99 
    100 	return EOPNOTSUPP;
    101 }
    102 __weak_alias(module_load_vfs,module_eopnotsupp);
    103 
    104 /*
    105  * module_error:
    106  *
    107  *	Utility function: log an error.
    108  */
    109 void
    110 module_error(const char *fmt, ...)
    111 {
    112 	va_list ap;
    113 
    114 	va_start(ap, fmt);
    115 	printf("WARNING: module error: ");
    116 	vprintf(fmt, ap);
    117 	printf("\n");
    118 	va_end(ap);
    119 }
    120 
    121 /*
    122  * module_print:
    123  *
    124  *	Utility function: log verbose output.
    125  */
    126 void
    127 module_print(const char *fmt, ...)
    128 {
    129 	va_list ap;
    130 
    131 	if (module_verbose_on) {
    132 		va_start(ap, fmt);
    133 		printf("DEBUG: module: ");
    134 		vprintf(fmt, ap);
    135 		printf("\n");
    136 		va_end(ap);
    137 	}
    138 }
    139 
    140 static int
    141 module_listener_cb(kauth_cred_t cred, kauth_action_t action, void *cookie,
    142     void *arg0, void *arg1, void *arg2, void *arg3)
    143 {
    144 	int result;
    145 
    146 	result = KAUTH_RESULT_DEFER;
    147 
    148 	if (action != KAUTH_SYSTEM_MODULE)
    149 		return result;
    150 
    151 	if ((uintptr_t)arg2 != 0)	/* autoload */
    152 		result = KAUTH_RESULT_ALLOW;
    153 
    154 	return result;
    155 }
    156 
    157 /*
    158  * module_init:
    159  *
    160  *	Initialize the module subsystem.
    161  */
    162 void
    163 module_init(void)
    164 {
    165 	extern struct vm_map *module_map;
    166 
    167 	if (module_map == NULL) {
    168 		module_map = kernel_map;
    169 	}
    170 	mutex_init(&module_lock, MUTEX_DEFAULT, IPL_NONE);
    171 	cv_init(&module_thread_cv, "modunload");
    172 	mutex_init(&module_thread_lock, MUTEX_DEFAULT, IPL_NONE);
    173 #ifdef MODULAR	/* XXX */
    174 	module_init_md();
    175 #endif
    176 
    177 #if __NetBSD_Version__ / 1000000 % 100 == 99	/* -current */
    178 	snprintf(module_base, sizeof(module_base), "/stand/%s/%s/modules",
    179 	    machine, osrelease);
    180 #else						/* release */
    181 	snprintf(module_base, sizeof(module_base), "/stand/%s/%d.%d/modules",
    182 	    machine, __NetBSD_Version__ / 100000000,
    183 	    __NetBSD_Version__ / 1000000 % 100);
    184 #endif
    185 
    186 	module_listener = kauth_listen_scope(KAUTH_SCOPE_SYSTEM,
    187 	    module_listener_cb, NULL);
    188 }
    189 
    190 /*
    191  * module_init2:
    192  *
    193  *	Start the auto unload kthread.
    194  */
    195 void
    196 module_init2(void)
    197 {
    198 	int error;
    199 
    200 	error = kthread_create(PRI_VM, KTHREAD_MPSAFE, NULL, module_thread,
    201 	    NULL, NULL, "modunload");
    202 	if (error != 0)
    203 		panic("module_init: %d", error);
    204 }
    205 
    206 SYSCTL_SETUP(sysctl_module_setup, "sysctl module setup")
    207 {
    208 	const struct sysctlnode *node = NULL;
    209 
    210 	sysctl_createv(clog, 0, NULL, NULL,
    211 		CTLFLAG_PERMANENT,
    212 		CTLTYPE_NODE, "kern", NULL,
    213 		NULL, 0, NULL, 0,
    214 		CTL_KERN, CTL_EOL);
    215 	sysctl_createv(clog, 0, NULL, &node,
    216 		CTLFLAG_PERMANENT,
    217 		CTLTYPE_NODE, "module",
    218 		SYSCTL_DESCR("Module options"),
    219 		NULL, 0, NULL, 0,
    220 		CTL_KERN, CTL_CREATE, CTL_EOL);
    221 
    222 	if (node == NULL)
    223 		return;
    224 
    225 	sysctl_createv(clog, 0, &node, NULL,
    226 		CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
    227 		CTLTYPE_INT, "autoload",
    228 		SYSCTL_DESCR("Enable automatic load of modules"),
    229 		NULL, 0, &module_autoload_on, 0,
    230 		CTL_CREATE, CTL_EOL);
    231 	sysctl_createv(clog, 0, &node, NULL,
    232 		CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
    233 		CTLTYPE_INT, "verbose",
    234 		SYSCTL_DESCR("Enable verbose output"),
    235 		NULL, 0, &module_verbose_on, 0,
    236 		CTL_CREATE, CTL_EOL);
    237 }
    238 
    239 /*
    240  * module_init_class:
    241  *
    242  *	Initialize all built-in and pre-loaded modules of the
    243  *	specified class.
    244  */
    245 void
    246 module_init_class(modclass_t class)
    247 {
    248 	__link_set_decl(modules, modinfo_t);
    249 	modinfo_t *const *mip, *mi;
    250 	module_t *mod;
    251 
    252 	mutex_enter(&module_lock);
    253 	/*
    254 	 * Builtins first.  These can't depend on pre-loaded modules.
    255 	 */
    256 	__link_set_foreach(mip, modules) {
    257 		mi = *mip;
    258 		if (mi == &module_dummy) {
    259 			continue;
    260 		}
    261 		if (class != MODULE_CLASS_ANY && class != mi->mi_class) {
    262 			continue;
    263 		}
    264 		(void)module_do_builtin(mi->mi_name, NULL);
    265 	}
    266 	/*
    267 	 * Now preloaded modules.  These will be pulled off the
    268 	 * list as we call module_do_load();
    269 	 */
    270 	do {
    271 		TAILQ_FOREACH(mod, &module_bootlist, mod_chain) {
    272 			mi = mod->mod_info;
    273 			if (class != MODULE_CLASS_ANY &&
    274 			    class != mi->mi_class)
    275 				continue;
    276 			module_do_load(mi->mi_name, false, 0, NULL, NULL,
    277 			    class, false);
    278 			break;
    279 		}
    280 	} while (mod != NULL);
    281 	mutex_exit(&module_lock);
    282 }
    283 
    284 /*
    285  * module_compatible:
    286  *
    287  *	Return true if the two supplied kernel versions are said to
    288  *	have the same binary interface for kernel code.  The entire
    289  *	version is signficant for the development tree (-current),
    290  *	major and minor versions are significant for official
    291  *	releases of the system.
    292  */
    293 bool
    294 module_compatible(int v1, int v2)
    295 {
    296 
    297 #if __NetBSD_Version__ / 1000000 % 100 == 99	/* -current */
    298 	return v1 == v2;
    299 #else						/* release */
    300 	return abs(v1 - v2) < 10000;
    301 #endif
    302 }
    303 
    304 /*
    305  * module_load:
    306  *
    307  *	Load a single module from the file system.
    308  */
    309 int
    310 module_load(const char *filename, int flags, prop_dictionary_t props,
    311 	    modclass_t class)
    312 {
    313 	int error;
    314 
    315 	/* Authorize. */
    316 	error = kauth_authorize_system(kauth_cred_get(), KAUTH_SYSTEM_MODULE,
    317 	    0, (void *)(uintptr_t)MODCTL_LOAD, NULL, NULL);
    318 	if (error != 0) {
    319 		return error;
    320 	}
    321 
    322 	mutex_enter(&module_lock);
    323 	error = module_do_load(filename, false, flags, props, NULL, class,
    324 	    false);
    325 	mutex_exit(&module_lock);
    326 
    327 	return error;
    328 }
    329 
    330 /*
    331  * module_autoload:
    332  *
    333  *	Load a single module from the file system, system initiated.
    334  */
    335 int
    336 module_autoload(const char *filename, modclass_t class)
    337 {
    338 	int error;
    339 
    340 	KASSERT(mutex_owned(&module_lock));
    341 
    342 	/* Nothing if the user has disabled it. */
    343 	if (!module_autoload_on) {
    344 		return EPERM;
    345 	}
    346 
    347         /* Disallow path separators and magic symlinks. */
    348         if (strchr(filename, '/') != NULL || strchr(filename, '@') != NULL ||
    349             strchr(filename, '.') != NULL) {
    350         	return EPERM;
    351 	}
    352 
    353 	/* Authorize. */
    354 	error = kauth_authorize_system(kauth_cred_get(), KAUTH_SYSTEM_MODULE,
    355 	    0, (void *)(uintptr_t)MODCTL_LOAD, (void *)(uintptr_t)1, NULL);
    356 	if (error != 0) {
    357 		return error;
    358 	}
    359 
    360 	return module_do_load(filename, false, 0, NULL, NULL, class, true);
    361 }
    362 
    363 /*
    364  * module_unload:
    365  *
    366  *	Find and unload a module by name.
    367  */
    368 int
    369 module_unload(const char *name)
    370 {
    371 	int error;
    372 
    373 	/* Authorize. */
    374 	error = kauth_authorize_system(kauth_cred_get(), KAUTH_SYSTEM_MODULE,
    375 	    0, (void *)(uintptr_t)MODCTL_UNLOAD, NULL, NULL);
    376 	if (error != 0) {
    377 		return error;
    378 	}
    379 
    380 	mutex_enter(&module_lock);
    381 	error = module_do_unload(name);
    382 	mutex_exit(&module_lock);
    383 
    384 	return error;
    385 }
    386 
    387 /*
    388  * module_lookup:
    389  *
    390  *	Look up a module by name.
    391  */
    392 module_t *
    393 module_lookup(const char *name)
    394 {
    395 	module_t *mod;
    396 
    397 	KASSERT(mutex_owned(&module_lock));
    398 
    399 	TAILQ_FOREACH(mod, &module_list, mod_chain) {
    400 		if (strcmp(mod->mod_info->mi_name, name) == 0) {
    401 			break;
    402 		}
    403 	}
    404 
    405 	return mod;
    406 }
    407 
    408 /*
    409  * module_hold:
    410  *
    411  *	Add a single reference to a module.  It's the caller's
    412  *	responsibility to ensure that the reference is dropped
    413  *	later.
    414  */
    415 int
    416 module_hold(const char *name)
    417 {
    418 	module_t *mod;
    419 
    420 	mutex_enter(&module_lock);
    421 	mod = module_lookup(name);
    422 	if (mod == NULL) {
    423 		mutex_exit(&module_lock);
    424 		return ENOENT;
    425 	}
    426 	mod->mod_refcnt++;
    427 	mutex_exit(&module_lock);
    428 
    429 	return 0;
    430 }
    431 
    432 /*
    433  * module_rele:
    434  *
    435  *	Release a reference acquired with module_hold().
    436  */
    437 void
    438 module_rele(const char *name)
    439 {
    440 	module_t *mod;
    441 
    442 	mutex_enter(&module_lock);
    443 	mod = module_lookup(name);
    444 	if (mod == NULL) {
    445 		mutex_exit(&module_lock);
    446 		panic("module_rele: gone");
    447 	}
    448 	mod->mod_refcnt--;
    449 	mutex_exit(&module_lock);
    450 }
    451 
    452 /*
    453  * module_enqueue:
    454  *
    455  *	Put a module onto the global list and update counters.
    456  */
    457 void
    458 module_enqueue(module_t *mod)
    459 {
    460 	int i;
    461 
    462 	KASSERT(mutex_owned(&module_lock));
    463 
    464 	/*
    465 	 * If there are requisite modules, put at the head of the queue.
    466 	 * This is so that autounload can unload requisite modules with
    467 	 * only one pass through the queue.
    468 	 */
    469 	if (mod->mod_nrequired) {
    470 		TAILQ_INSERT_HEAD(&module_list, mod, mod_chain);
    471 
    472 		/* Add references to the requisite modules. */
    473 		for (i = 0; i < mod->mod_nrequired; i++) {
    474 			KASSERT(mod->mod_required[i] != NULL);
    475 			mod->mod_required[i]->mod_refcnt++;
    476 		}
    477 	} else {
    478 		TAILQ_INSERT_TAIL(&module_list, mod, mod_chain);
    479 	}
    480 	module_count++;
    481 	module_gen++;
    482 }
    483 
    484 /*
    485  * module_do_builtin:
    486  *
    487  *	Initialize a single module from the list of modules that are
    488  *	built into the kernel (linked into the kernel image).
    489  */
    490 static int
    491 module_do_builtin(const char *name, module_t **modp)
    492 {
    493 	__link_set_decl(modules, modinfo_t);
    494 	modinfo_t *const *mip;
    495 	const char *p, *s;
    496 	char buf[MAXMODNAME];
    497 	modinfo_t *mi;
    498 	module_t *mod, *mod2;
    499 	size_t len;
    500 	int error;
    501 
    502 	KASSERT(mutex_owned(&module_lock));
    503 
    504 	/*
    505 	 * Check to see if already loaded.
    506 	 */
    507 	if ((mod = module_lookup(name)) != NULL) {
    508 		if (modp != NULL) {
    509 			*modp = mod;
    510 		}
    511 		return 0;
    512 	}
    513 
    514 	/*
    515 	 * Search the list to see if we have a module by this name.
    516 	 */
    517 	error = ENOENT;
    518 	__link_set_foreach(mip, modules) {
    519 		mi = *mip;
    520 		if (mi == &module_dummy) {
    521 			continue;
    522 		}
    523 		if (strcmp(mi->mi_name, name) == 0) {
    524 			error = 0;
    525 			break;
    526 		}
    527 	}
    528 	if (error != 0) {
    529 		module_error("can't find `%s'", name);
    530 		return error;
    531 	}
    532 
    533 	/*
    534 	 * Initialize pre-requisites.
    535 	 */
    536 	mod = kmem_zalloc(sizeof(*mod), KM_SLEEP);
    537 	if (mod == NULL) {
    538 		module_error("out of memory for `%s'", name);
    539 		return ENOMEM;
    540 	}
    541 	if (modp != NULL) {
    542 		*modp = mod;
    543 	}
    544 	if (mi->mi_required != NULL) {
    545 		for (s = mi->mi_required; *s != '\0'; s = p) {
    546 			if (*s == ',')
    547 				s++;
    548 			p = s;
    549 			while (*p != '\0' && *p != ',')
    550 				p++;
    551 			len = min(p - s + 1, sizeof(buf));
    552 			strlcpy(buf, s, len);
    553 			if (buf[0] == '\0')
    554 				break;
    555 			if (mod->mod_nrequired == MAXMODDEPS - 1) {
    556 				module_error("too many required modules");
    557 				kmem_free(mod, sizeof(*mod));
    558 				return EINVAL;
    559 			}
    560 			error = module_do_builtin(buf, &mod2);
    561 			if (error != 0) {
    562 				kmem_free(mod, sizeof(*mod));
    563 				return error;
    564 			}
    565 			mod->mod_required[mod->mod_nrequired++] = mod2;
    566 		}
    567 	}
    568 
    569 	/*
    570 	 * Try to initialize the module.
    571 	 */
    572 	KASSERT(module_active == NULL);
    573 	module_active = mod;
    574 	error = (*mi->mi_modcmd)(MODULE_CMD_INIT, NULL);
    575 	module_active = NULL;
    576 	if (error != 0) {
    577 		module_error("builtin module `%s' "
    578 		    "failed to init", mi->mi_name);
    579 		kmem_free(mod, sizeof(*mod));
    580 		return error;
    581 	}
    582 	if (mi->mi_class == MODULE_CLASS_SECMODEL)
    583 		secmodel_register();
    584 	mod->mod_info = mi;
    585 	mod->mod_source = MODULE_SOURCE_KERNEL;
    586 	module_enqueue(mod);
    587 	return 0;
    588 }
    589 
    590 /*
    591  * module_do_load:
    592  *
    593  *	Helper routine: load a module from the file system, or one
    594  *	pushed by the boot loader.
    595  */
    596 static int
    597 module_do_load(const char *name, bool isdep, int flags,
    598 	       prop_dictionary_t props, module_t **modp, modclass_t class,
    599 	       bool autoload)
    600 {
    601 	static TAILQ_HEAD(,module) pending = TAILQ_HEAD_INITIALIZER(pending);
    602 	static int depth;
    603 	const int maxdepth = 6;
    604 	modinfo_t *mi;
    605 	module_t *mod, *mod2;
    606 	prop_dictionary_t filedict;
    607 	char buf[MAXMODNAME];
    608 	const char *s, *p;
    609 	int error;
    610 	size_t len;
    611 
    612 	KASSERT(mutex_owned(&module_lock));
    613 
    614 	filedict = NULL;
    615 	error = 0;
    616 
    617 	/*
    618 	 * Avoid recursing too far.
    619 	 */
    620 	if (++depth > maxdepth) {
    621 		module_error("too many required modules");
    622 		depth--;
    623 		return EMLINK;
    624 	}
    625 
    626 	/*
    627 	 * Load the module and link.  Before going to the file system,
    628 	 * scan the list of modules loaded by the boot loader.  Just
    629 	 * before init is started the list of modules loaded at boot
    630 	 * will be purged.  Before init is started we can assume that
    631 	 * `name' is a module name and not a path name.
    632 	 */
    633 	TAILQ_FOREACH(mod, &module_bootlist, mod_chain) {
    634 		if (strcmp(mod->mod_info->mi_name, name) == 0) {
    635 			TAILQ_REMOVE(&module_bootlist, mod, mod_chain);
    636 			break;
    637 		}
    638 	}
    639 	if (mod != NULL) {
    640 		TAILQ_INSERT_TAIL(&pending, mod, mod_chain);
    641 	} else {
    642 		/*
    643 		 * If a requisite module, check to see if it is
    644 		 * already present.
    645 		 */
    646 		if (isdep) {
    647 			TAILQ_FOREACH(mod, &module_list, mod_chain) {
    648 				if (strcmp(mod->mod_info->mi_name, name) == 0) {
    649 					break;
    650 				}
    651 			}
    652 			if (mod != NULL) {
    653 				if (modp != NULL) {
    654 					*modp = mod;
    655 				}
    656 				depth--;
    657 				return 0;
    658 			}
    659 		}
    660 		mod = kmem_zalloc(sizeof(*mod), KM_SLEEP);
    661 		if (mod == NULL) {
    662 			module_error("out of memory for `%s'", name);
    663 			depth--;
    664 			return ENOMEM;
    665 		}
    666 
    667 		error = module_load_vfs(name, flags, autoload, mod, &filedict);
    668 		if (error != 0) {
    669 			kmem_free(mod, sizeof(*mod));
    670 			depth--;
    671 			return error;
    672 		}
    673 		mod->mod_source = MODULE_SOURCE_FILESYS;
    674 		TAILQ_INSERT_TAIL(&pending, mod, mod_chain);
    675 
    676 		error = module_fetch_info(mod);
    677 		if (error != 0) {
    678 			module_error("cannot fetch module info for `%s'",
    679 			    name);
    680 			goto fail;
    681 		}
    682 	}
    683 
    684 	/*
    685 	 * Check compatibility.
    686 	 */
    687 	mi = mod->mod_info;
    688 	if (strlen(mi->mi_name) >= MAXMODNAME) {
    689 		error = EINVAL;
    690 		module_error("module name `%s' too long", mi->mi_name);
    691 		goto fail;
    692 	}
    693 	if (!module_compatible(mi->mi_version, __NetBSD_Version__)) {
    694 		module_error("module built for `%d', system `%d'",
    695 		    mi->mi_version, __NetBSD_Version__);
    696 		if ((flags & MODCTL_LOAD_FORCE) != 0) {
    697 			module_error("forced load, system may be unstable");
    698 		} else {
    699 			error = EPROGMISMATCH;
    700 			goto fail;
    701 		}
    702 	}
    703 
    704 	/*
    705 	 * If a specific kind of module was requested, ensure that we have
    706 	 * a match.
    707 	 */
    708 	if (class != MODULE_CLASS_ANY && class != mi->mi_class) {
    709 		module_print("incompatible module class for `%s' (%d != %d)",
    710 		    name, class, mi->mi_class);
    711 		error = ENOENT;
    712 		goto fail;
    713 	}
    714 
    715 	/*
    716 	 * If loading a dependency, `name' is a plain module name.
    717 	 * The name must match.
    718 	 */
    719 	if (isdep && strcmp(mi->mi_name, name) != 0) {
    720 		module_error("dependency name mismatch (`%s' != `%s')",
    721 		    name, mi->mi_name);
    722 		error = ENOENT;
    723 		goto fail;
    724 	}
    725 
    726 	/*
    727 	 * Check to see if the module is already loaded.  If so, we may
    728 	 * have been recursively called to handle a dependency, so be sure
    729 	 * to set modp.
    730 	 */
    731 	if ((mod2 = module_lookup(mi->mi_name)) != NULL) {
    732 		if (modp != NULL)
    733 			*modp = mod2;
    734 		module_print("module `%s' already loaded", mi->mi_name);
    735 		error = EEXIST;
    736 		goto fail;
    737 	}
    738 
    739 	/*
    740 	 * Block circular dependencies.
    741 	 */
    742 	TAILQ_FOREACH(mod2, &pending, mod_chain) {
    743 		if (mod == mod2) {
    744 			continue;
    745 		}
    746 		if (strcmp(mod2->mod_info->mi_name, mi->mi_name) == 0) {
    747 		    	error = EDEADLK;
    748 			module_error("circular dependency detected for `%s'",
    749 			    mi->mi_name);
    750 		    	goto fail;
    751 		}
    752 	}
    753 
    754 	/*
    755 	 * Now try to load any requisite modules.
    756 	 */
    757 	if (mi->mi_required != NULL) {
    758 		for (s = mi->mi_required; *s != '\0'; s = p) {
    759 			if (*s == ',')
    760 				s++;
    761 			p = s;
    762 			while (*p != '\0' && *p != ',')
    763 				p++;
    764 			len = p - s + 1;
    765 			if (len >= MAXMODNAME) {
    766 				error = EINVAL;
    767 				module_error("required module name `%s'"
    768 				    " too long", mi->mi_required);
    769 				goto fail;
    770 			}
    771 			strlcpy(buf, s, len);
    772 			if (buf[0] == '\0')
    773 				break;
    774 			if (mod->mod_nrequired == MAXMODDEPS - 1) {
    775 				error = EINVAL;
    776 				module_error("too many required modules (%d)",
    777 				    mod->mod_nrequired);
    778 				goto fail;
    779 			}
    780 			if (strcmp(buf, mi->mi_name) == 0) {
    781 				error = EDEADLK;
    782 				module_error("self-dependency detected for "
    783 				   "`%s'", mi->mi_name);
    784 				goto fail;
    785 			}
    786 			error = module_do_load(buf, true, flags, NULL,
    787 			    &mod->mod_required[mod->mod_nrequired++],
    788 			    MODULE_CLASS_ANY, true);
    789 			if (error != 0)
    790 				goto fail;
    791 		}
    792 	}
    793 
    794 	/*
    795 	 * We loaded all needed modules successfully: perform global
    796 	 * relocations and initialize.
    797 	 */
    798 	error = kobj_affix(mod->mod_kobj, mi->mi_name);
    799 	if (error != 0) {
    800 		/* Cannot touch 'mi' as the module is now gone. */
    801 		module_error("unable to affix module `%s'", name);
    802 		goto fail2;
    803 	}
    804 
    805 	if (filedict) {
    806 		if (!module_merge_dicts(filedict, props)) {
    807 			module_error("module properties failed");
    808 			error = EINVAL;
    809 			goto fail;
    810 		}
    811 	}
    812 	KASSERT(module_active == NULL);
    813 	module_active = mod;
    814 	error = (*mi->mi_modcmd)(MODULE_CMD_INIT, filedict ? filedict : props);
    815 	module_active = NULL;
    816 	if (filedict) {
    817 		prop_object_release(filedict);
    818 		filedict = NULL;
    819 	}
    820 	if (error != 0) {
    821 		module_error("modcmd function returned error %d for `%s'",
    822 		    error, mi->mi_name);
    823 		goto fail;
    824 	}
    825 
    826 	if (mi->mi_class == MODULE_CLASS_SECMODEL)
    827 		secmodel_register();
    828 
    829 	/*
    830 	 * Good, the module loaded successfully.  Put it onto the
    831 	 * list and add references to its requisite modules.
    832 	 */
    833 	TAILQ_REMOVE(&pending, mod, mod_chain);
    834 	module_enqueue(mod);
    835 	if (modp != NULL) {
    836 		*modp = mod;
    837 	}
    838 	if (autoload) {
    839 		/*
    840 		 * Arrange to try unloading the module after
    841 		 * a short delay.
    842 		 */
    843 		mod->mod_autotime = time_second + module_autotime;
    844 		module_thread_kick();
    845 	}
    846 	depth--;
    847 	return 0;
    848 
    849  fail:
    850 	kobj_unload(mod->mod_kobj);
    851  fail2:
    852 	if (filedict != NULL) {
    853 		prop_object_release(filedict);
    854 		filedict = NULL;
    855 	}
    856 	TAILQ_REMOVE(&pending, mod, mod_chain);
    857 	kmem_free(mod, sizeof(*mod));
    858 	depth--;
    859 	return error;
    860 }
    861 
    862 /*
    863  * module_do_unload:
    864  *
    865  *	Helper routine: do the dirty work of unloading a module.
    866  */
    867 static int
    868 module_do_unload(const char *name)
    869 {
    870 	module_t *mod;
    871 	int error;
    872 	u_int i;
    873 
    874 	KASSERT(mutex_owned(&module_lock));
    875 
    876 	mod = module_lookup(name);
    877 	if (mod == NULL) {
    878 		module_error("module `%s' not found", name);
    879 		return ENOENT;
    880 	}
    881 	if (mod->mod_refcnt != 0 || mod->mod_source == MODULE_SOURCE_KERNEL) {
    882 		module_print("module `%s' busy", name);
    883 		return EBUSY;
    884 	}
    885 	KASSERT(module_active == NULL);
    886 	module_active = mod;
    887 	error = (*mod->mod_info->mi_modcmd)(MODULE_CMD_FINI, NULL);
    888 	module_active = NULL;
    889 	if (error != 0) {
    890 		module_print("cannot unload module `%s' error=%d", name,
    891 		    error);
    892 		return error;
    893 	}
    894 	if (mod->mod_info->mi_class == MODULE_CLASS_SECMODEL)
    895 		secmodel_deregister();
    896 	module_count--;
    897 	TAILQ_REMOVE(&module_list, mod, mod_chain);
    898 	for (i = 0; i < mod->mod_nrequired; i++) {
    899 		mod->mod_required[i]->mod_refcnt--;
    900 	}
    901 	if (mod->mod_kobj != NULL) {
    902 		kobj_unload(mod->mod_kobj);
    903 	}
    904 	kmem_free(mod, sizeof(*mod));
    905 	module_gen++;
    906 
    907 	return 0;
    908 }
    909 
    910 /*
    911  * module_prime:
    912  *
    913  *	Push a module loaded by the bootloader onto our internal
    914  *	list.
    915  */
    916 int
    917 module_prime(void *base, size_t size)
    918 {
    919 	module_t *mod;
    920 	int error;
    921 
    922 	mod = kmem_zalloc(sizeof(*mod), KM_SLEEP);
    923 	if (mod == NULL) {
    924 		return ENOMEM;
    925 	}
    926 	mod->mod_source = MODULE_SOURCE_BOOT;
    927 
    928 	error = kobj_load_mem(&mod->mod_kobj, base, size);
    929 	if (error != 0) {
    930 		kmem_free(mod, sizeof(*mod));
    931 		module_error("unable to load object pushed by boot loader");
    932 		return error;
    933 	}
    934 	error = module_fetch_info(mod);
    935 	if (error != 0) {
    936 		kobj_unload(mod->mod_kobj);
    937 		kmem_free(mod, sizeof(*mod));
    938 		module_error("unable to load object pushed by boot loader");
    939 		return error;
    940 	}
    941 
    942 	TAILQ_INSERT_TAIL(&module_bootlist, mod, mod_chain);
    943 
    944 	return 0;
    945 }
    946 
    947 /*
    948  * module_fetch_into:
    949  *
    950  *	Fetch modinfo record from a loaded module.
    951  */
    952 static int
    953 module_fetch_info(module_t *mod)
    954 {
    955 	int error;
    956 	void *addr;
    957 	size_t size;
    958 
    959 	/*
    960 	 * Find module info record and check compatibility.
    961 	 */
    962 	error = kobj_find_section(mod->mod_kobj, "link_set_modules",
    963 	    &addr, &size);
    964 	if (error != 0) {
    965 		module_error("`link_set_modules' section not present");
    966 		return error;
    967 	}
    968 	if (size != sizeof(modinfo_t **)) {
    969 		module_error("`link_set_modules' section wrong size");
    970 		return error;
    971 	}
    972 	mod->mod_info = *(modinfo_t **)addr;
    973 
    974 	return 0;
    975 }
    976 
    977 /*
    978  * module_find_section:
    979  *
    980  *	Allows a module that is being initialized to look up a section
    981  *	within its ELF object.
    982  */
    983 int
    984 module_find_section(const char *name, void **addr, size_t *size)
    985 {
    986 
    987 	KASSERT(mutex_owned(&module_lock));
    988 	KASSERT(module_active != NULL);
    989 
    990 	return kobj_find_section(module_active->mod_kobj, name, addr, size);
    991 }
    992 
    993 /*
    994  * module_thread:
    995  *
    996  *	Automatically unload modules.  We try once to unload autoloaded
    997  *	modules after module_autotime seconds.  If the system is under
    998  *	severe memory pressure, we'll try unloading all modules.
    999  */
   1000 static void
   1001 module_thread(void *cookie)
   1002 {
   1003 	module_t *mod, *next;
   1004 	modinfo_t *mi;
   1005 	int error;
   1006 
   1007 	for (;;) {
   1008 		mutex_enter(&module_lock);
   1009 		for (mod = TAILQ_FIRST(&module_list); mod != NULL; mod = next) {
   1010 			next = TAILQ_NEXT(mod, mod_chain);
   1011 			if (uvmexp.free < uvmexp.freemin) {
   1012 				module_thread_ticks = hz;
   1013 			} else if (mod->mod_autotime == 0) {
   1014 				continue;
   1015 			} else if (time_second < mod->mod_autotime) {
   1016 				module_thread_ticks = hz;
   1017 			    	continue;
   1018 			} else {
   1019 				mod->mod_autotime = 0;
   1020 			}
   1021 			/*
   1022 			 * If this module wants to avoid autounload then
   1023 			 * skip it.  Some modules can ping-pong in and out
   1024 			 * because their use is transient but often.
   1025 			 * Example: exec_script.
   1026 			 */
   1027 			mi = mod->mod_info;
   1028 			error = (*mi->mi_modcmd)(MODULE_CMD_AUTOUNLOAD, NULL);
   1029 			if (error == 0 || error == ENOTTY) {
   1030 				(void)module_do_unload(mi->mi_name);
   1031 			}
   1032 		}
   1033 		mutex_exit(&module_lock);
   1034 
   1035 		mutex_enter(&module_thread_lock);
   1036 		(void)cv_timedwait(&module_thread_cv, &module_thread_lock,
   1037 		    module_thread_ticks);
   1038 		module_thread_ticks = 0;
   1039 		mutex_exit(&module_thread_lock);
   1040 	}
   1041 }
   1042 
   1043 /*
   1044  * module_thread:
   1045  *
   1046  *	Kick the module thread into action, perhaps because the
   1047  *	system is low on memory.
   1048  */
   1049 void
   1050 module_thread_kick(void)
   1051 {
   1052 
   1053 	mutex_enter(&module_thread_lock);
   1054 	module_thread_ticks = hz;
   1055 	cv_broadcast(&module_thread_cv);
   1056 	mutex_exit(&module_thread_lock);
   1057 }
   1058 
   1059 #ifdef DDB
   1060 /*
   1061  * module_whatis:
   1062  *
   1063  *	Helper routine for DDB.
   1064  */
   1065 void
   1066 module_whatis(uintptr_t addr, void (*pr)(const char *, ...))
   1067 {
   1068 	module_t *mod;
   1069 	size_t msize;
   1070 	vaddr_t maddr;
   1071 
   1072 	TAILQ_FOREACH(mod, &module_list, mod_chain) {
   1073 		if (mod->mod_kobj == NULL) {
   1074 			continue;
   1075 		}
   1076 		if (kobj_stat(mod->mod_kobj, &maddr, &msize) != 0)
   1077 			continue;
   1078 		if (addr < maddr || addr >= maddr + msize) {
   1079 			continue;
   1080 		}
   1081 		(*pr)("%p is %p+%zu, in kernel module `%s'\n",
   1082 		    (void *)addr, (void *)maddr,
   1083 		    (size_t)(addr - maddr), mod->mod_info->mi_name);
   1084 	}
   1085 }
   1086 
   1087 /*
   1088  * module_print_list:
   1089  *
   1090  *	Helper routine for DDB.
   1091  */
   1092 void
   1093 module_print_list(void (*pr)(const char *, ...))
   1094 {
   1095 	const char *src;
   1096 	module_t *mod;
   1097 	size_t msize;
   1098 	vaddr_t maddr;
   1099 
   1100 	(*pr)("%16s %16s %8s %8s\n", "NAME", "TEXT/DATA", "SIZE", "SOURCE");
   1101 
   1102 	TAILQ_FOREACH(mod, &module_list, mod_chain) {
   1103 		switch (mod->mod_source) {
   1104 		case MODULE_SOURCE_KERNEL:
   1105 			src = "builtin";
   1106 			break;
   1107 		case MODULE_SOURCE_FILESYS:
   1108 			src = "filesys";
   1109 			break;
   1110 		case MODULE_SOURCE_BOOT:
   1111 			src = "boot";
   1112 			break;
   1113 		default:
   1114 			src = "unknown";
   1115 			break;
   1116 		}
   1117 		if (mod->mod_kobj == NULL) {
   1118 			maddr = 0;
   1119 			msize = 0;
   1120 		} else if (kobj_stat(mod->mod_kobj, &maddr, &msize) != 0)
   1121 			continue;
   1122 		(*pr)("%16s %16lx %8ld %8s\n", mod->mod_info->mi_name,
   1123 		    (long)maddr, (long)msize, src);
   1124 	}
   1125 }
   1126 #endif	/* DDB */
   1127 
   1128 static bool
   1129 module_merge_dicts(prop_dictionary_t existing_dict,
   1130 		   const prop_dictionary_t new_dict)
   1131 {
   1132 	prop_dictionary_keysym_t props_keysym;
   1133 	prop_object_iterator_t props_iter;
   1134 	prop_object_t props_obj;
   1135 	const char *props_key;
   1136 	bool error;
   1137 
   1138 	if (new_dict == NULL) {			/* nothing to merge */
   1139 		return true;
   1140 	}
   1141 
   1142 	error = false;
   1143 	props_iter = prop_dictionary_iterator(new_dict);
   1144 	if (props_iter == NULL) {
   1145 		return false;
   1146 	}
   1147 
   1148 	while ((props_obj = prop_object_iterator_next(props_iter)) != NULL) {
   1149 		props_keysym = (prop_dictionary_keysym_t)props_obj;
   1150 		props_key = prop_dictionary_keysym_cstring_nocopy(props_keysym);
   1151 		props_obj = prop_dictionary_get_keysym(new_dict, props_keysym);
   1152 		if ((props_obj == NULL) || !prop_dictionary_set(existing_dict,
   1153 		    props_key, props_obj)) {
   1154 			error = true;
   1155 			goto out;
   1156 		}
   1157 	}
   1158 	error = false;
   1159 
   1160 out:
   1161 	prop_object_iterator_release(props_iter);
   1162 
   1163 	return !error;
   1164 }
   1165