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