kern_linker.c revision 159588
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 159588 2006-06-13 21:28:18Z 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	lf = NULL;
349	foundfile = 0;
350	error = 0;
351
352	/*
353	 * We do not need to protect (lock) classes here because there is
354	 * no class registration past startup (SI_SUB_KLD, SI_ORDER_ANY)
355	 * and there is no class deregistration mechanism at this time.
356	 */
357	TAILQ_FOREACH(lc, &classes, link) {
358		KLD_DPF(FILE, ("linker_load_file: trying to load %s\n",
359		    filename));
360		error = LINKER_LOAD_FILE(lc, filename, &lf);
361		/*
362		 * If we got something other than ENOENT, then it exists but
363		 * we cannot load it for some other reason.
364		 */
365		if (error != ENOENT)
366			foundfile = 1;
367		if (lf) {
368			error = linker_file_register_modules(lf);
369			if (error == EEXIST) {
370				linker_file_unload(lf, LINKER_UNLOAD_FORCE);
371				return (error);
372			}
373			linker_file_register_sysctls(lf);
374			linker_file_sysinit(lf);
375			lf->flags |= LINKER_FILE_LINKED;
376			*result = lf;
377			return (0);
378		}
379	}
380	/*
381	 * Less than ideal, but tells the user whether it failed to load or
382	 * the module was not found.
383	 */
384	if (foundfile) {
385		/*
386		 * Format not recognized or otherwise unloadable.
387		 * When loading a module that is statically built into
388		 * the kernel EEXIST percolates back up as the return
389		 * value.  Preserve this so that apps like sysinstall
390		 * can recognize this special case and not post bogus
391		 * dialog boxes.
392		 */
393		if (error != EEXIST)
394			error = ENOEXEC;
395	} else
396		error = ENOENT;		/* Nothing found */
397	return (error);
398}
399
400int
401linker_reference_module(const char *modname, struct mod_depend *verinfo,
402    linker_file_t *result)
403{
404	modlist_t mod;
405
406	if ((mod = modlist_lookup2(modname, verinfo)) != NULL) {
407		*result = mod->container;
408		(*result)->refs++;
409		return (0);
410	}
411
412	return (linker_load_module(NULL, modname, NULL, verinfo, result));
413}
414
415linker_file_t
416linker_find_file_by_name(const char *filename)
417{
418	linker_file_t lf;
419	char *koname;
420
421	koname = malloc(strlen(filename) + 4, M_LINKER, M_WAITOK);
422	sprintf(koname, "%s.ko", filename);
423
424	mtx_lock(&kld_mtx);
425	TAILQ_FOREACH(lf, &linker_files, link) {
426		if (strcmp(lf->filename, koname) == 0)
427			break;
428		if (strcmp(lf->filename, filename) == 0)
429			break;
430	}
431	mtx_unlock(&kld_mtx);
432	free(koname, M_LINKER);
433	return (lf);
434}
435
436linker_file_t
437linker_find_file_by_id(int fileid)
438{
439	linker_file_t lf;
440
441	mtx_lock(&kld_mtx);
442	TAILQ_FOREACH(lf, &linker_files, link)
443		if (lf->id == fileid)
444			break;
445	mtx_unlock(&kld_mtx);
446	return (lf);
447}
448
449linker_file_t
450linker_make_file(const char *pathname, linker_class_t lc)
451{
452	linker_file_t lf;
453	const char *filename;
454
455	filename = linker_basename(pathname);
456
457	KLD_DPF(FILE, ("linker_make_file: new file, filename=%s\n", filename));
458	lf = (linker_file_t)kobj_create((kobj_class_t)lc, M_LINKER, M_WAITOK);
459	if (lf == NULL)
460		return (NULL);
461	lf->refs = 1;
462	lf->userrefs = 0;
463	lf->flags = 0;
464	lf->filename = linker_strdup(filename);
465	LINKER_GET_NEXT_FILE_ID(lf->id);
466	lf->ndeps = 0;
467	lf->deps = NULL;
468	STAILQ_INIT(&lf->common);
469	TAILQ_INIT(&lf->modules);
470	mtx_lock(&kld_mtx);
471	TAILQ_INSERT_TAIL(&linker_files, lf, link);
472	mtx_unlock(&kld_mtx);
473	return (lf);
474}
475
476int
477linker_file_unload(linker_file_t file, int flags)
478{
479	module_t mod, next;
480	modlist_t ml, nextml;
481	struct common_symbol *cp;
482	int error, i;
483
484	/* Refuse to unload modules if securelevel raised. */
485	if (securelevel > 0)
486		return (EPERM);
487#ifdef MAC
488	error = mac_check_kld_unload(curthread->td_ucred);
489	if (error)
490		return (error);
491#endif
492
493	KLD_DPF(FILE, ("linker_file_unload: lf->refs=%d\n", file->refs));
494
495	/* Easy case of just dropping a reference. */
496	if (file->refs > 1) {
497		file->refs--;
498		return (0);
499	}
500
501	KLD_DPF(FILE, ("linker_file_unload: file is unloading,"
502	    " informing modules\n"));
503
504	/*
505	 * Inform any modules associated with this file.
506	 */
507	MOD_XLOCK;
508	for (mod = TAILQ_FIRST(&file->modules); mod; mod = next) {
509		next = module_getfnext(mod);
510		MOD_XUNLOCK;
511
512		/*
513		 * Give the module a chance to veto the unload.
514		 */
515		if ((error = module_unload(mod, flags)) != 0) {
516			KLD_DPF(FILE, ("linker_file_unload: module %p"
517			    " vetoes unload\n", mod));
518			return (error);
519		}
520		MOD_XLOCK;
521		module_release(mod);
522	}
523	MOD_XUNLOCK;
524
525	TAILQ_FOREACH_SAFE(ml, &found_modules, link, nextml) {
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
749kern_kldload(struct thread *td, const char *file, int *fileid)
750{
751#ifdef HWPMC_HOOKS
752	struct pmckern_map_in pkm;
753#endif
754	const char *kldname, *modname;
755	linker_file_t lf;
756	int error;
757
758	if ((error = securelevel_gt(td->td_ucred, 0)) != 0)
759		return (error);
760
761	if ((error = suser(td)) != 0)
762		return (error);
763
764	/*
765	 * If file does not contain qualified name or any dot in it
766	 * (kldname.ko, or kldname.ver.ko) treat it as interface
767	 * name.
768	 */
769	if (index(file, '/') || index(file, '.')) {
770		kldname = file;
771		modname = NULL;
772	} else {
773		kldname = NULL;
774		modname = file;
775	}
776
777	mtx_lock(&Giant);
778	error = linker_load_module(kldname, modname, NULL, NULL, &lf);
779	if (error)
780		goto unlock;
781
782#ifdef HWPMC_HOOKS
783	pkm.pm_file = lf->filename;
784	pkm.pm_address = (uintptr_t) lf->address;
785	PMC_CALL_HOOK(td, PMC_FN_KLD_LOAD, (void *) &pkm);
786#endif
787	lf->userrefs++;
788	if (fileid != NULL)
789		*fileid = lf->id;
790unlock:
791	mtx_unlock(&Giant);
792	return (error);
793}
794
795int
796kldload(struct thread *td, struct kldload_args *uap)
797{
798	char *pathname = NULL;
799	int error;
800
801	td->td_retval[0] = -1;
802
803	pathname = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
804	error = copyinstr(uap->file, pathname, MAXPATHLEN, NULL);
805	if (error == 0)
806		error = kern_kldload(td, pathname, &td->td_retval[0]);
807
808	free(pathname, M_TEMP);
809	return (error);
810}
811
812/*
813 * MPSAFE
814 */
815int
816kern_kldunload(struct thread *td, int fileid, int flags)
817{
818#ifdef HWPMC_HOOKS
819	struct pmckern_map_out pkm;
820#endif
821	linker_file_t lf;
822	int error = 0;
823
824	if ((error = securelevel_gt(td->td_ucred, 0)) != 0)
825		return (error);
826
827	if ((error = suser(td)) != 0)
828		return (error);
829
830	mtx_lock(&Giant);
831	lf = linker_find_file_by_id(fileid);
832	if (lf) {
833		KLD_DPF(FILE, ("kldunload: lf->userrefs=%d\n", lf->userrefs));
834		if (lf->userrefs == 0) {
835			/*
836			 * XXX: maybe LINKER_UNLOAD_FORCE should override ?
837			 */
838			printf("kldunload: attempt to unload file that was"
839			    " loaded by the kernel\n");
840			error = EBUSY;
841		} else {
842#ifdef HWPMC_HOOKS
843			/* Save data needed by hwpmc(4) before unloading. */
844			pkm.pm_address = (uintptr_t) lf->address;
845			pkm.pm_size = lf->size;
846#endif
847			lf->userrefs--;
848			error = linker_file_unload(lf, flags);
849			if (error)
850				lf->userrefs++;
851		}
852	} else
853		error = ENOENT;
854
855#ifdef HWPMC_HOOKS
856	if (error == 0)
857		PMC_CALL_HOOK(td, PMC_FN_KLD_UNLOAD, (void *) &pkm);
858#endif
859	mtx_unlock(&Giant);
860	return (error);
861}
862
863/*
864 * MPSAFE
865 */
866int
867kldunload(struct thread *td, struct kldunload_args *uap)
868{
869
870	return (kern_kldunload(td, uap->fileid, LINKER_UNLOAD_NORMAL));
871}
872
873/*
874 * MPSAFE
875 */
876int
877kldunloadf(struct thread *td, struct kldunloadf_args *uap)
878{
879
880	if (uap->flags != LINKER_UNLOAD_NORMAL &&
881	    uap->flags != LINKER_UNLOAD_FORCE)
882		return (EINVAL);
883	return (kern_kldunload(td, uap->fileid, uap->flags));
884}
885
886/*
887 * MPSAFE
888 */
889int
890kldfind(struct thread *td, struct kldfind_args *uap)
891{
892	char *pathname;
893	const char *filename;
894	linker_file_t lf;
895	int error = 0;
896
897#ifdef MAC
898	error = mac_check_kld_stat(td->td_ucred);
899	if (error)
900		return (error);
901#endif
902
903	mtx_lock(&Giant);
904	td->td_retval[0] = -1;
905
906	pathname = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
907	if ((error = copyinstr(uap->file, pathname, MAXPATHLEN, NULL)) != 0)
908		goto out;
909
910	filename = linker_basename(pathname);
911	lf = linker_find_file_by_name(filename);
912	if (lf)
913		td->td_retval[0] = lf->id;
914	else
915		error = ENOENT;
916out:
917	if (pathname)
918		free(pathname, M_TEMP);
919	mtx_unlock(&Giant);
920	return (error);
921}
922
923/*
924 * MPSAFE
925 */
926int
927kldnext(struct thread *td, struct kldnext_args *uap)
928{
929	linker_file_t lf;
930	int error = 0;
931
932#ifdef MAC
933	error = mac_check_kld_stat(td->td_ucred);
934	if (error)
935		return (error);
936#endif
937
938	mtx_lock(&Giant);
939
940	if (uap->fileid == 0) {
941		mtx_lock(&kld_mtx);
942		if (TAILQ_FIRST(&linker_files))
943			td->td_retval[0] = TAILQ_FIRST(&linker_files)->id;
944		else
945			td->td_retval[0] = 0;
946		mtx_unlock(&kld_mtx);
947		goto out;
948	}
949	lf = linker_find_file_by_id(uap->fileid);
950	if (lf) {
951		if (TAILQ_NEXT(lf, link))
952			td->td_retval[0] = TAILQ_NEXT(lf, link)->id;
953		else
954			td->td_retval[0] = 0;
955	} else
956		error = ENOENT;
957out:
958	mtx_unlock(&Giant);
959	return (error);
960}
961
962/*
963 * MPSAFE
964 */
965int
966kldstat(struct thread *td, struct kldstat_args *uap)
967{
968	struct kld_file_stat stat;
969	linker_file_t lf;
970	int error, namelen;
971
972	/*
973	 * Check the version of the user's structure.
974	 */
975	error = copyin(uap->stat, &stat, sizeof(struct kld_file_stat));
976	if (error)
977		return (error);
978	if (stat.version != sizeof(struct kld_file_stat))
979		return (EINVAL);
980
981#ifdef MAC
982	error = mac_check_kld_stat(td->td_ucred);
983	if (error)
984		return (error);
985#endif
986
987	mtx_lock(&Giant);
988
989	lf = linker_find_file_by_id(uap->fileid);
990	if (lf == NULL) {
991		mtx_unlock(&Giant);
992		return (ENOENT);
993	}
994
995	namelen = strlen(lf->filename) + 1;
996	if (namelen > MAXPATHLEN)
997		namelen = MAXPATHLEN;
998	bcopy(lf->filename, &stat.name[0], namelen);
999	stat.refs = lf->refs;
1000	stat.id = lf->id;
1001	stat.address = lf->address;
1002	stat.size = lf->size;
1003	mtx_unlock(&Giant);
1004
1005	td->td_retval[0] = 0;
1006
1007	return (copyout(&stat, uap->stat, sizeof(struct kld_file_stat)));
1008}
1009
1010/*
1011 * MPSAFE
1012 */
1013int
1014kldfirstmod(struct thread *td, struct kldfirstmod_args *uap)
1015{
1016	linker_file_t lf;
1017	module_t mp;
1018	int error = 0;
1019
1020#ifdef MAC
1021	error = mac_check_kld_stat(td->td_ucred);
1022	if (error)
1023		return (error);
1024#endif
1025
1026	mtx_lock(&Giant);
1027	lf = linker_find_file_by_id(uap->fileid);
1028	if (lf) {
1029		MOD_SLOCK;
1030		mp = TAILQ_FIRST(&lf->modules);
1031		if (mp != NULL)
1032			td->td_retval[0] = module_getid(mp);
1033		else
1034			td->td_retval[0] = 0;
1035		MOD_SUNLOCK;
1036	} else
1037		error = ENOENT;
1038	mtx_unlock(&Giant);
1039	return (error);
1040}
1041
1042/*
1043 * MPSAFE
1044 */
1045int
1046kldsym(struct thread *td, struct kldsym_args *uap)
1047{
1048	char *symstr = NULL;
1049	c_linker_sym_t sym;
1050	linker_symval_t symval;
1051	linker_file_t lf;
1052	struct kld_sym_lookup lookup;
1053	int error = 0;
1054
1055#ifdef MAC
1056	error = mac_check_kld_stat(td->td_ucred);
1057	if (error)
1058		return (error);
1059#endif
1060
1061	mtx_lock(&Giant);
1062
1063	if ((error = copyin(uap->data, &lookup, sizeof(lookup))) != 0)
1064		goto out;
1065	if (lookup.version != sizeof(lookup) ||
1066	    uap->cmd != KLDSYM_LOOKUP) {
1067		error = EINVAL;
1068		goto out;
1069	}
1070	symstr = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
1071	if ((error = copyinstr(lookup.symname, symstr, MAXPATHLEN, NULL)) != 0)
1072		goto out;
1073	if (uap->fileid != 0) {
1074		lf = linker_find_file_by_id(uap->fileid);
1075		if (lf == NULL) {
1076			error = ENOENT;
1077			goto out;
1078		}
1079		if (LINKER_LOOKUP_SYMBOL(lf, symstr, &sym) == 0 &&
1080		    LINKER_SYMBOL_VALUES(lf, sym, &symval) == 0) {
1081			lookup.symvalue = (uintptr_t) symval.value;
1082			lookup.symsize = symval.size;
1083			error = copyout(&lookup, uap->data, sizeof(lookup));
1084		} else
1085			error = ENOENT;
1086	} else {
1087		mtx_lock(&kld_mtx);
1088		TAILQ_FOREACH(lf, &linker_files, link) {
1089			if (LINKER_LOOKUP_SYMBOL(lf, symstr, &sym) == 0 &&
1090			    LINKER_SYMBOL_VALUES(lf, sym, &symval) == 0) {
1091				lookup.symvalue = (uintptr_t)symval.value;
1092				lookup.symsize = symval.size;
1093				error = copyout(&lookup, uap->data,
1094				    sizeof(lookup));
1095				break;
1096			}
1097		}
1098		mtx_unlock(&kld_mtx);
1099		if (lf == NULL)
1100			error = ENOENT;
1101	}
1102out:
1103	if (symstr)
1104		free(symstr, M_TEMP);
1105	mtx_unlock(&Giant);
1106	return (error);
1107}
1108
1109/*
1110 * Preloaded module support
1111 */
1112
1113static modlist_t
1114modlist_lookup(const char *name, int ver)
1115{
1116	modlist_t mod;
1117
1118	TAILQ_FOREACH(mod, &found_modules, link) {
1119		if (strcmp(mod->name, name) == 0 &&
1120		    (ver == 0 || mod->version == ver))
1121			return (mod);
1122	}
1123	return (NULL);
1124}
1125
1126static modlist_t
1127modlist_lookup2(const char *name, struct mod_depend *verinfo)
1128{
1129	modlist_t mod, bestmod;
1130	int ver;
1131
1132	if (verinfo == NULL)
1133		return (modlist_lookup(name, 0));
1134	bestmod = NULL;
1135	TAILQ_FOREACH(mod, &found_modules, link) {
1136		if (strcmp(mod->name, name) != 0)
1137			continue;
1138		ver = mod->version;
1139		if (ver == verinfo->md_ver_preferred)
1140			return (mod);
1141		if (ver >= verinfo->md_ver_minimum &&
1142		    ver <= verinfo->md_ver_maximum &&
1143		    (bestmod == NULL || ver > bestmod->version))
1144			bestmod = mod;
1145	}
1146	return (bestmod);
1147}
1148
1149static modlist_t
1150modlist_newmodule(const char *modname, int version, linker_file_t container)
1151{
1152	modlist_t mod;
1153
1154	mod = malloc(sizeof(struct modlist), M_LINKER, M_NOWAIT | M_ZERO);
1155	if (mod == NULL)
1156		panic("no memory for module list");
1157	mod->container = container;
1158	mod->name = modname;
1159	mod->version = version;
1160	TAILQ_INSERT_TAIL(&found_modules, mod, link);
1161	return (mod);
1162}
1163
1164static void
1165linker_addmodules(linker_file_t lf, struct mod_metadata **start,
1166    struct mod_metadata **stop, int preload)
1167{
1168	struct mod_metadata *mp, **mdp;
1169	const char *modname;
1170	int ver;
1171
1172	for (mdp = start; mdp < stop; mdp++) {
1173		mp = *mdp;
1174		if (mp->md_type != MDT_VERSION)
1175			continue;
1176		modname = mp->md_cval;
1177		ver = ((struct mod_version *)mp->md_data)->mv_version;
1178		if (modlist_lookup(modname, ver) != NULL) {
1179			printf("module %s already present!\n", modname);
1180			/* XXX what can we do? this is a build error. :-( */
1181			continue;
1182		}
1183		modlist_newmodule(modname, ver, lf);
1184	}
1185}
1186
1187static void
1188linker_preload(void *arg)
1189{
1190	caddr_t modptr;
1191	const char *modname, *nmodname;
1192	char *modtype;
1193	linker_file_t lf;
1194	linker_class_t lc;
1195	int error;
1196	linker_file_list_t loaded_files;
1197	linker_file_list_t depended_files;
1198	struct mod_metadata *mp, *nmp;
1199	struct mod_metadata **start, **stop, **mdp, **nmdp;
1200	struct mod_depend *verinfo;
1201	int nver;
1202	int resolves;
1203	modlist_t mod;
1204	struct sysinit **si_start, **si_stop;
1205
1206	TAILQ_INIT(&loaded_files);
1207	TAILQ_INIT(&depended_files);
1208	TAILQ_INIT(&found_modules);
1209	error = 0;
1210
1211	modptr = NULL;
1212	while ((modptr = preload_search_next_name(modptr)) != NULL) {
1213		modname = (char *)preload_search_info(modptr, MODINFO_NAME);
1214		modtype = (char *)preload_search_info(modptr, MODINFO_TYPE);
1215		if (modname == NULL) {
1216			printf("Preloaded module at %p does not have a"
1217			    " name!\n", modptr);
1218			continue;
1219		}
1220		if (modtype == NULL) {
1221			printf("Preloaded module at %p does not have a type!\n",
1222			    modptr);
1223			continue;
1224		}
1225		if (bootverbose)
1226			printf("Preloaded %s \"%s\" at %p.\n", modtype, modname,
1227			    modptr);
1228		lf = NULL;
1229		TAILQ_FOREACH(lc, &classes, link) {
1230			error = LINKER_LINK_PRELOAD(lc, modname, &lf);
1231			if (!error)
1232				break;
1233			lf = NULL;
1234		}
1235		if (lf)
1236			TAILQ_INSERT_TAIL(&loaded_files, lf, loaded);
1237	}
1238
1239	/*
1240	 * First get a list of stuff in the kernel.
1241	 */
1242	if (linker_file_lookup_set(linker_kernel_file, MDT_SETNAME, &start,
1243	    &stop, NULL) == 0)
1244		linker_addmodules(linker_kernel_file, start, stop, 1);
1245
1246	/*
1247	 * this is a once-off kinky bubble sort resolve relocation dependency
1248	 * requirements
1249	 */
1250restart:
1251	TAILQ_FOREACH(lf, &loaded_files, loaded) {
1252		error = linker_file_lookup_set(lf, MDT_SETNAME, &start,
1253		    &stop, NULL);
1254		/*
1255		 * First, look to see if we would successfully link with this
1256		 * stuff.
1257		 */
1258		resolves = 1;	/* unless we know otherwise */
1259		if (!error) {
1260			for (mdp = start; mdp < stop; mdp++) {
1261				mp = *mdp;
1262				if (mp->md_type != MDT_DEPEND)
1263					continue;
1264				modname = mp->md_cval;
1265				verinfo = mp->md_data;
1266				for (nmdp = start; nmdp < stop; nmdp++) {
1267					nmp = *nmdp;
1268					if (nmp->md_type != MDT_VERSION)
1269						continue;
1270					nmodname = nmp->md_cval;
1271					if (strcmp(modname, nmodname) == 0)
1272						break;
1273				}
1274				if (nmdp < stop)   /* it's a self reference */
1275					continue;
1276
1277				/*
1278				 * ok, the module isn't here yet, we
1279				 * are not finished
1280				 */
1281				if (modlist_lookup2(modname, verinfo) == NULL)
1282					resolves = 0;
1283			}
1284		}
1285		/*
1286		 * OK, if we found our modules, we can link.  So, "provide"
1287		 * the modules inside and add it to the end of the link order
1288		 * list.
1289		 */
1290		if (resolves) {
1291			if (!error) {
1292				for (mdp = start; mdp < stop; mdp++) {
1293					mp = *mdp;
1294					if (mp->md_type != MDT_VERSION)
1295						continue;
1296					modname = mp->md_cval;
1297					nver = ((struct mod_version *)
1298					    mp->md_data)->mv_version;
1299					if (modlist_lookup(modname,
1300					    nver) != NULL) {
1301						printf("module %s already"
1302						    " present!\n", modname);
1303						linker_file_unload(lf,
1304						    LINKER_UNLOAD_FORCE);
1305						TAILQ_REMOVE(&loaded_files,
1306						    lf, loaded);
1307						/* we changed tailq next ptr */
1308						goto restart;
1309					}
1310					modlist_newmodule(modname, nver, lf);
1311				}
1312			}
1313			TAILQ_REMOVE(&loaded_files, lf, loaded);
1314			TAILQ_INSERT_TAIL(&depended_files, lf, loaded);
1315			/*
1316			 * Since we provided modules, we need to restart the
1317			 * sort so that the previous files that depend on us
1318			 * have a chance. Also, we've busted the tailq next
1319			 * pointer with the REMOVE.
1320			 */
1321			goto restart;
1322		}
1323	}
1324
1325	/*
1326	 * At this point, we check to see what could not be resolved..
1327	 */
1328	TAILQ_FOREACH(lf, &loaded_files, loaded) {
1329		printf("KLD file %s is missing dependencies\n", lf->filename);
1330		linker_file_unload(lf, LINKER_UNLOAD_FORCE);
1331		TAILQ_REMOVE(&loaded_files, lf, loaded);
1332	}
1333
1334	/*
1335	 * We made it. Finish off the linking in the order we determined.
1336	 */
1337	TAILQ_FOREACH(lf, &depended_files, loaded) {
1338		if (linker_kernel_file) {
1339			linker_kernel_file->refs++;
1340			error = linker_file_add_dependency(lf,
1341			    linker_kernel_file);
1342			if (error)
1343				panic("cannot add dependency");
1344		}
1345		lf->userrefs++;	/* so we can (try to) kldunload it */
1346		error = linker_file_lookup_set(lf, MDT_SETNAME, &start,
1347		    &stop, NULL);
1348		if (!error) {
1349			for (mdp = start; mdp < stop; mdp++) {
1350				mp = *mdp;
1351				if (mp->md_type != MDT_DEPEND)
1352					continue;
1353				modname = mp->md_cval;
1354				verinfo = mp->md_data;
1355				mod = modlist_lookup2(modname, verinfo);
1356				/* Don't count self-dependencies */
1357				if (lf == mod->container)
1358					continue;
1359				mod->container->refs++;
1360				error = linker_file_add_dependency(lf,
1361				    mod->container);
1362				if (error)
1363					panic("cannot add dependency");
1364			}
1365		}
1366		/*
1367		 * Now do relocation etc using the symbol search paths
1368		 * established by the dependencies
1369		 */
1370		error = LINKER_LINK_PRELOAD_FINISH(lf);
1371		if (error) {
1372			printf("KLD file %s - could not finalize loading\n",
1373			    lf->filename);
1374			linker_file_unload(lf, LINKER_UNLOAD_FORCE);
1375			continue;
1376		}
1377		linker_file_register_modules(lf);
1378		if (linker_file_lookup_set(lf, "sysinit_set", &si_start,
1379		    &si_stop, NULL) == 0)
1380			sysinit_add(si_start, si_stop);
1381		linker_file_register_sysctls(lf);
1382		lf->flags |= LINKER_FILE_LINKED;
1383	}
1384	/* woohoo! we made it! */
1385}
1386
1387SYSINIT(preload, SI_SUB_KLD, SI_ORDER_MIDDLE, linker_preload, 0)
1388
1389/*
1390 * Search for a not-loaded module by name.
1391 *
1392 * Modules may be found in the following locations:
1393 *
1394 * - preloaded (result is just the module name) - on disk (result is full path
1395 * to module)
1396 *
1397 * If the module name is qualified in any way (contains path, etc.) the we
1398 * simply return a copy of it.
1399 *
1400 * The search path can be manipulated via sysctl.  Note that we use the ';'
1401 * character as a separator to be consistent with the bootloader.
1402 */
1403
1404static char linker_hintfile[] = "linker.hints";
1405static char linker_path[MAXPATHLEN] = "/boot/kernel;/boot/modules";
1406
1407SYSCTL_STRING(_kern, OID_AUTO, module_path, CTLFLAG_RW, linker_path,
1408    sizeof(linker_path), "module load search path");
1409
1410TUNABLE_STR("module_path", linker_path, sizeof(linker_path));
1411
1412static char *linker_ext_list[] = {
1413	"",
1414	".ko",
1415	NULL
1416};
1417
1418/*
1419 * Check if file actually exists either with or without extension listed in
1420 * the linker_ext_list. (probably should be generic for the rest of the
1421 * kernel)
1422 */
1423static char *
1424linker_lookup_file(const char *path, int pathlen, const char *name,
1425    int namelen, struct vattr *vap)
1426{
1427	struct nameidata nd;
1428	struct thread *td = curthread;	/* XXX */
1429	char *result, **cpp, *sep;
1430	int error, len, extlen, reclen, flags;
1431	enum vtype type;
1432
1433	extlen = 0;
1434	for (cpp = linker_ext_list; *cpp; cpp++) {
1435		len = strlen(*cpp);
1436		if (len > extlen)
1437			extlen = len;
1438	}
1439	extlen++;		/* trailing '\0' */
1440	sep = (path[pathlen - 1] != '/') ? "/" : "";
1441
1442	reclen = pathlen + strlen(sep) + namelen + extlen + 1;
1443	result = malloc(reclen, M_LINKER, M_WAITOK);
1444	for (cpp = linker_ext_list; *cpp; cpp++) {
1445		snprintf(result, reclen, "%.*s%s%.*s%s", pathlen, path, sep,
1446		    namelen, name, *cpp);
1447		/*
1448		 * Attempt to open the file, and return the path if
1449		 * we succeed and it's a regular file.
1450		 */
1451		NDINIT(&nd, LOOKUP, FOLLOW, UIO_SYSSPACE, result, td);
1452		flags = FREAD;
1453		error = vn_open(&nd, &flags, 0, -1);
1454		if (error == 0) {
1455			NDFREE(&nd, NDF_ONLY_PNBUF);
1456			type = nd.ni_vp->v_type;
1457			if (vap)
1458				VOP_GETATTR(nd.ni_vp, vap, td->td_ucred, td);
1459			VOP_UNLOCK(nd.ni_vp, 0, td);
1460			vn_close(nd.ni_vp, FREAD, td->td_ucred, td);
1461			if (type == VREG)
1462				return (result);
1463		}
1464	}
1465	free(result, M_LINKER);
1466	return (NULL);
1467}
1468
1469#define	INT_ALIGN(base, ptr)	ptr =					\
1470	(base) + (((ptr) - (base) + sizeof(int) - 1) & ~(sizeof(int) - 1))
1471
1472/*
1473 * Lookup KLD which contains requested module in the "linker.hints" file. If
1474 * version specification is available, then try to find the best KLD.
1475 * Otherwise just find the latest one.
1476 */
1477static char *
1478linker_hints_lookup(const char *path, int pathlen, const char *modname,
1479    int modnamelen, struct mod_depend *verinfo)
1480{
1481	struct thread *td = curthread;	/* XXX */
1482	struct ucred *cred = td ? td->td_ucred : NULL;
1483	struct nameidata nd;
1484	struct vattr vattr, mattr;
1485	u_char *hints = NULL;
1486	u_char *cp, *recptr, *bufend, *result, *best, *pathbuf, *sep;
1487	int error, ival, bestver, *intp, reclen, found, flags, clen, blen;
1488
1489	result = NULL;
1490	bestver = found = 0;
1491
1492	sep = (path[pathlen - 1] != '/') ? "/" : "";
1493	reclen = imax(modnamelen, strlen(linker_hintfile)) + pathlen +
1494	    strlen(sep) + 1;
1495	pathbuf = malloc(reclen, M_LINKER, M_WAITOK);
1496	snprintf(pathbuf, reclen, "%.*s%s%s", pathlen, path, sep,
1497	    linker_hintfile);
1498
1499	NDINIT(&nd, LOOKUP, NOFOLLOW, UIO_SYSSPACE, pathbuf, td);
1500	flags = FREAD;
1501	error = vn_open(&nd, &flags, 0, -1);
1502	if (error)
1503		goto bad;
1504	NDFREE(&nd, NDF_ONLY_PNBUF);
1505	if (nd.ni_vp->v_type != VREG)
1506		goto bad;
1507	best = cp = NULL;
1508	error = VOP_GETATTR(nd.ni_vp, &vattr, cred, td);
1509	if (error)
1510		goto bad;
1511	/*
1512	 * XXX: we need to limit this number to some reasonable value
1513	 */
1514	if (vattr.va_size > 100 * 1024) {
1515		printf("hints file too large %ld\n", (long)vattr.va_size);
1516		goto bad;
1517	}
1518	hints = malloc(vattr.va_size, M_TEMP, M_WAITOK);
1519	if (hints == NULL)
1520		goto bad;
1521	error = vn_rdwr(UIO_READ, nd.ni_vp, (caddr_t)hints, vattr.va_size, 0,
1522	    UIO_SYSSPACE, IO_NODELOCKED, cred, NOCRED, &reclen, td);
1523	if (error)
1524		goto bad;
1525	VOP_UNLOCK(nd.ni_vp, 0, td);
1526	vn_close(nd.ni_vp, FREAD, cred, td);
1527	nd.ni_vp = NULL;
1528	if (reclen != 0) {
1529		printf("can't read %d\n", reclen);
1530		goto bad;
1531	}
1532	intp = (int *)hints;
1533	ival = *intp++;
1534	if (ival != LINKER_HINTS_VERSION) {
1535		printf("hints file version mismatch %d\n", ival);
1536		goto bad;
1537	}
1538	bufend = hints + vattr.va_size;
1539	recptr = (u_char *)intp;
1540	clen = blen = 0;
1541	while (recptr < bufend && !found) {
1542		intp = (int *)recptr;
1543		reclen = *intp++;
1544		ival = *intp++;
1545		cp = (char *)intp;
1546		switch (ival) {
1547		case MDT_VERSION:
1548			clen = *cp++;
1549			if (clen != modnamelen || bcmp(cp, modname, clen) != 0)
1550				break;
1551			cp += clen;
1552			INT_ALIGN(hints, cp);
1553			ival = *(int *)cp;
1554			cp += sizeof(int);
1555			clen = *cp++;
1556			if (verinfo == NULL ||
1557			    ival == verinfo->md_ver_preferred) {
1558				found = 1;
1559				break;
1560			}
1561			if (ival >= verinfo->md_ver_minimum &&
1562			    ival <= verinfo->md_ver_maximum &&
1563			    ival > bestver) {
1564				bestver = ival;
1565				best = cp;
1566				blen = clen;
1567			}
1568			break;
1569		default:
1570			break;
1571		}
1572		recptr += reclen + sizeof(int);
1573	}
1574	/*
1575	 * Finally check if KLD is in the place
1576	 */
1577	if (found)
1578		result = linker_lookup_file(path, pathlen, cp, clen, &mattr);
1579	else if (best)
1580		result = linker_lookup_file(path, pathlen, best, blen, &mattr);
1581
1582	/*
1583	 * KLD is newer than hints file. What we should do now?
1584	 */
1585	if (result && timespeccmp(&mattr.va_mtime, &vattr.va_mtime, >))
1586		printf("warning: KLD '%s' is newer than the linker.hints"
1587		    " file\n", result);
1588bad:
1589	free(pathbuf, M_LINKER);
1590	if (hints)
1591		free(hints, M_TEMP);
1592	if (nd.ni_vp != NULL) {
1593		VOP_UNLOCK(nd.ni_vp, 0, td);
1594		vn_close(nd.ni_vp, FREAD, cred, td);
1595	}
1596	/*
1597	 * If nothing found or hints is absent - fallback to the old
1598	 * way by using "kldname[.ko]" as module name.
1599	 */
1600	if (!found && !bestver && result == NULL)
1601		result = linker_lookup_file(path, pathlen, modname,
1602		    modnamelen, NULL);
1603	return (result);
1604}
1605
1606/*
1607 * Lookup KLD which contains requested module in the all directories.
1608 */
1609static char *
1610linker_search_module(const char *modname, int modnamelen,
1611    struct mod_depend *verinfo)
1612{
1613	char *cp, *ep, *result;
1614
1615	/*
1616	 * traverse the linker path
1617	 */
1618	for (cp = linker_path; *cp; cp = ep + 1) {
1619		/* find the end of this component */
1620		for (ep = cp; (*ep != 0) && (*ep != ';'); ep++);
1621		result = linker_hints_lookup(cp, ep - cp, modname,
1622		    modnamelen, verinfo);
1623		if (result != NULL)
1624			return (result);
1625		if (*ep == 0)
1626			break;
1627	}
1628	return (NULL);
1629}
1630
1631/*
1632 * Search for module in all directories listed in the linker_path.
1633 */
1634static char *
1635linker_search_kld(const char *name)
1636{
1637	char *cp, *ep, *result;
1638	int len;
1639
1640	/* qualified at all? */
1641	if (index(name, '/'))
1642		return (linker_strdup(name));
1643
1644	/* traverse the linker path */
1645	len = strlen(name);
1646	for (ep = linker_path; *ep; ep++) {
1647		cp = ep;
1648		/* find the end of this component */
1649		for (; *ep != 0 && *ep != ';'; ep++);
1650		result = linker_lookup_file(cp, ep - cp, name, len, NULL);
1651		if (result != NULL)
1652			return (result);
1653	}
1654	return (NULL);
1655}
1656
1657static const char *
1658linker_basename(const char *path)
1659{
1660	const char *filename;
1661
1662	filename = rindex(path, '/');
1663	if (filename == NULL)
1664		return path;
1665	if (filename[1])
1666		filename++;
1667	return (filename);
1668}
1669
1670#ifdef HWPMC_HOOKS
1671
1672/*
1673 * Inform hwpmc about the set of kernel modules currently loaded.
1674 */
1675void *
1676linker_hwpmc_list_objects(void)
1677{
1678	int nobjects, nmappings;
1679	linker_file_t lf;
1680	struct pmckern_map_in *ko, *kobase;
1681
1682	nmappings = 15;	/* a reasonable default */
1683
1684 retry:
1685	/* allocate nmappings+1 entries */
1686	MALLOC(kobase, struct pmckern_map_in *,
1687	    (nmappings + 1) * sizeof(struct pmckern_map_in), M_LINKER,
1688	    M_WAITOK | M_ZERO);
1689
1690	nobjects = 0;
1691	mtx_lock(&kld_mtx);
1692	TAILQ_FOREACH(lf, &linker_files, link)
1693		nobjects++;
1694
1695	KASSERT(nobjects > 0, ("linker_hpwmc_list_objects: no kernel "
1696		"objects?"));
1697
1698	if (nobjects > nmappings) {
1699		nmappings = nobjects;
1700		FREE(kobase, M_LINKER);
1701		mtx_unlock(&kld_mtx);
1702		goto retry;
1703	}
1704
1705	ko = kobase;
1706	TAILQ_FOREACH(lf, &linker_files, link) {
1707		ko->pm_file = lf->filename;
1708		ko->pm_address = (uintptr_t) lf->address;
1709		ko++;
1710	}
1711
1712	/* The last entry of the malloced area comprises of all zeros. */
1713	KASSERT(ko->pm_file == NULL,
1714	    ("linker_hwpmc_list_objects: last object not NULL"));
1715
1716	mtx_unlock(&kld_mtx);
1717
1718	return ((void *) kobase);
1719}
1720#endif
1721
1722/*
1723 * Find a file which contains given module and load it, if "parent" is not
1724 * NULL, register a reference to it.
1725 */
1726int
1727linker_load_module(const char *kldname, const char *modname,
1728    struct linker_file *parent, struct mod_depend *verinfo,
1729    struct linker_file **lfpp)
1730{
1731	linker_file_t lfdep;
1732	const char *filename;
1733	char *pathname;
1734	int error;
1735
1736	if (modname == NULL) {
1737		/*
1738 		 * We have to load KLD
1739 		 */
1740		KASSERT(verinfo == NULL, ("linker_load_module: verinfo"
1741		    " is not NULL"));
1742		pathname = linker_search_kld(kldname);
1743	} else {
1744		if (modlist_lookup2(modname, verinfo) != NULL)
1745			return (EEXIST);
1746		if (kldname != NULL)
1747			pathname = linker_strdup(kldname);
1748		else if (rootvnode == NULL)
1749			pathname = NULL;
1750		else
1751			/*
1752			 * Need to find a KLD with required module
1753			 */
1754			pathname = linker_search_module(modname,
1755			    strlen(modname), verinfo);
1756	}
1757	if (pathname == NULL)
1758		return (ENOENT);
1759
1760	/*
1761	 * Can't load more than one file with the same basename XXX:
1762	 * Actually it should be possible to have multiple KLDs with
1763	 * the same basename but different path because they can
1764	 * provide different versions of the same modules.
1765	 */
1766	filename = linker_basename(pathname);
1767	if (linker_find_file_by_name(filename)) {
1768		error = EEXIST;
1769		goto out;
1770	}
1771	do {
1772		error = linker_load_file(pathname, &lfdep);
1773		if (error)
1774			break;
1775		if (modname && verinfo &&
1776		    modlist_lookup2(modname, verinfo) == NULL) {
1777			linker_file_unload(lfdep, LINKER_UNLOAD_FORCE);
1778			error = ENOENT;
1779			break;
1780		}
1781		if (parent) {
1782			error = linker_file_add_dependency(parent, lfdep);
1783			if (error)
1784				break;
1785		}
1786		if (lfpp)
1787			*lfpp = lfdep;
1788	} while (0);
1789out:
1790	if (pathname)
1791		free(pathname, M_LINKER);
1792	return (error);
1793}
1794
1795/*
1796 * This routine is responsible for finding dependencies of userland initiated
1797 * kldload(2)'s of files.
1798 */
1799int
1800linker_load_dependencies(linker_file_t lf)
1801{
1802	linker_file_t lfdep;
1803	struct mod_metadata **start, **stop, **mdp, **nmdp;
1804	struct mod_metadata *mp, *nmp;
1805	struct mod_depend *verinfo;
1806	modlist_t mod;
1807	const char *modname, *nmodname;
1808	int ver, error = 0, count;
1809
1810	/*
1811	 * All files are dependant on /kernel.
1812	 */
1813	if (linker_kernel_file) {
1814		linker_kernel_file->refs++;
1815		error = linker_file_add_dependency(lf, linker_kernel_file);
1816		if (error)
1817			return (error);
1818	}
1819	if (linker_file_lookup_set(lf, MDT_SETNAME, &start, &stop,
1820	    &count) != 0)
1821		return (0);
1822	for (mdp = start; mdp < stop; mdp++) {
1823		mp = *mdp;
1824		if (mp->md_type != MDT_VERSION)
1825			continue;
1826		modname = mp->md_cval;
1827		ver = ((struct mod_version *)mp->md_data)->mv_version;
1828		mod = modlist_lookup(modname, ver);
1829		if (mod != NULL) {
1830			printf("interface %s.%d already present in the KLD"
1831			    " '%s'!\n", modname, ver,
1832			    mod->container->filename);
1833			return (EEXIST);
1834		}
1835	}
1836
1837	for (mdp = start; mdp < stop; mdp++) {
1838		mp = *mdp;
1839		if (mp->md_type != MDT_DEPEND)
1840			continue;
1841		modname = mp->md_cval;
1842		verinfo = mp->md_data;
1843		nmodname = NULL;
1844		for (nmdp = start; nmdp < stop; nmdp++) {
1845			nmp = *nmdp;
1846			if (nmp->md_type != MDT_VERSION)
1847				continue;
1848			nmodname = nmp->md_cval;
1849			if (strcmp(modname, nmodname) == 0)
1850				break;
1851		}
1852		if (nmdp < stop)/* early exit, it's a self reference */
1853			continue;
1854		mod = modlist_lookup2(modname, verinfo);
1855		if (mod) {	/* woohoo, it's loaded already */
1856			lfdep = mod->container;
1857			lfdep->refs++;
1858			error = linker_file_add_dependency(lf, lfdep);
1859			if (error)
1860				break;
1861			continue;
1862		}
1863		error = linker_load_module(NULL, modname, lf, verinfo, NULL);
1864		if (error) {
1865			printf("KLD %s: depends on %s - not available\n",
1866			    lf->filename, modname);
1867			break;
1868		}
1869	}
1870
1871	if (error)
1872		return (error);
1873	linker_addmodules(lf, start, stop, 0);
1874	return (error);
1875}
1876
1877static int
1878sysctl_kern_function_list_iterate(const char *name, void *opaque)
1879{
1880	struct sysctl_req *req;
1881
1882	req = opaque;
1883	return (SYSCTL_OUT(req, name, strlen(name) + 1));
1884}
1885
1886/*
1887 * Export a nul-separated, double-nul-terminated list of all function names
1888 * in the kernel.
1889 */
1890static int
1891sysctl_kern_function_list(SYSCTL_HANDLER_ARGS)
1892{
1893	linker_file_t lf;
1894	int error;
1895
1896#ifdef MAC
1897	error = mac_check_kld_stat(req->td->td_ucred);
1898	if (error)
1899		return (error);
1900#endif
1901	error = sysctl_wire_old_buffer(req, 0);
1902	if (error != 0)
1903		return (error);
1904	mtx_lock(&kld_mtx);
1905	TAILQ_FOREACH(lf, &linker_files, link) {
1906		error = LINKER_EACH_FUNCTION_NAME(lf,
1907		    sysctl_kern_function_list_iterate, req);
1908		if (error) {
1909			mtx_unlock(&kld_mtx);
1910			return (error);
1911		}
1912	}
1913	mtx_unlock(&kld_mtx);
1914	return (SYSCTL_OUT(req, "", 1));
1915}
1916
1917SYSCTL_PROC(_kern, OID_AUTO, function_list, CTLFLAG_RD,
1918    NULL, 0, sysctl_kern_function_list, "", "kernel function list");
1919