491be22b410c863c9bf26301e96bd362a4655f4c
[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->mmap_start = mmap(NULL, region->mmap_size,
851                                   PROT_READ | PROT_WRITE,
852                                   vm_mem_backing_src_alias(src_type)->flag,
853                                   -1, 0);
854         TEST_ASSERT(region->mmap_start != MAP_FAILED,
855                     "test_malloc failed, mmap_start: %p errno: %i",
856                     region->mmap_start, errno);
857
858         /* Align host address */
859         region->host_mem = align(region->mmap_start, alignment);
860
861         /* As needed perform madvise */
862         if ((src_type == VM_MEM_SRC_ANONYMOUS ||
863              src_type == VM_MEM_SRC_ANONYMOUS_THP) && thp_configured()) {
864                 ret = madvise(region->host_mem, npages * vm->page_size,
865                               src_type == VM_MEM_SRC_ANONYMOUS ? MADV_NOHUGEPAGE : MADV_HUGEPAGE);
866                 TEST_ASSERT(ret == 0, "madvise failed, addr: %p length: 0x%lx src_type: %s",
867                             region->host_mem, npages * vm->page_size,
868                             vm_mem_backing_src_alias(src_type)->name);
869         }
870
871         region->unused_phy_pages = sparsebit_alloc();
872         sparsebit_set_num(region->unused_phy_pages,
873                 guest_paddr >> vm->page_shift, npages);
874         region->region.slot = slot;
875         region->region.flags = flags;
876         region->region.guest_phys_addr = guest_paddr;
877         region->region.memory_size = npages * vm->page_size;
878         region->region.userspace_addr = (uintptr_t) region->host_mem;
879         ret = ioctl(vm->fd, KVM_SET_USER_MEMORY_REGION, &region->region);
880         TEST_ASSERT(ret == 0, "KVM_SET_USER_MEMORY_REGION IOCTL failed,\n"
881                 "  rc: %i errno: %i\n"
882                 "  slot: %u flags: 0x%x\n"
883                 "  guest_phys_addr: 0x%lx size: 0x%lx",
884                 ret, errno, slot, flags,
885                 guest_paddr, (uint64_t) region->region.memory_size);
886
887         /* Add to quick lookup data structures */
888         vm_userspace_mem_region_gpa_insert(&vm->regions.gpa_tree, region);
889         vm_userspace_mem_region_hva_insert(&vm->regions.hva_tree, region);
890         hash_add(vm->regions.slot_hash, &region->slot_node, slot);
891 }
892
893 /*
894  * Memslot to region
895  *
896  * Input Args:
897  *   vm - Virtual Machine
898  *   memslot - KVM memory slot ID
899  *
900  * Output Args: None
901  *
902  * Return:
903  *   Pointer to memory region structure that describe memory region
904  *   using kvm memory slot ID given by memslot.  TEST_ASSERT failure
905  *   on error (e.g. currently no memory region using memslot as a KVM
906  *   memory slot ID).
907  */
908 struct userspace_mem_region *
909 memslot2region(struct kvm_vm *vm, uint32_t memslot)
910 {
911         struct userspace_mem_region *region;
912
913         hash_for_each_possible(vm->regions.slot_hash, region, slot_node,
914                                memslot)
915                 if (region->region.slot == memslot)
916                         return region;
917
918         fprintf(stderr, "No mem region with the requested slot found,\n"
919                 "  requested slot: %u\n", memslot);
920         fputs("---- vm dump ----\n", stderr);
921         vm_dump(stderr, vm, 2);
922         TEST_FAIL("Mem region not found");
923         return NULL;
924 }
925
926 /*
927  * VM Memory Region Flags Set
928  *
929  * Input Args:
930  *   vm - Virtual Machine
931  *   flags - Starting guest physical address
932  *
933  * Output Args: None
934  *
935  * Return: None
936  *
937  * Sets the flags of the memory region specified by the value of slot,
938  * to the values given by flags.
939  */
940 void vm_mem_region_set_flags(struct kvm_vm *vm, uint32_t slot, uint32_t flags)
941 {
942         int ret;
943         struct userspace_mem_region *region;
944
945         region = memslot2region(vm, slot);
946
947         region->region.flags = flags;
948
949         ret = ioctl(vm->fd, KVM_SET_USER_MEMORY_REGION, &region->region);
950
951         TEST_ASSERT(ret == 0, "KVM_SET_USER_MEMORY_REGION IOCTL failed,\n"
952                 "  rc: %i errno: %i slot: %u flags: 0x%x",
953                 ret, errno, slot, flags);
954 }
955
956 /*
957  * VM Memory Region Move
958  *
959  * Input Args:
960  *   vm - Virtual Machine
961  *   slot - Slot of the memory region to move
962  *   new_gpa - Starting guest physical address
963  *
964  * Output Args: None
965  *
966  * Return: None
967  *
968  * Change the gpa of a memory region.
969  */
970 void vm_mem_region_move(struct kvm_vm *vm, uint32_t slot, uint64_t new_gpa)
971 {
972         struct userspace_mem_region *region;
973         int ret;
974
975         region = memslot2region(vm, slot);
976
977         region->region.guest_phys_addr = new_gpa;
978
979         ret = ioctl(vm->fd, KVM_SET_USER_MEMORY_REGION, &region->region);
980
981         TEST_ASSERT(!ret, "KVM_SET_USER_MEMORY_REGION failed\n"
982                     "ret: %i errno: %i slot: %u new_gpa: 0x%lx",
983                     ret, errno, slot, new_gpa);
984 }
985
986 /*
987  * VM Memory Region Delete
988  *
989  * Input Args:
990  *   vm - Virtual Machine
991  *   slot - Slot of the memory region to delete
992  *
993  * Output Args: None
994  *
995  * Return: None
996  *
997  * Delete a memory region.
998  */
999 void vm_mem_region_delete(struct kvm_vm *vm, uint32_t slot)
1000 {
1001         __vm_mem_region_delete(vm, memslot2region(vm, slot), true);
1002 }
1003
1004 /*
1005  * VCPU mmap Size
1006  *
1007  * Input Args: None
1008  *
1009  * Output Args: None
1010  *
1011  * Return:
1012  *   Size of VCPU state
1013  *
1014  * Returns the size of the structure pointed to by the return value
1015  * of vcpu_state().
1016  */
1017 static int vcpu_mmap_sz(void)
1018 {
1019         int dev_fd, ret;
1020
1021         dev_fd = open_kvm_dev_path_or_exit();
1022
1023         ret = ioctl(dev_fd, KVM_GET_VCPU_MMAP_SIZE, NULL);
1024         TEST_ASSERT(ret >= sizeof(struct kvm_run),
1025                 "%s KVM_GET_VCPU_MMAP_SIZE ioctl failed, rc: %i errno: %i",
1026                 __func__, ret, errno);
1027
1028         close(dev_fd);
1029
1030         return ret;
1031 }
1032
1033 /*
1034  * VM VCPU Add
1035  *
1036  * Input Args:
1037  *   vm - Virtual Machine
1038  *   vcpuid - VCPU ID
1039  *
1040  * Output Args: None
1041  *
1042  * Return: None
1043  *
1044  * Adds a virtual CPU to the VM specified by vm with the ID given by vcpuid.
1045  * No additional VCPU setup is done.
1046  */
1047 void vm_vcpu_add(struct kvm_vm *vm, uint32_t vcpuid)
1048 {
1049         struct vcpu *vcpu;
1050
1051         /* Confirm a vcpu with the specified id doesn't already exist. */
1052         vcpu = vcpu_find(vm, vcpuid);
1053         if (vcpu != NULL)
1054                 TEST_FAIL("vcpu with the specified id "
1055                         "already exists,\n"
1056                         "  requested vcpuid: %u\n"
1057                         "  existing vcpuid: %u state: %p",
1058                         vcpuid, vcpu->id, vcpu->state);
1059
1060         /* Allocate and initialize new vcpu structure. */
1061         vcpu = calloc(1, sizeof(*vcpu));
1062         TEST_ASSERT(vcpu != NULL, "Insufficient Memory");
1063         vcpu->id = vcpuid;
1064         vcpu->fd = ioctl(vm->fd, KVM_CREATE_VCPU, vcpuid);
1065         TEST_ASSERT(vcpu->fd >= 0, "KVM_CREATE_VCPU failed, rc: %i errno: %i",
1066                 vcpu->fd, errno);
1067
1068         TEST_ASSERT(vcpu_mmap_sz() >= sizeof(*vcpu->state), "vcpu mmap size "
1069                 "smaller than expected, vcpu_mmap_sz: %i expected_min: %zi",
1070                 vcpu_mmap_sz(), sizeof(*vcpu->state));
1071         vcpu->state = (struct kvm_run *) mmap(NULL, vcpu_mmap_sz(),
1072                 PROT_READ | PROT_WRITE, MAP_SHARED, vcpu->fd, 0);
1073         TEST_ASSERT(vcpu->state != MAP_FAILED, "mmap vcpu_state failed, "
1074                 "vcpu id: %u errno: %i", vcpuid, errno);
1075
1076         /* Add to linked-list of VCPUs. */
1077         list_add(&vcpu->list, &vm->vcpus);
1078 }
1079
1080 /*
1081  * VM Virtual Address Unused Gap
1082  *
1083  * Input Args:
1084  *   vm - Virtual Machine
1085  *   sz - Size (bytes)
1086  *   vaddr_min - Minimum Virtual Address
1087  *
1088  * Output Args: None
1089  *
1090  * Return:
1091  *   Lowest virtual address at or below vaddr_min, with at least
1092  *   sz unused bytes.  TEST_ASSERT failure if no area of at least
1093  *   size sz is available.
1094  *
1095  * Within the VM specified by vm, locates the lowest starting virtual
1096  * address >= vaddr_min, that has at least sz unallocated bytes.  A
1097  * TEST_ASSERT failure occurs for invalid input or no area of at least
1098  * sz unallocated bytes >= vaddr_min is available.
1099  */
1100 static vm_vaddr_t vm_vaddr_unused_gap(struct kvm_vm *vm, size_t sz,
1101                                       vm_vaddr_t vaddr_min)
1102 {
1103         uint64_t pages = (sz + vm->page_size - 1) >> vm->page_shift;
1104
1105         /* Determine lowest permitted virtual page index. */
1106         uint64_t pgidx_start = (vaddr_min + vm->page_size - 1) >> vm->page_shift;
1107         if ((pgidx_start * vm->page_size) < vaddr_min)
1108                 goto no_va_found;
1109
1110         /* Loop over section with enough valid virtual page indexes. */
1111         if (!sparsebit_is_set_num(vm->vpages_valid,
1112                 pgidx_start, pages))
1113                 pgidx_start = sparsebit_next_set_num(vm->vpages_valid,
1114                         pgidx_start, pages);
1115         do {
1116                 /*
1117                  * Are there enough unused virtual pages available at
1118                  * the currently proposed starting virtual page index.
1119                  * If not, adjust proposed starting index to next
1120                  * possible.
1121                  */
1122                 if (sparsebit_is_clear_num(vm->vpages_mapped,
1123                         pgidx_start, pages))
1124                         goto va_found;
1125                 pgidx_start = sparsebit_next_clear_num(vm->vpages_mapped,
1126                         pgidx_start, pages);
1127                 if (pgidx_start == 0)
1128                         goto no_va_found;
1129
1130                 /*
1131                  * If needed, adjust proposed starting virtual address,
1132                  * to next range of valid virtual addresses.
1133                  */
1134                 if (!sparsebit_is_set_num(vm->vpages_valid,
1135                         pgidx_start, pages)) {
1136                         pgidx_start = sparsebit_next_set_num(
1137                                 vm->vpages_valid, pgidx_start, pages);
1138                         if (pgidx_start == 0)
1139                                 goto no_va_found;
1140                 }
1141         } while (pgidx_start != 0);
1142
1143 no_va_found:
1144         TEST_FAIL("No vaddr of specified pages available, pages: 0x%lx", pages);
1145
1146         /* NOT REACHED */
1147         return -1;
1148
1149 va_found:
1150         TEST_ASSERT(sparsebit_is_set_num(vm->vpages_valid,
1151                 pgidx_start, pages),
1152                 "Unexpected, invalid virtual page index range,\n"
1153                 "  pgidx_start: 0x%lx\n"
1154                 "  pages: 0x%lx",
1155                 pgidx_start, pages);
1156         TEST_ASSERT(sparsebit_is_clear_num(vm->vpages_mapped,
1157                 pgidx_start, pages),
1158                 "Unexpected, pages already mapped,\n"
1159                 "  pgidx_start: 0x%lx\n"
1160                 "  pages: 0x%lx",
1161                 pgidx_start, pages);
1162
1163         return pgidx_start * vm->page_size;
1164 }
1165
1166 /*
1167  * VM Virtual Address Allocate
1168  *
1169  * Input Args:
1170  *   vm - Virtual Machine
1171  *   sz - Size in bytes
1172  *   vaddr_min - Minimum starting virtual address
1173  *   data_memslot - Memory region slot for data pages
1174  *   pgd_memslot - Memory region slot for new virtual translation tables
1175  *
1176  * Output Args: None
1177  *
1178  * Return:
1179  *   Starting guest virtual address
1180  *
1181  * Allocates at least sz bytes within the virtual address space of the vm
1182  * given by vm.  The allocated bytes are mapped to a virtual address >=
1183  * the address given by vaddr_min.  Note that each allocation uses a
1184  * a unique set of pages, with the minimum real allocation being at least
1185  * a page.
1186  */
1187 vm_vaddr_t vm_vaddr_alloc(struct kvm_vm *vm, size_t sz, vm_vaddr_t vaddr_min,
1188                           uint32_t data_memslot, uint32_t pgd_memslot)
1189 {
1190         uint64_t pages = (sz >> vm->page_shift) + ((sz % vm->page_size) != 0);
1191
1192         virt_pgd_alloc(vm, pgd_memslot);
1193         vm_paddr_t paddr = vm_phy_pages_alloc(vm, pages,
1194                                               KVM_UTIL_MIN_PFN * vm->page_size,
1195                                               data_memslot);
1196
1197         /*
1198          * Find an unused range of virtual page addresses of at least
1199          * pages in length.
1200          */
1201         vm_vaddr_t vaddr_start = vm_vaddr_unused_gap(vm, sz, vaddr_min);
1202
1203         /* Map the virtual pages. */
1204         for (vm_vaddr_t vaddr = vaddr_start; pages > 0;
1205                 pages--, vaddr += vm->page_size, paddr += vm->page_size) {
1206
1207                 virt_pg_map(vm, vaddr, paddr, pgd_memslot);
1208
1209                 sparsebit_set(vm->vpages_mapped,
1210                         vaddr >> vm->page_shift);
1211         }
1212
1213         return vaddr_start;
1214 }
1215
1216 /*
1217  * Map a range of VM virtual address to the VM's physical address
1218  *
1219  * Input Args:
1220  *   vm - Virtual Machine
1221  *   vaddr - Virtuall address to map
1222  *   paddr - VM Physical Address
1223  *   npages - The number of pages to map
1224  *   pgd_memslot - Memory region slot for new virtual translation tables
1225  *
1226  * Output Args: None
1227  *
1228  * Return: None
1229  *
1230  * Within the VM given by @vm, creates a virtual translation for
1231  * @npages starting at @vaddr to the page range starting at @paddr.
1232  */
1233 void virt_map(struct kvm_vm *vm, uint64_t vaddr, uint64_t paddr,
1234               unsigned int npages, uint32_t pgd_memslot)
1235 {
1236         size_t page_size = vm->page_size;
1237         size_t size = npages * page_size;
1238
1239         TEST_ASSERT(vaddr + size > vaddr, "Vaddr overflow");
1240         TEST_ASSERT(paddr + size > paddr, "Paddr overflow");
1241
1242         while (npages--) {
1243                 virt_pg_map(vm, vaddr, paddr, pgd_memslot);
1244                 vaddr += page_size;
1245                 paddr += page_size;
1246         }
1247 }
1248
1249 /*
1250  * Address VM Physical to Host Virtual
1251  *
1252  * Input Args:
1253  *   vm - Virtual Machine
1254  *   gpa - VM physical address
1255  *
1256  * Output Args: None
1257  *
1258  * Return:
1259  *   Equivalent host virtual address
1260  *
1261  * Locates the memory region containing the VM physical address given
1262  * by gpa, within the VM given by vm.  When found, the host virtual
1263  * address providing the memory to the vm physical address is returned.
1264  * A TEST_ASSERT failure occurs if no region containing gpa exists.
1265  */
1266 void *addr_gpa2hva(struct kvm_vm *vm, vm_paddr_t gpa)
1267 {
1268         struct userspace_mem_region *region;
1269
1270         region = userspace_mem_region_find(vm, gpa, gpa);
1271         if (!region) {
1272                 TEST_FAIL("No vm physical memory at 0x%lx", gpa);
1273                 return NULL;
1274         }
1275
1276         return (void *)((uintptr_t)region->host_mem
1277                 + (gpa - region->region.guest_phys_addr));
1278 }
1279
1280 /*
1281  * Address Host Virtual to VM Physical
1282  *
1283  * Input Args:
1284  *   vm - Virtual Machine
1285  *   hva - Host virtual address
1286  *
1287  * Output Args: None
1288  *
1289  * Return:
1290  *   Equivalent VM physical address
1291  *
1292  * Locates the memory region containing the host virtual address given
1293  * by hva, within the VM given by vm.  When found, the equivalent
1294  * VM physical address is returned. A TEST_ASSERT failure occurs if no
1295  * region containing hva exists.
1296  */
1297 vm_paddr_t addr_hva2gpa(struct kvm_vm *vm, void *hva)
1298 {
1299         struct rb_node *node;
1300
1301         for (node = vm->regions.hva_tree.rb_node; node; ) {
1302                 struct userspace_mem_region *region =
1303                         container_of(node, struct userspace_mem_region, hva_node);
1304
1305                 if (hva >= region->host_mem) {
1306                         if (hva <= (region->host_mem
1307                                 + region->region.memory_size - 1))
1308                                 return (vm_paddr_t)((uintptr_t)
1309                                         region->region.guest_phys_addr
1310                                         + (hva - (uintptr_t)region->host_mem));
1311
1312                         node = node->rb_right;
1313                 } else
1314                         node = node->rb_left;
1315         }
1316
1317         TEST_FAIL("No mapping to a guest physical address, hva: %p", hva);
1318         return -1;
1319 }
1320
1321 /*
1322  * VM Create IRQ Chip
1323  *
1324  * Input Args:
1325  *   vm - Virtual Machine
1326  *
1327  * Output Args: None
1328  *
1329  * Return: None
1330  *
1331  * Creates an interrupt controller chip for the VM specified by vm.
1332  */
1333 void vm_create_irqchip(struct kvm_vm *vm)
1334 {
1335         int ret;
1336
1337         ret = ioctl(vm->fd, KVM_CREATE_IRQCHIP, 0);
1338         TEST_ASSERT(ret == 0, "KVM_CREATE_IRQCHIP IOCTL failed, "
1339                 "rc: %i errno: %i", ret, errno);
1340
1341         vm->has_irqchip = true;
1342 }
1343
1344 /*
1345  * VM VCPU State
1346  *
1347  * Input Args:
1348  *   vm - Virtual Machine
1349  *   vcpuid - VCPU ID
1350  *
1351  * Output Args: None
1352  *
1353  * Return:
1354  *   Pointer to structure that describes the state of the VCPU.
1355  *
1356  * Locates and returns a pointer to a structure that describes the
1357  * state of the VCPU with the given vcpuid.
1358  */
1359 struct kvm_run *vcpu_state(struct kvm_vm *vm, uint32_t vcpuid)
1360 {
1361         struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1362         TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1363
1364         return vcpu->state;
1365 }
1366
1367 /*
1368  * VM VCPU Run
1369  *
1370  * Input Args:
1371  *   vm - Virtual Machine
1372  *   vcpuid - VCPU ID
1373  *
1374  * Output Args: None
1375  *
1376  * Return: None
1377  *
1378  * Switch to executing the code for the VCPU given by vcpuid, within the VM
1379  * given by vm.
1380  */
1381 void vcpu_run(struct kvm_vm *vm, uint32_t vcpuid)
1382 {
1383         int ret = _vcpu_run(vm, vcpuid);
1384         TEST_ASSERT(ret == 0, "KVM_RUN IOCTL failed, "
1385                 "rc: %i errno: %i", ret, errno);
1386 }
1387
1388 int _vcpu_run(struct kvm_vm *vm, uint32_t vcpuid)
1389 {
1390         struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1391         int rc;
1392
1393         TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1394         do {
1395                 rc = ioctl(vcpu->fd, KVM_RUN, NULL);
1396         } while (rc == -1 && errno == EINTR);
1397
1398         assert_on_unhandled_exception(vm, vcpuid);
1399
1400         return rc;
1401 }
1402
1403 int vcpu_get_fd(struct kvm_vm *vm, uint32_t vcpuid)
1404 {
1405         struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1406
1407         TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1408
1409         return vcpu->fd;
1410 }
1411
1412 void vcpu_run_complete_io(struct kvm_vm *vm, uint32_t vcpuid)
1413 {
1414         struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1415         int ret;
1416
1417         TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1418
1419         vcpu->state->immediate_exit = 1;
1420         ret = ioctl(vcpu->fd, KVM_RUN, NULL);
1421         vcpu->state->immediate_exit = 0;
1422
1423         TEST_ASSERT(ret == -1 && errno == EINTR,
1424                     "KVM_RUN IOCTL didn't exit immediately, rc: %i, errno: %i",
1425                     ret, errno);
1426 }
1427
1428 void vcpu_set_guest_debug(struct kvm_vm *vm, uint32_t vcpuid,
1429                           struct kvm_guest_debug *debug)
1430 {
1431         struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1432         int ret = ioctl(vcpu->fd, KVM_SET_GUEST_DEBUG, debug);
1433
1434         TEST_ASSERT(ret == 0, "KVM_SET_GUEST_DEBUG failed: %d", ret);
1435 }
1436
1437 /*
1438  * VM VCPU Set MP State
1439  *
1440  * Input Args:
1441  *   vm - Virtual Machine
1442  *   vcpuid - VCPU ID
1443  *   mp_state - mp_state to be set
1444  *
1445  * Output Args: None
1446  *
1447  * Return: None
1448  *
1449  * Sets the MP state of the VCPU given by vcpuid, to the state given
1450  * by mp_state.
1451  */
1452 void vcpu_set_mp_state(struct kvm_vm *vm, uint32_t vcpuid,
1453                        struct kvm_mp_state *mp_state)
1454 {
1455         struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1456         int ret;
1457
1458         TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1459
1460         ret = ioctl(vcpu->fd, KVM_SET_MP_STATE, mp_state);
1461         TEST_ASSERT(ret == 0, "KVM_SET_MP_STATE IOCTL failed, "
1462                 "rc: %i errno: %i", ret, errno);
1463 }
1464
1465 /*
1466  * VM VCPU Get Reg List
1467  *
1468  * Input Args:
1469  *   vm - Virtual Machine
1470  *   vcpuid - VCPU ID
1471  *
1472  * Output Args:
1473  *   None
1474  *
1475  * Return:
1476  *   A pointer to an allocated struct kvm_reg_list
1477  *
1478  * Get the list of guest registers which are supported for
1479  * KVM_GET_ONE_REG/KVM_SET_ONE_REG calls
1480  */
1481 struct kvm_reg_list *vcpu_get_reg_list(struct kvm_vm *vm, uint32_t vcpuid)
1482 {
1483         struct kvm_reg_list reg_list_n = { .n = 0 }, *reg_list;
1484         int ret;
1485
1486         ret = _vcpu_ioctl(vm, vcpuid, KVM_GET_REG_LIST, &reg_list_n);
1487         TEST_ASSERT(ret == -1 && errno == E2BIG, "KVM_GET_REG_LIST n=0");
1488         reg_list = calloc(1, sizeof(*reg_list) + reg_list_n.n * sizeof(__u64));
1489         reg_list->n = reg_list_n.n;
1490         vcpu_ioctl(vm, vcpuid, KVM_GET_REG_LIST, reg_list);
1491         return reg_list;
1492 }
1493
1494 /*
1495  * VM VCPU Regs Get
1496  *
1497  * Input Args:
1498  *   vm - Virtual Machine
1499  *   vcpuid - VCPU ID
1500  *
1501  * Output Args:
1502  *   regs - current state of VCPU regs
1503  *
1504  * Return: None
1505  *
1506  * Obtains the current register state for the VCPU specified by vcpuid
1507  * and stores it at the location given by regs.
1508  */
1509 void vcpu_regs_get(struct kvm_vm *vm, uint32_t vcpuid, struct kvm_regs *regs)
1510 {
1511         struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1512         int ret;
1513
1514         TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1515
1516         ret = ioctl(vcpu->fd, KVM_GET_REGS, regs);
1517         TEST_ASSERT(ret == 0, "KVM_GET_REGS failed, rc: %i errno: %i",
1518                 ret, errno);
1519 }
1520
1521 /*
1522  * VM VCPU Regs Set
1523  *
1524  * Input Args:
1525  *   vm - Virtual Machine
1526  *   vcpuid - VCPU ID
1527  *   regs - Values to set VCPU regs to
1528  *
1529  * Output Args: None
1530  *
1531  * Return: None
1532  *
1533  * Sets the regs of the VCPU specified by vcpuid to the values
1534  * given by regs.
1535  */
1536 void vcpu_regs_set(struct kvm_vm *vm, uint32_t vcpuid, struct kvm_regs *regs)
1537 {
1538         struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1539         int ret;
1540
1541         TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1542
1543         ret = ioctl(vcpu->fd, KVM_SET_REGS, regs);
1544         TEST_ASSERT(ret == 0, "KVM_SET_REGS failed, rc: %i errno: %i",
1545                 ret, errno);
1546 }
1547
1548 #ifdef __KVM_HAVE_VCPU_EVENTS
1549 void vcpu_events_get(struct kvm_vm *vm, uint32_t vcpuid,
1550                      struct kvm_vcpu_events *events)
1551 {
1552         struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1553         int ret;
1554
1555         TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1556
1557         ret = ioctl(vcpu->fd, KVM_GET_VCPU_EVENTS, events);
1558         TEST_ASSERT(ret == 0, "KVM_GET_VCPU_EVENTS, failed, rc: %i errno: %i",
1559                 ret, errno);
1560 }
1561
1562 void vcpu_events_set(struct kvm_vm *vm, uint32_t vcpuid,
1563                      struct kvm_vcpu_events *events)
1564 {
1565         struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1566         int ret;
1567
1568         TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1569
1570         ret = ioctl(vcpu->fd, KVM_SET_VCPU_EVENTS, events);
1571         TEST_ASSERT(ret == 0, "KVM_SET_VCPU_EVENTS, failed, rc: %i errno: %i",
1572                 ret, errno);
1573 }
1574 #endif
1575
1576 #ifdef __x86_64__
1577 void vcpu_nested_state_get(struct kvm_vm *vm, uint32_t vcpuid,
1578                            struct kvm_nested_state *state)
1579 {
1580         struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1581         int ret;
1582
1583         TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1584
1585         ret = ioctl(vcpu->fd, KVM_GET_NESTED_STATE, state);
1586         TEST_ASSERT(ret == 0,
1587                 "KVM_SET_NESTED_STATE failed, ret: %i errno: %i",
1588                 ret, errno);
1589 }
1590
1591 int vcpu_nested_state_set(struct kvm_vm *vm, uint32_t vcpuid,
1592                           struct kvm_nested_state *state, bool ignore_error)
1593 {
1594         struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1595         int ret;
1596
1597         TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1598
1599         ret = ioctl(vcpu->fd, KVM_SET_NESTED_STATE, state);
1600         if (!ignore_error) {
1601                 TEST_ASSERT(ret == 0,
1602                         "KVM_SET_NESTED_STATE failed, ret: %i errno: %i",
1603                         ret, errno);
1604         }
1605
1606         return ret;
1607 }
1608 #endif
1609
1610 /*
1611  * VM VCPU System Regs Get
1612  *
1613  * Input Args:
1614  *   vm - Virtual Machine
1615  *   vcpuid - VCPU ID
1616  *
1617  * Output Args:
1618  *   sregs - current state of VCPU system regs
1619  *
1620  * Return: None
1621  *
1622  * Obtains the current system register state for the VCPU specified by
1623  * vcpuid and stores it at the location given by sregs.
1624  */
1625 void vcpu_sregs_get(struct kvm_vm *vm, uint32_t vcpuid, struct kvm_sregs *sregs)
1626 {
1627         struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1628         int ret;
1629
1630         TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1631
1632         ret = ioctl(vcpu->fd, KVM_GET_SREGS, sregs);
1633         TEST_ASSERT(ret == 0, "KVM_GET_SREGS failed, rc: %i errno: %i",
1634                 ret, errno);
1635 }
1636
1637 /*
1638  * VM VCPU System Regs Set
1639  *
1640  * Input Args:
1641  *   vm - Virtual Machine
1642  *   vcpuid - VCPU ID
1643  *   sregs - Values to set VCPU system regs to
1644  *
1645  * Output Args: None
1646  *
1647  * Return: None
1648  *
1649  * Sets the system regs of the VCPU specified by vcpuid to the values
1650  * given by sregs.
1651  */
1652 void vcpu_sregs_set(struct kvm_vm *vm, uint32_t vcpuid, struct kvm_sregs *sregs)
1653 {
1654         int ret = _vcpu_sregs_set(vm, vcpuid, sregs);
1655         TEST_ASSERT(ret == 0, "KVM_RUN IOCTL failed, "
1656                 "rc: %i errno: %i", ret, errno);
1657 }
1658
1659 int _vcpu_sregs_set(struct kvm_vm *vm, uint32_t vcpuid, struct kvm_sregs *sregs)
1660 {
1661         struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1662
1663         TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1664
1665         return ioctl(vcpu->fd, KVM_SET_SREGS, sregs);
1666 }
1667
1668 void vcpu_fpu_get(struct kvm_vm *vm, uint32_t vcpuid, struct kvm_fpu *fpu)
1669 {
1670         int ret;
1671
1672         ret = _vcpu_ioctl(vm, vcpuid, KVM_GET_FPU, fpu);
1673         TEST_ASSERT(ret == 0, "KVM_GET_FPU failed, rc: %i errno: %i (%s)",
1674                     ret, errno, strerror(errno));
1675 }
1676
1677 void vcpu_fpu_set(struct kvm_vm *vm, uint32_t vcpuid, struct kvm_fpu *fpu)
1678 {
1679         int ret;
1680
1681         ret = _vcpu_ioctl(vm, vcpuid, KVM_SET_FPU, fpu);
1682         TEST_ASSERT(ret == 0, "KVM_SET_FPU failed, rc: %i errno: %i (%s)",
1683                     ret, errno, strerror(errno));
1684 }
1685
1686 void vcpu_get_reg(struct kvm_vm *vm, uint32_t vcpuid, struct kvm_one_reg *reg)
1687 {
1688         int ret;
1689
1690         ret = _vcpu_ioctl(vm, vcpuid, KVM_GET_ONE_REG, reg);
1691         TEST_ASSERT(ret == 0, "KVM_GET_ONE_REG failed, rc: %i errno: %i (%s)",
1692                     ret, errno, strerror(errno));
1693 }
1694
1695 void vcpu_set_reg(struct kvm_vm *vm, uint32_t vcpuid, struct kvm_one_reg *reg)
1696 {
1697         int ret;
1698
1699         ret = _vcpu_ioctl(vm, vcpuid, KVM_SET_ONE_REG, reg);
1700         TEST_ASSERT(ret == 0, "KVM_SET_ONE_REG failed, rc: %i errno: %i (%s)",
1701                     ret, errno, strerror(errno));
1702 }
1703
1704 /*
1705  * VCPU Ioctl
1706  *
1707  * Input Args:
1708  *   vm - Virtual Machine
1709  *   vcpuid - VCPU ID
1710  *   cmd - Ioctl number
1711  *   arg - Argument to pass to the ioctl
1712  *
1713  * Return: None
1714  *
1715  * Issues an arbitrary ioctl on a VCPU fd.
1716  */
1717 void vcpu_ioctl(struct kvm_vm *vm, uint32_t vcpuid,
1718                 unsigned long cmd, void *arg)
1719 {
1720         int ret;
1721
1722         ret = _vcpu_ioctl(vm, vcpuid, cmd, arg);
1723         TEST_ASSERT(ret == 0, "vcpu ioctl %lu failed, rc: %i errno: %i (%s)",
1724                 cmd, ret, errno, strerror(errno));
1725 }
1726
1727 int _vcpu_ioctl(struct kvm_vm *vm, uint32_t vcpuid,
1728                 unsigned long cmd, void *arg)
1729 {
1730         struct vcpu *vcpu = vcpu_find(vm, vcpuid);
1731         int ret;
1732
1733         TEST_ASSERT(vcpu != NULL, "vcpu not found, vcpuid: %u", vcpuid);
1734
1735         ret = ioctl(vcpu->fd, cmd, arg);
1736
1737         return ret;
1738 }
1739
1740 void *vcpu_map_dirty_ring(struct kvm_vm *vm, uint32_t vcpuid)
1741 {
1742         struct vcpu *vcpu;
1743         uint32_t size = vm->dirty_ring_size;
1744
1745         TEST_ASSERT(size > 0, "Should enable dirty ring first");
1746
1747         vcpu = vcpu_find(vm, vcpuid);
1748
1749         TEST_ASSERT(vcpu, "Cannot find vcpu %u", vcpuid);
1750
1751         if (!vcpu->dirty_gfns) {
1752                 void *addr;
1753
1754                 addr = mmap(NULL, size, PROT_READ,
1755                             MAP_PRIVATE, vcpu->fd,
1756                             vm->page_size * KVM_DIRTY_LOG_PAGE_OFFSET);
1757                 TEST_ASSERT(addr == MAP_FAILED, "Dirty ring mapped private");
1758
1759                 addr = mmap(NULL, size, PROT_READ | PROT_EXEC,
1760                             MAP_PRIVATE, vcpu->fd,
1761                             vm->page_size * KVM_DIRTY_LOG_PAGE_OFFSET);
1762                 TEST_ASSERT(addr == MAP_FAILED, "Dirty ring mapped exec");
1763
1764                 addr = mmap(NULL, size, PROT_READ | PROT_WRITE,
1765                             MAP_SHARED, vcpu->fd,
1766                             vm->page_size * KVM_DIRTY_LOG_PAGE_OFFSET);
1767                 TEST_ASSERT(addr != MAP_FAILED, "Dirty ring map failed");
1768
1769                 vcpu->dirty_gfns = addr;
1770                 vcpu->dirty_gfns_count = size / sizeof(struct kvm_dirty_gfn);
1771         }
1772
1773         return vcpu->dirty_gfns;
1774 }
1775
1776 /*
1777  * VM Ioctl
1778  *
1779  * Input Args:
1780  *   vm - Virtual Machine
1781  *   cmd - Ioctl number
1782  *   arg - Argument to pass to the ioctl
1783  *
1784  * Return: None
1785  *
1786  * Issues an arbitrary ioctl on a VM fd.
1787  */
1788 void vm_ioctl(struct kvm_vm *vm, unsigned long cmd, void *arg)
1789 {
1790         int ret;
1791
1792         ret = _vm_ioctl(vm, cmd, arg);
1793         TEST_ASSERT(ret == 0, "vm ioctl %lu failed, rc: %i errno: %i (%s)",
1794                 cmd, ret, errno, strerror(errno));
1795 }
1796
1797 int _vm_ioctl(struct kvm_vm *vm, unsigned long cmd, void *arg)
1798 {
1799         return ioctl(vm->fd, cmd, arg);
1800 }
1801
1802 /*
1803  * KVM system ioctl
1804  *
1805  * Input Args:
1806  *   vm - Virtual Machine
1807  *   cmd - Ioctl number
1808  *   arg - Argument to pass to the ioctl
1809  *
1810  * Return: None
1811  *
1812  * Issues an arbitrary ioctl on a KVM fd.
1813  */
1814 void kvm_ioctl(struct kvm_vm *vm, unsigned long cmd, void *arg)
1815 {
1816         int ret;
1817
1818         ret = ioctl(vm->kvm_fd, cmd, arg);
1819         TEST_ASSERT(ret == 0, "KVM ioctl %lu failed, rc: %i errno: %i (%s)",
1820                 cmd, ret, errno, strerror(errno));
1821 }
1822
1823 int _kvm_ioctl(struct kvm_vm *vm, unsigned long cmd, void *arg)
1824 {
1825         return ioctl(vm->kvm_fd, cmd, arg);
1826 }
1827
1828 /*
1829  * Device Ioctl
1830  */
1831
1832 int _kvm_device_check_attr(int dev_fd, uint32_t group, uint64_t attr)
1833 {
1834         struct kvm_device_attr attribute = {
1835                 .group = group,
1836                 .attr = attr,
1837                 .flags = 0,
1838         };
1839
1840         return ioctl(dev_fd, KVM_HAS_DEVICE_ATTR, &attribute);
1841 }
1842
1843 int kvm_device_check_attr(int dev_fd, uint32_t group, uint64_t attr)
1844 {
1845         int ret = _kvm_device_check_attr(dev_fd, group, attr);
1846
1847         TEST_ASSERT(ret >= 0, "KVM_HAS_DEVICE_ATTR failed, rc: %i errno: %i", ret, errno);
1848         return ret;
1849 }
1850
1851 int _kvm_create_device(struct kvm_vm *vm, uint64_t type, bool test, int *fd)
1852 {
1853         struct kvm_create_device create_dev;
1854         int ret;
1855
1856         create_dev.type = type;
1857         create_dev.fd = -1;
1858         create_dev.flags = test ? KVM_CREATE_DEVICE_TEST : 0;
1859         ret = ioctl(vm_get_fd(vm), KVM_CREATE_DEVICE, &create_dev);
1860         *fd = create_dev.fd;
1861         return ret;
1862 }
1863
1864 int kvm_create_device(struct kvm_vm *vm, uint64_t type, bool test)
1865 {
1866         int fd, ret;
1867
1868         ret = _kvm_create_device(vm, type, test, &fd);
1869
1870         if (!test) {
1871                 TEST_ASSERT(ret >= 0,
1872                             "KVM_CREATE_DEVICE IOCTL failed, rc: %i errno: %i", ret, errno);
1873                 return fd;
1874         }
1875         return ret;
1876 }
1877
1878 int _kvm_device_access(int dev_fd, uint32_t group, uint64_t attr,
1879                       void *val, bool write)
1880 {
1881         struct kvm_device_attr kvmattr = {
1882                 .group = group,
1883                 .attr = attr,
1884                 .flags = 0,
1885                 .addr = (uintptr_t)val,
1886         };
1887         int ret;
1888
1889         ret = ioctl(dev_fd, write ? KVM_SET_DEVICE_ATTR : KVM_GET_DEVICE_ATTR,
1890                     &kvmattr);
1891         return ret;
1892 }
1893
1894 int kvm_device_access(int dev_fd, uint32_t group, uint64_t attr,
1895                       void *val, bool write)
1896 {
1897         int ret = _kvm_device_access(dev_fd, group, attr, val, write);
1898
1899         TEST_ASSERT(ret >= 0, "KVM_SET|GET_DEVICE_ATTR IOCTL failed, rc: %i errno: %i", ret, errno);
1900         return ret;
1901 }
1902
1903 /*
1904  * VM Dump
1905  *
1906  * Input Args:
1907  *   vm - Virtual Machine
1908  *   indent - Left margin indent amount
1909  *
1910  * Output Args:
1911  *   stream - Output FILE stream
1912  *
1913  * Return: None
1914  *
1915  * Dumps the current state of the VM given by vm, to the FILE stream
1916  * given by stream.
1917  */
1918 void vm_dump(FILE *stream, struct kvm_vm *vm, uint8_t indent)
1919 {
1920         int ctr;
1921         struct userspace_mem_region *region;
1922         struct vcpu *vcpu;
1923
1924         fprintf(stream, "%*smode: 0x%x\n", indent, "", vm->mode);
1925         fprintf(stream, "%*sfd: %i\n", indent, "", vm->fd);
1926         fprintf(stream, "%*spage_size: 0x%x\n", indent, "", vm->page_size);
1927         fprintf(stream, "%*sMem Regions:\n", indent, "");
1928         hash_for_each(vm->regions.slot_hash, ctr, region, slot_node) {
1929                 fprintf(stream, "%*sguest_phys: 0x%lx size: 0x%lx "
1930                         "host_virt: %p\n", indent + 2, "",
1931                         (uint64_t) region->region.guest_phys_addr,
1932                         (uint64_t) region->region.memory_size,
1933                         region->host_mem);
1934                 fprintf(stream, "%*sunused_phy_pages: ", indent + 2, "");
1935                 sparsebit_dump(stream, region->unused_phy_pages, 0);
1936         }
1937         fprintf(stream, "%*sMapped Virtual Pages:\n", indent, "");
1938         sparsebit_dump(stream, vm->vpages_mapped, indent + 2);
1939         fprintf(stream, "%*spgd_created: %u\n", indent, "",
1940                 vm->pgd_created);
1941         if (vm->pgd_created) {
1942                 fprintf(stream, "%*sVirtual Translation Tables:\n",
1943                         indent + 2, "");
1944                 virt_dump(stream, vm, indent + 4);
1945         }
1946         fprintf(stream, "%*sVCPUs:\n", indent, "");
1947         list_for_each_entry(vcpu, &vm->vcpus, list)
1948                 vcpu_dump(stream, vm, vcpu->id, indent + 2);
1949 }
1950
1951 /* Known KVM exit reasons */
1952 static struct exit_reason {
1953         unsigned int reason;
1954         const char *name;
1955 } exit_reasons_known[] = {
1956         {KVM_EXIT_UNKNOWN, "UNKNOWN"},
1957         {KVM_EXIT_EXCEPTION, "EXCEPTION"},
1958         {KVM_EXIT_IO, "IO"},
1959         {KVM_EXIT_HYPERCALL, "HYPERCALL"},
1960         {KVM_EXIT_DEBUG, "DEBUG"},
1961         {KVM_EXIT_HLT, "HLT"},
1962         {KVM_EXIT_MMIO, "MMIO"},
1963         {KVM_EXIT_IRQ_WINDOW_OPEN, "IRQ_WINDOW_OPEN"},
1964         {KVM_EXIT_SHUTDOWN, "SHUTDOWN"},
1965         {KVM_EXIT_FAIL_ENTRY, "FAIL_ENTRY"},
1966         {KVM_EXIT_INTR, "INTR"},
1967         {KVM_EXIT_SET_TPR, "SET_TPR"},
1968         {KVM_EXIT_TPR_ACCESS, "TPR_ACCESS"},
1969         {KVM_EXIT_S390_SIEIC, "S390_SIEIC"},
1970         {KVM_EXIT_S390_RESET, "S390_RESET"},
1971         {KVM_EXIT_DCR, "DCR"},
1972         {KVM_EXIT_NMI, "NMI"},
1973         {KVM_EXIT_INTERNAL_ERROR, "INTERNAL_ERROR"},
1974         {KVM_EXIT_OSI, "OSI"},
1975         {KVM_EXIT_PAPR_HCALL, "PAPR_HCALL"},
1976         {KVM_EXIT_DIRTY_RING_FULL, "DIRTY_RING_FULL"},
1977         {KVM_EXIT_X86_RDMSR, "RDMSR"},
1978         {KVM_EXIT_X86_WRMSR, "WRMSR"},
1979         {KVM_EXIT_XEN, "XEN"},
1980 #ifdef KVM_EXIT_MEMORY_NOT_PRESENT
1981         {KVM_EXIT_MEMORY_NOT_PRESENT, "MEMORY_NOT_PRESENT"},
1982 #endif
1983 };
1984
1985 /*
1986  * Exit Reason String
1987  *
1988  * Input Args:
1989  *   exit_reason - Exit reason
1990  *
1991  * Output Args: None
1992  *
1993  * Return:
1994  *   Constant string pointer describing the exit reason.
1995  *
1996  * Locates and returns a constant string that describes the KVM exit
1997  * reason given by exit_reason.  If no such string is found, a constant
1998  * string of "Unknown" is returned.
1999  */
2000 const char *exit_reason_str(unsigned int exit_reason)
2001 {
2002         unsigned int n1;
2003
2004         for (n1 = 0; n1 < ARRAY_SIZE(exit_reasons_known); n1++) {
2005                 if (exit_reason == exit_reasons_known[n1].reason)
2006                         return exit_reasons_known[n1].name;
2007         }
2008
2009         return "Unknown";
2010 }
2011
2012 /*
2013  * Physical Contiguous Page Allocator
2014  *
2015  * Input Args:
2016  *   vm - Virtual Machine
2017  *   num - number of pages
2018  *   paddr_min - Physical address minimum
2019  *   memslot - Memory region to allocate page from
2020  *
2021  * Output Args: None
2022  *
2023  * Return:
2024  *   Starting physical address
2025  *
2026  * Within the VM specified by vm, locates a range of available physical
2027  * pages at or above paddr_min. If found, the pages are marked as in use
2028  * and their base address is returned. A TEST_ASSERT failure occurs if
2029  * not enough pages are available at or above paddr_min.
2030  */
2031 vm_paddr_t vm_phy_pages_alloc(struct kvm_vm *vm, size_t num,
2032                               vm_paddr_t paddr_min, uint32_t memslot)
2033 {
2034         struct userspace_mem_region *region;
2035         sparsebit_idx_t pg, base;
2036
2037         TEST_ASSERT(num > 0, "Must allocate at least one page");
2038
2039         TEST_ASSERT((paddr_min % vm->page_size) == 0, "Min physical address "
2040                 "not divisible by page size.\n"
2041                 "  paddr_min: 0x%lx page_size: 0x%x",
2042                 paddr_min, vm->page_size);
2043
2044         region = memslot2region(vm, memslot);
2045         base = pg = paddr_min >> vm->page_shift;
2046
2047         do {
2048                 for (; pg < base + num; ++pg) {
2049                         if (!sparsebit_is_set(region->unused_phy_pages, pg)) {
2050                                 base = pg = sparsebit_next_set(region->unused_phy_pages, pg);
2051                                 break;
2052                         }
2053                 }
2054         } while (pg && pg != base + num);
2055
2056         if (pg == 0) {
2057                 fprintf(stderr, "No guest physical page available, "
2058                         "paddr_min: 0x%lx page_size: 0x%x memslot: %u\n",
2059                         paddr_min, vm->page_size, memslot);
2060                 fputs("---- vm dump ----\n", stderr);
2061                 vm_dump(stderr, vm, 2);
2062                 abort();
2063         }
2064
2065         for (pg = base; pg < base + num; ++pg)
2066                 sparsebit_clear(region->unused_phy_pages, pg);
2067
2068         return base * vm->page_size;
2069 }
2070
2071 vm_paddr_t vm_phy_page_alloc(struct kvm_vm *vm, vm_paddr_t paddr_min,
2072                              uint32_t memslot)
2073 {
2074         return vm_phy_pages_alloc(vm, 1, paddr_min, memslot);
2075 }
2076
2077 /*
2078  * Address Guest Virtual to Host Virtual
2079  *
2080  * Input Args:
2081  *   vm - Virtual Machine
2082  *   gva - VM virtual address
2083  *
2084  * Output Args: None
2085  *
2086  * Return:
2087  *   Equivalent host virtual address
2088  */
2089 void *addr_gva2hva(struct kvm_vm *vm, vm_vaddr_t gva)
2090 {
2091         return addr_gpa2hva(vm, addr_gva2gpa(vm, gva));
2092 }
2093
2094 /*
2095  * Is Unrestricted Guest
2096  *
2097  * Input Args:
2098  *   vm - Virtual Machine
2099  *
2100  * Output Args: None
2101  *
2102  * Return: True if the unrestricted guest is set to 'Y', otherwise return false.
2103  *
2104  * Check if the unrestricted guest flag is enabled.
2105  */
2106 bool vm_is_unrestricted_guest(struct kvm_vm *vm)
2107 {
2108         char val = 'N';
2109         size_t count;
2110         FILE *f;
2111
2112         if (vm == NULL) {
2113                 /* Ensure that the KVM vendor-specific module is loaded. */
2114                 close(open_kvm_dev_path_or_exit());
2115         }
2116
2117         f = fopen("/sys/module/kvm_intel/parameters/unrestricted_guest", "r");
2118         if (f) {
2119                 count = fread(&val, sizeof(char), 1, f);
2120                 TEST_ASSERT(count == 1, "Unable to read from param file.");
2121                 fclose(f);
2122         }
2123
2124         return val == 'Y';
2125 }
2126
2127 unsigned int vm_get_page_size(struct kvm_vm *vm)
2128 {
2129         return vm->page_size;
2130 }
2131
2132 unsigned int vm_get_page_shift(struct kvm_vm *vm)
2133 {
2134         return vm->page_shift;
2135 }
2136
2137 uint64_t vm_get_max_gfn(struct kvm_vm *vm)
2138 {
2139         return vm->max_gfn;
2140 }
2141
2142 int vm_get_fd(struct kvm_vm *vm)
2143 {
2144         return vm->fd;
2145 }
2146
2147 static unsigned int vm_calc_num_pages(unsigned int num_pages,
2148                                       unsigned int page_shift,
2149                                       unsigned int new_page_shift,
2150                                       bool ceil)
2151 {
2152         unsigned int n = 1 << (new_page_shift - page_shift);
2153
2154         if (page_shift >= new_page_shift)
2155                 return num_pages * (1 << (page_shift - new_page_shift));
2156
2157         return num_pages / n + !!(ceil && num_pages % n);
2158 }
2159
2160 static inline int getpageshift(void)
2161 {
2162         return __builtin_ffs(getpagesize()) - 1;
2163 }
2164
2165 unsigned int
2166 vm_num_host_pages(enum vm_guest_mode mode, unsigned int num_guest_pages)
2167 {
2168         return vm_calc_num_pages(num_guest_pages,
2169                                  vm_guest_mode_params[mode].page_shift,
2170                                  getpageshift(), true);
2171 }
2172
2173 unsigned int
2174 vm_num_guest_pages(enum vm_guest_mode mode, unsigned int num_host_pages)
2175 {
2176         return vm_calc_num_pages(num_host_pages, getpageshift(),
2177                                  vm_guest_mode_params[mode].page_shift, false);
2178 }
2179
2180 unsigned int vm_calc_num_guest_pages(enum vm_guest_mode mode, size_t size)
2181 {
2182         unsigned int n;
2183         n = DIV_ROUND_UP(size, vm_guest_mode_params[mode].page_size);
2184         return vm_adjust_num_guest_pages(mode, n);
2185 }