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