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