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