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