1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3 * kvm_create_max_vcpus
4 *
5 * Copyright (C) 2019, Google LLC.
6 *
7 * Test for KVM_CAP_MAX_VCPUS and KVM_CAP_MAX_VCPU_ID.
8 */
9 #include <fcntl.h>
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <string.h>
13 #include <sys/resource.h>
14
15 #include "test_util.h"
16
17 #include "kvm_util.h"
18 #include "asm/kvm.h"
19 #include "linux/kvm.h"
20
test_vcpu_creation(int first_vcpu_id,int num_vcpus)21 void test_vcpu_creation(int first_vcpu_id, int num_vcpus)
22 {
23 struct kvm_vm *vm;
24 int i;
25
26 pr_info("Testing creating %d vCPUs, with IDs %d...%d.\n",
27 num_vcpus, first_vcpu_id, first_vcpu_id + num_vcpus - 1);
28
29 vm = vm_create_barebones();
30
31 for (i = first_vcpu_id; i < first_vcpu_id + num_vcpus; i++)
32 /* This asserts that the vCPU was created. */
33 __vm_vcpu_add(vm, i);
34
35 kvm_vm_free(vm);
36 }
37
main(int argc,char * argv[])38 int main(int argc, char *argv[])
39 {
40 int kvm_max_vcpu_id = kvm_check_cap(KVM_CAP_MAX_VCPU_ID);
41 int kvm_max_vcpus = kvm_check_cap(KVM_CAP_MAX_VCPUS);
42 /*
43 * Number of file descriptors reqired, KVM_CAP_MAX_VCPUS for vCPU fds +
44 * an arbitrary number for everything else.
45 */
46 int nr_fds_wanted = kvm_max_vcpus + 100;
47 struct rlimit rl;
48
49 pr_info("KVM_CAP_MAX_VCPU_ID: %d\n", kvm_max_vcpu_id);
50 pr_info("KVM_CAP_MAX_VCPUS: %d\n", kvm_max_vcpus);
51
52 /*
53 * Check that we're allowed to open nr_fds_wanted file descriptors and
54 * try raising the limits if needed.
55 */
56 TEST_ASSERT(!getrlimit(RLIMIT_NOFILE, &rl), "getrlimit() failed!");
57
58 if (rl.rlim_cur < nr_fds_wanted) {
59 rl.rlim_cur = nr_fds_wanted;
60 if (rl.rlim_max < nr_fds_wanted) {
61 int old_rlim_max = rl.rlim_max;
62 rl.rlim_max = nr_fds_wanted;
63
64 int r = setrlimit(RLIMIT_NOFILE, &rl);
65 __TEST_REQUIRE(r >= 0,
66 "RLIMIT_NOFILE hard limit is too low (%d, wanted %d)",
67 old_rlim_max, nr_fds_wanted);
68 } else {
69 TEST_ASSERT(!setrlimit(RLIMIT_NOFILE, &rl), "setrlimit() failed!");
70 }
71 }
72
73 /*
74 * Upstream KVM prior to 4.8 does not support KVM_CAP_MAX_VCPU_ID.
75 * Userspace is supposed to use KVM_CAP_MAX_VCPUS as the maximum ID
76 * in this case.
77 */
78 if (!kvm_max_vcpu_id)
79 kvm_max_vcpu_id = kvm_max_vcpus;
80
81 TEST_ASSERT(kvm_max_vcpu_id >= kvm_max_vcpus,
82 "KVM_MAX_VCPU_IDS (%d) must be at least as large as KVM_MAX_VCPUS (%d).",
83 kvm_max_vcpu_id, kvm_max_vcpus);
84
85 test_vcpu_creation(0, kvm_max_vcpus);
86
87 if (kvm_max_vcpu_id > kvm_max_vcpus)
88 test_vcpu_creation(
89 kvm_max_vcpu_id - kvm_max_vcpus, kvm_max_vcpus);
90
91 return 0;
92 }
93