[Writeup] Shared pseudocode: part 24 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/116 ------------------------------------------------------------------------------ #136 admin, 2026-11-28 17:47 UTC [OP] Source: https://romdump.net/raw/136

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

begin if EDSCR().ERR == '1' then return; end; // Error flag set: ignore write

if EDSCR().RXfull == '1' || (Halted() && EDSCR().MA == '1'
&& EDSCR().ITE == '0') then
    EDSCR().RXO = '1';  EDSCR().ERR = '1';              // Overrun condition: ignore write
    return;
end;

EDSCR().RXfull = '1';
DTRRX          = value;

if Halted() && EDSCR().MA == '1' then
    EDSCR().ITE = '0';                                // See comments in Write_EDITR
    if () then
        ExecuteA64(0xD5330501[31:0]);               // A64 "MRS X1,DBGDTRRX_EL0"
        ExecuteA64(0xB8004401[31:0]);               // A64 "STR W1,[X0],#4"
        X{64}(1) = ARBITRARY : bits(64);
    else
        ExecuteT32(0xEE10[15:0] /*hw1*/, 0x1E15[15:0] /*hw2*/);  // T32 "MRS R1,DBGDTRRXint"
        ExecuteT32(0xF840[15:0] /*hw1*/, 0x1B04[15:0] /*hw2*/);  // T32 "STR R1,[R0],#4"
        R(1) = ARBITRARY : bits(32);
    end;
    // If the store aborts, the Data Abort exception is taken and EDSCR.ERR is set to 1
    if EDSCR().ERR == '1' then
        EDSCR().RXfull = ARBITRARY : bit;
        DBGDTRRX_EL0() = ARBITRARY : bits(64);
    else
        // "MRS X1,DBGDTRRX_EL0" calls Read_DBGDTR_EL0() which clears RXfull.
        assert EDSCR().RXfull == '0';
    end;

    EDSCR().ITE = '1';                                // See comments in Write_EDITR
end;
return;

end;


## Library pseudocode for shared/debug/dccanditr/Write\_DBGDTRTX\_EL0

// Write_DBGDTRTX_EL0 // ==================== // Called on writes to debug register 0x08C.

func Write_DBGDTRTX_EL0(memory_mapped : boolean, value : bits(32)) begin DTRTX = value; return; end;


## Library pseudocode for shared/debug/dccanditr/Write\_DBGDTR\_EL0

// Write_DBGDTR_EL0 // ================== // System register writes to DBGDTR_EL0, DBGDTRTX_EL0 (AArch64) and DBGDTRTXint (AArch32)

func Write_DBGDTR_EL0{N}(value_in : bits(N)) begin var value : bits(N) = value_in; // For MSR DBGDTRTX_EL0, N=32, value=X[t]<31:0>, X[t]<63:32> is ignored // For MSR DBGDTR_EL0, N=64, value=X[t]<63:0> assert N IN {32,64}; if EDSCR().TXfull == '1' then value = ARBITRARY : bits(N); end; // On a 64-bit write, implement a half-duplex channel if N == 64 then DTRRX = value[63:32]; end; DTRTX = value[31:0]; // 32-bit or 64-bit write EDSCR().TXfull = '1'; return; end;


## Library pseudocode for shared/debug/dccanditr/Write\_EDITR

// Write_EDITR // ============= // Called on writes to debug register 0x084.

func Write_EDITR(memory_mapped : boolean, value : bits(32)) begin if EDSCR().ERR == '1' then return; end; // Error flag set: ignore write

if () then return; end; // Non-debug state: ignore write

if EDSCR().ITE == '0' || EDSCR().MA == '1' then
    EDSCR().ITO = '1';  EDSCR().ERR = '1';      // Overrun condition: block write
    return;
end;

// ITE indicates whether the PE is ready to accept another instruction; the PE
// may support multiple outstanding instructions. Unlike the "InstrCompl" flag
in [v7A] there
// is no indication that the pipeline is empty (all instructions have
completed). In this
// pseudocode, the assumption is that only one instruction can be executed at
a time,
// meaning ITE acts like "InstrCompl".
EDSCR().ITE = '0';

if () then
    ExecuteA64(value);
else
    ExecuteT32(value[15:0]/*hw1*/, value[31:16] /*hw2*/);
end;

EDSCR().ITE = '1';

return;

end;


## Library pseudocode for shared/debug/halting/DCPSInstruction

// DCPSInstruction // ================= // Operation of the DCPS instruction in Debug state

func DCPSInstruction(target_el : bits(2)) begin

SynchronizeContext();

var handle_el : bits(2);
case target_el of
    when EL1 =>
        if PSTATE.EL == EL2 || (PSTATE.EL == EL3 && ()) then
            handle_el = PSTATE.EL;
        elsif EL2Enabled() && HCR_EL2().TGE == '1' then
            Undefined();
        else
            handle_el = EL1;
        end;
    when EL2 =>
        if (EL2) then
            Undefined();
        elsif PSTATE.EL == EL3 && () then
            handle_el = EL3;
        elsif () && CurrentSecurityState() == SS_Secure then
            Undefined();
        else
            handle_el = EL2;
        end;
    when EL3 =>
        if EDSCR().SDD == '1' || (EL3) then
            Undefined();
        else
            handle_el = EL3;
        end;
    otherwise =>
        unreachable;
end;

let from_secure : boolean = CurrentSecurityState() == SS_Secure;
if ELUsingAArch32(handle_el) then
    if PSTATE.M == M32_Monitor then SCR().NS = '0'; end;
    assert UsingAArch32();                  // Cannot move from AArch64 to AArch32
    case handle_el of
        when EL1 =>
            AArch32_WriteMode(M32_Svc);
            if IsFeatureImplemented(FEAT_PAN) && SCTLR().SPAN == '0' then
                PSTATE.PAN = '1';
            end;
        when EL2 =>  AArch32_WriteMode(M32_Hyp);
        when EL3 =>
            AArch32_WriteMode(M32_Monitor);
            if IsFeatureImplemented(FEAT_PAN) then
                if !from_secure then
                    PSTATE.PAN = '0';
                elsif SCTLR().SPAN == '0' then
                    PSTATE.PAN = '1';
                end;
            end;
    end;
    if handle_el == EL2 then
        ELR_hyp() = ARBITRARY : bits(32);  HSR() = ARBITRARY : bits(32);
    else
        LR() = ARBITRARY : bits(32);
    end;
    SPSR_curr() = ARBITRARY : bits(32);
    if handle_el == EL2 then
        PSTATE.E = HSCTLR().EE;
    else
        PSTATE.E = SCTLR().EE;
    end;
    DLR() = ARBITRARY : bits(32);  DSPSR() = ARBITRARY : bits(32);

