[Writeup] Shared pseudocode: part 21 of 36 ========================================== Section: Silicon & Architectures Started: 2026-11-28 17:46 UTC by admin Replies: 0, last post 2026-11-28 17:46 UTC Page: 1 of 1 Web: https://romdump.net/t/113 ------------------------------------------------------------------------------ #133 admin, 2026-11-28 17:46 UTC [OP] Source: https://romdump.net/raw/133

Shared pseudocode from the offline Arm documentation snapshot. Part 21 of 36.

var fault : FaultRecord = NoFault(accdesc, va);

var ipa : AddressDescriptor;
(fault, ipa) = AArch64_S1Translate(fault, regime, va, size, aligned, accdesc);

if fault.statuscode != Fault_None then
    return CreateFaultyAddressDescriptor(fault);
end;

if accdesc.ss == SS_Realm then
    assert EL2Enabled();
end;
if regime == Regime_EL10 && EL2Enabled() then
    let s1aarch64 : boolean = TRUE;
    var pa : AddressDescriptor;
    (fault, pa) = AArch64_S2Translate(fault, ipa, s1aarch64, aligned, accdesc);

    if fault.statuscode != Fault_None then
        return CreateFaultyAddressDescriptor(fault);
    else
        return pa;
    end;
else
    return ipa;
end;

end;


## Library pseudocode for
aarch64/translation/vmsa\_translation/AArch64\_MemSwapTableDesc

// AArch64_MemSwapTableDesc // ========================== // Perform HW update of table descriptor as an atomic operation

func AArch64_MemSwapTableDesc{N : integer{64, 128}}(fault_in : FaultRecord, prev_desc : bits(N), new_desc : bits(N), ee : bit, descaccess : AccessDescriptor, descpaddr : AddressDescriptor ) => (FaultRecord, bits(N)) begin assert descaccess.acctype == AccessType_TTW; var fault : FaultRecord = fault_in; var iswrite : boolean;

if IsFeatureImplemented(FEAT_RME) then
    fault.gpcf = GranuleProtectionCheck(descpaddr, descaccess);
    if fault.gpcf.gpf != GPCF_None then
        fault.statuscode = Fault_GPCFOnWalk;
        fault.paddress   = descpaddr.paddress;
        fault.gpcfs2walk = fault.secondstage;
        return (fault, ARBITRARY : bits(N));
    end;
end;

// All observers in the shareability domain observe the
// following memory read and write accesses atomically.
var mem_desc : bits(N);
var memstatus : PhysMemRetStatus;
(memstatus, mem_desc) = PhysMemRead{N}(descpaddr, descaccess);

if ee == '1' then
    mem_desc = BigEndianReverse{N}(mem_desc);
end;

if IsFault(memstatus) then
    iswrite = FALSE;
    fault = HandleExternalTTWAbort(memstatus, iswrite, descpaddr, descaccess, N DIV 8, fault);
    if IsFault(fault.statuscode) then
        return (fault, ARBITRARY : bits(N));
    end;
end;

if mem_desc == prev_desc  then
    let ordered_new_desc : bits(N) = (if ee == '1' then BigEndianReverse{N}(new_desc)
                                                   else new_desc);
    memstatus = PhysMemWrite{N}(descpaddr, descaccess, ordered_new_desc);

    if IsFault(memstatus) then
        iswrite = TRUE;
        fault = HandleExternalTTWAbort(memstatus, iswrite, descpaddr, descaccess, N DIV 8,
                                       fault);

        if IsFault(fault.statuscode) then
            return (fault, ARBITRARY : bits(N));
        end;
    end;

    // Reflect what is now in memory (in little endian format)
    mem_desc = new_desc;
end;

return (fault, mem_desc);

end;


## Library pseudocode for
aarch64/translation/vmsa\_translation/AArch64\_S1DisabledOutput

// AArch64_S1DisabledOutput // ========================== // Map the VA to IPA/PA and assign default memory attributes

func AArch64_S1DisabledOutput(fault_in : FaultRecord, regime : Regime, va_in : bits(64), accdesc : AccessDescriptor, aligned : boolean) => (FaultRecord, AddressDescriptor) begin var va : bits(64) = va_in; let walkparams : S1TTWParams = AArch64_GetS1TTWParams(regime, accdesc.el, accdesc.ss, va); var fault : FaultRecord = fault_in;

if accdesc.acctype == AccessType_IFETCH then
    // No memory page is guarded when stage 1 address translation is disabled
    SetInGuardedPage(FALSE);
end;

// Output Address
var oa : FullAddress;
oa.address = va[NUM_PABITS-1:0];
case accdesc.ss of
    when SS_Secure =>    oa.paspace = PAS_Secure;
    when SS_NonSecure => oa.paspace = PAS_NonSecure;
    when SS_Root =>      oa.paspace = PAS_Root;
    when SS_Realm =>     oa.paspace = PAS_Realm;
end;

var memattrs : MemoryAttributes;
if regime == Regime_EL10 && EL2Enabled() && walkparams.dc ==
'1' then
    var default_cacheability : MemAttrHints;
    default_cacheability.attrs     = MemAttr_WB;
    default_cacheability.hints     = MemHint_RWA;
    default_cacheability.transient = FALSE;

    memattrs.memtype      = MemType_Normal;
    memattrs.outer        = default_cacheability;
    memattrs.inner        = default_cacheability;
    memattrs.shareability = Shareability_NSH;
    if walkparams.dct == '1' then
        memattrs.tags     = MemTag_AllocationTagged;
    elsif IsFeatureImplemented(FEAT_MTE_CANONICAL_TAGS) && walkparams.mtx == '1' then
        memattrs.tags     = MemTag_CanonicallyTagged;
    else
        memattrs.tags     = MemTag_Untagged;
    end;
    memattrs.xs           = '0';
elsif accdesc.acctype == AccessType_IFETCH then
    var i_cache_attr : MemAttrHints;
    if AArch64_S1ICacheEnabled(regime) then
        i_cache_attr.attrs     = MemAttr_WT;
        i_cache_attr.hints     = MemHint_RA;
        i_cache_attr.transient = FALSE;
    else
        i_cache_attr.attrs     = MemAttr_NC;
    end;

    memattrs.memtype      = MemType_Normal;
    memattrs.outer        = i_cache_attr;
    memattrs.inner        = i_cache_attr;
    memattrs.shareability = Shareability_OSH;
    memattrs.tags         = MemTag_Untagged;
    memattrs.xs           = '1';
elsif accdesc.acctype == AccessType_SPE &&
EffectivePMBLIMITR_EL1_nVM() == '1' then
    memattrs = S1DecodeMemAttrs(PMBMAR_EL1().Attr, PMBMAR_EL1().SH, TRUE,
                                walkparams, accdesc.acctype);
elsif accdesc.acctype == AccessType_TRBE &&
EffectiveTRBLIMITR_EL1_nVM() == '1' then
    memattrs = S1DecodeMemAttrs(TRBMAR_EL1().Attr, TRBMAR_EL1().SH, TRUE,
                                walkparams, accdesc.acctype);
