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