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