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