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