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)
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, 0);
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)
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, 0);
91 }
92 
93 static inline uint64_t ptw_ldq(const PTETranslate *in)
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, 0);
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 {
137     const int32_t a20_mask = x86_get_a20_mask(env);
138     const target_ulong addr = in->addr;
139     const int pg_mode = in->pg_mode;
140     const bool is_user = (in->mmu_idx == MMU_USER_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) +
168                             (((addr >> 48) & 0x1ff) << 3)) & a20_mask;
169                 if (!ptw_translate(&pte_trans, pte_addr)) {
170                     return false;
171                 }
172             restart_5:
173                 pte = ptw_ldq(&pte_trans);
174                 if (!(pte & PG_PRESENT_MASK)) {
175                     goto do_fault;
176                 }
177                 if (pte & (rsvd_mask | PG_PSE_MASK)) {
178                     goto do_fault_rsvd;
179                 }
180                 if (!ptw_setl(&pte_trans, pte, PG_ACCESSED_MASK)) {
181                     goto restart_5;
182                 }
183                 ptep = pte ^ PG_NX_MASK;
184             } else {
185                 pte = in->cr3;
186                 ptep = PG_NX_MASK | PG_USER_MASK | PG_RW_MASK;
187             }
188 
189             /*
190              * Page table level 4
191              */
192             pte_addr = ((pte & PG_ADDRESS_MASK) +
193                         (((addr >> 39) & 0x1ff) << 3)) & a20_mask;
194             if (!ptw_translate(&pte_trans, pte_addr)) {
195                 return false;
196             }
197         restart_4:
198             pte = ptw_ldq(&pte_trans);
199             if (!(pte & PG_PRESENT_MASK)) {
200                 goto do_fault;
201             }
202             if (pte & (rsvd_mask | PG_PSE_MASK)) {
203                 goto do_fault_rsvd;
204             }
205             if (!ptw_setl(&pte_trans, pte, PG_ACCESSED_MASK)) {
206                 goto restart_4;
207             }
208             ptep &= pte ^ PG_NX_MASK;
209 
210             /*
211              * Page table level 3
212              */
213             pte_addr = ((pte & PG_ADDRESS_MASK) +
214                         (((addr >> 30) & 0x1ff) << 3)) & a20_mask;
215             if (!ptw_translate(&pte_trans, pte_addr)) {
216                 return false;
217             }
218         restart_3_lma:
219             pte = ptw_ldq(&pte_trans);
220             if (!(pte & PG_PRESENT_MASK)) {
221                 goto do_fault;
222             }
223             if (pte & rsvd_mask) {
224                 goto do_fault_rsvd;
225             }
226             if (!ptw_setl(&pte_trans, pte, PG_ACCESSED_MASK)) {
227                 goto restart_3_lma;
228             }
229             ptep &= pte ^ PG_NX_MASK;
230             if (pte & PG_PSE_MASK) {
231                 /* 1 GB page */
232                 page_size = 1024 * 1024 * 1024;
233                 goto do_check_protect;
234             }
235         } else
236 #endif
237         {
238             /*
239              * Page table level 3
240              */
241             pte_addr = ((in->cr3 & ~0x1f) + ((addr >> 27) & 0x18)) & a20_mask;
242             if (!ptw_translate(&pte_trans, pte_addr)) {
243                 return false;
244             }
245             rsvd_mask |= PG_HI_USER_MASK;
246         restart_3_nolma:
247             pte = ptw_ldq(&pte_trans);
248             if (!(pte & PG_PRESENT_MASK)) {
249                 goto do_fault;
250             }
251             if (pte & (rsvd_mask | PG_NX_MASK)) {
252                 goto do_fault_rsvd;
253             }
254             if (!ptw_setl(&pte_trans, pte, PG_ACCESSED_MASK)) {
255                 goto restart_3_nolma;
256             }
257             ptep = PG_NX_MASK | PG_USER_MASK | PG_RW_MASK;
258         }
259 
260         /*
261          * Page table level 2
262          */
263         pte_addr = ((pte & PG_ADDRESS_MASK) +
264                     (((addr >> 21) & 0x1ff) << 3)) & a20_mask;
265         if (!ptw_translate(&pte_trans, pte_addr)) {
266             return false;
267         }
268     restart_2_pae:
269         pte = ptw_ldq(&pte_trans);
270         if (!(pte & PG_PRESENT_MASK)) {
271             goto do_fault;
272         }
273         if (pte & rsvd_mask) {
274             goto do_fault_rsvd;
275         }
276         if (pte & PG_PSE_MASK) {
277             /* 2 MB page */
278             page_size = 2048 * 1024;
279             ptep &= pte ^ PG_NX_MASK;
280             goto do_check_protect;
281         }
282         if (!ptw_setl(&pte_trans, pte, PG_ACCESSED_MASK)) {
283             goto restart_2_pae;
284         }
285         ptep &= pte ^ PG_NX_MASK;
286 
287         /*
288          * Page table level 1
289          */
290         pte_addr = ((pte & PG_ADDRESS_MASK) +
291                     (((addr >> 12) & 0x1ff) << 3)) & a20_mask;
292         if (!ptw_translate(&pte_trans, pte_addr)) {
293             return false;
294         }
295         pte = ptw_ldq(&pte_trans);
296         if (!(pte & PG_PRESENT_MASK)) {
297             goto do_fault;
298         }
299         if (pte & rsvd_mask) {
300             goto do_fault_rsvd;
301         }
302         /* combine pde and pte nx, user and rw protections */
303         ptep &= pte ^ PG_NX_MASK;
304         page_size = 4096;
305     } else {
306         /*
307          * Page table level 2
308          */
309         pte_addr = ((in->cr3 & ~0xfff) + ((addr >> 20) & 0xffc)) & a20_mask;
310         if (!ptw_translate(&pte_trans, pte_addr)) {
311             return false;
312         }
313     restart_2_nopae:
314         pte = ptw_ldl(&pte_trans);
315         if (!(pte & PG_PRESENT_MASK)) {
316             goto do_fault;
317         }
318         ptep = pte | PG_NX_MASK;
319 
320         /* if PSE bit is set, then we use a 4MB page */
321         if ((pte & PG_PSE_MASK) && (pg_mode & PG_MODE_PSE)) {
322             page_size = 4096 * 1024;
323             /*
324              * Bits 20-13 provide bits 39-32 of the address, bit 21 is reserved.
325              * Leave bits 20-13 in place for setting accessed/dirty bits below.
326              */
327             pte = (uint32_t)pte | ((pte & 0x1fe000LL) << (32 - 13));
328             rsvd_mask = 0x200000;
329             goto do_check_protect_pse36;
330         }
331         if (!ptw_setl(&pte_trans, pte, PG_ACCESSED_MASK)) {
332             goto restart_2_nopae;
333         }
334 
335         /*
336          * Page table level 1
337          */
338         pte_addr = ((pte & ~0xfffu) + ((addr >> 10) & 0xffc)) & a20_mask;
339         if (!ptw_translate(&pte_trans, pte_addr)) {
340             return false;
341         }
342         pte = ptw_ldl(&pte_trans);
343         if (!(pte & PG_PRESENT_MASK)) {
344             goto do_fault;
345         }
346         /* combine pde and pte user and rw protections */
347         ptep &= pte | PG_NX_MASK;
348         page_size = 4096;
349         rsvd_mask = 0;
350     }
351 
352 do_check_protect:
353     rsvd_mask |= (page_size - 1) & PG_ADDRESS_MASK & ~PG_PSE_PAT_MASK;
354 do_check_protect_pse36:
355     if (pte & rsvd_mask) {
356         goto do_fault_rsvd;
357     }
358     ptep ^= PG_NX_MASK;
359 
360     /* can the page can be put in the TLB?  prot will tell us */
361     if (is_user && !(ptep & PG_USER_MASK)) {
362         goto do_fault_protect;
363     }
364 
365     int prot = 0;
366     if (in->mmu_idx != MMU_KSMAP_IDX || !(ptep & PG_USER_MASK)) {
367         prot |= PAGE_READ;
368         if ((ptep & PG_RW_MASK) || !(is_user || (pg_mode & PG_MODE_WP))) {
369             prot |= PAGE_WRITE;
370         }
371     }
372     if (!(ptep & PG_NX_MASK) &&
373         (is_user ||
374          !((pg_mode & PG_MODE_SMEP) && (ptep & PG_USER_MASK)))) {
375         prot |= PAGE_EXEC;
376     }
377 
378     if (ptep & PG_USER_MASK) {
379         pkr = pg_mode & PG_MODE_PKE ? env->pkru : 0;
380     } else {
381         pkr = pg_mode & PG_MODE_PKS ? env->pkrs : 0;
382     }
383     if (pkr) {
384         uint32_t pk = (pte & PG_PKRU_MASK) >> PG_PKRU_BIT;
385         uint32_t pkr_ad = (pkr >> pk * 2) & 1;
386         uint32_t pkr_wd = (pkr >> pk * 2) & 2;
387         uint32_t pkr_prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
388 
389         if (pkr_ad) {
390             pkr_prot &= ~(PAGE_READ | PAGE_WRITE);
391         } else if (pkr_wd && (is_user || (pg_mode & PG_MODE_WP))) {
392             pkr_prot &= ~PAGE_WRITE;
393         }
394         if ((pkr_prot & (1 << access_type)) == 0) {
395             goto do_fault_pk_protect;
396         }
397         prot &= pkr_prot;
398     }
399 
400     if ((prot & (1 << access_type)) == 0) {
401         goto do_fault_protect;
402     }
403 
404     /* yes, it can! */
405     {
406         uint32_t set = PG_ACCESSED_MASK;
407         if (access_type == MMU_DATA_STORE) {
408             set |= PG_DIRTY_MASK;
409         } else if (!(pte & PG_DIRTY_MASK)) {
410             /*
411              * Only set write access if already dirty...
412              * otherwise wait for dirty access.
413              */
414             prot &= ~PAGE_WRITE;
415         }
416         if (!ptw_setl(&pte_trans, pte, set)) {
417             /*
418              * We can arrive here from any of 3 levels and 2 formats.
419              * The only safe thing is to restart the entire lookup.
420              */
421             goto restart_all;
422         }
423     }
424 
425     /* align to page_size */
426     paddr = (pte & a20_mask & PG_ADDRESS_MASK & ~(page_size - 1))
427           | (addr & (page_size - 1));
428 
429     if (in->ptw_idx == MMU_NESTED_IDX) {
430         CPUTLBEntryFull *full;
431         int flags, nested_page_size;
432 
433         flags = probe_access_full(env, paddr, 0, access_type,
434                                   MMU_NESTED_IDX, true,
435                                   &pte_trans.haddr, &full, 0);
436         if (unlikely(flags & TLB_INVALID_MASK)) {
437             *err = (TranslateFault){
438                 .error_code = env->error_code,
439                 .cr2 = paddr,
440                 .stage2 = S2_GPA,
441             };
442             return false;
443         }
444 
445         /* Merge stage1 & stage2 protection bits. */
446         prot &= full->prot;
447 
448         /* Re-verify resulting protection. */
449         if ((prot & (1 << access_type)) == 0) {
450             goto do_fault_protect;
451         }
452 
453         /* Merge stage1 & stage2 addresses to final physical address. */
454         nested_page_size = 1 << full->lg_page_size;
455         paddr = (full->phys_addr & ~(nested_page_size - 1))
456               | (paddr & (nested_page_size - 1));
457 
458         /*
459          * Use the larger of stage1 & stage2 page sizes, so that
460          * invalidation works.
461          */
462         if (nested_page_size > page_size) {
463             page_size = nested_page_size;
464         }
465     }
466 
467     out->paddr = paddr;
468     out->prot = prot;
469     out->page_size = page_size;
470     return true;
471 
472  do_fault_rsvd:
473     error_code = PG_ERROR_RSVD_MASK;
474     goto do_fault_cont;
475  do_fault_protect:
476     error_code = PG_ERROR_P_MASK;
477     goto do_fault_cont;
478  do_fault_pk_protect:
479     assert(access_type != MMU_INST_FETCH);
480     error_code = PG_ERROR_PK_MASK | PG_ERROR_P_MASK;
481     goto do_fault_cont;
482  do_fault:
483     error_code = 0;
484  do_fault_cont:
485     if (is_user) {
486         error_code |= PG_ERROR_U_MASK;
487     }
488     switch (access_type) {
489     case MMU_DATA_LOAD:
490         break;
491     case MMU_DATA_STORE:
492         error_code |= PG_ERROR_W_MASK;
493         break;
494     case MMU_INST_FETCH:
495         if (pg_mode & (PG_MODE_NXE | PG_MODE_SMEP)) {
496             error_code |= PG_ERROR_I_D_MASK;
497         }
498         break;
499     }
500     *err = (TranslateFault){
501         .exception_index = EXCP0E_PAGE,
502         .error_code = error_code,
503         .cr2 = addr,
504     };
505     return false;
506 }
507 
508 static G_NORETURN void raise_stage2(CPUX86State *env, TranslateFault *err,
509                                     uintptr_t retaddr)
510 {
511     uint64_t exit_info_1 = err->error_code;
512 
513     switch (err->stage2) {
514     case S2_GPT:
515         exit_info_1 |= SVM_NPTEXIT_GPT;
516         break;
517     case S2_GPA:
518         exit_info_1 |= SVM_NPTEXIT_GPA;
519         break;
520     default:
521         g_assert_not_reached();
522     }
523 
524     x86_stq_phys(env_cpu(env),
525                  env->vm_vmcb + offsetof(struct vmcb, control.exit_info_2),
526                  err->cr2);
527     cpu_vmexit(env, SVM_EXIT_NPF, exit_info_1, retaddr);
528 }
529 
530 static bool get_physical_address(CPUX86State *env, vaddr addr,
531                                  MMUAccessType access_type, int mmu_idx,
532                                  TranslateResult *out, TranslateFault *err)
533 {
534     TranslateParams in;
535     bool use_stage2 = env->hflags2 & HF2_NPT_MASK;
536 
537     in.addr = addr;
538     in.access_type = access_type;
539 
540     switch (mmu_idx) {
541     case MMU_PHYS_IDX:
542         break;
543 
544     case MMU_NESTED_IDX:
545         if (likely(use_stage2)) {
546             in.cr3 = env->nested_cr3;
547             in.pg_mode = env->nested_pg_mode;
548             in.mmu_idx = MMU_USER_IDX;
549             in.ptw_idx = MMU_PHYS_IDX;
550 
551             if (!mmu_translate(env, &in, out, err)) {
552                 err->stage2 = S2_GPA;
553                 return false;
554             }
555             return true;
556         }
557         break;
558 
559     default:
560         if (likely(env->cr[0] & CR0_PG_MASK)) {
561             in.cr3 = env->cr[3];
562             in.mmu_idx = mmu_idx;
563             in.ptw_idx = use_stage2 ? MMU_NESTED_IDX : MMU_PHYS_IDX;
564             in.pg_mode = get_pg_mode(env);
565 
566             if (in.pg_mode & PG_MODE_LMA) {
567                 /* test virtual address sign extension */
568                 int shift = in.pg_mode & PG_MODE_LA57 ? 56 : 47;
569                 int64_t sext = (int64_t)addr >> shift;
570                 if (sext != 0 && sext != -1) {
571                     *err = (TranslateFault){
572                         .exception_index = EXCP0D_GPF,
573                         .cr2 = addr,
574                     };
575                     return false;
576                 }
577             }
578             return mmu_translate(env, &in, out, err);
579         }
580         break;
581     }
582 
583     /* Translation disabled. */
584     out->paddr = addr & x86_get_a20_mask(env);
585 #ifdef TARGET_X86_64
586     if (!(env->hflags & HF_LMA_MASK)) {
587         /* Without long mode we can only address 32bits in real mode */
588         out->paddr = (uint32_t)out->paddr;
589     }
590 #endif
591     out->prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
592     out->page_size = TARGET_PAGE_SIZE;
593     return true;
594 }
595 
596 bool x86_cpu_tlb_fill(CPUState *cs, vaddr addr, int size,
597                       MMUAccessType access_type, int mmu_idx,
598                       bool probe, uintptr_t retaddr)
599 {
600     CPUX86State *env = cpu_env(cs);
601     TranslateResult out;
602     TranslateFault err;
603 
604     if (get_physical_address(env, addr, access_type, mmu_idx, &out, &err)) {
605         /*
606          * Even if 4MB pages, we map only one 4KB page in the cache to
607          * avoid filling it too fast.
608          */
609         assert(out.prot & (1 << access_type));
610         tlb_set_page_with_attrs(cs, addr & TARGET_PAGE_MASK,
611                                 out.paddr & TARGET_PAGE_MASK,
612                                 cpu_get_mem_attrs(env),
613                                 out.prot, mmu_idx, out.page_size);
614         return true;
615     }
616 
617     if (probe) {
618         /* This will be used if recursing for stage2 translation. */
619         env->error_code = err.error_code;
620         return false;
621     }
622 
623     if (err.stage2 != S2_NONE) {
624         raise_stage2(env, &err, retaddr);
625     }
626 
627     if (env->intercept_exceptions & (1 << err.exception_index)) {
628         /* cr2 is not modified in case of exceptions */
629         x86_stq_phys(cs, env->vm_vmcb +
630                      offsetof(struct vmcb, control.exit_info_2),
631                      err.cr2);
632     } else {
633         env->cr[2] = err.cr2;
634     }
635     raise_exception_err_ra(env, err.exception_index, err.error_code, retaddr);
636 }
637 
638 G_NORETURN void x86_cpu_do_unaligned_access(CPUState *cs, vaddr vaddr,
639                                             MMUAccessType access_type,
640                                             int mmu_idx, uintptr_t retaddr)
641 {
642     X86CPU *cpu = X86_CPU(cs);
643     handle_unaligned_access(&cpu->env, vaddr, access_type, retaddr);
644 }
645