xref: /openbmc/qemu/target/riscv/cpu_helper.c (revision 29409c1d)
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         env->vstvec = env->stvec;
130         env->stvec = env->stvec_hs;
131 
132         env->vsscratch = env->sscratch;
133         env->sscratch = env->sscratch_hs;
134 
135         env->vsepc = env->sepc;
136         env->sepc = env->sepc_hs;
137 
138         env->vscause = env->scause;
139         env->scause = env->scause_hs;
140 
141         env->vstval = env->sbadaddr;
142         env->sbadaddr = env->stval_hs;
143 
144         env->vsatp = env->satp;
145         env->satp = env->satp_hs;
146     } else {
147         /* Current V=0 and we are about to change to V=1 */
148         env->mstatus_hs = env->mstatus & mstatus_mask;
149         env->mstatus &= ~mstatus_mask;
150         env->mstatus |= env->vsstatus;
151 
152         env->stvec_hs = env->stvec;
153         env->stvec = env->vstvec;
154 
155         env->sscratch_hs = env->sscratch;
156         env->sscratch = env->vsscratch;
157 
158         env->sepc_hs = env->sepc;
159         env->sepc = env->vsepc;
160 
161         env->scause_hs = env->scause;
162         env->scause = env->vscause;
163 
164         env->stval_hs = env->sbadaddr;
165         env->sbadaddr = env->vstval;
166 
167         env->satp_hs = env->satp;
168         env->satp = env->vsatp;
169     }
170 }
171 
172 bool riscv_cpu_virt_enabled(CPURISCVState *env)
173 {
174     if (!riscv_has_ext(env, RVH)) {
175         return false;
176     }
177 
178     return get_field(env->virt, VIRT_ONOFF);
179 }
180 
181 void riscv_cpu_set_virt_enabled(CPURISCVState *env, bool enable)
182 {
183     if (!riscv_has_ext(env, RVH)) {
184         return;
185     }
186 
187     /* Flush the TLB on all virt mode changes. */
188     if (get_field(env->virt, VIRT_ONOFF) != enable) {
189         tlb_flush(env_cpu(env));
190     }
191 
192     env->virt = set_field(env->virt, VIRT_ONOFF, enable);
193 }
194 
195 bool riscv_cpu_force_hs_excep_enabled(CPURISCVState *env)
196 {
197     if (!riscv_has_ext(env, RVH)) {
198         return false;
199     }
200 
201     return get_field(env->virt, FORCE_HS_EXCEP);
202 }
203 
204 void riscv_cpu_set_force_hs_excep(CPURISCVState *env, bool enable)
205 {
206     if (!riscv_has_ext(env, RVH)) {
207         return;
208     }
209 
210     env->virt = set_field(env->virt, FORCE_HS_EXCEP, enable);
211 }
212 
213 int riscv_cpu_claim_interrupts(RISCVCPU *cpu, uint32_t interrupts)
214 {
215     CPURISCVState *env = &cpu->env;
216     if (env->miclaim & interrupts) {
217         return -1;
218     } else {
219         env->miclaim |= interrupts;
220         return 0;
221     }
222 }
223 
224 uint32_t riscv_cpu_update_mip(RISCVCPU *cpu, uint32_t mask, uint32_t value)
225 {
226     CPURISCVState *env = &cpu->env;
227     CPUState *cs = CPU(cpu);
228     uint32_t old = env->mip;
229     bool locked = false;
230 
231     if (!qemu_mutex_iothread_locked()) {
232         locked = true;
233         qemu_mutex_lock_iothread();
234     }
235 
236     env->mip = (env->mip & ~mask) | (value & mask);
237 
238     if (env->mip) {
239         cpu_interrupt(cs, CPU_INTERRUPT_HARD);
240     } else {
241         cpu_reset_interrupt(cs, CPU_INTERRUPT_HARD);
242     }
243 
244     if (locked) {
245         qemu_mutex_unlock_iothread();
246     }
247 
248     return old;
249 }
250 
251 void riscv_cpu_set_mode(CPURISCVState *env, target_ulong newpriv)
252 {
253     if (newpriv > PRV_M) {
254         g_assert_not_reached();
255     }
256     if (newpriv == PRV_H) {
257         newpriv = PRV_U;
258     }
259     /* tlb_flush is unnecessary as mode is contained in mmu_idx */
260     env->priv = newpriv;
261 
262     /*
263      * Clear the load reservation - otherwise a reservation placed in one
264      * context/process can be used by another, resulting in an SC succeeding
265      * incorrectly. Version 2.2 of the ISA specification explicitly requires
266      * this behaviour, while later revisions say that the kernel "should" use
267      * an SC instruction to force the yielding of a load reservation on a
268      * preemptive context switch. As a result, do both.
269      */
270     env->load_res = -1;
271 }
272 
273 /* get_physical_address - get the physical address for this virtual address
274  *
275  * Do a page table walk to obtain the physical address corresponding to a
276  * virtual address. Returns 0 if the translation was successful
277  *
278  * Adapted from Spike's mmu_t::translate and mmu_t::walk
279  *
280  */
281 static int get_physical_address(CPURISCVState *env, hwaddr *physical,
282                                 int *prot, target_ulong addr,
283                                 int access_type, int mmu_idx)
284 {
285     /* NOTE: the env->pc value visible here will not be
286      * correct, but the value visible to the exception handler
287      * (riscv_cpu_do_interrupt) is correct */
288     MemTxResult res;
289     MemTxAttrs attrs = MEMTXATTRS_UNSPECIFIED;
290     int mode = mmu_idx;
291 
292     if (mode == PRV_M && access_type != MMU_INST_FETCH) {
293         if (get_field(env->mstatus, MSTATUS_MPRV)) {
294             mode = get_field(env->mstatus, MSTATUS_MPP);
295         }
296     }
297 
298     if (mode == PRV_M || !riscv_feature(env, RISCV_FEATURE_MMU)) {
299         *physical = addr;
300         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
301         return TRANSLATE_SUCCESS;
302     }
303 
304     *prot = 0;
305 
306     hwaddr base;
307     int levels, ptidxbits, ptesize, vm, sum;
308     int mxr = get_field(env->mstatus, MSTATUS_MXR);
309 
310     if (env->priv_ver >= PRIV_VERSION_1_10_0) {
311         base = (hwaddr)get_field(env->satp, SATP_PPN) << PGSHIFT;
312         sum = get_field(env->mstatus, MSTATUS_SUM);
313         vm = get_field(env->satp, SATP_MODE);
314         switch (vm) {
315         case VM_1_10_SV32:
316           levels = 2; ptidxbits = 10; ptesize = 4; break;
317         case VM_1_10_SV39:
318           levels = 3; ptidxbits = 9; ptesize = 8; break;
319         case VM_1_10_SV48:
320           levels = 4; ptidxbits = 9; ptesize = 8; break;
321         case VM_1_10_SV57:
322           levels = 5; ptidxbits = 9; ptesize = 8; break;
323         case VM_1_10_MBARE:
324             *physical = addr;
325             *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
326             return TRANSLATE_SUCCESS;
327         default:
328           g_assert_not_reached();
329         }
330     } else {
331         base = (hwaddr)(env->sptbr) << PGSHIFT;
332         sum = !get_field(env->mstatus, MSTATUS_PUM);
333         vm = get_field(env->mstatus, MSTATUS_VM);
334         switch (vm) {
335         case VM_1_09_SV32:
336           levels = 2; ptidxbits = 10; ptesize = 4; break;
337         case VM_1_09_SV39:
338           levels = 3; ptidxbits = 9; ptesize = 8; break;
339         case VM_1_09_SV48:
340           levels = 4; ptidxbits = 9; ptesize = 8; break;
341         case VM_1_09_MBARE:
342             *physical = addr;
343             *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
344             return TRANSLATE_SUCCESS;
345         default:
346           g_assert_not_reached();
347         }
348     }
349 
350     CPUState *cs = env_cpu(env);
351     int va_bits = PGSHIFT + levels * ptidxbits;
352     target_ulong mask = (1L << (TARGET_LONG_BITS - (va_bits - 1))) - 1;
353     target_ulong masked_msbs = (addr >> (va_bits - 1)) & mask;
354     if (masked_msbs != 0 && masked_msbs != mask) {
355         return TRANSLATE_FAIL;
356     }
357 
358     int ptshift = (levels - 1) * ptidxbits;
359     int i;
360 
361 #if !TCG_OVERSIZED_GUEST
362 restart:
363 #endif
364     for (i = 0; i < levels; i++, ptshift -= ptidxbits) {
365         target_ulong idx = (addr >> (PGSHIFT + ptshift)) &
366                            ((1 << ptidxbits) - 1);
367 
368         /* check that physical address of PTE is legal */
369         hwaddr pte_addr = base + idx * ptesize;
370 
371         if (riscv_feature(env, RISCV_FEATURE_PMP) &&
372             !pmp_hart_has_privs(env, pte_addr, sizeof(target_ulong),
373             1 << MMU_DATA_LOAD, PRV_S)) {
374             return TRANSLATE_PMP_FAIL;
375         }
376 
377 #if defined(TARGET_RISCV32)
378         target_ulong pte = address_space_ldl(cs->as, pte_addr, attrs, &res);
379 #elif defined(TARGET_RISCV64)
380         target_ulong pte = address_space_ldq(cs->as, pte_addr, attrs, &res);
381 #endif
382         if (res != MEMTX_OK) {
383             return TRANSLATE_FAIL;
384         }
385 
386         hwaddr ppn = pte >> PTE_PPN_SHIFT;
387 
388         if (!(pte & PTE_V)) {
389             /* Invalid PTE */
390             return TRANSLATE_FAIL;
391         } else if (!(pte & (PTE_R | PTE_W | PTE_X))) {
392             /* Inner PTE, continue walking */
393             base = ppn << PGSHIFT;
394         } else if ((pte & (PTE_R | PTE_W | PTE_X)) == PTE_W) {
395             /* Reserved leaf PTE flags: PTE_W */
396             return TRANSLATE_FAIL;
397         } else if ((pte & (PTE_R | PTE_W | PTE_X)) == (PTE_W | PTE_X)) {
398             /* Reserved leaf PTE flags: PTE_W + PTE_X */
399             return TRANSLATE_FAIL;
400         } else if ((pte & PTE_U) && ((mode != PRV_U) &&
401                    (!sum || access_type == MMU_INST_FETCH))) {
402             /* User PTE flags when not U mode and mstatus.SUM is not set,
403                or the access type is an instruction fetch */
404             return TRANSLATE_FAIL;
405         } else if (!(pte & PTE_U) && (mode != PRV_S)) {
406             /* Supervisor PTE flags when not S mode */
407             return TRANSLATE_FAIL;
408         } else if (ppn & ((1ULL << ptshift) - 1)) {
409             /* Misaligned PPN */
410             return TRANSLATE_FAIL;
411         } else if (access_type == MMU_DATA_LOAD && !((pte & PTE_R) ||
412                    ((pte & PTE_X) && mxr))) {
413             /* Read access check failed */
414             return TRANSLATE_FAIL;
415         } else if (access_type == MMU_DATA_STORE && !(pte & PTE_W)) {
416             /* Write access check failed */
417             return TRANSLATE_FAIL;
418         } else if (access_type == MMU_INST_FETCH && !(pte & PTE_X)) {
419             /* Fetch access check failed */
420             return TRANSLATE_FAIL;
421         } else {
422             /* if necessary, set accessed and dirty bits. */
423             target_ulong updated_pte = pte | PTE_A |
424                 (access_type == MMU_DATA_STORE ? PTE_D : 0);
425 
426             /* Page table updates need to be atomic with MTTCG enabled */
427             if (updated_pte != pte) {
428                 /*
429                  * - if accessed or dirty bits need updating, and the PTE is
430                  *   in RAM, then we do so atomically with a compare and swap.
431                  * - if the PTE is in IO space or ROM, then it can't be updated
432                  *   and we return TRANSLATE_FAIL.
433                  * - if the PTE changed by the time we went to update it, then
434                  *   it is no longer valid and we must re-walk the page table.
435                  */
436                 MemoryRegion *mr;
437                 hwaddr l = sizeof(target_ulong), addr1;
438                 mr = address_space_translate(cs->as, pte_addr,
439                     &addr1, &l, false, MEMTXATTRS_UNSPECIFIED);
440                 if (memory_region_is_ram(mr)) {
441                     target_ulong *pte_pa =
442                         qemu_map_ram_ptr(mr->ram_block, addr1);
443 #if TCG_OVERSIZED_GUEST
444                     /* MTTCG is not enabled on oversized TCG guests so
445                      * page table updates do not need to be atomic */
446                     *pte_pa = pte = updated_pte;
447 #else
448                     target_ulong old_pte =
449                         atomic_cmpxchg(pte_pa, pte, updated_pte);
450                     if (old_pte != pte) {
451                         goto restart;
452                     } else {
453                         pte = updated_pte;
454                     }
455 #endif
456                 } else {
457                     /* misconfigured PTE in ROM (AD bits are not preset) or
458                      * PTE is in IO space and can't be updated atomically */
459                     return TRANSLATE_FAIL;
460                 }
461             }
462 
463             /* for superpage mappings, make a fake leaf PTE for the TLB's
464                benefit. */
465             target_ulong vpn = addr >> PGSHIFT;
466             *physical = (ppn | (vpn & ((1L << ptshift) - 1))) << PGSHIFT;
467 
468             /* set permissions on the TLB entry */
469             if ((pte & PTE_R) || ((pte & PTE_X) && mxr)) {
470                 *prot |= PAGE_READ;
471             }
472             if ((pte & PTE_X)) {
473                 *prot |= PAGE_EXEC;
474             }
475             /* add write permission on stores or if the page is already dirty,
476                so that we TLB miss on later writes to update the dirty bit */
477             if ((pte & PTE_W) &&
478                     (access_type == MMU_DATA_STORE || (pte & PTE_D))) {
479                 *prot |= PAGE_WRITE;
480             }
481             return TRANSLATE_SUCCESS;
482         }
483     }
484     return TRANSLATE_FAIL;
485 }
486 
487 static void raise_mmu_exception(CPURISCVState *env, target_ulong address,
488                                 MMUAccessType access_type, bool pmp_violation)
489 {
490     CPUState *cs = env_cpu(env);
491     int page_fault_exceptions =
492         (env->priv_ver >= PRIV_VERSION_1_10_0) &&
493         get_field(env->satp, SATP_MODE) != VM_1_10_MBARE &&
494         !pmp_violation;
495     switch (access_type) {
496     case MMU_INST_FETCH:
497         cs->exception_index = page_fault_exceptions ?
498             RISCV_EXCP_INST_PAGE_FAULT : RISCV_EXCP_INST_ACCESS_FAULT;
499         break;
500     case MMU_DATA_LOAD:
501         cs->exception_index = page_fault_exceptions ?
502             RISCV_EXCP_LOAD_PAGE_FAULT : RISCV_EXCP_LOAD_ACCESS_FAULT;
503         break;
504     case MMU_DATA_STORE:
505         cs->exception_index = page_fault_exceptions ?
506             RISCV_EXCP_STORE_PAGE_FAULT : RISCV_EXCP_STORE_AMO_ACCESS_FAULT;
507         break;
508     default:
509         g_assert_not_reached();
510     }
511     env->badaddr = address;
512 }
513 
514 hwaddr riscv_cpu_get_phys_page_debug(CPUState *cs, vaddr addr)
515 {
516     RISCVCPU *cpu = RISCV_CPU(cs);
517     hwaddr phys_addr;
518     int prot;
519     int mmu_idx = cpu_mmu_index(&cpu->env, false);
520 
521     if (get_physical_address(&cpu->env, &phys_addr, &prot, addr, 0, mmu_idx)) {
522         return -1;
523     }
524     return phys_addr;
525 }
526 
527 void riscv_cpu_do_transaction_failed(CPUState *cs, hwaddr physaddr,
528                                      vaddr addr, unsigned size,
529                                      MMUAccessType access_type,
530                                      int mmu_idx, MemTxAttrs attrs,
531                                      MemTxResult response, uintptr_t retaddr)
532 {
533     RISCVCPU *cpu = RISCV_CPU(cs);
534     CPURISCVState *env = &cpu->env;
535 
536     if (access_type == MMU_DATA_STORE) {
537         cs->exception_index = RISCV_EXCP_STORE_AMO_ACCESS_FAULT;
538     } else {
539         cs->exception_index = RISCV_EXCP_LOAD_ACCESS_FAULT;
540     }
541 
542     env->badaddr = addr;
543     riscv_raise_exception(&cpu->env, cs->exception_index, retaddr);
544 }
545 
546 void riscv_cpu_do_unaligned_access(CPUState *cs, vaddr addr,
547                                    MMUAccessType access_type, int mmu_idx,
548                                    uintptr_t retaddr)
549 {
550     RISCVCPU *cpu = RISCV_CPU(cs);
551     CPURISCVState *env = &cpu->env;
552     switch (access_type) {
553     case MMU_INST_FETCH:
554         cs->exception_index = RISCV_EXCP_INST_ADDR_MIS;
555         break;
556     case MMU_DATA_LOAD:
557         cs->exception_index = RISCV_EXCP_LOAD_ADDR_MIS;
558         break;
559     case MMU_DATA_STORE:
560         cs->exception_index = RISCV_EXCP_STORE_AMO_ADDR_MIS;
561         break;
562     default:
563         g_assert_not_reached();
564     }
565     env->badaddr = addr;
566     riscv_raise_exception(env, cs->exception_index, retaddr);
567 }
568 #endif
569 
570 bool riscv_cpu_tlb_fill(CPUState *cs, vaddr address, int size,
571                         MMUAccessType access_type, int mmu_idx,
572                         bool probe, uintptr_t retaddr)
573 {
574     RISCVCPU *cpu = RISCV_CPU(cs);
575     CPURISCVState *env = &cpu->env;
576 #ifndef CONFIG_USER_ONLY
577     hwaddr pa = 0;
578     int prot;
579     bool pmp_violation = false;
580     int ret = TRANSLATE_FAIL;
581     int mode = mmu_idx;
582 
583     qemu_log_mask(CPU_LOG_MMU, "%s ad %" VADDR_PRIx " rw %d mmu_idx %d\n",
584                   __func__, address, access_type, mmu_idx);
585 
586     ret = get_physical_address(env, &pa, &prot, address, access_type, mmu_idx);
587 
588     if (mode == PRV_M && access_type != MMU_INST_FETCH) {
589         if (get_field(env->mstatus, MSTATUS_MPRV)) {
590             mode = get_field(env->mstatus, MSTATUS_MPP);
591         }
592     }
593 
594     qemu_log_mask(CPU_LOG_MMU,
595                   "%s address=%" VADDR_PRIx " ret %d physical " TARGET_FMT_plx
596                   " prot %d\n", __func__, address, ret, pa, prot);
597 
598     if (riscv_feature(env, RISCV_FEATURE_PMP) &&
599         (ret == TRANSLATE_SUCCESS) &&
600         !pmp_hart_has_privs(env, pa, size, 1 << access_type, mode)) {
601         ret = TRANSLATE_PMP_FAIL;
602     }
603     if (ret == TRANSLATE_PMP_FAIL) {
604         pmp_violation = true;
605     }
606     if (ret == TRANSLATE_SUCCESS) {
607         tlb_set_page(cs, address & TARGET_PAGE_MASK, pa & TARGET_PAGE_MASK,
608                      prot, mmu_idx, TARGET_PAGE_SIZE);
609         return true;
610     } else if (probe) {
611         return false;
612     } else {
613         raise_mmu_exception(env, address, access_type, pmp_violation);
614         riscv_raise_exception(env, cs->exception_index, retaddr);
615     }
616 #else
617     switch (access_type) {
618     case MMU_INST_FETCH:
619         cs->exception_index = RISCV_EXCP_INST_PAGE_FAULT;
620         break;
621     case MMU_DATA_LOAD:
622         cs->exception_index = RISCV_EXCP_LOAD_PAGE_FAULT;
623         break;
624     case MMU_DATA_STORE:
625         cs->exception_index = RISCV_EXCP_STORE_PAGE_FAULT;
626         break;
627     default:
628         g_assert_not_reached();
629     }
630     env->badaddr = address;
631     cpu_loop_exit_restore(cs, retaddr);
632 #endif
633 }
634 
635 /*
636  * Handle Traps
637  *
638  * Adapted from Spike's processor_t::take_trap.
639  *
640  */
641 void riscv_cpu_do_interrupt(CPUState *cs)
642 {
643 #if !defined(CONFIG_USER_ONLY)
644 
645     RISCVCPU *cpu = RISCV_CPU(cs);
646     CPURISCVState *env = &cpu->env;
647     bool force_hs_execp = riscv_cpu_force_hs_excep_enabled(env);
648     target_ulong s;
649 
650     /* cs->exception is 32-bits wide unlike mcause which is XLEN-bits wide
651      * so we mask off the MSB and separate into trap type and cause.
652      */
653     bool async = !!(cs->exception_index & RISCV_EXCP_INT_FLAG);
654     target_ulong cause = cs->exception_index & RISCV_EXCP_INT_MASK;
655     target_ulong deleg = async ? env->mideleg : env->medeleg;
656     target_ulong tval = 0;
657 
658     if (!async) {
659         /* set tval to badaddr for traps with address information */
660         switch (cause) {
661         case RISCV_EXCP_INST_GUEST_PAGE_FAULT:
662         case RISCV_EXCP_LOAD_GUEST_ACCESS_FAULT:
663         case RISCV_EXCP_STORE_GUEST_AMO_ACCESS_FAULT:
664             force_hs_execp = true;
665             /* fallthrough */
666         case RISCV_EXCP_INST_ADDR_MIS:
667         case RISCV_EXCP_INST_ACCESS_FAULT:
668         case RISCV_EXCP_LOAD_ADDR_MIS:
669         case RISCV_EXCP_STORE_AMO_ADDR_MIS:
670         case RISCV_EXCP_LOAD_ACCESS_FAULT:
671         case RISCV_EXCP_STORE_AMO_ACCESS_FAULT:
672         case RISCV_EXCP_INST_PAGE_FAULT:
673         case RISCV_EXCP_LOAD_PAGE_FAULT:
674         case RISCV_EXCP_STORE_PAGE_FAULT:
675             tval = env->badaddr;
676             break;
677         default:
678             break;
679         }
680         /* ecall is dispatched as one cause so translate based on mode */
681         if (cause == RISCV_EXCP_U_ECALL) {
682             assert(env->priv <= 3);
683 
684             if (env->priv == PRV_M) {
685                 cause = RISCV_EXCP_M_ECALL;
686             } else if (env->priv == PRV_S && riscv_cpu_virt_enabled(env)) {
687                 cause = RISCV_EXCP_VS_ECALL;
688             } else if (env->priv == PRV_S && !riscv_cpu_virt_enabled(env)) {
689                 cause = RISCV_EXCP_S_ECALL;
690             } else if (env->priv == PRV_U) {
691                 cause = RISCV_EXCP_U_ECALL;
692             }
693         }
694     }
695 
696     trace_riscv_trap(env->mhartid, async, cause, env->pc, tval, cause < 23 ?
697         (async ? riscv_intr_names : riscv_excp_names)[cause] : "(unknown)");
698 
699     if (env->priv <= PRV_S &&
700             cause < TARGET_LONG_BITS && ((deleg >> cause) & 1)) {
701         /* handle the trap in S-mode */
702         if (riscv_has_ext(env, RVH)) {
703             target_ulong hdeleg = async ? env->hideleg : env->hedeleg;
704 
705             if (riscv_cpu_virt_enabled(env) && ((hdeleg >> cause) & 1) &&
706                 !force_hs_execp) {
707                 /* Trap to VS mode */
708             } else if (riscv_cpu_virt_enabled(env)) {
709                 /* Trap into HS mode, from virt */
710                 riscv_cpu_swap_hypervisor_regs(env);
711                 env->hstatus = set_field(env->hstatus, HSTATUS_SP2V,
712                                          get_field(env->hstatus, HSTATUS_SPV));
713                 env->hstatus = set_field(env->hstatus, HSTATUS_SP2P,
714                                          get_field(env->mstatus, SSTATUS_SPP));
715                 env->hstatus = set_field(env->hstatus, HSTATUS_SPV,
716                                          riscv_cpu_virt_enabled(env));
717 
718                 riscv_cpu_set_virt_enabled(env, 0);
719                 riscv_cpu_set_force_hs_excep(env, 0);
720             } else {
721                 /* Trap into HS mode */
722                 env->hstatus = set_field(env->hstatus, HSTATUS_SP2V,
723                                          get_field(env->hstatus, HSTATUS_SPV));
724                 env->hstatus = set_field(env->hstatus, HSTATUS_SP2P,
725                                          get_field(env->mstatus, SSTATUS_SPP));
726                 env->hstatus = set_field(env->hstatus, HSTATUS_SPV,
727                                          riscv_cpu_virt_enabled(env));
728             }
729         }
730 
731         s = env->mstatus;
732         s = set_field(s, MSTATUS_SPIE, env->priv_ver >= PRIV_VERSION_1_10_0 ?
733             get_field(s, MSTATUS_SIE) : get_field(s, MSTATUS_UIE << env->priv));
734         s = set_field(s, MSTATUS_SPP, env->priv);
735         s = set_field(s, MSTATUS_SIE, 0);
736         env->mstatus = s;
737         env->scause = cause | ((target_ulong)async << (TARGET_LONG_BITS - 1));
738         env->sepc = env->pc;
739         env->sbadaddr = tval;
740         env->pc = (env->stvec >> 2 << 2) +
741             ((async && (env->stvec & 3) == 1) ? cause * 4 : 0);
742         riscv_cpu_set_mode(env, PRV_S);
743     } else {
744         /* handle the trap in M-mode */
745         if (riscv_has_ext(env, RVH)) {
746             if (riscv_cpu_virt_enabled(env)) {
747                 riscv_cpu_swap_hypervisor_regs(env);
748             }
749             env->mstatus = set_field(env->mstatus, MSTATUS_MPV,
750                                       riscv_cpu_virt_enabled(env));
751             env->mstatus = set_field(env->mstatus, MSTATUS_MTL,
752                                       riscv_cpu_force_hs_excep_enabled(env));
753 
754             /* Trapping to M mode, virt is disabled */
755             riscv_cpu_set_virt_enabled(env, 0);
756             riscv_cpu_set_force_hs_excep(env, 0);
757         }
758 
759         s = env->mstatus;
760         s = set_field(s, MSTATUS_MPIE, env->priv_ver >= PRIV_VERSION_1_10_0 ?
761             get_field(s, MSTATUS_MIE) : get_field(s, MSTATUS_UIE << env->priv));
762         s = set_field(s, MSTATUS_MPP, env->priv);
763         s = set_field(s, MSTATUS_MIE, 0);
764         env->mstatus = s;
765         env->mcause = cause | ~(((target_ulong)-1) >> async);
766         env->mepc = env->pc;
767         env->mbadaddr = tval;
768         env->pc = (env->mtvec >> 2 << 2) +
769             ((async && (env->mtvec & 3) == 1) ? cause * 4 : 0);
770         riscv_cpu_set_mode(env, PRV_M);
771     }
772 
773     /* NOTE: it is not necessary to yield load reservations here. It is only
774      * necessary for an SC from "another hart" to cause a load reservation
775      * to be yielded. Refer to the memory consistency model section of the
776      * RISC-V ISA Specification.
777      */
778 
779 #endif
780     cs->exception_index = EXCP_NONE; /* mark handled to qemu */
781 }
782