KVM: selftests: create alias mappings when using shared memory
[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 #define _GNU_SOURCE /* for program_invocation_name */
9 #include "test_util.h"
10 #include "kvm_util.h"
11 #include "kvm_util_internal.h"
12 #include "processor.h"
13
14 #include <assert.h>
15 #include <sys/mman.h>
16 #include <sys/types.h>
17 #include <sys/stat.h>
18 #include <unistd.h>
19 #include <linux/kernel.h>
20
21 #define KVM_UTIL_MIN_PFN        2
22
23 static int vcpu_mmap_sz(void);
24
25 /* Aligns x up to the next multiple of size. Size must be a power of 2. */
26 static void *align(void *x, size_t size)
27 {
28         size_t mask = size - 1;
29         TEST_ASSERT(size != 0 && !(size & (size - 1)),
30                     "size not a power of 2: %lu", size);
31         return (void *) (((size_t) x + mask) & ~mask);
32 }
33
34 /*
35  * Open KVM_DEV_PATH if available, otherwise exit the entire program.
36  *
37  * Input Args:
38  *   flags - The flags to pass when opening KVM_DEV_PATH.
39  *
40  * Return:
41  *   The opened file descriptor of /dev/kvm.
42  */
43 static int _open_kvm_dev_path_or_exit(int flags)
44 {
45         int fd;
46
47         fd = open(KVM_DEV_PATH, flags);
48         if (fd < 0) {
49                 print_skip("%s not available, is KVM loaded? (errno: %d)",
50                            KVM_DEV_PATH, errno);
51                 exit(KSFT_SKIP);
52         }
53
54         return fd;
55 }
56
57 int open_kvm_dev_path_or_exit(void)
58 {
59         return _open_kvm_dev_path_or_exit(O_RDONLY);
60 }
61
62 /*
63  * Capability
64  *
65  * Input Args:
66  *   cap - Capability
67  *
68  * Output Args: None
69  *
70  * Return:
71  *   On success, the Value corresponding to the capability (KVM_CAP_*)
72  *   specified by the value of cap.  On failure a TEST_ASSERT failure
73  *   is produced.
74  *
75  * Looks up and returns the value corresponding to the capability
76  * (KVM_CAP_*) given by cap.
77  */
78 int kvm_check_cap(long cap)
79 {
80         int ret;
81         int kvm_fd;
82
83         kvm_fd = open_kvm_dev_path_or_exit();
84         ret = ioctl(kvm_fd, KVM_CHECK_EXTENSION, cap);
85         TEST_ASSERT(ret != -1, "KVM_CHECK_EXTENSION IOCTL failed,\n"
86                 "  rc: %i errno: %i", ret, errno);
87
88         close(kvm_fd);
89
90         return ret;
91 }
92
93 /* VM Enable Capability
94  *
95  * Input Args:
96  *   vm - Virtual Machine
97  *   cap - Capability
98  *
99  * Output Args: None
100  *
101  * Return: On success, 0. On failure a TEST_ASSERT failure is produced.
102  *
103  * Enables a capability (KVM_CAP_*) on the VM.
104  */
105 int vm_enable_cap(struct kvm_vm *vm, struct kvm_enable_cap *cap)
106 {
107         int ret;
108
109         ret = ioctl(vm->fd, KVM_ENABLE_CAP, cap);
110         TEST_ASSERT(ret == 0, "KVM_ENABLE_CAP IOCTL failed,\n"
111                 "  rc: %i errno: %i", ret, errno);
112
113         return ret;
114 }
115
116 /* VCPU Enable Capability
117  *
118  * Input Args:
119  *   vm - Virtual Machine
120  *   vcpu_id - VCPU
121  *   cap - Capability
122  *
123  * Output Args: None
124  *
125  * Return: On success, 0. On failure a TEST_ASSERT failure is produced.
126  *
127  * Enables a capability (KVM_CAP_*) on the VCPU.
128  */
129 int vcpu_enable_cap(struct kvm_vm *vm, uint32_t vcpu_id,
130                     struct kvm_enable_cap *cap)
131 {
132         struct vcpu *vcpu = vcpu_find(vm, vcpu_id);
133         int r;
134
135         TEST_ASSERT(vcpu, "cannot find vcpu %d", vcpu_id);
136
137         r = ioctl(vcpu->fd, KVM_ENABLE_CAP, cap);
138         TEST_ASSERT(!r, "KVM_ENABLE_CAP vCPU ioctl failed,\n"
139                         "  rc: %i, errno: %i", r, errno);
140
141         return r;
142 }
143
144 void vm_enable_dirty_ring(struct kvm_vm *vm, uint32_t ring_size)
145 {
146         struct kvm_enable_cap cap = { 0 };
147
148         cap.cap = KVM_CAP_DIRTY_LOG_RING;
149         cap.args[0] = ring_size;
150         vm_enable_cap(vm, &cap);
151         vm->dirty_ring_size = ring_size;
152 }
153
154 static void vm_open(struct kvm_vm *vm, int perm)
155 {
156         vm->kvm_fd = _open_kvm_dev_path_or_exit(perm);
157
158         if (!kvm_check_cap(KVM_CAP_IMMEDIATE_EXIT)) {
159                 print_skip("immediate_exit not available");
160                 exit(KSFT_SKIP);
161         }
162
163         vm->fd = ioctl(vm->kvm_fd, KVM_CREATE_VM, vm->type);
164         TEST_ASSERT(vm->fd >= 0, "KVM_CREATE_VM ioctl failed, "
165                 "rc: %i errno: %i", vm->fd, errno);
166 }
167
168 const char *vm_guest_mode_string(uint32_t i)
169 {
170         static const char * const strings[] = {
171                 [VM_MODE_P52V48_4K]     = "PA-bits:52,  VA-bits:48,  4K pages",
172                 [VM_MODE_P52V48_64K]    = "PA-bits:52,  VA-bits:48, 64K pages",
173                 [VM_MODE_P48V48_4K]     = "PA-bits:48,  VA-bits:48,  4K pages",
174                 [VM_MODE_P48V48_64K]    = "PA-bits:48,  VA-bits:48, 64K pages",
175                 [VM_MODE_P40V48_4K]     = "PA-bits:40,  VA-bits:48,  4K pages",
176                 [VM_MODE_P40V48_64K]    = "PA-bits:40,  VA-bits:48, 64K pages",
177                 [VM_MODE_PXXV48_4K]     = "PA-bits:ANY, VA-bits:48,  4K pages",
178         };
179         _Static_assert(sizeof(strings)/sizeof(char *) == NUM_VM_MODES,
180                        "Missing new mode strings?");
181
182         TEST_ASSERT(i < NUM_VM_MODES, "Guest mode ID %d too big", i);
183
184         return strings[i];
185 }
186
187 const struct vm_guest_mode_params vm_guest_mode_params[] = {
188         { 52, 48,  0x1000, 12 },
189         { 52, 48, 0x10000, 16 },
190         { 48, 48,  0x1000, 12 },
191         { 48, 48, 0x10000, 16 },
192         { 40, 48,  0x1000, 12 },
193         { 40, 48, 0x10000, 16 },
194         {  0,  0,  0x1000, 12 },
195 };
196 _Static_assert(sizeof(vm_guest_mode_params)/sizeof(struct vm_guest_mode_params) == NUM_VM_MODES,
197                "Missing new mode params?");
198
199 /*
200  * VM Create
201  *
202  * Input Args:
203  *   mode - VM Mode (e.g. VM_MODE_P52V48_4K)
204  *   phy_pages - Physical memory pages
205  *   perm - permission
206  *
207  * Output Args: None
208  *
209  * Return:
210  *   Pointer to opaque structure that describes the created VM.
211  *
212  * Creates a VM with the mode specified by mode (e.g. VM_MODE_P52V48_4K).
213  * When phy_pages is non-zero, a memory region of phy_pages physical pages
214  * is created and mapped starting at guest physical address 0.  The file
215  * descriptor to control the created VM is created with the permissions
216  * given by perm (e.g. O_RDWR).
217  */
218 struct kvm_vm *vm_create(enum vm_guest_mode mode, uint64_t phy_pages, int perm)
219 {
220         struct kvm_vm *vm;
221
222         pr_debug("%s: mode='%s' pages='%ld' perm='%d'\n", __func__,
223                  vm_guest_mode_string(mode), phy_pages, perm);
224
225         vm = calloc(1, sizeof(*vm));
226         TEST_ASSERT(vm != NULL, "Insufficient Memory");
227
228         INIT_LIST_HEAD(&vm->vcpus);
229         vm->regions.gpa_tree = RB_ROOT;
230         vm->regions.hva_tree = RB_ROOT;
231         hash_init(vm->regions.slot_hash);
232
233         vm->mode = mode;
234         vm->type = 0;
235
236         vm->pa_bits = vm_guest_mode_params[mode].pa_bits;
237         vm->va_bits = vm_guest_mode_params[mode].va_bits;
238         vm->page_size = vm_guest_mode_params[mode].page_size;
239         vm->page_shift = vm_guest_mode_params[mode].page_shift;
240
241         /* Setup mode specific traits. */
242         switch (vm->mode) {
243         case VM_MODE_P52V48_4K:
244                 vm->pgtable_levels = 4;
245                 break;
246         case VM_MODE_P52V48_64K:
247                 vm->pgtable_levels = 3;
248                 break;
249         case VM_MODE_P48V48_4K:
250                 vm->pgtable_levels = 4;
251                 break;
252         case VM_MODE_P48V48_64K:
253                 vm->pgtable_levels = 3;
254                 break;
255         case VM_MODE_P40V48_4K:
256                 vm->pgtable_levels = 4;
257                 break;
258         case VM_MODE_P40V48_64K:
259                 vm->pgtable_levels = 3;
260                 break;
261         case VM_MODE_PXXV48_4K:
262 #ifdef __x86_64__
263                 kvm_get_cpu_address_width(&vm->pa_bits, &vm->va_bits);
264                 /*
265                  * Ignore KVM support for 5-level paging (vm->va_bits == 57),
266                  * it doesn't take effect unless a CR4.LA57 is set, which it
267                  * isn't for this VM_MODE.
268                  */
269                 TEST_ASSERT(vm->va_bits == 48 || vm->va_bits == 57,
270                             "Linear address width (%d bits) not supported",
271                             vm->va_bits);
272                 pr_debug("Guest physical address width detected: %d\n",
273                          vm->pa_bits);
274                 vm->pgtable_levels = 4;
275                 vm->va_bits = 48;
276 #else
277                 TEST_FAIL("VM_MODE_PXXV48_4K not supported on non-x86 platforms");
278 #endif
279                 break;
280         default:
281                 TEST_FAIL("Unknown guest mode, mode: 0x%x", mode);
282         }
283
284 #ifdef __aarch64__
285         if (vm->pa_bits != 40)
286                 vm->type = KVM_VM_TYPE_ARM_IPA_SIZE(vm->pa_bits);
287 #endif
288
289         vm_open(vm, perm);
290
291         /* Limit to VA-bit canonical virtual addresses. */
292         vm->vpages_valid = sparsebit_alloc();
293         sparsebit_set_num(vm->vpages_valid,
294                 0, (1ULL << (vm->va_bits - 1)) >> vm->page_shift);
295         sparsebit_set_num(vm->vpages_valid,
296                 (~((1ULL << (vm->va_bits - 1)) - 1)) >> vm->page_shift,
297                 (1ULL << (vm->va_bits - 1)) >> vm->page_shift);
298
299         /* Limit physical addresses to PA-bits. */
300         vm->max_gfn = ((1ULL << vm->pa_bits) >> vm->page_shift) - 1;
301
302         /* Allocate and setup memory for guest. */
303         vm->vpages_mapped = sparsebit_alloc();
304         if (phy_pages != 0)
305                 vm_userspace_mem_region_add(vm, VM_MEM_SRC_ANONYMOUS,
306                                             0, 0, phy_pages, 0);
307
308         return vm;
309 }
310
311 struct kvm_vm *vm_create_with_vcpus(enum vm_guest_mode mode, uint32_t nr_vcpus,
312                                     uint64_t extra_mem_pages, uint32_t num_percpu_pages,
313                                     void *guest_code, uint32_t vcpuids[])
314 {
315         /* The maximum page table size for a memory region will be when the
316          * smallest pages are used. Considering each page contains x page
317          * table descriptors, the total extra size for page tables (for extra
318          * N pages) will be: N/x+N/x^2+N/x^3+... which is definitely smaller
319          * than N/x*2.
320          */
321         uint64_t vcpu_pages = (DEFAULT_STACK_PGS + num_percpu_pages) * nr_vcpus;
322         uint64_t extra_pg_pages = (extra_mem_pages + vcpu_pages) / PTES_PER_MIN_PAGE * 2;
323         uint64_t pages = DEFAULT_GUEST_PHY_PAGES + extra_mem_pages + vcpu_pages + extra_pg_pages;
324         struct kvm_vm *vm;
325         int i;
326
327         TEST_ASSERT(nr_vcpus <= kvm_check_cap(KVM_CAP_MAX_VCPUS),
328                     "nr_vcpus = %d too large for host, max-vcpus = %d",
329                     nr_vcpus, kvm_check_cap(KVM_CAP_MAX_VCPUS));
330
331         pages = vm_adjust_num_guest_pages(mode, pages);
332         vm = vm_create(mode, pages, O_RDWR);
333
334         kvm_vm_elf_load(vm, program_invocation_name, 0, 0);
335
336 #ifdef __x86_64__
337         vm_create_irqchip(vm);
338 #endif
339
340         for (i = 0; i < nr_vcpus; ++i) {
341                 uint32_t vcpuid = vcpuids ? vcpuids[i] : i;
342
343                 vm_vcpu_add_default(vm, vcpuid, guest_code);
344
345 #ifdef __x86_64__
346                 vcpu_set_cpuid(vm, vcpuid, kvm_get_supported_cpuid());
347 #endif
348         }
349
350         return vm;
351 }
352
353 struct kvm_vm *vm_create_default_with_vcpus(uint32_t nr_vcpus, uint64_t extra_mem_pages,
354                                             uint32_t num_percpu_pages, void *guest_code,
355                                             uint32_t vcpuids[])
356 {
357         return vm_create_with_vcpus(VM_MODE_DEFAULT, nr_vcpus, extra_mem_pages,
358                                     num_percpu_pages, guest_code, vcpuids);
359 }
360
361 struct kvm_vm *vm_create_default(uint32_t vcpuid, uint64_t extra_mem_pages,
362                                  void *guest_code)
363 {
364         return vm_create_default_with_vcpus(1, extra_mem_pages, 0, guest_code,
365                                             (uint32_t []){ vcpuid });
366 }
367
368 /*
369  * VM Restart
370  *
371  * Input Args:
372  *   vm - VM that has been released before
373  *   perm - permission
374  *
375  * Output Args: None
376  *
377  * Reopens the file descriptors associated to the VM and reinstates the
378  * global state, such as the irqchip and the memory regions that are mapped
379  * into the guest.
380  */
381 void kvm_vm_restart(struct kvm_vm *vmp, int perm)
382 {
383         int ctr;
384         struct userspace_mem_region *region;
385
386         vm_open(vmp, perm);
387         if (vmp->has_irqchip)
388                 vm_create_irqchip(vmp);
389
390         hash_for_each(vmp->regions.slot_hash, ctr, region, slot_node) {
391                 int ret = ioctl(vmp->fd, KVM_SET_USER_MEMORY_REGION, &region->region);
392                 TEST_ASSERT(ret == 0, "KVM_SET_USER_MEMORY_REGION IOCTL failed,\n"
393                             "  rc: %i errno: %i\n"
394                             "  slot: %u flags: 0x%x\n"
395                             "  guest_phys_addr: 0x%llx size: 0x%llx",
396                             ret, errno, region->region.slot,
397                             region->region.flags,
398                             region->region.guest_phys_addr,
399                             region->region.memory_size);
400         }
401 }
402
403 void kvm_vm_get_dirty_log(struct kvm_vm *vm, int slot, void *log)
404 {
405         struct kvm_dirty_log args = { .dirty_bitmap = log, .slot = slot };
406         int ret;
407
408         ret = ioctl(vm->fd, KVM_GET_DIRTY_LOG, &args);
409         TEST_ASSERT(ret == 0, "%s: KVM_GET_DIRTY_LOG failed: %s",
410                     __func__, strerror(-ret));
411 }
412
413 void kvm_vm_clear_dirty_log(struct kvm_vm *vm, int slot, void *log,
414                             uint64_t first_page, uint32_t num_pages)
415 {
416         struct kvm_clear_dirty_log args = { .dirty_bitmap = log, .slot = slot,
417                                             .first_page = first_page,
418                                             .num_pages = num_pages };
419         int ret;
420
421         ret = ioctl(vm->fd, KVM_CLEAR_DIRTY_LOG, &args);
422         TEST_ASSERT(ret == 0, "%s: KVM_CLEAR_DIRTY_LOG failed: %s",
423                     __func__, strerror(-ret));
424 }
425
426 uint32_t kvm_vm_reset_dirty_ring(struct kvm_vm *vm)
427 {
428         return ioctl(vm->fd, KVM_RESET_DIRTY_RINGS);
429 }
430
431 /*
432  * Userspace Memory Region Find
433  *
434  * Input Args:
435  *   vm - Virtual Machine
436  *   start - Starting VM physical address
437  *   end - Ending VM physical address, inclusive.
438  *
439  * Output Args: None
440  *
441  * Return:
442  *   Pointer to overlapping region, NULL if no such region.
443  *
444  * Searches for a region with any physical memory that overlaps with
445  * any portion of the guest physical addresses from start to end
446  * inclusive.  If multiple overlapping regions exist, a pointer to any
447  * of the regions is returned.  Null is returned only when no overlapping
448  * region exists.
449  */
450 static struct userspace_mem_region *
451 userspace_mem_region_find(struct kvm_vm *vm, uint64_t start, uint64_t end)
452 {
453         struct rb_node *node;
454
455         for (node = vm->regions.gpa_tree.rb_node; node; ) {
456                 struct userspace_mem_region *region =
457                         container_of(node, struct userspace_mem_region, gpa_node);
458                 uint64_t existing_start = region->region.guest_phys_addr;
459                 uint64_t existing_end = region->region.guest_phys_addr
460                         + region->region.memory_size - 1;
461                 if (start <= existing_end && end >= existing_start)
462                         return region;
463
464                 if (start < existing_start)
465                         node = node->rb_left;
466                 else
467                         node = node->rb_right;
468         }
469
470         return NULL;
471 }
472
473 /*
474  * KVM Userspace Memory Region Find
475  *
476  * Input Args:
477  *   vm - Virtual Machine
478  *   start - Starting VM physical address
479  *   end - Ending VM physical address, inclusive.
480  *
481  * Output Args: None
482  *
483  * Return:
484  *   Pointer to overlapping region, NULL if no such region.
485  *
486  * Public interface to userspace_mem_region_find. Allows tests to look up
487  * the memslot datastructure for a given range of guest physical memory.
488  */
489 struct kvm_userspace_memory_region *
490 kvm_userspace_memory_region_find(struct kvm_vm *vm, uint64_t start,
491                                  uint64_t end)
492 {
493         struct userspace_mem_region *region;
494
495         region = userspace_mem_region_find(vm, start, end);
496         if (!region)
497                 return NULL;
498
499         return &region->region;
500 }
501
502 /*
503  * VCPU Find
504  *
505  * Input Args:
506  *   vm - Virtual Machine
507  *   vcpuid - VCPU ID
508  *
509  * Output Args: None
510  *
511  * Return:
512  *   Pointer to VCPU structure
513  *
514  * Locates a vcpu structure that describes the VCPU specified by vcpuid and
515  * returns a pointer to it.  Returns NULL if the VM doesn't contain a VCPU
516  * for the specified vcpuid.
517  */
518 struct vcpu *vcpu_find(struct kvm_vm *vm, uint32_t vcpuid)
519 {
520         struct vcpu *vcpu;
521
522         list_for_each_entry(vcpu, &vm->vcpus, list) {
523                 if (vcpu->id == vcpuid)
524                         return vcpu;
525         }
526
527         return NULL;
528 }
529
530 /*
531  * VM VCPU Remove
532  *
533  * Input Args:
534  *   vcpu - VCPU to remove
535  *
536  * Output Args: None
537  *
538  * Return: None, TEST_ASSERT failures for all error conditions
539  *
540  * Removes a vCPU from a VM and frees its resources.
541  */
542 static void vm_vcpu_rm(struct kvm_vm *vm, struct vcpu *vcpu)
543 {
544         int ret;
545
546         if (vcpu->dirty_gfns) {
547                 ret = munmap(vcpu->dirty_gfns, vm->dirty_ring_size);
548                 TEST_ASSERT(ret == 0, "munmap of VCPU dirty ring failed, "
549                             "rc: %i errno: %i", ret, errno);
550                 vcpu->dirty_gfns = NULL;
551         }
552
553         ret = munmap(vcpu->state, vcpu_mmap_sz());
554         TEST_ASSERT(ret == 0, "munmap of VCPU fd failed, rc: %i "
555                 "errno: %i", ret, errno);
556         ret = close(vcpu->fd);
557         TEST_ASSERT(ret == 0, "Close of VCPU fd failed, rc: %i "
558                 "errno: %i", ret, errno);
559
560         list_del(&vcpu->list);
561         free(vcpu);
562 }
563
564 void kvm_vm_release(struct kvm_vm *vmp)
565 {
566         struct vcpu *vcpu, *tmp;
567         int ret;
568
569         list_for_each_entry_safe(vcpu, tmp, &vmp->vcpus, list)
570                 vm_vcpu_rm(vmp, vcpu);
571
572         ret = close(vmp->fd);
573         TEST_ASSERT(ret == 0, "Close of vm fd failed,\n"
574                 "  vmp->fd: %i rc: %i errno: %i", vmp->fd, ret, errno);
575
576         ret = close(vmp->kvm_fd);
577         TEST_ASSERT(ret == 0, "Close of /dev/kvm fd failed,\n"
578                 "  vmp->kvm_fd: %i rc: %i errno: %i", vmp->kvm_fd, ret, errno);
579 }
580
581 static void __vm_mem_region_delete(struct kvm_vm *vm,
582                                    struct userspace_mem_region *region,
583                                    bool unlink)
584 {
585         int ret;
586
587         if (unlink) {
588                 rb_erase(&region->gpa_node, &vm->regions.gpa_tree);
589                 rb_erase(&region->hva_node, &vm->regions.hva_tree);
590                 hash_del(&region->slot_node);
591         }
592
593         region->region.memory_size = 0;
594         ret = ioctl(vm->fd, KVM_SET_USER_MEMORY_REGION, &region->region);
595         TEST_ASSERT(ret == 0, "KVM_SET_USER_MEMORY_REGION IOCTL failed, "
596                     "rc: %i errno: %i", ret, errno);
597
598         sparsebit_free(&region->unused_phy_pages);
599         ret = munmap(region->mmap_start, region->mmap_size);
600         TEST_ASSERT(ret == 0, "munmap failed, rc: %i errno: %i", ret, errno);
601
602         free(region);
603 }
604
605 /*
606  * Destroys and frees the VM pointed to by vmp.
607  */
608 void kvm_vm_free(struct kvm_vm *vmp)
609 {
610         int ctr;
611         struct hlist_node *node;
612         struct userspace_mem_region *region;
613
614         if (vmp == NULL)
615                 return;
616
617         /* Free userspace_mem_regions. */
618         hash_for_each_safe(vmp->regions.slot_hash, ctr, node, region, slot_node)
619                 __vm_mem_region_delete(vmp, region, false);
620
621         /* Free sparsebit arrays. */
622         sparsebit_free(&vmp->vpages_valid);
623         sparsebit_free(&vmp->vpages_mapped);
624
625         kvm_vm_release(vmp);
626
627         /* Free the structure describing the VM. */
628         free(vmp);
629 }
630
631 /*
632  * Memory Compare, host virtual to guest virtual
633  *
634  * Input Args:
635  *   hva - Starting host virtual address
636  *   vm - Virtual Machine
637  *   gva - Starting guest virtual address
638  *   len - number of bytes to compare
639  *
640  * Output Args: None
641  *
642  * Input/Output Args: None
643  *
644  * Return:
645  *   Returns 0 if the bytes starting at hva for a length of len
646  *   are equal the guest virtual bytes starting at gva.  Returns
647  *   a value < 0, if bytes at hva are less than those at gva.
648  *   Otherwise a value > 0 is returned.
649  *
650  * Compares the bytes starting at the host virtual address hva, for
651  * a length of len, to the guest bytes starting at the guest virtual
652  * address given by gva.
653  */
654 int kvm_memcmp_hva_gva(void *hva, struct kvm_vm *vm, vm_vaddr_t gva, size_t len)
655 {
656         size_t amt;
657
658         /*
659          * Compare a batch of bytes until either a match is found
660          * or all the bytes have been compared.
661          */
662         for (uintptr_t offset = 0; offset < len; offset += amt) {
663                 uintptr_t ptr1 = (uintptr_t)hva + offset;
664
665                 /*
666                  * Determine host address for guest virtual address
667                  * at offset.
668                  */
669                 uintptr_t ptr2 = (uintptr_t)addr_gva2hva(vm, gva + offset);
670
671                 /*
672                  * Determine amount to compare on this pass.
673                  * Don't allow the comparsion to cross a page boundary.
674                  */
675                 amt = len - offset;
676                 if ((ptr1 >> vm->page_shift) != ((ptr1 + amt) >> vm->page_shift))
677                         amt = vm->page_size - (ptr1 % vm->page_size);
678                 if ((ptr2 >> vm->page_shift) != ((ptr2 + amt) >> vm->page_shift))
679                         amt = vm->page_size - (ptr2 % vm->page_size);
680
681                 assert((ptr1 >> vm->page_shift) == ((ptr1 + amt - 1) >> vm->page_shift));
682                 assert((ptr2 >> vm->page_shift) == ((ptr2 + amt - 1) >> vm->page_shift));
683
684                 /*
685                  * Perform the comparison.  If there is a difference
686                  * return that result to the caller, otherwise need
687                  * to continue on looking for a mismatch.
688                  */
689                 int ret = memcmp((void *)ptr1, (void *)ptr2, amt);
690                 if (ret != 0)
691                         return ret;
692         }
693
694         /*
695          * No mismatch found.  Let the caller know the two memory
696          * areas are equal.
697          */
698         return 0;
699 }
700
701 static void vm_userspace_mem_region_gpa_insert(struct rb_root *gpa_tree,
702                                                struct userspace_mem_region *region)
703 {
704         struct rb_node **cur, *parent;
705
706         for (cur = &gpa_tree->rb_node, parent = NULL; *cur; ) {
707                 struct userspace_mem_region *cregion;
708
709                 cregion = container_of(*cur, typeof(*cregion), gpa_node);
710                 parent = *cur;
711                 if (region->region.guest_phys_addr <
712                     cregion->region.guest_phys_addr)
713                         cur = &(*cur)->rb_left;
714                 else {
715                         TEST_ASSERT(region->region.guest_phys_addr !=
716                                     cregion->region.guest_phys_addr,
717                                     "Duplicate GPA in region tree");
718
719                         cur = &(*cur)->rb_right;
720                 }
721         }
722
723         rb_link_node(&region->gpa_node, parent, cur);
724         rb_insert_color(&region->gpa_node, gpa_tree);
725 }
726
727 static void vm_userspace_mem_region_hva_insert(struct rb_root *hva_tree,
728                                                struct userspace_mem_region *region)
729 {
730         struct rb_node **cur, *parent;
731
732         for (cur = &hva_tree->rb_node, parent = NULL; *cur; ) {
733                 struct userspace_mem_region *cregion;
734
735                 cregion = container_of(*cur, typeof(*cregion), hva_node);
736                 parent = *cur;
737                 if (region->host_mem < cregion->host_mem)
738                         cur = &(*cur)->rb_left;
739                 else {
740                         TEST_ASSERT(region->host_mem !=
741                                     cregion->host_mem,
742                                     "Duplicate HVA in region tree");
743
744                         cur = &(*cur)->rb_right;
745                 }
746         }
747
748         rb_link_node(&region->hva_node, parent, cur);
749         rb_insert_color(&region->hva_node, hva_tree);
750 }
751
752 /*
753  * VM Userspace Memory Region Add
754  *
755  * Input Args:
756  *   vm - Virtual Machine
757  *   src_type - Storage source for this region.
758  *              NULL to use anonymous memory.
759  *   guest_paddr - Starting guest physical address
760  *   slot - KVM region slot
761  *   npages - Number of physical pages
762  *   flags - KVM memory region flags (e.g. KVM_MEM_LOG_DIRTY_PAGES)
763  *
764  * Output Args: None
765  *
766  * Return: None
767  *
768  * Allocates a memory area of the number of pages specified by npages
769  * and maps it to the VM specified by vm, at a starting physical address
770  * given by guest_paddr.  The region is created with a KVM region slot
771  * given by slot, which must be unique and < KVM_MEM_SLOTS_NUM.  The
772  * region is created with the flags given by flags.
773  */
774 void vm_userspace_mem_region_add(struct kvm_vm *vm,
775         enum vm_mem_backing_src_type src_type,
776         uint64_t guest_paddr, uint32_t slot, uint64_t npages,
777         uint32_t flags)
778 {
779         int ret;
780         struct userspace_mem_region *region;
781         size_t backing_src_pagesz = get_backing_src_pagesz(src_type);
782         size_t alignment;
783
784         TEST_ASSERT(vm_adjust_num_guest_pages(vm->mode, npages) == npages,
785                 "Number of guest pages is not compatible with the host. "
786                 "Try npages=%d", vm_adjust_num_guest_pages(vm->mode, npages));
787
788         TEST_ASSERT((guest_paddr % vm->page_size) == 0, "Guest physical "
789                 "address not on a page boundary.\n"
790                 "  guest_paddr: 0x%lx vm->page_size: 0x%x",
791                 guest_paddr, vm->page_size);
792         TEST_ASSERT((((guest_paddr >> vm->page_shift) + npages) - 1)
793                 <= vm->max_gfn, "Physical range beyond maximum "
794                 "supported physical address,\n"
795                 "  guest_paddr: 0x%lx npages: 0x%lx\n"
796                 "  vm->max_gfn: 0x%lx vm->page_size: 0x%x",
797                 guest_paddr, npages, vm->max_gfn, vm->page_size);
798
799         /*
800          * Confirm a mem region with an overlapping address doesn't
801          * already exist.
802          */
803         region = (struct userspace_mem_region *) userspace_mem_region_find(
804                 vm, guest_paddr, (guest_paddr + npages * vm->page_size) - 1);
805         if (region != NULL)
806                 TEST_FAIL("overlapping userspace_mem_region already "
807                         "exists\n"
808                         "  requested guest_paddr: 0x%lx npages: 0x%lx "
809                         "page_size: 0x%x\n"
810                         "  existing guest_paddr: 0x%lx size: 0x%lx",
811                         guest_paddr, npages, vm->page_size,
812                         (uint64_t) region->region.guest_phys_addr,
813                         (uint64_t) region->region.memory_size);
814
815         /* Confirm no region with the requested slot already exists. */
816         hash_for_each_possible(vm->regions.slot_hash, region, slot_node,
817                                slot) {
818                 if (region->region.slot != slot)
819                         continue;
820
821                 TEST_FAIL("A mem region with the requested slot "
822                         "already exists.\n"
823                         "  requested slot: %u paddr: 0x%lx npages: 0x%lx\n"
824                         "  existing slot: %u paddr: 0x%lx size: 0x%lx",
825                         slot, guest_paddr, npages,
826                         region->region.slot,
827                         (uint64_t) region->region.guest_phys_addr,
828                         (uint64_t) region->region.memory_size);
829         }
830
831         /* Allocate and initialize new mem region structure. */
832         region = calloc(1, sizeof(*region));
833         TEST_ASSERT(region != NULL, "Insufficient Memory");
834         region->mmap_size = npages * vm->page_size;
835
836 #ifdef __s390x__
837         /* On s390x, the host address must be aligned to 1M (due to PGSTEs) */
838         alignment = 0x100000;
839 #else
840         alignment = 1;
841 #endif
842
843         if (src_type == VM_MEM_SRC_ANONYMOUS_THP)
844                 alignment = max(backing_src_pagesz, alignment);
845
846         /* Add enough memory to align up if necessary */
847         if (alignment > 1)
848                 region->mmap_size += alignment;
849
850         region->fd = -1;
851         if (src_type == VM_MEM_SRC_SHMEM) {
852                 region->fd = memfd_create("kvm_selftest", MFD_CLOEXEC);
853                 TEST_ASSERT(region->fd != -1,
854                             "memfd_create failed, errno: %i", errno);
855
856                 ret = ftruncate(region->fd, region->mmap_size);
857                 TEST_ASSERT(ret == 0, "ftruncate failed, errno: %i", errno);
858
859                 ret = fallocate(region->fd,
860                                 FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE, 0,
861                                 region->mmap_size);
862                 TEST_ASSERT(ret == 0, "fallocate failed, errno: %i", errno);
863         }
864
865         region->mmap_start = mmap(NULL, region->mmap_size,
866                                   PROT_READ | PROT_WRITE,
867                                   vm_mem_backing_src_alias(src_type)->flag,
868                                   region->fd, 0);
869         TEST_ASSERT(region->mmap_start != MAP_FAILED,
870                     "test_malloc failed, mmap_start: %p errno: %i",
871                     region->mmap_start, errno);
872
873         /* Align host address */
874         region->host_mem = align(region->mmap_start, alignment);
875
876         /* As needed perform madvise */
877         if ((src_type == VM_MEM_SRC_ANONYMOUS ||
878              src_type == VM_MEM_SRC_ANONYMOUS_THP) && thp_configured()) {
879                 ret = madvise(region->host_mem, npages * vm->page_size,
880                               src_type == VM_MEM_SRC_ANONYMOUS ? MADV_NOHUGEPAGE : MADV_HUGEPAGE);
881                 TEST_ASSERT(ret == 0, "madvise failed, addr: %p length: 0x%lx src_type: %s",
882                             region->host_mem, npages * vm->page_size,
883                             vm_mem_backing_src_alias(src_type)->name);
884         }
885
886         region->unused_phy_pages = sparsebit_alloc();
887         sparsebit_set_num(region->unused_phy_pages,
888                 guest_paddr >> vm->page_shift, npages);
889         region->region.slot = slot;
890         region->region.flags = flags;
891         region->region.guest_phys_addr = guest_paddr;
892         region->region.memory_size = npages * vm->page_size;
893         region->region.userspace_addr = (uintptr_t) region->host_mem;
894         ret = ioctl(vm->fd, KVM_SET_USER_MEMORY_REGION, &region->region);
895         TEST_ASSERT(ret == 0, "KVM_SET_USER_MEMORY_REGION IOCTL failed,\n"
896                 "  rc: %i errno: %i\n"
897                 "  slot: %u flags: 0x%x\n"
898                 "  guest_phys_addr: 0x%lx size: 0x%lx",
899                 ret, errno, slot, flags,
900                 guest_paddr, (uint64_t) region->region.memory_size);
901
902         /* Add to quick lookup data structures */
903         vm_userspace_mem_region_gpa_insert(&vm->regions.gpa_tree, region);
904         vm_userspace_mem_region_hva_insert(&vm->regions.hva_tree, region);
905         hash_add(vm->regions.slot_hash, &region->slot_node, slot);
906
907         /* If shared memory, create an alias. */
908         if (region->fd >= 0) {
909                 region->mmap_alias = mmap(NULL, region->mmap_size,
910                                           PROT_READ | PROT_WRITE,
911                                           vm_mem_backing_src_alias(src_type)->flag,
912                                           region->fd, 0);
913                 TEST_ASSERT(region->mmap_alias != MAP_FAILED,
914                             "mmap of alias failed, errno: %i", errno);
915
916                 /* Align host alias address */
917                 region->host_alias = align(region->mmap_alias, alignment);
918         }
919 }
920
921 /*
922  * Memslot to region
923  *
924  * Input Args:
925  *   vm - Virtual Machine
926  *   memslot - KVM memory slot ID
927  *
928  * Output Args: None
929  *
930  * Return:
931  *   Pointer to memory region structure that describe memory region
932  *   using kvm memory slot ID given by memslot.  TEST_ASSERT failure
933  *   on error (e.g. currently no memory region using memslot as a KVM
934  *   memory slot ID).
935  */
936 struct userspace_mem_region *
937 memslot2region(struct kvm_vm *vm, uint32_t memslot)
938 {
939         struct userspace_mem_region *region;
940
941         hash_for_each_possible(vm->regions.slot_hash, region, slot_node,
942                                memslot)
943                 if (region->region.slot == memslot)
944                         return region;
945
946         fprintf(stderr, "No mem region with the requested slot found,\n"
947                 "  requested slot: %u\n", memslot);
948         fputs("---- vm dump ----\n", stderr);
949         vm_dump(stderr, vm, 2);
950         TEST_FAIL("Mem region not found");
951         return NULL;
952 }
953
954 /*
955  * VM Memory Region Flags Set
956  *
957  * Input Args:
958  *   vm - Virtual Machine
959  *   flags - Starting guest physical address
960  *
961  * Output Args: None
962  *
963  * Return: None
964  *
965  * Sets the flags of the memory region specified by the value of slot,
966  * to the values given by flags.
967  */
968 void vm_mem_region_set_flags(struct kvm_vm *vm, uint32_t slot, uint32_t flags)
969 {
970         int ret;
971         struct userspace_mem_region *region;
972
973         region = memslot2region(vm, slot);
974
975         region->region.flags = flags;
976
977         ret = ioctl(vm->fd, KVM_SET_USER_MEMORY_REGION, &region->region);
978
979         TEST_ASSERT(ret == 0, "KVM_SET_USER_MEMORY_REGION IOCTL failed,\n"
980                 "  rc: %i errno: %i slot: %u flags: 0x%x",
981                 ret, errno, slot, flags);
982 }
983
984 /*
985  * VM Memory Region Move
986  *
987  * Input Args:
988  *   vm - Virtual Machine
989  *   slot - Slot of the memory region to move
990  *   new_gpa - Starting guest physical address
991  *
992  * Output Args: None
993  *
994  * Return: None
995  *
996  * Change the gpa of a memory region.
997  */
998 void vm_mem_region_move(struct kvm_vm *vm, uint32_t slot, uint64_t new_gpa)
999 {
1000         struct userspace_mem_region *region;
1001         int ret;
1002
1003         region = memslot2region(vm, slot);
1004
1005         region->region.guest_phys_addr = new_gpa;
1006
1007         ret = ioctl(vm->fd, KVM_SET_USER_MEMORY_REGION, &region->region);
1008
1009         TEST_ASSERT(!ret, "KVM_SET_USER_MEMORY_REGION failed\n"
1010                     "ret: %i errno: %i slot: %u new_gpa: 0x%lx",
1011                     ret, errno, slot, new_gpa);
1012 }
1013
1014 /*
1015  * VM Memory Region Delete
1016  *
1017  * Input Args:
1018  *   vm - Virtual Machine
1019  *   slot - Slot of the memory region to delete
1020  *
1021  * Output Args: None
1022  *
1023  * Return: None
1024  *
1025  * Delete a memory region.
1026  */
1027 void vm_mem_region_delete(struct kvm_vm *vm, uint32_t slot)
1028 {
1029         __vm_mem_region_delete(vm, memslot2region(vm, slot), true);
1030 }
1031
1032 /*
1033  * VCPU mmap Size
1034  *
1035  * Input Args: None
1036  *
1037  * Output Args: None
1038  *
1039  * Return:
1040  *   Size of VCPU state
1041  *
1042  * Returns the size of the structure pointed to by the return value
1043  * of vcpu_state().
1044  */
1045 static int vcpu_mmap_sz(void)
1046 {
1047         int dev_fd, ret;
1048
1049         dev_fd = open_kvm_dev_path_or_exit();
1050
1051         ret = ioctl(dev_fd, KVM_GET_VCPU_MMAP_SIZE, NULL);
1052         TEST_ASSERT(ret >= sizeof(struct kvm_run),
1053                 "%s KVM_GET_VCPU_MMAP_SIZE ioctl failed, rc: %i errno: %i",
1054                 __func__, ret, errno);
1055
1056         close(dev_fd);
1057
1058         return ret;
1059 }
1060
1061 /*
1062  * VM VCPU Add
1063  *
1064  * Input Args:
1065  *   vm - Virtual Machine
1066  *   vcpuid - VCPU ID
1067  *
1068  * Output Args: None
1069  *
1070  * Return: None
1071  *
1072  * Adds a virtual CPU to the VM specified by vm with the ID given by vcpuid.
1073  * No additional VCPU setup is done.
1074  */
1075 void vm_vcpu_add(struct kvm_vm *vm, uint32_t vcpuid)
1076 {
1077         struct vcpu *vcpu;
1078
1079         /* Confirm a vcpu with the specified id doesn't already exist. */
1080         vcpu = vcpu_find(vm, vcpuid);
1081         if (vcpu != NULL)
1082                 TEST_FAIL("vcpu with the specified id "
1083                         "already exists,\n"
1084                         "  requested vcpuid: %u\n"
1085                         "  existing vcpuid: %u state: %p",
1086                         vcpuid, vcpu->id, vcpu->state);
1087
1088         /* Allocate and initialize new vcpu structure. */
1089         vcpu = calloc(1, sizeof(*vcpu));
1090         TEST_ASSERT(vcpu != NULL, "Insufficient Memory");
1091         vcpu->id = vcpuid;
1092         vcpu->fd = ioctl(vm->fd, KVM_CREATE_VCPU, vcpuid);
1093         TEST_ASSERT(vcpu->fd >= 0, "KVM_CREATE_VCPU failed, rc: %i errno: %i",
1094                 vcpu->fd, errno);
1095
1096         TEST_ASSERT(vcpu_mmap_sz() >= sizeof(*vcpu->state), "vcpu mmap size "
1097                 "smaller than expected, vcpu_mmap_sz: %i expected_min: %zi",
1098                 vcpu_mmap_sz(), sizeof(*vcpu->state));
1099         vcpu->state = (struct kvm_run *) mmap(NULL, vcpu_mmap_sz(),
1100                 PROT_READ | PROT_WRITE, MAP_SHARED, vcpu->fd, 0);
1101         TEST_ASSERT(vcpu->state != MAP_FAILED, "mmap vcpu_state failed, "
1102                 "vcpu id: %u errno: %i", vcpuid, errno);
1103
1104         /* Add to linked-list of VCPUs. */
1105         list_add(&vcpu->list, &vm->vcpus);
1106 }
1107
1108 /*
1109  * VM Virtual Address Unused Gap
1110  *
1111  * Input Args:
1112  *   vm - Virtual Machine
1113  *   sz - Size (bytes)
1114  *   vaddr_min - Minimum Virtual Address
1115  *
1116  * Output Args: None
1117  *
1118  * Return:
1119  *   Lowest virtual address at or below vaddr_min, with at least
1120  *   sz unused bytes.  TEST_ASSERT failure if no area of at least
1121  *   size sz is available.
1122  *
1123  * Within the VM specified by vm, locates the lowest starting virtual
1124  * address >= vaddr_min, that has at least sz unallocated bytes.  A
1125  * TEST_ASSERT failure occurs for invalid input or no area of at least
1126  * sz unallocated bytes >= vaddr_min is available.
1127  */
1128 static vm_vaddr_t vm_vaddr_unused_gap(struct kvm_vm *vm, size_t sz,
1129                                       vm_vaddr_t vaddr_min)
1130 {
1131         uint64_t pages = (sz + vm->page_size - 1) >> vm->page_shift;
1132
1133         /* Determine lowest permitted virtual page index. */
1134         uint64_t pgidx_start = (vaddr_min + vm->page_size - 1) >> vm->page_shift;
1135         if ((pgidx_start * vm->page_size) < vaddr_min)
1136                 goto no_va_found;
1137
1138         /* Loop over section with enough valid virtual page indexes. */
1139         if (!sparsebit_is_set_num(vm->vpages_valid,
1140                 pgidx_start, pages))
1141                 pgidx_start = sparsebit_next_set_num(vm->vpages_valid,
1142                         pgidx_start, pages);
1143         do {
1144                 /*
1145                  * Are there enough unused virtual pages available at
1146                  * the currently proposed starting virtual page index.
1147                  * If not, adjust proposed starting index to next
1148                  * possible.
1149                  */
1150                 if (sparsebit_is_clear_num(vm->vpages_mapped,
1151                         pgidx_start, pages))
1152                         goto va_found;
1153                 pgidx_start = sparsebit_next_clear_num(vm->vpages_mapped,
1154                         pgidx_start, pages);
1155                 if (pgidx_start == 0)
1156                         goto no_va_found;
1157
1158                 /*
1159                  * If needed, adjust proposed starting virtual address,
1160                  * to next range of valid virtual addresses.
1161                  */
1162                 if (!sparsebit_is_set_num(vm->vpages_valid,
1163                         pgidx_start, pages)) {
1164                         pgidx_start = sparsebit_next_set_num(
1165                                 vm->vpages_valid, pgidx_start, pages);
1166                         if (pgidx_start == 0)
1167                                 goto no_va_found;
1168                 }
1169         } while (pgidx_start != 0);
1170
1171 no_va_found:
1172         TEST_FAIL("No vaddr of specified pages available, pages: 0x%lx", pages);
1173
1174         /* NOT REACHED */
1175         return -1;
1176
1177 va_found:
1178         TEST_ASSERT(sparsebit_is_set_num(vm->vpages_valid,
1179                 pgidx_start, pages),
1180                 "Unexpected, invalid virtual page index range,\n"
1181                 "  pgidx_start: 0x%lx\n"
1182                 "  pages: 0x%lx",
1183                 pgidx_start, pages);
1184         TEST_ASSERT(sparsebit_is_clear_num(vm->vpages_mapped,
1185                 pgidx_start, pages),
1186                 "Unexpected, pages already mapped,\n"
1187                 "  pgidx_start: 0x%lx\n"
1188                 "  pages: 0x%lx",
1189                 pgidx_start, pages);
1190
1191         return pgidx_start * vm->page_size;
1192 }
1193
1194 /*
1195  * VM Virtual Address Allocate
1196  *
1197  * Input Args:
1198  *   vm - Virtual Machine
1199  *   sz - Size in bytes
1200  *   vaddr_min - Minimum starting virtual address
1201  *   data_memslot - Memory region slot for data pages
1202  *   pgd_memslot - Memory region slot for new virtual translation tables
1203  *
1204  * Output Args: None
1205  *
1206  * Return:
1207  *   Starting guest virtual address
1208  *
1209  * Allocates at least sz bytes within the virtual address space of the vm
1210  * given by vm.  The allocated bytes are mapped to a virtual address >=
1211  * the address given by vaddr_min.  Note that each allocation uses a
1212  * a unique set of pages, with the minimum real allocation being at least
1213  * a page.
1214  */
1215 vm_vaddr_t vm_vaddr_alloc(struct kvm_vm *vm, size_t sz, vm_vaddr_t vaddr_min,
1216                           uint32_t data_memslot, uint32_t pgd_memslot)
1217 {
1218         uint64_t pages = (sz >> vm->page_shift) + ((sz % vm->page_size) != 0);
1219
1220         virt_pgd_alloc(vm, pgd_memslot);
1221         vm_paddr_t paddr = vm_phy_pages_alloc(vm, pages,
1222                                               KVM_UTIL_MIN_PFN * vm->page_size,
1223                                               data_memslot);
1224
1225         /*
1226          * Find an unused range of virtual page addresses of at least
1227          * pages in length.
1228          */
1229         vm_vaddr_t vaddr_start = vm_vaddr_unused_gap(vm, sz, vaddr_min);
1230
1231         /* Map the virtual pages. */
1232         for (vm_vaddr_t vaddr = vaddr_start; pages > 0;
1233                 pages--, vaddr += vm->page_size, paddr += vm->page_size) {
1234
1235                 virt_pg_map(vm, vaddr, paddr, pgd_memslot);
1236
1237                 sparsebit_set(vm->vpages_mapped,
1238                         vaddr >> vm->page_shift);
1239         }
1240
1241         return vaddr_start;
1242 }
1243
1244 /*
1245  * Map a range of VM virtual address to the VM's physical address
1246  *
1247  * Input Args:
1248  *   vm - Virtual Machine
1249  *   vaddr - Virtuall address to map
1250  *   paddr - VM Physical Address
1251  *   npages - The number of pages to map
1252  *   pgd_memslot - Memory region slot for new virtual translation tables
1253  *
1254  * Output Args: None
1255  *
1256  * Return: None
1257  *
1258  * Within the VM given by @vm, creates a virtual translation for
1259  * @npages starting at @vaddr to the page range starting at @paddr.
1260  */
1261 void virt_map(struct kvm_vm *vm, uint64_t vaddr, uint64_t paddr,
1262               unsigned int npages, uint32_t pgd_memslot)
1263 {
1264         size_t page_size = vm->page_size;
1265         size_t size = npages * page_size;
1266
1267         TEST_ASSERT(vaddr + size > vaddr, "Vaddr overflow");
1268         TEST_ASSERT(paddr + size > paddr, "Paddr overflow");
1269
1270         while (npages--) {
1271                 virt_pg_map(vm, vaddr, paddr, pgd_memslot);
1272                 vaddr += page_size;
1273                 paddr += page_size;
1274         }
1275 }
1276
1277 /*
1278  * Address VM Physical to Host Virtual
1279  *
1280  * Input Args:
1281  *   vm - Virtual Machine
1282  *   gpa - VM physical address
1283  *
1284  * Output Args: None
1285  *
1286  * Return:
1287  *   Equivalent host virtual address
1288  *
1289  * Locates the memory region containing the VM physical address given
1290  * by gpa, within the VM given by vm.  When found, the host virtual
1291  * address providing the memory to the vm physical address is returned.
1292  * A TEST_ASSERT failure occurs if no region containing gpa exists.
1293  */
1294 void *addr_gpa2hva(struct kvm_vm *vm, vm_paddr_t gpa)
1295 {
1296         struct userspace_mem_region *region;
1297
1298         region = userspace_mem_region_find(vm, gpa, gpa);
1299         if (!region) {
1300                 TEST_FAIL("No vm physical memory at 0x%lx", gpa);
1301                 return NULL;
1302         }
1303
1304         return (void *)((uintptr_t)region->host_mem
1305                 + (gpa - region->region.guest_phys_addr));
1306 }
1307
1308 /*
1309  * Address Host Virtual to VM Physical
1310  *
1311  * Input Args:
1312  *   vm - Virtual Machine
1313  *   hva - Host virtual address
1314  *
1315  * Output Args: None
1316  *
1317  * Return:
1318  *   Equivalent VM physical address
1319  *
1320  * Locates the memory region containing the host virtual address given
1321  * by hva, within the VM given by vm.  When found, the equivalent
1322  * VM physical address is returned. A TEST_ASSERT failure occurs if no
1323  * region containing hva exists.
1324  */
1325 vm_paddr_t addr_hva2gpa(struct kvm_vm *vm, void *hva)
1326 {
1327         struct rb_node *node;
1328
1329         for (node = vm->regions.hva_tree.rb_node; node; ) {
1330                 struct userspace_mem_region *region =
1331                         container_of(node, struct userspace_mem_region, hva_node);
1332
1333                 if (hva >= region->host_mem) {
1334                         if (hva <= (region->host_mem
1335                                 + region->region.memory_size - 1))
1336                                 return (vm_paddr_t)((uintptr_t)
1337                                         region->region.guest_phys_addr
1338                                         + (hva - (uintptr_t)region->host_mem));
1339
1340                         node = node->rb_right;
1341                 } else
1342                         node = node->rb_left;
1343         }
1344
1345         TEST_FAIL("No mapping to a guest physical address, hva: %p", hva);
1346         return -1;
1347 }
1348
1349 /*
1350  * Address VM physical to Host Virtual *alias*.
1351  *
1352  * Input Args:
1353  *   vm - Virtual Machine
1354  *   gpa - VM physical address
1355  *
1356  * Output Args: None
1357  *
1358  * Return:
1359  *   Equivalent address within the host virtual *alias* area, or NULL
1360  *   (without failing the test) if the guest memory is not shared (so
1361  *   no alias exists).
1362  *
1363  * When vm_create() and related functions are called with a shared memory
1364  * src_type, we also create a writable, shared alias mapping of the
1365  * underlying guest memory. This allows the host to manipulate guest memory
1366  * without mapping that memory in the guest's address space. And, for
1367  * userfaultfd-based demand paging, we can do so without triggering userfaults.
1368  */
1369 void *addr_gpa2alias(struct kvm_vm *vm, vm_paddr_t gpa)
1370 {
1371         struct userspace_mem_region *region;
1372         uintptr_t offset;
1373
1374         region = userspace_mem_region_find(vm, gpa, gpa);
1375         if (!region)
1376                 return NULL;
1377
1378         if (!region->host_alias)
1379                 return NULL;
1380
1381         offset = gpa - region->region.guest_phys_addr;
1382         return (void *) ((uintptr_t) region->host_alias + offset);
1383 }
1384
1385 /*
1386  * VM Create IRQ Chip
1387  *
1388  * Input Args:
1389  *   vm - Virtual Machine
1390  *
1391  * Output Args: None
1392  *
1393  * Return: None
1394  *
1395  * Creates an interrupt controller chip for the VM specified by vm.
1396  */
1397 void vm_create_irqchip(struct kvm_vm *vm)
1398 {
1399         int ret;
1400
1401         ret = ioctl(vm->fd, KVM_CREATE_IRQCHIP, 0);
1402         TEST_ASSERT(ret == 0, "KVM_CREATE_IRQCHIP IOCTL failed, "
1403                 "rc: %i errno: %i", ret, errno);
1404
1405         vm->has_irqchip = true;
1406 }
1407
1408 /*
1409  * VM VCPU State
1410  *
1411  * Input Args:
1412  *   vm - Virtual Machine
1413  *   vcpuid - VCPU ID
1414  *
1415  * Output Args: None
1416  *
1417  * Return:
1418  *   Pointer to structure that describes the state of the VCPU.
1419  *
1420  * Locates and returns a pointer to a structure that describes the
1421  * state of the VCPU with the given vcpuid.
1422  */
1423 struct kvm_run *vcpu_state(struct kvm_vm *vm, uint32_t vcpuid)
1424 {
1425         struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1426         TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1427
1428         return vcpu->state;
1429 }
1430
1431 /*
1432  * VM VCPU Run
1433  *
1434  * Input Args:
1435  *   vm - Virtual Machine
1436  *   vcpuid - VCPU ID
1437  *
1438  * Output Args: None
1439  *
1440  * Return: None
1441  *
1442  * Switch to executing the code for the VCPU given by vcpuid, within the VM
1443  * given by vm.
1444  */
1445 void vcpu_run(struct kvm_vm *vm, uint32_t vcpuid)
1446 {
1447         int ret = _vcpu_run(vm, vcpuid);
1448         TEST_ASSERT(ret == 0, "KVM_RUN IOCTL failed, "
1449                 "rc: %i errno: %i", ret, errno);
1450 }
1451
1452 int _vcpu_run(struct kvm_vm *vm, uint32_t vcpuid)
1453 {
1454         struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1455         int rc;
1456
1457         TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1458         do {
1459                 rc = ioctl(vcpu->fd, KVM_RUN, NULL);
1460         } while (rc == -1 && errno == EINTR);
1461
1462         assert_on_unhandled_exception(vm, vcpuid);
1463
1464         return rc;
1465 }
1466
1467 int vcpu_get_fd(struct kvm_vm *vm, uint32_t vcpuid)
1468 {
1469         struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1470
1471         TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1472
1473         return vcpu->fd;
1474 }
1475
1476 void vcpu_run_complete_io(struct kvm_vm *vm, uint32_t vcpuid)
1477 {
1478         struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1479         int ret;
1480
1481         TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1482
1483         vcpu->state->immediate_exit = 1;
1484         ret = ioctl(vcpu->fd, KVM_RUN, NULL);
1485         vcpu->state->immediate_exit = 0;
1486
1487         TEST_ASSERT(ret == -1 && errno == EINTR,
1488                     "KVM_RUN IOCTL didn't exit immediately, rc: %i, errno: %i",
1489                     ret, errno);
1490 }
1491
1492 void vcpu_set_guest_debug(struct kvm_vm *vm, uint32_t vcpuid,
1493                           struct kvm_guest_debug *debug)
1494 {
1495         struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1496         int ret = ioctl(vcpu->fd, KVM_SET_GUEST_DEBUG, debug);
1497
1498         TEST_ASSERT(ret == 0, "KVM_SET_GUEST_DEBUG failed: %d", ret);
1499 }
1500
1501 /*
1502  * VM VCPU Set MP State
1503  *
1504  * Input Args:
1505  *   vm - Virtual Machine
1506  *   vcpuid - VCPU ID
1507  *   mp_state - mp_state to be set
1508  *
1509  * Output Args: None
1510  *
1511  * Return: None
1512  *
1513  * Sets the MP state of the VCPU given by vcpuid, to the state given
1514  * by mp_state.
1515  */
1516 void vcpu_set_mp_state(struct kvm_vm *vm, uint32_t vcpuid,
1517                        struct kvm_mp_state *mp_state)
1518 {
1519         struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1520         int ret;
1521
1522         TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1523
1524         ret = ioctl(vcpu->fd, KVM_SET_MP_STATE, mp_state);
1525         TEST_ASSERT(ret == 0, "KVM_SET_MP_STATE IOCTL failed, "
1526                 "rc: %i errno: %i", ret, errno);
1527 }
1528
1529 /*
1530  * VM VCPU Get Reg List
1531  *
1532  * Input Args:
1533  *   vm - Virtual Machine
1534  *   vcpuid - VCPU ID
1535  *
1536  * Output Args:
1537  *   None
1538  *
1539  * Return:
1540  *   A pointer to an allocated struct kvm_reg_list
1541  *
1542  * Get the list of guest registers which are supported for
1543  * KVM_GET_ONE_REG/KVM_SET_ONE_REG calls
1544  */
1545 struct kvm_reg_list *vcpu_get_reg_list(struct kvm_vm *vm, uint32_t vcpuid)
1546 {
1547         struct kvm_reg_list reg_list_n = { .n = 0 }, *reg_list;
1548         int ret;
1549
1550         ret = _vcpu_ioctl(vm, vcpuid, KVM_GET_REG_LIST, &reg_list_n);
1551         TEST_ASSERT(ret == -1 && errno == E2BIG, "KVM_GET_REG_LIST n=0");
1552         reg_list = calloc(1, sizeof(*reg_list) + reg_list_n.n * sizeof(__u64));
1553         reg_list->n = reg_list_n.n;
1554         vcpu_ioctl(vm, vcpuid, KVM_GET_REG_LIST, reg_list);
1555         return reg_list;
1556 }
1557
1558 /*
1559  * VM VCPU Regs Get
1560  *
1561  * Input Args:
1562  *   vm - Virtual Machine
1563  *   vcpuid - VCPU ID
1564  *
1565  * Output Args:
1566  *   regs - current state of VCPU regs
1567  *
1568  * Return: None
1569  *
1570  * Obtains the current register state for the VCPU specified by vcpuid
1571  * and stores it at the location given by regs.
1572  */
1573 void vcpu_regs_get(struct kvm_vm *vm, uint32_t vcpuid, struct kvm_regs *regs)
1574 {
1575         struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1576         int ret;
1577
1578         TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1579
1580         ret = ioctl(vcpu->fd, KVM_GET_REGS, regs);
1581         TEST_ASSERT(ret == 0, "KVM_GET_REGS failed, rc: %i errno: %i",
1582                 ret, errno);
1583 }
1584
1585 /*
1586  * VM VCPU Regs Set
1587  *
1588  * Input Args:
1589  *   vm - Virtual Machine
1590  *   vcpuid - VCPU ID
1591  *   regs - Values to set VCPU regs to
1592  *
1593  * Output Args: None
1594  *
1595  * Return: None
1596  *
1597  * Sets the regs of the VCPU specified by vcpuid to the values
1598  * given by regs.
1599  */
1600 void vcpu_regs_set(struct kvm_vm *vm, uint32_t vcpuid, struct kvm_regs *regs)
1601 {
1602         struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1603         int ret;
1604
1605         TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1606
1607         ret = ioctl(vcpu->fd, KVM_SET_REGS, regs);
1608         TEST_ASSERT(ret == 0, "KVM_SET_REGS failed, rc: %i errno: %i",
1609                 ret, errno);
1610 }
1611
1612 #ifdef __KVM_HAVE_VCPU_EVENTS
1613 void vcpu_events_get(struct kvm_vm *vm, uint32_t vcpuid,
1614                      struct kvm_vcpu_events *events)
1615 {
1616         struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1617         int ret;
1618
1619         TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1620
1621         ret = ioctl(vcpu->fd, KVM_GET_VCPU_EVENTS, events);
1622         TEST_ASSERT(ret == 0, "KVM_GET_VCPU_EVENTS, failed, rc: %i errno: %i",
1623                 ret, errno);
1624 }
1625
1626 void vcpu_events_set(struct kvm_vm *vm, uint32_t vcpuid,
1627                      struct kvm_vcpu_events *events)
1628 {
1629         struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1630         int ret;
1631
1632         TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1633
1634         ret = ioctl(vcpu->fd, KVM_SET_VCPU_EVENTS, events);
1635         TEST_ASSERT(ret == 0, "KVM_SET_VCPU_EVENTS, failed, rc: %i errno: %i",
1636                 ret, errno);
1637 }
1638 #endif
1639
1640 #ifdef __x86_64__
1641 void vcpu_nested_state_get(struct kvm_vm *vm, uint32_t vcpuid,
1642                            struct kvm_nested_state *state)
1643 {
1644         struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1645         int ret;
1646
1647         TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1648
1649         ret = ioctl(vcpu->fd, KVM_GET_NESTED_STATE, state);
1650         TEST_ASSERT(ret == 0,
1651                 "KVM_SET_NESTED_STATE failed, ret: %i errno: %i",
1652                 ret, errno);
1653 }
1654
1655 int vcpu_nested_state_set(struct kvm_vm *vm, uint32_t vcpuid,
1656                           struct kvm_nested_state *state, bool ignore_error)
1657 {
1658         struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1659         int ret;
1660
1661         TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1662
1663         ret = ioctl(vcpu->fd, KVM_SET_NESTED_STATE, state);
1664         if (!ignore_error) {
1665                 TEST_ASSERT(ret == 0,
1666                         "KVM_SET_NESTED_STATE failed, ret: %i errno: %i",
1667                         ret, errno);
1668         }
1669
1670         return ret;
1671 }
1672 #endif
1673
1674 /*
1675  * VM VCPU System Regs Get
1676  *
1677  * Input Args:
1678  *   vm - Virtual Machine
1679  *   vcpuid - VCPU ID
1680  *
1681  * Output Args:
1682  *   sregs - current state of VCPU system regs
1683  *
1684  * Return: None
1685  *
1686  * Obtains the current system register state for the VCPU specified by
1687  * vcpuid and stores it at the location given by sregs.
1688  */
1689 void vcpu_sregs_get(struct kvm_vm *vm, uint32_t vcpuid, struct kvm_sregs *sregs)
1690 {
1691         struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1692         int ret;
1693
1694         TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1695
1696         ret = ioctl(vcpu->fd, KVM_GET_SREGS, sregs);
1697         TEST_ASSERT(ret == 0, "KVM_GET_SREGS failed, rc: %i errno: %i",
1698                 ret, errno);
1699 }
1700
1701 /*
1702  * VM VCPU System Regs Set
1703  *
1704  * Input Args:
1705  *   vm - Virtual Machine
1706  *   vcpuid - VCPU ID
1707  *   sregs - Values to set VCPU system regs to
1708  *
1709  * Output Args: None
1710  *
1711  * Return: None
1712  *
1713  * Sets the system regs of the VCPU specified by vcpuid to the values
1714  * given by sregs.
1715  */
1716 void vcpu_sregs_set(struct kvm_vm *vm, uint32_t vcpuid, struct kvm_sregs *sregs)
1717 {
1718         int ret = _vcpu_sregs_set(vm, vcpuid, sregs);
1719         TEST_ASSERT(ret == 0, "KVM_RUN IOCTL failed, "
1720                 "rc: %i errno: %i", ret, errno);
1721 }
1722
1723 int _vcpu_sregs_set(struct kvm_vm *vm, uint32_t vcpuid, struct kvm_sregs *sregs)
1724 {
1725         struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1726
1727         TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1728
1729         return ioctl(vcpu->fd, KVM_SET_SREGS, sregs);
1730 }
1731
1732 void vcpu_fpu_get(struct kvm_vm *vm, uint32_t vcpuid, struct kvm_fpu *fpu)
1733 {
1734         int ret;
1735
1736         ret = _vcpu_ioctl(vm, vcpuid, KVM_GET_FPU, fpu);
1737         TEST_ASSERT(ret == 0, "KVM_GET_FPU failed, rc: %i errno: %i (%s)",
1738                     ret, errno, strerror(errno));
1739 }
1740
1741 void vcpu_fpu_set(struct kvm_vm *vm, uint32_t vcpuid, struct kvm_fpu *fpu)
1742 {
1743         int ret;
1744
1745         ret = _vcpu_ioctl(vm, vcpuid, KVM_SET_FPU, fpu);
1746         TEST_ASSERT(ret == 0, "KVM_SET_FPU failed, rc: %i errno: %i (%s)",
1747                     ret, errno, strerror(errno));
1748 }
1749
1750 void vcpu_get_reg(struct kvm_vm *vm, uint32_t vcpuid, struct kvm_one_reg *reg)
1751 {
1752         int ret;
1753
1754         ret = _vcpu_ioctl(vm, vcpuid, KVM_GET_ONE_REG, reg);
1755         TEST_ASSERT(ret == 0, "KVM_GET_ONE_REG failed, rc: %i errno: %i (%s)",
1756                     ret, errno, strerror(errno));
1757 }
1758
1759 void vcpu_set_reg(struct kvm_vm *vm, uint32_t vcpuid, struct kvm_one_reg *reg)
1760 {
1761         int ret;
1762
1763         ret = _vcpu_ioctl(vm, vcpuid, KVM_SET_ONE_REG, reg);
1764         TEST_ASSERT(ret == 0, "KVM_SET_ONE_REG failed, rc: %i errno: %i (%s)",
1765                     ret, errno, strerror(errno));
1766 }
1767
1768 /*
1769  * VCPU Ioctl
1770  *
1771  * Input Args:
1772  *   vm - Virtual Machine
1773  *   vcpuid - VCPU ID
1774  *   cmd - Ioctl number
1775  *   arg - Argument to pass to the ioctl
1776  *
1777  * Return: None
1778  *
1779  * Issues an arbitrary ioctl on a VCPU fd.
1780  */
1781 void vcpu_ioctl(struct kvm_vm *vm, uint32_t vcpuid,
1782                 unsigned long cmd, void *arg)
1783 {
1784         int ret;
1785
1786         ret = _vcpu_ioctl(vm, vcpuid, cmd, arg);
1787         TEST_ASSERT(ret == 0, "vcpu ioctl %lu failed, rc: %i errno: %i (%s)",
1788                 cmd, ret, errno, strerror(errno));
1789 }
1790
1791 int _vcpu_ioctl(struct kvm_vm *vm, uint32_t vcpuid,
1792                 unsigned long cmd, void *arg)
1793 {
1794         struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1795         int ret;
1796
1797         TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1798
1799         ret = ioctl(vcpu->fd, cmd, arg);
1800
1801         return ret;
1802 }
1803
1804 void *vcpu_map_dirty_ring(struct kvm_vm *vm, uint32_t vcpuid)
1805 {
1806         struct vcpu *vcpu;
1807         uint32_t size = vm->dirty_ring_size;
1808
1809         TEST_ASSERT(size > 0, "Should enable dirty ring first");
1810
1811         vcpu = vcpu_find(vm, vcpuid);
1812
1813         TEST_ASSERT(vcpu, "Cannot find vcpu %u", vcpuid);
1814
1815         if (!vcpu->dirty_gfns) {
1816                 void *addr;
1817
1818                 addr = mmap(NULL, size, PROT_READ,
1819                             MAP_PRIVATE, vcpu->fd,
1820                             vm->page_size * KVM_DIRTY_LOG_PAGE_OFFSET);
1821                 TEST_ASSERT(addr == MAP_FAILED, "Dirty ring mapped private");
1822
1823                 addr = mmap(NULL, size, PROT_READ | PROT_EXEC,
1824                             MAP_PRIVATE, vcpu->fd,
1825                             vm->page_size * KVM_DIRTY_LOG_PAGE_OFFSET);
1826                 TEST_ASSERT(addr == MAP_FAILED, "Dirty ring mapped exec");
1827
1828                 addr = mmap(NULL, size, PROT_READ | PROT_WRITE,
1829                             MAP_SHARED, vcpu->fd,
1830                             vm->page_size * KVM_DIRTY_LOG_PAGE_OFFSET);
1831                 TEST_ASSERT(addr != MAP_FAILED, "Dirty ring map failed");
1832
1833                 vcpu->dirty_gfns = addr;
1834                 vcpu->dirty_gfns_count = size / sizeof(struct kvm_dirty_gfn);
1835         }
1836
1837         return vcpu->dirty_gfns;
1838 }
1839
1840 /*
1841  * VM Ioctl
1842  *
1843  * Input Args:
1844  *   vm - Virtual Machine
1845  *   cmd - Ioctl number
1846  *   arg - Argument to pass to the ioctl
1847  *
1848  * Return: None
1849  *
1850  * Issues an arbitrary ioctl on a VM fd.
1851  */
1852 void vm_ioctl(struct kvm_vm *vm, unsigned long cmd, void *arg)
1853 {
1854         int ret;
1855
1856         ret = _vm_ioctl(vm, cmd, arg);
1857         TEST_ASSERT(ret == 0, "vm ioctl %lu failed, rc: %i errno: %i (%s)",
1858                 cmd, ret, errno, strerror(errno));
1859 }
1860
1861 int _vm_ioctl(struct kvm_vm *vm, unsigned long cmd, void *arg)
1862 {
1863         return ioctl(vm->fd, cmd, arg);
1864 }
1865
1866 /*
1867  * KVM system ioctl
1868  *
1869  * Input Args:
1870  *   vm - Virtual Machine
1871  *   cmd - Ioctl number
1872  *   arg - Argument to pass to the ioctl
1873  *
1874  * Return: None
1875  *
1876  * Issues an arbitrary ioctl on a KVM fd.
1877  */
1878 void kvm_ioctl(struct kvm_vm *vm, unsigned long cmd, void *arg)
1879 {
1880         int ret;
1881
1882         ret = ioctl(vm->kvm_fd, cmd, arg);
1883         TEST_ASSERT(ret == 0, "KVM ioctl %lu failed, rc: %i errno: %i (%s)",
1884                 cmd, ret, errno, strerror(errno));
1885 }
1886
1887 int _kvm_ioctl(struct kvm_vm *vm, unsigned long cmd, void *arg)
1888 {
1889         return ioctl(vm->kvm_fd, cmd, arg);
1890 }
1891
1892 /*
1893  * Device Ioctl
1894  */
1895
1896 int _kvm_device_check_attr(int dev_fd, uint32_t group, uint64_t attr)
1897 {
1898         struct kvm_device_attr attribute = {
1899                 .group = group,
1900                 .attr = attr,
1901                 .flags = 0,
1902         };
1903
1904         return ioctl(dev_fd, KVM_HAS_DEVICE_ATTR, &attribute);
1905 }
1906
1907 int kvm_device_check_attr(int dev_fd, uint32_t group, uint64_t attr)
1908 {
1909         int ret = _kvm_device_check_attr(dev_fd, group, attr);
1910
1911         TEST_ASSERT(ret >= 0, "KVM_HAS_DEVICE_ATTR failed, rc: %i errno: %i", ret, errno);
1912         return ret;
1913 }
1914
1915 int _kvm_create_device(struct kvm_vm *vm, uint64_t type, bool test, int *fd)
1916 {
1917         struct kvm_create_device create_dev;
1918         int ret;
1919
1920         create_dev.type = type;
1921         create_dev.fd = -1;
1922         create_dev.flags = test ? KVM_CREATE_DEVICE_TEST : 0;
1923         ret = ioctl(vm_get_fd(vm), KVM_CREATE_DEVICE, &create_dev);
1924         *fd = create_dev.fd;
1925         return ret;
1926 }
1927
1928 int kvm_create_device(struct kvm_vm *vm, uint64_t type, bool test)
1929 {
1930         int fd, ret;
1931
1932         ret = _kvm_create_device(vm, type, test, &fd);
1933
1934         if (!test) {
1935                 TEST_ASSERT(ret >= 0,
1936                             "KVM_CREATE_DEVICE IOCTL failed, rc: %i errno: %i", ret, errno);
1937                 return fd;
1938         }
1939         return ret;
1940 }
1941
1942 int _kvm_device_access(int dev_fd, uint32_t group, uint64_t attr,
1943                       void *val, bool write)
1944 {
1945         struct kvm_device_attr kvmattr = {
1946                 .group = group,
1947                 .attr = attr,
1948                 .flags = 0,
1949                 .addr = (uintptr_t)val,
1950         };
1951         int ret;
1952
1953         ret = ioctl(dev_fd, write ? KVM_SET_DEVICE_ATTR : KVM_GET_DEVICE_ATTR,
1954                     &kvmattr);
1955         return ret;
1956 }
1957
1958 int kvm_device_access(int dev_fd, uint32_t group, uint64_t attr,
1959                       void *val, bool write)
1960 {
1961         int ret = _kvm_device_access(dev_fd, group, attr, val, write);
1962
1963         TEST_ASSERT(ret >= 0, "KVM_SET|GET_DEVICE_ATTR IOCTL failed, rc: %i errno: %i", ret, errno);
1964         return ret;
1965 }
1966
1967 /*
1968  * VM Dump
1969  *
1970  * Input Args:
1971  *   vm - Virtual Machine
1972  *   indent - Left margin indent amount
1973  *
1974  * Output Args:
1975  *   stream - Output FILE stream
1976  *
1977  * Return: None
1978  *
1979  * Dumps the current state of the VM given by vm, to the FILE stream
1980  * given by stream.
1981  */
1982 void vm_dump(FILE *stream, struct kvm_vm *vm, uint8_t indent)
1983 {
1984         int ctr;
1985         struct userspace_mem_region *region;
1986         struct vcpu *vcpu;
1987
1988         fprintf(stream, "%*smode: 0x%x\n", indent, "", vm->mode);
1989         fprintf(stream, "%*sfd: %i\n", indent, "", vm->fd);
1990         fprintf(stream, "%*spage_size: 0x%x\n", indent, "", vm->page_size);
1991         fprintf(stream, "%*sMem Regions:\n", indent, "");
1992         hash_for_each(vm->regions.slot_hash, ctr, region, slot_node) {
1993                 fprintf(stream, "%*sguest_phys: 0x%lx size: 0x%lx "
1994                         "host_virt: %p\n", indent + 2, "",
1995                         (uint64_t) region->region.guest_phys_addr,
1996                         (uint64_t) region->region.memory_size,
1997                         region->host_mem);
1998                 fprintf(stream, "%*sunused_phy_pages: ", indent + 2, "");
1999                 sparsebit_dump(stream, region->unused_phy_pages, 0);
2000         }
2001         fprintf(stream, "%*sMapped Virtual Pages:\n", indent, "");
2002         sparsebit_dump(stream, vm->vpages_mapped, indent + 2);
2003         fprintf(stream, "%*spgd_created: %u\n", indent, "",
2004                 vm->pgd_created);
2005         if (vm->pgd_created) {
2006                 fprintf(stream, "%*sVirtual Translation Tables:\n",
2007                         indent + 2, "");
2008                 virt_dump(stream, vm, indent + 4);
2009         }
2010         fprintf(stream, "%*sVCPUs:\n", indent, "");
2011         list_for_each_entry(vcpu, &vm->vcpus, list)
2012                 vcpu_dump(stream, vm, vcpu->id, indent + 2);
2013 }
2014
2015 /* Known KVM exit reasons */
2016 static struct exit_reason {
2017         unsigned int reason;
2018         const char *name;
2019 } exit_reasons_known[] = {
2020         {KVM_EXIT_UNKNOWN, "UNKNOWN"},
2021         {KVM_EXIT_EXCEPTION, "EXCEPTION"},
2022         {KVM_EXIT_IO, "IO"},
2023         {KVM_EXIT_HYPERCALL, "HYPERCALL"},
2024         {KVM_EXIT_DEBUG, "DEBUG"},
2025         {KVM_EXIT_HLT, "HLT"},
2026         {KVM_EXIT_MMIO, "MMIO"},
2027         {KVM_EXIT_IRQ_WINDOW_OPEN, "IRQ_WINDOW_OPEN"},
2028         {KVM_EXIT_SHUTDOWN, "SHUTDOWN"},
2029         {KVM_EXIT_FAIL_ENTRY, "FAIL_ENTRY"},
2030         {KVM_EXIT_INTR, "INTR"},
2031         {KVM_EXIT_SET_TPR, "SET_TPR"},
2032         {KVM_EXIT_TPR_ACCESS, "TPR_ACCESS"},
2033         {KVM_EXIT_S390_SIEIC, "S390_SIEIC"},
2034         {KVM_EXIT_S390_RESET, "S390_RESET"},
2035         {KVM_EXIT_DCR, "DCR"},
2036         {KVM_EXIT_NMI, "NMI"},
2037         {KVM_EXIT_INTERNAL_ERROR, "INTERNAL_ERROR"},
2038         {KVM_EXIT_OSI, "OSI"},
2039         {KVM_EXIT_PAPR_HCALL, "PAPR_HCALL"},
2040         {KVM_EXIT_DIRTY_RING_FULL, "DIRTY_RING_FULL"},
2041         {KVM_EXIT_X86_RDMSR, "RDMSR"},
2042         {KVM_EXIT_X86_WRMSR, "WRMSR"},
2043         {KVM_EXIT_XEN, "XEN"},
2044 #ifdef KVM_EXIT_MEMORY_NOT_PRESENT
2045         {KVM_EXIT_MEMORY_NOT_PRESENT, "MEMORY_NOT_PRESENT"},
2046 #endif
2047 };
2048
2049 /*
2050  * Exit Reason String
2051  *
2052  * Input Args:
2053  *   exit_reason - Exit reason
2054  *
2055  * Output Args: None
2056  *
2057  * Return:
2058  *   Constant string pointer describing the exit reason.
2059  *
2060  * Locates and returns a constant string that describes the KVM exit
2061  * reason given by exit_reason.  If no such string is found, a constant
2062  * string of "Unknown" is returned.
2063  */
2064 const char *exit_reason_str(unsigned int exit_reason)
2065 {
2066         unsigned int n1;
2067
2068         for (n1 = 0; n1 < ARRAY_SIZE(exit_reasons_known); n1++) {
2069                 if (exit_reason == exit_reasons_known[n1].reason)
2070                         return exit_reasons_known[n1].name;
2071         }
2072
2073         return "Unknown";
2074 }
2075
2076 /*
2077  * Physical Contiguous Page Allocator
2078  *
2079  * Input Args:
2080  *   vm - Virtual Machine
2081  *   num - number of pages
2082  *   paddr_min - Physical address minimum
2083  *   memslot - Memory region to allocate page from
2084  *
2085  * Output Args: None
2086  *
2087  * Return:
2088  *   Starting physical address
2089  *
2090  * Within the VM specified by vm, locates a range of available physical
2091  * pages at or above paddr_min. If found, the pages are marked as in use
2092  * and their base address is returned. A TEST_ASSERT failure occurs if
2093  * not enough pages are available at or above paddr_min.
2094  */
2095 vm_paddr_t vm_phy_pages_alloc(struct kvm_vm *vm, size_t num,
2096                               vm_paddr_t paddr_min, uint32_t memslot)
2097 {
2098         struct userspace_mem_region *region;
2099         sparsebit_idx_t pg, base;
2100
2101         TEST_ASSERT(num > 0, "Must allocate at least one page");
2102
2103         TEST_ASSERT((paddr_min % vm->page_size) == 0, "Min physical address "
2104                 "not divisible by page size.\n"
2105                 "  paddr_min: 0x%lx page_size: 0x%x",
2106                 paddr_min, vm->page_size);
2107
2108         region = memslot2region(vm, memslot);
2109         base = pg = paddr_min >> vm->page_shift;
2110
2111         do {
2112                 for (; pg < base + num; ++pg) {
2113                         if (!sparsebit_is_set(region->unused_phy_pages, pg)) {
2114                                 base = pg = sparsebit_next_set(region->unused_phy_pages, pg);
2115                                 break;
2116                         }
2117                 }
2118         } while (pg && pg != base + num);
2119
2120         if (pg == 0) {
2121                 fprintf(stderr, "No guest physical page available, "
2122                         "paddr_min: 0x%lx page_size: 0x%x memslot: %u\n",
2123                         paddr_min, vm->page_size, memslot);
2124                 fputs("---- vm dump ----\n", stderr);
2125                 vm_dump(stderr, vm, 2);
2126                 abort();
2127         }
2128
2129         for (pg = base; pg < base + num; ++pg)
2130                 sparsebit_clear(region->unused_phy_pages, pg);
2131
2132         return base * vm->page_size;
2133 }
2134
2135 vm_paddr_t vm_phy_page_alloc(struct kvm_vm *vm, vm_paddr_t paddr_min,
2136                              uint32_t memslot)
2137 {
2138         return vm_phy_pages_alloc(vm, 1, paddr_min, memslot);
2139 }
2140
2141 /*
2142  * Address Guest Virtual to Host Virtual
2143  *
2144  * Input Args:
2145  *   vm - Virtual Machine
2146  *   gva - VM virtual address
2147  *
2148  * Output Args: None
2149  *
2150  * Return:
2151  *   Equivalent host virtual address
2152  */
2153 void *addr_gva2hva(struct kvm_vm *vm, vm_vaddr_t gva)
2154 {
2155         return addr_gpa2hva(vm, addr_gva2gpa(vm, gva));
2156 }
2157
2158 /*
2159  * Is Unrestricted Guest
2160  *
2161  * Input Args:
2162  *   vm - Virtual Machine
2163  *
2164  * Output Args: None
2165  *
2166  * Return: True if the unrestricted guest is set to 'Y', otherwise return false.
2167  *
2168  * Check if the unrestricted guest flag is enabled.
2169  */
2170 bool vm_is_unrestricted_guest(struct kvm_vm *vm)
2171 {
2172         char val = 'N';
2173         size_t count;
2174         FILE *f;
2175
2176         if (vm == NULL) {
2177                 /* Ensure that the KVM vendor-specific module is loaded. */
2178                 close(open_kvm_dev_path_or_exit());
2179         }
2180
2181         f = fopen("/sys/module/kvm_intel/parameters/unrestricted_guest", "r");
2182         if (f) {
2183                 count = fread(&val, sizeof(char), 1, f);
2184                 TEST_ASSERT(count == 1, "Unable to read from param file.");
2185                 fclose(f);
2186         }
2187
2188         return val == 'Y';
2189 }
2190
2191 unsigned int vm_get_page_size(struct kvm_vm *vm)
2192 {
2193         return vm->page_size;
2194 }
2195
2196 unsigned int vm_get_page_shift(struct kvm_vm *vm)
2197 {
2198         return vm->page_shift;
2199 }
2200
2201 uint64_t vm_get_max_gfn(struct kvm_vm *vm)
2202 {
2203         return vm->max_gfn;
2204 }
2205
2206 int vm_get_fd(struct kvm_vm *vm)
2207 {
2208         return vm->fd;
2209 }
2210
2211 static unsigned int vm_calc_num_pages(unsigned int num_pages,
2212                                       unsigned int page_shift,
2213                                       unsigned int new_page_shift,
2214                                       bool ceil)
2215 {
2216         unsigned int n = 1 << (new_page_shift - page_shift);
2217
2218         if (page_shift >= new_page_shift)
2219                 return num_pages * (1 << (page_shift - new_page_shift));
2220
2221         return num_pages / n + !!(ceil && num_pages % n);
2222 }
2223
2224 static inline int getpageshift(void)
2225 {
2226         return __builtin_ffs(getpagesize()) - 1;
2227 }
2228
2229 unsigned int
2230 vm_num_host_pages(enum vm_guest_mode mode, unsigned int num_guest_pages)
2231 {
2232         return vm_calc_num_pages(num_guest_pages,
2233                                  vm_guest_mode_params[mode].page_shift,
2234                                  getpageshift(), true);
2235 }
2236
2237 unsigned int
2238 vm_num_guest_pages(enum vm_guest_mode mode, unsigned int num_host_pages)
2239 {
2240         return vm_calc_num_pages(num_host_pages, getpageshift(),
2241                                  vm_guest_mode_params[mode].page_shift, false);
2242 }
2243
2244 unsigned int vm_calc_num_guest_pages(enum vm_guest_mode mode, size_t size)
2245 {
2246         unsigned int n;
2247         n = DIV_ROUND_UP(size, vm_guest_mode_params[mode].page_size);
2248         return vm_adjust_num_guest_pages(mode, n);
2249 }