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