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