linux/arch/x86/mm/fault.c
<<
>>
Prefs
   1// SPDX-License-Identifier: GPL-2.0
   2/*
   3 *  Copyright (C) 1995  Linus Torvalds
   4 *  Copyright (C) 2001, 2002 Andi Kleen, SuSE Labs.
   5 *  Copyright (C) 2008-2009, Red Hat Inc., Ingo Molnar
   6 */
   7#include <linux/sched.h>                /* test_thread_flag(), ...      */
   8#include <linux/sched/task_stack.h>     /* task_stack_*(), ...          */
   9#include <linux/kdebug.h>               /* oops_begin/end, ...          */
  10#include <linux/extable.h>              /* search_exception_tables      */
  11#include <linux/memblock.h>             /* max_low_pfn                  */
  12#include <linux/kprobes.h>              /* NOKPROBE_SYMBOL, ...         */
  13#include <linux/mmiotrace.h>            /* kmmio_handler, ...           */
  14#include <linux/perf_event.h>           /* perf_sw_event                */
  15#include <linux/hugetlb.h>              /* hstate_index_to_shift        */
  16#include <linux/prefetch.h>             /* prefetchw                    */
  17#include <linux/context_tracking.h>     /* exception_enter(), ...       */
  18#include <linux/uaccess.h>              /* faulthandler_disabled()      */
  19#include <linux/efi.h>                  /* efi_recover_from_page_fault()*/
  20#include <linux/mm_types.h>
  21
  22#include <asm/cpufeature.h>             /* boot_cpu_has, ...            */
  23#include <asm/traps.h>                  /* dotraplinkage, ...           */
  24#include <asm/pgalloc.h>                /* pgd_*(), ...                 */
  25#include <asm/fixmap.h>                 /* VSYSCALL_ADDR                */
  26#include <asm/vsyscall.h>               /* emulate_vsyscall             */
  27#include <asm/vm86.h>                   /* struct vm86                  */
  28#include <asm/mmu_context.h>            /* vma_pkey()                   */
  29#include <asm/efi.h>                    /* efi_recover_from_page_fault()*/
  30#include <asm/desc.h>                   /* store_idt(), ...             */
  31#include <asm/cpu_entry_area.h>         /* exception stack              */
  32#include <asm/kvm_para.h>               /* kvm_handle_async_pf          */
  33#include <asm/vdso.h>                   /* fixup_vdso_exception()       */
  34
  35#define CREATE_TRACE_POINTS
  36#include <asm/trace/exceptions.h>
  37
  38/*
  39 * Returns 0 if mmiotrace is disabled, or if the fault is not
  40 * handled by mmiotrace:
  41 */
  42static nokprobe_inline int
  43kmmio_fault(struct pt_regs *regs, unsigned long addr)
  44{
  45        if (unlikely(is_kmmio_active()))
  46                if (kmmio_handler(regs, addr) == 1)
  47                        return -1;
  48        return 0;
  49}
  50
  51static nokprobe_inline int kprobes_fault(struct pt_regs *regs)
  52{
  53        int ret = 0;
  54
  55        /* kprobe_running() needs smp_processor_id() */
  56        if (kprobes_built_in() && !user_mode(regs)) {
  57                preempt_disable();
  58                if (kprobe_running() && kprobe_fault_handler(regs, 14))
  59                        ret = 1;
  60                preempt_enable();
  61        }
  62
  63        return ret;
  64}
  65
  66/*
  67 * Prefetch quirks:
  68 *
  69 * 32-bit mode:
  70 *
  71 *   Sometimes AMD Athlon/Opteron CPUs report invalid exceptions on prefetch.
  72 *   Check that here and ignore it.
  73 *
  74 * 64-bit mode:
  75 *
  76 *   Sometimes the CPU reports invalid exceptions on prefetch.
  77 *   Check that here and ignore it.
  78 *
  79 * Opcode checker based on code by Richard Brunner.
  80 */
  81static inline int
  82check_prefetch_opcode(struct pt_regs *regs, unsigned char *instr,
  83                      unsigned char opcode, int *prefetch)
  84{
  85        unsigned char instr_hi = opcode & 0xf0;
  86        unsigned char instr_lo = opcode & 0x0f;
  87
  88        switch (instr_hi) {
  89        case 0x20:
  90        case 0x30:
  91                /*
  92                 * Values 0x26,0x2E,0x36,0x3E are valid x86 prefixes.
  93                 * In X86_64 long mode, the CPU will signal invalid
  94                 * opcode if some of these prefixes are present so
  95                 * X86_64 will never get here anyway
  96                 */
  97                return ((instr_lo & 7) == 0x6);
  98#ifdef CONFIG_X86_64
  99        case 0x40:
 100                /*
 101                 * In AMD64 long mode 0x40..0x4F are valid REX prefixes
 102                 * Need to figure out under what instruction mode the
 103                 * instruction was issued. Could check the LDT for lm,
 104                 * but for now it's good enough to assume that long
 105                 * mode only uses well known segments or kernel.
 106                 */
 107                return (!user_mode(regs) || user_64bit_mode(regs));
 108#endif
 109        case 0x60:
 110                /* 0x64 thru 0x67 are valid prefixes in all modes. */
 111                return (instr_lo & 0xC) == 0x4;
 112        case 0xF0:
 113                /* 0xF0, 0xF2, 0xF3 are valid prefixes in all modes. */
 114                return !instr_lo || (instr_lo>>1) == 1;
 115        case 0x00:
 116                /* Prefetch instruction is 0x0F0D or 0x0F18 */
 117                if (probe_kernel_address(instr, opcode))
 118                        return 0;
 119
 120                *prefetch = (instr_lo == 0xF) &&
 121                        (opcode == 0x0D || opcode == 0x18);
 122                return 0;
 123        default:
 124                return 0;
 125        }
 126}
 127
 128static int
 129is_prefetch(struct pt_regs *regs, unsigned long error_code, unsigned long addr)
 130{
 131        unsigned char *max_instr;
 132        unsigned char *instr;
 133        int prefetch = 0;
 134
 135        /*
 136         * If it was a exec (instruction fetch) fault on NX page, then
 137         * do not ignore the fault:
 138         */
 139        if (error_code & X86_PF_INSTR)
 140                return 0;
 141
 142        instr = (void *)convert_ip_to_linear(current, regs);
 143        max_instr = instr + 15;
 144
 145        if (user_mode(regs) && instr >= (unsigned char *)TASK_SIZE_MAX)
 146                return 0;
 147
 148        while (instr < max_instr) {
 149                unsigned char opcode;
 150
 151                if (probe_kernel_address(instr, opcode))
 152                        break;
 153
 154                instr++;
 155
 156                if (!check_prefetch_opcode(regs, instr, opcode, &prefetch))
 157                        break;
 158        }
 159        return prefetch;
 160}
 161
 162DEFINE_SPINLOCK(pgd_lock);
 163LIST_HEAD(pgd_list);
 164
 165#ifdef CONFIG_X86_32
 166static inline pmd_t *vmalloc_sync_one(pgd_t *pgd, unsigned long address)
 167{
 168        unsigned index = pgd_index(address);
 169        pgd_t *pgd_k;
 170        p4d_t *p4d, *p4d_k;
 171        pud_t *pud, *pud_k;
 172        pmd_t *pmd, *pmd_k;
 173
 174        pgd += index;
 175        pgd_k = init_mm.pgd + index;
 176
 177        if (!pgd_present(*pgd_k))
 178                return NULL;
 179
 180        /*
 181         * set_pgd(pgd, *pgd_k); here would be useless on PAE
 182         * and redundant with the set_pmd() on non-PAE. As would
 183         * set_p4d/set_pud.
 184         */
 185        p4d = p4d_offset(pgd, address);
 186        p4d_k = p4d_offset(pgd_k, address);
 187        if (!p4d_present(*p4d_k))
 188                return NULL;
 189
 190        pud = pud_offset(p4d, address);
 191        pud_k = pud_offset(p4d_k, address);
 192        if (!pud_present(*pud_k))
 193                return NULL;
 194
 195        pmd = pmd_offset(pud, address);
 196        pmd_k = pmd_offset(pud_k, address);
 197        if (!pmd_present(*pmd_k))
 198                return NULL;
 199
 200        if (!pmd_present(*pmd))
 201                set_pmd(pmd, *pmd_k);
 202        else
 203                BUG_ON(pmd_pfn(*pmd) != pmd_pfn(*pmd_k));
 204
 205        return pmd_k;
 206}
 207
 208static void vmalloc_sync(void)
 209{
 210        unsigned long address;
 211
 212        if (SHARED_KERNEL_PMD)
 213                return;
 214
 215        for (address = VMALLOC_START & PMD_MASK;
 216             address >= TASK_SIZE_MAX && address < FIXADDR_TOP;
 217             address += PMD_SIZE) {
 218                struct page *page;
 219
 220                spin_lock(&pgd_lock);
 221                list_for_each_entry(page, &pgd_list, lru) {
 222                        spinlock_t *pgt_lock;
 223                        pmd_t *ret;
 224
 225                        /* the pgt_lock only for Xen */
 226                        pgt_lock = &pgd_page_get_mm(page)->page_table_lock;
 227
 228                        spin_lock(pgt_lock);
 229                        ret = vmalloc_sync_one(page_address(page), address);
 230                        spin_unlock(pgt_lock);
 231
 232                        if (!ret)
 233                                break;
 234                }
 235                spin_unlock(&pgd_lock);
 236        }
 237}
 238
 239void vmalloc_sync_mappings(void)
 240{
 241        vmalloc_sync();
 242}
 243
 244void vmalloc_sync_unmappings(void)
 245{
 246        vmalloc_sync();
 247}
 248
 249/*
 250 * 32-bit:
 251 *
 252 *   Handle a fault on the vmalloc or module mapping area
 253 */
 254static noinline int vmalloc_fault(unsigned long address)
 255{
 256        unsigned long pgd_paddr;
 257        pmd_t *pmd_k;
 258        pte_t *pte_k;
 259
 260        /* Make sure we are in vmalloc area: */
 261        if (!(address >= VMALLOC_START && address < VMALLOC_END))
 262                return -1;
 263
 264        WARN_ON_ONCE(in_nmi());
 265
 266        /*
 267         * Synchronize this task's top level page-table
 268         * with the 'reference' page table.
 269         *
 270         * Do _not_ use "current" here. We might be inside
 271         * an interrupt in the middle of a task switch..
 272         */
 273        pgd_paddr = read_cr3_pa();
 274        pmd_k = vmalloc_sync_one(__va(pgd_paddr), address);
 275        if (!pmd_k)
 276                return -1;
 277
 278        if (pmd_large(*pmd_k))
 279                return 0;
 280
 281        pte_k = pte_offset_kernel(pmd_k, address);
 282        if (!pte_present(*pte_k))
 283                return -1;
 284
 285        return 0;
 286}
 287NOKPROBE_SYMBOL(vmalloc_fault);
 288
 289/*
 290 * Did it hit the DOS screen memory VA from vm86 mode?
 291 */
 292static inline void
 293check_v8086_mode(struct pt_regs *regs, unsigned long address,
 294                 struct task_struct *tsk)
 295{
 296#ifdef CONFIG_VM86
 297        unsigned long bit;
 298
 299        if (!v8086_mode(regs) || !tsk->thread.vm86)
 300                return;
 301
 302        bit = (address - 0xA0000) >> PAGE_SHIFT;
 303        if (bit < 32)
 304                tsk->thread.vm86->screen_bitmap |= 1 << bit;
 305#endif
 306}
 307
 308static bool low_pfn(unsigned long pfn)
 309{
 310        return pfn < max_low_pfn;
 311}
 312
 313static void dump_pagetable(unsigned long address)
 314{
 315        pgd_t *base = __va(read_cr3_pa());
 316        pgd_t *pgd = &base[pgd_index(address)];
 317        p4d_t *p4d;
 318        pud_t *pud;
 319        pmd_t *pmd;
 320        pte_t *pte;
 321
 322#ifdef CONFIG_X86_PAE
 323        pr_info("*pdpt = %016Lx ", pgd_val(*pgd));
 324        if (!low_pfn(pgd_val(*pgd) >> PAGE_SHIFT) || !pgd_present(*pgd))
 325                goto out;
 326#define pr_pde pr_cont
 327#else
 328#define pr_pde pr_info
 329#endif
 330        p4d = p4d_offset(pgd, address);
 331        pud = pud_offset(p4d, address);
 332        pmd = pmd_offset(pud, address);
 333        pr_pde("*pde = %0*Lx ", sizeof(*pmd) * 2, (u64)pmd_val(*pmd));
 334#undef pr_pde
 335
 336        /*
 337         * We must not directly access the pte in the highpte
 338         * case if the page table is located in highmem.
 339         * And let's rather not kmap-atomic the pte, just in case
 340         * it's allocated already:
 341         */
 342        if (!low_pfn(pmd_pfn(*pmd)) || !pmd_present(*pmd) || pmd_large(*pmd))
 343                goto out;
 344
 345        pte = pte_offset_kernel(pmd, address);
 346        pr_cont("*pte = %0*Lx ", sizeof(*pte) * 2, (u64)pte_val(*pte));
 347out:
 348        pr_cont("\n");
 349}
 350
 351#else /* CONFIG_X86_64: */
 352
 353void vmalloc_sync_mappings(void)
 354{
 355        /*
 356         * 64-bit mappings might allocate new p4d/pud pages
 357         * that need to be propagated to all tasks' PGDs.
 358         */
 359        sync_global_pgds(VMALLOC_START & PGDIR_MASK, VMALLOC_END);
 360}
 361
 362void vmalloc_sync_unmappings(void)
 363{
 364        /*
 365         * Unmappings never allocate or free p4d/pud pages.
 366         * No work is required here.
 367         */
 368}
 369
 370/*
 371 * 64-bit:
 372 *
 373 *   Handle a fault on the vmalloc area
 374 */
 375static noinline int vmalloc_fault(unsigned long address)
 376{
 377        pgd_t *pgd, *pgd_k;
 378        p4d_t *p4d, *p4d_k;
 379        pud_t *pud;
 380        pmd_t *pmd;
 381        pte_t *pte;
 382
 383        /* Make sure we are in vmalloc area: */
 384        if (!(address >= VMALLOC_START && address < VMALLOC_END))
 385                return -1;
 386
 387        WARN_ON_ONCE(in_nmi());
 388
 389        /*
 390         * Copy kernel mappings over when needed. This can also
 391         * happen within a race in page table update. In the later
 392         * case just flush:
 393         */
 394        pgd = (pgd_t *)__va(read_cr3_pa()) + pgd_index(address);
 395        pgd_k = pgd_offset_k(address);
 396        if (pgd_none(*pgd_k))
 397                return -1;
 398
 399        if (pgtable_l5_enabled()) {
 400                if (pgd_none(*pgd)) {
 401                        set_pgd(pgd, *pgd_k);
 402                        arch_flush_lazy_mmu_mode();
 403                } else {
 404                        BUG_ON(pgd_page_vaddr(*pgd) != pgd_page_vaddr(*pgd_k));
 405                }
 406        }
 407
 408        /* With 4-level paging, copying happens on the p4d level. */
 409        p4d = p4d_offset(pgd, address);
 410        p4d_k = p4d_offset(pgd_k, address);
 411        if (p4d_none(*p4d_k))
 412                return -1;
 413
 414        if (p4d_none(*p4d) && !pgtable_l5_enabled()) {
 415                set_p4d(p4d, *p4d_k);
 416                arch_flush_lazy_mmu_mode();
 417        } else {
 418                BUG_ON(p4d_pfn(*p4d) != p4d_pfn(*p4d_k));
 419        }
 420
 421        BUILD_BUG_ON(CONFIG_PGTABLE_LEVELS < 4);
 422
 423        pud = pud_offset(p4d, address);
 424        if (pud_none(*pud))
 425                return -1;
 426
 427        if (pud_large(*pud))
 428                return 0;
 429
 430        pmd = pmd_offset(pud, address);
 431        if (pmd_none(*pmd))
 432                return -1;
 433
 434        if (pmd_large(*pmd))
 435                return 0;
 436
 437        pte = pte_offset_kernel(pmd, address);
 438        if (!pte_present(*pte))
 439                return -1;
 440
 441        return 0;
 442}
 443NOKPROBE_SYMBOL(vmalloc_fault);
 444
 445#ifdef CONFIG_CPU_SUP_AMD
 446static const char errata93_warning[] =
 447KERN_ERR 
 448"******* Your BIOS seems to not contain a fix for K8 errata #93\n"
 449"******* Working around it, but it may cause SEGVs or burn power.\n"
 450"******* Please consider a BIOS update.\n"
 451"******* Disabling USB legacy in the BIOS may also help.\n";
 452#endif
 453
 454/*
 455 * No vm86 mode in 64-bit mode:
 456 */
 457static inline void
 458check_v8086_mode(struct pt_regs *regs, unsigned long address,
 459                 struct task_struct *tsk)
 460{
 461}
 462
 463static int bad_address(void *p)
 464{
 465        unsigned long dummy;
 466
 467        return probe_kernel_address((unsigned long *)p, dummy);
 468}
 469
 470static void dump_pagetable(unsigned long address)
 471{
 472        pgd_t *base = __va(read_cr3_pa());
 473        pgd_t *pgd = base + pgd_index(address);
 474        p4d_t *p4d;
 475        pud_t *pud;
 476        pmd_t *pmd;
 477        pte_t *pte;
 478
 479        if (bad_address(pgd))
 480                goto bad;
 481
 482        pr_info("PGD %lx ", pgd_val(*pgd));
 483
 484        if (!pgd_present(*pgd))
 485                goto out;
 486
 487        p4d = p4d_offset(pgd, address);
 488        if (bad_address(p4d))
 489                goto bad;
 490
 491        pr_cont("P4D %lx ", p4d_val(*p4d));
 492        if (!p4d_present(*p4d) || p4d_large(*p4d))
 493                goto out;
 494
 495        pud = pud_offset(p4d, address);
 496        if (bad_address(pud))
 497                goto bad;
 498
 499        pr_cont("PUD %lx ", pud_val(*pud));
 500        if (!pud_present(*pud) || pud_large(*pud))
 501                goto out;
 502
 503        pmd = pmd_offset(pud, address);
 504        if (bad_address(pmd))
 505                goto bad;
 506
 507        pr_cont("PMD %lx ", pmd_val(*pmd));
 508        if (!pmd_present(*pmd) || pmd_large(*pmd))
 509                goto out;
 510
 511        pte = pte_offset_kernel(pmd, address);
 512        if (bad_address(pte))
 513                goto bad;
 514
 515        pr_cont("PTE %lx", pte_val(*pte));
 516out:
 517        pr_cont("\n");
 518        return;
 519bad:
 520        pr_info("BAD\n");
 521}
 522
 523#endif /* CONFIG_X86_64 */
 524
 525/*
 526 * Workaround for K8 erratum #93 & buggy BIOS.
 527 *
 528 * BIOS SMM functions are required to use a specific workaround
 529 * to avoid corruption of the 64bit RIP register on C stepping K8.
 530 *
 531 * A lot of BIOS that didn't get tested properly miss this.
 532 *
 533 * The OS sees this as a page fault with the upper 32bits of RIP cleared.
 534 * Try to work around it here.
 535 *
 536 * Note we only handle faults in kernel here.
 537 * Does nothing on 32-bit.
 538 */
 539static int is_errata93(struct pt_regs *regs, unsigned long address)
 540{
 541#if defined(CONFIG_X86_64) && defined(CONFIG_CPU_SUP_AMD)
 542        if (boot_cpu_data.x86_vendor != X86_VENDOR_AMD
 543            || boot_cpu_data.x86 != 0xf)
 544                return 0;
 545
 546        if (address != regs->ip)
 547                return 0;
 548
 549        if ((address >> 32) != 0)
 550                return 0;
 551
 552        address |= 0xffffffffUL << 32;
 553        if ((address >= (u64)_stext && address <= (u64)_etext) ||
 554            (address >= MODULES_VADDR && address <= MODULES_END)) {
 555                printk_once(errata93_warning);
 556                regs->ip = address;
 557                return 1;
 558        }
 559#endif
 560        return 0;
 561}
 562
 563/*
 564 * Work around K8 erratum #100 K8 in compat mode occasionally jumps
 565 * to illegal addresses >4GB.
 566 *
 567 * We catch this in the page fault handler because these addresses
 568 * are not reachable. Just detect this case and return.  Any code
 569 * segment in LDT is compatibility mode.
 570 */
 571static int is_errata100(struct pt_regs *regs, unsigned long address)
 572{
 573#ifdef CONFIG_X86_64
 574        if ((regs->cs == __USER32_CS || (regs->cs & (1<<2))) && (address >> 32))
 575                return 1;
 576#endif
 577        return 0;
 578}
 579
 580static int is_f00f_bug(struct pt_regs *regs, unsigned long address)
 581{
 582#ifdef CONFIG_X86_F00F_BUG
 583        unsigned long nr;
 584
 585        /*
 586         * Pentium F0 0F C7 C8 bug workaround:
 587         */
 588        if (boot_cpu_has_bug(X86_BUG_F00F)) {
 589                nr = (address - idt_descr.address) >> 3;
 590
 591                if (nr == 6) {
 592                        do_invalid_op(regs, 0);
 593                        return 1;
 594                }
 595        }
 596#endif
 597        return 0;
 598}
 599
 600static void
 601show_fault_oops(struct pt_regs *regs, unsigned long error_code,
 602                unsigned long address)
 603{
 604        if (!oops_may_print())
 605                return;
 606
 607        if (error_code & X86_PF_INSTR) {
 608                unsigned int level;
 609                pgd_t *pgd;
 610                pte_t *pte;
 611
 612                pgd = __va(read_cr3_pa());
 613                pgd += pgd_index(address);
 614
 615                pte = lookup_address_in_pgd(pgd, address, &level);
 616
 617                if (pte && pte_present(*pte) && !pte_exec(*pte))
 618                        pr_crit("kernel tried to execute NX-protected page - exploit attempt? (uid: %d)\n",
 619                                from_kuid(&init_user_ns, current_uid()));
 620                if (pte && pte_present(*pte) && pte_exec(*pte) &&
 621                                (pgd_flags(*pgd) & _PAGE_USER) &&
 622                                (__read_cr4() & X86_CR4_SMEP))
 623                        pr_crit("unable to execute userspace code (SMEP?) (uid: %d)\n",
 624                                from_kuid(&init_user_ns, current_uid()));
 625        }
 626
 627        pr_alert("BUG: unable to handle kernel %s at %px\n",
 628                 address < PAGE_SIZE ? "NULL pointer dereference" : "paging request",
 629                 (void *)address);
 630
 631        dump_pagetable(address);
 632}
 633
 634static noinline void
 635pgtable_bad(struct pt_regs *regs, unsigned long error_code,
 636            unsigned long address)
 637{
 638        struct task_struct *tsk;
 639        unsigned long flags;
 640        int sig;
 641
 642        flags = oops_begin();
 643        tsk = current;
 644        sig = SIGKILL;
 645
 646        printk(KERN_ALERT "%s: Corrupted page table at address %lx\n",
 647               tsk->comm, address);
 648        dump_pagetable(address);
 649
 650        tsk->thread.cr2         = address;
 651        tsk->thread.trap_nr     = X86_TRAP_PF;
 652        tsk->thread.error_code  = error_code;
 653
 654        if (__die("Bad pagetable", regs, error_code))
 655                sig = 0;
 656
 657        oops_end(flags, regs, sig);
 658}
 659
 660static void sanitize_error_code(unsigned long address,
 661                                unsigned long *error_code)
 662{
 663        /*
 664         * To avoid leaking information about the kernel page
 665         * table layout, pretend that user-mode accesses to
 666         * kernel addresses are always protection faults.
 667         */
 668        if (address >= TASK_SIZE_MAX)
 669                *error_code |= X86_PF_PROT;
 670}
 671
 672static void set_signal_archinfo(unsigned long address,
 673                                unsigned long error_code)
 674{
 675        struct task_struct *tsk = current;
 676
 677        tsk->thread.trap_nr = X86_TRAP_PF;
 678        tsk->thread.error_code = error_code | X86_PF_USER;
 679        tsk->thread.cr2 = address;
 680}
 681
 682static noinline void
 683no_context(struct pt_regs *regs, unsigned long error_code,
 684           unsigned long address, int signal, int si_code)
 685{
 686        struct task_struct *tsk = current;
 687        unsigned long flags;
 688        int sig;
 689
 690        /* Are we prepared to handle this kernel fault? */
 691        if (fixup_exception(regs, X86_TRAP_PF)) {
 692                /*
 693                 * Any interrupt that takes a fault gets the fixup. This makes
 694                 * the below recursive fault logic only apply to a faults from
 695                 * task context.
 696                 */
 697                if (in_interrupt())
 698                        return;
 699
 700                /*
 701                 * Per the above we're !in_interrupt(), aka. task context.
 702                 *
 703                 * In this case we need to make sure we're not recursively
 704                 * faulting through the emulate_vsyscall() logic.
 705                 */
 706                if (current->thread.sig_on_uaccess_err && signal) {
 707                        sanitize_error_code(address, &error_code);
 708
 709                        set_signal_archinfo(address, error_code);
 710
 711                        /* XXX: hwpoison faults will set the wrong code. */
 712                        force_sig_fault(signal, si_code, (void __user *)address,
 713                                        tsk);
 714                }
 715
 716                /*
 717                 * Barring that, we can do the fixup and be happy.
 718                 */
 719                return;
 720        }
 721
 722#ifdef CONFIG_VMAP_STACK
 723        /*
 724         * Stack overflow?  During boot, we can fault near the initial
 725         * stack in the direct map, but that's not an overflow -- check
 726         * that we're in vmalloc space to avoid this.
 727         */
 728        if (is_vmalloc_addr((void *)address) &&
 729            (((unsigned long)tsk->stack - 1 - address < PAGE_SIZE) ||
 730             address - ((unsigned long)tsk->stack + THREAD_SIZE) < PAGE_SIZE)) {
 731                unsigned long stack = __this_cpu_ist_top_va(DF) - sizeof(void *);
 732                /*
 733                 * We're likely to be running with very little stack space
 734                 * left.  It's plausible that we'd hit this condition but
 735                 * double-fault even before we get this far, in which case
 736                 * we're fine: the double-fault handler will deal with it.
 737                 *
 738                 * We don't want to make it all the way into the oops code
 739                 * and then double-fault, though, because we're likely to
 740                 * break the console driver and lose most of the stack dump.
 741                 */
 742                asm volatile ("movq %[stack], %%rsp\n\t"
 743                              "call handle_stack_overflow\n\t"
 744                              "1: jmp 1b"
 745                              : ASM_CALL_CONSTRAINT
 746                              : "D" ("kernel stack overflow (page fault)"),
 747                                "S" (regs), "d" (address),
 748                                [stack] "rm" (stack));
 749                unreachable();
 750        }
 751#endif
 752
 753        /*
 754         * 32-bit:
 755         *
 756         *   Valid to do another page fault here, because if this fault
 757         *   had been triggered by is_prefetch fixup_exception would have
 758         *   handled it.
 759         *
 760         * 64-bit:
 761         *
 762         *   Hall of shame of CPU/BIOS bugs.
 763         */
 764        if (is_prefetch(regs, error_code, address))
 765                return;
 766
 767        if (is_errata93(regs, address))
 768                return;
 769
 770        /*
 771         * Buggy firmware could access regions which might page fault, try to
 772         * recover from such faults.
 773         */
 774        if (IS_ENABLED(CONFIG_EFI))
 775                efi_recover_from_page_fault(address);
 776
 777        /*
 778         * Oops. The kernel tried to access some bad page. We'll have to
 779         * terminate things with extreme prejudice:
 780         */
 781        flags = oops_begin();
 782
 783        show_fault_oops(regs, error_code, address);
 784
 785        if (task_stack_end_corrupted(tsk))
 786                printk(KERN_EMERG "Thread overran stack, or stack corrupted\n");
 787
 788        tsk->thread.cr2         = address;
 789        tsk->thread.trap_nr     = X86_TRAP_PF;
 790        tsk->thread.error_code  = error_code;
 791
 792        sig = SIGKILL;
 793        if (__die("Oops", regs, error_code))
 794                sig = 0;
 795
 796        /* Executive summary in case the body of the oops scrolled away */
 797        printk(KERN_DEFAULT "CR2: %016lx\n", address);
 798
 799        oops_end(flags, regs, sig);
 800}
 801
 802/*
 803 * Print out info about fatal segfaults, if the show_unhandled_signals
 804 * sysctl is set:
 805 */
 806static inline void
 807show_signal_msg(struct pt_regs *regs, unsigned long error_code,
 808                unsigned long address, struct task_struct *tsk)
 809{
 810        const char *loglvl = task_pid_nr(tsk) > 1 ? KERN_INFO : KERN_EMERG;
 811
 812        if (!unhandled_signal(tsk, SIGSEGV))
 813                return;
 814
 815        if (!printk_ratelimit())
 816                return;
 817
 818        printk("%s%s[%d]: segfault at %lx ip %px sp %px error %lx",
 819                loglvl, tsk->comm, task_pid_nr(tsk), address,
 820                (void *)regs->ip, (void *)regs->sp, error_code);
 821
 822        print_vma_addr(KERN_CONT " in ", regs->ip);
 823
 824        printk(KERN_CONT "\n");
 825
 826        show_opcodes(regs, loglvl);
 827}
 828
 829static void
 830__bad_area_nosemaphore(struct pt_regs *regs, unsigned long error_code,
 831                       unsigned long address, u32 pkey, int si_code)
 832{
 833        struct task_struct *tsk = current;
 834
 835        /* User mode accesses just cause a SIGSEGV */
 836        if (error_code & X86_PF_USER) {
 837                /*
 838                 * It's possible to have interrupts off here:
 839                 */
 840                local_irq_enable();
 841
 842                /*
 843                 * Valid to do another page fault here because this one came
 844                 * from user space:
 845                 */
 846                if (is_prefetch(regs, error_code, address))
 847                        return;
 848
 849                if (is_errata100(regs, address))
 850                        return;
 851
 852#ifdef CONFIG_X86_64
 853                /*
 854                 * Instruction fetch faults in the vsyscall page might need
 855                 * emulation.
 856                 */
 857                if (unlikely((error_code & X86_PF_INSTR) &&
 858                             ((address & ~0xfff) == VSYSCALL_ADDR))) {
 859                        if (emulate_vsyscall(regs, address))
 860                                return;
 861                }
 862#endif
 863
 864                sanitize_error_code(address, &error_code);
 865
 866                if (fixup_vdso_exception(regs, X86_TRAP_PF, error_code, address))
 867                        return;
 868
 869                if (likely(show_unhandled_signals))
 870                        show_signal_msg(regs, error_code, address, tsk);
 871
 872                set_signal_archinfo(address, error_code);
 873
 874                if (si_code == SEGV_PKUERR)
 875                        force_sig_pkuerr((void __user *)address, pkey);
 876
 877                force_sig_fault(SIGSEGV, si_code, (void __user *)address, tsk);
 878
 879                return;
 880        }
 881
 882        if (is_f00f_bug(regs, address))
 883                return;
 884
 885        no_context(regs, error_code, address, SIGSEGV, si_code);
 886}
 887
 888static noinline void
 889bad_area_nosemaphore(struct pt_regs *regs, unsigned long error_code,
 890                     unsigned long address)
 891{
 892        __bad_area_nosemaphore(regs, error_code, address, 0, SEGV_MAPERR);
 893}
 894
 895static void
 896__bad_area(struct pt_regs *regs, unsigned long error_code,
 897           unsigned long address, u32 pkey, int si_code)
 898{
 899        struct mm_struct *mm = current->mm;
 900        /*
 901         * Something tried to access memory that isn't in our memory map..
 902         * Fix it, but check if it's kernel or user first..
 903         */
 904        mmap_read_unlock(mm);
 905
 906        __bad_area_nosemaphore(regs, error_code, address, pkey, si_code);
 907}
 908
 909static noinline void
 910bad_area(struct pt_regs *regs, unsigned long error_code, unsigned long address)
 911{
 912        __bad_area(regs, error_code, address, 0, SEGV_MAPERR);
 913}
 914
 915static inline bool bad_area_access_from_pkeys(unsigned long error_code,
 916                struct vm_area_struct *vma)
 917{
 918        /* This code is always called on the current mm */
 919        bool foreign = false;
 920
 921        if (!cpu_feature_enabled(X86_FEATURE_OSPKE))
 922                return false;
 923        if (error_code & X86_PF_PK)
 924                return true;
 925        /* this checks permission keys on the VMA: */
 926        if (!arch_vma_access_permitted(vma, (error_code & X86_PF_WRITE),
 927                                       (error_code & X86_PF_INSTR), foreign))
 928                return true;
 929        return false;
 930}
 931
 932static noinline void
 933bad_area_access_error(struct pt_regs *regs, unsigned long error_code,
 934                      unsigned long address, struct vm_area_struct *vma)
 935{
 936        /*
 937         * This OSPKE check is not strictly necessary at runtime.
 938         * But, doing it this way allows compiler optimizations
 939         * if pkeys are compiled out.
 940         */
 941        if (bad_area_access_from_pkeys(error_code, vma)) {
 942                /*
 943                 * A protection key fault means that the PKRU value did not allow
 944                 * access to some PTE.  Userspace can figure out what PKRU was
 945                 * from the XSAVE state.  This function captures the pkey from
 946                 * the vma and passes it to userspace so userspace can discover
 947                 * which protection key was set on the PTE.
 948                 *
 949                 * If we get here, we know that the hardware signaled a X86_PF_PK
 950                 * fault and that there was a VMA once we got in the fault
 951                 * handler.  It does *not* guarantee that the VMA we find here
 952                 * was the one that we faulted on.
 953                 *
 954                 * 1. T1   : mprotect_key(foo, PAGE_SIZE, pkey=4);
 955                 * 2. T1   : set PKRU to deny access to pkey=4, touches page
 956                 * 3. T1   : faults...
 957                 * 4.    T2: mprotect_key(foo, PAGE_SIZE, pkey=5);
 958                 * 5. T1   : enters fault handler, takes mmap_lock, etc...
 959                 * 6. T1   : reaches here, sees vma_pkey(vma)=5, when we really
 960                 *           faulted on a pte with its pkey=4.
 961                 */
 962                u32 pkey = vma_pkey(vma);
 963
 964                __bad_area(regs, error_code, address, pkey, SEGV_PKUERR);
 965        } else {
 966                __bad_area(regs, error_code, address, 0, SEGV_ACCERR);
 967        }
 968}
 969
 970/* Handle faults in the kernel portion of the address space */
 971static void
 972do_sigbus(struct pt_regs *regs, unsigned long error_code, unsigned long address,
 973          vm_fault_t fault)
 974{
 975        struct task_struct *tsk = current;
 976
 977        /* Kernel mode? Handle exceptions or die: */
 978        if (!(error_code & X86_PF_USER)) {
 979                no_context(regs, error_code, address, SIGBUS, BUS_ADRERR);
 980                return;
 981        }
 982
 983        /* User-space => ok to do another page fault: */
 984        if (is_prefetch(regs, error_code, address))
 985                return;
 986
 987        sanitize_error_code(address, &error_code);
 988
 989        if (fixup_vdso_exception(regs, X86_TRAP_PF, error_code, address))
 990                return;
 991
 992        set_signal_archinfo(address, error_code);
 993
 994#ifdef CONFIG_MEMORY_FAILURE
 995        if (fault & (VM_FAULT_HWPOISON|VM_FAULT_HWPOISON_LARGE)) {
 996                unsigned lsb = 0;
 997
 998                pr_err(
 999        "MCE: Killing %s:%d due to hardware memory corruption fault at %lx\n",
1000                        tsk->comm, tsk->pid, address);
1001                if (fault & VM_FAULT_HWPOISON_LARGE)
1002                        lsb = hstate_index_to_shift(VM_FAULT_GET_HINDEX(fault));
1003                if (fault & VM_FAULT_HWPOISON)
1004                        lsb = PAGE_SHIFT;
1005                force_sig_mceerr(BUS_MCEERR_AR, (void __user *)address, lsb, tsk);
1006                return;
1007        }
1008#endif
1009        force_sig_fault(SIGBUS, BUS_ADRERR, (void __user *)address, tsk);
1010}
1011
1012static noinline void
1013mm_fault_error(struct pt_regs *regs, unsigned long error_code,
1014               unsigned long address, vm_fault_t fault)
1015{
1016        if (fatal_signal_pending(current) && !(error_code & X86_PF_USER)) {
1017                no_context(regs, error_code, address, 0, 0);
1018                return;
1019        }
1020
1021        if (fault & VM_FAULT_OOM) {
1022                /* Kernel mode? Handle exceptions or die: */
1023                if (!(error_code & X86_PF_USER)) {
1024                        no_context(regs, error_code, address,
1025                                   SIGSEGV, SEGV_MAPERR);
1026                        return;
1027                }
1028
1029                /*
1030                 * We ran out of memory, call the OOM killer, and return the
1031                 * userspace (which will retry the fault, or kill us if we got
1032                 * oom-killed):
1033                 */
1034                pagefault_out_of_memory();
1035        } else {
1036                if (fault & (VM_FAULT_SIGBUS|VM_FAULT_HWPOISON|
1037                             VM_FAULT_HWPOISON_LARGE))
1038                        do_sigbus(regs, error_code, address, fault);
1039                else if (fault & VM_FAULT_SIGSEGV)
1040                        bad_area_nosemaphore(regs, error_code, address);
1041                else
1042                        BUG();
1043        }
1044}
1045
1046static int spurious_kernel_fault_check(unsigned long error_code, pte_t *pte)
1047{
1048        if ((error_code & X86_PF_WRITE) && !pte_write(*pte))
1049                return 0;
1050
1051        if ((error_code & X86_PF_INSTR) && !pte_exec(*pte))
1052                return 0;
1053        /*
1054         * Note: We do not do lazy flushing on protection key
1055         * changes, so no spurious fault will ever set X86_PF_PK.
1056         */
1057        if ((error_code & X86_PF_PK))
1058                return 1;
1059
1060        return 1;
1061}
1062
1063/*
1064 * Handle a spurious fault caused by a stale TLB entry.
1065 *
1066 * This allows us to lazily refresh the TLB when increasing the
1067 * permissions of a kernel page (RO -> RW or NX -> X).  Doing it
1068 * eagerly is very expensive since that implies doing a full
1069 * cross-processor TLB flush, even if no stale TLB entries exist
1070 * on other processors.
1071 *
1072 * Spurious faults may only occur if the TLB contains an entry with
1073 * fewer permission than the page table entry.  Non-present (P = 0)
1074 * and reserved bit (R = 1) faults are never spurious.
1075 *
1076 * There are no security implications to leaving a stale TLB when
1077 * increasing the permissions on a page.
1078 *
1079 * Returns non-zero if a spurious fault was handled, zero otherwise.
1080 *
1081 * See Intel Developer's Manual Vol 3 Section 4.10.4.3, bullet 3
1082 * (Optional Invalidation).
1083 */
1084static noinline int
1085spurious_kernel_fault(unsigned long error_code, unsigned long address)
1086{
1087        pgd_t *pgd;
1088        p4d_t *p4d;
1089        pud_t *pud;
1090        pmd_t *pmd;
1091        pte_t *pte;
1092        int ret;
1093
1094        /*
1095         * Only writes to RO or instruction fetches from NX may cause
1096         * spurious faults.
1097         *
1098         * These could be from user or supervisor accesses but the TLB
1099         * is only lazily flushed after a kernel mapping protection
1100         * change, so user accesses are not expected to cause spurious
1101         * faults.
1102         */
1103        if (error_code != (X86_PF_WRITE | X86_PF_PROT) &&
1104            error_code != (X86_PF_INSTR | X86_PF_PROT))
1105                return 0;
1106
1107        pgd = init_mm.pgd + pgd_index(address);
1108        if (!pgd_present(*pgd))
1109                return 0;
1110
1111        p4d = p4d_offset(pgd, address);
1112        if (!p4d_present(*p4d))
1113                return 0;
1114
1115        if (p4d_large(*p4d))
1116                return spurious_kernel_fault_check(error_code, (pte_t *) p4d);
1117
1118        pud = pud_offset(p4d, address);
1119        if (!pud_present(*pud))
1120                return 0;
1121
1122        if (pud_large(*pud))
1123                return spurious_kernel_fault_check(error_code, (pte_t *) pud);
1124
1125        pmd = pmd_offset(pud, address);
1126        if (!pmd_present(*pmd))
1127                return 0;
1128
1129        if (pmd_large(*pmd))
1130                return spurious_kernel_fault_check(error_code, (pte_t *) pmd);
1131
1132        pte = pte_offset_kernel(pmd, address);
1133        if (!pte_present(*pte))
1134                return 0;
1135
1136        ret = spurious_kernel_fault_check(error_code, pte);
1137        if (!ret)
1138                return 0;
1139
1140        /*
1141         * Make sure we have permissions in PMD.
1142         * If not, then there's a bug in the page tables:
1143         */
1144        ret = spurious_kernel_fault_check(error_code, (pte_t *) pmd);
1145        WARN_ONCE(!ret, "PMD has incorrect permission bits\n");
1146
1147        return ret;
1148}
1149NOKPROBE_SYMBOL(spurious_kernel_fault);
1150
1151int show_unhandled_signals = 1;
1152
1153static inline int
1154access_error(unsigned long error_code, struct vm_area_struct *vma)
1155{
1156        /* This is only called for the current mm, so: */
1157        bool foreign = false;
1158
1159        /*
1160         * Read or write was blocked by protection keys.  This is
1161         * always an unconditional error and can never result in
1162         * a follow-up action to resolve the fault, like a COW.
1163         */
1164        if (error_code & X86_PF_PK)
1165                return 1;
1166
1167        /*
1168         * SGX hardware blocked the access.  This usually happens
1169         * when the enclave memory contents have been destroyed, like
1170         * after a suspend/resume cycle. In any case, the kernel can't
1171         * fix the cause of the fault.  Handle the fault as an access
1172         * error even in cases where no actual access violation
1173         * occurred.  This allows userspace to rebuild the enclave in
1174         * response to the signal.
1175         */
1176        if (unlikely(error_code & X86_PF_SGX))
1177                return 1;
1178
1179        /*
1180         * Make sure to check the VMA so that we do not perform
1181         * faults just to hit a X86_PF_PK as soon as we fill in a
1182         * page.
1183         */
1184        if (!arch_vma_access_permitted(vma, (error_code & X86_PF_WRITE),
1185                                       (error_code & X86_PF_INSTR), foreign))
1186                return 1;
1187
1188        if (error_code & X86_PF_WRITE) {
1189                /* write, present and write, not present: */
1190                if (unlikely(!(vma->vm_flags & VM_WRITE)))
1191                        return 1;
1192                return 0;
1193        }
1194
1195        /* read, present: */
1196        if (unlikely(error_code & X86_PF_PROT))
1197                return 1;
1198
1199        /* read, not present: */
1200        if (unlikely(!(vma->vm_flags & (VM_READ | VM_EXEC | VM_WRITE))))
1201                return 1;
1202
1203        return 0;
1204}
1205
1206static int fault_in_kernel_space(unsigned long address)
1207{
1208        return address >= TASK_SIZE_MAX;
1209}
1210
1211static inline bool smap_violation(int error_code, struct pt_regs *regs)
1212{
1213        if (!IS_ENABLED(CONFIG_X86_SMAP))
1214                return false;
1215
1216        if (!static_cpu_has(X86_FEATURE_SMAP))
1217                return false;
1218
1219        if (error_code & X86_PF_USER)
1220                return false;
1221
1222        if (!user_mode(regs) && (regs->flags & X86_EFLAGS_AC))
1223                return false;
1224
1225        return true;
1226}
1227
1228/*
1229 * Called for all faults where 'address' is part of the kernel address
1230 * space.  Might get called for faults that originate from *code* that
1231 * ran in userspace or the kernel.
1232 */
1233static void
1234do_kern_addr_fault(struct pt_regs *regs, unsigned long hw_error_code,
1235                   unsigned long address)
1236{
1237        /*
1238         * We can fault-in kernel-space virtual memory on-demand. The
1239         * 'reference' page table is init_mm.pgd.
1240         *
1241         * NOTE! We MUST NOT take any locks for this case. We may
1242         * be in an interrupt or a critical region, and should
1243         * only copy the information from the master page table,
1244         * nothing more.
1245         *
1246         * Before doing this on-demand faulting, ensure that the
1247         * fault is not any of the following:
1248         * 1. A fault on a PTE with a reserved bit set.
1249         * 2. A fault caused by a user-mode access.  (Do not demand-
1250         *    fault kernel memory due to user-mode accesses).
1251         * 3. A fault caused by a page-level protection violation.
1252         *    (A demand fault would be on a non-present page which
1253         *     would have X86_PF_PROT==0).
1254         */
1255        if (!(hw_error_code & (X86_PF_RSVD | X86_PF_USER | X86_PF_PROT))) {
1256                if (vmalloc_fault(address) >= 0)
1257                        return;
1258        }
1259
1260        /* Was the fault spurious, caused by lazy TLB invalidation? */
1261        if (spurious_kernel_fault(hw_error_code, address))
1262                return;
1263
1264        /* kprobes don't want to hook the spurious faults: */
1265        if (kprobes_fault(regs))
1266                return;
1267
1268        /*
1269         * Note, despite being a "bad area", there are quite a few
1270         * acceptable reasons to get here, such as erratum fixups
1271         * and handling kernel code that can fault, like get_user().
1272         *
1273         * Don't take the mm semaphore here. If we fixup a prefetch
1274         * fault we could otherwise deadlock:
1275         */
1276        bad_area_nosemaphore(regs, hw_error_code, address);
1277}
1278NOKPROBE_SYMBOL(do_kern_addr_fault);
1279
1280/* Handle faults in the user portion of the address space */
1281static inline
1282void do_user_addr_fault(struct pt_regs *regs,
1283                        unsigned long hw_error_code,
1284                        unsigned long address)
1285{
1286        unsigned long sw_error_code;
1287        struct vm_area_struct *vma;
1288        struct task_struct *tsk;
1289        struct mm_struct *mm;
1290        vm_fault_t fault, major = 0;
1291        unsigned int flags = FAULT_FLAG_DEFAULT;
1292
1293        tsk = current;
1294        mm = tsk->mm;
1295
1296        /* kprobes don't want to hook the spurious faults: */
1297        if (unlikely(kprobes_fault(regs)))
1298                return;
1299
1300        if (unlikely(hw_error_code & X86_PF_RSVD))
1301                pgtable_bad(regs, hw_error_code, address);
1302
1303        if (unlikely(smap_violation(hw_error_code, regs))) {
1304                bad_area_nosemaphore(regs, hw_error_code, address);
1305                return;
1306        }
1307
1308        /*
1309         * If we're in an interrupt, have no user context or are running
1310         * in a region with pagefaults disabled then we must not take the fault
1311         */
1312        if (unlikely(faulthandler_disabled() || !mm)) {
1313                bad_area_nosemaphore(regs, hw_error_code, address);
1314                return;
1315        }
1316
1317        /*
1318         * hw_error_code is literally the "page fault error code" passed to
1319         * the kernel directly from the hardware.  But, we will shortly be
1320         * modifying it in software, so give it a new name.
1321         */
1322        sw_error_code = hw_error_code;
1323
1324        /*
1325         * It's safe to allow irq's after cr2 has been saved and the
1326         * vmalloc fault has been handled.
1327         *
1328         * User-mode registers count as a user access even for any
1329         * potential system fault or CPU buglet:
1330         */
1331        if (user_mode(regs)) {
1332                local_irq_enable();
1333                /*
1334                 * Up to this point, X86_PF_USER set in hw_error_code
1335                 * indicated a user-mode access.  But, after this,
1336                 * X86_PF_USER in sw_error_code will indicate either
1337                 * that, *or* an implicit kernel(supervisor)-mode access
1338                 * which originated from user mode.
1339                 */
1340                if (!(hw_error_code & X86_PF_USER)) {
1341                        /*
1342                         * The CPU was in user mode, but the CPU says
1343                         * the fault was not a user-mode access.
1344                         * Must be an implicit kernel-mode access,
1345                         * which we do not expect to happen in the
1346                         * user address space.
1347                         */
1348                        pr_warn_once("kernel-mode error from user-mode: %lx\n",
1349                                        hw_error_code);
1350
1351                        sw_error_code |= X86_PF_USER;
1352                }
1353                flags |= FAULT_FLAG_USER;
1354        } else {
1355                if (regs->flags & X86_EFLAGS_IF)
1356                        local_irq_enable();
1357        }
1358
1359        perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS, 1, regs, address);
1360
1361        if (sw_error_code & X86_PF_WRITE)
1362                flags |= FAULT_FLAG_WRITE;
1363        if (sw_error_code & X86_PF_INSTR)
1364                flags |= FAULT_FLAG_INSTRUCTION;
1365
1366        /*
1367         * Kernel-mode access to the user address space should only occur
1368         * on well-defined single instructions listed in the exception
1369         * tables.  But, an erroneous kernel fault occurring outside one of
1370         * those areas which also holds mmap_lock might deadlock attempting
1371         * to validate the fault against the address space.
1372         *
1373         * Only do the expensive exception table search when we might be at
1374         * risk of a deadlock.  This happens if we
1375         * 1. Failed to acquire mmap_lock, and
1376         * 2. The access did not originate in userspace.
1377         */
1378        if (unlikely(!mmap_read_trylock(mm))) {
1379                if (!user_mode(regs) && !search_exception_tables(regs->ip)) {
1380                        /*
1381                         * Fault from code in kernel from
1382                         * which we do not expect faults.
1383                         */
1384                        bad_area_nosemaphore(regs, sw_error_code, address);
1385                        return;
1386                }
1387retry:
1388                mmap_read_lock(mm);
1389        } else {
1390                /*
1391                 * The above down_read_trylock() might have succeeded in
1392                 * which case we'll have missed the might_sleep() from
1393                 * down_read():
1394                 */
1395                might_sleep();
1396        }
1397
1398        vma = find_vma(mm, address);
1399        if (unlikely(!vma)) {
1400                bad_area(regs, sw_error_code, address);
1401                return;
1402        }
1403        if (likely(vma->vm_start <= address))
1404                goto good_area;
1405        if (unlikely(!(vma->vm_flags & VM_GROWSDOWN))) {
1406                bad_area(regs, sw_error_code, address);
1407                return;
1408        }
1409        if (unlikely(expand_stack(vma, address))) {
1410                bad_area(regs, sw_error_code, address);
1411                return;
1412        }
1413
1414        /*
1415         * Ok, we have a good vm_area for this memory access, so
1416         * we can handle it..
1417         */
1418good_area:
1419        if (unlikely(access_error(sw_error_code, vma))) {
1420                bad_area_access_error(regs, sw_error_code, address, vma);
1421                return;
1422        }
1423
1424        /*
1425         * If for any reason at all we couldn't handle the fault,
1426         * make sure we exit gracefully rather than endlessly redo
1427         * the fault.  Since we never set FAULT_FLAG_RETRY_NOWAIT, if
1428         * we get VM_FAULT_RETRY back, the mmap_lock has been unlocked.
1429         *
1430         * Note that handle_userfault() may also release and reacquire mmap_lock
1431         * (and not return with VM_FAULT_RETRY), when returning to userland to
1432         * repeat the page fault later with a VM_FAULT_NOPAGE retval
1433         * (potentially after handling any pending signal during the return to
1434         * userland). The return to userland is identified whenever
1435         * FAULT_FLAG_USER|FAULT_FLAG_KILLABLE are both set in flags.
1436         */
1437        fault = handle_mm_fault(vma, address, flags);
1438        major |= fault & VM_FAULT_MAJOR;
1439
1440        /* Quick path to respond to signals */
1441        if (fault_signal_pending(fault, regs)) {
1442                if (!user_mode(regs))
1443                        no_context(regs, sw_error_code, address, SIGBUS,
1444                                   BUS_ADRERR);
1445                return;
1446        }
1447
1448        /*
1449         * If we need to retry the mmap_lock has already been released,
1450         * and if there is a fatal signal pending there is no guarantee
1451         * that we made any progress. Handle this case first.
1452         */
1453        if (unlikely((fault & VM_FAULT_RETRY) &&
1454                     (flags & FAULT_FLAG_ALLOW_RETRY))) {
1455                flags |= FAULT_FLAG_TRIED;
1456                goto retry;
1457        }
1458
1459        mmap_read_unlock(mm);
1460        if (unlikely(fault & VM_FAULT_ERROR)) {
1461                mm_fault_error(regs, sw_error_code, address, fault);
1462                return;
1463        }
1464
1465        /*
1466         * Major/minor page fault accounting. If any of the events
1467         * returned VM_FAULT_MAJOR, we account it as a major fault.
1468         */
1469        if (major) {
1470                tsk->maj_flt++;
1471                perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MAJ, 1, regs, address);
1472        } else {
1473                tsk->min_flt++;
1474                perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MIN, 1, regs, address);
1475        }
1476
1477        check_v8086_mode(regs, address, tsk);
1478}
1479NOKPROBE_SYMBOL(do_user_addr_fault);
1480
1481/*
1482 * This routine handles page faults.  It determines the address,
1483 * and the problem, and then passes it off to one of the appropriate
1484 * routines.
1485 */
1486static noinline void
1487__do_page_fault(struct pt_regs *regs, unsigned long hw_error_code,
1488                unsigned long address)
1489{
1490        prefetchw(&current->mm->mmap_sem);
1491
1492        if (unlikely(kmmio_fault(regs, address)))
1493                return;
1494
1495        /* Was the fault on kernel-controlled part of the address space? */
1496        if (unlikely(fault_in_kernel_space(address)))
1497                do_kern_addr_fault(regs, hw_error_code, address);
1498        else
1499                do_user_addr_fault(regs, hw_error_code, address);
1500}
1501NOKPROBE_SYMBOL(__do_page_fault);
1502
1503static nokprobe_inline void
1504trace_page_fault_entries(unsigned long address, struct pt_regs *regs,
1505                         unsigned long error_code)
1506{
1507        if (user_mode(regs))
1508                trace_page_fault_user(address, regs, error_code);
1509        else
1510                trace_page_fault_kernel(address, regs, error_code);
1511}
1512
1513/*
1514 * We must have this function blacklisted from kprobes, tagged with notrace
1515 * and call read_cr2() before calling anything else. To avoid calling any
1516 * kind of tracing machinery before we've observed the CR2 value.
1517 *
1518 * exception_{enter,exit}() contains all sorts of tracepoints.
1519 */
1520dotraplinkage void notrace
1521do_page_fault(struct pt_regs *regs, unsigned long error_code)
1522{
1523        unsigned long address = read_cr2(); /* Get the faulting address */
1524        enum ctx_state prev_state;
1525
1526        prev_state = exception_enter();
1527
1528        /*
1529         * KVM has two types of events that are, logically, interrupts, but
1530         * are unfortunately delivered using the #PF vector.  These events are
1531         * "you just accessed valid memory, but the host doesn't have it right
1532         * now, so I'll put you to sleep if you continue" and "that memory
1533         * you tried to access earlier is available now."
1534         *
1535         * We are relying on the interrupted context being sane (valid RSP,
1536         * relevant locks not held, etc.), which is fine as long as the
1537         * interrupted context had IF=1.  We are also relying on the KVM
1538         * async pf type field and CR2 being read consistently instead of
1539         * getting values from real and async page faults mixed up.
1540         *
1541         * Fingers crossed.
1542         */
1543        if (kvm_handle_async_pf(regs, (u32)address))
1544                goto exc_exit;
1545
1546        if (trace_pagefault_enabled())
1547                trace_page_fault_entries(address, regs, error_code);
1548
1549        __do_page_fault(regs, error_code, address);
1550
1551exc_exit:
1552        exception_exit(prev_state);
1553}
1554NOKPROBE_SYMBOL(do_page_fault);
1555