xref: /freebsd/sys/kern/kern_linker.c (revision e39e854e27f53a784c3982cbeb68f4ad1cfd9162)
1 /*-
2  * Copyright (c) 1997-2000 Doug Rabson
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26 
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29 
30 #include "opt_ddb.h"
31 #include "opt_kld.h"
32 #include "opt_hwpmc_hooks.h"
33 
34 #include <sys/param.h>
35 #include <sys/kernel.h>
36 #include <sys/systm.h>
37 #include <sys/malloc.h>
38 #include <sys/sysproto.h>
39 #include <sys/sysent.h>
40 #include <sys/priv.h>
41 #include <sys/proc.h>
42 #include <sys/lock.h>
43 #include <sys/mutex.h>
44 #include <sys/sx.h>
45 #include <sys/module.h>
46 #include <sys/mount.h>
47 #include <sys/linker.h>
48 #include <sys/fcntl.h>
49 #include <sys/jail.h>
50 #include <sys/libkern.h>
51 #include <sys/namei.h>
52 #include <sys/vnode.h>
53 #include <sys/syscallsubr.h>
54 #include <sys/sysctl.h>
55 
56 #include <net/vnet.h>
57 
58 #include <security/mac/mac_framework.h>
59 
60 #include "linker_if.h"
61 
62 #ifdef HWPMC_HOOKS
63 #include <sys/pmckern.h>
64 #endif
65 
66 #ifdef KLD_DEBUG
67 int kld_debug = 0;
68 SYSCTL_INT(_debug, OID_AUTO, kld_debug, CTLFLAG_RW | CTLFLAG_TUN,
69     &kld_debug, 0, "Set various levels of KLD debug");
70 TUNABLE_INT("debug.kld_debug", &kld_debug);
71 #endif
72 
73 #define	KLD_LOCK()		sx_xlock(&kld_sx)
74 #define	KLD_UNLOCK()		sx_xunlock(&kld_sx)
75 #define	KLD_DOWNGRADE()		sx_downgrade(&kld_sx)
76 #define	KLD_LOCK_READ()		sx_slock(&kld_sx)
77 #define	KLD_UNLOCK_READ()	sx_sunlock(&kld_sx)
78 #define	KLD_LOCKED()		sx_xlocked(&kld_sx)
79 #define	KLD_LOCK_ASSERT() do {						\
80 	if (!cold)							\
81 		sx_assert(&kld_sx, SX_XLOCKED);				\
82 } while (0)
83 
84 /*
85  * static char *linker_search_path(const char *name, struct mod_depend
86  * *verinfo);
87  */
88 static const char 	*linker_basename(const char *path);
89 
90 /*
91  * Find a currently loaded file given its filename.
92  */
93 static linker_file_t linker_find_file_by_name(const char* _filename);
94 
95 /*
96  * Find a currently loaded file given its file id.
97  */
98 static linker_file_t linker_find_file_by_id(int _fileid);
99 
100 /* Metadata from the static kernel */
101 SET_DECLARE(modmetadata_set, struct mod_metadata);
102 
103 MALLOC_DEFINE(M_LINKER, "linker", "kernel linker");
104 
105 linker_file_t linker_kernel_file;
106 
107 static struct sx kld_sx;	/* kernel linker lock */
108 
109 /*
110  * Load counter used by clients to determine if a linker file has been
111  * re-loaded. This counter is incremented for each file load.
112  */
113 static int loadcnt;
114 
115 static linker_class_list_t classes;
116 static linker_file_list_t linker_files;
117 static int next_file_id = 1;
118 static int linker_no_more_classes = 0;
119 
120 #define	LINKER_GET_NEXT_FILE_ID(a) do {					\
121 	linker_file_t lftmp;						\
122 									\
123 	KLD_LOCK_ASSERT();						\
124 retry:									\
125 	TAILQ_FOREACH(lftmp, &linker_files, link) {			\
126 		if (next_file_id == lftmp->id) {			\
127 			next_file_id++;					\
128 			goto retry;					\
129 		}							\
130 	}								\
131 	(a) = next_file_id;						\
132 } while(0)
133 
134 
135 /* XXX wrong name; we're looking at version provision tags here, not modules */
136 typedef TAILQ_HEAD(, modlist) modlisthead_t;
137 struct modlist {
138 	TAILQ_ENTRY(modlist) link;	/* chain together all modules */
139 	linker_file_t   container;
140 	const char 	*name;
141 	int             version;
142 };
143 typedef struct modlist *modlist_t;
144 static modlisthead_t found_modules;
145 
146 static int	linker_file_add_dependency(linker_file_t file,
147 		    linker_file_t dep);
148 static caddr_t	linker_file_lookup_symbol_internal(linker_file_t file,
149 		    const char* name, int deps);
150 static int	linker_load_module(const char *kldname,
151 		    const char *modname, struct linker_file *parent,
152 		    struct mod_depend *verinfo, struct linker_file **lfpp);
153 static modlist_t modlist_lookup2(const char *name, struct mod_depend *verinfo);
154 
155 static char *
156 linker_strdup(const char *str)
157 {
158 	char *result;
159 
160 	if ((result = malloc((strlen(str) + 1), M_LINKER, M_WAITOK)) != NULL)
161 		strcpy(result, str);
162 	return (result);
163 }
164 
165 static void
166 linker_init(void *arg)
167 {
168 
169 	sx_init(&kld_sx, "kernel linker");
170 	TAILQ_INIT(&classes);
171 	TAILQ_INIT(&linker_files);
172 }
173 
174 SYSINIT(linker, SI_SUB_KLD, SI_ORDER_FIRST, linker_init, 0);
175 
176 static void
177 linker_stop_class_add(void *arg)
178 {
179 
180 	linker_no_more_classes = 1;
181 }
182 
183 SYSINIT(linker_class, SI_SUB_KLD, SI_ORDER_ANY, linker_stop_class_add, NULL);
184 
185 int
186 linker_add_class(linker_class_t lc)
187 {
188 
189 	/*
190 	 * We disallow any class registration past SI_ORDER_ANY
191 	 * of SI_SUB_KLD.  We bump the reference count to keep the
192 	 * ops from being freed.
193 	 */
194 	if (linker_no_more_classes == 1)
195 		return (EPERM);
196 	kobj_class_compile((kobj_class_t) lc);
197 	((kobj_class_t)lc)->refs++;	/* XXX: kobj_mtx */
198 	TAILQ_INSERT_TAIL(&classes, lc, link);
199 	return (0);
200 }
201 
202 static void
203 linker_file_sysinit(linker_file_t lf)
204 {
205 	struct sysinit **start, **stop, **sipp, **xipp, *save;
206 
207 	KLD_DPF(FILE, ("linker_file_sysinit: calling SYSINITs for %s\n",
208 	    lf->filename));
209 
210 	if (linker_file_lookup_set(lf, "sysinit_set", &start, &stop, NULL) != 0)
211 		return;
212 	/*
213 	 * Perform a bubble sort of the system initialization objects by
214 	 * their subsystem (primary key) and order (secondary key).
215 	 *
216 	 * Since some things care about execution order, this is the operation
217 	 * which ensures continued function.
218 	 */
219 	for (sipp = start; sipp < stop; sipp++) {
220 		for (xipp = sipp + 1; xipp < stop; xipp++) {
221 			if ((*sipp)->subsystem < (*xipp)->subsystem ||
222 			    ((*sipp)->subsystem == (*xipp)->subsystem &&
223 			    (*sipp)->order <= (*xipp)->order))
224 				continue;	/* skip */
225 			save = *sipp;
226 			*sipp = *xipp;
227 			*xipp = save;
228 		}
229 	}
230 
231 	/*
232 	 * Traverse the (now) ordered list of system initialization tasks.
233 	 * Perform each task, and continue on to the next task.
234 	 */
235 	mtx_lock(&Giant);
236 	for (sipp = start; sipp < stop; sipp++) {
237 		if ((*sipp)->subsystem == SI_SUB_DUMMY)
238 			continue;	/* skip dummy task(s) */
239 
240 		/* Call function */
241 		(*((*sipp)->func)) ((*sipp)->udata);
242 	}
243 	mtx_unlock(&Giant);
244 }
245 
246 static void
247 linker_file_sysuninit(linker_file_t lf)
248 {
249 	struct sysinit **start, **stop, **sipp, **xipp, *save;
250 
251 	KLD_DPF(FILE, ("linker_file_sysuninit: calling SYSUNINITs for %s\n",
252 	    lf->filename));
253 
254 	if (linker_file_lookup_set(lf, "sysuninit_set", &start, &stop,
255 	    NULL) != 0)
256 		return;
257 
258 	/*
259 	 * Perform a reverse bubble sort of the system initialization objects
260 	 * by their subsystem (primary key) and order (secondary key).
261 	 *
262 	 * Since some things care about execution order, this is the operation
263 	 * which ensures continued function.
264 	 */
265 	for (sipp = start; sipp < stop; sipp++) {
266 		for (xipp = sipp + 1; xipp < stop; xipp++) {
267 			if ((*sipp)->subsystem > (*xipp)->subsystem ||
268 			    ((*sipp)->subsystem == (*xipp)->subsystem &&
269 			    (*sipp)->order >= (*xipp)->order))
270 				continue;	/* skip */
271 			save = *sipp;
272 			*sipp = *xipp;
273 			*xipp = save;
274 		}
275 	}
276 
277 	/*
278 	 * Traverse the (now) ordered list of system initialization tasks.
279 	 * Perform each task, and continue on to the next task.
280 	 */
281 	mtx_lock(&Giant);
282 	for (sipp = start; sipp < stop; sipp++) {
283 		if ((*sipp)->subsystem == SI_SUB_DUMMY)
284 			continue;	/* skip dummy task(s) */
285 
286 		/* Call function */
287 		(*((*sipp)->func)) ((*sipp)->udata);
288 	}
289 	mtx_unlock(&Giant);
290 }
291 
292 static void
293 linker_file_register_sysctls(linker_file_t lf)
294 {
295 	struct sysctl_oid **start, **stop, **oidp;
296 
297 	KLD_DPF(FILE,
298 	    ("linker_file_register_sysctls: registering SYSCTLs for %s\n",
299 	    lf->filename));
300 
301 	if (linker_file_lookup_set(lf, "sysctl_set", &start, &stop, NULL) != 0)
302 		return;
303 
304 	sysctl_lock();
305 	for (oidp = start; oidp < stop; oidp++)
306 		sysctl_register_oid(*oidp);
307 	sysctl_unlock();
308 }
309 
310 static void
311 linker_file_unregister_sysctls(linker_file_t lf)
312 {
313 	struct sysctl_oid **start, **stop, **oidp;
314 
315 	KLD_DPF(FILE, ("linker_file_unregister_sysctls: unregistering SYSCTLs"
316 	    " for %s\n", lf->filename));
317 
318 	if (linker_file_lookup_set(lf, "sysctl_set", &start, &stop, NULL) != 0)
319 		return;
320 
321 	sysctl_lock();
322 	for (oidp = start; oidp < stop; oidp++)
323 		sysctl_unregister_oid(*oidp);
324 	sysctl_unlock();
325 }
326 
327 static int
328 linker_file_register_modules(linker_file_t lf)
329 {
330 	struct mod_metadata **start, **stop, **mdp;
331 	const moduledata_t *moddata;
332 	int first_error, error;
333 
334 	KLD_DPF(FILE, ("linker_file_register_modules: registering modules"
335 	    " in %s\n", lf->filename));
336 
337 	if (linker_file_lookup_set(lf, "modmetadata_set", &start,
338 	    &stop, NULL) != 0) {
339 		/*
340 		 * This fallback should be unnecessary, but if we get booted
341 		 * from boot2 instead of loader and we are missing our
342 		 * metadata then we have to try the best we can.
343 		 */
344 		if (lf == linker_kernel_file) {
345 			start = SET_BEGIN(modmetadata_set);
346 			stop = SET_LIMIT(modmetadata_set);
347 		} else
348 			return (0);
349 	}
350 	first_error = 0;
351 	for (mdp = start; mdp < stop; mdp++) {
352 		if ((*mdp)->md_type != MDT_MODULE)
353 			continue;
354 		moddata = (*mdp)->md_data;
355 		KLD_DPF(FILE, ("Registering module %s in %s\n",
356 		    moddata->name, lf->filename));
357 		error = module_register(moddata, lf);
358 		if (error) {
359 			printf("Module %s failed to register: %d\n",
360 			    moddata->name, error);
361 			if (first_error == 0)
362 				first_error = error;
363 		}
364 	}
365 	return (first_error);
366 }
367 
368 static void
369 linker_init_kernel_modules(void)
370 {
371 
372 	linker_file_register_modules(linker_kernel_file);
373 }
374 
375 SYSINIT(linker_kernel, SI_SUB_KLD, SI_ORDER_ANY, linker_init_kernel_modules,
376     0);
377 
378 static int
379 linker_load_file(const char *filename, linker_file_t *result)
380 {
381 	linker_class_t lc;
382 	linker_file_t lf;
383 	int foundfile, error, modules;
384 
385 	/* Refuse to load modules if securelevel raised */
386 	if (prison0.pr_securelevel > 0)
387 		return (EPERM);
388 
389 	KLD_LOCK_ASSERT();
390 	lf = linker_find_file_by_name(filename);
391 	if (lf) {
392 		KLD_DPF(FILE, ("linker_load_file: file %s is already loaded,"
393 		    " incrementing refs\n", filename));
394 		*result = lf;
395 		lf->refs++;
396 		return (0);
397 	}
398 	foundfile = 0;
399 	error = 0;
400 
401 	/*
402 	 * We do not need to protect (lock) classes here because there is
403 	 * no class registration past startup (SI_SUB_KLD, SI_ORDER_ANY)
404 	 * and there is no class deregistration mechanism at this time.
405 	 */
406 	TAILQ_FOREACH(lc, &classes, link) {
407 		KLD_DPF(FILE, ("linker_load_file: trying to load %s\n",
408 		    filename));
409 		error = LINKER_LOAD_FILE(lc, filename, &lf);
410 		/*
411 		 * If we got something other than ENOENT, then it exists but
412 		 * we cannot load it for some other reason.
413 		 */
414 		if (error != ENOENT)
415 			foundfile = 1;
416 		if (lf) {
417 			error = linker_file_register_modules(lf);
418 			if (error == EEXIST) {
419 				linker_file_unload(lf, LINKER_UNLOAD_FORCE);
420 				return (error);
421 			}
422 			modules = !TAILQ_EMPTY(&lf->modules);
423 			KLD_UNLOCK();
424 			linker_file_register_sysctls(lf);
425 			linker_file_sysinit(lf);
426 			KLD_LOCK();
427 			lf->flags |= LINKER_FILE_LINKED;
428 
429 			/*
430 			 * If all of the modules in this file failed
431 			 * to load, unload the file and return an
432 			 * error of ENOEXEC.
433 			 */
434 			if (modules && TAILQ_EMPTY(&lf->modules)) {
435 				linker_file_unload(lf, LINKER_UNLOAD_FORCE);
436 				return (ENOEXEC);
437 			}
438 			*result = lf;
439 			return (0);
440 		}
441 	}
442 	/*
443 	 * Less than ideal, but tells the user whether it failed to load or
444 	 * the module was not found.
445 	 */
446 	if (foundfile) {
447 
448 		/*
449 		 * If the file type has not been recognized by the last try
450 		 * printout a message before to fail.
451 		 */
452 		if (error == ENOSYS)
453 			printf("linker_load_file: Unsupported file type\n");
454 
455 		/*
456 		 * Format not recognized or otherwise unloadable.
457 		 * When loading a module that is statically built into
458 		 * the kernel EEXIST percolates back up as the return
459 		 * value.  Preserve this so that apps like sysinstall
460 		 * can recognize this special case and not post bogus
461 		 * dialog boxes.
462 		 */
463 		if (error != EEXIST)
464 			error = ENOEXEC;
465 	} else
466 		error = ENOENT;		/* Nothing found */
467 	return (error);
468 }
469 
470 int
471 linker_reference_module(const char *modname, struct mod_depend *verinfo,
472     linker_file_t *result)
473 {
474 	modlist_t mod;
475 	int error;
476 
477 	KLD_LOCK();
478 	if ((mod = modlist_lookup2(modname, verinfo)) != NULL) {
479 		*result = mod->container;
480 		(*result)->refs++;
481 		KLD_UNLOCK();
482 		return (0);
483 	}
484 
485 	error = linker_load_module(NULL, modname, NULL, verinfo, result);
486 	KLD_UNLOCK();
487 	return (error);
488 }
489 
490 int
491 linker_release_module(const char *modname, struct mod_depend *verinfo,
492     linker_file_t lf)
493 {
494 	modlist_t mod;
495 	int error;
496 
497 	KLD_LOCK();
498 	if (lf == NULL) {
499 		KASSERT(modname != NULL,
500 		    ("linker_release_module: no file or name"));
501 		mod = modlist_lookup2(modname, verinfo);
502 		if (mod == NULL) {
503 			KLD_UNLOCK();
504 			return (ESRCH);
505 		}
506 		lf = mod->container;
507 	} else
508 		KASSERT(modname == NULL && verinfo == NULL,
509 		    ("linker_release_module: both file and name"));
510 	error =	linker_file_unload(lf, LINKER_UNLOAD_NORMAL);
511 	KLD_UNLOCK();
512 	return (error);
513 }
514 
515 static linker_file_t
516 linker_find_file_by_name(const char *filename)
517 {
518 	linker_file_t lf;
519 	char *koname;
520 
521 	koname = malloc(strlen(filename) + 4, M_LINKER, M_WAITOK);
522 	sprintf(koname, "%s.ko", filename);
523 
524 	KLD_LOCK_ASSERT();
525 	TAILQ_FOREACH(lf, &linker_files, link) {
526 		if (strcmp(lf->filename, koname) == 0)
527 			break;
528 		if (strcmp(lf->filename, filename) == 0)
529 			break;
530 	}
531 	free(koname, M_LINKER);
532 	return (lf);
533 }
534 
535 static linker_file_t
536 linker_find_file_by_id(int fileid)
537 {
538 	linker_file_t lf;
539 
540 	KLD_LOCK_ASSERT();
541 	TAILQ_FOREACH(lf, &linker_files, link)
542 		if (lf->id == fileid && lf->flags & LINKER_FILE_LINKED)
543 			break;
544 	return (lf);
545 }
546 
547 int
548 linker_file_foreach(linker_predicate_t *predicate, void *context)
549 {
550 	linker_file_t lf;
551 	int retval = 0;
552 
553 	KLD_LOCK();
554 	TAILQ_FOREACH(lf, &linker_files, link) {
555 		retval = predicate(lf, context);
556 		if (retval != 0)
557 			break;
558 	}
559 	KLD_UNLOCK();
560 	return (retval);
561 }
562 
563 linker_file_t
564 linker_make_file(const char *pathname, linker_class_t lc)
565 {
566 	linker_file_t lf;
567 	const char *filename;
568 
569 	KLD_LOCK_ASSERT();
570 	filename = linker_basename(pathname);
571 
572 	KLD_DPF(FILE, ("linker_make_file: new file, filename='%s' for pathname='%s'\n", filename, pathname));
573 	lf = (linker_file_t)kobj_create((kobj_class_t)lc, M_LINKER, M_WAITOK);
574 	if (lf == NULL)
575 		return (NULL);
576 	lf->refs = 1;
577 	lf->userrefs = 0;
578 	lf->flags = 0;
579 	lf->filename = linker_strdup(filename);
580 	lf->pathname = linker_strdup(pathname);
581 	LINKER_GET_NEXT_FILE_ID(lf->id);
582 	lf->ndeps = 0;
583 	lf->deps = NULL;
584 	lf->loadcnt = ++loadcnt;
585 	lf->sdt_probes = NULL;
586 	lf->sdt_nprobes = 0;
587 	STAILQ_INIT(&lf->common);
588 	TAILQ_INIT(&lf->modules);
589 	TAILQ_INSERT_TAIL(&linker_files, lf, link);
590 	return (lf);
591 }
592 
593 int
594 linker_file_unload(linker_file_t file, int flags)
595 {
596 	module_t mod, next;
597 	modlist_t ml, nextml;
598 	struct common_symbol *cp;
599 	int error, i;
600 
601 	/* Refuse to unload modules if securelevel raised. */
602 	if (prison0.pr_securelevel > 0)
603 		return (EPERM);
604 
605 	KLD_LOCK_ASSERT();
606 	KLD_DPF(FILE, ("linker_file_unload: lf->refs=%d\n", file->refs));
607 
608 	/* Easy case of just dropping a reference. */
609 	if (file->refs > 1) {
610 		file->refs--;
611 		return (0);
612 	}
613 
614 	KLD_DPF(FILE, ("linker_file_unload: file is unloading,"
615 	    " informing modules\n"));
616 
617 	/*
618 	 * Quiesce all the modules to give them a chance to veto the unload.
619 	 */
620 	MOD_SLOCK;
621 	for (mod = TAILQ_FIRST(&file->modules); mod;
622 	     mod = module_getfnext(mod)) {
623 
624 		error = module_quiesce(mod);
625 		if (error != 0 && flags != LINKER_UNLOAD_FORCE) {
626 			KLD_DPF(FILE, ("linker_file_unload: module %s"
627 			    " vetoed unload\n", module_getname(mod)));
628 			/*
629 			 * XXX: Do we need to tell all the quiesced modules
630 			 * that they can resume work now via a new module
631 			 * event?
632 			 */
633 			MOD_SUNLOCK;
634 			return (error);
635 		}
636 	}
637 	MOD_SUNLOCK;
638 
639 	/*
640 	 * Inform any modules associated with this file that they are
641 	 * being unloaded.
642 	 */
643 	MOD_XLOCK;
644 	for (mod = TAILQ_FIRST(&file->modules); mod; mod = next) {
645 		next = module_getfnext(mod);
646 		MOD_XUNLOCK;
647 
648 		/*
649 		 * Give the module a chance to veto the unload.
650 		 */
651 		if ((error = module_unload(mod)) != 0) {
652 #ifdef KLD_DEBUG
653 			MOD_SLOCK;
654 			KLD_DPF(FILE, ("linker_file_unload: module %s"
655 			    " failed unload\n", module_getname(mod)));
656 			MOD_SUNLOCK;
657 #endif
658 			return (error);
659 		}
660 		MOD_XLOCK;
661 		module_release(mod);
662 	}
663 	MOD_XUNLOCK;
664 
665 	TAILQ_FOREACH_SAFE(ml, &found_modules, link, nextml) {
666 		if (ml->container == file) {
667 			TAILQ_REMOVE(&found_modules, ml, link);
668 			free(ml, M_LINKER);
669 		}
670 	}
671 
672 	/*
673 	 * Don't try to run SYSUNINITs if we are unloaded due to a
674 	 * link error.
675 	 */
676 	if (file->flags & LINKER_FILE_LINKED) {
677 		file->flags &= ~LINKER_FILE_LINKED;
678 		KLD_UNLOCK();
679 		linker_file_sysuninit(file);
680 		linker_file_unregister_sysctls(file);
681 		KLD_LOCK();
682 	}
683 	TAILQ_REMOVE(&linker_files, file, link);
684 
685 	if (file->deps) {
686 		for (i = 0; i < file->ndeps; i++)
687 			linker_file_unload(file->deps[i], flags);
688 		free(file->deps, M_LINKER);
689 		file->deps = NULL;
690 	}
691 	while ((cp = STAILQ_FIRST(&file->common)) != NULL) {
692 		STAILQ_REMOVE_HEAD(&file->common, link);
693 		free(cp, M_LINKER);
694 	}
695 
696 	LINKER_UNLOAD(file);
697 	if (file->filename) {
698 		free(file->filename, M_LINKER);
699 		file->filename = NULL;
700 	}
701 	if (file->pathname) {
702 		free(file->pathname, M_LINKER);
703 		file->pathname = NULL;
704 	}
705 	kobj_delete((kobj_t) file, M_LINKER);
706 	return (0);
707 }
708 
709 int
710 linker_ctf_get(linker_file_t file, linker_ctf_t *lc)
711 {
712 	return (LINKER_CTF_GET(file, lc));
713 }
714 
715 static int
716 linker_file_add_dependency(linker_file_t file, linker_file_t dep)
717 {
718 	linker_file_t *newdeps;
719 
720 	KLD_LOCK_ASSERT();
721 	newdeps = malloc((file->ndeps + 1) * sizeof(linker_file_t *),
722 	    M_LINKER, M_WAITOK | M_ZERO);
723 	if (newdeps == NULL)
724 		return (ENOMEM);
725 
726 	if (file->deps) {
727 		bcopy(file->deps, newdeps,
728 		    file->ndeps * sizeof(linker_file_t *));
729 		free(file->deps, M_LINKER);
730 	}
731 	file->deps = newdeps;
732 	file->deps[file->ndeps] = dep;
733 	file->ndeps++;
734 	KLD_DPF(FILE, ("linker_file_add_dependency:"
735 	    " adding %s as dependency for %s\n",
736 	    dep->filename, file->filename));
737 	return (0);
738 }
739 
740 /*
741  * Locate a linker set and its contents.  This is a helper function to avoid
742  * linker_if.h exposure elsewhere.  Note: firstp and lastp are really void **.
743  * This function is used in this file so we can avoid having lots of (void **)
744  * casts.
745  */
746 int
747 linker_file_lookup_set(linker_file_t file, const char *name,
748     void *firstp, void *lastp, int *countp)
749 {
750 	int error, locked;
751 
752 	locked = KLD_LOCKED();
753 	if (!locked)
754 		KLD_LOCK();
755 	error = LINKER_LOOKUP_SET(file, name, firstp, lastp, countp);
756 	if (!locked)
757 		KLD_UNLOCK();
758 	return (error);
759 }
760 
761 /*
762  * List all functions in a file.
763  */
764 int
765 linker_file_function_listall(linker_file_t lf,
766     linker_function_nameval_callback_t callback_func, void *arg)
767 {
768 	return (LINKER_EACH_FUNCTION_NAMEVAL(lf, callback_func, arg));
769 }
770 
771 caddr_t
772 linker_file_lookup_symbol(linker_file_t file, const char *name, int deps)
773 {
774 	caddr_t sym;
775 	int locked;
776 
777 	locked = KLD_LOCKED();
778 	if (!locked)
779 		KLD_LOCK();
780 	sym = linker_file_lookup_symbol_internal(file, name, deps);
781 	if (!locked)
782 		KLD_UNLOCK();
783 	return (sym);
784 }
785 
786 static caddr_t
787 linker_file_lookup_symbol_internal(linker_file_t file, const char *name,
788     int deps)
789 {
790 	c_linker_sym_t sym;
791 	linker_symval_t symval;
792 	caddr_t address;
793 	size_t common_size = 0;
794 	int i;
795 
796 	KLD_LOCK_ASSERT();
797 	KLD_DPF(SYM, ("linker_file_lookup_symbol: file=%p, name=%s, deps=%d\n",
798 	    file, name, deps));
799 
800 	if (LINKER_LOOKUP_SYMBOL(file, name, &sym) == 0) {
801 		LINKER_SYMBOL_VALUES(file, sym, &symval);
802 		if (symval.value == 0)
803 			/*
804 			 * For commons, first look them up in the
805 			 * dependencies and only allocate space if not found
806 			 * there.
807 			 */
808 			common_size = symval.size;
809 		else {
810 			KLD_DPF(SYM, ("linker_file_lookup_symbol: symbol"
811 			    ".value=%p\n", symval.value));
812 			return (symval.value);
813 		}
814 	}
815 	if (deps) {
816 		for (i = 0; i < file->ndeps; i++) {
817 			address = linker_file_lookup_symbol_internal(
818 			    file->deps[i], name, 0);
819 			if (address) {
820 				KLD_DPF(SYM, ("linker_file_lookup_symbol:"
821 				    " deps value=%p\n", address));
822 				return (address);
823 			}
824 		}
825 	}
826 	if (common_size > 0) {
827 		/*
828 		 * This is a common symbol which was not found in the
829 		 * dependencies.  We maintain a simple common symbol table in
830 		 * the file object.
831 		 */
832 		struct common_symbol *cp;
833 
834 		STAILQ_FOREACH(cp, &file->common, link) {
835 			if (strcmp(cp->name, name) == 0) {
836 				KLD_DPF(SYM, ("linker_file_lookup_symbol:"
837 				    " old common value=%p\n", cp->address));
838 				return (cp->address);
839 			}
840 		}
841 		/*
842 		 * Round the symbol size up to align.
843 		 */
844 		common_size = (common_size + sizeof(int) - 1) & -sizeof(int);
845 		cp = malloc(sizeof(struct common_symbol)
846 		    + common_size + strlen(name) + 1, M_LINKER,
847 		    M_WAITOK | M_ZERO);
848 		cp->address = (caddr_t)(cp + 1);
849 		cp->name = cp->address + common_size;
850 		strcpy(cp->name, name);
851 		bzero(cp->address, common_size);
852 		STAILQ_INSERT_TAIL(&file->common, cp, link);
853 
854 		KLD_DPF(SYM, ("linker_file_lookup_symbol: new common"
855 		    " value=%p\n", cp->address));
856 		return (cp->address);
857 	}
858 	KLD_DPF(SYM, ("linker_file_lookup_symbol: fail\n"));
859 	return (0);
860 }
861 
862 /*
863  * Both DDB and stack(9) rely on the kernel linker to provide forward and
864  * backward lookup of symbols.  However, DDB and sometimes stack(9) need to
865  * do this in a lockfree manner.  We provide a set of internal helper
866  * routines to perform these operations without locks, and then wrappers that
867  * optionally lock.
868  *
869  * linker_debug_lookup() is ifdef DDB as currently it's only used by DDB.
870  */
871 #ifdef DDB
872 static int
873 linker_debug_lookup(const char *symstr, c_linker_sym_t *sym)
874 {
875 	linker_file_t lf;
876 
877 	TAILQ_FOREACH(lf, &linker_files, link) {
878 		if (LINKER_LOOKUP_SYMBOL(lf, symstr, sym) == 0)
879 			return (0);
880 	}
881 	return (ENOENT);
882 }
883 #endif
884 
885 static int
886 linker_debug_search_symbol(caddr_t value, c_linker_sym_t *sym, long *diffp)
887 {
888 	linker_file_t lf;
889 	c_linker_sym_t best, es;
890 	u_long diff, bestdiff, off;
891 
892 	best = 0;
893 	off = (uintptr_t)value;
894 	bestdiff = off;
895 	TAILQ_FOREACH(lf, &linker_files, link) {
896 		if (LINKER_SEARCH_SYMBOL(lf, value, &es, &diff) != 0)
897 			continue;
898 		if (es != 0 && diff < bestdiff) {
899 			best = es;
900 			bestdiff = diff;
901 		}
902 		if (bestdiff == 0)
903 			break;
904 	}
905 	if (best) {
906 		*sym = best;
907 		*diffp = bestdiff;
908 		return (0);
909 	} else {
910 		*sym = 0;
911 		*diffp = off;
912 		return (ENOENT);
913 	}
914 }
915 
916 static int
917 linker_debug_symbol_values(c_linker_sym_t sym, linker_symval_t *symval)
918 {
919 	linker_file_t lf;
920 
921 	TAILQ_FOREACH(lf, &linker_files, link) {
922 		if (LINKER_SYMBOL_VALUES(lf, sym, symval) == 0)
923 			return (0);
924 	}
925 	return (ENOENT);
926 }
927 
928 static int
929 linker_debug_search_symbol_name(caddr_t value, char *buf, u_int buflen,
930     long *offset)
931 {
932 	linker_symval_t symval;
933 	c_linker_sym_t sym;
934 	int error;
935 
936 	*offset = 0;
937 	error = linker_debug_search_symbol(value, &sym, offset);
938 	if (error)
939 		return (error);
940 	error = linker_debug_symbol_values(sym, &symval);
941 	if (error)
942 		return (error);
943 	strlcpy(buf, symval.name, buflen);
944 	return (0);
945 }
946 
947 /*
948  * DDB Helpers.  DDB has to look across multiple files with their own symbol
949  * tables and string tables.
950  *
951  * Note that we do not obey list locking protocols here.  We really don't need
952  * DDB to hang because somebody's got the lock held.  We'll take the chance
953  * that the files list is inconsistant instead.
954  */
955 #ifdef DDB
956 int
957 linker_ddb_lookup(const char *symstr, c_linker_sym_t *sym)
958 {
959 
960 	return (linker_debug_lookup(symstr, sym));
961 }
962 #endif
963 
964 int
965 linker_ddb_search_symbol(caddr_t value, c_linker_sym_t *sym, long *diffp)
966 {
967 
968 	return (linker_debug_search_symbol(value, sym, diffp));
969 }
970 
971 int
972 linker_ddb_symbol_values(c_linker_sym_t sym, linker_symval_t *symval)
973 {
974 
975 	return (linker_debug_symbol_values(sym, symval));
976 }
977 
978 int
979 linker_ddb_search_symbol_name(caddr_t value, char *buf, u_int buflen,
980     long *offset)
981 {
982 
983 	return (linker_debug_search_symbol_name(value, buf, buflen, offset));
984 }
985 
986 /*
987  * stack(9) helper for non-debugging environemnts.  Unlike DDB helpers, we do
988  * obey locking protocols, and offer a significantly less complex interface.
989  */
990 int
991 linker_search_symbol_name(caddr_t value, char *buf, u_int buflen,
992     long *offset)
993 {
994 	int error;
995 
996 	KLD_LOCK();
997 	error = linker_debug_search_symbol_name(value, buf, buflen, offset);
998 	KLD_UNLOCK();
999 	return (error);
1000 }
1001 
1002 /*
1003  * Syscalls.
1004  */
1005 int
1006 kern_kldload(struct thread *td, const char *file, int *fileid)
1007 {
1008 #ifdef HWPMC_HOOKS
1009 	struct pmckern_map_in pkm;
1010 #endif
1011 	const char *kldname, *modname;
1012 	linker_file_t lf;
1013 	int error;
1014 
1015 	if ((error = securelevel_gt(td->td_ucred, 0)) != 0)
1016 		return (error);
1017 
1018 	if ((error = priv_check(td, PRIV_KLD_LOAD)) != 0)
1019 		return (error);
1020 
1021 	/*
1022 	 * It is possible that kldloaded module will attach a new ifnet,
1023 	 * so vnet context must be set when this ocurs.
1024 	 */
1025 	CURVNET_SET(TD_TO_VNET(td));
1026 
1027 	/*
1028 	 * If file does not contain a qualified name or any dot in it
1029 	 * (kldname.ko, or kldname.ver.ko) treat it as an interface
1030 	 * name.
1031 	 */
1032 	if (strchr(file, '/') || strchr(file, '.')) {
1033 		kldname = file;
1034 		modname = NULL;
1035 	} else {
1036 		kldname = NULL;
1037 		modname = file;
1038 	}
1039 
1040 	KLD_LOCK();
1041 	error = linker_load_module(kldname, modname, NULL, NULL, &lf);
1042 	if (error) {
1043 		KLD_UNLOCK();
1044 		goto done;
1045 	}
1046 	lf->userrefs++;
1047 	if (fileid != NULL)
1048 		*fileid = lf->id;
1049 #ifdef HWPMC_HOOKS
1050 	KLD_DOWNGRADE();
1051 	pkm.pm_file = lf->filename;
1052 	pkm.pm_address = (uintptr_t) lf->address;
1053 	PMC_CALL_HOOK(td, PMC_FN_KLD_LOAD, (void *) &pkm);
1054 	KLD_UNLOCK_READ();
1055 #else
1056 	KLD_UNLOCK();
1057 #endif
1058 
1059 done:
1060 	CURVNET_RESTORE();
1061 	return (error);
1062 }
1063 
1064 int
1065 sys_kldload(struct thread *td, struct kldload_args *uap)
1066 {
1067 	char *pathname = NULL;
1068 	int error, fileid;
1069 
1070 	td->td_retval[0] = -1;
1071 
1072 	pathname = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
1073 	error = copyinstr(uap->file, pathname, MAXPATHLEN, NULL);
1074 	if (error == 0) {
1075 		error = kern_kldload(td, pathname, &fileid);
1076 		if (error == 0)
1077 			td->td_retval[0] = fileid;
1078 	}
1079 	free(pathname, M_TEMP);
1080 	return (error);
1081 }
1082 
1083 int
1084 kern_kldunload(struct thread *td, int fileid, int flags)
1085 {
1086 #ifdef HWPMC_HOOKS
1087 	struct pmckern_map_out pkm;
1088 #endif
1089 	linker_file_t lf;
1090 	int error = 0;
1091 
1092 	if ((error = securelevel_gt(td->td_ucred, 0)) != 0)
1093 		return (error);
1094 
1095 	if ((error = priv_check(td, PRIV_KLD_UNLOAD)) != 0)
1096 		return (error);
1097 
1098 	CURVNET_SET(TD_TO_VNET(td));
1099 	KLD_LOCK();
1100 	lf = linker_find_file_by_id(fileid);
1101 	if (lf) {
1102 		KLD_DPF(FILE, ("kldunload: lf->userrefs=%d\n", lf->userrefs));
1103 
1104 		/* Check if there are DTrace probes enabled on this file. */
1105 		if (lf->nenabled > 0) {
1106 			printf("kldunload: attempt to unload file that has"
1107 			    " DTrace probes enabled\n");
1108 			error = EBUSY;
1109 		} else if (lf->userrefs == 0) {
1110 			/*
1111 			 * XXX: maybe LINKER_UNLOAD_FORCE should override ?
1112 			 */
1113 			printf("kldunload: attempt to unload file that was"
1114 			    " loaded by the kernel\n");
1115 			error = EBUSY;
1116 		} else {
1117 #ifdef HWPMC_HOOKS
1118 			/* Save data needed by hwpmc(4) before unloading. */
1119 			pkm.pm_address = (uintptr_t) lf->address;
1120 			pkm.pm_size = lf->size;
1121 #endif
1122 			lf->userrefs--;
1123 			error = linker_file_unload(lf, flags);
1124 			if (error)
1125 				lf->userrefs++;
1126 		}
1127 	} else
1128 		error = ENOENT;
1129 
1130 #ifdef HWPMC_HOOKS
1131 	if (error == 0) {
1132 		KLD_DOWNGRADE();
1133 		PMC_CALL_HOOK(td, PMC_FN_KLD_UNLOAD, (void *) &pkm);
1134 		KLD_UNLOCK_READ();
1135 	} else
1136 		KLD_UNLOCK();
1137 #else
1138 	KLD_UNLOCK();
1139 #endif
1140 	CURVNET_RESTORE();
1141 	return (error);
1142 }
1143 
1144 int
1145 sys_kldunload(struct thread *td, struct kldunload_args *uap)
1146 {
1147 
1148 	return (kern_kldunload(td, uap->fileid, LINKER_UNLOAD_NORMAL));
1149 }
1150 
1151 int
1152 sys_kldunloadf(struct thread *td, struct kldunloadf_args *uap)
1153 {
1154 
1155 	if (uap->flags != LINKER_UNLOAD_NORMAL &&
1156 	    uap->flags != LINKER_UNLOAD_FORCE)
1157 		return (EINVAL);
1158 	return (kern_kldunload(td, uap->fileid, uap->flags));
1159 }
1160 
1161 int
1162 sys_kldfind(struct thread *td, struct kldfind_args *uap)
1163 {
1164 	char *pathname;
1165 	const char *filename;
1166 	linker_file_t lf;
1167 	int error;
1168 
1169 #ifdef MAC
1170 	error = mac_kld_check_stat(td->td_ucred);
1171 	if (error)
1172 		return (error);
1173 #endif
1174 
1175 	td->td_retval[0] = -1;
1176 
1177 	pathname = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
1178 	if ((error = copyinstr(uap->file, pathname, MAXPATHLEN, NULL)) != 0)
1179 		goto out;
1180 
1181 	filename = linker_basename(pathname);
1182 	KLD_LOCK();
1183 	lf = linker_find_file_by_name(filename);
1184 	if (lf)
1185 		td->td_retval[0] = lf->id;
1186 	else
1187 		error = ENOENT;
1188 	KLD_UNLOCK();
1189 out:
1190 	free(pathname, M_TEMP);
1191 	return (error);
1192 }
1193 
1194 int
1195 sys_kldnext(struct thread *td, struct kldnext_args *uap)
1196 {
1197 	linker_file_t lf;
1198 	int error = 0;
1199 
1200 #ifdef MAC
1201 	error = mac_kld_check_stat(td->td_ucred);
1202 	if (error)
1203 		return (error);
1204 #endif
1205 
1206 	KLD_LOCK();
1207 	if (uap->fileid == 0)
1208 		lf = TAILQ_FIRST(&linker_files);
1209 	else {
1210 		lf = linker_find_file_by_id(uap->fileid);
1211 		if (lf == NULL) {
1212 			error = ENOENT;
1213 			goto out;
1214 		}
1215 		lf = TAILQ_NEXT(lf, link);
1216 	}
1217 
1218 	/* Skip partially loaded files. */
1219 	while (lf != NULL && !(lf->flags & LINKER_FILE_LINKED))
1220 		lf = TAILQ_NEXT(lf, link);
1221 
1222 	if (lf)
1223 		td->td_retval[0] = lf->id;
1224 	else
1225 		td->td_retval[0] = 0;
1226 out:
1227 	KLD_UNLOCK();
1228 	return (error);
1229 }
1230 
1231 int
1232 sys_kldstat(struct thread *td, struct kldstat_args *uap)
1233 {
1234 	struct kld_file_stat stat;
1235 	int error, version;
1236 
1237 	/*
1238 	 * Check the version of the user's structure.
1239 	 */
1240 	if ((error = copyin(&uap->stat->version, &version, sizeof(version)))
1241 	    != 0)
1242 		return (error);
1243 	if (version != sizeof(struct kld_file_stat_1) &&
1244 	    version != sizeof(struct kld_file_stat))
1245 		return (EINVAL);
1246 
1247 	error = kern_kldstat(td, uap->fileid, &stat);
1248 	if (error != 0)
1249 		return (error);
1250 	return (copyout(&stat, uap->stat, version));
1251 }
1252 
1253 int
1254 kern_kldstat(struct thread *td, int fileid, struct kld_file_stat *stat)
1255 {
1256 	linker_file_t lf;
1257 	int namelen;
1258 #ifdef MAC
1259 	int error;
1260 
1261 	error = mac_kld_check_stat(td->td_ucred);
1262 	if (error)
1263 		return (error);
1264 #endif
1265 
1266 	KLD_LOCK();
1267 	lf = linker_find_file_by_id(fileid);
1268 	if (lf == NULL) {
1269 		KLD_UNLOCK();
1270 		return (ENOENT);
1271 	}
1272 
1273 	/* Version 1 fields: */
1274 	namelen = strlen(lf->filename) + 1;
1275 	if (namelen > MAXPATHLEN)
1276 		namelen = MAXPATHLEN;
1277 	bcopy(lf->filename, &stat->name[0], namelen);
1278 	stat->refs = lf->refs;
1279 	stat->id = lf->id;
1280 	stat->address = lf->address;
1281 	stat->size = lf->size;
1282 	/* Version 2 fields: */
1283 	namelen = strlen(lf->pathname) + 1;
1284 	if (namelen > MAXPATHLEN)
1285 		namelen = MAXPATHLEN;
1286 	bcopy(lf->pathname, &stat->pathname[0], namelen);
1287 	KLD_UNLOCK();
1288 
1289 	td->td_retval[0] = 0;
1290 	return (0);
1291 }
1292 
1293 int
1294 sys_kldfirstmod(struct thread *td, struct kldfirstmod_args *uap)
1295 {
1296 	linker_file_t lf;
1297 	module_t mp;
1298 	int error = 0;
1299 
1300 #ifdef MAC
1301 	error = mac_kld_check_stat(td->td_ucred);
1302 	if (error)
1303 		return (error);
1304 #endif
1305 
1306 	KLD_LOCK();
1307 	lf = linker_find_file_by_id(uap->fileid);
1308 	if (lf) {
1309 		MOD_SLOCK;
1310 		mp = TAILQ_FIRST(&lf->modules);
1311 		if (mp != NULL)
1312 			td->td_retval[0] = module_getid(mp);
1313 		else
1314 			td->td_retval[0] = 0;
1315 		MOD_SUNLOCK;
1316 	} else
1317 		error = ENOENT;
1318 	KLD_UNLOCK();
1319 	return (error);
1320 }
1321 
1322 int
1323 sys_kldsym(struct thread *td, struct kldsym_args *uap)
1324 {
1325 	char *symstr = NULL;
1326 	c_linker_sym_t sym;
1327 	linker_symval_t symval;
1328 	linker_file_t lf;
1329 	struct kld_sym_lookup lookup;
1330 	int error = 0;
1331 
1332 #ifdef MAC
1333 	error = mac_kld_check_stat(td->td_ucred);
1334 	if (error)
1335 		return (error);
1336 #endif
1337 
1338 	if ((error = copyin(uap->data, &lookup, sizeof(lookup))) != 0)
1339 		return (error);
1340 	if (lookup.version != sizeof(lookup) ||
1341 	    uap->cmd != KLDSYM_LOOKUP)
1342 		return (EINVAL);
1343 	symstr = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
1344 	if ((error = copyinstr(lookup.symname, symstr, MAXPATHLEN, NULL)) != 0)
1345 		goto out;
1346 	KLD_LOCK();
1347 	if (uap->fileid != 0) {
1348 		lf = linker_find_file_by_id(uap->fileid);
1349 		if (lf == NULL)
1350 			error = ENOENT;
1351 		else if (LINKER_LOOKUP_SYMBOL(lf, symstr, &sym) == 0 &&
1352 		    LINKER_SYMBOL_VALUES(lf, sym, &symval) == 0) {
1353 			lookup.symvalue = (uintptr_t) symval.value;
1354 			lookup.symsize = symval.size;
1355 			error = copyout(&lookup, uap->data, sizeof(lookup));
1356 		} else
1357 			error = ENOENT;
1358 	} else {
1359 		TAILQ_FOREACH(lf, &linker_files, link) {
1360 			if (LINKER_LOOKUP_SYMBOL(lf, symstr, &sym) == 0 &&
1361 			    LINKER_SYMBOL_VALUES(lf, sym, &symval) == 0) {
1362 				lookup.symvalue = (uintptr_t)symval.value;
1363 				lookup.symsize = symval.size;
1364 				error = copyout(&lookup, uap->data,
1365 				    sizeof(lookup));
1366 				break;
1367 			}
1368 		}
1369 		if (lf == NULL)
1370 			error = ENOENT;
1371 	}
1372 	KLD_UNLOCK();
1373 out:
1374 	free(symstr, M_TEMP);
1375 	return (error);
1376 }
1377 
1378 /*
1379  * Preloaded module support
1380  */
1381 
1382 static modlist_t
1383 modlist_lookup(const char *name, int ver)
1384 {
1385 	modlist_t mod;
1386 
1387 	TAILQ_FOREACH(mod, &found_modules, link) {
1388 		if (strcmp(mod->name, name) == 0 &&
1389 		    (ver == 0 || mod->version == ver))
1390 			return (mod);
1391 	}
1392 	return (NULL);
1393 }
1394 
1395 static modlist_t
1396 modlist_lookup2(const char *name, struct mod_depend *verinfo)
1397 {
1398 	modlist_t mod, bestmod;
1399 	int ver;
1400 
1401 	if (verinfo == NULL)
1402 		return (modlist_lookup(name, 0));
1403 	bestmod = NULL;
1404 	TAILQ_FOREACH(mod, &found_modules, link) {
1405 		if (strcmp(mod->name, name) != 0)
1406 			continue;
1407 		ver = mod->version;
1408 		if (ver == verinfo->md_ver_preferred)
1409 			return (mod);
1410 		if (ver >= verinfo->md_ver_minimum &&
1411 		    ver <= verinfo->md_ver_maximum &&
1412 		    (bestmod == NULL || ver > bestmod->version))
1413 			bestmod = mod;
1414 	}
1415 	return (bestmod);
1416 }
1417 
1418 static modlist_t
1419 modlist_newmodule(const char *modname, int version, linker_file_t container)
1420 {
1421 	modlist_t mod;
1422 
1423 	mod = malloc(sizeof(struct modlist), M_LINKER, M_NOWAIT | M_ZERO);
1424 	if (mod == NULL)
1425 		panic("no memory for module list");
1426 	mod->container = container;
1427 	mod->name = modname;
1428 	mod->version = version;
1429 	TAILQ_INSERT_TAIL(&found_modules, mod, link);
1430 	return (mod);
1431 }
1432 
1433 static void
1434 linker_addmodules(linker_file_t lf, struct mod_metadata **start,
1435     struct mod_metadata **stop, int preload)
1436 {
1437 	struct mod_metadata *mp, **mdp;
1438 	const char *modname;
1439 	int ver;
1440 
1441 	for (mdp = start; mdp < stop; mdp++) {
1442 		mp = *mdp;
1443 		if (mp->md_type != MDT_VERSION)
1444 			continue;
1445 		modname = mp->md_cval;
1446 		ver = ((struct mod_version *)mp->md_data)->mv_version;
1447 		if (modlist_lookup(modname, ver) != NULL) {
1448 			printf("module %s already present!\n", modname);
1449 			/* XXX what can we do? this is a build error. :-( */
1450 			continue;
1451 		}
1452 		modlist_newmodule(modname, ver, lf);
1453 	}
1454 }
1455 
1456 static void
1457 linker_preload(void *arg)
1458 {
1459 	caddr_t modptr;
1460 	const char *modname, *nmodname;
1461 	char *modtype;
1462 	linker_file_t lf, nlf;
1463 	linker_class_t lc;
1464 	int error;
1465 	linker_file_list_t loaded_files;
1466 	linker_file_list_t depended_files;
1467 	struct mod_metadata *mp, *nmp;
1468 	struct mod_metadata **start, **stop, **mdp, **nmdp;
1469 	struct mod_depend *verinfo;
1470 	int nver;
1471 	int resolves;
1472 	modlist_t mod;
1473 	struct sysinit **si_start, **si_stop;
1474 
1475 	TAILQ_INIT(&loaded_files);
1476 	TAILQ_INIT(&depended_files);
1477 	TAILQ_INIT(&found_modules);
1478 	error = 0;
1479 
1480 	modptr = NULL;
1481 	while ((modptr = preload_search_next_name(modptr)) != NULL) {
1482 		modname = (char *)preload_search_info(modptr, MODINFO_NAME);
1483 		modtype = (char *)preload_search_info(modptr, MODINFO_TYPE);
1484 		if (modname == NULL) {
1485 			printf("Preloaded module at %p does not have a"
1486 			    " name!\n", modptr);
1487 			continue;
1488 		}
1489 		if (modtype == NULL) {
1490 			printf("Preloaded module at %p does not have a type!\n",
1491 			    modptr);
1492 			continue;
1493 		}
1494 		if (bootverbose)
1495 			printf("Preloaded %s \"%s\" at %p.\n", modtype, modname,
1496 			    modptr);
1497 		lf = NULL;
1498 		TAILQ_FOREACH(lc, &classes, link) {
1499 			error = LINKER_LINK_PRELOAD(lc, modname, &lf);
1500 			if (!error)
1501 				break;
1502 			lf = NULL;
1503 		}
1504 		if (lf)
1505 			TAILQ_INSERT_TAIL(&loaded_files, lf, loaded);
1506 	}
1507 
1508 	/*
1509 	 * First get a list of stuff in the kernel.
1510 	 */
1511 	if (linker_file_lookup_set(linker_kernel_file, MDT_SETNAME, &start,
1512 	    &stop, NULL) == 0)
1513 		linker_addmodules(linker_kernel_file, start, stop, 1);
1514 
1515 	/*
1516 	 * This is a once-off kinky bubble sort to resolve relocation
1517 	 * dependency requirements.
1518 	 */
1519 restart:
1520 	TAILQ_FOREACH(lf, &loaded_files, loaded) {
1521 		error = linker_file_lookup_set(lf, MDT_SETNAME, &start,
1522 		    &stop, NULL);
1523 		/*
1524 		 * First, look to see if we would successfully link with this
1525 		 * stuff.
1526 		 */
1527 		resolves = 1;	/* unless we know otherwise */
1528 		if (!error) {
1529 			for (mdp = start; mdp < stop; mdp++) {
1530 				mp = *mdp;
1531 				if (mp->md_type != MDT_DEPEND)
1532 					continue;
1533 				modname = mp->md_cval;
1534 				verinfo = mp->md_data;
1535 				for (nmdp = start; nmdp < stop; nmdp++) {
1536 					nmp = *nmdp;
1537 					if (nmp->md_type != MDT_VERSION)
1538 						continue;
1539 					nmodname = nmp->md_cval;
1540 					if (strcmp(modname, nmodname) == 0)
1541 						break;
1542 				}
1543 				if (nmdp < stop)   /* it's a self reference */
1544 					continue;
1545 
1546 				/*
1547 				 * ok, the module isn't here yet, we
1548 				 * are not finished
1549 				 */
1550 				if (modlist_lookup2(modname, verinfo) == NULL)
1551 					resolves = 0;
1552 			}
1553 		}
1554 		/*
1555 		 * OK, if we found our modules, we can link.  So, "provide"
1556 		 * the modules inside and add it to the end of the link order
1557 		 * list.
1558 		 */
1559 		if (resolves) {
1560 			if (!error) {
1561 				for (mdp = start; mdp < stop; mdp++) {
1562 					mp = *mdp;
1563 					if (mp->md_type != MDT_VERSION)
1564 						continue;
1565 					modname = mp->md_cval;
1566 					nver = ((struct mod_version *)
1567 					    mp->md_data)->mv_version;
1568 					if (modlist_lookup(modname,
1569 					    nver) != NULL) {
1570 						printf("module %s already"
1571 						    " present!\n", modname);
1572 						TAILQ_REMOVE(&loaded_files,
1573 						    lf, loaded);
1574 						linker_file_unload(lf,
1575 						    LINKER_UNLOAD_FORCE);
1576 						/* we changed tailq next ptr */
1577 						goto restart;
1578 					}
1579 					modlist_newmodule(modname, nver, lf);
1580 				}
1581 			}
1582 			TAILQ_REMOVE(&loaded_files, lf, loaded);
1583 			TAILQ_INSERT_TAIL(&depended_files, lf, loaded);
1584 			/*
1585 			 * Since we provided modules, we need to restart the
1586 			 * sort so that the previous files that depend on us
1587 			 * have a chance. Also, we've busted the tailq next
1588 			 * pointer with the REMOVE.
1589 			 */
1590 			goto restart;
1591 		}
1592 	}
1593 
1594 	/*
1595 	 * At this point, we check to see what could not be resolved..
1596 	 */
1597 	while ((lf = TAILQ_FIRST(&loaded_files)) != NULL) {
1598 		TAILQ_REMOVE(&loaded_files, lf, loaded);
1599 		printf("KLD file %s is missing dependencies\n", lf->filename);
1600 		linker_file_unload(lf, LINKER_UNLOAD_FORCE);
1601 	}
1602 
1603 	/*
1604 	 * We made it. Finish off the linking in the order we determined.
1605 	 */
1606 	TAILQ_FOREACH_SAFE(lf, &depended_files, loaded, nlf) {
1607 		if (linker_kernel_file) {
1608 			linker_kernel_file->refs++;
1609 			error = linker_file_add_dependency(lf,
1610 			    linker_kernel_file);
1611 			if (error)
1612 				panic("cannot add dependency");
1613 		}
1614 		lf->userrefs++;	/* so we can (try to) kldunload it */
1615 		error = linker_file_lookup_set(lf, MDT_SETNAME, &start,
1616 		    &stop, NULL);
1617 		if (!error) {
1618 			for (mdp = start; mdp < stop; mdp++) {
1619 				mp = *mdp;
1620 				if (mp->md_type != MDT_DEPEND)
1621 					continue;
1622 				modname = mp->md_cval;
1623 				verinfo = mp->md_data;
1624 				mod = modlist_lookup2(modname, verinfo);
1625 				if (mod == NULL) {
1626 					printf("KLD file %s - cannot find "
1627 					    "dependency \"%s\"\n",
1628 					    lf->filename, modname);
1629 					goto fail;
1630 				}
1631 				/* Don't count self-dependencies */
1632 				if (lf == mod->container)
1633 					continue;
1634 				mod->container->refs++;
1635 				error = linker_file_add_dependency(lf,
1636 				    mod->container);
1637 				if (error)
1638 					panic("cannot add dependency");
1639 			}
1640 		}
1641 		/*
1642 		 * Now do relocation etc using the symbol search paths
1643 		 * established by the dependencies
1644 		 */
1645 		error = LINKER_LINK_PRELOAD_FINISH(lf);
1646 		if (error) {
1647 			printf("KLD file %s - could not finalize loading\n",
1648 			    lf->filename);
1649 			goto fail;
1650 		}
1651 		linker_file_register_modules(lf);
1652 		if (linker_file_lookup_set(lf, "sysinit_set", &si_start,
1653 		    &si_stop, NULL) == 0)
1654 			sysinit_add(si_start, si_stop);
1655 		linker_file_register_sysctls(lf);
1656 		lf->flags |= LINKER_FILE_LINKED;
1657 		continue;
1658 fail:
1659 		TAILQ_REMOVE(&depended_files, lf, loaded);
1660 		linker_file_unload(lf, LINKER_UNLOAD_FORCE);
1661 	}
1662 	/* woohoo! we made it! */
1663 }
1664 
1665 SYSINIT(preload, SI_SUB_KLD, SI_ORDER_MIDDLE, linker_preload, 0);
1666 
1667 /*
1668  * Search for a not-loaded module by name.
1669  *
1670  * Modules may be found in the following locations:
1671  *
1672  * - preloaded (result is just the module name) - on disk (result is full path
1673  * to module)
1674  *
1675  * If the module name is qualified in any way (contains path, etc.) the we
1676  * simply return a copy of it.
1677  *
1678  * The search path can be manipulated via sysctl.  Note that we use the ';'
1679  * character as a separator to be consistent with the bootloader.
1680  */
1681 
1682 static char linker_hintfile[] = "linker.hints";
1683 static char linker_path[MAXPATHLEN] = "/boot/kernel;/boot/modules";
1684 
1685 SYSCTL_STRING(_kern, OID_AUTO, module_path, CTLFLAG_RW, linker_path,
1686     sizeof(linker_path), "module load search path");
1687 
1688 TUNABLE_STR("module_path", linker_path, sizeof(linker_path));
1689 
1690 static char *linker_ext_list[] = {
1691 	"",
1692 	".ko",
1693 	NULL
1694 };
1695 
1696 /*
1697  * Check if file actually exists either with or without extension listed in
1698  * the linker_ext_list. (probably should be generic for the rest of the
1699  * kernel)
1700  */
1701 static char *
1702 linker_lookup_file(const char *path, int pathlen, const char *name,
1703     int namelen, struct vattr *vap)
1704 {
1705 	struct nameidata nd;
1706 	struct thread *td = curthread;	/* XXX */
1707 	char *result, **cpp, *sep;
1708 	int error, len, extlen, reclen, flags, vfslocked;
1709 	enum vtype type;
1710 
1711 	extlen = 0;
1712 	for (cpp = linker_ext_list; *cpp; cpp++) {
1713 		len = strlen(*cpp);
1714 		if (len > extlen)
1715 			extlen = len;
1716 	}
1717 	extlen++;		/* trailing '\0' */
1718 	sep = (path[pathlen - 1] != '/') ? "/" : "";
1719 
1720 	reclen = pathlen + strlen(sep) + namelen + extlen + 1;
1721 	result = malloc(reclen, M_LINKER, M_WAITOK);
1722 	for (cpp = linker_ext_list; *cpp; cpp++) {
1723 		snprintf(result, reclen, "%.*s%s%.*s%s", pathlen, path, sep,
1724 		    namelen, name, *cpp);
1725 		/*
1726 		 * Attempt to open the file, and return the path if
1727 		 * we succeed and it's a regular file.
1728 		 */
1729 		NDINIT(&nd, LOOKUP, FOLLOW | MPSAFE, UIO_SYSSPACE, result, td);
1730 		flags = FREAD;
1731 		error = vn_open(&nd, &flags, 0, NULL);
1732 		if (error == 0) {
1733 			vfslocked = NDHASGIANT(&nd);
1734 			NDFREE(&nd, NDF_ONLY_PNBUF);
1735 			type = nd.ni_vp->v_type;
1736 			if (vap)
1737 				VOP_GETATTR(nd.ni_vp, vap, td->td_ucred);
1738 			VOP_UNLOCK(nd.ni_vp, 0);
1739 			vn_close(nd.ni_vp, FREAD, td->td_ucred, td);
1740 			VFS_UNLOCK_GIANT(vfslocked);
1741 			if (type == VREG)
1742 				return (result);
1743 		}
1744 	}
1745 	free(result, M_LINKER);
1746 	return (NULL);
1747 }
1748 
1749 #define	INT_ALIGN(base, ptr)	ptr =					\
1750 	(base) + (((ptr) - (base) + sizeof(int) - 1) & ~(sizeof(int) - 1))
1751 
1752 /*
1753  * Lookup KLD which contains requested module in the "linker.hints" file. If
1754  * version specification is available, then try to find the best KLD.
1755  * Otherwise just find the latest one.
1756  */
1757 static char *
1758 linker_hints_lookup(const char *path, int pathlen, const char *modname,
1759     int modnamelen, struct mod_depend *verinfo)
1760 {
1761 	struct thread *td = curthread;	/* XXX */
1762 	struct ucred *cred = td ? td->td_ucred : NULL;
1763 	struct nameidata nd;
1764 	struct vattr vattr, mattr;
1765 	u_char *hints = NULL;
1766 	u_char *cp, *recptr, *bufend, *result, *best, *pathbuf, *sep;
1767 	int error, ival, bestver, *intp, found, flags, clen, blen;
1768 	ssize_t reclen;
1769 	int vfslocked = 0;
1770 
1771 	result = NULL;
1772 	bestver = found = 0;
1773 
1774 	sep = (path[pathlen - 1] != '/') ? "/" : "";
1775 	reclen = imax(modnamelen, strlen(linker_hintfile)) + pathlen +
1776 	    strlen(sep) + 1;
1777 	pathbuf = malloc(reclen, M_LINKER, M_WAITOK);
1778 	snprintf(pathbuf, reclen, "%.*s%s%s", pathlen, path, sep,
1779 	    linker_hintfile);
1780 
1781 	NDINIT(&nd, LOOKUP, NOFOLLOW | MPSAFE, UIO_SYSSPACE, pathbuf, td);
1782 	flags = FREAD;
1783 	error = vn_open(&nd, &flags, 0, NULL);
1784 	if (error)
1785 		goto bad;
1786 	vfslocked = NDHASGIANT(&nd);
1787 	NDFREE(&nd, NDF_ONLY_PNBUF);
1788 	if (nd.ni_vp->v_type != VREG)
1789 		goto bad;
1790 	best = cp = NULL;
1791 	error = VOP_GETATTR(nd.ni_vp, &vattr, cred);
1792 	if (error)
1793 		goto bad;
1794 	/*
1795 	 * XXX: we need to limit this number to some reasonable value
1796 	 */
1797 	if (vattr.va_size > 100 * 1024) {
1798 		printf("hints file too large %ld\n", (long)vattr.va_size);
1799 		goto bad;
1800 	}
1801 	hints = malloc(vattr.va_size, M_TEMP, M_WAITOK);
1802 	if (hints == NULL)
1803 		goto bad;
1804 	error = vn_rdwr(UIO_READ, nd.ni_vp, (caddr_t)hints, vattr.va_size, 0,
1805 	    UIO_SYSSPACE, IO_NODELOCKED, cred, NOCRED, &reclen, td);
1806 	if (error)
1807 		goto bad;
1808 	VOP_UNLOCK(nd.ni_vp, 0);
1809 	vn_close(nd.ni_vp, FREAD, cred, td);
1810 	VFS_UNLOCK_GIANT(vfslocked);
1811 	nd.ni_vp = NULL;
1812 	if (reclen != 0) {
1813 		printf("can't read %zd\n", reclen);
1814 		goto bad;
1815 	}
1816 	intp = (int *)hints;
1817 	ival = *intp++;
1818 	if (ival != LINKER_HINTS_VERSION) {
1819 		printf("hints file version mismatch %d\n", ival);
1820 		goto bad;
1821 	}
1822 	bufend = hints + vattr.va_size;
1823 	recptr = (u_char *)intp;
1824 	clen = blen = 0;
1825 	while (recptr < bufend && !found) {
1826 		intp = (int *)recptr;
1827 		reclen = *intp++;
1828 		ival = *intp++;
1829 		cp = (char *)intp;
1830 		switch (ival) {
1831 		case MDT_VERSION:
1832 			clen = *cp++;
1833 			if (clen != modnamelen || bcmp(cp, modname, clen) != 0)
1834 				break;
1835 			cp += clen;
1836 			INT_ALIGN(hints, cp);
1837 			ival = *(int *)cp;
1838 			cp += sizeof(int);
1839 			clen = *cp++;
1840 			if (verinfo == NULL ||
1841 			    ival == verinfo->md_ver_preferred) {
1842 				found = 1;
1843 				break;
1844 			}
1845 			if (ival >= verinfo->md_ver_minimum &&
1846 			    ival <= verinfo->md_ver_maximum &&
1847 			    ival > bestver) {
1848 				bestver = ival;
1849 				best = cp;
1850 				blen = clen;
1851 			}
1852 			break;
1853 		default:
1854 			break;
1855 		}
1856 		recptr += reclen + sizeof(int);
1857 	}
1858 	/*
1859 	 * Finally check if KLD is in the place
1860 	 */
1861 	if (found)
1862 		result = linker_lookup_file(path, pathlen, cp, clen, &mattr);
1863 	else if (best)
1864 		result = linker_lookup_file(path, pathlen, best, blen, &mattr);
1865 
1866 	/*
1867 	 * KLD is newer than hints file. What we should do now?
1868 	 */
1869 	if (result && timespeccmp(&mattr.va_mtime, &vattr.va_mtime, >))
1870 		printf("warning: KLD '%s' is newer than the linker.hints"
1871 		    " file\n", result);
1872 bad:
1873 	free(pathbuf, M_LINKER);
1874 	if (hints)
1875 		free(hints, M_TEMP);
1876 	if (nd.ni_vp != NULL) {
1877 		VOP_UNLOCK(nd.ni_vp, 0);
1878 		vn_close(nd.ni_vp, FREAD, cred, td);
1879 		VFS_UNLOCK_GIANT(vfslocked);
1880 	}
1881 	/*
1882 	 * If nothing found or hints is absent - fallback to the old
1883 	 * way by using "kldname[.ko]" as module name.
1884 	 */
1885 	if (!found && !bestver && result == NULL)
1886 		result = linker_lookup_file(path, pathlen, modname,
1887 		    modnamelen, NULL);
1888 	return (result);
1889 }
1890 
1891 /*
1892  * Lookup KLD which contains requested module in the all directories.
1893  */
1894 static char *
1895 linker_search_module(const char *modname, int modnamelen,
1896     struct mod_depend *verinfo)
1897 {
1898 	char *cp, *ep, *result;
1899 
1900 	/*
1901 	 * traverse the linker path
1902 	 */
1903 	for (cp = linker_path; *cp; cp = ep + 1) {
1904 		/* find the end of this component */
1905 		for (ep = cp; (*ep != 0) && (*ep != ';'); ep++);
1906 		result = linker_hints_lookup(cp, ep - cp, modname,
1907 		    modnamelen, verinfo);
1908 		if (result != NULL)
1909 			return (result);
1910 		if (*ep == 0)
1911 			break;
1912 	}
1913 	return (NULL);
1914 }
1915 
1916 /*
1917  * Search for module in all directories listed in the linker_path.
1918  */
1919 static char *
1920 linker_search_kld(const char *name)
1921 {
1922 	char *cp, *ep, *result;
1923 	int len;
1924 
1925 	/* qualified at all? */
1926 	if (strchr(name, '/'))
1927 		return (linker_strdup(name));
1928 
1929 	/* traverse the linker path */
1930 	len = strlen(name);
1931 	for (ep = linker_path; *ep; ep++) {
1932 		cp = ep;
1933 		/* find the end of this component */
1934 		for (; *ep != 0 && *ep != ';'; ep++);
1935 		result = linker_lookup_file(cp, ep - cp, name, len, NULL);
1936 		if (result != NULL)
1937 			return (result);
1938 	}
1939 	return (NULL);
1940 }
1941 
1942 static const char *
1943 linker_basename(const char *path)
1944 {
1945 	const char *filename;
1946 
1947 	filename = strrchr(path, '/');
1948 	if (filename == NULL)
1949 		return path;
1950 	if (filename[1])
1951 		filename++;
1952 	return (filename);
1953 }
1954 
1955 #ifdef HWPMC_HOOKS
1956 /*
1957  * Inform hwpmc about the set of kernel modules currently loaded.
1958  */
1959 void *
1960 linker_hwpmc_list_objects(void)
1961 {
1962 	linker_file_t lf;
1963 	struct pmckern_map_in *kobase;
1964 	int i, nmappings;
1965 
1966 	nmappings = 0;
1967 	KLD_LOCK_READ();
1968 	TAILQ_FOREACH(lf, &linker_files, link)
1969 		nmappings++;
1970 
1971 	/* Allocate nmappings + 1 entries. */
1972 	kobase = malloc((nmappings + 1) * sizeof(struct pmckern_map_in),
1973 	    M_LINKER, M_WAITOK | M_ZERO);
1974 	i = 0;
1975 	TAILQ_FOREACH(lf, &linker_files, link) {
1976 
1977 		/* Save the info for this linker file. */
1978 		kobase[i].pm_file = lf->filename;
1979 		kobase[i].pm_address = (uintptr_t)lf->address;
1980 		i++;
1981 	}
1982 	KLD_UNLOCK_READ();
1983 
1984 	KASSERT(i > 0, ("linker_hpwmc_list_objects: no kernel objects?"));
1985 
1986 	/* The last entry of the malloced area comprises of all zeros. */
1987 	KASSERT(kobase[i].pm_file == NULL,
1988 	    ("linker_hwpmc_list_objects: last object not NULL"));
1989 
1990 	return ((void *)kobase);
1991 }
1992 #endif
1993 
1994 /*
1995  * Find a file which contains given module and load it, if "parent" is not
1996  * NULL, register a reference to it.
1997  */
1998 static int
1999 linker_load_module(const char *kldname, const char *modname,
2000     struct linker_file *parent, struct mod_depend *verinfo,
2001     struct linker_file **lfpp)
2002 {
2003 	linker_file_t lfdep;
2004 	const char *filename;
2005 	char *pathname;
2006 	int error;
2007 
2008 	KLD_LOCK_ASSERT();
2009 	if (modname == NULL) {
2010 		/*
2011  		 * We have to load KLD
2012  		 */
2013 		KASSERT(verinfo == NULL, ("linker_load_module: verinfo"
2014 		    " is not NULL"));
2015 		pathname = linker_search_kld(kldname);
2016 	} else {
2017 		if (modlist_lookup2(modname, verinfo) != NULL)
2018 			return (EEXIST);
2019 		if (kldname != NULL)
2020 			pathname = linker_strdup(kldname);
2021 		else if (rootvnode == NULL)
2022 			pathname = NULL;
2023 		else
2024 			/*
2025 			 * Need to find a KLD with required module
2026 			 */
2027 			pathname = linker_search_module(modname,
2028 			    strlen(modname), verinfo);
2029 	}
2030 	if (pathname == NULL)
2031 		return (ENOENT);
2032 
2033 	/*
2034 	 * Can't load more than one file with the same basename XXX:
2035 	 * Actually it should be possible to have multiple KLDs with
2036 	 * the same basename but different path because they can
2037 	 * provide different versions of the same modules.
2038 	 */
2039 	filename = linker_basename(pathname);
2040 	if (linker_find_file_by_name(filename))
2041 		error = EEXIST;
2042 	else do {
2043 		error = linker_load_file(pathname, &lfdep);
2044 		if (error)
2045 			break;
2046 		if (modname && verinfo &&
2047 		    modlist_lookup2(modname, verinfo) == NULL) {
2048 			linker_file_unload(lfdep, LINKER_UNLOAD_FORCE);
2049 			error = ENOENT;
2050 			break;
2051 		}
2052 		if (parent) {
2053 			error = linker_file_add_dependency(parent, lfdep);
2054 			if (error)
2055 				break;
2056 		}
2057 		if (lfpp)
2058 			*lfpp = lfdep;
2059 	} while (0);
2060 	free(pathname, M_LINKER);
2061 	return (error);
2062 }
2063 
2064 /*
2065  * This routine is responsible for finding dependencies of userland initiated
2066  * kldload(2)'s of files.
2067  */
2068 int
2069 linker_load_dependencies(linker_file_t lf)
2070 {
2071 	linker_file_t lfdep;
2072 	struct mod_metadata **start, **stop, **mdp, **nmdp;
2073 	struct mod_metadata *mp, *nmp;
2074 	struct mod_depend *verinfo;
2075 	modlist_t mod;
2076 	const char *modname, *nmodname;
2077 	int ver, error = 0, count;
2078 
2079 	/*
2080 	 * All files are dependant on /kernel.
2081 	 */
2082 	KLD_LOCK_ASSERT();
2083 	if (linker_kernel_file) {
2084 		linker_kernel_file->refs++;
2085 		error = linker_file_add_dependency(lf, linker_kernel_file);
2086 		if (error)
2087 			return (error);
2088 	}
2089 	if (linker_file_lookup_set(lf, MDT_SETNAME, &start, &stop,
2090 	    &count) != 0)
2091 		return (0);
2092 	for (mdp = start; mdp < stop; mdp++) {
2093 		mp = *mdp;
2094 		if (mp->md_type != MDT_VERSION)
2095 			continue;
2096 		modname = mp->md_cval;
2097 		ver = ((struct mod_version *)mp->md_data)->mv_version;
2098 		mod = modlist_lookup(modname, ver);
2099 		if (mod != NULL) {
2100 			printf("interface %s.%d already present in the KLD"
2101 			    " '%s'!\n", modname, ver,
2102 			    mod->container->filename);
2103 			return (EEXIST);
2104 		}
2105 	}
2106 
2107 	for (mdp = start; mdp < stop; mdp++) {
2108 		mp = *mdp;
2109 		if (mp->md_type != MDT_DEPEND)
2110 			continue;
2111 		modname = mp->md_cval;
2112 		verinfo = mp->md_data;
2113 		nmodname = NULL;
2114 		for (nmdp = start; nmdp < stop; nmdp++) {
2115 			nmp = *nmdp;
2116 			if (nmp->md_type != MDT_VERSION)
2117 				continue;
2118 			nmodname = nmp->md_cval;
2119 			if (strcmp(modname, nmodname) == 0)
2120 				break;
2121 		}
2122 		if (nmdp < stop)/* early exit, it's a self reference */
2123 			continue;
2124 		mod = modlist_lookup2(modname, verinfo);
2125 		if (mod) {	/* woohoo, it's loaded already */
2126 			lfdep = mod->container;
2127 			lfdep->refs++;
2128 			error = linker_file_add_dependency(lf, lfdep);
2129 			if (error)
2130 				break;
2131 			continue;
2132 		}
2133 		error = linker_load_module(NULL, modname, lf, verinfo, NULL);
2134 		if (error) {
2135 			printf("KLD %s: depends on %s - not available or"
2136 			    " version mismatch\n", lf->filename, modname);
2137 			break;
2138 		}
2139 	}
2140 
2141 	if (error)
2142 		return (error);
2143 	linker_addmodules(lf, start, stop, 0);
2144 	return (error);
2145 }
2146 
2147 static int
2148 sysctl_kern_function_list_iterate(const char *name, void *opaque)
2149 {
2150 	struct sysctl_req *req;
2151 
2152 	req = opaque;
2153 	return (SYSCTL_OUT(req, name, strlen(name) + 1));
2154 }
2155 
2156 /*
2157  * Export a nul-separated, double-nul-terminated list of all function names
2158  * in the kernel.
2159  */
2160 static int
2161 sysctl_kern_function_list(SYSCTL_HANDLER_ARGS)
2162 {
2163 	linker_file_t lf;
2164 	int error;
2165 
2166 #ifdef MAC
2167 	error = mac_kld_check_stat(req->td->td_ucred);
2168 	if (error)
2169 		return (error);
2170 #endif
2171 	error = sysctl_wire_old_buffer(req, 0);
2172 	if (error != 0)
2173 		return (error);
2174 	KLD_LOCK();
2175 	TAILQ_FOREACH(lf, &linker_files, link) {
2176 		error = LINKER_EACH_FUNCTION_NAME(lf,
2177 		    sysctl_kern_function_list_iterate, req);
2178 		if (error) {
2179 			KLD_UNLOCK();
2180 			return (error);
2181 		}
2182 	}
2183 	KLD_UNLOCK();
2184 	return (SYSCTL_OUT(req, "", 1));
2185 }
2186 
2187 SYSCTL_PROC(_kern, OID_AUTO, function_list, CTLTYPE_OPAQUE | CTLFLAG_RD,
2188     NULL, 0, sysctl_kern_function_list, "", "kernel function list");
2189