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