[PATCH v6 2/3] perf/arm64: Add BRBE support for bpf_get_branch_snapshot()
James Clark
james.clark at linaro.org
Fri Nov 27 02:56:58 PST 2026
On 26/11/2026 17:19, Leo Yan wrote:
> On Mon, Aug 10, 2026 at 09:46:19AM -0700, Puranjay Mohan wrote:
>
> [...]
>
>> +int brbe_snapshot_branch_stack(struct perf_branch_entry *entries, unsigned int cnt)
>> +{
>> + u64 brbidr, brbfcr, brbcr, pmcr;
>> + int nr_hw, nr_copied = 0;
>> + bool paused_here = false;
>> + unsigned long flags;
>> +
>> + /* Called with migration disabled, so this is the CPU read below. */
>> + if (!valid_brbe_version())
>> + return 0;
>> +
>> + flags = raw_local_daif_save();
>> +
>> + brbcr = read_sysreg_s(SYS_BRBCR_EL1);
>> + brbfcr = read_sysreg_s(SYS_BRBFCR_EL1);
>> +
>> + /*
>> + * PAUSED is only ever set behind our back, so finding it set is final.
>> + * likely() keeps this inline; a taken branch costs a record.
>> + */
>> + if (likely(brbcr && !(brbfcr & BRBFCR_EL1_PAUSED))) {
>> + /*
>> + * Stop the counters so a freeze cannot set PAUSED behind the
>> + * value read below; the D19.3 conditions need a PMOVSCLR_EL0
>> + * bit, which a stopped counter cannot set.
>> + */
>> + pmcr = read_pmcr();
>> + write_pmcr(pmcr & ~ARMV8_PMU_PMCR_E);
>> + isb();
>> +
>> + brbfcr = read_sysreg_s(SYS_BRBFCR_EL1);
>> + paused_here = !(brbfcr & BRBFCR_EL1_PAUSED);
>> +
>> + write_sysreg_s(brbfcr | BRBFCR_EL1_PAUSED, SYS_BRBFCR_EL1);
>> + isb();
>> + }
>
> AI pointed out a edge case:
>
> 1) The PMU is enabled (PMCR_EL0.E=1). The first BRBFCR_EL1 read
> observes PAUSED=0.
> 2) A counter overflows and hardware freezes BRBE before the helper
> stops the counters. This can happen while interrupt is masked.
> 3) The helper saves PMCR_EL0 and clears PMCR_E. Its second BRBFCR_EL1
> read observes PAUSED=1, so paused_here becomes false.
> 4) The only write restoring the saved PMCR_EL0 is inside
> "if (paused_here)". The helper therefore returns with PMCR_EL0.E=0.
>
> This can happen with a normal PMU IRQ because hardware can freeze BRBE
> while local IRQs are masked.
>
Nice catch. This can be fixed by adding 'pmcr_saved' in addition to
'paused_here'. So 'pmcr_saved' would always always be set if the
likely-not-paused branch is true, and then 'paused_here' is still set
from the second read of BRBFCR.
Then on exit they are both treated separately. 'paused_here' invalidates
and unpauses again but 'pmcr_saved' can control restoring PMCR.
>> + trace_hardirqs_off();
>
> The irqsoff tracer misses the time between raw_local_daif_save() and
> this call. Other callers could introduce similar gaps by using the raw
> helper.
>
> I'll reply separately on the pNMI / NMI cases with an approach that
> may avoid adding the raw helpers.
And that other approach also avoids having to disable the PMU counters
so avoids the edge case above.
>
> Thanks,
> Leo
More information about the linux-arm-kernel
mailing list