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