xref: /openbmc/qemu/target/riscv/cpu_helper.c (revision 3ec0fe18)
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     uint64_t vstip = (env->vstime_irq) ? MIP_VSTIP : 0;
350 
351     return (env->mip | vsgein | vstip) & env->mie;
352 }
353 
354 int riscv_cpu_mirq_pending(CPURISCVState *env)
355 {
356     uint64_t irqs = riscv_cpu_all_pending(env) & ~env->mideleg &
357                     ~(MIP_SGEIP | MIP_VSSIP | MIP_VSTIP | MIP_VSEIP);
358 
359     return riscv_cpu_pending_to_irq(env, IRQ_M_EXT, IPRIO_DEFAULT_M,
360                                     irqs, env->miprio);
361 }
362 
363 int riscv_cpu_sirq_pending(CPURISCVState *env)
364 {
365     uint64_t irqs = riscv_cpu_all_pending(env) & env->mideleg &
366                     ~(MIP_VSSIP | MIP_VSTIP | MIP_VSEIP);
367 
368     return riscv_cpu_pending_to_irq(env, IRQ_S_EXT, IPRIO_DEFAULT_S,
369                                     irqs, env->siprio);
370 }
371 
372 int riscv_cpu_vsirq_pending(CPURISCVState *env)
373 {
374     uint64_t irqs = riscv_cpu_all_pending(env) & env->mideleg &
375                     (MIP_VSSIP | MIP_VSTIP | MIP_VSEIP);
376 
377     return riscv_cpu_pending_to_irq(env, IRQ_S_EXT, IPRIO_DEFAULT_S,
378                                     irqs >> 1, env->hviprio);
379 }
380 
381 static int riscv_cpu_local_irq_pending(CPURISCVState *env)
382 {
383     int virq;
384     uint64_t irqs, pending, mie, hsie, vsie;
385 
386     /* Determine interrupt enable state of all privilege modes */
387     if (riscv_cpu_virt_enabled(env)) {
388         mie = 1;
389         hsie = 1;
390         vsie = (env->priv < PRV_S) ||
391                (env->priv == PRV_S && get_field(env->mstatus, MSTATUS_SIE));
392     } else {
393         mie = (env->priv < PRV_M) ||
394               (env->priv == PRV_M && get_field(env->mstatus, MSTATUS_MIE));
395         hsie = (env->priv < PRV_S) ||
396                (env->priv == PRV_S && get_field(env->mstatus, MSTATUS_SIE));
397         vsie = 0;
398     }
399 
400     /* Determine all pending interrupts */
401     pending = riscv_cpu_all_pending(env);
402 
403     /* Check M-mode interrupts */
404     irqs = pending & ~env->mideleg & -mie;
405     if (irqs) {
406         return riscv_cpu_pending_to_irq(env, IRQ_M_EXT, IPRIO_DEFAULT_M,
407                                         irqs, env->miprio);
408     }
409 
410     /* Check HS-mode interrupts */
411     irqs = pending & env->mideleg & ~env->hideleg & -hsie;
412     if (irqs) {
413         return riscv_cpu_pending_to_irq(env, IRQ_S_EXT, IPRIO_DEFAULT_S,
414                                         irqs, env->siprio);
415     }
416 
417     /* Check VS-mode interrupts */
418     irqs = pending & env->mideleg & env->hideleg & -vsie;
419     if (irqs) {
420         virq = riscv_cpu_pending_to_irq(env, IRQ_S_EXT, IPRIO_DEFAULT_S,
421                                         irqs >> 1, env->hviprio);
422         return (virq <= 0) ? virq : virq + 1;
423     }
424 
425     /* Indicate no pending interrupt */
426     return RISCV_EXCP_NONE;
427 }
428 
429 bool riscv_cpu_exec_interrupt(CPUState *cs, int interrupt_request)
430 {
431     if (interrupt_request & CPU_INTERRUPT_HARD) {
432         RISCVCPU *cpu = RISCV_CPU(cs);
433         CPURISCVState *env = &cpu->env;
434         int interruptno = riscv_cpu_local_irq_pending(env);
435         if (interruptno >= 0) {
436             cs->exception_index = RISCV_EXCP_INT_FLAG | interruptno;
437             riscv_cpu_do_interrupt(cs);
438             return true;
439         }
440     }
441     return false;
442 }
443 
444 /* Return true is floating point support is currently enabled */
445 bool riscv_cpu_fp_enabled(CPURISCVState *env)
446 {
447     if (env->mstatus & MSTATUS_FS) {
448         if (riscv_cpu_virt_enabled(env) && !(env->mstatus_hs & MSTATUS_FS)) {
449             return false;
450         }
451         return true;
452     }
453 
454     return false;
455 }
456 
457 /* Return true is vector support is currently enabled */
458 bool riscv_cpu_vector_enabled(CPURISCVState *env)
459 {
460     if (env->mstatus & MSTATUS_VS) {
461         if (riscv_cpu_virt_enabled(env) && !(env->mstatus_hs & MSTATUS_VS)) {
462             return false;
463         }
464         return true;
465     }
466 
467     return false;
468 }
469 
470 void riscv_cpu_swap_hypervisor_regs(CPURISCVState *env)
471 {
472     uint64_t mstatus_mask = MSTATUS_MXR | MSTATUS_SUM |
473                             MSTATUS_SPP | MSTATUS_SPIE | MSTATUS_SIE |
474                             MSTATUS64_UXL | MSTATUS_VS;
475 
476     if (riscv_has_ext(env, RVF)) {
477         mstatus_mask |= MSTATUS_FS;
478     }
479     bool current_virt = riscv_cpu_virt_enabled(env);
480 
481     g_assert(riscv_has_ext(env, RVH));
482 
483     if (current_virt) {
484         /* Current V=1 and we are about to change to V=0 */
485         env->vsstatus = env->mstatus & mstatus_mask;
486         env->mstatus &= ~mstatus_mask;
487         env->mstatus |= env->mstatus_hs;
488 
489         env->vstvec = env->stvec;
490         env->stvec = env->stvec_hs;
491 
492         env->vsscratch = env->sscratch;
493         env->sscratch = env->sscratch_hs;
494 
495         env->vsepc = env->sepc;
496         env->sepc = env->sepc_hs;
497 
498         env->vscause = env->scause;
499         env->scause = env->scause_hs;
500 
501         env->vstval = env->stval;
502         env->stval = env->stval_hs;
503 
504         env->vsatp = env->satp;
505         env->satp = env->satp_hs;
506     } else {
507         /* Current V=0 and we are about to change to V=1 */
508         env->mstatus_hs = env->mstatus & mstatus_mask;
509         env->mstatus &= ~mstatus_mask;
510         env->mstatus |= env->vsstatus;
511 
512         env->stvec_hs = env->stvec;
513         env->stvec = env->vstvec;
514 
515         env->sscratch_hs = env->sscratch;
516         env->sscratch = env->vsscratch;
517 
518         env->sepc_hs = env->sepc;
519         env->sepc = env->vsepc;
520 
521         env->scause_hs = env->scause;
522         env->scause = env->vscause;
523 
524         env->stval_hs = env->stval;
525         env->stval = env->vstval;
526 
527         env->satp_hs = env->satp;
528         env->satp = env->vsatp;
529     }
530 }
531 
532 target_ulong riscv_cpu_get_geilen(CPURISCVState *env)
533 {
534     if (!riscv_has_ext(env, RVH)) {
535         return 0;
536     }
537 
538     return env->geilen;
539 }
540 
541 void riscv_cpu_set_geilen(CPURISCVState *env, target_ulong geilen)
542 {
543     if (!riscv_has_ext(env, RVH)) {
544         return;
545     }
546 
547     if (geilen > (TARGET_LONG_BITS - 1)) {
548         return;
549     }
550 
551     env->geilen = geilen;
552 }
553 
554 bool riscv_cpu_virt_enabled(CPURISCVState *env)
555 {
556     if (!riscv_has_ext(env, RVH)) {
557         return false;
558     }
559 
560     return get_field(env->virt, VIRT_ONOFF);
561 }
562 
563 void riscv_cpu_set_virt_enabled(CPURISCVState *env, bool enable)
564 {
565     if (!riscv_has_ext(env, RVH)) {
566         return;
567     }
568 
569     /* Flush the TLB on all virt mode changes. */
570     if (get_field(env->virt, VIRT_ONOFF) != enable) {
571         tlb_flush(env_cpu(env));
572     }
573 
574     env->virt = set_field(env->virt, VIRT_ONOFF, enable);
575 
576     if (enable) {
577         /*
578          * The guest external interrupts from an interrupt controller are
579          * delivered only when the Guest/VM is running (i.e. V=1). This means
580          * any guest external interrupt which is triggered while the Guest/VM
581          * is not running (i.e. V=0) will be missed on QEMU resulting in guest
582          * with sluggish response to serial console input and other I/O events.
583          *
584          * To solve this, we check and inject interrupt after setting V=1.
585          */
586         riscv_cpu_update_mip(env_archcpu(env), 0, 0);
587     }
588 }
589 
590 bool riscv_cpu_two_stage_lookup(int mmu_idx)
591 {
592     return mmu_idx & TB_FLAGS_PRIV_HYP_ACCESS_MASK;
593 }
594 
595 int riscv_cpu_claim_interrupts(RISCVCPU *cpu, uint64_t interrupts)
596 {
597     CPURISCVState *env = &cpu->env;
598     if (env->miclaim & interrupts) {
599         return -1;
600     } else {
601         env->miclaim |= interrupts;
602         return 0;
603     }
604 }
605 
606 uint64_t riscv_cpu_update_mip(RISCVCPU *cpu, uint64_t mask, uint64_t value)
607 {
608     CPURISCVState *env = &cpu->env;
609     CPUState *cs = CPU(cpu);
610     uint64_t gein, vsgein = 0, vstip = 0, old = env->mip;
611     bool locked = false;
612 
613     if (riscv_cpu_virt_enabled(env)) {
614         gein = get_field(env->hstatus, HSTATUS_VGEIN);
615         vsgein = (env->hgeip & (1ULL << gein)) ? MIP_VSEIP : 0;
616     }
617 
618     /* No need to update mip for VSTIP */
619     mask = ((mask == MIP_VSTIP) && env->vstime_irq) ? 0 : mask;
620     vstip = env->vstime_irq ? MIP_VSTIP : 0;
621 
622     if (!qemu_mutex_iothread_locked()) {
623         locked = true;
624         qemu_mutex_lock_iothread();
625     }
626 
627     env->mip = (env->mip & ~mask) | (value & mask);
628 
629     if (env->mip | vsgein | vstip) {
630         cpu_interrupt(cs, CPU_INTERRUPT_HARD);
631     } else {
632         cpu_reset_interrupt(cs, CPU_INTERRUPT_HARD);
633     }
634 
635     if (locked) {
636         qemu_mutex_unlock_iothread();
637     }
638 
639     return old;
640 }
641 
642 void riscv_cpu_set_rdtime_fn(CPURISCVState *env, uint64_t (*fn)(void *),
643                              void *arg)
644 {
645     env->rdtime_fn = fn;
646     env->rdtime_fn_arg = arg;
647 }
648 
649 void riscv_cpu_set_aia_ireg_rmw_fn(CPURISCVState *env, uint32_t priv,
650                                    int (*rmw_fn)(void *arg,
651                                                  target_ulong reg,
652                                                  target_ulong *val,
653                                                  target_ulong new_val,
654                                                  target_ulong write_mask),
655                                    void *rmw_fn_arg)
656 {
657     if (priv <= PRV_M) {
658         env->aia_ireg_rmw_fn[priv] = rmw_fn;
659         env->aia_ireg_rmw_fn_arg[priv] = rmw_fn_arg;
660     }
661 }
662 
663 void riscv_cpu_set_mode(CPURISCVState *env, target_ulong newpriv)
664 {
665     if (newpriv > PRV_M) {
666         g_assert_not_reached();
667     }
668     if (newpriv == PRV_H) {
669         newpriv = PRV_U;
670     }
671     /* tlb_flush is unnecessary as mode is contained in mmu_idx */
672     env->priv = newpriv;
673     env->xl = cpu_recompute_xl(env);
674     riscv_cpu_update_mask(env);
675 
676     /*
677      * Clear the load reservation - otherwise a reservation placed in one
678      * context/process can be used by another, resulting in an SC succeeding
679      * incorrectly. Version 2.2 of the ISA specification explicitly requires
680      * this behaviour, while later revisions say that the kernel "should" use
681      * an SC instruction to force the yielding of a load reservation on a
682      * preemptive context switch. As a result, do both.
683      */
684     env->load_res = -1;
685 }
686 
687 /*
688  * get_physical_address_pmp - check PMP permission for this physical address
689  *
690  * Match the PMP region and check permission for this physical address and it's
691  * TLB page. Returns 0 if the permission checking was successful
692  *
693  * @env: CPURISCVState
694  * @prot: The returned protection attributes
695  * @tlb_size: TLB page size containing addr. It could be modified after PMP
696  *            permission checking. NULL if not set TLB page for addr.
697  * @addr: The physical address to be checked permission
698  * @access_type: The type of MMU access
699  * @mode: Indicates current privilege level.
700  */
701 static int get_physical_address_pmp(CPURISCVState *env, int *prot,
702                                     target_ulong *tlb_size, hwaddr addr,
703                                     int size, MMUAccessType access_type,
704                                     int mode)
705 {
706     pmp_priv_t pmp_priv;
707     target_ulong tlb_size_pmp = 0;
708 
709     if (!riscv_feature(env, RISCV_FEATURE_PMP)) {
710         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
711         return TRANSLATE_SUCCESS;
712     }
713 
714     if (!pmp_hart_has_privs(env, addr, size, 1 << access_type, &pmp_priv,
715                             mode)) {
716         *prot = 0;
717         return TRANSLATE_PMP_FAIL;
718     }
719 
720     *prot = pmp_priv_to_page_prot(pmp_priv);
721     if (tlb_size != NULL) {
722         if (pmp_is_range_in_tlb(env, addr & ~(*tlb_size - 1), &tlb_size_pmp)) {
723             *tlb_size = tlb_size_pmp;
724         }
725     }
726 
727     return TRANSLATE_SUCCESS;
728 }
729 
730 /* get_physical_address - get the physical address for this virtual address
731  *
732  * Do a page table walk to obtain the physical address corresponding to a
733  * virtual address. Returns 0 if the translation was successful
734  *
735  * Adapted from Spike's mmu_t::translate and mmu_t::walk
736  *
737  * @env: CPURISCVState
738  * @physical: This will be set to the calculated physical address
739  * @prot: The returned protection attributes
740  * @addr: The virtual address to be translated
741  * @fault_pte_addr: If not NULL, this will be set to fault pte address
742  *                  when a error occurs on pte address translation.
743  *                  This will already be shifted to match htval.
744  * @access_type: The type of MMU access
745  * @mmu_idx: Indicates current privilege level
746  * @first_stage: Are we in first stage translation?
747  *               Second stage is used for hypervisor guest translation
748  * @two_stage: Are we going to perform two stage translation
749  * @is_debug: Is this access from a debugger or the monitor?
750  */
751 static int get_physical_address(CPURISCVState *env, hwaddr *physical,
752                                 int *prot, target_ulong addr,
753                                 target_ulong *fault_pte_addr,
754                                 int access_type, int mmu_idx,
755                                 bool first_stage, bool two_stage,
756                                 bool is_debug)
757 {
758     /* NOTE: the env->pc value visible here will not be
759      * correct, but the value visible to the exception handler
760      * (riscv_cpu_do_interrupt) is correct */
761     MemTxResult res;
762     MemTxAttrs attrs = MEMTXATTRS_UNSPECIFIED;
763     int mode = mmu_idx & TB_FLAGS_PRIV_MMU_MASK;
764     bool use_background = false;
765     hwaddr ppn;
766     RISCVCPU *cpu = env_archcpu(env);
767     int napot_bits = 0;
768     target_ulong napot_mask;
769 
770     /*
771      * Check if we should use the background registers for the two
772      * stage translation. We don't need to check if we actually need
773      * two stage translation as that happened before this function
774      * was called. Background registers will be used if the guest has
775      * forced a two stage translation to be on (in HS or M mode).
776      */
777     if (!riscv_cpu_virt_enabled(env) && two_stage) {
778         use_background = true;
779     }
780 
781     /* MPRV does not affect the virtual-machine load/store
782        instructions, HLV, HLVX, and HSV. */
783     if (riscv_cpu_two_stage_lookup(mmu_idx)) {
784         mode = get_field(env->hstatus, HSTATUS_SPVP);
785     } else if (mode == PRV_M && access_type != MMU_INST_FETCH) {
786         if (get_field(env->mstatus, MSTATUS_MPRV)) {
787             mode = get_field(env->mstatus, MSTATUS_MPP);
788         }
789     }
790 
791     if (first_stage == false) {
792         /* We are in stage 2 translation, this is similar to stage 1. */
793         /* Stage 2 is always taken as U-mode */
794         mode = PRV_U;
795     }
796 
797     if (mode == PRV_M || !riscv_feature(env, RISCV_FEATURE_MMU)) {
798         *physical = addr;
799         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
800         return TRANSLATE_SUCCESS;
801     }
802 
803     *prot = 0;
804 
805     hwaddr base;
806     int levels, ptidxbits, ptesize, vm, sum, mxr, widened;
807 
808     if (first_stage == true) {
809         mxr = get_field(env->mstatus, MSTATUS_MXR);
810     } else {
811         mxr = get_field(env->vsstatus, MSTATUS_MXR);
812     }
813 
814     if (first_stage == true) {
815         if (use_background) {
816             if (riscv_cpu_mxl(env) == MXL_RV32) {
817                 base = (hwaddr)get_field(env->vsatp, SATP32_PPN) << PGSHIFT;
818                 vm = get_field(env->vsatp, SATP32_MODE);
819             } else {
820                 base = (hwaddr)get_field(env->vsatp, SATP64_PPN) << PGSHIFT;
821                 vm = get_field(env->vsatp, SATP64_MODE);
822             }
823         } else {
824             if (riscv_cpu_mxl(env) == MXL_RV32) {
825                 base = (hwaddr)get_field(env->satp, SATP32_PPN) << PGSHIFT;
826                 vm = get_field(env->satp, SATP32_MODE);
827             } else {
828                 base = (hwaddr)get_field(env->satp, SATP64_PPN) << PGSHIFT;
829                 vm = get_field(env->satp, SATP64_MODE);
830             }
831         }
832         widened = 0;
833     } else {
834         if (riscv_cpu_mxl(env) == MXL_RV32) {
835             base = (hwaddr)get_field(env->hgatp, SATP32_PPN) << PGSHIFT;
836             vm = get_field(env->hgatp, SATP32_MODE);
837         } else {
838             base = (hwaddr)get_field(env->hgatp, SATP64_PPN) << PGSHIFT;
839             vm = get_field(env->hgatp, SATP64_MODE);
840         }
841         widened = 2;
842     }
843     /* status.SUM will be ignored if execute on background */
844     sum = get_field(env->mstatus, MSTATUS_SUM) || use_background || is_debug;
845     switch (vm) {
846     case VM_1_10_SV32:
847       levels = 2; ptidxbits = 10; ptesize = 4; break;
848     case VM_1_10_SV39:
849       levels = 3; ptidxbits = 9; ptesize = 8; break;
850     case VM_1_10_SV48:
851       levels = 4; ptidxbits = 9; ptesize = 8; break;
852     case VM_1_10_SV57:
853       levels = 5; ptidxbits = 9; ptesize = 8; break;
854     case VM_1_10_MBARE:
855         *physical = addr;
856         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
857         return TRANSLATE_SUCCESS;
858     default:
859       g_assert_not_reached();
860     }
861 
862     CPUState *cs = env_cpu(env);
863     int va_bits = PGSHIFT + levels * ptidxbits + widened;
864     target_ulong mask, masked_msbs;
865 
866     if (TARGET_LONG_BITS > (va_bits - 1)) {
867         mask = (1L << (TARGET_LONG_BITS - (va_bits - 1))) - 1;
868     } else {
869         mask = 0;
870     }
871     masked_msbs = (addr >> (va_bits - 1)) & mask;
872 
873     if (masked_msbs != 0 && masked_msbs != mask) {
874         return TRANSLATE_FAIL;
875     }
876 
877     int ptshift = (levels - 1) * ptidxbits;
878     int i;
879 
880 #if !TCG_OVERSIZED_GUEST
881 restart:
882 #endif
883     for (i = 0; i < levels; i++, ptshift -= ptidxbits) {
884         target_ulong idx;
885         if (i == 0) {
886             idx = (addr >> (PGSHIFT + ptshift)) &
887                            ((1 << (ptidxbits + widened)) - 1);
888         } else {
889             idx = (addr >> (PGSHIFT + ptshift)) &
890                            ((1 << ptidxbits) - 1);
891         }
892 
893         /* check that physical address of PTE is legal */
894         hwaddr pte_addr;
895 
896         if (two_stage && first_stage) {
897             int vbase_prot;
898             hwaddr vbase;
899 
900             /* Do the second stage translation on the base PTE address. */
901             int vbase_ret = get_physical_address(env, &vbase, &vbase_prot,
902                                                  base, NULL, MMU_DATA_LOAD,
903                                                  mmu_idx, false, true,
904                                                  is_debug);
905 
906             if (vbase_ret != TRANSLATE_SUCCESS) {
907                 if (fault_pte_addr) {
908                     *fault_pte_addr = (base + idx * ptesize) >> 2;
909                 }
910                 return TRANSLATE_G_STAGE_FAIL;
911             }
912 
913             pte_addr = vbase + idx * ptesize;
914         } else {
915             pte_addr = base + idx * ptesize;
916         }
917 
918         int pmp_prot;
919         int pmp_ret = get_physical_address_pmp(env, &pmp_prot, NULL, pte_addr,
920                                                sizeof(target_ulong),
921                                                MMU_DATA_LOAD, PRV_S);
922         if (pmp_ret != TRANSLATE_SUCCESS) {
923             return TRANSLATE_PMP_FAIL;
924         }
925 
926         target_ulong pte;
927         if (riscv_cpu_mxl(env) == MXL_RV32) {
928             pte = address_space_ldl(cs->as, pte_addr, attrs, &res);
929         } else {
930             pte = address_space_ldq(cs->as, pte_addr, attrs, &res);
931         }
932 
933         if (res != MEMTX_OK) {
934             return TRANSLATE_FAIL;
935         }
936 
937         if (riscv_cpu_sxl(env) == MXL_RV32) {
938             ppn = pte >> PTE_PPN_SHIFT;
939         } else if (cpu->cfg.ext_svpbmt || cpu->cfg.ext_svnapot) {
940             ppn = (pte & (target_ulong)PTE_PPN_MASK) >> PTE_PPN_SHIFT;
941         } else {
942             ppn = pte >> PTE_PPN_SHIFT;
943             if ((pte & ~(target_ulong)PTE_PPN_MASK) >> PTE_PPN_SHIFT) {
944                 return TRANSLATE_FAIL;
945             }
946         }
947 
948         if (!(pte & PTE_V)) {
949             /* Invalid PTE */
950             return TRANSLATE_FAIL;
951         } else if (!cpu->cfg.ext_svpbmt && (pte & PTE_PBMT)) {
952             return TRANSLATE_FAIL;
953         } else if (!(pte & (PTE_R | PTE_W | PTE_X))) {
954             /* Inner PTE, continue walking */
955             if (pte & (PTE_D | PTE_A | PTE_U | PTE_ATTR)) {
956                 return TRANSLATE_FAIL;
957             }
958             base = ppn << PGSHIFT;
959         } else if ((pte & (PTE_R | PTE_W | PTE_X)) == PTE_W) {
960             /* Reserved leaf PTE flags: PTE_W */
961             return TRANSLATE_FAIL;
962         } else if ((pte & (PTE_R | PTE_W | PTE_X)) == (PTE_W | PTE_X)) {
963             /* Reserved leaf PTE flags: PTE_W + PTE_X */
964             return TRANSLATE_FAIL;
965         } else if ((pte & PTE_U) && ((mode != PRV_U) &&
966                    (!sum || access_type == MMU_INST_FETCH))) {
967             /* User PTE flags when not U mode and mstatus.SUM is not set,
968                or the access type is an instruction fetch */
969             return TRANSLATE_FAIL;
970         } else if (!(pte & PTE_U) && (mode != PRV_S)) {
971             /* Supervisor PTE flags when not S mode */
972             return TRANSLATE_FAIL;
973         } else if (ppn & ((1ULL << ptshift) - 1)) {
974             /* Misaligned PPN */
975             return TRANSLATE_FAIL;
976         } else if (access_type == MMU_DATA_LOAD && !((pte & PTE_R) ||
977                    ((pte & PTE_X) && mxr))) {
978             /* Read access check failed */
979             return TRANSLATE_FAIL;
980         } else if (access_type == MMU_DATA_STORE && !(pte & PTE_W)) {
981             /* Write access check failed */
982             return TRANSLATE_FAIL;
983         } else if (access_type == MMU_INST_FETCH && !(pte & PTE_X)) {
984             /* Fetch access check failed */
985             return TRANSLATE_FAIL;
986         } else {
987             /* if necessary, set accessed and dirty bits. */
988             target_ulong updated_pte = pte | PTE_A |
989                 (access_type == MMU_DATA_STORE ? PTE_D : 0);
990 
991             /* Page table updates need to be atomic with MTTCG enabled */
992             if (updated_pte != pte) {
993                 /*
994                  * - if accessed or dirty bits need updating, and the PTE is
995                  *   in RAM, then we do so atomically with a compare and swap.
996                  * - if the PTE is in IO space or ROM, then it can't be updated
997                  *   and we return TRANSLATE_FAIL.
998                  * - if the PTE changed by the time we went to update it, then
999                  *   it is no longer valid and we must re-walk the page table.
1000                  */
1001                 MemoryRegion *mr;
1002                 hwaddr l = sizeof(target_ulong), addr1;
1003                 mr = address_space_translate(cs->as, pte_addr,
1004                     &addr1, &l, false, MEMTXATTRS_UNSPECIFIED);
1005                 if (memory_region_is_ram(mr)) {
1006                     target_ulong *pte_pa =
1007                         qemu_map_ram_ptr(mr->ram_block, addr1);
1008 #if TCG_OVERSIZED_GUEST
1009                     /* MTTCG is not enabled on oversized TCG guests so
1010                      * page table updates do not need to be atomic */
1011                     *pte_pa = pte = updated_pte;
1012 #else
1013                     target_ulong old_pte =
1014                         qatomic_cmpxchg(pte_pa, pte, updated_pte);
1015                     if (old_pte != pte) {
1016                         goto restart;
1017                     } else {
1018                         pte = updated_pte;
1019                     }
1020 #endif
1021                 } else {
1022                     /* misconfigured PTE in ROM (AD bits are not preset) or
1023                      * PTE is in IO space and can't be updated atomically */
1024                     return TRANSLATE_FAIL;
1025                 }
1026             }
1027 
1028             /* for superpage mappings, make a fake leaf PTE for the TLB's
1029                benefit. */
1030             target_ulong vpn = addr >> PGSHIFT;
1031 
1032             if (cpu->cfg.ext_svnapot && (pte & PTE_N)) {
1033                 napot_bits = ctzl(ppn) + 1;
1034                 if ((i != (levels - 1)) || (napot_bits != 4)) {
1035                     return TRANSLATE_FAIL;
1036                 }
1037             }
1038 
1039             napot_mask = (1 << napot_bits) - 1;
1040             *physical = (((ppn & ~napot_mask) | (vpn & napot_mask) |
1041                           (vpn & (((target_ulong)1 << ptshift) - 1))
1042                          ) << PGSHIFT) | (addr & ~TARGET_PAGE_MASK);
1043 
1044             /* set permissions on the TLB entry */
1045             if ((pte & PTE_R) || ((pte & PTE_X) && mxr)) {
1046                 *prot |= PAGE_READ;
1047             }
1048             if ((pte & PTE_X)) {
1049                 *prot |= PAGE_EXEC;
1050             }
1051             /* add write permission on stores or if the page is already dirty,
1052                so that we TLB miss on later writes to update the dirty bit */
1053             if ((pte & PTE_W) &&
1054                     (access_type == MMU_DATA_STORE || (pte & PTE_D))) {
1055                 *prot |= PAGE_WRITE;
1056             }
1057             return TRANSLATE_SUCCESS;
1058         }
1059     }
1060     return TRANSLATE_FAIL;
1061 }
1062 
1063 static void raise_mmu_exception(CPURISCVState *env, target_ulong address,
1064                                 MMUAccessType access_type, bool pmp_violation,
1065                                 bool first_stage, bool two_stage,
1066                                 bool two_stage_indirect)
1067 {
1068     CPUState *cs = env_cpu(env);
1069     int page_fault_exceptions, vm;
1070     uint64_t stap_mode;
1071 
1072     if (riscv_cpu_mxl(env) == MXL_RV32) {
1073         stap_mode = SATP32_MODE;
1074     } else {
1075         stap_mode = SATP64_MODE;
1076     }
1077 
1078     if (first_stage) {
1079         vm = get_field(env->satp, stap_mode);
1080     } else {
1081         vm = get_field(env->hgatp, stap_mode);
1082     }
1083 
1084     page_fault_exceptions = vm != VM_1_10_MBARE && !pmp_violation;
1085 
1086     switch (access_type) {
1087     case MMU_INST_FETCH:
1088         if (riscv_cpu_virt_enabled(env) && !first_stage) {
1089             cs->exception_index = RISCV_EXCP_INST_GUEST_PAGE_FAULT;
1090         } else {
1091             cs->exception_index = page_fault_exceptions ?
1092                 RISCV_EXCP_INST_PAGE_FAULT : RISCV_EXCP_INST_ACCESS_FAULT;
1093         }
1094         break;
1095     case MMU_DATA_LOAD:
1096         if (two_stage && !first_stage) {
1097             cs->exception_index = RISCV_EXCP_LOAD_GUEST_ACCESS_FAULT;
1098         } else {
1099             cs->exception_index = page_fault_exceptions ?
1100                 RISCV_EXCP_LOAD_PAGE_FAULT : RISCV_EXCP_LOAD_ACCESS_FAULT;
1101         }
1102         break;
1103     case MMU_DATA_STORE:
1104         if (two_stage && !first_stage) {
1105             cs->exception_index = RISCV_EXCP_STORE_GUEST_AMO_ACCESS_FAULT;
1106         } else {
1107             cs->exception_index = page_fault_exceptions ?
1108                 RISCV_EXCP_STORE_PAGE_FAULT : RISCV_EXCP_STORE_AMO_ACCESS_FAULT;
1109         }
1110         break;
1111     default:
1112         g_assert_not_reached();
1113     }
1114     env->badaddr = address;
1115     env->two_stage_lookup = two_stage;
1116     env->two_stage_indirect_lookup = two_stage_indirect;
1117 }
1118 
1119 hwaddr riscv_cpu_get_phys_page_debug(CPUState *cs, vaddr addr)
1120 {
1121     RISCVCPU *cpu = RISCV_CPU(cs);
1122     CPURISCVState *env = &cpu->env;
1123     hwaddr phys_addr;
1124     int prot;
1125     int mmu_idx = cpu_mmu_index(&cpu->env, false);
1126 
1127     if (get_physical_address(env, &phys_addr, &prot, addr, NULL, 0, mmu_idx,
1128                              true, riscv_cpu_virt_enabled(env), true)) {
1129         return -1;
1130     }
1131 
1132     if (riscv_cpu_virt_enabled(env)) {
1133         if (get_physical_address(env, &phys_addr, &prot, phys_addr, NULL,
1134                                  0, mmu_idx, false, true, true)) {
1135             return -1;
1136         }
1137     }
1138 
1139     return phys_addr & TARGET_PAGE_MASK;
1140 }
1141 
1142 void riscv_cpu_do_transaction_failed(CPUState *cs, hwaddr physaddr,
1143                                      vaddr addr, unsigned size,
1144                                      MMUAccessType access_type,
1145                                      int mmu_idx, MemTxAttrs attrs,
1146                                      MemTxResult response, uintptr_t retaddr)
1147 {
1148     RISCVCPU *cpu = RISCV_CPU(cs);
1149     CPURISCVState *env = &cpu->env;
1150 
1151     if (access_type == MMU_DATA_STORE) {
1152         cs->exception_index = RISCV_EXCP_STORE_AMO_ACCESS_FAULT;
1153     } else if (access_type == MMU_DATA_LOAD) {
1154         cs->exception_index = RISCV_EXCP_LOAD_ACCESS_FAULT;
1155     } else {
1156         cs->exception_index = RISCV_EXCP_INST_ACCESS_FAULT;
1157     }
1158 
1159     env->badaddr = addr;
1160     env->two_stage_lookup = riscv_cpu_virt_enabled(env) ||
1161                             riscv_cpu_two_stage_lookup(mmu_idx);
1162     env->two_stage_indirect_lookup = false;
1163     cpu_loop_exit_restore(cs, retaddr);
1164 }
1165 
1166 void riscv_cpu_do_unaligned_access(CPUState *cs, vaddr addr,
1167                                    MMUAccessType access_type, int mmu_idx,
1168                                    uintptr_t retaddr)
1169 {
1170     RISCVCPU *cpu = RISCV_CPU(cs);
1171     CPURISCVState *env = &cpu->env;
1172     switch (access_type) {
1173     case MMU_INST_FETCH:
1174         cs->exception_index = RISCV_EXCP_INST_ADDR_MIS;
1175         break;
1176     case MMU_DATA_LOAD:
1177         cs->exception_index = RISCV_EXCP_LOAD_ADDR_MIS;
1178         break;
1179     case MMU_DATA_STORE:
1180         cs->exception_index = RISCV_EXCP_STORE_AMO_ADDR_MIS;
1181         break;
1182     default:
1183         g_assert_not_reached();
1184     }
1185     env->badaddr = addr;
1186     env->two_stage_lookup = riscv_cpu_virt_enabled(env) ||
1187                             riscv_cpu_two_stage_lookup(mmu_idx);
1188     env->two_stage_indirect_lookup = false;
1189     cpu_loop_exit_restore(cs, retaddr);
1190 }
1191 
1192 bool riscv_cpu_tlb_fill(CPUState *cs, vaddr address, int size,
1193                         MMUAccessType access_type, int mmu_idx,
1194                         bool probe, uintptr_t retaddr)
1195 {
1196     RISCVCPU *cpu = RISCV_CPU(cs);
1197     CPURISCVState *env = &cpu->env;
1198     vaddr im_address;
1199     hwaddr pa = 0;
1200     int prot, prot2, prot_pmp;
1201     bool pmp_violation = false;
1202     bool first_stage_error = true;
1203     bool two_stage_lookup = false;
1204     bool two_stage_indirect_error = false;
1205     int ret = TRANSLATE_FAIL;
1206     int mode = mmu_idx;
1207     /* default TLB page size */
1208     target_ulong tlb_size = TARGET_PAGE_SIZE;
1209 
1210     env->guest_phys_fault_addr = 0;
1211 
1212     qemu_log_mask(CPU_LOG_MMU, "%s ad %" VADDR_PRIx " rw %d mmu_idx %d\n",
1213                   __func__, address, access_type, mmu_idx);
1214 
1215     /* MPRV does not affect the virtual-machine load/store
1216        instructions, HLV, HLVX, and HSV. */
1217     if (riscv_cpu_two_stage_lookup(mmu_idx)) {
1218         mode = get_field(env->hstatus, HSTATUS_SPVP);
1219     } else if (mode == PRV_M && access_type != MMU_INST_FETCH &&
1220                get_field(env->mstatus, MSTATUS_MPRV)) {
1221         mode = get_field(env->mstatus, MSTATUS_MPP);
1222         if (riscv_has_ext(env, RVH) && get_field(env->mstatus, MSTATUS_MPV)) {
1223             two_stage_lookup = true;
1224         }
1225     }
1226 
1227     if (riscv_cpu_virt_enabled(env) ||
1228         ((riscv_cpu_two_stage_lookup(mmu_idx) || two_stage_lookup) &&
1229          access_type != MMU_INST_FETCH)) {
1230         /* Two stage lookup */
1231         ret = get_physical_address(env, &pa, &prot, address,
1232                                    &env->guest_phys_fault_addr, access_type,
1233                                    mmu_idx, true, true, false);
1234 
1235         /*
1236          * A G-stage exception may be triggered during two state lookup.
1237          * And the env->guest_phys_fault_addr has already been set in
1238          * get_physical_address().
1239          */
1240         if (ret == TRANSLATE_G_STAGE_FAIL) {
1241             first_stage_error = false;
1242             two_stage_indirect_error = true;
1243             access_type = MMU_DATA_LOAD;
1244         }
1245 
1246         qemu_log_mask(CPU_LOG_MMU,
1247                       "%s 1st-stage address=%" VADDR_PRIx " ret %d physical "
1248                       TARGET_FMT_plx " prot %d\n",
1249                       __func__, address, ret, pa, prot);
1250 
1251         if (ret == TRANSLATE_SUCCESS) {
1252             /* Second stage lookup */
1253             im_address = pa;
1254 
1255             ret = get_physical_address(env, &pa, &prot2, im_address, NULL,
1256                                        access_type, mmu_idx, false, true,
1257                                        false);
1258 
1259             qemu_log_mask(CPU_LOG_MMU,
1260                     "%s 2nd-stage address=%" VADDR_PRIx " ret %d physical "
1261                     TARGET_FMT_plx " prot %d\n",
1262                     __func__, im_address, ret, pa, prot2);
1263 
1264             prot &= prot2;
1265 
1266             if (ret == TRANSLATE_SUCCESS) {
1267                 ret = get_physical_address_pmp(env, &prot_pmp, &tlb_size, pa,
1268                                                size, access_type, mode);
1269 
1270                 qemu_log_mask(CPU_LOG_MMU,
1271                               "%s PMP address=" TARGET_FMT_plx " ret %d prot"
1272                               " %d tlb_size " TARGET_FMT_lu "\n",
1273                               __func__, pa, ret, prot_pmp, tlb_size);
1274 
1275                 prot &= prot_pmp;
1276             }
1277 
1278             if (ret != TRANSLATE_SUCCESS) {
1279                 /*
1280                  * Guest physical address translation failed, this is a HS
1281                  * level exception
1282                  */
1283                 first_stage_error = false;
1284                 env->guest_phys_fault_addr = (im_address |
1285                                               (address &
1286                                                (TARGET_PAGE_SIZE - 1))) >> 2;
1287             }
1288         }
1289     } else {
1290         /* Single stage lookup */
1291         ret = get_physical_address(env, &pa, &prot, address, NULL,
1292                                    access_type, mmu_idx, true, false, false);
1293 
1294         qemu_log_mask(CPU_LOG_MMU,
1295                       "%s address=%" VADDR_PRIx " ret %d physical "
1296                       TARGET_FMT_plx " prot %d\n",
1297                       __func__, address, ret, pa, prot);
1298 
1299         if (ret == TRANSLATE_SUCCESS) {
1300             ret = get_physical_address_pmp(env, &prot_pmp, &tlb_size, pa,
1301                                            size, access_type, mode);
1302 
1303             qemu_log_mask(CPU_LOG_MMU,
1304                           "%s PMP address=" TARGET_FMT_plx " ret %d prot"
1305                           " %d tlb_size " TARGET_FMT_lu "\n",
1306                           __func__, pa, ret, prot_pmp, tlb_size);
1307 
1308             prot &= prot_pmp;
1309         }
1310     }
1311 
1312     if (ret == TRANSLATE_PMP_FAIL) {
1313         pmp_violation = true;
1314     }
1315 
1316     if (ret == TRANSLATE_SUCCESS) {
1317         tlb_set_page(cs, address & ~(tlb_size - 1), pa & ~(tlb_size - 1),
1318                      prot, mmu_idx, tlb_size);
1319         return true;
1320     } else if (probe) {
1321         return false;
1322     } else {
1323         raise_mmu_exception(env, address, access_type, pmp_violation,
1324                             first_stage_error,
1325                             riscv_cpu_virt_enabled(env) ||
1326                                 riscv_cpu_two_stage_lookup(mmu_idx),
1327                             two_stage_indirect_error);
1328         cpu_loop_exit_restore(cs, retaddr);
1329     }
1330 
1331     return true;
1332 }
1333 
1334 static target_ulong riscv_transformed_insn(CPURISCVState *env,
1335                                            target_ulong insn,
1336                                            target_ulong taddr)
1337 {
1338     target_ulong xinsn = 0;
1339     target_ulong access_rs1 = 0, access_imm = 0, access_size = 0;
1340 
1341     /*
1342      * Only Quadrant 0 and Quadrant 2 of RVC instruction space need to
1343      * be uncompressed. The Quadrant 1 of RVC instruction space need
1344      * not be transformed because these instructions won't generate
1345      * any load/store trap.
1346      */
1347 
1348     if ((insn & 0x3) != 0x3) {
1349         /* Transform 16bit instruction into 32bit instruction */
1350         switch (GET_C_OP(insn)) {
1351         case OPC_RISC_C_OP_QUAD0: /* Quadrant 0 */
1352             switch (GET_C_FUNC(insn)) {
1353             case OPC_RISC_C_FUNC_FLD_LQ:
1354                 if (riscv_cpu_xlen(env) != 128) { /* C.FLD (RV32/64) */
1355                     xinsn = OPC_RISC_FLD;
1356                     xinsn = SET_RD(xinsn, GET_C_RS2S(insn));
1357                     access_rs1 = GET_C_RS1S(insn);
1358                     access_imm = GET_C_LD_IMM(insn);
1359                     access_size = 8;
1360                 }
1361                 break;
1362             case OPC_RISC_C_FUNC_LW: /* C.LW */
1363                 xinsn = OPC_RISC_LW;
1364                 xinsn = SET_RD(xinsn, GET_C_RS2S(insn));
1365                 access_rs1 = GET_C_RS1S(insn);
1366                 access_imm = GET_C_LW_IMM(insn);
1367                 access_size = 4;
1368                 break;
1369             case OPC_RISC_C_FUNC_FLW_LD:
1370                 if (riscv_cpu_xlen(env) == 32) { /* C.FLW (RV32) */
1371                     xinsn = OPC_RISC_FLW;
1372                     xinsn = SET_RD(xinsn, GET_C_RS2S(insn));
1373                     access_rs1 = GET_C_RS1S(insn);
1374                     access_imm = GET_C_LW_IMM(insn);
1375                     access_size = 4;
1376                 } else { /* C.LD (RV64/RV128) */
1377                     xinsn = OPC_RISC_LD;
1378                     xinsn = SET_RD(xinsn, GET_C_RS2S(insn));
1379                     access_rs1 = GET_C_RS1S(insn);
1380                     access_imm = GET_C_LD_IMM(insn);
1381                     access_size = 8;
1382                 }
1383                 break;
1384             case OPC_RISC_C_FUNC_FSD_SQ:
1385                 if (riscv_cpu_xlen(env) != 128) { /* C.FSD (RV32/64) */
1386                     xinsn = OPC_RISC_FSD;
1387                     xinsn = SET_RS2(xinsn, GET_C_RS2S(insn));
1388                     access_rs1 = GET_C_RS1S(insn);
1389                     access_imm = GET_C_SD_IMM(insn);
1390                     access_size = 8;
1391                 }
1392                 break;
1393             case OPC_RISC_C_FUNC_SW: /* C.SW */
1394                 xinsn = OPC_RISC_SW;
1395                 xinsn = SET_RS2(xinsn, GET_C_RS2S(insn));
1396                 access_rs1 = GET_C_RS1S(insn);
1397                 access_imm = GET_C_SW_IMM(insn);
1398                 access_size = 4;
1399                 break;
1400             case OPC_RISC_C_FUNC_FSW_SD:
1401                 if (riscv_cpu_xlen(env) == 32) { /* C.FSW (RV32) */
1402                     xinsn = OPC_RISC_FSW;
1403                     xinsn = SET_RS2(xinsn, GET_C_RS2S(insn));
1404                     access_rs1 = GET_C_RS1S(insn);
1405                     access_imm = GET_C_SW_IMM(insn);
1406                     access_size = 4;
1407                 } else { /* C.SD (RV64/RV128) */
1408                     xinsn = OPC_RISC_SD;
1409                     xinsn = SET_RS2(xinsn, GET_C_RS2S(insn));
1410                     access_rs1 = GET_C_RS1S(insn);
1411                     access_imm = GET_C_SD_IMM(insn);
1412                     access_size = 8;
1413                 }
1414                 break;
1415             default:
1416                 break;
1417             }
1418             break;
1419         case OPC_RISC_C_OP_QUAD2: /* Quadrant 2 */
1420             switch (GET_C_FUNC(insn)) {
1421             case OPC_RISC_C_FUNC_FLDSP_LQSP:
1422                 if (riscv_cpu_xlen(env) != 128) { /* C.FLDSP (RV32/64) */
1423                     xinsn = OPC_RISC_FLD;
1424                     xinsn = SET_RD(xinsn, GET_C_RD(insn));
1425                     access_rs1 = 2;
1426                     access_imm = GET_C_LDSP_IMM(insn);
1427                     access_size = 8;
1428                 }
1429                 break;
1430             case OPC_RISC_C_FUNC_LWSP: /* C.LWSP */
1431                 xinsn = OPC_RISC_LW;
1432                 xinsn = SET_RD(xinsn, GET_C_RD(insn));
1433                 access_rs1 = 2;
1434                 access_imm = GET_C_LWSP_IMM(insn);
1435                 access_size = 4;
1436                 break;
1437             case OPC_RISC_C_FUNC_FLWSP_LDSP:
1438                 if (riscv_cpu_xlen(env) == 32) { /* C.FLWSP (RV32) */
1439                     xinsn = OPC_RISC_FLW;
1440                     xinsn = SET_RD(xinsn, GET_C_RD(insn));
1441                     access_rs1 = 2;
1442                     access_imm = GET_C_LWSP_IMM(insn);
1443                     access_size = 4;
1444                 } else { /* C.LDSP (RV64/RV128) */
1445                     xinsn = OPC_RISC_LD;
1446                     xinsn = SET_RD(xinsn, GET_C_RD(insn));
1447                     access_rs1 = 2;
1448                     access_imm = GET_C_LDSP_IMM(insn);
1449                     access_size = 8;
1450                 }
1451                 break;
1452             case OPC_RISC_C_FUNC_FSDSP_SQSP:
1453                 if (riscv_cpu_xlen(env) != 128) { /* C.FSDSP (RV32/64) */
1454                     xinsn = OPC_RISC_FSD;
1455                     xinsn = SET_RS2(xinsn, GET_C_RS2(insn));
1456                     access_rs1 = 2;
1457                     access_imm = GET_C_SDSP_IMM(insn);
1458                     access_size = 8;
1459                 }
1460                 break;
1461             case OPC_RISC_C_FUNC_SWSP: /* C.SWSP */
1462                 xinsn = OPC_RISC_SW;
1463                 xinsn = SET_RS2(xinsn, GET_C_RS2(insn));
1464                 access_rs1 = 2;
1465                 access_imm = GET_C_SWSP_IMM(insn);
1466                 access_size = 4;
1467                 break;
1468             case 7:
1469                 if (riscv_cpu_xlen(env) == 32) { /* C.FSWSP (RV32) */
1470                     xinsn = OPC_RISC_FSW;
1471                     xinsn = SET_RS2(xinsn, GET_C_RS2(insn));
1472                     access_rs1 = 2;
1473                     access_imm = GET_C_SWSP_IMM(insn);
1474                     access_size = 4;
1475                 } else { /* C.SDSP (RV64/RV128) */
1476                     xinsn = OPC_RISC_SD;
1477                     xinsn = SET_RS2(xinsn, GET_C_RS2(insn));
1478                     access_rs1 = 2;
1479                     access_imm = GET_C_SDSP_IMM(insn);
1480                     access_size = 8;
1481                 }
1482                 break;
1483             default:
1484                 break;
1485             }
1486             break;
1487         default:
1488             break;
1489         }
1490 
1491         /*
1492          * Clear Bit1 of transformed instruction to indicate that
1493          * original insruction was a 16bit instruction
1494          */
1495         xinsn &= ~((target_ulong)0x2);
1496     } else {
1497         /* Transform 32bit (or wider) instructions */
1498         switch (MASK_OP_MAJOR(insn)) {
1499         case OPC_RISC_ATOMIC:
1500             xinsn = insn;
1501             access_rs1 = GET_RS1(insn);
1502             access_size = 1 << GET_FUNCT3(insn);
1503             break;
1504         case OPC_RISC_LOAD:
1505         case OPC_RISC_FP_LOAD:
1506             xinsn = SET_I_IMM(insn, 0);
1507             access_rs1 = GET_RS1(insn);
1508             access_imm = GET_IMM(insn);
1509             access_size = 1 << GET_FUNCT3(insn);
1510             break;
1511         case OPC_RISC_STORE:
1512         case OPC_RISC_FP_STORE:
1513             xinsn = SET_S_IMM(insn, 0);
1514             access_rs1 = GET_RS1(insn);
1515             access_imm = GET_STORE_IMM(insn);
1516             access_size = 1 << GET_FUNCT3(insn);
1517             break;
1518         case OPC_RISC_SYSTEM:
1519             if (MASK_OP_SYSTEM(insn) == OPC_RISC_HLVHSV) {
1520                 xinsn = insn;
1521                 access_rs1 = GET_RS1(insn);
1522                 access_size = 1 << ((GET_FUNCT7(insn) >> 1) & 0x3);
1523                 access_size = 1 << access_size;
1524             }
1525             break;
1526         default:
1527             break;
1528         }
1529     }
1530 
1531     if (access_size) {
1532         xinsn = SET_RS1(xinsn, (taddr - (env->gpr[access_rs1] + access_imm)) &
1533                                (access_size - 1));
1534     }
1535 
1536     return xinsn;
1537 }
1538 #endif /* !CONFIG_USER_ONLY */
1539 
1540 /*
1541  * Handle Traps
1542  *
1543  * Adapted from Spike's processor_t::take_trap.
1544  *
1545  */
1546 void riscv_cpu_do_interrupt(CPUState *cs)
1547 {
1548 #if !defined(CONFIG_USER_ONLY)
1549 
1550     RISCVCPU *cpu = RISCV_CPU(cs);
1551     CPURISCVState *env = &cpu->env;
1552     bool write_gva = false;
1553     uint64_t s;
1554 
1555     /* cs->exception is 32-bits wide unlike mcause which is XLEN-bits wide
1556      * so we mask off the MSB and separate into trap type and cause.
1557      */
1558     bool async = !!(cs->exception_index & RISCV_EXCP_INT_FLAG);
1559     target_ulong cause = cs->exception_index & RISCV_EXCP_INT_MASK;
1560     uint64_t deleg = async ? env->mideleg : env->medeleg;
1561     target_ulong tval = 0;
1562     target_ulong tinst = 0;
1563     target_ulong htval = 0;
1564     target_ulong mtval2 = 0;
1565 
1566     if  (cause == RISCV_EXCP_SEMIHOST) {
1567         if (env->priv >= PRV_S) {
1568             do_common_semihosting(cs);
1569             env->pc += 4;
1570             return;
1571         }
1572         cause = RISCV_EXCP_BREAKPOINT;
1573     }
1574 
1575     if (!async) {
1576         /* set tval to badaddr for traps with address information */
1577         switch (cause) {
1578         case RISCV_EXCP_LOAD_GUEST_ACCESS_FAULT:
1579         case RISCV_EXCP_STORE_GUEST_AMO_ACCESS_FAULT:
1580         case RISCV_EXCP_LOAD_ADDR_MIS:
1581         case RISCV_EXCP_STORE_AMO_ADDR_MIS:
1582         case RISCV_EXCP_LOAD_ACCESS_FAULT:
1583         case RISCV_EXCP_STORE_AMO_ACCESS_FAULT:
1584         case RISCV_EXCP_LOAD_PAGE_FAULT:
1585         case RISCV_EXCP_STORE_PAGE_FAULT:
1586             write_gva = env->two_stage_lookup;
1587             tval = env->badaddr;
1588             if (env->two_stage_indirect_lookup) {
1589                 /*
1590                  * special pseudoinstruction for G-stage fault taken while
1591                  * doing VS-stage page table walk.
1592                  */
1593                 tinst = (riscv_cpu_xlen(env) == 32) ? 0x00002000 : 0x00003000;
1594             } else {
1595                 /*
1596                  * The "Addr. Offset" field in transformed instruction is
1597                  * non-zero only for misaligned access.
1598                  */
1599                 tinst = riscv_transformed_insn(env, env->bins, tval);
1600             }
1601             break;
1602         case RISCV_EXCP_INST_GUEST_PAGE_FAULT:
1603         case RISCV_EXCP_INST_ADDR_MIS:
1604         case RISCV_EXCP_INST_ACCESS_FAULT:
1605         case RISCV_EXCP_INST_PAGE_FAULT:
1606             write_gva = env->two_stage_lookup;
1607             tval = env->badaddr;
1608             if (env->two_stage_indirect_lookup) {
1609                 /*
1610                  * special pseudoinstruction for G-stage fault taken while
1611                  * doing VS-stage page table walk.
1612                  */
1613                 tinst = (riscv_cpu_xlen(env) == 32) ? 0x00002000 : 0x00003000;
1614             }
1615             break;
1616         case RISCV_EXCP_ILLEGAL_INST:
1617         case RISCV_EXCP_VIRT_INSTRUCTION_FAULT:
1618             tval = env->bins;
1619             break;
1620         default:
1621             break;
1622         }
1623         /* ecall is dispatched as one cause so translate based on mode */
1624         if (cause == RISCV_EXCP_U_ECALL) {
1625             assert(env->priv <= 3);
1626 
1627             if (env->priv == PRV_M) {
1628                 cause = RISCV_EXCP_M_ECALL;
1629             } else if (env->priv == PRV_S && riscv_cpu_virt_enabled(env)) {
1630                 cause = RISCV_EXCP_VS_ECALL;
1631             } else if (env->priv == PRV_S && !riscv_cpu_virt_enabled(env)) {
1632                 cause = RISCV_EXCP_S_ECALL;
1633             } else if (env->priv == PRV_U) {
1634                 cause = RISCV_EXCP_U_ECALL;
1635             }
1636         }
1637     }
1638 
1639     trace_riscv_trap(env->mhartid, async, cause, env->pc, tval,
1640                      riscv_cpu_get_trap_name(cause, async));
1641 
1642     qemu_log_mask(CPU_LOG_INT,
1643                   "%s: hart:"TARGET_FMT_ld", async:%d, cause:"TARGET_FMT_lx", "
1644                   "epc:0x"TARGET_FMT_lx", tval:0x"TARGET_FMT_lx", desc=%s\n",
1645                   __func__, env->mhartid, async, cause, env->pc, tval,
1646                   riscv_cpu_get_trap_name(cause, async));
1647 
1648     if (env->priv <= PRV_S &&
1649             cause < TARGET_LONG_BITS && ((deleg >> cause) & 1)) {
1650         /* handle the trap in S-mode */
1651         if (riscv_has_ext(env, RVH)) {
1652             uint64_t hdeleg = async ? env->hideleg : env->hedeleg;
1653 
1654             if (riscv_cpu_virt_enabled(env) && ((hdeleg >> cause) & 1)) {
1655                 /* Trap to VS mode */
1656                 /*
1657                  * See if we need to adjust cause. Yes if its VS mode interrupt
1658                  * no if hypervisor has delegated one of hs mode's interrupt
1659                  */
1660                 if (cause == IRQ_VS_TIMER || cause == IRQ_VS_SOFT ||
1661                     cause == IRQ_VS_EXT) {
1662                     cause = cause - 1;
1663                 }
1664                 write_gva = false;
1665             } else if (riscv_cpu_virt_enabled(env)) {
1666                 /* Trap into HS mode, from virt */
1667                 riscv_cpu_swap_hypervisor_regs(env);
1668                 env->hstatus = set_field(env->hstatus, HSTATUS_SPVP,
1669                                          env->priv);
1670                 env->hstatus = set_field(env->hstatus, HSTATUS_SPV,
1671                                          riscv_cpu_virt_enabled(env));
1672 
1673 
1674                 htval = env->guest_phys_fault_addr;
1675 
1676                 riscv_cpu_set_virt_enabled(env, 0);
1677             } else {
1678                 /* Trap into HS mode */
1679                 env->hstatus = set_field(env->hstatus, HSTATUS_SPV, false);
1680                 htval = env->guest_phys_fault_addr;
1681             }
1682             env->hstatus = set_field(env->hstatus, HSTATUS_GVA, write_gva);
1683         }
1684 
1685         s = env->mstatus;
1686         s = set_field(s, MSTATUS_SPIE, get_field(s, MSTATUS_SIE));
1687         s = set_field(s, MSTATUS_SPP, env->priv);
1688         s = set_field(s, MSTATUS_SIE, 0);
1689         env->mstatus = s;
1690         env->scause = cause | ((target_ulong)async << (TARGET_LONG_BITS - 1));
1691         env->sepc = env->pc;
1692         env->stval = tval;
1693         env->htval = htval;
1694         env->htinst = tinst;
1695         env->pc = (env->stvec >> 2 << 2) +
1696             ((async && (env->stvec & 3) == 1) ? cause * 4 : 0);
1697         riscv_cpu_set_mode(env, PRV_S);
1698     } else {
1699         /* handle the trap in M-mode */
1700         if (riscv_has_ext(env, RVH)) {
1701             if (riscv_cpu_virt_enabled(env)) {
1702                 riscv_cpu_swap_hypervisor_regs(env);
1703             }
1704             env->mstatus = set_field(env->mstatus, MSTATUS_MPV,
1705                                      riscv_cpu_virt_enabled(env));
1706             if (riscv_cpu_virt_enabled(env) && tval) {
1707                 env->mstatus = set_field(env->mstatus, MSTATUS_GVA, 1);
1708             }
1709 
1710             mtval2 = env->guest_phys_fault_addr;
1711 
1712             /* Trapping to M mode, virt is disabled */
1713             riscv_cpu_set_virt_enabled(env, 0);
1714         }
1715 
1716         s = env->mstatus;
1717         s = set_field(s, MSTATUS_MPIE, get_field(s, MSTATUS_MIE));
1718         s = set_field(s, MSTATUS_MPP, env->priv);
1719         s = set_field(s, MSTATUS_MIE, 0);
1720         env->mstatus = s;
1721         env->mcause = cause | ~(((target_ulong)-1) >> async);
1722         env->mepc = env->pc;
1723         env->mtval = tval;
1724         env->mtval2 = mtval2;
1725         env->mtinst = tinst;
1726         env->pc = (env->mtvec >> 2 << 2) +
1727             ((async && (env->mtvec & 3) == 1) ? cause * 4 : 0);
1728         riscv_cpu_set_mode(env, PRV_M);
1729     }
1730 
1731     /* NOTE: it is not necessary to yield load reservations here. It is only
1732      * necessary for an SC from "another hart" to cause a load reservation
1733      * to be yielded. Refer to the memory consistency model section of the
1734      * RISC-V ISA Specification.
1735      */
1736 
1737     env->two_stage_lookup = false;
1738     env->two_stage_indirect_lookup = false;
1739 #endif
1740     cs->exception_index = RISCV_EXCP_NONE; /* mark handled to qemu */
1741 }
1742