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