xref: /openbmc/qemu/target/riscv/cpu_helper.c (revision dc9acc9c)
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 "instmap.h"
26 #include "tcg/tcg-op.h"
27 #include "trace.h"
28 #include "semihosting/common-semi.h"
29 
30 int riscv_cpu_mmu_index(CPURISCVState *env, bool ifetch)
31 {
32 #ifdef CONFIG_USER_ONLY
33     return 0;
34 #else
35     return env->priv;
36 #endif
37 }
38 
39 void cpu_get_tb_cpu_state(CPURISCVState *env, target_ulong *pc,
40                           target_ulong *cs_base, uint32_t *pflags)
41 {
42     CPUState *cs = env_cpu(env);
43     RISCVCPU *cpu = RISCV_CPU(cs);
44 
45     uint32_t flags = 0;
46 
47     *pc = env->xl == MXL_RV32 ? env->pc & UINT32_MAX : env->pc;
48     *cs_base = 0;
49 
50     if (riscv_has_ext(env, RVV) || cpu->cfg.ext_zve32f || cpu->cfg.ext_zve64f) {
51         /*
52          * If env->vl equals to VLMAX, we can use generic vector operation
53          * expanders (GVEC) to accerlate the vector operations.
54          * However, as LMUL could be a fractional number. The maximum
55          * vector size can be operated might be less than 8 bytes,
56          * which is not supported by GVEC. So we set vl_eq_vlmax flag to true
57          * only when maxsz >= 8 bytes.
58          */
59         uint32_t vlmax = vext_get_vlmax(env_archcpu(env), env->vtype);
60         uint32_t sew = FIELD_EX64(env->vtype, VTYPE, VSEW);
61         uint32_t maxsz = vlmax << sew;
62         bool vl_eq_vlmax = (env->vstart == 0) && (vlmax == env->vl) &&
63                            (maxsz >= 8);
64         flags = FIELD_DP32(flags, TB_FLAGS, VILL, env->vill);
65         flags = FIELD_DP32(flags, TB_FLAGS, SEW, sew);
66         flags = FIELD_DP32(flags, TB_FLAGS, LMUL,
67                     FIELD_EX64(env->vtype, VTYPE, VLMUL));
68         flags = FIELD_DP32(flags, TB_FLAGS, VL_EQ_VLMAX, vl_eq_vlmax);
69         flags = FIELD_DP32(flags, TB_FLAGS, VTA,
70                     FIELD_EX64(env->vtype, VTYPE, VTA));
71         flags = FIELD_DP32(flags, TB_FLAGS, VMA,
72                     FIELD_EX64(env->vtype, VTYPE, VMA));
73     } else {
74         flags = FIELD_DP32(flags, TB_FLAGS, VILL, 1);
75     }
76 
77 #ifdef CONFIG_USER_ONLY
78     flags |= TB_FLAGS_MSTATUS_FS;
79     flags |= TB_FLAGS_MSTATUS_VS;
80 #else
81     flags |= cpu_mmu_index(env, 0);
82     if (riscv_cpu_fp_enabled(env)) {
83         flags |= env->mstatus & MSTATUS_FS;
84     }
85 
86     if (riscv_cpu_vector_enabled(env)) {
87         flags |= env->mstatus & MSTATUS_VS;
88     }
89 
90     if (riscv_has_ext(env, RVH)) {
91         if (env->priv == PRV_M ||
92             (env->priv == PRV_S && !riscv_cpu_virt_enabled(env)) ||
93             (env->priv == PRV_U && !riscv_cpu_virt_enabled(env) &&
94                 get_field(env->hstatus, HSTATUS_HU))) {
95             flags = FIELD_DP32(flags, TB_FLAGS, HLSX, 1);
96         }
97 
98         flags = FIELD_DP32(flags, TB_FLAGS, MSTATUS_HS_FS,
99                            get_field(env->mstatus_hs, MSTATUS_FS));
100 
101         flags = FIELD_DP32(flags, TB_FLAGS, MSTATUS_HS_VS,
102                            get_field(env->mstatus_hs, MSTATUS_VS));
103     }
104 #endif
105 
106     flags = FIELD_DP32(flags, TB_FLAGS, XL, env->xl);
107     if (env->cur_pmmask < (env->xl == MXL_RV32 ? UINT32_MAX : UINT64_MAX)) {
108         flags = FIELD_DP32(flags, TB_FLAGS, PM_MASK_ENABLED, 1);
109     }
110     if (env->cur_pmbase != 0) {
111         flags = FIELD_DP32(flags, TB_FLAGS, PM_BASE_ENABLED, 1);
112     }
113 
114     *pflags = flags;
115 }
116 
117 void riscv_cpu_update_mask(CPURISCVState *env)
118 {
119     target_ulong mask = -1, base = 0;
120     /*
121      * TODO: Current RVJ spec does not specify
122      * how the extension interacts with XLEN.
123      */
124 #ifndef CONFIG_USER_ONLY
125     if (riscv_has_ext(env, RVJ)) {
126         switch (env->priv) {
127         case PRV_M:
128             if (env->mmte & M_PM_ENABLE) {
129                 mask = env->mpmmask;
130                 base = env->mpmbase;
131             }
132             break;
133         case PRV_S:
134             if (env->mmte & S_PM_ENABLE) {
135                 mask = env->spmmask;
136                 base = env->spmbase;
137             }
138             break;
139         case PRV_U:
140             if (env->mmte & U_PM_ENABLE) {
141                 mask = env->upmmask;
142                 base = env->upmbase;
143             }
144             break;
145         default:
146             g_assert_not_reached();
147         }
148     }
149 #endif
150     if (env->xl == MXL_RV32) {
151         env->cur_pmmask = mask & UINT32_MAX;
152         env->cur_pmbase = base & UINT32_MAX;
153     } else {
154         env->cur_pmmask = mask;
155         env->cur_pmbase = base;
156     }
157 }
158 
159 #ifndef CONFIG_USER_ONLY
160 
161 /*
162  * The HS-mode is allowed to configure priority only for the
163  * following VS-mode local interrupts:
164  *
165  * 0  (Reserved interrupt, reads as zero)
166  * 1  Supervisor software interrupt
167  * 4  (Reserved interrupt, reads as zero)
168  * 5  Supervisor timer interrupt
169  * 8  (Reserved interrupt, reads as zero)
170  * 13 (Reserved interrupt)
171  * 14 "
172  * 15 "
173  * 16 "
174  * 17 "
175  * 18 "
176  * 19 "
177  * 20 "
178  * 21 "
179  * 22 "
180  * 23 "
181  */
182 
183 static const int hviprio_index2irq[] = {
184     0, 1, 4, 5, 8, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 };
185 static const int hviprio_index2rdzero[] = {
186     1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
187 
188 int riscv_cpu_hviprio_index2irq(int index, int *out_irq, int *out_rdzero)
189 {
190     if (index < 0 || ARRAY_SIZE(hviprio_index2irq) <= index) {
191         return -EINVAL;
192     }
193 
194     if (out_irq) {
195         *out_irq = hviprio_index2irq[index];
196     }
197 
198     if (out_rdzero) {
199         *out_rdzero = hviprio_index2rdzero[index];
200     }
201 
202     return 0;
203 }
204 
205 /*
206  * Default priorities of local interrupts are defined in the
207  * RISC-V Advanced Interrupt Architecture specification.
208  *
209  * ----------------------------------------------------------------
210  *  Default  |
211  *  Priority | Major Interrupt Numbers
212  * ----------------------------------------------------------------
213  *  Highest  | 47, 23, 46, 45, 22, 44,
214  *           | 43, 21, 42, 41, 20, 40
215  *           |
216  *           | 11 (0b),  3 (03),  7 (07)
217  *           |  9 (09),  1 (01),  5 (05)
218  *           | 12 (0c)
219  *           | 10 (0a),  2 (02),  6 (06)
220  *           |
221  *           | 39, 19, 38, 37, 18, 36,
222  *  Lowest   | 35, 17, 34, 33, 16, 32
223  * ----------------------------------------------------------------
224  */
225 static const uint8_t default_iprio[64] = {
226  /* Custom interrupts 48 to 63 */
227  [63] = IPRIO_MMAXIPRIO,
228  [62] = IPRIO_MMAXIPRIO,
229  [61] = IPRIO_MMAXIPRIO,
230  [60] = IPRIO_MMAXIPRIO,
231  [59] = IPRIO_MMAXIPRIO,
232  [58] = IPRIO_MMAXIPRIO,
233  [57] = IPRIO_MMAXIPRIO,
234  [56] = IPRIO_MMAXIPRIO,
235  [55] = IPRIO_MMAXIPRIO,
236  [54] = IPRIO_MMAXIPRIO,
237  [53] = IPRIO_MMAXIPRIO,
238  [52] = IPRIO_MMAXIPRIO,
239  [51] = IPRIO_MMAXIPRIO,
240  [50] = IPRIO_MMAXIPRIO,
241  [49] = IPRIO_MMAXIPRIO,
242  [48] = IPRIO_MMAXIPRIO,
243 
244  /* Custom interrupts 24 to 31 */
245  [31] = IPRIO_MMAXIPRIO,
246  [30] = IPRIO_MMAXIPRIO,
247  [29] = IPRIO_MMAXIPRIO,
248  [28] = IPRIO_MMAXIPRIO,
249  [27] = IPRIO_MMAXIPRIO,
250  [26] = IPRIO_MMAXIPRIO,
251  [25] = IPRIO_MMAXIPRIO,
252  [24] = IPRIO_MMAXIPRIO,
253 
254  [47] = IPRIO_DEFAULT_UPPER,
255  [23] = IPRIO_DEFAULT_UPPER + 1,
256  [46] = IPRIO_DEFAULT_UPPER + 2,
257  [45] = IPRIO_DEFAULT_UPPER + 3,
258  [22] = IPRIO_DEFAULT_UPPER + 4,
259  [44] = IPRIO_DEFAULT_UPPER + 5,
260 
261  [43] = IPRIO_DEFAULT_UPPER + 6,
262  [21] = IPRIO_DEFAULT_UPPER + 7,
263  [42] = IPRIO_DEFAULT_UPPER + 8,
264  [41] = IPRIO_DEFAULT_UPPER + 9,
265  [20] = IPRIO_DEFAULT_UPPER + 10,
266  [40] = IPRIO_DEFAULT_UPPER + 11,
267 
268  [11] = IPRIO_DEFAULT_M,
269  [3]  = IPRIO_DEFAULT_M + 1,
270  [7]  = IPRIO_DEFAULT_M + 2,
271 
272  [9]  = IPRIO_DEFAULT_S,
273  [1]  = IPRIO_DEFAULT_S + 1,
274  [5]  = IPRIO_DEFAULT_S + 2,
275 
276  [12] = IPRIO_DEFAULT_SGEXT,
277 
278  [10] = IPRIO_DEFAULT_VS,
279  [2]  = IPRIO_DEFAULT_VS + 1,
280  [6]  = IPRIO_DEFAULT_VS + 2,
281 
282  [39] = IPRIO_DEFAULT_LOWER,
283  [19] = IPRIO_DEFAULT_LOWER + 1,
284  [38] = IPRIO_DEFAULT_LOWER + 2,
285  [37] = IPRIO_DEFAULT_LOWER + 3,
286  [18] = IPRIO_DEFAULT_LOWER + 4,
287  [36] = IPRIO_DEFAULT_LOWER + 5,
288 
289  [35] = IPRIO_DEFAULT_LOWER + 6,
290  [17] = IPRIO_DEFAULT_LOWER + 7,
291  [34] = IPRIO_DEFAULT_LOWER + 8,
292  [33] = IPRIO_DEFAULT_LOWER + 9,
293  [16] = IPRIO_DEFAULT_LOWER + 10,
294  [32] = IPRIO_DEFAULT_LOWER + 11,
295 };
296 
297 uint8_t riscv_cpu_default_priority(int irq)
298 {
299     if (irq < 0 || irq > 63) {
300         return IPRIO_MMAXIPRIO;
301     }
302 
303     return default_iprio[irq] ? default_iprio[irq] : IPRIO_MMAXIPRIO;
304 };
305 
306 static int riscv_cpu_pending_to_irq(CPURISCVState *env,
307                                     int extirq, unsigned int extirq_def_prio,
308                                     uint64_t pending, uint8_t *iprio)
309 {
310     RISCVCPU *cpu = env_archcpu(env);
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 (!((extirq == IRQ_M_EXT) ? cpu->cfg.ext_smaia : cpu->cfg.ext_ssaia)) {
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                                 bool two_stage_indirect)
1062 {
1063     CPUState *cs = env_cpu(env);
1064     int page_fault_exceptions, vm;
1065     uint64_t stap_mode;
1066 
1067     if (riscv_cpu_mxl(env) == MXL_RV32) {
1068         stap_mode = SATP32_MODE;
1069     } else {
1070         stap_mode = SATP64_MODE;
1071     }
1072 
1073     if (first_stage) {
1074         vm = get_field(env->satp, stap_mode);
1075     } else {
1076         vm = get_field(env->hgatp, stap_mode);
1077     }
1078 
1079     page_fault_exceptions = vm != VM_1_10_MBARE && !pmp_violation;
1080 
1081     switch (access_type) {
1082     case MMU_INST_FETCH:
1083         if (riscv_cpu_virt_enabled(env) && !first_stage) {
1084             cs->exception_index = RISCV_EXCP_INST_GUEST_PAGE_FAULT;
1085         } else {
1086             cs->exception_index = page_fault_exceptions ?
1087                 RISCV_EXCP_INST_PAGE_FAULT : RISCV_EXCP_INST_ACCESS_FAULT;
1088         }
1089         break;
1090     case MMU_DATA_LOAD:
1091         if (two_stage && !first_stage) {
1092             cs->exception_index = RISCV_EXCP_LOAD_GUEST_ACCESS_FAULT;
1093         } else {
1094             cs->exception_index = page_fault_exceptions ?
1095                 RISCV_EXCP_LOAD_PAGE_FAULT : RISCV_EXCP_LOAD_ACCESS_FAULT;
1096         }
1097         break;
1098     case MMU_DATA_STORE:
1099         if (two_stage && !first_stage) {
1100             cs->exception_index = RISCV_EXCP_STORE_GUEST_AMO_ACCESS_FAULT;
1101         } else {
1102             cs->exception_index = page_fault_exceptions ?
1103                 RISCV_EXCP_STORE_PAGE_FAULT : RISCV_EXCP_STORE_AMO_ACCESS_FAULT;
1104         }
1105         break;
1106     default:
1107         g_assert_not_reached();
1108     }
1109     env->badaddr = address;
1110     env->two_stage_lookup = two_stage;
1111     env->two_stage_indirect_lookup = two_stage_indirect;
1112 }
1113 
1114 hwaddr riscv_cpu_get_phys_page_debug(CPUState *cs, vaddr addr)
1115 {
1116     RISCVCPU *cpu = RISCV_CPU(cs);
1117     CPURISCVState *env = &cpu->env;
1118     hwaddr phys_addr;
1119     int prot;
1120     int mmu_idx = cpu_mmu_index(&cpu->env, false);
1121 
1122     if (get_physical_address(env, &phys_addr, &prot, addr, NULL, 0, mmu_idx,
1123                              true, riscv_cpu_virt_enabled(env), true)) {
1124         return -1;
1125     }
1126 
1127     if (riscv_cpu_virt_enabled(env)) {
1128         if (get_physical_address(env, &phys_addr, &prot, phys_addr, NULL,
1129                                  0, mmu_idx, false, true, true)) {
1130             return -1;
1131         }
1132     }
1133 
1134     return phys_addr & TARGET_PAGE_MASK;
1135 }
1136 
1137 void riscv_cpu_do_transaction_failed(CPUState *cs, hwaddr physaddr,
1138                                      vaddr addr, unsigned size,
1139                                      MMUAccessType access_type,
1140                                      int mmu_idx, MemTxAttrs attrs,
1141                                      MemTxResult response, uintptr_t retaddr)
1142 {
1143     RISCVCPU *cpu = RISCV_CPU(cs);
1144     CPURISCVState *env = &cpu->env;
1145 
1146     if (access_type == MMU_DATA_STORE) {
1147         cs->exception_index = RISCV_EXCP_STORE_AMO_ACCESS_FAULT;
1148     } else if (access_type == MMU_DATA_LOAD) {
1149         cs->exception_index = RISCV_EXCP_LOAD_ACCESS_FAULT;
1150     } else {
1151         cs->exception_index = RISCV_EXCP_INST_ACCESS_FAULT;
1152     }
1153 
1154     env->badaddr = addr;
1155     env->two_stage_lookup = riscv_cpu_virt_enabled(env) ||
1156                             riscv_cpu_two_stage_lookup(mmu_idx);
1157     env->two_stage_indirect_lookup = false;
1158     cpu_loop_exit_restore(cs, retaddr);
1159 }
1160 
1161 void riscv_cpu_do_unaligned_access(CPUState *cs, vaddr addr,
1162                                    MMUAccessType access_type, int mmu_idx,
1163                                    uintptr_t retaddr)
1164 {
1165     RISCVCPU *cpu = RISCV_CPU(cs);
1166     CPURISCVState *env = &cpu->env;
1167     switch (access_type) {
1168     case MMU_INST_FETCH:
1169         cs->exception_index = RISCV_EXCP_INST_ADDR_MIS;
1170         break;
1171     case MMU_DATA_LOAD:
1172         cs->exception_index = RISCV_EXCP_LOAD_ADDR_MIS;
1173         break;
1174     case MMU_DATA_STORE:
1175         cs->exception_index = RISCV_EXCP_STORE_AMO_ADDR_MIS;
1176         break;
1177     default:
1178         g_assert_not_reached();
1179     }
1180     env->badaddr = addr;
1181     env->two_stage_lookup = riscv_cpu_virt_enabled(env) ||
1182                             riscv_cpu_two_stage_lookup(mmu_idx);
1183     env->two_stage_indirect_lookup = false;
1184     cpu_loop_exit_restore(cs, retaddr);
1185 }
1186 
1187 bool riscv_cpu_tlb_fill(CPUState *cs, vaddr address, int size,
1188                         MMUAccessType access_type, int mmu_idx,
1189                         bool probe, uintptr_t retaddr)
1190 {
1191     RISCVCPU *cpu = RISCV_CPU(cs);
1192     CPURISCVState *env = &cpu->env;
1193     vaddr im_address;
1194     hwaddr pa = 0;
1195     int prot, prot2, prot_pmp;
1196     bool pmp_violation = false;
1197     bool first_stage_error = true;
1198     bool two_stage_lookup = false;
1199     bool two_stage_indirect_error = false;
1200     int ret = TRANSLATE_FAIL;
1201     int mode = mmu_idx;
1202     /* default TLB page size */
1203     target_ulong tlb_size = TARGET_PAGE_SIZE;
1204 
1205     env->guest_phys_fault_addr = 0;
1206 
1207     qemu_log_mask(CPU_LOG_MMU, "%s ad %" VADDR_PRIx " rw %d mmu_idx %d\n",
1208                   __func__, address, access_type, mmu_idx);
1209 
1210     /* MPRV does not affect the virtual-machine load/store
1211        instructions, HLV, HLVX, and HSV. */
1212     if (riscv_cpu_two_stage_lookup(mmu_idx)) {
1213         mode = get_field(env->hstatus, HSTATUS_SPVP);
1214     } else if (mode == PRV_M && access_type != MMU_INST_FETCH &&
1215                get_field(env->mstatus, MSTATUS_MPRV)) {
1216         mode = get_field(env->mstatus, MSTATUS_MPP);
1217         if (riscv_has_ext(env, RVH) && get_field(env->mstatus, MSTATUS_MPV)) {
1218             two_stage_lookup = true;
1219         }
1220     }
1221 
1222     if (riscv_cpu_virt_enabled(env) ||
1223         ((riscv_cpu_two_stage_lookup(mmu_idx) || two_stage_lookup) &&
1224          access_type != MMU_INST_FETCH)) {
1225         /* Two stage lookup */
1226         ret = get_physical_address(env, &pa, &prot, address,
1227                                    &env->guest_phys_fault_addr, access_type,
1228                                    mmu_idx, true, true, false);
1229 
1230         /*
1231          * A G-stage exception may be triggered during two state lookup.
1232          * And the env->guest_phys_fault_addr has already been set in
1233          * get_physical_address().
1234          */
1235         if (ret == TRANSLATE_G_STAGE_FAIL) {
1236             first_stage_error = false;
1237             two_stage_indirect_error = true;
1238             access_type = MMU_DATA_LOAD;
1239         }
1240 
1241         qemu_log_mask(CPU_LOG_MMU,
1242                       "%s 1st-stage address=%" VADDR_PRIx " ret %d physical "
1243                       TARGET_FMT_plx " prot %d\n",
1244                       __func__, address, ret, pa, prot);
1245 
1246         if (ret == TRANSLATE_SUCCESS) {
1247             /* Second stage lookup */
1248             im_address = pa;
1249 
1250             ret = get_physical_address(env, &pa, &prot2, im_address, NULL,
1251                                        access_type, mmu_idx, false, true,
1252                                        false);
1253 
1254             qemu_log_mask(CPU_LOG_MMU,
1255                     "%s 2nd-stage address=%" VADDR_PRIx " ret %d physical "
1256                     TARGET_FMT_plx " prot %d\n",
1257                     __func__, im_address, ret, pa, prot2);
1258 
1259             prot &= prot2;
1260 
1261             if (ret == TRANSLATE_SUCCESS) {
1262                 ret = get_physical_address_pmp(env, &prot_pmp, &tlb_size, pa,
1263                                                size, access_type, mode);
1264 
1265                 qemu_log_mask(CPU_LOG_MMU,
1266                               "%s PMP address=" TARGET_FMT_plx " ret %d prot"
1267                               " %d tlb_size " TARGET_FMT_lu "\n",
1268                               __func__, pa, ret, prot_pmp, tlb_size);
1269 
1270                 prot &= prot_pmp;
1271             }
1272 
1273             if (ret != TRANSLATE_SUCCESS) {
1274                 /*
1275                  * Guest physical address translation failed, this is a HS
1276                  * level exception
1277                  */
1278                 first_stage_error = false;
1279                 env->guest_phys_fault_addr = (im_address |
1280                                               (address &
1281                                                (TARGET_PAGE_SIZE - 1))) >> 2;
1282             }
1283         }
1284     } else {
1285         /* Single stage lookup */
1286         ret = get_physical_address(env, &pa, &prot, address, NULL,
1287                                    access_type, mmu_idx, true, false, false);
1288 
1289         qemu_log_mask(CPU_LOG_MMU,
1290                       "%s address=%" VADDR_PRIx " ret %d physical "
1291                       TARGET_FMT_plx " prot %d\n",
1292                       __func__, address, ret, pa, prot);
1293 
1294         if (ret == TRANSLATE_SUCCESS) {
1295             ret = get_physical_address_pmp(env, &prot_pmp, &tlb_size, pa,
1296                                            size, access_type, mode);
1297 
1298             qemu_log_mask(CPU_LOG_MMU,
1299                           "%s PMP address=" TARGET_FMT_plx " ret %d prot"
1300                           " %d tlb_size " TARGET_FMT_lu "\n",
1301                           __func__, pa, ret, prot_pmp, tlb_size);
1302 
1303             prot &= prot_pmp;
1304         }
1305     }
1306 
1307     if (ret == TRANSLATE_PMP_FAIL) {
1308         pmp_violation = true;
1309     }
1310 
1311     if (ret == TRANSLATE_SUCCESS) {
1312         tlb_set_page(cs, address & ~(tlb_size - 1), pa & ~(tlb_size - 1),
1313                      prot, mmu_idx, tlb_size);
1314         return true;
1315     } else if (probe) {
1316         return false;
1317     } else {
1318         raise_mmu_exception(env, address, access_type, pmp_violation,
1319                             first_stage_error,
1320                             riscv_cpu_virt_enabled(env) ||
1321                                 riscv_cpu_two_stage_lookup(mmu_idx),
1322                             two_stage_indirect_error);
1323         cpu_loop_exit_restore(cs, retaddr);
1324     }
1325 
1326     return true;
1327 }
1328 
1329 static target_ulong riscv_transformed_insn(CPURISCVState *env,
1330                                            target_ulong insn,
1331                                            target_ulong taddr)
1332 {
1333     target_ulong xinsn = 0;
1334     target_ulong access_rs1 = 0, access_imm = 0, access_size = 0;
1335 
1336     /*
1337      * Only Quadrant 0 and Quadrant 2 of RVC instruction space need to
1338      * be uncompressed. The Quadrant 1 of RVC instruction space need
1339      * not be transformed because these instructions won't generate
1340      * any load/store trap.
1341      */
1342 
1343     if ((insn & 0x3) != 0x3) {
1344         /* Transform 16bit instruction into 32bit instruction */
1345         switch (GET_C_OP(insn)) {
1346         case OPC_RISC_C_OP_QUAD0: /* Quadrant 0 */
1347             switch (GET_C_FUNC(insn)) {
1348             case OPC_RISC_C_FUNC_FLD_LQ:
1349                 if (riscv_cpu_xlen(env) != 128) { /* C.FLD (RV32/64) */
1350                     xinsn = OPC_RISC_FLD;
1351                     xinsn = SET_RD(xinsn, GET_C_RS2S(insn));
1352                     access_rs1 = GET_C_RS1S(insn);
1353                     access_imm = GET_C_LD_IMM(insn);
1354                     access_size = 8;
1355                 }
1356                 break;
1357             case OPC_RISC_C_FUNC_LW: /* C.LW */
1358                 xinsn = OPC_RISC_LW;
1359                 xinsn = SET_RD(xinsn, GET_C_RS2S(insn));
1360                 access_rs1 = GET_C_RS1S(insn);
1361                 access_imm = GET_C_LW_IMM(insn);
1362                 access_size = 4;
1363                 break;
1364             case OPC_RISC_C_FUNC_FLW_LD:
1365                 if (riscv_cpu_xlen(env) == 32) { /* C.FLW (RV32) */
1366                     xinsn = OPC_RISC_FLW;
1367                     xinsn = SET_RD(xinsn, GET_C_RS2S(insn));
1368                     access_rs1 = GET_C_RS1S(insn);
1369                     access_imm = GET_C_LW_IMM(insn);
1370                     access_size = 4;
1371                 } else { /* C.LD (RV64/RV128) */
1372                     xinsn = OPC_RISC_LD;
1373                     xinsn = SET_RD(xinsn, GET_C_RS2S(insn));
1374                     access_rs1 = GET_C_RS1S(insn);
1375                     access_imm = GET_C_LD_IMM(insn);
1376                     access_size = 8;
1377                 }
1378                 break;
1379             case OPC_RISC_C_FUNC_FSD_SQ:
1380                 if (riscv_cpu_xlen(env) != 128) { /* C.FSD (RV32/64) */
1381                     xinsn = OPC_RISC_FSD;
1382                     xinsn = SET_RS2(xinsn, GET_C_RS2S(insn));
1383                     access_rs1 = GET_C_RS1S(insn);
1384                     access_imm = GET_C_SD_IMM(insn);
1385                     access_size = 8;
1386                 }
1387                 break;
1388             case OPC_RISC_C_FUNC_SW: /* C.SW */
1389                 xinsn = OPC_RISC_SW;
1390                 xinsn = SET_RS2(xinsn, GET_C_RS2S(insn));
1391                 access_rs1 = GET_C_RS1S(insn);
1392                 access_imm = GET_C_SW_IMM(insn);
1393                 access_size = 4;
1394                 break;
1395             case OPC_RISC_C_FUNC_FSW_SD:
1396                 if (riscv_cpu_xlen(env) == 32) { /* C.FSW (RV32) */
1397                     xinsn = OPC_RISC_FSW;
1398                     xinsn = SET_RS2(xinsn, GET_C_RS2S(insn));
1399                     access_rs1 = GET_C_RS1S(insn);
1400                     access_imm = GET_C_SW_IMM(insn);
1401                     access_size = 4;
1402                 } else { /* C.SD (RV64/RV128) */
1403                     xinsn = OPC_RISC_SD;
1404                     xinsn = SET_RS2(xinsn, GET_C_RS2S(insn));
1405                     access_rs1 = GET_C_RS1S(insn);
1406                     access_imm = GET_C_SD_IMM(insn);
1407                     access_size = 8;
1408                 }
1409                 break;
1410             default:
1411                 break;
1412             }
1413             break;
1414         case OPC_RISC_C_OP_QUAD2: /* Quadrant 2 */
1415             switch (GET_C_FUNC(insn)) {
1416             case OPC_RISC_C_FUNC_FLDSP_LQSP:
1417                 if (riscv_cpu_xlen(env) != 128) { /* C.FLDSP (RV32/64) */
1418                     xinsn = OPC_RISC_FLD;
1419                     xinsn = SET_RD(xinsn, GET_C_RD(insn));
1420                     access_rs1 = 2;
1421                     access_imm = GET_C_LDSP_IMM(insn);
1422                     access_size = 8;
1423                 }
1424                 break;
1425             case OPC_RISC_C_FUNC_LWSP: /* C.LWSP */
1426                 xinsn = OPC_RISC_LW;
1427                 xinsn = SET_RD(xinsn, GET_C_RD(insn));
1428                 access_rs1 = 2;
1429                 access_imm = GET_C_LWSP_IMM(insn);
1430                 access_size = 4;
1431                 break;
1432             case OPC_RISC_C_FUNC_FLWSP_LDSP:
1433                 if (riscv_cpu_xlen(env) == 32) { /* C.FLWSP (RV32) */
1434                     xinsn = OPC_RISC_FLW;
1435                     xinsn = SET_RD(xinsn, GET_C_RD(insn));
1436                     access_rs1 = 2;
1437                     access_imm = GET_C_LWSP_IMM(insn);
1438                     access_size = 4;
1439                 } else { /* C.LDSP (RV64/RV128) */
1440                     xinsn = OPC_RISC_LD;
1441                     xinsn = SET_RD(xinsn, GET_C_RD(insn));
1442                     access_rs1 = 2;
1443                     access_imm = GET_C_LDSP_IMM(insn);
1444                     access_size = 8;
1445                 }
1446                 break;
1447             case OPC_RISC_C_FUNC_FSDSP_SQSP:
1448                 if (riscv_cpu_xlen(env) != 128) { /* C.FSDSP (RV32/64) */
1449                     xinsn = OPC_RISC_FSD;
1450                     xinsn = SET_RS2(xinsn, GET_C_RS2(insn));
1451                     access_rs1 = 2;
1452                     access_imm = GET_C_SDSP_IMM(insn);
1453                     access_size = 8;
1454                 }
1455                 break;
1456             case OPC_RISC_C_FUNC_SWSP: /* C.SWSP */
1457                 xinsn = OPC_RISC_SW;
1458                 xinsn = SET_RS2(xinsn, GET_C_RS2(insn));
1459                 access_rs1 = 2;
1460                 access_imm = GET_C_SWSP_IMM(insn);
1461                 access_size = 4;
1462                 break;
1463             case 7:
1464                 if (riscv_cpu_xlen(env) == 32) { /* C.FSWSP (RV32) */
1465                     xinsn = OPC_RISC_FSW;
1466                     xinsn = SET_RS2(xinsn, GET_C_RS2(insn));
1467                     access_rs1 = 2;
1468                     access_imm = GET_C_SWSP_IMM(insn);
1469                     access_size = 4;
1470                 } else { /* C.SDSP (RV64/RV128) */
1471                     xinsn = OPC_RISC_SD;
1472                     xinsn = SET_RS2(xinsn, GET_C_RS2(insn));
1473                     access_rs1 = 2;
1474                     access_imm = GET_C_SDSP_IMM(insn);
1475                     access_size = 8;
1476                 }
1477                 break;
1478             default:
1479                 break;
1480             }
1481             break;
1482         default:
1483             break;
1484         }
1485 
1486         /*
1487          * Clear Bit1 of transformed instruction to indicate that
1488          * original insruction was a 16bit instruction
1489          */
1490         xinsn &= ~((target_ulong)0x2);
1491     } else {
1492         /* Transform 32bit (or wider) instructions */
1493         switch (MASK_OP_MAJOR(insn)) {
1494         case OPC_RISC_ATOMIC:
1495             xinsn = insn;
1496             access_rs1 = GET_RS1(insn);
1497             access_size = 1 << GET_FUNCT3(insn);
1498             break;
1499         case OPC_RISC_LOAD:
1500         case OPC_RISC_FP_LOAD:
1501             xinsn = SET_I_IMM(insn, 0);
1502             access_rs1 = GET_RS1(insn);
1503             access_imm = GET_IMM(insn);
1504             access_size = 1 << GET_FUNCT3(insn);
1505             break;
1506         case OPC_RISC_STORE:
1507         case OPC_RISC_FP_STORE:
1508             xinsn = SET_S_IMM(insn, 0);
1509             access_rs1 = GET_RS1(insn);
1510             access_imm = GET_STORE_IMM(insn);
1511             access_size = 1 << GET_FUNCT3(insn);
1512             break;
1513         case OPC_RISC_SYSTEM:
1514             if (MASK_OP_SYSTEM(insn) == OPC_RISC_HLVHSV) {
1515                 xinsn = insn;
1516                 access_rs1 = GET_RS1(insn);
1517                 access_size = 1 << ((GET_FUNCT7(insn) >> 1) & 0x3);
1518                 access_size = 1 << access_size;
1519             }
1520             break;
1521         default:
1522             break;
1523         }
1524     }
1525 
1526     if (access_size) {
1527         xinsn = SET_RS1(xinsn, (taddr - (env->gpr[access_rs1] + access_imm)) &
1528                                (access_size - 1));
1529     }
1530 
1531     return xinsn;
1532 }
1533 #endif /* !CONFIG_USER_ONLY */
1534 
1535 /*
1536  * Handle Traps
1537  *
1538  * Adapted from Spike's processor_t::take_trap.
1539  *
1540  */
1541 void riscv_cpu_do_interrupt(CPUState *cs)
1542 {
1543 #if !defined(CONFIG_USER_ONLY)
1544 
1545     RISCVCPU *cpu = RISCV_CPU(cs);
1546     CPURISCVState *env = &cpu->env;
1547     bool write_gva = false;
1548     uint64_t s;
1549 
1550     /* cs->exception is 32-bits wide unlike mcause which is XLEN-bits wide
1551      * so we mask off the MSB and separate into trap type and cause.
1552      */
1553     bool async = !!(cs->exception_index & RISCV_EXCP_INT_FLAG);
1554     target_ulong cause = cs->exception_index & RISCV_EXCP_INT_MASK;
1555     uint64_t deleg = async ? env->mideleg : env->medeleg;
1556     target_ulong tval = 0;
1557     target_ulong tinst = 0;
1558     target_ulong htval = 0;
1559     target_ulong mtval2 = 0;
1560 
1561     if  (cause == RISCV_EXCP_SEMIHOST) {
1562         if (env->priv >= PRV_S) {
1563             do_common_semihosting(cs);
1564             env->pc += 4;
1565             return;
1566         }
1567         cause = RISCV_EXCP_BREAKPOINT;
1568     }
1569 
1570     if (!async) {
1571         /* set tval to badaddr for traps with address information */
1572         switch (cause) {
1573         case RISCV_EXCP_LOAD_GUEST_ACCESS_FAULT:
1574         case RISCV_EXCP_STORE_GUEST_AMO_ACCESS_FAULT:
1575         case RISCV_EXCP_LOAD_ADDR_MIS:
1576         case RISCV_EXCP_STORE_AMO_ADDR_MIS:
1577         case RISCV_EXCP_LOAD_ACCESS_FAULT:
1578         case RISCV_EXCP_STORE_AMO_ACCESS_FAULT:
1579         case RISCV_EXCP_LOAD_PAGE_FAULT:
1580         case RISCV_EXCP_STORE_PAGE_FAULT:
1581             write_gva = env->two_stage_lookup;
1582             tval = env->badaddr;
1583             if (env->two_stage_indirect_lookup) {
1584                 /*
1585                  * special pseudoinstruction for G-stage fault taken while
1586                  * doing VS-stage page table walk.
1587                  */
1588                 tinst = (riscv_cpu_xlen(env) == 32) ? 0x00002000 : 0x00003000;
1589             } else {
1590                 /*
1591                  * The "Addr. Offset" field in transformed instruction is
1592                  * non-zero only for misaligned access.
1593                  */
1594                 tinst = riscv_transformed_insn(env, env->bins, tval);
1595             }
1596             break;
1597         case RISCV_EXCP_INST_GUEST_PAGE_FAULT:
1598         case RISCV_EXCP_INST_ADDR_MIS:
1599         case RISCV_EXCP_INST_ACCESS_FAULT:
1600         case RISCV_EXCP_INST_PAGE_FAULT:
1601             write_gva = env->two_stage_lookup;
1602             tval = env->badaddr;
1603             if (env->two_stage_indirect_lookup) {
1604                 /*
1605                  * special pseudoinstruction for G-stage fault taken while
1606                  * doing VS-stage page table walk.
1607                  */
1608                 tinst = (riscv_cpu_xlen(env) == 32) ? 0x00002000 : 0x00003000;
1609             }
1610             break;
1611         case RISCV_EXCP_ILLEGAL_INST:
1612         case RISCV_EXCP_VIRT_INSTRUCTION_FAULT:
1613             tval = env->bins;
1614             break;
1615         default:
1616             break;
1617         }
1618         /* ecall is dispatched as one cause so translate based on mode */
1619         if (cause == RISCV_EXCP_U_ECALL) {
1620             assert(env->priv <= 3);
1621 
1622             if (env->priv == PRV_M) {
1623                 cause = RISCV_EXCP_M_ECALL;
1624             } else if (env->priv == PRV_S && riscv_cpu_virt_enabled(env)) {
1625                 cause = RISCV_EXCP_VS_ECALL;
1626             } else if (env->priv == PRV_S && !riscv_cpu_virt_enabled(env)) {
1627                 cause = RISCV_EXCP_S_ECALL;
1628             } else if (env->priv == PRV_U) {
1629                 cause = RISCV_EXCP_U_ECALL;
1630             }
1631         }
1632     }
1633 
1634     trace_riscv_trap(env->mhartid, async, cause, env->pc, tval,
1635                      riscv_cpu_get_trap_name(cause, async));
1636 
1637     qemu_log_mask(CPU_LOG_INT,
1638                   "%s: hart:"TARGET_FMT_ld", async:%d, cause:"TARGET_FMT_lx", "
1639                   "epc:0x"TARGET_FMT_lx", tval:0x"TARGET_FMT_lx", desc=%s\n",
1640                   __func__, env->mhartid, async, cause, env->pc, tval,
1641                   riscv_cpu_get_trap_name(cause, async));
1642 
1643     if (env->priv <= PRV_S &&
1644             cause < TARGET_LONG_BITS && ((deleg >> cause) & 1)) {
1645         /* handle the trap in S-mode */
1646         if (riscv_has_ext(env, RVH)) {
1647             uint64_t hdeleg = async ? env->hideleg : env->hedeleg;
1648 
1649             if (riscv_cpu_virt_enabled(env) && ((hdeleg >> cause) & 1)) {
1650                 /* Trap to VS mode */
1651                 /*
1652                  * See if we need to adjust cause. Yes if its VS mode interrupt
1653                  * no if hypervisor has delegated one of hs mode's interrupt
1654                  */
1655                 if (cause == IRQ_VS_TIMER || cause == IRQ_VS_SOFT ||
1656                     cause == IRQ_VS_EXT) {
1657                     cause = cause - 1;
1658                 }
1659                 write_gva = false;
1660             } else if (riscv_cpu_virt_enabled(env)) {
1661                 /* Trap into HS mode, from virt */
1662                 riscv_cpu_swap_hypervisor_regs(env);
1663                 env->hstatus = set_field(env->hstatus, HSTATUS_SPVP,
1664                                          env->priv);
1665                 env->hstatus = set_field(env->hstatus, HSTATUS_SPV,
1666                                          riscv_cpu_virt_enabled(env));
1667 
1668 
1669                 htval = env->guest_phys_fault_addr;
1670 
1671                 riscv_cpu_set_virt_enabled(env, 0);
1672             } else {
1673                 /* Trap into HS mode */
1674                 env->hstatus = set_field(env->hstatus, HSTATUS_SPV, false);
1675                 htval = env->guest_phys_fault_addr;
1676             }
1677             env->hstatus = set_field(env->hstatus, HSTATUS_GVA, write_gva);
1678         }
1679 
1680         s = env->mstatus;
1681         s = set_field(s, MSTATUS_SPIE, get_field(s, MSTATUS_SIE));
1682         s = set_field(s, MSTATUS_SPP, env->priv);
1683         s = set_field(s, MSTATUS_SIE, 0);
1684         env->mstatus = s;
1685         env->scause = cause | ((target_ulong)async << (TARGET_LONG_BITS - 1));
1686         env->sepc = env->pc;
1687         env->stval = tval;
1688         env->htval = htval;
1689         env->htinst = tinst;
1690         env->pc = (env->stvec >> 2 << 2) +
1691             ((async && (env->stvec & 3) == 1) ? cause * 4 : 0);
1692         riscv_cpu_set_mode(env, PRV_S);
1693     } else {
1694         /* handle the trap in M-mode */
1695         if (riscv_has_ext(env, RVH)) {
1696             if (riscv_cpu_virt_enabled(env)) {
1697                 riscv_cpu_swap_hypervisor_regs(env);
1698             }
1699             env->mstatus = set_field(env->mstatus, MSTATUS_MPV,
1700                                      riscv_cpu_virt_enabled(env));
1701             if (riscv_cpu_virt_enabled(env) && tval) {
1702                 env->mstatus = set_field(env->mstatus, MSTATUS_GVA, 1);
1703             }
1704 
1705             mtval2 = env->guest_phys_fault_addr;
1706 
1707             /* Trapping to M mode, virt is disabled */
1708             riscv_cpu_set_virt_enabled(env, 0);
1709         }
1710 
1711         s = env->mstatus;
1712         s = set_field(s, MSTATUS_MPIE, get_field(s, MSTATUS_MIE));
1713         s = set_field(s, MSTATUS_MPP, env->priv);
1714         s = set_field(s, MSTATUS_MIE, 0);
1715         env->mstatus = s;
1716         env->mcause = cause | ~(((target_ulong)-1) >> async);
1717         env->mepc = env->pc;
1718         env->mtval = tval;
1719         env->mtval2 = mtval2;
1720         env->mtinst = tinst;
1721         env->pc = (env->mtvec >> 2 << 2) +
1722             ((async && (env->mtvec & 3) == 1) ? cause * 4 : 0);
1723         riscv_cpu_set_mode(env, PRV_M);
1724     }
1725 
1726     /* NOTE: it is not necessary to yield load reservations here. It is only
1727      * necessary for an SC from "another hart" to cause a load reservation
1728      * to be yielded. Refer to the memory consistency model section of the
1729      * RISC-V ISA Specification.
1730      */
1731 
1732     env->two_stage_lookup = false;
1733     env->two_stage_indirect_lookup = false;
1734 #endif
1735     cs->exception_index = RISCV_EXCP_NONE; /* mark handled to qemu */
1736 }
1737