check_emulated_instr() presets each counter to -N, N being the expected number of instructions or branches, and computes the number of counted events as "count - start", where start is -N as a 64-bit value. That only works if the counter wraps. The counter is only gp_counter_width bits wide, so if it counts fewer than N events, it reads back as a large positive value (2^width - N + delta), and the 64-bit subtraction yields 2^width + delta instead of delta. E.g. a 48-bit counter preset to -22 that counts only 10 events reads back as 0xfffffffffff4, and the difference is 0x100000000000a instead of 10. The "==" checks still fail in this case, but the ">=" checks, used without GLOBAL_CTRL and on CPUs with the instructions/branches retired overcount errata (i.e. all AMD CPUs), pass even though the counter didn't count the expected number of events. Mask the differences to the counter width, so that a counter that didn't count the expected number of events fails the ">=" checks. Fixes: 20cf91472daa ("x86/pmu: Test PMU virtualization on emulated instructions") Signed-off-by: Yosry Ahmed --- x86/pmu.c | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/x86/pmu.c b/x86/pmu.c index a54eb3843621c..db4198c2b64ae 100644 --- a/x86/pmu.c +++ b/x86/pmu.c @@ -736,7 +736,7 @@ static void check_running_counter_wrmsr(void) static void check_emulated_instr(void) { u32 eax, edx, ecx; - uint64_t status, instr_start, brnch_start; + uint64_t status, instr_start, brnch_start, instr_delta, brnch_delta; uint64_t gp_counter_width = (1ull << pmu.gp_counter_width) - 1; unsigned int branch_idx = pmu.is_intel ? INTEL_BRANCHES_IDX : AMD_BRANCHES_IDX; @@ -782,17 +782,20 @@ static void check_emulated_instr(void) __stop_event(&brnch_cnt); __stop_event(&instr_cnt); + instr_delta = (instr_cnt.count - instr_start) & gp_counter_width; + brnch_delta = (brnch_cnt.count - brnch_start) & gp_counter_width; + // Check that the end count - start count is at least the expected // number of instructions and branches. if (has_perf_global_ctrl && !pmu.errata.instructions_retired_overcount) - report(instr_cnt.count - instr_start == KVM_FEP_INSNS, "instruction count"); + report(instr_delta == KVM_FEP_INSNS, "instruction count"); else - report(instr_cnt.count - instr_start >= KVM_FEP_INSNS, "instruction count"); + report(instr_delta >= KVM_FEP_INSNS, "instruction count"); if (has_perf_global_ctrl && !pmu.errata.branches_retired_overcount) - report(brnch_cnt.count - brnch_start == KVM_FEP_BRANCHES, "branch count"); + report(brnch_delta == KVM_FEP_BRANCHES, "branch count"); else - report(brnch_cnt.count - brnch_start >= KVM_FEP_BRANCHES, "branch count"); + report(brnch_delta >= KVM_FEP_BRANCHES, "branch count"); if (this_cpu_has_perf_global_status()) { // Additionally check that those counters overflowed properly. -- 2.56.1.911.g883d8bcb20-goog