]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - sys/boot/common/module.c
MFC 239054,239057,239058,239060,239066,239067,239068,239070,239073,
[FreeBSD/stable/9.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             last_file_format = i = 0;
293             fp = NULL;
294             continue;
295         }
296         if (error == EFTYPE)
297             continue;           /* Unknown to this handler? */
298         if (error) {
299             sprintf(command_errbuf, "can't load file '%s': %s",
300                 filename, strerror(error));
301             break;
302         }
303     }
304     return (error);
305 }
306
307 static int
308 file_load_dependencies(struct preloaded_file *base_file)
309 {
310     struct file_metadata *md;
311     struct preloaded_file *fp;
312     struct mod_depend *verinfo;
313     struct kernel_module *mp;
314     char *dmodname;
315     int error;
316
317     md = file_findmetadata(base_file, MODINFOMD_DEPLIST);
318     if (md == NULL)
319         return (0);
320     error = 0;
321     do {
322         verinfo = (struct mod_depend*)md->md_data;
323         dmodname = (char *)(verinfo + 1);
324         if (file_findmodule(NULL, dmodname, verinfo) == NULL) {
325             printf("loading required module '%s'\n", dmodname);
326             error = mod_load(dmodname, verinfo, 0, NULL);
327             if (error)
328                 break;
329             /*
330              * If module loaded via kld name which isn't listed
331              * in the linker.hints file, we should check if it have
332              * required version.
333              */
334             mp = file_findmodule(NULL, dmodname, verinfo);
335             if (mp == NULL) {
336                 sprintf(command_errbuf, "module '%s' exists but with wrong version",
337                     dmodname);
338                 error = ENOENT;
339                 break;
340             }
341         }
342         md = metadata_next(md, MODINFOMD_DEPLIST);
343     } while (md);
344     if (!error)
345         return (0);
346     /* Load failed; discard everything */
347     while (base_file != NULL) {
348         fp = base_file;
349         base_file = base_file->f_next;
350         file_discard(fp);
351     }
352     return (error);
353 }
354 /*
355  * We've been asked to load (name) as (type), so just suck it in,
356  * no arguments or anything.
357  */
358 int
359 file_loadraw(char *type, char *name)
360 {
361     struct preloaded_file       *fp;
362     char                        *cp;
363     int                         fd, got;
364     vm_offset_t                 laddr;
365
366     /* We can't load first */
367     if ((file_findfile(NULL, NULL)) == NULL) {
368         command_errmsg = "can't load file before kernel";
369         return(CMD_ERROR);
370     }
371
372     /* locate the file on the load path */
373     cp = file_search(name, NULL);
374     if (cp == NULL) {
375         sprintf(command_errbuf, "can't find '%s'", name);
376         return(CMD_ERROR);
377     }
378     name = cp;
379
380     if ((fd = open(name, O_RDONLY)) < 0) {
381         sprintf(command_errbuf, "can't open '%s': %s", name, strerror(errno));
382         free(name);
383         return(CMD_ERROR);
384     }
385
386     if (archsw.arch_loadaddr != NULL)
387         loadaddr = archsw.arch_loadaddr(LOAD_RAW, name, loadaddr);
388
389     laddr = loadaddr;
390     for (;;) {
391         /* read in 4k chunks; size is not really important */
392         got = archsw.arch_readin(fd, laddr, 4096);
393         if (got == 0)                           /* end of file */
394             break;
395         if (got < 0) {                          /* error */
396             sprintf(command_errbuf, "error reading '%s': %s", name, strerror(errno));
397             free(name);
398             close(fd);
399             return(CMD_ERROR);
400         }
401         laddr += got;
402     }
403     
404     /* Looks OK so far; create & populate control structure */
405     fp = file_alloc();
406     fp->f_name = strdup(name);
407     fp->f_type = strdup(type);
408     fp->f_args = NULL;
409     fp->f_metadata = NULL;
410     fp->f_loader = -1;
411     fp->f_addr = loadaddr;
412     fp->f_size = laddr - loadaddr;
413
414     /* recognise space consumption */
415     loadaddr = laddr;
416
417     /* Add to the list of loaded files */
418     file_insert_tail(fp);
419     close(fd);
420     return(CMD_OK);
421 }
422
423 /*
424  * Load the module (name), pass it (argc),(argv), add container file
425  * to the list of loaded files.
426  * If module is already loaded just assign new argc/argv.
427  */
428 int
429 mod_load(char *modname, struct mod_depend *verinfo, int argc, char *argv[])
430 {
431     struct kernel_module        *mp;
432     int                         err;
433     char                        *filename;
434
435     if (file_havepath(modname)) {
436         printf("Warning: mod_load() called instead of mod_loadkld() for module '%s'\n", modname);
437         return (mod_loadkld(modname, argc, argv));
438     }
439     /* see if module is already loaded */
440     mp = file_findmodule(NULL, modname, verinfo);
441     if (mp) {
442 #ifdef moduleargs
443         if (mp->m_args)
444             free(mp->m_args);
445         mp->m_args = unargv(argc, argv);
446 #endif
447         sprintf(command_errbuf, "warning: module '%s' already loaded", mp->m_name);
448         return (0);
449     }
450     /* locate file with the module on the search path */
451     filename = mod_searchmodule(modname, verinfo);
452     if (filename == NULL) {
453         sprintf(command_errbuf, "can't find '%s'", modname);
454         return (ENOENT);
455     }
456     err = mod_loadkld(filename, argc, argv);
457     return (err);
458 }
459
460 /*
461  * Load specified KLD. If path is omitted, then try to locate it via
462  * search path.
463  */
464 int
465 mod_loadkld(const char *kldname, int argc, char *argv[])
466 {
467     struct preloaded_file       *fp, *last_file;
468     int                         err;
469     char                        *filename;
470
471     /*
472      * Get fully qualified KLD name
473      */
474     filename = file_search(kldname, kld_ext_list);
475     if (filename == NULL) {
476         sprintf(command_errbuf, "can't find '%s'", kldname);
477         return (ENOENT);
478     }
479     /* 
480      * Check if KLD already loaded
481      */
482     fp = file_findfile(filename, NULL);
483     if (fp) {
484         sprintf(command_errbuf, "warning: KLD '%s' already loaded", filename);
485         free(filename);
486         return (0);
487     }
488     for (last_file = preloaded_files; 
489          last_file != NULL && last_file->f_next != NULL;
490          last_file = last_file->f_next)
491         ;
492
493     do {
494         err = file_load(filename, loadaddr, &fp);
495         if (err)
496             break;
497         fp->f_args = unargv(argc, argv);
498         loadaddr = fp->f_addr + fp->f_size;
499         file_insert_tail(fp);           /* Add to the list of loaded files */
500         if (file_load_dependencies(fp) != 0) {
501             err = ENOENT;
502             last_file->f_next = NULL;
503             loadaddr = last_file->f_addr + last_file->f_size;
504             fp = NULL;
505             break;
506         }
507     } while(0);
508     if (err == EFTYPE)
509         sprintf(command_errbuf, "don't know how to load module '%s'", filename);
510     if (err && fp)
511         file_discard(fp);
512     free(filename);
513     return (err);
514 }
515
516 /*
517  * Find a file matching (name) and (type).
518  * NULL may be passed as a wildcard to either.
519  */
520 struct preloaded_file *
521 file_findfile(char *name, char *type)
522 {
523     struct preloaded_file *fp;
524
525     for (fp = preloaded_files; fp != NULL; fp = fp->f_next) {
526         if (((name == NULL) || !strcmp(name, fp->f_name)) &&
527             ((type == NULL) || !strcmp(type, fp->f_type)))
528             break;
529     }
530     return (fp);
531 }
532
533 /*
534  * Find a module matching (name) inside of given file.
535  * NULL may be passed as a wildcard.
536  */
537 struct kernel_module *
538 file_findmodule(struct preloaded_file *fp, char *modname,
539         struct mod_depend *verinfo)
540 {
541     struct kernel_module *mp, *best;
542     int bestver, mver;
543
544     if (fp == NULL) {
545         for (fp = preloaded_files; fp; fp = fp->f_next) {
546             mp = file_findmodule(fp, modname, verinfo);
547             if (mp)
548                 return (mp);
549         }
550         return (NULL);
551     }
552     best = NULL;
553     bestver = 0;
554     for (mp = fp->f_modules; mp; mp = mp->m_next) {
555         if (strcmp(modname, mp->m_name) == 0) {
556             if (verinfo == NULL)
557                 return (mp);
558             mver = mp->m_version;
559             if (mver == verinfo->md_ver_preferred)
560                 return (mp);
561             if (mver >= verinfo->md_ver_minimum && 
562                 mver <= verinfo->md_ver_maximum &&
563                 mver > bestver) {
564                 best = mp;
565                 bestver = mver;
566             }
567         }
568     }
569     return (best);
570 }
571 /*
572  * Make a copy of (size) bytes of data from (p), and associate them as
573  * metadata of (type) to the module (mp).
574  */
575 void
576 file_addmetadata(struct preloaded_file *fp, int type, size_t size, void *p)
577 {
578     struct file_metadata        *md;
579
580     md = malloc(sizeof(struct file_metadata) - sizeof(md->md_data) + size);
581     md->md_size = size;
582     md->md_type = type;
583     bcopy(p, md->md_data, size);
584     md->md_next = fp->f_metadata;
585     fp->f_metadata = md;
586 }
587
588 /*
589  * Find a metadata object of (type) associated with the file (fp)
590  */
591 struct file_metadata *
592 file_findmetadata(struct preloaded_file *fp, int type)
593 {
594     struct file_metadata *md;
595
596     for (md = fp->f_metadata; md != NULL; md = md->md_next)
597         if (md->md_type == type)
598             break;
599     return(md);
600 }
601
602 struct file_metadata *
603 metadata_next(struct file_metadata *md, int type)
604 {
605     if (md == NULL)
606         return (NULL);
607     while((md = md->md_next) != NULL)
608         if (md->md_type == type)
609             break;
610     return (md);
611 }
612
613 static char *emptyextlist[] = { "", NULL };
614
615 /*
616  * Check if the given file is in place and return full path to it.
617  */
618 static char *
619 file_lookup(const char *path, const char *name, int namelen, char **extlist)
620 {
621     struct stat st;
622     char        *result, *cp, **cpp;
623     int         pathlen, extlen, len;
624
625     pathlen = strlen(path);
626     extlen = 0;
627     if (extlist == NULL)
628         extlist = emptyextlist;
629     for (cpp = extlist; *cpp; cpp++) {
630         len = strlen(*cpp);
631         if (len > extlen)
632             extlen = len;
633     }
634     result = malloc(pathlen + namelen + extlen + 2);
635     if (result == NULL)
636         return (NULL);
637     bcopy(path, result, pathlen);
638     if (pathlen > 0 && result[pathlen - 1] != '/')
639         result[pathlen++] = '/';
640     cp = result + pathlen;
641     bcopy(name, cp, namelen);
642     cp += namelen;
643     for (cpp = extlist; *cpp; cpp++) {
644         strcpy(cp, *cpp);
645         if (stat(result, &st) == 0 && S_ISREG(st.st_mode))
646             return result;
647     }
648     free(result);
649     return NULL;
650 }
651
652 /*
653  * Check if file name have any qualifiers
654  */
655 static int
656 file_havepath(const char *name)
657 {
658     const char          *cp;
659
660     archsw.arch_getdev(NULL, name, &cp);
661     return (cp != name || strchr(name, '/') != NULL);
662 }
663
664 /*
665  * Attempt to find the file (name) on the module searchpath.
666  * If (name) is qualified in any way, we simply check it and
667  * return it or NULL.  If it is not qualified, then we attempt
668  * to construct a path using entries in the environment variable
669  * module_path.
670  *
671  * The path we return a pointer to need never be freed, as we manage
672  * it internally.
673  */
674 static char *
675 file_search(const char *name, char **extlist)
676 {
677     struct moduledir    *mdp;
678     struct stat         sb;
679     char                *result;
680     int                 namelen;
681
682     /* Don't look for nothing */
683     if (name == NULL)
684         return(NULL);
685
686     if (*name == 0)
687         return(strdup(name));
688
689     if (file_havepath(name)) {
690         /* Qualified, so just see if it exists */
691         if (stat(name, &sb) == 0)
692             return(strdup(name));
693         return(NULL);
694     }
695     moduledir_rebuild();
696     result = NULL;
697     namelen = strlen(name);
698     STAILQ_FOREACH(mdp, &moduledir_list, d_link) {
699         result = file_lookup(mdp->d_path, name, namelen, extlist);
700         if (result)
701             break;
702     }
703     return(result);
704 }
705
706 #define INT_ALIGN(base, ptr)    ptr = \
707         (base) + (((ptr) - (base) + sizeof(int) - 1) & ~(sizeof(int) - 1))
708
709 static char *
710 mod_search_hints(struct moduledir *mdp, const char *modname,
711         struct mod_depend *verinfo)
712 {
713     u_char      *cp, *recptr, *bufend, *best;
714     char        *result;
715     int         *intp, bestver, blen, clen, found, ival, modnamelen, reclen;
716
717     moduledir_readhints(mdp);
718     modnamelen = strlen(modname);
719     found = 0;
720     result = NULL;
721     bestver = 0;
722     if (mdp->d_hints == NULL)
723         goto bad;
724     recptr = mdp->d_hints;
725     bufend = recptr + mdp->d_hintsz;
726     clen = blen = 0;
727     best = cp = NULL;
728     while (recptr < bufend && !found) {
729         intp = (int*)recptr;
730         reclen = *intp++;
731         ival = *intp++;
732         cp = (char*)intp;
733         switch (ival) {
734         case MDT_VERSION:
735             clen = *cp++;
736             if (clen != modnamelen || bcmp(cp, modname, clen) != 0)
737                 break;
738             cp += clen;
739             INT_ALIGN(mdp->d_hints, cp);
740             ival = *(int*)cp;
741             cp += sizeof(int);
742             clen = *cp++;
743             if (verinfo == NULL || ival == verinfo->md_ver_preferred) {
744                 found = 1;
745                 break;
746             }
747             if (ival >= verinfo->md_ver_minimum && 
748                 ival <= verinfo->md_ver_maximum &&
749                 ival > bestver) {
750                 bestver = ival;
751                 best = cp;
752                 blen = clen;
753             }
754             break;
755         default:
756             break;
757         }
758         recptr += reclen + sizeof(int);
759     }
760     /*
761      * Finally check if KLD is in the place
762      */
763     if (found)
764         result = file_lookup(mdp->d_path, cp, clen, NULL);
765     else if (best)
766         result = file_lookup(mdp->d_path, best, blen, NULL);
767 bad:
768     /*
769      * If nothing found or hints is absent - fallback to the old way
770      * by using "kldname[.ko]" as module name.
771      */
772     if (!found && !bestver && result == NULL)
773         result = file_lookup(mdp->d_path, modname, modnamelen, kld_ext_list);
774     return result;
775 }
776
777 /*
778  * Attempt to locate the file containing the module (name)
779  */
780 static char *
781 mod_searchmodule(char *name, struct mod_depend *verinfo)
782 {
783     struct      moduledir *mdp;
784     char        *result;
785
786     moduledir_rebuild();
787     /*
788      * Now we ready to lookup module in the given directories
789      */
790     result = NULL;
791     STAILQ_FOREACH(mdp, &moduledir_list, d_link) {
792         result = mod_search_hints(mdp, name, verinfo);
793         if (result)
794             break;
795     }
796
797     return(result);
798 }
799
800 int
801 file_addmodule(struct preloaded_file *fp, char *modname, int version,
802         struct kernel_module **newmp)
803 {
804     struct kernel_module *mp;
805     struct mod_depend mdepend;
806
807     bzero(&mdepend, sizeof(mdepend));
808     mdepend.md_ver_preferred = version;
809     mp = file_findmodule(fp, modname, &mdepend);
810     if (mp)
811         return (EEXIST);
812     mp = malloc(sizeof(struct kernel_module));
813     if (mp == NULL)
814         return (ENOMEM);
815     bzero(mp, sizeof(struct kernel_module));
816     mp->m_name = strdup(modname);
817     mp->m_version = version;
818     mp->m_fp = fp;
819     mp->m_next = fp->f_modules;
820     fp->f_modules = mp;
821     if (newmp)
822         *newmp = mp;
823     return (0);
824 }
825
826 /*
827  * Throw a file away
828  */
829 void
830 file_discard(struct preloaded_file *fp)
831 {
832     struct file_metadata        *md, *md1;
833     struct kernel_module        *mp, *mp1;
834     if (fp == NULL)
835         return;
836     md = fp->f_metadata;
837     while (md) {
838         md1 = md;
839         md = md->md_next;
840         free(md1);
841     }
842     mp = fp->f_modules;
843     while (mp) {
844         if (mp->m_name)
845             free(mp->m_name);
846         mp1 = mp;
847         mp = mp->m_next;
848         free(mp1);
849     }   
850     if (fp->f_name != NULL)
851         free(fp->f_name);
852     if (fp->f_type != NULL)
853         free(fp->f_type);
854     if (fp->f_args != NULL)
855         free(fp->f_args);
856     free(fp);
857 }
858
859 /*
860  * Allocate a new file; must be used instead of malloc()
861  * to ensure safe initialisation.
862  */
863 struct preloaded_file *
864 file_alloc(void)
865 {
866     struct preloaded_file       *fp;
867     
868     if ((fp = malloc(sizeof(struct preloaded_file))) != NULL) {
869         bzero(fp, sizeof(struct preloaded_file));
870     }
871     return (fp);
872 }
873
874 /*
875  * Add a module to the chain
876  */
877 static void
878 file_insert_tail(struct preloaded_file *fp)
879 {
880     struct preloaded_file       *cm;
881     
882     /* Append to list of loaded file */
883     fp->f_next = NULL;
884     if (preloaded_files == NULL) {
885         preloaded_files = fp;
886     } else {
887         for (cm = preloaded_files; cm->f_next != NULL; cm = cm->f_next)
888             ;
889         cm->f_next = fp;
890     }
891 }
892
893 static char *
894 moduledir_fullpath(struct moduledir *mdp, const char *fname)
895 {
896     char *cp;
897
898     cp = malloc(strlen(mdp->d_path) + strlen(fname) + 2);
899     if (cp == NULL)
900         return NULL;
901     strcpy(cp, mdp->d_path);
902     strcat(cp, "/");
903     strcat(cp, fname);
904     return (cp);
905 }
906
907 /*
908  * Read linker.hints file into memory performing some sanity checks.
909  */
910 static void
911 moduledir_readhints(struct moduledir *mdp)
912 {
913     struct stat st;
914     char        *path;
915     int         fd, size, version;
916
917     if (mdp->d_hints != NULL || (mdp->d_flags & MDIR_NOHINTS))
918         return;
919     path = moduledir_fullpath(mdp, "linker.hints");
920     if (stat(path, &st) != 0 ||
921         st.st_size < (ssize_t)(sizeof(version) + sizeof(int)) ||
922         st.st_size > 100 * 1024 || (fd = open(path, O_RDONLY)) < 0) {
923         free(path);
924         mdp->d_flags |= MDIR_NOHINTS;
925         return;
926     }
927     free(path);
928     size = read(fd, &version, sizeof(version));
929     if (size != sizeof(version) || version != LINKER_HINTS_VERSION)
930         goto bad;
931     size = st.st_size - size;
932     mdp->d_hints = malloc(size);
933     if (mdp->d_hints == NULL)
934         goto bad;
935     if (read(fd, mdp->d_hints, size) != size)
936         goto bad;
937     mdp->d_hintsz = size;
938     close(fd);
939     return;
940 bad:
941     close(fd);
942     if (mdp->d_hints) {
943         free(mdp->d_hints);
944         mdp->d_hints = NULL;
945     }
946     mdp->d_flags |= MDIR_NOHINTS;
947     return;
948 }
949
950 /*
951  * Extract directories from the ';' separated list, remove duplicates.
952  */
953 static void
954 moduledir_rebuild(void)
955 {
956     struct      moduledir *mdp, *mtmp;
957     const char  *path, *cp, *ep;
958     int         cplen;
959
960     path = getenv("module_path");
961     if (path == NULL)
962         path = default_searchpath;
963     /*
964      * Rebuild list of module directories if it changed
965      */
966     STAILQ_FOREACH(mdp, &moduledir_list, d_link)
967         mdp->d_flags |= MDIR_REMOVED;
968
969     for (ep = path; *ep != 0;  ep++) {
970         cp = ep;
971         for (; *ep != 0 && *ep != ';'; ep++)
972             ;
973         /*
974          * Ignore trailing slashes
975          */
976         for (cplen = ep - cp; cplen > 1 && cp[cplen - 1] == '/'; cplen--)
977             ;
978         STAILQ_FOREACH(mdp, &moduledir_list, d_link) {
979             if (strlen(mdp->d_path) != cplen || bcmp(cp, mdp->d_path, cplen) != 0)
980                 continue;
981             mdp->d_flags &= ~MDIR_REMOVED;
982             break;
983         }
984         if (mdp == NULL) {
985             mdp = malloc(sizeof(*mdp) + cplen + 1);
986             if (mdp == NULL)
987                 return;
988             mdp->d_path = (char*)(mdp + 1);
989             bcopy(cp, mdp->d_path, cplen);
990             mdp->d_path[cplen] = 0;
991             mdp->d_hints = NULL;
992             mdp->d_flags = 0;
993             STAILQ_INSERT_TAIL(&moduledir_list, mdp, d_link);
994         }
995         if (*ep == 0)
996             break;
997     }
998     /*
999      * Delete unused directories if any
1000      */
1001     mdp = STAILQ_FIRST(&moduledir_list);
1002     while (mdp) {
1003         if ((mdp->d_flags & MDIR_REMOVED) == 0) {
1004             mdp = STAILQ_NEXT(mdp, d_link);
1005         } else {
1006             if (mdp->d_hints)
1007                 free(mdp->d_hints);
1008             mtmp = mdp;
1009             mdp = STAILQ_NEXT(mdp, d_link);
1010             STAILQ_REMOVE(&moduledir_list, mtmp, moduledir, d_link);
1011             free(mtmp);
1012         }
1013     }
1014     return;
1015 }