else                                        // Targeting AArch64
    let from_32 : boolean = UsingAArch32();
    if from_32 then AArch64_MaybeZeroRegisterUppers(); end;
    if from_32 && IsFeatureImplemented(FEAT_SME) && PSTATE.SM == '1' then
        ResetSVEState();
    else
        MaybeZeroSVEUppers(target_el);
    end;
    PSTATE.nRW = '0';  PSTATE.SP = '1';  PSTATE.EL = handle_el;
    if IsFeatureImplemented(FEAT_PAN) && ((handle_el == EL1 && SCTLR_EL1().SPAN == '0') ||
                                          (handle_el == EL2 && ELIsInHost(EL0) &&
                                           SCTLR_EL2().SPAN == '0')) then
        PSTATE.PAN = '1';
    end;
    ELR_ELx() = ARBITRARY : bits(64);
    SPSR_ELx() = ARBITRARY : bits(64);
    ESR_ELx() = ARBITRARY : bits(64);
    DLR_EL0() = ARBITRARY : bits(64);  DSPSR_EL0() = ARBITRARY : bits(64);
    if IsFeatureImplemented(FEAT_UAO) then PSTATE.UAO = '0'; end;
    if IsFeatureImplemented(FEAT_MTE) then PSTATE.TCO = '1'; end;
    if IsFeatureImplemented(FEAT_GCS) then PSTATE.EXLOCK = '0'; end;
end;
if IsFeatureImplemented(FEAT_UINJ) then PSTATE.UINJ = '0'; end;
UpdateEDSCRFields();                        // Update EDSCR PE state flags
return;

end;


## Library pseudocode for shared/debug/halting/DRPSInstruction

// DRPSInstruction // ================= // Operation of the A64 DRPS and T32 ERET instructions in Debug state

func DRPSInstruction begin SynchronizeContext();

DebugRestorePSR();

return;

end;


## Library pseudocode for shared/debug/halting/DebugHalt

// DebugHalt // ========= // Reason codes for entry to Debug state

constant DebugHalt_Breakpoint : bits(6) = '000111'; constant DebugHalt_EDBGRQ : bits(6) = '010011'; constant DebugHalt_Step_Normal : bits(6) = '011011'; constant DebugHalt_Step_Exclusive : bits(6) = '011111'; constant DebugHalt_OSUnlockCatch : bits(6) = '100011'; constant DebugHalt_ResetCatch : bits(6) = '100111'; constant DebugHalt_Watchpoint : bits(6) = '101011'; constant DebugHalt_HaltInstruction : bits(6) = '101111'; constant DebugHalt_SoftwareAccess : bits(6) = '110011'; constant DebugHalt_ExceptionCatch : bits(6) = '110111'; constant DebugHalt_Step_NoSyndrome : bits(6) = '111011';


## Library pseudocode for shared/debug/halting/DebugRestorePSR

// DebugRestorePSR // =================

func DebugRestorePSR begin // PSTATE.[N,Z,C,V,Q,GE,SS,D,A,I,F] are not observable and ignored in Debug state, so // behave as if UNKNOWN. if UsingAArch32() then let spsr : bits(32) = SPSR_curr(); SetPSTATEFromPSR{32}(spsr); PSTATE.[N,Z,C,V,Q,GE,SS,A,I,F] = ARBITRARY : bits(13); // In AArch32, all instructions are T32 and unconditional. PSTATE.IT = '00000000'; PSTATE.T = '1'; // PSTATE.J is RES0 DLR() = ARBITRARY : bits(32); DSPSR() = ARBITRARY : bits(32); else let spsr : bits(64) = SPSR_ELx(); SetPSTATEFromPSR{64}(spsr); PSTATE.[N,Z,C,V,SS,D,A,I,F] = ARBITRARY : bits(9); DLR_EL0() = ARBITRARY : bits(64); DSPSR_EL0() = ARBITRARY : bits(64); end; UpdateEDSCRFields(); // Update EDSCR PE state flags end;


## Library pseudocode for
shared/debug/halting/DisableITRAndResumeInstructionPrefetch

// DisableITRAndResumeInstructionPrefetch // ========================================

impdef func DisableITRAndResumeInstructionPrefetch begin return; end;


## Library pseudocode for shared/debug/halting/ExecuteA64

// ExecuteA64 // ============ // Execute an A64 instruction in Debug state.

impdef func ExecuteA64(instr : bits(32)) begin Unimplemented(); end;


## Library pseudocode for shared/debug/halting/ExecuteT32

// ExecuteT32 // ============ // Execute a T32 instruction in Debug state.

impdef func ExecuteT32(hw1 : bits(16), hw2 : bits(16)) begin Unimplemented(); end;


## Library pseudocode for shared/debug/halting/ExitDebugState

// ExitDebugState // ================

func ExitDebugState begin assert Halted(); SynchronizeContext();

// Although EDSCR.STATUS signals that the PE is restarting,
debuggers must use EDPRSR.SDR to
// detect that the PE has restarted.
EDSCR().STATUS = '000001';                           // Signal restarting
// Clear any pending Halting debug events
if IsFeatureImplemented(FEAT_Debugv8p8) then
    EDESR()[3:0] = '0000';
else
    EDESR()[2:0] = '000';
end;

var new_pc : bits(64);
var spsr : bits(64);

if UsingAArch32() then
    new_pc = ZeroExtend{64}(DLR());
    if IsFeatureImplemented(FEAT_Debugv8p9) then
        spsr = DSPSR2() :: DSPSR();
    else
        spsr = ZeroExtend{64}(DSPSR());
    end;
else
    new_pc = DLR_EL0();
    spsr = DSPSR_EL0();
end;

let illegal_psr_state : boolean = IllegalExceptionReturn{64}(spsr);
// If this is an illegal return, SetPSTATEFromPSR() will set PSTATE.IL.
SetPSTATEFromPSR{64}(spsr); // Can update privileged bits, even at EL0

let branch_conditional : boolean = FALSE;
if UsingAArch32() then
    if ConstrainUnpredictableBool(Unpredictable_RESTARTALIGNPC) then new_pc[0] = '0'; end;
    // AArch32 branch
    BranchTo{32}(new_pc[31:0], BranchType_DBGEXIT, branch_conditional);
else
    // If targeting AArch32 then PC[63:32,1:0] might be set to UNKNOWN.
    if illegal_psr_state && spsr[4] == '1' then
        new_pc[63:32] = ARBITRARY : bits(32);
        new_pc[1:0] = ARBITRARY : bits(2);
    end;
    if IsFeatureImplemented(FEAT_BRBE) then
        BRBEDebugStateExit(AArch64_BranchAddr(new_pc,PSTATE.EL));
    end;
    // A type of branch that is never predicted
    BranchTo{64}(new_pc, BranchType_DBGEXIT, branch_conditional);
end;

 // Atomically signal restarted
EDSCR().STATUS = '000010';
EDPRSR().SDR = '1';
// End of atomically signal
EDPRSR().HALTED = '0';
UpdateEDSCRFields();                               // Stop signaling PE state
DisableITRAndResumeInstructionPrefetch();

return;

end;


## Library pseudocode for shared/debug/halting/Halt

// Halt // ======

func Halt(reason : bits(6)) begin let is_async : boolean = FALSE; let fault : FaultRecord = NoFault(); Halt(reason, is_async, fault); end;

// Halt // ======

func Halt(reason : bits(6), is_async : boolean, fault : FaultRecord) begin CTI_SignalEvent(CrossTriggerIn_CrossHalt); // Trigger other cores to halt

let preferred_restart_address : bits(64) = ThisInstrAddr{}();
var spsr : bits(64) = GetPSRFromPSTATE{64}(DebugState);

