This forum was built by humans, for humans. AI was used exclusively for security auditing. The forum officially launched on November 24, 2026. Read more

romdump.net
romdump.net › Forum › Silicon & Architectures › Shared pseudocode: part 7 of 36

Writeup Shared pseudocode: part 7 of 36

started by admin

admin admin admingod mode Posts 116
Rep 505
Joined Nov 2026
2d ago OP #119

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

let ss : SecurityState = CurrentSecurityState();return AArch64_GenerateDebugExceptionsFrom(PSTATE.EL, ss, PSTATE.D);

end;


## Library pseudocode for aarch64/debug/enables/AArch64\_GenerateDebugExceptionsFrom

// AArch64_GenerateDebugExceptionsFrom // =====================================

func AArch64_GenerateDebugExceptionsFrom(from_el : bits(2), from_state : SecurityState, mask : bit) => boolean begin

if OSLSR_EL1().OSLK == '1' || DoubleLockStatus() || Halted() then
    return FALSE;
end;

let route_to_el2 : boolean = (HaveEL(EL2) && (from_state != SS_Secure || IsSecureEL2Enabled()) && (HCR_EL2().TGE == '1' || MDCR_EL2().TDE == '1')); let target : bits(2) = (if route_to_el2 then EL2 else EL1); var enabled : boolean; if HaveEL(EL3) && from_state == SS_Secure then enabled = MDCR_EL3().SDD == '0'; if from_el == EL0 && ELUsingAArch32(EL1) then enabled = enabled || SDER32_EL3().SUIDEN == '1'; end; else enabled = TRUE; end;

if from_el == target then enabled = enabled && MDSCR_EL1().KDE == '1' && mask == '0'; else enabled = enabled && UInt(target) > UInt(from_el); end;

return enabled;

end;


## Library pseudocode for aarch64/debug/ite/AArch64\_TRCIT

// AArch64_TRCIT // =============== // Determines whether an Instrumentation trace packet should // be generated and then generates an instrumentation trace packet // containing the value of the register passed as an argument

func AArch64_TRCIT(Xt : bits(64)) begin let ss = CurrentSecurityState(); if TraceInstrumentationAllowed(ss, PSTATE.EL) then TraceInstrumentation(Xt); end; end;


## Library pseudocode for aarch64/debug/ite/TraceInstrumentation

// TraceInstrumentation // ====================== // Generates an instrumentation trace packet // containing the value of the register passed as an argument

impdef func TraceInstrumentation(Xt : bits(64)) begin return; end;


## Library pseudocode for aarch64/debug/pmu/AArch64\_IncrementCycleCounter

// AArch64_IncrementCycleCounter // =============================== // Increment the cycle counter and possibly set overflow bits.

func AArch64_IncrementCycleCounter begin if (CYCLE_COUNTER_ID) then return; end; var d : bit = PMCR_EL0().D; // Check divide-by-64 var lc : bit = PMCR_EL0().LC; var lc_enabled : boolean; (lc_enabled, -) = PMUExceptionEnabled(); lc = if lc_enabled then '1' else lc; // Effective value of 'D' bit is 0 when Effective value of LC is '1' if lc == '1' then d = '0'; end; if d == '1' && () then return; end;

let old_value : integer = UInt(PMCCNTR_EL0());
let new_value : integer = old_value + 1;
PMCCNTR_EL0() = new_value[63:0];

let ovflw : integer{} = if HaveAArch32() && lc == '0' then 32 else 64;

if old_value[64:ovflw] != new_value[64:ovflw] then PMOVSSET_EL0().C = '1'; end;

return;

end;


## Library pseudocode for aarch64/debug/pmu/AArch64\_IncrementEventCounter

// AArch64_IncrementEventCounter // =============================== // Increment the specified event counter 'idx' by the specified amount 'increment'. // 'Vm' is the value event counter 'idx-1' is being incremented by if 'idx' is odd, // zero otherwise. // Returns the amount the counter was incremented by.

func AArch64_IncrementEventCounter(idx : integer, increment_in : integer, Vm : integer) => integer begin var old_value : integer; var new_value : integer;

old_value = UInt(PMEVCNTR_EL0(idx));
let increment : integer = PMUCountValue(idx, increment_in, Vm);
new_value = old_value + increment;

var lp : bit; if IsFeatureImplemented(FEAT_PMUv3p5) then PMEVCNTR_EL0(idx) = new_value[63:0]; var pmuexception_enabled : boolean; (pmuexception_enabled, -) = PMUExceptionEnabled(); if pmuexception_enabled then lp = '1'; else case GetPMUCounterRange(idx) of when PMUCounterRange_R1 => lp = PMCR_EL0().LP; when PMUCounterRange_R2 => lp = MDCR_EL2().HLP; when PMUCounterRange_R3 => lp = '1'; otherwise => unreachable; end; end; else lp = '0'; PMEVCNTR_EL0(idx) = ZeroExtend{64}(new_value[31:0]); end; let ovflw : integer{} = if lp == '1' then 64 else 32; if old_value[64:ovflw] != new_value[64:ovflw] then PMOVSSET_EL0()[idx] = '1'; // Check for the CHAIN event from an even counter if (idx[0] == '0' && idx + 1 < NUM_PMU_COUNTERS && lp == '0' && (GetPMUCounterRange(idx) == GetPMUCounterRange(idx+1) || ConstrainUnpredictableBool(Unpredictable_COUNT_CHAIN))) then // If PMU counters idx and idx+1 are not in same range, // it is CONSTRAINED UNPREDICTABLE if CHAIN event is counted PMUEvent(PMU_EVENT_CHAIN, 1, idx + 1); end; end;

return increment;

end;


## Library pseudocode for aarch64/debug/pmu/AArch64\_PMUCycle

// AArch64_PMUCycle // ================== // Called at the end of each cycle to increment event counters and // check for PMU overflow. In pseudocode, a cycle ends after the // execution of the operational pseudocode.

func AArch64_PMUCycle begin if !IsFeatureImplemented(FEAT_PMUv3) then return; end; if (( && ) || (!IsFeatureImplemented(FEAT_PMUv3p9) && ImpDefBool("PMU counts cycles in WFI or WFE state"))) then PMUEvent(PMU_EVENT_CPU_CYCLES); end; let counters : integer = NUM_PMU_COUNTERS; var Vm : integer = 0; if counters != 0 then for idx = 0 to counters - 1 do if CountPMUEvents(idx) then let accumulated : integer = PMUEventAccumulator[[idx]]; if (idx MOD 2) == 0 then Vm = 0; end; Vm = AArch64_IncrementEventCounter(idx, accumulated, Vm); end; PMUEventAccumulator[[idx]] = 0; end; end; AArch64_IncrementCycleCounter(); CheckForPMUOverflow(); end;


## Library pseudocode for aarch64/debug/profilingexception/TakeProfilingException

// TakeProfilingException // ======================== // Takes a Profiling exception.