else
    memattrs.memtype      = MemType_Device;
    memattrs.device       = DeviceType_nGnRnE;
    memattrs.shareability = Shareability_OSH;
    if IsFeatureImplemented(FEAT_MTE_CANONICAL_TAGS) && walkparams.mtx == '1' then
        memattrs.tags = MemTag_CanonicallyTagged;
    else
        memattrs.tags = MemTag_Untagged;
    end;
    memattrs.xs           = '1';
end;
memattrs.notagaccess = FALSE;

if walkparams.mtx == '1' && walkparams.tbi == '0' &&
accdesc.acctype != AccessType_IFETCH then
    // For the purpose of the checks in this function, the MTE tag bits are ignored.
    va[59:56] = if HasUnprivileged(regime) then Replicate{4}(va[55]) else '0000';
end;

fault.level = 0;
let addrtop : AddressSize = AArch64_AddrTop(walkparams.tbid, accdesc.acctype,
                                               walkparams.tbi);
let pamax : AddressSize = AArch64_PAMax();

let oamax : AddressSize = AArch64_OAMax();
var addrchecked : boolean = FALSE;

if accdesc.acctype == AccessType_SPE && EffectivePMBLIMITR_EL1_nVM()
== '1' then
    addrchecked = TRUE;
    if oamax > pamax && !IsZero(va[(oamax-1):pamax])then
        fault.statuscode = Fault_AddressSize;
    elsif !IsZero(va[63:oamax]) then
        if ConstrainUnpredictableBool(Unpredictable_PMBPTR_Fault_AddressSize)then
            fault.statuscode = Fault_AddressSize;
        else
            oa.address = ZeroExtend{NUM_PABITS}(oa.address[oamax-1:0]);
        end;
    end;
end;

if accdesc.acctype == AccessType_TRBE && EffectiveTRBLIMITR_EL1_nVM()
== '1' then
    addrchecked = TRUE;
    if oamax > pamax && !IsZero(va[(oamax-1):pamax])then
        fault.statuscode = Fault_AddressSize;
    elsif !IsZero(va[63:oamax]) then
        if ConstrainUnpredictableBool(Unpredictable_TRBPTR_Fault_AddressSize)then
            fault.statuscode = Fault_AddressSize;
        else
            oa.address = ZeroExtend{NUM_PABITS}(oa.address[oamax-1:0]);
        end;
    end;
end;

if fault.statuscode == Fault_None then
    if !addrchecked && addrtop > pamax && !IsZero(va[addrtop:pamax]) then
        fault.statuscode = Fault_AddressSize;
    elsif AArch64_S1HasAlignmentFaultDueToMemType(regime, accdesc, aligned, walkparams.ntlsmd,
                                                  memattrs) then
        fault.statuscode = Fault_Alignment;
    elsif ((accdesc.exclusive || accdesc.atomicop) &&
            !(regime == Regime_EL10 && EL2Enabled() &&
                IsFeatureImplemented(FEAT_HCRMAC) && HCR_EL2().DC == '1') &&
            ConstrainUnpredictableBool(Unpredictable_Atomic_MMU_IMPDEF_FAULT)) then
        fault.statuscode = Fault_Exclusive;
    end;
end;

if fault.statuscode != Fault_None then
    return (fault, ARBITRARY : AddressDescriptor);
else
    var ipa : AddressDescriptor = CreateAddressDescriptor(va_in, oa, memattrs, accdesc);
    ipa.mecid = AArch64_S1DisabledOutputMECID(walkparams, regime, ipa.paddress.paspace);
    return (fault, ipa);
end;

end;


## Library pseudocode for
aarch64/translation/vmsa\_translation/AArch64\_S1Translate

// AArch64_S1Translate // ===================== // Translate VA to IPA/PA depending on the regime

func AArch64_S1Translate(fault_in : FaultRecord, regime : Regime, va : bits(64), size : integer, aligned : boolean, accdesc : AccessDescriptor) => (FaultRecord, AddressDescriptor) recurselimit Unbounded_DescriptorUpdate begin var fault : FaultRecord = fault_in; // Prepare fault fields in case a fault is detected fault.secondstage = FALSE; fault.s2fs1walk = FALSE;

if (regime, accdesc.acctype) then
    return AArch64_S1DisabledOutput(fault, regime, va, accdesc, aligned);
end;

var walkparams : S1TTWParams = AArch64_GetS1TTWParams(regime, accdesc.el,
accdesc.ss, va);
let s1mintxsz : integer = AArch64_S1MinTxSZ(regime, walkparams);
let s1maxtxsz : integer = AArch64_MaxTxSZ(walkparams.tgx);
if AArch64_S1TxSZFaults(regime, walkparams) then
    fault.statuscode = Fault_Translation;
    fault.level      = 0;
    return (fault, ARBITRARY : AddressDescriptor);
elsif UInt(walkparams.txsz) < s1mintxsz then
    walkparams.txsz = s1mintxsz[5:0];
elsif UInt(walkparams.txsz) > s1maxtxsz then
    walkparams.txsz = s1maxtxsz[5:0];
end;

if AArch64_VAIsOutOfRange(va, accdesc.acctype, regime, walkparams) then
    fault.statuscode = Fault_Translation;
    fault.level      = 0;
    return (fault, ARBITRARY : AddressDescriptor);
end;

if accdesc.el == EL0 && walkparams.e0pd == '1' then
    fault.statuscode = Fault_Translation;
    fault.level      = 0;
    return (fault, ARBITRARY : AddressDescriptor);
end;

if (IsFeatureImplemented(FEAT_SVE) && accdesc.el == EL0 &&
walkparams.nfd == '1' &&
      ((accdesc.nonfault && accdesc.contiguous) ||
       (accdesc.firstfault && !accdesc.first && !accdesc.contiguous))) then
    fault.statuscode = Fault_Translation;
    fault.level      = 0;
    return (fault, ARBITRARY : AddressDescriptor);
end;

var descipaddr : AddressDescriptor;
var walkstate : TTWState;
var descriptor : bits(128);
if walkparams.d128 == '1' then
    (fault, descipaddr, walkstate, descriptor) = AArch64_S1Walk{128}(fault, walkparams, va,
                                                                     regime, accdesc);
else
    (fault, descipaddr, walkstate, descriptor[63:0]) = AArch64_S1Walk{64}(fault, walkparams, va,
                                                                          regime, accdesc);
    descriptor[127:64] = Zeros{64};
end;
if fault.statuscode != Fault_None then
    return (fault, ARBITRARY : AddressDescriptor);
end;
if AArch64_S1HasAlignmentFaultDueToMemType(regime, accdesc, aligned,
walkparams.ntlsmd,
                                           walkstate.memattrs) then
    fault.statuscode = Fault_Alignment;
end;

let fault_perm : FaultRecord = AArch64_S1CheckPermissions(fault, va, size,
regime,
                                                             walkstate, walkparams, accdesc);

var mem_desc : bits(128);
var new_desc : bits(128) = descriptor;

