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