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