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