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