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