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