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