1 // SPDX-License-Identifier: GPL-2.0-only 2 /* 3 * tools/testing/selftests/kvm/lib/kvm_util.c 4 * 5 * Copyright (C) 2018, Google LLC. 6 */ 7 #include "test_util.h" 8 #include "kvm_util.h" 9 #include "processor.h" 10 #include "ucall_common.h" 11 12 #include <assert.h> 13 #include <sched.h> 14 #include <sys/mman.h> 15 #include <sys/resource.h> 16 #include <sys/types.h> 17 #include <sys/stat.h> 18 #include <unistd.h> 19 #include <linux/kernel.h> 20 21 #define KVM_UTIL_MIN_PFN 2 22 23 uint32_t guest_random_seed; 24 struct guest_random_state guest_rng; 25 static uint32_t last_guest_seed; 26 27 static int vcpu_mmap_sz(void); 28 29 int __open_path_or_exit(const char *path, int flags, const char *enoent_help) 30 { 31 int fd; 32 33 fd = open(path, flags); 34 if (fd < 0) 35 goto error; 36 37 return fd; 38 39 error: 40 if (errno == EACCES || errno == ENOENT) 41 ksft_exit_skip("- Cannot open '%s': %s. %s\n", 42 path, strerror(errno), 43 errno == EACCES ? "Root required?" : enoent_help); 44 TEST_FAIL("Failed to open '%s'", path); 45 } 46 47 int open_path_or_exit(const char *path, int flags) 48 { 49 return __open_path_or_exit(path, flags, ""); 50 } 51 52 /* 53 * Open KVM_DEV_PATH if available, otherwise exit the entire program. 54 * 55 * Input Args: 56 * flags - The flags to pass when opening KVM_DEV_PATH. 57 * 58 * Return: 59 * The opened file descriptor of /dev/kvm. 60 */ 61 static int _open_kvm_dev_path_or_exit(int flags) 62 { 63 return __open_path_or_exit(KVM_DEV_PATH, flags, "Is KVM loaded and enabled?"); 64 } 65 66 int open_kvm_dev_path_or_exit(void) 67 { 68 return _open_kvm_dev_path_or_exit(O_RDONLY); 69 } 70 71 static ssize_t get_module_param(const char *module_name, const char *param, 72 void *buffer, size_t buffer_size) 73 { 74 const int path_size = 128; 75 char path[path_size]; 76 ssize_t bytes_read; 77 int fd, r; 78 79 /* Verify KVM is loaded, to provide a more helpful SKIP message. */ 80 close(open_kvm_dev_path_or_exit()); 81 82 r = snprintf(path, path_size, "/sys/module/%s/parameters/%s", 83 module_name, param); 84 TEST_ASSERT(r < path_size, 85 "Failed to construct sysfs path in %d bytes.", path_size); 86 87 fd = open_path_or_exit(path, O_RDONLY); 88 89 bytes_read = read(fd, buffer, buffer_size); 90 TEST_ASSERT(bytes_read > 0, "read(%s) returned %ld, wanted %ld bytes", 91 path, bytes_read, buffer_size); 92 93 r = close(fd); 94 TEST_ASSERT(!r, "close(%s) failed", path); 95 return bytes_read; 96 } 97 98 static int get_module_param_integer(const char *module_name, const char *param) 99 { 100 /* 101 * 16 bytes to hold a 64-bit value (1 byte per char), 1 byte for the 102 * NUL char, and 1 byte because the kernel sucks and inserts a newline 103 * at the end. 104 */ 105 char value[16 + 1 + 1]; 106 ssize_t r; 107 108 memset(value, '\0', sizeof(value)); 109 110 r = get_module_param(module_name, param, value, sizeof(value)); 111 TEST_ASSERT(value[r - 1] == '\n', 112 "Expected trailing newline, got char '%c'", value[r - 1]); 113 114 /* 115 * Squash the newline, otherwise atoi_paranoid() will complain about 116 * trailing non-NUL characters in the string. 117 */ 118 value[r - 1] = '\0'; 119 return atoi_paranoid(value); 120 } 121 122 static bool get_module_param_bool(const char *module_name, const char *param) 123 { 124 char value; 125 ssize_t r; 126 127 r = get_module_param(module_name, param, &value, sizeof(value)); 128 TEST_ASSERT_EQ(r, 1); 129 130 if (value == 'Y') 131 return true; 132 else if (value == 'N') 133 return false; 134 135 TEST_FAIL("Unrecognized value '%c' for boolean module param", value); 136 } 137 138 bool get_kvm_param_bool(const char *param) 139 { 140 return get_module_param_bool("kvm", param); 141 } 142 143 bool get_kvm_intel_param_bool(const char *param) 144 { 145 return get_module_param_bool("kvm_intel", param); 146 } 147 148 bool get_kvm_amd_param_bool(const char *param) 149 { 150 return get_module_param_bool("kvm_amd", param); 151 } 152 153 int get_kvm_param_integer(const char *param) 154 { 155 return get_module_param_integer("kvm", param); 156 } 157 158 int get_kvm_intel_param_integer(const char *param) 159 { 160 return get_module_param_integer("kvm_intel", param); 161 } 162 163 int get_kvm_amd_param_integer(const char *param) 164 { 165 return get_module_param_integer("kvm_amd", param); 166 } 167 168 /* 169 * Capability 170 * 171 * Input Args: 172 * cap - Capability 173 * 174 * Output Args: None 175 * 176 * Return: 177 * On success, the Value corresponding to the capability (KVM_CAP_*) 178 * specified by the value of cap. On failure a TEST_ASSERT failure 179 * is produced. 180 * 181 * Looks up and returns the value corresponding to the capability 182 * (KVM_CAP_*) given by cap. 183 */ 184 unsigned int kvm_check_cap(long cap) 185 { 186 int ret; 187 int kvm_fd; 188 189 kvm_fd = open_kvm_dev_path_or_exit(); 190 ret = __kvm_ioctl(kvm_fd, KVM_CHECK_EXTENSION, (void *)cap); 191 TEST_ASSERT(ret >= 0, KVM_IOCTL_ERROR(KVM_CHECK_EXTENSION, ret)); 192 193 close(kvm_fd); 194 195 return (unsigned int)ret; 196 } 197 198 void vm_enable_dirty_ring(struct kvm_vm *vm, uint32_t ring_size) 199 { 200 if (vm_check_cap(vm, KVM_CAP_DIRTY_LOG_RING_ACQ_REL)) 201 vm_enable_cap(vm, KVM_CAP_DIRTY_LOG_RING_ACQ_REL, ring_size); 202 else 203 vm_enable_cap(vm, KVM_CAP_DIRTY_LOG_RING, ring_size); 204 vm->dirty_ring_size = ring_size; 205 } 206 207 static void vm_open(struct kvm_vm *vm) 208 { 209 vm->kvm_fd = _open_kvm_dev_path_or_exit(O_RDWR); 210 211 TEST_REQUIRE(kvm_has_cap(KVM_CAP_IMMEDIATE_EXIT)); 212 213 vm->fd = __kvm_ioctl(vm->kvm_fd, KVM_CREATE_VM, (void *)vm->type); 214 TEST_ASSERT(vm->fd >= 0, KVM_IOCTL_ERROR(KVM_CREATE_VM, vm->fd)); 215 216 if (kvm_has_cap(KVM_CAP_BINARY_STATS_FD)) 217 vm->stats.fd = vm_get_stats_fd(vm); 218 else 219 vm->stats.fd = -1; 220 } 221 222 const char *vm_guest_mode_string(uint32_t i) 223 { 224 static const char * const strings[] = { 225 [VM_MODE_P52V48_4K] = "PA-bits:52, VA-bits:48, 4K pages", 226 [VM_MODE_P52V48_16K] = "PA-bits:52, VA-bits:48, 16K pages", 227 [VM_MODE_P52V48_64K] = "PA-bits:52, VA-bits:48, 64K pages", 228 [VM_MODE_P48V48_4K] = "PA-bits:48, VA-bits:48, 4K pages", 229 [VM_MODE_P48V48_16K] = "PA-bits:48, VA-bits:48, 16K pages", 230 [VM_MODE_P48V48_64K] = "PA-bits:48, VA-bits:48, 64K pages", 231 [VM_MODE_P40V48_4K] = "PA-bits:40, VA-bits:48, 4K pages", 232 [VM_MODE_P40V48_16K] = "PA-bits:40, VA-bits:48, 16K pages", 233 [VM_MODE_P40V48_64K] = "PA-bits:40, VA-bits:48, 64K pages", 234 [VM_MODE_PXXV48_4K] = "PA-bits:ANY, VA-bits:48, 4K pages", 235 [VM_MODE_P47V64_4K] = "PA-bits:47, VA-bits:64, 4K pages", 236 [VM_MODE_P44V64_4K] = "PA-bits:44, VA-bits:64, 4K pages", 237 [VM_MODE_P36V48_4K] = "PA-bits:36, VA-bits:48, 4K pages", 238 [VM_MODE_P36V48_16K] = "PA-bits:36, VA-bits:48, 16K pages", 239 [VM_MODE_P36V48_64K] = "PA-bits:36, VA-bits:48, 64K pages", 240 [VM_MODE_P47V47_16K] = "PA-bits:47, VA-bits:47, 16K pages", 241 [VM_MODE_P36V47_16K] = "PA-bits:36, VA-bits:47, 16K pages", 242 }; 243 _Static_assert(sizeof(strings)/sizeof(char *) == NUM_VM_MODES, 244 "Missing new mode strings?"); 245 246 TEST_ASSERT(i < NUM_VM_MODES, "Guest mode ID %d too big", i); 247 248 return strings[i]; 249 } 250 251 const struct vm_guest_mode_params vm_guest_mode_params[] = { 252 [VM_MODE_P52V48_4K] = { 52, 48, 0x1000, 12 }, 253 [VM_MODE_P52V48_16K] = { 52, 48, 0x4000, 14 }, 254 [VM_MODE_P52V48_64K] = { 52, 48, 0x10000, 16 }, 255 [VM_MODE_P48V48_4K] = { 48, 48, 0x1000, 12 }, 256 [VM_MODE_P48V48_16K] = { 48, 48, 0x4000, 14 }, 257 [VM_MODE_P48V48_64K] = { 48, 48, 0x10000, 16 }, 258 [VM_MODE_P40V48_4K] = { 40, 48, 0x1000, 12 }, 259 [VM_MODE_P40V48_16K] = { 40, 48, 0x4000, 14 }, 260 [VM_MODE_P40V48_64K] = { 40, 48, 0x10000, 16 }, 261 [VM_MODE_PXXV48_4K] = { 0, 0, 0x1000, 12 }, 262 [VM_MODE_P47V64_4K] = { 47, 64, 0x1000, 12 }, 263 [VM_MODE_P44V64_4K] = { 44, 64, 0x1000, 12 }, 264 [VM_MODE_P36V48_4K] = { 36, 48, 0x1000, 12 }, 265 [VM_MODE_P36V48_16K] = { 36, 48, 0x4000, 14 }, 266 [VM_MODE_P36V48_64K] = { 36, 48, 0x10000, 16 }, 267 [VM_MODE_P47V47_16K] = { 47, 47, 0x4000, 14 }, 268 [VM_MODE_P36V47_16K] = { 36, 47, 0x4000, 14 }, 269 }; 270 _Static_assert(sizeof(vm_guest_mode_params)/sizeof(struct vm_guest_mode_params) == NUM_VM_MODES, 271 "Missing new mode params?"); 272 273 /* 274 * Initializes vm->vpages_valid to match the canonical VA space of the 275 * architecture. 276 * 277 * The default implementation is valid for architectures which split the 278 * range addressed by a single page table into a low and high region 279 * based on the MSB of the VA. On architectures with this behavior 280 * the VA region spans [0, 2^(va_bits - 1)), [-(2^(va_bits - 1), -1]. 281 */ 282 __weak void vm_vaddr_populate_bitmap(struct kvm_vm *vm) 283 { 284 sparsebit_set_num(vm->vpages_valid, 285 0, (1ULL << (vm->va_bits - 1)) >> vm->page_shift); 286 sparsebit_set_num(vm->vpages_valid, 287 (~((1ULL << (vm->va_bits - 1)) - 1)) >> vm->page_shift, 288 (1ULL << (vm->va_bits - 1)) >> vm->page_shift); 289 } 290 291 struct kvm_vm *____vm_create(struct vm_shape shape) 292 { 293 struct kvm_vm *vm; 294 295 vm = calloc(1, sizeof(*vm)); 296 TEST_ASSERT(vm != NULL, "Insufficient Memory"); 297 298 INIT_LIST_HEAD(&vm->vcpus); 299 vm->regions.gpa_tree = RB_ROOT; 300 vm->regions.hva_tree = RB_ROOT; 301 hash_init(vm->regions.slot_hash); 302 303 vm->mode = shape.mode; 304 vm->type = shape.type; 305 306 vm->pa_bits = vm_guest_mode_params[vm->mode].pa_bits; 307 vm->va_bits = vm_guest_mode_params[vm->mode].va_bits; 308 vm->page_size = vm_guest_mode_params[vm->mode].page_size; 309 vm->page_shift = vm_guest_mode_params[vm->mode].page_shift; 310 311 /* Setup mode specific traits. */ 312 switch (vm->mode) { 313 case VM_MODE_P52V48_4K: 314 vm->pgtable_levels = 4; 315 break; 316 case VM_MODE_P52V48_64K: 317 vm->pgtable_levels = 3; 318 break; 319 case VM_MODE_P48V48_4K: 320 vm->pgtable_levels = 4; 321 break; 322 case VM_MODE_P48V48_64K: 323 vm->pgtable_levels = 3; 324 break; 325 case VM_MODE_P40V48_4K: 326 case VM_MODE_P36V48_4K: 327 vm->pgtable_levels = 4; 328 break; 329 case VM_MODE_P40V48_64K: 330 case VM_MODE_P36V48_64K: 331 vm->pgtable_levels = 3; 332 break; 333 case VM_MODE_P52V48_16K: 334 case VM_MODE_P48V48_16K: 335 case VM_MODE_P40V48_16K: 336 case VM_MODE_P36V48_16K: 337 vm->pgtable_levels = 4; 338 break; 339 case VM_MODE_P47V47_16K: 340 case VM_MODE_P36V47_16K: 341 vm->pgtable_levels = 3; 342 break; 343 case VM_MODE_PXXV48_4K: 344 #ifdef __x86_64__ 345 kvm_get_cpu_address_width(&vm->pa_bits, &vm->va_bits); 346 kvm_init_vm_address_properties(vm); 347 /* 348 * Ignore KVM support for 5-level paging (vm->va_bits == 57), 349 * it doesn't take effect unless a CR4.LA57 is set, which it 350 * isn't for this mode (48-bit virtual address space). 351 */ 352 TEST_ASSERT(vm->va_bits == 48 || vm->va_bits == 57, 353 "Linear address width (%d bits) not supported", 354 vm->va_bits); 355 pr_debug("Guest physical address width detected: %d\n", 356 vm->pa_bits); 357 vm->pgtable_levels = 4; 358 vm->va_bits = 48; 359 #else 360 TEST_FAIL("VM_MODE_PXXV48_4K not supported on non-x86 platforms"); 361 #endif 362 break; 363 case VM_MODE_P47V64_4K: 364 vm->pgtable_levels = 5; 365 break; 366 case VM_MODE_P44V64_4K: 367 vm->pgtable_levels = 5; 368 break; 369 default: 370 TEST_FAIL("Unknown guest mode: 0x%x", vm->mode); 371 } 372 373 #ifdef __aarch64__ 374 TEST_ASSERT(!vm->type, "ARM doesn't support test-provided types"); 375 if (vm->pa_bits != 40) 376 vm->type = KVM_VM_TYPE_ARM_IPA_SIZE(vm->pa_bits); 377 #endif 378 379 vm_open(vm); 380 381 /* Limit to VA-bit canonical virtual addresses. */ 382 vm->vpages_valid = sparsebit_alloc(); 383 vm_vaddr_populate_bitmap(vm); 384 385 /* Limit physical addresses to PA-bits. */ 386 vm->max_gfn = vm_compute_max_gfn(vm); 387 388 /* Allocate and setup memory for guest. */ 389 vm->vpages_mapped = sparsebit_alloc(); 390 391 return vm; 392 } 393 394 static uint64_t vm_nr_pages_required(enum vm_guest_mode mode, 395 uint32_t nr_runnable_vcpus, 396 uint64_t extra_mem_pages) 397 { 398 uint64_t page_size = vm_guest_mode_params[mode].page_size; 399 uint64_t nr_pages; 400 401 TEST_ASSERT(nr_runnable_vcpus, 402 "Use vm_create_barebones() for VMs that _never_ have vCPUs"); 403 404 TEST_ASSERT(nr_runnable_vcpus <= kvm_check_cap(KVM_CAP_MAX_VCPUS), 405 "nr_vcpus = %d too large for host, max-vcpus = %d", 406 nr_runnable_vcpus, kvm_check_cap(KVM_CAP_MAX_VCPUS)); 407 408 /* 409 * Arbitrarily allocate 512 pages (2mb when page size is 4kb) for the 410 * test code and other per-VM assets that will be loaded into memslot0. 411 */ 412 nr_pages = 512; 413 414 /* Account for the per-vCPU stacks on behalf of the test. */ 415 nr_pages += nr_runnable_vcpus * DEFAULT_STACK_PGS; 416 417 /* 418 * Account for the number of pages needed for the page tables. The 419 * maximum page table size for a memory region will be when the 420 * smallest page size is used. Considering each page contains x page 421 * table descriptors, the total extra size for page tables (for extra 422 * N pages) will be: N/x+N/x^2+N/x^3+... which is definitely smaller 423 * than N/x*2. 424 */ 425 nr_pages += (nr_pages + extra_mem_pages) / PTES_PER_MIN_PAGE * 2; 426 427 /* Account for the number of pages needed by ucall. */ 428 nr_pages += ucall_nr_pages_required(page_size); 429 430 return vm_adjust_num_guest_pages(mode, nr_pages); 431 } 432 433 void kvm_set_files_rlimit(uint32_t nr_vcpus) 434 { 435 /* 436 * Each vCPU will open two file descriptors: the vCPU itself and the 437 * vCPU's binary stats file descriptor. Add an arbitrary amount of 438 * buffer for all other files a test may open. 439 */ 440 int nr_fds_wanted = nr_vcpus * 2 + 100; 441 struct rlimit rl; 442 443 /* 444 * Check that we're allowed to open nr_fds_wanted file descriptors and 445 * try raising the limits if needed. 446 */ 447 TEST_ASSERT(!getrlimit(RLIMIT_NOFILE, &rl), "getrlimit() failed!"); 448 449 if (rl.rlim_cur < nr_fds_wanted) { 450 rl.rlim_cur = nr_fds_wanted; 451 if (rl.rlim_max < nr_fds_wanted) { 452 int old_rlim_max = rl.rlim_max; 453 454 rl.rlim_max = nr_fds_wanted; 455 __TEST_REQUIRE(setrlimit(RLIMIT_NOFILE, &rl) >= 0, 456 "RLIMIT_NOFILE hard limit is too low (%d, wanted %d)", 457 old_rlim_max, nr_fds_wanted); 458 } else { 459 TEST_ASSERT(!setrlimit(RLIMIT_NOFILE, &rl), "setrlimit() failed!"); 460 } 461 } 462 463 } 464 465 static bool is_guest_memfd_required(struct vm_shape shape) 466 { 467 #ifdef __x86_64__ 468 return shape.type == KVM_X86_SNP_VM; 469 #else 470 return false; 471 #endif 472 } 473 474 struct kvm_vm *__vm_create(struct vm_shape shape, uint32_t nr_runnable_vcpus, 475 uint64_t nr_extra_pages) 476 { 477 uint64_t nr_pages = vm_nr_pages_required(shape.mode, nr_runnable_vcpus, 478 nr_extra_pages); 479 struct userspace_mem_region *slot0; 480 struct kvm_vm *vm; 481 int i, flags; 482 483 kvm_set_files_rlimit(nr_runnable_vcpus); 484 485 pr_debug("%s: mode='%s' type='%d', pages='%ld'\n", __func__, 486 vm_guest_mode_string(shape.mode), shape.type, nr_pages); 487 488 vm = ____vm_create(shape); 489 490 /* 491 * Force GUEST_MEMFD for the primary memory region if necessary, e.g. 492 * for CoCo VMs that require GUEST_MEMFD backed private memory. 493 */ 494 flags = 0; 495 if (is_guest_memfd_required(shape)) 496 flags |= KVM_MEM_GUEST_MEMFD; 497 498 vm_userspace_mem_region_add(vm, VM_MEM_SRC_ANONYMOUS, 0, 0, nr_pages, flags); 499 for (i = 0; i < NR_MEM_REGIONS; i++) 500 vm->memslots[i] = 0; 501 502 kvm_vm_elf_load(vm, program_invocation_name); 503 504 /* 505 * TODO: Add proper defines to protect the library's memslots, and then 506 * carve out memslot1 for the ucall MMIO address. KVM treats writes to 507 * read-only memslots as MMIO, and creating a read-only memslot for the 508 * MMIO region would prevent silently clobbering the MMIO region. 509 */ 510 slot0 = memslot2region(vm, 0); 511 ucall_init(vm, slot0->region.guest_phys_addr + slot0->region.memory_size); 512 513 if (guest_random_seed != last_guest_seed) { 514 pr_info("Random seed: 0x%x\n", guest_random_seed); 515 last_guest_seed = guest_random_seed; 516 } 517 guest_rng = new_guest_random_state(guest_random_seed); 518 sync_global_to_guest(vm, guest_rng); 519 520 kvm_arch_vm_post_create(vm, nr_runnable_vcpus); 521 522 return vm; 523 } 524 525 /* 526 * VM Create with customized parameters 527 * 528 * Input Args: 529 * mode - VM Mode (e.g. VM_MODE_P52V48_4K) 530 * nr_vcpus - VCPU count 531 * extra_mem_pages - Non-slot0 physical memory total size 532 * guest_code - Guest entry point 533 * vcpuids - VCPU IDs 534 * 535 * Output Args: None 536 * 537 * Return: 538 * Pointer to opaque structure that describes the created VM. 539 * 540 * Creates a VM with the mode specified by mode (e.g. VM_MODE_P52V48_4K). 541 * extra_mem_pages is only used to calculate the maximum page table size, 542 * no real memory allocation for non-slot0 memory in this function. 543 */ 544 struct kvm_vm *__vm_create_with_vcpus(struct vm_shape shape, uint32_t nr_vcpus, 545 uint64_t extra_mem_pages, 546 void *guest_code, struct kvm_vcpu *vcpus[]) 547 { 548 struct kvm_vm *vm; 549 int i; 550 551 TEST_ASSERT(!nr_vcpus || vcpus, "Must provide vCPU array"); 552 553 vm = __vm_create(shape, nr_vcpus, extra_mem_pages); 554 555 for (i = 0; i < nr_vcpus; ++i) 556 vcpus[i] = vm_vcpu_add(vm, i, guest_code); 557 558 kvm_arch_vm_finalize_vcpus(vm); 559 return vm; 560 } 561 562 struct kvm_vm *__vm_create_shape_with_one_vcpu(struct vm_shape shape, 563 struct kvm_vcpu **vcpu, 564 uint64_t extra_mem_pages, 565 void *guest_code) 566 { 567 struct kvm_vcpu *vcpus[1]; 568 struct kvm_vm *vm; 569 570 vm = __vm_create_with_vcpus(shape, 1, extra_mem_pages, guest_code, vcpus); 571 572 *vcpu = vcpus[0]; 573 return vm; 574 } 575 576 /* 577 * VM Restart 578 * 579 * Input Args: 580 * vm - VM that has been released before 581 * 582 * Output Args: None 583 * 584 * Reopens the file descriptors associated to the VM and reinstates the 585 * global state, such as the irqchip and the memory regions that are mapped 586 * into the guest. 587 */ 588 void kvm_vm_restart(struct kvm_vm *vmp) 589 { 590 int ctr; 591 struct userspace_mem_region *region; 592 593 vm_open(vmp); 594 if (vmp->has_irqchip) 595 vm_create_irqchip(vmp); 596 597 hash_for_each(vmp->regions.slot_hash, ctr, region, slot_node) { 598 int ret = ioctl(vmp->fd, KVM_SET_USER_MEMORY_REGION2, ®ion->region); 599 600 TEST_ASSERT(ret == 0, "KVM_SET_USER_MEMORY_REGION2 IOCTL failed,\n" 601 " rc: %i errno: %i\n" 602 " slot: %u flags: 0x%x\n" 603 " guest_phys_addr: 0x%llx size: 0x%llx", 604 ret, errno, region->region.slot, 605 region->region.flags, 606 region->region.guest_phys_addr, 607 region->region.memory_size); 608 } 609 } 610 611 __weak struct kvm_vcpu *vm_arch_vcpu_recreate(struct kvm_vm *vm, 612 uint32_t vcpu_id) 613 { 614 return __vm_vcpu_add(vm, vcpu_id); 615 } 616 617 struct kvm_vcpu *vm_recreate_with_one_vcpu(struct kvm_vm *vm) 618 { 619 kvm_vm_restart(vm); 620 621 return vm_vcpu_recreate(vm, 0); 622 } 623 624 int __pin_task_to_cpu(pthread_t task, int cpu) 625 { 626 cpu_set_t cpuset; 627 628 CPU_ZERO(&cpuset); 629 CPU_SET(cpu, &cpuset); 630 631 return pthread_setaffinity_np(task, sizeof(cpuset), &cpuset); 632 } 633 634 static uint32_t parse_pcpu(const char *cpu_str, const cpu_set_t *allowed_mask) 635 { 636 uint32_t pcpu = atoi_non_negative("CPU number", cpu_str); 637 638 TEST_ASSERT(CPU_ISSET(pcpu, allowed_mask), 639 "Not allowed to run on pCPU '%d', check cgroups?", pcpu); 640 return pcpu; 641 } 642 643 void kvm_print_vcpu_pinning_help(void) 644 { 645 const char *name = program_invocation_name; 646 647 printf(" -c: Pin tasks to physical CPUs. Takes a list of comma separated\n" 648 " values (target pCPU), one for each vCPU, plus an optional\n" 649 " entry for the main application task (specified via entry\n" 650 " <nr_vcpus + 1>). If used, entries must be provided for all\n" 651 " vCPUs, i.e. pinning vCPUs is all or nothing.\n\n" 652 " E.g. to create 3 vCPUs, pin vCPU0=>pCPU22, vCPU1=>pCPU23,\n" 653 " vCPU2=>pCPU24, and pin the application task to pCPU50:\n\n" 654 " %s -v 3 -c 22,23,24,50\n\n" 655 " To leave the application task unpinned, drop the final entry:\n\n" 656 " %s -v 3 -c 22,23,24\n\n" 657 " (default: no pinning)\n", name, name); 658 } 659 660 void kvm_parse_vcpu_pinning(const char *pcpus_string, uint32_t vcpu_to_pcpu[], 661 int nr_vcpus) 662 { 663 cpu_set_t allowed_mask; 664 char *cpu, *cpu_list; 665 char delim[2] = ","; 666 int i, r; 667 668 cpu_list = strdup(pcpus_string); 669 TEST_ASSERT(cpu_list, "strdup() allocation failed."); 670 671 r = sched_getaffinity(0, sizeof(allowed_mask), &allowed_mask); 672 TEST_ASSERT(!r, "sched_getaffinity() failed"); 673 674 cpu = strtok(cpu_list, delim); 675 676 /* 1. Get all pcpus for vcpus. */ 677 for (i = 0; i < nr_vcpus; i++) { 678 TEST_ASSERT(cpu, "pCPU not provided for vCPU '%d'", i); 679 vcpu_to_pcpu[i] = parse_pcpu(cpu, &allowed_mask); 680 cpu = strtok(NULL, delim); 681 } 682 683 /* 2. Check if the main worker needs to be pinned. */ 684 if (cpu) { 685 pin_self_to_cpu(parse_pcpu(cpu, &allowed_mask)); 686 cpu = strtok(NULL, delim); 687 } 688 689 TEST_ASSERT(!cpu, "pCPU list contains trailing garbage characters '%s'", cpu); 690 free(cpu_list); 691 } 692 693 /* 694 * Userspace Memory Region Find 695 * 696 * Input Args: 697 * vm - Virtual Machine 698 * start - Starting VM physical address 699 * end - Ending VM physical address, inclusive. 700 * 701 * Output Args: None 702 * 703 * Return: 704 * Pointer to overlapping region, NULL if no such region. 705 * 706 * Searches for a region with any physical memory that overlaps with 707 * any portion of the guest physical addresses from start to end 708 * inclusive. If multiple overlapping regions exist, a pointer to any 709 * of the regions is returned. Null is returned only when no overlapping 710 * region exists. 711 */ 712 static struct userspace_mem_region * 713 userspace_mem_region_find(struct kvm_vm *vm, uint64_t start, uint64_t end) 714 { 715 struct rb_node *node; 716 717 for (node = vm->regions.gpa_tree.rb_node; node; ) { 718 struct userspace_mem_region *region = 719 container_of(node, struct userspace_mem_region, gpa_node); 720 uint64_t existing_start = region->region.guest_phys_addr; 721 uint64_t existing_end = region->region.guest_phys_addr 722 + region->region.memory_size - 1; 723 if (start <= existing_end && end >= existing_start) 724 return region; 725 726 if (start < existing_start) 727 node = node->rb_left; 728 else 729 node = node->rb_right; 730 } 731 732 return NULL; 733 } 734 735 static void kvm_stats_release(struct kvm_binary_stats *stats) 736 { 737 int ret; 738 739 if (stats->fd < 0) 740 return; 741 742 if (stats->desc) { 743 free(stats->desc); 744 stats->desc = NULL; 745 } 746 747 ret = close(stats->fd); 748 TEST_ASSERT(!ret, __KVM_SYSCALL_ERROR("close()", ret)); 749 stats->fd = -1; 750 } 751 752 __weak void vcpu_arch_free(struct kvm_vcpu *vcpu) 753 { 754 755 } 756 757 /* 758 * VM VCPU Remove 759 * 760 * Input Args: 761 * vcpu - VCPU to remove 762 * 763 * Output Args: None 764 * 765 * Return: None, TEST_ASSERT failures for all error conditions 766 * 767 * Removes a vCPU from a VM and frees its resources. 768 */ 769 static void vm_vcpu_rm(struct kvm_vm *vm, struct kvm_vcpu *vcpu) 770 { 771 int ret; 772 773 if (vcpu->dirty_gfns) { 774 ret = munmap(vcpu->dirty_gfns, vm->dirty_ring_size); 775 TEST_ASSERT(!ret, __KVM_SYSCALL_ERROR("munmap()", ret)); 776 vcpu->dirty_gfns = NULL; 777 } 778 779 ret = munmap(vcpu->run, vcpu_mmap_sz()); 780 TEST_ASSERT(!ret, __KVM_SYSCALL_ERROR("munmap()", ret)); 781 782 ret = close(vcpu->fd); 783 TEST_ASSERT(!ret, __KVM_SYSCALL_ERROR("close()", ret)); 784 785 kvm_stats_release(&vcpu->stats); 786 787 list_del(&vcpu->list); 788 789 vcpu_arch_free(vcpu); 790 free(vcpu); 791 } 792 793 void kvm_vm_release(struct kvm_vm *vmp) 794 { 795 struct kvm_vcpu *vcpu, *tmp; 796 int ret; 797 798 list_for_each_entry_safe(vcpu, tmp, &vmp->vcpus, list) 799 vm_vcpu_rm(vmp, vcpu); 800 801 ret = close(vmp->fd); 802 TEST_ASSERT(!ret, __KVM_SYSCALL_ERROR("close()", ret)); 803 804 ret = close(vmp->kvm_fd); 805 TEST_ASSERT(!ret, __KVM_SYSCALL_ERROR("close()", ret)); 806 807 /* Free cached stats metadata and close FD */ 808 kvm_stats_release(&vmp->stats); 809 810 kvm_arch_vm_release(vmp); 811 } 812 813 static void __vm_mem_region_delete(struct kvm_vm *vm, 814 struct userspace_mem_region *region) 815 { 816 int ret; 817 818 rb_erase(®ion->gpa_node, &vm->regions.gpa_tree); 819 rb_erase(®ion->hva_node, &vm->regions.hva_tree); 820 hash_del(®ion->slot_node); 821 822 sparsebit_free(®ion->unused_phy_pages); 823 sparsebit_free(®ion->protected_phy_pages); 824 ret = munmap(region->mmap_start, region->mmap_size); 825 TEST_ASSERT(!ret, __KVM_SYSCALL_ERROR("munmap()", ret)); 826 if (region->fd >= 0) { 827 /* There's an extra map when using shared memory. */ 828 ret = munmap(region->mmap_alias, region->mmap_size); 829 TEST_ASSERT(!ret, __KVM_SYSCALL_ERROR("munmap()", ret)); 830 close(region->fd); 831 } 832 if (region->region.guest_memfd >= 0) 833 close(region->region.guest_memfd); 834 835 free(region); 836 } 837 838 /* 839 * Destroys and frees the VM pointed to by vmp. 840 */ 841 void kvm_vm_free(struct kvm_vm *vmp) 842 { 843 int ctr; 844 struct hlist_node *node; 845 struct userspace_mem_region *region; 846 847 if (vmp == NULL) 848 return; 849 850 /* Free userspace_mem_regions. */ 851 hash_for_each_safe(vmp->regions.slot_hash, ctr, node, region, slot_node) 852 __vm_mem_region_delete(vmp, region); 853 854 /* Free sparsebit arrays. */ 855 sparsebit_free(&vmp->vpages_valid); 856 sparsebit_free(&vmp->vpages_mapped); 857 858 kvm_vm_release(vmp); 859 860 /* Free the structure describing the VM. */ 861 free(vmp); 862 } 863 864 int kvm_memfd_alloc(size_t size, bool hugepages) 865 { 866 int memfd_flags = MFD_CLOEXEC; 867 int fd, r; 868 869 if (hugepages) 870 memfd_flags |= MFD_HUGETLB; 871 872 fd = memfd_create("kvm_selftest", memfd_flags); 873 TEST_ASSERT(fd != -1, __KVM_SYSCALL_ERROR("memfd_create()", fd)); 874 875 r = ftruncate(fd, size); 876 TEST_ASSERT(!r, __KVM_SYSCALL_ERROR("ftruncate()", r)); 877 878 r = fallocate(fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE, 0, size); 879 TEST_ASSERT(!r, __KVM_SYSCALL_ERROR("fallocate()", r)); 880 881 return fd; 882 } 883 884 static void vm_userspace_mem_region_gpa_insert(struct rb_root *gpa_tree, 885 struct userspace_mem_region *region) 886 { 887 struct rb_node **cur, *parent; 888 889 for (cur = &gpa_tree->rb_node, parent = NULL; *cur; ) { 890 struct userspace_mem_region *cregion; 891 892 cregion = container_of(*cur, typeof(*cregion), gpa_node); 893 parent = *cur; 894 if (region->region.guest_phys_addr < 895 cregion->region.guest_phys_addr) 896 cur = &(*cur)->rb_left; 897 else { 898 TEST_ASSERT(region->region.guest_phys_addr != 899 cregion->region.guest_phys_addr, 900 "Duplicate GPA in region tree"); 901 902 cur = &(*cur)->rb_right; 903 } 904 } 905 906 rb_link_node(®ion->gpa_node, parent, cur); 907 rb_insert_color(®ion->gpa_node, gpa_tree); 908 } 909 910 static void vm_userspace_mem_region_hva_insert(struct rb_root *hva_tree, 911 struct userspace_mem_region *region) 912 { 913 struct rb_node **cur, *parent; 914 915 for (cur = &hva_tree->rb_node, parent = NULL; *cur; ) { 916 struct userspace_mem_region *cregion; 917 918 cregion = container_of(*cur, typeof(*cregion), hva_node); 919 parent = *cur; 920 if (region->host_mem < cregion->host_mem) 921 cur = &(*cur)->rb_left; 922 else { 923 TEST_ASSERT(region->host_mem != 924 cregion->host_mem, 925 "Duplicate HVA in region tree"); 926 927 cur = &(*cur)->rb_right; 928 } 929 } 930 931 rb_link_node(®ion->hva_node, parent, cur); 932 rb_insert_color(®ion->hva_node, hva_tree); 933 } 934 935 936 int __vm_set_user_memory_region(struct kvm_vm *vm, uint32_t slot, uint32_t flags, 937 uint64_t gpa, uint64_t size, void *hva) 938 { 939 struct kvm_userspace_memory_region region = { 940 .slot = slot, 941 .flags = flags, 942 .guest_phys_addr = gpa, 943 .memory_size = size, 944 .userspace_addr = (uintptr_t)hva, 945 }; 946 947 return ioctl(vm->fd, KVM_SET_USER_MEMORY_REGION, ®ion); 948 } 949 950 void vm_set_user_memory_region(struct kvm_vm *vm, uint32_t slot, uint32_t flags, 951 uint64_t gpa, uint64_t size, void *hva) 952 { 953 int ret = __vm_set_user_memory_region(vm, slot, flags, gpa, size, hva); 954 955 TEST_ASSERT(!ret, "KVM_SET_USER_MEMORY_REGION failed, errno = %d (%s)", 956 errno, strerror(errno)); 957 } 958 959 #define TEST_REQUIRE_SET_USER_MEMORY_REGION2() \ 960 __TEST_REQUIRE(kvm_has_cap(KVM_CAP_USER_MEMORY2), \ 961 "KVM selftests now require KVM_SET_USER_MEMORY_REGION2 (introduced in v6.8)") 962 963 int __vm_set_user_memory_region2(struct kvm_vm *vm, uint32_t slot, uint32_t flags, 964 uint64_t gpa, uint64_t size, void *hva, 965 uint32_t guest_memfd, uint64_t guest_memfd_offset) 966 { 967 struct kvm_userspace_memory_region2 region = { 968 .slot = slot, 969 .flags = flags, 970 .guest_phys_addr = gpa, 971 .memory_size = size, 972 .userspace_addr = (uintptr_t)hva, 973 .guest_memfd = guest_memfd, 974 .guest_memfd_offset = guest_memfd_offset, 975 }; 976 977 TEST_REQUIRE_SET_USER_MEMORY_REGION2(); 978 979 return ioctl(vm->fd, KVM_SET_USER_MEMORY_REGION2, ®ion); 980 } 981 982 void vm_set_user_memory_region2(struct kvm_vm *vm, uint32_t slot, uint32_t flags, 983 uint64_t gpa, uint64_t size, void *hva, 984 uint32_t guest_memfd, uint64_t guest_memfd_offset) 985 { 986 int ret = __vm_set_user_memory_region2(vm, slot, flags, gpa, size, hva, 987 guest_memfd, guest_memfd_offset); 988 989 TEST_ASSERT(!ret, "KVM_SET_USER_MEMORY_REGION2 failed, errno = %d (%s)", 990 errno, strerror(errno)); 991 } 992 993 994 /* FIXME: This thing needs to be ripped apart and rewritten. */ 995 void vm_mem_add(struct kvm_vm *vm, enum vm_mem_backing_src_type src_type, 996 uint64_t guest_paddr, uint32_t slot, uint64_t npages, 997 uint32_t flags, int guest_memfd, uint64_t guest_memfd_offset) 998 { 999 int ret; 1000 struct userspace_mem_region *region; 1001 size_t backing_src_pagesz = get_backing_src_pagesz(src_type); 1002 size_t mem_size = npages * vm->page_size; 1003 size_t alignment; 1004 1005 TEST_REQUIRE_SET_USER_MEMORY_REGION2(); 1006 1007 TEST_ASSERT(vm_adjust_num_guest_pages(vm->mode, npages) == npages, 1008 "Number of guest pages is not compatible with the host. " 1009 "Try npages=%d", vm_adjust_num_guest_pages(vm->mode, npages)); 1010 1011 TEST_ASSERT((guest_paddr % vm->page_size) == 0, "Guest physical " 1012 "address not on a page boundary.\n" 1013 " guest_paddr: 0x%lx vm->page_size: 0x%x", 1014 guest_paddr, vm->page_size); 1015 TEST_ASSERT((((guest_paddr >> vm->page_shift) + npages) - 1) 1016 <= vm->max_gfn, "Physical range beyond maximum " 1017 "supported physical address,\n" 1018 " guest_paddr: 0x%lx npages: 0x%lx\n" 1019 " vm->max_gfn: 0x%lx vm->page_size: 0x%x", 1020 guest_paddr, npages, vm->max_gfn, vm->page_size); 1021 1022 /* 1023 * Confirm a mem region with an overlapping address doesn't 1024 * already exist. 1025 */ 1026 region = (struct userspace_mem_region *) userspace_mem_region_find( 1027 vm, guest_paddr, (guest_paddr + npages * vm->page_size) - 1); 1028 if (region != NULL) 1029 TEST_FAIL("overlapping userspace_mem_region already " 1030 "exists\n" 1031 " requested guest_paddr: 0x%lx npages: 0x%lx " 1032 "page_size: 0x%x\n" 1033 " existing guest_paddr: 0x%lx size: 0x%lx", 1034 guest_paddr, npages, vm->page_size, 1035 (uint64_t) region->region.guest_phys_addr, 1036 (uint64_t) region->region.memory_size); 1037 1038 /* Confirm no region with the requested slot already exists. */ 1039 hash_for_each_possible(vm->regions.slot_hash, region, slot_node, 1040 slot) { 1041 if (region->region.slot != slot) 1042 continue; 1043 1044 TEST_FAIL("A mem region with the requested slot " 1045 "already exists.\n" 1046 " requested slot: %u paddr: 0x%lx npages: 0x%lx\n" 1047 " existing slot: %u paddr: 0x%lx size: 0x%lx", 1048 slot, guest_paddr, npages, 1049 region->region.slot, 1050 (uint64_t) region->region.guest_phys_addr, 1051 (uint64_t) region->region.memory_size); 1052 } 1053 1054 /* Allocate and initialize new mem region structure. */ 1055 region = calloc(1, sizeof(*region)); 1056 TEST_ASSERT(region != NULL, "Insufficient Memory"); 1057 region->mmap_size = mem_size; 1058 1059 #ifdef __s390x__ 1060 /* On s390x, the host address must be aligned to 1M (due to PGSTEs) */ 1061 alignment = 0x100000; 1062 #else 1063 alignment = 1; 1064 #endif 1065 1066 /* 1067 * When using THP mmap is not guaranteed to returned a hugepage aligned 1068 * address so we have to pad the mmap. Padding is not needed for HugeTLB 1069 * because mmap will always return an address aligned to the HugeTLB 1070 * page size. 1071 */ 1072 if (src_type == VM_MEM_SRC_ANONYMOUS_THP) 1073 alignment = max(backing_src_pagesz, alignment); 1074 1075 TEST_ASSERT_EQ(guest_paddr, align_up(guest_paddr, backing_src_pagesz)); 1076 1077 /* Add enough memory to align up if necessary */ 1078 if (alignment > 1) 1079 region->mmap_size += alignment; 1080 1081 region->fd = -1; 1082 if (backing_src_is_shared(src_type)) 1083 region->fd = kvm_memfd_alloc(region->mmap_size, 1084 src_type == VM_MEM_SRC_SHARED_HUGETLB); 1085 1086 region->mmap_start = mmap(NULL, region->mmap_size, 1087 PROT_READ | PROT_WRITE, 1088 vm_mem_backing_src_alias(src_type)->flag, 1089 region->fd, 0); 1090 TEST_ASSERT(region->mmap_start != MAP_FAILED, 1091 __KVM_SYSCALL_ERROR("mmap()", (int)(unsigned long)MAP_FAILED)); 1092 1093 TEST_ASSERT(!is_backing_src_hugetlb(src_type) || 1094 region->mmap_start == align_ptr_up(region->mmap_start, backing_src_pagesz), 1095 "mmap_start %p is not aligned to HugeTLB page size 0x%lx", 1096 region->mmap_start, backing_src_pagesz); 1097 1098 /* Align host address */ 1099 region->host_mem = align_ptr_up(region->mmap_start, alignment); 1100 1101 /* As needed perform madvise */ 1102 if ((src_type == VM_MEM_SRC_ANONYMOUS || 1103 src_type == VM_MEM_SRC_ANONYMOUS_THP) && thp_configured()) { 1104 ret = madvise(region->host_mem, mem_size, 1105 src_type == VM_MEM_SRC_ANONYMOUS ? MADV_NOHUGEPAGE : MADV_HUGEPAGE); 1106 TEST_ASSERT(ret == 0, "madvise failed, addr: %p length: 0x%lx src_type: %s", 1107 region->host_mem, mem_size, 1108 vm_mem_backing_src_alias(src_type)->name); 1109 } 1110 1111 region->backing_src_type = src_type; 1112 1113 if (flags & KVM_MEM_GUEST_MEMFD) { 1114 if (guest_memfd < 0) { 1115 uint32_t guest_memfd_flags = 0; 1116 TEST_ASSERT(!guest_memfd_offset, 1117 "Offset must be zero when creating new guest_memfd"); 1118 guest_memfd = vm_create_guest_memfd(vm, mem_size, guest_memfd_flags); 1119 } else { 1120 /* 1121 * Install a unique fd for each memslot so that the fd 1122 * can be closed when the region is deleted without 1123 * needing to track if the fd is owned by the framework 1124 * or by the caller. 1125 */ 1126 guest_memfd = dup(guest_memfd); 1127 TEST_ASSERT(guest_memfd >= 0, __KVM_SYSCALL_ERROR("dup()", guest_memfd)); 1128 } 1129 1130 region->region.guest_memfd = guest_memfd; 1131 region->region.guest_memfd_offset = guest_memfd_offset; 1132 } else { 1133 region->region.guest_memfd = -1; 1134 } 1135 1136 region->unused_phy_pages = sparsebit_alloc(); 1137 if (vm_arch_has_protected_memory(vm)) 1138 region->protected_phy_pages = sparsebit_alloc(); 1139 sparsebit_set_num(region->unused_phy_pages, 1140 guest_paddr >> vm->page_shift, npages); 1141 region->region.slot = slot; 1142 region->region.flags = flags; 1143 region->region.guest_phys_addr = guest_paddr; 1144 region->region.memory_size = npages * vm->page_size; 1145 region->region.userspace_addr = (uintptr_t) region->host_mem; 1146 ret = __vm_ioctl(vm, KVM_SET_USER_MEMORY_REGION2, ®ion->region); 1147 TEST_ASSERT(ret == 0, "KVM_SET_USER_MEMORY_REGION2 IOCTL failed,\n" 1148 " rc: %i errno: %i\n" 1149 " slot: %u flags: 0x%x\n" 1150 " guest_phys_addr: 0x%lx size: 0x%lx guest_memfd: %d", 1151 ret, errno, slot, flags, 1152 guest_paddr, (uint64_t) region->region.memory_size, 1153 region->region.guest_memfd); 1154 1155 /* Add to quick lookup data structures */ 1156 vm_userspace_mem_region_gpa_insert(&vm->regions.gpa_tree, region); 1157 vm_userspace_mem_region_hva_insert(&vm->regions.hva_tree, region); 1158 hash_add(vm->regions.slot_hash, ®ion->slot_node, slot); 1159 1160 /* If shared memory, create an alias. */ 1161 if (region->fd >= 0) { 1162 region->mmap_alias = mmap(NULL, region->mmap_size, 1163 PROT_READ | PROT_WRITE, 1164 vm_mem_backing_src_alias(src_type)->flag, 1165 region->fd, 0); 1166 TEST_ASSERT(region->mmap_alias != MAP_FAILED, 1167 __KVM_SYSCALL_ERROR("mmap()", (int)(unsigned long)MAP_FAILED)); 1168 1169 /* Align host alias address */ 1170 region->host_alias = align_ptr_up(region->mmap_alias, alignment); 1171 } 1172 } 1173 1174 void vm_userspace_mem_region_add(struct kvm_vm *vm, 1175 enum vm_mem_backing_src_type src_type, 1176 uint64_t guest_paddr, uint32_t slot, 1177 uint64_t npages, uint32_t flags) 1178 { 1179 vm_mem_add(vm, src_type, guest_paddr, slot, npages, flags, -1, 0); 1180 } 1181 1182 /* 1183 * Memslot to region 1184 * 1185 * Input Args: 1186 * vm - Virtual Machine 1187 * memslot - KVM memory slot ID 1188 * 1189 * Output Args: None 1190 * 1191 * Return: 1192 * Pointer to memory region structure that describe memory region 1193 * using kvm memory slot ID given by memslot. TEST_ASSERT failure 1194 * on error (e.g. currently no memory region using memslot as a KVM 1195 * memory slot ID). 1196 */ 1197 struct userspace_mem_region * 1198 memslot2region(struct kvm_vm *vm, uint32_t memslot) 1199 { 1200 struct userspace_mem_region *region; 1201 1202 hash_for_each_possible(vm->regions.slot_hash, region, slot_node, 1203 memslot) 1204 if (region->region.slot == memslot) 1205 return region; 1206 1207 fprintf(stderr, "No mem region with the requested slot found,\n" 1208 " requested slot: %u\n", memslot); 1209 fputs("---- vm dump ----\n", stderr); 1210 vm_dump(stderr, vm, 2); 1211 TEST_FAIL("Mem region not found"); 1212 return NULL; 1213 } 1214 1215 /* 1216 * VM Memory Region Flags Set 1217 * 1218 * Input Args: 1219 * vm - Virtual Machine 1220 * flags - Starting guest physical address 1221 * 1222 * Output Args: None 1223 * 1224 * Return: None 1225 * 1226 * Sets the flags of the memory region specified by the value of slot, 1227 * to the values given by flags. 1228 */ 1229 void vm_mem_region_set_flags(struct kvm_vm *vm, uint32_t slot, uint32_t flags) 1230 { 1231 int ret; 1232 struct userspace_mem_region *region; 1233 1234 region = memslot2region(vm, slot); 1235 1236 region->region.flags = flags; 1237 1238 ret = __vm_ioctl(vm, KVM_SET_USER_MEMORY_REGION2, ®ion->region); 1239 1240 TEST_ASSERT(ret == 0, "KVM_SET_USER_MEMORY_REGION2 IOCTL failed,\n" 1241 " rc: %i errno: %i slot: %u flags: 0x%x", 1242 ret, errno, slot, flags); 1243 } 1244 1245 /* 1246 * VM Memory Region Move 1247 * 1248 * Input Args: 1249 * vm - Virtual Machine 1250 * slot - Slot of the memory region to move 1251 * new_gpa - Starting guest physical address 1252 * 1253 * Output Args: None 1254 * 1255 * Return: None 1256 * 1257 * Change the gpa of a memory region. 1258 */ 1259 void vm_mem_region_move(struct kvm_vm *vm, uint32_t slot, uint64_t new_gpa) 1260 { 1261 struct userspace_mem_region *region; 1262 int ret; 1263 1264 region = memslot2region(vm, slot); 1265 1266 region->region.guest_phys_addr = new_gpa; 1267 1268 ret = __vm_ioctl(vm, KVM_SET_USER_MEMORY_REGION2, ®ion->region); 1269 1270 TEST_ASSERT(!ret, "KVM_SET_USER_MEMORY_REGION2 failed\n" 1271 "ret: %i errno: %i slot: %u new_gpa: 0x%lx", 1272 ret, errno, slot, new_gpa); 1273 } 1274 1275 /* 1276 * VM Memory Region Delete 1277 * 1278 * Input Args: 1279 * vm - Virtual Machine 1280 * slot - Slot of the memory region to delete 1281 * 1282 * Output Args: None 1283 * 1284 * Return: None 1285 * 1286 * Delete a memory region. 1287 */ 1288 void vm_mem_region_delete(struct kvm_vm *vm, uint32_t slot) 1289 { 1290 struct userspace_mem_region *region = memslot2region(vm, slot); 1291 1292 region->region.memory_size = 0; 1293 vm_ioctl(vm, KVM_SET_USER_MEMORY_REGION2, ®ion->region); 1294 1295 __vm_mem_region_delete(vm, region); 1296 } 1297 1298 void vm_guest_mem_fallocate(struct kvm_vm *vm, uint64_t base, uint64_t size, 1299 bool punch_hole) 1300 { 1301 const int mode = FALLOC_FL_KEEP_SIZE | (punch_hole ? FALLOC_FL_PUNCH_HOLE : 0); 1302 struct userspace_mem_region *region; 1303 uint64_t end = base + size; 1304 uint64_t gpa, len; 1305 off_t fd_offset; 1306 int ret; 1307 1308 for (gpa = base; gpa < end; gpa += len) { 1309 uint64_t offset; 1310 1311 region = userspace_mem_region_find(vm, gpa, gpa); 1312 TEST_ASSERT(region && region->region.flags & KVM_MEM_GUEST_MEMFD, 1313 "Private memory region not found for GPA 0x%lx", gpa); 1314 1315 offset = gpa - region->region.guest_phys_addr; 1316 fd_offset = region->region.guest_memfd_offset + offset; 1317 len = min_t(uint64_t, end - gpa, region->region.memory_size - offset); 1318 1319 ret = fallocate(region->region.guest_memfd, mode, fd_offset, len); 1320 TEST_ASSERT(!ret, "fallocate() failed to %s at %lx (len = %lu), fd = %d, mode = %x, offset = %lx", 1321 punch_hole ? "punch hole" : "allocate", gpa, len, 1322 region->region.guest_memfd, mode, fd_offset); 1323 } 1324 } 1325 1326 /* Returns the size of a vCPU's kvm_run structure. */ 1327 static int vcpu_mmap_sz(void) 1328 { 1329 int dev_fd, ret; 1330 1331 dev_fd = open_kvm_dev_path_or_exit(); 1332 1333 ret = ioctl(dev_fd, KVM_GET_VCPU_MMAP_SIZE, NULL); 1334 TEST_ASSERT(ret >= sizeof(struct kvm_run), 1335 KVM_IOCTL_ERROR(KVM_GET_VCPU_MMAP_SIZE, ret)); 1336 1337 close(dev_fd); 1338 1339 return ret; 1340 } 1341 1342 static bool vcpu_exists(struct kvm_vm *vm, uint32_t vcpu_id) 1343 { 1344 struct kvm_vcpu *vcpu; 1345 1346 list_for_each_entry(vcpu, &vm->vcpus, list) { 1347 if (vcpu->id == vcpu_id) 1348 return true; 1349 } 1350 1351 return false; 1352 } 1353 1354 /* 1355 * Adds a virtual CPU to the VM specified by vm with the ID given by vcpu_id. 1356 * No additional vCPU setup is done. Returns the vCPU. 1357 */ 1358 struct kvm_vcpu *__vm_vcpu_add(struct kvm_vm *vm, uint32_t vcpu_id) 1359 { 1360 struct kvm_vcpu *vcpu; 1361 1362 /* Confirm a vcpu with the specified id doesn't already exist. */ 1363 TEST_ASSERT(!vcpu_exists(vm, vcpu_id), "vCPU%d already exists", vcpu_id); 1364 1365 /* Allocate and initialize new vcpu structure. */ 1366 vcpu = calloc(1, sizeof(*vcpu)); 1367 TEST_ASSERT(vcpu != NULL, "Insufficient Memory"); 1368 1369 vcpu->vm = vm; 1370 vcpu->id = vcpu_id; 1371 vcpu->fd = __vm_ioctl(vm, KVM_CREATE_VCPU, (void *)(unsigned long)vcpu_id); 1372 TEST_ASSERT_VM_VCPU_IOCTL(vcpu->fd >= 0, KVM_CREATE_VCPU, vcpu->fd, vm); 1373 1374 TEST_ASSERT(vcpu_mmap_sz() >= sizeof(*vcpu->run), "vcpu mmap size " 1375 "smaller than expected, vcpu_mmap_sz: %i expected_min: %zi", 1376 vcpu_mmap_sz(), sizeof(*vcpu->run)); 1377 vcpu->run = (struct kvm_run *) mmap(NULL, vcpu_mmap_sz(), 1378 PROT_READ | PROT_WRITE, MAP_SHARED, vcpu->fd, 0); 1379 TEST_ASSERT(vcpu->run != MAP_FAILED, 1380 __KVM_SYSCALL_ERROR("mmap()", (int)(unsigned long)MAP_FAILED)); 1381 1382 if (kvm_has_cap(KVM_CAP_BINARY_STATS_FD)) 1383 vcpu->stats.fd = vcpu_get_stats_fd(vcpu); 1384 else 1385 vcpu->stats.fd = -1; 1386 1387 /* Add to linked-list of VCPUs. */ 1388 list_add(&vcpu->list, &vm->vcpus); 1389 1390 return vcpu; 1391 } 1392 1393 /* 1394 * VM Virtual Address Unused Gap 1395 * 1396 * Input Args: 1397 * vm - Virtual Machine 1398 * sz - Size (bytes) 1399 * vaddr_min - Minimum Virtual Address 1400 * 1401 * Output Args: None 1402 * 1403 * Return: 1404 * Lowest virtual address at or below vaddr_min, with at least 1405 * sz unused bytes. TEST_ASSERT failure if no area of at least 1406 * size sz is available. 1407 * 1408 * Within the VM specified by vm, locates the lowest starting virtual 1409 * address >= vaddr_min, that has at least sz unallocated bytes. A 1410 * TEST_ASSERT failure occurs for invalid input or no area of at least 1411 * sz unallocated bytes >= vaddr_min is available. 1412 */ 1413 vm_vaddr_t vm_vaddr_unused_gap(struct kvm_vm *vm, size_t sz, 1414 vm_vaddr_t vaddr_min) 1415 { 1416 uint64_t pages = (sz + vm->page_size - 1) >> vm->page_shift; 1417 1418 /* Determine lowest permitted virtual page index. */ 1419 uint64_t pgidx_start = (vaddr_min + vm->page_size - 1) >> vm->page_shift; 1420 if ((pgidx_start * vm->page_size) < vaddr_min) 1421 goto no_va_found; 1422 1423 /* Loop over section with enough valid virtual page indexes. */ 1424 if (!sparsebit_is_set_num(vm->vpages_valid, 1425 pgidx_start, pages)) 1426 pgidx_start = sparsebit_next_set_num(vm->vpages_valid, 1427 pgidx_start, pages); 1428 do { 1429 /* 1430 * Are there enough unused virtual pages available at 1431 * the currently proposed starting virtual page index. 1432 * If not, adjust proposed starting index to next 1433 * possible. 1434 */ 1435 if (sparsebit_is_clear_num(vm->vpages_mapped, 1436 pgidx_start, pages)) 1437 goto va_found; 1438 pgidx_start = sparsebit_next_clear_num(vm->vpages_mapped, 1439 pgidx_start, pages); 1440 if (pgidx_start == 0) 1441 goto no_va_found; 1442 1443 /* 1444 * If needed, adjust proposed starting virtual address, 1445 * to next range of valid virtual addresses. 1446 */ 1447 if (!sparsebit_is_set_num(vm->vpages_valid, 1448 pgidx_start, pages)) { 1449 pgidx_start = sparsebit_next_set_num( 1450 vm->vpages_valid, pgidx_start, pages); 1451 if (pgidx_start == 0) 1452 goto no_va_found; 1453 } 1454 } while (pgidx_start != 0); 1455 1456 no_va_found: 1457 TEST_FAIL("No vaddr of specified pages available, pages: 0x%lx", pages); 1458 1459 /* NOT REACHED */ 1460 return -1; 1461 1462 va_found: 1463 TEST_ASSERT(sparsebit_is_set_num(vm->vpages_valid, 1464 pgidx_start, pages), 1465 "Unexpected, invalid virtual page index range,\n" 1466 " pgidx_start: 0x%lx\n" 1467 " pages: 0x%lx", 1468 pgidx_start, pages); 1469 TEST_ASSERT(sparsebit_is_clear_num(vm->vpages_mapped, 1470 pgidx_start, pages), 1471 "Unexpected, pages already mapped,\n" 1472 " pgidx_start: 0x%lx\n" 1473 " pages: 0x%lx", 1474 pgidx_start, pages); 1475 1476 return pgidx_start * vm->page_size; 1477 } 1478 1479 static vm_vaddr_t ____vm_vaddr_alloc(struct kvm_vm *vm, size_t sz, 1480 vm_vaddr_t vaddr_min, 1481 enum kvm_mem_region_type type, 1482 bool protected) 1483 { 1484 uint64_t pages = (sz >> vm->page_shift) + ((sz % vm->page_size) != 0); 1485 1486 virt_pgd_alloc(vm); 1487 vm_paddr_t paddr = __vm_phy_pages_alloc(vm, pages, 1488 KVM_UTIL_MIN_PFN * vm->page_size, 1489 vm->memslots[type], protected); 1490 1491 /* 1492 * Find an unused range of virtual page addresses of at least 1493 * pages in length. 1494 */ 1495 vm_vaddr_t vaddr_start = vm_vaddr_unused_gap(vm, sz, vaddr_min); 1496 1497 /* Map the virtual pages. */ 1498 for (vm_vaddr_t vaddr = vaddr_start; pages > 0; 1499 pages--, vaddr += vm->page_size, paddr += vm->page_size) { 1500 1501 virt_pg_map(vm, vaddr, paddr); 1502 1503 sparsebit_set(vm->vpages_mapped, vaddr >> vm->page_shift); 1504 } 1505 1506 return vaddr_start; 1507 } 1508 1509 vm_vaddr_t __vm_vaddr_alloc(struct kvm_vm *vm, size_t sz, vm_vaddr_t vaddr_min, 1510 enum kvm_mem_region_type type) 1511 { 1512 return ____vm_vaddr_alloc(vm, sz, vaddr_min, type, 1513 vm_arch_has_protected_memory(vm)); 1514 } 1515 1516 vm_vaddr_t vm_vaddr_alloc_shared(struct kvm_vm *vm, size_t sz, 1517 vm_vaddr_t vaddr_min, 1518 enum kvm_mem_region_type type) 1519 { 1520 return ____vm_vaddr_alloc(vm, sz, vaddr_min, type, false); 1521 } 1522 1523 /* 1524 * VM Virtual Address Allocate 1525 * 1526 * Input Args: 1527 * vm - Virtual Machine 1528 * sz - Size in bytes 1529 * vaddr_min - Minimum starting virtual address 1530 * 1531 * Output Args: None 1532 * 1533 * Return: 1534 * Starting guest virtual address 1535 * 1536 * Allocates at least sz bytes within the virtual address space of the vm 1537 * given by vm. The allocated bytes are mapped to a virtual address >= 1538 * the address given by vaddr_min. Note that each allocation uses a 1539 * a unique set of pages, with the minimum real allocation being at least 1540 * a page. The allocated physical space comes from the TEST_DATA memory region. 1541 */ 1542 vm_vaddr_t vm_vaddr_alloc(struct kvm_vm *vm, size_t sz, vm_vaddr_t vaddr_min) 1543 { 1544 return __vm_vaddr_alloc(vm, sz, vaddr_min, MEM_REGION_TEST_DATA); 1545 } 1546 1547 /* 1548 * VM Virtual Address Allocate Pages 1549 * 1550 * Input Args: 1551 * vm - Virtual Machine 1552 * 1553 * Output Args: None 1554 * 1555 * Return: 1556 * Starting guest virtual address 1557 * 1558 * Allocates at least N system pages worth of bytes within the virtual address 1559 * space of the vm. 1560 */ 1561 vm_vaddr_t vm_vaddr_alloc_pages(struct kvm_vm *vm, int nr_pages) 1562 { 1563 return vm_vaddr_alloc(vm, nr_pages * getpagesize(), KVM_UTIL_MIN_VADDR); 1564 } 1565 1566 vm_vaddr_t __vm_vaddr_alloc_page(struct kvm_vm *vm, enum kvm_mem_region_type type) 1567 { 1568 return __vm_vaddr_alloc(vm, getpagesize(), KVM_UTIL_MIN_VADDR, type); 1569 } 1570 1571 /* 1572 * VM Virtual Address Allocate Page 1573 * 1574 * Input Args: 1575 * vm - Virtual Machine 1576 * 1577 * Output Args: None 1578 * 1579 * Return: 1580 * Starting guest virtual address 1581 * 1582 * Allocates at least one system page worth of bytes within the virtual address 1583 * space of the vm. 1584 */ 1585 vm_vaddr_t vm_vaddr_alloc_page(struct kvm_vm *vm) 1586 { 1587 return vm_vaddr_alloc_pages(vm, 1); 1588 } 1589 1590 /* 1591 * Map a range of VM virtual address to the VM's physical address 1592 * 1593 * Input Args: 1594 * vm - Virtual Machine 1595 * vaddr - Virtuall address to map 1596 * paddr - VM Physical Address 1597 * npages - The number of pages to map 1598 * 1599 * Output Args: None 1600 * 1601 * Return: None 1602 * 1603 * Within the VM given by @vm, creates a virtual translation for 1604 * @npages starting at @vaddr to the page range starting at @paddr. 1605 */ 1606 void virt_map(struct kvm_vm *vm, uint64_t vaddr, uint64_t paddr, 1607 unsigned int npages) 1608 { 1609 size_t page_size = vm->page_size; 1610 size_t size = npages * page_size; 1611 1612 TEST_ASSERT(vaddr + size > vaddr, "Vaddr overflow"); 1613 TEST_ASSERT(paddr + size > paddr, "Paddr overflow"); 1614 1615 while (npages--) { 1616 virt_pg_map(vm, vaddr, paddr); 1617 sparsebit_set(vm->vpages_mapped, vaddr >> vm->page_shift); 1618 1619 vaddr += page_size; 1620 paddr += page_size; 1621 } 1622 } 1623 1624 /* 1625 * Address VM Physical to Host Virtual 1626 * 1627 * Input Args: 1628 * vm - Virtual Machine 1629 * gpa - VM physical address 1630 * 1631 * Output Args: None 1632 * 1633 * Return: 1634 * Equivalent host virtual address 1635 * 1636 * Locates the memory region containing the VM physical address given 1637 * by gpa, within the VM given by vm. When found, the host virtual 1638 * address providing the memory to the vm physical address is returned. 1639 * A TEST_ASSERT failure occurs if no region containing gpa exists. 1640 */ 1641 void *addr_gpa2hva(struct kvm_vm *vm, vm_paddr_t gpa) 1642 { 1643 struct userspace_mem_region *region; 1644 1645 gpa = vm_untag_gpa(vm, gpa); 1646 1647 region = userspace_mem_region_find(vm, gpa, gpa); 1648 if (!region) { 1649 TEST_FAIL("No vm physical memory at 0x%lx", gpa); 1650 return NULL; 1651 } 1652 1653 return (void *)((uintptr_t)region->host_mem 1654 + (gpa - region->region.guest_phys_addr)); 1655 } 1656 1657 /* 1658 * Address Host Virtual to VM Physical 1659 * 1660 * Input Args: 1661 * vm - Virtual Machine 1662 * hva - Host virtual address 1663 * 1664 * Output Args: None 1665 * 1666 * Return: 1667 * Equivalent VM physical address 1668 * 1669 * Locates the memory region containing the host virtual address given 1670 * by hva, within the VM given by vm. When found, the equivalent 1671 * VM physical address is returned. A TEST_ASSERT failure occurs if no 1672 * region containing hva exists. 1673 */ 1674 vm_paddr_t addr_hva2gpa(struct kvm_vm *vm, void *hva) 1675 { 1676 struct rb_node *node; 1677 1678 for (node = vm->regions.hva_tree.rb_node; node; ) { 1679 struct userspace_mem_region *region = 1680 container_of(node, struct userspace_mem_region, hva_node); 1681 1682 if (hva >= region->host_mem) { 1683 if (hva <= (region->host_mem 1684 + region->region.memory_size - 1)) 1685 return (vm_paddr_t)((uintptr_t) 1686 region->region.guest_phys_addr 1687 + (hva - (uintptr_t)region->host_mem)); 1688 1689 node = node->rb_right; 1690 } else 1691 node = node->rb_left; 1692 } 1693 1694 TEST_FAIL("No mapping to a guest physical address, hva: %p", hva); 1695 return -1; 1696 } 1697 1698 /* 1699 * Address VM physical to Host Virtual *alias*. 1700 * 1701 * Input Args: 1702 * vm - Virtual Machine 1703 * gpa - VM physical address 1704 * 1705 * Output Args: None 1706 * 1707 * Return: 1708 * Equivalent address within the host virtual *alias* area, or NULL 1709 * (without failing the test) if the guest memory is not shared (so 1710 * no alias exists). 1711 * 1712 * Create a writable, shared virtual=>physical alias for the specific GPA. 1713 * The primary use case is to allow the host selftest to manipulate guest 1714 * memory without mapping said memory in the guest's address space. And, for 1715 * userfaultfd-based demand paging, to do so without triggering userfaults. 1716 */ 1717 void *addr_gpa2alias(struct kvm_vm *vm, vm_paddr_t gpa) 1718 { 1719 struct userspace_mem_region *region; 1720 uintptr_t offset; 1721 1722 region = userspace_mem_region_find(vm, gpa, gpa); 1723 if (!region) 1724 return NULL; 1725 1726 if (!region->host_alias) 1727 return NULL; 1728 1729 offset = gpa - region->region.guest_phys_addr; 1730 return (void *) ((uintptr_t) region->host_alias + offset); 1731 } 1732 1733 /* Create an interrupt controller chip for the specified VM. */ 1734 void vm_create_irqchip(struct kvm_vm *vm) 1735 { 1736 int r; 1737 1738 /* 1739 * Allocate a fully in-kernel IRQ chip by default, but fall back to a 1740 * split model (x86 only) if that fails (KVM x86 allows compiling out 1741 * support for KVM_CREATE_IRQCHIP). 1742 */ 1743 r = __vm_ioctl(vm, KVM_CREATE_IRQCHIP, NULL); 1744 if (r && errno == ENOTTY && kvm_has_cap(KVM_CAP_SPLIT_IRQCHIP)) 1745 vm_enable_cap(vm, KVM_CAP_SPLIT_IRQCHIP, 24); 1746 else 1747 TEST_ASSERT_VM_VCPU_IOCTL(!r, KVM_CREATE_IRQCHIP, r, vm); 1748 1749 vm->has_irqchip = true; 1750 } 1751 1752 int _vcpu_run(struct kvm_vcpu *vcpu) 1753 { 1754 int rc; 1755 1756 do { 1757 rc = __vcpu_run(vcpu); 1758 } while (rc == -1 && errno == EINTR); 1759 1760 if (!rc) 1761 assert_on_unhandled_exception(vcpu); 1762 1763 return rc; 1764 } 1765 1766 /* 1767 * Invoke KVM_RUN on a vCPU until KVM returns something other than -EINTR. 1768 * Assert if the KVM returns an error (other than -EINTR). 1769 */ 1770 void vcpu_run(struct kvm_vcpu *vcpu) 1771 { 1772 int ret = _vcpu_run(vcpu); 1773 1774 TEST_ASSERT(!ret, KVM_IOCTL_ERROR(KVM_RUN, ret)); 1775 } 1776 1777 void vcpu_run_complete_io(struct kvm_vcpu *vcpu) 1778 { 1779 int ret; 1780 1781 vcpu->run->immediate_exit = 1; 1782 ret = __vcpu_run(vcpu); 1783 vcpu->run->immediate_exit = 0; 1784 1785 TEST_ASSERT(ret == -1 && errno == EINTR, 1786 "KVM_RUN IOCTL didn't exit immediately, rc: %i, errno: %i", 1787 ret, errno); 1788 } 1789 1790 /* 1791 * Get the list of guest registers which are supported for 1792 * KVM_GET_ONE_REG/KVM_SET_ONE_REG ioctls. Returns a kvm_reg_list pointer, 1793 * it is the caller's responsibility to free the list. 1794 */ 1795 struct kvm_reg_list *vcpu_get_reg_list(struct kvm_vcpu *vcpu) 1796 { 1797 struct kvm_reg_list reg_list_n = { .n = 0 }, *reg_list; 1798 int ret; 1799 1800 ret = __vcpu_ioctl(vcpu, KVM_GET_REG_LIST, ®_list_n); 1801 TEST_ASSERT(ret == -1 && errno == E2BIG, "KVM_GET_REG_LIST n=0"); 1802 1803 reg_list = calloc(1, sizeof(*reg_list) + reg_list_n.n * sizeof(__u64)); 1804 reg_list->n = reg_list_n.n; 1805 vcpu_ioctl(vcpu, KVM_GET_REG_LIST, reg_list); 1806 return reg_list; 1807 } 1808 1809 void *vcpu_map_dirty_ring(struct kvm_vcpu *vcpu) 1810 { 1811 uint32_t page_size = getpagesize(); 1812 uint32_t size = vcpu->vm->dirty_ring_size; 1813 1814 TEST_ASSERT(size > 0, "Should enable dirty ring first"); 1815 1816 if (!vcpu->dirty_gfns) { 1817 void *addr; 1818 1819 addr = mmap(NULL, size, PROT_READ, MAP_PRIVATE, vcpu->fd, 1820 page_size * KVM_DIRTY_LOG_PAGE_OFFSET); 1821 TEST_ASSERT(addr == MAP_FAILED, "Dirty ring mapped private"); 1822 1823 addr = mmap(NULL, size, PROT_READ | PROT_EXEC, MAP_PRIVATE, vcpu->fd, 1824 page_size * KVM_DIRTY_LOG_PAGE_OFFSET); 1825 TEST_ASSERT(addr == MAP_FAILED, "Dirty ring mapped exec"); 1826 1827 addr = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, vcpu->fd, 1828 page_size * KVM_DIRTY_LOG_PAGE_OFFSET); 1829 TEST_ASSERT(addr != MAP_FAILED, "Dirty ring map failed"); 1830 1831 vcpu->dirty_gfns = addr; 1832 vcpu->dirty_gfns_count = size / sizeof(struct kvm_dirty_gfn); 1833 } 1834 1835 return vcpu->dirty_gfns; 1836 } 1837 1838 /* 1839 * Device Ioctl 1840 */ 1841 1842 int __kvm_has_device_attr(int dev_fd, uint32_t group, uint64_t attr) 1843 { 1844 struct kvm_device_attr attribute = { 1845 .group = group, 1846 .attr = attr, 1847 .flags = 0, 1848 }; 1849 1850 return ioctl(dev_fd, KVM_HAS_DEVICE_ATTR, &attribute); 1851 } 1852 1853 int __kvm_test_create_device(struct kvm_vm *vm, uint64_t type) 1854 { 1855 struct kvm_create_device create_dev = { 1856 .type = type, 1857 .flags = KVM_CREATE_DEVICE_TEST, 1858 }; 1859 1860 return __vm_ioctl(vm, KVM_CREATE_DEVICE, &create_dev); 1861 } 1862 1863 int __kvm_create_device(struct kvm_vm *vm, uint64_t type) 1864 { 1865 struct kvm_create_device create_dev = { 1866 .type = type, 1867 .fd = -1, 1868 .flags = 0, 1869 }; 1870 int err; 1871 1872 err = __vm_ioctl(vm, KVM_CREATE_DEVICE, &create_dev); 1873 TEST_ASSERT(err <= 0, "KVM_CREATE_DEVICE shouldn't return a positive value"); 1874 return err ? : create_dev.fd; 1875 } 1876 1877 int __kvm_device_attr_get(int dev_fd, uint32_t group, uint64_t attr, void *val) 1878 { 1879 struct kvm_device_attr kvmattr = { 1880 .group = group, 1881 .attr = attr, 1882 .flags = 0, 1883 .addr = (uintptr_t)val, 1884 }; 1885 1886 return __kvm_ioctl(dev_fd, KVM_GET_DEVICE_ATTR, &kvmattr); 1887 } 1888 1889 int __kvm_device_attr_set(int dev_fd, uint32_t group, uint64_t attr, void *val) 1890 { 1891 struct kvm_device_attr kvmattr = { 1892 .group = group, 1893 .attr = attr, 1894 .flags = 0, 1895 .addr = (uintptr_t)val, 1896 }; 1897 1898 return __kvm_ioctl(dev_fd, KVM_SET_DEVICE_ATTR, &kvmattr); 1899 } 1900 1901 /* 1902 * IRQ related functions. 1903 */ 1904 1905 int _kvm_irq_line(struct kvm_vm *vm, uint32_t irq, int level) 1906 { 1907 struct kvm_irq_level irq_level = { 1908 .irq = irq, 1909 .level = level, 1910 }; 1911 1912 return __vm_ioctl(vm, KVM_IRQ_LINE, &irq_level); 1913 } 1914 1915 void kvm_irq_line(struct kvm_vm *vm, uint32_t irq, int level) 1916 { 1917 int ret = _kvm_irq_line(vm, irq, level); 1918 1919 TEST_ASSERT(ret >= 0, KVM_IOCTL_ERROR(KVM_IRQ_LINE, ret)); 1920 } 1921 1922 struct kvm_irq_routing *kvm_gsi_routing_create(void) 1923 { 1924 struct kvm_irq_routing *routing; 1925 size_t size; 1926 1927 size = sizeof(struct kvm_irq_routing); 1928 /* Allocate space for the max number of entries: this wastes 196 KBs. */ 1929 size += KVM_MAX_IRQ_ROUTES * sizeof(struct kvm_irq_routing_entry); 1930 routing = calloc(1, size); 1931 assert(routing); 1932 1933 return routing; 1934 } 1935 1936 void kvm_gsi_routing_irqchip_add(struct kvm_irq_routing *routing, 1937 uint32_t gsi, uint32_t pin) 1938 { 1939 int i; 1940 1941 assert(routing); 1942 assert(routing->nr < KVM_MAX_IRQ_ROUTES); 1943 1944 i = routing->nr; 1945 routing->entries[i].gsi = gsi; 1946 routing->entries[i].type = KVM_IRQ_ROUTING_IRQCHIP; 1947 routing->entries[i].flags = 0; 1948 routing->entries[i].u.irqchip.irqchip = 0; 1949 routing->entries[i].u.irqchip.pin = pin; 1950 routing->nr++; 1951 } 1952 1953 int _kvm_gsi_routing_write(struct kvm_vm *vm, struct kvm_irq_routing *routing) 1954 { 1955 int ret; 1956 1957 assert(routing); 1958 ret = __vm_ioctl(vm, KVM_SET_GSI_ROUTING, routing); 1959 free(routing); 1960 1961 return ret; 1962 } 1963 1964 void kvm_gsi_routing_write(struct kvm_vm *vm, struct kvm_irq_routing *routing) 1965 { 1966 int ret; 1967 1968 ret = _kvm_gsi_routing_write(vm, routing); 1969 TEST_ASSERT(!ret, KVM_IOCTL_ERROR(KVM_SET_GSI_ROUTING, ret)); 1970 } 1971 1972 /* 1973 * VM Dump 1974 * 1975 * Input Args: 1976 * vm - Virtual Machine 1977 * indent - Left margin indent amount 1978 * 1979 * Output Args: 1980 * stream - Output FILE stream 1981 * 1982 * Return: None 1983 * 1984 * Dumps the current state of the VM given by vm, to the FILE stream 1985 * given by stream. 1986 */ 1987 void vm_dump(FILE *stream, struct kvm_vm *vm, uint8_t indent) 1988 { 1989 int ctr; 1990 struct userspace_mem_region *region; 1991 struct kvm_vcpu *vcpu; 1992 1993 fprintf(stream, "%*smode: 0x%x\n", indent, "", vm->mode); 1994 fprintf(stream, "%*sfd: %i\n", indent, "", vm->fd); 1995 fprintf(stream, "%*spage_size: 0x%x\n", indent, "", vm->page_size); 1996 fprintf(stream, "%*sMem Regions:\n", indent, ""); 1997 hash_for_each(vm->regions.slot_hash, ctr, region, slot_node) { 1998 fprintf(stream, "%*sguest_phys: 0x%lx size: 0x%lx " 1999 "host_virt: %p\n", indent + 2, "", 2000 (uint64_t) region->region.guest_phys_addr, 2001 (uint64_t) region->region.memory_size, 2002 region->host_mem); 2003 fprintf(stream, "%*sunused_phy_pages: ", indent + 2, ""); 2004 sparsebit_dump(stream, region->unused_phy_pages, 0); 2005 if (region->protected_phy_pages) { 2006 fprintf(stream, "%*sprotected_phy_pages: ", indent + 2, ""); 2007 sparsebit_dump(stream, region->protected_phy_pages, 0); 2008 } 2009 } 2010 fprintf(stream, "%*sMapped Virtual Pages:\n", indent, ""); 2011 sparsebit_dump(stream, vm->vpages_mapped, indent + 2); 2012 fprintf(stream, "%*spgd_created: %u\n", indent, "", 2013 vm->pgd_created); 2014 if (vm->pgd_created) { 2015 fprintf(stream, "%*sVirtual Translation Tables:\n", 2016 indent + 2, ""); 2017 virt_dump(stream, vm, indent + 4); 2018 } 2019 fprintf(stream, "%*sVCPUs:\n", indent, ""); 2020 2021 list_for_each_entry(vcpu, &vm->vcpus, list) 2022 vcpu_dump(stream, vcpu, indent + 2); 2023 } 2024 2025 #define KVM_EXIT_STRING(x) {KVM_EXIT_##x, #x} 2026 2027 /* Known KVM exit reasons */ 2028 static struct exit_reason { 2029 unsigned int reason; 2030 const char *name; 2031 } exit_reasons_known[] = { 2032 KVM_EXIT_STRING(UNKNOWN), 2033 KVM_EXIT_STRING(EXCEPTION), 2034 KVM_EXIT_STRING(IO), 2035 KVM_EXIT_STRING(HYPERCALL), 2036 KVM_EXIT_STRING(DEBUG), 2037 KVM_EXIT_STRING(HLT), 2038 KVM_EXIT_STRING(MMIO), 2039 KVM_EXIT_STRING(IRQ_WINDOW_OPEN), 2040 KVM_EXIT_STRING(SHUTDOWN), 2041 KVM_EXIT_STRING(FAIL_ENTRY), 2042 KVM_EXIT_STRING(INTR), 2043 KVM_EXIT_STRING(SET_TPR), 2044 KVM_EXIT_STRING(TPR_ACCESS), 2045 KVM_EXIT_STRING(S390_SIEIC), 2046 KVM_EXIT_STRING(S390_RESET), 2047 KVM_EXIT_STRING(DCR), 2048 KVM_EXIT_STRING(NMI), 2049 KVM_EXIT_STRING(INTERNAL_ERROR), 2050 KVM_EXIT_STRING(OSI), 2051 KVM_EXIT_STRING(PAPR_HCALL), 2052 KVM_EXIT_STRING(S390_UCONTROL), 2053 KVM_EXIT_STRING(WATCHDOG), 2054 KVM_EXIT_STRING(S390_TSCH), 2055 KVM_EXIT_STRING(EPR), 2056 KVM_EXIT_STRING(SYSTEM_EVENT), 2057 KVM_EXIT_STRING(S390_STSI), 2058 KVM_EXIT_STRING(IOAPIC_EOI), 2059 KVM_EXIT_STRING(HYPERV), 2060 KVM_EXIT_STRING(ARM_NISV), 2061 KVM_EXIT_STRING(X86_RDMSR), 2062 KVM_EXIT_STRING(X86_WRMSR), 2063 KVM_EXIT_STRING(DIRTY_RING_FULL), 2064 KVM_EXIT_STRING(AP_RESET_HOLD), 2065 KVM_EXIT_STRING(X86_BUS_LOCK), 2066 KVM_EXIT_STRING(XEN), 2067 KVM_EXIT_STRING(RISCV_SBI), 2068 KVM_EXIT_STRING(RISCV_CSR), 2069 KVM_EXIT_STRING(NOTIFY), 2070 KVM_EXIT_STRING(LOONGARCH_IOCSR), 2071 KVM_EXIT_STRING(MEMORY_FAULT), 2072 }; 2073 2074 /* 2075 * Exit Reason String 2076 * 2077 * Input Args: 2078 * exit_reason - Exit reason 2079 * 2080 * Output Args: None 2081 * 2082 * Return: 2083 * Constant string pointer describing the exit reason. 2084 * 2085 * Locates and returns a constant string that describes the KVM exit 2086 * reason given by exit_reason. If no such string is found, a constant 2087 * string of "Unknown" is returned. 2088 */ 2089 const char *exit_reason_str(unsigned int exit_reason) 2090 { 2091 unsigned int n1; 2092 2093 for (n1 = 0; n1 < ARRAY_SIZE(exit_reasons_known); n1++) { 2094 if (exit_reason == exit_reasons_known[n1].reason) 2095 return exit_reasons_known[n1].name; 2096 } 2097 2098 return "Unknown"; 2099 } 2100 2101 /* 2102 * Physical Contiguous Page Allocator 2103 * 2104 * Input Args: 2105 * vm - Virtual Machine 2106 * num - number of pages 2107 * paddr_min - Physical address minimum 2108 * memslot - Memory region to allocate page from 2109 * protected - True if the pages will be used as protected/private memory 2110 * 2111 * Output Args: None 2112 * 2113 * Return: 2114 * Starting physical address 2115 * 2116 * Within the VM specified by vm, locates a range of available physical 2117 * pages at or above paddr_min. If found, the pages are marked as in use 2118 * and their base address is returned. A TEST_ASSERT failure occurs if 2119 * not enough pages are available at or above paddr_min. 2120 */ 2121 vm_paddr_t __vm_phy_pages_alloc(struct kvm_vm *vm, size_t num, 2122 vm_paddr_t paddr_min, uint32_t memslot, 2123 bool protected) 2124 { 2125 struct userspace_mem_region *region; 2126 sparsebit_idx_t pg, base; 2127 2128 TEST_ASSERT(num > 0, "Must allocate at least one page"); 2129 2130 TEST_ASSERT((paddr_min % vm->page_size) == 0, "Min physical address " 2131 "not divisible by page size.\n" 2132 " paddr_min: 0x%lx page_size: 0x%x", 2133 paddr_min, vm->page_size); 2134 2135 region = memslot2region(vm, memslot); 2136 TEST_ASSERT(!protected || region->protected_phy_pages, 2137 "Region doesn't support protected memory"); 2138 2139 base = pg = paddr_min >> vm->page_shift; 2140 do { 2141 for (; pg < base + num; ++pg) { 2142 if (!sparsebit_is_set(region->unused_phy_pages, pg)) { 2143 base = pg = sparsebit_next_set(region->unused_phy_pages, pg); 2144 break; 2145 } 2146 } 2147 } while (pg && pg != base + num); 2148 2149 if (pg == 0) { 2150 fprintf(stderr, "No guest physical page available, " 2151 "paddr_min: 0x%lx page_size: 0x%x memslot: %u\n", 2152 paddr_min, vm->page_size, memslot); 2153 fputs("---- vm dump ----\n", stderr); 2154 vm_dump(stderr, vm, 2); 2155 abort(); 2156 } 2157 2158 for (pg = base; pg < base + num; ++pg) { 2159 sparsebit_clear(region->unused_phy_pages, pg); 2160 if (protected) 2161 sparsebit_set(region->protected_phy_pages, pg); 2162 } 2163 2164 return base * vm->page_size; 2165 } 2166 2167 vm_paddr_t vm_phy_page_alloc(struct kvm_vm *vm, vm_paddr_t paddr_min, 2168 uint32_t memslot) 2169 { 2170 return vm_phy_pages_alloc(vm, 1, paddr_min, memslot); 2171 } 2172 2173 vm_paddr_t vm_alloc_page_table(struct kvm_vm *vm) 2174 { 2175 return vm_phy_page_alloc(vm, KVM_GUEST_PAGE_TABLE_MIN_PADDR, 2176 vm->memslots[MEM_REGION_PT]); 2177 } 2178 2179 /* 2180 * Address Guest Virtual to Host Virtual 2181 * 2182 * Input Args: 2183 * vm - Virtual Machine 2184 * gva - VM virtual address 2185 * 2186 * Output Args: None 2187 * 2188 * Return: 2189 * Equivalent host virtual address 2190 */ 2191 void *addr_gva2hva(struct kvm_vm *vm, vm_vaddr_t gva) 2192 { 2193 return addr_gpa2hva(vm, addr_gva2gpa(vm, gva)); 2194 } 2195 2196 unsigned long __weak vm_compute_max_gfn(struct kvm_vm *vm) 2197 { 2198 return ((1ULL << vm->pa_bits) >> vm->page_shift) - 1; 2199 } 2200 2201 static unsigned int vm_calc_num_pages(unsigned int num_pages, 2202 unsigned int page_shift, 2203 unsigned int new_page_shift, 2204 bool ceil) 2205 { 2206 unsigned int n = 1 << (new_page_shift - page_shift); 2207 2208 if (page_shift >= new_page_shift) 2209 return num_pages * (1 << (page_shift - new_page_shift)); 2210 2211 return num_pages / n + !!(ceil && num_pages % n); 2212 } 2213 2214 static inline int getpageshift(void) 2215 { 2216 return __builtin_ffs(getpagesize()) - 1; 2217 } 2218 2219 unsigned int 2220 vm_num_host_pages(enum vm_guest_mode mode, unsigned int num_guest_pages) 2221 { 2222 return vm_calc_num_pages(num_guest_pages, 2223 vm_guest_mode_params[mode].page_shift, 2224 getpageshift(), true); 2225 } 2226 2227 unsigned int 2228 vm_num_guest_pages(enum vm_guest_mode mode, unsigned int num_host_pages) 2229 { 2230 return vm_calc_num_pages(num_host_pages, getpageshift(), 2231 vm_guest_mode_params[mode].page_shift, false); 2232 } 2233 2234 unsigned int vm_calc_num_guest_pages(enum vm_guest_mode mode, size_t size) 2235 { 2236 unsigned int n; 2237 n = DIV_ROUND_UP(size, vm_guest_mode_params[mode].page_size); 2238 return vm_adjust_num_guest_pages(mode, n); 2239 } 2240 2241 /* 2242 * Read binary stats descriptors 2243 * 2244 * Input Args: 2245 * stats_fd - the file descriptor for the binary stats file from which to read 2246 * header - the binary stats metadata header corresponding to the given FD 2247 * 2248 * Output Args: None 2249 * 2250 * Return: 2251 * A pointer to a newly allocated series of stat descriptors. 2252 * Caller is responsible for freeing the returned kvm_stats_desc. 2253 * 2254 * Read the stats descriptors from the binary stats interface. 2255 */ 2256 struct kvm_stats_desc *read_stats_descriptors(int stats_fd, 2257 struct kvm_stats_header *header) 2258 { 2259 struct kvm_stats_desc *stats_desc; 2260 ssize_t desc_size, total_size, ret; 2261 2262 desc_size = get_stats_descriptor_size(header); 2263 total_size = header->num_desc * desc_size; 2264 2265 stats_desc = calloc(header->num_desc, desc_size); 2266 TEST_ASSERT(stats_desc, "Allocate memory for stats descriptors"); 2267 2268 ret = pread(stats_fd, stats_desc, total_size, header->desc_offset); 2269 TEST_ASSERT(ret == total_size, "Read KVM stats descriptors"); 2270 2271 return stats_desc; 2272 } 2273 2274 /* 2275 * Read stat data for a particular stat 2276 * 2277 * Input Args: 2278 * stats_fd - the file descriptor for the binary stats file from which to read 2279 * header - the binary stats metadata header corresponding to the given FD 2280 * desc - the binary stat metadata for the particular stat to be read 2281 * max_elements - the maximum number of 8-byte values to read into data 2282 * 2283 * Output Args: 2284 * data - the buffer into which stat data should be read 2285 * 2286 * Read the data values of a specified stat from the binary stats interface. 2287 */ 2288 void read_stat_data(int stats_fd, struct kvm_stats_header *header, 2289 struct kvm_stats_desc *desc, uint64_t *data, 2290 size_t max_elements) 2291 { 2292 size_t nr_elements = min_t(ssize_t, desc->size, max_elements); 2293 size_t size = nr_elements * sizeof(*data); 2294 ssize_t ret; 2295 2296 TEST_ASSERT(desc->size, "No elements in stat '%s'", desc->name); 2297 TEST_ASSERT(max_elements, "Zero elements requested for stat '%s'", desc->name); 2298 2299 ret = pread(stats_fd, data, size, 2300 header->data_offset + desc->offset); 2301 2302 TEST_ASSERT(ret >= 0, "pread() failed on stat '%s', errno: %i (%s)", 2303 desc->name, errno, strerror(errno)); 2304 TEST_ASSERT(ret == size, 2305 "pread() on stat '%s' read %ld bytes, wanted %lu bytes", 2306 desc->name, size, ret); 2307 } 2308 2309 void kvm_get_stat(struct kvm_binary_stats *stats, const char *name, 2310 uint64_t *data, size_t max_elements) 2311 { 2312 struct kvm_stats_desc *desc; 2313 size_t size_desc; 2314 int i; 2315 2316 if (!stats->desc) { 2317 read_stats_header(stats->fd, &stats->header); 2318 stats->desc = read_stats_descriptors(stats->fd, &stats->header); 2319 } 2320 2321 size_desc = get_stats_descriptor_size(&stats->header); 2322 2323 for (i = 0; i < stats->header.num_desc; ++i) { 2324 desc = (void *)stats->desc + (i * size_desc); 2325 2326 if (strcmp(desc->name, name)) 2327 continue; 2328 2329 read_stat_data(stats->fd, &stats->header, desc, data, max_elements); 2330 return; 2331 } 2332 2333 TEST_FAIL("Unable to find stat '%s'", name); 2334 } 2335 2336 __weak void kvm_arch_vm_post_create(struct kvm_vm *vm, unsigned int nr_vcpus) 2337 { 2338 } 2339 2340 __weak void kvm_arch_vm_finalize_vcpus(struct kvm_vm *vm) 2341 { 2342 } 2343 2344 __weak void kvm_arch_vm_release(struct kvm_vm *vm) 2345 { 2346 } 2347 2348 __weak void kvm_selftest_arch_init(void) 2349 { 2350 } 2351 2352 void __attribute((constructor)) kvm_selftest_init(void) 2353 { 2354 /* Tell stdout not to buffer its content. */ 2355 setbuf(stdout, NULL); 2356 2357 guest_random_seed = last_guest_seed = random(); 2358 pr_info("Random seed: 0x%x\n", guest_random_seed); 2359 2360 kvm_selftest_arch_init(); 2361 } 2362 2363 bool vm_is_gpa_protected(struct kvm_vm *vm, vm_paddr_t paddr) 2364 { 2365 sparsebit_idx_t pg = 0; 2366 struct userspace_mem_region *region; 2367 2368 if (!vm_arch_has_protected_memory(vm)) 2369 return false; 2370 2371 region = userspace_mem_region_find(vm, paddr, paddr); 2372 TEST_ASSERT(region, "No vm physical memory at 0x%lx", paddr); 2373 2374 pg = paddr >> vm->page_shift; 2375 return sparsebit_is_set(region->protected_phy_pages, pg); 2376 } 2377