demand_paging_test.c 13.2 KB
Newer Older
1
2
3
4
5
6
7
8
9
// SPDX-License-Identifier: GPL-2.0
/*
 * KVM demand paging test
 * Adapted from dirty_log_test.c
 *
 * Copyright (C) 2018, Red Hat, Inc.
 * Copyright (C) 2019, Google, Inc.
 */

10
#define _GNU_SOURCE /* for pipe2 */
11

12
#include <inttypes.h>
13
14
15
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
16
#include <poll.h>
17
#include <pthread.h>
18
#include <linux/userfaultfd.h>
19
#include <sys/syscall.h>
20

21
#include "kvm_util.h"
22
#include "test_util.h"
23
24
#include "perf_test_util.h"
#include "guest_modes.h"
25

26
#ifdef __NR_userfaultfd
27

28
#ifdef PRINT_PER_PAGE_UPDATES
29
#define PER_PAGE_DEBUG(...) printf(__VA_ARGS__)
30
#else
31
#define PER_PAGE_DEBUG(...) _no_printf(__VA_ARGS__)
32
33
#endif

34
#ifdef PRINT_PER_VCPU_UPDATES
35
#define PER_VCPU_DEBUG(...) printf(__VA_ARGS__)
36
#else
37
#define PER_VCPU_DEBUG(...) _no_printf(__VA_ARGS__)
38
39
#endif

40
41
static int nr_vcpus = 1;
static uint64_t guest_percpu_mem_size = DEFAULT_PER_VCPU_MEM_SIZE;
42
static size_t demand_paging_size;
43
44
static char *guest_data_prototype;

45
46
47
static void *vcpu_worker(void *data)
{
	int ret;
48
	struct perf_test_vcpu_args *vcpu_args = (struct perf_test_vcpu_args *)data;
49
50
	int vcpu_id = vcpu_args->vcpu_id;
	struct kvm_vm *vm = perf_test_args.vm;
51
	struct kvm_run *run;
52
53
	struct timespec start;
	struct timespec ts_diff;
54

55
	vcpu_args_set(vm, vcpu_id, 1, vcpu_id);
56
	run = vcpu_state(vm, vcpu_id);
57

58
59
	clock_gettime(CLOCK_MONOTONIC, &start);

60
	/* Let the guest access its memory */
61
	ret = _vcpu_run(vm, vcpu_id);
62
	TEST_ASSERT(ret == 0, "vcpu_run failed: %d\n", ret);
63
	if (get_ucall(vm, vcpu_id, NULL) != UCALL_SYNC) {
64
65
66
67
68
		TEST_ASSERT(false,
			    "Invalid guest sync status: exit_reason=%s\n",
			    exit_reason_str(run->exit_reason));
	}

69
	ts_diff = timespec_elapsed(start);
70
71
	PER_VCPU_DEBUG("vCPU %d execution time: %ld.%.9lds\n", vcpu_id,
		       ts_diff.tv_sec, ts_diff.tv_nsec);
72

73
74
75
	return NULL;
}

76
static int handle_uffd_page_request(int uffd_mode, int uffd, uint64_t addr)
77
{
78
	pid_t tid = syscall(__NR_gettid);
79
	struct timespec start;
80
	struct timespec ts_diff;
81
82
	int r;

83
	clock_gettime(CLOCK_MONOTONIC, &start);
84

85
86
	if (uffd_mode == UFFDIO_REGISTER_MODE_MISSING) {
		struct uffdio_copy copy;
87

88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
		copy.src = (uint64_t)guest_data_prototype;
		copy.dst = addr;
		copy.len = demand_paging_size;
		copy.mode = 0;

		r = ioctl(uffd, UFFDIO_COPY, &copy);
		if (r == -1) {
			pr_info("Failed UFFDIO_COPY in 0x%lx from thread %d with errno: %d\n",
				addr, tid, errno);
			return r;
		}
	} else if (uffd_mode == UFFDIO_REGISTER_MODE_MINOR) {
		struct uffdio_continue cont = {0};

		cont.range.start = addr;
		cont.range.len = demand_paging_size;
104

105
106
107
108
109
110
111
112
		r = ioctl(uffd, UFFDIO_CONTINUE, &cont);
		if (r == -1) {
			pr_info("Failed UFFDIO_CONTINUE in 0x%lx from thread %d with errno: %d\n",
				addr, tid, errno);
			return r;
		}
	} else {
		TEST_FAIL("Invalid uffd mode %d", uffd_mode);
113
114
	}

115
	ts_diff = timespec_elapsed(start);
116

117
	PER_PAGE_DEBUG("UFFD page-in %d \t%ld ns\n", tid,
118
		       timespec_to_ns(ts_diff));
119
	PER_PAGE_DEBUG("Paged in %ld bytes at 0x%lx from thread %d\n",
120
		       demand_paging_size, addr, tid);
121

122
123
124
125
126
127
	return 0;
}

