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