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

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

    return PMUCounterRange_R1;
elsif n == INSTRUCTION_COUNTER_ID then
    assert IsFeatureImplemented(FEAT_PMUv3_ICNTR);
    return PMUCounterRange_R1;
else
    unreachable;
end;

end;


## Library pseudocode for shared/debug/pmu/GetPMUReadMask

// GetPMUReadMask // ================ // Return a mask of the PMU counters that can be read at the current // Exception level. // This mask masks reads from PMCNTENSET_EL0, PMCNTENCLR_EL0, PMINTENSET_EL1, // PMINTENCLR_EL1, PMOVSSET_EL0, and PMOVSCLR_EL0.

func GetPMUReadMask() => bits(64) begin var mask : bits(64) = SysRegGetPMUAccessMask();

// Additional PMICNTR_EL0 accessibility checks. PMICNTR_EL0
controls read-as-zero
// if a read of PMICFILTR_EL0 would be trapped to a higher Exception level.
if IsFeatureImplemented(FEAT_PMUv3_ICNTR) &&
mask[INSTRUCTION_COUNTER_ID] == '1' then
    // Check for trap to EL3.
    if HaveEL(EL3) && PSTATE.EL != EL3 && MDCR_EL3().EnPM2 == '0' then
        mask[INSTRUCTION_COUNTER_ID] = '0';
    end;

    // Check for trap to EL2.
    if EL2Enabled() && PSTATE.EL IN {EL0, EL1} && (EL0) then
        // If FEAT_PMUv3_ICNTR and EL2 are implemented, then so is FEAT_FGT2.
        assert IsFeatureImplemented(FEAT_FGT2);
        if ((HaveEL(EL3) && SCR_EL3().FGTEn2 == '0') ||
              HDFGRTR2_EL2().nPMICFILTR_EL0 == '0') then
            mask[INSTRUCTION_COUNTER_ID] = '0';
        end;
    end;
end;

// Traps on other counters do not affect those counters' controls in the same
way.

return mask;

end;


## Library pseudocode for shared/debug/pmu/GetPMUWriteMask

// GetPMUWriteMask // ================= // Return a mask of the PMU counters writable at the current Exception level. // This mask masks writes to PMCNTENSET_EL0, PMCNTENCLR_EL0, PMINTENSET_EL1, // PMINTENCLR_EL1, PMOVSSET_EL0, PMOVSCLR_EL0, and PMZR_EL0. // 'write_counter' is TRUE for a write to PMZR_EL0, when the counter is being // updated, and FALSE for other cases when the controls are being updated.

func GetPMUWriteMask(write_counter : boolean) => bits(64) begin var mask : bits(64) = SysRegGetPMUAccessMask();

// Check EL0 ignore write conditions
if (IsFeatureImplemented(FEAT_PMUv3p9) && (EL1) &&
      PSTATE.EL == EL0 && PMUSERENR_EL0().UEN == '1') then
    if (IsFeatureImplemented(FEAT_PMUv3_ICNTR) &&
          PMUSERENR_EL0().IR == '1') then          // PMICNTR_EL0 read-only
        mask[INSTRUCTION_COUNTER_ID] = '0';
    end;
    if PMUSERENR_EL0().CR == '1' then              // PMCCNTR_EL0 read-only
        mask[CYCLE_COUNTER_ID] = '0';
    end;
    if PMUSERENR_EL0().ER == '1' then              // PMEVCNTR[n]_EL0 read-only
        mask[30:0] = Zeros{31};
    end;
end;

// Additional PMICNTR_EL0 accessibility checks. PMICNTR_EL0 controls ignore
writes
// if a write of PMICFILTR_EL0 would be trapped to a higher Exception level.
// Indirect writes to PMICNTR_EL0 (through PMZR_EL0) are ignored if a write of
// PMICNTR_EL0 would be trapped to a higher Exception level.
if IsFeatureImplemented(FEAT_PMUv3_ICNTR) &&
mask[INSTRUCTION_COUNTER_ID] == '1' then
    // Check for trap to EL3.
    if HaveEL(EL3) && PSTATE.EL != EL3 && MDCR_EL3().EnPM2 == '0' then
        mask[INSTRUCTION_COUNTER_ID] = '0';
    end;

    // Check for trap to EL2.
    if EL2Enabled() && PSTATE.EL IN {EL0, EL1} && (EL0) then
        // If FEAT_PMUv3_ICNTR and EL2 are implemented, then so is FEAT_FGT2.
        assert IsFeatureImplemented(FEAT_FGT2);
        let fgt_bit : bit = (if write_counter then HDFGWTR2_EL2().nPMICNTR_EL0
                             else HDFGWTR2_EL2().nPMICFILTR_EL0);
        if (HaveEL(EL3) && SCR_EL3().FGTEn2 == '0') || fgt_bit == '0' then
            mask[INSTRUCTION_COUNTER_ID] = '0';
        end;
    end;
end;

// Traps on other counters do not affect those counters' controls in the same
way.

return mask;

end;


## Library pseudocode for shared/debug/pmu/HasElapsed64Cycles

// HasElapsed64Cycles // ==================== // Returns TRUE if 64 cycles have elapsed between the last count, and FALSE otherwise.

impdef func HasElapsed64Cycles() => boolean begin return TRUE; end;


## Library pseudocode for shared/debug/pmu/IncrementInstructionCounter

// IncrementInstructionCounter // ============================= // Increment the instruction counter and possibly set overflow bits.

func IncrementInstructionCounter(increment : integer) begin if CountPMUEvents(INSTRUCTION_COUNTER_ID) then let old_value : integer = UInt(PMICNTR_EL0()); let new_value : integer = old_value + increment; PMICNTR_EL0() = new_value[63:0];

 // The effective value of PMCR_EL0.LP is '1' for the instruction
counter
    if old_value[64] != new_value[64] then
        PMOVSSET_EL0().F0 = '1';
    end;
end;
return;

end;


## Library pseudocode for shared/debug/pmu/IsRange3Counter

// IsRange3Counter // ================= // Returns TRUE if the counter is in the third range.

func IsRange3Counter(n : integer) => boolean begin return PMUCounterRange_R3 == GetPMUCounterRange(n); end;


## Library pseudocode for shared/debug/pmu/PMUCaptureEvent

// PMUCaptureEvent // ================= // If permitted and enabled, generate a PMU snapshot Capture event.

func PMUCaptureEvent begin assert HaveEL(EL3) && IsFeatureImplemented(FEAT_PMUv3_SS) && HaveAArch64(); let debug_state : boolean = Halted();

if () then
    // Indicate a Capture event completed, unsuccessfully
    PMSSCR_EL1().[NC,SS] = '10';
    return;
end;
let counters : integer = NUM_PMU_COUNTERS;
for idx = 0 to counters - 1 do
    PMEVCNTSVR_EL1(idx) = PMEVCNTR_EL0(idx) as PMEVCNTSVR_EL1_Type;
end;
PMCCNTSVR_EL1() = PMCCNTR_EL0() as PMCCNTSVR_EL1_Type;

if IsFeatureImplemented(FEAT_PMUv3_ICNTR) then
    PMICNTSVR_EL1() = PMICNTR_EL0() as PMICNTSVR_EL1_Type;
end;

if IsFeatureImplemented(FEAT_PCSRv8p9) && PMPCSCTL().SS == '1' then
    if pc_sample.valid && !debug_state then
        SetPCSRActive();
        SetPCSample();
    else
        PMPCSR()[31:0] = Ones{32};
    end;
