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