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