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