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