if (IsFeatureImplemented(FEAT_BTI) && !is_async &&
      ! reason IN {DebugHalt_Step_Normal, DebugHalt_Step_Exclusive,
                   DebugHalt_Step_NoSyndrome, DebugHalt_Breakpoint,
                   DebugHalt_HaltInstruction} &&
      ConstrainUnpredictableBool(Unpredictable_ZEROBTYPE)) then
    spsr[11:10] = '00';
end;

if UsingAArch32() then
    DLR() = preferred_restart_address[31:0];
    DSPSR() = spsr[31:0];
    if IsFeatureImplemented(FEAT_Debugv8p9) then
        DSPSR2() = spsr[63:32];
    end;
else
    DLR_EL0() = preferred_restart_address;
    DSPSR_EL0() = spsr;
end;
EDSCR().ITE = '1';
EDSCR().ITO = '0';
if IsFeatureImplemented(FEAT_RME) then
    if PSTATE.EL == EL3 then
        EDSCR().SDD = '0';
    else
        EDSCR().SDD = if ExternalRootInvasiveDebugEnabled() then '0' else '1';
    end;
elsif CurrentSecurityState() == SS_Secure then
    EDSCR().SDD = '0';                        // If entered in Secure state, allow debug
elsif HaveEL(EL3) then
    EDSCR().SDD = if ExternalSecureInvasiveDebugEnabled() then '0' else '1';
else
    EDSCR().SDD = '1';                        // Otherwise EDSCR.SDD is RES1
end;
EDSCR().MA = '0';

// In Debug state:
// * PSTATE.[SS,SSBS,D,A,I,F] are not observable and ignored so behave-as-if
UNKNOWN.
// * PSTATE.[N,Z,C,V,Q,GE,E,M,nRW,EL,SP,DIT] are also not observable, but
since these
// are not changed on exception entry, this function also leaves them
unchanged.
// * PSTATE.[IT,T] are ignored.
// * PSTATE.IL is ignored and behave-as-if 0.
// * PSTATE.BTYPE is ignored and behave-as-if 0.
// * PSTATE.TCO is set 1.
// * PSTATE.PACM is ignored and behave-as-if 0.
// * PSTATE.[UAO,PAN] are observable and not changed on entry into Debug
state.
// * PSTATE.UINJ is set to 0.

if UsingAArch32() then
    PSTATE.[IT,SS,SSBS,A,I,F,T] = ARBITRARY : bits(14);
else
    PSTATE.[SS,SSBS,D,A,I,F]    = ARBITRARY : bits(6);
end;

if IsFeatureImplemented(FEAT_MTE) then PSTATE.TCO = '1'; end;
if IsFeatureImplemented(FEAT_BTI) then PSTATE.BTYPE = '00'; end;
if IsFeatureImplemented(FEAT_PAuth_LR) then PSTATE.PACM = '0'; end;
PSTATE.IL = '0';
if IsFeatureImplemented(FEAT_UINJ) then PSTATE.UINJ = '0'; end;
if IsFeatureImplemented(FEAT_BRBE) then
    BRBEDebugStateEntry(preferred_restart_address);
end;
StopInstructionPrefetchAndEnableITR();
// atomic write
EDSCR().STATUS = reason;
EDPRSR().HALTED = '1';
// end of atomic write
UpdateEDSCRFields();                        // Update EDSCR PE state flags.
if IsFeatureImplemented(FEAT_EDHSR) then
    UpdateEDHSR(reason, fault);             // Update EDHSR fields.
end;
if !is_async then EndOfInstruction(EndOfInstructionReason_Exception); end;
return;

end;


## Library pseudocode for shared/debug/halting/HaltOnBreakpointOrWatchpoint

// HaltOnBreakpointOrWatchpoint // ============================== // Returns TRUE if the Breakpoint and Watchpoint debug events should be considered for Debug // state entry, FALSE if they should be considered for a debug exception.

func HaltOnBreakpointOrWatchpoint() => boolean begin return HaltingAllowed() && EDSCR().HDE == '1' && OSLSR_EL1().OSLK == '0'; end;


## Library pseudocode for shared/debug/halting/Halted

// Halted // ========

readonly func Halted() => boolean begin return ! EDSCR().STATUS IN {'000001', '000010'}; // Halted end;


## Library pseudocode for shared/debug/halting/HaltingAllowed

// HaltingAllowed // ================ // Returns TRUE if halting is currently allowed, FALSE if halting is prohibited.

func HaltingAllowed() => boolean begin if Halted() || DoubleLockStatus() then return FALSE; end; let ss : SecurityState = CurrentSecurityState(); case ss of when SS_NonSecure => return ExternalInvasiveDebugEnabled(); when SS_Secure => return ExternalSecureInvasiveDebugEnabled(); when SS_Root => return ExternalRootInvasiveDebugEnabled(); when SS_Realm => return ExternalRealmInvasiveDebugEnabled(); end; end;


## Library pseudocode for shared/debug/halting/Restarting

// Restarting // ============

readonly func Restarting() => boolean begin return EDSCR().STATUS == '000001'; // Restarting end;


## Library pseudocode for
shared/debug/halting/StopInstructionPrefetchAndEnableITR

// StopInstructionPrefetchAndEnableITR // =====================================

impdef func StopInstructionPrefetchAndEnableITR begin return; end;


## Library pseudocode for shared/debug/halting/UpdateDbgAuthStatus

// UpdateDbgAuthStatus // ===================== // Provides information about the state of the // IMPLEMENTATION DEFINED authentication interface for debug.

func UpdateDbgAuthStatus begin var nsid, nsnid : bits(2); var sid, snid : bits(2); var rlid, rtid : bits(2); if SecureOnlyImplementation() then nsid = '00'; elsif ExternalInvasiveDebugEnabled() then nsid = '11'; // Non-secure Invasive debug implemented and enabled. else nsid = '10'; // Non-secure Invasive debug implemented and disabled. end;

if SecureOnlyImplementation() then
    nsnid = '00';
elsif ExternalNoninvasiveDebugEnabled() then
    nsnid = '11';         // Non-secure Non-Invasive debug implemented and enabled.
else
    nsnid = '10';         // Non-secure Non-Invasive debug implemented and disabled.
end;

if () then
    sid = '00';
elsif ExternalSecureInvasiveDebugEnabled() then
    sid = '11';           // Secure Invasive debug implemented and enabled.
else
    sid = '10';           // Secure Invasive debug implemented and disabled.
end;

if () then
    snid = '00';
elsif ExternalSecureNoninvasiveDebugEnabled() then
    snid = '11';          // Secure Non-Invasive debug implemented and enabled.
else
    snid = '10';          // Secure Non-Invasive debug implemented and disabled.
end;

if !IsFeatureImplemented(FEAT_RME) then
    rlid = '00';
elsif ExternalRealmInvasiveDebugEnabled() then
    rlid = '11';          // Realm Invasive debug implemented and enabled.
else
    rlid = '10';          // Realm Invasive debug implemented and disabled.
end;

if !IsFeatureImplemented(FEAT_RME) then
    rtid = '00';
elsif ExternalRootInvasiveDebugEnabled() then
    rtid = '11';          // Root Invasive debug implemented and enabled.
else
    rtid = '10';          // Root Invasive debug implemented and disabled.
end;

