]> git.kernelconcepts.de Git - karo-tx-linux.git/blob - tools/testing/selftests/vm/userfaultfd.c
regmap: rbtree: When adding a reg do a bsearch for target node
[karo-tx-linux.git] / tools / testing / selftests / vm / userfaultfd.c
1 /*
2  * Stress userfaultfd syscall.
3  *
4  *  Copyright (C) 2015  Red Hat, Inc.
5  *
6  *  This work is licensed under the terms of the GNU GPL, version 2. See
7  *  the COPYING file in the top-level directory.
8  *
9  * This test allocates two virtual areas and bounces the physical
10  * memory across the two virtual areas (from area_src to area_dst)
11  * using userfaultfd.
12  *
13  * There are three threads running per CPU:
14  *
15  * 1) one per-CPU thread takes a per-page pthread_mutex in a random
16  *    page of the area_dst (while the physical page may still be in
17  *    area_src), and increments a per-page counter in the same page,
18  *    and checks its value against a verification region.
19  *
20  * 2) another per-CPU thread handles the userfaults generated by
21  *    thread 1 above. userfaultfd blocking reads or poll() modes are
22  *    exercised interleaved.
23  *
24  * 3) one last per-CPU thread transfers the memory in the background
25  *    at maximum bandwidth (if not already transferred by thread
26  *    2). Each cpu thread takes cares of transferring a portion of the
27  *    area.
28  *
29  * When all threads of type 3 completed the transfer, one bounce is
30  * complete. area_src and area_dst are then swapped. All threads are
31  * respawned and so the bounce is immediately restarted in the
32  * opposite direction.
33  *
34  * per-CPU threads 1 by triggering userfaults inside
35  * pthread_mutex_lock will also verify the atomicity of the memory
36  * transfer (UFFDIO_COPY).
37  *
38  * The program takes two parameters: the amounts of physical memory in
39  * megabytes (MiB) of the area and the number of bounces to execute.
40  *
41  * # 100MiB 99999 bounces
42  * ./userfaultfd 100 99999
43  *
44  * # 1GiB 99 bounces
45  * ./userfaultfd 1000 99
46  *
47  * # 10MiB-~6GiB 999 bounces, continue forever unless an error triggers
48  * while ./userfaultfd $[RANDOM % 6000 + 10] 999; do true; done
49  */
50
51 #define _GNU_SOURCE
52 #include <stdio.h>
53 #include <errno.h>
54 #include <unistd.h>
55 #include <stdlib.h>
56 #include <sys/types.h>
57 #include <sys/stat.h>
58 #include <fcntl.h>
59 #include <time.h>
60 #include <signal.h>
61 #include <poll.h>
62 #include <string.h>
63 #include <sys/mman.h>
64 #include <sys/syscall.h>
65 #include <sys/ioctl.h>
66 #include <pthread.h>
67 #include "../../../../include/uapi/linux/userfaultfd.h"
68
69 #ifdef __x86_64__
70 #define __NR_userfaultfd 323
71 #elif defined(__i386__)
72 #define __NR_userfaultfd 374
73 #elif defined(__powewrpc__)
74 #define __NR_userfaultfd 364
75 #else
76 #error "missing __NR_userfaultfd definition"
77 #endif
78
79 static unsigned long nr_cpus, nr_pages, nr_pages_per_cpu, page_size;
80
81 #define BOUNCE_RANDOM           (1<<0)
82 #define BOUNCE_RACINGFAULTS     (1<<1)
83 #define BOUNCE_VERIFY           (1<<2)
84 #define BOUNCE_POLL             (1<<3)
85 static int bounces;
86
87 static unsigned long long *count_verify;
88 static int uffd, finished, *pipefd;
89 static char *area_src, *area_dst;
90 static char *zeropage;
91 pthread_attr_t attr;
92
93 /* pthread_mutex_t starts at page offset 0 */
94 #define area_mutex(___area, ___nr)                                      \
95         ((pthread_mutex_t *) ((___area) + (___nr)*page_size))
96 /*
97  * count is placed in the page after pthread_mutex_t naturally aligned
98  * to avoid non alignment faults on non-x86 archs.
99  */
100 #define area_count(___area, ___nr)                                      \
101         ((volatile unsigned long long *) ((unsigned long)               \
102                                  ((___area) + (___nr)*page_size +       \
103                                   sizeof(pthread_mutex_t) +             \
104                                   sizeof(unsigned long long) - 1) &     \
105                                  ~(unsigned long)(sizeof(unsigned long long) \
106                                                   -  1)))
107
108 static int my_bcmp(char *str1, char *str2, size_t n)
109 {
110         unsigned long i;
111         for (i = 0; i < n; i++)
112                 if (str1[i] != str2[i])
113                         return 1;
114         return 0;
115 }
116
117 static void *locking_thread(void *arg)
118 {
119         unsigned long cpu = (unsigned long) arg;
120         struct random_data rand;
121         unsigned long page_nr = *(&(page_nr)); /* uninitialized warning */
122         int32_t rand_nr;
123         unsigned long long count;
124         char randstate[64];
125         unsigned int seed;
126         time_t start;
127
128         if (bounces & BOUNCE_RANDOM) {
129                 seed = (unsigned int) time(NULL) - bounces;
130                 if (!(bounces & BOUNCE_RACINGFAULTS))
131                         seed += cpu;
132                 bzero(&rand, sizeof(rand));
133                 bzero(&randstate, sizeof(randstate));
134                 if (initstate_r(seed, randstate, sizeof(randstate), &rand))
135                         fprintf(stderr, "srandom_r error\n"), exit(1);
136         } else {
137                 page_nr = -bounces;
138                 if (!(bounces & BOUNCE_RACINGFAULTS))
139                         page_nr += cpu * nr_pages_per_cpu;
140         }
141
142         while (!finished) {
143                 if (bounces & BOUNCE_RANDOM) {
144                         if (random_r(&rand, &rand_nr))
145                                 fprintf(stderr, "random_r 1 error\n"), exit(1);
146                         page_nr = rand_nr;
147                         if (sizeof(page_nr) > sizeof(rand_nr)) {
148                                 if (random_r(&rand, &rand_nr))
149                                         fprintf(stderr, "random_r 2 error\n"), exit(1);
150                                 page_nr |= (((unsigned long) rand_nr) << 16) <<
151                                            16;
152                         }
153                 } else
154                         page_nr += 1;
155                 page_nr %= nr_pages;
156
157                 start = time(NULL);
158                 if (bounces & BOUNCE_VERIFY) {
159                         count = *area_count(area_dst, page_nr);
160                         if (!count)
161                                 fprintf(stderr,
162                                         "page_nr %lu wrong count %Lu %Lu\n",
163                                         page_nr, count,
164                                         count_verify[page_nr]), exit(1);
165
166
167                         /*
168                          * We can't use bcmp (or memcmp) because that
169                          * returns 0 erroneously if the memory is
170                          * changing under it (even if the end of the
171                          * page is never changing and always
172                          * different).
173                          */
174 #if 1
175                         if (!my_bcmp(area_dst + page_nr * page_size, zeropage,
176                                      page_size))
177                                 fprintf(stderr,
178                                         "my_bcmp page_nr %lu wrong count %Lu %Lu\n",
179                                         page_nr, count,
180                                         count_verify[page_nr]), exit(1);
181 #else
182                         unsigned long loops;
183
184                         loops = 0;
185                         /* uncomment the below line to test with mutex */
186                         /* pthread_mutex_lock(area_mutex(area_dst, page_nr)); */
187                         while (!bcmp(area_dst + page_nr * page_size, zeropage,
188                                      page_size)) {
189                                 loops += 1;
190                                 if (loops > 10)
191                                         break;
192                         }
193                         /* uncomment below line to test with mutex */
194                         /* pthread_mutex_unlock(area_mutex(area_dst, page_nr)); */
195                         if (loops) {
196                                 fprintf(stderr,
197                                         "page_nr %lu all zero thread %lu %p %lu\n",
198                                         page_nr, cpu, area_dst + page_nr * page_size,
199                                         loops);
200                                 if (loops > 10)
201                                         exit(1);
202                         }
203 #endif
204                 }
205
206                 pthread_mutex_lock(area_mutex(area_dst, page_nr));
207                 count = *area_count(area_dst, page_nr);
208                 if (count != count_verify[page_nr]) {
209                         fprintf(stderr,
210                                 "page_nr %lu memory corruption %Lu %Lu\n",
211                                 page_nr, count,
212                                 count_verify[page_nr]), exit(1);
213                 }
214                 count++;
215                 *area_count(area_dst, page_nr) = count_verify[page_nr] = count;
216                 pthread_mutex_unlock(area_mutex(area_dst, page_nr));
217
218                 if (time(NULL) - start > 1)
219                         fprintf(stderr,
220                                 "userfault too slow %ld "
221                                 "possible false positive with overcommit\n",
222                                 time(NULL) - start);
223         }
224
225         return NULL;
226 }
227
228 static int copy_page(unsigned long offset)
229 {
230         struct uffdio_copy uffdio_copy;
231
232         if (offset >= nr_pages * page_size)
233                 fprintf(stderr, "unexpected offset %lu\n",
234                         offset), exit(1);
235         uffdio_copy.dst = (unsigned long) area_dst + offset;
236         uffdio_copy.src = (unsigned long) area_src + offset;
237         uffdio_copy.len = page_size;
238         uffdio_copy.mode = 0;
239         uffdio_copy.copy = 0;
240         if (ioctl(uffd, UFFDIO_COPY, &uffdio_copy)) {
241                 /* real retval in ufdio_copy.copy */
242                 if (uffdio_copy.copy != -EEXIST)
243                         fprintf(stderr, "UFFDIO_COPY error %Ld\n",
244                                 uffdio_copy.copy), exit(1);
245         } else if (uffdio_copy.copy != page_size) {
246                 fprintf(stderr, "UFFDIO_COPY unexpected copy %Ld\n",
247                         uffdio_copy.copy), exit(1);
248         } else
249                 return 1;
250         return 0;
251 }
252
253 static void *uffd_poll_thread(void *arg)
254 {
255         unsigned long cpu = (unsigned long) arg;
256         struct pollfd pollfd[2];
257         struct uffd_msg msg;
258         int ret;
259         unsigned long offset;
260         char tmp_chr;
261         unsigned long userfaults = 0;
262
263         pollfd[0].fd = uffd;
264         pollfd[0].events = POLLIN;
265         pollfd[1].fd = pipefd[cpu*2];
266         pollfd[1].events = POLLIN;
267
268         for (;;) {
269                 ret = poll(pollfd, 2, -1);
270                 if (!ret)
271                         fprintf(stderr, "poll error %d\n", ret), exit(1);
272                 if (ret < 0)
273                         perror("poll"), exit(1);
274                 if (pollfd[1].revents & POLLIN) {
275                         if (read(pollfd[1].fd, &tmp_chr, 1) != 1)
276                                 fprintf(stderr, "read pipefd error\n"),
277                                         exit(1);
278                         break;
279                 }
280                 if (!(pollfd[0].revents & POLLIN))
281                         fprintf(stderr, "pollfd[0].revents %d\n",
282                                 pollfd[0].revents), exit(1);
283                 ret = read(uffd, &msg, sizeof(msg));
284                 if (ret < 0) {
285                         if (errno == EAGAIN)
286                                 continue;
287                         perror("nonblocking read error"), exit(1);
288                 }
289                 if (msg.event != UFFD_EVENT_PAGEFAULT)
290                         fprintf(stderr, "unexpected msg event %u\n",
291                                 msg.event), exit(1);
292                 if (msg.arg.pagefault.flags & UFFD_PAGEFAULT_FLAG_WRITE)
293                         fprintf(stderr, "unexpected write fault\n"), exit(1);
294                 offset = (char *)(unsigned long)msg.arg.pagefault.address -
295                          area_dst;
296                 offset &= ~(page_size-1);
297                 if (copy_page(offset))
298                         userfaults++;
299         }
300         return (void *)userfaults;
301 }
302
303 pthread_mutex_t uffd_read_mutex = PTHREAD_MUTEX_INITIALIZER;
304
305 static void *uffd_read_thread(void *arg)
306 {
307         unsigned long *this_cpu_userfaults;
308         struct uffd_msg msg;
309         unsigned long offset;
310         int ret;
311
312         this_cpu_userfaults = (unsigned long *) arg;
313         *this_cpu_userfaults = 0;
314
315         pthread_mutex_unlock(&uffd_read_mutex);
316         /* from here cancellation is ok */
317
318         for (;;) {
319                 ret = read(uffd, &msg, sizeof(msg));
320                 if (ret != sizeof(msg)) {
321                         if (ret < 0)
322                                 perror("blocking read error"), exit(1);
323                         else
324                                 fprintf(stderr, "short read\n"), exit(1);
325                 }
326                 if (msg.event != UFFD_EVENT_PAGEFAULT)
327                         fprintf(stderr, "unexpected msg event %u\n",
328                                 msg.event), exit(1);
329                 if (bounces & BOUNCE_VERIFY &&
330                     msg.arg.pagefault.flags & UFFD_PAGEFAULT_FLAG_WRITE)
331                         fprintf(stderr, "unexpected write fault\n"), exit(1);
332                 offset = (char *)(unsigned long)msg.arg.pagefault.address -
333                          area_dst;
334                 offset &= ~(page_size-1);
335                 if (copy_page(offset))
336                         (*this_cpu_userfaults)++;
337         }
338         return (void *)NULL;
339 }
340
341 static void *background_thread(void *arg)
342 {
343         unsigned long cpu = (unsigned long) arg;
344         unsigned long page_nr;
345
346         for (page_nr = cpu * nr_pages_per_cpu;
347              page_nr < (cpu+1) * nr_pages_per_cpu;
348              page_nr++)
349                 copy_page(page_nr * page_size);
350
351         return NULL;
352 }
353
354 static int stress(unsigned long *userfaults)
355 {
356         unsigned long cpu;
357         pthread_t locking_threads[nr_cpus];
358         pthread_t uffd_threads[nr_cpus];
359         pthread_t background_threads[nr_cpus];
360         void **_userfaults = (void **) userfaults;
361
362         finished = 0;
363         for (cpu = 0; cpu < nr_cpus; cpu++) {
364                 if (pthread_create(&locking_threads[cpu], &attr,
365                                    locking_thread, (void *)cpu))
366                         return 1;
367                 if (bounces & BOUNCE_POLL) {
368                         if (pthread_create(&uffd_threads[cpu], &attr,
369                                            uffd_poll_thread, (void *)cpu))
370                                 return 1;
371                 } else {
372                         if (pthread_create(&uffd_threads[cpu], &attr,
373                                            uffd_read_thread,
374                                            &_userfaults[cpu]))
375                                 return 1;
376                         pthread_mutex_lock(&uffd_read_mutex);
377                 }
378                 if (pthread_create(&background_threads[cpu], &attr,
379                                    background_thread, (void *)cpu))
380                         return 1;
381         }
382         for (cpu = 0; cpu < nr_cpus; cpu++)
383                 if (pthread_join(background_threads[cpu], NULL))
384                         return 1;
385
386         /*
387          * Be strict and immediately zap area_src, the whole area has
388          * been transferred already by the background treads. The
389          * area_src could then be faulted in in a racy way by still
390          * running uffdio_threads reading zeropages after we zapped
391          * area_src (but they're guaranteed to get -EEXIST from
392          * UFFDIO_COPY without writing zero pages into area_dst
393          * because the background threads already completed).
394          */
395         if (madvise(area_src, nr_pages * page_size, MADV_DONTNEED)) {
396                 perror("madvise");
397                 return 1;
398         }
399
400         for (cpu = 0; cpu < nr_cpus; cpu++) {
401                 char c;
402                 if (bounces & BOUNCE_POLL) {
403                         if (write(pipefd[cpu*2+1], &c, 1) != 1) {
404                                 fprintf(stderr, "pipefd write error\n");
405                                 return 1;
406                         }
407                         if (pthread_join(uffd_threads[cpu], &_userfaults[cpu]))
408                                 return 1;
409                 } else {
410                         if (pthread_cancel(uffd_threads[cpu]))
411                                 return 1;
412                         if (pthread_join(uffd_threads[cpu], NULL))
413                                 return 1;
414                 }
415         }
416
417         finished = 1;
418         for (cpu = 0; cpu < nr_cpus; cpu++)
419                 if (pthread_join(locking_threads[cpu], NULL))
420                         return 1;
421
422         return 0;
423 }
424
425 static int userfaultfd_stress(void)
426 {
427         void *area;
428         char *tmp_area;
429         unsigned long nr;
430         struct uffdio_register uffdio_register;
431         struct uffdio_api uffdio_api;
432         unsigned long cpu;
433         int uffd_flags;
434         unsigned long userfaults[nr_cpus];
435
436         if (posix_memalign(&area, page_size, nr_pages * page_size)) {
437                 fprintf(stderr, "out of memory\n");
438                 return 1;
439         }
440         area_src = area;
441         if (posix_memalign(&area, page_size, nr_pages * page_size)) {
442                 fprintf(stderr, "out of memory\n");
443                 return 1;
444         }
445         area_dst = area;
446
447         uffd = syscall(__NR_userfaultfd, O_CLOEXEC | O_NONBLOCK);
448         if (uffd < 0) {
449                 fprintf(stderr,
450                         "userfaultfd syscall not available in this kernel\n");
451                 return 1;
452         }
453         uffd_flags = fcntl(uffd, F_GETFD, NULL);
454
455         uffdio_api.api = UFFD_API;
456         uffdio_api.features = 0;
457         if (ioctl(uffd, UFFDIO_API, &uffdio_api)) {
458                 fprintf(stderr, "UFFDIO_API\n");
459                 return 1;
460         }
461         if (uffdio_api.api != UFFD_API) {
462                 fprintf(stderr, "UFFDIO_API error %Lu\n", uffdio_api.api);
463                 return 1;
464         }
465
466         count_verify = malloc(nr_pages * sizeof(unsigned long long));
467         if (!count_verify) {
468                 perror("count_verify");
469                 return 1;
470         }
471
472         for (nr = 0; nr < nr_pages; nr++) {
473                 *area_mutex(area_src, nr) = (pthread_mutex_t)
474                         PTHREAD_MUTEX_INITIALIZER;
475                 count_verify[nr] = *area_count(area_src, nr) = 1;
476         }
477
478         pipefd = malloc(sizeof(int) * nr_cpus * 2);
479         if (!pipefd) {
480                 perror("pipefd");
481                 return 1;
482         }
483         for (cpu = 0; cpu < nr_cpus; cpu++) {
484                 if (pipe2(&pipefd[cpu*2], O_CLOEXEC | O_NONBLOCK)) {
485                         perror("pipe");
486                         return 1;
487                 }
488         }
489
490         if (posix_memalign(&area, page_size, page_size)) {
491                 fprintf(stderr, "out of memory\n");
492                 return 1;
493         }
494         zeropage = area;
495         bzero(zeropage, page_size);
496
497         pthread_mutex_lock(&uffd_read_mutex);
498
499         pthread_attr_init(&attr);
500         pthread_attr_setstacksize(&attr, 16*1024*1024);
501
502         while (bounces--) {
503                 unsigned long expected_ioctls;
504
505                 printf("bounces: %d, mode:", bounces);
506                 if (bounces & BOUNCE_RANDOM)
507                         printf(" rnd");
508                 if (bounces & BOUNCE_RACINGFAULTS)
509                         printf(" racing");
510                 if (bounces & BOUNCE_VERIFY)
511                         printf(" ver");
512                 if (bounces & BOUNCE_POLL)
513                         printf(" poll");
514                 printf(", ");
515                 fflush(stdout);
516
517                 if (bounces & BOUNCE_POLL)
518                         fcntl(uffd, F_SETFL, uffd_flags | O_NONBLOCK);
519                 else
520                         fcntl(uffd, F_SETFL, uffd_flags & ~O_NONBLOCK);
521
522                 /* register */
523                 uffdio_register.range.start = (unsigned long) area_dst;
524                 uffdio_register.range.len = nr_pages * page_size;
525                 uffdio_register.mode = UFFDIO_REGISTER_MODE_MISSING;
526                 if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register)) {
527                         fprintf(stderr, "register failure\n");
528                         return 1;
529                 }
530                 expected_ioctls = (1 << _UFFDIO_WAKE) |
531                                   (1 << _UFFDIO_COPY) |
532                                   (1 << _UFFDIO_ZEROPAGE);
533                 if ((uffdio_register.ioctls & expected_ioctls) !=
534                     expected_ioctls) {
535                         fprintf(stderr,
536                                 "unexpected missing ioctl for anon memory\n");
537                         return 1;
538                 }
539
540                 /*
541                  * The madvise done previously isn't enough: some
542                  * uffd_thread could have read userfaults (one of
543                  * those already resolved by the background thread)
544                  * and it may be in the process of calling
545                  * UFFDIO_COPY. UFFDIO_COPY will read the zapped
546                  * area_src and it would map a zero page in it (of
547                  * course such a UFFDIO_COPY is perfectly safe as it'd
548                  * return -EEXIST). The problem comes at the next
549                  * bounce though: that racing UFFDIO_COPY would
550                  * generate zeropages in the area_src, so invalidating
551                  * the previous MADV_DONTNEED. Without this additional
552                  * MADV_DONTNEED those zeropages leftovers in the
553                  * area_src would lead to -EEXIST failure during the
554                  * next bounce, effectively leaving a zeropage in the
555                  * area_dst.
556                  *
557                  * Try to comment this out madvise to see the memory
558                  * corruption being caught pretty quick.
559                  *
560                  * khugepaged is also inhibited to collapse THP after
561                  * MADV_DONTNEED only after the UFFDIO_REGISTER, so it's
562                  * required to MADV_DONTNEED here.
563                  */
564                 if (madvise(area_dst, nr_pages * page_size, MADV_DONTNEED)) {
565                         perror("madvise 2");
566                         return 1;
567                 }
568
569                 /* bounce pass */
570                 if (stress(userfaults))
571                         return 1;
572
573                 /* unregister */
574                 if (ioctl(uffd, UFFDIO_UNREGISTER, &uffdio_register.range)) {
575                         fprintf(stderr, "register failure\n");
576                         return 1;
577                 }
578
579                 /* verification */
580                 if (bounces & BOUNCE_VERIFY) {
581                         for (nr = 0; nr < nr_pages; nr++) {
582                                 if (my_bcmp(area_dst,
583                                             area_dst + nr * page_size,
584                                             sizeof(pthread_mutex_t))) {
585                                         fprintf(stderr,
586                                                 "error mutex 2 %lu\n",
587                                                 nr);
588                                         bounces = 0;
589                                 }
590                                 if (*area_count(area_dst, nr) != count_verify[nr]) {
591                                         fprintf(stderr,
592                                                 "error area_count %Lu %Lu %lu\n",
593                                                 *area_count(area_src, nr),
594                                                 count_verify[nr],
595                                                 nr);
596                                         bounces = 0;
597                                 }
598                         }
599                 }
600
601                 /* prepare next bounce */
602                 tmp_area = area_src;
603                 area_src = area_dst;
604                 area_dst = tmp_area;
605
606                 printf("userfaults:");
607                 for (cpu = 0; cpu < nr_cpus; cpu++)
608                         printf(" %lu", userfaults[cpu]);
609                 printf("\n");
610         }
611
612         return 0;
613 }
614
615 int main(int argc, char **argv)
616 {
617         if (argc < 3)
618                 fprintf(stderr, "Usage: <MiB> <bounces>\n"), exit(1);
619         nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
620         page_size = sysconf(_SC_PAGE_SIZE);
621         if ((unsigned long) area_count(NULL, 0) + sizeof(unsigned long long) >
622             page_size)
623                 fprintf(stderr, "Impossible to run this test\n"), exit(2);
624         nr_pages_per_cpu = atol(argv[1]) * 1024*1024 / page_size /
625                 nr_cpus;
626         if (!nr_pages_per_cpu) {
627                 fprintf(stderr, "invalid MiB\n");
628                 fprintf(stderr, "Usage: <MiB> <bounces>\n"), exit(1);
629         }
630         bounces = atoi(argv[2]);
631         if (bounces <= 0) {
632                 fprintf(stderr, "invalid bounces\n");
633                 fprintf(stderr, "Usage: <MiB> <bounces>\n"), exit(1);
634         }
635         nr_pages = nr_pages_per_cpu * nr_cpus;
636         printf("nr_pages: %lu, nr_pages_per_cpu: %lu\n",
637                nr_pages, nr_pages_per_cpu);
638         return userfaultfd_stress();
639 }