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