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