DBGAUTHSTATUS_EL1().NSID  = nsid;
DBGAUTHSTATUS_EL1().NSNID = nsnid;
DBGAUTHSTATUS_EL1().SID   = sid;
DBGAUTHSTATUS_EL1().SNID  = snid;
DBGAUTHSTATUS_EL1().RLID  = rlid;
DBGAUTHSTATUS_EL1().RLNID = rlid; // Field has the same value as
DBGAUTHSTATUS_EL1.RLID.
DBGAUTHSTATUS_EL1().RTID  = rtid;
DBGAUTHSTATUS_EL1().RTNID = rtid; // Field has the same value as
DBGAUTHSTATUS_EL1.RTID.
return;

end;


## Library pseudocode for shared/debug/halting/UpdateEDHSR

// UpdateEDHSR // ============= // Update EDHSR watchpoint related fields.

func UpdateEDHSR(reason : bits(6), fault : FaultRecord) begin var syndrome : bits(64) = Zeros{}; if reason == DebugHalt_Watchpoint then if IsFeatureImplemented(FEAT_GCS) && fault.accessdesc.acctype == AccessType_GCS then syndrome[40] = '1'; // GCS end; syndrome[23:0] = WatchpointRelatedSyndrome(fault); if IsFeatureImplemented(FEAT_Debugv8p9) then if fault.write then syndrome[6] = '1'; end; // WnR if fault.accessdesc.acctype IN {AccessType_DC, AccessType_IC, AccessType_AT} then syndrome[8] = '1'; // CM end; if IsFeatureImplemented(FEAT_NV2) && fault.accessdesc.acctype == AccessType_NV2 then syndrome[13] = '1'; // VNCR end; end; else syndrome = ARBITRARY : bits(64); end;

EDHSR() = syndrome;

end;


## Library pseudocode for shared/debug/halting/UpdateEDSCRFields

// UpdateEDSCRFields // =================== // Update EDSCR PE state fields

func UpdateEDSCRFields begin if () then EDSCR().EL = '00'; if IsFeatureImplemented(FEAT_RME) then // SDD bit. EDSCR().SDD = if ExternalRootInvasiveDebugEnabled() then '0' else '1'; EDSCR().[NSE,NS] = ARBITRARY : bits(2); else // SDD bit. EDSCR().SDD = if ExternalSecureInvasiveDebugEnabled() then '0' else '1'; EDSCR().NS = ARBITRARY : bit; end;

    EDSCR().RW = '1111';
else
    EDSCR().EL = PSTATE.EL;
    // SError Pending.
    if EL2Enabled() && HCR_EL2().[AMO,TGE] == '10' && PSTATE.EL IN {EL0,EL1} then
        EDSCR().A = if IsVirtualSErrorPending() then '1' else '0';
    elsif (EffectiveSCR_EL3_EnDSE() == '1' && PSTATE.EL IN {EL0,EL1,EL2}) then
        EDSCR().A = if IsDelegatedSErrorPending() then '1' else '0';
    else
        EDSCR().A = if IsPhysicalSErrorPending() then '1' else '0';
    end;

    let ss : SecurityState = CurrentSecurityState();
    if IsFeatureImplemented(FEAT_RME) then
        case ss of
            when SS_Secure =>    EDSCR().[NSE,NS] = '00';
            when SS_NonSecure => EDSCR().[NSE,NS] = '01';
            when SS_Root =>      EDSCR().[NSE,NS] = '10';
            when SS_Realm =>     EDSCR().[NSE,NS] = '11';
        end;
    else
        EDSCR().NS = if ss == SS_Secure then '0' else '1';
    end;

    var RW : bits(4);
    RW[1] = if ELUsingAArch32(EL1) then '0' else '1';
    if PSTATE.EL != EL0 then
        RW[0] = RW[1];
    else
        RW[0] = if UsingAArch32() then '0' else '1';
    end;
    if () then
        RW[2] = RW[1];
    else
        RW[2] = if ELUsingAArch32(EL2) then '0' else '1';
    end;
    if (EL3) then
        RW[3] = RW[2];
    else
        RW[3] = if ELUsingAArch32(EL3) then '0' else '1';
    end;

    // The least-significant bits of EDSCR.RW are UNKNOWN if any higher EL is using AArch32.
    if RW[3] == '0' then RW[2:0] = ARBITRARY : bits(3);
    elsif RW[2] == '0' then RW[1:0] = ARBITRARY : bits(2);
    elsif RW[1] == '0' then RW[0] = ARBITRARY : bit; end;
    EDSCR().RW = RW;
end;
return;

end;


## Library pseudocode for shared/debug/haltingevents

var EDBGRQ : Signal; // Input Signal in external debug interface


## Library pseudocode for shared/debug/haltingevents/CheckEDBGRQ

// CheckEDBGRQ // ============= // Checks IMPLEMENTATION DEFINED EDBGRQ Input Signal of external debug interface. // This is an example of an IMPLEMENTATION DEFINED source of External Debug Request debug events.

func CheckEDBGRQ begin if EDBGRQ == HIGH then ExternalDebugRequest(); end; end;


## Library pseudocode for shared/debug/haltingevents/CheckExceptionCatch

// CheckExceptionCatch // ===================== // Check whether an Exception Catch debug event is set on the current Exception level

func CheckExceptionCatch(exception_entry : boolean) begin // Called after an exception entry or exit, that is, such that the Security state // and PSTATE.EL are correct for the exception target. When FEAT_Debugv8p2 // is not implemented, this function might also be called at any time. let ss : SecurityState = SecurityStateAtEL(PSTATE.EL); var base : integer;

case ss of
    when SS_Secure    => base = 0;
    when SS_NonSecure => base = 4;
    when SS_Realm     => base = 16;
    when SS_Root      => base = 0;
end;
if HaltingAllowed() then
    var halt : boolean;
    if IsFeatureImplemented(FEAT_Debugv8p2) then
        let exception_exit : boolean = !exception_entry;
        let increment : integer{} = if ss == SS_Realm then 4 else 8;
        let ctrl : bits(2) = (EDECCR()UInt([PSTATE.EL) + base + increment]::
                                EDECCR()UInt([PSTATE.EL) + base]);
        case ctrl of
            when '00' =>  halt = FALSE;
            when '01' =>  halt = TRUE;
            when '10' =>  halt = (exception_exit == TRUE);
            when '11' =>  halt = (exception_entry == TRUE);
        end;
    else
        halt = (EDECCR()UInt([PSTATE.EL) + base] == '1');
    end;

    if halt then
        if IsFeatureImplemented(FEAT_Debugv8p8) && exception_entry then
            EDESR().EC = '1';
        else
            Halt(DebugHalt_ExceptionCatch);
        end;
    end;
end;

end;


## Library pseudocode for
shared/debug/haltingevents/CheckExternalDebugRequestEvents

// CheckExternalDebugRequestEvents // ================================= // Checks for all External Debug Request debug events.

func CheckExternalDebugRequestEvents begin CheckTRBEHalt(); CheckPMUHalt(); CheckEDBGRQ(); return; end;


## Library pseudocode for shared/debug/haltingevents/CheckHaltingStep

// CheckHaltingStep // ================== // Check whether EDESR.SS has been set by Halting Step

