]> asedeno.scripts.mit.edu Git - linux.git/blob - tools/testing/selftests/kvm/lib/kvm_util.c
1634828733639fac64abfadd07e53feb28234545
[linux.git] / tools / testing / selftests / kvm / lib / kvm_util.c
1 /*
2  * tools/testing/selftests/kvm/lib/kvm_util.c
3  *
4  * Copyright (C) 2018, Google LLC.
5  *
6  * This work is licensed under the terms of the GNU GPL, version 2.
7  */
8
9 #include "test_util.h"
10 #include "kvm_util.h"
11 #include "kvm_util_internal.h"
12
13 #include <assert.h>
14 #include <sys/mman.h>
15 #include <sys/types.h>
16 #include <sys/stat.h>
17
18 #define KVM_DEV_PATH "/dev/kvm"
19
20 #define KVM_UTIL_PGS_PER_HUGEPG 512
21 #define KVM_UTIL_MIN_PADDR      0x2000
22
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)
25 {
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);
30 }
31
32 /* Capability
33  *
34  * Input Args:
35  *   cap - Capability
36  *
37  * Output Args: None
38  *
39  * Return:
40  *   On success, the Value corresponding to the capability (KVM_CAP_*)
41  *   specified by the value of cap.  On failure a TEST_ASSERT failure
42  *   is produced.
43  *
44  * Looks up and returns the value corresponding to the capability
45  * (KVM_CAP_*) given by cap.
46  */
47 int kvm_check_cap(long cap)
48 {
49         int ret;
50         int kvm_fd;
51
52         kvm_fd = open(KVM_DEV_PATH, O_RDONLY);
53         if (kvm_fd < 0)
54                 exit(KSFT_SKIP);
55
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);
59
60         close(kvm_fd);
61
62         return ret;
63 }
64
65 /* VM Create
66  *
67  * Input Args:
68  *   mode - VM Mode (e.g. VM_MODE_FLAT48PG)
69  *   phy_pages - Physical memory pages
70  *   perm - permission
71  *
72  * Output Args: None
73  *
74  * Return:
75  *   Pointer to opaque structure that describes the created VM.
76  *
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).
82  */
83 struct kvm_vm *vm_create(enum vm_guest_mode mode, uint64_t phy_pages, int perm)
84 {
85         struct kvm_vm *vm;
86         int kvm_fd;
87
88         /* Allocate memory. */
89         vm = calloc(1, sizeof(*vm));
90         TEST_ASSERT(vm != NULL, "Insufficent Memory");
91
92         vm->mode = mode;
93         kvm_fd = open(KVM_DEV_PATH, perm);
94         if (kvm_fd < 0)
95                 exit(KSFT_SKIP);
96
97         /* Create VM. */
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);
101
102         close(kvm_fd);
103
104         /* Setup mode specific traits. */
105         switch (vm->mode) {
106         case VM_MODE_FLAT48PG:
107                 vm->page_size = 0x1000;
108                 vm->page_shift = 12;
109
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);
117
118                 /* Limit physical addresses to 52-bits. */
119                 vm->max_gfn = ((1ULL << 52) >> vm->page_shift) - 1;
120                 break;
121
122         default:
123                 TEST_ASSERT(false, "Unknown guest mode, mode: 0x%x", mode);
124         }
125
126         /* Allocate and setup memory for guest. */
127         vm->vpages_mapped = sparsebit_alloc();
128         if (phy_pages != 0)
129                 vm_userspace_mem_region_add(vm, VM_MEM_SRC_ANONYMOUS,
130                                             0, 0, phy_pages, 0);
131
132         return vm;
133 }
134
135 /* Userspace Memory Region Find
136  *
137  * Input Args:
138  *   vm - Virtual Machine
139  *   start - Starting VM physical address
140  *   end - Ending VM physical address, inclusive.
141  *
142  * Output Args: None
143  *
144  * Return:
145  *   Pointer to overlapping region, NULL if no such region.
146  *
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
151  * region exists.
152  */
153 static struct userspace_mem_region *userspace_mem_region_find(
154         struct kvm_vm *vm, uint64_t start, uint64_t end)
155 {
156         struct userspace_mem_region *region;
157
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)
164                         return region;
165         }
166
167         return NULL;
168 }
169
170 /* KVM Userspace Memory Region Find
171  *
172  * Input Args:
173  *   vm - Virtual Machine
174  *   start - Starting VM physical address
175  *   end - Ending VM physical address, inclusive.
176  *
177  * Output Args: None
178  *
179  * Return:
180  *   Pointer to overlapping region, NULL if no such region.
181  *
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.
184  */
185 struct kvm_userspace_memory_region *
186 kvm_userspace_memory_region_find(struct kvm_vm *vm, uint64_t start,
187                                  uint64_t end)
188 {
189         struct userspace_mem_region *region;
190
191         region = userspace_mem_region_find(vm, start, end);
192         if (!region)
193                 return NULL;
194
195         return &region->region;
196 }
197
198 /* VCPU Find
199  *
200  * Input Args:
201  *   vm - Virtual Machine
202  *   vcpuid - VCPU ID
203  *
204  * Output Args: None
205  *
206  * Return:
207  *   Pointer to VCPU structure
208  *
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.
212  */
213 struct vcpu *vcpu_find(struct kvm_vm *vm,
214         uint32_t vcpuid)
215 {
216         struct vcpu *vcpup;
217
218         for (vcpup = vm->vcpu_head; vcpup; vcpup = vcpup->next) {
219                 if (vcpup->id == vcpuid)
220                         return vcpup;
221         }
222
223         return NULL;
224 }
225
226 /* VM VCPU Remove
227  *
228  * Input Args:
229  *   vm - Virtual Machine
230  *   vcpuid - VCPU ID
231  *
232  * Output Args: None
233  *
234  * Return: None, TEST_ASSERT failures for all error conditions
235  *
236  * Within the VM specified by vm, removes the VCPU given by vcpuid.
237  */
238 static void vm_vcpu_rm(struct kvm_vm *vm, uint32_t vcpuid)
239 {
240         struct vcpu *vcpu = vcpu_find(vm, vcpuid);
241         int ret;
242
243         ret = munmap(vcpu->state, sizeof(*vcpu->state));
244         TEST_ASSERT(ret == 0, "munmap of VCPU fd failed, rc: %i "
245                 "errno: %i", ret, errno);
246         close(vcpu->fd);
247         TEST_ASSERT(ret == 0, "Close of VCPU fd failed, rc: %i "
248                 "errno: %i", ret, errno);
249
250         if (vcpu->next)
251                 vcpu->next->prev = vcpu->prev;
252         if (vcpu->prev)
253                 vcpu->prev->next = vcpu->next;
254         else
255                 vm->vcpu_head = vcpu->next;
256         free(vcpu);
257 }
258
259
260 /* Destroys and frees the VM pointed to by vmp.
261  */
262 void kvm_vm_free(struct kvm_vm *vmp)
263 {
264         int ret;
265
266         if (vmp == NULL)
267                 return;
268
269         /* Free userspace_mem_regions. */
270         while (vmp->userspace_mem_region_head) {
271                 struct userspace_mem_region *region
272                         = vmp->userspace_mem_region_head;
273
274                 region->region.memory_size = 0;
275                 ret = ioctl(vmp->fd, KVM_SET_USER_MEMORY_REGION,
276                         &region->region);
277                 TEST_ASSERT(ret == 0, "KVM_SET_USER_MEMORY_REGION IOCTL failed, "
278                         "rc: %i errno: %i", ret, errno);
279
280                 vmp->userspace_mem_region_head = region->next;
281                 sparsebit_free(&region->unused_phy_pages);
282                 ret = munmap(region->mmap_start, region->mmap_size);
283                 TEST_ASSERT(ret == 0, "munmap failed, rc: %i errno: %i",
284                             ret, errno);
285
286                 free(region);
287         }
288
289         /* Free VCPUs. */
290         while (vmp->vcpu_head)
291                 vm_vcpu_rm(vmp, vmp->vcpu_head->id);
292
293         /* Free sparsebit arrays. */
294         sparsebit_free(&vmp->vpages_valid);
295         sparsebit_free(&vmp->vpages_mapped);
296
297         /* Close file descriptor for the VM. */
298         ret = close(vmp->fd);
299         TEST_ASSERT(ret == 0, "Close of vm fd failed,\n"
300                 "  vmp->fd: %i rc: %i errno: %i", vmp->fd, ret, errno);
301
302         close(vmp->kvm_fd);
303         TEST_ASSERT(ret == 0, "Close of /dev/kvm fd failed,\n"
304                 "  vmp->kvm_fd: %i rc: %i errno: %i", vmp->kvm_fd, ret, errno);
305
306         /* Free the structure describing the VM. */
307         free(vmp);
308 }
309
310 /* Memory Compare, host virtual to guest virtual
311  *
312  * Input Args:
313  *   hva - Starting host virtual address
314  *   vm - Virtual Machine
315  *   gva - Starting guest virtual address
316  *   len - number of bytes to compare
317  *
318  * Output Args: None
319  *
320  * Input/Output Args: None
321  *
322  * Return:
323  *   Returns 0 if the bytes starting at hva for a length of len
324  *   are equal the guest virtual bytes starting at gva.  Returns
325  *   a value < 0, if bytes at hva are less than those at gva.
326  *   Otherwise a value > 0 is returned.
327  *
328  * Compares the bytes starting at the host virtual address hva, for
329  * a length of len, to the guest bytes starting at the guest virtual
330  * address given by gva.
331  */
332 int kvm_memcmp_hva_gva(void *hva,
333         struct kvm_vm *vm, vm_vaddr_t gva, size_t len)
334 {
335         size_t amt;
336
337         /* Compare a batch of bytes until either a match is found
338          * or all the bytes have been compared.
339          */
340         for (uintptr_t offset = 0; offset < len; offset += amt) {
341                 uintptr_t ptr1 = (uintptr_t)hva + offset;
342
343                 /* Determine host address for guest virtual address
344                  * at offset.
345                  */
346                 uintptr_t ptr2 = (uintptr_t)addr_gva2hva(vm, gva + offset);
347
348                 /* Determine amount to compare on this pass.
349                  * Don't allow the comparsion to cross a page boundary.
350                  */
351                 amt = len - offset;
352                 if ((ptr1 >> vm->page_shift) != ((ptr1 + amt) >> vm->page_shift))
353                         amt = vm->page_size - (ptr1 % vm->page_size);
354                 if ((ptr2 >> vm->page_shift) != ((ptr2 + amt) >> vm->page_shift))
355                         amt = vm->page_size - (ptr2 % vm->page_size);
356
357                 assert((ptr1 >> vm->page_shift) == ((ptr1 + amt - 1) >> vm->page_shift));
358                 assert((ptr2 >> vm->page_shift) == ((ptr2 + amt - 1) >> vm->page_shift));
359
360                 /* Perform the comparison.  If there is a difference
361                  * return that result to the caller, otherwise need
362                  * to continue on looking for a mismatch.
363                  */
364                 int ret = memcmp((void *)ptr1, (void *)ptr2, amt);
365                 if (ret != 0)
366                         return ret;
367         }
368
369         /* No mismatch found.  Let the caller know the two memory
370          * areas are equal.
371          */
372         return 0;
373 }
374
375 /* Allocate an instance of struct kvm_cpuid2
376  *
377  * Input Args: None
378  *
379  * Output Args: None
380  *
381  * Return: A pointer to the allocated struct. The caller is responsible
382  * for freeing this struct.
383  *
384  * Since kvm_cpuid2 uses a 0-length array to allow a the size of the
385  * array to be decided at allocation time, allocation is slightly
386  * complicated. This function uses a reasonable default length for
387  * the array and performs the appropriate allocation.
388  */
389 static struct kvm_cpuid2 *allocate_kvm_cpuid2(void)
390 {
391         struct kvm_cpuid2 *cpuid;
392         int nent = 100;
393         size_t size;
394
395         size = sizeof(*cpuid);
396         size += nent * sizeof(struct kvm_cpuid_entry2);
397         cpuid = malloc(size);
398         if (!cpuid) {
399                 perror("malloc");
400                 abort();
401         }
402
403         cpuid->nent = nent;
404
405         return cpuid;
406 }
407
408 /* KVM Supported CPUID Get
409  *
410  * Input Args: None
411  *
412  * Output Args:
413  *
414  * Return: The supported KVM CPUID
415  *
416  * Get the guest CPUID supported by KVM.
417  */
418 struct kvm_cpuid2 *kvm_get_supported_cpuid(void)
419 {
420         static struct kvm_cpuid2 *cpuid;
421         int ret;
422         int kvm_fd;
423
424         if (cpuid)
425                 return cpuid;
426
427         cpuid = allocate_kvm_cpuid2();
428         kvm_fd = open(KVM_DEV_PATH, O_RDONLY);
429         if (kvm_fd < 0)
430                 exit(KSFT_SKIP);
431
432         ret = ioctl(kvm_fd, KVM_GET_SUPPORTED_CPUID, cpuid);
433         TEST_ASSERT(ret == 0, "KVM_GET_SUPPORTED_CPUID failed %d %d\n",
434                     ret, errno);
435
436         close(kvm_fd);
437         return cpuid;
438 }
439
440 /* Locate a cpuid entry.
441  *
442  * Input Args:
443  *   cpuid: The cpuid.
444  *   function: The function of the cpuid entry to find.
445  *
446  * Output Args: None
447  *
448  * Return: A pointer to the cpuid entry. Never returns NULL.
449  */
450 struct kvm_cpuid_entry2 *
451 kvm_get_supported_cpuid_index(uint32_t function, uint32_t index)
452 {
453         struct kvm_cpuid2 *cpuid;
454         struct kvm_cpuid_entry2 *entry = NULL;
455         int i;
456
457         cpuid = kvm_get_supported_cpuid();
458         for (i = 0; i < cpuid->nent; i++) {
459                 if (cpuid->entries[i].function == function &&
460                     cpuid->entries[i].index == index) {
461                         entry = &cpuid->entries[i];
462                         break;
463                 }
464         }
465
466         TEST_ASSERT(entry, "Guest CPUID entry not found: (EAX=%x, ECX=%x).",
467                     function, index);
468         return entry;
469 }
470
471 /* VM Userspace Memory Region Add
472  *
473  * Input Args:
474  *   vm - Virtual Machine
475  *   backing_src - Storage source for this region.
476  *                 NULL to use anonymous memory.
477  *   guest_paddr - Starting guest physical address
478  *   slot - KVM region slot
479  *   npages - Number of physical pages
480  *   flags - KVM memory region flags (e.g. KVM_MEM_LOG_DIRTY_PAGES)
481  *
482  * Output Args: None
483  *
484  * Return: None
485  *
486  * Allocates a memory area of the number of pages specified by npages
487  * and maps it to the VM specified by vm, at a starting physical address
488  * given by guest_paddr.  The region is created with a KVM region slot
489  * given by slot, which must be unique and < KVM_MEM_SLOTS_NUM.  The
490  * region is created with the flags given by flags.
491  */
492 void vm_userspace_mem_region_add(struct kvm_vm *vm,
493         enum vm_mem_backing_src_type src_type,
494         uint64_t guest_paddr, uint32_t slot, uint64_t npages,
495         uint32_t flags)
496 {
497         int ret;
498         unsigned long pmem_size = 0;
499         struct userspace_mem_region *region;
500         size_t huge_page_size = KVM_UTIL_PGS_PER_HUGEPG * vm->page_size;
501
502         TEST_ASSERT((guest_paddr % vm->page_size) == 0, "Guest physical "
503                 "address not on a page boundary.\n"
504                 "  guest_paddr: 0x%lx vm->page_size: 0x%x",
505                 guest_paddr, vm->page_size);
506         TEST_ASSERT((((guest_paddr >> vm->page_shift) + npages) - 1)
507                 <= vm->max_gfn, "Physical range beyond maximum "
508                 "supported physical address,\n"
509                 "  guest_paddr: 0x%lx npages: 0x%lx\n"
510                 "  vm->max_gfn: 0x%lx vm->page_size: 0x%x",
511                 guest_paddr, npages, vm->max_gfn, vm->page_size);
512
513         /* Confirm a mem region with an overlapping address doesn't
514          * already exist.
515          */
516         region = (struct userspace_mem_region *) userspace_mem_region_find(
517                 vm, guest_paddr, guest_paddr + npages * vm->page_size);
518         if (region != NULL)
519                 TEST_ASSERT(false, "overlapping userspace_mem_region already "
520                         "exists\n"
521                         "  requested guest_paddr: 0x%lx npages: 0x%lx "
522                         "page_size: 0x%x\n"
523                         "  existing guest_paddr: 0x%lx size: 0x%lx",
524                         guest_paddr, npages, vm->page_size,
525                         (uint64_t) region->region.guest_phys_addr,
526                         (uint64_t) region->region.memory_size);
527
528         /* Confirm no region with the requested slot already exists. */
529         for (region = vm->userspace_mem_region_head; region;
530                 region = region->next) {
531                 if (region->region.slot == slot)
532                         break;
533                 if ((guest_paddr <= (region->region.guest_phys_addr
534                                 + region->region.memory_size))
535                         && ((guest_paddr + npages * vm->page_size)
536                                 >= region->region.guest_phys_addr))
537                         break;
538         }
539         if (region != NULL)
540                 TEST_ASSERT(false, "A mem region with the requested slot "
541                         "or overlapping physical memory range already exists.\n"
542                         "  requested slot: %u paddr: 0x%lx npages: 0x%lx\n"
543                         "  existing slot: %u paddr: 0x%lx size: 0x%lx",
544                         slot, guest_paddr, npages,
545                         region->region.slot,
546                         (uint64_t) region->region.guest_phys_addr,
547                         (uint64_t) region->region.memory_size);
548
549         /* Allocate and initialize new mem region structure. */
550         region = calloc(1, sizeof(*region));
551         TEST_ASSERT(region != NULL, "Insufficient Memory");
552         region->mmap_size = npages * vm->page_size;
553
554         /* Enough memory to align up to a huge page. */
555         if (src_type == VM_MEM_SRC_ANONYMOUS_THP)
556                 region->mmap_size += huge_page_size;
557         region->mmap_start = mmap(NULL, region->mmap_size,
558                                   PROT_READ | PROT_WRITE,
559                                   MAP_PRIVATE | MAP_ANONYMOUS
560                                   | (src_type == VM_MEM_SRC_ANONYMOUS_HUGETLB ? MAP_HUGETLB : 0),
561                                   -1, 0);
562         TEST_ASSERT(region->mmap_start != MAP_FAILED,
563                     "test_malloc failed, mmap_start: %p errno: %i",
564                     region->mmap_start, errno);
565
566         /* Align THP allocation up to start of a huge page. */
567         region->host_mem = align(region->mmap_start,
568                                  src_type == VM_MEM_SRC_ANONYMOUS_THP ?  huge_page_size : 1);
569
570         /* As needed perform madvise */
571         if (src_type == VM_MEM_SRC_ANONYMOUS || src_type == VM_MEM_SRC_ANONYMOUS_THP) {
572                 ret = madvise(region->host_mem, npages * vm->page_size,
573                              src_type == VM_MEM_SRC_ANONYMOUS ? MADV_NOHUGEPAGE : MADV_HUGEPAGE);
574                 TEST_ASSERT(ret == 0, "madvise failed,\n"
575                             "  addr: %p\n"
576                             "  length: 0x%lx\n"
577                             "  src_type: %x",
578                             region->host_mem, npages * vm->page_size, src_type);
579         }
580
581         region->unused_phy_pages = sparsebit_alloc();
582         sparsebit_set_num(region->unused_phy_pages,
583                 guest_paddr >> vm->page_shift, npages);
584         region->region.slot = slot;
585         region->region.flags = flags;
586         region->region.guest_phys_addr = guest_paddr;
587         region->region.memory_size = npages * vm->page_size;
588         region->region.userspace_addr = (uintptr_t) region->host_mem;
589         ret = ioctl(vm->fd, KVM_SET_USER_MEMORY_REGION, &region->region);
590         TEST_ASSERT(ret == 0, "KVM_SET_USER_MEMORY_REGION IOCTL failed,\n"
591                 "  rc: %i errno: %i\n"
592                 "  slot: %u flags: 0x%x\n"
593                 "  guest_phys_addr: 0x%lx size: 0x%lx",
594                 ret, errno, slot, flags,
595                 guest_paddr, (uint64_t) region->region.memory_size);
596
597         /* Add to linked-list of memory regions. */
598         if (vm->userspace_mem_region_head)
599                 vm->userspace_mem_region_head->prev = region;
600         region->next = vm->userspace_mem_region_head;
601         vm->userspace_mem_region_head = region;
602 }
603
604 /* Memslot to region
605  *
606  * Input Args:
607  *   vm - Virtual Machine
608  *   memslot - KVM memory slot ID
609  *
610  * Output Args: None
611  *
612  * Return:
613  *   Pointer to memory region structure that describe memory region
614  *   using kvm memory slot ID given by memslot.  TEST_ASSERT failure
615  *   on error (e.g. currently no memory region using memslot as a KVM
616  *   memory slot ID).
617  */
618 static struct userspace_mem_region *memslot2region(struct kvm_vm *vm,
619         uint32_t memslot)
620 {
621         struct userspace_mem_region *region;
622
623         for (region = vm->userspace_mem_region_head; region;
624                 region = region->next) {
625                 if (region->region.slot == memslot)
626                         break;
627         }
628         if (region == NULL) {
629                 fprintf(stderr, "No mem region with the requested slot found,\n"
630                         "  requested slot: %u\n", memslot);
631                 fputs("---- vm dump ----\n", stderr);
632                 vm_dump(stderr, vm, 2);
633                 TEST_ASSERT(false, "Mem region not found");
634         }
635
636         return region;
637 }
638
639 /* VM Memory Region Flags Set
640  *
641  * Input Args:
642  *   vm - Virtual Machine
643  *   flags - Starting guest physical address
644  *
645  * Output Args: None
646  *
647  * Return: None
648  *
649  * Sets the flags of the memory region specified by the value of slot,
650  * to the values given by flags.
651  */
652 void vm_mem_region_set_flags(struct kvm_vm *vm, uint32_t slot, uint32_t flags)
653 {
654         int ret;
655         struct userspace_mem_region *region;
656
657         /* Locate memory region. */
658         region = memslot2region(vm, slot);
659
660         region->region.flags = flags;
661
662         ret = ioctl(vm->fd, KVM_SET_USER_MEMORY_REGION, &region->region);
663
664         TEST_ASSERT(ret == 0, "KVM_SET_USER_MEMORY_REGION IOCTL failed,\n"
665                 "  rc: %i errno: %i slot: %u flags: 0x%x",
666                 ret, errno, slot, flags);
667 }
668
669 /* VCPU mmap Size
670  *
671  * Input Args: None
672  *
673  * Output Args: None
674  *
675  * Return:
676  *   Size of VCPU state
677  *
678  * Returns the size of the structure pointed to by the return value
679  * of vcpu_state().
680  */
681 static int vcpu_mmap_sz(void)
682 {
683         int dev_fd, ret;
684
685         dev_fd = open(KVM_DEV_PATH, O_RDONLY);
686         if (dev_fd < 0)
687                 exit(KSFT_SKIP);
688
689         ret = ioctl(dev_fd, KVM_GET_VCPU_MMAP_SIZE, NULL);
690         TEST_ASSERT(ret >= sizeof(struct kvm_run),
691                 "%s KVM_GET_VCPU_MMAP_SIZE ioctl failed, rc: %i errno: %i",
692                 __func__, ret, errno);
693
694         close(dev_fd);
695
696         return ret;
697 }
698
699 /* VM VCPU Add
700  *
701  * Input Args:
702  *   vm - Virtual Machine
703  *   vcpuid - VCPU ID
704  *
705  * Output Args: None
706  *
707  * Return: None
708  *
709  * Creates and adds to the VM specified by vm and virtual CPU with
710  * the ID given by vcpuid.
711  */
712 void vm_vcpu_add(struct kvm_vm *vm, uint32_t vcpuid, int pgd_memslot, int gdt_memslot)
713 {
714         struct vcpu *vcpu;
715
716         /* Confirm a vcpu with the specified id doesn't already exist. */
717         vcpu = vcpu_find(vm, vcpuid);
718         if (vcpu != NULL)
719                 TEST_ASSERT(false, "vcpu with the specified id "
720                         "already exists,\n"
721                         "  requested vcpuid: %u\n"
722                         "  existing vcpuid: %u state: %p",
723                         vcpuid, vcpu->id, vcpu->state);
724
725         /* Allocate and initialize new vcpu structure. */
726         vcpu = calloc(1, sizeof(*vcpu));
727         TEST_ASSERT(vcpu != NULL, "Insufficient Memory");
728         vcpu->id = vcpuid;
729         vcpu->fd = ioctl(vm->fd, KVM_CREATE_VCPU, vcpuid);
730         TEST_ASSERT(vcpu->fd >= 0, "KVM_CREATE_VCPU failed, rc: %i errno: %i",
731                 vcpu->fd, errno);
732
733         TEST_ASSERT(vcpu_mmap_sz() >= sizeof(*vcpu->state), "vcpu mmap size "
734                 "smaller than expected, vcpu_mmap_sz: %i expected_min: %zi",
735                 vcpu_mmap_sz(), sizeof(*vcpu->state));
736         vcpu->state = (struct kvm_run *) mmap(NULL, sizeof(*vcpu->state),
737                 PROT_READ | PROT_WRITE, MAP_SHARED, vcpu->fd, 0);
738         TEST_ASSERT(vcpu->state != MAP_FAILED, "mmap vcpu_state failed, "
739                 "vcpu id: %u errno: %i", vcpuid, errno);
740
741         /* Add to linked-list of VCPUs. */
742         if (vm->vcpu_head)
743                 vm->vcpu_head->prev = vcpu;
744         vcpu->next = vm->vcpu_head;
745         vm->vcpu_head = vcpu;
746
747         vcpu_setup(vm, vcpuid, pgd_memslot, gdt_memslot);
748 }
749
750 /* VM Virtual Address Unused Gap
751  *
752  * Input Args:
753  *   vm - Virtual Machine
754  *   sz - Size (bytes)
755  *   vaddr_min - Minimum Virtual Address
756  *
757  * Output Args: None
758  *
759  * Return:
760  *   Lowest virtual address at or below vaddr_min, with at least
761  *   sz unused bytes.  TEST_ASSERT failure if no area of at least
762  *   size sz is available.
763  *
764  * Within the VM specified by vm, locates the lowest starting virtual
765  * address >= vaddr_min, that has at least sz unallocated bytes.  A
766  * TEST_ASSERT failure occurs for invalid input or no area of at least
767  * sz unallocated bytes >= vaddr_min is available.
768  */
769 static vm_vaddr_t vm_vaddr_unused_gap(struct kvm_vm *vm, size_t sz,
770         vm_vaddr_t vaddr_min)
771 {
772         uint64_t pages = (sz + vm->page_size - 1) >> vm->page_shift;
773
774         /* Determine lowest permitted virtual page index. */
775         uint64_t pgidx_start = (vaddr_min + vm->page_size - 1) >> vm->page_shift;
776         if ((pgidx_start * vm->page_size) < vaddr_min)
777                         goto no_va_found;
778
779         /* Loop over section with enough valid virtual page indexes. */
780         if (!sparsebit_is_set_num(vm->vpages_valid,
781                 pgidx_start, pages))
782                 pgidx_start = sparsebit_next_set_num(vm->vpages_valid,
783                         pgidx_start, pages);
784         do {
785                 /*
786                  * Are there enough unused virtual pages available at
787                  * the currently proposed starting virtual page index.
788                  * If not, adjust proposed starting index to next
789                  * possible.
790                  */
791                 if (sparsebit_is_clear_num(vm->vpages_mapped,
792                         pgidx_start, pages))
793                         goto va_found;
794                 pgidx_start = sparsebit_next_clear_num(vm->vpages_mapped,
795                         pgidx_start, pages);
796                 if (pgidx_start == 0)
797                         goto no_va_found;
798
799                 /*
800                  * If needed, adjust proposed starting virtual address,
801                  * to next range of valid virtual addresses.
802                  */
803                 if (!sparsebit_is_set_num(vm->vpages_valid,
804                         pgidx_start, pages)) {
805                         pgidx_start = sparsebit_next_set_num(
806                                 vm->vpages_valid, pgidx_start, pages);
807                         if (pgidx_start == 0)
808                                 goto no_va_found;
809                 }
810         } while (pgidx_start != 0);
811
812 no_va_found:
813         TEST_ASSERT(false, "No vaddr of specified pages available, "
814                 "pages: 0x%lx", pages);
815
816         /* NOT REACHED */
817         return -1;
818
819 va_found:
820         TEST_ASSERT(sparsebit_is_set_num(vm->vpages_valid,
821                 pgidx_start, pages),
822                 "Unexpected, invalid virtual page index range,\n"
823                 "  pgidx_start: 0x%lx\n"
824                 "  pages: 0x%lx",
825                 pgidx_start, pages);
826         TEST_ASSERT(sparsebit_is_clear_num(vm->vpages_mapped,
827                 pgidx_start, pages),
828                 "Unexpected, pages already mapped,\n"
829                 "  pgidx_start: 0x%lx\n"
830                 "  pages: 0x%lx",
831                 pgidx_start, pages);
832
833         return pgidx_start * vm->page_size;
834 }
835
836 /* VM Virtual Address Allocate
837  *
838  * Input Args:
839  *   vm - Virtual Machine
840  *   sz - Size in bytes
841  *   vaddr_min - Minimum starting virtual address
842  *   data_memslot - Memory region slot for data pages
843  *   pgd_memslot - Memory region slot for new virtual translation tables
844  *
845  * Output Args: None
846  *
847  * Return:
848  *   Starting guest virtual address
849  *
850  * Allocates at least sz bytes within the virtual address space of the vm
851  * given by vm.  The allocated bytes are mapped to a virtual address >=
852  * the address given by vaddr_min.  Note that each allocation uses a
853  * a unique set of pages, with the minimum real allocation being at least
854  * a page.
855  */
856 vm_vaddr_t vm_vaddr_alloc(struct kvm_vm *vm, size_t sz, vm_vaddr_t vaddr_min,
857         uint32_t data_memslot, uint32_t pgd_memslot)
858 {
859         uint64_t pages = (sz >> vm->page_shift) + ((sz % vm->page_size) != 0);
860
861         virt_pgd_alloc(vm, pgd_memslot);
862
863         /* Find an unused range of virtual page addresses of at least
864          * pages in length.
865          */
866         vm_vaddr_t vaddr_start = vm_vaddr_unused_gap(vm, sz, vaddr_min);
867
868         /* Map the virtual pages. */
869         for (vm_vaddr_t vaddr = vaddr_start; pages > 0;
870                 pages--, vaddr += vm->page_size) {
871                 vm_paddr_t paddr;
872
873                 paddr = vm_phy_page_alloc(vm, KVM_UTIL_MIN_PADDR, data_memslot);
874
875                 virt_pg_map(vm, vaddr, paddr, pgd_memslot);
876
877                 sparsebit_set(vm->vpages_mapped,
878                         vaddr >> vm->page_shift);
879         }
880
881         return vaddr_start;
882 }
883
884 /* Address VM Physical to Host Virtual
885  *
886  * Input Args:
887  *   vm - Virtual Machine
888  *   gpa - VM physical address
889  *
890  * Output Args: None
891  *
892  * Return:
893  *   Equivalent host virtual address
894  *
895  * Locates the memory region containing the VM physical address given
896  * by gpa, within the VM given by vm.  When found, the host virtual
897  * address providing the memory to the vm physical address is returned.
898  * A TEST_ASSERT failure occurs if no region containing gpa exists.
899  */
900 void *addr_gpa2hva(struct kvm_vm *vm, vm_paddr_t gpa)
901 {
902         struct userspace_mem_region *region;
903         for (region = vm->userspace_mem_region_head; region;
904              region = region->next) {
905                 if ((gpa >= region->region.guest_phys_addr)
906                         && (gpa <= (region->region.guest_phys_addr
907                                 + region->region.memory_size - 1)))
908                         return (void *) ((uintptr_t) region->host_mem
909                                 + (gpa - region->region.guest_phys_addr));
910         }
911
912         TEST_ASSERT(false, "No vm physical memory at 0x%lx", gpa);
913         return NULL;
914 }
915
916 /* Address Host Virtual to VM Physical
917  *
918  * Input Args:
919  *   vm - Virtual Machine
920  *   hva - Host virtual address
921  *
922  * Output Args: None
923  *
924  * Return:
925  *   Equivalent VM physical address
926  *
927  * Locates the memory region containing the host virtual address given
928  * by hva, within the VM given by vm.  When found, the equivalent
929  * VM physical address is returned. A TEST_ASSERT failure occurs if no
930  * region containing hva exists.
931  */
932 vm_paddr_t addr_hva2gpa(struct kvm_vm *vm, void *hva)
933 {
934         struct userspace_mem_region *region;
935         for (region = vm->userspace_mem_region_head; region;
936              region = region->next) {
937                 if ((hva >= region->host_mem)
938                         && (hva <= (region->host_mem
939                                 + region->region.memory_size - 1)))
940                         return (vm_paddr_t) ((uintptr_t)
941                                 region->region.guest_phys_addr
942                                 + (hva - (uintptr_t) region->host_mem));
943         }
944
945         TEST_ASSERT(false, "No mapping to a guest physical address, "
946                 "hva: %p", hva);
947         return -1;
948 }
949
950 /* VM Create IRQ Chip
951  *
952  * Input Args:
953  *   vm - Virtual Machine
954  *
955  * Output Args: None
956  *
957  * Return: None
958  *
959  * Creates an interrupt controller chip for the VM specified by vm.
960  */
961 void vm_create_irqchip(struct kvm_vm *vm)
962 {
963         int ret;
964
965         ret = ioctl(vm->fd, KVM_CREATE_IRQCHIP, 0);
966         TEST_ASSERT(ret == 0, "KVM_CREATE_IRQCHIP IOCTL failed, "
967                 "rc: %i errno: %i", ret, errno);
968 }
969
970 /* VM VCPU State
971  *
972  * Input Args:
973  *   vm - Virtual Machine
974  *   vcpuid - VCPU ID
975  *
976  * Output Args: None
977  *
978  * Return:
979  *   Pointer to structure that describes the state of the VCPU.
980  *
981  * Locates and returns a pointer to a structure that describes the
982  * state of the VCPU with the given vcpuid.
983  */
984 struct kvm_run *vcpu_state(struct kvm_vm *vm, uint32_t vcpuid)
985 {
986         struct vcpu *vcpu = vcpu_find(vm, vcpuid);
987         TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
988
989         return vcpu->state;
990 }
991
992 /* VM VCPU Run
993  *
994  * Input Args:
995  *   vm - Virtual Machine
996  *   vcpuid - VCPU ID
997  *
998  * Output Args: None
999  *
1000  * Return: None
1001  *
1002  * Switch to executing the code for the VCPU given by vcpuid, within the VM
1003  * given by vm.
1004  */
1005 void vcpu_run(struct kvm_vm *vm, uint32_t vcpuid)
1006 {
1007         int ret = _vcpu_run(vm, vcpuid);
1008         TEST_ASSERT(ret == 0, "KVM_RUN IOCTL failed, "
1009                 "rc: %i errno: %i", ret, errno);
1010 }
1011
1012 int _vcpu_run(struct kvm_vm *vm, uint32_t vcpuid)
1013 {
1014         struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1015         int rc;
1016
1017         TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1018         do {
1019                 rc = ioctl(vcpu->fd, KVM_RUN, NULL);
1020         } while (rc == -1 && errno == EINTR);
1021         return rc;
1022 }
1023
1024 /* VM VCPU Set MP State
1025  *
1026  * Input Args:
1027  *   vm - Virtual Machine
1028  *   vcpuid - VCPU ID
1029  *   mp_state - mp_state to be set
1030  *
1031  * Output Args: None
1032  *
1033  * Return: None
1034  *
1035  * Sets the MP state of the VCPU given by vcpuid, to the state given
1036  * by mp_state.
1037  */
1038 void vcpu_set_mp_state(struct kvm_vm *vm, uint32_t vcpuid,
1039         struct kvm_mp_state *mp_state)
1040 {
1041         struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1042         int ret;
1043
1044         TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1045
1046         ret = ioctl(vcpu->fd, KVM_SET_MP_STATE, mp_state);
1047         TEST_ASSERT(ret == 0, "KVM_SET_MP_STATE IOCTL failed, "
1048                 "rc: %i errno: %i", ret, errno);
1049 }
1050
1051 /* VM VCPU Regs Get
1052  *
1053  * Input Args:
1054  *   vm - Virtual Machine
1055  *   vcpuid - VCPU ID
1056  *
1057  * Output Args:
1058  *   regs - current state of VCPU regs
1059  *
1060  * Return: None
1061  *
1062  * Obtains the current register state for the VCPU specified by vcpuid
1063  * and stores it at the location given by regs.
1064  */
1065 void vcpu_regs_get(struct kvm_vm *vm,
1066         uint32_t vcpuid, struct kvm_regs *regs)
1067 {
1068         struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1069         int ret;
1070
1071         TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1072
1073         /* Get the regs. */
1074         ret = ioctl(vcpu->fd, KVM_GET_REGS, regs);
1075         TEST_ASSERT(ret == 0, "KVM_GET_REGS failed, rc: %i errno: %i",
1076                 ret, errno);
1077 }
1078
1079 /* VM VCPU Regs Set
1080  *
1081  * Input Args:
1082  *   vm - Virtual Machine
1083  *   vcpuid - VCPU ID
1084  *   regs - Values to set VCPU regs to
1085  *
1086  * Output Args: None
1087  *
1088  * Return: None
1089  *
1090  * Sets the regs of the VCPU specified by vcpuid to the values
1091  * given by regs.
1092  */
1093 void vcpu_regs_set(struct kvm_vm *vm,
1094         uint32_t vcpuid, struct kvm_regs *regs)
1095 {
1096         struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1097         int ret;
1098
1099         TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1100
1101         /* Set the regs. */
1102         ret = ioctl(vcpu->fd, KVM_SET_REGS, regs);
1103         TEST_ASSERT(ret == 0, "KVM_SET_REGS failed, rc: %i errno: %i",
1104                 ret, errno);
1105 }
1106
1107 void vcpu_events_get(struct kvm_vm *vm, uint32_t vcpuid,
1108                           struct kvm_vcpu_events *events)
1109 {
1110         struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1111         int ret;
1112
1113         TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1114
1115         /* Get the regs. */
1116         ret = ioctl(vcpu->fd, KVM_GET_VCPU_EVENTS, events);
1117         TEST_ASSERT(ret == 0, "KVM_GET_VCPU_EVENTS, failed, rc: %i errno: %i",
1118                 ret, errno);
1119 }
1120
1121 void vcpu_events_set(struct kvm_vm *vm, uint32_t vcpuid,
1122                           struct kvm_vcpu_events *events)
1123 {
1124         struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1125         int ret;
1126
1127         TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1128
1129         /* Set the regs. */
1130         ret = ioctl(vcpu->fd, KVM_SET_VCPU_EVENTS, events);
1131         TEST_ASSERT(ret == 0, "KVM_SET_VCPU_EVENTS, failed, rc: %i errno: %i",
1132                 ret, errno);
1133 }
1134
1135 /* VM VCPU Args Set
1136  *
1137  * Input Args:
1138  *   vm - Virtual Machine
1139  *   vcpuid - VCPU ID
1140  *   num - number of arguments
1141  *   ... - arguments, each of type uint64_t
1142  *
1143  * Output Args: None
1144  *
1145  * Return: None
1146  *
1147  * Sets the first num function input arguments to the values
1148  * given as variable args.  Each of the variable args is expected to
1149  * be of type uint64_t.
1150  */
1151 void vcpu_args_set(struct kvm_vm *vm, uint32_t vcpuid, unsigned int num, ...)
1152 {
1153         va_list ap;
1154         struct kvm_regs regs;
1155
1156         TEST_ASSERT(num >= 1 && num <= 6, "Unsupported number of args,\n"
1157                     "  num: %u\n",
1158                     num);
1159
1160         va_start(ap, num);
1161         vcpu_regs_get(vm, vcpuid, &regs);
1162
1163         if (num >= 1)
1164                 regs.rdi = va_arg(ap, uint64_t);
1165
1166         if (num >= 2)
1167                 regs.rsi = va_arg(ap, uint64_t);
1168
1169         if (num >= 3)
1170                 regs.rdx = va_arg(ap, uint64_t);
1171
1172         if (num >= 4)
1173                 regs.rcx = va_arg(ap, uint64_t);
1174
1175         if (num >= 5)
1176                 regs.r8 = va_arg(ap, uint64_t);
1177
1178         if (num >= 6)
1179                 regs.r9 = va_arg(ap, uint64_t);
1180
1181         vcpu_regs_set(vm, vcpuid, &regs);
1182         va_end(ap);
1183 }
1184
1185 /* VM VCPU System Regs Get
1186  *
1187  * Input Args:
1188  *   vm - Virtual Machine
1189  *   vcpuid - VCPU ID
1190  *
1191  * Output Args:
1192  *   sregs - current state of VCPU system regs
1193  *
1194  * Return: None
1195  *
1196  * Obtains the current system register state for the VCPU specified by
1197  * vcpuid and stores it at the location given by sregs.
1198  */
1199 void vcpu_sregs_get(struct kvm_vm *vm,
1200         uint32_t vcpuid, struct kvm_sregs *sregs)
1201 {
1202         struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1203         int ret;
1204
1205         TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1206
1207         /* Get the regs. */
1208         /* Get the regs. */
1209         ret = ioctl(vcpu->fd, KVM_GET_SREGS, sregs);
1210         TEST_ASSERT(ret == 0, "KVM_GET_SREGS failed, rc: %i errno: %i",
1211                 ret, errno);
1212 }
1213
1214 /* VM VCPU System Regs Set
1215  *
1216  * Input Args:
1217  *   vm - Virtual Machine
1218  *   vcpuid - VCPU ID
1219  *   sregs - Values to set VCPU system regs to
1220  *
1221  * Output Args: None
1222  *
1223  * Return: None
1224  *
1225  * Sets the system regs of the VCPU specified by vcpuid to the values
1226  * given by sregs.
1227  */
1228 void vcpu_sregs_set(struct kvm_vm *vm,
1229         uint32_t vcpuid, struct kvm_sregs *sregs)
1230 {
1231         int ret = _vcpu_sregs_set(vm, vcpuid, sregs);
1232         TEST_ASSERT(ret == 0, "KVM_RUN IOCTL failed, "
1233                 "rc: %i errno: %i", ret, errno);
1234 }
1235
1236 int _vcpu_sregs_set(struct kvm_vm *vm,
1237         uint32_t vcpuid, struct kvm_sregs *sregs)
1238 {
1239         struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1240         int ret;
1241
1242         TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1243
1244         /* Get the regs. */
1245         return ioctl(vcpu->fd, KVM_SET_SREGS, sregs);
1246 }
1247
1248 /* VCPU Ioctl
1249  *
1250  * Input Args:
1251  *   vm - Virtual Machine
1252  *   vcpuid - VCPU ID
1253  *   cmd - Ioctl number
1254  *   arg - Argument to pass to the ioctl
1255  *
1256  * Return: None
1257  *
1258  * Issues an arbitrary ioctl on a VCPU fd.
1259  */
1260 void vcpu_ioctl(struct kvm_vm *vm,
1261         uint32_t vcpuid, unsigned long cmd, void *arg)
1262 {
1263         struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1264         int ret;
1265
1266         TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1267
1268         ret = ioctl(vcpu->fd, cmd, arg);
1269         TEST_ASSERT(ret == 0, "vcpu ioctl %lu failed, rc: %i errno: %i (%s)",
1270                 cmd, ret, errno, strerror(errno));
1271 }
1272
1273 /* VM Ioctl
1274  *
1275  * Input Args:
1276  *   vm - Virtual Machine
1277  *   cmd - Ioctl number
1278  *   arg - Argument to pass to the ioctl
1279  *
1280  * Return: None
1281  *
1282  * Issues an arbitrary ioctl on a VM fd.
1283  */
1284 void vm_ioctl(struct kvm_vm *vm, unsigned long cmd, void *arg)
1285 {
1286         int ret;
1287
1288         ret = ioctl(vm->fd, cmd, arg);
1289         TEST_ASSERT(ret == 0, "vm ioctl %lu failed, rc: %i errno: %i (%s)",
1290                 cmd, ret, errno, strerror(errno));
1291 }
1292
1293 /* VM Dump
1294  *
1295  * Input Args:
1296  *   vm - Virtual Machine
1297  *   indent - Left margin indent amount
1298  *
1299  * Output Args:
1300  *   stream - Output FILE stream
1301  *
1302  * Return: None
1303  *
1304  * Dumps the current state of the VM given by vm, to the FILE stream
1305  * given by stream.
1306  */
1307 void vm_dump(FILE *stream, struct kvm_vm *vm, uint8_t indent)
1308 {
1309         struct userspace_mem_region *region;
1310         struct vcpu *vcpu;
1311
1312         fprintf(stream, "%*smode: 0x%x\n", indent, "", vm->mode);
1313         fprintf(stream, "%*sfd: %i\n", indent, "", vm->fd);
1314         fprintf(stream, "%*spage_size: 0x%x\n", indent, "", vm->page_size);
1315         fprintf(stream, "%*sMem Regions:\n", indent, "");
1316         for (region = vm->userspace_mem_region_head; region;
1317                 region = region->next) {
1318                 fprintf(stream, "%*sguest_phys: 0x%lx size: 0x%lx "
1319                         "host_virt: %p\n", indent + 2, "",
1320                         (uint64_t) region->region.guest_phys_addr,
1321                         (uint64_t) region->region.memory_size,
1322                         region->host_mem);
1323                 fprintf(stream, "%*sunused_phy_pages: ", indent + 2, "");
1324                 sparsebit_dump(stream, region->unused_phy_pages, 0);
1325         }
1326         fprintf(stream, "%*sMapped Virtual Pages:\n", indent, "");
1327         sparsebit_dump(stream, vm->vpages_mapped, indent + 2);
1328         fprintf(stream, "%*spgd_created: %u\n", indent, "",
1329                 vm->pgd_created);
1330         if (vm->pgd_created) {
1331                 fprintf(stream, "%*sVirtual Translation Tables:\n",
1332                         indent + 2, "");
1333                 virt_dump(stream, vm, indent + 4);
1334         }
1335         fprintf(stream, "%*sVCPUs:\n", indent, "");
1336         for (vcpu = vm->vcpu_head; vcpu; vcpu = vcpu->next)
1337                 vcpu_dump(stream, vm, vcpu->id, indent + 2);
1338 }
1339
1340 /* VM VCPU Dump
1341  *
1342  * Input Args:
1343  *   vm - Virtual Machine
1344  *   vcpuid - VCPU ID
1345  *   indent - Left margin indent amount
1346  *
1347  * Output Args:
1348  *   stream - Output FILE stream
1349  *
1350  * Return: None
1351  *
1352  * Dumps the current state of the VCPU specified by vcpuid, within the VM
1353  * given by vm, to the FILE stream given by stream.
1354  */
1355 void vcpu_dump(FILE *stream, struct kvm_vm *vm,
1356         uint32_t vcpuid, uint8_t indent)
1357 {
1358                 struct kvm_regs regs;
1359                 struct kvm_sregs sregs;
1360
1361                 fprintf(stream, "%*scpuid: %u\n", indent, "", vcpuid);
1362
1363                 fprintf(stream, "%*sregs:\n", indent + 2, "");
1364                 vcpu_regs_get(vm, vcpuid, &regs);
1365                 regs_dump(stream, &regs, indent + 4);
1366
1367                 fprintf(stream, "%*ssregs:\n", indent + 2, "");
1368                 vcpu_sregs_get(vm, vcpuid, &sregs);
1369                 sregs_dump(stream, &sregs, indent + 4);
1370 }
1371
1372 /* Known KVM exit reasons */
1373 static struct exit_reason {
1374         unsigned int reason;
1375         const char *name;
1376 } exit_reasons_known[] = {
1377         {KVM_EXIT_UNKNOWN, "UNKNOWN"},
1378         {KVM_EXIT_EXCEPTION, "EXCEPTION"},
1379         {KVM_EXIT_IO, "IO"},
1380         {KVM_EXIT_HYPERCALL, "HYPERCALL"},
1381         {KVM_EXIT_DEBUG, "DEBUG"},
1382         {KVM_EXIT_HLT, "HLT"},
1383         {KVM_EXIT_MMIO, "MMIO"},
1384         {KVM_EXIT_IRQ_WINDOW_OPEN, "IRQ_WINDOW_OPEN"},
1385         {KVM_EXIT_SHUTDOWN, "SHUTDOWN"},
1386         {KVM_EXIT_FAIL_ENTRY, "FAIL_ENTRY"},
1387         {KVM_EXIT_INTR, "INTR"},
1388         {KVM_EXIT_SET_TPR, "SET_TPR"},
1389         {KVM_EXIT_TPR_ACCESS, "TPR_ACCESS"},
1390         {KVM_EXIT_S390_SIEIC, "S390_SIEIC"},
1391         {KVM_EXIT_S390_RESET, "S390_RESET"},
1392         {KVM_EXIT_DCR, "DCR"},
1393         {KVM_EXIT_NMI, "NMI"},
1394         {KVM_EXIT_INTERNAL_ERROR, "INTERNAL_ERROR"},
1395         {KVM_EXIT_OSI, "OSI"},
1396         {KVM_EXIT_PAPR_HCALL, "PAPR_HCALL"},
1397 #ifdef KVM_EXIT_MEMORY_NOT_PRESENT
1398         {KVM_EXIT_MEMORY_NOT_PRESENT, "MEMORY_NOT_PRESENT"},
1399 #endif
1400 };
1401
1402 /* Exit Reason String
1403  *
1404  * Input Args:
1405  *   exit_reason - Exit reason
1406  *
1407  * Output Args: None
1408  *
1409  * Return:
1410  *   Constant string pointer describing the exit reason.
1411  *
1412  * Locates and returns a constant string that describes the KVM exit
1413  * reason given by exit_reason.  If no such string is found, a constant
1414  * string of "Unknown" is returned.
1415  */
1416 const char *exit_reason_str(unsigned int exit_reason)
1417 {
1418         unsigned int n1;
1419
1420         for (n1 = 0; n1 < ARRAY_SIZE(exit_reasons_known); n1++) {
1421                 if (exit_reason == exit_reasons_known[n1].reason)
1422                         return exit_reasons_known[n1].name;
1423         }
1424
1425         return "Unknown";
1426 }
1427
1428 /* Physical Page Allocate
1429  *
1430  * Input Args:
1431  *   vm - Virtual Machine
1432  *   paddr_min - Physical address minimum
1433  *   memslot - Memory region to allocate page from
1434  *
1435  * Output Args: None
1436  *
1437  * Return:
1438  *   Starting physical address
1439  *
1440  * Within the VM specified by vm, locates an available physical page
1441  * at or above paddr_min.  If found, the page is marked as in use
1442  * and its address is returned.  A TEST_ASSERT failure occurs if no
1443  * page is available at or above paddr_min.
1444  */
1445 vm_paddr_t vm_phy_page_alloc(struct kvm_vm *vm,
1446         vm_paddr_t paddr_min, uint32_t memslot)
1447 {
1448         struct userspace_mem_region *region;
1449         sparsebit_idx_t pg;
1450
1451         TEST_ASSERT((paddr_min % vm->page_size) == 0, "Min physical address "
1452                 "not divisible by page size.\n"
1453                 "  paddr_min: 0x%lx page_size: 0x%x",
1454                 paddr_min, vm->page_size);
1455
1456         /* Locate memory region. */
1457         region = memslot2region(vm, memslot);
1458
1459         /* Locate next available physical page at or above paddr_min. */
1460         pg = paddr_min >> vm->page_shift;
1461
1462         if (!sparsebit_is_set(region->unused_phy_pages, pg)) {
1463                 pg = sparsebit_next_set(region->unused_phy_pages, pg);
1464                 if (pg == 0) {
1465                         fprintf(stderr, "No guest physical page available, "
1466                                 "paddr_min: 0x%lx page_size: 0x%x memslot: %u",
1467                                 paddr_min, vm->page_size, memslot);
1468                         fputs("---- vm dump ----\n", stderr);
1469                         vm_dump(stderr, vm, 2);
1470                         abort();
1471                 }
1472         }
1473
1474         /* Specify page as in use and return its address. */
1475         sparsebit_clear(region->unused_phy_pages, pg);
1476
1477         return pg * vm->page_size;
1478 }
1479
1480 /* Address Guest Virtual to Host Virtual
1481  *
1482  * Input Args:
1483  *   vm - Virtual Machine
1484  *   gva - VM virtual address
1485  *
1486  * Output Args: None
1487  *
1488  * Return:
1489  *   Equivalent host virtual address
1490  */
1491 void *addr_gva2hva(struct kvm_vm *vm, vm_vaddr_t gva)
1492 {
1493         return addr_gpa2hva(vm, addr_gva2gpa(vm, gva));
1494 }