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