end;

if (IsFeatureImplemented(FEAT_BRBE) && BranchRecordAllowed(PSTATE.EL)
&&
      BRBCR_EL1().FZPSS == '1' && ((EL2) || BRBCR_EL2().FZPSS == '1')) then
    BRBEFreeze();
end;

// Indicate a successful Capture event
PMSSCR_EL1().[NC,SS] = '00';
if !debug_state || ConstrainUnpredictableBool(Unpredictable_PMUSNAPSHOTEVENT)
then
    PMUEvent(PMU_EVENT_PMU_SNAPSHOT);
end;

return;

end;


## Library pseudocode for shared/debug/pmu/PMUCaptureEventAllowed

// PMUCaptureEventAllowed // ======================== // Returns TRUE if PMU Capture events are allowed, and FALSE otherwise.

func PMUCaptureEventAllowed() => boolean begin if !IsFeatureImplemented(FEAT_PMUv3_SS) || () then return FALSE; end;

if () || OSLockStatus() then
    return FALSE;
elsif HaveEL(EL3) && MDCR_EL3().PMSSE != '01' then
    return MDCR_EL3().PMSSE == '11';
elsif HaveEL(EL2) && MDCR_EL2().PMSSE != '01' then
    return MDCR_EL2().PMSSE == '11';
else
    var pmsse_el1 : bits(2) = PMECR_EL1().SSE;
    if pmsse_el1 == '01' then            // Reserved value
        var c : Constraint;
        (c, pmsse_el1) = ConstrainUnpredictableBits{2}(Unpredictable_RESPMSSE);
        assert c IN {Constraint_DISABLED, Constraint_UNKNOWN};
        if c == Constraint_DISABLED then pmsse_el1 = '00'; end;
        // Otherwise the value returned by ConstrainUnpredictableBits must be
        // a non-reserved value
    end;
    return pmsse_el1 == '11';
end;

end;


## Library pseudocode for shared/debug/pmu/PMUCaptureEventEnabled

// PMUCaptureEventEnabled // ======================== // Returns TRUE if PMU Capture events are enabled, and FALSE otherwise.

func PMUCaptureEventEnabled() => boolean begin if !IsFeatureImplemented(FEAT_PMUv3_SS) || () then return FALSE; end; if HaveEL(EL3) && MDCR_EL3().PMSSE != '01' then return MDCR_EL3().PMSSE == '1x'; elsif HaveEL(EL2) && ELUsingAArch32(EL2) then return FALSE; elsif HaveEL(EL2) && MDCR_EL2().PMSSE != '01' then return MDCR_EL2().PMSSE == '1x'; elsif ELUsingAArch32(EL1) then return FALSE; else var pmsse_el1 : bits(2) = PMECR_EL1().SSE; if pmsse_el1 == '01' then // Reserved value var c : Constraint; (c, pmsse_el1) = ConstrainUnpredictableBits{2}(Unpredictable_RESPMSSE); assert c IN {Constraint_DISABLED, Constraint_UNKNOWN}; if c == Constraint_DISABLED then pmsse_el1 = '00'; end; end; // Otherwise the value returned by ConstrainUnpredictableBits must be // a non-reserved value return pmsse_el1 == '1x'; end; end;


## Library pseudocode for shared/debug/pmu/PMUCountValue

// PMUCountValue // =============== // Implements the PMU threshold function, if implemented. // Returns the value to increment event counter 'n' by. // 'Vb' is the base value of the event that event counter 'n' is configured to count. // 'Vm' is the value to increment event counter 'n-1' by if 'n' is odd, zero otherwise.

func PMUCountValue(n : integer, Vb : integer, Vm : integer) => integer begin assert (n MOD 2) == 1 || Vm == 0; assert n < NUM_PMU_COUNTERS;

if !IsFeatureImplemented(FEAT_PMUv3_TH) || () then
    return Vb;
end;

let TH : integer = UInt(PMEVTYPER_EL0(n).TH);

// Control register fields
var tc : bits(3) = PMEVTYPER_EL0(n).TC;
var te : bit = '0';
if IsFeatureImplemented(FEAT_PMUv3_EDGE) then
    te = PMEVTYPER_EL0(n).TE;
end;
var tlc : bits(2) = '00';
if IsFeatureImplemented(FEAT_PMUv3_TH2) && (n MOD 2) == 1 then
    tlc = PMEVTYPER_EL0(n).TLC;
end;

// Check for reserved cases
var c : Constraint;
(c, tc, te, tlc) = ReservedPMUThreshold(n, tc, te, tlc);
if c == Constraint_DISABLED then
    return Vb;
end;
// Otherwise the values returned by ReservedPMUThreshold must be defined
values

// Check if disabled. Note that this function will return the value of Vb when
// the control register fields are all zero, even without this check.
if tc == '000' && TH == 0 && te == '0' && tlc == '00'
then
    return Vb;
end;

// Threshold condition
var Ct : boolean;
case tc[2:1] of
    when '00' => Ct = (Vb != TH);        // Disabled or not-equal
    when '01' => Ct = (Vb == TH);        // Equals
    when '10' => Ct = (Vb >= TH);        // Greater-than-or-equal
    when '11' => Ct = (Vb <  TH);        // Less-than
end;

var Vn : integer;
if te == '1' then
    // Edge condition
    let Cp : boolean = PMULastThresholdValue[[n]];
    var Ce : boolean;
    var Ve : integer;
    case tc[1:0] of
        when '10' =>  Ce = (Cp != Ct);   // Both edges
        when 'x1' =>  Ce = (!Cp && Ct);  // Single edge
        otherwise =>  unreachable;     // Covered by ReservedPMUThreshold
    end;
    case tlc of
        when '00' =>  Ve = (if Ce then 1 else 0);
        when '10' =>  Ve = (if Ce then Vm else 0);
        otherwise =>  unreachable;     // Covered by ReservedPMUThreshold
    end;
    Vn = Ve;
else
    // Threshold condition
    var Vt : integer;
    case tc[0]::tlc of
        when '0 00' =>  Vt = (if Ct then Vb else 0);
        when '0 01' =>  Vt = (if Ct then Vb else Vm);
        when '0 10' =>  Vt = (if Ct then Vm else 0);
        when '1 00' =>  Vt = (if Ct then 1 else 0);
        when '1 01' =>  Vt = (if Ct then 1 else Vm);
        otherwise =>    unreachable;   // Covered by ReservedPMUThreshold
    end;
    Vn = Vt;
end;

PMULastThresholdValue[[n]] = Ct;

return Vn;

end;


## Library pseudocode for shared/debug/pmu/PMUCounterRange

// PMUCounterRange // =============== // Enumerates the ranges to which an event counter belongs to.

type PMUCounterRange of enumeration { PMUCounterRange_R1, PMUCounterRange_R2, PMUCounterRange_R3 };


## Library pseudocode for shared/debug/pmu/PMUEvent

// PMUEvent // ========== // Generate a PMU event. By default, increment by 1. func PMUEvent(pmuevent : bits(16)) begin PMUEvent(pmuevent, 1); end;

// PMUEvent // ========== // Accumulate a PMU Event.

func PMUEvent(pmuevent : bits(16), increment : integer) begin let counters : integer = NUM_PMU_COUNTERS; if counters != 0 then for idx = 0 to counters - 1 do PMUEvent(pmuevent, increment, idx); end; end;

