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