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