func CheckHaltingStep(is_async : boolean) begin let step_enabled : boolean = EDECR().SS == '1' && HaltingAllowed(); let active_pending : boolean = step_enabled && EDESR().SS == '1'; if active_pending then let fault : FaultRecord = NoFault(); Halt(DebugHalt_Step_NoSyndrome, is_async, fault); end; if step_enabled then ShouldAdvanceHS = TRUE; end; return; end;


## Library pseudocode for shared/debug/haltingevents/CheckOSUnlockCatch

// CheckOSUnlockCatch // ==================== // Called on unlocking the OS Lock to pend an OS Unlock Catch debug event

func CheckOSUnlockCatch begin if ((IsFeatureImplemented(FEAT_DoPD) && CTIDEVCTL().OSUCE == '1') || (!IsFeatureImplemented(FEAT_DoPD) && EDECR().OSUCE == '1')) then if () then EDESR().OSUC = '1'; end; end; end;


## Library pseudocode for shared/debug/haltingevents/CheckPMUHalt

// CheckPMUHalt // ==============

func CheckPMUHalt begin if !IsFeatureImplemented(FEAT_Debugv8p9) || !IsFeatureImplemented(FEAT_PMUv3p9) then return; end;

// The request remains set until the condition is cleared.
// For example, an interrupt handler or cross-triggered event handler clears
// the overflow status flag by writing to PMOVSCLR_EL0

let include_r1 : boolean = TRUE;
let include_r2 : boolean = TRUE;
let include_r3 : boolean = TRUE;

let pmuhalt : boolean = CheckPMUOverflowCondition(PMUOverflowCondition_EDBGRQ,
                                                  include_r1, include_r2, include_r3);
if pmuhalt && EDECR().PME == '1' then
    ExternalDebugRequest();
end;

end;


## Library pseudocode for
shared/debug/haltingevents/CheckPendingExceptionCatch

// CheckPendingExceptionCatch // ============================ // Check whether EDESR.EC has been set by an Exception Catch debug event.

func CheckPendingExceptionCatch(is_async : boolean) begin if IsFeatureImplemented(FEAT_Debugv8p8) && HaltingAllowed() && EDESR().EC == '1' then let fault : FaultRecord = NoFault(); Halt(DebugHalt_ExceptionCatch, is_async, fault); end; end;


## Library pseudocode for shared/debug/haltingevents/CheckPendingOSUnlockCatch

// CheckPendingOSUnlockCatch // =========================== // Check whether EDESR.OSUC has been set by an OS Unlock Catch debug event

func CheckPendingOSUnlockCatch begin if HaltingAllowed() && EDESR().OSUC == '1' then let is_async : boolean = TRUE; let fault : FaultRecord = NoFault(); Halt(DebugHalt_OSUnlockCatch, is_async, fault); end; end;


## Library pseudocode for shared/debug/haltingevents/CheckPendingResetCatch

// CheckPendingResetCatch // ======================== // Check whether EDESR.RC has been set by a Reset Catch debug event

func CheckPendingResetCatch begin if HaltingAllowed() && EDESR().RC == '1' then let is_async : boolean = TRUE; let fault : FaultRecord = NoFault(); Halt(DebugHalt_ResetCatch, is_async, fault); end; end;


## Library pseudocode for shared/debug/haltingevents/CheckResetCatch

// CheckResetCatch // ================= // Called after reset

func CheckResetCatch begin if ((IsFeatureImplemented(FEAT_DoPD) && CTIDEVCTL().RCE == '1') || (!IsFeatureImplemented(FEAT_DoPD) && EDECR().RCE == '1')) then EDESR().RC = '1'; // If halting is allowed then halt immediately if HaltingAllowed() then Halt(DebugHalt_ResetCatch); end; end; end;


## Library pseudocode for
shared/debug/haltingevents/CheckSoftwareAccessToDebugRegisters

// CheckSoftwareAccessToDebugRegisters // ===================================== // Check for access to Breakpoint and Watchpoint registers.

func CheckSoftwareAccessToDebugRegisters begin let os_lock : bit = (if ELUsingAArch32(EL1) then DBGOSLSR().OSLK else OSLSR_EL1().OSLK); if HaltingAllowed() && EDSCR().TDA == '1' && os_lock == '0' then Halt(DebugHalt_SoftwareAccess); end; end;


## Library pseudocode for shared/debug/haltingevents/CheckTRBEHalt

// CheckTRBEHalt // ===============

func CheckTRBEHalt begin if !IsFeatureImplemented(FEAT_Debugv8p9) || !IsFeatureImplemented(FEAT_TRBE_EXT) then return; end;

if TraceBufferEnabled() && TRBSR_EL1().IRQ == '1'
&& EDECR().TRBE == '1' then
    ExternalDebugRequest();
end;

end;


## Library pseudocode for shared/debug/haltingevents/ExternalDebugRequest

// ExternalDebugRequest // ======================

func ExternalDebugRequest begin if HaltingAllowed() then let is_async : boolean = TRUE; let fault : FaultRecord = NoFault(); Halt(DebugHalt_EDBGRQ, is_async, fault); // Otherwise the CTI continues to assert the debug request until it is taken. end; end;


## Library pseudocode for shared/debug/haltingevents/HSAdvance

// HSAdvance // =========== // Advance the Halting Step State Machine

func HSAdvance begin if then return; end; let step_enabled : boolean = EDECR().SS == '1' && HaltingAllowed(); let active_not_pending : boolean = step_enabled && EDESR().SS == '0'; if active_not_pending then EDESR().SS = '1'; end; // set as pending. ShouldAdvanceHS = FALSE; return; end;


## Library pseudocode for
shared/debug/interrupts/ExternalDebugInterruptsDisabled

// ExternalDebugInterruptsDisabled // ================================= // Determine whether EDSCR disables interrupts routed to 'target'.

func ExternalDebugInterruptsDisabled(target : bits(2)) => boolean begin var int_dis : boolean; let ss : SecurityState = SecurityStateAtEL(target); if IsFeatureImplemented(FEAT_Debugv8p4) then if EDSCR().INTdis[0] == '1' then case ss of when SS_NonSecure => int_dis = ExternalInvasiveDebugEnabled(); when SS_Secure => int_dis = ExternalSecureInvasiveDebugEnabled(); when SS_Realm => int_dis = ExternalRealmInvasiveDebugEnabled(); when SS_Root => int_dis = ExternalRootInvasiveDebugEnabled(); end; else int_dis = FALSE; end; else case target of when EL3 => int_dis = (EDSCR().INTdis == '11' && ExternalSecureInvasiveDebugEnabled()); when EL2 => int_dis = (EDSCR().INTdis == '1x' && ExternalInvasiveDebugEnabled()); when EL1 => if ss == SS_Secure then int_dis = (EDSCR().INTdis == '1x' && ExternalSecureInvasiveDebugEnabled()); else int_dis = (EDSCR().INTdis != '00' && ExternalInvasiveDebugEnabled()); end; end; end; return int_dis; end;


## Library pseudocode for shared/debug/pmu

var PMUEventAccumulator : array [[31]] of integer; // Accumulates PMU events for a cycle var PMULastThresholdValue : array [[31]] of boolean; // A record of the threshold result for each // event counter on the previous cycle

