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