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