OSDN Git Service

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