xref: /freebsd/sys/kern/kern_linker.c (revision db33c6f3ae9d1231087710068ee4ea5398aacca7)
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 	if (vattr.va_size < sizeof(ival)) {
2034 		printf("linker.hints file truncated\n");
2035 		goto bad;
2036 	}
2037 	hints = malloc(vattr.va_size, M_TEMP, M_WAITOK);
2038 	error = vn_rdwr(UIO_READ, nd.ni_vp, (caddr_t)hints, vattr.va_size, 0,
2039 	    UIO_SYSSPACE, IO_NODELOCKED, cred, NOCRED, &reclen, td);
2040 	if (error)
2041 		goto bad;
2042 	VOP_UNLOCK(nd.ni_vp);
2043 	vn_close(nd.ni_vp, FREAD, cred, td);
2044 	nd.ni_vp = NULL;
2045 	if (reclen != 0) {
2046 		printf("can't read %zd\n", reclen);
2047 		goto bad;
2048 	}
2049 	intp = (int *)hints;
2050 	ival = *intp++;
2051 	if (ival != LINKER_HINTS_VERSION) {
2052 		printf("linker.hints file version mismatch %d\n", ival);
2053 		goto bad;
2054 	}
2055 	bufend = hints + vattr.va_size;
2056 	recptr = (u_char *)intp;
2057 	clen = blen = 0;
2058 	while (recptr < bufend && !found) {
2059 		intp = (int *)recptr;
2060 		reclen = *intp++;
2061 		ival = *intp++;
2062 		cp = (char *)intp;
2063 		switch (ival) {
2064 		case MDT_VERSION:
2065 			clen = *cp++;
2066 			if (clen != modnamelen || bcmp(cp, modname, clen) != 0)
2067 				break;
2068 			cp += clen;
2069 			INT_ALIGN(hints, cp);
2070 			ival = *(int *)cp;
2071 			cp += sizeof(int);
2072 			clen = *cp++;
2073 			if (verinfo == NULL ||
2074 			    ival == verinfo->md_ver_preferred) {
2075 				found = 1;
2076 				break;
2077 			}
2078 			if (ival >= verinfo->md_ver_minimum &&
2079 			    ival <= verinfo->md_ver_maximum &&
2080 			    ival > bestver) {
2081 				bestver = ival;
2082 				best = cp;
2083 				blen = clen;
2084 			}
2085 			break;
2086 		default:
2087 			break;
2088 		}
2089 		recptr += reclen + sizeof(int);
2090 	}
2091 	/*
2092 	 * Finally check if KLD is in the place
2093 	 */
2094 	if (found)
2095 		result = linker_lookup_file(path, pathlen, cp, clen, &mattr);
2096 	else if (best)
2097 		result = linker_lookup_file(path, pathlen, best, blen, &mattr);
2098 
2099 	/*
2100 	 * KLD is newer than hints file. What we should do now?
2101 	 */
2102 	if (result && timespeccmp(&mattr.va_mtime, &vattr.va_mtime, >))
2103 		printf("warning: KLD '%s' is newer than the linker.hints"
2104 		    " file\n", result);
2105 bad:
2106 	free(pathbuf, M_LINKER);
2107 	if (hints)
2108 		free(hints, M_TEMP);
2109 	if (nd.ni_vp != NULL) {
2110 		VOP_UNLOCK(nd.ni_vp);
2111 		vn_close(nd.ni_vp, FREAD, cred, td);
2112 	}
2113 	/*
2114 	 * If nothing found or hints is absent - fallback to the old
2115 	 * way by using "kldname[.ko]" as module name.
2116 	 */
2117 	if (!found && !bestver && result == NULL)
2118 		result = linker_lookup_file(path, pathlen, modname,
2119 		    modnamelen, NULL);
2120 	return (result);
2121 }
2122 
2123 /*
2124  * Lookup KLD which contains requested module in the all directories.
2125  */
2126 static char *
2127 linker_search_module(const char *modname, int modnamelen,
2128     const struct mod_depend *verinfo)
2129 {
2130 	char *cp, *ep, *result;
2131 
2132 	/*
2133 	 * traverse the linker path
2134 	 */
2135 	for (cp = linker_path; *cp; cp = ep + 1) {
2136 		/* find the end of this component */
2137 		for (ep = cp; (*ep != 0) && (*ep != ';'); ep++);
2138 		result = linker_hints_lookup(cp, ep - cp, modname,
2139 		    modnamelen, verinfo);
2140 		if (result != NULL)
2141 			return (result);
2142 		if (*ep == 0)
2143 			break;
2144 	}
2145 	return (NULL);
2146 }
2147 
2148 /*
2149  * Search for module in all directories listed in the linker_path.
2150  */
2151 static char *
2152 linker_search_kld(const char *name)
2153 {
2154 	char *cp, *ep, *result;
2155 	int len;
2156 
2157 	/* qualified at all? */
2158 	if (strchr(name, '/'))
2159 		return (strdup(name, M_LINKER));
2160 
2161 	/* traverse the linker path */
2162 	len = strlen(name);
2163 	for (ep = linker_path; *ep; ep++) {
2164 		cp = ep;
2165 		/* find the end of this component */
2166 		for (; *ep != 0 && *ep != ';'; ep++);
2167 		result = linker_lookup_file(cp, ep - cp, name, len, NULL);
2168 		if (result != NULL)
2169 			return (result);
2170 	}
2171 	return (NULL);
2172 }
2173 
2174 static const char *
2175 linker_basename(const char *path)
2176 {
2177 	const char *filename;
2178 
2179 	filename = strrchr(path, '/');
2180 	if (filename == NULL)
2181 		return path;
2182 	if (filename[1])
2183 		filename++;
2184 	return (filename);
2185 }
2186 
2187 #ifdef HWPMC_HOOKS
2188 /*
2189  * Inform hwpmc about the set of kernel modules currently loaded.
2190  */
2191 void *
2192 linker_hwpmc_list_objects(void)
2193 {
2194 	linker_file_t lf;
2195 	struct pmckern_map_in *kobase;
2196 	int i, nmappings;
2197 
2198 	nmappings = 0;
2199 	sx_slock(&kld_sx);
2200 	TAILQ_FOREACH(lf, &linker_files, link)
2201 		nmappings++;
2202 
2203 	/* Allocate nmappings + 1 entries. */
2204 	kobase = malloc((nmappings + 1) * sizeof(struct pmckern_map_in),
2205 	    M_LINKER, M_WAITOK | M_ZERO);
2206 	i = 0;
2207 	TAILQ_FOREACH(lf, &linker_files, link) {
2208 		/* Save the info for this linker file. */
2209 		kobase[i].pm_file = lf->pathname;
2210 		kobase[i].pm_address = (uintptr_t)lf->address;
2211 		i++;
2212 	}
2213 	sx_sunlock(&kld_sx);
2214 
2215 	KASSERT(i > 0, ("linker_hpwmc_list_objects: no kernel objects?"));
2216 
2217 	/* The last entry of the malloced area comprises of all zeros. */
2218 	KASSERT(kobase[i].pm_file == NULL,
2219 	    ("linker_hwpmc_list_objects: last object not NULL"));
2220 
2221 	return ((void *)kobase);
2222 }
2223 #endif
2224 
2225 /* check if root file system is not mounted */
2226 static bool
2227 linker_root_mounted(void)
2228 {
2229 	struct pwd *pwd;
2230 	bool ret;
2231 
2232 	if (rootvnode == NULL)
2233 		return (false);
2234 
2235 	pwd = pwd_hold(curthread);
2236 	ret = pwd->pwd_rdir != NULL;
2237 	pwd_drop(pwd);
2238 	return (ret);
2239 }
2240 
2241 /*
2242  * Find a file which contains given module and load it, if "parent" is not
2243  * NULL, register a reference to it.
2244  */
2245 static int
2246 linker_load_module(const char *kldname, const char *modname,
2247     struct linker_file *parent, const struct mod_depend *verinfo,
2248     struct linker_file **lfpp)
2249 {
2250 	linker_file_t lfdep;
2251 	const char *filename;
2252 	char *pathname;
2253 	int error;
2254 
2255 	sx_assert(&kld_sx, SA_XLOCKED);
2256 	if (modname == NULL) {
2257 		/*
2258  		 * We have to load KLD
2259  		 */
2260 		KASSERT(verinfo == NULL, ("linker_load_module: verinfo"
2261 		    " is not NULL"));
2262 		if (!linker_root_mounted())
2263 			return (ENXIO);
2264 		pathname = linker_search_kld(kldname);
2265 	} else {
2266 		if (modlist_lookup2(modname, verinfo) != NULL)
2267 			return (EEXIST);
2268 		if (!linker_root_mounted())
2269 			return (ENXIO);
2270 		if (kldname != NULL)
2271 			pathname = strdup(kldname, M_LINKER);
2272 		else
2273 			/*
2274 			 * Need to find a KLD with required module
2275 			 */
2276 			pathname = linker_search_module(modname,
2277 			    strlen(modname), verinfo);
2278 	}
2279 	if (pathname == NULL)
2280 		return (ENOENT);
2281 
2282 	/*
2283 	 * Can't load more than one file with the same basename XXX:
2284 	 * Actually it should be possible to have multiple KLDs with
2285 	 * the same basename but different path because they can
2286 	 * provide different versions of the same modules.
2287 	 */
2288 	filename = linker_basename(pathname);
2289 	if (linker_find_file_by_name(filename))
2290 		error = EEXIST;
2291 	else do {
2292 		error = linker_load_file(pathname, &lfdep);
2293 		if (error)
2294 			break;
2295 		if (modname && verinfo &&
2296 		    modlist_lookup2(modname, verinfo) == NULL) {
2297 			linker_file_unload(lfdep, LINKER_UNLOAD_FORCE);
2298 			error = ENOENT;
2299 			break;
2300 		}
2301 		if (parent)
2302 			linker_file_add_dependency(parent, lfdep);
2303 		if (lfpp)
2304 			*lfpp = lfdep;
2305 	} while (0);
2306 	free(pathname, M_LINKER);
2307 	return (error);
2308 }
2309 
2310 /*
2311  * This routine is responsible for finding dependencies of userland initiated
2312  * kldload(2)'s of files.
2313  */
2314 int
2315 linker_load_dependencies(linker_file_t lf)
2316 {
2317 	linker_file_t lfdep;
2318 	struct mod_metadata **start, **stop, **mdp, **nmdp;
2319 	struct mod_metadata *mp, *nmp;
2320 	const struct mod_depend *verinfo;
2321 	modlist_t mod;
2322 	const char *modname, *nmodname;
2323 	int ver, error = 0;
2324 
2325 	/*
2326 	 * All files are dependent on /kernel.
2327 	 */
2328 	sx_assert(&kld_sx, SA_XLOCKED);
2329 	if (linker_kernel_file) {
2330 		linker_kernel_file->refs++;
2331 		linker_file_add_dependency(lf, linker_kernel_file);
2332 	}
2333 	if (linker_file_lookup_set(lf, MDT_SETNAME, &start, &stop,
2334 	    NULL) != 0)
2335 		return (0);
2336 	for (mdp = start; mdp < stop; mdp++) {
2337 		mp = *mdp;
2338 		if (mp->md_type != MDT_VERSION)
2339 			continue;
2340 		modname = mp->md_cval;
2341 		ver = ((const struct mod_version *)mp->md_data)->mv_version;
2342 		mod = modlist_lookup(modname, ver);
2343 		if (mod != NULL) {
2344 			printf("interface %s.%d already present in the KLD"
2345 			    " '%s'!\n", modname, ver,
2346 			    mod->container->filename);
2347 			return (EEXIST);
2348 		}
2349 	}
2350 
2351 	for (mdp = start; mdp < stop; mdp++) {
2352 		mp = *mdp;
2353 		if (mp->md_type != MDT_DEPEND)
2354 			continue;
2355 		modname = mp->md_cval;
2356 		verinfo = mp->md_data;
2357 		nmodname = NULL;
2358 		for (nmdp = start; nmdp < stop; nmdp++) {
2359 			nmp = *nmdp;
2360 			if (nmp->md_type != MDT_VERSION)
2361 				continue;
2362 			nmodname = nmp->md_cval;
2363 			if (strcmp(modname, nmodname) == 0)
2364 				break;
2365 		}
2366 		if (nmdp < stop)/* early exit, it's a self reference */
2367 			continue;
2368 		mod = modlist_lookup2(modname, verinfo);
2369 		if (mod) {	/* woohoo, it's loaded already */
2370 			lfdep = mod->container;
2371 			lfdep->refs++;
2372 			linker_file_add_dependency(lf, lfdep);
2373 			continue;
2374 		}
2375 		error = linker_load_module(NULL, modname, lf, verinfo, NULL);
2376 		if (error) {
2377 			printf("KLD %s: depends on %s - not available or"
2378 			    " version mismatch\n", lf->filename, modname);
2379 			break;
2380 		}
2381 	}
2382 
2383 	if (error)
2384 		return (error);
2385 	linker_addmodules(lf, start, stop, 0);
2386 	return (error);
2387 }
2388 
2389 static int
2390 sysctl_kern_function_list_iterate(const char *name, void *opaque)
2391 {
2392 	struct sysctl_req *req;
2393 
2394 	req = opaque;
2395 	return (SYSCTL_OUT(req, name, strlen(name) + 1));
2396 }
2397 
2398 /*
2399  * Export a nul-separated, double-nul-terminated list of all function names
2400  * in the kernel.
2401  */
2402 static int
2403 sysctl_kern_function_list(SYSCTL_HANDLER_ARGS)
2404 {
2405 	linker_file_t lf;
2406 	int error;
2407 
2408 #ifdef MAC
2409 	error = mac_kld_check_stat(req->td->td_ucred);
2410 	if (error)
2411 		return (error);
2412 #endif
2413 	error = sysctl_wire_old_buffer(req, 0);
2414 	if (error != 0)
2415 		return (error);
2416 	sx_xlock(&kld_sx);
2417 	TAILQ_FOREACH(lf, &linker_files, link) {
2418 		error = LINKER_EACH_FUNCTION_NAME(lf,
2419 		    sysctl_kern_function_list_iterate, req);
2420 		if (error) {
2421 			sx_xunlock(&kld_sx);
2422 			return (error);
2423 		}
2424 	}
2425 	sx_xunlock(&kld_sx);
2426 	return (SYSCTL_OUT(req, "", 1));
2427 }
2428 
2429 SYSCTL_PROC(_kern, OID_AUTO, function_list,
2430     CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0,
2431     sysctl_kern_function_list, "",
2432     "kernel function list");
2433