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