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