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