xfs/419: remove irrelevant swapfile test
[xfstests-dev.git] / src / writev_on_pagefault.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Takes page fault while writev is iterating over the vectors in the IOV
4  * Copyright (C) 2017 Red Hat, Inc. All Rights reserved.
5  */
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <sys/types.h>
9 #include <sys/stat.h>
10 #include <fcntl.h>
11 #include <string.h>
12 #include <unistd.h>
13 #include <sys/uio.h>
14 #include <limits.h>
15
16 #ifndef IOV_MAX
17 #define IOV_MAX 1024
18 #endif
19 #define DEF_IOV_CNT 3
20
21
22 void usage(char *progname)
23 {
24         fprintf(stderr, "usage: %s [-i iovcnt] filename\n", progname);
25         fprintf(stderr, "\t-i iovcnt: the count of io vectors (max is 1024), 3 by default\n");
26         exit(1);
27 }
28
29 int main(int argc, char *argv[])
30 {
31         int fd, i, c;
32         ssize_t ret;
33         struct iovec *iov;
34         int pagesz = 4096;
35         char *data = NULL;
36         char *filename = NULL;
37         int iov_cnt = DEF_IOV_CNT;
38
39
40         while ((c = getopt(argc, argv, "i:")) != -1) {
41                 char *endp;
42
43                 switch (c) {
44                 case 'i':
45                         iov_cnt = strtol(optarg, &endp, 0);
46                         if (*endp) {
47                                 fprintf(stderr, "Invalid iov count %s\n", optarg);
48                                 usage(argv[0]);
49                         }
50                         break;
51                 default:
52                         usage(argv[0]);
53                 }
54         }
55
56         if (iov_cnt > IOV_MAX || iov_cnt <= 0)
57                 usage(argv[0]);
58
59         if (optind == argc - 1)
60                 filename = argv[optind];
61         else
62                 usage(argv[0]);
63
64         pagesz = getpagesize();
65         data = malloc(pagesz * iov_cnt);
66         if (!data) {
67                 perror("malloc failed");
68                 return 1;
69         }
70
71         /*
72          * NOTE: no pre-writing/reading on the buffer before writev, to prevent
73          * page prefault from happening, we need it happen at writev time.
74          */
75
76         iov = calloc(iov_cnt, sizeof(struct iovec));
77         if (!iov) {
78                 perror("calloc failed");
79                 return 1;
80         }
81
82         for (i = 0; i < iov_cnt; i++) {
83                 (iov + i)->iov_base = (data + pagesz * i);
84                 (iov + i)->iov_len  = 1;
85         }
86
87         if ((fd = open(filename, O_TRUNC|O_CREAT|O_RDWR, 0644)) < 0) {
88                 perror("open failed");
89                 return 1;
90         }
91
92         ret = writev(fd, iov, iov_cnt);
93         if (ret < 0)
94                 perror("writev failed");
95         else
96                 printf("wrote %zd bytes\n", ret);
97
98         close(fd);
99         return 0;
100 }