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