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