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