func TakeProfilingException(target_el : bits(2), fsc : bits(5), synchronous : boolean) begin var except : ExceptionRecord = ExceptionSyndrome(Exception_Profiling); except.syndrome.iss[5:1] = fsc; if synchronous then except.syndrome.iss[0] = '1'; end;

let preferred_exception_return : bits(64) = ThisInstrAddr{}();let vect_offset : integer = 0x0;AArch64_TakeException(target_el, except, preferred_exception_return, vect_offset);

end;


## Library pseudocode for aarch64/debug/statisticalprofiling/CheckForSPEException

// CheckForSPEException // ====================== // Take an SPE Profiling exception if pending, permitted, and unmasked.

func CheckForSPEException begin if !IsFeatureImplemented(FEAT_SPE_EXC) then return; end;

if Halted() || Restarting() then
    return;
end;

var route_to_el3 : boolean = FALSE; var route_to_el2 : boolean = FALSE; var route_to_el1 : boolean = FALSE;

if HaveEL(EL3) && MDCR_EL3().PMSEE == '1x' then let pending : boolean = PMBSR_EL3().S == '1'; let masked : boolean = PSTATE.EL == EL3; route_to_el3 = pending && !masked; end;

var owning_ss : SecurityState; var owning_el : bits(2); (owning_ss, owning_el) = ProfilingBufferOwner(); let in_owning_ss : boolean = IsCurrentSecurityState(owning_ss);

if EffectivePMSCR_EL2_EE() == '1x' then let pending : boolean = PMBSR_EL2().S == '1'; let masked : boolean = (!in_owning_ss || PSTATE.EL == EL3 || (PSTATE.EL == EL2 && (PMSCR_EL2().EE != '11' || PMSCR_EL2().KE == '0' || PSTATE.PM == '1')) ); route_to_el2 = pending && !masked; end;

if EffectivePMSCR_EL1_EE() == '11' then let pending : boolean = PMBSR_EL1().S == '1'; let masked : boolean = (!in_owning_ss || PSTATE.EL IN {EL3, EL2} || (PSTATE.EL == EL1 && (PMSCR_EL1().KE == '0' || PSTATE.PM == '1')) ); if EffectiveTGE() == '1' then route_to_el2 = route_to_el2 || (pending && !masked); else route_to_el1 = pending && !masked; end; end;

let fsc : bits(5) = '00001'; // SPE exception let synchronous : boolean = FALSE;

// The relative priorities of the following checks is IMPLEMENTATION DEFINED if route_to_el3 then TakeProfilingException(EL3, fsc, synchronous); end; if route_to_el2 then TakeProfilingException(EL2, fsc, synchronous); end; if route_to_el1 then TakeProfilingException(EL1, fsc, synchronous); end;

end;


## Library pseudocode for aarch64/debug/statisticalprofiling/CheckMDCR\_EL3\_NSPBTrap

// CheckMDCR_EL3_NSPBTrap // ======================== // Check if the register access is trappable by MDCR_EL3.[NSPBE, NSPB]

func CheckMDCR_EL3_NSPBTrap() => boolean begin var state_bits : bits(3); var reserved : boolean; (state_bits, reserved) = EffectiveMDCR_EL3_NSPB(); return ((reserved && ConstrainUnpredictableBool(Unpredictable_RESERVEDNSxB_Trap)) || state_bits[0] == '0' || state_bits[1] != EffectiveSCR_EL3_NS() || (IsFeatureImplemented(FEAT_RME) && state_bits[2] != EffectiveSCR_EL3_NSE())); end;


## Library pseudocode for aarch64/debug/statisticalprofiling/CheckPSBTrap

// CheckPSBTrap // ============== // Checks whether PSB should trap to EL2.

func CheckPSBTrap begin if (IsFeatureImplemented(FEAT_FGT) && IsFeatureImplemented(FEAT_SPEv1p5) && PSTATE.EL IN {EL0, EL1} && EL2Enabled() && () && ((EL3) || SCR_EL3().FGTEn == '1') && HFGITR_EL2().PSBCSYNC == '1') then let target_el : bits(2) = EL2; let iss : bits(25) = 0x3[24:0]; AArch64_OtherInstrTrap(target_el, iss); end; end;


## Library pseudocode for aarch64/debug/statisticalprofiling/CollectContextIDR1

// CollectContextIDR1 // ==================== func CollectContextIDR1() => boolean begin if () then return FALSE; end; if PSTATE.EL == EL2 then return FALSE; end; if EL2Enabled() && HCR_EL2().TGE == '1' then return FALSE; end; return PMSCR_EL1().CX == '1'; end;


## Library pseudocode for aarch64/debug/statisticalprofiling/CollectContextIDR2

// CollectContextIDR2 // ====================

func CollectContextIDR2() => boolean begin if () then return FALSE; end; if () then return FALSE; end; return PMSCR_EL2().CX == '1'; end;


## Library pseudocode for aarch64/debug/statisticalprofiling/CollectPhysicalAddress

// CollectPhysicalAddress // ========================

func CollectPhysicalAddress() => boolean begin if () then return FALSE; end; let (owning_ss, owning_el) : (SecurityState, bits(2)) = ProfilingBufferOwner(); if HaveEL(EL2) && (owning_ss != SS_Secure || IsSecureEL2Enabled()) then return PMSCR_EL2().PA == '1' && (owning_el == EL2 || PMSCR_EL1().PA == '1'); else return PMSCR_EL1().PA == '1'; end; end;


## Library pseudocode for aarch64/debug/statisticalprofiling/CollectTimeStamp

// CollectTimeStamp // ================== func CollectTimeStamp() => TimeStamp begin if () then return TimeStamp_None; end; let (-, owning_el) = ProfilingBufferOwner();

if owning_el == EL2 then
    if PMSCR_EL2().TS == '0' then return TimeStamp_None; end;
else
    if PMSCR_EL1().TS == '0' then return TimeStamp_None; end;
end;

var PCT_el1 : bits(2); if !IsFeatureImplemented(FEAT_ECV) then PCT_el1 = '0'::PMSCR_EL1().PCT[0]; // PCT[1] is RES0 else PCT_el1 = PMSCR_EL1().PCT; if PCT_el1 == '10' then // Reserved value (-, PCT_el1) = ConstrainUnpredictableBits{2}(Unpredictable_PMSCR_PCT); end; end; if EL2Enabled() then var PCT_el2 : bits(2); if !IsFeatureImplemented(FEAT_ECV) then PCT_el2 = '0'::PMSCR_EL2().PCT[0]; // PCT[1] is RES0 else PCT_el2 = PMSCR_EL2().PCT; if PCT_el2 == '10' then // Reserved value (-, PCT_el2) = ConstrainUnpredictableBits{2}(Unpredictable_PMSCR_PCT); end; end; case PCT_el2 of when '00' => return if IsInHost() then TimeStamp_Physical else TimeStamp_Virtual; when '01' => if owning_el == EL2 then return TimeStamp_Physical; end; when '11' => assert IsFeatureImplemented(FEAT_ECV); // FEAT_ECV must be implemented if owning_el == EL1 && PCT_el1 == '00' then return if IsInHost() then TimeStamp_Physical else TimeStamp_Virtual; else return TimeStamp_OffsetPhysical; end; otherwise => unreachable; end; end;

