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