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