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