if AArch64_SetAccessFlag(walkparams.ha, accdesc, fault, fault_perm) then
    // Set descriptor AF bit
    new_desc[10] = '1';
end;

// If HW update of dirty bit is enabled, the walk state permissions
// will already reflect a configuration permitting writes.
// The update of the descriptor occurs only if the descriptor bits in
// memory do not reflect that and the access instigates a write.

if AArch64_SetDirtyState(walkparams.hd, (walkparams.pie OR descriptor[51]),
                         accdesc, fault, fault_perm) then
    // Clear descriptor AP[2]/nDirty bit permitting stage 1 writes
    new_desc[7] = '0';
end;

if fault.statuscode == Fault_None && fault_perm.statuscode !=
Fault_None then
    fault = fault_perm;
end;

// Either the access flag was clear or AP[2]/nDirty was set
if new_desc != descriptor then
    if ((descipaddr.memattrs) &&
          ConstrainUnpredictableBool(Unpredictable_Unsupported_Atomic_HW_Update)) then
        fault.statuscode = Fault_UnsupportedAtomicHWUpdate;
        return (fault, ARBITRARY : AddressDescriptor);
    end;

    var descpaddr : AddressDescriptor;
    let descaccess : AccessDescriptor = CreateAccDescTTEUpdate(accdesc);

    if regime == Regime_EL10 && EL2Enabled() then
        var s2fault : FaultRecord;
        let s1aarch64 : boolean = TRUE;
        let s2aligned : boolean = TRUE;
        (s2fault, descpaddr) = AArch64_S2Translate(fault, descipaddr, s1aarch64, s2aligned,
                                                   descaccess);
        if s2fault.statuscode != Fault_None then
            return (s2fault, ARBITRARY : AddressDescriptor);
        end;

    else
        descpaddr = descipaddr;
    end;
    if walkparams.d128 == '1' then
        (fault, mem_desc) = AArch64_MemSwapTableDesc{128}(fault, descriptor,
                                                          new_desc, walkparams.ee,
                                                          descaccess, descpaddr);
    else
        (fault, mem_desc[63:0]) = AArch64_MemSwapTableDesc{64}(fault, descriptor[63:0],
                                                               new_desc[63:0], walkparams.ee,
                                                               descaccess, descpaddr);
        mem_desc[127:64] = Zeros{64};
    end;

    if fault.statuscode != Fault_None then
        if (accdesc.acctype == AccessType_AT &&
                !(ImpDefBool("AT reports the HW update fault"))) then
            // Mask the fault
            fault.statuscode = Fault_None;
        else
            return (fault, ARBITRARY : AddressDescriptor);
        end;
    elsif new_desc != descriptor && mem_desc != new_desc then
        // HW update of Dirty state or AF was not successful due to the descriptor being updated
        // not matching the descriptor used for translation. Due to this, the walk is restarted.
        return AArch64_S1Translate(fault_in, regime, va, size, aligned, accdesc);
    end;
end;

if fault.statuscode != Fault_None then
    return (fault, ARBITRARY : AddressDescriptor);
end;

// Output Address
let oa : FullAddress = Stage1OA(va, walkparams, walkstate);

var memattrs : MemoryAttributes;
if AArch64_S1TreatAsNormalNC(walkstate, regime, accdesc) then
   // Treat memory attributes as Normal Non-Cacheable
    memattrs = NormalNCMemAttr();
    memattrs.xs = walkstate.memattrs.xs;

    // The effect of SCTLR_ELx.C when '0' is Constrained UNPREDICTABLE on the Tagged attribute
    // when the memory region is Allocation Tagged using Physical MTE.
    if (IsPMTESelected(accdesc.el) && walkstate.memattrs.tags == MemTag_AllocationTagged &&
          ConstrainUnpredictableBool(Unpredictable_S1CTAGGED)) then
        memattrs.tags = MemTag_AllocationTagged;
    // SCTLR_ELx.C has no effect on whether the memory region is treated as Canonically Tagged.
    elsif (IsFeatureImplemented(FEAT_MTE_CANONICAL_TAGS) &&
             walkstate.memattrs.tags == MemTag_CanonicallyTagged) then
        memattrs.tags = MemTag_CanonicallyTagged;
    end;
else
    memattrs = walkstate.memattrs;
end;

// Shareability value of stage 1 translation subject to stage 2 is
IMPLEMENTATION DEFINED
// to be either effective value or descriptor value
if (regime == Regime_EL10 && EL2Enabled() && HCR_EL2().VM ==
'1' &&
        !(ImpDefBool("Apply effective shareability at stage 1"))) then
    memattrs.shareability = walkstate.memattrs.shareability;
else
    memattrs.shareability = EffectiveShareability(memattrs);
end;

var ipa : AddressDescriptor = CreateAddressDescriptor(va, oa, memattrs,
accdesc);
ipa.s1assured = walkstate.s1assured;
let varange : VARange = AArch64_GetVARange(va);
ipa.mecid = AArch64_S1OutputMECID{128}(walkparams, regime, varange,
ipa.paddress.paspace,
                                      descriptor);

if (accdesc.atomicop && (memattrs) &&
      ConstrainUnpredictableBool(Unpredictable_Atomic_MMU_IMPDEF_FAULT)) then
    fault.statuscode = Fault_Exclusive;
    return (fault, ipa);
end;

if accdesc.ls64 && memattrs.memtype == MemType_Normal then
    if IsFeatureImplemented(FEAT_LS64WB) && !accdesc.withstatus then
        if ((memattrs) &&
              !(memattrs.inner.attrs == MemAttr_NC &&
                memattrs.outer.attrs == MemAttr_NC) &&
              (ImpDefBool(
                 "LD64B or ST64B faults to cacheable non-iWBoWB memory"))) then
            fault.statuscode = Fault_Exclusive;
            return (fault, ipa);
        end;
    elsif !(memattrs.inner.attrs == MemAttr_NC && memattrs.outer.attrs == MemAttr_NC) then
        fault.statuscode = Fault_Exclusive;
        return (fault, ipa);
    end;
end;

return (fault, ipa);

end;


## Library pseudocode for
aarch64/translation/vmsa\_translation/AArch64\_S1TreatAsNormalNC

// AArch64_S1TreatAsNormalNC // =========================== // Returns TRUE if stage 1 memory attributes should be treated as Normal Non-Cacheable

readonly func AArch64_S1TreatAsNormalNC(walkstate : TTWState, regime : Regime, accdesc : AccessDescriptor) => boolean begin return ((accdesc.acctype == AccessType_IFETCH && (walkstate.memattrs.memtype == MemType_Device || (regime))) || (accdesc.acctype != AccessType_IFETCH && (regime) && walkstate.memattrs.memtype == MemType_Normal)); end;


## Library pseudocode for
aarch64/translation/vmsa\_translation/AArch64\_S2Translate

// AArch64_S2Translate // ===================== // Translate stage 1 IPA to PA and combine memory attributes

