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