kern_linker.c revision 284153
1/*-
2 * Copyright (c) 1997-2000 Doug Rabson
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 *
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24 * SUCH DAMAGE.
25 */
26
27#include <sys/cdefs.h>
28__FBSDID("$FreeBSD: head/sys/kern/kern_linker.c 284153 2015-06-08 14:06:47Z jhb $");
29
30#include "opt_ddb.h"
31#include "opt_kld.h"
32#include "opt_hwpmc_hooks.h"
33
34#include <sys/param.h>
35#include <sys/kernel.h>
36#include <sys/systm.h>
37#include <sys/malloc.h>
38#include <sys/sysproto.h>
39#include <sys/sysent.h>
40#include <sys/priv.h>
41#include <sys/proc.h>
42#include <sys/lock.h>
43#include <sys/mutex.h>
44#include <sys/sx.h>
45#include <sys/module.h>
46#include <sys/mount.h>
47#include <sys/linker.h>
48#include <sys/eventhandler.h>
49#include <sys/fcntl.h>
50#include <sys/jail.h>
51#include <sys/libkern.h>
52#include <sys/namei.h>
53#include <sys/vnode.h>
54#include <sys/syscallsubr.h>
55#include <sys/sysctl.h>
56
57#include <net/vnet.h>
58
59#include <security/mac/mac_framework.h>
60
61#include "linker_if.h"
62
63#ifdef HWPMC_HOOKS
64#include <sys/pmckern.h>
65#endif
66
67#ifdef KLD_DEBUG
68int kld_debug = 0;
69SYSCTL_INT(_debug, OID_AUTO, kld_debug, CTLFLAG_RWTUN,
70    &kld_debug, 0, "Set various levels of KLD debug");
71#endif
72
73/*
74 * static char *linker_search_path(const char *name, struct mod_depend
75 * *verinfo);
76 */
77static const char 	*linker_basename(const char *path);
78
79/*
80 * Find a currently loaded file given its filename.
81 */
82static linker_file_t linker_find_file_by_name(const char* _filename);
83
84/*
85 * Find a currently loaded file given its file id.
86 */
87static linker_file_t linker_find_file_by_id(int _fileid);
88
89/* Metadata from the static kernel */
90SET_DECLARE(modmetadata_set, struct mod_metadata);
91
92MALLOC_DEFINE(M_LINKER, "linker", "kernel linker");
93
94linker_file_t linker_kernel_file;
95
96static struct sx kld_sx;	/* kernel linker lock */
97
98/*
99 * Load counter used by clients to determine if a linker file has been
100 * re-loaded. This counter is incremented for each file load.
101 */
102static int loadcnt;
103
104static linker_class_list_t classes;
105static linker_file_list_t linker_files;
106static int next_file_id = 1;
107static int linker_no_more_classes = 0;
108
109#define	LINKER_GET_NEXT_FILE_ID(a) do {					\
110	linker_file_t lftmp;						\
111									\
112	if (!cold)							\
113		sx_assert(&kld_sx, SA_XLOCKED);				\
114retry:									\
115	TAILQ_FOREACH(lftmp, &linker_files, link) {			\
116		if (next_file_id == lftmp->id) {			\
117			next_file_id++;					\
118			goto retry;					\
119		}							\
120	}								\
121	(a) = next_file_id;						\
122} while(0)
123
124
125/* XXX wrong name; we're looking at version provision tags here, not modules */
126typedef TAILQ_HEAD(, modlist) modlisthead_t;
127struct modlist {
128	TAILQ_ENTRY(modlist) link;	/* chain together all modules */
129	linker_file_t   container;
130	const char 	*name;
131	int             version;
132};
133typedef struct modlist *modlist_t;
134static modlisthead_t found_modules;
135
136static int	linker_file_add_dependency(linker_file_t file,
137		    linker_file_t dep);
138static caddr_t	linker_file_lookup_symbol_internal(linker_file_t file,
139		    const char* name, int deps);
140static int	linker_file_lookup_set_locked(linker_file_t file,
141		    const char *name, void *firstp, void *lastp, int *countp);
142static int	linker_load_module(const char *kldname,
143		    const char *modname, struct linker_file *parent,
144		    const struct mod_depend *verinfo, struct linker_file **lfpp);
145static modlist_t modlist_lookup2(const char *name, const struct mod_depend *verinfo);
146
147static void
148linker_init(void *arg)
149{
150
151	sx_init(&kld_sx, "kernel linker");
152	TAILQ_INIT(&classes);
153	TAILQ_INIT(&linker_files);
154}
155
156SYSINIT(linker, SI_SUB_KLD, SI_ORDER_FIRST, linker_init, 0);
157
158static void
159linker_stop_class_add(void *arg)
160{
161
162	linker_no_more_classes = 1;
163}
164
165SYSINIT(linker_class, SI_SUB_KLD, SI_ORDER_ANY, linker_stop_class_add, NULL);
166
167int
168linker_add_class(linker_class_t lc)
169{
170
171	/*
172	 * We disallow any class registration past SI_ORDER_ANY
173	 * of SI_SUB_KLD.  We bump the reference count to keep the
174	 * ops from being freed.
175	 */
176	if (linker_no_more_classes == 1)
177		return (EPERM);
178	kobj_class_compile((kobj_class_t) lc);
179	((kobj_class_t)lc)->refs++;	/* XXX: kobj_mtx */
180	TAILQ_INSERT_TAIL(&classes, lc, link);
181	return (0);
182}
183
184static void
185linker_file_sysinit(linker_file_t lf)
186{
187	struct sysinit **start, **stop, **sipp, **xipp, *save;
188
189	KLD_DPF(FILE, ("linker_file_sysinit: calling SYSINITs for %s\n",
190	    lf->filename));
191
192	sx_assert(&kld_sx, SA_XLOCKED);
193
194	if (linker_file_lookup_set_locked(lf, "sysinit_set", &start, &stop,
195	    NULL) != 0)
196		return;
197	/*
198	 * Perform a bubble sort of the system initialization objects by
199	 * their subsystem (primary key) and order (secondary key).
200	 *
201	 * Since some things care about execution order, this is the operation
202	 * which ensures continued function.
203	 */
204	for (sipp = start; sipp < stop; sipp++) {
205		for (xipp = sipp + 1; xipp < stop; xipp++) {
206			if ((*sipp)->subsystem < (*xipp)->subsystem ||
207			    ((*sipp)->subsystem == (*xipp)->subsystem &&
208			    (*sipp)->order <= (*xipp)->order))
209				continue;	/* skip */
210			save = *sipp;
211			*sipp = *xipp;
212			*xipp = save;
213		}
214	}
215
216	/*
217	 * Traverse the (now) ordered list of system initialization tasks.
218	 * Perform each task, and continue on to the next task.
219	 */
220	sx_xunlock(&kld_sx);
221	mtx_lock(&Giant);
222	for (sipp = start; sipp < stop; sipp++) {
223		if ((*sipp)->subsystem == SI_SUB_DUMMY)
224			continue;	/* skip dummy task(s) */
225
226		/* Call function */
227		(*((*sipp)->func)) ((*sipp)->udata);
228	}
229	mtx_unlock(&Giant);
230	sx_xlock(&kld_sx);
231}
232
233static void
234linker_file_sysuninit(linker_file_t lf)
235{
236	struct sysinit **start, **stop, **sipp, **xipp, *save;
237
238	KLD_DPF(FILE, ("linker_file_sysuninit: calling SYSUNINITs for %s\n",
239	    lf->filename));
240
241	sx_assert(&kld_sx, SA_XLOCKED);
242
243	if (linker_file_lookup_set_locked(lf, "sysuninit_set", &start, &stop,
244	    NULL) != 0)
245		return;
246
247	/*
248	 * Perform a reverse bubble sort of the system initialization objects
249	 * by their subsystem (primary key) and order (secondary key).
250	 *
251	 * Since some things care about execution order, this is the operation
252	 * which ensures continued function.
253	 */
254	for (sipp = start; sipp < stop; sipp++) {
255		for (xipp = sipp + 1; xipp < stop; xipp++) {
256			if ((*sipp)->subsystem > (*xipp)->subsystem ||
257			    ((*sipp)->subsystem == (*xipp)->subsystem &&
258			    (*sipp)->order >= (*xipp)->order))
259				continue;	/* skip */
260			save = *sipp;
261			*sipp = *xipp;
262			*xipp = save;
263		}
264	}
265
266	/*
267	 * Traverse the (now) ordered list of system initialization tasks.
268	 * Perform each task, and continue on to the next task.
269	 */
270	sx_xunlock(&kld_sx);
271	mtx_lock(&Giant);
272	for (sipp = start; sipp < stop; sipp++) {
273		if ((*sipp)->subsystem == SI_SUB_DUMMY)
274			continue;	/* skip dummy task(s) */
275
276		/* Call function */
277		(*((*sipp)->func)) ((*sipp)->udata);
278	}
279	mtx_unlock(&Giant);
280	sx_xlock(&kld_sx);
281}
282
283static void
284linker_file_register_sysctls(linker_file_t lf)
285{
286	struct sysctl_oid **start, **stop, **oidp;
287
288	KLD_DPF(FILE,
289	    ("linker_file_register_sysctls: registering SYSCTLs for %s\n",
290	    lf->filename));
291
292	sx_assert(&kld_sx, SA_XLOCKED);
293
294	if (linker_file_lookup_set_locked(lf, "sysctl_set", &start, &stop,
295	    NULL) != 0)
296		return;
297
298	sx_xunlock(&kld_sx);
299	sysctl_xlock();
300	for (oidp = start; oidp < stop; oidp++)
301		sysctl_register_oid(*oidp);
302	sysctl_xunlock();
303	sx_xlock(&kld_sx);
304}
305
306static void
307linker_file_unregister_sysctls(linker_file_t lf)
308{
309	struct sysctl_oid **start, **stop, **oidp;
310
311	KLD_DPF(FILE, ("linker_file_unregister_sysctls: unregistering SYSCTLs"
312	    " for %s\n", lf->filename));
313
314	sx_assert(&kld_sx, SA_XLOCKED);
315
316	if (linker_file_lookup_set_locked(lf, "sysctl_set", &start, &stop,
317	    NULL) != 0)
318		return;
319
320	sx_xunlock(&kld_sx);
321	sysctl_xlock();
322	for (oidp = start; oidp < stop; oidp++)
323		sysctl_unregister_oid(*oidp);
324	sysctl_xunlock();
325	sx_xlock(&kld_sx);
326}
327
328static int
329linker_file_register_modules(linker_file_t lf)
330{
331	struct mod_metadata **start, **stop, **mdp;
332	const moduledata_t *moddata;
333	int first_error, error;
334
335	KLD_DPF(FILE, ("linker_file_register_modules: registering modules"
336	    " in %s\n", lf->filename));
337
338	sx_assert(&kld_sx, SA_XLOCKED);
339
340	if (linker_file_lookup_set_locked(lf, "modmetadata_set", &start,
341	    &stop, NULL) != 0) {
342		/*
343		 * This fallback should be unnecessary, but if we get booted
344		 * from boot2 instead of loader and we are missing our
345		 * metadata then we have to try the best we can.
346		 */
347		if (lf == linker_kernel_file) {
348			start = SET_BEGIN(modmetadata_set);
349			stop = SET_LIMIT(modmetadata_set);
350		} else
351			return (0);
352	}
353	first_error = 0;
354	for (mdp = start; mdp < stop; mdp++) {
355		if ((*mdp)->md_type != MDT_MODULE)
356			continue;
357		moddata = (*mdp)->md_data;
358		KLD_DPF(FILE, ("Registering module %s in %s\n",
359		    moddata->name, lf->filename));
360		error = module_register(moddata, lf);
361		if (error) {
362			printf("Module %s failed to register: %d\n",
363			    moddata->name, error);
364			if (first_error == 0)
365				first_error = error;
366		}
367	}
368	return (first_error);
369}
370
371static void
372linker_init_kernel_modules(void)
373{
374
375	sx_xlock(&kld_sx);
376	linker_file_register_modules(linker_kernel_file);
377	sx_xunlock(&kld_sx);
378}
379
380SYSINIT(linker_kernel, SI_SUB_KLD, SI_ORDER_ANY, linker_init_kernel_modules,
381    0);
382
383static int
384linker_load_file(const char *filename, linker_file_t *result)
385{
386	linker_class_t lc;
387	linker_file_t lf;
388	int foundfile, error, modules;
389
390	/* Refuse to load modules if securelevel raised */
391	if (prison0.pr_securelevel > 0)
392		return (EPERM);
393
394	sx_assert(&kld_sx, SA_XLOCKED);
395	lf = linker_find_file_by_name(filename);
396	if (lf) {
397		KLD_DPF(FILE, ("linker_load_file: file %s is already loaded,"
398		    " incrementing refs\n", filename));
399		*result = lf;
400		lf->refs++;
401		return (0);
402	}
403	foundfile = 0;
404	error = 0;
405
406	/*
407	 * We do not need to protect (lock) classes here because there is
408	 * no class registration past startup (SI_SUB_KLD, SI_ORDER_ANY)
409	 * and there is no class deregistration mechanism at this time.
410	 */
411	TAILQ_FOREACH(lc, &classes, link) {
412		KLD_DPF(FILE, ("linker_load_file: trying to load %s\n",
413		    filename));
414		error = LINKER_LOAD_FILE(lc, filename, &lf);
415		/*
416		 * If we got something other than ENOENT, then it exists but
417		 * we cannot load it for some other reason.
418		 */
419		if (error != ENOENT)
420			foundfile = 1;
421		if (lf) {
422			error = linker_file_register_modules(lf);
423			if (error == EEXIST) {
424				linker_file_unload(lf, LINKER_UNLOAD_FORCE);
425				return (error);
426			}
427			modules = !TAILQ_EMPTY(&lf->modules);
428			linker_file_register_sysctls(lf);
429			linker_file_sysinit(lf);
430			lf->flags |= LINKER_FILE_LINKED;
431
432			/*
433			 * If all of the modules in this file failed
434			 * to load, unload the file and return an
435			 * error of ENOEXEC.
436			 */
437			if (modules && TAILQ_EMPTY(&lf->modules)) {
438				linker_file_unload(lf, LINKER_UNLOAD_FORCE);
439				return (ENOEXEC);
440			}
441			EVENTHANDLER_INVOKE(kld_load, lf);
442			*result = lf;
443			return (0);
444		}
445	}
446	/*
447	 * Less than ideal, but tells the user whether it failed to load or
448	 * the module was not found.
449	 */
450	if (foundfile) {
451
452		/*
453		 * If the file type has not been recognized by the last try
454		 * printout a message before to fail.
455		 */
456		if (error == ENOSYS)
457			printf("linker_load_file: Unsupported file type\n");
458
459		/*
460		 * Format not recognized or otherwise unloadable.
461		 * When loading a module that is statically built into
462		 * the kernel EEXIST percolates back up as the return
463		 * value.  Preserve this so that apps like sysinstall
464		 * can recognize this special case and not post bogus
465		 * dialog boxes.
466		 */
467		if (error != EEXIST)
468			error = ENOEXEC;
469	} else
470		error = ENOENT;		/* Nothing found */
471	return (error);
472}
473
474int
475linker_reference_module(const char *modname, struct mod_depend *verinfo,
476    linker_file_t *result)
477{
478	modlist_t mod;
479	int error;
480
481	sx_xlock(&kld_sx);
482	if ((mod = modlist_lookup2(modname, verinfo)) != NULL) {
483		*result = mod->container;
484		(*result)->refs++;
485		sx_xunlock(&kld_sx);
486		return (0);
487	}
488
489	error = linker_load_module(NULL, modname, NULL, verinfo, result);
490	sx_xunlock(&kld_sx);
491	return (error);
492}
493
494int
495linker_release_module(const char *modname, struct mod_depend *verinfo,
496    linker_file_t lf)
497{
498	modlist_t mod;
499	int error;
500
501	sx_xlock(&kld_sx);
502	if (lf == NULL) {
503		KASSERT(modname != NULL,
504		    ("linker_release_module: no file or name"));
505		mod = modlist_lookup2(modname, verinfo);
506		if (mod == NULL) {
507			sx_xunlock(&kld_sx);
508			return (ESRCH);
509		}
510		lf = mod->container;
511	} else
512		KASSERT(modname == NULL && verinfo == NULL,
513		    ("linker_release_module: both file and name"));
514	error =	linker_file_unload(lf, LINKER_UNLOAD_NORMAL);
515	sx_xunlock(&kld_sx);
516	return (error);
517}
518
519static linker_file_t
520linker_find_file_by_name(const char *filename)
521{
522	linker_file_t lf;
523	char *koname;
524
525	koname = malloc(strlen(filename) + 4, M_LINKER, M_WAITOK);
526	sprintf(koname, "%s.ko", filename);
527
528	sx_assert(&kld_sx, SA_XLOCKED);
529	TAILQ_FOREACH(lf, &linker_files, link) {
530		if (strcmp(lf->filename, koname) == 0)
531			break;
532		if (strcmp(lf->filename, filename) == 0)
533			break;
534	}
535	free(koname, M_LINKER);
536	return (lf);
537}
538
539static linker_file_t
540linker_find_file_by_id(int fileid)
541{
542	linker_file_t lf;
543
544	sx_assert(&kld_sx, SA_XLOCKED);
545	TAILQ_FOREACH(lf, &linker_files, link)
546		if (lf->id == fileid && lf->flags & LINKER_FILE_LINKED)
547			break;
548	return (lf);
549}
550
551int
552linker_file_foreach(linker_predicate_t *predicate, void *context)
553{
554	linker_file_t lf;
555	int retval = 0;
556
557	sx_xlock(&kld_sx);
558	TAILQ_FOREACH(lf, &linker_files, link) {
559		retval = predicate(lf, context);
560		if (retval != 0)
561			break;
562	}
563	sx_xunlock(&kld_sx);
564	return (retval);
565}
566
567linker_file_t
568linker_make_file(const char *pathname, linker_class_t lc)
569{
570	linker_file_t lf;
571	const char *filename;
572
573	if (!cold)
574		sx_assert(&kld_sx, SA_XLOCKED);
575	filename = linker_basename(pathname);
576
577	KLD_DPF(FILE, ("linker_make_file: new file, filename='%s' for pathname='%s'\n", filename, pathname));
578	lf = (linker_file_t)kobj_create((kobj_class_t)lc, M_LINKER, M_WAITOK);
579	if (lf == NULL)
580		return (NULL);
581	lf->ctors_addr = 0;
582	lf->ctors_size = 0;
583	lf->refs = 1;
584	lf->userrefs = 0;
585	lf->flags = 0;
586	lf->filename = strdup(filename, M_LINKER);
587	lf->pathname = strdup(pathname, M_LINKER);
588	LINKER_GET_NEXT_FILE_ID(lf->id);
589	lf->ndeps = 0;
590	lf->deps = NULL;
591	lf->loadcnt = ++loadcnt;
592	STAILQ_INIT(&lf->common);
593	TAILQ_INIT(&lf->modules);
594	TAILQ_INSERT_TAIL(&linker_files, lf, link);
595	return (lf);
596}
597
598int
599linker_file_unload(linker_file_t file, int flags)
600{
601	module_t mod, next;
602	modlist_t ml, nextml;
603	struct common_symbol *cp;
604	int error, i;
605
606	/* Refuse to unload modules if securelevel raised. */
607	if (prison0.pr_securelevel > 0)
608		return (EPERM);
609
610	sx_assert(&kld_sx, SA_XLOCKED);
611	KLD_DPF(FILE, ("linker_file_unload: lf->refs=%d\n", file->refs));
612
613	/* Easy case of just dropping a reference. */
614	if (file->refs > 1) {
615		file->refs--;
616		return (0);
617	}
618
619	/* Give eventhandlers a chance to prevent the unload. */
620	error = 0;
621	EVENTHANDLER_INVOKE(kld_unload_try, file, &error);
622	if (error != 0)
623		return (EBUSY);
624
625	KLD_DPF(FILE, ("linker_file_unload: file is unloading,"
626	    " informing modules\n"));
627
628	/*
629	 * Quiesce all the modules to give them a chance to veto the unload.
630	 */
631	MOD_SLOCK;
632	for (mod = TAILQ_FIRST(&file->modules); mod;
633	     mod = module_getfnext(mod)) {
634
635		error = module_quiesce(mod);
636		if (error != 0 && flags != LINKER_UNLOAD_FORCE) {
637			KLD_DPF(FILE, ("linker_file_unload: module %s"
638			    " vetoed unload\n", module_getname(mod)));
639			/*
640			 * XXX: Do we need to tell all the quiesced modules
641			 * that they can resume work now via a new module
642			 * event?
643			 */
644			MOD_SUNLOCK;
645			return (error);
646		}
647	}
648	MOD_SUNLOCK;
649
650	/*
651	 * Inform any modules associated with this file that they are
652	 * being unloaded.
653	 */
654	MOD_XLOCK;
655	for (mod = TAILQ_FIRST(&file->modules); mod; mod = next) {
656		next = module_getfnext(mod);
657		MOD_XUNLOCK;
658
659		/*
660		 * Give the module a chance to veto the unload.
661		 */
662		if ((error = module_unload(mod)) != 0) {
663#ifdef KLD_DEBUG
664			MOD_SLOCK;
665			KLD_DPF(FILE, ("linker_file_unload: module %s"
666			    " failed unload\n", module_getname(mod)));
667			MOD_SUNLOCK;
668#endif
669			return (error);
670		}
671		MOD_XLOCK;
672		module_release(mod);
673	}
674	MOD_XUNLOCK;
675
676	TAILQ_FOREACH_SAFE(ml, &found_modules, link, nextml) {
677		if (ml->container == file) {
678			TAILQ_REMOVE(&found_modules, ml, link);
679			free(ml, M_LINKER);
680		}
681	}
682
683	/*
684	 * Don't try to run SYSUNINITs if we are unloaded due to a
685	 * link error.
686	 */
687	if (file->flags & LINKER_FILE_LINKED) {
688		file->flags &= ~LINKER_FILE_LINKED;
689		linker_file_sysuninit(file);
690		linker_file_unregister_sysctls(file);
691	}
692	TAILQ_REMOVE(&linker_files, file, link);
693
694	if (file->deps) {
695		for (i = 0; i < file->ndeps; i++)
696			linker_file_unload(file->deps[i], flags);
697		free(file->deps, M_LINKER);
698		file->deps = NULL;
699	}
700	while ((cp = STAILQ_FIRST(&file->common)) != NULL) {
701		STAILQ_REMOVE_HEAD(&file->common, link);
702		free(cp, M_LINKER);
703	}
704
705	LINKER_UNLOAD(file);
706
707	EVENTHANDLER_INVOKE(kld_unload, file->filename, file->address,
708	    file->size);
709
710	if (file->filename) {
711		free(file->filename, M_LINKER);
712		file->filename = NULL;
713	}
714	if (file->pathname) {
715		free(file->pathname, M_LINKER);
716		file->pathname = NULL;
717	}
718	kobj_delete((kobj_t) file, M_LINKER);
719	return (0);
720}
721
722int
723linker_ctf_get(linker_file_t file, linker_ctf_t *lc)
724{
725	return (LINKER_CTF_GET(file, lc));
726}
727
728static int
729linker_file_add_dependency(linker_file_t file, linker_file_t dep)
730{
731	linker_file_t *newdeps;
732
733	sx_assert(&kld_sx, SA_XLOCKED);
734	file->deps = realloc(file->deps, (file->ndeps + 1) * sizeof(*newdeps),
735	    M_LINKER, M_WAITOK | M_ZERO);
736	file->deps[file->ndeps] = dep;
737	file->ndeps++;
738	KLD_DPF(FILE, ("linker_file_add_dependency:"
739	    " adding %s as dependency for %s\n",
740	    dep->filename, file->filename));
741	return (0);
742}
743
744/*
745 * Locate a linker set and its contents.  This is a helper function to avoid
746 * linker_if.h exposure elsewhere.  Note: firstp and lastp are really void **.
747 * This function is used in this file so we can avoid having lots of (void **)
748 * casts.
749 */
750static int
751linker_file_lookup_set_locked(linker_file_t file, const char *name,
752    void *firstp, void *lastp, int *countp)
753{
754
755	sx_assert(&kld_sx, SA_LOCKED);
756	return (LINKER_LOOKUP_SET(file, name, firstp, lastp, countp));
757}
758
759int
760linker_file_lookup_set(linker_file_t file, const char *name,
761    void *firstp, void *lastp, int *countp)
762{
763	int error;
764
765	sx_slock(&kld_sx);
766	error = linker_file_lookup_set_locked(file, name, firstp, lastp,
767	    countp);
768	sx_sunlock(&kld_sx);
769	return (error);
770}
771
772/*
773 * List all functions in a file.
774 */
775int
776linker_file_function_listall(linker_file_t lf,
777    linker_function_nameval_callback_t callback_func, void *arg)
778{
779	return (LINKER_EACH_FUNCTION_NAMEVAL(lf, callback_func, arg));
780}
781
782caddr_t
783linker_file_lookup_symbol(linker_file_t file, const char *name, int deps)
784{
785	caddr_t sym;
786	int locked;
787
788	locked = sx_xlocked(&kld_sx);
789	if (!locked)
790		sx_xlock(&kld_sx);
791	sym = linker_file_lookup_symbol_internal(file, name, deps);
792	if (!locked)
793		sx_xunlock(&kld_sx);
794	return (sym);
795}
796
797static caddr_t
798linker_file_lookup_symbol_internal(linker_file_t file, const char *name,
799    int deps)
800{
801	c_linker_sym_t sym;
802	linker_symval_t symval;
803	caddr_t address;
804	size_t common_size = 0;
805	int i;
806
807	sx_assert(&kld_sx, SA_XLOCKED);
808	KLD_DPF(SYM, ("linker_file_lookup_symbol: file=%p, name=%s, deps=%d\n",
809	    file, name, deps));
810
811	if (LINKER_LOOKUP_SYMBOL(file, name, &sym) == 0) {
812		LINKER_SYMBOL_VALUES(file, sym, &symval);
813		if (symval.value == 0)
814			/*
815			 * For commons, first look them up in the
816			 * dependencies and only allocate space if not found
817			 * there.
818			 */
819			common_size = symval.size;
820		else {
821			KLD_DPF(SYM, ("linker_file_lookup_symbol: symbol"
822			    ".value=%p\n", symval.value));
823			return (symval.value);
824		}
825	}
826	if (deps) {
827		for (i = 0; i < file->ndeps; i++) {
828			address = linker_file_lookup_symbol_internal(
829			    file->deps[i], name, 0);
830			if (address) {
831				KLD_DPF(SYM, ("linker_file_lookup_symbol:"
832				    " deps value=%p\n", address));
833				return (address);
834			}
835		}
836	}
837	if (common_size > 0) {
838		/*
839		 * This is a common symbol which was not found in the
840		 * dependencies.  We maintain a simple common symbol table in
841		 * the file object.
842		 */
843		struct common_symbol *cp;
844
845		STAILQ_FOREACH(cp, &file->common, link) {
846			if (strcmp(cp->name, name) == 0) {
847				KLD_DPF(SYM, ("linker_file_lookup_symbol:"
848				    " old common value=%p\n", cp->address));
849				return (cp->address);
850			}
851		}
852		/*
853		 * Round the symbol size up to align.
854		 */
855		common_size = (common_size + sizeof(int) - 1) & -sizeof(int);
856		cp = malloc(sizeof(struct common_symbol)
857		    + common_size + strlen(name) + 1, M_LINKER,
858		    M_WAITOK | M_ZERO);
859		cp->address = (caddr_t)(cp + 1);
860		cp->name = cp->address + common_size;
861		strcpy(cp->name, name);
862		bzero(cp->address, common_size);
863		STAILQ_INSERT_TAIL(&file->common, cp, link);
864
865		KLD_DPF(SYM, ("linker_file_lookup_symbol: new common"
866		    " value=%p\n", cp->address));
867		return (cp->address);
868	}
869	KLD_DPF(SYM, ("linker_file_lookup_symbol: fail\n"));
870	return (0);
871}
872
873/*
874 * Both DDB and stack(9) rely on the kernel linker to provide forward and
875 * backward lookup of symbols.  However, DDB and sometimes stack(9) need to
876 * do this in a lockfree manner.  We provide a set of internal helper
877 * routines to perform these operations without locks, and then wrappers that
878 * optionally lock.
879 *
880 * linker_debug_lookup() is ifdef DDB as currently it's only used by DDB.
881 */
882#ifdef DDB
883static int
884linker_debug_lookup(const char *symstr, c_linker_sym_t *sym)
885{
886	linker_file_t lf;
887
888	TAILQ_FOREACH(lf, &linker_files, link) {
889		if (LINKER_LOOKUP_SYMBOL(lf, symstr, sym) == 0)
890			return (0);
891	}
892	return (ENOENT);
893}
894#endif
895
896static int
897linker_debug_search_symbol(caddr_t value, c_linker_sym_t *sym, long *diffp)
898{
899	linker_file_t lf;
900	c_linker_sym_t best, es;
901	u_long diff, bestdiff, off;
902
903	best = 0;
904	off = (uintptr_t)value;
905	bestdiff = off;
906	TAILQ_FOREACH(lf, &linker_files, link) {
907		if (LINKER_SEARCH_SYMBOL(lf, value, &es, &diff) != 0)
908			continue;
909		if (es != 0 && diff < bestdiff) {
910			best = es;
911			bestdiff = diff;
912		}
913		if (bestdiff == 0)
914			break;
915	}
916	if (best) {
917		*sym = best;
918		*diffp = bestdiff;
919		return (0);
920	} else {
921		*sym = 0;
922		*diffp = off;
923		return (ENOENT);
924	}
925}
926
927static int
928linker_debug_symbol_values(c_linker_sym_t sym, linker_symval_t *symval)
929{
930	linker_file_t lf;
931
932	TAILQ_FOREACH(lf, &linker_files, link) {
933		if (LINKER_SYMBOL_VALUES(lf, sym, symval) == 0)
934			return (0);
935	}
936	return (ENOENT);
937}
938
939static int
940linker_debug_search_symbol_name(caddr_t value, char *buf, u_int buflen,
941    long *offset)
942{
943	linker_symval_t symval;
944	c_linker_sym_t sym;
945	int error;
946
947	*offset = 0;
948	error = linker_debug_search_symbol(value, &sym, offset);
949	if (error)
950		return (error);
951	error = linker_debug_symbol_values(sym, &symval);
952	if (error)
953		return (error);
954	strlcpy(buf, symval.name, buflen);
955	return (0);
956}
957
958/*
959 * DDB Helpers.  DDB has to look across multiple files with their own symbol
960 * tables and string tables.
961 *
962 * Note that we do not obey list locking protocols here.  We really don't need
963 * DDB to hang because somebody's got the lock held.  We'll take the chance
964 * that the files list is inconsistant instead.
965 */
966#ifdef DDB
967int
968linker_ddb_lookup(const char *symstr, c_linker_sym_t *sym)
969{
970
971	return (linker_debug_lookup(symstr, sym));
972}
973#endif
974
975int
976linker_ddb_search_symbol(caddr_t value, c_linker_sym_t *sym, long *diffp)
977{
978
979	return (linker_debug_search_symbol(value, sym, diffp));
980}
981
982int
983linker_ddb_symbol_values(c_linker_sym_t sym, linker_symval_t *symval)
984{
985
986	return (linker_debug_symbol_values(sym, symval));
987}
988
989int
990linker_ddb_search_symbol_name(caddr_t value, char *buf, u_int buflen,
991    long *offset)
992{
993
994	return (linker_debug_search_symbol_name(value, buf, buflen, offset));
995}
996
997/*
998 * stack(9) helper for non-debugging environemnts.  Unlike DDB helpers, we do
999 * obey locking protocols, and offer a significantly less complex interface.
1000 */
1001int
1002linker_search_symbol_name(caddr_t value, char *buf, u_int buflen,
1003    long *offset)
1004{
1005	int error;
1006
1007	sx_slock(&kld_sx);
1008	error = linker_debug_search_symbol_name(value, buf, buflen, offset);
1009	sx_sunlock(&kld_sx);
1010	return (error);
1011}
1012
1013/*
1014 * Syscalls.
1015 */
1016int
1017kern_kldload(struct thread *td, const char *file, int *fileid)
1018{
1019	const char *kldname, *modname;
1020	linker_file_t lf;
1021	int error;
1022
1023	if ((error = securelevel_gt(td->td_ucred, 0)) != 0)
1024		return (error);
1025
1026	if ((error = priv_check(td, PRIV_KLD_LOAD)) != 0)
1027		return (error);
1028
1029	/*
1030	 * It is possible that kldloaded module will attach a new ifnet,
1031	 * so vnet context must be set when this ocurs.
1032	 */
1033	CURVNET_SET(TD_TO_VNET(td));
1034
1035	/*
1036	 * If file does not contain a qualified name or any dot in it
1037	 * (kldname.ko, or kldname.ver.ko) treat it as an interface
1038	 * name.
1039	 */
1040	if (strchr(file, '/') || strchr(file, '.')) {
1041		kldname = file;
1042		modname = NULL;
1043	} else {
1044		kldname = NULL;
1045		modname = file;
1046	}
1047
1048	sx_xlock(&kld_sx);
1049	error = linker_load_module(kldname, modname, NULL, NULL, &lf);
1050	if (error) {
1051		sx_xunlock(&kld_sx);
1052		goto done;
1053	}
1054	lf->userrefs++;
1055	if (fileid != NULL)
1056		*fileid = lf->id;
1057	sx_xunlock(&kld_sx);
1058
1059done:
1060	CURVNET_RESTORE();
1061	return (error);
1062}
1063
1064int
1065sys_kldload(struct thread *td, struct kldload_args *uap)
1066{
1067	char *pathname = NULL;
1068	int error, fileid;
1069
1070	td->td_retval[0] = -1;
1071
1072	pathname = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
1073	error = copyinstr(uap->file, pathname, MAXPATHLEN, NULL);
1074	if (error == 0) {
1075		error = kern_kldload(td, pathname, &fileid);
1076		if (error == 0)
1077			td->td_retval[0] = fileid;
1078	}
1079	free(pathname, M_TEMP);
1080	return (error);
1081}
1082
1083int
1084kern_kldunload(struct thread *td, int fileid, int flags)
1085{
1086	linker_file_t lf;
1087	int error = 0;
1088
1089	if ((error = securelevel_gt(td->td_ucred, 0)) != 0)
1090		return (error);
1091
1092	if ((error = priv_check(td, PRIV_KLD_UNLOAD)) != 0)
1093		return (error);
1094
1095	CURVNET_SET(TD_TO_VNET(td));
1096	sx_xlock(&kld_sx);
1097	lf = linker_find_file_by_id(fileid);
1098	if (lf) {
1099		KLD_DPF(FILE, ("kldunload: lf->userrefs=%d\n", lf->userrefs));
1100
1101		if (lf->userrefs == 0) {
1102			/*
1103			 * XXX: maybe LINKER_UNLOAD_FORCE should override ?
1104			 */
1105			printf("kldunload: attempt to unload file that was"
1106			    " loaded by the kernel\n");
1107			error = EBUSY;
1108		} else {
1109			lf->userrefs--;
1110			error = linker_file_unload(lf, flags);
1111			if (error)
1112				lf->userrefs++;
1113		}
1114	} else
1115		error = ENOENT;
1116	sx_xunlock(&kld_sx);
1117
1118	CURVNET_RESTORE();
1119	return (error);
1120}
1121
1122int
1123sys_kldunload(struct thread *td, struct kldunload_args *uap)
1124{
1125
1126	return (kern_kldunload(td, uap->fileid, LINKER_UNLOAD_NORMAL));
1127}
1128
1129int
1130sys_kldunloadf(struct thread *td, struct kldunloadf_args *uap)
1131{
1132
1133	if (uap->flags != LINKER_UNLOAD_NORMAL &&
1134	    uap->flags != LINKER_UNLOAD_FORCE)
1135		return (EINVAL);
1136	return (kern_kldunload(td, uap->fileid, uap->flags));
1137}
1138
1139int
1140sys_kldfind(struct thread *td, struct kldfind_args *uap)
1141{
1142	char *pathname;
1143	const char *filename;
1144	linker_file_t lf;
1145	int error;
1146
1147#ifdef MAC
1148	error = mac_kld_check_stat(td->td_ucred);
1149	if (error)
1150		return (error);
1151#endif
1152
1153	td->td_retval[0] = -1;
1154
1155	pathname = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
1156	if ((error = copyinstr(uap->file, pathname, MAXPATHLEN, NULL)) != 0)
1157		goto out;
1158
1159	filename = linker_basename(pathname);
1160	sx_xlock(&kld_sx);
1161	lf = linker_find_file_by_name(filename);
1162	if (lf)
1163		td->td_retval[0] = lf->id;
1164	else
1165		error = ENOENT;
1166	sx_xunlock(&kld_sx);
1167out:
1168	free(pathname, M_TEMP);
1169	return (error);
1170}
1171
1172int
1173sys_kldnext(struct thread *td, struct kldnext_args *uap)
1174{
1175	linker_file_t lf;
1176	int error = 0;
1177
1178#ifdef MAC
1179	error = mac_kld_check_stat(td->td_ucred);
1180	if (error)
1181		return (error);
1182#endif
1183
1184	sx_xlock(&kld_sx);
1185	if (uap->fileid == 0)
1186		lf = TAILQ_FIRST(&linker_files);
1187	else {
1188		lf = linker_find_file_by_id(uap->fileid);
1189		if (lf == NULL) {
1190			error = ENOENT;
1191			goto out;
1192		}
1193		lf = TAILQ_NEXT(lf, link);
1194	}
1195
1196	/* Skip partially loaded files. */
1197	while (lf != NULL && !(lf->flags & LINKER_FILE_LINKED))
1198		lf = TAILQ_NEXT(lf, link);
1199
1200	if (lf)
1201		td->td_retval[0] = lf->id;
1202	else
1203		td->td_retval[0] = 0;
1204out:
1205	sx_xunlock(&kld_sx);
1206	return (error);
1207}
1208
1209int
1210sys_kldstat(struct thread *td, struct kldstat_args *uap)
1211{
1212	struct kld_file_stat stat;
1213	int error, version;
1214
1215	/*
1216	 * Check the version of the user's structure.
1217	 */
1218	if ((error = copyin(&uap->stat->version, &version, sizeof(version)))
1219	    != 0)
1220		return (error);
1221	if (version != sizeof(struct kld_file_stat_1) &&
1222	    version != sizeof(struct kld_file_stat))
1223		return (EINVAL);
1224
1225	error = kern_kldstat(td, uap->fileid, &stat);
1226	if (error != 0)
1227		return (error);
1228	return (copyout(&stat, uap->stat, version));
1229}
1230
1231int
1232kern_kldstat(struct thread *td, int fileid, struct kld_file_stat *stat)
1233{
1234	linker_file_t lf;
1235	int namelen;
1236#ifdef MAC
1237	int error;
1238
1239	error = mac_kld_check_stat(td->td_ucred);
1240	if (error)
1241		return (error);
1242#endif
1243
1244	sx_xlock(&kld_sx);
1245	lf = linker_find_file_by_id(fileid);
1246	if (lf == NULL) {
1247		sx_xunlock(&kld_sx);
1248		return (ENOENT);
1249	}
1250
1251	/* Version 1 fields: */
1252	namelen = strlen(lf->filename) + 1;
1253	if (namelen > MAXPATHLEN)
1254		namelen = MAXPATHLEN;
1255	bcopy(lf->filename, &stat->name[0], namelen);
1256	stat->refs = lf->refs;
1257	stat->id = lf->id;
1258	stat->address = lf->address;
1259	stat->size = lf->size;
1260	/* Version 2 fields: */
1261	namelen = strlen(lf->pathname) + 1;
1262	if (namelen > MAXPATHLEN)
1263		namelen = MAXPATHLEN;
1264	bcopy(lf->pathname, &stat->pathname[0], namelen);
1265	sx_xunlock(&kld_sx);
1266
1267	td->td_retval[0] = 0;
1268	return (0);
1269}
1270
1271int
1272sys_kldfirstmod(struct thread *td, struct kldfirstmod_args *uap)
1273{
1274	linker_file_t lf;
1275	module_t mp;
1276	int error = 0;
1277
1278#ifdef MAC
1279	error = mac_kld_check_stat(td->td_ucred);
1280	if (error)
1281		return (error);
1282#endif
1283
1284	sx_xlock(&kld_sx);
1285	lf = linker_find_file_by_id(uap->fileid);
1286	if (lf) {
1287		MOD_SLOCK;
1288		mp = TAILQ_FIRST(&lf->modules);
1289		if (mp != NULL)
1290			td->td_retval[0] = module_getid(mp);
1291		else
1292			td->td_retval[0] = 0;
1293		MOD_SUNLOCK;
1294	} else
1295		error = ENOENT;
1296	sx_xunlock(&kld_sx);
1297	return (error);
1298}
1299
1300int
1301sys_kldsym(struct thread *td, struct kldsym_args *uap)
1302{
1303	char *symstr = NULL;
1304	c_linker_sym_t sym;
1305	linker_symval_t symval;
1306	linker_file_t lf;
1307	struct kld_sym_lookup lookup;
1308	int error = 0;
1309
1310#ifdef MAC
1311	error = mac_kld_check_stat(td->td_ucred);
1312	if (error)
1313		return (error);
1314#endif
1315
1316	if ((error = copyin(uap->data, &lookup, sizeof(lookup))) != 0)
1317		return (error);
1318	if (lookup.version != sizeof(lookup) ||
1319	    uap->cmd != KLDSYM_LOOKUP)
1320		return (EINVAL);
1321	symstr = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
1322	if ((error = copyinstr(lookup.symname, symstr, MAXPATHLEN, NULL)) != 0)
1323		goto out;
1324	sx_xlock(&kld_sx);
1325	if (uap->fileid != 0) {
1326		lf = linker_find_file_by_id(uap->fileid);
1327		if (lf == NULL)
1328			error = ENOENT;
1329		else if (LINKER_LOOKUP_SYMBOL(lf, symstr, &sym) == 0 &&
1330		    LINKER_SYMBOL_VALUES(lf, sym, &symval) == 0) {
1331			lookup.symvalue = (uintptr_t) symval.value;
1332			lookup.symsize = symval.size;
1333			error = copyout(&lookup, uap->data, sizeof(lookup));
1334		} else
1335			error = ENOENT;
1336	} else {
1337		TAILQ_FOREACH(lf, &linker_files, link) {
1338			if (LINKER_LOOKUP_SYMBOL(lf, symstr, &sym) == 0 &&
1339			    LINKER_SYMBOL_VALUES(lf, sym, &symval) == 0) {
1340				lookup.symvalue = (uintptr_t)symval.value;
1341				lookup.symsize = symval.size;
1342				error = copyout(&lookup, uap->data,
1343				    sizeof(lookup));
1344				break;
1345			}
1346		}
1347		if (lf == NULL)
1348			error = ENOENT;
1349	}
1350	sx_xunlock(&kld_sx);
1351out:
1352	free(symstr, M_TEMP);
1353	return (error);
1354}
1355
1356/*
1357 * Preloaded module support
1358 */
1359
1360static modlist_t
1361modlist_lookup(const char *name, int ver)
1362{
1363	modlist_t mod;
1364
1365	TAILQ_FOREACH(mod, &found_modules, link) {
1366		if (strcmp(mod->name, name) == 0 &&
1367		    (ver == 0 || mod->version == ver))
1368			return (mod);
1369	}
1370	return (NULL);
1371}
1372
1373static modlist_t
1374modlist_lookup2(const char *name, const struct mod_depend *verinfo)
1375{
1376	modlist_t mod, bestmod;
1377	int ver;
1378
1379	if (verinfo == NULL)
1380		return (modlist_lookup(name, 0));
1381	bestmod = NULL;
1382	TAILQ_FOREACH(mod, &found_modules, link) {
1383		if (strcmp(mod->name, name) != 0)
1384			continue;
1385		ver = mod->version;
1386		if (ver == verinfo->md_ver_preferred)
1387			return (mod);
1388		if (ver >= verinfo->md_ver_minimum &&
1389		    ver <= verinfo->md_ver_maximum &&
1390		    (bestmod == NULL || ver > bestmod->version))
1391			bestmod = mod;
1392	}
1393	return (bestmod);
1394}
1395
1396static modlist_t
1397modlist_newmodule(const char *modname, int version, linker_file_t container)
1398{
1399	modlist_t mod;
1400
1401	mod = malloc(sizeof(struct modlist), M_LINKER, M_NOWAIT | M_ZERO);
1402	if (mod == NULL)
1403		panic("no memory for module list");
1404	mod->container = container;
1405	mod->name = modname;
1406	mod->version = version;
1407	TAILQ_INSERT_TAIL(&found_modules, mod, link);
1408	return (mod);
1409}
1410
1411static void
1412linker_addmodules(linker_file_t lf, struct mod_metadata **start,
1413    struct mod_metadata **stop, int preload)
1414{
1415	struct mod_metadata *mp, **mdp;
1416	const char *modname;
1417	int ver;
1418
1419	for (mdp = start; mdp < stop; mdp++) {
1420		mp = *mdp;
1421		if (mp->md_type != MDT_VERSION)
1422			continue;
1423		modname = mp->md_cval;
1424		ver = ((struct mod_version *)mp->md_data)->mv_version;
1425		if (modlist_lookup(modname, ver) != NULL) {
1426			printf("module %s already present!\n", modname);
1427			/* XXX what can we do? this is a build error. :-( */
1428			continue;
1429		}
1430		modlist_newmodule(modname, ver, lf);
1431	}
1432}
1433
1434static void
1435linker_preload(void *arg)
1436{
1437	caddr_t modptr;
1438	const char *modname, *nmodname;
1439	char *modtype;
1440	linker_file_t lf, nlf;
1441	linker_class_t lc;
1442	int error;
1443	linker_file_list_t loaded_files;
1444	linker_file_list_t depended_files;
1445	struct mod_metadata *mp, *nmp;
1446	struct mod_metadata **start, **stop, **mdp, **nmdp;
1447	const struct mod_depend *verinfo;
1448	int nver;
1449	int resolves;
1450	modlist_t mod;
1451	struct sysinit **si_start, **si_stop;
1452
1453	TAILQ_INIT(&loaded_files);
1454	TAILQ_INIT(&depended_files);
1455	TAILQ_INIT(&found_modules);
1456	error = 0;
1457
1458	modptr = NULL;
1459	sx_xlock(&kld_sx);
1460	while ((modptr = preload_search_next_name(modptr)) != NULL) {
1461		modname = (char *)preload_search_info(modptr, MODINFO_NAME);
1462		modtype = (char *)preload_search_info(modptr, MODINFO_TYPE);
1463		if (modname == NULL) {
1464			printf("Preloaded module at %p does not have a"
1465			    " name!\n", modptr);
1466			continue;
1467		}
1468		if (modtype == NULL) {
1469			printf("Preloaded module at %p does not have a type!\n",
1470			    modptr);
1471			continue;
1472		}
1473		if (bootverbose)
1474			printf("Preloaded %s \"%s\" at %p.\n", modtype, modname,
1475			    modptr);
1476		lf = NULL;
1477		TAILQ_FOREACH(lc, &classes, link) {
1478			error = LINKER_LINK_PRELOAD(lc, modname, &lf);
1479			if (!error)
1480				break;
1481			lf = NULL;
1482		}
1483		if (lf)
1484			TAILQ_INSERT_TAIL(&loaded_files, lf, loaded);
1485	}
1486
1487	/*
1488	 * First get a list of stuff in the kernel.
1489	 */
1490	if (linker_file_lookup_set_locked(linker_kernel_file, MDT_SETNAME,
1491	    &start, &stop, NULL) == 0)
1492		linker_addmodules(linker_kernel_file, start, stop, 1);
1493
1494	/*
1495	 * This is a once-off kinky bubble sort to resolve relocation
1496	 * dependency requirements.
1497	 */
1498restart:
1499	TAILQ_FOREACH(lf, &loaded_files, loaded) {
1500		error = linker_file_lookup_set_locked(lf, MDT_SETNAME, &start,
1501		    &stop, NULL);
1502		/*
1503		 * First, look to see if we would successfully link with this
1504		 * stuff.
1505		 */
1506		resolves = 1;	/* unless we know otherwise */
1507		if (!error) {
1508			for (mdp = start; mdp < stop; mdp++) {
1509				mp = *mdp;
1510				if (mp->md_type != MDT_DEPEND)
1511					continue;
1512				modname = mp->md_cval;
1513				verinfo = mp->md_data;
1514				for (nmdp = start; nmdp < stop; nmdp++) {
1515					nmp = *nmdp;
1516					if (nmp->md_type != MDT_VERSION)
1517						continue;
1518					nmodname = nmp->md_cval;
1519					if (strcmp(modname, nmodname) == 0)
1520						break;
1521				}
1522				if (nmdp < stop)   /* it's a self reference */
1523					continue;
1524
1525				/*
1526				 * ok, the module isn't here yet, we
1527				 * are not finished
1528				 */
1529				if (modlist_lookup2(modname, verinfo) == NULL)
1530					resolves = 0;
1531			}
1532		}
1533		/*
1534		 * OK, if we found our modules, we can link.  So, "provide"
1535		 * the modules inside and add it to the end of the link order
1536		 * list.
1537		 */
1538		if (resolves) {
1539			if (!error) {
1540				for (mdp = start; mdp < stop; mdp++) {
1541					mp = *mdp;
1542					if (mp->md_type != MDT_VERSION)
1543						continue;
1544					modname = mp->md_cval;
1545					nver = ((struct mod_version *)
1546					    mp->md_data)->mv_version;
1547					if (modlist_lookup(modname,
1548					    nver) != NULL) {
1549						printf("module %s already"
1550						    " present!\n", modname);
1551						TAILQ_REMOVE(&loaded_files,
1552						    lf, loaded);
1553						linker_file_unload(lf,
1554						    LINKER_UNLOAD_FORCE);
1555						/* we changed tailq next ptr */
1556						goto restart;
1557					}
1558					modlist_newmodule(modname, nver, lf);
1559				}
1560			}
1561			TAILQ_REMOVE(&loaded_files, lf, loaded);
1562			TAILQ_INSERT_TAIL(&depended_files, lf, loaded);
1563			/*
1564			 * Since we provided modules, we need to restart the
1565			 * sort so that the previous files that depend on us
1566			 * have a chance. Also, we've busted the tailq next
1567			 * pointer with the REMOVE.
1568			 */
1569			goto restart;
1570		}
1571	}
1572
1573	/*
1574	 * At this point, we check to see what could not be resolved..
1575	 */
1576	while ((lf = TAILQ_FIRST(&loaded_files)) != NULL) {
1577		TAILQ_REMOVE(&loaded_files, lf, loaded);
1578		printf("KLD file %s is missing dependencies\n", lf->filename);
1579		linker_file_unload(lf, LINKER_UNLOAD_FORCE);
1580	}
1581
1582	/*
1583	 * We made it. Finish off the linking in the order we determined.
1584	 */
1585	TAILQ_FOREACH_SAFE(lf, &depended_files, loaded, nlf) {
1586		if (linker_kernel_file) {
1587			linker_kernel_file->refs++;
1588			error = linker_file_add_dependency(lf,
1589			    linker_kernel_file);
1590			if (error)
1591				panic("cannot add dependency");
1592		}
1593		lf->userrefs++;	/* so we can (try to) kldunload it */
1594		error = linker_file_lookup_set_locked(lf, MDT_SETNAME, &start,
1595		    &stop, NULL);
1596		if (!error) {
1597			for (mdp = start; mdp < stop; mdp++) {
1598				mp = *mdp;
1599				if (mp->md_type != MDT_DEPEND)
1600					continue;
1601				modname = mp->md_cval;
1602				verinfo = mp->md_data;
1603				mod = modlist_lookup2(modname, verinfo);
1604				if (mod == NULL) {
1605					printf("KLD file %s - cannot find "
1606					    "dependency \"%s\"\n",
1607					    lf->filename, modname);
1608					goto fail;
1609				}
1610				/* Don't count self-dependencies */
1611				if (lf == mod->container)
1612					continue;
1613				mod->container->refs++;
1614				error = linker_file_add_dependency(lf,
1615				    mod->container);
1616				if (error)
1617					panic("cannot add dependency");
1618			}
1619		}
1620		/*
1621		 * Now do relocation etc using the symbol search paths
1622		 * established by the dependencies
1623		 */
1624		error = LINKER_LINK_PRELOAD_FINISH(lf);
1625		if (error) {
1626			printf("KLD file %s - could not finalize loading\n",
1627			    lf->filename);
1628			goto fail;
1629		}
1630		linker_file_register_modules(lf);
1631		if (linker_file_lookup_set_locked(lf, "sysinit_set", &si_start,
1632		    &si_stop, NULL) == 0)
1633			sysinit_add(si_start, si_stop);
1634		linker_file_register_sysctls(lf);
1635		lf->flags |= LINKER_FILE_LINKED;
1636		continue;
1637fail:
1638		TAILQ_REMOVE(&depended_files, lf, loaded);
1639		linker_file_unload(lf, LINKER_UNLOAD_FORCE);
1640	}
1641	sx_xunlock(&kld_sx);
1642	/* woohoo! we made it! */
1643}
1644
1645SYSINIT(preload, SI_SUB_KLD, SI_ORDER_MIDDLE, linker_preload, 0);
1646
1647/*
1648 * Search for a not-loaded module by name.
1649 *
1650 * Modules may be found in the following locations:
1651 *
1652 * - preloaded (result is just the module name) - on disk (result is full path
1653 * to module)
1654 *
1655 * If the module name is qualified in any way (contains path, etc.) the we
1656 * simply return a copy of it.
1657 *
1658 * The search path can be manipulated via sysctl.  Note that we use the ';'
1659 * character as a separator to be consistent with the bootloader.
1660 */
1661
1662static char linker_hintfile[] = "linker.hints";
1663static char linker_path[MAXPATHLEN] = "/boot/kernel;/boot/modules";
1664
1665SYSCTL_STRING(_kern, OID_AUTO, module_path, CTLFLAG_RWTUN, linker_path,
1666    sizeof(linker_path), "module load search path");
1667
1668TUNABLE_STR("module_path", linker_path, sizeof(linker_path));
1669
1670static char *linker_ext_list[] = {
1671	"",
1672	".ko",
1673	NULL
1674};
1675
1676/*
1677 * Check if file actually exists either with or without extension listed in
1678 * the linker_ext_list. (probably should be generic for the rest of the
1679 * kernel)
1680 */
1681static char *
1682linker_lookup_file(const char *path, int pathlen, const char *name,
1683    int namelen, struct vattr *vap)
1684{
1685	struct nameidata nd;
1686	struct thread *td = curthread;	/* XXX */
1687	char *result, **cpp, *sep;
1688	int error, len, extlen, reclen, flags;
1689	enum vtype type;
1690
1691	extlen = 0;
1692	for (cpp = linker_ext_list; *cpp; cpp++) {
1693		len = strlen(*cpp);
1694		if (len > extlen)
1695			extlen = len;
1696	}
1697	extlen++;		/* trailing '\0' */
1698	sep = (path[pathlen - 1] != '/') ? "/" : "";
1699
1700	reclen = pathlen + strlen(sep) + namelen + extlen + 1;
1701	result = malloc(reclen, M_LINKER, M_WAITOK);
1702	for (cpp = linker_ext_list; *cpp; cpp++) {
1703		snprintf(result, reclen, "%.*s%s%.*s%s", pathlen, path, sep,
1704		    namelen, name, *cpp);
1705		/*
1706		 * Attempt to open the file, and return the path if
1707		 * we succeed and it's a regular file.
1708		 */
1709		NDINIT(&nd, LOOKUP, FOLLOW, UIO_SYSSPACE, result, td);
1710		flags = FREAD;
1711		error = vn_open(&nd, &flags, 0, NULL);
1712		if (error == 0) {
1713			NDFREE(&nd, NDF_ONLY_PNBUF);
1714			type = nd.ni_vp->v_type;
1715			if (vap)
1716				VOP_GETATTR(nd.ni_vp, vap, td->td_ucred);
1717			VOP_UNLOCK(nd.ni_vp, 0);
1718			vn_close(nd.ni_vp, FREAD, td->td_ucred, td);
1719			if (type == VREG)
1720				return (result);
1721		}
1722	}
1723	free(result, M_LINKER);
1724	return (NULL);
1725}
1726
1727#define	INT_ALIGN(base, ptr)	ptr =					\
1728	(base) + (((ptr) - (base) + sizeof(int) - 1) & ~(sizeof(int) - 1))
1729
1730/*
1731 * Lookup KLD which contains requested module in the "linker.hints" file. If
1732 * version specification is available, then try to find the best KLD.
1733 * Otherwise just find the latest one.
1734 */
1735static char *
1736linker_hints_lookup(const char *path, int pathlen, const char *modname,
1737    int modnamelen, const struct mod_depend *verinfo)
1738{
1739	struct thread *td = curthread;	/* XXX */
1740	struct ucred *cred = td ? td->td_ucred : NULL;
1741	struct nameidata nd;
1742	struct vattr vattr, mattr;
1743	u_char *hints = NULL;
1744	u_char *cp, *recptr, *bufend, *result, *best, *pathbuf, *sep;
1745	int error, ival, bestver, *intp, found, flags, clen, blen;
1746	ssize_t reclen;
1747
1748	result = NULL;
1749	bestver = found = 0;
1750
1751	sep = (path[pathlen - 1] != '/') ? "/" : "";
1752	reclen = imax(modnamelen, strlen(linker_hintfile)) + pathlen +
1753	    strlen(sep) + 1;
1754	pathbuf = malloc(reclen, M_LINKER, M_WAITOK);
1755	snprintf(pathbuf, reclen, "%.*s%s%s", pathlen, path, sep,
1756	    linker_hintfile);
1757
1758	NDINIT(&nd, LOOKUP, NOFOLLOW, UIO_SYSSPACE, pathbuf, td);
1759	flags = FREAD;
1760	error = vn_open(&nd, &flags, 0, NULL);
1761	if (error)
1762		goto bad;
1763	NDFREE(&nd, NDF_ONLY_PNBUF);
1764	if (nd.ni_vp->v_type != VREG)
1765		goto bad;
1766	best = cp = NULL;
1767	error = VOP_GETATTR(nd.ni_vp, &vattr, cred);
1768	if (error)
1769		goto bad;
1770	/*
1771	 * XXX: we need to limit this number to some reasonable value
1772	 */
1773	if (vattr.va_size > LINKER_HINTS_MAX) {
1774		printf("hints file too large %ld\n", (long)vattr.va_size);
1775		goto bad;
1776	}
1777	hints = malloc(vattr.va_size, M_TEMP, M_WAITOK);
1778	if (hints == NULL)
1779		goto bad;
1780	error = vn_rdwr(UIO_READ, nd.ni_vp, (caddr_t)hints, vattr.va_size, 0,
1781	    UIO_SYSSPACE, IO_NODELOCKED, cred, NOCRED, &reclen, td);
1782	if (error)
1783		goto bad;
1784	VOP_UNLOCK(nd.ni_vp, 0);
1785	vn_close(nd.ni_vp, FREAD, cred, td);
1786	nd.ni_vp = NULL;
1787	if (reclen != 0) {
1788		printf("can't read %zd\n", reclen);
1789		goto bad;
1790	}
1791	intp = (int *)hints;
1792	ival = *intp++;
1793	if (ival != LINKER_HINTS_VERSION) {
1794		printf("hints file version mismatch %d\n", ival);
1795		goto bad;
1796	}
1797	bufend = hints + vattr.va_size;
1798	recptr = (u_char *)intp;
1799	clen = blen = 0;
1800	while (recptr < bufend && !found) {
1801		intp = (int *)recptr;
1802		reclen = *intp++;
1803		ival = *intp++;
1804		cp = (char *)intp;
1805		switch (ival) {
1806		case MDT_VERSION:
1807			clen = *cp++;
1808			if (clen != modnamelen || bcmp(cp, modname, clen) != 0)
1809				break;
1810			cp += clen;
1811			INT_ALIGN(hints, cp);
1812			ival = *(int *)cp;
1813			cp += sizeof(int);
1814			clen = *cp++;
1815			if (verinfo == NULL ||
1816			    ival == verinfo->md_ver_preferred) {
1817				found = 1;
1818				break;
1819			}
1820			if (ival >= verinfo->md_ver_minimum &&
1821			    ival <= verinfo->md_ver_maximum &&
1822			    ival > bestver) {
1823				bestver = ival;
1824				best = cp;
1825				blen = clen;
1826			}
1827			break;
1828		default:
1829			break;
1830		}
1831		recptr += reclen + sizeof(int);
1832	}
1833	/*
1834	 * Finally check if KLD is in the place
1835	 */
1836	if (found)
1837		result = linker_lookup_file(path, pathlen, cp, clen, &mattr);
1838	else if (best)
1839		result = linker_lookup_file(path, pathlen, best, blen, &mattr);
1840
1841	/*
1842	 * KLD is newer than hints file. What we should do now?
1843	 */
1844	if (result && timespeccmp(&mattr.va_mtime, &vattr.va_mtime, >))
1845		printf("warning: KLD '%s' is newer than the linker.hints"
1846		    " file\n", result);
1847bad:
1848	free(pathbuf, M_LINKER);
1849	if (hints)
1850		free(hints, M_TEMP);
1851	if (nd.ni_vp != NULL) {
1852		VOP_UNLOCK(nd.ni_vp, 0);
1853		vn_close(nd.ni_vp, FREAD, cred, td);
1854	}
1855	/*
1856	 * If nothing found or hints is absent - fallback to the old
1857	 * way by using "kldname[.ko]" as module name.
1858	 */
1859	if (!found && !bestver && result == NULL)
1860		result = linker_lookup_file(path, pathlen, modname,
1861		    modnamelen, NULL);
1862	return (result);
1863}
1864
1865/*
1866 * Lookup KLD which contains requested module in the all directories.
1867 */
1868static char *
1869linker_search_module(const char *modname, int modnamelen,
1870    const struct mod_depend *verinfo)
1871{
1872	char *cp, *ep, *result;
1873
1874	/*
1875	 * traverse the linker path
1876	 */
1877	for (cp = linker_path; *cp; cp = ep + 1) {
1878		/* find the end of this component */
1879		for (ep = cp; (*ep != 0) && (*ep != ';'); ep++);
1880		result = linker_hints_lookup(cp, ep - cp, modname,
1881		    modnamelen, verinfo);
1882		if (result != NULL)
1883			return (result);
1884		if (*ep == 0)
1885			break;
1886	}
1887	return (NULL);
1888}
1889
1890/*
1891 * Search for module in all directories listed in the linker_path.
1892 */
1893static char *
1894linker_search_kld(const char *name)
1895{
1896	char *cp, *ep, *result;
1897	int len;
1898
1899	/* qualified at all? */
1900	if (strchr(name, '/'))
1901		return (strdup(name, M_LINKER));
1902
1903	/* traverse the linker path */
1904	len = strlen(name);
1905	for (ep = linker_path; *ep; ep++) {
1906		cp = ep;
1907		/* find the end of this component */
1908		for (; *ep != 0 && *ep != ';'; ep++);
1909		result = linker_lookup_file(cp, ep - cp, name, len, NULL);
1910		if (result != NULL)
1911			return (result);
1912	}
1913	return (NULL);
1914}
1915
1916static const char *
1917linker_basename(const char *path)
1918{
1919	const char *filename;
1920
1921	filename = strrchr(path, '/');
1922	if (filename == NULL)
1923		return path;
1924	if (filename[1])
1925		filename++;
1926	return (filename);
1927}
1928
1929#ifdef HWPMC_HOOKS
1930/*
1931 * Inform hwpmc about the set of kernel modules currently loaded.
1932 */
1933void *
1934linker_hwpmc_list_objects(void)
1935{
1936	linker_file_t lf;
1937	struct pmckern_map_in *kobase;
1938	int i, nmappings;
1939
1940	nmappings = 0;
1941	sx_slock(&kld_sx);
1942	TAILQ_FOREACH(lf, &linker_files, link)
1943		nmappings++;
1944
1945	/* Allocate nmappings + 1 entries. */
1946	kobase = malloc((nmappings + 1) * sizeof(struct pmckern_map_in),
1947	    M_LINKER, M_WAITOK | M_ZERO);
1948	i = 0;
1949	TAILQ_FOREACH(lf, &linker_files, link) {
1950
1951		/* Save the info for this linker file. */
1952		kobase[i].pm_file = lf->filename;
1953		kobase[i].pm_address = (uintptr_t)lf->address;
1954		i++;
1955	}
1956	sx_sunlock(&kld_sx);
1957
1958	KASSERT(i > 0, ("linker_hpwmc_list_objects: no kernel objects?"));
1959
1960	/* The last entry of the malloced area comprises of all zeros. */
1961	KASSERT(kobase[i].pm_file == NULL,
1962	    ("linker_hwpmc_list_objects: last object not NULL"));
1963
1964	return ((void *)kobase);
1965}
1966#endif
1967
1968/*
1969 * Find a file which contains given module and load it, if "parent" is not
1970 * NULL, register a reference to it.
1971 */
1972static int
1973linker_load_module(const char *kldname, const char *modname,
1974    struct linker_file *parent, const struct mod_depend *verinfo,
1975    struct linker_file **lfpp)
1976{
1977	linker_file_t lfdep;
1978	const char *filename;
1979	char *pathname;
1980	int error;
1981
1982	sx_assert(&kld_sx, SA_XLOCKED);
1983	if (modname == NULL) {
1984		/*
1985 		 * We have to load KLD
1986 		 */
1987		KASSERT(verinfo == NULL, ("linker_load_module: verinfo"
1988		    " is not NULL"));
1989		pathname = linker_search_kld(kldname);
1990	} else {
1991		if (modlist_lookup2(modname, verinfo) != NULL)
1992			return (EEXIST);
1993		if (kldname != NULL)
1994			pathname = strdup(kldname, M_LINKER);
1995		else if (rootvnode == NULL)
1996			pathname = NULL;
1997		else
1998			/*
1999			 * Need to find a KLD with required module
2000			 */
2001			pathname = linker_search_module(modname,
2002			    strlen(modname), verinfo);
2003	}
2004	if (pathname == NULL)
2005		return (ENOENT);
2006
2007	/*
2008	 * Can't load more than one file with the same basename XXX:
2009	 * Actually it should be possible to have multiple KLDs with
2010	 * the same basename but different path because they can
2011	 * provide different versions of the same modules.
2012	 */
2013	filename = linker_basename(pathname);
2014	if (linker_find_file_by_name(filename))
2015		error = EEXIST;
2016	else do {
2017		error = linker_load_file(pathname, &lfdep);
2018		if (error)
2019			break;
2020		if (modname && verinfo &&
2021		    modlist_lookup2(modname, verinfo) == NULL) {
2022			linker_file_unload(lfdep, LINKER_UNLOAD_FORCE);
2023			error = ENOENT;
2024			break;
2025		}
2026		if (parent) {
2027			error = linker_file_add_dependency(parent, lfdep);
2028			if (error)
2029				break;
2030		}
2031		if (lfpp)
2032			*lfpp = lfdep;
2033	} while (0);
2034	free(pathname, M_LINKER);
2035	return (error);
2036}
2037
2038/*
2039 * This routine is responsible for finding dependencies of userland initiated
2040 * kldload(2)'s of files.
2041 */
2042int
2043linker_load_dependencies(linker_file_t lf)
2044{
2045	linker_file_t lfdep;
2046	struct mod_metadata **start, **stop, **mdp, **nmdp;
2047	struct mod_metadata *mp, *nmp;
2048	const struct mod_depend *verinfo;
2049	modlist_t mod;
2050	const char *modname, *nmodname;
2051	int ver, error = 0, count;
2052
2053	/*
2054	 * All files are dependant on /kernel.
2055	 */
2056	sx_assert(&kld_sx, SA_XLOCKED);
2057	if (linker_kernel_file) {
2058		linker_kernel_file->refs++;
2059		error = linker_file_add_dependency(lf, linker_kernel_file);
2060		if (error)
2061			return (error);
2062	}
2063	if (linker_file_lookup_set_locked(lf, MDT_SETNAME, &start, &stop,
2064	    &count) != 0)
2065		return (0);
2066	for (mdp = start; mdp < stop; mdp++) {
2067		mp = *mdp;
2068		if (mp->md_type != MDT_VERSION)
2069			continue;
2070		modname = mp->md_cval;
2071		ver = ((struct mod_version *)mp->md_data)->mv_version;
2072		mod = modlist_lookup(modname, ver);
2073		if (mod != NULL) {
2074			printf("interface %s.%d already present in the KLD"
2075			    " '%s'!\n", modname, ver,
2076			    mod->container->filename);
2077			return (EEXIST);
2078		}
2079	}
2080
2081	for (mdp = start; mdp < stop; mdp++) {
2082		mp = *mdp;
2083		if (mp->md_type != MDT_DEPEND)
2084			continue;
2085		modname = mp->md_cval;
2086		verinfo = mp->md_data;
2087		nmodname = NULL;
2088		for (nmdp = start; nmdp < stop; nmdp++) {
2089			nmp = *nmdp;
2090			if (nmp->md_type != MDT_VERSION)
2091				continue;
2092			nmodname = nmp->md_cval;
2093			if (strcmp(modname, nmodname) == 0)
2094				break;
2095		}
2096		if (nmdp < stop)/* early exit, it's a self reference */
2097			continue;
2098		mod = modlist_lookup2(modname, verinfo);
2099		if (mod) {	/* woohoo, it's loaded already */
2100			lfdep = mod->container;
2101			lfdep->refs++;
2102			error = linker_file_add_dependency(lf, lfdep);
2103			if (error)
2104				break;
2105			continue;
2106		}
2107		error = linker_load_module(NULL, modname, lf, verinfo, NULL);
2108		if (error) {
2109			printf("KLD %s: depends on %s - not available or"
2110			    " version mismatch\n", lf->filename, modname);
2111			break;
2112		}
2113	}
2114
2115	if (error)
2116		return (error);
2117	linker_addmodules(lf, start, stop, 0);
2118	return (error);
2119}
2120
2121static int
2122sysctl_kern_function_list_iterate(const char *name, void *opaque)
2123{
2124	struct sysctl_req *req;
2125
2126	req = opaque;
2127	return (SYSCTL_OUT(req, name, strlen(name) + 1));
2128}
2129
2130/*
2131 * Export a nul-separated, double-nul-terminated list of all function names
2132 * in the kernel.
2133 */
2134static int
2135sysctl_kern_function_list(SYSCTL_HANDLER_ARGS)
2136{
2137	linker_file_t lf;
2138	int error;
2139
2140#ifdef MAC
2141	error = mac_kld_check_stat(req->td->td_ucred);
2142	if (error)
2143		return (error);
2144#endif
2145	error = sysctl_wire_old_buffer(req, 0);
2146	if (error != 0)
2147		return (error);
2148	sx_xlock(&kld_sx);
2149	TAILQ_FOREACH(lf, &linker_files, link) {
2150		error = LINKER_EACH_FUNCTION_NAME(lf,
2151		    sysctl_kern_function_list_iterate, req);
2152		if (error) {
2153			sx_xunlock(&kld_sx);
2154			return (error);
2155		}
2156	}
2157	sx_xunlock(&kld_sx);
2158	return (SYSCTL_OUT(req, "", 1));
2159}
2160
2161SYSCTL_PROC(_kern, OID_AUTO, function_list, CTLTYPE_OPAQUE | CTLFLAG_RD,
2162    NULL, 0, sysctl_kern_function_list, "", "kernel function list");
2163