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