xref: /openbmc/qemu/target/riscv/cpu_helper.c (revision 43912529)
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 "exec/exec-all.h"
25 #include "tcg/tcg-op.h"
26 #include "trace.h"
27 #include "semihosting/common-semi.h"
28 
29 int riscv_cpu_mmu_index(CPURISCVState *env, bool ifetch)
30 {
31 #ifdef CONFIG_USER_ONLY
32     return 0;
33 #else
34     return env->priv;
35 #endif
36 }
37 
38 void cpu_get_tb_cpu_state(CPURISCVState *env, target_ulong *pc,
39                           target_ulong *cs_base, uint32_t *pflags)
40 {
41     CPUState *cs = env_cpu(env);
42     RISCVCPU *cpu = RISCV_CPU(cs);
43 
44     uint32_t flags = 0;
45 
46     *pc = env->xl == MXL_RV32 ? env->pc & UINT32_MAX : env->pc;
47     *cs_base = 0;
48 
49     if (riscv_has_ext(env, RVV) || cpu->cfg.ext_zve32f || cpu->cfg.ext_zve64f) {
50         /*
51          * If env->vl equals to VLMAX, we can use generic vector operation
52          * expanders (GVEC) to accerlate the vector operations.
53          * However, as LMUL could be a fractional number. The maximum
54          * vector size can be operated might be less than 8 bytes,
55          * which is not supported by GVEC. So we set vl_eq_vlmax flag to true
56          * only when maxsz >= 8 bytes.
57          */
58         uint32_t vlmax = vext_get_vlmax(env_archcpu(env), env->vtype);
59         uint32_t sew = FIELD_EX64(env->vtype, VTYPE, VSEW);
60         uint32_t maxsz = vlmax << sew;
61         bool vl_eq_vlmax = (env->vstart == 0) && (vlmax == env->vl) &&
62                            (maxsz >= 8);
63         flags = FIELD_DP32(flags, TB_FLAGS, VILL, env->vill);
64         flags = FIELD_DP32(flags, TB_FLAGS, SEW, sew);
65         flags = FIELD_DP32(flags, TB_FLAGS, LMUL,
66                     FIELD_EX64(env->vtype, VTYPE, VLMUL));
67         flags = FIELD_DP32(flags, TB_FLAGS, VL_EQ_VLMAX, vl_eq_vlmax);
68     } else {
69         flags = FIELD_DP32(flags, TB_FLAGS, VILL, 1);
70     }
71 
72 #ifdef CONFIG_USER_ONLY
73     flags |= TB_FLAGS_MSTATUS_FS;
74     flags |= TB_FLAGS_MSTATUS_VS;
75 #else
76     flags |= cpu_mmu_index(env, 0);
77     if (riscv_cpu_fp_enabled(env)) {
78         flags |= env->mstatus & MSTATUS_FS;
79     }
80 
81     if (riscv_cpu_vector_enabled(env)) {
82         flags |= env->mstatus & MSTATUS_VS;
83     }
84 
85     if (riscv_has_ext(env, RVH)) {
86         if (env->priv == PRV_M ||
87             (env->priv == PRV_S && !riscv_cpu_virt_enabled(env)) ||
88             (env->priv == PRV_U && !riscv_cpu_virt_enabled(env) &&
89                 get_field(env->hstatus, HSTATUS_HU))) {
90             flags = FIELD_DP32(flags, TB_FLAGS, HLSX, 1);
91         }
92 
93         flags = FIELD_DP32(flags, TB_FLAGS, MSTATUS_HS_FS,
94                            get_field(env->mstatus_hs, MSTATUS_FS));
95 
96         flags = FIELD_DP32(flags, TB_FLAGS, MSTATUS_HS_VS,
97                            get_field(env->mstatus_hs, MSTATUS_VS));
98     }
99 #endif
100 
101     flags = FIELD_DP32(flags, TB_FLAGS, XL, env->xl);
102     if (env->cur_pmmask < (env->xl == MXL_RV32 ? UINT32_MAX : UINT64_MAX)) {
103         flags = FIELD_DP32(flags, TB_FLAGS, PM_MASK_ENABLED, 1);
104     }
105     if (env->cur_pmbase != 0) {
106         flags = FIELD_DP32(flags, TB_FLAGS, PM_BASE_ENABLED, 1);
107     }
108 
109     *pflags = flags;
110 }
111 
112 void riscv_cpu_update_mask(CPURISCVState *env)
113 {
114     target_ulong mask = -1, base = 0;
115     /*
116      * TODO: Current RVJ spec does not specify
117      * how the extension interacts with XLEN.
118      */
119 #ifndef CONFIG_USER_ONLY
120     if (riscv_has_ext(env, RVJ)) {
121         switch (env->priv) {
122         case PRV_M:
123             if (env->mmte & M_PM_ENABLE) {
124                 mask = env->mpmmask;
125                 base = env->mpmbase;
126             }
127             break;
128         case PRV_S:
129             if (env->mmte & S_PM_ENABLE) {
130                 mask = env->spmmask;
131                 base = env->spmbase;
132             }
133             break;
134         case PRV_U:
135             if (env->mmte & U_PM_ENABLE) {
136                 mask = env->upmmask;
137                 base = env->upmbase;
138             }
139             break;
140         default:
141             g_assert_not_reached();
142         }
143     }
144 #endif
145     if (env->xl == MXL_RV32) {
146         env->cur_pmmask = mask & UINT32_MAX;
147         env->cur_pmbase = base & UINT32_MAX;
148     } else {
149         env->cur_pmmask = mask;
150         env->cur_pmbase = base;
151     }
152 }
153 
154 #ifndef CONFIG_USER_ONLY
155 
156 /*
157  * The HS-mode is allowed to configure priority only for the
158  * following VS-mode local interrupts:
159  *
160  * 0  (Reserved interrupt, reads as zero)
161  * 1  Supervisor software interrupt
162  * 4  (Reserved interrupt, reads as zero)
163  * 5  Supervisor timer interrupt
164  * 8  (Reserved interrupt, reads as zero)
165  * 13 (Reserved interrupt)
166  * 14 "
167  * 15 "
168  * 16 "
169  * 18 Debug/trace interrupt
170  * 20 (Reserved interrupt)
171  * 22 "
172  * 24 "
173  * 26 "
174  * 28 "
175  * 30 (Reserved for standard reporting of bus or system errors)
176  */
177 
178 static const int hviprio_index2irq[] = {
179     0, 1, 4, 5, 8, 13, 14, 15, 16, 18, 20, 22, 24, 26, 28, 30 };
180 static const int hviprio_index2rdzero[] = {
181     1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
182 
183 int riscv_cpu_hviprio_index2irq(int index, int *out_irq, int *out_rdzero)
184 {
185     if (index < 0 || ARRAY_SIZE(hviprio_index2irq) <= index) {
186         return -EINVAL;
187     }
188 
189     if (out_irq) {
190         *out_irq = hviprio_index2irq[index];
191     }
192 
193     if (out_rdzero) {
194         *out_rdzero = hviprio_index2rdzero[index];
195     }
196 
197     return 0;
198 }
199 
200 /*
201  * Default priorities of local interrupts are defined in the
202  * RISC-V Advanced Interrupt Architecture specification.
203  *
204  * ----------------------------------------------------------------
205  *  Default  |
206  *  Priority | Major Interrupt Numbers
207  * ----------------------------------------------------------------
208  *  Highest  | 63 (3f), 62 (3e), 31 (1f), 30 (1e), 61 (3d), 60 (3c),
209  *           | 59 (3b), 58 (3a), 29 (1d), 28 (1c), 57 (39), 56 (38),
210  *           | 55 (37), 54 (36), 27 (1b), 26 (1a), 53 (35), 52 (34),
211  *           | 51 (33), 50 (32), 25 (19), 24 (18), 49 (31), 48 (30)
212  *           |
213  *           | 11 (0b),  3 (03),  7 (07)
214  *           |  9 (09),  1 (01),  5 (05)
215  *           | 12 (0c)
216  *           | 10 (0a),  2 (02),  6 (06)
217  *           |
218  *           | 47 (2f), 46 (2e), 23 (17), 22 (16), 45 (2d), 44 (2c),
219  *           | 43 (2b), 42 (2a), 21 (15), 20 (14), 41 (29), 40 (28),
220  *           | 39 (27), 38 (26), 19 (13), 18 (12), 37 (25), 36 (24),
221  *  Lowest   | 35 (23), 34 (22), 17 (11), 16 (10), 33 (21), 32 (20)
222  * ----------------------------------------------------------------
223  */
224 static const uint8_t default_iprio[64] = {
225  [63] = IPRIO_DEFAULT_UPPER,
226  [62] = IPRIO_DEFAULT_UPPER + 1,
227  [31] = IPRIO_DEFAULT_UPPER + 2,
228  [30] = IPRIO_DEFAULT_UPPER + 3,
229  [61] = IPRIO_DEFAULT_UPPER + 4,
230  [60] = IPRIO_DEFAULT_UPPER + 5,
231 
232  [59] = IPRIO_DEFAULT_UPPER + 6,
233  [58] = IPRIO_DEFAULT_UPPER + 7,
234  [29] = IPRIO_DEFAULT_UPPER + 8,
235  [28] = IPRIO_DEFAULT_UPPER + 9,
236  [57] = IPRIO_DEFAULT_UPPER + 10,
237  [56] = IPRIO_DEFAULT_UPPER + 11,
238 
239  [55] = IPRIO_DEFAULT_UPPER + 12,
240  [54] = IPRIO_DEFAULT_UPPER + 13,
241  [27] = IPRIO_DEFAULT_UPPER + 14,
242  [26] = IPRIO_DEFAULT_UPPER + 15,
243  [53] = IPRIO_DEFAULT_UPPER + 16,
244  [52] = IPRIO_DEFAULT_UPPER + 17,
245 
246  [51] = IPRIO_DEFAULT_UPPER + 18,
247  [50] = IPRIO_DEFAULT_UPPER + 19,
248  [25] = IPRIO_DEFAULT_UPPER + 20,
249  [24] = IPRIO_DEFAULT_UPPER + 21,
250  [49] = IPRIO_DEFAULT_UPPER + 22,
251  [48] = IPRIO_DEFAULT_UPPER + 23,
252 
253  [11] = IPRIO_DEFAULT_M,
254  [3]  = IPRIO_DEFAULT_M + 1,
255  [7]  = IPRIO_DEFAULT_M + 2,
256 
257  [9]  = IPRIO_DEFAULT_S,
258  [1]  = IPRIO_DEFAULT_S + 1,
259  [5]  = IPRIO_DEFAULT_S + 2,
260 
261  [12] = IPRIO_DEFAULT_SGEXT,
262 
263  [10] = IPRIO_DEFAULT_VS,
264  [2]  = IPRIO_DEFAULT_VS + 1,
265  [6]  = IPRIO_DEFAULT_VS + 2,
266 
267  [47] = IPRIO_DEFAULT_LOWER,
268  [46] = IPRIO_DEFAULT_LOWER + 1,
269  [23] = IPRIO_DEFAULT_LOWER + 2,
270  [22] = IPRIO_DEFAULT_LOWER + 3,
271  [45] = IPRIO_DEFAULT_LOWER + 4,
272  [44] = IPRIO_DEFAULT_LOWER + 5,
273 
274  [43] = IPRIO_DEFAULT_LOWER + 6,
275  [42] = IPRIO_DEFAULT_LOWER + 7,
276  [21] = IPRIO_DEFAULT_LOWER + 8,
277  [20] = IPRIO_DEFAULT_LOWER + 9,
278  [41] = IPRIO_DEFAULT_LOWER + 10,
279  [40] = IPRIO_DEFAULT_LOWER + 11,
280 
281  [39] = IPRIO_DEFAULT_LOWER + 12,
282  [38] = IPRIO_DEFAULT_LOWER + 13,
283  [19] = IPRIO_DEFAULT_LOWER + 14,
284  [18] = IPRIO_DEFAULT_LOWER + 15,
285  [37] = IPRIO_DEFAULT_LOWER + 16,
286  [36] = IPRIO_DEFAULT_LOWER + 17,
287 
288  [35] = IPRIO_DEFAULT_LOWER + 18,
289  [34] = IPRIO_DEFAULT_LOWER + 19,
290  [17] = IPRIO_DEFAULT_LOWER + 20,
291  [16] = IPRIO_DEFAULT_LOWER + 21,
292  [33] = IPRIO_DEFAULT_LOWER + 22,
293  [32] = IPRIO_DEFAULT_LOWER + 23,
294 };
295 
296 uint8_t riscv_cpu_default_priority(int irq)
297 {
298     if (irq < 0 || irq > 63) {
299         return IPRIO_MMAXIPRIO;
300     }
301 
302     return default_iprio[irq] ? default_iprio[irq] : IPRIO_MMAXIPRIO;
303 };
304 
305 static int riscv_cpu_pending_to_irq(CPURISCVState *env,
306                                     int extirq, unsigned int extirq_def_prio,
307                                     uint64_t pending, uint8_t *iprio)
308 {
309     int irq, best_irq = RISCV_EXCP_NONE;
310     unsigned int prio, best_prio = UINT_MAX;
311 
312     if (!pending) {
313         return RISCV_EXCP_NONE;
314     }
315 
316     irq = ctz64(pending);
317     if (!riscv_feature(env, RISCV_FEATURE_AIA)) {
318         return irq;
319     }
320 
321     pending = pending >> irq;
322     while (pending) {
323         prio = iprio[irq];
324         if (!prio) {
325             if (irq == extirq) {
326                 prio = extirq_def_prio;
327             } else {
328                 prio = (riscv_cpu_default_priority(irq) < extirq_def_prio) ?
329                        1 : IPRIO_MMAXIPRIO;
330             }
331         }
332         if ((pending & 0x1) && (prio <= best_prio)) {
333             best_irq = irq;
334             best_prio = prio;
335         }
336         irq++;
337         pending = pending >> 1;
338     }
339 
340     return best_irq;
341 }
342 
343 static uint64_t riscv_cpu_all_pending(CPURISCVState *env)
344 {
345     uint32_t gein = get_field(env->hstatus, HSTATUS_VGEIN);
346     uint64_t vsgein = (env->hgeip & (1ULL << gein)) ? MIP_VSEIP : 0;
347 
348     return (env->mip | vsgein) & env->mie;
349 }
350 
351 int riscv_cpu_mirq_pending(CPURISCVState *env)
352 {
353     uint64_t irqs = riscv_cpu_all_pending(env) & ~env->mideleg &
354                     ~(MIP_SGEIP | MIP_VSSIP | MIP_VSTIP | MIP_VSEIP);
355 
356     return riscv_cpu_pending_to_irq(env, IRQ_M_EXT, IPRIO_DEFAULT_M,
357                                     irqs, env->miprio);
358 }
359 
360 int riscv_cpu_sirq_pending(CPURISCVState *env)
361 {
362     uint64_t irqs = riscv_cpu_all_pending(env) & env->mideleg &
363                     ~(MIP_VSSIP | MIP_VSTIP | MIP_VSEIP);
364 
365     return riscv_cpu_pending_to_irq(env, IRQ_S_EXT, IPRIO_DEFAULT_S,
366                                     irqs, env->siprio);
367 }
368 
369 int riscv_cpu_vsirq_pending(CPURISCVState *env)
370 {
371     uint64_t irqs = riscv_cpu_all_pending(env) & env->mideleg &
372                     (MIP_VSSIP | MIP_VSTIP | MIP_VSEIP);
373 
374     return riscv_cpu_pending_to_irq(env, IRQ_S_EXT, IPRIO_DEFAULT_S,
375                                     irqs >> 1, env->hviprio);
376 }
377 
378 static int riscv_cpu_local_irq_pending(CPURISCVState *env)
379 {
380     int virq;
381     uint64_t irqs, pending, mie, hsie, vsie;
382 
383     /* Determine interrupt enable state of all privilege modes */
384     if (riscv_cpu_virt_enabled(env)) {
385         mie = 1;
386         hsie = 1;
387         vsie = (env->priv < PRV_S) ||
388                (env->priv == PRV_S && get_field(env->mstatus, MSTATUS_SIE));
389     } else {
390         mie = (env->priv < PRV_M) ||
391               (env->priv == PRV_M && get_field(env->mstatus, MSTATUS_MIE));
392         hsie = (env->priv < PRV_S) ||
393                (env->priv == PRV_S && get_field(env->mstatus, MSTATUS_SIE));
394         vsie = 0;
395     }
396 
397     /* Determine all pending interrupts */
398     pending = riscv_cpu_all_pending(env);
399 
400     /* Check M-mode interrupts */
401     irqs = pending & ~env->mideleg & -mie;
402     if (irqs) {
403         return riscv_cpu_pending_to_irq(env, IRQ_M_EXT, IPRIO_DEFAULT_M,
404                                         irqs, env->miprio);
405     }
406 
407     /* Check HS-mode interrupts */
408     irqs = pending & env->mideleg & ~env->hideleg & -hsie;
409     if (irqs) {
410         return riscv_cpu_pending_to_irq(env, IRQ_S_EXT, IPRIO_DEFAULT_S,
411                                         irqs, env->siprio);
412     }
413 
414     /* Check VS-mode interrupts */
415     irqs = pending & env->mideleg & env->hideleg & -vsie;
416     if (irqs) {
417         virq = riscv_cpu_pending_to_irq(env, IRQ_S_EXT, IPRIO_DEFAULT_S,
418                                         irqs >> 1, env->hviprio);
419         return (virq <= 0) ? virq : virq + 1;
420     }
421 
422     /* Indicate no pending interrupt */
423     return RISCV_EXCP_NONE;
424 }
425 
426 bool riscv_cpu_exec_interrupt(CPUState *cs, int interrupt_request)
427 {
428     if (interrupt_request & CPU_INTERRUPT_HARD) {
429         RISCVCPU *cpu = RISCV_CPU(cs);
430         CPURISCVState *env = &cpu->env;
431         int interruptno = riscv_cpu_local_irq_pending(env);
432         if (interruptno >= 0) {
433             cs->exception_index = RISCV_EXCP_INT_FLAG | interruptno;
434             riscv_cpu_do_interrupt(cs);
435             return true;
436         }
437     }
438     return false;
439 }
440 
441 /* Return true is floating point support is currently enabled */
442 bool riscv_cpu_fp_enabled(CPURISCVState *env)
443 {
444     if (env->mstatus & MSTATUS_FS) {
445         if (riscv_cpu_virt_enabled(env) && !(env->mstatus_hs & MSTATUS_FS)) {
446             return false;
447         }
448         return true;
449     }
450 
451     return false;
452 }
453 
454 /* Return true is vector support is currently enabled */
455 bool riscv_cpu_vector_enabled(CPURISCVState *env)
456 {
457     if (env->mstatus & MSTATUS_VS) {
458         if (riscv_cpu_virt_enabled(env) && !(env->mstatus_hs & MSTATUS_VS)) {
459             return false;
460         }
461         return true;
462     }
463 
464     return false;
465 }
466 
467 void riscv_cpu_swap_hypervisor_regs(CPURISCVState *env)
468 {
469     uint64_t mstatus_mask = MSTATUS_MXR | MSTATUS_SUM | MSTATUS_FS |
470                             MSTATUS_SPP | MSTATUS_SPIE | MSTATUS_SIE |
471                             MSTATUS64_UXL | MSTATUS_VS;
472     bool current_virt = riscv_cpu_virt_enabled(env);
473 
474     g_assert(riscv_has_ext(env, RVH));
475 
476     if (current_virt) {
477         /* Current V=1 and we are about to change to V=0 */
478         env->vsstatus = env->mstatus & mstatus_mask;
479         env->mstatus &= ~mstatus_mask;
480         env->mstatus |= env->mstatus_hs;
481 
482         env->vstvec = env->stvec;
483         env->stvec = env->stvec_hs;
484 
485         env->vsscratch = env->sscratch;
486         env->sscratch = env->sscratch_hs;
487 
488         env->vsepc = env->sepc;
489         env->sepc = env->sepc_hs;
490 
491         env->vscause = env->scause;
492         env->scause = env->scause_hs;
493 
494         env->vstval = env->stval;
495         env->stval = env->stval_hs;
496 
497         env->vsatp = env->satp;
498         env->satp = env->satp_hs;
499     } else {
500         /* Current V=0 and we are about to change to V=1 */
501         env->mstatus_hs = env->mstatus & mstatus_mask;
502         env->mstatus &= ~mstatus_mask;
503         env->mstatus |= env->vsstatus;
504 
505         env->stvec_hs = env->stvec;
506         env->stvec = env->vstvec;
507 
508         env->sscratch_hs = env->sscratch;
509         env->sscratch = env->vsscratch;
510 
511         env->sepc_hs = env->sepc;
512         env->sepc = env->vsepc;
513 
514         env->scause_hs = env->scause;
515         env->scause = env->vscause;
516 
517         env->stval_hs = env->stval;
518         env->stval = env->vstval;
519 
520         env->satp_hs = env->satp;
521         env->satp = env->vsatp;
522     }
523 }
524 
525 target_ulong riscv_cpu_get_geilen(CPURISCVState *env)
526 {
527     if (!riscv_has_ext(env, RVH)) {
528         return 0;
529     }
530 
531     return env->geilen;
532 }
533 
534 void riscv_cpu_set_geilen(CPURISCVState *env, target_ulong geilen)
535 {
536     if (!riscv_has_ext(env, RVH)) {
537         return;
538     }
539 
540     if (geilen > (TARGET_LONG_BITS - 1)) {
541         return;
542     }
543 
544     env->geilen = geilen;
545 }
546 
547 bool riscv_cpu_virt_enabled(CPURISCVState *env)
548 {
549     if (!riscv_has_ext(env, RVH)) {
550         return false;
551     }
552 
553     return get_field(env->virt, VIRT_ONOFF);
554 }
555 
556 void riscv_cpu_set_virt_enabled(CPURISCVState *env, bool enable)
557 {
558     if (!riscv_has_ext(env, RVH)) {
559         return;
560     }
561 
562     /* Flush the TLB on all virt mode changes. */
563     if (get_field(env->virt, VIRT_ONOFF) != enable) {
564         tlb_flush(env_cpu(env));
565     }
566 
567     env->virt = set_field(env->virt, VIRT_ONOFF, enable);
568 
569     if (enable) {
570         /*
571          * The guest external interrupts from an interrupt controller are
572          * delivered only when the Guest/VM is running (i.e. V=1). This means
573          * any guest external interrupt which is triggered while the Guest/VM
574          * is not running (i.e. V=0) will be missed on QEMU resulting in guest
575          * with sluggish response to serial console input and other I/O events.
576          *
577          * To solve this, we check and inject interrupt after setting V=1.
578          */
579         riscv_cpu_update_mip(env_archcpu(env), 0, 0);
580     }
581 }
582 
583 bool riscv_cpu_two_stage_lookup(int mmu_idx)
584 {
585     return mmu_idx & TB_FLAGS_PRIV_HYP_ACCESS_MASK;
586 }
587 
588 int riscv_cpu_claim_interrupts(RISCVCPU *cpu, uint64_t interrupts)
589 {
590     CPURISCVState *env = &cpu->env;
591     if (env->miclaim & interrupts) {
592         return -1;
593     } else {
594         env->miclaim |= interrupts;
595         return 0;
596     }
597 }
598 
599 uint64_t riscv_cpu_update_mip(RISCVCPU *cpu, uint64_t mask, uint64_t value)
600 {
601     CPURISCVState *env = &cpu->env;
602     CPUState *cs = CPU(cpu);
603     uint64_t gein, vsgein = 0, old = env->mip;
604     bool locked = false;
605 
606     if (riscv_cpu_virt_enabled(env)) {
607         gein = get_field(env->hstatus, HSTATUS_VGEIN);
608         vsgein = (env->hgeip & (1ULL << gein)) ? MIP_VSEIP : 0;
609     }
610 
611     if (!qemu_mutex_iothread_locked()) {
612         locked = true;
613         qemu_mutex_lock_iothread();
614     }
615 
616     env->mip = (env->mip & ~mask) | (value & mask);
617 
618     if (env->mip | vsgein) {
619         cpu_interrupt(cs, CPU_INTERRUPT_HARD);
620     } else {
621         cpu_reset_interrupt(cs, CPU_INTERRUPT_HARD);
622     }
623 
624     if (locked) {
625         qemu_mutex_unlock_iothread();
626     }
627 
628     return old;
629 }
630 
631 void riscv_cpu_set_rdtime_fn(CPURISCVState *env, uint64_t (*fn)(uint32_t),
632                              uint32_t arg)
633 {
634     env->rdtime_fn = fn;
635     env->rdtime_fn_arg = arg;
636 }
637 
638 void riscv_cpu_set_aia_ireg_rmw_fn(CPURISCVState *env, uint32_t priv,
639                                    int (*rmw_fn)(void *arg,
640                                                  target_ulong reg,
641                                                  target_ulong *val,
642                                                  target_ulong new_val,
643                                                  target_ulong write_mask),
644                                    void *rmw_fn_arg)
645 {
646     if (priv <= PRV_M) {
647         env->aia_ireg_rmw_fn[priv] = rmw_fn;
648         env->aia_ireg_rmw_fn_arg[priv] = rmw_fn_arg;
649     }
650 }
651 
652 void riscv_cpu_set_mode(CPURISCVState *env, target_ulong newpriv)
653 {
654     if (newpriv > PRV_M) {
655         g_assert_not_reached();
656     }
657     if (newpriv == PRV_H) {
658         newpriv = PRV_U;
659     }
660     /* tlb_flush is unnecessary as mode is contained in mmu_idx */
661     env->priv = newpriv;
662     env->xl = cpu_recompute_xl(env);
663     riscv_cpu_update_mask(env);
664 
665     /*
666      * Clear the load reservation - otherwise a reservation placed in one
667      * context/process can be used by another, resulting in an SC succeeding
668      * incorrectly. Version 2.2 of the ISA specification explicitly requires
669      * this behaviour, while later revisions say that the kernel "should" use
670      * an SC instruction to force the yielding of a load reservation on a
671      * preemptive context switch. As a result, do both.
672      */
673     env->load_res = -1;
674 }
675 
676 /*
677  * get_physical_address_pmp - check PMP permission for this physical address
678  *
679  * Match the PMP region and check permission for this physical address and it's
680  * TLB page. Returns 0 if the permission checking was successful
681  *
682  * @env: CPURISCVState
683  * @prot: The returned protection attributes
684  * @tlb_size: TLB page size containing addr. It could be modified after PMP
685  *            permission checking. NULL if not set TLB page for addr.
686  * @addr: The physical address to be checked permission
687  * @access_type: The type of MMU access
688  * @mode: Indicates current privilege level.
689  */
690 static int get_physical_address_pmp(CPURISCVState *env, int *prot,
691                                     target_ulong *tlb_size, hwaddr addr,
692                                     int size, MMUAccessType access_type,
693                                     int mode)
694 {
695     pmp_priv_t pmp_priv;
696     target_ulong tlb_size_pmp = 0;
697 
698     if (!riscv_feature(env, RISCV_FEATURE_PMP)) {
699         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
700         return TRANSLATE_SUCCESS;
701     }
702 
703     if (!pmp_hart_has_privs(env, addr, size, 1 << access_type, &pmp_priv,
704                             mode)) {
705         *prot = 0;
706         return TRANSLATE_PMP_FAIL;
707     }
708 
709     *prot = pmp_priv_to_page_prot(pmp_priv);
710     if (tlb_size != NULL) {
711         if (pmp_is_range_in_tlb(env, addr & ~(*tlb_size - 1), &tlb_size_pmp)) {
712             *tlb_size = tlb_size_pmp;
713         }
714     }
715 
716     return TRANSLATE_SUCCESS;
717 }
718 
719 /* get_physical_address - get the physical address for this virtual address
720  *
721  * Do a page table walk to obtain the physical address corresponding to a
722  * virtual address. Returns 0 if the translation was successful
723  *
724  * Adapted from Spike's mmu_t::translate and mmu_t::walk
725  *
726  * @env: CPURISCVState
727  * @physical: This will be set to the calculated physical address
728  * @prot: The returned protection attributes
729  * @addr: The virtual address to be translated
730  * @fault_pte_addr: If not NULL, this will be set to fault pte address
731  *                  when a error occurs on pte address translation.
732  *                  This will already be shifted to match htval.
733  * @access_type: The type of MMU access
734  * @mmu_idx: Indicates current privilege level
735  * @first_stage: Are we in first stage translation?
736  *               Second stage is used for hypervisor guest translation
737  * @two_stage: Are we going to perform two stage translation
738  * @is_debug: Is this access from a debugger or the monitor?
739  */
740 static int get_physical_address(CPURISCVState *env, hwaddr *physical,
741                                 int *prot, target_ulong addr,
742                                 target_ulong *fault_pte_addr,
743                                 int access_type, int mmu_idx,
744                                 bool first_stage, bool two_stage,
745                                 bool is_debug)
746 {
747     /* NOTE: the env->pc value visible here will not be
748      * correct, but the value visible to the exception handler
749      * (riscv_cpu_do_interrupt) is correct */
750     MemTxResult res;
751     MemTxAttrs attrs = MEMTXATTRS_UNSPECIFIED;
752     int mode = mmu_idx & TB_FLAGS_PRIV_MMU_MASK;
753     bool use_background = false;
754     hwaddr ppn;
755     RISCVCPU *cpu = env_archcpu(env);
756     int napot_bits = 0;
757     target_ulong napot_mask;
758 
759     /*
760      * Check if we should use the background registers for the two
761      * stage translation. We don't need to check if we actually need
762      * two stage translation as that happened before this function
763      * was called. Background registers will be used if the guest has
764      * forced a two stage translation to be on (in HS or M mode).
765      */
766     if (!riscv_cpu_virt_enabled(env) && two_stage) {
767         use_background = true;
768     }
769 
770     /* MPRV does not affect the virtual-machine load/store
771        instructions, HLV, HLVX, and HSV. */
772     if (riscv_cpu_two_stage_lookup(mmu_idx)) {
773         mode = get_field(env->hstatus, HSTATUS_SPVP);
774     } else if (mode == PRV_M && access_type != MMU_INST_FETCH) {
775         if (get_field(env->mstatus, MSTATUS_MPRV)) {
776             mode = get_field(env->mstatus, MSTATUS_MPP);
777         }
778     }
779 
780     if (first_stage == false) {
781         /* We are in stage 2 translation, this is similar to stage 1. */
782         /* Stage 2 is always taken as U-mode */
783         mode = PRV_U;
784     }
785 
786     if (mode == PRV_M || !riscv_feature(env, RISCV_FEATURE_MMU)) {
787         *physical = addr;
788         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
789         return TRANSLATE_SUCCESS;
790     }
791 
792     *prot = 0;
793 
794     hwaddr base;
795     int levels, ptidxbits, ptesize, vm, sum, mxr, widened;
796 
797     if (first_stage == true) {
798         mxr = get_field(env->mstatus, MSTATUS_MXR);
799     } else {
800         mxr = get_field(env->vsstatus, MSTATUS_MXR);
801     }
802 
803     if (first_stage == true) {
804         if (use_background) {
805             if (riscv_cpu_mxl(env) == MXL_RV32) {
806                 base = (hwaddr)get_field(env->vsatp, SATP32_PPN) << PGSHIFT;
807                 vm = get_field(env->vsatp, SATP32_MODE);
808             } else {
809                 base = (hwaddr)get_field(env->vsatp, SATP64_PPN) << PGSHIFT;
810                 vm = get_field(env->vsatp, SATP64_MODE);
811             }
812         } else {
813             if (riscv_cpu_mxl(env) == MXL_RV32) {
814                 base = (hwaddr)get_field(env->satp, SATP32_PPN) << PGSHIFT;
815                 vm = get_field(env->satp, SATP32_MODE);
816             } else {
817                 base = (hwaddr)get_field(env->satp, SATP64_PPN) << PGSHIFT;
818                 vm = get_field(env->satp, SATP64_MODE);
819             }
820         }
821         widened = 0;
822     } else {
823         if (riscv_cpu_mxl(env) == MXL_RV32) {
824             base = (hwaddr)get_field(env->hgatp, SATP32_PPN) << PGSHIFT;
825             vm = get_field(env->hgatp, SATP32_MODE);
826         } else {
827             base = (hwaddr)get_field(env->hgatp, SATP64_PPN) << PGSHIFT;
828             vm = get_field(env->hgatp, SATP64_MODE);
829         }
830         widened = 2;
831     }
832     /* status.SUM will be ignored if execute on background */
833     sum = get_field(env->mstatus, MSTATUS_SUM) || use_background || is_debug;
834     switch (vm) {
835     case VM_1_10_SV32:
836       levels = 2; ptidxbits = 10; ptesize = 4; break;
837     case VM_1_10_SV39:
838       levels = 3; ptidxbits = 9; ptesize = 8; break;
839     case VM_1_10_SV48:
840       levels = 4; ptidxbits = 9; ptesize = 8; break;
841     case VM_1_10_SV57:
842       levels = 5; ptidxbits = 9; ptesize = 8; break;
843     case VM_1_10_MBARE:
844         *physical = addr;
845         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
846         return TRANSLATE_SUCCESS;
847     default:
848       g_assert_not_reached();
849     }
850 
851     CPUState *cs = env_cpu(env);
852     int va_bits = PGSHIFT + levels * ptidxbits + widened;
853     target_ulong mask, masked_msbs;
854 
855     if (TARGET_LONG_BITS > (va_bits - 1)) {
856         mask = (1L << (TARGET_LONG_BITS - (va_bits - 1))) - 1;
857     } else {
858         mask = 0;
859     }
860     masked_msbs = (addr >> (va_bits - 1)) & mask;
861 
862     if (masked_msbs != 0 && masked_msbs != mask) {
863         return TRANSLATE_FAIL;
864     }
865 
866     int ptshift = (levels - 1) * ptidxbits;
867     int i;
868 
869 #if !TCG_OVERSIZED_GUEST
870 restart:
871 #endif
872     for (i = 0; i < levels; i++, ptshift -= ptidxbits) {
873         target_ulong idx;
874         if (i == 0) {
875             idx = (addr >> (PGSHIFT + ptshift)) &
876                            ((1 << (ptidxbits + widened)) - 1);
877         } else {
878             idx = (addr >> (PGSHIFT + ptshift)) &
879                            ((1 << ptidxbits) - 1);
880         }
881 
882         /* check that physical address of PTE is legal */
883         hwaddr pte_addr;
884 
885         if (two_stage && first_stage) {
886             int vbase_prot;
887             hwaddr vbase;
888 
889             /* Do the second stage translation on the base PTE address. */
890             int vbase_ret = get_physical_address(env, &vbase, &vbase_prot,
891                                                  base, NULL, MMU_DATA_LOAD,
892                                                  mmu_idx, false, true,
893                                                  is_debug);
894 
895             if (vbase_ret != TRANSLATE_SUCCESS) {
896                 if (fault_pte_addr) {
897                     *fault_pte_addr = (base + idx * ptesize) >> 2;
898                 }
899                 return TRANSLATE_G_STAGE_FAIL;
900             }
901 
902             pte_addr = vbase + idx * ptesize;
903         } else {
904             pte_addr = base + idx * ptesize;
905         }
906 
907         int pmp_prot;
908         int pmp_ret = get_physical_address_pmp(env, &pmp_prot, NULL, pte_addr,
909                                                sizeof(target_ulong),
910                                                MMU_DATA_LOAD, PRV_S);
911         if (pmp_ret != TRANSLATE_SUCCESS) {
912             return TRANSLATE_PMP_FAIL;
913         }
914 
915         target_ulong pte;
916         if (riscv_cpu_mxl(env) == MXL_RV32) {
917             pte = address_space_ldl(cs->as, pte_addr, attrs, &res);
918         } else {
919             pte = address_space_ldq(cs->as, pte_addr, attrs, &res);
920         }
921 
922         if (res != MEMTX_OK) {
923             return TRANSLATE_FAIL;
924         }
925 
926         if (riscv_cpu_sxl(env) == MXL_RV32) {
927             ppn = pte >> PTE_PPN_SHIFT;
928         } else if (cpu->cfg.ext_svpbmt || cpu->cfg.ext_svnapot) {
929             ppn = (pte & (target_ulong)PTE_PPN_MASK) >> PTE_PPN_SHIFT;
930         } else {
931             ppn = pte >> PTE_PPN_SHIFT;
932             if ((pte & ~(target_ulong)PTE_PPN_MASK) >> PTE_PPN_SHIFT) {
933                 return TRANSLATE_FAIL;
934             }
935         }
936 
937         if (!(pte & PTE_V)) {
938             /* Invalid PTE */
939             return TRANSLATE_FAIL;
940         } else if (!cpu->cfg.ext_svpbmt && (pte & PTE_PBMT)) {
941             return TRANSLATE_FAIL;
942         } else if (!(pte & (PTE_R | PTE_W | PTE_X))) {
943             /* Inner PTE, continue walking */
944             if (pte & (PTE_D | PTE_A | PTE_U | PTE_ATTR)) {
945                 return TRANSLATE_FAIL;
946             }
947             base = ppn << PGSHIFT;
948         } else if ((pte & (PTE_R | PTE_W | PTE_X)) == PTE_W) {
949             /* Reserved leaf PTE flags: PTE_W */
950             return TRANSLATE_FAIL;
951         } else if ((pte & (PTE_R | PTE_W | PTE_X)) == (PTE_W | PTE_X)) {
952             /* Reserved leaf PTE flags: PTE_W + PTE_X */
953             return TRANSLATE_FAIL;
954         } else if ((pte & PTE_U) && ((mode != PRV_U) &&
955                    (!sum || access_type == MMU_INST_FETCH))) {
956             /* User PTE flags when not U mode and mstatus.SUM is not set,
957                or the access type is an instruction fetch */
958             return TRANSLATE_FAIL;
959         } else if (!(pte & PTE_U) && (mode != PRV_S)) {
960             /* Supervisor PTE flags when not S mode */
961             return TRANSLATE_FAIL;
962         } else if (ppn & ((1ULL << ptshift) - 1)) {
963             /* Misaligned PPN */
964             return TRANSLATE_FAIL;
965         } else if (access_type == MMU_DATA_LOAD && !((pte & PTE_R) ||
966                    ((pte & PTE_X) && mxr))) {
967             /* Read access check failed */
968             return TRANSLATE_FAIL;
969         } else if (access_type == MMU_DATA_STORE && !(pte & PTE_W)) {
970             /* Write access check failed */
971             return TRANSLATE_FAIL;
972         } else if (access_type == MMU_INST_FETCH && !(pte & PTE_X)) {
973             /* Fetch access check failed */
974             return TRANSLATE_FAIL;
975         } else {
976             /* if necessary, set accessed and dirty bits. */
977             target_ulong updated_pte = pte | PTE_A |
978                 (access_type == MMU_DATA_STORE ? PTE_D : 0);
979 
980             /* Page table updates need to be atomic with MTTCG enabled */
981             if (updated_pte != pte) {
982                 /*
983                  * - if accessed or dirty bits need updating, and the PTE is
984                  *   in RAM, then we do so atomically with a compare and swap.
985                  * - if the PTE is in IO space or ROM, then it can't be updated
986                  *   and we return TRANSLATE_FAIL.
987                  * - if the PTE changed by the time we went to update it, then
988                  *   it is no longer valid and we must re-walk the page table.
989                  */
990                 MemoryRegion *mr;
991                 hwaddr l = sizeof(target_ulong), addr1;
992                 mr = address_space_translate(cs->as, pte_addr,
993                     &addr1, &l, false, MEMTXATTRS_UNSPECIFIED);
994                 if (memory_region_is_ram(mr)) {
995                     target_ulong *pte_pa =
996                         qemu_map_ram_ptr(mr->ram_block, addr1);
997 #if TCG_OVERSIZED_GUEST
998                     /* MTTCG is not enabled on oversized TCG guests so
999                      * page table updates do not need to be atomic */
1000                     *pte_pa = pte = updated_pte;
1001 #else
1002                     target_ulong old_pte =
1003                         qatomic_cmpxchg(pte_pa, pte, updated_pte);
1004                     if (old_pte != pte) {
1005                         goto restart;
1006                     } else {
1007                         pte = updated_pte;
1008                     }
1009 #endif
1010                 } else {
1011                     /* misconfigured PTE in ROM (AD bits are not preset) or
1012                      * PTE is in IO space and can't be updated atomically */
1013                     return TRANSLATE_FAIL;
1014                 }
1015             }
1016 
1017             /* for superpage mappings, make a fake leaf PTE for the TLB's
1018                benefit. */
1019             target_ulong vpn = addr >> PGSHIFT;
1020 
1021             if (cpu->cfg.ext_svnapot && (pte & PTE_N)) {
1022                 napot_bits = ctzl(ppn) + 1;
1023                 if ((i != (levels - 1)) || (napot_bits != 4)) {
1024                     return TRANSLATE_FAIL;
1025                 }
1026             }
1027 
1028             napot_mask = (1 << napot_bits) - 1;
1029             *physical = (((ppn & ~napot_mask) | (vpn & napot_mask) |
1030                           (vpn & (((target_ulong)1 << ptshift) - 1))
1031                          ) << PGSHIFT) | (addr & ~TARGET_PAGE_MASK);
1032 
1033             /* set permissions on the TLB entry */
1034             if ((pte & PTE_R) || ((pte & PTE_X) && mxr)) {
1035                 *prot |= PAGE_READ;
1036             }
1037             if ((pte & PTE_X)) {
1038                 *prot |= PAGE_EXEC;
1039             }
1040             /* add write permission on stores or if the page is already dirty,
1041                so that we TLB miss on later writes to update the dirty bit */
1042             if ((pte & PTE_W) &&
1043                     (access_type == MMU_DATA_STORE || (pte & PTE_D))) {
1044                 *prot |= PAGE_WRITE;
1045             }
1046             return TRANSLATE_SUCCESS;
1047         }
1048     }
1049     return TRANSLATE_FAIL;
1050 }
1051 
1052 static void raise_mmu_exception(CPURISCVState *env, target_ulong address,
1053                                 MMUAccessType access_type, bool pmp_violation,
1054                                 bool first_stage, bool two_stage)
1055 {
1056     CPUState *cs = env_cpu(env);
1057     int page_fault_exceptions, vm;
1058     uint64_t stap_mode;
1059 
1060     if (riscv_cpu_mxl(env) == MXL_RV32) {
1061         stap_mode = SATP32_MODE;
1062     } else {
1063         stap_mode = SATP64_MODE;
1064     }
1065 
1066     if (first_stage) {
1067         vm = get_field(env->satp, stap_mode);
1068     } else {
1069         vm = get_field(env->hgatp, stap_mode);
1070     }
1071 
1072     page_fault_exceptions = vm != VM_1_10_MBARE && !pmp_violation;
1073 
1074     switch (access_type) {
1075     case MMU_INST_FETCH:
1076         if (riscv_cpu_virt_enabled(env) && !first_stage) {
1077             cs->exception_index = RISCV_EXCP_INST_GUEST_PAGE_FAULT;
1078         } else {
1079             cs->exception_index = page_fault_exceptions ?
1080                 RISCV_EXCP_INST_PAGE_FAULT : RISCV_EXCP_INST_ACCESS_FAULT;
1081         }
1082         break;
1083     case MMU_DATA_LOAD:
1084         if (two_stage && !first_stage) {
1085             cs->exception_index = RISCV_EXCP_LOAD_GUEST_ACCESS_FAULT;
1086         } else {
1087             cs->exception_index = page_fault_exceptions ?
1088                 RISCV_EXCP_LOAD_PAGE_FAULT : RISCV_EXCP_LOAD_ACCESS_FAULT;
1089         }
1090         break;
1091     case MMU_DATA_STORE:
1092         if (two_stage && !first_stage) {
1093             cs->exception_index = RISCV_EXCP_STORE_GUEST_AMO_ACCESS_FAULT;
1094         } else {
1095             cs->exception_index = page_fault_exceptions ?
1096                 RISCV_EXCP_STORE_PAGE_FAULT : RISCV_EXCP_STORE_AMO_ACCESS_FAULT;
1097         }
1098         break;
1099     default:
1100         g_assert_not_reached();
1101     }
1102     env->badaddr = address;
1103     env->two_stage_lookup = two_stage;
1104 }
1105 
1106 hwaddr riscv_cpu_get_phys_page_debug(CPUState *cs, vaddr addr)
1107 {
1108     RISCVCPU *cpu = RISCV_CPU(cs);
1109     CPURISCVState *env = &cpu->env;
1110     hwaddr phys_addr;
1111     int prot;
1112     int mmu_idx = cpu_mmu_index(&cpu->env, false);
1113 
1114     if (get_physical_address(env, &phys_addr, &prot, addr, NULL, 0, mmu_idx,
1115                              true, riscv_cpu_virt_enabled(env), true)) {
1116         return -1;
1117     }
1118 
1119     if (riscv_cpu_virt_enabled(env)) {
1120         if (get_physical_address(env, &phys_addr, &prot, phys_addr, NULL,
1121                                  0, mmu_idx, false, true, true)) {
1122             return -1;
1123         }
1124     }
1125 
1126     return phys_addr & TARGET_PAGE_MASK;
1127 }
1128 
1129 void riscv_cpu_do_transaction_failed(CPUState *cs, hwaddr physaddr,
1130                                      vaddr addr, unsigned size,
1131                                      MMUAccessType access_type,
1132                                      int mmu_idx, MemTxAttrs attrs,
1133                                      MemTxResult response, uintptr_t retaddr)
1134 {
1135     RISCVCPU *cpu = RISCV_CPU(cs);
1136     CPURISCVState *env = &cpu->env;
1137 
1138     if (access_type == MMU_DATA_STORE) {
1139         cs->exception_index = RISCV_EXCP_STORE_AMO_ACCESS_FAULT;
1140     } else if (access_type == MMU_DATA_LOAD) {
1141         cs->exception_index = RISCV_EXCP_LOAD_ACCESS_FAULT;
1142     } else {
1143         cs->exception_index = RISCV_EXCP_INST_ACCESS_FAULT;
1144     }
1145 
1146     env->badaddr = addr;
1147     env->two_stage_lookup = riscv_cpu_virt_enabled(env) ||
1148                             riscv_cpu_two_stage_lookup(mmu_idx);
1149     riscv_raise_exception(&cpu->env, cs->exception_index, retaddr);
1150 }
1151 
1152 void riscv_cpu_do_unaligned_access(CPUState *cs, vaddr addr,
1153                                    MMUAccessType access_type, int mmu_idx,
1154                                    uintptr_t retaddr)
1155 {
1156     RISCVCPU *cpu = RISCV_CPU(cs);
1157     CPURISCVState *env = &cpu->env;
1158     switch (access_type) {
1159     case MMU_INST_FETCH:
1160         cs->exception_index = RISCV_EXCP_INST_ADDR_MIS;
1161         break;
1162     case MMU_DATA_LOAD:
1163         cs->exception_index = RISCV_EXCP_LOAD_ADDR_MIS;
1164         break;
1165     case MMU_DATA_STORE:
1166         cs->exception_index = RISCV_EXCP_STORE_AMO_ADDR_MIS;
1167         break;
1168     default:
1169         g_assert_not_reached();
1170     }
1171     env->badaddr = addr;
1172     env->two_stage_lookup = riscv_cpu_virt_enabled(env) ||
1173                             riscv_cpu_two_stage_lookup(mmu_idx);
1174     riscv_raise_exception(env, cs->exception_index, retaddr);
1175 }
1176 
1177 bool riscv_cpu_tlb_fill(CPUState *cs, vaddr address, int size,
1178                         MMUAccessType access_type, int mmu_idx,
1179                         bool probe, uintptr_t retaddr)
1180 {
1181     RISCVCPU *cpu = RISCV_CPU(cs);
1182     CPURISCVState *env = &cpu->env;
1183     vaddr im_address;
1184     hwaddr pa = 0;
1185     int prot, prot2, prot_pmp;
1186     bool pmp_violation = false;
1187     bool first_stage_error = true;
1188     bool two_stage_lookup = false;
1189     int ret = TRANSLATE_FAIL;
1190     int mode = mmu_idx;
1191     /* default TLB page size */
1192     target_ulong tlb_size = TARGET_PAGE_SIZE;
1193 
1194     env->guest_phys_fault_addr = 0;
1195 
1196     qemu_log_mask(CPU_LOG_MMU, "%s ad %" VADDR_PRIx " rw %d mmu_idx %d\n",
1197                   __func__, address, access_type, mmu_idx);
1198 
1199     /* MPRV does not affect the virtual-machine load/store
1200        instructions, HLV, HLVX, and HSV. */
1201     if (riscv_cpu_two_stage_lookup(mmu_idx)) {
1202         mode = get_field(env->hstatus, HSTATUS_SPVP);
1203     } else if (mode == PRV_M && access_type != MMU_INST_FETCH &&
1204                get_field(env->mstatus, MSTATUS_MPRV)) {
1205         mode = get_field(env->mstatus, MSTATUS_MPP);
1206         if (riscv_has_ext(env, RVH) && get_field(env->mstatus, MSTATUS_MPV)) {
1207             two_stage_lookup = true;
1208         }
1209     }
1210 
1211     if (riscv_cpu_virt_enabled(env) ||
1212         ((riscv_cpu_two_stage_lookup(mmu_idx) || two_stage_lookup) &&
1213          access_type != MMU_INST_FETCH)) {
1214         /* Two stage lookup */
1215         ret = get_physical_address(env, &pa, &prot, address,
1216                                    &env->guest_phys_fault_addr, access_type,
1217                                    mmu_idx, true, true, false);
1218 
1219         /*
1220          * A G-stage exception may be triggered during two state lookup.
1221          * And the env->guest_phys_fault_addr has already been set in
1222          * get_physical_address().
1223          */
1224         if (ret == TRANSLATE_G_STAGE_FAIL) {
1225             first_stage_error = false;
1226             access_type = MMU_DATA_LOAD;
1227         }
1228 
1229         qemu_log_mask(CPU_LOG_MMU,
1230                       "%s 1st-stage address=%" VADDR_PRIx " ret %d physical "
1231                       TARGET_FMT_plx " prot %d\n",
1232                       __func__, address, ret, pa, prot);
1233 
1234         if (ret == TRANSLATE_SUCCESS) {
1235             /* Second stage lookup */
1236             im_address = pa;
1237 
1238             ret = get_physical_address(env, &pa, &prot2, im_address, NULL,
1239                                        access_type, mmu_idx, false, true,
1240                                        false);
1241 
1242             qemu_log_mask(CPU_LOG_MMU,
1243                     "%s 2nd-stage address=%" VADDR_PRIx " ret %d physical "
1244                     TARGET_FMT_plx " prot %d\n",
1245                     __func__, im_address, ret, pa, prot2);
1246 
1247             prot &= prot2;
1248 
1249             if (ret == TRANSLATE_SUCCESS) {
1250                 ret = get_physical_address_pmp(env, &prot_pmp, &tlb_size, pa,
1251                                                size, access_type, mode);
1252 
1253                 qemu_log_mask(CPU_LOG_MMU,
1254                               "%s PMP address=" TARGET_FMT_plx " ret %d prot"
1255                               " %d tlb_size " TARGET_FMT_lu "\n",
1256                               __func__, pa, ret, prot_pmp, tlb_size);
1257 
1258                 prot &= prot_pmp;
1259             }
1260 
1261             if (ret != TRANSLATE_SUCCESS) {
1262                 /*
1263                  * Guest physical address translation failed, this is a HS
1264                  * level exception
1265                  */
1266                 first_stage_error = false;
1267                 env->guest_phys_fault_addr = (im_address |
1268                                               (address &
1269                                                (TARGET_PAGE_SIZE - 1))) >> 2;
1270             }
1271         }
1272     } else {
1273         /* Single stage lookup */
1274         ret = get_physical_address(env, &pa, &prot, address, NULL,
1275                                    access_type, mmu_idx, true, false, false);
1276 
1277         qemu_log_mask(CPU_LOG_MMU,
1278                       "%s address=%" VADDR_PRIx " ret %d physical "
1279                       TARGET_FMT_plx " prot %d\n",
1280                       __func__, address, ret, pa, prot);
1281 
1282         if (ret == TRANSLATE_SUCCESS) {
1283             ret = get_physical_address_pmp(env, &prot_pmp, &tlb_size, pa,
1284                                            size, access_type, mode);
1285 
1286             qemu_log_mask(CPU_LOG_MMU,
1287                           "%s PMP address=" TARGET_FMT_plx " ret %d prot"
1288                           " %d tlb_size " TARGET_FMT_lu "\n",
1289                           __func__, pa, ret, prot_pmp, tlb_size);
1290 
1291             prot &= prot_pmp;
1292         }
1293     }
1294 
1295     if (ret == TRANSLATE_PMP_FAIL) {
1296         pmp_violation = true;
1297     }
1298 
1299     if (ret == TRANSLATE_SUCCESS) {
1300         tlb_set_page(cs, address & ~(tlb_size - 1), pa & ~(tlb_size - 1),
1301                      prot, mmu_idx, tlb_size);
1302         return true;
1303     } else if (probe) {
1304         return false;
1305     } else {
1306         raise_mmu_exception(env, address, access_type, pmp_violation,
1307                             first_stage_error,
1308                             riscv_cpu_virt_enabled(env) ||
1309                                 riscv_cpu_two_stage_lookup(mmu_idx));
1310         riscv_raise_exception(env, cs->exception_index, retaddr);
1311     }
1312 
1313     return true;
1314 }
1315 #endif /* !CONFIG_USER_ONLY */
1316 
1317 /*
1318  * Handle Traps
1319  *
1320  * Adapted from Spike's processor_t::take_trap.
1321  *
1322  */
1323 void riscv_cpu_do_interrupt(CPUState *cs)
1324 {
1325 #if !defined(CONFIG_USER_ONLY)
1326 
1327     RISCVCPU *cpu = RISCV_CPU(cs);
1328     CPURISCVState *env = &cpu->env;
1329     bool write_gva = false;
1330     uint64_t s;
1331 
1332     /* cs->exception is 32-bits wide unlike mcause which is XLEN-bits wide
1333      * so we mask off the MSB and separate into trap type and cause.
1334      */
1335     bool async = !!(cs->exception_index & RISCV_EXCP_INT_FLAG);
1336     target_ulong cause = cs->exception_index & RISCV_EXCP_INT_MASK;
1337     uint64_t deleg = async ? env->mideleg : env->medeleg;
1338     target_ulong tval = 0;
1339     target_ulong htval = 0;
1340     target_ulong mtval2 = 0;
1341 
1342     if  (cause == RISCV_EXCP_SEMIHOST) {
1343         if (env->priv >= PRV_S) {
1344             env->gpr[xA0] = do_common_semihosting(cs);
1345             env->pc += 4;
1346             return;
1347         }
1348         cause = RISCV_EXCP_BREAKPOINT;
1349     }
1350 
1351     if (!async) {
1352         /* set tval to badaddr for traps with address information */
1353         switch (cause) {
1354         case RISCV_EXCP_INST_GUEST_PAGE_FAULT:
1355         case RISCV_EXCP_LOAD_GUEST_ACCESS_FAULT:
1356         case RISCV_EXCP_STORE_GUEST_AMO_ACCESS_FAULT:
1357         case RISCV_EXCP_INST_ADDR_MIS:
1358         case RISCV_EXCP_INST_ACCESS_FAULT:
1359         case RISCV_EXCP_LOAD_ADDR_MIS:
1360         case RISCV_EXCP_STORE_AMO_ADDR_MIS:
1361         case RISCV_EXCP_LOAD_ACCESS_FAULT:
1362         case RISCV_EXCP_STORE_AMO_ACCESS_FAULT:
1363         case RISCV_EXCP_INST_PAGE_FAULT:
1364         case RISCV_EXCP_LOAD_PAGE_FAULT:
1365         case RISCV_EXCP_STORE_PAGE_FAULT:
1366             write_gva = true;
1367             tval = env->badaddr;
1368             break;
1369         case RISCV_EXCP_ILLEGAL_INST:
1370             tval = env->bins;
1371             break;
1372         default:
1373             break;
1374         }
1375         /* ecall is dispatched as one cause so translate based on mode */
1376         if (cause == RISCV_EXCP_U_ECALL) {
1377             assert(env->priv <= 3);
1378 
1379             if (env->priv == PRV_M) {
1380                 cause = RISCV_EXCP_M_ECALL;
1381             } else if (env->priv == PRV_S && riscv_cpu_virt_enabled(env)) {
1382                 cause = RISCV_EXCP_VS_ECALL;
1383             } else if (env->priv == PRV_S && !riscv_cpu_virt_enabled(env)) {
1384                 cause = RISCV_EXCP_S_ECALL;
1385             } else if (env->priv == PRV_U) {
1386                 cause = RISCV_EXCP_U_ECALL;
1387             }
1388         }
1389     }
1390 
1391     trace_riscv_trap(env->mhartid, async, cause, env->pc, tval,
1392                      riscv_cpu_get_trap_name(cause, async));
1393 
1394     qemu_log_mask(CPU_LOG_INT,
1395                   "%s: hart:"TARGET_FMT_ld", async:%d, cause:"TARGET_FMT_lx", "
1396                   "epc:0x"TARGET_FMT_lx", tval:0x"TARGET_FMT_lx", desc=%s\n",
1397                   __func__, env->mhartid, async, cause, env->pc, tval,
1398                   riscv_cpu_get_trap_name(cause, async));
1399 
1400     if (env->priv <= PRV_S &&
1401             cause < TARGET_LONG_BITS && ((deleg >> cause) & 1)) {
1402         /* handle the trap in S-mode */
1403         if (riscv_has_ext(env, RVH)) {
1404             uint64_t hdeleg = async ? env->hideleg : env->hedeleg;
1405 
1406             if (riscv_cpu_virt_enabled(env) && ((hdeleg >> cause) & 1)) {
1407                 /* Trap to VS mode */
1408                 /*
1409                  * See if we need to adjust cause. Yes if its VS mode interrupt
1410                  * no if hypervisor has delegated one of hs mode's interrupt
1411                  */
1412                 if (cause == IRQ_VS_TIMER || cause == IRQ_VS_SOFT ||
1413                     cause == IRQ_VS_EXT) {
1414                     cause = cause - 1;
1415                 }
1416                 write_gva = false;
1417             } else if (riscv_cpu_virt_enabled(env)) {
1418                 /* Trap into HS mode, from virt */
1419                 riscv_cpu_swap_hypervisor_regs(env);
1420                 env->hstatus = set_field(env->hstatus, HSTATUS_SPVP,
1421                                          env->priv);
1422                 env->hstatus = set_field(env->hstatus, HSTATUS_SPV,
1423                                          riscv_cpu_virt_enabled(env));
1424 
1425 
1426                 htval = env->guest_phys_fault_addr;
1427 
1428                 riscv_cpu_set_virt_enabled(env, 0);
1429             } else {
1430                 /* Trap into HS mode */
1431                 env->hstatus = set_field(env->hstatus, HSTATUS_SPV, false);
1432                 htval = env->guest_phys_fault_addr;
1433                 write_gva = false;
1434             }
1435             env->hstatus = set_field(env->hstatus, HSTATUS_GVA, write_gva);
1436         }
1437 
1438         s = env->mstatus;
1439         s = set_field(s, MSTATUS_SPIE, get_field(s, MSTATUS_SIE));
1440         s = set_field(s, MSTATUS_SPP, env->priv);
1441         s = set_field(s, MSTATUS_SIE, 0);
1442         env->mstatus = s;
1443         env->scause = cause | ((target_ulong)async << (TARGET_LONG_BITS - 1));
1444         env->sepc = env->pc;
1445         env->stval = tval;
1446         env->htval = htval;
1447         env->pc = (env->stvec >> 2 << 2) +
1448             ((async && (env->stvec & 3) == 1) ? cause * 4 : 0);
1449         riscv_cpu_set_mode(env, PRV_S);
1450     } else {
1451         /* handle the trap in M-mode */
1452         if (riscv_has_ext(env, RVH)) {
1453             if (riscv_cpu_virt_enabled(env)) {
1454                 riscv_cpu_swap_hypervisor_regs(env);
1455             }
1456             env->mstatus = set_field(env->mstatus, MSTATUS_MPV,
1457                                      riscv_cpu_virt_enabled(env));
1458             if (riscv_cpu_virt_enabled(env) && tval) {
1459                 env->mstatus = set_field(env->mstatus, MSTATUS_GVA, 1);
1460             }
1461 
1462             mtval2 = env->guest_phys_fault_addr;
1463 
1464             /* Trapping to M mode, virt is disabled */
1465             riscv_cpu_set_virt_enabled(env, 0);
1466         }
1467 
1468         s = env->mstatus;
1469         s = set_field(s, MSTATUS_MPIE, get_field(s, MSTATUS_MIE));
1470         s = set_field(s, MSTATUS_MPP, env->priv);
1471         s = set_field(s, MSTATUS_MIE, 0);
1472         env->mstatus = s;
1473         env->mcause = cause | ~(((target_ulong)-1) >> async);
1474         env->mepc = env->pc;
1475         env->mtval = tval;
1476         env->mtval2 = mtval2;
1477         env->pc = (env->mtvec >> 2 << 2) +
1478             ((async && (env->mtvec & 3) == 1) ? cause * 4 : 0);
1479         riscv_cpu_set_mode(env, PRV_M);
1480     }
1481 
1482     /* NOTE: it is not necessary to yield load reservations here. It is only
1483      * necessary for an SC from "another hart" to cause a load reservation
1484      * to be yielded. Refer to the memory consistency model section of the
1485      * RISC-V ISA Specification.
1486      */
1487 
1488     env->two_stage_lookup = false;
1489 #endif
1490     cs->exception_index = RISCV_EXCP_NONE; /* mark handled to qemu */
1491 }
1492