OSDN Git Service

target/riscv: Set MMU_2STAGE_BIT in riscv_cpu_mmu_index
[qmiga/qemu.git] / target / riscv / cpu_helper.c
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 "internals.h"
25 #include "pmu.h"
26 #include "exec/exec-all.h"
27 #include "instmap.h"
28 #include "tcg/tcg-op.h"
29 #include "trace.h"
30 #include "semihosting/common-semi.h"
31 #include "sysemu/cpu-timers.h"
32 #include "cpu_bits.h"
33 #include "debug.h"
34
35 int riscv_cpu_mmu_index(CPURISCVState *env, bool ifetch)
36 {
37 #ifdef CONFIG_USER_ONLY
38     return 0;
39 #else
40     bool virt = env->virt_enabled;
41     int mode = env->priv;
42
43     /* All priv -> mmu_idx mapping are here */
44     if (!ifetch) {
45         if (mode == PRV_M && get_field(env->mstatus, MSTATUS_MPRV)) {
46             mode = get_field(env->mstatus, MSTATUS_MPP);
47             virt = get_field(env->mstatus, MSTATUS_MPV);
48         }
49         if (mode == PRV_S && get_field(env->mstatus, MSTATUS_SUM)) {
50             mode = MMUIdx_S_SUM;
51         }
52     }
53
54     return mode | (virt ? MMU_2STAGE_BIT : 0);
55 #endif
56 }
57
58 void cpu_get_tb_cpu_state(CPURISCVState *env, target_ulong *pc,
59                           target_ulong *cs_base, uint32_t *pflags)
60 {
61     CPUState *cs = env_cpu(env);
62     RISCVCPU *cpu = RISCV_CPU(cs);
63     RISCVExtStatus fs, vs;
64     uint32_t flags = 0;
65
66     *pc = env->xl == MXL_RV32 ? env->pc & UINT32_MAX : env->pc;
67     *cs_base = 0;
68
69     if (cpu->cfg.ext_zve32f) {
70         /*
71          * If env->vl equals to VLMAX, we can use generic vector operation
72          * expanders (GVEC) to accerlate the vector operations.
73          * However, as LMUL could be a fractional number. The maximum
74          * vector size can be operated might be less than 8 bytes,
75          * which is not supported by GVEC. So we set vl_eq_vlmax flag to true
76          * only when maxsz >= 8 bytes.
77          */
78         uint32_t vlmax = vext_get_vlmax(cpu, env->vtype);
79         uint32_t sew = FIELD_EX64(env->vtype, VTYPE, VSEW);
80         uint32_t maxsz = vlmax << sew;
81         bool vl_eq_vlmax = (env->vstart == 0) && (vlmax == env->vl) &&
82                            (maxsz >= 8);
83         flags = FIELD_DP32(flags, TB_FLAGS, VILL, env->vill);
84         flags = FIELD_DP32(flags, TB_FLAGS, SEW, sew);
85         flags = FIELD_DP32(flags, TB_FLAGS, LMUL,
86                            FIELD_EX64(env->vtype, VTYPE, VLMUL));
87         flags = FIELD_DP32(flags, TB_FLAGS, VL_EQ_VLMAX, vl_eq_vlmax);
88         flags = FIELD_DP32(flags, TB_FLAGS, VTA,
89                            FIELD_EX64(env->vtype, VTYPE, VTA));
90         flags = FIELD_DP32(flags, TB_FLAGS, VMA,
91                            FIELD_EX64(env->vtype, VTYPE, VMA));
92         flags = FIELD_DP32(flags, TB_FLAGS, VSTART_EQ_ZERO, env->vstart == 0);
93     } else {
94         flags = FIELD_DP32(flags, TB_FLAGS, VILL, 1);
95     }
96
97 #ifdef CONFIG_USER_ONLY
98     fs = EXT_STATUS_DIRTY;
99     vs = EXT_STATUS_DIRTY;
100 #else
101     flags = FIELD_DP32(flags, TB_FLAGS, PRIV, env->priv);
102
103     flags |= cpu_mmu_index(env, 0);
104     fs = get_field(env->mstatus, MSTATUS_FS);
105     vs = get_field(env->mstatus, MSTATUS_VS);
106
107     if (env->virt_enabled) {
108         flags = FIELD_DP32(flags, TB_FLAGS, VIRT_ENABLED, 1);
109         /*
110          * Merge DISABLED and !DIRTY states using MIN.
111          * We will set both fields when dirtying.
112          */
113         fs = MIN(fs, get_field(env->mstatus_hs, MSTATUS_FS));
114         vs = MIN(vs, get_field(env->mstatus_hs, MSTATUS_VS));
115     }
116
117     if (cpu->cfg.debug && !icount_enabled()) {
118         flags = FIELD_DP32(flags, TB_FLAGS, ITRIGGER, env->itrigger_enabled);
119     }
120 #endif
121
122     flags = FIELD_DP32(flags, TB_FLAGS, FS, fs);
123     flags = FIELD_DP32(flags, TB_FLAGS, VS, vs);
124     flags = FIELD_DP32(flags, TB_FLAGS, XL, env->xl);
125     if (env->cur_pmmask < (env->xl == MXL_RV32 ? UINT32_MAX : UINT64_MAX)) {
126         flags = FIELD_DP32(flags, TB_FLAGS, PM_MASK_ENABLED, 1);
127     }
128     if (env->cur_pmbase != 0) {
129         flags = FIELD_DP32(flags, TB_FLAGS, PM_BASE_ENABLED, 1);
130     }
131
132     *pflags = flags;
133 }
134
135 void riscv_cpu_update_mask(CPURISCVState *env)
136 {
137     target_ulong mask = -1, base = 0;
138     /*
139      * TODO: Current RVJ spec does not specify
140      * how the extension interacts with XLEN.
141      */
142 #ifndef CONFIG_USER_ONLY
143     if (riscv_has_ext(env, RVJ)) {
144         switch (env->priv) {
145         case PRV_M:
146             if (env->mmte & M_PM_ENABLE) {
147                 mask = env->mpmmask;
148                 base = env->mpmbase;
149             }
150             break;
151         case PRV_S:
152             if (env->mmte & S_PM_ENABLE) {
153                 mask = env->spmmask;
154                 base = env->spmbase;
155             }
156             break;
157         case PRV_U:
158             if (env->mmte & U_PM_ENABLE) {
159                 mask = env->upmmask;
160                 base = env->upmbase;
161             }
162             break;
163         default:
164             g_assert_not_reached();
165         }
166     }
167 #endif
168     if (env->xl == MXL_RV32) {
169         env->cur_pmmask = mask & UINT32_MAX;
170         env->cur_pmbase = base & UINT32_MAX;
171     } else {
172         env->cur_pmmask = mask;
173         env->cur_pmbase = base;
174     }
175 }
176
177 #ifndef CONFIG_USER_ONLY
178
179 /*
180  * The HS-mode is allowed to configure priority only for the
181  * following VS-mode local interrupts:
182  *
183  * 0  (Reserved interrupt, reads as zero)
184  * 1  Supervisor software interrupt
185  * 4  (Reserved interrupt, reads as zero)
186  * 5  Supervisor timer interrupt
187  * 8  (Reserved interrupt, reads as zero)
188  * 13 (Reserved interrupt)
189  * 14 "
190  * 15 "
191  * 16 "
192  * 17 "
193  * 18 "
194  * 19 "
195  * 20 "
196  * 21 "
197  * 22 "
198  * 23 "
199  */
200
201 static const int hviprio_index2irq[] = {
202     0, 1, 4, 5, 8, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 };
203 static const int hviprio_index2rdzero[] = {
204     1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
205
206 int riscv_cpu_hviprio_index2irq(int index, int *out_irq, int *out_rdzero)
207 {
208     if (index < 0 || ARRAY_SIZE(hviprio_index2irq) <= index) {
209         return -EINVAL;
210     }
211
212     if (out_irq) {
213         *out_irq = hviprio_index2irq[index];
214     }
215
216     if (out_rdzero) {
217         *out_rdzero = hviprio_index2rdzero[index];
218     }
219
220     return 0;
221 }
222
223 /*
224  * Default priorities of local interrupts are defined in the
225  * RISC-V Advanced Interrupt Architecture specification.
226  *
227  * ----------------------------------------------------------------
228  *  Default  |
229  *  Priority | Major Interrupt Numbers
230  * ----------------------------------------------------------------
231  *  Highest  | 47, 23, 46, 45, 22, 44,
232  *           | 43, 21, 42, 41, 20, 40
233  *           |
234  *           | 11 (0b),  3 (03),  7 (07)
235  *           |  9 (09),  1 (01),  5 (05)
236  *           | 12 (0c)
237  *           | 10 (0a),  2 (02),  6 (06)
238  *           |
239  *           | 39, 19, 38, 37, 18, 36,
240  *  Lowest   | 35, 17, 34, 33, 16, 32
241  * ----------------------------------------------------------------
242  */
243 static const uint8_t default_iprio[64] = {
244     /* Custom interrupts 48 to 63 */
245     [63] = IPRIO_MMAXIPRIO,
246     [62] = IPRIO_MMAXIPRIO,
247     [61] = IPRIO_MMAXIPRIO,
248     [60] = IPRIO_MMAXIPRIO,
249     [59] = IPRIO_MMAXIPRIO,
250     [58] = IPRIO_MMAXIPRIO,
251     [57] = IPRIO_MMAXIPRIO,
252     [56] = IPRIO_MMAXIPRIO,
253     [55] = IPRIO_MMAXIPRIO,
254     [54] = IPRIO_MMAXIPRIO,
255     [53] = IPRIO_MMAXIPRIO,
256     [52] = IPRIO_MMAXIPRIO,
257     [51] = IPRIO_MMAXIPRIO,
258     [50] = IPRIO_MMAXIPRIO,
259     [49] = IPRIO_MMAXIPRIO,
260     [48] = IPRIO_MMAXIPRIO,
261
262     /* Custom interrupts 24 to 31 */
263     [31] = IPRIO_MMAXIPRIO,
264     [30] = IPRIO_MMAXIPRIO,
265     [29] = IPRIO_MMAXIPRIO,
266     [28] = IPRIO_MMAXIPRIO,
267     [27] = IPRIO_MMAXIPRIO,
268     [26] = IPRIO_MMAXIPRIO,
269     [25] = IPRIO_MMAXIPRIO,
270     [24] = IPRIO_MMAXIPRIO,
271
272     [47] = IPRIO_DEFAULT_UPPER,
273     [23] = IPRIO_DEFAULT_UPPER + 1,
274     [46] = IPRIO_DEFAULT_UPPER + 2,
275     [45] = IPRIO_DEFAULT_UPPER + 3,
276     [22] = IPRIO_DEFAULT_UPPER + 4,
277     [44] = IPRIO_DEFAULT_UPPER + 5,
278
279     [43] = IPRIO_DEFAULT_UPPER + 6,
280     [21] = IPRIO_DEFAULT_UPPER + 7,
281     [42] = IPRIO_DEFAULT_UPPER + 8,
282     [41] = IPRIO_DEFAULT_UPPER + 9,
283     [20] = IPRIO_DEFAULT_UPPER + 10,
284     [40] = IPRIO_DEFAULT_UPPER + 11,
285
286     [11] = IPRIO_DEFAULT_M,
287     [3]  = IPRIO_DEFAULT_M + 1,
288     [7]  = IPRIO_DEFAULT_M + 2,
289
290     [9]  = IPRIO_DEFAULT_S,
291     [1]  = IPRIO_DEFAULT_S + 1,
292     [5]  = IPRIO_DEFAULT_S + 2,
293
294     [12] = IPRIO_DEFAULT_SGEXT,
295
296     [10] = IPRIO_DEFAULT_VS,
297     [2]  = IPRIO_DEFAULT_VS + 1,
298     [6]  = IPRIO_DEFAULT_VS + 2,
299
300     [39] = IPRIO_DEFAULT_LOWER,
301     [19] = IPRIO_DEFAULT_LOWER + 1,
302     [38] = IPRIO_DEFAULT_LOWER + 2,
303     [37] = IPRIO_DEFAULT_LOWER + 3,
304     [18] = IPRIO_DEFAULT_LOWER + 4,
305     [36] = IPRIO_DEFAULT_LOWER + 5,
306
307     [35] = IPRIO_DEFAULT_LOWER + 6,
308     [17] = IPRIO_DEFAULT_LOWER + 7,
309     [34] = IPRIO_DEFAULT_LOWER + 8,
310     [33] = IPRIO_DEFAULT_LOWER + 9,
311     [16] = IPRIO_DEFAULT_LOWER + 10,
312     [32] = IPRIO_DEFAULT_LOWER + 11,
313 };
314
315 uint8_t riscv_cpu_default_priority(int irq)
316 {
317     if (irq < 0 || irq > 63) {
318         return IPRIO_MMAXIPRIO;
319     }
320
321     return default_iprio[irq] ? default_iprio[irq] : IPRIO_MMAXIPRIO;
322 };
323
324 static int riscv_cpu_pending_to_irq(CPURISCVState *env,
325                                     int extirq, unsigned int extirq_def_prio,
326                                     uint64_t pending, uint8_t *iprio)
327 {
328     int irq, best_irq = RISCV_EXCP_NONE;
329     unsigned int prio, best_prio = UINT_MAX;
330
331     if (!pending) {
332         return RISCV_EXCP_NONE;
333     }
334
335     irq = ctz64(pending);
336     if (!((extirq == IRQ_M_EXT) ? riscv_cpu_cfg(env)->ext_smaia :
337                                   riscv_cpu_cfg(env)->ext_ssaia)) {
338         return irq;
339     }
340
341     pending = pending >> irq;
342     while (pending) {
343         prio = iprio[irq];
344         if (!prio) {
345             if (irq == extirq) {
346                 prio = extirq_def_prio;
347             } else {
348                 prio = (riscv_cpu_default_priority(irq) < extirq_def_prio) ?
349                        1 : IPRIO_MMAXIPRIO;
350             }
351         }
352         if ((pending & 0x1) && (prio <= best_prio)) {
353             best_irq = irq;
354             best_prio = prio;
355         }
356         irq++;
357         pending = pending >> 1;
358     }
359
360     return best_irq;
361 }
362
363 uint64_t riscv_cpu_all_pending(CPURISCVState *env)
364 {
365     uint32_t gein = get_field(env->hstatus, HSTATUS_VGEIN);
366     uint64_t vsgein = (env->hgeip & (1ULL << gein)) ? MIP_VSEIP : 0;
367     uint64_t vstip = (env->vstime_irq) ? MIP_VSTIP : 0;
368
369     return (env->mip | vsgein | vstip) & env->mie;
370 }
371
372 int riscv_cpu_mirq_pending(CPURISCVState *env)
373 {
374     uint64_t irqs = riscv_cpu_all_pending(env) & ~env->mideleg &
375                     ~(MIP_SGEIP | MIP_VSSIP | MIP_VSTIP | MIP_VSEIP);
376
377     return riscv_cpu_pending_to_irq(env, IRQ_M_EXT, IPRIO_DEFAULT_M,
378                                     irqs, env->miprio);
379 }
380
381 int riscv_cpu_sirq_pending(CPURISCVState *env)
382 {
383     uint64_t irqs = riscv_cpu_all_pending(env) & env->mideleg &
384                     ~(MIP_VSSIP | MIP_VSTIP | MIP_VSEIP);
385
386     return riscv_cpu_pending_to_irq(env, IRQ_S_EXT, IPRIO_DEFAULT_S,
387                                     irqs, env->siprio);
388 }
389
390 int riscv_cpu_vsirq_pending(CPURISCVState *env)
391 {
392     uint64_t irqs = riscv_cpu_all_pending(env) & env->mideleg &
393                     (MIP_VSSIP | MIP_VSTIP | MIP_VSEIP);
394
395     return riscv_cpu_pending_to_irq(env, IRQ_S_EXT, IPRIO_DEFAULT_S,
396                                     irqs >> 1, env->hviprio);
397 }
398
399 static int riscv_cpu_local_irq_pending(CPURISCVState *env)
400 {
401     int virq;
402     uint64_t irqs, pending, mie, hsie, vsie;
403
404     /* Determine interrupt enable state of all privilege modes */
405     if (env->virt_enabled) {
406         mie = 1;
407         hsie = 1;
408         vsie = (env->priv < PRV_S) ||
409                (env->priv == PRV_S && get_field(env->mstatus, MSTATUS_SIE));
410     } else {
411         mie = (env->priv < PRV_M) ||
412               (env->priv == PRV_M && get_field(env->mstatus, MSTATUS_MIE));
413         hsie = (env->priv < PRV_S) ||
414                (env->priv == PRV_S && get_field(env->mstatus, MSTATUS_SIE));
415         vsie = 0;
416     }
417
418     /* Determine all pending interrupts */
419     pending = riscv_cpu_all_pending(env);
420
421     /* Check M-mode interrupts */
422     irqs = pending & ~env->mideleg & -mie;
423     if (irqs) {
424         return riscv_cpu_pending_to_irq(env, IRQ_M_EXT, IPRIO_DEFAULT_M,
425                                         irqs, env->miprio);
426     }
427
428     /* Check HS-mode interrupts */
429     irqs = pending & env->mideleg & ~env->hideleg & -hsie;
430     if (irqs) {
431         return riscv_cpu_pending_to_irq(env, IRQ_S_EXT, IPRIO_DEFAULT_S,
432                                         irqs, env->siprio);
433     }
434
435     /* Check VS-mode interrupts */
436     irqs = pending & env->mideleg & env->hideleg & -vsie;
437     if (irqs) {
438         virq = riscv_cpu_pending_to_irq(env, IRQ_S_EXT, IPRIO_DEFAULT_S,
439                                         irqs >> 1, env->hviprio);
440         return (virq <= 0) ? virq : virq + 1;
441     }
442
443     /* Indicate no pending interrupt */
444     return RISCV_EXCP_NONE;
445 }
446
447 bool riscv_cpu_exec_interrupt(CPUState *cs, int interrupt_request)
448 {
449     if (interrupt_request & CPU_INTERRUPT_HARD) {
450         RISCVCPU *cpu = RISCV_CPU(cs);
451         CPURISCVState *env = &cpu->env;
452         int interruptno = riscv_cpu_local_irq_pending(env);
453         if (interruptno >= 0) {
454             cs->exception_index = RISCV_EXCP_INT_FLAG | interruptno;
455             riscv_cpu_do_interrupt(cs);
456             return true;
457         }
458     }
459     return false;
460 }
461
462 /* Return true is floating point support is currently enabled */
463 bool riscv_cpu_fp_enabled(CPURISCVState *env)
464 {
465     if (env->mstatus & MSTATUS_FS) {
466         if (env->virt_enabled && !(env->mstatus_hs & MSTATUS_FS)) {
467             return false;
468         }
469         return true;
470     }
471
472     return false;
473 }
474
475 /* Return true is vector support is currently enabled */
476 bool riscv_cpu_vector_enabled(CPURISCVState *env)
477 {
478     if (env->mstatus & MSTATUS_VS) {
479         if (env->virt_enabled && !(env->mstatus_hs & MSTATUS_VS)) {
480             return false;
481         }
482         return true;
483     }
484
485     return false;
486 }
487
488 void riscv_cpu_swap_hypervisor_regs(CPURISCVState *env)
489 {
490     uint64_t mstatus_mask = MSTATUS_MXR | MSTATUS_SUM |
491                             MSTATUS_SPP | MSTATUS_SPIE | MSTATUS_SIE |
492                             MSTATUS64_UXL | MSTATUS_VS;
493
494     if (riscv_has_ext(env, RVF)) {
495         mstatus_mask |= MSTATUS_FS;
496     }
497     bool current_virt = env->virt_enabled;
498
499     g_assert(riscv_has_ext(env, RVH));
500
501     if (current_virt) {
502         /* Current V=1 and we are about to change to V=0 */
503         env->vsstatus = env->mstatus & mstatus_mask;
504         env->mstatus &= ~mstatus_mask;
505         env->mstatus |= env->mstatus_hs;
506
507         env->vstvec = env->stvec;
508         env->stvec = env->stvec_hs;
509
510         env->vsscratch = env->sscratch;
511         env->sscratch = env->sscratch_hs;
512
513         env->vsepc = env->sepc;
514         env->sepc = env->sepc_hs;
515
516         env->vscause = env->scause;
517         env->scause = env->scause_hs;
518
519         env->vstval = env->stval;
520         env->stval = env->stval_hs;
521
522         env->vsatp = env->satp;
523         env->satp = env->satp_hs;
524     } else {
525         /* Current V=0 and we are about to change to V=1 */
526         env->mstatus_hs = env->mstatus & mstatus_mask;
527         env->mstatus &= ~mstatus_mask;
528         env->mstatus |= env->vsstatus;
529
530         env->stvec_hs = env->stvec;
531         env->stvec = env->vstvec;
532
533         env->sscratch_hs = env->sscratch;
534         env->sscratch = env->vsscratch;
535
536         env->sepc_hs = env->sepc;
537         env->sepc = env->vsepc;
538
539         env->scause_hs = env->scause;
540         env->scause = env->vscause;
541
542         env->stval_hs = env->stval;
543         env->stval = env->vstval;
544
545         env->satp_hs = env->satp;
546         env->satp = env->vsatp;
547     }
548 }
549
550 target_ulong riscv_cpu_get_geilen(CPURISCVState *env)
551 {
552     if (!riscv_has_ext(env, RVH)) {
553         return 0;
554     }
555
556     return env->geilen;
557 }
558
559 void riscv_cpu_set_geilen(CPURISCVState *env, target_ulong geilen)
560 {
561     if (!riscv_has_ext(env, RVH)) {
562         return;
563     }
564
565     if (geilen > (TARGET_LONG_BITS - 1)) {
566         return;
567     }
568
569     env->geilen = geilen;
570 }
571
572 /* This function can only be called to set virt when RVH is enabled */
573 void riscv_cpu_set_virt_enabled(CPURISCVState *env, bool enable)
574 {
575     /* Flush the TLB on all virt mode changes. */
576     if (env->virt_enabled != enable) {
577         tlb_flush(env_cpu(env));
578     }
579
580     env->virt_enabled = enable;
581
582     if (enable) {
583         /*
584          * The guest external interrupts from an interrupt controller are
585          * delivered only when the Guest/VM is running (i.e. V=1). This means
586          * any guest external interrupt which is triggered while the Guest/VM
587          * is not running (i.e. V=0) will be missed on QEMU resulting in guest
588          * with sluggish response to serial console input and other I/O events.
589          *
590          * To solve this, we check and inject interrupt after setting V=1.
591          */
592         riscv_cpu_update_mip(env, 0, 0);
593     }
594 }
595
596 int riscv_cpu_claim_interrupts(RISCVCPU *cpu, uint64_t interrupts)
597 {
598     CPURISCVState *env = &cpu->env;
599     if (env->miclaim & interrupts) {
600         return -1;
601     } else {
602         env->miclaim |= interrupts;
603         return 0;
604     }
605 }
606
607 uint64_t riscv_cpu_update_mip(CPURISCVState *env, uint64_t mask,
608                               uint64_t value)
609 {
610     CPUState *cs = env_cpu(env);
611     uint64_t gein, vsgein = 0, vstip = 0, old = env->mip;
612
613     if (env->virt_enabled) {
614         gein = get_field(env->hstatus, HSTATUS_VGEIN);
615         vsgein = (env->hgeip & (1ULL << gein)) ? MIP_VSEIP : 0;
616     }
617
618     vstip = env->vstime_irq ? MIP_VSTIP : 0;
619
620     QEMU_IOTHREAD_LOCK_GUARD();
621
622     env->mip = (env->mip & ~mask) | (value & mask);
623
624     if (env->mip | vsgein | vstip) {
625         cpu_interrupt(cs, CPU_INTERRUPT_HARD);
626     } else {
627         cpu_reset_interrupt(cs, CPU_INTERRUPT_HARD);
628     }
629
630     return old;
631 }
632
633 void riscv_cpu_set_rdtime_fn(CPURISCVState *env, uint64_t (*fn)(void *),
634                              void *arg)
635 {
636     env->rdtime_fn = fn;
637     env->rdtime_fn_arg = arg;
638 }
639
640 void riscv_cpu_set_aia_ireg_rmw_fn(CPURISCVState *env, uint32_t priv,
641                                    int (*rmw_fn)(void *arg,
642                                                  target_ulong reg,
643                                                  target_ulong *val,
644                                                  target_ulong new_val,
645                                                  target_ulong write_mask),
646                                    void *rmw_fn_arg)
647 {
648     if (priv <= PRV_M) {
649         env->aia_ireg_rmw_fn[priv] = rmw_fn;
650         env->aia_ireg_rmw_fn_arg[priv] = rmw_fn_arg;
651     }
652 }
653
654 void riscv_cpu_set_mode(CPURISCVState *env, target_ulong newpriv)
655 {
656     g_assert(newpriv <= PRV_M && newpriv != PRV_RESERVED);
657
658     if (icount_enabled() && newpriv != env->priv) {
659         riscv_itrigger_update_priv(env);
660     }
661     /* tlb_flush is unnecessary as mode is contained in mmu_idx */
662     env->priv = newpriv;
663     env->xl = cpu_recompute_xl(env);
664     riscv_cpu_update_mask(env);
665
666     /*
667      * Clear the load reservation - otherwise a reservation placed in one
668      * context/process can be used by another, resulting in an SC succeeding
669      * incorrectly. Version 2.2 of the ISA specification explicitly requires
670      * this behaviour, while later revisions say that the kernel "should" use
671      * an SC instruction to force the yielding of a load reservation on a
672      * preemptive context switch. As a result, do both.
673      */
674     env->load_res = -1;
675 }
676
677 /*
678  * get_physical_address_pmp - check PMP permission for this physical address
679  *
680  * Match the PMP region and check permission for this physical address and it's
681  * TLB page. Returns 0 if the permission checking was successful
682  *
683  * @env: CPURISCVState
684  * @prot: The returned protection attributes
685  * @tlb_size: TLB page size containing addr. It could be modified after PMP
686  *            permission checking. NULL if not set TLB page for addr.
687  * @addr: The physical address to be checked permission
688  * @access_type: The type of MMU access
689  * @mode: Indicates current privilege level.
690  */
691 static int get_physical_address_pmp(CPURISCVState *env, int *prot,
692                                     target_ulong *tlb_size, hwaddr addr,
693                                     int size, MMUAccessType access_type,
694                                     int mode)
695 {
696     pmp_priv_t pmp_priv;
697     int pmp_index = -1;
698
699     if (!riscv_cpu_cfg(env)->pmp) {
700         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
701         return TRANSLATE_SUCCESS;
702     }
703
704     pmp_index = pmp_hart_has_privs(env, addr, size, 1 << access_type,
705                                    &pmp_priv, mode);
706     if (pmp_index < 0) {
707         *prot = 0;
708         return TRANSLATE_PMP_FAIL;
709     }
710
711     *prot = pmp_priv_to_page_prot(pmp_priv);
712     if ((tlb_size != NULL) && pmp_index != MAX_RISCV_PMPS) {
713         target_ulong tlb_sa = addr & ~(TARGET_PAGE_SIZE - 1);
714         target_ulong tlb_ea = tlb_sa + TARGET_PAGE_SIZE - 1;
715
716         *tlb_size = pmp_get_tlb_size(env, pmp_index, tlb_sa, tlb_ea);
717     }
718
719     return TRANSLATE_SUCCESS;
720 }
721
722 /*
723  * get_physical_address - get the physical address for this virtual address
724  *
725  * Do a page table walk to obtain the physical address corresponding to a
726  * virtual address. Returns 0 if the translation was successful
727  *
728  * Adapted from Spike's mmu_t::translate and mmu_t::walk
729  *
730  * @env: CPURISCVState
731  * @physical: This will be set to the calculated physical address
732  * @prot: The returned protection attributes
733  * @addr: The virtual address or guest physical address to be translated
734  * @fault_pte_addr: If not NULL, this will be set to fault pte address
735  *                  when a error occurs on pte address translation.
736  *                  This will already be shifted to match htval.
737  * @access_type: The type of MMU access
738  * @mmu_idx: Indicates current privilege level
739  * @first_stage: Are we in first stage translation?
740  *               Second stage is used for hypervisor guest translation
741  * @two_stage: Are we going to perform two stage translation
742  * @is_debug: Is this access from a debugger or the monitor?
743  */
744 static int get_physical_address(CPURISCVState *env, hwaddr *physical,
745                                 int *prot, vaddr addr,
746                                 target_ulong *fault_pte_addr,
747                                 int access_type, int mmu_idx,
748                                 bool first_stage, bool two_stage,
749                                 bool is_debug)
750 {
751     /*
752      * NOTE: the env->pc value visible here will not be
753      * correct, but the value visible to the exception handler
754      * (riscv_cpu_do_interrupt) is correct
755      */
756     MemTxResult res;
757     MemTxAttrs attrs = MEMTXATTRS_UNSPECIFIED;
758     int mode = mmuidx_priv(mmu_idx);
759     bool use_background = false;
760     hwaddr ppn;
761     int napot_bits = 0;
762     target_ulong napot_mask;
763
764     /*
765      * Check if we should use the background registers for the two
766      * stage translation. We don't need to check if we actually need
767      * two stage translation as that happened before this function
768      * was called. Background registers will be used if the guest has
769      * forced a two stage translation to be on (in HS or M mode).
770      */
771     if (!env->virt_enabled && two_stage) {
772         use_background = true;
773     }
774
775     if (first_stage == false) {
776         /*
777          * We are in stage 2 translation, this is similar to stage 1.
778          * Stage 2 is always taken as U-mode
779          */
780         mode = PRV_U;
781     }
782
783     if (mode == PRV_M || !riscv_cpu_cfg(env)->mmu) {
784         *physical = addr;
785         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
786         return TRANSLATE_SUCCESS;
787     }
788
789     *prot = 0;
790
791     hwaddr base;
792     int levels, ptidxbits, ptesize, vm, sum, mxr, widened;
793
794     if (first_stage == true) {
795         mxr = get_field(env->mstatus, MSTATUS_MXR);
796     } else {
797         mxr = get_field(env->vsstatus, MSTATUS_MXR);
798     }
799
800     if (first_stage == true) {
801         if (use_background) {
802             if (riscv_cpu_mxl(env) == MXL_RV32) {
803                 base = (hwaddr)get_field(env->vsatp, SATP32_PPN) << PGSHIFT;
804                 vm = get_field(env->vsatp, SATP32_MODE);
805             } else {
806                 base = (hwaddr)get_field(env->vsatp, SATP64_PPN) << PGSHIFT;
807                 vm = get_field(env->vsatp, SATP64_MODE);
808             }
809         } else {
810             if (riscv_cpu_mxl(env) == MXL_RV32) {
811                 base = (hwaddr)get_field(env->satp, SATP32_PPN) << PGSHIFT;
812                 vm = get_field(env->satp, SATP32_MODE);
813             } else {
814                 base = (hwaddr)get_field(env->satp, SATP64_PPN) << PGSHIFT;
815                 vm = get_field(env->satp, SATP64_MODE);
816             }
817         }
818         widened = 0;
819     } else {
820         if (riscv_cpu_mxl(env) == MXL_RV32) {
821             base = (hwaddr)get_field(env->hgatp, SATP32_PPN) << PGSHIFT;
822             vm = get_field(env->hgatp, SATP32_MODE);
823         } else {
824             base = (hwaddr)get_field(env->hgatp, SATP64_PPN) << PGSHIFT;
825             vm = get_field(env->hgatp, SATP64_MODE);
826         }
827         widened = 2;
828     }
829     /* status.SUM will be ignored if execute on background */
830     sum = mmuidx_sum(mmu_idx) || use_background || is_debug;
831     switch (vm) {
832     case VM_1_10_SV32:
833       levels = 2; ptidxbits = 10; ptesize = 4; break;
834     case VM_1_10_SV39:
835       levels = 3; ptidxbits = 9; ptesize = 8; break;
836     case VM_1_10_SV48:
837       levels = 4; ptidxbits = 9; ptesize = 8; break;
838     case VM_1_10_SV57:
839       levels = 5; ptidxbits = 9; ptesize = 8; break;
840     case VM_1_10_MBARE:
841         *physical = addr;
842         *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
843         return TRANSLATE_SUCCESS;
844     default:
845       g_assert_not_reached();
846     }
847
848     CPUState *cs = env_cpu(env);
849     int va_bits = PGSHIFT + levels * ptidxbits + widened;
850     target_ulong mask, masked_msbs;
851
852     if (TARGET_LONG_BITS > (va_bits - 1)) {
853         mask = (1L << (TARGET_LONG_BITS - (va_bits - 1))) - 1;
854     } else {
855         mask = 0;
856     }
857     masked_msbs = (addr >> (va_bits - 1)) & mask;
858
859     if (masked_msbs != 0 && masked_msbs != mask) {
860         return TRANSLATE_FAIL;
861     }
862
863     int ptshift = (levels - 1) * ptidxbits;
864     int i;
865
866 #if !TCG_OVERSIZED_GUEST
867 restart:
868 #endif
869     for (i = 0; i < levels; i++, ptshift -= ptidxbits) {
870         target_ulong idx;
871         if (i == 0) {
872             idx = (addr >> (PGSHIFT + ptshift)) &
873                            ((1 << (ptidxbits + widened)) - 1);
874         } else {
875             idx = (addr >> (PGSHIFT + ptshift)) &
876                            ((1 << ptidxbits) - 1);
877         }
878
879         /* check that physical address of PTE is legal */
880         hwaddr pte_addr;
881
882         if (two_stage && first_stage) {
883             int vbase_prot;
884             hwaddr vbase;
885
886             /* Do the second stage translation on the base PTE address. */
887             int vbase_ret = get_physical_address(env, &vbase, &vbase_prot,
888                                                  base, NULL, MMU_DATA_LOAD,
889                                                  mmu_idx, false, true,
890                                                  is_debug);
891
892             if (vbase_ret != TRANSLATE_SUCCESS) {
893                 if (fault_pte_addr) {
894                     *fault_pte_addr = (base + idx * ptesize) >> 2;
895                 }
896                 return TRANSLATE_G_STAGE_FAIL;
897             }
898
899             pte_addr = vbase + idx * ptesize;
900         } else {
901             pte_addr = base + idx * ptesize;
902         }
903
904         int pmp_prot;
905         int pmp_ret = get_physical_address_pmp(env, &pmp_prot, NULL, pte_addr,
906                                                sizeof(target_ulong),
907                                                MMU_DATA_LOAD, PRV_S);
908         if (pmp_ret != TRANSLATE_SUCCESS) {
909             return TRANSLATE_PMP_FAIL;
910         }
911
912         target_ulong pte;
913         if (riscv_cpu_mxl(env) == MXL_RV32) {
914             pte = address_space_ldl(cs->as, pte_addr, attrs, &res);
915         } else {
916             pte = address_space_ldq(cs->as, pte_addr, attrs, &res);
917         }
918
919         if (res != MEMTX_OK) {
920             return TRANSLATE_FAIL;
921         }
922
923         bool pbmte = env->menvcfg & MENVCFG_PBMTE;
924         bool hade = env->menvcfg & MENVCFG_HADE;
925
926         if (first_stage && two_stage && env->virt_enabled) {
927             pbmte = pbmte && (env->henvcfg & HENVCFG_PBMTE);
928             hade = hade && (env->henvcfg & HENVCFG_HADE);
929         }
930
931         if (riscv_cpu_sxl(env) == MXL_RV32) {
932             ppn = pte >> PTE_PPN_SHIFT;
933         } else if (pbmte || riscv_cpu_cfg(env)->ext_svnapot) {
934             ppn = (pte & (target_ulong)PTE_PPN_MASK) >> PTE_PPN_SHIFT;
935         } else {
936             ppn = pte >> PTE_PPN_SHIFT;
937             if ((pte & ~(target_ulong)PTE_PPN_MASK) >> PTE_PPN_SHIFT) {
938                 return TRANSLATE_FAIL;
939             }
940         }
941
942         if (!(pte & PTE_V)) {
943             /* Invalid PTE */
944             return TRANSLATE_FAIL;
945         } else if (!pbmte && (pte & PTE_PBMT)) {
946             return TRANSLATE_FAIL;
947         } else if (!(pte & (PTE_R | PTE_W | PTE_X))) {
948             /* Inner PTE, continue walking */
949             if (pte & (PTE_D | PTE_A | PTE_U | PTE_ATTR)) {
950                 return TRANSLATE_FAIL;
951             }
952             base = ppn << PGSHIFT;
953         } else if ((pte & (PTE_R | PTE_W | PTE_X)) == PTE_W) {
954             /* Reserved leaf PTE flags: PTE_W */
955             return TRANSLATE_FAIL;
956         } else if ((pte & (PTE_R | PTE_W | PTE_X)) == (PTE_W | PTE_X)) {
957             /* Reserved leaf PTE flags: PTE_W + PTE_X */
958             return TRANSLATE_FAIL;
959         } else if ((pte & PTE_U) && ((mode != PRV_U) &&
960                    (!sum || access_type == MMU_INST_FETCH))) {
961             /* User PTE flags when not U mode and mstatus.SUM is not set,
962                or the access type is an instruction fetch */
963             return TRANSLATE_FAIL;
964         } else if (!(pte & PTE_U) && (mode != PRV_S)) {
965             /* Supervisor PTE flags when not S mode */
966             return TRANSLATE_FAIL;
967         } else if (ppn & ((1ULL << ptshift) - 1)) {
968             /* Misaligned PPN */
969             return TRANSLATE_FAIL;
970         } else if (access_type == MMU_DATA_LOAD && !((pte & PTE_R) ||
971                    ((pte & PTE_X) && mxr))) {
972             /* Read access check failed */
973             return TRANSLATE_FAIL;
974         } else if (access_type == MMU_DATA_STORE && !(pte & PTE_W)) {
975             /* Write access check failed */
976             return TRANSLATE_FAIL;
977         } else if (access_type == MMU_INST_FETCH && !(pte & PTE_X)) {
978             /* Fetch access check failed */
979             return TRANSLATE_FAIL;
980         } else {
981             /* if necessary, set accessed and dirty bits. */
982             target_ulong updated_pte = pte | PTE_A |
983                 (access_type == MMU_DATA_STORE ? PTE_D : 0);
984
985             /* Page table updates need to be atomic with MTTCG enabled */
986             if (updated_pte != pte) {
987                 if (!hade) {
988                     return TRANSLATE_FAIL;
989                 }
990
991                 /*
992                  * - if accessed or dirty bits need updating, and the PTE is
993                  *   in RAM, then we do so atomically with a compare and swap.
994                  * - if the PTE is in IO space or ROM, then it can't be updated
995                  *   and we return TRANSLATE_FAIL.
996                  * - if the PTE changed by the time we went to update it, then
997                  *   it is no longer valid and we must re-walk the page table.
998                  */
999                 MemoryRegion *mr;
1000                 hwaddr l = sizeof(target_ulong), addr1;
1001                 mr = address_space_translate(cs->as, pte_addr, &addr1, &l,
1002                                              false, MEMTXATTRS_UNSPECIFIED);
1003                 if (memory_region_is_ram(mr)) {
1004                     target_ulong *pte_pa =
1005                         qemu_map_ram_ptr(mr->ram_block, addr1);
1006 #if TCG_OVERSIZED_GUEST
1007                     /*
1008                      * MTTCG is not enabled on oversized TCG guests so
1009                      * page table updates do not need to be atomic
1010                      */
1011                     *pte_pa = pte = updated_pte;
1012 #else
1013                     target_ulong old_pte =
1014                         qatomic_cmpxchg(pte_pa, pte, updated_pte);
1015                     if (old_pte != pte) {
1016                         goto restart;
1017                     } else {
1018                         pte = updated_pte;
1019                     }
1020 #endif
1021                 } else {
1022                     /*
1023                      * misconfigured PTE in ROM (AD bits are not preset) or
1024                      * PTE is in IO space and can't be updated atomically
1025                      */
1026                     return TRANSLATE_FAIL;
1027                 }
1028             }
1029
1030             /*
1031              * for superpage mappings, make a fake leaf PTE for the TLB's
1032              * benefit.
1033              */
1034             target_ulong vpn = addr >> PGSHIFT;
1035
1036             if (riscv_cpu_cfg(env)->ext_svnapot && (pte & PTE_N)) {
1037                 napot_bits = ctzl(ppn) + 1;
1038                 if ((i != (levels - 1)) || (napot_bits != 4)) {
1039                     return TRANSLATE_FAIL;
1040                 }
1041             }
1042
1043             napot_mask = (1 << napot_bits) - 1;
1044             *physical = (((ppn & ~napot_mask) | (vpn & napot_mask) |
1045                           (vpn & (((target_ulong)1 << ptshift) - 1))
1046                          ) << PGSHIFT) | (addr & ~TARGET_PAGE_MASK);
1047
1048             /* set permissions on the TLB entry */
1049             if ((pte & PTE_R) || ((pte & PTE_X) && mxr)) {
1050                 *prot |= PAGE_READ;
1051             }
1052             if (pte & PTE_X) {
1053                 *prot |= PAGE_EXEC;
1054             }
1055             /*
1056              * add write permission on stores or if the page is already dirty,
1057              * so that we TLB miss on later writes to update the dirty bit
1058              */
1059             if ((pte & PTE_W) &&
1060                 (access_type == MMU_DATA_STORE || (pte & PTE_D))) {
1061                 *prot |= PAGE_WRITE;
1062             }
1063             return TRANSLATE_SUCCESS;
1064         }
1065     }
1066     return TRANSLATE_FAIL;
1067 }
1068
1069 static void raise_mmu_exception(CPURISCVState *env, target_ulong address,
1070                                 MMUAccessType access_type, bool pmp_violation,
1071                                 bool first_stage, bool two_stage,
1072                                 bool two_stage_indirect)
1073 {
1074     CPUState *cs = env_cpu(env);
1075     int page_fault_exceptions, vm;
1076     uint64_t stap_mode;
1077
1078     if (riscv_cpu_mxl(env) == MXL_RV32) {
1079         stap_mode = SATP32_MODE;
1080     } else {
1081         stap_mode = SATP64_MODE;
1082     }
1083
1084     if (first_stage) {
1085         vm = get_field(env->satp, stap_mode);
1086     } else {
1087         vm = get_field(env->hgatp, stap_mode);
1088     }
1089
1090     page_fault_exceptions = vm != VM_1_10_MBARE && !pmp_violation;
1091
1092     switch (access_type) {
1093     case MMU_INST_FETCH:
1094         if (env->virt_enabled && !first_stage) {
1095             cs->exception_index = RISCV_EXCP_INST_GUEST_PAGE_FAULT;
1096         } else {
1097             cs->exception_index = page_fault_exceptions ?
1098                 RISCV_EXCP_INST_PAGE_FAULT : RISCV_EXCP_INST_ACCESS_FAULT;
1099         }
1100         break;
1101     case MMU_DATA_LOAD:
1102         if (two_stage && !first_stage) {
1103             cs->exception_index = RISCV_EXCP_LOAD_GUEST_ACCESS_FAULT;
1104         } else {
1105             cs->exception_index = page_fault_exceptions ?
1106                 RISCV_EXCP_LOAD_PAGE_FAULT : RISCV_EXCP_LOAD_ACCESS_FAULT;
1107         }
1108         break;
1109     case MMU_DATA_STORE:
1110         if (two_stage && !first_stage) {
1111             cs->exception_index = RISCV_EXCP_STORE_GUEST_AMO_ACCESS_FAULT;
1112         } else {
1113             cs->exception_index = page_fault_exceptions ?
1114                 RISCV_EXCP_STORE_PAGE_FAULT :
1115                 RISCV_EXCP_STORE_AMO_ACCESS_FAULT;
1116         }
1117         break;
1118     default:
1119         g_assert_not_reached();
1120     }
1121     env->badaddr = address;
1122     env->two_stage_lookup = two_stage;
1123     env->two_stage_indirect_lookup = two_stage_indirect;
1124 }
1125
1126 hwaddr riscv_cpu_get_phys_page_debug(CPUState *cs, vaddr addr)
1127 {
1128     RISCVCPU *cpu = RISCV_CPU(cs);
1129     CPURISCVState *env = &cpu->env;
1130     hwaddr phys_addr;
1131     int prot;
1132     int mmu_idx = cpu_mmu_index(&cpu->env, false);
1133
1134     if (get_physical_address(env, &phys_addr, &prot, addr, NULL, 0, mmu_idx,
1135                              true, env->virt_enabled, true)) {
1136         return -1;
1137     }
1138
1139     if (env->virt_enabled) {
1140         if (get_physical_address(env, &phys_addr, &prot, phys_addr, NULL,
1141                                  0, mmu_idx, false, true, true)) {
1142             return -1;
1143         }
1144     }
1145
1146     return phys_addr & TARGET_PAGE_MASK;
1147 }
1148
1149 void riscv_cpu_do_transaction_failed(CPUState *cs, hwaddr physaddr,
1150                                      vaddr addr, unsigned size,
1151                                      MMUAccessType access_type,
1152                                      int mmu_idx, MemTxAttrs attrs,
1153                                      MemTxResult response, uintptr_t retaddr)
1154 {
1155     RISCVCPU *cpu = RISCV_CPU(cs);
1156     CPURISCVState *env = &cpu->env;
1157
1158     if (access_type == MMU_DATA_STORE) {
1159         cs->exception_index = RISCV_EXCP_STORE_AMO_ACCESS_FAULT;
1160     } else if (access_type == MMU_DATA_LOAD) {
1161         cs->exception_index = RISCV_EXCP_LOAD_ACCESS_FAULT;
1162     } else {
1163         cs->exception_index = RISCV_EXCP_INST_ACCESS_FAULT;
1164     }
1165
1166     env->badaddr = addr;
1167     env->two_stage_lookup = mmuidx_2stage(mmu_idx);
1168     env->two_stage_indirect_lookup = false;
1169     cpu_loop_exit_restore(cs, retaddr);
1170 }
1171
1172 void riscv_cpu_do_unaligned_access(CPUState *cs, vaddr addr,
1173                                    MMUAccessType access_type, int mmu_idx,
1174                                    uintptr_t retaddr)
1175 {
1176     RISCVCPU *cpu = RISCV_CPU(cs);
1177     CPURISCVState *env = &cpu->env;
1178     switch (access_type) {
1179     case MMU_INST_FETCH:
1180         cs->exception_index = RISCV_EXCP_INST_ADDR_MIS;
1181         break;
1182     case MMU_DATA_LOAD:
1183         cs->exception_index = RISCV_EXCP_LOAD_ADDR_MIS;
1184         break;
1185     case MMU_DATA_STORE:
1186         cs->exception_index = RISCV_EXCP_STORE_AMO_ADDR_MIS;
1187         break;
1188     default:
1189         g_assert_not_reached();
1190     }
1191     env->badaddr = addr;
1192     env->two_stage_lookup = mmuidx_2stage(mmu_idx);
1193     env->two_stage_indirect_lookup = false;
1194     cpu_loop_exit_restore(cs, retaddr);
1195 }
1196
1197
1198 static void pmu_tlb_fill_incr_ctr(RISCVCPU *cpu, MMUAccessType access_type)
1199 {
1200     enum riscv_pmu_event_idx pmu_event_type;
1201
1202     switch (access_type) {
1203     case MMU_INST_FETCH:
1204         pmu_event_type = RISCV_PMU_EVENT_CACHE_ITLB_PREFETCH_MISS;
1205         break;
1206     case MMU_DATA_LOAD:
1207         pmu_event_type = RISCV_PMU_EVENT_CACHE_DTLB_READ_MISS;
1208         break;
1209     case MMU_DATA_STORE:
1210         pmu_event_type = RISCV_PMU_EVENT_CACHE_DTLB_WRITE_MISS;
1211         break;
1212     default:
1213         return;
1214     }
1215
1216     riscv_pmu_incr_ctr(cpu, pmu_event_type);
1217 }
1218
1219 bool riscv_cpu_tlb_fill(CPUState *cs, vaddr address, int size,
1220                         MMUAccessType access_type, int mmu_idx,
1221                         bool probe, uintptr_t retaddr)
1222 {
1223     RISCVCPU *cpu = RISCV_CPU(cs);
1224     CPURISCVState *env = &cpu->env;
1225     vaddr im_address;
1226     hwaddr pa = 0;
1227     int prot, prot2, prot_pmp;
1228     bool pmp_violation = false;
1229     bool first_stage_error = true;
1230     bool two_stage_lookup = mmuidx_2stage(mmu_idx);
1231     bool two_stage_indirect_error = false;
1232     int ret = TRANSLATE_FAIL;
1233     int mode = mmu_idx;
1234     /* default TLB page size */
1235     target_ulong tlb_size = TARGET_PAGE_SIZE;
1236
1237     env->guest_phys_fault_addr = 0;
1238
1239     qemu_log_mask(CPU_LOG_MMU, "%s ad %" VADDR_PRIx " rw %d mmu_idx %d\n",
1240                   __func__, address, access_type, mmu_idx);
1241
1242     pmu_tlb_fill_incr_ctr(cpu, access_type);
1243     if (two_stage_lookup) {
1244         /* Two stage lookup */
1245         ret = get_physical_address(env, &pa, &prot, address,
1246                                    &env->guest_phys_fault_addr, access_type,
1247                                    mmu_idx, true, true, false);
1248
1249         /*
1250          * A G-stage exception may be triggered during two state lookup.
1251          * And the env->guest_phys_fault_addr has already been set in
1252          * get_physical_address().
1253          */
1254         if (ret == TRANSLATE_G_STAGE_FAIL) {
1255             first_stage_error = false;
1256             two_stage_indirect_error = true;
1257             access_type = MMU_DATA_LOAD;
1258         }
1259
1260         qemu_log_mask(CPU_LOG_MMU,
1261                       "%s 1st-stage address=%" VADDR_PRIx " ret %d physical "
1262                       HWADDR_FMT_plx " prot %d\n",
1263                       __func__, address, ret, pa, prot);
1264
1265         if (ret == TRANSLATE_SUCCESS) {
1266             /* Second stage lookup */
1267             im_address = pa;
1268
1269             ret = get_physical_address(env, &pa, &prot2, im_address, NULL,
1270                                        access_type, mmu_idx, false, true,
1271                                        false);
1272
1273             qemu_log_mask(CPU_LOG_MMU,
1274                           "%s 2nd-stage address=%" VADDR_PRIx
1275                           " ret %d physical "
1276                           HWADDR_FMT_plx " prot %d\n",
1277                           __func__, im_address, ret, pa, prot2);
1278
1279             prot &= prot2;
1280
1281             if (ret == TRANSLATE_SUCCESS) {
1282                 ret = get_physical_address_pmp(env, &prot_pmp, &tlb_size, pa,
1283                                                size, access_type, mode);
1284
1285                 qemu_log_mask(CPU_LOG_MMU,
1286                               "%s PMP address=" HWADDR_FMT_plx " ret %d prot"
1287                               " %d tlb_size " TARGET_FMT_lu "\n",
1288                               __func__, pa, ret, prot_pmp, tlb_size);
1289
1290                 prot &= prot_pmp;
1291             }
1292
1293             if (ret != TRANSLATE_SUCCESS) {
1294                 /*
1295                  * Guest physical address translation failed, this is a HS
1296                  * level exception
1297                  */
1298                 first_stage_error = false;
1299                 env->guest_phys_fault_addr = (im_address |
1300                                               (address &
1301                                                (TARGET_PAGE_SIZE - 1))) >> 2;
1302             }
1303         }
1304     } else {
1305         /* Single stage lookup */
1306         ret = get_physical_address(env, &pa, &prot, address, NULL,
1307                                    access_type, mmu_idx, true, false, false);
1308
1309         qemu_log_mask(CPU_LOG_MMU,
1310                       "%s address=%" VADDR_PRIx " ret %d physical "
1311                       HWADDR_FMT_plx " prot %d\n",
1312                       __func__, address, ret, pa, prot);
1313
1314         if (ret == TRANSLATE_SUCCESS) {
1315             ret = get_physical_address_pmp(env, &prot_pmp, &tlb_size, pa,
1316                                            size, access_type, mode);
1317
1318             qemu_log_mask(CPU_LOG_MMU,
1319                           "%s PMP address=" HWADDR_FMT_plx " ret %d prot"
1320                           " %d tlb_size " TARGET_FMT_lu "\n",
1321                           __func__, pa, ret, prot_pmp, tlb_size);
1322
1323             prot &= prot_pmp;
1324         }
1325     }
1326
1327     if (ret == TRANSLATE_PMP_FAIL) {
1328         pmp_violation = true;
1329     }
1330
1331     if (ret == TRANSLATE_SUCCESS) {
1332         tlb_set_page(cs, address & ~(tlb_size - 1), pa & ~(tlb_size - 1),
1333                      prot, mmu_idx, tlb_size);
1334         return true;
1335     } else if (probe) {
1336         return false;
1337     } else {
1338         raise_mmu_exception(env, address, access_type, pmp_violation,
1339                             first_stage_error, two_stage_lookup,
1340                             two_stage_indirect_error);
1341         cpu_loop_exit_restore(cs, retaddr);
1342     }
1343
1344     return true;
1345 }
1346
1347 static target_ulong riscv_transformed_insn(CPURISCVState *env,
1348                                            target_ulong insn,
1349                                            target_ulong taddr)
1350 {
1351     target_ulong xinsn = 0;
1352     target_ulong access_rs1 = 0, access_imm = 0, access_size = 0;
1353
1354     /*
1355      * Only Quadrant 0 and Quadrant 2 of RVC instruction space need to
1356      * be uncompressed. The Quadrant 1 of RVC instruction space need
1357      * not be transformed because these instructions won't generate
1358      * any load/store trap.
1359      */
1360
1361     if ((insn & 0x3) != 0x3) {
1362         /* Transform 16bit instruction into 32bit instruction */
1363         switch (GET_C_OP(insn)) {
1364         case OPC_RISC_C_OP_QUAD0: /* Quadrant 0 */
1365             switch (GET_C_FUNC(insn)) {
1366             case OPC_RISC_C_FUNC_FLD_LQ:
1367                 if (riscv_cpu_xlen(env) != 128) { /* C.FLD (RV32/64) */
1368                     xinsn = OPC_RISC_FLD;
1369                     xinsn = SET_RD(xinsn, GET_C_RS2S(insn));
1370                     access_rs1 = GET_C_RS1S(insn);
1371                     access_imm = GET_C_LD_IMM(insn);
1372                     access_size = 8;
1373                 }
1374                 break;
1375             case OPC_RISC_C_FUNC_LW: /* C.LW */
1376                 xinsn = OPC_RISC_LW;
1377                 xinsn = SET_RD(xinsn, GET_C_RS2S(insn));
1378                 access_rs1 = GET_C_RS1S(insn);
1379                 access_imm = GET_C_LW_IMM(insn);
1380                 access_size = 4;
1381                 break;
1382             case OPC_RISC_C_FUNC_FLW_LD:
1383                 if (riscv_cpu_xlen(env) == 32) { /* C.FLW (RV32) */
1384                     xinsn = OPC_RISC_FLW;
1385                     xinsn = SET_RD(xinsn, GET_C_RS2S(insn));
1386                     access_rs1 = GET_C_RS1S(insn);
1387                     access_imm = GET_C_LW_IMM(insn);
1388                     access_size = 4;
1389                 } else { /* C.LD (RV64/RV128) */
1390                     xinsn = OPC_RISC_LD;
1391                     xinsn = SET_RD(xinsn, GET_C_RS2S(insn));
1392                     access_rs1 = GET_C_RS1S(insn);
1393                     access_imm = GET_C_LD_IMM(insn);
1394                     access_size = 8;
1395                 }
1396                 break;
1397             case OPC_RISC_C_FUNC_FSD_SQ:
1398                 if (riscv_cpu_xlen(env) != 128) { /* C.FSD (RV32/64) */
1399                     xinsn = OPC_RISC_FSD;
1400                     xinsn = SET_RS2(xinsn, GET_C_RS2S(insn));
1401                     access_rs1 = GET_C_RS1S(insn);
1402                     access_imm = GET_C_SD_IMM(insn);
1403                     access_size = 8;
1404                 }
1405                 break;
1406             case OPC_RISC_C_FUNC_SW: /* C.SW */
1407                 xinsn = OPC_RISC_SW;
1408                 xinsn = SET_RS2(xinsn, GET_C_RS2S(insn));
1409                 access_rs1 = GET_C_RS1S(insn);
1410                 access_imm = GET_C_SW_IMM(insn);
1411                 access_size = 4;
1412                 break;
1413             case OPC_RISC_C_FUNC_FSW_SD:
1414                 if (riscv_cpu_xlen(env) == 32) { /* C.FSW (RV32) */
1415                     xinsn = OPC_RISC_FSW;
1416                     xinsn = SET_RS2(xinsn, GET_C_RS2S(insn));
1417                     access_rs1 = GET_C_RS1S(insn);
1418                     access_imm = GET_C_SW_IMM(insn);
1419                     access_size = 4;
1420                 } else { /* C.SD (RV64/RV128) */
1421                     xinsn = OPC_RISC_SD;
1422                     xinsn = SET_RS2(xinsn, GET_C_RS2S(insn));
1423                     access_rs1 = GET_C_RS1S(insn);
1424                     access_imm = GET_C_SD_IMM(insn);
1425                     access_size = 8;
1426                 }
1427                 break;
1428             default:
1429                 break;
1430             }
1431             break;
1432         case OPC_RISC_C_OP_QUAD2: /* Quadrant 2 */
1433             switch (GET_C_FUNC(insn)) {
1434             case OPC_RISC_C_FUNC_FLDSP_LQSP:
1435                 if (riscv_cpu_xlen(env) != 128) { /* C.FLDSP (RV32/64) */
1436                     xinsn = OPC_RISC_FLD;
1437                     xinsn = SET_RD(xinsn, GET_C_RD(insn));
1438                     access_rs1 = 2;
1439                     access_imm = GET_C_LDSP_IMM(insn);
1440                     access_size = 8;
1441                 }
1442                 break;
1443             case OPC_RISC_C_FUNC_LWSP: /* C.LWSP */
1444                 xinsn = OPC_RISC_LW;
1445                 xinsn = SET_RD(xinsn, GET_C_RD(insn));
1446                 access_rs1 = 2;
1447                 access_imm = GET_C_LWSP_IMM(insn);
1448                 access_size = 4;
1449                 break;
1450             case OPC_RISC_C_FUNC_FLWSP_LDSP:
1451                 if (riscv_cpu_xlen(env) == 32) { /* C.FLWSP (RV32) */
1452                     xinsn = OPC_RISC_FLW;
1453                     xinsn = SET_RD(xinsn, GET_C_RD(insn));
1454                     access_rs1 = 2;
1455                     access_imm = GET_C_LWSP_IMM(insn);
1456                     access_size = 4;
1457                 } else { /* C.LDSP (RV64/RV128) */
1458                     xinsn = OPC_RISC_LD;
1459                     xinsn = SET_RD(xinsn, GET_C_RD(insn));
1460                     access_rs1 = 2;
1461                     access_imm = GET_C_LDSP_IMM(insn);
1462                     access_size = 8;
1463                 }
1464                 break;
1465             case OPC_RISC_C_FUNC_FSDSP_SQSP:
1466                 if (riscv_cpu_xlen(env) != 128) { /* C.FSDSP (RV32/64) */
1467                     xinsn = OPC_RISC_FSD;
1468                     xinsn = SET_RS2(xinsn, GET_C_RS2(insn));
1469                     access_rs1 = 2;
1470                     access_imm = GET_C_SDSP_IMM(insn);
1471                     access_size = 8;
1472                 }
1473                 break;
1474             case OPC_RISC_C_FUNC_SWSP: /* C.SWSP */
1475                 xinsn = OPC_RISC_SW;
1476                 xinsn = SET_RS2(xinsn, GET_C_RS2(insn));
1477                 access_rs1 = 2;
1478                 access_imm = GET_C_SWSP_IMM(insn);
1479                 access_size = 4;
1480                 break;
1481             case 7:
1482                 if (riscv_cpu_xlen(env) == 32) { /* C.FSWSP (RV32) */
1483                     xinsn = OPC_RISC_FSW;
1484                     xinsn = SET_RS2(xinsn, GET_C_RS2(insn));
1485                     access_rs1 = 2;
1486                     access_imm = GET_C_SWSP_IMM(insn);
1487                     access_size = 4;
1488                 } else { /* C.SDSP (RV64/RV128) */
1489                     xinsn = OPC_RISC_SD;
1490                     xinsn = SET_RS2(xinsn, GET_C_RS2(insn));
1491                     access_rs1 = 2;
1492                     access_imm = GET_C_SDSP_IMM(insn);
1493                     access_size = 8;
1494                 }
1495                 break;
1496             default:
1497                 break;
1498             }
1499             break;
1500         default:
1501             break;
1502         }
1503
1504         /*
1505          * Clear Bit1 of transformed instruction to indicate that
1506          * original insruction was a 16bit instruction
1507          */
1508         xinsn &= ~((target_ulong)0x2);
1509     } else {
1510         /* Transform 32bit (or wider) instructions */
1511         switch (MASK_OP_MAJOR(insn)) {
1512         case OPC_RISC_ATOMIC:
1513             xinsn = insn;
1514             access_rs1 = GET_RS1(insn);
1515             access_size = 1 << GET_FUNCT3(insn);
1516             break;
1517         case OPC_RISC_LOAD:
1518         case OPC_RISC_FP_LOAD:
1519             xinsn = SET_I_IMM(insn, 0);
1520             access_rs1 = GET_RS1(insn);
1521             access_imm = GET_IMM(insn);
1522             access_size = 1 << GET_FUNCT3(insn);
1523             break;
1524         case OPC_RISC_STORE:
1525         case OPC_RISC_FP_STORE:
1526             xinsn = SET_S_IMM(insn, 0);
1527             access_rs1 = GET_RS1(insn);
1528             access_imm = GET_STORE_IMM(insn);
1529             access_size = 1 << GET_FUNCT3(insn);
1530             break;
1531         case OPC_RISC_SYSTEM:
1532             if (MASK_OP_SYSTEM(insn) == OPC_RISC_HLVHSV) {
1533                 xinsn = insn;
1534                 access_rs1 = GET_RS1(insn);
1535                 access_size = 1 << ((GET_FUNCT7(insn) >> 1) & 0x3);
1536                 access_size = 1 << access_size;
1537             }
1538             break;
1539         default:
1540             break;
1541         }
1542     }
1543
1544     if (access_size) {
1545         xinsn = SET_RS1(xinsn, (taddr - (env->gpr[access_rs1] + access_imm)) &
1546                                (access_size - 1));
1547     }
1548
1549     return xinsn;
1550 }
1551 #endif /* !CONFIG_USER_ONLY */
1552
1553 /*
1554  * Handle Traps
1555  *
1556  * Adapted from Spike's processor_t::take_trap.
1557  *
1558  */
1559 void riscv_cpu_do_interrupt(CPUState *cs)
1560 {
1561 #if !defined(CONFIG_USER_ONLY)
1562
1563     RISCVCPU *cpu = RISCV_CPU(cs);
1564     CPURISCVState *env = &cpu->env;
1565     bool write_gva = false;
1566     uint64_t s;
1567
1568     /*
1569      * cs->exception is 32-bits wide unlike mcause which is XLEN-bits wide
1570      * so we mask off the MSB and separate into trap type and cause.
1571      */
1572     bool async = !!(cs->exception_index & RISCV_EXCP_INT_FLAG);
1573     target_ulong cause = cs->exception_index & RISCV_EXCP_INT_MASK;
1574     uint64_t deleg = async ? env->mideleg : env->medeleg;
1575     target_ulong tval = 0;
1576     target_ulong tinst = 0;
1577     target_ulong htval = 0;
1578     target_ulong mtval2 = 0;
1579
1580     if  (cause == RISCV_EXCP_SEMIHOST) {
1581         do_common_semihosting(cs);
1582         env->pc += 4;
1583         return;
1584     }
1585
1586     if (!async) {
1587         /* set tval to badaddr for traps with address information */
1588         switch (cause) {
1589         case RISCV_EXCP_LOAD_GUEST_ACCESS_FAULT:
1590         case RISCV_EXCP_STORE_GUEST_AMO_ACCESS_FAULT:
1591         case RISCV_EXCP_LOAD_ADDR_MIS:
1592         case RISCV_EXCP_STORE_AMO_ADDR_MIS:
1593         case RISCV_EXCP_LOAD_ACCESS_FAULT:
1594         case RISCV_EXCP_STORE_AMO_ACCESS_FAULT:
1595         case RISCV_EXCP_LOAD_PAGE_FAULT:
1596         case RISCV_EXCP_STORE_PAGE_FAULT:
1597             write_gva = env->two_stage_lookup;
1598             tval = env->badaddr;
1599             if (env->two_stage_indirect_lookup) {
1600                 /*
1601                  * special pseudoinstruction for G-stage fault taken while
1602                  * doing VS-stage page table walk.
1603                  */
1604                 tinst = (riscv_cpu_xlen(env) == 32) ? 0x00002000 : 0x00003000;
1605             } else {
1606                 /*
1607                  * The "Addr. Offset" field in transformed instruction is
1608                  * non-zero only for misaligned access.
1609                  */
1610                 tinst = riscv_transformed_insn(env, env->bins, tval);
1611             }
1612             break;
1613         case RISCV_EXCP_INST_GUEST_PAGE_FAULT:
1614         case RISCV_EXCP_INST_ADDR_MIS:
1615         case RISCV_EXCP_INST_ACCESS_FAULT:
1616         case RISCV_EXCP_INST_PAGE_FAULT:
1617             write_gva = env->two_stage_lookup;
1618             tval = env->badaddr;
1619             if (env->two_stage_indirect_lookup) {
1620                 /*
1621                  * special pseudoinstruction for G-stage fault taken while
1622                  * doing VS-stage page table walk.
1623                  */
1624                 tinst = (riscv_cpu_xlen(env) == 32) ? 0x00002000 : 0x00003000;
1625             }
1626             break;
1627         case RISCV_EXCP_ILLEGAL_INST:
1628         case RISCV_EXCP_VIRT_INSTRUCTION_FAULT:
1629             tval = env->bins;
1630             break;
1631         case RISCV_EXCP_BREAKPOINT:
1632             if (cs->watchpoint_hit) {
1633                 tval = cs->watchpoint_hit->hitaddr;
1634                 cs->watchpoint_hit = NULL;
1635             }
1636             break;
1637         default:
1638             break;
1639         }
1640         /* ecall is dispatched as one cause so translate based on mode */
1641         if (cause == RISCV_EXCP_U_ECALL) {
1642             assert(env->priv <= 3);
1643
1644             if (env->priv == PRV_M) {
1645                 cause = RISCV_EXCP_M_ECALL;
1646             } else if (env->priv == PRV_S && env->virt_enabled) {
1647                 cause = RISCV_EXCP_VS_ECALL;
1648             } else if (env->priv == PRV_S && !env->virt_enabled) {
1649                 cause = RISCV_EXCP_S_ECALL;
1650             } else if (env->priv == PRV_U) {
1651                 cause = RISCV_EXCP_U_ECALL;
1652             }
1653         }
1654     }
1655
1656     trace_riscv_trap(env->mhartid, async, cause, env->pc, tval,
1657                      riscv_cpu_get_trap_name(cause, async));
1658
1659     qemu_log_mask(CPU_LOG_INT,
1660                   "%s: hart:"TARGET_FMT_ld", async:%d, cause:"TARGET_FMT_lx", "
1661                   "epc:0x"TARGET_FMT_lx", tval:0x"TARGET_FMT_lx", desc=%s\n",
1662                   __func__, env->mhartid, async, cause, env->pc, tval,
1663                   riscv_cpu_get_trap_name(cause, async));
1664
1665     if (env->priv <= PRV_S &&
1666             cause < TARGET_LONG_BITS && ((deleg >> cause) & 1)) {
1667         /* handle the trap in S-mode */
1668         if (riscv_has_ext(env, RVH)) {
1669             uint64_t hdeleg = async ? env->hideleg : env->hedeleg;
1670
1671             if (env->virt_enabled && ((hdeleg >> cause) & 1)) {
1672                 /* Trap to VS mode */
1673                 /*
1674                  * See if we need to adjust cause. Yes if its VS mode interrupt
1675                  * no if hypervisor has delegated one of hs mode's interrupt
1676                  */
1677                 if (cause == IRQ_VS_TIMER || cause == IRQ_VS_SOFT ||
1678                     cause == IRQ_VS_EXT) {
1679                     cause = cause - 1;
1680                 }
1681                 write_gva = false;
1682             } else if (env->virt_enabled) {
1683                 /* Trap into HS mode, from virt */
1684                 riscv_cpu_swap_hypervisor_regs(env);
1685                 env->hstatus = set_field(env->hstatus, HSTATUS_SPVP,
1686                                          env->priv);
1687                 env->hstatus = set_field(env->hstatus, HSTATUS_SPV, true);
1688
1689                 htval = env->guest_phys_fault_addr;
1690
1691                 riscv_cpu_set_virt_enabled(env, 0);
1692             } else {
1693                 /* Trap into HS mode */
1694                 env->hstatus = set_field(env->hstatus, HSTATUS_SPV, false);
1695                 htval = env->guest_phys_fault_addr;
1696             }
1697             env->hstatus = set_field(env->hstatus, HSTATUS_GVA, write_gva);
1698         }
1699
1700         s = env->mstatus;
1701         s = set_field(s, MSTATUS_SPIE, get_field(s, MSTATUS_SIE));
1702         s = set_field(s, MSTATUS_SPP, env->priv);
1703         s = set_field(s, MSTATUS_SIE, 0);
1704         env->mstatus = s;
1705         env->scause = cause | ((target_ulong)async << (TARGET_LONG_BITS - 1));
1706         env->sepc = env->pc;
1707         env->stval = tval;
1708         env->htval = htval;
1709         env->htinst = tinst;
1710         env->pc = (env->stvec >> 2 << 2) +
1711                   ((async && (env->stvec & 3) == 1) ? cause * 4 : 0);
1712         riscv_cpu_set_mode(env, PRV_S);
1713     } else {
1714         /* handle the trap in M-mode */
1715         if (riscv_has_ext(env, RVH)) {
1716             if (env->virt_enabled) {
1717                 riscv_cpu_swap_hypervisor_regs(env);
1718             }
1719             env->mstatus = set_field(env->mstatus, MSTATUS_MPV,
1720                                      env->virt_enabled);
1721             if (env->virt_enabled && tval) {
1722                 env->mstatus = set_field(env->mstatus, MSTATUS_GVA, 1);
1723             }
1724
1725             mtval2 = env->guest_phys_fault_addr;
1726
1727             /* Trapping to M mode, virt is disabled */
1728             riscv_cpu_set_virt_enabled(env, 0);
1729         }
1730
1731         s = env->mstatus;
1732         s = set_field(s, MSTATUS_MPIE, get_field(s, MSTATUS_MIE));
1733         s = set_field(s, MSTATUS_MPP, env->priv);
1734         s = set_field(s, MSTATUS_MIE, 0);
1735         env->mstatus = s;
1736         env->mcause = cause | ~(((target_ulong)-1) >> async);
1737         env->mepc = env->pc;
1738         env->mtval = tval;
1739         env->mtval2 = mtval2;
1740         env->mtinst = tinst;
1741         env->pc = (env->mtvec >> 2 << 2) +
1742                   ((async && (env->mtvec & 3) == 1) ? cause * 4 : 0);
1743         riscv_cpu_set_mode(env, PRV_M);
1744     }
1745
1746     /*
1747      * NOTE: it is not necessary to yield load reservations here. It is only
1748      * necessary for an SC from "another hart" to cause a load reservation
1749      * to be yielded. Refer to the memory consistency model section of the
1750      * RISC-V ISA Specification.
1751      */
1752
1753     env->two_stage_lookup = false;
1754     env->two_stage_indirect_lookup = false;
1755 #endif
1756     cs->exception_index = RISCV_EXCP_NONE; /* mark handled to qemu */
1757 }