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