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