if (HaveAArch64() && IsFeatureImplemented(FEAT_PMUv3_ICNTR)
&&
      pmuevent == PMU_EVENT_INST_RETIRED) then
    IncrementInstructionCounter(increment);
end;

end;

// PMUEvent // ========== // Accumulate a PMU Event for a specific event counter.

func PMUEvent(pmuevent : bits(16), increment : integer, idx : integer) begin if !IsFeatureImplemented(FEAT_PMUv3) then return; end; if UsingAArch32() then if PMEVTYPER(idx).evtCount == pmuevent then PMUEventAccumulator[[idx]] = PMUEventAccumulator[[idx]] + increment; end; else if PMEVTYPER_EL0(idx).evtCount == pmuevent then PMUEventAccumulator[[idx]] = PMUEventAccumulator[[idx]] + increment; end; end; end;


## Library pseudocode for shared/debug/pmu/PMUOverflowCondition

// PMUOverflowCondition // ====================== // Enumerates the reasons for which the PMU overflow condition is evaluated.

type PMUOverflowCondition of enumeration { PMUOverflowCondition_PMUException, PMUOverflowCondition_BRBEFreeze, PMUOverflowCondition_Freeze, PMUOverflowCondition_IRQ, PMUOverflowCondition_EDBGRQ };


## Library pseudocode for shared/debug/pmu/PMUSwIncrement

// PMUSwIncrement // ================ // Generate PMU Events on a System register write to PMSWINC

func PMUSwIncrement(sw_incr_in : bits(64)) begin

var sw_incr : bits(64)   = sw_incr_in;
var mask : bits(31)      = Zeros{};
let counters : integer{} = GetNumEventCountersAccessible();
if counters > 0 then
    mask[counters-1:0] = Ones{counters};
end;

if (IsFeatureImplemented(FEAT_PMUv3p9) && (EL1) &&
      PSTATE.EL == EL0 && PMUSERENR_EL0().[UEN,SW] == '10') then
    mask = mask AND PMUACR_EL1()[30:0];
end;

sw_incr = sw_incr AND ZeroExtend{64}(mask);
for idx = 0 to 30 do
    if sw_incr[idx] == '1' then
        PMUEvent(PMU_EVENT_SW_INCR, 1, idx);
    end;
end;

return;

end;


## Library pseudocode for shared/debug/pmu/ReservedPMUThreshold

// ReservedPMUThreshold // ====================== // Checks if the given PMEVTYPER_EL1().[TH,TE,TLC] values are reserved and will // generate Constrained Unpredictable behavior, otherwise return Constraint_NONE.

func ReservedPMUThreshold(n : integer, tc_in : bits(3), te_in : bit, tlc_in : bits(2)) => (Constraint, bits(3), bit, bits(2)) begin var tc : bits(3) = tc_in; var te : bit = te_in; var tlc : bits(2) = tlc_in;

var reserved : boolean = FALSE;

if IsFeatureImplemented(FEAT_PMUv3_EDGE) then
    if te == '1' && tc[1:0] == '00' then      // Edge condition
        reserved = TRUE;
    end;
else
    te = '0';                                 // Control is RES0
end;

if IsFeatureImplemented(FEAT_PMUv3_TH2) && (n MOD 2) == 1 then
    if tlc == '11' then                       // Reserved value
        reserved = TRUE;
    end;
    if te == '1' then                         // Edge condition
        if tlc == '01' then
            reserved = TRUE;
        end;
    else                                      // Threshold condition
        if tc[0] == '1' && tlc == '10' then
            reserved = TRUE;
        end;
    end;
else
    tlc = '00';                               // Controls are RES0
end;

var c : Constraint = Constraint_NONE;
if reserved then
    var unpred_reserved_bits : bits(6);
    (c, unpred_reserved_bits) = ConstrainUnpredictableBits{6}(Unpredictable_RESTC);
    tc  = unpred_reserved_bits[5:3];
    te  = unpred_reserved_bits[2];
    tlc = unpred_reserved_bits[1:0];
end;

return (c, tc, te, tlc);

end;


## Library pseudocode for shared/debug/pmu/SMEPMUEventPredicate

// SMEPMUEventPredicate // ====================== // Call the relevant PMU predication events based on the SME instruction properties.

func SMEPMUEventPredicate{N}(mask1 : bits(N), mask2 : bits(N), esize : integer) begin PMUEvent(PMU_EVENT_SVE_PRED_SPEC); PMUEvent(PMU_EVENT_SME_PRED2_SPEC); if AllElementsActive{N}(mask1, esize) && AllElementsActive{N}(mask2, esize) then PMUEvent(PMU_EVENT_SME_PRED2_FULL_SPEC); else PMUEvent(PMU_EVENT_SME_PRED2_NOT_FULL_SPEC); if {N}(mask1, esize) && {N}(mask2, esize) then PMUEvent(PMU_EVENT_SME_PRED2_EMPTY_SPEC); else PMUEvent(PMU_EVENT_SME_PRED2_PARTIAL_SPEC); end; end; end;


## Library pseudocode for shared/debug/pmu/SVEPMUEventPredicate

// SVEPMUEventPredicate // ====================== // Call the relevant PMU predication events based on the SVE instruction properties.

func SVEPMUEventPredicate{N}(mask : bits(N), esize : integer) begin PMUEvent(PMU_EVENT_SVE_PRED_SPEC); if AllElementsActive{N}(mask, esize) then PMUEvent(PMU_EVENT_SVE_PRED_FULL_SPEC); else PMUEvent(PMU_EVENT_SVE_PRED_NOT_FULL_SPEC); if {N}(mask, esize) then PMUEvent(PMU_EVENT_SVE_PRED_EMPTY_SPEC); else PMUEvent(PMU_EVENT_SVE_PRED_PARTIAL_SPEC); end; end; end;


## Library pseudocode for shared/debug/pmu/ShouldPMUFreeze

// ShouldPMUFreeze // =================

func ShouldPMUFreeze(r : PMUCounterRange) => boolean begin let include_r1 : boolean = (r == PMUCounterRange_R1); let include_r2 : boolean = (r == PMUCounterRange_R2); let include_r3 : boolean = FALSE;

if r == PMUCounterRange_R3 then
    return FALSE;
end;

let overflow : boolean =
CheckPMUOverflowCondition(PMUOverflowCondition_Freeze,
                                                   include_r1, include_r2, include_r3);
return overflow;

end;


## Library pseudocode for shared/debug/pmu/SysRegGetPMUAccessMask

// SysRegGetPMUAccessMask // ======================== // Return a mask of the PMU counters accessible at the current Exception level // for a System register access

func SysRegGetPMUAccessMask() => bits(64) begin var mask : bits(64) = Zeros{};

// PMICNTR_EL0 is only accessible at EL0 using AArch64 when
PMUSERENR_EL0.UEN is 1.
if IsFeatureImplemented(FEAT_PMUv3_ICNTR) && () then
    assert IsFeatureImplemented(FEAT_PMUv3p9);
    if PSTATE.EL != EL0 || PMUSERENR_EL0().UEN == '1' then
        mask[INSTRUCTION_COUNTER_ID] = '1';
    end;
end;

// PMCCNTR_EL0 is always implemented and accessible
mask[CYCLE_COUNTER_ID] = '1';

// PMEVCNTR_EL0(n)
let counters : integer{} = GetNumEventCountersAccessible();
if counters > 0 then
    mask[counters-1:0] = Ones{counters};
