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