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