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