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