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