case PCT_el1 of when '00' => return if IsInHost() then TimeStamp_Physical else TimeStamp_Virtual; when '01' => return TimeStamp_Physical; when '11' => assert IsFeatureImplemented(FEAT_ECV); // FEAT_ECV must be implemented return TimeStamp_OffsetPhysical; otherwise => unreachable; end;

end;


## Library pseudocode for aarch64/debug/statisticalprofiling/DefaultSPEEvent

// DefaultSPEEvent // ================= // Return the target ELx for an indirect write to PMBSR_ELx for an Other buffer management // event or anything other than a buffer management event.

func DefaultSPEEvent() => bits(2) begin return ReportSPEEvent(Zeros{6}, ARBITRARY : bits(6)); end;


## Library pseudocode for aarch64/debug/statisticalprofiling/EffectiveMDCR\_EL3\_NSPB

// EffectiveMDCR_EL3_NSPB // ======================== // Return the Effective value of MDCR_EL3.[NSPBE, NSPB] field and whether it is a reserved value.

readonly func EffectiveMDCR_EL3_NSPB() => (bits(3), boolean) begin var state_bits : bits(3); var reserved : boolean = FALSE;

if IsFeatureImplemented(FEAT_RME) then
    state_bits = MDCR_EL3().[NSPBE, NSPB];
    if state_bits == '10x' || (!IsFeatureImplemented(FEAT_Secure) && state_bits == '00x') then
        // Reserved value
        reserved = TRUE;
        (-, state_bits) = ConstrainUnpredictableBits{3}(Unpredictable_RESERVEDNSxB);
    end;
else
    state_bits = '0' :: MDCR_EL3().NSPB;
end;

return (state_bits, reserved);

end;


## Library pseudocode for aarch64/debug/statisticalprofiling/EffectivePMBLIMITR\_EL1\_nVM

// EffectivePMBLIMITR_EL1_nVM // ============================

readonly func EffectivePMBLIMITR_EL1_nVM() => bit begin if !IsFeatureImplemented(FEAT_SPE_nVM) then return '0'; end; if HaveEL(EL2) then let (owning_ss, owning_el) : (SecurityState, bits(2)) = ProfilingBufferOwner(); if ((owning_ss != SS_Secure || IsSecureEL2Enabled()) && owning_el == EL1 && PMSCR_EL2().EnVM == '0') then return '0'; end; end; return PMBLIMITR_EL1().nVM; end;


## Library pseudocode for aarch64/debug/statisticalprofiling/EffectivePMSCR\_EL1\_EE

// EffectivePMSCR_EL1_EE // ======================= // Return the Effective value of PMSCR_EL1.EE for the purpose of controlling the // SPE Profiling exception.

func EffectivePMSCR_EL1_EE() => bits(2) begin if EffectivePMSCR_EL2_EE() == '00' then return '00'; end;

var ee : bits(2) = PMSCR_EL1().EE;
if ee IN {'01', '10'} then            // Reserved value
    if IsFeatureImplemented(FEAT_NV) then
        ee[0] = ee[1];
    else
        var c : Constraint;
        (c, ee) = ConstrainUnpredictableBits{2}(Unpredictable_RESPMSEE);
        assert c IN {Constraint_DISABLED, Constraint_UNKNOWN};
        if c == Constraint_DISABLED then
            ee = '00';
        end;
        // Otherwise the value returned by ConstrainUnpredictableBits must be
        // a non-reserved value
    end;
end;

return ee;

end;


## Library pseudocode for aarch64/debug/statisticalprofiling/EffectivePMSCR\_EL2\_EE

// EffectivePMSCR_EL2_EE // ======================= // Return the Effective value of PMSCR_EL2.EE.

readonly func EffectivePMSCR_EL2_EE() => bits(2) begin if !IsFeatureImplemented(FEAT_SPE_EXC) then return '00'; end;

if HaveEL(EL3) && MDCR_EL3().PMSEE == '00' then
    return '00';
end;

let check_el2 : boolean = (HaveEL(EL2) && (EffectiveSCR_EL3_NS() == '1' || IsSecureEL2Enabled())); return if check_el2 then PMSCR_EL2().EE else '01';

end;


## Library pseudocode for aarch64/debug/statisticalprofiling/GetPMBSR\_EL1\_FSC

// GetPMBSR_EL1_FSC // ================== // Query the PMBSR_EL1.FSC field.

func GetPMBSR_EL1_FSC() => bits(6) begin var FSC : bits(6);

FSC = PMBSR_EL1()[5:0];return FSC;

end;


## Library pseudocode for aarch64/debug/statisticalprofiling/GetPMBSR\_EL2\_FSC

// GetPMBSR_EL2_FSC // ================== // Query the PMBSR_EL2.FSC field.

func GetPMBSR_EL2_FSC() => bits(6) begin var FSC : bits(6);

FSC = PMBSR_EL2()[5:0];return FSC;

end;


## Library pseudocode for aarch64/debug/statisticalprofiling/GetPMBSR\_EL3\_FSC

// GetPMBSR_EL3_FSC // ================== // Query the PMBSR_EL3.FSC field.

func GetPMBSR_EL3_FSC() => bits(6) begin var FSC : bits(6);

FSC = PMBSR_EL3()[5:0];return FSC;

end;


## Library pseudocode for aarch64/debug/statisticalprofiling/OtherSPEManagementEvent

// OtherSPEManagementEvent // ========================= // Report an Other buffer management event, with the status code 'bsc'

func OtherSPEManagementEvent(bsc : bits(6)) begin let target_el : bits(2) = DefaultSPEEvent(); if PMBSR_EL(target_el).S == '0' then PMBSR_EL(target_el).S = '1'; // Assert interrupt or exception PMBSR_EL(target_el).EC = '000000'; // Other buffer management event PMBSR_EL(target_el).MSS = ZeroExtend{16}(bsc); PMBSR_EL(target_el).MSS2 = Zeros{24}; end; end;


## Library pseudocode for aarch64/debug/statisticalprofiling/PMBSR\_EL

// PMBSR_EL - accessor // ===================

accessor PMBSR_EL(el : bits(2)) <=> value : PMBSRType begin getter var r : bits(64); case el of when EL1 => r = PMBSR_EL1(); when EL2 => r = PMBSR_EL2(); when EL3 => r = PMBSR_EL3(); otherwise => unreachable; end; return r; end; setter let r : bits(64) = value; case el of when EL1 => PMBSR_EL1() = r; when EL2 => PMBSR_EL2() = r; when EL3 => PMBSR_EL3() = r; otherwise => unreachable; end; return; end; end;


## Library pseudocode for aarch64/debug/statisticalprofiling/ProfilingBufferEnabled

// ProfilingBufferEnabled // ========================

