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