xref: /openbmc/qemu/target/riscv/cpu_helper.c (revision eaecd473)
1 /*
2  * RISC-V CPU helpers for qemu.
3  *
4  * Copyright (c) 2016-2017 Sagar Karandikar, sagark@eecs.berkeley.edu
5  * Copyright (c) 2017-2018 SiFive, Inc.
6  *
7  * This program is free software; you can redistribute it and/or modify it
8  * under the terms and conditions of the GNU General Public License,
9  * version 2 or later, as published by the Free Software Foundation.
10  *
11  * This program is distributed in the hope it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
14  * more details.
15  *
16  * You should have received a copy of the GNU General Public License along with
17  * this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19 
20 #include "qemu/osdep.h"
21 #include "qemu/log.h"
22 #include "qemu/main-loop.h"
23 #include "cpu.h"
24 #include "internals.h"
25 #include "pmu.h"
26 #include "exec/exec-all.h"
27 #include "instmap.h"
28 #include "tcg/tcg-op.h"
29 #include "trace.h"
30 #include "semihosting/common-semi.h"
31 #include "sysemu/cpu-timers.h"
32 #include "cpu_bits.h"
33 #include "debug.h"
34 
35 int riscv_cpu_mmu_index(CPURISCVState *env, bool ifetch)
36 {
37 #ifdef CONFIG_USER_ONLY
38     return 0;
39 #else
40     bool virt = env->virt_enabled;
41     int mode = env->priv;
42 
43     /* All priv -> mmu_idx mapping are here */
44     if (!ifetch) {
45         uint64_t status = env->mstatus;
46 
47         if (mode == PRV_M && get_field(status, MSTATUS_MPRV)) {
48             mode = get_field(env->mstatus, MSTATUS_MPP);
49             virt = get_field(env->mstatus, MSTATUS_MPV);
50             if (virt) {
51                 status = env->vsstatus;
52             }
53         }
54         if (mode == PRV_S && get_field(status, MSTATUS_SUM)) {
55             mode = MMUIdx_S_SUM;
56         }
57     }
58 
59     return mode | (virt ? MMU_2STAGE_BIT : 0);
60 #endif
61 }
62 
63 void cpu_get_tb_cpu_state(CPURISCVState *env, target_ulong *pc,
64                           target_ulong *cs_base, uint32_t *pflags)
65 {
66     CPUState *cs = env_cpu(env);
67     RISCVCPU *cpu = RISCV_CPU(cs);
68     RISCVExtStatus fs, vs;
69     uint32_t flags = 0;
70 
71     *pc = env->xl == MXL_RV32 ? env->pc & UINT32_MAX : env->pc;
72     *cs_base = 0;
73 
74     if (cpu->cfg.ext_zve32f) {
75         /*
76          * If env->vl equals to VLMAX, we can use generic vector operation
77          * expanders (GVEC) to accerlate the vector operations.
78          * However, as LMUL could be a fractional number. The maximum
79          * vector size can be operated might be less than 8 bytes,
80          * which is not supported by GVEC. So we set vl_eq_vlmax flag to true
81          * only when maxsz >= 8 bytes.
82          */
83         uint32_t vlmax = vext_get_vlmax(cpu, env->vtype);
84         uint32_t sew = FIELD_EX64(env->vtype, VTYPE, VSEW);
85         uint32_t maxsz = vlmax << sew;
86         bool vl_eq_vlmax = (env->vstart == 0) && (vlmax == env->vl) &&
87                            (maxsz >= 8);
88         flags = FIELD_DP32(flags, TB_FLAGS, VILL, env->vill);
89         flags = FIELD_DP32(flags, TB_FLAGS, SEW, sew);
90         flags = FIELD_DP32(flags, TB_FLAGS, LMUL,
91                            FIELD_EX64(env->vtype, VTYPE, VLMUL));
92         flags = FIELD_DP32(flags, TB_FLAGS, VL_EQ_VLMAX, vl_eq_vlmax);
93         flags = FIELD_DP32(flags, TB_FLAGS, VTA,
94                            FIELD_EX64(env->vtype, VTYPE, VTA));
95         flags = FIELD_DP32(flags, TB_FLAGS, VMA,
96                            FIELD_EX64(env->vtype, VTYPE, VMA));
97         flags = FIELD_DP32(flags, TB_FLAGS, VSTART_EQ_ZERO, env->vstart == 0);
98     } else {
99         flags = FIELD_DP32(flags, TB_FLAGS, VILL, 1);
100     }
101 
102 #ifdef CONFIG_USER_ONLY
103     fs = EXT_STATUS_DIRTY;
104     vs = EXT_STATUS_DIRTY;
105 #else
106     flags = FIELD_DP32(flags, TB_FLAGS, PRIV, env->priv);
107 
108     flags |= cpu_mmu_index(env, 0);
109     fs = get_field(env->mstatus, MSTATUS_FS);
110     vs = get_field(env->mstatus, MSTATUS_VS);
111 
112     if (env->virt_enabled) {
113         flags = FIELD_DP32(flags, TB_FLAGS, VIRT_ENABLED, 1);
114         /*
115          * Merge DISABLED and !DIRTY states using MIN.
116          * We will set both fields when dirtying.
117          */
118         fs = MIN(fs, get_field(env->mstatus_hs, MSTATUS_FS));
119         vs = MIN(vs, get_field(env->mstatus_hs, MSTATUS_VS));
120     }
121 
122     if (cpu->cfg.debug && !icount_enabled()) {
123         flags = FIELD_DP32(flags, TB_FLAGS, ITRIGGER, env->itrigger_enabled);
124     }
125 #endif
126 
127     flags = FIELD_DP32(flags, TB_FLAGS, FS, fs);
128     flags = FIELD_DP32(flags, TB_FLAGS, VS, vs);
129     flags = FIELD_DP32(flags, TB_FLAGS, XL, env->xl);
130     if (env->cur_pmmask < (env->xl == MXL_RV32 ? UINT32_MAX : UINT64_MAX)) {
131         flags = FIELD_DP32(flags, TB_FLAGS, PM_MASK_ENABLED, 1);
132     }
133     if (env->cur_pmbase != 0) {
134         flags = FIELD_DP32(flags, TB_FLAGS, PM_BASE_ENABLED, 1);
135     }
136 
137     *pflags = flags;
138 }
139 
140 void riscv_cpu_update_mask(CPURISCVState *env)
141 {
142     target_ulong mask = -1, base = 0;
143     /*
144      * TODO: Current RVJ spec does not specify
145      * how the extension interacts with XLEN.
146      */
147 #ifndef CONFIG_USER_ONLY
148     if (riscv_has_ext(env, RVJ)) {
149         switch (env->priv) {
150         case PRV_M:
151             if (env->mmte & M_PM_ENABLE) {
152                 mask = env->mpmmask;
153                 base = env->mpmbase;
154             }
155             break;
156         case PRV_S:
157             if (env->mmte & S_PM_ENABLE) {
158                 mask = env->spmmask;
159                 base = env->spmbase;
160             }
161             break;
162         case PRV_U:
163             if (env->mmte & U_PM_ENABLE) {
164                 mask = env->upmmask;
165                 base = env->upmbase;
166             }
167             break;
168         default:
169             g_assert_not_reached();
170         }
171     }
172 #endif
173     if (env->xl == MXL_RV32) {
174         env->cur_pmmask = mask & UINT32_MAX;
175         env->cur_pmbase = base & UINT32_MAX;
176     } else {
177         env->cur_pmmask = mask;
178         env->cur_pmbase = base;
179     }
180 }
181 
182 #ifndef CONFIG_USER_ONLY
183 
184 /*
185  * The HS-mode is allowed to configure priority only for the
186  * following VS-mode local interrupts:
187  *
188  * 0  (Reserved interrupt, reads as zero)
189  * 1  Supervisor software interrupt
190  * 4  (Reserved interrupt, reads as zero)
191  * 5  Supervisor timer interrupt
192  * 8  (Reserved interrupt, reads as zero)
193  * 13 (Reserved interrupt)
194  * 14 "
195  * 15 "
196  * 16 "
197  * 17 "
198  * 18 "
199  * 19 "
200  * 20 "
201  * 21 "
202  * 22 "
203  * 23 "
204  */
205 
206 static const int hviprio_index2irq[] = {
207     0, 1, 4, 5, 8, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 };
208 static const int hviprio_index2rdzero[] = {
209     1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
210 
211 int riscv_cpu_hviprio_index2irq(int index, int *out_irq, int *out_rdzero)
212 {
213     if (index < 0 || ARRAY_SIZE(hviprio_index2irq) <= index) {
214         return -EINVAL;
215     }
216 
217     if (out_irq) {
218         *out_irq = hviprio_index2irq[index];
219     }
220 
221     if (out_rdzero) {
222         *out_rdzero = hviprio_index2rdzero[index];
223     }
224 
225     return 0;
226 }
227 
228 /*
229  * Default priorities of local interrupts are defined in the
230  * RISC-V Advanced Interrupt Architecture specification.
231  *
232  * ----------------------------------------------------------------
233  *  Default  |
234  *  Priority | Major Interrupt Numbers
235  * ----------------------------------------------------------------
236  *  Highest  | 47, 23, 46, 45, 22, 44,
237  *           | 43, 21, 42, 41, 20, 40
238  *           |
239  *           | 11 (0b),  3 (03),  7 (07)
240  *           |  9 (09),  1 (01),  5 (05)
241  *           | 12 (0c)
242  *           | 10 (0a),  2 (02),  6 (06)
243  *           |
244  *           | 39, 19, 38, 37, 18, 36,
245  *  Lowest   | 35, 17, 34, 33, 16, 32
246  * ----------------------------------------------------------------
247  */
248 static const uint8_t default_iprio[64] = {
249     /* Custom interrupts 48 to 63 */
250     [63] = IPRIO_MMAXIPRIO,
251     [62] = IPRIO_MMAXIPRIO,
252     [61] = IPRIO_MMAXIPRIO,
253     [60] = IPRIO_MMAXIPRIO,
254     [59] = IPRIO_MMAXIPRIO,
255     [58] = IPRIO_MMAXIPRIO,
256     [57] = IPRIO_MMAXIPRIO,
257     [56] = IPRIO_MMAXIPRIO,
258     [55] = IPRIO_MMAXIPRIO,
259     [54] = IPRIO_MMAXIPRIO,
260     [53] = IPRIO_MMAXIPRIO,
261     [52] = IPRIO_MMAXIPRIO,
262     [51] = IPRIO_MMAXIPRIO,
263     [50] = IPRIO_MMAXIPRIO,
264     [49] = IPRIO_MMAXIPRIO,
265     [48] = IPRIO_MMAXIPRIO,
266 
267     /* Custom interrupts 24 to 31 */
268     [31] = IPRIO_MMAXIPRIO,
269     [30] = IPRIO_MMAXIPRIO,
270     [29] = IPRIO_MMAXIPRIO,
271     [28] = IPRIO_MMAXIPRIO,
272     [27] = IPRIO_MMAXIPRIO,
273     [26] = IPRIO_MMAXIPRIO,
274     [25] = IPRIO_MMAXIPRIO,
275     [24] = IPRIO_MMAXIPRIO,
276 
277     [47] = IPRIO_DEFAULT_UPPER,
278     [23] = IPRIO_DEFAULT_UPPER + 1,
279     [46] = IPRIO_DEFAULT_UPPER + 2,
280     [45] = IPRIO_DEFAULT_UPPER + 3,
281     [22] = IPRIO_DEFAULT_UPPER + 4,
282     [44] = IPRIO_DEFAULT_UPPER + 5,
283 
284     [43] = IPRIO_DEFAULT_UPPER + 6,
285     [21] = IPRIO_DEFAULT_UPPER + 7,
286     [42] = IPRIO_DEFAULT_UPPER + 8,
287     [41] = IPRIO_DEFAULT_UPPER + 9,
288     [20] = IPRIO_DEFAULT_UPPER + 10,
289     [40] = IPRIO_DEFAULT_UPPER + 11,
290 
291     [11] = IPRIO_DEFAULT_M,
292     [3]  = IPRIO_DEFAULT_M + 1,
293     [7]  = IPRIO_DEFAULT_M + 2,
294 
295     [9]  = IPRIO_DEFAULT_S,
296     [1]  = IPRIO_DEFAULT_S + 1,
297     [5]  = IPRIO_DEFAULT_S + 2,
298 
299     [12] = IPRIO_DEFAULT_SGEXT,
300 
301     [10] = IPRIO_DEFAULT_VS,
302     [2]  = IPRIO_DEFAULT_VS + 1,
303     [6]  = IPRIO_DEFAULT_VS + 2,
304 
305     [39] = IPRIO_DEFAULT_LOWER,
306     [19] = IPRIO_DEFAULT_LOWER + 1,
307     [38] = IPRIO_DEFAULT_LOWER + 2,
308     [37] = IPRIO_DEFAULT_LOWER + 3,
309     [18] = IPRIO_DEFAULT_LOWER + 4,
310     [36] = IPRIO_DEFAULT_LOWER + 5,
311 
312     [35] = IPRIO_DEFAULT_LOWER + 6,
313     [17] = IPRIO_DEFAULT_LOWER + 7,
314     [34] = IPRIO_DEFAULT_LOWER + 8,
315     [33] = IPRIO_DEFAULT_LOWER + 9,
316     [16] = IPRIO_DEFAULT_LOWER + 10,
317     [32] = IPRIO_DEFAULT_LOWER + 11,
318 };
319 
320 uint8_t riscv_cpu_default_priority(int irq)
321 {
322     if (irq < 0 || irq > 63) {
323         return IPRIO_MMAXIPRIO;
324     }
325 
326     return default_iprio[irq] ? default_iprio[irq] : IPRIO_MMAXIPRIO;
327 };
328 
329 static int riscv_cpu_pending_to_irq(CPURISCVState *env,
330                                     int extirq, unsigned int extirq_def_prio,
331                                     uint64_t pending, uint8_t *iprio)
332 {
333     int irq, best_irq = RISCV_EXCP_NONE;
334     unsigned int prio, best_prio = UINT_MAX;
335 
336     if (!pending) {
337         return RISCV_EXCP_NONE;
338     }
339 
340     irq = ctz64(pending);
341     if (!((extirq == IRQ_M_EXT) ? riscv_cpu_cfg(env)->ext_smaia :
342                                   riscv_cpu_cfg(env)->ext_ssaia)) {
343         return irq;
344     }
345 
346     pending = pending >> irq;
347     while (pending) {
348         prio = iprio[irq];
349         if (!prio) {
350             if (irq == extirq) {
351                 prio = extirq_def_prio;
352             } else {
353                 prio = (riscv_cpu_default_priority(irq) < extirq_def_prio) ?
354                        1 : IPRIO_MMAXIPRIO;
355             }
356         }
357         if ((pending & 0x1) && (prio <= best_prio)) {
358             best_irq = irq;
359             best_prio = prio;
360         }
361         irq++;
362         pending = pending >> 1;
363     }
364 
365     return best_irq;
366 }
367 
368 uint64_t riscv_cpu_all_pending(CPURISCVState *env)
369 {
370     uint32_t gein = get_field(env->hstatus, HSTATUS_VGEIN);
371     uint64_t vsgein = (env->hgeip & (1ULL << gein)) ? MIP_VSEIP : 0;
372     uint64_t vstip = (env->vstime_irq) ? MIP_VSTIP : 0;
373 
374     return (env->mip | vsgein | vstip) & env->mie;
375 }
376 
377 int riscv_cpu_mirq_pending(CPURISCVState *env)
378 {
379     uint64_t irqs = riscv_cpu_all_pending(env) & ~env->mideleg &
380                     ~(MIP_SGEIP | MIP_VSSIP | MIP_VSTIP | MIP_VSEIP);
381 
382     return riscv_cpu_pending_to_irq(env, IRQ_M_EXT, IPRIO_DEFAULT_M,
383                                     irqs, env->miprio);
384 }
385 
386 int riscv_cpu_sirq_pending(CPURISCVState *env)
387 {
388     uint64_t irqs = riscv_cpu_all_pending(env) & env->mideleg &
389                     ~(MIP_VSSIP | MIP_VSTIP | MIP_VSEIP);
390 
391     return riscv_cpu_pending_to_irq(env, IRQ_S_EXT, IPRIO_DEFAULT_S,
392                                     irqs, env->siprio);
393 }
394 
395 int riscv_cpu_vsirq_pending(CPURISCVState *env)
396 {
397     uint64_t irqs = riscv_cpu_all_pending(env) & env->mideleg &
398                     (MIP_VSSIP | MIP_VSTIP | MIP_VSEIP);
399 
400     return riscv_cpu_pending_to_irq(env, IRQ_S_EXT, IPRIO_DEFAULT_S,
401                                     irqs >> 1, env->hviprio);
402 }
403 
404 static int riscv_cpu_local_irq_pending(CPURISCVState *env)
405 {
406     int virq;
407     uint64_t irqs, pending, mie, hsie, vsie;
408 
409     /* Determine interrupt enable state of all privilege modes */
410     if (env->virt_enabled) {
411         mie = 1;
412         hsie = 1;
413         vsie = (env->priv < PRV_S) ||
414                (env->priv == PRV_S && get_field(env->mstatus, MSTATUS_SIE));
415     } else {
416         mie = (env->priv < PRV_M) ||
417               (env->priv == PRV_M && get_field(env->mstatus, MSTATUS_MIE));
418         hsie = (env->priv < PRV_S) ||
419                (env->priv == PRV_S && get_field(env->mstatus, MSTATUS_SIE));
420         vsie = 0;
421     }
422 
423     /* Determine all pending interrupts */
424     pending = riscv_cpu_all_pending(env);
425 
426     /* Check M-mode interrupts */
427     irqs = pending & ~env->mideleg & -mie;
428     if (irqs) {
429         return riscv_cpu_pending_to_irq(env, IRQ_M_EXT, IPRIO_DEFAULT_M,
430                                         irqs, env->miprio);
431     }
432 
433     /* Check HS-mode interrupts */
434     irqs = pending & env->mideleg & ~env->hideleg & -hsie;
435     if (irqs) {
436         return riscv_cpu_pending_to_irq(env, IRQ_S_EXT, IPRIO_DEFAULT_S,
437                                         irqs, env->siprio);
438     }
439 
440     /* Check VS-mode interrupts */
441     irqs = pending & env->mideleg & env->hideleg & -vsie;
442     if (irqs) {
443         virq = riscv_cpu_pending_to_irq(env, IRQ_S_EXT, IPRIO_DEFAULT_S,
444                                         irqs >> 1, env->hviprio);
445         return (virq <= 0) ? virq : virq + 1;
446     }
447 
448     /* Indicate no pending interrupt */
449     return RISCV_EXCP_NONE;
450 }
451 
452 bool riscv_cpu_exec_interrupt(CPUState *cs, int interrupt_request)
453 {
454     if (interrupt_request & CPU_INTERRUPT_HARD) {
455         RISCVCPU *cpu = RISCV_CPU(cs);
456         CPURISCVState *env = &cpu->env;
457         int interruptno = riscv_cpu_local_irq_pending(env);
458         if (interruptno >= 0) {
459             cs->exception_index = RISCV_EXCP_INT_FLAG | interruptno;
460             riscv_cpu_do_interrupt(cs);
461             return true;
462         }
463     }
464     return false;
465 }
466 
467 /* Return true is floating point support is currently enabled */
468 bool riscv_cpu_fp_enabled(CPURISCVState *env)
469 {
470     if (env->mstatus & MSTATUS_FS) {
471         if (env->virt_enabled && !(env->mstatus_hs & MSTATUS_FS)) {
472             return false;
473         }
474         return true;
475     }
476 
477     return false;
478 }
479 
480 /* Return true is vector support is currently enabled */
481 bool riscv_cpu_vector_enabled(CPURISCVState *env)
482 {
483     if (env->mstatus & MSTATUS_VS) {
484         if (env->virt_enabled && !(env->mstatus_hs & MSTATUS_VS)) {
485             return false;
486         }
487         return true;
488     }
489 
490     return false;
491 }
492 
493 void riscv_cpu_swap_hypervisor_regs(CPURISCVState *env)
494 {
495     uint64_t mstatus_mask = MSTATUS_MXR | MSTATUS_SUM |
496                             MSTATUS_SPP | MSTATUS_SPIE | MSTATUS_SIE |
497                             MSTATUS64_UXL | MSTATUS_VS;
498 
499     if (riscv_has_ext(env, RVF)) {
500         mstatus_mask |= MSTATUS_FS;
501     }
502     bool current_virt = env->virt_enabled;
503 
504     g_assert(riscv_has_ext(env, RVH));
505 
506     if (current_virt) {
507         /* Current V=1 and we are about to change to V=0 */
508         env->vsstatus = env->mstatus & mstatus_mask;
509         env->mstatus &= ~mstatus_mask;
510         env->mstatus |= env->mstatus_hs;
511 
512         env->vstvec = env->stvec;
513         env->stvec = env->stvec_hs;
514 
515         env->vsscratch = env->sscratch;
516         env->sscratch = env->sscratch_hs;
517 
518         env->vsepc = env->sepc;
519         env->sepc = env->sepc_hs;
520 
521         env->vscause = env->scause;
522         env->scause = env->scause_hs;
523 
524         env->vstval = env->stval;
525         env->stval = env->stval_hs;
526 
527         env->vsatp = env->satp;
528         env->satp = env->satp_hs;
529     } else {
530         /* Current V=0 and we are about to change to V=1 */
531         env->mstatus_hs = env->mstatus & mstatus_mask;
532         env->mstatus &= ~mstatus_mask;
533         env->mstatus |= env->vsstatus;
534 
535         env->stvec_hs = env->stvec;
536         env->stvec = env->vstvec;
537 
538         env->sscratch_hs = env->sscratch;
539         env->sscratch = env->vsscratch;
540 
541         env->sepc_hs = env->sepc;
542         env->sepc = env->vsepc;
543 
544         env->scause_hs = env->scause;
545         env->scause = env->vscause;
546 
547         env->stval_hs = env->stval;
548         env->stval = env->vstval;
549 
550         env->satp_hs = env->satp;
551         env->satp = env->vsatp;
552     }
553 }
554 
555 target_ulong riscv_cpu_get_geilen(CPURISCVState *env)
556 {
557     if (!riscv_has_ext(env, RVH)) {
558         return 0;
559     }
560 
561     return env->geilen;
562 }
563 
564 void riscv_cpu_set_geilen(CPURISCVState *env, target_ulong geilen)
565 {
566     if (!riscv_has_ext(env, RVH)) {
567         return;
568     }
569 
570     if (geilen > (TARGET_LONG_BITS - 1)) {
571         return;
572     }
573 
574     env->geilen = geilen;
575 }
576 
577 /* This function can only be called to set virt when RVH is enabled */
578 void riscv_cpu_set_virt_enabled(CPURISCVState *env, bool enable)
579 {
580     /* Flush the TLB on all virt mode changes. */
581     if (env->virt_enabled != enable) {
582         tlb_flush(env_cpu(env));
583     }
584 
585     env->virt_enabled = enable;
586 
587     if (enable) {
588         /*
589          * The guest external interrupts from an interrupt controller are
590          * delivered only when the Guest/VM is running (i.e. V=1). This means
591          * any guest external interrupt which is triggered while the Guest/VM
592          * is not running (i.e. V=0) will be missed on QEMU resulting in guest
593          * with sluggish response to serial console input and other I/O events.
594          *
595          * To solve this, we check and inject interrupt after setting V=1.
596          */
597         riscv_cpu_update_mip(env, 0, 0);
598     }
599 }
600 
601 int riscv_cpu_claim_interrupts(RISCVCPU *cpu, uint64_t interrupts)
602 {
603     CPURISCVState *env = &cpu->env;
604     if (env->miclaim & interrupts) {
605         return -1;
606     } else {
607         env->miclaim |= interrupts;
608         return 0;
609     }
610 }
611 
612 uint64_t riscv_cpu_update_mip(CPURISCVState *env, uint64_t mask,
613                               uint64_t value)
614 {
615     CPUState *cs = env_cpu(env);
616     uint64_t gein, vsgein = 0, vstip = 0, old = env->mip;
617 
618     if (env->virt_enabled) {
619         gein = get_field(env->hstatus, HSTATUS_VGEIN);
620         vsgein = (env->hgeip & (1ULL << gein)) ? MIP_VSEIP : 0;
621     }
622 
623     vstip = env->vstime_irq ? MIP_VSTIP : 0;
624 
625     QEMU_IOTHREAD_LOCK_GUARD();
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     return old;
636 }
637 
638 void riscv_cpu_set_rdtime_fn(CPURISCVState *env, uint64_t (*fn)(void *),
639                              void *arg)
640 {
641     env->rdtime_fn = fn;
642     env->rdtime_fn_arg = arg;
643 }
644 
645 void riscv_cpu_set_aia_ireg_rmw_fn(CPURISCVState *env, uint32_t priv,
646                                    int (*rmw_fn)(void *arg,
647                                                  target_ulong reg,
648                                                  target_ulong *val,
649                                                  target_ulong new_val,
650                                                  target_ulong write_mask),
651                                    void *rmw_fn_arg)
652 {
653     if (priv <= PRV_M) {
654         env->aia_ireg_rmw_fn[priv] = rmw_fn;
655         env->aia_ireg_rmw_fn_arg[priv] = rmw_fn_arg;
656     }
657 }
658 
659 void riscv_cpu_set_mode(CPURISCVState *env, target_ulong newpriv)
660 {
661     g_assert(newpriv <= PRV_M && newpriv != PRV_RESERVED);
662 
663     if (icount_enabled() && newpriv != env->priv) {
664         riscv_itrigger_update_priv(env);
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     int pmp_index = -1;
703 
704     if (!riscv_cpu_cfg(env)->pmp) {
705         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
706         return TRANSLATE_SUCCESS;
707     }
708 
709     pmp_index = pmp_hart_has_privs(env, addr, size, 1 << access_type,
710                                    &pmp_priv, mode);
711     if (pmp_index < 0) {
712         *prot = 0;
713         return TRANSLATE_PMP_FAIL;
714     }
715 
716     *prot = pmp_priv_to_page_prot(pmp_priv);
717     if ((tlb_size != NULL) && pmp_index != MAX_RISCV_PMPS) {
718         target_ulong tlb_sa = addr & ~(TARGET_PAGE_SIZE - 1);
719         target_ulong tlb_ea = tlb_sa + TARGET_PAGE_SIZE - 1;
720 
721         *tlb_size = pmp_get_tlb_size(env, pmp_index, tlb_sa, tlb_ea);
722     }
723 
724     return TRANSLATE_SUCCESS;
725 }
726 
727 /*
728  * get_physical_address - get the physical address for this virtual address
729  *
730  * Do a page table walk to obtain the physical address corresponding to a
731  * virtual address. Returns 0 if the translation was successful
732  *
733  * Adapted from Spike's mmu_t::translate and mmu_t::walk
734  *
735  * @env: CPURISCVState
736  * @physical: This will be set to the calculated physical address
737  * @prot: The returned protection attributes
738  * @addr: The virtual address or guest physical address to be translated
739  * @fault_pte_addr: If not NULL, this will be set to fault pte address
740  *                  when a error occurs on pte address translation.
741  *                  This will already be shifted to match htval.
742  * @access_type: The type of MMU access
743  * @mmu_idx: Indicates current privilege level
744  * @first_stage: Are we in first stage translation?
745  *               Second stage is used for hypervisor guest translation
746  * @two_stage: Are we going to perform two stage translation
747  * @is_debug: Is this access from a debugger or the monitor?
748  */
749 static int get_physical_address(CPURISCVState *env, hwaddr *physical,
750                                 int *prot, vaddr addr,
751                                 target_ulong *fault_pte_addr,
752                                 int access_type, int mmu_idx,
753                                 bool first_stage, bool two_stage,
754                                 bool is_debug)
755 {
756     /*
757      * NOTE: the env->pc value visible here will not be
758      * correct, but the value visible to the exception handler
759      * (riscv_cpu_do_interrupt) is correct
760      */
761     MemTxResult res;
762     MemTxAttrs attrs = MEMTXATTRS_UNSPECIFIED;
763     int mode = mmuidx_priv(mmu_idx);
764     bool use_background = false;
765     hwaddr ppn;
766     int napot_bits = 0;
767     target_ulong napot_mask;
768 
769     /*
770      * Check if we should use the background registers for the two
771      * stage translation. We don't need to check if we actually need
772      * two stage translation as that happened before this function
773      * was called. Background registers will be used if the guest has
774      * forced a two stage translation to be on (in HS or M mode).
775      */
776     if (!env->virt_enabled && two_stage) {
777         use_background = true;
778     }
779 
780     if (first_stage == false) {
781         /*
782          * We are in stage 2 translation, this is similar to stage 1.
783          * Stage 2 is always taken as U-mode
784          */
785         mode = PRV_U;
786     }
787 
788     if (mode == PRV_M || !riscv_cpu_cfg(env)->mmu) {
789         *physical = addr;
790         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
791         return TRANSLATE_SUCCESS;
792     }
793 
794     *prot = 0;
795 
796     hwaddr base;
797     int levels, ptidxbits, ptesize, vm, sum, mxr, widened;
798 
799     if (first_stage == true) {
800         mxr = get_field(env->mstatus, MSTATUS_MXR);
801     } else {
802         mxr = get_field(env->vsstatus, MSTATUS_MXR);
803     }
804 
805     if (first_stage == true) {
806         if (use_background) {
807             if (riscv_cpu_mxl(env) == MXL_RV32) {
808                 base = (hwaddr)get_field(env->vsatp, SATP32_PPN) << PGSHIFT;
809                 vm = get_field(env->vsatp, SATP32_MODE);
810             } else {
811                 base = (hwaddr)get_field(env->vsatp, SATP64_PPN) << PGSHIFT;
812                 vm = get_field(env->vsatp, SATP64_MODE);
813             }
814         } else {
815             if (riscv_cpu_mxl(env) == MXL_RV32) {
816                 base = (hwaddr)get_field(env->satp, SATP32_PPN) << PGSHIFT;
817                 vm = get_field(env->satp, SATP32_MODE);
818             } else {
819                 base = (hwaddr)get_field(env->satp, SATP64_PPN) << PGSHIFT;
820                 vm = get_field(env->satp, SATP64_MODE);
821             }
822         }
823         widened = 0;
824     } else {
825         if (riscv_cpu_mxl(env) == MXL_RV32) {
826             base = (hwaddr)get_field(env->hgatp, SATP32_PPN) << PGSHIFT;
827             vm = get_field(env->hgatp, SATP32_MODE);
828         } else {
829             base = (hwaddr)get_field(env->hgatp, SATP64_PPN) << PGSHIFT;
830             vm = get_field(env->hgatp, SATP64_MODE);
831         }
832         widened = 2;
833     }
834     sum = mmuidx_sum(mmu_idx) || is_debug;
835     switch (vm) {
836     case VM_1_10_SV32:
837       levels = 2; ptidxbits = 10; ptesize = 4; break;
838     case VM_1_10_SV39:
839       levels = 3; ptidxbits = 9; ptesize = 8; break;
840     case VM_1_10_SV48:
841       levels = 4; ptidxbits = 9; ptesize = 8; break;
842     case VM_1_10_SV57:
843       levels = 5; ptidxbits = 9; ptesize = 8; break;
844     case VM_1_10_MBARE:
845         *physical = addr;
846         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
847         return TRANSLATE_SUCCESS;
848     default:
849       g_assert_not_reached();
850     }
851 
852     CPUState *cs = env_cpu(env);
853     int va_bits = PGSHIFT + levels * ptidxbits + widened;
854     target_ulong mask, masked_msbs;
855 
856     if (TARGET_LONG_BITS > (va_bits - 1)) {
857         mask = (1L << (TARGET_LONG_BITS - (va_bits - 1))) - 1;
858     } else {
859         mask = 0;
860     }
861     masked_msbs = (addr >> (va_bits - 1)) & mask;
862 
863     if (masked_msbs != 0 && masked_msbs != mask) {
864         return TRANSLATE_FAIL;
865     }
866 
867     int ptshift = (levels - 1) * ptidxbits;
868     int i;
869 
870 #if !TCG_OVERSIZED_GUEST
871 restart:
872 #endif
873     for (i = 0; i < levels; i++, ptshift -= ptidxbits) {
874         target_ulong idx;
875         if (i == 0) {
876             idx = (addr >> (PGSHIFT + ptshift)) &
877                            ((1 << (ptidxbits + widened)) - 1);
878         } else {
879             idx = (addr >> (PGSHIFT + ptshift)) &
880                            ((1 << ptidxbits) - 1);
881         }
882 
883         /* check that physical address of PTE is legal */
884         hwaddr pte_addr;
885 
886         if (two_stage && first_stage) {
887             int vbase_prot;
888             hwaddr vbase;
889 
890             /* Do the second stage translation on the base PTE address. */
891             int vbase_ret = get_physical_address(env, &vbase, &vbase_prot,
892                                                  base, NULL, MMU_DATA_LOAD,
893                                                  mmu_idx, false, true,
894                                                  is_debug);
895 
896             if (vbase_ret != TRANSLATE_SUCCESS) {
897                 if (fault_pte_addr) {
898                     *fault_pte_addr = (base + idx * ptesize) >> 2;
899                 }
900                 return TRANSLATE_G_STAGE_FAIL;
901             }
902 
903             pte_addr = vbase + idx * ptesize;
904         } else {
905             pte_addr = base + idx * ptesize;
906         }
907 
908         int pmp_prot;
909         int pmp_ret = get_physical_address_pmp(env, &pmp_prot, NULL, pte_addr,
910                                                sizeof(target_ulong),
911                                                MMU_DATA_LOAD, PRV_S);
912         if (pmp_ret != TRANSLATE_SUCCESS) {
913             return TRANSLATE_PMP_FAIL;
914         }
915 
916         target_ulong pte;
917         if (riscv_cpu_mxl(env) == MXL_RV32) {
918             pte = address_space_ldl(cs->as, pte_addr, attrs, &res);
919         } else {
920             pte = address_space_ldq(cs->as, pte_addr, attrs, &res);
921         }
922 
923         if (res != MEMTX_OK) {
924             return TRANSLATE_FAIL;
925         }
926 
927         bool pbmte = env->menvcfg & MENVCFG_PBMTE;
928         bool hade = env->menvcfg & MENVCFG_HADE;
929 
930         if (first_stage && two_stage && env->virt_enabled) {
931             pbmte = pbmte && (env->henvcfg & HENVCFG_PBMTE);
932             hade = hade && (env->henvcfg & HENVCFG_HADE);
933         }
934 
935         if (riscv_cpu_sxl(env) == MXL_RV32) {
936             ppn = pte >> PTE_PPN_SHIFT;
937         } else if (pbmte || riscv_cpu_cfg(env)->ext_svnapot) {
938             ppn = (pte & (target_ulong)PTE_PPN_MASK) >> PTE_PPN_SHIFT;
939         } else {
940             ppn = pte >> PTE_PPN_SHIFT;
941             if ((pte & ~(target_ulong)PTE_PPN_MASK) >> PTE_PPN_SHIFT) {
942                 return TRANSLATE_FAIL;
943             }
944         }
945 
946         if (!(pte & PTE_V)) {
947             /* Invalid PTE */
948             return TRANSLATE_FAIL;
949         } else if (!pbmte && (pte & PTE_PBMT)) {
950             return TRANSLATE_FAIL;
951         } else if (!(pte & (PTE_R | PTE_W | PTE_X))) {
952             /* Inner PTE, continue walking */
953             if (pte & (PTE_D | PTE_A | PTE_U | PTE_ATTR)) {
954                 return TRANSLATE_FAIL;
955             }
956             base = ppn << PGSHIFT;
957         } else if ((pte & (PTE_R | PTE_W | PTE_X)) == PTE_W) {
958             /* Reserved leaf PTE flags: PTE_W */
959             return TRANSLATE_FAIL;
960         } else if ((pte & (PTE_R | PTE_W | PTE_X)) == (PTE_W | PTE_X)) {
961             /* Reserved leaf PTE flags: PTE_W + PTE_X */
962             return TRANSLATE_FAIL;
963         } else if ((pte & PTE_U) && ((mode != PRV_U) &&
964                    (!sum || access_type == MMU_INST_FETCH))) {
965             /* User PTE flags when not U mode and mstatus.SUM is not set,
966                or the access type is an instruction fetch */
967             return TRANSLATE_FAIL;
968         } else if (!(pte & PTE_U) && (mode != PRV_S)) {
969             /* Supervisor PTE flags when not S mode */
970             return TRANSLATE_FAIL;
971         } else if (ppn & ((1ULL << ptshift) - 1)) {
972             /* Misaligned PPN */
973             return TRANSLATE_FAIL;
974         } else if (access_type == MMU_DATA_LOAD && !((pte & PTE_R) ||
975                    ((pte & PTE_X) && mxr))) {
976             /* Read access check failed */
977             return TRANSLATE_FAIL;
978         } else if (access_type == MMU_DATA_STORE && !(pte & PTE_W)) {
979             /* Write access check failed */
980             return TRANSLATE_FAIL;
981         } else if (access_type == MMU_INST_FETCH && !(pte & PTE_X)) {
982             /* Fetch access check failed */
983             return TRANSLATE_FAIL;
984         } else {
985             /* if necessary, set accessed and dirty bits. */
986             target_ulong updated_pte = pte | PTE_A |
987                 (access_type == MMU_DATA_STORE ? PTE_D : 0);
988 
989             /* Page table updates need to be atomic with MTTCG enabled */
990             if (updated_pte != pte) {
991                 if (!hade) {
992                     return TRANSLATE_FAIL;
993                 }
994 
995                 /*
996                  * - if accessed or dirty bits need updating, and the PTE is
997                  *   in RAM, then we do so atomically with a compare and swap.
998                  * - if the PTE is in IO space or ROM, then it can't be updated
999                  *   and we return TRANSLATE_FAIL.
1000                  * - if the PTE changed by the time we went to update it, then
1001                  *   it is no longer valid and we must re-walk the page table.
1002                  */
1003                 MemoryRegion *mr;
1004                 hwaddr l = sizeof(target_ulong), addr1;
1005                 mr = address_space_translate(cs->as, pte_addr, &addr1, &l,
1006                                              false, MEMTXATTRS_UNSPECIFIED);
1007                 if (memory_region_is_ram(mr)) {
1008                     target_ulong *pte_pa =
1009                         qemu_map_ram_ptr(mr->ram_block, addr1);
1010 #if TCG_OVERSIZED_GUEST
1011                     /*
1012                      * MTTCG is not enabled on oversized TCG guests so
1013                      * page table updates do not need to be atomic
1014                      */
1015                     *pte_pa = pte = updated_pte;
1016 #else
1017                     target_ulong old_pte =
1018                         qatomic_cmpxchg(pte_pa, pte, updated_pte);
1019                     if (old_pte != pte) {
1020                         goto restart;
1021                     } else {
1022                         pte = updated_pte;
1023                     }
1024 #endif
1025                 } else {
1026                     /*
1027                      * misconfigured PTE in ROM (AD bits are not preset) or
1028                      * PTE is in IO space and can't be updated atomically
1029                      */
1030                     return TRANSLATE_FAIL;
1031                 }
1032             }
1033 
1034             /*
1035              * for superpage mappings, make a fake leaf PTE for the TLB's
1036              * benefit.
1037              */
1038             target_ulong vpn = addr >> PGSHIFT;
1039 
1040             if (riscv_cpu_cfg(env)->ext_svnapot && (pte & PTE_N)) {
1041                 napot_bits = ctzl(ppn) + 1;
1042                 if ((i != (levels - 1)) || (napot_bits != 4)) {
1043                     return TRANSLATE_FAIL;
1044                 }
1045             }
1046 
1047             napot_mask = (1 << napot_bits) - 1;
1048             *physical = (((ppn & ~napot_mask) | (vpn & napot_mask) |
1049                           (vpn & (((target_ulong)1 << ptshift) - 1))
1050                          ) << PGSHIFT) | (addr & ~TARGET_PAGE_MASK);
1051 
1052             /* set permissions on the TLB entry */
1053             if ((pte & PTE_R) || ((pte & PTE_X) && mxr)) {
1054                 *prot |= PAGE_READ;
1055             }
1056             if (pte & PTE_X) {
1057                 *prot |= PAGE_EXEC;
1058             }
1059             /*
1060              * add write permission on stores or if the page is already dirty,
1061              * so that we TLB miss on later writes to update the dirty bit
1062              */
1063             if ((pte & PTE_W) &&
1064                 (access_type == MMU_DATA_STORE || (pte & PTE_D))) {
1065                 *prot |= PAGE_WRITE;
1066             }
1067             return TRANSLATE_SUCCESS;
1068         }
1069     }
1070     return TRANSLATE_FAIL;
1071 }
1072 
1073 static void raise_mmu_exception(CPURISCVState *env, target_ulong address,
1074                                 MMUAccessType access_type, bool pmp_violation,
1075                                 bool first_stage, bool two_stage,
1076                                 bool two_stage_indirect)
1077 {
1078     CPUState *cs = env_cpu(env);
1079     int page_fault_exceptions, vm;
1080     uint64_t stap_mode;
1081 
1082     if (riscv_cpu_mxl(env) == MXL_RV32) {
1083         stap_mode = SATP32_MODE;
1084     } else {
1085         stap_mode = SATP64_MODE;
1086     }
1087 
1088     if (first_stage) {
1089         vm = get_field(env->satp, stap_mode);
1090     } else {
1091         vm = get_field(env->hgatp, stap_mode);
1092     }
1093 
1094     page_fault_exceptions = vm != VM_1_10_MBARE && !pmp_violation;
1095 
1096     switch (access_type) {
1097     case MMU_INST_FETCH:
1098         if (env->virt_enabled && !first_stage) {
1099             cs->exception_index = RISCV_EXCP_INST_GUEST_PAGE_FAULT;
1100         } else {
1101             cs->exception_index = page_fault_exceptions ?
1102                 RISCV_EXCP_INST_PAGE_FAULT : RISCV_EXCP_INST_ACCESS_FAULT;
1103         }
1104         break;
1105     case MMU_DATA_LOAD:
1106         if (two_stage && !first_stage) {
1107             cs->exception_index = RISCV_EXCP_LOAD_GUEST_ACCESS_FAULT;
1108         } else {
1109             cs->exception_index = page_fault_exceptions ?
1110                 RISCV_EXCP_LOAD_PAGE_FAULT : RISCV_EXCP_LOAD_ACCESS_FAULT;
1111         }
1112         break;
1113     case MMU_DATA_STORE:
1114         if (two_stage && !first_stage) {
1115             cs->exception_index = RISCV_EXCP_STORE_GUEST_AMO_ACCESS_FAULT;
1116         } else {
1117             cs->exception_index = page_fault_exceptions ?
1118                 RISCV_EXCP_STORE_PAGE_FAULT :
1119                 RISCV_EXCP_STORE_AMO_ACCESS_FAULT;
1120         }
1121         break;
1122     default:
1123         g_assert_not_reached();
1124     }
1125     env->badaddr = address;
1126     env->two_stage_lookup = two_stage;
1127     env->two_stage_indirect_lookup = two_stage_indirect;
1128 }
1129 
1130 hwaddr riscv_cpu_get_phys_page_debug(CPUState *cs, vaddr addr)
1131 {
1132     RISCVCPU *cpu = RISCV_CPU(cs);
1133     CPURISCVState *env = &cpu->env;
1134     hwaddr phys_addr;
1135     int prot;
1136     int mmu_idx = cpu_mmu_index(&cpu->env, false);
1137 
1138     if (get_physical_address(env, &phys_addr, &prot, addr, NULL, 0, mmu_idx,
1139                              true, env->virt_enabled, true)) {
1140         return -1;
1141     }
1142 
1143     if (env->virt_enabled) {
1144         if (get_physical_address(env, &phys_addr, &prot, phys_addr, NULL,
1145                                  0, mmu_idx, false, true, true)) {
1146             return -1;
1147         }
1148     }
1149 
1150     return phys_addr & TARGET_PAGE_MASK;
1151 }
1152 
1153 void riscv_cpu_do_transaction_failed(CPUState *cs, hwaddr physaddr,
1154                                      vaddr addr, unsigned size,
1155                                      MMUAccessType access_type,
1156                                      int mmu_idx, MemTxAttrs attrs,
1157                                      MemTxResult response, uintptr_t retaddr)
1158 {
1159     RISCVCPU *cpu = RISCV_CPU(cs);
1160     CPURISCVState *env = &cpu->env;
1161 
1162     if (access_type == MMU_DATA_STORE) {
1163         cs->exception_index = RISCV_EXCP_STORE_AMO_ACCESS_FAULT;
1164     } else if (access_type == MMU_DATA_LOAD) {
1165         cs->exception_index = RISCV_EXCP_LOAD_ACCESS_FAULT;
1166     } else {
1167         cs->exception_index = RISCV_EXCP_INST_ACCESS_FAULT;
1168     }
1169 
1170     env->badaddr = addr;
1171     env->two_stage_lookup = mmuidx_2stage(mmu_idx);
1172     env->two_stage_indirect_lookup = false;
1173     cpu_loop_exit_restore(cs, retaddr);
1174 }
1175 
1176 void riscv_cpu_do_unaligned_access(CPUState *cs, vaddr addr,
1177                                    MMUAccessType access_type, int mmu_idx,
1178                                    uintptr_t retaddr)
1179 {
1180     RISCVCPU *cpu = RISCV_CPU(cs);
1181     CPURISCVState *env = &cpu->env;
1182     switch (access_type) {
1183     case MMU_INST_FETCH:
1184         cs->exception_index = RISCV_EXCP_INST_ADDR_MIS;
1185         break;
1186     case MMU_DATA_LOAD:
1187         cs->exception_index = RISCV_EXCP_LOAD_ADDR_MIS;
1188         break;
1189     case MMU_DATA_STORE:
1190         cs->exception_index = RISCV_EXCP_STORE_AMO_ADDR_MIS;
1191         break;
1192     default:
1193         g_assert_not_reached();
1194     }
1195     env->badaddr = addr;
1196     env->two_stage_lookup = mmuidx_2stage(mmu_idx);
1197     env->two_stage_indirect_lookup = false;
1198     cpu_loop_exit_restore(cs, retaddr);
1199 }
1200 
1201 
1202 static void pmu_tlb_fill_incr_ctr(RISCVCPU *cpu, MMUAccessType access_type)
1203 {
1204     enum riscv_pmu_event_idx pmu_event_type;
1205 
1206     switch (access_type) {
1207     case MMU_INST_FETCH:
1208         pmu_event_type = RISCV_PMU_EVENT_CACHE_ITLB_PREFETCH_MISS;
1209         break;
1210     case MMU_DATA_LOAD:
1211         pmu_event_type = RISCV_PMU_EVENT_CACHE_DTLB_READ_MISS;
1212         break;
1213     case MMU_DATA_STORE:
1214         pmu_event_type = RISCV_PMU_EVENT_CACHE_DTLB_WRITE_MISS;
1215         break;
1216     default:
1217         return;
1218     }
1219 
1220     riscv_pmu_incr_ctr(cpu, pmu_event_type);
1221 }
1222 
1223 bool riscv_cpu_tlb_fill(CPUState *cs, vaddr address, int size,
1224                         MMUAccessType access_type, int mmu_idx,
1225                         bool probe, uintptr_t retaddr)
1226 {
1227     RISCVCPU *cpu = RISCV_CPU(cs);
1228     CPURISCVState *env = &cpu->env;
1229     vaddr im_address;
1230     hwaddr pa = 0;
1231     int prot, prot2, prot_pmp;
1232     bool pmp_violation = false;
1233     bool first_stage_error = true;
1234     bool two_stage_lookup = mmuidx_2stage(mmu_idx);
1235     bool two_stage_indirect_error = false;
1236     int ret = TRANSLATE_FAIL;
1237     int mode = mmu_idx;
1238     /* default TLB page size */
1239     target_ulong tlb_size = TARGET_PAGE_SIZE;
1240 
1241     env->guest_phys_fault_addr = 0;
1242 
1243     qemu_log_mask(CPU_LOG_MMU, "%s ad %" VADDR_PRIx " rw %d mmu_idx %d\n",
1244                   __func__, address, access_type, mmu_idx);
1245 
1246     pmu_tlb_fill_incr_ctr(cpu, access_type);
1247     if (two_stage_lookup) {
1248         /* Two stage lookup */
1249         ret = get_physical_address(env, &pa, &prot, address,
1250                                    &env->guest_phys_fault_addr, access_type,
1251                                    mmu_idx, true, true, false);
1252 
1253         /*
1254          * A G-stage exception may be triggered during two state lookup.
1255          * And the env->guest_phys_fault_addr has already been set in
1256          * get_physical_address().
1257          */
1258         if (ret == TRANSLATE_G_STAGE_FAIL) {
1259             first_stage_error = false;
1260             two_stage_indirect_error = true;
1261             access_type = MMU_DATA_LOAD;
1262         }
1263 
1264         qemu_log_mask(CPU_LOG_MMU,
1265                       "%s 1st-stage address=%" VADDR_PRIx " ret %d physical "
1266                       HWADDR_FMT_plx " prot %d\n",
1267                       __func__, address, ret, pa, prot);
1268 
1269         if (ret == TRANSLATE_SUCCESS) {
1270             /* Second stage lookup */
1271             im_address = pa;
1272 
1273             ret = get_physical_address(env, &pa, &prot2, im_address, NULL,
1274                                        access_type, mmu_idx, false, true,
1275                                        false);
1276 
1277             qemu_log_mask(CPU_LOG_MMU,
1278                           "%s 2nd-stage address=%" VADDR_PRIx
1279                           " ret %d physical "
1280                           HWADDR_FMT_plx " prot %d\n",
1281                           __func__, im_address, ret, pa, prot2);
1282 
1283             prot &= prot2;
1284 
1285             if (ret == TRANSLATE_SUCCESS) {
1286                 ret = get_physical_address_pmp(env, &prot_pmp, &tlb_size, pa,
1287                                                size, access_type, mode);
1288 
1289                 qemu_log_mask(CPU_LOG_MMU,
1290                               "%s PMP address=" HWADDR_FMT_plx " ret %d prot"
1291                               " %d tlb_size " TARGET_FMT_lu "\n",
1292                               __func__, pa, ret, prot_pmp, tlb_size);
1293 
1294                 prot &= prot_pmp;
1295             }
1296 
1297             if (ret != TRANSLATE_SUCCESS) {
1298                 /*
1299                  * Guest physical address translation failed, this is a HS
1300                  * level exception
1301                  */
1302                 first_stage_error = false;
1303                 env->guest_phys_fault_addr = (im_address |
1304                                               (address &
1305                                                (TARGET_PAGE_SIZE - 1))) >> 2;
1306             }
1307         }
1308     } else {
1309         /* Single stage lookup */
1310         ret = get_physical_address(env, &pa, &prot, address, NULL,
1311                                    access_type, mmu_idx, true, false, false);
1312 
1313         qemu_log_mask(CPU_LOG_MMU,
1314                       "%s address=%" VADDR_PRIx " ret %d physical "
1315                       HWADDR_FMT_plx " prot %d\n",
1316                       __func__, address, ret, pa, prot);
1317 
1318         if (ret == TRANSLATE_SUCCESS) {
1319             ret = get_physical_address_pmp(env, &prot_pmp, &tlb_size, pa,
1320                                            size, access_type, mode);
1321 
1322             qemu_log_mask(CPU_LOG_MMU,
1323                           "%s PMP address=" HWADDR_FMT_plx " ret %d prot"
1324                           " %d tlb_size " TARGET_FMT_lu "\n",
1325                           __func__, pa, ret, prot_pmp, tlb_size);
1326 
1327             prot &= prot_pmp;
1328         }
1329     }
1330 
1331     if (ret == TRANSLATE_PMP_FAIL) {
1332         pmp_violation = true;
1333     }
1334 
1335     if (ret == TRANSLATE_SUCCESS) {
1336         tlb_set_page(cs, address & ~(tlb_size - 1), pa & ~(tlb_size - 1),
1337                      prot, mmu_idx, tlb_size);
1338         return true;
1339     } else if (probe) {
1340         return false;
1341     } else {
1342         raise_mmu_exception(env, address, access_type, pmp_violation,
1343                             first_stage_error, two_stage_lookup,
1344                             two_stage_indirect_error);
1345         cpu_loop_exit_restore(cs, retaddr);
1346     }
1347 
1348     return true;
1349 }
1350 
1351 static target_ulong riscv_transformed_insn(CPURISCVState *env,
1352                                            target_ulong insn,
1353                                            target_ulong taddr)
1354 {
1355     target_ulong xinsn = 0;
1356     target_ulong access_rs1 = 0, access_imm = 0, access_size = 0;
1357 
1358     /*
1359      * Only Quadrant 0 and Quadrant 2 of RVC instruction space need to
1360      * be uncompressed. The Quadrant 1 of RVC instruction space need
1361      * not be transformed because these instructions won't generate
1362      * any load/store trap.
1363      */
1364 
1365     if ((insn & 0x3) != 0x3) {
1366         /* Transform 16bit instruction into 32bit instruction */
1367         switch (GET_C_OP(insn)) {
1368         case OPC_RISC_C_OP_QUAD0: /* Quadrant 0 */
1369             switch (GET_C_FUNC(insn)) {
1370             case OPC_RISC_C_FUNC_FLD_LQ:
1371                 if (riscv_cpu_xlen(env) != 128) { /* C.FLD (RV32/64) */
1372                     xinsn = OPC_RISC_FLD;
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_LW: /* C.LW */
1380                 xinsn = OPC_RISC_LW;
1381                 xinsn = SET_RD(xinsn, GET_C_RS2S(insn));
1382                 access_rs1 = GET_C_RS1S(insn);
1383                 access_imm = GET_C_LW_IMM(insn);
1384                 access_size = 4;
1385                 break;
1386             case OPC_RISC_C_FUNC_FLW_LD:
1387                 if (riscv_cpu_xlen(env) == 32) { /* C.FLW (RV32) */
1388                     xinsn = OPC_RISC_FLW;
1389                     xinsn = SET_RD(xinsn, GET_C_RS2S(insn));
1390                     access_rs1 = GET_C_RS1S(insn);
1391                     access_imm = GET_C_LW_IMM(insn);
1392                     access_size = 4;
1393                 } else { /* C.LD (RV64/RV128) */
1394                     xinsn = OPC_RISC_LD;
1395                     xinsn = SET_RD(xinsn, GET_C_RS2S(insn));
1396                     access_rs1 = GET_C_RS1S(insn);
1397                     access_imm = GET_C_LD_IMM(insn);
1398                     access_size = 8;
1399                 }
1400                 break;
1401             case OPC_RISC_C_FUNC_FSD_SQ:
1402                 if (riscv_cpu_xlen(env) != 128) { /* C.FSD (RV32/64) */
1403                     xinsn = OPC_RISC_FSD;
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             case OPC_RISC_C_FUNC_SW: /* C.SW */
1411                 xinsn = OPC_RISC_SW;
1412                 xinsn = SET_RS2(xinsn, GET_C_RS2S(insn));
1413                 access_rs1 = GET_C_RS1S(insn);
1414                 access_imm = GET_C_SW_IMM(insn);
1415                 access_size = 4;
1416                 break;
1417             case OPC_RISC_C_FUNC_FSW_SD:
1418                 if (riscv_cpu_xlen(env) == 32) { /* C.FSW (RV32) */
1419                     xinsn = OPC_RISC_FSW;
1420                     xinsn = SET_RS2(xinsn, GET_C_RS2S(insn));
1421                     access_rs1 = GET_C_RS1S(insn);
1422                     access_imm = GET_C_SW_IMM(insn);
1423                     access_size = 4;
1424                 } else { /* C.SD (RV64/RV128) */
1425                     xinsn = OPC_RISC_SD;
1426                     xinsn = SET_RS2(xinsn, GET_C_RS2S(insn));
1427                     access_rs1 = GET_C_RS1S(insn);
1428                     access_imm = GET_C_SD_IMM(insn);
1429                     access_size = 8;
1430                 }
1431                 break;
1432             default:
1433                 break;
1434             }
1435             break;
1436         case OPC_RISC_C_OP_QUAD2: /* Quadrant 2 */
1437             switch (GET_C_FUNC(insn)) {
1438             case OPC_RISC_C_FUNC_FLDSP_LQSP:
1439                 if (riscv_cpu_xlen(env) != 128) { /* C.FLDSP (RV32/64) */
1440                     xinsn = OPC_RISC_FLD;
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_LWSP: /* C.LWSP */
1448                 xinsn = OPC_RISC_LW;
1449                 xinsn = SET_RD(xinsn, GET_C_RD(insn));
1450                 access_rs1 = 2;
1451                 access_imm = GET_C_LWSP_IMM(insn);
1452                 access_size = 4;
1453                 break;
1454             case OPC_RISC_C_FUNC_FLWSP_LDSP:
1455                 if (riscv_cpu_xlen(env) == 32) { /* C.FLWSP (RV32) */
1456                     xinsn = OPC_RISC_FLW;
1457                     xinsn = SET_RD(xinsn, GET_C_RD(insn));
1458                     access_rs1 = 2;
1459                     access_imm = GET_C_LWSP_IMM(insn);
1460                     access_size = 4;
1461                 } else { /* C.LDSP (RV64/RV128) */
1462                     xinsn = OPC_RISC_LD;
1463                     xinsn = SET_RD(xinsn, GET_C_RD(insn));
1464                     access_rs1 = 2;
1465                     access_imm = GET_C_LDSP_IMM(insn);
1466                     access_size = 8;
1467                 }
1468                 break;
1469             case OPC_RISC_C_FUNC_FSDSP_SQSP:
1470                 if (riscv_cpu_xlen(env) != 128) { /* C.FSDSP (RV32/64) */
1471                     xinsn = OPC_RISC_FSD;
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             case OPC_RISC_C_FUNC_SWSP: /* C.SWSP */
1479                 xinsn = OPC_RISC_SW;
1480                 xinsn = SET_RS2(xinsn, GET_C_RS2(insn));
1481                 access_rs1 = 2;
1482                 access_imm = GET_C_SWSP_IMM(insn);
1483                 access_size = 4;
1484                 break;
1485             case 7:
1486                 if (riscv_cpu_xlen(env) == 32) { /* C.FSWSP (RV32) */
1487                     xinsn = OPC_RISC_FSW;
1488                     xinsn = SET_RS2(xinsn, GET_C_RS2(insn));
1489                     access_rs1 = 2;
1490                     access_imm = GET_C_SWSP_IMM(insn);
1491                     access_size = 4;
1492                 } else { /* C.SDSP (RV64/RV128) */
1493                     xinsn = OPC_RISC_SD;
1494                     xinsn = SET_RS2(xinsn, GET_C_RS2(insn));
1495                     access_rs1 = 2;
1496                     access_imm = GET_C_SDSP_IMM(insn);
1497                     access_size = 8;
1498                 }
1499                 break;
1500             default:
1501                 break;
1502             }
1503             break;
1504         default:
1505             break;
1506         }
1507 
1508         /*
1509          * Clear Bit1 of transformed instruction to indicate that
1510          * original insruction was a 16bit instruction
1511          */
1512         xinsn &= ~((target_ulong)0x2);
1513     } else {
1514         /* Transform 32bit (or wider) instructions */
1515         switch (MASK_OP_MAJOR(insn)) {
1516         case OPC_RISC_ATOMIC:
1517             xinsn = insn;
1518             access_rs1 = GET_RS1(insn);
1519             access_size = 1 << GET_FUNCT3(insn);
1520             break;
1521         case OPC_RISC_LOAD:
1522         case OPC_RISC_FP_LOAD:
1523             xinsn = SET_I_IMM(insn, 0);
1524             access_rs1 = GET_RS1(insn);
1525             access_imm = GET_IMM(insn);
1526             access_size = 1 << GET_FUNCT3(insn);
1527             break;
1528         case OPC_RISC_STORE:
1529         case OPC_RISC_FP_STORE:
1530             xinsn = SET_S_IMM(insn, 0);
1531             access_rs1 = GET_RS1(insn);
1532             access_imm = GET_STORE_IMM(insn);
1533             access_size = 1 << GET_FUNCT3(insn);
1534             break;
1535         case OPC_RISC_SYSTEM:
1536             if (MASK_OP_SYSTEM(insn) == OPC_RISC_HLVHSV) {
1537                 xinsn = insn;
1538                 access_rs1 = GET_RS1(insn);
1539                 access_size = 1 << ((GET_FUNCT7(insn) >> 1) & 0x3);
1540                 access_size = 1 << access_size;
1541             }
1542             break;
1543         default:
1544             break;
1545         }
1546     }
1547 
1548     if (access_size) {
1549         xinsn = SET_RS1(xinsn, (taddr - (env->gpr[access_rs1] + access_imm)) &
1550                                (access_size - 1));
1551     }
1552 
1553     return xinsn;
1554 }
1555 #endif /* !CONFIG_USER_ONLY */
1556 
1557 /*
1558  * Handle Traps
1559  *
1560  * Adapted from Spike's processor_t::take_trap.
1561  *
1562  */
1563 void riscv_cpu_do_interrupt(CPUState *cs)
1564 {
1565 #if !defined(CONFIG_USER_ONLY)
1566 
1567     RISCVCPU *cpu = RISCV_CPU(cs);
1568     CPURISCVState *env = &cpu->env;
1569     bool write_gva = false;
1570     uint64_t s;
1571 
1572     /*
1573      * cs->exception is 32-bits wide unlike mcause which is XLEN-bits wide
1574      * so we mask off the MSB and separate into trap type and cause.
1575      */
1576     bool async = !!(cs->exception_index & RISCV_EXCP_INT_FLAG);
1577     target_ulong cause = cs->exception_index & RISCV_EXCP_INT_MASK;
1578     uint64_t deleg = async ? env->mideleg : env->medeleg;
1579     target_ulong tval = 0;
1580     target_ulong tinst = 0;
1581     target_ulong htval = 0;
1582     target_ulong mtval2 = 0;
1583 
1584     if  (cause == RISCV_EXCP_SEMIHOST) {
1585         do_common_semihosting(cs);
1586         env->pc += 4;
1587         return;
1588     }
1589 
1590     if (!async) {
1591         /* set tval to badaddr for traps with address information */
1592         switch (cause) {
1593         case RISCV_EXCP_LOAD_GUEST_ACCESS_FAULT:
1594         case RISCV_EXCP_STORE_GUEST_AMO_ACCESS_FAULT:
1595         case RISCV_EXCP_LOAD_ADDR_MIS:
1596         case RISCV_EXCP_STORE_AMO_ADDR_MIS:
1597         case RISCV_EXCP_LOAD_ACCESS_FAULT:
1598         case RISCV_EXCP_STORE_AMO_ACCESS_FAULT:
1599         case RISCV_EXCP_LOAD_PAGE_FAULT:
1600         case RISCV_EXCP_STORE_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             } else {
1610                 /*
1611                  * The "Addr. Offset" field in transformed instruction is
1612                  * non-zero only for misaligned access.
1613                  */
1614                 tinst = riscv_transformed_insn(env, env->bins, tval);
1615             }
1616             break;
1617         case RISCV_EXCP_INST_GUEST_PAGE_FAULT:
1618         case RISCV_EXCP_INST_ADDR_MIS:
1619         case RISCV_EXCP_INST_ACCESS_FAULT:
1620         case RISCV_EXCP_INST_PAGE_FAULT:
1621             write_gva = env->two_stage_lookup;
1622             tval = env->badaddr;
1623             if (env->two_stage_indirect_lookup) {
1624                 /*
1625                  * special pseudoinstruction for G-stage fault taken while
1626                  * doing VS-stage page table walk.
1627                  */
1628                 tinst = (riscv_cpu_xlen(env) == 32) ? 0x00002000 : 0x00003000;
1629             }
1630             break;
1631         case RISCV_EXCP_ILLEGAL_INST:
1632         case RISCV_EXCP_VIRT_INSTRUCTION_FAULT:
1633             tval = env->bins;
1634             break;
1635         case RISCV_EXCP_BREAKPOINT:
1636             if (cs->watchpoint_hit) {
1637                 tval = cs->watchpoint_hit->hitaddr;
1638                 cs->watchpoint_hit = NULL;
1639             }
1640             break;
1641         default:
1642             break;
1643         }
1644         /* ecall is dispatched as one cause so translate based on mode */
1645         if (cause == RISCV_EXCP_U_ECALL) {
1646             assert(env->priv <= 3);
1647 
1648             if (env->priv == PRV_M) {
1649                 cause = RISCV_EXCP_M_ECALL;
1650             } else if (env->priv == PRV_S && env->virt_enabled) {
1651                 cause = RISCV_EXCP_VS_ECALL;
1652             } else if (env->priv == PRV_S && !env->virt_enabled) {
1653                 cause = RISCV_EXCP_S_ECALL;
1654             } else if (env->priv == PRV_U) {
1655                 cause = RISCV_EXCP_U_ECALL;
1656             }
1657         }
1658     }
1659 
1660     trace_riscv_trap(env->mhartid, async, cause, env->pc, tval,
1661                      riscv_cpu_get_trap_name(cause, async));
1662 
1663     qemu_log_mask(CPU_LOG_INT,
1664                   "%s: hart:"TARGET_FMT_ld", async:%d, cause:"TARGET_FMT_lx", "
1665                   "epc:0x"TARGET_FMT_lx", tval:0x"TARGET_FMT_lx", desc=%s\n",
1666                   __func__, env->mhartid, async, cause, env->pc, tval,
1667                   riscv_cpu_get_trap_name(cause, async));
1668 
1669     if (env->priv <= PRV_S &&
1670             cause < TARGET_LONG_BITS && ((deleg >> cause) & 1)) {
1671         /* handle the trap in S-mode */
1672         if (riscv_has_ext(env, RVH)) {
1673             uint64_t hdeleg = async ? env->hideleg : env->hedeleg;
1674 
1675             if (env->virt_enabled && ((hdeleg >> cause) & 1)) {
1676                 /* Trap to VS mode */
1677                 /*
1678                  * See if we need to adjust cause. Yes if its VS mode interrupt
1679                  * no if hypervisor has delegated one of hs mode's interrupt
1680                  */
1681                 if (cause == IRQ_VS_TIMER || cause == IRQ_VS_SOFT ||
1682                     cause == IRQ_VS_EXT) {
1683                     cause = cause - 1;
1684                 }
1685                 write_gva = false;
1686             } else if (env->virt_enabled) {
1687                 /* Trap into HS mode, from virt */
1688                 riscv_cpu_swap_hypervisor_regs(env);
1689                 env->hstatus = set_field(env->hstatus, HSTATUS_SPVP,
1690                                          env->priv);
1691                 env->hstatus = set_field(env->hstatus, HSTATUS_SPV, true);
1692 
1693                 htval = env->guest_phys_fault_addr;
1694 
1695                 riscv_cpu_set_virt_enabled(env, 0);
1696             } else {
1697                 /* Trap into HS mode */
1698                 env->hstatus = set_field(env->hstatus, HSTATUS_SPV, false);
1699                 htval = env->guest_phys_fault_addr;
1700             }
1701             env->hstatus = set_field(env->hstatus, HSTATUS_GVA, write_gva);
1702         }
1703 
1704         s = env->mstatus;
1705         s = set_field(s, MSTATUS_SPIE, get_field(s, MSTATUS_SIE));
1706         s = set_field(s, MSTATUS_SPP, env->priv);
1707         s = set_field(s, MSTATUS_SIE, 0);
1708         env->mstatus = s;
1709         env->scause = cause | ((target_ulong)async << (TARGET_LONG_BITS - 1));
1710         env->sepc = env->pc;
1711         env->stval = tval;
1712         env->htval = htval;
1713         env->htinst = tinst;
1714         env->pc = (env->stvec >> 2 << 2) +
1715                   ((async && (env->stvec & 3) == 1) ? cause * 4 : 0);
1716         riscv_cpu_set_mode(env, PRV_S);
1717     } else {
1718         /* handle the trap in M-mode */
1719         if (riscv_has_ext(env, RVH)) {
1720             if (env->virt_enabled) {
1721                 riscv_cpu_swap_hypervisor_regs(env);
1722             }
1723             env->mstatus = set_field(env->mstatus, MSTATUS_MPV,
1724                                      env->virt_enabled);
1725             if (env->virt_enabled && tval) {
1726                 env->mstatus = set_field(env->mstatus, MSTATUS_GVA, 1);
1727             }
1728 
1729             mtval2 = env->guest_phys_fault_addr;
1730 
1731             /* Trapping to M mode, virt is disabled */
1732             riscv_cpu_set_virt_enabled(env, 0);
1733         }
1734 
1735         s = env->mstatus;
1736         s = set_field(s, MSTATUS_MPIE, get_field(s, MSTATUS_MIE));
1737         s = set_field(s, MSTATUS_MPP, env->priv);
1738         s = set_field(s, MSTATUS_MIE, 0);
1739         env->mstatus = s;
1740         env->mcause = cause | ~(((target_ulong)-1) >> async);
1741         env->mepc = env->pc;
1742         env->mtval = tval;
1743         env->mtval2 = mtval2;
1744         env->mtinst = tinst;
1745         env->pc = (env->mtvec >> 2 << 2) +
1746                   ((async && (env->mtvec & 3) == 1) ? cause * 4 : 0);
1747         riscv_cpu_set_mode(env, PRV_M);
1748     }
1749 
1750     /*
1751      * NOTE: it is not necessary to yield load reservations here. It is only
1752      * necessary for an SC from "another hart" to cause a load reservation
1753      * to be yielded. Refer to the memory consistency model section of the
1754      * RISC-V ISA Specification.
1755      */
1756 
1757     env->two_stage_lookup = false;
1758     env->two_stage_indirect_lookup = false;
1759 #endif
1760     cs->exception_index = RISCV_EXCP_NONE; /* mark handled to qemu */
1761 }
1762