1 // SPDX-License-Identifier: GPL-2.0-only
3 * tools/testing/selftests/kvm/lib/kvm_util.c
5 * Copyright (C) 2018, Google LLC.
10 #include "kvm_util_internal.h"
11 #include "processor.h"
15 #include <sys/types.h>
17 #include <linux/kernel.h>
19 #define KVM_UTIL_PGS_PER_HUGEPG 512
20 #define KVM_UTIL_MIN_PFN 2
22 /* Aligns x up to the next multiple of size. Size must be a power of 2. */
23 static void *align(void *x, size_t size)
25 size_t mask = size - 1;
26 TEST_ASSERT(size != 0 && !(size & (size - 1)),
27 "size not a power of 2: %lu", size);
28 return (void *) (((size_t) x + mask) & ~mask);
40 * On success, the Value corresponding to the capability (KVM_CAP_*)
41 * specified by the value of cap. On failure a TEST_ASSERT failure
44 * Looks up and returns the value corresponding to the capability
45 * (KVM_CAP_*) given by cap.
47 int kvm_check_cap(long cap)
52 kvm_fd = open(KVM_DEV_PATH, O_RDONLY);
56 ret = ioctl(kvm_fd, KVM_CHECK_EXTENSION, cap);
57 TEST_ASSERT(ret != -1, "KVM_CHECK_EXTENSION IOCTL failed,\n"
58 " rc: %i errno: %i", ret, errno);
65 /* VM Enable Capability
68 * vm - Virtual Machine
73 * Return: On success, 0. On failure a TEST_ASSERT failure is produced.
75 * Enables a capability (KVM_CAP_*) on the VM.
77 int vm_enable_cap(struct kvm_vm *vm, struct kvm_enable_cap *cap)
81 ret = ioctl(vm->fd, KVM_ENABLE_CAP, cap);
82 TEST_ASSERT(ret == 0, "KVM_ENABLE_CAP IOCTL failed,\n"
83 " rc: %i errno: %i", ret, errno);
88 static void vm_open(struct kvm_vm *vm, int perm)
90 vm->kvm_fd = open(KVM_DEV_PATH, perm);
94 if (!kvm_check_cap(KVM_CAP_IMMEDIATE_EXIT)) {
95 print_skip("immediate_exit not available");
99 vm->fd = ioctl(vm->kvm_fd, KVM_CREATE_VM, vm->type);
100 TEST_ASSERT(vm->fd >= 0, "KVM_CREATE_VM ioctl failed, "
101 "rc: %i errno: %i", vm->fd, errno);
104 const char * const vm_guest_mode_string[] = {
105 "PA-bits:52, VA-bits:48, 4K pages",
106 "PA-bits:52, VA-bits:48, 64K pages",
107 "PA-bits:48, VA-bits:48, 4K pages",
108 "PA-bits:48, VA-bits:48, 64K pages",
109 "PA-bits:40, VA-bits:48, 4K pages",
110 "PA-bits:40, VA-bits:48, 64K pages",
111 "PA-bits:ANY, VA-bits:48, 4K pages",
113 _Static_assert(sizeof(vm_guest_mode_string)/sizeof(char *) == NUM_VM_MODES,
114 "Missing new mode strings?");
116 struct vm_guest_mode_params {
117 unsigned int pa_bits;
118 unsigned int va_bits;
119 unsigned int page_size;
120 unsigned int page_shift;
123 static const struct vm_guest_mode_params vm_guest_mode_params[] = {
124 { 52, 48, 0x1000, 12 },
125 { 52, 48, 0x10000, 16 },
126 { 48, 48, 0x1000, 12 },
127 { 48, 48, 0x10000, 16 },
128 { 40, 48, 0x1000, 12 },
129 { 40, 48, 0x10000, 16 },
130 { 0, 0, 0x1000, 12 },
132 _Static_assert(sizeof(vm_guest_mode_params)/sizeof(struct vm_guest_mode_params) == NUM_VM_MODES,
133 "Missing new mode params?");
139 * mode - VM Mode (e.g. VM_MODE_P52V48_4K)
140 * phy_pages - Physical memory pages
146 * Pointer to opaque structure that describes the created VM.
148 * Creates a VM with the mode specified by mode (e.g. VM_MODE_P52V48_4K).
149 * When phy_pages is non-zero, a memory region of phy_pages physical pages
150 * is created and mapped starting at guest physical address 0. The file
151 * descriptor to control the created VM is created with the permissions
152 * given by perm (e.g. O_RDWR).
154 struct kvm_vm *_vm_create(enum vm_guest_mode mode, uint64_t phy_pages, int perm)
158 pr_debug("%s: mode='%s' pages='%ld' perm='%d'\n", __func__,
159 vm_guest_mode_string(mode), phy_pages, perm);
161 vm = calloc(1, sizeof(*vm));
162 TEST_ASSERT(vm != NULL, "Insufficient Memory");
164 INIT_LIST_HEAD(&vm->vcpus);
165 INIT_LIST_HEAD(&vm->userspace_mem_regions);
170 vm->pa_bits = vm_guest_mode_params[mode].pa_bits;
171 vm->va_bits = vm_guest_mode_params[mode].va_bits;
172 vm->page_size = vm_guest_mode_params[mode].page_size;
173 vm->page_shift = vm_guest_mode_params[mode].page_shift;
175 /* Setup mode specific traits. */
177 case VM_MODE_P52V48_4K:
178 vm->pgtable_levels = 4;
180 case VM_MODE_P52V48_64K:
181 vm->pgtable_levels = 3;
183 case VM_MODE_P48V48_4K:
184 vm->pgtable_levels = 4;
186 case VM_MODE_P48V48_64K:
187 vm->pgtable_levels = 3;
189 case VM_MODE_P40V48_4K:
190 vm->pgtable_levels = 4;
192 case VM_MODE_P40V48_64K:
193 vm->pgtable_levels = 3;
195 case VM_MODE_PXXV48_4K:
197 kvm_get_cpu_address_width(&vm->pa_bits, &vm->va_bits);
198 TEST_ASSERT(vm->va_bits == 48, "Linear address width "
199 "(%d bits) not supported", vm->va_bits);
200 pr_debug("Guest physical address width detected: %d\n",
202 vm->pgtable_levels = 4;
204 TEST_FAIL("VM_MODE_PXXV48_4K not supported on non-x86 platforms");
208 TEST_FAIL("Unknown guest mode, mode: 0x%x", mode);
212 if (vm->pa_bits != 40)
213 vm->type = KVM_VM_TYPE_ARM_IPA_SIZE(vm->pa_bits);
218 /* Limit to VA-bit canonical virtual addresses. */
219 vm->vpages_valid = sparsebit_alloc();
220 sparsebit_set_num(vm->vpages_valid,
221 0, (1ULL << (vm->va_bits - 1)) >> vm->page_shift);
222 sparsebit_set_num(vm->vpages_valid,
223 (~((1ULL << (vm->va_bits - 1)) - 1)) >> vm->page_shift,
224 (1ULL << (vm->va_bits - 1)) >> vm->page_shift);
226 /* Limit physical addresses to PA-bits. */
227 vm->max_gfn = ((1ULL << vm->pa_bits) >> vm->page_shift) - 1;
229 /* Allocate and setup memory for guest. */
230 vm->vpages_mapped = sparsebit_alloc();
232 vm_userspace_mem_region_add(vm, VM_MEM_SRC_ANONYMOUS,
238 struct kvm_vm *vm_create(enum vm_guest_mode mode, uint64_t phy_pages, int perm)
240 return _vm_create(mode, phy_pages, perm);
247 * vm - VM that has been released before
252 * Reopens the file descriptors associated to the VM and reinstates the
253 * global state, such as the irqchip and the memory regions that are mapped
256 void kvm_vm_restart(struct kvm_vm *vmp, int perm)
258 struct userspace_mem_region *region;
261 if (vmp->has_irqchip)
262 vm_create_irqchip(vmp);
264 list_for_each_entry(region, &vmp->userspace_mem_regions, list) {
265 int ret = ioctl(vmp->fd, KVM_SET_USER_MEMORY_REGION, ®ion->region);
266 TEST_ASSERT(ret == 0, "KVM_SET_USER_MEMORY_REGION IOCTL failed,\n"
267 " rc: %i errno: %i\n"
268 " slot: %u flags: 0x%x\n"
269 " guest_phys_addr: 0x%llx size: 0x%llx",
270 ret, errno, region->region.slot,
271 region->region.flags,
272 region->region.guest_phys_addr,
273 region->region.memory_size);
277 void kvm_vm_get_dirty_log(struct kvm_vm *vm, int slot, void *log)
279 struct kvm_dirty_log args = { .dirty_bitmap = log, .slot = slot };
282 ret = ioctl(vm->fd, KVM_GET_DIRTY_LOG, &args);
283 TEST_ASSERT(ret == 0, "%s: KVM_GET_DIRTY_LOG failed: %s",
284 __func__, strerror(-ret));
287 void kvm_vm_clear_dirty_log(struct kvm_vm *vm, int slot, void *log,
288 uint64_t first_page, uint32_t num_pages)
290 struct kvm_clear_dirty_log args = { .dirty_bitmap = log, .slot = slot,
291 .first_page = first_page,
292 .num_pages = num_pages };
295 ret = ioctl(vm->fd, KVM_CLEAR_DIRTY_LOG, &args);
296 TEST_ASSERT(ret == 0, "%s: KVM_CLEAR_DIRTY_LOG failed: %s",
297 __func__, strerror(-ret));
301 * Userspace Memory Region Find
304 * vm - Virtual Machine
305 * start - Starting VM physical address
306 * end - Ending VM physical address, inclusive.
311 * Pointer to overlapping region, NULL if no such region.
313 * Searches for a region with any physical memory that overlaps with
314 * any portion of the guest physical addresses from start to end
315 * inclusive. If multiple overlapping regions exist, a pointer to any
316 * of the regions is returned. Null is returned only when no overlapping
319 static struct userspace_mem_region *
320 userspace_mem_region_find(struct kvm_vm *vm, uint64_t start, uint64_t end)
322 struct userspace_mem_region *region;
324 list_for_each_entry(region, &vm->userspace_mem_regions, list) {
325 uint64_t existing_start = region->region.guest_phys_addr;
326 uint64_t existing_end = region->region.guest_phys_addr
327 + region->region.memory_size - 1;
328 if (start <= existing_end && end >= existing_start)
336 * KVM Userspace Memory Region Find
339 * vm - Virtual Machine
340 * start - Starting VM physical address
341 * end - Ending VM physical address, inclusive.
346 * Pointer to overlapping region, NULL if no such region.
348 * Public interface to userspace_mem_region_find. Allows tests to look up
349 * the memslot datastructure for a given range of guest physical memory.
351 struct kvm_userspace_memory_region *
352 kvm_userspace_memory_region_find(struct kvm_vm *vm, uint64_t start,
355 struct userspace_mem_region *region;
357 region = userspace_mem_region_find(vm, start, end);
361 return ®ion->region;
368 * vm - Virtual Machine
374 * Pointer to VCPU structure
376 * Locates a vcpu structure that describes the VCPU specified by vcpuid and
377 * returns a pointer to it. Returns NULL if the VM doesn't contain a VCPU
378 * for the specified vcpuid.
380 struct vcpu *vcpu_find(struct kvm_vm *vm, uint32_t vcpuid)
384 list_for_each_entry(vcpu, &vm->vcpus, list) {
385 if (vcpu->id == vcpuid)
396 * vcpu - VCPU to remove
400 * Return: None, TEST_ASSERT failures for all error conditions
402 * Removes a vCPU from a VM and frees its resources.
404 static void vm_vcpu_rm(struct vcpu *vcpu)
408 ret = munmap(vcpu->state, sizeof(*vcpu->state));
409 TEST_ASSERT(ret == 0, "munmap of VCPU fd failed, rc: %i "
410 "errno: %i", ret, errno);
412 TEST_ASSERT(ret == 0, "Close of VCPU fd failed, rc: %i "
413 "errno: %i", ret, errno);
415 list_del(&vcpu->list);
419 void kvm_vm_release(struct kvm_vm *vmp)
421 struct vcpu *vcpu, *tmp;
424 list_for_each_entry_safe(vcpu, tmp, &vmp->vcpus, list)
427 ret = close(vmp->fd);
428 TEST_ASSERT(ret == 0, "Close of vm fd failed,\n"
429 " vmp->fd: %i rc: %i errno: %i", vmp->fd, ret, errno);
432 TEST_ASSERT(ret == 0, "Close of /dev/kvm fd failed,\n"
433 " vmp->kvm_fd: %i rc: %i errno: %i", vmp->kvm_fd, ret, errno);
436 static void __vm_mem_region_delete(struct kvm_vm *vm,
437 struct userspace_mem_region *region)
441 list_del(®ion->list);
443 region->region.memory_size = 0;
444 ret = ioctl(vm->fd, KVM_SET_USER_MEMORY_REGION, ®ion->region);
445 TEST_ASSERT(ret == 0, "KVM_SET_USER_MEMORY_REGION IOCTL failed, "
446 "rc: %i errno: %i", ret, errno);
448 sparsebit_free(®ion->unused_phy_pages);
449 ret = munmap(region->mmap_start, region->mmap_size);
450 TEST_ASSERT(ret == 0, "munmap failed, rc: %i errno: %i", ret, errno);
456 * Destroys and frees the VM pointed to by vmp.
458 void kvm_vm_free(struct kvm_vm *vmp)
460 struct userspace_mem_region *region, *tmp;
465 /* Free userspace_mem_regions. */
466 list_for_each_entry_safe(region, tmp, &vmp->userspace_mem_regions, list)
467 __vm_mem_region_delete(vmp, region);
469 /* Free sparsebit arrays. */
470 sparsebit_free(&vmp->vpages_valid);
471 sparsebit_free(&vmp->vpages_mapped);
475 /* Free the structure describing the VM. */
480 * Memory Compare, host virtual to guest virtual
483 * hva - Starting host virtual address
484 * vm - Virtual Machine
485 * gva - Starting guest virtual address
486 * len - number of bytes to compare
490 * Input/Output Args: None
493 * Returns 0 if the bytes starting at hva for a length of len
494 * are equal the guest virtual bytes starting at gva. Returns
495 * a value < 0, if bytes at hva are less than those at gva.
496 * Otherwise a value > 0 is returned.
498 * Compares the bytes starting at the host virtual address hva, for
499 * a length of len, to the guest bytes starting at the guest virtual
500 * address given by gva.
502 int kvm_memcmp_hva_gva(void *hva, struct kvm_vm *vm, vm_vaddr_t gva, size_t len)
507 * Compare a batch of bytes until either a match is found
508 * or all the bytes have been compared.
510 for (uintptr_t offset = 0; offset < len; offset += amt) {
511 uintptr_t ptr1 = (uintptr_t)hva + offset;
514 * Determine host address for guest virtual address
517 uintptr_t ptr2 = (uintptr_t)addr_gva2hva(vm, gva + offset);
520 * Determine amount to compare on this pass.
521 * Don't allow the comparsion to cross a page boundary.
524 if ((ptr1 >> vm->page_shift) != ((ptr1 + amt) >> vm->page_shift))
525 amt = vm->page_size - (ptr1 % vm->page_size);
526 if ((ptr2 >> vm->page_shift) != ((ptr2 + amt) >> vm->page_shift))
527 amt = vm->page_size - (ptr2 % vm->page_size);
529 assert((ptr1 >> vm->page_shift) == ((ptr1 + amt - 1) >> vm->page_shift));
530 assert((ptr2 >> vm->page_shift) == ((ptr2 + amt - 1) >> vm->page_shift));
533 * Perform the comparison. If there is a difference
534 * return that result to the caller, otherwise need
535 * to continue on looking for a mismatch.
537 int ret = memcmp((void *)ptr1, (void *)ptr2, amt);
543 * No mismatch found. Let the caller know the two memory
550 * VM Userspace Memory Region Add
553 * vm - Virtual Machine
554 * backing_src - Storage source for this region.
555 * NULL to use anonymous memory.
556 * guest_paddr - Starting guest physical address
557 * slot - KVM region slot
558 * npages - Number of physical pages
559 * flags - KVM memory region flags (e.g. KVM_MEM_LOG_DIRTY_PAGES)
565 * Allocates a memory area of the number of pages specified by npages
566 * and maps it to the VM specified by vm, at a starting physical address
567 * given by guest_paddr. The region is created with a KVM region slot
568 * given by slot, which must be unique and < KVM_MEM_SLOTS_NUM. The
569 * region is created with the flags given by flags.
571 void vm_userspace_mem_region_add(struct kvm_vm *vm,
572 enum vm_mem_backing_src_type src_type,
573 uint64_t guest_paddr, uint32_t slot, uint64_t npages,
577 struct userspace_mem_region *region;
578 size_t huge_page_size = KVM_UTIL_PGS_PER_HUGEPG * vm->page_size;
581 TEST_ASSERT(vm_adjust_num_guest_pages(vm->mode, npages) == npages,
582 "Number of guest pages is not compatible with the host. "
583 "Try npages=%d", vm_adjust_num_guest_pages(vm->mode, npages));
585 TEST_ASSERT((guest_paddr % vm->page_size) == 0, "Guest physical "
586 "address not on a page boundary.\n"
587 " guest_paddr: 0x%lx vm->page_size: 0x%x",
588 guest_paddr, vm->page_size);
589 TEST_ASSERT((((guest_paddr >> vm->page_shift) + npages) - 1)
590 <= vm->max_gfn, "Physical range beyond maximum "
591 "supported physical address,\n"
592 " guest_paddr: 0x%lx npages: 0x%lx\n"
593 " vm->max_gfn: 0x%lx vm->page_size: 0x%x",
594 guest_paddr, npages, vm->max_gfn, vm->page_size);
597 * Confirm a mem region with an overlapping address doesn't
600 region = (struct userspace_mem_region *) userspace_mem_region_find(
601 vm, guest_paddr, (guest_paddr + npages * vm->page_size) - 1);
603 TEST_FAIL("overlapping userspace_mem_region already "
605 " requested guest_paddr: 0x%lx npages: 0x%lx "
607 " existing guest_paddr: 0x%lx size: 0x%lx",
608 guest_paddr, npages, vm->page_size,
609 (uint64_t) region->region.guest_phys_addr,
610 (uint64_t) region->region.memory_size);
612 /* Confirm no region with the requested slot already exists. */
613 list_for_each_entry(region, &vm->userspace_mem_regions, list) {
614 if (region->region.slot != slot)
617 TEST_FAIL("A mem region with the requested slot "
619 " requested slot: %u paddr: 0x%lx npages: 0x%lx\n"
620 " existing slot: %u paddr: 0x%lx size: 0x%lx",
621 slot, guest_paddr, npages,
623 (uint64_t) region->region.guest_phys_addr,
624 (uint64_t) region->region.memory_size);
627 /* Allocate and initialize new mem region structure. */
628 region = calloc(1, sizeof(*region));
629 TEST_ASSERT(region != NULL, "Insufficient Memory");
630 region->mmap_size = npages * vm->page_size;
633 /* On s390x, the host address must be aligned to 1M (due to PGSTEs) */
634 alignment = 0x100000;
639 if (src_type == VM_MEM_SRC_ANONYMOUS_THP)
640 alignment = max(huge_page_size, alignment);
642 /* Add enough memory to align up if necessary */
644 region->mmap_size += alignment;
646 region->mmap_start = mmap(NULL, region->mmap_size,
647 PROT_READ | PROT_WRITE,
648 MAP_PRIVATE | MAP_ANONYMOUS
649 | (src_type == VM_MEM_SRC_ANONYMOUS_HUGETLB ? MAP_HUGETLB : 0),
651 TEST_ASSERT(region->mmap_start != MAP_FAILED,
652 "test_malloc failed, mmap_start: %p errno: %i",
653 region->mmap_start, errno);
655 /* Align host address */
656 region->host_mem = align(region->mmap_start, alignment);
658 /* As needed perform madvise */
659 if (src_type == VM_MEM_SRC_ANONYMOUS || src_type == VM_MEM_SRC_ANONYMOUS_THP) {
660 ret = madvise(region->host_mem, npages * vm->page_size,
661 src_type == VM_MEM_SRC_ANONYMOUS ? MADV_NOHUGEPAGE : MADV_HUGEPAGE);
662 TEST_ASSERT(ret == 0, "madvise failed,\n"
666 region->host_mem, npages * vm->page_size, src_type);
669 region->unused_phy_pages = sparsebit_alloc();
670 sparsebit_set_num(region->unused_phy_pages,
671 guest_paddr >> vm->page_shift, npages);
672 region->region.slot = slot;
673 region->region.flags = flags;
674 region->region.guest_phys_addr = guest_paddr;
675 region->region.memory_size = npages * vm->page_size;
676 region->region.userspace_addr = (uintptr_t) region->host_mem;
677 ret = ioctl(vm->fd, KVM_SET_USER_MEMORY_REGION, ®ion->region);
678 TEST_ASSERT(ret == 0, "KVM_SET_USER_MEMORY_REGION IOCTL failed,\n"
679 " rc: %i errno: %i\n"
680 " slot: %u flags: 0x%x\n"
681 " guest_phys_addr: 0x%lx size: 0x%lx",
682 ret, errno, slot, flags,
683 guest_paddr, (uint64_t) region->region.memory_size);
685 /* Add to linked-list of memory regions. */
686 list_add(®ion->list, &vm->userspace_mem_regions);
693 * vm - Virtual Machine
694 * memslot - KVM memory slot ID
699 * Pointer to memory region structure that describe memory region
700 * using kvm memory slot ID given by memslot. TEST_ASSERT failure
701 * on error (e.g. currently no memory region using memslot as a KVM
704 struct userspace_mem_region *
705 memslot2region(struct kvm_vm *vm, uint32_t memslot)
707 struct userspace_mem_region *region;
709 list_for_each_entry(region, &vm->userspace_mem_regions, list) {
710 if (region->region.slot == memslot)
714 fprintf(stderr, "No mem region with the requested slot found,\n"
715 " requested slot: %u\n", memslot);
716 fputs("---- vm dump ----\n", stderr);
717 vm_dump(stderr, vm, 2);
718 TEST_FAIL("Mem region not found");
723 * VM Memory Region Flags Set
726 * vm - Virtual Machine
727 * flags - Starting guest physical address
733 * Sets the flags of the memory region specified by the value of slot,
734 * to the values given by flags.
736 void vm_mem_region_set_flags(struct kvm_vm *vm, uint32_t slot, uint32_t flags)
739 struct userspace_mem_region *region;
741 region = memslot2region(vm, slot);
743 region->region.flags = flags;
745 ret = ioctl(vm->fd, KVM_SET_USER_MEMORY_REGION, ®ion->region);
747 TEST_ASSERT(ret == 0, "KVM_SET_USER_MEMORY_REGION IOCTL failed,\n"
748 " rc: %i errno: %i slot: %u flags: 0x%x",
749 ret, errno, slot, flags);
753 * VM Memory Region Move
756 * vm - Virtual Machine
757 * slot - Slot of the memory region to move
758 * new_gpa - Starting guest physical address
764 * Change the gpa of a memory region.
766 void vm_mem_region_move(struct kvm_vm *vm, uint32_t slot, uint64_t new_gpa)
768 struct userspace_mem_region *region;
771 region = memslot2region(vm, slot);
773 region->region.guest_phys_addr = new_gpa;
775 ret = ioctl(vm->fd, KVM_SET_USER_MEMORY_REGION, ®ion->region);
777 TEST_ASSERT(!ret, "KVM_SET_USER_MEMORY_REGION failed\n"
778 "ret: %i errno: %i slot: %u new_gpa: 0x%lx",
779 ret, errno, slot, new_gpa);
783 * VM Memory Region Delete
786 * vm - Virtual Machine
787 * slot - Slot of the memory region to delete
793 * Delete a memory region.
795 void vm_mem_region_delete(struct kvm_vm *vm, uint32_t slot)
797 __vm_mem_region_delete(vm, memslot2region(vm, slot));
810 * Returns the size of the structure pointed to by the return value
813 static int vcpu_mmap_sz(void)
817 dev_fd = open(KVM_DEV_PATH, O_RDONLY);
821 ret = ioctl(dev_fd, KVM_GET_VCPU_MMAP_SIZE, NULL);
822 TEST_ASSERT(ret >= sizeof(struct kvm_run),
823 "%s KVM_GET_VCPU_MMAP_SIZE ioctl failed, rc: %i errno: %i",
824 __func__, ret, errno);
835 * vm - Virtual Machine
842 * Adds a virtual CPU to the VM specified by vm with the ID given by vcpuid.
843 * No additional VCPU setup is done.
845 void vm_vcpu_add(struct kvm_vm *vm, uint32_t vcpuid)
849 /* Confirm a vcpu with the specified id doesn't already exist. */
850 vcpu = vcpu_find(vm, vcpuid);
852 TEST_FAIL("vcpu with the specified id "
854 " requested vcpuid: %u\n"
855 " existing vcpuid: %u state: %p",
856 vcpuid, vcpu->id, vcpu->state);
858 /* Allocate and initialize new vcpu structure. */
859 vcpu = calloc(1, sizeof(*vcpu));
860 TEST_ASSERT(vcpu != NULL, "Insufficient Memory");
862 vcpu->fd = ioctl(vm->fd, KVM_CREATE_VCPU, vcpuid);
863 TEST_ASSERT(vcpu->fd >= 0, "KVM_CREATE_VCPU failed, rc: %i errno: %i",
866 TEST_ASSERT(vcpu_mmap_sz() >= sizeof(*vcpu->state), "vcpu mmap size "
867 "smaller than expected, vcpu_mmap_sz: %i expected_min: %zi",
868 vcpu_mmap_sz(), sizeof(*vcpu->state));
869 vcpu->state = (struct kvm_run *) mmap(NULL, sizeof(*vcpu->state),
870 PROT_READ | PROT_WRITE, MAP_SHARED, vcpu->fd, 0);
871 TEST_ASSERT(vcpu->state != MAP_FAILED, "mmap vcpu_state failed, "
872 "vcpu id: %u errno: %i", vcpuid, errno);
874 /* Add to linked-list of VCPUs. */
875 list_add(&vcpu->list, &vm->vcpus);
879 * VM Virtual Address Unused Gap
882 * vm - Virtual Machine
884 * vaddr_min - Minimum Virtual Address
889 * Lowest virtual address at or below vaddr_min, with at least
890 * sz unused bytes. TEST_ASSERT failure if no area of at least
891 * size sz is available.
893 * Within the VM specified by vm, locates the lowest starting virtual
894 * address >= vaddr_min, that has at least sz unallocated bytes. A
895 * TEST_ASSERT failure occurs for invalid input or no area of at least
896 * sz unallocated bytes >= vaddr_min is available.
898 static vm_vaddr_t vm_vaddr_unused_gap(struct kvm_vm *vm, size_t sz,
899 vm_vaddr_t vaddr_min)
901 uint64_t pages = (sz + vm->page_size - 1) >> vm->page_shift;
903 /* Determine lowest permitted virtual page index. */
904 uint64_t pgidx_start = (vaddr_min + vm->page_size - 1) >> vm->page_shift;
905 if ((pgidx_start * vm->page_size) < vaddr_min)
908 /* Loop over section with enough valid virtual page indexes. */
909 if (!sparsebit_is_set_num(vm->vpages_valid,
911 pgidx_start = sparsebit_next_set_num(vm->vpages_valid,
915 * Are there enough unused virtual pages available at
916 * the currently proposed starting virtual page index.
917 * If not, adjust proposed starting index to next
920 if (sparsebit_is_clear_num(vm->vpages_mapped,
923 pgidx_start = sparsebit_next_clear_num(vm->vpages_mapped,
925 if (pgidx_start == 0)
929 * If needed, adjust proposed starting virtual address,
930 * to next range of valid virtual addresses.
932 if (!sparsebit_is_set_num(vm->vpages_valid,
933 pgidx_start, pages)) {
934 pgidx_start = sparsebit_next_set_num(
935 vm->vpages_valid, pgidx_start, pages);
936 if (pgidx_start == 0)
939 } while (pgidx_start != 0);
942 TEST_FAIL("No vaddr of specified pages available, pages: 0x%lx", pages);
948 TEST_ASSERT(sparsebit_is_set_num(vm->vpages_valid,
950 "Unexpected, invalid virtual page index range,\n"
951 " pgidx_start: 0x%lx\n"
954 TEST_ASSERT(sparsebit_is_clear_num(vm->vpages_mapped,
956 "Unexpected, pages already mapped,\n"
957 " pgidx_start: 0x%lx\n"
961 return pgidx_start * vm->page_size;
965 * VM Virtual Address Allocate
968 * vm - Virtual Machine
970 * vaddr_min - Minimum starting virtual address
971 * data_memslot - Memory region slot for data pages
972 * pgd_memslot - Memory region slot for new virtual translation tables
977 * Starting guest virtual address
979 * Allocates at least sz bytes within the virtual address space of the vm
980 * given by vm. The allocated bytes are mapped to a virtual address >=
981 * the address given by vaddr_min. Note that each allocation uses a
982 * a unique set of pages, with the minimum real allocation being at least
985 vm_vaddr_t vm_vaddr_alloc(struct kvm_vm *vm, size_t sz, vm_vaddr_t vaddr_min,
986 uint32_t data_memslot, uint32_t pgd_memslot)
988 uint64_t pages = (sz >> vm->page_shift) + ((sz % vm->page_size) != 0);
990 virt_pgd_alloc(vm, pgd_memslot);
993 * Find an unused range of virtual page addresses of at least
996 vm_vaddr_t vaddr_start = vm_vaddr_unused_gap(vm, sz, vaddr_min);
998 /* Map the virtual pages. */
999 for (vm_vaddr_t vaddr = vaddr_start; pages > 0;
1000 pages--, vaddr += vm->page_size) {
1003 paddr = vm_phy_page_alloc(vm,
1004 KVM_UTIL_MIN_PFN * vm->page_size, data_memslot);
1006 virt_pg_map(vm, vaddr, paddr, pgd_memslot);
1008 sparsebit_set(vm->vpages_mapped,
1009 vaddr >> vm->page_shift);
1016 * Map a range of VM virtual address to the VM's physical address
1019 * vm - Virtual Machine
1020 * vaddr - Virtuall address to map
1021 * paddr - VM Physical Address
1022 * npages - The number of pages to map
1023 * pgd_memslot - Memory region slot for new virtual translation tables
1029 * Within the VM given by @vm, creates a virtual translation for
1030 * @npages starting at @vaddr to the page range starting at @paddr.
1032 void virt_map(struct kvm_vm *vm, uint64_t vaddr, uint64_t paddr,
1033 unsigned int npages, uint32_t pgd_memslot)
1035 size_t page_size = vm->page_size;
1036 size_t size = npages * page_size;
1038 TEST_ASSERT(vaddr + size > vaddr, "Vaddr overflow");
1039 TEST_ASSERT(paddr + size > paddr, "Paddr overflow");
1042 virt_pg_map(vm, vaddr, paddr, pgd_memslot);
1049 * Address VM Physical to Host Virtual
1052 * vm - Virtual Machine
1053 * gpa - VM physical address
1058 * Equivalent host virtual address
1060 * Locates the memory region containing the VM physical address given
1061 * by gpa, within the VM given by vm. When found, the host virtual
1062 * address providing the memory to the vm physical address is returned.
1063 * A TEST_ASSERT failure occurs if no region containing gpa exists.
1065 void *addr_gpa2hva(struct kvm_vm *vm, vm_paddr_t gpa)
1067 struct userspace_mem_region *region;
1069 list_for_each_entry(region, &vm->userspace_mem_regions, list) {
1070 if ((gpa >= region->region.guest_phys_addr)
1071 && (gpa <= (region->region.guest_phys_addr
1072 + region->region.memory_size - 1)))
1073 return (void *) ((uintptr_t) region->host_mem
1074 + (gpa - region->region.guest_phys_addr));
1077 TEST_FAIL("No vm physical memory at 0x%lx", gpa);
1082 * Address Host Virtual to VM Physical
1085 * vm - Virtual Machine
1086 * hva - Host virtual address
1091 * Equivalent VM physical address
1093 * Locates the memory region containing the host virtual address given
1094 * by hva, within the VM given by vm. When found, the equivalent
1095 * VM physical address is returned. A TEST_ASSERT failure occurs if no
1096 * region containing hva exists.
1098 vm_paddr_t addr_hva2gpa(struct kvm_vm *vm, void *hva)
1100 struct userspace_mem_region *region;
1102 list_for_each_entry(region, &vm->userspace_mem_regions, list) {
1103 if ((hva >= region->host_mem)
1104 && (hva <= (region->host_mem
1105 + region->region.memory_size - 1)))
1106 return (vm_paddr_t) ((uintptr_t)
1107 region->region.guest_phys_addr
1108 + (hva - (uintptr_t) region->host_mem));
1111 TEST_FAIL("No mapping to a guest physical address, hva: %p", hva);
1116 * VM Create IRQ Chip
1119 * vm - Virtual Machine
1125 * Creates an interrupt controller chip for the VM specified by vm.
1127 void vm_create_irqchip(struct kvm_vm *vm)
1131 ret = ioctl(vm->fd, KVM_CREATE_IRQCHIP, 0);
1132 TEST_ASSERT(ret == 0, "KVM_CREATE_IRQCHIP IOCTL failed, "
1133 "rc: %i errno: %i", ret, errno);
1135 vm->has_irqchip = true;
1142 * vm - Virtual Machine
1148 * Pointer to structure that describes the state of the VCPU.
1150 * Locates and returns a pointer to a structure that describes the
1151 * state of the VCPU with the given vcpuid.
1153 struct kvm_run *vcpu_state(struct kvm_vm *vm, uint32_t vcpuid)
1155 struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1156 TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1165 * vm - Virtual Machine
1172 * Switch to executing the code for the VCPU given by vcpuid, within the VM
1175 void vcpu_run(struct kvm_vm *vm, uint32_t vcpuid)
1177 int ret = _vcpu_run(vm, vcpuid);
1178 TEST_ASSERT(ret == 0, "KVM_RUN IOCTL failed, "
1179 "rc: %i errno: %i", ret, errno);
1182 int _vcpu_run(struct kvm_vm *vm, uint32_t vcpuid)
1184 struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1187 TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1189 rc = ioctl(vcpu->fd, KVM_RUN, NULL);
1190 } while (rc == -1 && errno == EINTR);
1194 void vcpu_run_complete_io(struct kvm_vm *vm, uint32_t vcpuid)
1196 struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1199 TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1201 vcpu->state->immediate_exit = 1;
1202 ret = ioctl(vcpu->fd, KVM_RUN, NULL);
1203 vcpu->state->immediate_exit = 0;
1205 TEST_ASSERT(ret == -1 && errno == EINTR,
1206 "KVM_RUN IOCTL didn't exit immediately, rc: %i, errno: %i",
1210 void vcpu_set_guest_debug(struct kvm_vm *vm, uint32_t vcpuid,
1211 struct kvm_guest_debug *debug)
1213 struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1214 int ret = ioctl(vcpu->fd, KVM_SET_GUEST_DEBUG, debug);
1216 TEST_ASSERT(ret == 0, "KVM_SET_GUEST_DEBUG failed: %d", ret);
1220 * VM VCPU Set MP State
1223 * vm - Virtual Machine
1225 * mp_state - mp_state to be set
1231 * Sets the MP state of the VCPU given by vcpuid, to the state given
1234 void vcpu_set_mp_state(struct kvm_vm *vm, uint32_t vcpuid,
1235 struct kvm_mp_state *mp_state)
1237 struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1240 TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1242 ret = ioctl(vcpu->fd, KVM_SET_MP_STATE, mp_state);
1243 TEST_ASSERT(ret == 0, "KVM_SET_MP_STATE IOCTL failed, "
1244 "rc: %i errno: %i", ret, errno);
1251 * vm - Virtual Machine
1255 * regs - current state of VCPU regs
1259 * Obtains the current register state for the VCPU specified by vcpuid
1260 * and stores it at the location given by regs.
1262 void vcpu_regs_get(struct kvm_vm *vm, uint32_t vcpuid, struct kvm_regs *regs)
1264 struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1267 TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1269 ret = ioctl(vcpu->fd, KVM_GET_REGS, regs);
1270 TEST_ASSERT(ret == 0, "KVM_GET_REGS failed, rc: %i errno: %i",
1278 * vm - Virtual Machine
1280 * regs - Values to set VCPU regs to
1286 * Sets the regs of the VCPU specified by vcpuid to the values
1289 void vcpu_regs_set(struct kvm_vm *vm, uint32_t vcpuid, struct kvm_regs *regs)
1291 struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1294 TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1296 ret = ioctl(vcpu->fd, KVM_SET_REGS, regs);
1297 TEST_ASSERT(ret == 0, "KVM_SET_REGS failed, rc: %i errno: %i",
1301 #ifdef __KVM_HAVE_VCPU_EVENTS
1302 void vcpu_events_get(struct kvm_vm *vm, uint32_t vcpuid,
1303 struct kvm_vcpu_events *events)
1305 struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1308 TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1310 ret = ioctl(vcpu->fd, KVM_GET_VCPU_EVENTS, events);
1311 TEST_ASSERT(ret == 0, "KVM_GET_VCPU_EVENTS, failed, rc: %i errno: %i",
1315 void vcpu_events_set(struct kvm_vm *vm, uint32_t vcpuid,
1316 struct kvm_vcpu_events *events)
1318 struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1321 TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1323 ret = ioctl(vcpu->fd, KVM_SET_VCPU_EVENTS, events);
1324 TEST_ASSERT(ret == 0, "KVM_SET_VCPU_EVENTS, failed, rc: %i errno: %i",
1330 void vcpu_nested_state_get(struct kvm_vm *vm, uint32_t vcpuid,
1331 struct kvm_nested_state *state)
1333 struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1336 TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1338 ret = ioctl(vcpu->fd, KVM_GET_NESTED_STATE, state);
1339 TEST_ASSERT(ret == 0,
1340 "KVM_SET_NESTED_STATE failed, ret: %i errno: %i",
1344 int vcpu_nested_state_set(struct kvm_vm *vm, uint32_t vcpuid,
1345 struct kvm_nested_state *state, bool ignore_error)
1347 struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1350 TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1352 ret = ioctl(vcpu->fd, KVM_SET_NESTED_STATE, state);
1353 if (!ignore_error) {
1354 TEST_ASSERT(ret == 0,
1355 "KVM_SET_NESTED_STATE failed, ret: %i errno: %i",
1364 * VM VCPU System Regs Get
1367 * vm - Virtual Machine
1371 * sregs - current state of VCPU system regs
1375 * Obtains the current system register state for the VCPU specified by
1376 * vcpuid and stores it at the location given by sregs.
1378 void vcpu_sregs_get(struct kvm_vm *vm, uint32_t vcpuid, struct kvm_sregs *sregs)
1380 struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1383 TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1385 ret = ioctl(vcpu->fd, KVM_GET_SREGS, sregs);
1386 TEST_ASSERT(ret == 0, "KVM_GET_SREGS failed, rc: %i errno: %i",
1391 * VM VCPU System Regs Set
1394 * vm - Virtual Machine
1396 * sregs - Values to set VCPU system regs to
1402 * Sets the system regs of the VCPU specified by vcpuid to the values
1405 void vcpu_sregs_set(struct kvm_vm *vm, uint32_t vcpuid, struct kvm_sregs *sregs)
1407 int ret = _vcpu_sregs_set(vm, vcpuid, sregs);
1408 TEST_ASSERT(ret == 0, "KVM_RUN IOCTL failed, "
1409 "rc: %i errno: %i", ret, errno);
1412 int _vcpu_sregs_set(struct kvm_vm *vm, uint32_t vcpuid, struct kvm_sregs *sregs)
1414 struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1416 TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1418 return ioctl(vcpu->fd, KVM_SET_SREGS, sregs);
1421 void vcpu_fpu_get(struct kvm_vm *vm, uint32_t vcpuid, struct kvm_fpu *fpu)
1425 ret = _vcpu_ioctl(vm, vcpuid, KVM_GET_FPU, fpu);
1426 TEST_ASSERT(ret == 0, "KVM_GET_FPU failed, rc: %i errno: %i (%s)",
1427 ret, errno, strerror(errno));
1430 void vcpu_fpu_set(struct kvm_vm *vm, uint32_t vcpuid, struct kvm_fpu *fpu)
1434 ret = _vcpu_ioctl(vm, vcpuid, KVM_SET_FPU, fpu);
1435 TEST_ASSERT(ret == 0, "KVM_SET_FPU failed, rc: %i errno: %i (%s)",
1436 ret, errno, strerror(errno));
1439 void vcpu_get_reg(struct kvm_vm *vm, uint32_t vcpuid, struct kvm_one_reg *reg)
1443 ret = _vcpu_ioctl(vm, vcpuid, KVM_GET_ONE_REG, reg);
1444 TEST_ASSERT(ret == 0, "KVM_GET_ONE_REG failed, rc: %i errno: %i (%s)",
1445 ret, errno, strerror(errno));
1448 void vcpu_set_reg(struct kvm_vm *vm, uint32_t vcpuid, struct kvm_one_reg *reg)
1452 ret = _vcpu_ioctl(vm, vcpuid, KVM_SET_ONE_REG, reg);
1453 TEST_ASSERT(ret == 0, "KVM_SET_ONE_REG failed, rc: %i errno: %i (%s)",
1454 ret, errno, strerror(errno));
1461 * vm - Virtual Machine
1463 * cmd - Ioctl number
1464 * arg - Argument to pass to the ioctl
1468 * Issues an arbitrary ioctl on a VCPU fd.
1470 void vcpu_ioctl(struct kvm_vm *vm, uint32_t vcpuid,
1471 unsigned long cmd, void *arg)
1475 ret = _vcpu_ioctl(vm, vcpuid, cmd, arg);
1476 TEST_ASSERT(ret == 0, "vcpu ioctl %lu failed, rc: %i errno: %i (%s)",
1477 cmd, ret, errno, strerror(errno));
1480 int _vcpu_ioctl(struct kvm_vm *vm, uint32_t vcpuid,
1481 unsigned long cmd, void *arg)
1483 struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1486 TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1488 ret = ioctl(vcpu->fd, cmd, arg);
1497 * vm - Virtual Machine
1498 * cmd - Ioctl number
1499 * arg - Argument to pass to the ioctl
1503 * Issues an arbitrary ioctl on a VM fd.
1505 void vm_ioctl(struct kvm_vm *vm, unsigned long cmd, void *arg)
1509 ret = ioctl(vm->fd, cmd, arg);
1510 TEST_ASSERT(ret == 0, "vm ioctl %lu failed, rc: %i errno: %i (%s)",
1511 cmd, ret, errno, strerror(errno));
1518 * vm - Virtual Machine
1519 * indent - Left margin indent amount
1522 * stream - Output FILE stream
1526 * Dumps the current state of the VM given by vm, to the FILE stream
1529 void vm_dump(FILE *stream, struct kvm_vm *vm, uint8_t indent)
1531 struct userspace_mem_region *region;
1534 fprintf(stream, "%*smode: 0x%x\n", indent, "", vm->mode);
1535 fprintf(stream, "%*sfd: %i\n", indent, "", vm->fd);
1536 fprintf(stream, "%*spage_size: 0x%x\n", indent, "", vm->page_size);
1537 fprintf(stream, "%*sMem Regions:\n", indent, "");
1538 list_for_each_entry(region, &vm->userspace_mem_regions, list) {
1539 fprintf(stream, "%*sguest_phys: 0x%lx size: 0x%lx "
1540 "host_virt: %p\n", indent + 2, "",
1541 (uint64_t) region->region.guest_phys_addr,
1542 (uint64_t) region->region.memory_size,
1544 fprintf(stream, "%*sunused_phy_pages: ", indent + 2, "");
1545 sparsebit_dump(stream, region->unused_phy_pages, 0);
1547 fprintf(stream, "%*sMapped Virtual Pages:\n", indent, "");
1548 sparsebit_dump(stream, vm->vpages_mapped, indent + 2);
1549 fprintf(stream, "%*spgd_created: %u\n", indent, "",
1551 if (vm->pgd_created) {
1552 fprintf(stream, "%*sVirtual Translation Tables:\n",
1554 virt_dump(stream, vm, indent + 4);
1556 fprintf(stream, "%*sVCPUs:\n", indent, "");
1557 list_for_each_entry(vcpu, &vm->vcpus, list)
1558 vcpu_dump(stream, vm, vcpu->id, indent + 2);
1561 /* Known KVM exit reasons */
1562 static struct exit_reason {
1563 unsigned int reason;
1565 } exit_reasons_known[] = {
1566 {KVM_EXIT_UNKNOWN, "UNKNOWN"},
1567 {KVM_EXIT_EXCEPTION, "EXCEPTION"},
1568 {KVM_EXIT_IO, "IO"},
1569 {KVM_EXIT_HYPERCALL, "HYPERCALL"},
1570 {KVM_EXIT_DEBUG, "DEBUG"},
1571 {KVM_EXIT_HLT, "HLT"},
1572 {KVM_EXIT_MMIO, "MMIO"},
1573 {KVM_EXIT_IRQ_WINDOW_OPEN, "IRQ_WINDOW_OPEN"},
1574 {KVM_EXIT_SHUTDOWN, "SHUTDOWN"},
1575 {KVM_EXIT_FAIL_ENTRY, "FAIL_ENTRY"},
1576 {KVM_EXIT_INTR, "INTR"},
1577 {KVM_EXIT_SET_TPR, "SET_TPR"},
1578 {KVM_EXIT_TPR_ACCESS, "TPR_ACCESS"},
1579 {KVM_EXIT_S390_SIEIC, "S390_SIEIC"},
1580 {KVM_EXIT_S390_RESET, "S390_RESET"},
1581 {KVM_EXIT_DCR, "DCR"},
1582 {KVM_EXIT_NMI, "NMI"},
1583 {KVM_EXIT_INTERNAL_ERROR, "INTERNAL_ERROR"},
1584 {KVM_EXIT_OSI, "OSI"},
1585 {KVM_EXIT_PAPR_HCALL, "PAPR_HCALL"},
1586 #ifdef KVM_EXIT_MEMORY_NOT_PRESENT
1587 {KVM_EXIT_MEMORY_NOT_PRESENT, "MEMORY_NOT_PRESENT"},
1592 * Exit Reason String
1595 * exit_reason - Exit reason
1600 * Constant string pointer describing the exit reason.
1602 * Locates and returns a constant string that describes the KVM exit
1603 * reason given by exit_reason. If no such string is found, a constant
1604 * string of "Unknown" is returned.
1606 const char *exit_reason_str(unsigned int exit_reason)
1610 for (n1 = 0; n1 < ARRAY_SIZE(exit_reasons_known); n1++) {
1611 if (exit_reason == exit_reasons_known[n1].reason)
1612 return exit_reasons_known[n1].name;
1619 * Physical Contiguous Page Allocator
1622 * vm - Virtual Machine
1623 * num - number of pages
1624 * paddr_min - Physical address minimum
1625 * memslot - Memory region to allocate page from
1630 * Starting physical address
1632 * Within the VM specified by vm, locates a range of available physical
1633 * pages at or above paddr_min. If found, the pages are marked as in use
1634 * and their base address is returned. A TEST_ASSERT failure occurs if
1635 * not enough pages are available at or above paddr_min.
1637 vm_paddr_t vm_phy_pages_alloc(struct kvm_vm *vm, size_t num,
1638 vm_paddr_t paddr_min, uint32_t memslot)
1640 struct userspace_mem_region *region;
1641 sparsebit_idx_t pg, base;
1643 TEST_ASSERT(num > 0, "Must allocate at least one page");
1645 TEST_ASSERT((paddr_min % vm->page_size) == 0, "Min physical address "
1646 "not divisible by page size.\n"
1647 " paddr_min: 0x%lx page_size: 0x%x",
1648 paddr_min, vm->page_size);
1650 region = memslot2region(vm, memslot);
1651 base = pg = paddr_min >> vm->page_shift;
1654 for (; pg < base + num; ++pg) {
1655 if (!sparsebit_is_set(region->unused_phy_pages, pg)) {
1656 base = pg = sparsebit_next_set(region->unused_phy_pages, pg);
1660 } while (pg && pg != base + num);
1663 fprintf(stderr, "No guest physical page available, "
1664 "paddr_min: 0x%lx page_size: 0x%x memslot: %u\n",
1665 paddr_min, vm->page_size, memslot);
1666 fputs("---- vm dump ----\n", stderr);
1667 vm_dump(stderr, vm, 2);
1671 for (pg = base; pg < base + num; ++pg)
1672 sparsebit_clear(region->unused_phy_pages, pg);
1674 return base * vm->page_size;
1677 vm_paddr_t vm_phy_page_alloc(struct kvm_vm *vm, vm_paddr_t paddr_min,
1680 return vm_phy_pages_alloc(vm, 1, paddr_min, memslot);
1684 * Address Guest Virtual to Host Virtual
1687 * vm - Virtual Machine
1688 * gva - VM virtual address
1693 * Equivalent host virtual address
1695 void *addr_gva2hva(struct kvm_vm *vm, vm_vaddr_t gva)
1697 return addr_gpa2hva(vm, addr_gva2gpa(vm, gva));
1701 * Is Unrestricted Guest
1704 * vm - Virtual Machine
1708 * Return: True if the unrestricted guest is set to 'Y', otherwise return false.
1710 * Check if the unrestricted guest flag is enabled.
1712 bool vm_is_unrestricted_guest(struct kvm_vm *vm)
1719 /* Ensure that the KVM vendor-specific module is loaded. */
1720 f = fopen(KVM_DEV_PATH, "r");
1721 TEST_ASSERT(f != NULL, "Error in opening KVM dev file: %d",
1726 f = fopen("/sys/module/kvm_intel/parameters/unrestricted_guest", "r");
1728 count = fread(&val, sizeof(char), 1, f);
1729 TEST_ASSERT(count == 1, "Unable to read from param file.");
1736 unsigned int vm_get_page_size(struct kvm_vm *vm)
1738 return vm->page_size;
1741 unsigned int vm_get_page_shift(struct kvm_vm *vm)
1743 return vm->page_shift;
1746 unsigned int vm_get_max_gfn(struct kvm_vm *vm)
1751 int vm_get_fd(struct kvm_vm *vm)
1756 static unsigned int vm_calc_num_pages(unsigned int num_pages,
1757 unsigned int page_shift,
1758 unsigned int new_page_shift,
1761 unsigned int n = 1 << (new_page_shift - page_shift);
1763 if (page_shift >= new_page_shift)
1764 return num_pages * (1 << (page_shift - new_page_shift));
1766 return num_pages / n + !!(ceil && num_pages % n);
1769 static inline int getpageshift(void)
1771 return __builtin_ffs(getpagesize()) - 1;
1775 vm_num_host_pages(enum vm_guest_mode mode, unsigned int num_guest_pages)
1777 return vm_calc_num_pages(num_guest_pages,
1778 vm_guest_mode_params[mode].page_shift,
1779 getpageshift(), true);
1783 vm_num_guest_pages(enum vm_guest_mode mode, unsigned int num_host_pages)
1785 return vm_calc_num_pages(num_host_pages, getpageshift(),
1786 vm_guest_mode_params[mode].page_shift, false);
1789 unsigned int vm_calc_num_guest_pages(enum vm_guest_mode mode, size_t size)
1792 n = DIV_ROUND_UP(size, vm_guest_mode_params[mode].page_size);
1793 return vm_adjust_num_guest_pages(mode, n);