xref: /linux/tools/testing/selftests/mm/uffd-stress.c (revision f3bd00507f226a419125df6064632bcbd47d8e70)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Stress userfaultfd syscall.
4  *
5  *  Copyright (C) 2015  Red Hat, Inc.
6  *
7  * This test allocates two virtual areas and bounces the physical
8  * memory across the two virtual areas (from area_src to area_dst)
9  * using userfaultfd.
10  *
11  * There are three threads running per CPU:
12  *
13  * 1) one per-CPU thread takes a per-page pthread_mutex in a random
14  *    page of the area_dst (while the physical page may still be in
15  *    area_src), and increments a per-page counter in the same page,
16  *    and checks its value against a verification region.
17  *
18  * 2) another per-CPU thread handles the userfaults generated by
19  *    thread 1 above. userfaultfd blocking reads or poll() modes are
20  *    exercised interleaved.
21  *
22  * 3) one last per-CPU thread transfers the memory in the background
23  *    at maximum bandwidth (if not already transferred by thread
24  *    2). Each cpu thread takes cares of transferring a portion of the
25  *    area.
26  *
27  * When all threads of type 3 completed the transfer, one bounce is
28  * complete. area_src and area_dst are then swapped. All threads are
29  * respawned and so the bounce is immediately restarted in the
30  * opposite direction.
31  *
32  * per-CPU threads 1 by triggering userfaults inside
33  * pthread_mutex_lock will also verify the atomicity of the memory
34  * transfer (UFFDIO_COPY).
35  */
36 
37 #include "uffd-common.h"
38 
39 uint64_t features;
40 #ifdef __NR_userfaultfd
41 
42 #define BOUNCE_RANDOM		(1<<0)
43 #define BOUNCE_RACINGFAULTS	(1<<1)
44 #define BOUNCE_VERIFY		(1<<2)
45 #define BOUNCE_POLL		(1<<3)
46 static int bounces;
47 /* defined globally for this particular test as the sigalrm handler
48  * depends on test_uffdio_*_eexist.
49  * XXX: define gopts in main() when we figure out a way to deal with
50  * test_uffdio_*_eexist.
51  */
52 static uffd_global_test_opts_t *gopts;
53 
54 /* exercise the test_uffdio_*_eexist every ALARM_INTERVAL_SECS */
55 #define ALARM_INTERVAL_SECS 10
56 static char *zeropage;
57 pthread_attr_t attr;
58 
59 #define swap(a, b) \
60 	do { __auto_type __tmp = (a); (a) = (b); (b) = __tmp; } while (0)
61 
62 const char *examples =
63 	"# Run anonymous memory test on 100MiB region with 99999 bounces:\n"
64 	"./uffd-stress anon 100 99999\n\n"
65 	"# Run share memory test on 1GiB region with 99 bounces:\n"
66 	"./uffd-stress shmem 1000 99\n\n"
67 	"# Run hugetlb memory test on 256MiB region with 50 bounces:\n"
68 	"./uffd-stress hugetlb 256 50\n\n"
69 	"# Run the same hugetlb test but using private file:\n"
70 	"./uffd-stress hugetlb-private 256 50\n\n"
71 	"# 10MiB-~6GiB 999 bounces anonymous test, "
72 	"continue forever unless an error triggers\n"
73 	"while ./uffd-stress anon $[RANDOM % 6000 + 10] 999; do true; done\n\n";
74 
75 static void usage(void)
76 {
77 	fprintf(stderr, "\nUsage: ./uffd-stress <test type> <MiB> <bounces>\n\n");
78 	fprintf(stderr, "Supported <test type>: anon, hugetlb, "
79 		"hugetlb-private, shmem, shmem-private\n\n");
80 	fprintf(stderr, "Examples:\n\n");
81 	fprintf(stderr, "%s", examples);
82 	exit(1);
83 }
84 
85 static void uffd_stats_reset(uffd_global_test_opts_t *gopts, struct uffd_args *args,
86 			     unsigned long n_cpus)
87 {
88 	int i;
89 
90 	for (i = 0; i < n_cpus; i++) {
91 		args[i].cpu = i;
92 		args[i].apply_wp = gopts->test_uffdio_wp;
93 		args[i].missing_faults = 0;
94 		args[i].wp_faults = 0;
95 		args[i].minor_faults = 0;
96 		args[i].gopts = gopts;
97 	}
98 }
99 
100 static void *locking_thread(void *arg)
101 {
102 	struct uffd_args *args = (struct uffd_args *) arg;
103 	uffd_global_test_opts_t *gopts = args->gopts;
104 	unsigned long cpu = (unsigned long) args->cpu;
105 	unsigned long page_nr;
106 	unsigned long long count;
107 
108 	if (!(bounces & BOUNCE_RANDOM)) {
109 		page_nr = -bounces;
110 		if (!(bounces & BOUNCE_RACINGFAULTS))
111 			page_nr += cpu * gopts->nr_pages_per_cpu;
112 	}
113 
114 	while (!gopts->finished) {
115 		if (bounces & BOUNCE_RANDOM) {
116 			if (getrandom(&page_nr, sizeof(page_nr), 0) != sizeof(page_nr))
117 				err("getrandom failed");
118 		} else
119 			page_nr += 1;
120 		page_nr %= gopts->nr_pages;
121 		pthread_mutex_lock(area_mutex(gopts->area_dst, page_nr, gopts));
122 		count = *area_count(gopts->area_dst, page_nr, gopts);
123 		if (count != gopts->count_verify[page_nr])
124 			err("page_nr %lu memory corruption %llu %llu",
125 			    page_nr, count, gopts->count_verify[page_nr]);
126 		count++;
127 		*area_count(gopts->area_dst, page_nr, gopts) = gopts->count_verify[page_nr] = count;
128 		pthread_mutex_unlock(area_mutex(gopts->area_dst, page_nr, gopts));
129 	}
130 
131 	return NULL;
132 }
133 
134 static int copy_page_retry(uffd_global_test_opts_t *gopts, unsigned long offset)
135 {
136 	return __copy_page(gopts, offset, true, gopts->test_uffdio_wp);
137 }
138 
139 pthread_mutex_t uffd_read_mutex = PTHREAD_MUTEX_INITIALIZER;
140 
141 static void *uffd_read_thread(void *arg)
142 {
143 	struct uffd_args *args = (struct uffd_args *)arg;
144 	uffd_global_test_opts_t *gopts = args->gopts;
145 	struct uffd_msg msg;
146 
147 	pthread_mutex_unlock(&uffd_read_mutex);
148 	/* from here cancellation is ok */
149 
150 	for (;;) {
151 		if (uffd_read_msg(gopts, &msg))
152 			continue;
153 		uffd_handle_page_fault(gopts, &msg, args);
154 	}
155 
156 	return NULL;
157 }
158 
159 static void *background_thread(void *arg)
160 {
161 	struct uffd_args *args = (struct uffd_args *) arg;
162 	uffd_global_test_opts_t *gopts = args->gopts;
163 	unsigned long cpu = (unsigned long) args->cpu;
164 	unsigned long page_nr, start_nr, mid_nr, end_nr;
165 
166 	start_nr = cpu * gopts->nr_pages_per_cpu;
167 	end_nr = (cpu+1) * gopts->nr_pages_per_cpu;
168 	mid_nr = (start_nr + end_nr) / 2;
169 
170 	/* Copy the first half of the pages */
171 	for (page_nr = start_nr; page_nr < mid_nr; page_nr++)
172 		copy_page_retry(gopts, page_nr * gopts->page_size);
173 
174 	/*
175 	 * If we need to test uffd-wp, set it up now.  Then we'll have
176 	 * at least the first half of the pages mapped already which
177 	 * can be write-protected for testing
178 	 */
179 	if (gopts->test_uffdio_wp)
180 		wp_range(gopts->uffd, (unsigned long)gopts->area_dst + start_nr * gopts->page_size,
181 			gopts->nr_pages_per_cpu * gopts->page_size, true);
182 
183 	/*
184 	 * Continue the 2nd half of the page copying, handling write
185 	 * protection faults if any
186 	 */
187 	for (page_nr = mid_nr; page_nr < end_nr; page_nr++)
188 		copy_page_retry(gopts, page_nr * gopts->page_size);
189 
190 	return NULL;
191 }
192 
193 static int stress(struct uffd_args *args)
194 {
195 	unsigned long cpu;
196 	uffd_global_test_opts_t *gopts = args->gopts;
197 	pthread_t locking_threads[gopts->nr_parallel];
198 	pthread_t uffd_threads[gopts->nr_parallel];
199 	pthread_t background_threads[gopts->nr_parallel];
200 
201 	gopts->finished = 0;
202 	for (cpu = 0; cpu < gopts->nr_parallel; cpu++) {
203 		if (pthread_create(&locking_threads[cpu], &attr,
204 				   locking_thread, (void *)&args[cpu]))
205 			return 1;
206 		if (bounces & BOUNCE_POLL) {
207 			if (pthread_create(&uffd_threads[cpu],
208 					   &attr,
209 					   uffd_poll_thread,
210 					   (void *) &args[cpu]))
211 				err("uffd_poll_thread create");
212 		} else {
213 			if (pthread_create(&uffd_threads[cpu], &attr,
214 					   uffd_read_thread,
215 					   (void *)&args[cpu]))
216 				return 1;
217 			pthread_mutex_lock(&uffd_read_mutex);
218 		}
219 		if (pthread_create(&background_threads[cpu], &attr,
220 				   background_thread, (void *)&args[cpu]))
221 			return 1;
222 	}
223 	for (cpu = 0; cpu < gopts->nr_parallel; cpu++)
224 		if (pthread_join(background_threads[cpu], NULL))
225 			return 1;
226 
227 	/*
228 	 * Be strict and immediately zap area_src, the whole area has
229 	 * been transferred already by the background treads. The
230 	 * area_src could then be faulted in a racy way by still
231 	 * running uffdio_threads reading zeropages after we zapped
232 	 * area_src (but they're guaranteed to get -EEXIST from
233 	 * UFFDIO_COPY without writing zero pages into area_dst
234 	 * because the background threads already completed).
235 	 */
236 	uffd_test_ops->release_pages(gopts, gopts->area_src);
237 
238 	gopts->finished = 1;
239 	for (cpu = 0; cpu < gopts->nr_parallel; cpu++)
240 		if (pthread_join(locking_threads[cpu], NULL))
241 			return 1;
242 
243 	for (cpu = 0; cpu < gopts->nr_parallel; cpu++) {
244 		char c = '\0';
245 		if (bounces & BOUNCE_POLL) {
246 			if (write(gopts->pipefd[cpu*2+1], &c, 1) != 1)
247 				err("pipefd write error");
248 			if (pthread_join(uffd_threads[cpu],
249 					 (void *)&args[cpu]))
250 				return 1;
251 		} else {
252 			if (pthread_cancel(uffd_threads[cpu]))
253 				return 1;
254 			if (pthread_join(uffd_threads[cpu], NULL))
255 				return 1;
256 		}
257 	}
258 
259 	return 0;
260 }
261 
262 static int userfaultfd_stress(uffd_global_test_opts_t *gopts)
263 {
264 	void *area;
265 	unsigned long nr;
266 	struct uffd_args args[gopts->nr_parallel];
267 	uint64_t mem_size = gopts->nr_pages * gopts->page_size;
268 	int flags = 0;
269 
270 	memset(args, 0, sizeof(struct uffd_args) * gopts->nr_parallel);
271 
272 	if (features & UFFD_FEATURE_WP_UNPOPULATED && gopts->test_type == TEST_ANON)
273 		flags = UFFD_FEATURE_WP_UNPOPULATED;
274 
275 	if (uffd_test_ctx_init(gopts, flags, NULL))
276 		err("context init failed");
277 
278 	if (posix_memalign(&area, gopts->page_size, gopts->page_size))
279 		err("out of memory");
280 	zeropage = area;
281 	bzero(zeropage, gopts->page_size);
282 
283 	pthread_mutex_lock(&uffd_read_mutex);
284 
285 	pthread_attr_init(&attr);
286 	pthread_attr_setstacksize(&attr, 16*1024*1024);
287 
288 	while (bounces--) {
289 		ksft_print_msg("bounces: %d, mode:%s%s%s%s, ",
290 			       bounces,
291 			       bounces & BOUNCE_RANDOM ? " rnd" : "",
292 			       bounces & BOUNCE_RACINGFAULTS ? " racing" : "",
293 			       bounces & BOUNCE_VERIFY ? " ver" : "",
294 			       bounces & BOUNCE_POLL ? " poll" : " read");
295 		fflush(stdout);
296 
297 		if (bounces & BOUNCE_POLL)
298 			fcntl(gopts->uffd, F_SETFL, gopts->uffd_flags | O_NONBLOCK);
299 		else
300 			fcntl(gopts->uffd, F_SETFL, gopts->uffd_flags & ~O_NONBLOCK);
301 
302 		/* register */
303 		if (uffd_register(gopts->uffd, gopts->area_dst, mem_size,
304 				  true, gopts->test_uffdio_wp, false))
305 			err("register failure");
306 
307 		if (gopts->area_dst_alias) {
308 			if (uffd_register(gopts->uffd, gopts->area_dst_alias, mem_size,
309 					  true, gopts->test_uffdio_wp, false))
310 				err("register failure alias");
311 		}
312 
313 		/*
314 		 * The madvise done previously isn't enough: some
315 		 * uffd_thread could have read userfaults (one of
316 		 * those already resolved by the background thread)
317 		 * and it may be in the process of calling
318 		 * UFFDIO_COPY. UFFDIO_COPY will read the zapped
319 		 * area_src and it would map a zero page in it (of
320 		 * course such a UFFDIO_COPY is perfectly safe as it'd
321 		 * return -EEXIST). The problem comes at the next
322 		 * bounce though: that racing UFFDIO_COPY would
323 		 * generate zeropages in the area_src, so invalidating
324 		 * the previous MADV_DONTNEED. Without this additional
325 		 * MADV_DONTNEED those zeropages leftovers in the
326 		 * area_src would lead to -EEXIST failure during the
327 		 * next bounce, effectively leaving a zeropage in the
328 		 * area_dst.
329 		 *
330 		 * Try to comment this out madvise to see the memory
331 		 * corruption being caught pretty quick.
332 		 *
333 		 * khugepaged is also inhibited to collapse THP after
334 		 * MADV_DONTNEED only after the UFFDIO_REGISTER, so it's
335 		 * required to MADV_DONTNEED here.
336 		 */
337 		uffd_test_ops->release_pages(gopts, gopts->area_dst);
338 
339 		uffd_stats_reset(gopts, args, gopts->nr_parallel);
340 
341 		/* bounce pass */
342 		if (stress(args)) {
343 			uffd_test_ctx_clear(gopts);
344 			return 1;
345 		}
346 
347 		/* Clear all the write protections if there is any */
348 		if (gopts->test_uffdio_wp)
349 			wp_range(gopts->uffd, (unsigned long)gopts->area_dst,
350 				 gopts->nr_pages * gopts->page_size, false);
351 
352 		/* unregister */
353 		if (uffd_unregister(gopts->uffd, gopts->area_dst, mem_size))
354 			err("unregister failure");
355 		if (gopts->area_dst_alias) {
356 			if (uffd_unregister(gopts->uffd, gopts->area_dst_alias, mem_size))
357 				err("unregister failure alias");
358 		}
359 
360 		/* verification */
361 		if (bounces & BOUNCE_VERIFY)
362 			for (nr = 0; nr < gopts->nr_pages; nr++)
363 				if (*area_count(gopts->area_dst, nr, gopts) !=
364 						gopts->count_verify[nr])
365 					err("error area_count %llu %llu %lu\n",
366 					    *area_count(gopts->area_src, nr, gopts),
367 					    gopts->count_verify[nr], nr);
368 
369 		/* prepare next bounce */
370 		swap(gopts->area_src, gopts->area_dst);
371 
372 		swap(gopts->area_src_alias, gopts->area_dst_alias);
373 
374 		uffd_stats_report(args, gopts->nr_parallel);
375 	}
376 	uffd_test_ctx_clear(gopts);
377 
378 	return 0;
379 }
380 
381 static void set_test_type(uffd_global_test_opts_t *gopts, const char *type)
382 {
383 	if (!strcmp(type, "anon")) {
384 		gopts->test_type = TEST_ANON;
385 		uffd_test_ops = &anon_uffd_test_ops;
386 	} else if (!strcmp(type, "hugetlb")) {
387 		gopts->test_type = TEST_HUGETLB;
388 		uffd_test_ops = &hugetlb_uffd_test_ops;
389 		gopts->map_shared = true;
390 	} else if (!strcmp(type, "hugetlb-private")) {
391 		gopts->test_type = TEST_HUGETLB;
392 		uffd_test_ops = &hugetlb_uffd_test_ops;
393 	} else if (!strcmp(type, "shmem")) {
394 		gopts->map_shared = true;
395 		gopts->test_type = TEST_SHMEM;
396 		uffd_test_ops = &shmem_uffd_test_ops;
397 	} else if (!strcmp(type, "shmem-private")) {
398 		gopts->test_type = TEST_SHMEM;
399 		uffd_test_ops = &shmem_uffd_test_ops;
400 	}
401 }
402 
403 static void parse_test_type_arg(uffd_global_test_opts_t *gopts, const char *raw_type)
404 {
405 	set_test_type(gopts, raw_type);
406 
407 	if (!gopts->test_type)
408 		err("failed to parse test type argument: '%s'", raw_type);
409 
410 	if (gopts->test_type == TEST_HUGETLB)
411 		gopts->page_size = default_huge_page_size();
412 	else
413 		gopts->page_size = sysconf(_SC_PAGE_SIZE);
414 
415 	if (!gopts->page_size)
416 		err("Unable to determine page size");
417 	if ((unsigned long) area_count(NULL, 0, gopts) + sizeof(unsigned long long) * 2
418 	    > gopts->page_size)
419 		err("Impossible to run this test");
420 
421 	/*
422 	 * Whether we can test certain features depends not just on test type,
423 	 * but also on whether or not this particular kernel supports the
424 	 * feature.
425 	 */
426 
427 	if (uffd_get_features(&features) && errno == ENOENT)
428 		ksft_exit_skip("failed to get available features (%d)\n", errno);
429 
430 	gopts->test_uffdio_wp = gopts->test_uffdio_wp &&
431 		(features & UFFD_FEATURE_PAGEFAULT_FLAG_WP);
432 
433 	if (gopts->test_type != TEST_ANON && !(features & UFFD_FEATURE_WP_HUGETLBFS_SHMEM))
434 		gopts->test_uffdio_wp = false;
435 
436 	close(gopts->uffd);
437 	gopts->uffd = -1;
438 }
439 
440 static void sigalrm(int sig)
441 {
442 	if (sig != SIGALRM)
443 		abort();
444 	gopts->test_uffdio_copy_eexist = true;
445 	alarm(ALARM_INTERVAL_SECS);
446 }
447 
448 int main(int argc, char **argv)
449 {
450 	unsigned long nr_cpus;
451 	size_t bytes;
452 
453 	gopts = (uffd_global_test_opts_t *) malloc(sizeof(uffd_global_test_opts_t));
454 
455 	if (argc < 4)
456 		usage();
457 
458 	ksft_print_header();
459 	ksft_set_plan(1);
460 
461 	if (signal(SIGALRM, sigalrm) == SIG_ERR)
462 		err("failed to arm SIGALRM");
463 	alarm(ALARM_INTERVAL_SECS);
464 
465 	parse_test_type_arg(gopts, argv[1]);
466 	bytes = atol(argv[2]) * 1024 * 1024;
467 
468 	nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
469 	if (nr_cpus > 32) {
470 		/* Don't let calculation below go to zero. */
471 		ksft_print_msg("_SC_NPROCESSORS_ONLN (%lu) too large, capping nr_threads to 32\n",
472 			       nr_cpus);
473 		gopts->nr_parallel = 32;
474 	} else {
475 		gopts->nr_parallel = nr_cpus;
476 	}
477 
478 	/*
479 	 * src and dst each require bytes / page_size number of hugepages.
480 	 * Ensure nr_parallel - 1 hugepages on top of that to account
481 	 * for racy extra reservation of hugepages.
482 	 */
483 	if (gopts->test_type == TEST_HUGETLB) {
484 		unsigned long nr = 2 * (bytes / gopts->page_size) + gopts->nr_parallel - 1;
485 
486 		if (!hugetlb_setup_default(nr))
487 			ksft_exit_skip("Skipping userfaultfd... not enough hugepages\n");
488 	}
489 
490 	gopts->nr_pages_per_cpu = bytes / gopts->page_size / gopts->nr_parallel;
491 	if (!gopts->nr_pages_per_cpu) {
492 		ksft_exit_skip("pages_per_cpu = 0, cannot test (%zu / %lu / %lu)\n",
493 			       bytes, gopts->page_size, gopts->nr_parallel);
494 	}
495 
496 	bounces = atoi(argv[3]);
497 	if (bounces <= 0) {
498 		_err("invalid bounces");
499 		usage();
500 	}
501 	gopts->nr_pages = gopts->nr_pages_per_cpu * gopts->nr_parallel;
502 
503 	ksft_print_msg("nr_pages: %lu, nr_pages_per_cpu: %lu\n",
504 		       gopts->nr_pages, gopts->nr_pages_per_cpu);
505 
506 	ksft_test_result(!userfaultfd_stress(gopts),
507 			 "uffd-stress %s\n", argv[1]);
508 	ksft_finished();
509 }
510 
511 #else /* __NR_userfaultfd */
512 
513 #warning "missing __NR_userfaultfd definition"
514 
515 int main(void)
516 {
517 	ksft_print_header();
518 	ksft_exit_skip("missing __NR_userfaultfd definition\n");
519 }
520 
521 #endif /* __NR_userfaultfd */
522