xref: /netbsd-src/sys/kern/kern_module.c (revision a5847cc334d9a7029f6352b847e9e8d71a0f9e0c)
1 /*	$NetBSD: kern_module.c,v 1.84 2011/11/06 12:40:04 tron 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.84 2011/11/06 12:40:04 tron 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, modp, 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 			    &mod2, MODULE_CLASS_ANY, true);
1036 			if (error != 0)
1037 				goto fail;
1038 			mod->mod_required[mod->mod_nrequired++] = mod2;
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 		mod->mod_flags |= MODFLG_AUTO_LOADED;
1093 		module_thread_kick();
1094 	}
1095 	depth--;
1096 	return 0;
1097 
1098  fail:
1099 	kobj_unload(mod->mod_kobj);
1100  fail2:
1101 	if (filedict != NULL) {
1102 		prop_object_release(filedict);
1103 		filedict = NULL;
1104 	}
1105 	TAILQ_REMOVE(pending, mod, mod_chain);
1106 	kmem_free(mod, sizeof(*mod));
1107 	depth--;
1108 	return error;
1109 }
1110 
1111 /*
1112  * module_do_unload:
1113  *
1114  *	Helper routine: do the dirty work of unloading a module.
1115  */
1116 static int
1117 module_do_unload(const char *name, bool load_requires_force)
1118 {
1119 	module_t *mod, *prev_active;
1120 	int error;
1121 	u_int i;
1122 
1123 	KASSERT(kernconfig_is_held());
1124 
1125 	mod = module_lookup(name);
1126 	if (mod == NULL) {
1127 		module_error("module `%s' not found", name);
1128 		return ENOENT;
1129 	}
1130 	if (mod->mod_refcnt != 0) {
1131 		module_print("module `%s' busy", name);
1132 		return EBUSY;
1133 	}
1134 
1135 	/*
1136 	 * Builtin secmodels are there to stay.
1137 	 */
1138 	if (mod->mod_source == MODULE_SOURCE_KERNEL &&
1139 	    mod->mod_info->mi_class == MODULE_CLASS_SECMODEL) {
1140 		return EPERM;
1141 	}
1142 
1143 	prev_active = module_active;
1144 	module_active = mod;
1145 	error = (*mod->mod_info->mi_modcmd)(MODULE_CMD_FINI, NULL);
1146 	module_active = prev_active;
1147 	if (error != 0) {
1148 		module_print("cannot unload module `%s' error=%d", name,
1149 		    error);
1150 		return error;
1151 	}
1152 	if (mod->mod_info->mi_class == MODULE_CLASS_SECMODEL)
1153 		secmodel_deregister();
1154 	module_count--;
1155 	TAILQ_REMOVE(&module_list, mod, mod_chain);
1156 	for (i = 0; i < mod->mod_nrequired; i++) {
1157 		mod->mod_required[i]->mod_refcnt--;
1158 	}
1159 	if (mod->mod_kobj != NULL) {
1160 		kobj_unload(mod->mod_kobj);
1161 	}
1162 	if (mod->mod_source == MODULE_SOURCE_KERNEL) {
1163 		mod->mod_nrequired = 0; /* will be re-parsed */
1164 		if (load_requires_force)
1165 			module_require_force(mod);
1166 		TAILQ_INSERT_TAIL(&module_builtins, mod, mod_chain);
1167 		module_builtinlist++;
1168 	} else {
1169 		kmem_free(mod, sizeof(*mod));
1170 	}
1171 	module_gen++;
1172 
1173 	module_print("unloaded module `%s'", name);
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(const char *name, 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, name, 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 ENOEXEC;
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 
1278 			/* skip built-in modules */
1279 			if (mod->mod_source == MODULE_SOURCE_KERNEL)
1280 				continue;
1281 			/* skip modules that weren't auto-loaded */
1282 			if ((mod->mod_flags & MODFLG_AUTO_LOADED) == 0)
1283 				continue;
1284 
1285 			if (uvmexp.free < uvmexp.freemin) {
1286 				module_thread_ticks = hz;
1287 			} else if (mod->mod_autotime == 0) {
1288 				continue;
1289 			} else if (time_second < mod->mod_autotime) {
1290 				module_thread_ticks = hz;
1291 			    	continue;
1292 			} else {
1293 				mod->mod_autotime = 0;
1294 			}
1295 
1296 			/*
1297 			 * If this module wants to avoid autounload then
1298 			 * skip it.  Some modules can ping-pong in and out
1299 			 * because their use is transient but often.
1300 			 * Example: exec_script.
1301 			 */
1302 			mi = mod->mod_info;
1303 			error = (*mi->mi_modcmd)(MODULE_CMD_AUTOUNLOAD, NULL);
1304 			if (error == 0 || error == ENOTTY) {
1305 				(void)module_do_unload(mi->mi_name, false);
1306 			}
1307 		}
1308 		kernconfig_unlock();
1309 
1310 		mutex_enter(&module_thread_lock);
1311 		(void)cv_timedwait(&module_thread_cv, &module_thread_lock,
1312 		    module_thread_ticks);
1313 		module_thread_ticks = 0;
1314 		mutex_exit(&module_thread_lock);
1315 	}
1316 }
1317 
1318 /*
1319  * module_thread:
1320  *
1321  *	Kick the module thread into action, perhaps because the
1322  *	system is low on memory.
1323  */
1324 void
1325 module_thread_kick(void)
1326 {
1327 
1328 	mutex_enter(&module_thread_lock);
1329 	module_thread_ticks = hz;
1330 	cv_broadcast(&module_thread_cv);
1331 	mutex_exit(&module_thread_lock);
1332 }
1333 
1334 #ifdef DDB
1335 /*
1336  * module_whatis:
1337  *
1338  *	Helper routine for DDB.
1339  */
1340 void
1341 module_whatis(uintptr_t addr, void (*pr)(const char *, ...))
1342 {
1343 	module_t *mod;
1344 	size_t msize;
1345 	vaddr_t maddr;
1346 
1347 	TAILQ_FOREACH(mod, &module_list, mod_chain) {
1348 		if (mod->mod_kobj == NULL) {
1349 			continue;
1350 		}
1351 		if (kobj_stat(mod->mod_kobj, &maddr, &msize) != 0)
1352 			continue;
1353 		if (addr < maddr || addr >= maddr + msize) {
1354 			continue;
1355 		}
1356 		(*pr)("%p is %p+%zu, in kernel module `%s'\n",
1357 		    (void *)addr, (void *)maddr,
1358 		    (size_t)(addr - maddr), mod->mod_info->mi_name);
1359 	}
1360 }
1361 
1362 /*
1363  * module_print_list:
1364  *
1365  *	Helper routine for DDB.
1366  */
1367 void
1368 module_print_list(void (*pr)(const char *, ...))
1369 {
1370 	const char *src;
1371 	module_t *mod;
1372 	size_t msize;
1373 	vaddr_t maddr;
1374 
1375 	(*pr)("%16s %16s %8s %8s\n", "NAME", "TEXT/DATA", "SIZE", "SOURCE");
1376 
1377 	TAILQ_FOREACH(mod, &module_list, mod_chain) {
1378 		switch (mod->mod_source) {
1379 		case MODULE_SOURCE_KERNEL:
1380 			src = "builtin";
1381 			break;
1382 		case MODULE_SOURCE_FILESYS:
1383 			src = "filesys";
1384 			break;
1385 		case MODULE_SOURCE_BOOT:
1386 			src = "boot";
1387 			break;
1388 		default:
1389 			src = "unknown";
1390 			break;
1391 		}
1392 		if (mod->mod_kobj == NULL) {
1393 			maddr = 0;
1394 			msize = 0;
1395 		} else if (kobj_stat(mod->mod_kobj, &maddr, &msize) != 0)
1396 			continue;
1397 		(*pr)("%16s %16lx %8ld %8s\n", mod->mod_info->mi_name,
1398 		    (long)maddr, (long)msize, src);
1399 	}
1400 }
1401 #endif	/* DDB */
1402 
1403 static bool
1404 module_merge_dicts(prop_dictionary_t existing_dict,
1405 		   const prop_dictionary_t new_dict)
1406 {
1407 	prop_dictionary_keysym_t props_keysym;
1408 	prop_object_iterator_t props_iter;
1409 	prop_object_t props_obj;
1410 	const char *props_key;
1411 	bool error;
1412 
1413 	if (new_dict == NULL) {			/* nothing to merge */
1414 		return true;
1415 	}
1416 
1417 	error = false;
1418 	props_iter = prop_dictionary_iterator(new_dict);
1419 	if (props_iter == NULL) {
1420 		return false;
1421 	}
1422 
1423 	while ((props_obj = prop_object_iterator_next(props_iter)) != NULL) {
1424 		props_keysym = (prop_dictionary_keysym_t)props_obj;
1425 		props_key = prop_dictionary_keysym_cstring_nocopy(props_keysym);
1426 		props_obj = prop_dictionary_get_keysym(new_dict, props_keysym);
1427 		if ((props_obj == NULL) || !prop_dictionary_set(existing_dict,
1428 		    props_key, props_obj)) {
1429 			error = true;
1430 			goto out;
1431 		}
1432 	}
1433 	error = false;
1434 
1435 out:
1436 	prop_object_iterator_release(props_iter);
1437 
1438 	return !error;
1439 }
1440