end;

// Check EL0 ignore access conditions
if (IsFeatureImplemented(FEAT_PMUv3p9) && (EL1) &&
      PSTATE.EL == EL0 && PMUSERENR_EL0().UEN == '1') then
    mask = mask AND PMUACR_EL1();  // User access control
end;

return mask;

end;


## Library pseudocode for shared/debug/pmu/SysRegZeroCycleCounter

// SysRegZeroCycleCounter // ======================== // Called on a System register write to PMCR_EL0 or PMCR that writes '1' to PMCR_EL0.C or PMCR.C.

func SysRegZeroCycleCounter begin var mask : bits(64) = Zeros{}; mask[CYCLE_COUNTER_ID] = '1'; SysRegZeroPMUCounters(mask); end;


## Library pseudocode for shared/debug/pmu/SysRegZeroEventCounters

// SysRegZeroEventCounters // ========================== // Zero all the event counters. // Called on a System register write to PMCR_EL0 or PMCR that writes '1' to PMCR_EL0.P or PMCR.P.

func SysRegZeroEventCounters begin // Although SysRegZeroPMUCounters implements the functionality for PMUACR_EL1 // that is part of FEAT_PMUv3p9, it should be noted that writes to // PMCR_EL0 are not allowed at EL0 when PMUSERENR_EL0.UEN is 1, meaning // it is not relevant in this case. SysRegZeroPMUCounters(Zeros{33} :: Ones{31}); end;


## Library pseudocode for shared/debug/pmu/SysRegZeroPMUCounters

// SysRegZeroPMUCounters // ======================= // Zero set of counters specified by the mask in 'val', for System register access. // For a System register write to PMZR_EL0, 'val' is the value passed in X.

func SysRegZeroPMUCounters(val : bits(64)) begin let masked_val : bits(64) = val AND GetPMUWriteMask(TRUE); ApplyPMUZeroMask(masked_val); return; end;


## Library pseudocode for shared/debug/pmu/Write\_PMCNTENCLR

// Write_PMCNTENCLR // ================== // System register write to PMCNTENCLR.

func Write_PMCNTENCLR(value_in : bits(32)) begin let write_mask : bits(32) = GetPMUWriteMask(FALSE)[31:0];

PMCNTENCLR() = PMCNTENCLR() AND NOT (value_in AND write_mask);

end;


## Library pseudocode for shared/debug/pmu/Write\_PMCNTENCLR\_EL0

// Write_PMCNTENCLR_EL0 // ====================== // System register write to PMCNTENCLR_EL0.

func Write_PMCNTENCLR_EL0(value_in : bits(64)) begin let write_mask : bits(64) = GetPMUWriteMask(FALSE);

PMCNTENCLR_EL0() = PMCNTENCLR_EL0() AND NOT (value_in AND
write_mask);

end;


## Library pseudocode for shared/debug/pmu/Write\_PMCNTENSET

// Write_PMCNTENSET // ================== // System register write to PMCNTENSET.

func Write_PMCNTENSET(value_in : bits(32)) begin let write_mask : bits(32) = GetPMUWriteMask(FALSE)[31:0];

PMCNTENSET() = PMCNTENSET() OR (value_in AND write_mask);

end;


## Library pseudocode for shared/debug/pmu/Write\_PMCNTENSET\_EL0

// Write_PMCNTENSET_EL0 // ====================== // System register write to PMCNTENSET_EL0.

func Write_PMCNTENSET_EL0(value_in : bits(64)) begin let write_mask : bits(64) = GetPMUWriteMask(FALSE);

PMCNTENSET_EL0() = PMCNTENSET_EL0() OR (value_in AND write_mask);

end;


## Library pseudocode for shared/debug/pmu/Write\_PMINTENCLR

// Write_PMINTENCLR // ================== // System register write to PMINTENCLR.

func Write_PMINTENCLR(value_in : bits(32)) begin let write_mask : bits(32) = GetPMUWriteMask(FALSE)[31:0];

PMINTENCLR() = PMINTENCLR() AND NOT (value_in AND write_mask);

end;


## Library pseudocode for shared/debug/pmu/Write\_PMINTENCLR\_EL1

// Write_PMINTENCLR_EL1 // ====================== // System register write to PMINTENCLR_EL1.

func Write_PMINTENCLR_EL1(value_in : bits(64)) begin let write_mask : bits(64) = GetPMUWriteMask(FALSE);

PMINTENCLR_EL1() = PMINTENCLR_EL1() AND NOT (value_in AND
write_mask);

end;


## Library pseudocode for shared/debug/pmu/Write\_PMINTENSET

// Write_PMINTENSET // ================== // System register write to PMINTENSET.

func Write_PMINTENSET(value_in : bits(32)) begin let write_mask : bits(32) = GetPMUWriteMask(FALSE)[31:0];

PMINTENSET() = PMINTENSET() OR (value_in AND write_mask);

end;


## Library pseudocode for shared/debug/pmu/Write\_PMINTENSET\_EL1

// Write_PMINTENSET_EL1 // ====================== // System register write to PMINTENSET_EL1.

func Write_PMINTENSET_EL1(value_in : bits(64)) begin let write_mask : bits(64) = GetPMUWriteMask(FALSE);

PMINTENSET_EL1() = PMINTENSET_EL1() OR (value_in AND write_mask);

end;


## Library pseudocode for shared/debug/pmu/Write\_PMOVSCLR\_EL0

// Write_PMOVSCLR_EL0 // ==================== // System register write to PMOVSCLR_EL0.

func Write_PMOVSCLR_EL0(value_in : bits(64)) begin let write_mask : bits(64) = GetPMUWriteMask(FALSE);

PMOVSCLR_EL0() = PMOVSCLR_EL0() AND NOT (value_in AND write_mask);

end;


## Library pseudocode for shared/debug/pmu/Write\_PMOVSR

// Write_PMOVSR // ============== // System register write to PMOVSR.

func Write_PMOVSR(value_in : bits(32)) begin let write_mask : bits(32) = GetPMUWriteMask(FALSE)[31:0];

PMOVSR() = PMOVSR() AND NOT (value_in AND write_mask);

end;


## Library pseudocode for shared/debug/pmu/Write\_PMOVSSET

// Write_PMOVSSET // ================ // System register write to PMOVSSET.

func Write_PMOVSSET(value_in : bits(32)) begin let write_mask : bits(32) = GetPMUWriteMask(FALSE)[31:0];

PMOVSSET() = PMOVSSET() OR (value_in AND write_mask);

end;


## Library pseudocode for shared/debug/pmu/Write\_PMOVSSET\_EL0

// Write_PMOVSSET_EL0 // ==================== // System register write to PMOVSSET_EL0.

func Write_PMOVSSET_EL0(value_in : bits(64)) begin let write_mask : bits(64) = GetPMUWriteMask(FALSE);

PMOVSSET_EL0() = PMOVSSET_EL0() OR (value_in AND write_mask);

end;


## Library pseudocode for shared/debug/samplebasedprofiling/CreatePCSample

// CreatePCSample // ================

