OSDN Git Service

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