]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/kern_linker.c
MFC r357983:
[FreeBSD/FreeBSD.git] / sys / kern / kern_linker.c
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 1997-2000 Doug Rabson
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31
32 #include "opt_ddb.h"
33 #include "opt_kld.h"
34 #include "opt_hwpmc_hooks.h"
35
36 #include <sys/param.h>
37 #include <sys/kernel.h>
38 #include <sys/systm.h>
39 #include <sys/malloc.h>
40 #include <sys/sysproto.h>
41 #include <sys/sysent.h>
42 #include <sys/priv.h>
43 #include <sys/proc.h>
44 #include <sys/lock.h>
45 #include <sys/mutex.h>
46 #include <sys/sx.h>
47 #include <sys/module.h>
48 #include <sys/mount.h>
49 #include <sys/linker.h>
50 #include <sys/eventhandler.h>
51 #include <sys/fcntl.h>
52 #include <sys/jail.h>
53 #include <sys/libkern.h>
54 #include <sys/namei.h>
55 #include <sys/vnode.h>
56 #include <sys/syscallsubr.h>
57 #include <sys/sysctl.h>
58
59 #ifdef DDB
60 #include <ddb/ddb.h>
61 #endif
62
63 #include <net/vnet.h>
64
65 #include <security/mac/mac_framework.h>
66
67 #include "linker_if.h"
68
69 #ifdef HWPMC_HOOKS
70 #include <sys/pmckern.h>
71 #endif
72
73 #ifdef KLD_DEBUG
74 int kld_debug = 0;
75 SYSCTL_INT(_debug, OID_AUTO, kld_debug, CTLFLAG_RWTUN,
76     &kld_debug, 0, "Set various levels of KLD debug");
77 #endif
78
79 /* These variables are used by kernel debuggers to enumerate loaded files. */
80 const int kld_off_address = offsetof(struct linker_file, address);
81 const int kld_off_filename = offsetof(struct linker_file, filename);
82 const int kld_off_pathname = offsetof(struct linker_file, pathname);
83 const int kld_off_next = offsetof(struct linker_file, link.tqe_next);
84
85 /*
86  * static char *linker_search_path(const char *name, struct mod_depend
87  * *verinfo);
88  */
89 static const char       *linker_basename(const char *path);
90
91 /*
92  * Find a currently loaded file given its filename.
93  */
94 static linker_file_t linker_find_file_by_name(const char* _filename);
95
96 /*
97  * Find a currently loaded file given its file id.
98  */
99 static linker_file_t linker_find_file_by_id(int _fileid);
100
101 /* Metadata from the static kernel */
102 SET_DECLARE(modmetadata_set, struct mod_metadata);
103
104 MALLOC_DEFINE(M_LINKER, "linker", "kernel linker");
105
106 linker_file_t linker_kernel_file;
107
108 static struct sx kld_sx;        /* kernel linker lock */
109
110 /*
111  * Load counter used by clients to determine if a linker file has been
112  * re-loaded. This counter is incremented for each file load.
113  */
114 static int loadcnt;
115
116 static linker_class_list_t classes;
117 static linker_file_list_t linker_files;
118 static int next_file_id = 1;
119 static int linker_no_more_classes = 0;
120
121 #define LINKER_GET_NEXT_FILE_ID(a) do {                                 \
122         linker_file_t lftmp;                                            \
123                                                                         \
124         if (!cold)                                                      \
125                 sx_assert(&kld_sx, SA_XLOCKED);                         \
126 retry:                                                                  \
127         TAILQ_FOREACH(lftmp, &linker_files, link) {                     \
128                 if (next_file_id == lftmp->id) {                        \
129                         next_file_id++;                                 \
130                         goto retry;                                     \
131                 }                                                       \
132         }                                                               \
133         (a) = next_file_id;                                             \
134 } while(0)
135
136
137 /* XXX wrong name; we're looking at version provision tags here, not modules */
138 typedef TAILQ_HEAD(, modlist) modlisthead_t;
139 struct modlist {
140         TAILQ_ENTRY(modlist) link;      /* chain together all modules */
141         linker_file_t   container;
142         const char      *name;
143         int             version;
144 };
145 typedef struct modlist *modlist_t;
146 static modlisthead_t found_modules;
147
148 static int      linker_file_add_dependency(linker_file_t file,
149                     linker_file_t dep);
150 static caddr_t  linker_file_lookup_symbol_internal(linker_file_t file,
151                     const char* name, int deps);
152 static int      linker_load_module(const char *kldname,
153                     const char *modname, struct linker_file *parent,
154                     const struct mod_depend *verinfo, struct linker_file **lfpp);
155 static modlist_t modlist_lookup2(const char *name, const struct mod_depend *verinfo);
156
157 static void
158 linker_init(void *arg)
159 {
160
161         sx_init(&kld_sx, "kernel linker");
162         TAILQ_INIT(&classes);
163         TAILQ_INIT(&linker_files);
164 }
165
166 SYSINIT(linker, SI_SUB_KLD, SI_ORDER_FIRST, linker_init, NULL);
167
168 static void
169 linker_stop_class_add(void *arg)
170 {
171
172         linker_no_more_classes = 1;
173 }
174
175 SYSINIT(linker_class, SI_SUB_KLD, SI_ORDER_ANY, linker_stop_class_add, NULL);
176
177 int
178 linker_add_class(linker_class_t lc)
179 {
180
181         /*
182          * We disallow any class registration past SI_ORDER_ANY
183          * of SI_SUB_KLD.  We bump the reference count to keep the
184          * ops from being freed.
185          */
186         if (linker_no_more_classes == 1)
187                 return (EPERM);
188         kobj_class_compile((kobj_class_t) lc);
189         ((kobj_class_t)lc)->refs++;     /* XXX: kobj_mtx */
190         TAILQ_INSERT_TAIL(&classes, lc, link);
191         return (0);
192 }
193
194 static void
195 linker_file_sysinit(linker_file_t lf)
196 {
197         struct sysinit **start, **stop, **sipp, **xipp, *save;
198
199         KLD_DPF(FILE, ("linker_file_sysinit: calling SYSINITs for %s\n",
200             lf->filename));
201
202         sx_assert(&kld_sx, SA_XLOCKED);
203
204         if (linker_file_lookup_set(lf, "sysinit_set", &start, &stop, NULL) != 0)
205                 return;
206         /*
207          * Perform a bubble sort of the system initialization objects by
208          * their subsystem (primary key) and order (secondary key).
209          *
210          * Since some things care about execution order, this is the operation
211          * which ensures continued function.
212          */
213         for (sipp = start; sipp < stop; sipp++) {
214                 for (xipp = sipp + 1; xipp < stop; xipp++) {
215                         if ((*sipp)->subsystem < (*xipp)->subsystem ||
216                             ((*sipp)->subsystem == (*xipp)->subsystem &&
217                             (*sipp)->order <= (*xipp)->order))
218                                 continue;       /* skip */
219                         save = *sipp;
220                         *sipp = *xipp;
221                         *xipp = save;
222                 }
223         }
224
225         /*
226          * Traverse the (now) ordered list of system initialization tasks.
227          * Perform each task, and continue on to the next task.
228          */
229         sx_xunlock(&kld_sx);
230         mtx_lock(&Giant);
231         for (sipp = start; sipp < stop; sipp++) {
232                 if ((*sipp)->subsystem == SI_SUB_DUMMY)
233                         continue;       /* skip dummy task(s) */
234
235                 /* Call function */
236                 (*((*sipp)->func)) ((*sipp)->udata);
237         }
238         mtx_unlock(&Giant);
239         sx_xlock(&kld_sx);
240 }
241
242 static void
243 linker_file_sysuninit(linker_file_t lf)
244 {
245         struct sysinit **start, **stop, **sipp, **xipp, *save;
246
247         KLD_DPF(FILE, ("linker_file_sysuninit: calling SYSUNINITs for %s\n",
248             lf->filename));
249
250         sx_assert(&kld_sx, SA_XLOCKED);
251
252         if (linker_file_lookup_set(lf, "sysuninit_set", &start, &stop,
253             NULL) != 0)
254                 return;
255
256         /*
257          * Perform a reverse bubble sort of the system initialization objects
258          * by their subsystem (primary key) and order (secondary key).
259          *
260          * Since some things care about execution order, this is the operation
261          * which ensures continued function.
262          */
263         for (sipp = start; sipp < stop; sipp++) {
264                 for (xipp = sipp + 1; xipp < stop; xipp++) {
265                         if ((*sipp)->subsystem > (*xipp)->subsystem ||
266                             ((*sipp)->subsystem == (*xipp)->subsystem &&
267                             (*sipp)->order >= (*xipp)->order))
268                                 continue;       /* skip */
269                         save = *sipp;
270                         *sipp = *xipp;
271                         *xipp = save;
272                 }
273         }
274
275         /*
276          * Traverse the (now) ordered list of system initialization tasks.
277          * Perform each task, and continue on to the next task.
278          */
279         sx_xunlock(&kld_sx);
280         mtx_lock(&Giant);
281         for (sipp = start; sipp < stop; sipp++) {
282                 if ((*sipp)->subsystem == SI_SUB_DUMMY)
283                         continue;       /* skip dummy task(s) */
284
285                 /* Call function */
286                 (*((*sipp)->func)) ((*sipp)->udata);
287         }
288         mtx_unlock(&Giant);
289         sx_xlock(&kld_sx);
290 }
291
292 static void
293 linker_file_register_sysctls(linker_file_t lf, bool enable)
294 {
295         struct sysctl_oid **start, **stop, **oidp;
296
297         KLD_DPF(FILE,
298             ("linker_file_register_sysctls: registering SYSCTLs for %s\n",
299             lf->filename));
300
301         sx_assert(&kld_sx, SA_XLOCKED);
302
303         if (linker_file_lookup_set(lf, "sysctl_set", &start, &stop, NULL) != 0)
304                 return;
305
306         sx_xunlock(&kld_sx);
307         sysctl_wlock();
308         for (oidp = start; oidp < stop; oidp++) {
309                 if (enable)
310                         sysctl_register_oid(*oidp);
311                 else
312                         sysctl_register_disabled_oid(*oidp);
313         }
314         sysctl_wunlock();
315         sx_xlock(&kld_sx);
316 }
317
318 static void
319 linker_file_enable_sysctls(linker_file_t lf)
320 {
321         struct sysctl_oid **start, **stop, **oidp;
322
323         KLD_DPF(FILE,
324             ("linker_file_enable_sysctls: enable SYSCTLs for %s\n",
325             lf->filename));
326
327         sx_assert(&kld_sx, SA_XLOCKED);
328
329         if (linker_file_lookup_set(lf, "sysctl_set", &start, &stop, NULL) != 0)
330                 return;
331
332         sx_xunlock(&kld_sx);
333         sysctl_wlock();
334         for (oidp = start; oidp < stop; oidp++)
335                 sysctl_enable_oid(*oidp);
336         sysctl_wunlock();
337         sx_xlock(&kld_sx);
338 }
339
340 static void
341 linker_file_unregister_sysctls(linker_file_t lf)
342 {
343         struct sysctl_oid **start, **stop, **oidp;
344
345         KLD_DPF(FILE, ("linker_file_unregister_sysctls: unregistering SYSCTLs"
346             " for %s\n", lf->filename));
347
348         sx_assert(&kld_sx, SA_XLOCKED);
349
350         if (linker_file_lookup_set(lf, "sysctl_set", &start, &stop, NULL) != 0)
351                 return;
352
353         sx_xunlock(&kld_sx);
354         sysctl_wlock();
355         for (oidp = start; oidp < stop; oidp++)
356                 sysctl_unregister_oid(*oidp);
357         sysctl_wunlock();
358         sx_xlock(&kld_sx);
359 }
360
361 static int
362 linker_file_register_modules(linker_file_t lf)
363 {
364         struct mod_metadata **start, **stop, **mdp;
365         const moduledata_t *moddata;
366         int first_error, error;
367
368         KLD_DPF(FILE, ("linker_file_register_modules: registering modules"
369             " in %s\n", lf->filename));
370
371         sx_assert(&kld_sx, SA_XLOCKED);
372
373         if (linker_file_lookup_set(lf, "modmetadata_set", &start,
374             &stop, NULL) != 0) {
375                 /*
376                  * This fallback should be unnecessary, but if we get booted
377                  * from boot2 instead of loader and we are missing our
378                  * metadata then we have to try the best we can.
379                  */
380                 if (lf == linker_kernel_file) {
381                         start = SET_BEGIN(modmetadata_set);
382                         stop = SET_LIMIT(modmetadata_set);
383                 } else
384                         return (0);
385         }
386         first_error = 0;
387         for (mdp = start; mdp < stop; mdp++) {
388                 if ((*mdp)->md_type != MDT_MODULE)
389                         continue;
390                 moddata = (*mdp)->md_data;
391                 KLD_DPF(FILE, ("Registering module %s in %s\n",
392                     moddata->name, lf->filename));
393                 error = module_register(moddata, lf);
394                 if (error) {
395                         printf("Module %s failed to register: %d\n",
396                             moddata->name, error);
397                         if (first_error == 0)
398                                 first_error = error;
399                 }
400         }
401         return (first_error);
402 }
403
404 static void
405 linker_init_kernel_modules(void)
406 {
407
408         sx_xlock(&kld_sx);
409         linker_file_register_modules(linker_kernel_file);
410         sx_xunlock(&kld_sx);
411 }
412
413 SYSINIT(linker_kernel, SI_SUB_KLD, SI_ORDER_ANY, linker_init_kernel_modules,
414     NULL);
415
416 static int
417 linker_load_file(const char *filename, linker_file_t *result)
418 {
419         linker_class_t lc;
420         linker_file_t lf;
421         int foundfile, error, modules;
422
423         /* Refuse to load modules if securelevel raised */
424         if (prison0.pr_securelevel > 0)
425                 return (EPERM);
426
427         sx_assert(&kld_sx, SA_XLOCKED);
428         lf = linker_find_file_by_name(filename);
429         if (lf) {
430                 KLD_DPF(FILE, ("linker_load_file: file %s is already loaded,"
431                     " incrementing refs\n", filename));
432                 *result = lf;
433                 lf->refs++;
434                 return (0);
435         }
436         foundfile = 0;
437         error = 0;
438
439         /*
440          * We do not need to protect (lock) classes here because there is
441          * no class registration past startup (SI_SUB_KLD, SI_ORDER_ANY)
442          * and there is no class deregistration mechanism at this time.
443          */
444         TAILQ_FOREACH(lc, &classes, link) {
445                 KLD_DPF(FILE, ("linker_load_file: trying to load %s\n",
446                     filename));
447                 error = LINKER_LOAD_FILE(lc, filename, &lf);
448                 /*
449                  * If we got something other than ENOENT, then it exists but
450                  * we cannot load it for some other reason.
451                  */
452                 if (error != ENOENT)
453                         foundfile = 1;
454                 if (lf) {
455                         error = linker_file_register_modules(lf);
456                         if (error == EEXIST) {
457                                 linker_file_unload(lf, LINKER_UNLOAD_FORCE);
458                                 return (error);
459                         }
460                         modules = !TAILQ_EMPTY(&lf->modules);
461                         linker_file_register_sysctls(lf, false);
462                         linker_file_sysinit(lf);
463                         lf->flags |= LINKER_FILE_LINKED;
464
465                         /*
466                          * If all of the modules in this file failed
467                          * to load, unload the file and return an
468                          * error of ENOEXEC.
469                          */
470                         if (modules && TAILQ_EMPTY(&lf->modules)) {
471                                 linker_file_unload(lf, LINKER_UNLOAD_FORCE);
472                                 return (ENOEXEC);
473                         }
474                         linker_file_enable_sysctls(lf);
475                         EVENTHANDLER_INVOKE(kld_load, lf);
476                         *result = lf;
477                         return (0);
478                 }
479         }
480         /*
481          * Less than ideal, but tells the user whether it failed to load or
482          * the module was not found.
483          */
484         if (foundfile) {
485
486                 /*
487                  * If the file type has not been recognized by the last try
488                  * printout a message before to fail.
489                  */
490                 if (error == ENOSYS)
491                         printf("%s: %s - unsupported file type\n",
492                             __func__, filename);
493
494                 /*
495                  * Format not recognized or otherwise unloadable.
496                  * When loading a module that is statically built into
497                  * the kernel EEXIST percolates back up as the return
498                  * value.  Preserve this so that apps like sysinstall
499                  * can recognize this special case and not post bogus
500                  * dialog boxes.
501                  */
502                 if (error != EEXIST)
503                         error = ENOEXEC;
504         } else
505                 error = ENOENT;         /* Nothing found */
506         return (error);
507 }
508
509 int
510 linker_reference_module(const char *modname, struct mod_depend *verinfo,
511     linker_file_t *result)
512 {
513         modlist_t mod;
514         int error;
515
516         sx_xlock(&kld_sx);
517         if ((mod = modlist_lookup2(modname, verinfo)) != NULL) {
518                 *result = mod->container;
519                 (*result)->refs++;
520                 sx_xunlock(&kld_sx);
521                 return (0);
522         }
523
524         error = linker_load_module(NULL, modname, NULL, verinfo, result);
525         sx_xunlock(&kld_sx);
526         return (error);
527 }
528
529 int
530 linker_release_module(const char *modname, struct mod_depend *verinfo,
531     linker_file_t lf)
532 {
533         modlist_t mod;
534         int error;
535
536         sx_xlock(&kld_sx);
537         if (lf == NULL) {
538                 KASSERT(modname != NULL,
539                     ("linker_release_module: no file or name"));
540                 mod = modlist_lookup2(modname, verinfo);
541                 if (mod == NULL) {
542                         sx_xunlock(&kld_sx);
543                         return (ESRCH);
544                 }
545                 lf = mod->container;
546         } else
547                 KASSERT(modname == NULL && verinfo == NULL,
548                     ("linker_release_module: both file and name"));
549         error = linker_file_unload(lf, LINKER_UNLOAD_NORMAL);
550         sx_xunlock(&kld_sx);
551         return (error);
552 }
553
554 static linker_file_t
555 linker_find_file_by_name(const char *filename)
556 {
557         linker_file_t lf;
558         char *koname;
559
560         koname = malloc(strlen(filename) + 4, M_LINKER, M_WAITOK);
561         sprintf(koname, "%s.ko", filename);
562
563         sx_assert(&kld_sx, SA_XLOCKED);
564         TAILQ_FOREACH(lf, &linker_files, link) {
565                 if (strcmp(lf->filename, koname) == 0)
566                         break;
567                 if (strcmp(lf->filename, filename) == 0)
568                         break;
569         }
570         free(koname, M_LINKER);
571         return (lf);
572 }
573
574 static linker_file_t
575 linker_find_file_by_id(int fileid)
576 {
577         linker_file_t lf;
578
579         sx_assert(&kld_sx, SA_XLOCKED);
580         TAILQ_FOREACH(lf, &linker_files, link)
581                 if (lf->id == fileid && lf->flags & LINKER_FILE_LINKED)
582                         break;
583         return (lf);
584 }
585
586 int
587 linker_file_foreach(linker_predicate_t *predicate, void *context)
588 {
589         linker_file_t lf;
590         int retval = 0;
591
592         sx_xlock(&kld_sx);
593         TAILQ_FOREACH(lf, &linker_files, link) {
594                 retval = predicate(lf, context);
595                 if (retval != 0)
596                         break;
597         }
598         sx_xunlock(&kld_sx);
599         return (retval);
600 }
601
602 linker_file_t
603 linker_make_file(const char *pathname, linker_class_t lc)
604 {
605         linker_file_t lf;
606         const char *filename;
607
608         if (!cold)
609                 sx_assert(&kld_sx, SA_XLOCKED);
610         filename = linker_basename(pathname);
611
612         KLD_DPF(FILE, ("linker_make_file: new file, filename='%s' for pathname='%s'\n", filename, pathname));
613         lf = (linker_file_t)kobj_create((kobj_class_t)lc, M_LINKER, M_WAITOK);
614         if (lf == NULL)
615                 return (NULL);
616         lf->ctors_addr = 0;
617         lf->ctors_size = 0;
618         lf->refs = 1;
619         lf->userrefs = 0;
620         lf->flags = 0;
621         lf->filename = strdup(filename, M_LINKER);
622         lf->pathname = strdup(pathname, M_LINKER);
623         LINKER_GET_NEXT_FILE_ID(lf->id);
624         lf->ndeps = 0;
625         lf->deps = NULL;
626         lf->loadcnt = ++loadcnt;
627 #ifdef __arm__
628         lf->exidx_addr = 0;
629         lf->exidx_size = 0;
630 #endif
631         STAILQ_INIT(&lf->common);
632         TAILQ_INIT(&lf->modules);
633         TAILQ_INSERT_TAIL(&linker_files, lf, link);
634         return (lf);
635 }
636
637 int
638 linker_file_unload(linker_file_t file, int flags)
639 {
640         module_t mod, next;
641         modlist_t ml, nextml;
642         struct common_symbol *cp;
643         int error, i;
644
645         /* Refuse to unload modules if securelevel raised. */
646         if (prison0.pr_securelevel > 0)
647                 return (EPERM);
648
649         sx_assert(&kld_sx, SA_XLOCKED);
650         KLD_DPF(FILE, ("linker_file_unload: lf->refs=%d\n", file->refs));
651
652         /* Easy case of just dropping a reference. */
653         if (file->refs > 1) {
654                 file->refs--;
655                 return (0);
656         }
657
658         /* Give eventhandlers a chance to prevent the unload. */
659         error = 0;
660         EVENTHANDLER_INVOKE(kld_unload_try, file, &error);
661         if (error != 0)
662                 return (EBUSY);
663
664         KLD_DPF(FILE, ("linker_file_unload: file is unloading,"
665             " informing modules\n"));
666
667         /*
668          * Quiesce all the modules to give them a chance to veto the unload.
669          */
670         MOD_SLOCK;
671         for (mod = TAILQ_FIRST(&file->modules); mod;
672              mod = module_getfnext(mod)) {
673
674                 error = module_quiesce(mod);
675                 if (error != 0 && flags != LINKER_UNLOAD_FORCE) {
676                         KLD_DPF(FILE, ("linker_file_unload: module %s"
677                             " vetoed unload\n", module_getname(mod)));
678                         /*
679                          * XXX: Do we need to tell all the quiesced modules
680                          * that they can resume work now via a new module
681                          * event?
682                          */
683                         MOD_SUNLOCK;
684                         return (error);
685                 }
686         }
687         MOD_SUNLOCK;
688
689         /*
690          * Inform any modules associated with this file that they are
691          * being unloaded.
692          */
693         MOD_XLOCK;
694         for (mod = TAILQ_FIRST(&file->modules); mod; mod = next) {
695                 next = module_getfnext(mod);
696                 MOD_XUNLOCK;
697
698                 /*
699                  * Give the module a chance to veto the unload.
700                  */
701                 if ((error = module_unload(mod)) != 0) {
702 #ifdef KLD_DEBUG
703                         MOD_SLOCK;
704                         KLD_DPF(FILE, ("linker_file_unload: module %s"
705                             " failed unload\n", module_getname(mod)));
706                         MOD_SUNLOCK;
707 #endif
708                         return (error);
709                 }
710                 MOD_XLOCK;
711                 module_release(mod);
712         }
713         MOD_XUNLOCK;
714
715         TAILQ_FOREACH_SAFE(ml, &found_modules, link, nextml) {
716                 if (ml->container == file) {
717                         TAILQ_REMOVE(&found_modules, ml, link);
718                         free(ml, M_LINKER);
719                 }
720         }
721
722         /*
723          * Don't try to run SYSUNINITs if we are unloaded due to a
724          * link error.
725          */
726         if (file->flags & LINKER_FILE_LINKED) {
727                 file->flags &= ~LINKER_FILE_LINKED;
728                 linker_file_unregister_sysctls(file);
729                 linker_file_sysuninit(file);
730         }
731         TAILQ_REMOVE(&linker_files, file, link);
732
733         if (file->deps) {
734                 for (i = 0; i < file->ndeps; i++)
735                         linker_file_unload(file->deps[i], flags);
736                 free(file->deps, M_LINKER);
737                 file->deps = NULL;
738         }
739         while ((cp = STAILQ_FIRST(&file->common)) != NULL) {
740                 STAILQ_REMOVE_HEAD(&file->common, link);
741                 free(cp, M_LINKER);
742         }
743
744         LINKER_UNLOAD(file);
745
746         EVENTHANDLER_INVOKE(kld_unload, file->filename, file->address,
747             file->size);
748
749         if (file->filename) {
750                 free(file->filename, M_LINKER);
751                 file->filename = NULL;
752         }
753         if (file->pathname) {
754                 free(file->pathname, M_LINKER);
755                 file->pathname = NULL;
756         }
757         kobj_delete((kobj_t) file, M_LINKER);
758         return (0);
759 }
760
761 int
762 linker_ctf_get(linker_file_t file, linker_ctf_t *lc)
763 {
764         return (LINKER_CTF_GET(file, lc));
765 }
766
767 static int
768 linker_file_add_dependency(linker_file_t file, linker_file_t dep)
769 {
770         linker_file_t *newdeps;
771
772         sx_assert(&kld_sx, SA_XLOCKED);
773         file->deps = realloc(file->deps, (file->ndeps + 1) * sizeof(*newdeps),
774             M_LINKER, M_WAITOK | M_ZERO);
775         file->deps[file->ndeps] = dep;
776         file->ndeps++;
777         KLD_DPF(FILE, ("linker_file_add_dependency:"
778             " adding %s as dependency for %s\n", 
779             dep->filename, file->filename));
780         return (0);
781 }
782
783 /*
784  * Locate a linker set and its contents.  This is a helper function to avoid
785  * linker_if.h exposure elsewhere.  Note: firstp and lastp are really void **.
786  * This function is used in this file so we can avoid having lots of (void **)
787  * casts.
788  */
789 int
790 linker_file_lookup_set(linker_file_t file, const char *name,
791     void *firstp, void *lastp, int *countp)
792 {
793
794         sx_assert(&kld_sx, SA_LOCKED);
795         return (LINKER_LOOKUP_SET(file, name, firstp, lastp, countp));
796 }
797
798 /*
799  * List all functions in a file.
800  */
801 int
802 linker_file_function_listall(linker_file_t lf,
803     linker_function_nameval_callback_t callback_func, void *arg)
804 {
805         return (LINKER_EACH_FUNCTION_NAMEVAL(lf, callback_func, arg));
806 }
807
808 caddr_t
809 linker_file_lookup_symbol(linker_file_t file, const char *name, int deps)
810 {
811         caddr_t sym;
812         int locked;
813
814         locked = sx_xlocked(&kld_sx);
815         if (!locked)
816                 sx_xlock(&kld_sx);
817         sym = linker_file_lookup_symbol_internal(file, name, deps);
818         if (!locked)
819                 sx_xunlock(&kld_sx);
820         return (sym);
821 }
822
823 static caddr_t
824 linker_file_lookup_symbol_internal(linker_file_t file, const char *name,
825     int deps)
826 {
827         c_linker_sym_t sym;
828         linker_symval_t symval;
829         caddr_t address;
830         size_t common_size = 0;
831         int i;
832
833         sx_assert(&kld_sx, SA_XLOCKED);
834         KLD_DPF(SYM, ("linker_file_lookup_symbol: file=%p, name=%s, deps=%d\n",
835             file, name, deps));
836
837         if (LINKER_LOOKUP_SYMBOL(file, name, &sym) == 0) {
838                 LINKER_SYMBOL_VALUES(file, sym, &symval);
839                 if (symval.value == 0)
840                         /*
841                          * For commons, first look them up in the
842                          * dependencies and only allocate space if not found
843                          * there.
844                          */
845                         common_size = symval.size;
846                 else {
847                         KLD_DPF(SYM, ("linker_file_lookup_symbol: symbol"
848                             ".value=%p\n", symval.value));
849                         return (symval.value);
850                 }
851         }
852         if (deps) {
853                 for (i = 0; i < file->ndeps; i++) {
854                         address = linker_file_lookup_symbol_internal(
855                             file->deps[i], name, 0);
856                         if (address) {
857                                 KLD_DPF(SYM, ("linker_file_lookup_symbol:"
858                                     " deps value=%p\n", address));
859                                 return (address);
860                         }
861                 }
862         }
863         if (common_size > 0) {
864                 /*
865                  * This is a common symbol which was not found in the
866                  * dependencies.  We maintain a simple common symbol table in
867                  * the file object.
868                  */
869                 struct common_symbol *cp;
870
871                 STAILQ_FOREACH(cp, &file->common, link) {
872                         if (strcmp(cp->name, name) == 0) {
873                                 KLD_DPF(SYM, ("linker_file_lookup_symbol:"
874                                     " old common value=%p\n", cp->address));
875                                 return (cp->address);
876                         }
877                 }
878                 /*
879                  * Round the symbol size up to align.
880                  */
881                 common_size = (common_size + sizeof(int) - 1) & -sizeof(int);
882                 cp = malloc(sizeof(struct common_symbol)
883                     + common_size + strlen(name) + 1, M_LINKER,
884                     M_WAITOK | M_ZERO);
885                 cp->address = (caddr_t)(cp + 1);
886                 cp->name = cp->address + common_size;
887                 strcpy(cp->name, name);
888                 bzero(cp->address, common_size);
889                 STAILQ_INSERT_TAIL(&file->common, cp, link);
890
891                 KLD_DPF(SYM, ("linker_file_lookup_symbol: new common"
892                     " value=%p\n", cp->address));
893                 return (cp->address);
894         }
895         KLD_DPF(SYM, ("linker_file_lookup_symbol: fail\n"));
896         return (0);
897 }
898
899 /*
900  * Both DDB and stack(9) rely on the kernel linker to provide forward and
901  * backward lookup of symbols.  However, DDB and sometimes stack(9) need to
902  * do this in a lockfree manner.  We provide a set of internal helper
903  * routines to perform these operations without locks, and then wrappers that
904  * optionally lock.
905  *
906  * linker_debug_lookup() is ifdef DDB as currently it's only used by DDB.
907  */
908 #ifdef DDB
909 static int
910 linker_debug_lookup(const char *symstr, c_linker_sym_t *sym)
911 {
912         linker_file_t lf;
913
914         TAILQ_FOREACH(lf, &linker_files, link) {
915                 if (LINKER_LOOKUP_SYMBOL(lf, symstr, sym) == 0)
916                         return (0);
917         }
918         return (ENOENT);
919 }
920 #endif
921
922 static int
923 linker_debug_search_symbol(caddr_t value, c_linker_sym_t *sym, long *diffp)
924 {
925         linker_file_t lf;
926         c_linker_sym_t best, es;
927         u_long diff, bestdiff, off;
928
929         best = 0;
930         off = (uintptr_t)value;
931         bestdiff = off;
932         TAILQ_FOREACH(lf, &linker_files, link) {
933                 if (LINKER_SEARCH_SYMBOL(lf, value, &es, &diff) != 0)
934                         continue;
935                 if (es != 0 && diff < bestdiff) {
936                         best = es;
937                         bestdiff = diff;
938                 }
939                 if (bestdiff == 0)
940                         break;
941         }
942         if (best) {
943                 *sym = best;
944                 *diffp = bestdiff;
945                 return (0);
946         } else {
947                 *sym = 0;
948                 *diffp = off;
949                 return (ENOENT);
950         }
951 }
952
953 static int
954 linker_debug_symbol_values(c_linker_sym_t sym, linker_symval_t *symval)
955 {
956         linker_file_t lf;
957
958         TAILQ_FOREACH(lf, &linker_files, link) {
959                 if (LINKER_SYMBOL_VALUES(lf, sym, symval) == 0)
960                         return (0);
961         }
962         return (ENOENT);
963 }
964
965 static int
966 linker_debug_search_symbol_name(caddr_t value, char *buf, u_int buflen,
967     long *offset)
968 {
969         linker_symval_t symval;
970         c_linker_sym_t sym;
971         int error;
972
973         *offset = 0;
974         error = linker_debug_search_symbol(value, &sym, offset);
975         if (error)
976                 return (error);
977         error = linker_debug_symbol_values(sym, &symval);
978         if (error)
979                 return (error);
980         strlcpy(buf, symval.name, buflen);
981         return (0);
982 }
983
984 /*
985  * DDB Helpers.  DDB has to look across multiple files with their own symbol
986  * tables and string tables.
987  *
988  * Note that we do not obey list locking protocols here.  We really don't need
989  * DDB to hang because somebody's got the lock held.  We'll take the chance
990  * that the files list is inconsistent instead.
991  */
992 #ifdef DDB
993 int
994 linker_ddb_lookup(const char *symstr, c_linker_sym_t *sym)
995 {
996
997         return (linker_debug_lookup(symstr, sym));
998 }
999 #endif
1000
1001 int
1002 linker_ddb_search_symbol(caddr_t value, c_linker_sym_t *sym, long *diffp)
1003 {
1004
1005         return (linker_debug_search_symbol(value, sym, diffp));
1006 }
1007
1008 int
1009 linker_ddb_symbol_values(c_linker_sym_t sym, linker_symval_t *symval)
1010 {
1011
1012         return (linker_debug_symbol_values(sym, symval));
1013 }
1014
1015 int
1016 linker_ddb_search_symbol_name(caddr_t value, char *buf, u_int buflen,
1017     long *offset)
1018 {
1019
1020         return (linker_debug_search_symbol_name(value, buf, buflen, offset));
1021 }
1022
1023 /*
1024  * stack(9) helper for non-debugging environemnts.  Unlike DDB helpers, we do
1025  * obey locking protocols, and offer a significantly less complex interface.
1026  */
1027 int
1028 linker_search_symbol_name(caddr_t value, char *buf, u_int buflen,
1029     long *offset)
1030 {
1031         int error;
1032
1033         sx_slock(&kld_sx);
1034         error = linker_debug_search_symbol_name(value, buf, buflen, offset);
1035         sx_sunlock(&kld_sx);
1036         return (error);
1037 }
1038
1039 /*
1040  * Syscalls.
1041  */
1042 int
1043 kern_kldload(struct thread *td, const char *file, int *fileid)
1044 {
1045         const char *kldname, *modname;
1046         linker_file_t lf;
1047         int error;
1048
1049         if ((error = securelevel_gt(td->td_ucred, 0)) != 0)
1050                 return (error);
1051
1052         if ((error = priv_check(td, PRIV_KLD_LOAD)) != 0)
1053                 return (error);
1054
1055         /*
1056          * It is possible that kldloaded module will attach a new ifnet,
1057          * so vnet context must be set when this ocurs.
1058          */
1059         CURVNET_SET(TD_TO_VNET(td));
1060
1061         /*
1062          * If file does not contain a qualified name or any dot in it
1063          * (kldname.ko, or kldname.ver.ko) treat it as an interface
1064          * name.
1065          */
1066         if (strchr(file, '/') || strchr(file, '.')) {
1067                 kldname = file;
1068                 modname = NULL;
1069         } else {
1070                 kldname = NULL;
1071                 modname = file;
1072         }
1073
1074         sx_xlock(&kld_sx);
1075         error = linker_load_module(kldname, modname, NULL, NULL, &lf);
1076         if (error) {
1077                 sx_xunlock(&kld_sx);
1078                 goto done;
1079         }
1080         lf->userrefs++;
1081         if (fileid != NULL)
1082                 *fileid = lf->id;
1083         sx_xunlock(&kld_sx);
1084
1085 done:
1086         CURVNET_RESTORE();
1087         return (error);
1088 }
1089
1090 int
1091 sys_kldload(struct thread *td, struct kldload_args *uap)
1092 {
1093         char *pathname = NULL;
1094         int error, fileid;
1095
1096         td->td_retval[0] = -1;
1097
1098         pathname = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
1099         error = copyinstr(uap->file, pathname, MAXPATHLEN, NULL);
1100         if (error == 0) {
1101                 error = kern_kldload(td, pathname, &fileid);
1102                 if (error == 0)
1103                         td->td_retval[0] = fileid;
1104         }
1105         free(pathname, M_TEMP);
1106         return (error);
1107 }
1108
1109 int
1110 kern_kldunload(struct thread *td, int fileid, int flags)
1111 {
1112         linker_file_t lf;
1113         int error = 0;
1114
1115         if ((error = securelevel_gt(td->td_ucred, 0)) != 0)
1116                 return (error);
1117
1118         if ((error = priv_check(td, PRIV_KLD_UNLOAD)) != 0)
1119                 return (error);
1120
1121         CURVNET_SET(TD_TO_VNET(td));
1122         sx_xlock(&kld_sx);
1123         lf = linker_find_file_by_id(fileid);
1124         if (lf) {
1125                 KLD_DPF(FILE, ("kldunload: lf->userrefs=%d\n", lf->userrefs));
1126
1127                 if (lf->userrefs == 0) {
1128                         /*
1129                          * XXX: maybe LINKER_UNLOAD_FORCE should override ?
1130                          */
1131                         printf("kldunload: attempt to unload file that was"
1132                             " loaded by the kernel\n");
1133                         error = EBUSY;
1134                 } else {
1135                         lf->userrefs--;
1136                         error = linker_file_unload(lf, flags);
1137                         if (error)
1138                                 lf->userrefs++;
1139                 }
1140         } else
1141                 error = ENOENT;
1142         sx_xunlock(&kld_sx);
1143
1144         CURVNET_RESTORE();
1145         return (error);
1146 }
1147
1148 int
1149 sys_kldunload(struct thread *td, struct kldunload_args *uap)
1150 {
1151
1152         return (kern_kldunload(td, uap->fileid, LINKER_UNLOAD_NORMAL));
1153 }
1154
1155 int
1156 sys_kldunloadf(struct thread *td, struct kldunloadf_args *uap)
1157 {
1158
1159         if (uap->flags != LINKER_UNLOAD_NORMAL &&
1160             uap->flags != LINKER_UNLOAD_FORCE)
1161                 return (EINVAL);
1162         return (kern_kldunload(td, uap->fileid, uap->flags));
1163 }
1164
1165 int
1166 sys_kldfind(struct thread *td, struct kldfind_args *uap)
1167 {
1168         char *pathname;
1169         const char *filename;
1170         linker_file_t lf;
1171         int error;
1172
1173 #ifdef MAC
1174         error = mac_kld_check_stat(td->td_ucred);
1175         if (error)
1176                 return (error);
1177 #endif
1178
1179         td->td_retval[0] = -1;
1180
1181         pathname = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
1182         if ((error = copyinstr(uap->file, pathname, MAXPATHLEN, NULL)) != 0)
1183                 goto out;
1184
1185         filename = linker_basename(pathname);
1186         sx_xlock(&kld_sx);
1187         lf = linker_find_file_by_name(filename);
1188         if (lf)
1189                 td->td_retval[0] = lf->id;
1190         else
1191                 error = ENOENT;
1192         sx_xunlock(&kld_sx);
1193 out:
1194         free(pathname, M_TEMP);
1195         return (error);
1196 }
1197
1198 int
1199 sys_kldnext(struct thread *td, struct kldnext_args *uap)
1200 {
1201         linker_file_t lf;
1202         int error = 0;
1203
1204 #ifdef MAC
1205         error = mac_kld_check_stat(td->td_ucred);
1206         if (error)
1207                 return (error);
1208 #endif
1209
1210         sx_xlock(&kld_sx);
1211         if (uap->fileid == 0)
1212                 lf = TAILQ_FIRST(&linker_files);
1213         else {
1214                 lf = linker_find_file_by_id(uap->fileid);
1215                 if (lf == NULL) {
1216                         error = ENOENT;
1217                         goto out;
1218                 }
1219                 lf = TAILQ_NEXT(lf, link);
1220         }
1221
1222         /* Skip partially loaded files. */
1223         while (lf != NULL && !(lf->flags & LINKER_FILE_LINKED))
1224                 lf = TAILQ_NEXT(lf, link);
1225
1226         if (lf)
1227                 td->td_retval[0] = lf->id;
1228         else
1229                 td->td_retval[0] = 0;
1230 out:
1231         sx_xunlock(&kld_sx);
1232         return (error);
1233 }
1234
1235 int
1236 sys_kldstat(struct thread *td, struct kldstat_args *uap)
1237 {
1238         struct kld_file_stat *stat;
1239         int error, version;
1240
1241         /*
1242          * Check the version of the user's structure.
1243          */
1244         if ((error = copyin(&uap->stat->version, &version, sizeof(version)))
1245             != 0)
1246                 return (error);
1247         if (version != sizeof(struct kld_file_stat_1) &&
1248             version != sizeof(struct kld_file_stat))
1249                 return (EINVAL);
1250
1251         stat = malloc(sizeof(*stat), M_TEMP, M_WAITOK | M_ZERO);
1252         error = kern_kldstat(td, uap->fileid, stat);
1253         if (error == 0)
1254                 error = copyout(stat, uap->stat, version);
1255         free(stat, M_TEMP);
1256         return (error);
1257 }
1258
1259 int
1260 kern_kldstat(struct thread *td, int fileid, struct kld_file_stat *stat)
1261 {
1262         linker_file_t lf;
1263         int namelen;
1264 #ifdef MAC
1265         int error;
1266
1267         error = mac_kld_check_stat(td->td_ucred);
1268         if (error)
1269                 return (error);
1270 #endif
1271
1272         sx_xlock(&kld_sx);
1273         lf = linker_find_file_by_id(fileid);
1274         if (lf == NULL) {
1275                 sx_xunlock(&kld_sx);
1276                 return (ENOENT);
1277         }
1278
1279         /* Version 1 fields: */
1280         namelen = strlen(lf->filename) + 1;
1281         if (namelen > sizeof(stat->name))
1282                 namelen = sizeof(stat->name);
1283         bcopy(lf->filename, &stat->name[0], namelen);
1284         stat->refs = lf->refs;
1285         stat->id = lf->id;
1286         stat->address = lf->address;
1287         stat->size = lf->size;
1288         /* Version 2 fields: */
1289         namelen = strlen(lf->pathname) + 1;
1290         if (namelen > sizeof(stat->pathname))
1291                 namelen = sizeof(stat->pathname);
1292         bcopy(lf->pathname, &stat->pathname[0], namelen);
1293         sx_xunlock(&kld_sx);
1294
1295         td->td_retval[0] = 0;
1296         return (0);
1297 }
1298
1299 #ifdef DDB
1300 DB_COMMAND(kldstat, db_kldstat)
1301 {
1302         linker_file_t lf;
1303
1304 #define POINTER_WIDTH   ((int)(sizeof(void *) * 2 + 2))
1305         db_printf("Id Refs Address%*c Size     Name\n", POINTER_WIDTH - 7, ' ');
1306 #undef  POINTER_WIDTH
1307         TAILQ_FOREACH(lf, &linker_files, link) {
1308                 if (db_pager_quit)
1309                         return;
1310                 db_printf("%2d %4d %p %-8zx %s\n", lf->id, lf->refs,
1311                     lf->address, lf->size, lf->filename);
1312         }
1313 }
1314 #endif /* DDB */
1315
1316 int
1317 sys_kldfirstmod(struct thread *td, struct kldfirstmod_args *uap)
1318 {
1319         linker_file_t lf;
1320         module_t mp;
1321         int error = 0;
1322
1323 #ifdef MAC
1324         error = mac_kld_check_stat(td->td_ucred);
1325         if (error)
1326                 return (error);
1327 #endif
1328
1329         sx_xlock(&kld_sx);
1330         lf = linker_find_file_by_id(uap->fileid);
1331         if (lf) {
1332                 MOD_SLOCK;
1333                 mp = TAILQ_FIRST(&lf->modules);
1334                 if (mp != NULL)
1335                         td->td_retval[0] = module_getid(mp);
1336                 else
1337                         td->td_retval[0] = 0;
1338                 MOD_SUNLOCK;
1339         } else
1340                 error = ENOENT;
1341         sx_xunlock(&kld_sx);
1342         return (error);
1343 }
1344
1345 int
1346 sys_kldsym(struct thread *td, struct kldsym_args *uap)
1347 {
1348         char *symstr = NULL;
1349         c_linker_sym_t sym;
1350         linker_symval_t symval;
1351         linker_file_t lf;
1352         struct kld_sym_lookup lookup;
1353         int error = 0;
1354
1355 #ifdef MAC
1356         error = mac_kld_check_stat(td->td_ucred);
1357         if (error)
1358                 return (error);
1359 #endif
1360
1361         if ((error = copyin(uap->data, &lookup, sizeof(lookup))) != 0)
1362                 return (error);
1363         if (lookup.version != sizeof(lookup) ||
1364             uap->cmd != KLDSYM_LOOKUP)
1365                 return (EINVAL);
1366         symstr = malloc(MAXPATHLEN, M_TEMP, M_WAITOK);
1367         if ((error = copyinstr(lookup.symname, symstr, MAXPATHLEN, NULL)) != 0)
1368                 goto out;
1369         sx_xlock(&kld_sx);
1370         if (uap->fileid != 0) {
1371                 lf = linker_find_file_by_id(uap->fileid);
1372                 if (lf == NULL)
1373                         error = ENOENT;
1374                 else if (LINKER_LOOKUP_SYMBOL(lf, symstr, &sym) == 0 &&
1375                     LINKER_SYMBOL_VALUES(lf, sym, &symval) == 0) {
1376                         lookup.symvalue = (uintptr_t) symval.value;
1377                         lookup.symsize = symval.size;
1378                         error = copyout(&lookup, uap->data, sizeof(lookup));
1379                 } else
1380                         error = ENOENT;
1381         } else {
1382                 TAILQ_FOREACH(lf, &linker_files, link) {
1383                         if (LINKER_LOOKUP_SYMBOL(lf, symstr, &sym) == 0 &&
1384                             LINKER_SYMBOL_VALUES(lf, sym, &symval) == 0) {
1385                                 lookup.symvalue = (uintptr_t)symval.value;
1386                                 lookup.symsize = symval.size;
1387                                 error = copyout(&lookup, uap->data,
1388                                     sizeof(lookup));
1389                                 break;
1390                         }
1391                 }
1392                 if (lf == NULL)
1393                         error = ENOENT;
1394         }
1395         sx_xunlock(&kld_sx);
1396 out:
1397         free(symstr, M_TEMP);
1398         return (error);
1399 }
1400
1401 /*
1402  * Preloaded module support
1403  */
1404
1405 static modlist_t
1406 modlist_lookup(const char *name, int ver)
1407 {
1408         modlist_t mod;
1409
1410         TAILQ_FOREACH(mod, &found_modules, link) {
1411                 if (strcmp(mod->name, name) == 0 &&
1412                     (ver == 0 || mod->version == ver))
1413                         return (mod);
1414         }
1415         return (NULL);
1416 }
1417
1418 static modlist_t
1419 modlist_lookup2(const char *name, const struct mod_depend *verinfo)
1420 {
1421         modlist_t mod, bestmod;
1422         int ver;
1423
1424         if (verinfo == NULL)
1425                 return (modlist_lookup(name, 0));
1426         bestmod = NULL;
1427         TAILQ_FOREACH(mod, &found_modules, link) {
1428                 if (strcmp(mod->name, name) != 0)
1429                         continue;
1430                 ver = mod->version;
1431                 if (ver == verinfo->md_ver_preferred)
1432                         return (mod);
1433                 if (ver >= verinfo->md_ver_minimum &&
1434                     ver <= verinfo->md_ver_maximum &&
1435                     (bestmod == NULL || ver > bestmod->version))
1436                         bestmod = mod;
1437         }
1438         return (bestmod);
1439 }
1440
1441 static modlist_t
1442 modlist_newmodule(const char *modname, int version, linker_file_t container)
1443 {
1444         modlist_t mod;
1445
1446         mod = malloc(sizeof(struct modlist), M_LINKER, M_NOWAIT | M_ZERO);
1447         if (mod == NULL)
1448                 panic("no memory for module list");
1449         mod->container = container;
1450         mod->name = modname;
1451         mod->version = version;
1452         TAILQ_INSERT_TAIL(&found_modules, mod, link);
1453         return (mod);
1454 }
1455
1456 static void
1457 linker_addmodules(linker_file_t lf, struct mod_metadata **start,
1458     struct mod_metadata **stop, int preload)
1459 {
1460         struct mod_metadata *mp, **mdp;
1461         const char *modname;
1462         int ver;
1463
1464         for (mdp = start; mdp < stop; mdp++) {
1465                 mp = *mdp;
1466                 if (mp->md_type != MDT_VERSION)
1467                         continue;
1468                 modname = mp->md_cval;
1469                 ver = ((const struct mod_version *)mp->md_data)->mv_version;
1470                 if (modlist_lookup(modname, ver) != NULL) {
1471                         printf("module %s already present!\n", modname);
1472                         /* XXX what can we do? this is a build error. :-( */
1473                         continue;
1474                 }
1475                 modlist_newmodule(modname, ver, lf);
1476         }
1477 }
1478
1479 static void
1480 linker_preload(void *arg)
1481 {
1482         caddr_t modptr;
1483         const char *modname, *nmodname;
1484         char *modtype;
1485         linker_file_t lf, nlf;
1486         linker_class_t lc;
1487         int error;
1488         linker_file_list_t loaded_files;
1489         linker_file_list_t depended_files;
1490         struct mod_metadata *mp, *nmp;
1491         struct mod_metadata **start, **stop, **mdp, **nmdp;
1492         const struct mod_depend *verinfo;
1493         int nver;
1494         int resolves;
1495         modlist_t mod;
1496         struct sysinit **si_start, **si_stop;
1497
1498         TAILQ_INIT(&loaded_files);
1499         TAILQ_INIT(&depended_files);
1500         TAILQ_INIT(&found_modules);
1501         error = 0;
1502
1503         modptr = NULL;
1504         sx_xlock(&kld_sx);
1505         while ((modptr = preload_search_next_name(modptr)) != NULL) {
1506                 modname = (char *)preload_search_info(modptr, MODINFO_NAME);
1507                 modtype = (char *)preload_search_info(modptr, MODINFO_TYPE);
1508                 if (modname == NULL) {
1509                         printf("Preloaded module at %p does not have a"
1510                             " name!\n", modptr);
1511                         continue;
1512                 }
1513                 if (modtype == NULL) {
1514                         printf("Preloaded module at %p does not have a type!\n",
1515                             modptr);
1516                         continue;
1517                 }
1518                 if (bootverbose)
1519                         printf("Preloaded %s \"%s\" at %p.\n", modtype, modname,
1520                             modptr);
1521                 lf = NULL;
1522                 TAILQ_FOREACH(lc, &classes, link) {
1523                         error = LINKER_LINK_PRELOAD(lc, modname, &lf);
1524                         if (!error)
1525                                 break;
1526                         lf = NULL;
1527                 }
1528                 if (lf)
1529                         TAILQ_INSERT_TAIL(&loaded_files, lf, loaded);
1530         }
1531
1532         /*
1533          * First get a list of stuff in the kernel.
1534          */
1535         if (linker_file_lookup_set(linker_kernel_file, MDT_SETNAME, &start,
1536             &stop, NULL) == 0)
1537                 linker_addmodules(linker_kernel_file, start, stop, 1);
1538
1539         /*
1540          * This is a once-off kinky bubble sort to resolve relocation
1541          * dependency requirements.
1542          */
1543 restart:
1544         TAILQ_FOREACH(lf, &loaded_files, loaded) {
1545                 error = linker_file_lookup_set(lf, MDT_SETNAME, &start,
1546                     &stop, NULL);
1547                 /*
1548                  * First, look to see if we would successfully link with this
1549                  * stuff.
1550                  */
1551                 resolves = 1;   /* unless we know otherwise */
1552                 if (!error) {
1553                         for (mdp = start; mdp < stop; mdp++) {
1554                                 mp = *mdp;
1555                                 if (mp->md_type != MDT_DEPEND)
1556                                         continue;
1557                                 modname = mp->md_cval;
1558                                 verinfo = mp->md_data;
1559                                 for (nmdp = start; nmdp < stop; nmdp++) {
1560                                         nmp = *nmdp;
1561                                         if (nmp->md_type != MDT_VERSION)
1562                                                 continue;
1563                                         nmodname = nmp->md_cval;
1564                                         if (strcmp(modname, nmodname) == 0)
1565                                                 break;
1566                                 }
1567                                 if (nmdp < stop)   /* it's a self reference */
1568                                         continue;
1569
1570                                 /*
1571                                  * ok, the module isn't here yet, we
1572                                  * are not finished
1573                                  */
1574                                 if (modlist_lookup2(modname, verinfo) == NULL)
1575                                         resolves = 0;
1576                         }
1577                 }
1578                 /*
1579                  * OK, if we found our modules, we can link.  So, "provide"
1580                  * the modules inside and add it to the end of the link order
1581                  * list.
1582                  */
1583                 if (resolves) {
1584                         if (!error) {
1585                                 for (mdp = start; mdp < stop; mdp++) {
1586                                         mp = *mdp;
1587                                         if (mp->md_type != MDT_VERSION)
1588                                                 continue;
1589                                         modname = mp->md_cval;
1590                                         nver = ((const struct mod_version *)
1591                                             mp->md_data)->mv_version;
1592                                         if (modlist_lookup(modname,
1593                                             nver) != NULL) {
1594                                                 printf("module %s already"
1595                                                     " present!\n", modname);
1596                                                 TAILQ_REMOVE(&loaded_files,
1597                                                     lf, loaded);
1598                                                 linker_file_unload(lf,
1599                                                     LINKER_UNLOAD_FORCE);
1600                                                 /* we changed tailq next ptr */
1601                                                 goto restart;
1602                                         }
1603                                         modlist_newmodule(modname, nver, lf);
1604                                 }
1605                         }
1606                         TAILQ_REMOVE(&loaded_files, lf, loaded);
1607                         TAILQ_INSERT_TAIL(&depended_files, lf, loaded);
1608                         /*
1609                          * Since we provided modules, we need to restart the
1610                          * sort so that the previous files that depend on us
1611                          * have a chance. Also, we've busted the tailq next
1612                          * pointer with the REMOVE.
1613                          */
1614                         goto restart;
1615                 }
1616         }
1617
1618         /*
1619          * At this point, we check to see what could not be resolved..
1620          */
1621         while ((lf = TAILQ_FIRST(&loaded_files)) != NULL) {
1622                 TAILQ_REMOVE(&loaded_files, lf, loaded);
1623                 printf("KLD file %s is missing dependencies\n", lf->filename);
1624                 linker_file_unload(lf, LINKER_UNLOAD_FORCE);
1625         }
1626
1627         /*
1628          * We made it. Finish off the linking in the order we determined.
1629          */
1630         TAILQ_FOREACH_SAFE(lf, &depended_files, loaded, nlf) {
1631                 if (linker_kernel_file) {
1632                         linker_kernel_file->refs++;
1633                         error = linker_file_add_dependency(lf,
1634                             linker_kernel_file);
1635                         if (error)
1636                                 panic("cannot add dependency");
1637                 }
1638                 error = linker_file_lookup_set(lf, MDT_SETNAME, &start,
1639                     &stop, NULL);
1640                 if (!error) {
1641                         for (mdp = start; mdp < stop; mdp++) {
1642                                 mp = *mdp;
1643                                 if (mp->md_type != MDT_DEPEND)
1644                                         continue;
1645                                 modname = mp->md_cval;
1646                                 verinfo = mp->md_data;
1647                                 mod = modlist_lookup2(modname, verinfo);
1648                                 if (mod == NULL) {
1649                                         printf("KLD file %s - cannot find "
1650                                             "dependency \"%s\"\n",
1651                                             lf->filename, modname);
1652                                         goto fail;
1653                                 }
1654                                 /* Don't count self-dependencies */
1655                                 if (lf == mod->container)
1656                                         continue;
1657                                 mod->container->refs++;
1658                                 error = linker_file_add_dependency(lf,
1659                                     mod->container);
1660                                 if (error)
1661                                         panic("cannot add dependency");
1662                         }
1663                 }
1664                 /*
1665                  * Now do relocation etc using the symbol search paths
1666                  * established by the dependencies
1667                  */
1668                 error = LINKER_LINK_PRELOAD_FINISH(lf);
1669                 if (error) {
1670                         printf("KLD file %s - could not finalize loading\n",
1671                             lf->filename);
1672                         goto fail;
1673                 }
1674                 linker_file_register_modules(lf);
1675                 if (!TAILQ_EMPTY(&lf->modules))
1676                         lf->flags |= LINKER_FILE_MODULES;
1677                 if (linker_file_lookup_set(lf, "sysinit_set", &si_start,
1678                     &si_stop, NULL) == 0)
1679                         sysinit_add(si_start, si_stop);
1680                 linker_file_register_sysctls(lf, true);
1681                 lf->flags |= LINKER_FILE_LINKED;
1682                 continue;
1683 fail:
1684                 TAILQ_REMOVE(&depended_files, lf, loaded);
1685                 linker_file_unload(lf, LINKER_UNLOAD_FORCE);
1686         }
1687         sx_xunlock(&kld_sx);
1688         /* woohoo! we made it! */
1689 }
1690
1691 SYSINIT(preload, SI_SUB_KLD, SI_ORDER_MIDDLE, linker_preload, NULL);
1692
1693 /*
1694  * Handle preload files that failed to load any modules.
1695  */
1696 static void
1697 linker_preload_finish(void *arg)
1698 {
1699         linker_file_t lf, nlf;
1700
1701         sx_xlock(&kld_sx);
1702         TAILQ_FOREACH_SAFE(lf, &linker_files, link, nlf) {
1703                 /*
1704                  * If all of the modules in this file failed to load, unload
1705                  * the file and return an error of ENOEXEC.  (Parity with
1706                  * linker_load_file.)
1707                  */
1708                 if ((lf->flags & LINKER_FILE_MODULES) != 0 &&
1709                     TAILQ_EMPTY(&lf->modules)) {
1710                         linker_file_unload(lf, LINKER_UNLOAD_FORCE);
1711                         continue;
1712                 }
1713
1714                 lf->flags &= ~LINKER_FILE_MODULES;
1715                 lf->userrefs++; /* so we can (try to) kldunload it */
1716         }
1717         sx_xunlock(&kld_sx);
1718 }
1719
1720 /*
1721  * Attempt to run after all DECLARE_MODULE SYSINITs.  Unfortunately they can be
1722  * scheduled at any subsystem and order, so run this as late as possible.  init
1723  * becomes runnable in SI_SUB_KTHREAD_INIT, so go slightly before that.
1724  */
1725 SYSINIT(preload_finish, SI_SUB_KTHREAD_INIT - 100, SI_ORDER_MIDDLE,
1726     linker_preload_finish, NULL);
1727
1728 /*
1729  * Search for a not-loaded module by name.
1730  *
1731  * Modules may be found in the following locations:
1732  *
1733  * - preloaded (result is just the module name) - on disk (result is full path
1734  * to module)
1735  *
1736  * If the module name is qualified in any way (contains path, etc.) the we
1737  * simply return a copy of it.
1738  *
1739  * The search path can be manipulated via sysctl.  Note that we use the ';'
1740  * character as a separator to be consistent with the bootloader.
1741  */
1742
1743 static char linker_hintfile[] = "linker.hints";
1744 static char linker_path[MAXPATHLEN] = "/boot/kernel;/boot/modules";
1745
1746 SYSCTL_STRING(_kern, OID_AUTO, module_path, CTLFLAG_RWTUN, linker_path,
1747     sizeof(linker_path), "module load search path");
1748
1749 TUNABLE_STR("module_path", linker_path, sizeof(linker_path));
1750
1751 static char *linker_ext_list[] = {
1752         "",
1753         ".ko",
1754         NULL
1755 };
1756
1757 /*
1758  * Check if file actually exists either with or without extension listed in
1759  * the linker_ext_list. (probably should be generic for the rest of the
1760  * kernel)
1761  */
1762 static char *
1763 linker_lookup_file(const char *path, int pathlen, const char *name,
1764     int namelen, struct vattr *vap)
1765 {
1766         struct nameidata nd;
1767         struct thread *td = curthread;  /* XXX */
1768         char *result, **cpp, *sep;
1769         int error, len, extlen, reclen, flags;
1770         enum vtype type;
1771
1772         extlen = 0;
1773         for (cpp = linker_ext_list; *cpp; cpp++) {
1774                 len = strlen(*cpp);
1775                 if (len > extlen)
1776                         extlen = len;
1777         }
1778         extlen++;               /* trailing '\0' */
1779         sep = (path[pathlen - 1] != '/') ? "/" : "";
1780
1781         reclen = pathlen + strlen(sep) + namelen + extlen + 1;
1782         result = malloc(reclen, M_LINKER, M_WAITOK);
1783         for (cpp = linker_ext_list; *cpp; cpp++) {
1784                 snprintf(result, reclen, "%.*s%s%.*s%s", pathlen, path, sep,
1785                     namelen, name, *cpp);
1786                 /*
1787                  * Attempt to open the file, and return the path if
1788                  * we succeed and it's a regular file.
1789                  */
1790                 NDINIT(&nd, LOOKUP, FOLLOW, UIO_SYSSPACE, result, td);
1791                 flags = FREAD;
1792                 error = vn_open(&nd, &flags, 0, NULL);
1793                 if (error == 0) {
1794                         NDFREE(&nd, NDF_ONLY_PNBUF);
1795                         type = nd.ni_vp->v_type;
1796                         if (vap)
1797                                 VOP_GETATTR(nd.ni_vp, vap, td->td_ucred);
1798                         VOP_UNLOCK(nd.ni_vp, 0);
1799                         vn_close(nd.ni_vp, FREAD, td->td_ucred, td);
1800                         if (type == VREG)
1801                                 return (result);
1802                 }
1803         }
1804         free(result, M_LINKER);
1805         return (NULL);
1806 }
1807
1808 #define INT_ALIGN(base, ptr)    ptr =                                   \
1809         (base) + roundup2((ptr) - (base), sizeof(int))
1810
1811 /*
1812  * Lookup KLD which contains requested module in the "linker.hints" file. If
1813  * version specification is available, then try to find the best KLD.
1814  * Otherwise just find the latest one.
1815  */
1816 static char *
1817 linker_hints_lookup(const char *path, int pathlen, const char *modname,
1818     int modnamelen, const struct mod_depend *verinfo)
1819 {
1820         struct thread *td = curthread;  /* XXX */
1821         struct ucred *cred = td ? td->td_ucred : NULL;
1822         struct nameidata nd;
1823         struct vattr vattr, mattr;
1824         u_char *hints = NULL;
1825         u_char *cp, *recptr, *bufend, *result, *best, *pathbuf, *sep;
1826         int error, ival, bestver, *intp, found, flags, clen, blen;
1827         ssize_t reclen;
1828
1829         result = NULL;
1830         bestver = found = 0;
1831
1832         sep = (path[pathlen - 1] != '/') ? "/" : "";
1833         reclen = imax(modnamelen, strlen(linker_hintfile)) + pathlen +
1834             strlen(sep) + 1;
1835         pathbuf = malloc(reclen, M_LINKER, M_WAITOK);
1836         snprintf(pathbuf, reclen, "%.*s%s%s", pathlen, path, sep,
1837             linker_hintfile);
1838
1839         NDINIT(&nd, LOOKUP, NOFOLLOW, UIO_SYSSPACE, pathbuf, td);
1840         flags = FREAD;
1841         error = vn_open(&nd, &flags, 0, NULL);
1842         if (error)
1843                 goto bad;
1844         NDFREE(&nd, NDF_ONLY_PNBUF);
1845         if (nd.ni_vp->v_type != VREG)
1846                 goto bad;
1847         best = cp = NULL;
1848         error = VOP_GETATTR(nd.ni_vp, &vattr, cred);
1849         if (error)
1850                 goto bad;
1851         /*
1852          * XXX: we need to limit this number to some reasonable value
1853          */
1854         if (vattr.va_size > LINKER_HINTS_MAX) {
1855                 printf("hints file too large %ld\n", (long)vattr.va_size);
1856                 goto bad;
1857         }
1858         hints = malloc(vattr.va_size, M_TEMP, M_WAITOK);
1859         error = vn_rdwr(UIO_READ, nd.ni_vp, (caddr_t)hints, vattr.va_size, 0,
1860             UIO_SYSSPACE, IO_NODELOCKED, cred, NOCRED, &reclen, td);
1861         if (error)
1862                 goto bad;
1863         VOP_UNLOCK(nd.ni_vp, 0);
1864         vn_close(nd.ni_vp, FREAD, cred, td);
1865         nd.ni_vp = NULL;
1866         if (reclen != 0) {
1867                 printf("can't read %zd\n", reclen);
1868                 goto bad;
1869         }
1870         intp = (int *)hints;
1871         ival = *intp++;
1872         if (ival != LINKER_HINTS_VERSION) {
1873                 printf("hints file version mismatch %d\n", ival);
1874                 goto bad;
1875         }
1876         bufend = hints + vattr.va_size;
1877         recptr = (u_char *)intp;
1878         clen = blen = 0;
1879         while (recptr < bufend && !found) {
1880                 intp = (int *)recptr;
1881                 reclen = *intp++;
1882                 ival = *intp++;
1883                 cp = (char *)intp;
1884                 switch (ival) {
1885                 case MDT_VERSION:
1886                         clen = *cp++;
1887                         if (clen != modnamelen || bcmp(cp, modname, clen) != 0)
1888                                 break;
1889                         cp += clen;
1890                         INT_ALIGN(hints, cp);
1891                         ival = *(int *)cp;
1892                         cp += sizeof(int);
1893                         clen = *cp++;
1894                         if (verinfo == NULL ||
1895                             ival == verinfo->md_ver_preferred) {
1896                                 found = 1;
1897                                 break;
1898                         }
1899                         if (ival >= verinfo->md_ver_minimum &&
1900                             ival <= verinfo->md_ver_maximum &&
1901                             ival > bestver) {
1902                                 bestver = ival;
1903                                 best = cp;
1904                                 blen = clen;
1905                         }
1906                         break;
1907                 default:
1908                         break;
1909                 }
1910                 recptr += reclen + sizeof(int);
1911         }
1912         /*
1913          * Finally check if KLD is in the place
1914          */
1915         if (found)
1916                 result = linker_lookup_file(path, pathlen, cp, clen, &mattr);
1917         else if (best)
1918                 result = linker_lookup_file(path, pathlen, best, blen, &mattr);
1919
1920         /*
1921          * KLD is newer than hints file. What we should do now?
1922          */
1923         if (result && timespeccmp(&mattr.va_mtime, &vattr.va_mtime, >))
1924                 printf("warning: KLD '%s' is newer than the linker.hints"
1925                     " file\n", result);
1926 bad:
1927         free(pathbuf, M_LINKER);
1928         if (hints)
1929                 free(hints, M_TEMP);
1930         if (nd.ni_vp != NULL) {
1931                 VOP_UNLOCK(nd.ni_vp, 0);
1932                 vn_close(nd.ni_vp, FREAD, cred, td);
1933         }
1934         /*
1935          * If nothing found or hints is absent - fallback to the old
1936          * way by using "kldname[.ko]" as module name.
1937          */
1938         if (!found && !bestver && result == NULL)
1939                 result = linker_lookup_file(path, pathlen, modname,
1940                     modnamelen, NULL);
1941         return (result);
1942 }
1943
1944 /*
1945  * Lookup KLD which contains requested module in the all directories.
1946  */
1947 static char *
1948 linker_search_module(const char *modname, int modnamelen,
1949     const struct mod_depend *verinfo)
1950 {
1951         char *cp, *ep, *result;
1952
1953         /*
1954          * traverse the linker path
1955          */
1956         for (cp = linker_path; *cp; cp = ep + 1) {
1957                 /* find the end of this component */
1958                 for (ep = cp; (*ep != 0) && (*ep != ';'); ep++);
1959                 result = linker_hints_lookup(cp, ep - cp, modname,
1960                     modnamelen, verinfo);
1961                 if (result != NULL)
1962                         return (result);
1963                 if (*ep == 0)
1964                         break;
1965         }
1966         return (NULL);
1967 }
1968
1969 /*
1970  * Search for module in all directories listed in the linker_path.
1971  */
1972 static char *
1973 linker_search_kld(const char *name)
1974 {
1975         char *cp, *ep, *result;
1976         int len;
1977
1978         /* qualified at all? */
1979         if (strchr(name, '/'))
1980                 return (strdup(name, M_LINKER));
1981
1982         /* traverse the linker path */
1983         len = strlen(name);
1984         for (ep = linker_path; *ep; ep++) {
1985                 cp = ep;
1986                 /* find the end of this component */
1987                 for (; *ep != 0 && *ep != ';'; ep++);
1988                 result = linker_lookup_file(cp, ep - cp, name, len, NULL);
1989                 if (result != NULL)
1990                         return (result);
1991         }
1992         return (NULL);
1993 }
1994
1995 static const char *
1996 linker_basename(const char *path)
1997 {
1998         const char *filename;
1999
2000         filename = strrchr(path, '/');
2001         if (filename == NULL)
2002                 return path;
2003         if (filename[1])
2004                 filename++;
2005         return (filename);
2006 }
2007
2008 #ifdef HWPMC_HOOKS
2009 /*
2010  * Inform hwpmc about the set of kernel modules currently loaded.
2011  */
2012 void *
2013 linker_hwpmc_list_objects(void)
2014 {
2015         linker_file_t lf;
2016         struct pmckern_map_in *kobase;
2017         int i, nmappings;
2018
2019         nmappings = 0;
2020         sx_slock(&kld_sx);
2021         TAILQ_FOREACH(lf, &linker_files, link)
2022                 nmappings++;
2023
2024         /* Allocate nmappings + 1 entries. */
2025         kobase = malloc((nmappings + 1) * sizeof(struct pmckern_map_in),
2026             M_LINKER, M_WAITOK | M_ZERO);
2027         i = 0;
2028         TAILQ_FOREACH(lf, &linker_files, link) {
2029
2030                 /* Save the info for this linker file. */
2031                 kobase[i].pm_file = lf->filename;
2032                 kobase[i].pm_address = (uintptr_t)lf->address;
2033                 i++;
2034         }
2035         sx_sunlock(&kld_sx);
2036
2037         KASSERT(i > 0, ("linker_hpwmc_list_objects: no kernel objects?"));
2038
2039         /* The last entry of the malloced area comprises of all zeros. */
2040         KASSERT(kobase[i].pm_file == NULL,
2041             ("linker_hwpmc_list_objects: last object not NULL"));
2042
2043         return ((void *)kobase);
2044 }
2045 #endif
2046
2047 /*
2048  * Find a file which contains given module and load it, if "parent" is not
2049  * NULL, register a reference to it.
2050  */
2051 static int
2052 linker_load_module(const char *kldname, const char *modname,
2053     struct linker_file *parent, const struct mod_depend *verinfo,
2054     struct linker_file **lfpp)
2055 {
2056         linker_file_t lfdep;
2057         const char *filename;
2058         char *pathname;
2059         int error;
2060
2061         sx_assert(&kld_sx, SA_XLOCKED);
2062         if (modname == NULL) {
2063                 /*
2064                  * We have to load KLD
2065                  */
2066                 KASSERT(verinfo == NULL, ("linker_load_module: verinfo"
2067                     " is not NULL"));
2068                 /* check if root file system is not mounted */
2069                 if (rootvnode == NULL || curproc->p_fd->fd_rdir == NULL)
2070                         return (ENXIO);
2071                 pathname = linker_search_kld(kldname);
2072         } else {
2073                 if (modlist_lookup2(modname, verinfo) != NULL)
2074                         return (EEXIST);
2075                 /* check if root file system is not mounted */
2076                 if (rootvnode == NULL || curproc->p_fd->fd_rdir == NULL)
2077                         return (ENXIO);
2078                 if (kldname != NULL)
2079                         pathname = strdup(kldname, M_LINKER);
2080                 else
2081                         /*
2082                          * Need to find a KLD with required module
2083                          */
2084                         pathname = linker_search_module(modname,
2085                             strlen(modname), verinfo);
2086         }
2087         if (pathname == NULL)
2088                 return (ENOENT);
2089
2090         /*
2091          * Can't load more than one file with the same basename XXX:
2092          * Actually it should be possible to have multiple KLDs with
2093          * the same basename but different path because they can
2094          * provide different versions of the same modules.
2095          */
2096         filename = linker_basename(pathname);
2097         if (linker_find_file_by_name(filename))
2098                 error = EEXIST;
2099         else do {
2100                 error = linker_load_file(pathname, &lfdep);
2101                 if (error)
2102                         break;
2103                 if (modname && verinfo &&
2104                     modlist_lookup2(modname, verinfo) == NULL) {
2105                         linker_file_unload(lfdep, LINKER_UNLOAD_FORCE);
2106                         error = ENOENT;
2107                         break;
2108                 }
2109                 if (parent) {
2110                         error = linker_file_add_dependency(parent, lfdep);
2111                         if (error)
2112                                 break;
2113                 }
2114                 if (lfpp)
2115                         *lfpp = lfdep;
2116         } while (0);
2117         free(pathname, M_LINKER);
2118         return (error);
2119 }
2120
2121 /*
2122  * This routine is responsible for finding dependencies of userland initiated
2123  * kldload(2)'s of files.
2124  */
2125 int
2126 linker_load_dependencies(linker_file_t lf)
2127 {
2128         linker_file_t lfdep;
2129         struct mod_metadata **start, **stop, **mdp, **nmdp;
2130         struct mod_metadata *mp, *nmp;
2131         const struct mod_depend *verinfo;
2132         modlist_t mod;
2133         const char *modname, *nmodname;
2134         int ver, error = 0;
2135
2136         /*
2137          * All files are dependent on /kernel.
2138          */
2139         sx_assert(&kld_sx, SA_XLOCKED);
2140         if (linker_kernel_file) {
2141                 linker_kernel_file->refs++;
2142                 error = linker_file_add_dependency(lf, linker_kernel_file);
2143                 if (error)
2144                         return (error);
2145         }
2146         if (linker_file_lookup_set(lf, MDT_SETNAME, &start, &stop,
2147             NULL) != 0)
2148                 return (0);
2149         for (mdp = start; mdp < stop; mdp++) {
2150                 mp = *mdp;
2151                 if (mp->md_type != MDT_VERSION)
2152                         continue;
2153                 modname = mp->md_cval;
2154                 ver = ((const struct mod_version *)mp->md_data)->mv_version;
2155                 mod = modlist_lookup(modname, ver);
2156                 if (mod != NULL) {
2157                         printf("interface %s.%d already present in the KLD"
2158                             " '%s'!\n", modname, ver,
2159                             mod->container->filename);
2160                         return (EEXIST);
2161                 }
2162         }
2163
2164         for (mdp = start; mdp < stop; mdp++) {
2165                 mp = *mdp;
2166                 if (mp->md_type != MDT_DEPEND)
2167                         continue;
2168                 modname = mp->md_cval;
2169                 verinfo = mp->md_data;
2170                 nmodname = NULL;
2171                 for (nmdp = start; nmdp < stop; nmdp++) {
2172                         nmp = *nmdp;
2173                         if (nmp->md_type != MDT_VERSION)
2174                                 continue;
2175                         nmodname = nmp->md_cval;
2176                         if (strcmp(modname, nmodname) == 0)
2177                                 break;
2178                 }
2179                 if (nmdp < stop)/* early exit, it's a self reference */
2180                         continue;
2181                 mod = modlist_lookup2(modname, verinfo);
2182                 if (mod) {      /* woohoo, it's loaded already */
2183                         lfdep = mod->container;
2184                         lfdep->refs++;
2185                         error = linker_file_add_dependency(lf, lfdep);
2186                         if (error)
2187                                 break;
2188                         continue;
2189                 }
2190                 error = linker_load_module(NULL, modname, lf, verinfo, NULL);
2191                 if (error) {
2192                         printf("KLD %s: depends on %s - not available or"
2193                             " version mismatch\n", lf->filename, modname);
2194                         break;
2195                 }
2196         }
2197
2198         if (error)
2199                 return (error);
2200         linker_addmodules(lf, start, stop, 0);
2201         return (error);
2202 }
2203
2204 static int
2205 sysctl_kern_function_list_iterate(const char *name, void *opaque)
2206 {
2207         struct sysctl_req *req;
2208
2209         req = opaque;
2210         return (SYSCTL_OUT(req, name, strlen(name) + 1));
2211 }
2212
2213 /*
2214  * Export a nul-separated, double-nul-terminated list of all function names
2215  * in the kernel.
2216  */
2217 static int
2218 sysctl_kern_function_list(SYSCTL_HANDLER_ARGS)
2219 {
2220         linker_file_t lf;
2221         int error;
2222
2223 #ifdef MAC
2224         error = mac_kld_check_stat(req->td->td_ucred);
2225         if (error)
2226                 return (error);
2227 #endif
2228         error = sysctl_wire_old_buffer(req, 0);
2229         if (error != 0)
2230                 return (error);
2231         sx_xlock(&kld_sx);
2232         TAILQ_FOREACH(lf, &linker_files, link) {
2233                 error = LINKER_EACH_FUNCTION_NAME(lf,
2234                     sysctl_kern_function_list_iterate, req);
2235                 if (error) {
2236                         sx_xunlock(&kld_sx);
2237                         return (error);
2238                 }
2239         }
2240         sx_xunlock(&kld_sx);
2241         return (SYSCTL_OUT(req, "", 1));
2242 }
2243
2244 SYSCTL_PROC(_kern, OID_AUTO, function_list, CTLTYPE_OPAQUE | CTLFLAG_RD,
2245     NULL, 0, sysctl_kern_function_list, "", "kernel function list");