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