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