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