1 // SPDX-License-Identifier: GPL-2.0-only
3 * Copyright (C) 2021, Google LLC.
5 * Tests for adjusting the system counter from userspace
7 #include <asm/kvm_para.h>
13 #include "test_util.h"
15 #include "processor.h"
23 static struct test_case test_cases
[] = {
25 { 180 * NSEC_PER_SEC
},
26 { -180 * NSEC_PER_SEC
},
29 static void check_preconditions(struct kvm_vcpu
*vcpu
)
31 __TEST_REQUIRE(!__vcpu_has_device_attr(vcpu
, KVM_VCPU_TSC_CTRL
,
33 "KVM_VCPU_TSC_OFFSET not supported; skipping test");
36 static void setup_system_counter(struct kvm_vcpu
*vcpu
, struct test_case
*test
)
38 vcpu_device_attr_set(vcpu
, KVM_VCPU_TSC_CTRL
, KVM_VCPU_TSC_OFFSET
,
42 static uint64_t guest_read_system_counter(struct test_case
*test
)
47 static uint64_t host_read_guest_system_counter(struct test_case
*test
)
49 return rdtsc() + test
->tsc_offset
;
52 #else /* __x86_64__ */
54 #error test not implemented for this architecture!
58 #define GUEST_SYNC_CLOCK(__stage, __val) \
59 GUEST_SYNC_ARGS(__stage, __val, 0, 0, 0)
61 static void guest_main(void)
65 for (i
= 0; i
< ARRAY_SIZE(test_cases
); i
++) {
66 struct test_case
*test
= &test_cases
[i
];
68 GUEST_SYNC_CLOCK(i
, guest_read_system_counter(test
));
72 static void handle_sync(struct ucall
*uc
, uint64_t start
, uint64_t end
)
74 uint64_t obs
= uc
->args
[2];
76 TEST_ASSERT(start
<= obs
&& obs
<= end
,
77 "unexpected system counter value: %"PRIu64
" expected range: [%"PRIu64
", %"PRIu64
"]",
80 pr_info("system counter value: %"PRIu64
" expected range [%"PRIu64
", %"PRIu64
"]\n",
84 static void handle_abort(struct ucall
*uc
)
86 REPORT_GUEST_ASSERT(*uc
);
89 static void enter_guest(struct kvm_vcpu
*vcpu
)
95 for (i
= 0; i
< ARRAY_SIZE(test_cases
); i
++) {
96 struct test_case
*test
= &test_cases
[i
];
98 setup_system_counter(vcpu
, test
);
99 start
= host_read_guest_system_counter(test
);
101 end
= host_read_guest_system_counter(test
);
103 switch (get_ucall(vcpu
, &uc
)) {
105 handle_sync(&uc
, start
, end
);
111 TEST_ASSERT(0, "unhandled ucall %ld",
112 get_ucall(vcpu
, &uc
));
119 struct kvm_vcpu
*vcpu
;
122 vm
= vm_create_with_one_vcpu(&vcpu
, guest_main
);
123 check_preconditions(vcpu
);