bool quit_uffd_thread;

struct uffd_handler_args {
128
	int uffd_mode;
129
130
	int uffd;
	int pipefd;
131
	useconds_t delay;
132
133
134
135
136
137
138
};

static void *uffd_handler_thread_fn(void *arg)
{
	struct uffd_handler_args *uffd_args = (struct uffd_handler_args *)arg;
	int uffd = uffd_args->uffd;
	int pipefd = uffd_args->pipefd;
139
	useconds_t delay = uffd_args->delay;
140
	int64_t pages = 0;
141
142
	struct timespec start;
	struct timespec ts_diff;
143

144
	clock_gettime(CLOCK_MONOTONIC, &start);
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
	while (!quit_uffd_thread) {
		struct uffd_msg msg;
		struct pollfd pollfd[2];
		char tmp_chr;
		int r;
		uint64_t addr;

		pollfd[0].fd = uffd;
		pollfd[0].events = POLLIN;
		pollfd[1].fd = pipefd;
		pollfd[1].events = POLLIN;

		r = poll(pollfd, 2, -1);
		switch (r) {
		case -1:
160
			pr_info("poll err");
161
162
163
164
165
166
			continue;
		case 0:
			continue;
		case 1:
			break;
		default:
167
			pr_info("Polling uffd returned %d", r);
168
169
170
171
			return NULL;
		}

		if (pollfd[0].revents & POLLERR) {
172
			pr_info("uffd revents has POLLERR");
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
			return NULL;
		}

		if (pollfd[1].revents & POLLIN) {
			r = read(pollfd[1].fd, &tmp_chr, 1);
			TEST_ASSERT(r == 1,
				    "Error reading pipefd in UFFD thread\n");
			return NULL;
		}

		if (!pollfd[0].revents & POLLIN)
			continue;

		r = read(uffd, &msg, sizeof(msg));
		if (r == -1) {
			if (errno == EAGAIN)
				continue;
190
			pr_info("Read of uffd got errno %d\n", errno);
191
192
193
194
			return NULL;
		}

		if (r != sizeof(msg)) {
195
			pr_info("Read on uffd returned unexpected size: %d bytes", r);
196
197
198
199
200
201
			return NULL;
		}

		if (!(msg.event & UFFD_EVENT_PAGEFAULT))
			continue;

202
203
		if (delay)
			usleep(delay);
204
		addr =  msg.arg.pagefault.address;
205
		r = handle_uffd_page_request(uffd_args->uffd_mode, uffd, addr);
206
207
208
209
210
		if (r < 0)
			return NULL;
		pages++;
	}

211
	ts_diff = timespec_elapsed(start);
212
213
214
	PER_VCPU_DEBUG("userfaulted %ld pages over %ld.%.9lds. (%f/sec)\n",
		       pages, ts_diff.tv_sec, ts_diff.tv_nsec,
		       pages / ((double)ts_diff.tv_sec + (double)ts_diff.tv_nsec / 100000000.0));
215

216
217
218
	return NULL;
}

219
220
static void setup_demand_paging(struct kvm_vm *vm,
				pthread_t *uffd_handler_thread, int pipefd,
221
				int uffd_mode, useconds_t uffd_delay,
222
				struct uffd_handler_args *uffd_args,
223
				void *hva, void *alias, uint64_t len)
