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