func AArch64_S2Translate(fault_in : FaultRecord, ipa : AddressDescriptor, s1aarch64 : boolean, aligned : boolean, accdesc : AccessDescriptor) => (FaultRecord, AddressDescriptor) recurselimit Unbounded_DescriptorUpdate begin var walkparams : S2TTWParams = AArch64_GetS2TTWParams(accdesc.ss, ipa.paddress.paspace, s1aarch64); var fault : FaultRecord = fault_in; var s2fs1mro : boolean; // Prepare fault fields in case a fault is detected fault.statuscode = Fault_None; // Ignore any faults from stage 1 fault.dirtybit = FALSE; fault.overlay = FALSE; fault.tagaccess = FALSE; fault.s1tagnotdata = FALSE; fault.secondstage = TRUE; fault.s2fs1walk = accdesc.acctype == AccessType_TTW; fault.ipaddress = ipa.paddress;

if walkparams.vm != '1' then
    // Stage 2 translation is disabled
    return (fault, ipa);
end;

let s2mintxsz : integer = AArch64_S2MinTxSZ(walkparams, s1aarch64);
let s2maxtxsz : integer = AArch64_MaxTxSZ(walkparams.tgx);
if AArch64_S2TxSZFaults(walkparams, s1aarch64) then
    fault.statuscode = Fault_Translation;
    fault.level      = 0;
    return (fault, ARBITRARY : AddressDescriptor);
elsif UInt(walkparams.txsz) < s2mintxsz then
    walkparams.txsz = s2mintxsz[5:0];
elsif UInt(walkparams.txsz) > s2maxtxsz then
    walkparams.txsz = s2maxtxsz[5:0];
end;

if (walkparams.d128 == '0' &&
    (AArch64_S2InvalidSL(walkparams) || AArch64_S2InconsistentSL(walkparams))) then
    fault.statuscode = Fault_Translation;
    fault.level      = 0;
    return (fault, ARBITRARY : AddressDescriptor);
end;

if AArch64_IPAIsOutOfRange(ipa.paddress.address, walkparams) then
    fault.statuscode = Fault_Translation;
    fault.level      = 0;
    return (fault, ARBITRARY : AddressDescriptor);
end;

var descpaddr : AddressDescriptor;
var walkstate : TTWState;
var descriptor : bits(128);
if walkparams.d128 == '1' then
    (fault, descpaddr, walkstate, descriptor) = AArch64_S2Walk{128}(fault, ipa, walkparams,
                                                                    accdesc);
else
    (fault, descpaddr, walkstate, descriptor[63:0]) = AArch64_S2Walk{64}(fault, ipa, walkparams,
                                                                         accdesc);
    descriptor[127:64] = Zeros{64};
end;
if fault.statuscode != Fault_None then
    return (fault, ARBITRARY : AddressDescriptor);
end;

if AArch64_S2HasAlignmentFaultDueToMemType(accdesc, aligned,
walkstate.memattrs) then
    fault.statuscode = Fault_Alignment;
end;

var fault_perm : FaultRecord;
(fault_perm, s2fs1mro) = AArch64_S2CheckPermissions(fault, walkstate,
walkparams, ipa, accdesc);

var mem_desc : bits(128);
var new_desc : bits(128) = descriptor;

if AArch64_SetAccessFlag(walkparams.ha, accdesc, fault, fault_perm) then
    // Set descriptor AF bit
    new_desc[10] = '1';
end;

// If HW update of dirty bit is enabled, the walk state permissions
// will already reflect a configuration permitting writes.
// The update of the descriptor occurs only if the descriptor bits in
// memory do not reflect that and the access instigates a write.

if AArch64_SetDirtyState(walkparams.hd, (walkparams.s2pie OR descriptor[51]),
                         accdesc, fault, fault_perm) then
    // Set descriptor S2AP[1]/Dirty bit permitting stage 2 writes
    new_desc[7] = '1';
end;

if fault.statuscode == Fault_None && fault_perm.statuscode !=
Fault_None then
    fault = fault_perm;
end;

// Either the access flag was clear or S2AP[1]/Dirty was clear
if new_desc != descriptor then
    if ((descpaddr.memattrs) &&
          ConstrainUnpredictableBool(Unpredictable_Unsupported_Atomic_HW_Update)) then
        fault.statuscode = Fault_UnsupportedAtomicHWUpdate;
        return (fault, ARBITRARY : AddressDescriptor);
    end;

    if walkparams.hdbss == '1' && descriptor[7] == '0' && new_desc[7] == '1' then
        fault = AppendToHDBSS(fault, ipa.paddress, accdesc, walkparams, walkstate.level);
    end;

    // If an error, other than a synchronous External abort, occurred on the HDBSS update,
    // stage 2 hardware update of dirty state is not permitted.
    if (!(walkparams.hdbss == '1' && descriptor[7] != new_desc[7]) ||
          (HDBSSPROD_EL2().FSC != '101000' &&
            (!fault.hdbssf || IsExternalAbort(fault.statuscode)))) then
        let descaccess : AccessDescriptor = CreateAccDescTTEUpdate(accdesc);
        if walkparams.d128 == '1' then
            (fault, mem_desc) = AArch64_MemSwapTableDesc{128}(fault, descriptor, new_desc,
                                                         walkparams.ee, descaccess,
                                                         descpaddr);
        else
            (fault, mem_desc[63:0]) = AArch64_MemSwapTableDesc{64}(fault, descriptor[63:0],
                                                               new_desc[63:0], walkparams.ee,
                                                               descaccess, descpaddr);
            mem_desc[127:64] = Zeros{64};
        end;
    end;

    if fault.statuscode != Fault_None then
        if (accdesc.acctype == AccessType_AT &&
                !(ImpDefBool("AT reports the HW update fault"))) then
            // Mask the fault
            fault.statuscode = Fault_None;
        else
            return (fault, ARBITRARY : AddressDescriptor);
        end;
    elsif new_desc != descriptor && mem_desc != new_desc then
        // HW update of Dirty state or AF was not successful due to the descriptor being updated
        // not matching the descriptor used for translation. Due to this, the walk is restarted.
        return AArch64_S2Translate(fault_in, ipa, s1aarch64, aligned, accdesc);
    end;
end;

if fault.statuscode != Fault_None then
    return (fault, ARBITRARY : AddressDescriptor);
end;

// Output Address
let oa : FullAddress = Stage2OA(ipa.paddress.address, walkparams, walkstate);
var s2_memattrs : MemoryAttributes;

if AArch64_S2TreatAsNormalNC(walkstate, walkparams, accdesc) then
    // Treat memory attributes as Normal Non-Cacheable
    s2_memattrs = NormalNCMemAttr();
    s2_memattrs.xs = walkstate.memattrs.xs;
    if walkstate.memattrs.tags == MemTag_CanonicallyTagged then
        s2_memattrs.tags = MemTag_CanonicallyTagged;
    end;
else
    s2_memattrs = walkstate.memattrs;
end;

let s2aarch64 : boolean = TRUE;
var memattrs : MemoryAttributes;
if walkparams.fwb == '0' then
    memattrs = S2CombineS1MemAttrs(ipa.memattrs, s2_memattrs, s2aarch64);
