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