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