224
{
225
	bool is_minor = (uffd_mode == UFFDIO_REGISTER_MODE_MINOR);
226
227
228
	int uffd;
	struct uffdio_api uffdio_api;
	struct uffdio_register uffdio_register;
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
	uint64_t expected_ioctls = ((uint64_t) 1) << _UFFDIO_COPY;

	PER_PAGE_DEBUG("Userfaultfd %s mode, faults resolved with %s\n",
		       is_minor ? "MINOR" : "MISSING",
		       is_minor ? "UFFDIO_CONINUE" : "UFFDIO_COPY");

	/* In order to get minor faults, prefault via the alias. */
	if (is_minor) {
		size_t p;

		expected_ioctls = ((uint64_t) 1) << _UFFDIO_CONTINUE;

		TEST_ASSERT(alias != NULL, "Alias required for minor faults");
		for (p = 0; p < (len / demand_paging_size); ++p) {
			memcpy(alias + (p * demand_paging_size),
			       guest_data_prototype, demand_paging_size);
		}
	}
247
248

	uffd = syscall(__NR_userfaultfd, O_CLOEXEC | O_NONBLOCK);
249
	TEST_ASSERT(uffd >= 0, "uffd creation failed, errno: %d", errno);
250
251
252

	uffdio_api.api = UFFD_API;
	uffdio_api.features = 0;
253
254
255
	TEST_ASSERT(ioctl(uffd, UFFDIO_API, &uffdio_api) != -1,
		    "ioctl UFFDIO_API failed: %" PRIu64,
		    (uint64_t)uffdio_api.api);
256

257
258
	uffdio_register.range.start = (uint64_t)hva;
	uffdio_register.range.len = len;
259
	uffdio_register.mode = uffd_mode;
260
261
	TEST_ASSERT(ioctl(uffd, UFFDIO_REGISTER, &uffdio_register) != -1,
		    "ioctl UFFDIO_REGISTER failed");
262
263
	TEST_ASSERT((uffdio_register.ioctls & expected_ioctls) ==
		    expected_ioctls, "missing userfaultfd ioctls");
264

265
	uffd_args->uffd_mode = uffd_mode;
266
267
268
	uffd_args->uffd = uffd;
	uffd_args->pipefd = pipefd;
	uffd_args->delay = uffd_delay;
269
	pthread_create(uffd_handler_thread, NULL, uffd_handler_thread_fn,
270
271
272
273
		       uffd_args);

	PER_VCPU_DEBUG("Created uffd thread for HVA range [%p, %p)\n",
		       hva, hva + len);
274
275
}

276
struct test_params {
277
	int uffd_mode;
278
	useconds_t uffd_delay;
279
	enum vm_mem_backing_src_type src_type;
280
	bool partition_vcpu_memory_access;
281
282
283
};