readonly func ProfilingBufferEnabled() => boolean begin if !IsFeatureImplemented(FEAT_SPE) then return FALSE; end;

let (-, owning_el) : (SecurityState, bits(2)) = ProfilingBufferOwner();

return (owning_el) && PMBLIMITR_EL1().E == '1';

end;


## Library pseudocode for aarch64/debug/statisticalprofiling/ProfilingBufferOwner

// ProfilingBufferOwner // ======================

readonly func ProfilingBufferOwner() => (SecurityState, bits(2)) begin var owning_ss : SecurityState;

var state_bits : bits(3);
if HaveEL(EL3) then
    (state_bits, -) = EffectiveMDCR_EL3_NSPB();
else
    state_bits = if SecureOnlyImplementation() then '001' else '011';
end;

case state_bits of when '00x' => owning_ss = SS_Secure; when '01x' => owning_ss = SS_NonSecure; when '11x' => owning_ss = SS_Realm; end;

var owning_el : bits(2); if HaveEL(EL2) && (owning_ss != SS_Secure || IsSecureEL2Enabled()) then owning_el = if MDCR_EL2().E2PB == '00' then EL2 else EL1; else owning_el = EL1; end;

return (owning_ss, owning_el);

end;


## Library pseudocode for aarch64/debug/statisticalprofiling/ProfilingSynchronizationBarrier

// ProfilingSynchronizationBarrier // ================================= // Barrier to ensure that all existing profiling data has been formatted, and profiling buffer // addresses have been translated such that writes to the profiling buffer have been initiated. // A following DSB completes when writes to the profiling buffer have completed.

impdef func ProfilingSynchronizationBarrier begin return; end;


## Library pseudocode for aarch64/debug/statisticalprofiling/ReportSPEEvent

// ReportSPEEvent // ================ // Return the target ELx for an indirect write to PMBSR_ELx. // When the indirect write is due to a buffer management event: // 'ec_bits' is the Event Class for the management event. // 'fsc_bits' is the Fault Status Code when this is a fault, ignored otherwise. // Otherwise, 'ec_bits' should be Zeros().

func ReportSPEEvent(ec_bits : bits(6), fsc_bits : bits(6)) => bits(2) begin var target_el : bits(2); var route_to_el3 : boolean = FALSE; var route_to_el2 : boolean = FALSE;

if IsFeatureImplemented(FEAT_SPE_EXC) then
    if ec_bits == '011111' then                      // implementation defined fault
        return ImpDefBits{2}("target_el for SPE ImpDef Fault");
    end;
let s1fault : boolean = (ec_bits == '100100');   // Stage 1 faultlet s2fault : boolean = (ec_bits == '100101');   // Stage 2 faultvar gpcfault, gpfault : boolean;if IsFeatureImplemented(FEAT_RME) then    // Granule Protection Check fault, other than GPF. That is, a GPT address size fault,    // GPT walk fault, or synchronous External abort on GPT fetch.    gpcfault = (ec_bits == '011110');    // Other Granule Protection Fault, reported as Stage 1 or Stage 2 fault.    gpfault  =  ((s1fault || s2fault) &amp;&amp; fsc_bits IN {'10001x', '1001xx', '101000'});else    gpcfault = FALSE;    gpfault  = FALSE;end;let sync_ext_abort : boolean = ((s1fault || s2fault) &amp;&amp;                                   fsc_bits IN {'010000', '01001x', '0101xx', '011011'});var owning_ss : SecurityState;var owning_el : bits(2);(owning_ss, owning_el) = ProfilingBufferOwner();if HaveEL(EL3) &amp;&amp; MDCR_EL3().PMSEE == '1x' then    route_to_el3 = (MDCR_EL3().PMSEE == '11' ||                    gpcfault || (gpfault &amp;&amp; SCR_EL3().GPF == '1') ||                    (sync_ext_abort &amp;&amp; EffectiveEA() == '1'));end;if EffectivePMSCR_EL2_EE() == '1x' then    route_to_el2 = (PMSCR_EL2().EE == '11' || (s1fault &amp;&amp; owning_el == EL2) || s2fault ||                    gpcfault || (gpfault &amp;&amp; HCR_EL2().GPF == '1') ||                    (sync_ext_abort &amp;&amp; EffectiveHCR_TEA() == '1'));end;

end;

if route_to_el3 then target_el = EL3; elsif route_to_el2 then target_el = EL2; else target_el = EL1; end;

return target_el;

end;


## Library pseudocode for aarch64/debug/statisticalprofiling/SPE

// SPE Implementation Constants // ============================

constant SPEMaxAddrs : integer{} = 32; constant SPEMaxCounters : integer{} = 32; constant SPEMaxRecordSize : integer{} = 2048;


## Library pseudocode for aarch64/debug/statisticalprofiling/SPEAddByteToRecord

// SPEAddByteToRecord // ==================== // Add one byte to a record and increase size property appropriately.

func SPEAddByteToRecord(b : bits(8)) begin assert SPERecordSize < SPEMaxRecordSize; SPERecordData[[SPERecordSize]] = b; SPERecordSize = SPERecordSize + 1; end;


## Library pseudocode for aarch64/debug/statisticalprofiling/SPEAddPacketToRecord

// SPEAddPacketToRecord // ====================== // Add passed header and payload data to the record. // Payload must be a multiple of 8.

func SPEAddPacketToRecord{N}(header_hi : bits(2), header_lo : bits(4), payload : bits(N)) begin assert N MOD 8 == 0; var sz : bits(2); case N of when 8 => sz = '00'; when 16 => sz = '01'; when 32 => sz = '10'; when 64 => sz = '11'; otherwise => unreachable; end;

let header : bits(8) = header_hi::sz::header_lo;SPEAddByteToRecord(header);for i = 0 to (N DIV 8)-1 do    SPEAddByteToRecord(payload[i*:8]);end;

end;


## Library pseudocode for aarch64/debug/statisticalprofiling/SPEAddressEnabled

// SPEAddressEnabled // =================== // Checks if an address packet is enabled and its data can be recorded.

func SPEAddressEnabled(address_index : integer) => boolean begin var address_packet_enabled: boolean; let have_pbtfilt : boolean = IsFeatureImplemented(FEAT_SPE_PBTFILT);

case address_index of
    when SPEAddrPosPrevBranchTarget =>
        address_packet_enabled = !have_pbtfilt || PMSFCR_EL1().nPBT == '0';
    otherwise =>
        address_packet_enabled = TRUE;
end;

return address_packet_enabled;

end;


## Library pseudocode for aarch64/debug/statisticalprofiling/SPEBranch

// SPEBranch // =========== // Called on every branch if SPE is present. Maintains previous branch target // and branch related SPE functionality.

func SPEBranch{N}(target : bits(N), branch_type : BranchType, conditional : boolean, taken_flag : boolean) begin let is_isb : boolean = FALSE; SPEBranch{N}(target, branch_type, conditional, taken_flag, is_isb); end;

