2 * tools/testing/selftests/kvm/lib/kvm_util.c
4 * Copyright (C) 2018, Google LLC.
6 * This work is licensed under the terms of the GNU GPL, version 2.
11 #include "kvm_util_internal.h"
15 #include <sys/types.h>
18 #define KVM_DEV_PATH "/dev/kvm"
20 #define KVM_UTIL_PGS_PER_HUGEPG 512
21 #define KVM_UTIL_MIN_PADDR 0x2000
23 /* Aligns x up to the next multiple of size. Size must be a power of 2. */
24 static void *align(void *x, size_t size)
26 size_t mask = size - 1;
27 TEST_ASSERT(size != 0 && !(size & (size - 1)),
28 "size not a power of 2: %lu", size);
29 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);
68 * mode - VM Mode (e.g. VM_MODE_FLAT48PG)
69 * phy_pages - Physical memory pages
75 * Pointer to opaque structure that describes the created VM.
77 * Creates a VM with the mode specified by mode (e.g. VM_MODE_FLAT48PG).
78 * When phy_pages is non-zero, a memory region of phy_pages physical pages
79 * is created and mapped starting at guest physical address 0. The file
80 * descriptor to control the created VM is created with the permissions
81 * given by perm (e.g. O_RDWR).
83 struct kvm_vm *vm_create(enum vm_guest_mode mode, uint64_t phy_pages, int perm)
88 /* Allocate memory. */
89 vm = calloc(1, sizeof(*vm));
90 TEST_ASSERT(vm != NULL, "Insufficent Memory");
93 kvm_fd = open(KVM_DEV_PATH, perm);
98 vm->fd = ioctl(kvm_fd, KVM_CREATE_VM, NULL);
99 TEST_ASSERT(vm->fd >= 0, "KVM_CREATE_VM ioctl failed, "
100 "rc: %i errno: %i", vm->fd, errno);
104 /* Setup mode specific traits. */
106 case VM_MODE_FLAT48PG:
107 vm->page_size = 0x1000;
110 /* Limit to 48-bit canonical virtual addresses. */
111 vm->vpages_valid = sparsebit_alloc();
112 sparsebit_set_num(vm->vpages_valid,
113 0, (1ULL << (48 - 1)) >> vm->page_shift);
114 sparsebit_set_num(vm->vpages_valid,
115 (~((1ULL << (48 - 1)) - 1)) >> vm->page_shift,
116 (1ULL << (48 - 1)) >> vm->page_shift);
118 /* Limit physical addresses to 52-bits. */
119 vm->max_gfn = ((1ULL << 52) >> vm->page_shift) - 1;
123 TEST_ASSERT(false, "Unknown guest mode, mode: 0x%x", mode);
126 /* Allocate and setup memory for guest. */
127 vm->vpages_mapped = sparsebit_alloc();
129 vm_userspace_mem_region_add(vm, VM_MEM_SRC_ANONYMOUS,
135 /* Userspace Memory Region Find
138 * vm - Virtual Machine
139 * start - Starting VM physical address
140 * end - Ending VM physical address, inclusive.
145 * Pointer to overlapping region, NULL if no such region.
147 * Searches for a region with any physical memory that overlaps with
148 * any portion of the guest physical addresses from start to end
149 * inclusive. If multiple overlapping regions exist, a pointer to any
150 * of the regions is returned. Null is returned only when no overlapping
153 static struct userspace_mem_region *userspace_mem_region_find(
154 struct kvm_vm *vm, uint64_t start, uint64_t end)
156 struct userspace_mem_region *region;
158 for (region = vm->userspace_mem_region_head; region;
159 region = region->next) {
160 uint64_t existing_start = region->region.guest_phys_addr;
161 uint64_t existing_end = region->region.guest_phys_addr
162 + region->region.memory_size - 1;
163 if (start <= existing_end && end >= existing_start)
170 /* KVM Userspace Memory Region Find
173 * vm - Virtual Machine
174 * start - Starting VM physical address
175 * end - Ending VM physical address, inclusive.
180 * Pointer to overlapping region, NULL if no such region.
182 * Public interface to userspace_mem_region_find. Allows tests to look up
183 * the memslot datastructure for a given range of guest physical memory.
185 struct kvm_userspace_memory_region *
186 kvm_userspace_memory_region_find(struct kvm_vm *vm, uint64_t start,
189 struct userspace_mem_region *region;
191 region = userspace_mem_region_find(vm, start, end);
195 return ®ion->region;
201 * vm - Virtual Machine
207 * Pointer to VCPU structure
209 * Locates a vcpu structure that describes the VCPU specified by vcpuid and
210 * returns a pointer to it. Returns NULL if the VM doesn't contain a VCPU
211 * for the specified vcpuid.
213 struct vcpu *vcpu_find(struct kvm_vm *vm,
218 for (vcpup = vm->vcpu_head; vcpup; vcpup = vcpup->next) {
219 if (vcpup->id == vcpuid)
229 * vm - Virtual Machine
234 * Return: None, TEST_ASSERT failures for all error conditions
236 * Within the VM specified by vm, removes the VCPU given by vcpuid.
238 static void vm_vcpu_rm(struct kvm_vm *vm, uint32_t vcpuid)
240 struct vcpu *vcpu = vcpu_find(vm, vcpuid);
242 int ret = close(vcpu->fd);
243 TEST_ASSERT(ret == 0, "Close of VCPU fd failed, rc: %i "
244 "errno: %i", ret, errno);
247 vcpu->next->prev = vcpu->prev;
249 vcpu->prev->next = vcpu->next;
251 vm->vcpu_head = vcpu->next;
256 /* Destroys and frees the VM pointed to by vmp.
258 void kvm_vm_free(struct kvm_vm *vmp)
265 /* Free userspace_mem_regions. */
266 while (vmp->userspace_mem_region_head) {
267 struct userspace_mem_region *region
268 = vmp->userspace_mem_region_head;
270 region->region.memory_size = 0;
271 ret = ioctl(vmp->fd, KVM_SET_USER_MEMORY_REGION,
273 TEST_ASSERT(ret == 0, "KVM_SET_USER_MEMORY_REGION IOCTL failed, "
274 "rc: %i errno: %i", ret, errno);
276 vmp->userspace_mem_region_head = region->next;
277 sparsebit_free(®ion->unused_phy_pages);
278 ret = munmap(region->mmap_start, region->mmap_size);
279 TEST_ASSERT(ret == 0, "munmap failed, rc: %i errno: %i",
286 while (vmp->vcpu_head)
287 vm_vcpu_rm(vmp, vmp->vcpu_head->id);
289 /* Free sparsebit arrays. */
290 sparsebit_free(&vmp->vpages_valid);
291 sparsebit_free(&vmp->vpages_mapped);
293 /* Close file descriptor for the VM. */
294 ret = close(vmp->fd);
295 TEST_ASSERT(ret == 0, "Close of vm fd failed,\n"
296 " vmp->fd: %i rc: %i errno: %i", vmp->fd, ret, errno);
298 /* Free the structure describing the VM. */
302 /* Memory Compare, host virtual to guest virtual
305 * hva - Starting host virtual address
306 * vm - Virtual Machine
307 * gva - Starting guest virtual address
308 * len - number of bytes to compare
312 * Input/Output Args: None
315 * Returns 0 if the bytes starting at hva for a length of len
316 * are equal the guest virtual bytes starting at gva. Returns
317 * a value < 0, if bytes at hva are less than those at gva.
318 * Otherwise a value > 0 is returned.
320 * Compares the bytes starting at the host virtual address hva, for
321 * a length of len, to the guest bytes starting at the guest virtual
322 * address given by gva.
324 int kvm_memcmp_hva_gva(void *hva,
325 struct kvm_vm *vm, vm_vaddr_t gva, size_t len)
329 /* Compare a batch of bytes until either a match is found
330 * or all the bytes have been compared.
332 for (uintptr_t offset = 0; offset < len; offset += amt) {
333 uintptr_t ptr1 = (uintptr_t)hva + offset;
335 /* Determine host address for guest virtual address
338 uintptr_t ptr2 = (uintptr_t)addr_gva2hva(vm, gva + offset);
340 /* Determine amount to compare on this pass.
341 * Don't allow the comparsion to cross a page boundary.
344 if ((ptr1 >> vm->page_shift) != ((ptr1 + amt) >> vm->page_shift))
345 amt = vm->page_size - (ptr1 % vm->page_size);
346 if ((ptr2 >> vm->page_shift) != ((ptr2 + amt) >> vm->page_shift))
347 amt = vm->page_size - (ptr2 % vm->page_size);
349 assert((ptr1 >> vm->page_shift) == ((ptr1 + amt - 1) >> vm->page_shift));
350 assert((ptr2 >> vm->page_shift) == ((ptr2 + amt - 1) >> vm->page_shift));
352 /* Perform the comparison. If there is a difference
353 * return that result to the caller, otherwise need
354 * to continue on looking for a mismatch.
356 int ret = memcmp((void *)ptr1, (void *)ptr2, amt);
361 /* No mismatch found. Let the caller know the two memory
367 /* Allocate an instance of struct kvm_cpuid2
373 * Return: A pointer to the allocated struct. The caller is responsible
374 * for freeing this struct.
376 * Since kvm_cpuid2 uses a 0-length array to allow a the size of the
377 * array to be decided at allocation time, allocation is slightly
378 * complicated. This function uses a reasonable default length for
379 * the array and performs the appropriate allocation.
381 static struct kvm_cpuid2 *allocate_kvm_cpuid2(void)
383 struct kvm_cpuid2 *cpuid;
387 size = sizeof(*cpuid);
388 size += nent * sizeof(struct kvm_cpuid_entry2);
389 cpuid = malloc(size);
400 /* KVM Supported CPUID Get
406 * Return: The supported KVM CPUID
408 * Get the guest CPUID supported by KVM.
410 struct kvm_cpuid2 *kvm_get_supported_cpuid(void)
412 static struct kvm_cpuid2 *cpuid;
419 cpuid = allocate_kvm_cpuid2();
420 kvm_fd = open(KVM_DEV_PATH, O_RDONLY);
424 ret = ioctl(kvm_fd, KVM_GET_SUPPORTED_CPUID, cpuid);
425 TEST_ASSERT(ret == 0, "KVM_GET_SUPPORTED_CPUID failed %d %d\n",
432 /* Locate a cpuid entry.
436 * function: The function of the cpuid entry to find.
440 * Return: A pointer to the cpuid entry. Never returns NULL.
442 struct kvm_cpuid_entry2 *
443 kvm_get_supported_cpuid_index(uint32_t function, uint32_t index)
445 struct kvm_cpuid2 *cpuid;
446 struct kvm_cpuid_entry2 *entry = NULL;
449 cpuid = kvm_get_supported_cpuid();
450 for (i = 0; i < cpuid->nent; i++) {
451 if (cpuid->entries[i].function == function &&
452 cpuid->entries[i].index == index) {
453 entry = &cpuid->entries[i];
458 TEST_ASSERT(entry, "Guest CPUID entry not found: (EAX=%x, ECX=%x).",
463 /* VM Userspace Memory Region Add
466 * vm - Virtual Machine
467 * backing_src - Storage source for this region.
468 * NULL to use anonymous memory.
469 * guest_paddr - Starting guest physical address
470 * slot - KVM region slot
471 * npages - Number of physical pages
472 * flags - KVM memory region flags (e.g. KVM_MEM_LOG_DIRTY_PAGES)
478 * Allocates a memory area of the number of pages specified by npages
479 * and maps it to the VM specified by vm, at a starting physical address
480 * given by guest_paddr. The region is created with a KVM region slot
481 * given by slot, which must be unique and < KVM_MEM_SLOTS_NUM. The
482 * region is created with the flags given by flags.
484 void vm_userspace_mem_region_add(struct kvm_vm *vm,
485 enum vm_mem_backing_src_type src_type,
486 uint64_t guest_paddr, uint32_t slot, uint64_t npages,
490 unsigned long pmem_size = 0;
491 struct userspace_mem_region *region;
492 size_t huge_page_size = KVM_UTIL_PGS_PER_HUGEPG * vm->page_size;
494 TEST_ASSERT((guest_paddr % vm->page_size) == 0, "Guest physical "
495 "address not on a page boundary.\n"
496 " guest_paddr: 0x%lx vm->page_size: 0x%x",
497 guest_paddr, vm->page_size);
498 TEST_ASSERT((((guest_paddr >> vm->page_shift) + npages) - 1)
499 <= vm->max_gfn, "Physical range beyond maximum "
500 "supported physical address,\n"
501 " guest_paddr: 0x%lx npages: 0x%lx\n"
502 " vm->max_gfn: 0x%lx vm->page_size: 0x%x",
503 guest_paddr, npages, vm->max_gfn, vm->page_size);
505 /* Confirm a mem region with an overlapping address doesn't
508 region = (struct userspace_mem_region *) userspace_mem_region_find(
509 vm, guest_paddr, guest_paddr + npages * vm->page_size);
511 TEST_ASSERT(false, "overlapping userspace_mem_region already "
513 " requested guest_paddr: 0x%lx npages: 0x%lx "
515 " existing guest_paddr: 0x%lx size: 0x%lx",
516 guest_paddr, npages, vm->page_size,
517 (uint64_t) region->region.guest_phys_addr,
518 (uint64_t) region->region.memory_size);
520 /* Confirm no region with the requested slot already exists. */
521 for (region = vm->userspace_mem_region_head; region;
522 region = region->next) {
523 if (region->region.slot == slot)
525 if ((guest_paddr <= (region->region.guest_phys_addr
526 + region->region.memory_size))
527 && ((guest_paddr + npages * vm->page_size)
528 >= region->region.guest_phys_addr))
532 TEST_ASSERT(false, "A mem region with the requested slot "
533 "or overlapping physical memory range already exists.\n"
534 " requested slot: %u paddr: 0x%lx npages: 0x%lx\n"
535 " existing slot: %u paddr: 0x%lx size: 0x%lx",
536 slot, guest_paddr, npages,
538 (uint64_t) region->region.guest_phys_addr,
539 (uint64_t) region->region.memory_size);
541 /* Allocate and initialize new mem region structure. */
542 region = calloc(1, sizeof(*region));
543 TEST_ASSERT(region != NULL, "Insufficient Memory");
544 region->mmap_size = npages * vm->page_size;
546 /* Enough memory to align up to a huge page. */
547 if (src_type == VM_MEM_SRC_ANONYMOUS_THP)
548 region->mmap_size += huge_page_size;
549 region->mmap_start = mmap(NULL, region->mmap_size,
550 PROT_READ | PROT_WRITE,
551 MAP_PRIVATE | MAP_ANONYMOUS
552 | (src_type == VM_MEM_SRC_ANONYMOUS_HUGETLB ? MAP_HUGETLB : 0),
554 TEST_ASSERT(region->mmap_start != MAP_FAILED,
555 "test_malloc failed, mmap_start: %p errno: %i",
556 region->mmap_start, errno);
558 /* Align THP allocation up to start of a huge page. */
559 region->host_mem = align(region->mmap_start,
560 src_type == VM_MEM_SRC_ANONYMOUS_THP ? huge_page_size : 1);
562 /* As needed perform madvise */
563 if (src_type == VM_MEM_SRC_ANONYMOUS || src_type == VM_MEM_SRC_ANONYMOUS_THP) {
564 ret = madvise(region->host_mem, npages * vm->page_size,
565 src_type == VM_MEM_SRC_ANONYMOUS ? MADV_NOHUGEPAGE : MADV_HUGEPAGE);
566 TEST_ASSERT(ret == 0, "madvise failed,\n"
570 region->host_mem, npages * vm->page_size, src_type);
573 region->unused_phy_pages = sparsebit_alloc();
574 sparsebit_set_num(region->unused_phy_pages,
575 guest_paddr >> vm->page_shift, npages);
576 region->region.slot = slot;
577 region->region.flags = flags;
578 region->region.guest_phys_addr = guest_paddr;
579 region->region.memory_size = npages * vm->page_size;
580 region->region.userspace_addr = (uintptr_t) region->host_mem;
581 ret = ioctl(vm->fd, KVM_SET_USER_MEMORY_REGION, ®ion->region);
582 TEST_ASSERT(ret == 0, "KVM_SET_USER_MEMORY_REGION IOCTL failed,\n"
583 " rc: %i errno: %i\n"
584 " slot: %u flags: 0x%x\n"
585 " guest_phys_addr: 0x%lx size: 0x%lx",
586 ret, errno, slot, flags,
587 guest_paddr, (uint64_t) region->region.memory_size);
589 /* Add to linked-list of memory regions. */
590 if (vm->userspace_mem_region_head)
591 vm->userspace_mem_region_head->prev = region;
592 region->next = vm->userspace_mem_region_head;
593 vm->userspace_mem_region_head = region;
599 * vm - Virtual Machine
600 * memslot - KVM memory slot ID
605 * Pointer to memory region structure that describe memory region
606 * using kvm memory slot ID given by memslot. TEST_ASSERT failure
607 * on error (e.g. currently no memory region using memslot as a KVM
610 static struct userspace_mem_region *memslot2region(struct kvm_vm *vm,
613 struct userspace_mem_region *region;
615 for (region = vm->userspace_mem_region_head; region;
616 region = region->next) {
617 if (region->region.slot == memslot)
620 if (region == NULL) {
621 fprintf(stderr, "No mem region with the requested slot found,\n"
622 " requested slot: %u\n", memslot);
623 fputs("---- vm dump ----\n", stderr);
624 vm_dump(stderr, vm, 2);
625 TEST_ASSERT(false, "Mem region not found");
631 /* VM Memory Region Flags Set
634 * vm - Virtual Machine
635 * flags - Starting guest physical address
641 * Sets the flags of the memory region specified by the value of slot,
642 * to the values given by flags.
644 void vm_mem_region_set_flags(struct kvm_vm *vm, uint32_t slot, uint32_t flags)
647 struct userspace_mem_region *region;
649 /* Locate memory region. */
650 region = memslot2region(vm, slot);
652 region->region.flags = flags;
654 ret = ioctl(vm->fd, KVM_SET_USER_MEMORY_REGION, ®ion->region);
656 TEST_ASSERT(ret == 0, "KVM_SET_USER_MEMORY_REGION IOCTL failed,\n"
657 " rc: %i errno: %i slot: %u flags: 0x%x",
658 ret, errno, slot, flags);
670 * Returns the size of the structure pointed to by the return value
673 static int vcpu_mmap_sz(void)
677 dev_fd = open(KVM_DEV_PATH, O_RDONLY);
681 ret = ioctl(dev_fd, KVM_GET_VCPU_MMAP_SIZE, NULL);
682 TEST_ASSERT(ret >= sizeof(struct kvm_run),
683 "%s KVM_GET_VCPU_MMAP_SIZE ioctl failed, rc: %i errno: %i",
684 __func__, ret, errno);
694 * vm - Virtual Machine
701 * Creates and adds to the VM specified by vm and virtual CPU with
702 * the ID given by vcpuid.
704 void vm_vcpu_add(struct kvm_vm *vm, uint32_t vcpuid)
708 /* Confirm a vcpu with the specified id doesn't already exist. */
709 vcpu = vcpu_find(vm, vcpuid);
711 TEST_ASSERT(false, "vcpu with the specified id "
713 " requested vcpuid: %u\n"
714 " existing vcpuid: %u state: %p",
715 vcpuid, vcpu->id, vcpu->state);
717 /* Allocate and initialize new vcpu structure. */
718 vcpu = calloc(1, sizeof(*vcpu));
719 TEST_ASSERT(vcpu != NULL, "Insufficient Memory");
721 vcpu->fd = ioctl(vm->fd, KVM_CREATE_VCPU, vcpuid);
722 TEST_ASSERT(vcpu->fd >= 0, "KVM_CREATE_VCPU failed, rc: %i errno: %i",
725 TEST_ASSERT(vcpu_mmap_sz() >= sizeof(*vcpu->state), "vcpu mmap size "
726 "smaller than expected, vcpu_mmap_sz: %i expected_min: %zi",
727 vcpu_mmap_sz(), sizeof(*vcpu->state));
728 vcpu->state = (struct kvm_run *) mmap(NULL, sizeof(*vcpu->state),
729 PROT_READ | PROT_WRITE, MAP_SHARED, vcpu->fd, 0);
730 TEST_ASSERT(vcpu->state != MAP_FAILED, "mmap vcpu_state failed, "
731 "vcpu id: %u errno: %i", vcpuid, errno);
733 /* Add to linked-list of VCPUs. */
735 vm->vcpu_head->prev = vcpu;
736 vcpu->next = vm->vcpu_head;
737 vm->vcpu_head = vcpu;
739 vcpu_setup(vm, vcpuid);
742 /* VM Virtual Address Unused Gap
745 * vm - Virtual Machine
747 * vaddr_min - Minimum Virtual Address
752 * Lowest virtual address at or below vaddr_min, with at least
753 * sz unused bytes. TEST_ASSERT failure if no area of at least
754 * size sz is available.
756 * Within the VM specified by vm, locates the lowest starting virtual
757 * address >= vaddr_min, that has at least sz unallocated bytes. A
758 * TEST_ASSERT failure occurs for invalid input or no area of at least
759 * sz unallocated bytes >= vaddr_min is available.
761 static vm_vaddr_t vm_vaddr_unused_gap(struct kvm_vm *vm, size_t sz,
762 vm_vaddr_t vaddr_min)
764 uint64_t pages = (sz + vm->page_size - 1) >> vm->page_shift;
766 /* Determine lowest permitted virtual page index. */
767 uint64_t pgidx_start = (vaddr_min + vm->page_size - 1) >> vm->page_shift;
768 if ((pgidx_start * vm->page_size) < vaddr_min)
771 /* Loop over section with enough valid virtual page indexes. */
772 if (!sparsebit_is_set_num(vm->vpages_valid,
774 pgidx_start = sparsebit_next_set_num(vm->vpages_valid,
778 * Are there enough unused virtual pages available at
779 * the currently proposed starting virtual page index.
780 * If not, adjust proposed starting index to next
783 if (sparsebit_is_clear_num(vm->vpages_mapped,
786 pgidx_start = sparsebit_next_clear_num(vm->vpages_mapped,
788 if (pgidx_start == 0)
792 * If needed, adjust proposed starting virtual address,
793 * to next range of valid virtual addresses.
795 if (!sparsebit_is_set_num(vm->vpages_valid,
796 pgidx_start, pages)) {
797 pgidx_start = sparsebit_next_set_num(
798 vm->vpages_valid, pgidx_start, pages);
799 if (pgidx_start == 0)
802 } while (pgidx_start != 0);
805 TEST_ASSERT(false, "No vaddr of specified pages available, "
806 "pages: 0x%lx", pages);
812 TEST_ASSERT(sparsebit_is_set_num(vm->vpages_valid,
814 "Unexpected, invalid virtual page index range,\n"
815 " pgidx_start: 0x%lx\n"
818 TEST_ASSERT(sparsebit_is_clear_num(vm->vpages_mapped,
820 "Unexpected, pages already mapped,\n"
821 " pgidx_start: 0x%lx\n"
825 return pgidx_start * vm->page_size;
828 /* VM Virtual Address Allocate
831 * vm - Virtual Machine
833 * vaddr_min - Minimum starting virtual address
834 * data_memslot - Memory region slot for data pages
835 * pgd_memslot - Memory region slot for new virtual translation tables
840 * Starting guest virtual address
842 * Allocates at least sz bytes within the virtual address space of the vm
843 * given by vm. The allocated bytes are mapped to a virtual address >=
844 * the address given by vaddr_min. Note that each allocation uses a
845 * a unique set of pages, with the minimum real allocation being at least
848 vm_vaddr_t vm_vaddr_alloc(struct kvm_vm *vm, size_t sz, vm_vaddr_t vaddr_min,
849 uint32_t data_memslot, uint32_t pgd_memslot)
851 uint64_t pages = (sz >> vm->page_shift) + ((sz % vm->page_size) != 0);
853 virt_pgd_alloc(vm, pgd_memslot);
855 /* Find an unused range of virtual page addresses of at least
858 vm_vaddr_t vaddr_start = vm_vaddr_unused_gap(vm, sz, vaddr_min);
860 /* Map the virtual pages. */
861 for (vm_vaddr_t vaddr = vaddr_start; pages > 0;
862 pages--, vaddr += vm->page_size) {
865 paddr = vm_phy_page_alloc(vm, KVM_UTIL_MIN_PADDR, data_memslot);
867 virt_pg_map(vm, vaddr, paddr, pgd_memslot);
869 sparsebit_set(vm->vpages_mapped,
870 vaddr >> vm->page_shift);
876 /* Address VM Physical to Host Virtual
879 * vm - Virtual Machine
880 * gpa - VM physical address
885 * Equivalent host virtual address
887 * Locates the memory region containing the VM physical address given
888 * by gpa, within the VM given by vm. When found, the host virtual
889 * address providing the memory to the vm physical address is returned.
890 * A TEST_ASSERT failure occurs if no region containing gpa exists.
892 void *addr_gpa2hva(struct kvm_vm *vm, vm_paddr_t gpa)
894 struct userspace_mem_region *region;
895 for (region = vm->userspace_mem_region_head; region;
896 region = region->next) {
897 if ((gpa >= region->region.guest_phys_addr)
898 && (gpa <= (region->region.guest_phys_addr
899 + region->region.memory_size - 1)))
900 return (void *) ((uintptr_t) region->host_mem
901 + (gpa - region->region.guest_phys_addr));
904 TEST_ASSERT(false, "No vm physical memory at 0x%lx", gpa);
908 /* Address Host Virtual to VM Physical
911 * vm - Virtual Machine
912 * hva - Host virtual address
917 * Equivalent VM physical address
919 * Locates the memory region containing the host virtual address given
920 * by hva, within the VM given by vm. When found, the equivalent
921 * VM physical address is returned. A TEST_ASSERT failure occurs if no
922 * region containing hva exists.
924 vm_paddr_t addr_hva2gpa(struct kvm_vm *vm, void *hva)
926 struct userspace_mem_region *region;
927 for (region = vm->userspace_mem_region_head; region;
928 region = region->next) {
929 if ((hva >= region->host_mem)
930 && (hva <= (region->host_mem
931 + region->region.memory_size - 1)))
932 return (vm_paddr_t) ((uintptr_t)
933 region->region.guest_phys_addr
934 + (hva - (uintptr_t) region->host_mem));
937 TEST_ASSERT(false, "No mapping to a guest physical address, "
942 /* VM Create IRQ Chip
945 * vm - Virtual Machine
951 * Creates an interrupt controller chip for the VM specified by vm.
953 void vm_create_irqchip(struct kvm_vm *vm)
957 ret = ioctl(vm->fd, KVM_CREATE_IRQCHIP, 0);
958 TEST_ASSERT(ret == 0, "KVM_CREATE_IRQCHIP IOCTL failed, "
959 "rc: %i errno: %i", ret, errno);
965 * vm - Virtual Machine
971 * Pointer to structure that describes the state of the VCPU.
973 * Locates and returns a pointer to a structure that describes the
974 * state of the VCPU with the given vcpuid.
976 struct kvm_run *vcpu_state(struct kvm_vm *vm, uint32_t vcpuid)
978 struct vcpu *vcpu = vcpu_find(vm, vcpuid);
979 TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
987 * vm - Virtual Machine
994 * Switch to executing the code for the VCPU given by vcpuid, within the VM
997 void vcpu_run(struct kvm_vm *vm, uint32_t vcpuid)
999 int ret = _vcpu_run(vm, vcpuid);
1000 TEST_ASSERT(ret == 0, "KVM_RUN IOCTL failed, "
1001 "rc: %i errno: %i", ret, errno);
1004 int _vcpu_run(struct kvm_vm *vm, uint32_t vcpuid)
1006 struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1009 TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1011 rc = ioctl(vcpu->fd, KVM_RUN, NULL);
1012 } while (rc == -1 && errno == EINTR);
1016 /* VM VCPU Set MP State
1019 * vm - Virtual Machine
1021 * mp_state - mp_state to be set
1027 * Sets the MP state of the VCPU given by vcpuid, to the state given
1030 void vcpu_set_mp_state(struct kvm_vm *vm, uint32_t vcpuid,
1031 struct kvm_mp_state *mp_state)
1033 struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1036 TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1038 ret = ioctl(vcpu->fd, KVM_SET_MP_STATE, mp_state);
1039 TEST_ASSERT(ret == 0, "KVM_SET_MP_STATE IOCTL failed, "
1040 "rc: %i errno: %i", ret, errno);
1046 * vm - Virtual Machine
1050 * regs - current state of VCPU regs
1054 * Obtains the current register state for the VCPU specified by vcpuid
1055 * and stores it at the location given by regs.
1057 void vcpu_regs_get(struct kvm_vm *vm,
1058 uint32_t vcpuid, struct kvm_regs *regs)
1060 struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1063 TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1066 ret = ioctl(vcpu->fd, KVM_GET_REGS, regs);
1067 TEST_ASSERT(ret == 0, "KVM_GET_REGS failed, rc: %i errno: %i",
1074 * vm - Virtual Machine
1076 * regs - Values to set VCPU regs to
1082 * Sets the regs of the VCPU specified by vcpuid to the values
1085 void vcpu_regs_set(struct kvm_vm *vm,
1086 uint32_t vcpuid, struct kvm_regs *regs)
1088 struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1091 TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1094 ret = ioctl(vcpu->fd, KVM_SET_REGS, regs);
1095 TEST_ASSERT(ret == 0, "KVM_SET_REGS failed, rc: %i errno: %i",
1099 void vcpu_events_get(struct kvm_vm *vm, uint32_t vcpuid,
1100 struct kvm_vcpu_events *events)
1102 struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1105 TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1108 ret = ioctl(vcpu->fd, KVM_GET_VCPU_EVENTS, events);
1109 TEST_ASSERT(ret == 0, "KVM_GET_VCPU_EVENTS, failed, rc: %i errno: %i",
1113 void vcpu_events_set(struct kvm_vm *vm, uint32_t vcpuid,
1114 struct kvm_vcpu_events *events)
1116 struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1119 TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1122 ret = ioctl(vcpu->fd, KVM_SET_VCPU_EVENTS, events);
1123 TEST_ASSERT(ret == 0, "KVM_SET_VCPU_EVENTS, failed, rc: %i errno: %i",
1130 * vm - Virtual Machine
1132 * num - number of arguments
1133 * ... - arguments, each of type uint64_t
1139 * Sets the first num function input arguments to the values
1140 * given as variable args. Each of the variable args is expected to
1141 * be of type uint64_t.
1143 void vcpu_args_set(struct kvm_vm *vm, uint32_t vcpuid, unsigned int num, ...)
1146 struct kvm_regs regs;
1148 TEST_ASSERT(num >= 1 && num <= 6, "Unsupported number of args,\n"
1153 vcpu_regs_get(vm, vcpuid, ®s);
1156 regs.rdi = va_arg(ap, uint64_t);
1159 regs.rsi = va_arg(ap, uint64_t);
1162 regs.rdx = va_arg(ap, uint64_t);
1165 regs.rcx = va_arg(ap, uint64_t);
1168 regs.r8 = va_arg(ap, uint64_t);
1171 regs.r9 = va_arg(ap, uint64_t);
1173 vcpu_regs_set(vm, vcpuid, ®s);
1177 /* VM VCPU System Regs Get
1180 * vm - Virtual Machine
1184 * sregs - current state of VCPU system regs
1188 * Obtains the current system register state for the VCPU specified by
1189 * vcpuid and stores it at the location given by sregs.
1191 void vcpu_sregs_get(struct kvm_vm *vm,
1192 uint32_t vcpuid, struct kvm_sregs *sregs)
1194 struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1197 TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1201 ret = ioctl(vcpu->fd, KVM_GET_SREGS, sregs);
1202 TEST_ASSERT(ret == 0, "KVM_GET_SREGS failed, rc: %i errno: %i",
1206 /* VM VCPU System Regs Set
1209 * vm - Virtual Machine
1211 * sregs - Values to set VCPU system regs to
1217 * Sets the system regs of the VCPU specified by vcpuid to the values
1220 void vcpu_sregs_set(struct kvm_vm *vm,
1221 uint32_t vcpuid, struct kvm_sregs *sregs)
1223 int ret = _vcpu_sregs_set(vm, vcpuid, sregs);
1224 TEST_ASSERT(ret == 0, "KVM_RUN IOCTL failed, "
1225 "rc: %i errno: %i", ret, errno);
1228 int _vcpu_sregs_set(struct kvm_vm *vm,
1229 uint32_t vcpuid, struct kvm_sregs *sregs)
1231 struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1234 TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1237 return ioctl(vcpu->fd, KVM_SET_SREGS, sregs);
1243 * vm - Virtual Machine
1245 * cmd - Ioctl number
1246 * arg - Argument to pass to the ioctl
1250 * Issues an arbitrary ioctl on a VCPU fd.
1252 void vcpu_ioctl(struct kvm_vm *vm,
1253 uint32_t vcpuid, unsigned long cmd, void *arg)
1255 struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1258 TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1260 ret = ioctl(vcpu->fd, cmd, arg);
1261 TEST_ASSERT(ret == 0, "vcpu ioctl %lu failed, rc: %i errno: %i (%s)",
1262 cmd, ret, errno, strerror(errno));
1268 * vm - Virtual Machine
1269 * cmd - Ioctl number
1270 * arg - Argument to pass to the ioctl
1274 * Issues an arbitrary ioctl on a VM fd.
1276 void vm_ioctl(struct kvm_vm *vm, unsigned long cmd, void *arg)
1280 ret = ioctl(vm->fd, cmd, arg);
1281 TEST_ASSERT(ret == 0, "vm ioctl %lu failed, rc: %i errno: %i (%s)",
1282 cmd, ret, errno, strerror(errno));
1288 * vm - Virtual Machine
1289 * indent - Left margin indent amount
1292 * stream - Output FILE stream
1296 * Dumps the current state of the VM given by vm, to the FILE stream
1299 void vm_dump(FILE *stream, struct kvm_vm *vm, uint8_t indent)
1301 struct userspace_mem_region *region;
1304 fprintf(stream, "%*smode: 0x%x\n", indent, "", vm->mode);
1305 fprintf(stream, "%*sfd: %i\n", indent, "", vm->fd);
1306 fprintf(stream, "%*spage_size: 0x%x\n", indent, "", vm->page_size);
1307 fprintf(stream, "%*sMem Regions:\n", indent, "");
1308 for (region = vm->userspace_mem_region_head; region;
1309 region = region->next) {
1310 fprintf(stream, "%*sguest_phys: 0x%lx size: 0x%lx "
1311 "host_virt: %p\n", indent + 2, "",
1312 (uint64_t) region->region.guest_phys_addr,
1313 (uint64_t) region->region.memory_size,
1315 fprintf(stream, "%*sunused_phy_pages: ", indent + 2, "");
1316 sparsebit_dump(stream, region->unused_phy_pages, 0);
1318 fprintf(stream, "%*sMapped Virtual Pages:\n", indent, "");
1319 sparsebit_dump(stream, vm->vpages_mapped, indent + 2);
1320 fprintf(stream, "%*spgd_created: %u\n", indent, "",
1322 if (vm->pgd_created) {
1323 fprintf(stream, "%*sVirtual Translation Tables:\n",
1325 virt_dump(stream, vm, indent + 4);
1327 fprintf(stream, "%*sVCPUs:\n", indent, "");
1328 for (vcpu = vm->vcpu_head; vcpu; vcpu = vcpu->next)
1329 vcpu_dump(stream, vm, vcpu->id, indent + 2);
1335 * vm - Virtual Machine
1337 * indent - Left margin indent amount
1340 * stream - Output FILE stream
1344 * Dumps the current state of the VCPU specified by vcpuid, within the VM
1345 * given by vm, to the FILE stream given by stream.
1347 void vcpu_dump(FILE *stream, struct kvm_vm *vm,
1348 uint32_t vcpuid, uint8_t indent)
1350 struct kvm_regs regs;
1351 struct kvm_sregs sregs;
1353 fprintf(stream, "%*scpuid: %u\n", indent, "", vcpuid);
1355 fprintf(stream, "%*sregs:\n", indent + 2, "");
1356 vcpu_regs_get(vm, vcpuid, ®s);
1357 regs_dump(stream, ®s, indent + 4);
1359 fprintf(stream, "%*ssregs:\n", indent + 2, "");
1360 vcpu_sregs_get(vm, vcpuid, &sregs);
1361 sregs_dump(stream, &sregs, indent + 4);
1364 /* Known KVM exit reasons */
1365 static struct exit_reason {
1366 unsigned int reason;
1368 } exit_reasons_known[] = {
1369 {KVM_EXIT_UNKNOWN, "UNKNOWN"},
1370 {KVM_EXIT_EXCEPTION, "EXCEPTION"},
1371 {KVM_EXIT_IO, "IO"},
1372 {KVM_EXIT_HYPERCALL, "HYPERCALL"},
1373 {KVM_EXIT_DEBUG, "DEBUG"},
1374 {KVM_EXIT_HLT, "HLT"},
1375 {KVM_EXIT_MMIO, "MMIO"},
1376 {KVM_EXIT_IRQ_WINDOW_OPEN, "IRQ_WINDOW_OPEN"},
1377 {KVM_EXIT_SHUTDOWN, "SHUTDOWN"},
1378 {KVM_EXIT_FAIL_ENTRY, "FAIL_ENTRY"},
1379 {KVM_EXIT_INTR, "INTR"},
1380 {KVM_EXIT_SET_TPR, "SET_TPR"},
1381 {KVM_EXIT_TPR_ACCESS, "TPR_ACCESS"},
1382 {KVM_EXIT_S390_SIEIC, "S390_SIEIC"},
1383 {KVM_EXIT_S390_RESET, "S390_RESET"},
1384 {KVM_EXIT_DCR, "DCR"},
1385 {KVM_EXIT_NMI, "NMI"},
1386 {KVM_EXIT_INTERNAL_ERROR, "INTERNAL_ERROR"},
1387 {KVM_EXIT_OSI, "OSI"},
1388 {KVM_EXIT_PAPR_HCALL, "PAPR_HCALL"},
1389 #ifdef KVM_EXIT_MEMORY_NOT_PRESENT
1390 {KVM_EXIT_MEMORY_NOT_PRESENT, "MEMORY_NOT_PRESENT"},
1394 /* Exit Reason String
1397 * exit_reason - Exit reason
1402 * Constant string pointer describing the exit reason.
1404 * Locates and returns a constant string that describes the KVM exit
1405 * reason given by exit_reason. If no such string is found, a constant
1406 * string of "Unknown" is returned.
1408 const char *exit_reason_str(unsigned int exit_reason)
1412 for (n1 = 0; n1 < ARRAY_SIZE(exit_reasons_known); n1++) {
1413 if (exit_reason == exit_reasons_known[n1].reason)
1414 return exit_reasons_known[n1].name;
1420 /* Physical Page Allocate
1423 * vm - Virtual Machine
1424 * paddr_min - Physical address minimum
1425 * memslot - Memory region to allocate page from
1430 * Starting physical address
1432 * Within the VM specified by vm, locates an available physical page
1433 * at or above paddr_min. If found, the page is marked as in use
1434 * and its address is returned. A TEST_ASSERT failure occurs if no
1435 * page is available at or above paddr_min.
1437 vm_paddr_t vm_phy_page_alloc(struct kvm_vm *vm,
1438 vm_paddr_t paddr_min, uint32_t memslot)
1440 struct userspace_mem_region *region;
1443 TEST_ASSERT((paddr_min % vm->page_size) == 0, "Min physical address "
1444 "not divisible by page size.\n"
1445 " paddr_min: 0x%lx page_size: 0x%x",
1446 paddr_min, vm->page_size);
1448 /* Locate memory region. */
1449 region = memslot2region(vm, memslot);
1451 /* Locate next available physical page at or above paddr_min. */
1452 pg = paddr_min >> vm->page_shift;
1454 if (!sparsebit_is_set(region->unused_phy_pages, pg)) {
1455 pg = sparsebit_next_set(region->unused_phy_pages, pg);
1457 fprintf(stderr, "No guest physical page available, "
1458 "paddr_min: 0x%lx page_size: 0x%x memslot: %u",
1459 paddr_min, vm->page_size, memslot);
1460 fputs("---- vm dump ----\n", stderr);
1461 vm_dump(stderr, vm, 2);
1466 /* Specify page as in use and return its address. */
1467 sparsebit_clear(region->unused_phy_pages, pg);
1469 return pg * vm->page_size;
1472 /* Address Guest Virtual to Host Virtual
1475 * vm - Virtual Machine
1476 * gva - VM virtual address
1481 * Equivalent host virtual address
1483 void *addr_gva2hva(struct kvm_vm *vm, vm_vaddr_t gva)
1485 return addr_gpa2hva(vm, addr_gva2gpa(vm, gva));