static void run_test(enum vm_guest_mode mode, void *arg)
284
{
285
	struct test_params *p = arg;
286
287
288
	pthread_t *vcpu_threads;
	pthread_t *uffd_handler_threads = NULL;
	struct uffd_handler_args *uffd_args = NULL;
289
290
	struct timespec start;
	struct timespec ts_diff;
291
	int *pipefds = NULL;
292
	struct kvm_vm *vm;
293
	int vcpu_id;
294
	int r;
295

296
	vm = perf_test_create_vm(mode, nr_vcpus, guest_percpu_mem_size,
297
				 p->src_type);
298

299
300
	perf_test_args.wr_fract = 1;

301
	demand_paging_size = get_backing_src_pagesz(p->src_type);
302
303

	guest_data_prototype = malloc(demand_paging_size);
304
305
	TEST_ASSERT(guest_data_prototype,
		    "Failed to allocate buffer for guest data pattern");
306
	memset(guest_data_prototype, 0xAB, demand_paging_size);
307

308
	vcpu_threads = malloc(nr_vcpus * sizeof(*vcpu_threads));
309
	TEST_ASSERT(vcpu_threads, "Memory allocation failed");
310

311
312
	perf_test_setup_vcpus(vm, nr_vcpus, guest_percpu_mem_size,
			      p->partition_vcpu_memory_access);
313

314
	if (p->uffd_mode) {
315
		uffd_handler_threads =
316
			malloc(nr_vcpus * sizeof(*uffd_handler_threads));
317
		TEST_ASSERT(uffd_handler_threads, "Memory allocation failed");
318

319
		uffd_args = malloc(nr_vcpus * sizeof(*uffd_args));
320
321
		TEST_ASSERT(uffd_args, "Memory allocation failed");

322
		pipefds = malloc(sizeof(int) * nr_vcpus * 2);
323
324
		TEST_ASSERT(pipefds, "Unable to allocate memory for pipefd");

325
		for (vcpu_id = 0; vcpu_id < nr_vcpus; vcpu_id++) {
326
327
			vm_paddr_t vcpu_gpa;
			void *vcpu_hva;
328
			void *vcpu_alias;
329
			uint64_t vcpu_mem_size;
330

331
332
333
334
335
336
337
338
339

			if (p->partition_vcpu_memory_access) {
				vcpu_gpa = guest_test_phys_mem +
					   (vcpu_id * guest_percpu_mem_size);
				vcpu_mem_size = guest_percpu_mem_size;
			} else {
				vcpu_gpa = guest_test_phys_mem;
				vcpu_mem_size = guest_percpu_mem_size * nr_vcpus;
			}
340
			PER_VCPU_DEBUG("Added VCPU %d with test mem gpa [%lx, %lx)\n",
341
				       vcpu_id, vcpu_gpa, vcpu_gpa + vcpu_mem_size);
342

343
			/* Cache the host addresses of the region */
344
			vcpu_hva = addr_gpa2hva(vm, vcpu_gpa);
345
			vcpu_alias = addr_gpa2alias(vm, vcpu_gpa);
346
347
348
349
350
351
352
353
354

			/*
			 * Set up user fault fd to handle demand paging
			 * requests.
			 */
			r = pipe2(&pipefds[vcpu_id * 2],
				  O_CLOEXEC | O_NONBLOCK);
			TEST_ASSERT(!r, "Failed to set up pipefd");

355
			setup_demand_paging(vm, &uffd_handler_threads[vcpu_id],
356
357
358
					    pipefds[vcpu_id * 2], p->uffd_mode,
					    p->uffd_delay, &uffd_args[vcpu_id],
					    vcpu_hva, vcpu_alias,
359
					    vcpu_mem_size);
360
361
362
		}
	}

363
	/* Export the shared variables to the guest */
364
	sync_global_to_guest(vm, perf_test_args);
365

366
	pr_info("Finished creating vCPUs and starting uffd threads\n");
367

368
369
	clock_gettime(CLOCK_MONOTONIC, &start);

370
	for (vcpu_id = 0; vcpu_id < nr_vcpus; vcpu_id++) {
371
		pthread_create(&vcpu_threads[vcpu_id], NULL, vcpu_worker,
372
			       &perf_test_args.vcpu_args[vcpu_id]);
373
374
	}

375
	pr_info("Started all vCPUs\n");
376
377

	/* Wait for the vcpu threads to quit */
378
	for (vcpu_id = 0; vcpu_id < nr_vcpus; vcpu_id++) {
379
380
381
382
		pthread_join(vcpu_threads[vcpu_id], NULL);
		PER_VCPU_DEBUG("Joined thread for vCPU %d\n", vcpu_id);
	}

383
	ts_diff = timespec_elapsed(start);
384

385
	pr_info("All vCPU threads joined\n");
386

387
	if (p->uffd_mode) {
388
389
		char c;

390
		/* Tell the user fault fd handler threads to quit */
391
		for (vcpu_id = 0; vcpu_id < nr_vcpus; vcpu_id++) {
392
393
			r = write(pipefds[vcpu_id * 2 + 1], &c, 1);
			TEST_ASSERT(r == 1, "Unable to write to pipefd");
394

395
396
			pthread_join(uffd_handler_threads[vcpu_id], NULL);
		}
397
398
	}

399
400
	pr_info("Total guest execution time: %ld.%.9lds\n",
		ts_diff.tv_sec, ts_diff.tv_nsec);
401
	pr_info("Overall demand paging rate: %f pgs/sec\n",
402
		perf_test_args.vcpu_args[0].pages * nr_vcpus /
403
		((double)ts_diff.tv_sec + (double)ts_diff.tv_nsec / 100000000.0));
404

405
	perf_test_destroy_vm(vm);
406
407

	free(guest_data_prototype);
408
	free(vcpu_threads);
409
	if (p->uffd_mode) {
410
411
412
413
		free(uffd_handler_threads);
		free(uffd_args);
		free(pipefds);
	}
414
415
416
417
418
}

