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