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