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