else
    memattrs = s2_memattrs;
end;

var pa : AddressDescriptor = CreateAddressDescriptor(ipa.vaddress, oa,
memattrs, accdesc);
pa.s2fs1mro = s2fs1mro;
pa.mecid = AArch64_S2OutputMECID{128}(walkparams, pa.paddress.paspace,
descriptor);

if (accdesc.acctype == AccessType_TTW && accdesc.atomicop &&
(pa.memattrs) &&
      ConstrainUnpredictableBool(Unpredictable_Unsupported_Atomic_HW_Update)) then
    fault.statuscode = Fault_UnsupportedAtomicHWUpdate;
    return (fault, pa);
end;

if (accdesc.acctype != AccessType_TTW && accdesc.atomicop &&
(pa.memattrs) &&
      ConstrainUnpredictableBool(Unpredictable_Atomic_MMU_IMPDEF_FAULT)) then
    fault.statuscode = Fault_Exclusive;
    return (fault, pa);
end;

if accdesc.ls64 && s2_memattrs.memtype == MemType_Normal then
    if IsFeatureImplemented(FEAT_LS64WB) && !accdesc.withstatus then
        if ((s2_memattrs) &&
              !(s2_memattrs.inner.attrs == MemAttr_NC &&
                s2_memattrs.outer.attrs == MemAttr_NC) &&
              (ImpDefBool(
                 "LD64B or ST64B faults to cacheable non-iWBoWB memory"))) then
            fault.statuscode = Fault_Exclusive;
            return (fault, pa);
        end;
    elsif !(s2_memattrs.inner.attrs == MemAttr_NC && s2_memattrs.outer.attrs == MemAttr_NC) then
        fault.statuscode = Fault_Exclusive;
        return (fault, pa);
    end;
end;

return (fault, pa);

end;


## Library pseudocode for
aarch64/translation/vmsa\_translation/AArch64\_S2TreatAsNormalNC

// AArch64_S2TreatAsNormalNC // =========================== // Returns TRUE if stage 2 memory attributes should be treated as Normal Non-cacheable

readonly func AArch64_S2TreatAsNormalNC(walkstate : TTWState, walkparams : S2TTWParams, accdesc : AccessDescriptor) => boolean begin return ((accdesc.acctype == AccessType_TTW && walkstate.memattrs.memtype == MemType_Device && walkparams.ptw == '0') || (accdesc.acctype == AccessType_IFETCH && (walkstate.memattrs.memtype == MemType_Device || ())) || (accdesc.acctype != AccessType_IFETCH && walkstate.memattrs.memtype == MemType_Normal && ())); end;


## Library pseudocode for
aarch64/translation/vmsa\_translation/AArch64\_SetAccessFlag

// AArch64_SetAccessFlag // ======================= // Determine whether the access flag could be set by HW given the fault status

func AArch64_SetAccessFlag(ha : bit, accdesc : AccessDescriptor, fault : FaultRecord, fault_perm : FaultRecord) => boolean begin if ha == '0' || (fault, fault_perm) then return FALSE; elsif accdesc.acctype == AccessType_AT then return ImpDefBool("AT updates AF"); elsif accdesc.acctype IN {AccessType_DC, AccessType_IC} then return ImpDefBool("Generate access flag fault on IC/DC operations"); else // Set descriptor AF bit return TRUE; end; end;


## Library pseudocode for
aarch64/translation/vmsa\_translation/AArch64\_SetDirtyState

// AArch64_SetDirtyState // ======================= // Determine whether dirty state is required to be updated by HW given the fault status

func AArch64_SetDirtyState(hd : bits(1), dbm : bits(1), accdesc : AccessDescriptor, fault : FaultRecord, fault_perm : FaultRecord) => boolean begin if hd == '0' then return FALSE; elsif (fault, fault_perm) then return FALSE; elsif accdesc.acctype IN {AccessType_AT, AccessType_IC, AccessType_DC} then return FALSE; elsif !accdesc.write then return FALSE; else return dbm == '1'; end; end;


## Library pseudocode for
aarch64/translation/vmsa\_translation/AArch64\_SettingAccessFlagPermitted

// AArch64_SettingAccessFlagPermitted // ==================================== // Determine whether the access flag could be set by HW given the fault status

func AArch64_SettingAccessFlagPermitted(fault : FaultRecord, fault_perm : FaultRecord) => boolean begin if fault.statuscode == Fault_None && fault_perm.statuscode == Fault_None then return TRUE; elsif fault.statuscode == Fault_Alignment || fault_perm.statuscode == Fault_Permission then return ConstrainUnpredictableBool(Unpredictable_AFUPDATE); else return FALSE; end; end;


## Library pseudocode for
aarch64/translation/vmsa\_translation/AArch64\_SettingDirtyStatePermitted

// AArch64_SettingDirtyStatePermitted // ==================================== // Determine whether the dirty state could be set by HW given the fault status

func AArch64_SettingDirtyStatePermitted(fault : FaultRecord, fault_perm : FaultRecord) => boolean begin if fault_perm.statuscode != Fault_None then return FALSE; elsif fault.statuscode == Fault_None then return TRUE; elsif fault.statuscode == Fault_Alignment then return ConstrainUnpredictableBool(Unpredictable_DBUPDATE); else return FALSE; end; end;


## Library pseudocode for
aarch64/translation/vmsa\_translation/AArch64\_TranslateAddress

// AArch64_TranslateAddress // ========================== // Main entry point for translating an address

func AArch64_TranslateAddress(va : bits(64), accdesc : AccessDescriptor, aligned : boolean, size : integer) => AddressDescriptor begin if (SPESampleInFlight && !(accdesc.acctype IN {AccessType_IFETCH, AccessType_SPE, AccessType_TRBE})) then SPEStartCounter(SPECounterPosTranslationLatency); end;

var result : AddressDescriptor = AArch64_FullTranslate(va, size,
accdesc, aligned);

if (!IsFault(result) && accdesc.acctype != AccessType_IFETCH
&&
      !ImpDefBool(
          "GPF, GPC, Data SyncExternal Aborts, TagChecks prioritized over Watchpoints")) then
    result.fault = AArch64_CheckDebug(va, accdesc, size);
end;

if (IsFeatureImplemented(FEAT_RME) && !IsFault(result) &&
      IsGranuleProtectionCheckedAccess(accdesc)) then
    result.fault.gpcf = GranuleProtectionCheck(result, accdesc);

    if result.fault.gpcf.gpf != GPCF_None then
        result.fault.statuscode = Fault_GPCFOnOutput;
        result.fault.paddress   = result.paddress;
        result.fault.vaddress   = result.vaddress;
    end;
end;

if (!IsFault(result) && accdesc.acctype == AccessType_IFETCH
&&
      !ImpDefBool("Instruction SyncExternal Aborts prioritized over Breakpoints")) then
    result.fault = AArch64_CheckDebug(va, accdesc, size);
end;

