xref: /openbmc/qemu/target/riscv/cpu_helper.c (revision 17b3c353)
1 /*
2  * RISC-V CPU helpers for qemu.
3  *
4  * Copyright (c) 2016-2017 Sagar Karandikar, sagark@eecs.berkeley.edu
5  * Copyright (c) 2017-2018 SiFive, Inc.
6  *
7  * This program is free software; you can redistribute it and/or modify it
8  * under the terms and conditions of the GNU General Public License,
9  * version 2 or later, as published by the Free Software Foundation.
10  *
11  * This program is distributed in the hope it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
14  * more details.
15  *
16  * You should have received a copy of the GNU General Public License along with
17  * this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19 
20 #include "qemu/osdep.h"
21 #include "qemu/log.h"
22 #include "qemu/main-loop.h"
23 #include "cpu.h"
24 #include "exec/exec-all.h"
25 #include "tcg/tcg-op.h"
26 #include "trace.h"
27 #include "semihosting/common-semi.h"
28 
29 int riscv_cpu_mmu_index(CPURISCVState *env, bool ifetch)
30 {
31 #ifdef CONFIG_USER_ONLY
32     return 0;
33 #else
34     return env->priv;
35 #endif
36 }
37 
38 #ifndef CONFIG_USER_ONLY
39 static int riscv_cpu_local_irq_pending(CPURISCVState *env)
40 {
41     target_ulong irqs;
42 
43     target_ulong mstatus_mie = get_field(env->mstatus, MSTATUS_MIE);
44     target_ulong mstatus_sie = get_field(env->mstatus, MSTATUS_SIE);
45     target_ulong hs_mstatus_sie = get_field(env->mstatus_hs, MSTATUS_SIE);
46 
47     target_ulong pending = env->mip & env->mie &
48                                ~(MIP_VSSIP | MIP_VSTIP | MIP_VSEIP);
49     target_ulong vspending = (env->mip & env->mie &
50                               (MIP_VSSIP | MIP_VSTIP | MIP_VSEIP));
51 
52     target_ulong mie    = env->priv < PRV_M ||
53                           (env->priv == PRV_M && mstatus_mie);
54     target_ulong sie    = env->priv < PRV_S ||
55                           (env->priv == PRV_S && mstatus_sie);
56     target_ulong hs_sie = env->priv < PRV_S ||
57                           (env->priv == PRV_S && hs_mstatus_sie);
58 
59     if (riscv_cpu_virt_enabled(env)) {
60         target_ulong pending_hs_irq = pending & -hs_sie;
61 
62         if (pending_hs_irq) {
63             riscv_cpu_set_force_hs_excep(env, FORCE_HS_EXCEP);
64             return ctz64(pending_hs_irq);
65         }
66 
67         pending = vspending;
68     }
69 
70     irqs = (pending & ~env->mideleg & -mie) | (pending &  env->mideleg & -sie);
71 
72     if (irqs) {
73         return ctz64(irqs); /* since non-zero */
74     } else {
75         return RISCV_EXCP_NONE; /* indicates no pending interrupt */
76     }
77 }
78 
79 bool riscv_cpu_exec_interrupt(CPUState *cs, int interrupt_request)
80 {
81     if (interrupt_request & CPU_INTERRUPT_HARD) {
82         RISCVCPU *cpu = RISCV_CPU(cs);
83         CPURISCVState *env = &cpu->env;
84         int interruptno = riscv_cpu_local_irq_pending(env);
85         if (interruptno >= 0) {
86             cs->exception_index = RISCV_EXCP_INT_FLAG | interruptno;
87             riscv_cpu_do_interrupt(cs);
88             return true;
89         }
90     }
91     return false;
92 }
93 
94 /* Return true is floating point support is currently enabled */
95 bool riscv_cpu_fp_enabled(CPURISCVState *env)
96 {
97     if (env->mstatus & MSTATUS_FS) {
98         if (riscv_cpu_virt_enabled(env) && !(env->mstatus_hs & MSTATUS_FS)) {
99             return false;
100         }
101         return true;
102     }
103 
104     return false;
105 }
106 
107 void riscv_cpu_swap_hypervisor_regs(CPURISCVState *env)
108 {
109     uint64_t mstatus_mask = MSTATUS_MXR | MSTATUS_SUM | MSTATUS_FS |
110                             MSTATUS_SPP | MSTATUS_SPIE | MSTATUS_SIE |
111                             MSTATUS64_UXL;
112     bool current_virt = riscv_cpu_virt_enabled(env);
113 
114     g_assert(riscv_has_ext(env, RVH));
115 
116     if (current_virt) {
117         /* Current V=1 and we are about to change to V=0 */
118         env->vsstatus = env->mstatus & mstatus_mask;
119         env->mstatus &= ~mstatus_mask;
120         env->mstatus |= env->mstatus_hs;
121 
122         env->vstvec = env->stvec;
123         env->stvec = env->stvec_hs;
124 
125         env->vsscratch = env->sscratch;
126         env->sscratch = env->sscratch_hs;
127 
128         env->vsepc = env->sepc;
129         env->sepc = env->sepc_hs;
130 
131         env->vscause = env->scause;
132         env->scause = env->scause_hs;
133 
134         env->vstval = env->stval;
135         env->stval = env->stval_hs;
136 
137         env->vsatp = env->satp;
138         env->satp = env->satp_hs;
139     } else {
140         /* Current V=0 and we are about to change to V=1 */
141         env->mstatus_hs = env->mstatus & mstatus_mask;
142         env->mstatus &= ~mstatus_mask;
143         env->mstatus |= env->vsstatus;
144 
145         env->stvec_hs = env->stvec;
146         env->stvec = env->vstvec;
147 
148         env->sscratch_hs = env->sscratch;
149         env->sscratch = env->vsscratch;
150 
151         env->sepc_hs = env->sepc;
152         env->sepc = env->vsepc;
153 
154         env->scause_hs = env->scause;
155         env->scause = env->vscause;
156 
157         env->stval_hs = env->stval;
158         env->stval = env->vstval;
159 
160         env->satp_hs = env->satp;
161         env->satp = env->vsatp;
162     }
163 }
164 
165 bool riscv_cpu_virt_enabled(CPURISCVState *env)
166 {
167     if (!riscv_has_ext(env, RVH)) {
168         return false;
169     }
170 
171     return get_field(env->virt, VIRT_ONOFF);
172 }
173 
174 void riscv_cpu_set_virt_enabled(CPURISCVState *env, bool enable)
175 {
176     if (!riscv_has_ext(env, RVH)) {
177         return;
178     }
179 
180     /* Flush the TLB on all virt mode changes. */
181     if (get_field(env->virt, VIRT_ONOFF) != enable) {
182         tlb_flush(env_cpu(env));
183     }
184 
185     env->virt = set_field(env->virt, VIRT_ONOFF, enable);
186 }
187 
188 bool riscv_cpu_force_hs_excep_enabled(CPURISCVState *env)
189 {
190     if (!riscv_has_ext(env, RVH)) {
191         return false;
192     }
193 
194     return get_field(env->virt, FORCE_HS_EXCEP);
195 }
196 
197 void riscv_cpu_set_force_hs_excep(CPURISCVState *env, bool enable)
198 {
199     if (!riscv_has_ext(env, RVH)) {
200         return;
201     }
202 
203     env->virt = set_field(env->virt, FORCE_HS_EXCEP, enable);
204 }
205 
206 bool riscv_cpu_two_stage_lookup(int mmu_idx)
207 {
208     return mmu_idx & TB_FLAGS_PRIV_HYP_ACCESS_MASK;
209 }
210 
211 int riscv_cpu_claim_interrupts(RISCVCPU *cpu, uint32_t interrupts)
212 {
213     CPURISCVState *env = &cpu->env;
214     if (env->miclaim & interrupts) {
215         return -1;
216     } else {
217         env->miclaim |= interrupts;
218         return 0;
219     }
220 }
221 
222 uint32_t riscv_cpu_update_mip(RISCVCPU *cpu, uint32_t mask, uint32_t value)
223 {
224     CPURISCVState *env = &cpu->env;
225     CPUState *cs = CPU(cpu);
226     uint32_t old = env->mip;
227     bool locked = false;
228 
229     if (!qemu_mutex_iothread_locked()) {
230         locked = true;
231         qemu_mutex_lock_iothread();
232     }
233 
234     env->mip = (env->mip & ~mask) | (value & mask);
235 
236     if (env->mip) {
237         cpu_interrupt(cs, CPU_INTERRUPT_HARD);
238     } else {
239         cpu_reset_interrupt(cs, CPU_INTERRUPT_HARD);
240     }
241 
242     if (locked) {
243         qemu_mutex_unlock_iothread();
244     }
245 
246     return old;
247 }
248 
249 void riscv_cpu_set_rdtime_fn(CPURISCVState *env, uint64_t (*fn)(uint32_t),
250                              uint32_t arg)
251 {
252     env->rdtime_fn = fn;
253     env->rdtime_fn_arg = arg;
254 }
255 
256 void riscv_cpu_set_mode(CPURISCVState *env, target_ulong newpriv)
257 {
258     if (newpriv > PRV_M) {
259         g_assert_not_reached();
260     }
261     if (newpriv == PRV_H) {
262         newpriv = PRV_U;
263     }
264     /* tlb_flush is unnecessary as mode is contained in mmu_idx */
265     env->priv = newpriv;
266 
267     /*
268      * Clear the load reservation - otherwise a reservation placed in one
269      * context/process can be used by another, resulting in an SC succeeding
270      * incorrectly. Version 2.2 of the ISA specification explicitly requires
271      * this behaviour, while later revisions say that the kernel "should" use
272      * an SC instruction to force the yielding of a load reservation on a
273      * preemptive context switch. As a result, do both.
274      */
275     env->load_res = -1;
276 }
277 
278 /*
279  * get_physical_address_pmp - check PMP permission for this physical address
280  *
281  * Match the PMP region and check permission for this physical address and it's
282  * TLB page. Returns 0 if the permission checking was successful
283  *
284  * @env: CPURISCVState
285  * @prot: The returned protection attributes
286  * @tlb_size: TLB page size containing addr. It could be modified after PMP
287  *            permission checking. NULL if not set TLB page for addr.
288  * @addr: The physical address to be checked permission
289  * @access_type: The type of MMU access
290  * @mode: Indicates current privilege level.
291  */
292 static int get_physical_address_pmp(CPURISCVState *env, int *prot,
293                                     target_ulong *tlb_size, hwaddr addr,
294                                     int size, MMUAccessType access_type,
295                                     int mode)
296 {
297     pmp_priv_t pmp_priv;
298     target_ulong tlb_size_pmp = 0;
299 
300     if (!riscv_feature(env, RISCV_FEATURE_PMP)) {
301         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
302         return TRANSLATE_SUCCESS;
303     }
304 
305     if (!pmp_hart_has_privs(env, addr, size, 1 << access_type, &pmp_priv,
306                             mode)) {
307         *prot = 0;
308         return TRANSLATE_PMP_FAIL;
309     }
310 
311     *prot = pmp_priv_to_page_prot(pmp_priv);
312     if (tlb_size != NULL) {
313         if (pmp_is_range_in_tlb(env, addr & ~(*tlb_size - 1), &tlb_size_pmp)) {
314             *tlb_size = tlb_size_pmp;
315         }
316     }
317 
318     return TRANSLATE_SUCCESS;
319 }
320 
321 /* get_physical_address - get the physical address for this virtual address
322  *
323  * Do a page table walk to obtain the physical address corresponding to a
324  * virtual address. Returns 0 if the translation was successful
325  *
326  * Adapted from Spike's mmu_t::translate and mmu_t::walk
327  *
328  * @env: CPURISCVState
329  * @physical: This will be set to the calculated physical address
330  * @prot: The returned protection attributes
331  * @addr: The virtual address to be translated
332  * @fault_pte_addr: If not NULL, this will be set to fault pte address
333  *                  when a error occurs on pte address translation.
334  *                  This will already be shifted to match htval.
335  * @access_type: The type of MMU access
336  * @mmu_idx: Indicates current privilege level
337  * @first_stage: Are we in first stage translation?
338  *               Second stage is used for hypervisor guest translation
339  * @two_stage: Are we going to perform two stage translation
340  * @is_debug: Is this access from a debugger or the monitor?
341  */
342 static int get_physical_address(CPURISCVState *env, hwaddr *physical,
343                                 int *prot, target_ulong addr,
344                                 target_ulong *fault_pte_addr,
345                                 int access_type, int mmu_idx,
346                                 bool first_stage, bool two_stage,
347                                 bool is_debug)
348 {
349     /* NOTE: the env->pc value visible here will not be
350      * correct, but the value visible to the exception handler
351      * (riscv_cpu_do_interrupt) is correct */
352     MemTxResult res;
353     MemTxAttrs attrs = MEMTXATTRS_UNSPECIFIED;
354     int mode = mmu_idx & TB_FLAGS_PRIV_MMU_MASK;
355     bool use_background = false;
356 
357     /*
358      * Check if we should use the background registers for the two
359      * stage translation. We don't need to check if we actually need
360      * two stage translation as that happened before this function
361      * was called. Background registers will be used if the guest has
362      * forced a two stage translation to be on (in HS or M mode).
363      */
364     if (!riscv_cpu_virt_enabled(env) && two_stage) {
365         use_background = true;
366     }
367 
368     /* MPRV does not affect the virtual-machine load/store
369        instructions, HLV, HLVX, and HSV. */
370     if (riscv_cpu_two_stage_lookup(mmu_idx)) {
371         mode = get_field(env->hstatus, HSTATUS_SPVP);
372     } else if (mode == PRV_M && access_type != MMU_INST_FETCH) {
373         if (get_field(env->mstatus, MSTATUS_MPRV)) {
374             mode = get_field(env->mstatus, MSTATUS_MPP);
375         }
376     }
377 
378     if (first_stage == false) {
379         /* We are in stage 2 translation, this is similar to stage 1. */
380         /* Stage 2 is always taken as U-mode */
381         mode = PRV_U;
382     }
383 
384     if (mode == PRV_M || !riscv_feature(env, RISCV_FEATURE_MMU)) {
385         *physical = addr;
386         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
387         return TRANSLATE_SUCCESS;
388     }
389 
390     *prot = 0;
391 
392     hwaddr base;
393     int levels, ptidxbits, ptesize, vm, sum, mxr, widened;
394 
395     if (first_stage == true) {
396         mxr = get_field(env->mstatus, MSTATUS_MXR);
397     } else {
398         mxr = get_field(env->vsstatus, MSTATUS_MXR);
399     }
400 
401     if (first_stage == true) {
402         if (use_background) {
403             if (riscv_cpu_is_32bit(env)) {
404                 base = (hwaddr)get_field(env->vsatp, SATP32_PPN) << PGSHIFT;
405                 vm = get_field(env->vsatp, SATP32_MODE);
406             } else {
407                 base = (hwaddr)get_field(env->vsatp, SATP64_PPN) << PGSHIFT;
408                 vm = get_field(env->vsatp, SATP64_MODE);
409             }
410         } else {
411             if (riscv_cpu_is_32bit(env)) {
412                 base = (hwaddr)get_field(env->satp, SATP32_PPN) << PGSHIFT;
413                 vm = get_field(env->satp, SATP32_MODE);
414             } else {
415                 base = (hwaddr)get_field(env->satp, SATP64_PPN) << PGSHIFT;
416                 vm = get_field(env->satp, SATP64_MODE);
417             }
418         }
419         widened = 0;
420     } else {
421         if (riscv_cpu_is_32bit(env)) {
422             base = (hwaddr)get_field(env->hgatp, SATP32_PPN) << PGSHIFT;
423             vm = get_field(env->hgatp, SATP32_MODE);
424         } else {
425             base = (hwaddr)get_field(env->hgatp, SATP64_PPN) << PGSHIFT;
426             vm = get_field(env->hgatp, SATP64_MODE);
427         }
428         widened = 2;
429     }
430     /* status.SUM will be ignored if execute on background */
431     sum = get_field(env->mstatus, MSTATUS_SUM) || use_background || is_debug;
432     switch (vm) {
433     case VM_1_10_SV32:
434       levels = 2; ptidxbits = 10; ptesize = 4; break;
435     case VM_1_10_SV39:
436       levels = 3; ptidxbits = 9; ptesize = 8; break;
437     case VM_1_10_SV48:
438       levels = 4; ptidxbits = 9; ptesize = 8; break;
439     case VM_1_10_SV57:
440       levels = 5; ptidxbits = 9; ptesize = 8; break;
441     case VM_1_10_MBARE:
442         *physical = addr;
443         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
444         return TRANSLATE_SUCCESS;
445     default:
446       g_assert_not_reached();
447     }
448 
449     CPUState *cs = env_cpu(env);
450     int va_bits = PGSHIFT + levels * ptidxbits + widened;
451     target_ulong mask, masked_msbs;
452 
453     if (TARGET_LONG_BITS > (va_bits - 1)) {
454         mask = (1L << (TARGET_LONG_BITS - (va_bits - 1))) - 1;
455     } else {
456         mask = 0;
457     }
458     masked_msbs = (addr >> (va_bits - 1)) & mask;
459 
460     if (masked_msbs != 0 && masked_msbs != mask) {
461         return TRANSLATE_FAIL;
462     }
463 
464     int ptshift = (levels - 1) * ptidxbits;
465     int i;
466 
467 #if !TCG_OVERSIZED_GUEST
468 restart:
469 #endif
470     for (i = 0; i < levels; i++, ptshift -= ptidxbits) {
471         target_ulong idx;
472         if (i == 0) {
473             idx = (addr >> (PGSHIFT + ptshift)) &
474                            ((1 << (ptidxbits + widened)) - 1);
475         } else {
476             idx = (addr >> (PGSHIFT + ptshift)) &
477                            ((1 << ptidxbits) - 1);
478         }
479 
480         /* check that physical address of PTE is legal */
481         hwaddr pte_addr;
482 
483         if (two_stage && first_stage) {
484             int vbase_prot;
485             hwaddr vbase;
486 
487             /* Do the second stage translation on the base PTE address. */
488             int vbase_ret = get_physical_address(env, &vbase, &vbase_prot,
489                                                  base, NULL, MMU_DATA_LOAD,
490                                                  mmu_idx, false, true,
491                                                  is_debug);
492 
493             if (vbase_ret != TRANSLATE_SUCCESS) {
494                 if (fault_pte_addr) {
495                     *fault_pte_addr = (base + idx * ptesize) >> 2;
496                 }
497                 return TRANSLATE_G_STAGE_FAIL;
498             }
499 
500             pte_addr = vbase + idx * ptesize;
501         } else {
502             pte_addr = base + idx * ptesize;
503         }
504 
505         int pmp_prot;
506         int pmp_ret = get_physical_address_pmp(env, &pmp_prot, NULL, pte_addr,
507                                                sizeof(target_ulong),
508                                                MMU_DATA_LOAD, PRV_S);
509         if (pmp_ret != TRANSLATE_SUCCESS) {
510             return TRANSLATE_PMP_FAIL;
511         }
512 
513         target_ulong pte;
514         if (riscv_cpu_is_32bit(env)) {
515             pte = address_space_ldl(cs->as, pte_addr, attrs, &res);
516         } else {
517             pte = address_space_ldq(cs->as, pte_addr, attrs, &res);
518         }
519 
520         if (res != MEMTX_OK) {
521             return TRANSLATE_FAIL;
522         }
523 
524         hwaddr ppn = pte >> PTE_PPN_SHIFT;
525 
526         if (!(pte & PTE_V)) {
527             /* Invalid PTE */
528             return TRANSLATE_FAIL;
529         } else if (!(pte & (PTE_R | PTE_W | PTE_X))) {
530             /* Inner PTE, continue walking */
531             base = ppn << PGSHIFT;
532         } else if ((pte & (PTE_R | PTE_W | PTE_X)) == PTE_W) {
533             /* Reserved leaf PTE flags: PTE_W */
534             return TRANSLATE_FAIL;
535         } else if ((pte & (PTE_R | PTE_W | PTE_X)) == (PTE_W | PTE_X)) {
536             /* Reserved leaf PTE flags: PTE_W + PTE_X */
537             return TRANSLATE_FAIL;
538         } else if ((pte & PTE_U) && ((mode != PRV_U) &&
539                    (!sum || access_type == MMU_INST_FETCH))) {
540             /* User PTE flags when not U mode and mstatus.SUM is not set,
541                or the access type is an instruction fetch */
542             return TRANSLATE_FAIL;
543         } else if (!(pte & PTE_U) && (mode != PRV_S)) {
544             /* Supervisor PTE flags when not S mode */
545             return TRANSLATE_FAIL;
546         } else if (ppn & ((1ULL << ptshift) - 1)) {
547             /* Misaligned PPN */
548             return TRANSLATE_FAIL;
549         } else if (access_type == MMU_DATA_LOAD && !((pte & PTE_R) ||
550                    ((pte & PTE_X) && mxr))) {
551             /* Read access check failed */
552             return TRANSLATE_FAIL;
553         } else if (access_type == MMU_DATA_STORE && !(pte & PTE_W)) {
554             /* Write access check failed */
555             return TRANSLATE_FAIL;
556         } else if (access_type == MMU_INST_FETCH && !(pte & PTE_X)) {
557             /* Fetch access check failed */
558             return TRANSLATE_FAIL;
559         } else {
560             /* if necessary, set accessed and dirty bits. */
561             target_ulong updated_pte = pte | PTE_A |
562                 (access_type == MMU_DATA_STORE ? PTE_D : 0);
563 
564             /* Page table updates need to be atomic with MTTCG enabled */
565             if (updated_pte != pte) {
566                 /*
567                  * - if accessed or dirty bits need updating, and the PTE is
568                  *   in RAM, then we do so atomically with a compare and swap.
569                  * - if the PTE is in IO space or ROM, then it can't be updated
570                  *   and we return TRANSLATE_FAIL.
571                  * - if the PTE changed by the time we went to update it, then
572                  *   it is no longer valid and we must re-walk the page table.
573                  */
574                 MemoryRegion *mr;
575                 hwaddr l = sizeof(target_ulong), addr1;
576                 mr = address_space_translate(cs->as, pte_addr,
577                     &addr1, &l, false, MEMTXATTRS_UNSPECIFIED);
578                 if (memory_region_is_ram(mr)) {
579                     target_ulong *pte_pa =
580                         qemu_map_ram_ptr(mr->ram_block, addr1);
581 #if TCG_OVERSIZED_GUEST
582                     /* MTTCG is not enabled on oversized TCG guests so
583                      * page table updates do not need to be atomic */
584                     *pte_pa = pte = updated_pte;
585 #else
586                     target_ulong old_pte =
587                         qatomic_cmpxchg(pte_pa, pte, updated_pte);
588                     if (old_pte != pte) {
589                         goto restart;
590                     } else {
591                         pte = updated_pte;
592                     }
593 #endif
594                 } else {
595                     /* misconfigured PTE in ROM (AD bits are not preset) or
596                      * PTE is in IO space and can't be updated atomically */
597                     return TRANSLATE_FAIL;
598                 }
599             }
600 
601             /* for superpage mappings, make a fake leaf PTE for the TLB's
602                benefit. */
603             target_ulong vpn = addr >> PGSHIFT;
604             *physical = ((ppn | (vpn & ((1L << ptshift) - 1))) << PGSHIFT) |
605                         (addr & ~TARGET_PAGE_MASK);
606 
607             /* set permissions on the TLB entry */
608             if ((pte & PTE_R) || ((pte & PTE_X) && mxr)) {
609                 *prot |= PAGE_READ;
610             }
611             if ((pte & PTE_X)) {
612                 *prot |= PAGE_EXEC;
613             }
614             /* add write permission on stores or if the page is already dirty,
615                so that we TLB miss on later writes to update the dirty bit */
616             if ((pte & PTE_W) &&
617                     (access_type == MMU_DATA_STORE || (pte & PTE_D))) {
618                 *prot |= PAGE_WRITE;
619             }
620             return TRANSLATE_SUCCESS;
621         }
622     }
623     return TRANSLATE_FAIL;
624 }
625 
626 static void raise_mmu_exception(CPURISCVState *env, target_ulong address,
627                                 MMUAccessType access_type, bool pmp_violation,
628                                 bool first_stage, bool two_stage)
629 {
630     CPUState *cs = env_cpu(env);
631     int page_fault_exceptions, vm;
632     uint64_t stap_mode;
633 
634     if (riscv_cpu_is_32bit(env)) {
635         stap_mode = SATP32_MODE;
636     } else {
637         stap_mode = SATP64_MODE;
638     }
639 
640     if (first_stage) {
641         vm = get_field(env->satp, stap_mode);
642     } else {
643         vm = get_field(env->hgatp, stap_mode);
644     }
645 
646     page_fault_exceptions = vm != VM_1_10_MBARE && !pmp_violation;
647 
648     switch (access_type) {
649     case MMU_INST_FETCH:
650         if (riscv_cpu_virt_enabled(env) && !first_stage) {
651             cs->exception_index = RISCV_EXCP_INST_GUEST_PAGE_FAULT;
652         } else {
653             cs->exception_index = page_fault_exceptions ?
654                 RISCV_EXCP_INST_PAGE_FAULT : RISCV_EXCP_INST_ACCESS_FAULT;
655         }
656         break;
657     case MMU_DATA_LOAD:
658         if (two_stage && !first_stage) {
659             cs->exception_index = RISCV_EXCP_LOAD_GUEST_ACCESS_FAULT;
660         } else {
661             cs->exception_index = page_fault_exceptions ?
662                 RISCV_EXCP_LOAD_PAGE_FAULT : RISCV_EXCP_LOAD_ACCESS_FAULT;
663         }
664         break;
665     case MMU_DATA_STORE:
666         if (two_stage && !first_stage) {
667             cs->exception_index = RISCV_EXCP_STORE_GUEST_AMO_ACCESS_FAULT;
668         } else {
669             cs->exception_index = page_fault_exceptions ?
670                 RISCV_EXCP_STORE_PAGE_FAULT : RISCV_EXCP_STORE_AMO_ACCESS_FAULT;
671         }
672         break;
673     default:
674         g_assert_not_reached();
675     }
676     env->badaddr = address;
677     env->two_stage_lookup = two_stage;
678 }
679 
680 hwaddr riscv_cpu_get_phys_page_debug(CPUState *cs, vaddr addr)
681 {
682     RISCVCPU *cpu = RISCV_CPU(cs);
683     CPURISCVState *env = &cpu->env;
684     hwaddr phys_addr;
685     int prot;
686     int mmu_idx = cpu_mmu_index(&cpu->env, false);
687 
688     if (get_physical_address(env, &phys_addr, &prot, addr, NULL, 0, mmu_idx,
689                              true, riscv_cpu_virt_enabled(env), true)) {
690         return -1;
691     }
692 
693     if (riscv_cpu_virt_enabled(env)) {
694         if (get_physical_address(env, &phys_addr, &prot, phys_addr, NULL,
695                                  0, mmu_idx, false, true, true)) {
696             return -1;
697         }
698     }
699 
700     return phys_addr & TARGET_PAGE_MASK;
701 }
702 
703 void riscv_cpu_do_transaction_failed(CPUState *cs, hwaddr physaddr,
704                                      vaddr addr, unsigned size,
705                                      MMUAccessType access_type,
706                                      int mmu_idx, MemTxAttrs attrs,
707                                      MemTxResult response, uintptr_t retaddr)
708 {
709     RISCVCPU *cpu = RISCV_CPU(cs);
710     CPURISCVState *env = &cpu->env;
711 
712     if (access_type == MMU_DATA_STORE) {
713         cs->exception_index = RISCV_EXCP_STORE_AMO_ACCESS_FAULT;
714     } else if (access_type == MMU_DATA_LOAD) {
715         cs->exception_index = RISCV_EXCP_LOAD_ACCESS_FAULT;
716     } else {
717         cs->exception_index = RISCV_EXCP_INST_ACCESS_FAULT;
718     }
719 
720     env->badaddr = addr;
721     env->two_stage_lookup = riscv_cpu_virt_enabled(env) ||
722                             riscv_cpu_two_stage_lookup(mmu_idx);
723     riscv_raise_exception(&cpu->env, cs->exception_index, retaddr);
724 }
725 
726 void riscv_cpu_do_unaligned_access(CPUState *cs, vaddr addr,
727                                    MMUAccessType access_type, int mmu_idx,
728                                    uintptr_t retaddr)
729 {
730     RISCVCPU *cpu = RISCV_CPU(cs);
731     CPURISCVState *env = &cpu->env;
732     switch (access_type) {
733     case MMU_INST_FETCH:
734         cs->exception_index = RISCV_EXCP_INST_ADDR_MIS;
735         break;
736     case MMU_DATA_LOAD:
737         cs->exception_index = RISCV_EXCP_LOAD_ADDR_MIS;
738         break;
739     case MMU_DATA_STORE:
740         cs->exception_index = RISCV_EXCP_STORE_AMO_ADDR_MIS;
741         break;
742     default:
743         g_assert_not_reached();
744     }
745     env->badaddr = addr;
746     env->two_stage_lookup = riscv_cpu_virt_enabled(env) ||
747                             riscv_cpu_two_stage_lookup(mmu_idx);
748     riscv_raise_exception(env, cs->exception_index, retaddr);
749 }
750 #endif /* !CONFIG_USER_ONLY */
751 
752 bool riscv_cpu_tlb_fill(CPUState *cs, vaddr address, int size,
753                         MMUAccessType access_type, int mmu_idx,
754                         bool probe, uintptr_t retaddr)
755 {
756     RISCVCPU *cpu = RISCV_CPU(cs);
757     CPURISCVState *env = &cpu->env;
758 #ifndef CONFIG_USER_ONLY
759     vaddr im_address;
760     hwaddr pa = 0;
761     int prot, prot2, prot_pmp;
762     bool pmp_violation = false;
763     bool first_stage_error = true;
764     bool two_stage_lookup = false;
765     int ret = TRANSLATE_FAIL;
766     int mode = mmu_idx;
767     /* default TLB page size */
768     target_ulong tlb_size = TARGET_PAGE_SIZE;
769 
770     env->guest_phys_fault_addr = 0;
771 
772     qemu_log_mask(CPU_LOG_MMU, "%s ad %" VADDR_PRIx " rw %d mmu_idx %d\n",
773                   __func__, address, access_type, mmu_idx);
774 
775     /* MPRV does not affect the virtual-machine load/store
776        instructions, HLV, HLVX, and HSV. */
777     if (riscv_cpu_two_stage_lookup(mmu_idx)) {
778         mode = get_field(env->hstatus, HSTATUS_SPVP);
779     } else if (mode == PRV_M && access_type != MMU_INST_FETCH &&
780                get_field(env->mstatus, MSTATUS_MPRV)) {
781         mode = get_field(env->mstatus, MSTATUS_MPP);
782         if (riscv_has_ext(env, RVH) && get_field(env->mstatus, MSTATUS_MPV)) {
783             two_stage_lookup = true;
784         }
785     }
786 
787     if (riscv_cpu_virt_enabled(env) ||
788         ((riscv_cpu_two_stage_lookup(mmu_idx) || two_stage_lookup) &&
789          access_type != MMU_INST_FETCH)) {
790         /* Two stage lookup */
791         ret = get_physical_address(env, &pa, &prot, address,
792                                    &env->guest_phys_fault_addr, access_type,
793                                    mmu_idx, true, true, false);
794 
795         /*
796          * A G-stage exception may be triggered during two state lookup.
797          * And the env->guest_phys_fault_addr has already been set in
798          * get_physical_address().
799          */
800         if (ret == TRANSLATE_G_STAGE_FAIL) {
801             first_stage_error = false;
802             access_type = MMU_DATA_LOAD;
803         }
804 
805         qemu_log_mask(CPU_LOG_MMU,
806                       "%s 1st-stage address=%" VADDR_PRIx " ret %d physical "
807                       TARGET_FMT_plx " prot %d\n",
808                       __func__, address, ret, pa, prot);
809 
810         if (ret == TRANSLATE_SUCCESS) {
811             /* Second stage lookup */
812             im_address = pa;
813 
814             ret = get_physical_address(env, &pa, &prot2, im_address, NULL,
815                                        access_type, mmu_idx, false, true,
816                                        false);
817 
818             qemu_log_mask(CPU_LOG_MMU,
819                     "%s 2nd-stage address=%" VADDR_PRIx " ret %d physical "
820                     TARGET_FMT_plx " prot %d\n",
821                     __func__, im_address, ret, pa, prot2);
822 
823             prot &= prot2;
824 
825             if (ret == TRANSLATE_SUCCESS) {
826                 ret = get_physical_address_pmp(env, &prot_pmp, &tlb_size, pa,
827                                                size, access_type, mode);
828 
829                 qemu_log_mask(CPU_LOG_MMU,
830                               "%s PMP address=" TARGET_FMT_plx " ret %d prot"
831                               " %d tlb_size " TARGET_FMT_lu "\n",
832                               __func__, pa, ret, prot_pmp, tlb_size);
833 
834                 prot &= prot_pmp;
835             }
836 
837             if (ret != TRANSLATE_SUCCESS) {
838                 /*
839                  * Guest physical address translation failed, this is a HS
840                  * level exception
841                  */
842                 first_stage_error = false;
843                 env->guest_phys_fault_addr = (im_address |
844                                               (address &
845                                                (TARGET_PAGE_SIZE - 1))) >> 2;
846             }
847         }
848     } else {
849         /* Single stage lookup */
850         ret = get_physical_address(env, &pa, &prot, address, NULL,
851                                    access_type, mmu_idx, true, false, false);
852 
853         qemu_log_mask(CPU_LOG_MMU,
854                       "%s address=%" VADDR_PRIx " ret %d physical "
855                       TARGET_FMT_plx " prot %d\n",
856                       __func__, address, ret, pa, prot);
857 
858         if (ret == TRANSLATE_SUCCESS) {
859             ret = get_physical_address_pmp(env, &prot_pmp, &tlb_size, pa,
860                                            size, access_type, mode);
861 
862             qemu_log_mask(CPU_LOG_MMU,
863                           "%s PMP address=" TARGET_FMT_plx " ret %d prot"
864                           " %d tlb_size " TARGET_FMT_lu "\n",
865                           __func__, pa, ret, prot_pmp, tlb_size);
866 
867             prot &= prot_pmp;
868         }
869     }
870 
871     if (ret == TRANSLATE_PMP_FAIL) {
872         pmp_violation = true;
873     }
874 
875     if (ret == TRANSLATE_SUCCESS) {
876         tlb_set_page(cs, address & ~(tlb_size - 1), pa & ~(tlb_size - 1),
877                      prot, mmu_idx, tlb_size);
878         return true;
879     } else if (probe) {
880         return false;
881     } else {
882         raise_mmu_exception(env, address, access_type, pmp_violation,
883                             first_stage_error,
884                             riscv_cpu_virt_enabled(env) ||
885                                 riscv_cpu_two_stage_lookup(mmu_idx));
886         riscv_raise_exception(env, cs->exception_index, retaddr);
887     }
888 
889     return true;
890 
891 #else
892     switch (access_type) {
893     case MMU_INST_FETCH:
894         cs->exception_index = RISCV_EXCP_INST_PAGE_FAULT;
895         break;
896     case MMU_DATA_LOAD:
897         cs->exception_index = RISCV_EXCP_LOAD_PAGE_FAULT;
898         break;
899     case MMU_DATA_STORE:
900         cs->exception_index = RISCV_EXCP_STORE_PAGE_FAULT;
901         break;
902     default:
903         g_assert_not_reached();
904     }
905     env->badaddr = address;
906     cpu_loop_exit_restore(cs, retaddr);
907 #endif
908 }
909 
910 /*
911  * Handle Traps
912  *
913  * Adapted from Spike's processor_t::take_trap.
914  *
915  */
916 void riscv_cpu_do_interrupt(CPUState *cs)
917 {
918 #if !defined(CONFIG_USER_ONLY)
919 
920     RISCVCPU *cpu = RISCV_CPU(cs);
921     CPURISCVState *env = &cpu->env;
922     bool force_hs_execp = riscv_cpu_force_hs_excep_enabled(env);
923     uint64_t s;
924 
925     /* cs->exception is 32-bits wide unlike mcause which is XLEN-bits wide
926      * so we mask off the MSB and separate into trap type and cause.
927      */
928     bool async = !!(cs->exception_index & RISCV_EXCP_INT_FLAG);
929     target_ulong cause = cs->exception_index & RISCV_EXCP_INT_MASK;
930     target_ulong deleg = async ? env->mideleg : env->medeleg;
931     bool write_tval = false;
932     target_ulong tval = 0;
933     target_ulong htval = 0;
934     target_ulong mtval2 = 0;
935 
936     if  (cause == RISCV_EXCP_SEMIHOST) {
937         if (env->priv >= PRV_S) {
938             env->gpr[xA0] = do_common_semihosting(cs);
939             env->pc += 4;
940             return;
941         }
942         cause = RISCV_EXCP_BREAKPOINT;
943     }
944 
945     if (!async) {
946         /* set tval to badaddr for traps with address information */
947         switch (cause) {
948         case RISCV_EXCP_INST_GUEST_PAGE_FAULT:
949         case RISCV_EXCP_LOAD_GUEST_ACCESS_FAULT:
950         case RISCV_EXCP_STORE_GUEST_AMO_ACCESS_FAULT:
951             force_hs_execp = true;
952             /* fallthrough */
953         case RISCV_EXCP_INST_ADDR_MIS:
954         case RISCV_EXCP_INST_ACCESS_FAULT:
955         case RISCV_EXCP_LOAD_ADDR_MIS:
956         case RISCV_EXCP_STORE_AMO_ADDR_MIS:
957         case RISCV_EXCP_LOAD_ACCESS_FAULT:
958         case RISCV_EXCP_STORE_AMO_ACCESS_FAULT:
959         case RISCV_EXCP_INST_PAGE_FAULT:
960         case RISCV_EXCP_LOAD_PAGE_FAULT:
961         case RISCV_EXCP_STORE_PAGE_FAULT:
962             write_tval  = true;
963             tval = env->badaddr;
964             break;
965         default:
966             break;
967         }
968         /* ecall is dispatched as one cause so translate based on mode */
969         if (cause == RISCV_EXCP_U_ECALL) {
970             assert(env->priv <= 3);
971 
972             if (env->priv == PRV_M) {
973                 cause = RISCV_EXCP_M_ECALL;
974             } else if (env->priv == PRV_S && riscv_cpu_virt_enabled(env)) {
975                 cause = RISCV_EXCP_VS_ECALL;
976             } else if (env->priv == PRV_S && !riscv_cpu_virt_enabled(env)) {
977                 cause = RISCV_EXCP_S_ECALL;
978             } else if (env->priv == PRV_U) {
979                 cause = RISCV_EXCP_U_ECALL;
980             }
981         }
982     }
983 
984     trace_riscv_trap(env->mhartid, async, cause, env->pc, tval,
985                      riscv_cpu_get_trap_name(cause, async));
986 
987     qemu_log_mask(CPU_LOG_INT,
988                   "%s: hart:"TARGET_FMT_ld", async:%d, cause:"TARGET_FMT_lx", "
989                   "epc:0x"TARGET_FMT_lx", tval:0x"TARGET_FMT_lx", desc=%s\n",
990                   __func__, env->mhartid, async, cause, env->pc, tval,
991                   riscv_cpu_get_trap_name(cause, async));
992 
993     if (env->priv <= PRV_S &&
994             cause < TARGET_LONG_BITS && ((deleg >> cause) & 1)) {
995         /* handle the trap in S-mode */
996         if (riscv_has_ext(env, RVH)) {
997             target_ulong hdeleg = async ? env->hideleg : env->hedeleg;
998 
999             if (env->two_stage_lookup && write_tval) {
1000                 /*
1001                  * If we are writing a guest virtual address to stval, set
1002                  * this to 1. If we are trapping to VS we will set this to 0
1003                  * later.
1004                  */
1005                 env->hstatus = set_field(env->hstatus, HSTATUS_GVA, 1);
1006             } else {
1007                 /* For other HS-mode traps, we set this to 0. */
1008                 env->hstatus = set_field(env->hstatus, HSTATUS_GVA, 0);
1009             }
1010 
1011             if (riscv_cpu_virt_enabled(env) && ((hdeleg >> cause) & 1) &&
1012                 !force_hs_execp) {
1013                 /* Trap to VS mode */
1014                 /*
1015                  * See if we need to adjust cause. Yes if its VS mode interrupt
1016                  * no if hypervisor has delegated one of hs mode's interrupt
1017                  */
1018                 if (cause == IRQ_VS_TIMER || cause == IRQ_VS_SOFT ||
1019                     cause == IRQ_VS_EXT) {
1020                     cause = cause - 1;
1021                 }
1022                 env->hstatus = set_field(env->hstatus, HSTATUS_GVA, 0);
1023             } else if (riscv_cpu_virt_enabled(env)) {
1024                 /* Trap into HS mode, from virt */
1025                 riscv_cpu_swap_hypervisor_regs(env);
1026                 env->hstatus = set_field(env->hstatus, HSTATUS_SPVP,
1027                                          env->priv);
1028                 env->hstatus = set_field(env->hstatus, HSTATUS_SPV,
1029                                          riscv_cpu_virt_enabled(env));
1030 
1031                 htval = env->guest_phys_fault_addr;
1032 
1033                 riscv_cpu_set_virt_enabled(env, 0);
1034                 riscv_cpu_set_force_hs_excep(env, 0);
1035             } else {
1036                 /* Trap into HS mode */
1037                 env->hstatus = set_field(env->hstatus, HSTATUS_SPV, false);
1038                 htval = env->guest_phys_fault_addr;
1039             }
1040         }
1041 
1042         s = env->mstatus;
1043         s = set_field(s, MSTATUS_SPIE, get_field(s, MSTATUS_SIE));
1044         s = set_field(s, MSTATUS_SPP, env->priv);
1045         s = set_field(s, MSTATUS_SIE, 0);
1046         env->mstatus = s;
1047         env->scause = cause | ((target_ulong)async << (TARGET_LONG_BITS - 1));
1048         env->sepc = env->pc;
1049         env->stval = tval;
1050         env->htval = htval;
1051         env->pc = (env->stvec >> 2 << 2) +
1052             ((async && (env->stvec & 3) == 1) ? cause * 4 : 0);
1053         riscv_cpu_set_mode(env, PRV_S);
1054     } else {
1055         /* handle the trap in M-mode */
1056         if (riscv_has_ext(env, RVH)) {
1057             if (riscv_cpu_virt_enabled(env)) {
1058                 riscv_cpu_swap_hypervisor_regs(env);
1059             }
1060             env->mstatus = set_field(env->mstatus, MSTATUS_MPV,
1061                                      riscv_cpu_virt_enabled(env));
1062             if (riscv_cpu_virt_enabled(env) && tval) {
1063                 env->mstatus = set_field(env->mstatus, MSTATUS_GVA, 1);
1064             }
1065 
1066             mtval2 = env->guest_phys_fault_addr;
1067 
1068             /* Trapping to M mode, virt is disabled */
1069             riscv_cpu_set_virt_enabled(env, 0);
1070             riscv_cpu_set_force_hs_excep(env, 0);
1071         }
1072 
1073         s = env->mstatus;
1074         s = set_field(s, MSTATUS_MPIE, get_field(s, MSTATUS_MIE));
1075         s = set_field(s, MSTATUS_MPP, env->priv);
1076         s = set_field(s, MSTATUS_MIE, 0);
1077         env->mstatus = s;
1078         env->mcause = cause | ~(((target_ulong)-1) >> async);
1079         env->mepc = env->pc;
1080         env->mtval = tval;
1081         env->mtval2 = mtval2;
1082         env->pc = (env->mtvec >> 2 << 2) +
1083             ((async && (env->mtvec & 3) == 1) ? cause * 4 : 0);
1084         riscv_cpu_set_mode(env, PRV_M);
1085     }
1086 
1087     /* NOTE: it is not necessary to yield load reservations here. It is only
1088      * necessary for an SC from "another hart" to cause a load reservation
1089      * to be yielded. Refer to the memory consistency model section of the
1090      * RISC-V ISA Specification.
1091      */
1092 
1093     env->two_stage_lookup = false;
1094 #endif
1095     cs->exception_index = RISCV_EXCP_NONE; /* mark handled to qemu */
1096 }
1097