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