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