xref: /netbsd-src/sys/kern/kern_module.c (revision 07cd2d7f4155df9bb93647120ce3750eec13203b)
1 /*	$NetBSD: kern_module.c,v 1.62 2010/03/18 18:25:45 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.62 2010/03/18 18:25:45 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 	module_t *mod;
399 	modinfo_t *mi;
400 
401 	mutex_enter(&module_lock);
402 	/*
403 	 * Builtins first.  These will not depend on pre-loaded modules
404 	 * (because the kernel would not link).
405 	 */
406 	do {
407 		TAILQ_FOREACH(mod, &module_builtins, mod_chain) {
408 			mi = mod->mod_info;
409 			if (class != MODULE_CLASS_ANY && class != mi->mi_class)
410 				continue;
411 			(void)module_do_builtin(mi->mi_name, NULL);
412 			break;
413 		}
414 	} while (mod != NULL);
415 
416 	/*
417 	 * Now preloaded modules.  These will be pulled off the
418 	 * list as we call module_do_load();
419 	 */
420 	do {
421 		TAILQ_FOREACH(mod, &module_bootlist, mod_chain) {
422 			mi = mod->mod_info;
423 			if (class != MODULE_CLASS_ANY && class != mi->mi_class)
424 				continue;
425 			module_do_load(mi->mi_name, false, 0, NULL, NULL,
426 			    class, false);
427 			break;
428 		}
429 	} while (mod != NULL);
430 	mutex_exit(&module_lock);
431 }
432 
433 /*
434  * module_compatible:
435  *
436  *	Return true if the two supplied kernel versions are said to
437  *	have the same binary interface for kernel code.  The entire
438  *	version is signficant for the development tree (-current),
439  *	major and minor versions are significant for official
440  *	releases of the system.
441  */
442 bool
443 module_compatible(int v1, int v2)
444 {
445 
446 #if __NetBSD_Version__ / 1000000 % 100 == 99	/* -current */
447 	return v1 == v2;
448 #else						/* release */
449 	return abs(v1 - v2) < 10000;
450 #endif
451 }
452 
453 /*
454  * module_load:
455  *
456  *	Load a single module from the file system.
457  */
458 int
459 module_load(const char *filename, int flags, prop_dictionary_t props,
460 	    modclass_t class)
461 {
462 	int error;
463 
464 	/* Authorize. */
465 	error = kauth_authorize_system(kauth_cred_get(), KAUTH_SYSTEM_MODULE,
466 	    0, (void *)(uintptr_t)MODCTL_LOAD, NULL, NULL);
467 	if (error != 0) {
468 		return error;
469 	}
470 
471 	mutex_enter(&module_lock);
472 	error = module_do_load(filename, false, flags, props, NULL, class,
473 	    false);
474 	mutex_exit(&module_lock);
475 
476 	return error;
477 }
478 
479 /*
480  * module_autoload:
481  *
482  *	Load a single module from the file system, system initiated.
483  */
484 int
485 module_autoload(const char *filename, modclass_t class)
486 {
487 	int error;
488 
489 	KASSERT(mutex_owned(&module_lock));
490 
491 	/* Nothing if the user has disabled it. */
492 	if (!module_autoload_on) {
493 		return EPERM;
494 	}
495 
496         /* Disallow path separators and magic symlinks. */
497         if (strchr(filename, '/') != NULL || strchr(filename, '@') != NULL ||
498             strchr(filename, '.') != NULL) {
499         	return EPERM;
500 	}
501 
502 	/* Authorize. */
503 	error = kauth_authorize_system(kauth_cred_get(), KAUTH_SYSTEM_MODULE,
504 	    0, (void *)(uintptr_t)MODCTL_LOAD, (void *)(uintptr_t)1, NULL);
505 	if (error != 0) {
506 		return error;
507 	}
508 
509 	return module_do_load(filename, false, 0, NULL, NULL, class, true);
510 }
511 
512 /*
513  * module_unload:
514  *
515  *	Find and unload a module by name.
516  */
517 int
518 module_unload(const char *name)
519 {
520 	int error;
521 
522 	/* Authorize. */
523 	error = kauth_authorize_system(kauth_cred_get(), KAUTH_SYSTEM_MODULE,
524 	    0, (void *)(uintptr_t)MODCTL_UNLOAD, NULL, NULL);
525 	if (error != 0) {
526 		return error;
527 	}
528 
529 	mutex_enter(&module_lock);
530 	error = module_do_unload(name);
531 	mutex_exit(&module_lock);
532 
533 	return error;
534 }
535 
536 /*
537  * module_lookup:
538  *
539  *	Look up a module by name.
540  */
541 module_t *
542 module_lookup(const char *name)
543 {
544 	module_t *mod;
545 
546 	KASSERT(mutex_owned(&module_lock));
547 
548 	TAILQ_FOREACH(mod, &module_list, mod_chain) {
549 		if (strcmp(mod->mod_info->mi_name, name) == 0) {
550 			break;
551 		}
552 	}
553 
554 	return mod;
555 }
556 
557 /*
558  * module_hold:
559  *
560  *	Add a single reference to a module.  It's the caller's
561  *	responsibility to ensure that the reference is dropped
562  *	later.
563  */
564 int
565 module_hold(const char *name)
566 {
567 	module_t *mod;
568 
569 	mutex_enter(&module_lock);
570 	mod = module_lookup(name);
571 	if (mod == NULL) {
572 		mutex_exit(&module_lock);
573 		return ENOENT;
574 	}
575 	mod->mod_refcnt++;
576 	mutex_exit(&module_lock);
577 
578 	return 0;
579 }
580 
581 /*
582  * module_rele:
583  *
584  *	Release a reference acquired with module_hold().
585  */
586 void
587 module_rele(const char *name)
588 {
589 	module_t *mod;
590 
591 	mutex_enter(&module_lock);
592 	mod = module_lookup(name);
593 	if (mod == NULL) {
594 		mutex_exit(&module_lock);
595 		panic("module_rele: gone");
596 	}
597 	mod->mod_refcnt--;
598 	mutex_exit(&module_lock);
599 }
600 
601 /*
602  * module_enqueue:
603  *
604  *	Put a module onto the global list and update counters.
605  */
606 void
607 module_enqueue(module_t *mod)
608 {
609 	int i;
610 
611 	KASSERT(mutex_owned(&module_lock));
612 
613 	/*
614 	 * If there are requisite modules, put at the head of the queue.
615 	 * This is so that autounload can unload requisite modules with
616 	 * only one pass through the queue.
617 	 */
618 	if (mod->mod_nrequired) {
619 		TAILQ_INSERT_HEAD(&module_list, mod, mod_chain);
620 
621 		/* Add references to the requisite modules. */
622 		for (i = 0; i < mod->mod_nrequired; i++) {
623 			KASSERT(mod->mod_required[i] != NULL);
624 			mod->mod_required[i]->mod_refcnt++;
625 		}
626 	} else {
627 		TAILQ_INSERT_TAIL(&module_list, mod, mod_chain);
628 	}
629 	module_count++;
630 	module_gen++;
631 }
632 
633 /*
634  * module_do_builtin:
635  *
636  *	Initialize a module from the list of modules that are
637  *	already linked into the kernel.
638  */
639 static int
640 module_do_builtin(const char *name, module_t **modp)
641 {
642 	const char *p, *s;
643 	char buf[MAXMODNAME];
644 	modinfo_t *mi = NULL;
645 	module_t *mod, *mod2, *mod_loaded;
646 	size_t len;
647 	int error;
648 
649 	KASSERT(mutex_owned(&module_lock));
650 
651 	/*
652 	 * Search the list to see if we have a module by this name.
653 	 */
654 	TAILQ_FOREACH(mod, &module_builtins, mod_chain) {
655 		if (strcmp(mod->mod_info->mi_name, name) == 0) {
656 			mi = mod->mod_info;
657 			break;
658 		}
659 	}
660 
661 	/*
662 	 * Check to see if already loaded.  This might happen if we
663 	 * were already loaded as a dependency.
664 	 */
665 	if ((mod_loaded = module_lookup(name)) != NULL) {
666 		KASSERT(mod == NULL);
667 		if (modp)
668 			*modp = mod_loaded;
669 		return 0;
670 	}
671 
672 	/* Note! This is from TAILQ, not immediate above */
673 	if (mi == NULL)
674 		panic("can't find `%s'", name);
675 
676 	/*
677 	 * Initialize pre-requisites.
678 	 */
679 	if (mi->mi_required != NULL) {
680 		for (s = mi->mi_required; *s != '\0'; s = p) {
681 			if (*s == ',')
682 				s++;
683 			p = s;
684 			while (*p != '\0' && *p != ',')
685 				p++;
686 			len = min(p - s + 1, sizeof(buf));
687 			strlcpy(buf, s, len);
688 			if (buf[0] == '\0')
689 				break;
690 			if (mod->mod_nrequired == MAXMODDEPS - 1) {
691 				module_error("too many required modules");
692 				return EINVAL;
693 			}
694 			error = module_do_builtin(buf, &mod2);
695 			if (error != 0) {
696 				return error;
697 			}
698 			mod->mod_required[mod->mod_nrequired++] = mod2;
699 		}
700 	}
701 
702 	/*
703 	 * Try to initialize the module.
704 	 */
705 	KASSERT(module_active == NULL);
706 	module_active = mod;
707 	error = (*mi->mi_modcmd)(MODULE_CMD_INIT, NULL);
708 	module_active = NULL;
709 	if (error != 0) {
710 		module_error("builtin module `%s' "
711 		    "failed to init", mi->mi_name);
712 		return error;
713 	}
714 
715 	/* load always succeeds after this point */
716 
717 	TAILQ_REMOVE(&module_builtins, mod, mod_chain);
718 	module_builtinlist--;
719 	if (modp != NULL) {
720 		*modp = mod;
721 	}
722 	if (mi->mi_class == MODULE_CLASS_SECMODEL)
723 		secmodel_register();
724 	module_enqueue(mod);
725 	return 0;
726 }
727 
728 /*
729  * module_do_load:
730  *
731  *	Helper routine: load a module from the file system, or one
732  *	pushed by the boot loader.
733  */
734 static int
735 module_do_load(const char *name, bool isdep, int flags,
736 	       prop_dictionary_t props, module_t **modp, modclass_t class,
737 	       bool autoload)
738 {
739 	static TAILQ_HEAD(,module) pending = TAILQ_HEAD_INITIALIZER(pending);
740 	static int depth;
741 	const int maxdepth = 6;
742 	modinfo_t *mi;
743 	module_t *mod, *mod2;
744 	prop_dictionary_t filedict;
745 	char buf[MAXMODNAME];
746 	const char *s, *p;
747 	int error;
748 	size_t len;
749 
750 	KASSERT(mutex_owned(&module_lock));
751 
752 	filedict = NULL;
753 	error = 0;
754 
755 	/*
756 	 * Avoid recursing too far.
757 	 */
758 	if (++depth > maxdepth) {
759 		module_error("too many required modules");
760 		depth--;
761 		return EMLINK;
762 	}
763 
764 	/*
765 	 * Search the list of disabled builtins first.
766 	 */
767 	TAILQ_FOREACH(mod, &module_builtins, mod_chain) {
768 		if (strcmp(mod->mod_info->mi_name, name) == 0) {
769 			break;
770 		}
771 	}
772 	if (mod) {
773 		if ((flags & MODCTL_LOAD_FORCE) == 0) {
774 			if (!autoload) {
775 				module_error("use -f to reinstate "
776 				    "builtin module \"%s\"", name);
777 			}
778 			depth--;
779 			return EPERM;
780 		} else {
781 			error = module_do_builtin(name, NULL);
782 			depth--;
783 			return error;
784 		}
785 	}
786 
787 	/*
788 	 * Load the module and link.  Before going to the file system,
789 	 * scan the list of modules loaded by the boot loader.
790 	 */
791 	TAILQ_FOREACH(mod, &module_bootlist, mod_chain) {
792 		if (strcmp(mod->mod_info->mi_name, name) == 0) {
793 			TAILQ_REMOVE(&module_bootlist, mod, mod_chain);
794 			break;
795 		}
796 	}
797 	if (mod != NULL) {
798 		TAILQ_INSERT_TAIL(&pending, mod, mod_chain);
799 	} else {
800 		/*
801 		 * If a requisite module, check to see if it is
802 		 * already present.
803 		 */
804 		if (isdep) {
805 			TAILQ_FOREACH(mod, &module_list, mod_chain) {
806 				if (strcmp(mod->mod_info->mi_name, name) == 0) {
807 					break;
808 				}
809 			}
810 			if (mod != NULL) {
811 				if (modp != NULL) {
812 					*modp = mod;
813 				}
814 				depth--;
815 				return 0;
816 			}
817 		}
818 		mod = kmem_zalloc(sizeof(*mod), KM_SLEEP);
819 		if (mod == NULL) {
820 			module_error("out of memory for `%s'", name);
821 			depth--;
822 			return ENOMEM;
823 		}
824 
825 		error = module_load_vfs(name, flags, autoload, mod, &filedict);
826 		if (error != 0) {
827 			kmem_free(mod, sizeof(*mod));
828 			depth--;
829 			return error;
830 		}
831 		mod->mod_source = MODULE_SOURCE_FILESYS;
832 		TAILQ_INSERT_TAIL(&pending, mod, mod_chain);
833 
834 		error = module_fetch_info(mod);
835 		if (error != 0) {
836 			module_error("cannot fetch module info for `%s'",
837 			    name);
838 			goto fail;
839 		}
840 	}
841 
842 	/*
843 	 * Check compatibility.
844 	 */
845 	mi = mod->mod_info;
846 	if (strlen(mi->mi_name) >= MAXMODNAME) {
847 		error = EINVAL;
848 		module_error("module name `%s' too long", mi->mi_name);
849 		goto fail;
850 	}
851 	if (!module_compatible(mi->mi_version, __NetBSD_Version__)) {
852 		module_error("module built for `%d', system `%d'",
853 		    mi->mi_version, __NetBSD_Version__);
854 		if ((flags & MODCTL_LOAD_FORCE) != 0) {
855 			module_error("forced load, system may be unstable");
856 		} else {
857 			error = EPROGMISMATCH;
858 			goto fail;
859 		}
860 	}
861 
862 	/*
863 	 * If a specific kind of module was requested, ensure that we have
864 	 * a match.
865 	 */
866 	if (class != MODULE_CLASS_ANY && class != mi->mi_class) {
867 		module_print("incompatible module class for `%s' (%d != %d)",
868 		    name, class, mi->mi_class);
869 		error = ENOENT;
870 		goto fail;
871 	}
872 
873 	/*
874 	 * If loading a dependency, `name' is a plain module name.
875 	 * The name must match.
876 	 */
877 	if (isdep && strcmp(mi->mi_name, name) != 0) {
878 		module_error("dependency name mismatch (`%s' != `%s')",
879 		    name, mi->mi_name);
880 		error = ENOENT;
881 		goto fail;
882 	}
883 
884 	/*
885 	 * Check to see if the module is already loaded.  If so, we may
886 	 * have been recursively called to handle a dependency, so be sure
887 	 * to set modp.
888 	 */
889 	if ((mod2 = module_lookup(mi->mi_name)) != NULL) {
890 		if (modp != NULL)
891 			*modp = mod2;
892 		module_print("module `%s' already loaded", mi->mi_name);
893 		error = EEXIST;
894 		goto fail;
895 	}
896 
897 	/*
898 	 * Block circular dependencies.
899 	 */
900 	TAILQ_FOREACH(mod2, &pending, mod_chain) {
901 		if (mod == mod2) {
902 			continue;
903 		}
904 		if (strcmp(mod2->mod_info->mi_name, mi->mi_name) == 0) {
905 		    	error = EDEADLK;
906 			module_error("circular dependency detected for `%s'",
907 			    mi->mi_name);
908 		    	goto fail;
909 		}
910 	}
911 
912 	/*
913 	 * Now try to load any requisite modules.
914 	 */
915 	if (mi->mi_required != NULL) {
916 		for (s = mi->mi_required; *s != '\0'; s = p) {
917 			if (*s == ',')
918 				s++;
919 			p = s;
920 			while (*p != '\0' && *p != ',')
921 				p++;
922 			len = p - s + 1;
923 			if (len >= MAXMODNAME) {
924 				error = EINVAL;
925 				module_error("required module name `%s'"
926 				    " too long", mi->mi_required);
927 				goto fail;
928 			}
929 			strlcpy(buf, s, len);
930 			if (buf[0] == '\0')
931 				break;
932 			if (mod->mod_nrequired == MAXMODDEPS - 1) {
933 				error = EINVAL;
934 				module_error("too many required modules (%d)",
935 				    mod->mod_nrequired);
936 				goto fail;
937 			}
938 			if (strcmp(buf, mi->mi_name) == 0) {
939 				error = EDEADLK;
940 				module_error("self-dependency detected for "
941 				   "`%s'", mi->mi_name);
942 				goto fail;
943 			}
944 			error = module_do_load(buf, true, flags, NULL,
945 			    &mod->mod_required[mod->mod_nrequired++],
946 			    MODULE_CLASS_ANY, true);
947 			if (error != 0)
948 				goto fail;
949 		}
950 	}
951 
952 	/*
953 	 * We loaded all needed modules successfully: perform global
954 	 * relocations and initialize.
955 	 */
956 	error = kobj_affix(mod->mod_kobj, mi->mi_name);
957 	if (error != 0) {
958 		/* Cannot touch 'mi' as the module is now gone. */
959 		module_error("unable to affix module `%s'", name);
960 		goto fail2;
961 	}
962 
963 	if (filedict) {
964 		if (!module_merge_dicts(filedict, props)) {
965 			module_error("module properties failed");
966 			error = EINVAL;
967 			goto fail;
968 		}
969 	}
970 	KASSERT(module_active == NULL);
971 	module_active = mod;
972 	error = (*mi->mi_modcmd)(MODULE_CMD_INIT, filedict ? filedict : props);
973 	module_active = NULL;
974 	if (filedict) {
975 		prop_object_release(filedict);
976 		filedict = NULL;
977 	}
978 	if (error != 0) {
979 		module_error("modcmd function returned error %d for `%s'",
980 		    error, mi->mi_name);
981 		goto fail;
982 	}
983 
984 	if (mi->mi_class == MODULE_CLASS_SECMODEL)
985 		secmodel_register();
986 
987 	/*
988 	 * Good, the module loaded successfully.  Put it onto the
989 	 * list and add references to its requisite modules.
990 	 */
991 	TAILQ_REMOVE(&pending, mod, mod_chain);
992 	module_enqueue(mod);
993 	if (modp != NULL) {
994 		*modp = mod;
995 	}
996 	if (autoload) {
997 		/*
998 		 * Arrange to try unloading the module after
999 		 * a short delay.
1000 		 */
1001 		mod->mod_autotime = time_second + module_autotime;
1002 		module_thread_kick();
1003 	}
1004 	depth--;
1005 	return 0;
1006 
1007  fail:
1008 	kobj_unload(mod->mod_kobj);
1009  fail2:
1010 	if (filedict != NULL) {
1011 		prop_object_release(filedict);
1012 		filedict = NULL;
1013 	}
1014 	TAILQ_REMOVE(&pending, mod, mod_chain);
1015 	kmem_free(mod, sizeof(*mod));
1016 	depth--;
1017 	return error;
1018 }
1019 
1020 /*
1021  * module_do_unload:
1022  *
1023  *	Helper routine: do the dirty work of unloading a module.
1024  */
1025 static int
1026 module_do_unload(const char *name)
1027 {
1028 	module_t *mod;
1029 	int error;
1030 	u_int i;
1031 
1032 	KASSERT(mutex_owned(&module_lock));
1033 
1034 	mod = module_lookup(name);
1035 	if (mod == NULL) {
1036 		module_error("module `%s' not found", name);
1037 		return ENOENT;
1038 	}
1039 	if (mod->mod_refcnt != 0) {
1040 		module_print("module `%s' busy", name);
1041 		return EBUSY;
1042 	}
1043 	KASSERT(module_active == NULL);
1044 	module_active = mod;
1045 	error = (*mod->mod_info->mi_modcmd)(MODULE_CMD_FINI, NULL);
1046 	module_active = NULL;
1047 	if (error != 0) {
1048 		module_print("cannot unload module `%s' error=%d", name,
1049 		    error);
1050 		return error;
1051 	}
1052 	if (mod->mod_info->mi_class == MODULE_CLASS_SECMODEL)
1053 		secmodel_deregister();
1054 	module_count--;
1055 	TAILQ_REMOVE(&module_list, mod, mod_chain);
1056 	for (i = 0; i < mod->mod_nrequired; i++) {
1057 		mod->mod_required[i]->mod_refcnt--;
1058 	}
1059 	if (mod->mod_kobj != NULL) {
1060 		kobj_unload(mod->mod_kobj);
1061 	}
1062 	if (mod->mod_source == MODULE_SOURCE_KERNEL) {
1063 		mod->mod_nrequired = 0; /* will be re-parsed */
1064 		TAILQ_INSERT_TAIL(&module_builtins, mod, mod_chain);
1065 		module_builtinlist++;
1066 	} else {
1067 		kmem_free(mod, sizeof(*mod));
1068 	}
1069 	module_gen++;
1070 
1071 	return 0;
1072 }
1073 
1074 /*
1075  * module_prime:
1076  *
1077  *	Push a module loaded by the bootloader onto our internal
1078  *	list.
1079  */
1080 int
1081 module_prime(void *base, size_t size)
1082 {
1083 	module_t *mod;
1084 	int error;
1085 
1086 	mod = kmem_zalloc(sizeof(*mod), KM_SLEEP);
1087 	if (mod == NULL) {
1088 		return ENOMEM;
1089 	}
1090 	mod->mod_source = MODULE_SOURCE_BOOT;
1091 
1092 	error = kobj_load_mem(&mod->mod_kobj, base, size);
1093 	if (error != 0) {
1094 		kmem_free(mod, sizeof(*mod));
1095 		module_error("unable to load object pushed by boot loader");
1096 		return error;
1097 	}
1098 	error = module_fetch_info(mod);
1099 	if (error != 0) {
1100 		kobj_unload(mod->mod_kobj);
1101 		kmem_free(mod, sizeof(*mod));
1102 		module_error("unable to load object pushed by boot loader");
1103 		return error;
1104 	}
1105 
1106 	TAILQ_INSERT_TAIL(&module_bootlist, mod, mod_chain);
1107 
1108 	return 0;
1109 }
1110 
1111 /*
1112  * module_fetch_into:
1113  *
1114  *	Fetch modinfo record from a loaded module.
1115  */
1116 static int
1117 module_fetch_info(module_t *mod)
1118 {
1119 	int error;
1120 	void *addr;
1121 	size_t size;
1122 
1123 	/*
1124 	 * Find module info record and check compatibility.
1125 	 */
1126 	error = kobj_find_section(mod->mod_kobj, "link_set_modules",
1127 	    &addr, &size);
1128 	if (error != 0) {
1129 		module_error("`link_set_modules' section not present");
1130 		return error;
1131 	}
1132 	if (size != sizeof(modinfo_t **)) {
1133 		module_error("`link_set_modules' section wrong size");
1134 		return error;
1135 	}
1136 	mod->mod_info = *(modinfo_t **)addr;
1137 
1138 	return 0;
1139 }
1140 
1141 /*
1142  * module_find_section:
1143  *
1144  *	Allows a module that is being initialized to look up a section
1145  *	within its ELF object.
1146  */
1147 int
1148 module_find_section(const char *name, void **addr, size_t *size)
1149 {
1150 
1151 	KASSERT(mutex_owned(&module_lock));
1152 	KASSERT(module_active != NULL);
1153 
1154 	return kobj_find_section(module_active->mod_kobj, name, addr, size);
1155 }
1156 
1157 /*
1158  * module_thread:
1159  *
1160  *	Automatically unload modules.  We try once to unload autoloaded
1161  *	modules after module_autotime seconds.  If the system is under
1162  *	severe memory pressure, we'll try unloading all modules.
1163  */
1164 static void
1165 module_thread(void *cookie)
1166 {
1167 	module_t *mod, *next;
1168 	modinfo_t *mi;
1169 	int error;
1170 
1171 	for (;;) {
1172 		mutex_enter(&module_lock);
1173 		for (mod = TAILQ_FIRST(&module_list); mod != NULL; mod = next) {
1174 			next = TAILQ_NEXT(mod, mod_chain);
1175 			if (mod->mod_source == MODULE_SOURCE_KERNEL)
1176 				continue;
1177 			if (uvmexp.free < uvmexp.freemin) {
1178 				module_thread_ticks = hz;
1179 			} else if (mod->mod_autotime == 0) {
1180 				continue;
1181 			} else if (time_second < mod->mod_autotime) {
1182 				module_thread_ticks = hz;
1183 			    	continue;
1184 			} else {
1185 				mod->mod_autotime = 0;
1186 			}
1187 			/*
1188 			 * If this module wants to avoid autounload then
1189 			 * skip it.  Some modules can ping-pong in and out
1190 			 * because their use is transient but often.
1191 			 * Example: exec_script.
1192 			 */
1193 			mi = mod->mod_info;
1194 			error = (*mi->mi_modcmd)(MODULE_CMD_AUTOUNLOAD, NULL);
1195 			if (error == 0 || error == ENOTTY) {
1196 				(void)module_do_unload(mi->mi_name);
1197 			}
1198 		}
1199 		mutex_exit(&module_lock);
1200 
1201 		mutex_enter(&module_thread_lock);
1202 		(void)cv_timedwait(&module_thread_cv, &module_thread_lock,
1203 		    module_thread_ticks);
1204 		module_thread_ticks = 0;
1205 		mutex_exit(&module_thread_lock);
1206 	}
1207 }
1208 
1209 /*
1210  * module_thread:
1211  *
1212  *	Kick the module thread into action, perhaps because the
1213  *	system is low on memory.
1214  */
1215 void
1216 module_thread_kick(void)
1217 {
1218 
1219 	mutex_enter(&module_thread_lock);
1220 	module_thread_ticks = hz;
1221 	cv_broadcast(&module_thread_cv);
1222 	mutex_exit(&module_thread_lock);
1223 }
1224 
1225 #ifdef DDB
1226 /*
1227  * module_whatis:
1228  *
1229  *	Helper routine for DDB.
1230  */
1231 void
1232 module_whatis(uintptr_t addr, void (*pr)(const char *, ...))
1233 {
1234 	module_t *mod;
1235 	size_t msize;
1236 	vaddr_t maddr;
1237 
1238 	TAILQ_FOREACH(mod, &module_list, mod_chain) {
1239 		if (mod->mod_kobj == NULL) {
1240 			continue;
1241 		}
1242 		if (kobj_stat(mod->mod_kobj, &maddr, &msize) != 0)
1243 			continue;
1244 		if (addr < maddr || addr >= maddr + msize) {
1245 			continue;
1246 		}
1247 		(*pr)("%p is %p+%zu, in kernel module `%s'\n",
1248 		    (void *)addr, (void *)maddr,
1249 		    (size_t)(addr - maddr), mod->mod_info->mi_name);
1250 	}
1251 }
1252 
1253 /*
1254  * module_print_list:
1255  *
1256  *	Helper routine for DDB.
1257  */
1258 void
1259 module_print_list(void (*pr)(const char *, ...))
1260 {
1261 	const char *src;
1262 	module_t *mod;
1263 	size_t msize;
1264 	vaddr_t maddr;
1265 
1266 	(*pr)("%16s %16s %8s %8s\n", "NAME", "TEXT/DATA", "SIZE", "SOURCE");
1267 
1268 	TAILQ_FOREACH(mod, &module_list, mod_chain) {
1269 		switch (mod->mod_source) {
1270 		case MODULE_SOURCE_KERNEL:
1271 			src = "builtin";
1272 			break;
1273 		case MODULE_SOURCE_FILESYS:
1274 			src = "filesys";
1275 			break;
1276 		case MODULE_SOURCE_BOOT:
1277 			src = "boot";
1278 			break;
1279 		default:
1280 			src = "unknown";
1281 			break;
1282 		}
1283 		if (mod->mod_kobj == NULL) {
1284 			maddr = 0;
1285 			msize = 0;
1286 		} else if (kobj_stat(mod->mod_kobj, &maddr, &msize) != 0)
1287 			continue;
1288 		(*pr)("%16s %16lx %8ld %8s\n", mod->mod_info->mi_name,
1289 		    (long)maddr, (long)msize, src);
1290 	}
1291 }
1292 #endif	/* DDB */
1293 
1294 static bool
1295 module_merge_dicts(prop_dictionary_t existing_dict,
1296 		   const prop_dictionary_t new_dict)
1297 {
1298 	prop_dictionary_keysym_t props_keysym;
1299 	prop_object_iterator_t props_iter;
1300 	prop_object_t props_obj;
1301 	const char *props_key;
1302 	bool error;
1303 
1304 	if (new_dict == NULL) {			/* nothing to merge */
1305 		return true;
1306 	}
1307 
1308 	error = false;
1309 	props_iter = prop_dictionary_iterator(new_dict);
1310 	if (props_iter == NULL) {
1311 		return false;
1312 	}
1313 
1314 	while ((props_obj = prop_object_iterator_next(props_iter)) != NULL) {
1315 		props_keysym = (prop_dictionary_keysym_t)props_obj;
1316 		props_key = prop_dictionary_keysym_cstring_nocopy(props_keysym);
1317 		props_obj = prop_dictionary_get_keysym(new_dict, props_keysym);
1318 		if ((props_obj == NULL) || !prop_dictionary_set(existing_dict,
1319 		    props_key, props_obj)) {
1320 			error = true;
1321 			goto out;
1322 		}
1323 	}
1324 	error = false;
1325 
1326 out:
1327 	prop_object_iterator_release(props_iter);
1328 
1329 	return !error;
1330 }
1331