func CreatePCSample begin // In a simple sequential execution of the program, CreatePCSample is executed each time the PE // executes an instruction that can be sampled. An implementation is not constrained such that // reads of EDPCSRlo return the current values of PC, etc. if PCSRSuspended() then return; end; pc_sample.valid = ExternalNoninvasiveDebugAllowed() && (); pc_sample.pc = ThisInstrAddr{64}(); pc_sample.el = PSTATE.EL; pc_sample.rw = if UsingAArch32() then '0' else '1'; pc_sample.ss = CurrentSecurityState(); pc_sample.contextidr = if ELUsingAArch32(EL1) then CONTEXTIDR() else CONTEXTIDR_EL1()[31:0]; pc_sample.has_el2 = PSTATE.EL != EL3 && EL2Enabled();

if pc_sample.has_el2 then
    pc_sample.vmid = VMID();
    if ((IsFeatureImplemented(FEAT_VHE) || IsFeatureImplemented(FEAT_Debugv8p2)) &&
          (EL2)) then
        pc_sample.contextidr_el2 = CONTEXTIDR_EL2()[31:0];
    else
        pc_sample.contextidr_el2 = ARBITRARY : bits(32);
    end;
    pc_sample.el0h = PSTATE.EL == EL0 && IsInHost();
end;
return;

end;


## Library pseudocode for shared/debug/samplebasedprofiling/PCSRSuspended

// PCSRSuspended // =============== // Returns TRUE if PC Sample-based Profiling is suspended, and FALSE otherwise.

func PCSRSuspended() => boolean begin if IsFeatureImplemented(FEAT_PMUv3_SS) && PMPCSCTL().SS == '1' then return FALSE; end; if IsFeatureImplemented(FEAT_PCSRv8p9) && PMPCSCTL().IMP == '1' then return PMPCSCTL().EN == '0'; end; return ImpDefBool("PCSR is suspended"); end;


## Library pseudocode for shared/debug/samplebasedprofiling/PCSample

// PCSample // ========

type PCSample of record { valid : boolean, pc : bits(64), el : bits(2), rw : bit, ss : SecurityState, has_el2 : boolean, contextidr : bits(32), contextidr_el2 : bits(32), el0h : boolean, vmid : bits(NUM_VMIDBITS) };

var pc_sample : PCSample;


## Library pseudocode for shared/debug/samplebasedprofiling/Read\_EDPCSRlo

// Read_EDPCSRlo // ===============

func Read_EDPCSRlo(memory_mapped : boolean) => bits(32) begin // The Software lock is OPTIONAL. let update : boolean = !memory_mapped || EDLSR().SLK == '0';// Software locked: no side-effects var sample : bits(32); if pc_sample.valid then sample = pc_sample.pc[31:0]; if update then if IsFeatureImplemented(FEAT_VHE) && EDSCR().SC2 == '1' then EDPCSR().SC2_1.EDPCSRhi = (if pc_sample.rw == '0' then Zeros{24} else pc_sample.pc[55:32]); EDPCSR().EL = pc_sample.el; EDPCSR().NS = (if pc_sample.ss == SS_Secure then '0' else '1'); else EDPCSR().SC2_0.EDPCSRhi = (if pc_sample.rw == '0' then Zeros{32} else pc_sample.pc[63:32]); end; EDCIDSR() = pc_sample.contextidr; if ((IsFeatureImplemented(FEAT_VHE) || IsFeatureImplemented(FEAT_Debugv8p2)) && EDSCR().SC2 == '1') then EDVIDSR() = (if pc_sample.has_el2 then pc_sample.contextidr_el2 else ARBITRARY : bits(32)); else EDVIDSR().VMID = (if pc_sample.has_el2 && pc_sample.el IN {EL1,EL0} then pc_sample.vmid else Zeros{NUM_VMIDBITS}); EDVIDSR().NS = (if pc_sample.ss == SS_Secure then '0' else '1'); EDVIDSR().E2 = (if pc_sample.el == EL2 then '1' else '0'); EDVIDSR().E3 = (if pc_sample.el == EL3 then '1' else '0') AND pc_sample.rw; // The conditions for setting HV are not specified if PCSRhi is zero. // An example implementation may be "pc_sample.rw". EDVIDSR().HV = (if !IsZero(EDPCSR().SC2_0.EDPCSRhi) then '1' else ImpDefBit("0 or 1")); end; end; else sample = Ones{32}; if update then EDPCSR()[63:32] = ARBITRARY : bits(32); EDCIDSR() = ARBITRARY : bits(32); EDVIDSR() = ARBITRARY : bits(32); end; end;

return sample;

end;


## Library pseudocode for shared/debug/samplebasedprofiling/Read\_PMPCSR

// Read_PMPCSR // =============

func Read_PMPCSR(memory_mapped : boolean) => bits(64) begin // The Software lock is OPTIONAL. var update : boolean = !memory_mapped || PMLSR().SLK == '0'; // Software locked: no side-effects

if IsFeatureImplemented(FEAT_PCSRv8p9) && update then
    if IsFeatureImplemented(FEAT_PMUv3_SS) && PMPCSCTL().SS == '1' then
        update = FALSE;
    elsif PMPCSCTL().[IMP,EN] == '10' || (PMPCSCTL().IMP == '0' && PCSRSuspended()) then
        pc_sample.valid = FALSE;
        SetPCSRActive();
    end;
end;

if pc_sample.valid then
    if update then SetPCSample(); end;
    return PMPCSR();
else
    if update then SetPCSRUnknown(); end;
    return (ARBITRARY : bits(32) :: Ones{32});
end;

end;


## Library pseudocode for shared/debug/samplebasedprofiling/SetPCSRActive

// SetPCSRActive // =============== // Sets PC Sample-based Profiling to active state.

func SetPCSRActive begin if PMPCSCTL().IMP == '1' then PMPCSCTL().EN = '1'; // If PMPCSCTL.IMP reads as 0b0, then PMPCSCTL.EN is RES0, and it is // IMPLEMENTATION DEFINED whether PSCR is suspended or active at reset. end; end;


## Library pseudocode for shared/debug/samplebasedprofiling/SetPCSRUnknown

// SetPCSRUnknown // ================ // Sets the PC sample registers to UNKNOWN values because PC sampling // is prohibited.

func SetPCSRUnknown begin PMPCSR()[31:0] = Ones{32}; PMPCSR()[55:32] = ARBITRARY : bits(24); PMPCSR().EL = ARBITRARY : bits(2); PMPCSR().NS = ARBITRARY : bit;

if IsFeatureImplemented(FEAT_PMUv3_EXT64) then
    PMCCIDSR()      = ARBITRARY : bits(64);
    PMVCIDSR().VMID = ARBITRARY : bits(NUM_VMIDBITS);
end;
if IsFeatureImplemented(FEAT_PMUv3_EXT32) then
    PMCID1SR()      = ARBITRARY : bits(32);
    PMCID2SR()      = ARBITRARY : bits(32);
    PMVIDSR().VMID  = ARBITRARY : bits(NUM_VMIDBITS);
end;

return;

end;


## Library pseudocode for shared/debug/samplebasedprofiling/SetPCSample

// SetPCSample // ============= // Sets the PC sample registers to the appropriate sample values.

