1 // SPDX-License-Identifier: GPL-2.0-only
3 * tools/testing/selftests/kvm/lib/kvm_util.c
5 * Copyright (C) 2018, Google LLC.
8 #define _GNU_SOURCE /* for program_invocation_name */
11 #include "kvm_util_internal.h"
12 #include "processor.h"
16 #include <sys/types.h>
19 #include <linux/kernel.h>
21 #define KVM_UTIL_MIN_PFN 2
23 static int vcpu_mmap_sz(void);
25 int open_path_or_exit(const char *path, int flags)
29 fd = open(path, flags);
31 print_skip("%s not available (errno: %d)", path, errno);
39 * Open KVM_DEV_PATH if available, otherwise exit the entire program.
42 * flags - The flags to pass when opening KVM_DEV_PATH.
45 * The opened file descriptor of /dev/kvm.
47 static int _open_kvm_dev_path_or_exit(int flags)
49 return open_path_or_exit(KVM_DEV_PATH, flags);
52 int open_kvm_dev_path_or_exit(void)
54 return _open_kvm_dev_path_or_exit(O_RDONLY);
66 * On success, the Value corresponding to the capability (KVM_CAP_*)
67 * specified by the value of cap. On failure a TEST_ASSERT failure
70 * Looks up and returns the value corresponding to the capability
71 * (KVM_CAP_*) given by cap.
73 int kvm_check_cap(long cap)
78 kvm_fd = open_kvm_dev_path_or_exit();
79 ret = ioctl(kvm_fd, KVM_CHECK_EXTENSION, cap);
80 TEST_ASSERT(ret >= 0, "KVM_CHECK_EXTENSION IOCTL failed,\n"
81 " rc: %i errno: %i", ret, errno);
88 /* VM Check Capability
91 * vm - Virtual Machine
97 * On success, the Value corresponding to the capability (KVM_CAP_*)
98 * specified by the value of cap. On failure a TEST_ASSERT failure
101 * Looks up and returns the value corresponding to the capability
102 * (KVM_CAP_*) given by cap.
104 int vm_check_cap(struct kvm_vm *vm, long cap)
108 ret = ioctl(vm->fd, KVM_CHECK_EXTENSION, cap);
109 TEST_ASSERT(ret >= 0, "KVM_CHECK_EXTENSION VM IOCTL failed,\n"
110 " rc: %i errno: %i", ret, errno);
115 /* VM Enable Capability
118 * vm - Virtual Machine
123 * Return: On success, 0. On failure a TEST_ASSERT failure is produced.
125 * Enables a capability (KVM_CAP_*) on the VM.
127 int vm_enable_cap(struct kvm_vm *vm, struct kvm_enable_cap *cap)
131 ret = ioctl(vm->fd, KVM_ENABLE_CAP, cap);
132 TEST_ASSERT(ret == 0, "KVM_ENABLE_CAP IOCTL failed,\n"
133 " rc: %i errno: %i", ret, errno);
138 /* VCPU Enable Capability
141 * vm - Virtual Machine
147 * Return: On success, 0. On failure a TEST_ASSERT failure is produced.
149 * Enables a capability (KVM_CAP_*) on the VCPU.
151 int vcpu_enable_cap(struct kvm_vm *vm, uint32_t vcpu_id,
152 struct kvm_enable_cap *cap)
154 struct vcpu *vcpu = vcpu_find(vm, vcpu_id);
157 TEST_ASSERT(vcpu, "cannot find vcpu %d", vcpu_id);
159 r = ioctl(vcpu->fd, KVM_ENABLE_CAP, cap);
160 TEST_ASSERT(!r, "KVM_ENABLE_CAP vCPU ioctl failed,\n"
161 " rc: %i, errno: %i", r, errno);
166 void vm_enable_dirty_ring(struct kvm_vm *vm, uint32_t ring_size)
168 struct kvm_enable_cap cap = { 0 };
170 cap.cap = KVM_CAP_DIRTY_LOG_RING;
171 cap.args[0] = ring_size;
172 vm_enable_cap(vm, &cap);
173 vm->dirty_ring_size = ring_size;
176 static void vm_open(struct kvm_vm *vm, int perm)
178 vm->kvm_fd = _open_kvm_dev_path_or_exit(perm);
180 if (!kvm_check_cap(KVM_CAP_IMMEDIATE_EXIT)) {
181 print_skip("immediate_exit not available");
185 vm->fd = ioctl(vm->kvm_fd, KVM_CREATE_VM, vm->type);
186 TEST_ASSERT(vm->fd >= 0, "KVM_CREATE_VM ioctl failed, "
187 "rc: %i errno: %i", vm->fd, errno);
190 const char *vm_guest_mode_string(uint32_t i)
192 static const char * const strings[] = {
193 [VM_MODE_P52V48_4K] = "PA-bits:52, VA-bits:48, 4K pages",
194 [VM_MODE_P52V48_64K] = "PA-bits:52, VA-bits:48, 64K pages",
195 [VM_MODE_P48V48_4K] = "PA-bits:48, VA-bits:48, 4K pages",
196 [VM_MODE_P48V48_16K] = "PA-bits:48, VA-bits:48, 16K pages",
197 [VM_MODE_P48V48_64K] = "PA-bits:48, VA-bits:48, 64K pages",
198 [VM_MODE_P40V48_4K] = "PA-bits:40, VA-bits:48, 4K pages",
199 [VM_MODE_P40V48_16K] = "PA-bits:40, VA-bits:48, 16K pages",
200 [VM_MODE_P40V48_64K] = "PA-bits:40, VA-bits:48, 64K pages",
201 [VM_MODE_PXXV48_4K] = "PA-bits:ANY, VA-bits:48, 4K pages",
202 [VM_MODE_P47V64_4K] = "PA-bits:47, VA-bits:64, 4K pages",
203 [VM_MODE_P44V64_4K] = "PA-bits:44, VA-bits:64, 4K pages",
204 [VM_MODE_P36V48_4K] = "PA-bits:36, VA-bits:48, 4K pages",
205 [VM_MODE_P36V48_16K] = "PA-bits:36, VA-bits:48, 16K pages",
206 [VM_MODE_P36V48_64K] = "PA-bits:36, VA-bits:48, 64K pages",
207 [VM_MODE_P36V47_16K] = "PA-bits:36, VA-bits:47, 16K pages",
209 _Static_assert(sizeof(strings)/sizeof(char *) == NUM_VM_MODES,
210 "Missing new mode strings?");
212 TEST_ASSERT(i < NUM_VM_MODES, "Guest mode ID %d too big", i);
217 const struct vm_guest_mode_params vm_guest_mode_params[] = {
218 [VM_MODE_P52V48_4K] = { 52, 48, 0x1000, 12 },
219 [VM_MODE_P52V48_64K] = { 52, 48, 0x10000, 16 },
220 [VM_MODE_P48V48_4K] = { 48, 48, 0x1000, 12 },
221 [VM_MODE_P48V48_16K] = { 48, 48, 0x4000, 14 },
222 [VM_MODE_P48V48_64K] = { 48, 48, 0x10000, 16 },
223 [VM_MODE_P40V48_4K] = { 40, 48, 0x1000, 12 },
224 [VM_MODE_P40V48_16K] = { 40, 48, 0x4000, 14 },
225 [VM_MODE_P40V48_64K] = { 40, 48, 0x10000, 16 },
226 [VM_MODE_PXXV48_4K] = { 0, 0, 0x1000, 12 },
227 [VM_MODE_P47V64_4K] = { 47, 64, 0x1000, 12 },
228 [VM_MODE_P44V64_4K] = { 44, 64, 0x1000, 12 },
229 [VM_MODE_P36V48_4K] = { 36, 48, 0x1000, 12 },
230 [VM_MODE_P36V48_16K] = { 36, 48, 0x4000, 14 },
231 [VM_MODE_P36V48_64K] = { 36, 48, 0x10000, 16 },
232 [VM_MODE_P36V47_16K] = { 36, 47, 0x4000, 14 },
234 _Static_assert(sizeof(vm_guest_mode_params)/sizeof(struct vm_guest_mode_params) == NUM_VM_MODES,
235 "Missing new mode params?");
241 * mode - VM Mode (e.g. VM_MODE_P52V48_4K)
242 * phy_pages - Physical memory pages
248 * Pointer to opaque structure that describes the created VM.
250 * Creates a VM with the mode specified by mode (e.g. VM_MODE_P52V48_4K).
251 * When phy_pages is non-zero, a memory region of phy_pages physical pages
252 * is created and mapped starting at guest physical address 0. The file
253 * descriptor to control the created VM is created with the permissions
254 * given by perm (e.g. O_RDWR).
256 struct kvm_vm *vm_create(enum vm_guest_mode mode, uint64_t phy_pages, int perm)
260 pr_debug("%s: mode='%s' pages='%ld' perm='%d'\n", __func__,
261 vm_guest_mode_string(mode), phy_pages, perm);
263 vm = calloc(1, sizeof(*vm));
264 TEST_ASSERT(vm != NULL, "Insufficient Memory");
266 INIT_LIST_HEAD(&vm->vcpus);
267 vm->regions.gpa_tree = RB_ROOT;
268 vm->regions.hva_tree = RB_ROOT;
269 hash_init(vm->regions.slot_hash);
274 vm->pa_bits = vm_guest_mode_params[mode].pa_bits;
275 vm->va_bits = vm_guest_mode_params[mode].va_bits;
276 vm->page_size = vm_guest_mode_params[mode].page_size;
277 vm->page_shift = vm_guest_mode_params[mode].page_shift;
279 /* Setup mode specific traits. */
281 case VM_MODE_P52V48_4K:
282 vm->pgtable_levels = 4;
284 case VM_MODE_P52V48_64K:
285 vm->pgtable_levels = 3;
287 case VM_MODE_P48V48_4K:
288 vm->pgtable_levels = 4;
290 case VM_MODE_P48V48_64K:
291 vm->pgtable_levels = 3;
293 case VM_MODE_P40V48_4K:
294 case VM_MODE_P36V48_4K:
295 vm->pgtable_levels = 4;
297 case VM_MODE_P40V48_64K:
298 case VM_MODE_P36V48_64K:
299 vm->pgtable_levels = 3;
301 case VM_MODE_P48V48_16K:
302 case VM_MODE_P40V48_16K:
303 case VM_MODE_P36V48_16K:
304 vm->pgtable_levels = 4;
306 case VM_MODE_P36V47_16K:
307 vm->pgtable_levels = 3;
309 case VM_MODE_PXXV48_4K:
311 kvm_get_cpu_address_width(&vm->pa_bits, &vm->va_bits);
313 * Ignore KVM support for 5-level paging (vm->va_bits == 57),
314 * it doesn't take effect unless a CR4.LA57 is set, which it
315 * isn't for this VM_MODE.
317 TEST_ASSERT(vm->va_bits == 48 || vm->va_bits == 57,
318 "Linear address width (%d bits) not supported",
320 pr_debug("Guest physical address width detected: %d\n",
322 vm->pgtable_levels = 4;
325 TEST_FAIL("VM_MODE_PXXV48_4K not supported on non-x86 platforms");
328 case VM_MODE_P47V64_4K:
329 vm->pgtable_levels = 5;
331 case VM_MODE_P44V64_4K:
332 vm->pgtable_levels = 5;
335 TEST_FAIL("Unknown guest mode, mode: 0x%x", mode);
339 if (vm->pa_bits != 40)
340 vm->type = KVM_VM_TYPE_ARM_IPA_SIZE(vm->pa_bits);
345 /* Limit to VA-bit canonical virtual addresses. */
346 vm->vpages_valid = sparsebit_alloc();
347 sparsebit_set_num(vm->vpages_valid,
348 0, (1ULL << (vm->va_bits - 1)) >> vm->page_shift);
349 sparsebit_set_num(vm->vpages_valid,
350 (~((1ULL << (vm->va_bits - 1)) - 1)) >> vm->page_shift,
351 (1ULL << (vm->va_bits - 1)) >> vm->page_shift);
353 /* Limit physical addresses to PA-bits. */
354 vm->max_gfn = vm_compute_max_gfn(vm);
356 /* Allocate and setup memory for guest. */
357 vm->vpages_mapped = sparsebit_alloc();
359 vm_userspace_mem_region_add(vm, VM_MEM_SRC_ANONYMOUS,
366 * VM Create with customized parameters
369 * mode - VM Mode (e.g. VM_MODE_P52V48_4K)
370 * nr_vcpus - VCPU count
371 * slot0_mem_pages - Slot0 physical memory size
372 * extra_mem_pages - Non-slot0 physical memory total size
373 * num_percpu_pages - Per-cpu physical memory pages
374 * guest_code - Guest entry point
380 * Pointer to opaque structure that describes the created VM.
382 * Creates a VM with the mode specified by mode (e.g. VM_MODE_P52V48_4K),
383 * with customized slot0 memory size, at least 512 pages currently.
384 * extra_mem_pages is only used to calculate the maximum page table size,
385 * no real memory allocation for non-slot0 memory in this function.
387 struct kvm_vm *vm_create_with_vcpus(enum vm_guest_mode mode, uint32_t nr_vcpus,
388 uint64_t slot0_mem_pages, uint64_t extra_mem_pages,
389 uint32_t num_percpu_pages, void *guest_code,
392 uint64_t vcpu_pages, extra_pg_pages, pages;
396 /* Force slot0 memory size not small than DEFAULT_GUEST_PHY_PAGES */
397 if (slot0_mem_pages < DEFAULT_GUEST_PHY_PAGES)
398 slot0_mem_pages = DEFAULT_GUEST_PHY_PAGES;
400 /* The maximum page table size for a memory region will be when the
401 * smallest pages are used. Considering each page contains x page
402 * table descriptors, the total extra size for page tables (for extra
403 * N pages) will be: N/x+N/x^2+N/x^3+... which is definitely smaller
406 vcpu_pages = (DEFAULT_STACK_PGS + num_percpu_pages) * nr_vcpus;
407 extra_pg_pages = (slot0_mem_pages + extra_mem_pages + vcpu_pages) / PTES_PER_MIN_PAGE * 2;
408 pages = slot0_mem_pages + vcpu_pages + extra_pg_pages;
410 TEST_ASSERT(nr_vcpus <= kvm_check_cap(KVM_CAP_MAX_VCPUS),
411 "nr_vcpus = %d too large for host, max-vcpus = %d",
412 nr_vcpus, kvm_check_cap(KVM_CAP_MAX_VCPUS));
414 pages = vm_adjust_num_guest_pages(mode, pages);
415 vm = vm_create(mode, pages, O_RDWR);
417 kvm_vm_elf_load(vm, program_invocation_name);
420 vm_create_irqchip(vm);
423 for (i = 0; i < nr_vcpus; ++i) {
424 uint32_t vcpuid = vcpuids ? vcpuids[i] : i;
426 vm_vcpu_add_default(vm, vcpuid, guest_code);
432 struct kvm_vm *vm_create_default_with_vcpus(uint32_t nr_vcpus, uint64_t extra_mem_pages,
433 uint32_t num_percpu_pages, void *guest_code,
436 return vm_create_with_vcpus(VM_MODE_DEFAULT, nr_vcpus, DEFAULT_GUEST_PHY_PAGES,
437 extra_mem_pages, num_percpu_pages, guest_code, vcpuids);
440 struct kvm_vm *vm_create_default(uint32_t vcpuid, uint64_t extra_mem_pages,
443 return vm_create_default_with_vcpus(1, extra_mem_pages, 0, guest_code,
444 (uint32_t []){ vcpuid });
451 * vm - VM that has been released before
456 * Reopens the file descriptors associated to the VM and reinstates the
457 * global state, such as the irqchip and the memory regions that are mapped
460 void kvm_vm_restart(struct kvm_vm *vmp, int perm)
463 struct userspace_mem_region *region;
466 if (vmp->has_irqchip)
467 vm_create_irqchip(vmp);
469 hash_for_each(vmp->regions.slot_hash, ctr, region, slot_node) {
470 int ret = ioctl(vmp->fd, KVM_SET_USER_MEMORY_REGION, ®ion->region);
471 TEST_ASSERT(ret == 0, "KVM_SET_USER_MEMORY_REGION IOCTL failed,\n"
472 " rc: %i errno: %i\n"
473 " slot: %u flags: 0x%x\n"
474 " guest_phys_addr: 0x%llx size: 0x%llx",
475 ret, errno, region->region.slot,
476 region->region.flags,
477 region->region.guest_phys_addr,
478 region->region.memory_size);
482 void kvm_vm_get_dirty_log(struct kvm_vm *vm, int slot, void *log)
484 struct kvm_dirty_log args = { .dirty_bitmap = log, .slot = slot };
487 ret = ioctl(vm->fd, KVM_GET_DIRTY_LOG, &args);
488 TEST_ASSERT(ret == 0, "%s: KVM_GET_DIRTY_LOG failed: %s",
489 __func__, strerror(-ret));
492 void kvm_vm_clear_dirty_log(struct kvm_vm *vm, int slot, void *log,
493 uint64_t first_page, uint32_t num_pages)
495 struct kvm_clear_dirty_log args = {
496 .dirty_bitmap = log, .slot = slot,
497 .first_page = first_page,
498 .num_pages = num_pages
502 ret = ioctl(vm->fd, KVM_CLEAR_DIRTY_LOG, &args);
503 TEST_ASSERT(ret == 0, "%s: KVM_CLEAR_DIRTY_LOG failed: %s",
504 __func__, strerror(-ret));
507 uint32_t kvm_vm_reset_dirty_ring(struct kvm_vm *vm)
509 return ioctl(vm->fd, KVM_RESET_DIRTY_RINGS);
513 * Userspace Memory Region Find
516 * vm - Virtual Machine
517 * start - Starting VM physical address
518 * end - Ending VM physical address, inclusive.
523 * Pointer to overlapping region, NULL if no such region.
525 * Searches for a region with any physical memory that overlaps with
526 * any portion of the guest physical addresses from start to end
527 * inclusive. If multiple overlapping regions exist, a pointer to any
528 * of the regions is returned. Null is returned only when no overlapping
531 static struct userspace_mem_region *
532 userspace_mem_region_find(struct kvm_vm *vm, uint64_t start, uint64_t end)
534 struct rb_node *node;
536 for (node = vm->regions.gpa_tree.rb_node; node; ) {
537 struct userspace_mem_region *region =
538 container_of(node, struct userspace_mem_region, gpa_node);
539 uint64_t existing_start = region->region.guest_phys_addr;
540 uint64_t existing_end = region->region.guest_phys_addr
541 + region->region.memory_size - 1;
542 if (start <= existing_end && end >= existing_start)
545 if (start < existing_start)
546 node = node->rb_left;
548 node = node->rb_right;
555 * KVM Userspace Memory Region Find
558 * vm - Virtual Machine
559 * start - Starting VM physical address
560 * end - Ending VM physical address, inclusive.
565 * Pointer to overlapping region, NULL if no such region.
567 * Public interface to userspace_mem_region_find. Allows tests to look up
568 * the memslot datastructure for a given range of guest physical memory.
570 struct kvm_userspace_memory_region *
571 kvm_userspace_memory_region_find(struct kvm_vm *vm, uint64_t start,
574 struct userspace_mem_region *region;
576 region = userspace_mem_region_find(vm, start, end);
580 return ®ion->region;
587 * vm - Virtual Machine
593 * Pointer to VCPU structure
595 * Locates a vcpu structure that describes the VCPU specified by vcpuid and
596 * returns a pointer to it. Returns NULL if the VM doesn't contain a VCPU
597 * for the specified vcpuid.
599 struct vcpu *vcpu_find(struct kvm_vm *vm, uint32_t vcpuid)
603 list_for_each_entry(vcpu, &vm->vcpus, list) {
604 if (vcpu->id == vcpuid)
615 * vcpu - VCPU to remove
619 * Return: None, TEST_ASSERT failures for all error conditions
621 * Removes a vCPU from a VM and frees its resources.
623 static void vm_vcpu_rm(struct kvm_vm *vm, struct vcpu *vcpu)
627 if (vcpu->dirty_gfns) {
628 ret = munmap(vcpu->dirty_gfns, vm->dirty_ring_size);
629 TEST_ASSERT(ret == 0, "munmap of VCPU dirty ring failed, "
630 "rc: %i errno: %i", ret, errno);
631 vcpu->dirty_gfns = NULL;
634 ret = munmap(vcpu->state, vcpu_mmap_sz());
635 TEST_ASSERT(ret == 0, "munmap of VCPU fd failed, rc: %i "
636 "errno: %i", ret, errno);
637 ret = close(vcpu->fd);
638 TEST_ASSERT(ret == 0, "Close of VCPU fd failed, rc: %i "
639 "errno: %i", ret, errno);
641 list_del(&vcpu->list);
645 void kvm_vm_release(struct kvm_vm *vmp)
647 struct vcpu *vcpu, *tmp;
650 list_for_each_entry_safe(vcpu, tmp, &vmp->vcpus, list)
651 vm_vcpu_rm(vmp, vcpu);
653 ret = close(vmp->fd);
654 TEST_ASSERT(ret == 0, "Close of vm fd failed,\n"
655 " vmp->fd: %i rc: %i errno: %i", vmp->fd, ret, errno);
657 ret = close(vmp->kvm_fd);
658 TEST_ASSERT(ret == 0, "Close of /dev/kvm fd failed,\n"
659 " vmp->kvm_fd: %i rc: %i errno: %i", vmp->kvm_fd, ret, errno);
662 static void __vm_mem_region_delete(struct kvm_vm *vm,
663 struct userspace_mem_region *region,
669 rb_erase(®ion->gpa_node, &vm->regions.gpa_tree);
670 rb_erase(®ion->hva_node, &vm->regions.hva_tree);
671 hash_del(®ion->slot_node);
674 region->region.memory_size = 0;
675 ret = ioctl(vm->fd, KVM_SET_USER_MEMORY_REGION, ®ion->region);
676 TEST_ASSERT(ret == 0, "KVM_SET_USER_MEMORY_REGION IOCTL failed, "
677 "rc: %i errno: %i", ret, errno);
679 sparsebit_free(®ion->unused_phy_pages);
680 ret = munmap(region->mmap_start, region->mmap_size);
681 TEST_ASSERT(ret == 0, "munmap failed, rc: %i errno: %i", ret, errno);
687 * Destroys and frees the VM pointed to by vmp.
689 void kvm_vm_free(struct kvm_vm *vmp)
692 struct hlist_node *node;
693 struct userspace_mem_region *region;
698 /* Free userspace_mem_regions. */
699 hash_for_each_safe(vmp->regions.slot_hash, ctr, node, region, slot_node)
700 __vm_mem_region_delete(vmp, region, false);
702 /* Free sparsebit arrays. */
703 sparsebit_free(&vmp->vpages_valid);
704 sparsebit_free(&vmp->vpages_mapped);
708 /* Free the structure describing the VM. */
713 * Memory Compare, host virtual to guest virtual
716 * hva - Starting host virtual address
717 * vm - Virtual Machine
718 * gva - Starting guest virtual address
719 * len - number of bytes to compare
723 * Input/Output Args: None
726 * Returns 0 if the bytes starting at hva for a length of len
727 * are equal the guest virtual bytes starting at gva. Returns
728 * a value < 0, if bytes at hva are less than those at gva.
729 * Otherwise a value > 0 is returned.
731 * Compares the bytes starting at the host virtual address hva, for
732 * a length of len, to the guest bytes starting at the guest virtual
733 * address given by gva.
735 int kvm_memcmp_hva_gva(void *hva, struct kvm_vm *vm, vm_vaddr_t gva, size_t len)
740 * Compare a batch of bytes until either a match is found
741 * or all the bytes have been compared.
743 for (uintptr_t offset = 0; offset < len; offset += amt) {
744 uintptr_t ptr1 = (uintptr_t)hva + offset;
747 * Determine host address for guest virtual address
750 uintptr_t ptr2 = (uintptr_t)addr_gva2hva(vm, gva + offset);
753 * Determine amount to compare on this pass.
754 * Don't allow the comparsion to cross a page boundary.
757 if ((ptr1 >> vm->page_shift) != ((ptr1 + amt) >> vm->page_shift))
758 amt = vm->page_size - (ptr1 % vm->page_size);
759 if ((ptr2 >> vm->page_shift) != ((ptr2 + amt) >> vm->page_shift))
760 amt = vm->page_size - (ptr2 % vm->page_size);
762 assert((ptr1 >> vm->page_shift) == ((ptr1 + amt - 1) >> vm->page_shift));
763 assert((ptr2 >> vm->page_shift) == ((ptr2 + amt - 1) >> vm->page_shift));
766 * Perform the comparison. If there is a difference
767 * return that result to the caller, otherwise need
768 * to continue on looking for a mismatch.
770 int ret = memcmp((void *)ptr1, (void *)ptr2, amt);
776 * No mismatch found. Let the caller know the two memory
782 static void vm_userspace_mem_region_gpa_insert(struct rb_root *gpa_tree,
783 struct userspace_mem_region *region)
785 struct rb_node **cur, *parent;
787 for (cur = &gpa_tree->rb_node, parent = NULL; *cur; ) {
788 struct userspace_mem_region *cregion;
790 cregion = container_of(*cur, typeof(*cregion), gpa_node);
792 if (region->region.guest_phys_addr <
793 cregion->region.guest_phys_addr)
794 cur = &(*cur)->rb_left;
796 TEST_ASSERT(region->region.guest_phys_addr !=
797 cregion->region.guest_phys_addr,
798 "Duplicate GPA in region tree");
800 cur = &(*cur)->rb_right;
804 rb_link_node(®ion->gpa_node, parent, cur);
805 rb_insert_color(®ion->gpa_node, gpa_tree);
808 static void vm_userspace_mem_region_hva_insert(struct rb_root *hva_tree,
809 struct userspace_mem_region *region)
811 struct rb_node **cur, *parent;
813 for (cur = &hva_tree->rb_node, parent = NULL; *cur; ) {
814 struct userspace_mem_region *cregion;
816 cregion = container_of(*cur, typeof(*cregion), hva_node);
818 if (region->host_mem < cregion->host_mem)
819 cur = &(*cur)->rb_left;
821 TEST_ASSERT(region->host_mem !=
823 "Duplicate HVA in region tree");
825 cur = &(*cur)->rb_right;
829 rb_link_node(®ion->hva_node, parent, cur);
830 rb_insert_color(®ion->hva_node, hva_tree);
834 * VM Userspace Memory Region Add
837 * vm - Virtual Machine
838 * src_type - Storage source for this region.
839 * NULL to use anonymous memory.
840 * guest_paddr - Starting guest physical address
841 * slot - KVM region slot
842 * npages - Number of physical pages
843 * flags - KVM memory region flags (e.g. KVM_MEM_LOG_DIRTY_PAGES)
849 * Allocates a memory area of the number of pages specified by npages
850 * and maps it to the VM specified by vm, at a starting physical address
851 * given by guest_paddr. The region is created with a KVM region slot
852 * given by slot, which must be unique and < KVM_MEM_SLOTS_NUM. The
853 * region is created with the flags given by flags.
855 void vm_userspace_mem_region_add(struct kvm_vm *vm,
856 enum vm_mem_backing_src_type src_type,
857 uint64_t guest_paddr, uint32_t slot, uint64_t npages,
861 struct userspace_mem_region *region;
862 size_t backing_src_pagesz = get_backing_src_pagesz(src_type);
865 TEST_ASSERT(vm_adjust_num_guest_pages(vm->mode, npages) == npages,
866 "Number of guest pages is not compatible with the host. "
867 "Try npages=%d", vm_adjust_num_guest_pages(vm->mode, npages));
869 TEST_ASSERT((guest_paddr % vm->page_size) == 0, "Guest physical "
870 "address not on a page boundary.\n"
871 " guest_paddr: 0x%lx vm->page_size: 0x%x",
872 guest_paddr, vm->page_size);
873 TEST_ASSERT((((guest_paddr >> vm->page_shift) + npages) - 1)
874 <= vm->max_gfn, "Physical range beyond maximum "
875 "supported physical address,\n"
876 " guest_paddr: 0x%lx npages: 0x%lx\n"
877 " vm->max_gfn: 0x%lx vm->page_size: 0x%x",
878 guest_paddr, npages, vm->max_gfn, vm->page_size);
881 * Confirm a mem region with an overlapping address doesn't
884 region = (struct userspace_mem_region *) userspace_mem_region_find(
885 vm, guest_paddr, (guest_paddr + npages * vm->page_size) - 1);
887 TEST_FAIL("overlapping userspace_mem_region already "
889 " requested guest_paddr: 0x%lx npages: 0x%lx "
891 " existing guest_paddr: 0x%lx size: 0x%lx",
892 guest_paddr, npages, vm->page_size,
893 (uint64_t) region->region.guest_phys_addr,
894 (uint64_t) region->region.memory_size);
896 /* Confirm no region with the requested slot already exists. */
897 hash_for_each_possible(vm->regions.slot_hash, region, slot_node,
899 if (region->region.slot != slot)
902 TEST_FAIL("A mem region with the requested slot "
904 " requested slot: %u paddr: 0x%lx npages: 0x%lx\n"
905 " existing slot: %u paddr: 0x%lx size: 0x%lx",
906 slot, guest_paddr, npages,
908 (uint64_t) region->region.guest_phys_addr,
909 (uint64_t) region->region.memory_size);
912 /* Allocate and initialize new mem region structure. */
913 region = calloc(1, sizeof(*region));
914 TEST_ASSERT(region != NULL, "Insufficient Memory");
915 region->mmap_size = npages * vm->page_size;
918 /* On s390x, the host address must be aligned to 1M (due to PGSTEs) */
919 alignment = 0x100000;
925 * When using THP mmap is not guaranteed to returned a hugepage aligned
926 * address so we have to pad the mmap. Padding is not needed for HugeTLB
927 * because mmap will always return an address aligned to the HugeTLB
930 if (src_type == VM_MEM_SRC_ANONYMOUS_THP)
931 alignment = max(backing_src_pagesz, alignment);
933 ASSERT_EQ(guest_paddr, align_up(guest_paddr, backing_src_pagesz));
935 /* Add enough memory to align up if necessary */
937 region->mmap_size += alignment;
940 if (backing_src_is_shared(src_type)) {
941 int memfd_flags = MFD_CLOEXEC;
943 if (src_type == VM_MEM_SRC_SHARED_HUGETLB)
944 memfd_flags |= MFD_HUGETLB;
946 region->fd = memfd_create("kvm_selftest", memfd_flags);
947 TEST_ASSERT(region->fd != -1,
948 "memfd_create failed, errno: %i", errno);
950 ret = ftruncate(region->fd, region->mmap_size);
951 TEST_ASSERT(ret == 0, "ftruncate failed, errno: %i", errno);
953 ret = fallocate(region->fd,
954 FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE, 0,
956 TEST_ASSERT(ret == 0, "fallocate failed, errno: %i", errno);
959 region->mmap_start = mmap(NULL, region->mmap_size,
960 PROT_READ | PROT_WRITE,
961 vm_mem_backing_src_alias(src_type)->flag,
963 TEST_ASSERT(region->mmap_start != MAP_FAILED,
964 "test_malloc failed, mmap_start: %p errno: %i",
965 region->mmap_start, errno);
967 TEST_ASSERT(!is_backing_src_hugetlb(src_type) ||
968 region->mmap_start == align_ptr_up(region->mmap_start, backing_src_pagesz),
969 "mmap_start %p is not aligned to HugeTLB page size 0x%lx",
970 region->mmap_start, backing_src_pagesz);
972 /* Align host address */
973 region->host_mem = align_ptr_up(region->mmap_start, alignment);
975 /* As needed perform madvise */
976 if ((src_type == VM_MEM_SRC_ANONYMOUS ||
977 src_type == VM_MEM_SRC_ANONYMOUS_THP) && thp_configured()) {
978 ret = madvise(region->host_mem, npages * vm->page_size,
979 src_type == VM_MEM_SRC_ANONYMOUS ? MADV_NOHUGEPAGE : MADV_HUGEPAGE);
980 TEST_ASSERT(ret == 0, "madvise failed, addr: %p length: 0x%lx src_type: %s",
981 region->host_mem, npages * vm->page_size,
982 vm_mem_backing_src_alias(src_type)->name);
985 region->unused_phy_pages = sparsebit_alloc();
986 sparsebit_set_num(region->unused_phy_pages,
987 guest_paddr >> vm->page_shift, npages);
988 region->region.slot = slot;
989 region->region.flags = flags;
990 region->region.guest_phys_addr = guest_paddr;
991 region->region.memory_size = npages * vm->page_size;
992 region->region.userspace_addr = (uintptr_t) region->host_mem;
993 ret = ioctl(vm->fd, KVM_SET_USER_MEMORY_REGION, ®ion->region);
994 TEST_ASSERT(ret == 0, "KVM_SET_USER_MEMORY_REGION IOCTL failed,\n"
995 " rc: %i errno: %i\n"
996 " slot: %u flags: 0x%x\n"
997 " guest_phys_addr: 0x%lx size: 0x%lx",
998 ret, errno, slot, flags,
999 guest_paddr, (uint64_t) region->region.memory_size);
1001 /* Add to quick lookup data structures */
1002 vm_userspace_mem_region_gpa_insert(&vm->regions.gpa_tree, region);
1003 vm_userspace_mem_region_hva_insert(&vm->regions.hva_tree, region);
1004 hash_add(vm->regions.slot_hash, ®ion->slot_node, slot);
1006 /* If shared memory, create an alias. */
1007 if (region->fd >= 0) {
1008 region->mmap_alias = mmap(NULL, region->mmap_size,
1009 PROT_READ | PROT_WRITE,
1010 vm_mem_backing_src_alias(src_type)->flag,
1012 TEST_ASSERT(region->mmap_alias != MAP_FAILED,
1013 "mmap of alias failed, errno: %i", errno);
1015 /* Align host alias address */
1016 region->host_alias = align_ptr_up(region->mmap_alias, alignment);
1024 * vm - Virtual Machine
1025 * memslot - KVM memory slot ID
1030 * Pointer to memory region structure that describe memory region
1031 * using kvm memory slot ID given by memslot. TEST_ASSERT failure
1032 * on error (e.g. currently no memory region using memslot as a KVM
1035 struct userspace_mem_region *
1036 memslot2region(struct kvm_vm *vm, uint32_t memslot)
1038 struct userspace_mem_region *region;
1040 hash_for_each_possible(vm->regions.slot_hash, region, slot_node,
1042 if (region->region.slot == memslot)
1045 fprintf(stderr, "No mem region with the requested slot found,\n"
1046 " requested slot: %u\n", memslot);
1047 fputs("---- vm dump ----\n", stderr);
1048 vm_dump(stderr, vm, 2);
1049 TEST_FAIL("Mem region not found");
1054 * VM Memory Region Flags Set
1057 * vm - Virtual Machine
1058 * flags - Starting guest physical address
1064 * Sets the flags of the memory region specified by the value of slot,
1065 * to the values given by flags.
1067 void vm_mem_region_set_flags(struct kvm_vm *vm, uint32_t slot, uint32_t flags)
1070 struct userspace_mem_region *region;
1072 region = memslot2region(vm, slot);
1074 region->region.flags = flags;
1076 ret = ioctl(vm->fd, KVM_SET_USER_MEMORY_REGION, ®ion->region);
1078 TEST_ASSERT(ret == 0, "KVM_SET_USER_MEMORY_REGION IOCTL failed,\n"
1079 " rc: %i errno: %i slot: %u flags: 0x%x",
1080 ret, errno, slot, flags);
1084 * VM Memory Region Move
1087 * vm - Virtual Machine
1088 * slot - Slot of the memory region to move
1089 * new_gpa - Starting guest physical address
1095 * Change the gpa of a memory region.
1097 void vm_mem_region_move(struct kvm_vm *vm, uint32_t slot, uint64_t new_gpa)
1099 struct userspace_mem_region *region;
1102 region = memslot2region(vm, slot);
1104 region->region.guest_phys_addr = new_gpa;
1106 ret = ioctl(vm->fd, KVM_SET_USER_MEMORY_REGION, ®ion->region);
1108 TEST_ASSERT(!ret, "KVM_SET_USER_MEMORY_REGION failed\n"
1109 "ret: %i errno: %i slot: %u new_gpa: 0x%lx",
1110 ret, errno, slot, new_gpa);
1114 * VM Memory Region Delete
1117 * vm - Virtual Machine
1118 * slot - Slot of the memory region to delete
1124 * Delete a memory region.
1126 void vm_mem_region_delete(struct kvm_vm *vm, uint32_t slot)
1128 __vm_mem_region_delete(vm, memslot2region(vm, slot), true);
1139 * Size of VCPU state
1141 * Returns the size of the structure pointed to by the return value
1144 static int vcpu_mmap_sz(void)
1148 dev_fd = open_kvm_dev_path_or_exit();
1150 ret = ioctl(dev_fd, KVM_GET_VCPU_MMAP_SIZE, NULL);
1151 TEST_ASSERT(ret >= sizeof(struct kvm_run),
1152 "%s KVM_GET_VCPU_MMAP_SIZE ioctl failed, rc: %i errno: %i",
1153 __func__, ret, errno);
1164 * vm - Virtual Machine
1171 * Adds a virtual CPU to the VM specified by vm with the ID given by vcpuid.
1172 * No additional VCPU setup is done.
1174 void vm_vcpu_add(struct kvm_vm *vm, uint32_t vcpuid)
1178 /* Confirm a vcpu with the specified id doesn't already exist. */
1179 vcpu = vcpu_find(vm, vcpuid);
1181 TEST_FAIL("vcpu with the specified id "
1183 " requested vcpuid: %u\n"
1184 " existing vcpuid: %u state: %p",
1185 vcpuid, vcpu->id, vcpu->state);
1187 /* Allocate and initialize new vcpu structure. */
1188 vcpu = calloc(1, sizeof(*vcpu));
1189 TEST_ASSERT(vcpu != NULL, "Insufficient Memory");
1191 vcpu->fd = ioctl(vm->fd, KVM_CREATE_VCPU, vcpuid);
1192 TEST_ASSERT(vcpu->fd >= 0, "KVM_CREATE_VCPU failed, rc: %i errno: %i",
1195 TEST_ASSERT(vcpu_mmap_sz() >= sizeof(*vcpu->state), "vcpu mmap size "
1196 "smaller than expected, vcpu_mmap_sz: %i expected_min: %zi",
1197 vcpu_mmap_sz(), sizeof(*vcpu->state));
1198 vcpu->state = (struct kvm_run *) mmap(NULL, vcpu_mmap_sz(),
1199 PROT_READ | PROT_WRITE, MAP_SHARED, vcpu->fd, 0);
1200 TEST_ASSERT(vcpu->state != MAP_FAILED, "mmap vcpu_state failed, "
1201 "vcpu id: %u errno: %i", vcpuid, errno);
1203 /* Add to linked-list of VCPUs. */
1204 list_add(&vcpu->list, &vm->vcpus);
1208 * VM Virtual Address Unused Gap
1211 * vm - Virtual Machine
1213 * vaddr_min - Minimum Virtual Address
1218 * Lowest virtual address at or below vaddr_min, with at least
1219 * sz unused bytes. TEST_ASSERT failure if no area of at least
1220 * size sz is available.
1222 * Within the VM specified by vm, locates the lowest starting virtual
1223 * address >= vaddr_min, that has at least sz unallocated bytes. A
1224 * TEST_ASSERT failure occurs for invalid input or no area of at least
1225 * sz unallocated bytes >= vaddr_min is available.
1227 static vm_vaddr_t vm_vaddr_unused_gap(struct kvm_vm *vm, size_t sz,
1228 vm_vaddr_t vaddr_min)
1230 uint64_t pages = (sz + vm->page_size - 1) >> vm->page_shift;
1232 /* Determine lowest permitted virtual page index. */
1233 uint64_t pgidx_start = (vaddr_min + vm->page_size - 1) >> vm->page_shift;
1234 if ((pgidx_start * vm->page_size) < vaddr_min)
1237 /* Loop over section with enough valid virtual page indexes. */
1238 if (!sparsebit_is_set_num(vm->vpages_valid,
1239 pgidx_start, pages))
1240 pgidx_start = sparsebit_next_set_num(vm->vpages_valid,
1241 pgidx_start, pages);
1244 * Are there enough unused virtual pages available at
1245 * the currently proposed starting virtual page index.
1246 * If not, adjust proposed starting index to next
1249 if (sparsebit_is_clear_num(vm->vpages_mapped,
1250 pgidx_start, pages))
1252 pgidx_start = sparsebit_next_clear_num(vm->vpages_mapped,
1253 pgidx_start, pages);
1254 if (pgidx_start == 0)
1258 * If needed, adjust proposed starting virtual address,
1259 * to next range of valid virtual addresses.
1261 if (!sparsebit_is_set_num(vm->vpages_valid,
1262 pgidx_start, pages)) {
1263 pgidx_start = sparsebit_next_set_num(
1264 vm->vpages_valid, pgidx_start, pages);
1265 if (pgidx_start == 0)
1268 } while (pgidx_start != 0);
1271 TEST_FAIL("No vaddr of specified pages available, pages: 0x%lx", pages);
1277 TEST_ASSERT(sparsebit_is_set_num(vm->vpages_valid,
1278 pgidx_start, pages),
1279 "Unexpected, invalid virtual page index range,\n"
1280 " pgidx_start: 0x%lx\n"
1282 pgidx_start, pages);
1283 TEST_ASSERT(sparsebit_is_clear_num(vm->vpages_mapped,
1284 pgidx_start, pages),
1285 "Unexpected, pages already mapped,\n"
1286 " pgidx_start: 0x%lx\n"
1288 pgidx_start, pages);
1290 return pgidx_start * vm->page_size;
1294 * VM Virtual Address Allocate
1297 * vm - Virtual Machine
1298 * sz - Size in bytes
1299 * vaddr_min - Minimum starting virtual address
1300 * data_memslot - Memory region slot for data pages
1301 * pgd_memslot - Memory region slot for new virtual translation tables
1306 * Starting guest virtual address
1308 * Allocates at least sz bytes within the virtual address space of the vm
1309 * given by vm. The allocated bytes are mapped to a virtual address >=
1310 * the address given by vaddr_min. Note that each allocation uses a
1311 * a unique set of pages, with the minimum real allocation being at least
1314 vm_vaddr_t vm_vaddr_alloc(struct kvm_vm *vm, size_t sz, vm_vaddr_t vaddr_min)
1316 uint64_t pages = (sz >> vm->page_shift) + ((sz % vm->page_size) != 0);
1319 vm_paddr_t paddr = vm_phy_pages_alloc(vm, pages,
1320 KVM_UTIL_MIN_PFN * vm->page_size, 0);
1323 * Find an unused range of virtual page addresses of at least
1326 vm_vaddr_t vaddr_start = vm_vaddr_unused_gap(vm, sz, vaddr_min);
1328 /* Map the virtual pages. */
1329 for (vm_vaddr_t vaddr = vaddr_start; pages > 0;
1330 pages--, vaddr += vm->page_size, paddr += vm->page_size) {
1332 virt_pg_map(vm, vaddr, paddr);
1334 sparsebit_set(vm->vpages_mapped,
1335 vaddr >> vm->page_shift);
1342 * VM Virtual Address Allocate Pages
1345 * vm - Virtual Machine
1350 * Starting guest virtual address
1352 * Allocates at least N system pages worth of bytes within the virtual address
1355 vm_vaddr_t vm_vaddr_alloc_pages(struct kvm_vm *vm, int nr_pages)
1357 return vm_vaddr_alloc(vm, nr_pages * getpagesize(), KVM_UTIL_MIN_VADDR);
1361 * VM Virtual Address Allocate Page
1364 * vm - Virtual Machine
1369 * Starting guest virtual address
1371 * Allocates at least one system page worth of bytes within the virtual address
1374 vm_vaddr_t vm_vaddr_alloc_page(struct kvm_vm *vm)
1376 return vm_vaddr_alloc_pages(vm, 1);
1380 * Map a range of VM virtual address to the VM's physical address
1383 * vm - Virtual Machine
1384 * vaddr - Virtuall address to map
1385 * paddr - VM Physical Address
1386 * npages - The number of pages to map
1387 * pgd_memslot - Memory region slot for new virtual translation tables
1393 * Within the VM given by @vm, creates a virtual translation for
1394 * @npages starting at @vaddr to the page range starting at @paddr.
1396 void virt_map(struct kvm_vm *vm, uint64_t vaddr, uint64_t paddr,
1397 unsigned int npages)
1399 size_t page_size = vm->page_size;
1400 size_t size = npages * page_size;
1402 TEST_ASSERT(vaddr + size > vaddr, "Vaddr overflow");
1403 TEST_ASSERT(paddr + size > paddr, "Paddr overflow");
1406 virt_pg_map(vm, vaddr, paddr);
1413 * Address VM Physical to Host Virtual
1416 * vm - Virtual Machine
1417 * gpa - VM physical address
1422 * Equivalent host virtual address
1424 * Locates the memory region containing the VM physical address given
1425 * by gpa, within the VM given by vm. When found, the host virtual
1426 * address providing the memory to the vm physical address is returned.
1427 * A TEST_ASSERT failure occurs if no region containing gpa exists.
1429 void *addr_gpa2hva(struct kvm_vm *vm, vm_paddr_t gpa)
1431 struct userspace_mem_region *region;
1433 region = userspace_mem_region_find(vm, gpa, gpa);
1435 TEST_FAIL("No vm physical memory at 0x%lx", gpa);
1439 return (void *)((uintptr_t)region->host_mem
1440 + (gpa - region->region.guest_phys_addr));
1444 * Address Host Virtual to VM Physical
1447 * vm - Virtual Machine
1448 * hva - Host virtual address
1453 * Equivalent VM physical address
1455 * Locates the memory region containing the host virtual address given
1456 * by hva, within the VM given by vm. When found, the equivalent
1457 * VM physical address is returned. A TEST_ASSERT failure occurs if no
1458 * region containing hva exists.
1460 vm_paddr_t addr_hva2gpa(struct kvm_vm *vm, void *hva)
1462 struct rb_node *node;
1464 for (node = vm->regions.hva_tree.rb_node; node; ) {
1465 struct userspace_mem_region *region =
1466 container_of(node, struct userspace_mem_region, hva_node);
1468 if (hva >= region->host_mem) {
1469 if (hva <= (region->host_mem
1470 + region->region.memory_size - 1))
1471 return (vm_paddr_t)((uintptr_t)
1472 region->region.guest_phys_addr
1473 + (hva - (uintptr_t)region->host_mem));
1475 node = node->rb_right;
1477 node = node->rb_left;
1480 TEST_FAIL("No mapping to a guest physical address, hva: %p", hva);
1485 * Address VM physical to Host Virtual *alias*.
1488 * vm - Virtual Machine
1489 * gpa - VM physical address
1494 * Equivalent address within the host virtual *alias* area, or NULL
1495 * (without failing the test) if the guest memory is not shared (so
1498 * When vm_create() and related functions are called with a shared memory
1499 * src_type, we also create a writable, shared alias mapping of the
1500 * underlying guest memory. This allows the host to manipulate guest memory
1501 * without mapping that memory in the guest's address space. And, for
1502 * userfaultfd-based demand paging, we can do so without triggering userfaults.
1504 void *addr_gpa2alias(struct kvm_vm *vm, vm_paddr_t gpa)
1506 struct userspace_mem_region *region;
1509 region = userspace_mem_region_find(vm, gpa, gpa);
1513 if (!region->host_alias)
1516 offset = gpa - region->region.guest_phys_addr;
1517 return (void *) ((uintptr_t) region->host_alias + offset);
1521 * VM Create IRQ Chip
1524 * vm - Virtual Machine
1530 * Creates an interrupt controller chip for the VM specified by vm.
1532 void vm_create_irqchip(struct kvm_vm *vm)
1536 ret = ioctl(vm->fd, KVM_CREATE_IRQCHIP, 0);
1537 TEST_ASSERT(ret == 0, "KVM_CREATE_IRQCHIP IOCTL failed, "
1538 "rc: %i errno: %i", ret, errno);
1540 vm->has_irqchip = true;
1547 * vm - Virtual Machine
1553 * Pointer to structure that describes the state of the VCPU.
1555 * Locates and returns a pointer to a structure that describes the
1556 * state of the VCPU with the given vcpuid.
1558 struct kvm_run *vcpu_state(struct kvm_vm *vm, uint32_t vcpuid)
1560 struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1561 TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1570 * vm - Virtual Machine
1577 * Switch to executing the code for the VCPU given by vcpuid, within the VM
1580 void vcpu_run(struct kvm_vm *vm, uint32_t vcpuid)
1582 int ret = _vcpu_run(vm, vcpuid);
1583 TEST_ASSERT(ret == 0, "KVM_RUN IOCTL failed, "
1584 "rc: %i errno: %i", ret, errno);
1587 int _vcpu_run(struct kvm_vm *vm, uint32_t vcpuid)
1589 struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1592 TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1594 rc = ioctl(vcpu->fd, KVM_RUN, NULL);
1595 } while (rc == -1 && errno == EINTR);
1597 assert_on_unhandled_exception(vm, vcpuid);
1602 int vcpu_get_fd(struct kvm_vm *vm, uint32_t vcpuid)
1604 struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1606 TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1611 void vcpu_run_complete_io(struct kvm_vm *vm, uint32_t vcpuid)
1613 struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1616 TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1618 vcpu->state->immediate_exit = 1;
1619 ret = ioctl(vcpu->fd, KVM_RUN, NULL);
1620 vcpu->state->immediate_exit = 0;
1622 TEST_ASSERT(ret == -1 && errno == EINTR,
1623 "KVM_RUN IOCTL didn't exit immediately, rc: %i, errno: %i",
1627 void vcpu_set_guest_debug(struct kvm_vm *vm, uint32_t vcpuid,
1628 struct kvm_guest_debug *debug)
1630 struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1631 int ret = ioctl(vcpu->fd, KVM_SET_GUEST_DEBUG, debug);
1633 TEST_ASSERT(ret == 0, "KVM_SET_GUEST_DEBUG failed: %d", ret);
1637 * VM VCPU Set MP State
1640 * vm - Virtual Machine
1642 * mp_state - mp_state to be set
1648 * Sets the MP state of the VCPU given by vcpuid, to the state given
1651 void vcpu_set_mp_state(struct kvm_vm *vm, uint32_t vcpuid,
1652 struct kvm_mp_state *mp_state)
1654 struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1657 TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1659 ret = ioctl(vcpu->fd, KVM_SET_MP_STATE, mp_state);
1660 TEST_ASSERT(ret == 0, "KVM_SET_MP_STATE IOCTL failed, "
1661 "rc: %i errno: %i", ret, errno);
1665 * VM VCPU Get Reg List
1668 * vm - Virtual Machine
1675 * A pointer to an allocated struct kvm_reg_list
1677 * Get the list of guest registers which are supported for
1678 * KVM_GET_ONE_REG/KVM_SET_ONE_REG calls
1680 struct kvm_reg_list *vcpu_get_reg_list(struct kvm_vm *vm, uint32_t vcpuid)
1682 struct kvm_reg_list reg_list_n = { .n = 0 }, *reg_list;
1685 ret = _vcpu_ioctl(vm, vcpuid, KVM_GET_REG_LIST, ®_list_n);
1686 TEST_ASSERT(ret == -1 && errno == E2BIG, "KVM_GET_REG_LIST n=0");
1687 reg_list = calloc(1, sizeof(*reg_list) + reg_list_n.n * sizeof(__u64));
1688 reg_list->n = reg_list_n.n;
1689 vcpu_ioctl(vm, vcpuid, KVM_GET_REG_LIST, reg_list);
1697 * vm - Virtual Machine
1701 * regs - current state of VCPU regs
1705 * Obtains the current register state for the VCPU specified by vcpuid
1706 * and stores it at the location given by regs.
1708 void vcpu_regs_get(struct kvm_vm *vm, uint32_t vcpuid, struct kvm_regs *regs)
1710 struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1713 TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1715 ret = ioctl(vcpu->fd, KVM_GET_REGS, regs);
1716 TEST_ASSERT(ret == 0, "KVM_GET_REGS failed, rc: %i errno: %i",
1724 * vm - Virtual Machine
1726 * regs - Values to set VCPU regs to
1732 * Sets the regs of the VCPU specified by vcpuid to the values
1735 void vcpu_regs_set(struct kvm_vm *vm, uint32_t vcpuid, struct kvm_regs *regs)
1737 struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1740 TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1742 ret = ioctl(vcpu->fd, KVM_SET_REGS, regs);
1743 TEST_ASSERT(ret == 0, "KVM_SET_REGS failed, rc: %i errno: %i",
1747 #ifdef __KVM_HAVE_VCPU_EVENTS
1748 void vcpu_events_get(struct kvm_vm *vm, uint32_t vcpuid,
1749 struct kvm_vcpu_events *events)
1751 struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1754 TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1756 ret = ioctl(vcpu->fd, KVM_GET_VCPU_EVENTS, events);
1757 TEST_ASSERT(ret == 0, "KVM_GET_VCPU_EVENTS, failed, rc: %i errno: %i",
1761 void vcpu_events_set(struct kvm_vm *vm, uint32_t vcpuid,
1762 struct kvm_vcpu_events *events)
1764 struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1767 TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1769 ret = ioctl(vcpu->fd, KVM_SET_VCPU_EVENTS, events);
1770 TEST_ASSERT(ret == 0, "KVM_SET_VCPU_EVENTS, failed, rc: %i errno: %i",
1776 void vcpu_nested_state_get(struct kvm_vm *vm, uint32_t vcpuid,
1777 struct kvm_nested_state *state)
1779 struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1782 TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1784 ret = ioctl(vcpu->fd, KVM_GET_NESTED_STATE, state);
1785 TEST_ASSERT(ret == 0,
1786 "KVM_SET_NESTED_STATE failed, ret: %i errno: %i",
1790 int vcpu_nested_state_set(struct kvm_vm *vm, uint32_t vcpuid,
1791 struct kvm_nested_state *state, bool ignore_error)
1793 struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1796 TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1798 ret = ioctl(vcpu->fd, KVM_SET_NESTED_STATE, state);
1799 if (!ignore_error) {
1800 TEST_ASSERT(ret == 0,
1801 "KVM_SET_NESTED_STATE failed, ret: %i errno: %i",
1810 * VM VCPU System Regs Get
1813 * vm - Virtual Machine
1817 * sregs - current state of VCPU system regs
1821 * Obtains the current system register state for the VCPU specified by
1822 * vcpuid and stores it at the location given by sregs.
1824 void vcpu_sregs_get(struct kvm_vm *vm, uint32_t vcpuid, struct kvm_sregs *sregs)
1826 struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1829 TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1831 ret = ioctl(vcpu->fd, KVM_GET_SREGS, sregs);
1832 TEST_ASSERT(ret == 0, "KVM_GET_SREGS failed, rc: %i errno: %i",
1837 * VM VCPU System Regs Set
1840 * vm - Virtual Machine
1842 * sregs - Values to set VCPU system regs to
1848 * Sets the system regs of the VCPU specified by vcpuid to the values
1851 void vcpu_sregs_set(struct kvm_vm *vm, uint32_t vcpuid, struct kvm_sregs *sregs)
1853 int ret = _vcpu_sregs_set(vm, vcpuid, sregs);
1854 TEST_ASSERT(ret == 0, "KVM_SET_SREGS IOCTL failed, "
1855 "rc: %i errno: %i", ret, errno);
1858 int _vcpu_sregs_set(struct kvm_vm *vm, uint32_t vcpuid, struct kvm_sregs *sregs)
1860 struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1862 TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1864 return ioctl(vcpu->fd, KVM_SET_SREGS, sregs);
1867 void vcpu_fpu_get(struct kvm_vm *vm, uint32_t vcpuid, struct kvm_fpu *fpu)
1871 ret = _vcpu_ioctl(vm, vcpuid, KVM_GET_FPU, fpu);
1872 TEST_ASSERT(ret == 0, "KVM_GET_FPU failed, rc: %i errno: %i (%s)",
1873 ret, errno, strerror(errno));
1876 void vcpu_fpu_set(struct kvm_vm *vm, uint32_t vcpuid, struct kvm_fpu *fpu)
1880 ret = _vcpu_ioctl(vm, vcpuid, KVM_SET_FPU, fpu);
1881 TEST_ASSERT(ret == 0, "KVM_SET_FPU failed, rc: %i errno: %i (%s)",
1882 ret, errno, strerror(errno));
1885 void vcpu_get_reg(struct kvm_vm *vm, uint32_t vcpuid, struct kvm_one_reg *reg)
1889 ret = _vcpu_ioctl(vm, vcpuid, KVM_GET_ONE_REG, reg);
1890 TEST_ASSERT(ret == 0, "KVM_GET_ONE_REG failed, rc: %i errno: %i (%s)",
1891 ret, errno, strerror(errno));
1894 void vcpu_set_reg(struct kvm_vm *vm, uint32_t vcpuid, struct kvm_one_reg *reg)
1898 ret = _vcpu_ioctl(vm, vcpuid, KVM_SET_ONE_REG, reg);
1899 TEST_ASSERT(ret == 0, "KVM_SET_ONE_REG failed, rc: %i errno: %i (%s)",
1900 ret, errno, strerror(errno));
1907 * vm - Virtual Machine
1909 * cmd - Ioctl number
1910 * arg - Argument to pass to the ioctl
1914 * Issues an arbitrary ioctl on a VCPU fd.
1916 void vcpu_ioctl(struct kvm_vm *vm, uint32_t vcpuid,
1917 unsigned long cmd, void *arg)
1921 ret = _vcpu_ioctl(vm, vcpuid, cmd, arg);
1922 TEST_ASSERT(ret == 0, "vcpu ioctl %lu failed, rc: %i errno: %i (%s)",
1923 cmd, ret, errno, strerror(errno));
1926 int _vcpu_ioctl(struct kvm_vm *vm, uint32_t vcpuid,
1927 unsigned long cmd, void *arg)
1929 struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1932 TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1934 ret = ioctl(vcpu->fd, cmd, arg);
1939 void *vcpu_map_dirty_ring(struct kvm_vm *vm, uint32_t vcpuid)
1942 uint32_t size = vm->dirty_ring_size;
1944 TEST_ASSERT(size > 0, "Should enable dirty ring first");
1946 vcpu = vcpu_find(vm, vcpuid);
1948 TEST_ASSERT(vcpu, "Cannot find vcpu %u", vcpuid);
1950 if (!vcpu->dirty_gfns) {
1953 addr = mmap(NULL, size, PROT_READ,
1954 MAP_PRIVATE, vcpu->fd,
1955 vm->page_size * KVM_DIRTY_LOG_PAGE_OFFSET);
1956 TEST_ASSERT(addr == MAP_FAILED, "Dirty ring mapped private");
1958 addr = mmap(NULL, size, PROT_READ | PROT_EXEC,
1959 MAP_PRIVATE, vcpu->fd,
1960 vm->page_size * KVM_DIRTY_LOG_PAGE_OFFSET);
1961 TEST_ASSERT(addr == MAP_FAILED, "Dirty ring mapped exec");
1963 addr = mmap(NULL, size, PROT_READ | PROT_WRITE,
1964 MAP_SHARED, vcpu->fd,
1965 vm->page_size * KVM_DIRTY_LOG_PAGE_OFFSET);
1966 TEST_ASSERT(addr != MAP_FAILED, "Dirty ring map failed");
1968 vcpu->dirty_gfns = addr;
1969 vcpu->dirty_gfns_count = size / sizeof(struct kvm_dirty_gfn);
1972 return vcpu->dirty_gfns;
1979 * vm - Virtual Machine
1980 * cmd - Ioctl number
1981 * arg - Argument to pass to the ioctl
1985 * Issues an arbitrary ioctl on a VM fd.
1987 void vm_ioctl(struct kvm_vm *vm, unsigned long cmd, void *arg)
1991 ret = _vm_ioctl(vm, cmd, arg);
1992 TEST_ASSERT(ret == 0, "vm ioctl %lu failed, rc: %i errno: %i (%s)",
1993 cmd, ret, errno, strerror(errno));
1996 int _vm_ioctl(struct kvm_vm *vm, unsigned long cmd, void *arg)
1998 return ioctl(vm->fd, cmd, arg);
2005 * vm - Virtual Machine
2006 * cmd - Ioctl number
2007 * arg - Argument to pass to the ioctl
2011 * Issues an arbitrary ioctl on a KVM fd.
2013 void kvm_ioctl(struct kvm_vm *vm, unsigned long cmd, void *arg)
2017 ret = ioctl(vm->kvm_fd, cmd, arg);
2018 TEST_ASSERT(ret == 0, "KVM ioctl %lu failed, rc: %i errno: %i (%s)",
2019 cmd, ret, errno, strerror(errno));
2022 int _kvm_ioctl(struct kvm_vm *vm, unsigned long cmd, void *arg)
2024 return ioctl(vm->kvm_fd, cmd, arg);
2031 int _kvm_device_check_attr(int dev_fd, uint32_t group, uint64_t attr)
2033 struct kvm_device_attr attribute = {
2039 return ioctl(dev_fd, KVM_HAS_DEVICE_ATTR, &attribute);
2042 int kvm_device_check_attr(int dev_fd, uint32_t group, uint64_t attr)
2044 int ret = _kvm_device_check_attr(dev_fd, group, attr);
2046 TEST_ASSERT(!ret, "KVM_HAS_DEVICE_ATTR failed, rc: %i errno: %i", ret, errno);
2050 int _kvm_create_device(struct kvm_vm *vm, uint64_t type, bool test, int *fd)
2052 struct kvm_create_device create_dev;
2055 create_dev.type = type;
2057 create_dev.flags = test ? KVM_CREATE_DEVICE_TEST : 0;
2058 ret = ioctl(vm_get_fd(vm), KVM_CREATE_DEVICE, &create_dev);
2059 *fd = create_dev.fd;
2063 int kvm_create_device(struct kvm_vm *vm, uint64_t type, bool test)
2067 ret = _kvm_create_device(vm, type, test, &fd);
2071 "KVM_CREATE_DEVICE IOCTL failed, rc: %i errno: %i", ret, errno);
2077 int _kvm_device_access(int dev_fd, uint32_t group, uint64_t attr,
2078 void *val, bool write)
2080 struct kvm_device_attr kvmattr = {
2084 .addr = (uintptr_t)val,
2088 ret = ioctl(dev_fd, write ? KVM_SET_DEVICE_ATTR : KVM_GET_DEVICE_ATTR,
2093 int kvm_device_access(int dev_fd, uint32_t group, uint64_t attr,
2094 void *val, bool write)
2096 int ret = _kvm_device_access(dev_fd, group, attr, val, write);
2098 TEST_ASSERT(!ret, "KVM_SET|GET_DEVICE_ATTR IOCTL failed, rc: %i errno: %i", ret, errno);
2102 int _vcpu_has_device_attr(struct kvm_vm *vm, uint32_t vcpuid, uint32_t group,
2105 struct vcpu *vcpu = vcpu_find(vm, vcpuid);
2107 TEST_ASSERT(vcpu, "nonexistent vcpu id: %d", vcpuid);
2109 return _kvm_device_check_attr(vcpu->fd, group, attr);
2112 int vcpu_has_device_attr(struct kvm_vm *vm, uint32_t vcpuid, uint32_t group,
2115 int ret = _vcpu_has_device_attr(vm, vcpuid, group, attr);
2117 TEST_ASSERT(!ret, "KVM_HAS_DEVICE_ATTR IOCTL failed, rc: %i errno: %i", ret, errno);
2121 int _vcpu_access_device_attr(struct kvm_vm *vm, uint32_t vcpuid, uint32_t group,
2122 uint64_t attr, void *val, bool write)
2124 struct vcpu *vcpu = vcpu_find(vm, vcpuid);
2126 TEST_ASSERT(vcpu, "nonexistent vcpu id: %d", vcpuid);
2128 return _kvm_device_access(vcpu->fd, group, attr, val, write);
2131 int vcpu_access_device_attr(struct kvm_vm *vm, uint32_t vcpuid, uint32_t group,
2132 uint64_t attr, void *val, bool write)
2134 int ret = _vcpu_access_device_attr(vm, vcpuid, group, attr, val, write);
2136 TEST_ASSERT(!ret, "KVM_SET|GET_DEVICE_ATTR IOCTL failed, rc: %i errno: %i", ret, errno);
2141 * IRQ related functions.
2144 int _kvm_irq_line(struct kvm_vm *vm, uint32_t irq, int level)
2146 struct kvm_irq_level irq_level = {
2151 return _vm_ioctl(vm, KVM_IRQ_LINE, &irq_level);
2154 void kvm_irq_line(struct kvm_vm *vm, uint32_t irq, int level)
2156 int ret = _kvm_irq_line(vm, irq, level);
2158 TEST_ASSERT(ret >= 0, "KVM_IRQ_LINE failed, rc: %i errno: %i", ret, errno);
2161 struct kvm_irq_routing *kvm_gsi_routing_create(void)
2163 struct kvm_irq_routing *routing;
2166 size = sizeof(struct kvm_irq_routing);
2167 /* Allocate space for the max number of entries: this wastes 196 KBs. */
2168 size += KVM_MAX_IRQ_ROUTES * sizeof(struct kvm_irq_routing_entry);
2169 routing = calloc(1, size);
2175 void kvm_gsi_routing_irqchip_add(struct kvm_irq_routing *routing,
2176 uint32_t gsi, uint32_t pin)
2181 assert(routing->nr < KVM_MAX_IRQ_ROUTES);
2184 routing->entries[i].gsi = gsi;
2185 routing->entries[i].type = KVM_IRQ_ROUTING_IRQCHIP;
2186 routing->entries[i].flags = 0;
2187 routing->entries[i].u.irqchip.irqchip = 0;
2188 routing->entries[i].u.irqchip.pin = pin;
2192 int _kvm_gsi_routing_write(struct kvm_vm *vm, struct kvm_irq_routing *routing)
2197 ret = ioctl(vm_get_fd(vm), KVM_SET_GSI_ROUTING, routing);
2203 void kvm_gsi_routing_write(struct kvm_vm *vm, struct kvm_irq_routing *routing)
2207 ret = _kvm_gsi_routing_write(vm, routing);
2208 TEST_ASSERT(ret == 0, "KVM_SET_GSI_ROUTING failed, rc: %i errno: %i",
2216 * vm - Virtual Machine
2217 * indent - Left margin indent amount
2220 * stream - Output FILE stream
2224 * Dumps the current state of the VM given by vm, to the FILE stream
2227 void vm_dump(FILE *stream, struct kvm_vm *vm, uint8_t indent)
2230 struct userspace_mem_region *region;
2233 fprintf(stream, "%*smode: 0x%x\n", indent, "", vm->mode);
2234 fprintf(stream, "%*sfd: %i\n", indent, "", vm->fd);
2235 fprintf(stream, "%*spage_size: 0x%x\n", indent, "", vm->page_size);
2236 fprintf(stream, "%*sMem Regions:\n", indent, "");
2237 hash_for_each(vm->regions.slot_hash, ctr, region, slot_node) {
2238 fprintf(stream, "%*sguest_phys: 0x%lx size: 0x%lx "
2239 "host_virt: %p\n", indent + 2, "",
2240 (uint64_t) region->region.guest_phys_addr,
2241 (uint64_t) region->region.memory_size,
2243 fprintf(stream, "%*sunused_phy_pages: ", indent + 2, "");
2244 sparsebit_dump(stream, region->unused_phy_pages, 0);
2246 fprintf(stream, "%*sMapped Virtual Pages:\n", indent, "");
2247 sparsebit_dump(stream, vm->vpages_mapped, indent + 2);
2248 fprintf(stream, "%*spgd_created: %u\n", indent, "",
2250 if (vm->pgd_created) {
2251 fprintf(stream, "%*sVirtual Translation Tables:\n",
2253 virt_dump(stream, vm, indent + 4);
2255 fprintf(stream, "%*sVCPUs:\n", indent, "");
2256 list_for_each_entry(vcpu, &vm->vcpus, list)
2257 vcpu_dump(stream, vm, vcpu->id, indent + 2);
2260 /* Known KVM exit reasons */
2261 static struct exit_reason {
2262 unsigned int reason;
2264 } exit_reasons_known[] = {
2265 {KVM_EXIT_UNKNOWN, "UNKNOWN"},
2266 {KVM_EXIT_EXCEPTION, "EXCEPTION"},
2267 {KVM_EXIT_IO, "IO"},
2268 {KVM_EXIT_HYPERCALL, "HYPERCALL"},
2269 {KVM_EXIT_DEBUG, "DEBUG"},
2270 {KVM_EXIT_HLT, "HLT"},
2271 {KVM_EXIT_MMIO, "MMIO"},
2272 {KVM_EXIT_IRQ_WINDOW_OPEN, "IRQ_WINDOW_OPEN"},
2273 {KVM_EXIT_SHUTDOWN, "SHUTDOWN"},
2274 {KVM_EXIT_FAIL_ENTRY, "FAIL_ENTRY"},
2275 {KVM_EXIT_INTR, "INTR"},
2276 {KVM_EXIT_SET_TPR, "SET_TPR"},
2277 {KVM_EXIT_TPR_ACCESS, "TPR_ACCESS"},
2278 {KVM_EXIT_S390_SIEIC, "S390_SIEIC"},
2279 {KVM_EXIT_S390_RESET, "S390_RESET"},
2280 {KVM_EXIT_DCR, "DCR"},
2281 {KVM_EXIT_NMI, "NMI"},
2282 {KVM_EXIT_INTERNAL_ERROR, "INTERNAL_ERROR"},
2283 {KVM_EXIT_OSI, "OSI"},
2284 {KVM_EXIT_PAPR_HCALL, "PAPR_HCALL"},
2285 {KVM_EXIT_DIRTY_RING_FULL, "DIRTY_RING_FULL"},
2286 {KVM_EXIT_X86_RDMSR, "RDMSR"},
2287 {KVM_EXIT_X86_WRMSR, "WRMSR"},
2288 {KVM_EXIT_XEN, "XEN"},
2289 #ifdef KVM_EXIT_MEMORY_NOT_PRESENT
2290 {KVM_EXIT_MEMORY_NOT_PRESENT, "MEMORY_NOT_PRESENT"},
2295 * Exit Reason String
2298 * exit_reason - Exit reason
2303 * Constant string pointer describing the exit reason.
2305 * Locates and returns a constant string that describes the KVM exit
2306 * reason given by exit_reason. If no such string is found, a constant
2307 * string of "Unknown" is returned.
2309 const char *exit_reason_str(unsigned int exit_reason)
2313 for (n1 = 0; n1 < ARRAY_SIZE(exit_reasons_known); n1++) {
2314 if (exit_reason == exit_reasons_known[n1].reason)
2315 return exit_reasons_known[n1].name;
2322 * Physical Contiguous Page Allocator
2325 * vm - Virtual Machine
2326 * num - number of pages
2327 * paddr_min - Physical address minimum
2328 * memslot - Memory region to allocate page from
2333 * Starting physical address
2335 * Within the VM specified by vm, locates a range of available physical
2336 * pages at or above paddr_min. If found, the pages are marked as in use
2337 * and their base address is returned. A TEST_ASSERT failure occurs if
2338 * not enough pages are available at or above paddr_min.
2340 vm_paddr_t vm_phy_pages_alloc(struct kvm_vm *vm, size_t num,
2341 vm_paddr_t paddr_min, uint32_t memslot)
2343 struct userspace_mem_region *region;
2344 sparsebit_idx_t pg, base;
2346 TEST_ASSERT(num > 0, "Must allocate at least one page");
2348 TEST_ASSERT((paddr_min % vm->page_size) == 0, "Min physical address "
2349 "not divisible by page size.\n"
2350 " paddr_min: 0x%lx page_size: 0x%x",
2351 paddr_min, vm->page_size);
2353 region = memslot2region(vm, memslot);
2354 base = pg = paddr_min >> vm->page_shift;
2357 for (; pg < base + num; ++pg) {
2358 if (!sparsebit_is_set(region->unused_phy_pages, pg)) {
2359 base = pg = sparsebit_next_set(region->unused_phy_pages, pg);
2363 } while (pg && pg != base + num);
2366 fprintf(stderr, "No guest physical page available, "
2367 "paddr_min: 0x%lx page_size: 0x%x memslot: %u\n",
2368 paddr_min, vm->page_size, memslot);
2369 fputs("---- vm dump ----\n", stderr);
2370 vm_dump(stderr, vm, 2);
2374 for (pg = base; pg < base + num; ++pg)
2375 sparsebit_clear(region->unused_phy_pages, pg);
2377 return base * vm->page_size;
2380 vm_paddr_t vm_phy_page_alloc(struct kvm_vm *vm, vm_paddr_t paddr_min,
2383 return vm_phy_pages_alloc(vm, 1, paddr_min, memslot);
2386 /* Arbitrary minimum physical address used for virtual translation tables. */
2387 #define KVM_GUEST_PAGE_TABLE_MIN_PADDR 0x180000
2389 vm_paddr_t vm_alloc_page_table(struct kvm_vm *vm)
2391 return vm_phy_page_alloc(vm, KVM_GUEST_PAGE_TABLE_MIN_PADDR, 0);
2395 * Address Guest Virtual to Host Virtual
2398 * vm - Virtual Machine
2399 * gva - VM virtual address
2404 * Equivalent host virtual address
2406 void *addr_gva2hva(struct kvm_vm *vm, vm_vaddr_t gva)
2408 return addr_gpa2hva(vm, addr_gva2gpa(vm, gva));
2412 * Is Unrestricted Guest
2415 * vm - Virtual Machine
2419 * Return: True if the unrestricted guest is set to 'Y', otherwise return false.
2421 * Check if the unrestricted guest flag is enabled.
2423 bool vm_is_unrestricted_guest(struct kvm_vm *vm)
2430 /* Ensure that the KVM vendor-specific module is loaded. */
2431 close(open_kvm_dev_path_or_exit());
2434 f = fopen("/sys/module/kvm_intel/parameters/unrestricted_guest", "r");
2436 count = fread(&val, sizeof(char), 1, f);
2437 TEST_ASSERT(count == 1, "Unable to read from param file.");
2444 unsigned int vm_get_page_size(struct kvm_vm *vm)
2446 return vm->page_size;
2449 unsigned int vm_get_page_shift(struct kvm_vm *vm)
2451 return vm->page_shift;
2454 unsigned long __attribute__((weak)) vm_compute_max_gfn(struct kvm_vm *vm)
2456 return ((1ULL << vm->pa_bits) >> vm->page_shift) - 1;
2459 uint64_t vm_get_max_gfn(struct kvm_vm *vm)
2464 int vm_get_fd(struct kvm_vm *vm)
2469 static unsigned int vm_calc_num_pages(unsigned int num_pages,
2470 unsigned int page_shift,
2471 unsigned int new_page_shift,
2474 unsigned int n = 1 << (new_page_shift - page_shift);
2476 if (page_shift >= new_page_shift)
2477 return num_pages * (1 << (page_shift - new_page_shift));
2479 return num_pages / n + !!(ceil && num_pages % n);
2482 static inline int getpageshift(void)
2484 return __builtin_ffs(getpagesize()) - 1;
2488 vm_num_host_pages(enum vm_guest_mode mode, unsigned int num_guest_pages)
2490 return vm_calc_num_pages(num_guest_pages,
2491 vm_guest_mode_params[mode].page_shift,
2492 getpageshift(), true);
2496 vm_num_guest_pages(enum vm_guest_mode mode, unsigned int num_host_pages)
2498 return vm_calc_num_pages(num_host_pages, getpageshift(),
2499 vm_guest_mode_params[mode].page_shift, false);
2502 unsigned int vm_calc_num_guest_pages(enum vm_guest_mode mode, size_t size)
2505 n = DIV_ROUND_UP(size, vm_guest_mode_params[mode].page_size);
2506 return vm_adjust_num_guest_pages(mode, n);
2509 int vm_get_stats_fd(struct kvm_vm *vm)
2511 return ioctl(vm->fd, KVM_GET_STATS_FD, NULL);
2514 int vcpu_get_stats_fd(struct kvm_vm *vm, uint32_t vcpuid)
2516 struct vcpu *vcpu = vcpu_find(vm, vcpuid);
2518 return ioctl(vcpu->fd, KVM_GET_STATS_FD, NULL);