module.c revision 294985
1/*-
2 * Copyright (c) 1998 Michael Smith <msmith@freebsd.org>
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: stable/10/sys/boot/common/module.c 294985 2016-01-28 12:23:25Z smh $");
29
30/*
31 * file/module function dispatcher, support, etc.
32 */
33
34#include <stand.h>
35#include <string.h>
36#include <sys/param.h>
37#include <sys/linker.h>
38#include <sys/module.h>
39#include <sys/queue.h>
40
41#include "bootstrap.h"
42
43#define	MDIR_REMOVED	0x0001
44#define	MDIR_NOHINTS	0x0002
45
46struct moduledir {
47	char	*d_path;	/* path of modules directory */
48	u_char	*d_hints;	/* content of linker.hints file */
49	int	d_hintsz;	/* size of hints data */
50	int	d_flags;
51	STAILQ_ENTRY(moduledir) d_link;
52};
53
54static int			file_load(char *filename, vm_offset_t dest, struct preloaded_file **result);
55static int			file_load_dependencies(struct preloaded_file *base_mod);
56static char *			file_search(const char *name, char **extlist);
57static struct kernel_module *	file_findmodule(struct preloaded_file *fp, char *modname, struct mod_depend *verinfo);
58static int			file_havepath(const char *name);
59static char			*mod_searchmodule(char *name, struct mod_depend *verinfo);
60static void			file_insert_tail(struct preloaded_file *mp);
61struct file_metadata*		metadata_next(struct file_metadata *base_mp, int type);
62static void			moduledir_readhints(struct moduledir *mdp);
63static void			moduledir_rebuild(void);
64
65/* load address should be tweaked by first module loaded (kernel) */
66static vm_offset_t	loadaddr = 0;
67
68#if defined(LOADER_FDT_SUPPORT)
69static const char	*default_searchpath =
70    "/boot/kernel;/boot/modules;/boot/dtb";
71#else
72static const char	*default_searchpath ="/boot/kernel;/boot/modules";
73#endif
74
75static STAILQ_HEAD(, moduledir) moduledir_list = STAILQ_HEAD_INITIALIZER(moduledir_list);
76
77struct preloaded_file *preloaded_files = NULL;
78
79static char *kld_ext_list[] = {
80    ".ko",
81    "",
82    ".debug",
83    NULL
84};
85
86
87/*
88 * load an object, either a disk file or code module.
89 *
90 * To load a file, the syntax is:
91 *
92 * load -t <type> <path>
93 *
94 * code modules are loaded as:
95 *
96 * load <path> <options>
97 */
98
99COMMAND_SET(load, "load", "load a kernel or module", command_load);
100
101static int
102command_load(int argc, char *argv[])
103{
104    struct preloaded_file *fp;
105    char	*typestr;
106    int		dofile, dokld, ch, error;
107
108    dokld = dofile = 0;
109    optind = 1;
110    optreset = 1;
111    typestr = NULL;
112    if (argc == 1) {
113	command_errmsg = "no filename specified";
114	return (CMD_CRIT);
115    }
116    while ((ch = getopt(argc, argv, "kt:")) != -1) {
117	switch(ch) {
118	case 'k':
119	    dokld = 1;
120	    break;
121	case 't':
122	    typestr = optarg;
123	    dofile = 1;
124	    break;
125	case '?':
126	default:
127	    /* getopt has already reported an error */
128	    return (CMD_OK);
129	}
130    }
131    argv += (optind - 1);
132    argc -= (optind - 1);
133
134    /*
135     * Request to load a raw file?
136     */
137    if (dofile) {
138	if ((argc != 2) || (typestr == NULL) || (*typestr == 0)) {
139	    command_errmsg = "invalid load type";
140	    return (CMD_CRIT);
141	}
142
143	fp = file_findfile(argv[1], typestr);
144	if (fp) {
145		sprintf(command_errbuf, "warning: file '%s' already loaded", argv[1]);
146		return (CMD_WARN);
147	}
148
149	if (file_loadraw(argv[1], typestr, 1) != NULL)
150		return (CMD_OK);
151
152	/* Failing to load mfs_root is never going to end well! */
153	if (strcmp("mfs_root", typestr) == 0)
154		return (CMD_FATAL);
155
156	return (CMD_ERROR);
157    }
158    /*
159     * Do we have explicit KLD load ?
160     */
161    if (dokld || file_havepath(argv[1])) {
162	error = mod_loadkld(argv[1], argc - 2, argv + 2);
163	if (error == EEXIST) {
164	    sprintf(command_errbuf, "warning: KLD '%s' already loaded", argv[1]);
165	    return (CMD_WARN);
166	}
167
168	return (error == 0 ? CMD_OK : CMD_CRIT);
169    }
170    /*
171     * Looks like a request for a module.
172     */
173    error = mod_load(argv[1], NULL, argc - 2, argv + 2);
174    if (error == EEXIST) {
175	sprintf(command_errbuf, "warning: module '%s' already loaded", argv[1]);
176	return (CMD_WARN);
177    }
178
179    return (error == 0 ? CMD_OK : CMD_CRIT);
180}
181
182COMMAND_SET(load_geli, "load_geli", "load a geli key", command_load_geli);
183
184static int
185command_load_geli(int argc, char *argv[])
186{
187    char	typestr[80];
188    char	*cp;
189    int		ch, num;
190
191    if (argc < 3) {
192	    command_errmsg = "usage is [-n key#] <prov> <file>";
193	    return(CMD_ERROR);
194    }
195
196    num = 0;
197    optind = 1;
198    optreset = 1;
199    while ((ch = getopt(argc, argv, "n:")) != -1) {
200	switch(ch) {
201	case 'n':
202	    num = strtol(optarg, &cp, 0);
203	    if (cp == optarg) {
204		    sprintf(command_errbuf, "bad key index '%s'", optarg);
205		    return(CMD_ERROR);
206	    }
207	    break;
208	case '?':
209	default:
210	    /* getopt has already reported an error */
211	    return(CMD_OK);
212	}
213    }
214    argv += (optind - 1);
215    argc -= (optind - 1);
216    sprintf(typestr, "%s:geli_keyfile%d", argv[1], num);
217    return (file_loadraw(argv[2], typestr, 1) ? CMD_OK : CMD_ERROR);
218}
219
220COMMAND_SET(unload, "unload", "unload all modules", command_unload);
221
222static int
223command_unload(int argc, char *argv[])
224{
225    struct preloaded_file	*fp;
226
227    while (preloaded_files != NULL) {
228	fp = preloaded_files;
229	preloaded_files = preloaded_files->f_next;
230	file_discard(fp);
231    }
232    loadaddr = 0;
233    unsetenv("kernelname");
234    return(CMD_OK);
235}
236
237COMMAND_SET(lsmod, "lsmod", "list loaded modules", command_lsmod);
238
239static int
240command_lsmod(int argc, char *argv[])
241{
242    struct preloaded_file	*fp;
243    struct kernel_module	*mp;
244    struct file_metadata	*md;
245    char			lbuf[80];
246    int				ch, verbose;
247
248    verbose = 0;
249    optind = 1;
250    optreset = 1;
251    while ((ch = getopt(argc, argv, "v")) != -1) {
252	switch(ch) {
253	case 'v':
254	    verbose = 1;
255	    break;
256	case '?':
257	default:
258	    /* getopt has already reported an error */
259	    return(CMD_OK);
260	}
261    }
262
263    pager_open();
264    for (fp = preloaded_files; fp; fp = fp->f_next) {
265	sprintf(lbuf, " %p: %s (%s, 0x%lx)\n",
266		(void *) fp->f_addr, fp->f_name, fp->f_type, (long) fp->f_size);
267	pager_output(lbuf);
268	if (fp->f_args != NULL) {
269	    pager_output("    args: ");
270	    pager_output(fp->f_args);
271	    pager_output("\n");
272	}
273	if (fp->f_modules) {
274	    pager_output("  modules: ");
275	    for (mp = fp->f_modules; mp; mp = mp->m_next) {
276		sprintf(lbuf, "%s.%d ", mp->m_name, mp->m_version);
277		pager_output(lbuf);
278	    }
279	    pager_output("\n");
280	}
281	if (verbose) {
282	    /* XXX could add some formatting smarts here to display some better */
283	    for (md = fp->f_metadata; md != NULL; md = md->md_next) {
284		sprintf(lbuf, "      0x%04x, 0x%lx\n", md->md_type, (long) md->md_size);
285		pager_output(lbuf);
286	    }
287	}
288    }
289    pager_close();
290    return(CMD_OK);
291}
292
293/*
294 * File level interface, functions file_*
295 */
296int
297file_load(char *filename, vm_offset_t dest, struct preloaded_file **result)
298{
299    static int last_file_format = 0;
300    struct preloaded_file *fp;
301    int error;
302    int i;
303
304    if (archsw.arch_loadaddr != NULL)
305	dest = archsw.arch_loadaddr(LOAD_RAW, filename, dest);
306
307    error = EFTYPE;
308    for (i = last_file_format, fp = NULL;
309	file_formats[i] && fp == NULL; i++) {
310	error = (file_formats[i]->l_load)(filename, dest, &fp);
311	if (error == 0) {
312	    fp->f_loader = last_file_format = i; /* remember the loader */
313	    *result = fp;
314	    break;
315	} else if (last_file_format == i && i != 0) {
316	    /* Restart from the beginning */
317	    i = -1;
318	    last_file_format = 0;
319	    fp = NULL;
320	    continue;
321	}
322	if (error == EFTYPE)
323	    continue;		/* Unknown to this handler? */
324	if (error) {
325	    sprintf(command_errbuf, "can't load file '%s': %s",
326		filename, strerror(error));
327	    break;
328	}
329    }
330    return (error);
331}
332
333static int
334file_load_dependencies(struct preloaded_file *base_file)
335{
336    struct file_metadata *md;
337    struct preloaded_file *fp;
338    struct mod_depend *verinfo;
339    struct kernel_module *mp;
340    char *dmodname;
341    int error;
342
343    md = file_findmetadata(base_file, MODINFOMD_DEPLIST);
344    if (md == NULL)
345	return (0);
346    error = 0;
347    do {
348	verinfo = (struct mod_depend*)md->md_data;
349	dmodname = (char *)(verinfo + 1);
350	if (file_findmodule(NULL, dmodname, verinfo) == NULL) {
351	    printf("loading required module '%s'\n", dmodname);
352	    error = mod_load(dmodname, verinfo, 0, NULL);
353	    if (error)
354		break;
355	    /*
356	     * If module loaded via kld name which isn't listed
357	     * in the linker.hints file, we should check if it have
358	     * required version.
359	     */
360	    mp = file_findmodule(NULL, dmodname, verinfo);
361	    if (mp == NULL) {
362		sprintf(command_errbuf, "module '%s' exists but with wrong version",
363		    dmodname);
364		error = ENOENT;
365		break;
366	    }
367	}
368	md = metadata_next(md, MODINFOMD_DEPLIST);
369    } while (md);
370    if (!error)
371	return (0);
372    /* Load failed; discard everything */
373    while (base_file != NULL) {
374        fp = base_file;
375        base_file = base_file->f_next;
376        file_discard(fp);
377    }
378    return (error);
379}
380
381/*
382 * We've been asked to load (fname) as (type), so just suck it in,
383 * no arguments or anything.
384 */
385struct preloaded_file *
386file_loadraw(const char *fname, char *type, int insert)
387{
388    struct preloaded_file	*fp;
389    char			*name;
390    int				fd, got;
391    vm_offset_t			laddr;
392
393    /* We can't load first */
394    if ((file_findfile(NULL, NULL)) == NULL) {
395	command_errmsg = "can't load file before kernel";
396	return(NULL);
397    }
398
399    /* locate the file on the load path */
400    name = file_search(fname, NULL);
401    if (name == NULL) {
402	sprintf(command_errbuf, "can't find '%s'", fname);
403	return(NULL);
404    }
405
406    if ((fd = open(name, O_RDONLY)) < 0) {
407	sprintf(command_errbuf, "can't open '%s': %s", name, strerror(errno));
408	free(name);
409	return(NULL);
410    }
411
412    if (archsw.arch_loadaddr != NULL)
413	loadaddr = archsw.arch_loadaddr(LOAD_RAW, name, loadaddr);
414
415    laddr = loadaddr;
416    for (;;) {
417	/* read in 4k chunks; size is not really important */
418	got = archsw.arch_readin(fd, laddr, 4096);
419	if (got == 0)				/* end of file */
420	    break;
421	if (got < 0) {				/* error */
422	    sprintf(command_errbuf, "error reading '%s': %s", name, strerror(errno));
423	    free(name);
424	    close(fd);
425	    return(NULL);
426	}
427	laddr += got;
428    }
429
430    /* Looks OK so far; create & populate control structure */
431    fp = file_alloc();
432    fp->f_name = strdup(name);
433    fp->f_type = strdup(type);
434    fp->f_args = NULL;
435    fp->f_metadata = NULL;
436    fp->f_loader = -1;
437    fp->f_addr = loadaddr;
438    fp->f_size = laddr - loadaddr;
439
440    /* recognise space consumption */
441    loadaddr = laddr;
442
443    /* Add to the list of loaded files */
444    if (insert != 0)
445    	file_insert_tail(fp);
446    close(fd);
447    return(fp);
448}
449
450/*
451 * Load the module (name), pass it (argc),(argv), add container file
452 * to the list of loaded files.
453 * If module is already loaded just assign new argc/argv.
454 */
455int
456mod_load(char *modname, struct mod_depend *verinfo, int argc, char *argv[])
457{
458    struct kernel_module	*mp;
459    int				err;
460    char			*filename;
461
462    if (file_havepath(modname)) {
463	printf("Warning: mod_load() called instead of mod_loadkld() for module '%s'\n", modname);
464	return (mod_loadkld(modname, argc, argv));
465    }
466    /* see if module is already loaded */
467    mp = file_findmodule(NULL, modname, verinfo);
468    if (mp) {
469#ifdef moduleargs
470	if (mp->m_args)
471	    free(mp->m_args);
472	mp->m_args = unargv(argc, argv);
473#endif
474	sprintf(command_errbuf, "warning: module '%s' already loaded", mp->m_name);
475	return (0);
476    }
477    /* locate file with the module on the search path */
478    filename = mod_searchmodule(modname, verinfo);
479    if (filename == NULL) {
480	sprintf(command_errbuf, "can't find '%s'", modname);
481	return (ENOENT);
482    }
483    err = mod_loadkld(filename, argc, argv);
484    return (err);
485}
486
487/*
488 * Load specified KLD. If path is omitted, then try to locate it via
489 * search path.
490 */
491int
492mod_loadkld(const char *kldname, int argc, char *argv[])
493{
494    struct preloaded_file	*fp, *last_file;
495    int				err;
496    char			*filename;
497
498    /*
499     * Get fully qualified KLD name
500     */
501    filename = file_search(kldname, kld_ext_list);
502    if (filename == NULL) {
503	sprintf(command_errbuf, "can't find '%s'", kldname);
504	return (ENOENT);
505    }
506    /*
507     * Check if KLD already loaded
508     */
509    fp = file_findfile(filename, NULL);
510    if (fp) {
511	sprintf(command_errbuf, "warning: KLD '%s' already loaded", filename);
512	free(filename);
513	return (0);
514    }
515    for (last_file = preloaded_files;
516	 last_file != NULL && last_file->f_next != NULL;
517	 last_file = last_file->f_next)
518	;
519
520    do {
521	err = file_load(filename, loadaddr, &fp);
522	if (err)
523	    break;
524	fp->f_args = unargv(argc, argv);
525	loadaddr = fp->f_addr + fp->f_size;
526	file_insert_tail(fp);		/* Add to the list of loaded files */
527	if (file_load_dependencies(fp) != 0) {
528	    err = ENOENT;
529	    last_file->f_next = NULL;
530	    loadaddr = last_file->f_addr + last_file->f_size;
531	    fp = NULL;
532	    break;
533	}
534    } while(0);
535    if (err == EFTYPE)
536	sprintf(command_errbuf, "don't know how to load module '%s'", filename);
537    if (err && fp)
538	file_discard(fp);
539    free(filename);
540    return (err);
541}
542
543/*
544 * Find a file matching (name) and (type).
545 * NULL may be passed as a wildcard to either.
546 */
547struct preloaded_file *
548file_findfile(const char *name, const char *type)
549{
550    struct preloaded_file *fp;
551
552    for (fp = preloaded_files; fp != NULL; fp = fp->f_next) {
553	if (((name == NULL) || !strcmp(name, fp->f_name)) &&
554	    ((type == NULL) || !strcmp(type, fp->f_type)))
555	    break;
556    }
557    return (fp);
558}
559
560/*
561 * Find a module matching (name) inside of given file.
562 * NULL may be passed as a wildcard.
563 */
564struct kernel_module *
565file_findmodule(struct preloaded_file *fp, char *modname,
566	struct mod_depend *verinfo)
567{
568    struct kernel_module *mp, *best;
569    int bestver, mver;
570
571    if (fp == NULL) {
572	for (fp = preloaded_files; fp; fp = fp->f_next) {
573	    mp = file_findmodule(fp, modname, verinfo);
574    	    if (mp)
575		return (mp);
576	}
577	return (NULL);
578    }
579    best = NULL;
580    bestver = 0;
581    for (mp = fp->f_modules; mp; mp = mp->m_next) {
582        if (strcmp(modname, mp->m_name) == 0) {
583	    if (verinfo == NULL)
584		return (mp);
585	    mver = mp->m_version;
586	    if (mver == verinfo->md_ver_preferred)
587		return (mp);
588	    if (mver >= verinfo->md_ver_minimum &&
589		mver <= verinfo->md_ver_maximum &&
590		mver > bestver) {
591		best = mp;
592		bestver = mver;
593	    }
594	}
595    }
596    return (best);
597}
598/*
599 * Make a copy of (size) bytes of data from (p), and associate them as
600 * metadata of (type) to the module (mp).
601 */
602void
603file_addmetadata(struct preloaded_file *fp, int type, size_t size, void *p)
604{
605    struct file_metadata	*md;
606
607    md = malloc(sizeof(struct file_metadata) - sizeof(md->md_data) + size);
608    md->md_size = size;
609    md->md_type = type;
610    bcopy(p, md->md_data, size);
611    md->md_next = fp->f_metadata;
612    fp->f_metadata = md;
613}
614
615/*
616 * Find a metadata object of (type) associated with the file (fp)
617 */
618struct file_metadata *
619file_findmetadata(struct preloaded_file *fp, int type)
620{
621    struct file_metadata *md;
622
623    for (md = fp->f_metadata; md != NULL; md = md->md_next)
624	if (md->md_type == type)
625	    break;
626    return(md);
627}
628
629struct file_metadata *
630metadata_next(struct file_metadata *md, int type)
631{
632    if (md == NULL)
633	return (NULL);
634    while((md = md->md_next) != NULL)
635	if (md->md_type == type)
636	    break;
637    return (md);
638}
639
640static char *emptyextlist[] = { "", NULL };
641
642/*
643 * Check if the given file is in place and return full path to it.
644 */
645static char *
646file_lookup(const char *path, const char *name, int namelen, char **extlist)
647{
648    struct stat	st;
649    char	*result, *cp, **cpp;
650    int		pathlen, extlen, len;
651
652    pathlen = strlen(path);
653    extlen = 0;
654    if (extlist == NULL)
655	extlist = emptyextlist;
656    for (cpp = extlist; *cpp; cpp++) {
657	len = strlen(*cpp);
658	if (len > extlen)
659	    extlen = len;
660    }
661    result = malloc(pathlen + namelen + extlen + 2);
662    if (result == NULL)
663	return (NULL);
664    bcopy(path, result, pathlen);
665    if (pathlen > 0 && result[pathlen - 1] != '/')
666	result[pathlen++] = '/';
667    cp = result + pathlen;
668    bcopy(name, cp, namelen);
669    cp += namelen;
670    for (cpp = extlist; *cpp; cpp++) {
671	strcpy(cp, *cpp);
672	if (stat(result, &st) == 0 && S_ISREG(st.st_mode))
673	    return result;
674    }
675    free(result);
676    return NULL;
677}
678
679/*
680 * Check if file name have any qualifiers
681 */
682static int
683file_havepath(const char *name)
684{
685    const char		*cp;
686
687    archsw.arch_getdev(NULL, name, &cp);
688    return (cp != name || strchr(name, '/') != NULL);
689}
690
691/*
692 * Attempt to find the file (name) on the module searchpath.
693 * If (name) is qualified in any way, we simply check it and
694 * return it or NULL.  If it is not qualified, then we attempt
695 * to construct a path using entries in the environment variable
696 * module_path.
697 *
698 * The path we return a pointer to need never be freed, as we manage
699 * it internally.
700 */
701static char *
702file_search(const char *name, char **extlist)
703{
704    struct moduledir	*mdp;
705    struct stat		sb;
706    char		*result;
707    int			namelen;
708
709    /* Don't look for nothing */
710    if (name == NULL)
711	return(NULL);
712
713    if (*name == 0)
714	return(strdup(name));
715
716    if (file_havepath(name)) {
717	/* Qualified, so just see if it exists */
718	if (stat(name, &sb) == 0)
719	    return(strdup(name));
720	return(NULL);
721    }
722    moduledir_rebuild();
723    result = NULL;
724    namelen = strlen(name);
725    STAILQ_FOREACH(mdp, &moduledir_list, d_link) {
726	result = file_lookup(mdp->d_path, name, namelen, extlist);
727	if (result)
728	    break;
729    }
730    return(result);
731}
732
733#define	INT_ALIGN(base, ptr)	ptr = \
734	(base) + (((ptr) - (base) + sizeof(int) - 1) & ~(sizeof(int) - 1))
735
736static char *
737mod_search_hints(struct moduledir *mdp, const char *modname,
738	struct mod_depend *verinfo)
739{
740    u_char	*cp, *recptr, *bufend, *best;
741    char	*result;
742    int		*intp, bestver, blen, clen, found, ival, modnamelen, reclen;
743
744    moduledir_readhints(mdp);
745    modnamelen = strlen(modname);
746    found = 0;
747    result = NULL;
748    bestver = 0;
749    if (mdp->d_hints == NULL)
750	goto bad;
751    recptr = mdp->d_hints;
752    bufend = recptr + mdp->d_hintsz;
753    clen = blen = 0;
754    best = cp = NULL;
755    while (recptr < bufend && !found) {
756	intp = (int*)recptr;
757	reclen = *intp++;
758	ival = *intp++;
759	cp = (char*)intp;
760	switch (ival) {
761	case MDT_VERSION:
762	    clen = *cp++;
763	    if (clen != modnamelen || bcmp(cp, modname, clen) != 0)
764		break;
765	    cp += clen;
766	    INT_ALIGN(mdp->d_hints, cp);
767	    ival = *(int*)cp;
768	    cp += sizeof(int);
769	    clen = *cp++;
770	    if (verinfo == NULL || ival == verinfo->md_ver_preferred) {
771		found = 1;
772		break;
773	    }
774	    if (ival >= verinfo->md_ver_minimum &&
775		ival <= verinfo->md_ver_maximum &&
776		ival > bestver) {
777		bestver = ival;
778		best = cp;
779		blen = clen;
780	    }
781	    break;
782	default:
783	    break;
784	}
785	recptr += reclen + sizeof(int);
786    }
787    /*
788     * Finally check if KLD is in the place
789     */
790    if (found)
791	result = file_lookup(mdp->d_path, cp, clen, NULL);
792    else if (best)
793	result = file_lookup(mdp->d_path, best, blen, NULL);
794bad:
795    /*
796     * If nothing found or hints is absent - fallback to the old way
797     * by using "kldname[.ko]" as module name.
798     */
799    if (!found && !bestver && result == NULL)
800	result = file_lookup(mdp->d_path, modname, modnamelen, kld_ext_list);
801    return result;
802}
803
804/*
805 * Attempt to locate the file containing the module (name)
806 */
807static char *
808mod_searchmodule(char *name, struct mod_depend *verinfo)
809{
810    struct	moduledir *mdp;
811    char	*result;
812
813    moduledir_rebuild();
814    /*
815     * Now we ready to lookup module in the given directories
816     */
817    result = NULL;
818    STAILQ_FOREACH(mdp, &moduledir_list, d_link) {
819	result = mod_search_hints(mdp, name, verinfo);
820	if (result)
821	    break;
822    }
823
824    return(result);
825}
826
827int
828file_addmodule(struct preloaded_file *fp, char *modname, int version,
829	struct kernel_module **newmp)
830{
831    struct kernel_module *mp;
832    struct mod_depend mdepend;
833
834    bzero(&mdepend, sizeof(mdepend));
835    mdepend.md_ver_preferred = version;
836    mp = file_findmodule(fp, modname, &mdepend);
837    if (mp)
838	return (EEXIST);
839    mp = malloc(sizeof(struct kernel_module));
840    if (mp == NULL)
841	return (ENOMEM);
842    bzero(mp, sizeof(struct kernel_module));
843    mp->m_name = strdup(modname);
844    mp->m_version = version;
845    mp->m_fp = fp;
846    mp->m_next = fp->f_modules;
847    fp->f_modules = mp;
848    if (newmp)
849	*newmp = mp;
850    return (0);
851}
852
853/*
854 * Throw a file away
855 */
856void
857file_discard(struct preloaded_file *fp)
858{
859    struct file_metadata	*md, *md1;
860    struct kernel_module	*mp, *mp1;
861    if (fp == NULL)
862	return;
863    md = fp->f_metadata;
864    while (md) {
865	md1 = md;
866	md = md->md_next;
867	free(md1);
868    }
869    mp = fp->f_modules;
870    while (mp) {
871	if (mp->m_name)
872	    free(mp->m_name);
873	mp1 = mp;
874	mp = mp->m_next;
875	free(mp1);
876    }
877    if (fp->f_name != NULL)
878	free(fp->f_name);
879    if (fp->f_type != NULL)
880        free(fp->f_type);
881    if (fp->f_args != NULL)
882        free(fp->f_args);
883    free(fp);
884}
885
886/*
887 * Allocate a new file; must be used instead of malloc()
888 * to ensure safe initialisation.
889 */
890struct preloaded_file *
891file_alloc(void)
892{
893    struct preloaded_file	*fp;
894
895    if ((fp = malloc(sizeof(struct preloaded_file))) != NULL) {
896	bzero(fp, sizeof(struct preloaded_file));
897    }
898    return (fp);
899}
900
901/*
902 * Add a module to the chain
903 */
904static void
905file_insert_tail(struct preloaded_file *fp)
906{
907    struct preloaded_file	*cm;
908
909    /* Append to list of loaded file */
910    fp->f_next = NULL;
911    if (preloaded_files == NULL) {
912	preloaded_files = fp;
913    } else {
914	for (cm = preloaded_files; cm->f_next != NULL; cm = cm->f_next)
915	    ;
916	cm->f_next = fp;
917    }
918}
919
920static char *
921moduledir_fullpath(struct moduledir *mdp, const char *fname)
922{
923    char *cp;
924
925    cp = malloc(strlen(mdp->d_path) + strlen(fname) + 2);
926    if (cp == NULL)
927	return NULL;
928    strcpy(cp, mdp->d_path);
929    strcat(cp, "/");
930    strcat(cp, fname);
931    return (cp);
932}
933
934/*
935 * Read linker.hints file into memory performing some sanity checks.
936 */
937static void
938moduledir_readhints(struct moduledir *mdp)
939{
940    struct stat	st;
941    char	*path;
942    int		fd, size, version;
943
944    if (mdp->d_hints != NULL || (mdp->d_flags & MDIR_NOHINTS))
945	return;
946    path = moduledir_fullpath(mdp, "linker.hints");
947    if (stat(path, &st) != 0 ||
948	st.st_size < (ssize_t)(sizeof(version) + sizeof(int)) ||
949	st.st_size > 100 * 1024 || (fd = open(path, O_RDONLY)) < 0) {
950	free(path);
951	mdp->d_flags |= MDIR_NOHINTS;
952	return;
953    }
954    free(path);
955    size = read(fd, &version, sizeof(version));
956    if (size != sizeof(version) || version != LINKER_HINTS_VERSION)
957	goto bad;
958    size = st.st_size - size;
959    mdp->d_hints = malloc(size);
960    if (mdp->d_hints == NULL)
961	goto bad;
962    if (read(fd, mdp->d_hints, size) != size)
963	goto bad;
964    mdp->d_hintsz = size;
965    close(fd);
966    return;
967bad:
968    close(fd);
969    if (mdp->d_hints) {
970	free(mdp->d_hints);
971	mdp->d_hints = NULL;
972    }
973    mdp->d_flags |= MDIR_NOHINTS;
974    return;
975}
976
977/*
978 * Extract directories from the ';' separated list, remove duplicates.
979 */
980static void
981moduledir_rebuild(void)
982{
983    struct	moduledir *mdp, *mtmp;
984    const char	*path, *cp, *ep;
985    size_t	cplen;
986
987    path = getenv("module_path");
988    if (path == NULL)
989	path = default_searchpath;
990    /*
991     * Rebuild list of module directories if it changed
992     */
993    STAILQ_FOREACH(mdp, &moduledir_list, d_link)
994	mdp->d_flags |= MDIR_REMOVED;
995
996    for (ep = path; *ep != 0;  ep++) {
997	cp = ep;
998	for (; *ep != 0 && *ep != ';'; ep++)
999	    ;
1000	/*
1001	 * Ignore trailing slashes
1002	 */
1003	for (cplen = ep - cp; cplen > 1 && cp[cplen - 1] == '/'; cplen--)
1004	    ;
1005	STAILQ_FOREACH(mdp, &moduledir_list, d_link) {
1006	    if (strlen(mdp->d_path) != cplen ||	bcmp(cp, mdp->d_path, cplen) != 0)
1007		continue;
1008	    mdp->d_flags &= ~MDIR_REMOVED;
1009	    break;
1010	}
1011	if (mdp == NULL) {
1012	    mdp = malloc(sizeof(*mdp) + cplen + 1);
1013	    if (mdp == NULL)
1014		return;
1015	    mdp->d_path = (char*)(mdp + 1);
1016	    bcopy(cp, mdp->d_path, cplen);
1017	    mdp->d_path[cplen] = 0;
1018	    mdp->d_hints = NULL;
1019	    mdp->d_flags = 0;
1020	    STAILQ_INSERT_TAIL(&moduledir_list, mdp, d_link);
1021	}
1022	if (*ep == 0)
1023	    break;
1024    }
1025    /*
1026     * Delete unused directories if any
1027     */
1028    mdp = STAILQ_FIRST(&moduledir_list);
1029    while (mdp) {
1030	if ((mdp->d_flags & MDIR_REMOVED) == 0) {
1031	    mdp = STAILQ_NEXT(mdp, d_link);
1032	} else {
1033	    if (mdp->d_hints)
1034		free(mdp->d_hints);
1035	    mtmp = mdp;
1036	    mdp = STAILQ_NEXT(mdp, d_link);
1037	    STAILQ_REMOVE(&moduledir_list, mtmp, moduledir, d_link);
1038	    free(mtmp);
1039	}
1040    }
1041    return;
1042}
1043