kern_linker.c revision 233276
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 233276 2012-03-21 09:48:32Z ae $");
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/fcntl.h>
49#include <sys/jail.h>
50#include <sys/libkern.h>
51#include <sys/namei.h>
52#include <sys/vnode.h>
53#include <sys/syscallsubr.h>
54#include <sys/sysctl.h>
55
56#include <net/vnet.h>
57
58#include <security/mac/mac_framework.h>
59
60#include "linker_if.h"
61
62#ifdef HWPMC_HOOKS
63#include <sys/pmckern.h>
64#endif
65
66#ifdef KLD_DEBUG
67int kld_debug = 0;
68SYSCTL_INT(_debug, OID_AUTO, kld_debug, CTLFLAG_RW | CTLFLAG_TUN,
69    &kld_debug, 0, "Set various levels of KLD debug");
70TUNABLE_INT("debug.kld_debug", &kld_debug);
71#endif
72
73#define	KLD_LOCK()		sx_xlock(&kld_sx)
74#define	KLD_UNLOCK()		sx_xunlock(&kld_sx)
75#define	KLD_DOWNGRADE()		sx_downgrade(&kld_sx)
76#define	KLD_LOCK_READ()		sx_slock(&kld_sx)
77#define	KLD_UNLOCK_READ()	sx_sunlock(&kld_sx)
78#define	KLD_LOCKED()		sx_xlocked(&kld_sx)
79#define	KLD_LOCK_ASSERT() do {						\
80	if (!cold)							\
81		sx_assert(&kld_sx, SX_XLOCKED);				\
82} while (0)
83
84/*
85 * static char *linker_search_path(const char *name, struct mod_depend
86 * *verinfo);
87 */
88static const char 	*linker_basename(const char *path);
89
90/*
91 * Find a currently loaded file given its filename.
92 */
93static linker_file_t linker_find_file_by_name(const char* _filename);
94
95/*
96 * Find a currently loaded file given its file id.
97 */
98static linker_file_t linker_find_file_by_id(int _fileid);
99
100/* Metadata from the static kernel */
101SET_DECLARE(modmetadata_set, struct mod_metadata);
102
103MALLOC_DEFINE(M_LINKER, "linker", "kernel linker");
104
105linker_file_t linker_kernel_file;
106
107static struct sx kld_sx;	/* kernel linker lock */
108
109/*
110 * Load counter used by clients to determine if a linker file has been
111 * re-loaded. This counter is incremented for each file load.
112 */
113static int loadcnt;
114
115static linker_class_list_t classes;
116static linker_file_list_t linker_files;
117static int next_file_id = 1;
118static int linker_no_more_classes = 0;
119
120#define	LINKER_GET_NEXT_FILE_ID(a) do {					\
121	linker_file_t lftmp;						\
122									\
123	KLD_LOCK_ASSERT();						\
124retry:									\
125	TAILQ_FOREACH(lftmp, &linker_files, link) {			\
126		if (next_file_id == lftmp->id) {			\
127			next_file_id++;					\
128			goto retry;					\
129		}							\
130	}								\
131	(a) = next_file_id;						\
132} while(0)
133
134
135/* XXX wrong name; we're looking at version provision tags here, not modules */
136typedef TAILQ_HEAD(, modlist) modlisthead_t;
137struct modlist {
138	TAILQ_ENTRY(modlist) link;	/* chain together all modules */
139	linker_file_t   container;
140	const char 	*name;
141	int             version;
142};
143typedef struct modlist *modlist_t;
144static modlisthead_t found_modules;
145
146static int	linker_file_add_dependency(linker_file_t file,
147		    linker_file_t dep);
148static caddr_t	linker_file_lookup_symbol_internal(linker_file_t file,
149		    const char* name, int deps);
150static int	linker_load_module(const char *kldname,
151		    const char *modname, struct linker_file *parent,
152		    struct mod_depend *verinfo, struct linker_file **lfpp);
153static modlist_t modlist_lookup2(const char *name, struct mod_depend *verinfo);
154
155static char *
156linker_strdup(const char *str)
157{
158	char *result;
159
160	if ((result = malloc((strlen(str) + 1), M_LINKER, M_WAITOK)) != NULL)
161		strcpy(result, str);
162	return (result);
163}
164
165static void
166linker_init(void *arg)
167{
168
169	sx_init(&kld_sx, "kernel linker");
170	TAILQ_INIT(&classes);
171	TAILQ_INIT(&linker_files);
172}
173
174SYSINIT(linker, SI_SUB_KLD, SI_ORDER_FIRST, linker_init, 0);
175
176static void
177linker_stop_class_add(void *arg)
178{
179
180	linker_no_more_classes = 1;
181}
182
183SYSINIT(linker_class, SI_SUB_KLD, SI_ORDER_ANY, linker_stop_class_add, NULL);
184
185int
186linker_add_class(linker_class_t lc)
187{
188
189	/*
190	 * We disallow any class registration past SI_ORDER_ANY
191	 * of SI_SUB_KLD.  We bump the reference count to keep the
192	 * ops from being freed.
193	 */
194	if (linker_no_more_classes == 1)
195		return (EPERM);
196	kobj_class_compile((kobj_class_t) lc);
197	((kobj_class_t)lc)->refs++;	/* XXX: kobj_mtx */
198	TAILQ_INSERT_TAIL(&classes, lc, link);
199	return (0);
200}
201
202static void
203linker_file_sysinit(linker_file_t lf)
204{
205	struct sysinit **start, **stop, **sipp, **xipp, *save;
206
207	KLD_DPF(FILE, ("linker_file_sysinit: calling SYSINITs for %s\n",
208	    lf->filename));
209
210	if (linker_file_lookup_set(lf, "sysinit_set", &start, &stop, NULL) != 0)
211		return;
212	/*
213	 * Perform a bubble sort of the system initialization objects by
214	 * their subsystem (primary key) and order (secondary key).
215	 *
216	 * Since some things care about execution order, this is the operation
217	 * which ensures continued function.
218	 */
219	for (sipp = start; sipp < stop; sipp++) {
220		for (xipp = sipp + 1; xipp < stop; xipp++) {
221			if ((*sipp)->subsystem < (*xipp)->subsystem ||
222			    ((*sipp)->subsystem == (*xipp)->subsystem &&
223			    (*sipp)->order <= (*xipp)->order))
224				continue;	/* skip */
225			save = *sipp;
226			*sipp = *xipp;
227			*xipp = save;
228		}
229	}
230
231	/*
232	 * Traverse the (now) ordered list of system initialization tasks.
233	 * Perform each task, and continue on to the next task.
234	 */
235	mtx_lock(&Giant);
236	for (sipp = start; sipp < stop; sipp++) {
237		if ((*sipp)->subsystem == SI_SUB_DUMMY)
238			continue;	/* skip dummy task(s) */
239
240		/* Call function */
241		(*((*sipp)->func)) ((*sipp)->udata);
242	}
243	mtx_unlock(&Giant);
244}
245
246static void
247linker_file_sysuninit(linker_file_t lf)
248{
249	struct sysinit **start, **stop, **sipp, **xipp, *save;
250
251	KLD_DPF(FILE, ("linker_file_sysuninit: calling SYSUNINITs for %s\n",
252	    lf->filename));
253
254	if (linker_file_lookup_set(lf, "sysuninit_set", &start, &stop,
255	    NULL) != 0)
256		return;
257
258	/*
259	 * Perform a reverse bubble sort of the system initialization objects
260	 * by their subsystem (primary key) and order (secondary key).
261	 *
262	 * Since some things care about execution order, this is the operation
263	 * which ensures continued function.
264	 */
265	for (sipp = start; sipp < stop; sipp++) {
266		for (xipp = sipp + 1; xipp < stop; xipp++) {
267			if ((*sipp)->subsystem > (*xipp)->subsystem ||
268			    ((*sipp)->subsystem == (*xipp)->subsystem &&
269			    (*sipp)->order >= (*xipp)->order))
270				continue;	/* skip */
271			save = *sipp;
272			*sipp = *xipp;
273			*xipp = save;
274		}
275	}
276
277	/*
278	 * Traverse the (now) ordered list of system initialization tasks.
279	 * Perform each task, and continue on to the next task.
280	 */
281	mtx_lock(&Giant);
282	for (sipp = start; sipp < stop; sipp++) {
283		if ((*sipp)->subsystem == SI_SUB_DUMMY)
284			continue;	/* skip dummy task(s) */
285
286		/* Call function */
287		(*((*sipp)->func)) ((*sipp)->udata);
288	}
289	mtx_unlock(&Giant);
290}
291
292static void
293linker_file_register_sysctls(linker_file_t lf)
294{
295	struct sysctl_oid **start, **stop, **oidp;
296
297	KLD_DPF(FILE,
298	    ("linker_file_register_sysctls: registering SYSCTLs for %s\n",
299	    lf->filename));
300
301	if (linker_file_lookup_set(lf, "sysctl_set", &start, &stop, NULL) != 0)
302		return;
303
304	sysctl_lock();
305	for (oidp = start; oidp < stop; oidp++)
306		sysctl_register_oid(*oidp);
307	sysctl_unlock();
308}
309
310static void
311linker_file_unregister_sysctls(linker_file_t lf)
312{
313	struct sysctl_oid **start, **stop, **oidp;
314
315	KLD_DPF(FILE, ("linker_file_unregister_sysctls: registering SYSCTLs"
316	    " for %s\n", lf->filename));
317
318	if (linker_file_lookup_set(lf, "sysctl_set", &start, &stop, NULL) != 0)
319		return;
320
321	sysctl_lock();
322	for (oidp = start; oidp < stop; oidp++)
323		sysctl_unregister_oid(*oidp);
324	sysctl_unlock();
325}
326
327static int
328linker_file_register_modules(linker_file_t lf)
329{
330	struct mod_metadata **start, **stop, **mdp;
331	const moduledata_t *moddata;
332	int first_error, error;
333
334	KLD_DPF(FILE, ("linker_file_register_modules: registering modules"
335	    " in %s\n", lf->filename));
336
337	if (linker_file_lookup_set(lf, "modmetadata_set", &start,
338	    &stop, NULL) != 0) {
339		/*
340		 * This fallback should be unnecessary, but if we get booted
341		 * from boot2 instead of loader and we are missing our
342		 * metadata then we have to try the best we can.
343		 */
344		if (lf == linker_kernel_file) {
345			start = SET_BEGIN(modmetadata_set);
346			stop = SET_LIMIT(modmetadata_set);
347		} else
348			return (0);
349	}
350	first_error = 0;
351	for (mdp = start; mdp < stop; mdp++) {
352		if ((*mdp)->md_type != MDT_MODULE)
353			continue;
354		moddata = (*mdp)->md_data;
355		KLD_DPF(FILE, ("Registering module %s in %s\n",
356		    moddata->name, lf->filename));
357		error = module_register(moddata, lf);
358		if (error) {
359			printf("Module %s failed to register: %d\n",
360			    moddata->name, error);
361			if (first_error == 0)
362				first_error = error;
363		}
364	}
365	return (first_error);
366}
367
368static void
369linker_init_kernel_modules(void)
370{
371
372	linker_file_register_modules(linker_kernel_file);
373}
374
375SYSINIT(linker_kernel, SI_SUB_KLD, SI_ORDER_ANY, linker_init_kernel_modules,
376    0);
377
378static int
379linker_load_file(const char *filename, linker_file_t *result)
380{
381	linker_class_t lc;
382	linker_file_t lf;
383	int foundfile, error;
384
385	/* Refuse to load modules if securelevel raised */
386	if (prison0.pr_securelevel > 0)
387		return (EPERM);
388
389	KLD_LOCK_ASSERT();
390	lf = linker_find_file_by_name(filename);
391	if (lf) {
392		KLD_DPF(FILE, ("linker_load_file: file %s is already loaded,"
393		    " incrementing refs\n", filename));
394		*result = lf;
395		lf->refs++;
396		return (0);
397	}
398	foundfile = 0;
399	error = 0;
400
401	/*
402	 * We do not need to protect (lock) classes here because there is
403	 * no class registration past startup (SI_SUB_KLD, SI_ORDER_ANY)
404	 * and there is no class deregistration mechanism at this time.
405	 */
406	TAILQ_FOREACH(lc, &classes, link) {
407		KLD_DPF(FILE, ("linker_load_file: trying to load %s\n",
408		    filename));
409		error = LINKER_LOAD_FILE(lc, filename, &lf);
410		/*
411		 * If we got something other than ENOENT, then it exists but
412		 * we cannot load it for some other reason.
413		 */
414		if (error != ENOENT)
415			foundfile = 1;
416		if (lf) {
417			error = linker_file_register_modules(lf);
418			if (error == EEXIST) {
419				linker_file_unload(lf, LINKER_UNLOAD_FORCE);
420				return (error);
421			}
422			KLD_UNLOCK();
423			linker_file_register_sysctls(lf);
424			linker_file_sysinit(lf);
425			KLD_LOCK();
426			lf->flags |= LINKER_FILE_LINKED;
427			*result = lf;
428			return (0);
429		}
430	}
431	/*
432	 * Less than ideal, but tells the user whether it failed to load or
433	 * the module was not found.
434	 */
435	if (foundfile) {
436
437		/*
438		 * If the file type has not been recognized by the last try
439		 * printout a message before to fail.
440		 */
441		if (error == ENOSYS)
442			printf("linker_load_file: Unsupported file type\n");
443
444		/*
445		 * Format not recognized or otherwise unloadable.
446		 * When loading a module that is statically built into
447		 * the kernel EEXIST percolates back up as the return
448		 * value.  Preserve this so that apps like sysinstall
449		 * can recognize this special case and not post bogus
450		 * dialog boxes.
451		 */
452		if (error != EEXIST)
453			error = ENOEXEC;
454	} else
455		error = ENOENT;		/* Nothing found */
456	return (error);
457}
458
459int
460linker_reference_module(const char *modname, struct mod_depend *verinfo,
461    linker_file_t *result)
462{
463	modlist_t mod;
464	int error;
465
466	KLD_LOCK();
467	if ((mod = modlist_lookup2(modname, verinfo)) != NULL) {
468		*result = mod->container;
469		(*result)->refs++;
470		KLD_UNLOCK();
471		return (0);
472	}
473
474	error = linker_load_module(NULL, modname, NULL, verinfo, result);
475	KLD_UNLOCK();
476	return (error);
477}
478
479int
480linker_release_module(const char *modname, struct mod_depend *verinfo,
481    linker_file_t lf)
482{
483	modlist_t mod;
484	int error;
485
486	KLD_LOCK();
487	if (lf == NULL) {
488		KASSERT(modname != NULL,
489		    ("linker_release_module: no file or name"));
490		mod = modlist_lookup2(modname, verinfo);
491		if (mod == NULL) {
492			KLD_UNLOCK();
493			return (ESRCH);
494		}
495		lf = mod->container;
496	} else
497		KASSERT(modname == NULL && verinfo == NULL,
498		    ("linker_release_module: both file and name"));
499	error =	linker_file_unload(lf, LINKER_UNLOAD_NORMAL);
500	KLD_UNLOCK();
501	return (error);
502}
503
504static linker_file_t
505linker_find_file_by_name(const char *filename)
506{
507	linker_file_t lf;
508	char *koname;
509
510	koname = malloc(strlen(filename) + 4, M_LINKER, M_WAITOK);
511	sprintf(koname, "%s.ko", filename);
512
513	KLD_LOCK_ASSERT();
514	TAILQ_FOREACH(lf, &linker_files, link) {
515		if (strcmp(lf->filename, koname) == 0)
516			break;
517		if (strcmp(lf->filename, filename) == 0)
518			break;
519	}
520	free(koname, M_LINKER);
521	return (lf);
522}
523
524static linker_file_t
525linker_find_file_by_id(int fileid)
526{
527	linker_file_t lf;
528
529	KLD_LOCK_ASSERT();
530	TAILQ_FOREACH(lf, &linker_files, link)
531		if (lf->id == fileid && lf->flags & LINKER_FILE_LINKED)
532			break;
533	return (lf);
534}
535
536int
537linker_file_foreach(linker_predicate_t *predicate, void *context)
538{
539	linker_file_t lf;
540	int retval = 0;
541
542	KLD_LOCK();
543	TAILQ_FOREACH(lf, &linker_files, link) {
544		retval = predicate(lf, context);
545		if (retval != 0)
546			break;
547	}
548	KLD_UNLOCK();
549	return (retval);
550}
551
552linker_file_t
553linker_make_file(const char *pathname, linker_class_t lc)
554{
555	linker_file_t lf;
556	const char *filename;
557
558	KLD_LOCK_ASSERT();
559	filename = linker_basename(pathname);
560
561	KLD_DPF(FILE, ("linker_make_file: new file, filename='%s' for pathname='%s'\n", filename, pathname));
562	lf = (linker_file_t)kobj_create((kobj_class_t)lc, M_LINKER, M_WAITOK);
563	if (lf == NULL)
564		return (NULL);
565	lf->refs = 1;
566	lf->userrefs = 0;
567	lf->flags = 0;
568	lf->filename = linker_strdup(filename);
569	lf->pathname = linker_strdup(pathname);
570	LINKER_GET_NEXT_FILE_ID(lf->id);
571	lf->ndeps = 0;
572	lf->deps = NULL;
573	lf->loadcnt = ++loadcnt;
574	lf->sdt_probes = NULL;
575	lf->sdt_nprobes = 0;
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 be 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#ifdef HWPMC_HOOKS
1039	KLD_DOWNGRADE();
1040	pkm.pm_file = lf->filename;
1041	pkm.pm_address = (uintptr_t) lf->address;
1042	PMC_CALL_HOOK(td, PMC_FN_KLD_LOAD, (void *) &pkm);
1043	KLD_UNLOCK_READ();
1044#else
1045	KLD_UNLOCK();
1046#endif
1047
1048done:
1049	CURVNET_RESTORE();
1050	return (error);
1051}
1052
1053int
1054sys_kldload(struct thread *td, struct kldload_args *uap)
1055{
1056	char *pathname = NULL;
1057	int error, fileid;
1058
1059	td->td_retval[0] = -1;
1060
1061	pathname = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
1062	error = copyinstr(uap->file, pathname, MAXPATHLEN, NULL);
1063	if (error == 0) {
1064		error = kern_kldload(td, pathname, &fileid);
1065		if (error == 0)
1066			td->td_retval[0] = fileid;
1067	}
1068	free(pathname, M_TEMP);
1069	return (error);
1070}
1071
1072int
1073kern_kldunload(struct thread *td, int fileid, int flags)
1074{
1075#ifdef HWPMC_HOOKS
1076	struct pmckern_map_out pkm;
1077#endif
1078	linker_file_t lf;
1079	int error = 0;
1080
1081	if ((error = securelevel_gt(td->td_ucred, 0)) != 0)
1082		return (error);
1083
1084	if ((error = priv_check(td, PRIV_KLD_UNLOAD)) != 0)
1085		return (error);
1086
1087	CURVNET_SET(TD_TO_VNET(td));
1088	KLD_LOCK();
1089	lf = linker_find_file_by_id(fileid);
1090	if (lf) {
1091		KLD_DPF(FILE, ("kldunload: lf->userrefs=%d\n", lf->userrefs));
1092
1093		/* Check if there are DTrace probes enabled on this file. */
1094		if (lf->nenabled > 0) {
1095			printf("kldunload: attempt to unload file that has"
1096			    " DTrace probes enabled\n");
1097			error = EBUSY;
1098		} else if (lf->userrefs == 0) {
1099			/*
1100			 * XXX: maybe LINKER_UNLOAD_FORCE should override ?
1101			 */
1102			printf("kldunload: attempt to unload file that was"
1103			    " loaded by the kernel\n");
1104			error = EBUSY;
1105		} else {
1106#ifdef HWPMC_HOOKS
1107			/* Save data needed by hwpmc(4) before unloading. */
1108			pkm.pm_address = (uintptr_t) lf->address;
1109			pkm.pm_size = lf->size;
1110#endif
1111			lf->userrefs--;
1112			error = linker_file_unload(lf, flags);
1113			if (error)
1114				lf->userrefs++;
1115		}
1116	} else
1117		error = ENOENT;
1118
1119#ifdef HWPMC_HOOKS
1120	if (error == 0) {
1121		KLD_DOWNGRADE();
1122		PMC_CALL_HOOK(td, PMC_FN_KLD_UNLOAD, (void *) &pkm);
1123		KLD_UNLOCK_READ();
1124	} else
1125		KLD_UNLOCK();
1126#else
1127	KLD_UNLOCK();
1128#endif
1129	CURVNET_RESTORE();
1130	return (error);
1131}
1132
1133int
1134sys_kldunload(struct thread *td, struct kldunload_args *uap)
1135{
1136
1137	return (kern_kldunload(td, uap->fileid, LINKER_UNLOAD_NORMAL));
1138}
1139
1140int
1141sys_kldunloadf(struct thread *td, struct kldunloadf_args *uap)
1142{
1143
1144	if (uap->flags != LINKER_UNLOAD_NORMAL &&
1145	    uap->flags != LINKER_UNLOAD_FORCE)
1146		return (EINVAL);
1147	return (kern_kldunload(td, uap->fileid, uap->flags));
1148}
1149
1150int
1151sys_kldfind(struct thread *td, struct kldfind_args *uap)
1152{
1153	char *pathname;
1154	const char *filename;
1155	linker_file_t lf;
1156	int error;
1157
1158#ifdef MAC
1159	error = mac_kld_check_stat(td->td_ucred);
1160	if (error)
1161		return (error);
1162#endif
1163
1164	td->td_retval[0] = -1;
1165
1166	pathname = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
1167	if ((error = copyinstr(uap->file, pathname, MAXPATHLEN, NULL)) != 0)
1168		goto out;
1169
1170	filename = linker_basename(pathname);
1171	KLD_LOCK();
1172	lf = linker_find_file_by_name(filename);
1173	if (lf)
1174		td->td_retval[0] = lf->id;
1175	else
1176		error = ENOENT;
1177	KLD_UNLOCK();
1178out:
1179	free(pathname, M_TEMP);
1180	return (error);
1181}
1182
1183int
1184sys_kldnext(struct thread *td, struct kldnext_args *uap)
1185{
1186	linker_file_t lf;
1187	int error = 0;
1188
1189#ifdef MAC
1190	error = mac_kld_check_stat(td->td_ucred);
1191	if (error)
1192		return (error);
1193#endif
1194
1195	KLD_LOCK();
1196	if (uap->fileid == 0)
1197		lf = TAILQ_FIRST(&linker_files);
1198	else {
1199		lf = linker_find_file_by_id(uap->fileid);
1200		if (lf == NULL) {
1201			error = ENOENT;
1202			goto out;
1203		}
1204		lf = TAILQ_NEXT(lf, link);
1205	}
1206
1207	/* Skip partially loaded files. */
1208	while (lf != NULL && !(lf->flags & LINKER_FILE_LINKED))
1209		lf = TAILQ_NEXT(lf, link);
1210
1211	if (lf)
1212		td->td_retval[0] = lf->id;
1213	else
1214		td->td_retval[0] = 0;
1215out:
1216	KLD_UNLOCK();
1217	return (error);
1218}
1219
1220int
1221sys_kldstat(struct thread *td, struct kldstat_args *uap)
1222{
1223	struct kld_file_stat stat;
1224	int error, version;
1225
1226	/*
1227	 * Check the version of the user's structure.
1228	 */
1229	if ((error = copyin(&uap->stat->version, &version, sizeof(version)))
1230	    != 0)
1231		return (error);
1232	if (version != sizeof(struct kld_file_stat_1) &&
1233	    version != sizeof(struct kld_file_stat))
1234		return (EINVAL);
1235
1236	error = kern_kldstat(td, uap->fileid, &stat);
1237	if (error != 0)
1238		return (error);
1239	return (copyout(&stat, uap->stat, version));
1240}
1241
1242int
1243kern_kldstat(struct thread *td, int fileid, struct kld_file_stat *stat)
1244{
1245	linker_file_t lf;
1246	int namelen;
1247#ifdef MAC
1248	int error;
1249
1250	error = mac_kld_check_stat(td->td_ucred);
1251	if (error)
1252		return (error);
1253#endif
1254
1255	KLD_LOCK();
1256	lf = linker_find_file_by_id(fileid);
1257	if (lf == NULL) {
1258		KLD_UNLOCK();
1259		return (ENOENT);
1260	}
1261
1262	/* Version 1 fields: */
1263	namelen = strlen(lf->filename) + 1;
1264	if (namelen > MAXPATHLEN)
1265		namelen = MAXPATHLEN;
1266	bcopy(lf->filename, &stat->name[0], namelen);
1267	stat->refs = lf->refs;
1268	stat->id = lf->id;
1269	stat->address = lf->address;
1270	stat->size = lf->size;
1271	/* Version 2 fields: */
1272	namelen = strlen(lf->pathname) + 1;
1273	if (namelen > MAXPATHLEN)
1274		namelen = MAXPATHLEN;
1275	bcopy(lf->pathname, &stat->pathname[0], namelen);
1276	KLD_UNLOCK();
1277
1278	td->td_retval[0] = 0;
1279	return (0);
1280}
1281
1282int
1283sys_kldfirstmod(struct thread *td, struct kldfirstmod_args *uap)
1284{
1285	linker_file_t lf;
1286	module_t mp;
1287	int error = 0;
1288
1289#ifdef MAC
1290	error = mac_kld_check_stat(td->td_ucred);
1291	if (error)
1292		return (error);
1293#endif
1294
1295	KLD_LOCK();
1296	lf = linker_find_file_by_id(uap->fileid);
1297	if (lf) {
1298		MOD_SLOCK;
1299		mp = TAILQ_FIRST(&lf->modules);
1300		if (mp != NULL)
1301			td->td_retval[0] = module_getid(mp);
1302		else
1303			td->td_retval[0] = 0;
1304		MOD_SUNLOCK;
1305	} else
1306		error = ENOENT;
1307	KLD_UNLOCK();
1308	return (error);
1309}
1310
1311int
1312sys_kldsym(struct thread *td, struct kldsym_args *uap)
1313{
1314	char *symstr = NULL;
1315	c_linker_sym_t sym;
1316	linker_symval_t symval;
1317	linker_file_t lf;
1318	struct kld_sym_lookup lookup;
1319	int error = 0;
1320
1321#ifdef MAC
1322	error = mac_kld_check_stat(td->td_ucred);
1323	if (error)
1324		return (error);
1325#endif
1326
1327	if ((error = copyin(uap->data, &lookup, sizeof(lookup))) != 0)
1328		return (error);
1329	if (lookup.version != sizeof(lookup) ||
1330	    uap->cmd != KLDSYM_LOOKUP)
1331		return (EINVAL);
1332	symstr = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
1333	if ((error = copyinstr(lookup.symname, symstr, MAXPATHLEN, NULL)) != 0)
1334		goto out;
1335	KLD_LOCK();
1336	if (uap->fileid != 0) {
1337		lf = linker_find_file_by_id(uap->fileid);
1338		if (lf == NULL)
1339			error = ENOENT;
1340		else if (LINKER_LOOKUP_SYMBOL(lf, symstr, &sym) == 0 &&
1341		    LINKER_SYMBOL_VALUES(lf, sym, &symval) == 0) {
1342			lookup.symvalue = (uintptr_t) symval.value;
1343			lookup.symsize = symval.size;
1344			error = copyout(&lookup, uap->data, sizeof(lookup));
1345		} else
1346			error = ENOENT;
1347	} else {
1348		TAILQ_FOREACH(lf, &linker_files, link) {
1349			if (LINKER_LOOKUP_SYMBOL(lf, symstr, &sym) == 0 &&
1350			    LINKER_SYMBOL_VALUES(lf, sym, &symval) == 0) {
1351				lookup.symvalue = (uintptr_t)symval.value;
1352				lookup.symsize = symval.size;
1353				error = copyout(&lookup, uap->data,
1354				    sizeof(lookup));
1355				break;
1356			}
1357		}
1358		if (lf == NULL)
1359			error = ENOENT;
1360	}
1361	KLD_UNLOCK();
1362out:
1363	free(symstr, M_TEMP);
1364	return (error);
1365}
1366
1367/*
1368 * Preloaded module support
1369 */
1370
1371static modlist_t
1372modlist_lookup(const char *name, int ver)
1373{
1374	modlist_t mod;
1375
1376	TAILQ_FOREACH(mod, &found_modules, link) {
1377		if (strcmp(mod->name, name) == 0 &&
1378		    (ver == 0 || mod->version == ver))
1379			return (mod);
1380	}
1381	return (NULL);
1382}
1383
1384static modlist_t
1385modlist_lookup2(const char *name, struct mod_depend *verinfo)
1386{
1387	modlist_t mod, bestmod;
1388	int ver;
1389
1390	if (verinfo == NULL)
1391		return (modlist_lookup(name, 0));
1392	bestmod = NULL;
1393	TAILQ_FOREACH(mod, &found_modules, link) {
1394		if (strcmp(mod->name, name) != 0)
1395			continue;
1396		ver = mod->version;
1397		if (ver == verinfo->md_ver_preferred)
1398			return (mod);
1399		if (ver >= verinfo->md_ver_minimum &&
1400		    ver <= verinfo->md_ver_maximum &&
1401		    (bestmod == NULL || ver > bestmod->version))
1402			bestmod = mod;
1403	}
1404	return (bestmod);
1405}
1406
1407static modlist_t
1408modlist_newmodule(const char *modname, int version, linker_file_t container)
1409{
1410	modlist_t mod;
1411
1412	mod = malloc(sizeof(struct modlist), M_LINKER, M_NOWAIT | M_ZERO);
1413	if (mod == NULL)
1414		panic("no memory for module list");
1415	mod->container = container;
1416	mod->name = modname;
1417	mod->version = version;
1418	TAILQ_INSERT_TAIL(&found_modules, mod, link);
1419	return (mod);
1420}
1421
1422static void
1423linker_addmodules(linker_file_t lf, struct mod_metadata **start,
1424    struct mod_metadata **stop, int preload)
1425{
1426	struct mod_metadata *mp, **mdp;
1427	const char *modname;
1428	int ver;
1429
1430	for (mdp = start; mdp < stop; mdp++) {
1431		mp = *mdp;
1432		if (mp->md_type != MDT_VERSION)
1433			continue;
1434		modname = mp->md_cval;
1435		ver = ((struct mod_version *)mp->md_data)->mv_version;
1436		if (modlist_lookup(modname, ver) != NULL) {
1437			printf("module %s already present!\n", modname);
1438			/* XXX what can we do? this is a build error. :-( */
1439			continue;
1440		}
1441		modlist_newmodule(modname, ver, lf);
1442	}
1443}
1444
1445static void
1446linker_preload(void *arg)
1447{
1448	caddr_t modptr;
1449	const char *modname, *nmodname;
1450	char *modtype;
1451	linker_file_t lf, nlf;
1452	linker_class_t lc;
1453	int error;
1454	linker_file_list_t loaded_files;
1455	linker_file_list_t depended_files;
1456	struct mod_metadata *mp, *nmp;
1457	struct mod_metadata **start, **stop, **mdp, **nmdp;
1458	struct mod_depend *verinfo;
1459	int nver;
1460	int resolves;
1461	modlist_t mod;
1462	struct sysinit **si_start, **si_stop;
1463
1464	TAILQ_INIT(&loaded_files);
1465	TAILQ_INIT(&depended_files);
1466	TAILQ_INIT(&found_modules);
1467	error = 0;
1468
1469	modptr = NULL;
1470	while ((modptr = preload_search_next_name(modptr)) != NULL) {
1471		modname = (char *)preload_search_info(modptr, MODINFO_NAME);
1472		modtype = (char *)preload_search_info(modptr, MODINFO_TYPE);
1473		if (modname == NULL) {
1474			printf("Preloaded module at %p does not have a"
1475			    " name!\n", modptr);
1476			continue;
1477		}
1478		if (modtype == NULL) {
1479			printf("Preloaded module at %p does not have a type!\n",
1480			    modptr);
1481			continue;
1482		}
1483		if (bootverbose)
1484			printf("Preloaded %s \"%s\" at %p.\n", modtype, modname,
1485			    modptr);
1486		lf = NULL;
1487		TAILQ_FOREACH(lc, &classes, link) {
1488			error = LINKER_LINK_PRELOAD(lc, modname, &lf);
1489			if (!error)
1490				break;
1491			lf = NULL;
1492		}
1493		if (lf)
1494			TAILQ_INSERT_TAIL(&loaded_files, lf, loaded);
1495	}
1496
1497	/*
1498	 * First get a list of stuff in the kernel.
1499	 */
1500	if (linker_file_lookup_set(linker_kernel_file, MDT_SETNAME, &start,
1501	    &stop, NULL) == 0)
1502		linker_addmodules(linker_kernel_file, start, stop, 1);
1503
1504	/*
1505	 * This is a once-off kinky bubble sort to resolve relocation
1506	 * dependency requirements.
1507	 */
1508restart:
1509	TAILQ_FOREACH(lf, &loaded_files, loaded) {
1510		error = linker_file_lookup_set(lf, MDT_SETNAME, &start,
1511		    &stop, NULL);
1512		/*
1513		 * First, look to see if we would successfully link with this
1514		 * stuff.
1515		 */
1516		resolves = 1;	/* unless we know otherwise */
1517		if (!error) {
1518			for (mdp = start; mdp < stop; mdp++) {
1519				mp = *mdp;
1520				if (mp->md_type != MDT_DEPEND)
1521					continue;
1522				modname = mp->md_cval;
1523				verinfo = mp->md_data;
1524				for (nmdp = start; nmdp < stop; nmdp++) {
1525					nmp = *nmdp;
1526					if (nmp->md_type != MDT_VERSION)
1527						continue;
1528					nmodname = nmp->md_cval;
1529					if (strcmp(modname, nmodname) == 0)
1530						break;
1531				}
1532				if (nmdp < stop)   /* it's a self reference */
1533					continue;
1534
1535				/*
1536				 * ok, the module isn't here yet, we
1537				 * are not finished
1538				 */
1539				if (modlist_lookup2(modname, verinfo) == NULL)
1540					resolves = 0;
1541			}
1542		}
1543		/*
1544		 * OK, if we found our modules, we can link.  So, "provide"
1545		 * the modules inside and add it to the end of the link order
1546		 * list.
1547		 */
1548		if (resolves) {
1549			if (!error) {
1550				for (mdp = start; mdp < stop; mdp++) {
1551					mp = *mdp;
1552					if (mp->md_type != MDT_VERSION)
1553						continue;
1554					modname = mp->md_cval;
1555					nver = ((struct mod_version *)
1556					    mp->md_data)->mv_version;
1557					if (modlist_lookup(modname,
1558					    nver) != NULL) {
1559						printf("module %s already"
1560						    " present!\n", modname);
1561						TAILQ_REMOVE(&loaded_files,
1562						    lf, loaded);
1563						linker_file_unload(lf,
1564						    LINKER_UNLOAD_FORCE);
1565						/* we changed tailq next ptr */
1566						goto restart;
1567					}
1568					modlist_newmodule(modname, nver, lf);
1569				}
1570			}
1571			TAILQ_REMOVE(&loaded_files, lf, loaded);
1572			TAILQ_INSERT_TAIL(&depended_files, lf, loaded);
1573			/*
1574			 * Since we provided modules, we need to restart the
1575			 * sort so that the previous files that depend on us
1576			 * have a chance. Also, we've busted the tailq next
1577			 * pointer with the REMOVE.
1578			 */
1579			goto restart;
1580		}
1581	}
1582
1583	/*
1584	 * At this point, we check to see what could not be resolved..
1585	 */
1586	while ((lf = TAILQ_FIRST(&loaded_files)) != NULL) {
1587		TAILQ_REMOVE(&loaded_files, lf, loaded);
1588		printf("KLD file %s is missing dependencies\n", lf->filename);
1589		linker_file_unload(lf, LINKER_UNLOAD_FORCE);
1590	}
1591
1592	/*
1593	 * We made it. Finish off the linking in the order we determined.
1594	 */
1595	TAILQ_FOREACH_SAFE(lf, &depended_files, loaded, nlf) {
1596		if (linker_kernel_file) {
1597			linker_kernel_file->refs++;
1598			error = linker_file_add_dependency(lf,
1599			    linker_kernel_file);
1600			if (error)
1601				panic("cannot add dependency");
1602		}
1603		lf->userrefs++;	/* so we can (try to) kldunload it */
1604		error = linker_file_lookup_set(lf, MDT_SETNAME, &start,
1605		    &stop, NULL);
1606		if (!error) {
1607			for (mdp = start; mdp < stop; mdp++) {
1608				mp = *mdp;
1609				if (mp->md_type != MDT_DEPEND)
1610					continue;
1611				modname = mp->md_cval;
1612				verinfo = mp->md_data;
1613				mod = modlist_lookup2(modname, verinfo);
1614				if (mod == NULL) {
1615					printf("KLD file %s - cannot find "
1616					    "dependency \"%s\"\n",
1617					    lf->filename, modname);
1618					goto fail;
1619				}
1620				/* Don't count self-dependencies */
1621				if (lf == mod->container)
1622					continue;
1623				mod->container->refs++;
1624				error = linker_file_add_dependency(lf,
1625				    mod->container);
1626				if (error)
1627					panic("cannot add dependency");
1628			}
1629		}
1630		/*
1631		 * Now do relocation etc using the symbol search paths
1632		 * established by the dependencies
1633		 */
1634		error = LINKER_LINK_PRELOAD_FINISH(lf);
1635		if (error) {
1636			printf("KLD file %s - could not finalize loading\n",
1637			    lf->filename);
1638			goto fail;
1639		}
1640		linker_file_register_modules(lf);
1641		if (linker_file_lookup_set(lf, "sysinit_set", &si_start,
1642		    &si_stop, NULL) == 0)
1643			sysinit_add(si_start, si_stop);
1644		linker_file_register_sysctls(lf);
1645		lf->flags |= LINKER_FILE_LINKED;
1646		continue;
1647fail:
1648		TAILQ_REMOVE(&depended_files, lf, loaded);
1649		linker_file_unload(lf, LINKER_UNLOAD_FORCE);
1650	}
1651	/* woohoo! we made it! */
1652}
1653
1654SYSINIT(preload, SI_SUB_KLD, SI_ORDER_MIDDLE, linker_preload, 0);
1655
1656/*
1657 * Search for a not-loaded module by name.
1658 *
1659 * Modules may be found in the following locations:
1660 *
1661 * - preloaded (result is just the module name) - on disk (result is full path
1662 * to module)
1663 *
1664 * If the module name is qualified in any way (contains path, etc.) the we
1665 * simply return a copy of it.
1666 *
1667 * The search path can be manipulated via sysctl.  Note that we use the ';'
1668 * character as a separator to be consistent with the bootloader.
1669 */
1670
1671static char linker_hintfile[] = "linker.hints";
1672static char linker_path[MAXPATHLEN] = "/boot/kernel;/boot/modules";
1673
1674SYSCTL_STRING(_kern, OID_AUTO, module_path, CTLFLAG_RW, linker_path,
1675    sizeof(linker_path), "module load search path");
1676
1677TUNABLE_STR("module_path", linker_path, sizeof(linker_path));
1678
1679static char *linker_ext_list[] = {
1680	"",
1681	".ko",
1682	NULL
1683};
1684
1685/*
1686 * Check if file actually exists either with or without extension listed in
1687 * the linker_ext_list. (probably should be generic for the rest of the
1688 * kernel)
1689 */
1690static char *
1691linker_lookup_file(const char *path, int pathlen, const char *name,
1692    int namelen, struct vattr *vap)
1693{
1694	struct nameidata nd;
1695	struct thread *td = curthread;	/* XXX */
1696	char *result, **cpp, *sep;
1697	int error, len, extlen, reclen, flags, vfslocked;
1698	enum vtype type;
1699
1700	extlen = 0;
1701	for (cpp = linker_ext_list; *cpp; cpp++) {
1702		len = strlen(*cpp);
1703		if (len > extlen)
1704			extlen = len;
1705	}
1706	extlen++;		/* trailing '\0' */
1707	sep = (path[pathlen - 1] != '/') ? "/" : "";
1708
1709	reclen = pathlen + strlen(sep) + namelen + extlen + 1;
1710	result = malloc(reclen, M_LINKER, M_WAITOK);
1711	for (cpp = linker_ext_list; *cpp; cpp++) {
1712		snprintf(result, reclen, "%.*s%s%.*s%s", pathlen, path, sep,
1713		    namelen, name, *cpp);
1714		/*
1715		 * Attempt to open the file, and return the path if
1716		 * we succeed and it's a regular file.
1717		 */
1718		NDINIT(&nd, LOOKUP, FOLLOW | MPSAFE, UIO_SYSSPACE, result, td);
1719		flags = FREAD;
1720		error = vn_open(&nd, &flags, 0, NULL);
1721		if (error == 0) {
1722			vfslocked = NDHASGIANT(&nd);
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			VFS_UNLOCK_GIANT(vfslocked);
1730			if (type == VREG)
1731				return (result);
1732		}
1733	}
1734	free(result, M_LINKER);
1735	return (NULL);
1736}
1737
1738#define	INT_ALIGN(base, ptr)	ptr =					\
1739	(base) + (((ptr) - (base) + sizeof(int) - 1) & ~(sizeof(int) - 1))
1740
1741/*
1742 * Lookup KLD which contains requested module in the "linker.hints" file. If
1743 * version specification is available, then try to find the best KLD.
1744 * Otherwise just find the latest one.
1745 */
1746static char *
1747linker_hints_lookup(const char *path, int pathlen, const char *modname,
1748    int modnamelen, struct mod_depend *verinfo)
1749{
1750	struct thread *td = curthread;	/* XXX */
1751	struct ucred *cred = td ? td->td_ucred : NULL;
1752	struct nameidata nd;
1753	struct vattr vattr, mattr;
1754	u_char *hints = NULL;
1755	u_char *cp, *recptr, *bufend, *result, *best, *pathbuf, *sep;
1756	int error, ival, bestver, *intp, found, flags, clen, blen;
1757	ssize_t reclen;
1758	int vfslocked = 0;
1759
1760	result = NULL;
1761	bestver = found = 0;
1762
1763	sep = (path[pathlen - 1] != '/') ? "/" : "";
1764	reclen = imax(modnamelen, strlen(linker_hintfile)) + pathlen +
1765	    strlen(sep) + 1;
1766	pathbuf = malloc(reclen, M_LINKER, M_WAITOK);
1767	snprintf(pathbuf, reclen, "%.*s%s%s", pathlen, path, sep,
1768	    linker_hintfile);
1769
1770	NDINIT(&nd, LOOKUP, NOFOLLOW | MPSAFE, UIO_SYSSPACE, pathbuf, td);
1771	flags = FREAD;
1772	error = vn_open(&nd, &flags, 0, NULL);
1773	if (error)
1774		goto bad;
1775	vfslocked = NDHASGIANT(&nd);
1776	NDFREE(&nd, NDF_ONLY_PNBUF);
1777	if (nd.ni_vp->v_type != VREG)
1778		goto bad;
1779	best = cp = NULL;
1780	error = VOP_GETATTR(nd.ni_vp, &vattr, cred);
1781	if (error)
1782		goto bad;
1783	/*
1784	 * XXX: we need to limit this number to some reasonable value
1785	 */
1786	if (vattr.va_size > 100 * 1024) {
1787		printf("hints file too large %ld\n", (long)vattr.va_size);
1788		goto bad;
1789	}
1790	hints = malloc(vattr.va_size, M_TEMP, M_WAITOK);
1791	if (hints == NULL)
1792		goto bad;
1793	error = vn_rdwr(UIO_READ, nd.ni_vp, (caddr_t)hints, vattr.va_size, 0,
1794	    UIO_SYSSPACE, IO_NODELOCKED, cred, NOCRED, &reclen, td);
1795	if (error)
1796		goto bad;
1797	VOP_UNLOCK(nd.ni_vp, 0);
1798	vn_close(nd.ni_vp, FREAD, cred, td);
1799	VFS_UNLOCK_GIANT(vfslocked);
1800	nd.ni_vp = NULL;
1801	if (reclen != 0) {
1802		printf("can't read %zd\n", reclen);
1803		goto bad;
1804	}
1805	intp = (int *)hints;
1806	ival = *intp++;
1807	if (ival != LINKER_HINTS_VERSION) {
1808		printf("hints file version mismatch %d\n", ival);
1809		goto bad;
1810	}
1811	bufend = hints + vattr.va_size;
1812	recptr = (u_char *)intp;
1813	clen = blen = 0;
1814	while (recptr < bufend && !found) {
1815		intp = (int *)recptr;
1816		reclen = *intp++;
1817		ival = *intp++;
1818		cp = (char *)intp;
1819		switch (ival) {
1820		case MDT_VERSION:
1821			clen = *cp++;
1822			if (clen != modnamelen || bcmp(cp, modname, clen) != 0)
1823				break;
1824			cp += clen;
1825			INT_ALIGN(hints, cp);
1826			ival = *(int *)cp;
1827			cp += sizeof(int);
1828			clen = *cp++;
1829			if (verinfo == NULL ||
1830			    ival == verinfo->md_ver_preferred) {
1831				found = 1;
1832				break;
1833			}
1834			if (ival >= verinfo->md_ver_minimum &&
1835			    ival <= verinfo->md_ver_maximum &&
1836			    ival > bestver) {
1837				bestver = ival;
1838				best = cp;
1839				blen = clen;
1840			}
1841			break;
1842		default:
1843			break;
1844		}
1845		recptr += reclen + sizeof(int);
1846	}
1847	/*
1848	 * Finally check if KLD is in the place
1849	 */
1850	if (found)
1851		result = linker_lookup_file(path, pathlen, cp, clen, &mattr);
1852	else if (best)
1853		result = linker_lookup_file(path, pathlen, best, blen, &mattr);
1854
1855	/*
1856	 * KLD is newer than hints file. What we should do now?
1857	 */
1858	if (result && timespeccmp(&mattr.va_mtime, &vattr.va_mtime, >))
1859		printf("warning: KLD '%s' is newer than the linker.hints"
1860		    " file\n", result);
1861bad:
1862	free(pathbuf, M_LINKER);
1863	if (hints)
1864		free(hints, M_TEMP);
1865	if (nd.ni_vp != NULL) {
1866		VOP_UNLOCK(nd.ni_vp, 0);
1867		vn_close(nd.ni_vp, FREAD, cred, td);
1868		VFS_UNLOCK_GIANT(vfslocked);
1869	}
1870	/*
1871	 * If nothing found or hints is absent - fallback to the old
1872	 * way by using "kldname[.ko]" as module name.
1873	 */
1874	if (!found && !bestver && result == NULL)
1875		result = linker_lookup_file(path, pathlen, modname,
1876		    modnamelen, NULL);
1877	return (result);
1878}
1879
1880/*
1881 * Lookup KLD which contains requested module in the all directories.
1882 */
1883static char *
1884linker_search_module(const char *modname, int modnamelen,
1885    struct mod_depend *verinfo)
1886{
1887	char *cp, *ep, *result;
1888
1889	/*
1890	 * traverse the linker path
1891	 */
1892	for (cp = linker_path; *cp; cp = ep + 1) {
1893		/* find the end of this component */
1894		for (ep = cp; (*ep != 0) && (*ep != ';'); ep++);
1895		result = linker_hints_lookup(cp, ep - cp, modname,
1896		    modnamelen, verinfo);
1897		if (result != NULL)
1898			return (result);
1899		if (*ep == 0)
1900			break;
1901	}
1902	return (NULL);
1903}
1904
1905/*
1906 * Search for module in all directories listed in the linker_path.
1907 */
1908static char *
1909linker_search_kld(const char *name)
1910{
1911	char *cp, *ep, *result;
1912	int len;
1913
1914	/* qualified at all? */
1915	if (strchr(name, '/'))
1916		return (linker_strdup(name));
1917
1918	/* traverse the linker path */
1919	len = strlen(name);
1920	for (ep = linker_path; *ep; ep++) {
1921		cp = ep;
1922		/* find the end of this component */
1923		for (; *ep != 0 && *ep != ';'; ep++);
1924		result = linker_lookup_file(cp, ep - cp, name, len, NULL);
1925		if (result != NULL)
1926			return (result);
1927	}
1928	return (NULL);
1929}
1930
1931static const char *
1932linker_basename(const char *path)
1933{
1934	const char *filename;
1935
1936	filename = strrchr(path, '/');
1937	if (filename == NULL)
1938		return path;
1939	if (filename[1])
1940		filename++;
1941	return (filename);
1942}
1943
1944#ifdef HWPMC_HOOKS
1945/*
1946 * Inform hwpmc about the set of kernel modules currently loaded.
1947 */
1948void *
1949linker_hwpmc_list_objects(void)
1950{
1951	linker_file_t lf;
1952	struct pmckern_map_in *kobase;
1953	int i, nmappings;
1954
1955	nmappings = 0;
1956	KLD_LOCK_READ();
1957	TAILQ_FOREACH(lf, &linker_files, link)
1958		nmappings++;
1959
1960	/* Allocate nmappings + 1 entries. */
1961	kobase = malloc((nmappings + 1) * sizeof(struct pmckern_map_in),
1962	    M_LINKER, M_WAITOK | M_ZERO);
1963	i = 0;
1964	TAILQ_FOREACH(lf, &linker_files, link) {
1965
1966		/* Save the info for this linker file. */
1967		kobase[i].pm_file = lf->filename;
1968		kobase[i].pm_address = (uintptr_t)lf->address;
1969		i++;
1970	}
1971	KLD_UNLOCK_READ();
1972
1973	KASSERT(i > 0, ("linker_hpwmc_list_objects: no kernel objects?"));
1974
1975	/* The last entry of the malloced area comprises of all zeros. */
1976	KASSERT(kobase[i].pm_file == NULL,
1977	    ("linker_hwpmc_list_objects: last object not NULL"));
1978
1979	return ((void *)kobase);
1980}
1981#endif
1982
1983/*
1984 * Find a file which contains given module and load it, if "parent" is not
1985 * NULL, register a reference to it.
1986 */
1987static int
1988linker_load_module(const char *kldname, const char *modname,
1989    struct linker_file *parent, struct mod_depend *verinfo,
1990    struct linker_file **lfpp)
1991{
1992	linker_file_t lfdep;
1993	const char *filename;
1994	char *pathname;
1995	int error;
1996
1997	KLD_LOCK_ASSERT();
1998	if (modname == NULL) {
1999		/*
2000 		 * We have to load KLD
2001 		 */
2002		KASSERT(verinfo == NULL, ("linker_load_module: verinfo"
2003		    " is not NULL"));
2004		pathname = linker_search_kld(kldname);
2005	} else {
2006		if (modlist_lookup2(modname, verinfo) != NULL)
2007			return (EEXIST);
2008		if (kldname != NULL)
2009			pathname = linker_strdup(kldname);
2010		else if (rootvnode == NULL)
2011			pathname = NULL;
2012		else
2013			/*
2014			 * Need to find a KLD with required module
2015			 */
2016			pathname = linker_search_module(modname,
2017			    strlen(modname), verinfo);
2018	}
2019	if (pathname == NULL)
2020		return (ENOENT);
2021
2022	/*
2023	 * Can't load more than one file with the same basename XXX:
2024	 * Actually it should be possible to have multiple KLDs with
2025	 * the same basename but different path because they can
2026	 * provide different versions of the same modules.
2027	 */
2028	filename = linker_basename(pathname);
2029	if (linker_find_file_by_name(filename))
2030		error = EEXIST;
2031	else do {
2032		error = linker_load_file(pathname, &lfdep);
2033		if (error)
2034			break;
2035		if (modname && verinfo &&
2036		    modlist_lookup2(modname, verinfo) == NULL) {
2037			linker_file_unload(lfdep, LINKER_UNLOAD_FORCE);
2038			error = ENOENT;
2039			break;
2040		}
2041		if (parent) {
2042			error = linker_file_add_dependency(parent, lfdep);
2043			if (error)
2044				break;
2045		}
2046		if (lfpp)
2047			*lfpp = lfdep;
2048	} while (0);
2049	free(pathname, M_LINKER);
2050	return (error);
2051}
2052
2053/*
2054 * This routine is responsible for finding dependencies of userland initiated
2055 * kldload(2)'s of files.
2056 */
2057int
2058linker_load_dependencies(linker_file_t lf)
2059{
2060	linker_file_t lfdep;
2061	struct mod_metadata **start, **stop, **mdp, **nmdp;
2062	struct mod_metadata *mp, *nmp;
2063	struct mod_depend *verinfo;
2064	modlist_t mod;
2065	const char *modname, *nmodname;
2066	int ver, error = 0, count;
2067
2068	/*
2069	 * All files are dependant on /kernel.
2070	 */
2071	KLD_LOCK_ASSERT();
2072	if (linker_kernel_file) {
2073		linker_kernel_file->refs++;
2074		error = linker_file_add_dependency(lf, linker_kernel_file);
2075		if (error)
2076			return (error);
2077	}
2078	if (linker_file_lookup_set(lf, MDT_SETNAME, &start, &stop,
2079	    &count) != 0)
2080		return (0);
2081	for (mdp = start; mdp < stop; mdp++) {
2082		mp = *mdp;
2083		if (mp->md_type != MDT_VERSION)
2084			continue;
2085		modname = mp->md_cval;
2086		ver = ((struct mod_version *)mp->md_data)->mv_version;
2087		mod = modlist_lookup(modname, ver);
2088		if (mod != NULL) {
2089			printf("interface %s.%d already present in the KLD"
2090			    " '%s'!\n", modname, ver,
2091			    mod->container->filename);
2092			return (EEXIST);
2093		}
2094	}
2095
2096	for (mdp = start; mdp < stop; mdp++) {
2097		mp = *mdp;
2098		if (mp->md_type != MDT_DEPEND)
2099			continue;
2100		modname = mp->md_cval;
2101		verinfo = mp->md_data;
2102		nmodname = NULL;
2103		for (nmdp = start; nmdp < stop; nmdp++) {
2104			nmp = *nmdp;
2105			if (nmp->md_type != MDT_VERSION)
2106				continue;
2107			nmodname = nmp->md_cval;
2108			if (strcmp(modname, nmodname) == 0)
2109				break;
2110		}
2111		if (nmdp < stop)/* early exit, it's a self reference */
2112			continue;
2113		mod = modlist_lookup2(modname, verinfo);
2114		if (mod) {	/* woohoo, it's loaded already */
2115			lfdep = mod->container;
2116			lfdep->refs++;
2117			error = linker_file_add_dependency(lf, lfdep);
2118			if (error)
2119				break;
2120			continue;
2121		}
2122		error = linker_load_module(NULL, modname, lf, verinfo, NULL);
2123		if (error) {
2124			printf("KLD %s: depends on %s - not available or"
2125			    " version mismatch\n", lf->filename, modname);
2126			break;
2127		}
2128	}
2129
2130	if (error)
2131		return (error);
2132	linker_addmodules(lf, start, stop, 0);
2133	return (error);
2134}
2135
2136static int
2137sysctl_kern_function_list_iterate(const char *name, void *opaque)
2138{
2139	struct sysctl_req *req;
2140
2141	req = opaque;
2142	return (SYSCTL_OUT(req, name, strlen(name) + 1));
2143}
2144
2145/*
2146 * Export a nul-separated, double-nul-terminated list of all function names
2147 * in the kernel.
2148 */
2149static int
2150sysctl_kern_function_list(SYSCTL_HANDLER_ARGS)
2151{
2152	linker_file_t lf;
2153	int error;
2154
2155#ifdef MAC
2156	error = mac_kld_check_stat(req->td->td_ucred);
2157	if (error)
2158		return (error);
2159#endif
2160	error = sysctl_wire_old_buffer(req, 0);
2161	if (error != 0)
2162		return (error);
2163	KLD_LOCK();
2164	TAILQ_FOREACH(lf, &linker_files, link) {
2165		error = LINKER_EACH_FUNCTION_NAME(lf,
2166		    sysctl_kern_function_list_iterate, req);
2167		if (error) {
2168			KLD_UNLOCK();
2169			return (error);
2170		}
2171	}
2172	KLD_UNLOCK();
2173	return (SYSCTL_OUT(req, "", 1));
2174}
2175
2176SYSCTL_PROC(_kern, OID_AUTO, function_list, CTLTYPE_OPAQUE | CTLFLAG_RD,
2177    NULL, 0, sysctl_kern_function_list, "", "kernel function list");
2178