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