kvm_create_max_vcpus.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. #include "test_util.h"
  15. #include "kvm_util.h"
  16. #include "asm/kvm.h"
  17. #include "linux/kvm.h"
  18. void test_vcpu_creation(int first_vcpu_id, int num_vcpus)
  19. {
  20. struct kvm_vm *vm;
  21. int i;
  22. pr_info("Testing creating %d vCPUs, with IDs %d...%d.\n",
  23. num_vcpus, first_vcpu_id, first_vcpu_id + num_vcpus - 1);
  24. vm = vm_create_barebones();
  25. for (i = first_vcpu_id; i < first_vcpu_id + num_vcpus; i++)
  26. /* This asserts that the vCPU was created. */
  27. __vm_vcpu_add(vm, i);
  28. kvm_vm_free(vm);
  29. }
  30. int main(int argc, char *argv[])
  31. {
  32. int kvm_max_vcpu_id = kvm_check_cap(KVM_CAP_MAX_VCPU_ID);
  33. int kvm_max_vcpus = kvm_check_cap(KVM_CAP_MAX_VCPUS);
  34. /*
  35. * Number of file descriptors reqired, KVM_CAP_MAX_VCPUS for vCPU fds +
  36. * an arbitrary number for everything else.
  37. */
  38. int nr_fds_wanted = kvm_max_vcpus + 100;
  39. struct rlimit rl;
  40. pr_info("KVM_CAP_MAX_VCPU_ID: %d\n", kvm_max_vcpu_id);
  41. pr_info("KVM_CAP_MAX_VCPUS: %d\n", kvm_max_vcpus);
  42. /*
  43. * Check that we're allowed to open nr_fds_wanted file descriptors and
  44. * try raising the limits if needed.
  45. */
  46. TEST_ASSERT(!getrlimit(RLIMIT_NOFILE, &rl), "getrlimit() failed!");
  47. if (rl.rlim_cur < nr_fds_wanted) {
  48. rl.rlim_cur = nr_fds_wanted;
  49. if (rl.rlim_max < nr_fds_wanted) {
  50. int old_rlim_max = rl.rlim_max;
  51. rl.rlim_max = nr_fds_wanted;
  52. int r = setrlimit(RLIMIT_NOFILE, &rl);
  53. __TEST_REQUIRE(r >= 0,
  54. "RLIMIT_NOFILE hard limit is too low (%d, wanted %d)",
  55. old_rlim_max, nr_fds_wanted);
  56. } else {
  57. TEST_ASSERT(!setrlimit(RLIMIT_NOFILE, &rl), "setrlimit() failed!");
  58. }
  59. }
  60. /*
  61. * Upstream KVM prior to 4.8 does not support KVM_CAP_MAX_VCPU_ID.
  62. * Userspace is supposed to use KVM_CAP_MAX_VCPUS as the maximum ID
  63. * in this case.
  64. */
  65. if (!kvm_max_vcpu_id)
  66. kvm_max_vcpu_id = kvm_max_vcpus;
  67. TEST_ASSERT(kvm_max_vcpu_id >= kvm_max_vcpus,
  68. "KVM_MAX_VCPU_IDS (%d) must be at least as large as KVM_MAX_VCPUS (%d).",
  69. kvm_max_vcpu_id, kvm_max_vcpus);
  70. test_vcpu_creation(0, kvm_max_vcpus);
  71. if (kvm_max_vcpu_id > kvm_max_vcpus)
  72. test_vcpu_creation(
  73. kvm_max_vcpu_id - kvm_max_vcpus, kvm_max_vcpus);
  74. return 0;
  75. }