func SPEBranch{N}(target : bits(N), branch_type : BranchType, conditional : boolean, taken_flag : boolean, is_isb : boolean) begin // If the PE implements branch prediction, data about (mis)prediction is collected // through the PMU events.

var collect_prev_br : boolean;
let collect_prev_br_eret : boolean = ImpDefBool("SPE prev br on eret");
let collect_prev_br_exception : boolean = (ImpDefBool(
                                              "SPE prev br on exception"));
let collect_prev_br_isb : boolean = ImpDefBool("SPE prev br on isb");
case branch_type of
    when BranchType_EXCEPTION => collect_prev_br = collect_prev_br_exception;
    when BranchType_ERET      => collect_prev_br = collect_prev_br_eret;
    otherwise                 => collect_prev_br = !is_isb || collect_prev_br_isb;
end;

// Implements previous branch target functionality if (taken_flag && IsFeatureImplemented(FEAT_SPE_PBT) && StatisticalProfilingEnabled() && collect_prev_br) then

if SPESampleInFlight then    let previous_target : bits(64) = SPESamplePreviousBranchAddress;    SPESampleAddress[[SPEAddrPosPrevBranchTarget]][63:0] = previous_target[63:0];    let previous_branch_valid : boolean = SPESamplePreviousBranchAddressValid;    SPESampleAddressValid[[SPEAddrPosPrevBranchTarget]] = previous_branch_valid;end;// Save the target address for it to be added to a future record.SPESamplePreviousBranchAddress[55:0] = target[55:0];var ns : bit;var nse : bit;case CurrentSecurityState() of    when SS_Secure =&gt;        ns = '0';        nse = '0';    when SS_NonSecure =&gt;        ns = '1';        nse = '0';    when SS_Realm =&gt;        ns  = '1';        nse = '1';    otherwise =&gt; unreachable;end;SPESamplePreviousBranchAddress[63] = ns;SPESamplePreviousBranchAddress[60] = nse;SPESamplePreviousBranchAddress[62:61] = PSTATE.EL;SPESamplePreviousBranchAddressValid   = TRUE;

end;

if () then if taken_flag then // Invalidate previous branch address, if profiling is disabled // or prohibited. SPESamplePreviousBranchAddressValid = FALSE; end; return; end;

if SPESampleInFlight then SPESampleOpAttr.branch_is_direct = branch_type IN {BranchType_DIR, BranchType_DIRCALL}; SPESampleOpAttr.branch_has_link = branch_type IN {BranchType_DIRCALL, BranchType_INDCALL}; SPESampleOpAttr.procedure_return = branch_type == BranchType_RET; SPESampleOpAttr.op_type = SPEOpType_Branch; SPESampleOpAttr.is_conditional = conditional; SPESampleOpAttr.cond_pass = taken_flag;

// Save the target address.if taken_flag then    var ns : bit;    var nse : bit;    case CurrentSecurityState() of        when SS_Secure =&gt;            ns = '0';            nse = '0';        when SS_NonSecure =&gt;            ns = '1';            nse = '0';        when SS_Realm =&gt;            ns  = '1';            nse = '1';        otherwise =&gt; unreachable;    end;    let el : bits(2) = PSTATE.EL;    SPESampleAddress[[SPEAddrPosBranchTarget]][55:0]  = target[55:0];    SPESampleAddress[[SPEAddrPosBranchTarget]][63:56] = ns::el::nse::Zeros{4};    SPESampleAddressValid[[SPEAddrPosBranchTarget]]   = TRUE;end;

end;

end;


## Library pseudocode for aarch64/debug/statisticalprofiling/SPEBufferIsFull

// SPEBufferIsFull // ================= // Return true if another full size sample record would not fit in the // profiling buffer.

func SPEBufferIsFull() => boolean begin let write_pointer_limit : integer = UInt(PMBLIMITR_EL1().LIMIT::Zeros{12}); let current_write_pointer : integer = UInt(PMBPTR_EL1()); let record_max_size : integer = 1 << UInt(PMSIDR_EL1().MaxSize); return current_write_pointer > (write_pointer_limit - record_max_size); end;


## Library pseudocode for aarch64/debug/statisticalprofiling/SPECollectRecord

// SPECollectRecord // ================== // Returns TRUE if the sampled class of instructions or operations, as // determined by PMSFCR_EL1, are recorded and FALSE otherwise.

func SPECollectRecord(events : bits(64), total_latency : integer, optype : SPEOpType) => boolean begin // Filtering by events var is_rejected_event : boolean; var is_rejected_nevent : boolean; (is_rejected_event, is_rejected_nevent) = SPEFilterByEvents(events);

// Filtering by type
let is_rejected_type : boolean = SPEFilterByType(SPESampleOpAttr);

// Filtering by latency let is_rejected_latency : boolean = SPEFilterByLatency(total_latency);

let is_rejected_data_source : boolean = SPEFilterByDataSource(optype);

var return_value : boolean; return_value = !(is_rejected_nevent || is_rejected_event || is_rejected_type || is_rejected_latency || is_rejected_data_source);

if return_value then PMUEvent(PMU_EVENT_SAMPLE_FILTRATE); end;

return return_value;

end;


## Library pseudocode for aarch64/debug/statisticalprofiling/SPECompleteSample

// SPECompleteSample // =================== // Called to complete the sampling process.

func SPECompleteSample begin assert SPESampleInFlight;

PMUEvent(PMU_EVENT_SAMPLE_FEED);

// Stop any pending counters for counter_index = 0 to (SPEMaxCounters - 1) do if SPESampleCounterPending[[counter_index]] then SPEStopCounter(counter_index); end; end;

// Record any IMPLEMENTATION DEFINED events let impdef_events : bits(64) = ImpDefBits{}("SPE EVENTS"); SPESampleEvents[63:48] = impdef_events[63:48]; // The number of bits available for IMPLEMENTATION DEFINED events // is reduced by FEAT_SPEv1p4 if !IsFeatureImplemented(FEAT_SPEv1p4) then SPESampleEvents[31:24] = impdef_events[31:24]; end; SPESampleEvents[15:12] = impdef_events[15:12]; // Bit 24 encodes whether the sample was collected in Streaming SVE mode. if IsFeatureImplemented(FEAT_SPE_SME) then SPESampleEvents[24] = PSTATE.SM; end; SPESampleEvents[6] = if (SPESampleOpAttr.is_conditional && .cond_pass) then '1' else '0';

var collect_record : boolean; collect_record = SPECollectRecord(SPESampleEvents, SPESampleCounter[[SPECounterPosTotalLatency]], SPESampleOpAttr.op_type); var discard : boolean = FALSE; if IsFeatureImplemented(FEAT_SPEv1p2) then discard = PMBLIMITR_EL1().FM == '10'; end; if collect_record && !discard then SPEConstructRecord(); if SPEBufferIsFull() then let bsc : bits(6) = '000001'; // Buffer full event OtherSPEManagementEvent(bsc); PMUEvent(PMU_EVENT_SAMPLE_BUFFER_FULL); end; end;

