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