Merge tag 'trace-printf-v6.13' of git://git.kernel.org/pub/scm/linux/kernel/git/trace...
[drm/drm-misc.git] / tools / testing / selftests / kvm / system_counter_offset_test.c
blob513d421a9bff85a96e619f187310769de7e48490
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3 * Copyright (C) 2021, Google LLC.
5 * Tests for adjusting the system counter from userspace
6 */
7 #include <asm/kvm_para.h>
8 #include <stdint.h>
9 #include <string.h>
10 #include <sys/stat.h>
11 #include <time.h>
13 #include "test_util.h"
14 #include "kvm_util.h"
15 #include "processor.h"
17 #ifdef __x86_64__
19 struct test_case {
20 uint64_t tsc_offset;
23 static struct test_case test_cases[] = {
24 { 0 },
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,
32 KVM_VCPU_TSC_OFFSET),
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,
39 &test->tsc_offset);
42 static uint64_t guest_read_system_counter(struct test_case *test)
44 return rdtsc();
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!
56 #endif
58 #define GUEST_SYNC_CLOCK(__stage, __val) \
59 GUEST_SYNC_ARGS(__stage, __val, 0, 0, 0)
61 static void guest_main(void)
63 int i;
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"]",
78 obs, start, end);
80 pr_info("system counter value: %"PRIu64" expected range [%"PRIu64", %"PRIu64"]\n",
81 obs, start, end);
84 static void handle_abort(struct ucall *uc)
86 REPORT_GUEST_ASSERT(*uc);
89 static void enter_guest(struct kvm_vcpu *vcpu)
91 uint64_t start, end;
92 struct ucall uc;
93 int i;
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);
100 vcpu_run(vcpu);
101 end = host_read_guest_system_counter(test);
103 switch (get_ucall(vcpu, &uc)) {
104 case UCALL_SYNC:
105 handle_sync(&uc, start, end);
106 break;
107 case UCALL_ABORT:
108 handle_abort(&uc);
109 return;
110 default:
111 TEST_ASSERT(0, "unhandled ucall %ld",
112 get_ucall(vcpu, &uc));
117 int main(void)
119 struct kvm_vcpu *vcpu;
120 struct kvm_vm *vm;
122 vm = vm_create_with_one_vcpu(&vcpu, guest_main);
123 check_preconditions(vcpu);
125 enter_guest(vcpu);
126 kvm_vm_free(vm);