SPESampleInFlight = FALSE;

SPEResetSampleStorage();

end;

// Order of addresses in sample storage and architectural index values constant SPEAddrPosPCVirtual : integer = 0; constant SPEAddrPosBranchTarget : integer = 1; constant SPEAddrPosDataVirtual : integer = 2; constant SPEAddrPosDataPhysical : integer = 3; constant SPEAddrPosPrevBranchTarget : integer = 4; // Order of counters in sample storage and architectural index values constant SPECounterPosTotalLatency : integer = 0; constant SPECounterPosIssueLatency : integer = 1; constant SPECounterPosTranslationLatency : integer = 2; constant SPECounterPosAltIssueLatency : integer = 4; // Sample in-flight flag var SPESampleInFlight : boolean = FALSE;

// Globally declared variables which store data about the sample.

// Context storage var SPESampleContextEL1 : bits(32); var SPESampleContextEL1Valid : boolean; var SPESampleContextEL2 : bits(32); var SPESampleContextEL2Valid : boolean;

// Counter storage var SPESampleCounter : array [[SPEMaxCounters]] of integer; var SPESampleCounterValid : array [[SPEMaxCounters]] of boolean; var SPESampleCounterPending : array [[SPEMaxCounters]] of boolean;

// Address storage var SPESampleAddress : array [[SPEMaxAddrs]] of bits(64); var SPESampleAddressValid : array [[SPEMaxAddrs]] of boolean; var SPESamplePreviousBranchAddress : bits(64); var SPESamplePreviousBranchAddressValid : boolean;

// Data source storage var SPESampleDataSource : bits(16); var SPESampleDataSourceValid : boolean;

// OpAttr storage var SPESampleOpAttr : SPEOpAttr;

// Timestamp storage var SPESampleTimestamp : bits(64); var SPESampleTimestampValid : boolean;

// Event storage var SPESampleEvents : bits(64);


## Library pseudocode for aarch64/debug/statisticalprofiling/SPEConstructClass

// SPEConstructClass // =================== // Constructs the encodings for the class and subclass fields.

func SPEConstructClass() => (bits(2), bits(8)) begin var op_class : bits(2); var op_subclass : bits(8); let cond : bit = if SPESampleOpAttr.is_conditional then '1' else '0'; let fp : bit = if SPESampleOpAttr.is_floating_point then '1' else '0'; let ldst : bit = if SPESampleOpAttr.op_type == SPEOpType_Store then '1' else '0'; let ar : bit = if SPESampleOpAttr.is_acquire_release then '1' else '0'; let excl : bit = if SPESampleOpAttr.is_exclusive then '1' else '0'; let at : bit = if SPESampleOpAttr.at then '1' else '0'; let indirect : bit = if SPESampleOpAttr.branch_is_direct then '0' else '1'; let pred : bit = if SPESampleOpAttr.is_predicated then '1' else '0'; let sg : bit = if SPESampleOpAttr.is_gather_scatter then '1' else '0'; let evl : bits(3) = SPESampleOpAttr.evl; let simd : bit = if SPESampleOpAttr.is_simd then '1' else '0'; let ets : bits(4) = SPESampleOpAttr.ets; // Since this implementation of SPE samples instruction instead of micro-operations, a // Branch with link or Procedure return instruction will never be recorded as a "Load/store, // GCS" format Operation Type packet. Therefore the COMMON bit is hard-wired to '1'. let common : bit = '1'; if SPESampleOpAttr.op_type == SPEOpType_Other then op_class = '00'; op_subclass = Zeros{5}::simd::fp::cond; elsif SPESampleOpAttr.op_type == SPEOpType_OtherSVE then op_class = '00'; op_subclass = '0'::evl::'1'::pred::fp::'0'; elsif SPESampleOpAttr.op_type == SPEOpType_OtherSME then op_class = '00'; op_subclass = '1'::ets[3:1]::'1'::ets[0]::fp::'0'; elsif SPESampleOpAttr.op_type == SPEOpType_Branch then op_class = '10'; var cr : bits(2) = '00'; var gcs : bit = '0'; if IsFeatureImplemented(FEAT_SPE_CRR) then if SPESampleOpAttr.branch_has_link then cr = '01'; elsif SPESampleOpAttr.procedure_return then cr = '10'; else cr = '11'; end; end; if IsFeatureImplemented(FEAT_GCS) then if (SPESampleOpAttr.ldst_type == SPELDSTType_GCS && (SPESampleOpAttr.branch_has_link || SPESampleOpAttr.procedure_return)) then gcs = '1'; end; end; op_subclass = Zeros{3}::cr::gcs::indirect::cond; elsif SPESampleOpAttr.op_type IN {SPEOpType_Load, SPEOpType_Store, SPEOpType_LoadAtomic} then op_class = '01'; case SPESampleOpAttr.ldst_type of when SPELDSTType_NV2 => op_subclass = '0011000'::ldst; when SPELDSTType_Extended => op_subclass = '000'::ar::excl::at::'1'::ldst; when SPELDSTType_General => op_subclass = Zeros{7}::ldst; when SPELDSTType_SIMDFP => op_subclass = '0000010'::ldst; when SPELDSTType_SVESME => op_subclass = sg::evl::'1'::pred::'0'::ldst; when SPELDSTType_Unspecified => op_subclass = '0001000'::ldst; when SPELDSTType_Tags => op_subclass = '0001010'::ldst; when SPELDSTType_MemCopy => op_subclass = '0010000'::ldst; when SPELDSTType_MemSet => op_subclass = '00100101'; when SPELDSTType_GCS => op_subclass = '01000'::common::'0'::ldst; when SPELDSTType_GCSSS2 => unreachable; // GCSSS2 is converted to GCS, should not appear here otherwise => unreachable; end; else unreachable; end; return (op_class, op_subclass); end;


## Library pseudocode for aarch64/debug/statisticalprofiling/SPEConstructRecord

// SPEConstructRecord // ==================== // Create new record and populate it with packets using sample storage data. // This is an example implementation, packets may appear in // any order as long as the record ends with an End or Timestamp packet.

func SPEConstructRecord begin // Empty the record. SPEEmptyRecord();

var op_class : bits(2);
var op_subclass : bits(8);
// Add operation details
(op_class, op_subclass) = SPEConstructClass();
SPEAddPacketToRecord{8}('01', '10'::op_class, op_subclass);

// Add contextEL1 if available if SPESampleContextEL1Valid then SPEAddPacketToRecord{32}('01', '0100', SPESampleContextEL1); end;

// Add contextEL2 if available if SPESampleContextEL2Valid then SPEAddPacketToRecord{32}('01', '0101', SPESampleContextEL2); end;

