1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Test for x86 KVM_CAP_MSR_PLATFORM_INFO
4  *
5  * Copyright (C) 2018, Google LLC.
6  *
7  * This work is licensed under the terms of the GNU GPL, version 2.
8  *
9  * Verifies expected behavior of controlling guest access to
10  * MSR_PLATFORM_INFO.
11  */
12 
13 #define _GNU_SOURCE /* for program_invocation_short_name */
14 #include <fcntl.h>
15 #include <stdio.h>
16 #include <stdlib.h>
17 #include <string.h>
18 #include <sys/ioctl.h>
19 
20 #include "test_util.h"
21 #include "kvm_util.h"
22 #include "processor.h"
23 
24 #define MSR_PLATFORM_INFO_MAX_TURBO_RATIO 0xff00
25 
26 static void guest_code(void)
27 {
28 	uint64_t msr_platform_info;
29 
30 	for (;;) {
31 		msr_platform_info = rdmsr(MSR_PLATFORM_INFO);
32 		GUEST_SYNC(msr_platform_info);
33 		asm volatile ("inc %r11");
34 	}
35 }
36 
37 static void test_msr_platform_info_enabled(struct kvm_vcpu *vcpu)
38 {
39 	struct kvm_run *run = vcpu->run;
40 	struct ucall uc;
41 
42 	vm_enable_cap(vcpu->vm, KVM_CAP_MSR_PLATFORM_INFO, true);
43 	vcpu_run(vcpu);
44 	TEST_ASSERT(run->exit_reason == KVM_EXIT_IO,
45 			"Exit_reason other than KVM_EXIT_IO: %u (%s),\n",
46 			run->exit_reason,
47 			exit_reason_str(run->exit_reason));
48 	get_ucall(vcpu, &uc);
49 	TEST_ASSERT(uc.cmd == UCALL_SYNC,
50 			"Received ucall other than UCALL_SYNC: %lu\n", uc.cmd);
51 	TEST_ASSERT((uc.args[1] & MSR_PLATFORM_INFO_MAX_TURBO_RATIO) ==
52 		MSR_PLATFORM_INFO_MAX_TURBO_RATIO,
53 		"Expected MSR_PLATFORM_INFO to have max turbo ratio mask: %i.",
54 		MSR_PLATFORM_INFO_MAX_TURBO_RATIO);
55 }
56 
57 static void test_msr_platform_info_disabled(struct kvm_vcpu *vcpu)
58 {
59 	struct kvm_run *run = vcpu->run;
60 
61 	vm_enable_cap(vcpu->vm, KVM_CAP_MSR_PLATFORM_INFO, false);
62 	vcpu_run(vcpu);
63 	TEST_ASSERT(run->exit_reason == KVM_EXIT_SHUTDOWN,
64 			"Exit_reason other than KVM_EXIT_SHUTDOWN: %u (%s)\n",
65 			run->exit_reason,
66 			exit_reason_str(run->exit_reason));
67 }
68 
69 int main(int argc, char *argv[])
70 {
71 	struct kvm_vcpu *vcpu;
72 	struct kvm_vm *vm;
73 	uint64_t msr_platform_info;
74 
75 	/* Tell stdout not to buffer its content */
76 	setbuf(stdout, NULL);
77 
78 	TEST_REQUIRE(kvm_has_cap(KVM_CAP_MSR_PLATFORM_INFO));
79 
80 	vm = vm_create_with_one_vcpu(&vcpu, guest_code);
81 
82 	msr_platform_info = vcpu_get_msr(vcpu, MSR_PLATFORM_INFO);
83 	vcpu_set_msr(vcpu, MSR_PLATFORM_INFO,
84 		     msr_platform_info | MSR_PLATFORM_INFO_MAX_TURBO_RATIO);
85 	test_msr_platform_info_enabled(vcpu);
86 	test_msr_platform_info_disabled(vcpu);
87 	vcpu_set_msr(vcpu, MSR_PLATFORM_INFO, msr_platform_info);
88 
89 	kvm_vm_free(vm);
90 
91 	return 0;
92 }
93