static void help(char *name)
{
	puts("");
419
	printf("usage: %s [-h] [-m vm_mode] [-u uffd_mode] [-d uffd_delay_usec]\n"
420
	       "          [-b memory] [-t type] [-v vcpus] [-o]\n", name);
421
	guest_modes_help();
422
423
	printf(" -u: use userfaultfd to handle vCPU page faults. Mode is a\n"
	       "     UFFD registration mode: 'MISSING' or 'MINOR'.\n");
424
425
426
	printf(" -d: add a delay in usec to the User Fault\n"
	       "     FD handler to simulate demand paging\n"
	       "     overheads. Ignored without -u.\n");
427
	printf(" -b: specify the size of the memory region which should be\n"
428
429
	       "     demand paged by each vCPU. e.g. 10M or 3G.\n"
	       "     Default: 1G\n");
430
431
	printf(" -t: The type of backing memory to use. Default: anonymous\n");
	backing_src_help();
432
	printf(" -v: specify the number of vCPUs to run.\n");
433
434
	printf(" -o: Overlap guest memory accesses instead of partitioning\n"
	       "     them into a separate region of memory for each vCPU.\n");
435
436
437
438
439
440
	puts("");
	exit(0);
}

int main(int argc, char *argv[])
{
441
	int max_vcpus = kvm_check_cap(KVM_CAP_MAX_VCPUS);
442
	struct test_params p = {
443
		.src_type = VM_MEM_SRC_ANONYMOUS,
444
445
		.partition_vcpu_memory_access = true,
	};
446
447
448
	int opt;

	guest_modes_append_default();
449

450
	while ((opt = getopt(argc, argv, "hm:u:d:b:t:v:o")) != -1) {
451
452
		switch (opt) {
		case 'm':
453
			guest_modes_cmdline(optarg);
454
			break;
455
		case 'u':
456
457
458
459
460
			if (!strcmp("MISSING", optarg))
				p.uffd_mode = UFFDIO_REGISTER_MODE_MISSING;
			else if (!strcmp("MINOR", optarg))
				p.uffd_mode = UFFDIO_REGISTER_MODE_MINOR;
			TEST_ASSERT(p.uffd_mode, "UFFD mode must be 'MISSING' or 'MINOR'.");
461
			break;
462
		case 'd':
463
464
			p.uffd_delay = strtoul(optarg, NULL, 0);
			TEST_ASSERT(p.uffd_delay >= 0, "A negative UFFD delay is not supported.");
465
			break;
466
		case 'b':
467
			guest_percpu_mem_size = parse_size(optarg);
468
			break;
469
470
471
		case 't':
			p.src_type = parse_backing_src_type(optarg);
			break;
472
		case 'v':
473
474
475
			nr_vcpus = atoi(optarg);
			TEST_ASSERT(nr_vcpus > 0 && nr_vcpus <= max_vcpus,
				    "Invalid number of vcpus, must be between 1 and %d", max_vcpus);
476
			break;
477
478
479
		case 'o':
			p.partition_vcpu_memory_access = false;
			break;
480
481
482
483
484
485
486
		case 'h':
		default:
			help(argv[0]);
			break;
		}
	}

487
488
489
490
	if (p.uffd_mode == UFFDIO_REGISTER_MODE_MINOR &&
	    !backing_src_is_shared(p.src_type)) {
		TEST_FAIL("userfaultfd MINOR mode requires shared memory; pick a different -t");
	}
491

492
	for_each_guest_mode(run_test, &p);
493
494
495

	return 0;
}
496
497
498
499
500
501
502

#else /* __NR_userfaultfd */

#warning "missing __NR_userfaultfd definition"

int main(void)
{
503
504
	print_skip("__NR_userfaultfd must be present for userfaultfd test");
	return KSFT_SKIP;
505
506
507
}

#endif /* __NR_userfaultfd */