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