1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright (c) 2017 Intel Corporation. */
12 #include <sys/types.h>
15 #define MiB(a) ((a)*1024*1024)
18 void err_exit(char *op)
20 fprintf(stderr, "%s: %s\n", op, strerror(errno));
24 void worker_fn(void *ptr)
26 char *data = (char *)ptr;
30 for (i = 0; i < 10; i++) {
34 err = madvise(data, MiB(2), MADV_DONTNEED);
38 /* Mix up the thread timings to encourage the race. */
39 err = usleep(rand() % 100);
45 int main(int argc, char *argv[])
47 pthread_t thread[NUM_THREADS];
52 printf("Usage: %s <file>\n", basename(argv[0]));
56 fd = open(argv[1], O_RDWR|O_CREAT, S_IRUSR|S_IWUSR);
60 /* This allows us to map a huge page. */
62 ftruncate(fd, MiB(2));
65 * First we set up a shared mapping. Our write will (hopefully) get
66 * the filesystem to give us a 2MiB huge page DAX mapping. We will
67 * then use this 2MiB page for our private mapping race.
69 data = mmap(NULL, MiB(2), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
70 if (data == MAP_FAILED)
71 err_exit("shared mmap");
75 err = munmap(data, MiB(2));
77 err_exit("shared munmap");
79 for (i = 0; i < 500; i++) {
80 data = mmap(NULL, MiB(2), PROT_READ|PROT_WRITE, MAP_PRIVATE,
82 if (data == MAP_FAILED)
83 err_exit("private mmap");
85 for (j = 0; j < NUM_THREADS; j++) {
86 err = pthread_create(&thread[j], NULL,
87 (void*)&worker_fn, data);
89 err_exit("pthread_create");
92 for (j = 0; j < NUM_THREADS; j++) {
93 err = pthread_join(thread[j], NULL);
95 err_exit("pthread_join");
98 err = munmap(data, MiB(2));
100 err_exit("private munmap");