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