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