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