kern_linker.c revision 196019
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 196019 2009-08-01 19:26:27Z rwatson $");
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;
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	/*
997	 * It is possible that kldloaded module will attach a new ifnet,
998	 * so vnet context must be set when this ocurs.
999	 */
1000	CURVNET_SET(TD_TO_VNET(td));
1001
1002	/*
1003	 * If file does not contain a qualified name or any dot in it
1004	 * (kldname.ko, or kldname.ver.ko) treat it as an interface
1005	 * name.
1006	 */
1007	if (index(file, '/') || index(file, '.')) {
1008		kldname = file;
1009		modname = NULL;
1010	} else {
1011		kldname = NULL;
1012		modname = file;
1013	}
1014
1015	KLD_LOCK();
1016	error = linker_load_module(kldname, modname, NULL, NULL, &lf);
1017	if (error)
1018		goto unlock;
1019#ifdef HWPMC_HOOKS
1020	pkm.pm_file = lf->filename;
1021	pkm.pm_address = (uintptr_t) lf->address;
1022	PMC_CALL_HOOK(td, PMC_FN_KLD_LOAD, (void *) &pkm);
1023#endif
1024	lf->userrefs++;
1025	if (fileid != NULL)
1026		*fileid = lf->id;
1027unlock:
1028	KLD_UNLOCK();
1029	CURVNET_RESTORE();
1030	return (error);
1031}
1032
1033int
1034kldload(struct thread *td, struct kldload_args *uap)
1035{
1036	char *pathname = NULL;
1037	int error, fileid;
1038
1039	td->td_retval[0] = -1;
1040
1041	pathname = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
1042	error = copyinstr(uap->file, pathname, MAXPATHLEN, NULL);
1043	if (error == 0) {
1044		error = kern_kldload(td, pathname, &fileid);
1045		if (error == 0)
1046			td->td_retval[0] = fileid;
1047	}
1048	free(pathname, M_TEMP);
1049	return (error);
1050}
1051
1052int
1053kern_kldunload(struct thread *td, int fileid, int flags)
1054{
1055#ifdef HWPMC_HOOKS
1056	struct pmckern_map_out pkm;
1057#endif
1058	linker_file_t lf;
1059	int error = 0;
1060
1061	if ((error = securelevel_gt(td->td_ucred, 0)) != 0)
1062		return (error);
1063
1064	if ((error = priv_check(td, PRIV_KLD_UNLOAD)) != 0)
1065		return (error);
1066
1067	CURVNET_SET(TD_TO_VNET(td));
1068	KLD_LOCK();
1069	lf = linker_find_file_by_id(fileid);
1070	if (lf) {
1071		KLD_DPF(FILE, ("kldunload: lf->userrefs=%d\n", lf->userrefs));
1072
1073		/* Check if there are DTrace probes enabled on this file. */
1074		if (lf->nenabled > 0) {
1075			printf("kldunload: attempt to unload file that has"
1076			    " DTrace probes enabled\n");
1077			error = EBUSY;
1078		} else if (lf->userrefs == 0) {
1079			/*
1080			 * XXX: maybe LINKER_UNLOAD_FORCE should override ?
1081			 */
1082			printf("kldunload: attempt to unload file that was"
1083			    " loaded by the kernel\n");
1084			error = EBUSY;
1085		} else {
1086#ifdef HWPMC_HOOKS
1087			/* Save data needed by hwpmc(4) before unloading. */
1088			pkm.pm_address = (uintptr_t) lf->address;
1089			pkm.pm_size = lf->size;
1090#endif
1091			lf->userrefs--;
1092			error = linker_file_unload(lf, flags);
1093			if (error)
1094				lf->userrefs++;
1095		}
1096	} else
1097		error = ENOENT;
1098
1099#ifdef HWPMC_HOOKS
1100	if (error == 0)
1101		PMC_CALL_HOOK(td, PMC_FN_KLD_UNLOAD, (void *) &pkm);
1102#endif
1103	KLD_UNLOCK();
1104	CURVNET_RESTORE();
1105	return (error);
1106}
1107
1108int
1109kldunload(struct thread *td, struct kldunload_args *uap)
1110{
1111
1112	return (kern_kldunload(td, uap->fileid, LINKER_UNLOAD_NORMAL));
1113}
1114
1115int
1116kldunloadf(struct thread *td, struct kldunloadf_args *uap)
1117{
1118
1119	if (uap->flags != LINKER_UNLOAD_NORMAL &&
1120	    uap->flags != LINKER_UNLOAD_FORCE)
1121		return (EINVAL);
1122	return (kern_kldunload(td, uap->fileid, uap->flags));
1123}
1124
1125int
1126kldfind(struct thread *td, struct kldfind_args *uap)
1127{
1128	char *pathname;
1129	const char *filename;
1130	linker_file_t lf;
1131	int error;
1132
1133#ifdef MAC
1134	error = mac_kld_check_stat(td->td_ucred);
1135	if (error)
1136		return (error);
1137#endif
1138
1139	td->td_retval[0] = -1;
1140
1141	pathname = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
1142	if ((error = copyinstr(uap->file, pathname, MAXPATHLEN, NULL)) != 0)
1143		goto out;
1144
1145	filename = linker_basename(pathname);
1146	KLD_LOCK();
1147	lf = linker_find_file_by_name(filename);
1148	if (lf)
1149		td->td_retval[0] = lf->id;
1150	else
1151		error = ENOENT;
1152	KLD_UNLOCK();
1153out:
1154	free(pathname, M_TEMP);
1155	return (error);
1156}
1157
1158int
1159kldnext(struct thread *td, struct kldnext_args *uap)
1160{
1161	linker_file_t lf;
1162	int error = 0;
1163
1164#ifdef MAC
1165	error = mac_kld_check_stat(td->td_ucred);
1166	if (error)
1167		return (error);
1168#endif
1169
1170	KLD_LOCK();
1171	if (uap->fileid == 0)
1172		lf = TAILQ_FIRST(&linker_files);
1173	else {
1174		lf = linker_find_file_by_id(uap->fileid);
1175		if (lf == NULL) {
1176			error = ENOENT;
1177			goto out;
1178		}
1179		lf = TAILQ_NEXT(lf, link);
1180	}
1181
1182	/* Skip partially loaded files. */
1183	while (lf != NULL && !(lf->flags & LINKER_FILE_LINKED))
1184		lf = TAILQ_NEXT(lf, link);
1185
1186	if (lf)
1187		td->td_retval[0] = lf->id;
1188	else
1189		td->td_retval[0] = 0;
1190out:
1191	KLD_UNLOCK();
1192	return (error);
1193}
1194
1195int
1196kldstat(struct thread *td, struct kldstat_args *uap)
1197{
1198	struct kld_file_stat stat;
1199	linker_file_t lf;
1200	int error, namelen, version, version_num;
1201
1202	/*
1203	 * Check the version of the user's structure.
1204	 */
1205	if ((error = copyin(&uap->stat->version, &version, sizeof(version))) != 0)
1206		return (error);
1207	if (version == sizeof(struct kld_file_stat_1))
1208		version_num = 1;
1209	else if (version == sizeof(struct kld_file_stat))
1210		version_num = 2;
1211	else
1212		return (EINVAL);
1213
1214#ifdef MAC
1215	error = mac_kld_check_stat(td->td_ucred);
1216	if (error)
1217		return (error);
1218#endif
1219
1220	KLD_LOCK();
1221	lf = linker_find_file_by_id(uap->fileid);
1222	if (lf == NULL) {
1223		KLD_UNLOCK();
1224		return (ENOENT);
1225	}
1226
1227	/* Version 1 fields: */
1228	namelen = strlen(lf->filename) + 1;
1229	if (namelen > MAXPATHLEN)
1230		namelen = MAXPATHLEN;
1231	bcopy(lf->filename, &stat.name[0], namelen);
1232	stat.refs = lf->refs;
1233	stat.id = lf->id;
1234	stat.address = lf->address;
1235	stat.size = lf->size;
1236	if (version_num > 1) {
1237		/* Version 2 fields: */
1238		namelen = strlen(lf->pathname) + 1;
1239		if (namelen > MAXPATHLEN)
1240			namelen = MAXPATHLEN;
1241		bcopy(lf->pathname, &stat.pathname[0], namelen);
1242	}
1243	KLD_UNLOCK();
1244
1245	td->td_retval[0] = 0;
1246
1247	return (copyout(&stat, uap->stat, version));
1248}
1249
1250int
1251kldfirstmod(struct thread *td, struct kldfirstmod_args *uap)
1252{
1253	linker_file_t lf;
1254	module_t mp;
1255	int error = 0;
1256
1257#ifdef MAC
1258	error = mac_kld_check_stat(td->td_ucred);
1259	if (error)
1260		return (error);
1261#endif
1262
1263	KLD_LOCK();
1264	lf = linker_find_file_by_id(uap->fileid);
1265	if (lf) {
1266		MOD_SLOCK;
1267		mp = TAILQ_FIRST(&lf->modules);
1268		if (mp != NULL)
1269			td->td_retval[0] = module_getid(mp);
1270		else
1271			td->td_retval[0] = 0;
1272		MOD_SUNLOCK;
1273	} else
1274		error = ENOENT;
1275	KLD_UNLOCK();
1276	return (error);
1277}
1278
1279int
1280kldsym(struct thread *td, struct kldsym_args *uap)
1281{
1282	char *symstr = NULL;
1283	c_linker_sym_t sym;
1284	linker_symval_t symval;
1285	linker_file_t lf;
1286	struct kld_sym_lookup lookup;
1287	int error = 0;
1288
1289#ifdef MAC
1290	error = mac_kld_check_stat(td->td_ucred);
1291	if (error)
1292		return (error);
1293#endif
1294
1295	if ((error = copyin(uap->data, &lookup, sizeof(lookup))) != 0)
1296		return (error);
1297	if (lookup.version != sizeof(lookup) ||
1298	    uap->cmd != KLDSYM_LOOKUP)
1299		return (EINVAL);
1300	symstr = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
1301	if ((error = copyinstr(lookup.symname, symstr, MAXPATHLEN, NULL)) != 0)
1302		goto out;
1303	KLD_LOCK();
1304	if (uap->fileid != 0) {
1305		lf = linker_find_file_by_id(uap->fileid);
1306		if (lf == NULL)
1307			error = ENOENT;
1308		else if (LINKER_LOOKUP_SYMBOL(lf, symstr, &sym) == 0 &&
1309		    LINKER_SYMBOL_VALUES(lf, sym, &symval) == 0) {
1310			lookup.symvalue = (uintptr_t) symval.value;
1311			lookup.symsize = symval.size;
1312			error = copyout(&lookup, uap->data, sizeof(lookup));
1313		} else
1314			error = ENOENT;
1315	} else {
1316		TAILQ_FOREACH(lf, &linker_files, link) {
1317			if (LINKER_LOOKUP_SYMBOL(lf, symstr, &sym) == 0 &&
1318			    LINKER_SYMBOL_VALUES(lf, sym, &symval) == 0) {
1319				lookup.symvalue = (uintptr_t)symval.value;
1320				lookup.symsize = symval.size;
1321				error = copyout(&lookup, uap->data,
1322				    sizeof(lookup));
1323				break;
1324			}
1325		}
1326		if (lf == NULL)
1327			error = ENOENT;
1328	}
1329	KLD_UNLOCK();
1330out:
1331	free(symstr, M_TEMP);
1332	return (error);
1333}
1334
1335/*
1336 * Preloaded module support
1337 */
1338
1339static modlist_t
1340modlist_lookup(const char *name, int ver)
1341{
1342	modlist_t mod;
1343
1344	TAILQ_FOREACH(mod, &found_modules, link) {
1345		if (strcmp(mod->name, name) == 0 &&
1346		    (ver == 0 || mod->version == ver))
1347			return (mod);
1348	}
1349	return (NULL);
1350}
1351
1352static modlist_t
1353modlist_lookup2(const char *name, struct mod_depend *verinfo)
1354{
1355	modlist_t mod, bestmod;
1356	int ver;
1357
1358	if (verinfo == NULL)
1359		return (modlist_lookup(name, 0));
1360	bestmod = NULL;
1361	TAILQ_FOREACH(mod, &found_modules, link) {
1362		if (strcmp(mod->name, name) != 0)
1363			continue;
1364		ver = mod->version;
1365		if (ver == verinfo->md_ver_preferred)
1366			return (mod);
1367		if (ver >= verinfo->md_ver_minimum &&
1368		    ver <= verinfo->md_ver_maximum &&
1369		    (bestmod == NULL || ver > bestmod->version))
1370			bestmod = mod;
1371	}
1372	return (bestmod);
1373}
1374
1375static modlist_t
1376modlist_newmodule(const char *modname, int version, linker_file_t container)
1377{
1378	modlist_t mod;
1379
1380	mod = malloc(sizeof(struct modlist), M_LINKER, M_NOWAIT | M_ZERO);
1381	if (mod == NULL)
1382		panic("no memory for module list");
1383	mod->container = container;
1384	mod->name = modname;
1385	mod->version = version;
1386	TAILQ_INSERT_TAIL(&found_modules, mod, link);
1387	return (mod);
1388}
1389
1390static void
1391linker_addmodules(linker_file_t lf, struct mod_metadata **start,
1392    struct mod_metadata **stop, int preload)
1393{
1394	struct mod_metadata *mp, **mdp;
1395	const char *modname;
1396	int ver;
1397
1398	for (mdp = start; mdp < stop; mdp++) {
1399		mp = *mdp;
1400		if (mp->md_type != MDT_VERSION)
1401			continue;
1402		modname = mp->md_cval;
1403		ver = ((struct mod_version *)mp->md_data)->mv_version;
1404		if (modlist_lookup(modname, ver) != NULL) {
1405			printf("module %s already present!\n", modname);
1406			/* XXX what can we do? this is a build error. :-( */
1407			continue;
1408		}
1409		modlist_newmodule(modname, ver, lf);
1410	}
1411}
1412
1413static void
1414linker_preload(void *arg)
1415{
1416	caddr_t modptr;
1417	const char *modname, *nmodname;
1418	char *modtype;
1419	linker_file_t lf, nlf;
1420	linker_class_t lc;
1421	int error;
1422	linker_file_list_t loaded_files;
1423	linker_file_list_t depended_files;
1424	struct mod_metadata *mp, *nmp;
1425	struct mod_metadata **start, **stop, **mdp, **nmdp;
1426	struct mod_depend *verinfo;
1427	int nver;
1428	int resolves;
1429	modlist_t mod;
1430	struct sysinit **si_start, **si_stop;
1431
1432	TAILQ_INIT(&loaded_files);
1433	TAILQ_INIT(&depended_files);
1434	TAILQ_INIT(&found_modules);
1435	error = 0;
1436
1437	modptr = NULL;
1438	while ((modptr = preload_search_next_name(modptr)) != NULL) {
1439		modname = (char *)preload_search_info(modptr, MODINFO_NAME);
1440		modtype = (char *)preload_search_info(modptr, MODINFO_TYPE);
1441		if (modname == NULL) {
1442			printf("Preloaded module at %p does not have a"
1443			    " name!\n", modptr);
1444			continue;
1445		}
1446		if (modtype == NULL) {
1447			printf("Preloaded module at %p does not have a type!\n",
1448			    modptr);
1449			continue;
1450		}
1451		if (bootverbose)
1452			printf("Preloaded %s \"%s\" at %p.\n", modtype, modname,
1453			    modptr);
1454		lf = NULL;
1455		TAILQ_FOREACH(lc, &classes, link) {
1456			error = LINKER_LINK_PRELOAD(lc, modname, &lf);
1457			if (!error)
1458				break;
1459			lf = NULL;
1460		}
1461		if (lf)
1462			TAILQ_INSERT_TAIL(&loaded_files, lf, loaded);
1463	}
1464
1465	/*
1466	 * First get a list of stuff in the kernel.
1467	 */
1468	if (linker_file_lookup_set(linker_kernel_file, MDT_SETNAME, &start,
1469	    &stop, NULL) == 0)
1470		linker_addmodules(linker_kernel_file, start, stop, 1);
1471
1472	/*
1473	 * This is a once-off kinky bubble sort to resolve relocation
1474	 * dependency requirements.
1475	 */
1476restart:
1477	TAILQ_FOREACH(lf, &loaded_files, loaded) {
1478		error = linker_file_lookup_set(lf, MDT_SETNAME, &start,
1479		    &stop, NULL);
1480		/*
1481		 * First, look to see if we would successfully link with this
1482		 * stuff.
1483		 */
1484		resolves = 1;	/* unless we know otherwise */
1485		if (!error) {
1486			for (mdp = start; mdp < stop; mdp++) {
1487				mp = *mdp;
1488				if (mp->md_type != MDT_DEPEND)
1489					continue;
1490				modname = mp->md_cval;
1491				verinfo = mp->md_data;
1492				for (nmdp = start; nmdp < stop; nmdp++) {
1493					nmp = *nmdp;
1494					if (nmp->md_type != MDT_VERSION)
1495						continue;
1496					nmodname = nmp->md_cval;
1497					if (strcmp(modname, nmodname) == 0)
1498						break;
1499				}
1500				if (nmdp < stop)   /* it's a self reference */
1501					continue;
1502
1503				/*
1504				 * ok, the module isn't here yet, we
1505				 * are not finished
1506				 */
1507				if (modlist_lookup2(modname, verinfo) == NULL)
1508					resolves = 0;
1509			}
1510		}
1511		/*
1512		 * OK, if we found our modules, we can link.  So, "provide"
1513		 * the modules inside and add it to the end of the link order
1514		 * list.
1515		 */
1516		if (resolves) {
1517			if (!error) {
1518				for (mdp = start; mdp < stop; mdp++) {
1519					mp = *mdp;
1520					if (mp->md_type != MDT_VERSION)
1521						continue;
1522					modname = mp->md_cval;
1523					nver = ((struct mod_version *)
1524					    mp->md_data)->mv_version;
1525					if (modlist_lookup(modname,
1526					    nver) != NULL) {
1527						printf("module %s already"
1528						    " present!\n", modname);
1529						TAILQ_REMOVE(&loaded_files,
1530						    lf, loaded);
1531						linker_file_unload(lf,
1532						    LINKER_UNLOAD_FORCE);
1533						/* we changed tailq next ptr */
1534						goto restart;
1535					}
1536					modlist_newmodule(modname, nver, lf);
1537				}
1538			}
1539			TAILQ_REMOVE(&loaded_files, lf, loaded);
1540			TAILQ_INSERT_TAIL(&depended_files, lf, loaded);
1541			/*
1542			 * Since we provided modules, we need to restart the
1543			 * sort so that the previous files that depend on us
1544			 * have a chance. Also, we've busted the tailq next
1545			 * pointer with the REMOVE.
1546			 */
1547			goto restart;
1548		}
1549	}
1550
1551	/*
1552	 * At this point, we check to see what could not be resolved..
1553	 */
1554	while ((lf = TAILQ_FIRST(&loaded_files)) != NULL) {
1555		TAILQ_REMOVE(&loaded_files, lf, loaded);
1556		printf("KLD file %s is missing dependencies\n", lf->filename);
1557		linker_file_unload(lf, LINKER_UNLOAD_FORCE);
1558	}
1559
1560	/*
1561	 * We made it. Finish off the linking in the order we determined.
1562	 */
1563	TAILQ_FOREACH_SAFE(lf, &depended_files, loaded, nlf) {
1564		if (linker_kernel_file) {
1565			linker_kernel_file->refs++;
1566			error = linker_file_add_dependency(lf,
1567			    linker_kernel_file);
1568			if (error)
1569				panic("cannot add dependency");
1570		}
1571		lf->userrefs++;	/* so we can (try to) kldunload it */
1572		error = linker_file_lookup_set(lf, MDT_SETNAME, &start,
1573		    &stop, NULL);
1574		if (!error) {
1575			for (mdp = start; mdp < stop; mdp++) {
1576				mp = *mdp;
1577				if (mp->md_type != MDT_DEPEND)
1578					continue;
1579				modname = mp->md_cval;
1580				verinfo = mp->md_data;
1581				mod = modlist_lookup2(modname, verinfo);
1582				/* Don't count self-dependencies */
1583				if (lf == mod->container)
1584					continue;
1585				mod->container->refs++;
1586				error = linker_file_add_dependency(lf,
1587				    mod->container);
1588				if (error)
1589					panic("cannot add dependency");
1590			}
1591		}
1592		/*
1593		 * Now do relocation etc using the symbol search paths
1594		 * established by the dependencies
1595		 */
1596		error = LINKER_LINK_PRELOAD_FINISH(lf);
1597		if (error) {
1598			TAILQ_REMOVE(&depended_files, lf, loaded);
1599			printf("KLD file %s - could not finalize loading\n",
1600			    lf->filename);
1601			linker_file_unload(lf, LINKER_UNLOAD_FORCE);
1602			continue;
1603		}
1604		linker_file_register_modules(lf);
1605		if (linker_file_lookup_set(lf, "sysinit_set", &si_start,
1606		    &si_stop, NULL) == 0)
1607			sysinit_add(si_start, si_stop);
1608		linker_file_register_sysctls(lf);
1609		lf->flags |= LINKER_FILE_LINKED;
1610	}
1611	/* woohoo! we made it! */
1612}
1613
1614SYSINIT(preload, SI_SUB_KLD, SI_ORDER_MIDDLE, linker_preload, 0);
1615
1616/*
1617 * Search for a not-loaded module by name.
1618 *
1619 * Modules may be found in the following locations:
1620 *
1621 * - preloaded (result is just the module name) - on disk (result is full path
1622 * to module)
1623 *
1624 * If the module name is qualified in any way (contains path, etc.) the we
1625 * simply return a copy of it.
1626 *
1627 * The search path can be manipulated via sysctl.  Note that we use the ';'
1628 * character as a separator to be consistent with the bootloader.
1629 */
1630
1631static char linker_hintfile[] = "linker.hints";
1632static char linker_path[MAXPATHLEN] = "/boot/kernel;/boot/modules";
1633
1634SYSCTL_STRING(_kern, OID_AUTO, module_path, CTLFLAG_RW, linker_path,
1635    sizeof(linker_path), "module load search path");
1636
1637TUNABLE_STR("module_path", linker_path, sizeof(linker_path));
1638
1639static char *linker_ext_list[] = {
1640	"",
1641	".ko",
1642	NULL
1643};
1644
1645/*
1646 * Check if file actually exists either with or without extension listed in
1647 * the linker_ext_list. (probably should be generic for the rest of the
1648 * kernel)
1649 */
1650static char *
1651linker_lookup_file(const char *path, int pathlen, const char *name,
1652    int namelen, struct vattr *vap)
1653{
1654	struct nameidata nd;
1655	struct thread *td = curthread;	/* XXX */
1656	char *result, **cpp, *sep;
1657	int error, len, extlen, reclen, flags, vfslocked;
1658	enum vtype type;
1659
1660	extlen = 0;
1661	for (cpp = linker_ext_list; *cpp; cpp++) {
1662		len = strlen(*cpp);
1663		if (len > extlen)
1664			extlen = len;
1665	}
1666	extlen++;		/* trailing '\0' */
1667	sep = (path[pathlen - 1] != '/') ? "/" : "";
1668
1669	reclen = pathlen + strlen(sep) + namelen + extlen + 1;
1670	result = malloc(reclen, M_LINKER, M_WAITOK);
1671	for (cpp = linker_ext_list; *cpp; cpp++) {
1672		snprintf(result, reclen, "%.*s%s%.*s%s", pathlen, path, sep,
1673		    namelen, name, *cpp);
1674		/*
1675		 * Attempt to open the file, and return the path if
1676		 * we succeed and it's a regular file.
1677		 */
1678		NDINIT(&nd, LOOKUP, FOLLOW | MPSAFE, UIO_SYSSPACE, result, td);
1679		flags = FREAD;
1680		error = vn_open(&nd, &flags, 0, NULL);
1681		if (error == 0) {
1682			vfslocked = NDHASGIANT(&nd);
1683			NDFREE(&nd, NDF_ONLY_PNBUF);
1684			type = nd.ni_vp->v_type;
1685			if (vap)
1686				VOP_GETATTR(nd.ni_vp, vap, td->td_ucred);
1687			VOP_UNLOCK(nd.ni_vp, 0);
1688			vn_close(nd.ni_vp, FREAD, td->td_ucred, td);
1689			VFS_UNLOCK_GIANT(vfslocked);
1690			if (type == VREG)
1691				return (result);
1692		}
1693	}
1694	free(result, M_LINKER);
1695	return (NULL);
1696}
1697
1698#define	INT_ALIGN(base, ptr)	ptr =					\
1699	(base) + (((ptr) - (base) + sizeof(int) - 1) & ~(sizeof(int) - 1))
1700
1701/*
1702 * Lookup KLD which contains requested module in the "linker.hints" file. If
1703 * version specification is available, then try to find the best KLD.
1704 * Otherwise just find the latest one.
1705 */
1706static char *
1707linker_hints_lookup(const char *path, int pathlen, const char *modname,
1708    int modnamelen, struct mod_depend *verinfo)
1709{
1710	struct thread *td = curthread;	/* XXX */
1711	struct ucred *cred = td ? td->td_ucred : NULL;
1712	struct nameidata nd;
1713	struct vattr vattr, mattr;
1714	u_char *hints = NULL;
1715	u_char *cp, *recptr, *bufend, *result, *best, *pathbuf, *sep;
1716	int error, ival, bestver, *intp, reclen, found, flags, clen, blen;
1717	int vfslocked = 0;
1718
1719	result = NULL;
1720	bestver = found = 0;
1721
1722	sep = (path[pathlen - 1] != '/') ? "/" : "";
1723	reclen = imax(modnamelen, strlen(linker_hintfile)) + pathlen +
1724	    strlen(sep) + 1;
1725	pathbuf = malloc(reclen, M_LINKER, M_WAITOK);
1726	snprintf(pathbuf, reclen, "%.*s%s%s", pathlen, path, sep,
1727	    linker_hintfile);
1728
1729	NDINIT(&nd, LOOKUP, NOFOLLOW | MPSAFE, UIO_SYSSPACE, pathbuf, td);
1730	flags = FREAD;
1731	error = vn_open(&nd, &flags, 0, NULL);
1732	if (error)
1733		goto bad;
1734	vfslocked = NDHASGIANT(&nd);
1735	NDFREE(&nd, NDF_ONLY_PNBUF);
1736	if (nd.ni_vp->v_type != VREG)
1737		goto bad;
1738	best = cp = NULL;
1739	error = VOP_GETATTR(nd.ni_vp, &vattr, cred);
1740	if (error)
1741		goto bad;
1742	/*
1743	 * XXX: we need to limit this number to some reasonable value
1744	 */
1745	if (vattr.va_size > 100 * 1024) {
1746		printf("hints file too large %ld\n", (long)vattr.va_size);
1747		goto bad;
1748	}
1749	hints = malloc(vattr.va_size, M_TEMP, M_WAITOK);
1750	if (hints == NULL)
1751		goto bad;
1752	error = vn_rdwr(UIO_READ, nd.ni_vp, (caddr_t)hints, vattr.va_size, 0,
1753	    UIO_SYSSPACE, IO_NODELOCKED, cred, NOCRED, &reclen, td);
1754	if (error)
1755		goto bad;
1756	VOP_UNLOCK(nd.ni_vp, 0);
1757	vn_close(nd.ni_vp, FREAD, cred, td);
1758	VFS_UNLOCK_GIANT(vfslocked);
1759	nd.ni_vp = NULL;
1760	if (reclen != 0) {
1761		printf("can't read %d\n", reclen);
1762		goto bad;
1763	}
1764	intp = (int *)hints;
1765	ival = *intp++;
1766	if (ival != LINKER_HINTS_VERSION) {
1767		printf("hints file version mismatch %d\n", ival);
1768		goto bad;
1769	}
1770	bufend = hints + vattr.va_size;
1771	recptr = (u_char *)intp;
1772	clen = blen = 0;
1773	while (recptr < bufend && !found) {
1774		intp = (int *)recptr;
1775		reclen = *intp++;
1776		ival = *intp++;
1777		cp = (char *)intp;
1778		switch (ival) {
1779		case MDT_VERSION:
1780			clen = *cp++;
1781			if (clen != modnamelen || bcmp(cp, modname, clen) != 0)
1782				break;
1783			cp += clen;
1784			INT_ALIGN(hints, cp);
1785			ival = *(int *)cp;
1786			cp += sizeof(int);
1787			clen = *cp++;
1788			if (verinfo == NULL ||
1789			    ival == verinfo->md_ver_preferred) {
1790				found = 1;
1791				break;
1792			}
1793			if (ival >= verinfo->md_ver_minimum &&
1794			    ival <= verinfo->md_ver_maximum &&
1795			    ival > bestver) {
1796				bestver = ival;
1797				best = cp;
1798				blen = clen;
1799			}
1800			break;
1801		default:
1802			break;
1803		}
1804		recptr += reclen + sizeof(int);
1805	}
1806	/*
1807	 * Finally check if KLD is in the place
1808	 */
1809	if (found)
1810		result = linker_lookup_file(path, pathlen, cp, clen, &mattr);
1811	else if (best)
1812		result = linker_lookup_file(path, pathlen, best, blen, &mattr);
1813
1814	/*
1815	 * KLD is newer than hints file. What we should do now?
1816	 */
1817	if (result && timespeccmp(&mattr.va_mtime, &vattr.va_mtime, >))
1818		printf("warning: KLD '%s' is newer than the linker.hints"
1819		    " file\n", result);
1820bad:
1821	free(pathbuf, M_LINKER);
1822	if (hints)
1823		free(hints, M_TEMP);
1824	if (nd.ni_vp != NULL) {
1825		VOP_UNLOCK(nd.ni_vp, 0);
1826		vn_close(nd.ni_vp, FREAD, cred, td);
1827		VFS_UNLOCK_GIANT(vfslocked);
1828	}
1829	/*
1830	 * If nothing found or hints is absent - fallback to the old
1831	 * way by using "kldname[.ko]" as module name.
1832	 */
1833	if (!found && !bestver && result == NULL)
1834		result = linker_lookup_file(path, pathlen, modname,
1835		    modnamelen, NULL);
1836	return (result);
1837}
1838
1839/*
1840 * Lookup KLD which contains requested module in the all directories.
1841 */
1842static char *
1843linker_search_module(const char *modname, int modnamelen,
1844    struct mod_depend *verinfo)
1845{
1846	char *cp, *ep, *result;
1847
1848	/*
1849	 * traverse the linker path
1850	 */
1851	for (cp = linker_path; *cp; cp = ep + 1) {
1852		/* find the end of this component */
1853		for (ep = cp; (*ep != 0) && (*ep != ';'); ep++);
1854		result = linker_hints_lookup(cp, ep - cp, modname,
1855		    modnamelen, verinfo);
1856		if (result != NULL)
1857			return (result);
1858		if (*ep == 0)
1859			break;
1860	}
1861	return (NULL);
1862}
1863
1864/*
1865 * Search for module in all directories listed in the linker_path.
1866 */
1867static char *
1868linker_search_kld(const char *name)
1869{
1870	char *cp, *ep, *result;
1871	int len;
1872
1873	/* qualified at all? */
1874	if (index(name, '/'))
1875		return (linker_strdup(name));
1876
1877	/* traverse the linker path */
1878	len = strlen(name);
1879	for (ep = linker_path; *ep; ep++) {
1880		cp = ep;
1881		/* find the end of this component */
1882		for (; *ep != 0 && *ep != ';'; ep++);
1883		result = linker_lookup_file(cp, ep - cp, name, len, NULL);
1884		if (result != NULL)
1885			return (result);
1886	}
1887	return (NULL);
1888}
1889
1890static const char *
1891linker_basename(const char *path)
1892{
1893	const char *filename;
1894
1895	filename = rindex(path, '/');
1896	if (filename == NULL)
1897		return path;
1898	if (filename[1])
1899		filename++;
1900	return (filename);
1901}
1902
1903#ifdef HWPMC_HOOKS
1904/*
1905 * Inform hwpmc about the set of kernel modules currently loaded.
1906 */
1907void *
1908linker_hwpmc_list_objects(void)
1909{
1910	linker_file_t lf;
1911	struct pmckern_map_in *kobase;
1912	int i, nmappings;
1913
1914	nmappings = 0;
1915	KLD_LOCK();
1916	TAILQ_FOREACH(lf, &linker_files, link)
1917		nmappings++;
1918
1919	/* Allocate nmappings + 1 entries. */
1920	kobase = malloc((nmappings + 1) * sizeof(struct pmckern_map_in),
1921	    M_LINKER, M_WAITOK | M_ZERO);
1922	i = 0;
1923	TAILQ_FOREACH(lf, &linker_files, link) {
1924
1925		/* Save the info for this linker file. */
1926		kobase[i].pm_file = lf->filename;
1927		kobase[i].pm_address = (uintptr_t)lf->address;
1928		i++;
1929	}
1930	KLD_UNLOCK();
1931
1932	KASSERT(i > 0, ("linker_hpwmc_list_objects: no kernel objects?"));
1933
1934	/* The last entry of the malloced area comprises of all zeros. */
1935	KASSERT(kobase[i].pm_file == NULL,
1936	    ("linker_hwpmc_list_objects: last object not NULL"));
1937
1938	return ((void *)kobase);
1939}
1940#endif
1941
1942/*
1943 * Find a file which contains given module and load it, if "parent" is not
1944 * NULL, register a reference to it.
1945 */
1946static int
1947linker_load_module(const char *kldname, const char *modname,
1948    struct linker_file *parent, struct mod_depend *verinfo,
1949    struct linker_file **lfpp)
1950{
1951	linker_file_t lfdep;
1952	const char *filename;
1953	char *pathname;
1954	int error;
1955
1956	KLD_LOCK_ASSERT();
1957	if (modname == NULL) {
1958		/*
1959 		 * We have to load KLD
1960 		 */
1961		KASSERT(verinfo == NULL, ("linker_load_module: verinfo"
1962		    " is not NULL"));
1963		pathname = linker_search_kld(kldname);
1964	} else {
1965		if (modlist_lookup2(modname, verinfo) != NULL)
1966			return (EEXIST);
1967		if (kldname != NULL)
1968			pathname = linker_strdup(kldname);
1969		else if (rootvnode == NULL)
1970			pathname = NULL;
1971		else
1972			/*
1973			 * Need to find a KLD with required module
1974			 */
1975			pathname = linker_search_module(modname,
1976			    strlen(modname), verinfo);
1977	}
1978	if (pathname == NULL)
1979		return (ENOENT);
1980
1981	/*
1982	 * Can't load more than one file with the same basename XXX:
1983	 * Actually it should be possible to have multiple KLDs with
1984	 * the same basename but different path because they can
1985	 * provide different versions of the same modules.
1986	 */
1987	filename = linker_basename(pathname);
1988	if (linker_find_file_by_name(filename))
1989		error = EEXIST;
1990	else do {
1991		error = linker_load_file(pathname, &lfdep);
1992		if (error)
1993			break;
1994		if (modname && verinfo &&
1995		    modlist_lookup2(modname, verinfo) == NULL) {
1996			linker_file_unload(lfdep, LINKER_UNLOAD_FORCE);
1997			error = ENOENT;
1998			break;
1999		}
2000		if (parent) {
2001			error = linker_file_add_dependency(parent, lfdep);
2002			if (error)
2003				break;
2004		}
2005		if (lfpp)
2006			*lfpp = lfdep;
2007	} while (0);
2008	free(pathname, M_LINKER);
2009	return (error);
2010}
2011
2012/*
2013 * This routine is responsible for finding dependencies of userland initiated
2014 * kldload(2)'s of files.
2015 */
2016int
2017linker_load_dependencies(linker_file_t lf)
2018{
2019	linker_file_t lfdep;
2020	struct mod_metadata **start, **stop, **mdp, **nmdp;
2021	struct mod_metadata *mp, *nmp;
2022	struct mod_depend *verinfo;
2023	modlist_t mod;
2024	const char *modname, *nmodname;
2025	int ver, error = 0, count;
2026
2027	/*
2028	 * All files are dependant on /kernel.
2029	 */
2030	KLD_LOCK_ASSERT();
2031	if (linker_kernel_file) {
2032		linker_kernel_file->refs++;
2033		error = linker_file_add_dependency(lf, linker_kernel_file);
2034		if (error)
2035			return (error);
2036	}
2037	if (linker_file_lookup_set(lf, MDT_SETNAME, &start, &stop,
2038	    &count) != 0)
2039		return (0);
2040	for (mdp = start; mdp < stop; mdp++) {
2041		mp = *mdp;
2042		if (mp->md_type != MDT_VERSION)
2043			continue;
2044		modname = mp->md_cval;
2045		ver = ((struct mod_version *)mp->md_data)->mv_version;
2046		mod = modlist_lookup(modname, ver);
2047		if (mod != NULL) {
2048			printf("interface %s.%d already present in the KLD"
2049			    " '%s'!\n", modname, ver,
2050			    mod->container->filename);
2051			return (EEXIST);
2052		}
2053	}
2054
2055	for (mdp = start; mdp < stop; mdp++) {
2056		mp = *mdp;
2057		if (mp->md_type != MDT_DEPEND)
2058			continue;
2059		modname = mp->md_cval;
2060		verinfo = mp->md_data;
2061		nmodname = NULL;
2062		for (nmdp = start; nmdp < stop; nmdp++) {
2063			nmp = *nmdp;
2064			if (nmp->md_type != MDT_VERSION)
2065				continue;
2066			nmodname = nmp->md_cval;
2067			if (strcmp(modname, nmodname) == 0)
2068				break;
2069		}
2070		if (nmdp < stop)/* early exit, it's a self reference */
2071			continue;
2072		mod = modlist_lookup2(modname, verinfo);
2073		if (mod) {	/* woohoo, it's loaded already */
2074			lfdep = mod->container;
2075			lfdep->refs++;
2076			error = linker_file_add_dependency(lf, lfdep);
2077			if (error)
2078				break;
2079			continue;
2080		}
2081		error = linker_load_module(NULL, modname, lf, verinfo, NULL);
2082		if (error) {
2083			printf("KLD %s: depends on %s - not available or"
2084			    " version mismatch\n", lf->filename, modname);
2085			break;
2086		}
2087	}
2088
2089	if (error)
2090		return (error);
2091	linker_addmodules(lf, start, stop, 0);
2092	return (error);
2093}
2094
2095static int
2096sysctl_kern_function_list_iterate(const char *name, void *opaque)
2097{
2098	struct sysctl_req *req;
2099
2100	req = opaque;
2101	return (SYSCTL_OUT(req, name, strlen(name) + 1));
2102}
2103
2104/*
2105 * Export a nul-separated, double-nul-terminated list of all function names
2106 * in the kernel.
2107 */
2108static int
2109sysctl_kern_function_list(SYSCTL_HANDLER_ARGS)
2110{
2111	linker_file_t lf;
2112	int error;
2113
2114#ifdef MAC
2115	error = mac_kld_check_stat(req->td->td_ucred);
2116	if (error)
2117		return (error);
2118#endif
2119	error = sysctl_wire_old_buffer(req, 0);
2120	if (error != 0)
2121		return (error);
2122	KLD_LOCK();
2123	TAILQ_FOREACH(lf, &linker_files, link) {
2124		error = LINKER_EACH_FUNCTION_NAME(lf,
2125		    sysctl_kern_function_list_iterate, req);
2126		if (error) {
2127			KLD_UNLOCK();
2128			return (error);
2129		}
2130	}
2131	KLD_UNLOCK();
2132	return (SYSCTL_OUT(req, "", 1));
2133}
2134
2135SYSCTL_PROC(_kern, OID_AUTO, function_list, CTLFLAG_RD,
2136    NULL, 0, sysctl_kern_function_list, "", "kernel function list");
2137