xref: /linux/tools/testing/selftests/kvm/x86/nested_close_kvm_test.c (revision 2bee2e6c983baa3605765621f26173ff0fa40365)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2019, Red Hat, Inc.
4  *
5  * Verify that nothing bad happens if a KVM user exits with open
6  * file descriptors while executing a nested guest.
7  */
8 
9 #include "test_util.h"
10 #include "kvm_util.h"
11 #include "processor.h"
12 #include "vmx.h"
13 #include "svm_util.h"
14 
15 #include <string.h>
16 #include <sys/ioctl.h>
17 
18 #include "kselftest.h"
19 
20 enum {
21 	PORT_L0_EXIT = 0x2000,
22 };
23 
24 static void l2_guest_code(void)
25 {
26 	/* Exit to L0 */
27 	asm volatile("inb %%dx, %%al"
28 		     : : [port] "d" (PORT_L0_EXIT) : "rax");
29 }
30 
31 static void l1_vmx_code(struct vmx_pages *vmx_pages)
32 {
33 	GUEST_ASSERT(prepare_for_vmx_operation(vmx_pages));
34 	GUEST_ASSERT(load_vmcs(vmx_pages));
35 
36 	/* Prepare the VMCS for L2 execution. */
37 	prepare_vmcs(vmx_pages, l2_guest_code);
38 
39 	GUEST_ASSERT(!vmlaunch());
40 	GUEST_ASSERT(0);
41 }
42 
43 static void l1_svm_code(struct svm_test_data *svm)
44 {
45 	/* Prepare the VMCB for L2 execution. */
46 	generic_svm_setup(svm, l2_guest_code);
47 
48 	run_guest(svm->vmcb, svm->vmcb_gpa);
49 	GUEST_ASSERT(0);
50 }
51 
52 static void l1_guest_code(void *data)
53 {
54 	if (this_cpu_has(X86_FEATURE_VMX))
55 		l1_vmx_code(data);
56 	else
57 		l1_svm_code(data);
58 }
59 
60 int main(int argc, char *argv[])
61 {
62 	gva_t guest_gva;
63 	struct kvm_vcpu *vcpu;
64 	struct kvm_vm *vm;
65 
66 	TEST_REQUIRE(kvm_cpu_has(X86_FEATURE_VMX) ||
67 		     kvm_cpu_has(X86_FEATURE_SVM));
68 
69 	vm = vm_create_with_one_vcpu(&vcpu, l1_guest_code);
70 
71 	if (kvm_cpu_has(X86_FEATURE_VMX))
72 		vcpu_alloc_vmx(vm, &guest_gva);
73 	else
74 		vcpu_alloc_svm(vm, &guest_gva);
75 
76 	vcpu_args_set(vcpu, 1, guest_gva);
77 
78 	for (;;) {
79 		volatile struct kvm_run *run = vcpu->run;
80 		struct ucall uc;
81 
82 		vcpu_run(vcpu);
83 		TEST_ASSERT_KVM_EXIT_REASON(vcpu, KVM_EXIT_IO);
84 
85 		if (run->io.port == PORT_L0_EXIT)
86 			break;
87 
88 		switch (get_ucall(vcpu, &uc)) {
89 		case UCALL_ABORT:
90 			REPORT_GUEST_ASSERT(uc);
91 			/* NOT REACHED */
92 		default:
93 			TEST_FAIL("Unknown ucall %lu", uc.cmd);
94 		}
95 	}
96 }
97