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