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