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