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