Linux 4.19.133
[linux/fpc-iii.git] / tools / testing / selftests / kvm / cr4_cpuid_sync_test.c
blob11ec358bf96906113c203c36bab921d1e41ea972
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * CR4 and CPUID sync test
5 * Copyright 2018, Red Hat, Inc. and/or its affiliates.
7 * Author:
8 * Wei Huang <wei@redhat.com>
9 */
11 #include <fcntl.h>
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <string.h>
15 #include <sys/ioctl.h>
17 #include "test_util.h"
19 #include "kvm_util.h"
20 #include "x86.h"
22 #define X86_FEATURE_XSAVE (1<<26)
23 #define X86_FEATURE_OSXSAVE (1<<27)
24 #define VCPU_ID 1
26 static inline bool cr4_cpuid_is_sync(void)
28 int func, subfunc;
29 uint32_t eax, ebx, ecx, edx;
30 uint64_t cr4;
32 func = 0x1;
33 subfunc = 0x0;
34 __asm__ __volatile__("cpuid"
35 : "=a"(eax), "=b"(ebx), "=c"(ecx), "=d"(edx)
36 : "a"(func), "c"(subfunc));
38 cr4 = get_cr4();
40 return (!!(ecx & X86_FEATURE_OSXSAVE)) == (!!(cr4 & X86_CR4_OSXSAVE));
43 static void guest_code(void)
45 uint64_t cr4;
47 /* turn on CR4.OSXSAVE */
48 cr4 = get_cr4();
49 cr4 |= X86_CR4_OSXSAVE;
50 set_cr4(cr4);
52 /* verify CR4.OSXSAVE == CPUID.OSXSAVE */
53 GUEST_ASSERT(cr4_cpuid_is_sync());
55 /* notify hypervisor to change CR4 */
56 GUEST_SYNC(0);
58 /* check again */
59 GUEST_ASSERT(cr4_cpuid_is_sync());
61 GUEST_DONE();
64 int main(int argc, char *argv[])
66 struct kvm_run *run;
67 struct kvm_vm *vm;
68 struct kvm_sregs sregs;
69 struct kvm_cpuid_entry2 *entry;
70 int rc;
72 entry = kvm_get_supported_cpuid_entry(1);
73 if (!(entry->ecx & X86_FEATURE_XSAVE)) {
74 printf("XSAVE feature not supported, skipping test\n");
75 return 0;
78 /* Tell stdout not to buffer its content */
79 setbuf(stdout, NULL);
81 /* Create VM */
82 vm = vm_create_default(VCPU_ID, 0, guest_code);
83 vcpu_set_cpuid(vm, VCPU_ID, kvm_get_supported_cpuid());
84 run = vcpu_state(vm, VCPU_ID);
86 while (1) {
87 rc = _vcpu_run(vm, VCPU_ID);
89 if (run->exit_reason == KVM_EXIT_IO) {
90 switch (run->io.port) {
91 case GUEST_PORT_SYNC:
92 /* emulate hypervisor clearing CR4.OSXSAVE */
93 vcpu_sregs_get(vm, VCPU_ID, &sregs);
94 sregs.cr4 &= ~X86_CR4_OSXSAVE;
95 vcpu_sregs_set(vm, VCPU_ID, &sregs);
96 break;
97 case GUEST_PORT_ABORT:
98 TEST_ASSERT(false, "Guest CR4 bit (OSXSAVE) unsynchronized with CPUID bit.");
99 break;
100 case GUEST_PORT_DONE:
101 goto done;
102 default:
103 TEST_ASSERT(false, "Unknown port 0x%x.",
104 run->io.port);
109 kvm_vm_free(vm);
111 done:
112 return 0;