kern_linker.c revision 92803
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 92803 2002-03-20 16:03:42Z 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	mtx_lock(&Giant);
702
703	if (securelevel_gt(td->td_ucred, 0) == 0) {
704		error = EPERM;
705		goto out;
706	}
707
708	if ((error = suser_xxx(td->td_ucred, NULL, 0)) != 0)
709		goto out;
710
711	pathname = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
712	if ((error = copyinstr(SCARG(uap, file), pathname, MAXPATHLEN,
713	    NULL)) != 0)
714		goto out;
715
716	/*
717	 * If path do not contain qualified name or any dot in it
718	 * (kldname.ko, or kldname.ver.ko) treat it as interface
719	 * name.
720	 */
721	if (index(pathname, '/') || index(pathname, '.')) {
722		kldname = pathname;
723		modname = NULL;
724	} else {
725		kldname = NULL;
726		modname = pathname;
727	}
728	error = linker_load_module(kldname, modname, NULL, NULL, &lf);
729	if (error)
730		goto out;
731
732	lf->userrefs++;
733	td->td_retval[0] = lf->id;
734out:
735	if (pathname)
736		free(pathname, M_TEMP);
737	mtx_unlock(&Giant);
738	return (error);
739}
740
741/*
742 * MPSAFE
743 */
744int
745kldunload(struct thread *td, struct kldunload_args *uap)
746{
747	linker_file_t lf;
748	int error = 0;
749
750	mtx_lock(&Giant);
751
752	if (securelevel_gt(td->td_ucred, 0) == 0) {
753		error = EPERM;
754		goto out;
755	}
756
757	if ((error = suser_xxx(td->td_ucred, NULL, 0)) != 0)
758		goto out;
759
760	lf = linker_find_file_by_id(SCARG(uap, fileid));
761	if (lf) {
762		KLD_DPF(FILE, ("kldunload: lf->userrefs=%d\n", lf->userrefs));
763		if (lf->userrefs == 0) {
764			printf("kldunload: attempt to unload file that was"
765			    " loaded by the kernel\n");
766			error = EBUSY;
767			goto out;
768		}
769		lf->userrefs--;
770		error = linker_file_unload(lf);
771		if (error)
772			lf->userrefs++;
773	} else
774		error = ENOENT;
775out:
776	mtx_unlock(&Giant);
777	return (error);
778}
779
780/*
781 * MPSAFE
782 */
783int
784kldfind(struct thread *td, struct kldfind_args *uap)
785{
786	char *pathname;
787	const char *filename;
788	linker_file_t lf;
789	int error = 0;
790
791	mtx_lock(&Giant);
792	td->td_retval[0] = -1;
793
794	pathname = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
795	if ((error = copyinstr(SCARG(uap, file), pathname, MAXPATHLEN,
796	    NULL)) != 0)
797		goto out;
798
799	filename = linker_basename(pathname);
800	lf = linker_find_file_by_name(filename);
801	if (lf)
802		td->td_retval[0] = lf->id;
803	else
804		error = ENOENT;
805out:
806	if (pathname)
807		free(pathname, M_TEMP);
808	mtx_unlock(&Giant);
809	return (error);
810}
811
812/*
813 * MPSAFE
814 */
815int
816kldnext(struct thread *td, struct kldnext_args *uap)
817{
818	linker_file_t lf;
819	int error = 0;
820
821	mtx_lock(&Giant);
822
823	if (SCARG(uap, fileid) == 0) {
824		if (TAILQ_FIRST(&linker_files))
825			td->td_retval[0] = TAILQ_FIRST(&linker_files)->id;
826		else
827			td->td_retval[0] = 0;
828		goto out;
829	}
830	lf = linker_find_file_by_id(SCARG(uap, fileid));
831	if (lf) {
832		if (TAILQ_NEXT(lf, link))
833			td->td_retval[0] = TAILQ_NEXT(lf, link)->id;
834		else
835			td->td_retval[0] = 0;
836	} else
837		error = ENOENT;
838out:
839	mtx_unlock(&Giant);
840	return (error);
841}
842
843/*
844 * MPSAFE
845 */
846int
847kldstat(struct thread *td, struct kldstat_args *uap)
848{
849	linker_file_t lf;
850	int error = 0;
851	int namelen, version;
852	struct kld_file_stat *stat;
853
854	mtx_lock(&Giant);
855
856	lf = linker_find_file_by_id(SCARG(uap, fileid));
857	if (lf == NULL) {
858		error = ENOENT;
859		goto out;
860	}
861	stat = SCARG(uap, stat);
862
863	/*
864	 * Check the version of the user's structure.
865	 */
866	if ((error = copyin(&stat->version, &version, sizeof(version))) != 0)
867		goto out;
868	if (version != sizeof(struct kld_file_stat)) {
869		error = EINVAL;
870		goto out;
871	}
872	namelen = strlen(lf->filename) + 1;
873	if (namelen > MAXPATHLEN)
874		namelen = MAXPATHLEN;
875	if ((error = copyout(lf->filename, &stat->name[0], namelen)) != 0)
876		goto out;
877	if ((error = copyout(&lf->refs, &stat->refs, sizeof(int))) != 0)
878		goto out;
879	if ((error = copyout(&lf->id, &stat->id, sizeof(int))) != 0)
880		goto out;
881	if ((error = copyout(&lf->address, &stat->address,
882	    sizeof(caddr_t))) != 0)
883		goto out;
884	if ((error = copyout(&lf->size, &stat->size, sizeof(size_t))) != 0)
885		goto out;
886
887	td->td_retval[0] = 0;
888out:
889	mtx_unlock(&Giant);
890	return (error);
891}
892
893/*
894 * MPSAFE
895 */
896int
897kldfirstmod(struct thread *td, struct kldfirstmod_args *uap)
898{
899	linker_file_t lf;
900	module_t mp;
901	int error = 0;
902
903	mtx_lock(&Giant);
904	lf = linker_find_file_by_id(SCARG(uap, fileid));
905	if (lf) {
906		MOD_SLOCK;
907		mp = TAILQ_FIRST(&lf->modules);
908		if (mp != NULL)
909			td->td_retval[0] = module_getid(mp);
910		else
911			td->td_retval[0] = 0;
912		MOD_SUNLOCK;
913	} else
914		error = ENOENT;
915	mtx_unlock(&Giant);
916	return (error);
917}
918
919/*
920 * MPSAFE
921 */
922int
923kldsym(struct thread *td, struct kldsym_args *uap)
924{
925	char *symstr = NULL;
926	c_linker_sym_t sym;
927	linker_symval_t symval;
928	linker_file_t lf;
929	struct kld_sym_lookup lookup;
930	int error = 0;
931
932	mtx_lock(&Giant);
933
934	if ((error = copyin(SCARG(uap, data), &lookup, sizeof(lookup))) != 0)
935		goto out;
936	if (lookup.version != sizeof(lookup) ||
937	    SCARG(uap, cmd) != KLDSYM_LOOKUP) {
938		error = EINVAL;
939		goto out;
940	}
941	symstr = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
942	if ((error = copyinstr(lookup.symname, symstr, MAXPATHLEN, NULL)) != 0)
943		goto out;
944	if (SCARG(uap, fileid) != 0) {
945		lf = linker_find_file_by_id(SCARG(uap, fileid));
946		if (lf == NULL) {
947			error = ENOENT;
948			goto out;
949		}
950		if (LINKER_LOOKUP_SYMBOL(lf, symstr, &sym) == 0 &&
951		    LINKER_SYMBOL_VALUES(lf, sym, &symval) == 0) {
952			lookup.symvalue = (uintptr_t) symval.value;
953			lookup.symsize = symval.size;
954			error = copyout(&lookup, SCARG(uap, data),
955			    sizeof(lookup));
956		} else
957			error = ENOENT;
958	} else {
959		TAILQ_FOREACH(lf, &linker_files, link) {
960			if (LINKER_LOOKUP_SYMBOL(lf, symstr, &sym) == 0 &&
961			    LINKER_SYMBOL_VALUES(lf, sym, &symval) == 0) {
962				lookup.symvalue = (uintptr_t)symval.value;
963				lookup.symsize = symval.size;
964				error = copyout(&lookup, SCARG(uap, data),
965				    sizeof(lookup));
966				break;
967			}
968		}
969		if (lf == NULL)
970			error = ENOENT;
971	}
972out:
973	if (symstr)
974		free(symstr, M_TEMP);
975	mtx_unlock(&Giant);
976	return (error);
977}
978
979/*
980 * Preloaded module support
981 */
982
983static modlist_t
984modlist_lookup(const char *name, int ver)
985{
986	modlist_t mod;
987
988	TAILQ_FOREACH(mod, &found_modules, link) {
989		if (strcmp(mod->name, name) == 0 &&
990		    (ver == 0 || mod->version == ver))
991			return (mod);
992	}
993	return (NULL);
994}
995
996static modlist_t
997modlist_lookup2(const char *name, struct mod_depend *verinfo)
998{
999	modlist_t mod, bestmod;
1000	int ver;
1001
1002	if (verinfo == NULL)
1003		return (modlist_lookup(name, 0));
1004	bestmod = NULL;
1005	for (mod = TAILQ_FIRST(&found_modules); mod;
1006	    mod = TAILQ_NEXT(mod, link)) {
1007		if (strcmp(mod->name, name) != 0)
1008			continue;
1009		ver = mod->version;
1010		if (ver == verinfo->md_ver_preferred)
1011			return (mod);
1012		if (ver >= verinfo->md_ver_minimum &&
1013		    ver <= verinfo->md_ver_maximum &&
1014		    ver > bestmod->version)
1015			bestmod = mod;
1016	}
1017	return (bestmod);
1018}
1019
1020static modlist_t
1021modlist_newmodule(const char *modname, int version, linker_file_t container)
1022{
1023	modlist_t mod;
1024
1025	mod = malloc(sizeof(struct modlist), M_LINKER, M_NOWAIT | M_ZERO);
1026	if (mod == NULL)
1027		panic("no memory for module list");
1028	mod->container = container;
1029	mod->name = modname;
1030	mod->version = version;
1031	TAILQ_INSERT_TAIL(&found_modules, mod, link);
1032	return (mod);
1033}
1034
1035/*
1036 * This routine is cheap and nasty but will work for data pointers.
1037 */
1038static void *
1039linker_reloc_ptr(linker_file_t lf, const void *offset)
1040{
1041	return (lf->address + (uintptr_t)offset);
1042}
1043
1044/*
1045 * Dereference MDT_VERSION metadata into module name and version
1046 */
1047static void
1048linker_mdt_version(linker_file_t lf, struct mod_metadata *mp,
1049    const char **modname, int *version)
1050{
1051	struct mod_version *mvp;
1052
1053	if (modname)
1054		*modname = linker_reloc_ptr(lf, mp->md_cval);
1055	if (version) {
1056		mvp = linker_reloc_ptr(lf, mp->md_data);
1057		*version = mvp->mv_version;
1058	}
1059}
1060
1061/*
1062 * Dereference MDT_DEPEND metadata into module name and mod_depend structure
1063 */
1064static void
1065linker_mdt_depend(linker_file_t lf, struct mod_metadata *mp,
1066    const char **modname, struct mod_depend **verinfo)
1067{
1068
1069	if (modname)
1070		*modname = linker_reloc_ptr(lf, mp->md_cval);
1071	if (verinfo)
1072		*verinfo = linker_reloc_ptr(lf, mp->md_data);
1073}
1074
1075static void
1076linker_addmodules(linker_file_t lf, struct mod_metadata **start,
1077    struct mod_metadata **stop, int preload)
1078{
1079	struct mod_metadata *mp, **mdp;
1080	const char *modname;
1081	int ver;
1082
1083	for (mdp = start; mdp < stop; mdp++) {
1084		if (preload)
1085			mp = *mdp;
1086		else
1087			mp = linker_reloc_ptr(lf, *mdp);
1088		if (mp->md_type != MDT_VERSION)
1089			continue;
1090		if (preload) {
1091			modname = mp->md_cval;
1092			ver = ((struct mod_version *)mp->md_data)->mv_version;
1093		} else
1094	        	linker_mdt_version(lf, mp, &modname, &ver);
1095		if (modlist_lookup(modname, ver) != NULL) {
1096			printf("module %s already present!\n", modname);
1097			/* XXX what can we do? this is a build error. :-( */
1098			continue;
1099		}
1100		modlist_newmodule(modname, ver, lf);
1101	}
1102}
1103
1104static void
1105linker_preload(void *arg)
1106{
1107	caddr_t modptr;
1108	const char *modname, *nmodname;
1109	char *modtype;
1110	linker_file_t lf;
1111	linker_class_t lc;
1112	int error;
1113	linker_file_list_t loaded_files;
1114	linker_file_list_t depended_files;
1115	struct mod_metadata *mp, *nmp;
1116	struct mod_metadata **start, **stop, **mdp, **nmdp;
1117	struct mod_depend *verinfo;
1118	int nver;
1119	int resolves;
1120	modlist_t mod;
1121	struct sysinit **si_start, **si_stop;
1122
1123	TAILQ_INIT(&loaded_files);
1124	TAILQ_INIT(&depended_files);
1125	TAILQ_INIT(&found_modules);
1126	error = 0;
1127
1128	modptr = NULL;
1129	while ((modptr = preload_search_next_name(modptr)) != NULL) {
1130		modname = (char *)preload_search_info(modptr, MODINFO_NAME);
1131		modtype = (char *)preload_search_info(modptr, MODINFO_TYPE);
1132		if (modname == NULL) {
1133			printf("Preloaded module at %p does not have a"
1134			    " name!\n", modptr);
1135			continue;
1136		}
1137		if (modtype == NULL) {
1138			printf("Preloaded module at %p does not have a type!\n",
1139			    modptr);
1140			continue;
1141		}
1142		printf("Preloaded %s \"%s\" at %p.\n", modtype, modname,
1143		    modptr);
1144		lf = NULL;
1145		TAILQ_FOREACH(lc, &classes, link) {
1146			error = LINKER_LINK_PRELOAD(lc, modname, &lf);
1147			if (error) {
1148				lf = NULL;
1149				break;
1150			}
1151		}
1152		if (lf)
1153			TAILQ_INSERT_TAIL(&loaded_files, lf, loaded);
1154	}
1155
1156	/*
1157	 * First get a list of stuff in the kernel.
1158	 */
1159	if (linker_file_lookup_set(linker_kernel_file, MDT_SETNAME, &start,
1160	    &stop, NULL) == 0)
1161		linker_addmodules(linker_kernel_file, start, stop, 1);
1162
1163	/*
1164	 * this is a once-off kinky bubble sort resolve relocation dependency
1165	 * requirements
1166	 */
1167restart:
1168	TAILQ_FOREACH(lf, &loaded_files, loaded) {
1169		error = linker_file_lookup_set(lf, MDT_SETNAME, &start,
1170		    &stop, NULL);
1171		/*
1172		 * First, look to see if we would successfully link with this
1173		 * stuff.
1174		 */
1175		resolves = 1;	/* unless we know otherwise */
1176		if (!error) {
1177			for (mdp = start; mdp < stop; mdp++) {
1178				mp = linker_reloc_ptr(lf, *mdp);
1179				if (mp->md_type != MDT_DEPEND)
1180					continue;
1181				linker_mdt_depend(lf, mp, &modname, &verinfo);
1182				for (nmdp = start; nmdp < stop; nmdp++) {
1183					nmp = linker_reloc_ptr(lf, *nmdp);
1184					if (nmp->md_type != MDT_VERSION)
1185						continue;
1186					linker_mdt_version(lf, nmp, &nmodname,
1187					    NULL);
1188					nmodname = linker_reloc_ptr(lf,
1189					    nmp->md_cval);
1190					if (strcmp(modname, nmodname) == 0)
1191						break;
1192				}
1193				if (nmdp < stop)   /* it's a self reference */
1194					continue;
1195
1196				/*
1197				 * ok, the module isn't here yet, we
1198				 * are not finished
1199				 */
1200				if (modlist_lookup2(modname, verinfo) == NULL)
1201					resolves = 0;
1202			}
1203		}
1204		/*
1205		 * OK, if we found our modules, we can link.  So, "provide"
1206		 * the modules inside and add it to the end of the link order
1207		 * list.
1208		 */
1209		if (resolves) {
1210			if (!error) {
1211				for (mdp = start; mdp < stop; mdp++) {
1212					mp = linker_reloc_ptr(lf, *mdp);
1213					if (mp->md_type != MDT_VERSION)
1214						continue;
1215					linker_mdt_version(lf, mp,
1216					    &modname, &nver);
1217					if (modlist_lookup(modname,
1218					    nver) != NULL) {
1219						printf("module %s already"
1220						    " present!\n", modname);
1221						linker_file_unload(lf);
1222						TAILQ_REMOVE(&loaded_files,
1223						    lf, loaded);
1224						/* we changed tailq next ptr */
1225						goto restart;
1226					}
1227					modlist_newmodule(modname, nver, lf);
1228				}
1229			}
1230			TAILQ_REMOVE(&loaded_files, lf, loaded);
1231			TAILQ_INSERT_TAIL(&depended_files, lf, loaded);
1232			/*
1233			 * Since we provided modules, we need to restart the
1234			 * sort so that the previous files that depend on us
1235			 * have a chance. Also, we've busted the tailq next
1236			 * pointer with the REMOVE.
1237			 */
1238			goto restart;
1239		}
1240	}
1241
1242	/*
1243	 * At this point, we check to see what could not be resolved..
1244	 */
1245	TAILQ_FOREACH(lf, &loaded_files, loaded) {
1246		printf("KLD file %s is missing dependencies\n", lf->filename);
1247		linker_file_unload(lf);
1248		TAILQ_REMOVE(&loaded_files, lf, loaded);
1249	}
1250
1251	/*
1252	 * We made it. Finish off the linking in the order we determined.
1253	 */
1254	TAILQ_FOREACH(lf, &depended_files, loaded) {
1255		if (linker_kernel_file) {
1256			linker_kernel_file->refs++;
1257			error = linker_file_add_dependency(lf,
1258			    linker_kernel_file);
1259			if (error)
1260				panic("cannot add dependency");
1261		}
1262		lf->userrefs++;	/* so we can (try to) kldunload it */
1263		error = linker_file_lookup_set(lf, MDT_SETNAME, &start,
1264		    &stop, NULL);
1265		if (!error) {
1266			for (mdp = start; mdp < stop; mdp++) {
1267				mp = linker_reloc_ptr(lf, *mdp);
1268				if (mp->md_type != MDT_DEPEND)
1269					continue;
1270				linker_mdt_depend(lf, mp, &modname, &verinfo);
1271				mod = modlist_lookup2(modname, verinfo);
1272				mod->container->refs++;
1273				error = linker_file_add_dependency(lf,
1274				    mod->container);
1275				if (error)
1276					panic("cannot add dependency");
1277			}
1278		}
1279		/*
1280		 * Now do relocation etc using the symbol search paths
1281		 * established by the dependencies
1282		 */
1283		error = LINKER_LINK_PRELOAD_FINISH(lf);
1284		if (error) {
1285			printf("KLD file %s - could not finalize loading\n",
1286			    lf->filename);
1287			linker_file_unload(lf);
1288			continue;
1289		}
1290		linker_file_register_modules(lf);
1291		if (linker_file_lookup_set(lf, "sysinit_set", &si_start,
1292		    &si_stop, NULL) == 0)
1293			sysinit_add(si_start, si_stop);
1294		linker_file_register_sysctls(lf);
1295		lf->flags |= LINKER_FILE_LINKED;
1296	}
1297	/* woohoo! we made it! */
1298}
1299
1300SYSINIT(preload, SI_SUB_KLD, SI_ORDER_MIDDLE, linker_preload, 0)
1301
1302/*
1303 * Search for a not-loaded module by name.
1304 *
1305 * Modules may be found in the following locations:
1306 *
1307 * - preloaded (result is just the module name) - on disk (result is full path
1308 * to module)
1309 *
1310 * If the module name is qualified in any way (contains path, etc.) the we
1311 * simply return a copy of it.
1312 *
1313 * The search path can be manipulated via sysctl.  Note that we use the ';'
1314 * character as a separator to be consistent with the bootloader.
1315 */
1316
1317static char linker_hintfile[] = "linker.hints";
1318static char linker_path[MAXPATHLEN] = "/boot/kernel;/boot/modules;/modules";
1319
1320SYSCTL_STRING(_kern, OID_AUTO, module_path, CTLFLAG_RW, linker_path,
1321    sizeof(linker_path), "module load search path");
1322
1323TUNABLE_STR("module_path", linker_path, sizeof(linker_path));
1324
1325static char *linker_ext_list[] = {
1326	"",
1327	".ko",
1328	NULL
1329};
1330
1331/*
1332 * Check if file actually exists either with or without extension listed in
1333 * the linker_ext_list. (probably should be generic for the rest of the
1334 * kernel)
1335 */
1336static char *
1337linker_lookup_file(const char *path, int pathlen, const char *name,
1338    int namelen, struct vattr *vap)
1339{
1340	struct nameidata nd;
1341	struct thread *td = curthread;	/* XXX */
1342	char *result, **cpp, *sep;
1343	int error, len, extlen, reclen, flags;
1344	enum vtype type;
1345
1346	extlen = 0;
1347	for (cpp = linker_ext_list; *cpp; cpp++) {
1348		len = strlen(*cpp);
1349		if (len > extlen)
1350			extlen = len;
1351	}
1352	extlen++;		/* trailing '\0' */
1353	sep = (path[pathlen - 1] != '/') ? "/" : "";
1354
1355	reclen = pathlen + strlen(sep) + namelen + extlen + 1;
1356	result = malloc(reclen, M_LINKER, M_WAITOK);
1357	for (cpp = linker_ext_list; *cpp; cpp++) {
1358		snprintf(result, reclen, "%.*s%s%.*s%s", pathlen, path, sep,
1359		    namelen, name, *cpp);
1360		/*
1361		 * Attempt to open the file, and return the path if
1362		 * we succeed and it's a regular file.
1363		 */
1364		NDINIT(&nd, LOOKUP, FOLLOW, UIO_SYSSPACE, result, td);
1365		flags = FREAD;
1366		error = vn_open(&nd, &flags, 0);
1367		if (error == 0) {
1368			NDFREE(&nd, NDF_ONLY_PNBUF);
1369			type = nd.ni_vp->v_type;
1370			if (vap)
1371				VOP_GETATTR(nd.ni_vp, vap, td->td_ucred, td);
1372			VOP_UNLOCK(nd.ni_vp, 0, td);
1373			vn_close(nd.ni_vp, FREAD, td->td_ucred, td);
1374			if (type == VREG)
1375				return (result);
1376		}
1377	}
1378	free(result, M_LINKER);
1379	return (NULL);
1380}
1381
1382#define	INT_ALIGN(base, ptr)	ptr =					\
1383	(base) + (((ptr) - (base) + sizeof(int) - 1) & ~(sizeof(int) - 1))
1384
1385/*
1386 * Lookup KLD which contains requested module in the "linker.hints" file. If
1387 * version specification is available, then try to find the best KLD.
1388 * Otherwise just find the latest one.
1389 *
1390 * XXX: Vnode locking here is hosed; lock should be held for calls to
1391 * VOP_GETATTR() and vn_rdwr().
1392 */
1393static char *
1394linker_hints_lookup(const char *path, int pathlen, const char *modname,
1395    int modnamelen, struct mod_depend *verinfo)
1396{
1397	struct thread *td = curthread;	/* XXX */
1398	struct ucred *cred = td ? td->td_ucred : NULL;
1399	struct nameidata nd;
1400	struct vattr vattr, mattr;
1401	u_char *hints = NULL;
1402	u_char *cp, *recptr, *bufend, *result, *best, *pathbuf, *sep;
1403	int error, ival, bestver, *intp, reclen, found, flags, clen, blen;
1404
1405	result = NULL;
1406	bestver = found = 0;
1407
1408	sep = (path[pathlen - 1] != '/') ? "/" : "";
1409	reclen = imax(modnamelen, strlen(linker_hintfile)) + pathlen +
1410	    strlen(sep) + 1;
1411	pathbuf = malloc(reclen, M_LINKER, M_WAITOK);
1412	snprintf(pathbuf, reclen, "%.*s%s%s", pathlen, path, sep,
1413	    linker_hintfile);
1414
1415	NDINIT(&nd, LOOKUP, NOFOLLOW, UIO_SYSSPACE, pathbuf, td);
1416	flags = FREAD;
1417	error = vn_open(&nd, &flags, 0);
1418	if (error)
1419		goto bad;
1420	NDFREE(&nd, NDF_ONLY_PNBUF);
1421	VOP_UNLOCK(nd.ni_vp, 0, td);
1422	if (nd.ni_vp->v_type != VREG)
1423		goto bad;
1424	best = cp = NULL;
1425	error = VOP_GETATTR(nd.ni_vp, &vattr, cred, td);
1426	if (error)
1427		goto bad;
1428	/*
1429	 * XXX: we need to limit this number to some reasonable value
1430	 */
1431	if (vattr.va_size > 100 * 1024) {
1432		printf("hints file too large %ld\n", (long)vattr.va_size);
1433		goto bad;
1434	}
1435	hints = malloc(vattr.va_size, M_TEMP, M_WAITOK);
1436	if (hints == NULL)
1437		goto bad;
1438	error = vn_rdwr(UIO_READ, nd.ni_vp, (caddr_t)hints, vattr.va_size, 0,
1439	    UIO_SYSSPACE, IO_NODELOCKED, cred, &reclen, td);
1440	if (error)
1441		goto bad;
1442	vn_close(nd.ni_vp, FREAD, cred, td);
1443	nd.ni_vp = NULL;
1444	if (reclen != 0) {
1445		printf("can't read %d\n", reclen);
1446		goto bad;
1447	}
1448	intp = (int *)hints;
1449	ival = *intp++;
1450	if (ival != LINKER_HINTS_VERSION) {
1451		printf("hints file version mismatch %d\n", ival);
1452		goto bad;
1453	}
1454	bufend = hints + vattr.va_size;
1455	recptr = (u_char *)intp;
1456	clen = blen = 0;
1457	while (recptr < bufend && !found) {
1458		intp = (int *)recptr;
1459		reclen = *intp++;
1460		ival = *intp++;
1461		cp = (char *)intp;
1462		switch (ival) {
1463		case MDT_VERSION:
1464			clen = *cp++;
1465			if (clen != modnamelen || bcmp(cp, modname, clen) != 0)
1466				break;
1467			cp += clen;
1468			INT_ALIGN(hints, cp);
1469			ival = *(int *)cp;
1470			cp += sizeof(int);
1471			clen = *cp++;
1472			if (verinfo == NULL ||
1473			    ival == verinfo->md_ver_preferred) {
1474				found = 1;
1475				break;
1476			}
1477			if (ival >= verinfo->md_ver_minimum &&
1478			    ival <= verinfo->md_ver_maximum &&
1479			    ival > bestver) {
1480				bestver = ival;
1481				best = cp;
1482				blen = clen;
1483			}
1484			break;
1485		default:
1486			break;
1487		}
1488		recptr += reclen + sizeof(int);
1489	}
1490	/*
1491	 * Finally check if KLD is in the place
1492	 */
1493	if (found)
1494		result = linker_lookup_file(path, pathlen, cp, clen, &mattr);
1495	else if (best)
1496		result = linker_lookup_file(path, pathlen, best, blen, &mattr);
1497
1498	/*
1499	 * KLD is newer than hints file. What we should do now?
1500	 */
1501	if (result && timespeccmp(&mattr.va_mtime, &vattr.va_mtime, >))
1502		printf("warning: KLD '%s' is newer than the linker.hints"
1503		    " file\n", result);
1504bad:
1505	if (hints)
1506		free(hints, M_TEMP);
1507	if (nd.ni_vp != NULL)
1508		vn_close(nd.ni_vp, FREAD, cred, td);
1509	/*
1510	 * If nothing found or hints is absent - fallback to the old
1511	 * way by using "kldname[.ko]" as module name.
1512	 */
1513	if (!found && !bestver && result == NULL)
1514		result = linker_lookup_file(path, pathlen, modname,
1515		    modnamelen, NULL);
1516	return (result);
1517}
1518
1519/*
1520 * Lookup KLD which contains requested module in the all directories.
1521 */
1522static char *
1523linker_search_module(const char *modname, int modnamelen,
1524    struct mod_depend *verinfo)
1525{
1526	char *cp, *ep, *result;
1527
1528	/*
1529	 * traverse the linker path
1530	 */
1531	for (cp = linker_path; *cp; cp = ep + 1) {
1532		/* find the end of this component */
1533		for (ep = cp; (*ep != 0) && (*ep != ';'); ep++);
1534		result = linker_hints_lookup(cp, ep - cp, modname,
1535		    modnamelen, verinfo);
1536		if (result != NULL)
1537			return (result);
1538		if (*ep == 0)
1539			break;
1540	}
1541	return (NULL);
1542}
1543
1544/*
1545 * Search for module in all directories listed in the linker_path.
1546 */
1547static char *
1548linker_search_kld(const char *name)
1549{
1550	char *cp, *ep, *result, **cpp;
1551	int extlen, len;
1552
1553	/* qualified at all? */
1554	if (index(name, '/'))
1555		return (linker_strdup(name));
1556
1557	extlen = 0;
1558	for (cpp = linker_ext_list; *cpp; cpp++) {
1559		len = strlen(*cpp);
1560		if (len > extlen)
1561			extlen = len;
1562	}
1563	extlen++;		/* trailing '\0' */
1564
1565	/* traverse the linker path */
1566	len = strlen(name);
1567	for (ep = linker_path; *ep; ep++) {
1568		cp = ep;
1569		/* find the end of this component */
1570		for (; *ep != 0 && *ep != ';'; ep++);
1571		result = linker_lookup_file(cp, ep - cp, name, len, NULL);
1572		if (result != NULL)
1573			return (result);
1574	}
1575	return (NULL);
1576}
1577
1578static const char *
1579linker_basename(const char *path)
1580{
1581	const char *filename;
1582
1583	filename = rindex(path, '/');
1584	if (filename == NULL)
1585		return path;
1586	if (filename[1])
1587		filename++;
1588	return (filename);
1589}
1590
1591/*
1592 * Find a file which contains given module and load it, if "parent" is not
1593 * NULL, register a reference to it.
1594 */
1595static int
1596linker_load_module(const char *kldname, const char *modname,
1597    struct linker_file *parent, struct mod_depend *verinfo,
1598    struct linker_file **lfpp)
1599{
1600	linker_file_t lfdep;
1601	const char *filename;
1602	char *pathname;
1603	int error;
1604
1605	if (modname == NULL) {
1606		/*
1607 		 * We have to load KLD
1608 		 */
1609		KASSERT(verinfo == NULL, ("linker_load_module: verinfo"
1610		    " is not NULL"));
1611		pathname = linker_search_kld(kldname);
1612	} else {
1613		if (modlist_lookup2(modname, verinfo) != NULL)
1614			return (EEXIST);
1615		if (kldname == NULL)
1616			/*
1617			 * Need to find a KLD with required module
1618			 */
1619			pathname = linker_search_module(modname,
1620			    strlen(modname), verinfo);
1621		else
1622			pathname = linker_strdup(kldname);
1623	}
1624	if (pathname == NULL)
1625		return (ENOENT);
1626
1627	/*
1628	 * Can't load more than one file with the same basename XXX:
1629	 * Actually it should be possible to have multiple KLDs with
1630	 * the same basename but different path because they can
1631	 * provide different versions of the same modules.
1632	 */
1633	filename = linker_basename(pathname);
1634	if (linker_find_file_by_name(filename)) {
1635		error = EEXIST;
1636		goto out;
1637	}
1638	do {
1639		error = linker_load_file(pathname, &lfdep);
1640		if (error)
1641			break;
1642		if (modname && verinfo &&
1643		    modlist_lookup2(modname, verinfo) == NULL) {
1644			linker_file_unload(lfdep);
1645			error = ENOENT;
1646			break;
1647		}
1648		if (parent) {
1649			error = linker_file_add_dependency(parent, lfdep);
1650			if (error)
1651				break;
1652		}
1653		if (lfpp)
1654			*lfpp = lfdep;
1655	} while (0);
1656out:
1657	if (pathname)
1658		free(pathname, M_LINKER);
1659	return (error);
1660}
1661
1662/*
1663 * This routine is responsible for finding dependencies of userland initiated
1664 * kldload(2)'s of files.
1665 */
1666int
1667linker_load_dependencies(linker_file_t lf)
1668{
1669	linker_file_t lfdep;
1670	struct mod_metadata **start, **stop, **mdp, **nmdp;
1671	struct mod_metadata *mp, *nmp;
1672	struct mod_depend *verinfo;
1673	modlist_t mod;
1674	const char *modname, *nmodname;
1675	int ver, error = 0, count;
1676
1677	/*
1678	 * All files are dependant on /kernel.
1679	 */
1680	if (linker_kernel_file) {
1681		linker_kernel_file->refs++;
1682		error = linker_file_add_dependency(lf, linker_kernel_file);
1683		if (error)
1684			return (error);
1685	}
1686	if (linker_file_lookup_set(lf, MDT_SETNAME, &start, &stop,
1687	    &count) != 0)
1688		return (0);
1689	for (mdp = start; mdp < stop; mdp++) {
1690		mp = linker_reloc_ptr(lf, *mdp);
1691		if (mp->md_type != MDT_VERSION)
1692			continue;
1693		linker_mdt_version(lf, mp, &modname, &ver);
1694		mod = modlist_lookup(modname, ver);
1695		if (mod != NULL) {
1696			printf("interface %s.%d already present in the KLD"
1697			    " '%s'!\n", modname, ver,
1698			    mod->container->filename);
1699			return (EEXIST);
1700		}
1701	}
1702
1703	for (mdp = start; mdp < stop; mdp++) {
1704		mp = linker_reloc_ptr(lf, *mdp);
1705		if (mp->md_type != MDT_DEPEND)
1706			continue;
1707		linker_mdt_depend(lf, mp, &modname, &verinfo);
1708		nmodname = NULL;
1709		for (nmdp = start; nmdp < stop; nmdp++) {
1710			nmp = linker_reloc_ptr(lf, *nmdp);
1711			if (nmp->md_type != MDT_VERSION)
1712				continue;
1713			nmodname = linker_reloc_ptr(lf, nmp->md_cval);
1714			if (strcmp(modname, nmodname) == 0)
1715				break;
1716		}
1717		if (nmdp < stop)/* early exit, it's a self reference */
1718			continue;
1719		mod = modlist_lookup2(modname, verinfo);
1720		if (mod) {	/* woohoo, it's loaded already */
1721			lfdep = mod->container;
1722			lfdep->refs++;
1723			error = linker_file_add_dependency(lf, lfdep);
1724			if (error)
1725				break;
1726			continue;
1727		}
1728		error = linker_load_module(NULL, modname, lf, verinfo, NULL);
1729		if (error) {
1730			printf("KLD %s: depends on %s - not available\n",
1731			    lf->filename, modname);
1732			break;
1733		}
1734	}
1735
1736	if (error)
1737		return (error);
1738	linker_addmodules(lf, start, stop, 0);
1739	return (error);
1740}
1741
1742static int
1743sysctl_kern_function_list_iterate(const char *name, void *opaque)
1744{
1745	struct sysctl_req *req;
1746
1747	req = opaque;
1748	return (SYSCTL_OUT(req, name, strlen(name) + 1));
1749}
1750
1751/*
1752 * Export a nul-separated, double-nul-terminated list of all function names
1753 * in the kernel.
1754 */
1755static int
1756sysctl_kern_function_list(SYSCTL_HANDLER_ARGS)
1757{
1758	linker_file_t lf;
1759	int error;
1760
1761	TAILQ_FOREACH(lf, &linker_files, link) {
1762		error = LINKER_EACH_FUNCTION_NAME(lf,
1763		    sysctl_kern_function_list_iterate, req);
1764		if (error)
1765			return (error);
1766	}
1767	return (SYSCTL_OUT(req, "", 1));
1768}
1769
1770SYSCTL_PROC(_kern, OID_AUTO, function_list, CTLFLAG_RD,
1771    NULL, 0, sysctl_kern_function_list, "", "kernel function list");
1772