// Constant used in PMU functions to represent actions on the cycle counter. constant CYCLE_COUNTER_ID : integer = 31; // Constant used in PMU functions to represent actions on the instruction counter. constant INSTRUCTION_COUNTER_ID : integer = 32;


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

// ApplyPMUZeroMask // ================== // Zero the set of counters specified by the mask in 'masked_val'. // 'masked_val' is expected to already be masked for the permitted counters for the current // access type before this function is called.

func ApplyPMUZeroMask(masked_val : bits(64)) begin for idx = 0 to 63 do if masked_val[idx] == '1' then case idx of when INSTRUCTION_COUNTER_ID => PMICNTR_EL0() = Zeros{64}; when CYCLE_COUNTER_ID => if () then PMCCNTR() = Zeros{64}; else PMCCNTR_EL0() = Zeros{64}; end; otherwise => if () then PMEVCNTR(idx) = Zeros{32}; elsif IsFeatureImplemented(FEAT_PMUv3p5) then PMEVCNTR_EL0(idx) = Zeros{64}; else PMEVCNTR_EL0(idx)[31:0] = Zeros{32}; end; end; end; end;

return;

end;


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

// CheckForPMUOverflow // ===================== // Called before each instruction is executed. // If a PMU event counter has overflowed, this function might do any of: // - Signal a Performance Monitors overflow interrupt request. // - Signal a CTI Performance Monitors overflow event. // - Generate an External Debug Request debug event. // - Generate a BRBE freeze event.

func CheckForPMUOverflow begin let include_r1 : boolean = TRUE; let include_r2 : boolean = TRUE; let include_r3 : boolean = TRUE;

let enabled : boolean = PMUInterruptEnabled();
let pmuirq : boolean = CheckPMUOverflowCondition(PMUOverflowCondition_IRQ,
                                                 include_r1, include_r2, include_r3);

SetInterruptRequestLevel(InterruptID_PMUIRQ,
                         if enabled && pmuirq then HIGH else LOW);
CTI_SetEventLevel(CrossTriggerIn_PMUOverflow,
                  if pmuirq then HIGH else LOW);

if ShouldBRBEFreeze() then
    BRBEFreeze();
end;

return;

end;


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

// CheckPMUOverflowCondition // =========================== // Checks for PMU overflow under certain parameter conditions described by 'reason'. // If 'include_r1' is TRUE, then check counters in the range [0..(HPMN-1)], CCNTR // and ICNTR, unless excluded by 'reason'. // If 'include_r2' is TRUE, then check counters in the range [HPMN..(EPMN-1)]. // If 'include_r3' is TRUE, then check counters in the range [EPMN..(N-1)].

func CheckPMUOverflowCondition(reason : PMUOverflowCondition, include_r1 : boolean, include_r2 : boolean, include_r3 : boolean ) => boolean begin // 'reason' is decoded into a further set of parameters: // If 'check_e' is TRUE, then check the applicable one of PMCR_EL0.E and MDCR_EL2.HPME. // If 'check_inten' is TRUE, then check the applicable PMINTENCLR_EL1 bit. // If 'exclude_cyc' is TRUE, then CCNTR is NOT checked. var check_e : boolean; var check_inten : boolean; var exclude_cyc : boolean; case reason of when PMUOverflowCondition_PMUException => check_e = TRUE; check_inten = TRUE; exclude_cyc = FALSE; when PMUOverflowCondition_BRBEFreeze => check_e = FALSE; check_inten = FALSE; exclude_cyc = TRUE; when PMUOverflowCondition_Freeze => check_e = FALSE; check_inten = FALSE; exclude_cyc = TRUE; when PMUOverflowCondition_IRQ, PMUOverflowCondition_EDBGRQ => check_e = TRUE; check_inten = TRUE; exclude_cyc = FALSE; otherwise => unreachable; end;

var ovsf : bits(64);

if HaveAArch64() then
    ovsf = PMOVSSET_EL0();
    ovsf[63:33] = Zeros{31};
    if !IsFeatureImplemented(FEAT_PMUv3_ICNTR) then
        ovsf[INSTRUCTION_COUNTER_ID] = '0';
    end;
else
    ovsf = ZeroExtend{64}(PMOVSSET());
end;

let counters : integer{} = NUM_PMU_COUNTERS;
// Remove unimplemented counters - these fields are RES0
if counters < 31 then
    ovsf[30:counters] = Zeros{31-counters};
end;

for idx = 0 to counters - 1 do
    var global_en : bit;
    case GetPMUCounterRange(idx) of
        when PMUCounterRange_R1 =>
            global_en = if HaveAArch64() then PMCR_EL0().E else PMCR().E;
            if !include_r1 then
                ovsf[idx] = '0';
            end;
        when PMUCounterRange_R2 =>
            global_en = if HaveAArch64() then MDCR_EL2().HPME else HDCR().HPME;
            if !include_r2 then
                ovsf[idx] = '0';
            end;
        when PMUCounterRange_R3 =>
            global_en = PMCCR().EPME;
            if !include_r3 then
                ovsf[idx] = '0';
            end;
        otherwise =>
            unreachable;
    end;
    if check_e then
        ovsf[idx] = ovsf[idx] AND global_en;
    end;
end;

// Cycle counter
if exclude_cyc || !include_r1 then
    ovsf[CYCLE_COUNTER_ID] = '0';
end;

if check_e then
    ovsf[CYCLE_COUNTER_ID] = ovsf[CYCLE_COUNTER_ID] AND PMCR_EL0().E;
end;

// Instruction counter
if HaveAArch64() && IsFeatureImplemented(FEAT_PMUv3_ICNTR) then
    if !include_r1 then
        ovsf[INSTRUCTION_COUNTER_ID] = '0';
    end;
    if check_e then
        ovsf[INSTRUCTION_COUNTER_ID] = ovsf[INSTRUCTION_COUNTER_ID] AND PMCR_EL0().E;
    end;
end;

if check_inten then
    let inten : bits(64) = (if HaveAArch64() then PMINTENCLR_EL1
                               else ZeroExtend{64}(PMINTENCLR()));
    ovsf = ovsf AND inten;
end;

return !IsZero(ovsf);

end;


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

// CountPMUEvents // ================ // Return TRUE if counter "idx" should count its event. // For the cycle counter, idx == CYCLE_COUNTER_ID (31). // For the instruction counter, idx == INSTRUCTION_COUNTER_ID (32).

func CountPMUEvents(idx : integer) => boolean begin let counters : integer = NUM_PMU_COUNTERS; assert (idx == CYCLE_COUNTER_ID || idx < counters || (idx == INSTRUCTION_COUNTER_ID && IsFeatureImplemented(FEAT_PMUv3_ICNTR)));

var debug : boolean;
var enabled : boolean;
var prohibited : boolean;
var filtered : boolean;
var frozen : boolean;

// Event counting is disabled in Debug state
debug = Halted();

// Software can reserve some counters
let counter_range : PMUCounterRange = GetPMUCounterRange(idx);
var ss : SecurityState = CurrentSecurityState();

// Main enable controls
var global_en : bit;
var counter_en : bit;
case counter_range of
    when PMUCounterRange_R1 =>
        global_en = if HaveAArch64() then PMCR_EL0().E else PMCR().E;
    when PMUCounterRange_R2 =>
        global_en = if HaveAArch64() then MDCR_EL2().HPME else HDCR().HPME;
    when PMUCounterRange_R3 =>
        assert IsFeatureImplemented(FEAT_PMUv3_EXTPMN);
        global_en = PMCCR().EPME;
    otherwise =>
        unreachable;
