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