perf_counter: provide pagefault software events
[safe/jmp/linux-2.6] / arch / x86 / mm / fault.c
1 /*
2  *  Copyright (C) 1995  Linus Torvalds
3  *  Copyright (C) 2001, 2002 Andi Kleen, SuSE Labs.
4  *  Copyright (C) 2008-2009, Red Hat Inc., Ingo Molnar
5  */
6 #include <linux/interrupt.h>
7 #include <linux/mmiotrace.h>
8 #include <linux/bootmem.h>
9 #include <linux/compiler.h>
10 #include <linux/highmem.h>
11 #include <linux/kprobes.h>
12 #include <linux/uaccess.h>
13 #include <linux/vmalloc.h>
14 #include <linux/vt_kern.h>
15 #include <linux/signal.h>
16 #include <linux/kernel.h>
17 #include <linux/ptrace.h>
18 #include <linux/string.h>
19 #include <linux/module.h>
20 #include <linux/kdebug.h>
21 #include <linux/errno.h>
22 #include <linux/magic.h>
23 #include <linux/sched.h>
24 #include <linux/types.h>
25 #include <linux/init.h>
26 #include <linux/mman.h>
27 #include <linux/tty.h>
28 #include <linux/smp.h>
29 #include <linux/mm.h>
30 #include <linux/perf_counter.h>
31
32 #include <asm-generic/sections.h>
33
34 #include <asm/tlbflush.h>
35 #include <asm/pgalloc.h>
36 #include <asm/segment.h>
37 #include <asm/system.h>
38 #include <asm/proto.h>
39 #include <asm/traps.h>
40 #include <asm/desc.h>
41
42 /*
43  * Page fault error code bits:
44  *
45  *   bit 0 ==    0: no page found       1: protection fault
46  *   bit 1 ==    0: read access         1: write access
47  *   bit 2 ==    0: kernel-mode access  1: user-mode access
48  *   bit 3 ==                           1: use of reserved bit detected
49  *   bit 4 ==                           1: fault was an instruction fetch
50  */
51 enum x86_pf_error_code {
52
53         PF_PROT         =               1 << 0,
54         PF_WRITE        =               1 << 1,
55         PF_USER         =               1 << 2,
56         PF_RSVD         =               1 << 3,
57         PF_INSTR        =               1 << 4,
58 };
59
60 /*
61  * Returns 0 if mmiotrace is disabled, or if the fault is not
62  * handled by mmiotrace:
63  */
64 static inline int kmmio_fault(struct pt_regs *regs, unsigned long addr)
65 {
66         if (unlikely(is_kmmio_active()))
67                 if (kmmio_handler(regs, addr) == 1)
68                         return -1;
69         return 0;
70 }
71
72 static inline int notify_page_fault(struct pt_regs *regs)
73 {
74         int ret = 0;
75
76         /* kprobe_running() needs smp_processor_id() */
77         if (kprobes_built_in() && !user_mode_vm(regs)) {
78                 preempt_disable();
79                 if (kprobe_running() && kprobe_fault_handler(regs, 14))
80                         ret = 1;
81                 preempt_enable();
82         }
83
84         return ret;
85 }
86
87 /*
88  * Prefetch quirks:
89  *
90  * 32-bit mode:
91  *
92  *   Sometimes AMD Athlon/Opteron CPUs report invalid exceptions on prefetch.
93  *   Check that here and ignore it.
94  *
95  * 64-bit mode:
96  *
97  *   Sometimes the CPU reports invalid exceptions on prefetch.
98  *   Check that here and ignore it.
99  *
100  * Opcode checker based on code by Richard Brunner.
101  */
102 static inline int
103 check_prefetch_opcode(struct pt_regs *regs, unsigned char *instr,
104                       unsigned char opcode, int *prefetch)
105 {
106         unsigned char instr_hi = opcode & 0xf0;
107         unsigned char instr_lo = opcode & 0x0f;
108
109         switch (instr_hi) {
110         case 0x20:
111         case 0x30:
112                 /*
113                  * Values 0x26,0x2E,0x36,0x3E are valid x86 prefixes.
114                  * In X86_64 long mode, the CPU will signal invalid
115                  * opcode if some of these prefixes are present so
116                  * X86_64 will never get here anyway
117                  */
118                 return ((instr_lo & 7) == 0x6);
119 #ifdef CONFIG_X86_64
120         case 0x40:
121                 /*
122                  * In AMD64 long mode 0x40..0x4F are valid REX prefixes
123                  * Need to figure out under what instruction mode the
124                  * instruction was issued. Could check the LDT for lm,
125                  * but for now it's good enough to assume that long
126                  * mode only uses well known segments or kernel.
127                  */
128                 return (!user_mode(regs)) || (regs->cs == __USER_CS);
129 #endif
130         case 0x60:
131                 /* 0x64 thru 0x67 are valid prefixes in all modes. */
132                 return (instr_lo & 0xC) == 0x4;
133         case 0xF0:
134                 /* 0xF0, 0xF2, 0xF3 are valid prefixes in all modes. */
135                 return !instr_lo || (instr_lo>>1) == 1;
136         case 0x00:
137                 /* Prefetch instruction is 0x0F0D or 0x0F18 */
138                 if (probe_kernel_address(instr, opcode))
139                         return 0;
140
141                 *prefetch = (instr_lo == 0xF) &&
142                         (opcode == 0x0D || opcode == 0x18);
143                 return 0;
144         default:
145                 return 0;
146         }
147 }
148
149 static int
150 is_prefetch(struct pt_regs *regs, unsigned long error_code, unsigned long addr)
151 {
152         unsigned char *max_instr;
153         unsigned char *instr;
154         int prefetch = 0;
155
156         /*
157          * If it was a exec (instruction fetch) fault on NX page, then
158          * do not ignore the fault:
159          */
160         if (error_code & PF_INSTR)
161                 return 0;
162
163         instr = (void *)convert_ip_to_linear(current, regs);
164         max_instr = instr + 15;
165
166         if (user_mode(regs) && instr >= (unsigned char *)TASK_SIZE)
167                 return 0;
168
169         while (instr < max_instr) {
170                 unsigned char opcode;
171
172                 if (probe_kernel_address(instr, opcode))
173                         break;
174
175                 instr++;
176
177                 if (!check_prefetch_opcode(regs, instr, opcode, &prefetch))
178                         break;
179         }
180         return prefetch;
181 }
182
183 static void
184 force_sig_info_fault(int si_signo, int si_code, unsigned long address,
185                      struct task_struct *tsk)
186 {
187         siginfo_t info;
188
189         info.si_signo   = si_signo;
190         info.si_errno   = 0;
191         info.si_code    = si_code;
192         info.si_addr    = (void __user *)address;
193
194         force_sig_info(si_signo, &info, tsk);
195 }
196
197 DEFINE_SPINLOCK(pgd_lock);
198 LIST_HEAD(pgd_list);
199
200 #ifdef CONFIG_X86_32
201 static inline pmd_t *vmalloc_sync_one(pgd_t *pgd, unsigned long address)
202 {
203         unsigned index = pgd_index(address);
204         pgd_t *pgd_k;
205         pud_t *pud, *pud_k;
206         pmd_t *pmd, *pmd_k;
207
208         pgd += index;
209         pgd_k = init_mm.pgd + index;
210
211         if (!pgd_present(*pgd_k))
212                 return NULL;
213
214         /*
215          * set_pgd(pgd, *pgd_k); here would be useless on PAE
216          * and redundant with the set_pmd() on non-PAE. As would
217          * set_pud.
218          */
219         pud = pud_offset(pgd, address);
220         pud_k = pud_offset(pgd_k, address);
221         if (!pud_present(*pud_k))
222                 return NULL;
223
224         pmd = pmd_offset(pud, address);
225         pmd_k = pmd_offset(pud_k, address);
226         if (!pmd_present(*pmd_k))
227                 return NULL;
228
229         if (!pmd_present(*pmd)) {
230                 set_pmd(pmd, *pmd_k);
231                 arch_flush_lazy_mmu_mode();
232         } else {
233                 BUG_ON(pmd_page(*pmd) != pmd_page(*pmd_k));
234         }
235
236         return pmd_k;
237 }
238
239 void vmalloc_sync_all(void)
240 {
241         unsigned long address;
242
243         if (SHARED_KERNEL_PMD)
244                 return;
245
246         for (address = VMALLOC_START & PMD_MASK;
247              address >= TASK_SIZE && address < FIXADDR_TOP;
248              address += PMD_SIZE) {
249
250                 unsigned long flags;
251                 struct page *page;
252
253                 spin_lock_irqsave(&pgd_lock, flags);
254                 list_for_each_entry(page, &pgd_list, lru) {
255                         if (!vmalloc_sync_one(page_address(page), address))
256                                 break;
257                 }
258                 spin_unlock_irqrestore(&pgd_lock, flags);
259         }
260 }
261
262 /*
263  * 32-bit:
264  *
265  *   Handle a fault on the vmalloc or module mapping area
266  */
267 static noinline int vmalloc_fault(unsigned long address)
268 {
269         unsigned long pgd_paddr;
270         pmd_t *pmd_k;
271         pte_t *pte_k;
272
273         /* Make sure we are in vmalloc area: */
274         if (!(address >= VMALLOC_START && address < VMALLOC_END))
275                 return -1;
276
277         /*
278          * Synchronize this task's top level page-table
279          * with the 'reference' page table.
280          *
281          * Do _not_ use "current" here. We might be inside
282          * an interrupt in the middle of a task switch..
283          */
284         pgd_paddr = read_cr3();
285         pmd_k = vmalloc_sync_one(__va(pgd_paddr), address);
286         if (!pmd_k)
287                 return -1;
288
289         pte_k = pte_offset_kernel(pmd_k, address);
290         if (!pte_present(*pte_k))
291                 return -1;
292
293         return 0;
294 }
295
296 /*
297  * Did it hit the DOS screen memory VA from vm86 mode?
298  */
299 static inline void
300 check_v8086_mode(struct pt_regs *regs, unsigned long address,
301                  struct task_struct *tsk)
302 {
303         unsigned long bit;
304
305         if (!v8086_mode(regs))
306                 return;
307
308         bit = (address - 0xA0000) >> PAGE_SHIFT;
309         if (bit < 32)
310                 tsk->thread.screen_bitmap |= 1 << bit;
311 }
312
313 static void dump_pagetable(unsigned long address)
314 {
315         __typeof__(pte_val(__pte(0))) page;
316
317         page = read_cr3();
318         page = ((__typeof__(page) *) __va(page))[address >> PGDIR_SHIFT];
319
320 #ifdef CONFIG_X86_PAE
321         printk("*pdpt = %016Lx ", page);
322         if ((page >> PAGE_SHIFT) < max_low_pfn
323             && page & _PAGE_PRESENT) {
324                 page &= PAGE_MASK;
325                 page = ((__typeof__(page) *) __va(page))[(address >> PMD_SHIFT)
326                                                         & (PTRS_PER_PMD - 1)];
327                 printk(KERN_CONT "*pde = %016Lx ", page);
328                 page &= ~_PAGE_NX;
329         }
330 #else
331         printk("*pde = %08lx ", page);
332 #endif
333
334         /*
335          * We must not directly access the pte in the highpte
336          * case if the page table is located in highmem.
337          * And let's rather not kmap-atomic the pte, just in case
338          * it's allocated already:
339          */
340         if ((page >> PAGE_SHIFT) < max_low_pfn
341             && (page & _PAGE_PRESENT)
342             && !(page & _PAGE_PSE)) {
343
344                 page &= PAGE_MASK;
345                 page = ((__typeof__(page) *) __va(page))[(address >> PAGE_SHIFT)
346                                                         & (PTRS_PER_PTE - 1)];
347                 printk("*pte = %0*Lx ", sizeof(page)*2, (u64)page);
348         }
349
350         printk("\n");
351 }
352
353 #else /* CONFIG_X86_64: */
354
355 void vmalloc_sync_all(void)
356 {
357         unsigned long address;
358
359         for (address = VMALLOC_START & PGDIR_MASK; address <= VMALLOC_END;
360              address += PGDIR_SIZE) {
361
362                 const pgd_t *pgd_ref = pgd_offset_k(address);
363                 unsigned long flags;
364                 struct page *page;
365
366                 if (pgd_none(*pgd_ref))
367                         continue;
368
369                 spin_lock_irqsave(&pgd_lock, flags);
370                 list_for_each_entry(page, &pgd_list, lru) {
371                         pgd_t *pgd;
372                         pgd = (pgd_t *)page_address(page) + pgd_index(address);
373                         if (pgd_none(*pgd))
374                                 set_pgd(pgd, *pgd_ref);
375                         else
376                                 BUG_ON(pgd_page_vaddr(*pgd) != pgd_page_vaddr(*pgd_ref));
377                 }
378                 spin_unlock_irqrestore(&pgd_lock, flags);
379         }
380 }
381
382 /*
383  * 64-bit:
384  *
385  *   Handle a fault on the vmalloc area
386  *
387  * This assumes no large pages in there.
388  */
389 static noinline int vmalloc_fault(unsigned long address)
390 {
391         pgd_t *pgd, *pgd_ref;
392         pud_t *pud, *pud_ref;
393         pmd_t *pmd, *pmd_ref;
394         pte_t *pte, *pte_ref;
395
396         /* Make sure we are in vmalloc area: */
397         if (!(address >= VMALLOC_START && address < VMALLOC_END))
398                 return -1;
399
400         /*
401          * Copy kernel mappings over when needed. This can also
402          * happen within a race in page table update. In the later
403          * case just flush:
404          */
405         pgd = pgd_offset(current->active_mm, address);
406         pgd_ref = pgd_offset_k(address);
407         if (pgd_none(*pgd_ref))
408                 return -1;
409
410         if (pgd_none(*pgd))
411                 set_pgd(pgd, *pgd_ref);
412         else
413                 BUG_ON(pgd_page_vaddr(*pgd) != pgd_page_vaddr(*pgd_ref));
414
415         /*
416          * Below here mismatches are bugs because these lower tables
417          * are shared:
418          */
419
420         pud = pud_offset(pgd, address);
421         pud_ref = pud_offset(pgd_ref, address);
422         if (pud_none(*pud_ref))
423                 return -1;
424
425         if (pud_none(*pud) || pud_page_vaddr(*pud) != pud_page_vaddr(*pud_ref))
426                 BUG();
427
428         pmd = pmd_offset(pud, address);
429         pmd_ref = pmd_offset(pud_ref, address);
430         if (pmd_none(*pmd_ref))
431                 return -1;
432
433         if (pmd_none(*pmd) || pmd_page(*pmd) != pmd_page(*pmd_ref))
434                 BUG();
435
436         pte_ref = pte_offset_kernel(pmd_ref, address);
437         if (!pte_present(*pte_ref))
438                 return -1;
439
440         pte = pte_offset_kernel(pmd, address);
441
442         /*
443          * Don't use pte_page here, because the mappings can point
444          * outside mem_map, and the NUMA hash lookup cannot handle
445          * that:
446          */
447         if (!pte_present(*pte) || pte_pfn(*pte) != pte_pfn(*pte_ref))
448                 BUG();
449
450         return 0;
451 }
452
453 static const char errata93_warning[] =
454 KERN_ERR "******* Your BIOS seems to not contain a fix for K8 errata #93\n"
455 KERN_ERR "******* Working around it, but it may cause SEGVs or burn power.\n"
456 KERN_ERR "******* Please consider a BIOS update.\n"
457 KERN_ERR "******* Disabling USB legacy in the BIOS may also help.\n";
458
459 /*
460  * No vm86 mode in 64-bit mode:
461  */
462 static inline void
463 check_v8086_mode(struct pt_regs *regs, unsigned long address,
464                  struct task_struct *tsk)
465 {
466 }
467
468 static int bad_address(void *p)
469 {
470         unsigned long dummy;
471
472         return probe_kernel_address((unsigned long *)p, dummy);
473 }
474
475 static void dump_pagetable(unsigned long address)
476 {
477         pgd_t *pgd;
478         pud_t *pud;
479         pmd_t *pmd;
480         pte_t *pte;
481
482         pgd = (pgd_t *)read_cr3();
483
484         pgd = __va((unsigned long)pgd & PHYSICAL_PAGE_MASK);
485
486         pgd += pgd_index(address);
487         if (bad_address(pgd))
488                 goto bad;
489
490         printk("PGD %lx ", pgd_val(*pgd));
491
492         if (!pgd_present(*pgd))
493                 goto out;
494
495         pud = pud_offset(pgd, address);
496         if (bad_address(pud))
497                 goto bad;
498
499         printk("PUD %lx ", pud_val(*pud));
500         if (!pud_present(*pud) || pud_large(*pud))
501                 goto out;
502
503         pmd = pmd_offset(pud, address);
504         if (bad_address(pmd))
505                 goto bad;
506
507         printk("PMD %lx ", pmd_val(*pmd));
508         if (!pmd_present(*pmd) || pmd_large(*pmd))
509                 goto out;
510
511         pte = pte_offset_kernel(pmd, address);
512         if (bad_address(pte))
513                 goto bad;
514
515         printk("PTE %lx", pte_val(*pte));
516 out:
517         printk("\n");
518         return;
519 bad:
520         printk("BAD\n");
521 }
522
523 #endif /* CONFIG_X86_64 */
524
525 /*
526  * Workaround for K8 erratum #93 & buggy BIOS.
527  *
528  * BIOS SMM functions are required to use a specific workaround
529  * to avoid corruption of the 64bit RIP register on C stepping K8.
530  *
531  * A lot of BIOS that didn't get tested properly miss this.
532  *
533  * The OS sees this as a page fault with the upper 32bits of RIP cleared.
534  * Try to work around it here.
535  *
536  * Note we only handle faults in kernel here.
537  * Does nothing on 32-bit.
538  */
539 static int is_errata93(struct pt_regs *regs, unsigned long address)
540 {
541 #ifdef CONFIG_X86_64
542         static int once;
543
544         if (address != regs->ip)
545                 return 0;
546
547         if ((address >> 32) != 0)
548                 return 0;
549
550         address |= 0xffffffffUL << 32;
551         if ((address >= (u64)_stext && address <= (u64)_etext) ||
552             (address >= MODULES_VADDR && address <= MODULES_END)) {
553                 if (!once) {
554                         printk(errata93_warning);
555                         once = 1;
556                 }
557                 regs->ip = address;
558                 return 1;
559         }
560 #endif
561         return 0;
562 }
563
564 /*
565  * Work around K8 erratum #100 K8 in compat mode occasionally jumps
566  * to illegal addresses >4GB.
567  *
568  * We catch this in the page fault handler because these addresses
569  * are not reachable. Just detect this case and return.  Any code
570  * segment in LDT is compatibility mode.
571  */
572 static int is_errata100(struct pt_regs *regs, unsigned long address)
573 {
574 #ifdef CONFIG_X86_64
575         if ((regs->cs == __USER32_CS || (regs->cs & (1<<2))) && (address >> 32))
576                 return 1;
577 #endif
578         return 0;
579 }
580
581 static int is_f00f_bug(struct pt_regs *regs, unsigned long address)
582 {
583 #ifdef CONFIG_X86_F00F_BUG
584         unsigned long nr;
585
586         /*
587          * Pentium F0 0F C7 C8 bug workaround:
588          */
589         if (boot_cpu_data.f00f_bug) {
590                 nr = (address - idt_descr.address) >> 3;
591
592                 if (nr == 6) {
593                         do_invalid_op(regs, 0);
594                         return 1;
595                 }
596         }
597 #endif
598         return 0;
599 }
600
601 static const char nx_warning[] = KERN_CRIT
602 "kernel tried to execute NX-protected page - exploit attempt? (uid: %d)\n";
603
604 static void
605 show_fault_oops(struct pt_regs *regs, unsigned long error_code,
606                 unsigned long address)
607 {
608         if (!oops_may_print())
609                 return;
610
611         if (error_code & PF_INSTR) {
612                 unsigned int level;
613
614                 pte_t *pte = lookup_address(address, &level);
615
616                 if (pte && pte_present(*pte) && !pte_exec(*pte))
617                         printk(nx_warning, current_uid());
618         }
619
620         printk(KERN_ALERT "BUG: unable to handle kernel ");
621         if (address < PAGE_SIZE)
622                 printk(KERN_CONT "NULL pointer dereference");
623         else
624                 printk(KERN_CONT "paging request");
625
626         printk(KERN_CONT " at %p\n", (void *) address);
627         printk(KERN_ALERT "IP:");
628         printk_address(regs->ip, 1);
629
630         dump_pagetable(address);
631 }
632
633 static noinline void
634 pgtable_bad(struct pt_regs *regs, unsigned long error_code,
635             unsigned long address)
636 {
637         struct task_struct *tsk;
638         unsigned long flags;
639         int sig;
640
641         flags = oops_begin();
642         tsk = current;
643         sig = SIGKILL;
644
645         printk(KERN_ALERT "%s: Corrupted page table at address %lx\n",
646                tsk->comm, address);
647         dump_pagetable(address);
648
649         tsk->thread.cr2         = address;
650         tsk->thread.trap_no     = 14;
651         tsk->thread.error_code  = error_code;
652
653         if (__die("Bad pagetable", regs, error_code))
654                 sig = 0;
655
656         oops_end(flags, regs, sig);
657 }
658
659 static noinline void
660 no_context(struct pt_regs *regs, unsigned long error_code,
661            unsigned long address)
662 {
663         struct task_struct *tsk = current;
664         unsigned long *stackend;
665         unsigned long flags;
666         int sig;
667
668         /* Are we prepared to handle this kernel fault? */
669         if (fixup_exception(regs))
670                 return;
671
672         /*
673          * 32-bit:
674          *
675          *   Valid to do another page fault here, because if this fault
676          *   had been triggered by is_prefetch fixup_exception would have
677          *   handled it.
678          *
679          * 64-bit:
680          *
681          *   Hall of shame of CPU/BIOS bugs.
682          */
683         if (is_prefetch(regs, error_code, address))
684                 return;
685
686         if (is_errata93(regs, address))
687                 return;
688
689         /*
690          * Oops. The kernel tried to access some bad page. We'll have to
691          * terminate things with extreme prejudice:
692          */
693         flags = oops_begin();
694
695         show_fault_oops(regs, error_code, address);
696
697         stackend = end_of_stack(tsk);
698         if (*stackend != STACK_END_MAGIC)
699                 printk(KERN_ALERT "Thread overran stack, or stack corrupted\n");
700
701         tsk->thread.cr2         = address;
702         tsk->thread.trap_no     = 14;
703         tsk->thread.error_code  = error_code;
704
705         sig = SIGKILL;
706         if (__die("Oops", regs, error_code))
707                 sig = 0;
708
709         /* Executive summary in case the body of the oops scrolled away */
710         printk(KERN_EMERG "CR2: %016lx\n", address);
711
712         oops_end(flags, regs, sig);
713 }
714
715 /*
716  * Print out info about fatal segfaults, if the show_unhandled_signals
717  * sysctl is set:
718  */
719 static inline void
720 show_signal_msg(struct pt_regs *regs, unsigned long error_code,
721                 unsigned long address, struct task_struct *tsk)
722 {
723         if (!unhandled_signal(tsk, SIGSEGV))
724                 return;
725
726         if (!printk_ratelimit())
727                 return;
728
729         printk(KERN_CONT "%s%s[%d]: segfault at %lx ip %p sp %p error %lx",
730                 task_pid_nr(tsk) > 1 ? KERN_INFO : KERN_EMERG,
731                 tsk->comm, task_pid_nr(tsk), address,
732                 (void *)regs->ip, (void *)regs->sp, error_code);
733
734         print_vma_addr(KERN_CONT " in ", regs->ip);
735
736         printk(KERN_CONT "\n");
737 }
738
739 static void
740 __bad_area_nosemaphore(struct pt_regs *regs, unsigned long error_code,
741                        unsigned long address, int si_code)
742 {
743         struct task_struct *tsk = current;
744
745         /* User mode accesses just cause a SIGSEGV */
746         if (error_code & PF_USER) {
747                 /*
748                  * It's possible to have interrupts off here:
749                  */
750                 local_irq_enable();
751
752                 /*
753                  * Valid to do another page fault here because this one came
754                  * from user space:
755                  */
756                 if (is_prefetch(regs, error_code, address))
757                         return;
758
759                 if (is_errata100(regs, address))
760                         return;
761
762                 if (unlikely(show_unhandled_signals))
763                         show_signal_msg(regs, error_code, address, tsk);
764
765                 /* Kernel addresses are always protection faults: */
766                 tsk->thread.cr2         = address;
767                 tsk->thread.error_code  = error_code | (address >= TASK_SIZE);
768                 tsk->thread.trap_no     = 14;
769
770                 force_sig_info_fault(SIGSEGV, si_code, address, tsk);
771
772                 return;
773         }
774
775         if (is_f00f_bug(regs, address))
776                 return;
777
778         no_context(regs, error_code, address);
779 }
780
781 static noinline void
782 bad_area_nosemaphore(struct pt_regs *regs, unsigned long error_code,
783                      unsigned long address)
784 {
785         __bad_area_nosemaphore(regs, error_code, address, SEGV_MAPERR);
786 }
787
788 static void
789 __bad_area(struct pt_regs *regs, unsigned long error_code,
790            unsigned long address, int si_code)
791 {
792         struct mm_struct *mm = current->mm;
793
794         /*
795          * Something tried to access memory that isn't in our memory map..
796          * Fix it, but check if it's kernel or user first..
797          */
798         up_read(&mm->mmap_sem);
799
800         __bad_area_nosemaphore(regs, error_code, address, si_code);
801 }
802
803 static noinline void
804 bad_area(struct pt_regs *regs, unsigned long error_code, unsigned long address)
805 {
806         __bad_area(regs, error_code, address, SEGV_MAPERR);
807 }
808
809 static noinline void
810 bad_area_access_error(struct pt_regs *regs, unsigned long error_code,
811                       unsigned long address)
812 {
813         __bad_area(regs, error_code, address, SEGV_ACCERR);
814 }
815
816 /* TODO: fixup for "mm-invoke-oom-killer-from-page-fault.patch" */
817 static void
818 out_of_memory(struct pt_regs *regs, unsigned long error_code,
819               unsigned long address)
820 {
821         /*
822          * We ran out of memory, call the OOM killer, and return the userspace
823          * (which will retry the fault, or kill us if we got oom-killed):
824          */
825         up_read(&current->mm->mmap_sem);
826
827         pagefault_out_of_memory();
828 }
829
830 static void
831 do_sigbus(struct pt_regs *regs, unsigned long error_code, unsigned long address)
832 {
833         struct task_struct *tsk = current;
834         struct mm_struct *mm = tsk->mm;
835
836         up_read(&mm->mmap_sem);
837
838         /* Kernel mode? Handle exceptions or die: */
839         if (!(error_code & PF_USER))
840                 no_context(regs, error_code, address);
841
842         /* User-space => ok to do another page fault: */
843         if (is_prefetch(regs, error_code, address))
844                 return;
845
846         tsk->thread.cr2         = address;
847         tsk->thread.error_code  = error_code;
848         tsk->thread.trap_no     = 14;
849
850         force_sig_info_fault(SIGBUS, BUS_ADRERR, address, tsk);
851 }
852
853 static noinline void
854 mm_fault_error(struct pt_regs *regs, unsigned long error_code,
855                unsigned long address, unsigned int fault)
856 {
857         if (fault & VM_FAULT_OOM) {
858                 out_of_memory(regs, error_code, address);
859         } else {
860                 if (fault & VM_FAULT_SIGBUS)
861                         do_sigbus(regs, error_code, address);
862                 else
863                         BUG();
864         }
865 }
866
867 static int spurious_fault_check(unsigned long error_code, pte_t *pte)
868 {
869         if ((error_code & PF_WRITE) && !pte_write(*pte))
870                 return 0;
871
872         if ((error_code & PF_INSTR) && !pte_exec(*pte))
873                 return 0;
874
875         return 1;
876 }
877
878 /*
879  * Handle a spurious fault caused by a stale TLB entry.
880  *
881  * This allows us to lazily refresh the TLB when increasing the
882  * permissions of a kernel page (RO -> RW or NX -> X).  Doing it
883  * eagerly is very expensive since that implies doing a full
884  * cross-processor TLB flush, even if no stale TLB entries exist
885  * on other processors.
886  *
887  * There are no security implications to leaving a stale TLB when
888  * increasing the permissions on a page.
889  */
890 static noinline int
891 spurious_fault(unsigned long error_code, unsigned long address)
892 {
893         pgd_t *pgd;
894         pud_t *pud;
895         pmd_t *pmd;
896         pte_t *pte;
897         int ret;
898
899         /* Reserved-bit violation or user access to kernel space? */
900         if (error_code & (PF_USER | PF_RSVD))
901                 return 0;
902
903         pgd = init_mm.pgd + pgd_index(address);
904         if (!pgd_present(*pgd))
905                 return 0;
906
907         pud = pud_offset(pgd, address);
908         if (!pud_present(*pud))
909                 return 0;
910
911         if (pud_large(*pud))
912                 return spurious_fault_check(error_code, (pte_t *) pud);
913
914         pmd = pmd_offset(pud, address);
915         if (!pmd_present(*pmd))
916                 return 0;
917
918         if (pmd_large(*pmd))
919                 return spurious_fault_check(error_code, (pte_t *) pmd);
920
921         pte = pte_offset_kernel(pmd, address);
922         if (!pte_present(*pte))
923                 return 0;
924
925         ret = spurious_fault_check(error_code, pte);
926         if (!ret)
927                 return 0;
928
929         /*
930          * Make sure we have permissions in PMD.
931          * If not, then there's a bug in the page tables:
932          */
933         ret = spurious_fault_check(error_code, (pte_t *) pmd);
934         WARN_ONCE(!ret, "PMD has incorrect permission bits\n");
935
936         return ret;
937 }
938
939 int show_unhandled_signals = 1;
940
941 static inline int
942 access_error(unsigned long error_code, int write, struct vm_area_struct *vma)
943 {
944         if (write) {
945                 /* write, present and write, not present: */
946                 if (unlikely(!(vma->vm_flags & VM_WRITE)))
947                         return 1;
948                 return 0;
949         }
950
951         /* read, present: */
952         if (unlikely(error_code & PF_PROT))
953                 return 1;
954
955         /* read, not present: */
956         if (unlikely(!(vma->vm_flags & (VM_READ | VM_EXEC | VM_WRITE))))
957                 return 1;
958
959         return 0;
960 }
961
962 static int fault_in_kernel_space(unsigned long address)
963 {
964         return address >= TASK_SIZE_MAX;
965 }
966
967 /*
968  * This routine handles page faults.  It determines the address,
969  * and the problem, and then passes it off to one of the appropriate
970  * routines.
971  */
972 dotraplinkage void __kprobes
973 do_page_fault(struct pt_regs *regs, unsigned long error_code)
974 {
975         struct vm_area_struct *vma;
976         struct task_struct *tsk;
977         unsigned long address;
978         struct mm_struct *mm;
979         int write;
980         int fault;
981
982         tsk = current;
983         mm = tsk->mm;
984
985         prefetchw(&mm->mmap_sem);
986
987         /* Get the faulting address: */
988         address = read_cr2();
989
990         if (unlikely(kmmio_fault(regs, address)))
991                 return;
992
993         /*
994          * We fault-in kernel-space virtual memory on-demand. The
995          * 'reference' page table is init_mm.pgd.
996          *
997          * NOTE! We MUST NOT take any locks for this case. We may
998          * be in an interrupt or a critical region, and should
999          * only copy the information from the master page table,
1000          * nothing more.
1001          *
1002          * This verifies that the fault happens in kernel space
1003          * (error_code & 4) == 0, and that the fault was not a
1004          * protection error (error_code & 9) == 0.
1005          */
1006         if (unlikely(fault_in_kernel_space(address))) {
1007                 if (!(error_code & (PF_RSVD|PF_USER|PF_PROT)) &&
1008                     vmalloc_fault(address) >= 0)
1009                         return;
1010
1011                 /* Can handle a stale RO->RW TLB: */
1012                 if (spurious_fault(error_code, address))
1013                         return;
1014
1015                 /* kprobes don't want to hook the spurious faults: */
1016                 if (notify_page_fault(regs))
1017                         return;
1018                 /*
1019                  * Don't take the mm semaphore here. If we fixup a prefetch
1020                  * fault we could otherwise deadlock:
1021                  */
1022                 bad_area_nosemaphore(regs, error_code, address);
1023
1024                 return;
1025         }
1026
1027         /* kprobes don't want to hook the spurious faults: */
1028         if (unlikely(notify_page_fault(regs)))
1029                 return;
1030         /*
1031          * It's safe to allow irq's after cr2 has been saved and the
1032          * vmalloc fault has been handled.
1033          *
1034          * User-mode registers count as a user access even for any
1035          * potential system fault or CPU buglet:
1036          */
1037         if (user_mode_vm(regs)) {
1038                 local_irq_enable();
1039                 error_code |= PF_USER;
1040         } else {
1041                 if (regs->flags & X86_EFLAGS_IF)
1042                         local_irq_enable();
1043         }
1044
1045         if (unlikely(error_code & PF_RSVD))
1046                 pgtable_bad(regs, error_code, address);
1047
1048         perf_swcounter_event(PERF_COUNT_PAGE_FAULTS, 1, 0, regs);
1049
1050         /*
1051          * If we're in an interrupt, have no user context or are running
1052          * in an atomic region then we must not take the fault:
1053          */
1054         if (unlikely(in_atomic() || !mm)) {
1055                 bad_area_nosemaphore(regs, error_code, address);
1056                 return;
1057         }
1058
1059         /*
1060          * When running in the kernel we expect faults to occur only to
1061          * addresses in user space.  All other faults represent errors in
1062          * the kernel and should generate an OOPS.  Unfortunately, in the
1063          * case of an erroneous fault occurring in a code path which already
1064          * holds mmap_sem we will deadlock attempting to validate the fault
1065          * against the address space.  Luckily the kernel only validly
1066          * references user space from well defined areas of code, which are
1067          * listed in the exceptions table.
1068          *
1069          * As the vast majority of faults will be valid we will only perform
1070          * the source reference check when there is a possibility of a
1071          * deadlock. Attempt to lock the address space, if we cannot we then
1072          * validate the source. If this is invalid we can skip the address
1073          * space check, thus avoiding the deadlock:
1074          */
1075         if (unlikely(!down_read_trylock(&mm->mmap_sem))) {
1076                 if ((error_code & PF_USER) == 0 &&
1077                     !search_exception_tables(regs->ip)) {
1078                         bad_area_nosemaphore(regs, error_code, address);
1079                         return;
1080                 }
1081                 down_read(&mm->mmap_sem);
1082         } else {
1083                 /*
1084                  * The above down_read_trylock() might have succeeded in
1085                  * which case we'll have missed the might_sleep() from
1086                  * down_read():
1087                  */
1088                 might_sleep();
1089         }
1090
1091         vma = find_vma(mm, address);
1092         if (unlikely(!vma)) {
1093                 bad_area(regs, error_code, address);
1094                 return;
1095         }
1096         if (likely(vma->vm_start <= address))
1097                 goto good_area;
1098         if (unlikely(!(vma->vm_flags & VM_GROWSDOWN))) {
1099                 bad_area(regs, error_code, address);
1100                 return;
1101         }
1102         if (error_code & PF_USER) {
1103                 /*
1104                  * Accessing the stack below %sp is always a bug.
1105                  * The large cushion allows instructions like enter
1106                  * and pusha to work. ("enter $65535, $31" pushes
1107                  * 32 pointers and then decrements %sp by 65535.)
1108                  */
1109                 if (unlikely(address + 65536 + 32 * sizeof(unsigned long) < regs->sp)) {
1110                         bad_area(regs, error_code, address);
1111                         return;
1112                 }
1113         }
1114         if (unlikely(expand_stack(vma, address))) {
1115                 bad_area(regs, error_code, address);
1116                 return;
1117         }
1118
1119         /*
1120          * Ok, we have a good vm_area for this memory access, so
1121          * we can handle it..
1122          */
1123 good_area:
1124         write = error_code & PF_WRITE;
1125
1126         if (unlikely(access_error(error_code, write, vma))) {
1127                 bad_area_access_error(regs, error_code, address);
1128                 return;
1129         }
1130
1131         /*
1132          * If for any reason at all we couldn't handle the fault,
1133          * make sure we exit gracefully rather than endlessly redo
1134          * the fault:
1135          */
1136         fault = handle_mm_fault(mm, vma, address, write);
1137
1138         if (unlikely(fault & VM_FAULT_ERROR)) {
1139                 mm_fault_error(regs, error_code, address, fault);
1140                 return;
1141         }
1142
1143         if (fault & VM_FAULT_MAJOR)
1144                 tsk->maj_flt++;
1145         else
1146                 tsk->min_flt++;
1147
1148         check_v8086_mode(regs, address, tsk);
1149
1150         up_read(&mm->mmap_sem);
1151 }