]> git.kernelconcepts.de Git - karo-tx-linux.git/blob - kernel/module.c
Merge ../linus
[karo-tx-linux.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/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 <linux/mutex.h>
43 #include <linux/unwind.h>
44 #include <asm/uaccess.h>
45 #include <asm/semaphore.h>
46 #include <asm/cacheflush.h>
47 #include <linux/license.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         memset(&mod->mkobj.kobj, 0, sizeof(mod->mkobj.kobj));
1059         err = kobject_set_name(&mod->mkobj.kobj, "%s", mod->name);
1060         if (err)
1061                 goto out;
1062         kobj_set_kset_s(&mod->mkobj, module_subsys);
1063         mod->mkobj.mod = mod;
1064         err = kobject_register(&mod->mkobj.kobj);
1065         if (err)
1066                 goto out;
1067
1068         err = module_param_sysfs_setup(mod, kparam, num_params);
1069         if (err)
1070                 goto out_unreg;
1071
1072         err = module_add_modinfo_attrs(mod);
1073         if (err)
1074                 goto out_unreg;
1075
1076         return 0;
1077
1078 out_unreg:
1079         kobject_unregister(&mod->mkobj.kobj);
1080 out:
1081         return err;
1082 }
1083
1084 static void mod_kobject_remove(struct module *mod)
1085 {
1086         module_remove_modinfo_attrs(mod);
1087         module_param_sysfs_remove(mod);
1088
1089         kobject_unregister(&mod->mkobj.kobj);
1090 }
1091
1092 /*
1093  * unlink the module with the whole machine is stopped with interrupts off
1094  * - this defends against kallsyms not taking locks
1095  */
1096 static int __unlink_module(void *_mod)
1097 {
1098         struct module *mod = _mod;
1099         list_del(&mod->list);
1100         return 0;
1101 }
1102
1103 /* Free a module, remove from lists, etc (must hold module mutex). */
1104 static void free_module(struct module *mod)
1105 {
1106         /* Delete from various lists */
1107         stop_machine_run(__unlink_module, mod, NR_CPUS);
1108         remove_sect_attrs(mod);
1109         mod_kobject_remove(mod);
1110
1111         unwind_remove_table(mod->unwind_info, 0);
1112
1113         /* Arch-specific cleanup. */
1114         module_arch_cleanup(mod);
1115
1116         /* Module unload stuff */
1117         module_unload_free(mod);
1118
1119         /* This may be NULL, but that's OK */
1120         module_free(mod, mod->module_init);
1121         kfree(mod->args);
1122         if (mod->percpu)
1123                 percpu_modfree(mod->percpu);
1124
1125         /* Finally, free the core (containing the module structure) */
1126         module_free(mod, mod->module_core);
1127 }
1128
1129 void *__symbol_get(const char *symbol)
1130 {
1131         struct module *owner;
1132         unsigned long value, flags;
1133         const unsigned long *crc;
1134
1135         spin_lock_irqsave(&modlist_lock, flags);
1136         value = __find_symbol(symbol, &owner, &crc, 1);
1137         if (value && !strong_try_module_get(owner))
1138                 value = 0;
1139         spin_unlock_irqrestore(&modlist_lock, flags);
1140
1141         return (void *)value;
1142 }
1143 EXPORT_SYMBOL_GPL(__symbol_get);
1144
1145 /*
1146  * Ensure that an exported symbol [global namespace] does not already exist
1147  * in the Kernel or in some other modules exported symbol table.
1148  */
1149 static int verify_export_symbols(struct module *mod)
1150 {
1151         const char *name = NULL;
1152         unsigned long i, ret = 0;
1153         struct module *owner;
1154         const unsigned long *crc;
1155
1156         for (i = 0; i < mod->num_syms; i++)
1157                 if (__find_symbol(mod->syms[i].name, &owner, &crc, 1)) {
1158                         name = mod->syms[i].name;
1159                         ret = -ENOEXEC;
1160                         goto dup;
1161                 }
1162
1163         for (i = 0; i < mod->num_gpl_syms; i++)
1164                 if (__find_symbol(mod->gpl_syms[i].name, &owner, &crc, 1)) {
1165                         name = mod->gpl_syms[i].name;
1166                         ret = -ENOEXEC;
1167                         goto dup;
1168                 }
1169
1170 dup:
1171         if (ret)
1172                 printk(KERN_ERR "%s: exports duplicate symbol %s (owned by %s)\n",
1173                         mod->name, name, module_name(owner));
1174
1175         return ret;
1176 }
1177
1178 /* Change all symbols so that sh_value encodes the pointer directly. */
1179 static int simplify_symbols(Elf_Shdr *sechdrs,
1180                             unsigned int symindex,
1181                             const char *strtab,
1182                             unsigned int versindex,
1183                             unsigned int pcpuindex,
1184                             struct module *mod)
1185 {
1186         Elf_Sym *sym = (void *)sechdrs[symindex].sh_addr;
1187         unsigned long secbase;
1188         unsigned int i, n = sechdrs[symindex].sh_size / sizeof(Elf_Sym);
1189         int ret = 0;
1190
1191         for (i = 1; i < n; i++) {
1192                 switch (sym[i].st_shndx) {
1193                 case SHN_COMMON:
1194                         /* We compiled with -fno-common.  These are not
1195                            supposed to happen.  */
1196                         DEBUGP("Common symbol: %s\n", strtab + sym[i].st_name);
1197                         printk("%s: please compile with -fno-common\n",
1198                                mod->name);
1199                         ret = -ENOEXEC;
1200                         break;
1201
1202                 case SHN_ABS:
1203                         /* Don't need to do anything */
1204                         DEBUGP("Absolute symbol: 0x%08lx\n",
1205                                (long)sym[i].st_value);
1206                         break;
1207
1208                 case SHN_UNDEF:
1209                         sym[i].st_value
1210                           = resolve_symbol(sechdrs, versindex,
1211                                            strtab + sym[i].st_name, mod);
1212
1213                         /* Ok if resolved.  */
1214                         if (sym[i].st_value != 0)
1215                                 break;
1216                         /* Ok if weak.  */
1217                         if (ELF_ST_BIND(sym[i].st_info) == STB_WEAK)
1218                                 break;
1219
1220                         printk(KERN_WARNING "%s: Unknown symbol %s\n",
1221                                mod->name, strtab + sym[i].st_name);
1222                         ret = -ENOENT;
1223                         break;
1224
1225                 default:
1226                         /* Divert to percpu allocation if a percpu var. */
1227                         if (sym[i].st_shndx == pcpuindex)
1228                                 secbase = (unsigned long)mod->percpu;
1229                         else
1230                                 secbase = sechdrs[sym[i].st_shndx].sh_addr;
1231                         sym[i].st_value += secbase;
1232                         break;
1233                 }
1234         }
1235
1236         return ret;
1237 }
1238
1239 /* Update size with this section: return offset. */
1240 static long get_offset(unsigned long *size, Elf_Shdr *sechdr)
1241 {
1242         long ret;
1243
1244         ret = ALIGN(*size, sechdr->sh_addralign ?: 1);
1245         *size = ret + sechdr->sh_size;
1246         return ret;
1247 }
1248
1249 /* Lay out the SHF_ALLOC sections in a way not dissimilar to how ld
1250    might -- code, read-only data, read-write data, small data.  Tally
1251    sizes, and place the offsets into sh_entsize fields: high bit means it
1252    belongs in init. */
1253 static void layout_sections(struct module *mod,
1254                             const Elf_Ehdr *hdr,
1255                             Elf_Shdr *sechdrs,
1256                             const char *secstrings)
1257 {
1258         static unsigned long const masks[][2] = {
1259                 /* NOTE: all executable code must be the first section
1260                  * in this array; otherwise modify the text_size
1261                  * finder in the two loops below */
1262                 { SHF_EXECINSTR | SHF_ALLOC, ARCH_SHF_SMALL },
1263                 { SHF_ALLOC, SHF_WRITE | ARCH_SHF_SMALL },
1264                 { SHF_WRITE | SHF_ALLOC, ARCH_SHF_SMALL },
1265                 { ARCH_SHF_SMALL | SHF_ALLOC, 0 }
1266         };
1267         unsigned int m, i;
1268
1269         for (i = 0; i < hdr->e_shnum; i++)
1270                 sechdrs[i].sh_entsize = ~0UL;
1271
1272         DEBUGP("Core section allocation order:\n");
1273         for (m = 0; m < ARRAY_SIZE(masks); ++m) {
1274                 for (i = 0; i < hdr->e_shnum; ++i) {
1275                         Elf_Shdr *s = &sechdrs[i];
1276
1277                         if ((s->sh_flags & masks[m][0]) != masks[m][0]
1278                             || (s->sh_flags & masks[m][1])
1279                             || s->sh_entsize != ~0UL
1280                             || strncmp(secstrings + s->sh_name,
1281                                        ".init", 5) == 0)
1282                                 continue;
1283                         s->sh_entsize = get_offset(&mod->core_size, s);
1284                         DEBUGP("\t%s\n", secstrings + s->sh_name);
1285                 }
1286                 if (m == 0)
1287                         mod->core_text_size = mod->core_size;
1288         }
1289
1290         DEBUGP("Init section allocation order:\n");
1291         for (m = 0; m < ARRAY_SIZE(masks); ++m) {
1292                 for (i = 0; i < hdr->e_shnum; ++i) {
1293                         Elf_Shdr *s = &sechdrs[i];
1294
1295                         if ((s->sh_flags & masks[m][0]) != masks[m][0]
1296                             || (s->sh_flags & masks[m][1])
1297                             || s->sh_entsize != ~0UL
1298                             || strncmp(secstrings + s->sh_name,
1299                                        ".init", 5) != 0)
1300                                 continue;
1301                         s->sh_entsize = (get_offset(&mod->init_size, s)
1302                                          | INIT_OFFSET_MASK);
1303                         DEBUGP("\t%s\n", secstrings + s->sh_name);
1304                 }
1305                 if (m == 0)
1306                         mod->init_text_size = mod->init_size;
1307         }
1308 }
1309
1310 static void set_license(struct module *mod, const char *license)
1311 {
1312         if (!license)
1313                 license = "unspecified";
1314
1315         mod->license_gplok = license_is_gpl_compatible(license);
1316         if (!mod->license_gplok && !(tainted & TAINT_PROPRIETARY_MODULE)) {
1317                 printk(KERN_WARNING "%s: module license '%s' taints kernel.\n",
1318                        mod->name, license);
1319                 add_taint(TAINT_PROPRIETARY_MODULE);
1320         }
1321 }
1322
1323 /* Parse tag=value strings from .modinfo section */
1324 static char *next_string(char *string, unsigned long *secsize)
1325 {
1326         /* Skip non-zero chars */
1327         while (string[0]) {
1328                 string++;
1329                 if ((*secsize)-- <= 1)
1330                         return NULL;
1331         }
1332
1333         /* Skip any zero padding. */
1334         while (!string[0]) {
1335                 string++;
1336                 if ((*secsize)-- <= 1)
1337                         return NULL;
1338         }
1339         return string;
1340 }
1341
1342 static char *get_modinfo(Elf_Shdr *sechdrs,
1343                          unsigned int info,
1344                          const char *tag)
1345 {
1346         char *p;
1347         unsigned int taglen = strlen(tag);
1348         unsigned long size = sechdrs[info].sh_size;
1349
1350         for (p = (char *)sechdrs[info].sh_addr; p; p = next_string(p, &size)) {
1351                 if (strncmp(p, tag, taglen) == 0 && p[taglen] == '=')
1352                         return p + taglen + 1;
1353         }
1354         return NULL;
1355 }
1356
1357 static void setup_modinfo(struct module *mod, Elf_Shdr *sechdrs,
1358                           unsigned int infoindex)
1359 {
1360         struct module_attribute *attr;
1361         int i;
1362
1363         for (i = 0; (attr = modinfo_attrs[i]); i++) {
1364                 if (attr->setup)
1365                         attr->setup(mod,
1366                                     get_modinfo(sechdrs,
1367                                                 infoindex,
1368                                                 attr->attr.name));
1369         }
1370 }
1371
1372 #ifdef CONFIG_KALLSYMS
1373 int is_exported(const char *name, const struct module *mod)
1374 {
1375         if (!mod && lookup_symbol(name, __start___ksymtab, __stop___ksymtab))
1376                 return 1;
1377         else
1378                 if (mod && lookup_symbol(name, mod->syms, mod->syms + mod->num_syms))
1379                         return 1;
1380                 else
1381                         return 0;
1382 }
1383
1384 /* As per nm */
1385 static char elf_type(const Elf_Sym *sym,
1386                      Elf_Shdr *sechdrs,
1387                      const char *secstrings,
1388                      struct module *mod)
1389 {
1390         if (ELF_ST_BIND(sym->st_info) == STB_WEAK) {
1391                 if (ELF_ST_TYPE(sym->st_info) == STT_OBJECT)
1392                         return 'v';
1393                 else
1394                         return 'w';
1395         }
1396         if (sym->st_shndx == SHN_UNDEF)
1397                 return 'U';
1398         if (sym->st_shndx == SHN_ABS)
1399                 return 'a';
1400         if (sym->st_shndx >= SHN_LORESERVE)
1401                 return '?';
1402         if (sechdrs[sym->st_shndx].sh_flags & SHF_EXECINSTR)
1403                 return 't';
1404         if (sechdrs[sym->st_shndx].sh_flags & SHF_ALLOC
1405             && sechdrs[sym->st_shndx].sh_type != SHT_NOBITS) {
1406                 if (!(sechdrs[sym->st_shndx].sh_flags & SHF_WRITE))
1407                         return 'r';
1408                 else if (sechdrs[sym->st_shndx].sh_flags & ARCH_SHF_SMALL)
1409                         return 'g';
1410                 else
1411                         return 'd';
1412         }
1413         if (sechdrs[sym->st_shndx].sh_type == SHT_NOBITS) {
1414                 if (sechdrs[sym->st_shndx].sh_flags & ARCH_SHF_SMALL)
1415                         return 's';
1416                 else
1417                         return 'b';
1418         }
1419         if (strncmp(secstrings + sechdrs[sym->st_shndx].sh_name,
1420                     ".debug", strlen(".debug")) == 0)
1421                 return 'n';
1422         return '?';
1423 }
1424
1425 static void add_kallsyms(struct module *mod,
1426                          Elf_Shdr *sechdrs,
1427                          unsigned int symindex,
1428                          unsigned int strindex,
1429                          const char *secstrings)
1430 {
1431         unsigned int i;
1432
1433         mod->symtab = (void *)sechdrs[symindex].sh_addr;
1434         mod->num_symtab = sechdrs[symindex].sh_size / sizeof(Elf_Sym);
1435         mod->strtab = (void *)sechdrs[strindex].sh_addr;
1436
1437         /* Set types up while we still have access to sections. */
1438         for (i = 0; i < mod->num_symtab; i++)
1439                 mod->symtab[i].st_info
1440                         = elf_type(&mod->symtab[i], sechdrs, secstrings, mod);
1441 }
1442 #else
1443 static inline void add_kallsyms(struct module *mod,
1444                                 Elf_Shdr *sechdrs,
1445                                 unsigned int symindex,
1446                                 unsigned int strindex,
1447                                 const char *secstrings)
1448 {
1449 }
1450 #endif /* CONFIG_KALLSYMS */
1451
1452 /* Allocate and load the module: note that size of section 0 is always
1453    zero, and we rely on this for optional sections. */
1454 static struct module *load_module(void __user *umod,
1455                                   unsigned long len,
1456                                   const char __user *uargs)
1457 {
1458         Elf_Ehdr *hdr;
1459         Elf_Shdr *sechdrs;
1460         char *secstrings, *args, *modmagic, *strtab = NULL;
1461         unsigned int i;
1462         unsigned int symindex = 0;
1463         unsigned int strindex = 0;
1464         unsigned int setupindex;
1465         unsigned int exindex;
1466         unsigned int exportindex;
1467         unsigned int modindex;
1468         unsigned int obsparmindex;
1469         unsigned int infoindex;
1470         unsigned int gplindex;
1471         unsigned int crcindex;
1472         unsigned int gplcrcindex;
1473         unsigned int versindex;
1474         unsigned int pcpuindex;
1475         unsigned int gplfutureindex;
1476         unsigned int gplfuturecrcindex;
1477         unsigned int unwindex = 0;
1478         unsigned int unusedindex;
1479         unsigned int unusedcrcindex;
1480         unsigned int unusedgplindex;
1481         unsigned int unusedgplcrcindex;
1482         struct module *mod;
1483         long err = 0;
1484         void *percpu = NULL, *ptr = NULL; /* Stops spurious gcc warning */
1485         struct exception_table_entry *extable;
1486         mm_segment_t old_fs;
1487
1488         DEBUGP("load_module: umod=%p, len=%lu, uargs=%p\n",
1489                umod, len, uargs);
1490         if (len < sizeof(*hdr))
1491                 return ERR_PTR(-ENOEXEC);
1492
1493         /* Suck in entire file: we'll want most of it. */
1494         /* vmalloc barfs on "unusual" numbers.  Check here */
1495         if (len > 64 * 1024 * 1024 || (hdr = vmalloc(len)) == NULL)
1496                 return ERR_PTR(-ENOMEM);
1497         if (copy_from_user(hdr, umod, len) != 0) {
1498                 err = -EFAULT;
1499                 goto free_hdr;
1500         }
1501
1502         /* Sanity checks against insmoding binaries or wrong arch,
1503            weird elf version */
1504         if (memcmp(hdr->e_ident, ELFMAG, 4) != 0
1505             || hdr->e_type != ET_REL
1506             || !elf_check_arch(hdr)
1507             || hdr->e_shentsize != sizeof(*sechdrs)) {
1508                 err = -ENOEXEC;
1509                 goto free_hdr;
1510         }
1511
1512         if (len < hdr->e_shoff + hdr->e_shnum * sizeof(Elf_Shdr))
1513                 goto truncated;
1514
1515         /* Convenience variables */
1516         sechdrs = (void *)hdr + hdr->e_shoff;
1517         secstrings = (void *)hdr + sechdrs[hdr->e_shstrndx].sh_offset;
1518         sechdrs[0].sh_addr = 0;
1519
1520         for (i = 1; i < hdr->e_shnum; i++) {
1521                 if (sechdrs[i].sh_type != SHT_NOBITS
1522                     && len < sechdrs[i].sh_offset + sechdrs[i].sh_size)
1523                         goto truncated;
1524
1525                 /* Mark all sections sh_addr with their address in the
1526                    temporary image. */
1527                 sechdrs[i].sh_addr = (size_t)hdr + sechdrs[i].sh_offset;
1528
1529                 /* Internal symbols and strings. */
1530                 if (sechdrs[i].sh_type == SHT_SYMTAB) {
1531                         symindex = i;
1532                         strindex = sechdrs[i].sh_link;
1533                         strtab = (char *)hdr + sechdrs[strindex].sh_offset;
1534                 }
1535 #ifndef CONFIG_MODULE_UNLOAD
1536                 /* Don't load .exit sections */
1537                 if (strncmp(secstrings+sechdrs[i].sh_name, ".exit", 5) == 0)
1538                         sechdrs[i].sh_flags &= ~(unsigned long)SHF_ALLOC;
1539 #endif
1540         }
1541
1542         modindex = find_sec(hdr, sechdrs, secstrings,
1543                             ".gnu.linkonce.this_module");
1544         if (!modindex) {
1545                 printk(KERN_WARNING "No module found in object\n");
1546                 err = -ENOEXEC;
1547                 goto free_hdr;
1548         }
1549         mod = (void *)sechdrs[modindex].sh_addr;
1550
1551         if (symindex == 0) {
1552                 printk(KERN_WARNING "%s: module has no symbols (stripped?)\n",
1553                        mod->name);
1554                 err = -ENOEXEC;
1555                 goto free_hdr;
1556         }
1557
1558         /* Optional sections */
1559         exportindex = find_sec(hdr, sechdrs, secstrings, "__ksymtab");
1560         gplindex = find_sec(hdr, sechdrs, secstrings, "__ksymtab_gpl");
1561         gplfutureindex = find_sec(hdr, sechdrs, secstrings, "__ksymtab_gpl_future");
1562         unusedindex = find_sec(hdr, sechdrs, secstrings, "__ksymtab_unused");
1563         unusedgplindex = find_sec(hdr, sechdrs, secstrings, "__ksymtab_unused_gpl");
1564         crcindex = find_sec(hdr, sechdrs, secstrings, "__kcrctab");
1565         gplcrcindex = find_sec(hdr, sechdrs, secstrings, "__kcrctab_gpl");
1566         gplfuturecrcindex = find_sec(hdr, sechdrs, secstrings, "__kcrctab_gpl_future");
1567         unusedcrcindex = find_sec(hdr, sechdrs, secstrings, "__kcrctab_unused");
1568         unusedgplcrcindex = find_sec(hdr, sechdrs, secstrings, "__kcrctab_unused_gpl");
1569         setupindex = find_sec(hdr, sechdrs, secstrings, "__param");
1570         exindex = find_sec(hdr, sechdrs, secstrings, "__ex_table");
1571         obsparmindex = find_sec(hdr, sechdrs, secstrings, "__obsparm");
1572         versindex = find_sec(hdr, sechdrs, secstrings, "__versions");
1573         infoindex = find_sec(hdr, sechdrs, secstrings, ".modinfo");
1574         pcpuindex = find_pcpusec(hdr, sechdrs, secstrings);
1575 #ifdef ARCH_UNWIND_SECTION_NAME
1576         unwindex = find_sec(hdr, sechdrs, secstrings, ARCH_UNWIND_SECTION_NAME);
1577 #endif
1578
1579         /* Don't keep modinfo section */
1580         sechdrs[infoindex].sh_flags &= ~(unsigned long)SHF_ALLOC;
1581 #ifdef CONFIG_KALLSYMS
1582         /* Keep symbol and string tables for decoding later. */
1583         sechdrs[symindex].sh_flags |= SHF_ALLOC;
1584         sechdrs[strindex].sh_flags |= SHF_ALLOC;
1585 #endif
1586         if (unwindex)
1587                 sechdrs[unwindex].sh_flags |= SHF_ALLOC;
1588
1589         /* Check module struct version now, before we try to use module. */
1590         if (!check_modstruct_version(sechdrs, versindex, mod)) {
1591                 err = -ENOEXEC;
1592                 goto free_hdr;
1593         }
1594
1595         modmagic = get_modinfo(sechdrs, infoindex, "vermagic");
1596         /* This is allowed: modprobe --force will invalidate it. */
1597         if (!modmagic) {
1598                 add_taint(TAINT_FORCED_MODULE);
1599                 printk(KERN_WARNING "%s: no version magic, tainting kernel.\n",
1600                        mod->name);
1601         } else if (!same_magic(modmagic, vermagic)) {
1602                 printk(KERN_ERR "%s: version magic '%s' should be '%s'\n",
1603                        mod->name, modmagic, vermagic);
1604                 err = -ENOEXEC;
1605                 goto free_hdr;
1606         }
1607
1608         /* Now copy in args */
1609         args = strndup_user(uargs, ~0UL >> 1);
1610         if (IS_ERR(args)) {
1611                 err = PTR_ERR(args);
1612                 goto free_hdr;
1613         }
1614
1615         if (find_module(mod->name)) {
1616                 err = -EEXIST;
1617                 goto free_mod;
1618         }
1619
1620         mod->state = MODULE_STATE_COMING;
1621
1622         /* Allow arches to frob section contents and sizes.  */
1623         err = module_frob_arch_sections(hdr, sechdrs, secstrings, mod);
1624         if (err < 0)
1625                 goto free_mod;
1626
1627         if (pcpuindex) {
1628                 /* We have a special allocation for this section. */
1629                 percpu = percpu_modalloc(sechdrs[pcpuindex].sh_size,
1630                                          sechdrs[pcpuindex].sh_addralign,
1631                                          mod->name);
1632                 if (!percpu) {
1633                         err = -ENOMEM;
1634                         goto free_mod;
1635                 }
1636                 sechdrs[pcpuindex].sh_flags &= ~(unsigned long)SHF_ALLOC;
1637                 mod->percpu = percpu;
1638         }
1639
1640         /* Determine total sizes, and put offsets in sh_entsize.  For now
1641            this is done generically; there doesn't appear to be any
1642            special cases for the architectures. */
1643         layout_sections(mod, hdr, sechdrs, secstrings);
1644
1645         /* Do the allocs. */
1646         ptr = module_alloc(mod->core_size);
1647         if (!ptr) {
1648                 err = -ENOMEM;
1649                 goto free_percpu;
1650         }
1651         memset(ptr, 0, mod->core_size);
1652         mod->module_core = ptr;
1653
1654         ptr = module_alloc(mod->init_size);
1655         if (!ptr && mod->init_size) {
1656                 err = -ENOMEM;
1657                 goto free_core;
1658         }
1659         memset(ptr, 0, mod->init_size);
1660         mod->module_init = ptr;
1661
1662         /* Transfer each section which specifies SHF_ALLOC */
1663         DEBUGP("final section addresses:\n");
1664         for (i = 0; i < hdr->e_shnum; i++) {
1665                 void *dest;
1666
1667                 if (!(sechdrs[i].sh_flags & SHF_ALLOC))
1668                         continue;
1669
1670                 if (sechdrs[i].sh_entsize & INIT_OFFSET_MASK)
1671                         dest = mod->module_init
1672                                 + (sechdrs[i].sh_entsize & ~INIT_OFFSET_MASK);
1673                 else
1674                         dest = mod->module_core + sechdrs[i].sh_entsize;
1675
1676                 if (sechdrs[i].sh_type != SHT_NOBITS)
1677                         memcpy(dest, (void *)sechdrs[i].sh_addr,
1678                                sechdrs[i].sh_size);
1679                 /* Update sh_addr to point to copy in image. */
1680                 sechdrs[i].sh_addr = (unsigned long)dest;
1681                 DEBUGP("\t0x%lx %s\n", sechdrs[i].sh_addr, secstrings + sechdrs[i].sh_name);
1682         }
1683         /* Module has been moved. */
1684         mod = (void *)sechdrs[modindex].sh_addr;
1685
1686         /* Now we've moved module, initialize linked lists, etc. */
1687         module_unload_init(mod);
1688
1689         /* Set up license info based on the info section */
1690         set_license(mod, get_modinfo(sechdrs, infoindex, "license"));
1691
1692         if (strcmp(mod->name, "ndiswrapper") == 0)
1693                 add_taint(TAINT_PROPRIETARY_MODULE);
1694         if (strcmp(mod->name, "driverloader") == 0)
1695                 add_taint(TAINT_PROPRIETARY_MODULE);
1696
1697         /* Set up MODINFO_ATTR fields */
1698         setup_modinfo(mod, sechdrs, infoindex);
1699
1700         /* Fix up syms, so that st_value is a pointer to location. */
1701         err = simplify_symbols(sechdrs, symindex, strtab, versindex, pcpuindex,
1702                                mod);
1703         if (err < 0)
1704                 goto cleanup;
1705
1706         /* Set up EXPORTed & EXPORT_GPLed symbols (section 0 is 0 length) */
1707         mod->num_syms = sechdrs[exportindex].sh_size / sizeof(*mod->syms);
1708         mod->syms = (void *)sechdrs[exportindex].sh_addr;
1709         if (crcindex)
1710                 mod->crcs = (void *)sechdrs[crcindex].sh_addr;
1711         mod->num_gpl_syms = sechdrs[gplindex].sh_size / sizeof(*mod->gpl_syms);
1712         mod->gpl_syms = (void *)sechdrs[gplindex].sh_addr;
1713         if (gplcrcindex)
1714                 mod->gpl_crcs = (void *)sechdrs[gplcrcindex].sh_addr;
1715         mod->num_gpl_future_syms = sechdrs[gplfutureindex].sh_size /
1716                                         sizeof(*mod->gpl_future_syms);
1717         mod->num_unused_syms = sechdrs[unusedindex].sh_size /
1718                                         sizeof(*mod->unused_syms);
1719         mod->num_unused_gpl_syms = sechdrs[unusedgplindex].sh_size /
1720                                         sizeof(*mod->unused_gpl_syms);
1721         mod->gpl_future_syms = (void *)sechdrs[gplfutureindex].sh_addr;
1722         if (gplfuturecrcindex)
1723                 mod->gpl_future_crcs = (void *)sechdrs[gplfuturecrcindex].sh_addr;
1724
1725         mod->unused_syms = (void *)sechdrs[unusedindex].sh_addr;
1726         if (unusedcrcindex)
1727                 mod->unused_crcs = (void *)sechdrs[unusedcrcindex].sh_addr;
1728         mod->unused_gpl_syms = (void *)sechdrs[unusedgplindex].sh_addr;
1729         if (unusedgplcrcindex)
1730                 mod->unused_crcs = (void *)sechdrs[unusedgplcrcindex].sh_addr;
1731
1732 #ifdef CONFIG_MODVERSIONS
1733         if ((mod->num_syms && !crcindex) || 
1734             (mod->num_gpl_syms && !gplcrcindex) ||
1735             (mod->num_gpl_future_syms && !gplfuturecrcindex) ||
1736             (mod->num_unused_syms && !unusedcrcindex) ||
1737             (mod->num_unused_gpl_syms && !unusedgplcrcindex)) {
1738                 printk(KERN_WARNING "%s: No versions for exported symbols."
1739                        " Tainting kernel.\n", mod->name);
1740                 add_taint(TAINT_FORCED_MODULE);
1741         }
1742 #endif
1743
1744         /* Now do relocations. */
1745         for (i = 1; i < hdr->e_shnum; i++) {
1746                 const char *strtab = (char *)sechdrs[strindex].sh_addr;
1747                 unsigned int info = sechdrs[i].sh_info;
1748
1749                 /* Not a valid relocation section? */
1750                 if (info >= hdr->e_shnum)
1751                         continue;
1752
1753                 /* Don't bother with non-allocated sections */
1754                 if (!(sechdrs[info].sh_flags & SHF_ALLOC))
1755                         continue;
1756
1757                 if (sechdrs[i].sh_type == SHT_REL)
1758                         err = apply_relocate(sechdrs, strtab, symindex, i,mod);
1759                 else if (sechdrs[i].sh_type == SHT_RELA)
1760                         err = apply_relocate_add(sechdrs, strtab, symindex, i,
1761                                                  mod);
1762                 if (err < 0)
1763                         goto cleanup;
1764         }
1765
1766         /* Find duplicate symbols */
1767         err = verify_export_symbols(mod);
1768
1769         if (err < 0)
1770                 goto cleanup;
1771
1772         /* Set up and sort exception table */
1773         mod->num_exentries = sechdrs[exindex].sh_size / sizeof(*mod->extable);
1774         mod->extable = extable = (void *)sechdrs[exindex].sh_addr;
1775         sort_extable(extable, extable + mod->num_exentries);
1776
1777         /* Finally, copy percpu area over. */
1778         percpu_modcopy(mod->percpu, (void *)sechdrs[pcpuindex].sh_addr,
1779                        sechdrs[pcpuindex].sh_size);
1780
1781         add_kallsyms(mod, sechdrs, symindex, strindex, secstrings);
1782
1783         err = module_finalize(hdr, sechdrs, mod);
1784         if (err < 0)
1785                 goto cleanup;
1786
1787         /* flush the icache in correct context */
1788         old_fs = get_fs();
1789         set_fs(KERNEL_DS);
1790
1791         /*
1792          * Flush the instruction cache, since we've played with text.
1793          * Do it before processing of module parameters, so the module
1794          * can provide parameter accessor functions of its own.
1795          */
1796         if (mod->module_init)
1797                 flush_icache_range((unsigned long)mod->module_init,
1798                                    (unsigned long)mod->module_init
1799                                    + mod->init_size);
1800         flush_icache_range((unsigned long)mod->module_core,
1801                            (unsigned long)mod->module_core + mod->core_size);
1802
1803         set_fs(old_fs);
1804
1805         mod->args = args;
1806         if (obsparmindex)
1807                 printk(KERN_WARNING "%s: Ignoring obsolete parameters\n",
1808                        mod->name);
1809
1810         /* Size of section 0 is 0, so this works well if no params */
1811         err = parse_args(mod->name, mod->args,
1812                          (struct kernel_param *)
1813                          sechdrs[setupindex].sh_addr,
1814                          sechdrs[setupindex].sh_size
1815                          / sizeof(struct kernel_param),
1816                          NULL);
1817         if (err < 0)
1818                 goto arch_cleanup;
1819
1820         err = mod_sysfs_setup(mod, 
1821                               (struct kernel_param *)
1822                               sechdrs[setupindex].sh_addr,
1823                               sechdrs[setupindex].sh_size
1824                               / sizeof(struct kernel_param));
1825         if (err < 0)
1826                 goto arch_cleanup;
1827         add_sect_attrs(mod, hdr->e_shnum, secstrings, sechdrs);
1828
1829         /* Size of section 0 is 0, so this works well if no unwind info. */
1830         mod->unwind_info = unwind_add_table(mod,
1831                                             (void *)sechdrs[unwindex].sh_addr,
1832                                             sechdrs[unwindex].sh_size);
1833
1834         /* Get rid of temporary copy */
1835         vfree(hdr);
1836
1837         /* Done! */
1838         return mod;
1839
1840  arch_cleanup:
1841         module_arch_cleanup(mod);
1842  cleanup:
1843         module_unload_free(mod);
1844         module_free(mod, mod->module_init);
1845  free_core:
1846         module_free(mod, mod->module_core);
1847  free_percpu:
1848         if (percpu)
1849                 percpu_modfree(percpu);
1850  free_mod:
1851         kfree(args);
1852  free_hdr:
1853         vfree(hdr);
1854         return ERR_PTR(err);
1855
1856  truncated:
1857         printk(KERN_ERR "Module len %lu truncated\n", len);
1858         err = -ENOEXEC;
1859         goto free_hdr;
1860 }
1861
1862 /*
1863  * link the module with the whole machine is stopped with interrupts off
1864  * - this defends against kallsyms not taking locks
1865  */
1866 static int __link_module(void *_mod)
1867 {
1868         struct module *mod = _mod;
1869         list_add(&mod->list, &modules);
1870         return 0;
1871 }
1872
1873 /* This is where the real work happens */
1874 asmlinkage long
1875 sys_init_module(void __user *umod,
1876                 unsigned long len,
1877                 const char __user *uargs)
1878 {
1879         struct module *mod;
1880         int ret = 0;
1881
1882         /* Must have permission */
1883         if (!capable(CAP_SYS_MODULE))
1884                 return -EPERM;
1885
1886         /* Only one module load at a time, please */
1887         if (mutex_lock_interruptible(&module_mutex) != 0)
1888                 return -EINTR;
1889
1890         /* Do all the hard work */
1891         mod = load_module(umod, len, uargs);
1892         if (IS_ERR(mod)) {
1893                 mutex_unlock(&module_mutex);
1894                 return PTR_ERR(mod);
1895         }
1896
1897         /* Now sew it into the lists.  They won't access us, since
1898            strong_try_module_get() will fail. */
1899         stop_machine_run(__link_module, mod, NR_CPUS);
1900
1901         /* Drop lock so they can recurse */
1902         mutex_unlock(&module_mutex);
1903
1904         blocking_notifier_call_chain(&module_notify_list,
1905                         MODULE_STATE_COMING, mod);
1906
1907         /* Start the module */
1908         if (mod->init != NULL)
1909                 ret = mod->init();
1910         if (ret < 0) {
1911                 /* Init routine failed: abort.  Try to protect us from
1912                    buggy refcounters. */
1913                 mod->state = MODULE_STATE_GOING;
1914                 synchronize_sched();
1915                 if (mod->unsafe)
1916                         printk(KERN_ERR "%s: module is now stuck!\n",
1917                                mod->name);
1918                 else {
1919                         module_put(mod);
1920                         mutex_lock(&module_mutex);
1921                         free_module(mod);
1922                         mutex_unlock(&module_mutex);
1923                 }
1924                 return ret;
1925         }
1926
1927         /* Now it's a first class citizen! */
1928         mutex_lock(&module_mutex);
1929         mod->state = MODULE_STATE_LIVE;
1930         /* Drop initial reference. */
1931         module_put(mod);
1932         unwind_remove_table(mod->unwind_info, 1);
1933         module_free(mod, mod->module_init);
1934         mod->module_init = NULL;
1935         mod->init_size = 0;
1936         mod->init_text_size = 0;
1937         mutex_unlock(&module_mutex);
1938
1939         return 0;
1940 }
1941
1942 static inline int within(unsigned long addr, void *start, unsigned long size)
1943 {
1944         return ((void *)addr >= start && (void *)addr < start + size);
1945 }
1946
1947 #ifdef CONFIG_KALLSYMS
1948 /*
1949  * This ignores the intensely annoying "mapping symbols" found
1950  * in ARM ELF files: $a, $t and $d.
1951  */
1952 static inline int is_arm_mapping_symbol(const char *str)
1953 {
1954         return str[0] == '$' && strchr("atd", str[1]) 
1955                && (str[2] == '\0' || str[2] == '.');
1956 }
1957
1958 static const char *get_ksymbol(struct module *mod,
1959                                unsigned long addr,
1960                                unsigned long *size,
1961                                unsigned long *offset)
1962 {
1963         unsigned int i, best = 0;
1964         unsigned long nextval;
1965
1966         /* At worse, next value is at end of module */
1967         if (within(addr, mod->module_init, mod->init_size))
1968                 nextval = (unsigned long)mod->module_init+mod->init_text_size;
1969         else 
1970                 nextval = (unsigned long)mod->module_core+mod->core_text_size;
1971
1972         /* Scan for closest preceeding symbol, and next symbol. (ELF
1973            starts real symbols at 1). */
1974         for (i = 1; i < mod->num_symtab; i++) {
1975                 if (mod->symtab[i].st_shndx == SHN_UNDEF)
1976                         continue;
1977
1978                 /* We ignore unnamed symbols: they're uninformative
1979                  * and inserted at a whim. */
1980                 if (mod->symtab[i].st_value <= addr
1981                     && mod->symtab[i].st_value > mod->symtab[best].st_value
1982                     && *(mod->strtab + mod->symtab[i].st_name) != '\0'
1983                     && !is_arm_mapping_symbol(mod->strtab + mod->symtab[i].st_name))
1984                         best = i;
1985                 if (mod->symtab[i].st_value > addr
1986                     && mod->symtab[i].st_value < nextval
1987                     && *(mod->strtab + mod->symtab[i].st_name) != '\0'
1988                     && !is_arm_mapping_symbol(mod->strtab + mod->symtab[i].st_name))
1989                         nextval = mod->symtab[i].st_value;
1990         }
1991
1992         if (!best)
1993                 return NULL;
1994
1995         *size = nextval - mod->symtab[best].st_value;
1996         *offset = addr - mod->symtab[best].st_value;
1997         return mod->strtab + mod->symtab[best].st_name;
1998 }
1999
2000 /* For kallsyms to ask for address resolution.  NULL means not found.
2001    We don't lock, as this is used for oops resolution and races are a
2002    lesser concern. */
2003 const char *module_address_lookup(unsigned long addr,
2004                                   unsigned long *size,
2005                                   unsigned long *offset,
2006                                   char **modname)
2007 {
2008         struct module *mod;
2009
2010         list_for_each_entry(mod, &modules, list) {
2011                 if (within(addr, mod->module_init, mod->init_size)
2012                     || within(addr, mod->module_core, mod->core_size)) {
2013                         *modname = mod->name;
2014                         return get_ksymbol(mod, addr, size, offset);
2015                 }
2016         }
2017         return NULL;
2018 }
2019
2020 struct module *module_get_kallsym(unsigned int symnum,
2021                                   unsigned long *value,
2022                                   char *type,
2023                                   char namebuf[128])
2024 {
2025         struct module *mod;
2026
2027         mutex_lock(&module_mutex);
2028         list_for_each_entry(mod, &modules, list) {
2029                 if (symnum < mod->num_symtab) {
2030                         *value = mod->symtab[symnum].st_value;
2031                         *type = mod->symtab[symnum].st_info;
2032                         strncpy(namebuf,
2033                                 mod->strtab + mod->symtab[symnum].st_name,
2034                                 127);
2035                         mutex_unlock(&module_mutex);
2036                         return mod;
2037                 }
2038                 symnum -= mod->num_symtab;
2039         }
2040         mutex_unlock(&module_mutex);
2041         return NULL;
2042 }
2043
2044 static unsigned long mod_find_symname(struct module *mod, const char *name)
2045 {
2046         unsigned int i;
2047
2048         for (i = 0; i < mod->num_symtab; i++)
2049                 if (strcmp(name, mod->strtab+mod->symtab[i].st_name) == 0 &&
2050                     mod->symtab[i].st_info != 'U')
2051                         return mod->symtab[i].st_value;
2052         return 0;
2053 }
2054
2055 /* Look for this name: can be of form module:name. */
2056 unsigned long module_kallsyms_lookup_name(const char *name)
2057 {
2058         struct module *mod;
2059         char *colon;
2060         unsigned long ret = 0;
2061
2062         /* Don't lock: we're in enough trouble already. */
2063         if ((colon = strchr(name, ':')) != NULL) {
2064                 *colon = '\0';
2065                 if ((mod = find_module(name)) != NULL)
2066                         ret = mod_find_symname(mod, colon+1);
2067                 *colon = ':';
2068         } else {
2069                 list_for_each_entry(mod, &modules, list)
2070                         if ((ret = mod_find_symname(mod, name)) != 0)
2071                                 break;
2072         }
2073         return ret;
2074 }
2075 #endif /* CONFIG_KALLSYMS */
2076
2077 /* Called by the /proc file system to return a list of modules. */
2078 static void *m_start(struct seq_file *m, loff_t *pos)
2079 {
2080         struct list_head *i;
2081         loff_t n = 0;
2082
2083         mutex_lock(&module_mutex);
2084         list_for_each(i, &modules) {
2085                 if (n++ == *pos)
2086                         break;
2087         }
2088         if (i == &modules)
2089                 return NULL;
2090         return i;
2091 }
2092
2093 static void *m_next(struct seq_file *m, void *p, loff_t *pos)
2094 {
2095         struct list_head *i = p;
2096         (*pos)++;
2097         if (i->next == &modules)
2098                 return NULL;
2099         return i->next;
2100 }
2101
2102 static void m_stop(struct seq_file *m, void *p)
2103 {
2104         mutex_unlock(&module_mutex);
2105 }
2106
2107 static int m_show(struct seq_file *m, void *p)
2108 {
2109         struct module *mod = list_entry(p, struct module, list);
2110         seq_printf(m, "%s %lu",
2111                    mod->name, mod->init_size + mod->core_size);
2112         print_unload_info(m, mod);
2113
2114         /* Informative for users. */
2115         seq_printf(m, " %s",
2116                    mod->state == MODULE_STATE_GOING ? "Unloading":
2117                    mod->state == MODULE_STATE_COMING ? "Loading":
2118                    "Live");
2119         /* Used by oprofile and other similar tools. */
2120         seq_printf(m, " 0x%p", mod->module_core);
2121
2122         seq_printf(m, "\n");
2123         return 0;
2124 }
2125
2126 /* Format: modulename size refcount deps address
2127
2128    Where refcount is a number or -, and deps is a comma-separated list
2129    of depends or -.
2130 */
2131 struct seq_operations modules_op = {
2132         .start  = m_start,
2133         .next   = m_next,
2134         .stop   = m_stop,
2135         .show   = m_show
2136 };
2137
2138 /* Given an address, look for it in the module exception tables. */
2139 const struct exception_table_entry *search_module_extables(unsigned long addr)
2140 {
2141         unsigned long flags;
2142         const struct exception_table_entry *e = NULL;
2143         struct module *mod;
2144
2145         spin_lock_irqsave(&modlist_lock, flags);
2146         list_for_each_entry(mod, &modules, list) {
2147                 if (mod->num_exentries == 0)
2148                         continue;
2149                                 
2150                 e = search_extable(mod->extable,
2151                                    mod->extable + mod->num_exentries - 1,
2152                                    addr);
2153                 if (e)
2154                         break;
2155         }
2156         spin_unlock_irqrestore(&modlist_lock, flags);
2157
2158         /* Now, if we found one, we are running inside it now, hence
2159            we cannot unload the module, hence no refcnt needed. */
2160         return e;
2161 }
2162
2163 /* Is this a valid kernel address?  We don't grab the lock: we are oopsing. */
2164 struct module *__module_text_address(unsigned long addr)
2165 {
2166         struct module *mod;
2167
2168         list_for_each_entry(mod, &modules, list)
2169                 if (within(addr, mod->module_init, mod->init_text_size)
2170                     || within(addr, mod->module_core, mod->core_text_size))
2171                         return mod;
2172         return NULL;
2173 }
2174
2175 struct module *module_text_address(unsigned long addr)
2176 {
2177         struct module *mod;
2178         unsigned long flags;
2179
2180         spin_lock_irqsave(&modlist_lock, flags);
2181         mod = __module_text_address(addr);
2182         spin_unlock_irqrestore(&modlist_lock, flags);
2183
2184         return mod;
2185 }
2186
2187 /* Don't grab lock, we're oopsing. */
2188 void print_modules(void)
2189 {
2190         struct module *mod;
2191
2192         printk("Modules linked in:");
2193         list_for_each_entry(mod, &modules, list)
2194                 printk(" %s", mod->name);
2195         printk("\n");
2196 }
2197
2198 void module_add_driver(struct module *mod, struct device_driver *drv)
2199 {
2200         if (!mod || !drv)
2201                 return;
2202
2203         /* Don't check return code; this call is idempotent */
2204         sysfs_create_link(&drv->kobj, &mod->mkobj.kobj, "module");
2205 }
2206 EXPORT_SYMBOL(module_add_driver);
2207
2208 void module_remove_driver(struct device_driver *drv)
2209 {
2210         if (!drv)
2211                 return;
2212         sysfs_remove_link(&drv->kobj, "module");
2213 }
2214 EXPORT_SYMBOL(module_remove_driver);
2215
2216 #ifdef CONFIG_MODVERSIONS
2217 /* Generate the signature for struct module here, too, for modversions. */
2218 void struct_module(struct module *mod) { return; }
2219 EXPORT_SYMBOL(struct_module);
2220 #endif