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