xref: /freebsd/sys/kern/kern_linker.c (revision 8776669b53777489f705930295036a5eb0c5a37e)
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/eventhandler.h>
49 #include <sys/fcntl.h>
50 #include <sys/jail.h>
51 #include <sys/libkern.h>
52 #include <sys/namei.h>
53 #include <sys/vnode.h>
54 #include <sys/syscallsubr.h>
55 #include <sys/sysctl.h>
56 
57 #include <net/vnet.h>
58 
59 #include <security/mac/mac_framework.h>
60 
61 #include "linker_if.h"
62 
63 #ifdef HWPMC_HOOKS
64 #include <sys/pmckern.h>
65 #endif
66 
67 #ifdef KLD_DEBUG
68 int kld_debug = 0;
69 SYSCTL_INT(_debug, OID_AUTO, kld_debug, CTLFLAG_RW | CTLFLAG_TUN,
70     &kld_debug, 0, "Set various levels of KLD debug");
71 TUNABLE_INT("debug.kld_debug", &kld_debug);
72 #endif
73 
74 #define	KLD_LOCK()		sx_xlock(&kld_sx)
75 #define	KLD_UNLOCK()		sx_xunlock(&kld_sx)
76 #define	KLD_DOWNGRADE()		sx_downgrade(&kld_sx)
77 #define	KLD_LOCK_READ()		sx_slock(&kld_sx)
78 #define	KLD_UNLOCK_READ()	sx_sunlock(&kld_sx)
79 #define	KLD_LOCKED()		sx_xlocked(&kld_sx)
80 #define	KLD_LOCK_ASSERT() do {						\
81 	if (!cold)							\
82 		sx_assert(&kld_sx, SX_XLOCKED);				\
83 } while (0)
84 
85 /*
86  * static char *linker_search_path(const char *name, struct mod_depend
87  * *verinfo);
88  */
89 static const char 	*linker_basename(const char *path);
90 
91 /*
92  * Find a currently loaded file given its filename.
93  */
94 static linker_file_t linker_find_file_by_name(const char* _filename);
95 
96 /*
97  * Find a currently loaded file given its file id.
98  */
99 static linker_file_t linker_find_file_by_id(int _fileid);
100 
101 /* Metadata from the static kernel */
102 SET_DECLARE(modmetadata_set, struct mod_metadata);
103 
104 MALLOC_DEFINE(M_LINKER, "linker", "kernel linker");
105 
106 linker_file_t linker_kernel_file;
107 
108 static struct sx kld_sx;	/* kernel linker lock */
109 
110 /*
111  * Load counter used by clients to determine if a linker file has been
112  * re-loaded. This counter is incremented for each file load.
113  */
114 static int loadcnt;
115 
116 static linker_class_list_t classes;
117 static linker_file_list_t linker_files;
118 static int next_file_id = 1;
119 static int linker_no_more_classes = 0;
120 
121 #define	LINKER_GET_NEXT_FILE_ID(a) do {					\
122 	linker_file_t lftmp;						\
123 									\
124 	KLD_LOCK_ASSERT();						\
125 retry:									\
126 	TAILQ_FOREACH(lftmp, &linker_files, link) {			\
127 		if (next_file_id == lftmp->id) {			\
128 			next_file_id++;					\
129 			goto retry;					\
130 		}							\
131 	}								\
132 	(a) = next_file_id;						\
133 } while(0)
134 
135 
136 /* XXX wrong name; we're looking at version provision tags here, not modules */
137 typedef TAILQ_HEAD(, modlist) modlisthead_t;
138 struct modlist {
139 	TAILQ_ENTRY(modlist) link;	/* chain together all modules */
140 	linker_file_t   container;
141 	const char 	*name;
142 	int             version;
143 };
144 typedef struct modlist *modlist_t;
145 static modlisthead_t found_modules;
146 
147 static int	linker_file_add_dependency(linker_file_t file,
148 		    linker_file_t dep);
149 static caddr_t	linker_file_lookup_symbol_internal(linker_file_t file,
150 		    const char* name, int deps);
151 static int	linker_load_module(const char *kldname,
152 		    const char *modname, struct linker_file *parent,
153 		    struct mod_depend *verinfo, struct linker_file **lfpp);
154 static modlist_t modlist_lookup2(const char *name, struct mod_depend *verinfo);
155 
156 static char *
157 linker_strdup(const char *str)
158 {
159 	char *result;
160 
161 	if ((result = malloc((strlen(str) + 1), M_LINKER, M_WAITOK)) != NULL)
162 		strcpy(result, str);
163 	return (result);
164 }
165 
166 static void
167 linker_init(void *arg)
168 {
169 
170 	sx_init(&kld_sx, "kernel linker");
171 	TAILQ_INIT(&classes);
172 	TAILQ_INIT(&linker_files);
173 }
174 
175 SYSINIT(linker, SI_SUB_KLD, SI_ORDER_FIRST, linker_init, 0);
176 
177 static void
178 linker_stop_class_add(void *arg)
179 {
180 
181 	linker_no_more_classes = 1;
182 }
183 
184 SYSINIT(linker_class, SI_SUB_KLD, SI_ORDER_ANY, linker_stop_class_add, NULL);
185 
186 int
187 linker_add_class(linker_class_t lc)
188 {
189 
190 	/*
191 	 * We disallow any class registration past SI_ORDER_ANY
192 	 * of SI_SUB_KLD.  We bump the reference count to keep the
193 	 * ops from being freed.
194 	 */
195 	if (linker_no_more_classes == 1)
196 		return (EPERM);
197 	kobj_class_compile((kobj_class_t) lc);
198 	((kobj_class_t)lc)->refs++;	/* XXX: kobj_mtx */
199 	TAILQ_INSERT_TAIL(&classes, lc, link);
200 	return (0);
201 }
202 
203 static void
204 linker_file_sysinit(linker_file_t lf)
205 {
206 	struct sysinit **start, **stop, **sipp, **xipp, *save;
207 
208 	KLD_DPF(FILE, ("linker_file_sysinit: calling SYSINITs for %s\n",
209 	    lf->filename));
210 
211 	if (linker_file_lookup_set(lf, "sysinit_set", &start, &stop, NULL) != 0)
212 		return;
213 	/*
214 	 * Perform a bubble sort of the system initialization objects by
215 	 * their subsystem (primary key) and order (secondary key).
216 	 *
217 	 * Since some things care about execution order, this is the operation
218 	 * which ensures continued function.
219 	 */
220 	for (sipp = start; sipp < stop; sipp++) {
221 		for (xipp = sipp + 1; xipp < stop; xipp++) {
222 			if ((*sipp)->subsystem < (*xipp)->subsystem ||
223 			    ((*sipp)->subsystem == (*xipp)->subsystem &&
224 			    (*sipp)->order <= (*xipp)->order))
225 				continue;	/* skip */
226 			save = *sipp;
227 			*sipp = *xipp;
228 			*xipp = save;
229 		}
230 	}
231 
232 	/*
233 	 * Traverse the (now) ordered list of system initialization tasks.
234 	 * Perform each task, and continue on to the next task.
235 	 */
236 	mtx_lock(&Giant);
237 	for (sipp = start; sipp < stop; sipp++) {
238 		if ((*sipp)->subsystem == SI_SUB_DUMMY)
239 			continue;	/* skip dummy task(s) */
240 
241 		/* Call function */
242 		(*((*sipp)->func)) ((*sipp)->udata);
243 	}
244 	mtx_unlock(&Giant);
245 }
246 
247 static void
248 linker_file_sysuninit(linker_file_t lf)
249 {
250 	struct sysinit **start, **stop, **sipp, **xipp, *save;
251 
252 	KLD_DPF(FILE, ("linker_file_sysuninit: calling SYSUNINITs for %s\n",
253 	    lf->filename));
254 
255 	if (linker_file_lookup_set(lf, "sysuninit_set", &start, &stop,
256 	    NULL) != 0)
257 		return;
258 
259 	/*
260 	 * Perform a reverse bubble sort of the system initialization objects
261 	 * by their subsystem (primary key) and order (secondary key).
262 	 *
263 	 * Since some things care about execution order, this is the operation
264 	 * which ensures continued function.
265 	 */
266 	for (sipp = start; sipp < stop; sipp++) {
267 		for (xipp = sipp + 1; xipp < stop; xipp++) {
268 			if ((*sipp)->subsystem > (*xipp)->subsystem ||
269 			    ((*sipp)->subsystem == (*xipp)->subsystem &&
270 			    (*sipp)->order >= (*xipp)->order))
271 				continue;	/* skip */
272 			save = *sipp;
273 			*sipp = *xipp;
274 			*xipp = save;
275 		}
276 	}
277 
278 	/*
279 	 * Traverse the (now) ordered list of system initialization tasks.
280 	 * Perform each task, and continue on to the next task.
281 	 */
282 	mtx_lock(&Giant);
283 	for (sipp = start; sipp < stop; sipp++) {
284 		if ((*sipp)->subsystem == SI_SUB_DUMMY)
285 			continue;	/* skip dummy task(s) */
286 
287 		/* Call function */
288 		(*((*sipp)->func)) ((*sipp)->udata);
289 	}
290 	mtx_unlock(&Giant);
291 }
292 
293 static void
294 linker_file_register_sysctls(linker_file_t lf)
295 {
296 	struct sysctl_oid **start, **stop, **oidp;
297 
298 	KLD_DPF(FILE,
299 	    ("linker_file_register_sysctls: registering SYSCTLs for %s\n",
300 	    lf->filename));
301 
302 	if (linker_file_lookup_set(lf, "sysctl_set", &start, &stop, NULL) != 0)
303 		return;
304 
305 	sysctl_lock();
306 	for (oidp = start; oidp < stop; oidp++)
307 		sysctl_register_oid(*oidp);
308 	sysctl_unlock();
309 }
310 
311 static void
312 linker_file_unregister_sysctls(linker_file_t lf)
313 {
314 	struct sysctl_oid **start, **stop, **oidp;
315 
316 	KLD_DPF(FILE, ("linker_file_unregister_sysctls: unregistering SYSCTLs"
317 	    " for %s\n", lf->filename));
318 
319 	if (linker_file_lookup_set(lf, "sysctl_set", &start, &stop, NULL) != 0)
320 		return;
321 
322 	sysctl_lock();
323 	for (oidp = start; oidp < stop; oidp++)
324 		sysctl_unregister_oid(*oidp);
325 	sysctl_unlock();
326 }
327 
328 static int
329 linker_file_register_modules(linker_file_t lf)
330 {
331 	struct mod_metadata **start, **stop, **mdp;
332 	const moduledata_t *moddata;
333 	int first_error, error;
334 
335 	KLD_DPF(FILE, ("linker_file_register_modules: registering modules"
336 	    " in %s\n", lf->filename));
337 
338 	if (linker_file_lookup_set(lf, "modmetadata_set", &start,
339 	    &stop, NULL) != 0) {
340 		/*
341 		 * This fallback should be unnecessary, but if we get booted
342 		 * from boot2 instead of loader and we are missing our
343 		 * metadata then we have to try the best we can.
344 		 */
345 		if (lf == linker_kernel_file) {
346 			start = SET_BEGIN(modmetadata_set);
347 			stop = SET_LIMIT(modmetadata_set);
348 		} else
349 			return (0);
350 	}
351 	first_error = 0;
352 	for (mdp = start; mdp < stop; mdp++) {
353 		if ((*mdp)->md_type != MDT_MODULE)
354 			continue;
355 		moddata = (*mdp)->md_data;
356 		KLD_DPF(FILE, ("Registering module %s in %s\n",
357 		    moddata->name, lf->filename));
358 		error = module_register(moddata, lf);
359 		if (error) {
360 			printf("Module %s failed to register: %d\n",
361 			    moddata->name, error);
362 			if (first_error == 0)
363 				first_error = error;
364 		}
365 	}
366 	return (first_error);
367 }
368 
369 static void
370 linker_init_kernel_modules(void)
371 {
372 
373 	linker_file_register_modules(linker_kernel_file);
374 }
375 
376 SYSINIT(linker_kernel, SI_SUB_KLD, SI_ORDER_ANY, linker_init_kernel_modules,
377     0);
378 
379 static int
380 linker_load_file(const char *filename, linker_file_t *result)
381 {
382 	linker_class_t lc;
383 	linker_file_t lf;
384 	int foundfile, error, modules;
385 
386 	/* Refuse to load modules if securelevel raised */
387 	if (prison0.pr_securelevel > 0)
388 		return (EPERM);
389 
390 	KLD_LOCK_ASSERT();
391 	lf = linker_find_file_by_name(filename);
392 	if (lf) {
393 		KLD_DPF(FILE, ("linker_load_file: file %s is already loaded,"
394 		    " incrementing refs\n", filename));
395 		*result = lf;
396 		lf->refs++;
397 		return (0);
398 	}
399 	foundfile = 0;
400 	error = 0;
401 
402 	/*
403 	 * We do not need to protect (lock) classes here because there is
404 	 * no class registration past startup (SI_SUB_KLD, SI_ORDER_ANY)
405 	 * and there is no class deregistration mechanism at this time.
406 	 */
407 	TAILQ_FOREACH(lc, &classes, link) {
408 		KLD_DPF(FILE, ("linker_load_file: trying to load %s\n",
409 		    filename));
410 		error = LINKER_LOAD_FILE(lc, filename, &lf);
411 		/*
412 		 * If we got something other than ENOENT, then it exists but
413 		 * we cannot load it for some other reason.
414 		 */
415 		if (error != ENOENT)
416 			foundfile = 1;
417 		if (lf) {
418 			error = linker_file_register_modules(lf);
419 			if (error == EEXIST) {
420 				linker_file_unload(lf, LINKER_UNLOAD_FORCE);
421 				return (error);
422 			}
423 			modules = !TAILQ_EMPTY(&lf->modules);
424 			KLD_UNLOCK();
425 			linker_file_register_sysctls(lf);
426 			linker_file_sysinit(lf);
427 			KLD_LOCK();
428 			lf->flags |= LINKER_FILE_LINKED;
429 
430 			/*
431 			 * If all of the modules in this file failed
432 			 * to load, unload the file and return an
433 			 * error of ENOEXEC.
434 			 */
435 			if (modules && TAILQ_EMPTY(&lf->modules)) {
436 				linker_file_unload(lf, LINKER_UNLOAD_FORCE);
437 				return (ENOEXEC);
438 			}
439 			*result = lf;
440 			return (0);
441 		}
442 	}
443 	/*
444 	 * Less than ideal, but tells the user whether it failed to load or
445 	 * the module was not found.
446 	 */
447 	if (foundfile) {
448 
449 		/*
450 		 * If the file type has not been recognized by the last try
451 		 * printout a message before to fail.
452 		 */
453 		if (error == ENOSYS)
454 			printf("linker_load_file: Unsupported file type\n");
455 
456 		/*
457 		 * Format not recognized or otherwise unloadable.
458 		 * When loading a module that is statically built into
459 		 * the kernel EEXIST percolates back up as the return
460 		 * value.  Preserve this so that apps like sysinstall
461 		 * can recognize this special case and not post bogus
462 		 * dialog boxes.
463 		 */
464 		if (error != EEXIST)
465 			error = ENOEXEC;
466 	} else
467 		error = ENOENT;		/* Nothing found */
468 	return (error);
469 }
470 
471 int
472 linker_reference_module(const char *modname, struct mod_depend *verinfo,
473     linker_file_t *result)
474 {
475 	modlist_t mod;
476 	int error;
477 
478 	KLD_LOCK();
479 	if ((mod = modlist_lookup2(modname, verinfo)) != NULL) {
480 		*result = mod->container;
481 		(*result)->refs++;
482 		KLD_UNLOCK();
483 		return (0);
484 	}
485 
486 	error = linker_load_module(NULL, modname, NULL, verinfo, result);
487 	KLD_UNLOCK();
488 	return (error);
489 }
490 
491 int
492 linker_release_module(const char *modname, struct mod_depend *verinfo,
493     linker_file_t lf)
494 {
495 	modlist_t mod;
496 	int error;
497 
498 	KLD_LOCK();
499 	if (lf == NULL) {
500 		KASSERT(modname != NULL,
501 		    ("linker_release_module: no file or name"));
502 		mod = modlist_lookup2(modname, verinfo);
503 		if (mod == NULL) {
504 			KLD_UNLOCK();
505 			return (ESRCH);
506 		}
507 		lf = mod->container;
508 	} else
509 		KASSERT(modname == NULL && verinfo == NULL,
510 		    ("linker_release_module: both file and name"));
511 	error =	linker_file_unload(lf, LINKER_UNLOAD_NORMAL);
512 	KLD_UNLOCK();
513 	return (error);
514 }
515 
516 static linker_file_t
517 linker_find_file_by_name(const char *filename)
518 {
519 	linker_file_t lf;
520 	char *koname;
521 
522 	koname = malloc(strlen(filename) + 4, M_LINKER, M_WAITOK);
523 	sprintf(koname, "%s.ko", filename);
524 
525 	KLD_LOCK_ASSERT();
526 	TAILQ_FOREACH(lf, &linker_files, link) {
527 		if (strcmp(lf->filename, koname) == 0)
528 			break;
529 		if (strcmp(lf->filename, filename) == 0)
530 			break;
531 	}
532 	free(koname, M_LINKER);
533 	return (lf);
534 }
535 
536 static linker_file_t
537 linker_find_file_by_id(int fileid)
538 {
539 	linker_file_t lf;
540 
541 	KLD_LOCK_ASSERT();
542 	TAILQ_FOREACH(lf, &linker_files, link)
543 		if (lf->id == fileid && lf->flags & LINKER_FILE_LINKED)
544 			break;
545 	return (lf);
546 }
547 
548 int
549 linker_file_foreach(linker_predicate_t *predicate, void *context)
550 {
551 	linker_file_t lf;
552 	int retval = 0;
553 
554 	KLD_LOCK();
555 	TAILQ_FOREACH(lf, &linker_files, link) {
556 		retval = predicate(lf, context);
557 		if (retval != 0)
558 			break;
559 	}
560 	KLD_UNLOCK();
561 	return (retval);
562 }
563 
564 linker_file_t
565 linker_make_file(const char *pathname, linker_class_t lc)
566 {
567 	linker_file_t lf;
568 	const char *filename;
569 
570 	KLD_LOCK_ASSERT();
571 	filename = linker_basename(pathname);
572 
573 	KLD_DPF(FILE, ("linker_make_file: new file, filename='%s' for pathname='%s'\n", filename, pathname));
574 	lf = (linker_file_t)kobj_create((kobj_class_t)lc, M_LINKER, M_WAITOK);
575 	if (lf == NULL)
576 		return (NULL);
577 	lf->refs = 1;
578 	lf->userrefs = 0;
579 	lf->flags = 0;
580 	lf->filename = linker_strdup(filename);
581 	lf->pathname = linker_strdup(pathname);
582 	LINKER_GET_NEXT_FILE_ID(lf->id);
583 	lf->ndeps = 0;
584 	lf->deps = NULL;
585 	lf->loadcnt = ++loadcnt;
586 	STAILQ_INIT(&lf->common);
587 	TAILQ_INIT(&lf->modules);
588 	TAILQ_INSERT_TAIL(&linker_files, lf, link);
589 	return (lf);
590 }
591 
592 int
593 linker_file_unload(linker_file_t file, int flags)
594 {
595 	module_t mod, next;
596 	modlist_t ml, nextml;
597 	struct common_symbol *cp;
598 	int error, i;
599 
600 	/* Refuse to unload modules if securelevel raised. */
601 	if (prison0.pr_securelevel > 0)
602 		return (EPERM);
603 
604 	KLD_LOCK_ASSERT();
605 	KLD_DPF(FILE, ("linker_file_unload: lf->refs=%d\n", file->refs));
606 
607 	/* Easy case of just dropping a reference. */
608 	if (file->refs > 1) {
609 		file->refs--;
610 		return (0);
611 	}
612 
613 	KLD_DPF(FILE, ("linker_file_unload: file is unloading,"
614 	    " informing modules\n"));
615 
616 	/*
617 	 * Quiesce all the modules to give them a chance to veto the unload.
618 	 */
619 	MOD_SLOCK;
620 	for (mod = TAILQ_FIRST(&file->modules); mod;
621 	     mod = module_getfnext(mod)) {
622 
623 		error = module_quiesce(mod);
624 		if (error != 0 && flags != LINKER_UNLOAD_FORCE) {
625 			KLD_DPF(FILE, ("linker_file_unload: module %s"
626 			    " vetoed unload\n", module_getname(mod)));
627 			/*
628 			 * XXX: Do we need to tell all the quiesced modules
629 			 * that they can resume work now via a new module
630 			 * event?
631 			 */
632 			MOD_SUNLOCK;
633 			return (error);
634 		}
635 	}
636 	MOD_SUNLOCK;
637 
638 	/*
639 	 * Inform any modules associated with this file that they are
640 	 * being unloaded.
641 	 */
642 	MOD_XLOCK;
643 	for (mod = TAILQ_FIRST(&file->modules); mod; mod = next) {
644 		next = module_getfnext(mod);
645 		MOD_XUNLOCK;
646 
647 		/*
648 		 * Give the module a chance to veto the unload.
649 		 */
650 		if ((error = module_unload(mod)) != 0) {
651 #ifdef KLD_DEBUG
652 			MOD_SLOCK;
653 			KLD_DPF(FILE, ("linker_file_unload: module %s"
654 			    " failed unload\n", module_getname(mod)));
655 			MOD_SUNLOCK;
656 #endif
657 			return (error);
658 		}
659 		MOD_XLOCK;
660 		module_release(mod);
661 	}
662 	MOD_XUNLOCK;
663 
664 	TAILQ_FOREACH_SAFE(ml, &found_modules, link, nextml) {
665 		if (ml->container == file) {
666 			TAILQ_REMOVE(&found_modules, ml, link);
667 			free(ml, M_LINKER);
668 		}
669 	}
670 
671 	/*
672 	 * Don't try to run SYSUNINITs if we are unloaded due to a
673 	 * link error.
674 	 */
675 	if (file->flags & LINKER_FILE_LINKED) {
676 		file->flags &= ~LINKER_FILE_LINKED;
677 		KLD_UNLOCK();
678 		linker_file_sysuninit(file);
679 		linker_file_unregister_sysctls(file);
680 		KLD_LOCK();
681 	}
682 	TAILQ_REMOVE(&linker_files, file, link);
683 
684 	if (file->deps) {
685 		for (i = 0; i < file->ndeps; i++)
686 			linker_file_unload(file->deps[i], flags);
687 		free(file->deps, M_LINKER);
688 		file->deps = NULL;
689 	}
690 	while ((cp = STAILQ_FIRST(&file->common)) != NULL) {
691 		STAILQ_REMOVE_HEAD(&file->common, link);
692 		free(cp, M_LINKER);
693 	}
694 
695 	LINKER_UNLOAD(file);
696 	if (file->filename) {
697 		free(file->filename, M_LINKER);
698 		file->filename = NULL;
699 	}
700 	if (file->pathname) {
701 		free(file->pathname, M_LINKER);
702 		file->pathname = NULL;
703 	}
704 	kobj_delete((kobj_t) file, M_LINKER);
705 	return (0);
706 }
707 
708 int
709 linker_ctf_get(linker_file_t file, linker_ctf_t *lc)
710 {
711 	return (LINKER_CTF_GET(file, lc));
712 }
713 
714 static int
715 linker_file_add_dependency(linker_file_t file, linker_file_t dep)
716 {
717 	linker_file_t *newdeps;
718 
719 	KLD_LOCK_ASSERT();
720 	newdeps = malloc((file->ndeps + 1) * sizeof(linker_file_t *),
721 	    M_LINKER, M_WAITOK | M_ZERO);
722 	if (newdeps == NULL)
723 		return (ENOMEM);
724 
725 	if (file->deps) {
726 		bcopy(file->deps, newdeps,
727 		    file->ndeps * sizeof(linker_file_t *));
728 		free(file->deps, M_LINKER);
729 	}
730 	file->deps = newdeps;
731 	file->deps[file->ndeps] = dep;
732 	file->ndeps++;
733 	KLD_DPF(FILE, ("linker_file_add_dependency:"
734 	    " adding %s as dependency for %s\n",
735 	    dep->filename, file->filename));
736 	return (0);
737 }
738 
739 /*
740  * Locate a linker set and its contents.  This is a helper function to avoid
741  * linker_if.h exposure elsewhere.  Note: firstp and lastp are really void **.
742  * This function is used in this file so we can avoid having lots of (void **)
743  * casts.
744  */
745 int
746 linker_file_lookup_set(linker_file_t file, const char *name,
747     void *firstp, void *lastp, int *countp)
748 {
749 	int error, locked;
750 
751 	locked = KLD_LOCKED();
752 	if (!locked)
753 		KLD_LOCK();
754 	error = LINKER_LOOKUP_SET(file, name, firstp, lastp, countp);
755 	if (!locked)
756 		KLD_UNLOCK();
757 	return (error);
758 }
759 
760 /*
761  * List all functions in a file.
762  */
763 int
764 linker_file_function_listall(linker_file_t lf,
765     linker_function_nameval_callback_t callback_func, void *arg)
766 {
767 	return (LINKER_EACH_FUNCTION_NAMEVAL(lf, callback_func, arg));
768 }
769 
770 caddr_t
771 linker_file_lookup_symbol(linker_file_t file, const char *name, int deps)
772 {
773 	caddr_t sym;
774 	int locked;
775 
776 	locked = KLD_LOCKED();
777 	if (!locked)
778 		KLD_LOCK();
779 	sym = linker_file_lookup_symbol_internal(file, name, deps);
780 	if (!locked)
781 		KLD_UNLOCK();
782 	return (sym);
783 }
784 
785 static caddr_t
786 linker_file_lookup_symbol_internal(linker_file_t file, const char *name,
787     int deps)
788 {
789 	c_linker_sym_t sym;
790 	linker_symval_t symval;
791 	caddr_t address;
792 	size_t common_size = 0;
793 	int i;
794 
795 	KLD_LOCK_ASSERT();
796 	KLD_DPF(SYM, ("linker_file_lookup_symbol: file=%p, name=%s, deps=%d\n",
797 	    file, name, deps));
798 
799 	if (LINKER_LOOKUP_SYMBOL(file, name, &sym) == 0) {
800 		LINKER_SYMBOL_VALUES(file, sym, &symval);
801 		if (symval.value == 0)
802 			/*
803 			 * For commons, first look them up in the
804 			 * dependencies and only allocate space if not found
805 			 * there.
806 			 */
807 			common_size = symval.size;
808 		else {
809 			KLD_DPF(SYM, ("linker_file_lookup_symbol: symbol"
810 			    ".value=%p\n", symval.value));
811 			return (symval.value);
812 		}
813 	}
814 	if (deps) {
815 		for (i = 0; i < file->ndeps; i++) {
816 			address = linker_file_lookup_symbol_internal(
817 			    file->deps[i], name, 0);
818 			if (address) {
819 				KLD_DPF(SYM, ("linker_file_lookup_symbol:"
820 				    " deps value=%p\n", address));
821 				return (address);
822 			}
823 		}
824 	}
825 	if (common_size > 0) {
826 		/*
827 		 * This is a common symbol which was not found in the
828 		 * dependencies.  We maintain a simple common symbol table in
829 		 * the file object.
830 		 */
831 		struct common_symbol *cp;
832 
833 		STAILQ_FOREACH(cp, &file->common, link) {
834 			if (strcmp(cp->name, name) == 0) {
835 				KLD_DPF(SYM, ("linker_file_lookup_symbol:"
836 				    " old common value=%p\n", cp->address));
837 				return (cp->address);
838 			}
839 		}
840 		/*
841 		 * Round the symbol size up to align.
842 		 */
843 		common_size = (common_size + sizeof(int) - 1) & -sizeof(int);
844 		cp = malloc(sizeof(struct common_symbol)
845 		    + common_size + strlen(name) + 1, M_LINKER,
846 		    M_WAITOK | M_ZERO);
847 		cp->address = (caddr_t)(cp + 1);
848 		cp->name = cp->address + common_size;
849 		strcpy(cp->name, name);
850 		bzero(cp->address, common_size);
851 		STAILQ_INSERT_TAIL(&file->common, cp, link);
852 
853 		KLD_DPF(SYM, ("linker_file_lookup_symbol: new common"
854 		    " value=%p\n", cp->address));
855 		return (cp->address);
856 	}
857 	KLD_DPF(SYM, ("linker_file_lookup_symbol: fail\n"));
858 	return (0);
859 }
860 
861 /*
862  * Both DDB and stack(9) rely on the kernel linker to provide forward and
863  * backward lookup of symbols.  However, DDB and sometimes stack(9) need to
864  * do this in a lockfree manner.  We provide a set of internal helper
865  * routines to perform these operations without locks, and then wrappers that
866  * optionally lock.
867  *
868  * linker_debug_lookup() is ifdef DDB as currently it's only used by DDB.
869  */
870 #ifdef DDB
871 static int
872 linker_debug_lookup(const char *symstr, c_linker_sym_t *sym)
873 {
874 	linker_file_t lf;
875 
876 	TAILQ_FOREACH(lf, &linker_files, link) {
877 		if (LINKER_LOOKUP_SYMBOL(lf, symstr, sym) == 0)
878 			return (0);
879 	}
880 	return (ENOENT);
881 }
882 #endif
883 
884 static int
885 linker_debug_search_symbol(caddr_t value, c_linker_sym_t *sym, long *diffp)
886 {
887 	linker_file_t lf;
888 	c_linker_sym_t best, es;
889 	u_long diff, bestdiff, off;
890 
891 	best = 0;
892 	off = (uintptr_t)value;
893 	bestdiff = off;
894 	TAILQ_FOREACH(lf, &linker_files, link) {
895 		if (LINKER_SEARCH_SYMBOL(lf, value, &es, &diff) != 0)
896 			continue;
897 		if (es != 0 && diff < bestdiff) {
898 			best = es;
899 			bestdiff = diff;
900 		}
901 		if (bestdiff == 0)
902 			break;
903 	}
904 	if (best) {
905 		*sym = best;
906 		*diffp = bestdiff;
907 		return (0);
908 	} else {
909 		*sym = 0;
910 		*diffp = off;
911 		return (ENOENT);
912 	}
913 }
914 
915 static int
916 linker_debug_symbol_values(c_linker_sym_t sym, linker_symval_t *symval)
917 {
918 	linker_file_t lf;
919 
920 	TAILQ_FOREACH(lf, &linker_files, link) {
921 		if (LINKER_SYMBOL_VALUES(lf, sym, symval) == 0)
922 			return (0);
923 	}
924 	return (ENOENT);
925 }
926 
927 static int
928 linker_debug_search_symbol_name(caddr_t value, char *buf, u_int buflen,
929     long *offset)
930 {
931 	linker_symval_t symval;
932 	c_linker_sym_t sym;
933 	int error;
934 
935 	*offset = 0;
936 	error = linker_debug_search_symbol(value, &sym, offset);
937 	if (error)
938 		return (error);
939 	error = linker_debug_symbol_values(sym, &symval);
940 	if (error)
941 		return (error);
942 	strlcpy(buf, symval.name, buflen);
943 	return (0);
944 }
945 
946 /*
947  * DDB Helpers.  DDB has to look across multiple files with their own symbol
948  * tables and string tables.
949  *
950  * Note that we do not obey list locking protocols here.  We really don't need
951  * DDB to hang because somebody's got the lock held.  We'll take the chance
952  * that the files list is inconsistant instead.
953  */
954 #ifdef DDB
955 int
956 linker_ddb_lookup(const char *symstr, c_linker_sym_t *sym)
957 {
958 
959 	return (linker_debug_lookup(symstr, sym));
960 }
961 #endif
962 
963 int
964 linker_ddb_search_symbol(caddr_t value, c_linker_sym_t *sym, long *diffp)
965 {
966 
967 	return (linker_debug_search_symbol(value, sym, diffp));
968 }
969 
970 int
971 linker_ddb_symbol_values(c_linker_sym_t sym, linker_symval_t *symval)
972 {
973 
974 	return (linker_debug_symbol_values(sym, symval));
975 }
976 
977 int
978 linker_ddb_search_symbol_name(caddr_t value, char *buf, u_int buflen,
979     long *offset)
980 {
981 
982 	return (linker_debug_search_symbol_name(value, buf, buflen, offset));
983 }
984 
985 /*
986  * stack(9) helper for non-debugging environemnts.  Unlike DDB helpers, we do
987  * obey locking protocols, and offer a significantly less complex interface.
988  */
989 int
990 linker_search_symbol_name(caddr_t value, char *buf, u_int buflen,
991     long *offset)
992 {
993 	int error;
994 
995 	KLD_LOCK();
996 	error = linker_debug_search_symbol_name(value, buf, buflen, offset);
997 	KLD_UNLOCK();
998 	return (error);
999 }
1000 
1001 /*
1002  * Syscalls.
1003  */
1004 int
1005 kern_kldload(struct thread *td, const char *file, int *fileid)
1006 {
1007 #ifdef HWPMC_HOOKS
1008 	struct pmckern_map_in pkm;
1009 #endif
1010 	const char *kldname, *modname;
1011 	linker_file_t lf;
1012 	int error;
1013 
1014 	if ((error = securelevel_gt(td->td_ucred, 0)) != 0)
1015 		return (error);
1016 
1017 	if ((error = priv_check(td, PRIV_KLD_LOAD)) != 0)
1018 		return (error);
1019 
1020 	/*
1021 	 * It is possible that kldloaded module will attach a new ifnet,
1022 	 * so vnet context must be set when this ocurs.
1023 	 */
1024 	CURVNET_SET(TD_TO_VNET(td));
1025 
1026 	/*
1027 	 * If file does not contain a qualified name or any dot in it
1028 	 * (kldname.ko, or kldname.ver.ko) treat it as an interface
1029 	 * name.
1030 	 */
1031 	if (strchr(file, '/') || strchr(file, '.')) {
1032 		kldname = file;
1033 		modname = NULL;
1034 	} else {
1035 		kldname = NULL;
1036 		modname = file;
1037 	}
1038 
1039 	KLD_LOCK();
1040 	error = linker_load_module(kldname, modname, NULL, NULL, &lf);
1041 	if (error) {
1042 		KLD_UNLOCK();
1043 		goto done;
1044 	}
1045 	lf->userrefs++;
1046 	if (fileid != NULL)
1047 		*fileid = lf->id;
1048 
1049 	EVENTHANDLER_INVOKE(mod_load, lf);
1050 
1051 #ifdef HWPMC_HOOKS
1052 	KLD_DOWNGRADE();
1053 	pkm.pm_file = lf->filename;
1054 	pkm.pm_address = (uintptr_t) lf->address;
1055 	PMC_CALL_HOOK(td, PMC_FN_KLD_LOAD, (void *) &pkm);
1056 	KLD_UNLOCK_READ();
1057 #else
1058 	KLD_UNLOCK();
1059 #endif
1060 
1061 done:
1062 	CURVNET_RESTORE();
1063 	return (error);
1064 }
1065 
1066 int
1067 sys_kldload(struct thread *td, struct kldload_args *uap)
1068 {
1069 	char *pathname = NULL;
1070 	int error, fileid;
1071 
1072 	td->td_retval[0] = -1;
1073 
1074 	pathname = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
1075 	error = copyinstr(uap->file, pathname, MAXPATHLEN, NULL);
1076 	if (error == 0) {
1077 		error = kern_kldload(td, pathname, &fileid);
1078 		if (error == 0)
1079 			td->td_retval[0] = fileid;
1080 	}
1081 	free(pathname, M_TEMP);
1082 	return (error);
1083 }
1084 
1085 int
1086 kern_kldunload(struct thread *td, int fileid, int flags)
1087 {
1088 #ifdef HWPMC_HOOKS
1089 	struct pmckern_map_out pkm;
1090 #endif
1091 	linker_file_t lf;
1092 	int error = 0;
1093 
1094 	if ((error = securelevel_gt(td->td_ucred, 0)) != 0)
1095 		return (error);
1096 
1097 	if ((error = priv_check(td, PRIV_KLD_UNLOAD)) != 0)
1098 		return (error);
1099 
1100 	CURVNET_SET(TD_TO_VNET(td));
1101 	KLD_LOCK();
1102 	lf = linker_find_file_by_id(fileid);
1103 	if (lf) {
1104 		KLD_DPF(FILE, ("kldunload: lf->userrefs=%d\n", lf->userrefs));
1105 
1106 		EVENTHANDLER_INVOKE(mod_unload, lf, &error);
1107 		if (error != 0)
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;
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, UIO_SYSSPACE, result, td);
1730 		flags = FREAD;
1731 		error = vn_open(&nd, &flags, 0, NULL);
1732 		if (error == 0) {
1733 			NDFREE(&nd, NDF_ONLY_PNBUF);
1734 			type = nd.ni_vp->v_type;
1735 			if (vap)
1736 				VOP_GETATTR(nd.ni_vp, vap, td->td_ucred);
1737 			VOP_UNLOCK(nd.ni_vp, 0);
1738 			vn_close(nd.ni_vp, FREAD, td->td_ucred, td);
1739 			if (type == VREG)
1740 				return (result);
1741 		}
1742 	}
1743 	free(result, M_LINKER);
1744 	return (NULL);
1745 }
1746 
1747 #define	INT_ALIGN(base, ptr)	ptr =					\
1748 	(base) + (((ptr) - (base) + sizeof(int) - 1) & ~(sizeof(int) - 1))
1749 
1750 /*
1751  * Lookup KLD which contains requested module in the "linker.hints" file. If
1752  * version specification is available, then try to find the best KLD.
1753  * Otherwise just find the latest one.
1754  */
1755 static char *
1756 linker_hints_lookup(const char *path, int pathlen, const char *modname,
1757     int modnamelen, struct mod_depend *verinfo)
1758 {
1759 	struct thread *td = curthread;	/* XXX */
1760 	struct ucred *cred = td ? td->td_ucred : NULL;
1761 	struct nameidata nd;
1762 	struct vattr vattr, mattr;
1763 	u_char *hints = NULL;
1764 	u_char *cp, *recptr, *bufend, *result, *best, *pathbuf, *sep;
1765 	int error, ival, bestver, *intp, found, flags, clen, blen;
1766 	ssize_t reclen;
1767 
1768 	result = NULL;
1769 	bestver = found = 0;
1770 
1771 	sep = (path[pathlen - 1] != '/') ? "/" : "";
1772 	reclen = imax(modnamelen, strlen(linker_hintfile)) + pathlen +
1773 	    strlen(sep) + 1;
1774 	pathbuf = malloc(reclen, M_LINKER, M_WAITOK);
1775 	snprintf(pathbuf, reclen, "%.*s%s%s", pathlen, path, sep,
1776 	    linker_hintfile);
1777 
1778 	NDINIT(&nd, LOOKUP, NOFOLLOW, UIO_SYSSPACE, pathbuf, td);
1779 	flags = FREAD;
1780 	error = vn_open(&nd, &flags, 0, NULL);
1781 	if (error)
1782 		goto bad;
1783 	NDFREE(&nd, NDF_ONLY_PNBUF);
1784 	if (nd.ni_vp->v_type != VREG)
1785 		goto bad;
1786 	best = cp = NULL;
1787 	error = VOP_GETATTR(nd.ni_vp, &vattr, cred);
1788 	if (error)
1789 		goto bad;
1790 	/*
1791 	 * XXX: we need to limit this number to some reasonable value
1792 	 */
1793 	if (vattr.va_size > 100 * 1024) {
1794 		printf("hints file too large %ld\n", (long)vattr.va_size);
1795 		goto bad;
1796 	}
1797 	hints = malloc(vattr.va_size, M_TEMP, M_WAITOK);
1798 	if (hints == NULL)
1799 		goto bad;
1800 	error = vn_rdwr(UIO_READ, nd.ni_vp, (caddr_t)hints, vattr.va_size, 0,
1801 	    UIO_SYSSPACE, IO_NODELOCKED, cred, NOCRED, &reclen, td);
1802 	if (error)
1803 		goto bad;
1804 	VOP_UNLOCK(nd.ni_vp, 0);
1805 	vn_close(nd.ni_vp, FREAD, cred, td);
1806 	nd.ni_vp = NULL;
1807 	if (reclen != 0) {
1808 		printf("can't read %zd\n", reclen);
1809 		goto bad;
1810 	}
1811 	intp = (int *)hints;
1812 	ival = *intp++;
1813 	if (ival != LINKER_HINTS_VERSION) {
1814 		printf("hints file version mismatch %d\n", ival);
1815 		goto bad;
1816 	}
1817 	bufend = hints + vattr.va_size;
1818 	recptr = (u_char *)intp;
1819 	clen = blen = 0;
1820 	while (recptr < bufend && !found) {
1821 		intp = (int *)recptr;
1822 		reclen = *intp++;
1823 		ival = *intp++;
1824 		cp = (char *)intp;
1825 		switch (ival) {
1826 		case MDT_VERSION:
1827 			clen = *cp++;
1828 			if (clen != modnamelen || bcmp(cp, modname, clen) != 0)
1829 				break;
1830 			cp += clen;
1831 			INT_ALIGN(hints, cp);
1832 			ival = *(int *)cp;
1833 			cp += sizeof(int);
1834 			clen = *cp++;
1835 			if (verinfo == NULL ||
1836 			    ival == verinfo->md_ver_preferred) {
1837 				found = 1;
1838 				break;
1839 			}
1840 			if (ival >= verinfo->md_ver_minimum &&
1841 			    ival <= verinfo->md_ver_maximum &&
1842 			    ival > bestver) {
1843 				bestver = ival;
1844 				best = cp;
1845 				blen = clen;
1846 			}
1847 			break;
1848 		default:
1849 			break;
1850 		}
1851 		recptr += reclen + sizeof(int);
1852 	}
1853 	/*
1854 	 * Finally check if KLD is in the place
1855 	 */
1856 	if (found)
1857 		result = linker_lookup_file(path, pathlen, cp, clen, &mattr);
1858 	else if (best)
1859 		result = linker_lookup_file(path, pathlen, best, blen, &mattr);
1860 
1861 	/*
1862 	 * KLD is newer than hints file. What we should do now?
1863 	 */
1864 	if (result && timespeccmp(&mattr.va_mtime, &vattr.va_mtime, >))
1865 		printf("warning: KLD '%s' is newer than the linker.hints"
1866 		    " file\n", result);
1867 bad:
1868 	free(pathbuf, M_LINKER);
1869 	if (hints)
1870 		free(hints, M_TEMP);
1871 	if (nd.ni_vp != NULL) {
1872 		VOP_UNLOCK(nd.ni_vp, 0);
1873 		vn_close(nd.ni_vp, FREAD, cred, td);
1874 	}
1875 	/*
1876 	 * If nothing found or hints is absent - fallback to the old
1877 	 * way by using "kldname[.ko]" as module name.
1878 	 */
1879 	if (!found && !bestver && result == NULL)
1880 		result = linker_lookup_file(path, pathlen, modname,
1881 		    modnamelen, NULL);
1882 	return (result);
1883 }
1884 
1885 /*
1886  * Lookup KLD which contains requested module in the all directories.
1887  */
1888 static char *
1889 linker_search_module(const char *modname, int modnamelen,
1890     struct mod_depend *verinfo)
1891 {
1892 	char *cp, *ep, *result;
1893 
1894 	/*
1895 	 * traverse the linker path
1896 	 */
1897 	for (cp = linker_path; *cp; cp = ep + 1) {
1898 		/* find the end of this component */
1899 		for (ep = cp; (*ep != 0) && (*ep != ';'); ep++);
1900 		result = linker_hints_lookup(cp, ep - cp, modname,
1901 		    modnamelen, verinfo);
1902 		if (result != NULL)
1903 			return (result);
1904 		if (*ep == 0)
1905 			break;
1906 	}
1907 	return (NULL);
1908 }
1909 
1910 /*
1911  * Search for module in all directories listed in the linker_path.
1912  */
1913 static char *
1914 linker_search_kld(const char *name)
1915 {
1916 	char *cp, *ep, *result;
1917 	int len;
1918 
1919 	/* qualified at all? */
1920 	if (strchr(name, '/'))
1921 		return (linker_strdup(name));
1922 
1923 	/* traverse the linker path */
1924 	len = strlen(name);
1925 	for (ep = linker_path; *ep; ep++) {
1926 		cp = ep;
1927 		/* find the end of this component */
1928 		for (; *ep != 0 && *ep != ';'; ep++);
1929 		result = linker_lookup_file(cp, ep - cp, name, len, NULL);
1930 		if (result != NULL)
1931 			return (result);
1932 	}
1933 	return (NULL);
1934 }
1935 
1936 static const char *
1937 linker_basename(const char *path)
1938 {
1939 	const char *filename;
1940 
1941 	filename = strrchr(path, '/');
1942 	if (filename == NULL)
1943 		return path;
1944 	if (filename[1])
1945 		filename++;
1946 	return (filename);
1947 }
1948 
1949 #ifdef HWPMC_HOOKS
1950 /*
1951  * Inform hwpmc about the set of kernel modules currently loaded.
1952  */
1953 void *
1954 linker_hwpmc_list_objects(void)
1955 {
1956 	linker_file_t lf;
1957 	struct pmckern_map_in *kobase;
1958 	int i, nmappings;
1959 
1960 	nmappings = 0;
1961 	KLD_LOCK_READ();
1962 	TAILQ_FOREACH(lf, &linker_files, link)
1963 		nmappings++;
1964 
1965 	/* Allocate nmappings + 1 entries. */
1966 	kobase = malloc((nmappings + 1) * sizeof(struct pmckern_map_in),
1967 	    M_LINKER, M_WAITOK | M_ZERO);
1968 	i = 0;
1969 	TAILQ_FOREACH(lf, &linker_files, link) {
1970 
1971 		/* Save the info for this linker file. */
1972 		kobase[i].pm_file = lf->filename;
1973 		kobase[i].pm_address = (uintptr_t)lf->address;
1974 		i++;
1975 	}
1976 	KLD_UNLOCK_READ();
1977 
1978 	KASSERT(i > 0, ("linker_hpwmc_list_objects: no kernel objects?"));
1979 
1980 	/* The last entry of the malloced area comprises of all zeros. */
1981 	KASSERT(kobase[i].pm_file == NULL,
1982 	    ("linker_hwpmc_list_objects: last object not NULL"));
1983 
1984 	return ((void *)kobase);
1985 }
1986 #endif
1987 
1988 /*
1989  * Find a file which contains given module and load it, if "parent" is not
1990  * NULL, register a reference to it.
1991  */
1992 static int
1993 linker_load_module(const char *kldname, const char *modname,
1994     struct linker_file *parent, struct mod_depend *verinfo,
1995     struct linker_file **lfpp)
1996 {
1997 	linker_file_t lfdep;
1998 	const char *filename;
1999 	char *pathname;
2000 	int error;
2001 
2002 	KLD_LOCK_ASSERT();
2003 	if (modname == NULL) {
2004 		/*
2005  		 * We have to load KLD
2006  		 */
2007 		KASSERT(verinfo == NULL, ("linker_load_module: verinfo"
2008 		    " is not NULL"));
2009 		pathname = linker_search_kld(kldname);
2010 	} else {
2011 		if (modlist_lookup2(modname, verinfo) != NULL)
2012 			return (EEXIST);
2013 		if (kldname != NULL)
2014 			pathname = linker_strdup(kldname);
2015 		else if (rootvnode == NULL)
2016 			pathname = NULL;
2017 		else
2018 			/*
2019 			 * Need to find a KLD with required module
2020 			 */
2021 			pathname = linker_search_module(modname,
2022 			    strlen(modname), verinfo);
2023 	}
2024 	if (pathname == NULL)
2025 		return (ENOENT);
2026 
2027 	/*
2028 	 * Can't load more than one file with the same basename XXX:
2029 	 * Actually it should be possible to have multiple KLDs with
2030 	 * the same basename but different path because they can
2031 	 * provide different versions of the same modules.
2032 	 */
2033 	filename = linker_basename(pathname);
2034 	if (linker_find_file_by_name(filename))
2035 		error = EEXIST;
2036 	else do {
2037 		error = linker_load_file(pathname, &lfdep);
2038 		if (error)
2039 			break;
2040 		if (modname && verinfo &&
2041 		    modlist_lookup2(modname, verinfo) == NULL) {
2042 			linker_file_unload(lfdep, LINKER_UNLOAD_FORCE);
2043 			error = ENOENT;
2044 			break;
2045 		}
2046 		if (parent) {
2047 			error = linker_file_add_dependency(parent, lfdep);
2048 			if (error)
2049 				break;
2050 		}
2051 		if (lfpp)
2052 			*lfpp = lfdep;
2053 	} while (0);
2054 	free(pathname, M_LINKER);
2055 	return (error);
2056 }
2057 
2058 /*
2059  * This routine is responsible for finding dependencies of userland initiated
2060  * kldload(2)'s of files.
2061  */
2062 int
2063 linker_load_dependencies(linker_file_t lf)
2064 {
2065 	linker_file_t lfdep;
2066 	struct mod_metadata **start, **stop, **mdp, **nmdp;
2067 	struct mod_metadata *mp, *nmp;
2068 	struct mod_depend *verinfo;
2069 	modlist_t mod;
2070 	const char *modname, *nmodname;
2071 	int ver, error = 0, count;
2072 
2073 	/*
2074 	 * All files are dependant on /kernel.
2075 	 */
2076 	KLD_LOCK_ASSERT();
2077 	if (linker_kernel_file) {
2078 		linker_kernel_file->refs++;
2079 		error = linker_file_add_dependency(lf, linker_kernel_file);
2080 		if (error)
2081 			return (error);
2082 	}
2083 	if (linker_file_lookup_set(lf, MDT_SETNAME, &start, &stop,
2084 	    &count) != 0)
2085 		return (0);
2086 	for (mdp = start; mdp < stop; mdp++) {
2087 		mp = *mdp;
2088 		if (mp->md_type != MDT_VERSION)
2089 			continue;
2090 		modname = mp->md_cval;
2091 		ver = ((struct mod_version *)mp->md_data)->mv_version;
2092 		mod = modlist_lookup(modname, ver);
2093 		if (mod != NULL) {
2094 			printf("interface %s.%d already present in the KLD"
2095 			    " '%s'!\n", modname, ver,
2096 			    mod->container->filename);
2097 			return (EEXIST);
2098 		}
2099 	}
2100 
2101 	for (mdp = start; mdp < stop; mdp++) {
2102 		mp = *mdp;
2103 		if (mp->md_type != MDT_DEPEND)
2104 			continue;
2105 		modname = mp->md_cval;
2106 		verinfo = mp->md_data;
2107 		nmodname = NULL;
2108 		for (nmdp = start; nmdp < stop; nmdp++) {
2109 			nmp = *nmdp;
2110 			if (nmp->md_type != MDT_VERSION)
2111 				continue;
2112 			nmodname = nmp->md_cval;
2113 			if (strcmp(modname, nmodname) == 0)
2114 				break;
2115 		}
2116 		if (nmdp < stop)/* early exit, it's a self reference */
2117 			continue;
2118 		mod = modlist_lookup2(modname, verinfo);
2119 		if (mod) {	/* woohoo, it's loaded already */
2120 			lfdep = mod->container;
2121 			lfdep->refs++;
2122 			error = linker_file_add_dependency(lf, lfdep);
2123 			if (error)
2124 				break;
2125 			continue;
2126 		}
2127 		error = linker_load_module(NULL, modname, lf, verinfo, NULL);
2128 		if (error) {
2129 			printf("KLD %s: depends on %s - not available or"
2130 			    " version mismatch\n", lf->filename, modname);
2131 			break;
2132 		}
2133 	}
2134 
2135 	if (error)
2136 		return (error);
2137 	linker_addmodules(lf, start, stop, 0);
2138 	return (error);
2139 }
2140 
2141 static int
2142 sysctl_kern_function_list_iterate(const char *name, void *opaque)
2143 {
2144 	struct sysctl_req *req;
2145 
2146 	req = opaque;
2147 	return (SYSCTL_OUT(req, name, strlen(name) + 1));
2148 }
2149 
2150 /*
2151  * Export a nul-separated, double-nul-terminated list of all function names
2152  * in the kernel.
2153  */
2154 static int
2155 sysctl_kern_function_list(SYSCTL_HANDLER_ARGS)
2156 {
2157 	linker_file_t lf;
2158 	int error;
2159 
2160 #ifdef MAC
2161 	error = mac_kld_check_stat(req->td->td_ucred);
2162 	if (error)
2163 		return (error);
2164 #endif
2165 	error = sysctl_wire_old_buffer(req, 0);
2166 	if (error != 0)
2167 		return (error);
2168 	KLD_LOCK();
2169 	TAILQ_FOREACH(lf, &linker_files, link) {
2170 		error = LINKER_EACH_FUNCTION_NAME(lf,
2171 		    sysctl_kern_function_list_iterate, req);
2172 		if (error) {
2173 			KLD_UNLOCK();
2174 			return (error);
2175 		}
2176 	}
2177 	KLD_UNLOCK();
2178 	return (SYSCTL_OUT(req, "", 1));
2179 }
2180 
2181 SYSCTL_PROC(_kern, OID_AUTO, function_list, CTLTYPE_OPAQUE | CTLFLAG_RD,
2182     NULL, 0, sysctl_kern_function_list, "", "kernel function list");
2183