kern_linker.c revision 95488
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 * $FreeBSD: head/sys/kern/kern_linker.c 95488 2002-04-26 09:52:54Z brian $
27 */
28
29#include "opt_ddb.h"
30
31#include <sys/param.h>
32#include <sys/kernel.h>
33#include <sys/systm.h>
34#include <sys/malloc.h>
35#include <sys/sysproto.h>
36#include <sys/sysent.h>
37#include <sys/proc.h>
38#include <sys/lock.h>
39#include <sys/mutex.h>
40#include <sys/sx.h>
41#include <sys/module.h>
42#include <sys/linker.h>
43#include <sys/fcntl.h>
44#include <sys/libkern.h>
45#include <sys/namei.h>
46#include <sys/vnode.h>
47#include <sys/sysctl.h>
48
49#include "linker_if.h"
50
51#ifdef KLD_DEBUG
52int kld_debug = 0;
53#endif
54
55/*
56 * static char *linker_search_path(const char *name, struct mod_depend
57 * *verinfo);
58 */
59static const char 	*linker_basename(const char *path);
60static int 	linker_load_module(const char *kldname, const char *modname,
61		    struct linker_file *parent, struct mod_depend *verinfo,
62		    struct linker_file **lfpp);
63
64/* Metadata from the static kernel */
65SET_DECLARE(modmetadata_set, struct mod_metadata);
66
67MALLOC_DEFINE(M_LINKER, "linker", "kernel linker");
68
69linker_file_t linker_kernel_file;
70
71static struct lock lock;	/* lock for the file list */
72static linker_class_list_t classes;
73static linker_file_list_t linker_files;
74static int next_file_id = 1;
75
76#define	LINKER_GET_NEXT_FILE_ID(a) do {					\
77	linker_file_t lftmp;						\
78									\
79retry:									\
80	TAILQ_FOREACH(lftmp, &linker_files, link) {			\
81		if (next_file_id == lftmp->id) {			\
82			next_file_id++;					\
83			goto retry;					\
84		}							\
85	}								\
86	(a) = next_file_id;						\
87} while(0)
88
89
90/* XXX wrong name; we're looking at version provision tags here, not modules */
91typedef TAILQ_HEAD(, modlist) modlisthead_t;
92struct modlist {
93	TAILQ_ENTRY(modlist) link;	/* chain together all modules */
94	linker_file_t   container;
95	const char 	*name;
96	int             version;
97};
98typedef struct modlist *modlist_t;
99static modlisthead_t found_modules;
100
101static modlist_t	modlist_lookup2(const char *name,
102			    struct mod_depend *verinfo);
103
104static char *
105linker_strdup(const char *str)
106{
107	char *result;
108
109	if ((result = malloc((strlen(str) + 1), M_LINKER, M_WAITOK)) != NULL)
110		strcpy(result, str);
111	return (result);
112}
113
114static void
115linker_init(void *arg)
116{
117
118	lockinit(&lock, PVM, "klink", 0, 0);
119	TAILQ_INIT(&classes);
120	TAILQ_INIT(&linker_files);
121}
122
123SYSINIT(linker, SI_SUB_KLD, SI_ORDER_FIRST, linker_init, 0)
124
125int
126linker_add_class(linker_class_t lc)
127{
128
129	kobj_class_compile((kobj_class_t) lc);
130	TAILQ_INSERT_TAIL(&classes, lc, link);
131	return (0);
132}
133
134static void
135linker_file_sysinit(linker_file_t lf)
136{
137	struct sysinit **start, **stop, **sipp, **xipp, *save;
138
139	KLD_DPF(FILE, ("linker_file_sysinit: calling SYSINITs for %s\n",
140	    lf->filename));
141
142	if (linker_file_lookup_set(lf, "sysinit_set", &start, &stop, NULL) != 0)
143		return;
144	/*
145	 * Perform a bubble sort of the system initialization objects by
146	 * their subsystem (primary key) and order (secondary key).
147	 *
148	 * Since some things care about execution order, this is the operation
149	 * which ensures continued function.
150	 */
151	for (sipp = start; sipp < stop; sipp++) {
152		for (xipp = sipp + 1; xipp < stop; xipp++) {
153			if ((*sipp)->subsystem < (*xipp)->subsystem ||
154			    ((*sipp)->subsystem == (*xipp)->subsystem &&
155			    (*sipp)->order <= (*xipp)->order))
156				continue;	/* skip */
157			save = *sipp;
158			*sipp = *xipp;
159			*xipp = save;
160		}
161	}
162
163	/*
164	 * Traverse the (now) ordered list of system initialization tasks.
165	 * Perform each task, and continue on to the next task.
166	 */
167	for (sipp = start; sipp < stop; sipp++) {
168		if ((*sipp)->subsystem == SI_SUB_DUMMY)
169			continue;	/* skip dummy task(s) */
170
171		/* Call function */
172		(*((*sipp)->func)) ((*sipp)->udata);
173	}
174}
175
176static void
177linker_file_sysuninit(linker_file_t lf)
178{
179	struct sysinit **start, **stop, **sipp, **xipp, *save;
180
181	KLD_DPF(FILE, ("linker_file_sysuninit: calling SYSUNINITs for %s\n",
182	    lf->filename));
183
184	if (linker_file_lookup_set(lf, "sysuninit_set", &start, &stop,
185	    NULL) != 0)
186		return;
187
188	/*
189	 * Perform a reverse bubble sort of the system initialization objects
190	 * by their subsystem (primary key) and order (secondary key).
191	 *
192	 * Since some things care about execution order, this is the operation
193	 * which ensures continued function.
194	 */
195	for (sipp = start; sipp < stop; sipp++) {
196		for (xipp = sipp + 1; xipp < stop; xipp++) {
197			if ((*sipp)->subsystem > (*xipp)->subsystem ||
198			    ((*sipp)->subsystem == (*xipp)->subsystem &&
199			    (*sipp)->order >= (*xipp)->order))
200				continue;	/* skip */
201			save = *sipp;
202			*sipp = *xipp;
203			*xipp = save;
204		}
205	}
206
207	/*
208	 * Traverse the (now) ordered list of system initialization tasks.
209	 * Perform each task, and continue on to the next task.
210	 */
211	for (sipp = start; sipp < stop; sipp++) {
212		if ((*sipp)->subsystem == SI_SUB_DUMMY)
213			continue;	/* skip dummy task(s) */
214
215		/* Call function */
216		(*((*sipp)->func)) ((*sipp)->udata);
217	}
218}
219
220static void
221linker_file_register_sysctls(linker_file_t lf)
222{
223	struct sysctl_oid **start, **stop, **oidp;
224
225	KLD_DPF(FILE,
226	    ("linker_file_register_sysctls: registering SYSCTLs for %s\n",
227	    lf->filename));
228
229	if (linker_file_lookup_set(lf, "sysctl_set", &start, &stop, NULL) != 0)
230		return;
231
232	for (oidp = start; oidp < stop; oidp++)
233		sysctl_register_oid(*oidp);
234}
235
236static void
237linker_file_unregister_sysctls(linker_file_t lf)
238{
239	struct sysctl_oid **start, **stop, **oidp;
240
241	KLD_DPF(FILE, ("linker_file_unregister_sysctls: registering SYSCTLs"
242	    " for %s\n", lf->filename));
243
244	if (linker_file_lookup_set(lf, "sysctl_set", &start, &stop, NULL) != 0)
245		return;
246
247	for (oidp = start; oidp < stop; oidp++)
248		sysctl_unregister_oid(*oidp);
249}
250
251static int
252linker_file_register_modules(linker_file_t lf)
253{
254	struct mod_metadata **start, **stop, **mdp;
255	const moduledata_t *moddata;
256	int error;
257
258	KLD_DPF(FILE, ("linker_file_register_modules: registering modules"
259	    " in %s\n", lf->filename));
260
261	if (linker_file_lookup_set(lf, "modmetadata_set", &start,
262	    &stop, 0) != 0) {
263		/*
264		 * This fallback should be unnecessary, but if we get booted
265		 * from boot2 instead of loader and we are missing our
266		 * metadata then we have to try the best we can.
267		 */
268		if (lf == linker_kernel_file) {
269			start = SET_BEGIN(modmetadata_set);
270			stop = SET_LIMIT(modmetadata_set);
271		} else
272			return (0);
273	}
274	for (mdp = start; mdp < stop; mdp++) {
275		if ((*mdp)->md_type != MDT_MODULE)
276			continue;
277		moddata = (*mdp)->md_data;
278		KLD_DPF(FILE, ("Registering module %s in %s\n",
279		    moddata->name, lf->filename));
280		error = module_register(moddata, lf);
281		if (error)
282			printf("Module %s failed to register: %d\n",
283			    moddata->name, error);
284	}
285	return (0);
286}
287
288static void
289linker_init_kernel_modules(void)
290{
291
292	linker_file_register_modules(linker_kernel_file);
293}
294
295SYSINIT(linker_kernel, SI_SUB_KLD, SI_ORDER_ANY, linker_init_kernel_modules, 0)
296
297int
298linker_load_file(const char *filename, linker_file_t *result)
299{
300	linker_class_t lc;
301	linker_file_t lf;
302	int foundfile, error = 0;
303
304	/* Refuse to load modules if securelevel raised */
305	if (securelevel > 0)
306		return (EPERM);
307
308	lf = linker_find_file_by_name(filename);
309	if (lf) {
310		KLD_DPF(FILE, ("linker_load_file: file %s is already loaded,"
311		    " incrementing refs\n", filename));
312		*result = lf;
313		lf->refs++;
314		goto out;
315	}
316	lf = NULL;
317	foundfile = 0;
318	TAILQ_FOREACH(lc, &classes, link) {
319		KLD_DPF(FILE, ("linker_load_file: trying to load %s\n",
320		    filename));
321		error = LINKER_LOAD_FILE(lc, filename, &lf);
322		/*
323		 * If we got something other than ENOENT, then it exists but
324		 * we cannot load it for some other reason.
325		 */
326		if (error != ENOENT)
327			foundfile = 1;
328		if (lf) {
329			linker_file_register_modules(lf);
330			linker_file_register_sysctls(lf);
331			linker_file_sysinit(lf);
332			lf->flags |= LINKER_FILE_LINKED;
333			*result = lf;
334			error = 0;
335			goto out;
336		}
337	}
338	/*
339	 * Less than ideal, but tells the user whether it failed to load or
340	 * the module was not found.
341	 */
342	if (foundfile)
343		/* Format not recognized (or unloadable). */
344		error = ENOEXEC;
345	else
346		error = ENOENT;		/* Nothing found */
347out:
348	return (error);
349}
350
351int
352linker_reference_module(const char *modname, struct mod_depend *verinfo,
353    linker_file_t *result)
354{
355	modlist_t mod;
356
357	if ((mod = modlist_lookup2(modname, verinfo)) != NULL) {
358		*result = mod->container;
359		(*result)->refs++;
360		return (0);
361	}
362
363	return (linker_load_module(NULL, modname, NULL, verinfo, result));
364}
365
366linker_file_t
367linker_find_file_by_name(const char *filename)
368{
369	linker_file_t lf = 0;
370	char *koname;
371
372	koname = malloc(strlen(filename) + 4, M_LINKER, M_WAITOK);
373	if (koname == NULL)
374		goto out;
375	sprintf(koname, "%s.ko", filename);
376
377	lockmgr(&lock, LK_SHARED, 0, curthread);
378	TAILQ_FOREACH(lf, &linker_files, link) {
379		if (strcmp(lf->filename, koname) == 0)
380			break;
381		if (strcmp(lf->filename, filename) == 0)
382			break;
383	}
384	lockmgr(&lock, LK_RELEASE, 0, curthread);
385out:
386	if (koname)
387		free(koname, M_LINKER);
388	return (lf);
389}
390
391linker_file_t
392linker_find_file_by_id(int fileid)
393{
394	linker_file_t lf = 0;
395
396	lockmgr(&lock, LK_SHARED, 0, curthread);
397	TAILQ_FOREACH(lf, &linker_files, link)
398		if (lf->id == fileid)
399			break;
400	lockmgr(&lock, LK_RELEASE, 0, curthread);
401	return (lf);
402}
403
404linker_file_t
405linker_make_file(const char *pathname, linker_class_t lc)
406{
407	linker_file_t lf;
408	const char *filename;
409
410	lf = NULL;
411	filename = linker_basename(pathname);
412
413	KLD_DPF(FILE, ("linker_make_file: new file, filename=%s\n", filename));
414	lockmgr(&lock, LK_EXCLUSIVE, 0, curthread);
415	lf = (linker_file_t)kobj_create((kobj_class_t)lc, M_LINKER, M_WAITOK);
416	if (lf == NULL)
417		goto out;
418	lf->refs = 1;
419	lf->userrefs = 0;
420	lf->flags = 0;
421	lf->filename = linker_strdup(filename);
422	LINKER_GET_NEXT_FILE_ID(lf->id);
423	lf->ndeps = 0;
424	lf->deps = NULL;
425	STAILQ_INIT(&lf->common);
426	TAILQ_INIT(&lf->modules);
427	TAILQ_INSERT_TAIL(&linker_files, lf, link);
428out:
429	lockmgr(&lock, LK_RELEASE, 0, curthread);
430	return (lf);
431}
432
433int
434linker_file_unload(linker_file_t file)
435{
436	module_t mod, next;
437	modlist_t ml, nextml;
438	struct common_symbol *cp;
439	int error, i;
440
441	error = 0;
442
443	/* Refuse to unload modules if securelevel raised. */
444	if (securelevel > 0)
445		return (EPERM);
446
447	KLD_DPF(FILE, ("linker_file_unload: lf->refs=%d\n", file->refs));
448	lockmgr(&lock, LK_EXCLUSIVE, 0, curthread);
449	if (file->refs == 1) {
450		KLD_DPF(FILE, ("linker_file_unload: file is unloading,"
451		    " informing modules\n"));
452
453		/*
454		 * Inform any modules associated with this file.
455		 */
456		MOD_XLOCK;
457		for (mod = TAILQ_FIRST(&file->modules); mod; mod = next) {
458			next = module_getfnext(mod);
459			MOD_XUNLOCK;
460
461			/*
462			 * Give the module a chance to veto the unload.
463			 */
464			if ((error = module_unload(mod)) != 0) {
465				KLD_DPF(FILE, ("linker_file_unload: module %x"
466				    " vetoes unload\n", mod));
467				lockmgr(&lock, LK_RELEASE, 0, curthread);
468				goto out;
469			} else
470				MOD_XLOCK;
471			module_release(mod);
472		}
473		MOD_XUNLOCK;
474	}
475	file->refs--;
476	if (file->refs > 0) {
477		lockmgr(&lock, LK_RELEASE, 0, curthread);
478		goto out;
479	}
480	for (ml = TAILQ_FIRST(&found_modules); ml; ml = nextml) {
481		nextml = TAILQ_NEXT(ml, link);
482		if (ml->container == file)
483			TAILQ_REMOVE(&found_modules, ml, link);
484	}
485
486	/*
487	 * Don't try to run SYSUNINITs if we are unloaded due to a
488	 * link error.
489	 */
490	if (file->flags & LINKER_FILE_LINKED) {
491		linker_file_sysuninit(file);
492		linker_file_unregister_sysctls(file);
493	}
494	TAILQ_REMOVE(&linker_files, file, link);
495	lockmgr(&lock, LK_RELEASE, 0, curthread);
496
497	if (file->deps) {
498		for (i = 0; i < file->ndeps; i++)
499			linker_file_unload(file->deps[i]);
500		free(file->deps, M_LINKER);
501		file->deps = NULL;
502	}
503	for (cp = STAILQ_FIRST(&file->common); cp;
504	    cp = STAILQ_FIRST(&file->common)) {
505		STAILQ_REMOVE(&file->common, cp, common_symbol, link);
506		free(cp, M_LINKER);
507	}
508
509	LINKER_UNLOAD(file);
510	if (file->filename) {
511		free(file->filename, M_LINKER);
512		file->filename = NULL;
513	}
514	kobj_delete((kobj_t) file, M_LINKER);
515out:
516	return (error);
517}
518
519int
520linker_file_add_dependency(linker_file_t file, linker_file_t dep)
521{
522	linker_file_t *newdeps;
523
524	newdeps = malloc((file->ndeps + 1) * sizeof(linker_file_t *),
525	    M_LINKER, M_WAITOK | M_ZERO);
526	if (newdeps == NULL)
527		return (ENOMEM);
528
529	if (file->deps) {
530		bcopy(file->deps, newdeps,
531		    file->ndeps * sizeof(linker_file_t *));
532		free(file->deps, M_LINKER);
533	}
534	file->deps = newdeps;
535	file->deps[file->ndeps] = dep;
536	file->ndeps++;
537	return (0);
538}
539
540/*
541 * Locate a linker set and its contents.  This is a helper function to avoid
542 * linker_if.h exposure elsewhere.  Note: firstp and lastp are really void ***
543 */
544int
545linker_file_lookup_set(linker_file_t file, const char *name,
546    void *firstp, void *lastp, int *countp)
547{
548
549	return (LINKER_LOOKUP_SET(file, name, firstp, lastp, countp));
550}
551
552caddr_t
553linker_file_lookup_symbol(linker_file_t file, const char *name, int deps)
554{
555	c_linker_sym_t sym;
556	linker_symval_t symval;
557	caddr_t address;
558	size_t common_size = 0;
559	int i;
560
561	KLD_DPF(SYM, ("linker_file_lookup_symbol: file=%x, name=%s, deps=%d\n",
562	    file, name, deps));
563
564	if (LINKER_LOOKUP_SYMBOL(file, name, &sym) == 0) {
565		LINKER_SYMBOL_VALUES(file, sym, &symval);
566		if (symval.value == 0)
567			/*
568			 * For commons, first look them up in the
569			 * dependencies and only allocate space if not found
570			 * there.
571			 */
572			common_size = symval.size;
573		else {
574			KLD_DPF(SYM, ("linker_file_lookup_symbol: symbol"
575			    ".value=%x\n", symval.value));
576			return (symval.value);
577		}
578	}
579	if (deps) {
580		for (i = 0; i < file->ndeps; i++) {
581			address = linker_file_lookup_symbol(file->deps[i],
582			    name, 0);
583			if (address) {
584				KLD_DPF(SYM, ("linker_file_lookup_symbol:"
585				    " deps value=%x\n", address));
586				return (address);
587			}
588		}
589	}
590	if (common_size > 0) {
591		/*
592		 * This is a common symbol which was not found in the
593		 * dependencies.  We maintain a simple common symbol table in
594		 * the file object.
595		 */
596		struct common_symbol *cp;
597
598		STAILQ_FOREACH(cp, &file->common, link) {
599			if (strcmp(cp->name, name) == 0) {
600				KLD_DPF(SYM, ("linker_file_lookup_symbol:"
601				    " old common value=%x\n", cp->address));
602				return (cp->address);
603			}
604		}
605		/*
606		 * Round the symbol size up to align.
607		 */
608		common_size = (common_size + sizeof(int) - 1) & -sizeof(int);
609		cp = malloc(sizeof(struct common_symbol)
610		    + common_size + strlen(name) + 1, M_LINKER,
611		    M_WAITOK | M_ZERO);
612		if (cp == NULL) {
613			KLD_DPF(SYM, ("linker_file_lookup_symbol: nomem\n"));
614			return (0);
615		}
616		cp->address = (caddr_t)(cp + 1);
617		cp->name = cp->address + common_size;
618		strcpy(cp->name, name);
619		bzero(cp->address, common_size);
620		STAILQ_INSERT_TAIL(&file->common, cp, link);
621
622		KLD_DPF(SYM, ("linker_file_lookup_symbol: new common"
623		    " value=%x\n", cp->address));
624		return (cp->address);
625	}
626	KLD_DPF(SYM, ("linker_file_lookup_symbol: fail\n"));
627	return (0);
628}
629
630#ifdef DDB
631/*
632 * DDB Helpers.  DDB has to look across multiple files with their own symbol
633 * tables and string tables.
634 *
635 * Note that we do not obey list locking protocols here.  We really don't need
636 * DDB to hang because somebody's got the lock held.  We'll take the chance
637 * that the files list is inconsistant instead.
638 */
639
640int
641linker_ddb_lookup(const char *symstr, c_linker_sym_t *sym)
642{
643	linker_file_t lf;
644
645	TAILQ_FOREACH(lf, &linker_files, link) {
646		if (LINKER_LOOKUP_SYMBOL(lf, symstr, sym) == 0)
647			return (0);
648	}
649	return (ENOENT);
650}
651
652int
653linker_ddb_search_symbol(caddr_t value, c_linker_sym_t *sym, long *diffp)
654{
655	linker_file_t lf;
656	c_linker_sym_t best, es;
657	u_long diff, bestdiff, off;
658
659	best = 0;
660	off = (uintptr_t)value;
661	bestdiff = off;
662	TAILQ_FOREACH(lf, &linker_files, link) {
663		if (LINKER_SEARCH_SYMBOL(lf, value, &es, &diff) != 0)
664			continue;
665		if (es != 0 && diff < bestdiff) {
666			best = es;
667			bestdiff = diff;
668		}
669		if (bestdiff == 0)
670			break;
671	}
672	if (best) {
673		*sym = best;
674		*diffp = bestdiff;
675		return (0);
676	} else {
677		*sym = 0;
678		*diffp = off;
679		return (ENOENT);
680	}
681}
682
683int
684linker_ddb_symbol_values(c_linker_sym_t sym, linker_symval_t *symval)
685{
686	linker_file_t lf;
687
688	TAILQ_FOREACH(lf, &linker_files, link) {
689		if (LINKER_SYMBOL_VALUES(lf, sym, symval) == 0)
690			return (0);
691	}
692	return (ENOENT);
693}
694#endif
695
696/*
697 * Syscalls.
698 */
699/*
700 * MPSAFE
701 */
702int
703kldload(struct thread *td, struct kldload_args *uap)
704{
705	char *kldname, *modname;
706	char *pathname = NULL;
707	linker_file_t lf;
708	int error = 0;
709
710	td->td_retval[0] = -1;
711
712	mtx_lock(&Giant);
713
714	if ((error = securelevel_gt(td->td_ucred, 0)) != 0)
715		goto out;
716
717	if ((error = suser(td)) != 0)
718		goto out;
719
720	pathname = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
721	if ((error = copyinstr(SCARG(uap, file), pathname, MAXPATHLEN,
722	    NULL)) != 0)
723		goto out;
724
725	/*
726	 * If path do not contain qualified name or any dot in it
727	 * (kldname.ko, or kldname.ver.ko) treat it as interface
728	 * name.
729	 */
730	if (index(pathname, '/') || index(pathname, '.')) {
731		kldname = pathname;
732		modname = NULL;
733	} else {
734		kldname = NULL;
735		modname = pathname;
736	}
737	error = linker_load_module(kldname, modname, NULL, NULL, &lf);
738	if (error)
739		goto out;
740
741	lf->userrefs++;
742	td->td_retval[0] = lf->id;
743out:
744	if (pathname)
745		free(pathname, M_TEMP);
746	mtx_unlock(&Giant);
747	return (error);
748}
749
750/*
751 * MPSAFE
752 */
753int
754kldunload(struct thread *td, struct kldunload_args *uap)
755{
756	linker_file_t lf;
757	int error = 0;
758
759	mtx_lock(&Giant);
760
761	if ((error = securelevel_gt(td->td_ucred, 0)) != 0)
762		goto out;
763
764	if ((error = suser(td)) != 0)
765		goto out;
766
767	lf = linker_find_file_by_id(SCARG(uap, fileid));
768	if (lf) {
769		KLD_DPF(FILE, ("kldunload: lf->userrefs=%d\n", lf->userrefs));
770		if (lf->userrefs == 0) {
771			printf("kldunload: attempt to unload file that was"
772			    " loaded by the kernel\n");
773			error = EBUSY;
774			goto out;
775		}
776		lf->userrefs--;
777		error = linker_file_unload(lf);
778		if (error)
779			lf->userrefs++;
780	} else
781		error = ENOENT;
782out:
783	mtx_unlock(&Giant);
784	return (error);
785}
786
787/*
788 * MPSAFE
789 */
790int
791kldfind(struct thread *td, struct kldfind_args *uap)
792{
793	char *pathname;
794	const char *filename;
795	linker_file_t lf;
796	int error = 0;
797
798	mtx_lock(&Giant);
799	td->td_retval[0] = -1;
800
801	pathname = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
802	if ((error = copyinstr(SCARG(uap, file), pathname, MAXPATHLEN,
803	    NULL)) != 0)
804		goto out;
805
806	filename = linker_basename(pathname);
807	lf = linker_find_file_by_name(filename);
808	if (lf)
809		td->td_retval[0] = lf->id;
810	else
811		error = ENOENT;
812out:
813	if (pathname)
814		free(pathname, M_TEMP);
815	mtx_unlock(&Giant);
816	return (error);
817}
818
819/*
820 * MPSAFE
821 */
822int
823kldnext(struct thread *td, struct kldnext_args *uap)
824{
825	linker_file_t lf;
826	int error = 0;
827
828	mtx_lock(&Giant);
829
830	if (SCARG(uap, fileid) == 0) {
831		if (TAILQ_FIRST(&linker_files))
832			td->td_retval[0] = TAILQ_FIRST(&linker_files)->id;
833		else
834			td->td_retval[0] = 0;
835		goto out;
836	}
837	lf = linker_find_file_by_id(SCARG(uap, fileid));
838	if (lf) {
839		if (TAILQ_NEXT(lf, link))
840			td->td_retval[0] = TAILQ_NEXT(lf, link)->id;
841		else
842			td->td_retval[0] = 0;
843	} else
844		error = ENOENT;
845out:
846	mtx_unlock(&Giant);
847	return (error);
848}
849
850/*
851 * MPSAFE
852 */
853int
854kldstat(struct thread *td, struct kldstat_args *uap)
855{
856	linker_file_t lf;
857	int error = 0;
858	int namelen, version;
859	struct kld_file_stat *stat;
860
861	mtx_lock(&Giant);
862
863	lf = linker_find_file_by_id(SCARG(uap, fileid));
864	if (lf == NULL) {
865		error = ENOENT;
866		goto out;
867	}
868	stat = SCARG(uap, stat);
869
870	/*
871	 * Check the version of the user's structure.
872	 */
873	if ((error = copyin(&stat->version, &version, sizeof(version))) != 0)
874		goto out;
875	if (version != sizeof(struct kld_file_stat)) {
876		error = EINVAL;
877		goto out;
878	}
879	namelen = strlen(lf->filename) + 1;
880	if (namelen > MAXPATHLEN)
881		namelen = MAXPATHLEN;
882	if ((error = copyout(lf->filename, &stat->name[0], namelen)) != 0)
883		goto out;
884	if ((error = copyout(&lf->refs, &stat->refs, sizeof(int))) != 0)
885		goto out;
886	if ((error = copyout(&lf->id, &stat->id, sizeof(int))) != 0)
887		goto out;
888	if ((error = copyout(&lf->address, &stat->address,
889	    sizeof(caddr_t))) != 0)
890		goto out;
891	if ((error = copyout(&lf->size, &stat->size, sizeof(size_t))) != 0)
892		goto out;
893
894	td->td_retval[0] = 0;
895out:
896	mtx_unlock(&Giant);
897	return (error);
898}
899
900/*
901 * MPSAFE
902 */
903int
904kldfirstmod(struct thread *td, struct kldfirstmod_args *uap)
905{
906	linker_file_t lf;
907	module_t mp;
908	int error = 0;
909
910	mtx_lock(&Giant);
911	lf = linker_find_file_by_id(SCARG(uap, fileid));
912	if (lf) {
913		MOD_SLOCK;
914		mp = TAILQ_FIRST(&lf->modules);
915		if (mp != NULL)
916			td->td_retval[0] = module_getid(mp);
917		else
918			td->td_retval[0] = 0;
919		MOD_SUNLOCK;
920	} else
921		error = ENOENT;
922	mtx_unlock(&Giant);
923	return (error);
924}
925
926/*
927 * MPSAFE
928 */
929int
930kldsym(struct thread *td, struct kldsym_args *uap)
931{
932	char *symstr = NULL;
933	c_linker_sym_t sym;
934	linker_symval_t symval;
935	linker_file_t lf;
936	struct kld_sym_lookup lookup;
937	int error = 0;
938
939	mtx_lock(&Giant);
940
941	if ((error = copyin(SCARG(uap, data), &lookup, sizeof(lookup))) != 0)
942		goto out;
943	if (lookup.version != sizeof(lookup) ||
944	    SCARG(uap, cmd) != KLDSYM_LOOKUP) {
945		error = EINVAL;
946		goto out;
947	}
948	symstr = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
949	if ((error = copyinstr(lookup.symname, symstr, MAXPATHLEN, NULL)) != 0)
950		goto out;
951	if (SCARG(uap, fileid) != 0) {
952		lf = linker_find_file_by_id(SCARG(uap, fileid));
953		if (lf == NULL) {
954			error = ENOENT;
955			goto out;
956		}
957		if (LINKER_LOOKUP_SYMBOL(lf, symstr, &sym) == 0 &&
958		    LINKER_SYMBOL_VALUES(lf, sym, &symval) == 0) {
959			lookup.symvalue = (uintptr_t) symval.value;
960			lookup.symsize = symval.size;
961			error = copyout(&lookup, SCARG(uap, data),
962			    sizeof(lookup));
963		} else
964			error = ENOENT;
965	} else {
966		TAILQ_FOREACH(lf, &linker_files, link) {
967			if (LINKER_LOOKUP_SYMBOL(lf, symstr, &sym) == 0 &&
968			    LINKER_SYMBOL_VALUES(lf, sym, &symval) == 0) {
969				lookup.symvalue = (uintptr_t)symval.value;
970				lookup.symsize = symval.size;
971				error = copyout(&lookup, SCARG(uap, data),
972				    sizeof(lookup));
973				break;
974			}
975		}
976		if (lf == NULL)
977			error = ENOENT;
978	}
979out:
980	if (symstr)
981		free(symstr, M_TEMP);
982	mtx_unlock(&Giant);
983	return (error);
984}
985
986/*
987 * Preloaded module support
988 */
989
990static modlist_t
991modlist_lookup(const char *name, int ver)
992{
993	modlist_t mod;
994
995	TAILQ_FOREACH(mod, &found_modules, link) {
996		if (strcmp(mod->name, name) == 0 &&
997		    (ver == 0 || mod->version == ver))
998			return (mod);
999	}
1000	return (NULL);
1001}
1002
1003static modlist_t
1004modlist_lookup2(const char *name, struct mod_depend *verinfo)
1005{
1006	modlist_t mod, bestmod;
1007	int ver;
1008
1009	if (verinfo == NULL)
1010		return (modlist_lookup(name, 0));
1011	bestmod = NULL;
1012	for (mod = TAILQ_FIRST(&found_modules); mod;
1013	    mod = TAILQ_NEXT(mod, link)) {
1014		if (strcmp(mod->name, name) != 0)
1015			continue;
1016		ver = mod->version;
1017		if (ver == verinfo->md_ver_preferred)
1018			return (mod);
1019		if (ver >= verinfo->md_ver_minimum &&
1020		    ver <= verinfo->md_ver_maximum &&
1021		    ver > bestmod->version)
1022			bestmod = mod;
1023	}
1024	return (bestmod);
1025}
1026
1027static modlist_t
1028modlist_newmodule(const char *modname, int version, linker_file_t container)
1029{
1030	modlist_t mod;
1031
1032	mod = malloc(sizeof(struct modlist), M_LINKER, M_NOWAIT | M_ZERO);
1033	if (mod == NULL)
1034		panic("no memory for module list");
1035	mod->container = container;
1036	mod->name = modname;
1037	mod->version = version;
1038	TAILQ_INSERT_TAIL(&found_modules, mod, link);
1039	return (mod);
1040}
1041
1042/*
1043 * This routine is cheap and nasty but will work for data pointers.
1044 */
1045static void *
1046linker_reloc_ptr(linker_file_t lf, const void *offset)
1047{
1048	return (lf->address + (uintptr_t)offset);
1049}
1050
1051/*
1052 * Dereference MDT_VERSION metadata into module name and version
1053 */
1054static void
1055linker_mdt_version(linker_file_t lf, struct mod_metadata *mp,
1056    const char **modname, int *version)
1057{
1058	struct mod_version *mvp;
1059
1060	if (modname)
1061		*modname = linker_reloc_ptr(lf, mp->md_cval);
1062	if (version) {
1063		mvp = linker_reloc_ptr(lf, mp->md_data);
1064		*version = mvp->mv_version;
1065	}
1066}
1067
1068/*
1069 * Dereference MDT_DEPEND metadata into module name and mod_depend structure
1070 */
1071static void
1072linker_mdt_depend(linker_file_t lf, struct mod_metadata *mp,
1073    const char **modname, struct mod_depend **verinfo)
1074{
1075
1076	if (modname)
1077		*modname = linker_reloc_ptr(lf, mp->md_cval);
1078	if (verinfo)
1079		*verinfo = linker_reloc_ptr(lf, mp->md_data);
1080}
1081
1082static void
1083linker_addmodules(linker_file_t lf, struct mod_metadata **start,
1084    struct mod_metadata **stop, int preload)
1085{
1086	struct mod_metadata *mp, **mdp;
1087	const char *modname;
1088	int ver;
1089
1090	for (mdp = start; mdp < stop; mdp++) {
1091		if (preload)
1092			mp = *mdp;
1093		else
1094			mp = linker_reloc_ptr(lf, *mdp);
1095		if (mp->md_type != MDT_VERSION)
1096			continue;
1097		if (preload) {
1098			modname = mp->md_cval;
1099			ver = ((struct mod_version *)mp->md_data)->mv_version;
1100		} else
1101	        	linker_mdt_version(lf, mp, &modname, &ver);
1102		if (modlist_lookup(modname, ver) != NULL) {
1103			printf("module %s already present!\n", modname);
1104			/* XXX what can we do? this is a build error. :-( */
1105			continue;
1106		}
1107		modlist_newmodule(modname, ver, lf);
1108	}
1109}
1110
1111static void
1112linker_preload(void *arg)
1113{
1114	caddr_t modptr;
1115	const char *modname, *nmodname;
1116	char *modtype;
1117	linker_file_t lf;
1118	linker_class_t lc;
1119	int error;
1120	linker_file_list_t loaded_files;
1121	linker_file_list_t depended_files;
1122	struct mod_metadata *mp, *nmp;
1123	struct mod_metadata **start, **stop, **mdp, **nmdp;
1124	struct mod_depend *verinfo;
1125	int nver;
1126	int resolves;
1127	modlist_t mod;
1128	struct sysinit **si_start, **si_stop;
1129
1130	TAILQ_INIT(&loaded_files);
1131	TAILQ_INIT(&depended_files);
1132	TAILQ_INIT(&found_modules);
1133	error = 0;
1134
1135	modptr = NULL;
1136	while ((modptr = preload_search_next_name(modptr)) != NULL) {
1137		modname = (char *)preload_search_info(modptr, MODINFO_NAME);
1138		modtype = (char *)preload_search_info(modptr, MODINFO_TYPE);
1139		if (modname == NULL) {
1140			printf("Preloaded module at %p does not have a"
1141			    " name!\n", modptr);
1142			continue;
1143		}
1144		if (modtype == NULL) {
1145			printf("Preloaded module at %p does not have a type!\n",
1146			    modptr);
1147			continue;
1148		}
1149		printf("Preloaded %s \"%s\" at %p.\n", modtype, modname,
1150		    modptr);
1151		lf = NULL;
1152		TAILQ_FOREACH(lc, &classes, link) {
1153			error = LINKER_LINK_PRELOAD(lc, modname, &lf);
1154			if (error) {
1155				lf = NULL;
1156				break;
1157			}
1158		}
1159		if (lf)
1160			TAILQ_INSERT_TAIL(&loaded_files, lf, loaded);
1161	}
1162
1163	/*
1164	 * First get a list of stuff in the kernel.
1165	 */
1166	if (linker_file_lookup_set(linker_kernel_file, MDT_SETNAME, &start,
1167	    &stop, NULL) == 0)
1168		linker_addmodules(linker_kernel_file, start, stop, 1);
1169
1170	/*
1171	 * this is a once-off kinky bubble sort resolve relocation dependency
1172	 * requirements
1173	 */
1174restart:
1175	TAILQ_FOREACH(lf, &loaded_files, loaded) {
1176		error = linker_file_lookup_set(lf, MDT_SETNAME, &start,
1177		    &stop, NULL);
1178		/*
1179		 * First, look to see if we would successfully link with this
1180		 * stuff.
1181		 */
1182		resolves = 1;	/* unless we know otherwise */
1183		if (!error) {
1184			for (mdp = start; mdp < stop; mdp++) {
1185				mp = linker_reloc_ptr(lf, *mdp);
1186				if (mp->md_type != MDT_DEPEND)
1187					continue;
1188				linker_mdt_depend(lf, mp, &modname, &verinfo);
1189				for (nmdp = start; nmdp < stop; nmdp++) {
1190					nmp = linker_reloc_ptr(lf, *nmdp);
1191					if (nmp->md_type != MDT_VERSION)
1192						continue;
1193					linker_mdt_version(lf, nmp, &nmodname,
1194					    NULL);
1195					nmodname = linker_reloc_ptr(lf,
1196					    nmp->md_cval);
1197					if (strcmp(modname, nmodname) == 0)
1198						break;
1199				}
1200				if (nmdp < stop)   /* it's a self reference */
1201					continue;
1202
1203				/*
1204				 * ok, the module isn't here yet, we
1205				 * are not finished
1206				 */
1207				if (modlist_lookup2(modname, verinfo) == NULL)
1208					resolves = 0;
1209			}
1210		}
1211		/*
1212		 * OK, if we found our modules, we can link.  So, "provide"
1213		 * the modules inside and add it to the end of the link order
1214		 * list.
1215		 */
1216		if (resolves) {
1217			if (!error) {
1218				for (mdp = start; mdp < stop; mdp++) {
1219					mp = linker_reloc_ptr(lf, *mdp);
1220					if (mp->md_type != MDT_VERSION)
1221						continue;
1222					linker_mdt_version(lf, mp,
1223					    &modname, &nver);
1224					if (modlist_lookup(modname,
1225					    nver) != NULL) {
1226						printf("module %s already"
1227						    " present!\n", modname);
1228						linker_file_unload(lf);
1229						TAILQ_REMOVE(&loaded_files,
1230						    lf, loaded);
1231						/* we changed tailq next ptr */
1232						goto restart;
1233					}
1234					modlist_newmodule(modname, nver, lf);
1235				}
1236			}
1237			TAILQ_REMOVE(&loaded_files, lf, loaded);
1238			TAILQ_INSERT_TAIL(&depended_files, lf, loaded);
1239			/*
1240			 * Since we provided modules, we need to restart the
1241			 * sort so that the previous files that depend on us
1242			 * have a chance. Also, we've busted the tailq next
1243			 * pointer with the REMOVE.
1244			 */
1245			goto restart;
1246		}
1247	}
1248
1249	/*
1250	 * At this point, we check to see what could not be resolved..
1251	 */
1252	TAILQ_FOREACH(lf, &loaded_files, loaded) {
1253		printf("KLD file %s is missing dependencies\n", lf->filename);
1254		linker_file_unload(lf);
1255		TAILQ_REMOVE(&loaded_files, lf, loaded);
1256	}
1257
1258	/*
1259	 * We made it. Finish off the linking in the order we determined.
1260	 */
1261	TAILQ_FOREACH(lf, &depended_files, loaded) {
1262		if (linker_kernel_file) {
1263			linker_kernel_file->refs++;
1264			error = linker_file_add_dependency(lf,
1265			    linker_kernel_file);
1266			if (error)
1267				panic("cannot add dependency");
1268		}
1269		lf->userrefs++;	/* so we can (try to) kldunload it */
1270		error = linker_file_lookup_set(lf, MDT_SETNAME, &start,
1271		    &stop, NULL);
1272		if (!error) {
1273			for (mdp = start; mdp < stop; mdp++) {
1274				mp = linker_reloc_ptr(lf, *mdp);
1275				if (mp->md_type != MDT_DEPEND)
1276					continue;
1277				linker_mdt_depend(lf, mp, &modname, &verinfo);
1278				mod = modlist_lookup2(modname, verinfo);
1279				mod->container->refs++;
1280				error = linker_file_add_dependency(lf,
1281				    mod->container);
1282				if (error)
1283					panic("cannot add dependency");
1284			}
1285		}
1286		/*
1287		 * Now do relocation etc using the symbol search paths
1288		 * established by the dependencies
1289		 */
1290		error = LINKER_LINK_PRELOAD_FINISH(lf);
1291		if (error) {
1292			printf("KLD file %s - could not finalize loading\n",
1293			    lf->filename);
1294			linker_file_unload(lf);
1295			continue;
1296		}
1297		linker_file_register_modules(lf);
1298		if (linker_file_lookup_set(lf, "sysinit_set", &si_start,
1299		    &si_stop, NULL) == 0)
1300			sysinit_add(si_start, si_stop);
1301		linker_file_register_sysctls(lf);
1302		lf->flags |= LINKER_FILE_LINKED;
1303	}
1304	/* woohoo! we made it! */
1305}
1306
1307SYSINIT(preload, SI_SUB_KLD, SI_ORDER_MIDDLE, linker_preload, 0)
1308
1309/*
1310 * Search for a not-loaded module by name.
1311 *
1312 * Modules may be found in the following locations:
1313 *
1314 * - preloaded (result is just the module name) - on disk (result is full path
1315 * to module)
1316 *
1317 * If the module name is qualified in any way (contains path, etc.) the we
1318 * simply return a copy of it.
1319 *
1320 * The search path can be manipulated via sysctl.  Note that we use the ';'
1321 * character as a separator to be consistent with the bootloader.
1322 */
1323
1324static char linker_hintfile[] = "linker.hints";
1325static char linker_path[MAXPATHLEN] = "/boot/kernel;/boot/modules;/modules";
1326
1327SYSCTL_STRING(_kern, OID_AUTO, module_path, CTLFLAG_RW, linker_path,
1328    sizeof(linker_path), "module load search path");
1329
1330TUNABLE_STR("module_path", linker_path, sizeof(linker_path));
1331
1332static char *linker_ext_list[] = {
1333	"",
1334	".ko",
1335	NULL
1336};
1337
1338/*
1339 * Check if file actually exists either with or without extension listed in
1340 * the linker_ext_list. (probably should be generic for the rest of the
1341 * kernel)
1342 */
1343static char *
1344linker_lookup_file(const char *path, int pathlen, const char *name,
1345    int namelen, struct vattr *vap)
1346{
1347	struct nameidata nd;
1348	struct thread *td = curthread;	/* XXX */
1349	char *result, **cpp, *sep;
1350	int error, len, extlen, reclen, flags;
1351	enum vtype type;
1352
1353	extlen = 0;
1354	for (cpp = linker_ext_list; *cpp; cpp++) {
1355		len = strlen(*cpp);
1356		if (len > extlen)
1357			extlen = len;
1358	}
1359	extlen++;		/* trailing '\0' */
1360	sep = (path[pathlen - 1] != '/') ? "/" : "";
1361
1362	reclen = pathlen + strlen(sep) + namelen + extlen + 1;
1363	result = malloc(reclen, M_LINKER, M_WAITOK);
1364	for (cpp = linker_ext_list; *cpp; cpp++) {
1365		snprintf(result, reclen, "%.*s%s%.*s%s", pathlen, path, sep,
1366		    namelen, name, *cpp);
1367		/*
1368		 * Attempt to open the file, and return the path if
1369		 * we succeed and it's a regular file.
1370		 */
1371		NDINIT(&nd, LOOKUP, FOLLOW, UIO_SYSSPACE, result, td);
1372		flags = FREAD;
1373		error = vn_open(&nd, &flags, 0);
1374		if (error == 0) {
1375			NDFREE(&nd, NDF_ONLY_PNBUF);
1376			type = nd.ni_vp->v_type;
1377			if (vap)
1378				VOP_GETATTR(nd.ni_vp, vap, td->td_ucred, td);
1379			VOP_UNLOCK(nd.ni_vp, 0, td);
1380			vn_close(nd.ni_vp, FREAD, td->td_ucred, td);
1381			if (type == VREG)
1382				return (result);
1383		}
1384	}
1385	free(result, M_LINKER);
1386	return (NULL);
1387}
1388
1389#define	INT_ALIGN(base, ptr)	ptr =					\
1390	(base) + (((ptr) - (base) + sizeof(int) - 1) & ~(sizeof(int) - 1))
1391
1392/*
1393 * Lookup KLD which contains requested module in the "linker.hints" file. If
1394 * version specification is available, then try to find the best KLD.
1395 * Otherwise just find the latest one.
1396 *
1397 * XXX: Vnode locking here is hosed; lock should be held for calls to
1398 * VOP_GETATTR() and vn_rdwr().
1399 */
1400static char *
1401linker_hints_lookup(const char *path, int pathlen, const char *modname,
1402    int modnamelen, struct mod_depend *verinfo)
1403{
1404	struct thread *td = curthread;	/* XXX */
1405	struct ucred *cred = td ? td->td_ucred : NULL;
1406	struct nameidata nd;
1407	struct vattr vattr, mattr;
1408	u_char *hints = NULL;
1409	u_char *cp, *recptr, *bufend, *result, *best, *pathbuf, *sep;
1410	int error, ival, bestver, *intp, reclen, found, flags, clen, blen;
1411
1412	result = NULL;
1413	bestver = found = 0;
1414
1415	sep = (path[pathlen - 1] != '/') ? "/" : "";
1416	reclen = imax(modnamelen, strlen(linker_hintfile)) + pathlen +
1417	    strlen(sep) + 1;
1418	pathbuf = malloc(reclen, M_LINKER, M_WAITOK);
1419	snprintf(pathbuf, reclen, "%.*s%s%s", pathlen, path, sep,
1420	    linker_hintfile);
1421
1422	NDINIT(&nd, LOOKUP, NOFOLLOW, UIO_SYSSPACE, pathbuf, td);
1423	flags = FREAD;
1424	error = vn_open(&nd, &flags, 0);
1425	if (error)
1426		goto bad;
1427	NDFREE(&nd, NDF_ONLY_PNBUF);
1428	VOP_UNLOCK(nd.ni_vp, 0, td);
1429	if (nd.ni_vp->v_type != VREG)
1430		goto bad;
1431	best = cp = NULL;
1432	error = VOP_GETATTR(nd.ni_vp, &vattr, cred, td);
1433	if (error)
1434		goto bad;
1435	/*
1436	 * XXX: we need to limit this number to some reasonable value
1437	 */
1438	if (vattr.va_size > 100 * 1024) {
1439		printf("hints file too large %ld\n", (long)vattr.va_size);
1440		goto bad;
1441	}
1442	hints = malloc(vattr.va_size, M_TEMP, M_WAITOK);
1443	if (hints == NULL)
1444		goto bad;
1445	error = vn_rdwr(UIO_READ, nd.ni_vp, (caddr_t)hints, vattr.va_size, 0,
1446	    UIO_SYSSPACE, IO_NODELOCKED, cred, &reclen, td);
1447	if (error)
1448		goto bad;
1449	vn_close(nd.ni_vp, FREAD, cred, td);
1450	nd.ni_vp = NULL;
1451	if (reclen != 0) {
1452		printf("can't read %d\n", reclen);
1453		goto bad;
1454	}
1455	intp = (int *)hints;
1456	ival = *intp++;
1457	if (ival != LINKER_HINTS_VERSION) {
1458		printf("hints file version mismatch %d\n", ival);
1459		goto bad;
1460	}
1461	bufend = hints + vattr.va_size;
1462	recptr = (u_char *)intp;
1463	clen = blen = 0;
1464	while (recptr < bufend && !found) {
1465		intp = (int *)recptr;
1466		reclen = *intp++;
1467		ival = *intp++;
1468		cp = (char *)intp;
1469		switch (ival) {
1470		case MDT_VERSION:
1471			clen = *cp++;
1472			if (clen != modnamelen || bcmp(cp, modname, clen) != 0)
1473				break;
1474			cp += clen;
1475			INT_ALIGN(hints, cp);
1476			ival = *(int *)cp;
1477			cp += sizeof(int);
1478			clen = *cp++;
1479			if (verinfo == NULL ||
1480			    ival == verinfo->md_ver_preferred) {
1481				found = 1;
1482				break;
1483			}
1484			if (ival >= verinfo->md_ver_minimum &&
1485			    ival <= verinfo->md_ver_maximum &&
1486			    ival > bestver) {
1487				bestver = ival;
1488				best = cp;
1489				blen = clen;
1490			}
1491			break;
1492		default:
1493			break;
1494		}
1495		recptr += reclen + sizeof(int);
1496	}
1497	/*
1498	 * Finally check if KLD is in the place
1499	 */
1500	if (found)
1501		result = linker_lookup_file(path, pathlen, cp, clen, &mattr);
1502	else if (best)
1503		result = linker_lookup_file(path, pathlen, best, blen, &mattr);
1504
1505	/*
1506	 * KLD is newer than hints file. What we should do now?
1507	 */
1508	if (result && timespeccmp(&mattr.va_mtime, &vattr.va_mtime, >))
1509		printf("warning: KLD '%s' is newer than the linker.hints"
1510		    " file\n", result);
1511bad:
1512	if (hints)
1513		free(hints, M_TEMP);
1514	if (nd.ni_vp != NULL)
1515		vn_close(nd.ni_vp, FREAD, cred, td);
1516	/*
1517	 * If nothing found or hints is absent - fallback to the old
1518	 * way by using "kldname[.ko]" as module name.
1519	 */
1520	if (!found && !bestver && result == NULL)
1521		result = linker_lookup_file(path, pathlen, modname,
1522		    modnamelen, NULL);
1523	return (result);
1524}
1525
1526/*
1527 * Lookup KLD which contains requested module in the all directories.
1528 */
1529static char *
1530linker_search_module(const char *modname, int modnamelen,
1531    struct mod_depend *verinfo)
1532{
1533	char *cp, *ep, *result;
1534
1535	/*
1536	 * traverse the linker path
1537	 */
1538	for (cp = linker_path; *cp; cp = ep + 1) {
1539		/* find the end of this component */
1540		for (ep = cp; (*ep != 0) && (*ep != ';'); ep++);
1541		result = linker_hints_lookup(cp, ep - cp, modname,
1542		    modnamelen, verinfo);
1543		if (result != NULL)
1544			return (result);
1545		if (*ep == 0)
1546			break;
1547	}
1548	return (NULL);
1549}
1550
1551/*
1552 * Search for module in all directories listed in the linker_path.
1553 */
1554static char *
1555linker_search_kld(const char *name)
1556{
1557	char *cp, *ep, *result, **cpp;
1558	int extlen, len;
1559
1560	/* qualified at all? */
1561	if (index(name, '/'))
1562		return (linker_strdup(name));
1563
1564	extlen = 0;
1565	for (cpp = linker_ext_list; *cpp; cpp++) {
1566		len = strlen(*cpp);
1567		if (len > extlen)
1568			extlen = len;
1569	}
1570	extlen++;		/* trailing '\0' */
1571
1572	/* traverse the linker path */
1573	len = strlen(name);
1574	for (ep = linker_path; *ep; ep++) {
1575		cp = ep;
1576		/* find the end of this component */
1577		for (; *ep != 0 && *ep != ';'; ep++);
1578		result = linker_lookup_file(cp, ep - cp, name, len, NULL);
1579		if (result != NULL)
1580			return (result);
1581	}
1582	return (NULL);
1583}
1584
1585static const char *
1586linker_basename(const char *path)
1587{
1588	const char *filename;
1589
1590	filename = rindex(path, '/');
1591	if (filename == NULL)
1592		return path;
1593	if (filename[1])
1594		filename++;
1595	return (filename);
1596}
1597
1598/*
1599 * Find a file which contains given module and load it, if "parent" is not
1600 * NULL, register a reference to it.
1601 */
1602static int
1603linker_load_module(const char *kldname, const char *modname,
1604    struct linker_file *parent, struct mod_depend *verinfo,
1605    struct linker_file **lfpp)
1606{
1607	linker_file_t lfdep;
1608	const char *filename;
1609	char *pathname;
1610	int error;
1611
1612	if (modname == NULL) {
1613		/*
1614 		 * We have to load KLD
1615 		 */
1616		KASSERT(verinfo == NULL, ("linker_load_module: verinfo"
1617		    " is not NULL"));
1618		pathname = linker_search_kld(kldname);
1619	} else {
1620		if (modlist_lookup2(modname, verinfo) != NULL)
1621			return (EEXIST);
1622		if (kldname != NULL)
1623			pathname = linker_strdup(kldname);
1624		else if (rootvnode == NULL)
1625			pathname = NULL;
1626		else
1627			/*
1628			 * Need to find a KLD with required module
1629			 */
1630			pathname = linker_search_module(modname,
1631			    strlen(modname), verinfo);
1632	}
1633	if (pathname == NULL)
1634		return (ENOENT);
1635
1636	/*
1637	 * Can't load more than one file with the same basename XXX:
1638	 * Actually it should be possible to have multiple KLDs with
1639	 * the same basename but different path because they can
1640	 * provide different versions of the same modules.
1641	 */
1642	filename = linker_basename(pathname);
1643	if (linker_find_file_by_name(filename)) {
1644		error = EEXIST;
1645		goto out;
1646	}
1647	do {
1648		error = linker_load_file(pathname, &lfdep);
1649		if (error)
1650			break;
1651		if (modname && verinfo &&
1652		    modlist_lookup2(modname, verinfo) == NULL) {
1653			linker_file_unload(lfdep);
1654			error = ENOENT;
1655			break;
1656		}
1657		if (parent) {
1658			error = linker_file_add_dependency(parent, lfdep);
1659			if (error)
1660				break;
1661		}
1662		if (lfpp)
1663			*lfpp = lfdep;
1664	} while (0);
1665out:
1666	if (pathname)
1667		free(pathname, M_LINKER);
1668	return (error);
1669}
1670
1671/*
1672 * This routine is responsible for finding dependencies of userland initiated
1673 * kldload(2)'s of files.
1674 */
1675int
1676linker_load_dependencies(linker_file_t lf)
1677{
1678	linker_file_t lfdep;
1679	struct mod_metadata **start, **stop, **mdp, **nmdp;
1680	struct mod_metadata *mp, *nmp;
1681	struct mod_depend *verinfo;
1682	modlist_t mod;
1683	const char *modname, *nmodname;
1684	int ver, error = 0, count;
1685
1686	/*
1687	 * All files are dependant on /kernel.
1688	 */
1689	if (linker_kernel_file) {
1690		linker_kernel_file->refs++;
1691		error = linker_file_add_dependency(lf, linker_kernel_file);
1692		if (error)
1693			return (error);
1694	}
1695	if (linker_file_lookup_set(lf, MDT_SETNAME, &start, &stop,
1696	    &count) != 0)
1697		return (0);
1698	for (mdp = start; mdp < stop; mdp++) {
1699		mp = linker_reloc_ptr(lf, *mdp);
1700		if (mp->md_type != MDT_VERSION)
1701			continue;
1702		linker_mdt_version(lf, mp, &modname, &ver);
1703		mod = modlist_lookup(modname, ver);
1704		if (mod != NULL) {
1705			printf("interface %s.%d already present in the KLD"
1706			    " '%s'!\n", modname, ver,
1707			    mod->container->filename);
1708			return (EEXIST);
1709		}
1710	}
1711
1712	for (mdp = start; mdp < stop; mdp++) {
1713		mp = linker_reloc_ptr(lf, *mdp);
1714		if (mp->md_type != MDT_DEPEND)
1715			continue;
1716		linker_mdt_depend(lf, mp, &modname, &verinfo);
1717		nmodname = NULL;
1718		for (nmdp = start; nmdp < stop; nmdp++) {
1719			nmp = linker_reloc_ptr(lf, *nmdp);
1720			if (nmp->md_type != MDT_VERSION)
1721				continue;
1722			nmodname = linker_reloc_ptr(lf, nmp->md_cval);
1723			if (strcmp(modname, nmodname) == 0)
1724				break;
1725		}
1726		if (nmdp < stop)/* early exit, it's a self reference */
1727			continue;
1728		mod = modlist_lookup2(modname, verinfo);
1729		if (mod) {	/* woohoo, it's loaded already */
1730			lfdep = mod->container;
1731			lfdep->refs++;
1732			error = linker_file_add_dependency(lf, lfdep);
1733			if (error)
1734				break;
1735			continue;
1736		}
1737		error = linker_load_module(NULL, modname, lf, verinfo, NULL);
1738		if (error) {
1739			printf("KLD %s: depends on %s - not available\n",
1740			    lf->filename, modname);
1741			break;
1742		}
1743	}
1744
1745	if (error)
1746		return (error);
1747	linker_addmodules(lf, start, stop, 0);
1748	return (error);
1749}
1750
1751static int
1752sysctl_kern_function_list_iterate(const char *name, void *opaque)
1753{
1754	struct sysctl_req *req;
1755
1756	req = opaque;
1757	return (SYSCTL_OUT(req, name, strlen(name) + 1));
1758}
1759
1760/*
1761 * Export a nul-separated, double-nul-terminated list of all function names
1762 * in the kernel.
1763 */
1764static int
1765sysctl_kern_function_list(SYSCTL_HANDLER_ARGS)
1766{
1767	linker_file_t lf;
1768	int error;
1769
1770	TAILQ_FOREACH(lf, &linker_files, link) {
1771		error = LINKER_EACH_FUNCTION_NAME(lf,
1772		    sysctl_kern_function_list_iterate, req);
1773		if (error)
1774			return (error);
1775	}
1776	return (SYSCTL_OUT(req, "", 1));
1777}
1778
1779SYSCTL_PROC(_kern, OID_AUTO, function_list, CTLFLAG_RD,
1780    NULL, 0, sysctl_kern_function_list, "", "kernel function list");
1781