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