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