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