// Add valid counters for counter_index = 0 to (SPEMaxCounters - 1) do if SPESampleCounterValid[[counter_index]] then if counter_index >= 8 then // Need extended format SPEAddByteToRecord('001000'::counter_index[4:3]); end; // Check for overflow let large_counters : boolean = ImpDefBool("SPE 16bit counters"); if large_counters then if SPESampleCounter[[counter_index]] > 0xFFFF then SPESampleCounter[[counter_index]] = 0xFFFF; end; else if SPESampleCounter[[counter_index]] > 0xFFF then SPESampleCounter[[counter_index]] = 0xFFF; end; end;

    // Add byte0 for short format (byte1 for extended format)    SPEAddPacketToRecord{16}('10', '1'::counter_index[2:0],                             SPESampleCounter[[counter_index]][15:0]);end;

end;

// Add valid addresses if IsFeatureImplemented(FEAT_SPE_PBT) then // Under some conditions, it is IMPLEMENTATION_DEFINED whether the // previous branch packet is present. let include_prev_br : boolean = ImpDefBool("SPE get prev br if not br"); if SPESampleOpAttr.op_type != SPEOpType_Branch && !include_prev_br then SPESampleAddressValid[[SPEAddrPosPrevBranchTarget]] = FALSE; end; end;

// Data Virtual address should not be collected if this was an NV2 access and Statistical // Profiling is disabled at EL2. if (EL2) && SPESampleOpAttr.ldst_type == SPELDSTType_NV2 then SPESampleAddressValid[[SPEAddrPosDataVirtual]] = FALSE; end;

for address_index = 0 to (SPEMaxAddrs - 1) do if SPESampleAddressValid[[address_index]] && SPEAddressEnabled(address_index) then if address_index >= 8 then // Need extended format SPEAddByteToRecord('001000'::address_index[4:3]); end; SPEAddPacketToRecord{64}('10', '0'::address_index[2:0], SPESampleAddress[[address_index]]); end; end;

// Add Data Source if SPESampleDataSourceValid then let ds_payload_size : integer{} = SPEGetDataSourcePayloadSize(); SPEAddPacketToRecord{8 * ds_payload_size}('01', '0011', SPESampleDataSource[8*ds_payload_size-1:0]); end;

// Add events // Get size of payload in bytes. let payload_size : integer{} = SPEGetEventsPayloadSize(); SPEAddPacketToRecord{8 * payload_size}('01', '0010', SPESampleEvents[8*payload_size-1:0]);

// Add Timestamp to end the record if one is available. // Otherwise end with an End packet. if SPESampleTimestampValid then SPEAddPacketToRecord{64}('01', '0001', SPESampleTimestamp); else SPEAddByteToRecord('00000001'); end;

// Add padding while SPERecordSize MOD (1<<UInt(PMBIDR_EL1().Align)) != 0 looplimit 2048 do SPEAddByteToRecord(Zeros{8}); end; SPEWriteToBuffer(); CTI_SignalEvent(CrossTriggerIn_SPESample);

end;


## Library pseudocode for aarch64/debug/statisticalprofiling/SPECycle

// SPECycle // ========== // Function called at the end of every cycle. Responsible for asserting interrupts // and advancing counters.

func SPECycle begin if !IsFeatureImplemented(FEAT_SPE) then return; end;

// Increment pending countersif SPESampleInFlight then    for i = 0 to (SPEMaxCounters - 1) do        if SPESampleCounterPending
  • then SPESampleCounter

  • = SPESampleCounter

    • 1; end; end; end;

    // Assert PMBIRQ if appropriate. if SPEInterruptEnabled() && PMBSR_EL1().S == '1' then SetInterruptRequestLevel(InterruptID_PMBIRQ, HIGH); else SetInterruptRequestLevel(InterruptID_PMBIRQ, LOW); end; end;


## Library pseudocode for aarch64/debug/statisticalprofiling/SPEEmptyRecord

// SPEEmptyRecord // ================ // Reset record data.

func SPEEmptyRecord begin SPERecordSize = 0; for i = 0 to (SPEMaxRecordSize - 1) do SPERecordData

  • = Zeros{8}; end; end;

## Library pseudocode for aarch64/debug/statisticalprofiling/SPEEncodeETS

// SPEEncodeETS // ============== // Encodes an integer tile size length into the ets field for the SPE operation type packet.

func SPEEncodeETS(size : integer) => bits(4) begin var ets : bits(4); if size <= 128 then ets = '0000'; elsif size <= 256 then ets = '0001'; elsif size <= 512 then ets = '0010'; elsif size <= 1024 then ets = '0011'; elsif size <= 2048 then ets = '0100'; elsif size <= 4096 then ets = '0101'; elsif size <= 8192 then ets = '0110'; elsif size <= 16384 then ets = '0111'; elsif size <= 32768 then ets = '1000'; elsif size <= 65536 then ets = '1001'; elsif size <= 131072 then ets = '1010'; elsif size <= 262144 then ets = '1011'; else ets = '1111'; end; return ets; end;


## Library pseudocode for aarch64/debug/statisticalprofiling/SPEEncodeEVL

// SPEEncodeEVL // ============== // Encodes an integer vector length into the evl field for the SPE operation type packet.

func SPEEncodeEVL(vl : integer) => bits(3) begin var evl : bits(3); if vl <= 32 then evl = '000'; elsif vl <= 64 then evl = '001'; elsif vl <= 128 then evl = '010'; elsif vl <= 256 then evl = '011'; elsif vl <= 512 then evl = '100'; elsif vl <= 1024 then evl = '101'; elsif vl <= 2048 then evl = '110'; else if IsFeatureImplemented(FEAT_SPE_SME) then evl = '111'; else unreachable; end; end; return evl; end;


## Library pseudocode for aarch64/debug/statisticalprofiling/SPEEvent

// SPEEvent // ========== // Called when a PMU event is generated by the sampled structure. // Sets appropriate bit in SPESampleStorage.events.

