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