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