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