xref: /linux/tools/testing/selftests/kvm/x86_64/hyperv_extended_hypercalls.c (revision 119ff04864a24470b1e531bb53e5c141aa8fefb0)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Test Hyper-V extended hypercall, HV_EXT_CALL_QUERY_CAPABILITIES (0x8001),
4  * exit to userspace and receive result in guest.
5  *
6  * Negative tests are present in hyperv_features.c
7  *
8  * Copyright 2022 Google LLC
9  * Author: Vipin Sharma <vipinsh@google.com>
10  */
11 #include "kvm_util.h"
12 #include "processor.h"
13 #include "hyperv.h"
14 
15 /* Any value is fine */
16 #define EXT_CAPABILITIES 0xbull
17 
18 static void guest_code(vm_paddr_t in_pg_gpa, vm_paddr_t out_pg_gpa,
19 		       vm_vaddr_t out_pg_gva)
20 {
21 	uint64_t *output_gva;
22 
23 	wrmsr(HV_X64_MSR_GUEST_OS_ID, HYPERV_LINUX_OS_ID);
24 	wrmsr(HV_X64_MSR_HYPERCALL, in_pg_gpa);
25 
26 	output_gva = (uint64_t *)out_pg_gva;
27 
28 	hyperv_hypercall(HV_EXT_CALL_QUERY_CAPABILITIES, in_pg_gpa, out_pg_gpa);
29 
30 	/* TLFS states output will be a uint64_t value */
31 	GUEST_ASSERT_EQ(*output_gva, EXT_CAPABILITIES);
32 
33 	GUEST_DONE();
34 }
35 
36 int main(void)
37 {
38 	vm_vaddr_t hcall_out_page;
39 	vm_vaddr_t hcall_in_page;
40 	struct kvm_vcpu *vcpu;
41 	struct kvm_run *run;
42 	struct kvm_vm *vm;
43 	uint64_t *outval;
44 	struct ucall uc;
45 
46 	TEST_REQUIRE(kvm_has_cap(KVM_CAP_HYPERV_CPUID));
47 
48 	/* Verify if extended hypercalls are supported */
49 	if (!kvm_cpuid_has(kvm_get_supported_hv_cpuid(),
50 			   HV_ENABLE_EXTENDED_HYPERCALLS)) {
51 		print_skip("Extended calls not supported by the kernel");
52 		exit(KSFT_SKIP);
53 	}
54 
55 	vm = vm_create_with_one_vcpu(&vcpu, guest_code);
56 	run = vcpu->run;
57 	vcpu_set_hv_cpuid(vcpu);
58 
59 	/* Hypercall input */
60 	hcall_in_page = vm_vaddr_alloc_pages(vm, 1);
61 	memset(addr_gva2hva(vm, hcall_in_page), 0x0, vm->page_size);
62 
63 	/* Hypercall output */
64 	hcall_out_page = vm_vaddr_alloc_pages(vm, 1);
65 	memset(addr_gva2hva(vm, hcall_out_page), 0x0, vm->page_size);
66 
67 	vcpu_args_set(vcpu, 3, addr_gva2gpa(vm, hcall_in_page),
68 		      addr_gva2gpa(vm, hcall_out_page), hcall_out_page);
69 
70 	vcpu_run(vcpu);
71 
72 	TEST_ASSERT(run->exit_reason == KVM_EXIT_HYPERV,
73 		    "Unexpected exit reason: %u (%s)",
74 		    run->exit_reason, exit_reason_str(run->exit_reason));
75 
76 	outval = addr_gpa2hva(vm, run->hyperv.u.hcall.params[1]);
77 	*outval = EXT_CAPABILITIES;
78 	run->hyperv.u.hcall.result = HV_STATUS_SUCCESS;
79 
80 	vcpu_run(vcpu);
81 
82 	TEST_ASSERT(run->exit_reason == KVM_EXIT_IO,
83 		    "Unexpected exit reason: %u (%s)",
84 		    run->exit_reason, exit_reason_str(run->exit_reason));
85 
86 	switch (get_ucall(vcpu, &uc)) {
87 	case UCALL_ABORT:
88 		REPORT_GUEST_ASSERT(uc);
89 		break;
90 	case UCALL_DONE:
91 		break;
92 	default:
93 		TEST_FAIL("Unhandled ucall: %ld", uc.cmd);
94 	}
95 
96 	kvm_vm_free(vm);
97 	return 0;
98 }
99