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