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