reflink: ensure that we can handle reflinking a lot of extents
[xfstests-dev.git] / src / punch-alternating.c
1 /*
2  * Punch out every other block in a file.
3  * Copyright (C) 2016 Oracle.
4  */
5 #include <stdio.h>
6 #include <sys/types.h>
7 #include <sys/stat.h>
8 #include <unistd.h>
9 #include <fcntl.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include "global.h"
13
14 int main(int argc, char *argv[])
15 {
16         struct stat     s;
17         off_t           offset;
18         int             fd;
19         blksize_t       blksz;
20         off_t           sz;
21         int             mode;
22         int             error;
23
24         if (argc != 2) {
25                 printf("Usage: %s file\n", argv[0]);
26                 printf("Punches every other block in the file.\n");
27                 return 1;
28         }
29
30         fd = open(argv[1], O_WRONLY);
31         if (fd < 0)
32                 goto err;
33
34         error = fstat(fd, &s);
35         if (error)
36                 goto err;
37
38         sz = s.st_size;
39         blksz = s.st_blksize;
40
41         mode = FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE;
42         for (offset = 0; offset < sz; offset += blksz * 2) {
43                 error = fallocate(fd, mode, offset, blksz);
44                 if (error)
45                         goto err;
46         }
47
48         error = fsync(fd);
49         if (error)
50                 goto err;
51
52         error = close(fd);
53         if (error)
54                 goto err;
55         return 0;
56 err:
57         perror(argv[1]);
58         return 2;
59 }