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