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