xref: /netbsd-src/sys/kern/kern_module.c (revision bbde328be4e75ea9ad02e9715ea13ca54b797ada)
1 /*	$NetBSD: kern_module.c,v 1.65 2010/05/02 11:01:03 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.65 2010/05/02 11:01:03 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_BOOL, "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_BOOL, "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 		/*
692 		 * XXX: We'd like to panic here, but currently in some
693 		 * cases (such as nfsserver + nfs), the dependee can be
694 		 * succesfully linked without the dependencies.
695 		 */
696 		module_error("can't find builtin dependency `%s'", name);
697 		return ENOENT;
698 	}
699 
700 	/*
701 	 * Initialize pre-requisites.
702 	 */
703 	if (mi->mi_required != NULL) {
704 		for (s = mi->mi_required; *s != '\0'; s = p) {
705 			if (*s == ',')
706 				s++;
707 			p = s;
708 			while (*p != '\0' && *p != ',')
709 				p++;
710 			len = min(p - s + 1, sizeof(buf));
711 			strlcpy(buf, s, len);
712 			if (buf[0] == '\0')
713 				break;
714 			if (mod->mod_nrequired == MAXMODDEPS - 1) {
715 				module_error("too many required modules");
716 				return EINVAL;
717 			}
718 			error = module_do_builtin(buf, &mod2);
719 			if (error != 0) {
720 				return error;
721 			}
722 			mod->mod_required[mod->mod_nrequired++] = mod2;
723 		}
724 	}
725 
726 	/*
727 	 * Try to initialize the module.
728 	 */
729 	KASSERT(module_active == NULL);
730 	module_active = mod;
731 	error = (*mi->mi_modcmd)(MODULE_CMD_INIT, NULL);
732 	module_active = NULL;
733 	if (error != 0) {
734 		module_error("builtin module `%s' "
735 		    "failed to init", mi->mi_name);
736 		return error;
737 	}
738 
739 	/* load always succeeds after this point */
740 
741 	TAILQ_REMOVE(&module_builtins, mod, mod_chain);
742 	module_builtinlist--;
743 	if (modp != NULL) {
744 		*modp = mod;
745 	}
746 	if (mi->mi_class == MODULE_CLASS_SECMODEL)
747 		secmodel_register();
748 	module_enqueue(mod);
749 	return 0;
750 }
751 
752 /*
753  * module_do_load:
754  *
755  *	Helper routine: load a module from the file system, or one
756  *	pushed by the boot loader.
757  */
758 static int
759 module_do_load(const char *name, bool isdep, int flags,
760 	       prop_dictionary_t props, module_t **modp, modclass_t class,
761 	       bool autoload)
762 {
763 	static TAILQ_HEAD(,module) pending = TAILQ_HEAD_INITIALIZER(pending);
764 	static int depth;
765 	const int maxdepth = 6;
766 	modinfo_t *mi;
767 	module_t *mod, *mod2;
768 	prop_dictionary_t filedict;
769 	char buf[MAXMODNAME];
770 	const char *s, *p;
771 	int error;
772 	size_t len;
773 
774 	KASSERT(mutex_owned(&module_lock));
775 
776 	filedict = NULL;
777 	error = 0;
778 
779 	/*
780 	 * Avoid recursing too far.
781 	 */
782 	if (++depth > maxdepth) {
783 		module_error("too many required modules");
784 		depth--;
785 		return EMLINK;
786 	}
787 
788 	/*
789 	 * Search the list of disabled builtins first.
790 	 */
791 	TAILQ_FOREACH(mod, &module_builtins, mod_chain) {
792 		if (strcmp(mod->mod_info->mi_name, name) == 0) {
793 			break;
794 		}
795 	}
796 	if (mod) {
797 		if ((flags & MODCTL_LOAD_FORCE) == 0) {
798 			if (!autoload) {
799 				module_error("use -f to reinstate "
800 				    "builtin module \"%s\"", name);
801 			}
802 			depth--;
803 			return EPERM;
804 		} else {
805 			error = module_do_builtin(name, NULL);
806 			depth--;
807 			return error;
808 		}
809 	}
810 
811 	/*
812 	 * Load the module and link.  Before going to the file system,
813 	 * scan the list of modules loaded by the boot loader.
814 	 */
815 	TAILQ_FOREACH(mod, &module_bootlist, mod_chain) {
816 		if (strcmp(mod->mod_info->mi_name, name) == 0) {
817 			TAILQ_REMOVE(&module_bootlist, mod, mod_chain);
818 			break;
819 		}
820 	}
821 	if (mod != NULL) {
822 		TAILQ_INSERT_TAIL(&pending, mod, mod_chain);
823 	} else {
824 		/*
825 		 * If a requisite module, check to see if it is
826 		 * already present.
827 		 */
828 		if (isdep) {
829 			TAILQ_FOREACH(mod, &module_list, mod_chain) {
830 				if (strcmp(mod->mod_info->mi_name, name) == 0) {
831 					break;
832 				}
833 			}
834 			if (mod != NULL) {
835 				if (modp != NULL) {
836 					*modp = mod;
837 				}
838 				depth--;
839 				return 0;
840 			}
841 		}
842 		mod = kmem_zalloc(sizeof(*mod), KM_SLEEP);
843 		if (mod == NULL) {
844 			module_error("out of memory for `%s'", name);
845 			depth--;
846 			return ENOMEM;
847 		}
848 
849 		error = module_load_vfs(name, flags, autoload, mod, &filedict);
850 		if (error != 0) {
851 			kmem_free(mod, sizeof(*mod));
852 			depth--;
853 			return error;
854 		}
855 		mod->mod_source = MODULE_SOURCE_FILESYS;
856 		TAILQ_INSERT_TAIL(&pending, mod, mod_chain);
857 
858 		error = module_fetch_info(mod);
859 		if (error != 0) {
860 			module_error("cannot fetch module info for `%s'",
861 			    name);
862 			goto fail;
863 		}
864 	}
865 
866 	/*
867 	 * Check compatibility.
868 	 */
869 	mi = mod->mod_info;
870 	if (strlen(mi->mi_name) >= MAXMODNAME) {
871 		error = EINVAL;
872 		module_error("module name `%s' too long", mi->mi_name);
873 		goto fail;
874 	}
875 	if (!module_compatible(mi->mi_version, __NetBSD_Version__)) {
876 		module_error("module built for `%d', system `%d'",
877 		    mi->mi_version, __NetBSD_Version__);
878 		if ((flags & MODCTL_LOAD_FORCE) != 0) {
879 			module_error("forced load, system may be unstable");
880 		} else {
881 			error = EPROGMISMATCH;
882 			goto fail;
883 		}
884 	}
885 
886 	/*
887 	 * If a specific kind of module was requested, ensure that we have
888 	 * a match.
889 	 */
890 	if (class != MODULE_CLASS_ANY && class != mi->mi_class) {
891 		module_print("incompatible module class for `%s' (%d != %d)",
892 		    name, class, mi->mi_class);
893 		error = ENOENT;
894 		goto fail;
895 	}
896 
897 	/*
898 	 * If loading a dependency, `name' is a plain module name.
899 	 * The name must match.
900 	 */
901 	if (isdep && strcmp(mi->mi_name, name) != 0) {
902 		module_error("dependency name mismatch (`%s' != `%s')",
903 		    name, mi->mi_name);
904 		error = ENOENT;
905 		goto fail;
906 	}
907 
908 	/*
909 	 * Check to see if the module is already loaded.  If so, we may
910 	 * have been recursively called to handle a dependency, so be sure
911 	 * to set modp.
912 	 */
913 	if ((mod2 = module_lookup(mi->mi_name)) != NULL) {
914 		if (modp != NULL)
915 			*modp = mod2;
916 		module_print("module `%s' already loaded", mi->mi_name);
917 		error = EEXIST;
918 		goto fail;
919 	}
920 
921 	/*
922 	 * Block circular dependencies.
923 	 */
924 	TAILQ_FOREACH(mod2, &pending, mod_chain) {
925 		if (mod == mod2) {
926 			continue;
927 		}
928 		if (strcmp(mod2->mod_info->mi_name, mi->mi_name) == 0) {
929 		    	error = EDEADLK;
930 			module_error("circular dependency detected for `%s'",
931 			    mi->mi_name);
932 		    	goto fail;
933 		}
934 	}
935 
936 	/*
937 	 * Now try to load any requisite modules.
938 	 */
939 	if (mi->mi_required != NULL) {
940 		for (s = mi->mi_required; *s != '\0'; s = p) {
941 			if (*s == ',')
942 				s++;
943 			p = s;
944 			while (*p != '\0' && *p != ',')
945 				p++;
946 			len = p - s + 1;
947 			if (len >= MAXMODNAME) {
948 				error = EINVAL;
949 				module_error("required module name `%s'"
950 				    " too long", mi->mi_required);
951 				goto fail;
952 			}
953 			strlcpy(buf, s, len);
954 			if (buf[0] == '\0')
955 				break;
956 			if (mod->mod_nrequired == MAXMODDEPS - 1) {
957 				error = EINVAL;
958 				module_error("too many required modules (%d)",
959 				    mod->mod_nrequired);
960 				goto fail;
961 			}
962 			if (strcmp(buf, mi->mi_name) == 0) {
963 				error = EDEADLK;
964 				module_error("self-dependency detected for "
965 				   "`%s'", mi->mi_name);
966 				goto fail;
967 			}
968 			error = module_do_load(buf, true, flags, NULL,
969 			    &mod->mod_required[mod->mod_nrequired++],
970 			    MODULE_CLASS_ANY, true);
971 			if (error != 0)
972 				goto fail;
973 		}
974 	}
975 
976 	/*
977 	 * We loaded all needed modules successfully: perform global
978 	 * relocations and initialize.
979 	 */
980 	error = kobj_affix(mod->mod_kobj, mi->mi_name);
981 	if (error != 0) {
982 		/* Cannot touch 'mi' as the module is now gone. */
983 		module_error("unable to affix module `%s'", name);
984 		goto fail2;
985 	}
986 
987 	if (filedict) {
988 		if (!module_merge_dicts(filedict, props)) {
989 			module_error("module properties failed");
990 			error = EINVAL;
991 			goto fail;
992 		}
993 	}
994 	KASSERT(module_active == NULL);
995 	module_active = mod;
996 	error = (*mi->mi_modcmd)(MODULE_CMD_INIT, filedict ? filedict : props);
997 	module_active = NULL;
998 	if (filedict) {
999 		prop_object_release(filedict);
1000 		filedict = NULL;
1001 	}
1002 	if (error != 0) {
1003 		module_error("modcmd function returned error %d for `%s'",
1004 		    error, mi->mi_name);
1005 		goto fail;
1006 	}
1007 
1008 	if (mi->mi_class == MODULE_CLASS_SECMODEL)
1009 		secmodel_register();
1010 
1011 	/*
1012 	 * Good, the module loaded successfully.  Put it onto the
1013 	 * list and add references to its requisite modules.
1014 	 */
1015 	TAILQ_REMOVE(&pending, mod, mod_chain);
1016 	module_enqueue(mod);
1017 	if (modp != NULL) {
1018 		*modp = mod;
1019 	}
1020 	if (autoload) {
1021 		/*
1022 		 * Arrange to try unloading the module after
1023 		 * a short delay.
1024 		 */
1025 		mod->mod_autotime = time_second + module_autotime;
1026 		module_thread_kick();
1027 	}
1028 	depth--;
1029 	return 0;
1030 
1031  fail:
1032 	kobj_unload(mod->mod_kobj);
1033  fail2:
1034 	if (filedict != NULL) {
1035 		prop_object_release(filedict);
1036 		filedict = NULL;
1037 	}
1038 	TAILQ_REMOVE(&pending, mod, mod_chain);
1039 	kmem_free(mod, sizeof(*mod));
1040 	depth--;
1041 	return error;
1042 }
1043 
1044 /*
1045  * module_do_unload:
1046  *
1047  *	Helper routine: do the dirty work of unloading a module.
1048  */
1049 static int
1050 module_do_unload(const char *name)
1051 {
1052 	module_t *mod;
1053 	int error;
1054 	u_int i;
1055 
1056 	KASSERT(mutex_owned(&module_lock));
1057 
1058 	mod = module_lookup(name);
1059 	if (mod == NULL) {
1060 		module_error("module `%s' not found", name);
1061 		return ENOENT;
1062 	}
1063 	if (mod->mod_refcnt != 0) {
1064 		module_print("module `%s' busy", name);
1065 		return EBUSY;
1066 	}
1067 	KASSERT(module_active == NULL);
1068 	module_active = mod;
1069 	error = (*mod->mod_info->mi_modcmd)(MODULE_CMD_FINI, NULL);
1070 	module_active = NULL;
1071 	if (error != 0) {
1072 		module_print("cannot unload module `%s' error=%d", name,
1073 		    error);
1074 		return error;
1075 	}
1076 	if (mod->mod_info->mi_class == MODULE_CLASS_SECMODEL)
1077 		secmodel_deregister();
1078 	module_count--;
1079 	TAILQ_REMOVE(&module_list, mod, mod_chain);
1080 	for (i = 0; i < mod->mod_nrequired; i++) {
1081 		mod->mod_required[i]->mod_refcnt--;
1082 	}
1083 	if (mod->mod_kobj != NULL) {
1084 		kobj_unload(mod->mod_kobj);
1085 	}
1086 	if (mod->mod_source == MODULE_SOURCE_KERNEL) {
1087 		mod->mod_nrequired = 0; /* will be re-parsed */
1088 		TAILQ_INSERT_TAIL(&module_builtins, mod, mod_chain);
1089 		module_builtinlist++;
1090 	} else {
1091 		kmem_free(mod, sizeof(*mod));
1092 	}
1093 	module_gen++;
1094 
1095 	return 0;
1096 }
1097 
1098 /*
1099  * module_prime:
1100  *
1101  *	Push a module loaded by the bootloader onto our internal
1102  *	list.
1103  */
1104 int
1105 module_prime(void *base, size_t size)
1106 {
1107 	module_t *mod;
1108 	int error;
1109 
1110 	mod = kmem_zalloc(sizeof(*mod), KM_SLEEP);
1111 	if (mod == NULL) {
1112 		return ENOMEM;
1113 	}
1114 	mod->mod_source = MODULE_SOURCE_BOOT;
1115 
1116 	error = kobj_load_mem(&mod->mod_kobj, base, size);
1117 	if (error != 0) {
1118 		kmem_free(mod, sizeof(*mod));
1119 		module_error("unable to load object pushed by boot loader");
1120 		return error;
1121 	}
1122 	error = module_fetch_info(mod);
1123 	if (error != 0) {
1124 		kobj_unload(mod->mod_kobj);
1125 		kmem_free(mod, sizeof(*mod));
1126 		module_error("unable to load object pushed by boot loader");
1127 		return error;
1128 	}
1129 
1130 	TAILQ_INSERT_TAIL(&module_bootlist, mod, mod_chain);
1131 
1132 	return 0;
1133 }
1134 
1135 /*
1136  * module_fetch_into:
1137  *
1138  *	Fetch modinfo record from a loaded module.
1139  */
1140 static int
1141 module_fetch_info(module_t *mod)
1142 {
1143 	int error;
1144 	void *addr;
1145 	size_t size;
1146 
1147 	/*
1148 	 * Find module info record and check compatibility.
1149 	 */
1150 	error = kobj_find_section(mod->mod_kobj, "link_set_modules",
1151 	    &addr, &size);
1152 	if (error != 0) {
1153 		module_error("`link_set_modules' section not present");
1154 		return error;
1155 	}
1156 	if (size != sizeof(modinfo_t **)) {
1157 		module_error("`link_set_modules' section wrong size");
1158 		return error;
1159 	}
1160 	mod->mod_info = *(modinfo_t **)addr;
1161 
1162 	return 0;
1163 }
1164 
1165 /*
1166  * module_find_section:
1167  *
1168  *	Allows a module that is being initialized to look up a section
1169  *	within its ELF object.
1170  */
1171 int
1172 module_find_section(const char *name, void **addr, size_t *size)
1173 {
1174 
1175 	KASSERT(mutex_owned(&module_lock));
1176 	KASSERT(module_active != NULL);
1177 
1178 	return kobj_find_section(module_active->mod_kobj, name, addr, size);
1179 }
1180 
1181 /*
1182  * module_thread:
1183  *
1184  *	Automatically unload modules.  We try once to unload autoloaded
1185  *	modules after module_autotime seconds.  If the system is under
1186  *	severe memory pressure, we'll try unloading all modules.
1187  */
1188 static void
1189 module_thread(void *cookie)
1190 {
1191 	module_t *mod, *next;
1192 	modinfo_t *mi;
1193 	int error;
1194 
1195 	for (;;) {
1196 		mutex_enter(&module_lock);
1197 		for (mod = TAILQ_FIRST(&module_list); mod != NULL; mod = next) {
1198 			next = TAILQ_NEXT(mod, mod_chain);
1199 			if (mod->mod_source == MODULE_SOURCE_KERNEL)
1200 				continue;
1201 			if (uvmexp.free < uvmexp.freemin) {
1202 				module_thread_ticks = hz;
1203 			} else if (mod->mod_autotime == 0) {
1204 				continue;
1205 			} else if (time_second < mod->mod_autotime) {
1206 				module_thread_ticks = hz;
1207 			    	continue;
1208 			} else {
1209 				mod->mod_autotime = 0;
1210 			}
1211 			/*
1212 			 * If this module wants to avoid autounload then
1213 			 * skip it.  Some modules can ping-pong in and out
1214 			 * because their use is transient but often.
1215 			 * Example: exec_script.
1216 			 */
1217 			mi = mod->mod_info;
1218 			error = (*mi->mi_modcmd)(MODULE_CMD_AUTOUNLOAD, NULL);
1219 			if (error == 0 || error == ENOTTY) {
1220 				(void)module_do_unload(mi->mi_name);
1221 			}
1222 		}
1223 		mutex_exit(&module_lock);
1224 
1225 		mutex_enter(&module_thread_lock);
1226 		(void)cv_timedwait(&module_thread_cv, &module_thread_lock,
1227 		    module_thread_ticks);
1228 		module_thread_ticks = 0;
1229 		mutex_exit(&module_thread_lock);
1230 	}
1231 }
1232 
1233 /*
1234  * module_thread:
1235  *
1236  *	Kick the module thread into action, perhaps because the
1237  *	system is low on memory.
1238  */
1239 void
1240 module_thread_kick(void)
1241 {
1242 
1243 	mutex_enter(&module_thread_lock);
1244 	module_thread_ticks = hz;
1245 	cv_broadcast(&module_thread_cv);
1246 	mutex_exit(&module_thread_lock);
1247 }
1248 
1249 #ifdef DDB
1250 /*
1251  * module_whatis:
1252  *
1253  *	Helper routine for DDB.
1254  */
1255 void
1256 module_whatis(uintptr_t addr, void (*pr)(const char *, ...))
1257 {
1258 	module_t *mod;
1259 	size_t msize;
1260 	vaddr_t maddr;
1261 
1262 	TAILQ_FOREACH(mod, &module_list, mod_chain) {
1263 		if (mod->mod_kobj == NULL) {
1264 			continue;
1265 		}
1266 		if (kobj_stat(mod->mod_kobj, &maddr, &msize) != 0)
1267 			continue;
1268 		if (addr < maddr || addr >= maddr + msize) {
1269 			continue;
1270 		}
1271 		(*pr)("%p is %p+%zu, in kernel module `%s'\n",
1272 		    (void *)addr, (void *)maddr,
1273 		    (size_t)(addr - maddr), mod->mod_info->mi_name);
1274 	}
1275 }
1276 
1277 /*
1278  * module_print_list:
1279  *
1280  *	Helper routine for DDB.
1281  */
1282 void
1283 module_print_list(void (*pr)(const char *, ...))
1284 {
1285 	const char *src;
1286 	module_t *mod;
1287 	size_t msize;
1288 	vaddr_t maddr;
1289 
1290 	(*pr)("%16s %16s %8s %8s\n", "NAME", "TEXT/DATA", "SIZE", "SOURCE");
1291 
1292 	TAILQ_FOREACH(mod, &module_list, mod_chain) {
1293 		switch (mod->mod_source) {
1294 		case MODULE_SOURCE_KERNEL:
1295 			src = "builtin";
1296 			break;
1297 		case MODULE_SOURCE_FILESYS:
1298 			src = "filesys";
1299 			break;
1300 		case MODULE_SOURCE_BOOT:
1301 			src = "boot";
1302 			break;
1303 		default:
1304 			src = "unknown";
1305 			break;
1306 		}
1307 		if (mod->mod_kobj == NULL) {
1308 			maddr = 0;
1309 			msize = 0;
1310 		} else if (kobj_stat(mod->mod_kobj, &maddr, &msize) != 0)
1311 			continue;
1312 		(*pr)("%16s %16lx %8ld %8s\n", mod->mod_info->mi_name,
1313 		    (long)maddr, (long)msize, src);
1314 	}
1315 }
1316 #endif	/* DDB */
1317 
1318 static bool
1319 module_merge_dicts(prop_dictionary_t existing_dict,
1320 		   const prop_dictionary_t new_dict)
1321 {
1322 	prop_dictionary_keysym_t props_keysym;
1323 	prop_object_iterator_t props_iter;
1324 	prop_object_t props_obj;
1325 	const char *props_key;
1326 	bool error;
1327 
1328 	if (new_dict == NULL) {			/* nothing to merge */
1329 		return true;
1330 	}
1331 
1332 	error = false;
1333 	props_iter = prop_dictionary_iterator(new_dict);
1334 	if (props_iter == NULL) {
1335 		return false;
1336 	}
1337 
1338 	while ((props_obj = prop_object_iterator_next(props_iter)) != NULL) {
1339 		props_keysym = (prop_dictionary_keysym_t)props_obj;
1340 		props_key = prop_dictionary_keysym_cstring_nocopy(props_keysym);
1341 		props_obj = prop_dictionary_get_keysym(new_dict, props_keysym);
1342 		if ((props_obj == NULL) || !prop_dictionary_set(existing_dict,
1343 		    props_key, props_obj)) {
1344 			error = true;
1345 			goto out;
1346 		}
1347 	}
1348 	error = false;
1349 
1350 out:
1351 	prop_object_iterator_release(props_iter);
1352 
1353 	return !error;
1354 }
1355