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