xref: /linux/tools/testing/selftests/kvm/demand_paging_test.c (revision 2b7deea3ec7c81a92d4c17751d3bcd780d065ae4)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * KVM demand paging test
4  * Adapted from dirty_log_test.c
5  *
6  * Copyright (C) 2018, Red Hat, Inc.
7  * Copyright (C) 2019, Google, Inc.
8  */
9 #include <inttypes.h>
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <time.h>
13 #include <poll.h>
14 #include <pthread.h>
15 #include <linux/userfaultfd.h>
16 #include <sys/syscall.h>
17 
18 #include "kvm_util.h"
19 #include "test_util.h"
20 #include "memstress.h"
21 #include "guest_modes.h"
22 #include "ucall_common.h"
23 #include "userfaultfd_util.h"
24 
25 #ifdef __NR_userfaultfd
26 
27 static int nr_vcpus = 1;
28 static uint64_t guest_percpu_mem_size = DEFAULT_PER_VCPU_MEM_SIZE;
29 
30 static size_t demand_paging_size;
31 static char *guest_data_prototype;
32 
33 static void vcpu_worker(struct memstress_vcpu_args *vcpu_args)
34 {
35 	struct kvm_vcpu *vcpu = vcpu_args->vcpu;
36 	int vcpu_idx = vcpu_args->vcpu_idx;
37 	struct kvm_run *run = vcpu->run;
38 	struct timespec start;
39 	struct timespec ts_diff;
40 	int ret;
41 
42 	clock_gettime(CLOCK_MONOTONIC, &start);
43 
44 	/* Let the guest access its memory */
45 	ret = _vcpu_run(vcpu);
46 	TEST_ASSERT(ret == 0, "vcpu_run failed: %d", ret);
47 	if (get_ucall(vcpu, NULL) != UCALL_SYNC) {
48 		TEST_ASSERT(false,
49 			    "Invalid guest sync status: exit_reason=%s",
50 			    exit_reason_str(run->exit_reason));
51 	}
52 
53 	ts_diff = timespec_elapsed(start);
54 	PER_VCPU_DEBUG("vCPU %d execution time: %ld.%.9lds\n", vcpu_idx,
55 		       ts_diff.tv_sec, ts_diff.tv_nsec);
56 }
57 
58 static int handle_uffd_page_request(int uffd_mode, int uffd,
59 		struct uffd_msg *msg)
60 {
61 	pid_t tid = syscall(__NR_gettid);
62 	uint64_t addr = msg->arg.pagefault.address;
63 	struct timespec start;
64 	struct timespec ts_diff;
65 	int r;
66 
67 	clock_gettime(CLOCK_MONOTONIC, &start);
68 
69 	if (uffd_mode == UFFDIO_REGISTER_MODE_MISSING) {
70 		struct uffdio_copy copy;
71 
72 		copy.src = (uint64_t)guest_data_prototype;
73 		copy.dst = addr;
74 		copy.len = demand_paging_size;
75 		copy.mode = 0;
76 
77 		r = ioctl(uffd, UFFDIO_COPY, &copy);
78 		if (r == -1) {
79 			pr_info("Failed UFFDIO_COPY in 0x%lx from thread %d with errno: %d\n",
80 				addr, tid, errno);
81 			return r;
82 		}
83 	} else if (uffd_mode == UFFDIO_REGISTER_MODE_MINOR) {
84 		struct uffdio_continue cont = {0};
85 
86 		cont.range.start = addr;
87 		cont.range.len = demand_paging_size;
88 
89 		r = ioctl(uffd, UFFDIO_CONTINUE, &cont);
90 		if (r == -1) {
91 			pr_info("Failed UFFDIO_CONTINUE in 0x%lx from thread %d with errno: %d\n",
92 				addr, tid, errno);
93 			return r;
94 		}
95 	} else {
96 		TEST_FAIL("Invalid uffd mode %d", uffd_mode);
97 	}
98 
99 	ts_diff = timespec_elapsed(start);
100 
101 	PER_PAGE_DEBUG("UFFD page-in %d \t%ld ns\n", tid,
102 		       timespec_to_ns(ts_diff));
103 	PER_PAGE_DEBUG("Paged in %ld bytes at 0x%lx from thread %d\n",
104 		       demand_paging_size, addr, tid);
105 
106 	return 0;
107 }
108 
109 struct test_params {
110 	int uffd_mode;
111 	useconds_t uffd_delay;
112 	enum vm_mem_backing_src_type src_type;
113 	bool partition_vcpu_memory_access;
114 };
115 
116 static void prefault_mem(void *alias, uint64_t len)
117 {
118 	size_t p;
119 
120 	TEST_ASSERT(alias != NULL, "Alias required for minor faults");
121 	for (p = 0; p < (len / demand_paging_size); ++p) {
122 		memcpy(alias + (p * demand_paging_size),
123 		       guest_data_prototype, demand_paging_size);
124 	}
125 }
126 
127 static void run_test(enum vm_guest_mode mode, void *arg)
128 {
129 	struct memstress_vcpu_args *vcpu_args;
130 	struct test_params *p = arg;
131 	struct uffd_desc **uffd_descs = NULL;
132 	struct timespec start;
133 	struct timespec ts_diff;
134 	struct kvm_vm *vm;
135 	int i;
136 
137 	vm = memstress_create_vm(mode, nr_vcpus, guest_percpu_mem_size, 1,
138 				 p->src_type, p->partition_vcpu_memory_access);
139 
140 	demand_paging_size = get_backing_src_pagesz(p->src_type);
141 
142 	guest_data_prototype = malloc(demand_paging_size);
143 	TEST_ASSERT(guest_data_prototype,
144 		    "Failed to allocate buffer for guest data pattern");
145 	memset(guest_data_prototype, 0xAB, demand_paging_size);
146 
147 	if (p->uffd_mode == UFFDIO_REGISTER_MODE_MINOR) {
148 		for (i = 0; i < nr_vcpus; i++) {
149 			vcpu_args = &memstress_args.vcpu_args[i];
150 			prefault_mem(addr_gpa2alias(vm, vcpu_args->gpa),
151 				     vcpu_args->pages * memstress_args.guest_page_size);
152 		}
153 	}
154 
155 	if (p->uffd_mode) {
156 		uffd_descs = malloc(nr_vcpus * sizeof(struct uffd_desc *));
157 		TEST_ASSERT(uffd_descs, "Memory allocation failed");
158 		for (i = 0; i < nr_vcpus; i++) {
159 			void *vcpu_hva;
160 
161 			vcpu_args = &memstress_args.vcpu_args[i];
162 
163 			/* Cache the host addresses of the region */
164 			vcpu_hva = addr_gpa2hva(vm, vcpu_args->gpa);
165 			/*
166 			 * Set up user fault fd to handle demand paging
167 			 * requests.
168 			 */
169 			uffd_descs[i] = uffd_setup_demand_paging(
170 				p->uffd_mode, p->uffd_delay, vcpu_hva,
171 				vcpu_args->pages * memstress_args.guest_page_size,
172 				&handle_uffd_page_request);
173 		}
174 	}
175 
176 	pr_info("Finished creating vCPUs and starting uffd threads\n");
177 
178 	clock_gettime(CLOCK_MONOTONIC, &start);
179 	memstress_start_vcpu_threads(nr_vcpus, vcpu_worker);
180 	pr_info("Started all vCPUs\n");
181 
182 	memstress_join_vcpu_threads(nr_vcpus);
183 	ts_diff = timespec_elapsed(start);
184 	pr_info("All vCPU threads joined\n");
185 
186 	if (p->uffd_mode) {
187 		/* Tell the user fault fd handler threads to quit */
188 		for (i = 0; i < nr_vcpus; i++)
189 			uffd_stop_demand_paging(uffd_descs[i]);
190 	}
191 
192 	pr_info("Total guest execution time: %ld.%.9lds\n",
193 		ts_diff.tv_sec, ts_diff.tv_nsec);
194 	pr_info("Overall demand paging rate: %f pgs/sec\n",
195 		memstress_args.vcpu_args[0].pages * nr_vcpus /
196 		((double)ts_diff.tv_sec + (double)ts_diff.tv_nsec / NSEC_PER_SEC));
197 
198 	memstress_destroy_vm(vm);
199 
200 	free(guest_data_prototype);
201 	if (p->uffd_mode)
202 		free(uffd_descs);
203 }
204 
205 static void help(char *name)
206 {
207 	puts("");
208 	printf("usage: %s [-h] [-m vm_mode] [-u uffd_mode] [-d uffd_delay_usec]\n"
209 	       "          [-b memory] [-s type] [-v vcpus] [-c cpu_list] [-o]\n", name);
210 	guest_modes_help();
211 	printf(" -u: use userfaultfd to handle vCPU page faults. Mode is a\n"
212 	       "     UFFD registration mode: 'MISSING' or 'MINOR'.\n");
213 	kvm_print_vcpu_pinning_help();
214 	printf(" -d: add a delay in usec to the User Fault\n"
215 	       "     FD handler to simulate demand paging\n"
216 	       "     overheads. Ignored without -u.\n");
217 	printf(" -b: specify the size of the memory region which should be\n"
218 	       "     demand paged by each vCPU. e.g. 10M or 3G.\n"
219 	       "     Default: 1G\n");
220 	backing_src_help("-s");
221 	printf(" -v: specify the number of vCPUs to run.\n");
222 	printf(" -o: Overlap guest memory accesses instead of partitioning\n"
223 	       "     them into a separate region of memory for each vCPU.\n");
224 	puts("");
225 	exit(0);
226 }
227 
228 int main(int argc, char *argv[])
229 {
230 	int max_vcpus = kvm_check_cap(KVM_CAP_MAX_VCPUS);
231 	const char *cpulist = NULL;
232 	struct test_params p = {
233 		.src_type = DEFAULT_VM_MEM_SRC,
234 		.partition_vcpu_memory_access = true,
235 	};
236 	int opt;
237 
238 	guest_modes_append_default();
239 
240 	while ((opt = getopt(argc, argv, "hm:u:d:b:s:v:c:o")) != -1) {
241 		switch (opt) {
242 		case 'm':
243 			guest_modes_cmdline(optarg);
244 			break;
245 		case 'u':
246 			if (!strcmp("MISSING", optarg))
247 				p.uffd_mode = UFFDIO_REGISTER_MODE_MISSING;
248 			else if (!strcmp("MINOR", optarg))
249 				p.uffd_mode = UFFDIO_REGISTER_MODE_MINOR;
250 			TEST_ASSERT(p.uffd_mode, "UFFD mode must be 'MISSING' or 'MINOR'.");
251 			break;
252 		case 'd':
253 			p.uffd_delay = strtoul(optarg, NULL, 0);
254 			TEST_ASSERT(p.uffd_delay >= 0, "A negative UFFD delay is not supported.");
255 			break;
256 		case 'b':
257 			guest_percpu_mem_size = parse_size(optarg);
258 			break;
259 		case 's':
260 			p.src_type = parse_backing_src_type(optarg);
261 			break;
262 		case 'v':
263 			nr_vcpus = atoi_positive("Number of vCPUs", optarg);
264 			TEST_ASSERT(nr_vcpus <= max_vcpus,
265 				    "Invalid number of vcpus, must be between 1 and %d", max_vcpus);
266 			break;
267 		case 'c':
268 			cpulist = optarg;
269 			break;
270 		case 'o':
271 			p.partition_vcpu_memory_access = false;
272 			break;
273 		case 'h':
274 		default:
275 			help(argv[0]);
276 			break;
277 		}
278 	}
279 
280 	if (p.uffd_mode == UFFDIO_REGISTER_MODE_MINOR &&
281 	    !backing_src_is_shared(p.src_type)) {
282 		TEST_FAIL("userfaultfd MINOR mode requires shared memory; pick a different -s");
283 	}
284 
285 	if (cpulist) {
286 		kvm_parse_vcpu_pinning(cpulist, memstress_args.vcpu_to_pcpu,
287 				       nr_vcpus);
288 		memstress_args.pin_vcpus = true;
289 	}
290 
291 	for_each_guest_mode(run_test, &p);
292 
293 	return 0;
294 }
295 
296 #else /* __NR_userfaultfd */
297 
298 #warning "missing __NR_userfaultfd definition"
299 
300 int main(void)
301 {
302 	print_skip("__NR_userfaultfd must be present for userfaultfd test");
303 	return KSFT_SKIP;
304 }
305 
306 #endif /* __NR_userfaultfd */
307