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