kern_linker.c revision 159797
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 159797 2006-06-20 20:37:17Z 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
452int
453linker_file_foreach(linker_predicate_t *predicate, void *context)
454{
455	linker_file_t lf;
456	int retval = 0;
457
458	mtx_lock(&Giant);
459	TAILQ_FOREACH(lf, &linker_files, link) {
460		retval = predicate(lf, context);
461		if (retval != 0)
462			break;
463	}
464	mtx_unlock(&Giant);
465	return (retval);
466}
467
468linker_file_t
469linker_make_file(const char *pathname, linker_class_t lc)
470{
471	linker_file_t lf;
472	const char *filename;
473
474	filename = linker_basename(pathname);
475
476	KLD_DPF(FILE, ("linker_make_file: new file, filename=%s\n", filename));
477	lf = (linker_file_t)kobj_create((kobj_class_t)lc, M_LINKER, M_WAITOK);
478	if (lf == NULL)
479		return (NULL);
480	lf->refs = 1;
481	lf->userrefs = 0;
482	lf->flags = 0;
483	lf->filename = linker_strdup(filename);
484	LINKER_GET_NEXT_FILE_ID(lf->id);
485	lf->ndeps = 0;
486	lf->deps = NULL;
487	STAILQ_INIT(&lf->common);
488	TAILQ_INIT(&lf->modules);
489	mtx_lock(&kld_mtx);
490	TAILQ_INSERT_TAIL(&linker_files, lf, link);
491	mtx_unlock(&kld_mtx);
492	return (lf);
493}
494
495int
496linker_file_unload(linker_file_t file, int flags)
497{
498	module_t mod, next;
499	modlist_t ml, nextml;
500	struct common_symbol *cp;
501	int error, i;
502
503	/* Refuse to unload modules if securelevel raised. */
504	if (securelevel > 0)
505		return (EPERM);
506#ifdef MAC
507	error = mac_check_kld_unload(curthread->td_ucred);
508	if (error)
509		return (error);
510#endif
511
512	KLD_DPF(FILE, ("linker_file_unload: lf->refs=%d\n", file->refs));
513
514	/* Easy case of just dropping a reference. */
515	if (file->refs > 1) {
516		file->refs--;
517		return (0);
518	}
519
520	KLD_DPF(FILE, ("linker_file_unload: file is unloading,"
521	    " informing modules\n"));
522
523	/*
524	 * Inform any modules associated with this file.
525	 */
526	MOD_XLOCK;
527	for (mod = TAILQ_FIRST(&file->modules); mod; mod = next) {
528		next = module_getfnext(mod);
529		MOD_XUNLOCK;
530
531		/*
532		 * Give the module a chance to veto the unload.
533		 */
534		if ((error = module_unload(mod, flags)) != 0) {
535			KLD_DPF(FILE, ("linker_file_unload: module %p"
536			    " vetoes unload\n", mod));
537			return (error);
538		}
539		MOD_XLOCK;
540		module_release(mod);
541	}
542	MOD_XUNLOCK;
543
544	TAILQ_FOREACH_SAFE(ml, &found_modules, link, nextml) {
545		if (ml->container == file) {
546			TAILQ_REMOVE(&found_modules, ml, link);
547			free(ml, M_LINKER);
548		}
549	}
550
551	/*
552	 * Don't try to run SYSUNINITs if we are unloaded due to a
553	 * link error.
554	 */
555	if (file->flags & LINKER_FILE_LINKED) {
556		linker_file_sysuninit(file);
557		linker_file_unregister_sysctls(file);
558	}
559	mtx_lock(&kld_mtx);
560	TAILQ_REMOVE(&linker_files, file, link);
561	mtx_unlock(&kld_mtx);
562
563	if (file->deps) {
564		for (i = 0; i < file->ndeps; i++)
565			linker_file_unload(file->deps[i], flags);
566		free(file->deps, M_LINKER);
567		file->deps = NULL;
568	}
569	for (cp = STAILQ_FIRST(&file->common); cp;
570	    cp = STAILQ_FIRST(&file->common)) {
571		STAILQ_REMOVE(&file->common, cp, common_symbol, link);
572		free(cp, M_LINKER);
573	}
574
575	LINKER_UNLOAD(file);
576	if (file->filename) {
577		free(file->filename, M_LINKER);
578		file->filename = NULL;
579	}
580	kobj_delete((kobj_t) file, M_LINKER);
581	return (0);
582}
583
584static int
585linker_file_add_dependency(linker_file_t file, linker_file_t dep)
586{
587	linker_file_t *newdeps;
588
589	newdeps = malloc((file->ndeps + 1) * sizeof(linker_file_t *),
590	    M_LINKER, M_WAITOK | M_ZERO);
591	if (newdeps == NULL)
592		return (ENOMEM);
593
594	if (file->deps) {
595		bcopy(file->deps, newdeps,
596		    file->ndeps * sizeof(linker_file_t *));
597		free(file->deps, M_LINKER);
598	}
599	file->deps = newdeps;
600	file->deps[file->ndeps] = dep;
601	file->ndeps++;
602	return (0);
603}
604
605/*
606 * Locate a linker set and its contents.  This is a helper function to avoid
607 * linker_if.h exposure elsewhere.  Note: firstp and lastp are really void ***
608 */
609int
610linker_file_lookup_set(linker_file_t file, const char *name,
611    void *firstp, void *lastp, int *countp)
612{
613
614	return (LINKER_LOOKUP_SET(file, name, firstp, lastp, countp));
615}
616
617caddr_t
618linker_file_lookup_symbol(linker_file_t file, const char *name, int deps)
619{
620	c_linker_sym_t sym;
621	linker_symval_t symval;
622	caddr_t address;
623	size_t common_size = 0;
624	int i;
625
626	KLD_DPF(SYM, ("linker_file_lookup_symbol: file=%p, name=%s, deps=%d\n",
627	    file, name, deps));
628
629	if (LINKER_LOOKUP_SYMBOL(file, name, &sym) == 0) {
630		LINKER_SYMBOL_VALUES(file, sym, &symval);
631		if (symval.value == 0)
632			/*
633			 * For commons, first look them up in the
634			 * dependencies and only allocate space if not found
635			 * there.
636			 */
637			common_size = symval.size;
638		else {
639			KLD_DPF(SYM, ("linker_file_lookup_symbol: symbol"
640			    ".value=%p\n", symval.value));
641			return (symval.value);
642		}
643	}
644	if (deps) {
645		for (i = 0; i < file->ndeps; i++) {
646			address = linker_file_lookup_symbol(file->deps[i],
647			    name, 0);
648			if (address) {
649				KLD_DPF(SYM, ("linker_file_lookup_symbol:"
650				    " deps value=%p\n", address));
651				return (address);
652			}
653		}
654	}
655	if (common_size > 0) {
656		/*
657		 * This is a common symbol which was not found in the
658		 * dependencies.  We maintain a simple common symbol table in
659		 * the file object.
660		 */
661		struct common_symbol *cp;
662
663		STAILQ_FOREACH(cp, &file->common, link) {
664			if (strcmp(cp->name, name) == 0) {
665				KLD_DPF(SYM, ("linker_file_lookup_symbol:"
666				    " old common value=%p\n", cp->address));
667				return (cp->address);
668			}
669		}
670		/*
671		 * Round the symbol size up to align.
672		 */
673		common_size = (common_size + sizeof(int) - 1) & -sizeof(int);
674		cp = malloc(sizeof(struct common_symbol)
675		    + common_size + strlen(name) + 1, M_LINKER,
676		    M_WAITOK | M_ZERO);
677		cp->address = (caddr_t)(cp + 1);
678		cp->name = cp->address + common_size;
679		strcpy(cp->name, name);
680		bzero(cp->address, common_size);
681		STAILQ_INSERT_TAIL(&file->common, cp, link);
682
683		KLD_DPF(SYM, ("linker_file_lookup_symbol: new common"
684		    " value=%p\n", cp->address));
685		return (cp->address);
686	}
687	KLD_DPF(SYM, ("linker_file_lookup_symbol: fail\n"));
688	return (0);
689}
690
691#ifdef DDB
692/*
693 * DDB Helpers.  DDB has to look across multiple files with their own symbol
694 * tables and string tables.
695 *
696 * Note that we do not obey list locking protocols here.  We really don't need
697 * DDB to hang because somebody's got the lock held.  We'll take the chance
698 * that the files list is inconsistant instead.
699 */
700
701int
702linker_ddb_lookup(const char *symstr, c_linker_sym_t *sym)
703{
704	linker_file_t lf;
705
706	TAILQ_FOREACH(lf, &linker_files, link) {
707		if (LINKER_LOOKUP_SYMBOL(lf, symstr, sym) == 0)
708			return (0);
709	}
710	return (ENOENT);
711}
712
713int
714linker_ddb_search_symbol(caddr_t value, c_linker_sym_t *sym, long *diffp)
715{
716	linker_file_t lf;
717	c_linker_sym_t best, es;
718	u_long diff, bestdiff, off;
719
720	best = 0;
721	off = (uintptr_t)value;
722	bestdiff = off;
723	TAILQ_FOREACH(lf, &linker_files, link) {
724		if (LINKER_SEARCH_SYMBOL(lf, value, &es, &diff) != 0)
725			continue;
726		if (es != 0 && diff < bestdiff) {
727			best = es;
728			bestdiff = diff;
729		}
730		if (bestdiff == 0)
731			break;
732	}
733	if (best) {
734		*sym = best;
735		*diffp = bestdiff;
736		return (0);
737	} else {
738		*sym = 0;
739		*diffp = off;
740		return (ENOENT);
741	}
742}
743
744int
745linker_ddb_symbol_values(c_linker_sym_t sym, linker_symval_t *symval)
746{
747	linker_file_t lf;
748
749	TAILQ_FOREACH(lf, &linker_files, link) {
750		if (LINKER_SYMBOL_VALUES(lf, sym, symval) == 0)
751			return (0);
752	}
753	return (ENOENT);
754}
755#endif
756
757/*
758 * Syscalls.
759 */
760/*
761 * MPSAFE
762 */
763int
764kern_kldload(struct thread *td, const char *file, int *fileid)
765{
766#ifdef HWPMC_HOOKS
767	struct pmckern_map_in pkm;
768#endif
769	const char *kldname, *modname;
770	linker_file_t lf;
771	int error;
772
773	if ((error = securelevel_gt(td->td_ucred, 0)) != 0)
774		return (error);
775
776	if ((error = suser(td)) != 0)
777		return (error);
778
779	/*
780	 * If file does not contain qualified name or any dot in it
781	 * (kldname.ko, or kldname.ver.ko) treat it as interface
782	 * name.
783	 */
784	if (index(file, '/') || index(file, '.')) {
785		kldname = file;
786		modname = NULL;
787	} else {
788		kldname = NULL;
789		modname = file;
790	}
791
792	mtx_lock(&Giant);
793	error = linker_load_module(kldname, modname, NULL, NULL, &lf);
794	if (error)
795		goto unlock;
796
797#ifdef HWPMC_HOOKS
798	pkm.pm_file = lf->filename;
799	pkm.pm_address = (uintptr_t) lf->address;
800	PMC_CALL_HOOK(td, PMC_FN_KLD_LOAD, (void *) &pkm);
801#endif
802	lf->userrefs++;
803	if (fileid != NULL)
804		*fileid = lf->id;
805unlock:
806	mtx_unlock(&Giant);
807	return (error);
808}
809
810int
811kldload(struct thread *td, struct kldload_args *uap)
812{
813	char *pathname = NULL;
814	int error, fileid;
815
816	td->td_retval[0] = -1;
817
818	pathname = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
819	error = copyinstr(uap->file, pathname, MAXPATHLEN, NULL);
820	if (error == 0) {
821		error = kern_kldload(td, pathname, &fileid);
822		if (error == 0)
823			td->td_retval[0] = fileid;
824	}
825	free(pathname, M_TEMP);
826	return (error);
827}
828
829/*
830 * MPSAFE
831 */
832int
833kern_kldunload(struct thread *td, int fileid, int flags)
834{
835#ifdef HWPMC_HOOKS
836	struct pmckern_map_out pkm;
837#endif
838	linker_file_t lf;
839	int error = 0;
840
841	if ((error = securelevel_gt(td->td_ucred, 0)) != 0)
842		return (error);
843
844	if ((error = suser(td)) != 0)
845		return (error);
846
847	mtx_lock(&Giant);
848	lf = linker_find_file_by_id(fileid);
849	if (lf) {
850		KLD_DPF(FILE, ("kldunload: lf->userrefs=%d\n", lf->userrefs));
851		if (lf->userrefs == 0) {
852			/*
853			 * XXX: maybe LINKER_UNLOAD_FORCE should override ?
854			 */
855			printf("kldunload: attempt to unload file that was"
856			    " loaded by the kernel\n");
857			error = EBUSY;
858		} else {
859#ifdef HWPMC_HOOKS
860			/* Save data needed by hwpmc(4) before unloading. */
861			pkm.pm_address = (uintptr_t) lf->address;
862			pkm.pm_size = lf->size;
863#endif
864			lf->userrefs--;
865			error = linker_file_unload(lf, flags);
866			if (error)
867				lf->userrefs++;
868		}
869	} else
870		error = ENOENT;
871
872#ifdef HWPMC_HOOKS
873	if (error == 0)
874		PMC_CALL_HOOK(td, PMC_FN_KLD_UNLOAD, (void *) &pkm);
875#endif
876	mtx_unlock(&Giant);
877	return (error);
878}
879
880/*
881 * MPSAFE
882 */
883int
884kldunload(struct thread *td, struct kldunload_args *uap)
885{
886
887	return (kern_kldunload(td, uap->fileid, LINKER_UNLOAD_NORMAL));
888}
889
890/*
891 * MPSAFE
892 */
893int
894kldunloadf(struct thread *td, struct kldunloadf_args *uap)
895{
896
897	if (uap->flags != LINKER_UNLOAD_NORMAL &&
898	    uap->flags != LINKER_UNLOAD_FORCE)
899		return (EINVAL);
900	return (kern_kldunload(td, uap->fileid, uap->flags));
901}
902
903/*
904 * MPSAFE
905 */
906int
907kldfind(struct thread *td, struct kldfind_args *uap)
908{
909	char *pathname;
910	const char *filename;
911	linker_file_t lf;
912	int error;
913
914#ifdef MAC
915	error = mac_check_kld_stat(td->td_ucred);
916	if (error)
917		return (error);
918#endif
919
920	mtx_lock(&Giant);
921	td->td_retval[0] = -1;
922
923	pathname = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
924	if ((error = copyinstr(uap->file, pathname, MAXPATHLEN, NULL)) != 0)
925		goto out;
926
927	filename = linker_basename(pathname);
928	lf = linker_find_file_by_name(filename);
929	if (lf)
930		td->td_retval[0] = lf->id;
931	else
932		error = ENOENT;
933out:
934	free(pathname, M_TEMP);
935	mtx_unlock(&Giant);
936	return (error);
937}
938
939/*
940 * MPSAFE
941 */
942int
943kldnext(struct thread *td, struct kldnext_args *uap)
944{
945	linker_file_t lf;
946	int error = 0;
947
948#ifdef MAC
949	error = mac_check_kld_stat(td->td_ucred);
950	if (error)
951		return (error);
952#endif
953
954	mtx_lock(&Giant);
955
956	if (uap->fileid == 0) {
957		mtx_lock(&kld_mtx);
958		if (TAILQ_FIRST(&linker_files))
959			td->td_retval[0] = TAILQ_FIRST(&linker_files)->id;
960		else
961			td->td_retval[0] = 0;
962		mtx_unlock(&kld_mtx);
963		goto out;
964	}
965	lf = linker_find_file_by_id(uap->fileid);
966	if (lf) {
967		if (TAILQ_NEXT(lf, link))
968			td->td_retval[0] = TAILQ_NEXT(lf, link)->id;
969		else
970			td->td_retval[0] = 0;
971	} else
972		error = ENOENT;
973out:
974	mtx_unlock(&Giant);
975	return (error);
976}
977
978/*
979 * MPSAFE
980 */
981int
982kldstat(struct thread *td, struct kldstat_args *uap)
983{
984	struct kld_file_stat stat;
985	linker_file_t lf;
986	int error, namelen;
987
988	/*
989	 * Check the version of the user's structure.
990	 */
991	error = copyin(uap->stat, &stat, sizeof(struct kld_file_stat));
992	if (error)
993		return (error);
994	if (stat.version != sizeof(struct kld_file_stat))
995		return (EINVAL);
996
997#ifdef MAC
998	error = mac_check_kld_stat(td->td_ucred);
999	if (error)
1000		return (error);
1001#endif
1002
1003	mtx_lock(&Giant);
1004
1005	lf = linker_find_file_by_id(uap->fileid);
1006	if (lf == NULL) {
1007		mtx_unlock(&Giant);
1008		return (ENOENT);
1009	}
1010
1011	namelen = strlen(lf->filename) + 1;
1012	if (namelen > MAXPATHLEN)
1013		namelen = MAXPATHLEN;
1014	bcopy(lf->filename, &stat.name[0], namelen);
1015	stat.refs = lf->refs;
1016	stat.id = lf->id;
1017	stat.address = lf->address;
1018	stat.size = lf->size;
1019	mtx_unlock(&Giant);
1020
1021	td->td_retval[0] = 0;
1022
1023	return (copyout(&stat, uap->stat, sizeof(struct kld_file_stat)));
1024}
1025
1026/*
1027 * MPSAFE
1028 */
1029int
1030kldfirstmod(struct thread *td, struct kldfirstmod_args *uap)
1031{
1032	linker_file_t lf;
1033	module_t mp;
1034	int error = 0;
1035
1036#ifdef MAC
1037	error = mac_check_kld_stat(td->td_ucred);
1038	if (error)
1039		return (error);
1040#endif
1041
1042	mtx_lock(&Giant);
1043	lf = linker_find_file_by_id(uap->fileid);
1044	if (lf) {
1045		MOD_SLOCK;
1046		mp = TAILQ_FIRST(&lf->modules);
1047		if (mp != NULL)
1048			td->td_retval[0] = module_getid(mp);
1049		else
1050			td->td_retval[0] = 0;
1051		MOD_SUNLOCK;
1052	} else
1053		error = ENOENT;
1054	mtx_unlock(&Giant);
1055	return (error);
1056}
1057
1058/*
1059 * MPSAFE
1060 */
1061int
1062kldsym(struct thread *td, struct kldsym_args *uap)
1063{
1064	char *symstr = NULL;
1065	c_linker_sym_t sym;
1066	linker_symval_t symval;
1067	linker_file_t lf;
1068	struct kld_sym_lookup lookup;
1069	int error = 0;
1070
1071#ifdef MAC
1072	error = mac_check_kld_stat(td->td_ucred);
1073	if (error)
1074		return (error);
1075#endif
1076
1077	mtx_lock(&Giant);
1078
1079	if ((error = copyin(uap->data, &lookup, sizeof(lookup))) != 0)
1080		goto out;
1081	if (lookup.version != sizeof(lookup) ||
1082	    uap->cmd != KLDSYM_LOOKUP) {
1083		error = EINVAL;
1084		goto out;
1085	}
1086	symstr = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
1087	if ((error = copyinstr(lookup.symname, symstr, MAXPATHLEN, NULL)) != 0)
1088		goto out;
1089	if (uap->fileid != 0) {
1090		lf = linker_find_file_by_id(uap->fileid);
1091		if (lf == NULL) {
1092			error = ENOENT;
1093			goto out;
1094		}
1095		if (LINKER_LOOKUP_SYMBOL(lf, symstr, &sym) == 0 &&
1096		    LINKER_SYMBOL_VALUES(lf, sym, &symval) == 0) {
1097			lookup.symvalue = (uintptr_t) symval.value;
1098			lookup.symsize = symval.size;
1099			error = copyout(&lookup, uap->data, sizeof(lookup));
1100		} else
1101			error = ENOENT;
1102	} else {
1103		mtx_lock(&kld_mtx);
1104		TAILQ_FOREACH(lf, &linker_files, link) {
1105			if (LINKER_LOOKUP_SYMBOL(lf, symstr, &sym) == 0 &&
1106			    LINKER_SYMBOL_VALUES(lf, sym, &symval) == 0) {
1107				lookup.symvalue = (uintptr_t)symval.value;
1108				lookup.symsize = symval.size;
1109				error = copyout(&lookup, uap->data,
1110				    sizeof(lookup));
1111				break;
1112			}
1113		}
1114		mtx_unlock(&kld_mtx);
1115		if (lf == NULL)
1116			error = ENOENT;
1117	}
1118out:
1119	if (symstr)
1120		free(symstr, M_TEMP);
1121	mtx_unlock(&Giant);
1122	return (error);
1123}
1124
1125/*
1126 * Preloaded module support
1127 */
1128
1129static modlist_t
1130modlist_lookup(const char *name, int ver)
1131{
1132	modlist_t mod;
1133
1134	TAILQ_FOREACH(mod, &found_modules, link) {
1135		if (strcmp(mod->name, name) == 0 &&
1136		    (ver == 0 || mod->version == ver))
1137			return (mod);
1138	}
1139	return (NULL);
1140}
1141
1142static modlist_t
1143modlist_lookup2(const char *name, struct mod_depend *verinfo)
1144{
1145	modlist_t mod, bestmod;
1146	int ver;
1147
1148	if (verinfo == NULL)
1149		return (modlist_lookup(name, 0));
1150	bestmod = NULL;
1151	TAILQ_FOREACH(mod, &found_modules, link) {
1152		if (strcmp(mod->name, name) != 0)
1153			continue;
1154		ver = mod->version;
1155		if (ver == verinfo->md_ver_preferred)
1156			return (mod);
1157		if (ver >= verinfo->md_ver_minimum &&
1158		    ver <= verinfo->md_ver_maximum &&
1159		    (bestmod == NULL || ver > bestmod->version))
1160			bestmod = mod;
1161	}
1162	return (bestmod);
1163}
1164
1165static modlist_t
1166modlist_newmodule(const char *modname, int version, linker_file_t container)
1167{
1168	modlist_t mod;
1169
1170	mod = malloc(sizeof(struct modlist), M_LINKER, M_NOWAIT | M_ZERO);
1171	if (mod == NULL)
1172		panic("no memory for module list");
1173	mod->container = container;
1174	mod->name = modname;
1175	mod->version = version;
1176	TAILQ_INSERT_TAIL(&found_modules, mod, link);
1177	return (mod);
1178}
1179
1180static void
1181linker_addmodules(linker_file_t lf, struct mod_metadata **start,
1182    struct mod_metadata **stop, int preload)
1183{
1184	struct mod_metadata *mp, **mdp;
1185	const char *modname;
1186	int ver;
1187
1188	for (mdp = start; mdp < stop; mdp++) {
1189		mp = *mdp;
1190		if (mp->md_type != MDT_VERSION)
1191			continue;
1192		modname = mp->md_cval;
1193		ver = ((struct mod_version *)mp->md_data)->mv_version;
1194		if (modlist_lookup(modname, ver) != NULL) {
1195			printf("module %s already present!\n", modname);
1196			/* XXX what can we do? this is a build error. :-( */
1197			continue;
1198		}
1199		modlist_newmodule(modname, ver, lf);
1200	}
1201}
1202
1203static void
1204linker_preload(void *arg)
1205{
1206	caddr_t modptr;
1207	const char *modname, *nmodname;
1208	char *modtype;
1209	linker_file_t lf;
1210	linker_class_t lc;
1211	int error;
1212	linker_file_list_t loaded_files;
1213	linker_file_list_t depended_files;
1214	struct mod_metadata *mp, *nmp;
1215	struct mod_metadata **start, **stop, **mdp, **nmdp;
1216	struct mod_depend *verinfo;
1217	int nver;
1218	int resolves;
1219	modlist_t mod;
1220	struct sysinit **si_start, **si_stop;
1221
1222	TAILQ_INIT(&loaded_files);
1223	TAILQ_INIT(&depended_files);
1224	TAILQ_INIT(&found_modules);
1225	error = 0;
1226
1227	modptr = NULL;
1228	while ((modptr = preload_search_next_name(modptr)) != NULL) {
1229		modname = (char *)preload_search_info(modptr, MODINFO_NAME);
1230		modtype = (char *)preload_search_info(modptr, MODINFO_TYPE);
1231		if (modname == NULL) {
1232			printf("Preloaded module at %p does not have a"
1233			    " name!\n", modptr);
1234			continue;
1235		}
1236		if (modtype == NULL) {
1237			printf("Preloaded module at %p does not have a type!\n",
1238			    modptr);
1239			continue;
1240		}
1241		if (bootverbose)
1242			printf("Preloaded %s \"%s\" at %p.\n", modtype, modname,
1243			    modptr);
1244		lf = NULL;
1245		TAILQ_FOREACH(lc, &classes, link) {
1246			error = LINKER_LINK_PRELOAD(lc, modname, &lf);
1247			if (!error)
1248				break;
1249			lf = NULL;
1250		}
1251		if (lf)
1252			TAILQ_INSERT_TAIL(&loaded_files, lf, loaded);
1253	}
1254
1255	/*
1256	 * First get a list of stuff in the kernel.
1257	 */
1258	if (linker_file_lookup_set(linker_kernel_file, MDT_SETNAME, &start,
1259	    &stop, NULL) == 0)
1260		linker_addmodules(linker_kernel_file, start, stop, 1);
1261
1262	/*
1263	 * this is a once-off kinky bubble sort resolve relocation dependency
1264	 * requirements
1265	 */
1266restart:
1267	TAILQ_FOREACH(lf, &loaded_files, loaded) {
1268		error = linker_file_lookup_set(lf, MDT_SETNAME, &start,
1269		    &stop, NULL);
1270		/*
1271		 * First, look to see if we would successfully link with this
1272		 * stuff.
1273		 */
1274		resolves = 1;	/* unless we know otherwise */
1275		if (!error) {
1276			for (mdp = start; mdp < stop; mdp++) {
1277				mp = *mdp;
1278				if (mp->md_type != MDT_DEPEND)
1279					continue;
1280				modname = mp->md_cval;
1281				verinfo = mp->md_data;
1282				for (nmdp = start; nmdp < stop; nmdp++) {
1283					nmp = *nmdp;
1284					if (nmp->md_type != MDT_VERSION)
1285						continue;
1286					nmodname = nmp->md_cval;
1287					if (strcmp(modname, nmodname) == 0)
1288						break;
1289				}
1290				if (nmdp < stop)   /* it's a self reference */
1291					continue;
1292
1293				/*
1294				 * ok, the module isn't here yet, we
1295				 * are not finished
1296				 */
1297				if (modlist_lookup2(modname, verinfo) == NULL)
1298					resolves = 0;
1299			}
1300		}
1301		/*
1302		 * OK, if we found our modules, we can link.  So, "provide"
1303		 * the modules inside and add it to the end of the link order
1304		 * list.
1305		 */
1306		if (resolves) {
1307			if (!error) {
1308				for (mdp = start; mdp < stop; mdp++) {
1309					mp = *mdp;
1310					if (mp->md_type != MDT_VERSION)
1311						continue;
1312					modname = mp->md_cval;
1313					nver = ((struct mod_version *)
1314					    mp->md_data)->mv_version;
1315					if (modlist_lookup(modname,
1316					    nver) != NULL) {
1317						printf("module %s already"
1318						    " present!\n", modname);
1319						linker_file_unload(lf,
1320						    LINKER_UNLOAD_FORCE);
1321						TAILQ_REMOVE(&loaded_files,
1322						    lf, loaded);
1323						/* we changed tailq next ptr */
1324						goto restart;
1325					}
1326					modlist_newmodule(modname, nver, lf);
1327				}
1328			}
1329			TAILQ_REMOVE(&loaded_files, lf, loaded);
1330			TAILQ_INSERT_TAIL(&depended_files, lf, loaded);
1331			/*
1332			 * Since we provided modules, we need to restart the
1333			 * sort so that the previous files that depend on us
1334			 * have a chance. Also, we've busted the tailq next
1335			 * pointer with the REMOVE.
1336			 */
1337			goto restart;
1338		}
1339	}
1340
1341	/*
1342	 * At this point, we check to see what could not be resolved..
1343	 */
1344	TAILQ_FOREACH(lf, &loaded_files, loaded) {
1345		printf("KLD file %s is missing dependencies\n", lf->filename);
1346		linker_file_unload(lf, LINKER_UNLOAD_FORCE);
1347		TAILQ_REMOVE(&loaded_files, lf, loaded);
1348	}
1349
1350	/*
1351	 * We made it. Finish off the linking in the order we determined.
1352	 */
1353	TAILQ_FOREACH(lf, &depended_files, loaded) {
1354		if (linker_kernel_file) {
1355			linker_kernel_file->refs++;
1356			error = linker_file_add_dependency(lf,
1357			    linker_kernel_file);
1358			if (error)
1359				panic("cannot add dependency");
1360		}
1361		lf->userrefs++;	/* so we can (try to) kldunload it */
1362		error = linker_file_lookup_set(lf, MDT_SETNAME, &start,
1363		    &stop, NULL);
1364		if (!error) {
1365			for (mdp = start; mdp < stop; mdp++) {
1366				mp = *mdp;
1367				if (mp->md_type != MDT_DEPEND)
1368					continue;
1369				modname = mp->md_cval;
1370				verinfo = mp->md_data;
1371				mod = modlist_lookup2(modname, verinfo);
1372				/* Don't count self-dependencies */
1373				if (lf == mod->container)
1374					continue;
1375				mod->container->refs++;
1376				error = linker_file_add_dependency(lf,
1377				    mod->container);
1378				if (error)
1379					panic("cannot add dependency");
1380			}
1381		}
1382		/*
1383		 * Now do relocation etc using the symbol search paths
1384		 * established by the dependencies
1385		 */
1386		error = LINKER_LINK_PRELOAD_FINISH(lf);
1387		if (error) {
1388			printf("KLD file %s - could not finalize loading\n",
1389			    lf->filename);
1390			linker_file_unload(lf, LINKER_UNLOAD_FORCE);
1391			continue;
1392		}
1393		linker_file_register_modules(lf);
1394		if (linker_file_lookup_set(lf, "sysinit_set", &si_start,
1395		    &si_stop, NULL) == 0)
1396			sysinit_add(si_start, si_stop);
1397		linker_file_register_sysctls(lf);
1398		lf->flags |= LINKER_FILE_LINKED;
1399	}
1400	/* woohoo! we made it! */
1401}
1402
1403SYSINIT(preload, SI_SUB_KLD, SI_ORDER_MIDDLE, linker_preload, 0)
1404
1405/*
1406 * Search for a not-loaded module by name.
1407 *
1408 * Modules may be found in the following locations:
1409 *
1410 * - preloaded (result is just the module name) - on disk (result is full path
1411 * to module)
1412 *
1413 * If the module name is qualified in any way (contains path, etc.) the we
1414 * simply return a copy of it.
1415 *
1416 * The search path can be manipulated via sysctl.  Note that we use the ';'
1417 * character as a separator to be consistent with the bootloader.
1418 */
1419
1420static char linker_hintfile[] = "linker.hints";
1421static char linker_path[MAXPATHLEN] = "/boot/kernel;/boot/modules";
1422
1423SYSCTL_STRING(_kern, OID_AUTO, module_path, CTLFLAG_RW, linker_path,
1424    sizeof(linker_path), "module load search path");
1425
1426TUNABLE_STR("module_path", linker_path, sizeof(linker_path));
1427
1428static char *linker_ext_list[] = {
1429	"",
1430	".ko",
1431	NULL
1432};
1433
1434/*
1435 * Check if file actually exists either with or without extension listed in
1436 * the linker_ext_list. (probably should be generic for the rest of the
1437 * kernel)
1438 */
1439static char *
1440linker_lookup_file(const char *path, int pathlen, const char *name,
1441    int namelen, struct vattr *vap)
1442{
1443	struct nameidata nd;
1444	struct thread *td = curthread;	/* XXX */
1445	char *result, **cpp, *sep;
1446	int error, len, extlen, reclen, flags;
1447	enum vtype type;
1448
1449	extlen = 0;
1450	for (cpp = linker_ext_list; *cpp; cpp++) {
1451		len = strlen(*cpp);
1452		if (len > extlen)
1453			extlen = len;
1454	}
1455	extlen++;		/* trailing '\0' */
1456	sep = (path[pathlen - 1] != '/') ? "/" : "";
1457
1458	reclen = pathlen + strlen(sep) + namelen + extlen + 1;
1459	result = malloc(reclen, M_LINKER, M_WAITOK);
1460	for (cpp = linker_ext_list; *cpp; cpp++) {
1461		snprintf(result, reclen, "%.*s%s%.*s%s", pathlen, path, sep,
1462		    namelen, name, *cpp);
1463		/*
1464		 * Attempt to open the file, and return the path if
1465		 * we succeed and it's a regular file.
1466		 */
1467		NDINIT(&nd, LOOKUP, FOLLOW, UIO_SYSSPACE, result, td);
1468		flags = FREAD;
1469		error = vn_open(&nd, &flags, 0, -1);
1470		if (error == 0) {
1471			NDFREE(&nd, NDF_ONLY_PNBUF);
1472			type = nd.ni_vp->v_type;
1473			if (vap)
1474				VOP_GETATTR(nd.ni_vp, vap, td->td_ucred, td);
1475			VOP_UNLOCK(nd.ni_vp, 0, td);
1476			vn_close(nd.ni_vp, FREAD, td->td_ucred, td);
1477			if (type == VREG)
1478				return (result);
1479		}
1480	}
1481	free(result, M_LINKER);
1482	return (NULL);
1483}
1484
1485#define	INT_ALIGN(base, ptr)	ptr =					\
1486	(base) + (((ptr) - (base) + sizeof(int) - 1) & ~(sizeof(int) - 1))
1487
1488/*
1489 * Lookup KLD which contains requested module in the "linker.hints" file. If
1490 * version specification is available, then try to find the best KLD.
1491 * Otherwise just find the latest one.
1492 */
1493static char *
1494linker_hints_lookup(const char *path, int pathlen, const char *modname,
1495    int modnamelen, struct mod_depend *verinfo)
1496{
1497	struct thread *td = curthread;	/* XXX */
1498	struct ucred *cred = td ? td->td_ucred : NULL;
1499	struct nameidata nd;
1500	struct vattr vattr, mattr;
1501	u_char *hints = NULL;
1502	u_char *cp, *recptr, *bufend, *result, *best, *pathbuf, *sep;
1503	int error, ival, bestver, *intp, reclen, found, flags, clen, blen;
1504
1505	result = NULL;
1506	bestver = found = 0;
1507
1508	sep = (path[pathlen - 1] != '/') ? "/" : "";
1509	reclen = imax(modnamelen, strlen(linker_hintfile)) + pathlen +
1510	    strlen(sep) + 1;
1511	pathbuf = malloc(reclen, M_LINKER, M_WAITOK);
1512	snprintf(pathbuf, reclen, "%.*s%s%s", pathlen, path, sep,
1513	    linker_hintfile);
1514
1515	NDINIT(&nd, LOOKUP, NOFOLLOW, UIO_SYSSPACE, pathbuf, td);
1516	flags = FREAD;
1517	error = vn_open(&nd, &flags, 0, -1);
1518	if (error)
1519		goto bad;
1520	NDFREE(&nd, NDF_ONLY_PNBUF);
1521	if (nd.ni_vp->v_type != VREG)
1522		goto bad;
1523	best = cp = NULL;
1524	error = VOP_GETATTR(nd.ni_vp, &vattr, cred, td);
1525	if (error)
1526		goto bad;
1527	/*
1528	 * XXX: we need to limit this number to some reasonable value
1529	 */
1530	if (vattr.va_size > 100 * 1024) {
1531		printf("hints file too large %ld\n", (long)vattr.va_size);
1532		goto bad;
1533	}
1534	hints = malloc(vattr.va_size, M_TEMP, M_WAITOK);
1535	if (hints == NULL)
1536		goto bad;
1537	error = vn_rdwr(UIO_READ, nd.ni_vp, (caddr_t)hints, vattr.va_size, 0,
1538	    UIO_SYSSPACE, IO_NODELOCKED, cred, NOCRED, &reclen, td);
1539	if (error)
1540		goto bad;
1541	VOP_UNLOCK(nd.ni_vp, 0, td);
1542	vn_close(nd.ni_vp, FREAD, cred, td);
1543	nd.ni_vp = NULL;
1544	if (reclen != 0) {
1545		printf("can't read %d\n", reclen);
1546		goto bad;
1547	}
1548	intp = (int *)hints;
1549	ival = *intp++;
1550	if (ival != LINKER_HINTS_VERSION) {
1551		printf("hints file version mismatch %d\n", ival);
1552		goto bad;
1553	}
1554	bufend = hints + vattr.va_size;
1555	recptr = (u_char *)intp;
1556	clen = blen = 0;
1557	while (recptr < bufend && !found) {
1558		intp = (int *)recptr;
1559		reclen = *intp++;
1560		ival = *intp++;
1561		cp = (char *)intp;
1562		switch (ival) {
1563		case MDT_VERSION:
1564			clen = *cp++;
1565			if (clen != modnamelen || bcmp(cp, modname, clen) != 0)
1566				break;
1567			cp += clen;
1568			INT_ALIGN(hints, cp);
1569			ival = *(int *)cp;
1570			cp += sizeof(int);
1571			clen = *cp++;
1572			if (verinfo == NULL ||
1573			    ival == verinfo->md_ver_preferred) {
1574				found = 1;
1575				break;
1576			}
1577			if (ival >= verinfo->md_ver_minimum &&
1578			    ival <= verinfo->md_ver_maximum &&
1579			    ival > bestver) {
1580				bestver = ival;
1581				best = cp;
1582				blen = clen;
1583			}
1584			break;
1585		default:
1586			break;
1587		}
1588		recptr += reclen + sizeof(int);
1589	}
1590	/*
1591	 * Finally check if KLD is in the place
1592	 */
1593	if (found)
1594		result = linker_lookup_file(path, pathlen, cp, clen, &mattr);
1595	else if (best)
1596		result = linker_lookup_file(path, pathlen, best, blen, &mattr);
1597
1598	/*
1599	 * KLD is newer than hints file. What we should do now?
1600	 */
1601	if (result && timespeccmp(&mattr.va_mtime, &vattr.va_mtime, >))
1602		printf("warning: KLD '%s' is newer than the linker.hints"
1603		    " file\n", result);
1604bad:
1605	free(pathbuf, M_LINKER);
1606	if (hints)
1607		free(hints, M_TEMP);
1608	if (nd.ni_vp != NULL) {
1609		VOP_UNLOCK(nd.ni_vp, 0, td);
1610		vn_close(nd.ni_vp, FREAD, cred, td);
1611	}
1612	/*
1613	 * If nothing found or hints is absent - fallback to the old
1614	 * way by using "kldname[.ko]" as module name.
1615	 */
1616	if (!found && !bestver && result == NULL)
1617		result = linker_lookup_file(path, pathlen, modname,
1618		    modnamelen, NULL);
1619	return (result);
1620}
1621
1622/*
1623 * Lookup KLD which contains requested module in the all directories.
1624 */
1625static char *
1626linker_search_module(const char *modname, int modnamelen,
1627    struct mod_depend *verinfo)
1628{
1629	char *cp, *ep, *result;
1630
1631	/*
1632	 * traverse the linker path
1633	 */
1634	for (cp = linker_path; *cp; cp = ep + 1) {
1635		/* find the end of this component */
1636		for (ep = cp; (*ep != 0) && (*ep != ';'); ep++);
1637		result = linker_hints_lookup(cp, ep - cp, modname,
1638		    modnamelen, verinfo);
1639		if (result != NULL)
1640			return (result);
1641		if (*ep == 0)
1642			break;
1643	}
1644	return (NULL);
1645}
1646
1647/*
1648 * Search for module in all directories listed in the linker_path.
1649 */
1650static char *
1651linker_search_kld(const char *name)
1652{
1653	char *cp, *ep, *result;
1654	int len;
1655
1656	/* qualified at all? */
1657	if (index(name, '/'))
1658		return (linker_strdup(name));
1659
1660	/* traverse the linker path */
1661	len = strlen(name);
1662	for (ep = linker_path; *ep; ep++) {
1663		cp = ep;
1664		/* find the end of this component */
1665		for (; *ep != 0 && *ep != ';'; ep++);
1666		result = linker_lookup_file(cp, ep - cp, name, len, NULL);
1667		if (result != NULL)
1668			return (result);
1669	}
1670	return (NULL);
1671}
1672
1673static const char *
1674linker_basename(const char *path)
1675{
1676	const char *filename;
1677
1678	filename = rindex(path, '/');
1679	if (filename == NULL)
1680		return path;
1681	if (filename[1])
1682		filename++;
1683	return (filename);
1684}
1685
1686#ifdef HWPMC_HOOKS
1687
1688struct hwpmc_context {
1689	int	nobjects;
1690	int	nmappings;
1691	struct pmckern_map_in *kobase;
1692};
1693
1694static int
1695linker_hwpmc_list_object(linker_file_t lf, void *arg)
1696{
1697	struct hwpmc_context *hc;
1698
1699	hc = arg;
1700
1701	/* If we run out of mappings, fail. */
1702	if (hc->nobjects >= hc->nmappings)
1703		return (1);
1704
1705	/* Save the info for this linker file. */
1706	hc->kobase[hc->nobjects].pm_file = lf->filename;
1707	hc->kobase[hc->nobjects].pm_address = (uintptr_t)lf->address;
1708	hc->nobjects++;
1709	return (0);
1710}
1711
1712/*
1713 * Inform hwpmc about the set of kernel modules currently loaded.
1714 */
1715void *
1716linker_hwpmc_list_objects(void)
1717{
1718	struct hwpmc_context hc;
1719
1720	hc.nmappings = 15;	/* a reasonable default */
1721
1722 retry:
1723	/* allocate nmappings+1 entries */
1724	MALLOC(hc.kobase, struct pmckern_map_in *,
1725	    (hc.nmappings + 1) * sizeof(struct pmckern_map_in), M_LINKER,
1726	    M_WAITOK | M_ZERO);
1727
1728	hc.nobjects = 0;
1729	if (linker_file_foreach(linker_hwpmc_list_object, &hc) != 0) {
1730		hc.nmappings = hc.nobjects;
1731		FREE(hc.kobase, M_LINKER);
1732		goto retry;
1733	}
1734
1735	KASSERT(hc.nobjects > 0, ("linker_hpwmc_list_objects: no kernel "
1736		"objects?"));
1737
1738	/* The last entry of the malloced area comprises of all zeros. */
1739	KASSERT(hc.kobase[hc.nobjects].pm_file == NULL,
1740	    ("linker_hwpmc_list_objects: last object not NULL"));
1741
1742	return ((void *)hc.kobase);
1743}
1744#endif
1745
1746/*
1747 * Find a file which contains given module and load it, if "parent" is not
1748 * NULL, register a reference to it.
1749 */
1750static int
1751linker_load_module(const char *kldname, const char *modname,
1752    struct linker_file *parent, struct mod_depend *verinfo,
1753    struct linker_file **lfpp)
1754{
1755	linker_file_t lfdep;
1756	const char *filename;
1757	char *pathname;
1758	int error;
1759
1760	if (modname == NULL) {
1761		/*
1762 		 * We have to load KLD
1763 		 */
1764		KASSERT(verinfo == NULL, ("linker_load_module: verinfo"
1765		    " is not NULL"));
1766		pathname = linker_search_kld(kldname);
1767	} else {
1768		if (modlist_lookup2(modname, verinfo) != NULL)
1769			return (EEXIST);
1770		if (kldname != NULL)
1771			pathname = linker_strdup(kldname);
1772		else if (rootvnode == NULL)
1773			pathname = NULL;
1774		else
1775			/*
1776			 * Need to find a KLD with required module
1777			 */
1778			pathname = linker_search_module(modname,
1779			    strlen(modname), verinfo);
1780	}
1781	if (pathname == NULL)
1782		return (ENOENT);
1783
1784	/*
1785	 * Can't load more than one file with the same basename XXX:
1786	 * Actually it should be possible to have multiple KLDs with
1787	 * the same basename but different path because they can
1788	 * provide different versions of the same modules.
1789	 */
1790	filename = linker_basename(pathname);
1791	if (linker_find_file_by_name(filename))
1792		error = EEXIST;
1793	else do {
1794		error = linker_load_file(pathname, &lfdep);
1795		if (error)
1796			break;
1797		if (modname && verinfo &&
1798		    modlist_lookup2(modname, verinfo) == NULL) {
1799			linker_file_unload(lfdep, LINKER_UNLOAD_FORCE);
1800			error = ENOENT;
1801			break;
1802		}
1803		if (parent) {
1804			error = linker_file_add_dependency(parent, lfdep);
1805			if (error)
1806				break;
1807		}
1808		if (lfpp)
1809			*lfpp = lfdep;
1810	} while (0);
1811	free(pathname, M_LINKER);
1812	return (error);
1813}
1814
1815/*
1816 * This routine is responsible for finding dependencies of userland initiated
1817 * kldload(2)'s of files.
1818 */
1819int
1820linker_load_dependencies(linker_file_t lf)
1821{
1822	linker_file_t lfdep;
1823	struct mod_metadata **start, **stop, **mdp, **nmdp;
1824	struct mod_metadata *mp, *nmp;
1825	struct mod_depend *verinfo;
1826	modlist_t mod;
1827	const char *modname, *nmodname;
1828	int ver, error = 0, count;
1829
1830	/*
1831	 * All files are dependant on /kernel.
1832	 */
1833	if (linker_kernel_file) {
1834		linker_kernel_file->refs++;
1835		error = linker_file_add_dependency(lf, linker_kernel_file);
1836		if (error)
1837			return (error);
1838	}
1839	if (linker_file_lookup_set(lf, MDT_SETNAME, &start, &stop,
1840	    &count) != 0)
1841		return (0);
1842	for (mdp = start; mdp < stop; mdp++) {
1843		mp = *mdp;
1844		if (mp->md_type != MDT_VERSION)
1845			continue;
1846		modname = mp->md_cval;
1847		ver = ((struct mod_version *)mp->md_data)->mv_version;
1848		mod = modlist_lookup(modname, ver);
1849		if (mod != NULL) {
1850			printf("interface %s.%d already present in the KLD"
1851			    " '%s'!\n", modname, ver,
1852			    mod->container->filename);
1853			return (EEXIST);
1854		}
1855	}
1856
1857	for (mdp = start; mdp < stop; mdp++) {
1858		mp = *mdp;
1859		if (mp->md_type != MDT_DEPEND)
1860			continue;
1861		modname = mp->md_cval;
1862		verinfo = mp->md_data;
1863		nmodname = NULL;
1864		for (nmdp = start; nmdp < stop; nmdp++) {
1865			nmp = *nmdp;
1866			if (nmp->md_type != MDT_VERSION)
1867				continue;
1868			nmodname = nmp->md_cval;
1869			if (strcmp(modname, nmodname) == 0)
1870				break;
1871		}
1872		if (nmdp < stop)/* early exit, it's a self reference */
1873			continue;
1874		mod = modlist_lookup2(modname, verinfo);
1875		if (mod) {	/* woohoo, it's loaded already */
1876			lfdep = mod->container;
1877			lfdep->refs++;
1878			error = linker_file_add_dependency(lf, lfdep);
1879			if (error)
1880				break;
1881			continue;
1882		}
1883		error = linker_load_module(NULL, modname, lf, verinfo, NULL);
1884		if (error) {
1885			printf("KLD %s: depends on %s - not available\n",
1886			    lf->filename, modname);
1887			break;
1888		}
1889	}
1890
1891	if (error)
1892		return (error);
1893	linker_addmodules(lf, start, stop, 0);
1894	return (error);
1895}
1896
1897static int
1898sysctl_kern_function_list_iterate(const char *name, void *opaque)
1899{
1900	struct sysctl_req *req;
1901
1902	req = opaque;
1903	return (SYSCTL_OUT(req, name, strlen(name) + 1));
1904}
1905
1906/*
1907 * Export a nul-separated, double-nul-terminated list of all function names
1908 * in the kernel.
1909 */
1910static int
1911sysctl_kern_function_list(SYSCTL_HANDLER_ARGS)
1912{
1913	linker_file_t lf;
1914	int error;
1915
1916#ifdef MAC
1917	error = mac_check_kld_stat(req->td->td_ucred);
1918	if (error)
1919		return (error);
1920#endif
1921	error = sysctl_wire_old_buffer(req, 0);
1922	if (error != 0)
1923		return (error);
1924	mtx_lock(&kld_mtx);
1925	TAILQ_FOREACH(lf, &linker_files, link) {
1926		error = LINKER_EACH_FUNCTION_NAME(lf,
1927		    sysctl_kern_function_list_iterate, req);
1928		if (error) {
1929			mtx_unlock(&kld_mtx);
1930			return (error);
1931		}
1932	}
1933	mtx_unlock(&kld_mtx);
1934	return (SYSCTL_OUT(req, "", 1));
1935}
1936
1937SYSCTL_PROC(_kern, OID_AUTO, function_list, CTLFLAG_RD,
1938    NULL, 0, sysctl_kern_function_list, "", "kernel function list");
1939