func SPEEvent(pmuevent : bits(16)) begin if SPESampleInFlight then case pmuevent of when PMU_EVENT_DSNP_HIT_RD => if IsFeatureImplemented(FEAT_SPEv1p4) then SPESampleEvents[23] = '1'; // Snoop hit end; when {PMU_EVENT_L1D_LFB_HIT_RD, PMU_EVENT_L2D_LFB_HIT_RD, PMU_EVENT_L3D_LFB_HIT_RD, PMU_EVENT_LL_LFB_HIT_RD} => if IsFeatureImplemented(FEAT_SPEv1p4) then SPESampleEvents[22] = '1'; // Recent fetch end; when {PMU_EVENT_L1D_CACHE_HITM_RD, PMU_EVENT_L2D_CACHE_HITM_RD, PMU_EVENT_L3D_CACHE_HITM_RD, PMU_EVENT_LL_CACHE_HITM_RD} => if IsFeatureImplemented(FEAT_SPEv1p4) then SPESampleEvents[21] = '1'; // Modified end; when PMU_EVENT_L2D_CACHE_LMISS_RD => if IsFeatureImplemented(FEAT_SPEv1p4) then SPESampleEvents[20] = '1'; // Level 2 cache miss end; when PMU_EVENT_L2D_CACHE_RD => if IsFeatureImplemented(FEAT_SPEv1p4) then SPESampleEvents[19] = '1'; // Level 2 cache access end; when PMU_EVENT_SVE_PRED_EMPTY_SPEC => if IsFeatureImplemented(FEAT_SPEv1p1) then SPESampleEvents[18] = '1'; // Empty predicate end; when PMU_EVENT_SVE_PRED_NOT_FULL_SPEC => if IsFeatureImplemented(FEAT_SPEv1p1) then SPESampleEvents[17] = '1'; // Partial predicate end; when PMU_EVENT_LDST_ALIGN_LAT => if IsFeatureImplemented(FEAT_SPEv1p1) then SPESampleEvents[11] = '1'; // Misaligned end; when PMU_EVENT_REMOTE_ACCESS => SPESampleEvents[10] = '1'; // Remote access when PMU_EVENT_LL_CACHE_MISS => SPESampleEvents[9] = '1'; // Last level cache miss when PMU_EVENT_LL_CACHE => SPESampleEvents[8] = '1'; // Last level cache access when PMU_EVENT_BR_MIS_PRED => SPESampleEvents[7] = '1'; // Mispredicted when PMU_EVENT_BR_MIS_PRED_RETIRED => SPESampleEvents[7] = '1'; // Not taken when PMU_EVENT_DTLB_WALK => SPESampleEvents[5] = '1'; // TLB walk when PMU_EVENT_L1D_TLB => SPESampleEvents[4] = '1'; // TLB access when PMU_EVENT_L1D_CACHE_REFILL => if !IsFeatureImplemented(FEAT_SPEv1p4) then SPESampleEvents[3] = '1'; // Level 1 cache refill end; when PMU_EVENT_L1D_CACHE_LMISS_RD => if IsFeatureImplemented(FEAT_SPEv1p4) then SPESampleEvents[3] = '1'; // Level 1 cache miss end; when PMU_EVENT_L1D_CACHE => SPESampleEvents[2] = '1'; // Level 1 cache access when PMU_EVENT_INST_RETIRED => SPESampleEvents[1] = '1'; // Retired when PMU_EVENT_EXC_TAKEN => SPESampleEvents[0] = '1'; // Exception otherwise => return; end; end; end;


## Library pseudocode for aarch64/debug/statisticalprofiling/SPEFilterByDataSource

// SPEFilterByDataSource // ======================= // Carry out filtering by data source.

func SPEFilterByDataSource(optype : SPEOpType) => boolean begin // Filtering by Data Source var is_rejected_data_source : boolean = FALSE; if (IsFeatureImplemented(FEAT_SPE_FDS) && SPESampleDataSourceValid && (optype IN {SPEOpType_Load, SPEOpType_LoadAtomic})) then let data_source : bits(16) = SPESampleDataSource; let index : integer = UInt(data_source[5:0]); let is_ds : boolean = PMSDSFR_EL1()[index] == '1'; if is_ds then PMUEvent(PMU_EVENT_SAMPLE_FEED_DS); end; if PMSFCR_EL1().FDS == '1' then // Filtering by Data Source is enabled is_rejected_data_source = !is_ds; end; end; return is_rejected_data_source; end;


## Library pseudocode for aarch64/debug/statisticalprofiling/SPEFilterByEvents

// SPEFilterByEvents // =================== // Carries out filtering by the event bits.

func SPEFilterByEvents(events : bits(64)) => (boolean, boolean) begin // "mask" defines which Events packet bits are checked by the filter var mask : bits(64) = Zeros{}; let impdef_mask : bits(64) = ImpDefBits{}("SPE mask");

mask[63:48] = impdef_mask[63:48];
if IsFeatureImplemented(FEAT_SPE_SME) && IsFeatureImplemented(FEAT_SPEv1p4) then
    mask[25:24] = '11';                 // Streaming mode, SMCU
end;
if IsFeatureImplemented(FEAT_SPEv1p4) then
    mask[23:19] = '11111';              // Snoop hit, Recent fetch, Modified,
                                        // Level 2 cache miss, Level 2 cache access
else
    mask[31:24] = impdef_mask[31:24];
end;
if IsFeatureImplemented(FEAT_SPEv1p1) && IsFeatureImplemented(FEAT_SVE) then
    mask[18:17] = '11';                 // Predicates
end;
mask[15:12] = impdef_mask[15:12];
if IsFeatureImplemented(FEAT_SPEv1p1) then
    mask[11] = '1';                     // Data alignment
end;
if IsFeatureImplemented(FEAT_SPEv1p4) then
    mask[10:8] = '111';                 // Remote access, Last level cache access,
                                        // Last level cache miss
else
    mask[10:8] = impdef_mask[10:8];
end;
mask[7] = '1';                          // Mispredicted
if IsFeatureImplemented(FEAT_SPE_FnE) then
    mask[6] = '1';                      // Not taken
end;
mask[5,3,1] = '111';                    // TLB walk, Level 1 cache miss, Retired
if IsFeatureImplemented(FEAT_SPEv1p4) then
    mask[4,2] = '11';                   // TLB access, Level 1 cache access
else
    mask[4,2] = impdef_mask[4,2];
end;

let e : bits(64) = events AND mask;

// Filtering by event let evfr : bits(64) = PMSEVFR_EL1() AND mask; var is_rejected_event : boolean = FALSE; let is_evt : boolean = IsZero(NOT(e) AND evfr); if PMSFCR_EL1().FE == '1' then // Filtering by event is enabled if !IsZero(evfr) then // Not a CONSTRAINED UNPREDICTABLE case is_rejected_event = !is_evt; else is_rejected_event = ConstrainUnpredictableBool(Unpredictable_BADPMSFCR); end; end;

// Filtering by inverse event var is_rejected_nevent : boolean = FALSE; var is_nevt : boolean; if IsFeatureImplemented(FEAT_SPE_FnE) then let nevfr : bits(64) = PMSNEVFR_EL1() AND mask; is_nevt = IsZero(e AND nevfr); if PMSFCR_EL1().FnE == '1' then // Inverse filtering by event is enabled if !IsZero(nevfr) then // Not a CONSTRAINED UNPREDICTABLE case is_rejected_nevent = !is_nevt; else is_rejected_nevent = ConstrainUnpredictableBool(Unpredictable_BADPMSFCR); end; end; else is_nevt = TRUE; // not implemented end; if is_evt && is_nevt then PMUEvent(PMU_EVENT_SAMPLE_FEED_EVENT); end; if (IsFeatureImplemented(FEAT_SPE_FnE) && PMSFCR_EL1().[FnE,FE]== '11' && !IsZero(PMSEVFR_EL1() AND PMSNEVFR_EL1() AND mask)) then // CONSTRAINED UNPREDICTABLE case due to combination of filter and inverse filter is_rejected_nevent = ConstrainUnpredictableBool(Unpredictable_BADPMSFCR); is_rejected_event = ConstrainUnpredictableBool(Unpredictable_BADPMSFCR); end;

Log in to reply.