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