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