if SPESampleInFlight &&
    !(accdesc.acctype IN {AccessType_IFETCH, AccessType_TRBE, AccessType_SPE}) then
    SPEStopCounter(SPECounterPosTranslationLatency);
end;

// Update virtual address for abort functions
result.vaddress = ZeroExtend{64}(va);

return result;

end;


## Library pseudocode for
aarch64/translation/vmsa\_translation/AArch64\_TranslateTagAddress

// AArch64_TranslateTagAddress // ============================= // Translate an address for accessing an Allocation Tag.

func AArch64_TranslateTagAddress(va : bits(64), accdesc_in : AccessDescriptor, aligned : boolean, size : integer) => (MemTagType, AddressDescriptor) begin assert !accdesc_in.tagchecked; var accdesc : AccessDescriptor = accdesc_in; let taddrdesc : AddressDescriptor = AArch64_TranslateAddress(va, accdesc, aligned, size);

return (taddrdesc.memattrs.tags, taddrdesc);

end;


## Library pseudocode for
aarch64/translation/vmsa\_ttentry/AArch64\_BlockDescSupported

// AArch64_BlockDescSupported // ============================ // Determine whether a block descriptor is valid for the given granule size // and level

func AArch64_BlockDescSupported(d128 : bit, ds : bit, tgx : TGx, level : integer) => boolean begin case tgx of when TGx_4KB => return ((level == 0 && (ds == '1' || d128 == '1')) || level == 1 || level == 2); when TGx_16KB => return ((level == 1 && (ds == '1' || d128 == '1')) || level == 2); when TGx_64KB => return ((level == 1 && (d128 == '1' || AArch64_PAMax() >= 52)) || level == 2); end; return FALSE; end;


## Library pseudocode for
aarch64/translation/vmsa\_ttentry/AArch64\_ContiguousBit

// AArch64_ContiguousBit // ======================= // Get the value of the contiguous bit

func AArch64_ContiguousBit{N}(tgx : TGx, d128 : bit, level : integer, descriptor : bits(N)) => bit begin if ImpDefBool("Treat Contiguous bit as 0") then return '0'; end;

if d128 == '1' then
    if (tgx == TGx_64KB && level == 1) || (tgx == TGx_4KB && level == 0) then
        return '0'; // RES0
    else
        return descriptor[111];
    end;
end;
// When using TGx 64KB then the Contiguous bit is RES0 for Block
// descriptors at level 1. For VMSAv8-64, level 1 Block descriptors
// can exist only if FEAT_LPA is implemented.

if tgx == TGx_64KB && level == 1 then
    return '0'; // RES0
end;

// When the Effective value of TCR_ELx.DS is '1',
// the Contiguous bit is RES0 for all the following:
//      * For TGx 4KB, Block descriptors at level 0
//      * For TGx 16KB, Block descriptors at level 1
// For VMSAv8-64, the above Block descriptors at the specified
// levels can exist only if the Effective value of TCR_ELx.DS is 1.

if tgx == TGx_16KB && level == 1 then
    return '0'; // RES0
end;

if tgx == TGx_4KB  && level == 0 then
    return '0'; // RES0
end;

return descriptor[52];

end;


## Library pseudocode for
aarch64/translation/vmsa\_ttentry/AArch64\_DecodeDescriptorType

// AArch64_DecodeDescriptorType // ============================== // Determine whether the descriptor is a page, block or table

func AArch64_DecodeDescriptorType{N}(descriptor : bits(N), d128 : bit, ds : bit, tgx : TGx, level : integer) => DescriptorType begin if descriptor[0] == '0' then return DescriptorType_Invalid; elsif d128 == '1' then let skl : bits(2) = descriptor[110:109]; if tgx IN {TGx_16KB, TGx_64KB} && UInt(skl) == 3 then return DescriptorType_Invalid; end;

    let effective_level : integer = level + UInt(skl);
    if effective_level > FINAL_LEVEL then
        return DescriptorType_Invalid;
    elsif effective_level == FINAL_LEVEL then
        return DescriptorType_Leaf;
    else
        return DescriptorType_Table;
    end;
else
    if descriptor[1] == '1' then
        if level == FINAL_LEVEL then
            return DescriptorType_Leaf;
        else
            return DescriptorType_Table;
        end;
    elsif descriptor[1] == '0' then
        if AArch64_BlockDescSupported(d128, ds, tgx, level) then
            return DescriptorType_Leaf;
        else
            return DescriptorType_Invalid;
        end;
    end;
    unreachable;
end;

end;


## Library pseudocode for
aarch64/translation/vmsa\_ttentry/AArch64\_S1ApplyOutputPerms

// AArch64_S1ApplyOutputPerms // ============================ // Apply output permissions encoded in stage 1 page/block descriptors

func AArch64_S1ApplyOutputPerms{N}(permissions_in : Permissions, descriptor : bits(N), regime : Regime, walkparams : S1TTWParams) => Permissions begin var permissions : Permissions = permissions_in;

var pi_index : bits (4);
if walkparams.pie == '1' then
    if walkparams.d128 == '1' then
        pi_index = descriptor[118:115];
    else
        pi_index = descriptor[54:53]::descriptor[51]::descriptor[6];
    end;
    permissions.ppi    = walkparams.pir[UInt(pi_index)*:4];
    permissions.upi    = walkparams.pire0[UInt(pi_index)*:4];
    permissions.ndirty = descriptor[7];
else
    if regime == Regime_EL10 && EL2Enabled() && walkparams.nv1 == '1' then
        permissions.ap[2:1] = descriptor[7]::'0';
        permissions.pxn     = descriptor[54];
    elsif HasUnprivileged(regime) then
        permissions.ap[2:1] = descriptor[7:6];
        permissions.uxn     = descriptor[54];
        permissions.pxn     = descriptor[53];
    else
        permissions.ap[2:1] = descriptor[7]::'1';
        permissions.xn      = descriptor[54];
    end;
    permissions.dbm = descriptor[51];
end;
if IsFeatureImplemented(FEAT_S1POE) then
    if walkparams.d128 == '1' then
        permissions.po_index[3:0] = descriptor[124:121];
    else
        permissions.po_index[3:0] = '0'::descriptor[62:60];
    end;
end;

return permissions;

end;


## Library pseudocode for
aarch64/translation/vmsa\_ttentry/AArch64\_S1ApplyTablePerms

// AArch64_S1ApplyTablePerms // =========================== // Apply hierarchical permissions encoded in stage 1 table descriptors

func AArch64_S1ApplyTablePerms(permissions_in : Permissions, descriptor : bits(64), regime : Regime, walkparams : S1TTWParams) => Permissions begin var permissions : Permissions = permissions_in; var ap_table : bits(2); var pxn_table : bit; var uxn_table : bit; var xn_table : bit; if regime == Regime_EL10 && EL2Enabled() && walkparams.nv1 == '1' then ap_table = descriptor[62]::'0'; pxn_table = descriptor[60]; permissions.ap_table = permissions.ap_table OR ap_table; permissions.pxn_table = permissions.pxn_table OR pxn_table;

