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