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