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