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