xref: /openbmc/qemu/target/riscv/cpu_helper.c (revision 0774a7a1)
1 /*
2  * RISC-V CPU helpers for qemu.
3  *
4  * Copyright (c) 2016-2017 Sagar Karandikar, sagark@eecs.berkeley.edu
5  * Copyright (c) 2017-2018 SiFive, Inc.
6  *
7  * This program is free software; you can redistribute it and/or modify it
8  * under the terms and conditions of the GNU General Public License,
9  * version 2 or later, as published by the Free Software Foundation.
10  *
11  * This program is distributed in the hope it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
14  * more details.
15  *
16  * You should have received a copy of the GNU General Public License along with
17  * this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19 
20 #include "qemu/osdep.h"
21 #include "qemu/log.h"
22 #include "qemu/main-loop.h"
23 #include "cpu.h"
24 #include "exec/exec-all.h"
25 #include "tcg/tcg-op.h"
26 #include "trace.h"
27 #include "semihosting/common-semi.h"
28 
29 int riscv_cpu_mmu_index(CPURISCVState *env, bool ifetch)
30 {
31 #ifdef CONFIG_USER_ONLY
32     return 0;
33 #else
34     return env->priv;
35 #endif
36 }
37 
38 static RISCVMXL cpu_get_xl(CPURISCVState *env)
39 {
40 #if defined(TARGET_RISCV32)
41     return MXL_RV32;
42 #elif defined(CONFIG_USER_ONLY)
43     return MXL_RV64;
44 #else
45     RISCVMXL xl = riscv_cpu_mxl(env);
46 
47     /*
48      * When emulating a 32-bit-only cpu, use RV32.
49      * When emulating a 64-bit cpu, and MXL has been reduced to RV32,
50      * MSTATUSH doesn't have UXL/SXL, therefore XLEN cannot be widened
51      * back to RV64 for lower privs.
52      */
53     if (xl != MXL_RV32) {
54         switch (env->priv) {
55         case PRV_M:
56             break;
57         case PRV_U:
58             xl = get_field(env->mstatus, MSTATUS64_UXL);
59             break;
60         default: /* PRV_S | PRV_H */
61             xl = get_field(env->mstatus, MSTATUS64_SXL);
62             break;
63         }
64     }
65     return xl;
66 #endif
67 }
68 
69 void cpu_get_tb_cpu_state(CPURISCVState *env, target_ulong *pc,
70                           target_ulong *cs_base, uint32_t *pflags)
71 {
72     uint32_t flags = 0;
73 
74     *pc = env->pc;
75     *cs_base = 0;
76 
77     if (riscv_has_ext(env, RVV)) {
78         uint32_t vlmax = vext_get_vlmax(env_archcpu(env), env->vtype);
79         bool vl_eq_vlmax = (env->vstart == 0) && (vlmax == env->vl);
80         flags = FIELD_DP32(flags, TB_FLAGS, VILL,
81                     FIELD_EX64(env->vtype, VTYPE, VILL));
82         flags = FIELD_DP32(flags, TB_FLAGS, SEW,
83                     FIELD_EX64(env->vtype, VTYPE, VSEW));
84         flags = FIELD_DP32(flags, TB_FLAGS, LMUL,
85                     FIELD_EX64(env->vtype, VTYPE, VLMUL));
86         flags = FIELD_DP32(flags, TB_FLAGS, VL_EQ_VLMAX, vl_eq_vlmax);
87     } else {
88         flags = FIELD_DP32(flags, TB_FLAGS, VILL, 1);
89     }
90 
91 #ifdef CONFIG_USER_ONLY
92     flags |= TB_FLAGS_MSTATUS_FS;
93 #else
94     flags |= cpu_mmu_index(env, 0);
95     if (riscv_cpu_fp_enabled(env)) {
96         flags |= env->mstatus & MSTATUS_FS;
97     }
98 
99     if (riscv_has_ext(env, RVH)) {
100         if (env->priv == PRV_M ||
101             (env->priv == PRV_S && !riscv_cpu_virt_enabled(env)) ||
102             (env->priv == PRV_U && !riscv_cpu_virt_enabled(env) &&
103                 get_field(env->hstatus, HSTATUS_HU))) {
104             flags = FIELD_DP32(flags, TB_FLAGS, HLSX, 1);
105         }
106 
107         flags = FIELD_DP32(flags, TB_FLAGS, MSTATUS_HS_FS,
108                            get_field(env->mstatus_hs, MSTATUS_FS));
109     }
110     if (riscv_has_ext(env, RVJ)) {
111         int priv = flags & TB_FLAGS_PRIV_MMU_MASK;
112         bool pm_enabled = false;
113         switch (priv) {
114         case PRV_U:
115             pm_enabled = env->mmte & U_PM_ENABLE;
116             break;
117         case PRV_S:
118             pm_enabled = env->mmte & S_PM_ENABLE;
119             break;
120         case PRV_M:
121             pm_enabled = env->mmte & M_PM_ENABLE;
122             break;
123         default:
124             g_assert_not_reached();
125         }
126         flags = FIELD_DP32(flags, TB_FLAGS, PM_ENABLED, pm_enabled);
127     }
128 #endif
129 
130     flags = FIELD_DP32(flags, TB_FLAGS, XL, cpu_get_xl(env));
131 
132     *pflags = flags;
133 }
134 
135 #ifndef CONFIG_USER_ONLY
136 static int riscv_cpu_local_irq_pending(CPURISCVState *env)
137 {
138     target_ulong irqs;
139 
140     target_ulong mstatus_mie = get_field(env->mstatus, MSTATUS_MIE);
141     target_ulong mstatus_sie = get_field(env->mstatus, MSTATUS_SIE);
142     target_ulong hs_mstatus_sie = get_field(env->mstatus_hs, MSTATUS_SIE);
143 
144     target_ulong pending = env->mip & env->mie &
145                                ~(MIP_VSSIP | MIP_VSTIP | MIP_VSEIP);
146     target_ulong vspending = (env->mip & env->mie &
147                               (MIP_VSSIP | MIP_VSTIP | MIP_VSEIP));
148 
149     target_ulong mie    = env->priv < PRV_M ||
150                           (env->priv == PRV_M && mstatus_mie);
151     target_ulong sie    = env->priv < PRV_S ||
152                           (env->priv == PRV_S && mstatus_sie);
153     target_ulong hs_sie = env->priv < PRV_S ||
154                           (env->priv == PRV_S && hs_mstatus_sie);
155 
156     if (riscv_cpu_virt_enabled(env)) {
157         target_ulong pending_hs_irq = pending & -hs_sie;
158 
159         if (pending_hs_irq) {
160             riscv_cpu_set_force_hs_excep(env, FORCE_HS_EXCEP);
161             return ctz64(pending_hs_irq);
162         }
163 
164         pending = vspending;
165     }
166 
167     irqs = (pending & ~env->mideleg & -mie) | (pending &  env->mideleg & -sie);
168 
169     if (irqs) {
170         return ctz64(irqs); /* since non-zero */
171     } else {
172         return RISCV_EXCP_NONE; /* indicates no pending interrupt */
173     }
174 }
175 
176 bool riscv_cpu_exec_interrupt(CPUState *cs, int interrupt_request)
177 {
178     if (interrupt_request & CPU_INTERRUPT_HARD) {
179         RISCVCPU *cpu = RISCV_CPU(cs);
180         CPURISCVState *env = &cpu->env;
181         int interruptno = riscv_cpu_local_irq_pending(env);
182         if (interruptno >= 0) {
183             cs->exception_index = RISCV_EXCP_INT_FLAG | interruptno;
184             riscv_cpu_do_interrupt(cs);
185             return true;
186         }
187     }
188     return false;
189 }
190 
191 /* Return true is floating point support is currently enabled */
192 bool riscv_cpu_fp_enabled(CPURISCVState *env)
193 {
194     if (env->mstatus & MSTATUS_FS) {
195         if (riscv_cpu_virt_enabled(env) && !(env->mstatus_hs & MSTATUS_FS)) {
196             return false;
197         }
198         return true;
199     }
200 
201     return false;
202 }
203 
204 void riscv_cpu_swap_hypervisor_regs(CPURISCVState *env)
205 {
206     uint64_t mstatus_mask = MSTATUS_MXR | MSTATUS_SUM | MSTATUS_FS |
207                             MSTATUS_SPP | MSTATUS_SPIE | MSTATUS_SIE |
208                             MSTATUS64_UXL;
209     bool current_virt = riscv_cpu_virt_enabled(env);
210 
211     g_assert(riscv_has_ext(env, RVH));
212 
213     if (current_virt) {
214         /* Current V=1 and we are about to change to V=0 */
215         env->vsstatus = env->mstatus & mstatus_mask;
216         env->mstatus &= ~mstatus_mask;
217         env->mstatus |= env->mstatus_hs;
218 
219         env->vstvec = env->stvec;
220         env->stvec = env->stvec_hs;
221 
222         env->vsscratch = env->sscratch;
223         env->sscratch = env->sscratch_hs;
224 
225         env->vsepc = env->sepc;
226         env->sepc = env->sepc_hs;
227 
228         env->vscause = env->scause;
229         env->scause = env->scause_hs;
230 
231         env->vstval = env->stval;
232         env->stval = env->stval_hs;
233 
234         env->vsatp = env->satp;
235         env->satp = env->satp_hs;
236     } else {
237         /* Current V=0 and we are about to change to V=1 */
238         env->mstatus_hs = env->mstatus & mstatus_mask;
239         env->mstatus &= ~mstatus_mask;
240         env->mstatus |= env->vsstatus;
241 
242         env->stvec_hs = env->stvec;
243         env->stvec = env->vstvec;
244 
245         env->sscratch_hs = env->sscratch;
246         env->sscratch = env->vsscratch;
247 
248         env->sepc_hs = env->sepc;
249         env->sepc = env->vsepc;
250 
251         env->scause_hs = env->scause;
252         env->scause = env->vscause;
253 
254         env->stval_hs = env->stval;
255         env->stval = env->vstval;
256 
257         env->satp_hs = env->satp;
258         env->satp = env->vsatp;
259     }
260 }
261 
262 bool riscv_cpu_virt_enabled(CPURISCVState *env)
263 {
264     if (!riscv_has_ext(env, RVH)) {
265         return false;
266     }
267 
268     return get_field(env->virt, VIRT_ONOFF);
269 }
270 
271 void riscv_cpu_set_virt_enabled(CPURISCVState *env, bool enable)
272 {
273     if (!riscv_has_ext(env, RVH)) {
274         return;
275     }
276 
277     /* Flush the TLB on all virt mode changes. */
278     if (get_field(env->virt, VIRT_ONOFF) != enable) {
279         tlb_flush(env_cpu(env));
280     }
281 
282     env->virt = set_field(env->virt, VIRT_ONOFF, enable);
283 }
284 
285 bool riscv_cpu_force_hs_excep_enabled(CPURISCVState *env)
286 {
287     if (!riscv_has_ext(env, RVH)) {
288         return false;
289     }
290 
291     return get_field(env->virt, FORCE_HS_EXCEP);
292 }
293 
294 void riscv_cpu_set_force_hs_excep(CPURISCVState *env, bool enable)
295 {
296     if (!riscv_has_ext(env, RVH)) {
297         return;
298     }
299 
300     env->virt = set_field(env->virt, FORCE_HS_EXCEP, enable);
301 }
302 
303 bool riscv_cpu_two_stage_lookup(int mmu_idx)
304 {
305     return mmu_idx & TB_FLAGS_PRIV_HYP_ACCESS_MASK;
306 }
307 
308 int riscv_cpu_claim_interrupts(RISCVCPU *cpu, uint32_t interrupts)
309 {
310     CPURISCVState *env = &cpu->env;
311     if (env->miclaim & interrupts) {
312         return -1;
313     } else {
314         env->miclaim |= interrupts;
315         return 0;
316     }
317 }
318 
319 uint32_t riscv_cpu_update_mip(RISCVCPU *cpu, uint32_t mask, uint32_t value)
320 {
321     CPURISCVState *env = &cpu->env;
322     CPUState *cs = CPU(cpu);
323     uint32_t old = env->mip;
324     bool locked = false;
325 
326     if (!qemu_mutex_iothread_locked()) {
327         locked = true;
328         qemu_mutex_lock_iothread();
329     }
330 
331     env->mip = (env->mip & ~mask) | (value & mask);
332 
333     if (env->mip) {
334         cpu_interrupt(cs, CPU_INTERRUPT_HARD);
335     } else {
336         cpu_reset_interrupt(cs, CPU_INTERRUPT_HARD);
337     }
338 
339     if (locked) {
340         qemu_mutex_unlock_iothread();
341     }
342 
343     return old;
344 }
345 
346 void riscv_cpu_set_rdtime_fn(CPURISCVState *env, uint64_t (*fn)(uint32_t),
347                              uint32_t arg)
348 {
349     env->rdtime_fn = fn;
350     env->rdtime_fn_arg = arg;
351 }
352 
353 void riscv_cpu_set_mode(CPURISCVState *env, target_ulong newpriv)
354 {
355     if (newpriv > PRV_M) {
356         g_assert_not_reached();
357     }
358     if (newpriv == PRV_H) {
359         newpriv = PRV_U;
360     }
361     /* tlb_flush is unnecessary as mode is contained in mmu_idx */
362     env->priv = newpriv;
363 
364     /*
365      * Clear the load reservation - otherwise a reservation placed in one
366      * context/process can be used by another, resulting in an SC succeeding
367      * incorrectly. Version 2.2 of the ISA specification explicitly requires
368      * this behaviour, while later revisions say that the kernel "should" use
369      * an SC instruction to force the yielding of a load reservation on a
370      * preemptive context switch. As a result, do both.
371      */
372     env->load_res = -1;
373 }
374 
375 /*
376  * get_physical_address_pmp - check PMP permission for this physical address
377  *
378  * Match the PMP region and check permission for this physical address and it's
379  * TLB page. Returns 0 if the permission checking was successful
380  *
381  * @env: CPURISCVState
382  * @prot: The returned protection attributes
383  * @tlb_size: TLB page size containing addr. It could be modified after PMP
384  *            permission checking. NULL if not set TLB page for addr.
385  * @addr: The physical address to be checked permission
386  * @access_type: The type of MMU access
387  * @mode: Indicates current privilege level.
388  */
389 static int get_physical_address_pmp(CPURISCVState *env, int *prot,
390                                     target_ulong *tlb_size, hwaddr addr,
391                                     int size, MMUAccessType access_type,
392                                     int mode)
393 {
394     pmp_priv_t pmp_priv;
395     target_ulong tlb_size_pmp = 0;
396 
397     if (!riscv_feature(env, RISCV_FEATURE_PMP)) {
398         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
399         return TRANSLATE_SUCCESS;
400     }
401 
402     if (!pmp_hart_has_privs(env, addr, size, 1 << access_type, &pmp_priv,
403                             mode)) {
404         *prot = 0;
405         return TRANSLATE_PMP_FAIL;
406     }
407 
408     *prot = pmp_priv_to_page_prot(pmp_priv);
409     if (tlb_size != NULL) {
410         if (pmp_is_range_in_tlb(env, addr & ~(*tlb_size - 1), &tlb_size_pmp)) {
411             *tlb_size = tlb_size_pmp;
412         }
413     }
414 
415     return TRANSLATE_SUCCESS;
416 }
417 
418 /* get_physical_address - get the physical address for this virtual address
419  *
420  * Do a page table walk to obtain the physical address corresponding to a
421  * virtual address. Returns 0 if the translation was successful
422  *
423  * Adapted from Spike's mmu_t::translate and mmu_t::walk
424  *
425  * @env: CPURISCVState
426  * @physical: This will be set to the calculated physical address
427  * @prot: The returned protection attributes
428  * @addr: The virtual address to be translated
429  * @fault_pte_addr: If not NULL, this will be set to fault pte address
430  *                  when a error occurs on pte address translation.
431  *                  This will already be shifted to match htval.
432  * @access_type: The type of MMU access
433  * @mmu_idx: Indicates current privilege level
434  * @first_stage: Are we in first stage translation?
435  *               Second stage is used for hypervisor guest translation
436  * @two_stage: Are we going to perform two stage translation
437  * @is_debug: Is this access from a debugger or the monitor?
438  */
439 static int get_physical_address(CPURISCVState *env, hwaddr *physical,
440                                 int *prot, target_ulong addr,
441                                 target_ulong *fault_pte_addr,
442                                 int access_type, int mmu_idx,
443                                 bool first_stage, bool two_stage,
444                                 bool is_debug)
445 {
446     /* NOTE: the env->pc value visible here will not be
447      * correct, but the value visible to the exception handler
448      * (riscv_cpu_do_interrupt) is correct */
449     MemTxResult res;
450     MemTxAttrs attrs = MEMTXATTRS_UNSPECIFIED;
451     int mode = mmu_idx & TB_FLAGS_PRIV_MMU_MASK;
452     bool use_background = false;
453 
454     /*
455      * Check if we should use the background registers for the two
456      * stage translation. We don't need to check if we actually need
457      * two stage translation as that happened before this function
458      * was called. Background registers will be used if the guest has
459      * forced a two stage translation to be on (in HS or M mode).
460      */
461     if (!riscv_cpu_virt_enabled(env) && two_stage) {
462         use_background = true;
463     }
464 
465     /* MPRV does not affect the virtual-machine load/store
466        instructions, HLV, HLVX, and HSV. */
467     if (riscv_cpu_two_stage_lookup(mmu_idx)) {
468         mode = get_field(env->hstatus, HSTATUS_SPVP);
469     } else if (mode == PRV_M && access_type != MMU_INST_FETCH) {
470         if (get_field(env->mstatus, MSTATUS_MPRV)) {
471             mode = get_field(env->mstatus, MSTATUS_MPP);
472         }
473     }
474 
475     if (first_stage == false) {
476         /* We are in stage 2 translation, this is similar to stage 1. */
477         /* Stage 2 is always taken as U-mode */
478         mode = PRV_U;
479     }
480 
481     if (mode == PRV_M || !riscv_feature(env, RISCV_FEATURE_MMU)) {
482         *physical = addr;
483         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
484         return TRANSLATE_SUCCESS;
485     }
486 
487     *prot = 0;
488 
489     hwaddr base;
490     int levels, ptidxbits, ptesize, vm, sum, mxr, widened;
491 
492     if (first_stage == true) {
493         mxr = get_field(env->mstatus, MSTATUS_MXR);
494     } else {
495         mxr = get_field(env->vsstatus, MSTATUS_MXR);
496     }
497 
498     if (first_stage == true) {
499         if (use_background) {
500             if (riscv_cpu_mxl(env) == MXL_RV32) {
501                 base = (hwaddr)get_field(env->vsatp, SATP32_PPN) << PGSHIFT;
502                 vm = get_field(env->vsatp, SATP32_MODE);
503             } else {
504                 base = (hwaddr)get_field(env->vsatp, SATP64_PPN) << PGSHIFT;
505                 vm = get_field(env->vsatp, SATP64_MODE);
506             }
507         } else {
508             if (riscv_cpu_mxl(env) == MXL_RV32) {
509                 base = (hwaddr)get_field(env->satp, SATP32_PPN) << PGSHIFT;
510                 vm = get_field(env->satp, SATP32_MODE);
511             } else {
512                 base = (hwaddr)get_field(env->satp, SATP64_PPN) << PGSHIFT;
513                 vm = get_field(env->satp, SATP64_MODE);
514             }
515         }
516         widened = 0;
517     } else {
518         if (riscv_cpu_mxl(env) == MXL_RV32) {
519             base = (hwaddr)get_field(env->hgatp, SATP32_PPN) << PGSHIFT;
520             vm = get_field(env->hgatp, SATP32_MODE);
521         } else {
522             base = (hwaddr)get_field(env->hgatp, SATP64_PPN) << PGSHIFT;
523             vm = get_field(env->hgatp, SATP64_MODE);
524         }
525         widened = 2;
526     }
527     /* status.SUM will be ignored if execute on background */
528     sum = get_field(env->mstatus, MSTATUS_SUM) || use_background || is_debug;
529     switch (vm) {
530     case VM_1_10_SV32:
531       levels = 2; ptidxbits = 10; ptesize = 4; break;
532     case VM_1_10_SV39:
533       levels = 3; ptidxbits = 9; ptesize = 8; break;
534     case VM_1_10_SV48:
535       levels = 4; ptidxbits = 9; ptesize = 8; break;
536     case VM_1_10_SV57:
537       levels = 5; ptidxbits = 9; ptesize = 8; break;
538     case VM_1_10_MBARE:
539         *physical = addr;
540         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
541         return TRANSLATE_SUCCESS;
542     default:
543       g_assert_not_reached();
544     }
545 
546     CPUState *cs = env_cpu(env);
547     int va_bits = PGSHIFT + levels * ptidxbits + widened;
548     target_ulong mask, masked_msbs;
549 
550     if (TARGET_LONG_BITS > (va_bits - 1)) {
551         mask = (1L << (TARGET_LONG_BITS - (va_bits - 1))) - 1;
552     } else {
553         mask = 0;
554     }
555     masked_msbs = (addr >> (va_bits - 1)) & mask;
556 
557     if (masked_msbs != 0 && masked_msbs != mask) {
558         return TRANSLATE_FAIL;
559     }
560 
561     int ptshift = (levels - 1) * ptidxbits;
562     int i;
563 
564 #if !TCG_OVERSIZED_GUEST
565 restart:
566 #endif
567     for (i = 0; i < levels; i++, ptshift -= ptidxbits) {
568         target_ulong idx;
569         if (i == 0) {
570             idx = (addr >> (PGSHIFT + ptshift)) &
571                            ((1 << (ptidxbits + widened)) - 1);
572         } else {
573             idx = (addr >> (PGSHIFT + ptshift)) &
574                            ((1 << ptidxbits) - 1);
575         }
576 
577         /* check that physical address of PTE is legal */
578         hwaddr pte_addr;
579 
580         if (two_stage && first_stage) {
581             int vbase_prot;
582             hwaddr vbase;
583 
584             /* Do the second stage translation on the base PTE address. */
585             int vbase_ret = get_physical_address(env, &vbase, &vbase_prot,
586                                                  base, NULL, MMU_DATA_LOAD,
587                                                  mmu_idx, false, true,
588                                                  is_debug);
589 
590             if (vbase_ret != TRANSLATE_SUCCESS) {
591                 if (fault_pte_addr) {
592                     *fault_pte_addr = (base + idx * ptesize) >> 2;
593                 }
594                 return TRANSLATE_G_STAGE_FAIL;
595             }
596 
597             pte_addr = vbase + idx * ptesize;
598         } else {
599             pte_addr = base + idx * ptesize;
600         }
601 
602         int pmp_prot;
603         int pmp_ret = get_physical_address_pmp(env, &pmp_prot, NULL, pte_addr,
604                                                sizeof(target_ulong),
605                                                MMU_DATA_LOAD, PRV_S);
606         if (pmp_ret != TRANSLATE_SUCCESS) {
607             return TRANSLATE_PMP_FAIL;
608         }
609 
610         target_ulong pte;
611         if (riscv_cpu_mxl(env) == MXL_RV32) {
612             pte = address_space_ldl(cs->as, pte_addr, attrs, &res);
613         } else {
614             pte = address_space_ldq(cs->as, pte_addr, attrs, &res);
615         }
616 
617         if (res != MEMTX_OK) {
618             return TRANSLATE_FAIL;
619         }
620 
621         hwaddr ppn = pte >> PTE_PPN_SHIFT;
622 
623         if (!(pte & PTE_V)) {
624             /* Invalid PTE */
625             return TRANSLATE_FAIL;
626         } else if (!(pte & (PTE_R | PTE_W | PTE_X))) {
627             /* Inner PTE, continue walking */
628             base = ppn << PGSHIFT;
629         } else if ((pte & (PTE_R | PTE_W | PTE_X)) == PTE_W) {
630             /* Reserved leaf PTE flags: PTE_W */
631             return TRANSLATE_FAIL;
632         } else if ((pte & (PTE_R | PTE_W | PTE_X)) == (PTE_W | PTE_X)) {
633             /* Reserved leaf PTE flags: PTE_W + PTE_X */
634             return TRANSLATE_FAIL;
635         } else if ((pte & PTE_U) && ((mode != PRV_U) &&
636                    (!sum || access_type == MMU_INST_FETCH))) {
637             /* User PTE flags when not U mode and mstatus.SUM is not set,
638                or the access type is an instruction fetch */
639             return TRANSLATE_FAIL;
640         } else if (!(pte & PTE_U) && (mode != PRV_S)) {
641             /* Supervisor PTE flags when not S mode */
642             return TRANSLATE_FAIL;
643         } else if (ppn & ((1ULL << ptshift) - 1)) {
644             /* Misaligned PPN */
645             return TRANSLATE_FAIL;
646         } else if (access_type == MMU_DATA_LOAD && !((pte & PTE_R) ||
647                    ((pte & PTE_X) && mxr))) {
648             /* Read access check failed */
649             return TRANSLATE_FAIL;
650         } else if (access_type == MMU_DATA_STORE && !(pte & PTE_W)) {
651             /* Write access check failed */
652             return TRANSLATE_FAIL;
653         } else if (access_type == MMU_INST_FETCH && !(pte & PTE_X)) {
654             /* Fetch access check failed */
655             return TRANSLATE_FAIL;
656         } else {
657             /* if necessary, set accessed and dirty bits. */
658             target_ulong updated_pte = pte | PTE_A |
659                 (access_type == MMU_DATA_STORE ? PTE_D : 0);
660 
661             /* Page table updates need to be atomic with MTTCG enabled */
662             if (updated_pte != pte) {
663                 /*
664                  * - if accessed or dirty bits need updating, and the PTE is
665                  *   in RAM, then we do so atomically with a compare and swap.
666                  * - if the PTE is in IO space or ROM, then it can't be updated
667                  *   and we return TRANSLATE_FAIL.
668                  * - if the PTE changed by the time we went to update it, then
669                  *   it is no longer valid and we must re-walk the page table.
670                  */
671                 MemoryRegion *mr;
672                 hwaddr l = sizeof(target_ulong), addr1;
673                 mr = address_space_translate(cs->as, pte_addr,
674                     &addr1, &l, false, MEMTXATTRS_UNSPECIFIED);
675                 if (memory_region_is_ram(mr)) {
676                     target_ulong *pte_pa =
677                         qemu_map_ram_ptr(mr->ram_block, addr1);
678 #if TCG_OVERSIZED_GUEST
679                     /* MTTCG is not enabled on oversized TCG guests so
680                      * page table updates do not need to be atomic */
681                     *pte_pa = pte = updated_pte;
682 #else
683                     target_ulong old_pte =
684                         qatomic_cmpxchg(pte_pa, pte, updated_pte);
685                     if (old_pte != pte) {
686                         goto restart;
687                     } else {
688                         pte = updated_pte;
689                     }
690 #endif
691                 } else {
692                     /* misconfigured PTE in ROM (AD bits are not preset) or
693                      * PTE is in IO space and can't be updated atomically */
694                     return TRANSLATE_FAIL;
695                 }
696             }
697 
698             /* for superpage mappings, make a fake leaf PTE for the TLB's
699                benefit. */
700             target_ulong vpn = addr >> PGSHIFT;
701             *physical = ((ppn | (vpn & ((1L << ptshift) - 1))) << PGSHIFT) |
702                         (addr & ~TARGET_PAGE_MASK);
703 
704             /* set permissions on the TLB entry */
705             if ((pte & PTE_R) || ((pte & PTE_X) && mxr)) {
706                 *prot |= PAGE_READ;
707             }
708             if ((pte & PTE_X)) {
709                 *prot |= PAGE_EXEC;
710             }
711             /* add write permission on stores or if the page is already dirty,
712                so that we TLB miss on later writes to update the dirty bit */
713             if ((pte & PTE_W) &&
714                     (access_type == MMU_DATA_STORE || (pte & PTE_D))) {
715                 *prot |= PAGE_WRITE;
716             }
717             return TRANSLATE_SUCCESS;
718         }
719     }
720     return TRANSLATE_FAIL;
721 }
722 
723 static void raise_mmu_exception(CPURISCVState *env, target_ulong address,
724                                 MMUAccessType access_type, bool pmp_violation,
725                                 bool first_stage, bool two_stage)
726 {
727     CPUState *cs = env_cpu(env);
728     int page_fault_exceptions, vm;
729     uint64_t stap_mode;
730 
731     if (riscv_cpu_mxl(env) == MXL_RV32) {
732         stap_mode = SATP32_MODE;
733     } else {
734         stap_mode = SATP64_MODE;
735     }
736 
737     if (first_stage) {
738         vm = get_field(env->satp, stap_mode);
739     } else {
740         vm = get_field(env->hgatp, stap_mode);
741     }
742 
743     page_fault_exceptions = vm != VM_1_10_MBARE && !pmp_violation;
744 
745     switch (access_type) {
746     case MMU_INST_FETCH:
747         if (riscv_cpu_virt_enabled(env) && !first_stage) {
748             cs->exception_index = RISCV_EXCP_INST_GUEST_PAGE_FAULT;
749         } else {
750             cs->exception_index = page_fault_exceptions ?
751                 RISCV_EXCP_INST_PAGE_FAULT : RISCV_EXCP_INST_ACCESS_FAULT;
752         }
753         break;
754     case MMU_DATA_LOAD:
755         if (two_stage && !first_stage) {
756             cs->exception_index = RISCV_EXCP_LOAD_GUEST_ACCESS_FAULT;
757         } else {
758             cs->exception_index = page_fault_exceptions ?
759                 RISCV_EXCP_LOAD_PAGE_FAULT : RISCV_EXCP_LOAD_ACCESS_FAULT;
760         }
761         break;
762     case MMU_DATA_STORE:
763         if (two_stage && !first_stage) {
764             cs->exception_index = RISCV_EXCP_STORE_GUEST_AMO_ACCESS_FAULT;
765         } else {
766             cs->exception_index = page_fault_exceptions ?
767                 RISCV_EXCP_STORE_PAGE_FAULT : RISCV_EXCP_STORE_AMO_ACCESS_FAULT;
768         }
769         break;
770     default:
771         g_assert_not_reached();
772     }
773     env->badaddr = address;
774     env->two_stage_lookup = two_stage;
775 }
776 
777 hwaddr riscv_cpu_get_phys_page_debug(CPUState *cs, vaddr addr)
778 {
779     RISCVCPU *cpu = RISCV_CPU(cs);
780     CPURISCVState *env = &cpu->env;
781     hwaddr phys_addr;
782     int prot;
783     int mmu_idx = cpu_mmu_index(&cpu->env, false);
784 
785     if (get_physical_address(env, &phys_addr, &prot, addr, NULL, 0, mmu_idx,
786                              true, riscv_cpu_virt_enabled(env), true)) {
787         return -1;
788     }
789 
790     if (riscv_cpu_virt_enabled(env)) {
791         if (get_physical_address(env, &phys_addr, &prot, phys_addr, NULL,
792                                  0, mmu_idx, false, true, true)) {
793             return -1;
794         }
795     }
796 
797     return phys_addr & TARGET_PAGE_MASK;
798 }
799 
800 void riscv_cpu_do_transaction_failed(CPUState *cs, hwaddr physaddr,
801                                      vaddr addr, unsigned size,
802                                      MMUAccessType access_type,
803                                      int mmu_idx, MemTxAttrs attrs,
804                                      MemTxResult response, uintptr_t retaddr)
805 {
806     RISCVCPU *cpu = RISCV_CPU(cs);
807     CPURISCVState *env = &cpu->env;
808 
809     if (access_type == MMU_DATA_STORE) {
810         cs->exception_index = RISCV_EXCP_STORE_AMO_ACCESS_FAULT;
811     } else if (access_type == MMU_DATA_LOAD) {
812         cs->exception_index = RISCV_EXCP_LOAD_ACCESS_FAULT;
813     } else {
814         cs->exception_index = RISCV_EXCP_INST_ACCESS_FAULT;
815     }
816 
817     env->badaddr = addr;
818     env->two_stage_lookup = riscv_cpu_virt_enabled(env) ||
819                             riscv_cpu_two_stage_lookup(mmu_idx);
820     riscv_raise_exception(&cpu->env, cs->exception_index, retaddr);
821 }
822 
823 void riscv_cpu_do_unaligned_access(CPUState *cs, vaddr addr,
824                                    MMUAccessType access_type, int mmu_idx,
825                                    uintptr_t retaddr)
826 {
827     RISCVCPU *cpu = RISCV_CPU(cs);
828     CPURISCVState *env = &cpu->env;
829     switch (access_type) {
830     case MMU_INST_FETCH:
831         cs->exception_index = RISCV_EXCP_INST_ADDR_MIS;
832         break;
833     case MMU_DATA_LOAD:
834         cs->exception_index = RISCV_EXCP_LOAD_ADDR_MIS;
835         break;
836     case MMU_DATA_STORE:
837         cs->exception_index = RISCV_EXCP_STORE_AMO_ADDR_MIS;
838         break;
839     default:
840         g_assert_not_reached();
841     }
842     env->badaddr = addr;
843     env->two_stage_lookup = riscv_cpu_virt_enabled(env) ||
844                             riscv_cpu_two_stage_lookup(mmu_idx);
845     riscv_raise_exception(env, cs->exception_index, retaddr);
846 }
847 #endif /* !CONFIG_USER_ONLY */
848 
849 bool riscv_cpu_tlb_fill(CPUState *cs, vaddr address, int size,
850                         MMUAccessType access_type, int mmu_idx,
851                         bool probe, uintptr_t retaddr)
852 {
853     RISCVCPU *cpu = RISCV_CPU(cs);
854     CPURISCVState *env = &cpu->env;
855 #ifndef CONFIG_USER_ONLY
856     vaddr im_address;
857     hwaddr pa = 0;
858     int prot, prot2, prot_pmp;
859     bool pmp_violation = false;
860     bool first_stage_error = true;
861     bool two_stage_lookup = false;
862     int ret = TRANSLATE_FAIL;
863     int mode = mmu_idx;
864     /* default TLB page size */
865     target_ulong tlb_size = TARGET_PAGE_SIZE;
866 
867     env->guest_phys_fault_addr = 0;
868 
869     qemu_log_mask(CPU_LOG_MMU, "%s ad %" VADDR_PRIx " rw %d mmu_idx %d\n",
870                   __func__, address, access_type, mmu_idx);
871 
872     /* MPRV does not affect the virtual-machine load/store
873        instructions, HLV, HLVX, and HSV. */
874     if (riscv_cpu_two_stage_lookup(mmu_idx)) {
875         mode = get_field(env->hstatus, HSTATUS_SPVP);
876     } else if (mode == PRV_M && access_type != MMU_INST_FETCH &&
877                get_field(env->mstatus, MSTATUS_MPRV)) {
878         mode = get_field(env->mstatus, MSTATUS_MPP);
879         if (riscv_has_ext(env, RVH) && get_field(env->mstatus, MSTATUS_MPV)) {
880             two_stage_lookup = true;
881         }
882     }
883 
884     if (riscv_cpu_virt_enabled(env) ||
885         ((riscv_cpu_two_stage_lookup(mmu_idx) || two_stage_lookup) &&
886          access_type != MMU_INST_FETCH)) {
887         /* Two stage lookup */
888         ret = get_physical_address(env, &pa, &prot, address,
889                                    &env->guest_phys_fault_addr, access_type,
890                                    mmu_idx, true, true, false);
891 
892         /*
893          * A G-stage exception may be triggered during two state lookup.
894          * And the env->guest_phys_fault_addr has already been set in
895          * get_physical_address().
896          */
897         if (ret == TRANSLATE_G_STAGE_FAIL) {
898             first_stage_error = false;
899             access_type = MMU_DATA_LOAD;
900         }
901 
902         qemu_log_mask(CPU_LOG_MMU,
903                       "%s 1st-stage address=%" VADDR_PRIx " ret %d physical "
904                       TARGET_FMT_plx " prot %d\n",
905                       __func__, address, ret, pa, prot);
906 
907         if (ret == TRANSLATE_SUCCESS) {
908             /* Second stage lookup */
909             im_address = pa;
910 
911             ret = get_physical_address(env, &pa, &prot2, im_address, NULL,
912                                        access_type, mmu_idx, false, true,
913                                        false);
914 
915             qemu_log_mask(CPU_LOG_MMU,
916                     "%s 2nd-stage address=%" VADDR_PRIx " ret %d physical "
917                     TARGET_FMT_plx " prot %d\n",
918                     __func__, im_address, ret, pa, prot2);
919 
920             prot &= prot2;
921 
922             if (ret == TRANSLATE_SUCCESS) {
923                 ret = get_physical_address_pmp(env, &prot_pmp, &tlb_size, pa,
924                                                size, access_type, mode);
925 
926                 qemu_log_mask(CPU_LOG_MMU,
927                               "%s PMP address=" TARGET_FMT_plx " ret %d prot"
928                               " %d tlb_size " TARGET_FMT_lu "\n",
929                               __func__, pa, ret, prot_pmp, tlb_size);
930 
931                 prot &= prot_pmp;
932             }
933 
934             if (ret != TRANSLATE_SUCCESS) {
935                 /*
936                  * Guest physical address translation failed, this is a HS
937                  * level exception
938                  */
939                 first_stage_error = false;
940                 env->guest_phys_fault_addr = (im_address |
941                                               (address &
942                                                (TARGET_PAGE_SIZE - 1))) >> 2;
943             }
944         }
945     } else {
946         /* Single stage lookup */
947         ret = get_physical_address(env, &pa, &prot, address, NULL,
948                                    access_type, mmu_idx, true, false, false);
949 
950         qemu_log_mask(CPU_LOG_MMU,
951                       "%s address=%" VADDR_PRIx " ret %d physical "
952                       TARGET_FMT_plx " prot %d\n",
953                       __func__, address, ret, pa, prot);
954 
955         if (ret == TRANSLATE_SUCCESS) {
956             ret = get_physical_address_pmp(env, &prot_pmp, &tlb_size, pa,
957                                            size, access_type, mode);
958 
959             qemu_log_mask(CPU_LOG_MMU,
960                           "%s PMP address=" TARGET_FMT_plx " ret %d prot"
961                           " %d tlb_size " TARGET_FMT_lu "\n",
962                           __func__, pa, ret, prot_pmp, tlb_size);
963 
964             prot &= prot_pmp;
965         }
966     }
967 
968     if (ret == TRANSLATE_PMP_FAIL) {
969         pmp_violation = true;
970     }
971 
972     if (ret == TRANSLATE_SUCCESS) {
973         tlb_set_page(cs, address & ~(tlb_size - 1), pa & ~(tlb_size - 1),
974                      prot, mmu_idx, tlb_size);
975         return true;
976     } else if (probe) {
977         return false;
978     } else {
979         raise_mmu_exception(env, address, access_type, pmp_violation,
980                             first_stage_error,
981                             riscv_cpu_virt_enabled(env) ||
982                                 riscv_cpu_two_stage_lookup(mmu_idx));
983         riscv_raise_exception(env, cs->exception_index, retaddr);
984     }
985 
986     return true;
987 
988 #else
989     switch (access_type) {
990     case MMU_INST_FETCH:
991         cs->exception_index = RISCV_EXCP_INST_PAGE_FAULT;
992         break;
993     case MMU_DATA_LOAD:
994         cs->exception_index = RISCV_EXCP_LOAD_PAGE_FAULT;
995         break;
996     case MMU_DATA_STORE:
997         cs->exception_index = RISCV_EXCP_STORE_PAGE_FAULT;
998         break;
999     default:
1000         g_assert_not_reached();
1001     }
1002     env->badaddr = address;
1003     cpu_loop_exit_restore(cs, retaddr);
1004 #endif
1005 }
1006 
1007 /*
1008  * Handle Traps
1009  *
1010  * Adapted from Spike's processor_t::take_trap.
1011  *
1012  */
1013 void riscv_cpu_do_interrupt(CPUState *cs)
1014 {
1015 #if !defined(CONFIG_USER_ONLY)
1016 
1017     RISCVCPU *cpu = RISCV_CPU(cs);
1018     CPURISCVState *env = &cpu->env;
1019     bool force_hs_execp = riscv_cpu_force_hs_excep_enabled(env);
1020     uint64_t s;
1021 
1022     /* cs->exception is 32-bits wide unlike mcause which is XLEN-bits wide
1023      * so we mask off the MSB and separate into trap type and cause.
1024      */
1025     bool async = !!(cs->exception_index & RISCV_EXCP_INT_FLAG);
1026     target_ulong cause = cs->exception_index & RISCV_EXCP_INT_MASK;
1027     target_ulong deleg = async ? env->mideleg : env->medeleg;
1028     bool write_tval = false;
1029     target_ulong tval = 0;
1030     target_ulong htval = 0;
1031     target_ulong mtval2 = 0;
1032 
1033     if  (cause == RISCV_EXCP_SEMIHOST) {
1034         if (env->priv >= PRV_S) {
1035             env->gpr[xA0] = do_common_semihosting(cs);
1036             env->pc += 4;
1037             return;
1038         }
1039         cause = RISCV_EXCP_BREAKPOINT;
1040     }
1041 
1042     if (!async) {
1043         /* set tval to badaddr for traps with address information */
1044         switch (cause) {
1045         case RISCV_EXCP_INST_GUEST_PAGE_FAULT:
1046         case RISCV_EXCP_LOAD_GUEST_ACCESS_FAULT:
1047         case RISCV_EXCP_STORE_GUEST_AMO_ACCESS_FAULT:
1048             force_hs_execp = true;
1049             /* fallthrough */
1050         case RISCV_EXCP_INST_ADDR_MIS:
1051         case RISCV_EXCP_INST_ACCESS_FAULT:
1052         case RISCV_EXCP_LOAD_ADDR_MIS:
1053         case RISCV_EXCP_STORE_AMO_ADDR_MIS:
1054         case RISCV_EXCP_LOAD_ACCESS_FAULT:
1055         case RISCV_EXCP_STORE_AMO_ACCESS_FAULT:
1056         case RISCV_EXCP_INST_PAGE_FAULT:
1057         case RISCV_EXCP_LOAD_PAGE_FAULT:
1058         case RISCV_EXCP_STORE_PAGE_FAULT:
1059             write_tval  = true;
1060             tval = env->badaddr;
1061             break;
1062         default:
1063             break;
1064         }
1065         /* ecall is dispatched as one cause so translate based on mode */
1066         if (cause == RISCV_EXCP_U_ECALL) {
1067             assert(env->priv <= 3);
1068 
1069             if (env->priv == PRV_M) {
1070                 cause = RISCV_EXCP_M_ECALL;
1071             } else if (env->priv == PRV_S && riscv_cpu_virt_enabled(env)) {
1072                 cause = RISCV_EXCP_VS_ECALL;
1073             } else if (env->priv == PRV_S && !riscv_cpu_virt_enabled(env)) {
1074                 cause = RISCV_EXCP_S_ECALL;
1075             } else if (env->priv == PRV_U) {
1076                 cause = RISCV_EXCP_U_ECALL;
1077             }
1078         }
1079     }
1080 
1081     trace_riscv_trap(env->mhartid, async, cause, env->pc, tval,
1082                      riscv_cpu_get_trap_name(cause, async));
1083 
1084     qemu_log_mask(CPU_LOG_INT,
1085                   "%s: hart:"TARGET_FMT_ld", async:%d, cause:"TARGET_FMT_lx", "
1086                   "epc:0x"TARGET_FMT_lx", tval:0x"TARGET_FMT_lx", desc=%s\n",
1087                   __func__, env->mhartid, async, cause, env->pc, tval,
1088                   riscv_cpu_get_trap_name(cause, async));
1089 
1090     if (env->priv <= PRV_S &&
1091             cause < TARGET_LONG_BITS && ((deleg >> cause) & 1)) {
1092         /* handle the trap in S-mode */
1093         if (riscv_has_ext(env, RVH)) {
1094             target_ulong hdeleg = async ? env->hideleg : env->hedeleg;
1095 
1096             if (env->two_stage_lookup && write_tval) {
1097                 /*
1098                  * If we are writing a guest virtual address to stval, set
1099                  * this to 1. If we are trapping to VS we will set this to 0
1100                  * later.
1101                  */
1102                 env->hstatus = set_field(env->hstatus, HSTATUS_GVA, 1);
1103             } else {
1104                 /* For other HS-mode traps, we set this to 0. */
1105                 env->hstatus = set_field(env->hstatus, HSTATUS_GVA, 0);
1106             }
1107 
1108             if (riscv_cpu_virt_enabled(env) && ((hdeleg >> cause) & 1) &&
1109                 !force_hs_execp) {
1110                 /* Trap to VS mode */
1111                 /*
1112                  * See if we need to adjust cause. Yes if its VS mode interrupt
1113                  * no if hypervisor has delegated one of hs mode's interrupt
1114                  */
1115                 if (cause == IRQ_VS_TIMER || cause == IRQ_VS_SOFT ||
1116                     cause == IRQ_VS_EXT) {
1117                     cause = cause - 1;
1118                 }
1119                 env->hstatus = set_field(env->hstatus, HSTATUS_GVA, 0);
1120             } else if (riscv_cpu_virt_enabled(env)) {
1121                 /* Trap into HS mode, from virt */
1122                 riscv_cpu_swap_hypervisor_regs(env);
1123                 env->hstatus = set_field(env->hstatus, HSTATUS_SPVP,
1124                                          env->priv);
1125                 env->hstatus = set_field(env->hstatus, HSTATUS_SPV,
1126                                          riscv_cpu_virt_enabled(env));
1127 
1128                 htval = env->guest_phys_fault_addr;
1129 
1130                 riscv_cpu_set_virt_enabled(env, 0);
1131                 riscv_cpu_set_force_hs_excep(env, 0);
1132             } else {
1133                 /* Trap into HS mode */
1134                 env->hstatus = set_field(env->hstatus, HSTATUS_SPV, false);
1135                 htval = env->guest_phys_fault_addr;
1136             }
1137         }
1138 
1139         s = env->mstatus;
1140         s = set_field(s, MSTATUS_SPIE, get_field(s, MSTATUS_SIE));
1141         s = set_field(s, MSTATUS_SPP, env->priv);
1142         s = set_field(s, MSTATUS_SIE, 0);
1143         env->mstatus = s;
1144         env->scause = cause | ((target_ulong)async << (TARGET_LONG_BITS - 1));
1145         env->sepc = env->pc;
1146         env->stval = tval;
1147         env->htval = htval;
1148         env->pc = (env->stvec >> 2 << 2) +
1149             ((async && (env->stvec & 3) == 1) ? cause * 4 : 0);
1150         riscv_cpu_set_mode(env, PRV_S);
1151     } else {
1152         /* handle the trap in M-mode */
1153         if (riscv_has_ext(env, RVH)) {
1154             if (riscv_cpu_virt_enabled(env)) {
1155                 riscv_cpu_swap_hypervisor_regs(env);
1156             }
1157             env->mstatus = set_field(env->mstatus, MSTATUS_MPV,
1158                                      riscv_cpu_virt_enabled(env));
1159             if (riscv_cpu_virt_enabled(env) && tval) {
1160                 env->mstatus = set_field(env->mstatus, MSTATUS_GVA, 1);
1161             }
1162 
1163             mtval2 = env->guest_phys_fault_addr;
1164 
1165             /* Trapping to M mode, virt is disabled */
1166             riscv_cpu_set_virt_enabled(env, 0);
1167             riscv_cpu_set_force_hs_excep(env, 0);
1168         }
1169 
1170         s = env->mstatus;
1171         s = set_field(s, MSTATUS_MPIE, get_field(s, MSTATUS_MIE));
1172         s = set_field(s, MSTATUS_MPP, env->priv);
1173         s = set_field(s, MSTATUS_MIE, 0);
1174         env->mstatus = s;
1175         env->mcause = cause | ~(((target_ulong)-1) >> async);
1176         env->mepc = env->pc;
1177         env->mtval = tval;
1178         env->mtval2 = mtval2;
1179         env->pc = (env->mtvec >> 2 << 2) +
1180             ((async && (env->mtvec & 3) == 1) ? cause * 4 : 0);
1181         riscv_cpu_set_mode(env, PRV_M);
1182     }
1183 
1184     /* NOTE: it is not necessary to yield load reservations here. It is only
1185      * necessary for an SC from "another hart" to cause a load reservation
1186      * to be yielded. Refer to the memory consistency model section of the
1187      * RISC-V ISA Specification.
1188      */
1189 
1190     env->two_stage_lookup = false;
1191 #endif
1192     cs->exception_index = RISCV_EXCP_NONE; /* mark handled to qemu */
1193 }
1194