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