btrfs/220: fix how we tests for mount options
[xfstests-dev.git] / src / t_mmap_fallocate.c
1 #include <fcntl.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <libgen.h>
5 #include <sys/mman.h>
6 #include <unistd.h>
7
8 int main(int argc, char **argv)
9 {
10         int fd;
11         char *buf;
12         size_t fsize, i;
13
14         if (argc != 3) {
15                 fprintf(stderr, "Usage: %s <file> <size-in-KB>\n",
16                         basename(argv[0]));
17                 exit(1);
18         }
19
20         fsize = strtol(argv[2], NULL, 10);
21         if (fsize <= 0) {
22                 fprintf(stderr, "Invalid file size: %s\n", argv[2]);
23                 exit(1);
24         }
25         fsize <<= 10;
26
27         fd = open(argv[1], O_RDWR | O_CREAT | O_TRUNC, 0644);
28         if (fd < 0) {
29                 perror("Cannot open file");
30                 exit(1);
31         }
32
33         buf = mmap(NULL, fsize, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
34         if (buf == MAP_FAILED) {
35                 perror("Cannot memory map");
36                 exit(1);
37         }
38
39         /*
40          * We extend the file byte-by-byte through fallocate(2) and write data
41          * to each byte through the mmap. Then we verify whether the data is
42          * really there to see whether the zeroing of last file page during
43          * writeback didn't corrupt the data.
44          */
45         for (i = 0; i < fsize; i++) {
46                 if (posix_fallocate(fd, i, 1) != 0) {
47                         perror("Cannot fallocate");
48                         exit(1);
49                 }
50                 buf[i] = 0x78;
51
52                 if (buf[i] != 0x78) {
53                         fprintf(stderr,
54                                 "Value not written correctly (off=%lu)\n",
55                                 (unsigned long)i);
56                         exit(1);
57                 }
58         }
59
60         for (i = 0; i < fsize; i++) {
61                 if (buf[i] != 0x78) {
62                         fprintf(stderr, "Value has been modified (off=%lu)\n",
63                                 (unsigned long)i);
64                         exit(1);
65                 }
66         }
67
68         return 0;
69 }