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