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