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