elsif HasUnprivileged(regime) then
    ap_table  = descriptor[62:61];
    uxn_table = descriptor[60];
    pxn_table = descriptor[59];
    permissions.ap_table  = permissions.ap_table  OR ap_table;
    permissions.uxn_table = permissions.uxn_table OR uxn_table;
    permissions.pxn_table = permissions.pxn_table OR pxn_table;
else
    ap_table = descriptor[62]::'0';
    xn_table = descriptor[60];
    permissions.ap_table = permissions.ap_table OR ap_table;
    permissions.xn_table = permissions.xn_table OR xn_table;
end;

return permissions;

end;


## Library pseudocode for
aarch64/translation/vmsa\_ttentry/AArch64\_S2ApplyOutputPerms

// AArch64_S2ApplyOutputPerms // ============================ // Apply output permissions encoded in stage 2 page/block descriptors

func AArch64_S2ApplyOutputPerms{N}(descriptor : bits(N), walkparams : S2TTWParams) => Permissions begin var permissions : Permissions; var s2pi_index : bits(4); if walkparams.s2pie == '1' then if walkparams.d128 == '1' then s2pi_index = descriptor[118:115]; else s2pi_index = descriptor[54:53,51,6]; end; permissions.s2pi = walkparams.s2pir[UInt(s2pi_index)*:4]; permissions.s2dirty = descriptor[7]; else permissions.s2ap = descriptor[7:6]; if walkparams.d128 == '1' then permissions.s2xn = descriptor[118]; else permissions.s2xn = descriptor[54]; end;

    if IsFeatureImplemented(FEAT_XNX) then
        if walkparams.d128 == '1' then
            permissions.s2xnx = descriptor[117];
        else
            permissions.s2xnx = descriptor[53];
        end;
    else
        permissions.s2xnx = '0';
    end;

    permissions.dbm = descriptor[51];
end;
if IsFeatureImplemented(FEAT_S2POE) then
    if walkparams.d128 == '1' then
        permissions.s2po_index = descriptor[124:121];
    else
        permissions.s2po_index = descriptor[62:59];
    end;
end;
return permissions;

end;


## Library pseudocode for aarch64/translation/vmsa\_ttentry/AArch64\_nTFaults

// AArch64_nTFaults // ================== // Identify whether the nT bit in a block or table descriptor is effectively set // causing a translation fault

func AArch64_nTFaults{N}(d128 : bit, descriptor : bits(N)) => boolean begin if !IsFeatureImplemented(FEAT_BBML1) then return FALSE; end; let nT : bit = if d128 == '1' then descriptor[6] else descriptor[16];

