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