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