end;

case idx of
    when INSTRUCTION_COUNTER_ID =>
        assert HaveAArch64();
        counter_en = PMCNTENSET_EL0().F0;
    when CYCLE_COUNTER_ID =>
        counter_en = if HaveAArch64() then PMCNTENSET_EL0().C else PMCNTENSET().C;
    otherwise =>
        counter_en = if HaveAArch64() then PMCNTENSET_EL0()[idx] else PMCNTENSET()[idx];
end;

enabled = global_en == '1' && counter_en == '1';

// Event counting is allowed unless it is prohibited by any rule below
prohibited = FALSE;

// Event counting in Secure state or at EL3 is prohibited if all of:
// * EL3 is implemented
// * One of the following is true:
//   - EL3 is using AArch64, MDCR_EL3.SPME == 0, and either:
//     - FEAT_PMUv3p7 is not implemented
//     - MDCR_EL3.MPMX == 0
//   - EL3 is using AArch32 and SDCR.SPME == 0
// * Either not executing at EL0 using AArch32, or one of the following is
true:
//     - EL3 is using AArch32 and SDER.SUNIDEN == 0
// - EL3 is using AArch64, EL1 is using AArch32, and SDER32_EL3.SUNIDEN == 0
// * PMNx is not reserved for use by the external interface
if (HaveEL(EL3) && (ss == SS_Secure || PSTATE.EL == EL3) &&
      counter_range != PMUCounterRange_R3) then
    if (EL3) then
        prohibited = (MDCR_EL3().SPME == '0' &&
                      (!IsFeatureImplemented(FEAT_PMUv3p7) || MDCR_EL3().MPMX == '0'));
    else
        prohibited = SDCR().SPME == '0';
    end;

    if prohibited && PSTATE.EL == EL0 then
        if ELUsingAArch32(EL3) then
            prohibited = SDER().SUNIDEN == '0';
        elsif ELUsingAArch32(EL1) then
            prohibited = SDER32_EL3().SUNIDEN == '0';
        end;
    end;
end;

// Event counting at EL3 is prohibited if all of:
// * FEAT_PMUv3p7 is implemented
// * EL3 is using AArch64
// * One of the following is true:
//   - MDCR_EL3.SPME == 0
//   - PMNx is not reserved for EL2
// * MDCR_EL3.MPMX == 1
// * PMNx is not reserved for use by the external interface
if (!prohibited && IsFeatureImplemented(FEAT_PMUv3p7) &&
PSTATE.EL == EL3 &&
      HaveAArch64() && counter_range != PMUCounterRange_R3) then
    prohibited = (MDCR_EL3().MPMX == '1' &&
                  (MDCR_EL3().SPME == '0' || counter_range == PMUCounterRange_R1));
end;

// Event counting at EL2 is prohibited if all of:
// * FEAT_PMUv3p1 is implemented
// * PMNx is not reserved for EL2 or the external interface
// * EL2 is using AArch64 and MDCR_EL2.HPMD == 1, or EL2 is using AArch32 and
HDCR.HPMD == 1
if (!prohibited && PSTATE.EL == EL2 &&
IsFeatureImplemented(FEAT_PMUv3p1) &&
      counter_range == PMUCounterRange_R1) then
    let hpmd : bit = if HaveAArch64() then MDCR_EL2().HPMD else HDCR().HPMD;
    prohibited = hpmd == '1';
end;

// The IMPLEMENTATION DEFINED authentication interface might override software
if prohibited && !IsFeatureImplemented(FEAT_Debugv8p2) then
    prohibited = ();
end;

// If FEAT_PMUv3p7 is implemented, event counting can be frozen
if IsFeatureImplemented(FEAT_PMUv3p7) then
    var fz : bit;
    case counter_range of
        when PMUCounterRange_R1 =>
            fz = if HaveAArch64() then PMCR_EL0().FZO else PMCR().FZO;
        when PMUCounterRange_R2 =>
            fz = if HaveAArch64() then MDCR_EL2().HPMFZO else HDCR().HPMFZO;
        when PMUCounterRange_R3 =>
            fz = '0';
        otherwise =>
            unreachable;
    end;
    frozen = (fz == '1') && ShouldPMUFreeze(counter_range);
    frozen = frozen || SPEFreezeOnEvent(idx);
else
    frozen = FALSE;
end;

// PMCR_EL0.DP or PMCR.DP disables the cycle counter when event counting is
prohibited
// or frozen
if (prohibited || frozen) && idx == CYCLE_COUNTER_ID then
    let dp : bit = if HaveAArch64() then PMCR_EL0().DP else PMCR().DP;
    enabled = enabled && dp == '0';
    // Otherwise whether event counting is prohibited or frozen does not affect the cycle
    // counter
    prohibited = FALSE;
    frozen = FALSE;
end;

// If FEAT_PMUv3p5 is implemented, cycle counting can be prohibited.
// This is not overridden by PMCR_EL0.DP.
if IsFeatureImplemented(FEAT_PMUv3p5) && idx == CYCLE_COUNTER_ID then
    if HaveEL(EL3) && (ss == SS_Secure || PSTATE.EL == EL3) then
        let sccd = if HaveAArch64() then MDCR_EL3().SCCD else SDCR().SCCD;
        if sccd == '1' then
            prohibited = TRUE;
        end;
    end;

    if PSTATE.EL == EL2 then
        let hccd = if HaveAArch64() then MDCR_EL2().HCCD else HDCR().HCCD;
        if hccd == '1' then
            prohibited = TRUE;
        end;
    end;
end;

// If FEAT_PMUv3p7 is implemented, cycle counting an be prohibited at EL3.
// This is not overridden by PMCR_EL0.DP.
if IsFeatureImplemented(FEAT_PMUv3p7) && idx == CYCLE_COUNTER_ID then
    if PSTATE.EL == EL3 && HaveAArch64() && MDCR_EL3().MCCD == '1' then
        prohibited = TRUE;
    end;
end;

// Event counting can be filtered by the {P, U, NSK, NSU, NSH, M, SH, RLK,
RLU, RLH} bits
var filter : bits(32);
case idx of
    when INSTRUCTION_COUNTER_ID =>
        filter = PMICFILTR_EL0()[31:0];
    when CYCLE_COUNTER_ID =>
        filter = if HaveAArch64() then PMCCFILTR_EL0()[31:0] else PMCCFILTR();
    otherwise =>
        filter = if HaveAArch64() then PMEVTYPER_EL0(idx)[31:0] else PMEVTYPER(idx);
end;

let p : bit   = filter[31];
let u : bit   = filter[30];
let nsk : bit = if HaveEL(EL3) then filter[29] else '0';
let nsu : bit = if HaveEL(EL3) then filter[28] else '0';
let nsh : bit = if HaveEL(EL2) then filter[27] else '0';
let m : bit = if HaveEL(EL3) && HaveAArch64() then filter[26] else
'0';
let sh : bit = if HaveEL(EL3) && IsFeatureImplemented(FEAT_SEL2) then
filter[24] else '0';
let rlk : bit = if IsFeatureImplemented(FEAT_RME) then filter[22] else '0';
let rlu : bit = if IsFeatureImplemented(FEAT_RME) then filter[21] else '0';
let rlh : bit = if IsFeatureImplemented(FEAT_RME) then filter[20] else '0';

