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