xref: /linux/tools/testing/selftests/mm/uffd-stress.c (revision 8804d970fab45726b3c7cd7f240b31122aa94219)
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 
usage(void)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 
uffd_stats_reset(uffd_global_test_opts_t * gopts,struct uffd_args * args,unsigned long n_cpus)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 
locking_thread(void * arg)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 
copy_page_retry(uffd_global_test_opts_t * gopts,unsigned long offset)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 
uffd_read_thread(void * arg)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 
background_thread(void * arg)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 
stress(struct uffd_args * args)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;
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 
userfaultfd_stress(uffd_global_test_opts_t * gopts)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 		printf("bounces: %d, mode:", bounces);
290 		if (bounces & BOUNCE_RANDOM)
291 			printf(" rnd");
292 		if (bounces & BOUNCE_RACINGFAULTS)
293 			printf(" racing");
294 		if (bounces & BOUNCE_VERIFY)
295 			printf(" ver");
296 		if (bounces & BOUNCE_POLL)
297 			printf(" poll");
298 		else
299 			printf(" read");
300 		printf(", ");
301 		fflush(stdout);
302 
303 		if (bounces & BOUNCE_POLL)
304 			fcntl(gopts->uffd, F_SETFL, gopts->uffd_flags | O_NONBLOCK);
305 		else
306 			fcntl(gopts->uffd, F_SETFL, gopts->uffd_flags & ~O_NONBLOCK);
307 
308 		/* register */
309 		if (uffd_register(gopts->uffd, gopts->area_dst, mem_size,
310 				  true, gopts->test_uffdio_wp, false))
311 			err("register failure");
312 
313 		if (gopts->area_dst_alias) {
314 			if (uffd_register(gopts->uffd, gopts->area_dst_alias, mem_size,
315 					  true, gopts->test_uffdio_wp, false))
316 				err("register failure alias");
317 		}
318 
319 		/*
320 		 * The madvise done previously isn't enough: some
321 		 * uffd_thread could have read userfaults (one of
322 		 * those already resolved by the background thread)
323 		 * and it may be in the process of calling
324 		 * UFFDIO_COPY. UFFDIO_COPY will read the zapped
325 		 * area_src and it would map a zero page in it (of
326 		 * course such a UFFDIO_COPY is perfectly safe as it'd
327 		 * return -EEXIST). The problem comes at the next
328 		 * bounce though: that racing UFFDIO_COPY would
329 		 * generate zeropages in the area_src, so invalidating
330 		 * the previous MADV_DONTNEED. Without this additional
331 		 * MADV_DONTNEED those zeropages leftovers in the
332 		 * area_src would lead to -EEXIST failure during the
333 		 * next bounce, effectively leaving a zeropage in the
334 		 * area_dst.
335 		 *
336 		 * Try to comment this out madvise to see the memory
337 		 * corruption being caught pretty quick.
338 		 *
339 		 * khugepaged is also inhibited to collapse THP after
340 		 * MADV_DONTNEED only after the UFFDIO_REGISTER, so it's
341 		 * required to MADV_DONTNEED here.
342 		 */
343 		uffd_test_ops->release_pages(gopts, gopts->area_dst);
344 
345 		uffd_stats_reset(gopts, args, gopts->nr_parallel);
346 
347 		/* bounce pass */
348 		if (stress(args)) {
349 			uffd_test_ctx_clear(gopts);
350 			return 1;
351 		}
352 
353 		/* Clear all the write protections if there is any */
354 		if (gopts->test_uffdio_wp)
355 			wp_range(gopts->uffd, (unsigned long)gopts->area_dst,
356 				 gopts->nr_pages * gopts->page_size, false);
357 
358 		/* unregister */
359 		if (uffd_unregister(gopts->uffd, gopts->area_dst, mem_size))
360 			err("unregister failure");
361 		if (gopts->area_dst_alias) {
362 			if (uffd_unregister(gopts->uffd, gopts->area_dst_alias, mem_size))
363 				err("unregister failure alias");
364 		}
365 
366 		/* verification */
367 		if (bounces & BOUNCE_VERIFY)
368 			for (nr = 0; nr < gopts->nr_pages; nr++)
369 				if (*area_count(gopts->area_dst, nr, gopts) !=
370 						gopts->count_verify[nr])
371 					err("error area_count %llu %llu %lu\n",
372 					    *area_count(gopts->area_src, nr, gopts),
373 					    gopts->count_verify[nr], nr);
374 
375 		/* prepare next bounce */
376 		swap(gopts->area_src, gopts->area_dst);
377 
378 		swap(gopts->area_src_alias, gopts->area_dst_alias);
379 
380 		uffd_stats_report(args, gopts->nr_parallel);
381 	}
382 	uffd_test_ctx_clear(gopts);
383 
384 	return 0;
385 }
386 
set_test_type(uffd_global_test_opts_t * gopts,const char * type)387 static void set_test_type(uffd_global_test_opts_t *gopts, const char *type)
388 {
389 	if (!strcmp(type, "anon")) {
390 		gopts->test_type = TEST_ANON;
391 		uffd_test_ops = &anon_uffd_test_ops;
392 	} else if (!strcmp(type, "hugetlb")) {
393 		gopts->test_type = TEST_HUGETLB;
394 		uffd_test_ops = &hugetlb_uffd_test_ops;
395 		gopts->map_shared = true;
396 	} else if (!strcmp(type, "hugetlb-private")) {
397 		gopts->test_type = TEST_HUGETLB;
398 		uffd_test_ops = &hugetlb_uffd_test_ops;
399 	} else if (!strcmp(type, "shmem")) {
400 		gopts->map_shared = true;
401 		gopts->test_type = TEST_SHMEM;
402 		uffd_test_ops = &shmem_uffd_test_ops;
403 	} else if (!strcmp(type, "shmem-private")) {
404 		gopts->test_type = TEST_SHMEM;
405 		uffd_test_ops = &shmem_uffd_test_ops;
406 	}
407 }
408 
parse_test_type_arg(uffd_global_test_opts_t * gopts,const char * raw_type)409 static void parse_test_type_arg(uffd_global_test_opts_t *gopts, const char *raw_type)
410 {
411 	set_test_type(gopts, raw_type);
412 
413 	if (!gopts->test_type)
414 		err("failed to parse test type argument: '%s'", raw_type);
415 
416 	if (gopts->test_type == TEST_HUGETLB)
417 		gopts->page_size = default_huge_page_size();
418 	else
419 		gopts->page_size = sysconf(_SC_PAGE_SIZE);
420 
421 	if (!gopts->page_size)
422 		err("Unable to determine page size");
423 	if ((unsigned long) area_count(NULL, 0, gopts) + sizeof(unsigned long long) * 2
424 	    > gopts->page_size)
425 		err("Impossible to run this test");
426 
427 	/*
428 	 * Whether we can test certain features depends not just on test type,
429 	 * but also on whether or not this particular kernel supports the
430 	 * feature.
431 	 */
432 
433 	if (uffd_get_features(&features) && errno == ENOENT)
434 		ksft_exit_skip("failed to get available features (%d)\n", errno);
435 
436 	gopts->test_uffdio_wp = gopts->test_uffdio_wp &&
437 		(features & UFFD_FEATURE_PAGEFAULT_FLAG_WP);
438 
439 	if (gopts->test_type != TEST_ANON && !(features & UFFD_FEATURE_WP_HUGETLBFS_SHMEM))
440 		gopts->test_uffdio_wp = false;
441 
442 	close(gopts->uffd);
443 	gopts->uffd = -1;
444 }
445 
sigalrm(int sig)446 static void sigalrm(int sig)
447 {
448 	if (sig != SIGALRM)
449 		abort();
450 	gopts->test_uffdio_copy_eexist = true;
451 	alarm(ALARM_INTERVAL_SECS);
452 }
453 
main(int argc,char ** argv)454 int main(int argc, char **argv)
455 {
456 	unsigned long nr_cpus;
457 	size_t bytes;
458 
459 	gopts = (uffd_global_test_opts_t *) malloc(sizeof(uffd_global_test_opts_t));
460 
461 	if (argc < 4)
462 		usage();
463 
464 	if (signal(SIGALRM, sigalrm) == SIG_ERR)
465 		err("failed to arm SIGALRM");
466 	alarm(ALARM_INTERVAL_SECS);
467 
468 	parse_test_type_arg(gopts, argv[1]);
469 	bytes = atol(argv[2]) * 1024 * 1024;
470 
471 	nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
472 	if (nr_cpus > 32) {
473 		/* Don't let calculation below go to zero. */
474 		ksft_print_msg("_SC_NPROCESSORS_ONLN (%lu) too large, capping nr_threads to 32\n",
475 			       nr_cpus);
476 		gopts->nr_parallel = 32;
477 	} else {
478 		gopts->nr_parallel = nr_cpus;
479 	}
480 
481 	/*
482 	 * src and dst each require bytes / page_size number of hugepages.
483 	 * Ensure nr_parallel - 1 hugepages on top of that to account
484 	 * for racy extra reservation of hugepages.
485 	 */
486 	if (gopts->test_type == TEST_HUGETLB &&
487 	   get_free_hugepages() < 2 * (bytes / gopts->page_size) + gopts->nr_parallel - 1) {
488 		printf("skip: Skipping userfaultfd... not enough hugepages\n");
489 		return KSFT_SKIP;
490 	}
491 
492 	gopts->nr_pages_per_cpu = bytes / gopts->page_size / gopts->nr_parallel;
493 	if (!gopts->nr_pages_per_cpu) {
494 		_err("pages_per_cpu = 0, cannot test (%lu / %lu / %lu)",
495 			bytes, gopts->page_size, gopts->nr_parallel);
496 		usage();
497 	}
498 
499 	bounces = atoi(argv[3]);
500 	if (bounces <= 0) {
501 		_err("invalid bounces");
502 		usage();
503 	}
504 	gopts->nr_pages = gopts->nr_pages_per_cpu * gopts->nr_parallel;
505 
506 	printf("nr_pages: %lu, nr_pages_per_cpu: %lu\n",
507 	       gopts->nr_pages, gopts->nr_pages_per_cpu);
508 	return userfaultfd_stress(gopts);
509 }
510 
511 #else /* __NR_userfaultfd */
512 
513 #warning "missing __NR_userfaultfd definition"
514 
main(void)515 int main(void)
516 {
517 	printf("skip: Skipping userfaultfd test (missing __NR_userfaultfd)\n");
518 	return KSFT_SKIP;
519 }
520 
521 #endif /* __NR_userfaultfd */
522