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