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