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