xref: /openbmc/qemu/target/riscv/cpu_helper.c (revision 41fc1f02947dd7a33b2c1d0e8474744b12f2514e)
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_zve32x) {
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 int riscv_cpu_claim_interrupts(RISCVCPU *cpu, uint64_t interrupts)
623 {
624     CPURISCVState *env = &cpu->env;
625     if (env->miclaim & interrupts) {
626         return -1;
627     } else {
628         env->miclaim |= interrupts;
629         return 0;
630     }
631 }
632 
633 void riscv_cpu_interrupt(CPURISCVState *env)
634 {
635     uint64_t gein, vsgein = 0, vstip = 0, irqf = 0;
636     CPUState *cs = env_cpu(env);
637 
638     BQL_LOCK_GUARD();
639 
640     if (env->virt_enabled) {
641         gein = get_field(env->hstatus, HSTATUS_VGEIN);
642         vsgein = (env->hgeip & (1ULL << gein)) ? MIP_VSEIP : 0;
643         irqf = env->hvien & env->hvip & env->vsie;
644     } else {
645         irqf = env->mvien & env->mvip & env->sie;
646     }
647 
648     vstip = env->vstime_irq ? MIP_VSTIP : 0;
649 
650     if (env->mip | vsgein | vstip | irqf) {
651         cpu_interrupt(cs, CPU_INTERRUPT_HARD);
652     } else {
653         cpu_reset_interrupt(cs, CPU_INTERRUPT_HARD);
654     }
655 }
656 
657 uint64_t riscv_cpu_update_mip(CPURISCVState *env, uint64_t mask, uint64_t value)
658 {
659     uint64_t old = env->mip;
660 
661     /* No need to update mip for VSTIP */
662     mask = ((mask == MIP_VSTIP) && env->vstime_irq) ? 0 : mask;
663 
664     BQL_LOCK_GUARD();
665 
666     env->mip = (env->mip & ~mask) | (value & mask);
667 
668     riscv_cpu_interrupt(env);
669 
670     return old;
671 }
672 
673 void riscv_cpu_set_rdtime_fn(CPURISCVState *env, uint64_t (*fn)(void *),
674                              void *arg)
675 {
676     env->rdtime_fn = fn;
677     env->rdtime_fn_arg = arg;
678 }
679 
680 void riscv_cpu_set_aia_ireg_rmw_fn(CPURISCVState *env, uint32_t priv,
681                                    int (*rmw_fn)(void *arg,
682                                                  target_ulong reg,
683                                                  target_ulong *val,
684                                                  target_ulong new_val,
685                                                  target_ulong write_mask),
686                                    void *rmw_fn_arg)
687 {
688     if (priv <= PRV_M) {
689         env->aia_ireg_rmw_fn[priv] = rmw_fn;
690         env->aia_ireg_rmw_fn_arg[priv] = rmw_fn_arg;
691     }
692 }
693 
694 void riscv_cpu_set_mode(CPURISCVState *env, target_ulong newpriv, bool virt_en)
695 {
696     g_assert(newpriv <= PRV_M && newpriv != PRV_RESERVED);
697 
698     if (newpriv != env->priv || env->virt_enabled != virt_en) {
699         if (icount_enabled()) {
700             riscv_itrigger_update_priv(env);
701         }
702 
703         riscv_pmu_update_fixed_ctrs(env, newpriv, virt_en);
704     }
705 
706     /* tlb_flush is unnecessary as mode is contained in mmu_idx */
707     env->priv = newpriv;
708     env->xl = cpu_recompute_xl(env);
709     riscv_cpu_update_mask(env);
710 
711     /*
712      * Clear the load reservation - otherwise a reservation placed in one
713      * context/process can be used by another, resulting in an SC succeeding
714      * incorrectly. Version 2.2 of the ISA specification explicitly requires
715      * this behaviour, while later revisions say that the kernel "should" use
716      * an SC instruction to force the yielding of a load reservation on a
717      * preemptive context switch. As a result, do both.
718      */
719     env->load_res = -1;
720 
721     if (riscv_has_ext(env, RVH)) {
722         /* Flush the TLB on all virt mode changes. */
723         if (env->virt_enabled != virt_en) {
724             tlb_flush(env_cpu(env));
725         }
726 
727         env->virt_enabled = virt_en;
728         if (virt_en) {
729             /*
730              * The guest external interrupts from an interrupt controller are
731              * delivered only when the Guest/VM is running (i.e. V=1). This
732              * means any guest external interrupt which is triggered while the
733              * Guest/VM is not running (i.e. V=0) will be missed on QEMU
734              * resulting in guest with sluggish response to serial console
735              * input and other I/O events.
736              *
737              * To solve this, we check and inject interrupt after setting V=1.
738              */
739             riscv_cpu_update_mip(env, 0, 0);
740         }
741     }
742 }
743 
744 /*
745  * get_physical_address_pmp - check PMP permission for this physical address
746  *
747  * Match the PMP region and check permission for this physical address and it's
748  * TLB page. Returns 0 if the permission checking was successful
749  *
750  * @env: CPURISCVState
751  * @prot: The returned protection attributes
752  * @addr: The physical address to be checked permission
753  * @access_type: The type of MMU access
754  * @mode: Indicates current privilege level.
755  */
756 static int get_physical_address_pmp(CPURISCVState *env, int *prot, hwaddr addr,
757                                     int size, MMUAccessType access_type,
758                                     int mode)
759 {
760     pmp_priv_t pmp_priv;
761     bool pmp_has_privs;
762 
763     if (!riscv_cpu_cfg(env)->pmp) {
764         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
765         return TRANSLATE_SUCCESS;
766     }
767 
768     pmp_has_privs = pmp_hart_has_privs(env, addr, size, 1 << access_type,
769                                        &pmp_priv, mode);
770     if (!pmp_has_privs) {
771         *prot = 0;
772         return TRANSLATE_PMP_FAIL;
773     }
774 
775     *prot = pmp_priv_to_page_prot(pmp_priv);
776 
777     return TRANSLATE_SUCCESS;
778 }
779 
780 /*
781  * get_physical_address - get the physical address for this virtual address
782  *
783  * Do a page table walk to obtain the physical address corresponding to a
784  * virtual address. Returns 0 if the translation was successful
785  *
786  * Adapted from Spike's mmu_t::translate and mmu_t::walk
787  *
788  * @env: CPURISCVState
789  * @physical: This will be set to the calculated physical address
790  * @prot: The returned protection attributes
791  * @addr: The virtual address or guest physical address to be translated
792  * @fault_pte_addr: If not NULL, this will be set to fault pte address
793  *                  when a error occurs on pte address translation.
794  *                  This will already be shifted to match htval.
795  * @access_type: The type of MMU access
796  * @mmu_idx: Indicates current privilege level
797  * @first_stage: Are we in first stage translation?
798  *               Second stage is used for hypervisor guest translation
799  * @two_stage: Are we going to perform two stage translation
800  * @is_debug: Is this access from a debugger or the monitor?
801  */
802 static int get_physical_address(CPURISCVState *env, hwaddr *physical,
803                                 int *ret_prot, vaddr addr,
804                                 target_ulong *fault_pte_addr,
805                                 int access_type, int mmu_idx,
806                                 bool first_stage, bool two_stage,
807                                 bool is_debug)
808 {
809     /*
810      * NOTE: the env->pc value visible here will not be
811      * correct, but the value visible to the exception handler
812      * (riscv_cpu_do_interrupt) is correct
813      */
814     MemTxResult res;
815     MemTxAttrs attrs = MEMTXATTRS_UNSPECIFIED;
816     int mode = mmuidx_priv(mmu_idx);
817     bool use_background = false;
818     hwaddr ppn;
819     int napot_bits = 0;
820     target_ulong napot_mask;
821 
822     /*
823      * Check if we should use the background registers for the two
824      * stage translation. We don't need to check if we actually need
825      * two stage translation as that happened before this function
826      * was called. Background registers will be used if the guest has
827      * forced a two stage translation to be on (in HS or M mode).
828      */
829     if (!env->virt_enabled && two_stage) {
830         use_background = true;
831     }
832 
833     if (mode == PRV_M || !riscv_cpu_cfg(env)->mmu) {
834         *physical = addr;
835         *ret_prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
836         return TRANSLATE_SUCCESS;
837     }
838 
839     *ret_prot = 0;
840 
841     hwaddr base;
842     int levels, ptidxbits, ptesize, vm, widened;
843 
844     if (first_stage == true) {
845         if (use_background) {
846             if (riscv_cpu_mxl(env) == MXL_RV32) {
847                 base = (hwaddr)get_field(env->vsatp, SATP32_PPN) << PGSHIFT;
848                 vm = get_field(env->vsatp, SATP32_MODE);
849             } else {
850                 base = (hwaddr)get_field(env->vsatp, SATP64_PPN) << PGSHIFT;
851                 vm = get_field(env->vsatp, SATP64_MODE);
852             }
853         } else {
854             if (riscv_cpu_mxl(env) == MXL_RV32) {
855                 base = (hwaddr)get_field(env->satp, SATP32_PPN) << PGSHIFT;
856                 vm = get_field(env->satp, SATP32_MODE);
857             } else {
858                 base = (hwaddr)get_field(env->satp, SATP64_PPN) << PGSHIFT;
859                 vm = get_field(env->satp, SATP64_MODE);
860             }
861         }
862         widened = 0;
863     } else {
864         if (riscv_cpu_mxl(env) == MXL_RV32) {
865             base = (hwaddr)get_field(env->hgatp, SATP32_PPN) << PGSHIFT;
866             vm = get_field(env->hgatp, SATP32_MODE);
867         } else {
868             base = (hwaddr)get_field(env->hgatp, SATP64_PPN) << PGSHIFT;
869             vm = get_field(env->hgatp, SATP64_MODE);
870         }
871         widened = 2;
872     }
873 
874     switch (vm) {
875     case VM_1_10_SV32:
876       levels = 2; ptidxbits = 10; ptesize = 4; break;
877     case VM_1_10_SV39:
878       levels = 3; ptidxbits = 9; ptesize = 8; break;
879     case VM_1_10_SV48:
880       levels = 4; ptidxbits = 9; ptesize = 8; break;
881     case VM_1_10_SV57:
882       levels = 5; ptidxbits = 9; ptesize = 8; break;
883     case VM_1_10_MBARE:
884         *physical = addr;
885         *ret_prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
886         return TRANSLATE_SUCCESS;
887     default:
888       g_assert_not_reached();
889     }
890 
891     CPUState *cs = env_cpu(env);
892     int va_bits = PGSHIFT + levels * ptidxbits + widened;
893     int sxlen = 16 << riscv_cpu_sxl(env);
894     int sxlen_bytes = sxlen / 8;
895 
896     if (first_stage == true) {
897         target_ulong mask, masked_msbs;
898 
899         if (sxlen > (va_bits - 1)) {
900             mask = (1L << (sxlen - (va_bits - 1))) - 1;
901         } else {
902             mask = 0;
903         }
904         masked_msbs = (addr >> (va_bits - 1)) & mask;
905 
906         if (masked_msbs != 0 && masked_msbs != mask) {
907             return TRANSLATE_FAIL;
908         }
909     } else {
910         if (vm != VM_1_10_SV32 && addr >> va_bits != 0) {
911             return TRANSLATE_FAIL;
912         }
913     }
914 
915     bool pbmte = env->menvcfg & MENVCFG_PBMTE;
916     bool svade = riscv_cpu_cfg(env)->ext_svade;
917     bool svadu = riscv_cpu_cfg(env)->ext_svadu;
918     bool adue = svadu ? env->menvcfg & MENVCFG_ADUE : !svade;
919 
920     if (first_stage && two_stage && env->virt_enabled) {
921         pbmte = pbmte && (env->henvcfg & HENVCFG_PBMTE);
922         adue = adue && (env->henvcfg & HENVCFG_ADUE);
923     }
924 
925     int ptshift = (levels - 1) * ptidxbits;
926     target_ulong pte;
927     hwaddr pte_addr;
928     int i;
929 
930 #if !TCG_OVERSIZED_GUEST
931 restart:
932 #endif
933     for (i = 0; i < levels; i++, ptshift -= ptidxbits) {
934         target_ulong idx;
935         if (i == 0) {
936             idx = (addr >> (PGSHIFT + ptshift)) &
937                            ((1 << (ptidxbits + widened)) - 1);
938         } else {
939             idx = (addr >> (PGSHIFT + ptshift)) &
940                            ((1 << ptidxbits) - 1);
941         }
942 
943         /* check that physical address of PTE is legal */
944 
945         if (two_stage && first_stage) {
946             int vbase_prot;
947             hwaddr vbase;
948 
949             /* Do the second stage translation on the base PTE address. */
950             int vbase_ret = get_physical_address(env, &vbase, &vbase_prot,
951                                                  base, NULL, MMU_DATA_LOAD,
952                                                  MMUIdx_U, false, true,
953                                                  is_debug);
954 
955             if (vbase_ret != TRANSLATE_SUCCESS) {
956                 if (fault_pte_addr) {
957                     *fault_pte_addr = (base + idx * ptesize) >> 2;
958                 }
959                 return TRANSLATE_G_STAGE_FAIL;
960             }
961 
962             pte_addr = vbase + idx * ptesize;
963         } else {
964             pte_addr = base + idx * ptesize;
965         }
966 
967         int pmp_prot;
968         int pmp_ret = get_physical_address_pmp(env, &pmp_prot, pte_addr,
969                                                sxlen_bytes,
970                                                MMU_DATA_LOAD, PRV_S);
971         if (pmp_ret != TRANSLATE_SUCCESS) {
972             return TRANSLATE_PMP_FAIL;
973         }
974 
975         if (riscv_cpu_mxl(env) == MXL_RV32) {
976             pte = address_space_ldl(cs->as, pte_addr, attrs, &res);
977         } else {
978             pte = address_space_ldq(cs->as, pte_addr, attrs, &res);
979         }
980 
981         if (res != MEMTX_OK) {
982             return TRANSLATE_FAIL;
983         }
984 
985         if (riscv_cpu_sxl(env) == MXL_RV32) {
986             ppn = pte >> PTE_PPN_SHIFT;
987         } else {
988             if (pte & PTE_RESERVED) {
989                 return TRANSLATE_FAIL;
990             }
991 
992             if (!pbmte && (pte & PTE_PBMT)) {
993                 return TRANSLATE_FAIL;
994             }
995 
996             if (!riscv_cpu_cfg(env)->ext_svnapot && (pte & PTE_N)) {
997                 return TRANSLATE_FAIL;
998             }
999 
1000             ppn = (pte & (target_ulong)PTE_PPN_MASK) >> PTE_PPN_SHIFT;
1001         }
1002 
1003         if (!(pte & PTE_V)) {
1004             /* Invalid PTE */
1005             return TRANSLATE_FAIL;
1006         }
1007         if (pte & (PTE_R | PTE_W | PTE_X)) {
1008             goto leaf;
1009         }
1010 
1011         /* Inner PTE, continue walking */
1012         if (pte & (PTE_D | PTE_A | PTE_U | PTE_ATTR)) {
1013             return TRANSLATE_FAIL;
1014         }
1015         base = ppn << PGSHIFT;
1016     }
1017 
1018     /* No leaf pte at any translation level. */
1019     return TRANSLATE_FAIL;
1020 
1021  leaf:
1022     if (ppn & ((1ULL << ptshift) - 1)) {
1023         /* Misaligned PPN */
1024         return TRANSLATE_FAIL;
1025     }
1026     if (!pbmte && (pte & PTE_PBMT)) {
1027         /* Reserved without Svpbmt. */
1028         return TRANSLATE_FAIL;
1029     }
1030 
1031     /* Check for reserved combinations of RWX flags. */
1032     switch (pte & (PTE_R | PTE_W | PTE_X)) {
1033     case PTE_W:
1034     case PTE_W | PTE_X:
1035         return TRANSLATE_FAIL;
1036     }
1037 
1038     int prot = 0;
1039     if (pte & PTE_R) {
1040         prot |= PAGE_READ;
1041     }
1042     if (pte & PTE_W) {
1043         prot |= PAGE_WRITE;
1044     }
1045     if (pte & PTE_X) {
1046         bool mxr = false;
1047 
1048         /*
1049          * Use mstatus for first stage or for the second stage without
1050          * virt_enabled (MPRV+MPV)
1051          */
1052         if (first_stage || !env->virt_enabled) {
1053             mxr = get_field(env->mstatus, MSTATUS_MXR);
1054         }
1055 
1056         /* MPRV+MPV case, check VSSTATUS */
1057         if (first_stage && two_stage && !env->virt_enabled) {
1058             mxr |= get_field(env->vsstatus, MSTATUS_MXR);
1059         }
1060 
1061         /*
1062          * Setting MXR at HS-level overrides both VS-stage and G-stage
1063          * execute-only permissions
1064          */
1065         if (env->virt_enabled) {
1066             mxr |= get_field(env->mstatus_hs, MSTATUS_MXR);
1067         }
1068 
1069         if (mxr) {
1070             prot |= PAGE_READ;
1071         }
1072         prot |= PAGE_EXEC;
1073     }
1074 
1075     if (pte & PTE_U) {
1076         if (mode != PRV_U) {
1077             if (!mmuidx_sum(mmu_idx)) {
1078                 return TRANSLATE_FAIL;
1079             }
1080             /* SUM allows only read+write, not execute. */
1081             prot &= PAGE_READ | PAGE_WRITE;
1082         }
1083     } else if (mode != PRV_S) {
1084         /* Supervisor PTE flags when not S mode */
1085         return TRANSLATE_FAIL;
1086     }
1087 
1088     if (!((prot >> access_type) & 1)) {
1089         /* Access check failed */
1090         return TRANSLATE_FAIL;
1091     }
1092 
1093     target_ulong updated_pte = pte;
1094 
1095     /*
1096      * If ADUE is enabled, set accessed and dirty bits.
1097      * Otherwise raise an exception if necessary.
1098      */
1099     if (adue) {
1100         updated_pte |= PTE_A | (access_type == MMU_DATA_STORE ? PTE_D : 0);
1101     } else if (!(pte & PTE_A) ||
1102                (access_type == MMU_DATA_STORE && !(pte & PTE_D))) {
1103         return TRANSLATE_FAIL;
1104     }
1105 
1106     /* Page table updates need to be atomic with MTTCG enabled */
1107     if (updated_pte != pte && !is_debug) {
1108         if (!adue) {
1109             return TRANSLATE_FAIL;
1110         }
1111 
1112         /*
1113          * - if accessed or dirty bits need updating, and the PTE is
1114          *   in RAM, then we do so atomically with a compare and swap.
1115          * - if the PTE is in IO space or ROM, then it can't be updated
1116          *   and we return TRANSLATE_FAIL.
1117          * - if the PTE changed by the time we went to update it, then
1118          *   it is no longer valid and we must re-walk the page table.
1119          */
1120         MemoryRegion *mr;
1121         hwaddr l = sxlen_bytes, addr1;
1122         mr = address_space_translate(cs->as, pte_addr, &addr1, &l,
1123                                      false, MEMTXATTRS_UNSPECIFIED);
1124         if (memory_region_is_ram(mr)) {
1125             target_ulong *pte_pa = qemu_map_ram_ptr(mr->ram_block, addr1);
1126 #if TCG_OVERSIZED_GUEST
1127             /*
1128              * MTTCG is not enabled on oversized TCG guests so
1129              * page table updates do not need to be atomic
1130              */
1131             *pte_pa = pte = updated_pte;
1132 #else
1133             target_ulong old_pte;
1134             if (riscv_cpu_sxl(env) == MXL_RV32) {
1135                 old_pte = qatomic_cmpxchg((uint32_t *)pte_pa, pte, updated_pte);
1136             } else {
1137                 old_pte = qatomic_cmpxchg(pte_pa, pte, updated_pte);
1138             }
1139             if (old_pte != pte) {
1140                 goto restart;
1141             }
1142             pte = updated_pte;
1143 #endif
1144         } else {
1145             /*
1146              * Misconfigured PTE in ROM (AD bits are not preset) or
1147              * PTE is in IO space and can't be updated atomically.
1148              */
1149             return TRANSLATE_FAIL;
1150         }
1151     }
1152 
1153     /* For superpage mappings, make a fake leaf PTE for the TLB's benefit. */
1154     target_ulong vpn = addr >> PGSHIFT;
1155 
1156     if (riscv_cpu_cfg(env)->ext_svnapot && (pte & PTE_N)) {
1157         napot_bits = ctzl(ppn) + 1;
1158         if ((i != (levels - 1)) || (napot_bits != 4)) {
1159             return TRANSLATE_FAIL;
1160         }
1161     }
1162 
1163     napot_mask = (1 << napot_bits) - 1;
1164     *physical = (((ppn & ~napot_mask) | (vpn & napot_mask) |
1165                   (vpn & (((target_ulong)1 << ptshift) - 1))
1166                  ) << PGSHIFT) | (addr & ~TARGET_PAGE_MASK);
1167 
1168     /*
1169      * Remove write permission unless this is a store, or the page is
1170      * already dirty, so that we TLB miss on later writes to update
1171      * the dirty bit.
1172      */
1173     if (access_type != MMU_DATA_STORE && !(pte & PTE_D)) {
1174         prot &= ~PAGE_WRITE;
1175     }
1176     *ret_prot = prot;
1177 
1178     return TRANSLATE_SUCCESS;
1179 }
1180 
1181 static void raise_mmu_exception(CPURISCVState *env, target_ulong address,
1182                                 MMUAccessType access_type, bool pmp_violation,
1183                                 bool first_stage, bool two_stage,
1184                                 bool two_stage_indirect)
1185 {
1186     CPUState *cs = env_cpu(env);
1187 
1188     switch (access_type) {
1189     case MMU_INST_FETCH:
1190         if (pmp_violation) {
1191             cs->exception_index = RISCV_EXCP_INST_ACCESS_FAULT;
1192         } else if (env->virt_enabled && !first_stage) {
1193             cs->exception_index = RISCV_EXCP_INST_GUEST_PAGE_FAULT;
1194         } else {
1195             cs->exception_index = RISCV_EXCP_INST_PAGE_FAULT;
1196         }
1197         break;
1198     case MMU_DATA_LOAD:
1199         if (pmp_violation) {
1200             cs->exception_index = RISCV_EXCP_LOAD_ACCESS_FAULT;
1201         } else if (two_stage && !first_stage) {
1202             cs->exception_index = RISCV_EXCP_LOAD_GUEST_ACCESS_FAULT;
1203         } else {
1204             cs->exception_index = RISCV_EXCP_LOAD_PAGE_FAULT;
1205         }
1206         break;
1207     case MMU_DATA_STORE:
1208         if (pmp_violation) {
1209             cs->exception_index = RISCV_EXCP_STORE_AMO_ACCESS_FAULT;
1210         } else if (two_stage && !first_stage) {
1211             cs->exception_index = RISCV_EXCP_STORE_GUEST_AMO_ACCESS_FAULT;
1212         } else {
1213             cs->exception_index = RISCV_EXCP_STORE_PAGE_FAULT;
1214         }
1215         break;
1216     default:
1217         g_assert_not_reached();
1218     }
1219     env->badaddr = address;
1220     env->two_stage_lookup = two_stage;
1221     env->two_stage_indirect_lookup = two_stage_indirect;
1222 }
1223 
1224 hwaddr riscv_cpu_get_phys_page_debug(CPUState *cs, vaddr addr)
1225 {
1226     RISCVCPU *cpu = RISCV_CPU(cs);
1227     CPURISCVState *env = &cpu->env;
1228     hwaddr phys_addr;
1229     int prot;
1230     int mmu_idx = riscv_env_mmu_index(&cpu->env, false);
1231 
1232     if (get_physical_address(env, &phys_addr, &prot, addr, NULL, 0, mmu_idx,
1233                              true, env->virt_enabled, true)) {
1234         return -1;
1235     }
1236 
1237     if (env->virt_enabled) {
1238         if (get_physical_address(env, &phys_addr, &prot, phys_addr, NULL,
1239                                  0, MMUIdx_U, false, true, true)) {
1240             return -1;
1241         }
1242     }
1243 
1244     return phys_addr & TARGET_PAGE_MASK;
1245 }
1246 
1247 void riscv_cpu_do_transaction_failed(CPUState *cs, hwaddr physaddr,
1248                                      vaddr addr, unsigned size,
1249                                      MMUAccessType access_type,
1250                                      int mmu_idx, MemTxAttrs attrs,
1251                                      MemTxResult response, uintptr_t retaddr)
1252 {
1253     RISCVCPU *cpu = RISCV_CPU(cs);
1254     CPURISCVState *env = &cpu->env;
1255 
1256     if (access_type == MMU_DATA_STORE) {
1257         cs->exception_index = RISCV_EXCP_STORE_AMO_ACCESS_FAULT;
1258     } else if (access_type == MMU_DATA_LOAD) {
1259         cs->exception_index = RISCV_EXCP_LOAD_ACCESS_FAULT;
1260     } else {
1261         cs->exception_index = RISCV_EXCP_INST_ACCESS_FAULT;
1262     }
1263 
1264     env->badaddr = addr;
1265     env->two_stage_lookup = mmuidx_2stage(mmu_idx);
1266     env->two_stage_indirect_lookup = false;
1267     cpu_loop_exit_restore(cs, retaddr);
1268 }
1269 
1270 void riscv_cpu_do_unaligned_access(CPUState *cs, vaddr addr,
1271                                    MMUAccessType access_type, int mmu_idx,
1272                                    uintptr_t retaddr)
1273 {
1274     RISCVCPU *cpu = RISCV_CPU(cs);
1275     CPURISCVState *env = &cpu->env;
1276     switch (access_type) {
1277     case MMU_INST_FETCH:
1278         cs->exception_index = RISCV_EXCP_INST_ADDR_MIS;
1279         break;
1280     case MMU_DATA_LOAD:
1281         cs->exception_index = RISCV_EXCP_LOAD_ADDR_MIS;
1282         break;
1283     case MMU_DATA_STORE:
1284         cs->exception_index = RISCV_EXCP_STORE_AMO_ADDR_MIS;
1285         break;
1286     default:
1287         g_assert_not_reached();
1288     }
1289     env->badaddr = addr;
1290     env->two_stage_lookup = mmuidx_2stage(mmu_idx);
1291     env->two_stage_indirect_lookup = false;
1292     cpu_loop_exit_restore(cs, retaddr);
1293 }
1294 
1295 
1296 static void pmu_tlb_fill_incr_ctr(RISCVCPU *cpu, MMUAccessType access_type)
1297 {
1298     enum riscv_pmu_event_idx pmu_event_type;
1299 
1300     switch (access_type) {
1301     case MMU_INST_FETCH:
1302         pmu_event_type = RISCV_PMU_EVENT_CACHE_ITLB_PREFETCH_MISS;
1303         break;
1304     case MMU_DATA_LOAD:
1305         pmu_event_type = RISCV_PMU_EVENT_CACHE_DTLB_READ_MISS;
1306         break;
1307     case MMU_DATA_STORE:
1308         pmu_event_type = RISCV_PMU_EVENT_CACHE_DTLB_WRITE_MISS;
1309         break;
1310     default:
1311         return;
1312     }
1313 
1314     riscv_pmu_incr_ctr(cpu, pmu_event_type);
1315 }
1316 
1317 bool riscv_cpu_tlb_fill(CPUState *cs, vaddr address, int size,
1318                         MMUAccessType access_type, int mmu_idx,
1319                         bool probe, uintptr_t retaddr)
1320 {
1321     RISCVCPU *cpu = RISCV_CPU(cs);
1322     CPURISCVState *env = &cpu->env;
1323     vaddr im_address;
1324     hwaddr pa = 0;
1325     int prot, prot2, prot_pmp;
1326     bool pmp_violation = false;
1327     bool first_stage_error = true;
1328     bool two_stage_lookup = mmuidx_2stage(mmu_idx);
1329     bool two_stage_indirect_error = false;
1330     int ret = TRANSLATE_FAIL;
1331     int mode = mmuidx_priv(mmu_idx);
1332     /* default TLB page size */
1333     hwaddr tlb_size = TARGET_PAGE_SIZE;
1334 
1335     env->guest_phys_fault_addr = 0;
1336 
1337     qemu_log_mask(CPU_LOG_MMU, "%s ad %" VADDR_PRIx " rw %d mmu_idx %d\n",
1338                   __func__, address, access_type, mmu_idx);
1339 
1340     pmu_tlb_fill_incr_ctr(cpu, access_type);
1341     if (two_stage_lookup) {
1342         /* Two stage lookup */
1343         ret = get_physical_address(env, &pa, &prot, address,
1344                                    &env->guest_phys_fault_addr, access_type,
1345                                    mmu_idx, true, true, false);
1346 
1347         /*
1348          * A G-stage exception may be triggered during two state lookup.
1349          * And the env->guest_phys_fault_addr has already been set in
1350          * get_physical_address().
1351          */
1352         if (ret == TRANSLATE_G_STAGE_FAIL) {
1353             first_stage_error = false;
1354             two_stage_indirect_error = true;
1355         }
1356 
1357         qemu_log_mask(CPU_LOG_MMU,
1358                       "%s 1st-stage address=%" VADDR_PRIx " ret %d physical "
1359                       HWADDR_FMT_plx " prot %d\n",
1360                       __func__, address, ret, pa, prot);
1361 
1362         if (ret == TRANSLATE_SUCCESS) {
1363             /* Second stage lookup */
1364             im_address = pa;
1365 
1366             ret = get_physical_address(env, &pa, &prot2, im_address, NULL,
1367                                        access_type, MMUIdx_U, false, true,
1368                                        false);
1369 
1370             qemu_log_mask(CPU_LOG_MMU,
1371                           "%s 2nd-stage address=%" VADDR_PRIx
1372                           " ret %d physical "
1373                           HWADDR_FMT_plx " prot %d\n",
1374                           __func__, im_address, ret, pa, prot2);
1375 
1376             prot &= prot2;
1377 
1378             if (ret == TRANSLATE_SUCCESS) {
1379                 ret = get_physical_address_pmp(env, &prot_pmp, pa,
1380                                                size, access_type, mode);
1381                 tlb_size = pmp_get_tlb_size(env, pa);
1382 
1383                 qemu_log_mask(CPU_LOG_MMU,
1384                               "%s PMP address=" HWADDR_FMT_plx " ret %d prot"
1385                               " %d tlb_size %" HWADDR_PRIu "\n",
1386                               __func__, pa, ret, prot_pmp, tlb_size);
1387 
1388                 prot &= prot_pmp;
1389             } else {
1390                 /*
1391                  * Guest physical address translation failed, this is a HS
1392                  * level exception
1393                  */
1394                 first_stage_error = false;
1395                 if (ret != TRANSLATE_PMP_FAIL) {
1396                     env->guest_phys_fault_addr = (im_address |
1397                                                   (address &
1398                                                    (TARGET_PAGE_SIZE - 1))) >> 2;
1399                 }
1400             }
1401         }
1402     } else {
1403         /* Single stage lookup */
1404         ret = get_physical_address(env, &pa, &prot, address, NULL,
1405                                    access_type, mmu_idx, true, false, false);
1406 
1407         qemu_log_mask(CPU_LOG_MMU,
1408                       "%s address=%" VADDR_PRIx " ret %d physical "
1409                       HWADDR_FMT_plx " prot %d\n",
1410                       __func__, address, ret, pa, prot);
1411 
1412         if (ret == TRANSLATE_SUCCESS) {
1413             ret = get_physical_address_pmp(env, &prot_pmp, pa,
1414                                            size, access_type, mode);
1415             tlb_size = pmp_get_tlb_size(env, pa);
1416 
1417             qemu_log_mask(CPU_LOG_MMU,
1418                           "%s PMP address=" HWADDR_FMT_plx " ret %d prot"
1419                           " %d tlb_size %" HWADDR_PRIu "\n",
1420                           __func__, pa, ret, prot_pmp, tlb_size);
1421 
1422             prot &= prot_pmp;
1423         }
1424     }
1425 
1426     if (ret == TRANSLATE_PMP_FAIL) {
1427         pmp_violation = true;
1428     }
1429 
1430     if (ret == TRANSLATE_SUCCESS) {
1431         tlb_set_page(cs, address & ~(tlb_size - 1), pa & ~(tlb_size - 1),
1432                      prot, mmu_idx, tlb_size);
1433         return true;
1434     } else if (probe) {
1435         return false;
1436     } else {
1437         raise_mmu_exception(env, address, access_type, pmp_violation,
1438                             first_stage_error, two_stage_lookup,
1439                             two_stage_indirect_error);
1440         cpu_loop_exit_restore(cs, retaddr);
1441     }
1442 
1443     return true;
1444 }
1445 
1446 static target_ulong riscv_transformed_insn(CPURISCVState *env,
1447                                            target_ulong insn,
1448                                            target_ulong taddr)
1449 {
1450     target_ulong xinsn = 0;
1451     target_ulong access_rs1 = 0, access_imm = 0, access_size = 0;
1452 
1453     /*
1454      * Only Quadrant 0 and Quadrant 2 of RVC instruction space need to
1455      * be uncompressed. The Quadrant 1 of RVC instruction space need
1456      * not be transformed because these instructions won't generate
1457      * any load/store trap.
1458      */
1459 
1460     if ((insn & 0x3) != 0x3) {
1461         /* Transform 16bit instruction into 32bit instruction */
1462         switch (GET_C_OP(insn)) {
1463         case OPC_RISC_C_OP_QUAD0: /* Quadrant 0 */
1464             switch (GET_C_FUNC(insn)) {
1465             case OPC_RISC_C_FUNC_FLD_LQ:
1466                 if (riscv_cpu_xlen(env) != 128) { /* C.FLD (RV32/64) */
1467                     xinsn = OPC_RISC_FLD;
1468                     xinsn = SET_RD(xinsn, GET_C_RS2S(insn));
1469                     access_rs1 = GET_C_RS1S(insn);
1470                     access_imm = GET_C_LD_IMM(insn);
1471                     access_size = 8;
1472                 }
1473                 break;
1474             case OPC_RISC_C_FUNC_LW: /* C.LW */
1475                 xinsn = OPC_RISC_LW;
1476                 xinsn = SET_RD(xinsn, GET_C_RS2S(insn));
1477                 access_rs1 = GET_C_RS1S(insn);
1478                 access_imm = GET_C_LW_IMM(insn);
1479                 access_size = 4;
1480                 break;
1481             case OPC_RISC_C_FUNC_FLW_LD:
1482                 if (riscv_cpu_xlen(env) == 32) { /* C.FLW (RV32) */
1483                     xinsn = OPC_RISC_FLW;
1484                     xinsn = SET_RD(xinsn, GET_C_RS2S(insn));
1485                     access_rs1 = GET_C_RS1S(insn);
1486                     access_imm = GET_C_LW_IMM(insn);
1487                     access_size = 4;
1488                 } else { /* C.LD (RV64/RV128) */
1489                     xinsn = OPC_RISC_LD;
1490                     xinsn = SET_RD(xinsn, GET_C_RS2S(insn));
1491                     access_rs1 = GET_C_RS1S(insn);
1492                     access_imm = GET_C_LD_IMM(insn);
1493                     access_size = 8;
1494                 }
1495                 break;
1496             case OPC_RISC_C_FUNC_FSD_SQ:
1497                 if (riscv_cpu_xlen(env) != 128) { /* C.FSD (RV32/64) */
1498                     xinsn = OPC_RISC_FSD;
1499                     xinsn = SET_RS2(xinsn, GET_C_RS2S(insn));
1500                     access_rs1 = GET_C_RS1S(insn);
1501                     access_imm = GET_C_SD_IMM(insn);
1502                     access_size = 8;
1503                 }
1504                 break;
1505             case OPC_RISC_C_FUNC_SW: /* C.SW */
1506                 xinsn = OPC_RISC_SW;
1507                 xinsn = SET_RS2(xinsn, GET_C_RS2S(insn));
1508                 access_rs1 = GET_C_RS1S(insn);
1509                 access_imm = GET_C_SW_IMM(insn);
1510                 access_size = 4;
1511                 break;
1512             case OPC_RISC_C_FUNC_FSW_SD:
1513                 if (riscv_cpu_xlen(env) == 32) { /* C.FSW (RV32) */
1514                     xinsn = OPC_RISC_FSW;
1515                     xinsn = SET_RS2(xinsn, GET_C_RS2S(insn));
1516                     access_rs1 = GET_C_RS1S(insn);
1517                     access_imm = GET_C_SW_IMM(insn);
1518                     access_size = 4;
1519                 } else { /* C.SD (RV64/RV128) */
1520                     xinsn = OPC_RISC_SD;
1521                     xinsn = SET_RS2(xinsn, GET_C_RS2S(insn));
1522                     access_rs1 = GET_C_RS1S(insn);
1523                     access_imm = GET_C_SD_IMM(insn);
1524                     access_size = 8;
1525                 }
1526                 break;
1527             default:
1528                 break;
1529             }
1530             break;
1531         case OPC_RISC_C_OP_QUAD2: /* Quadrant 2 */
1532             switch (GET_C_FUNC(insn)) {
1533             case OPC_RISC_C_FUNC_FLDSP_LQSP:
1534                 if (riscv_cpu_xlen(env) != 128) { /* C.FLDSP (RV32/64) */
1535                     xinsn = OPC_RISC_FLD;
1536                     xinsn = SET_RD(xinsn, GET_C_RD(insn));
1537                     access_rs1 = 2;
1538                     access_imm = GET_C_LDSP_IMM(insn);
1539                     access_size = 8;
1540                 }
1541                 break;
1542             case OPC_RISC_C_FUNC_LWSP: /* C.LWSP */
1543                 xinsn = OPC_RISC_LW;
1544                 xinsn = SET_RD(xinsn, GET_C_RD(insn));
1545                 access_rs1 = 2;
1546                 access_imm = GET_C_LWSP_IMM(insn);
1547                 access_size = 4;
1548                 break;
1549             case OPC_RISC_C_FUNC_FLWSP_LDSP:
1550                 if (riscv_cpu_xlen(env) == 32) { /* C.FLWSP (RV32) */
1551                     xinsn = OPC_RISC_FLW;
1552                     xinsn = SET_RD(xinsn, GET_C_RD(insn));
1553                     access_rs1 = 2;
1554                     access_imm = GET_C_LWSP_IMM(insn);
1555                     access_size = 4;
1556                 } else { /* C.LDSP (RV64/RV128) */
1557                     xinsn = OPC_RISC_LD;
1558                     xinsn = SET_RD(xinsn, GET_C_RD(insn));
1559                     access_rs1 = 2;
1560                     access_imm = GET_C_LDSP_IMM(insn);
1561                     access_size = 8;
1562                 }
1563                 break;
1564             case OPC_RISC_C_FUNC_FSDSP_SQSP:
1565                 if (riscv_cpu_xlen(env) != 128) { /* C.FSDSP (RV32/64) */
1566                     xinsn = OPC_RISC_FSD;
1567                     xinsn = SET_RS2(xinsn, GET_C_RS2(insn));
1568                     access_rs1 = 2;
1569                     access_imm = GET_C_SDSP_IMM(insn);
1570                     access_size = 8;
1571                 }
1572                 break;
1573             case OPC_RISC_C_FUNC_SWSP: /* C.SWSP */
1574                 xinsn = OPC_RISC_SW;
1575                 xinsn = SET_RS2(xinsn, GET_C_RS2(insn));
1576                 access_rs1 = 2;
1577                 access_imm = GET_C_SWSP_IMM(insn);
1578                 access_size = 4;
1579                 break;
1580             case 7:
1581                 if (riscv_cpu_xlen(env) == 32) { /* C.FSWSP (RV32) */
1582                     xinsn = OPC_RISC_FSW;
1583                     xinsn = SET_RS2(xinsn, GET_C_RS2(insn));
1584                     access_rs1 = 2;
1585                     access_imm = GET_C_SWSP_IMM(insn);
1586                     access_size = 4;
1587                 } else { /* C.SDSP (RV64/RV128) */
1588                     xinsn = OPC_RISC_SD;
1589                     xinsn = SET_RS2(xinsn, GET_C_RS2(insn));
1590                     access_rs1 = 2;
1591                     access_imm = GET_C_SDSP_IMM(insn);
1592                     access_size = 8;
1593                 }
1594                 break;
1595             default:
1596                 break;
1597             }
1598             break;
1599         default:
1600             break;
1601         }
1602 
1603         /*
1604          * Clear Bit1 of transformed instruction to indicate that
1605          * original insruction was a 16bit instruction
1606          */
1607         xinsn &= ~((target_ulong)0x2);
1608     } else {
1609         /* Transform 32bit (or wider) instructions */
1610         switch (MASK_OP_MAJOR(insn)) {
1611         case OPC_RISC_ATOMIC:
1612             xinsn = insn;
1613             access_rs1 = GET_RS1(insn);
1614             access_size = 1 << GET_FUNCT3(insn);
1615             break;
1616         case OPC_RISC_LOAD:
1617         case OPC_RISC_FP_LOAD:
1618             xinsn = SET_I_IMM(insn, 0);
1619             access_rs1 = GET_RS1(insn);
1620             access_imm = GET_IMM(insn);
1621             access_size = 1 << GET_FUNCT3(insn);
1622             break;
1623         case OPC_RISC_STORE:
1624         case OPC_RISC_FP_STORE:
1625             xinsn = SET_S_IMM(insn, 0);
1626             access_rs1 = GET_RS1(insn);
1627             access_imm = GET_STORE_IMM(insn);
1628             access_size = 1 << GET_FUNCT3(insn);
1629             break;
1630         case OPC_RISC_SYSTEM:
1631             if (MASK_OP_SYSTEM(insn) == OPC_RISC_HLVHSV) {
1632                 xinsn = insn;
1633                 access_rs1 = GET_RS1(insn);
1634                 access_size = 1 << ((GET_FUNCT7(insn) >> 1) & 0x3);
1635                 access_size = 1 << access_size;
1636             }
1637             break;
1638         default:
1639             break;
1640         }
1641     }
1642 
1643     if (access_size) {
1644         xinsn = SET_RS1(xinsn, (taddr - (env->gpr[access_rs1] + access_imm)) &
1645                                (access_size - 1));
1646     }
1647 
1648     return xinsn;
1649 }
1650 
1651 /*
1652  * Handle Traps
1653  *
1654  * Adapted from Spike's processor_t::take_trap.
1655  *
1656  */
1657 void riscv_cpu_do_interrupt(CPUState *cs)
1658 {
1659     RISCVCPU *cpu = RISCV_CPU(cs);
1660     CPURISCVState *env = &cpu->env;
1661     bool virt = env->virt_enabled;
1662     bool write_gva = false;
1663     uint64_t s;
1664 
1665     /*
1666      * cs->exception is 32-bits wide unlike mcause which is XLEN-bits wide
1667      * so we mask off the MSB and separate into trap type and cause.
1668      */
1669     bool async = !!(cs->exception_index & RISCV_EXCP_INT_FLAG);
1670     target_ulong cause = cs->exception_index & RISCV_EXCP_INT_MASK;
1671     uint64_t deleg = async ? env->mideleg : env->medeleg;
1672     bool s_injected = env->mvip & (1 << cause) & env->mvien &&
1673         !(env->mip & (1 << cause));
1674     bool vs_injected = env->hvip & (1 << cause) & env->hvien &&
1675         !(env->mip & (1 << cause));
1676     target_ulong tval = 0;
1677     target_ulong tinst = 0;
1678     target_ulong htval = 0;
1679     target_ulong mtval2 = 0;
1680     int sxlen = 0;
1681     int mxlen = 0;
1682 
1683     if (!async) {
1684         /* set tval to badaddr for traps with address information */
1685         switch (cause) {
1686 #ifdef CONFIG_TCG
1687         case RISCV_EXCP_SEMIHOST:
1688             do_common_semihosting(cs);
1689             env->pc += 4;
1690             return;
1691 #endif
1692         case RISCV_EXCP_LOAD_GUEST_ACCESS_FAULT:
1693         case RISCV_EXCP_STORE_GUEST_AMO_ACCESS_FAULT:
1694         case RISCV_EXCP_LOAD_ADDR_MIS:
1695         case RISCV_EXCP_STORE_AMO_ADDR_MIS:
1696         case RISCV_EXCP_LOAD_ACCESS_FAULT:
1697         case RISCV_EXCP_STORE_AMO_ACCESS_FAULT:
1698         case RISCV_EXCP_LOAD_PAGE_FAULT:
1699         case RISCV_EXCP_STORE_PAGE_FAULT:
1700             write_gva = env->two_stage_lookup;
1701             tval = env->badaddr;
1702             if (env->two_stage_indirect_lookup) {
1703                 /*
1704                  * special pseudoinstruction for G-stage fault taken while
1705                  * doing VS-stage page table walk.
1706                  */
1707                 tinst = (riscv_cpu_xlen(env) == 32) ? 0x00002000 : 0x00003000;
1708             } else {
1709                 /*
1710                  * The "Addr. Offset" field in transformed instruction is
1711                  * non-zero only for misaligned access.
1712                  */
1713                 tinst = riscv_transformed_insn(env, env->bins, tval);
1714             }
1715             break;
1716         case RISCV_EXCP_INST_GUEST_PAGE_FAULT:
1717         case RISCV_EXCP_INST_ADDR_MIS:
1718         case RISCV_EXCP_INST_ACCESS_FAULT:
1719         case RISCV_EXCP_INST_PAGE_FAULT:
1720             write_gva = env->two_stage_lookup;
1721             tval = env->badaddr;
1722             if (env->two_stage_indirect_lookup) {
1723                 /*
1724                  * special pseudoinstruction for G-stage fault taken while
1725                  * doing VS-stage page table walk.
1726                  */
1727                 tinst = (riscv_cpu_xlen(env) == 32) ? 0x00002000 : 0x00003000;
1728             }
1729             break;
1730         case RISCV_EXCP_ILLEGAL_INST:
1731         case RISCV_EXCP_VIRT_INSTRUCTION_FAULT:
1732             tval = env->bins;
1733             break;
1734         case RISCV_EXCP_BREAKPOINT:
1735             tval = env->badaddr;
1736             if (cs->watchpoint_hit) {
1737                 tval = cs->watchpoint_hit->hitaddr;
1738                 cs->watchpoint_hit = NULL;
1739             }
1740             break;
1741         default:
1742             break;
1743         }
1744         /* ecall is dispatched as one cause so translate based on mode */
1745         if (cause == RISCV_EXCP_U_ECALL) {
1746             assert(env->priv <= 3);
1747 
1748             if (env->priv == PRV_M) {
1749                 cause = RISCV_EXCP_M_ECALL;
1750             } else if (env->priv == PRV_S && env->virt_enabled) {
1751                 cause = RISCV_EXCP_VS_ECALL;
1752             } else if (env->priv == PRV_S && !env->virt_enabled) {
1753                 cause = RISCV_EXCP_S_ECALL;
1754             } else if (env->priv == PRV_U) {
1755                 cause = RISCV_EXCP_U_ECALL;
1756             }
1757         }
1758     }
1759 
1760     trace_riscv_trap(env->mhartid, async, cause, env->pc, tval,
1761                      riscv_cpu_get_trap_name(cause, async));
1762 
1763     qemu_log_mask(CPU_LOG_INT,
1764                   "%s: hart:"TARGET_FMT_ld", async:%d, cause:"TARGET_FMT_lx", "
1765                   "epc:0x"TARGET_FMT_lx", tval:0x"TARGET_FMT_lx", desc=%s\n",
1766                   __func__, env->mhartid, async, cause, env->pc, tval,
1767                   riscv_cpu_get_trap_name(cause, async));
1768 
1769     if (env->priv <= PRV_S && cause < 64 &&
1770         (((deleg >> cause) & 1) || s_injected || vs_injected)) {
1771         /* handle the trap in S-mode */
1772         if (riscv_has_ext(env, RVH)) {
1773             uint64_t hdeleg = async ? env->hideleg : env->hedeleg;
1774 
1775             if (env->virt_enabled &&
1776                 (((hdeleg >> cause) & 1) || vs_injected)) {
1777                 /* Trap to VS mode */
1778                 /*
1779                  * See if we need to adjust cause. Yes if its VS mode interrupt
1780                  * no if hypervisor has delegated one of hs mode's interrupt
1781                  */
1782                 if (async && (cause == IRQ_VS_TIMER || cause == IRQ_VS_SOFT ||
1783                               cause == IRQ_VS_EXT)) {
1784                     cause = cause - 1;
1785                 }
1786                 write_gva = false;
1787             } else if (env->virt_enabled) {
1788                 /* Trap into HS mode, from virt */
1789                 riscv_cpu_swap_hypervisor_regs(env);
1790                 env->hstatus = set_field(env->hstatus, HSTATUS_SPVP,
1791                                          env->priv);
1792                 env->hstatus = set_field(env->hstatus, HSTATUS_SPV, true);
1793 
1794                 htval = env->guest_phys_fault_addr;
1795 
1796                 virt = false;
1797             } else {
1798                 /* Trap into HS mode */
1799                 env->hstatus = set_field(env->hstatus, HSTATUS_SPV, false);
1800                 htval = env->guest_phys_fault_addr;
1801             }
1802             env->hstatus = set_field(env->hstatus, HSTATUS_GVA, write_gva);
1803         }
1804 
1805         s = env->mstatus;
1806         s = set_field(s, MSTATUS_SPIE, get_field(s, MSTATUS_SIE));
1807         s = set_field(s, MSTATUS_SPP, env->priv);
1808         s = set_field(s, MSTATUS_SIE, 0);
1809         env->mstatus = s;
1810         sxlen = 16 << riscv_cpu_sxl(env);
1811         env->scause = cause | ((target_ulong)async << (sxlen - 1));
1812         env->sepc = env->pc;
1813         env->stval = tval;
1814         env->htval = htval;
1815         env->htinst = tinst;
1816         env->pc = (env->stvec >> 2 << 2) +
1817                   ((async && (env->stvec & 3) == 1) ? cause * 4 : 0);
1818         riscv_cpu_set_mode(env, PRV_S, virt);
1819     } else {
1820         /* handle the trap in M-mode */
1821         if (riscv_has_ext(env, RVH)) {
1822             if (env->virt_enabled) {
1823                 riscv_cpu_swap_hypervisor_regs(env);
1824             }
1825             env->mstatus = set_field(env->mstatus, MSTATUS_MPV,
1826                                      env->virt_enabled);
1827             if (env->virt_enabled && tval) {
1828                 env->mstatus = set_field(env->mstatus, MSTATUS_GVA, 1);
1829             }
1830 
1831             mtval2 = env->guest_phys_fault_addr;
1832 
1833             /* Trapping to M mode, virt is disabled */
1834             virt = false;
1835         }
1836 
1837         s = env->mstatus;
1838         s = set_field(s, MSTATUS_MPIE, get_field(s, MSTATUS_MIE));
1839         s = set_field(s, MSTATUS_MPP, env->priv);
1840         s = set_field(s, MSTATUS_MIE, 0);
1841         env->mstatus = s;
1842         mxlen = 16 << riscv_cpu_mxl(env);
1843         env->mcause = cause | ((target_ulong)async << (mxlen - 1));
1844         env->mepc = env->pc;
1845         env->mtval = tval;
1846         env->mtval2 = mtval2;
1847         env->mtinst = tinst;
1848         env->pc = (env->mtvec >> 2 << 2) +
1849                   ((async && (env->mtvec & 3) == 1) ? cause * 4 : 0);
1850         riscv_cpu_set_mode(env, PRV_M, virt);
1851     }
1852 
1853     /*
1854      * NOTE: it is not necessary to yield load reservations here. It is only
1855      * necessary for an SC from "another hart" to cause a load reservation
1856      * to be yielded. Refer to the memory consistency model section of the
1857      * RISC-V ISA Specification.
1858      */
1859 
1860     env->two_stage_lookup = false;
1861     env->two_stage_indirect_lookup = false;
1862 }
1863 
1864 #endif /* !CONFIG_USER_ONLY */
1865