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