xref: /qemu/target/riscv/cpu_helper.c (revision 6b8f40c61bbfef1abe77eeb9c716ec642927c12c)
1 /*
2  * RISC-V CPU helpers for qemu.
3  *
4  * Copyright (c) 2016-2017 Sagar Karandikar, sagark@eecs.berkeley.edu
5  * Copyright (c) 2017-2018 SiFive, Inc.
6  *
7  * This program is free software; you can redistribute it and/or modify it
8  * under the terms and conditions of the GNU General Public License,
9  * version 2 or later, as published by the Free Software Foundation.
10  *
11  * This program is distributed in the hope it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
14  * more details.
15  *
16  * You should have received a copy of the GNU General Public License along with
17  * this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19 
20 #include "qemu/osdep.h"
21 #include "qemu/log.h"
22 #include "qemu/main-loop.h"
23 #include "cpu.h"
24 #include "internals.h"
25 #include "pmu.h"
26 #include "exec/exec-all.h"
27 #include "exec/page-protection.h"
28 #include "instmap.h"
29 #include "tcg/tcg-op.h"
30 #include "trace.h"
31 #include "semihosting/common-semi.h"
32 #include "system/cpu-timers.h"
33 #include "cpu_bits.h"
34 #include "debug.h"
35 #include "tcg/oversized-guest.h"
36 #include "pmp.h"
37 
38 int riscv_env_mmu_index(CPURISCVState *env, bool ifetch)
39 {
40 #ifdef CONFIG_USER_ONLY
41     return 0;
42 #else
43     bool virt = env->virt_enabled;
44     int mode = env->priv;
45 
46     /* All priv -> mmu_idx mapping are here */
47     if (!ifetch) {
48         uint64_t status = env->mstatus;
49 
50         if (mode == PRV_M && get_field(status, MSTATUS_MPRV)) {
51             mode = get_field(env->mstatus, MSTATUS_MPP);
52             virt = get_field(env->mstatus, MSTATUS_MPV) &&
53                    (mode != PRV_M);
54             if (virt) {
55                 status = env->vsstatus;
56             }
57         }
58         if (mode == PRV_S && get_field(status, MSTATUS_SUM)) {
59             mode = MMUIdx_S_SUM;
60         }
61     }
62 
63     return mode | (virt ? MMU_2STAGE_BIT : 0);
64 #endif
65 }
66 
67 bool cpu_get_fcfien(CPURISCVState *env)
68 {
69     /* no cfi extension, return false */
70     if (!env_archcpu(env)->cfg.ext_zicfilp) {
71         return false;
72     }
73 
74     switch (env->priv) {
75     case PRV_U:
76         if (riscv_has_ext(env, RVS)) {
77             return env->senvcfg & SENVCFG_LPE;
78         }
79         return env->menvcfg & MENVCFG_LPE;
80 #ifndef CONFIG_USER_ONLY
81     case PRV_S:
82         if (env->virt_enabled) {
83             return env->henvcfg & HENVCFG_LPE;
84         }
85         return env->menvcfg & MENVCFG_LPE;
86     case PRV_M:
87         return env->mseccfg & MSECCFG_MLPE;
88 #endif
89     default:
90         g_assert_not_reached();
91     }
92 }
93 
94 bool cpu_get_bcfien(CPURISCVState *env)
95 {
96     /* no cfi extension, return false */
97     if (!env_archcpu(env)->cfg.ext_zicfiss) {
98         return false;
99     }
100 
101     switch (env->priv) {
102     case PRV_U:
103         /*
104          * If S is not implemented then shadow stack for U can't be turned on
105          * It is checked in `riscv_cpu_validate_set_extensions`, so no need to
106          * check here or assert here
107          */
108         return env->senvcfg & SENVCFG_SSE;
109 #ifndef CONFIG_USER_ONLY
110     case PRV_S:
111         if (env->virt_enabled) {
112             return env->henvcfg & HENVCFG_SSE;
113         }
114         return env->menvcfg & MENVCFG_SSE;
115     case PRV_M: /* M-mode shadow stack is always off */
116         return false;
117 #endif
118     default:
119         g_assert_not_reached();
120     }
121 }
122 
123 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 #if !TCG_OVERSIZED_GUEST
1171 restart:
1172 #endif
1173     for (i = 0; i < levels; i++, ptshift -= ptidxbits) {
1174         target_ulong idx;
1175         if (i == 0) {
1176             idx = (addr >> (PGSHIFT + ptshift)) &
1177                            ((1 << (ptidxbits + widened)) - 1);
1178         } else {
1179             idx = (addr >> (PGSHIFT + ptshift)) &
1180                            ((1 << ptidxbits) - 1);
1181         }
1182 
1183         /* check that physical address of PTE is legal */
1184 
1185         if (two_stage && first_stage) {
1186             int vbase_prot;
1187             hwaddr vbase;
1188 
1189             /* Do the second stage translation on the base PTE address. */
1190             int vbase_ret = get_physical_address(env, &vbase, &vbase_prot,
1191                                                  base, NULL, MMU_DATA_LOAD,
1192                                                  MMUIdx_U, false, true,
1193                                                  is_debug, false);
1194 
1195             if (vbase_ret != TRANSLATE_SUCCESS) {
1196                 if (fault_pte_addr) {
1197                     *fault_pte_addr = (base + idx * ptesize) >> 2;
1198                 }
1199                 return TRANSLATE_G_STAGE_FAIL;
1200             }
1201 
1202             pte_addr = vbase + idx * ptesize;
1203         } else {
1204             pte_addr = base + idx * ptesize;
1205         }
1206 
1207         int pmp_prot;
1208         int pmp_ret = get_physical_address_pmp(env, &pmp_prot, pte_addr,
1209                                                sxlen_bytes,
1210                                                MMU_DATA_LOAD, PRV_S);
1211         if (pmp_ret != TRANSLATE_SUCCESS) {
1212             return TRANSLATE_PMP_FAIL;
1213         }
1214 
1215         if (riscv_cpu_mxl(env) == MXL_RV32) {
1216             pte = address_space_ldl(cs->as, pte_addr, attrs, &res);
1217         } else {
1218             pte = address_space_ldq(cs->as, pte_addr, attrs, &res);
1219         }
1220 
1221         if (res != MEMTX_OK) {
1222             return TRANSLATE_FAIL;
1223         }
1224 
1225         if (riscv_cpu_sxl(env) == MXL_RV32) {
1226             ppn = pte >> PTE_PPN_SHIFT;
1227         } else {
1228             if (pte & PTE_RESERVED) {
1229                 return TRANSLATE_FAIL;
1230             }
1231 
1232             if (!pbmte && (pte & PTE_PBMT)) {
1233                 return TRANSLATE_FAIL;
1234             }
1235 
1236             if (!riscv_cpu_cfg(env)->ext_svnapot && (pte & PTE_N)) {
1237                 return TRANSLATE_FAIL;
1238             }
1239 
1240             ppn = (pte & (target_ulong)PTE_PPN_MASK) >> PTE_PPN_SHIFT;
1241         }
1242 
1243         if (!(pte & PTE_V)) {
1244             /* Invalid PTE */
1245             return TRANSLATE_FAIL;
1246         }
1247         if (pte & (PTE_R | PTE_W | PTE_X)) {
1248             goto leaf;
1249         }
1250 
1251         /* Inner PTE, continue walking */
1252         if (pte & (PTE_D | PTE_A | PTE_U | PTE_ATTR)) {
1253             return TRANSLATE_FAIL;
1254         }
1255         base = ppn << PGSHIFT;
1256     }
1257 
1258     /* No leaf pte at any translation level. */
1259     return TRANSLATE_FAIL;
1260 
1261  leaf:
1262     if (ppn & ((1ULL << ptshift) - 1)) {
1263         /* Misaligned PPN */
1264         return TRANSLATE_FAIL;
1265     }
1266     if (!pbmte && (pte & PTE_PBMT)) {
1267         /* Reserved without Svpbmt. */
1268         return TRANSLATE_FAIL;
1269     }
1270 
1271     target_ulong rwx = pte & (PTE_R | PTE_W | PTE_X);
1272     /* Check for reserved combinations of RWX flags. */
1273     switch (rwx) {
1274     case PTE_W | PTE_X:
1275         return TRANSLATE_FAIL;
1276     case PTE_W:
1277         /* if bcfi enabled, PTE_W is not reserved and shadow stack page */
1278         if (cpu_get_bcfien(env) && first_stage) {
1279             sstack_page = true;
1280             /*
1281              * if ss index, read and write allowed. else if not a probe
1282              * then only read allowed
1283              */
1284             rwx = is_sstack_idx ? (PTE_R | PTE_W) : (is_probe ? 0 :  PTE_R);
1285             break;
1286         }
1287         return TRANSLATE_FAIL;
1288     case PTE_R:
1289         /*
1290          * no matter what's the `access_type`, shadow stack access to readonly
1291          * memory are always store page faults. During unwind, loads will be
1292          * promoted as store fault.
1293          */
1294         if (is_sstack_idx) {
1295             return TRANSLATE_FAIL;
1296         }
1297         break;
1298     }
1299 
1300     int prot = 0;
1301     if (rwx & PTE_R) {
1302         prot |= PAGE_READ;
1303     }
1304     if (rwx & PTE_W) {
1305         prot |= PAGE_WRITE;
1306     }
1307     if (rwx & PTE_X) {
1308         bool mxr = false;
1309 
1310         /*
1311          * Use mstatus for first stage or for the second stage without
1312          * virt_enabled (MPRV+MPV)
1313          */
1314         if (first_stage || !env->virt_enabled) {
1315             mxr = get_field(env->mstatus, MSTATUS_MXR);
1316         }
1317 
1318         /* MPRV+MPV case, check VSSTATUS */
1319         if (first_stage && two_stage && !env->virt_enabled) {
1320             mxr |= get_field(env->vsstatus, MSTATUS_MXR);
1321         }
1322 
1323         /*
1324          * Setting MXR at HS-level overrides both VS-stage and G-stage
1325          * execute-only permissions
1326          */
1327         if (env->virt_enabled) {
1328             mxr |= get_field(env->mstatus_hs, MSTATUS_MXR);
1329         }
1330 
1331         if (mxr) {
1332             prot |= PAGE_READ;
1333         }
1334         prot |= PAGE_EXEC;
1335     }
1336 
1337     if (pte & PTE_U) {
1338         if (mode != PRV_U) {
1339             if (!mmuidx_sum(mmu_idx)) {
1340                 return TRANSLATE_FAIL;
1341             }
1342             /* SUM allows only read+write, not execute. */
1343             prot &= PAGE_READ | PAGE_WRITE;
1344         }
1345     } else if (mode != PRV_S) {
1346         /* Supervisor PTE flags when not S mode */
1347         return TRANSLATE_FAIL;
1348     }
1349 
1350     if (!((prot >> access_type) & 1)) {
1351         /*
1352          * Access check failed, access check failures for shadow stack are
1353          * access faults.
1354          */
1355         return sstack_page ? TRANSLATE_PMP_FAIL : TRANSLATE_FAIL;
1356     }
1357 
1358     target_ulong updated_pte = pte;
1359 
1360     /*
1361      * If ADUE is enabled, set accessed and dirty bits.
1362      * Otherwise raise an exception if necessary.
1363      */
1364     if (adue) {
1365         updated_pte |= PTE_A | (access_type == MMU_DATA_STORE ? PTE_D : 0);
1366     } else if (!(pte & PTE_A) ||
1367                (access_type == MMU_DATA_STORE && !(pte & PTE_D))) {
1368         return TRANSLATE_FAIL;
1369     }
1370 
1371     /* Page table updates need to be atomic with MTTCG enabled */
1372     if (updated_pte != pte && !is_debug) {
1373         if (!adue) {
1374             return TRANSLATE_FAIL;
1375         }
1376 
1377         /*
1378          * - if accessed or dirty bits need updating, and the PTE is
1379          *   in RAM, then we do so atomically with a compare and swap.
1380          * - if the PTE is in IO space or ROM, then it can't be updated
1381          *   and we return TRANSLATE_FAIL.
1382          * - if the PTE changed by the time we went to update it, then
1383          *   it is no longer valid and we must re-walk the page table.
1384          */
1385         MemoryRegion *mr;
1386         hwaddr l = sxlen_bytes, addr1;
1387         mr = address_space_translate(cs->as, pte_addr, &addr1, &l,
1388                                      false, MEMTXATTRS_UNSPECIFIED);
1389         if (memory_region_is_ram(mr)) {
1390             target_ulong *pte_pa = qemu_map_ram_ptr(mr->ram_block, addr1);
1391 #if TCG_OVERSIZED_GUEST
1392             /*
1393              * MTTCG is not enabled on oversized TCG guests so
1394              * page table updates do not need to be atomic
1395              */
1396             *pte_pa = pte = updated_pte;
1397 #else
1398             target_ulong old_pte;
1399             if (riscv_cpu_sxl(env) == MXL_RV32) {
1400                 old_pte = qatomic_cmpxchg((uint32_t *)pte_pa, pte, updated_pte);
1401             } else {
1402                 old_pte = qatomic_cmpxchg(pte_pa, pte, updated_pte);
1403             }
1404             if (old_pte != pte) {
1405                 goto restart;
1406             }
1407             pte = updated_pte;
1408 #endif
1409         } else {
1410             /*
1411              * Misconfigured PTE in ROM (AD bits are not preset) or
1412              * PTE is in IO space and can't be updated atomically.
1413              */
1414             return TRANSLATE_FAIL;
1415         }
1416     }
1417 
1418     /* For superpage mappings, make a fake leaf PTE for the TLB's benefit. */
1419     target_ulong vpn = addr >> PGSHIFT;
1420 
1421     if (riscv_cpu_cfg(env)->ext_svnapot && (pte & PTE_N)) {
1422         napot_bits = ctzl(ppn) + 1;
1423         if ((i != (levels - 1)) || (napot_bits != 4)) {
1424             return TRANSLATE_FAIL;
1425         }
1426     }
1427 
1428     napot_mask = (1 << napot_bits) - 1;
1429     *physical = (((ppn & ~napot_mask) | (vpn & napot_mask) |
1430                   (vpn & (((target_ulong)1 << ptshift) - 1))
1431                  ) << PGSHIFT) | (addr & ~TARGET_PAGE_MASK);
1432 
1433     /*
1434      * Remove write permission unless this is a store, or the page is
1435      * already dirty, so that we TLB miss on later writes to update
1436      * the dirty bit.
1437      */
1438     if (access_type != MMU_DATA_STORE && !(pte & PTE_D)) {
1439         prot &= ~PAGE_WRITE;
1440     }
1441     *ret_prot = prot;
1442 
1443     return TRANSLATE_SUCCESS;
1444 }
1445 
1446 static void raise_mmu_exception(CPURISCVState *env, target_ulong address,
1447                                 MMUAccessType access_type, bool pmp_violation,
1448                                 bool first_stage, bool two_stage,
1449                                 bool two_stage_indirect)
1450 {
1451     CPUState *cs = env_cpu(env);
1452 
1453     switch (access_type) {
1454     case MMU_INST_FETCH:
1455         if (pmp_violation) {
1456             cs->exception_index = RISCV_EXCP_INST_ACCESS_FAULT;
1457         } else if (env->virt_enabled && !first_stage) {
1458             cs->exception_index = RISCV_EXCP_INST_GUEST_PAGE_FAULT;
1459         } else {
1460             cs->exception_index = RISCV_EXCP_INST_PAGE_FAULT;
1461         }
1462         break;
1463     case MMU_DATA_LOAD:
1464         if (pmp_violation) {
1465             cs->exception_index = RISCV_EXCP_LOAD_ACCESS_FAULT;
1466         } else if (two_stage && !first_stage) {
1467             cs->exception_index = RISCV_EXCP_LOAD_GUEST_ACCESS_FAULT;
1468         } else {
1469             cs->exception_index = RISCV_EXCP_LOAD_PAGE_FAULT;
1470         }
1471         break;
1472     case MMU_DATA_STORE:
1473         if (pmp_violation) {
1474             cs->exception_index = RISCV_EXCP_STORE_AMO_ACCESS_FAULT;
1475         } else if (two_stage && !first_stage) {
1476             cs->exception_index = RISCV_EXCP_STORE_GUEST_AMO_ACCESS_FAULT;
1477         } else {
1478             cs->exception_index = RISCV_EXCP_STORE_PAGE_FAULT;
1479         }
1480         break;
1481     default:
1482         g_assert_not_reached();
1483     }
1484     env->badaddr = address;
1485     env->two_stage_lookup = two_stage;
1486     env->two_stage_indirect_lookup = two_stage_indirect;
1487 }
1488 
1489 hwaddr riscv_cpu_get_phys_page_debug(CPUState *cs, vaddr addr)
1490 {
1491     RISCVCPU *cpu = RISCV_CPU(cs);
1492     CPURISCVState *env = &cpu->env;
1493     hwaddr phys_addr;
1494     int prot;
1495     int mmu_idx = riscv_env_mmu_index(&cpu->env, false);
1496 
1497     if (get_physical_address(env, &phys_addr, &prot, addr, NULL, 0, mmu_idx,
1498                              true, env->virt_enabled, true, false)) {
1499         return -1;
1500     }
1501 
1502     if (env->virt_enabled) {
1503         if (get_physical_address(env, &phys_addr, &prot, phys_addr, NULL,
1504                                  0, MMUIdx_U, false, true, true, false)) {
1505             return -1;
1506         }
1507     }
1508 
1509     return phys_addr & TARGET_PAGE_MASK;
1510 }
1511 
1512 void riscv_cpu_do_transaction_failed(CPUState *cs, hwaddr physaddr,
1513                                      vaddr addr, unsigned size,
1514                                      MMUAccessType access_type,
1515                                      int mmu_idx, MemTxAttrs attrs,
1516                                      MemTxResult response, uintptr_t retaddr)
1517 {
1518     RISCVCPU *cpu = RISCV_CPU(cs);
1519     CPURISCVState *env = &cpu->env;
1520 
1521     if (access_type == MMU_DATA_STORE) {
1522         cs->exception_index = RISCV_EXCP_STORE_AMO_ACCESS_FAULT;
1523     } else if (access_type == MMU_DATA_LOAD) {
1524         cs->exception_index = RISCV_EXCP_LOAD_ACCESS_FAULT;
1525     } else {
1526         cs->exception_index = RISCV_EXCP_INST_ACCESS_FAULT;
1527     }
1528 
1529     env->badaddr = addr;
1530     env->two_stage_lookup = mmuidx_2stage(mmu_idx);
1531     env->two_stage_indirect_lookup = false;
1532     cpu_loop_exit_restore(cs, retaddr);
1533 }
1534 
1535 void riscv_cpu_do_unaligned_access(CPUState *cs, vaddr addr,
1536                                    MMUAccessType access_type, int mmu_idx,
1537                                    uintptr_t retaddr)
1538 {
1539     RISCVCPU *cpu = RISCV_CPU(cs);
1540     CPURISCVState *env = &cpu->env;
1541     switch (access_type) {
1542     case MMU_INST_FETCH:
1543         cs->exception_index = RISCV_EXCP_INST_ADDR_MIS;
1544         break;
1545     case MMU_DATA_LOAD:
1546         cs->exception_index = RISCV_EXCP_LOAD_ADDR_MIS;
1547         /* shadow stack mis aligned accesses are access faults */
1548         if (mmu_idx & MMU_IDX_SS_WRITE) {
1549             cs->exception_index = RISCV_EXCP_LOAD_ACCESS_FAULT;
1550         }
1551         break;
1552     case MMU_DATA_STORE:
1553         cs->exception_index = RISCV_EXCP_STORE_AMO_ADDR_MIS;
1554         /* shadow stack mis aligned accesses are access faults */
1555         if (mmu_idx & MMU_IDX_SS_WRITE) {
1556             cs->exception_index = RISCV_EXCP_STORE_AMO_ACCESS_FAULT;
1557         }
1558         break;
1559     default:
1560         g_assert_not_reached();
1561     }
1562     env->badaddr = addr;
1563     env->two_stage_lookup = mmuidx_2stage(mmu_idx);
1564     env->two_stage_indirect_lookup = false;
1565     cpu_loop_exit_restore(cs, retaddr);
1566 }
1567 
1568 
1569 static void pmu_tlb_fill_incr_ctr(RISCVCPU *cpu, MMUAccessType access_type)
1570 {
1571     enum riscv_pmu_event_idx pmu_event_type;
1572 
1573     switch (access_type) {
1574     case MMU_INST_FETCH:
1575         pmu_event_type = RISCV_PMU_EVENT_CACHE_ITLB_PREFETCH_MISS;
1576         break;
1577     case MMU_DATA_LOAD:
1578         pmu_event_type = RISCV_PMU_EVENT_CACHE_DTLB_READ_MISS;
1579         break;
1580     case MMU_DATA_STORE:
1581         pmu_event_type = RISCV_PMU_EVENT_CACHE_DTLB_WRITE_MISS;
1582         break;
1583     default:
1584         return;
1585     }
1586 
1587     riscv_pmu_incr_ctr(cpu, pmu_event_type);
1588 }
1589 
1590 bool riscv_cpu_tlb_fill(CPUState *cs, vaddr address, int size,
1591                         MMUAccessType access_type, int mmu_idx,
1592                         bool probe, uintptr_t retaddr)
1593 {
1594     RISCVCPU *cpu = RISCV_CPU(cs);
1595     CPURISCVState *env = &cpu->env;
1596     vaddr im_address;
1597     hwaddr pa = 0;
1598     int prot, prot2, prot_pmp;
1599     bool pmp_violation = false;
1600     bool first_stage_error = true;
1601     bool two_stage_lookup = mmuidx_2stage(mmu_idx);
1602     bool two_stage_indirect_error = false;
1603     int ret = TRANSLATE_FAIL;
1604     int mode = mmuidx_priv(mmu_idx);
1605     /* default TLB page size */
1606     hwaddr tlb_size = TARGET_PAGE_SIZE;
1607 
1608     env->guest_phys_fault_addr = 0;
1609 
1610     qemu_log_mask(CPU_LOG_MMU, "%s ad %" VADDR_PRIx " rw %d mmu_idx %d\n",
1611                   __func__, address, access_type, mmu_idx);
1612 
1613     pmu_tlb_fill_incr_ctr(cpu, access_type);
1614     if (two_stage_lookup) {
1615         /* Two stage lookup */
1616         ret = get_physical_address(env, &pa, &prot, address,
1617                                    &env->guest_phys_fault_addr, access_type,
1618                                    mmu_idx, true, true, false, probe);
1619 
1620         /*
1621          * A G-stage exception may be triggered during two state lookup.
1622          * And the env->guest_phys_fault_addr has already been set in
1623          * get_physical_address().
1624          */
1625         if (ret == TRANSLATE_G_STAGE_FAIL) {
1626             first_stage_error = false;
1627             two_stage_indirect_error = true;
1628         }
1629 
1630         qemu_log_mask(CPU_LOG_MMU,
1631                       "%s 1st-stage address=%" VADDR_PRIx " ret %d physical "
1632                       HWADDR_FMT_plx " prot %d\n",
1633                       __func__, address, ret, pa, prot);
1634 
1635         if (ret == TRANSLATE_SUCCESS) {
1636             /* Second stage lookup */
1637             im_address = pa;
1638 
1639             ret = get_physical_address(env, &pa, &prot2, im_address, NULL,
1640                                        access_type, MMUIdx_U, false, true,
1641                                        false, probe);
1642 
1643             qemu_log_mask(CPU_LOG_MMU,
1644                           "%s 2nd-stage address=%" VADDR_PRIx
1645                           " ret %d physical "
1646                           HWADDR_FMT_plx " prot %d\n",
1647                           __func__, im_address, ret, pa, prot2);
1648 
1649             prot &= prot2;
1650 
1651             if (ret == TRANSLATE_SUCCESS) {
1652                 ret = get_physical_address_pmp(env, &prot_pmp, pa,
1653                                                size, access_type, mode);
1654                 tlb_size = pmp_get_tlb_size(env, pa);
1655 
1656                 qemu_log_mask(CPU_LOG_MMU,
1657                               "%s PMP address=" HWADDR_FMT_plx " ret %d prot"
1658                               " %d tlb_size %" HWADDR_PRIu "\n",
1659                               __func__, pa, ret, prot_pmp, tlb_size);
1660 
1661                 prot &= prot_pmp;
1662             } else {
1663                 /*
1664                  * Guest physical address translation failed, this is a HS
1665                  * level exception
1666                  */
1667                 first_stage_error = false;
1668                 if (ret != TRANSLATE_PMP_FAIL) {
1669                     env->guest_phys_fault_addr = (im_address |
1670                                                   (address &
1671                                                    (TARGET_PAGE_SIZE - 1))) >> 2;
1672                 }
1673             }
1674         }
1675     } else {
1676         /* Single stage lookup */
1677         ret = get_physical_address(env, &pa, &prot, address, NULL,
1678                                    access_type, mmu_idx, true, false, false,
1679                                    probe);
1680 
1681         qemu_log_mask(CPU_LOG_MMU,
1682                       "%s address=%" VADDR_PRIx " ret %d physical "
1683                       HWADDR_FMT_plx " prot %d\n",
1684                       __func__, address, ret, pa, prot);
1685 
1686         if (ret == TRANSLATE_SUCCESS) {
1687             ret = get_physical_address_pmp(env, &prot_pmp, pa,
1688                                            size, access_type, mode);
1689             tlb_size = pmp_get_tlb_size(env, pa);
1690 
1691             qemu_log_mask(CPU_LOG_MMU,
1692                           "%s PMP address=" HWADDR_FMT_plx " ret %d prot"
1693                           " %d tlb_size %" HWADDR_PRIu "\n",
1694                           __func__, pa, ret, prot_pmp, tlb_size);
1695 
1696             prot &= prot_pmp;
1697         }
1698     }
1699 
1700     if (ret == TRANSLATE_PMP_FAIL) {
1701         pmp_violation = true;
1702     }
1703 
1704     if (ret == TRANSLATE_SUCCESS) {
1705         tlb_set_page(cs, address & ~(tlb_size - 1), pa & ~(tlb_size - 1),
1706                      prot, mmu_idx, tlb_size);
1707         return true;
1708     } else if (probe) {
1709         return false;
1710     } else {
1711         raise_mmu_exception(env, address, access_type, pmp_violation,
1712                             first_stage_error, two_stage_lookup,
1713                             two_stage_indirect_error);
1714         cpu_loop_exit_restore(cs, retaddr);
1715     }
1716 
1717     return true;
1718 }
1719 
1720 static target_ulong riscv_transformed_insn(CPURISCVState *env,
1721                                            target_ulong insn,
1722                                            target_ulong taddr)
1723 {
1724     target_ulong xinsn = 0;
1725     target_ulong access_rs1 = 0, access_imm = 0, access_size = 0;
1726 
1727     /*
1728      * Only Quadrant 0 and Quadrant 2 of RVC instruction space need to
1729      * be uncompressed. The Quadrant 1 of RVC instruction space need
1730      * not be transformed because these instructions won't generate
1731      * any load/store trap.
1732      */
1733 
1734     if ((insn & 0x3) != 0x3) {
1735         /* Transform 16bit instruction into 32bit instruction */
1736         switch (GET_C_OP(insn)) {
1737         case OPC_RISC_C_OP_QUAD0: /* Quadrant 0 */
1738             switch (GET_C_FUNC(insn)) {
1739             case OPC_RISC_C_FUNC_FLD_LQ:
1740                 if (riscv_cpu_xlen(env) != 128) { /* C.FLD (RV32/64) */
1741                     xinsn = OPC_RISC_FLD;
1742                     xinsn = SET_RD(xinsn, GET_C_RS2S(insn));
1743                     access_rs1 = GET_C_RS1S(insn);
1744                     access_imm = GET_C_LD_IMM(insn);
1745                     access_size = 8;
1746                 }
1747                 break;
1748             case OPC_RISC_C_FUNC_LW: /* C.LW */
1749                 xinsn = OPC_RISC_LW;
1750                 xinsn = SET_RD(xinsn, GET_C_RS2S(insn));
1751                 access_rs1 = GET_C_RS1S(insn);
1752                 access_imm = GET_C_LW_IMM(insn);
1753                 access_size = 4;
1754                 break;
1755             case OPC_RISC_C_FUNC_FLW_LD:
1756                 if (riscv_cpu_xlen(env) == 32) { /* C.FLW (RV32) */
1757                     xinsn = OPC_RISC_FLW;
1758                     xinsn = SET_RD(xinsn, GET_C_RS2S(insn));
1759                     access_rs1 = GET_C_RS1S(insn);
1760                     access_imm = GET_C_LW_IMM(insn);
1761                     access_size = 4;
1762                 } else { /* C.LD (RV64/RV128) */
1763                     xinsn = OPC_RISC_LD;
1764                     xinsn = SET_RD(xinsn, GET_C_RS2S(insn));
1765                     access_rs1 = GET_C_RS1S(insn);
1766                     access_imm = GET_C_LD_IMM(insn);
1767                     access_size = 8;
1768                 }
1769                 break;
1770             case OPC_RISC_C_FUNC_FSD_SQ:
1771                 if (riscv_cpu_xlen(env) != 128) { /* C.FSD (RV32/64) */
1772                     xinsn = OPC_RISC_FSD;
1773                     xinsn = SET_RS2(xinsn, GET_C_RS2S(insn));
1774                     access_rs1 = GET_C_RS1S(insn);
1775                     access_imm = GET_C_SD_IMM(insn);
1776                     access_size = 8;
1777                 }
1778                 break;
1779             case OPC_RISC_C_FUNC_SW: /* C.SW */
1780                 xinsn = OPC_RISC_SW;
1781                 xinsn = SET_RS2(xinsn, GET_C_RS2S(insn));
1782                 access_rs1 = GET_C_RS1S(insn);
1783                 access_imm = GET_C_SW_IMM(insn);
1784                 access_size = 4;
1785                 break;
1786             case OPC_RISC_C_FUNC_FSW_SD:
1787                 if (riscv_cpu_xlen(env) == 32) { /* C.FSW (RV32) */
1788                     xinsn = OPC_RISC_FSW;
1789                     xinsn = SET_RS2(xinsn, GET_C_RS2S(insn));
1790                     access_rs1 = GET_C_RS1S(insn);
1791                     access_imm = GET_C_SW_IMM(insn);
1792                     access_size = 4;
1793                 } else { /* C.SD (RV64/RV128) */
1794                     xinsn = OPC_RISC_SD;
1795                     xinsn = SET_RS2(xinsn, GET_C_RS2S(insn));
1796                     access_rs1 = GET_C_RS1S(insn);
1797                     access_imm = GET_C_SD_IMM(insn);
1798                     access_size = 8;
1799                 }
1800                 break;
1801             default:
1802                 break;
1803             }
1804             break;
1805         case OPC_RISC_C_OP_QUAD2: /* Quadrant 2 */
1806             switch (GET_C_FUNC(insn)) {
1807             case OPC_RISC_C_FUNC_FLDSP_LQSP:
1808                 if (riscv_cpu_xlen(env) != 128) { /* C.FLDSP (RV32/64) */
1809                     xinsn = OPC_RISC_FLD;
1810                     xinsn = SET_RD(xinsn, GET_C_RD(insn));
1811                     access_rs1 = 2;
1812                     access_imm = GET_C_LDSP_IMM(insn);
1813                     access_size = 8;
1814                 }
1815                 break;
1816             case OPC_RISC_C_FUNC_LWSP: /* C.LWSP */
1817                 xinsn = OPC_RISC_LW;
1818                 xinsn = SET_RD(xinsn, GET_C_RD(insn));
1819                 access_rs1 = 2;
1820                 access_imm = GET_C_LWSP_IMM(insn);
1821                 access_size = 4;
1822                 break;
1823             case OPC_RISC_C_FUNC_FLWSP_LDSP:
1824                 if (riscv_cpu_xlen(env) == 32) { /* C.FLWSP (RV32) */
1825                     xinsn = OPC_RISC_FLW;
1826                     xinsn = SET_RD(xinsn, GET_C_RD(insn));
1827                     access_rs1 = 2;
1828                     access_imm = GET_C_LWSP_IMM(insn);
1829                     access_size = 4;
1830                 } else { /* C.LDSP (RV64/RV128) */
1831                     xinsn = OPC_RISC_LD;
1832                     xinsn = SET_RD(xinsn, GET_C_RD(insn));
1833                     access_rs1 = 2;
1834                     access_imm = GET_C_LDSP_IMM(insn);
1835                     access_size = 8;
1836                 }
1837                 break;
1838             case OPC_RISC_C_FUNC_FSDSP_SQSP:
1839                 if (riscv_cpu_xlen(env) != 128) { /* C.FSDSP (RV32/64) */
1840                     xinsn = OPC_RISC_FSD;
1841                     xinsn = SET_RS2(xinsn, GET_C_RS2(insn));
1842                     access_rs1 = 2;
1843                     access_imm = GET_C_SDSP_IMM(insn);
1844                     access_size = 8;
1845                 }
1846                 break;
1847             case OPC_RISC_C_FUNC_SWSP: /* C.SWSP */
1848                 xinsn = OPC_RISC_SW;
1849                 xinsn = SET_RS2(xinsn, GET_C_RS2(insn));
1850                 access_rs1 = 2;
1851                 access_imm = GET_C_SWSP_IMM(insn);
1852                 access_size = 4;
1853                 break;
1854             case 7:
1855                 if (riscv_cpu_xlen(env) == 32) { /* C.FSWSP (RV32) */
1856                     xinsn = OPC_RISC_FSW;
1857                     xinsn = SET_RS2(xinsn, GET_C_RS2(insn));
1858                     access_rs1 = 2;
1859                     access_imm = GET_C_SWSP_IMM(insn);
1860                     access_size = 4;
1861                 } else { /* C.SDSP (RV64/RV128) */
1862                     xinsn = OPC_RISC_SD;
1863                     xinsn = SET_RS2(xinsn, GET_C_RS2(insn));
1864                     access_rs1 = 2;
1865                     access_imm = GET_C_SDSP_IMM(insn);
1866                     access_size = 8;
1867                 }
1868                 break;
1869             default:
1870                 break;
1871             }
1872             break;
1873         default:
1874             break;
1875         }
1876 
1877         /*
1878          * Clear Bit1 of transformed instruction to indicate that
1879          * original insruction was a 16bit instruction
1880          */
1881         xinsn &= ~((target_ulong)0x2);
1882     } else {
1883         /* Transform 32bit (or wider) instructions */
1884         switch (MASK_OP_MAJOR(insn)) {
1885         case OPC_RISC_ATOMIC:
1886             xinsn = insn;
1887             access_rs1 = GET_RS1(insn);
1888             access_size = 1 << GET_FUNCT3(insn);
1889             break;
1890         case OPC_RISC_LOAD:
1891         case OPC_RISC_FP_LOAD:
1892             xinsn = SET_I_IMM(insn, 0);
1893             access_rs1 = GET_RS1(insn);
1894             access_imm = GET_IMM(insn);
1895             access_size = 1 << GET_FUNCT3(insn);
1896             break;
1897         case OPC_RISC_STORE:
1898         case OPC_RISC_FP_STORE:
1899             xinsn = SET_S_IMM(insn, 0);
1900             access_rs1 = GET_RS1(insn);
1901             access_imm = GET_STORE_IMM(insn);
1902             access_size = 1 << GET_FUNCT3(insn);
1903             break;
1904         case OPC_RISC_SYSTEM:
1905             if (MASK_OP_SYSTEM(insn) == OPC_RISC_HLVHSV) {
1906                 xinsn = insn;
1907                 access_rs1 = GET_RS1(insn);
1908                 access_size = 1 << ((GET_FUNCT7(insn) >> 1) & 0x3);
1909                 access_size = 1 << access_size;
1910             }
1911             break;
1912         default:
1913             break;
1914         }
1915     }
1916 
1917     if (access_size) {
1918         xinsn = SET_RS1(xinsn, (taddr - (env->gpr[access_rs1] + access_imm)) &
1919                                (access_size - 1));
1920     }
1921 
1922     return xinsn;
1923 }
1924 
1925 static target_ulong promote_load_fault(target_ulong orig_cause)
1926 {
1927     switch (orig_cause) {
1928     case RISCV_EXCP_LOAD_GUEST_ACCESS_FAULT:
1929         return RISCV_EXCP_STORE_GUEST_AMO_ACCESS_FAULT;
1930 
1931     case RISCV_EXCP_LOAD_ACCESS_FAULT:
1932         return RISCV_EXCP_STORE_AMO_ACCESS_FAULT;
1933 
1934     case RISCV_EXCP_LOAD_PAGE_FAULT:
1935         return RISCV_EXCP_STORE_PAGE_FAULT;
1936     }
1937 
1938     /* if no promotion, return original cause */
1939     return orig_cause;
1940 }
1941 
1942 static void riscv_do_nmi(CPURISCVState *env, target_ulong cause, bool virt)
1943 {
1944     env->mnstatus = set_field(env->mnstatus, MNSTATUS_NMIE, false);
1945     env->mnstatus = set_field(env->mnstatus, MNSTATUS_MNPV, virt);
1946     env->mnstatus = set_field(env->mnstatus, MNSTATUS_MNPP, env->priv);
1947     env->mncause = cause;
1948     env->mnepc = env->pc;
1949     env->pc = env->rnmi_irqvec;
1950 
1951     if (cpu_get_fcfien(env)) {
1952         env->mnstatus = set_field(env->mnstatus, MNSTATUS_MNPELP, env->elp);
1953     }
1954 
1955     /* Trapping to M mode, virt is disabled */
1956     riscv_cpu_set_mode(env, PRV_M, false);
1957 }
1958 
1959 /*
1960  * Handle Traps
1961  *
1962  * Adapted from Spike's processor_t::take_trap.
1963  *
1964  */
1965 void riscv_cpu_do_interrupt(CPUState *cs)
1966 {
1967     RISCVCPU *cpu = RISCV_CPU(cs);
1968     CPURISCVState *env = &cpu->env;
1969     bool virt = env->virt_enabled;
1970     bool write_gva = false;
1971     bool always_storeamo = (env->excp_uw2 & RISCV_UW2_ALWAYS_STORE_AMO);
1972     bool vsmode_exc;
1973     uint64_t s;
1974     int mode;
1975 
1976     /*
1977      * cs->exception is 32-bits wide unlike mcause which is XLEN-bits wide
1978      * so we mask off the MSB and separate into trap type and cause.
1979      */
1980     bool async = !!(cs->exception_index & RISCV_EXCP_INT_FLAG);
1981     target_ulong cause = cs->exception_index & RISCV_EXCP_INT_MASK;
1982     uint64_t deleg = async ? env->mideleg : env->medeleg;
1983     bool s_injected = env->mvip & (1ULL << cause) & env->mvien &&
1984         !(env->mip & (1ULL << cause));
1985     bool vs_injected = env->hvip & (1ULL << cause) & env->hvien &&
1986         !(env->mip & (1ULL << cause));
1987     bool smode_double_trap = false;
1988     uint64_t hdeleg = async ? env->hideleg : env->hedeleg;
1989     target_ulong tval = 0;
1990     target_ulong tinst = 0;
1991     target_ulong htval = 0;
1992     target_ulong mtval2 = 0;
1993     int sxlen = 0;
1994     int mxlen = 16 << riscv_cpu_mxl(env);
1995     bool nnmi_excep = false;
1996 
1997     if (cpu->cfg.ext_smrnmi && env->rnmip && async) {
1998         riscv_do_nmi(env, cause | ((target_ulong)1U << (mxlen - 1)),
1999                      env->virt_enabled);
2000         return;
2001     }
2002 
2003     if (!async) {
2004         /* set tval to badaddr for traps with address information */
2005         switch (cause) {
2006 #ifdef CONFIG_TCG
2007         case RISCV_EXCP_SEMIHOST:
2008             do_common_semihosting(cs);
2009             env->pc += 4;
2010             return;
2011 #endif
2012         case RISCV_EXCP_LOAD_GUEST_ACCESS_FAULT:
2013         case RISCV_EXCP_STORE_GUEST_AMO_ACCESS_FAULT:
2014         case RISCV_EXCP_LOAD_ADDR_MIS:
2015         case RISCV_EXCP_STORE_AMO_ADDR_MIS:
2016         case RISCV_EXCP_LOAD_ACCESS_FAULT:
2017         case RISCV_EXCP_STORE_AMO_ACCESS_FAULT:
2018         case RISCV_EXCP_LOAD_PAGE_FAULT:
2019         case RISCV_EXCP_STORE_PAGE_FAULT:
2020             if (always_storeamo) {
2021                 cause = promote_load_fault(cause);
2022             }
2023             write_gva = env->two_stage_lookup;
2024             tval = env->badaddr;
2025             if (env->two_stage_indirect_lookup) {
2026                 /*
2027                  * special pseudoinstruction for G-stage fault taken while
2028                  * doing VS-stage page table walk.
2029                  */
2030                 tinst = (riscv_cpu_xlen(env) == 32) ? 0x00002000 : 0x00003000;
2031             } else {
2032                 /*
2033                  * The "Addr. Offset" field in transformed instruction is
2034                  * non-zero only for misaligned access.
2035                  */
2036                 tinst = riscv_transformed_insn(env, env->bins, tval);
2037             }
2038             break;
2039         case RISCV_EXCP_INST_GUEST_PAGE_FAULT:
2040         case RISCV_EXCP_INST_ADDR_MIS:
2041         case RISCV_EXCP_INST_ACCESS_FAULT:
2042         case RISCV_EXCP_INST_PAGE_FAULT:
2043             write_gva = env->two_stage_lookup;
2044             tval = env->badaddr;
2045             if (env->two_stage_indirect_lookup) {
2046                 /*
2047                  * special pseudoinstruction for G-stage fault taken while
2048                  * doing VS-stage page table walk.
2049                  */
2050                 tinst = (riscv_cpu_xlen(env) == 32) ? 0x00002000 : 0x00003000;
2051             }
2052             break;
2053         case RISCV_EXCP_ILLEGAL_INST:
2054         case RISCV_EXCP_VIRT_INSTRUCTION_FAULT:
2055             tval = env->bins;
2056             break;
2057         case RISCV_EXCP_BREAKPOINT:
2058             tval = env->badaddr;
2059             if (cs->watchpoint_hit) {
2060                 tval = cs->watchpoint_hit->hitaddr;
2061                 cs->watchpoint_hit = NULL;
2062             }
2063             break;
2064         case RISCV_EXCP_SW_CHECK:
2065             tval = env->sw_check_code;
2066             break;
2067         default:
2068             break;
2069         }
2070         /* ecall is dispatched as one cause so translate based on mode */
2071         if (cause == RISCV_EXCP_U_ECALL) {
2072             assert(env->priv <= 3);
2073 
2074             if (env->priv == PRV_M) {
2075                 cause = RISCV_EXCP_M_ECALL;
2076             } else if (env->priv == PRV_S && env->virt_enabled) {
2077                 cause = RISCV_EXCP_VS_ECALL;
2078             } else if (env->priv == PRV_S && !env->virt_enabled) {
2079                 cause = RISCV_EXCP_S_ECALL;
2080             } else if (env->priv == PRV_U) {
2081                 cause = RISCV_EXCP_U_ECALL;
2082             }
2083         }
2084     }
2085 
2086     trace_riscv_trap(env->mhartid, async, cause, env->pc, tval,
2087                      riscv_cpu_get_trap_name(cause, async));
2088 
2089     qemu_log_mask(CPU_LOG_INT,
2090                   "%s: hart:"TARGET_FMT_ld", async:%d, cause:"TARGET_FMT_lx", "
2091                   "epc:0x"TARGET_FMT_lx", tval:0x"TARGET_FMT_lx", desc=%s\n",
2092                   __func__, env->mhartid, async, cause, env->pc, tval,
2093                   riscv_cpu_get_trap_name(cause, async));
2094 
2095     mode = env->priv <= PRV_S && cause < 64 &&
2096         (((deleg >> cause) & 1) || s_injected || vs_injected) ? PRV_S : PRV_M;
2097 
2098     vsmode_exc = env->virt_enabled && (((hdeleg >> cause) & 1) || vs_injected);
2099     /*
2100      * Check double trap condition only if already in S-mode and targeting
2101      * S-mode
2102      */
2103     if (cpu->cfg.ext_ssdbltrp && env->priv == PRV_S && mode == PRV_S) {
2104         bool dte = (env->menvcfg & MENVCFG_DTE) != 0;
2105         bool sdt = (env->mstatus & MSTATUS_SDT) != 0;
2106         /* In VS or HS */
2107         if (riscv_has_ext(env, RVH)) {
2108             if (vsmode_exc) {
2109                 /* VS -> VS, use henvcfg instead of menvcfg*/
2110                 dte = (env->henvcfg & HENVCFG_DTE) != 0;
2111             } else if (env->virt_enabled) {
2112                 /* VS -> HS, use mstatus_hs */
2113                 sdt = (env->mstatus_hs & MSTATUS_SDT) != 0;
2114             }
2115         }
2116         smode_double_trap = dte && sdt;
2117         if (smode_double_trap) {
2118             mode = PRV_M;
2119         }
2120     }
2121 
2122     if (mode == PRV_S) {
2123         /* handle the trap in S-mode */
2124         /* save elp status */
2125         if (cpu_get_fcfien(env)) {
2126             env->mstatus = set_field(env->mstatus, MSTATUS_SPELP, env->elp);
2127         }
2128 
2129         if (riscv_has_ext(env, RVH)) {
2130             if (vsmode_exc) {
2131                 /* Trap to VS mode */
2132                 /*
2133                  * See if we need to adjust cause. Yes if its VS mode interrupt
2134                  * no if hypervisor has delegated one of hs mode's interrupt
2135                  */
2136                 if (async && (cause == IRQ_VS_TIMER || cause == IRQ_VS_SOFT ||
2137                               cause == IRQ_VS_EXT)) {
2138                     cause = cause - 1;
2139                 }
2140                 write_gva = false;
2141             } else if (env->virt_enabled) {
2142                 /* Trap into HS mode, from virt */
2143                 riscv_cpu_swap_hypervisor_regs(env);
2144                 env->hstatus = set_field(env->hstatus, HSTATUS_SPVP,
2145                                          env->priv);
2146                 env->hstatus = set_field(env->hstatus, HSTATUS_SPV, true);
2147 
2148                 htval = env->guest_phys_fault_addr;
2149 
2150                 virt = false;
2151             } else {
2152                 /* Trap into HS mode */
2153                 env->hstatus = set_field(env->hstatus, HSTATUS_SPV, false);
2154                 htval = env->guest_phys_fault_addr;
2155             }
2156             env->hstatus = set_field(env->hstatus, HSTATUS_GVA, write_gva);
2157         }
2158 
2159         s = env->mstatus;
2160         s = set_field(s, MSTATUS_SPIE, get_field(s, MSTATUS_SIE));
2161         s = set_field(s, MSTATUS_SPP, env->priv);
2162         s = set_field(s, MSTATUS_SIE, 0);
2163         if (riscv_env_smode_dbltrp_enabled(env, virt)) {
2164             s = set_field(s, MSTATUS_SDT, 1);
2165         }
2166         env->mstatus = s;
2167         sxlen = 16 << riscv_cpu_sxl(env);
2168         env->scause = cause | ((target_ulong)async << (sxlen - 1));
2169         env->sepc = env->pc;
2170         env->stval = tval;
2171         env->htval = htval;
2172         env->htinst = tinst;
2173         env->pc = (env->stvec >> 2 << 2) +
2174                   ((async && (env->stvec & 3) == 1) ? cause * 4 : 0);
2175         riscv_cpu_set_mode(env, PRV_S, virt);
2176     } else {
2177         /*
2178          * If the hart encounters an exception while executing in M-mode
2179          * with the mnstatus.NMIE bit clear, the exception is an RNMI exception.
2180          */
2181         nnmi_excep = cpu->cfg.ext_smrnmi &&
2182                      !get_field(env->mnstatus, MNSTATUS_NMIE) &&
2183                      !async;
2184 
2185         /* handle the trap in M-mode */
2186         /* save elp status */
2187         if (cpu_get_fcfien(env)) {
2188             if (nnmi_excep) {
2189                 env->mnstatus = set_field(env->mnstatus, MNSTATUS_MNPELP,
2190                                           env->elp);
2191             } else {
2192                 env->mstatus = set_field(env->mstatus, MSTATUS_MPELP, env->elp);
2193             }
2194         }
2195 
2196         if (riscv_has_ext(env, RVH)) {
2197             if (env->virt_enabled) {
2198                 riscv_cpu_swap_hypervisor_regs(env);
2199             }
2200             env->mstatus = set_field(env->mstatus, MSTATUS_MPV,
2201                                      env->virt_enabled);
2202             if (env->virt_enabled && tval) {
2203                 env->mstatus = set_field(env->mstatus, MSTATUS_GVA, 1);
2204             }
2205 
2206             mtval2 = env->guest_phys_fault_addr;
2207 
2208             /* Trapping to M mode, virt is disabled */
2209             virt = false;
2210         }
2211         /*
2212          * If the hart encounters an exception while executing in M-mode,
2213          * with the mnstatus.NMIE bit clear, the program counter is set to
2214          * the RNMI exception trap handler address.
2215          */
2216         nnmi_excep = cpu->cfg.ext_smrnmi &&
2217                      !get_field(env->mnstatus, MNSTATUS_NMIE) &&
2218                      !async;
2219 
2220         s = env->mstatus;
2221         s = set_field(s, MSTATUS_MPIE, get_field(s, MSTATUS_MIE));
2222         s = set_field(s, MSTATUS_MPP, env->priv);
2223         s = set_field(s, MSTATUS_MIE, 0);
2224         if (cpu->cfg.ext_smdbltrp) {
2225             if (env->mstatus & MSTATUS_MDT) {
2226                 assert(env->priv == PRV_M);
2227                 if (!cpu->cfg.ext_smrnmi || nnmi_excep) {
2228                     cpu_abort(CPU(cpu), "M-mode double trap\n");
2229                 } else {
2230                     riscv_do_nmi(env, cause, false);
2231                     return;
2232                 }
2233             }
2234 
2235             s = set_field(s, MSTATUS_MDT, 1);
2236         }
2237         env->mstatus = s;
2238         env->mcause = cause | ((target_ulong)async << (mxlen - 1));
2239         if (smode_double_trap) {
2240             env->mtval2 = env->mcause;
2241             env->mcause = RISCV_EXCP_DOUBLE_TRAP;
2242         } else {
2243             env->mtval2 = mtval2;
2244         }
2245         env->mepc = env->pc;
2246         env->mtval = tval;
2247         env->mtinst = tinst;
2248 
2249         /*
2250          * For RNMI exception, program counter is set to the RNMI exception
2251          * trap handler address.
2252          */
2253         if (nnmi_excep) {
2254             env->pc = env->rnmi_excpvec;
2255         } else {
2256             env->pc = (env->mtvec >> 2 << 2) +
2257                       ((async && (env->mtvec & 3) == 1) ? cause * 4 : 0);
2258         }
2259         riscv_cpu_set_mode(env, PRV_M, virt);
2260     }
2261 
2262     /*
2263      * Interrupt/exception/trap delivery is asynchronous event and as per
2264      * zicfilp spec CPU should clear up the ELP state. No harm in clearing
2265      * unconditionally.
2266      */
2267     env->elp = false;
2268 
2269     /*
2270      * NOTE: it is not necessary to yield load reservations here. It is only
2271      * necessary for an SC from "another hart" to cause a load reservation
2272      * to be yielded. Refer to the memory consistency model section of the
2273      * RISC-V ISA Specification.
2274      */
2275 
2276     env->two_stage_lookup = false;
2277     env->two_stage_indirect_lookup = false;
2278 }
2279 
2280 #endif /* !CONFIG_USER_ONLY */
2281