fstests: convert remaining tests to SPDX license tags
[xfstests-dev.git] / src / t_mmap_stale_pmd.c
1 #include <errno.h>
2 #include <fcntl.h>
3 #include <libgen.h>
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <string.h>
7 #include <sys/mman.h>
8 #include <sys/stat.h>
9 #include <sys/types.h>
10 #include <unistd.h>
11
12 #define MiB(a) ((a)*1024*1024)
13
14 void err_exit(char *op)
15 {
16         fprintf(stderr, "%s: %s\n", op, strerror(errno));
17         exit(1);
18 }
19
20 int main(int argc, char *argv[])
21 {
22         volatile int a __attribute__((__unused__));
23         char *buffer = "HELLO WORLD!";
24         char *data;
25         int fd, err, ret = 0;
26
27         if (argc < 2) {
28                 printf("Usage: %s <pmem file>\n", basename(argv[0]));
29                 exit(0);
30         }
31
32         fd = open(argv[1], O_RDWR|O_CREAT, S_IRUSR|S_IWUSR);
33         if (fd < 0)
34                 err_exit("fd");
35
36         /*
37          * This allows us to map a huge zero page, and we do it at a non-zero
38          * offset for a little additional testing.
39          */
40         ftruncate(fd, 0);
41         ftruncate(fd, MiB(4));
42
43         data = mmap(NULL, MiB(2), PROT_READ, MAP_SHARED, fd, MiB(2));
44
45         /*
46          * This faults in a 2MiB zero page to satisfy the read.
47          * 'a' is volatile so this read doesn't get optimized out.
48          */
49         a = data[0];
50
51         pwrite(fd, buffer, strlen(buffer), MiB(2));
52
53         /*
54          * Try and use the mmap to read back the data we just wrote with
55          * pwrite().  If the kernel bug is present the mapping from the 2MiB
56          * zero page will still be intact, and we'll read back zeros instead.
57          */
58         if (strncmp(buffer, data, strlen(buffer))) {
59                 fprintf(stderr, "strncmp mismatch: '%s' vs '%s'\n", buffer,
60                                 data);
61                 ret = 1;
62         }
63
64         err = munmap(data, MiB(2));
65         if (err < 0)
66                 err_exit("munmap");
67
68         err = close(fd);
69         if (err < 0)
70                 err_exit("close");
71
72         return ret;
73 }