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