xref: /openbmc/qemu/target/riscv/cpu_helper.c (revision 22a7c2f239229b2ee9fcbac03cb598d9aebb9196)
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/cputlb.h"
27 #include "exec/exec-all.h"
28 #include "exec/page-protection.h"
29 #include "system/memory.h"
30 #include "instmap.h"
31 #include "tcg/tcg-op.h"
32 #include "accel/tcg/cpu-ops.h"
33 #include "trace.h"
34 #include "semihosting/common-semi.h"
35 #include "exec/icount.h"
36 #include "cpu_bits.h"
37 #include "debug.h"
38 #include "pmp.h"
39 
40 int riscv_env_mmu_index(CPURISCVState *env, bool ifetch)
41 {
42 #ifdef CONFIG_USER_ONLY
43     return 0;
44 #else
45     bool virt = env->virt_enabled;
46     int mode = env->priv;
47 
48     /* All priv -> mmu_idx mapping are here */
49     if (!ifetch) {
50         uint64_t status = env->mstatus;
51 
52         if (mode == PRV_M && get_field(status, MSTATUS_MPRV)) {
53             mode = get_field(env->mstatus, MSTATUS_MPP);
54             virt = get_field(env->mstatus, MSTATUS_MPV) &&
55                    (mode != PRV_M);
56             if (virt) {
57                 status = env->vsstatus;
58             }
59         }
60         if (mode == PRV_S && get_field(status, MSTATUS_SUM)) {
61             mode = MMUIdx_S_SUM;
62         }
63     }
64 
65     return mode | (virt ? MMU_2STAGE_BIT : 0);
66 #endif
67 }
68 
69 bool cpu_get_fcfien(CPURISCVState *env)
70 {
71     /* no cfi extension, return false */
72     if (!env_archcpu(env)->cfg.ext_zicfilp) {
73         return false;
74     }
75 
76     switch (env->priv) {
77     case PRV_U:
78         if (riscv_has_ext(env, RVS)) {
79             return env->senvcfg & SENVCFG_LPE;
80         }
81         return env->menvcfg & MENVCFG_LPE;
82 #ifndef CONFIG_USER_ONLY
83     case PRV_S:
84         if (env->virt_enabled) {
85             return env->henvcfg & HENVCFG_LPE;
86         }
87         return env->menvcfg & MENVCFG_LPE;
88     case PRV_M:
89         return env->mseccfg & MSECCFG_MLPE;
90 #endif
91     default:
92         g_assert_not_reached();
93     }
94 }
95 
96 bool cpu_get_bcfien(CPURISCVState *env)
97 {
98     /* no cfi extension, return false */
99     if (!env_archcpu(env)->cfg.ext_zicfiss) {
100         return false;
101     }
102 
103     switch (env->priv) {
104     case PRV_U:
105         /*
106          * If S is not implemented then shadow stack for U can't be turned on
107          * It is checked in `riscv_cpu_validate_set_extensions`, so no need to
108          * check here or assert here
109          */
110         return env->senvcfg & SENVCFG_SSE;
111 #ifndef CONFIG_USER_ONLY
112     case PRV_S:
113         if (env->virt_enabled) {
114             return env->henvcfg & HENVCFG_SSE;
115         }
116         return env->menvcfg & MENVCFG_SSE;
117     case PRV_M: /* M-mode shadow stack is always off */
118         return false;
119 #endif
120     default:
121         g_assert_not_reached();
122     }
123 }
124 
125 bool riscv_env_smode_dbltrp_enabled(CPURISCVState *env, bool virt)
126 {
127 #ifdef CONFIG_USER_ONLY
128     return false;
129 #else
130     if (virt) {
131         return (env->henvcfg & HENVCFG_DTE) != 0;
132     } else {
133         return (env->menvcfg & MENVCFG_DTE) != 0;
134     }
135 #endif
136 }
137 
138 void cpu_get_tb_cpu_state(CPURISCVState *env, vaddr *pc,
139                           uint64_t *cs_base, uint32_t *pflags)
140 {
141     RISCVCPU *cpu = env_archcpu(env);
142     RISCVExtStatus fs, vs;
143     uint32_t flags = 0;
144     bool pm_signext = riscv_cpu_virt_mem_enabled(env);
145 
146     *pc = env->xl == MXL_RV32 ? env->pc & UINT32_MAX : env->pc;
147     *cs_base = 0;
148 
149     if (cpu->cfg.ext_zve32x) {
150         /*
151          * If env->vl equals to VLMAX, we can use generic vector operation
152          * expanders (GVEC) to accerlate the vector operations.
153          * However, as LMUL could be a fractional number. The maximum
154          * vector size can be operated might be less than 8 bytes,
155          * which is not supported by GVEC. So we set vl_eq_vlmax flag to true
156          * only when maxsz >= 8 bytes.
157          */
158 
159         /* lmul encoded as in DisasContext::lmul */
160         int8_t lmul = sextract32(FIELD_EX64(env->vtype, VTYPE, VLMUL), 0, 3);
161         uint32_t vsew = FIELD_EX64(env->vtype, VTYPE, VSEW);
162         uint32_t vlmax = vext_get_vlmax(cpu->cfg.vlenb, vsew, lmul);
163         uint32_t maxsz = vlmax << vsew;
164         bool vl_eq_vlmax = (env->vstart == 0) && (vlmax == env->vl) &&
165                            (maxsz >= 8);
166         flags = FIELD_DP32(flags, TB_FLAGS, VILL, env->vill);
167         flags = FIELD_DP32(flags, TB_FLAGS, SEW, vsew);
168         flags = FIELD_DP32(flags, TB_FLAGS, LMUL,
169                            FIELD_EX64(env->vtype, VTYPE, VLMUL));
170         flags = FIELD_DP32(flags, TB_FLAGS, VL_EQ_VLMAX, vl_eq_vlmax);
171         flags = FIELD_DP32(flags, TB_FLAGS, VTA,
172                            FIELD_EX64(env->vtype, VTYPE, VTA));
173         flags = FIELD_DP32(flags, TB_FLAGS, VMA,
174                            FIELD_EX64(env->vtype, VTYPE, VMA));
175         flags = FIELD_DP32(flags, TB_FLAGS, VSTART_EQ_ZERO, env->vstart == 0);
176     } else {
177         flags = FIELD_DP32(flags, TB_FLAGS, VILL, 1);
178     }
179 
180     if (cpu_get_fcfien(env)) {
181         /*
182          * For Forward CFI, only the expectation of a lpad at
183          * the start of the block is tracked via env->elp. env->elp
184          * is turned on during jalr translation.
185          */
186         flags = FIELD_DP32(flags, TB_FLAGS, FCFI_LP_EXPECTED, env->elp);
187         flags = FIELD_DP32(flags, TB_FLAGS, FCFI_ENABLED, 1);
188     }
189 
190     if (cpu_get_bcfien(env)) {
191         flags = FIELD_DP32(flags, TB_FLAGS, BCFI_ENABLED, 1);
192     }
193 
194 #ifdef CONFIG_USER_ONLY
195     fs = EXT_STATUS_DIRTY;
196     vs = EXT_STATUS_DIRTY;
197 #else
198     flags = FIELD_DP32(flags, TB_FLAGS, PRIV, env->priv);
199 
200     flags |= riscv_env_mmu_index(env, 0);
201     fs = get_field(env->mstatus, MSTATUS_FS);
202     vs = get_field(env->mstatus, MSTATUS_VS);
203 
204     if (env->virt_enabled) {
205         flags = FIELD_DP32(flags, TB_FLAGS, VIRT_ENABLED, 1);
206         /*
207          * Merge DISABLED and !DIRTY states using MIN.
208          * We will set both fields when dirtying.
209          */
210         fs = MIN(fs, get_field(env->mstatus_hs, MSTATUS_FS));
211         vs = MIN(vs, get_field(env->mstatus_hs, MSTATUS_VS));
212     }
213 
214     /* With Zfinx, floating point is enabled/disabled by Smstateen. */
215     if (!riscv_has_ext(env, RVF)) {
216         fs = (smstateen_acc_ok(env, 0, SMSTATEEN0_FCSR) == RISCV_EXCP_NONE)
217              ? EXT_STATUS_DIRTY : EXT_STATUS_DISABLED;
218     }
219 
220     if (cpu->cfg.debug && !icount_enabled()) {
221         flags = FIELD_DP32(flags, TB_FLAGS, ITRIGGER, env->itrigger_enabled);
222     }
223 #endif
224 
225     flags = FIELD_DP32(flags, TB_FLAGS, FS, fs);
226     flags = FIELD_DP32(flags, TB_FLAGS, VS, vs);
227     flags = FIELD_DP32(flags, TB_FLAGS, XL, env->xl);
228     flags = FIELD_DP32(flags, TB_FLAGS, AXL, cpu_address_xl(env));
229     flags = FIELD_DP32(flags, TB_FLAGS, PM_PMM, riscv_pm_get_pmm(env));
230     flags = FIELD_DP32(flags, TB_FLAGS, PM_SIGNEXTEND, pm_signext);
231 
232     *pflags = flags;
233 }
234 
235 RISCVPmPmm riscv_pm_get_pmm(CPURISCVState *env)
236 {
237 #ifndef CONFIG_USER_ONLY
238     int priv_mode = cpu_address_mode(env);
239 
240     if (get_field(env->mstatus, MSTATUS_MPRV) &&
241         get_field(env->mstatus, MSTATUS_MXR)) {
242         return PMM_FIELD_DISABLED;
243     }
244 
245     /* Get current PMM field */
246     switch (priv_mode) {
247     case PRV_M:
248         if (riscv_cpu_cfg(env)->ext_smmpm) {
249             return get_field(env->mseccfg, MSECCFG_PMM);
250         }
251         break;
252     case PRV_S:
253         if (riscv_cpu_cfg(env)->ext_smnpm) {
254             if (get_field(env->mstatus, MSTATUS_MPV)) {
255                 return get_field(env->henvcfg, HENVCFG_PMM);
256             } else {
257                 return get_field(env->menvcfg, MENVCFG_PMM);
258             }
259         }
260         break;
261     case PRV_U:
262         if (riscv_has_ext(env, RVS)) {
263             if (riscv_cpu_cfg(env)->ext_ssnpm) {
264                 return get_field(env->senvcfg, SENVCFG_PMM);
265             }
266         } else {
267             if (riscv_cpu_cfg(env)->ext_smnpm) {
268                 return get_field(env->menvcfg, MENVCFG_PMM);
269             }
270         }
271         break;
272     default:
273         g_assert_not_reached();
274     }
275     return PMM_FIELD_DISABLED;
276 #else
277     return PMM_FIELD_DISABLED;
278 #endif
279 }
280 
281 RISCVPmPmm riscv_pm_get_virt_pmm(CPURISCVState *env)
282 {
283 #ifndef CONFIG_USER_ONLY
284     int priv_mode = cpu_address_mode(env);
285 
286     if (priv_mode == PRV_U) {
287         return get_field(env->hstatus, HSTATUS_HUPMM);
288     } else {
289         if (get_field(env->hstatus, HSTATUS_SPVP)) {
290             return get_field(env->henvcfg, HENVCFG_PMM);
291         } else {
292             return get_field(env->senvcfg, SENVCFG_PMM);
293         }
294     }
295 #else
296     return PMM_FIELD_DISABLED;
297 #endif
298 }
299 
300 bool riscv_cpu_virt_mem_enabled(CPURISCVState *env)
301 {
302 #ifndef CONFIG_USER_ONLY
303     int satp_mode = 0;
304     int priv_mode = cpu_address_mode(env);
305 
306     if (riscv_cpu_mxl(env) == MXL_RV32) {
307         satp_mode = get_field(env->satp, SATP32_MODE);
308     } else {
309         satp_mode = get_field(env->satp, SATP64_MODE);
310     }
311 
312     return ((satp_mode != VM_1_10_MBARE) && (priv_mode != PRV_M));
313 #else
314     return false;
315 #endif
316 }
317 
318 uint32_t riscv_pm_get_pmlen(RISCVPmPmm pmm)
319 {
320     switch (pmm) {
321     case PMM_FIELD_DISABLED:
322         return 0;
323     case PMM_FIELD_PMLEN7:
324         return 7;
325     case PMM_FIELD_PMLEN16:
326         return 16;
327     default:
328         g_assert_not_reached();
329     }
330 }
331 
332 #ifndef CONFIG_USER_ONLY
333 
334 /*
335  * The HS-mode is allowed to configure priority only for the
336  * following VS-mode local interrupts:
337  *
338  * 0  (Reserved interrupt, reads as zero)
339  * 1  Supervisor software interrupt
340  * 4  (Reserved interrupt, reads as zero)
341  * 5  Supervisor timer interrupt
342  * 8  (Reserved interrupt, reads as zero)
343  * 13 (Reserved interrupt)
344  * 14 "
345  * 15 "
346  * 16 "
347  * 17 "
348  * 18 "
349  * 19 "
350  * 20 "
351  * 21 "
352  * 22 "
353  * 23 "
354  */
355 
356 static const int hviprio_index2irq[] = {
357     0, 1, 4, 5, 8, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 };
358 static const int hviprio_index2rdzero[] = {
359     1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
360 
361 int riscv_cpu_hviprio_index2irq(int index, int *out_irq, int *out_rdzero)
362 {
363     if (index < 0 || ARRAY_SIZE(hviprio_index2irq) <= index) {
364         return -EINVAL;
365     }
366 
367     if (out_irq) {
368         *out_irq = hviprio_index2irq[index];
369     }
370 
371     if (out_rdzero) {
372         *out_rdzero = hviprio_index2rdzero[index];
373     }
374 
375     return 0;
376 }
377 
378 /*
379  * Default priorities of local interrupts are defined in the
380  * RISC-V Advanced Interrupt Architecture specification.
381  *
382  * ----------------------------------------------------------------
383  *  Default  |
384  *  Priority | Major Interrupt Numbers
385  * ----------------------------------------------------------------
386  *  Highest  | 47, 23, 46, 45, 22, 44,
387  *           | 43, 21, 42, 41, 20, 40
388  *           |
389  *           | 11 (0b),  3 (03),  7 (07)
390  *           |  9 (09),  1 (01),  5 (05)
391  *           | 12 (0c)
392  *           | 10 (0a),  2 (02),  6 (06)
393  *           |
394  *           | 39, 19, 38, 37, 18, 36,
395  *  Lowest   | 35, 17, 34, 33, 16, 32
396  * ----------------------------------------------------------------
397  */
398 static const uint8_t default_iprio[64] = {
399     /* Custom interrupts 48 to 63 */
400     [63] = IPRIO_MMAXIPRIO,
401     [62] = IPRIO_MMAXIPRIO,
402     [61] = IPRIO_MMAXIPRIO,
403     [60] = IPRIO_MMAXIPRIO,
404     [59] = IPRIO_MMAXIPRIO,
405     [58] = IPRIO_MMAXIPRIO,
406     [57] = IPRIO_MMAXIPRIO,
407     [56] = IPRIO_MMAXIPRIO,
408     [55] = IPRIO_MMAXIPRIO,
409     [54] = IPRIO_MMAXIPRIO,
410     [53] = IPRIO_MMAXIPRIO,
411     [52] = IPRIO_MMAXIPRIO,
412     [51] = IPRIO_MMAXIPRIO,
413     [50] = IPRIO_MMAXIPRIO,
414     [49] = IPRIO_MMAXIPRIO,
415     [48] = IPRIO_MMAXIPRIO,
416 
417     /* Custom interrupts 24 to 31 */
418     [31] = IPRIO_MMAXIPRIO,
419     [30] = IPRIO_MMAXIPRIO,
420     [29] = IPRIO_MMAXIPRIO,
421     [28] = IPRIO_MMAXIPRIO,
422     [27] = IPRIO_MMAXIPRIO,
423     [26] = IPRIO_MMAXIPRIO,
424     [25] = IPRIO_MMAXIPRIO,
425     [24] = IPRIO_MMAXIPRIO,
426 
427     [47] = IPRIO_DEFAULT_UPPER,
428     [23] = IPRIO_DEFAULT_UPPER + 1,
429     [46] = IPRIO_DEFAULT_UPPER + 2,
430     [45] = IPRIO_DEFAULT_UPPER + 3,
431     [22] = IPRIO_DEFAULT_UPPER + 4,
432     [44] = IPRIO_DEFAULT_UPPER + 5,
433 
434     [43] = IPRIO_DEFAULT_UPPER + 6,
435     [21] = IPRIO_DEFAULT_UPPER + 7,
436     [42] = IPRIO_DEFAULT_UPPER + 8,
437     [41] = IPRIO_DEFAULT_UPPER + 9,
438     [20] = IPRIO_DEFAULT_UPPER + 10,
439     [40] = IPRIO_DEFAULT_UPPER + 11,
440 
441     [11] = IPRIO_DEFAULT_M,
442     [3]  = IPRIO_DEFAULT_M + 1,
443     [7]  = IPRIO_DEFAULT_M + 2,
444 
445     [9]  = IPRIO_DEFAULT_S,
446     [1]  = IPRIO_DEFAULT_S + 1,
447     [5]  = IPRIO_DEFAULT_S + 2,
448 
449     [12] = IPRIO_DEFAULT_SGEXT,
450 
451     [10] = IPRIO_DEFAULT_VS,
452     [2]  = IPRIO_DEFAULT_VS + 1,
453     [6]  = IPRIO_DEFAULT_VS + 2,
454 
455     [39] = IPRIO_DEFAULT_LOWER,
456     [19] = IPRIO_DEFAULT_LOWER + 1,
457     [38] = IPRIO_DEFAULT_LOWER + 2,
458     [37] = IPRIO_DEFAULT_LOWER + 3,
459     [18] = IPRIO_DEFAULT_LOWER + 4,
460     [36] = IPRIO_DEFAULT_LOWER + 5,
461 
462     [35] = IPRIO_DEFAULT_LOWER + 6,
463     [17] = IPRIO_DEFAULT_LOWER + 7,
464     [34] = IPRIO_DEFAULT_LOWER + 8,
465     [33] = IPRIO_DEFAULT_LOWER + 9,
466     [16] = IPRIO_DEFAULT_LOWER + 10,
467     [32] = IPRIO_DEFAULT_LOWER + 11,
468 };
469 
470 uint8_t riscv_cpu_default_priority(int irq)
471 {
472     if (irq < 0 || irq > 63) {
473         return IPRIO_MMAXIPRIO;
474     }
475 
476     return default_iprio[irq] ? default_iprio[irq] : IPRIO_MMAXIPRIO;
477 };
478 
479 static int riscv_cpu_pending_to_irq(CPURISCVState *env,
480                                     int extirq, unsigned int extirq_def_prio,
481                                     uint64_t pending, uint8_t *iprio)
482 {
483     int irq, best_irq = RISCV_EXCP_NONE;
484     unsigned int prio, best_prio = UINT_MAX;
485 
486     if (!pending) {
487         return RISCV_EXCP_NONE;
488     }
489 
490     irq = ctz64(pending);
491     if (!((extirq == IRQ_M_EXT) ? riscv_cpu_cfg(env)->ext_smaia :
492                                   riscv_cpu_cfg(env)->ext_ssaia)) {
493         return irq;
494     }
495 
496     pending = pending >> irq;
497     while (pending) {
498         prio = iprio[irq];
499         if (!prio) {
500             if (irq == extirq) {
501                 prio = extirq_def_prio;
502             } else {
503                 prio = (riscv_cpu_default_priority(irq) < extirq_def_prio) ?
504                        1 : IPRIO_MMAXIPRIO;
505             }
506         }
507         if ((pending & 0x1) && (prio <= best_prio)) {
508             best_irq = irq;
509             best_prio = prio;
510         }
511         irq++;
512         pending = pending >> 1;
513     }
514 
515     return best_irq;
516 }
517 
518 /*
519  * Doesn't report interrupts inserted using mvip from M-mode firmware or
520  * using hvip bits 13:63 from HS-mode. Those are returned in
521  * riscv_cpu_sirq_pending() and riscv_cpu_vsirq_pending().
522  */
523 uint64_t riscv_cpu_all_pending(CPURISCVState *env)
524 {
525     uint32_t gein = get_field(env->hstatus, HSTATUS_VGEIN);
526     uint64_t vsgein = (env->hgeip & (1ULL << gein)) ? MIP_VSEIP : 0;
527     uint64_t vstip = (env->vstime_irq) ? MIP_VSTIP : 0;
528 
529     return (env->mip | vsgein | vstip) & env->mie;
530 }
531 
532 int riscv_cpu_mirq_pending(CPURISCVState *env)
533 {
534     uint64_t irqs = riscv_cpu_all_pending(env) & ~env->mideleg &
535                     ~(MIP_SGEIP | MIP_VSSIP | MIP_VSTIP | MIP_VSEIP);
536 
537     return riscv_cpu_pending_to_irq(env, IRQ_M_EXT, IPRIO_DEFAULT_M,
538                                     irqs, env->miprio);
539 }
540 
541 int riscv_cpu_sirq_pending(CPURISCVState *env)
542 {
543     uint64_t irqs = riscv_cpu_all_pending(env) & env->mideleg &
544                     ~(MIP_VSSIP | MIP_VSTIP | MIP_VSEIP);
545     uint64_t irqs_f = env->mvip & env->mvien & ~env->mideleg & env->sie;
546 
547     return riscv_cpu_pending_to_irq(env, IRQ_S_EXT, IPRIO_DEFAULT_S,
548                                     irqs | irqs_f, env->siprio);
549 }
550 
551 int riscv_cpu_vsirq_pending(CPURISCVState *env)
552 {
553     uint64_t irqs = riscv_cpu_all_pending(env) & env->mideleg & env->hideleg;
554     uint64_t irqs_f_vs = env->hvip & env->hvien & ~env->hideleg & env->vsie;
555     uint64_t vsbits;
556 
557     /* Bring VS-level bits to correct position */
558     vsbits = irqs & VS_MODE_INTERRUPTS;
559     irqs &= ~VS_MODE_INTERRUPTS;
560     irqs |= vsbits >> 1;
561 
562     return riscv_cpu_pending_to_irq(env, IRQ_S_EXT, IPRIO_DEFAULT_S,
563                                     (irqs | irqs_f_vs), env->hviprio);
564 }
565 
566 static int riscv_cpu_local_irq_pending(CPURISCVState *env)
567 {
568     uint64_t irqs, pending, mie, hsie, vsie, irqs_f, irqs_f_vs;
569     uint64_t vsbits, irq_delegated;
570     int virq;
571 
572     /* Priority: RNMI > Other interrupt. */
573     if (riscv_cpu_cfg(env)->ext_smrnmi) {
574         /* If mnstatus.NMIE == 0, all interrupts are disabled. */
575         if (!get_field(env->mnstatus, MNSTATUS_NMIE)) {
576             return RISCV_EXCP_NONE;
577         }
578 
579         if (env->rnmip) {
580             return ctz64(env->rnmip); /* since non-zero */
581         }
582     }
583 
584     /* Determine interrupt enable state of all privilege modes */
585     if (env->virt_enabled) {
586         mie = 1;
587         hsie = 1;
588         vsie = (env->priv < PRV_S) ||
589                (env->priv == PRV_S && get_field(env->mstatus, MSTATUS_SIE));
590     } else {
591         mie = (env->priv < PRV_M) ||
592               (env->priv == PRV_M && get_field(env->mstatus, MSTATUS_MIE));
593         hsie = (env->priv < PRV_S) ||
594                (env->priv == PRV_S && get_field(env->mstatus, MSTATUS_SIE));
595         vsie = 0;
596     }
597 
598     /* Determine all pending interrupts */
599     pending = riscv_cpu_all_pending(env);
600 
601     /* Check M-mode interrupts */
602     irqs = pending & ~env->mideleg & -mie;
603     if (irqs) {
604         return riscv_cpu_pending_to_irq(env, IRQ_M_EXT, IPRIO_DEFAULT_M,
605                                         irqs, env->miprio);
606     }
607 
608     /* Check for virtual S-mode interrupts. */
609     irqs_f = env->mvip & (env->mvien & ~env->mideleg) & env->sie;
610 
611     /* Check HS-mode interrupts */
612     irqs =  ((pending & env->mideleg & ~env->hideleg) | irqs_f) & -hsie;
613     if (irqs) {
614         return riscv_cpu_pending_to_irq(env, IRQ_S_EXT, IPRIO_DEFAULT_S,
615                                         irqs, env->siprio);
616     }
617 
618     /* Check for virtual VS-mode interrupts. */
619     irqs_f_vs = env->hvip & env->hvien & ~env->hideleg & env->vsie;
620 
621     /* Check VS-mode interrupts */
622     irq_delegated = pending & env->mideleg & env->hideleg;
623 
624     /* Bring VS-level bits to correct position */
625     vsbits = irq_delegated & VS_MODE_INTERRUPTS;
626     irq_delegated &= ~VS_MODE_INTERRUPTS;
627     irq_delegated |= vsbits >> 1;
628 
629     irqs = (irq_delegated | irqs_f_vs) & -vsie;
630     if (irqs) {
631         virq = riscv_cpu_pending_to_irq(env, IRQ_S_EXT, IPRIO_DEFAULT_S,
632                                         irqs, env->hviprio);
633         if (virq <= 0 || (virq > 12 && virq <= 63)) {
634             return virq;
635         } else {
636             return virq + 1;
637         }
638     }
639 
640     /* Indicate no pending interrupt */
641     return RISCV_EXCP_NONE;
642 }
643 
644 bool riscv_cpu_exec_interrupt(CPUState *cs, int interrupt_request)
645 {
646     uint32_t mask = CPU_INTERRUPT_HARD | CPU_INTERRUPT_RNMI;
647 
648     if (interrupt_request & mask) {
649         RISCVCPU *cpu = RISCV_CPU(cs);
650         CPURISCVState *env = &cpu->env;
651         int interruptno = riscv_cpu_local_irq_pending(env);
652         if (interruptno >= 0) {
653             cs->exception_index = RISCV_EXCP_INT_FLAG | interruptno;
654             riscv_cpu_do_interrupt(cs);
655             return true;
656         }
657     }
658     return false;
659 }
660 
661 /* Return true is floating point support is currently enabled */
662 bool riscv_cpu_fp_enabled(CPURISCVState *env)
663 {
664     if (env->mstatus & MSTATUS_FS) {
665         if (env->virt_enabled && !(env->mstatus_hs & MSTATUS_FS)) {
666             return false;
667         }
668         return true;
669     }
670 
671     return false;
672 }
673 
674 /* Return true is vector support is currently enabled */
675 bool riscv_cpu_vector_enabled(CPURISCVState *env)
676 {
677     if (env->mstatus & MSTATUS_VS) {
678         if (env->virt_enabled && !(env->mstatus_hs & MSTATUS_VS)) {
679             return false;
680         }
681         return true;
682     }
683 
684     return false;
685 }
686 
687 void riscv_cpu_swap_hypervisor_regs(CPURISCVState *env)
688 {
689     uint64_t mstatus_mask = MSTATUS_MXR | MSTATUS_SUM |
690                             MSTATUS_SPP | MSTATUS_SPIE | MSTATUS_SIE |
691                             MSTATUS64_UXL | MSTATUS_VS;
692 
693     if (riscv_has_ext(env, RVF)) {
694         mstatus_mask |= MSTATUS_FS;
695     }
696     bool current_virt = env->virt_enabled;
697 
698     /*
699      * If zicfilp extension available and henvcfg.LPE = 1,
700      * then apply SPELP mask on mstatus
701      */
702     if (env_archcpu(env)->cfg.ext_zicfilp &&
703         get_field(env->henvcfg, HENVCFG_LPE)) {
704         mstatus_mask |= SSTATUS_SPELP;
705     }
706 
707     g_assert(riscv_has_ext(env, RVH));
708 
709     if (riscv_env_smode_dbltrp_enabled(env, current_virt)) {
710         mstatus_mask |= MSTATUS_SDT;
711     }
712 
713     if (current_virt) {
714         /* Current V=1 and we are about to change to V=0 */
715         env->vsstatus = env->mstatus & mstatus_mask;
716         env->mstatus &= ~mstatus_mask;
717         env->mstatus |= env->mstatus_hs;
718 
719         env->vstvec = env->stvec;
720         env->stvec = env->stvec_hs;
721 
722         env->vsscratch = env->sscratch;
723         env->sscratch = env->sscratch_hs;
724 
725         env->vsepc = env->sepc;
726         env->sepc = env->sepc_hs;
727 
728         env->vscause = env->scause;
729         env->scause = env->scause_hs;
730 
731         env->vstval = env->stval;
732         env->stval = env->stval_hs;
733 
734         env->vsatp = env->satp;
735         env->satp = env->satp_hs;
736     } else {
737         /* Current V=0 and we are about to change to V=1 */
738         env->mstatus_hs = env->mstatus & mstatus_mask;
739         env->mstatus &= ~mstatus_mask;
740         env->mstatus |= env->vsstatus;
741 
742         env->stvec_hs = env->stvec;
743         env->stvec = env->vstvec;
744 
745         env->sscratch_hs = env->sscratch;
746         env->sscratch = env->vsscratch;
747 
748         env->sepc_hs = env->sepc;
749         env->sepc = env->vsepc;
750 
751         env->scause_hs = env->scause;
752         env->scause = env->vscause;
753 
754         env->stval_hs = env->stval;
755         env->stval = env->vstval;
756 
757         env->satp_hs = env->satp;
758         env->satp = env->vsatp;
759     }
760 }
761 
762 target_ulong riscv_cpu_get_geilen(CPURISCVState *env)
763 {
764     if (!riscv_has_ext(env, RVH)) {
765         return 0;
766     }
767 
768     return env->geilen;
769 }
770 
771 void riscv_cpu_set_geilen(CPURISCVState *env, target_ulong geilen)
772 {
773     if (!riscv_has_ext(env, RVH)) {
774         return;
775     }
776 
777     if (geilen > (TARGET_LONG_BITS - 1)) {
778         return;
779     }
780 
781     env->geilen = geilen;
782 }
783 
784 void riscv_cpu_set_rnmi(RISCVCPU *cpu, uint32_t irq, bool level)
785 {
786     CPURISCVState *env = &cpu->env;
787     CPUState *cs = CPU(cpu);
788     bool release_lock = false;
789 
790     if (!bql_locked()) {
791         release_lock = true;
792         bql_lock();
793     }
794 
795     if (level) {
796         env->rnmip |= 1 << irq;
797         cpu_interrupt(cs, CPU_INTERRUPT_RNMI);
798     } else {
799         env->rnmip &= ~(1 << irq);
800         cpu_reset_interrupt(cs, CPU_INTERRUPT_RNMI);
801     }
802 
803     if (release_lock) {
804         bql_unlock();
805     }
806 }
807 
808 int riscv_cpu_claim_interrupts(RISCVCPU *cpu, uint64_t interrupts)
809 {
810     CPURISCVState *env = &cpu->env;
811     if (env->miclaim & interrupts) {
812         return -1;
813     } else {
814         env->miclaim |= interrupts;
815         return 0;
816     }
817 }
818 
819 void riscv_cpu_interrupt(CPURISCVState *env)
820 {
821     uint64_t gein, vsgein = 0, vstip = 0, irqf = 0;
822     CPUState *cs = env_cpu(env);
823 
824     BQL_LOCK_GUARD();
825 
826     if (env->virt_enabled) {
827         gein = get_field(env->hstatus, HSTATUS_VGEIN);
828         vsgein = (env->hgeip & (1ULL << gein)) ? MIP_VSEIP : 0;
829         irqf = env->hvien & env->hvip & env->vsie;
830     } else {
831         irqf = env->mvien & env->mvip & env->sie;
832     }
833 
834     vstip = env->vstime_irq ? MIP_VSTIP : 0;
835 
836     if (env->mip | vsgein | vstip | irqf) {
837         cpu_interrupt(cs, CPU_INTERRUPT_HARD);
838     } else {
839         cpu_reset_interrupt(cs, CPU_INTERRUPT_HARD);
840     }
841 }
842 
843 uint64_t riscv_cpu_update_mip(CPURISCVState *env, uint64_t mask, uint64_t value)
844 {
845     uint64_t old = env->mip;
846 
847     /* No need to update mip for VSTIP */
848     mask = ((mask == MIP_VSTIP) && env->vstime_irq) ? 0 : mask;
849 
850     BQL_LOCK_GUARD();
851 
852     env->mip = (env->mip & ~mask) | (value & mask);
853 
854     riscv_cpu_interrupt(env);
855 
856     return old;
857 }
858 
859 void riscv_cpu_set_rdtime_fn(CPURISCVState *env, uint64_t (*fn)(void *),
860                              void *arg)
861 {
862     env->rdtime_fn = fn;
863     env->rdtime_fn_arg = arg;
864 }
865 
866 void riscv_cpu_set_aia_ireg_rmw_fn(CPURISCVState *env, uint32_t priv,
867                                    int (*rmw_fn)(void *arg,
868                                                  target_ulong reg,
869                                                  target_ulong *val,
870                                                  target_ulong new_val,
871                                                  target_ulong write_mask),
872                                    void *rmw_fn_arg)
873 {
874     if (priv <= PRV_M) {
875         env->aia_ireg_rmw_fn[priv] = rmw_fn;
876         env->aia_ireg_rmw_fn_arg[priv] = rmw_fn_arg;
877     }
878 }
879 
880 static void riscv_ctr_freeze(CPURISCVState *env, uint64_t freeze_mask,
881                              bool virt)
882 {
883     uint64_t ctl = virt ? env->vsctrctl : env->mctrctl;
884 
885     assert((freeze_mask & (~(XCTRCTL_BPFRZ | XCTRCTL_LCOFIFRZ))) == 0);
886 
887     if (ctl & freeze_mask) {
888         env->sctrstatus |= SCTRSTATUS_FROZEN;
889     }
890 }
891 
892 void riscv_ctr_clear(CPURISCVState *env)
893 {
894     memset(env->ctr_src, 0x0, sizeof(env->ctr_src));
895     memset(env->ctr_dst, 0x0, sizeof(env->ctr_dst));
896     memset(env->ctr_data, 0x0, sizeof(env->ctr_data));
897 }
898 
899 static uint64_t riscv_ctr_priv_to_mask(target_ulong priv, bool virt)
900 {
901     switch (priv) {
902     case PRV_M:
903         return MCTRCTL_M;
904     case PRV_S:
905         if (virt) {
906             return XCTRCTL_S;
907         }
908         return XCTRCTL_S;
909     case PRV_U:
910         if (virt) {
911             return XCTRCTL_U;
912         }
913         return XCTRCTL_U;
914     }
915 
916     g_assert_not_reached();
917 }
918 
919 static uint64_t riscv_ctr_get_control(CPURISCVState *env, target_long priv,
920                                       bool virt)
921 {
922     switch (priv) {
923     case PRV_M:
924         return env->mctrctl;
925     case PRV_S:
926     case PRV_U:
927         if (virt) {
928             return env->vsctrctl;
929         }
930         return env->mctrctl;
931     }
932 
933     g_assert_not_reached();
934 }
935 
936 /*
937  * This function assumes that src privilege and target privilege are not same
938  * and src privilege is less than target privilege. This includes the virtual
939  * state as well.
940  */
941 static bool riscv_ctr_check_xte(CPURISCVState *env, target_long src_prv,
942                                 bool src_virt)
943 {
944     target_long tgt_prv = env->priv;
945     bool res = true;
946 
947     /*
948      * VS and U mode are same in terms of xTE bits required to record an
949      * external trap. See 6.1.2. External Traps, table 8 External Trap Enable
950      * Requirements. This changes VS to U to simplify the logic a bit.
951      */
952     if (src_virt && src_prv == PRV_S) {
953         src_prv = PRV_U;
954     } else if (env->virt_enabled && tgt_prv == PRV_S) {
955         tgt_prv = PRV_U;
956     }
957 
958     /* VU mode is an outlier here. */
959     if (src_virt && src_prv == PRV_U) {
960         res &= !!(env->vsctrctl & XCTRCTL_STE);
961     }
962 
963     switch (src_prv) {
964     case PRV_U:
965         if (tgt_prv == PRV_U) {
966             break;
967         }
968         res &= !!(env->mctrctl & XCTRCTL_STE);
969         /* fall-through */
970     case PRV_S:
971         if (tgt_prv == PRV_S) {
972             break;
973         }
974         res &= !!(env->mctrctl & MCTRCTL_MTE);
975         /* fall-through */
976     case PRV_M:
977         break;
978     }
979 
980     return res;
981 }
982 
983 /*
984  * Special cases for traps and trap returns:
985  *
986  * 1- Traps, and trap returns, between enabled modes are recorded as normal.
987  * 2- Traps from an inhibited mode to an enabled mode, and trap returns from an
988  * enabled mode back to an inhibited mode, are partially recorded.  In such
989  * cases, the PC from the inhibited mode (source PC for traps, and target PC
990  * for trap returns) is 0.
991  *
992  * 3- Trap returns from an inhibited mode to an enabled mode are not recorded.
993  * Traps from an enabled mode to an inhibited mode, known as external traps,
994  * receive special handling.
995  * By default external traps are not recorded, but a handshake mechanism exists
996  * to allow partial recording.  Software running in the target mode of the trap
997  * can opt-in to allowing CTR to record traps into that mode even when the mode
998  * is inhibited.  The MTE, STE, and VSTE bits allow M-mode, S-mode, and VS-mode,
999  * respectively, to opt-in. When an External Trap occurs, and xTE=1, such that
1000  * x is the target privilege mode of the trap, will CTR record the trap. In such
1001  * cases, the target PC is 0.
1002  */
1003 /*
1004  * CTR arrays are implemented as circular buffers and new entry is stored at
1005  * sctrstatus.WRPTR, but they are presented to software as moving circular
1006  * buffers. Which means, software get's the illusion that whenever a new entry
1007  * is added the whole buffer is moved by one place and the new entry is added at
1008  * the start keeping new entry at idx 0 and older ones follow.
1009  *
1010  * Depth = 16.
1011  *
1012  * buffer [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [A] [B] [C] [D] [E] [F]
1013  * WRPTR                                   W
1014  * entry   7   6   5   4   3   2   1   0   F   E   D   C   B   A   9   8
1015  *
1016  * When a new entry is added:
1017  * buffer [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [A] [B] [C] [D] [E] [F]
1018  * WRPTR                                       W
1019  * entry   8   7   6   5   4   3   2   1   0   F   E   D   C   B   A   9
1020  *
1021  * entry here denotes the logical entry number that software can access
1022  * using ctrsource, ctrtarget and ctrdata registers. So xiselect 0x200
1023  * will return entry 0 i-e buffer[8] and 0x201 will return entry 1 i-e
1024  * buffer[7]. Here is how we convert entry to buffer idx.
1025  *
1026  *    entry = isel - CTR_ENTRIES_FIRST;
1027  *    idx = (sctrstatus.WRPTR - entry - 1) & (depth - 1);
1028  */
1029 void riscv_ctr_add_entry(CPURISCVState *env, target_long src, target_long dst,
1030     enum CTRType type, target_ulong src_priv, bool src_virt)
1031 {
1032     bool tgt_virt = env->virt_enabled;
1033     uint64_t src_mask = riscv_ctr_priv_to_mask(src_priv, src_virt);
1034     uint64_t tgt_mask = riscv_ctr_priv_to_mask(env->priv, tgt_virt);
1035     uint64_t src_ctrl = riscv_ctr_get_control(env, src_priv, src_virt);
1036     uint64_t tgt_ctrl = riscv_ctr_get_control(env, env->priv, tgt_virt);
1037     uint64_t depth, head;
1038     bool ext_trap = false;
1039 
1040     /*
1041      * Return immediately if both target and src recording is disabled or if
1042      * CTR is in frozen state.
1043      */
1044     if ((!(src_ctrl & src_mask) && !(tgt_ctrl & tgt_mask)) ||
1045         env->sctrstatus & SCTRSTATUS_FROZEN) {
1046         return;
1047     }
1048 
1049     /*
1050      * With RAS Emul enabled, only allow Indirect, direct calls, Function
1051      * returns and Co-routine swap types.
1052      */
1053     if (tgt_ctrl & XCTRCTL_RASEMU &&
1054         type != CTRDATA_TYPE_INDIRECT_CALL &&
1055         type != CTRDATA_TYPE_DIRECT_CALL &&
1056         type != CTRDATA_TYPE_RETURN &&
1057         type != CTRDATA_TYPE_CO_ROUTINE_SWAP) {
1058         return;
1059     }
1060 
1061     if (type == CTRDATA_TYPE_EXCEPTION || type == CTRDATA_TYPE_INTERRUPT) {
1062         /* Case 2 for traps. */
1063         if (!(src_ctrl & src_mask)) {
1064             src = 0;
1065         } else if (!(tgt_ctrl & tgt_mask)) {
1066             /* Check if target priv-mode has allowed external trap recording. */
1067             if (!riscv_ctr_check_xte(env, src_priv, src_virt)) {
1068                 return;
1069             }
1070 
1071             ext_trap = true;
1072             dst = 0;
1073         }
1074     } else if (type == CTRDATA_TYPE_EXCEP_INT_RET) {
1075         /*
1076          * Case 3 for trap returns.  Trap returns from inhibited mode are not
1077          * recorded.
1078          */
1079         if (!(src_ctrl & src_mask)) {
1080             return;
1081         }
1082 
1083         /* Case 2 for trap returns. */
1084         if (!(tgt_ctrl & tgt_mask)) {
1085             dst = 0;
1086         }
1087     }
1088 
1089     /* Ignore filters in case of RASEMU mode or External trap. */
1090     if (!(tgt_ctrl & XCTRCTL_RASEMU) && !ext_trap) {
1091         /*
1092          * Check if the specific type is inhibited. Not taken branch filter is
1093          * an enable bit and needs to be checked separatly.
1094          */
1095         bool check = tgt_ctrl & BIT_ULL(type + XCTRCTL_INH_START);
1096         if ((type == CTRDATA_TYPE_NONTAKEN_BRANCH && !check) ||
1097             (type != CTRDATA_TYPE_NONTAKEN_BRANCH && check)) {
1098             return;
1099         }
1100     }
1101 
1102     head = get_field(env->sctrstatus, SCTRSTATUS_WRPTR_MASK);
1103 
1104     depth = 16 << get_field(env->sctrdepth, SCTRDEPTH_MASK);
1105     if (tgt_ctrl & XCTRCTL_RASEMU && type == CTRDATA_TYPE_RETURN) {
1106         head = (head - 1) & (depth - 1);
1107 
1108         env->ctr_src[head] &= ~CTRSOURCE_VALID;
1109         env->sctrstatus =
1110             set_field(env->sctrstatus, SCTRSTATUS_WRPTR_MASK, head);
1111         return;
1112     }
1113 
1114     /* In case of Co-routine SWAP we overwrite latest entry. */
1115     if (tgt_ctrl & XCTRCTL_RASEMU && type == CTRDATA_TYPE_CO_ROUTINE_SWAP) {
1116         head = (head - 1) & (depth - 1);
1117     }
1118 
1119     env->ctr_src[head] = src | CTRSOURCE_VALID;
1120     env->ctr_dst[head] = dst & ~CTRTARGET_MISP;
1121     env->ctr_data[head] = set_field(0, CTRDATA_TYPE_MASK, type);
1122 
1123     head = (head + 1) & (depth - 1);
1124 
1125     env->sctrstatus = set_field(env->sctrstatus, SCTRSTATUS_WRPTR_MASK, head);
1126 }
1127 
1128 void riscv_cpu_set_mode(CPURISCVState *env, target_ulong newpriv, bool virt_en)
1129 {
1130     g_assert(newpriv <= PRV_M && newpriv != PRV_RESERVED);
1131 
1132     if (newpriv != env->priv || env->virt_enabled != virt_en) {
1133         if (icount_enabled()) {
1134             riscv_itrigger_update_priv(env);
1135         }
1136 
1137         riscv_pmu_update_fixed_ctrs(env, newpriv, virt_en);
1138     }
1139 
1140     /* tlb_flush is unnecessary as mode is contained in mmu_idx */
1141     env->priv = newpriv;
1142     env->xl = cpu_recompute_xl(env);
1143 
1144     /*
1145      * Clear the load reservation - otherwise a reservation placed in one
1146      * context/process can be used by another, resulting in an SC succeeding
1147      * incorrectly. Version 2.2 of the ISA specification explicitly requires
1148      * this behaviour, while later revisions say that the kernel "should" use
1149      * an SC instruction to force the yielding of a load reservation on a
1150      * preemptive context switch. As a result, do both.
1151      */
1152     env->load_res = -1;
1153 
1154     if (riscv_has_ext(env, RVH)) {
1155         /* Flush the TLB on all virt mode changes. */
1156         if (env->virt_enabled != virt_en) {
1157             tlb_flush(env_cpu(env));
1158         }
1159 
1160         env->virt_enabled = virt_en;
1161         if (virt_en) {
1162             /*
1163              * The guest external interrupts from an interrupt controller are
1164              * delivered only when the Guest/VM is running (i.e. V=1). This
1165              * means any guest external interrupt which is triggered while the
1166              * Guest/VM is not running (i.e. V=0) will be missed on QEMU
1167              * resulting in guest with sluggish response to serial console
1168              * input and other I/O events.
1169              *
1170              * To solve this, we check and inject interrupt after setting V=1.
1171              */
1172             riscv_cpu_update_mip(env, 0, 0);
1173         }
1174     }
1175 }
1176 
1177 /*
1178  * get_physical_address_pmp - check PMP permission for this physical address
1179  *
1180  * Match the PMP region and check permission for this physical address and it's
1181  * TLB page. Returns 0 if the permission checking was successful
1182  *
1183  * @env: CPURISCVState
1184  * @prot: The returned protection attributes
1185  * @addr: The physical address to be checked permission
1186  * @access_type: The type of MMU access
1187  * @mode: Indicates current privilege level.
1188  */
1189 static int get_physical_address_pmp(CPURISCVState *env, int *prot, hwaddr addr,
1190                                     int size, MMUAccessType access_type,
1191                                     int mode)
1192 {
1193     pmp_priv_t pmp_priv;
1194     bool pmp_has_privs;
1195 
1196     if (!riscv_cpu_cfg(env)->pmp) {
1197         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
1198         return TRANSLATE_SUCCESS;
1199     }
1200 
1201     pmp_has_privs = pmp_hart_has_privs(env, addr, size, 1 << access_type,
1202                                        &pmp_priv, mode);
1203     if (!pmp_has_privs) {
1204         *prot = 0;
1205         return TRANSLATE_PMP_FAIL;
1206     }
1207 
1208     *prot = pmp_priv_to_page_prot(pmp_priv);
1209 
1210     return TRANSLATE_SUCCESS;
1211 }
1212 
1213 /* Returns 'true' if a svukte address check is needed */
1214 static bool do_svukte_check(CPURISCVState *env, bool first_stage,
1215                              int mode, bool virt)
1216 {
1217     /* Svukte extension depends on Sv39. */
1218     if (!(env_archcpu(env)->cfg.ext_svukte ||
1219         !first_stage ||
1220         VM_1_10_SV39 != get_field(env->satp, SATP64_MODE))) {
1221         return false;
1222     }
1223 
1224     /*
1225      * Check hstatus.HUKTE if the effective mode is switched to VU-mode by
1226      * executing HLV/HLVX/HSV in U-mode.
1227      * For other cases, check senvcfg.UKTE.
1228      */
1229     if (env->priv == PRV_U && !env->virt_enabled && virt) {
1230         if (!get_field(env->hstatus, HSTATUS_HUKTE)) {
1231             return false;
1232         }
1233     } else if (!get_field(env->senvcfg, SENVCFG_UKTE)) {
1234         return false;
1235     }
1236 
1237     /*
1238      * Svukte extension is qualified only in U or VU-mode.
1239      *
1240      * Effective mode can be switched to U or VU-mode by:
1241      *   - M-mode + mstatus.MPRV=1 + mstatus.MPP=U-mode.
1242      *   - Execute HLV/HLVX/HSV from HS-mode + hstatus.SPVP=0.
1243      *   - U-mode.
1244      *   - VU-mode.
1245      *   - Execute HLV/HLVX/HSV from U-mode + hstatus.HU=1.
1246      */
1247     if (mode != PRV_U) {
1248         return false;
1249     }
1250 
1251     return true;
1252 }
1253 
1254 static bool check_svukte_addr(CPURISCVState *env, vaddr addr)
1255 {
1256     /* svukte extension excludes RV32 */
1257     uint32_t sxlen = 32 * riscv_cpu_sxl(env);
1258     uint64_t high_bit = addr & (1UL << (sxlen - 1));
1259     return !high_bit;
1260 }
1261 
1262 /*
1263  * get_physical_address - get the physical address for this virtual address
1264  *
1265  * Do a page table walk to obtain the physical address corresponding to a
1266  * virtual address. Returns 0 if the translation was successful
1267  *
1268  * Adapted from Spike's mmu_t::translate and mmu_t::walk
1269  *
1270  * @env: CPURISCVState
1271  * @physical: This will be set to the calculated physical address
1272  * @prot: The returned protection attributes
1273  * @addr: The virtual address or guest physical address to be translated
1274  * @fault_pte_addr: If not NULL, this will be set to fault pte address
1275  *                  when a error occurs on pte address translation.
1276  *                  This will already be shifted to match htval.
1277  * @access_type: The type of MMU access
1278  * @mmu_idx: Indicates current privilege level
1279  * @first_stage: Are we in first stage translation?
1280  *               Second stage is used for hypervisor guest translation
1281  * @two_stage: Are we going to perform two stage translation
1282  * @is_debug: Is this access from a debugger or the monitor?
1283  */
1284 static int get_physical_address(CPURISCVState *env, hwaddr *physical,
1285                                 int *ret_prot, vaddr addr,
1286                                 target_ulong *fault_pte_addr,
1287                                 int access_type, int mmu_idx,
1288                                 bool first_stage, bool two_stage,
1289                                 bool is_debug, bool is_probe)
1290 {
1291     /*
1292      * NOTE: the env->pc value visible here will not be
1293      * correct, but the value visible to the exception handler
1294      * (riscv_cpu_do_interrupt) is correct
1295      */
1296     MemTxResult res;
1297     MemTxAttrs attrs = MEMTXATTRS_UNSPECIFIED;
1298     int mode = mmuidx_priv(mmu_idx);
1299     bool virt = mmuidx_2stage(mmu_idx);
1300     bool use_background = false;
1301     hwaddr ppn;
1302     int napot_bits = 0;
1303     target_ulong napot_mask;
1304     bool is_sstack_idx = ((mmu_idx & MMU_IDX_SS_WRITE) == MMU_IDX_SS_WRITE);
1305     bool sstack_page = false;
1306 
1307     if (do_svukte_check(env, first_stage, mode, virt) &&
1308         !check_svukte_addr(env, addr)) {
1309         return TRANSLATE_FAIL;
1310     }
1311 
1312     /*
1313      * Check if we should use the background registers for the two
1314      * stage translation. We don't need to check if we actually need
1315      * two stage translation as that happened before this function
1316      * was called. Background registers will be used if the guest has
1317      * forced a two stage translation to be on (in HS or M mode).
1318      */
1319     if (!env->virt_enabled && two_stage) {
1320         use_background = true;
1321     }
1322 
1323     if (mode == PRV_M || !riscv_cpu_cfg(env)->mmu) {
1324         *physical = addr;
1325         *ret_prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
1326         return TRANSLATE_SUCCESS;
1327     }
1328 
1329     *ret_prot = 0;
1330 
1331     hwaddr base;
1332     int levels, ptidxbits, ptesize, vm, widened;
1333 
1334     if (first_stage == true) {
1335         if (use_background) {
1336             if (riscv_cpu_mxl(env) == MXL_RV32) {
1337                 base = (hwaddr)get_field(env->vsatp, SATP32_PPN) << PGSHIFT;
1338                 vm = get_field(env->vsatp, SATP32_MODE);
1339             } else {
1340                 base = (hwaddr)get_field(env->vsatp, SATP64_PPN) << PGSHIFT;
1341                 vm = get_field(env->vsatp, SATP64_MODE);
1342             }
1343         } else {
1344             if (riscv_cpu_mxl(env) == MXL_RV32) {
1345                 base = (hwaddr)get_field(env->satp, SATP32_PPN) << PGSHIFT;
1346                 vm = get_field(env->satp, SATP32_MODE);
1347             } else {
1348                 base = (hwaddr)get_field(env->satp, SATP64_PPN) << PGSHIFT;
1349                 vm = get_field(env->satp, SATP64_MODE);
1350             }
1351         }
1352         widened = 0;
1353     } else {
1354         if (riscv_cpu_mxl(env) == MXL_RV32) {
1355             base = (hwaddr)get_field(env->hgatp, SATP32_PPN) << PGSHIFT;
1356             vm = get_field(env->hgatp, SATP32_MODE);
1357         } else {
1358             base = (hwaddr)get_field(env->hgatp, SATP64_PPN) << PGSHIFT;
1359             vm = get_field(env->hgatp, SATP64_MODE);
1360         }
1361         widened = 2;
1362     }
1363 
1364     switch (vm) {
1365     case VM_1_10_SV32:
1366       levels = 2; ptidxbits = 10; ptesize = 4; break;
1367     case VM_1_10_SV39:
1368       levels = 3; ptidxbits = 9; ptesize = 8; break;
1369     case VM_1_10_SV48:
1370       levels = 4; ptidxbits = 9; ptesize = 8; break;
1371     case VM_1_10_SV57:
1372       levels = 5; ptidxbits = 9; ptesize = 8; break;
1373     case VM_1_10_MBARE:
1374         *physical = addr;
1375         *ret_prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
1376         return TRANSLATE_SUCCESS;
1377     default:
1378       g_assert_not_reached();
1379     }
1380 
1381     CPUState *cs = env_cpu(env);
1382     int va_bits = PGSHIFT + levels * ptidxbits + widened;
1383     int sxlen = 16 << riscv_cpu_sxl(env);
1384     int sxlen_bytes = sxlen / 8;
1385 
1386     if (first_stage == true) {
1387         target_ulong mask, masked_msbs;
1388 
1389         if (sxlen > (va_bits - 1)) {
1390             mask = (1L << (sxlen - (va_bits - 1))) - 1;
1391         } else {
1392             mask = 0;
1393         }
1394         masked_msbs = (addr >> (va_bits - 1)) & mask;
1395 
1396         if (masked_msbs != 0 && masked_msbs != mask) {
1397             return TRANSLATE_FAIL;
1398         }
1399     } else {
1400         if (vm != VM_1_10_SV32 && addr >> va_bits != 0) {
1401             return TRANSLATE_FAIL;
1402         }
1403     }
1404 
1405     bool pbmte = env->menvcfg & MENVCFG_PBMTE;
1406     bool svade = riscv_cpu_cfg(env)->ext_svade;
1407     bool svadu = riscv_cpu_cfg(env)->ext_svadu;
1408     bool adue = svadu ? env->menvcfg & MENVCFG_ADUE : !svade;
1409 
1410     if (first_stage && two_stage && env->virt_enabled) {
1411         pbmte = pbmte && (env->henvcfg & HENVCFG_PBMTE);
1412         adue = adue && (env->henvcfg & HENVCFG_ADUE);
1413     }
1414 
1415     int ptshift = (levels - 1) * ptidxbits;
1416     target_ulong pte;
1417     hwaddr pte_addr;
1418     int i;
1419 
1420  restart:
1421     for (i = 0; i < levels; i++, ptshift -= ptidxbits) {
1422         target_ulong idx;
1423         if (i == 0) {
1424             idx = (addr >> (PGSHIFT + ptshift)) &
1425                            ((1 << (ptidxbits + widened)) - 1);
1426         } else {
1427             idx = (addr >> (PGSHIFT + ptshift)) &
1428                            ((1 << ptidxbits) - 1);
1429         }
1430 
1431         /* check that physical address of PTE is legal */
1432 
1433         if (two_stage && first_stage) {
1434             int vbase_prot;
1435             hwaddr vbase;
1436 
1437             /* Do the second stage translation on the base PTE address. */
1438             int vbase_ret = get_physical_address(env, &vbase, &vbase_prot,
1439                                                  base, NULL, MMU_DATA_LOAD,
1440                                                  MMUIdx_U, false, true,
1441                                                  is_debug, false);
1442 
1443             if (vbase_ret != TRANSLATE_SUCCESS) {
1444                 if (fault_pte_addr) {
1445                     *fault_pte_addr = (base + idx * ptesize) >> 2;
1446                 }
1447                 return TRANSLATE_G_STAGE_FAIL;
1448             }
1449 
1450             pte_addr = vbase + idx * ptesize;
1451         } else {
1452             pte_addr = base + idx * ptesize;
1453         }
1454 
1455         int pmp_prot;
1456         int pmp_ret = get_physical_address_pmp(env, &pmp_prot, pte_addr,
1457                                                sxlen_bytes,
1458                                                MMU_DATA_LOAD, PRV_S);
1459         if (pmp_ret != TRANSLATE_SUCCESS) {
1460             return TRANSLATE_PMP_FAIL;
1461         }
1462 
1463         if (riscv_cpu_mxl(env) == MXL_RV32) {
1464             pte = address_space_ldl(cs->as, pte_addr, attrs, &res);
1465         } else {
1466             pte = address_space_ldq(cs->as, pte_addr, attrs, &res);
1467         }
1468 
1469         if (res != MEMTX_OK) {
1470             return TRANSLATE_FAIL;
1471         }
1472 
1473         if (riscv_cpu_sxl(env) == MXL_RV32) {
1474             ppn = pte >> PTE_PPN_SHIFT;
1475         } else {
1476             if (pte & PTE_RESERVED) {
1477                 qemu_log_mask(LOG_GUEST_ERROR, "%s: reserved bits set in PTE: "
1478                               "addr: 0x%" HWADDR_PRIx " pte: 0x" TARGET_FMT_lx "\n",
1479                               __func__, pte_addr, pte);
1480                 return TRANSLATE_FAIL;
1481             }
1482 
1483             if (!pbmte && (pte & PTE_PBMT)) {
1484                 /* Reserved without Svpbmt. */
1485                 qemu_log_mask(LOG_GUEST_ERROR, "%s: PBMT bits set in PTE, "
1486                               "and Svpbmt extension is disabled: "
1487                               "addr: 0x%" HWADDR_PRIx " pte: 0x" TARGET_FMT_lx "\n",
1488                               __func__, pte_addr, pte);
1489                 return TRANSLATE_FAIL;
1490             }
1491 
1492             if (!riscv_cpu_cfg(env)->ext_svnapot && (pte & PTE_N)) {
1493                 /* Reserved without Svnapot extension */
1494                 qemu_log_mask(LOG_GUEST_ERROR, "%s: N bit set in PTE, "
1495                               "and Svnapot extension is disabled: "
1496                               "addr: 0x%" HWADDR_PRIx " pte: 0x" TARGET_FMT_lx "\n",
1497                               __func__, pte_addr, pte);
1498                 return TRANSLATE_FAIL;
1499             }
1500 
1501             ppn = (pte & (target_ulong)PTE_PPN_MASK) >> PTE_PPN_SHIFT;
1502         }
1503 
1504         if (!(pte & PTE_V)) {
1505             /* Invalid PTE */
1506             return TRANSLATE_FAIL;
1507         }
1508 
1509         if (pte & (PTE_R | PTE_W | PTE_X)) {
1510             goto leaf;
1511         }
1512 
1513         if (pte & (PTE_D | PTE_A | PTE_U | PTE_ATTR)) {
1514             /* D, A, and U bits are reserved in non-leaf/inner PTEs */
1515             qemu_log_mask(LOG_GUEST_ERROR, "%s: D, A, or U bits set in non-leaf PTE: "
1516                           "addr: 0x%" HWADDR_PRIx " pte: 0x" TARGET_FMT_lx "\n",
1517                           __func__, pte_addr, pte);
1518             return TRANSLATE_FAIL;
1519         }
1520         /* Inner PTE, continue walking */
1521         base = ppn << PGSHIFT;
1522     }
1523 
1524     /* No leaf pte at any translation level. */
1525     return TRANSLATE_FAIL;
1526 
1527  leaf:
1528     if (ppn & ((1ULL << ptshift) - 1)) {
1529         /* Misaligned PPN */
1530         qemu_log_mask(LOG_GUEST_ERROR, "%s: PPN bits in PTE is misaligned: "
1531                       "addr: 0x%" HWADDR_PRIx " pte: 0x" TARGET_FMT_lx "\n",
1532                       __func__, pte_addr, pte);
1533         return TRANSLATE_FAIL;
1534     }
1535     if (!pbmte && (pte & PTE_PBMT)) {
1536         /* Reserved without Svpbmt. */
1537         qemu_log_mask(LOG_GUEST_ERROR, "%s: PBMT bits set in PTE, "
1538                       "and Svpbmt extension is disabled: "
1539                       "addr: 0x%" HWADDR_PRIx " pte: 0x" TARGET_FMT_lx "\n",
1540                       __func__, pte_addr, pte);
1541         return TRANSLATE_FAIL;
1542     }
1543 
1544     target_ulong rwx = pte & (PTE_R | PTE_W | PTE_X);
1545     /* Check for reserved combinations of RWX flags. */
1546     switch (rwx) {
1547     case PTE_W | PTE_X:
1548         return TRANSLATE_FAIL;
1549     case PTE_W:
1550         /* if bcfi enabled, PTE_W is not reserved and shadow stack page */
1551         if (cpu_get_bcfien(env) && first_stage) {
1552             sstack_page = true;
1553             /*
1554              * if ss index, read and write allowed. else if not a probe
1555              * then only read allowed
1556              */
1557             rwx = is_sstack_idx ? (PTE_R | PTE_W) : (is_probe ? 0 :  PTE_R);
1558             break;
1559         }
1560         return TRANSLATE_FAIL;
1561     case PTE_R:
1562         /*
1563          * no matter what's the `access_type`, shadow stack access to readonly
1564          * memory are always store page faults. During unwind, loads will be
1565          * promoted as store fault.
1566          */
1567         if (is_sstack_idx) {
1568             return TRANSLATE_FAIL;
1569         }
1570         break;
1571     }
1572 
1573     int prot = 0;
1574     if (rwx & PTE_R) {
1575         prot |= PAGE_READ;
1576     }
1577     if (rwx & PTE_W) {
1578         prot |= PAGE_WRITE;
1579     }
1580     if (rwx & PTE_X) {
1581         bool mxr = false;
1582 
1583         /*
1584          * Use mstatus for first stage or for the second stage without
1585          * virt_enabled (MPRV+MPV)
1586          */
1587         if (first_stage || !env->virt_enabled) {
1588             mxr = get_field(env->mstatus, MSTATUS_MXR);
1589         }
1590 
1591         /* MPRV+MPV case, check VSSTATUS */
1592         if (first_stage && two_stage && !env->virt_enabled) {
1593             mxr |= get_field(env->vsstatus, MSTATUS_MXR);
1594         }
1595 
1596         /*
1597          * Setting MXR at HS-level overrides both VS-stage and G-stage
1598          * execute-only permissions
1599          */
1600         if (env->virt_enabled) {
1601             mxr |= get_field(env->mstatus_hs, MSTATUS_MXR);
1602         }
1603 
1604         if (mxr) {
1605             prot |= PAGE_READ;
1606         }
1607         prot |= PAGE_EXEC;
1608     }
1609 
1610     if (pte & PTE_U) {
1611         if (mode != PRV_U) {
1612             if (!mmuidx_sum(mmu_idx)) {
1613                 return TRANSLATE_FAIL;
1614             }
1615             /* SUM allows only read+write, not execute. */
1616             prot &= PAGE_READ | PAGE_WRITE;
1617         }
1618     } else if (mode != PRV_S) {
1619         /* Supervisor PTE flags when not S mode */
1620         return TRANSLATE_FAIL;
1621     }
1622 
1623     if (!((prot >> access_type) & 1)) {
1624         /*
1625          * Access check failed, access check failures for shadow stack are
1626          * access faults.
1627          */
1628         return sstack_page ? TRANSLATE_PMP_FAIL : TRANSLATE_FAIL;
1629     }
1630 
1631     target_ulong updated_pte = pte;
1632 
1633     /*
1634      * If ADUE is enabled, set accessed and dirty bits.
1635      * Otherwise raise an exception if necessary.
1636      */
1637     if (adue) {
1638         updated_pte |= PTE_A | (access_type == MMU_DATA_STORE ? PTE_D : 0);
1639     } else if (!(pte & PTE_A) ||
1640                (access_type == MMU_DATA_STORE && !(pte & PTE_D))) {
1641         return TRANSLATE_FAIL;
1642     }
1643 
1644     /* Page table updates need to be atomic with MTTCG enabled */
1645     if (updated_pte != pte && !is_debug) {
1646         if (!adue) {
1647             return TRANSLATE_FAIL;
1648         }
1649 
1650         /*
1651          * - if accessed or dirty bits need updating, and the PTE is
1652          *   in RAM, then we do so atomically with a compare and swap.
1653          * - if the PTE is in IO space or ROM, then it can't be updated
1654          *   and we return TRANSLATE_FAIL.
1655          * - if the PTE changed by the time we went to update it, then
1656          *   it is no longer valid and we must re-walk the page table.
1657          */
1658         MemoryRegion *mr;
1659         hwaddr l = sxlen_bytes, addr1;
1660         mr = address_space_translate(cs->as, pte_addr, &addr1, &l,
1661                                      false, MEMTXATTRS_UNSPECIFIED);
1662         if (memory_region_is_ram(mr)) {
1663             target_ulong *pte_pa = qemu_map_ram_ptr(mr->ram_block, addr1);
1664             target_ulong old_pte;
1665             if (riscv_cpu_sxl(env) == MXL_RV32) {
1666                 old_pte = qatomic_cmpxchg((uint32_t *)pte_pa, pte, updated_pte);
1667             } else {
1668                 old_pte = qatomic_cmpxchg(pte_pa, pte, updated_pte);
1669             }
1670             if (old_pte != pte) {
1671                 goto restart;
1672             }
1673             pte = updated_pte;
1674         } else {
1675             /*
1676              * Misconfigured PTE in ROM (AD bits are not preset) or
1677              * PTE is in IO space and can't be updated atomically.
1678              */
1679             return TRANSLATE_FAIL;
1680         }
1681     }
1682 
1683     /* For superpage mappings, make a fake leaf PTE for the TLB's benefit. */
1684     target_ulong vpn = addr >> PGSHIFT;
1685 
1686     if (riscv_cpu_cfg(env)->ext_svnapot && (pte & PTE_N)) {
1687         napot_bits = ctzl(ppn) + 1;
1688         if ((i != (levels - 1)) || (napot_bits != 4)) {
1689             return TRANSLATE_FAIL;
1690         }
1691     }
1692 
1693     napot_mask = (1 << napot_bits) - 1;
1694     *physical = (((ppn & ~napot_mask) | (vpn & napot_mask) |
1695                   (vpn & (((target_ulong)1 << ptshift) - 1))
1696                  ) << PGSHIFT) | (addr & ~TARGET_PAGE_MASK);
1697 
1698     /*
1699      * Remove write permission unless this is a store, or the page is
1700      * already dirty, so that we TLB miss on later writes to update
1701      * the dirty bit.
1702      */
1703     if (access_type != MMU_DATA_STORE && !(pte & PTE_D)) {
1704         prot &= ~PAGE_WRITE;
1705     }
1706     *ret_prot = prot;
1707 
1708     return TRANSLATE_SUCCESS;
1709 }
1710 
1711 static void raise_mmu_exception(CPURISCVState *env, target_ulong address,
1712                                 MMUAccessType access_type, bool pmp_violation,
1713                                 bool first_stage, bool two_stage,
1714                                 bool two_stage_indirect)
1715 {
1716     CPUState *cs = env_cpu(env);
1717 
1718     switch (access_type) {
1719     case MMU_INST_FETCH:
1720         if (pmp_violation) {
1721             cs->exception_index = RISCV_EXCP_INST_ACCESS_FAULT;
1722         } else if (env->virt_enabled && !first_stage) {
1723             cs->exception_index = RISCV_EXCP_INST_GUEST_PAGE_FAULT;
1724         } else {
1725             cs->exception_index = RISCV_EXCP_INST_PAGE_FAULT;
1726         }
1727         break;
1728     case MMU_DATA_LOAD:
1729         if (pmp_violation) {
1730             cs->exception_index = RISCV_EXCP_LOAD_ACCESS_FAULT;
1731         } else if (two_stage && !first_stage) {
1732             cs->exception_index = RISCV_EXCP_LOAD_GUEST_ACCESS_FAULT;
1733         } else {
1734             cs->exception_index = RISCV_EXCP_LOAD_PAGE_FAULT;
1735         }
1736         break;
1737     case MMU_DATA_STORE:
1738         if (pmp_violation) {
1739             cs->exception_index = RISCV_EXCP_STORE_AMO_ACCESS_FAULT;
1740         } else if (two_stage && !first_stage) {
1741             cs->exception_index = RISCV_EXCP_STORE_GUEST_AMO_ACCESS_FAULT;
1742         } else {
1743             cs->exception_index = RISCV_EXCP_STORE_PAGE_FAULT;
1744         }
1745         break;
1746     default:
1747         g_assert_not_reached();
1748     }
1749     env->badaddr = address;
1750     env->two_stage_lookup = two_stage;
1751     env->two_stage_indirect_lookup = two_stage_indirect;
1752 }
1753 
1754 hwaddr riscv_cpu_get_phys_page_debug(CPUState *cs, vaddr addr)
1755 {
1756     RISCVCPU *cpu = RISCV_CPU(cs);
1757     CPURISCVState *env = &cpu->env;
1758     hwaddr phys_addr;
1759     int prot;
1760     int mmu_idx = riscv_env_mmu_index(&cpu->env, false);
1761 
1762     if (get_physical_address(env, &phys_addr, &prot, addr, NULL, 0, mmu_idx,
1763                              true, env->virt_enabled, true, false)) {
1764         return -1;
1765     }
1766 
1767     if (env->virt_enabled) {
1768         if (get_physical_address(env, &phys_addr, &prot, phys_addr, NULL,
1769                                  0, MMUIdx_U, false, true, true, false)) {
1770             return -1;
1771         }
1772     }
1773 
1774     return phys_addr & TARGET_PAGE_MASK;
1775 }
1776 
1777 void riscv_cpu_do_transaction_failed(CPUState *cs, hwaddr physaddr,
1778                                      vaddr addr, unsigned size,
1779                                      MMUAccessType access_type,
1780                                      int mmu_idx, MemTxAttrs attrs,
1781                                      MemTxResult response, uintptr_t retaddr)
1782 {
1783     RISCVCPU *cpu = RISCV_CPU(cs);
1784     CPURISCVState *env = &cpu->env;
1785 
1786     if (access_type == MMU_DATA_STORE) {
1787         cs->exception_index = RISCV_EXCP_STORE_AMO_ACCESS_FAULT;
1788     } else if (access_type == MMU_DATA_LOAD) {
1789         cs->exception_index = RISCV_EXCP_LOAD_ACCESS_FAULT;
1790     } else {
1791         cs->exception_index = RISCV_EXCP_INST_ACCESS_FAULT;
1792     }
1793 
1794     env->badaddr = addr;
1795     env->two_stage_lookup = mmuidx_2stage(mmu_idx);
1796     env->two_stage_indirect_lookup = false;
1797     cpu_loop_exit_restore(cs, retaddr);
1798 }
1799 
1800 void riscv_cpu_do_unaligned_access(CPUState *cs, vaddr addr,
1801                                    MMUAccessType access_type, int mmu_idx,
1802                                    uintptr_t retaddr)
1803 {
1804     RISCVCPU *cpu = RISCV_CPU(cs);
1805     CPURISCVState *env = &cpu->env;
1806     switch (access_type) {
1807     case MMU_INST_FETCH:
1808         cs->exception_index = RISCV_EXCP_INST_ADDR_MIS;
1809         break;
1810     case MMU_DATA_LOAD:
1811         cs->exception_index = RISCV_EXCP_LOAD_ADDR_MIS;
1812         /* shadow stack mis aligned accesses are access faults */
1813         if (mmu_idx & MMU_IDX_SS_WRITE) {
1814             cs->exception_index = RISCV_EXCP_LOAD_ACCESS_FAULT;
1815         }
1816         break;
1817     case MMU_DATA_STORE:
1818         cs->exception_index = RISCV_EXCP_STORE_AMO_ADDR_MIS;
1819         /* shadow stack mis aligned accesses are access faults */
1820         if (mmu_idx & MMU_IDX_SS_WRITE) {
1821             cs->exception_index = RISCV_EXCP_STORE_AMO_ACCESS_FAULT;
1822         }
1823         break;
1824     default:
1825         g_assert_not_reached();
1826     }
1827     env->badaddr = addr;
1828     env->two_stage_lookup = mmuidx_2stage(mmu_idx);
1829     env->two_stage_indirect_lookup = false;
1830     cpu_loop_exit_restore(cs, retaddr);
1831 }
1832 
1833 
1834 static void pmu_tlb_fill_incr_ctr(RISCVCPU *cpu, MMUAccessType access_type)
1835 {
1836     enum riscv_pmu_event_idx pmu_event_type;
1837 
1838     switch (access_type) {
1839     case MMU_INST_FETCH:
1840         pmu_event_type = RISCV_PMU_EVENT_CACHE_ITLB_PREFETCH_MISS;
1841         break;
1842     case MMU_DATA_LOAD:
1843         pmu_event_type = RISCV_PMU_EVENT_CACHE_DTLB_READ_MISS;
1844         break;
1845     case MMU_DATA_STORE:
1846         pmu_event_type = RISCV_PMU_EVENT_CACHE_DTLB_WRITE_MISS;
1847         break;
1848     default:
1849         return;
1850     }
1851 
1852     riscv_pmu_incr_ctr(cpu, pmu_event_type);
1853 }
1854 
1855 bool riscv_cpu_tlb_fill(CPUState *cs, vaddr address, int size,
1856                         MMUAccessType access_type, int mmu_idx,
1857                         bool probe, uintptr_t retaddr)
1858 {
1859     RISCVCPU *cpu = RISCV_CPU(cs);
1860     CPURISCVState *env = &cpu->env;
1861     vaddr im_address;
1862     hwaddr pa = 0;
1863     int prot, prot2, prot_pmp;
1864     bool pmp_violation = false;
1865     bool first_stage_error = true;
1866     bool two_stage_lookup = mmuidx_2stage(mmu_idx);
1867     bool two_stage_indirect_error = false;
1868     int ret = TRANSLATE_FAIL;
1869     int mode = mmuidx_priv(mmu_idx);
1870     /* default TLB page size */
1871     hwaddr tlb_size = TARGET_PAGE_SIZE;
1872 
1873     env->guest_phys_fault_addr = 0;
1874 
1875     qemu_log_mask(CPU_LOG_MMU, "%s ad %" VADDR_PRIx " rw %d mmu_idx %d\n",
1876                   __func__, address, access_type, mmu_idx);
1877 
1878     pmu_tlb_fill_incr_ctr(cpu, access_type);
1879     if (two_stage_lookup) {
1880         /* Two stage lookup */
1881         ret = get_physical_address(env, &pa, &prot, address,
1882                                    &env->guest_phys_fault_addr, access_type,
1883                                    mmu_idx, true, true, false, probe);
1884 
1885         /*
1886          * A G-stage exception may be triggered during two state lookup.
1887          * And the env->guest_phys_fault_addr has already been set in
1888          * get_physical_address().
1889          */
1890         if (ret == TRANSLATE_G_STAGE_FAIL) {
1891             first_stage_error = false;
1892             two_stage_indirect_error = true;
1893         }
1894 
1895         qemu_log_mask(CPU_LOG_MMU,
1896                       "%s 1st-stage address=%" VADDR_PRIx " ret %d physical "
1897                       HWADDR_FMT_plx " prot %d\n",
1898                       __func__, address, ret, pa, prot);
1899 
1900         if (ret == TRANSLATE_SUCCESS) {
1901             /* Second stage lookup */
1902             im_address = pa;
1903 
1904             ret = get_physical_address(env, &pa, &prot2, im_address, NULL,
1905                                        access_type, MMUIdx_U, false, true,
1906                                        false, probe);
1907 
1908             qemu_log_mask(CPU_LOG_MMU,
1909                           "%s 2nd-stage address=%" VADDR_PRIx
1910                           " ret %d physical "
1911                           HWADDR_FMT_plx " prot %d\n",
1912                           __func__, im_address, ret, pa, prot2);
1913 
1914             prot &= prot2;
1915 
1916             if (ret == TRANSLATE_SUCCESS) {
1917                 ret = get_physical_address_pmp(env, &prot_pmp, pa,
1918                                                size, access_type, mode);
1919                 tlb_size = pmp_get_tlb_size(env, pa);
1920 
1921                 qemu_log_mask(CPU_LOG_MMU,
1922                               "%s PMP address=" HWADDR_FMT_plx " ret %d prot"
1923                               " %d tlb_size %" HWADDR_PRIu "\n",
1924                               __func__, pa, ret, prot_pmp, tlb_size);
1925 
1926                 prot &= prot_pmp;
1927             } else {
1928                 /*
1929                  * Guest physical address translation failed, this is a HS
1930                  * level exception
1931                  */
1932                 first_stage_error = false;
1933                 if (ret != TRANSLATE_PMP_FAIL) {
1934                     env->guest_phys_fault_addr = (im_address |
1935                                                   (address &
1936                                                    (TARGET_PAGE_SIZE - 1))) >> 2;
1937                 }
1938             }
1939         }
1940     } else {
1941         /* Single stage lookup */
1942         ret = get_physical_address(env, &pa, &prot, address, NULL,
1943                                    access_type, mmu_idx, true, false, false,
1944                                    probe);
1945 
1946         qemu_log_mask(CPU_LOG_MMU,
1947                       "%s address=%" VADDR_PRIx " ret %d physical "
1948                       HWADDR_FMT_plx " prot %d\n",
1949                       __func__, address, ret, pa, prot);
1950 
1951         if (ret == TRANSLATE_SUCCESS) {
1952             ret = get_physical_address_pmp(env, &prot_pmp, pa,
1953                                            size, access_type, mode);
1954             tlb_size = pmp_get_tlb_size(env, pa);
1955 
1956             qemu_log_mask(CPU_LOG_MMU,
1957                           "%s PMP address=" HWADDR_FMT_plx " ret %d prot"
1958                           " %d tlb_size %" HWADDR_PRIu "\n",
1959                           __func__, pa, ret, prot_pmp, tlb_size);
1960 
1961             prot &= prot_pmp;
1962         }
1963     }
1964 
1965     if (ret == TRANSLATE_PMP_FAIL) {
1966         pmp_violation = true;
1967     }
1968 
1969     if (ret == TRANSLATE_SUCCESS) {
1970         tlb_set_page(cs, address & ~(tlb_size - 1), pa & ~(tlb_size - 1),
1971                      prot, mmu_idx, tlb_size);
1972         return true;
1973     } else if (probe) {
1974         return false;
1975     } else {
1976         int wp_access = 0;
1977 
1978         if (access_type == MMU_DATA_LOAD) {
1979             wp_access |= BP_MEM_READ;
1980         } else if (access_type == MMU_DATA_STORE) {
1981             wp_access |= BP_MEM_WRITE;
1982         }
1983 
1984         /*
1985          * If a watchpoint isn't found for 'addr' this will
1986          * be a no-op and we'll resume the mmu_exception path.
1987          * Otherwise we'll throw a debug exception and execution
1988          * will continue elsewhere.
1989          */
1990         cpu_check_watchpoint(cs, address, size, MEMTXATTRS_UNSPECIFIED,
1991                              wp_access, retaddr);
1992 
1993         raise_mmu_exception(env, address, access_type, pmp_violation,
1994                             first_stage_error, two_stage_lookup,
1995                             two_stage_indirect_error);
1996         cpu_loop_exit_restore(cs, retaddr);
1997     }
1998 
1999     return true;
2000 }
2001 
2002 static target_ulong riscv_transformed_insn(CPURISCVState *env,
2003                                            target_ulong insn,
2004                                            target_ulong taddr)
2005 {
2006     target_ulong xinsn = 0;
2007     target_ulong access_rs1 = 0, access_imm = 0, access_size = 0;
2008 
2009     /*
2010      * Only Quadrant 0 and Quadrant 2 of RVC instruction space need to
2011      * be uncompressed. The Quadrant 1 of RVC instruction space need
2012      * not be transformed because these instructions won't generate
2013      * any load/store trap.
2014      */
2015 
2016     if ((insn & 0x3) != 0x3) {
2017         /* Transform 16bit instruction into 32bit instruction */
2018         switch (GET_C_OP(insn)) {
2019         case OPC_RISC_C_OP_QUAD0: /* Quadrant 0 */
2020             switch (GET_C_FUNC(insn)) {
2021             case OPC_RISC_C_FUNC_FLD_LQ:
2022                 if (riscv_cpu_xlen(env) != 128) { /* C.FLD (RV32/64) */
2023                     xinsn = OPC_RISC_FLD;
2024                     xinsn = SET_RD(xinsn, GET_C_RS2S(insn));
2025                     access_rs1 = GET_C_RS1S(insn);
2026                     access_imm = GET_C_LD_IMM(insn);
2027                     access_size = 8;
2028                 }
2029                 break;
2030             case OPC_RISC_C_FUNC_LW: /* C.LW */
2031                 xinsn = OPC_RISC_LW;
2032                 xinsn = SET_RD(xinsn, GET_C_RS2S(insn));
2033                 access_rs1 = GET_C_RS1S(insn);
2034                 access_imm = GET_C_LW_IMM(insn);
2035                 access_size = 4;
2036                 break;
2037             case OPC_RISC_C_FUNC_FLW_LD:
2038                 if (riscv_cpu_xlen(env) == 32) { /* C.FLW (RV32) */
2039                     xinsn = OPC_RISC_FLW;
2040                     xinsn = SET_RD(xinsn, GET_C_RS2S(insn));
2041                     access_rs1 = GET_C_RS1S(insn);
2042                     access_imm = GET_C_LW_IMM(insn);
2043                     access_size = 4;
2044                 } else { /* C.LD (RV64/RV128) */
2045                     xinsn = OPC_RISC_LD;
2046                     xinsn = SET_RD(xinsn, GET_C_RS2S(insn));
2047                     access_rs1 = GET_C_RS1S(insn);
2048                     access_imm = GET_C_LD_IMM(insn);
2049                     access_size = 8;
2050                 }
2051                 break;
2052             case OPC_RISC_C_FUNC_FSD_SQ:
2053                 if (riscv_cpu_xlen(env) != 128) { /* C.FSD (RV32/64) */
2054                     xinsn = OPC_RISC_FSD;
2055                     xinsn = SET_RS2(xinsn, GET_C_RS2S(insn));
2056                     access_rs1 = GET_C_RS1S(insn);
2057                     access_imm = GET_C_SD_IMM(insn);
2058                     access_size = 8;
2059                 }
2060                 break;
2061             case OPC_RISC_C_FUNC_SW: /* C.SW */
2062                 xinsn = OPC_RISC_SW;
2063                 xinsn = SET_RS2(xinsn, GET_C_RS2S(insn));
2064                 access_rs1 = GET_C_RS1S(insn);
2065                 access_imm = GET_C_SW_IMM(insn);
2066                 access_size = 4;
2067                 break;
2068             case OPC_RISC_C_FUNC_FSW_SD:
2069                 if (riscv_cpu_xlen(env) == 32) { /* C.FSW (RV32) */
2070                     xinsn = OPC_RISC_FSW;
2071                     xinsn = SET_RS2(xinsn, GET_C_RS2S(insn));
2072                     access_rs1 = GET_C_RS1S(insn);
2073                     access_imm = GET_C_SW_IMM(insn);
2074                     access_size = 4;
2075                 } else { /* C.SD (RV64/RV128) */
2076                     xinsn = OPC_RISC_SD;
2077                     xinsn = SET_RS2(xinsn, GET_C_RS2S(insn));
2078                     access_rs1 = GET_C_RS1S(insn);
2079                     access_imm = GET_C_SD_IMM(insn);
2080                     access_size = 8;
2081                 }
2082                 break;
2083             default:
2084                 break;
2085             }
2086             break;
2087         case OPC_RISC_C_OP_QUAD2: /* Quadrant 2 */
2088             switch (GET_C_FUNC(insn)) {
2089             case OPC_RISC_C_FUNC_FLDSP_LQSP:
2090                 if (riscv_cpu_xlen(env) != 128) { /* C.FLDSP (RV32/64) */
2091                     xinsn = OPC_RISC_FLD;
2092                     xinsn = SET_RD(xinsn, GET_C_RD(insn));
2093                     access_rs1 = 2;
2094                     access_imm = GET_C_LDSP_IMM(insn);
2095                     access_size = 8;
2096                 }
2097                 break;
2098             case OPC_RISC_C_FUNC_LWSP: /* C.LWSP */
2099                 xinsn = OPC_RISC_LW;
2100                 xinsn = SET_RD(xinsn, GET_C_RD(insn));
2101                 access_rs1 = 2;
2102                 access_imm = GET_C_LWSP_IMM(insn);
2103                 access_size = 4;
2104                 break;
2105             case OPC_RISC_C_FUNC_FLWSP_LDSP:
2106                 if (riscv_cpu_xlen(env) == 32) { /* C.FLWSP (RV32) */
2107                     xinsn = OPC_RISC_FLW;
2108                     xinsn = SET_RD(xinsn, GET_C_RD(insn));
2109                     access_rs1 = 2;
2110                     access_imm = GET_C_LWSP_IMM(insn);
2111                     access_size = 4;
2112                 } else { /* C.LDSP (RV64/RV128) */
2113                     xinsn = OPC_RISC_LD;
2114                     xinsn = SET_RD(xinsn, GET_C_RD(insn));
2115                     access_rs1 = 2;
2116                     access_imm = GET_C_LDSP_IMM(insn);
2117                     access_size = 8;
2118                 }
2119                 break;
2120             case OPC_RISC_C_FUNC_FSDSP_SQSP:
2121                 if (riscv_cpu_xlen(env) != 128) { /* C.FSDSP (RV32/64) */
2122                     xinsn = OPC_RISC_FSD;
2123                     xinsn = SET_RS2(xinsn, GET_C_RS2(insn));
2124                     access_rs1 = 2;
2125                     access_imm = GET_C_SDSP_IMM(insn);
2126                     access_size = 8;
2127                 }
2128                 break;
2129             case OPC_RISC_C_FUNC_SWSP: /* C.SWSP */
2130                 xinsn = OPC_RISC_SW;
2131                 xinsn = SET_RS2(xinsn, GET_C_RS2(insn));
2132                 access_rs1 = 2;
2133                 access_imm = GET_C_SWSP_IMM(insn);
2134                 access_size = 4;
2135                 break;
2136             case 7:
2137                 if (riscv_cpu_xlen(env) == 32) { /* C.FSWSP (RV32) */
2138                     xinsn = OPC_RISC_FSW;
2139                     xinsn = SET_RS2(xinsn, GET_C_RS2(insn));
2140                     access_rs1 = 2;
2141                     access_imm = GET_C_SWSP_IMM(insn);
2142                     access_size = 4;
2143                 } else { /* C.SDSP (RV64/RV128) */
2144                     xinsn = OPC_RISC_SD;
2145                     xinsn = SET_RS2(xinsn, GET_C_RS2(insn));
2146                     access_rs1 = 2;
2147                     access_imm = GET_C_SDSP_IMM(insn);
2148                     access_size = 8;
2149                 }
2150                 break;
2151             default:
2152                 break;
2153             }
2154             break;
2155         default:
2156             break;
2157         }
2158 
2159         /*
2160          * Clear Bit1 of transformed instruction to indicate that
2161          * original insruction was a 16bit instruction
2162          */
2163         xinsn &= ~((target_ulong)0x2);
2164     } else {
2165         /* Transform 32bit (or wider) instructions */
2166         switch (MASK_OP_MAJOR(insn)) {
2167         case OPC_RISC_ATOMIC:
2168             xinsn = insn;
2169             access_rs1 = GET_RS1(insn);
2170             access_size = 1 << GET_FUNCT3(insn);
2171             break;
2172         case OPC_RISC_LOAD:
2173         case OPC_RISC_FP_LOAD:
2174             xinsn = SET_I_IMM(insn, 0);
2175             access_rs1 = GET_RS1(insn);
2176             access_imm = GET_IMM(insn);
2177             access_size = 1 << GET_FUNCT3(insn);
2178             break;
2179         case OPC_RISC_STORE:
2180         case OPC_RISC_FP_STORE:
2181             xinsn = SET_S_IMM(insn, 0);
2182             access_rs1 = GET_RS1(insn);
2183             access_imm = GET_STORE_IMM(insn);
2184             access_size = 1 << GET_FUNCT3(insn);
2185             break;
2186         case OPC_RISC_SYSTEM:
2187             if (MASK_OP_SYSTEM(insn) == OPC_RISC_HLVHSV) {
2188                 xinsn = insn;
2189                 access_rs1 = GET_RS1(insn);
2190                 access_size = 1 << ((GET_FUNCT7(insn) >> 1) & 0x3);
2191                 access_size = 1 << access_size;
2192             }
2193             break;
2194         default:
2195             break;
2196         }
2197     }
2198 
2199     if (access_size) {
2200         xinsn = SET_RS1(xinsn, (taddr - (env->gpr[access_rs1] + access_imm)) &
2201                                (access_size - 1));
2202     }
2203 
2204     return xinsn;
2205 }
2206 
2207 static target_ulong promote_load_fault(target_ulong orig_cause)
2208 {
2209     switch (orig_cause) {
2210     case RISCV_EXCP_LOAD_GUEST_ACCESS_FAULT:
2211         return RISCV_EXCP_STORE_GUEST_AMO_ACCESS_FAULT;
2212 
2213     case RISCV_EXCP_LOAD_ACCESS_FAULT:
2214         return RISCV_EXCP_STORE_AMO_ACCESS_FAULT;
2215 
2216     case RISCV_EXCP_LOAD_PAGE_FAULT:
2217         return RISCV_EXCP_STORE_PAGE_FAULT;
2218     }
2219 
2220     /* if no promotion, return original cause */
2221     return orig_cause;
2222 }
2223 
2224 static void riscv_do_nmi(CPURISCVState *env, target_ulong cause, bool virt)
2225 {
2226     env->mnstatus = set_field(env->mnstatus, MNSTATUS_NMIE, false);
2227     env->mnstatus = set_field(env->mnstatus, MNSTATUS_MNPV, virt);
2228     env->mnstatus = set_field(env->mnstatus, MNSTATUS_MNPP, env->priv);
2229     env->mncause = cause;
2230     env->mnepc = env->pc;
2231     env->pc = env->rnmi_irqvec;
2232 
2233     if (cpu_get_fcfien(env)) {
2234         env->mnstatus = set_field(env->mnstatus, MNSTATUS_MNPELP, env->elp);
2235     }
2236 
2237     /* Trapping to M mode, virt is disabled */
2238     riscv_cpu_set_mode(env, PRV_M, false);
2239 }
2240 
2241 /*
2242  * Handle Traps
2243  *
2244  * Adapted from Spike's processor_t::take_trap.
2245  *
2246  */
2247 void riscv_cpu_do_interrupt(CPUState *cs)
2248 {
2249     RISCVCPU *cpu = RISCV_CPU(cs);
2250     CPURISCVState *env = &cpu->env;
2251     bool virt = env->virt_enabled;
2252     bool write_gva = false;
2253     bool always_storeamo = (env->excp_uw2 & RISCV_UW2_ALWAYS_STORE_AMO);
2254     bool vsmode_exc;
2255     uint64_t s;
2256     int mode;
2257 
2258     /*
2259      * cs->exception is 32-bits wide unlike mcause which is XLEN-bits wide
2260      * so we mask off the MSB and separate into trap type and cause.
2261      */
2262     bool async = !!(cs->exception_index & RISCV_EXCP_INT_FLAG);
2263     target_ulong cause = cs->exception_index & RISCV_EXCP_INT_MASK;
2264     uint64_t deleg = async ? env->mideleg : env->medeleg;
2265     bool s_injected = env->mvip & (1ULL << cause) & env->mvien &&
2266         !(env->mip & (1ULL << cause));
2267     bool vs_injected = env->hvip & (1ULL << cause) & env->hvien &&
2268         !(env->mip & (1ULL << cause));
2269     bool smode_double_trap = false;
2270     uint64_t hdeleg = async ? env->hideleg : env->hedeleg;
2271     const bool prev_virt = env->virt_enabled;
2272     const target_ulong prev_priv = env->priv;
2273     target_ulong tval = 0;
2274     target_ulong tinst = 0;
2275     target_ulong htval = 0;
2276     target_ulong mtval2 = 0;
2277     target_ulong src;
2278     int sxlen = 0;
2279     int mxlen = 16 << riscv_cpu_mxl(env);
2280     bool nnmi_excep = false;
2281 
2282     if (cpu->cfg.ext_smrnmi && env->rnmip && async) {
2283         riscv_do_nmi(env, cause | ((target_ulong)1U << (mxlen - 1)),
2284                      env->virt_enabled);
2285         return;
2286     }
2287 
2288     if (!async) {
2289         /* set tval to badaddr for traps with address information */
2290         switch (cause) {
2291 #ifdef CONFIG_TCG
2292         case RISCV_EXCP_SEMIHOST:
2293             do_common_semihosting(cs);
2294             env->pc += 4;
2295             return;
2296 #endif
2297         case RISCV_EXCP_LOAD_GUEST_ACCESS_FAULT:
2298         case RISCV_EXCP_STORE_GUEST_AMO_ACCESS_FAULT:
2299         case RISCV_EXCP_LOAD_ADDR_MIS:
2300         case RISCV_EXCP_STORE_AMO_ADDR_MIS:
2301         case RISCV_EXCP_LOAD_ACCESS_FAULT:
2302         case RISCV_EXCP_STORE_AMO_ACCESS_FAULT:
2303         case RISCV_EXCP_LOAD_PAGE_FAULT:
2304         case RISCV_EXCP_STORE_PAGE_FAULT:
2305             if (always_storeamo) {
2306                 cause = promote_load_fault(cause);
2307             }
2308             write_gva = env->two_stage_lookup;
2309             tval = env->badaddr;
2310             if (env->two_stage_indirect_lookup) {
2311                 /*
2312                  * special pseudoinstruction for G-stage fault taken while
2313                  * doing VS-stage page table walk.
2314                  */
2315                 tinst = (riscv_cpu_xlen(env) == 32) ? 0x00002000 : 0x00003000;
2316             } else {
2317                 /*
2318                  * The "Addr. Offset" field in transformed instruction is
2319                  * non-zero only for misaligned access.
2320                  */
2321                 tinst = riscv_transformed_insn(env, env->bins, tval);
2322             }
2323             break;
2324         case RISCV_EXCP_INST_GUEST_PAGE_FAULT:
2325         case RISCV_EXCP_INST_ADDR_MIS:
2326         case RISCV_EXCP_INST_ACCESS_FAULT:
2327         case RISCV_EXCP_INST_PAGE_FAULT:
2328             write_gva = env->two_stage_lookup;
2329             tval = env->badaddr;
2330             if (env->two_stage_indirect_lookup) {
2331                 /*
2332                  * special pseudoinstruction for G-stage fault taken while
2333                  * doing VS-stage page table walk.
2334                  */
2335                 tinst = (riscv_cpu_xlen(env) == 32) ? 0x00002000 : 0x00003000;
2336             }
2337             break;
2338         case RISCV_EXCP_ILLEGAL_INST:
2339         case RISCV_EXCP_VIRT_INSTRUCTION_FAULT:
2340             tval = env->bins;
2341             break;
2342         case RISCV_EXCP_BREAKPOINT:
2343             tval = env->badaddr;
2344             if (cs->watchpoint_hit) {
2345                 tval = cs->watchpoint_hit->hitaddr;
2346                 cs->watchpoint_hit = NULL;
2347             }
2348             break;
2349         case RISCV_EXCP_SW_CHECK:
2350             tval = env->sw_check_code;
2351             break;
2352         default:
2353             break;
2354         }
2355         /* ecall is dispatched as one cause so translate based on mode */
2356         if (cause == RISCV_EXCP_U_ECALL) {
2357             assert(env->priv <= 3);
2358 
2359             if (env->priv == PRV_M) {
2360                 cause = RISCV_EXCP_M_ECALL;
2361             } else if (env->priv == PRV_S && env->virt_enabled) {
2362                 cause = RISCV_EXCP_VS_ECALL;
2363             } else if (env->priv == PRV_S && !env->virt_enabled) {
2364                 cause = RISCV_EXCP_S_ECALL;
2365             } else if (env->priv == PRV_U) {
2366                 cause = RISCV_EXCP_U_ECALL;
2367             }
2368         }
2369     }
2370 
2371     trace_riscv_trap(env->mhartid, async, cause, env->pc, tval,
2372                      riscv_cpu_get_trap_name(cause, async));
2373 
2374     qemu_log_mask(CPU_LOG_INT,
2375                   "%s: hart:"TARGET_FMT_ld", async:%d, cause:"TARGET_FMT_lx", "
2376                   "epc:0x"TARGET_FMT_lx", tval:0x"TARGET_FMT_lx", desc=%s\n",
2377                   __func__, env->mhartid, async, cause, env->pc, tval,
2378                   riscv_cpu_get_trap_name(cause, async));
2379 
2380     mode = env->priv <= PRV_S && cause < 64 &&
2381         (((deleg >> cause) & 1) || s_injected || vs_injected) ? PRV_S : PRV_M;
2382 
2383     vsmode_exc = env->virt_enabled && cause < 64 &&
2384         (((hdeleg >> cause) & 1) || vs_injected);
2385 
2386     /*
2387      * Check double trap condition only if already in S-mode and targeting
2388      * S-mode
2389      */
2390     if (cpu->cfg.ext_ssdbltrp && env->priv == PRV_S && mode == PRV_S) {
2391         bool dte = (env->menvcfg & MENVCFG_DTE) != 0;
2392         bool sdt = (env->mstatus & MSTATUS_SDT) != 0;
2393         /* In VS or HS */
2394         if (riscv_has_ext(env, RVH)) {
2395             if (vsmode_exc) {
2396                 /* VS -> VS, use henvcfg instead of menvcfg*/
2397                 dte = (env->henvcfg & HENVCFG_DTE) != 0;
2398             } else if (env->virt_enabled) {
2399                 /* VS -> HS, use mstatus_hs */
2400                 sdt = (env->mstatus_hs & MSTATUS_SDT) != 0;
2401             }
2402         }
2403         smode_double_trap = dte && sdt;
2404         if (smode_double_trap) {
2405             mode = PRV_M;
2406         }
2407     }
2408 
2409     if (mode == PRV_S) {
2410         /* handle the trap in S-mode */
2411         /* save elp status */
2412         if (cpu_get_fcfien(env)) {
2413             env->mstatus = set_field(env->mstatus, MSTATUS_SPELP, env->elp);
2414         }
2415 
2416         if (riscv_has_ext(env, RVH)) {
2417             if (vsmode_exc) {
2418                 /* Trap to VS mode */
2419                 /*
2420                  * See if we need to adjust cause. Yes if its VS mode interrupt
2421                  * no if hypervisor has delegated one of hs mode's interrupt
2422                  */
2423                 if (async && (cause == IRQ_VS_TIMER || cause == IRQ_VS_SOFT ||
2424                               cause == IRQ_VS_EXT)) {
2425                     cause = cause - 1;
2426                 }
2427                 write_gva = false;
2428             } else if (env->virt_enabled) {
2429                 /* Trap into HS mode, from virt */
2430                 riscv_cpu_swap_hypervisor_regs(env);
2431                 env->hstatus = set_field(env->hstatus, HSTATUS_SPVP,
2432                                          env->priv);
2433                 env->hstatus = set_field(env->hstatus, HSTATUS_SPV, true);
2434 
2435                 htval = env->guest_phys_fault_addr;
2436 
2437                 virt = false;
2438             } else {
2439                 /* Trap into HS mode */
2440                 env->hstatus = set_field(env->hstatus, HSTATUS_SPV, false);
2441                 htval = env->guest_phys_fault_addr;
2442             }
2443             env->hstatus = set_field(env->hstatus, HSTATUS_GVA, write_gva);
2444         }
2445 
2446         s = env->mstatus;
2447         s = set_field(s, MSTATUS_SPIE, get_field(s, MSTATUS_SIE));
2448         s = set_field(s, MSTATUS_SPP, env->priv);
2449         s = set_field(s, MSTATUS_SIE, 0);
2450         if (riscv_env_smode_dbltrp_enabled(env, virt)) {
2451             s = set_field(s, MSTATUS_SDT, 1);
2452         }
2453         env->mstatus = s;
2454         sxlen = 16 << riscv_cpu_sxl(env);
2455         env->scause = cause | ((target_ulong)async << (sxlen - 1));
2456         env->sepc = env->pc;
2457         env->stval = tval;
2458         env->htval = htval;
2459         env->htinst = tinst;
2460         env->pc = (env->stvec >> 2 << 2) +
2461                   ((async && (env->stvec & 3) == 1) ? cause * 4 : 0);
2462         riscv_cpu_set_mode(env, PRV_S, virt);
2463 
2464         src = env->sepc;
2465     } else {
2466         /*
2467          * If the hart encounters an exception while executing in M-mode
2468          * with the mnstatus.NMIE bit clear, the exception is an RNMI exception.
2469          */
2470         nnmi_excep = cpu->cfg.ext_smrnmi &&
2471                      !get_field(env->mnstatus, MNSTATUS_NMIE) &&
2472                      !async;
2473 
2474         /* handle the trap in M-mode */
2475         /* save elp status */
2476         if (cpu_get_fcfien(env)) {
2477             if (nnmi_excep) {
2478                 env->mnstatus = set_field(env->mnstatus, MNSTATUS_MNPELP,
2479                                           env->elp);
2480             } else {
2481                 env->mstatus = set_field(env->mstatus, MSTATUS_MPELP, env->elp);
2482             }
2483         }
2484 
2485         if (riscv_has_ext(env, RVH)) {
2486             if (env->virt_enabled) {
2487                 riscv_cpu_swap_hypervisor_regs(env);
2488             }
2489             env->mstatus = set_field(env->mstatus, MSTATUS_MPV,
2490                                      env->virt_enabled);
2491             if (env->virt_enabled && tval) {
2492                 env->mstatus = set_field(env->mstatus, MSTATUS_GVA, 1);
2493             }
2494 
2495             mtval2 = env->guest_phys_fault_addr;
2496 
2497             /* Trapping to M mode, virt is disabled */
2498             virt = false;
2499         }
2500         /*
2501          * If the hart encounters an exception while executing in M-mode,
2502          * with the mnstatus.NMIE bit clear, the program counter is set to
2503          * the RNMI exception trap handler address.
2504          */
2505         nnmi_excep = cpu->cfg.ext_smrnmi &&
2506                      !get_field(env->mnstatus, MNSTATUS_NMIE) &&
2507                      !async;
2508 
2509         s = env->mstatus;
2510         s = set_field(s, MSTATUS_MPIE, get_field(s, MSTATUS_MIE));
2511         s = set_field(s, MSTATUS_MPP, env->priv);
2512         s = set_field(s, MSTATUS_MIE, 0);
2513         if (cpu->cfg.ext_smdbltrp) {
2514             if (env->mstatus & MSTATUS_MDT) {
2515                 assert(env->priv == PRV_M);
2516                 if (!cpu->cfg.ext_smrnmi || nnmi_excep) {
2517                     cpu_abort(CPU(cpu), "M-mode double trap\n");
2518                 } else {
2519                     riscv_do_nmi(env, cause, false);
2520                     return;
2521                 }
2522             }
2523 
2524             s = set_field(s, MSTATUS_MDT, 1);
2525         }
2526         env->mstatus = s;
2527         env->mcause = cause | ((target_ulong)async << (mxlen - 1));
2528         if (smode_double_trap) {
2529             env->mtval2 = env->mcause;
2530             env->mcause = RISCV_EXCP_DOUBLE_TRAP;
2531         } else {
2532             env->mtval2 = mtval2;
2533         }
2534         env->mepc = env->pc;
2535         env->mtval = tval;
2536         env->mtinst = tinst;
2537 
2538         /*
2539          * For RNMI exception, program counter is set to the RNMI exception
2540          * trap handler address.
2541          */
2542         if (nnmi_excep) {
2543             env->pc = env->rnmi_excpvec;
2544         } else {
2545             env->pc = (env->mtvec >> 2 << 2) +
2546                       ((async && (env->mtvec & 3) == 1) ? cause * 4 : 0);
2547         }
2548         riscv_cpu_set_mode(env, PRV_M, virt);
2549         src = env->mepc;
2550     }
2551 
2552     if (riscv_cpu_cfg(env)->ext_smctr || riscv_cpu_cfg(env)->ext_ssctr) {
2553         if (async && cause == IRQ_PMU_OVF) {
2554             riscv_ctr_freeze(env, XCTRCTL_LCOFIFRZ, virt);
2555         } else if (!async && cause == RISCV_EXCP_BREAKPOINT) {
2556             riscv_ctr_freeze(env, XCTRCTL_BPFRZ, virt);
2557         }
2558 
2559         riscv_ctr_add_entry(env, src, env->pc,
2560                         async ? CTRDATA_TYPE_INTERRUPT : CTRDATA_TYPE_EXCEPTION,
2561                         prev_priv, prev_virt);
2562     }
2563 
2564     /*
2565      * Interrupt/exception/trap delivery is asynchronous event and as per
2566      * zicfilp spec CPU should clear up the ELP state. No harm in clearing
2567      * unconditionally.
2568      */
2569     env->elp = false;
2570 
2571     /*
2572      * NOTE: it is not necessary to yield load reservations here. It is only
2573      * necessary for an SC from "another hart" to cause a load reservation
2574      * to be yielded. Refer to the memory consistency model section of the
2575      * RISC-V ISA Specification.
2576      */
2577 
2578     env->two_stage_lookup = false;
2579     env->two_stage_indirect_lookup = false;
2580 }
2581 
2582 #endif /* !CONFIG_USER_ONLY */
2583