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