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