func SetPCSample begin PMPCSR()[31:0] = pc_sample.pc[31:0]; PMPCSR()[55:32] = (if pc_sample.rw == '0' then Zeros{24} else pc_sample.pc[55:32]); PMPCSR().EL = pc_sample.el; if IsFeatureImplemented(FEAT_RME) then case pc_sample.ss of when SS_Secure => PMPCSR().NSE = '0'; PMPCSR().NS = '0'; when SS_NonSecure => PMPCSR().NSE = '0'; PMPCSR().NS = '1'; when SS_Root => PMPCSR().NSE = '1'; PMPCSR().NS = '0'; when SS_Realm => PMPCSR().NSE = '1'; PMPCSR().NS = '1'; end; else PMPCSR().NS = (if pc_sample.ss == SS_Secure then '0' else '1'); end; let contextidr_el2 : bits(32) = (if pc_sample.has_el2 then pc_sample.contextidr_el2 else ARBITRARY : bits(32)); var vmid : bits(NUM_VMIDBITS) = ARBITRARY : bits(NUM_VMIDBITS); if pc_sample.has_el2 && pc_sample.el IN {EL1,EL0} && .el0h then vmid = pc_sample.vmid; end; if IsFeatureImplemented(FEAT_PMUv3_EXT64) then PMCCIDSR() = contextidr_el2::pc_sample.contextidr; PMVCIDSR().VMID = vmid; end; if IsFeatureImplemented(FEAT_PMUv3_EXT32) then PMCID1SR() = pc_sample.contextidr; PMCID2SR() = contextidr_el2; PMVIDSR().VMID = vmid; end;

return;

end;


## Library pseudocode for shared/debug/softwarestep/CheckSoftwareStep

// CheckSoftwareStep // =================== // Take a Software Step exception if in the active-pending state

func CheckSoftwareStep begin

// Other self-hosted debug functions will call
AArch32_GenerateDebugExceptions() if called from
// AArch32 state. However, because Software Step is only active when the debug
target Exception
// level is using AArch64, CheckSoftwareStep only calls
AArch64_GenerateDebugExceptions().
let step_enabled : boolean = ((DebugTarget()) &&
                              AArch64_GenerateDebugExceptions() &&
                              MDSCR_EL1().SS == '1');
let active_pending : boolean = step_enabled && PSTATE.SS == '0'; //
active-pending
if active_pending then
    AArch64_SoftwareStepException();
end;
ShouldAdvanceSS = TRUE;
return;

end;


## Library pseudocode for shared/debug/softwarestep/DebugExceptionReturnSS

// DebugExceptionReturnSS // ======================== // Returns value to write to PSTATE.SS on an exception return or Debug state exit.

func DebugExceptionReturnSS{N}(spsr : bits(N)) => bit begin assert Halted() || Restarting() || PSTATE.EL != EL0;

var enabled_at_source : boolean;
if Restarting() then
    enabled_at_source = FALSE;
elsif UsingAArch32() then
    enabled_at_source = AArch32_GenerateDebugExceptions();
else
    enabled_at_source = AArch64_GenerateDebugExceptions();
end;
var valid : boolean;
var dest_el : bits(2);
if IllegalExceptionReturn{N}(spsr) then
    dest_el = PSTATE.EL;
else
    (valid, dest_el) = ELFromSPSR{N}(spsr);  assert valid;
end;

let dest_ss : SecurityState = SecurityStateAtEL(dest_el);
var enabled_at_dest : boolean;
let dest_using_32 : boolean = (if dest_el == EL0 then spsr[4] == '1'
                                                 else ELUsingAArch32(dest_el));
if dest_using_32 then
    enabled_at_dest = AArch32_GenerateDebugExceptionsFrom(dest_el, dest_ss);
else
    let mask : bit = spsr[9];
    enabled_at_dest = AArch64_GenerateDebugExceptionsFrom(dest_el, dest_ss, mask);
end;

let ELd : bits(2) = DebugTargetFrom(dest_ss);
var SS_bit : bit;
if (ELd) && MDSCR_EL1().SS == '1' && !enabled_at_source
&& enabled_at_dest then
    SS_bit = spsr[21];
else
    SS_bit = '0';
end;
return SS_bit;

end;


## Library pseudocode for shared/debug/softwarestep/SSAdvance

// SSAdvance // =========== // Advance the Software Step state machine.

func SSAdvance begin

// A simpler implementation of this function just clears PSTATE.SS
to zero regardless of the
// current Software Step state machine. However, this check is made to
illustrate that the
// PE only needs to consider advancing the state machine from the
active-not-pending
// state.
if  then return; end;
let target : bits(2) = DebugTarget();
let step_enabled : boolean = (target) && MDSCR_EL1().SS == '1';
let active_not_pending : boolean = step_enabled && PSTATE.SS == '1';
if active_not_pending then PSTATE.SS = '0'; end;
ShouldAdvanceSS = FALSE;
return;

end;


## Library pseudocode for shared/debug/softwarestep/SoftwareStepOpEnabled

// SoftwareStepOpEnabled // ======================= // Returns a boolean indicating if execution from MDSTEPOP_EL1 is enabled.

func SoftwareStepOpEnabled() => boolean begin

if !IsFeatureImplemented(FEAT_STEP2) || UsingAArch32() then
    return FALSE;
end;

let step_enabled = AArch64_GenerateDebugExceptions() && MDSCR_EL1().SS
== '1';
let active_not_pending = step_enabled && PSTATE.SS == '1';
let stepop = (MDSCR_EL1().EnSTEPOP == '1' &&
              ((EL3) || MDCR_EL3().EnSTEPOP == '1') &&
              (() || MDCR_EL2().EnSTEPOP == '1'));
return active_not_pending && stepop;

end;


## Library pseudocode for shared/debug/watchpoint/DataCacheWatchpointSize

// DataCacheWatchpointSize // ========================= // Return the IMPLEMENTATION DEFINED data cache watchpoint size func DataCacheWatchpointSize() => integer begin let size : integer = ImpDefInt("Data Cache Invalidate Watchpoint Size"); assert IsPow2(size) && size >= 2^(UInt(CTR_EL0().DminLine) + 2) && size <= 2048; return size; end;


## Library pseudocode for shared/debug/watchpoint/WatchpointInfo

// WatchpointInfo // ============== // Watchpoint related fields.

