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