xref: /openbmc/qemu/target/riscv/cpu_helper.c (revision 200dbf37)
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 "cpu.h"
23 #include "exec/exec-all.h"
24 #include "tcg-op.h"
25 #include "trace.h"
26 
27 int riscv_cpu_mmu_index(CPURISCVState *env, bool ifetch)
28 {
29 #ifdef CONFIG_USER_ONLY
30     return 0;
31 #else
32     return env->priv;
33 #endif
34 }
35 
36 #ifndef CONFIG_USER_ONLY
37 static int riscv_cpu_local_irq_pending(CPURISCVState *env)
38 {
39     target_ulong mstatus_mie = get_field(env->mstatus, MSTATUS_MIE);
40     target_ulong mstatus_sie = get_field(env->mstatus, MSTATUS_SIE);
41     target_ulong pending = atomic_read(&env->mip) & env->mie;
42     target_ulong mie = env->priv < PRV_M || (env->priv == PRV_M && mstatus_mie);
43     target_ulong sie = env->priv < PRV_S || (env->priv == PRV_S && mstatus_sie);
44     target_ulong irqs = (pending & ~env->mideleg & -mie) |
45                         (pending &  env->mideleg & -sie);
46 
47     if (irqs) {
48         return ctz64(irqs); /* since non-zero */
49     } else {
50         return EXCP_NONE; /* indicates no pending interrupt */
51     }
52 }
53 #endif
54 
55 bool riscv_cpu_exec_interrupt(CPUState *cs, int interrupt_request)
56 {
57 #if !defined(CONFIG_USER_ONLY)
58     if (interrupt_request & CPU_INTERRUPT_HARD) {
59         RISCVCPU *cpu = RISCV_CPU(cs);
60         CPURISCVState *env = &cpu->env;
61         int interruptno = riscv_cpu_local_irq_pending(env);
62         if (interruptno >= 0) {
63             cs->exception_index = RISCV_EXCP_INT_FLAG | interruptno;
64             riscv_cpu_do_interrupt(cs);
65             return true;
66         }
67     }
68 #endif
69     return false;
70 }
71 
72 #if !defined(CONFIG_USER_ONLY)
73 
74 int riscv_cpu_claim_interrupts(RISCVCPU *cpu, uint32_t interrupts)
75 {
76     CPURISCVState *env = &cpu->env;
77     if (env->miclaim & interrupts) {
78         return -1;
79     } else {
80         env->miclaim |= interrupts;
81         return 0;
82     }
83 }
84 
85 struct CpuAsyncInfo {
86     uint32_t new_mip;
87 };
88 
89 static void riscv_cpu_update_mip_irqs_async(CPUState *target_cpu_state,
90                                             run_on_cpu_data data)
91 {
92     CPURISCVState *env = &RISCV_CPU(target_cpu_state)->env;
93     RISCVCPU *cpu = riscv_env_get_cpu(env);
94     struct CpuAsyncInfo *info = (struct CpuAsyncInfo *) data.host_ptr;
95 
96     if (info->new_mip) {
97         cpu_interrupt(CPU(cpu), CPU_INTERRUPT_HARD);
98     } else {
99         cpu_reset_interrupt(CPU(cpu), CPU_INTERRUPT_HARD);
100     }
101 
102     g_free(info);
103 }
104 
105 uint32_t riscv_cpu_update_mip(RISCVCPU *cpu, uint32_t mask, uint32_t value)
106 {
107     CPURISCVState *env = &cpu->env;
108     CPUState *cs = CPU(cpu);
109     struct CpuAsyncInfo *info;
110     uint32_t old, new, cmp = atomic_read(&env->mip);
111 
112     do {
113         old = cmp;
114         new = (old & ~mask) | (value & mask);
115         cmp = atomic_cmpxchg(&env->mip, old, new);
116     } while (old != cmp);
117 
118     info = g_new(struct CpuAsyncInfo, 1);
119     info->new_mip = new;
120 
121     async_run_on_cpu(cs, riscv_cpu_update_mip_irqs_async,
122                      RUN_ON_CPU_HOST_PTR(info));
123 
124     return old;
125 }
126 
127 void riscv_cpu_set_mode(CPURISCVState *env, target_ulong newpriv)
128 {
129     if (newpriv > PRV_M) {
130         g_assert_not_reached();
131     }
132     if (newpriv == PRV_H) {
133         newpriv = PRV_U;
134     }
135     /* tlb_flush is unnecessary as mode is contained in mmu_idx */
136     env->priv = newpriv;
137 }
138 
139 /* get_physical_address - get the physical address for this virtual address
140  *
141  * Do a page table walk to obtain the physical address corresponding to a
142  * virtual address. Returns 0 if the translation was successful
143  *
144  * Adapted from Spike's mmu_t::translate and mmu_t::walk
145  *
146  */
147 static int get_physical_address(CPURISCVState *env, hwaddr *physical,
148                                 int *prot, target_ulong addr,
149                                 int access_type, int mmu_idx)
150 {
151     /* NOTE: the env->pc value visible here will not be
152      * correct, but the value visible to the exception handler
153      * (riscv_cpu_do_interrupt) is correct */
154 
155     int mode = mmu_idx;
156 
157     if (mode == PRV_M && access_type != MMU_INST_FETCH) {
158         if (get_field(env->mstatus, MSTATUS_MPRV)) {
159             mode = get_field(env->mstatus, MSTATUS_MPP);
160         }
161     }
162 
163     if (mode == PRV_M || !riscv_feature(env, RISCV_FEATURE_MMU)) {
164         *physical = addr;
165         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
166         return TRANSLATE_SUCCESS;
167     }
168 
169     *prot = 0;
170 
171     target_ulong base;
172     int levels, ptidxbits, ptesize, vm, sum;
173     int mxr = get_field(env->mstatus, MSTATUS_MXR);
174 
175     if (env->priv_ver >= PRIV_VERSION_1_10_0) {
176         base = get_field(env->satp, SATP_PPN) << PGSHIFT;
177         sum = get_field(env->mstatus, MSTATUS_SUM);
178         vm = get_field(env->satp, SATP_MODE);
179         switch (vm) {
180         case VM_1_10_SV32:
181           levels = 2; ptidxbits = 10; ptesize = 4; break;
182         case VM_1_10_SV39:
183           levels = 3; ptidxbits = 9; ptesize = 8; break;
184         case VM_1_10_SV48:
185           levels = 4; ptidxbits = 9; ptesize = 8; break;
186         case VM_1_10_SV57:
187           levels = 5; ptidxbits = 9; ptesize = 8; break;
188         case VM_1_10_MBARE:
189             *physical = addr;
190             *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
191             return TRANSLATE_SUCCESS;
192         default:
193           g_assert_not_reached();
194         }
195     } else {
196         base = env->sptbr << PGSHIFT;
197         sum = !get_field(env->mstatus, MSTATUS_PUM);
198         vm = get_field(env->mstatus, MSTATUS_VM);
199         switch (vm) {
200         case VM_1_09_SV32:
201           levels = 2; ptidxbits = 10; ptesize = 4; break;
202         case VM_1_09_SV39:
203           levels = 3; ptidxbits = 9; ptesize = 8; break;
204         case VM_1_09_SV48:
205           levels = 4; ptidxbits = 9; ptesize = 8; break;
206         case VM_1_09_MBARE:
207             *physical = addr;
208             *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
209             return TRANSLATE_SUCCESS;
210         default:
211           g_assert_not_reached();
212         }
213     }
214 
215     CPUState *cs = CPU(riscv_env_get_cpu(env));
216     int va_bits = PGSHIFT + levels * ptidxbits;
217     target_ulong mask = (1L << (TARGET_LONG_BITS - (va_bits - 1))) - 1;
218     target_ulong masked_msbs = (addr >> (va_bits - 1)) & mask;
219     if (masked_msbs != 0 && masked_msbs != mask) {
220         return TRANSLATE_FAIL;
221     }
222 
223     int ptshift = (levels - 1) * ptidxbits;
224     int i;
225 
226 #if !TCG_OVERSIZED_GUEST
227 restart:
228 #endif
229     for (i = 0; i < levels; i++, ptshift -= ptidxbits) {
230         target_ulong idx = (addr >> (PGSHIFT + ptshift)) &
231                            ((1 << ptidxbits) - 1);
232 
233         /* check that physical address of PTE is legal */
234         target_ulong pte_addr = base + idx * ptesize;
235 #if defined(TARGET_RISCV32)
236         target_ulong pte = ldl_phys(cs->as, pte_addr);
237 #elif defined(TARGET_RISCV64)
238         target_ulong pte = ldq_phys(cs->as, pte_addr);
239 #endif
240         target_ulong ppn = pte >> PTE_PPN_SHIFT;
241 
242         if (!(pte & PTE_V)) {
243             /* Invalid PTE */
244             return TRANSLATE_FAIL;
245         } else if (!(pte & (PTE_R | PTE_W | PTE_X))) {
246             /* Inner PTE, continue walking */
247             base = ppn << PGSHIFT;
248         } else if ((pte & (PTE_R | PTE_W | PTE_X)) == PTE_W) {
249             /* Reserved leaf PTE flags: PTE_W */
250             return TRANSLATE_FAIL;
251         } else if ((pte & (PTE_R | PTE_W | PTE_X)) == (PTE_W | PTE_X)) {
252             /* Reserved leaf PTE flags: PTE_W + PTE_X */
253             return TRANSLATE_FAIL;
254         } else if ((pte & PTE_U) && ((mode != PRV_U) &&
255                    (!sum || access_type == MMU_INST_FETCH))) {
256             /* User PTE flags when not U mode and mstatus.SUM is not set,
257                or the access type is an instruction fetch */
258             return TRANSLATE_FAIL;
259         } else if (!(pte & PTE_U) && (mode != PRV_S)) {
260             /* Supervisor PTE flags when not S mode */
261             return TRANSLATE_FAIL;
262         } else if (ppn & ((1ULL << ptshift) - 1)) {
263             /* Misaligned PPN */
264             return TRANSLATE_FAIL;
265         } else if (access_type == MMU_DATA_LOAD && !((pte & PTE_R) ||
266                    ((pte & PTE_X) && mxr))) {
267             /* Read access check failed */
268             return TRANSLATE_FAIL;
269         } else if (access_type == MMU_DATA_STORE && !(pte & PTE_W)) {
270             /* Write access check failed */
271             return TRANSLATE_FAIL;
272         } else if (access_type == MMU_INST_FETCH && !(pte & PTE_X)) {
273             /* Fetch access check failed */
274             return TRANSLATE_FAIL;
275         } else {
276             /* if necessary, set accessed and dirty bits. */
277             target_ulong updated_pte = pte | PTE_A |
278                 (access_type == MMU_DATA_STORE ? PTE_D : 0);
279 
280             /* Page table updates need to be atomic with MTTCG enabled */
281             if (updated_pte != pte) {
282                 /*
283                  * - if accessed or dirty bits need updating, and the PTE is
284                  *   in RAM, then we do so atomically with a compare and swap.
285                  * - if the PTE is in IO space or ROM, then it can't be updated
286                  *   and we return TRANSLATE_FAIL.
287                  * - if the PTE changed by the time we went to update it, then
288                  *   it is no longer valid and we must re-walk the page table.
289                  */
290                 MemoryRegion *mr;
291                 hwaddr l = sizeof(target_ulong), addr1;
292                 mr = address_space_translate(cs->as, pte_addr,
293                     &addr1, &l, false, MEMTXATTRS_UNSPECIFIED);
294                 if (memory_region_is_ram(mr)) {
295                     target_ulong *pte_pa =
296                         qemu_map_ram_ptr(mr->ram_block, addr1);
297 #if TCG_OVERSIZED_GUEST
298                     /* MTTCG is not enabled on oversized TCG guests so
299                      * page table updates do not need to be atomic */
300                     *pte_pa = pte = updated_pte;
301 #else
302                     target_ulong old_pte =
303                         atomic_cmpxchg(pte_pa, pte, updated_pte);
304                     if (old_pte != pte) {
305                         goto restart;
306                     } else {
307                         pte = updated_pte;
308                     }
309 #endif
310                 } else {
311                     /* misconfigured PTE in ROM (AD bits are not preset) or
312                      * PTE is in IO space and can't be updated atomically */
313                     return TRANSLATE_FAIL;
314                 }
315             }
316 
317             /* for superpage mappings, make a fake leaf PTE for the TLB's
318                benefit. */
319             target_ulong vpn = addr >> PGSHIFT;
320             *physical = (ppn | (vpn & ((1L << ptshift) - 1))) << PGSHIFT;
321 
322             /* set permissions on the TLB entry */
323             if ((pte & PTE_R) || ((pte & PTE_X) && mxr)) {
324                 *prot |= PAGE_READ;
325             }
326             if ((pte & PTE_X)) {
327                 *prot |= PAGE_EXEC;
328             }
329             /* add write permission on stores or if the page is already dirty,
330                so that we TLB miss on later writes to update the dirty bit */
331             if ((pte & PTE_W) &&
332                     (access_type == MMU_DATA_STORE || (pte & PTE_D))) {
333                 *prot |= PAGE_WRITE;
334             }
335             return TRANSLATE_SUCCESS;
336         }
337     }
338     return TRANSLATE_FAIL;
339 }
340 
341 static void raise_mmu_exception(CPURISCVState *env, target_ulong address,
342                                 MMUAccessType access_type)
343 {
344     CPUState *cs = CPU(riscv_env_get_cpu(env));
345     int page_fault_exceptions =
346         (env->priv_ver >= PRIV_VERSION_1_10_0) &&
347         get_field(env->satp, SATP_MODE) != VM_1_10_MBARE;
348     switch (access_type) {
349     case MMU_INST_FETCH:
350         cs->exception_index = page_fault_exceptions ?
351             RISCV_EXCP_INST_PAGE_FAULT : RISCV_EXCP_INST_ACCESS_FAULT;
352         break;
353     case MMU_DATA_LOAD:
354         cs->exception_index = page_fault_exceptions ?
355             RISCV_EXCP_LOAD_PAGE_FAULT : RISCV_EXCP_LOAD_ACCESS_FAULT;
356         break;
357     case MMU_DATA_STORE:
358         cs->exception_index = page_fault_exceptions ?
359             RISCV_EXCP_STORE_PAGE_FAULT : RISCV_EXCP_STORE_AMO_ACCESS_FAULT;
360         break;
361     default:
362         g_assert_not_reached();
363     }
364     env->badaddr = address;
365 }
366 
367 hwaddr riscv_cpu_get_phys_page_debug(CPUState *cs, vaddr addr)
368 {
369     RISCVCPU *cpu = RISCV_CPU(cs);
370     hwaddr phys_addr;
371     int prot;
372     int mmu_idx = cpu_mmu_index(&cpu->env, false);
373 
374     if (get_physical_address(&cpu->env, &phys_addr, &prot, addr, 0, mmu_idx)) {
375         return -1;
376     }
377     return phys_addr;
378 }
379 
380 void riscv_cpu_do_unaligned_access(CPUState *cs, vaddr addr,
381                                    MMUAccessType access_type, int mmu_idx,
382                                    uintptr_t retaddr)
383 {
384     RISCVCPU *cpu = RISCV_CPU(cs);
385     CPURISCVState *env = &cpu->env;
386     switch (access_type) {
387     case MMU_INST_FETCH:
388         cs->exception_index = RISCV_EXCP_INST_ADDR_MIS;
389         break;
390     case MMU_DATA_LOAD:
391         cs->exception_index = RISCV_EXCP_LOAD_ADDR_MIS;
392         break;
393     case MMU_DATA_STORE:
394         cs->exception_index = RISCV_EXCP_STORE_AMO_ADDR_MIS;
395         break;
396     default:
397         g_assert_not_reached();
398     }
399     env->badaddr = addr;
400     riscv_raise_exception(env, cs->exception_index, retaddr);
401 }
402 #endif
403 
404 bool riscv_cpu_tlb_fill(CPUState *cs, vaddr address, int size,
405                         MMUAccessType access_type, int mmu_idx,
406                         bool probe, uintptr_t retaddr)
407 {
408 #ifndef CONFIG_USER_ONLY
409     RISCVCPU *cpu = RISCV_CPU(cs);
410     CPURISCVState *env = &cpu->env;
411     hwaddr pa = 0;
412     int prot;
413     int ret = TRANSLATE_FAIL;
414 
415     qemu_log_mask(CPU_LOG_MMU, "%s ad %" VADDR_PRIx " rw %d mmu_idx %d\n",
416                   __func__, address, access_type, mmu_idx);
417 
418     ret = get_physical_address(env, &pa, &prot, address, access_type, mmu_idx);
419 
420     qemu_log_mask(CPU_LOG_MMU,
421                   "%s address=%" VADDR_PRIx " ret %d physical " TARGET_FMT_plx
422                   " prot %d\n", __func__, address, ret, pa, prot);
423 
424     if (riscv_feature(env, RISCV_FEATURE_PMP) &&
425         !pmp_hart_has_privs(env, pa, TARGET_PAGE_SIZE, 1 << access_type)) {
426         ret = TRANSLATE_FAIL;
427     }
428     if (ret == TRANSLATE_SUCCESS) {
429         tlb_set_page(cs, address & TARGET_PAGE_MASK, pa & TARGET_PAGE_MASK,
430                      prot, mmu_idx, TARGET_PAGE_SIZE);
431         return true;
432     } else if (probe) {
433         return false;
434     } else {
435         raise_mmu_exception(env, address, access_type);
436         riscv_raise_exception(env, cs->exception_index, retaddr);
437     }
438 #else
439     switch (access_type) {
440     case MMU_INST_FETCH:
441         cs->exception_index = RISCV_EXCP_INST_PAGE_FAULT;
442         break;
443     case MMU_DATA_LOAD:
444         cs->exception_index = RISCV_EXCP_LOAD_PAGE_FAULT;
445         break;
446     case MMU_DATA_STORE:
447         cs->exception_index = RISCV_EXCP_STORE_PAGE_FAULT;
448         break;
449     }
450     cpu_loop_exit_restore(cs, retaddr);
451 #endif
452 }
453 
454 /*
455  * Handle Traps
456  *
457  * Adapted from Spike's processor_t::take_trap.
458  *
459  */
460 void riscv_cpu_do_interrupt(CPUState *cs)
461 {
462 #if !defined(CONFIG_USER_ONLY)
463 
464     RISCVCPU *cpu = RISCV_CPU(cs);
465     CPURISCVState *env = &cpu->env;
466 
467     /* cs->exception is 32-bits wide unlike mcause which is XLEN-bits wide
468      * so we mask off the MSB and separate into trap type and cause.
469      */
470     bool async = !!(cs->exception_index & RISCV_EXCP_INT_FLAG);
471     target_ulong cause = cs->exception_index & RISCV_EXCP_INT_MASK;
472     target_ulong deleg = async ? env->mideleg : env->medeleg;
473     target_ulong tval = 0;
474 
475     static const int ecall_cause_map[] = {
476         [PRV_U] = RISCV_EXCP_U_ECALL,
477         [PRV_S] = RISCV_EXCP_S_ECALL,
478         [PRV_H] = RISCV_EXCP_H_ECALL,
479         [PRV_M] = RISCV_EXCP_M_ECALL
480     };
481 
482     if (!async) {
483         /* set tval to badaddr for traps with address information */
484         switch (cause) {
485         case RISCV_EXCP_INST_ADDR_MIS:
486         case RISCV_EXCP_INST_ACCESS_FAULT:
487         case RISCV_EXCP_LOAD_ADDR_MIS:
488         case RISCV_EXCP_STORE_AMO_ADDR_MIS:
489         case RISCV_EXCP_LOAD_ACCESS_FAULT:
490         case RISCV_EXCP_STORE_AMO_ACCESS_FAULT:
491         case RISCV_EXCP_INST_PAGE_FAULT:
492         case RISCV_EXCP_LOAD_PAGE_FAULT:
493         case RISCV_EXCP_STORE_PAGE_FAULT:
494             tval = env->badaddr;
495             break;
496         default:
497             break;
498         }
499         /* ecall is dispatched as one cause so translate based on mode */
500         if (cause == RISCV_EXCP_U_ECALL) {
501             assert(env->priv <= 3);
502             cause = ecall_cause_map[env->priv];
503         }
504     }
505 
506     trace_riscv_trap(env->mhartid, async, cause, env->pc, tval, cause < 16 ?
507         (async ? riscv_intr_names : riscv_excp_names)[cause] : "(unknown)");
508 
509     if (env->priv <= PRV_S &&
510             cause < TARGET_LONG_BITS && ((deleg >> cause) & 1)) {
511         /* handle the trap in S-mode */
512         target_ulong s = env->mstatus;
513         s = set_field(s, MSTATUS_SPIE, env->priv_ver >= PRIV_VERSION_1_10_0 ?
514             get_field(s, MSTATUS_SIE) : get_field(s, MSTATUS_UIE << env->priv));
515         s = set_field(s, MSTATUS_SPP, env->priv);
516         s = set_field(s, MSTATUS_SIE, 0);
517         env->mstatus = s;
518         env->scause = cause | ((target_ulong)async << (TARGET_LONG_BITS - 1));
519         env->sepc = env->pc;
520         env->sbadaddr = tval;
521         env->pc = (env->stvec >> 2 << 2) +
522             ((async && (env->stvec & 3) == 1) ? cause * 4 : 0);
523         riscv_cpu_set_mode(env, PRV_S);
524     } else {
525         /* handle the trap in M-mode */
526         target_ulong s = env->mstatus;
527         s = set_field(s, MSTATUS_MPIE, env->priv_ver >= PRIV_VERSION_1_10_0 ?
528             get_field(s, MSTATUS_MIE) : get_field(s, MSTATUS_UIE << env->priv));
529         s = set_field(s, MSTATUS_MPP, env->priv);
530         s = set_field(s, MSTATUS_MIE, 0);
531         env->mstatus = s;
532         env->mcause = cause | ~(((target_ulong)-1) >> async);
533         env->mepc = env->pc;
534         env->mbadaddr = tval;
535         env->pc = (env->mtvec >> 2 << 2) +
536             ((async && (env->mtvec & 3) == 1) ? cause * 4 : 0);
537         riscv_cpu_set_mode(env, PRV_M);
538     }
539 
540     /* NOTE: it is not necessary to yield load reservations here. It is only
541      * necessary for an SC from "another hart" to cause a load reservation
542      * to be yielded. Refer to the memory consistency model section of the
543      * RISC-V ISA Specification.
544      */
545 
546 #endif
547     cs->exception_index = EXCP_NONE; /* mark handled to qemu */
548 }
549