type WatchpointInfo of record { wptype : WatchpointType, // Type of watchpoint matched maybe_false_match : boolean, // Watchpoint matches rounded range watchpt_num : integer, // Matching watchpoint number value_match : boolean, // Watchpoint match vaddress : bits(64) // Matching Virtual Address };


## Library pseudocode for shared/debug/watchpoint/WatchpointType

// WatchpointType // ==============

type WatchpointType of enumeration { WatchpointType_Inactive, // Watchpoint inactive or disabled WatchpointType_AddrMatch, // Address Match watchpoint WatchpointType_AddrMismatch // Address Mismatch watchpoint };


## Library pseudocode for shared/exceptions/aborts/EffectiveHCRX\_EL2\_TMEA

// EffectiveHCRX_EL2_TMEA // ======================== // Return the Effective value of HCRX_EL2.TMEA.

readonly func EffectiveHCRX_EL2_TMEA() => bit begin if (IsFeatureImplemented(FEAT_DoubleFault2) && EL2Enabled() && (EL2) && IsHCRXEL2Enabled()) then return HCRX_EL2().TMEA; else return '0'; end; end;


## Library pseudocode for shared/exceptions/aborts/EffectiveHCR\_AMO

// EffectiveHCR_AMO // ================== // Return the Effective value of HCR_EL2.AMO.

readonly func EffectiveHCR_AMO() => bit begin if EffectiveTGE() == '1' then return (if ELUsingAArch32(EL2) || EffectiveHCR_EL2_E2H() == '0' then '1' else '0'); elsif EL2Enabled() then return (if ELUsingAArch32(EL2) then HCR().AMO else HCR_EL2().AMO); else return '0'; end; end;


## Library pseudocode for shared/exceptions/aborts/EffectiveHCR\_TEA

// EffectiveHCR_TEA // ================== // Return the Effective value of HCR_EL2.TEA.

func EffectiveHCR_TEA() => bit begin if EL2Enabled() && IsFeatureImplemented(FEAT_RAS) then return (if ELUsingAArch32(EL2) then HCR2().TEA else HCR_EL2().TEA); else return '0'; end; end;


## Library pseudocode for shared/exceptions/aborts/EffectiveNMEA

// EffectiveNMEA // =============== // Returns the Effective value of SCR_EL3.NMEA or SCTLR2_ELx.NMEA.

func EffectiveNMEA(el : bits(2)) => bit begin if IsFeatureImplemented(FEAT_DoubleFault2) then if el == EL3 && (EL3) then return EffectiveSCR_EL3_NMEA(); elsif (el == EL2 || (el == EL0 && ELIsInHost(el))) && (EL2) then return (if IsSCTLR2EL2Enabled() then SCTLR2_EL2().NMEA else '0'); elsif (el == EL1 || (el == EL0 && (el))) && (EL1) then return (if IsSCTLR2EL1Enabled() then SCTLR2_EL1().NMEA else '0'); else return '0'; end; end; if IsFeatureImplemented(FEAT_DoubleFault) && el == EL3 && (EL3) then return EffectiveSCR_EL3_NMEA(); else return '0'; end; end;


## Library pseudocode for shared/exceptions/aborts/PhysicalSErrorTarget

// PhysicalSErrorTarget // ====================== // Returns a tuple of whether SError exception can be taken and, if so, the // target Exception level. // If EL3 is implemented and using AArch32, then a target Exception level of // EL1 means Abort mode, and EL3 means Monitor mode, including in Secure // state when Abort mode is part of EL3.

func PhysicalSErrorTarget() => (boolean, bits(2)) begin if Halted() then return (TRUE, ARBITRARY : bits(2)); end;

let effective_ea : bit = EffectiveEA();
let effective_amo : bit = EffectiveHCR_AMO();
let effective_tge : bit = EffectiveTGE();
let effective_nmea : bit = EffectiveNMEA(PSTATE.EL);

// When EL3 is implemented and using AArch32, the SCR.AW bit can allow
PSTATE.A
// to mask SError exceptions in Non-secure state when SCR.EA is 1 and the
Effective
// value of HCR.AMO is 0.
var effective_aw : bit;
if (ELUsingAArch32(EL3) && effective_ea == '1' &&
      CurrentSecurityState() == SS_NonSecure && effective_amo == '0') then
    effective_aw = SCR().AW;
else
    effective_aw = '0';
end;

// The exception is masked by software.
var masked : boolean;
case PSTATE.EL of
    when EL3 =>
        masked = (() && effective_ea == '0') || PSTATE.A == '1';
    when EL2 =>
        masked = ((effective_ea == '0' || effective_aw == '1') &&
                  ((() && effective_tge == '0' && effective_amo == '0') ||
                   PSTATE.A == '1'));
    when EL1, EL0 =>
        masked = ((effective_ea == '0' || effective_aw == '1') &&
                  effective_amo == '0' && PSTATE.A == '1');
end;

// When FEAT_DoubleFault or FEAT_DoubleFault2 is implemented, the mask might
be overridden.
masked = (masked && effective_nmea == '0');

// External debug might disable the exception in the current Security state.
// This is not relevant at EL3.
let intdis : boolean = PSTATE.EL != EL3 &&
ExternalDebugInterruptsDisabled(EL1);

var target_el : bits(2) = ARBITRARY : bits(2);
if effective_ea == '1' || (PSTATE.EL == EL3 && (EL3)) then
    if !masked then target_el = EL3; end;

elsif EL2Enabled() && effective_amo == '1' && !intdis
&& PSTATE.EL IN {EL0, EL1} then
    target_el = EL2;
    masked = FALSE;

elsif (EffectiveHCRX_EL2_TMEA() == '1' && !intdis &&
         ((PSTATE.EL == EL1 && PSTATE.A == '1') ||
          (PSTATE.EL == EL0 && masked && ()))) then
    target_el = EL2;
    masked = FALSE;

elsif (EffectiveSCR_EL3_TMEA() == '1' &&
         ((PSTATE.EL IN {EL2, EL1} && PSTATE.A == '1') ||
         (PSTATE.EL IN {EL2, EL0} && masked) || intdis)) then
    target_el = EL3;
    masked = FALSE;

elsif PSTATE.EL == EL2 || IsInHost() then
    if !masked then target_el = EL2; end;

else
    assert (PSTATE.EL == EL1 ||
              (PSTATE.EL == EL3 && ELUsingAArch32(EL3)) ||
              (PSTATE.EL == EL0 && ()));
    if !masked then target_el = EL1; end;
end;

// External debug might disable the exception for the target Exception level.
if !masked && ExternalDebugInterruptsDisabled(target_el) then
    masked = TRUE;
    target_el = ARBITRARY : bits(2);
end;

return (masked, target_el);

end;


## Library pseudocode for shared/exceptions/aborts/SyncExternalAbortTarget

// SyncExternalAbortTarget // ========================= // Returns the target Exception level for a Synchronous External Data or // Instruction or Prefetch Abort. // If EL3 is implemented and using AArch32, then a target Exception level of // EL1 means Abort mode, and EL3 means Monitor mode, including in Secure // state when Abort mode is part of EL3.

func SyncExternalAbortTarget(fault : FaultRecord) => bits(2) begin let effective_ea : bit = EffectiveEA(); let effective_tea : bit = EffectiveHCR_TEA(); let effective_tge : bit = EffectiveTGE();

var target_el : bits(2);
if effective_ea == '1' || (PSTATE.EL == EL3 && (EL3)) then
    target_el = EL3;

elsif (EL2Enabled() && PSTATE.EL IN {EL1, EL0} &&
       (effective_tea == '1' || IsSecondStage(fault) ||
        fault.accessdesc.acctype == AccessType_NV2 ||
        (PSTATE.EL == EL0 && effective_tge == '1'))) then
    target_el = EL2;

elsif EffectiveHCRX_EL2_TMEA() == '1' && PSTATE.A == '1' &&
PSTATE.EL == EL1 then
    target_el = EL2;

elsif EffectiveSCR_EL3_TMEA() == '1' && PSTATE.A == '1' &&
PSTATE.EL IN {EL1, EL2} then
    target_el = EL3;

else
    assert PSTATE.EL != EL3 || ELUsingAArch32(EL3);
    target_el = (if PSTATE.EL == EL2 then EL2 else EL1);
end;

return target_el;

end;


## Library pseudocode for shared/exceptions/exceptions/ConditionSyndrome

// ConditionSyndrome // =================== // Return CV and COND fields of instruction syndrome

func ConditionSyndrome() => bits(5) begin

var syndrome : bits(5);

if UsingAArch32() then
    let cond = CurrentCond();
    if PSTATE.T == '0' then             // A32
        syndrome[4] = '1';
        // A conditional A32 instruction that is known to pass its condition code check
        // can be presented either with COND set to 0xE, the value for unconditional, or
        // the COND value held in the instruction.
        if ConditionHolds(cond) && ConstrainUnpredictableBool(Unpredictable_ESRCONDPASS) then
            syndrome[3:0] = '1110';
        else
            syndrome[3:0] = cond;
        end;
    else                                // T32
        // When a T32 instruction is trapped, it is IMPLEMENTATION DEFINED whether:
        //  * CV set to 0 and COND is set to an UNKNOWN value
        //  * CV set to 1 and COND is set to the condition code for the condition that
        //    applied to the instruction.
        if ImpDefBool("Condition valid for trapped T32") then
            syndrome[4] = '1';
            syndrome[3:0] = cond;
        else
            syndrome[4] = '0';
            syndrome[3:0] = ARBITRARY : bits(4);
        end;
    end;
else
    syndrome[4] = '1';
    syndrome[3:0] = '1110';
end;
return syndrome;

end;


## Library pseudocode for shared/exceptions/exceptions/Exception

// Exception // ========= // Classes of exception.

type Exception of enumeration { Exception_Uncategorized, // Uncategorized or unknown reason Exception_WFxTrap, // Trapped WFI or WFE instruction Exception_CP15RTTrap, // Trapped AArch32 MCR or MRC access, coproc=0b111 Exception_CP15RRTTrap, // Trapped AArch32 MCRR or MRRC access, coproc=0b1111 Exception_CP14RTTrap, // Trapped AArch32 MCR or MRC access, coproc=0b1110 Exception_CP14DTTrap, // Trapped AArch32 LDC or STC access, coproc=0b1110 Exception_CP14RRTTrap, // Trapped AArch32 MRRC access, coproc=0b1110 Exception_AdvSIMDFPAccessTrap, // HCPTR-trapped access to SIMD or FP Exception_FPIDTrap, // Trapped access to SIMD or FP ID register Exception_OtherTrap, // Trapped access to other instructions // Trapped BXJ instruction not supported in Armv8 Exception_PACTrap, // Trapped invalid PAC use Exception_IllegalState, // Illegal Execution state Exception_SupervisorCall, // Supervisor Call Exception_HypervisorCall, // Hypervisor Call Exception_MonitorCall, // Monitor Call or Trapped SMC instruction Exception_SystemRegisterTrap, // Trapped MRS or MSR System register access Exception_ERetTrap, // Trapped invalid ERET use Exception_InstructionAbort, // Instruction Abort or Prefetch Abort Exception_PCAlignment, // PC alignment fault Exception_DataAbort, // Data Abort Exception_NV2DataAbort, // Data abort at EL1 reported as being from EL2 Exception_PACFail, // PAC Authentication failure Exception_SPAlignment, // SP alignment fault Exception_FPTrappedException, // IEEE trapped FP exception Exception_SError, // SError interrupt Exception_Breakpoint, // (Hardware) Breakpoint Exception_SoftwareStep, // Software Step Exception_Watchpoint, // Watchpoint Exception_NV2Watchpoint, // Watchpoint at EL1 reported as being from EL2 Exception_SoftwareBreakpoint, // Software Breakpoint Instruction Exception_VectorCatch, // AArch32 Vector Catch Exception_IRQ, // IRQ interrupt Exception_SVEAccessTrap, // HCPTR trapped access to SVE Exception_SMEAccessTrap, // HCPTR trapped access to SME Exception_GPC, // Granule protection check Exception_BranchTarget, // Branch Target Identification Exception_MemCpyMemSet, // Exception from a CPY* or SET* instruction Exception_GCSFail, // GCS Exceptions Exception_Profiling, // Profiling exception Exception_SystemRegister128Trap, // Trapped MRRS or MSRR System register or SYSP access Exception_ConditionalFault, // Exception due to a CFLT instruction Exception_FIQ}; // FIQ interrupt


## Library pseudocode for shared/exceptions/exceptions/ExceptionRecord

// ExceptionRecord // ===============

type ExceptionRecord of record { exceptype : Exception, // Exception class syndrome : IssType, // Syndrome record paddress : FullAddress, // Physical fault address vaddress : bits(64), // Virtual fault address ipavalid : boolean, // Validity of Intermediate Physical fault address pavalid : boolean, // Validity of Physical fault address NS : bit, // Intermediate Physical fault address space ipaddress : bits(NUM_PABITS), // Intermediate Physical fault address trappedsyscallinst : boolean}; // Trapped SVC or SMC instruction


## Library pseudocode for shared/exceptions/exceptions/ExceptionSyndrome

// ExceptionSyndrome // =================== // Return a blank exception syndrome record for an exception of the given type.

func ExceptionSyndrome(exceptype : Exception) => ExceptionRecord begin

var r : ExceptionRecord;

r.exceptype      = exceptype;

// Initialize all other fields
r.syndrome.iss   = Zeros{25};
r.syndrome.iss2  = Zeros{24};
r.vaddress       = Zeros{64};
r.ipavalid       = FALSE;
r.pavalid        = FALSE;
r.NS             = '0';
r.ipaddress      = Zeros{NUM_PABITS};
r.paddress.paspace = ARBITRARY : PASpace;
r.paddress.address = ARBITRARY : bits(NUM_PABITS);
r.trappedsyscallinst = FALSE;
return r;

end;


## Library pseudocode for shared/exceptions/traps/Undefined

// Undefined // ===========

noreturn func Undefined begin if UsingAArch32() then AArch32_Undefined(); else AArch64_Undefined(); end; end;


## Library pseudocode for shared/functions/aborts/EncodeLDFSC

// EncodeLDFSC // ============= // Function that gives the Long-descriptor FSC code for types of Fault

func EncodeLDFSC(statuscode : Fault, level : integer) => bits(6) begin var result : bits(6);

// 128-bit descriptors will start from level -2 for 4KB to resolve
bits IA[55:51]
if level == -2 then
    assert IsFeatureImplemented(FEAT_D128);
    case statuscode of
        when Fault_AddressSize =>          result = '101100';
        when Fault_Translation =>          result = '101010';
        when Fault_SyncExternalOnWalk =>   result = '010010';
        when Fault_SyncParityOnWalk =>
            result = '011010';
            assert !IsFeatureImplemented(FEAT_RAS);
        when Fault_GPCFOnWalk =>           result = '100010';
        otherwise =>                       unreachable;
    end;
    return result;
end;

if level == -1 then
    assert IsFeatureImplemented(FEAT_LPA2);
    case statuscode of
        when Fault_AddressSize =>          result = '101001';
        when Fault_Translation =>          result = '101011';
        when Fault_SyncExternalOnWalk =>   result = '010011';
        when Fault_SyncParityOnWalk =>
            result = '011011';
            assert !IsFeatureImplemented(FEAT_RAS);
        when Fault_GPCFOnWalk =>           result = '100011';
        otherwise =>                       unreachable;
    end;

    return result;
end;
case statuscode of
    when Fault_AddressSize =>         result = '0000'::level[1:0]; assert level IN {0,1,2,3};
    when Fault_AccessFlag =>          result = '0010'::level[1:0]; assert level IN {0,1,2,3};
    when Fault_Permission =>          result = '0011'::level[1:0]; assert level IN {0,1,2,3};
    when Fault_Translation   =>       result = '0001'::level[1:0]; assert level IN {0,1,2,3};
    when Fault_AsyncExternal =>       result = '010001'; assert UsingAArch32();
    when Fault_SyncExternal  =>       result = '010000';
    when Fault_SyncExternalOnWalk =>  result = '0101'::level[1:0]; assert level IN {0,1,2,3};
    when Fault_SyncParity    =>       result = '011000';
------------------------------------------------------------------------------ Page 1 of 1. End of thread.