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