xref: /openbmc/qemu/target/riscv/cpu_helper.c (revision 5a894dd7)
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));
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 bool riscv_cpu_two_stage_lookup(CPURISCVState *env)
224 {
225     if (!riscv_has_ext(env, RVH)) {
226         return false;
227     }
228 
229     return get_field(env->virt, HS_TWO_STAGE);
230 }
231 
232 void riscv_cpu_set_two_stage_lookup(CPURISCVState *env, bool enable)
233 {
234     if (!riscv_has_ext(env, RVH)) {
235         return;
236     }
237 
238     env->virt = set_field(env->virt, HS_TWO_STAGE, enable);
239 }
240 
241 int riscv_cpu_claim_interrupts(RISCVCPU *cpu, uint32_t interrupts)
242 {
243     CPURISCVState *env = &cpu->env;
244     if (env->miclaim & interrupts) {
245         return -1;
246     } else {
247         env->miclaim |= interrupts;
248         return 0;
249     }
250 }
251 
252 uint32_t riscv_cpu_update_mip(RISCVCPU *cpu, uint32_t mask, uint32_t value)
253 {
254     CPURISCVState *env = &cpu->env;
255     CPUState *cs = CPU(cpu);
256     uint32_t old = env->mip;
257     bool locked = false;
258 
259     if (!qemu_mutex_iothread_locked()) {
260         locked = true;
261         qemu_mutex_lock_iothread();
262     }
263 
264     env->mip = (env->mip & ~mask) | (value & mask);
265 
266     if (env->mip) {
267         cpu_interrupt(cs, CPU_INTERRUPT_HARD);
268     } else {
269         cpu_reset_interrupt(cs, CPU_INTERRUPT_HARD);
270     }
271 
272     if (locked) {
273         qemu_mutex_unlock_iothread();
274     }
275 
276     return old;
277 }
278 
279 void riscv_cpu_set_rdtime_fn(CPURISCVState *env, uint64_t (*fn)(void))
280 {
281     env->rdtime_fn = fn;
282 }
283 
284 void riscv_cpu_set_mode(CPURISCVState *env, target_ulong newpriv)
285 {
286     if (newpriv > PRV_M) {
287         g_assert_not_reached();
288     }
289     if (newpriv == PRV_H) {
290         newpriv = PRV_U;
291     }
292     /* tlb_flush is unnecessary as mode is contained in mmu_idx */
293     env->priv = newpriv;
294 
295     /*
296      * Clear the load reservation - otherwise a reservation placed in one
297      * context/process can be used by another, resulting in an SC succeeding
298      * incorrectly. Version 2.2 of the ISA specification explicitly requires
299      * this behaviour, while later revisions say that the kernel "should" use
300      * an SC instruction to force the yielding of a load reservation on a
301      * preemptive context switch. As a result, do both.
302      */
303     env->load_res = -1;
304 }
305 
306 /* get_physical_address - get the physical address for this virtual address
307  *
308  * Do a page table walk to obtain the physical address corresponding to a
309  * virtual address. Returns 0 if the translation was successful
310  *
311  * Adapted from Spike's mmu_t::translate and mmu_t::walk
312  *
313  * @env: CPURISCVState
314  * @physical: This will be set to the calculated physical address
315  * @prot: The returned protection attributes
316  * @addr: The virtual address to be translated
317  * @access_type: The type of MMU access
318  * @mmu_idx: Indicates current privilege level
319  * @first_stage: Are we in first stage translation?
320  *               Second stage is used for hypervisor guest translation
321  * @two_stage: Are we going to perform two stage translation
322  */
323 static int get_physical_address(CPURISCVState *env, hwaddr *physical,
324                                 int *prot, target_ulong addr,
325                                 int access_type, int mmu_idx,
326                                 bool first_stage, bool two_stage)
327 {
328     /* NOTE: the env->pc value visible here will not be
329      * correct, but the value visible to the exception handler
330      * (riscv_cpu_do_interrupt) is correct */
331     MemTxResult res;
332     MemTxAttrs attrs = MEMTXATTRS_UNSPECIFIED;
333     int mode = mmu_idx;
334     bool use_background = false;
335 
336     /*
337      * Check if we should use the background registers for the two
338      * stage translation. We don't need to check if we actually need
339      * two stage translation as that happened before this function
340      * was called. Background registers will be used if the guest has
341      * forced a two stage translation to be on (in HS or M mode).
342      */
343     if (mode == PRV_M && access_type != MMU_INST_FETCH) {
344         if (get_field(env->mstatus, MSTATUS_MPRV)) {
345             mode = get_field(env->mstatus, MSTATUS_MPP);
346 
347             if (riscv_has_ext(env, RVH) &&
348                 MSTATUS_MPV_ISSET(env)) {
349                 use_background = true;
350             }
351         }
352     }
353 
354     if (mode == PRV_S && access_type != MMU_INST_FETCH &&
355         riscv_has_ext(env, RVH) && !riscv_cpu_virt_enabled(env)) {
356         if (get_field(env->hstatus, HSTATUS_SPRV)) {
357             mode = get_field(env->mstatus, SSTATUS_SPP);
358             use_background = true;
359         }
360     }
361 
362     if (first_stage == false) {
363         /* We are in stage 2 translation, this is similar to stage 1. */
364         /* Stage 2 is always taken as U-mode */
365         mode = PRV_U;
366     }
367 
368     if (mode == PRV_M || !riscv_feature(env, RISCV_FEATURE_MMU)) {
369         *physical = addr;
370         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
371         return TRANSLATE_SUCCESS;
372     }
373 
374     *prot = 0;
375 
376     hwaddr base;
377     int levels, ptidxbits, ptesize, vm, sum, mxr, widened;
378 
379     if (first_stage == true) {
380         mxr = get_field(env->mstatus, MSTATUS_MXR);
381     } else {
382         mxr = get_field(env->vsstatus, MSTATUS_MXR);
383     }
384 
385     if (first_stage == true) {
386         if (use_background) {
387             base = (hwaddr)get_field(env->vsatp, SATP_PPN) << PGSHIFT;
388             vm = get_field(env->vsatp, SATP_MODE);
389         } else {
390             base = (hwaddr)get_field(env->satp, SATP_PPN) << PGSHIFT;
391             vm = get_field(env->satp, SATP_MODE);
392         }
393         widened = 0;
394     } else {
395         base = (hwaddr)get_field(env->hgatp, HGATP_PPN) << PGSHIFT;
396         vm = get_field(env->hgatp, HGATP_MODE);
397         widened = 2;
398     }
399     sum = get_field(env->mstatus, MSTATUS_SUM);
400     switch (vm) {
401     case VM_1_10_SV32:
402       levels = 2; ptidxbits = 10; ptesize = 4; break;
403     case VM_1_10_SV39:
404       levels = 3; ptidxbits = 9; ptesize = 8; break;
405     case VM_1_10_SV48:
406       levels = 4; ptidxbits = 9; ptesize = 8; break;
407     case VM_1_10_SV57:
408       levels = 5; ptidxbits = 9; ptesize = 8; break;
409     case VM_1_10_MBARE:
410         *physical = addr;
411         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
412         return TRANSLATE_SUCCESS;
413     default:
414       g_assert_not_reached();
415     }
416 
417     CPUState *cs = env_cpu(env);
418     int va_bits = PGSHIFT + levels * ptidxbits + widened;
419     target_ulong mask, masked_msbs;
420 
421     if (TARGET_LONG_BITS > (va_bits - 1)) {
422         mask = (1L << (TARGET_LONG_BITS - (va_bits - 1))) - 1;
423     } else {
424         mask = 0;
425     }
426     masked_msbs = (addr >> (va_bits - 1)) & mask;
427 
428     if (masked_msbs != 0 && masked_msbs != mask) {
429         return TRANSLATE_FAIL;
430     }
431 
432     int ptshift = (levels - 1) * ptidxbits;
433     int i;
434 
435 #if !TCG_OVERSIZED_GUEST
436 restart:
437 #endif
438     for (i = 0; i < levels; i++, ptshift -= ptidxbits) {
439         target_ulong idx;
440         if (i == 0) {
441             idx = (addr >> (PGSHIFT + ptshift)) &
442                            ((1 << (ptidxbits + widened)) - 1);
443         } else {
444             idx = (addr >> (PGSHIFT + ptshift)) &
445                            ((1 << ptidxbits) - 1);
446         }
447 
448         /* check that physical address of PTE is legal */
449         hwaddr pte_addr;
450 
451         if (two_stage && first_stage) {
452             int vbase_prot;
453             hwaddr vbase;
454 
455             /* Do the second stage translation on the base PTE address. */
456             int vbase_ret = get_physical_address(env, &vbase, &vbase_prot,
457                                                  base, MMU_DATA_LOAD,
458                                                  mmu_idx, false, true);
459 
460             if (vbase_ret != TRANSLATE_SUCCESS) {
461                 return vbase_ret;
462             }
463 
464             pte_addr = vbase + idx * ptesize;
465         } else {
466             pte_addr = base + idx * ptesize;
467         }
468 
469         if (riscv_feature(env, RISCV_FEATURE_PMP) &&
470             !pmp_hart_has_privs(env, pte_addr, sizeof(target_ulong),
471             1 << MMU_DATA_LOAD, PRV_S)) {
472             return TRANSLATE_PMP_FAIL;
473         }
474 
475 #if defined(TARGET_RISCV32)
476         target_ulong pte = address_space_ldl(cs->as, pte_addr, attrs, &res);
477 #elif defined(TARGET_RISCV64)
478         target_ulong pte = address_space_ldq(cs->as, pte_addr, attrs, &res);
479 #endif
480         if (res != MEMTX_OK) {
481             return TRANSLATE_FAIL;
482         }
483 
484         hwaddr ppn = pte >> PTE_PPN_SHIFT;
485 
486         if (!(pte & PTE_V)) {
487             /* Invalid PTE */
488             return TRANSLATE_FAIL;
489         } else if (!(pte & (PTE_R | PTE_W | PTE_X))) {
490             /* Inner PTE, continue walking */
491             base = ppn << PGSHIFT;
492         } else if ((pte & (PTE_R | PTE_W | PTE_X)) == PTE_W) {
493             /* Reserved leaf PTE flags: PTE_W */
494             return TRANSLATE_FAIL;
495         } else if ((pte & (PTE_R | PTE_W | PTE_X)) == (PTE_W | PTE_X)) {
496             /* Reserved leaf PTE flags: PTE_W + PTE_X */
497             return TRANSLATE_FAIL;
498         } else if ((pte & PTE_U) && ((mode != PRV_U) &&
499                    (!sum || access_type == MMU_INST_FETCH))) {
500             /* User PTE flags when not U mode and mstatus.SUM is not set,
501                or the access type is an instruction fetch */
502             return TRANSLATE_FAIL;
503         } else if (!(pte & PTE_U) && (mode != PRV_S)) {
504             /* Supervisor PTE flags when not S mode */
505             return TRANSLATE_FAIL;
506         } else if (ppn & ((1ULL << ptshift) - 1)) {
507             /* Misaligned PPN */
508             return TRANSLATE_FAIL;
509         } else if (access_type == MMU_DATA_LOAD && !((pte & PTE_R) ||
510                    ((pte & PTE_X) && mxr))) {
511             /* Read access check failed */
512             return TRANSLATE_FAIL;
513         } else if (access_type == MMU_DATA_STORE && !(pte & PTE_W)) {
514             /* Write access check failed */
515             return TRANSLATE_FAIL;
516         } else if (access_type == MMU_INST_FETCH && !(pte & PTE_X)) {
517             /* Fetch access check failed */
518             return TRANSLATE_FAIL;
519         } else {
520             /* if necessary, set accessed and dirty bits. */
521             target_ulong updated_pte = pte | PTE_A |
522                 (access_type == MMU_DATA_STORE ? PTE_D : 0);
523 
524             /* Page table updates need to be atomic with MTTCG enabled */
525             if (updated_pte != pte) {
526                 /*
527                  * - if accessed or dirty bits need updating, and the PTE is
528                  *   in RAM, then we do so atomically with a compare and swap.
529                  * - if the PTE is in IO space or ROM, then it can't be updated
530                  *   and we return TRANSLATE_FAIL.
531                  * - if the PTE changed by the time we went to update it, then
532                  *   it is no longer valid and we must re-walk the page table.
533                  */
534                 MemoryRegion *mr;
535                 hwaddr l = sizeof(target_ulong), addr1;
536                 mr = address_space_translate(cs->as, pte_addr,
537                     &addr1, &l, false, MEMTXATTRS_UNSPECIFIED);
538                 if (memory_region_is_ram(mr)) {
539                     target_ulong *pte_pa =
540                         qemu_map_ram_ptr(mr->ram_block, addr1);
541 #if TCG_OVERSIZED_GUEST
542                     /* MTTCG is not enabled on oversized TCG guests so
543                      * page table updates do not need to be atomic */
544                     *pte_pa = pte = updated_pte;
545 #else
546                     target_ulong old_pte =
547                         atomic_cmpxchg(pte_pa, pte, updated_pte);
548                     if (old_pte != pte) {
549                         goto restart;
550                     } else {
551                         pte = updated_pte;
552                     }
553 #endif
554                 } else {
555                     /* misconfigured PTE in ROM (AD bits are not preset) or
556                      * PTE is in IO space and can't be updated atomically */
557                     return TRANSLATE_FAIL;
558                 }
559             }
560 
561             /* for superpage mappings, make a fake leaf PTE for the TLB's
562                benefit. */
563             target_ulong vpn = addr >> PGSHIFT;
564             *physical = ((ppn | (vpn & ((1L << ptshift) - 1))) << PGSHIFT) |
565                         (addr & ~TARGET_PAGE_MASK);
566 
567             /* set permissions on the TLB entry */
568             if ((pte & PTE_R) || ((pte & PTE_X) && mxr)) {
569                 *prot |= PAGE_READ;
570             }
571             if ((pte & PTE_X)) {
572                 *prot |= PAGE_EXEC;
573             }
574             /* add write permission on stores or if the page is already dirty,
575                so that we TLB miss on later writes to update the dirty bit */
576             if ((pte & PTE_W) &&
577                     (access_type == MMU_DATA_STORE || (pte & PTE_D))) {
578                 *prot |= PAGE_WRITE;
579             }
580             return TRANSLATE_SUCCESS;
581         }
582     }
583     return TRANSLATE_FAIL;
584 }
585 
586 static void raise_mmu_exception(CPURISCVState *env, target_ulong address,
587                                 MMUAccessType access_type, bool pmp_violation,
588                                 bool first_stage)
589 {
590     CPUState *cs = env_cpu(env);
591     int page_fault_exceptions;
592     if (first_stage) {
593         page_fault_exceptions =
594             get_field(env->satp, SATP_MODE) != VM_1_10_MBARE &&
595             !pmp_violation;
596     } else {
597         page_fault_exceptions =
598             get_field(env->hgatp, HGATP_MODE) != VM_1_10_MBARE &&
599             !pmp_violation;
600     }
601     switch (access_type) {
602     case MMU_INST_FETCH:
603         if (riscv_cpu_virt_enabled(env) && !first_stage) {
604             cs->exception_index = RISCV_EXCP_INST_GUEST_PAGE_FAULT;
605         } else {
606             cs->exception_index = page_fault_exceptions ?
607                 RISCV_EXCP_INST_PAGE_FAULT : RISCV_EXCP_INST_ACCESS_FAULT;
608         }
609         break;
610     case MMU_DATA_LOAD:
611         if (riscv_cpu_virt_enabled(env) && !first_stage) {
612             cs->exception_index = RISCV_EXCP_LOAD_GUEST_ACCESS_FAULT;
613         } else {
614             cs->exception_index = page_fault_exceptions ?
615                 RISCV_EXCP_LOAD_PAGE_FAULT : RISCV_EXCP_LOAD_ACCESS_FAULT;
616         }
617         break;
618     case MMU_DATA_STORE:
619         if (riscv_cpu_virt_enabled(env) && !first_stage) {
620             cs->exception_index = RISCV_EXCP_STORE_GUEST_AMO_ACCESS_FAULT;
621         } else {
622             cs->exception_index = page_fault_exceptions ?
623                 RISCV_EXCP_STORE_PAGE_FAULT : RISCV_EXCP_STORE_AMO_ACCESS_FAULT;
624         }
625         break;
626     default:
627         g_assert_not_reached();
628     }
629     env->badaddr = address;
630 }
631 
632 hwaddr riscv_cpu_get_phys_page_debug(CPUState *cs, vaddr addr)
633 {
634     RISCVCPU *cpu = RISCV_CPU(cs);
635     CPURISCVState *env = &cpu->env;
636     hwaddr phys_addr;
637     int prot;
638     int mmu_idx = cpu_mmu_index(&cpu->env, false);
639 
640     if (get_physical_address(env, &phys_addr, &prot, addr, 0, mmu_idx,
641                              true, riscv_cpu_virt_enabled(env))) {
642         return -1;
643     }
644 
645     if (riscv_cpu_virt_enabled(env)) {
646         if (get_physical_address(env, &phys_addr, &prot, phys_addr,
647                                  0, mmu_idx, false, true)) {
648             return -1;
649         }
650     }
651 
652     return phys_addr & TARGET_PAGE_MASK;
653 }
654 
655 void riscv_cpu_do_transaction_failed(CPUState *cs, hwaddr physaddr,
656                                      vaddr addr, unsigned size,
657                                      MMUAccessType access_type,
658                                      int mmu_idx, MemTxAttrs attrs,
659                                      MemTxResult response, uintptr_t retaddr)
660 {
661     RISCVCPU *cpu = RISCV_CPU(cs);
662     CPURISCVState *env = &cpu->env;
663 
664     if (access_type == MMU_DATA_STORE) {
665         cs->exception_index = RISCV_EXCP_STORE_AMO_ACCESS_FAULT;
666     } else {
667         cs->exception_index = RISCV_EXCP_LOAD_ACCESS_FAULT;
668     }
669 
670     env->badaddr = addr;
671     riscv_raise_exception(&cpu->env, cs->exception_index, retaddr);
672 }
673 
674 void riscv_cpu_do_unaligned_access(CPUState *cs, vaddr addr,
675                                    MMUAccessType access_type, int mmu_idx,
676                                    uintptr_t retaddr)
677 {
678     RISCVCPU *cpu = RISCV_CPU(cs);
679     CPURISCVState *env = &cpu->env;
680     switch (access_type) {
681     case MMU_INST_FETCH:
682         cs->exception_index = RISCV_EXCP_INST_ADDR_MIS;
683         break;
684     case MMU_DATA_LOAD:
685         cs->exception_index = RISCV_EXCP_LOAD_ADDR_MIS;
686         break;
687     case MMU_DATA_STORE:
688         cs->exception_index = RISCV_EXCP_STORE_AMO_ADDR_MIS;
689         break;
690     default:
691         g_assert_not_reached();
692     }
693     env->badaddr = addr;
694     riscv_raise_exception(env, cs->exception_index, retaddr);
695 }
696 #endif
697 
698 bool riscv_cpu_tlb_fill(CPUState *cs, vaddr address, int size,
699                         MMUAccessType access_type, int mmu_idx,
700                         bool probe, uintptr_t retaddr)
701 {
702     RISCVCPU *cpu = RISCV_CPU(cs);
703     CPURISCVState *env = &cpu->env;
704 #ifndef CONFIG_USER_ONLY
705     vaddr im_address;
706     hwaddr pa = 0;
707     int prot, prot2;
708     bool pmp_violation = false;
709     bool m_mode_two_stage = false;
710     bool hs_mode_two_stage = false;
711     bool first_stage_error = true;
712     int ret = TRANSLATE_FAIL;
713     int mode = mmu_idx;
714     target_ulong tlb_size = 0;
715 
716     env->guest_phys_fault_addr = 0;
717 
718     qemu_log_mask(CPU_LOG_MMU, "%s ad %" VADDR_PRIx " rw %d mmu_idx %d\n",
719                   __func__, address, access_type, mmu_idx);
720 
721     /*
722      * Determine if we are in M mode and MPRV is set or in HS mode and SPRV is
723      * set and we want to access a virtulisation address.
724      */
725     if (riscv_has_ext(env, RVH)) {
726         m_mode_two_stage = env->priv == PRV_M &&
727                            access_type != MMU_INST_FETCH &&
728                            get_field(env->mstatus, MSTATUS_MPRV) &&
729                            MSTATUS_MPV_ISSET(env);
730 
731         hs_mode_two_stage = env->priv == PRV_S &&
732                             !riscv_cpu_virt_enabled(env) &&
733                             access_type != MMU_INST_FETCH &&
734                             get_field(env->hstatus, HSTATUS_SPRV) &&
735                             get_field(env->hstatus, HSTATUS_SPV);
736     }
737 
738     if (mode == PRV_M && access_type != MMU_INST_FETCH) {
739         if (get_field(env->mstatus, MSTATUS_MPRV)) {
740             mode = get_field(env->mstatus, MSTATUS_MPP);
741         }
742     }
743 
744     if (riscv_cpu_virt_enabled(env) || m_mode_two_stage || hs_mode_two_stage) {
745         /* Two stage lookup */
746         ret = get_physical_address(env, &pa, &prot, address, access_type,
747                                    mmu_idx, true, true);
748 
749         qemu_log_mask(CPU_LOG_MMU,
750                       "%s 1st-stage address=%" VADDR_PRIx " ret %d physical "
751                       TARGET_FMT_plx " prot %d\n",
752                       __func__, address, ret, pa, prot);
753 
754         if (ret != TRANSLATE_FAIL) {
755             /* Second stage lookup */
756             im_address = pa;
757 
758             ret = get_physical_address(env, &pa, &prot2, im_address,
759                                        access_type, mmu_idx, false, true);
760 
761             qemu_log_mask(CPU_LOG_MMU,
762                     "%s 2nd-stage address=%" VADDR_PRIx " ret %d physical "
763                     TARGET_FMT_plx " prot %d\n",
764                     __func__, im_address, ret, pa, prot2);
765 
766             prot &= prot2;
767 
768             if (riscv_feature(env, RISCV_FEATURE_PMP) &&
769                 (ret == TRANSLATE_SUCCESS) &&
770                 !pmp_hart_has_privs(env, pa, size, 1 << access_type, mode)) {
771                 ret = TRANSLATE_PMP_FAIL;
772             }
773 
774             if (ret != TRANSLATE_SUCCESS) {
775                 /*
776                  * Guest physical address translation failed, this is a HS
777                  * level exception
778                  */
779                 first_stage_error = false;
780                 env->guest_phys_fault_addr = (im_address |
781                                               (address &
782                                                (TARGET_PAGE_SIZE - 1))) >> 2;
783             }
784         }
785     } else {
786         /* Single stage lookup */
787         ret = get_physical_address(env, &pa, &prot, address, access_type,
788                                    mmu_idx, true, false);
789 
790         qemu_log_mask(CPU_LOG_MMU,
791                       "%s address=%" VADDR_PRIx " ret %d physical "
792                       TARGET_FMT_plx " prot %d\n",
793                       __func__, address, ret, pa, prot);
794     }
795 
796     if (riscv_feature(env, RISCV_FEATURE_PMP) &&
797         (ret == TRANSLATE_SUCCESS) &&
798         !pmp_hart_has_privs(env, pa, size, 1 << access_type, mode)) {
799         ret = TRANSLATE_PMP_FAIL;
800     }
801     if (ret == TRANSLATE_PMP_FAIL) {
802         pmp_violation = true;
803     }
804 
805     if (ret == TRANSLATE_SUCCESS) {
806         if (pmp_is_range_in_tlb(env, pa & TARGET_PAGE_MASK, &tlb_size)) {
807             tlb_set_page(cs, address & ~(tlb_size - 1), pa & ~(tlb_size - 1),
808                          prot, mmu_idx, tlb_size);
809         } else {
810             tlb_set_page(cs, address & TARGET_PAGE_MASK, pa & TARGET_PAGE_MASK,
811                          prot, mmu_idx, TARGET_PAGE_SIZE);
812         }
813         return true;
814     } else if (probe) {
815         return false;
816     } else {
817         raise_mmu_exception(env, address, access_type, pmp_violation, first_stage_error);
818         riscv_raise_exception(env, cs->exception_index, retaddr);
819     }
820 
821     return true;
822 
823 #else
824     switch (access_type) {
825     case MMU_INST_FETCH:
826         cs->exception_index = RISCV_EXCP_INST_PAGE_FAULT;
827         break;
828     case MMU_DATA_LOAD:
829         cs->exception_index = RISCV_EXCP_LOAD_PAGE_FAULT;
830         break;
831     case MMU_DATA_STORE:
832         cs->exception_index = RISCV_EXCP_STORE_PAGE_FAULT;
833         break;
834     default:
835         g_assert_not_reached();
836     }
837     env->badaddr = address;
838     cpu_loop_exit_restore(cs, retaddr);
839 #endif
840 }
841 
842 /*
843  * Handle Traps
844  *
845  * Adapted from Spike's processor_t::take_trap.
846  *
847  */
848 void riscv_cpu_do_interrupt(CPUState *cs)
849 {
850 #if !defined(CONFIG_USER_ONLY)
851 
852     RISCVCPU *cpu = RISCV_CPU(cs);
853     CPURISCVState *env = &cpu->env;
854     bool force_hs_execp = riscv_cpu_force_hs_excep_enabled(env);
855     target_ulong s;
856 
857     /* cs->exception is 32-bits wide unlike mcause which is XLEN-bits wide
858      * so we mask off the MSB and separate into trap type and cause.
859      */
860     bool async = !!(cs->exception_index & RISCV_EXCP_INT_FLAG);
861     target_ulong cause = cs->exception_index & RISCV_EXCP_INT_MASK;
862     target_ulong deleg = async ? env->mideleg : env->medeleg;
863     target_ulong tval = 0;
864     target_ulong htval = 0;
865     target_ulong mtval2 = 0;
866 
867     if (!async) {
868         /* set tval to badaddr for traps with address information */
869         switch (cause) {
870         case RISCV_EXCP_INST_GUEST_PAGE_FAULT:
871         case RISCV_EXCP_LOAD_GUEST_ACCESS_FAULT:
872         case RISCV_EXCP_STORE_GUEST_AMO_ACCESS_FAULT:
873             force_hs_execp = true;
874             /* fallthrough */
875         case RISCV_EXCP_INST_ADDR_MIS:
876         case RISCV_EXCP_INST_ACCESS_FAULT:
877         case RISCV_EXCP_LOAD_ADDR_MIS:
878         case RISCV_EXCP_STORE_AMO_ADDR_MIS:
879         case RISCV_EXCP_LOAD_ACCESS_FAULT:
880         case RISCV_EXCP_STORE_AMO_ACCESS_FAULT:
881         case RISCV_EXCP_INST_PAGE_FAULT:
882         case RISCV_EXCP_LOAD_PAGE_FAULT:
883         case RISCV_EXCP_STORE_PAGE_FAULT:
884             tval = env->badaddr;
885             break;
886         default:
887             break;
888         }
889         /* ecall is dispatched as one cause so translate based on mode */
890         if (cause == RISCV_EXCP_U_ECALL) {
891             assert(env->priv <= 3);
892 
893             if (env->priv == PRV_M) {
894                 cause = RISCV_EXCP_M_ECALL;
895             } else if (env->priv == PRV_S && riscv_cpu_virt_enabled(env)) {
896                 cause = RISCV_EXCP_VS_ECALL;
897             } else if (env->priv == PRV_S && !riscv_cpu_virt_enabled(env)) {
898                 cause = RISCV_EXCP_S_ECALL;
899             } else if (env->priv == PRV_U) {
900                 cause = RISCV_EXCP_U_ECALL;
901             }
902         }
903     }
904 
905     trace_riscv_trap(env->mhartid, async, cause, env->pc, tval, cause < 23 ?
906         (async ? riscv_intr_names : riscv_excp_names)[cause] : "(unknown)");
907 
908     if (env->priv <= PRV_S &&
909             cause < TARGET_LONG_BITS && ((deleg >> cause) & 1)) {
910         /* handle the trap in S-mode */
911         if (riscv_has_ext(env, RVH)) {
912             target_ulong hdeleg = async ? env->hideleg : env->hedeleg;
913 
914             if (riscv_cpu_virt_enabled(env) && ((hdeleg >> cause) & 1) &&
915                 !force_hs_execp) {
916                 /*
917                  * See if we need to adjust cause. Yes if its VS mode interrupt
918                  * no if hypervisor has delegated one of hs mode's interrupt
919                  */
920                 if (cause == IRQ_VS_TIMER || cause == IRQ_VS_SOFT ||
921                     cause == IRQ_VS_EXT)
922                     cause = cause - 1;
923                 /* Trap to VS mode */
924             } else if (riscv_cpu_virt_enabled(env)) {
925                 /* Trap into HS mode, from virt */
926                 riscv_cpu_swap_hypervisor_regs(env);
927                 env->hstatus = set_field(env->hstatus, HSTATUS_SP2V,
928                                          get_field(env->hstatus, HSTATUS_SPV));
929                 env->hstatus = set_field(env->hstatus, HSTATUS_SP2P,
930                                          get_field(env->mstatus, SSTATUS_SPP));
931                 env->hstatus = set_field(env->hstatus, HSTATUS_SPV,
932                                          riscv_cpu_virt_enabled(env));
933 
934                 htval = env->guest_phys_fault_addr;
935 
936                 riscv_cpu_set_virt_enabled(env, 0);
937                 riscv_cpu_set_force_hs_excep(env, 0);
938             } else {
939                 /* Trap into HS mode */
940                 env->hstatus = set_field(env->hstatus, HSTATUS_SP2V,
941                                          get_field(env->hstatus, HSTATUS_SPV));
942                 env->hstatus = set_field(env->hstatus, HSTATUS_SP2P,
943                                          get_field(env->mstatus, SSTATUS_SPP));
944                 env->hstatus = set_field(env->hstatus, HSTATUS_SPV,
945                                          riscv_cpu_virt_enabled(env));
946 
947                 htval = env->guest_phys_fault_addr;
948             }
949         }
950 
951         s = env->mstatus;
952         s = set_field(s, MSTATUS_SPIE, get_field(s, MSTATUS_SIE));
953         s = set_field(s, MSTATUS_SPP, env->priv);
954         s = set_field(s, MSTATUS_SIE, 0);
955         env->mstatus = s;
956         env->scause = cause | ((target_ulong)async << (TARGET_LONG_BITS - 1));
957         env->sepc = env->pc;
958         env->sbadaddr = tval;
959         env->htval = htval;
960         env->pc = (env->stvec >> 2 << 2) +
961             ((async && (env->stvec & 3) == 1) ? cause * 4 : 0);
962         riscv_cpu_set_mode(env, PRV_S);
963     } else {
964         /* handle the trap in M-mode */
965         if (riscv_has_ext(env, RVH)) {
966             if (riscv_cpu_virt_enabled(env)) {
967                 riscv_cpu_swap_hypervisor_regs(env);
968             }
969 #ifdef TARGET_RISCV32
970             env->mstatush = set_field(env->mstatush, MSTATUS_MPV,
971                                        riscv_cpu_virt_enabled(env));
972             env->mstatush = set_field(env->mstatush, MSTATUS_MTL,
973                                        riscv_cpu_force_hs_excep_enabled(env));
974 #else
975             env->mstatus = set_field(env->mstatus, MSTATUS_MPV,
976                                       riscv_cpu_virt_enabled(env));
977             env->mstatus = set_field(env->mstatus, MSTATUS_MTL,
978                                       riscv_cpu_force_hs_excep_enabled(env));
979 #endif
980 
981             mtval2 = env->guest_phys_fault_addr;
982 
983             /* Trapping to M mode, virt is disabled */
984             riscv_cpu_set_virt_enabled(env, 0);
985             riscv_cpu_set_force_hs_excep(env, 0);
986         }
987 
988         s = env->mstatus;
989         s = set_field(s, MSTATUS_MPIE, get_field(s, MSTATUS_MIE));
990         s = set_field(s, MSTATUS_MPP, env->priv);
991         s = set_field(s, MSTATUS_MIE, 0);
992         env->mstatus = s;
993         env->mcause = cause | ~(((target_ulong)-1) >> async);
994         env->mepc = env->pc;
995         env->mbadaddr = tval;
996         env->mtval2 = mtval2;
997         env->pc = (env->mtvec >> 2 << 2) +
998             ((async && (env->mtvec & 3) == 1) ? cause * 4 : 0);
999         riscv_cpu_set_mode(env, PRV_M);
1000     }
1001 
1002     /* NOTE: it is not necessary to yield load reservations here. It is only
1003      * necessary for an SC from "another hart" to cause a load reservation
1004      * to be yielded. Refer to the memory consistency model section of the
1005      * RISC-V ISA Specification.
1006      */
1007 
1008 #endif
1009     cs->exception_index = EXCP_NONE; /* mark handled to qemu */
1010 }
1011