1 /*
2  *  x86 exception helpers - sysemu code
3  *
4  *  Copyright (c) 2003 Fabrice Bellard
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
18  */
19 
20 #include "qemu/osdep.h"
21 #include "cpu.h"
22 #include "exec/exec-all.h"
23 #include "tcg/helper-tcg.h"
24 
25 typedef struct TranslateParams {
26     target_ulong addr;
27     target_ulong cr3;
28     int pg_mode;
29     int mmu_idx;
30     int ptw_idx;
31     MMUAccessType access_type;
32 } TranslateParams;
33 
34 typedef struct TranslateResult {
35     hwaddr paddr;
36     int prot;
37     int page_size;
38 } TranslateResult;
39 
40 typedef enum TranslateFaultStage2 {
41     S2_NONE,
42     S2_GPA,
43     S2_GPT,
44 } TranslateFaultStage2;
45 
46 typedef struct TranslateFault {
47     int exception_index;
48     int error_code;
49     target_ulong cr2;
50     TranslateFaultStage2 stage2;
51 } TranslateFault;
52 
53 typedef struct PTETranslate {
54     CPUX86State *env;
55     TranslateFault *err;
56     int ptw_idx;
57     void *haddr;
58     hwaddr gaddr;
59 } PTETranslate;
60 
61 static bool ptw_translate(PTETranslate *inout, hwaddr addr)
62 {
63     CPUTLBEntryFull *full;
64     int flags;
65 
66     inout->gaddr = addr;
67     flags = probe_access_full(inout->env, addr, MMU_DATA_STORE,
68                               inout->ptw_idx, true, &inout->haddr, &full, 0);
69 
70     if (unlikely(flags & TLB_INVALID_MASK)) {
71         TranslateFault *err = inout->err;
72 
73         assert(inout->ptw_idx == MMU_NESTED_IDX);
74         err->exception_index = 0; /* unused */
75         err->error_code = inout->env->error_code;
76         err->cr2 = addr;
77         err->stage2 = S2_GPT;
78         return false;
79     }
80     return true;
81 }
82 
83 static inline uint32_t ptw_ldl(const PTETranslate *in)
84 {
85     if (likely(in->haddr)) {
86         return ldl_p(in->haddr);
87     }
88     return cpu_ldl_mmuidx_ra(in->env, in->gaddr, in->ptw_idx, 0);
89 }
90 
91 static inline uint64_t ptw_ldq(const PTETranslate *in)
92 {
93     if (likely(in->haddr)) {
94         return ldq_p(in->haddr);
95     }
96     return cpu_ldq_mmuidx_ra(in->env, in->gaddr, in->ptw_idx, 0);
97 }
98 
99 /*
100  * Note that we can use a 32-bit cmpxchg for all page table entries,
101  * even 64-bit ones, because PG_PRESENT_MASK, PG_ACCESSED_MASK and
102  * PG_DIRTY_MASK are all in the low 32 bits.
103  */
104 static bool ptw_setl_slow(const PTETranslate *in, uint32_t old, uint32_t new)
105 {
106     uint32_t cmp;
107 
108     /* Does x86 really perform a rmw cycle on mmio for ptw? */
109     start_exclusive();
110     cmp = cpu_ldl_mmuidx_ra(in->env, in->gaddr, in->ptw_idx, 0);
111     if (cmp == old) {
112         cpu_stl_mmuidx_ra(in->env, in->gaddr, new, in->ptw_idx, 0);
113     }
114     end_exclusive();
115     return cmp == old;
116 }
117 
118 static inline bool ptw_setl(const PTETranslate *in, uint32_t old, uint32_t set)
119 {
120     if (set & ~old) {
121         uint32_t new = old | set;
122         if (likely(in->haddr)) {
123             old = cpu_to_le32(old);
124             new = cpu_to_le32(new);
125             return qatomic_cmpxchg((uint32_t *)in->haddr, old, new) == old;
126         }
127         return ptw_setl_slow(in, old, new);
128     }
129     return true;
130 }
131 
132 static bool mmu_translate(CPUX86State *env, const TranslateParams *in,
133                           TranslateResult *out, TranslateFault *err)
134 {
135     const int32_t a20_mask = x86_get_a20_mask(env);
136     const target_ulong addr = in->addr;
137     const int pg_mode = in->pg_mode;
138     const bool is_user = (in->mmu_idx == MMU_USER_IDX);
139     const MMUAccessType access_type = in->access_type;
140     uint64_t ptep, pte, rsvd_mask;
141     PTETranslate pte_trans = {
142         .env = env,
143         .err = err,
144         .ptw_idx = in->ptw_idx,
145     };
146     hwaddr pte_addr, paddr;
147     uint32_t pkr;
148     int page_size;
149 
150  restart_all:
151     rsvd_mask = ~MAKE_64BIT_MASK(0, env_archcpu(env)->phys_bits);
152     rsvd_mask &= PG_ADDRESS_MASK;
153     if (!(pg_mode & PG_MODE_NXE)) {
154         rsvd_mask |= PG_NX_MASK;
155     }
156 
157     if (pg_mode & PG_MODE_PAE) {
158 #ifdef TARGET_X86_64
159         if (pg_mode & PG_MODE_LMA) {
160             if (pg_mode & PG_MODE_LA57) {
161                 /*
162                  * Page table level 5
163                  */
164                 pte_addr = ((in->cr3 & ~0xfff) +
165                             (((addr >> 48) & 0x1ff) << 3)) & a20_mask;
166                 if (!ptw_translate(&pte_trans, pte_addr)) {
167                     return false;
168                 }
169             restart_5:
170                 pte = ptw_ldq(&pte_trans);
171                 if (!(pte & PG_PRESENT_MASK)) {
172                     goto do_fault;
173                 }
174                 if (pte & (rsvd_mask | PG_PSE_MASK)) {
175                     goto do_fault_rsvd;
176                 }
177                 if (!ptw_setl(&pte_trans, pte, PG_ACCESSED_MASK)) {
178                     goto restart_5;
179                 }
180                 ptep = pte ^ PG_NX_MASK;
181             } else {
182                 pte = in->cr3;
183                 ptep = PG_NX_MASK | PG_USER_MASK | PG_RW_MASK;
184             }
185 
186             /*
187              * Page table level 4
188              */
189             pte_addr = ((pte & PG_ADDRESS_MASK) +
190                         (((addr >> 39) & 0x1ff) << 3)) & a20_mask;
191             if (!ptw_translate(&pte_trans, pte_addr)) {
192                 return false;
193             }
194         restart_4:
195             pte = ptw_ldq(&pte_trans);
196             if (!(pte & PG_PRESENT_MASK)) {
197                 goto do_fault;
198             }
199             if (pte & (rsvd_mask | PG_PSE_MASK)) {
200                 goto do_fault_rsvd;
201             }
202             if (!ptw_setl(&pte_trans, pte, PG_ACCESSED_MASK)) {
203                 goto restart_4;
204             }
205             ptep &= pte ^ PG_NX_MASK;
206 
207             /*
208              * Page table level 3
209              */
210             pte_addr = ((pte & PG_ADDRESS_MASK) +
211                         (((addr >> 30) & 0x1ff) << 3)) & a20_mask;
212             if (!ptw_translate(&pte_trans, pte_addr)) {
213                 return false;
214             }
215         restart_3_lma:
216             pte = ptw_ldq(&pte_trans);
217             if (!(pte & PG_PRESENT_MASK)) {
218                 goto do_fault;
219             }
220             if (pte & rsvd_mask) {
221                 goto do_fault_rsvd;
222             }
223             if (!ptw_setl(&pte_trans, pte, PG_ACCESSED_MASK)) {
224                 goto restart_3_lma;
225             }
226             ptep &= pte ^ PG_NX_MASK;
227             if (pte & PG_PSE_MASK) {
228                 /* 1 GB page */
229                 page_size = 1024 * 1024 * 1024;
230                 goto do_check_protect;
231             }
232         } else
233 #endif
234         {
235             /*
236              * Page table level 3
237              */
238             pte_addr = ((in->cr3 & ~0x1f) + ((addr >> 27) & 0x18)) & a20_mask;
239             if (!ptw_translate(&pte_trans, pte_addr)) {
240                 return false;
241             }
242             rsvd_mask |= PG_HI_USER_MASK;
243         restart_3_nolma:
244             pte = ptw_ldq(&pte_trans);
245             if (!(pte & PG_PRESENT_MASK)) {
246                 goto do_fault;
247             }
248             if (pte & (rsvd_mask | PG_NX_MASK)) {
249                 goto do_fault_rsvd;
250             }
251             if (!ptw_setl(&pte_trans, pte, PG_ACCESSED_MASK)) {
252                 goto restart_3_nolma;
253             }
254             ptep = PG_NX_MASK | PG_USER_MASK | PG_RW_MASK;
255         }
256 
257         /*
258          * Page table level 2
259          */
260         pte_addr = ((pte & PG_ADDRESS_MASK) +
261                     (((addr >> 21) & 0x1ff) << 3)) & a20_mask;
262         if (!ptw_translate(&pte_trans, pte_addr)) {
263             return false;
264         }
265     restart_2_pae:
266         pte = ptw_ldq(&pte_trans);
267         if (!(pte & PG_PRESENT_MASK)) {
268             goto do_fault;
269         }
270         if (pte & rsvd_mask) {
271             goto do_fault_rsvd;
272         }
273         if (pte & PG_PSE_MASK) {
274             /* 2 MB page */
275             page_size = 2048 * 1024;
276             ptep &= pte ^ PG_NX_MASK;
277             goto do_check_protect;
278         }
279         if (!ptw_setl(&pte_trans, pte, PG_ACCESSED_MASK)) {
280             goto restart_2_pae;
281         }
282         ptep &= pte ^ PG_NX_MASK;
283 
284         /*
285          * Page table level 1
286          */
287         pte_addr = ((pte & PG_ADDRESS_MASK) +
288                     (((addr >> 12) & 0x1ff) << 3)) & a20_mask;
289         if (!ptw_translate(&pte_trans, pte_addr)) {
290             return false;
291         }
292         pte = ptw_ldq(&pte_trans);
293         if (!(pte & PG_PRESENT_MASK)) {
294             goto do_fault;
295         }
296         if (pte & rsvd_mask) {
297             goto do_fault_rsvd;
298         }
299         /* combine pde and pte nx, user and rw protections */
300         ptep &= pte ^ PG_NX_MASK;
301         page_size = 4096;
302     } else {
303         /*
304          * Page table level 2
305          */
306         pte_addr = ((in->cr3 & ~0xfff) + ((addr >> 20) & 0xffc)) & a20_mask;
307         if (!ptw_translate(&pte_trans, pte_addr)) {
308             return false;
309         }
310     restart_2_nopae:
311         pte = ptw_ldl(&pte_trans);
312         if (!(pte & PG_PRESENT_MASK)) {
313             goto do_fault;
314         }
315         ptep = pte | PG_NX_MASK;
316 
317         /* if PSE bit is set, then we use a 4MB page */
318         if ((pte & PG_PSE_MASK) && (pg_mode & PG_MODE_PSE)) {
319             page_size = 4096 * 1024;
320             /*
321              * Bits 20-13 provide bits 39-32 of the address, bit 21 is reserved.
322              * Leave bits 20-13 in place for setting accessed/dirty bits below.
323              */
324             pte = (uint32_t)pte | ((pte & 0x1fe000LL) << (32 - 13));
325             rsvd_mask = 0x200000;
326             goto do_check_protect_pse36;
327         }
328         if (!ptw_setl(&pte_trans, pte, PG_ACCESSED_MASK)) {
329             goto restart_2_nopae;
330         }
331 
332         /*
333          * Page table level 1
334          */
335         pte_addr = ((pte & ~0xfffu) + ((addr >> 10) & 0xffc)) & a20_mask;
336         if (!ptw_translate(&pte_trans, pte_addr)) {
337             return false;
338         }
339         pte = ptw_ldl(&pte_trans);
340         if (!(pte & PG_PRESENT_MASK)) {
341             goto do_fault;
342         }
343         /* combine pde and pte user and rw protections */
344         ptep &= pte | PG_NX_MASK;
345         page_size = 4096;
346         rsvd_mask = 0;
347     }
348 
349 do_check_protect:
350     rsvd_mask |= (page_size - 1) & PG_ADDRESS_MASK & ~PG_PSE_PAT_MASK;
351 do_check_protect_pse36:
352     if (pte & rsvd_mask) {
353         goto do_fault_rsvd;
354     }
355     ptep ^= PG_NX_MASK;
356 
357     /* can the page can be put in the TLB?  prot will tell us */
358     if (is_user && !(ptep & PG_USER_MASK)) {
359         goto do_fault_protect;
360     }
361 
362     int prot = 0;
363     if (in->mmu_idx != MMU_KSMAP_IDX || !(ptep & PG_USER_MASK)) {
364         prot |= PAGE_READ;
365         if ((ptep & PG_RW_MASK) || !(is_user || (pg_mode & PG_MODE_WP))) {
366             prot |= PAGE_WRITE;
367         }
368     }
369     if (!(ptep & PG_NX_MASK) &&
370         (is_user ||
371          !((pg_mode & PG_MODE_SMEP) && (ptep & PG_USER_MASK)))) {
372         prot |= PAGE_EXEC;
373     }
374 
375     if (ptep & PG_USER_MASK) {
376         pkr = pg_mode & PG_MODE_PKE ? env->pkru : 0;
377     } else {
378         pkr = pg_mode & PG_MODE_PKS ? env->pkrs : 0;
379     }
380     if (pkr) {
381         uint32_t pk = (pte & PG_PKRU_MASK) >> PG_PKRU_BIT;
382         uint32_t pkr_ad = (pkr >> pk * 2) & 1;
383         uint32_t pkr_wd = (pkr >> pk * 2) & 2;
384         uint32_t pkr_prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
385 
386         if (pkr_ad) {
387             pkr_prot &= ~(PAGE_READ | PAGE_WRITE);
388         } else if (pkr_wd && (is_user || (pg_mode & PG_MODE_WP))) {
389             pkr_prot &= ~PAGE_WRITE;
390         }
391         if ((pkr_prot & (1 << access_type)) == 0) {
392             goto do_fault_pk_protect;
393         }
394         prot &= pkr_prot;
395     }
396 
397     if ((prot & (1 << access_type)) == 0) {
398         goto do_fault_protect;
399     }
400 
401     /* yes, it can! */
402     {
403         uint32_t set = PG_ACCESSED_MASK;
404         if (access_type == MMU_DATA_STORE) {
405             set |= PG_DIRTY_MASK;
406         } else if (!(pte & PG_DIRTY_MASK)) {
407             /*
408              * Only set write access if already dirty...
409              * otherwise wait for dirty access.
410              */
411             prot &= ~PAGE_WRITE;
412         }
413         if (!ptw_setl(&pte_trans, pte, set)) {
414             /*
415              * We can arrive here from any of 3 levels and 2 formats.
416              * The only safe thing is to restart the entire lookup.
417              */
418             goto restart_all;
419         }
420     }
421 
422     /* align to page_size */
423     paddr = (pte & a20_mask & PG_ADDRESS_MASK & ~(page_size - 1))
424           | (addr & (page_size - 1));
425 
426     if (in->ptw_idx == MMU_NESTED_IDX) {
427         CPUTLBEntryFull *full;
428         int flags, nested_page_size;
429 
430         flags = probe_access_full(env, paddr, access_type,
431                                   MMU_NESTED_IDX, true,
432                                   &pte_trans.haddr, &full, 0);
433         if (unlikely(flags & TLB_INVALID_MASK)) {
434             err->exception_index = 0; /* unused */
435             err->error_code = env->error_code;
436             err->cr2 = paddr;
437             err->stage2 = S2_GPA;
438             return false;
439         }
440 
441         /* Merge stage1 & stage2 protection bits. */
442         prot &= full->prot;
443 
444         /* Re-verify resulting protection. */
445         if ((prot & (1 << access_type)) == 0) {
446             goto do_fault_protect;
447         }
448 
449         /* Merge stage1 & stage2 addresses to final physical address. */
450         nested_page_size = 1 << full->lg_page_size;
451         paddr = (full->phys_addr & ~(nested_page_size - 1))
452               | (paddr & (nested_page_size - 1));
453 
454         /*
455          * Use the larger of stage1 & stage2 page sizes, so that
456          * invalidation works.
457          */
458         if (nested_page_size > page_size) {
459             page_size = nested_page_size;
460         }
461     }
462 
463     out->paddr = paddr;
464     out->prot = prot;
465     out->page_size = page_size;
466     return true;
467 
468     int error_code;
469  do_fault_rsvd:
470     error_code = PG_ERROR_RSVD_MASK;
471     goto do_fault_cont;
472  do_fault_protect:
473     error_code = PG_ERROR_P_MASK;
474     goto do_fault_cont;
475  do_fault_pk_protect:
476     assert(access_type != MMU_INST_FETCH);
477     error_code = PG_ERROR_PK_MASK | PG_ERROR_P_MASK;
478     goto do_fault_cont;
479  do_fault:
480     error_code = 0;
481  do_fault_cont:
482     if (is_user) {
483         error_code |= PG_ERROR_U_MASK;
484     }
485     switch (access_type) {
486     case MMU_DATA_LOAD:
487         break;
488     case MMU_DATA_STORE:
489         error_code |= PG_ERROR_W_MASK;
490         break;
491     case MMU_INST_FETCH:
492         if (pg_mode & (PG_MODE_NXE | PG_MODE_SMEP)) {
493             error_code |= PG_ERROR_I_D_MASK;
494         }
495         break;
496     }
497     err->exception_index = EXCP0E_PAGE;
498     err->error_code = error_code;
499     err->cr2 = addr;
500     err->stage2 = S2_NONE;
501     return false;
502 }
503 
504 static G_NORETURN void raise_stage2(CPUX86State *env, TranslateFault *err,
505                                     uintptr_t retaddr)
506 {
507     uint64_t exit_info_1 = err->error_code;
508 
509     switch (err->stage2) {
510     case S2_GPT:
511         exit_info_1 |= SVM_NPTEXIT_GPT;
512         break;
513     case S2_GPA:
514         exit_info_1 |= SVM_NPTEXIT_GPA;
515         break;
516     default:
517         g_assert_not_reached();
518     }
519 
520     x86_stq_phys(env_cpu(env),
521                  env->vm_vmcb + offsetof(struct vmcb, control.exit_info_2),
522                  err->cr2);
523     cpu_vmexit(env, SVM_EXIT_NPF, exit_info_1, retaddr);
524 }
525 
526 static bool get_physical_address(CPUX86State *env, vaddr addr,
527                                  MMUAccessType access_type, int mmu_idx,
528                                  TranslateResult *out, TranslateFault *err)
529 {
530     TranslateParams in;
531     bool use_stage2 = env->hflags2 & HF2_NPT_MASK;
532 
533     in.addr = addr;
534     in.access_type = access_type;
535 
536     switch (mmu_idx) {
537     case MMU_PHYS_IDX:
538         break;
539 
540     case MMU_NESTED_IDX:
541         if (likely(use_stage2)) {
542             in.cr3 = env->nested_cr3;
543             in.pg_mode = env->nested_pg_mode;
544             in.mmu_idx = MMU_USER_IDX;
545             in.ptw_idx = MMU_PHYS_IDX;
546 
547             if (!mmu_translate(env, &in, out, err)) {
548                 err->stage2 = S2_GPA;
549                 return false;
550             }
551             return true;
552         }
553         break;
554 
555     default:
556         if (likely(env->cr[0] & CR0_PG_MASK)) {
557             in.cr3 = env->cr[3];
558             in.mmu_idx = mmu_idx;
559             in.ptw_idx = use_stage2 ? MMU_NESTED_IDX : MMU_PHYS_IDX;
560             in.pg_mode = get_pg_mode(env);
561 
562             if (in.pg_mode & PG_MODE_LMA) {
563                 /* test virtual address sign extension */
564                 int shift = in.pg_mode & PG_MODE_LA57 ? 56 : 47;
565                 int64_t sext = (int64_t)addr >> shift;
566                 if (sext != 0 && sext != -1) {
567                     err->exception_index = EXCP0D_GPF;
568                     err->error_code = 0;
569                     err->cr2 = addr;
570                     return false;
571                 }
572             }
573             return mmu_translate(env, &in, out, err);
574         }
575         break;
576     }
577 
578     /* Translation disabled. */
579     out->paddr = addr & x86_get_a20_mask(env);
580 #ifdef TARGET_X86_64
581     if (!(env->hflags & HF_LMA_MASK)) {
582         /* Without long mode we can only address 32bits in real mode */
583         out->paddr = (uint32_t)out->paddr;
584     }
585 #endif
586     out->prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
587     out->page_size = TARGET_PAGE_SIZE;
588     return true;
589 }
590 
591 bool x86_cpu_tlb_fill(CPUState *cs, vaddr addr, int size,
592                       MMUAccessType access_type, int mmu_idx,
593                       bool probe, uintptr_t retaddr)
594 {
595     CPUX86State *env = cs->env_ptr;
596     TranslateResult out;
597     TranslateFault err;
598 
599     if (get_physical_address(env, addr, access_type, mmu_idx, &out, &err)) {
600         /*
601          * Even if 4MB pages, we map only one 4KB page in the cache to
602          * avoid filling it too fast.
603          */
604         assert(out.prot & (1 << access_type));
605         tlb_set_page_with_attrs(cs, addr & TARGET_PAGE_MASK,
606                                 out.paddr & TARGET_PAGE_MASK,
607                                 cpu_get_mem_attrs(env),
608                                 out.prot, mmu_idx, out.page_size);
609         return true;
610     }
611 
612     if (probe) {
613         /* This will be used if recursing for stage2 translation. */
614         env->error_code = err.error_code;
615         return false;
616     }
617 
618     if (err.stage2 != S2_NONE) {
619         raise_stage2(env, &err, retaddr);
620     }
621 
622     if (env->intercept_exceptions & (1 << err.exception_index)) {
623         /* cr2 is not modified in case of exceptions */
624         x86_stq_phys(cs, env->vm_vmcb +
625                      offsetof(struct vmcb, control.exit_info_2),
626                      err.cr2);
627     } else {
628         env->cr[2] = err.cr2;
629     }
630     raise_exception_err_ra(env, err.exception_index, err.error_code, retaddr);
631 }
632 
633 G_NORETURN void x86_cpu_do_unaligned_access(CPUState *cs, vaddr vaddr,
634                                             MMUAccessType access_type,
635                                             int mmu_idx, uintptr_t retaddr)
636 {
637     X86CPU *cpu = X86_CPU(cs);
638     handle_unaligned_access(&cpu->env, vaddr, access_type, retaddr);
639 }
640