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