xref: /openbmc/qemu/target/riscv/cpu_helper.c (revision f6e33708)
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 "internals.h"
25 #include "pmu.h"
26 #include "exec/exec-all.h"
27 #include "instmap.h"
28 #include "tcg/tcg-op.h"
29 #include "trace.h"
30 #include "semihosting/common-semi.h"
31 #include "sysemu/cpu-timers.h"
32 #include "cpu_bits.h"
33 #include "debug.h"
34 #include "tcg/oversized-guest.h"
35 
36 int riscv_env_mmu_index(CPURISCVState *env, bool ifetch)
37 {
38 #ifdef CONFIG_USER_ONLY
39     return 0;
40 #else
41     bool virt = env->virt_enabled;
42     int mode = env->priv;
43 
44     /* All priv -> mmu_idx mapping are here */
45     if (!ifetch) {
46         uint64_t status = env->mstatus;
47 
48         if (mode == PRV_M && get_field(status, MSTATUS_MPRV)) {
49             mode = get_field(env->mstatus, MSTATUS_MPP);
50             virt = get_field(env->mstatus, MSTATUS_MPV) &&
51                    (mode != PRV_M);
52             if (virt) {
53                 status = env->vsstatus;
54             }
55         }
56         if (mode == PRV_S && get_field(status, MSTATUS_SUM)) {
57             mode = MMUIdx_S_SUM;
58         }
59     }
60 
61     return mode | (virt ? MMU_2STAGE_BIT : 0);
62 #endif
63 }
64 
65 void cpu_get_tb_cpu_state(CPURISCVState *env, vaddr *pc,
66                           uint64_t *cs_base, uint32_t *pflags)
67 {
68     RISCVCPU *cpu = env_archcpu(env);
69     RISCVExtStatus fs, vs;
70     uint32_t flags = 0;
71 
72     *pc = env->xl == MXL_RV32 ? env->pc & UINT32_MAX : env->pc;
73     *cs_base = 0;
74 
75     if (cpu->cfg.ext_zve32f) {
76         /*
77          * If env->vl equals to VLMAX, we can use generic vector operation
78          * expanders (GVEC) to accerlate the vector operations.
79          * However, as LMUL could be a fractional number. The maximum
80          * vector size can be operated might be less than 8 bytes,
81          * which is not supported by GVEC. So we set vl_eq_vlmax flag to true
82          * only when maxsz >= 8 bytes.
83          */
84 
85         /* lmul encoded as in DisasContext::lmul */
86         int8_t lmul = sextract32(FIELD_EX64(env->vtype, VTYPE, VLMUL), 0, 3);
87         uint32_t vsew = FIELD_EX64(env->vtype, VTYPE, VSEW);
88         uint32_t vlmax = vext_get_vlmax(cpu->cfg.vlenb, vsew, lmul);
89         uint32_t maxsz = vlmax << vsew;
90         bool vl_eq_vlmax = (env->vstart == 0) && (vlmax == env->vl) &&
91                            (maxsz >= 8);
92         flags = FIELD_DP32(flags, TB_FLAGS, VILL, env->vill);
93         flags = FIELD_DP32(flags, TB_FLAGS, SEW, vsew);
94         flags = FIELD_DP32(flags, TB_FLAGS, LMUL,
95                            FIELD_EX64(env->vtype, VTYPE, VLMUL));
96         flags = FIELD_DP32(flags, TB_FLAGS, VL_EQ_VLMAX, vl_eq_vlmax);
97         flags = FIELD_DP32(flags, TB_FLAGS, VTA,
98                            FIELD_EX64(env->vtype, VTYPE, VTA));
99         flags = FIELD_DP32(flags, TB_FLAGS, VMA,
100                            FIELD_EX64(env->vtype, VTYPE, VMA));
101         flags = FIELD_DP32(flags, TB_FLAGS, VSTART_EQ_ZERO, env->vstart == 0);
102     } else {
103         flags = FIELD_DP32(flags, TB_FLAGS, VILL, 1);
104     }
105 
106 #ifdef CONFIG_USER_ONLY
107     fs = EXT_STATUS_DIRTY;
108     vs = EXT_STATUS_DIRTY;
109 #else
110     flags = FIELD_DP32(flags, TB_FLAGS, PRIV, env->priv);
111 
112     flags |= riscv_env_mmu_index(env, 0);
113     fs = get_field(env->mstatus, MSTATUS_FS);
114     vs = get_field(env->mstatus, MSTATUS_VS);
115 
116     if (env->virt_enabled) {
117         flags = FIELD_DP32(flags, TB_FLAGS, VIRT_ENABLED, 1);
118         /*
119          * Merge DISABLED and !DIRTY states using MIN.
120          * We will set both fields when dirtying.
121          */
122         fs = MIN(fs, get_field(env->mstatus_hs, MSTATUS_FS));
123         vs = MIN(vs, get_field(env->mstatus_hs, MSTATUS_VS));
124     }
125 
126     /* With Zfinx, floating point is enabled/disabled by Smstateen. */
127     if (!riscv_has_ext(env, RVF)) {
128         fs = (smstateen_acc_ok(env, 0, SMSTATEEN0_FCSR) == RISCV_EXCP_NONE)
129              ? EXT_STATUS_DIRTY : EXT_STATUS_DISABLED;
130     }
131 
132     if (cpu->cfg.debug && !icount_enabled()) {
133         flags = FIELD_DP32(flags, TB_FLAGS, ITRIGGER, env->itrigger_enabled);
134     }
135 #endif
136 
137     flags = FIELD_DP32(flags, TB_FLAGS, FS, fs);
138     flags = FIELD_DP32(flags, TB_FLAGS, VS, vs);
139     flags = FIELD_DP32(flags, TB_FLAGS, XL, env->xl);
140     flags = FIELD_DP32(flags, TB_FLAGS, AXL, cpu_address_xl(env));
141     if (env->cur_pmmask != 0) {
142         flags = FIELD_DP32(flags, TB_FLAGS, PM_MASK_ENABLED, 1);
143     }
144     if (env->cur_pmbase != 0) {
145         flags = FIELD_DP32(flags, TB_FLAGS, PM_BASE_ENABLED, 1);
146     }
147 
148     *pflags = flags;
149 }
150 
151 void riscv_cpu_update_mask(CPURISCVState *env)
152 {
153     target_ulong mask = 0, base = 0;
154     RISCVMXL xl = env->xl;
155     /*
156      * TODO: Current RVJ spec does not specify
157      * how the extension interacts with XLEN.
158      */
159 #ifndef CONFIG_USER_ONLY
160     int mode = cpu_address_mode(env);
161     xl = cpu_get_xl(env, mode);
162     if (riscv_has_ext(env, RVJ)) {
163         switch (mode) {
164         case PRV_M:
165             if (env->mmte & M_PM_ENABLE) {
166                 mask = env->mpmmask;
167                 base = env->mpmbase;
168             }
169             break;
170         case PRV_S:
171             if (env->mmte & S_PM_ENABLE) {
172                 mask = env->spmmask;
173                 base = env->spmbase;
174             }
175             break;
176         case PRV_U:
177             if (env->mmte & U_PM_ENABLE) {
178                 mask = env->upmmask;
179                 base = env->upmbase;
180             }
181             break;
182         default:
183             g_assert_not_reached();
184         }
185     }
186 #endif
187     if (xl == MXL_RV32) {
188         env->cur_pmmask = mask & UINT32_MAX;
189         env->cur_pmbase = base & UINT32_MAX;
190     } else {
191         env->cur_pmmask = mask;
192         env->cur_pmbase = base;
193     }
194 }
195 
196 #ifndef CONFIG_USER_ONLY
197 
198 /*
199  * The HS-mode is allowed to configure priority only for the
200  * following VS-mode local interrupts:
201  *
202  * 0  (Reserved interrupt, reads as zero)
203  * 1  Supervisor software interrupt
204  * 4  (Reserved interrupt, reads as zero)
205  * 5  Supervisor timer interrupt
206  * 8  (Reserved interrupt, reads as zero)
207  * 13 (Reserved interrupt)
208  * 14 "
209  * 15 "
210  * 16 "
211  * 17 "
212  * 18 "
213  * 19 "
214  * 20 "
215  * 21 "
216  * 22 "
217  * 23 "
218  */
219 
220 static const int hviprio_index2irq[] = {
221     0, 1, 4, 5, 8, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 };
222 static const int hviprio_index2rdzero[] = {
223     1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
224 
225 int riscv_cpu_hviprio_index2irq(int index, int *out_irq, int *out_rdzero)
226 {
227     if (index < 0 || ARRAY_SIZE(hviprio_index2irq) <= index) {
228         return -EINVAL;
229     }
230 
231     if (out_irq) {
232         *out_irq = hviprio_index2irq[index];
233     }
234 
235     if (out_rdzero) {
236         *out_rdzero = hviprio_index2rdzero[index];
237     }
238 
239     return 0;
240 }
241 
242 /*
243  * Default priorities of local interrupts are defined in the
244  * RISC-V Advanced Interrupt Architecture specification.
245  *
246  * ----------------------------------------------------------------
247  *  Default  |
248  *  Priority | Major Interrupt Numbers
249  * ----------------------------------------------------------------
250  *  Highest  | 47, 23, 46, 45, 22, 44,
251  *           | 43, 21, 42, 41, 20, 40
252  *           |
253  *           | 11 (0b),  3 (03),  7 (07)
254  *           |  9 (09),  1 (01),  5 (05)
255  *           | 12 (0c)
256  *           | 10 (0a),  2 (02),  6 (06)
257  *           |
258  *           | 39, 19, 38, 37, 18, 36,
259  *  Lowest   | 35, 17, 34, 33, 16, 32
260  * ----------------------------------------------------------------
261  */
262 static const uint8_t default_iprio[64] = {
263     /* Custom interrupts 48 to 63 */
264     [63] = IPRIO_MMAXIPRIO,
265     [62] = IPRIO_MMAXIPRIO,
266     [61] = IPRIO_MMAXIPRIO,
267     [60] = IPRIO_MMAXIPRIO,
268     [59] = IPRIO_MMAXIPRIO,
269     [58] = IPRIO_MMAXIPRIO,
270     [57] = IPRIO_MMAXIPRIO,
271     [56] = IPRIO_MMAXIPRIO,
272     [55] = IPRIO_MMAXIPRIO,
273     [54] = IPRIO_MMAXIPRIO,
274     [53] = IPRIO_MMAXIPRIO,
275     [52] = IPRIO_MMAXIPRIO,
276     [51] = IPRIO_MMAXIPRIO,
277     [50] = IPRIO_MMAXIPRIO,
278     [49] = IPRIO_MMAXIPRIO,
279     [48] = IPRIO_MMAXIPRIO,
280 
281     /* Custom interrupts 24 to 31 */
282     [31] = IPRIO_MMAXIPRIO,
283     [30] = IPRIO_MMAXIPRIO,
284     [29] = IPRIO_MMAXIPRIO,
285     [28] = IPRIO_MMAXIPRIO,
286     [27] = IPRIO_MMAXIPRIO,
287     [26] = IPRIO_MMAXIPRIO,
288     [25] = IPRIO_MMAXIPRIO,
289     [24] = IPRIO_MMAXIPRIO,
290 
291     [47] = IPRIO_DEFAULT_UPPER,
292     [23] = IPRIO_DEFAULT_UPPER + 1,
293     [46] = IPRIO_DEFAULT_UPPER + 2,
294     [45] = IPRIO_DEFAULT_UPPER + 3,
295     [22] = IPRIO_DEFAULT_UPPER + 4,
296     [44] = IPRIO_DEFAULT_UPPER + 5,
297 
298     [43] = IPRIO_DEFAULT_UPPER + 6,
299     [21] = IPRIO_DEFAULT_UPPER + 7,
300     [42] = IPRIO_DEFAULT_UPPER + 8,
301     [41] = IPRIO_DEFAULT_UPPER + 9,
302     [20] = IPRIO_DEFAULT_UPPER + 10,
303     [40] = IPRIO_DEFAULT_UPPER + 11,
304 
305     [11] = IPRIO_DEFAULT_M,
306     [3]  = IPRIO_DEFAULT_M + 1,
307     [7]  = IPRIO_DEFAULT_M + 2,
308 
309     [9]  = IPRIO_DEFAULT_S,
310     [1]  = IPRIO_DEFAULT_S + 1,
311     [5]  = IPRIO_DEFAULT_S + 2,
312 
313     [12] = IPRIO_DEFAULT_SGEXT,
314 
315     [10] = IPRIO_DEFAULT_VS,
316     [2]  = IPRIO_DEFAULT_VS + 1,
317     [6]  = IPRIO_DEFAULT_VS + 2,
318 
319     [39] = IPRIO_DEFAULT_LOWER,
320     [19] = IPRIO_DEFAULT_LOWER + 1,
321     [38] = IPRIO_DEFAULT_LOWER + 2,
322     [37] = IPRIO_DEFAULT_LOWER + 3,
323     [18] = IPRIO_DEFAULT_LOWER + 4,
324     [36] = IPRIO_DEFAULT_LOWER + 5,
325 
326     [35] = IPRIO_DEFAULT_LOWER + 6,
327     [17] = IPRIO_DEFAULT_LOWER + 7,
328     [34] = IPRIO_DEFAULT_LOWER + 8,
329     [33] = IPRIO_DEFAULT_LOWER + 9,
330     [16] = IPRIO_DEFAULT_LOWER + 10,
331     [32] = IPRIO_DEFAULT_LOWER + 11,
332 };
333 
334 uint8_t riscv_cpu_default_priority(int irq)
335 {
336     if (irq < 0 || irq > 63) {
337         return IPRIO_MMAXIPRIO;
338     }
339 
340     return default_iprio[irq] ? default_iprio[irq] : IPRIO_MMAXIPRIO;
341 };
342 
343 static int riscv_cpu_pending_to_irq(CPURISCVState *env,
344                                     int extirq, unsigned int extirq_def_prio,
345                                     uint64_t pending, uint8_t *iprio)
346 {
347     int irq, best_irq = RISCV_EXCP_NONE;
348     unsigned int prio, best_prio = UINT_MAX;
349 
350     if (!pending) {
351         return RISCV_EXCP_NONE;
352     }
353 
354     irq = ctz64(pending);
355     if (!((extirq == IRQ_M_EXT) ? riscv_cpu_cfg(env)->ext_smaia :
356                                   riscv_cpu_cfg(env)->ext_ssaia)) {
357         return irq;
358     }
359 
360     pending = pending >> irq;
361     while (pending) {
362         prio = iprio[irq];
363         if (!prio) {
364             if (irq == extirq) {
365                 prio = extirq_def_prio;
366             } else {
367                 prio = (riscv_cpu_default_priority(irq) < extirq_def_prio) ?
368                        1 : IPRIO_MMAXIPRIO;
369             }
370         }
371         if ((pending & 0x1) && (prio <= best_prio)) {
372             best_irq = irq;
373             best_prio = prio;
374         }
375         irq++;
376         pending = pending >> 1;
377     }
378 
379     return best_irq;
380 }
381 
382 /*
383  * Doesn't report interrupts inserted using mvip from M-mode firmware or
384  * using hvip bits 13:63 from HS-mode. Those are returned in
385  * riscv_cpu_sirq_pending() and riscv_cpu_vsirq_pending().
386  */
387 uint64_t riscv_cpu_all_pending(CPURISCVState *env)
388 {
389     uint32_t gein = get_field(env->hstatus, HSTATUS_VGEIN);
390     uint64_t vsgein = (env->hgeip & (1ULL << gein)) ? MIP_VSEIP : 0;
391     uint64_t vstip = (env->vstime_irq) ? MIP_VSTIP : 0;
392 
393     return (env->mip | vsgein | vstip) & env->mie;
394 }
395 
396 int riscv_cpu_mirq_pending(CPURISCVState *env)
397 {
398     uint64_t irqs = riscv_cpu_all_pending(env) & ~env->mideleg &
399                     ~(MIP_SGEIP | MIP_VSSIP | MIP_VSTIP | MIP_VSEIP);
400 
401     return riscv_cpu_pending_to_irq(env, IRQ_M_EXT, IPRIO_DEFAULT_M,
402                                     irqs, env->miprio);
403 }
404 
405 int riscv_cpu_sirq_pending(CPURISCVState *env)
406 {
407     uint64_t irqs = riscv_cpu_all_pending(env) & env->mideleg &
408                     ~(MIP_VSSIP | MIP_VSTIP | MIP_VSEIP);
409     uint64_t irqs_f = env->mvip & env->mvien & ~env->mideleg & env->sie;
410 
411     return riscv_cpu_pending_to_irq(env, IRQ_S_EXT, IPRIO_DEFAULT_S,
412                                     irqs | irqs_f, env->siprio);
413 }
414 
415 int riscv_cpu_vsirq_pending(CPURISCVState *env)
416 {
417     uint64_t irqs = riscv_cpu_all_pending(env) & env->mideleg & env->hideleg;
418     uint64_t irqs_f_vs = env->hvip & env->hvien & ~env->hideleg & env->vsie;
419     uint64_t vsbits;
420 
421     /* Bring VS-level bits to correct position */
422     vsbits = irqs & VS_MODE_INTERRUPTS;
423     irqs &= ~VS_MODE_INTERRUPTS;
424     irqs |= vsbits >> 1;
425 
426     return riscv_cpu_pending_to_irq(env, IRQ_S_EXT, IPRIO_DEFAULT_S,
427                                     (irqs | irqs_f_vs), env->hviprio);
428 }
429 
430 static int riscv_cpu_local_irq_pending(CPURISCVState *env)
431 {
432     uint64_t irqs, pending, mie, hsie, vsie, irqs_f, irqs_f_vs;
433     uint64_t vsbits, irq_delegated;
434     int virq;
435 
436     /* Determine interrupt enable state of all privilege modes */
437     if (env->virt_enabled) {
438         mie = 1;
439         hsie = 1;
440         vsie = (env->priv < PRV_S) ||
441                (env->priv == PRV_S && get_field(env->mstatus, MSTATUS_SIE));
442     } else {
443         mie = (env->priv < PRV_M) ||
444               (env->priv == PRV_M && get_field(env->mstatus, MSTATUS_MIE));
445         hsie = (env->priv < PRV_S) ||
446                (env->priv == PRV_S && get_field(env->mstatus, MSTATUS_SIE));
447         vsie = 0;
448     }
449 
450     /* Determine all pending interrupts */
451     pending = riscv_cpu_all_pending(env);
452 
453     /* Check M-mode interrupts */
454     irqs = pending & ~env->mideleg & -mie;
455     if (irqs) {
456         return riscv_cpu_pending_to_irq(env, IRQ_M_EXT, IPRIO_DEFAULT_M,
457                                         irqs, env->miprio);
458     }
459 
460     /* Check for virtual S-mode interrupts. */
461     irqs_f = env->mvip & (env->mvien & ~env->mideleg) & env->sie;
462 
463     /* Check HS-mode interrupts */
464     irqs =  ((pending & env->mideleg & ~env->hideleg) | irqs_f) & -hsie;
465     if (irqs) {
466         return riscv_cpu_pending_to_irq(env, IRQ_S_EXT, IPRIO_DEFAULT_S,
467                                         irqs, env->siprio);
468     }
469 
470     /* Check for virtual VS-mode interrupts. */
471     irqs_f_vs = env->hvip & env->hvien & ~env->hideleg & env->vsie;
472 
473     /* Check VS-mode interrupts */
474     irq_delegated = pending & env->mideleg & env->hideleg;
475 
476     /* Bring VS-level bits to correct position */
477     vsbits = irq_delegated & VS_MODE_INTERRUPTS;
478     irq_delegated &= ~VS_MODE_INTERRUPTS;
479     irq_delegated |= vsbits >> 1;
480 
481     irqs = (irq_delegated | irqs_f_vs) & -vsie;
482     if (irqs) {
483         virq = riscv_cpu_pending_to_irq(env, IRQ_S_EXT, IPRIO_DEFAULT_S,
484                                         irqs, env->hviprio);
485         if (virq <= 0 || (virq > 12 && virq <= 63)) {
486             return virq;
487         } else {
488             return virq + 1;
489         }
490     }
491 
492     /* Indicate no pending interrupt */
493     return RISCV_EXCP_NONE;
494 }
495 
496 bool riscv_cpu_exec_interrupt(CPUState *cs, int interrupt_request)
497 {
498     if (interrupt_request & CPU_INTERRUPT_HARD) {
499         RISCVCPU *cpu = RISCV_CPU(cs);
500         CPURISCVState *env = &cpu->env;
501         int interruptno = riscv_cpu_local_irq_pending(env);
502         if (interruptno >= 0) {
503             cs->exception_index = RISCV_EXCP_INT_FLAG | interruptno;
504             riscv_cpu_do_interrupt(cs);
505             return true;
506         }
507     }
508     return false;
509 }
510 
511 /* Return true is floating point support is currently enabled */
512 bool riscv_cpu_fp_enabled(CPURISCVState *env)
513 {
514     if (env->mstatus & MSTATUS_FS) {
515         if (env->virt_enabled && !(env->mstatus_hs & MSTATUS_FS)) {
516             return false;
517         }
518         return true;
519     }
520 
521     return false;
522 }
523 
524 /* Return true is vector support is currently enabled */
525 bool riscv_cpu_vector_enabled(CPURISCVState *env)
526 {
527     if (env->mstatus & MSTATUS_VS) {
528         if (env->virt_enabled && !(env->mstatus_hs & MSTATUS_VS)) {
529             return false;
530         }
531         return true;
532     }
533 
534     return false;
535 }
536 
537 void riscv_cpu_swap_hypervisor_regs(CPURISCVState *env)
538 {
539     uint64_t mstatus_mask = MSTATUS_MXR | MSTATUS_SUM |
540                             MSTATUS_SPP | MSTATUS_SPIE | MSTATUS_SIE |
541                             MSTATUS64_UXL | MSTATUS_VS;
542 
543     if (riscv_has_ext(env, RVF)) {
544         mstatus_mask |= MSTATUS_FS;
545     }
546     bool current_virt = env->virt_enabled;
547 
548     g_assert(riscv_has_ext(env, RVH));
549 
550     if (current_virt) {
551         /* Current V=1 and we are about to change to V=0 */
552         env->vsstatus = env->mstatus & mstatus_mask;
553         env->mstatus &= ~mstatus_mask;
554         env->mstatus |= env->mstatus_hs;
555 
556         env->vstvec = env->stvec;
557         env->stvec = env->stvec_hs;
558 
559         env->vsscratch = env->sscratch;
560         env->sscratch = env->sscratch_hs;
561 
562         env->vsepc = env->sepc;
563         env->sepc = env->sepc_hs;
564 
565         env->vscause = env->scause;
566         env->scause = env->scause_hs;
567 
568         env->vstval = env->stval;
569         env->stval = env->stval_hs;
570 
571         env->vsatp = env->satp;
572         env->satp = env->satp_hs;
573     } else {
574         /* Current V=0 and we are about to change to V=1 */
575         env->mstatus_hs = env->mstatus & mstatus_mask;
576         env->mstatus &= ~mstatus_mask;
577         env->mstatus |= env->vsstatus;
578 
579         env->stvec_hs = env->stvec;
580         env->stvec = env->vstvec;
581 
582         env->sscratch_hs = env->sscratch;
583         env->sscratch = env->vsscratch;
584 
585         env->sepc_hs = env->sepc;
586         env->sepc = env->vsepc;
587 
588         env->scause_hs = env->scause;
589         env->scause = env->vscause;
590 
591         env->stval_hs = env->stval;
592         env->stval = env->vstval;
593 
594         env->satp_hs = env->satp;
595         env->satp = env->vsatp;
596     }
597 }
598 
599 target_ulong riscv_cpu_get_geilen(CPURISCVState *env)
600 {
601     if (!riscv_has_ext(env, RVH)) {
602         return 0;
603     }
604 
605     return env->geilen;
606 }
607 
608 void riscv_cpu_set_geilen(CPURISCVState *env, target_ulong geilen)
609 {
610     if (!riscv_has_ext(env, RVH)) {
611         return;
612     }
613 
614     if (geilen > (TARGET_LONG_BITS - 1)) {
615         return;
616     }
617 
618     env->geilen = geilen;
619 }
620 
621 /* This function can only be called to set virt when RVH is enabled */
622 void riscv_cpu_set_virt_enabled(CPURISCVState *env, bool enable)
623 {
624     /* Flush the TLB on all virt mode changes. */
625     if (env->virt_enabled != enable) {
626         tlb_flush(env_cpu(env));
627     }
628 
629     env->virt_enabled = enable;
630 
631     if (enable) {
632         /*
633          * The guest external interrupts from an interrupt controller are
634          * delivered only when the Guest/VM is running (i.e. V=1). This means
635          * any guest external interrupt which is triggered while the Guest/VM
636          * is not running (i.e. V=0) will be missed on QEMU resulting in guest
637          * with sluggish response to serial console input and other I/O events.
638          *
639          * To solve this, we check and inject interrupt after setting V=1.
640          */
641         riscv_cpu_update_mip(env, 0, 0);
642     }
643 }
644 
645 int riscv_cpu_claim_interrupts(RISCVCPU *cpu, uint64_t interrupts)
646 {
647     CPURISCVState *env = &cpu->env;
648     if (env->miclaim & interrupts) {
649         return -1;
650     } else {
651         env->miclaim |= interrupts;
652         return 0;
653     }
654 }
655 
656 void riscv_cpu_interrupt(CPURISCVState *env)
657 {
658     uint64_t gein, vsgein = 0, vstip = 0, irqf = 0;
659     CPUState *cs = env_cpu(env);
660 
661     BQL_LOCK_GUARD();
662 
663     if (env->virt_enabled) {
664         gein = get_field(env->hstatus, HSTATUS_VGEIN);
665         vsgein = (env->hgeip & (1ULL << gein)) ? MIP_VSEIP : 0;
666         irqf = env->hvien & env->hvip & env->vsie;
667     } else {
668         irqf = env->mvien & env->mvip & env->sie;
669     }
670 
671     vstip = env->vstime_irq ? MIP_VSTIP : 0;
672 
673     if (env->mip | vsgein | vstip | irqf) {
674         cpu_interrupt(cs, CPU_INTERRUPT_HARD);
675     } else {
676         cpu_reset_interrupt(cs, CPU_INTERRUPT_HARD);
677     }
678 }
679 
680 uint64_t riscv_cpu_update_mip(CPURISCVState *env, uint64_t mask, uint64_t value)
681 {
682     uint64_t old = env->mip;
683 
684     /* No need to update mip for VSTIP */
685     mask = ((mask == MIP_VSTIP) && env->vstime_irq) ? 0 : mask;
686 
687     BQL_LOCK_GUARD();
688 
689     env->mip = (env->mip & ~mask) | (value & mask);
690 
691     riscv_cpu_interrupt(env);
692 
693     return old;
694 }
695 
696 void riscv_cpu_set_rdtime_fn(CPURISCVState *env, uint64_t (*fn)(void *),
697                              void *arg)
698 {
699     env->rdtime_fn = fn;
700     env->rdtime_fn_arg = arg;
701 }
702 
703 void riscv_cpu_set_aia_ireg_rmw_fn(CPURISCVState *env, uint32_t priv,
704                                    int (*rmw_fn)(void *arg,
705                                                  target_ulong reg,
706                                                  target_ulong *val,
707                                                  target_ulong new_val,
708                                                  target_ulong write_mask),
709                                    void *rmw_fn_arg)
710 {
711     if (priv <= PRV_M) {
712         env->aia_ireg_rmw_fn[priv] = rmw_fn;
713         env->aia_ireg_rmw_fn_arg[priv] = rmw_fn_arg;
714     }
715 }
716 
717 void riscv_cpu_set_mode(CPURISCVState *env, target_ulong newpriv)
718 {
719     g_assert(newpriv <= PRV_M && newpriv != PRV_RESERVED);
720 
721     if (icount_enabled() && newpriv != env->priv) {
722         riscv_itrigger_update_priv(env);
723     }
724     /* tlb_flush is unnecessary as mode is contained in mmu_idx */
725     env->priv = newpriv;
726     env->xl = cpu_recompute_xl(env);
727     riscv_cpu_update_mask(env);
728 
729     /*
730      * Clear the load reservation - otherwise a reservation placed in one
731      * context/process can be used by another, resulting in an SC succeeding
732      * incorrectly. Version 2.2 of the ISA specification explicitly requires
733      * this behaviour, while later revisions say that the kernel "should" use
734      * an SC instruction to force the yielding of a load reservation on a
735      * preemptive context switch. As a result, do both.
736      */
737     env->load_res = -1;
738 }
739 
740 /*
741  * get_physical_address_pmp - check PMP permission for this physical address
742  *
743  * Match the PMP region and check permission for this physical address and it's
744  * TLB page. Returns 0 if the permission checking was successful
745  *
746  * @env: CPURISCVState
747  * @prot: The returned protection attributes
748  * @addr: The physical address to be checked permission
749  * @access_type: The type of MMU access
750  * @mode: Indicates current privilege level.
751  */
752 static int get_physical_address_pmp(CPURISCVState *env, int *prot, hwaddr addr,
753                                     int size, MMUAccessType access_type,
754                                     int mode)
755 {
756     pmp_priv_t pmp_priv;
757     bool pmp_has_privs;
758 
759     if (!riscv_cpu_cfg(env)->pmp) {
760         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
761         return TRANSLATE_SUCCESS;
762     }
763 
764     pmp_has_privs = pmp_hart_has_privs(env, addr, size, 1 << access_type,
765                                        &pmp_priv, mode);
766     if (!pmp_has_privs) {
767         *prot = 0;
768         return TRANSLATE_PMP_FAIL;
769     }
770 
771     *prot = pmp_priv_to_page_prot(pmp_priv);
772 
773     return TRANSLATE_SUCCESS;
774 }
775 
776 /*
777  * get_physical_address - get the physical address for this virtual address
778  *
779  * Do a page table walk to obtain the physical address corresponding to a
780  * virtual address. Returns 0 if the translation was successful
781  *
782  * Adapted from Spike's mmu_t::translate and mmu_t::walk
783  *
784  * @env: CPURISCVState
785  * @physical: This will be set to the calculated physical address
786  * @prot: The returned protection attributes
787  * @addr: The virtual address or guest physical address to be translated
788  * @fault_pte_addr: If not NULL, this will be set to fault pte address
789  *                  when a error occurs on pte address translation.
790  *                  This will already be shifted to match htval.
791  * @access_type: The type of MMU access
792  * @mmu_idx: Indicates current privilege level
793  * @first_stage: Are we in first stage translation?
794  *               Second stage is used for hypervisor guest translation
795  * @two_stage: Are we going to perform two stage translation
796  * @is_debug: Is this access from a debugger or the monitor?
797  */
798 static int get_physical_address(CPURISCVState *env, hwaddr *physical,
799                                 int *ret_prot, vaddr addr,
800                                 target_ulong *fault_pte_addr,
801                                 int access_type, int mmu_idx,
802                                 bool first_stage, bool two_stage,
803                                 bool is_debug)
804 {
805     /*
806      * NOTE: the env->pc value visible here will not be
807      * correct, but the value visible to the exception handler
808      * (riscv_cpu_do_interrupt) is correct
809      */
810     MemTxResult res;
811     MemTxAttrs attrs = MEMTXATTRS_UNSPECIFIED;
812     int mode = mmuidx_priv(mmu_idx);
813     bool use_background = false;
814     hwaddr ppn;
815     int napot_bits = 0;
816     target_ulong napot_mask;
817 
818     /*
819      * Check if we should use the background registers for the two
820      * stage translation. We don't need to check if we actually need
821      * two stage translation as that happened before this function
822      * was called. Background registers will be used if the guest has
823      * forced a two stage translation to be on (in HS or M mode).
824      */
825     if (!env->virt_enabled && two_stage) {
826         use_background = true;
827     }
828 
829     if (mode == PRV_M || !riscv_cpu_cfg(env)->mmu) {
830         *physical = addr;
831         *ret_prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
832         return TRANSLATE_SUCCESS;
833     }
834 
835     *ret_prot = 0;
836 
837     hwaddr base;
838     int levels, ptidxbits, ptesize, vm, widened;
839 
840     if (first_stage == true) {
841         if (use_background) {
842             if (riscv_cpu_mxl(env) == MXL_RV32) {
843                 base = (hwaddr)get_field(env->vsatp, SATP32_PPN) << PGSHIFT;
844                 vm = get_field(env->vsatp, SATP32_MODE);
845             } else {
846                 base = (hwaddr)get_field(env->vsatp, SATP64_PPN) << PGSHIFT;
847                 vm = get_field(env->vsatp, SATP64_MODE);
848             }
849         } else {
850             if (riscv_cpu_mxl(env) == MXL_RV32) {
851                 base = (hwaddr)get_field(env->satp, SATP32_PPN) << PGSHIFT;
852                 vm = get_field(env->satp, SATP32_MODE);
853             } else {
854                 base = (hwaddr)get_field(env->satp, SATP64_PPN) << PGSHIFT;
855                 vm = get_field(env->satp, SATP64_MODE);
856             }
857         }
858         widened = 0;
859     } else {
860         if (riscv_cpu_mxl(env) == MXL_RV32) {
861             base = (hwaddr)get_field(env->hgatp, SATP32_PPN) << PGSHIFT;
862             vm = get_field(env->hgatp, SATP32_MODE);
863         } else {
864             base = (hwaddr)get_field(env->hgatp, SATP64_PPN) << PGSHIFT;
865             vm = get_field(env->hgatp, SATP64_MODE);
866         }
867         widened = 2;
868     }
869 
870     switch (vm) {
871     case VM_1_10_SV32:
872       levels = 2; ptidxbits = 10; ptesize = 4; break;
873     case VM_1_10_SV39:
874       levels = 3; ptidxbits = 9; ptesize = 8; break;
875     case VM_1_10_SV48:
876       levels = 4; ptidxbits = 9; ptesize = 8; break;
877     case VM_1_10_SV57:
878       levels = 5; ptidxbits = 9; ptesize = 8; break;
879     case VM_1_10_MBARE:
880         *physical = addr;
881         *ret_prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
882         return TRANSLATE_SUCCESS;
883     default:
884       g_assert_not_reached();
885     }
886 
887     CPUState *cs = env_cpu(env);
888     int va_bits = PGSHIFT + levels * ptidxbits + widened;
889 
890     if (first_stage == true) {
891         target_ulong mask, masked_msbs;
892 
893         if (TARGET_LONG_BITS > (va_bits - 1)) {
894             mask = (1L << (TARGET_LONG_BITS - (va_bits - 1))) - 1;
895         } else {
896             mask = 0;
897         }
898         masked_msbs = (addr >> (va_bits - 1)) & mask;
899 
900         if (masked_msbs != 0 && masked_msbs != mask) {
901             return TRANSLATE_FAIL;
902         }
903     } else {
904         if (vm != VM_1_10_SV32 && addr >> va_bits != 0) {
905             return TRANSLATE_FAIL;
906         }
907     }
908 
909     bool pbmte = env->menvcfg & MENVCFG_PBMTE;
910     bool adue = env->menvcfg & MENVCFG_ADUE;
911 
912     if (first_stage && two_stage && env->virt_enabled) {
913         pbmte = pbmte && (env->henvcfg & HENVCFG_PBMTE);
914         adue = adue && (env->henvcfg & HENVCFG_ADUE);
915     }
916 
917     int ptshift = (levels - 1) * ptidxbits;
918     target_ulong pte;
919     hwaddr pte_addr;
920     int i;
921 
922 #if !TCG_OVERSIZED_GUEST
923 restart:
924 #endif
925     for (i = 0; i < levels; i++, ptshift -= ptidxbits) {
926         target_ulong idx;
927         if (i == 0) {
928             idx = (addr >> (PGSHIFT + ptshift)) &
929                            ((1 << (ptidxbits + widened)) - 1);
930         } else {
931             idx = (addr >> (PGSHIFT + ptshift)) &
932                            ((1 << ptidxbits) - 1);
933         }
934 
935         /* check that physical address of PTE is legal */
936 
937         if (two_stage && first_stage) {
938             int vbase_prot;
939             hwaddr vbase;
940 
941             /* Do the second stage translation on the base PTE address. */
942             int vbase_ret = get_physical_address(env, &vbase, &vbase_prot,
943                                                  base, NULL, MMU_DATA_LOAD,
944                                                  MMUIdx_U, false, true,
945                                                  is_debug);
946 
947             if (vbase_ret != TRANSLATE_SUCCESS) {
948                 if (fault_pte_addr) {
949                     *fault_pte_addr = (base + idx * ptesize) >> 2;
950                 }
951                 return TRANSLATE_G_STAGE_FAIL;
952             }
953 
954             pte_addr = vbase + idx * ptesize;
955         } else {
956             pte_addr = base + idx * ptesize;
957         }
958 
959         int pmp_prot;
960         int pmp_ret = get_physical_address_pmp(env, &pmp_prot, pte_addr,
961                                                sizeof(target_ulong),
962                                                MMU_DATA_LOAD, PRV_S);
963         if (pmp_ret != TRANSLATE_SUCCESS) {
964             return TRANSLATE_PMP_FAIL;
965         }
966 
967         if (riscv_cpu_mxl(env) == MXL_RV32) {
968             pte = address_space_ldl(cs->as, pte_addr, attrs, &res);
969         } else {
970             pte = address_space_ldq(cs->as, pte_addr, attrs, &res);
971         }
972 
973         if (res != MEMTX_OK) {
974             return TRANSLATE_FAIL;
975         }
976 
977         if (riscv_cpu_sxl(env) == MXL_RV32) {
978             ppn = pte >> PTE_PPN_SHIFT;
979         } else {
980             if (pte & PTE_RESERVED) {
981                 return TRANSLATE_FAIL;
982             }
983 
984             if (!pbmte && (pte & PTE_PBMT)) {
985                 return TRANSLATE_FAIL;
986             }
987 
988             if (!riscv_cpu_cfg(env)->ext_svnapot && (pte & PTE_N)) {
989                 return TRANSLATE_FAIL;
990             }
991 
992             ppn = (pte & (target_ulong)PTE_PPN_MASK) >> PTE_PPN_SHIFT;
993         }
994 
995         if (!(pte & PTE_V)) {
996             /* Invalid PTE */
997             return TRANSLATE_FAIL;
998         }
999         if (pte & (PTE_R | PTE_W | PTE_X)) {
1000             goto leaf;
1001         }
1002 
1003         /* Inner PTE, continue walking */
1004         if (pte & (PTE_D | PTE_A | PTE_U | PTE_ATTR)) {
1005             return TRANSLATE_FAIL;
1006         }
1007         base = ppn << PGSHIFT;
1008     }
1009 
1010     /* No leaf pte at any translation level. */
1011     return TRANSLATE_FAIL;
1012 
1013  leaf:
1014     if (ppn & ((1ULL << ptshift) - 1)) {
1015         /* Misaligned PPN */
1016         return TRANSLATE_FAIL;
1017     }
1018     if (!pbmte && (pte & PTE_PBMT)) {
1019         /* Reserved without Svpbmt. */
1020         return TRANSLATE_FAIL;
1021     }
1022 
1023     /* Check for reserved combinations of RWX flags. */
1024     switch (pte & (PTE_R | PTE_W | PTE_X)) {
1025     case PTE_W:
1026     case PTE_W | PTE_X:
1027         return TRANSLATE_FAIL;
1028     }
1029 
1030     int prot = 0;
1031     if (pte & PTE_R) {
1032         prot |= PAGE_READ;
1033     }
1034     if (pte & PTE_W) {
1035         prot |= PAGE_WRITE;
1036     }
1037     if (pte & PTE_X) {
1038         bool mxr = false;
1039 
1040         /*
1041          * Use mstatus for first stage or for the second stage without
1042          * virt_enabled (MPRV+MPV)
1043          */
1044         if (first_stage || !env->virt_enabled) {
1045             mxr = get_field(env->mstatus, MSTATUS_MXR);
1046         }
1047 
1048         /* MPRV+MPV case, check VSSTATUS */
1049         if (first_stage && two_stage && !env->virt_enabled) {
1050             mxr |= get_field(env->vsstatus, MSTATUS_MXR);
1051         }
1052 
1053         /*
1054          * Setting MXR at HS-level overrides both VS-stage and G-stage
1055          * execute-only permissions
1056          */
1057         if (env->virt_enabled) {
1058             mxr |= get_field(env->mstatus_hs, MSTATUS_MXR);
1059         }
1060 
1061         if (mxr) {
1062             prot |= PAGE_READ;
1063         }
1064         prot |= PAGE_EXEC;
1065     }
1066 
1067     if (pte & PTE_U) {
1068         if (mode != PRV_U) {
1069             if (!mmuidx_sum(mmu_idx)) {
1070                 return TRANSLATE_FAIL;
1071             }
1072             /* SUM allows only read+write, not execute. */
1073             prot &= PAGE_READ | PAGE_WRITE;
1074         }
1075     } else if (mode != PRV_S) {
1076         /* Supervisor PTE flags when not S mode */
1077         return TRANSLATE_FAIL;
1078     }
1079 
1080     if (!((prot >> access_type) & 1)) {
1081         /* Access check failed */
1082         return TRANSLATE_FAIL;
1083     }
1084 
1085     /* If necessary, set accessed and dirty bits. */
1086     target_ulong updated_pte = pte | PTE_A |
1087                 (access_type == MMU_DATA_STORE ? PTE_D : 0);
1088 
1089     /* Page table updates need to be atomic with MTTCG enabled */
1090     if (updated_pte != pte && !is_debug) {
1091         if (!adue) {
1092             return TRANSLATE_FAIL;
1093         }
1094 
1095         /*
1096          * - if accessed or dirty bits need updating, and the PTE is
1097          *   in RAM, then we do so atomically with a compare and swap.
1098          * - if the PTE is in IO space or ROM, then it can't be updated
1099          *   and we return TRANSLATE_FAIL.
1100          * - if the PTE changed by the time we went to update it, then
1101          *   it is no longer valid and we must re-walk the page table.
1102          */
1103         MemoryRegion *mr;
1104         hwaddr l = sizeof(target_ulong), addr1;
1105         mr = address_space_translate(cs->as, pte_addr, &addr1, &l,
1106                                      false, MEMTXATTRS_UNSPECIFIED);
1107         if (memory_region_is_ram(mr)) {
1108             target_ulong *pte_pa = qemu_map_ram_ptr(mr->ram_block, addr1);
1109 #if TCG_OVERSIZED_GUEST
1110             /*
1111              * MTTCG is not enabled on oversized TCG guests so
1112              * page table updates do not need to be atomic
1113              */
1114             *pte_pa = pte = updated_pte;
1115 #else
1116             target_ulong old_pte = qatomic_cmpxchg(pte_pa, pte, updated_pte);
1117             if (old_pte != pte) {
1118                 goto restart;
1119             }
1120             pte = updated_pte;
1121 #endif
1122         } else {
1123             /*
1124              * Misconfigured PTE in ROM (AD bits are not preset) or
1125              * PTE is in IO space and can't be updated atomically.
1126              */
1127             return TRANSLATE_FAIL;
1128         }
1129     }
1130 
1131     /* For superpage mappings, make a fake leaf PTE for the TLB's benefit. */
1132     target_ulong vpn = addr >> PGSHIFT;
1133 
1134     if (riscv_cpu_cfg(env)->ext_svnapot && (pte & PTE_N)) {
1135         napot_bits = ctzl(ppn) + 1;
1136         if ((i != (levels - 1)) || (napot_bits != 4)) {
1137             return TRANSLATE_FAIL;
1138         }
1139     }
1140 
1141     napot_mask = (1 << napot_bits) - 1;
1142     *physical = (((ppn & ~napot_mask) | (vpn & napot_mask) |
1143                   (vpn & (((target_ulong)1 << ptshift) - 1))
1144                  ) << PGSHIFT) | (addr & ~TARGET_PAGE_MASK);
1145 
1146     /*
1147      * Remove write permission unless this is a store, or the page is
1148      * already dirty, so that we TLB miss on later writes to update
1149      * the dirty bit.
1150      */
1151     if (access_type != MMU_DATA_STORE && !(pte & PTE_D)) {
1152         prot &= ~PAGE_WRITE;
1153     }
1154     *ret_prot = prot;
1155 
1156     return TRANSLATE_SUCCESS;
1157 }
1158 
1159 static void raise_mmu_exception(CPURISCVState *env, target_ulong address,
1160                                 MMUAccessType access_type, bool pmp_violation,
1161                                 bool first_stage, bool two_stage,
1162                                 bool two_stage_indirect)
1163 {
1164     CPUState *cs = env_cpu(env);
1165 
1166     switch (access_type) {
1167     case MMU_INST_FETCH:
1168         if (env->virt_enabled && !first_stage) {
1169             cs->exception_index = RISCV_EXCP_INST_GUEST_PAGE_FAULT;
1170         } else {
1171             cs->exception_index = pmp_violation ?
1172                 RISCV_EXCP_INST_ACCESS_FAULT : RISCV_EXCP_INST_PAGE_FAULT;
1173         }
1174         break;
1175     case MMU_DATA_LOAD:
1176         if (two_stage && !first_stage) {
1177             cs->exception_index = RISCV_EXCP_LOAD_GUEST_ACCESS_FAULT;
1178         } else {
1179             cs->exception_index = pmp_violation ?
1180                 RISCV_EXCP_LOAD_ACCESS_FAULT : RISCV_EXCP_LOAD_PAGE_FAULT;
1181         }
1182         break;
1183     case MMU_DATA_STORE:
1184         if (two_stage && !first_stage) {
1185             cs->exception_index = RISCV_EXCP_STORE_GUEST_AMO_ACCESS_FAULT;
1186         } else {
1187             cs->exception_index = pmp_violation ?
1188                 RISCV_EXCP_STORE_AMO_ACCESS_FAULT :
1189                 RISCV_EXCP_STORE_PAGE_FAULT;
1190         }
1191         break;
1192     default:
1193         g_assert_not_reached();
1194     }
1195     env->badaddr = address;
1196     env->two_stage_lookup = two_stage;
1197     env->two_stage_indirect_lookup = two_stage_indirect;
1198 }
1199 
1200 hwaddr riscv_cpu_get_phys_page_debug(CPUState *cs, vaddr addr)
1201 {
1202     RISCVCPU *cpu = RISCV_CPU(cs);
1203     CPURISCVState *env = &cpu->env;
1204     hwaddr phys_addr;
1205     int prot;
1206     int mmu_idx = riscv_env_mmu_index(&cpu->env, false);
1207 
1208     if (get_physical_address(env, &phys_addr, &prot, addr, NULL, 0, mmu_idx,
1209                              true, env->virt_enabled, true)) {
1210         return -1;
1211     }
1212 
1213     if (env->virt_enabled) {
1214         if (get_physical_address(env, &phys_addr, &prot, phys_addr, NULL,
1215                                  0, mmu_idx, false, true, true)) {
1216             return -1;
1217         }
1218     }
1219 
1220     return phys_addr & TARGET_PAGE_MASK;
1221 }
1222 
1223 void riscv_cpu_do_transaction_failed(CPUState *cs, hwaddr physaddr,
1224                                      vaddr addr, unsigned size,
1225                                      MMUAccessType access_type,
1226                                      int mmu_idx, MemTxAttrs attrs,
1227                                      MemTxResult response, uintptr_t retaddr)
1228 {
1229     RISCVCPU *cpu = RISCV_CPU(cs);
1230     CPURISCVState *env = &cpu->env;
1231 
1232     if (access_type == MMU_DATA_STORE) {
1233         cs->exception_index = RISCV_EXCP_STORE_AMO_ACCESS_FAULT;
1234     } else if (access_type == MMU_DATA_LOAD) {
1235         cs->exception_index = RISCV_EXCP_LOAD_ACCESS_FAULT;
1236     } else {
1237         cs->exception_index = RISCV_EXCP_INST_ACCESS_FAULT;
1238     }
1239 
1240     env->badaddr = addr;
1241     env->two_stage_lookup = mmuidx_2stage(mmu_idx);
1242     env->two_stage_indirect_lookup = false;
1243     cpu_loop_exit_restore(cs, retaddr);
1244 }
1245 
1246 void riscv_cpu_do_unaligned_access(CPUState *cs, vaddr addr,
1247                                    MMUAccessType access_type, int mmu_idx,
1248                                    uintptr_t retaddr)
1249 {
1250     RISCVCPU *cpu = RISCV_CPU(cs);
1251     CPURISCVState *env = &cpu->env;
1252     switch (access_type) {
1253     case MMU_INST_FETCH:
1254         cs->exception_index = RISCV_EXCP_INST_ADDR_MIS;
1255         break;
1256     case MMU_DATA_LOAD:
1257         cs->exception_index = RISCV_EXCP_LOAD_ADDR_MIS;
1258         break;
1259     case MMU_DATA_STORE:
1260         cs->exception_index = RISCV_EXCP_STORE_AMO_ADDR_MIS;
1261         break;
1262     default:
1263         g_assert_not_reached();
1264     }
1265     env->badaddr = addr;
1266     env->two_stage_lookup = mmuidx_2stage(mmu_idx);
1267     env->two_stage_indirect_lookup = false;
1268     cpu_loop_exit_restore(cs, retaddr);
1269 }
1270 
1271 
1272 static void pmu_tlb_fill_incr_ctr(RISCVCPU *cpu, MMUAccessType access_type)
1273 {
1274     enum riscv_pmu_event_idx pmu_event_type;
1275 
1276     switch (access_type) {
1277     case MMU_INST_FETCH:
1278         pmu_event_type = RISCV_PMU_EVENT_CACHE_ITLB_PREFETCH_MISS;
1279         break;
1280     case MMU_DATA_LOAD:
1281         pmu_event_type = RISCV_PMU_EVENT_CACHE_DTLB_READ_MISS;
1282         break;
1283     case MMU_DATA_STORE:
1284         pmu_event_type = RISCV_PMU_EVENT_CACHE_DTLB_WRITE_MISS;
1285         break;
1286     default:
1287         return;
1288     }
1289 
1290     riscv_pmu_incr_ctr(cpu, pmu_event_type);
1291 }
1292 
1293 bool riscv_cpu_tlb_fill(CPUState *cs, vaddr address, int size,
1294                         MMUAccessType access_type, int mmu_idx,
1295                         bool probe, uintptr_t retaddr)
1296 {
1297     RISCVCPU *cpu = RISCV_CPU(cs);
1298     CPURISCVState *env = &cpu->env;
1299     vaddr im_address;
1300     hwaddr pa = 0;
1301     int prot, prot2, prot_pmp;
1302     bool pmp_violation = false;
1303     bool first_stage_error = true;
1304     bool two_stage_lookup = mmuidx_2stage(mmu_idx);
1305     bool two_stage_indirect_error = false;
1306     int ret = TRANSLATE_FAIL;
1307     int mode = mmu_idx;
1308     /* default TLB page size */
1309     target_ulong tlb_size = TARGET_PAGE_SIZE;
1310 
1311     env->guest_phys_fault_addr = 0;
1312 
1313     qemu_log_mask(CPU_LOG_MMU, "%s ad %" VADDR_PRIx " rw %d mmu_idx %d\n",
1314                   __func__, address, access_type, mmu_idx);
1315 
1316     pmu_tlb_fill_incr_ctr(cpu, access_type);
1317     if (two_stage_lookup) {
1318         /* Two stage lookup */
1319         ret = get_physical_address(env, &pa, &prot, address,
1320                                    &env->guest_phys_fault_addr, access_type,
1321                                    mmu_idx, true, true, false);
1322 
1323         /*
1324          * A G-stage exception may be triggered during two state lookup.
1325          * And the env->guest_phys_fault_addr has already been set in
1326          * get_physical_address().
1327          */
1328         if (ret == TRANSLATE_G_STAGE_FAIL) {
1329             first_stage_error = false;
1330             two_stage_indirect_error = true;
1331         }
1332 
1333         qemu_log_mask(CPU_LOG_MMU,
1334                       "%s 1st-stage address=%" VADDR_PRIx " ret %d physical "
1335                       HWADDR_FMT_plx " prot %d\n",
1336                       __func__, address, ret, pa, prot);
1337 
1338         if (ret == TRANSLATE_SUCCESS) {
1339             /* Second stage lookup */
1340             im_address = pa;
1341 
1342             ret = get_physical_address(env, &pa, &prot2, im_address, NULL,
1343                                        access_type, MMUIdx_U, false, true,
1344                                        false);
1345 
1346             qemu_log_mask(CPU_LOG_MMU,
1347                           "%s 2nd-stage address=%" VADDR_PRIx
1348                           " ret %d physical "
1349                           HWADDR_FMT_plx " prot %d\n",
1350                           __func__, im_address, ret, pa, prot2);
1351 
1352             prot &= prot2;
1353 
1354             if (ret == TRANSLATE_SUCCESS) {
1355                 ret = get_physical_address_pmp(env, &prot_pmp, pa,
1356                                                size, access_type, mode);
1357                 tlb_size = pmp_get_tlb_size(env, pa);
1358 
1359                 qemu_log_mask(CPU_LOG_MMU,
1360                               "%s PMP address=" HWADDR_FMT_plx " ret %d prot"
1361                               " %d tlb_size " TARGET_FMT_lu "\n",
1362                               __func__, pa, ret, prot_pmp, tlb_size);
1363 
1364                 prot &= prot_pmp;
1365             }
1366 
1367             if (ret != TRANSLATE_SUCCESS) {
1368                 /*
1369                  * Guest physical address translation failed, this is a HS
1370                  * level exception
1371                  */
1372                 first_stage_error = false;
1373                 env->guest_phys_fault_addr = (im_address |
1374                                               (address &
1375                                                (TARGET_PAGE_SIZE - 1))) >> 2;
1376             }
1377         }
1378     } else {
1379         /* Single stage lookup */
1380         ret = get_physical_address(env, &pa, &prot, address, NULL,
1381                                    access_type, mmu_idx, true, false, false);
1382 
1383         qemu_log_mask(CPU_LOG_MMU,
1384                       "%s address=%" VADDR_PRIx " ret %d physical "
1385                       HWADDR_FMT_plx " prot %d\n",
1386                       __func__, address, ret, pa, prot);
1387 
1388         if (ret == TRANSLATE_SUCCESS) {
1389             ret = get_physical_address_pmp(env, &prot_pmp, pa,
1390                                            size, access_type, mode);
1391             tlb_size = pmp_get_tlb_size(env, pa);
1392 
1393             qemu_log_mask(CPU_LOG_MMU,
1394                           "%s PMP address=" HWADDR_FMT_plx " ret %d prot"
1395                           " %d tlb_size " TARGET_FMT_lu "\n",
1396                           __func__, pa, ret, prot_pmp, tlb_size);
1397 
1398             prot &= prot_pmp;
1399         }
1400     }
1401 
1402     if (ret == TRANSLATE_PMP_FAIL) {
1403         pmp_violation = true;
1404     }
1405 
1406     if (ret == TRANSLATE_SUCCESS) {
1407         tlb_set_page(cs, address & ~(tlb_size - 1), pa & ~(tlb_size - 1),
1408                      prot, mmu_idx, tlb_size);
1409         return true;
1410     } else if (probe) {
1411         return false;
1412     } else {
1413         raise_mmu_exception(env, address, access_type, pmp_violation,
1414                             first_stage_error, two_stage_lookup,
1415                             two_stage_indirect_error);
1416         cpu_loop_exit_restore(cs, retaddr);
1417     }
1418 
1419     return true;
1420 }
1421 
1422 static target_ulong riscv_transformed_insn(CPURISCVState *env,
1423                                            target_ulong insn,
1424                                            target_ulong taddr)
1425 {
1426     target_ulong xinsn = 0;
1427     target_ulong access_rs1 = 0, access_imm = 0, access_size = 0;
1428 
1429     /*
1430      * Only Quadrant 0 and Quadrant 2 of RVC instruction space need to
1431      * be uncompressed. The Quadrant 1 of RVC instruction space need
1432      * not be transformed because these instructions won't generate
1433      * any load/store trap.
1434      */
1435 
1436     if ((insn & 0x3) != 0x3) {
1437         /* Transform 16bit instruction into 32bit instruction */
1438         switch (GET_C_OP(insn)) {
1439         case OPC_RISC_C_OP_QUAD0: /* Quadrant 0 */
1440             switch (GET_C_FUNC(insn)) {
1441             case OPC_RISC_C_FUNC_FLD_LQ:
1442                 if (riscv_cpu_xlen(env) != 128) { /* C.FLD (RV32/64) */
1443                     xinsn = OPC_RISC_FLD;
1444                     xinsn = SET_RD(xinsn, GET_C_RS2S(insn));
1445                     access_rs1 = GET_C_RS1S(insn);
1446                     access_imm = GET_C_LD_IMM(insn);
1447                     access_size = 8;
1448                 }
1449                 break;
1450             case OPC_RISC_C_FUNC_LW: /* C.LW */
1451                 xinsn = OPC_RISC_LW;
1452                 xinsn = SET_RD(xinsn, GET_C_RS2S(insn));
1453                 access_rs1 = GET_C_RS1S(insn);
1454                 access_imm = GET_C_LW_IMM(insn);
1455                 access_size = 4;
1456                 break;
1457             case OPC_RISC_C_FUNC_FLW_LD:
1458                 if (riscv_cpu_xlen(env) == 32) { /* C.FLW (RV32) */
1459                     xinsn = OPC_RISC_FLW;
1460                     xinsn = SET_RD(xinsn, GET_C_RS2S(insn));
1461                     access_rs1 = GET_C_RS1S(insn);
1462                     access_imm = GET_C_LW_IMM(insn);
1463                     access_size = 4;
1464                 } else { /* C.LD (RV64/RV128) */
1465                     xinsn = OPC_RISC_LD;
1466                     xinsn = SET_RD(xinsn, GET_C_RS2S(insn));
1467                     access_rs1 = GET_C_RS1S(insn);
1468                     access_imm = GET_C_LD_IMM(insn);
1469                     access_size = 8;
1470                 }
1471                 break;
1472             case OPC_RISC_C_FUNC_FSD_SQ:
1473                 if (riscv_cpu_xlen(env) != 128) { /* C.FSD (RV32/64) */
1474                     xinsn = OPC_RISC_FSD;
1475                     xinsn = SET_RS2(xinsn, GET_C_RS2S(insn));
1476                     access_rs1 = GET_C_RS1S(insn);
1477                     access_imm = GET_C_SD_IMM(insn);
1478                     access_size = 8;
1479                 }
1480                 break;
1481             case OPC_RISC_C_FUNC_SW: /* C.SW */
1482                 xinsn = OPC_RISC_SW;
1483                 xinsn = SET_RS2(xinsn, GET_C_RS2S(insn));
1484                 access_rs1 = GET_C_RS1S(insn);
1485                 access_imm = GET_C_SW_IMM(insn);
1486                 access_size = 4;
1487                 break;
1488             case OPC_RISC_C_FUNC_FSW_SD:
1489                 if (riscv_cpu_xlen(env) == 32) { /* C.FSW (RV32) */
1490                     xinsn = OPC_RISC_FSW;
1491                     xinsn = SET_RS2(xinsn, GET_C_RS2S(insn));
1492                     access_rs1 = GET_C_RS1S(insn);
1493                     access_imm = GET_C_SW_IMM(insn);
1494                     access_size = 4;
1495                 } else { /* C.SD (RV64/RV128) */
1496                     xinsn = OPC_RISC_SD;
1497                     xinsn = SET_RS2(xinsn, GET_C_RS2S(insn));
1498                     access_rs1 = GET_C_RS1S(insn);
1499                     access_imm = GET_C_SD_IMM(insn);
1500                     access_size = 8;
1501                 }
1502                 break;
1503             default:
1504                 break;
1505             }
1506             break;
1507         case OPC_RISC_C_OP_QUAD2: /* Quadrant 2 */
1508             switch (GET_C_FUNC(insn)) {
1509             case OPC_RISC_C_FUNC_FLDSP_LQSP:
1510                 if (riscv_cpu_xlen(env) != 128) { /* C.FLDSP (RV32/64) */
1511                     xinsn = OPC_RISC_FLD;
1512                     xinsn = SET_RD(xinsn, GET_C_RD(insn));
1513                     access_rs1 = 2;
1514                     access_imm = GET_C_LDSP_IMM(insn);
1515                     access_size = 8;
1516                 }
1517                 break;
1518             case OPC_RISC_C_FUNC_LWSP: /* C.LWSP */
1519                 xinsn = OPC_RISC_LW;
1520                 xinsn = SET_RD(xinsn, GET_C_RD(insn));
1521                 access_rs1 = 2;
1522                 access_imm = GET_C_LWSP_IMM(insn);
1523                 access_size = 4;
1524                 break;
1525             case OPC_RISC_C_FUNC_FLWSP_LDSP:
1526                 if (riscv_cpu_xlen(env) == 32) { /* C.FLWSP (RV32) */
1527                     xinsn = OPC_RISC_FLW;
1528                     xinsn = SET_RD(xinsn, GET_C_RD(insn));
1529                     access_rs1 = 2;
1530                     access_imm = GET_C_LWSP_IMM(insn);
1531                     access_size = 4;
1532                 } else { /* C.LDSP (RV64/RV128) */
1533                     xinsn = OPC_RISC_LD;
1534                     xinsn = SET_RD(xinsn, GET_C_RD(insn));
1535                     access_rs1 = 2;
1536                     access_imm = GET_C_LDSP_IMM(insn);
1537                     access_size = 8;
1538                 }
1539                 break;
1540             case OPC_RISC_C_FUNC_FSDSP_SQSP:
1541                 if (riscv_cpu_xlen(env) != 128) { /* C.FSDSP (RV32/64) */
1542                     xinsn = OPC_RISC_FSD;
1543                     xinsn = SET_RS2(xinsn, GET_C_RS2(insn));
1544                     access_rs1 = 2;
1545                     access_imm = GET_C_SDSP_IMM(insn);
1546                     access_size = 8;
1547                 }
1548                 break;
1549             case OPC_RISC_C_FUNC_SWSP: /* C.SWSP */
1550                 xinsn = OPC_RISC_SW;
1551                 xinsn = SET_RS2(xinsn, GET_C_RS2(insn));
1552                 access_rs1 = 2;
1553                 access_imm = GET_C_SWSP_IMM(insn);
1554                 access_size = 4;
1555                 break;
1556             case 7:
1557                 if (riscv_cpu_xlen(env) == 32) { /* C.FSWSP (RV32) */
1558                     xinsn = OPC_RISC_FSW;
1559                     xinsn = SET_RS2(xinsn, GET_C_RS2(insn));
1560                     access_rs1 = 2;
1561                     access_imm = GET_C_SWSP_IMM(insn);
1562                     access_size = 4;
1563                 } else { /* C.SDSP (RV64/RV128) */
1564                     xinsn = OPC_RISC_SD;
1565                     xinsn = SET_RS2(xinsn, GET_C_RS2(insn));
1566                     access_rs1 = 2;
1567                     access_imm = GET_C_SDSP_IMM(insn);
1568                     access_size = 8;
1569                 }
1570                 break;
1571             default:
1572                 break;
1573             }
1574             break;
1575         default:
1576             break;
1577         }
1578 
1579         /*
1580          * Clear Bit1 of transformed instruction to indicate that
1581          * original insruction was a 16bit instruction
1582          */
1583         xinsn &= ~((target_ulong)0x2);
1584     } else {
1585         /* Transform 32bit (or wider) instructions */
1586         switch (MASK_OP_MAJOR(insn)) {
1587         case OPC_RISC_ATOMIC:
1588             xinsn = insn;
1589             access_rs1 = GET_RS1(insn);
1590             access_size = 1 << GET_FUNCT3(insn);
1591             break;
1592         case OPC_RISC_LOAD:
1593         case OPC_RISC_FP_LOAD:
1594             xinsn = SET_I_IMM(insn, 0);
1595             access_rs1 = GET_RS1(insn);
1596             access_imm = GET_IMM(insn);
1597             access_size = 1 << GET_FUNCT3(insn);
1598             break;
1599         case OPC_RISC_STORE:
1600         case OPC_RISC_FP_STORE:
1601             xinsn = SET_S_IMM(insn, 0);
1602             access_rs1 = GET_RS1(insn);
1603             access_imm = GET_STORE_IMM(insn);
1604             access_size = 1 << GET_FUNCT3(insn);
1605             break;
1606         case OPC_RISC_SYSTEM:
1607             if (MASK_OP_SYSTEM(insn) == OPC_RISC_HLVHSV) {
1608                 xinsn = insn;
1609                 access_rs1 = GET_RS1(insn);
1610                 access_size = 1 << ((GET_FUNCT7(insn) >> 1) & 0x3);
1611                 access_size = 1 << access_size;
1612             }
1613             break;
1614         default:
1615             break;
1616         }
1617     }
1618 
1619     if (access_size) {
1620         xinsn = SET_RS1(xinsn, (taddr - (env->gpr[access_rs1] + access_imm)) &
1621                                (access_size - 1));
1622     }
1623 
1624     return xinsn;
1625 }
1626 #endif /* !CONFIG_USER_ONLY */
1627 
1628 /*
1629  * Handle Traps
1630  *
1631  * Adapted from Spike's processor_t::take_trap.
1632  *
1633  */
1634 void riscv_cpu_do_interrupt(CPUState *cs)
1635 {
1636 #if !defined(CONFIG_USER_ONLY)
1637 
1638     RISCVCPU *cpu = RISCV_CPU(cs);
1639     CPURISCVState *env = &cpu->env;
1640     bool write_gva = false;
1641     uint64_t s;
1642 
1643     /*
1644      * cs->exception is 32-bits wide unlike mcause which is XLEN-bits wide
1645      * so we mask off the MSB and separate into trap type and cause.
1646      */
1647     bool async = !!(cs->exception_index & RISCV_EXCP_INT_FLAG);
1648     target_ulong cause = cs->exception_index & RISCV_EXCP_INT_MASK;
1649     uint64_t deleg = async ? env->mideleg : env->medeleg;
1650     bool s_injected = env->mvip & (1 << cause) & env->mvien &&
1651         !(env->mip & (1 << cause));
1652     bool vs_injected = env->hvip & (1 << cause) & env->hvien &&
1653         !(env->mip & (1 << cause));
1654     target_ulong tval = 0;
1655     target_ulong tinst = 0;
1656     target_ulong htval = 0;
1657     target_ulong mtval2 = 0;
1658 
1659     if (!async) {
1660         /* set tval to badaddr for traps with address information */
1661         switch (cause) {
1662         case RISCV_EXCP_SEMIHOST:
1663             do_common_semihosting(cs);
1664             env->pc += 4;
1665             return;
1666         case RISCV_EXCP_LOAD_GUEST_ACCESS_FAULT:
1667         case RISCV_EXCP_STORE_GUEST_AMO_ACCESS_FAULT:
1668         case RISCV_EXCP_LOAD_ADDR_MIS:
1669         case RISCV_EXCP_STORE_AMO_ADDR_MIS:
1670         case RISCV_EXCP_LOAD_ACCESS_FAULT:
1671         case RISCV_EXCP_STORE_AMO_ACCESS_FAULT:
1672         case RISCV_EXCP_LOAD_PAGE_FAULT:
1673         case RISCV_EXCP_STORE_PAGE_FAULT:
1674             write_gva = env->two_stage_lookup;
1675             tval = env->badaddr;
1676             if (env->two_stage_indirect_lookup) {
1677                 /*
1678                  * special pseudoinstruction for G-stage fault taken while
1679                  * doing VS-stage page table walk.
1680                  */
1681                 tinst = (riscv_cpu_xlen(env) == 32) ? 0x00002000 : 0x00003000;
1682             } else {
1683                 /*
1684                  * The "Addr. Offset" field in transformed instruction is
1685                  * non-zero only for misaligned access.
1686                  */
1687                 tinst = riscv_transformed_insn(env, env->bins, tval);
1688             }
1689             break;
1690         case RISCV_EXCP_INST_GUEST_PAGE_FAULT:
1691         case RISCV_EXCP_INST_ADDR_MIS:
1692         case RISCV_EXCP_INST_ACCESS_FAULT:
1693         case RISCV_EXCP_INST_PAGE_FAULT:
1694             write_gva = env->two_stage_lookup;
1695             tval = env->badaddr;
1696             if (env->two_stage_indirect_lookup) {
1697                 /*
1698                  * special pseudoinstruction for G-stage fault taken while
1699                  * doing VS-stage page table walk.
1700                  */
1701                 tinst = (riscv_cpu_xlen(env) == 32) ? 0x00002000 : 0x00003000;
1702             }
1703             break;
1704         case RISCV_EXCP_ILLEGAL_INST:
1705         case RISCV_EXCP_VIRT_INSTRUCTION_FAULT:
1706             tval = env->bins;
1707             break;
1708         case RISCV_EXCP_BREAKPOINT:
1709             if (cs->watchpoint_hit) {
1710                 tval = cs->watchpoint_hit->hitaddr;
1711                 cs->watchpoint_hit = NULL;
1712             }
1713             break;
1714         default:
1715             break;
1716         }
1717         /* ecall is dispatched as one cause so translate based on mode */
1718         if (cause == RISCV_EXCP_U_ECALL) {
1719             assert(env->priv <= 3);
1720 
1721             if (env->priv == PRV_M) {
1722                 cause = RISCV_EXCP_M_ECALL;
1723             } else if (env->priv == PRV_S && env->virt_enabled) {
1724                 cause = RISCV_EXCP_VS_ECALL;
1725             } else if (env->priv == PRV_S && !env->virt_enabled) {
1726                 cause = RISCV_EXCP_S_ECALL;
1727             } else if (env->priv == PRV_U) {
1728                 cause = RISCV_EXCP_U_ECALL;
1729             }
1730         }
1731     }
1732 
1733     trace_riscv_trap(env->mhartid, async, cause, env->pc, tval,
1734                      riscv_cpu_get_trap_name(cause, async));
1735 
1736     qemu_log_mask(CPU_LOG_INT,
1737                   "%s: hart:"TARGET_FMT_ld", async:%d, cause:"TARGET_FMT_lx", "
1738                   "epc:0x"TARGET_FMT_lx", tval:0x"TARGET_FMT_lx", desc=%s\n",
1739                   __func__, env->mhartid, async, cause, env->pc, tval,
1740                   riscv_cpu_get_trap_name(cause, async));
1741 
1742     if (env->priv <= PRV_S && cause < 64 &&
1743         (((deleg >> cause) & 1) || s_injected || vs_injected)) {
1744         /* handle the trap in S-mode */
1745         if (riscv_has_ext(env, RVH)) {
1746             uint64_t hdeleg = async ? env->hideleg : env->hedeleg;
1747 
1748             if (env->virt_enabled &&
1749                 (((hdeleg >> cause) & 1) || vs_injected)) {
1750                 /* Trap to VS mode */
1751                 /*
1752                  * See if we need to adjust cause. Yes if its VS mode interrupt
1753                  * no if hypervisor has delegated one of hs mode's interrupt
1754                  */
1755                 if (async && (cause == IRQ_VS_TIMER || cause == IRQ_VS_SOFT ||
1756                               cause == IRQ_VS_EXT)) {
1757                     cause = cause - 1;
1758                 }
1759                 write_gva = false;
1760             } else if (env->virt_enabled) {
1761                 /* Trap into HS mode, from virt */
1762                 riscv_cpu_swap_hypervisor_regs(env);
1763                 env->hstatus = set_field(env->hstatus, HSTATUS_SPVP,
1764                                          env->priv);
1765                 env->hstatus = set_field(env->hstatus, HSTATUS_SPV, true);
1766 
1767                 htval = env->guest_phys_fault_addr;
1768 
1769                 riscv_cpu_set_virt_enabled(env, 0);
1770             } else {
1771                 /* Trap into HS mode */
1772                 env->hstatus = set_field(env->hstatus, HSTATUS_SPV, false);
1773                 htval = env->guest_phys_fault_addr;
1774             }
1775             env->hstatus = set_field(env->hstatus, HSTATUS_GVA, write_gva);
1776         }
1777 
1778         s = env->mstatus;
1779         s = set_field(s, MSTATUS_SPIE, get_field(s, MSTATUS_SIE));
1780         s = set_field(s, MSTATUS_SPP, env->priv);
1781         s = set_field(s, MSTATUS_SIE, 0);
1782         env->mstatus = s;
1783         env->scause = cause | ((target_ulong)async << (TARGET_LONG_BITS - 1));
1784         env->sepc = env->pc;
1785         env->stval = tval;
1786         env->htval = htval;
1787         env->htinst = tinst;
1788         env->pc = (env->stvec >> 2 << 2) +
1789                   ((async && (env->stvec & 3) == 1) ? cause * 4 : 0);
1790         riscv_cpu_set_mode(env, PRV_S);
1791     } else {
1792         /* handle the trap in M-mode */
1793         if (riscv_has_ext(env, RVH)) {
1794             if (env->virt_enabled) {
1795                 riscv_cpu_swap_hypervisor_regs(env);
1796             }
1797             env->mstatus = set_field(env->mstatus, MSTATUS_MPV,
1798                                      env->virt_enabled);
1799             if (env->virt_enabled && tval) {
1800                 env->mstatus = set_field(env->mstatus, MSTATUS_GVA, 1);
1801             }
1802 
1803             mtval2 = env->guest_phys_fault_addr;
1804 
1805             /* Trapping to M mode, virt is disabled */
1806             riscv_cpu_set_virt_enabled(env, 0);
1807         }
1808 
1809         s = env->mstatus;
1810         s = set_field(s, MSTATUS_MPIE, get_field(s, MSTATUS_MIE));
1811         s = set_field(s, MSTATUS_MPP, env->priv);
1812         s = set_field(s, MSTATUS_MIE, 0);
1813         env->mstatus = s;
1814         env->mcause = cause | ~(((target_ulong)-1) >> async);
1815         env->mepc = env->pc;
1816         env->mtval = tval;
1817         env->mtval2 = mtval2;
1818         env->mtinst = tinst;
1819         env->pc = (env->mtvec >> 2 << 2) +
1820                   ((async && (env->mtvec & 3) == 1) ? cause * 4 : 0);
1821         riscv_cpu_set_mode(env, PRV_M);
1822     }
1823 
1824     /*
1825      * NOTE: it is not necessary to yield load reservations here. It is only
1826      * necessary for an SC from "another hart" to cause a load reservation
1827      * to be yielded. Refer to the memory consistency model section of the
1828      * RISC-V ISA Specification.
1829      */
1830 
1831     env->two_stage_lookup = false;
1832     env->two_stage_indirect_lookup = false;
1833 #endif
1834     cs->exception_index = RISCV_EXCP_NONE; /* mark handled to qemu */
1835 }
1836