xref: /netbsd-src/sys/kern/kern_module.c (revision 33881f779a77dce6440bdc44610d94de75bebefe)
1 /*	$NetBSD: kern_module.c,v 1.147 2020/02/22 19:51:57 pgoyette Exp $	*/
2 
3 /*-
4  * Copyright (c) 2008 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software developed for The NetBSD Foundation
8  * by Andrew Doran.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  */
31 
32 /*
33  * Kernel module support.
34  */
35 
36 #include <sys/cdefs.h>
37 __KERNEL_RCSID(0, "$NetBSD: kern_module.c,v 1.147 2020/02/22 19:51:57 pgoyette Exp $");
38 
39 #define _MODULE_INTERNAL
40 
41 #ifdef _KERNEL_OPT
42 #include "opt_ddb.h"
43 #include "opt_modular.h"
44 #endif
45 
46 #include <sys/param.h>
47 #include <sys/systm.h>
48 #include <sys/kernel.h>
49 #include <sys/proc.h>
50 #include <sys/lwp.h>
51 #include <sys/kauth.h>
52 #include <sys/kobj.h>
53 #include <sys/kmem.h>
54 #include <sys/module.h>
55 #include <sys/module_hook.h>
56 #include <sys/kthread.h>
57 #include <sys/sysctl.h>
58 #include <sys/lock.h>
59 #include <sys/evcnt.h>
60 
61 #include <uvm/uvm_extern.h>
62 
63 struct vm_map *module_map;
64 const char *module_machine;
65 char	module_base[MODULE_BASE_SIZE];
66 
67 struct modlist        module_list = TAILQ_HEAD_INITIALIZER(module_list);
68 struct modlist        module_builtins = TAILQ_HEAD_INITIALIZER(module_builtins);
69 static struct modlist module_bootlist = TAILQ_HEAD_INITIALIZER(module_bootlist);
70 
71 struct module_callbacks {
72 	TAILQ_ENTRY(module_callbacks) modcb_list;
73 	void (*modcb_load)(struct module *);
74 	void (*modcb_unload)(struct module *);
75 };
76 TAILQ_HEAD(modcblist, module_callbacks);
77 static struct modcblist modcblist;
78 
79 static module_t *module_netbsd;
80 static const modinfo_t module_netbsd_modinfo = {
81 	.mi_version = __NetBSD_Version__,
82 	.mi_class = MODULE_CLASS_MISC,
83 	.mi_name = "netbsd"
84 };
85 
86 static module_t	*module_active;
87 bool		module_verbose_on;
88 #ifdef MODULAR_DEFAULT_AUTOLOAD
89 bool		module_autoload_on = true;
90 #else
91 bool		module_autoload_on = false;
92 #endif
93 u_int		module_count;
94 u_int		module_builtinlist;
95 u_int		module_autotime = 10;
96 u_int		module_gen = 1;
97 static kcondvar_t module_thread_cv;
98 static kmutex_t module_thread_lock;
99 static int	module_thread_ticks;
100 int (*module_load_vfs_vec)(const char *, int, bool, module_t *,
101 			   prop_dictionary_t *) = (void *)eopnotsupp;
102 
103 static kauth_listener_t	module_listener;
104 
105 static specificdata_domain_t module_specificdata_domain;
106 
107 /* Ensure that the kernel's link set isn't empty. */
108 static modinfo_t module_dummy;
109 __link_set_add_rodata(modules, module_dummy);
110 
111 static module_t	*module_newmodule(modsrc_t);
112 static void	module_free(module_t *);
113 static void	module_require_force(module_t *);
114 static int	module_do_load(const char *, bool, int, prop_dictionary_t,
115 		    module_t **, modclass_t modclass, bool);
116 static int	module_do_unload(const char *, bool);
117 static int	module_do_builtin(const module_t *, const char *, module_t **,
118     prop_dictionary_t);
119 static int	module_fetch_info(module_t *);
120 static void	module_thread(void *);
121 
122 static module_t	*module_lookup(const char *);
123 static void	module_enqueue(module_t *);
124 
125 static bool	module_merge_dicts(prop_dictionary_t, const prop_dictionary_t);
126 
127 static void	sysctl_module_setup(void);
128 static int	sysctl_module_autotime(SYSCTLFN_PROTO);
129 
130 static void	module_callback_load(struct module *);
131 static void	module_callback_unload(struct module *);
132 
133 #define MODULE_CLASS_MATCH(mi, modclass) \
134 	((modclass) == MODULE_CLASS_ANY || (modclass) == (mi)->mi_class)
135 
136 static void
137 module_incompat(const modinfo_t *mi, int modclass)
138 {
139 	module_error("incompatible module class for `%s' (%d != %d)",
140 	    mi->mi_name, modclass, mi->mi_class);
141 }
142 
143 struct module *
144 module_kernel(void)
145 {
146 
147 	return module_netbsd;
148 }
149 
150 /*
151  * module_error:
152  *
153  *	Utility function: log an error.
154  */
155 void
156 module_error(const char *fmt, ...)
157 {
158 	va_list ap;
159 
160 	va_start(ap, fmt);
161 	printf("WARNING: module error: ");
162 	vprintf(fmt, ap);
163 	printf("\n");
164 	va_end(ap);
165 }
166 
167 /*
168  * module_print:
169  *
170  *	Utility function: log verbose output.
171  */
172 void
173 module_print(const char *fmt, ...)
174 {
175 	va_list ap;
176 
177 	if (module_verbose_on) {
178 		va_start(ap, fmt);
179 		printf("DEBUG: module: ");
180 		vprintf(fmt, ap);
181 		printf("\n");
182 		va_end(ap);
183 	}
184 }
185 
186 /*
187  * module_name:
188  *
189  *	Utility function: return the module's name.
190  */
191 const char *
192 module_name(struct module *mod)
193 {
194 
195 	return mod->mod_info->mi_name;
196 }
197 
198 /*
199  * module_source:
200  *
201  *	Utility function: return the module's source.
202  */
203 modsrc_t
204 module_source(struct module *mod)
205 {
206 
207 	return mod->mod_source;
208 }
209 
210 static int
211 module_listener_cb(kauth_cred_t cred, kauth_action_t action, void *cookie,
212     void *arg0, void *arg1, void *arg2, void *arg3)
213 {
214 	int result;
215 
216 	result = KAUTH_RESULT_DEFER;
217 
218 	if (action != KAUTH_SYSTEM_MODULE)
219 		return result;
220 
221 	if ((uintptr_t)arg2 != 0)	/* autoload */
222 		result = KAUTH_RESULT_ALLOW;
223 
224 	return result;
225 }
226 
227 /*
228  * Allocate a new module_t
229  */
230 static module_t *
231 module_newmodule(modsrc_t source)
232 {
233 	module_t *mod;
234 
235 	mod = kmem_zalloc(sizeof(*mod), KM_SLEEP);
236 	mod->mod_source = source;
237 	specificdata_init(module_specificdata_domain, &mod->mod_sdref);
238 	return mod;
239 }
240 
241 /*
242  * Free a module_t
243  */
244 static void
245 module_free(module_t *mod)
246 {
247 
248 	specificdata_fini(module_specificdata_domain, &mod->mod_sdref);
249 	if (mod->mod_required)
250 		kmem_free(mod->mod_required, mod->mod_arequired *
251 		    sizeof(module_t *));
252 	kmem_free(mod, sizeof(*mod));
253 }
254 
255 /*
256  * Require the -f (force) flag to load a module
257  */
258 static void
259 module_require_force(struct module *mod)
260 {
261 	SET(mod->mod_flags, MODFLG_MUST_FORCE);
262 }
263 
264 /*
265  * Add modules to the builtin list.  This can done at boottime or
266  * at runtime if the module is linked into the kernel with an
267  * external linker.  All or none of the input will be handled.
268  * Optionally, the modules can be initialized.  If they are not
269  * initialized, module_init_class() or module_load() can be used
270  * later, but these are not guaranteed to give atomic results.
271  */
272 int
273 module_builtin_add(modinfo_t *const *mip, size_t nmodinfo, bool init)
274 {
275 	struct module **modp = NULL, *mod_iter;
276 	int rv = 0, i, mipskip;
277 
278 	if (init) {
279 		rv = kauth_authorize_system(kauth_cred_get(),
280 		    KAUTH_SYSTEM_MODULE, 0, (void *)(uintptr_t)MODCTL_LOAD,
281 		    (void *)(uintptr_t)1, NULL);
282 		if (rv) {
283 			return rv;
284 		}
285 	}
286 
287 	for (i = 0, mipskip = 0; i < nmodinfo; i++) {
288 		if (mip[i] == &module_dummy) {
289 			KASSERT(nmodinfo > 0);
290 			nmodinfo--;
291 		}
292 	}
293 	if (nmodinfo == 0)
294 		return 0;
295 
296 	modp = kmem_zalloc(sizeof(*modp) * nmodinfo, KM_SLEEP);
297 	for (i = 0, mipskip = 0; i < nmodinfo; i++) {
298 		if (mip[i+mipskip] == &module_dummy) {
299 			mipskip++;
300 			continue;
301 		}
302 		modp[i] = module_newmodule(MODULE_SOURCE_KERNEL);
303 		modp[i]->mod_info = mip[i+mipskip];
304 	}
305 	kernconfig_lock();
306 
307 	/* do this in three stages for error recovery and atomicity */
308 
309 	/* first check for presence */
310 	for (i = 0; i < nmodinfo; i++) {
311 		TAILQ_FOREACH(mod_iter, &module_builtins, mod_chain) {
312 			if (strcmp(mod_iter->mod_info->mi_name,
313 			    modp[i]->mod_info->mi_name) == 0)
314 				break;
315 		}
316 		if (mod_iter) {
317 			rv = EEXIST;
318 			goto out;
319 		}
320 
321 		if (module_lookup(modp[i]->mod_info->mi_name) != NULL) {
322 			rv = EEXIST;
323 			goto out;
324 		}
325 	}
326 
327 	/* then add to list */
328 	for (i = 0; i < nmodinfo; i++) {
329 		TAILQ_INSERT_TAIL(&module_builtins, modp[i], mod_chain);
330 		module_builtinlist++;
331 	}
332 
333 	/* finally, init (if required) */
334 	if (init) {
335 		for (i = 0; i < nmodinfo; i++) {
336 			rv = module_do_builtin(modp[i],
337 			    modp[i]->mod_info->mi_name, NULL, NULL);
338 			/* throw in the towel, recovery hard & not worth it */
339 			if (rv)
340 				panic("%s: builtin module \"%s\" init failed:"
341 				    " %d", __func__,
342 				    modp[i]->mod_info->mi_name, rv);
343 		}
344 	}
345 
346  out:
347 	kernconfig_unlock();
348 	if (rv != 0) {
349 		for (i = 0; i < nmodinfo; i++) {
350 			if (modp[i])
351 				module_free(modp[i]);
352 		}
353 	}
354 	kmem_free(modp, sizeof(*modp) * nmodinfo);
355 	return rv;
356 }
357 
358 /*
359  * Optionally fini and remove builtin module from the kernel.
360  * Note: the module will now be unreachable except via mi && builtin_add.
361  */
362 int
363 module_builtin_remove(modinfo_t *mi, bool fini)
364 {
365 	struct module *mod;
366 	int rv = 0;
367 
368 	if (fini) {
369 		rv = kauth_authorize_system(kauth_cred_get(),
370 		    KAUTH_SYSTEM_MODULE, 0, (void *)(uintptr_t)MODCTL_UNLOAD,
371 		    NULL, NULL);
372 		if (rv)
373 			return rv;
374 
375 		kernconfig_lock();
376 		rv = module_do_unload(mi->mi_name, true);
377 		if (rv) {
378 			goto out;
379 		}
380 	} else {
381 		kernconfig_lock();
382 	}
383 	TAILQ_FOREACH(mod, &module_builtins, mod_chain) {
384 		if (strcmp(mod->mod_info->mi_name, mi->mi_name) == 0)
385 			break;
386 	}
387 	if (mod) {
388 		TAILQ_REMOVE(&module_builtins, mod, mod_chain);
389 		module_builtinlist--;
390 	} else {
391 		KASSERT(fini == false);
392 		rv = ENOENT;
393 	}
394 
395  out:
396 	kernconfig_unlock();
397 	return rv;
398 }
399 
400 /*
401  * module_init:
402  *
403  *	Initialize the module subsystem.
404  */
405 void
406 module_init(void)
407 {
408 	__link_set_decl(modules, modinfo_t);
409 	extern struct vm_map *module_map;
410 	modinfo_t *const *mip;
411 	int rv;
412 
413 	if (module_map == NULL) {
414 		module_map = kernel_map;
415 	}
416 	cv_init(&module_thread_cv, "mod_unld");
417 	mutex_init(&module_thread_lock, MUTEX_DEFAULT, IPL_NONE);
418 	TAILQ_INIT(&modcblist);
419 
420 #ifdef MODULAR	/* XXX */
421 	module_init_md();
422 #endif
423 
424 	if (!module_machine)
425 		module_machine = machine;
426 #if __NetBSD_Version__ / 1000000 % 100 == 99	/* -current */
427 	snprintf(module_base, sizeof(module_base), "/stand/%s/%s/modules",
428 	    module_machine, osrelease);
429 #else						/* release */
430 	snprintf(module_base, sizeof(module_base), "/stand/%s/%d.%d/modules",
431 	    module_machine, __NetBSD_Version__ / 100000000,
432 	    __NetBSD_Version__ / 1000000 % 100);
433 #endif
434 
435 	module_listener = kauth_listen_scope(KAUTH_SCOPE_SYSTEM,
436 	    module_listener_cb, NULL);
437 
438 	__link_set_foreach(mip, modules) {
439 		if ((rv = module_builtin_add(mip, 1, false)) != 0)
440 			module_error("builtin %s failed: %d\n",
441 			    (*mip)->mi_name, rv);
442 	}
443 
444 	sysctl_module_setup();
445 	module_specificdata_domain = specificdata_domain_create();
446 
447 	module_netbsd = module_newmodule(MODULE_SOURCE_KERNEL);
448 	module_netbsd->mod_refcnt = 1;
449 	module_netbsd->mod_info = &module_netbsd_modinfo;
450 }
451 
452 /*
453  * module_start_unload_thread:
454  *
455  *	Start the auto unload kthread.
456  */
457 void
458 module_start_unload_thread(void)
459 {
460 	int error;
461 
462 	error = kthread_create(PRI_VM, KTHREAD_MPSAFE, NULL, module_thread,
463 	    NULL, NULL, "modunload");
464 	if (error != 0)
465 		panic("%s: %d", __func__, error);
466 }
467 
468 /*
469  * module_builtin_require_force
470  *
471  * Require MODCTL_MUST_FORCE to load any built-in modules that have
472  * not yet been initialized
473  */
474 void
475 module_builtin_require_force(void)
476 {
477 	module_t *mod;
478 
479 	kernconfig_lock();
480 	TAILQ_FOREACH(mod, &module_builtins, mod_chain) {
481 		module_require_force(mod);
482 	}
483 	kernconfig_unlock();
484 }
485 
486 static struct sysctllog *module_sysctllog;
487 
488 static int
489 sysctl_module_autotime(SYSCTLFN_ARGS)
490 {
491 	struct sysctlnode node;
492 	int t, error;
493 
494 	t = *(int *)rnode->sysctl_data;
495 
496 	node = *rnode;
497 	node.sysctl_data = &t;
498 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
499 	if (error || newp == NULL)
500 		return (error);
501 
502 	if (t < 0)
503 		return (EINVAL);
504 
505 	*(int *)rnode->sysctl_data = t;
506 	return (0);
507 }
508 
509 static void
510 sysctl_module_setup(void)
511 {
512 	const struct sysctlnode *node = NULL;
513 
514 	sysctl_createv(&module_sysctllog, 0, NULL, &node,
515 		CTLFLAG_PERMANENT,
516 		CTLTYPE_NODE, "module",
517 		SYSCTL_DESCR("Module options"),
518 		NULL, 0, NULL, 0,
519 		CTL_KERN, CTL_CREATE, CTL_EOL);
520 
521 	if (node == NULL)
522 		return;
523 
524 	sysctl_createv(&module_sysctllog, 0, &node, NULL,
525 		CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
526 		CTLTYPE_BOOL, "autoload",
527 		SYSCTL_DESCR("Enable automatic load of modules"),
528 		NULL, 0, &module_autoload_on, 0,
529 		CTL_CREATE, CTL_EOL);
530 	sysctl_createv(&module_sysctllog, 0, &node, NULL,
531 		CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
532 		CTLTYPE_BOOL, "verbose",
533 		SYSCTL_DESCR("Enable verbose output"),
534 		NULL, 0, &module_verbose_on, 0,
535 		CTL_CREATE, CTL_EOL);
536 	sysctl_createv(&module_sysctllog, 0, &node, NULL,
537 		CTLFLAG_PERMANENT | CTLFLAG_READONLY,
538 		CTLTYPE_STRING, "path",
539 		SYSCTL_DESCR("Default module load path"),
540 		NULL, 0, module_base, 0,
541 		CTL_CREATE, CTL_EOL);
542 	sysctl_createv(&module_sysctllog, 0, &node, NULL,
543 		CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
544 		CTLTYPE_INT, "autotime",
545 		SYSCTL_DESCR("Auto-unload delay"),
546 		sysctl_module_autotime, 0, &module_autotime, 0,
547 		CTL_CREATE, CTL_EOL);
548 }
549 
550 /*
551  * module_init_class:
552  *
553  *	Initialize all built-in and pre-loaded modules of the
554  *	specified class.
555  */
556 void
557 module_init_class(modclass_t modclass)
558 {
559 	TAILQ_HEAD(, module) bi_fail = TAILQ_HEAD_INITIALIZER(bi_fail);
560 	module_t *mod;
561 	modinfo_t *mi;
562 
563 	kernconfig_lock();
564 	/*
565 	 * Builtins first.  These will not depend on pre-loaded modules
566 	 * (because the kernel would not link).
567 	 */
568 	do {
569 		TAILQ_FOREACH(mod, &module_builtins, mod_chain) {
570 			mi = mod->mod_info;
571 			if (!MODULE_CLASS_MATCH(mi, modclass))
572 				continue;
573 			/*
574 			 * If initializing a builtin module fails, don't try
575 			 * to load it again.  But keep it around and queue it
576 			 * on the builtins list after we're done with module
577 			 * init.  Don't set it to MODFLG_MUST_FORCE in case a
578 			 * future attempt to initialize can be successful.
579 			 * (If the module has previously been set to
580 			 * MODFLG_MUST_FORCE, don't try to override that!)
581 			 */
582 			if (ISSET(mod->mod_flags, MODFLG_MUST_FORCE) ||
583 			    module_do_builtin(mod, mi->mi_name, NULL,
584 			    NULL) != 0) {
585 				TAILQ_REMOVE(&module_builtins, mod, mod_chain);
586 				TAILQ_INSERT_TAIL(&bi_fail, mod, mod_chain);
587 			}
588 			break;
589 		}
590 	} while (mod != NULL);
591 
592 	/*
593 	 * Now preloaded modules.  These will be pulled off the
594 	 * list as we call module_do_load();
595 	 */
596 	do {
597 		TAILQ_FOREACH(mod, &module_bootlist, mod_chain) {
598 			mi = mod->mod_info;
599 			if (!MODULE_CLASS_MATCH(mi, modclass))
600 				continue;
601 			module_do_load(mi->mi_name, false, 0, NULL, NULL,
602 			    modclass, false);
603 			break;
604 		}
605 	} while (mod != NULL);
606 
607 	/* return failed builtin modules to builtin list */
608 	while ((mod = TAILQ_FIRST(&bi_fail)) != NULL) {
609 		TAILQ_REMOVE(&bi_fail, mod, mod_chain);
610 		TAILQ_INSERT_TAIL(&module_builtins, mod, mod_chain);
611 	}
612 
613 	kernconfig_unlock();
614 }
615 
616 /*
617  * module_compatible:
618  *
619  *	Return true if the two supplied kernel versions are said to
620  *	have the same binary interface for kernel code.  The entire
621  *	version is signficant for the development tree (-current),
622  *	major and minor versions are significant for official
623  *	releases of the system.
624  */
625 bool
626 module_compatible(int v1, int v2)
627 {
628 
629 #if __NetBSD_Version__ / 1000000 % 100 == 99	/* -current */
630 	return v1 == v2;
631 #else						/* release */
632 	return abs(v1 - v2) < 10000;
633 #endif
634 }
635 
636 /*
637  * module_load:
638  *
639  *	Load a single module from the file system.
640  */
641 int
642 module_load(const char *filename, int flags, prop_dictionary_t props,
643 	    modclass_t modclass)
644 {
645 	module_t *mod;
646 	int error;
647 
648 	/* Test if we already have the module loaded before
649 	 * authorizing so we have the opportunity to return EEXIST. */
650 	kernconfig_lock();
651 	mod = module_lookup(filename);
652 	if (mod != NULL) {
653 		module_print("%s module `%s' already loaded",
654 		    "requested", filename);
655 		error = EEXIST;
656 		goto out;
657 	}
658 
659 	/* Authorize. */
660 	error = kauth_authorize_system(kauth_cred_get(), KAUTH_SYSTEM_MODULE,
661 	    0, (void *)(uintptr_t)MODCTL_LOAD, NULL, NULL);
662 	if (error != 0)
663 		goto out;
664 
665 	error = module_do_load(filename, false, flags, props, NULL, modclass,
666 	    false);
667 
668 out:
669 	kernconfig_unlock();
670 	return error;
671 }
672 
673 /*
674  * module_autoload:
675  *
676  *	Load a single module from the file system, system initiated.
677  */
678 int
679 module_autoload(const char *filename, modclass_t modclass)
680 {
681 	int error;
682 	struct proc *p = curlwp->l_proc;
683 
684 	kernconfig_lock();
685 
686 	/* Nothing if the user has disabled it. */
687 	if (!module_autoload_on) {
688 		kernconfig_unlock();
689 		return EPERM;
690 	}
691 
692         /* Disallow path separators and magic symlinks. */
693         if (strchr(filename, '/') != NULL || strchr(filename, '@') != NULL ||
694             strchr(filename, '.') != NULL) {
695 		kernconfig_unlock();
696         	return EPERM;
697 	}
698 
699 	/* Authorize. */
700 	error = kauth_authorize_system(kauth_cred_get(), KAUTH_SYSTEM_MODULE,
701 	    0, (void *)(uintptr_t)MODCTL_LOAD, (void *)(uintptr_t)1, NULL);
702 
703 	if (error == 0)
704 		error = module_do_load(filename, false, 0, NULL, NULL, modclass,
705 		    true);
706 
707 	module_print("Autoload for `%s' requested by pid %d (%s), status %d\n",
708 	    filename, p->p_pid, p->p_comm, error);
709 	kernconfig_unlock();
710 	return error;
711 }
712 
713 /*
714  * module_unload:
715  *
716  *	Find and unload a module by name.
717  */
718 int
719 module_unload(const char *name)
720 {
721 	int error;
722 
723 	/* Authorize. */
724 	error = kauth_authorize_system(kauth_cred_get(), KAUTH_SYSTEM_MODULE,
725 	    0, (void *)(uintptr_t)MODCTL_UNLOAD, NULL, NULL);
726 	if (error != 0) {
727 		return error;
728 	}
729 
730 	kernconfig_lock();
731 	error = module_do_unload(name, true);
732 	kernconfig_unlock();
733 
734 	return error;
735 }
736 
737 /*
738  * module_lookup:
739  *
740  *	Look up a module by name.
741  */
742 module_t *
743 module_lookup(const char *name)
744 {
745 	module_t *mod;
746 
747 	KASSERT(kernconfig_is_held());
748 
749 	TAILQ_FOREACH(mod, &module_list, mod_chain) {
750 		if (strcmp(mod->mod_info->mi_name, name) == 0)
751 			break;
752 	}
753 
754 	return mod;
755 }
756 
757 /*
758  * module_hold:
759  *
760  *	Add a single reference to a module.  It's the caller's
761  *	responsibility to ensure that the reference is dropped
762  *	later.
763  */
764 void
765 module_hold(module_t *mod)
766 {
767 
768 	kernconfig_lock();
769 	mod->mod_refcnt++;
770 	kernconfig_unlock();
771 }
772 
773 /*
774  * module_rele:
775  *
776  *	Release a reference acquired with module_hold().
777  */
778 void
779 module_rele(module_t *mod)
780 {
781 
782 	kernconfig_lock();
783 	KASSERT(mod->mod_refcnt > 0);
784 	mod->mod_refcnt--;
785 	kernconfig_unlock();
786 }
787 
788 /*
789  * module_enqueue:
790  *
791  *	Put a module onto the global list and update counters.
792  */
793 void
794 module_enqueue(module_t *mod)
795 {
796 	int i;
797 
798 	KASSERT(kernconfig_is_held());
799 
800 	/*
801 	 * Put new entry at the head of the queue so autounload can unload
802 	 * requisite modules with only one pass through the queue.
803 	 */
804 	TAILQ_INSERT_HEAD(&module_list, mod, mod_chain);
805 	if (mod->mod_nrequired) {
806 
807 		/* Add references to the requisite modules. */
808 		for (i = 0; i < mod->mod_nrequired; i++) {
809 			KASSERT((*mod->mod_required)[i] != NULL);
810 			(*mod->mod_required)[i]->mod_refcnt++;
811 		}
812 	}
813 	module_count++;
814 	module_gen++;
815 }
816 
817 /*
818  * Our array of required module pointers starts with zero entries.  If we
819  * need to add a new entry, and the list is already full, we reallocate a
820  * larger array, adding MAXMODDEPS entries.
821  */
822 static void
823 alloc_required(module_t *mod)
824 {
825 	module_t *(*new)[], *(*old)[];
826 	int areq;
827 	int i;
828 
829 	if (mod->mod_nrequired >= mod->mod_arequired) {
830 		areq = mod->mod_arequired + MAXMODDEPS;
831 		old = mod->mod_required;
832 		new = kmem_zalloc(areq * sizeof(module_t *), KM_SLEEP);
833 		for (i = 0; i < mod->mod_arequired; i++)
834 			(*new)[i] = (*old)[i];
835 		mod->mod_required = new;
836 		if (old)
837 			kmem_free(old, mod->mod_arequired * sizeof(module_t *));
838 		mod->mod_arequired = areq;
839 	}
840 }
841 
842 /*
843  * module_do_builtin:
844  *
845  *	Initialize a module from the list of modules that are
846  *	already linked into the kernel.
847  */
848 static int
849 module_do_builtin(const module_t *pmod, const char *name, module_t **modp,
850     prop_dictionary_t props)
851 {
852 	const char *p, *s;
853 	char buf[MAXMODNAME];
854 	modinfo_t *mi = NULL;
855 	module_t *mod, *mod2, *mod_loaded, *prev_active;
856 	size_t len;
857 	int error;
858 
859 	KASSERT(kernconfig_is_held());
860 
861 	/*
862 	 * Search the list to see if we have a module by this name.
863 	 */
864 	TAILQ_FOREACH(mod, &module_builtins, mod_chain) {
865 		if (strcmp(mod->mod_info->mi_name, name) == 0) {
866 			mi = mod->mod_info;
867 			break;
868 		}
869 	}
870 
871 	/*
872 	 * Check to see if already loaded.  This might happen if we
873 	 * were already loaded as a dependency.
874 	 */
875 	if ((mod_loaded = module_lookup(name)) != NULL) {
876 		KASSERT(mod == NULL);
877 		if (modp)
878 			*modp = mod_loaded;
879 		return 0;
880 	}
881 
882 	/* Note! This is from TAILQ, not immediate above */
883 	if (mi == NULL) {
884 		/*
885 		 * XXX: We'd like to panic here, but currently in some
886 		 * cases (such as nfsserver + nfs), the dependee can be
887 		 * succesfully linked without the dependencies.
888 		 */
889 		module_error("built-in module %s can't find builtin "
890 		    "dependency `%s'", pmod->mod_info->mi_name, name);
891 		return ENOENT;
892 	}
893 
894 	/*
895 	 * Initialize pre-requisites.
896 	 */
897 	KASSERT(mod->mod_required == NULL);
898 	KASSERT(mod->mod_arequired == 0);
899 	KASSERT(mod->mod_nrequired == 0);
900 	if (mi->mi_required != NULL) {
901 		for (s = mi->mi_required; *s != '\0'; s = p) {
902 			if (*s == ',')
903 				s++;
904 			p = s;
905 			while (*p != '\0' && *p != ',')
906 				p++;
907 			len = uimin(p - s + 1, sizeof(buf));
908 			strlcpy(buf, s, len);
909 			if (buf[0] == '\0')
910 				break;
911 			alloc_required(mod);
912 			error = module_do_builtin(mod, buf, &mod2, NULL);
913 			if (error != 0) {
914 				module_error("built-in module %s prerequisite "
915 				    "%s failed, error %d", name, buf, error);
916 				goto fail;
917 			}
918 			(*mod->mod_required)[mod->mod_nrequired++] = mod2;
919 		}
920 	}
921 
922 	/*
923 	 * Try to initialize the module.
924 	 */
925 	prev_active = module_active;
926 	module_active = mod;
927 	error = (*mi->mi_modcmd)(MODULE_CMD_INIT, props);
928 	module_active = prev_active;
929 	if (error != 0) {
930 		module_error("built-in module %s failed its MODULE_CMD_INIT, "
931 		    "error %d", mi->mi_name, error);
932 		goto fail;
933 	}
934 
935 	/* load always succeeds after this point */
936 
937 	TAILQ_REMOVE(&module_builtins, mod, mod_chain);
938 	module_builtinlist--;
939 	if (modp != NULL) {
940 		*modp = mod;
941 	}
942 	module_enqueue(mod);
943 	return 0;
944 
945  fail:
946 	if (mod->mod_required)
947 		kmem_free(mod->mod_required, mod->mod_arequired *
948 		    sizeof(module_t *));
949 	mod->mod_arequired = 0;
950 	mod->mod_nrequired = 0;
951 	mod->mod_required = NULL;
952 	return error;
953 }
954 
955 /*
956  * module_load_sysctl
957  *
958  * Check to see if a non-builtin module has any SYSCTL_SETUP() routine(s)
959  * registered.  If so, call it (them).
960  */
961 
962 static void
963 module_load_sysctl(module_t *mod)
964 {
965 	void (**ls_funcp)(struct sysctllog **);
966 	void *ls_start;
967 	size_t ls_size, count;
968 	int error;
969 
970 	/*
971 	 * Built-in modules don't have a mod_kobj so we cannot search
972 	 * for their link_set_sysctl_funcs
973 	 */
974 	if (mod->mod_source == MODULE_SOURCE_KERNEL)
975 		return;
976 
977 	error = kobj_find_section(mod->mod_kobj, "link_set_sysctl_funcs",
978 	    &ls_start, &ls_size);
979 	if (error == 0) {
980 		count = ls_size / sizeof(ls_start);
981 		ls_funcp = ls_start;
982 		while (count--) {
983 			(**ls_funcp)(&mod->mod_sysctllog);
984 			ls_funcp++;
985 		}
986 	}
987 }
988 
989 /*
990  * module_load_evcnt
991  *
992  * Check to see if a non-builtin module has any static evcnt's defined;
993  * if so, attach them.
994  */
995 
996 static void
997 module_load_evcnt(module_t *mod)
998 {
999 	struct evcnt * const *ls_evp;
1000 	void *ls_start;
1001 	size_t ls_size, count;
1002 	int error;
1003 
1004 	/*
1005 	 * Built-in modules' static evcnt stuff will be handled
1006 	 * automatically as part of general kernel initialization
1007 	 */
1008 	if (mod->mod_source == MODULE_SOURCE_KERNEL)
1009 		return;
1010 
1011 	error = kobj_find_section(mod->mod_kobj, "link_set_evcnts",
1012 	    &ls_start, &ls_size);
1013 	if (error == 0) {
1014 		count = ls_size / sizeof(*ls_evp);
1015 		ls_evp = ls_start;
1016 		while (count--) {
1017 			evcnt_attach_static(*ls_evp++);
1018 		}
1019 	}
1020 }
1021 
1022 /*
1023  * module_unload_evcnt
1024  *
1025  * Check to see if a non-builtin module has any static evcnt's defined;
1026  * if so, detach them.
1027  */
1028 
1029 static void
1030 module_unload_evcnt(module_t *mod)
1031 {
1032 	struct evcnt * const *ls_evp;
1033 	void *ls_start;
1034 	size_t ls_size, count;
1035 	int error;
1036 
1037 	/*
1038 	 * Built-in modules' static evcnt stuff will be handled
1039 	 * automatically as part of general kernel initialization
1040 	 */
1041 	if (mod->mod_source == MODULE_SOURCE_KERNEL)
1042 		return;
1043 
1044 	error = kobj_find_section(mod->mod_kobj, "link_set_evcnts",
1045 	    &ls_start, &ls_size);
1046 	if (error == 0) {
1047 		count = ls_size / sizeof(*ls_evp);
1048 		ls_evp = (void *)((char *)ls_start + ls_size);
1049 		while (count--) {
1050 			evcnt_detach(*--ls_evp);
1051 		}
1052 	}
1053 }
1054 
1055 /*
1056  * module_do_load:
1057  *
1058  *	Helper routine: load a module from the file system, or one
1059  *	pushed by the boot loader.
1060  */
1061 static int
1062 module_do_load(const char *name, bool isdep, int flags,
1063 	       prop_dictionary_t props, module_t **modp, modclass_t modclass,
1064 	       bool autoload)
1065 {
1066 	/* The pending list for this level of recursion */
1067 	TAILQ_HEAD(pending_t, module);
1068 	struct pending_t *pending;
1069 	struct pending_t new_pending = TAILQ_HEAD_INITIALIZER(new_pending);
1070 
1071 	/* The stack of pending lists */
1072 	static SLIST_HEAD(pend_head, pend_entry) pend_stack =
1073 		SLIST_HEAD_INITIALIZER(pend_stack);
1074 	struct pend_entry {
1075 		SLIST_ENTRY(pend_entry) pe_entry;
1076 		struct pending_t *pe_pending;
1077 	} my_pend_entry;
1078 
1079 	modinfo_t *mi;
1080 	module_t *mod, *mod2, *prev_active;
1081 	prop_dictionary_t filedict;
1082 	char buf[MAXMODNAME];
1083 	const char *s, *p;
1084 	int error;
1085 	size_t len;
1086 
1087 	KASSERT(kernconfig_is_held());
1088 
1089 	filedict = NULL;
1090 	error = 0;
1091 
1092 	/*
1093 	 * Set up the pending list for this entry.  If this is an
1094 	 * internal entry (for a dependency), then use the same list
1095 	 * as for the outer call;  otherwise, it's an external entry
1096 	 * (possibly recursive, ie a module's xxx_modcmd(init, ...)
1097 	 * routine called us), so use the locally allocated list.  In
1098 	 * either case, add it to our stack.
1099 	 */
1100 	if (isdep) {
1101 		KASSERT(SLIST_FIRST(&pend_stack) != NULL);
1102 		pending = SLIST_FIRST(&pend_stack)->pe_pending;
1103 	} else
1104 		pending = &new_pending;
1105 	my_pend_entry.pe_pending = pending;
1106 	SLIST_INSERT_HEAD(&pend_stack, &my_pend_entry, pe_entry);
1107 
1108 	/*
1109 	 * Search the list of disabled builtins first.
1110 	 */
1111 	TAILQ_FOREACH(mod, &module_builtins, mod_chain) {
1112 		if (strcmp(mod->mod_info->mi_name, name) == 0) {
1113 			break;
1114 		}
1115 	}
1116 	if (mod) {
1117 		if (ISSET(mod->mod_flags, MODFLG_MUST_FORCE) &&
1118 		    !ISSET(flags, MODCTL_LOAD_FORCE)) {
1119 			if (!autoload) {
1120 				module_error("use -f to reinstate "
1121 				    "builtin module `%s'", name);
1122 			}
1123 			SLIST_REMOVE_HEAD(&pend_stack, pe_entry);
1124 			return EPERM;
1125 		} else {
1126 			SLIST_REMOVE_HEAD(&pend_stack, pe_entry);
1127 			error = module_do_builtin(mod, name, modp, props);
1128 			return error;
1129 		}
1130 	}
1131 
1132 	/*
1133 	 * Load the module and link.  Before going to the file system,
1134 	 * scan the list of modules loaded by the boot loader.
1135 	 */
1136 	TAILQ_FOREACH(mod, &module_bootlist, mod_chain) {
1137 		if (strcmp(mod->mod_info->mi_name, name) == 0) {
1138 			TAILQ_REMOVE(&module_bootlist, mod, mod_chain);
1139 			break;
1140 		}
1141 	}
1142 	if (mod != NULL) {
1143 		TAILQ_INSERT_TAIL(pending, mod, mod_chain);
1144 	} else {
1145 		/*
1146 		 * Check to see if module is already present.
1147 		 */
1148 		mod = module_lookup(name);
1149 		if (mod != NULL) {
1150 			if (modp != NULL) {
1151 				*modp = mod;
1152 			}
1153 			module_print("%s module `%s' already loaded",
1154 			    isdep ? "dependent" : "requested", name);
1155 			SLIST_REMOVE_HEAD(&pend_stack, pe_entry);
1156 			return EEXIST;
1157 		}
1158 
1159 		mod = module_newmodule(MODULE_SOURCE_FILESYS);
1160 		if (mod == NULL) {
1161 			module_error("out of memory for `%s'", name);
1162 			SLIST_REMOVE_HEAD(&pend_stack, pe_entry);
1163 			return ENOMEM;
1164 		}
1165 
1166 		error = module_load_vfs_vec(name, flags, autoload, mod,
1167 					    &filedict);
1168 		if (error != 0) {
1169 #ifdef DEBUG
1170 			/*
1171 			 * The exec class of modules contains a list of
1172 			 * modules that is the union of all the modules
1173 			 * available for each architecture, so we don't
1174 			 * print an error if they are missing.
1175 			 */
1176 			if ((modclass != MODULE_CLASS_EXEC || error != ENOENT)
1177 			    && root_device != NULL)
1178 				module_error("vfs load failed for `%s', "
1179 				    "error %d", name, error);
1180 #endif
1181 			SLIST_REMOVE_HEAD(&pend_stack, pe_entry);
1182 			module_free(mod);
1183 			return error;
1184 		}
1185 		TAILQ_INSERT_TAIL(pending, mod, mod_chain);
1186 
1187 		error = module_fetch_info(mod);
1188 		if (error != 0) {
1189 			module_error("cannot fetch info for `%s', error %d",
1190 			    name, error);
1191 			goto fail;
1192 		}
1193 	}
1194 
1195 	/*
1196 	 * Check compatibility.
1197 	 */
1198 	mi = mod->mod_info;
1199 	if (strnlen(mi->mi_name, MAXMODNAME) >= MAXMODNAME) {
1200 		error = EINVAL;
1201 		module_error("module name `%s' longer than %d", mi->mi_name,
1202 		    MAXMODNAME);
1203 		goto fail;
1204 	}
1205 	if (mi->mi_class <= MODULE_CLASS_ANY ||
1206 	    mi->mi_class >= MODULE_CLASS_MAX) {
1207 		error = EINVAL;
1208 		module_error("module `%s' has invalid class %d",
1209 		    mi->mi_name, mi->mi_class);
1210 		    goto fail;
1211 	}
1212 	if (!module_compatible(mi->mi_version, __NetBSD_Version__)) {
1213 		module_error("module `%s' built for `%d', system `%d'",
1214 		    mi->mi_name, mi->mi_version, __NetBSD_Version__);
1215 		if (ISSET(flags, MODCTL_LOAD_FORCE)) {
1216 			module_error("forced load, system may be unstable");
1217 		} else {
1218 			error = EPROGMISMATCH;
1219 			goto fail;
1220 		}
1221 	}
1222 
1223 	/*
1224 	 * If a specific kind of module was requested, ensure that we have
1225 	 * a match.
1226 	 */
1227 	if (!MODULE_CLASS_MATCH(mi, modclass)) {
1228 		module_incompat(mi, modclass);
1229 		error = ENOENT;
1230 		goto fail;
1231 	}
1232 
1233 	/*
1234 	 * If loading a dependency, `name' is a plain module name.
1235 	 * The name must match.
1236 	 */
1237 	if (isdep && strcmp(mi->mi_name, name) != 0) {
1238 		module_error("dependency name mismatch (`%s' != `%s')",
1239 		    name, mi->mi_name);
1240 		error = ENOENT;
1241 		goto fail;
1242 	}
1243 
1244 	/*
1245 	 * If we loaded a module from the filesystem, check the actual
1246 	 * module name (from the modinfo_t) to ensure another module
1247 	 * with the same name doesn't already exist.  (There's no
1248 	 * guarantee the filename will match the module name, and the
1249 	 * dup-symbols check may not be sufficient.)
1250 	 */
1251 	if (mod->mod_source == MODULE_SOURCE_FILESYS) {
1252 		mod2 = module_lookup(mod->mod_info->mi_name);
1253 		if ( mod2 && mod2 != mod) {
1254 			module_error("module with name `%s' already loaded",
1255 			    mod2->mod_info->mi_name);
1256 			error = EEXIST;
1257 			if (modp != NULL)
1258 				*modp = mod2;
1259 			goto fail;
1260 		}
1261 	}
1262 
1263 	/*
1264 	 * Block circular dependencies.
1265 	 */
1266 	TAILQ_FOREACH(mod2, pending, mod_chain) {
1267 		if (mod == mod2) {
1268 			continue;
1269 		}
1270 		if (strcmp(mod2->mod_info->mi_name, mi->mi_name) == 0) {
1271 			error = EDEADLK;
1272 			module_error("circular dependency detected for `%s'",
1273 			    mi->mi_name);
1274 			goto fail;
1275 		}
1276 	}
1277 
1278 	/*
1279 	 * Now try to load any requisite modules.
1280 	 */
1281 	if (mi->mi_required != NULL) {
1282 		mod->mod_arequired = 0;
1283 		for (s = mi->mi_required; *s != '\0'; s = p) {
1284 			if (*s == ',')
1285 				s++;
1286 			p = s;
1287 			while (*p != '\0' && *p != ',')
1288 				p++;
1289 			len = p - s + 1;
1290 			if (len >= MAXMODNAME) {
1291 				error = EINVAL;
1292 				module_error("required module name `%s' "
1293 				    "longer than %d", mi->mi_required,
1294 				    MAXMODNAME);
1295 				goto fail;
1296 			}
1297 			strlcpy(buf, s, len);
1298 			if (buf[0] == '\0')
1299 				break;
1300 			alloc_required(mod);
1301 			if (strcmp(buf, mi->mi_name) == 0) {
1302 				error = EDEADLK;
1303 				module_error("self-dependency detected for "
1304 				   "`%s'", mi->mi_name);
1305 				goto fail;
1306 			}
1307 			error = module_do_load(buf, true, flags, NULL,
1308 			    &mod2, MODULE_CLASS_ANY, true);
1309 			if (error != 0 && error != EEXIST) {
1310 				module_error("recursive load failed for `%s' "
1311 				    "(`%s' required), error %d", mi->mi_name,
1312 				    buf, error);
1313 				goto fail;
1314 			}
1315 			(*mod->mod_required)[mod->mod_nrequired++] = mod2;
1316 		}
1317 	}
1318 
1319 	/*
1320 	 * We loaded all needed modules successfully: perform global
1321 	 * relocations and initialize.
1322 	 */
1323 	{
1324 		char xname[MAXMODNAME];
1325 
1326 		/*
1327 		 * In case of error the entire module is gone, so we
1328 		 * need to save its name for possible error report.
1329 		 */
1330 
1331 		strlcpy(xname, mi->mi_name, MAXMODNAME);
1332 		error = kobj_affix(mod->mod_kobj, mi->mi_name);
1333 		if (error != 0) {
1334 			module_error("unable to affix module `%s', error %d",
1335 			    xname, error);
1336 			goto fail2;
1337 		}
1338 	}
1339 
1340 	if (filedict) {
1341 		if (!module_merge_dicts(filedict, props)) {
1342 			module_error("module properties failed for %s", name);
1343 			error = EINVAL;
1344 			goto fail;
1345 		}
1346 	}
1347 
1348 	prev_active = module_active;
1349 	module_active = mod;
1350 	error = (*mi->mi_modcmd)(MODULE_CMD_INIT, filedict ? filedict : props);
1351 	module_active = prev_active;
1352 	if (filedict) {
1353 		prop_object_release(filedict);
1354 		filedict = NULL;
1355 	}
1356 	if (error != 0) {
1357 		module_error("modcmd(CMD_INIT) failed for `%s', error %d",
1358 		    mi->mi_name, error);
1359 		goto fail;
1360 	}
1361 
1362 	/*
1363 	 * If a recursive load already added a module with the same
1364 	 * name, abort.
1365 	 */
1366 	mod2 = module_lookup(mi->mi_name);
1367 	if (mod2 && mod2 != mod) {
1368 		module_error("recursive load causes duplicate module `%s'",
1369 		    mi->mi_name);
1370 		error = EEXIST;
1371 		goto fail1;
1372 	}
1373 
1374 	module_load_sysctl(mod);	/* Set-up module's sysctl if any */
1375 	module_load_evcnt(mod);		/* Attach any static evcnt needed */
1376 
1377 	/*
1378 	 * Good, the module loaded successfully.  Put it onto the
1379 	 * list and add references to its requisite modules.
1380 	 */
1381 	TAILQ_REMOVE(pending, mod, mod_chain);
1382 	module_enqueue(mod);
1383 	if (modp != NULL) {
1384 		*modp = mod;
1385 	}
1386 	if (autoload && module_autotime > 0) {
1387 		/*
1388 		 * Arrange to try unloading the module after
1389 		 * a short delay unless auto-unload is disabled.
1390 		 */
1391 		mod->mod_autotime = time_second + module_autotime;
1392 		SET(mod->mod_flags, MODFLG_AUTO_LOADED);
1393 		module_thread_kick();
1394 	}
1395 	SLIST_REMOVE_HEAD(&pend_stack, pe_entry);
1396 	module_print("module `%s' loaded successfully", mi->mi_name);
1397 	module_callback_load(mod);
1398 	return 0;
1399 
1400  fail1:
1401 	(*mi->mi_modcmd)(MODULE_CMD_FINI, NULL);
1402  fail:
1403 	kobj_unload(mod->mod_kobj);
1404  fail2:
1405 	if (filedict != NULL) {
1406 		prop_object_release(filedict);
1407 		filedict = NULL;
1408 	}
1409 	TAILQ_REMOVE(pending, mod, mod_chain);
1410 	SLIST_REMOVE_HEAD(&pend_stack, pe_entry);
1411 	module_free(mod);
1412 	return error;
1413 }
1414 
1415 /*
1416  * module_do_unload:
1417  *
1418  *	Helper routine: do the dirty work of unloading a module.
1419  */
1420 static int
1421 module_do_unload(const char *name, bool load_requires_force)
1422 {
1423 	module_t *mod, *prev_active;
1424 	int error;
1425 	u_int i;
1426 
1427 	KASSERT(kernconfig_is_held());
1428 	KASSERT(name != NULL);
1429 
1430 	module_print("unload requested for '%s' (%s)", name,
1431 	    load_requires_force ? "TRUE" : "FALSE");
1432 	mod = module_lookup(name);
1433 	if (mod == NULL) {
1434 		module_error("module `%s' not found", name);
1435 		return ENOENT;
1436 	}
1437 	if (mod->mod_refcnt != 0) {
1438 		module_print("module `%s' busy (%d refs)", name,
1439 		    mod->mod_refcnt);
1440 		return EBUSY;
1441 	}
1442 
1443 	/*
1444 	 * Builtin secmodels are there to stay.
1445 	 */
1446 	if (mod->mod_source == MODULE_SOURCE_KERNEL &&
1447 	    mod->mod_info->mi_class == MODULE_CLASS_SECMODEL) {
1448 		module_print("cannot unload built-in secmodel module `%s'",
1449 		    name);
1450 		return EPERM;
1451 	}
1452 
1453 	prev_active = module_active;
1454 	module_active = mod;
1455 	module_callback_unload(mod);
1456 
1457 	/*
1458 	 * If there were any registered SYSCTL_SETUP funcs, make sure
1459 	 * we release the sysctl entries
1460 	 */
1461 	if (mod->mod_sysctllog) {
1462 		sysctl_teardown(&mod->mod_sysctllog);
1463 	}
1464 	module_unload_evcnt(mod);
1465 	error = (*mod->mod_info->mi_modcmd)(MODULE_CMD_FINI, NULL);
1466 	module_active = prev_active;
1467 	if (error != 0) {
1468 		module_load_sysctl(mod);	/* re-enable sysctl stuff */
1469 		module_load_evcnt(mod);		/* and reenable evcnts */
1470 		module_print("cannot unload module `%s' error=%d", name,
1471 		    error);
1472 		return error;
1473 	}
1474 	module_count--;
1475 	TAILQ_REMOVE(&module_list, mod, mod_chain);
1476 	for (i = 0; i < mod->mod_nrequired; i++) {
1477 		(*mod->mod_required)[i]->mod_refcnt--;
1478 	}
1479 	module_print("unloaded module `%s'", name);
1480 	if (mod->mod_kobj != NULL) {
1481 		kobj_unload(mod->mod_kobj);
1482 	}
1483 	if (mod->mod_source == MODULE_SOURCE_KERNEL) {
1484 		if (mod->mod_required != NULL) {
1485 			/*
1486 			 * release "required" resources - will be re-parsed
1487 			 * if the module is re-enabled
1488 			 */
1489 			kmem_free(mod->mod_required,
1490 			    mod->mod_arequired * sizeof(module_t *));
1491 			mod->mod_nrequired = 0;
1492 			mod->mod_arequired = 0;
1493 			mod->mod_required = NULL;
1494 		}
1495 		if (load_requires_force)
1496 			module_require_force(mod);
1497 		TAILQ_INSERT_TAIL(&module_builtins, mod, mod_chain);
1498 		module_builtinlist++;
1499 	} else {
1500 		module_free(mod);
1501 	}
1502 	module_gen++;
1503 
1504 	return 0;
1505 }
1506 
1507 /*
1508  * module_prime:
1509  *
1510  *	Push a module loaded by the bootloader onto our internal
1511  *	list.
1512  */
1513 int
1514 module_prime(const char *name, void *base, size_t size)
1515 {
1516 	__link_set_decl(modules, modinfo_t);
1517 	modinfo_t *const *mip;
1518 	module_t *mod;
1519 	int error;
1520 
1521 	/* Check for module name same as a built-in module */
1522 
1523 	__link_set_foreach(mip, modules) {
1524 		if (*mip == &module_dummy)
1525 			continue;
1526 		if (strcmp((*mip)->mi_name, name) == 0) {
1527 			module_error("module `%s' pushed by boot loader "
1528 			    "already exists", name);
1529 			return EEXIST;
1530 		}
1531 	}
1532 
1533 	/* Also eliminate duplicate boolist entries */
1534 
1535 	TAILQ_FOREACH(mod, &module_bootlist, mod_chain) {
1536 		if (strcmp(mod->mod_info->mi_name, name) == 0) {
1537 			module_error("duplicate bootlist entry for module "
1538 			    "`%s'", name);
1539 			return EEXIST;
1540 		}
1541 	}
1542 
1543 	mod = module_newmodule(MODULE_SOURCE_BOOT);
1544 	if (mod == NULL) {
1545 		return ENOMEM;
1546 	}
1547 
1548 	error = kobj_load_mem(&mod->mod_kobj, name, base, size);
1549 	if (error != 0) {
1550 		module_free(mod);
1551 		module_error("unable to load `%s' pushed by boot loader, "
1552 		    "error %d", name, error);
1553 		return error;
1554 	}
1555 	error = module_fetch_info(mod);
1556 	if (error != 0) {
1557 		kobj_unload(mod->mod_kobj);
1558 		module_free(mod);
1559 		module_error("unable to fetch_info for `%s' pushed by boot "
1560 		    "loader, error %d", name, error);
1561 		return error;
1562 	}
1563 
1564 	TAILQ_INSERT_TAIL(&module_bootlist, mod, mod_chain);
1565 
1566 	return 0;
1567 }
1568 
1569 /*
1570  * module_fetch_into:
1571  *
1572  *	Fetch modinfo record from a loaded module.
1573  */
1574 static int
1575 module_fetch_info(module_t *mod)
1576 {
1577 	int error;
1578 	void *addr;
1579 	size_t size;
1580 
1581 	/*
1582 	 * Find module info record and check compatibility.
1583 	 */
1584 	error = kobj_find_section(mod->mod_kobj, "link_set_modules",
1585 	    &addr, &size);
1586 	if (error != 0) {
1587 		module_error("`link_set_modules' section not present, "
1588 		    "error %d", error);
1589 		return error;
1590 	}
1591 	if (size != sizeof(modinfo_t **)) {
1592 		module_error("`link_set_modules' section wrong size "
1593 		    "(got %zu, wanted %zu)", size, sizeof(modinfo_t **));
1594 		return ENOEXEC;
1595 	}
1596 	mod->mod_info = *(modinfo_t **)addr;
1597 
1598 	return 0;
1599 }
1600 
1601 /*
1602  * module_find_section:
1603  *
1604  *	Allows a module that is being initialized to look up a section
1605  *	within its ELF object.
1606  */
1607 int
1608 module_find_section(const char *name, void **addr, size_t *size)
1609 {
1610 
1611 	KASSERT(kernconfig_is_held());
1612 	KASSERT(module_active != NULL);
1613 
1614 	return kobj_find_section(module_active->mod_kobj, name, addr, size);
1615 }
1616 
1617 /*
1618  * module_thread:
1619  *
1620  *	Automatically unload modules.  We try once to unload autoloaded
1621  *	modules after module_autotime seconds.  If the system is under
1622  *	severe memory pressure, we'll try unloading all modules, else if
1623  *	module_autotime is zero, we don't try to unload, even if the
1624  *	module was previously scheduled for unload.
1625  */
1626 static void
1627 module_thread(void *cookie)
1628 {
1629 	module_t *mod, *next;
1630 	modinfo_t *mi;
1631 	int error;
1632 
1633 	for (;;) {
1634 		kernconfig_lock();
1635 		for (mod = TAILQ_FIRST(&module_list); mod != NULL; mod = next) {
1636 			next = TAILQ_NEXT(mod, mod_chain);
1637 
1638 			/* skip built-in modules */
1639 			if (mod->mod_source == MODULE_SOURCE_KERNEL)
1640 				continue;
1641 			/* skip modules that weren't auto-loaded */
1642 			if (!ISSET(mod->mod_flags, MODFLG_AUTO_LOADED))
1643 				continue;
1644 
1645 			if (uvm_availmem() < uvmexp.freemin) {
1646 				module_thread_ticks = hz;
1647 			} else if (module_autotime == 0 ||
1648 				   mod->mod_autotime == 0) {
1649 				continue;
1650 			} else if (time_second < mod->mod_autotime) {
1651 				module_thread_ticks = hz;
1652 			    	continue;
1653 			} else {
1654 				mod->mod_autotime = 0;
1655 			}
1656 
1657 			/*
1658 			 * If this module wants to avoid autounload then
1659 			 * skip it.  Some modules can ping-pong in and out
1660 			 * because their use is transient but often.
1661 			 * Example: exec_script.
1662 			 */
1663 			mi = mod->mod_info;
1664 			error = (*mi->mi_modcmd)(MODULE_CMD_AUTOUNLOAD, NULL);
1665 			if (error == 0 || error == ENOTTY) {
1666 				(void)module_do_unload(mi->mi_name, false);
1667 			} else
1668 				module_print("module `%s' declined to be "
1669 				    "auto-unloaded error=%d", mi->mi_name,
1670 				    error);
1671 		}
1672 		kernconfig_unlock();
1673 
1674 		mutex_enter(&module_thread_lock);
1675 		(void)cv_timedwait(&module_thread_cv, &module_thread_lock,
1676 		    module_thread_ticks);
1677 		module_thread_ticks = 0;
1678 		mutex_exit(&module_thread_lock);
1679 	}
1680 }
1681 
1682 /*
1683  * module_thread:
1684  *
1685  *	Kick the module thread into action, perhaps because the
1686  *	system is low on memory.
1687  */
1688 void
1689 module_thread_kick(void)
1690 {
1691 
1692 	mutex_enter(&module_thread_lock);
1693 	module_thread_ticks = hz;
1694 	cv_broadcast(&module_thread_cv);
1695 	mutex_exit(&module_thread_lock);
1696 }
1697 
1698 #ifdef DDB
1699 /*
1700  * module_whatis:
1701  *
1702  *	Helper routine for DDB.
1703  */
1704 void
1705 module_whatis(uintptr_t addr, void (*pr)(const char *, ...))
1706 {
1707 	module_t *mod;
1708 	size_t msize;
1709 	vaddr_t maddr;
1710 
1711 	TAILQ_FOREACH(mod, &module_list, mod_chain) {
1712 		if (mod->mod_kobj == NULL) {
1713 			continue;
1714 		}
1715 		if (kobj_stat(mod->mod_kobj, &maddr, &msize) != 0)
1716 			continue;
1717 		if (addr < maddr || addr >= maddr + msize) {
1718 			continue;
1719 		}
1720 		(*pr)("%p is %p+%zu, in kernel module `%s'\n",
1721 		    (void *)addr, (void *)maddr,
1722 		    (size_t)(addr - maddr), mod->mod_info->mi_name);
1723 	}
1724 }
1725 
1726 /*
1727  * module_print_list:
1728  *
1729  *	Helper routine for DDB.
1730  */
1731 void
1732 module_print_list(void (*pr)(const char *, ...))
1733 {
1734 	const char *src;
1735 	module_t *mod;
1736 	size_t msize;
1737 	vaddr_t maddr;
1738 
1739 	(*pr)("%16s %16s %8s %8s\n", "NAME", "TEXT/DATA", "SIZE", "SOURCE");
1740 
1741 	TAILQ_FOREACH(mod, &module_list, mod_chain) {
1742 		switch (mod->mod_source) {
1743 		case MODULE_SOURCE_KERNEL:
1744 			src = "builtin";
1745 			break;
1746 		case MODULE_SOURCE_FILESYS:
1747 			src = "filesys";
1748 			break;
1749 		case MODULE_SOURCE_BOOT:
1750 			src = "boot";
1751 			break;
1752 		default:
1753 			src = "unknown";
1754 			break;
1755 		}
1756 		if (mod->mod_kobj == NULL) {
1757 			maddr = 0;
1758 			msize = 0;
1759 		} else if (kobj_stat(mod->mod_kobj, &maddr, &msize) != 0)
1760 			continue;
1761 		(*pr)("%16s %16lx %8ld %8s\n", mod->mod_info->mi_name,
1762 		    (long)maddr, (long)msize, src);
1763 	}
1764 }
1765 #endif	/* DDB */
1766 
1767 static bool
1768 module_merge_dicts(prop_dictionary_t existing_dict,
1769 		   const prop_dictionary_t new_dict)
1770 {
1771 	prop_dictionary_keysym_t props_keysym;
1772 	prop_object_iterator_t props_iter;
1773 	prop_object_t props_obj;
1774 	const char *props_key;
1775 	bool error;
1776 
1777 	if (new_dict == NULL) {			/* nothing to merge */
1778 		return true;
1779 	}
1780 
1781 	error = false;
1782 	props_iter = prop_dictionary_iterator(new_dict);
1783 	if (props_iter == NULL) {
1784 		return false;
1785 	}
1786 
1787 	while ((props_obj = prop_object_iterator_next(props_iter)) != NULL) {
1788 		props_keysym = (prop_dictionary_keysym_t)props_obj;
1789 		props_key = prop_dictionary_keysym_cstring_nocopy(props_keysym);
1790 		props_obj = prop_dictionary_get_keysym(new_dict, props_keysym);
1791 		if ((props_obj == NULL) || !prop_dictionary_set(existing_dict,
1792 		    props_key, props_obj)) {
1793 			error = true;
1794 			goto out;
1795 		}
1796 	}
1797 	error = false;
1798 
1799 out:
1800 	prop_object_iterator_release(props_iter);
1801 
1802 	return !error;
1803 }
1804 
1805 /*
1806  * module_specific_key_create:
1807  *
1808  *	Create a key for subsystem module-specific data.
1809  */
1810 specificdata_key_t
1811 module_specific_key_create(specificdata_key_t *keyp, specificdata_dtor_t dtor)
1812 {
1813 
1814 	return specificdata_key_create(module_specificdata_domain, keyp, dtor);
1815 }
1816 
1817 /*
1818  * module_specific_key_delete:
1819  *
1820  *	Delete a key for subsystem module-specific data.
1821  */
1822 void
1823 module_specific_key_delete(specificdata_key_t key)
1824 {
1825 
1826 	return specificdata_key_delete(module_specificdata_domain, key);
1827 }
1828 
1829 /*
1830  * module_getspecific:
1831  *
1832  *	Return module-specific data corresponding to the specified key.
1833  */
1834 void *
1835 module_getspecific(module_t *mod, specificdata_key_t key)
1836 {
1837 
1838 	return specificdata_getspecific(module_specificdata_domain,
1839 	    &mod->mod_sdref, key);
1840 }
1841 
1842 /*
1843  * module_setspecific:
1844  *
1845  *	Set module-specific data corresponding to the specified key.
1846  */
1847 void
1848 module_setspecific(module_t *mod, specificdata_key_t key, void *data)
1849 {
1850 
1851 	specificdata_setspecific(module_specificdata_domain,
1852 	    &mod->mod_sdref, key, data);
1853 }
1854 
1855 /*
1856  * module_register_callbacks:
1857  *
1858  *	Register a new set of callbacks to be called on module load/unload.
1859  *	Call the load callback on each existing module.
1860  *	Return an opaque handle for unregistering these later.
1861  */
1862 void *
1863 module_register_callbacks(void (*load)(struct module *),
1864     void (*unload)(struct module *))
1865 {
1866 	struct module_callbacks *modcb;
1867 	struct module *mod;
1868 
1869 	modcb = kmem_alloc(sizeof(*modcb), KM_SLEEP);
1870 	modcb->modcb_load = load;
1871 	modcb->modcb_unload = unload;
1872 
1873 	kernconfig_lock();
1874 	TAILQ_INSERT_TAIL(&modcblist, modcb, modcb_list);
1875 	TAILQ_FOREACH(mod, &module_list, mod_chain)
1876 		load(mod);
1877 	kernconfig_unlock();
1878 
1879 	return modcb;
1880 }
1881 
1882 /*
1883  * module_unregister_callbacks:
1884  *
1885  *	Unregister a previously-registered set of module load/unload callbacks.
1886  *	Call the unload callback on each existing module.
1887  */
1888 void
1889 module_unregister_callbacks(void *opaque)
1890 {
1891 	struct module_callbacks *modcb;
1892 	struct module *mod;
1893 
1894 	modcb = opaque;
1895 	kernconfig_lock();
1896 	TAILQ_FOREACH(mod, &module_list, mod_chain)
1897 		modcb->modcb_unload(mod);
1898 	TAILQ_REMOVE(&modcblist, modcb, modcb_list);
1899 	kernconfig_unlock();
1900 	kmem_free(modcb, sizeof(*modcb));
1901 }
1902 
1903 /*
1904  * module_callback_load:
1905  *
1906  *	Helper routine: call all load callbacks on a module being loaded.
1907  */
1908 static void
1909 module_callback_load(struct module *mod)
1910 {
1911 	struct module_callbacks *modcb;
1912 
1913 	TAILQ_FOREACH(modcb, &modcblist, modcb_list) {
1914 		modcb->modcb_load(mod);
1915 	}
1916 }
1917 
1918 /*
1919  * module_callback_unload:
1920  *
1921  *	Helper routine: call all unload callbacks on a module being unloaded.
1922  */
1923 static void
1924 module_callback_unload(struct module *mod)
1925 {
1926 	struct module_callbacks *modcb;
1927 
1928 	TAILQ_FOREACH(modcb, &modcblist, modcb_list) {
1929 		modcb->modcb_unload(mod);
1930 	}
1931 }
1932