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