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