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