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