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