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