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