xref: /linux/tools/testing/selftests/kvm/include/kvm_util.h (revision 18812bf31fff2b11c7915596b94c190701952f20)
1 /* SPDX-License-Identifier: GPL-2.0-only */
2 /*
3  * Copyright (C) 2018, Google LLC.
4  */
5 #ifndef SELFTEST_KVM_UTIL_H
6 #define SELFTEST_KVM_UTIL_H
7 
8 #include "test_util.h"
9 
10 #include <linux/compiler.h>
11 #include "linux/hashtable.h"
12 #include "linux/list.h"
13 #include <linux/kernel.h>
14 #include <linux/kvm.h>
15 #include "linux/rbtree.h"
16 #include <linux/types.h>
17 #include <unistd.h>
18 
19 #include <asm/atomic.h>
20 #include <asm/kvm.h>
21 
22 #include <sys/eventfd.h>
23 #include <sys/ioctl.h>
24 
25 #include <pthread.h>
26 
27 #include "kvm_syscalls.h"
28 #include "kvm_util_arch.h"
29 #include "kvm_util_types.h"
30 #include "sparsebit.h"
31 
32 #define KVM_DEV_PATH "/dev/kvm"
33 #define KVM_MAX_VCPUS 512
34 
35 #define NSEC_PER_SEC 1000000000L
36 
37 #define KVM_INVALID_MEMSLOT UINT_MAX
38 
39 struct userspace_mem_region {
40 	struct kvm_userspace_memory_region2 region;
41 	struct sparsebit *unused_phy_pages;
42 	struct sparsebit *protected_phy_pages;
43 	int fd;
44 	off_t offset;
45 	enum vm_mem_backing_src_type backing_src_type;
46 	void *host_mem;
47 	void *host_alias;
48 	void *mmap_start;
49 	void *mmap_alias;
50 	size_t mmap_size;
51 	struct rb_node gpa_node;
52 	struct rb_node hva_node;
53 	struct hlist_node slot_node;
54 };
55 
56 struct kvm_binary_stats {
57 	int fd;
58 	struct kvm_stats_header header;
59 	struct kvm_stats_desc *desc;
60 };
61 
62 struct kvm_vcpu {
63 	struct list_head list;
64 	u32 id;
65 	int fd;
66 	struct kvm_vm *vm;
67 	struct kvm_run *run;
68 #ifdef __x86_64__
69 	struct kvm_cpuid2 *cpuid;
70 #endif
71 #ifdef __aarch64__
72 	struct kvm_vcpu_init init;
73 #endif
74 	struct kvm_binary_stats stats;
75 	struct kvm_dirty_gfn *dirty_gfns;
76 	u32 fetch_index;
77 	u32 dirty_gfns_count;
78 };
79 
80 struct userspace_mem_regions {
81 	struct rb_root gpa_tree;
82 	struct rb_root hva_tree;
83 	DECLARE_HASHTABLE(slot_hash, 9);
84 };
85 
86 /*
87  * Memory region types are passed to various page allocators to communicate
88  * various properties and metadata related to the allocation.  Note, the
89  * descriptions below described the primary usage of each type.  Individual
90  * tests may allocate memory for other purposes.
91  *
92  * By default, all regions except TEST_EXTRA are mapped to memslot '0'.  The
93  * TEST_EXTRA region is left unmapped as it's intended to be used only for test
94  * specific allocations, i.e. should never be used by core/infrastructure code.
95  * Tests can override the memslot for any or all types, e.g. so that all test
96  * data is allocated from a curated memslot.
97  */
98 enum kvm_mem_region_type {
99 	/*
100 	 * The CODE region is used by lib/elf when loading the test's code into
101 	 * guest memory.
102 	 */
103 	MEM_REGION_CODE,
104 	/*
105 	 * The DATA region is used to allocate core data structures, e.g. vCPU
106 	 * stacks, VM exception tables, x86's TSS, etc.
107 	 */
108 	MEM_REGION_DATA,
109 	/*
110 	 * The PT region, a.k.a. Page Table region, is used to allocate page
111 	 * table pages.
112 	 */
113 	MEM_REGION_PT,
114 	/*
115 	 * The TEST_DATA region is used for allocating test data that is either
116 	 * test specific, and/or isn't considered a "core" data structure.
117 	 */
118 	MEM_REGION_TEST_DATA,
119 	/*
120 	 * The TEST_EXTRA region is for special snowflakes, where a test wants
121 	 * to create and use a one-off memslot, without impacting "normal" test
122 	 * data allocations.
123 	 */
124 	MEM_REGION_TEST_EXTRA,
125 	NR_MEM_REGIONS,
126 };
127 
128 struct kvm_mmu {
129 	bool pgd_created;
130 	u64 pgd;
131 	int pgtable_levels;
132 
133 	struct kvm_mmu_arch arch;
134 };
135 
136 struct kvm_vm {
137 	int mode;
138 	unsigned long type;
139 	int kvm_fd;
140 	int fd;
141 	unsigned int page_size;
142 	unsigned int page_shift;
143 	unsigned int pa_bits;
144 	unsigned int va_bits;
145 	u64 max_gfn;
146 	struct list_head vcpus;
147 	struct userspace_mem_regions regions;
148 	struct sparsebit *vpages_valid;
149 	struct sparsebit *vpages_mapped;
150 	bool has_irqchip;
151 	gpa_t ucall_mmio_addr;
152 	gva_t handlers;
153 	u32 dirty_ring_size;
154 	gpa_t gpa_tag_mask;
155 
156 	/*
157 	 * "mmu" is the guest's stage-1, with a short name because the vast
158 	 * majority of tests only care about the stage-1 MMU.
159 	 */
160 	struct kvm_mmu mmu;
161 	struct kvm_mmu stage2_mmu;
162 
163 	struct kvm_vm_arch arch;
164 
165 	struct kvm_binary_stats stats;
166 
167 	u32 memslots[NR_MEM_REGIONS];
168 };
169 
170 struct vcpu_reg_sublist {
171 	const char *name;
172 	long capability;
173 	int feature;
174 	int feature_type;
175 	bool finalize;
176 	__u64 *regs;
177 	__u64 regs_n;
178 	__u64 *rejects_set;
179 	__u64 rejects_set_n;
180 	__u64 *skips_set;
181 	__u64 skips_set_n;
182 };
183 
184 struct vcpu_reg_list {
185 	char *name;
186 	struct vcpu_reg_sublist sublists[];
187 };
188 
189 #define for_each_sublist(c, s)		\
190 	for ((s) = &(c)->sublists[0]; (s)->regs; ++(s))
191 
192 #define kvm_for_each_vcpu(vm, i, vcpu)			\
193 	for ((i) = 0; (i) <= (vm)->last_vcpu_id; (i)++)	\
194 		if (!((vcpu) = vm->vcpus[i]))		\
195 			continue;			\
196 		else
197 
198 struct userspace_mem_region *
199 memslot2region(struct kvm_vm *vm, u32 memslot);
200 
201 static inline struct userspace_mem_region *vm_get_mem_region(struct kvm_vm *vm,
202 							     enum kvm_mem_region_type type)
203 {
204 	TEST_ASSERT(type < NR_MEM_REGIONS,
205 		    "Invalid memory region type '%u'", type);
206 	return memslot2region(vm, vm->memslots[type]);
207 }
208 
209 /* Minimum allocated guest virtual and physical addresses */
210 #define KVM_UTIL_MIN_VADDR		0x2000
211 #define KVM_GUEST_PAGE_TABLE_MIN_PADDR	0x180000
212 
213 #define DEFAULT_GUEST_STACK_VADDR_MIN	0xab6000
214 #define DEFAULT_STACK_PGS		5
215 
216 enum vm_guest_mode {
217 	VM_MODE_P52V48_4K,
218 	VM_MODE_P52V48_16K,
219 	VM_MODE_P52V48_64K,
220 	VM_MODE_P48V48_4K,
221 	VM_MODE_P48V48_16K,
222 	VM_MODE_P48V48_64K,
223 	VM_MODE_P40V48_4K,
224 	VM_MODE_P40V48_16K,
225 	VM_MODE_P40V48_64K,
226 	VM_MODE_PXXVYY_4K,	/* For 48-bit or 57-bit VA, depending on host support */
227 	VM_MODE_P47V64_4K,
228 	VM_MODE_P44V64_4K,
229 	VM_MODE_P36V48_4K,
230 	VM_MODE_P36V48_16K,
231 	VM_MODE_P36V48_64K,
232 	VM_MODE_P47V47_16K,
233 	VM_MODE_P36V47_16K,
234 
235 	VM_MODE_P56V57_4K,	/* For riscv64 */
236 	VM_MODE_P56V48_4K,
237 	VM_MODE_P56V39_4K,
238 	VM_MODE_P50V57_4K,
239 	VM_MODE_P50V48_4K,
240 	VM_MODE_P50V39_4K,
241 	VM_MODE_P41V57_4K,
242 	VM_MODE_P41V48_4K,
243 	VM_MODE_P41V39_4K,
244 
245 	VM_MODE_P52V52_4K,	/* For powerpc64 */
246 	VM_MODE_P52V52_64K,
247 
248 	NUM_VM_MODES,
249 };
250 
251 struct vm_shape {
252 	u32 type;
253 	u8  mode;
254 	u8  pad0;
255 	u16 pad1;
256 };
257 
258 kvm_static_assert(sizeof(struct vm_shape) == sizeof(u64));
259 
260 #define VM_TYPE_DEFAULT			0
261 
262 #define VM_SHAPE(__mode)			\
263 ({						\
264 	struct vm_shape shape = {		\
265 		.mode = (__mode),		\
266 		.type = VM_TYPE_DEFAULT		\
267 	};					\
268 						\
269 	shape;					\
270 })
271 
272 extern enum vm_guest_mode vm_mode_default;
273 
274 #if defined(__aarch64__)
275 
276 #define VM_MODE_DEFAULT			vm_mode_default
277 #define MIN_PAGE_SHIFT			12U
278 #define ptes_per_page(page_size)	((page_size) / 8)
279 
280 #elif defined(__x86_64__)
281 
282 #define VM_MODE_DEFAULT			VM_MODE_PXXVYY_4K
283 #define MIN_PAGE_SHIFT			12U
284 #define ptes_per_page(page_size)	((page_size) / 8)
285 
286 #elif defined(__s390x__)
287 
288 #define VM_MODE_DEFAULT			VM_MODE_P44V64_4K
289 #define MIN_PAGE_SHIFT			12U
290 #define ptes_per_page(page_size)	((page_size) / 16)
291 
292 #elif defined(__riscv)
293 
294 #if __riscv_xlen == 32
295 #error "RISC-V 32-bit kvm selftests not supported"
296 #endif
297 
298 #define VM_MODE_DEFAULT			vm_mode_default
299 #define MIN_PAGE_SHIFT			12U
300 #define ptes_per_page(page_size)	((page_size) / 8)
301 
302 #elif defined(__loongarch__)
303 #define VM_MODE_DEFAULT			VM_MODE_P47V47_16K
304 #define MIN_PAGE_SHIFT			12U
305 #define ptes_per_page(page_size)	((page_size) / 8)
306 
307 #elif defined(__powerpc64__)
308 
309 #define VM_MODE_DEFAULT			vm_mode_default
310 #define MIN_PAGE_SHIFT			12U
311 #define ptes_per_page(page_size)	((page_size) / 8)
312 
313 #endif
314 
315 #define VM_SHAPE_DEFAULT	VM_SHAPE(VM_MODE_DEFAULT)
316 
317 #define MIN_PAGE_SIZE		(1U << MIN_PAGE_SHIFT)
318 #define PTES_PER_MIN_PAGE	ptes_per_page(MIN_PAGE_SIZE)
319 
320 struct vm_guest_mode_params {
321 	unsigned int pa_bits;
322 	unsigned int va_bits;
323 	unsigned int page_size;
324 	unsigned int page_shift;
325 };
326 extern const struct vm_guest_mode_params vm_guest_mode_params[];
327 
328 int __open_path_or_exit(const char *path, int flags, const char *enoent_help);
329 int open_path_or_exit(const char *path, int flags);
330 int open_kvm_dev_path_or_exit(void);
331 
332 int kvm_get_module_param_integer(const char *module_name, const char *param);
333 bool kvm_get_module_param_bool(const char *module_name, const char *param);
334 
335 static inline bool get_kvm_param_bool(const char *param)
336 {
337 	return kvm_get_module_param_bool("kvm", param);
338 }
339 
340 static inline int get_kvm_param_integer(const char *param)
341 {
342 	return kvm_get_module_param_integer("kvm", param);
343 }
344 
345 unsigned int kvm_check_cap(long cap);
346 
347 static inline bool kvm_has_cap(long cap)
348 {
349 	return kvm_check_cap(cap);
350 }
351 
352 /*
353  * Use the "inner", double-underscore macro when reporting errors from within
354  * other macros so that the name of ioctl() and not its literal numeric value
355  * is printed on error.  The "outer" macro is strongly preferred when reporting
356  * errors "directly", i.e. without an additional layer of macros, as it reduces
357  * the probability of passing in the wrong string.
358  */
359 #define __KVM_IOCTL_ERROR(_name, _ret)	__KVM_SYSCALL_ERROR(_name, _ret)
360 #define KVM_IOCTL_ERROR(_ioctl, _ret) __KVM_IOCTL_ERROR(#_ioctl, _ret)
361 
362 #define kvm_do_ioctl(fd, cmd, arg)						\
363 ({										\
364 	kvm_static_assert(!_IOC_SIZE(cmd) || sizeof(*arg) == _IOC_SIZE(cmd));	\
365 	ioctl(fd, cmd, arg);							\
366 })
367 
368 #define __kvm_ioctl(kvm_fd, cmd, arg)				\
369 	kvm_do_ioctl(kvm_fd, cmd, arg)
370 
371 #define kvm_ioctl(kvm_fd, cmd, arg)				\
372 ({								\
373 	int ret = __kvm_ioctl(kvm_fd, cmd, arg);		\
374 								\
375 	TEST_ASSERT(!ret, __KVM_IOCTL_ERROR(#cmd, ret));	\
376 })
377 
378 static __always_inline void static_assert_is_vm(struct kvm_vm *vm) { }
379 
380 #define __vm_ioctl(vm, cmd, arg)				\
381 ({								\
382 	static_assert_is_vm(vm);				\
383 	kvm_do_ioctl((vm)->fd, cmd, arg);			\
384 })
385 
386 /*
387  * Assert that a VM or vCPU ioctl() succeeded, with extra magic to detect if
388  * the ioctl() failed because KVM killed/bugged the VM.  To detect a dead VM,
389  * probe KVM_CAP_USER_MEMORY, which (a) has been supported by KVM since before
390  * selftests existed and (b) should never outright fail, i.e. is supposed to
391  * return 0 or 1.  If KVM kills a VM, KVM returns -EIO for all ioctl()s for the
392  * VM and its vCPUs, including KVM_CHECK_EXTENSION.
393  */
394 #define __TEST_ASSERT_VM_VCPU_IOCTL(cond, name, ret, vm)				\
395 do {											\
396 	int __errno = errno;								\
397 											\
398 	static_assert_is_vm(vm);							\
399 											\
400 	if (cond)									\
401 		break;									\
402 											\
403 	if (errno == EIO &&								\
404 	    __vm_ioctl(vm, KVM_CHECK_EXTENSION, (void *)KVM_CAP_USER_MEMORY) < 0) {	\
405 		TEST_ASSERT(errno == EIO, "KVM killed the VM, should return -EIO");	\
406 		TEST_FAIL("KVM killed/bugged the VM, check the kernel log for clues");	\
407 	}										\
408 	errno = __errno;								\
409 	TEST_ASSERT(cond, __KVM_IOCTL_ERROR(name, ret));				\
410 } while (0)
411 
412 #define TEST_ASSERT_VM_VCPU_IOCTL(cond, cmd, ret, vm)		\
413 	__TEST_ASSERT_VM_VCPU_IOCTL(cond, #cmd, ret, vm)
414 
415 #define vm_ioctl(vm, cmd, arg)					\
416 ({								\
417 	int ret = __vm_ioctl(vm, cmd, arg);			\
418 								\
419 	__TEST_ASSERT_VM_VCPU_IOCTL(!ret, #cmd, ret, vm);		\
420 })
421 
422 static __always_inline void static_assert_is_vcpu(struct kvm_vcpu *vcpu) { }
423 
424 #define __vcpu_ioctl(vcpu, cmd, arg)				\
425 ({								\
426 	static_assert_is_vcpu(vcpu);				\
427 	kvm_do_ioctl((vcpu)->fd, cmd, arg);			\
428 })
429 
430 #define vcpu_ioctl(vcpu, cmd, arg)				\
431 ({								\
432 	int ret = __vcpu_ioctl(vcpu, cmd, arg);			\
433 								\
434 	__TEST_ASSERT_VM_VCPU_IOCTL(!ret, #cmd, ret, (vcpu)->vm);	\
435 })
436 
437 #define __gmem_ioctl(gmem_fd, cmd, arg)				\
438 	kvm_do_ioctl(gmem_fd, cmd, arg)
439 
440 #define gmem_ioctl(gmem_fd, cmd, arg)				\
441 ({								\
442 	int ret = __gmem_ioctl(gmem_fd, cmd, arg);		\
443 								\
444 	TEST_ASSERT(!ret, __KVM_IOCTL_ERROR(#cmd, ret));	\
445 })
446 
447 /*
448  * Looks up and returns the value corresponding to the capability
449  * (KVM_CAP_*) given by cap.
450  */
451 static inline int vm_check_cap(struct kvm_vm *vm, long cap)
452 {
453 	int ret =  __vm_ioctl(vm, KVM_CHECK_EXTENSION, (void *)cap);
454 
455 	TEST_ASSERT_VM_VCPU_IOCTL(ret >= 0, KVM_CHECK_EXTENSION, ret, vm);
456 	return ret;
457 }
458 
459 static inline int __vm_enable_cap(struct kvm_vm *vm, u32 cap, u64 arg0)
460 {
461 	struct kvm_enable_cap enable_cap = { .cap = cap, .args = { arg0 } };
462 
463 	return __vm_ioctl(vm, KVM_ENABLE_CAP, &enable_cap);
464 }
465 
466 static inline void vm_enable_cap(struct kvm_vm *vm, u32 cap, u64 arg0)
467 {
468 	struct kvm_enable_cap enable_cap = { .cap = cap, .args = { arg0 } };
469 
470 	vm_ioctl(vm, KVM_ENABLE_CAP, &enable_cap);
471 }
472 
473 int kvm_gpa_to_guest_memfd(struct kvm_vm *vm, gpa_t gpa, off_t *fd_offset,
474 			   size_t *nr_bytes);
475 
476 /*
477  * KVM_SET_MEMORY_ATTRIBUTES{,2} overwrites _all_ attributes.  These
478  * flows need significant enhancements to support multiple attributes.
479  */
480 #define TEST_ASSERT_SUPPORTED_ATTRIBUTES(attributes)				\
481 	TEST_ASSERT(!(attributes) || (attributes) == KVM_MEMORY_ATTRIBUTE_PRIVATE,	\
482 		    "Update me to support multiple attributes!")
483 
484 static inline void vm_set_memory_attributes(struct kvm_vm *vm, gpa_t gpa,
485 					    size_t size, u64 attributes)
486 {
487 	struct kvm_memory_attributes attr = {
488 		.attributes = attributes,
489 		.address = gpa,
490 		.size = size,
491 		.flags = 0,
492 	};
493 
494 	TEST_ASSERT_SUPPORTED_ATTRIBUTES(attributes);
495 
496 	vm_ioctl(vm, KVM_SET_MEMORY_ATTRIBUTES, &attr);
497 }
498 
499 static inline int __gmem_set_memory_attributes(int fd, u64 offset,
500 					       size_t size, u64 attributes,
501 					       u64 *error_offset)
502 {
503 	struct kvm_memory_attributes2 attr = {
504 		.attributes = attributes,
505 		.offset = offset,
506 		.size = size,
507 		.flags = 0,
508 		.error_offset = 0,
509 	};
510 	int r;
511 
512 	r = __gmem_ioctl(fd, KVM_SET_MEMORY_ATTRIBUTES2, &attr);
513 
514 	/* Copy error_offset regardless of r so caller can check. */
515 	if (error_offset)
516 		*error_offset = attr.error_offset;
517 
518 	return r;
519 }
520 
521 static inline int __gmem_set_private(int fd, u64 offset, size_t size,
522 				     u64 *error_offset)
523 {
524 	return __gmem_set_memory_attributes(fd, offset, size,
525 					    KVM_MEMORY_ATTRIBUTE_PRIVATE,
526 					    error_offset);
527 }
528 
529 static inline int __gmem_set_shared(int fd, u64 offset, size_t size,
530 				    u64 *error_offset)
531 {
532 	return __gmem_set_memory_attributes(fd, offset, size, 0,
533 					    error_offset);
534 }
535 
536 static inline void gmem_set_memory_attributes(int fd, u64 offset,
537 					      size_t size, u64 attributes)
538 {
539 	struct kvm_memory_attributes2 attr = {
540 		.attributes = attributes,
541 		.offset = offset,
542 		.size = size,
543 		.flags = 0,
544 	};
545 
546 	TEST_ASSERT_SUPPORTED_ATTRIBUTES(attributes);
547 
548 	__TEST_REQUIRE(kvm_check_cap(KVM_CAP_GUEST_MEMFD_MEMORY_ATTRIBUTES) > 0,
549 		       "No valid attributes for guest_memfd ioctl!");
550 
551 	gmem_ioctl(fd, KVM_SET_MEMORY_ATTRIBUTES2, &attr);
552 }
553 
554 static inline void gmem_set_private(int fd, u64 offset, size_t size)
555 {
556 	gmem_set_memory_attributes(fd, offset, size,
557 				   KVM_MEMORY_ATTRIBUTE_PRIVATE);
558 }
559 
560 static inline void gmem_set_shared(int fd, u64 offset, size_t size)
561 {
562 	gmem_set_memory_attributes(fd, offset, size, 0);
563 }
564 
565 static inline void vm_mem_set_memory_attributes(struct kvm_vm *vm, gpa_t gpa,
566 						size_t size, u64 attrs)
567 {
568 	if (kvm_has_gmem_attributes) {
569 		gpa_t end = gpa + size;
570 		off_t fd_offset;
571 		gpa_t addr;
572 		size_t len;
573 		int fd;
574 
575 		for (addr = gpa; addr < end; addr += len) {
576 			fd = kvm_gpa_to_guest_memfd(vm, addr, &fd_offset, &len);
577 			len = min(end - addr, len);
578 
579 			gmem_set_memory_attributes(fd, fd_offset, len, attrs);
580 		}
581 	} else {
582 		vm_set_memory_attributes(vm, gpa, size, attrs);
583 	}
584 }
585 
586 static inline void vm_mem_set_private(struct kvm_vm *vm, gpa_t gpa,
587 				      size_t size)
588 {
589 	vm_mem_set_memory_attributes(vm, gpa, size,
590 				     KVM_MEMORY_ATTRIBUTE_PRIVATE);
591 }
592 
593 static inline void vm_mem_set_shared(struct kvm_vm *vm, gpa_t gpa,
594 				     size_t size)
595 {
596 	vm_mem_set_memory_attributes(vm, gpa, size, 0);
597 }
598 
599 void vm_guest_mem_fallocate(struct kvm_vm *vm, gpa_t gpa, u64 size,
600 			    bool punch_hole);
601 
602 static inline void vm_guest_mem_punch_hole(struct kvm_vm *vm, gpa_t gpa,
603 					   u64 size)
604 {
605 	vm_guest_mem_fallocate(vm, gpa, size, true);
606 }
607 
608 static inline void vm_guest_mem_allocate(struct kvm_vm *vm, gpa_t gpa,
609 					 u64 size)
610 {
611 	vm_guest_mem_fallocate(vm, gpa, size, false);
612 }
613 
614 void vm_enable_dirty_ring(struct kvm_vm *vm, u32 ring_size);
615 const char *vm_guest_mode_string(u32 i);
616 
617 void kvm_vm_free(struct kvm_vm *vmp);
618 void kvm_vm_restart(struct kvm_vm *vmp);
619 void kvm_vm_release(struct kvm_vm *vmp);
620 void kvm_vm_elf_load(struct kvm_vm *vm, const char *filename);
621 int kvm_memfd_alloc(size_t size, bool hugepages);
622 
623 void vm_dump(FILE *stream, struct kvm_vm *vm, u8 indent);
624 
625 static inline void kvm_vm_get_dirty_log(struct kvm_vm *vm, int slot, void *log)
626 {
627 	struct kvm_dirty_log args = { .dirty_bitmap = log, .slot = slot };
628 
629 	vm_ioctl(vm, KVM_GET_DIRTY_LOG, &args);
630 }
631 
632 static inline void kvm_vm_clear_dirty_log(struct kvm_vm *vm, int slot, void *log,
633 					  u64 first_page, u32 num_pages)
634 {
635 	struct kvm_clear_dirty_log args = {
636 		.dirty_bitmap = log,
637 		.slot = slot,
638 		.first_page = first_page,
639 		.num_pages = num_pages
640 	};
641 
642 	vm_ioctl(vm, KVM_CLEAR_DIRTY_LOG, &args);
643 }
644 
645 static inline u32 kvm_vm_reset_dirty_ring(struct kvm_vm *vm)
646 {
647 	return __vm_ioctl(vm, KVM_RESET_DIRTY_RINGS, NULL);
648 }
649 
650 static inline void kvm_vm_register_coalesced_io(struct kvm_vm *vm,
651 						u64 address,
652 						u64 size, bool pio)
653 {
654 	struct kvm_coalesced_mmio_zone zone = {
655 		.addr = address,
656 		.size = size,
657 		.pio  = pio,
658 	};
659 
660 	vm_ioctl(vm, KVM_REGISTER_COALESCED_MMIO, &zone);
661 }
662 
663 static inline void kvm_vm_unregister_coalesced_io(struct kvm_vm *vm,
664 						  u64 address,
665 						  u64 size, bool pio)
666 {
667 	struct kvm_coalesced_mmio_zone zone = {
668 		.addr = address,
669 		.size = size,
670 		.pio  = pio,
671 	};
672 
673 	vm_ioctl(vm, KVM_UNREGISTER_COALESCED_MMIO, &zone);
674 }
675 
676 static inline int vm_get_stats_fd(struct kvm_vm *vm)
677 {
678 	int fd = __vm_ioctl(vm, KVM_GET_STATS_FD, NULL);
679 
680 	TEST_ASSERT_VM_VCPU_IOCTL(fd >= 0, KVM_GET_STATS_FD, fd, vm);
681 	return fd;
682 }
683 
684 static inline int __kvm_irqfd(struct kvm_vm *vm, u32 gsi, int eventfd,
685 			      u32 flags)
686 {
687 	struct kvm_irqfd irqfd = {
688 		.fd = eventfd,
689 		.gsi = gsi,
690 		.flags = flags,
691 		.resamplefd = -1,
692 	};
693 
694 	return __vm_ioctl(vm, KVM_IRQFD, &irqfd);
695 }
696 
697 static inline void kvm_irqfd(struct kvm_vm *vm, u32 gsi, int eventfd, u32 flags)
698 {
699 	int ret = __kvm_irqfd(vm, gsi, eventfd, flags);
700 
701 	TEST_ASSERT_VM_VCPU_IOCTL(!ret, KVM_IRQFD, ret, vm);
702 }
703 
704 static inline void kvm_assign_irqfd(struct kvm_vm *vm, u32 gsi, int eventfd)
705 {
706 	kvm_irqfd(vm, gsi, eventfd, 0);
707 }
708 
709 static inline void kvm_deassign_irqfd(struct kvm_vm *vm, u32 gsi, int eventfd)
710 {
711 	kvm_irqfd(vm, gsi, eventfd, KVM_IRQFD_FLAG_DEASSIGN);
712 }
713 
714 static inline int kvm_new_eventfd(void)
715 {
716 	int fd = eventfd(0, 0);
717 
718 	TEST_ASSERT(fd >= 0, __KVM_SYSCALL_ERROR("eventfd()", fd));
719 	return fd;
720 }
721 
722 static inline void read_stats_header(int stats_fd, struct kvm_stats_header *header)
723 {
724 	ssize_t ret;
725 
726 	ret = pread(stats_fd, header, sizeof(*header), 0);
727 	TEST_ASSERT(ret == sizeof(*header),
728 		    "Failed to read '%lu' header bytes, ret = '%ld'",
729 		    sizeof(*header), ret);
730 }
731 
732 struct kvm_stats_desc *read_stats_descriptors(int stats_fd,
733 					      struct kvm_stats_header *header);
734 
735 static inline ssize_t get_stats_descriptor_size(struct kvm_stats_header *header)
736 {
737 	 /*
738 	  * The base size of the descriptor is defined by KVM's ABI, but the
739 	  * size of the name field is variable, as far as KVM's ABI is
740 	  * concerned. For a given instance of KVM, the name field is the same
741 	  * size for all stats and is provided in the overall stats header.
742 	  */
743 	return sizeof(struct kvm_stats_desc) + header->name_size;
744 }
745 
746 static inline struct kvm_stats_desc *get_stats_descriptor(struct kvm_stats_desc *stats,
747 							  int index,
748 							  struct kvm_stats_header *header)
749 {
750 	/*
751 	 * Note, size_desc includes the size of the name field, which is
752 	 * variable. i.e. this is NOT equivalent to &stats_desc[i].
753 	 */
754 	return (void *)stats + index * get_stats_descriptor_size(header);
755 }
756 
757 void read_stat_data(int stats_fd, struct kvm_stats_header *header,
758 		    struct kvm_stats_desc *desc, u64 *data,
759 		    size_t max_elements);
760 
761 void kvm_get_stat(struct kvm_binary_stats *stats, const char *name,
762 		  u64 *data, size_t max_elements);
763 
764 #define __get_stat(stats, stat)							\
765 ({										\
766 	u64 data;								\
767 										\
768 	kvm_get_stat(stats, #stat, &data, 1);					\
769 	data;									\
770 })
771 
772 #define vm_get_stat(vm, stat) __get_stat(&(vm)->stats, stat)
773 #define vcpu_get_stat(vcpu, stat) __get_stat(&(vcpu)->stats, stat)
774 
775 static inline bool read_smt_control(char *buf, size_t buf_size)
776 {
777 	FILE *f = fopen("/sys/devices/system/cpu/smt/control", "r");
778 	bool ret;
779 
780 	if (!f)
781 		return false;
782 
783 	ret = fread(buf, sizeof(*buf), buf_size, f) > 0;
784 	fclose(f);
785 
786 	return ret;
787 }
788 
789 static inline bool is_smt_possible(void)
790 {
791 	char buf[16];
792 
793 	if (read_smt_control(buf, sizeof(buf)) &&
794 	    (!strncmp(buf, "forceoff", 8) || !strncmp(buf, "notsupported", 12)))
795 		return false;
796 
797 	return true;
798 }
799 
800 static inline bool is_smt_on(void)
801 {
802 	char buf[16];
803 
804 	if (read_smt_control(buf, sizeof(buf)) && !strncmp(buf, "on", 2))
805 		return true;
806 
807 	return false;
808 }
809 
810 void vm_create_irqchip(struct kvm_vm *vm);
811 
812 static inline int __vm_create_guest_memfd(struct kvm_vm *vm, u64 size,
813 					  u64 flags)
814 {
815 	struct kvm_create_guest_memfd guest_memfd = {
816 		.size = size,
817 		.flags = flags,
818 	};
819 
820 	return __vm_ioctl(vm, KVM_CREATE_GUEST_MEMFD, &guest_memfd);
821 }
822 
823 static inline int vm_create_guest_memfd(struct kvm_vm *vm, u64 size,
824 					u64 flags)
825 {
826 	int fd = __vm_create_guest_memfd(vm, size, flags);
827 
828 	TEST_ASSERT(fd >= 0, KVM_IOCTL_ERROR(KVM_CREATE_GUEST_MEMFD, fd));
829 	return fd;
830 }
831 
832 void vm_set_user_memory_region(struct kvm_vm *vm, u32 slot, u32 flags,
833 			       gpa_t gpa, u64 size, void *hva);
834 int __vm_set_user_memory_region(struct kvm_vm *vm, u32 slot, u32 flags,
835 				gpa_t gpa, u64 size, void *hva);
836 void vm_set_user_memory_region2(struct kvm_vm *vm, u32 slot, u32 flags,
837 				gpa_t gpa, u64 size, void *hva,
838 				u32 gmem_fd, u64 gmem_offset);
839 int __vm_set_user_memory_region2(struct kvm_vm *vm, u32 slot, u32 flags,
840 				 gpa_t gpa, u64 size, void *hva,
841 				 u32 gmem_fd, u64 gmem_offset);
842 
843 void vm_userspace_mem_region_add(struct kvm_vm *vm,
844 				 enum vm_mem_backing_src_type src_type,
845 				 gpa_t gpa, u32 slot, u64 npages, u32 flags);
846 void vm_mem_add(struct kvm_vm *vm, enum vm_mem_backing_src_type src_type,
847 		gpa_t gpa, u32 slot, u64 npages, u32 flags,
848 		int gmem_fd, u64 gmem_offset, u64 gmem_flags);
849 
850 
851 static inline void ____vm_override_mem_region(struct kvm_vm *vm,
852 					      enum kvm_mem_region_type type,
853 					      u32 slot)
854 {
855 	TEST_ASSERT(vm->memslots[type] == KVM_INVALID_MEMSLOT,
856 		    "Memory region type '%u' was already overridden with slot=%u",
857 		    type, vm->memslots[type]);
858 
859 	vm->memslots[type] = slot;
860 }
861 
862 static inline void __vm_override_mem_region(struct kvm_vm *vm,
863 					    enum kvm_mem_region_type type,
864 					    enum vm_mem_backing_src_type src_type,
865 					    gpa_t gpa, u32 slot, u64 npages,
866 					    u32 flags)
867 {
868 	____vm_override_mem_region(vm, type, slot);
869 	vm_userspace_mem_region_add(vm, src_type, gpa, slot, npages, flags);
870 }
871 
872 static inline void vm_override_mem_region(struct kvm_vm *vm,
873 					  enum kvm_mem_region_type type,
874 					  enum vm_mem_backing_src_type src_type,
875 					  gpa_t gpa, u32 slot, u64 npages)
876 {
877 	__vm_override_mem_region(vm, type, src_type, gpa, slot, npages, 0);
878 }
879 
880 #ifndef vm_arch_has_protected_memory
881 static inline bool vm_arch_has_protected_memory(struct kvm_vm *vm)
882 {
883 	return false;
884 }
885 #endif
886 
887 void vm_mem_region_set_flags(struct kvm_vm *vm, u32 slot, u32 flags);
888 void vm_mem_region_reload(struct kvm_vm *vm, u32 slot);
889 void vm_mem_region_move(struct kvm_vm *vm, u32 slot, u64 new_gpa);
890 void vm_mem_region_delete(struct kvm_vm *vm, u32 slot);
891 struct kvm_vcpu *__vm_vcpu_add(struct kvm_vm *vm, u32 vcpu_id);
892 void vm_populate_gva_bitmap(struct kvm_vm *vm);
893 gva_t vm_unused_gva_gap(struct kvm_vm *vm, size_t sz, gva_t min_gva);
894 gva_t vm_alloc(struct kvm_vm *vm, size_t sz, gva_t min_gva);
895 gva_t __vm_alloc(struct kvm_vm *vm, size_t sz, gva_t min_gva,
896 		 enum kvm_mem_region_type type);
897 gva_t vm_alloc_shared(struct kvm_vm *vm, size_t sz, gva_t min_gva,
898 		      enum kvm_mem_region_type type);
899 gva_t vm_alloc_pages(struct kvm_vm *vm, int nr_pages);
900 gva_t __vm_alloc_page(struct kvm_vm *vm, enum kvm_mem_region_type type);
901 gva_t vm_alloc_page(struct kvm_vm *vm);
902 
903 void virt_map(struct kvm_vm *vm, gva_t gva, gpa_t gpa,
904 	      unsigned int npages);
905 void *addr_gpa2hva(struct kvm_vm *vm, gpa_t gpa);
906 void *addr_gva2hva(struct kvm_vm *vm, gva_t gva);
907 gpa_t addr_hva2gpa(struct kvm_vm *vm, void *hva);
908 void *addr_gpa2alias(struct kvm_vm *vm, gpa_t gpa);
909 
910 static inline int kvm_slot_to_fd(struct kvm_vm *vm, u32 slot)
911 {
912 	return memslot2region(vm, slot)->fd;
913 }
914 
915 #ifndef vcpu_arch_put_guest
916 #define vcpu_arch_put_guest(mem, val) do { (mem) = (val); } while (0)
917 #endif
918 
919 static inline gpa_t vm_untag_gpa(struct kvm_vm *vm, gpa_t gpa)
920 {
921 	return gpa & ~vm->gpa_tag_mask;
922 }
923 
924 void vcpu_run(struct kvm_vcpu *vcpu);
925 int _vcpu_run(struct kvm_vcpu *vcpu);
926 
927 static inline int __vcpu_run(struct kvm_vcpu *vcpu)
928 {
929 	return __vcpu_ioctl(vcpu, KVM_RUN, NULL);
930 }
931 
932 void vcpu_run_complete_io(struct kvm_vcpu *vcpu);
933 struct kvm_reg_list *vcpu_get_reg_list(struct kvm_vcpu *vcpu);
934 
935 static inline void vcpu_enable_cap(struct kvm_vcpu *vcpu, u32 cap,
936 				   u64 arg0)
937 {
938 	struct kvm_enable_cap enable_cap = { .cap = cap, .args = { arg0 } };
939 
940 	vcpu_ioctl(vcpu, KVM_ENABLE_CAP, &enable_cap);
941 }
942 
943 static inline void vcpu_guest_debug_set(struct kvm_vcpu *vcpu,
944 					struct kvm_guest_debug *debug)
945 {
946 	vcpu_ioctl(vcpu, KVM_SET_GUEST_DEBUG, debug);
947 }
948 
949 static inline void vcpu_mp_state_get(struct kvm_vcpu *vcpu,
950 				     struct kvm_mp_state *mp_state)
951 {
952 	vcpu_ioctl(vcpu, KVM_GET_MP_STATE, mp_state);
953 }
954 static inline void vcpu_mp_state_set(struct kvm_vcpu *vcpu,
955 				     struct kvm_mp_state *mp_state)
956 {
957 	vcpu_ioctl(vcpu, KVM_SET_MP_STATE, mp_state);
958 }
959 
960 static inline void vcpu_regs_get(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
961 {
962 	vcpu_ioctl(vcpu, KVM_GET_REGS, regs);
963 }
964 
965 static inline void vcpu_regs_set(struct kvm_vcpu *vcpu, struct kvm_regs *regs)
966 {
967 	vcpu_ioctl(vcpu, KVM_SET_REGS, regs);
968 }
969 static inline void vcpu_sregs_get(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
970 {
971 	vcpu_ioctl(vcpu, KVM_GET_SREGS, sregs);
972 
973 }
974 static inline void vcpu_sregs_set(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
975 {
976 	vcpu_ioctl(vcpu, KVM_SET_SREGS, sregs);
977 }
978 static inline int _vcpu_sregs_set(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs)
979 {
980 	return __vcpu_ioctl(vcpu, KVM_SET_SREGS, sregs);
981 }
982 static inline void vcpu_fpu_get(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
983 {
984 	vcpu_ioctl(vcpu, KVM_GET_FPU, fpu);
985 }
986 static inline void vcpu_fpu_set(struct kvm_vcpu *vcpu, struct kvm_fpu *fpu)
987 {
988 	vcpu_ioctl(vcpu, KVM_SET_FPU, fpu);
989 }
990 
991 static inline int __vcpu_get_reg(struct kvm_vcpu *vcpu, u64 id, void *addr)
992 {
993 	struct kvm_one_reg reg = { .id = id, .addr = (u64)addr };
994 
995 	return __vcpu_ioctl(vcpu, KVM_GET_ONE_REG, &reg);
996 }
997 
998 static inline int __vcpu_set_reg(struct kvm_vcpu *vcpu, u64 id, u64 val)
999 {
1000 	struct kvm_one_reg reg = { .id = id, .addr = (u64)&val };
1001 
1002 	return __vcpu_ioctl(vcpu, KVM_SET_ONE_REG, &reg);
1003 }
1004 
1005 static inline u64 vcpu_get_reg(struct kvm_vcpu *vcpu, u64 id)
1006 {
1007 	u64 val;
1008 	struct kvm_one_reg reg = { .id = id, .addr = (u64)&val };
1009 
1010 	TEST_ASSERT(KVM_REG_SIZE(id) <= sizeof(val), "Reg %lx too big", id);
1011 
1012 	vcpu_ioctl(vcpu, KVM_GET_ONE_REG, &reg);
1013 	return val;
1014 }
1015 
1016 static inline void vcpu_set_reg(struct kvm_vcpu *vcpu, u64 id, u64 val)
1017 {
1018 	struct kvm_one_reg reg = { .id = id, .addr = (u64)&val };
1019 
1020 	TEST_ASSERT(KVM_REG_SIZE(id) <= sizeof(val), "Reg %lx too big", id);
1021 
1022 	vcpu_ioctl(vcpu, KVM_SET_ONE_REG, &reg);
1023 }
1024 
1025 #ifdef __KVM_HAVE_VCPU_EVENTS
1026 static inline void vcpu_events_get(struct kvm_vcpu *vcpu,
1027 				   struct kvm_vcpu_events *events)
1028 {
1029 	vcpu_ioctl(vcpu, KVM_GET_VCPU_EVENTS, events);
1030 }
1031 static inline void vcpu_events_set(struct kvm_vcpu *vcpu,
1032 				   struct kvm_vcpu_events *events)
1033 {
1034 	vcpu_ioctl(vcpu, KVM_SET_VCPU_EVENTS, events);
1035 }
1036 #endif
1037 #ifdef __x86_64__
1038 static inline void vcpu_nested_state_get(struct kvm_vcpu *vcpu,
1039 					 struct kvm_nested_state *state)
1040 {
1041 	vcpu_ioctl(vcpu, KVM_GET_NESTED_STATE, state);
1042 }
1043 static inline int __vcpu_nested_state_set(struct kvm_vcpu *vcpu,
1044 					  struct kvm_nested_state *state)
1045 {
1046 	return __vcpu_ioctl(vcpu, KVM_SET_NESTED_STATE, state);
1047 }
1048 
1049 static inline void vcpu_nested_state_set(struct kvm_vcpu *vcpu,
1050 					 struct kvm_nested_state *state)
1051 {
1052 	vcpu_ioctl(vcpu, KVM_SET_NESTED_STATE, state);
1053 }
1054 #endif
1055 static inline int vcpu_get_stats_fd(struct kvm_vcpu *vcpu)
1056 {
1057 	int fd = __vcpu_ioctl(vcpu, KVM_GET_STATS_FD, NULL);
1058 
1059 	TEST_ASSERT_VM_VCPU_IOCTL(fd >= 0, KVM_GET_STATS_FD, fd, vcpu->vm);
1060 	return fd;
1061 }
1062 
1063 int __kvm_has_device_attr(int dev_fd, u32 group, u64 attr);
1064 
1065 static inline void kvm_has_device_attr(int dev_fd, u32 group, u64 attr)
1066 {
1067 	int ret = __kvm_has_device_attr(dev_fd, group, attr);
1068 
1069 	TEST_ASSERT(!ret, "KVM_HAS_DEVICE_ATTR failed, rc: %i errno: %i", ret, errno);
1070 }
1071 
1072 int __kvm_device_attr_get(int dev_fd, u32 group, u64 attr, void *val);
1073 
1074 static inline void kvm_device_attr_get(int dev_fd, u32 group,
1075 				       u64 attr, void *val)
1076 {
1077 	int ret = __kvm_device_attr_get(dev_fd, group, attr, val);
1078 
1079 	TEST_ASSERT(!ret, KVM_IOCTL_ERROR(KVM_GET_DEVICE_ATTR, ret));
1080 }
1081 
1082 int __kvm_device_attr_set(int dev_fd, u32 group, u64 attr, void *val);
1083 
1084 static inline void kvm_device_attr_set(int dev_fd, u32 group,
1085 				       u64 attr, void *val)
1086 {
1087 	int ret = __kvm_device_attr_set(dev_fd, group, attr, val);
1088 
1089 	TEST_ASSERT(!ret, KVM_IOCTL_ERROR(KVM_SET_DEVICE_ATTR, ret));
1090 }
1091 
1092 static inline int __vcpu_has_device_attr(struct kvm_vcpu *vcpu, u32 group,
1093 					 u64 attr)
1094 {
1095 	return __kvm_has_device_attr(vcpu->fd, group, attr);
1096 }
1097 
1098 static inline void vcpu_has_device_attr(struct kvm_vcpu *vcpu, u32 group,
1099 					u64 attr)
1100 {
1101 	kvm_has_device_attr(vcpu->fd, group, attr);
1102 }
1103 
1104 static inline int __vcpu_device_attr_get(struct kvm_vcpu *vcpu, u32 group,
1105 					 u64 attr, void *val)
1106 {
1107 	return __kvm_device_attr_get(vcpu->fd, group, attr, val);
1108 }
1109 
1110 static inline void vcpu_device_attr_get(struct kvm_vcpu *vcpu, u32 group,
1111 					u64 attr, void *val)
1112 {
1113 	kvm_device_attr_get(vcpu->fd, group, attr, val);
1114 }
1115 
1116 static inline int __vcpu_device_attr_set(struct kvm_vcpu *vcpu, u32 group,
1117 					 u64 attr, void *val)
1118 {
1119 	return __kvm_device_attr_set(vcpu->fd, group, attr, val);
1120 }
1121 
1122 static inline void vcpu_device_attr_set(struct kvm_vcpu *vcpu, u32 group,
1123 					u64 attr, void *val)
1124 {
1125 	kvm_device_attr_set(vcpu->fd, group, attr, val);
1126 }
1127 
1128 int __kvm_test_create_device(struct kvm_vm *vm, u64 type);
1129 int __kvm_create_device(struct kvm_vm *vm, u64 type);
1130 
1131 static inline int kvm_create_device(struct kvm_vm *vm, u64 type)
1132 {
1133 	int fd = __kvm_create_device(vm, type);
1134 
1135 	TEST_ASSERT(fd >= 0, KVM_IOCTL_ERROR(KVM_CREATE_DEVICE, fd));
1136 	return fd;
1137 }
1138 
1139 void *vcpu_map_dirty_ring(struct kvm_vcpu *vcpu);
1140 
1141 /*
1142  * VM VCPU Args Set
1143  *
1144  * Input Args:
1145  *   vcpu - vCPU
1146  *   num - number of arguments
1147  *   ... - arguments, each of type u64
1148  *
1149  * Output Args: None
1150  *
1151  * Return: None
1152  *
1153  * Sets the first @num input parameters for the function at @vcpu's entry point,
1154  * per the C calling convention of the architecture, to the values given as
1155  * variable args. Each of the variable args is expected to be of type u64.
1156  * The maximum @num can be is specific to the architecture.
1157  */
1158 void vcpu_args_set(struct kvm_vcpu *vcpu, unsigned int num, ...);
1159 
1160 void kvm_irq_line(struct kvm_vm *vm, u32 irq, int level);
1161 int _kvm_irq_line(struct kvm_vm *vm, u32 irq, int level);
1162 
1163 #define KVM_MAX_IRQ_ROUTES		4096
1164 
1165 struct kvm_irq_routing *kvm_gsi_routing_create(void);
1166 void kvm_gsi_routing_irqchip_add(struct kvm_irq_routing *routing,
1167 		u32 gsi, u32 pin);
1168 int _kvm_gsi_routing_write(struct kvm_vm *vm, struct kvm_irq_routing *routing);
1169 void kvm_gsi_routing_write(struct kvm_vm *vm, struct kvm_irq_routing *routing);
1170 
1171 const char *exit_reason_str(unsigned int exit_reason);
1172 
1173 bool kvm_arch_needs_naturally_aligned_page_tables(void);
1174 
1175 /*
1176  * True on powerpc when this host is a pseries LPAR (nested case).
1177  * PowerPC's PAPR L0 does not guarantee H_GUEST_CREATE / H_GUEST_CREATE_VCPU up
1178  * to MAX_VCPUS or creating hundreds of VMs - due to limited resouces at L0 for
1179  * guest management space. This helper allows us to skip such tests when we are
1180  * running nested.
1181  */
1182 static inline bool kvm_is_ppc_pseries_lpar(void)
1183 {
1184 #ifdef __powerpc64__
1185 	return !access("/proc/device-tree/rtas/ibm,hypertas-functions", F_OK);
1186 #else
1187 	return false;
1188 #endif
1189 }
1190 
1191 gpa_t ____vm_phy_pages_alloc(struct kvm_vm *vm, size_t nr_pages, gpa_t min_gpa,
1192 			     u32 memslot, bool protected, bool naturally_aligned);
1193 gpa_t __vm_phy_pages_alloc(struct kvm_vm *vm, size_t nr_pages,
1194 			   enum kvm_mem_region_type type, bool protected);
1195 
1196 static inline gpa_t vm_phy_pages_alloc(struct kvm_vm *vm, size_t nr_pages,
1197 				       enum kvm_mem_region_type type)
1198 {
1199 	/*
1200 	 * By default, allocate memory as protected for VMs that support
1201 	 * protected memory, as the majority of memory for such VMs is
1202 	 * protected, i.e. using shared memory is effectively opt-in.
1203 	 */
1204 	return __vm_phy_pages_alloc(vm, nr_pages, type,
1205 				    vm_arch_has_protected_memory(vm));
1206 }
1207 
1208 static inline gpa_t vm_phy_page_alloc(struct kvm_vm *vm,
1209 				      enum kvm_mem_region_type type)
1210 {
1211 	return vm_phy_pages_alloc(vm, 1, type);
1212 }
1213 
1214 static inline gpa_t vm_alloc_page_table_pages(struct kvm_vm *vm, size_t nr_pages)
1215 {
1216 	return vm_phy_pages_alloc(vm, nr_pages, MEM_REGION_PT);
1217 }
1218 
1219 static inline gpa_t vm_alloc_page_table(struct kvm_vm *vm)
1220 {
1221 	return vm_alloc_page_table_pages(vm, 1);
1222 }
1223 
1224 /*
1225  * ____vm_create() does KVM_CREATE_VM and little else.  __vm_create() also
1226  * loads the test binary into guest memory and creates an IRQ chip (x86 only).
1227  * __vm_create() does NOT create vCPUs, @nr_runnable_vcpus is used purely to
1228  * calculate the amount of memory needed for per-vCPU data, e.g. stacks.
1229  */
1230 struct kvm_vm *____vm_create(struct vm_shape shape);
1231 struct kvm_vm *__vm_create(struct vm_shape shape, u32 nr_runnable_vcpus,
1232 			   u64 nr_extra_pages);
1233 
1234 static inline struct kvm_vm *vm_create_barebones(void)
1235 {
1236 	return ____vm_create(VM_SHAPE_DEFAULT);
1237 }
1238 
1239 static inline struct kvm_vm *vm_create_barebones_type(unsigned long type)
1240 {
1241 	const struct vm_shape shape = {
1242 		.mode = VM_MODE_DEFAULT,
1243 		.type = type,
1244 	};
1245 
1246 	return ____vm_create(shape);
1247 }
1248 
1249 static inline struct kvm_vm *vm_create(u32 nr_runnable_vcpus)
1250 {
1251 	return __vm_create(VM_SHAPE_DEFAULT, nr_runnable_vcpus, 0);
1252 }
1253 
1254 struct kvm_vm *__vm_create_with_vcpus(struct vm_shape shape, u32 nr_vcpus,
1255 				      u64 extra_mem_pages,
1256 				      void *guest_code, struct kvm_vcpu *vcpus[]);
1257 
1258 static inline struct kvm_vm *vm_create_with_vcpus(u32 nr_vcpus,
1259 						  void *guest_code,
1260 						  struct kvm_vcpu *vcpus[])
1261 {
1262 	return __vm_create_with_vcpus(VM_SHAPE_DEFAULT, nr_vcpus, 0,
1263 				      guest_code, vcpus);
1264 }
1265 
1266 
1267 struct kvm_vm *__vm_create_shape_with_one_vcpu(struct vm_shape shape,
1268 					       struct kvm_vcpu **vcpu,
1269 					       u64 extra_mem_pages,
1270 					       void *guest_code);
1271 
1272 /*
1273  * Create a VM with a single vCPU with reasonable defaults and @extra_mem_pages
1274  * additional pages of guest memory.  Returns the VM and vCPU (via out param).
1275  */
1276 static inline struct kvm_vm *__vm_create_with_one_vcpu(struct kvm_vcpu **vcpu,
1277 						       u64 extra_mem_pages,
1278 						       void *guest_code)
1279 {
1280 	return __vm_create_shape_with_one_vcpu(VM_SHAPE_DEFAULT, vcpu,
1281 					       extra_mem_pages, guest_code);
1282 }
1283 
1284 static inline struct kvm_vm *vm_create_with_one_vcpu(struct kvm_vcpu **vcpu,
1285 						     void *guest_code)
1286 {
1287 	return __vm_create_with_one_vcpu(vcpu, 0, guest_code);
1288 }
1289 
1290 static inline struct kvm_vm *vm_create_shape_with_one_vcpu(struct vm_shape shape,
1291 							   struct kvm_vcpu **vcpu,
1292 							   void *guest_code)
1293 {
1294 	return __vm_create_shape_with_one_vcpu(shape, vcpu, 0, guest_code);
1295 }
1296 
1297 struct kvm_vcpu *vm_recreate_with_one_vcpu(struct kvm_vm *vm);
1298 
1299 void kvm_set_files_rlimit(u32 nr_vcpus);
1300 
1301 int kvm_pick_random_cpu(cpu_set_t *possible_cpus);
1302 
1303 int __pin_task_to_cpu(pthread_t task, int cpu);
1304 
1305 static inline void pin_task_to_cpu(pthread_t task, int cpu)
1306 {
1307 	int r;
1308 
1309 	r = __pin_task_to_cpu(task, cpu);
1310 	TEST_ASSERT(!r, "Failed to set thread affinity to pCPU '%u'", cpu);
1311 }
1312 
1313 static inline int pin_task_to_random_cpu(pthread_t task, cpu_set_t *possible_cpus)
1314 {
1315 	int cpu;
1316 
1317 	cpu = kvm_pick_random_cpu(possible_cpus);
1318 	pin_task_to_cpu(task, cpu);
1319 	return cpu;
1320 }
1321 
1322 static inline int pin_task_to_any_cpu(pthread_t task)
1323 {
1324 	int cpu = sched_getcpu();
1325 
1326 	pin_task_to_cpu(task, cpu);
1327 	return cpu;
1328 }
1329 
1330 static inline void pin_self_to_cpu(int cpu)
1331 {
1332 	pin_task_to_cpu(pthread_self(), cpu);
1333 }
1334 
1335 static inline int pin_self_to_any_cpu(void)
1336 {
1337 	return pin_task_to_any_cpu(pthread_self());
1338 }
1339 
1340 void pin_pages(void *vaddr, uint64_t size);
1341 void unpin_pages(void);
1342 
1343 void kvm_print_vcpu_pinning_help(void);
1344 void kvm_parse_vcpu_pinning(const char *pcpus_string, u32 vcpu_to_pcpu[],
1345 			    int nr_vcpus);
1346 
1347 unsigned long vm_compute_max_gfn(struct kvm_vm *vm);
1348 unsigned int vm_calc_num_guest_pages(enum vm_guest_mode mode, size_t size);
1349 unsigned int vm_num_host_pages(enum vm_guest_mode mode, unsigned int num_guest_pages);
1350 unsigned int vm_num_guest_pages(enum vm_guest_mode mode, unsigned int num_host_pages);
1351 static inline unsigned int
1352 vm_adjust_num_guest_pages(enum vm_guest_mode mode, unsigned int num_guest_pages)
1353 {
1354 	unsigned int n;
1355 	n = vm_num_guest_pages(mode, vm_num_host_pages(mode, num_guest_pages));
1356 	return n;
1357 }
1358 
1359 #define sync_global_to_guest(vm, g) ({				\
1360 	typeof(g) *_p = addr_gva2hva(vm, (gva_t)&(g));		\
1361 	memcpy(_p, &(g), sizeof(g));				\
1362 })
1363 
1364 #define sync_global_from_guest(vm, g) ({			\
1365 	typeof(g) *_p = addr_gva2hva(vm, (gva_t)&(g));		\
1366 	memcpy(&(g), _p, sizeof(g));				\
1367 })
1368 
1369 #define SYNC_FROM_GUEST_AND_READ(_vm, _variable) ({		\
1370 	sync_global_from_guest(_vm, _variable);			\
1371 	READ_ONCE(_variable);					\
1372 })
1373 
1374 #define WRITE_AND_SYNC_TO_GUEST(_vm, _variable, _value) do {	\
1375 	WRITE_ONCE(_variable, _value);				\
1376 	sync_global_to_guest(_vm, _variable);			\
1377 } while (0)
1378 
1379 /*
1380  * Write a global value, but only in the VM's (guest's) domain.  Primarily used
1381  * for "globals" that hold per-VM values (VMs always duplicate code and global
1382  * data into their own region of physical memory), but can be used anytime it's
1383  * undesirable to change the host's copy of the global.
1384  */
1385 #define write_guest_global(vm, g, val) ({			\
1386 	typeof(g) *_p = addr_gva2hva(vm, (gva_t)&(g));		\
1387 	typeof(g) _val = val;					\
1388 								\
1389 	memcpy(_p, &(_val), sizeof(g));				\
1390 })
1391 
1392 void assert_on_unhandled_exception(struct kvm_vcpu *vcpu);
1393 
1394 void vcpu_arch_dump(FILE *stream, struct kvm_vcpu *vcpu,
1395 		    u8 indent);
1396 
1397 static inline void vcpu_dump(FILE *stream, struct kvm_vcpu *vcpu,
1398 			     u8 indent)
1399 {
1400 	vcpu_arch_dump(stream, vcpu, indent);
1401 }
1402 
1403 /*
1404  * Adds a vCPU with reasonable defaults (e.g. a stack)
1405  *
1406  * Input Args:
1407  *   vm - Virtual Machine
1408  *   vcpu_id - The id of the VCPU to add to the VM.
1409  */
1410 struct kvm_vcpu *vm_arch_vcpu_add(struct kvm_vm *vm, u32 vcpu_id);
1411 void vcpu_arch_set_entry_point(struct kvm_vcpu *vcpu, void *guest_code);
1412 
1413 static inline struct kvm_vcpu *vm_vcpu_add(struct kvm_vm *vm, u32 vcpu_id,
1414 					   void *guest_code)
1415 {
1416 	struct kvm_vcpu *vcpu = vm_arch_vcpu_add(vm, vcpu_id);
1417 
1418 	vcpu_arch_set_entry_point(vcpu, guest_code);
1419 
1420 	return vcpu;
1421 }
1422 
1423 /* Re-create a vCPU after restarting a VM, e.g. for state save/restore tests. */
1424 struct kvm_vcpu *vm_arch_vcpu_recreate(struct kvm_vm *vm, u32 vcpu_id);
1425 
1426 static inline struct kvm_vcpu *vm_vcpu_recreate(struct kvm_vm *vm,
1427 						u32 vcpu_id)
1428 {
1429 	return vm_arch_vcpu_recreate(vm, vcpu_id);
1430 }
1431 
1432 void vcpu_arch_free(struct kvm_vcpu *vcpu);
1433 
1434 void virt_arch_pgd_alloc(struct kvm_vm *vm);
1435 
1436 static inline void virt_pgd_alloc(struct kvm_vm *vm)
1437 {
1438 	virt_arch_pgd_alloc(vm);
1439 }
1440 
1441 /*
1442  * Within @vm, creates a virtual translation for the page starting
1443  * at @gva to the page starting at @gpa.
1444  */
1445 void virt_arch_pg_map(struct kvm_vm *vm, gva_t gva, gpa_t gpa);
1446 
1447 static inline void virt_pg_map(struct kvm_vm *vm, gva_t gva, gpa_t gpa)
1448 {
1449 	virt_arch_pg_map(vm, gva, gpa);
1450 	sparsebit_set(vm->vpages_mapped, gva >> vm->page_shift);
1451 }
1452 
1453 
1454 /*
1455  * Address Guest Virtual to Guest Physical
1456  *
1457  * Input Args:
1458  *   vm - Virtual Machine
1459  *   gva - VM virtual address
1460  *
1461  * Output Args: None
1462  *
1463  * Return:
1464  *   Equivalent VM physical address
1465  *
1466  * Returns the VM physical address of the translated VM virtual
1467  * address given by @gva.
1468  */
1469 gpa_t addr_arch_gva2gpa(struct kvm_vm *vm, gva_t gva);
1470 
1471 static inline gpa_t addr_gva2gpa(struct kvm_vm *vm, gva_t gva)
1472 {
1473 	return addr_arch_gva2gpa(vm, gva);
1474 }
1475 
1476 /*
1477  * Virtual Translation Tables Dump
1478  *
1479  * Input Args:
1480  *   stream - Output FILE stream
1481  *   vm     - Virtual Machine
1482  *   indent - Left margin indent amount
1483  *
1484  * Output Args: None
1485  *
1486  * Return: None
1487  *
1488  * Dumps to the FILE stream given by @stream, the contents of all the
1489  * virtual translation tables for the VM given by @vm.
1490  */
1491 void virt_arch_dump(FILE *stream, struct kvm_vm *vm, u8 indent);
1492 
1493 static inline void virt_dump(FILE *stream, struct kvm_vm *vm, u8 indent)
1494 {
1495 	virt_arch_dump(stream, vm, indent);
1496 }
1497 
1498 
1499 static inline int __vm_disable_nx_huge_pages(struct kvm_vm *vm)
1500 {
1501 	return __vm_enable_cap(vm, KVM_CAP_VM_DISABLE_NX_HUGE_PAGES, 0);
1502 }
1503 
1504 static inline u64 vm_page_align(struct kvm_vm *vm, u64 v)
1505 {
1506 	return (v + vm->page_size - 1) & ~(vm->page_size - 1);
1507 }
1508 
1509 /*
1510  * Arch hook that is invoked via a constructor, i.e. before executing main(),
1511  * to allow for arch-specific setup that is common to all tests, e.g. computing
1512  * the default guest "mode".
1513  */
1514 void kvm_selftest_arch_init(void);
1515 
1516 void kvm_arch_vm_post_create(struct kvm_vm *vm, unsigned int nr_vcpus);
1517 void kvm_arch_vm_finalize_vcpus(struct kvm_vm *vm);
1518 void kvm_arch_vm_release(struct kvm_vm *vm);
1519 
1520 bool vm_is_gpa_protected(struct kvm_vm *vm, gpa_t gpa);
1521 
1522 u32 guest_get_vcpuid(void);
1523 
1524 bool kvm_arch_has_default_irqchip(void);
1525 
1526 #endif /* SELFTEST_KVM_UTIL_H */
1527