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