ss = CurrentSecurityState();
case PSTATE.EL of
    when EL0 =>
        case ss of
            when SS_NonSecure => filtered = u != nsu;
            when SS_Secure =>    filtered = u == '1';
            when SS_Realm =>     filtered = u != rlu;
        end;
    when EL1 =>
        case ss of
            when SS_NonSecure => filtered = p != nsk;
            when SS_Secure =>    filtered = p == '1';
            when SS_Realm =>     filtered = p != rlk;
        end;
    when EL2 =>
        case ss of
            when SS_NonSecure => filtered = nsh == '0';
            when SS_Secure =>    filtered = nsh == sh;
            when SS_Realm =>     filtered = nsh == rlh;
        end;
    when EL3 =>
        if HaveAArch64() then
            filtered = m != p;
        else
            filtered = p == '1';
        end;
end;

if IsFeatureImplemented(FEAT_PMUv3_SME) then
    let is_streaming_mode : boolean = PSTATE.SM == '1';
    var vs : bits(2);
    case idx of
        when INSTRUCTION_COUNTER_ID =>
            vs = PMICFILTR_EL0().VS;
        when CYCLE_COUNTER_ID =>
            vs = PMCCFILTR_EL0().VS;
        otherwise =>
            vs = PMEVTYPER_EL0(idx).VS;
    end;

    var streaming_mode_filtered : boolean;
    if vs == '11' then
        streaming_mode_filtered = ConstrainUnpredictableBool(Unpredictable_RES_PMU_VS);
    else
        streaming_mode_filtered =  ((is_streaming_mode && vs[0] == '1') ||
                                    (!is_streaming_mode && vs[1] == '1'));
    end;

    filtered = filtered || streaming_mode_filtered;
end;

return !debug && enabled && !prohibited && !filtered
&& !frozen;

end;


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

// EffectiveEPMN // =============== // Returns the Effective value of PMCCR.EPMN.

func EffectiveEPMN() => bits(5) begin let counters : integer = NUM_PMU_COUNTERS; var epmn_bits : bits(5);

if IsFeatureImplemented(FEAT_PMUv3_EXTPMN) then
    epmn_bits = PMCCR().EPMN;
    if UInt(epmn_bits) > counters then
        (-, epmn_bits) = ConstrainUnpredictableBits{5}(Unpredictable_RES_EPMN);
    end;
else
    epmn_bits = counters[4:0];
end;

return epmn_bits;

end;


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

// EffectiveHPMN // =============== // Returns the Effective value of MDCR_EL2.HPMN or HDCR.HPMN.

func EffectiveHPMN() => bits(5) begin let counters : integer = UInt(EffectiveEPMN()); var hpmn_bits : bits(5);

if HaveEL(EL2) then // Software can reserve some event counters for
EL2
    hpmn_bits = if HaveAArch64() then MDCR_EL2().HPMN else HDCR().HPMN;

    // When FEAT_PMUv3_EXTPMN is implemented, out of range values are capped.
    if UInt(hpmn_bits) > counters && IsFeatureImplemented(FEAT_PMUv3_EXTPMN) then
        hpmn_bits = counters[4:0];
    end;

    if (UInt(hpmn_bits) > counters ||
          (!IsFeatureImplemented(FEAT_HPMN0) && IsZero(hpmn_bits))) then
        (-, hpmn_bits) = ConstrainUnpredictableBits{5}(Unpredictable_RES_HPMN);
    end;
else
    hpmn_bits = counters[4:0];
end;

return hpmn_bits;

end;


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

// ExtRegGetPMUAccessMask // ======================== // Return a mask of the PMU counters accessible via external PMU access.

func ExtRegGetPMUAccessMask(addrdesc : AddressDescriptor) => bits(64) begin var mask : bits(64) = Zeros{};

if IsFeatureImplemented(FEAT_PMUv3_ICNTR) then
    mask[INSTRUCTION_COUNTER_ID] = '1';
end;

mask[CYCLE_COUNTER_ID] = '1';

let counters : integer{} = (if (IsFeatureImplemented(FEAT_PMUv3_EXTPMN)
&&
                                 (addrdesc)) then UInt(EffectiveEPMN())
                            else NUM_PMU_COUNTERS);

if counters > 0 then
    mask[counters-1:0] = Ones{counters};
end;

return mask;

end;


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

// ExtRegZeroCycleCounter // ======================== // Called on an external PMU write to PMCR_EL0 that writes '1' to PMCR_EL0.C.

func ExtRegZeroCycleCounter(addrdesc : AddressDescriptor) begin var mask : bits(64) = Zeros{}; mask[CYCLE_COUNTER_ID] = '1'; ExtRegZeroPMUCounters(mask, addrdesc); end;


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

// ExtRegZeroEventCounters // ========================== // Zero all the event counters. // Called on an external PMU write to PMCR_EL0 that writes '1' to PMCR_EL0.P.

func ExtRegZeroEventCounters(addrdesc : AddressDescriptor) begin ExtRegZeroPMUCounters(Zeros{33} :: Ones{31}, addrdesc); end;


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

// ExtRegZeroPMUCounters // ========================= // Zero set of counters specified by the mask in 'val', for external PMU access.

func ExtRegZeroPMUCounters(val : bits(64), addrdesc : AddressDescriptor) begin let masked_val : bits(64) = val AND ExtRegGetPMUAccessMask(addrdesc); ApplyPMUZeroMask(masked_val); return; end;


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

// GetNumEventCountersAccessible // =============================== // Return the number of event counters that can be accessed at the current Exception level.

func GetNumEventCountersAccessible() => integer{0..NUM_PMU_COUNTERS} begin var n : integer;

// Software can reserve some counters for EL2
if PSTATE.EL IN {EL1, EL0} && EL2Enabled() then
    n = UInt(EffectiveHPMN());
else
    n = UInt(EffectiveEPMN());
end;

return n as integer{0..NUM_PMU_COUNTERS};

end;


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

// GetNumEventCountersSelfHosted // =============================== // Return the number of event counters that can be accessed by the Self-hosted software.

func GetNumEventCountersSelfHosted() => integer begin if IsFeatureImplemented(FEAT_PMUv3_EXTPMN) then return UInt(EffectiveEPMN()); else return NUM_PMU_COUNTERS; end; end;


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

// GetPMUCounterRange // ==================== // Returns the range that a counter is currently in.

func GetPMUCounterRange(n : integer) => PMUCounterRange begin

let counters : integer = NUM_PMU_COUNTERS;
let epmn : integer = UInt(EffectiveEPMN());
let hpmn : integer = UInt(EffectiveHPMN());

if n < hpmn then
    return PMUCounterRange_R1;
elsif n < epmn then
    return PMUCounterRange_R2;
elsif n < counters then
    assert IsFeatureImplemented(FEAT_PMUv3_EXTPMN);
    return PMUCounterRange_R3;
elsif n == CYCLE_COUNTER_ID then
------------------------------------------------------------------------------ Page 1 of 1. End of thread.