xref: /openbmc/qemu/target/riscv/cpu_helper.c (revision 1f2355f5)
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 svade = riscv_cpu_cfg(env)->ext_svade;
911     bool svadu = riscv_cpu_cfg(env)->ext_svadu;
912     bool adue = svadu ? env->menvcfg & MENVCFG_ADUE : !svade;
913 
914     if (first_stage && two_stage && env->virt_enabled) {
915         pbmte = pbmte && (env->henvcfg & HENVCFG_PBMTE);
916         adue = adue && (env->henvcfg & HENVCFG_ADUE);
917     }
918 
919     int ptshift = (levels - 1) * ptidxbits;
920     target_ulong pte;
921     hwaddr pte_addr;
922     int i;
923 
924 #if !TCG_OVERSIZED_GUEST
925 restart:
926 #endif
927     for (i = 0; i < levels; i++, ptshift -= ptidxbits) {
928         target_ulong idx;
929         if (i == 0) {
930             idx = (addr >> (PGSHIFT + ptshift)) &
931                            ((1 << (ptidxbits + widened)) - 1);
932         } else {
933             idx = (addr >> (PGSHIFT + ptshift)) &
934                            ((1 << ptidxbits) - 1);
935         }
936 
937         /* check that physical address of PTE is legal */
938 
939         if (two_stage && first_stage) {
940             int vbase_prot;
941             hwaddr vbase;
942 
943             /* Do the second stage translation on the base PTE address. */
944             int vbase_ret = get_physical_address(env, &vbase, &vbase_prot,
945                                                  base, NULL, MMU_DATA_LOAD,
946                                                  MMUIdx_U, false, true,
947                                                  is_debug);
948 
949             if (vbase_ret != TRANSLATE_SUCCESS) {
950                 if (fault_pte_addr) {
951                     *fault_pte_addr = (base + idx * ptesize) >> 2;
952                 }
953                 return TRANSLATE_G_STAGE_FAIL;
954             }
955 
956             pte_addr = vbase + idx * ptesize;
957         } else {
958             pte_addr = base + idx * ptesize;
959         }
960 
961         int pmp_prot;
962         int pmp_ret = get_physical_address_pmp(env, &pmp_prot, pte_addr,
963                                                sizeof(target_ulong),
964                                                MMU_DATA_LOAD, PRV_S);
965         if (pmp_ret != TRANSLATE_SUCCESS) {
966             return TRANSLATE_PMP_FAIL;
967         }
968 
969         if (riscv_cpu_mxl(env) == MXL_RV32) {
970             pte = address_space_ldl(cs->as, pte_addr, attrs, &res);
971         } else {
972             pte = address_space_ldq(cs->as, pte_addr, attrs, &res);
973         }
974 
975         if (res != MEMTX_OK) {
976             return TRANSLATE_FAIL;
977         }
978 
979         if (riscv_cpu_sxl(env) == MXL_RV32) {
980             ppn = pte >> PTE_PPN_SHIFT;
981         } else {
982             if (pte & PTE_RESERVED) {
983                 return TRANSLATE_FAIL;
984             }
985 
986             if (!pbmte && (pte & PTE_PBMT)) {
987                 return TRANSLATE_FAIL;
988             }
989 
990             if (!riscv_cpu_cfg(env)->ext_svnapot && (pte & PTE_N)) {
991                 return TRANSLATE_FAIL;
992             }
993 
994             ppn = (pte & (target_ulong)PTE_PPN_MASK) >> PTE_PPN_SHIFT;
995         }
996 
997         if (!(pte & PTE_V)) {
998             /* Invalid PTE */
999             return TRANSLATE_FAIL;
1000         }
1001         if (pte & (PTE_R | PTE_W | PTE_X)) {
1002             goto leaf;
1003         }
1004 
1005         /* Inner PTE, continue walking */
1006         if (pte & (PTE_D | PTE_A | PTE_U | PTE_ATTR)) {
1007             return TRANSLATE_FAIL;
1008         }
1009         base = ppn << PGSHIFT;
1010     }
1011 
1012     /* No leaf pte at any translation level. */
1013     return TRANSLATE_FAIL;
1014 
1015  leaf:
1016     if (ppn & ((1ULL << ptshift) - 1)) {
1017         /* Misaligned PPN */
1018         return TRANSLATE_FAIL;
1019     }
1020     if (!pbmte && (pte & PTE_PBMT)) {
1021         /* Reserved without Svpbmt. */
1022         return TRANSLATE_FAIL;
1023     }
1024 
1025     /* Check for reserved combinations of RWX flags. */
1026     switch (pte & (PTE_R | PTE_W | PTE_X)) {
1027     case PTE_W:
1028     case PTE_W | PTE_X:
1029         return TRANSLATE_FAIL;
1030     }
1031 
1032     int prot = 0;
1033     if (pte & PTE_R) {
1034         prot |= PAGE_READ;
1035     }
1036     if (pte & PTE_W) {
1037         prot |= PAGE_WRITE;
1038     }
1039     if (pte & PTE_X) {
1040         bool mxr = false;
1041 
1042         /*
1043          * Use mstatus for first stage or for the second stage without
1044          * virt_enabled (MPRV+MPV)
1045          */
1046         if (first_stage || !env->virt_enabled) {
1047             mxr = get_field(env->mstatus, MSTATUS_MXR);
1048         }
1049 
1050         /* MPRV+MPV case, check VSSTATUS */
1051         if (first_stage && two_stage && !env->virt_enabled) {
1052             mxr |= get_field(env->vsstatus, MSTATUS_MXR);
1053         }
1054 
1055         /*
1056          * Setting MXR at HS-level overrides both VS-stage and G-stage
1057          * execute-only permissions
1058          */
1059         if (env->virt_enabled) {
1060             mxr |= get_field(env->mstatus_hs, MSTATUS_MXR);
1061         }
1062 
1063         if (mxr) {
1064             prot |= PAGE_READ;
1065         }
1066         prot |= PAGE_EXEC;
1067     }
1068 
1069     if (pte & PTE_U) {
1070         if (mode != PRV_U) {
1071             if (!mmuidx_sum(mmu_idx)) {
1072                 return TRANSLATE_FAIL;
1073             }
1074             /* SUM allows only read+write, not execute. */
1075             prot &= PAGE_READ | PAGE_WRITE;
1076         }
1077     } else if (mode != PRV_S) {
1078         /* Supervisor PTE flags when not S mode */
1079         return TRANSLATE_FAIL;
1080     }
1081 
1082     if (!((prot >> access_type) & 1)) {
1083         /* Access check failed */
1084         return TRANSLATE_FAIL;
1085     }
1086 
1087     target_ulong updated_pte = pte;
1088 
1089     /*
1090      * If ADUE is enabled, set accessed and dirty bits.
1091      * Otherwise raise an exception if necessary.
1092      */
1093     if (adue) {
1094         updated_pte |= PTE_A | (access_type == MMU_DATA_STORE ? PTE_D : 0);
1095     } else if (!(pte & PTE_A) ||
1096                (access_type == MMU_DATA_STORE && !(pte & PTE_D))) {
1097         return TRANSLATE_FAIL;
1098     }
1099 
1100     /* Page table updates need to be atomic with MTTCG enabled */
1101     if (updated_pte != pte && !is_debug) {
1102         if (!adue) {
1103             return TRANSLATE_FAIL;
1104         }
1105 
1106         /*
1107          * - if accessed or dirty bits need updating, and the PTE is
1108          *   in RAM, then we do so atomically with a compare and swap.
1109          * - if the PTE is in IO space or ROM, then it can't be updated
1110          *   and we return TRANSLATE_FAIL.
1111          * - if the PTE changed by the time we went to update it, then
1112          *   it is no longer valid and we must re-walk the page table.
1113          */
1114         MemoryRegion *mr;
1115         hwaddr l = sizeof(target_ulong), addr1;
1116         mr = address_space_translate(cs->as, pte_addr, &addr1, &l,
1117                                      false, MEMTXATTRS_UNSPECIFIED);
1118         if (memory_region_is_ram(mr)) {
1119             target_ulong *pte_pa = qemu_map_ram_ptr(mr->ram_block, addr1);
1120 #if TCG_OVERSIZED_GUEST
1121             /*
1122              * MTTCG is not enabled on oversized TCG guests so
1123              * page table updates do not need to be atomic
1124              */
1125             *pte_pa = pte = updated_pte;
1126 #else
1127             target_ulong old_pte = qatomic_cmpxchg(pte_pa, pte, updated_pte);
1128             if (old_pte != pte) {
1129                 goto restart;
1130             }
1131             pte = updated_pte;
1132 #endif
1133         } else {
1134             /*
1135              * Misconfigured PTE in ROM (AD bits are not preset) or
1136              * PTE is in IO space and can't be updated atomically.
1137              */
1138             return TRANSLATE_FAIL;
1139         }
1140     }
1141 
1142     /* For superpage mappings, make a fake leaf PTE for the TLB's benefit. */
1143     target_ulong vpn = addr >> PGSHIFT;
1144 
1145     if (riscv_cpu_cfg(env)->ext_svnapot && (pte & PTE_N)) {
1146         napot_bits = ctzl(ppn) + 1;
1147         if ((i != (levels - 1)) || (napot_bits != 4)) {
1148             return TRANSLATE_FAIL;
1149         }
1150     }
1151 
1152     napot_mask = (1 << napot_bits) - 1;
1153     *physical = (((ppn & ~napot_mask) | (vpn & napot_mask) |
1154                   (vpn & (((target_ulong)1 << ptshift) - 1))
1155                  ) << PGSHIFT) | (addr & ~TARGET_PAGE_MASK);
1156 
1157     /*
1158      * Remove write permission unless this is a store, or the page is
1159      * already dirty, so that we TLB miss on later writes to update
1160      * the dirty bit.
1161      */
1162     if (access_type != MMU_DATA_STORE && !(pte & PTE_D)) {
1163         prot &= ~PAGE_WRITE;
1164     }
1165     *ret_prot = prot;
1166 
1167     return TRANSLATE_SUCCESS;
1168 }
1169 
1170 static void raise_mmu_exception(CPURISCVState *env, target_ulong address,
1171                                 MMUAccessType access_type, bool pmp_violation,
1172                                 bool first_stage, bool two_stage,
1173                                 bool two_stage_indirect)
1174 {
1175     CPUState *cs = env_cpu(env);
1176 
1177     switch (access_type) {
1178     case MMU_INST_FETCH:
1179         if (env->virt_enabled && !first_stage) {
1180             cs->exception_index = RISCV_EXCP_INST_GUEST_PAGE_FAULT;
1181         } else {
1182             cs->exception_index = pmp_violation ?
1183                 RISCV_EXCP_INST_ACCESS_FAULT : RISCV_EXCP_INST_PAGE_FAULT;
1184         }
1185         break;
1186     case MMU_DATA_LOAD:
1187         if (two_stage && !first_stage) {
1188             cs->exception_index = RISCV_EXCP_LOAD_GUEST_ACCESS_FAULT;
1189         } else {
1190             cs->exception_index = pmp_violation ?
1191                 RISCV_EXCP_LOAD_ACCESS_FAULT : RISCV_EXCP_LOAD_PAGE_FAULT;
1192         }
1193         break;
1194     case MMU_DATA_STORE:
1195         if (two_stage && !first_stage) {
1196             cs->exception_index = RISCV_EXCP_STORE_GUEST_AMO_ACCESS_FAULT;
1197         } else {
1198             cs->exception_index = pmp_violation ?
1199                 RISCV_EXCP_STORE_AMO_ACCESS_FAULT :
1200                 RISCV_EXCP_STORE_PAGE_FAULT;
1201         }
1202         break;
1203     default:
1204         g_assert_not_reached();
1205     }
1206     env->badaddr = address;
1207     env->two_stage_lookup = two_stage;
1208     env->two_stage_indirect_lookup = two_stage_indirect;
1209 }
1210 
1211 hwaddr riscv_cpu_get_phys_page_debug(CPUState *cs, vaddr addr)
1212 {
1213     RISCVCPU *cpu = RISCV_CPU(cs);
1214     CPURISCVState *env = &cpu->env;
1215     hwaddr phys_addr;
1216     int prot;
1217     int mmu_idx = riscv_env_mmu_index(&cpu->env, false);
1218 
1219     if (get_physical_address(env, &phys_addr, &prot, addr, NULL, 0, mmu_idx,
1220                              true, env->virt_enabled, true)) {
1221         return -1;
1222     }
1223 
1224     if (env->virt_enabled) {
1225         if (get_physical_address(env, &phys_addr, &prot, phys_addr, NULL,
1226                                  0, MMUIdx_U, false, true, true)) {
1227             return -1;
1228         }
1229     }
1230 
1231     return phys_addr & TARGET_PAGE_MASK;
1232 }
1233 
1234 void riscv_cpu_do_transaction_failed(CPUState *cs, hwaddr physaddr,
1235                                      vaddr addr, unsigned size,
1236                                      MMUAccessType access_type,
1237                                      int mmu_idx, MemTxAttrs attrs,
1238                                      MemTxResult response, uintptr_t retaddr)
1239 {
1240     RISCVCPU *cpu = RISCV_CPU(cs);
1241     CPURISCVState *env = &cpu->env;
1242 
1243     if (access_type == MMU_DATA_STORE) {
1244         cs->exception_index = RISCV_EXCP_STORE_AMO_ACCESS_FAULT;
1245     } else if (access_type == MMU_DATA_LOAD) {
1246         cs->exception_index = RISCV_EXCP_LOAD_ACCESS_FAULT;
1247     } else {
1248         cs->exception_index = RISCV_EXCP_INST_ACCESS_FAULT;
1249     }
1250 
1251     env->badaddr = addr;
1252     env->two_stage_lookup = mmuidx_2stage(mmu_idx);
1253     env->two_stage_indirect_lookup = false;
1254     cpu_loop_exit_restore(cs, retaddr);
1255 }
1256 
1257 void riscv_cpu_do_unaligned_access(CPUState *cs, vaddr addr,
1258                                    MMUAccessType access_type, int mmu_idx,
1259                                    uintptr_t retaddr)
1260 {
1261     RISCVCPU *cpu = RISCV_CPU(cs);
1262     CPURISCVState *env = &cpu->env;
1263     switch (access_type) {
1264     case MMU_INST_FETCH:
1265         cs->exception_index = RISCV_EXCP_INST_ADDR_MIS;
1266         break;
1267     case MMU_DATA_LOAD:
1268         cs->exception_index = RISCV_EXCP_LOAD_ADDR_MIS;
1269         break;
1270     case MMU_DATA_STORE:
1271         cs->exception_index = RISCV_EXCP_STORE_AMO_ADDR_MIS;
1272         break;
1273     default:
1274         g_assert_not_reached();
1275     }
1276     env->badaddr = addr;
1277     env->two_stage_lookup = mmuidx_2stage(mmu_idx);
1278     env->two_stage_indirect_lookup = false;
1279     cpu_loop_exit_restore(cs, retaddr);
1280 }
1281 
1282 
1283 static void pmu_tlb_fill_incr_ctr(RISCVCPU *cpu, MMUAccessType access_type)
1284 {
1285     enum riscv_pmu_event_idx pmu_event_type;
1286 
1287     switch (access_type) {
1288     case MMU_INST_FETCH:
1289         pmu_event_type = RISCV_PMU_EVENT_CACHE_ITLB_PREFETCH_MISS;
1290         break;
1291     case MMU_DATA_LOAD:
1292         pmu_event_type = RISCV_PMU_EVENT_CACHE_DTLB_READ_MISS;
1293         break;
1294     case MMU_DATA_STORE:
1295         pmu_event_type = RISCV_PMU_EVENT_CACHE_DTLB_WRITE_MISS;
1296         break;
1297     default:
1298         return;
1299     }
1300 
1301     riscv_pmu_incr_ctr(cpu, pmu_event_type);
1302 }
1303 
1304 bool riscv_cpu_tlb_fill(CPUState *cs, vaddr address, int size,
1305                         MMUAccessType access_type, int mmu_idx,
1306                         bool probe, uintptr_t retaddr)
1307 {
1308     RISCVCPU *cpu = RISCV_CPU(cs);
1309     CPURISCVState *env = &cpu->env;
1310     vaddr im_address;
1311     hwaddr pa = 0;
1312     int prot, prot2, prot_pmp;
1313     bool pmp_violation = false;
1314     bool first_stage_error = true;
1315     bool two_stage_lookup = mmuidx_2stage(mmu_idx);
1316     bool two_stage_indirect_error = false;
1317     int ret = TRANSLATE_FAIL;
1318     int mode = mmuidx_priv(mmu_idx);
1319     /* default TLB page size */
1320     target_ulong tlb_size = TARGET_PAGE_SIZE;
1321 
1322     env->guest_phys_fault_addr = 0;
1323 
1324     qemu_log_mask(CPU_LOG_MMU, "%s ad %" VADDR_PRIx " rw %d mmu_idx %d\n",
1325                   __func__, address, access_type, mmu_idx);
1326 
1327     pmu_tlb_fill_incr_ctr(cpu, access_type);
1328     if (two_stage_lookup) {
1329         /* Two stage lookup */
1330         ret = get_physical_address(env, &pa, &prot, address,
1331                                    &env->guest_phys_fault_addr, access_type,
1332                                    mmu_idx, true, true, false);
1333 
1334         /*
1335          * A G-stage exception may be triggered during two state lookup.
1336          * And the env->guest_phys_fault_addr has already been set in
1337          * get_physical_address().
1338          */
1339         if (ret == TRANSLATE_G_STAGE_FAIL) {
1340             first_stage_error = false;
1341             two_stage_indirect_error = true;
1342         }
1343 
1344         qemu_log_mask(CPU_LOG_MMU,
1345                       "%s 1st-stage address=%" VADDR_PRIx " ret %d physical "
1346                       HWADDR_FMT_plx " prot %d\n",
1347                       __func__, address, ret, pa, prot);
1348 
1349         if (ret == TRANSLATE_SUCCESS) {
1350             /* Second stage lookup */
1351             im_address = pa;
1352 
1353             ret = get_physical_address(env, &pa, &prot2, im_address, NULL,
1354                                        access_type, MMUIdx_U, false, true,
1355                                        false);
1356 
1357             qemu_log_mask(CPU_LOG_MMU,
1358                           "%s 2nd-stage address=%" VADDR_PRIx
1359                           " ret %d physical "
1360                           HWADDR_FMT_plx " prot %d\n",
1361                           __func__, im_address, ret, pa, prot2);
1362 
1363             prot &= prot2;
1364 
1365             if (ret == TRANSLATE_SUCCESS) {
1366                 ret = get_physical_address_pmp(env, &prot_pmp, pa,
1367                                                size, access_type, mode);
1368                 tlb_size = pmp_get_tlb_size(env, pa);
1369 
1370                 qemu_log_mask(CPU_LOG_MMU,
1371                               "%s PMP address=" HWADDR_FMT_plx " ret %d prot"
1372                               " %d tlb_size " TARGET_FMT_lu "\n",
1373                               __func__, pa, ret, prot_pmp, tlb_size);
1374 
1375                 prot &= prot_pmp;
1376             }
1377 
1378             if (ret != TRANSLATE_SUCCESS) {
1379                 /*
1380                  * Guest physical address translation failed, this is a HS
1381                  * level exception
1382                  */
1383                 first_stage_error = false;
1384                 env->guest_phys_fault_addr = (im_address |
1385                                               (address &
1386                                                (TARGET_PAGE_SIZE - 1))) >> 2;
1387             }
1388         }
1389     } else {
1390         /* Single stage lookup */
1391         ret = get_physical_address(env, &pa, &prot, address, NULL,
1392                                    access_type, mmu_idx, true, false, false);
1393 
1394         qemu_log_mask(CPU_LOG_MMU,
1395                       "%s address=%" VADDR_PRIx " ret %d physical "
1396                       HWADDR_FMT_plx " prot %d\n",
1397                       __func__, address, ret, pa, prot);
1398 
1399         if (ret == TRANSLATE_SUCCESS) {
1400             ret = get_physical_address_pmp(env, &prot_pmp, pa,
1401                                            size, access_type, mode);
1402             tlb_size = pmp_get_tlb_size(env, pa);
1403 
1404             qemu_log_mask(CPU_LOG_MMU,
1405                           "%s PMP address=" HWADDR_FMT_plx " ret %d prot"
1406                           " %d tlb_size " TARGET_FMT_lu "\n",
1407                           __func__, pa, ret, prot_pmp, tlb_size);
1408 
1409             prot &= prot_pmp;
1410         }
1411     }
1412 
1413     if (ret == TRANSLATE_PMP_FAIL) {
1414         pmp_violation = true;
1415     }
1416 
1417     if (ret == TRANSLATE_SUCCESS) {
1418         tlb_set_page(cs, address & ~(tlb_size - 1), pa & ~(tlb_size - 1),
1419                      prot, mmu_idx, tlb_size);
1420         return true;
1421     } else if (probe) {
1422         return false;
1423     } else {
1424         raise_mmu_exception(env, address, access_type, pmp_violation,
1425                             first_stage_error, two_stage_lookup,
1426                             two_stage_indirect_error);
1427         cpu_loop_exit_restore(cs, retaddr);
1428     }
1429 
1430     return true;
1431 }
1432 
1433 static target_ulong riscv_transformed_insn(CPURISCVState *env,
1434                                            target_ulong insn,
1435                                            target_ulong taddr)
1436 {
1437     target_ulong xinsn = 0;
1438     target_ulong access_rs1 = 0, access_imm = 0, access_size = 0;
1439 
1440     /*
1441      * Only Quadrant 0 and Quadrant 2 of RVC instruction space need to
1442      * be uncompressed. The Quadrant 1 of RVC instruction space need
1443      * not be transformed because these instructions won't generate
1444      * any load/store trap.
1445      */
1446 
1447     if ((insn & 0x3) != 0x3) {
1448         /* Transform 16bit instruction into 32bit instruction */
1449         switch (GET_C_OP(insn)) {
1450         case OPC_RISC_C_OP_QUAD0: /* Quadrant 0 */
1451             switch (GET_C_FUNC(insn)) {
1452             case OPC_RISC_C_FUNC_FLD_LQ:
1453                 if (riscv_cpu_xlen(env) != 128) { /* C.FLD (RV32/64) */
1454                     xinsn = OPC_RISC_FLD;
1455                     xinsn = SET_RD(xinsn, GET_C_RS2S(insn));
1456                     access_rs1 = GET_C_RS1S(insn);
1457                     access_imm = GET_C_LD_IMM(insn);
1458                     access_size = 8;
1459                 }
1460                 break;
1461             case OPC_RISC_C_FUNC_LW: /* C.LW */
1462                 xinsn = OPC_RISC_LW;
1463                 xinsn = SET_RD(xinsn, GET_C_RS2S(insn));
1464                 access_rs1 = GET_C_RS1S(insn);
1465                 access_imm = GET_C_LW_IMM(insn);
1466                 access_size = 4;
1467                 break;
1468             case OPC_RISC_C_FUNC_FLW_LD:
1469                 if (riscv_cpu_xlen(env) == 32) { /* C.FLW (RV32) */
1470                     xinsn = OPC_RISC_FLW;
1471                     xinsn = SET_RD(xinsn, GET_C_RS2S(insn));
1472                     access_rs1 = GET_C_RS1S(insn);
1473                     access_imm = GET_C_LW_IMM(insn);
1474                     access_size = 4;
1475                 } else { /* C.LD (RV64/RV128) */
1476                     xinsn = OPC_RISC_LD;
1477                     xinsn = SET_RD(xinsn, GET_C_RS2S(insn));
1478                     access_rs1 = GET_C_RS1S(insn);
1479                     access_imm = GET_C_LD_IMM(insn);
1480                     access_size = 8;
1481                 }
1482                 break;
1483             case OPC_RISC_C_FUNC_FSD_SQ:
1484                 if (riscv_cpu_xlen(env) != 128) { /* C.FSD (RV32/64) */
1485                     xinsn = OPC_RISC_FSD;
1486                     xinsn = SET_RS2(xinsn, GET_C_RS2S(insn));
1487                     access_rs1 = GET_C_RS1S(insn);
1488                     access_imm = GET_C_SD_IMM(insn);
1489                     access_size = 8;
1490                 }
1491                 break;
1492             case OPC_RISC_C_FUNC_SW: /* C.SW */
1493                 xinsn = OPC_RISC_SW;
1494                 xinsn = SET_RS2(xinsn, GET_C_RS2S(insn));
1495                 access_rs1 = GET_C_RS1S(insn);
1496                 access_imm = GET_C_SW_IMM(insn);
1497                 access_size = 4;
1498                 break;
1499             case OPC_RISC_C_FUNC_FSW_SD:
1500                 if (riscv_cpu_xlen(env) == 32) { /* C.FSW (RV32) */
1501                     xinsn = OPC_RISC_FSW;
1502                     xinsn = SET_RS2(xinsn, GET_C_RS2S(insn));
1503                     access_rs1 = GET_C_RS1S(insn);
1504                     access_imm = GET_C_SW_IMM(insn);
1505                     access_size = 4;
1506                 } else { /* C.SD (RV64/RV128) */
1507                     xinsn = OPC_RISC_SD;
1508                     xinsn = SET_RS2(xinsn, GET_C_RS2S(insn));
1509                     access_rs1 = GET_C_RS1S(insn);
1510                     access_imm = GET_C_SD_IMM(insn);
1511                     access_size = 8;
1512                 }
1513                 break;
1514             default:
1515                 break;
1516             }
1517             break;
1518         case OPC_RISC_C_OP_QUAD2: /* Quadrant 2 */
1519             switch (GET_C_FUNC(insn)) {
1520             case OPC_RISC_C_FUNC_FLDSP_LQSP:
1521                 if (riscv_cpu_xlen(env) != 128) { /* C.FLDSP (RV32/64) */
1522                     xinsn = OPC_RISC_FLD;
1523                     xinsn = SET_RD(xinsn, GET_C_RD(insn));
1524                     access_rs1 = 2;
1525                     access_imm = GET_C_LDSP_IMM(insn);
1526                     access_size = 8;
1527                 }
1528                 break;
1529             case OPC_RISC_C_FUNC_LWSP: /* C.LWSP */
1530                 xinsn = OPC_RISC_LW;
1531                 xinsn = SET_RD(xinsn, GET_C_RD(insn));
1532                 access_rs1 = 2;
1533                 access_imm = GET_C_LWSP_IMM(insn);
1534                 access_size = 4;
1535                 break;
1536             case OPC_RISC_C_FUNC_FLWSP_LDSP:
1537                 if (riscv_cpu_xlen(env) == 32) { /* C.FLWSP (RV32) */
1538                     xinsn = OPC_RISC_FLW;
1539                     xinsn = SET_RD(xinsn, GET_C_RD(insn));
1540                     access_rs1 = 2;
1541                     access_imm = GET_C_LWSP_IMM(insn);
1542                     access_size = 4;
1543                 } else { /* C.LDSP (RV64/RV128) */
1544                     xinsn = OPC_RISC_LD;
1545                     xinsn = SET_RD(xinsn, GET_C_RD(insn));
1546                     access_rs1 = 2;
1547                     access_imm = GET_C_LDSP_IMM(insn);
1548                     access_size = 8;
1549                 }
1550                 break;
1551             case OPC_RISC_C_FUNC_FSDSP_SQSP:
1552                 if (riscv_cpu_xlen(env) != 128) { /* C.FSDSP (RV32/64) */
1553                     xinsn = OPC_RISC_FSD;
1554                     xinsn = SET_RS2(xinsn, GET_C_RS2(insn));
1555                     access_rs1 = 2;
1556                     access_imm = GET_C_SDSP_IMM(insn);
1557                     access_size = 8;
1558                 }
1559                 break;
1560             case OPC_RISC_C_FUNC_SWSP: /* C.SWSP */
1561                 xinsn = OPC_RISC_SW;
1562                 xinsn = SET_RS2(xinsn, GET_C_RS2(insn));
1563                 access_rs1 = 2;
1564                 access_imm = GET_C_SWSP_IMM(insn);
1565                 access_size = 4;
1566                 break;
1567             case 7:
1568                 if (riscv_cpu_xlen(env) == 32) { /* C.FSWSP (RV32) */
1569                     xinsn = OPC_RISC_FSW;
1570                     xinsn = SET_RS2(xinsn, GET_C_RS2(insn));
1571                     access_rs1 = 2;
1572                     access_imm = GET_C_SWSP_IMM(insn);
1573                     access_size = 4;
1574                 } else { /* C.SDSP (RV64/RV128) */
1575                     xinsn = OPC_RISC_SD;
1576                     xinsn = SET_RS2(xinsn, GET_C_RS2(insn));
1577                     access_rs1 = 2;
1578                     access_imm = GET_C_SDSP_IMM(insn);
1579                     access_size = 8;
1580                 }
1581                 break;
1582             default:
1583                 break;
1584             }
1585             break;
1586         default:
1587             break;
1588         }
1589 
1590         /*
1591          * Clear Bit1 of transformed instruction to indicate that
1592          * original insruction was a 16bit instruction
1593          */
1594         xinsn &= ~((target_ulong)0x2);
1595     } else {
1596         /* Transform 32bit (or wider) instructions */
1597         switch (MASK_OP_MAJOR(insn)) {
1598         case OPC_RISC_ATOMIC:
1599             xinsn = insn;
1600             access_rs1 = GET_RS1(insn);
1601             access_size = 1 << GET_FUNCT3(insn);
1602             break;
1603         case OPC_RISC_LOAD:
1604         case OPC_RISC_FP_LOAD:
1605             xinsn = SET_I_IMM(insn, 0);
1606             access_rs1 = GET_RS1(insn);
1607             access_imm = GET_IMM(insn);
1608             access_size = 1 << GET_FUNCT3(insn);
1609             break;
1610         case OPC_RISC_STORE:
1611         case OPC_RISC_FP_STORE:
1612             xinsn = SET_S_IMM(insn, 0);
1613             access_rs1 = GET_RS1(insn);
1614             access_imm = GET_STORE_IMM(insn);
1615             access_size = 1 << GET_FUNCT3(insn);
1616             break;
1617         case OPC_RISC_SYSTEM:
1618             if (MASK_OP_SYSTEM(insn) == OPC_RISC_HLVHSV) {
1619                 xinsn = insn;
1620                 access_rs1 = GET_RS1(insn);
1621                 access_size = 1 << ((GET_FUNCT7(insn) >> 1) & 0x3);
1622                 access_size = 1 << access_size;
1623             }
1624             break;
1625         default:
1626             break;
1627         }
1628     }
1629 
1630     if (access_size) {
1631         xinsn = SET_RS1(xinsn, (taddr - (env->gpr[access_rs1] + access_imm)) &
1632                                (access_size - 1));
1633     }
1634 
1635     return xinsn;
1636 }
1637 #endif /* !CONFIG_USER_ONLY */
1638 
1639 /*
1640  * Handle Traps
1641  *
1642  * Adapted from Spike's processor_t::take_trap.
1643  *
1644  */
1645 void riscv_cpu_do_interrupt(CPUState *cs)
1646 {
1647 #if !defined(CONFIG_USER_ONLY)
1648 
1649     RISCVCPU *cpu = RISCV_CPU(cs);
1650     CPURISCVState *env = &cpu->env;
1651     bool write_gva = false;
1652     uint64_t s;
1653 
1654     /*
1655      * cs->exception is 32-bits wide unlike mcause which is XLEN-bits wide
1656      * so we mask off the MSB and separate into trap type and cause.
1657      */
1658     bool async = !!(cs->exception_index & RISCV_EXCP_INT_FLAG);
1659     target_ulong cause = cs->exception_index & RISCV_EXCP_INT_MASK;
1660     uint64_t deleg = async ? env->mideleg : env->medeleg;
1661     bool s_injected = env->mvip & (1 << cause) & env->mvien &&
1662         !(env->mip & (1 << cause));
1663     bool vs_injected = env->hvip & (1 << cause) & env->hvien &&
1664         !(env->mip & (1 << cause));
1665     target_ulong tval = 0;
1666     target_ulong tinst = 0;
1667     target_ulong htval = 0;
1668     target_ulong mtval2 = 0;
1669 
1670     if (!async) {
1671         /* set tval to badaddr for traps with address information */
1672         switch (cause) {
1673         case RISCV_EXCP_SEMIHOST:
1674             do_common_semihosting(cs);
1675             env->pc += 4;
1676             return;
1677         case RISCV_EXCP_LOAD_GUEST_ACCESS_FAULT:
1678         case RISCV_EXCP_STORE_GUEST_AMO_ACCESS_FAULT:
1679         case RISCV_EXCP_LOAD_ADDR_MIS:
1680         case RISCV_EXCP_STORE_AMO_ADDR_MIS:
1681         case RISCV_EXCP_LOAD_ACCESS_FAULT:
1682         case RISCV_EXCP_STORE_AMO_ACCESS_FAULT:
1683         case RISCV_EXCP_LOAD_PAGE_FAULT:
1684         case RISCV_EXCP_STORE_PAGE_FAULT:
1685             write_gva = env->two_stage_lookup;
1686             tval = env->badaddr;
1687             if (env->two_stage_indirect_lookup) {
1688                 /*
1689                  * special pseudoinstruction for G-stage fault taken while
1690                  * doing VS-stage page table walk.
1691                  */
1692                 tinst = (riscv_cpu_xlen(env) == 32) ? 0x00002000 : 0x00003000;
1693             } else {
1694                 /*
1695                  * The "Addr. Offset" field in transformed instruction is
1696                  * non-zero only for misaligned access.
1697                  */
1698                 tinst = riscv_transformed_insn(env, env->bins, tval);
1699             }
1700             break;
1701         case RISCV_EXCP_INST_GUEST_PAGE_FAULT:
1702         case RISCV_EXCP_INST_ADDR_MIS:
1703         case RISCV_EXCP_INST_ACCESS_FAULT:
1704         case RISCV_EXCP_INST_PAGE_FAULT:
1705             write_gva = env->two_stage_lookup;
1706             tval = env->badaddr;
1707             if (env->two_stage_indirect_lookup) {
1708                 /*
1709                  * special pseudoinstruction for G-stage fault taken while
1710                  * doing VS-stage page table walk.
1711                  */
1712                 tinst = (riscv_cpu_xlen(env) == 32) ? 0x00002000 : 0x00003000;
1713             }
1714             break;
1715         case RISCV_EXCP_ILLEGAL_INST:
1716         case RISCV_EXCP_VIRT_INSTRUCTION_FAULT:
1717             tval = env->bins;
1718             break;
1719         case RISCV_EXCP_BREAKPOINT:
1720             if (cs->watchpoint_hit) {
1721                 tval = cs->watchpoint_hit->hitaddr;
1722                 cs->watchpoint_hit = NULL;
1723             }
1724             break;
1725         default:
1726             break;
1727         }
1728         /* ecall is dispatched as one cause so translate based on mode */
1729         if (cause == RISCV_EXCP_U_ECALL) {
1730             assert(env->priv <= 3);
1731 
1732             if (env->priv == PRV_M) {
1733                 cause = RISCV_EXCP_M_ECALL;
1734             } else if (env->priv == PRV_S && env->virt_enabled) {
1735                 cause = RISCV_EXCP_VS_ECALL;
1736             } else if (env->priv == PRV_S && !env->virt_enabled) {
1737                 cause = RISCV_EXCP_S_ECALL;
1738             } else if (env->priv == PRV_U) {
1739                 cause = RISCV_EXCP_U_ECALL;
1740             }
1741         }
1742     }
1743 
1744     trace_riscv_trap(env->mhartid, async, cause, env->pc, tval,
1745                      riscv_cpu_get_trap_name(cause, async));
1746 
1747     qemu_log_mask(CPU_LOG_INT,
1748                   "%s: hart:"TARGET_FMT_ld", async:%d, cause:"TARGET_FMT_lx", "
1749                   "epc:0x"TARGET_FMT_lx", tval:0x"TARGET_FMT_lx", desc=%s\n",
1750                   __func__, env->mhartid, async, cause, env->pc, tval,
1751                   riscv_cpu_get_trap_name(cause, async));
1752 
1753     if (env->priv <= PRV_S && cause < 64 &&
1754         (((deleg >> cause) & 1) || s_injected || vs_injected)) {
1755         /* handle the trap in S-mode */
1756         if (riscv_has_ext(env, RVH)) {
1757             uint64_t hdeleg = async ? env->hideleg : env->hedeleg;
1758 
1759             if (env->virt_enabled &&
1760                 (((hdeleg >> cause) & 1) || vs_injected)) {
1761                 /* Trap to VS mode */
1762                 /*
1763                  * See if we need to adjust cause. Yes if its VS mode interrupt
1764                  * no if hypervisor has delegated one of hs mode's interrupt
1765                  */
1766                 if (async && (cause == IRQ_VS_TIMER || cause == IRQ_VS_SOFT ||
1767                               cause == IRQ_VS_EXT)) {
1768                     cause = cause - 1;
1769                 }
1770                 write_gva = false;
1771             } else if (env->virt_enabled) {
1772                 /* Trap into HS mode, from virt */
1773                 riscv_cpu_swap_hypervisor_regs(env);
1774                 env->hstatus = set_field(env->hstatus, HSTATUS_SPVP,
1775                                          env->priv);
1776                 env->hstatus = set_field(env->hstatus, HSTATUS_SPV, true);
1777 
1778                 htval = env->guest_phys_fault_addr;
1779 
1780                 riscv_cpu_set_virt_enabled(env, 0);
1781             } else {
1782                 /* Trap into HS mode */
1783                 env->hstatus = set_field(env->hstatus, HSTATUS_SPV, false);
1784                 htval = env->guest_phys_fault_addr;
1785             }
1786             env->hstatus = set_field(env->hstatus, HSTATUS_GVA, write_gva);
1787         }
1788 
1789         s = env->mstatus;
1790         s = set_field(s, MSTATUS_SPIE, get_field(s, MSTATUS_SIE));
1791         s = set_field(s, MSTATUS_SPP, env->priv);
1792         s = set_field(s, MSTATUS_SIE, 0);
1793         env->mstatus = s;
1794         env->scause = cause | ((target_ulong)async << (TARGET_LONG_BITS - 1));
1795         env->sepc = env->pc;
1796         env->stval = tval;
1797         env->htval = htval;
1798         env->htinst = tinst;
1799         env->pc = (env->stvec >> 2 << 2) +
1800                   ((async && (env->stvec & 3) == 1) ? cause * 4 : 0);
1801         riscv_cpu_set_mode(env, PRV_S);
1802     } else {
1803         /* handle the trap in M-mode */
1804         if (riscv_has_ext(env, RVH)) {
1805             if (env->virt_enabled) {
1806                 riscv_cpu_swap_hypervisor_regs(env);
1807             }
1808             env->mstatus = set_field(env->mstatus, MSTATUS_MPV,
1809                                      env->virt_enabled);
1810             if (env->virt_enabled && tval) {
1811                 env->mstatus = set_field(env->mstatus, MSTATUS_GVA, 1);
1812             }
1813 
1814             mtval2 = env->guest_phys_fault_addr;
1815 
1816             /* Trapping to M mode, virt is disabled */
1817             riscv_cpu_set_virt_enabled(env, 0);
1818         }
1819 
1820         s = env->mstatus;
1821         s = set_field(s, MSTATUS_MPIE, get_field(s, MSTATUS_MIE));
1822         s = set_field(s, MSTATUS_MPP, env->priv);
1823         s = set_field(s, MSTATUS_MIE, 0);
1824         env->mstatus = s;
1825         env->mcause = cause | ~(((target_ulong)-1) >> async);
1826         env->mepc = env->pc;
1827         env->mtval = tval;
1828         env->mtval2 = mtval2;
1829         env->mtinst = tinst;
1830         env->pc = (env->mtvec >> 2 << 2) +
1831                   ((async && (env->mtvec & 3) == 1) ? cause * 4 : 0);
1832         riscv_cpu_set_mode(env, PRV_M);
1833     }
1834 
1835     /*
1836      * NOTE: it is not necessary to yield load reservations here. It is only
1837      * necessary for an SC from "another hart" to cause a load reservation
1838      * to be yielded. Refer to the memory consistency model section of the
1839      * RISC-V ISA Specification.
1840      */
1841 
1842     env->two_stage_lookup = false;
1843     env->two_stage_indirect_lookup = false;
1844 #endif
1845     cs->exception_index = RISCV_EXCP_NONE; /* mark handled to qemu */
1846 }
1847