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