Skip to content

Commit eae260b

Browse files
vittyvkbonzini
authored andcommitted
KVM: selftests: Make hyperv_clock selftest more stable
hyperv_clock doesn't always give a stable test result, especially with AMD CPUs. The test compares Hyper-V MSR clocksource (acquired either with rdmsr() from within the guest or KVM_GET_MSRS from the host) against rdtsc(). To increase the accuracy, increase the measured delay (done with nop loop) by two orders of magnitude and take the mean rdtsc() value before and after rdmsr()/KVM_GET_MSRS. Reported-by: Maxim Levitsky <[email protected]> Signed-off-by: Vitaly Kuznetsov <[email protected]> Reviewed-by: Maxim Levitsky <[email protected]> Tested-by: Maxim Levitsky <[email protected]> Message-Id: <[email protected]> Signed-off-by: Paolo Bonzini <[email protected]>
1 parent 5ba7c4c commit eae260b

File tree

1 file changed

+7
-3
lines changed

1 file changed

+7
-3
lines changed

tools/testing/selftests/kvm/x86_64/hyperv_clock.c

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ static inline void nop_loop(void)
4444
{
4545
int i;
4646

47-
for (i = 0; i < 1000000; i++)
47+
for (i = 0; i < 100000000; i++)
4848
asm volatile("nop");
4949
}
5050

@@ -56,12 +56,14 @@ static inline void check_tsc_msr_rdtsc(void)
5656
tsc_freq = rdmsr(HV_X64_MSR_TSC_FREQUENCY);
5757
GUEST_ASSERT(tsc_freq > 0);
5858

59-
/* First, check MSR-based clocksource */
59+
/* For increased accuracy, take mean rdtsc() before and afrer rdmsr() */
6060
r1 = rdtsc();
6161
t1 = rdmsr(HV_X64_MSR_TIME_REF_COUNT);
62+
r1 = (r1 + rdtsc()) / 2;
6263
nop_loop();
6364
r2 = rdtsc();
6465
t2 = rdmsr(HV_X64_MSR_TIME_REF_COUNT);
66+
r2 = (r2 + rdtsc()) / 2;
6567

6668
GUEST_ASSERT(r2 > r1 && t2 > t1);
6769

@@ -181,12 +183,14 @@ static void host_check_tsc_msr_rdtsc(struct kvm_vm *vm)
181183
tsc_freq = vcpu_get_msr(vm, VCPU_ID, HV_X64_MSR_TSC_FREQUENCY);
182184
TEST_ASSERT(tsc_freq > 0, "TSC frequency must be nonzero");
183185

184-
/* First, check MSR-based clocksource */
186+
/* For increased accuracy, take mean rdtsc() before and afrer ioctl */
185187
r1 = rdtsc();
186188
t1 = vcpu_get_msr(vm, VCPU_ID, HV_X64_MSR_TIME_REF_COUNT);
189+
r1 = (r1 + rdtsc()) / 2;
187190
nop_loop();
188191
r2 = rdtsc();
189192
t2 = vcpu_get_msr(vm, VCPU_ID, HV_X64_MSR_TIME_REF_COUNT);
193+
r2 = (r2 + rdtsc()) / 2;
190194

191195
TEST_ASSERT(t2 > t1, "Time reference MSR is not monotonic (%ld <= %ld)", t1, t2);
192196

0 commit comments

Comments
 (0)