]> git.kernelconcepts.de Git - karo-tx-linux.git/blob - kernel/module.c
arm: imx6: defconfig: update tx6 defconfigs
[karo-tx-linux.git] / kernel / module.c
1 /*
2    Copyright (C) 2002 Richard Henderson
3    Copyright (C) 2001 Rusty Russell, 2002, 2010 Rusty Russell IBM.
4
5     This program is free software; you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation; either version 2 of the License, or
8     (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
15     You should have received a copy of the GNU General Public License
16     along with this program; if not, write to the Free Software
17     Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18 */
19 #include <linux/export.h>
20 #include <linux/moduleloader.h>
21 #include <linux/ftrace_event.h>
22 #include <linux/init.h>
23 #include <linux/kallsyms.h>
24 #include <linux/file.h>
25 #include <linux/fs.h>
26 #include <linux/sysfs.h>
27 #include <linux/kernel.h>
28 #include <linux/slab.h>
29 #include <linux/vmalloc.h>
30 #include <linux/elf.h>
31 #include <linux/proc_fs.h>
32 #include <linux/security.h>
33 #include <linux/seq_file.h>
34 #include <linux/syscalls.h>
35 #include <linux/fcntl.h>
36 #include <linux/rcupdate.h>
37 #include <linux/capability.h>
38 #include <linux/cpu.h>
39 #include <linux/moduleparam.h>
40 #include <linux/errno.h>
41 #include <linux/err.h>
42 #include <linux/vermagic.h>
43 #include <linux/notifier.h>
44 #include <linux/sched.h>
45 #include <linux/stop_machine.h>
46 #include <linux/device.h>
47 #include <linux/string.h>
48 #include <linux/mutex.h>
49 #include <linux/rculist.h>
50 #include <asm/uaccess.h>
51 #include <asm/cacheflush.h>
52 #include <asm/mmu_context.h>
53 #include <linux/license.h>
54 #include <asm/sections.h>
55 #include <linux/tracepoint.h>
56 #include <linux/ftrace.h>
57 #include <linux/async.h>
58 #include <linux/percpu.h>
59 #include <linux/kmemleak.h>
60 #include <linux/jump_label.h>
61 #include <linux/pfn.h>
62 #include <linux/bsearch.h>
63 #include <linux/fips.h>
64 #include <uapi/linux/module.h>
65 #include "module-internal.h"
66
67 #define CREATE_TRACE_POINTS
68 #include <trace/events/module.h>
69
70 #ifndef ARCH_SHF_SMALL
71 #define ARCH_SHF_SMALL 0
72 #endif
73
74 /*
75  * Modules' sections will be aligned on page boundaries
76  * to ensure complete separation of code and data, but
77  * only when CONFIG_DEBUG_SET_MODULE_RONX=y
78  */
79 #ifdef CONFIG_DEBUG_SET_MODULE_RONX
80 # define debug_align(X) ALIGN(X, PAGE_SIZE)
81 #else
82 # define debug_align(X) (X)
83 #endif
84
85 /*
86  * Given BASE and SIZE this macro calculates the number of pages the
87  * memory regions occupies
88  */
89 #define MOD_NUMBER_OF_PAGES(BASE, SIZE) (((SIZE) > 0) ?         \
90                 (PFN_DOWN((unsigned long)(BASE) + (SIZE) - 1) - \
91                          PFN_DOWN((unsigned long)BASE) + 1)     \
92                 : (0UL))
93
94 /* If this is set, the section belongs in the init part of the module */
95 #define INIT_OFFSET_MASK (1UL << (BITS_PER_LONG-1))
96
97 /*
98  * Mutex protects:
99  * 1) List of modules (also safely readable with preempt_disable),
100  * 2) module_use links,
101  * 3) module_addr_min/module_addr_max.
102  * (delete uses stop_machine/add uses RCU list operations). */
103 DEFINE_MUTEX(module_mutex);
104 EXPORT_SYMBOL_GPL(module_mutex);
105 static LIST_HEAD(modules);
106 #ifdef CONFIG_KGDB_KDB
107 struct list_head *kdb_modules = &modules; /* kdb needs the list of modules */
108 #endif /* CONFIG_KGDB_KDB */
109
110 #ifdef CONFIG_MODULE_SIG
111 #ifdef CONFIG_MODULE_SIG_FORCE
112 static bool sig_enforce = true;
113 #else
114 static bool sig_enforce = false;
115
116 static int param_set_bool_enable_only(const char *val,
117                                       const struct kernel_param *kp)
118 {
119         int err;
120         bool test;
121         struct kernel_param dummy_kp = *kp;
122
123         dummy_kp.arg = &test;
124
125         err = param_set_bool(val, &dummy_kp);
126         if (err)
127                 return err;
128
129         /* Don't let them unset it once it's set! */
130         if (!test && sig_enforce)
131                 return -EROFS;
132
133         if (test)
134                 sig_enforce = true;
135         return 0;
136 }
137
138 static const struct kernel_param_ops param_ops_bool_enable_only = {
139         .flags = KERNEL_PARAM_FL_NOARG,
140         .set = param_set_bool_enable_only,
141         .get = param_get_bool,
142 };
143 #define param_check_bool_enable_only param_check_bool
144
145 module_param(sig_enforce, bool_enable_only, 0644);
146 #endif /* !CONFIG_MODULE_SIG_FORCE */
147 #endif /* CONFIG_MODULE_SIG */
148
149 /* Block module loading/unloading? */
150 int modules_disabled = 0;
151 core_param(nomodule, modules_disabled, bint, 0);
152
153 /* Waiting for a module to finish initializing? */
154 static DECLARE_WAIT_QUEUE_HEAD(module_wq);
155
156 static BLOCKING_NOTIFIER_HEAD(module_notify_list);
157
158 /* Bounds of module allocation, for speeding __module_address.
159  * Protected by module_mutex. */
160 static unsigned long module_addr_min = -1UL, module_addr_max = 0;
161
162 int register_module_notifier(struct notifier_block * nb)
163 {
164         return blocking_notifier_chain_register(&module_notify_list, nb);
165 }
166 EXPORT_SYMBOL(register_module_notifier);
167
168 int unregister_module_notifier(struct notifier_block * nb)
169 {
170         return blocking_notifier_chain_unregister(&module_notify_list, nb);
171 }
172 EXPORT_SYMBOL(unregister_module_notifier);
173
174 struct load_info {
175         Elf_Ehdr *hdr;
176         unsigned long len;
177         Elf_Shdr *sechdrs;
178         char *secstrings, *strtab;
179         unsigned long symoffs, stroffs;
180         struct _ddebug *debug;
181         unsigned int num_debug;
182         bool sig_ok;
183         struct {
184                 unsigned int sym, str, mod, vers, info, pcpu;
185         } index;
186 };
187
188 /* We require a truly strong try_module_get(): 0 means failure due to
189    ongoing or failed initialization etc. */
190 static inline int strong_try_module_get(struct module *mod)
191 {
192         BUG_ON(mod && mod->state == MODULE_STATE_UNFORMED);
193         if (mod && mod->state == MODULE_STATE_COMING)
194                 return -EBUSY;
195         if (try_module_get(mod))
196                 return 0;
197         else
198                 return -ENOENT;
199 }
200
201 static inline void add_taint_module(struct module *mod, unsigned flag,
202                                     enum lockdep_ok lockdep_ok)
203 {
204         add_taint(flag, lockdep_ok);
205         mod->taints |= (1U << flag);
206 }
207
208 /*
209  * A thread that wants to hold a reference to a module only while it
210  * is running can call this to safely exit.  nfsd and lockd use this.
211  */
212 void __module_put_and_exit(struct module *mod, long code)
213 {
214         module_put(mod);
215         do_exit(code);
216 }
217 EXPORT_SYMBOL(__module_put_and_exit);
218
219 /* Find a module section: 0 means not found. */
220 static unsigned int find_sec(const struct load_info *info, const char *name)
221 {
222         unsigned int i;
223
224         for (i = 1; i < info->hdr->e_shnum; i++) {
225                 Elf_Shdr *shdr = &info->sechdrs[i];
226                 /* Alloc bit cleared means "ignore it." */
227                 if ((shdr->sh_flags & SHF_ALLOC)
228                     && strcmp(info->secstrings + shdr->sh_name, name) == 0)
229                         return i;
230         }
231         return 0;
232 }
233
234 /* Find a module section, or NULL. */
235 static void *section_addr(const struct load_info *info, const char *name)
236 {
237         /* Section 0 has sh_addr 0. */
238         return (void *)info->sechdrs[find_sec(info, name)].sh_addr;
239 }
240
241 /* Find a module section, or NULL.  Fill in number of "objects" in section. */
242 static void *section_objs(const struct load_info *info,
243                           const char *name,
244                           size_t object_size,
245                           unsigned int *num)
246 {
247         unsigned int sec = find_sec(info, name);
248
249         /* Section 0 has sh_addr 0 and sh_size 0. */
250         *num = info->sechdrs[sec].sh_size / object_size;
251         return (void *)info->sechdrs[sec].sh_addr;
252 }
253
254 /* Provided by the linker */
255 extern const struct kernel_symbol __start___ksymtab[];
256 extern const struct kernel_symbol __stop___ksymtab[];
257 extern const struct kernel_symbol __start___ksymtab_gpl[];
258 extern const struct kernel_symbol __stop___ksymtab_gpl[];
259 extern const struct kernel_symbol __start___ksymtab_gpl_future[];
260 extern const struct kernel_symbol __stop___ksymtab_gpl_future[];
261 extern const unsigned long __start___kcrctab[];
262 extern const unsigned long __start___kcrctab_gpl[];
263 extern const unsigned long __start___kcrctab_gpl_future[];
264 #ifdef CONFIG_UNUSED_SYMBOLS
265 extern const struct kernel_symbol __start___ksymtab_unused[];
266 extern const struct kernel_symbol __stop___ksymtab_unused[];
267 extern const struct kernel_symbol __start___ksymtab_unused_gpl[];
268 extern const struct kernel_symbol __stop___ksymtab_unused_gpl[];
269 extern const unsigned long __start___kcrctab_unused[];
270 extern const unsigned long __start___kcrctab_unused_gpl[];
271 #endif
272
273 #ifndef CONFIG_MODVERSIONS
274 #define symversion(base, idx) NULL
275 #else
276 #define symversion(base, idx) ((base != NULL) ? ((base) + (idx)) : NULL)
277 #endif
278
279 static bool each_symbol_in_section(const struct symsearch *arr,
280                                    unsigned int arrsize,
281                                    struct module *owner,
282                                    bool (*fn)(const struct symsearch *syms,
283                                               struct module *owner,
284                                               void *data),
285                                    void *data)
286 {
287         unsigned int j;
288
289         for (j = 0; j < arrsize; j++) {
290                 if (fn(&arr[j], owner, data))
291                         return true;
292         }
293
294         return false;
295 }
296
297 /* Returns true as soon as fn returns true, otherwise false. */
298 bool each_symbol_section(bool (*fn)(const struct symsearch *arr,
299                                     struct module *owner,
300                                     void *data),
301                          void *data)
302 {
303         struct module *mod;
304         static const struct symsearch arr[] = {
305                 { __start___ksymtab, __stop___ksymtab, __start___kcrctab,
306                   NOT_GPL_ONLY, false },
307                 { __start___ksymtab_gpl, __stop___ksymtab_gpl,
308                   __start___kcrctab_gpl,
309                   GPL_ONLY, false },
310                 { __start___ksymtab_gpl_future, __stop___ksymtab_gpl_future,
311                   __start___kcrctab_gpl_future,
312                   WILL_BE_GPL_ONLY, false },
313 #ifdef CONFIG_UNUSED_SYMBOLS
314                 { __start___ksymtab_unused, __stop___ksymtab_unused,
315                   __start___kcrctab_unused,
316                   NOT_GPL_ONLY, true },
317                 { __start___ksymtab_unused_gpl, __stop___ksymtab_unused_gpl,
318                   __start___kcrctab_unused_gpl,
319                   GPL_ONLY, true },
320 #endif
321         };
322
323         if (each_symbol_in_section(arr, ARRAY_SIZE(arr), NULL, fn, data))
324                 return true;
325
326         list_for_each_entry_rcu(mod, &modules, list) {
327                 struct symsearch arr[] = {
328                         { mod->syms, mod->syms + mod->num_syms, mod->crcs,
329                           NOT_GPL_ONLY, false },
330                         { mod->gpl_syms, mod->gpl_syms + mod->num_gpl_syms,
331                           mod->gpl_crcs,
332                           GPL_ONLY, false },
333                         { mod->gpl_future_syms,
334                           mod->gpl_future_syms + mod->num_gpl_future_syms,
335                           mod->gpl_future_crcs,
336                           WILL_BE_GPL_ONLY, false },
337 #ifdef CONFIG_UNUSED_SYMBOLS
338                         { mod->unused_syms,
339                           mod->unused_syms + mod->num_unused_syms,
340                           mod->unused_crcs,
341                           NOT_GPL_ONLY, true },
342                         { mod->unused_gpl_syms,
343                           mod->unused_gpl_syms + mod->num_unused_gpl_syms,
344                           mod->unused_gpl_crcs,
345                           GPL_ONLY, true },
346 #endif
347                 };
348
349                 if (mod->state == MODULE_STATE_UNFORMED)
350                         continue;
351
352                 if (each_symbol_in_section(arr, ARRAY_SIZE(arr), mod, fn, data))
353                         return true;
354         }
355         return false;
356 }
357 EXPORT_SYMBOL_GPL(each_symbol_section);
358
359 struct find_symbol_arg {
360         /* Input */
361         const char *name;
362         bool gplok;
363         bool warn;
364
365         /* Output */
366         struct module *owner;
367         const unsigned long *crc;
368         const struct kernel_symbol *sym;
369 };
370
371 static bool check_symbol(const struct symsearch *syms,
372                                  struct module *owner,
373                                  unsigned int symnum, void *data)
374 {
375         struct find_symbol_arg *fsa = data;
376
377         if (!fsa->gplok) {
378                 if (syms->licence == GPL_ONLY)
379                         return false;
380                 if (syms->licence == WILL_BE_GPL_ONLY && fsa->warn) {
381                         printk(KERN_WARNING "Symbol %s is being used "
382                                "by a non-GPL module, which will not "
383                                "be allowed in the future\n", fsa->name);
384                 }
385         }
386
387 #ifdef CONFIG_UNUSED_SYMBOLS
388         if (syms->unused && fsa->warn) {
389                 printk(KERN_WARNING "Symbol %s is marked as UNUSED, "
390                        "however this module is using it.\n", fsa->name);
391                 printk(KERN_WARNING
392                        "This symbol will go away in the future.\n");
393                 printk(KERN_WARNING
394                        "Please evalute if this is the right api to use and if "
395                        "it really is, submit a report the linux kernel "
396                        "mailinglist together with submitting your code for "
397                        "inclusion.\n");
398         }
399 #endif
400
401         fsa->owner = owner;
402         fsa->crc = symversion(syms->crcs, symnum);
403         fsa->sym = &syms->start[symnum];
404         return true;
405 }
406
407 static int cmp_name(const void *va, const void *vb)
408 {
409         const char *a;
410         const struct kernel_symbol *b;
411         a = va; b = vb;
412         return strcmp(a, b->name);
413 }
414
415 static bool find_symbol_in_section(const struct symsearch *syms,
416                                    struct module *owner,
417                                    void *data)
418 {
419         struct find_symbol_arg *fsa = data;
420         struct kernel_symbol *sym;
421
422         sym = bsearch(fsa->name, syms->start, syms->stop - syms->start,
423                         sizeof(struct kernel_symbol), cmp_name);
424
425         if (sym != NULL && check_symbol(syms, owner, sym - syms->start, data))
426                 return true;
427
428         return false;
429 }
430
431 /* Find a symbol and return it, along with, (optional) crc and
432  * (optional) module which owns it.  Needs preempt disabled or module_mutex. */
433 const struct kernel_symbol *find_symbol(const char *name,
434                                         struct module **owner,
435                                         const unsigned long **crc,
436                                         bool gplok,
437                                         bool warn)
438 {
439         struct find_symbol_arg fsa;
440
441         fsa.name = name;
442         fsa.gplok = gplok;
443         fsa.warn = warn;
444
445         if (each_symbol_section(find_symbol_in_section, &fsa)) {
446                 if (owner)
447                         *owner = fsa.owner;
448                 if (crc)
449                         *crc = fsa.crc;
450                 return fsa.sym;
451         }
452
453         pr_debug("Failed to find symbol %s\n", name);
454         return NULL;
455 }
456 EXPORT_SYMBOL_GPL(find_symbol);
457
458 /* Search for module by name: must hold module_mutex. */
459 static struct module *find_module_all(const char *name, size_t len,
460                                       bool even_unformed)
461 {
462         struct module *mod;
463
464         list_for_each_entry(mod, &modules, list) {
465                 if (!even_unformed && mod->state == MODULE_STATE_UNFORMED)
466                         continue;
467                 if (strlen(mod->name) == len && !memcmp(mod->name, name, len))
468                         return mod;
469         }
470         return NULL;
471 }
472
473 struct module *find_module(const char *name)
474 {
475         return find_module_all(name, strlen(name), false);
476 }
477 EXPORT_SYMBOL_GPL(find_module);
478
479 #ifdef CONFIG_SMP
480
481 static inline void __percpu *mod_percpu(struct module *mod)
482 {
483         return mod->percpu;
484 }
485
486 static int percpu_modalloc(struct module *mod, struct load_info *info)
487 {
488         Elf_Shdr *pcpusec = &info->sechdrs[info->index.pcpu];
489         unsigned long align = pcpusec->sh_addralign;
490
491         if (!pcpusec->sh_size)
492                 return 0;
493
494         if (align > PAGE_SIZE) {
495                 printk(KERN_WARNING "%s: per-cpu alignment %li > %li\n",
496                        mod->name, align, PAGE_SIZE);
497                 align = PAGE_SIZE;
498         }
499
500         mod->percpu = __alloc_reserved_percpu(pcpusec->sh_size, align);
501         if (!mod->percpu) {
502                 printk(KERN_WARNING
503                        "%s: Could not allocate %lu bytes percpu data\n",
504                        mod->name, (unsigned long)pcpusec->sh_size);
505                 return -ENOMEM;
506         }
507         mod->percpu_size = pcpusec->sh_size;
508         return 0;
509 }
510
511 static void percpu_modfree(struct module *mod)
512 {
513         free_percpu(mod->percpu);
514 }
515
516 static unsigned int find_pcpusec(struct load_info *info)
517 {
518         return find_sec(info, ".data..percpu");
519 }
520
521 static void percpu_modcopy(struct module *mod,
522                            const void *from, unsigned long size)
523 {
524         int cpu;
525
526         for_each_possible_cpu(cpu)
527                 memcpy(per_cpu_ptr(mod->percpu, cpu), from, size);
528 }
529
530 /**
531  * is_module_percpu_address - test whether address is from module static percpu
532  * @addr: address to test
533  *
534  * Test whether @addr belongs to module static percpu area.
535  *
536  * RETURNS:
537  * %true if @addr is from module static percpu area
538  */
539 bool is_module_percpu_address(unsigned long addr)
540 {
541         struct module *mod;
542         unsigned int cpu;
543
544         preempt_disable();
545
546         list_for_each_entry_rcu(mod, &modules, list) {
547                 if (mod->state == MODULE_STATE_UNFORMED)
548                         continue;
549                 if (!mod->percpu_size)
550                         continue;
551                 for_each_possible_cpu(cpu) {
552                         void *start = per_cpu_ptr(mod->percpu, cpu);
553
554                         if ((void *)addr >= start &&
555                             (void *)addr < start + mod->percpu_size) {
556                                 preempt_enable();
557                                 return true;
558                         }
559                 }
560         }
561
562         preempt_enable();
563         return false;
564 }
565
566 #else /* ... !CONFIG_SMP */
567
568 static inline void __percpu *mod_percpu(struct module *mod)
569 {
570         return NULL;
571 }
572 static int percpu_modalloc(struct module *mod, struct load_info *info)
573 {
574         /* UP modules shouldn't have this section: ENOMEM isn't quite right */
575         if (info->sechdrs[info->index.pcpu].sh_size != 0)
576                 return -ENOMEM;
577         return 0;
578 }
579 static inline void percpu_modfree(struct module *mod)
580 {
581 }
582 static unsigned int find_pcpusec(struct load_info *info)
583 {
584         return 0;
585 }
586 static inline void percpu_modcopy(struct module *mod,
587                                   const void *from, unsigned long size)
588 {
589         /* pcpusec should be 0, and size of that section should be 0. */
590         BUG_ON(size != 0);
591 }
592 bool is_module_percpu_address(unsigned long addr)
593 {
594         return false;
595 }
596
597 #endif /* CONFIG_SMP */
598
599 #define MODINFO_ATTR(field)     \
600 static void setup_modinfo_##field(struct module *mod, const char *s)  \
601 {                                                                     \
602         mod->field = kstrdup(s, GFP_KERNEL);                          \
603 }                                                                     \
604 static ssize_t show_modinfo_##field(struct module_attribute *mattr,   \
605                         struct module_kobject *mk, char *buffer)      \
606 {                                                                     \
607         return scnprintf(buffer, PAGE_SIZE, "%s\n", mk->mod->field);  \
608 }                                                                     \
609 static int modinfo_##field##_exists(struct module *mod)               \
610 {                                                                     \
611         return mod->field != NULL;                                    \
612 }                                                                     \
613 static void free_modinfo_##field(struct module *mod)                  \
614 {                                                                     \
615         kfree(mod->field);                                            \
616         mod->field = NULL;                                            \
617 }                                                                     \
618 static struct module_attribute modinfo_##field = {                    \
619         .attr = { .name = __stringify(field), .mode = 0444 },         \
620         .show = show_modinfo_##field,                                 \
621         .setup = setup_modinfo_##field,                               \
622         .test = modinfo_##field##_exists,                             \
623         .free = free_modinfo_##field,                                 \
624 };
625
626 MODINFO_ATTR(version);
627 MODINFO_ATTR(srcversion);
628
629 static char last_unloaded_module[MODULE_NAME_LEN+1];
630
631 #ifdef CONFIG_MODULE_UNLOAD
632
633 EXPORT_TRACEPOINT_SYMBOL(module_get);
634
635 /* Init the unload section of the module. */
636 static int module_unload_init(struct module *mod)
637 {
638         mod->refptr = alloc_percpu(struct module_ref);
639         if (!mod->refptr)
640                 return -ENOMEM;
641
642         INIT_LIST_HEAD(&mod->source_list);
643         INIT_LIST_HEAD(&mod->target_list);
644
645         /* Hold reference count during initialization. */
646         __this_cpu_write(mod->refptr->incs, 1);
647
648         return 0;
649 }
650
651 /* Does a already use b? */
652 static int already_uses(struct module *a, struct module *b)
653 {
654         struct module_use *use;
655
656         list_for_each_entry(use, &b->source_list, source_list) {
657                 if (use->source == a) {
658                         pr_debug("%s uses %s!\n", a->name, b->name);
659                         return 1;
660                 }
661         }
662         pr_debug("%s does not use %s!\n", a->name, b->name);
663         return 0;
664 }
665
666 /*
667  * Module a uses b
668  *  - we add 'a' as a "source", 'b' as a "target" of module use
669  *  - the module_use is added to the list of 'b' sources (so
670  *    'b' can walk the list to see who sourced them), and of 'a'
671  *    targets (so 'a' can see what modules it targets).
672  */
673 static int add_module_usage(struct module *a, struct module *b)
674 {
675         struct module_use *use;
676
677         pr_debug("Allocating new usage for %s.\n", a->name);
678         use = kmalloc(sizeof(*use), GFP_ATOMIC);
679         if (!use) {
680                 printk(KERN_WARNING "%s: out of memory loading\n", a->name);
681                 return -ENOMEM;
682         }
683
684         use->source = a;
685         use->target = b;
686         list_add(&use->source_list, &b->source_list);
687         list_add(&use->target_list, &a->target_list);
688         return 0;
689 }
690
691 /* Module a uses b: caller needs module_mutex() */
692 int ref_module(struct module *a, struct module *b)
693 {
694         int err;
695
696         if (b == NULL || already_uses(a, b))
697                 return 0;
698
699         /* If module isn't available, we fail. */
700         err = strong_try_module_get(b);
701         if (err)
702                 return err;
703
704         err = add_module_usage(a, b);
705         if (err) {
706                 module_put(b);
707                 return err;
708         }
709         return 0;
710 }
711 EXPORT_SYMBOL_GPL(ref_module);
712
713 /* Clear the unload stuff of the module. */
714 static void module_unload_free(struct module *mod)
715 {
716         struct module_use *use, *tmp;
717
718         mutex_lock(&module_mutex);
719         list_for_each_entry_safe(use, tmp, &mod->target_list, target_list) {
720                 struct module *i = use->target;
721                 pr_debug("%s unusing %s\n", mod->name, i->name);
722                 module_put(i);
723                 list_del(&use->source_list);
724                 list_del(&use->target_list);
725                 kfree(use);
726         }
727         mutex_unlock(&module_mutex);
728
729         free_percpu(mod->refptr);
730 }
731
732 #ifdef CONFIG_MODULE_FORCE_UNLOAD
733 static inline int try_force_unload(unsigned int flags)
734 {
735         int ret = (flags & O_TRUNC);
736         if (ret)
737                 add_taint(TAINT_FORCED_RMMOD, LOCKDEP_NOW_UNRELIABLE);
738         return ret;
739 }
740 #else
741 static inline int try_force_unload(unsigned int flags)
742 {
743         return 0;
744 }
745 #endif /* CONFIG_MODULE_FORCE_UNLOAD */
746
747 struct stopref
748 {
749         struct module *mod;
750         int flags;
751         int *forced;
752 };
753
754 /* Whole machine is stopped with interrupts off when this runs. */
755 static int __try_stop_module(void *_sref)
756 {
757         struct stopref *sref = _sref;
758
759         /* If it's not unused, quit unless we're forcing. */
760         if (module_refcount(sref->mod) != 0) {
761                 if (!(*sref->forced = try_force_unload(sref->flags)))
762                         return -EWOULDBLOCK;
763         }
764
765         /* Mark it as dying. */
766         sref->mod->state = MODULE_STATE_GOING;
767         return 0;
768 }
769
770 static int try_stop_module(struct module *mod, int flags, int *forced)
771 {
772         struct stopref sref = { mod, flags, forced };
773
774         return stop_machine(__try_stop_module, &sref, NULL);
775 }
776
777 unsigned long module_refcount(struct module *mod)
778 {
779         unsigned long incs = 0, decs = 0;
780         int cpu;
781
782         for_each_possible_cpu(cpu)
783                 decs += per_cpu_ptr(mod->refptr, cpu)->decs;
784         /*
785          * ensure the incs are added up after the decs.
786          * module_put ensures incs are visible before decs with smp_wmb.
787          *
788          * This 2-count scheme avoids the situation where the refcount
789          * for CPU0 is read, then CPU0 increments the module refcount,
790          * then CPU1 drops that refcount, then the refcount for CPU1 is
791          * read. We would record a decrement but not its corresponding
792          * increment so we would see a low count (disaster).
793          *
794          * Rare situation? But module_refcount can be preempted, and we
795          * might be tallying up 4096+ CPUs. So it is not impossible.
796          */
797         smp_rmb();
798         for_each_possible_cpu(cpu)
799                 incs += per_cpu_ptr(mod->refptr, cpu)->incs;
800         return incs - decs;
801 }
802 EXPORT_SYMBOL(module_refcount);
803
804 /* This exists whether we can unload or not */
805 static void free_module(struct module *mod);
806
807 SYSCALL_DEFINE2(delete_module, const char __user *, name_user,
808                 unsigned int, flags)
809 {
810         struct module *mod;
811         char name[MODULE_NAME_LEN];
812         int ret, forced = 0;
813
814         if (!capable(CAP_SYS_MODULE) || modules_disabled)
815                 return -EPERM;
816
817         if (strncpy_from_user(name, name_user, MODULE_NAME_LEN-1) < 0)
818                 return -EFAULT;
819         name[MODULE_NAME_LEN-1] = '\0';
820
821         if (!(flags & O_NONBLOCK)) {
822                 printk(KERN_WARNING
823                        "waiting module removal not supported: please upgrade");
824         }
825
826         if (mutex_lock_interruptible(&module_mutex) != 0)
827                 return -EINTR;
828
829         mod = find_module(name);
830         if (!mod) {
831                 ret = -ENOENT;
832                 goto out;
833         }
834
835         if (!list_empty(&mod->source_list)) {
836                 /* Other modules depend on us: get rid of them first. */
837                 ret = -EWOULDBLOCK;
838                 goto out;
839         }
840
841         /* Doing init or already dying? */
842         if (mod->state != MODULE_STATE_LIVE) {
843                 /* FIXME: if (force), slam module count damn the torpedoes */
844                 pr_debug("%s already dying\n", mod->name);
845                 ret = -EBUSY;
846                 goto out;
847         }
848
849         /* If it has an init func, it must have an exit func to unload */
850         if (mod->init && !mod->exit) {
851                 forced = try_force_unload(flags);
852                 if (!forced) {
853                         /* This module can't be removed */
854                         ret = -EBUSY;
855                         goto out;
856                 }
857         }
858
859         /* Stop the machine so refcounts can't move and disable module. */
860         ret = try_stop_module(mod, flags, &forced);
861         if (ret != 0)
862                 goto out;
863
864         mutex_unlock(&module_mutex);
865         /* Final destruction now no one is using it. */
866         if (mod->exit != NULL)
867                 mod->exit();
868         blocking_notifier_call_chain(&module_notify_list,
869                                      MODULE_STATE_GOING, mod);
870         async_synchronize_full();
871
872         /* Store the name of the last unloaded module for diagnostic purposes */
873         strlcpy(last_unloaded_module, mod->name, sizeof(last_unloaded_module));
874
875         free_module(mod);
876         return 0;
877 out:
878         mutex_unlock(&module_mutex);
879         return ret;
880 }
881
882 static inline void print_unload_info(struct seq_file *m, struct module *mod)
883 {
884         struct module_use *use;
885         int printed_something = 0;
886
887         seq_printf(m, " %lu ", module_refcount(mod));
888
889         /* Always include a trailing , so userspace can differentiate
890            between this and the old multi-field proc format. */
891         list_for_each_entry(use, &mod->source_list, source_list) {
892                 printed_something = 1;
893                 seq_printf(m, "%s,", use->source->name);
894         }
895
896         if (mod->init != NULL && mod->exit == NULL) {
897                 printed_something = 1;
898                 seq_printf(m, "[permanent],");
899         }
900
901         if (!printed_something)
902                 seq_printf(m, "-");
903 }
904
905 void __symbol_put(const char *symbol)
906 {
907         struct module *owner;
908
909         preempt_disable();
910         if (!find_symbol(symbol, &owner, NULL, true, false))
911                 BUG();
912         module_put(owner);
913         preempt_enable();
914 }
915 EXPORT_SYMBOL(__symbol_put);
916
917 /* Note this assumes addr is a function, which it currently always is. */
918 void symbol_put_addr(void *addr)
919 {
920         struct module *modaddr;
921         unsigned long a = (unsigned long)dereference_function_descriptor(addr);
922
923         if (core_kernel_text(a))
924                 return;
925
926         /* module_text_address is safe here: we're supposed to have reference
927          * to module from symbol_get, so it can't go away. */
928         modaddr = __module_text_address(a);
929         BUG_ON(!modaddr);
930         module_put(modaddr);
931 }
932 EXPORT_SYMBOL_GPL(symbol_put_addr);
933
934 static ssize_t show_refcnt(struct module_attribute *mattr,
935                            struct module_kobject *mk, char *buffer)
936 {
937         return sprintf(buffer, "%lu\n", module_refcount(mk->mod));
938 }
939
940 static struct module_attribute modinfo_refcnt =
941         __ATTR(refcnt, 0444, show_refcnt, NULL);
942
943 void __module_get(struct module *module)
944 {
945         if (module) {
946                 preempt_disable();
947                 __this_cpu_inc(module->refptr->incs);
948                 trace_module_get(module, _RET_IP_);
949                 preempt_enable();
950         }
951 }
952 EXPORT_SYMBOL(__module_get);
953
954 bool try_module_get(struct module *module)
955 {
956         bool ret = true;
957
958         if (module) {
959                 preempt_disable();
960
961                 if (likely(module_is_live(module))) {
962                         __this_cpu_inc(module->refptr->incs);
963                         trace_module_get(module, _RET_IP_);
964                 } else
965                         ret = false;
966
967                 preempt_enable();
968         }
969         return ret;
970 }
971 EXPORT_SYMBOL(try_module_get);
972
973 void module_put(struct module *module)
974 {
975         if (module) {
976                 preempt_disable();
977                 smp_wmb(); /* see comment in module_refcount */
978                 __this_cpu_inc(module->refptr->decs);
979
980                 trace_module_put(module, _RET_IP_);
981                 preempt_enable();
982         }
983 }
984 EXPORT_SYMBOL(module_put);
985
986 #else /* !CONFIG_MODULE_UNLOAD */
987 static inline void print_unload_info(struct seq_file *m, struct module *mod)
988 {
989         /* We don't know the usage count, or what modules are using. */
990         seq_printf(m, " - -");
991 }
992
993 static inline void module_unload_free(struct module *mod)
994 {
995 }
996
997 int ref_module(struct module *a, struct module *b)
998 {
999         return strong_try_module_get(b);
1000 }
1001 EXPORT_SYMBOL_GPL(ref_module);
1002
1003 static inline int module_unload_init(struct module *mod)
1004 {
1005         return 0;
1006 }
1007 #endif /* CONFIG_MODULE_UNLOAD */
1008
1009 static size_t module_flags_taint(struct module *mod, char *buf)
1010 {
1011         size_t l = 0;
1012
1013         if (mod->taints & (1 << TAINT_PROPRIETARY_MODULE))
1014                 buf[l++] = 'P';
1015         if (mod->taints & (1 << TAINT_OOT_MODULE))
1016                 buf[l++] = 'O';
1017         if (mod->taints & (1 << TAINT_FORCED_MODULE))
1018                 buf[l++] = 'F';
1019         if (mod->taints & (1 << TAINT_CRAP))
1020                 buf[l++] = 'C';
1021         /*
1022          * TAINT_FORCED_RMMOD: could be added.
1023          * TAINT_UNSAFE_SMP, TAINT_MACHINE_CHECK, TAINT_BAD_PAGE don't
1024          * apply to modules.
1025          */
1026         return l;
1027 }
1028
1029 static ssize_t show_initstate(struct module_attribute *mattr,
1030                               struct module_kobject *mk, char *buffer)
1031 {
1032         const char *state = "unknown";
1033
1034         switch (mk->mod->state) {
1035         case MODULE_STATE_LIVE:
1036                 state = "live";
1037                 break;
1038         case MODULE_STATE_COMING:
1039                 state = "coming";
1040                 break;
1041         case MODULE_STATE_GOING:
1042                 state = "going";
1043                 break;
1044         default:
1045                 BUG();
1046         }
1047         return sprintf(buffer, "%s\n", state);
1048 }
1049
1050 static struct module_attribute modinfo_initstate =
1051         __ATTR(initstate, 0444, show_initstate, NULL);
1052
1053 static ssize_t store_uevent(struct module_attribute *mattr,
1054                             struct module_kobject *mk,
1055                             const char *buffer, size_t count)
1056 {
1057         enum kobject_action action;
1058
1059         if (kobject_action_type(buffer, count, &action) == 0)
1060                 kobject_uevent(&mk->kobj, action);
1061         return count;
1062 }
1063
1064 struct module_attribute module_uevent =
1065         __ATTR(uevent, 0200, NULL, store_uevent);
1066
1067 static ssize_t show_coresize(struct module_attribute *mattr,
1068                              struct module_kobject *mk, char *buffer)
1069 {
1070         return sprintf(buffer, "%u\n", mk->mod->core_size);
1071 }
1072
1073 static struct module_attribute modinfo_coresize =
1074         __ATTR(coresize, 0444, show_coresize, NULL);
1075
1076 static ssize_t show_initsize(struct module_attribute *mattr,
1077                              struct module_kobject *mk, char *buffer)
1078 {
1079         return sprintf(buffer, "%u\n", mk->mod->init_size);
1080 }
1081
1082 static struct module_attribute modinfo_initsize =
1083         __ATTR(initsize, 0444, show_initsize, NULL);
1084
1085 static ssize_t show_taint(struct module_attribute *mattr,
1086                           struct module_kobject *mk, char *buffer)
1087 {
1088         size_t l;
1089
1090         l = module_flags_taint(mk->mod, buffer);
1091         buffer[l++] = '\n';
1092         return l;
1093 }
1094
1095 static struct module_attribute modinfo_taint =
1096         __ATTR(taint, 0444, show_taint, NULL);
1097
1098 static struct module_attribute *modinfo_attrs[] = {
1099         &module_uevent,
1100         &modinfo_version,
1101         &modinfo_srcversion,
1102         &modinfo_initstate,
1103         &modinfo_coresize,
1104         &modinfo_initsize,
1105         &modinfo_taint,
1106 #ifdef CONFIG_MODULE_UNLOAD
1107         &modinfo_refcnt,
1108 #endif
1109         NULL,
1110 };
1111
1112 static const char vermagic[] = VERMAGIC_STRING;
1113
1114 static int try_to_force_load(struct module *mod, const char *reason)
1115 {
1116 #ifdef CONFIG_MODULE_FORCE_LOAD
1117         if (!test_taint(TAINT_FORCED_MODULE))
1118                 printk(KERN_WARNING "%s: %s: kernel tainted.\n",
1119                        mod->name, reason);
1120         add_taint_module(mod, TAINT_FORCED_MODULE, LOCKDEP_NOW_UNRELIABLE);
1121         return 0;
1122 #else
1123         return -ENOEXEC;
1124 #endif
1125 }
1126
1127 #ifdef CONFIG_MODVERSIONS
1128 /* If the arch applies (non-zero) relocations to kernel kcrctab, unapply it. */
1129 static unsigned long maybe_relocated(unsigned long crc,
1130                                      const struct module *crc_owner)
1131 {
1132 #ifdef ARCH_RELOCATES_KCRCTAB
1133         if (crc_owner == NULL)
1134                 return crc - (unsigned long)reloc_start;
1135 #endif
1136         return crc;
1137 }
1138
1139 static int check_version(Elf_Shdr *sechdrs,
1140                          unsigned int versindex,
1141                          const char *symname,
1142                          struct module *mod, 
1143                          const unsigned long *crc,
1144                          const struct module *crc_owner)
1145 {
1146         unsigned int i, num_versions;
1147         struct modversion_info *versions;
1148
1149         /* Exporting module didn't supply crcs?  OK, we're already tainted. */
1150         if (!crc)
1151                 return 1;
1152
1153         /* No versions at all?  modprobe --force does this. */
1154         if (versindex == 0)
1155                 return try_to_force_load(mod, symname) == 0;
1156
1157         versions = (void *) sechdrs[versindex].sh_addr;
1158         num_versions = sechdrs[versindex].sh_size
1159                 / sizeof(struct modversion_info);
1160
1161         for (i = 0; i < num_versions; i++) {
1162                 if (strcmp(versions[i].name, symname) != 0)
1163                         continue;
1164
1165                 if (versions[i].crc == maybe_relocated(*crc, crc_owner))
1166                         return 1;
1167                 pr_debug("Found checksum %lX vs module %lX\n",
1168                        maybe_relocated(*crc, crc_owner), versions[i].crc);
1169                 goto bad_version;
1170         }
1171
1172         printk(KERN_WARNING "%s: no symbol version for %s\n",
1173                mod->name, symname);
1174         return 0;
1175
1176 bad_version:
1177         printk("%s: disagrees about version of symbol %s\n",
1178                mod->name, symname);
1179         return 0;
1180 }
1181
1182 static inline int check_modstruct_version(Elf_Shdr *sechdrs,
1183                                           unsigned int versindex,
1184                                           struct module *mod)
1185 {
1186         const unsigned long *crc;
1187
1188         /* Since this should be found in kernel (which can't be removed),
1189          * no locking is necessary. */
1190         if (!find_symbol(VMLINUX_SYMBOL_STR(module_layout), NULL,
1191                          &crc, true, false))
1192                 BUG();
1193         return check_version(sechdrs, versindex,
1194                              VMLINUX_SYMBOL_STR(module_layout), mod, crc,
1195                              NULL);
1196 }
1197
1198 /* First part is kernel version, which we ignore if module has crcs. */
1199 static inline int same_magic(const char *amagic, const char *bmagic,
1200                              bool has_crcs)
1201 {
1202         if (has_crcs) {
1203                 amagic += strcspn(amagic, " ");
1204                 bmagic += strcspn(bmagic, " ");
1205         }
1206         return strcmp(amagic, bmagic) == 0;
1207 }
1208 #else
1209 static inline int check_version(Elf_Shdr *sechdrs,
1210                                 unsigned int versindex,
1211                                 const char *symname,
1212                                 struct module *mod, 
1213                                 const unsigned long *crc,
1214                                 const struct module *crc_owner)
1215 {
1216         return 1;
1217 }
1218
1219 static inline int check_modstruct_version(Elf_Shdr *sechdrs,
1220                                           unsigned int versindex,
1221                                           struct module *mod)
1222 {
1223         return 1;
1224 }
1225
1226 static inline int same_magic(const char *amagic, const char *bmagic,
1227                              bool has_crcs)
1228 {
1229         return strcmp(amagic, bmagic) == 0;
1230 }
1231 #endif /* CONFIG_MODVERSIONS */
1232
1233 /* Resolve a symbol for this module.  I.e. if we find one, record usage. */
1234 static const struct kernel_symbol *resolve_symbol(struct module *mod,
1235                                                   const struct load_info *info,
1236                                                   const char *name,
1237                                                   char ownername[])
1238 {
1239         struct module *owner;
1240         const struct kernel_symbol *sym;
1241         const unsigned long *crc;
1242         int err;
1243
1244         mutex_lock(&module_mutex);
1245         sym = find_symbol(name, &owner, &crc,
1246                           !(mod->taints & (1 << TAINT_PROPRIETARY_MODULE)), true);
1247         if (!sym)
1248                 goto unlock;
1249
1250         if (!check_version(info->sechdrs, info->index.vers, name, mod, crc,
1251                            owner)) {
1252                 sym = ERR_PTR(-EINVAL);
1253                 goto getname;
1254         }
1255
1256         err = ref_module(mod, owner);
1257         if (err) {
1258                 sym = ERR_PTR(err);
1259                 goto getname;
1260         }
1261
1262 getname:
1263         /* We must make copy under the lock if we failed to get ref. */
1264         strncpy(ownername, module_name(owner), MODULE_NAME_LEN);
1265 unlock:
1266         mutex_unlock(&module_mutex);
1267         return sym;
1268 }
1269
1270 static const struct kernel_symbol *
1271 resolve_symbol_wait(struct module *mod,
1272                     const struct load_info *info,
1273                     const char *name)
1274 {
1275         const struct kernel_symbol *ksym;
1276         char owner[MODULE_NAME_LEN];
1277
1278         if (wait_event_interruptible_timeout(module_wq,
1279                         !IS_ERR(ksym = resolve_symbol(mod, info, name, owner))
1280                         || PTR_ERR(ksym) != -EBUSY,
1281                                              30 * HZ) <= 0) {
1282                 printk(KERN_WARNING "%s: gave up waiting for init of module %s.\n",
1283                        mod->name, owner);
1284         }
1285         return ksym;
1286 }
1287
1288 /*
1289  * /sys/module/foo/sections stuff
1290  * J. Corbet <corbet@lwn.net>
1291  */
1292 #ifdef CONFIG_SYSFS
1293
1294 #ifdef CONFIG_KALLSYMS
1295 static inline bool sect_empty(const Elf_Shdr *sect)
1296 {
1297         return !(sect->sh_flags & SHF_ALLOC) || sect->sh_size == 0;
1298 }
1299
1300 struct module_sect_attr
1301 {
1302         struct module_attribute mattr;
1303         char *name;
1304         unsigned long address;
1305 };
1306
1307 struct module_sect_attrs
1308 {
1309         struct attribute_group grp;
1310         unsigned int nsections;
1311         struct module_sect_attr attrs[0];
1312 };
1313
1314 static ssize_t module_sect_show(struct module_attribute *mattr,
1315                                 struct module_kobject *mk, char *buf)
1316 {
1317         struct module_sect_attr *sattr =
1318                 container_of(mattr, struct module_sect_attr, mattr);
1319         return sprintf(buf, "0x%pK\n", (void *)sattr->address);
1320 }
1321
1322 static void free_sect_attrs(struct module_sect_attrs *sect_attrs)
1323 {
1324         unsigned int section;
1325
1326         for (section = 0; section < sect_attrs->nsections; section++)
1327                 kfree(sect_attrs->attrs[section].name);
1328         kfree(sect_attrs);
1329 }
1330
1331 static void add_sect_attrs(struct module *mod, const struct load_info *info)
1332 {
1333         unsigned int nloaded = 0, i, size[2];
1334         struct module_sect_attrs *sect_attrs;
1335         struct module_sect_attr *sattr;
1336         struct attribute **gattr;
1337
1338         /* Count loaded sections and allocate structures */
1339         for (i = 0; i < info->hdr->e_shnum; i++)
1340                 if (!sect_empty(&info->sechdrs[i]))
1341                         nloaded++;
1342         size[0] = ALIGN(sizeof(*sect_attrs)
1343                         + nloaded * sizeof(sect_attrs->attrs[0]),
1344                         sizeof(sect_attrs->grp.attrs[0]));
1345         size[1] = (nloaded + 1) * sizeof(sect_attrs->grp.attrs[0]);
1346         sect_attrs = kzalloc(size[0] + size[1], GFP_KERNEL);
1347         if (sect_attrs == NULL)
1348                 return;
1349
1350         /* Setup section attributes. */
1351         sect_attrs->grp.name = "sections";
1352         sect_attrs->grp.attrs = (void *)sect_attrs + size[0];
1353
1354         sect_attrs->nsections = 0;
1355         sattr = &sect_attrs->attrs[0];
1356         gattr = &sect_attrs->grp.attrs[0];
1357         for (i = 0; i < info->hdr->e_shnum; i++) {
1358                 Elf_Shdr *sec = &info->sechdrs[i];
1359                 if (sect_empty(sec))
1360                         continue;
1361                 sattr->address = sec->sh_addr;
1362                 sattr->name = kstrdup(info->secstrings + sec->sh_name,
1363                                         GFP_KERNEL);
1364                 if (sattr->name == NULL)
1365                         goto out;
1366                 sect_attrs->nsections++;
1367                 sysfs_attr_init(&sattr->mattr.attr);
1368                 sattr->mattr.show = module_sect_show;
1369                 sattr->mattr.store = NULL;
1370                 sattr->mattr.attr.name = sattr->name;
1371                 sattr->mattr.attr.mode = S_IRUGO;
1372                 *(gattr++) = &(sattr++)->mattr.attr;
1373         }
1374         *gattr = NULL;
1375
1376         if (sysfs_create_group(&mod->mkobj.kobj, &sect_attrs->grp))
1377                 goto out;
1378
1379         mod->sect_attrs = sect_attrs;
1380         return;
1381   out:
1382         free_sect_attrs(sect_attrs);
1383 }
1384
1385 static void remove_sect_attrs(struct module *mod)
1386 {
1387         if (mod->sect_attrs) {
1388                 sysfs_remove_group(&mod->mkobj.kobj,
1389                                    &mod->sect_attrs->grp);
1390                 /* We are positive that no one is using any sect attrs
1391                  * at this point.  Deallocate immediately. */
1392                 free_sect_attrs(mod->sect_attrs);
1393                 mod->sect_attrs = NULL;
1394         }
1395 }
1396
1397 /*
1398  * /sys/module/foo/notes/.section.name gives contents of SHT_NOTE sections.
1399  */
1400
1401 struct module_notes_attrs {
1402         struct kobject *dir;
1403         unsigned int notes;
1404         struct bin_attribute attrs[0];
1405 };
1406
1407 static ssize_t module_notes_read(struct file *filp, struct kobject *kobj,
1408                                  struct bin_attribute *bin_attr,
1409                                  char *buf, loff_t pos, size_t count)
1410 {
1411         /*
1412          * The caller checked the pos and count against our size.
1413          */
1414         memcpy(buf, bin_attr->private + pos, count);
1415         return count;
1416 }
1417
1418 static void free_notes_attrs(struct module_notes_attrs *notes_attrs,
1419                              unsigned int i)
1420 {
1421         if (notes_attrs->dir) {
1422                 while (i-- > 0)
1423                         sysfs_remove_bin_file(notes_attrs->dir,
1424                                               &notes_attrs->attrs[i]);
1425                 kobject_put(notes_attrs->dir);
1426         }
1427         kfree(notes_attrs);
1428 }
1429
1430 static void add_notes_attrs(struct module *mod, const struct load_info *info)
1431 {
1432         unsigned int notes, loaded, i;
1433         struct module_notes_attrs *notes_attrs;
1434         struct bin_attribute *nattr;
1435
1436         /* failed to create section attributes, so can't create notes */
1437         if (!mod->sect_attrs)
1438                 return;
1439
1440         /* Count notes sections and allocate structures.  */
1441         notes = 0;
1442         for (i = 0; i < info->hdr->e_shnum; i++)
1443                 if (!sect_empty(&info->sechdrs[i]) &&
1444                     (info->sechdrs[i].sh_type == SHT_NOTE))
1445                         ++notes;
1446
1447         if (notes == 0)
1448                 return;
1449
1450         notes_attrs = kzalloc(sizeof(*notes_attrs)
1451                               + notes * sizeof(notes_attrs->attrs[0]),
1452                               GFP_KERNEL);
1453         if (notes_attrs == NULL)
1454                 return;
1455
1456         notes_attrs->notes = notes;
1457         nattr = &notes_attrs->attrs[0];
1458         for (loaded = i = 0; i < info->hdr->e_shnum; ++i) {
1459                 if (sect_empty(&info->sechdrs[i]))
1460                         continue;
1461                 if (info->sechdrs[i].sh_type == SHT_NOTE) {
1462                         sysfs_bin_attr_init(nattr);
1463                         nattr->attr.name = mod->sect_attrs->attrs[loaded].name;
1464                         nattr->attr.mode = S_IRUGO;
1465                         nattr->size = info->sechdrs[i].sh_size;
1466                         nattr->private = (void *) info->sechdrs[i].sh_addr;
1467                         nattr->read = module_notes_read;
1468                         ++nattr;
1469                 }
1470                 ++loaded;
1471         }
1472
1473         notes_attrs->dir = kobject_create_and_add("notes", &mod->mkobj.kobj);
1474         if (!notes_attrs->dir)
1475                 goto out;
1476
1477         for (i = 0; i < notes; ++i)
1478                 if (sysfs_create_bin_file(notes_attrs->dir,
1479                                           &notes_attrs->attrs[i]))
1480                         goto out;
1481
1482         mod->notes_attrs = notes_attrs;
1483         return;
1484
1485   out:
1486         free_notes_attrs(notes_attrs, i);
1487 }
1488
1489 static void remove_notes_attrs(struct module *mod)
1490 {
1491         if (mod->notes_attrs)
1492                 free_notes_attrs(mod->notes_attrs, mod->notes_attrs->notes);
1493 }
1494
1495 #else
1496
1497 static inline void add_sect_attrs(struct module *mod,
1498                                   const struct load_info *info)
1499 {
1500 }
1501
1502 static inline void remove_sect_attrs(struct module *mod)
1503 {
1504 }
1505
1506 static inline void add_notes_attrs(struct module *mod,
1507                                    const struct load_info *info)
1508 {
1509 }
1510
1511 static inline void remove_notes_attrs(struct module *mod)
1512 {
1513 }
1514 #endif /* CONFIG_KALLSYMS */
1515
1516 static void add_usage_links(struct module *mod)
1517 {
1518 #ifdef CONFIG_MODULE_UNLOAD
1519         struct module_use *use;
1520         int nowarn;
1521
1522         mutex_lock(&module_mutex);
1523         list_for_each_entry(use, &mod->target_list, target_list) {
1524                 nowarn = sysfs_create_link(use->target->holders_dir,
1525                                            &mod->mkobj.kobj, mod->name);
1526         }
1527         mutex_unlock(&module_mutex);
1528 #endif
1529 }
1530
1531 static void del_usage_links(struct module *mod)
1532 {
1533 #ifdef CONFIG_MODULE_UNLOAD
1534         struct module_use *use;
1535
1536         mutex_lock(&module_mutex);
1537         list_for_each_entry(use, &mod->target_list, target_list)
1538                 sysfs_remove_link(use->target->holders_dir, mod->name);
1539         mutex_unlock(&module_mutex);
1540 #endif
1541 }
1542
1543 static int module_add_modinfo_attrs(struct module *mod)
1544 {
1545         struct module_attribute *attr;
1546         struct module_attribute *temp_attr;
1547         int error = 0;
1548         int i;
1549
1550         mod->modinfo_attrs = kzalloc((sizeof(struct module_attribute) *
1551                                         (ARRAY_SIZE(modinfo_attrs) + 1)),
1552                                         GFP_KERNEL);
1553         if (!mod->modinfo_attrs)
1554                 return -ENOMEM;
1555
1556         temp_attr = mod->modinfo_attrs;
1557         for (i = 0; (attr = modinfo_attrs[i]) && !error; i++) {
1558                 if (!attr->test ||
1559                     (attr->test && attr->test(mod))) {
1560                         memcpy(temp_attr, attr, sizeof(*temp_attr));
1561                         sysfs_attr_init(&temp_attr->attr);
1562                         error = sysfs_create_file(&mod->mkobj.kobj,&temp_attr->attr);
1563                         ++temp_attr;
1564                 }
1565         }
1566         return error;
1567 }
1568
1569 static void module_remove_modinfo_attrs(struct module *mod)
1570 {
1571         struct module_attribute *attr;
1572         int i;
1573
1574         for (i = 0; (attr = &mod->modinfo_attrs[i]); i++) {
1575                 /* pick a field to test for end of list */
1576                 if (!attr->attr.name)
1577                         break;
1578                 sysfs_remove_file(&mod->mkobj.kobj,&attr->attr);
1579                 if (attr->free)
1580                         attr->free(mod);
1581         }
1582         kfree(mod->modinfo_attrs);
1583 }
1584
1585 static void mod_kobject_put(struct module *mod)
1586 {
1587         DECLARE_COMPLETION_ONSTACK(c);
1588         mod->mkobj.kobj_completion = &c;
1589         kobject_put(&mod->mkobj.kobj);
1590         wait_for_completion(&c);
1591 }
1592
1593 static int mod_sysfs_init(struct module *mod)
1594 {
1595         int err;
1596         struct kobject *kobj;
1597
1598         if (!module_sysfs_initialized) {
1599                 printk(KERN_ERR "%s: module sysfs not initialized\n",
1600                        mod->name);
1601                 err = -EINVAL;
1602                 goto out;
1603         }
1604
1605         kobj = kset_find_obj(module_kset, mod->name);
1606         if (kobj) {
1607                 printk(KERN_ERR "%s: module is already loaded\n", mod->name);
1608                 kobject_put(kobj);
1609                 err = -EINVAL;
1610                 goto out;
1611         }
1612
1613         mod->mkobj.mod = mod;
1614
1615         memset(&mod->mkobj.kobj, 0, sizeof(mod->mkobj.kobj));
1616         mod->mkobj.kobj.kset = module_kset;
1617         err = kobject_init_and_add(&mod->mkobj.kobj, &module_ktype, NULL,
1618                                    "%s", mod->name);
1619         if (err)
1620                 mod_kobject_put(mod);
1621
1622         /* delay uevent until full sysfs population */
1623 out:
1624         return err;
1625 }
1626
1627 static int mod_sysfs_setup(struct module *mod,
1628                            const struct load_info *info,
1629                            struct kernel_param *kparam,
1630                            unsigned int num_params)
1631 {
1632         int err;
1633
1634         err = mod_sysfs_init(mod);
1635         if (err)
1636                 goto out;
1637
1638         mod->holders_dir = kobject_create_and_add("holders", &mod->mkobj.kobj);
1639         if (!mod->holders_dir) {
1640                 err = -ENOMEM;
1641                 goto out_unreg;
1642         }
1643
1644         err = module_param_sysfs_setup(mod, kparam, num_params);
1645         if (err)
1646                 goto out_unreg_holders;
1647
1648         err = module_add_modinfo_attrs(mod);
1649         if (err)
1650                 goto out_unreg_param;
1651
1652         add_usage_links(mod);
1653         add_sect_attrs(mod, info);
1654         add_notes_attrs(mod, info);
1655
1656         kobject_uevent(&mod->mkobj.kobj, KOBJ_ADD);
1657         return 0;
1658
1659 out_unreg_param:
1660         module_param_sysfs_remove(mod);
1661 out_unreg_holders:
1662         kobject_put(mod->holders_dir);
1663 out_unreg:
1664         mod_kobject_put(mod);
1665 out:
1666         return err;
1667 }
1668
1669 static void mod_sysfs_fini(struct module *mod)
1670 {
1671         remove_notes_attrs(mod);
1672         remove_sect_attrs(mod);
1673         mod_kobject_put(mod);
1674 }
1675
1676 #else /* !CONFIG_SYSFS */
1677
1678 static int mod_sysfs_setup(struct module *mod,
1679                            const struct load_info *info,
1680                            struct kernel_param *kparam,
1681                            unsigned int num_params)
1682 {
1683         return 0;
1684 }
1685
1686 static void mod_sysfs_fini(struct module *mod)
1687 {
1688 }
1689
1690 static void module_remove_modinfo_attrs(struct module *mod)
1691 {
1692 }
1693
1694 static void del_usage_links(struct module *mod)
1695 {
1696 }
1697
1698 #endif /* CONFIG_SYSFS */
1699
1700 static void mod_sysfs_teardown(struct module *mod)
1701 {
1702         del_usage_links(mod);
1703         module_remove_modinfo_attrs(mod);
1704         module_param_sysfs_remove(mod);
1705         kobject_put(mod->mkobj.drivers_dir);
1706         kobject_put(mod->holders_dir);
1707         mod_sysfs_fini(mod);
1708 }
1709
1710 /*
1711  * unlink the module with the whole machine is stopped with interrupts off
1712  * - this defends against kallsyms not taking locks
1713  */
1714 static int __unlink_module(void *_mod)
1715 {
1716         struct module *mod = _mod;
1717         list_del(&mod->list);
1718         module_bug_cleanup(mod);
1719         return 0;
1720 }
1721
1722 #ifdef CONFIG_DEBUG_SET_MODULE_RONX
1723 /*
1724  * LKM RO/NX protection: protect module's text/ro-data
1725  * from modification and any data from execution.
1726  */
1727 void set_page_attributes(void *start, void *end, int (*set)(unsigned long start, int num_pages))
1728 {
1729         unsigned long begin_pfn = PFN_DOWN((unsigned long)start);
1730         unsigned long end_pfn = PFN_DOWN((unsigned long)end);
1731
1732         if (end_pfn > begin_pfn)
1733                 set(begin_pfn << PAGE_SHIFT, end_pfn - begin_pfn);
1734 }
1735
1736 static void set_section_ro_nx(void *base,
1737                         unsigned long text_size,
1738                         unsigned long ro_size,
1739                         unsigned long total_size)
1740 {
1741         /* begin and end PFNs of the current subsection */
1742         unsigned long begin_pfn;
1743         unsigned long end_pfn;
1744
1745         /*
1746          * Set RO for module text and RO-data:
1747          * - Always protect first page.
1748          * - Do not protect last partial page.
1749          */
1750         if (ro_size > 0)
1751                 set_page_attributes(base, base + ro_size, set_memory_ro);
1752
1753         /*
1754          * Set NX permissions for module data:
1755          * - Do not protect first partial page.
1756          * - Always protect last page.
1757          */
1758         if (total_size > text_size) {
1759                 begin_pfn = PFN_UP((unsigned long)base + text_size);
1760                 end_pfn = PFN_UP((unsigned long)base + total_size);
1761                 if (end_pfn > begin_pfn)
1762                         set_memory_nx(begin_pfn << PAGE_SHIFT, end_pfn - begin_pfn);
1763         }
1764 }
1765
1766 static void unset_module_core_ro_nx(struct module *mod)
1767 {
1768         set_page_attributes(mod->module_core + mod->core_text_size,
1769                 mod->module_core + mod->core_size,
1770                 set_memory_x);
1771         set_page_attributes(mod->module_core,
1772                 mod->module_core + mod->core_ro_size,
1773                 set_memory_rw);
1774 }
1775
1776 static void unset_module_init_ro_nx(struct module *mod)
1777 {
1778         set_page_attributes(mod->module_init + mod->init_text_size,
1779                 mod->module_init + mod->init_size,
1780                 set_memory_x);
1781         set_page_attributes(mod->module_init,
1782                 mod->module_init + mod->init_ro_size,
1783                 set_memory_rw);
1784 }
1785
1786 /* Iterate through all modules and set each module's text as RW */
1787 void set_all_modules_text_rw(void)
1788 {
1789         struct module *mod;
1790
1791         mutex_lock(&module_mutex);
1792         list_for_each_entry_rcu(mod, &modules, list) {
1793                 if (mod->state == MODULE_STATE_UNFORMED)
1794                         continue;
1795                 if ((mod->module_core) && (mod->core_text_size)) {
1796                         set_page_attributes(mod->module_core,
1797                                                 mod->module_core + mod->core_text_size,
1798                                                 set_memory_rw);
1799                 }
1800                 if ((mod->module_init) && (mod->init_text_size)) {
1801                         set_page_attributes(mod->module_init,
1802                                                 mod->module_init + mod->init_text_size,
1803                                                 set_memory_rw);
1804                 }
1805         }
1806         mutex_unlock(&module_mutex);
1807 }
1808
1809 /* Iterate through all modules and set each module's text as RO */
1810 void set_all_modules_text_ro(void)
1811 {
1812         struct module *mod;
1813
1814         mutex_lock(&module_mutex);
1815         list_for_each_entry_rcu(mod, &modules, list) {
1816                 if (mod->state == MODULE_STATE_UNFORMED)
1817                         continue;
1818                 if ((mod->module_core) && (mod->core_text_size)) {
1819                         set_page_attributes(mod->module_core,
1820                                                 mod->module_core + mod->core_text_size,
1821                                                 set_memory_ro);
1822                 }
1823                 if ((mod->module_init) && (mod->init_text_size)) {
1824                         set_page_attributes(mod->module_init,
1825                                                 mod->module_init + mod->init_text_size,
1826                                                 set_memory_ro);
1827                 }
1828         }
1829         mutex_unlock(&module_mutex);
1830 }
1831 #else
1832 static inline void set_section_ro_nx(void *base, unsigned long text_size, unsigned long ro_size, unsigned long total_size) { }
1833 static void unset_module_core_ro_nx(struct module *mod) { }
1834 static void unset_module_init_ro_nx(struct module *mod) { }
1835 #endif
1836
1837 void __weak module_free(struct module *mod, void *module_region)
1838 {
1839         vfree(module_region);
1840 }
1841
1842 void __weak module_arch_cleanup(struct module *mod)
1843 {
1844 }
1845
1846 /* Free a module, remove from lists, etc. */
1847 static void free_module(struct module *mod)
1848 {
1849         trace_module_free(mod);
1850
1851         mod_sysfs_teardown(mod);
1852
1853         /* We leave it in list to prevent duplicate loads, but make sure
1854          * that noone uses it while it's being deconstructed. */
1855         mod->state = MODULE_STATE_UNFORMED;
1856
1857         /* Remove dynamic debug info */
1858         ddebug_remove_module(mod->name);
1859
1860         /* Arch-specific cleanup. */
1861         module_arch_cleanup(mod);
1862
1863         /* Module unload stuff */
1864         module_unload_free(mod);
1865
1866         /* Free any allocated parameters. */
1867         destroy_params(mod->kp, mod->num_kp);
1868
1869         /* Now we can delete it from the lists */
1870         mutex_lock(&module_mutex);
1871         stop_machine(__unlink_module, mod, NULL);
1872         mutex_unlock(&module_mutex);
1873
1874         /* This may be NULL, but that's OK */
1875         unset_module_init_ro_nx(mod);
1876         module_free(mod, mod->module_init);
1877         kfree(mod->args);
1878         percpu_modfree(mod);
1879
1880         /* Free lock-classes: */
1881         lockdep_free_key_range(mod->module_core, mod->core_size);
1882
1883         /* Finally, free the core (containing the module structure) */
1884         unset_module_core_ro_nx(mod);
1885         module_free(mod, mod->module_core);
1886
1887 #ifdef CONFIG_MPU
1888         update_protections(current->mm);
1889 #endif
1890 }
1891
1892 void *__symbol_get(const char *symbol)
1893 {
1894         struct module *owner;
1895         const struct kernel_symbol *sym;
1896
1897         preempt_disable();
1898         sym = find_symbol(symbol, &owner, NULL, true, true);
1899         if (sym && strong_try_module_get(owner))
1900                 sym = NULL;
1901         preempt_enable();
1902
1903         return sym ? (void *)sym->value : NULL;
1904 }
1905 EXPORT_SYMBOL_GPL(__symbol_get);
1906
1907 /*
1908  * Ensure that an exported symbol [global namespace] does not already exist
1909  * in the kernel or in some other module's exported symbol table.
1910  *
1911  * You must hold the module_mutex.
1912  */
1913 static int verify_export_symbols(struct module *mod)
1914 {
1915         unsigned int i;
1916         struct module *owner;
1917         const struct kernel_symbol *s;
1918         struct {
1919                 const struct kernel_symbol *sym;
1920                 unsigned int num;
1921         } arr[] = {
1922                 { mod->syms, mod->num_syms },
1923                 { mod->gpl_syms, mod->num_gpl_syms },
1924                 { mod->gpl_future_syms, mod->num_gpl_future_syms },
1925 #ifdef CONFIG_UNUSED_SYMBOLS
1926                 { mod->unused_syms, mod->num_unused_syms },
1927                 { mod->unused_gpl_syms, mod->num_unused_gpl_syms },
1928 #endif
1929         };
1930
1931         for (i = 0; i < ARRAY_SIZE(arr); i++) {
1932                 for (s = arr[i].sym; s < arr[i].sym + arr[i].num; s++) {
1933                         if (find_symbol(s->name, &owner, NULL, true, false)) {
1934                                 printk(KERN_ERR
1935                                        "%s: exports duplicate symbol %s"
1936                                        " (owned by %s)\n",
1937                                        mod->name, s->name, module_name(owner));
1938                                 return -ENOEXEC;
1939                         }
1940                 }
1941         }
1942         return 0;
1943 }
1944
1945 /* Change all symbols so that st_value encodes the pointer directly. */
1946 static int simplify_symbols(struct module *mod, const struct load_info *info)
1947 {
1948         Elf_Shdr *symsec = &info->sechdrs[info->index.sym];
1949         Elf_Sym *sym = (void *)symsec->sh_addr;
1950         unsigned long secbase;
1951         unsigned int i;
1952         int ret = 0;
1953         const struct kernel_symbol *ksym;
1954
1955         for (i = 1; i < symsec->sh_size / sizeof(Elf_Sym); i++) {
1956                 const char *name = info->strtab + sym[i].st_name;
1957
1958                 switch (sym[i].st_shndx) {
1959                 case SHN_COMMON:
1960                         /* We compiled with -fno-common.  These are not
1961                            supposed to happen.  */
1962                         pr_debug("Common symbol: %s\n", name);
1963                         printk("%s: please compile with -fno-common\n",
1964                                mod->name);
1965                         ret = -ENOEXEC;
1966                         break;
1967
1968                 case SHN_ABS:
1969                         /* Don't need to do anything */
1970                         pr_debug("Absolute symbol: 0x%08lx\n",
1971                                (long)sym[i].st_value);
1972                         break;
1973
1974                 case SHN_UNDEF:
1975                         ksym = resolve_symbol_wait(mod, info, name);
1976                         /* Ok if resolved.  */
1977                         if (ksym && !IS_ERR(ksym)) {
1978                                 sym[i].st_value = ksym->value;
1979                                 break;
1980                         }
1981
1982                         /* Ok if weak.  */
1983                         if (!ksym && ELF_ST_BIND(sym[i].st_info) == STB_WEAK)
1984                                 break;
1985
1986                         printk(KERN_WARNING "%s: Unknown symbol %s (err %li)\n",
1987                                mod->name, name, PTR_ERR(ksym));
1988                         ret = PTR_ERR(ksym) ?: -ENOENT;
1989                         break;
1990
1991                 default:
1992                         /* Divert to percpu allocation if a percpu var. */
1993                         if (sym[i].st_shndx == info->index.pcpu)
1994                                 secbase = (unsigned long)mod_percpu(mod);
1995                         else
1996                                 secbase = info->sechdrs[sym[i].st_shndx].sh_addr;
1997                         sym[i].st_value += secbase;
1998                         break;
1999                 }
2000         }
2001
2002         return ret;
2003 }
2004
2005 static int apply_relocations(struct module *mod, const struct load_info *info)
2006 {
2007         unsigned int i;
2008         int err = 0;
2009
2010         /* Now do relocations. */
2011         for (i = 1; i < info->hdr->e_shnum; i++) {
2012                 unsigned int infosec = info->sechdrs[i].sh_info;
2013
2014                 /* Not a valid relocation section? */
2015                 if (infosec >= info->hdr->e_shnum)
2016                         continue;
2017
2018                 /* Don't bother with non-allocated sections */
2019                 if (!(info->sechdrs[infosec].sh_flags & SHF_ALLOC))
2020                         continue;
2021
2022                 if (info->sechdrs[i].sh_type == SHT_REL)
2023                         err = apply_relocate(info->sechdrs, info->strtab,
2024                                              info->index.sym, i, mod);
2025                 else if (info->sechdrs[i].sh_type == SHT_RELA)
2026                         err = apply_relocate_add(info->sechdrs, info->strtab,
2027                                                  info->index.sym, i, mod);
2028                 if (err < 0)
2029                         break;
2030         }
2031         return err;
2032 }
2033
2034 /* Additional bytes needed by arch in front of individual sections */
2035 unsigned int __weak arch_mod_section_prepend(struct module *mod,
2036                                              unsigned int section)
2037 {
2038         /* default implementation just returns zero */
2039         return 0;
2040 }
2041
2042 /* Update size with this section: return offset. */
2043 static long get_offset(struct module *mod, unsigned int *size,
2044                        Elf_Shdr *sechdr, unsigned int section)
2045 {
2046         long ret;
2047
2048         *size += arch_mod_section_prepend(mod, section);
2049         ret = ALIGN(*size, sechdr->sh_addralign ?: 1);
2050         *size = ret + sechdr->sh_size;
2051         return ret;
2052 }
2053
2054 /* Lay out the SHF_ALLOC sections in a way not dissimilar to how ld
2055    might -- code, read-only data, read-write data, small data.  Tally
2056    sizes, and place the offsets into sh_entsize fields: high bit means it
2057    belongs in init. */
2058 static void layout_sections(struct module *mod, struct load_info *info)
2059 {
2060         static unsigned long const masks[][2] = {
2061                 /* NOTE: all executable code must be the first section
2062                  * in this array; otherwise modify the text_size
2063                  * finder in the two loops below */
2064                 { SHF_EXECINSTR | SHF_ALLOC, ARCH_SHF_SMALL },
2065                 { SHF_ALLOC, SHF_WRITE | ARCH_SHF_SMALL },
2066                 { SHF_WRITE | SHF_ALLOC, ARCH_SHF_SMALL },
2067                 { ARCH_SHF_SMALL | SHF_ALLOC, 0 }
2068         };
2069         unsigned int m, i;
2070
2071         for (i = 0; i < info->hdr->e_shnum; i++)
2072                 info->sechdrs[i].sh_entsize = ~0UL;
2073
2074         pr_debug("Core section allocation order:\n");
2075         for (m = 0; m < ARRAY_SIZE(masks); ++m) {
2076                 for (i = 0; i < info->hdr->e_shnum; ++i) {
2077                         Elf_Shdr *s = &info->sechdrs[i];
2078                         const char *sname = info->secstrings + s->sh_name;
2079
2080                         if ((s->sh_flags & masks[m][0]) != masks[m][0]
2081                             || (s->sh_flags & masks[m][1])
2082                             || s->sh_entsize != ~0UL
2083                             || strstarts(sname, ".init"))
2084                                 continue;
2085                         s->sh_entsize = get_offset(mod, &mod->core_size, s, i);
2086                         pr_debug("\t%s\n", sname);
2087                 }
2088                 switch (m) {
2089                 case 0: /* executable */
2090                         mod->core_size = debug_align(mod->core_size);
2091                         mod->core_text_size = mod->core_size;
2092                         break;
2093                 case 1: /* RO: text and ro-data */
2094                         mod->core_size = debug_align(mod->core_size);
2095                         mod->core_ro_size = mod->core_size;
2096                         break;
2097                 case 3: /* whole core */
2098                         mod->core_size = debug_align(mod->core_size);
2099                         break;
2100                 }
2101         }
2102
2103         pr_debug("Init section allocation order:\n");
2104         for (m = 0; m < ARRAY_SIZE(masks); ++m) {
2105                 for (i = 0; i < info->hdr->e_shnum; ++i) {
2106                         Elf_Shdr *s = &info->sechdrs[i];
2107                         const char *sname = info->secstrings + s->sh_name;
2108
2109                         if ((s->sh_flags & masks[m][0]) != masks[m][0]
2110                             || (s->sh_flags & masks[m][1])
2111                             || s->sh_entsize != ~0UL
2112                             || !strstarts(sname, ".init"))
2113                                 continue;
2114                         s->sh_entsize = (get_offset(mod, &mod->init_size, s, i)
2115                                          | INIT_OFFSET_MASK);
2116                         pr_debug("\t%s\n", sname);
2117                 }
2118                 switch (m) {
2119                 case 0: /* executable */
2120                         mod->init_size = debug_align(mod->init_size);
2121                         mod->init_text_size = mod->init_size;
2122                         break;
2123                 case 1: /* RO: text and ro-data */
2124                         mod->init_size = debug_align(mod->init_size);
2125                         mod->init_ro_size = mod->init_size;
2126                         break;
2127                 case 3: /* whole init */
2128                         mod->init_size = debug_align(mod->init_size);
2129                         break;
2130                 }
2131         }
2132 }
2133
2134 static void set_license(struct module *mod, const char *license)
2135 {
2136         if (!license)
2137                 license = "unspecified";
2138
2139         if (!license_is_gpl_compatible(license)) {
2140                 if (!test_taint(TAINT_PROPRIETARY_MODULE))
2141                         printk(KERN_WARNING "%s: module license '%s' taints "
2142                                 "kernel.\n", mod->name, license);
2143                 add_taint_module(mod, TAINT_PROPRIETARY_MODULE,
2144                                  LOCKDEP_NOW_UNRELIABLE);
2145         }
2146 }
2147
2148 /* Parse tag=value strings from .modinfo section */
2149 static char *next_string(char *string, unsigned long *secsize)
2150 {
2151         /* Skip non-zero chars */
2152         while (string[0]) {
2153                 string++;
2154                 if ((*secsize)-- <= 1)
2155                         return NULL;
2156         }
2157
2158         /* Skip any zero padding. */
2159         while (!string[0]) {
2160                 string++;
2161                 if ((*secsize)-- <= 1)
2162                         return NULL;
2163         }
2164         return string;
2165 }
2166
2167 static char *get_modinfo(struct load_info *info, const char *tag)
2168 {
2169         char *p;
2170         unsigned int taglen = strlen(tag);
2171         Elf_Shdr *infosec = &info->sechdrs[info->index.info];
2172         unsigned long size = infosec->sh_size;
2173
2174         for (p = (char *)infosec->sh_addr; p; p = next_string(p, &size)) {
2175                 if (strncmp(p, tag, taglen) == 0 && p[taglen] == '=')
2176                         return p + taglen + 1;
2177         }
2178         return NULL;
2179 }
2180
2181 static void setup_modinfo(struct module *mod, struct load_info *info)
2182 {
2183         struct module_attribute *attr;
2184         int i;
2185
2186         for (i = 0; (attr = modinfo_attrs[i]); i++) {
2187                 if (attr->setup)
2188                         attr->setup(mod, get_modinfo(info, attr->attr.name));
2189         }
2190 }
2191
2192 static void free_modinfo(struct module *mod)
2193 {
2194         struct module_attribute *attr;
2195         int i;
2196
2197         for (i = 0; (attr = modinfo_attrs[i]); i++) {
2198                 if (attr->free)
2199                         attr->free(mod);
2200         }
2201 }
2202
2203 #ifdef CONFIG_KALLSYMS
2204
2205 /* lookup symbol in given range of kernel_symbols */
2206 static const struct kernel_symbol *lookup_symbol(const char *name,
2207         const struct kernel_symbol *start,
2208         const struct kernel_symbol *stop)
2209 {
2210         return bsearch(name, start, stop - start,
2211                         sizeof(struct kernel_symbol), cmp_name);
2212 }
2213
2214 static int is_exported(const char *name, unsigned long value,
2215                        const struct module *mod)
2216 {
2217         const struct kernel_symbol *ks;
2218         if (!mod)
2219                 ks = lookup_symbol(name, __start___ksymtab, __stop___ksymtab);
2220         else
2221                 ks = lookup_symbol(name, mod->syms, mod->syms + mod->num_syms);
2222         return ks != NULL && ks->value == value;
2223 }
2224
2225 /* As per nm */
2226 static char elf_type(const Elf_Sym *sym, const struct load_info *info)
2227 {
2228         const Elf_Shdr *sechdrs = info->sechdrs;
2229
2230         if (ELF_ST_BIND(sym->st_info) == STB_WEAK) {
2231                 if (ELF_ST_TYPE(sym->st_info) == STT_OBJECT)
2232                         return 'v';
2233                 else
2234                         return 'w';
2235         }
2236         if (sym->st_shndx == SHN_UNDEF)
2237                 return 'U';
2238         if (sym->st_shndx == SHN_ABS)
2239                 return 'a';
2240         if (sym->st_shndx >= SHN_LORESERVE)
2241                 return '?';
2242         if (sechdrs[sym->st_shndx].sh_flags & SHF_EXECINSTR)
2243                 return 't';
2244         if (sechdrs[sym->st_shndx].sh_flags & SHF_ALLOC
2245             && sechdrs[sym->st_shndx].sh_type != SHT_NOBITS) {
2246                 if (!(sechdrs[sym->st_shndx].sh_flags & SHF_WRITE))
2247                         return 'r';
2248                 else if (sechdrs[sym->st_shndx].sh_flags & ARCH_SHF_SMALL)
2249                         return 'g';
2250                 else
2251                         return 'd';
2252         }
2253         if (sechdrs[sym->st_shndx].sh_type == SHT_NOBITS) {
2254                 if (sechdrs[sym->st_shndx].sh_flags & ARCH_SHF_SMALL)
2255                         return 's';
2256                 else
2257                         return 'b';
2258         }
2259         if (strstarts(info->secstrings + sechdrs[sym->st_shndx].sh_name,
2260                       ".debug")) {
2261                 return 'n';
2262         }
2263         return '?';
2264 }
2265
2266 static bool is_core_symbol(const Elf_Sym *src, const Elf_Shdr *sechdrs,
2267                            unsigned int shnum)
2268 {
2269         const Elf_Shdr *sec;
2270
2271         if (src->st_shndx == SHN_UNDEF
2272             || src->st_shndx >= shnum
2273             || !src->st_name)
2274                 return false;
2275
2276         sec = sechdrs + src->st_shndx;
2277         if (!(sec->sh_flags & SHF_ALLOC)
2278 #ifndef CONFIG_KALLSYMS_ALL
2279             || !(sec->sh_flags & SHF_EXECINSTR)
2280 #endif
2281             || (sec->sh_entsize & INIT_OFFSET_MASK))
2282                 return false;
2283
2284         return true;
2285 }
2286
2287 /*
2288  * We only allocate and copy the strings needed by the parts of symtab
2289  * we keep.  This is simple, but has the effect of making multiple
2290  * copies of duplicates.  We could be more sophisticated, see
2291  * linux-kernel thread starting with
2292  * <73defb5e4bca04a6431392cc341112b1@localhost>.
2293  */
2294 static void layout_symtab(struct module *mod, struct load_info *info)
2295 {
2296         Elf_Shdr *symsect = info->sechdrs + info->index.sym;
2297         Elf_Shdr *strsect = info->sechdrs + info->index.str;
2298         const Elf_Sym *src;
2299         unsigned int i, nsrc, ndst, strtab_size = 0;
2300
2301         /* Put symbol section at end of init part of module. */
2302         symsect->sh_flags |= SHF_ALLOC;
2303         symsect->sh_entsize = get_offset(mod, &mod->init_size, symsect,
2304                                          info->index.sym) | INIT_OFFSET_MASK;
2305         pr_debug("\t%s\n", info->secstrings + symsect->sh_name);
2306
2307         src = (void *)info->hdr + symsect->sh_offset;
2308         nsrc = symsect->sh_size / sizeof(*src);
2309
2310         /* Compute total space required for the core symbols' strtab. */
2311         for (ndst = i = 0; i < nsrc; i++) {
2312                 if (i == 0 ||
2313                     is_core_symbol(src+i, info->sechdrs, info->hdr->e_shnum)) {
2314                         strtab_size += strlen(&info->strtab[src[i].st_name])+1;
2315                         ndst++;
2316                 }
2317         }
2318
2319         /* Append room for core symbols at end of core part. */
2320         info->symoffs = ALIGN(mod->core_size, symsect->sh_addralign ?: 1);
2321         info->stroffs = mod->core_size = info->symoffs + ndst * sizeof(Elf_Sym);
2322         mod->core_size += strtab_size;
2323
2324         /* Put string table section at end of init part of module. */
2325         strsect->sh_flags |= SHF_ALLOC;
2326         strsect->sh_entsize = get_offset(mod, &mod->init_size, strsect,
2327                                          info->index.str) | INIT_OFFSET_MASK;
2328         pr_debug("\t%s\n", info->secstrings + strsect->sh_name);
2329 }
2330
2331 static void add_kallsyms(struct module *mod, const struct load_info *info)
2332 {
2333         unsigned int i, ndst;
2334         const Elf_Sym *src;
2335         Elf_Sym *dst;
2336         char *s;
2337         Elf_Shdr *symsec = &info->sechdrs[info->index.sym];
2338
2339         mod->symtab = (void *)symsec->sh_addr;
2340         mod->num_symtab = symsec->sh_size / sizeof(Elf_Sym);
2341         /* Make sure we get permanent strtab: don't use info->strtab. */
2342         mod->strtab = (void *)info->sechdrs[info->index.str].sh_addr;
2343
2344         /* Set types up while we still have access to sections. */
2345         for (i = 0; i < mod->num_symtab; i++)
2346                 mod->symtab[i].st_info = elf_type(&mod->symtab[i], info);
2347
2348         mod->core_symtab = dst = mod->module_core + info->symoffs;
2349         mod->core_strtab = s = mod->module_core + info->stroffs;
2350         src = mod->symtab;
2351         for (ndst = i = 0; i < mod->num_symtab; i++) {
2352                 if (i == 0 ||
2353                     is_core_symbol(src+i, info->sechdrs, info->hdr->e_shnum)) {
2354                         dst[ndst] = src[i];
2355                         dst[ndst++].st_name = s - mod->core_strtab;
2356                         s += strlcpy(s, &mod->strtab[src[i].st_name],
2357                                      KSYM_NAME_LEN) + 1;
2358                 }
2359         }
2360         mod->core_num_syms = ndst;
2361 }
2362 #else
2363 static inline void layout_symtab(struct module *mod, struct load_info *info)
2364 {
2365 }
2366
2367 static void add_kallsyms(struct module *mod, const struct load_info *info)
2368 {
2369 }
2370 #endif /* CONFIG_KALLSYMS */
2371
2372 static void dynamic_debug_setup(struct _ddebug *debug, unsigned int num)
2373 {
2374         if (!debug)
2375                 return;
2376 #ifdef CONFIG_DYNAMIC_DEBUG
2377         if (ddebug_add_module(debug, num, debug->modname))
2378                 printk(KERN_ERR "dynamic debug error adding module: %s\n",
2379                                         debug->modname);
2380 #endif
2381 }
2382
2383 static void dynamic_debug_remove(struct _ddebug *debug)
2384 {
2385         if (debug)
2386                 ddebug_remove_module(debug->modname);
2387 }
2388
2389 void * __weak module_alloc(unsigned long size)
2390 {
2391         return vmalloc_exec(size);
2392 }
2393
2394 static void *module_alloc_update_bounds(unsigned long size)
2395 {
2396         void *ret = module_alloc(size);
2397
2398         if (ret) {
2399                 mutex_lock(&module_mutex);
2400                 /* Update module bounds. */
2401                 if ((unsigned long)ret < module_addr_min)
2402                         module_addr_min = (unsigned long)ret;
2403                 if ((unsigned long)ret + size > module_addr_max)
2404                         module_addr_max = (unsigned long)ret + size;
2405                 mutex_unlock(&module_mutex);
2406         }
2407         return ret;
2408 }
2409
2410 #ifdef CONFIG_DEBUG_KMEMLEAK
2411 static void kmemleak_load_module(const struct module *mod,
2412                                  const struct load_info *info)
2413 {
2414         unsigned int i;
2415
2416         /* only scan the sections containing data */
2417         kmemleak_scan_area(mod, sizeof(struct module), GFP_KERNEL);
2418
2419         for (i = 1; i < info->hdr->e_shnum; i++) {
2420                 /* Scan all writable sections that's not executable */
2421                 if (!(info->sechdrs[i].sh_flags & SHF_ALLOC) ||
2422                     !(info->sechdrs[i].sh_flags & SHF_WRITE) ||
2423                     (info->sechdrs[i].sh_flags & SHF_EXECINSTR))
2424                         continue;
2425
2426                 kmemleak_scan_area((void *)info->sechdrs[i].sh_addr,
2427                                    info->sechdrs[i].sh_size, GFP_KERNEL);
2428         }
2429 }
2430 #else
2431 static inline void kmemleak_load_module(const struct module *mod,
2432                                         const struct load_info *info)
2433 {
2434 }
2435 #endif
2436
2437 #ifdef CONFIG_MODULE_SIG
2438 static int module_sig_check(struct load_info *info)
2439 {
2440         int err = -ENOKEY;
2441         const unsigned long markerlen = sizeof(MODULE_SIG_STRING) - 1;
2442         const void *mod = info->hdr;
2443
2444         if (info->len > markerlen &&
2445             memcmp(mod + info->len - markerlen, MODULE_SIG_STRING, markerlen) == 0) {
2446                 /* We truncate the module to discard the signature */
2447                 info->len -= markerlen;
2448                 err = mod_verify_sig(mod, &info->len);
2449         }
2450
2451         if (!err) {
2452                 info->sig_ok = true;
2453                 return 0;
2454         }
2455
2456         /* Not having a signature is only an error if we're strict. */
2457         if (err < 0 && fips_enabled)
2458                 panic("Module verification failed with error %d in FIPS mode\n",
2459                       err);
2460         if (err == -ENOKEY && !sig_enforce)
2461                 err = 0;
2462
2463         return err;
2464 }
2465 #else /* !CONFIG_MODULE_SIG */
2466 static int module_sig_check(struct load_info *info)
2467 {
2468         return 0;
2469 }
2470 #endif /* !CONFIG_MODULE_SIG */
2471
2472 /* Sanity checks against invalid binaries, wrong arch, weird elf version. */
2473 static int elf_header_check(struct load_info *info)
2474 {
2475         if (info->len < sizeof(*(info->hdr)))
2476                 return -ENOEXEC;
2477
2478         if (memcmp(info->hdr->e_ident, ELFMAG, SELFMAG) != 0
2479             || info->hdr->e_type != ET_REL
2480             || !elf_check_arch(info->hdr)
2481             || info->hdr->e_shentsize != sizeof(Elf_Shdr))
2482                 return -ENOEXEC;
2483
2484         if (info->hdr->e_shoff >= info->len
2485             || (info->hdr->e_shnum * sizeof(Elf_Shdr) >
2486                 info->len - info->hdr->e_shoff))
2487                 return -ENOEXEC;
2488
2489         return 0;
2490 }
2491
2492 /* Sets info->hdr and info->len. */
2493 static int copy_module_from_user(const void __user *umod, unsigned long len,
2494                                   struct load_info *info)
2495 {
2496         int err;
2497
2498         info->len = len;
2499         if (info->len < sizeof(*(info->hdr)))
2500                 return -ENOEXEC;
2501
2502         err = security_kernel_module_from_file(NULL);
2503         if (err)
2504                 return err;
2505
2506         /* Suck in entire file: we'll want most of it. */
2507         info->hdr = vmalloc(info->len);
2508         if (!info->hdr)
2509                 return -ENOMEM;
2510
2511         if (copy_from_user(info->hdr, umod, info->len) != 0) {
2512                 vfree(info->hdr);
2513                 return -EFAULT;
2514         }
2515
2516         return 0;
2517 }
2518
2519 /* Sets info->hdr and info->len. */
2520 static int copy_module_from_fd(int fd, struct load_info *info)
2521 {
2522         struct fd f = fdget(fd);
2523         int err;
2524         struct kstat stat;
2525         loff_t pos;
2526         ssize_t bytes = 0;
2527
2528         if (!f.file)
2529                 return -ENOEXEC;
2530
2531         err = security_kernel_module_from_file(f.file);
2532         if (err)
2533                 goto out;
2534
2535         err = vfs_getattr(&f.file->f_path, &stat);
2536         if (err)
2537                 goto out;
2538
2539         if (stat.size > INT_MAX) {
2540                 err = -EFBIG;
2541                 goto out;
2542         }
2543
2544         /* Don't hand 0 to vmalloc, it whines. */
2545         if (stat.size == 0) {
2546                 err = -EINVAL;
2547                 goto out;
2548         }
2549
2550         info->hdr = vmalloc(stat.size);
2551         if (!info->hdr) {
2552                 err = -ENOMEM;
2553                 goto out;
2554         }
2555
2556         pos = 0;
2557         while (pos < stat.size) {
2558                 bytes = kernel_read(f.file, pos, (char *)(info->hdr) + pos,
2559                                     stat.size - pos);
2560                 if (bytes < 0) {
2561                         vfree(info->hdr);
2562                         err = bytes;
2563                         goto out;
2564                 }
2565                 if (bytes == 0)
2566                         break;
2567                 pos += bytes;
2568         }
2569         info->len = pos;
2570
2571 out:
2572         fdput(f);
2573         return err;
2574 }
2575
2576 static void free_copy(struct load_info *info)
2577 {
2578         vfree(info->hdr);
2579 }
2580
2581 static int rewrite_section_headers(struct load_info *info, int flags)
2582 {
2583         unsigned int i;
2584
2585         /* This should always be true, but let's be sure. */
2586         info->sechdrs[0].sh_addr = 0;
2587
2588         for (i = 1; i < info->hdr->e_shnum; i++) {
2589                 Elf_Shdr *shdr = &info->sechdrs[i];
2590                 if (shdr->sh_type != SHT_NOBITS
2591                     && info->len < shdr->sh_offset + shdr->sh_size) {
2592                         printk(KERN_ERR "Module len %lu truncated\n",
2593                                info->len);
2594                         return -ENOEXEC;
2595                 }
2596
2597                 /* Mark all sections sh_addr with their address in the
2598                    temporary image. */
2599                 shdr->sh_addr = (size_t)info->hdr + shdr->sh_offset;
2600
2601 #ifndef CONFIG_MODULE_UNLOAD
2602                 /* Don't load .exit sections */
2603                 if (strstarts(info->secstrings+shdr->sh_name, ".exit"))
2604                         shdr->sh_flags &= ~(unsigned long)SHF_ALLOC;
2605 #endif
2606         }
2607
2608         /* Track but don't keep modinfo and version sections. */
2609         if (flags & MODULE_INIT_IGNORE_MODVERSIONS)
2610                 info->index.vers = 0; /* Pretend no __versions section! */
2611         else
2612                 info->index.vers = find_sec(info, "__versions");
2613         info->index.info = find_sec(info, ".modinfo");
2614         info->sechdrs[info->index.info].sh_flags &= ~(unsigned long)SHF_ALLOC;
2615         info->sechdrs[info->index.vers].sh_flags &= ~(unsigned long)SHF_ALLOC;
2616         return 0;
2617 }
2618
2619 /*
2620  * Set up our basic convenience variables (pointers to section headers,
2621  * search for module section index etc), and do some basic section
2622  * verification.
2623  *
2624  * Return the temporary module pointer (we'll replace it with the final
2625  * one when we move the module sections around).
2626  */
2627 static struct module *setup_load_info(struct load_info *info, int flags)
2628 {
2629         unsigned int i;
2630         int err;
2631         struct module *mod;
2632
2633         /* Set up the convenience variables */
2634         info->sechdrs = (void *)info->hdr + info->hdr->e_shoff;
2635         info->secstrings = (void *)info->hdr
2636                 + info->sechdrs[info->hdr->e_shstrndx].sh_offset;
2637
2638         err = rewrite_section_headers(info, flags);
2639         if (err)
2640                 return ERR_PTR(err);
2641
2642         /* Find internal symbols and strings. */
2643         for (i = 1; i < info->hdr->e_shnum; i++) {
2644                 if (info->sechdrs[i].sh_type == SHT_SYMTAB) {
2645                         info->index.sym = i;
2646                         info->index.str = info->sechdrs[i].sh_link;
2647                         info->strtab = (char *)info->hdr
2648                                 + info->sechdrs[info->index.str].sh_offset;
2649                         break;
2650                 }
2651         }
2652
2653         info->index.mod = find_sec(info, ".gnu.linkonce.this_module");
2654         if (!info->index.mod) {
2655                 printk(KERN_WARNING "No module found in object\n");
2656                 return ERR_PTR(-ENOEXEC);
2657         }
2658         /* This is temporary: point mod into copy of data. */
2659         mod = (void *)info->sechdrs[info->index.mod].sh_addr;
2660
2661         if (info->index.sym == 0) {
2662                 printk(KERN_WARNING "%s: module has no symbols (stripped?)\n",
2663                        mod->name);
2664                 return ERR_PTR(-ENOEXEC);
2665         }
2666
2667         info->index.pcpu = find_pcpusec(info);
2668
2669         /* Check module struct version now, before we try to use module. */
2670         if (!check_modstruct_version(info->sechdrs, info->index.vers, mod))
2671                 return ERR_PTR(-ENOEXEC);
2672
2673         return mod;
2674 }
2675
2676 static int check_modinfo(struct module *mod, struct load_info *info, int flags)
2677 {
2678         const char *modmagic = get_modinfo(info, "vermagic");
2679         int err;
2680
2681         if (flags & MODULE_INIT_IGNORE_VERMAGIC)
2682                 modmagic = NULL;
2683
2684         /* This is allowed: modprobe --force will invalidate it. */
2685         if (!modmagic) {
2686                 err = try_to_force_load(mod, "bad vermagic");
2687                 if (err)
2688                         return err;
2689         } else if (!same_magic(modmagic, vermagic, info->index.vers)) {
2690                 printk(KERN_ERR "%s: version magic '%s' should be '%s'\n",
2691                        mod->name, modmagic, vermagic);
2692                 return -ENOEXEC;
2693         }
2694
2695         if (!get_modinfo(info, "intree"))
2696                 add_taint_module(mod, TAINT_OOT_MODULE, LOCKDEP_STILL_OK);
2697
2698         if (get_modinfo(info, "staging")) {
2699                 add_taint_module(mod, TAINT_CRAP, LOCKDEP_STILL_OK);
2700                 printk(KERN_WARNING "%s: module is from the staging directory,"
2701                        " the quality is unknown, you have been warned.\n",
2702                        mod->name);
2703         }
2704
2705         /* Set up license info based on the info section */
2706         set_license(mod, get_modinfo(info, "license"));
2707
2708         return 0;
2709 }
2710
2711 static int find_module_sections(struct module *mod, struct load_info *info)
2712 {
2713         mod->kp = section_objs(info, "__param",
2714                                sizeof(*mod->kp), &mod->num_kp);
2715         mod->syms = section_objs(info, "__ksymtab",
2716                                  sizeof(*mod->syms), &mod->num_syms);
2717         mod->crcs = section_addr(info, "__kcrctab");
2718         mod->gpl_syms = section_objs(info, "__ksymtab_gpl",
2719                                      sizeof(*mod->gpl_syms),
2720                                      &mod->num_gpl_syms);
2721         mod->gpl_crcs = section_addr(info, "__kcrctab_gpl");
2722         mod->gpl_future_syms = section_objs(info,
2723                                             "__ksymtab_gpl_future",
2724                                             sizeof(*mod->gpl_future_syms),
2725                                             &mod->num_gpl_future_syms);
2726         mod->gpl_future_crcs = section_addr(info, "__kcrctab_gpl_future");
2727
2728 #ifdef CONFIG_UNUSED_SYMBOLS
2729         mod->unused_syms = section_objs(info, "__ksymtab_unused",
2730                                         sizeof(*mod->unused_syms),
2731                                         &mod->num_unused_syms);
2732         mod->unused_crcs = section_addr(info, "__kcrctab_unused");
2733         mod->unused_gpl_syms = section_objs(info, "__ksymtab_unused_gpl",
2734                                             sizeof(*mod->unused_gpl_syms),
2735                                             &mod->num_unused_gpl_syms);
2736         mod->unused_gpl_crcs = section_addr(info, "__kcrctab_unused_gpl");
2737 #endif
2738 #ifdef CONFIG_CONSTRUCTORS
2739         mod->ctors = section_objs(info, ".ctors",
2740                                   sizeof(*mod->ctors), &mod->num_ctors);
2741         if (!mod->ctors)
2742                 mod->ctors = section_objs(info, ".init_array",
2743                                 sizeof(*mod->ctors), &mod->num_ctors);
2744         else if (find_sec(info, ".init_array")) {
2745                 /*
2746                  * This shouldn't happen with same compiler and binutils
2747                  * building all parts of the module.
2748                  */
2749                 printk(KERN_WARNING "%s: has both .ctors and .init_array.\n",
2750                        mod->name);
2751                 return -EINVAL;
2752         }
2753 #endif
2754
2755 #ifdef CONFIG_TRACEPOINTS
2756         mod->tracepoints_ptrs = section_objs(info, "__tracepoints_ptrs",
2757                                              sizeof(*mod->tracepoints_ptrs),
2758                                              &mod->num_tracepoints);
2759 #endif
2760 #ifdef HAVE_JUMP_LABEL
2761         mod->jump_entries = section_objs(info, "__jump_table",
2762                                         sizeof(*mod->jump_entries),
2763                                         &mod->num_jump_entries);
2764 #endif
2765 #ifdef CONFIG_EVENT_TRACING
2766         mod->trace_events = section_objs(info, "_ftrace_events",
2767                                          sizeof(*mod->trace_events),
2768                                          &mod->num_trace_events);
2769 #endif
2770 #ifdef CONFIG_TRACING
2771         mod->trace_bprintk_fmt_start = section_objs(info, "__trace_printk_fmt",
2772                                          sizeof(*mod->trace_bprintk_fmt_start),
2773                                          &mod->num_trace_bprintk_fmt);
2774 #endif
2775 #ifdef CONFIG_FTRACE_MCOUNT_RECORD
2776         /* sechdrs[0].sh_size is always zero */
2777         mod->ftrace_callsites = section_objs(info, "__mcount_loc",
2778                                              sizeof(*mod->ftrace_callsites),
2779                                              &mod->num_ftrace_callsites);
2780 #endif
2781
2782         mod->extable = section_objs(info, "__ex_table",
2783                                     sizeof(*mod->extable), &mod->num_exentries);
2784
2785         if (section_addr(info, "__obsparm"))
2786                 printk(KERN_WARNING "%s: Ignoring obsolete parameters\n",
2787                        mod->name);
2788
2789         info->debug = section_objs(info, "__verbose",
2790                                    sizeof(*info->debug), &info->num_debug);
2791
2792         return 0;
2793 }
2794
2795 static int move_module(struct module *mod, struct load_info *info)
2796 {
2797         int i;
2798         void *ptr;
2799
2800         /* Do the allocs. */
2801         ptr = module_alloc_update_bounds(mod->core_size);
2802         /*
2803          * The pointer to this block is stored in the module structure
2804          * which is inside the block. Just mark it as not being a
2805          * leak.
2806          */
2807         kmemleak_not_leak(ptr);
2808         if (!ptr)
2809                 return -ENOMEM;
2810
2811         memset(ptr, 0, mod->core_size);
2812         mod->module_core = ptr;
2813
2814         if (mod->init_size) {
2815                 ptr = module_alloc_update_bounds(mod->init_size);
2816                 /*
2817                  * The pointer to this block is stored in the module structure
2818                  * which is inside the block. This block doesn't need to be
2819                  * scanned as it contains data and code that will be freed
2820                  * after the module is initialized.
2821                  */
2822                 kmemleak_ignore(ptr);
2823                 if (!ptr) {
2824                         module_free(mod, mod->module_core);
2825                         return -ENOMEM;
2826                 }
2827                 memset(ptr, 0, mod->init_size);
2828                 mod->module_init = ptr;
2829         } else
2830                 mod->module_init = NULL;
2831
2832         /* Transfer each section which specifies SHF_ALLOC */
2833         pr_debug("final section addresses:\n");
2834         for (i = 0; i < info->hdr->e_shnum; i++) {
2835                 void *dest;
2836                 Elf_Shdr *shdr = &info->sechdrs[i];
2837
2838                 if (!(shdr->sh_flags & SHF_ALLOC))
2839                         continue;
2840
2841                 if (shdr->sh_entsize & INIT_OFFSET_MASK)
2842                         dest = mod->module_init
2843                                 + (shdr->sh_entsize & ~INIT_OFFSET_MASK);
2844                 else
2845                         dest = mod->module_core + shdr->sh_entsize;
2846
2847                 if (shdr->sh_type != SHT_NOBITS)
2848                         memcpy(dest, (void *)shdr->sh_addr, shdr->sh_size);
2849                 /* Update sh_addr to point to copy in image. */
2850                 shdr->sh_addr = (unsigned long)dest;
2851                 pr_debug("\t0x%lx %s\n",
2852                          (long)shdr->sh_addr, info->secstrings + shdr->sh_name);
2853         }
2854
2855         return 0;
2856 }
2857
2858 static int check_module_license_and_versions(struct module *mod)
2859 {
2860         /*
2861          * ndiswrapper is under GPL by itself, but loads proprietary modules.
2862          * Don't use add_taint_module(), as it would prevent ndiswrapper from
2863          * using GPL-only symbols it needs.
2864          */
2865         if (strcmp(mod->name, "ndiswrapper") == 0)
2866                 add_taint(TAINT_PROPRIETARY_MODULE, LOCKDEP_NOW_UNRELIABLE);
2867
2868         /* driverloader was caught wrongly pretending to be under GPL */
2869         if (strcmp(mod->name, "driverloader") == 0)
2870                 add_taint_module(mod, TAINT_PROPRIETARY_MODULE,
2871                                  LOCKDEP_NOW_UNRELIABLE);
2872
2873         /* lve claims to be GPL but upstream won't provide source */
2874         if (strcmp(mod->name, "lve") == 0)
2875                 add_taint_module(mod, TAINT_PROPRIETARY_MODULE,
2876                                  LOCKDEP_NOW_UNRELIABLE);
2877
2878 #ifdef CONFIG_MODVERSIONS
2879         if ((mod->num_syms && !mod->crcs)
2880             || (mod->num_gpl_syms && !mod->gpl_crcs)
2881             || (mod->num_gpl_future_syms && !mod->gpl_future_crcs)
2882 #ifdef CONFIG_UNUSED_SYMBOLS
2883             || (mod->num_unused_syms && !mod->unused_crcs)
2884             || (mod->num_unused_gpl_syms && !mod->unused_gpl_crcs)
2885 #endif
2886                 ) {
2887                 return try_to_force_load(mod,
2888                                          "no versions for exported symbols");
2889         }
2890 #endif
2891         return 0;
2892 }
2893
2894 static void flush_module_icache(const struct module *mod)
2895 {
2896         mm_segment_t old_fs;
2897
2898         /* flush the icache in correct context */
2899         old_fs = get_fs();
2900         set_fs(KERNEL_DS);
2901
2902         /*
2903          * Flush the instruction cache, since we've played with text.
2904          * Do it before processing of module parameters, so the module
2905          * can provide parameter accessor functions of its own.
2906          */
2907         if (mod->module_init)
2908                 flush_icache_range((unsigned long)mod->module_init,
2909                                    (unsigned long)mod->module_init
2910                                    + mod->init_size);
2911         flush_icache_range((unsigned long)mod->module_core,
2912                            (unsigned long)mod->module_core + mod->core_size);
2913
2914         set_fs(old_fs);
2915 }
2916
2917 int __weak module_frob_arch_sections(Elf_Ehdr *hdr,
2918                                      Elf_Shdr *sechdrs,
2919                                      char *secstrings,
2920                                      struct module *mod)
2921 {
2922         return 0;
2923 }
2924
2925 static struct module *layout_and_allocate(struct load_info *info, int flags)
2926 {
2927         /* Module within temporary copy. */
2928         struct module *mod;
2929         int err;
2930
2931         mod = setup_load_info(info, flags);
2932         if (IS_ERR(mod))
2933                 return mod;
2934
2935         err = check_modinfo(mod, info, flags);
2936         if (err)
2937                 return ERR_PTR(err);
2938
2939         /* Allow arches to frob section contents and sizes.  */
2940         err = module_frob_arch_sections(info->hdr, info->sechdrs,
2941                                         info->secstrings, mod);
2942         if (err < 0)
2943                 return ERR_PTR(err);
2944
2945         /* We will do a special allocation for per-cpu sections later. */
2946         info->sechdrs[info->index.pcpu].sh_flags &= ~(unsigned long)SHF_ALLOC;
2947
2948         /* Determine total sizes, and put offsets in sh_entsize.  For now
2949            this is done generically; there doesn't appear to be any
2950            special cases for the architectures. */
2951         layout_sections(mod, info);
2952         layout_symtab(mod, info);
2953
2954         /* Allocate and move to the final place */
2955         err = move_module(mod, info);
2956         if (err)
2957                 return ERR_PTR(err);
2958
2959         /* Module has been copied to its final place now: return it. */
2960         mod = (void *)info->sechdrs[info->index.mod].sh_addr;
2961         kmemleak_load_module(mod, info);
2962         return mod;
2963 }
2964
2965 /* mod is no longer valid after this! */
2966 static void module_deallocate(struct module *mod, struct load_info *info)
2967 {
2968         percpu_modfree(mod);
2969         module_free(mod, mod->module_init);
2970         module_free(mod, mod->module_core);
2971 }
2972
2973 int __weak module_finalize(const Elf_Ehdr *hdr,
2974                            const Elf_Shdr *sechdrs,
2975                            struct module *me)
2976 {
2977         return 0;
2978 }
2979
2980 static int post_relocation(struct module *mod, const struct load_info *info)
2981 {
2982         /* Sort exception table now relocations are done. */
2983         sort_extable(mod->extable, mod->extable + mod->num_exentries);
2984
2985         /* Copy relocated percpu area over. */
2986         percpu_modcopy(mod, (void *)info->sechdrs[info->index.pcpu].sh_addr,
2987                        info->sechdrs[info->index.pcpu].sh_size);
2988
2989         /* Setup kallsyms-specific fields. */
2990         add_kallsyms(mod, info);
2991
2992         /* Arch-specific module finalizing. */
2993         return module_finalize(info->hdr, info->sechdrs, mod);
2994 }
2995
2996 /* Is this module of this name done loading?  No locks held. */
2997 static bool finished_loading(const char *name)
2998 {
2999         struct module *mod;
3000         bool ret;
3001
3002         mutex_lock(&module_mutex);
3003         mod = find_module_all(name, strlen(name), true);
3004         ret = !mod || mod->state == MODULE_STATE_LIVE
3005                 || mod->state == MODULE_STATE_GOING;
3006         mutex_unlock(&module_mutex);
3007
3008         return ret;
3009 }
3010
3011 /* Call module constructors. */
3012 static void do_mod_ctors(struct module *mod)
3013 {
3014 #ifdef CONFIG_CONSTRUCTORS
3015         unsigned long i;
3016
3017         for (i = 0; i < mod->num_ctors; i++)
3018                 mod->ctors[i]();
3019 #endif
3020 }
3021
3022 /* This is where the real work happens */
3023 static int do_init_module(struct module *mod)
3024 {
3025         int ret = 0;
3026
3027         /*
3028          * We want to find out whether @mod uses async during init.  Clear
3029          * PF_USED_ASYNC.  async_schedule*() will set it.
3030          */
3031         current->flags &= ~PF_USED_ASYNC;
3032
3033         blocking_notifier_call_chain(&module_notify_list,
3034                         MODULE_STATE_COMING, mod);
3035
3036         /* Set RO and NX regions for core */
3037         set_section_ro_nx(mod->module_core,
3038                                 mod->core_text_size,
3039                                 mod->core_ro_size,
3040                                 mod->core_size);
3041
3042         /* Set RO and NX regions for init */
3043         set_section_ro_nx(mod->module_init,
3044                                 mod->init_text_size,
3045                                 mod->init_ro_size,
3046                                 mod->init_size);
3047
3048         do_mod_ctors(mod);
3049         /* Start the module */
3050         if (mod->init != NULL)
3051                 ret = do_one_initcall(mod->init);
3052         if (ret < 0) {
3053                 /* Init routine failed: abort.  Try to protect us from
3054                    buggy refcounters. */
3055                 mod->state = MODULE_STATE_GOING;
3056                 synchronize_sched();
3057                 module_put(mod);
3058                 blocking_notifier_call_chain(&module_notify_list,
3059                                              MODULE_STATE_GOING, mod);
3060                 free_module(mod);
3061                 wake_up_all(&module_wq);
3062                 return ret;
3063         }
3064         if (ret > 0) {
3065                 printk(KERN_WARNING
3066 "%s: '%s'->init suspiciously returned %d, it should follow 0/-E convention\n"
3067 "%s: loading module anyway...\n",
3068                        __func__, mod->name, ret,
3069                        __func__);
3070                 dump_stack();
3071         }
3072
3073         /* Now it's a first class citizen! */
3074         mod->state = MODULE_STATE_LIVE;
3075         blocking_notifier_call_chain(&module_notify_list,
3076                                      MODULE_STATE_LIVE, mod);
3077
3078         /*
3079          * We need to finish all async code before the module init sequence
3080          * is done.  This has potential to deadlock.  For example, a newly
3081          * detected block device can trigger request_module() of the
3082          * default iosched from async probing task.  Once userland helper
3083          * reaches here, async_synchronize_full() will wait on the async
3084          * task waiting on request_module() and deadlock.
3085          *
3086          * This deadlock is avoided by perfomring async_synchronize_full()
3087          * iff module init queued any async jobs.  This isn't a full
3088          * solution as it will deadlock the same if module loading from
3089          * async jobs nests more than once; however, due to the various
3090          * constraints, this hack seems to be the best option for now.
3091          * Please refer to the following thread for details.
3092          *
3093          * http://thread.gmane.org/gmane.linux.kernel/1420814
3094          */
3095         if (current->flags & PF_USED_ASYNC)
3096                 async_synchronize_full();
3097
3098         mutex_lock(&module_mutex);
3099         /* Drop initial reference. */
3100         module_put(mod);
3101         trim_init_extable(mod);
3102 #ifdef CONFIG_KALLSYMS
3103         mod->num_symtab = mod->core_num_syms;
3104         mod->symtab = mod->core_symtab;
3105         mod->strtab = mod->core_strtab;
3106 #endif
3107         unset_module_init_ro_nx(mod);
3108         module_free(mod, mod->module_init);
3109         mod->module_init = NULL;
3110         mod->init_size = 0;
3111         mod->init_ro_size = 0;
3112         mod->init_text_size = 0;
3113         mutex_unlock(&module_mutex);
3114         wake_up_all(&module_wq);
3115
3116         return 0;
3117 }
3118
3119 static int may_init_module(void)
3120 {
3121         if (!capable(CAP_SYS_MODULE) || modules_disabled)
3122                 return -EPERM;
3123
3124         return 0;
3125 }
3126
3127 /*
3128  * We try to place it in the list now to make sure it's unique before
3129  * we dedicate too many resources.  In particular, temporary percpu
3130  * memory exhaustion.
3131  */
3132 static int add_unformed_module(struct module *mod)
3133 {
3134         int err;
3135         struct module *old;
3136
3137         mod->state = MODULE_STATE_UNFORMED;
3138
3139 again:
3140         mutex_lock(&module_mutex);
3141         old = find_module_all(mod->name, strlen(mod->name), true);
3142         if (old != NULL) {
3143                 if (old->state == MODULE_STATE_COMING
3144                     || old->state == MODULE_STATE_UNFORMED) {
3145                         /* Wait in case it fails to load. */
3146                         mutex_unlock(&module_mutex);
3147                         err = wait_event_interruptible(module_wq,
3148                                                finished_loading(mod->name));
3149                         if (err)
3150                                 goto out_unlocked;
3151                         goto again;
3152                 }
3153                 err = -EEXIST;
3154                 goto out;
3155         }
3156         list_add_rcu(&mod->list, &modules);
3157         err = 0;
3158
3159 out:
3160         mutex_unlock(&module_mutex);
3161 out_unlocked:
3162         return err;
3163 }
3164
3165 static int complete_formation(struct module *mod, struct load_info *info)
3166 {
3167         int err;
3168
3169         mutex_lock(&module_mutex);
3170
3171         /* Find duplicate symbols (must be called under lock). */
3172         err = verify_export_symbols(mod);
3173         if (err < 0)
3174                 goto out;
3175
3176         /* This relies on module_mutex for list integrity. */
3177         module_bug_finalize(info->hdr, info->sechdrs, mod);
3178
3179         /* Mark state as coming so strong_try_module_get() ignores us,
3180          * but kallsyms etc. can see us. */
3181         mod->state = MODULE_STATE_COMING;
3182
3183 out:
3184         mutex_unlock(&module_mutex);
3185         return err;
3186 }
3187
3188 static int unknown_module_param_cb(char *param, char *val, const char *modname)
3189 {
3190         /* Check for magic 'dyndbg' arg */ 
3191         int ret = ddebug_dyndbg_module_param_cb(param, val, modname);
3192         if (ret != 0) {
3193                 printk(KERN_WARNING "%s: unknown parameter '%s' ignored\n",
3194                        modname, param);
3195         }
3196         return 0;
3197 }
3198
3199 /* Allocate and load the module: note that size of section 0 is always
3200    zero, and we rely on this for optional sections. */
3201 static int load_module(struct load_info *info, const char __user *uargs,
3202                        int flags)
3203 {
3204         struct module *mod;
3205         long err;
3206
3207         err = module_sig_check(info);
3208         if (err)
3209                 goto free_copy;
3210
3211         err = elf_header_check(info);
3212         if (err)
3213                 goto free_copy;
3214
3215         /* Figure out module layout, and allocate all the memory. */
3216         mod = layout_and_allocate(info, flags);
3217         if (IS_ERR(mod)) {
3218                 err = PTR_ERR(mod);
3219                 goto free_copy;
3220         }
3221
3222         /* Reserve our place in the list. */
3223         err = add_unformed_module(mod);
3224         if (err)
3225                 goto free_module;
3226
3227 #ifdef CONFIG_MODULE_SIG
3228         mod->sig_ok = info->sig_ok;
3229         if (!mod->sig_ok) {
3230                 printk_once(KERN_NOTICE
3231                             "%s: module verification failed: signature and/or"
3232                             " required key missing - tainting kernel\n",
3233                             mod->name);
3234                 add_taint_module(mod, TAINT_FORCED_MODULE, LOCKDEP_STILL_OK);
3235         }
3236 #endif
3237
3238         /* To avoid stressing percpu allocator, do this once we're unique. */
3239         err = percpu_modalloc(mod, info);
3240         if (err)
3241                 goto unlink_mod;
3242
3243         /* Now module is in final location, initialize linked lists, etc. */
3244         err = module_unload_init(mod);
3245         if (err)
3246                 goto unlink_mod;
3247
3248         /* Now we've got everything in the final locations, we can
3249          * find optional sections. */
3250         err = find_module_sections(mod, info);
3251         if (err)
3252                 goto free_unload;
3253
3254         err = check_module_license_and_versions(mod);
3255         if (err)
3256                 goto free_unload;
3257
3258         /* Set up MODINFO_ATTR fields */
3259         setup_modinfo(mod, info);
3260
3261         /* Fix up syms, so that st_value is a pointer to location. */
3262         err = simplify_symbols(mod, info);
3263         if (err < 0)
3264                 goto free_modinfo;
3265
3266         err = apply_relocations(mod, info);
3267         if (err < 0)
3268                 goto free_modinfo;
3269
3270         err = post_relocation(mod, info);
3271         if (err < 0)
3272                 goto free_modinfo;
3273
3274         flush_module_icache(mod);
3275
3276         /* Now copy in args */
3277         mod->args = strndup_user(uargs, ~0UL >> 1);
3278         if (IS_ERR(mod->args)) {
3279                 err = PTR_ERR(mod->args);
3280                 goto free_arch_cleanup;
3281         }
3282
3283         dynamic_debug_setup(info->debug, info->num_debug);
3284
3285         /* Finally it's fully formed, ready to start executing. */
3286         err = complete_formation(mod, info);
3287         if (err)
3288                 goto ddebug_cleanup;
3289
3290         /* Module is ready to execute: parsing args may do that. */
3291         err = parse_args(mod->name, mod->args, mod->kp, mod->num_kp,
3292                          -32768, 32767, unknown_module_param_cb);
3293         if (err < 0)
3294                 goto bug_cleanup;
3295
3296         /* Link in to syfs. */
3297         err = mod_sysfs_setup(mod, info, mod->kp, mod->num_kp);
3298         if (err < 0)
3299                 goto bug_cleanup;
3300
3301         /* Get rid of temporary copy. */
3302         free_copy(info);
3303
3304         /* Done! */
3305         trace_module_load(mod);
3306
3307         return do_init_module(mod);
3308
3309  bug_cleanup:
3310         /* module_bug_cleanup needs module_mutex protection */
3311         mutex_lock(&module_mutex);
3312         module_bug_cleanup(mod);
3313         mutex_unlock(&module_mutex);
3314  ddebug_cleanup:
3315         dynamic_debug_remove(info->debug);
3316         synchronize_sched();
3317         kfree(mod->args);
3318  free_arch_cleanup:
3319         module_arch_cleanup(mod);
3320  free_modinfo:
3321         free_modinfo(mod);
3322  free_unload:
3323         module_unload_free(mod);
3324  unlink_mod:
3325         mutex_lock(&module_mutex);
3326         /* Unlink carefully: kallsyms could be walking list. */
3327         list_del_rcu(&mod->list);
3328         wake_up_all(&module_wq);
3329         mutex_unlock(&module_mutex);
3330  free_module:
3331         module_deallocate(mod, info);
3332  free_copy:
3333         free_copy(info);
3334         return err;
3335 }
3336
3337 SYSCALL_DEFINE3(init_module, void __user *, umod,
3338                 unsigned long, len, const char __user *, uargs)
3339 {
3340         int err;
3341         struct load_info info = { };
3342
3343         err = may_init_module();
3344         if (err)
3345                 return err;
3346
3347         pr_debug("init_module: umod=%p, len=%lu, uargs=%p\n",
3348                umod, len, uargs);
3349
3350         err = copy_module_from_user(umod, len, &info);
3351         if (err)
3352                 return err;
3353
3354         return load_module(&info, uargs, 0);
3355 }
3356
3357 SYSCALL_DEFINE3(finit_module, int, fd, const char __user *, uargs, int, flags)
3358 {
3359         int err;
3360         struct load_info info = { };
3361
3362         err = may_init_module();
3363         if (err)
3364                 return err;
3365
3366         pr_debug("finit_module: fd=%d, uargs=%p, flags=%i\n", fd, uargs, flags);
3367
3368         if (flags & ~(MODULE_INIT_IGNORE_MODVERSIONS
3369                       |MODULE_INIT_IGNORE_VERMAGIC))
3370                 return -EINVAL;
3371
3372         err = copy_module_from_fd(fd, &info);
3373         if (err)
3374                 return err;
3375
3376         return load_module(&info, uargs, flags);
3377 }
3378
3379 static inline int within(unsigned long addr, void *start, unsigned long size)
3380 {
3381         return ((void *)addr >= start && (void *)addr < start + size);
3382 }
3383
3384 #ifdef CONFIG_KALLSYMS
3385 /*
3386  * This ignores the intensely annoying "mapping symbols" found
3387  * in ARM ELF files: $a, $t and $d.
3388  */
3389 static inline int is_arm_mapping_symbol(const char *str)
3390 {
3391         return str[0] == '$' && strchr("atd", str[1])
3392                && (str[2] == '\0' || str[2] == '.');
3393 }
3394
3395 static const char *get_ksymbol(struct module *mod,
3396                                unsigned long addr,
3397                                unsigned long *size,
3398                                unsigned long *offset)
3399 {
3400         unsigned int i, best = 0;
3401         unsigned long nextval;
3402
3403         /* At worse, next value is at end of module */
3404         if (within_module_init(addr, mod))
3405                 nextval = (unsigned long)mod->module_init+mod->init_text_size;
3406         else
3407                 nextval = (unsigned long)mod->module_core+mod->core_text_size;
3408
3409         /* Scan for closest preceding symbol, and next symbol. (ELF
3410            starts real symbols at 1). */
3411         for (i = 1; i < mod->num_symtab; i++) {
3412                 if (mod->symtab[i].st_shndx == SHN_UNDEF)
3413                         continue;
3414
3415                 /* We ignore unnamed symbols: they're uninformative
3416                  * and inserted at a whim. */
3417                 if (mod->symtab[i].st_value <= addr
3418                     && mod->symtab[i].st_value > mod->symtab[best].st_value
3419                     && *(mod->strtab + mod->symtab[i].st_name) != '\0'
3420                     && !is_arm_mapping_symbol(mod->strtab + mod->symtab[i].st_name))
3421                         best = i;
3422                 if (mod->symtab[i].st_value > addr
3423                     && mod->symtab[i].st_value < nextval
3424                     && *(mod->strtab + mod->symtab[i].st_name) != '\0'
3425                     && !is_arm_mapping_symbol(mod->strtab + mod->symtab[i].st_name))
3426                         nextval = mod->symtab[i].st_value;
3427         }
3428
3429         if (!best)
3430                 return NULL;
3431
3432         if (size)
3433                 *size = nextval - mod->symtab[best].st_value;
3434         if (offset)
3435                 *offset = addr - mod->symtab[best].st_value;
3436         return mod->strtab + mod->symtab[best].st_name;
3437 }
3438
3439 /* For kallsyms to ask for address resolution.  NULL means not found.  Careful
3440  * not to lock to avoid deadlock on oopses, simply disable preemption. */
3441 const char *module_address_lookup(unsigned long addr,
3442                             unsigned long *size,
3443                             unsigned long *offset,
3444                             char **modname,
3445                             char *namebuf)
3446 {
3447         struct module *mod;
3448         const char *ret = NULL;
3449
3450         preempt_disable();
3451         list_for_each_entry_rcu(mod, &modules, list) {
3452                 if (mod->state == MODULE_STATE_UNFORMED)
3453                         continue;
3454                 if (within_module_init(addr, mod) ||
3455                     within_module_core(addr, mod)) {
3456                         if (modname)
3457                                 *modname = mod->name;
3458                         ret = get_ksymbol(mod, addr, size, offset);
3459                         break;
3460                 }
3461         }
3462         /* Make a copy in here where it's safe */
3463         if (ret) {
3464                 strncpy(namebuf, ret, KSYM_NAME_LEN - 1);
3465                 ret = namebuf;
3466         }
3467         preempt_enable();
3468         return ret;
3469 }
3470
3471 int lookup_module_symbol_name(unsigned long addr, char *symname)
3472 {
3473         struct module *mod;
3474
3475         preempt_disable();
3476         list_for_each_entry_rcu(mod, &modules, list) {
3477                 if (mod->state == MODULE_STATE_UNFORMED)
3478                         continue;
3479                 if (within_module_init(addr, mod) ||
3480                     within_module_core(addr, mod)) {
3481                         const char *sym;
3482
3483                         sym = get_ksymbol(mod, addr, NULL, NULL);
3484                         if (!sym)
3485                                 goto out;
3486                         strlcpy(symname, sym, KSYM_NAME_LEN);
3487                         preempt_enable();
3488                         return 0;
3489                 }
3490         }
3491 out:
3492         preempt_enable();
3493         return -ERANGE;
3494 }
3495
3496 int lookup_module_symbol_attrs(unsigned long addr, unsigned long *size,
3497                         unsigned long *offset, char *modname, char *name)
3498 {
3499         struct module *mod;
3500
3501         preempt_disable();
3502         list_for_each_entry_rcu(mod, &modules, list) {
3503                 if (mod->state == MODULE_STATE_UNFORMED)
3504                         continue;
3505                 if (within_module_init(addr, mod) ||
3506                     within_module_core(addr, mod)) {
3507                         const char *sym;
3508
3509                         sym = get_ksymbol(mod, addr, size, offset);
3510                         if (!sym)
3511                                 goto out;
3512                         if (modname)
3513                                 strlcpy(modname, mod->name, MODULE_NAME_LEN);
3514                         if (name)
3515                                 strlcpy(name, sym, KSYM_NAME_LEN);
3516                         preempt_enable();
3517                         return 0;
3518                 }
3519         }
3520 out:
3521         preempt_enable();
3522         return -ERANGE;
3523 }
3524
3525 int module_get_kallsym(unsigned int symnum, unsigned long *value, char *type,
3526                         char *name, char *module_name, int *exported)
3527 {
3528         struct module *mod;
3529
3530         preempt_disable();
3531         list_for_each_entry_rcu(mod, &modules, list) {
3532                 if (mod->state == MODULE_STATE_UNFORMED)
3533                         continue;
3534                 if (symnum < mod->num_symtab) {
3535                         *value = mod->symtab[symnum].st_value;
3536                         *type = mod->symtab[symnum].st_info;
3537                         strlcpy(name, mod->strtab + mod->symtab[symnum].st_name,
3538                                 KSYM_NAME_LEN);
3539                         strlcpy(module_name, mod->name, MODULE_NAME_LEN);
3540                         *exported = is_exported(name, *value, mod);
3541                         preempt_enable();
3542                         return 0;
3543                 }
3544                 symnum -= mod->num_symtab;
3545         }
3546         preempt_enable();
3547         return -ERANGE;
3548 }
3549
3550 static unsigned long mod_find_symname(struct module *mod, const char *name)
3551 {
3552         unsigned int i;
3553
3554         for (i = 0; i < mod->num_symtab; i++)
3555                 if (strcmp(name, mod->strtab+mod->symtab[i].st_name) == 0 &&
3556                     mod->symtab[i].st_info != 'U')
3557                         return mod->symtab[i].st_value;
3558         return 0;
3559 }
3560
3561 /* Look for this name: can be of form module:name. */
3562 unsigned long module_kallsyms_lookup_name(const char *name)
3563 {
3564         struct module *mod;
3565         char *colon;
3566         unsigned long ret = 0;
3567
3568         /* Don't lock: we're in enough trouble already. */
3569         preempt_disable();
3570         if ((colon = strchr(name, ':')) != NULL) {
3571                 if ((mod = find_module_all(name, colon - name, false)) != NULL)
3572                         ret = mod_find_symname(mod, colon+1);
3573         } else {
3574                 list_for_each_entry_rcu(mod, &modules, list) {
3575                         if (mod->state == MODULE_STATE_UNFORMED)
3576                                 continue;
3577                         if ((ret = mod_find_symname(mod, name)) != 0)
3578                                 break;
3579                 }
3580         }
3581         preempt_enable();
3582         return ret;
3583 }
3584
3585 int module_kallsyms_on_each_symbol(int (*fn)(void *, const char *,
3586                                              struct module *, unsigned long),
3587                                    void *data)
3588 {
3589         struct module *mod;
3590         unsigned int i;
3591         int ret;
3592
3593         list_for_each_entry(mod, &modules, list) {
3594                 if (mod->state == MODULE_STATE_UNFORMED)
3595                         continue;
3596                 for (i = 0; i < mod->num_symtab; i++) {
3597                         ret = fn(data, mod->strtab + mod->symtab[i].st_name,
3598                                  mod, mod->symtab[i].st_value);
3599                         if (ret != 0)
3600                                 return ret;
3601                 }
3602         }
3603         return 0;
3604 }
3605 #endif /* CONFIG_KALLSYMS */
3606
3607 static char *module_flags(struct module *mod, char *buf)
3608 {
3609         int bx = 0;
3610
3611         BUG_ON(mod->state == MODULE_STATE_UNFORMED);
3612         if (mod->taints ||
3613             mod->state == MODULE_STATE_GOING ||
3614             mod->state == MODULE_STATE_COMING) {
3615                 buf[bx++] = '(';
3616                 bx += module_flags_taint(mod, buf + bx);
3617                 /* Show a - for module-is-being-unloaded */
3618                 if (mod->state == MODULE_STATE_GOING)
3619                         buf[bx++] = '-';
3620                 /* Show a + for module-is-being-loaded */
3621                 if (mod->state == MODULE_STATE_COMING)
3622                         buf[bx++] = '+';
3623                 buf[bx++] = ')';
3624         }
3625         buf[bx] = '\0';
3626
3627         return buf;
3628 }
3629
3630 #ifdef CONFIG_PROC_FS
3631 /* Called by the /proc file system to return a list of modules. */
3632 static void *m_start(struct seq_file *m, loff_t *pos)
3633 {
3634         mutex_lock(&module_mutex);
3635         return seq_list_start(&modules, *pos);
3636 }
3637
3638 static void *m_next(struct seq_file *m, void *p, loff_t *pos)
3639 {
3640         return seq_list_next(p, &modules, pos);
3641 }
3642
3643 static void m_stop(struct seq_file *m, void *p)
3644 {
3645         mutex_unlock(&module_mutex);
3646 }
3647
3648 static int m_show(struct seq_file *m, void *p)
3649 {
3650         struct module *mod = list_entry(p, struct module, list);
3651         char buf[8];
3652
3653         /* We always ignore unformed modules. */
3654         if (mod->state == MODULE_STATE_UNFORMED)
3655                 return 0;
3656
3657         seq_printf(m, "%s %u",
3658                    mod->name, mod->init_size + mod->core_size);
3659         print_unload_info(m, mod);
3660
3661         /* Informative for users. */
3662         seq_printf(m, " %s",
3663                    mod->state == MODULE_STATE_GOING ? "Unloading":
3664                    mod->state == MODULE_STATE_COMING ? "Loading":
3665                    "Live");
3666         /* Used by oprofile and other similar tools. */
3667         seq_printf(m, " 0x%pK", mod->module_core);
3668
3669         /* Taints info */
3670         if (mod->taints)
3671                 seq_printf(m, " %s", module_flags(mod, buf));
3672
3673         seq_printf(m, "\n");
3674         return 0;
3675 }
3676
3677 /* Format: modulename size refcount deps address
3678
3679    Where refcount is a number or -, and deps is a comma-separated list
3680    of depends or -.
3681 */
3682 static const struct seq_operations modules_op = {
3683         .start  = m_start,
3684         .next   = m_next,
3685         .stop   = m_stop,
3686         .show   = m_show
3687 };
3688
3689 static int modules_open(struct inode *inode, struct file *file)
3690 {
3691         return seq_open(file, &modules_op);
3692 }
3693
3694 static const struct file_operations proc_modules_operations = {
3695         .open           = modules_open,
3696         .read           = seq_read,
3697         .llseek         = seq_lseek,
3698         .release        = seq_release,
3699 };
3700
3701 static int __init proc_modules_init(void)
3702 {
3703         proc_create("modules", 0, NULL, &proc_modules_operations);
3704         return 0;
3705 }
3706 module_init(proc_modules_init);
3707 #endif
3708
3709 /* Given an address, look for it in the module exception tables. */
3710 const struct exception_table_entry *search_module_extables(unsigned long addr)
3711 {
3712         const struct exception_table_entry *e = NULL;
3713         struct module *mod;
3714
3715         preempt_disable();
3716         list_for_each_entry_rcu(mod, &modules, list) {
3717                 if (mod->state == MODULE_STATE_UNFORMED)
3718                         continue;
3719                 if (mod->num_exentries == 0)
3720                         continue;
3721
3722                 e = search_extable(mod->extable,
3723                                    mod->extable + mod->num_exentries - 1,
3724                                    addr);
3725                 if (e)
3726                         break;
3727         }
3728         preempt_enable();
3729
3730         /* Now, if we found one, we are running inside it now, hence
3731            we cannot unload the module, hence no refcnt needed. */
3732         return e;
3733 }
3734
3735 /*
3736  * is_module_address - is this address inside a module?
3737  * @addr: the address to check.
3738  *
3739  * See is_module_text_address() if you simply want to see if the address
3740  * is code (not data).
3741  */
3742 bool is_module_address(unsigned long addr)
3743 {
3744         bool ret;
3745
3746         preempt_disable();
3747         ret = __module_address(addr) != NULL;
3748         preempt_enable();
3749
3750         return ret;
3751 }
3752
3753 /*
3754  * __module_address - get the module which contains an address.
3755  * @addr: the address.
3756  *
3757  * Must be called with preempt disabled or module mutex held so that
3758  * module doesn't get freed during this.
3759  */
3760 struct module *__module_address(unsigned long addr)
3761 {
3762         struct module *mod;
3763
3764         if (addr < module_addr_min || addr > module_addr_max)
3765                 return NULL;
3766
3767         list_for_each_entry_rcu(mod, &modules, list) {
3768                 if (mod->state == MODULE_STATE_UNFORMED)
3769                         continue;
3770                 if (within_module_core(addr, mod)
3771                     || within_module_init(addr, mod))
3772                         return mod;
3773         }
3774         return NULL;
3775 }
3776 EXPORT_SYMBOL_GPL(__module_address);
3777
3778 /*
3779  * is_module_text_address - is this address inside module code?
3780  * @addr: the address to check.
3781  *
3782  * See is_module_address() if you simply want to see if the address is
3783  * anywhere in a module.  See kernel_text_address() for testing if an
3784  * address corresponds to kernel or module code.
3785  */
3786 bool is_module_text_address(unsigned long addr)
3787 {
3788         bool ret;
3789
3790         preempt_disable();
3791         ret = __module_text_address(addr) != NULL;
3792         preempt_enable();
3793
3794         return ret;
3795 }
3796
3797 /*
3798  * __module_text_address - get the module whose code contains an address.
3799  * @addr: the address.
3800  *
3801  * Must be called with preempt disabled or module mutex held so that
3802  * module doesn't get freed during this.
3803  */
3804 struct module *__module_text_address(unsigned long addr)
3805 {
3806         struct module *mod = __module_address(addr);
3807         if (mod) {
3808                 /* Make sure it's within the text section. */
3809                 if (!within(addr, mod->module_init, mod->init_text_size)
3810                     && !within(addr, mod->module_core, mod->core_text_size))
3811                         mod = NULL;
3812         }
3813         return mod;
3814 }
3815 EXPORT_SYMBOL_GPL(__module_text_address);
3816
3817 /* Don't grab lock, we're oopsing. */
3818 void print_modules(void)
3819 {
3820         struct module *mod;
3821         char buf[8];
3822
3823         printk(KERN_DEFAULT "Modules linked in:");
3824         /* Most callers should already have preempt disabled, but make sure */
3825         preempt_disable();
3826         list_for_each_entry_rcu(mod, &modules, list) {
3827                 if (mod->state == MODULE_STATE_UNFORMED)
3828                         continue;
3829                 printk(" %s%s", mod->name, module_flags(mod, buf));
3830         }
3831         preempt_enable();
3832         if (last_unloaded_module[0])
3833                 printk(" [last unloaded: %s]", last_unloaded_module);
3834         printk("\n");
3835 }
3836
3837 #ifdef CONFIG_MODVERSIONS
3838 /* Generate the signature for all relevant module structures here.
3839  * If these change, we don't want to try to parse the module. */
3840 void module_layout(struct module *mod,
3841                    struct modversion_info *ver,
3842                    struct kernel_param *kp,
3843                    struct kernel_symbol *ks,
3844                    struct tracepoint * const *tp)
3845 {
3846 }
3847 EXPORT_SYMBOL(module_layout);
3848 #endif