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