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