return nT == '1' && ImpDefBool("nT bit causes Translation
Fault");

end;


## Library pseudocode for
aarch64/translation/vmsa\_walk/AArch64\_S1InitialTTWState

// AArch64_S1InitialTTWState // =========================== // Set properties of first access to translation tables in stage 1

func AArch64_S1InitialTTWState(walkparams : S1TTWParams, va : bits(64), regime : Regime, ss : SecurityState) => TTWState begin var walkstate : TTWState; var tablebase : FullAddress; var permissions : Permissions; var ttbr : bits(128);

ttbr              = AArch64_S1TTBR(regime, va);
case ss of
    when SS_Secure =>    tablebase.paspace = PAS_Secure;
    when SS_NonSecure => tablebase.paspace = PAS_NonSecure;
    when SS_Root =>      tablebase.paspace = PAS_Root;
    when SS_Realm =>     tablebase.paspace = PAS_Realm;
end;

tablebase.address = AArch64_S1TTBaseAddress{128}(walkparams, regime, ttbr);

permissions.ap_table = '00';
if HasUnprivileged(regime) then
    permissions.uxn_table = '0';
    permissions.pxn_table = '0';
else
    permissions.xn_table  = '0';
end;

walkstate.baseaddress = tablebase;
walkstate.level       = AArch64_S1StartLevel(walkparams);
walkstate.istable     = TRUE;
// In regimes that support global and non-global translations, translation
// table entries from lookup levels other than the final level of lookup
// are treated as being non-global
walkstate.nG          = if HasUnprivileged(regime) then '1' else '0';
walkstate.memattrs = WalkMemAttrs(walkparams.sh, walkparams.irgn,
walkparams.orgn);
walkstate.permissions = permissions;
if regime == Regime_EL10 && EL2Enabled() && HCR_EL2().VM ==
'1' then
    if ((AArch64_GetVARange(va) == VARange_LOWER && VTCR_EL2().TL0 == '1') ||
        (AArch64_GetVARange(va) == VARange_UPPER && VTCR_EL2().TL1 == '1')) then
        walkstate.s1assured = TRUE;
    else
        walkstate.s1assured = FALSE;
    end;
else
    walkstate.s1assured = FALSE;
end;
walkstate.disch = walkparams.disch;

return walkstate;

end;


## Library pseudocode for
aarch64/translation/vmsa\_walk/AArch64\_S1NextWalkStateLeaf

// AArch64_S1NextWalkStateLeaf // ============================= // Decode stage 1 page or block descriptor as output to this stage of translation

func AArch64_S1NextWalkStateLeaf{N}(currentstate : TTWState, s2fs1mro : boolean, regime : Regime, accdesc : AccessDescriptor, walkparams : S1TTWParams, descriptor : bits(N)) => TTWState begin var nextstate : TTWState; var baseaddress : FullAddress; baseaddress.address = AArch64_S1LeafBase{N}(descriptor, walkparams, currentstate.level);

if currentstate.baseaddress.paspace == PAS_Secure then
    // Determine PA space of the block from NS bit
    let ns : bit = if walkparams.d128 == '1' then descriptor[127] else descriptor[5];
    baseaddress.paspace = if ns == '0' then PAS_Secure else PAS_NonSecure;
elsif currentstate.baseaddress.paspace == PAS_Root then
    // Determine PA space of the block from NSE and NS bits
    let ns : bit = if walkparams.d128 == '1' then descriptor[127] else descriptor[5];
    let nse : bit = descriptor[11];
    let nse2 : bit = '0';     // NSE2 has the Effective value of 0 within a PE.
    baseaddress.paspace = DecodePASpace(nse2, nse, ns);

    // If Secure state is not implemented, but RME is,
    // force Secure space accesses to Non-secure space
    if baseaddress.paspace == PAS_Secure && () then
        baseaddress.paspace = PAS_NonSecure;
    end;

elsif (currentstate.baseaddress.paspace == PAS_Realm &&
        regime IN {Regime_EL2, Regime_EL20}) then
    // Realm EL2 and EL2&0 regimes have a stage 1 NS bit
    let ns : bit = if walkparams.d128 == '1' then descriptor[127] else descriptor[5];
    baseaddress.paspace = if ns == '0' then PAS_Realm else PAS_NonSecure;
elsif currentstate.baseaddress.paspace == PAS_Realm then
    // Realm EL1&0 regime does not have a stage 1 NS bit
    baseaddress.paspace = PAS_Realm;
else
    baseaddress.paspace = PAS_NonSecure;
end;

nextstate.istable     = FALSE;
nextstate.level       = currentstate.level;
nextstate.baseaddress = baseaddress;

var attrindx : bits(4);
if walkparams.aie == '1' then
    if walkparams.d128 == '1' then
        attrindx = descriptor[5:2];
    else
        attrindx = descriptor[59,4:2];
    end;
else
    attrindx = '0'::descriptor[4:2];
end;

var sh : bits(2);
if walkparams.d128 == '1' then
    sh = descriptor[9:8];
elsif walkparams.ds == '1' then
    sh = walkparams.sh;
else
    sh = descriptor[9:8];
end;
let attr : bits(8) = AArch64_MAIRAttr(UInt(attrindx), walkparams.mair2,
walkparams.mair);
let s1aarch64 : boolean = TRUE;

nextstate.memattrs = S1DecodeMemAttrs(attr, sh, s1aarch64, walkparams,
accdesc.acctype);
nextstate.permissions =
AArch64_S1ApplyOutputPerms{N}(currentstate.permissions,
                                                   descriptor, regime, walkparams);
var protectedbit : bit;
if walkparams.d128 == '1' then
    protectedbit = descriptor[114];
else
    protectedbit = if walkparams.pnch == '1' then descriptor[52] else '0';
end;
if (currentstate.s1assured && s2fs1mro && protectedbit == '1')
then
    nextstate.s1assured = TRUE;
else
    nextstate.s1assured = FALSE;
end;

if walkparams.pnch == '1' || currentstate.disch == '1' then
    nextstate.contiguous = '0';
else
    nextstate.contiguous = AArch64_ContiguousBit{N}(walkparams.tgx, walkparams.d128,
                                                    currentstate.level, descriptor);
end;
if (regime) then
    nextstate.nG = '0';
elsif accdesc.ss == SS_Secure && currentstate.baseaddress.paspace ==
PAS_NonSecure then
    // In Secure state, a translation must be treated as non-global,
    // regardless of the value of the nG bit,
    // if NSTable is set to 1 at any level of the translation table walk
    nextstate.nG = '1';
elsif walkparams.fng == '1' then
    // Translations are treated as non-global regardless of the value of the nG bit.
    nextstate.nG = '1';
elsif (regime == Regime_EL10 && EL2Enabled() && HCR_EL2().VM
== '1' &&
        (walkparams.d128 == '1' || walkparams.pnch == '1') &&
        !nextstate.s1assured && walkparams.fngna == '1') then
    // Translations are treated as non-global regardless of the value of the nG bit.
    nextstate.nG = '1';
else
    nextstate.nG = descriptor[11];
end;

if walkparams.d128 == '1' then
    nextstate.guardedpage = descriptor[113];
else
    nextstate.guardedpage = descriptor[50];
end;

return nextstate;

end;


## Library pseudocode for
aarch64/translation/vmsa\_walk/AArch64\_S1NextWalkStateTable

// AArch64_S1NextWalkStateTable // ============================== // Decode stage 1 table descriptor to transition to the next level

func AArch64_S1NextWalkStateTable{N}(currentstate : TTWState, s2fs1mro : boolean, regime : Regime, walkparams : S1TTWParams, descriptor : bits(N)) => TTWState begin var nextstate : TTWState; var tablebase : FullAddress; let skl : bits(2) = if walkparams.d128 == '1' then descriptor[110:109] else '00'; tablebase.address = AArch64_NextTableBase{N}(descriptor, walkparams.d128, skl, walkparams.ds, walkparams.tgx);

if currentstate.baseaddress.paspace == PAS_Secure then
    // Determine PA space of the next table from NSTable bit
    var nstable : bit;
    nstable = if walkparams.d128 == '1' then descriptor[127] else descriptor[63];
    tablebase.paspace = if nstable == '0' then PAS_Secure else PAS_NonSecure;
else
    // Otherwise bit 63 is RES0 and there is no NSTable bit
    tablebase.paspace = currentstate.baseaddress.paspace;
end;

nextstate.istable     = TRUE;
nextstate.nG          = currentstate.nG;
if walkparams.d128 == '1' then
    nextstate.level   = currentstate.level + UInt(skl) + 1;
else
    nextstate.level   = currentstate.level + 1;
end;
nextstate.baseaddress = tablebase;
nextstate.memattrs    = currentstate.memattrs;
if walkparams.hpd == '0' && walkparams.pie == '0' then
    nextstate.permissions = AArch64_S1ApplyTablePerms(currentstate.permissions,
                                                      descriptor[63:0], regime, walkparams);
else
    nextstate.permissions = currentstate.permissions;
end;
var protectedbit : bit;
if walkparams.d128 == '1' then
    protectedbit = descriptor[114];
else
    protectedbit = if walkparams.pnch == '1' then descriptor[52] else '0';
end;
if (currentstate.s1assured && s2fs1mro && protectedbit == '1')
then
    nextstate.s1assured = TRUE;
else
    nextstate.s1assured = FALSE;
end;
nextstate.disch = if walkparams.d128 == '1' then descriptor[112] else '0';

return nextstate;

end;


## Library pseudocode for aarch64/translation/vmsa\_walk/AArch64\_S1Walk

// AArch64_S1Walk // ================ // Traverse stage 1 translation tables obtaining the final descriptor // as well as the address leading to that descriptor

func AArch64_S1Walk{N : integer{64, 128}}(fault_in : FaultRecord, walkparams : S1TTWParams, va : bits(64), regime : Regime, accdesc : AccessDescriptor ) => (FaultRecord, AddressDescriptor, TTWState, bits(N)) begin var fault : FaultRecord = fault_in; var aligned : boolean;

if HasUnprivileged(regime) && AArch64_S1EPD(regime, va) ==
'1' then
    fault.statuscode = Fault_Translation;
    fault.level      = 0;
    return (fault, ARBITRARY : AddressDescriptor, ARBITRARY : TTWState, ARBITRARY : bits(N));
end;

var walkstate : TTWState = AArch64_S1InitialTTWState(walkparams, va, regime,
accdesc.ss);
let startlevel : integer = walkstate.level;

if startlevel > 3 then
    fault.statuscode = Fault_Translation;
    fault.level      = 0;
    return (fault, ARBITRARY : AddressDescriptor, ARBITRARY : TTWState, ARBITRARY : bits(N));
end;

var descriptor : bits(N);
var walkaddress : AddressDescriptor;
var skl : bits(2) = '00';
walkaddress.vaddress = va;
walkaddress.mecid = AArch64_S1TTWalkMECID(walkparams.emec, regime,
accdesc.ss);

if (regime) then
    walkaddress.memattrs = NormalNCMemAttr();
    walkaddress.memattrs.xs = walkstate.memattrs.xs;
else
    walkaddress.memattrs = walkstate.memattrs;
end;

// Shareability value of stage 1 translation subject to stage 2 is
IMPLEMENTATION DEFINED
// to be either effective value or descriptor value
------------------------------------------------------------------------------ Page 1 of 1. End of thread.