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