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