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