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