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