1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * CR4 and CPUID sync test
4 *
5 * Copyright 2018, Red Hat, Inc. and/or its affiliates.
6 *
7 * Author:
8 * Wei Huang <wei@redhat.com>
9 */
10
11 #include <fcntl.h>
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <string.h>
15 #include <sys/ioctl.h>
16
17 #include "test_util.h"
18
19 #include "kvm_util.h"
20 #include "processor.h"
21
cr4_cpuid_is_sync(void)22 static inline bool cr4_cpuid_is_sync(void)
23 {
24 uint64_t cr4 = get_cr4();
25
26 return (this_cpu_has(X86_FEATURE_OSXSAVE) == !!(cr4 & X86_CR4_OSXSAVE));
27 }
28
guest_code(void)29 static void guest_code(void)
30 {
31 uint64_t cr4;
32
33 /* turn on CR4.OSXSAVE */
34 cr4 = get_cr4();
35 cr4 |= X86_CR4_OSXSAVE;
36 set_cr4(cr4);
37
38 /* verify CR4.OSXSAVE == CPUID.OSXSAVE */
39 GUEST_ASSERT(cr4_cpuid_is_sync());
40
41 /* notify hypervisor to change CR4 */
42 GUEST_SYNC(0);
43
44 /* check again */
45 GUEST_ASSERT(cr4_cpuid_is_sync());
46
47 GUEST_DONE();
48 }
49
main(int argc,char * argv[])50 int main(int argc, char *argv[])
51 {
52 struct kvm_vcpu *vcpu;
53 struct kvm_run *run;
54 struct kvm_vm *vm;
55 struct kvm_sregs sregs;
56 struct ucall uc;
57
58 TEST_REQUIRE(kvm_cpu_has(X86_FEATURE_XSAVE));
59
60 /* Tell stdout not to buffer its content */
61 setbuf(stdout, NULL);
62
63 vm = vm_create_with_one_vcpu(&vcpu, guest_code);
64 run = vcpu->run;
65
66 while (1) {
67 vcpu_run(vcpu);
68
69 TEST_ASSERT(run->exit_reason == KVM_EXIT_IO,
70 "Unexpected exit reason: %u (%s),\n",
71 run->exit_reason,
72 exit_reason_str(run->exit_reason));
73
74 switch (get_ucall(vcpu, &uc)) {
75 case UCALL_SYNC:
76 /* emulate hypervisor clearing CR4.OSXSAVE */
77 vcpu_sregs_get(vcpu, &sregs);
78 sregs.cr4 &= ~X86_CR4_OSXSAVE;
79 vcpu_sregs_set(vcpu, &sregs);
80 break;
81 case UCALL_ABORT:
82 REPORT_GUEST_ASSERT(uc);
83 break;
84 case UCALL_DONE:
85 goto done;
86 default:
87 TEST_FAIL("Unknown ucall %lu", uc.cmd);
88 }
89 }
90
91 done:
92 kvm_vm_free(vm);
93 return 0;
94 }
95