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