kern_linker.c revision 267985
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 267985 2014-06-27 22:05:21Z gjb $");
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	file->deps = realloc(file->deps, (file->ndeps + 1) * sizeof(*newdeps),
729	    M_LINKER, M_WAITOK | M_ZERO);
730	file->deps[file->ndeps] = dep;
731	file->ndeps++;
732	KLD_DPF(FILE, ("linker_file_add_dependency:"
733	    " adding %s as dependency for %s\n",
734	    dep->filename, file->filename));
735	return (0);
736}
737
738/*
739 * Locate a linker set and its contents.  This is a helper function to avoid
740 * linker_if.h exposure elsewhere.  Note: firstp and lastp are really void **.
741 * This function is used in this file so we can avoid having lots of (void **)
742 * casts.
743 */
744int
745linker_file_lookup_set(linker_file_t file, const char *name,
746    void *firstp, void *lastp, int *countp)
747{
748
749	sx_assert(&kld_sx, SA_LOCKED);
750	return (LINKER_LOOKUP_SET(file, name, firstp, lastp, countp));
751}
752
753/*
754 * List all functions in a file.
755 */
756int
757linker_file_function_listall(linker_file_t lf,
758    linker_function_nameval_callback_t callback_func, void *arg)
759{
760	return (LINKER_EACH_FUNCTION_NAMEVAL(lf, callback_func, arg));
761}
762
763caddr_t
764linker_file_lookup_symbol(linker_file_t file, const char *name, int deps)
765{
766	caddr_t sym;
767	int locked;
768
769	locked = sx_xlocked(&kld_sx);
770	if (!locked)
771		sx_xlock(&kld_sx);
772	sym = linker_file_lookup_symbol_internal(file, name, deps);
773	if (!locked)
774		sx_xunlock(&kld_sx);
775	return (sym);
776}
777
778static caddr_t
779linker_file_lookup_symbol_internal(linker_file_t file, const char *name,
780    int deps)
781{
782	c_linker_sym_t sym;
783	linker_symval_t symval;
784	caddr_t address;
785	size_t common_size = 0;
786	int i;
787
788	sx_assert(&kld_sx, SA_XLOCKED);
789	KLD_DPF(SYM, ("linker_file_lookup_symbol: file=%p, name=%s, deps=%d\n",
790	    file, name, deps));
791
792	if (LINKER_LOOKUP_SYMBOL(file, name, &sym) == 0) {
793		LINKER_SYMBOL_VALUES(file, sym, &symval);
794		if (symval.value == 0)
795			/*
796			 * For commons, first look them up in the
797			 * dependencies and only allocate space if not found
798			 * there.
799			 */
800			common_size = symval.size;
801		else {
802			KLD_DPF(SYM, ("linker_file_lookup_symbol: symbol"
803			    ".value=%p\n", symval.value));
804			return (symval.value);
805		}
806	}
807	if (deps) {
808		for (i = 0; i < file->ndeps; i++) {
809			address = linker_file_lookup_symbol_internal(
810			    file->deps[i], name, 0);
811			if (address) {
812				KLD_DPF(SYM, ("linker_file_lookup_symbol:"
813				    " deps value=%p\n", address));
814				return (address);
815			}
816		}
817	}
818	if (common_size > 0) {
819		/*
820		 * This is a common symbol which was not found in the
821		 * dependencies.  We maintain a simple common symbol table in
822		 * the file object.
823		 */
824		struct common_symbol *cp;
825
826		STAILQ_FOREACH(cp, &file->common, link) {
827			if (strcmp(cp->name, name) == 0) {
828				KLD_DPF(SYM, ("linker_file_lookup_symbol:"
829				    " old common value=%p\n", cp->address));
830				return (cp->address);
831			}
832		}
833		/*
834		 * Round the symbol size up to align.
835		 */
836		common_size = (common_size + sizeof(int) - 1) & -sizeof(int);
837		cp = malloc(sizeof(struct common_symbol)
838		    + common_size + strlen(name) + 1, M_LINKER,
839		    M_WAITOK | M_ZERO);
840		cp->address = (caddr_t)(cp + 1);
841		cp->name = cp->address + common_size;
842		strcpy(cp->name, name);
843		bzero(cp->address, common_size);
844		STAILQ_INSERT_TAIL(&file->common, cp, link);
845
846		KLD_DPF(SYM, ("linker_file_lookup_symbol: new common"
847		    " value=%p\n", cp->address));
848		return (cp->address);
849	}
850	KLD_DPF(SYM, ("linker_file_lookup_symbol: fail\n"));
851	return (0);
852}
853
854/*
855 * Both DDB and stack(9) rely on the kernel linker to provide forward and
856 * backward lookup of symbols.  However, DDB and sometimes stack(9) need to
857 * do this in a lockfree manner.  We provide a set of internal helper
858 * routines to perform these operations without locks, and then wrappers that
859 * optionally lock.
860 *
861 * linker_debug_lookup() is ifdef DDB as currently it's only used by DDB.
862 */
863#ifdef DDB
864static int
865linker_debug_lookup(const char *symstr, c_linker_sym_t *sym)
866{
867	linker_file_t lf;
868
869	TAILQ_FOREACH(lf, &linker_files, link) {
870		if (LINKER_LOOKUP_SYMBOL(lf, symstr, sym) == 0)
871			return (0);
872	}
873	return (ENOENT);
874}
875#endif
876
877static int
878linker_debug_search_symbol(caddr_t value, c_linker_sym_t *sym, long *diffp)
879{
880	linker_file_t lf;
881	c_linker_sym_t best, es;
882	u_long diff, bestdiff, off;
883
884	best = 0;
885	off = (uintptr_t)value;
886	bestdiff = off;
887	TAILQ_FOREACH(lf, &linker_files, link) {
888		if (LINKER_SEARCH_SYMBOL(lf, value, &es, &diff) != 0)
889			continue;
890		if (es != 0 && diff < bestdiff) {
891			best = es;
892			bestdiff = diff;
893		}
894		if (bestdiff == 0)
895			break;
896	}
897	if (best) {
898		*sym = best;
899		*diffp = bestdiff;
900		return (0);
901	} else {
902		*sym = 0;
903		*diffp = off;
904		return (ENOENT);
905	}
906}
907
908static int
909linker_debug_symbol_values(c_linker_sym_t sym, linker_symval_t *symval)
910{
911	linker_file_t lf;
912
913	TAILQ_FOREACH(lf, &linker_files, link) {
914		if (LINKER_SYMBOL_VALUES(lf, sym, symval) == 0)
915			return (0);
916	}
917	return (ENOENT);
918}
919
920static int
921linker_debug_search_symbol_name(caddr_t value, char *buf, u_int buflen,
922    long *offset)
923{
924	linker_symval_t symval;
925	c_linker_sym_t sym;
926	int error;
927
928	*offset = 0;
929	error = linker_debug_search_symbol(value, &sym, offset);
930	if (error)
931		return (error);
932	error = linker_debug_symbol_values(sym, &symval);
933	if (error)
934		return (error);
935	strlcpy(buf, symval.name, buflen);
936	return (0);
937}
938
939/*
940 * DDB Helpers.  DDB has to look across multiple files with their own symbol
941 * tables and string tables.
942 *
943 * Note that we do not obey list locking protocols here.  We really don't need
944 * DDB to hang because somebody's got the lock held.  We'll take the chance
945 * that the files list is inconsistant instead.
946 */
947#ifdef DDB
948int
949linker_ddb_lookup(const char *symstr, c_linker_sym_t *sym)
950{
951
952	return (linker_debug_lookup(symstr, sym));
953}
954#endif
955
956int
957linker_ddb_search_symbol(caddr_t value, c_linker_sym_t *sym, long *diffp)
958{
959
960	return (linker_debug_search_symbol(value, sym, diffp));
961}
962
963int
964linker_ddb_symbol_values(c_linker_sym_t sym, linker_symval_t *symval)
965{
966
967	return (linker_debug_symbol_values(sym, symval));
968}
969
970int
971linker_ddb_search_symbol_name(caddr_t value, char *buf, u_int buflen,
972    long *offset)
973{
974
975	return (linker_debug_search_symbol_name(value, buf, buflen, offset));
976}
977
978/*
979 * stack(9) helper for non-debugging environemnts.  Unlike DDB helpers, we do
980 * obey locking protocols, and offer a significantly less complex interface.
981 */
982int
983linker_search_symbol_name(caddr_t value, char *buf, u_int buflen,
984    long *offset)
985{
986	int error;
987
988	sx_xlock(&kld_sx);
989	error = linker_debug_search_symbol_name(value, buf, buflen, offset);
990	sx_xunlock(&kld_sx);
991	return (error);
992}
993
994/*
995 * Syscalls.
996 */
997int
998kern_kldload(struct thread *td, const char *file, int *fileid)
999{
1000	const char *kldname, *modname;
1001	linker_file_t lf;
1002	int error;
1003
1004	if ((error = securelevel_gt(td->td_ucred, 0)) != 0)
1005		return (error);
1006
1007	if ((error = priv_check(td, PRIV_KLD_LOAD)) != 0)
1008		return (error);
1009
1010	/*
1011	 * It is possible that kldloaded module will attach a new ifnet,
1012	 * so vnet context must be set when this ocurs.
1013	 */
1014	CURVNET_SET(TD_TO_VNET(td));
1015
1016	/*
1017	 * If file does not contain a qualified name or any dot in it
1018	 * (kldname.ko, or kldname.ver.ko) treat it as an interface
1019	 * name.
1020	 */
1021	if (strchr(file, '/') || strchr(file, '.')) {
1022		kldname = file;
1023		modname = NULL;
1024	} else {
1025		kldname = NULL;
1026		modname = file;
1027	}
1028
1029	sx_xlock(&kld_sx);
1030	error = linker_load_module(kldname, modname, NULL, NULL, &lf);
1031	if (error) {
1032		sx_xunlock(&kld_sx);
1033		goto done;
1034	}
1035	lf->userrefs++;
1036	if (fileid != NULL)
1037		*fileid = lf->id;
1038	sx_xunlock(&kld_sx);
1039
1040done:
1041	CURVNET_RESTORE();
1042	return (error);
1043}
1044
1045int
1046sys_kldload(struct thread *td, struct kldload_args *uap)
1047{
1048	char *pathname = NULL;
1049	int error, fileid;
1050
1051	td->td_retval[0] = -1;
1052
1053	pathname = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
1054	error = copyinstr(uap->file, pathname, MAXPATHLEN, NULL);
1055	if (error == 0) {
1056		error = kern_kldload(td, pathname, &fileid);
1057		if (error == 0)
1058			td->td_retval[0] = fileid;
1059	}
1060	free(pathname, M_TEMP);
1061	return (error);
1062}
1063
1064int
1065kern_kldunload(struct thread *td, int fileid, int flags)
1066{
1067	linker_file_t lf;
1068	int error = 0;
1069
1070	if ((error = securelevel_gt(td->td_ucred, 0)) != 0)
1071		return (error);
1072
1073	if ((error = priv_check(td, PRIV_KLD_UNLOAD)) != 0)
1074		return (error);
1075
1076	CURVNET_SET(TD_TO_VNET(td));
1077	sx_xlock(&kld_sx);
1078	lf = linker_find_file_by_id(fileid);
1079	if (lf) {
1080		KLD_DPF(FILE, ("kldunload: lf->userrefs=%d\n", lf->userrefs));
1081
1082		if (lf->userrefs == 0) {
1083			/*
1084			 * XXX: maybe LINKER_UNLOAD_FORCE should override ?
1085			 */
1086			printf("kldunload: attempt to unload file that was"
1087			    " loaded by the kernel\n");
1088			error = EBUSY;
1089		} else {
1090			lf->userrefs--;
1091			error = linker_file_unload(lf, flags);
1092			if (error)
1093				lf->userrefs++;
1094		}
1095	} else
1096		error = ENOENT;
1097	sx_xunlock(&kld_sx);
1098
1099	CURVNET_RESTORE();
1100	return (error);
1101}
1102
1103int
1104sys_kldunload(struct thread *td, struct kldunload_args *uap)
1105{
1106
1107	return (kern_kldunload(td, uap->fileid, LINKER_UNLOAD_NORMAL));
1108}
1109
1110int
1111sys_kldunloadf(struct thread *td, struct kldunloadf_args *uap)
1112{
1113
1114	if (uap->flags != LINKER_UNLOAD_NORMAL &&
1115	    uap->flags != LINKER_UNLOAD_FORCE)
1116		return (EINVAL);
1117	return (kern_kldunload(td, uap->fileid, uap->flags));
1118}
1119
1120int
1121sys_kldfind(struct thread *td, struct kldfind_args *uap)
1122{
1123	char *pathname;
1124	const char *filename;
1125	linker_file_t lf;
1126	int error;
1127
1128#ifdef MAC
1129	error = mac_kld_check_stat(td->td_ucred);
1130	if (error)
1131		return (error);
1132#endif
1133
1134	td->td_retval[0] = -1;
1135
1136	pathname = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
1137	if ((error = copyinstr(uap->file, pathname, MAXPATHLEN, NULL)) != 0)
1138		goto out;
1139
1140	filename = linker_basename(pathname);
1141	sx_xlock(&kld_sx);
1142	lf = linker_find_file_by_name(filename);
1143	if (lf)
1144		td->td_retval[0] = lf->id;
1145	else
1146		error = ENOENT;
1147	sx_xunlock(&kld_sx);
1148out:
1149	free(pathname, M_TEMP);
1150	return (error);
1151}
1152
1153int
1154sys_kldnext(struct thread *td, struct kldnext_args *uap)
1155{
1156	linker_file_t lf;
1157	int error = 0;
1158
1159#ifdef MAC
1160	error = mac_kld_check_stat(td->td_ucred);
1161	if (error)
1162		return (error);
1163#endif
1164
1165	sx_xlock(&kld_sx);
1166	if (uap->fileid == 0)
1167		lf = TAILQ_FIRST(&linker_files);
1168	else {
1169		lf = linker_find_file_by_id(uap->fileid);
1170		if (lf == NULL) {
1171			error = ENOENT;
1172			goto out;
1173		}
1174		lf = TAILQ_NEXT(lf, link);
1175	}
1176
1177	/* Skip partially loaded files. */
1178	while (lf != NULL && !(lf->flags & LINKER_FILE_LINKED))
1179		lf = TAILQ_NEXT(lf, link);
1180
1181	if (lf)
1182		td->td_retval[0] = lf->id;
1183	else
1184		td->td_retval[0] = 0;
1185out:
1186	sx_xunlock(&kld_sx);
1187	return (error);
1188}
1189
1190int
1191sys_kldstat(struct thread *td, struct kldstat_args *uap)
1192{
1193	struct kld_file_stat stat;
1194	int error, version;
1195
1196	/*
1197	 * Check the version of the user's structure.
1198	 */
1199	if ((error = copyin(&uap->stat->version, &version, sizeof(version)))
1200	    != 0)
1201		return (error);
1202	if (version != sizeof(struct kld_file_stat_1) &&
1203	    version != sizeof(struct kld_file_stat))
1204		return (EINVAL);
1205
1206	error = kern_kldstat(td, uap->fileid, &stat);
1207	if (error != 0)
1208		return (error);
1209	return (copyout(&stat, uap->stat, version));
1210}
1211
1212int
1213kern_kldstat(struct thread *td, int fileid, struct kld_file_stat *stat)
1214{
1215	linker_file_t lf;
1216	int namelen;
1217#ifdef MAC
1218	int error;
1219
1220	error = mac_kld_check_stat(td->td_ucred);
1221	if (error)
1222		return (error);
1223#endif
1224
1225	sx_xlock(&kld_sx);
1226	lf = linker_find_file_by_id(fileid);
1227	if (lf == NULL) {
1228		sx_xunlock(&kld_sx);
1229		return (ENOENT);
1230	}
1231
1232	/* Version 1 fields: */
1233	namelen = strlen(lf->filename) + 1;
1234	if (namelen > MAXPATHLEN)
1235		namelen = MAXPATHLEN;
1236	bcopy(lf->filename, &stat->name[0], namelen);
1237	stat->refs = lf->refs;
1238	stat->id = lf->id;
1239	stat->address = lf->address;
1240	stat->size = lf->size;
1241	/* Version 2 fields: */
1242	namelen = strlen(lf->pathname) + 1;
1243	if (namelen > MAXPATHLEN)
1244		namelen = MAXPATHLEN;
1245	bcopy(lf->pathname, &stat->pathname[0], namelen);
1246	sx_xunlock(&kld_sx);
1247
1248	td->td_retval[0] = 0;
1249	return (0);
1250}
1251
1252int
1253sys_kldfirstmod(struct thread *td, struct kldfirstmod_args *uap)
1254{
1255	linker_file_t lf;
1256	module_t mp;
1257	int error = 0;
1258
1259#ifdef MAC
1260	error = mac_kld_check_stat(td->td_ucred);
1261	if (error)
1262		return (error);
1263#endif
1264
1265	sx_xlock(&kld_sx);
1266	lf = linker_find_file_by_id(uap->fileid);
1267	if (lf) {
1268		MOD_SLOCK;
1269		mp = TAILQ_FIRST(&lf->modules);
1270		if (mp != NULL)
1271			td->td_retval[0] = module_getid(mp);
1272		else
1273			td->td_retval[0] = 0;
1274		MOD_SUNLOCK;
1275	} else
1276		error = ENOENT;
1277	sx_xunlock(&kld_sx);
1278	return (error);
1279}
1280
1281int
1282sys_kldsym(struct thread *td, struct kldsym_args *uap)
1283{
1284	char *symstr = NULL;
1285	c_linker_sym_t sym;
1286	linker_symval_t symval;
1287	linker_file_t lf;
1288	struct kld_sym_lookup lookup;
1289	int error = 0;
1290
1291#ifdef MAC
1292	error = mac_kld_check_stat(td->td_ucred);
1293	if (error)
1294		return (error);
1295#endif
1296
1297	if ((error = copyin(uap->data, &lookup, sizeof(lookup))) != 0)
1298		return (error);
1299	if (lookup.version != sizeof(lookup) ||
1300	    uap->cmd != KLDSYM_LOOKUP)
1301		return (EINVAL);
1302	symstr = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
1303	if ((error = copyinstr(lookup.symname, symstr, MAXPATHLEN, NULL)) != 0)
1304		goto out;
1305	sx_xlock(&kld_sx);
1306	if (uap->fileid != 0) {
1307		lf = linker_find_file_by_id(uap->fileid);
1308		if (lf == NULL)
1309			error = ENOENT;
1310		else if (LINKER_LOOKUP_SYMBOL(lf, symstr, &sym) == 0 &&
1311		    LINKER_SYMBOL_VALUES(lf, sym, &symval) == 0) {
1312			lookup.symvalue = (uintptr_t) symval.value;
1313			lookup.symsize = symval.size;
1314			error = copyout(&lookup, uap->data, sizeof(lookup));
1315		} else
1316			error = ENOENT;
1317	} else {
1318		TAILQ_FOREACH(lf, &linker_files, link) {
1319			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,
1324				    sizeof(lookup));
1325				break;
1326			}
1327		}
1328		if (lf == NULL)
1329			error = ENOENT;
1330	}
1331	sx_xunlock(&kld_sx);
1332out:
1333	free(symstr, M_TEMP);
1334	return (error);
1335}
1336
1337/*
1338 * Preloaded module support
1339 */
1340
1341static modlist_t
1342modlist_lookup(const char *name, int ver)
1343{
1344	modlist_t mod;
1345
1346	TAILQ_FOREACH(mod, &found_modules, link) {
1347		if (strcmp(mod->name, name) == 0 &&
1348		    (ver == 0 || mod->version == ver))
1349			return (mod);
1350	}
1351	return (NULL);
1352}
1353
1354static modlist_t
1355modlist_lookup2(const char *name, struct mod_depend *verinfo)
1356{
1357	modlist_t mod, bestmod;
1358	int ver;
1359
1360	if (verinfo == NULL)
1361		return (modlist_lookup(name, 0));
1362	bestmod = NULL;
1363	TAILQ_FOREACH(mod, &found_modules, link) {
1364		if (strcmp(mod->name, name) != 0)
1365			continue;
1366		ver = mod->version;
1367		if (ver == verinfo->md_ver_preferred)
1368			return (mod);
1369		if (ver >= verinfo->md_ver_minimum &&
1370		    ver <= verinfo->md_ver_maximum &&
1371		    (bestmod == NULL || ver > bestmod->version))
1372			bestmod = mod;
1373	}
1374	return (bestmod);
1375}
1376
1377static modlist_t
1378modlist_newmodule(const char *modname, int version, linker_file_t container)
1379{
1380	modlist_t mod;
1381
1382	mod = malloc(sizeof(struct modlist), M_LINKER, M_NOWAIT | M_ZERO);
1383	if (mod == NULL)
1384		panic("no memory for module list");
1385	mod->container = container;
1386	mod->name = modname;
1387	mod->version = version;
1388	TAILQ_INSERT_TAIL(&found_modules, mod, link);
1389	return (mod);
1390}
1391
1392static void
1393linker_addmodules(linker_file_t lf, struct mod_metadata **start,
1394    struct mod_metadata **stop, int preload)
1395{
1396	struct mod_metadata *mp, **mdp;
1397	const char *modname;
1398	int ver;
1399
1400	for (mdp = start; mdp < stop; mdp++) {
1401		mp = *mdp;
1402		if (mp->md_type != MDT_VERSION)
1403			continue;
1404		modname = mp->md_cval;
1405		ver = ((struct mod_version *)mp->md_data)->mv_version;
1406		if (modlist_lookup(modname, ver) != NULL) {
1407			printf("module %s already present!\n", modname);
1408			/* XXX what can we do? this is a build error. :-( */
1409			continue;
1410		}
1411		modlist_newmodule(modname, ver, lf);
1412	}
1413}
1414
1415static void
1416linker_preload(void *arg)
1417{
1418	caddr_t modptr;
1419	const char *modname, *nmodname;
1420	char *modtype;
1421	linker_file_t lf, nlf;
1422	linker_class_t lc;
1423	int error;
1424	linker_file_list_t loaded_files;
1425	linker_file_list_t depended_files;
1426	struct mod_metadata *mp, *nmp;
1427	struct mod_metadata **start, **stop, **mdp, **nmdp;
1428	struct mod_depend *verinfo;
1429	int nver;
1430	int resolves;
1431	modlist_t mod;
1432	struct sysinit **si_start, **si_stop;
1433
1434	TAILQ_INIT(&loaded_files);
1435	TAILQ_INIT(&depended_files);
1436	TAILQ_INIT(&found_modules);
1437	error = 0;
1438
1439	modptr = NULL;
1440	sx_xlock(&kld_sx);
1441	while ((modptr = preload_search_next_name(modptr)) != NULL) {
1442		modname = (char *)preload_search_info(modptr, MODINFO_NAME);
1443		modtype = (char *)preload_search_info(modptr, MODINFO_TYPE);
1444		if (modname == NULL) {
1445			printf("Preloaded module at %p does not have a"
1446			    " name!\n", modptr);
1447			continue;
1448		}
1449		if (modtype == NULL) {
1450			printf("Preloaded module at %p does not have a type!\n",
1451			    modptr);
1452			continue;
1453		}
1454		if (bootverbose)
1455			printf("Preloaded %s \"%s\" at %p.\n", modtype, modname,
1456			    modptr);
1457		lf = NULL;
1458		TAILQ_FOREACH(lc, &classes, link) {
1459			error = LINKER_LINK_PRELOAD(lc, modname, &lf);
1460			if (!error)
1461				break;
1462			lf = NULL;
1463		}
1464		if (lf)
1465			TAILQ_INSERT_TAIL(&loaded_files, lf, loaded);
1466	}
1467
1468	/*
1469	 * First get a list of stuff in the kernel.
1470	 */
1471	if (linker_file_lookup_set(linker_kernel_file, MDT_SETNAME, &start,
1472	    &stop, NULL) == 0)
1473		linker_addmodules(linker_kernel_file, start, stop, 1);
1474
1475	/*
1476	 * This is a once-off kinky bubble sort to resolve relocation
1477	 * dependency requirements.
1478	 */
1479restart:
1480	TAILQ_FOREACH(lf, &loaded_files, loaded) {
1481		error = linker_file_lookup_set(lf, MDT_SETNAME, &start,
1482		    &stop, NULL);
1483		/*
1484		 * First, look to see if we would successfully link with this
1485		 * stuff.
1486		 */
1487		resolves = 1;	/* unless we know otherwise */
1488		if (!error) {
1489			for (mdp = start; mdp < stop; mdp++) {
1490				mp = *mdp;
1491				if (mp->md_type != MDT_DEPEND)
1492					continue;
1493				modname = mp->md_cval;
1494				verinfo = mp->md_data;
1495				for (nmdp = start; nmdp < stop; nmdp++) {
1496					nmp = *nmdp;
1497					if (nmp->md_type != MDT_VERSION)
1498						continue;
1499					nmodname = nmp->md_cval;
1500					if (strcmp(modname, nmodname) == 0)
1501						break;
1502				}
1503				if (nmdp < stop)   /* it's a self reference */
1504					continue;
1505
1506				/*
1507				 * ok, the module isn't here yet, we
1508				 * are not finished
1509				 */
1510				if (modlist_lookup2(modname, verinfo) == NULL)
1511					resolves = 0;
1512			}
1513		}
1514		/*
1515		 * OK, if we found our modules, we can link.  So, "provide"
1516		 * the modules inside and add it to the end of the link order
1517		 * list.
1518		 */
1519		if (resolves) {
1520			if (!error) {
1521				for (mdp = start; mdp < stop; mdp++) {
1522					mp = *mdp;
1523					if (mp->md_type != MDT_VERSION)
1524						continue;
1525					modname = mp->md_cval;
1526					nver = ((struct mod_version *)
1527					    mp->md_data)->mv_version;
1528					if (modlist_lookup(modname,
1529					    nver) != NULL) {
1530						printf("module %s already"
1531						    " present!\n", modname);
1532						TAILQ_REMOVE(&loaded_files,
1533						    lf, loaded);
1534						linker_file_unload(lf,
1535						    LINKER_UNLOAD_FORCE);
1536						/* we changed tailq next ptr */
1537						goto restart;
1538					}
1539					modlist_newmodule(modname, nver, lf);
1540				}
1541			}
1542			TAILQ_REMOVE(&loaded_files, lf, loaded);
1543			TAILQ_INSERT_TAIL(&depended_files, lf, loaded);
1544			/*
1545			 * Since we provided modules, we need to restart the
1546			 * sort so that the previous files that depend on us
1547			 * have a chance. Also, we've busted the tailq next
1548			 * pointer with the REMOVE.
1549			 */
1550			goto restart;
1551		}
1552	}
1553
1554	/*
1555	 * At this point, we check to see what could not be resolved..
1556	 */
1557	while ((lf = TAILQ_FIRST(&loaded_files)) != NULL) {
1558		TAILQ_REMOVE(&loaded_files, lf, loaded);
1559		printf("KLD file %s is missing dependencies\n", lf->filename);
1560		linker_file_unload(lf, LINKER_UNLOAD_FORCE);
1561	}
1562
1563	/*
1564	 * We made it. Finish off the linking in the order we determined.
1565	 */
1566	TAILQ_FOREACH_SAFE(lf, &depended_files, loaded, nlf) {
1567		if (linker_kernel_file) {
1568			linker_kernel_file->refs++;
1569			error = linker_file_add_dependency(lf,
1570			    linker_kernel_file);
1571			if (error)
1572				panic("cannot add dependency");
1573		}
1574		lf->userrefs++;	/* so we can (try to) kldunload it */
1575		error = linker_file_lookup_set(lf, MDT_SETNAME, &start,
1576		    &stop, NULL);
1577		if (!error) {
1578			for (mdp = start; mdp < stop; mdp++) {
1579				mp = *mdp;
1580				if (mp->md_type != MDT_DEPEND)
1581					continue;
1582				modname = mp->md_cval;
1583				verinfo = mp->md_data;
1584				mod = modlist_lookup2(modname, verinfo);
1585				if (mod == NULL) {
1586					printf("KLD file %s - cannot find "
1587					    "dependency \"%s\"\n",
1588					    lf->filename, modname);
1589					goto fail;
1590				}
1591				/* Don't count self-dependencies */
1592				if (lf == mod->container)
1593					continue;
1594				mod->container->refs++;
1595				error = linker_file_add_dependency(lf,
1596				    mod->container);
1597				if (error)
1598					panic("cannot add dependency");
1599			}
1600		}
1601		/*
1602		 * Now do relocation etc using the symbol search paths
1603		 * established by the dependencies
1604		 */
1605		error = LINKER_LINK_PRELOAD_FINISH(lf);
1606		if (error) {
1607			printf("KLD file %s - could not finalize loading\n",
1608			    lf->filename);
1609			goto fail;
1610		}
1611		linker_file_register_modules(lf);
1612		if (linker_file_lookup_set(lf, "sysinit_set", &si_start,
1613		    &si_stop, NULL) == 0)
1614			sysinit_add(si_start, si_stop);
1615		linker_file_register_sysctls(lf);
1616		lf->flags |= LINKER_FILE_LINKED;
1617		continue;
1618fail:
1619		TAILQ_REMOVE(&depended_files, lf, loaded);
1620		linker_file_unload(lf, LINKER_UNLOAD_FORCE);
1621	}
1622	sx_xunlock(&kld_sx);
1623	/* woohoo! we made it! */
1624}
1625
1626SYSINIT(preload, SI_SUB_KLD, SI_ORDER_MIDDLE, linker_preload, 0);
1627
1628/*
1629 * Search for a not-loaded module by name.
1630 *
1631 * Modules may be found in the following locations:
1632 *
1633 * - preloaded (result is just the module name) - on disk (result is full path
1634 * to module)
1635 *
1636 * If the module name is qualified in any way (contains path, etc.) the we
1637 * simply return a copy of it.
1638 *
1639 * The search path can be manipulated via sysctl.  Note that we use the ';'
1640 * character as a separator to be consistent with the bootloader.
1641 */
1642
1643static char linker_hintfile[] = "linker.hints";
1644static char linker_path[MAXPATHLEN] = "/boot/kernel;/boot/modules";
1645
1646SYSCTL_STRING(_kern, OID_AUTO, module_path, CTLFLAG_RW, linker_path,
1647    sizeof(linker_path), "module load search path");
1648
1649TUNABLE_STR("module_path", linker_path, sizeof(linker_path));
1650
1651static char *linker_ext_list[] = {
1652	"",
1653	".ko",
1654	NULL
1655};
1656
1657/*
1658 * Check if file actually exists either with or without extension listed in
1659 * the linker_ext_list. (probably should be generic for the rest of the
1660 * kernel)
1661 */
1662static char *
1663linker_lookup_file(const char *path, int pathlen, const char *name,
1664    int namelen, struct vattr *vap)
1665{
1666	struct nameidata nd;
1667	struct thread *td = curthread;	/* XXX */
1668	char *result, **cpp, *sep;
1669	int error, len, extlen, reclen, flags;
1670	enum vtype type;
1671
1672	extlen = 0;
1673	for (cpp = linker_ext_list; *cpp; cpp++) {
1674		len = strlen(*cpp);
1675		if (len > extlen)
1676			extlen = len;
1677	}
1678	extlen++;		/* trailing '\0' */
1679	sep = (path[pathlen - 1] != '/') ? "/" : "";
1680
1681	reclen = pathlen + strlen(sep) + namelen + extlen + 1;
1682	result = malloc(reclen, M_LINKER, M_WAITOK);
1683	for (cpp = linker_ext_list; *cpp; cpp++) {
1684		snprintf(result, reclen, "%.*s%s%.*s%s", pathlen, path, sep,
1685		    namelen, name, *cpp);
1686		/*
1687		 * Attempt to open the file, and return the path if
1688		 * we succeed and it's a regular file.
1689		 */
1690		NDINIT(&nd, LOOKUP, FOLLOW, UIO_SYSSPACE, result, td);
1691		flags = FREAD;
1692		error = vn_open(&nd, &flags, 0, NULL);
1693		if (error == 0) {
1694			NDFREE(&nd, NDF_ONLY_PNBUF);
1695			type = nd.ni_vp->v_type;
1696			if (vap)
1697				VOP_GETATTR(nd.ni_vp, vap, td->td_ucred);
1698			VOP_UNLOCK(nd.ni_vp, 0);
1699			vn_close(nd.ni_vp, FREAD, td->td_ucred, td);
1700			if (type == VREG)
1701				return (result);
1702		}
1703	}
1704	free(result, M_LINKER);
1705	return (NULL);
1706}
1707
1708#define	INT_ALIGN(base, ptr)	ptr =					\
1709	(base) + (((ptr) - (base) + sizeof(int) - 1) & ~(sizeof(int) - 1))
1710
1711/*
1712 * Lookup KLD which contains requested module in the "linker.hints" file. If
1713 * version specification is available, then try to find the best KLD.
1714 * Otherwise just find the latest one.
1715 */
1716static char *
1717linker_hints_lookup(const char *path, int pathlen, const char *modname,
1718    int modnamelen, struct mod_depend *verinfo)
1719{
1720	struct thread *td = curthread;	/* XXX */
1721	struct ucred *cred = td ? td->td_ucred : NULL;
1722	struct nameidata nd;
1723	struct vattr vattr, mattr;
1724	u_char *hints = NULL;
1725	u_char *cp, *recptr, *bufend, *result, *best, *pathbuf, *sep;
1726	int error, ival, bestver, *intp, found, flags, clen, blen;
1727	ssize_t reclen;
1728
1729	result = NULL;
1730	bestver = found = 0;
1731
1732	sep = (path[pathlen - 1] != '/') ? "/" : "";
1733	reclen = imax(modnamelen, strlen(linker_hintfile)) + pathlen +
1734	    strlen(sep) + 1;
1735	pathbuf = malloc(reclen, M_LINKER, M_WAITOK);
1736	snprintf(pathbuf, reclen, "%.*s%s%s", pathlen, path, sep,
1737	    linker_hintfile);
1738
1739	NDINIT(&nd, LOOKUP, NOFOLLOW, UIO_SYSSPACE, pathbuf, td);
1740	flags = FREAD;
1741	error = vn_open(&nd, &flags, 0, NULL);
1742	if (error)
1743		goto bad;
1744	NDFREE(&nd, NDF_ONLY_PNBUF);
1745	if (nd.ni_vp->v_type != VREG)
1746		goto bad;
1747	best = cp = NULL;
1748	error = VOP_GETATTR(nd.ni_vp, &vattr, cred);
1749	if (error)
1750		goto bad;
1751	/*
1752	 * XXX: we need to limit this number to some reasonable value
1753	 */
1754	if (vattr.va_size > 100 * 1024) {
1755		printf("hints file too large %ld\n", (long)vattr.va_size);
1756		goto bad;
1757	}
1758	hints = malloc(vattr.va_size, M_TEMP, M_WAITOK);
1759	if (hints == NULL)
1760		goto bad;
1761	error = vn_rdwr(UIO_READ, nd.ni_vp, (caddr_t)hints, vattr.va_size, 0,
1762	    UIO_SYSSPACE, IO_NODELOCKED, cred, NOCRED, &reclen, td);
1763	if (error)
1764		goto bad;
1765	VOP_UNLOCK(nd.ni_vp, 0);
1766	vn_close(nd.ni_vp, FREAD, cred, td);
1767	nd.ni_vp = NULL;
1768	if (reclen != 0) {
1769		printf("can't read %zd\n", reclen);
1770		goto bad;
1771	}
1772	intp = (int *)hints;
1773	ival = *intp++;
1774	if (ival != LINKER_HINTS_VERSION) {
1775		printf("hints file version mismatch %d\n", ival);
1776		goto bad;
1777	}
1778	bufend = hints + vattr.va_size;
1779	recptr = (u_char *)intp;
1780	clen = blen = 0;
1781	while (recptr < bufend && !found) {
1782		intp = (int *)recptr;
1783		reclen = *intp++;
1784		ival = *intp++;
1785		cp = (char *)intp;
1786		switch (ival) {
1787		case MDT_VERSION:
1788			clen = *cp++;
1789			if (clen != modnamelen || bcmp(cp, modname, clen) != 0)
1790				break;
1791			cp += clen;
1792			INT_ALIGN(hints, cp);
1793			ival = *(int *)cp;
1794			cp += sizeof(int);
1795			clen = *cp++;
1796			if (verinfo == NULL ||
1797			    ival == verinfo->md_ver_preferred) {
1798				found = 1;
1799				break;
1800			}
1801			if (ival >= verinfo->md_ver_minimum &&
1802			    ival <= verinfo->md_ver_maximum &&
1803			    ival > bestver) {
1804				bestver = ival;
1805				best = cp;
1806				blen = clen;
1807			}
1808			break;
1809		default:
1810			break;
1811		}
1812		recptr += reclen + sizeof(int);
1813	}
1814	/*
1815	 * Finally check if KLD is in the place
1816	 */
1817	if (found)
1818		result = linker_lookup_file(path, pathlen, cp, clen, &mattr);
1819	else if (best)
1820		result = linker_lookup_file(path, pathlen, best, blen, &mattr);
1821
1822	/*
1823	 * KLD is newer than hints file. What we should do now?
1824	 */
1825	if (result && timespeccmp(&mattr.va_mtime, &vattr.va_mtime, >))
1826		printf("warning: KLD '%s' is newer than the linker.hints"
1827		    " file\n", result);
1828bad:
1829	free(pathbuf, M_LINKER);
1830	if (hints)
1831		free(hints, M_TEMP);
1832	if (nd.ni_vp != NULL) {
1833		VOP_UNLOCK(nd.ni_vp, 0);
1834		vn_close(nd.ni_vp, FREAD, cred, td);
1835	}
1836	/*
1837	 * If nothing found or hints is absent - fallback to the old
1838	 * way by using "kldname[.ko]" as module name.
1839	 */
1840	if (!found && !bestver && result == NULL)
1841		result = linker_lookup_file(path, pathlen, modname,
1842		    modnamelen, NULL);
1843	return (result);
1844}
1845
1846/*
1847 * Lookup KLD which contains requested module in the all directories.
1848 */
1849static char *
1850linker_search_module(const char *modname, int modnamelen,
1851    struct mod_depend *verinfo)
1852{
1853	char *cp, *ep, *result;
1854
1855	/*
1856	 * traverse the linker path
1857	 */
1858	for (cp = linker_path; *cp; cp = ep + 1) {
1859		/* find the end of this component */
1860		for (ep = cp; (*ep != 0) && (*ep != ';'); ep++);
1861		result = linker_hints_lookup(cp, ep - cp, modname,
1862		    modnamelen, verinfo);
1863		if (result != NULL)
1864			return (result);
1865		if (*ep == 0)
1866			break;
1867	}
1868	return (NULL);
1869}
1870
1871/*
1872 * Search for module in all directories listed in the linker_path.
1873 */
1874static char *
1875linker_search_kld(const char *name)
1876{
1877	char *cp, *ep, *result;
1878	int len;
1879
1880	/* qualified at all? */
1881	if (strchr(name, '/'))
1882		return (strdup(name, M_LINKER));
1883
1884	/* traverse the linker path */
1885	len = strlen(name);
1886	for (ep = linker_path; *ep; ep++) {
1887		cp = ep;
1888		/* find the end of this component */
1889		for (; *ep != 0 && *ep != ';'; ep++);
1890		result = linker_lookup_file(cp, ep - cp, name, len, NULL);
1891		if (result != NULL)
1892			return (result);
1893	}
1894	return (NULL);
1895}
1896
1897static const char *
1898linker_basename(const char *path)
1899{
1900	const char *filename;
1901
1902	filename = strrchr(path, '/');
1903	if (filename == NULL)
1904		return path;
1905	if (filename[1])
1906		filename++;
1907	return (filename);
1908}
1909
1910#ifdef HWPMC_HOOKS
1911/*
1912 * Inform hwpmc about the set of kernel modules currently loaded.
1913 */
1914void *
1915linker_hwpmc_list_objects(void)
1916{
1917	linker_file_t lf;
1918	struct pmckern_map_in *kobase;
1919	int i, nmappings;
1920
1921	nmappings = 0;
1922	sx_slock(&kld_sx);
1923	TAILQ_FOREACH(lf, &linker_files, link)
1924		nmappings++;
1925
1926	/* Allocate nmappings + 1 entries. */
1927	kobase = malloc((nmappings + 1) * sizeof(struct pmckern_map_in),
1928	    M_LINKER, M_WAITOK | M_ZERO);
1929	i = 0;
1930	TAILQ_FOREACH(lf, &linker_files, link) {
1931
1932		/* Save the info for this linker file. */
1933		kobase[i].pm_file = lf->filename;
1934		kobase[i].pm_address = (uintptr_t)lf->address;
1935		i++;
1936	}
1937	sx_sunlock(&kld_sx);
1938
1939	KASSERT(i > 0, ("linker_hpwmc_list_objects: no kernel objects?"));
1940
1941	/* The last entry of the malloced area comprises of all zeros. */
1942	KASSERT(kobase[i].pm_file == NULL,
1943	    ("linker_hwpmc_list_objects: last object not NULL"));
1944
1945	return ((void *)kobase);
1946}
1947#endif
1948
1949/*
1950 * Find a file which contains given module and load it, if "parent" is not
1951 * NULL, register a reference to it.
1952 */
1953static int
1954linker_load_module(const char *kldname, const char *modname,
1955    struct linker_file *parent, struct mod_depend *verinfo,
1956    struct linker_file **lfpp)
1957{
1958	linker_file_t lfdep;
1959	const char *filename;
1960	char *pathname;
1961	int error;
1962
1963	sx_assert(&kld_sx, SA_XLOCKED);
1964	if (modname == NULL) {
1965		/*
1966 		 * We have to load KLD
1967 		 */
1968		KASSERT(verinfo == NULL, ("linker_load_module: verinfo"
1969		    " is not NULL"));
1970		pathname = linker_search_kld(kldname);
1971	} else {
1972		if (modlist_lookup2(modname, verinfo) != NULL)
1973			return (EEXIST);
1974		if (kldname != NULL)
1975			pathname = strdup(kldname, M_LINKER);
1976		else if (rootvnode == NULL)
1977			pathname = NULL;
1978		else
1979			/*
1980			 * Need to find a KLD with required module
1981			 */
1982			pathname = linker_search_module(modname,
1983			    strlen(modname), verinfo);
1984	}
1985	if (pathname == NULL)
1986		return (ENOENT);
1987
1988	/*
1989	 * Can't load more than one file with the same basename XXX:
1990	 * Actually it should be possible to have multiple KLDs with
1991	 * the same basename but different path because they can
1992	 * provide different versions of the same modules.
1993	 */
1994	filename = linker_basename(pathname);
1995	if (linker_find_file_by_name(filename))
1996		error = EEXIST;
1997	else do {
1998		error = linker_load_file(pathname, &lfdep);
1999		if (error)
2000			break;
2001		if (modname && verinfo &&
2002		    modlist_lookup2(modname, verinfo) == NULL) {
2003			linker_file_unload(lfdep, LINKER_UNLOAD_FORCE);
2004			error = ENOENT;
2005			break;
2006		}
2007		if (parent) {
2008			error = linker_file_add_dependency(parent, lfdep);
2009			if (error)
2010				break;
2011		}
2012		if (lfpp)
2013			*lfpp = lfdep;
2014	} while (0);
2015	free(pathname, M_LINKER);
2016	return (error);
2017}
2018
2019/*
2020 * This routine is responsible for finding dependencies of userland initiated
2021 * kldload(2)'s of files.
2022 */
2023int
2024linker_load_dependencies(linker_file_t lf)
2025{
2026	linker_file_t lfdep;
2027	struct mod_metadata **start, **stop, **mdp, **nmdp;
2028	struct mod_metadata *mp, *nmp;
2029	struct mod_depend *verinfo;
2030	modlist_t mod;
2031	const char *modname, *nmodname;
2032	int ver, error = 0, count;
2033
2034	/*
2035	 * All files are dependant on /kernel.
2036	 */
2037	sx_assert(&kld_sx, SA_XLOCKED);
2038	if (linker_kernel_file) {
2039		linker_kernel_file->refs++;
2040		error = linker_file_add_dependency(lf, linker_kernel_file);
2041		if (error)
2042			return (error);
2043	}
2044	if (linker_file_lookup_set(lf, MDT_SETNAME, &start, &stop,
2045	    &count) != 0)
2046		return (0);
2047	for (mdp = start; mdp < stop; mdp++) {
2048		mp = *mdp;
2049		if (mp->md_type != MDT_VERSION)
2050			continue;
2051		modname = mp->md_cval;
2052		ver = ((struct mod_version *)mp->md_data)->mv_version;
2053		mod = modlist_lookup(modname, ver);
2054		if (mod != NULL) {
2055			printf("interface %s.%d already present in the KLD"
2056			    " '%s'!\n", modname, ver,
2057			    mod->container->filename);
2058			return (EEXIST);
2059		}
2060	}
2061
2062	for (mdp = start; mdp < stop; mdp++) {
2063		mp = *mdp;
2064		if (mp->md_type != MDT_DEPEND)
2065			continue;
2066		modname = mp->md_cval;
2067		verinfo = mp->md_data;
2068		nmodname = NULL;
2069		for (nmdp = start; nmdp < stop; nmdp++) {
2070			nmp = *nmdp;
2071			if (nmp->md_type != MDT_VERSION)
2072				continue;
2073			nmodname = nmp->md_cval;
2074			if (strcmp(modname, nmodname) == 0)
2075				break;
2076		}
2077		if (nmdp < stop)/* early exit, it's a self reference */
2078			continue;
2079		mod = modlist_lookup2(modname, verinfo);
2080		if (mod) {	/* woohoo, it's loaded already */
2081			lfdep = mod->container;
2082			lfdep->refs++;
2083			error = linker_file_add_dependency(lf, lfdep);
2084			if (error)
2085				break;
2086			continue;
2087		}
2088		error = linker_load_module(NULL, modname, lf, verinfo, NULL);
2089		if (error) {
2090			printf("KLD %s: depends on %s - not available or"
2091			    " version mismatch\n", lf->filename, modname);
2092			break;
2093		}
2094	}
2095
2096	if (error)
2097		return (error);
2098	linker_addmodules(lf, start, stop, 0);
2099	return (error);
2100}
2101
2102static int
2103sysctl_kern_function_list_iterate(const char *name, void *opaque)
2104{
2105	struct sysctl_req *req;
2106
2107	req = opaque;
2108	return (SYSCTL_OUT(req, name, strlen(name) + 1));
2109}
2110
2111/*
2112 * Export a nul-separated, double-nul-terminated list of all function names
2113 * in the kernel.
2114 */
2115static int
2116sysctl_kern_function_list(SYSCTL_HANDLER_ARGS)
2117{
2118	linker_file_t lf;
2119	int error;
2120
2121#ifdef MAC
2122	error = mac_kld_check_stat(req->td->td_ucred);
2123	if (error)
2124		return (error);
2125#endif
2126	error = sysctl_wire_old_buffer(req, 0);
2127	if (error != 0)
2128		return (error);
2129	sx_xlock(&kld_sx);
2130	TAILQ_FOREACH(lf, &linker_files, link) {
2131		error = LINKER_EACH_FUNCTION_NAME(lf,
2132		    sysctl_kern_function_list_iterate, req);
2133		if (error) {
2134			sx_xunlock(&kld_sx);
2135			return (error);
2136		}
2137	}
2138	sx_xunlock(&kld_sx);
2139	return (SYSCTL_OUT(req, "", 1));
2140}
2141
2142SYSCTL_PROC(_kern, OID_AUTO, function_list, CTLTYPE_OPAQUE | CTLFLAG_RD,
2143    NULL, 0, sysctl_kern_function_list, "", "kernel function list");
2144