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