Re: [PATCH v10 18/18] KVM: selftests: Add Topdown PERF_METRICS test
From: Chen, Zide
Date: Tue Dec 01 2026 - 13:22:10 EST
On 12/1/2026 3:35 AM, Mi, Dapeng wrote:
>> diff --git a/tools/testing/selftests/kvm/x86/pmu_perf_metrics_test.c b/tools/testing/selftests/kvm/x86/pmu_perf_metrics_test.c
>> new file mode 100644
>> index 000000000000..07a6c948e4cd
>> --- /dev/null
>> +++ b/tools/testing/selftests/kvm/x86/pmu_perf_metrics_test.c
>> @@ -0,0 +1,391 @@
>> +// SPDX-License-Identifier: GPL-2.0-only
>> +/*
>> + * Test for KVM Topdown Microarchitecture Analysis (TMA) and PERF_METRICS.
>> + *
>> + * Copyright (C) 2026, Intel Corporation
>> + */
>> +
>> +#include <linux/bitfield.h>
>> +
>> +#include "processor.h"
>> +#include "pmu.h"
>> +
>> +/* Number of iterations of the loop for the guest measurement payload. */
>> +#define NUM_LOOPS 10
>> +#define PERF_METRICS_TEST_VAL 0x12345678ULL
>
> The sum of 4 metric fields is 0x114, which is far away from 0xff. Could we
> change it to an available value?
Nice catch!
While WRMSR does not enforce the arithmetic sum of the Level-1
metric fields (only validating reserved bits), using an architecturally
valid value whose Level-1 metrics sum to 0xff avoids confusion.
I will update it to 0x12345663ULL (0x12 + 0x34 + 0x56 + 0x63 == 0xff).
>> +#define SLOTS_TEST_VAL 0x12345ULL
>> +
>> +static void guest_test_rdpmc(u32 rdpmc_idx, bool expect_success, u64 expected_val)
>> +{
>> + u8 vector;
>> + u64 val;
>> +
>> + vector = rdpmc_safe(rdpmc_idx, &val);
>> + __GUEST_ASSERT(expect_success ? !vector : vector == GP_VECTOR,
>> + "Expected %s on RDPMC(0x%x), got %s",
>> + expect_success ? "no fault" : "#GP", rdpmc_idx, ex_str(vector));
>> + if (expect_success)
>> + GUEST_ASSERT_EQ(val, expected_val);
>> +
>> + if (!is_forced_emulation_enabled)
>> + return;
>> +
>> + vector = rdpmc_safe_fep(rdpmc_idx, &val);
>> + __GUEST_ASSERT(expect_success ? !vector : vector == GP_VECTOR,
>> + "Expected %s on FEP RDPMC(0x%x), got %s",
>> + expect_success ? "no fault" : "#GP", rdpmc_idx, ex_str(vector));
>> + if (expect_success)
>> + GUEST_ASSERT_EQ(val, expected_val);
>> +}
>
> There is a similar guest_test_rdpmc() helper in pmu_counters_test.c. Better
> move the helper into a common header and then avoid the duplication.
guest_test_rdpmc() is just ~15 lines of test assertion glue. Moving it
into pmu.h requires exporting ad-hoc assertion macros like
GUEST_ASSERT_PMC_MSR_ACCESS and GUEST_ASSERT_PMC_VALUE, and it encodes
test-specific expectations (#GP vs exact match) into an architectural
header.
I guess in selftests, a little duplicated assertion is often preferred
over polluting common headers. This is unlike GUEST_MEASURE_EVENT(),
which is a complex inline assembly primitive where duplication would be
error-prone and a maintenance burden.
That said, if you still feel strongly about deduplicating it, I am open
to moving it.
> Others look good to me. Thanks.