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