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, 0, 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 = (TranslateFault){
75             .error_code = inout->env->error_code,
76             .cr2 = addr,
77             .stage2 = S2_GPT,
78         };
79         return false;
80     }
81     return true;
82 }
83 
84 static inline uint32_t ptw_ldl(const PTETranslate *in)
85 {
86     if (likely(in->haddr)) {
87         return ldl_p(in->haddr);
88     }
89     return cpu_ldl_mmuidx_ra(in->env, in->gaddr, in->ptw_idx, 0);
90 }
91 
92 static inline uint64_t ptw_ldq(const PTETranslate *in)
93 {
94     if (likely(in->haddr)) {
95         return ldq_p(in->haddr);
96     }
97     return cpu_ldq_mmuidx_ra(in->env, in->gaddr, in->ptw_idx, 0);
98 }
99 
100 /*
101  * Note that we can use a 32-bit cmpxchg for all page table entries,
102  * even 64-bit ones, because PG_PRESENT_MASK, PG_ACCESSED_MASK and
103  * PG_DIRTY_MASK are all in the low 32 bits.
104  */
105 static bool ptw_setl_slow(const PTETranslate *in, uint32_t old, uint32_t new)
106 {
107     uint32_t cmp;
108 
109     /* Does x86 really perform a rmw cycle on mmio for ptw? */
110     start_exclusive();
111     cmp = cpu_ldl_mmuidx_ra(in->env, in->gaddr, in->ptw_idx, 0);
112     if (cmp == old) {
113         cpu_stl_mmuidx_ra(in->env, in->gaddr, new, in->ptw_idx, 0);
114     }
115     end_exclusive();
116     return cmp == old;
117 }
118 
119 static inline bool ptw_setl(const PTETranslate *in, uint32_t old, uint32_t set)
120 {
121     if (set & ~old) {
122         uint32_t new = old | set;
123         if (likely(in->haddr)) {
124             old = cpu_to_le32(old);
125             new = cpu_to_le32(new);
126             return qatomic_cmpxchg((uint32_t *)in->haddr, old, new) == old;
127         }
128         return ptw_setl_slow(in, old, new);
129     }
130     return true;
131 }
132 
133 static bool mmu_translate(CPUX86State *env, const TranslateParams *in,
134                           TranslateResult *out, TranslateFault *err)
135 {
136     const int32_t a20_mask = x86_get_a20_mask(env);
137     const target_ulong addr = in->addr;
138     const int pg_mode = in->pg_mode;
139     const bool is_user = (in->mmu_idx == MMU_USER_IDX);
140     const MMUAccessType access_type = in->access_type;
141     uint64_t ptep, pte, rsvd_mask;
142     PTETranslate pte_trans = {
143         .env = env,
144         .err = err,
145         .ptw_idx = in->ptw_idx,
146     };
147     hwaddr pte_addr, paddr;
148     uint32_t pkr;
149     int page_size;
150 
151  restart_all:
152     rsvd_mask = ~MAKE_64BIT_MASK(0, env_archcpu(env)->phys_bits);
153     rsvd_mask &= PG_ADDRESS_MASK;
154     if (!(pg_mode & PG_MODE_NXE)) {
155         rsvd_mask |= PG_NX_MASK;
156     }
157 
158     if (pg_mode & PG_MODE_PAE) {
159 #ifdef TARGET_X86_64
160         if (pg_mode & PG_MODE_LMA) {
161             if (pg_mode & PG_MODE_LA57) {
162                 /*
163                  * Page table level 5
164                  */
165                 pte_addr = ((in->cr3 & ~0xfff) +
166                             (((addr >> 48) & 0x1ff) << 3)) & a20_mask;
167                 if (!ptw_translate(&pte_trans, pte_addr)) {
168                     return false;
169                 }
170             restart_5:
171                 pte = ptw_ldq(&pte_trans);
172                 if (!(pte & PG_PRESENT_MASK)) {
173                     goto do_fault;
174                 }
175                 if (pte & (rsvd_mask | PG_PSE_MASK)) {
176                     goto do_fault_rsvd;
177                 }
178                 if (!ptw_setl(&pte_trans, pte, PG_ACCESSED_MASK)) {
179                     goto restart_5;
180                 }
181                 ptep = pte ^ PG_NX_MASK;
182             } else {
183                 pte = in->cr3;
184                 ptep = PG_NX_MASK | PG_USER_MASK | PG_RW_MASK;
185             }
186 
187             /*
188              * Page table level 4
189              */
190             pte_addr = ((pte & PG_ADDRESS_MASK) +
191                         (((addr >> 39) & 0x1ff) << 3)) & a20_mask;
192             if (!ptw_translate(&pte_trans, pte_addr)) {
193                 return false;
194             }
195         restart_4:
196             pte = ptw_ldq(&pte_trans);
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) +
212                         (((addr >> 30) & 0x1ff) << 3)) & a20_mask;
213             if (!ptw_translate(&pte_trans, pte_addr)) {
214                 return false;
215             }
216         restart_3_lma:
217             pte = ptw_ldq(&pte_trans);
218             if (!(pte & PG_PRESENT_MASK)) {
219                 goto do_fault;
220             }
221             if (pte & rsvd_mask) {
222                 goto do_fault_rsvd;
223             }
224             if (!ptw_setl(&pte_trans, pte, PG_ACCESSED_MASK)) {
225                 goto restart_3_lma;
226             }
227             ptep &= pte ^ PG_NX_MASK;
228             if (pte & PG_PSE_MASK) {
229                 /* 1 GB page */
230                 page_size = 1024 * 1024 * 1024;
231                 goto do_check_protect;
232             }
233         } else
234 #endif
235         {
236             /*
237              * Page table level 3
238              */
239             pte_addr = ((in->cr3 & ~0x1f) + ((addr >> 27) & 0x18)) & a20_mask;
240             if (!ptw_translate(&pte_trans, pte_addr)) {
241                 return false;
242             }
243             rsvd_mask |= PG_HI_USER_MASK;
244         restart_3_nolma:
245             pte = ptw_ldq(&pte_trans);
246             if (!(pte & PG_PRESENT_MASK)) {
247                 goto do_fault;
248             }
249             if (pte & (rsvd_mask | PG_NX_MASK)) {
250                 goto do_fault_rsvd;
251             }
252             if (!ptw_setl(&pte_trans, pte, PG_ACCESSED_MASK)) {
253                 goto restart_3_nolma;
254             }
255             ptep = PG_NX_MASK | PG_USER_MASK | PG_RW_MASK;
256         }
257 
258         /*
259          * Page table level 2
260          */
261         pte_addr = ((pte & PG_ADDRESS_MASK) +
262                     (((addr >> 21) & 0x1ff) << 3)) & a20_mask;
263         if (!ptw_translate(&pte_trans, pte_addr)) {
264             return false;
265         }
266     restart_2_pae:
267         pte = ptw_ldq(&pte_trans);
268         if (!(pte & PG_PRESENT_MASK)) {
269             goto do_fault;
270         }
271         if (pte & rsvd_mask) {
272             goto do_fault_rsvd;
273         }
274         if (pte & PG_PSE_MASK) {
275             /* 2 MB page */
276             page_size = 2048 * 1024;
277             ptep &= pte ^ PG_NX_MASK;
278             goto do_check_protect;
279         }
280         if (!ptw_setl(&pte_trans, pte, PG_ACCESSED_MASK)) {
281             goto restart_2_pae;
282         }
283         ptep &= pte ^ PG_NX_MASK;
284 
285         /*
286          * Page table level 1
287          */
288         pte_addr = ((pte & PG_ADDRESS_MASK) +
289                     (((addr >> 12) & 0x1ff) << 3)) & a20_mask;
290         if (!ptw_translate(&pte_trans, pte_addr)) {
291             return false;
292         }
293         pte = ptw_ldq(&pte_trans);
294         if (!(pte & PG_PRESENT_MASK)) {
295             goto do_fault;
296         }
297         if (pte & rsvd_mask) {
298             goto do_fault_rsvd;
299         }
300         /* combine pde and pte nx, user and rw protections */
301         ptep &= pte ^ PG_NX_MASK;
302         page_size = 4096;
303     } else {
304         /*
305          * Page table level 2
306          */
307         pte_addr = ((in->cr3 & ~0xfff) + ((addr >> 20) & 0xffc)) & a20_mask;
308         if (!ptw_translate(&pte_trans, pte_addr)) {
309             return false;
310         }
311     restart_2_nopae:
312         pte = ptw_ldl(&pte_trans);
313         if (!(pte & PG_PRESENT_MASK)) {
314             goto do_fault;
315         }
316         ptep = pte | PG_NX_MASK;
317 
318         /* if PSE bit is set, then we use a 4MB page */
319         if ((pte & PG_PSE_MASK) && (pg_mode & PG_MODE_PSE)) {
320             page_size = 4096 * 1024;
321             /*
322              * Bits 20-13 provide bits 39-32 of the address, bit 21 is reserved.
323              * Leave bits 20-13 in place for setting accessed/dirty bits below.
324              */
325             pte = (uint32_t)pte | ((pte & 0x1fe000LL) << (32 - 13));
326             rsvd_mask = 0x200000;
327             goto do_check_protect_pse36;
328         }
329         if (!ptw_setl(&pte_trans, pte, PG_ACCESSED_MASK)) {
330             goto restart_2_nopae;
331         }
332 
333         /*
334          * Page table level 1
335          */
336         pte_addr = ((pte & ~0xfffu) + ((addr >> 10) & 0xffc)) & a20_mask;
337         if (!ptw_translate(&pte_trans, pte_addr)) {
338             return false;
339         }
340         pte = ptw_ldl(&pte_trans);
341         if (!(pte & PG_PRESENT_MASK)) {
342             goto do_fault;
343         }
344         /* combine pde and pte user and rw protections */
345         ptep &= pte | PG_NX_MASK;
346         page_size = 4096;
347         rsvd_mask = 0;
348     }
349 
350 do_check_protect:
351     rsvd_mask |= (page_size - 1) & PG_ADDRESS_MASK & ~PG_PSE_PAT_MASK;
352 do_check_protect_pse36:
353     if (pte & rsvd_mask) {
354         goto do_fault_rsvd;
355     }
356     ptep ^= PG_NX_MASK;
357 
358     /* can the page can be put in the TLB?  prot will tell us */
359     if (is_user && !(ptep & PG_USER_MASK)) {
360         goto do_fault_protect;
361     }
362 
363     int prot = 0;
364     if (in->mmu_idx != MMU_KSMAP_IDX || !(ptep & PG_USER_MASK)) {
365         prot |= PAGE_READ;
366         if ((ptep & PG_RW_MASK) || !(is_user || (pg_mode & PG_MODE_WP))) {
367             prot |= PAGE_WRITE;
368         }
369     }
370     if (!(ptep & PG_NX_MASK) &&
371         (is_user ||
372          !((pg_mode & PG_MODE_SMEP) && (ptep & PG_USER_MASK)))) {
373         prot |= PAGE_EXEC;
374     }
375 
376     if (ptep & PG_USER_MASK) {
377         pkr = pg_mode & PG_MODE_PKE ? env->pkru : 0;
378     } else {
379         pkr = pg_mode & PG_MODE_PKS ? env->pkrs : 0;
380     }
381     if (pkr) {
382         uint32_t pk = (pte & PG_PKRU_MASK) >> PG_PKRU_BIT;
383         uint32_t pkr_ad = (pkr >> pk * 2) & 1;
384         uint32_t pkr_wd = (pkr >> pk * 2) & 2;
385         uint32_t pkr_prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
386 
387         if (pkr_ad) {
388             pkr_prot &= ~(PAGE_READ | PAGE_WRITE);
389         } else if (pkr_wd && (is_user || (pg_mode & PG_MODE_WP))) {
390             pkr_prot &= ~PAGE_WRITE;
391         }
392         if ((pkr_prot & (1 << access_type)) == 0) {
393             goto do_fault_pk_protect;
394         }
395         prot &= pkr_prot;
396     }
397 
398     if ((prot & (1 << access_type)) == 0) {
399         goto do_fault_protect;
400     }
401 
402     /* yes, it can! */
403     {
404         uint32_t set = PG_ACCESSED_MASK;
405         if (access_type == MMU_DATA_STORE) {
406             set |= PG_DIRTY_MASK;
407         } else if (!(pte & PG_DIRTY_MASK)) {
408             /*
409              * Only set write access if already dirty...
410              * otherwise wait for dirty access.
411              */
412             prot &= ~PAGE_WRITE;
413         }
414         if (!ptw_setl(&pte_trans, pte, set)) {
415             /*
416              * We can arrive here from any of 3 levels and 2 formats.
417              * The only safe thing is to restart the entire lookup.
418              */
419             goto restart_all;
420         }
421     }
422 
423     /* align to page_size */
424     paddr = (pte & a20_mask & PG_ADDRESS_MASK & ~(page_size - 1))
425           | (addr & (page_size - 1));
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;
466     out->prot = prot;
467     out->page_size = page_size;
468     return true;
469 
470     int error_code;
471  do_fault_rsvd:
472     error_code = PG_ERROR_RSVD_MASK;
473     goto do_fault_cont;
474  do_fault_protect:
475     error_code = PG_ERROR_P_MASK;
476     goto do_fault_cont;
477  do_fault_pk_protect:
478     assert(access_type != MMU_INST_FETCH);
479     error_code = PG_ERROR_PK_MASK | PG_ERROR_P_MASK;
480     goto do_fault_cont;
481  do_fault:
482     error_code = 0;
483  do_fault_cont:
484     if (is_user) {
485         error_code |= PG_ERROR_U_MASK;
486     }
487     switch (access_type) {
488     case MMU_DATA_LOAD:
489         break;
490     case MMU_DATA_STORE:
491         error_code |= PG_ERROR_W_MASK;
492         break;
493     case MMU_INST_FETCH:
494         if (pg_mode & (PG_MODE_NXE | PG_MODE_SMEP)) {
495             error_code |= PG_ERROR_I_D_MASK;
496         }
497         break;
498     }
499     *err = (TranslateFault){
500         .exception_index = EXCP0E_PAGE,
501         .error_code = error_code,
502         .cr2 = addr,
503     };
504     return false;
505 }
506 
507 static G_NORETURN void raise_stage2(CPUX86State *env, TranslateFault *err,
508                                     uintptr_t retaddr)
509 {
510     uint64_t exit_info_1 = err->error_code;
511 
512     switch (err->stage2) {
513     case S2_GPT:
514         exit_info_1 |= SVM_NPTEXIT_GPT;
515         break;
516     case S2_GPA:
517         exit_info_1 |= SVM_NPTEXIT_GPA;
518         break;
519     default:
520         g_assert_not_reached();
521     }
522 
523     x86_stq_phys(env_cpu(env),
524                  env->vm_vmcb + offsetof(struct vmcb, control.exit_info_2),
525                  err->cr2);
526     cpu_vmexit(env, SVM_EXIT_NPF, exit_info_1, retaddr);
527 }
528 
529 static bool get_physical_address(CPUX86State *env, vaddr addr,
530                                  MMUAccessType access_type, int mmu_idx,
531                                  TranslateResult *out, TranslateFault *err)
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 = MMU_USER_IDX;
548             in.ptw_idx = MMU_PHYS_IDX;
549 
550             if (!mmu_translate(env, &in, out, err)) {
551                 err->stage2 = S2_GPA;
552                 return false;
553             }
554             return true;
555         }
556         break;
557 
558     default:
559         if (likely(env->cr[0] & CR0_PG_MASK)) {
560             in.cr3 = env->cr[3];
561             in.mmu_idx = mmu_idx;
562             in.ptw_idx = use_stage2 ? MMU_NESTED_IDX : MMU_PHYS_IDX;
563             in.pg_mode = get_pg_mode(env);
564 
565             if (in.pg_mode & PG_MODE_LMA) {
566                 /* test virtual address sign extension */
567                 int shift = in.pg_mode & PG_MODE_LA57 ? 56 : 47;
568                 int64_t sext = (int64_t)addr >> shift;
569                 if (sext != 0 && sext != -1) {
570                     *err = (TranslateFault){
571                         .exception_index = EXCP0D_GPF,
572                         .cr2 = addr,
573                     };
574                     return false;
575                 }
576             }
577             return mmu_translate(env, &in, out, err);
578         }
579         break;
580     }
581 
582     /* Translation disabled. */
583     out->paddr = addr & x86_get_a20_mask(env);
584 #ifdef TARGET_X86_64
585     if (!(env->hflags & HF_LMA_MASK)) {
586         /* Without long mode we can only address 32bits in real mode */
587         out->paddr = (uint32_t)out->paddr;
588     }
589 #endif
590     out->prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
591     out->page_size = TARGET_PAGE_SIZE;
592     return true;
593 }
594 
595 bool x86_cpu_tlb_fill(CPUState *cs, vaddr addr, int size,
596                       MMUAccessType access_type, int mmu_idx,
597                       bool probe, uintptr_t retaddr)
598 {
599     CPUX86State *env = cs->env_ptr;
600     TranslateResult out;
601     TranslateFault err;
602 
603     if (get_physical_address(env, addr, access_type, mmu_idx, &out, &err)) {
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