qemu/target/arm/ptw.c
<<
>>
Prefs
   1/*
   2 * ARM page table walking.
   3 *
   4 * This code is licensed under the GNU GPL v2 or later.
   5 *
   6 * SPDX-License-Identifier: GPL-2.0-or-later
   7 */
   8
   9#include "qemu/osdep.h"
  10#include "qemu/log.h"
  11#include "qemu/range.h"
  12#include "qemu/main-loop.h"
  13#include "exec/page-protection.h"
  14#include "exec/target_page.h"
  15#include "exec/tlb-flags.h"
  16#include "accel/tcg/probe.h"
  17#include "cpu.h"
  18#include "internals.h"
  19#include "cpu-features.h"
  20#include "idau.h"
  21
  22typedef struct S1Translate {
  23    /*
  24     * in_mmu_idx : specifies which TTBR, TCR, etc to use for the walk.
  25     * Together with in_space, specifies the architectural translation regime.
  26     */
  27    ARMMMUIdx in_mmu_idx;
  28    /*
  29     * in_ptw_idx: specifies which mmuidx to use for the actual
  30     * page table descriptor load operations. This will be one of the
  31     * ARMMMUIdx_Stage2* or one of the ARMMMUIdx_Phys_* indexes.
  32     * If a Secure ptw is "downgraded" to NonSecure by an NSTable bit,
  33     * this field is updated accordingly.
  34     */
  35    ARMMMUIdx in_ptw_idx;
  36    /*
  37     * in_space: the security space for this walk. This plus
  38     * the in_mmu_idx specify the architectural translation regime.
  39     * If a Secure ptw is "downgraded" to NonSecure by an NSTable bit,
  40     * this field is updated accordingly.
  41     *
  42     * Note that the security space for the in_ptw_idx may be different
  43     * from that for the in_mmu_idx. We do not need to explicitly track
  44     * the in_ptw_idx security space because:
  45     *  - if the in_ptw_idx is an ARMMMUIdx_Phys_* then the mmuidx
  46     *    itself specifies the security space
  47     *  - if the in_ptw_idx is an ARMMMUIdx_Stage2* then the security
  48     *    space used for ptw reads is the same as that of the security
  49     *    space of the stage 1 translation for all cases except where
  50     *    stage 1 is Secure; in that case the only possibilities for
  51     *    the ptw read are Secure and NonSecure, and the in_ptw_idx
  52     *    value being Stage2 vs Stage2_S distinguishes those.
  53     */
  54    ARMSecuritySpace in_space;
  55    /*
  56     * in_debug: is this a QEMU debug access (gdbstub, etc)? Debug
  57     * accesses will not update the guest page table access flags
  58     * and will not change the state of the softmmu TLBs.
  59     */
  60    bool in_debug;
  61    /*
  62     * If this is stage 2 of a stage 1+2 page table walk, then this must
  63     * be true if stage 1 is an EL0 access; otherwise this is ignored.
  64     * Stage 2 is indicated by in_mmu_idx set to ARMMMUIdx_Stage2{,_S}.
  65     */
  66    bool in_s1_is_el0;
  67    bool out_rw;
  68    bool out_be;
  69    ARMSecuritySpace out_space;
  70    hwaddr out_virt;
  71    hwaddr out_phys;
  72    void *out_host;
  73} S1Translate;
  74
  75static bool get_phys_addr_nogpc(CPUARMState *env, S1Translate *ptw,
  76                                vaddr address,
  77                                MMUAccessType access_type, MemOp memop,
  78                                GetPhysAddrResult *result,
  79                                ARMMMUFaultInfo *fi);
  80
  81static bool get_phys_addr_gpc(CPUARMState *env, S1Translate *ptw,
  82                              vaddr address,
  83                              MMUAccessType access_type, MemOp memop,
  84                              GetPhysAddrResult *result,
  85                              ARMMMUFaultInfo *fi);
  86
  87static int get_S1prot(CPUARMState *env, ARMMMUIdx mmu_idx, bool is_aa64,
  88                      int user_rw, int prot_rw, int xn, int pxn,
  89                      ARMSecuritySpace in_pa, ARMSecuritySpace out_pa);
  90
  91/* This mapping is common between ID_AA64MMFR0.PARANGE and TCR_ELx.{I}PS. */
  92static const uint8_t pamax_map[] = {
  93    [0] = 32,
  94    [1] = 36,
  95    [2] = 40,
  96    [3] = 42,
  97    [4] = 44,
  98    [5] = 48,
  99    [6] = 52,
 100};
 101
 102uint8_t round_down_to_parange_index(uint8_t bit_size)
 103{
 104    for (int i = ARRAY_SIZE(pamax_map) - 1; i >= 0; i--) {
 105        if (pamax_map[i] <= bit_size) {
 106            return i;
 107        }
 108    }
 109    g_assert_not_reached();
 110}
 111
 112uint8_t round_down_to_parange_bit_size(uint8_t bit_size)
 113{
 114    return pamax_map[round_down_to_parange_index(bit_size)];
 115}
 116
 117/*
 118 * The cpu-specific constant value of PAMax; also used by hw/arm/virt.
 119 * Note that machvirt_init calls this on a CPU that is inited but not realized!
 120 */
 121unsigned int arm_pamax(ARMCPU *cpu)
 122{
 123    if (arm_feature(&cpu->env, ARM_FEATURE_AARCH64)) {
 124        unsigned int parange =
 125            FIELD_EX64_IDREG(&cpu->isar, ID_AA64MMFR0, PARANGE);
 126
 127        /*
 128         * id_aa64mmfr0 is a read-only register so values outside of the
 129         * supported mappings can be considered an implementation error.
 130         */
 131        assert(parange < ARRAY_SIZE(pamax_map));
 132        return pamax_map[parange];
 133    }
 134
 135    if (arm_feature(&cpu->env, ARM_FEATURE_LPAE)) {
 136        /* v7 or v8 with LPAE */
 137        return 40;
 138    }
 139    /* Anything else */
 140    return 32;
 141}
 142
 143/*
 144 * Convert a possible stage1+2 MMU index into the appropriate stage 1 MMU index
 145 */
 146ARMMMUIdx stage_1_mmu_idx(ARMMMUIdx mmu_idx)
 147{
 148    switch (mmu_idx) {
 149    case ARMMMUIdx_E10_0:
 150        return ARMMMUIdx_Stage1_E0;
 151    case ARMMMUIdx_E10_1:
 152        return ARMMMUIdx_Stage1_E1;
 153    case ARMMMUIdx_E10_1_PAN:
 154        return ARMMMUIdx_Stage1_E1_PAN;
 155    default:
 156        return mmu_idx;
 157    }
 158}
 159
 160ARMMMUIdx arm_stage1_mmu_idx(CPUARMState *env)
 161{
 162    return stage_1_mmu_idx(arm_mmu_idx(env));
 163}
 164
 165/*
 166 * Return where we should do ptw loads from for a stage 2 walk.
 167 * This depends on whether the address we are looking up is a
 168 * Secure IPA or a NonSecure IPA, which we know from whether this is
 169 * Stage2 or Stage2_S.
 170 * If this is the Secure EL1&0 regime we need to check the NSW and SW bits.
 171 */
 172static ARMMMUIdx ptw_idx_for_stage_2(CPUARMState *env, ARMMMUIdx stage2idx)
 173{
 174    bool s2walk_secure;
 175
 176    /*
 177     * We're OK to check the current state of the CPU here because
 178     * (1) we always invalidate all TLBs when the SCR_EL3.NS or SCR_EL3.NSE bit
 179     * changes.
 180     * (2) there's no way to do a lookup that cares about Stage 2 for a
 181     * different security state to the current one for AArch64, and AArch32
 182     * never has a secure EL2. (AArch32 ATS12NSO[UP][RW] allow EL3 to do
 183     * an NS stage 1+2 lookup while the NS bit is 0.)
 184     */
 185    if (!arm_el_is_aa64(env, 3)) {
 186        return ARMMMUIdx_Phys_NS;
 187    }
 188
 189    switch (arm_security_space_below_el3(env)) {
 190    case ARMSS_NonSecure:
 191        return ARMMMUIdx_Phys_NS;
 192    case ARMSS_Realm:
 193        return ARMMMUIdx_Phys_Realm;
 194    case ARMSS_Secure:
 195        if (stage2idx == ARMMMUIdx_Stage2_S) {
 196            s2walk_secure = !(env->cp15.vstcr_el2 & VSTCR_SW);
 197        } else {
 198            s2walk_secure = !(env->cp15.vtcr_el2 & VTCR_NSW);
 199        }
 200        return s2walk_secure ? ARMMMUIdx_Phys_S : ARMMMUIdx_Phys_NS;
 201    default:
 202        g_assert_not_reached();
 203    }
 204}
 205
 206static bool regime_translation_big_endian(CPUARMState *env, ARMMMUIdx mmu_idx)
 207{
 208    return (regime_sctlr(env, mmu_idx) & SCTLR_EE) != 0;
 209}
 210
 211/* Return the TTBR associated with this translation regime */
 212static uint64_t regime_ttbr(CPUARMState *env, ARMMMUIdx mmu_idx, int ttbrn)
 213{
 214    if (mmu_idx == ARMMMUIdx_Stage2) {
 215        return env->cp15.vttbr_el2;
 216    }
 217    if (mmu_idx == ARMMMUIdx_Stage2_S) {
 218        return env->cp15.vsttbr_el2;
 219    }
 220    if (ttbrn == 0) {
 221        return env->cp15.ttbr0_el[regime_el(env, mmu_idx)];
 222    } else {
 223        return env->cp15.ttbr1_el[regime_el(env, mmu_idx)];
 224    }
 225}
 226
 227/* Return true if the specified stage of address translation is disabled */
 228static bool regime_translation_disabled(CPUARMState *env, ARMMMUIdx mmu_idx,
 229                                        ARMSecuritySpace space)
 230{
 231    uint64_t hcr_el2;
 232
 233    if (arm_feature(env, ARM_FEATURE_M)) {
 234        bool is_secure = arm_space_is_secure(space);
 235        switch (env->v7m.mpu_ctrl[is_secure] &
 236                (R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK)) {
 237        case R_V7M_MPU_CTRL_ENABLE_MASK:
 238            /* Enabled, but not for HardFault and NMI */
 239            return mmu_idx & ARM_MMU_IDX_M_NEGPRI;
 240        case R_V7M_MPU_CTRL_ENABLE_MASK | R_V7M_MPU_CTRL_HFNMIENA_MASK:
 241            /* Enabled for all cases */
 242            return false;
 243        case 0:
 244        default:
 245            /*
 246             * HFNMIENA set and ENABLE clear is UNPREDICTABLE, but
 247             * we warned about that in armv7m_nvic.c when the guest set it.
 248             */
 249            return true;
 250        }
 251    }
 252
 253
 254    switch (mmu_idx) {
 255    case ARMMMUIdx_Stage2:
 256    case ARMMMUIdx_Stage2_S:
 257        /* HCR.DC means HCR.VM behaves as 1 */
 258        hcr_el2 = arm_hcr_el2_eff_secstate(env, space);
 259        return (hcr_el2 & (HCR_DC | HCR_VM)) == 0;
 260
 261    case ARMMMUIdx_E10_0:
 262    case ARMMMUIdx_E10_1:
 263    case ARMMMUIdx_E10_1_PAN:
 264        /* TGE means that EL0/1 act as if SCTLR_EL1.M is zero */
 265        hcr_el2 = arm_hcr_el2_eff_secstate(env, space);
 266        if (hcr_el2 & HCR_TGE) {
 267            return true;
 268        }
 269        break;
 270
 271    case ARMMMUIdx_Stage1_E0:
 272    case ARMMMUIdx_Stage1_E1:
 273    case ARMMMUIdx_Stage1_E1_PAN:
 274        /* HCR.DC means SCTLR_EL1.M behaves as 0 */
 275        hcr_el2 = arm_hcr_el2_eff_secstate(env, space);
 276        if (hcr_el2 & HCR_DC) {
 277            return true;
 278        }
 279        break;
 280
 281    case ARMMMUIdx_E20_0:
 282    case ARMMMUIdx_E20_2:
 283    case ARMMMUIdx_E20_2_PAN:
 284    case ARMMMUIdx_E2:
 285    case ARMMMUIdx_E3:
 286    case ARMMMUIdx_E30_0:
 287    case ARMMMUIdx_E30_3_PAN:
 288        break;
 289
 290    case ARMMMUIdx_Phys_S:
 291    case ARMMMUIdx_Phys_NS:
 292    case ARMMMUIdx_Phys_Root:
 293    case ARMMMUIdx_Phys_Realm:
 294        /* No translation for physical address spaces. */
 295        return true;
 296
 297    default:
 298        g_assert_not_reached();
 299    }
 300
 301    return (regime_sctlr(env, mmu_idx) & SCTLR_M) == 0;
 302}
 303
 304static bool granule_protection_check(CPUARMState *env, uint64_t paddress,
 305                                     ARMSecuritySpace pspace,
 306                                     ARMMMUFaultInfo *fi)
 307{
 308    MemTxAttrs attrs = {
 309        .secure = true,
 310        .space = ARMSS_Root,
 311    };
 312    ARMCPU *cpu = env_archcpu(env);
 313    uint64_t gpccr = env->cp15.gpccr_el3;
 314    unsigned pps, pgs, l0gptsz, level = 0;
 315    uint64_t tableaddr, pps_mask, align, entry, index;
 316    AddressSpace *as;
 317    MemTxResult result;
 318    int gpi;
 319
 320    if (!FIELD_EX64(gpccr, GPCCR, GPC)) {
 321        return true;
 322    }
 323
 324    /*
 325     * GPC Priority 1 (R_GMGRR):
 326     * R_JWCSM: If the configuration of GPCCR_EL3 is invalid,
 327     * the access fails as GPT walk fault at level 0.
 328     */
 329
 330    /*
 331     * Configuration of PPS to a value exceeding the implemented
 332     * physical address size is invalid.
 333     */
 334    pps = FIELD_EX64(gpccr, GPCCR, PPS);
 335    if (pps > FIELD_EX64_IDREG(&cpu->isar, ID_AA64MMFR0, PARANGE)) {
 336        goto fault_walk;
 337    }
 338    pps = pamax_map[pps];
 339    pps_mask = MAKE_64BIT_MASK(0, pps);
 340
 341    switch (FIELD_EX64(gpccr, GPCCR, SH)) {
 342    case 0b10: /* outer shareable */
 343        break;
 344    case 0b00: /* non-shareable */
 345    case 0b11: /* inner shareable */
 346        /* Inner and Outer non-cacheable requires Outer shareable. */
 347        if (FIELD_EX64(gpccr, GPCCR, ORGN) == 0 &&
 348            FIELD_EX64(gpccr, GPCCR, IRGN) == 0) {
 349            goto fault_walk;
 350        }
 351        break;
 352    default:   /* reserved */
 353        goto fault_walk;
 354    }
 355
 356    switch (FIELD_EX64(gpccr, GPCCR, PGS)) {
 357    case 0b00: /* 4KB */
 358        pgs = 12;
 359        break;
 360    case 0b01: /* 64KB */
 361        pgs = 16;
 362        break;
 363    case 0b10: /* 16KB */
 364        pgs = 14;
 365        break;
 366    default: /* reserved */
 367        goto fault_walk;
 368    }
 369
 370    /* Note this field is read-only and fixed at reset. */
 371    l0gptsz = 30 + FIELD_EX64(gpccr, GPCCR, L0GPTSZ);
 372
 373    /*
 374     * GPC Priority 2: Secure, Realm or Root address exceeds PPS.
 375     * R_CPDSB: A NonSecure physical address input exceeding PPS
 376     * does not experience any fault.
 377     */
 378    if (paddress & ~pps_mask) {
 379        if (pspace == ARMSS_NonSecure) {
 380            return true;
 381        }
 382        goto fault_size;
 383    }
 384
 385    /* GPC Priority 3: the base address of GPTBR_EL3 exceeds PPS. */
 386    tableaddr = env->cp15.gptbr_el3 << 12;
 387    if (tableaddr & ~pps_mask) {
 388        goto fault_size;
 389    }
 390
 391    /*
 392     * BADDR is aligned per a function of PPS and L0GPTSZ.
 393     * These bits of GPTBR_EL3 are RES0, but are not a configuration error,
 394     * unlike the RES0 bits of the GPT entries (R_XNKFZ).
 395     */
 396    align = MAX(pps - l0gptsz + 3, 12);
 397    align = MAKE_64BIT_MASK(0, align);
 398    tableaddr &= ~align;
 399
 400    as = arm_addressspace(env_cpu(env), attrs);
 401
 402    /* Level 0 lookup. */
 403    index = extract64(paddress, l0gptsz, pps - l0gptsz);
 404    tableaddr += index * 8;
 405    entry = address_space_ldq_le(as, tableaddr, attrs, &result);
 406    if (result != MEMTX_OK) {
 407        goto fault_eabt;
 408    }
 409
 410    switch (extract32(entry, 0, 4)) {
 411    case 1: /* block descriptor */
 412        if (entry >> 8) {
 413            goto fault_walk; /* RES0 bits not 0 */
 414        }
 415        gpi = extract32(entry, 4, 4);
 416        goto found;
 417    case 3: /* table descriptor */
 418        tableaddr = entry & ~0xf;
 419        align = MAX(l0gptsz - pgs - 1, 12);
 420        align = MAKE_64BIT_MASK(0, align);
 421        if (tableaddr & (~pps_mask | align)) {
 422            goto fault_walk; /* RES0 bits not 0 */
 423        }
 424        break;
 425    default: /* invalid */
 426        goto fault_walk;
 427    }
 428
 429    /* Level 1 lookup */
 430    level = 1;
 431    index = extract64(paddress, pgs + 4, l0gptsz - pgs - 4);
 432    tableaddr += index * 8;
 433    entry = address_space_ldq_le(as, tableaddr, attrs, &result);
 434    if (result != MEMTX_OK) {
 435        goto fault_eabt;
 436    }
 437
 438    switch (extract32(entry, 0, 4)) {
 439    case 1: /* contiguous descriptor */
 440        if (entry >> 10) {
 441            goto fault_walk; /* RES0 bits not 0 */
 442        }
 443        /*
 444         * Because the softmmu tlb only works on units of TARGET_PAGE_SIZE,
 445         * and because we cannot invalidate by pa, and thus will always
 446         * flush entire tlbs, we don't actually care about the range here
 447         * and can simply extract the GPI as the result.
 448         */
 449        if (extract32(entry, 8, 2) == 0) {
 450            goto fault_walk; /* reserved contig */
 451        }
 452        gpi = extract32(entry, 4, 4);
 453        break;
 454    default:
 455        index = extract64(paddress, pgs, 4);
 456        gpi = extract64(entry, index * 4, 4);
 457        break;
 458    }
 459
 460 found:
 461    switch (gpi) {
 462    case 0b0000: /* no access */
 463        break;
 464    case 0b1111: /* all access */
 465        return true;
 466    case 0b1000:
 467    case 0b1001:
 468    case 0b1010:
 469    case 0b1011:
 470        if (pspace == (gpi & 3)) {
 471            return true;
 472        }
 473        break;
 474    default:
 475        goto fault_walk; /* reserved */
 476    }
 477
 478    fi->gpcf = GPCF_Fail;
 479    goto fault_common;
 480 fault_eabt:
 481    fi->gpcf = GPCF_EABT;
 482    goto fault_common;
 483 fault_size:
 484    fi->gpcf = GPCF_AddressSize;
 485    goto fault_common;
 486 fault_walk:
 487    fi->gpcf = GPCF_Walk;
 488 fault_common:
 489    fi->level = level;
 490    fi->paddr = paddress;
 491    fi->paddr_space = pspace;
 492    return false;
 493}
 494
 495static bool S1_attrs_are_device(uint8_t attrs)
 496{
 497    /*
 498     * This slightly under-decodes the MAIR_ELx field:
 499     * 0b0000dd01 is Device with FEAT_XS, otherwise UNPREDICTABLE;
 500     * 0b0000dd1x is UNPREDICTABLE.
 501     */
 502    return (attrs & 0xf0) == 0;
 503}
 504
 505static bool S2_attrs_are_device(uint64_t hcr, uint8_t attrs)
 506{
 507    /*
 508     * For an S1 page table walk, the stage 1 attributes are always
 509     * some form of "this is Normal memory". The combined S1+S2
 510     * attributes are therefore only Device if stage 2 specifies Device.
 511     * With HCR_EL2.FWB == 0 this is when descriptor bits [5:4] are 0b00,
 512     * ie when cacheattrs.attrs bits [3:2] are 0b00.
 513     * With HCR_EL2.FWB == 1 this is when descriptor bit [4] is 0, ie
 514     * when cacheattrs.attrs bit [2] is 0.
 515     */
 516    if (hcr & HCR_FWB) {
 517        return (attrs & 0x4) == 0;
 518    } else {
 519        return (attrs & 0xc) == 0;
 520    }
 521}
 522
 523static ARMSecuritySpace S2_security_space(ARMSecuritySpace s1_space,
 524                                          ARMMMUIdx s2_mmu_idx)
 525{
 526    /*
 527     * Return the security space to use for stage 2 when doing
 528     * the S1 page table descriptor load.
 529     */
 530    if (regime_is_stage2(s2_mmu_idx)) {
 531        /*
 532         * The security space for ptw reads is almost always the same
 533         * as that of the security space of the stage 1 translation.
 534         * The only exception is when stage 1 is Secure; in that case
 535         * the ptw read might be to the Secure or the NonSecure space
 536         * (but never Realm or Root), and the s2_mmu_idx tells us which.
 537         * Root translations are always single-stage.
 538         */
 539        if (s1_space == ARMSS_Secure) {
 540            return arm_secure_to_space(s2_mmu_idx == ARMMMUIdx_Stage2_S);
 541        } else {
 542            assert(s2_mmu_idx != ARMMMUIdx_Stage2_S);
 543            assert(s1_space != ARMSS_Root);
 544            return s1_space;
 545        }
 546    } else {
 547        /* ptw loads are from phys: the mmu idx itself says which space */
 548        return arm_phys_to_space(s2_mmu_idx);
 549    }
 550}
 551
 552static bool fault_s1ns(ARMSecuritySpace space, ARMMMUIdx s2_mmu_idx)
 553{
 554    /*
 555     * For stage 2 faults in Secure EL22, S1NS indicates
 556     * whether the faulting IPA is in the Secure or NonSecure
 557     * IPA space. For all other kinds of fault, it is false.
 558     */
 559    return space == ARMSS_Secure && regime_is_stage2(s2_mmu_idx)
 560        && s2_mmu_idx == ARMMMUIdx_Stage2_S;
 561}
 562
 563/* Translate a S1 pagetable walk through S2 if needed.  */
 564static bool S1_ptw_translate(CPUARMState *env, S1Translate *ptw,
 565                             hwaddr addr, ARMMMUFaultInfo *fi)
 566{
 567    ARMMMUIdx mmu_idx = ptw->in_mmu_idx;
 568    ARMMMUIdx s2_mmu_idx = ptw->in_ptw_idx;
 569    uint8_t pte_attrs;
 570
 571    ptw->out_virt = addr;
 572
 573    if (unlikely(ptw->in_debug)) {
 574        /*
 575         * From gdbstub, do not use softmmu so that we don't modify the
 576         * state of the cpu at all, including softmmu tlb contents.
 577         */
 578        ARMSecuritySpace s2_space = S2_security_space(ptw->in_space, s2_mmu_idx);
 579        S1Translate s2ptw = {
 580            .in_mmu_idx = s2_mmu_idx,
 581            .in_ptw_idx = ptw_idx_for_stage_2(env, s2_mmu_idx),
 582            .in_space = s2_space,
 583            .in_debug = true,
 584        };
 585        GetPhysAddrResult s2 = { };
 586
 587        if (get_phys_addr_gpc(env, &s2ptw, addr, MMU_DATA_LOAD, 0, &s2, fi)) {
 588            goto fail;
 589        }
 590
 591        ptw->out_phys = s2.f.phys_addr;
 592        pte_attrs = s2.cacheattrs.attrs;
 593        ptw->out_host = NULL;
 594        ptw->out_rw = false;
 595        ptw->out_space = s2.f.attrs.space;
 596    } else {
 597#ifdef CONFIG_TCG
 598        CPUTLBEntryFull *full;
 599        int flags;
 600
 601        env->tlb_fi = fi;
 602        flags = probe_access_full_mmu(env, addr, 0, MMU_DATA_LOAD,
 603                                      arm_to_core_mmu_idx(s2_mmu_idx),
 604                                      &ptw->out_host, &full);
 605        env->tlb_fi = NULL;
 606
 607        if (unlikely(flags & TLB_INVALID_MASK)) {
 608            goto fail;
 609        }
 610        ptw->out_phys = full->phys_addr | (addr & ~TARGET_PAGE_MASK);
 611        ptw->out_rw = full->prot & PAGE_WRITE;
 612        pte_attrs = full->extra.arm.pte_attrs;
 613        ptw->out_space = full->attrs.space;
 614#else
 615        g_assert_not_reached();
 616#endif
 617    }
 618
 619    if (regime_is_stage2(s2_mmu_idx)) {
 620        uint64_t hcr = arm_hcr_el2_eff_secstate(env, ptw->in_space);
 621
 622        if ((hcr & HCR_PTW) && S2_attrs_are_device(hcr, pte_attrs)) {
 623            /*
 624             * PTW set and S1 walk touched S2 Device memory:
 625             * generate Permission fault.
 626             */
 627            fi->type = ARMFault_Permission;
 628            fi->s2addr = addr;
 629            fi->stage2 = true;
 630            fi->s1ptw = true;
 631            fi->s1ns = fault_s1ns(ptw->in_space, s2_mmu_idx);
 632            return false;
 633        }
 634    }
 635
 636    ptw->out_be = regime_translation_big_endian(env, mmu_idx);
 637    return true;
 638
 639 fail:
 640    assert(fi->type != ARMFault_None);
 641    if (fi->type == ARMFault_GPCFOnOutput) {
 642        fi->type = ARMFault_GPCFOnWalk;
 643    }
 644    fi->s2addr = addr;
 645    fi->stage2 = regime_is_stage2(s2_mmu_idx);
 646    fi->s1ptw = fi->stage2;
 647    fi->s1ns = fault_s1ns(ptw->in_space, s2_mmu_idx);
 648    return false;
 649}
 650
 651/* All loads done in the course of a page table walk go through here. */
 652static uint32_t arm_ldl_ptw(CPUARMState *env, S1Translate *ptw,
 653                            ARMMMUFaultInfo *fi)
 654{
 655    CPUState *cs = env_cpu(env);
 656    void *host = ptw->out_host;
 657    uint32_t data;
 658
 659    if (likely(host)) {
 660        /* Page tables are in RAM, and we have the host address. */
 661        data = qatomic_read((uint32_t *)host);
 662        if (ptw->out_be) {
 663            data = be32_to_cpu(data);
 664        } else {
 665            data = le32_to_cpu(data);
 666        }
 667    } else {
 668        /* Page tables are in MMIO. */
 669        MemTxAttrs attrs = {
 670            .space = ptw->out_space,
 671            .secure = arm_space_is_secure(ptw->out_space),
 672        };
 673        AddressSpace *as = arm_addressspace(cs, attrs);
 674        MemTxResult result = MEMTX_OK;
 675
 676        if (ptw->out_be) {
 677            data = address_space_ldl_be(as, ptw->out_phys, attrs, &result);
 678        } else {
 679            data = address_space_ldl_le(as, ptw->out_phys, attrs, &result);
 680        }
 681        if (unlikely(result != MEMTX_OK)) {
 682            fi->type = ARMFault_SyncExternalOnWalk;
 683            fi->ea = arm_extabort_type(result);
 684            return 0;
 685        }
 686    }
 687    return data;
 688}
 689
 690static uint64_t arm_ldq_ptw(CPUARMState *env, S1Translate *ptw,
 691                            ARMMMUFaultInfo *fi)
 692{
 693    CPUState *cs = env_cpu(env);
 694    void *host = ptw->out_host;
 695    uint64_t data;
 696
 697    if (likely(host)) {
 698        /* Page tables are in RAM, and we have the host address. */
 699#ifdef CONFIG_ATOMIC64
 700        data = qatomic_read__nocheck((uint64_t *)host);
 701        if (ptw->out_be) {
 702            data = be64_to_cpu(data);
 703        } else {
 704            data = le64_to_cpu(data);
 705        }
 706#else
 707        if (ptw->out_be) {
 708            data = ldq_be_p(host);
 709        } else {
 710            data = ldq_le_p(host);
 711        }
 712#endif
 713    } else {
 714        /* Page tables are in MMIO. */
 715        MemTxAttrs attrs = {
 716            .space = ptw->out_space,
 717            .secure = arm_space_is_secure(ptw->out_space),
 718        };
 719        AddressSpace *as = arm_addressspace(cs, attrs);
 720        MemTxResult result = MEMTX_OK;
 721
 722        if (ptw->out_be) {
 723            data = address_space_ldq_be(as, ptw->out_phys, attrs, &result);
 724        } else {
 725            data = address_space_ldq_le(as, ptw->out_phys, attrs, &result);
 726        }
 727        if (unlikely(result != MEMTX_OK)) {
 728            fi->type = ARMFault_SyncExternalOnWalk;
 729            fi->ea = arm_extabort_type(result);
 730            return 0;
 731        }
 732    }
 733    return data;
 734}
 735
 736static uint64_t arm_casq_ptw(CPUARMState *env, uint64_t old_val,
 737                             uint64_t new_val, S1Translate *ptw,
 738                             ARMMMUFaultInfo *fi)
 739{
 740#if defined(CONFIG_ATOMIC64) && defined(CONFIG_TCG)
 741    uint64_t cur_val;
 742    void *host = ptw->out_host;
 743
 744    if (unlikely(!host)) {
 745        /* Page table in MMIO Memory Region */
 746        CPUState *cs = env_cpu(env);
 747        MemTxAttrs attrs = {
 748            .space = ptw->out_space,
 749            .secure = arm_space_is_secure(ptw->out_space),
 750        };
 751        AddressSpace *as = arm_addressspace(cs, attrs);
 752        MemTxResult result = MEMTX_OK;
 753        bool need_lock = !bql_locked();
 754
 755        if (need_lock) {
 756            bql_lock();
 757        }
 758        if (ptw->out_be) {
 759            cur_val = address_space_ldq_be(as, ptw->out_phys, attrs, &result);
 760            if (unlikely(result != MEMTX_OK)) {
 761                fi->type = ARMFault_SyncExternalOnWalk;
 762                fi->ea = arm_extabort_type(result);
 763                if (need_lock) {
 764                    bql_unlock();
 765                }
 766                return old_val;
 767            }
 768            if (cur_val == old_val) {
 769                address_space_stq_be(as, ptw->out_phys, new_val, attrs, &result);
 770                if (unlikely(result != MEMTX_OK)) {
 771                    fi->type = ARMFault_SyncExternalOnWalk;
 772                    fi->ea = arm_extabort_type(result);
 773                    if (need_lock) {
 774                        bql_unlock();
 775                    }
 776                    return old_val;
 777                }
 778                cur_val = new_val;
 779            }
 780        } else {
 781            cur_val = address_space_ldq_le(as, ptw->out_phys, attrs, &result);
 782            if (unlikely(result != MEMTX_OK)) {
 783                fi->type = ARMFault_SyncExternalOnWalk;
 784                fi->ea = arm_extabort_type(result);
 785                if (need_lock) {
 786                    bql_unlock();
 787                }
 788                return old_val;
 789            }
 790            if (cur_val == old_val) {
 791                address_space_stq_le(as, ptw->out_phys, new_val, attrs, &result);
 792                if (unlikely(result != MEMTX_OK)) {
 793                    fi->type = ARMFault_SyncExternalOnWalk;
 794                    fi->ea = arm_extabort_type(result);
 795                    if (need_lock) {
 796                        bql_unlock();
 797                    }
 798                    return old_val;
 799                }
 800                cur_val = new_val;
 801            }
 802        }
 803        if (need_lock) {
 804            bql_unlock();
 805        }
 806        return cur_val;
 807    }
 808
 809    /*
 810     * Raising a stage2 Protection fault for an atomic update to a read-only
 811     * page is delayed until it is certain that there is a change to make.
 812     */
 813    if (unlikely(!ptw->out_rw)) {
 814        int flags;
 815
 816        env->tlb_fi = fi;
 817        flags = probe_access_full_mmu(env, ptw->out_virt, 0,
 818                                      MMU_DATA_STORE,
 819                                      arm_to_core_mmu_idx(ptw->in_ptw_idx),
 820                                      NULL, NULL);
 821        env->tlb_fi = NULL;
 822
 823        if (unlikely(flags & TLB_INVALID_MASK)) {
 824            /*
 825             * We know this must be a stage 2 fault because the granule
 826             * protection table does not separately track read and write
 827             * permission, so all GPC faults are caught in S1_ptw_translate():
 828             * we only get here for "readable but not writeable".
 829             */
 830            assert(fi->type != ARMFault_None);
 831            fi->s2addr = ptw->out_virt;
 832            fi->stage2 = true;
 833            fi->s1ptw = true;
 834            fi->s1ns = fault_s1ns(ptw->in_space, ptw->in_ptw_idx);
 835            return 0;
 836        }
 837
 838        /* In case CAS mismatches and we loop, remember writability. */
 839        ptw->out_rw = true;
 840    }
 841
 842    if (ptw->out_be) {
 843        old_val = cpu_to_be64(old_val);
 844        new_val = cpu_to_be64(new_val);
 845        cur_val = qatomic_cmpxchg__nocheck((uint64_t *)host, old_val, new_val);
 846        cur_val = be64_to_cpu(cur_val);
 847    } else {
 848        old_val = cpu_to_le64(old_val);
 849        new_val = cpu_to_le64(new_val);
 850        cur_val = qatomic_cmpxchg__nocheck((uint64_t *)host, old_val, new_val);
 851        cur_val = le64_to_cpu(cur_val);
 852    }
 853    return cur_val;
 854#else
 855    /* AArch32 does not have FEAT_HADFS; non-TCG guests only use debug-mode. */
 856    g_assert_not_reached();
 857#endif
 858}
 859
 860static bool get_level1_table_address(CPUARMState *env, ARMMMUIdx mmu_idx,
 861                                     uint32_t *table, uint32_t address)
 862{
 863    /* Note that we can only get here for an AArch32 PL0/PL1 lookup */
 864    uint64_t tcr = regime_tcr(env, mmu_idx);
 865    int maskshift = extract32(tcr, 0, 3);
 866    uint32_t mask = ~(((uint32_t)0xffffffffu) >> maskshift);
 867    uint32_t base_mask;
 868
 869    if (address & mask) {
 870        if (tcr & TTBCR_PD1) {
 871            /* Translation table walk disabled for TTBR1 */
 872            return false;
 873        }
 874        *table = regime_ttbr(env, mmu_idx, 1) & 0xffffc000;
 875    } else {
 876        if (tcr & TTBCR_PD0) {
 877            /* Translation table walk disabled for TTBR0 */
 878            return false;
 879        }
 880        base_mask = ~((uint32_t)0x3fffu >> maskshift);
 881        *table = regime_ttbr(env, mmu_idx, 0) & base_mask;
 882    }
 883    *table |= (address >> 18) & 0x3ffc;
 884    return true;
 885}
 886
 887/*
 888 * Translate section/page access permissions to page R/W protection flags
 889 * @env:         CPUARMState
 890 * @mmu_idx:     MMU index indicating required translation regime
 891 * @ap:          The 3-bit access permissions (AP[2:0])
 892 * @domain_prot: The 2-bit domain access permissions
 893 * @is_user: TRUE if accessing from PL0
 894 */
 895static int ap_to_rw_prot_is_user(CPUARMState *env, ARMMMUIdx mmu_idx,
 896                         int ap, int domain_prot, bool is_user)
 897{
 898    if (domain_prot == 3) {
 899        return PAGE_READ | PAGE_WRITE;
 900    }
 901
 902    switch (ap) {
 903    case 0:
 904        if (arm_feature(env, ARM_FEATURE_V7)) {
 905            return 0;
 906        }
 907        switch (regime_sctlr(env, mmu_idx) & (SCTLR_S | SCTLR_R)) {
 908        case SCTLR_S:
 909            return is_user ? 0 : PAGE_READ;
 910        case SCTLR_R:
 911            return PAGE_READ;
 912        default:
 913            return 0;
 914        }
 915    case 1:
 916        return is_user ? 0 : PAGE_READ | PAGE_WRITE;
 917    case 2:
 918        if (is_user) {
 919            return PAGE_READ;
 920        } else {
 921            return PAGE_READ | PAGE_WRITE;
 922        }
 923    case 3:
 924        return PAGE_READ | PAGE_WRITE;
 925    case 4: /* Reserved.  */
 926        return 0;
 927    case 5:
 928        return is_user ? 0 : PAGE_READ;
 929    case 6:
 930        return PAGE_READ;
 931    case 7:
 932        if (!arm_feature(env, ARM_FEATURE_V6K)) {
 933            return 0;
 934        }
 935        return PAGE_READ;
 936    default:
 937        g_assert_not_reached();
 938    }
 939}
 940
 941/*
 942 * Translate section/page access permissions to page R/W protection flags
 943 * @env:         CPUARMState
 944 * @mmu_idx:     MMU index indicating required translation regime
 945 * @ap:          The 3-bit access permissions (AP[2:0])
 946 * @domain_prot: The 2-bit domain access permissions
 947 */
 948static int ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx,
 949                         int ap, int domain_prot)
 950{
 951   return ap_to_rw_prot_is_user(env, mmu_idx, ap, domain_prot,
 952                                regime_is_user(env, mmu_idx));
 953}
 954
 955/*
 956 * Translate section/page access permissions to page R/W protection flags.
 957 * @ap:      The 2-bit simple AP (AP[2:1])
 958 * @is_user: TRUE if accessing from PL0
 959 */
 960static int simple_ap_to_rw_prot_is_user(int ap, bool is_user)
 961{
 962    switch (ap) {
 963    case 0:
 964        return is_user ? 0 : PAGE_READ | PAGE_WRITE;
 965    case 1:
 966        return PAGE_READ | PAGE_WRITE;
 967    case 2:
 968        return is_user ? 0 : PAGE_READ;
 969    case 3:
 970        return PAGE_READ;
 971    default:
 972        g_assert_not_reached();
 973    }
 974}
 975
 976static int simple_ap_to_rw_prot(CPUARMState *env, ARMMMUIdx mmu_idx, int ap)
 977{
 978    return simple_ap_to_rw_prot_is_user(ap, regime_is_user(env, mmu_idx));
 979}
 980
 981static bool get_phys_addr_v5(CPUARMState *env, S1Translate *ptw,
 982                             uint32_t address, MMUAccessType access_type,
 983                             GetPhysAddrResult *result, ARMMMUFaultInfo *fi)
 984{
 985    int level = 1;
 986    uint32_t table;
 987    uint32_t desc;
 988    int type;
 989    int ap;
 990    int domain = 0;
 991    int domain_prot;
 992    hwaddr phys_addr;
 993    uint32_t dacr;
 994
 995    /* Pagetable walk.  */
 996    /* Lookup l1 descriptor.  */
 997    if (!get_level1_table_address(env, ptw->in_mmu_idx, &table, address)) {
 998        /* Section translation fault if page walk is disabled by PD0 or PD1 */
 999        fi->type = ARMFault_Translation;
1000        goto do_fault;
1001    }
1002    if (!S1_ptw_translate(env, ptw, table, fi)) {
1003        goto do_fault;
1004    }
1005    desc = arm_ldl_ptw(env, ptw, fi);
1006    if (fi->type != ARMFault_None) {
1007        goto do_fault;
1008    }
1009    type = (desc & 3);
1010    domain = (desc >> 5) & 0x0f;
1011    if (regime_el(env, ptw->in_mmu_idx) == 1) {
1012        dacr = env->cp15.dacr_ns;
1013    } else {
1014        dacr = env->cp15.dacr_s;
1015    }
1016    domain_prot = (dacr >> (domain * 2)) & 3;
1017    if (type == 0) {
1018        /* Section translation fault.  */
1019        fi->type = ARMFault_Translation;
1020        goto do_fault;
1021    }
1022    if (type != 2) {
1023        level = 2;
1024    }
1025    if (domain_prot == 0 || domain_prot == 2) {
1026        fi->type = ARMFault_Domain;
1027        goto do_fault;
1028    }
1029    if (type == 2) {
1030        /* 1Mb section.  */
1031        phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
1032        ap = (desc >> 10) & 3;
1033        result->f.lg_page_size = 20; /* 1MB */
1034    } else {
1035        /* Lookup l2 entry.  */
1036        if (type == 1) {
1037            /* Coarse pagetable.  */
1038            table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
1039        } else {
1040            /* Fine pagetable.  */
1041            table = (desc & 0xfffff000) | ((address >> 8) & 0xffc);
1042        }
1043        if (!S1_ptw_translate(env, ptw, table, fi)) {
1044            goto do_fault;
1045        }
1046        desc = arm_ldl_ptw(env, ptw, fi);
1047        if (fi->type != ARMFault_None) {
1048            goto do_fault;
1049        }
1050        switch (desc & 3) {
1051        case 0: /* Page translation fault.  */
1052            fi->type = ARMFault_Translation;
1053            goto do_fault;
1054        case 1: /* 64k page.  */
1055            phys_addr = (desc & 0xffff0000) | (address & 0xffff);
1056            ap = (desc >> (4 + ((address >> 13) & 6))) & 3;
1057            result->f.lg_page_size = 16;
1058            break;
1059        case 2: /* 4k page.  */
1060            phys_addr = (desc & 0xfffff000) | (address & 0xfff);
1061            ap = (desc >> (4 + ((address >> 9) & 6))) & 3;
1062            result->f.lg_page_size = 12;
1063            break;
1064        case 3: /* 1k page, or ARMv6/XScale "extended small (4k) page" */
1065            if (type == 1) {
1066                /* ARMv6/XScale extended small page format */
1067                if (arm_feature(env, ARM_FEATURE_XSCALE)
1068                    || arm_feature(env, ARM_FEATURE_V6)) {
1069                    phys_addr = (desc & 0xfffff000) | (address & 0xfff);
1070                    result->f.lg_page_size = 12;
1071                } else {
1072                    /*
1073                     * UNPREDICTABLE in ARMv5; we choose to take a
1074                     * page translation fault.
1075                     */
1076                    fi->type = ARMFault_Translation;
1077                    goto do_fault;
1078                }
1079            } else {
1080                phys_addr = (desc & 0xfffffc00) | (address & 0x3ff);
1081                result->f.lg_page_size = 10;
1082            }
1083            ap = (desc >> 4) & 3;
1084            break;
1085        default:
1086            /* Never happens, but compiler isn't smart enough to tell.  */
1087            g_assert_not_reached();
1088        }
1089    }
1090    result->f.prot = ap_to_rw_prot(env, ptw->in_mmu_idx, ap, domain_prot);
1091    result->f.prot |= result->f.prot ? PAGE_EXEC : 0;
1092    if (!(result->f.prot & (1 << access_type))) {
1093        /* Access permission fault.  */
1094        fi->type = ARMFault_Permission;
1095        goto do_fault;
1096    }
1097    result->f.phys_addr = phys_addr;
1098    return false;
1099do_fault:
1100    fi->domain = domain;
1101    fi->level = level;
1102    return true;
1103}
1104
1105static bool get_phys_addr_v6(CPUARMState *env, S1Translate *ptw,
1106                             uint32_t address, MMUAccessType access_type,
1107                             GetPhysAddrResult *result, ARMMMUFaultInfo *fi)
1108{
1109    ARMCPU *cpu = env_archcpu(env);
1110    ARMMMUIdx mmu_idx = ptw->in_mmu_idx;
1111    int level = 1;
1112    uint32_t table;
1113    uint32_t desc;
1114    uint32_t xn;
1115    uint32_t pxn = 0;
1116    int type;
1117    int ap;
1118    int domain = 0;
1119    int domain_prot;
1120    hwaddr phys_addr;
1121    uint32_t dacr;
1122    bool ns;
1123    ARMSecuritySpace out_space;
1124
1125    /* Pagetable walk.  */
1126    /* Lookup l1 descriptor.  */
1127    if (!get_level1_table_address(env, mmu_idx, &table, address)) {
1128        /* Section translation fault if page walk is disabled by PD0 or PD1 */
1129        fi->type = ARMFault_Translation;
1130        goto do_fault;
1131    }
1132    if (!S1_ptw_translate(env, ptw, table, fi)) {
1133        goto do_fault;
1134    }
1135    desc = arm_ldl_ptw(env, ptw, fi);
1136    if (fi->type != ARMFault_None) {
1137        goto do_fault;
1138    }
1139    type = (desc & 3);
1140    if (type == 0 || (type == 3 && !cpu_isar_feature(aa32_pxn, cpu))) {
1141        /* Section translation fault, or attempt to use the encoding
1142         * which is Reserved on implementations without PXN.
1143         */
1144        fi->type = ARMFault_Translation;
1145        goto do_fault;
1146    }
1147    if ((type == 1) || !(desc & (1 << 18))) {
1148        /* Page or Section.  */
1149        domain = (desc >> 5) & 0x0f;
1150    }
1151    if (regime_el(env, mmu_idx) == 1) {
1152        dacr = env->cp15.dacr_ns;
1153    } else {
1154        dacr = env->cp15.dacr_s;
1155    }
1156    if (type == 1) {
1157        level = 2;
1158    }
1159    domain_prot = (dacr >> (domain * 2)) & 3;
1160    if (domain_prot == 0 || domain_prot == 2) {
1161        /* Section or Page domain fault */
1162        fi->type = ARMFault_Domain;
1163        goto do_fault;
1164    }
1165    if (type != 1) {
1166        if (desc & (1 << 18)) {
1167            /* Supersection.  */
1168            phys_addr = (desc & 0xff000000) | (address & 0x00ffffff);
1169            phys_addr |= (uint64_t)extract32(desc, 20, 4) << 32;
1170            phys_addr |= (uint64_t)extract32(desc, 5, 4) << 36;
1171            result->f.lg_page_size = 24;  /* 16MB */
1172        } else {
1173            /* Section.  */
1174            phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);
1175            result->f.lg_page_size = 20;  /* 1MB */
1176        }
1177        ap = ((desc >> 10) & 3) | ((desc >> 13) & 4);
1178        xn = desc & (1 << 4);
1179        pxn = desc & 1;
1180        ns = extract32(desc, 19, 1);
1181    } else {
1182        if (cpu_isar_feature(aa32_pxn, cpu)) {
1183            pxn = (desc >> 2) & 1;
1184        }
1185        ns = extract32(desc, 3, 1);
1186        /* Lookup l2 entry.  */
1187        table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);
1188        if (!S1_ptw_translate(env, ptw, table, fi)) {
1189            goto do_fault;
1190        }
1191        desc = arm_ldl_ptw(env, ptw, fi);
1192        if (fi->type != ARMFault_None) {
1193            goto do_fault;
1194        }
1195        ap = ((desc >> 4) & 3) | ((desc >> 7) & 4);
1196        switch (desc & 3) {
1197        case 0: /* Page translation fault.  */
1198            fi->type = ARMFault_Translation;
1199            goto do_fault;
1200        case 1: /* 64k page.  */
1201            phys_addr = (desc & 0xffff0000) | (address & 0xffff);
1202            xn = desc & (1 << 15);
1203            result->f.lg_page_size = 16;
1204            break;
1205        case 2: case 3: /* 4k page.  */
1206            phys_addr = (desc & 0xfffff000) | (address & 0xfff);
1207            xn = desc & 1;
1208            result->f.lg_page_size = 12;
1209            break;
1210        default:
1211            /* Never happens, but compiler isn't smart enough to tell.  */
1212            g_assert_not_reached();
1213        }
1214    }
1215    out_space = ptw->in_space;
1216    if (ns) {
1217        /*
1218         * The NS bit will (as required by the architecture) have no effect if
1219         * the CPU doesn't support TZ or this is a non-secure translation
1220         * regime, because the output space will already be non-secure.
1221         */
1222        out_space = ARMSS_NonSecure;
1223    }
1224    if (domain_prot == 3) {
1225        result->f.prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
1226    } else {
1227        int user_rw, prot_rw;
1228
1229        if (arm_feature(env, ARM_FEATURE_V6K) &&
1230                (regime_sctlr(env, mmu_idx) & SCTLR_AFE)) {
1231            /* The simplified model uses AP[0] as an access control bit.  */
1232            if ((ap & 1) == 0) {
1233                /* Access flag fault.  */
1234                fi->type = ARMFault_AccessFlag;
1235                goto do_fault;
1236            }
1237            prot_rw = simple_ap_to_rw_prot(env, mmu_idx, ap >> 1);
1238            user_rw = simple_ap_to_rw_prot_is_user(ap >> 1, 1);
1239        } else {
1240            prot_rw = ap_to_rw_prot(env, mmu_idx, ap, domain_prot);
1241            user_rw = ap_to_rw_prot_is_user(env, mmu_idx, ap, domain_prot, 1);
1242        }
1243
1244        result->f.prot = get_S1prot(env, mmu_idx, false, user_rw, prot_rw,
1245                                    xn, pxn, result->f.attrs.space, out_space);
1246        if (!(result->f.prot & (1 << access_type))) {
1247            /* Access permission fault.  */
1248            fi->type = ARMFault_Permission;
1249            goto do_fault;
1250        }
1251    }
1252    result->f.attrs.space = out_space;
1253    result->f.attrs.secure = arm_space_is_secure(out_space);
1254    result->f.phys_addr = phys_addr;
1255    return false;
1256do_fault:
1257    fi->domain = domain;
1258    fi->level = level;
1259    return true;
1260}
1261
1262/*
1263 * Translate S2 section/page access permissions to protection flags
1264 * @env:     CPUARMState
1265 * @s2ap:    The 2-bit stage2 access permissions (S2AP)
1266 * @xn:      XN (execute-never) bits
1267 * @s1_is_el0: true if this is S2 of an S1+2 walk for EL0
1268 */
1269static int get_S2prot_noexecute(int s2ap)
1270{
1271    int prot = 0;
1272
1273    if (s2ap & 1) {
1274        prot |= PAGE_READ;
1275    }
1276    if (s2ap & 2) {
1277        prot |= PAGE_WRITE;
1278    }
1279    return prot;
1280}
1281
1282static int get_S2prot(CPUARMState *env, int s2ap, int xn, bool s1_is_el0)
1283{
1284    int prot = get_S2prot_noexecute(s2ap);
1285
1286    if (cpu_isar_feature(any_tts2uxn, env_archcpu(env))) {
1287        switch (xn) {
1288        case 0:
1289            prot |= PAGE_EXEC;
1290            break;
1291        case 1:
1292            if (s1_is_el0) {
1293                prot |= PAGE_EXEC;
1294            }
1295            break;
1296        case 2:
1297            break;
1298        case 3:
1299            if (!s1_is_el0) {
1300                prot |= PAGE_EXEC;
1301            }
1302            break;
1303        default:
1304            g_assert_not_reached();
1305        }
1306    } else {
1307        if (!extract32(xn, 1, 1)) {
1308            if (arm_el_is_aa64(env, 2) || prot & PAGE_READ) {
1309                prot |= PAGE_EXEC;
1310            }
1311        }
1312    }
1313    return prot;
1314}
1315
1316/*
1317 * Translate section/page access permissions to protection flags
1318 * @env:     CPUARMState
1319 * @mmu_idx: MMU index indicating required translation regime
1320 * @is_aa64: TRUE if AArch64
1321 * @user_rw: Translated AP for user access
1322 * @prot_rw: Translated AP for privileged access
1323 * @xn:      XN (execute-never) bit
1324 * @pxn:     PXN (privileged execute-never) bit
1325 * @in_pa:   The original input pa space
1326 * @out_pa:  The output pa space, modified by NSTable, NS, and NSE
1327 */
1328static int get_S1prot(CPUARMState *env, ARMMMUIdx mmu_idx, bool is_aa64,
1329                      int user_rw, int prot_rw, int xn, int pxn,
1330                      ARMSecuritySpace in_pa, ARMSecuritySpace out_pa)
1331{
1332    ARMCPU *cpu = env_archcpu(env);
1333    bool is_user = regime_is_user(env, mmu_idx);
1334    bool have_wxn;
1335    int wxn = 0;
1336
1337    assert(!regime_is_stage2(mmu_idx));
1338
1339    if (is_user) {
1340        prot_rw = user_rw;
1341    } else {
1342        /*
1343         * PAN controls can forbid data accesses but don't affect insn fetch.
1344         * Plain PAN forbids data accesses if EL0 has data permissions;
1345         * PAN3 forbids data accesses if EL0 has either data or exec perms.
1346         * Note that for AArch64 the 'user can exec' case is exactly !xn.
1347         * We make the IMPDEF choices that SCR_EL3.SIF and Realm EL2&0
1348         * do not affect EPAN.
1349         */
1350        if (user_rw && regime_is_pan(env, mmu_idx)) {
1351            prot_rw = 0;
1352        } else if (cpu_isar_feature(aa64_pan3, cpu) && is_aa64 &&
1353                   regime_is_pan(env, mmu_idx) &&
1354                   (regime_sctlr(env, mmu_idx) & SCTLR_EPAN) && !xn) {
1355            prot_rw = 0;
1356        }
1357    }
1358
1359    if (in_pa != out_pa) {
1360        switch (in_pa) {
1361        case ARMSS_Root:
1362            /*
1363             * R_ZWRVD: permission fault for insn fetched from non-Root,
1364             * I_WWBFB: SIF has no effect in EL3.
1365             */
1366            return prot_rw;
1367        case ARMSS_Realm:
1368            /*
1369             * R_PKTDS: permission fault for insn fetched from non-Realm,
1370             * for Realm EL2 or EL2&0.  The corresponding fault for EL1&0
1371             * happens during any stage2 translation.
1372             */
1373            switch (mmu_idx) {
1374            case ARMMMUIdx_E2:
1375            case ARMMMUIdx_E20_0:
1376            case ARMMMUIdx_E20_2:
1377            case ARMMMUIdx_E20_2_PAN:
1378                return prot_rw;
1379            default:
1380                break;
1381            }
1382            break;
1383        case ARMSS_Secure:
1384            if (env->cp15.scr_el3 & SCR_SIF) {
1385                return prot_rw;
1386            }
1387            break;
1388        default:
1389            /* Input NonSecure must have output NonSecure. */
1390            g_assert_not_reached();
1391        }
1392    }
1393
1394    /* TODO have_wxn should be replaced with
1395     *   ARM_FEATURE_V8 || (ARM_FEATURE_V7 && ARM_FEATURE_EL2)
1396     * when ARM_FEATURE_EL2 starts getting set. For now we assume all LPAE
1397     * compatible processors have EL2, which is required for [U]WXN.
1398     */
1399    have_wxn = arm_feature(env, ARM_FEATURE_LPAE);
1400
1401    if (have_wxn) {
1402        wxn = regime_sctlr(env, mmu_idx) & SCTLR_WXN;
1403    }
1404
1405    if (is_aa64) {
1406        if (regime_has_2_ranges(mmu_idx) && !is_user) {
1407            xn = pxn || (user_rw & PAGE_WRITE);
1408        }
1409    } else if (arm_feature(env, ARM_FEATURE_V7)) {
1410        switch (regime_el(env, mmu_idx)) {
1411        case 1:
1412        case 3:
1413            if (is_user) {
1414                xn = xn || !(user_rw & PAGE_READ);
1415            } else {
1416                int uwxn = 0;
1417                if (have_wxn) {
1418                    uwxn = regime_sctlr(env, mmu_idx) & SCTLR_UWXN;
1419                }
1420                xn = xn || !(prot_rw & PAGE_READ) || pxn ||
1421                     (uwxn && (user_rw & PAGE_WRITE));
1422            }
1423            break;
1424        case 2:
1425            break;
1426        }
1427    } else {
1428        xn = wxn = 0;
1429    }
1430
1431    if (xn || (wxn && (prot_rw & PAGE_WRITE))) {
1432        return prot_rw;
1433    }
1434    return prot_rw | PAGE_EXEC;
1435}
1436
1437static ARMVAParameters aa32_va_parameters(CPUARMState *env, uint32_t va,
1438                                          ARMMMUIdx mmu_idx)
1439{
1440    uint64_t tcr = regime_tcr(env, mmu_idx);
1441    uint32_t el = regime_el(env, mmu_idx);
1442    int select, tsz;
1443    bool epd, hpd;
1444
1445    assert(mmu_idx != ARMMMUIdx_Stage2_S);
1446
1447    if (mmu_idx == ARMMMUIdx_Stage2) {
1448        /* VTCR */
1449        bool sext = extract32(tcr, 4, 1);
1450        bool sign = extract32(tcr, 3, 1);
1451
1452        /*
1453         * If the sign-extend bit is not the same as t0sz[3], the result
1454         * is unpredictable. Flag this as a guest error.
1455         */
1456        if (sign != sext) {
1457            qemu_log_mask(LOG_GUEST_ERROR,
1458                          "AArch32: VTCR.S / VTCR.T0SZ[3] mismatch\n");
1459        }
1460        tsz = sextract32(tcr, 0, 4) + 8;
1461        select = 0;
1462        hpd = false;
1463        epd = false;
1464    } else if (el == 2) {
1465        /* HTCR */
1466        tsz = extract32(tcr, 0, 3);
1467        select = 0;
1468        hpd = extract64(tcr, 24, 1);
1469        epd = false;
1470    } else {
1471        int t0sz = extract32(tcr, 0, 3);
1472        int t1sz = extract32(tcr, 16, 3);
1473
1474        if (t1sz == 0) {
1475            select = va > (0xffffffffu >> t0sz);
1476        } else {
1477            /* Note that we will detect errors later.  */
1478            select = va >= ~(0xffffffffu >> t1sz);
1479        }
1480        if (!select) {
1481            tsz = t0sz;
1482            epd = extract32(tcr, 7, 1);
1483            hpd = extract64(tcr, 41, 1);
1484        } else {
1485            tsz = t1sz;
1486            epd = extract32(tcr, 23, 1);
1487            hpd = extract64(tcr, 42, 1);
1488        }
1489        /* For aarch32, hpd0 is not enabled without t2e as well.  */
1490        hpd &= extract32(tcr, 6, 1);
1491    }
1492
1493    return (ARMVAParameters) {
1494        .tsz = tsz,
1495        .select = select,
1496        .epd = epd,
1497        .hpd = hpd,
1498    };
1499}
1500
1501/*
1502 * check_s2_mmu_setup
1503 * @cpu:        ARMCPU
1504 * @is_aa64:    True if the translation regime is in AArch64 state
1505 * @tcr:        VTCR_EL2 or VSTCR_EL2
1506 * @ds:         Effective value of TCR.DS.
1507 * @iasize:     Bitsize of IPAs
1508 * @stride:     Page-table stride (See the ARM ARM)
1509 *
1510 * Decode the starting level of the S2 lookup, returning INT_MIN if
1511 * the configuration is invalid.
1512 */
1513static int check_s2_mmu_setup(ARMCPU *cpu, bool is_aa64, uint64_t tcr,
1514                              bool ds, int iasize, int stride)
1515{
1516    int sl0, sl2, startlevel, granulebits, levels;
1517    int s1_min_iasize, s1_max_iasize;
1518
1519    sl0 = extract32(tcr, 6, 2);
1520    if (is_aa64) {
1521        /*
1522         * AArch64.S2InvalidSL: Interpretation of SL depends on the page size,
1523         * so interleave AArch64.S2StartLevel.
1524         */
1525        switch (stride) {
1526        case 9: /* 4KB */
1527            /* SL2 is RES0 unless DS=1 & 4KB granule. */
1528            sl2 = extract64(tcr, 33, 1);
1529            if (ds && sl2) {
1530                if (sl0 != 0) {
1531                    goto fail;
1532                }
1533                startlevel = -1;
1534            } else {
1535                startlevel = 2 - sl0;
1536                switch (sl0) {
1537                case 2:
1538                    if (arm_pamax(cpu) < 44) {
1539                        goto fail;
1540                    }
1541                    break;
1542                case 3:
1543                    if (!cpu_isar_feature(aa64_st, cpu)) {
1544                        goto fail;
1545                    }
1546                    startlevel = 3;
1547                    break;
1548                }
1549            }
1550            break;
1551        case 11: /* 16KB */
1552            switch (sl0) {
1553            case 2:
1554                if (arm_pamax(cpu) < 42) {
1555                    goto fail;
1556                }
1557                break;
1558            case 3:
1559                if (!ds) {
1560                    goto fail;
1561                }
1562                break;
1563            }
1564            startlevel = 3 - sl0;
1565            break;
1566        case 13: /* 64KB */
1567            switch (sl0) {
1568            case 2:
1569                if (arm_pamax(cpu) < 44) {
1570                    goto fail;
1571                }
1572                break;
1573            case 3:
1574                goto fail;
1575            }
1576            startlevel = 3 - sl0;
1577            break;
1578        default:
1579            g_assert_not_reached();
1580        }
1581    } else {
1582        /*
1583         * Things are simpler for AArch32 EL2, with only 4k pages.
1584         * There is no separate S2InvalidSL function, but AArch32.S2Walk
1585         * begins with walkparms.sl0 in {'1x'}.
1586         */
1587        assert(stride == 9);
1588        if (sl0 >= 2) {
1589            goto fail;
1590        }
1591        startlevel = 2 - sl0;
1592    }
1593
1594    /* AArch{64,32}.S2InconsistentSL are functionally equivalent.  */
1595    levels = 3 - startlevel;
1596    granulebits = stride + 3;
1597
1598    s1_min_iasize = levels * stride + granulebits + 1;
1599    s1_max_iasize = s1_min_iasize + (stride - 1) + 4;
1600
1601    if (iasize >= s1_min_iasize && iasize <= s1_max_iasize) {
1602        return startlevel;
1603    }
1604
1605 fail:
1606    return INT_MIN;
1607}
1608
1609static bool lpae_block_desc_valid(ARMCPU *cpu, bool ds,
1610                                  ARMGranuleSize gran, int level)
1611{
1612    /*
1613     * See pseudocode AArch46.BlockDescSupported(): block descriptors
1614     * are not valid at all levels, depending on the page size.
1615     */
1616    switch (gran) {
1617    case Gran4K:
1618        return (level == 0 && ds) || level == 1 || level == 2;
1619    case Gran16K:
1620        return (level == 1 && ds) || level == 2;
1621    case Gran64K:
1622        return (level == 1 && arm_pamax(cpu) == 52) || level == 2;
1623    default:
1624        g_assert_not_reached();
1625    }
1626}
1627
1628static bool nv_nv1_enabled(CPUARMState *env, S1Translate *ptw)
1629{
1630    uint64_t hcr = arm_hcr_el2_eff_secstate(env, ptw->in_space);
1631    return (hcr & (HCR_NV | HCR_NV1)) == (HCR_NV | HCR_NV1);
1632}
1633
1634/**
1635 * get_phys_addr_lpae: perform one stage of page table walk, LPAE format
1636 *
1637 * Returns false if the translation was successful. Otherwise, phys_ptr,
1638 * attrs, prot and page_size may not be filled in, and the populated fsr
1639 * value provides information on why the translation aborted, in the format
1640 * of a long-format DFSR/IFSR fault register, with the following caveat:
1641 * the WnR bit is never set (the caller must do this).
1642 *
1643 * @env: CPUARMState
1644 * @ptw: Current and next stage parameters for the walk.
1645 * @address: virtual address to get physical address for
1646 * @access_type: MMU_DATA_LOAD, MMU_DATA_STORE or MMU_INST_FETCH
1647 * @memop: memory operation feeding this access, or 0 for none
1648 * @result: set on translation success,
1649 * @fi: set to fault info if the translation fails
1650 */
1651static bool get_phys_addr_lpae(CPUARMState *env, S1Translate *ptw,
1652                               uint64_t address,
1653                               MMUAccessType access_type, MemOp memop,
1654                               GetPhysAddrResult *result, ARMMMUFaultInfo *fi)
1655{
1656    ARMCPU *cpu = env_archcpu(env);
1657    ARMMMUIdx mmu_idx = ptw->in_mmu_idx;
1658    int32_t level;
1659    ARMVAParameters param;
1660    uint64_t ttbr;
1661    hwaddr descaddr, indexmask, indexmask_grainsize;
1662    uint32_t tableattrs;
1663    uint64_t page_size;
1664    uint64_t attrs;
1665    int32_t stride;
1666    int addrsize, inputsize, outputsize;
1667    uint64_t tcr = regime_tcr(env, mmu_idx);
1668    int ap, xn, pxn;
1669    uint32_t el = regime_el(env, mmu_idx);
1670    uint64_t descaddrmask;
1671    bool aarch64 = arm_el_is_aa64(env, el);
1672    uint64_t descriptor, new_descriptor;
1673    ARMSecuritySpace out_space;
1674    bool device;
1675
1676    /* TODO: This code does not support shareability levels. */
1677    if (aarch64) {
1678        int ps;
1679
1680        param = aa64_va_parameters(env, address, mmu_idx,
1681                                   access_type != MMU_INST_FETCH,
1682                                   !arm_el_is_aa64(env, 1));
1683        level = 0;
1684
1685        /*
1686         * If TxSZ is programmed to a value larger than the maximum,
1687         * or smaller than the effective minimum, it is IMPLEMENTATION
1688         * DEFINED whether we behave as if the field were programmed
1689         * within bounds, or if a level 0 Translation fault is generated.
1690         *
1691         * With FEAT_LVA, fault on less than minimum becomes required,
1692         * so our choice is to always raise the fault.
1693         */
1694        if (param.tsz_oob) {
1695            goto do_translation_fault;
1696        }
1697
1698        addrsize = 64 - 8 * param.tbi;
1699        inputsize = 64 - param.tsz;
1700
1701        /*
1702         * Bound PS by PARANGE to find the effective output address size.
1703         * ID_AA64MMFR0 is a read-only register so values outside of the
1704         * supported mappings can be considered an implementation error.
1705         */
1706        ps = FIELD_EX64_IDREG(&cpu->isar, ID_AA64MMFR0, PARANGE);
1707        ps = MIN(ps, param.ps);
1708        assert(ps < ARRAY_SIZE(pamax_map));
1709        outputsize = pamax_map[ps];
1710
1711        /*
1712         * With LPA2, the effective output address (OA) size is at most 48 bits
1713         * unless TCR.DS == 1
1714         */
1715        if (!param.ds && param.gran != Gran64K) {
1716            outputsize = MIN(outputsize, 48);
1717        }
1718    } else {
1719        param = aa32_va_parameters(env, address, mmu_idx);
1720        level = 1;
1721        addrsize = (mmu_idx == ARMMMUIdx_Stage2 ? 40 : 32);
1722        inputsize = addrsize - param.tsz;
1723        outputsize = 40;
1724    }
1725
1726    /*
1727     * We determined the region when collecting the parameters, but we
1728     * have not yet validated that the address is valid for the region.
1729     * Extract the top bits and verify that they all match select.
1730     *
1731     * For aa32, if inputsize == addrsize, then we have selected the
1732     * region by exclusion in aa32_va_parameters and there is no more
1733     * validation to do here.
1734     */
1735    if (inputsize < addrsize) {
1736        uint64_t top_bits = sextract64(address, inputsize,
1737                                           addrsize - inputsize);
1738        if (-top_bits != param.select) {
1739            /* The gap between the two regions is a Translation fault */
1740            goto do_translation_fault;
1741        }
1742    }
1743
1744    stride = arm_granule_bits(param.gran) - 3;
1745
1746    /*
1747     * Note that QEMU ignores shareability and cacheability attributes,
1748     * so we don't need to do anything with the SH, ORGN, IRGN fields
1749     * in the TTBCR.  Similarly, TTBCR:A1 selects whether we get the
1750     * ASID from TTBR0 or TTBR1, but QEMU's TLB doesn't currently
1751     * implement any ASID-like capability so we can ignore it (instead
1752     * we will always flush the TLB any time the ASID is changed).
1753     */
1754    ttbr = regime_ttbr(env, mmu_idx, param.select);
1755
1756    /*
1757     * Here we should have set up all the parameters for the translation:
1758     * inputsize, ttbr, epd, stride, tbi
1759     */
1760
1761    if (param.epd) {
1762        /*
1763         * Translation table walk disabled => Translation fault on TLB miss
1764         * Note: This is always 0 on 64-bit EL2 and EL3.
1765         */
1766        goto do_translation_fault;
1767    }
1768
1769    if (!regime_is_stage2(mmu_idx)) {
1770        /*
1771         * The starting level depends on the virtual address size (which can
1772         * be up to 48 bits) and the translation granule size. It indicates
1773         * the number of strides (stride bits at a time) needed to
1774         * consume the bits of the input address. In the pseudocode this is:
1775         *  level = 4 - RoundUp((inputsize - grainsize) / stride)
1776         * where their 'inputsize' is our 'inputsize', 'grainsize' is
1777         * our 'stride + 3' and 'stride' is our 'stride'.
1778         * Applying the usual "rounded up m/n is (m+n-1)/n" and simplifying:
1779         * = 4 - (inputsize - stride - 3 + stride - 1) / stride
1780         * = 4 - (inputsize - 4) / stride;
1781         */
1782        level = 4 - (inputsize - 4) / stride;
1783    } else {
1784        int startlevel = check_s2_mmu_setup(cpu, aarch64, tcr, param.ds,
1785                                            inputsize, stride);
1786        if (startlevel == INT_MIN) {
1787            level = 0;
1788            goto do_translation_fault;
1789        }
1790        level = startlevel;
1791    }
1792
1793    indexmask_grainsize = MAKE_64BIT_MASK(0, stride + 3);
1794    indexmask = MAKE_64BIT_MASK(0, inputsize - (stride * (4 - level)));
1795
1796    /* Now we can extract the actual base address from the TTBR */
1797    descaddr = extract64(ttbr, 0, 48);
1798
1799    /*
1800     * For FEAT_LPA and PS=6, bits [51:48] of descaddr are in [5:2] of TTBR.
1801     *
1802     * Otherwise, if the base address is out of range, raise AddressSizeFault.
1803     * In the pseudocode, this is !IsZero(baseregister<47:outputsize>),
1804     * but we've just cleared the bits above 47, so simplify the test.
1805     */
1806    if (outputsize > 48) {
1807        descaddr |= extract64(ttbr, 2, 4) << 48;
1808    } else if (descaddr >> outputsize) {
1809        level = 0;
1810        fi->type = ARMFault_AddressSize;
1811        goto do_fault;
1812    }
1813
1814    /*
1815     * We rely on this masking to clear the RES0 bits at the bottom of the TTBR
1816     * and also to mask out CnP (bit 0) which could validly be non-zero.
1817     */
1818    descaddr &= ~indexmask;
1819
1820    /*
1821     * For AArch32, the address field in the descriptor goes up to bit 39
1822     * for both v7 and v8.  However, for v8 the SBZ bits [47:40] must be 0
1823     * or an AddressSize fault is raised.  So for v8 we extract those SBZ
1824     * bits as part of the address, which will be checked via outputsize.
1825     * For AArch64, the address field goes up to bit 47, or 49 with FEAT_LPA2;
1826     * the highest bits of a 52-bit output are placed elsewhere.
1827     */
1828    if (param.ds) {
1829        descaddrmask = MAKE_64BIT_MASK(0, 50);
1830    } else if (arm_feature(env, ARM_FEATURE_V8)) {
1831        descaddrmask = MAKE_64BIT_MASK(0, 48);
1832    } else {
1833        descaddrmask = MAKE_64BIT_MASK(0, 40);
1834    }
1835    descaddrmask &= ~indexmask_grainsize;
1836    tableattrs = 0;
1837
1838 next_level:
1839    descaddr |= (address >> (stride * (4 - level))) & indexmask;
1840    descaddr &= ~7ULL;
1841
1842    /*
1843     * Process the NSTable bit from the previous level.  This changes
1844     * the table address space and the output space from Secure to
1845     * NonSecure.  With RME, the EL3 translation regime does not change
1846     * from Root to NonSecure.
1847     */
1848    if (ptw->in_space == ARMSS_Secure
1849        && !regime_is_stage2(mmu_idx)
1850        && extract32(tableattrs, 4, 1)) {
1851        /*
1852         * Stage2_S -> Stage2 or Phys_S -> Phys_NS
1853         * Assert the relative order of the secure/non-secure indexes.
1854         */
1855        QEMU_BUILD_BUG_ON(ARMMMUIdx_Phys_S + 1 != ARMMMUIdx_Phys_NS);
1856        QEMU_BUILD_BUG_ON(ARMMMUIdx_Stage2_S + 1 != ARMMMUIdx_Stage2);
1857        ptw->in_ptw_idx += 1;
1858        ptw->in_space = ARMSS_NonSecure;
1859    }
1860
1861    if (!S1_ptw_translate(env, ptw, descaddr, fi)) {
1862        goto do_fault;
1863    }
1864    descriptor = arm_ldq_ptw(env, ptw, fi);
1865    if (fi->type != ARMFault_None) {
1866        goto do_fault;
1867    }
1868    new_descriptor = descriptor;
1869
1870 restart_atomic_update:
1871    if (!(descriptor & 1) ||
1872        (!(descriptor & 2) &&
1873         !lpae_block_desc_valid(cpu, param.ds, param.gran, level))) {
1874        /* Invalid, or a block descriptor at an invalid level */
1875        goto do_translation_fault;
1876    }
1877
1878    descaddr = descriptor & descaddrmask;
1879
1880    /*
1881     * For FEAT_LPA and PS=6, bits [51:48] of descaddr are in [15:12]
1882     * of descriptor.  For FEAT_LPA2 and effective DS, bits [51:50] of
1883     * descaddr are in [9:8].  Otherwise, if descaddr is out of range,
1884     * raise AddressSizeFault.
1885     */
1886    if (outputsize > 48) {
1887        if (param.ds) {
1888            descaddr |= extract64(descriptor, 8, 2) << 50;
1889        } else {
1890            descaddr |= extract64(descriptor, 12, 4) << 48;
1891        }
1892    } else if (descaddr >> outputsize) {
1893        fi->type = ARMFault_AddressSize;
1894        goto do_fault;
1895    }
1896
1897    if ((descriptor & 2) && (level < 3)) {
1898        /*
1899         * Table entry. The top five bits are attributes which may
1900         * propagate down through lower levels of the table (and
1901         * which are all arranged so that 0 means "no effect", so
1902         * we can gather them up by ORing in the bits at each level).
1903         */
1904        tableattrs |= extract64(descriptor, 59, 5);
1905        level++;
1906        indexmask = indexmask_grainsize;
1907        goto next_level;
1908    }
1909
1910    /*
1911     * Block entry at level 1 or 2, or page entry at level 3.
1912     * These are basically the same thing, although the number
1913     * of bits we pull in from the vaddr varies. Note that although
1914     * descaddrmask masks enough of the low bits of the descriptor
1915     * to give a correct page or table address, the address field
1916     * in a block descriptor is smaller; so we need to explicitly
1917     * clear the lower bits here before ORing in the low vaddr bits.
1918     *
1919     * Afterward, descaddr is the final physical address.
1920     */
1921    page_size = (1ULL << ((stride * (4 - level)) + 3));
1922    descaddr &= ~(hwaddr)(page_size - 1);
1923    descaddr |= (address & (page_size - 1));
1924
1925    if (likely(!ptw->in_debug)) {
1926        /*
1927         * Access flag.
1928         * If HA is enabled, prepare to update the descriptor below.
1929         * Otherwise, pass the access fault on to software.
1930         */
1931        if (!(descriptor & (1 << 10))) {
1932            if (param.ha) {
1933                new_descriptor |= 1 << 10; /* AF */
1934            } else {
1935                fi->type = ARMFault_AccessFlag;
1936                goto do_fault;
1937            }
1938        }
1939
1940        /*
1941         * Dirty Bit.
1942         * If HD is enabled, pre-emptively set/clear the appropriate AP/S2AP
1943         * bit for writeback. The actual write protection test may still be
1944         * overridden by tableattrs, to be merged below.
1945         */
1946        if (param.hd
1947            && extract64(descriptor, 51, 1)  /* DBM */
1948            && access_type == MMU_DATA_STORE) {
1949            if (regime_is_stage2(mmu_idx)) {
1950                new_descriptor |= 1ull << 7;    /* set S2AP[1] */
1951            } else {
1952                new_descriptor &= ~(1ull << 7); /* clear AP[2] */
1953            }
1954        }
1955    }
1956
1957    /*
1958     * Extract attributes from the (modified) descriptor, and apply
1959     * table descriptors. Stage 2 table descriptors do not include
1960     * any attribute fields. HPD disables all the table attributes
1961     * except NSTable (which we have already handled).
1962     */
1963    attrs = new_descriptor & (MAKE_64BIT_MASK(2, 10) | MAKE_64BIT_MASK(50, 14));
1964    if (!regime_is_stage2(mmu_idx)) {
1965        if (!param.hpd) {
1966            attrs |= extract64(tableattrs, 0, 2) << 53;     /* XN, PXN */
1967            /*
1968             * The sense of AP[1] vs APTable[0] is reversed, as APTable[0] == 1
1969             * means "force PL1 access only", which means forcing AP[1] to 0.
1970             */
1971            attrs &= ~(extract64(tableattrs, 2, 1) << 6); /* !APT[0] => AP[1] */
1972            attrs |= extract32(tableattrs, 3, 1) << 7;    /* APT[1] => AP[2] */
1973        }
1974    }
1975
1976    ap = extract32(attrs, 6, 2);
1977    out_space = ptw->in_space;
1978    if (regime_is_stage2(mmu_idx)) {
1979        /*
1980         * R_GYNXY: For stage2 in Realm security state, bit 55 is NS.
1981         * The bit remains ignored for other security states.
1982         * R_YMCSL: Executing an insn fetched from non-Realm causes
1983         * a stage2 permission fault.
1984         */
1985        if (out_space == ARMSS_Realm && extract64(attrs, 55, 1)) {
1986            out_space = ARMSS_NonSecure;
1987            result->f.prot = get_S2prot_noexecute(ap);
1988        } else {
1989            xn = extract64(attrs, 53, 2);
1990            result->f.prot = get_S2prot(env, ap, xn, ptw->in_s1_is_el0);
1991        }
1992
1993        result->cacheattrs.is_s2_format = true;
1994        result->cacheattrs.attrs = extract32(attrs, 2, 4);
1995        /*
1996         * Security state does not really affect HCR_EL2.FWB;
1997         * we only need to filter FWB for aa32 or other FEAT.
1998         */
1999        device = S2_attrs_are_device(arm_hcr_el2_eff(env),
2000                                     result->cacheattrs.attrs);
2001    } else {
2002        int nse, ns = extract32(attrs, 5, 1);
2003        uint8_t attrindx;
2004        uint64_t mair;
2005        int user_rw, prot_rw;
2006
2007        switch (out_space) {
2008        case ARMSS_Root:
2009            /*
2010             * R_GVZML: Bit 11 becomes the NSE field in the EL3 regime.
2011             * R_XTYPW: NSE and NS together select the output pa space.
2012             */
2013            nse = extract32(attrs, 11, 1);
2014            out_space = (nse << 1) | ns;
2015            if (out_space == ARMSS_Secure &&
2016                !cpu_isar_feature(aa64_sel2, cpu)) {
2017                out_space = ARMSS_NonSecure;
2018            }
2019            break;
2020        case ARMSS_Secure:
2021            if (ns) {
2022                out_space = ARMSS_NonSecure;
2023            }
2024            break;
2025        case ARMSS_Realm:
2026            switch (mmu_idx) {
2027            case ARMMMUIdx_Stage1_E0:
2028            case ARMMMUIdx_Stage1_E1:
2029            case ARMMMUIdx_Stage1_E1_PAN:
2030                /* I_CZPRF: For Realm EL1&0 stage1, NS bit is RES0. */
2031                break;
2032            case ARMMMUIdx_E2:
2033            case ARMMMUIdx_E20_0:
2034            case ARMMMUIdx_E20_2:
2035            case ARMMMUIdx_E20_2_PAN:
2036                /*
2037                 * R_LYKFZ, R_WGRZN: For Realm EL2 and EL2&1,
2038                 * NS changes the output to non-secure space.
2039                 */
2040                if (ns) {
2041                    out_space = ARMSS_NonSecure;
2042                }
2043                break;
2044            default:
2045                g_assert_not_reached();
2046            }
2047            break;
2048        case ARMSS_NonSecure:
2049            /* R_QRMFF: For NonSecure state, the NS bit is RES0. */
2050            break;
2051        default:
2052            g_assert_not_reached();
2053        }
2054        xn = extract64(attrs, 54, 1);
2055        pxn = extract64(attrs, 53, 1);
2056
2057        if (el == 1 && nv_nv1_enabled(env, ptw)) {
2058            /*
2059             * With FEAT_NV, when HCR_EL2.{NV,NV1} == {1,1}, the block/page
2060             * descriptor bit 54 holds PXN, 53 is RES0, and the effective value
2061             * of UXN is 0. Similarly for bits 59 and 60 in table descriptors
2062             * (which we have already folded into bits 53 and 54 of attrs).
2063             * AP[1] (descriptor bit 6, our ap bit 0) is treated as 0.
2064             * Similarly, APTable[0] from the table descriptor is treated as 0;
2065             * we already folded this into AP[1] and squashing that to 0 does
2066             * the right thing.
2067             */
2068            pxn = xn;
2069            xn = 0;
2070            ap &= ~1;
2071        }
2072
2073        user_rw = simple_ap_to_rw_prot_is_user(ap, true);
2074        prot_rw = simple_ap_to_rw_prot_is_user(ap, false);
2075        /*
2076         * Note that we modified ptw->in_space earlier for NSTable, but
2077         * result->f.attrs retains a copy of the original security space.
2078         */
2079        result->f.prot = get_S1prot(env, mmu_idx, aarch64, user_rw, prot_rw,
2080                                    xn, pxn, result->f.attrs.space, out_space);
2081
2082        /* Index into MAIR registers for cache attributes */
2083        attrindx = extract32(attrs, 2, 3);
2084        mair = env->cp15.mair_el[regime_el(env, mmu_idx)];
2085        assert(attrindx <= 7);
2086        result->cacheattrs.is_s2_format = false;
2087        result->cacheattrs.attrs = extract64(mair, attrindx * 8, 8);
2088
2089        /* When in aarch64 mode, and BTI is enabled, remember GP in the TLB. */
2090        if (aarch64 && cpu_isar_feature(aa64_bti, cpu)) {
2091            result->f.extra.arm.guarded = extract64(attrs, 50, 1); /* GP */
2092        }
2093        device = S1_attrs_are_device(result->cacheattrs.attrs);
2094    }
2095
2096    /*
2097     * Enable alignment checks on Device memory.
2098     *
2099     * Per R_XCHFJ, the correct ordering for alignment, permission,
2100     * and stage 2 faults is:
2101     *    - Alignment fault caused by the memory type
2102     *    - Permission fault
2103     *    - A stage 2 fault on the memory access
2104     * Perform the alignment check now, so that we recognize it in
2105     * the correct order.  Set TLB_CHECK_ALIGNED so that any subsequent
2106     * softmmu tlb hit will also check the alignment; clear along the
2107     * non-device path so that tlb_fill_flags is consistent in the
2108     * event of restart_atomic_update.
2109     *
2110     * In v7, for a CPU without the Virtualization Extensions this
2111     * access is UNPREDICTABLE; we choose to make it take the alignment
2112     * fault as is required for a v7VE CPU. (QEMU doesn't emulate any
2113     * CPUs with ARM_FEATURE_LPAE but not ARM_FEATURE_V7VE anyway.)
2114     */
2115    if (device) {
2116        unsigned a_bits = memop_atomicity_bits(memop);
2117        if (address & ((1 << a_bits) - 1)) {
2118            fi->type = ARMFault_Alignment;
2119            goto do_fault;
2120        }
2121        result->f.tlb_fill_flags = TLB_CHECK_ALIGNED;
2122    } else {
2123        result->f.tlb_fill_flags = 0;
2124    }
2125
2126    if (!(result->f.prot & (1 << access_type))) {
2127        fi->type = ARMFault_Permission;
2128        goto do_fault;
2129    }
2130
2131    /* If FEAT_HAFDBS has made changes, update the PTE. */
2132    if (new_descriptor != descriptor) {
2133        new_descriptor = arm_casq_ptw(env, descriptor, new_descriptor, ptw, fi);
2134        if (fi->type != ARMFault_None) {
2135            goto do_fault;
2136        }
2137        /*
2138         * I_YZSVV says that if the in-memory descriptor has changed,
2139         * then we must use the information in that new value
2140         * (which might include a different output address, different
2141         * attributes, or generate a fault).
2142         * Restart the handling of the descriptor value from scratch.
2143         */
2144        if (new_descriptor != descriptor) {
2145            descriptor = new_descriptor;
2146            goto restart_atomic_update;
2147        }
2148    }
2149
2150    result->f.attrs.space = out_space;
2151    result->f.attrs.secure = arm_space_is_secure(out_space);
2152
2153    /*
2154     * For FEAT_LPA2 and effective DS, the SH field in the attributes
2155     * was re-purposed for output address bits.  The SH attribute in
2156     * that case comes from TCR_ELx, which we extracted earlier.
2157     */
2158    if (param.ds) {
2159        result->cacheattrs.shareability = param.sh;
2160    } else {
2161        result->cacheattrs.shareability = extract32(attrs, 8, 2);
2162    }
2163
2164    result->f.phys_addr = descaddr;
2165    result->f.lg_page_size = ctz64(page_size);
2166    return false;
2167
2168 do_translation_fault:
2169    fi->type = ARMFault_Translation;
2170 do_fault:
2171    if (fi->s1ptw) {
2172        /* Retain the existing stage 2 fi->level */
2173        assert(fi->stage2);
2174    } else {
2175        fi->level = level;
2176        fi->stage2 = regime_is_stage2(mmu_idx);
2177    }
2178    fi->s1ns = fault_s1ns(ptw->in_space, mmu_idx);
2179    return true;
2180}
2181
2182static bool get_phys_addr_pmsav5(CPUARMState *env,
2183                                 S1Translate *ptw,
2184                                 uint32_t address,
2185                                 MMUAccessType access_type,
2186                                 GetPhysAddrResult *result,
2187                                 ARMMMUFaultInfo *fi)
2188{
2189    int n;
2190    uint32_t mask;
2191    uint32_t base;
2192    ARMMMUIdx mmu_idx = ptw->in_mmu_idx;
2193    bool is_user = regime_is_user(env, mmu_idx);
2194
2195    if (regime_translation_disabled(env, mmu_idx, ptw->in_space)) {
2196        /* MPU disabled.  */
2197        result->f.phys_addr = address;
2198        result->f.prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
2199        return false;
2200    }
2201
2202    result->f.phys_addr = address;
2203    for (n = 7; n >= 0; n--) {
2204        base = env->cp15.c6_region[n];
2205        if ((base & 1) == 0) {
2206            continue;
2207        }
2208        mask = 1 << ((base >> 1) & 0x1f);
2209        /* Keep this shift separate from the above to avoid an
2210           (undefined) << 32.  */
2211        mask = (mask << 1) - 1;
2212        if (((base ^ address) & ~mask) == 0) {
2213            break;
2214        }
2215    }
2216    if (n < 0) {
2217        fi->type = ARMFault_Background;
2218        return true;
2219    }
2220
2221    if (access_type == MMU_INST_FETCH) {
2222        mask = env->cp15.pmsav5_insn_ap;
2223    } else {
2224        mask = env->cp15.pmsav5_data_ap;
2225    }
2226    mask = (mask >> (n * 4)) & 0xf;
2227    switch (mask) {
2228    case 0:
2229        fi->type = ARMFault_Permission;
2230        fi->level = 1;
2231        return true;
2232    case 1:
2233        if (is_user) {
2234            fi->type = ARMFault_Permission;
2235            fi->level = 1;
2236            return true;
2237        }
2238        result->f.prot = PAGE_READ | PAGE_WRITE;
2239        break;
2240    case 2:
2241        result->f.prot = PAGE_READ;
2242        if (!is_user) {
2243            result->f.prot |= PAGE_WRITE;
2244        }
2245        break;
2246    case 3:
2247        result->f.prot = PAGE_READ | PAGE_WRITE;
2248        break;
2249    case 5:
2250        if (is_user) {
2251            fi->type = ARMFault_Permission;
2252            fi->level = 1;
2253            return true;
2254        }
2255        result->f.prot = PAGE_READ;
2256        break;
2257    case 6:
2258        result->f.prot = PAGE_READ;
2259        break;
2260    default:
2261        /* Bad permission.  */
2262        fi->type = ARMFault_Permission;
2263        fi->level = 1;
2264        return true;
2265    }
2266    result->f.prot |= PAGE_EXEC;
2267    return false;
2268}
2269
2270static void get_phys_addr_pmsav7_default(CPUARMState *env, ARMMMUIdx mmu_idx,
2271                                         int32_t address, uint8_t *prot)
2272{
2273    if (!arm_feature(env, ARM_FEATURE_M)) {
2274        *prot = PAGE_READ | PAGE_WRITE;
2275        switch (address) {
2276        case 0xF0000000 ... 0xFFFFFFFF:
2277            if (regime_sctlr(env, mmu_idx) & SCTLR_V) {
2278                /* hivecs execing is ok */
2279                *prot |= PAGE_EXEC;
2280            }
2281            break;
2282        case 0x00000000 ... 0x7FFFFFFF:
2283            *prot |= PAGE_EXEC;
2284            break;
2285        }
2286    } else {
2287        /* Default system address map for M profile cores.
2288         * The architecture specifies which regions are execute-never;
2289         * at the MPU level no other checks are defined.
2290         */
2291        switch (address) {
2292        case 0x00000000 ... 0x1fffffff: /* ROM */
2293        case 0x20000000 ... 0x3fffffff: /* SRAM */
2294        case 0x60000000 ... 0x7fffffff: /* RAM */
2295        case 0x80000000 ... 0x9fffffff: /* RAM */
2296            *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
2297            break;
2298        case 0x40000000 ... 0x5fffffff: /* Peripheral */
2299        case 0xa0000000 ... 0xbfffffff: /* Device */
2300        case 0xc0000000 ... 0xdfffffff: /* Device */
2301        case 0xe0000000 ... 0xffffffff: /* System */
2302            *prot = PAGE_READ | PAGE_WRITE;
2303            break;
2304        default:
2305            g_assert_not_reached();
2306        }
2307    }
2308}
2309
2310static bool m_is_ppb_region(CPUARMState *env, uint32_t address)
2311{
2312    /* True if address is in the M profile PPB region 0xe0000000 - 0xe00fffff */
2313    return arm_feature(env, ARM_FEATURE_M) &&
2314        extract32(address, 20, 12) == 0xe00;
2315}
2316
2317static bool m_is_system_region(CPUARMState *env, uint32_t address)
2318{
2319    /*
2320     * True if address is in the M profile system region
2321     * 0xe0000000 - 0xffffffff
2322     */
2323    return arm_feature(env, ARM_FEATURE_M) && extract32(address, 29, 3) == 0x7;
2324}
2325
2326static bool pmsav7_use_background_region(ARMCPU *cpu, ARMMMUIdx mmu_idx,
2327                                         bool is_secure, bool is_user)
2328{
2329    /*
2330     * Return true if we should use the default memory map as a
2331     * "background" region if there are no hits against any MPU regions.
2332     */
2333    CPUARMState *env = &cpu->env;
2334
2335    if (is_user) {
2336        return false;
2337    }
2338
2339    if (arm_feature(env, ARM_FEATURE_M)) {
2340        return env->v7m.mpu_ctrl[is_secure] & R_V7M_MPU_CTRL_PRIVDEFENA_MASK;
2341    }
2342
2343    if (mmu_idx == ARMMMUIdx_Stage2) {
2344        return false;
2345    }
2346
2347    return regime_sctlr(env, mmu_idx) & SCTLR_BR;
2348}
2349
2350static bool get_phys_addr_pmsav7(CPUARMState *env,
2351                                 S1Translate *ptw,
2352                                 uint32_t address,
2353                                 MMUAccessType access_type,
2354                                 GetPhysAddrResult *result,
2355                                 ARMMMUFaultInfo *fi)
2356{
2357    ARMCPU *cpu = env_archcpu(env);
2358    int n;
2359    ARMMMUIdx mmu_idx = ptw->in_mmu_idx;
2360    bool is_user = regime_is_user(env, mmu_idx);
2361    bool secure = arm_space_is_secure(ptw->in_space);
2362
2363    result->f.phys_addr = address;
2364    result->f.lg_page_size = TARGET_PAGE_BITS;
2365    result->f.prot = 0;
2366
2367    if (regime_translation_disabled(env, mmu_idx, ptw->in_space) ||
2368        m_is_ppb_region(env, address)) {
2369        /*
2370         * MPU disabled or M profile PPB access: use default memory map.
2371         * The other case which uses the default memory map in the
2372         * v7M ARM ARM pseudocode is exception vector reads from the vector
2373         * table. In QEMU those accesses are done in arm_v7m_load_vector(),
2374         * which always does a direct read using address_space_ldl(), rather
2375         * than going via this function, so we don't need to check that here.
2376         */
2377        get_phys_addr_pmsav7_default(env, mmu_idx, address, &result->f.prot);
2378    } else { /* MPU enabled */
2379        for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {
2380            /* region search */
2381            uint32_t base = env->pmsav7.drbar[n];
2382            uint32_t rsize = extract32(env->pmsav7.drsr[n], 1, 5);
2383            uint32_t rmask;
2384            bool srdis = false;
2385
2386            if (!(env->pmsav7.drsr[n] & 0x1)) {
2387                continue;
2388            }
2389
2390            if (!rsize) {
2391                qemu_log_mask(LOG_GUEST_ERROR,
2392                              "DRSR[%d]: Rsize field cannot be 0\n", n);
2393                continue;
2394            }
2395            rsize++;
2396            rmask = (1ull << rsize) - 1;
2397
2398            if (base & rmask) {
2399                qemu_log_mask(LOG_GUEST_ERROR,
2400                              "DRBAR[%d]: 0x%" PRIx32 " misaligned "
2401                              "to DRSR region size, mask = 0x%" PRIx32 "\n",
2402                              n, base, rmask);
2403                continue;
2404            }
2405
2406            if (address < base || address > base + rmask) {
2407                /*
2408                 * Address not in this region. We must check whether the
2409                 * region covers addresses in the same page as our address.
2410                 * In that case we must not report a size that covers the
2411                 * whole page for a subsequent hit against a different MPU
2412                 * region or the background region, because it would result in
2413                 * incorrect TLB hits for subsequent accesses to addresses that
2414                 * are in this MPU region.
2415                 */
2416                if (ranges_overlap(base, rmask,
2417                                   address & TARGET_PAGE_MASK,
2418                                   TARGET_PAGE_SIZE)) {
2419                    result->f.lg_page_size = 0;
2420                }
2421                continue;
2422            }
2423
2424            /* Region matched */
2425
2426            if (rsize >= 8) { /* no subregions for regions < 256 bytes */
2427                int i, snd;
2428                uint32_t srdis_mask;
2429
2430                rsize -= 3; /* sub region size (power of 2) */
2431                snd = ((address - base) >> rsize) & 0x7;
2432                srdis = extract32(env->pmsav7.drsr[n], snd + 8, 1);
2433
2434                srdis_mask = srdis ? 0x3 : 0x0;
2435                for (i = 2; i <= 8 && rsize < TARGET_PAGE_BITS; i *= 2) {
2436                    /*
2437                     * This will check in groups of 2, 4 and then 8, whether
2438                     * the subregion bits are consistent. rsize is incremented
2439                     * back up to give the region size, considering consistent
2440                     * adjacent subregions as one region. Stop testing if rsize
2441                     * is already big enough for an entire QEMU page.
2442                     */
2443                    int snd_rounded = snd & ~(i - 1);
2444                    uint32_t srdis_multi = extract32(env->pmsav7.drsr[n],
2445                                                     snd_rounded + 8, i);
2446                    if (srdis_mask ^ srdis_multi) {
2447                        break;
2448                    }
2449                    srdis_mask = (srdis_mask << i) | srdis_mask;
2450                    rsize++;
2451                }
2452            }
2453            if (srdis) {
2454                continue;
2455            }
2456            if (rsize < TARGET_PAGE_BITS) {
2457                result->f.lg_page_size = rsize;
2458            }
2459            break;
2460        }
2461
2462        if (n == -1) { /* no hits */
2463            if (!pmsav7_use_background_region(cpu, mmu_idx, secure, is_user)) {
2464                /* background fault */
2465                fi->type = ARMFault_Background;
2466                return true;
2467            }
2468            get_phys_addr_pmsav7_default(env, mmu_idx, address,
2469                                         &result->f.prot);
2470        } else { /* a MPU hit! */
2471            uint32_t ap = extract32(env->pmsav7.dracr[n], 8, 3);
2472            uint32_t xn = extract32(env->pmsav7.dracr[n], 12, 1);
2473
2474            if (m_is_system_region(env, address)) {
2475                /* System space is always execute never */
2476                xn = 1;
2477            }
2478
2479            if (is_user) { /* User mode AP bit decoding */
2480                switch (ap) {
2481                case 0:
2482                case 1:
2483                case 5:
2484                    break; /* no access */
2485                case 3:
2486                    result->f.prot |= PAGE_WRITE;
2487                    /* fall through */
2488                case 2:
2489                case 6:
2490                    result->f.prot |= PAGE_READ | PAGE_EXEC;
2491                    break;
2492                case 7:
2493                    /* for v7M, same as 6; for R profile a reserved value */
2494                    if (arm_feature(env, ARM_FEATURE_M)) {
2495                        result->f.prot |= PAGE_READ | PAGE_EXEC;
2496                        break;
2497                    }
2498                    /* fall through */
2499                default:
2500                    qemu_log_mask(LOG_GUEST_ERROR,
2501                                  "DRACR[%d]: Bad value for AP bits: 0x%"
2502                                  PRIx32 "\n", n, ap);
2503                }
2504            } else { /* Priv. mode AP bits decoding */
2505                switch (ap) {
2506                case 0:
2507                    break; /* no access */
2508                case 1:
2509                case 2:
2510                case 3:
2511                    result->f.prot |= PAGE_WRITE;
2512                    /* fall through */
2513                case 5:
2514                case 6:
2515                    result->f.prot |= PAGE_READ | PAGE_EXEC;
2516                    break;
2517                case 7:
2518                    /* for v7M, same as 6; for R profile a reserved value */
2519                    if (arm_feature(env, ARM_FEATURE_M)) {
2520                        result->f.prot |= PAGE_READ | PAGE_EXEC;
2521                        break;
2522                    }
2523                    /* fall through */
2524                default:
2525                    qemu_log_mask(LOG_GUEST_ERROR,
2526                                  "DRACR[%d]: Bad value for AP bits: 0x%"
2527                                  PRIx32 "\n", n, ap);
2528                }
2529            }
2530
2531            /* execute never */
2532            if (xn) {
2533                result->f.prot &= ~PAGE_EXEC;
2534            }
2535        }
2536    }
2537
2538    fi->type = ARMFault_Permission;
2539    fi->level = 1;
2540    return !(result->f.prot & (1 << access_type));
2541}
2542
2543static uint32_t *regime_rbar(CPUARMState *env, ARMMMUIdx mmu_idx,
2544                             uint32_t secure)
2545{
2546    if (regime_el(env, mmu_idx) == 2) {
2547        return env->pmsav8.hprbar;
2548    } else {
2549        return env->pmsav8.rbar[secure];
2550    }
2551}
2552
2553static uint32_t *regime_rlar(CPUARMState *env, ARMMMUIdx mmu_idx,
2554                             uint32_t secure)
2555{
2556    if (regime_el(env, mmu_idx) == 2) {
2557        return env->pmsav8.hprlar;
2558    } else {
2559        return env->pmsav8.rlar[secure];
2560    }
2561}
2562
2563bool pmsav8_mpu_lookup(CPUARMState *env, uint32_t address,
2564                       MMUAccessType access_type, ARMMMUIdx mmu_idx,
2565                       bool secure, GetPhysAddrResult *result,
2566                       ARMMMUFaultInfo *fi, uint32_t *mregion)
2567{
2568    /*
2569     * Perform a PMSAv8 MPU lookup (without also doing the SAU check
2570     * that a full phys-to-virt translation does).
2571     * mregion is (if not NULL) set to the region number which matched,
2572     * or -1 if no region number is returned (MPU off, address did not
2573     * hit a region, address hit in multiple regions).
2574     * If the region hit doesn't cover the entire TARGET_PAGE the address
2575     * is within, then we set the result page_size to 1 to force the
2576     * memory system to use a subpage.
2577     */
2578    ARMCPU *cpu = env_archcpu(env);
2579    bool is_user = regime_is_user(env, mmu_idx);
2580    int n;
2581    int matchregion = -1;
2582    bool hit = false;
2583    uint32_t addr_page_base = address & TARGET_PAGE_MASK;
2584    uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
2585    int region_counter;
2586
2587    if (regime_el(env, mmu_idx) == 2) {
2588        region_counter = cpu->pmsav8r_hdregion;
2589    } else {
2590        region_counter = cpu->pmsav7_dregion;
2591    }
2592
2593    result->f.lg_page_size = TARGET_PAGE_BITS;
2594    result->f.phys_addr = address;
2595    result->f.prot = 0;
2596    if (mregion) {
2597        *mregion = -1;
2598    }
2599
2600    if (mmu_idx == ARMMMUIdx_Stage2) {
2601        fi->stage2 = true;
2602    }
2603
2604    /*
2605     * Unlike the ARM ARM pseudocode, we don't need to check whether this
2606     * was an exception vector read from the vector table (which is always
2607     * done using the default system address map), because those accesses
2608     * are done in arm_v7m_load_vector(), which always does a direct
2609     * read using address_space_ldl(), rather than going via this function.
2610     */
2611    if (regime_translation_disabled(env, mmu_idx, arm_secure_to_space(secure))) {
2612        /* MPU disabled */
2613        hit = true;
2614    } else if (m_is_ppb_region(env, address)) {
2615        hit = true;
2616    } else {
2617        if (pmsav7_use_background_region(cpu, mmu_idx, secure, is_user)) {
2618            hit = true;
2619        }
2620
2621        uint32_t bitmask;
2622        if (arm_feature(env, ARM_FEATURE_M)) {
2623            bitmask = 0x1f;
2624        } else {
2625            bitmask = 0x3f;
2626            fi->level = 0;
2627        }
2628
2629        for (n = region_counter - 1; n >= 0; n--) {
2630            /* region search */
2631            /*
2632             * Note that the base address is bits [31:x] from the register
2633             * with bits [x-1:0] all zeroes, but the limit address is bits
2634             * [31:x] from the register with bits [x:0] all ones. Where x is
2635             * 5 for Cortex-M and 6 for Cortex-R
2636             */
2637            uint32_t base = regime_rbar(env, mmu_idx, secure)[n] & ~bitmask;
2638            uint32_t limit = regime_rlar(env, mmu_idx, secure)[n] | bitmask;
2639
2640            if (!(regime_rlar(env, mmu_idx, secure)[n] & 0x1)) {
2641                /* Region disabled */
2642                continue;
2643            }
2644
2645            if (address < base || address > limit) {
2646                /*
2647                 * Address not in this region. We must check whether the
2648                 * region covers addresses in the same page as our address.
2649                 * In that case we must not report a size that covers the
2650                 * whole page for a subsequent hit against a different MPU
2651                 * region or the background region, because it would result in
2652                 * incorrect TLB hits for subsequent accesses to addresses that
2653                 * are in this MPU region.
2654                 */
2655                if (limit >= base &&
2656                    ranges_overlap(base, limit - base + 1,
2657                                   addr_page_base,
2658                                   TARGET_PAGE_SIZE)) {
2659                    result->f.lg_page_size = 0;
2660                }
2661                continue;
2662            }
2663
2664            if (base > addr_page_base || limit < addr_page_limit) {
2665                result->f.lg_page_size = 0;
2666            }
2667
2668            if (matchregion != -1) {
2669                /*
2670                 * Multiple regions match -- always a failure (unlike
2671                 * PMSAv7 where highest-numbered-region wins)
2672                 */
2673                fi->type = ARMFault_Permission;
2674                if (arm_feature(env, ARM_FEATURE_M)) {
2675                    fi->level = 1;
2676                }
2677                return true;
2678            }
2679
2680            matchregion = n;
2681            hit = true;
2682        }
2683    }
2684
2685    if (!hit) {
2686        if (arm_feature(env, ARM_FEATURE_M)) {
2687            fi->type = ARMFault_Background;
2688        } else {
2689            fi->type = ARMFault_Permission;
2690        }
2691        return true;
2692    }
2693
2694    if (matchregion == -1) {
2695        /* hit using the background region */
2696        get_phys_addr_pmsav7_default(env, mmu_idx, address, &result->f.prot);
2697    } else {
2698        uint32_t matched_rbar = regime_rbar(env, mmu_idx, secure)[matchregion];
2699        uint32_t matched_rlar = regime_rlar(env, mmu_idx, secure)[matchregion];
2700        uint32_t ap = extract32(matched_rbar, 1, 2);
2701        uint32_t xn = extract32(matched_rbar, 0, 1);
2702        bool pxn = false;
2703
2704        if (arm_feature(env, ARM_FEATURE_V8_1M)) {
2705            pxn = extract32(matched_rlar, 4, 1);
2706        }
2707
2708        if (m_is_system_region(env, address)) {
2709            /* System space is always execute never */
2710            xn = 1;
2711        }
2712
2713        if (regime_el(env, mmu_idx) == 2) {
2714            result->f.prot = simple_ap_to_rw_prot_is_user(ap,
2715                                            mmu_idx != ARMMMUIdx_E2);
2716        } else {
2717            result->f.prot = simple_ap_to_rw_prot(env, mmu_idx, ap);
2718        }
2719
2720        if (!arm_feature(env, ARM_FEATURE_M)) {
2721            uint8_t attrindx = extract32(matched_rlar, 1, 3);
2722            uint64_t mair = env->cp15.mair_el[regime_el(env, mmu_idx)];
2723            uint8_t sh = extract32(matched_rlar, 3, 2);
2724
2725            if (regime_sctlr(env, mmu_idx) & SCTLR_WXN &&
2726                result->f.prot & PAGE_WRITE && mmu_idx != ARMMMUIdx_Stage2) {
2727                xn = 0x1;
2728            }
2729
2730            if ((regime_el(env, mmu_idx) == 1) &&
2731                regime_sctlr(env, mmu_idx) & SCTLR_UWXN && ap == 0x1) {
2732                pxn = 0x1;
2733            }
2734
2735            result->cacheattrs.is_s2_format = false;
2736            result->cacheattrs.attrs = extract64(mair, attrindx * 8, 8);
2737            result->cacheattrs.shareability = sh;
2738        }
2739
2740        if (result->f.prot && !xn && !(pxn && !is_user)) {
2741            result->f.prot |= PAGE_EXEC;
2742        }
2743
2744        if (mregion) {
2745            *mregion = matchregion;
2746        }
2747    }
2748
2749    fi->type = ARMFault_Permission;
2750    if (arm_feature(env, ARM_FEATURE_M)) {
2751        fi->level = 1;
2752    }
2753    return !(result->f.prot & (1 << access_type));
2754}
2755
2756static bool v8m_is_sau_exempt(CPUARMState *env,
2757                              uint32_t address, MMUAccessType access_type)
2758{
2759    /*
2760     * The architecture specifies that certain address ranges are
2761     * exempt from v8M SAU/IDAU checks.
2762     */
2763    return
2764        (access_type == MMU_INST_FETCH && m_is_system_region(env, address)) ||
2765        (address >= 0xe0000000 && address <= 0xe0002fff) ||
2766        (address >= 0xe000e000 && address <= 0xe000efff) ||
2767        (address >= 0xe002e000 && address <= 0xe002efff) ||
2768        (address >= 0xe0040000 && address <= 0xe0041fff) ||
2769        (address >= 0xe00ff000 && address <= 0xe00fffff);
2770}
2771
2772void v8m_security_lookup(CPUARMState *env, uint32_t address,
2773                         MMUAccessType access_type, ARMMMUIdx mmu_idx,
2774                         bool is_secure, V8M_SAttributes *sattrs)
2775{
2776    /*
2777     * Look up the security attributes for this address. Compare the
2778     * pseudocode SecurityCheck() function.
2779     * We assume the caller has zero-initialized *sattrs.
2780     */
2781    ARMCPU *cpu = env_archcpu(env);
2782    int r;
2783    bool idau_exempt = false, idau_ns = true, idau_nsc = true;
2784    int idau_region = IREGION_NOTVALID;
2785    uint32_t addr_page_base = address & TARGET_PAGE_MASK;
2786    uint32_t addr_page_limit = addr_page_base + (TARGET_PAGE_SIZE - 1);
2787
2788    if (cpu->idau) {
2789        IDAUInterfaceClass *iic = IDAU_INTERFACE_GET_CLASS(cpu->idau);
2790        IDAUInterface *ii = IDAU_INTERFACE(cpu->idau);
2791
2792        iic->check(ii, address, &idau_region, &idau_exempt, &idau_ns,
2793                   &idau_nsc);
2794    }
2795
2796    if (access_type == MMU_INST_FETCH && extract32(address, 28, 4) == 0xf) {
2797        /* 0xf0000000..0xffffffff is always S for insn fetches */
2798        return;
2799    }
2800
2801    if (idau_exempt || v8m_is_sau_exempt(env, address, access_type)) {
2802        sattrs->ns = !is_secure;
2803        return;
2804    }
2805
2806    if (idau_region != IREGION_NOTVALID) {
2807        sattrs->irvalid = true;
2808        sattrs->iregion = idau_region;
2809    }
2810
2811    switch (env->sau.ctrl & 3) {
2812    case 0: /* SAU.ENABLE == 0, SAU.ALLNS == 0 */
2813        break;
2814    case 2: /* SAU.ENABLE == 0, SAU.ALLNS == 1 */
2815        sattrs->ns = true;
2816        break;
2817    default: /* SAU.ENABLE == 1 */
2818        for (r = 0; r < cpu->sau_sregion; r++) {
2819            if (env->sau.rlar[r] & 1) {
2820                uint32_t base = env->sau.rbar[r] & ~0x1f;
2821                uint32_t limit = env->sau.rlar[r] | 0x1f;
2822
2823                if (base <= address && limit >= address) {
2824                    if (base > addr_page_base || limit < addr_page_limit) {
2825                        sattrs->subpage = true;
2826                    }
2827                    if (sattrs->srvalid) {
2828                        /*
2829                         * If we hit in more than one region then we must report
2830                         * as Secure, not NS-Callable, with no valid region
2831                         * number info.
2832                         */
2833                        sattrs->ns = false;
2834                        sattrs->nsc = false;
2835                        sattrs->sregion = 0;
2836                        sattrs->srvalid = false;
2837                        break;
2838                    } else {
2839                        if (env->sau.rlar[r] & 2) {
2840                            sattrs->nsc = true;
2841                        } else {
2842                            sattrs->ns = true;
2843                        }
2844                        sattrs->srvalid = true;
2845                        sattrs->sregion = r;
2846                    }
2847                } else {
2848                    /*
2849                     * Address not in this region. We must check whether the
2850                     * region covers addresses in the same page as our address.
2851                     * In that case we must not report a size that covers the
2852                     * whole page for a subsequent hit against a different MPU
2853                     * region or the background region, because it would result
2854                     * in incorrect TLB hits for subsequent accesses to
2855                     * addresses that are in this MPU region.
2856                     */
2857                    if (limit >= base &&
2858                        ranges_overlap(base, limit - base + 1,
2859                                       addr_page_base,
2860                                       TARGET_PAGE_SIZE)) {
2861                        sattrs->subpage = true;
2862                    }
2863                }
2864            }
2865        }
2866        break;
2867    }
2868
2869    /*
2870     * The IDAU will override the SAU lookup results if it specifies
2871     * higher security than the SAU does.
2872     */
2873    if (!idau_ns) {
2874        if (sattrs->ns || (!idau_nsc && sattrs->nsc)) {
2875            sattrs->ns = false;
2876            sattrs->nsc = idau_nsc;
2877        }
2878    }
2879}
2880
2881static bool get_phys_addr_pmsav8(CPUARMState *env,
2882                                 S1Translate *ptw,
2883                                 uint32_t address,
2884                                 MMUAccessType access_type,
2885                                 GetPhysAddrResult *result,
2886                                 ARMMMUFaultInfo *fi)
2887{
2888    V8M_SAttributes sattrs = {};
2889    ARMMMUIdx mmu_idx = ptw->in_mmu_idx;
2890    bool secure = arm_space_is_secure(ptw->in_space);
2891    bool ret;
2892
2893    if (arm_feature(env, ARM_FEATURE_M_SECURITY)) {
2894        v8m_security_lookup(env, address, access_type, mmu_idx,
2895                            secure, &sattrs);
2896        if (access_type == MMU_INST_FETCH) {
2897            /*
2898             * Instruction fetches always use the MMU bank and the
2899             * transaction attribute determined by the fetch address,
2900             * regardless of CPU state. This is painful for QEMU
2901             * to handle, because it would mean we need to encode
2902             * into the mmu_idx not just the (user, negpri) information
2903             * for the current security state but also that for the
2904             * other security state, which would balloon the number
2905             * of mmu_idx values needed alarmingly.
2906             * Fortunately we can avoid this because it's not actually
2907             * possible to arbitrarily execute code from memory with
2908             * the wrong security attribute: it will always generate
2909             * an exception of some kind or another, apart from the
2910             * special case of an NS CPU executing an SG instruction
2911             * in S&NSC memory. So we always just fail the translation
2912             * here and sort things out in the exception handler
2913             * (including possibly emulating an SG instruction).
2914             */
2915            if (sattrs.ns != !secure) {
2916                if (sattrs.nsc) {
2917                    fi->type = ARMFault_QEMU_NSCExec;
2918                } else {
2919                    fi->type = ARMFault_QEMU_SFault;
2920                }
2921                result->f.lg_page_size = sattrs.subpage ? 0 : TARGET_PAGE_BITS;
2922                result->f.phys_addr = address;
2923                result->f.prot = 0;
2924                return true;
2925            }
2926        } else {
2927            /*
2928             * For data accesses we always use the MMU bank indicated
2929             * by the current CPU state, but the security attributes
2930             * might downgrade a secure access to nonsecure.
2931             */
2932            if (sattrs.ns) {
2933                result->f.attrs.secure = false;
2934                result->f.attrs.space = ARMSS_NonSecure;
2935            } else if (!secure) {
2936                /*
2937                 * NS access to S memory must fault.
2938                 * Architecturally we should first check whether the
2939                 * MPU information for this address indicates that we
2940                 * are doing an unaligned access to Device memory, which
2941                 * should generate a UsageFault instead. QEMU does not
2942                 * currently check for that kind of unaligned access though.
2943                 * If we added it we would need to do so as a special case
2944                 * for M_FAKE_FSR_SFAULT in arm_v7m_cpu_do_interrupt().
2945                 */
2946                fi->type = ARMFault_QEMU_SFault;
2947                result->f.lg_page_size = sattrs.subpage ? 0 : TARGET_PAGE_BITS;
2948                result->f.phys_addr = address;
2949                result->f.prot = 0;
2950                return true;
2951            }
2952        }
2953    }
2954
2955    ret = pmsav8_mpu_lookup(env, address, access_type, mmu_idx, secure,
2956                            result, fi, NULL);
2957    if (sattrs.subpage) {
2958        result->f.lg_page_size = 0;
2959    }
2960    return ret;
2961}
2962
2963/*
2964 * Translate from the 4-bit stage 2 representation of
2965 * memory attributes (without cache-allocation hints) to
2966 * the 8-bit representation of the stage 1 MAIR registers
2967 * (which includes allocation hints).
2968 *
2969 * ref: shared/translation/attrs/S2AttrDecode()
2970 *      .../S2ConvertAttrsHints()
2971 */
2972static uint8_t convert_stage2_attrs(uint64_t hcr, uint8_t s2attrs)
2973{
2974    uint8_t hiattr = extract32(s2attrs, 2, 2);
2975    uint8_t loattr = extract32(s2attrs, 0, 2);
2976    uint8_t hihint = 0, lohint = 0;
2977
2978    if (hiattr != 0) { /* normal memory */
2979        if (hcr & HCR_CD) { /* cache disabled */
2980            hiattr = loattr = 1; /* non-cacheable */
2981        } else {
2982            if (hiattr != 1) { /* Write-through or write-back */
2983                hihint = 3; /* RW allocate */
2984            }
2985            if (loattr != 1) { /* Write-through or write-back */
2986                lohint = 3; /* RW allocate */
2987            }
2988        }
2989    }
2990
2991    return (hiattr << 6) | (hihint << 4) | (loattr << 2) | lohint;
2992}
2993
2994/*
2995 * Combine either inner or outer cacheability attributes for normal
2996 * memory, according to table D4-42 and pseudocode procedure
2997 * CombineS1S2AttrHints() of ARM DDI 0487B.b (the ARMv8 ARM).
2998 *
2999 * NB: only stage 1 includes allocation hints (RW bits), leading to
3000 * some asymmetry.
3001 */
3002static uint8_t combine_cacheattr_nibble(uint8_t s1, uint8_t s2)
3003{
3004    if (s1 == 4 || s2 == 4) {
3005        /* non-cacheable has precedence */
3006        return 4;
3007    } else if (extract32(s1, 2, 2) == 0 || extract32(s1, 2, 2) == 2) {
3008        /* stage 1 write-through takes precedence */
3009        return s1;
3010    } else if (extract32(s2, 2, 2) == 2) {
3011        /* stage 2 write-through takes precedence, but the allocation hint
3012         * is still taken from stage 1
3013         */
3014        return (2 << 2) | extract32(s1, 0, 2);
3015    } else { /* write-back */
3016        return s1;
3017    }
3018}
3019
3020/*
3021 * Combine the memory type and cacheability attributes of
3022 * s1 and s2 for the HCR_EL2.FWB == 0 case, returning the
3023 * combined attributes in MAIR_EL1 format.
3024 */
3025static uint8_t combined_attrs_nofwb(uint64_t hcr,
3026                                    ARMCacheAttrs s1, ARMCacheAttrs s2)
3027{
3028    uint8_t s1lo, s2lo, s1hi, s2hi, s2_mair_attrs, ret_attrs;
3029
3030    if (s2.is_s2_format) {
3031        s2_mair_attrs = convert_stage2_attrs(hcr, s2.attrs);
3032    } else {
3033        s2_mair_attrs = s2.attrs;
3034    }
3035
3036    s1lo = extract32(s1.attrs, 0, 4);
3037    s2lo = extract32(s2_mair_attrs, 0, 4);
3038    s1hi = extract32(s1.attrs, 4, 4);
3039    s2hi = extract32(s2_mair_attrs, 4, 4);
3040
3041    /* Combine memory type and cacheability attributes */
3042    if (s1hi == 0 || s2hi == 0) {
3043        /* Device has precedence over normal */
3044        if (s1lo == 0 || s2lo == 0) {
3045            /* nGnRnE has precedence over anything */
3046            ret_attrs = 0;
3047        } else if (s1lo == 4 || s2lo == 4) {
3048            /* non-Reordering has precedence over Reordering */
3049            ret_attrs = 4;  /* nGnRE */
3050        } else if (s1lo == 8 || s2lo == 8) {
3051            /* non-Gathering has precedence over Gathering */
3052            ret_attrs = 8;  /* nGRE */
3053        } else {
3054            ret_attrs = 0xc; /* GRE */
3055        }
3056    } else { /* Normal memory */
3057        /* Outer/inner cacheability combine independently */
3058        ret_attrs = combine_cacheattr_nibble(s1hi, s2hi) << 4
3059                  | combine_cacheattr_nibble(s1lo, s2lo);
3060    }
3061    return ret_attrs;
3062}
3063
3064static uint8_t force_cacheattr_nibble_wb(uint8_t attr)
3065{
3066    /*
3067     * Given the 4 bits specifying the outer or inner cacheability
3068     * in MAIR format, return a value specifying Normal Write-Back,
3069     * with the allocation and transient hints taken from the input
3070     * if the input specified some kind of cacheable attribute.
3071     */
3072    if (attr == 0 || attr == 4) {
3073        /*
3074         * 0 == an UNPREDICTABLE encoding
3075         * 4 == Non-cacheable
3076         * Either way, force Write-Back RW allocate non-transient
3077         */
3078        return 0xf;
3079    }
3080    /* Change WriteThrough to WriteBack, keep allocation and transient hints */
3081    return attr | 4;
3082}
3083
3084/*
3085 * Combine the memory type and cacheability attributes of
3086 * s1 and s2 for the HCR_EL2.FWB == 1 case, returning the
3087 * combined attributes in MAIR_EL1 format.
3088 */
3089static uint8_t combined_attrs_fwb(ARMCacheAttrs s1, ARMCacheAttrs s2)
3090{
3091    assert(s2.is_s2_format && !s1.is_s2_format);
3092
3093    switch (s2.attrs) {
3094    case 7:
3095        /* Use stage 1 attributes */
3096        return s1.attrs;
3097    case 6:
3098        /*
3099         * Force Normal Write-Back. Note that if S1 is Normal cacheable
3100         * then we take the allocation hints from it; otherwise it is
3101         * RW allocate, non-transient.
3102         */
3103        if ((s1.attrs & 0xf0) == 0) {
3104            /* S1 is Device */
3105            return 0xff;
3106        }
3107        /* Need to check the Inner and Outer nibbles separately */
3108        return force_cacheattr_nibble_wb(s1.attrs & 0xf) |
3109            force_cacheattr_nibble_wb(s1.attrs >> 4) << 4;
3110    case 5:
3111        /* If S1 attrs are Device, use them; otherwise Normal Non-cacheable */
3112        if ((s1.attrs & 0xf0) == 0) {
3113            return s1.attrs;
3114        }
3115        return 0x44;
3116    case 0 ... 3:
3117        /* Force Device, of subtype specified by S2 */
3118        return s2.attrs << 2;
3119    default:
3120        /*
3121         * RESERVED values (including RES0 descriptor bit [5] being nonzero);
3122         * arbitrarily force Device.
3123         */
3124        return 0;
3125    }
3126}
3127
3128/*
3129 * Combine S1 and S2 cacheability/shareability attributes, per D4.5.4
3130 * and CombineS1S2Desc()
3131 *
3132 * @env:     CPUARMState
3133 * @s1:      Attributes from stage 1 walk
3134 * @s2:      Attributes from stage 2 walk
3135 */
3136static ARMCacheAttrs combine_cacheattrs(uint64_t hcr,
3137                                        ARMCacheAttrs s1, ARMCacheAttrs s2)
3138{
3139    ARMCacheAttrs ret;
3140    bool tagged = false;
3141
3142    assert(!s1.is_s2_format);
3143    ret.is_s2_format = false;
3144
3145    if (s1.attrs == 0xf0) {
3146        tagged = true;
3147        s1.attrs = 0xff;
3148    }
3149
3150    /* Combine shareability attributes (table D4-43) */
3151    if (s1.shareability == 2 || s2.shareability == 2) {
3152        /* if either are outer-shareable, the result is outer-shareable */
3153        ret.shareability = 2;
3154    } else if (s1.shareability == 3 || s2.shareability == 3) {
3155        /* if either are inner-shareable, the result is inner-shareable */
3156        ret.shareability = 3;
3157    } else {
3158        /* both non-shareable */
3159        ret.shareability = 0;
3160    }
3161
3162    /* Combine memory type and cacheability attributes */
3163    if (hcr & HCR_FWB) {
3164        ret.attrs = combined_attrs_fwb(s1, s2);
3165    } else {
3166        ret.attrs = combined_attrs_nofwb(hcr, s1, s2);
3167    }
3168
3169    /*
3170     * Any location for which the resultant memory type is any
3171     * type of Device memory is always treated as Outer Shareable.
3172     * Any location for which the resultant memory type is Normal
3173     * Inner Non-cacheable, Outer Non-cacheable is always treated
3174     * as Outer Shareable.
3175     * TODO: FEAT_XS adds another value (0x40) also meaning iNCoNC
3176     */
3177    if ((ret.attrs & 0xf0) == 0 || ret.attrs == 0x44) {
3178        ret.shareability = 2;
3179    }
3180
3181    /* TODO: CombineS1S2Desc does not consider transient, only WB, RWA. */
3182    if (tagged && ret.attrs == 0xff) {
3183        ret.attrs = 0xf0;
3184    }
3185
3186    return ret;
3187}
3188
3189/*
3190 * MMU disabled.  S1 addresses within aa64 translation regimes are
3191 * still checked for bounds -- see AArch64.S1DisabledOutput().
3192 */
3193static bool get_phys_addr_disabled(CPUARMState *env,
3194                                   S1Translate *ptw,
3195                                   vaddr address,
3196                                   MMUAccessType access_type,
3197                                   GetPhysAddrResult *result,
3198                                   ARMMMUFaultInfo *fi)
3199{
3200    ARMMMUIdx mmu_idx = ptw->in_mmu_idx;
3201    uint8_t memattr = 0x00;    /* Device nGnRnE */
3202    uint8_t shareability = 0;  /* non-shareable */
3203    int r_el;
3204
3205    switch (mmu_idx) {
3206    case ARMMMUIdx_Stage2:
3207    case ARMMMUIdx_Stage2_S:
3208    case ARMMMUIdx_Phys_S:
3209    case ARMMMUIdx_Phys_NS:
3210    case ARMMMUIdx_Phys_Root:
3211    case ARMMMUIdx_Phys_Realm:
3212        break;
3213
3214    default:
3215        r_el = regime_el(env, mmu_idx);
3216        if (arm_el_is_aa64(env, r_el)) {
3217            int pamax = arm_pamax(env_archcpu(env));
3218            uint64_t tcr = env->cp15.tcr_el[r_el];
3219            int addrtop, tbi;
3220
3221            tbi = aa64_va_parameter_tbi(tcr, mmu_idx);
3222            if (access_type == MMU_INST_FETCH) {
3223                tbi &= ~aa64_va_parameter_tbid(tcr, mmu_idx);
3224            }
3225            tbi = (tbi >> extract64(address, 55, 1)) & 1;
3226            addrtop = (tbi ? 55 : 63);
3227
3228            if (extract64(address, pamax, addrtop - pamax + 1) != 0) {
3229                fi->type = ARMFault_AddressSize;
3230                fi->level = 0;
3231                fi->stage2 = false;
3232                return 1;
3233            }
3234
3235            /*
3236             * When TBI is disabled, we've just validated that all of the
3237             * bits above PAMax are zero, so logically we only need to
3238             * clear the top byte for TBI.  But it's clearer to follow
3239             * the pseudocode set of addrdesc.paddress.
3240             */
3241            address = extract64(address, 0, 52);
3242        }
3243
3244        /* Fill in cacheattr a-la AArch64.TranslateAddressS1Off. */
3245        if (r_el == 1) {
3246            uint64_t hcr = arm_hcr_el2_eff_secstate(env, ptw->in_space);
3247            if (hcr & HCR_DC) {
3248                if (hcr & HCR_DCT) {
3249                    memattr = 0xf0;  /* Tagged, Normal, WB, RWA */
3250                } else {
3251                    memattr = 0xff;  /* Normal, WB, RWA */
3252                }
3253            }
3254        }
3255        if (memattr == 0) {
3256            if (access_type == MMU_INST_FETCH) {
3257                if (regime_sctlr(env, mmu_idx) & SCTLR_I) {
3258                    memattr = 0xee;  /* Normal, WT, RA, NT */
3259                } else {
3260                    memattr = 0x44;  /* Normal, NC, No */
3261                }
3262            }
3263            shareability = 2; /* outer shareable */
3264        }
3265        result->cacheattrs.is_s2_format = false;
3266        break;
3267    }
3268
3269    result->f.phys_addr = address;
3270    result->f.prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;
3271    result->f.lg_page_size = TARGET_PAGE_BITS;
3272    result->cacheattrs.shareability = shareability;
3273    result->cacheattrs.attrs = memattr;
3274    return false;
3275}
3276
3277static bool get_phys_addr_twostage(CPUARMState *env, S1Translate *ptw,
3278                                   vaddr address,
3279                                   MMUAccessType access_type, MemOp memop,
3280                                   GetPhysAddrResult *result,
3281                                   ARMMMUFaultInfo *fi)
3282{
3283    hwaddr ipa;
3284    int s1_prot, s1_lgpgsz;
3285    ARMSecuritySpace in_space = ptw->in_space;
3286    bool ret, ipa_secure, s1_guarded;
3287    ARMCacheAttrs cacheattrs1;
3288    ARMSecuritySpace ipa_space;
3289    uint64_t hcr;
3290
3291    ret = get_phys_addr_nogpc(env, ptw, address, access_type,
3292                              memop, result, fi);
3293
3294    /* If S1 fails, return early.  */
3295    if (ret) {
3296        return ret;
3297    }
3298
3299    ipa = result->f.phys_addr;
3300    ipa_secure = result->f.attrs.secure;
3301    ipa_space = result->f.attrs.space;
3302
3303    ptw->in_s1_is_el0 = ptw->in_mmu_idx == ARMMMUIdx_Stage1_E0;
3304    ptw->in_mmu_idx = ipa_secure ? ARMMMUIdx_Stage2_S : ARMMMUIdx_Stage2;
3305    ptw->in_space = ipa_space;
3306    ptw->in_ptw_idx = ptw_idx_for_stage_2(env, ptw->in_mmu_idx);
3307
3308    /*
3309     * S1 is done, now do S2 translation.
3310     * Save the stage1 results so that we may merge prot and cacheattrs later.
3311     */
3312    s1_prot = result->f.prot;
3313    s1_lgpgsz = result->f.lg_page_size;
3314    s1_guarded = result->f.extra.arm.guarded;
3315    cacheattrs1 = result->cacheattrs;
3316    memset(result, 0, sizeof(*result));
3317
3318    ret = get_phys_addr_nogpc(env, ptw, ipa, access_type,
3319                              memop, result, fi);
3320    fi->s2addr = ipa;
3321
3322    /* Combine the S1 and S2 perms.  */
3323    result->f.prot &= s1_prot;
3324
3325    /* If S2 fails, return early.  */
3326    if (ret) {
3327        return ret;
3328    }
3329
3330    /*
3331     * If either S1 or S2 returned a result smaller than TARGET_PAGE_SIZE,
3332     * this means "don't put this in the TLB"; in this case, return a
3333     * result with lg_page_size == 0 to achieve that. Otherwise,
3334     * use the maximum of the S1 & S2 page size, so that invalidation
3335     * of pages > TARGET_PAGE_SIZE works correctly. (This works even though
3336     * we know the combined result permissions etc only cover the minimum
3337     * of the S1 and S2 page size, because we know that the common TLB code
3338     * never actually creates TLB entries bigger than TARGET_PAGE_SIZE,
3339     * and passing a larger page size value only affects invalidations.)
3340     */
3341    if (result->f.lg_page_size < TARGET_PAGE_BITS ||
3342        s1_lgpgsz < TARGET_PAGE_BITS) {
3343        result->f.lg_page_size = 0;
3344    } else if (result->f.lg_page_size < s1_lgpgsz) {
3345        result->f.lg_page_size = s1_lgpgsz;
3346    }
3347
3348    /* Combine the S1 and S2 cache attributes. */
3349    hcr = arm_hcr_el2_eff_secstate(env, in_space);
3350    if (hcr & HCR_DC) {
3351        /*
3352         * HCR.DC forces the first stage attributes to
3353         *  Normal Non-Shareable,
3354         *  Inner Write-Back Read-Allocate Write-Allocate,
3355         *  Outer Write-Back Read-Allocate Write-Allocate.
3356         * Do not overwrite Tagged within attrs.
3357         */
3358        if (cacheattrs1.attrs != 0xf0) {
3359            cacheattrs1.attrs = 0xff;
3360        }
3361        cacheattrs1.shareability = 0;
3362    }
3363    result->cacheattrs = combine_cacheattrs(hcr, cacheattrs1,
3364                                            result->cacheattrs);
3365
3366    /* No BTI GP information in stage 2, we just use the S1 value */
3367    result->f.extra.arm.guarded = s1_guarded;
3368
3369    /*
3370     * Check if IPA translates to secure or non-secure PA space.
3371     * Note that VSTCR overrides VTCR and {N}SW overrides {N}SA.
3372     */
3373    if (in_space == ARMSS_Secure) {
3374        result->f.attrs.secure =
3375            !(env->cp15.vstcr_el2 & (VSTCR_SA | VSTCR_SW))
3376            && (ipa_secure
3377                || !(env->cp15.vtcr_el2 & (VTCR_NSA | VTCR_NSW)));
3378        result->f.attrs.space = arm_secure_to_space(result->f.attrs.secure);
3379    }
3380
3381    return false;
3382}
3383
3384static bool get_phys_addr_nogpc(CPUARMState *env, S1Translate *ptw,
3385                                      vaddr address,
3386                                      MMUAccessType access_type, MemOp memop,
3387                                      GetPhysAddrResult *result,
3388                                      ARMMMUFaultInfo *fi)
3389{
3390    ARMMMUIdx mmu_idx = ptw->in_mmu_idx;
3391    ARMMMUIdx s1_mmu_idx;
3392
3393    /*
3394     * The page table entries may downgrade Secure to NonSecure, but
3395     * cannot upgrade a NonSecure translation regime's attributes
3396     * to Secure or Realm.
3397     */
3398    result->f.attrs.space = ptw->in_space;
3399    result->f.attrs.secure = arm_space_is_secure(ptw->in_space);
3400
3401    switch (mmu_idx) {
3402    case ARMMMUIdx_Phys_S:
3403    case ARMMMUIdx_Phys_NS:
3404    case ARMMMUIdx_Phys_Root:
3405    case ARMMMUIdx_Phys_Realm:
3406        /* Checking Phys early avoids special casing later vs regime_el. */
3407        return get_phys_addr_disabled(env, ptw, address, access_type,
3408                                      result, fi);
3409
3410    case ARMMMUIdx_Stage1_E0:
3411    case ARMMMUIdx_Stage1_E1:
3412    case ARMMMUIdx_Stage1_E1_PAN:
3413        /*
3414         * First stage lookup uses second stage for ptw; only
3415         * Secure has both S and NS IPA and starts with Stage2_S.
3416         */
3417        ptw->in_ptw_idx = (ptw->in_space == ARMSS_Secure) ?
3418            ARMMMUIdx_Stage2_S : ARMMMUIdx_Stage2;
3419        break;
3420
3421    case ARMMMUIdx_Stage2:
3422    case ARMMMUIdx_Stage2_S:
3423        /*
3424         * Second stage lookup uses physical for ptw; whether this is S or
3425         * NS may depend on the SW/NSW bits if this is a stage 2 lookup for
3426         * the Secure EL2&0 regime.
3427         */
3428        ptw->in_ptw_idx = ptw_idx_for_stage_2(env, mmu_idx);
3429        break;
3430
3431    case ARMMMUIdx_E10_0:
3432        s1_mmu_idx = ARMMMUIdx_Stage1_E0;
3433        goto do_twostage;
3434    case ARMMMUIdx_E10_1:
3435        s1_mmu_idx = ARMMMUIdx_Stage1_E1;
3436        goto do_twostage;
3437    case ARMMMUIdx_E10_1_PAN:
3438        s1_mmu_idx = ARMMMUIdx_Stage1_E1_PAN;
3439    do_twostage:
3440        /*
3441         * Call ourselves recursively to do the stage 1 and then stage 2
3442         * translations if mmu_idx is a two-stage regime, and EL2 present.
3443         * Otherwise, a stage1+stage2 translation is just stage 1.
3444         */
3445        ptw->in_mmu_idx = mmu_idx = s1_mmu_idx;
3446        if (arm_feature(env, ARM_FEATURE_EL2) &&
3447            !regime_translation_disabled(env, ARMMMUIdx_Stage2, ptw->in_space)) {
3448            return get_phys_addr_twostage(env, ptw, address, access_type,
3449                                          memop, result, fi);
3450        }
3451        /* fall through */
3452
3453    default:
3454        /* Single stage uses physical for ptw. */
3455        ptw->in_ptw_idx = arm_space_to_phys(ptw->in_space);
3456        break;
3457    }
3458
3459    result->f.attrs.user = regime_is_user(env, mmu_idx);
3460
3461    /*
3462     * Fast Context Switch Extension. This doesn't exist at all in v8.
3463     * In v7 and earlier it affects all stage 1 translations.
3464     */
3465    if (address < 0x02000000 && mmu_idx != ARMMMUIdx_Stage2
3466        && !arm_feature(env, ARM_FEATURE_V8)) {
3467        if (regime_el(env, mmu_idx) == 3) {
3468            address += env->cp15.fcseidr_s;
3469        } else {
3470            address += env->cp15.fcseidr_ns;
3471        }
3472    }
3473
3474    if (arm_feature(env, ARM_FEATURE_PMSA)) {
3475        bool ret;
3476        result->f.lg_page_size = TARGET_PAGE_BITS;
3477
3478        if (arm_feature(env, ARM_FEATURE_V8)) {
3479            /* PMSAv8 */
3480            ret = get_phys_addr_pmsav8(env, ptw, address, access_type,
3481                                       result, fi);
3482        } else if (arm_feature(env, ARM_FEATURE_V7)) {
3483            /* PMSAv7 */
3484            ret = get_phys_addr_pmsav7(env, ptw, address, access_type,
3485                                       result, fi);
3486        } else {
3487            /* Pre-v7 MPU */
3488            ret = get_phys_addr_pmsav5(env, ptw, address, access_type,
3489                                       result, fi);
3490        }
3491        qemu_log_mask(CPU_LOG_MMU, "PMSA MPU lookup for %s at 0x%08" PRIx32
3492                      " mmu_idx %u -> %s (prot %c%c%c)\n",
3493                      access_type == MMU_DATA_LOAD ? "reading" :
3494                      (access_type == MMU_DATA_STORE ? "writing" : "execute"),
3495                      (uint32_t)address, mmu_idx,
3496                      ret ? "Miss" : "Hit",
3497                      result->f.prot & PAGE_READ ? 'r' : '-',
3498                      result->f.prot & PAGE_WRITE ? 'w' : '-',
3499                      result->f.prot & PAGE_EXEC ? 'x' : '-');
3500
3501        return ret;
3502    }
3503
3504    /* Definitely a real MMU, not an MPU */
3505
3506    if (regime_translation_disabled(env, mmu_idx, ptw->in_space)) {
3507        return get_phys_addr_disabled(env, ptw, address, access_type,
3508                                      result, fi);
3509    }
3510
3511    if (regime_using_lpae_format(env, mmu_idx)) {
3512        return get_phys_addr_lpae(env, ptw, address, access_type,
3513                                  memop, result, fi);
3514    } else if (arm_feature(env, ARM_FEATURE_V7) ||
3515               regime_sctlr(env, mmu_idx) & SCTLR_XP) {
3516        return get_phys_addr_v6(env, ptw, address, access_type, result, fi);
3517    } else {
3518        return get_phys_addr_v5(env, ptw, address, access_type, result, fi);
3519    }
3520}
3521
3522static bool get_phys_addr_gpc(CPUARMState *env, S1Translate *ptw,
3523                              vaddr address,
3524                              MMUAccessType access_type, MemOp memop,
3525                              GetPhysAddrResult *result,
3526                              ARMMMUFaultInfo *fi)
3527{
3528    if (get_phys_addr_nogpc(env, ptw, address, access_type,
3529                            memop, result, fi)) {
3530        return true;
3531    }
3532    if (!granule_protection_check(env, result->f.phys_addr,
3533                                  result->f.attrs.space, fi)) {
3534        fi->type = ARMFault_GPCFOnOutput;
3535        return true;
3536    }
3537    return false;
3538}
3539
3540bool get_phys_addr_with_space_nogpc(CPUARMState *env, vaddr address,
3541                                    MMUAccessType access_type, MemOp memop,
3542                                    ARMMMUIdx mmu_idx, ARMSecuritySpace space,
3543                                    GetPhysAddrResult *result,
3544                                    ARMMMUFaultInfo *fi)
3545{
3546    S1Translate ptw = {
3547        .in_mmu_idx = mmu_idx,
3548        .in_space = space,
3549    };
3550    return get_phys_addr_nogpc(env, &ptw, address, access_type,
3551                               memop, result, fi);
3552}
3553
3554static ARMSecuritySpace
3555arm_mmu_idx_to_security_space(CPUARMState *env, ARMMMUIdx mmu_idx)
3556{
3557    ARMSecuritySpace ss;
3558
3559    switch (mmu_idx) {
3560    case ARMMMUIdx_E10_0:
3561    case ARMMMUIdx_E10_1:
3562    case ARMMMUIdx_E10_1_PAN:
3563    case ARMMMUIdx_E20_0:
3564    case ARMMMUIdx_E20_2:
3565    case ARMMMUIdx_E20_2_PAN:
3566    case ARMMMUIdx_Stage1_E0:
3567    case ARMMMUIdx_Stage1_E1:
3568    case ARMMMUIdx_Stage1_E1_PAN:
3569    case ARMMMUIdx_E2:
3570        ss = arm_security_space_below_el3(env);
3571        break;
3572    case ARMMMUIdx_Stage2:
3573        /*
3574         * For Secure EL2, we need this index to be NonSecure;
3575         * otherwise this will already be NonSecure or Realm.
3576         */
3577        ss = arm_security_space_below_el3(env);
3578        if (ss == ARMSS_Secure) {
3579            ss = ARMSS_NonSecure;
3580        }
3581        break;
3582    case ARMMMUIdx_Phys_NS:
3583    case ARMMMUIdx_MPrivNegPri:
3584    case ARMMMUIdx_MUserNegPri:
3585    case ARMMMUIdx_MPriv:
3586    case ARMMMUIdx_MUser:
3587        ss = ARMSS_NonSecure;
3588        break;
3589    case ARMMMUIdx_Stage2_S:
3590    case ARMMMUIdx_Phys_S:
3591    case ARMMMUIdx_MSPrivNegPri:
3592    case ARMMMUIdx_MSUserNegPri:
3593    case ARMMMUIdx_MSPriv:
3594    case ARMMMUIdx_MSUser:
3595        ss = ARMSS_Secure;
3596        break;
3597    case ARMMMUIdx_E3:
3598    case ARMMMUIdx_E30_0:
3599    case ARMMMUIdx_E30_3_PAN:
3600        if (arm_feature(env, ARM_FEATURE_AARCH64) &&
3601            cpu_isar_feature(aa64_rme, env_archcpu(env))) {
3602            ss = ARMSS_Root;
3603        } else {
3604            ss = ARMSS_Secure;
3605        }
3606        break;
3607    case ARMMMUIdx_Phys_Root:
3608        ss = ARMSS_Root;
3609        break;
3610    case ARMMMUIdx_Phys_Realm:
3611        ss = ARMSS_Realm;
3612        break;
3613    default:
3614        g_assert_not_reached();
3615    }
3616
3617    return ss;
3618}
3619
3620bool get_phys_addr(CPUARMState *env, vaddr address,
3621                   MMUAccessType access_type, MemOp memop, ARMMMUIdx mmu_idx,
3622                   GetPhysAddrResult *result, ARMMMUFaultInfo *fi)
3623{
3624    S1Translate ptw = {
3625        .in_mmu_idx = mmu_idx,
3626        .in_space = arm_mmu_idx_to_security_space(env, mmu_idx),
3627    };
3628
3629    return get_phys_addr_gpc(env, &ptw, address, access_type,
3630                             memop, result, fi);
3631}
3632
3633static hwaddr arm_cpu_get_phys_page(CPUARMState *env, vaddr addr,
3634                                    MemTxAttrs *attrs, ARMMMUIdx mmu_idx)
3635{
3636    S1Translate ptw = {
3637        .in_mmu_idx = mmu_idx,
3638        .in_space = arm_mmu_idx_to_security_space(env, mmu_idx),
3639        .in_debug = true,
3640    };
3641    GetPhysAddrResult res = {};
3642    ARMMMUFaultInfo fi = {};
3643    bool ret = get_phys_addr_gpc(env, &ptw, addr, MMU_DATA_LOAD, 0, &res, &fi);
3644    *attrs = res.f.attrs;
3645
3646    if (ret) {
3647        return -1;
3648    }
3649    return res.f.phys_addr;
3650}
3651
3652hwaddr arm_cpu_get_phys_page_attrs_debug(CPUState *cs, vaddr addr,
3653                                         MemTxAttrs *attrs)
3654{
3655    ARMCPU *cpu = ARM_CPU(cs);
3656    CPUARMState *env = &cpu->env;
3657    ARMMMUIdx mmu_idx = arm_mmu_idx(env);
3658
3659    hwaddr res = arm_cpu_get_phys_page(env, addr, attrs, mmu_idx);
3660
3661    if (res != -1) {
3662        return res;
3663    }
3664
3665    /*
3666     * Memory may be accessible for an "unprivileged load/store" variant.
3667     * In this case, get_a64_user_mem_index function generates an op using an
3668     * unprivileged mmu idx, so we need to try with it.
3669     */
3670    switch (mmu_idx) {
3671    case ARMMMUIdx_E10_1:
3672    case ARMMMUIdx_E10_1_PAN:
3673        return arm_cpu_get_phys_page(env, addr, attrs, ARMMMUIdx_E10_0);
3674    case ARMMMUIdx_E20_2:
3675    case ARMMMUIdx_E20_2_PAN:
3676        return arm_cpu_get_phys_page(env, addr, attrs, ARMMMUIdx_E20_0);
3677    default:
3678        return -1;
3679    }
3680}
3681