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