fsx: use an enum to define the operation commands
[xfstests-dev.git] / ltp / fsx.c
1 /*
2  *      Copyright (C) 1991, NeXT Computer, Inc.  All Rights Reserverd.
3  *
4  *      File:   fsx.c
5  *      Author: Avadis Tevanian, Jr.
6  *
7  *      File system exerciser. 
8  *
9  *      Rewritten 8/98 by Conrad Minshall.
10  *
11  *      Small changes to work under Linux -- davej.
12  *
13  *      Checks for mmap last-page zero fill.
14  */
15
16 #include "global.h"
17
18 #include <limits.h>
19 #include <time.h>
20 #include <strings.h>
21 #include <sys/file.h>
22 #include <sys/mman.h>
23 #include <stdbool.h>
24 #ifdef HAVE_ERR_H
25 #include <err.h>
26 #endif
27 #include <signal.h>
28 #include <stdio.h>
29 #include <stddef.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <stdarg.h>
33 #include <errno.h>
34 #ifdef AIO
35 #include <libaio.h>
36 #endif
37
38 #ifndef MAP_FILE
39 # define MAP_FILE 0
40 #endif
41
42 #define NUMPRINTCOLUMNS 32      /* # columns of data to print on each line */
43
44 /* Operation flags */
45
46 enum opflags { FL_NONE = 0, FL_SKIPPED = 1, FL_CLOSE_OPEN = 2, FL_KEEP_SIZE = 4 };
47
48 /*
49  *      A log entry is an operation and a bunch of arguments.
50  */
51
52 struct log_entry {
53         int     operation;
54         int     args[3];
55         enum opflags flags;
56 };
57
58 #define LOGSIZE 10000
59
60 struct log_entry        oplog[LOGSIZE]; /* the log */
61 int                     logptr = 0;     /* current position in log */
62 int                     logcount = 0;   /* total ops */
63
64 /*
65  * The operation matrix is complex due to conditional execution of different
66  * features. Hence when we come to deciding what operation to run, we need to
67  * be careful in how we select the different operations. The active operations
68  * are mapped to numbers as follows:
69  *
70  *                      lite    !lite   integrity
71  * READ:                0       0       0
72  * WRITE:               1       1       1
73  * MAPREAD:             2       2       2
74  * MAPWRITE:            3       3       3
75  * TRUNCATE:            -       4       4
76  * FALLOCATE:           -       5       5
77  * PUNCH HOLE:          -       6       6
78  * ZERO RANGE:          -       7       7
79  * COLLAPSE RANGE:      -       8       8
80  * FSYNC:               -       -       9
81  *
82  * When mapped read/writes are disabled, they are simply converted to normal
83  * reads and writes. When fallocate/fpunch calls are disabled, they are
84  * skipped.
85  *
86  * Because of the "lite" version, we also need to have different "maximum
87  * operation" defines to allow the ops to be selected correctly based on the
88  * mode being run.
89  */
90
91 enum {
92         /* common operations */
93         OP_READ = 0,
94         OP_WRITE,
95         OP_MAPREAD,
96         OP_MAPWRITE,
97         OP_MAX_LITE,
98
99         /* !lite operations */
100         OP_TRUNCATE = OP_MAX_LITE,
101         OP_FALLOCATE,
102         OP_PUNCH_HOLE,
103         OP_ZERO_RANGE,
104         OP_COLLAPSE_RANGE,
105         OP_INSERT_RANGE,
106         OP_MAX_FULL,
107
108         /* integrity operations */
109         OP_FSYNC = OP_MAX_FULL,
110         OP_MAX_INTEGRITY,
111 };
112
113 #undef PAGE_SIZE
114 #define PAGE_SIZE       getpagesize()
115 #undef PAGE_MASK
116 #define PAGE_MASK       (PAGE_SIZE - 1)
117
118 char    *original_buf;                  /* a pointer to the original data */
119 char    *good_buf;                      /* a pointer to the correct data */
120 char    *temp_buf;                      /* a pointer to the current data */
121 char    *fname;                         /* name of our test file */
122 char    *bname;                         /* basename of our test file */
123 char    *logdev;                        /* -i flag */
124 char    *logid;                         /* -j flag */
125 char    dname[1024];                    /* -P flag */
126 char    goodfile[PATH_MAX];
127 int     dirpath = 0;                    /* -P flag */
128 int     fd;                             /* fd for our test file */
129
130 blksize_t       block_size = 0;
131 off_t           file_size = 0;
132 off_t           biggest = 0;
133 unsigned long   testcalls = 0;          /* calls to function "test" */
134
135 unsigned long   simulatedopcount = 0;   /* -b flag */
136 int     closeprob = 0;                  /* -c flag */
137 int     debug = 0;                      /* -d flag */
138 unsigned long   debugstart = 0;         /* -D flag */
139 char    filldata = 0;                   /* -g flag */
140 int     flush = 0;                      /* -f flag */
141 int     do_fsync = 0;                   /* -y flag */
142 unsigned long   maxfilelen = 256 * 1024;        /* -l flag */
143 int     sizechecks = 1;                 /* -n flag disables them */
144 int     maxoplen = 64 * 1024;           /* -o flag */
145 int     quiet = 0;                      /* -q flag */
146 unsigned long progressinterval = 0;     /* -p flag */
147 int     readbdy = 1;                    /* -r flag */
148 int     style = 0;                      /* -s flag */
149 int     prealloc = 0;                   /* -x flag */
150 int     truncbdy = 1;                   /* -t flag */
151 int     writebdy = 1;                   /* -w flag */
152 long    monitorstart = -1;              /* -m flag */
153 long    monitorend = -1;                /* -m flag */
154 int     lite = 0;                       /* -L flag */
155 long    numops = -1;                    /* -N flag */
156 int     randomoplen = 1;                /* -O flag disables it */
157 int     seed = 1;                       /* -S flag */
158 int     mapped_writes = 1;              /* -W flag disables */
159 int     fallocate_calls = 1;            /* -F flag disables */
160 int     keep_size_calls = 1;            /* -K flag disables */
161 int     punch_hole_calls = 1;           /* -H flag disables */
162 int     zero_range_calls = 1;           /* -z flag disables */
163 int     collapse_range_calls = 1;       /* -C flag disables */
164 int     insert_range_calls = 1;         /* -I flag disables */
165 int     mapped_reads = 1;               /* -R flag disables it */
166 int     check_file = 0;                 /* -X flag enables */
167 int     integrity = 0;                  /* -i flag */
168 int     fsxgoodfd = 0;
169 int     o_direct;                       /* -Z */
170 int     aio = 0;
171 int     mark_nr = 0;
172
173 int page_size;
174 int page_mask;
175 int mmap_mask;
176 #ifdef AIO
177 int aio_rw(int rw, int fd, char *buf, unsigned len, unsigned offset);
178 #define READ 0
179 #define WRITE 1
180 #define fsxread(a,b,c,d)        aio_rw(READ, a,b,c,d)
181 #define fsxwrite(a,b,c,d)       aio_rw(WRITE, a,b,c,d)
182 #else
183 #define fsxread(a,b,c,d)        read(a,b,c)
184 #define fsxwrite(a,b,c,d)       write(a,b,c)
185 #endif
186
187 const char *replayops = NULL;
188 const char *recordops = NULL;
189 FILE *  fsxlogf = NULL;
190 FILE *  replayopsf = NULL;
191 char opsfile[PATH_MAX];
192 int badoff = -1;
193 int closeopen = 0;
194
195 static void *round_ptr_up(void *ptr, unsigned long align, unsigned long offset)
196 {
197         unsigned long ret = (unsigned long)ptr;
198
199         ret = ((ret + align - 1) & ~(align - 1));
200         ret += offset;
201         return (void *)ret;
202 }
203
204 void
205 vwarnc(int code, const char *fmt, va_list ap)
206 {
207         if (logid)
208                 fprintf(stderr, "%s: ", logid);
209         fprintf(stderr, "fsx: ");
210         if (fmt != NULL) {
211                 vfprintf(stderr, fmt, ap);
212                 fprintf(stderr, ": ");
213         }
214         fprintf(stderr, "%s\n", strerror(code));
215 }
216
217 void
218 warn(const char * fmt, ...)  {
219         va_list ap;
220         va_start(ap, fmt);
221         vwarnc(errno, fmt, ap);
222         va_end(ap);
223 }
224
225 void
226 prt(const char *fmt, ...)
227 {
228         va_list args;
229
230         if (logid)
231                 fprintf(stdout, "%s: ", logid);
232         va_start(args, fmt);
233         vfprintf(stdout, fmt, args);
234         va_end(args);
235         if (fsxlogf) {
236                 va_start(args, fmt);
237                 vfprintf(fsxlogf, fmt, args);
238                 va_end(args);
239         }
240 }
241
242 void
243 prterr(const char *prefix)
244 {
245         prt("%s%s%s\n", prefix, prefix ? ": " : "", strerror(errno));
246 }
247
248
249 static const char *op_names[] = {
250         [OP_READ] = "read",
251         [OP_WRITE] = "write",
252         [OP_MAPREAD] = "mapread",
253         [OP_MAPWRITE] = "mapwrite",
254         [OP_TRUNCATE] = "truncate",
255         [OP_FALLOCATE] = "fallocate",
256         [OP_PUNCH_HOLE] = "punch_hole",
257         [OP_ZERO_RANGE] = "zero_range",
258         [OP_COLLAPSE_RANGE] = "collapse_range",
259         [OP_INSERT_RANGE] = "insert_range",
260         [OP_FSYNC] = "fsync",
261 };
262
263 static const char *op_name(int operation)
264 {
265         if (operation >= 0 &&
266             operation < sizeof(op_names) / sizeof(op_names[0]))
267                 return op_names[operation];
268         return NULL;
269 }
270
271 static int op_code(const char *name)
272 {
273         int i;
274
275         for (i = 0; i < sizeof(op_names) / sizeof(op_names[0]); i++)
276                 if (op_names[i] && strcmp(name, op_names[i]) == 0)
277                         return i;
278         return -1;
279 }
280
281 void
282 log4(int operation, int arg0, int arg1, enum opflags flags)
283 {
284         struct log_entry *le;
285
286         le = &oplog[logptr];
287         le->operation = operation;
288         if (closeopen)
289                 flags |= FL_CLOSE_OPEN;
290         le->args[0] = arg0;
291         le->args[1] = arg1;
292         le->args[2] = file_size;
293         le->flags = flags;
294         logptr++;
295         logcount++;
296         if (logptr >= LOGSIZE)
297                 logptr = 0;
298 }
299
300
301 void
302 logdump(void)
303 {
304         FILE    *logopsf;
305         int     i, count, down;
306         struct log_entry        *lp;
307
308         prt("LOG DUMP (%d total operations):\n", logcount);
309
310         logopsf = fopen(opsfile, "w");
311         if (!logopsf)
312                 prterr(opsfile);
313
314         if (logcount < LOGSIZE) {
315                 i = 0;
316                 count = logcount;
317         } else {
318                 i = logptr;
319                 count = LOGSIZE;
320         }
321         for ( ; count > 0; count--) {
322                 bool overlap;
323                 int opnum;
324
325                 opnum = i+1 + (logcount/LOGSIZE)*LOGSIZE;
326                 prt("%d(%3d mod 256): ", opnum, opnum%256);
327                 lp = &oplog[i];
328
329                 overlap = badoff >= lp->args[0] &&
330                           badoff < lp->args[0] + lp->args[1];
331
332                 if (lp->flags & FL_SKIPPED) {
333                         prt("SKIPPED (no operation)");
334                         goto skipped;
335                 }
336
337                 switch (lp->operation) {
338                 case OP_MAPREAD:
339                         prt("MAPREAD  0x%x thru 0x%x\t(0x%x bytes)",
340                             lp->args[0], lp->args[0] + lp->args[1] - 1,
341                             lp->args[1]);
342                         if (overlap)
343                                 prt("\t***RRRR***");
344                         break;
345                 case OP_MAPWRITE:
346                         prt("MAPWRITE 0x%x thru 0x%x\t(0x%x bytes)",
347                             lp->args[0], lp->args[0] + lp->args[1] - 1,
348                             lp->args[1]);
349                         if (overlap)
350                                 prt("\t******WWWW");
351                         break;
352                 case OP_READ:
353                         prt("READ     0x%x thru 0x%x\t(0x%x bytes)",
354                             lp->args[0], lp->args[0] + lp->args[1] - 1,
355                             lp->args[1]);
356                         if (overlap)
357                                 prt("\t***RRRR***");
358                         break;
359                 case OP_WRITE:
360                         prt("WRITE    0x%x thru 0x%x\t(0x%x bytes)",
361                             lp->args[0], lp->args[0] + lp->args[1] - 1,
362                             lp->args[1]);
363                         if (lp->args[0] > lp->args[2])
364                                 prt(" HOLE");
365                         else if (lp->args[0] + lp->args[1] > lp->args[2])
366                                 prt(" EXTEND");
367                         overlap = (badoff >= lp->args[0] ||
368                                    badoff >=lp->args[2]) &&
369                                   badoff < lp->args[0] + lp->args[1];
370                         if (overlap)
371                                 prt("\t***WWWW");
372                         break;
373                 case OP_TRUNCATE:
374                         down = lp->args[1] < lp->args[2];
375                         prt("TRUNCATE %s\tfrom 0x%x to 0x%x",
376                             down ? "DOWN" : "UP", lp->args[2], lp->args[1]);
377                         overlap = badoff >= lp->args[1 + !down] &&
378                                   badoff < lp->args[1 + !!down];
379                         if (overlap)
380                                 prt("\t******WWWW");
381                         break;
382                 case OP_FALLOCATE:
383                         /* 0: offset 1: length 2: where alloced */
384                         prt("FALLOC   0x%x thru 0x%x\t(0x%x bytes) ",
385                                 lp->args[0], lp->args[0] + lp->args[1],
386                                 lp->args[1]);
387                         if (lp->args[0] + lp->args[1] <= lp->args[2])
388                                 prt("INTERIOR");
389                         else if (lp->flags & FL_KEEP_SIZE)
390                                 prt("PAST_EOF");
391                         else
392                                 prt("EXTENDING");
393                         if (overlap)
394                                 prt("\t******FFFF");
395                         break;
396                 case OP_PUNCH_HOLE:
397                         prt("PUNCH    0x%x thru 0x%x\t(0x%x bytes)",
398                             lp->args[0], lp->args[0] + lp->args[1] - 1,
399                             lp->args[1]);
400                         if (overlap)
401                                 prt("\t******PPPP");
402                         break;
403                 case OP_ZERO_RANGE:
404                         prt("ZERO     0x%x thru 0x%x\t(0x%x bytes)",
405                             lp->args[0], lp->args[0] + lp->args[1] - 1,
406                             lp->args[1]);
407                         if (overlap)
408                                 prt("\t******ZZZZ");
409                         break;
410                 case OP_COLLAPSE_RANGE:
411                         prt("COLLAPSE 0x%x thru 0x%x\t(0x%x bytes)",
412                             lp->args[0], lp->args[0] + lp->args[1] - 1,
413                             lp->args[1]);
414                         if (overlap)
415                                 prt("\t******CCCC");
416                         break;
417                 case OP_INSERT_RANGE:
418                         prt("INSERT 0x%x thru 0x%x\t(0x%x bytes)",
419                             lp->args[0], lp->args[0] + lp->args[1] - 1,
420                             lp->args[1]);
421                         if (overlap)
422                                 prt("\t******IIII");
423                         break;
424                 case OP_FSYNC:
425                         prt("FSYNC");
426                         break;
427                 default:
428                         prt("BOGUS LOG ENTRY (operation code = %d)!",
429                             lp->operation);
430                         continue;
431                 }
432
433             skipped:
434                 if (lp->flags & FL_CLOSE_OPEN)
435                         prt("\n\t\tCLOSE/OPEN");
436                 prt("\n");
437                 i++;
438                 if (i == LOGSIZE)
439                         i = 0;
440
441                 if (logopsf) {
442                         if (lp->flags & FL_SKIPPED)
443                                 fprintf(logopsf, "skip ");
444                         fprintf(logopsf, "%s 0x%x 0x%x 0x%x",
445                                 op_name(lp->operation),
446                                 lp->args[0], lp->args[1], lp->args[2]);
447                         if (lp->flags & FL_KEEP_SIZE)
448                                 fprintf(logopsf, " keep_size");
449                         if (lp->flags & FL_CLOSE_OPEN)
450                                 fprintf(logopsf, " close_open");
451                         if (overlap)
452                                 fprintf(logopsf, " *");
453                         fprintf(logopsf, "\n");
454                 }
455         }
456
457         if (logopsf) {
458                 if (fclose(logopsf) != 0)
459                         prterr(opsfile);
460                 else
461                         prt("Log of operations saved to \"%s\"; "
462                             "replay with --replay-ops\n",
463                             opsfile);
464         }
465 }
466
467
468 void
469 save_buffer(char *buffer, off_t bufferlength, int fd)
470 {
471         off_t ret;
472         ssize_t byteswritten;
473
474         if (fd <= 0 || bufferlength == 0)
475                 return;
476
477         if (bufferlength > SSIZE_MAX) {
478                 prt("fsx flaw: overflow in save_buffer\n");
479                 exit(67);
480         }
481         if (lite) {
482                 off_t size_by_seek = lseek(fd, (off_t)0, SEEK_END);
483                 if (size_by_seek == (off_t)-1)
484                         prterr("save_buffer: lseek eof");
485                 else if (bufferlength > size_by_seek) {
486                         warn("save_buffer: .fsxgood file too short... will save 0x%llx bytes instead of 0x%llx\n", (unsigned long long)size_by_seek,
487                              (unsigned long long)bufferlength);
488                         bufferlength = size_by_seek;
489                 }
490         }
491
492         ret = lseek(fd, (off_t)0, SEEK_SET);
493         if (ret == (off_t)-1)
494                 prterr("save_buffer: lseek 0");
495         
496         byteswritten = write(fd, buffer, (size_t)bufferlength);
497         if (byteswritten != bufferlength) {
498                 if (byteswritten == -1)
499                         prterr("save_buffer write");
500                 else
501                         warn("save_buffer: short write, 0x%x bytes instead of 0x%llx\n",
502                              (unsigned)byteswritten,
503                              (unsigned long long)bufferlength);
504         }
505 }
506
507
508 void
509 report_failure(int status)
510 {
511         logdump();
512         
513         if (fsxgoodfd) {
514                 if (good_buf) {
515                         save_buffer(good_buf, file_size, fsxgoodfd);
516                         prt("Correct content saved for comparison\n");
517                         prt("(maybe hexdump \"%s\" vs \"%s\")\n",
518                             fname, goodfile);
519                 }
520                 close(fsxgoodfd);
521         }
522         exit(status);
523 }
524
525
526 #define short_at(cp) ((unsigned short)((*((unsigned char *)(cp)) << 8) | \
527                                         *(((unsigned char *)(cp)) + 1)))
528
529 void
530 mark_log(void)
531 {
532         char command[256];
533         int ret;
534
535         snprintf(command, 256, "dmsetup message %s 0 mark %s.mark%d", logdev,
536                  bname, mark_nr);
537         ret = system(command);
538         if (ret) {
539                 prterr("dmsetup mark failed");
540                 exit(211);
541         }
542 }
543
544 void
545 dump_fsync_buffer(void)
546 {
547         char fname_buffer[PATH_MAX];
548         int good_fd;
549
550         if (!good_buf)
551                 return;
552
553         snprintf(fname_buffer, sizeof(fname_buffer), "%s%s.mark%d", dname,
554                  bname, mark_nr);
555         good_fd = open(fname_buffer, O_WRONLY|O_CREAT|O_TRUNC, 0666);
556         if (good_fd < 0) {
557                 prterr(fname_buffer);
558                 exit(212);
559         }
560
561         save_buffer(good_buf, file_size, good_fd);
562         close(good_fd);
563         prt("Dumped fsync buffer to %s\n", fname_buffer + dirpath);
564 }
565
566 void
567 check_buffers(char *buf, unsigned offset, unsigned size)
568 {
569         unsigned char c, t;
570         unsigned i = 0;
571         unsigned n = 0;
572         unsigned op = 0;
573         unsigned bad = 0;
574
575         if (memcmp(good_buf + offset, buf, size) != 0) {
576                 prt("READ BAD DATA: offset = 0x%x, size = 0x%x, fname = %s\n",
577                     offset, size, fname);
578                 prt("OFFSET\tGOOD\tBAD\tRANGE\n");
579                 while (size > 0) {
580                         c = good_buf[offset];
581                         t = buf[i];
582                         if (c != t) {
583                                 if (n < 16) {
584                                         bad = short_at(&buf[i]);
585                                         prt("0x%05x\t0x%04x\t0x%04x", offset,
586                                             short_at(&good_buf[offset]), bad);
587                                         op = buf[offset & 1 ? i+1 : i];
588                                         prt("\t0x%05x\n", n);
589                                         if (op)
590                                                 prt("operation# (mod 256) for "
591                                                   "the bad data may be %u\n",
592                                                 ((unsigned)op & 0xff));
593                                         else
594                                                 prt("operation# (mod 256) for "
595                                                   "the bad data unknown, check"
596                                                   " HOLE and EXTEND ops\n");
597                                 }
598                                 n++;
599                                 badoff = offset;
600                         }
601                         offset++;
602                         i++;
603                         size--;
604                 }
605                 report_failure(110);
606         }
607 }
608
609
610 void
611 check_size(void)
612 {
613         struct stat     statbuf;
614         off_t   size_by_seek;
615
616         if (fstat(fd, &statbuf)) {
617                 prterr("check_size: fstat");
618                 statbuf.st_size = -1;
619         }
620         size_by_seek = lseek(fd, (off_t)0, SEEK_END);
621         if (file_size != statbuf.st_size || file_size != size_by_seek) {
622                 prt("Size error: expected 0x%llx stat 0x%llx seek 0x%llx\n",
623                     (unsigned long long)file_size,
624                     (unsigned long long)statbuf.st_size,
625                     (unsigned long long)size_by_seek);
626                 report_failure(120);
627         }
628 }
629
630
631 void
632 check_trunc_hack(void)
633 {
634         struct stat statbuf;
635         off_t offset = file_size + (off_t)100000;
636
637         if (ftruncate(fd, file_size))
638                 goto ftruncate_err;
639         if (ftruncate(fd, offset))
640                 goto ftruncate_err;
641         fstat(fd, &statbuf);
642         if (statbuf.st_size != offset) {
643                 prt("no extend on truncate! not posix!\n");
644                 exit(130);
645         }
646         if (ftruncate(fd, file_size)) {
647 ftruncate_err:
648                 prterr("check_trunc_hack: ftruncate");
649                 exit(131);
650         }
651 }
652
653 void
654 doflush(unsigned offset, unsigned size)
655 {
656         unsigned pg_offset;
657         unsigned map_size;
658         char    *p;
659
660         if (o_direct == O_DIRECT)
661                 return;
662
663         pg_offset = offset & mmap_mask;
664         map_size  = pg_offset + size;
665
666         if ((p = (char *)mmap(0, map_size, PROT_READ | PROT_WRITE,
667                               MAP_FILE | MAP_SHARED, fd,
668                               (off_t)(offset - pg_offset))) == (char *)-1) {
669                 prterr("doflush: mmap");
670                 report_failure(202);
671         }
672         if (msync(p, map_size, MS_INVALIDATE) != 0) {
673                 prterr("doflush: msync");
674                 report_failure(203);
675         }
676         if (munmap(p, map_size) != 0) {
677                 prterr("doflush: munmap");
678                 report_failure(204);
679         }
680 }
681
682 void
683 doread(unsigned offset, unsigned size)
684 {
685         off_t ret;
686         unsigned iret;
687
688         offset -= offset % readbdy;
689         if (o_direct)
690                 size -= size % readbdy;
691         if (size == 0) {
692                 if (!quiet && testcalls > simulatedopcount && !o_direct)
693                         prt("skipping zero size read\n");
694                 log4(OP_READ, offset, size, FL_SKIPPED);
695                 return;
696         }
697         if (size + offset > file_size) {
698                 if (!quiet && testcalls > simulatedopcount)
699                         prt("skipping seek/read past end of file\n");
700                 log4(OP_READ, offset, size, FL_SKIPPED);
701                 return;
702         }
703
704         log4(OP_READ, offset, size, FL_NONE);
705
706         if (testcalls <= simulatedopcount)
707                 return;
708
709         if (!quiet &&
710                 ((progressinterval && testcalls % progressinterval == 0)  ||
711                 (debug &&
712                        (monitorstart == -1 ||
713                         (offset + size > monitorstart &&
714                         (monitorend == -1 || offset <= monitorend))))))
715                 prt("%lu read\t0x%x thru\t0x%x\t(0x%x bytes)\n", testcalls,
716                     offset, offset + size - 1, size);
717         ret = lseek(fd, (off_t)offset, SEEK_SET);
718         if (ret == (off_t)-1) {
719                 prterr("doread: lseek");
720                 report_failure(140);
721         }
722         iret = fsxread(fd, temp_buf, size, offset);
723         if (iret != size) {
724                 if (iret == -1)
725                         prterr("doread: read");
726                 else
727                         prt("short read: 0x%x bytes instead of 0x%x\n",
728                             iret, size);
729                 report_failure(141);
730         }
731         check_buffers(temp_buf, offset, size);
732 }
733
734 void
735 check_eofpage(char *s, unsigned offset, char *p, int size)
736 {
737         unsigned long last_page, should_be_zero;
738
739         if (offset + size <= (file_size & ~page_mask))
740                 return;
741         /*
742          * we landed in the last page of the file
743          * test to make sure the VM system provided 0's 
744          * beyond the true end of the file mapping
745          * (as required by mmap def in 1996 posix 1003.1)
746          */
747         last_page = ((unsigned long)p + (offset & page_mask) + size) & ~page_mask;
748
749         for (should_be_zero = last_page + (file_size & page_mask);
750              should_be_zero < last_page + page_size;
751              should_be_zero++)
752                 if (*(char *)should_be_zero) {
753                         prt("Mapped %s: non-zero data past EOF (0x%llx) page offset 0x%x is 0x%04x\n",
754                             s, file_size - 1, should_be_zero & page_mask,
755                             short_at(should_be_zero));
756                         report_failure(205);
757                 }
758 }
759
760 void
761 check_contents(void)
762 {
763         static char *check_buf;
764         unsigned offset = 0;
765         unsigned size = file_size;
766         unsigned map_offset;
767         unsigned map_size;
768         char *p;
769         off_t ret;
770         unsigned iret;
771
772         if (!check_buf) {
773                 check_buf = (char *) malloc(maxfilelen + writebdy);
774                 assert(check_buf != NULL);
775                 check_buf = round_ptr_up(check_buf, writebdy, 0);
776                 memset(check_buf, '\0', maxfilelen);
777         }
778
779         if (o_direct)
780                 size -= size % readbdy;
781         if (size == 0)
782                 return;
783
784         ret = lseek(fd, (off_t)offset, SEEK_SET);
785         if (ret == (off_t)-1) {
786                 prterr("doread: lseek");
787                 report_failure(140);
788         }
789
790         iret = fsxread(fd, check_buf, size, offset);
791         if (iret != size) {
792                 if (iret == -1)
793                         prterr("check_contents: read");
794                 else
795                         prt("short check read: 0x%x bytes instead of 0x%x\n",
796                             iret, size);
797                 report_failure(141);
798         }
799         check_buffers(check_buf, offset, size);
800
801         /* Map eof page, check it */
802         map_offset = size - (size & PAGE_MASK);
803         if (map_offset == size)
804                 map_offset -= PAGE_SIZE;
805         map_size  = size - map_offset;
806
807         p = mmap(0, map_size, PROT_READ, MAP_SHARED, fd, map_offset);
808         if (p == MAP_FAILED) {
809                 prterr("check_contents: mmap");
810                 report_failure(190);
811         }
812         check_eofpage("check_contents", map_offset, p, map_size);
813
814         if (munmap(p, map_size) != 0) {
815                 prterr("check_contents: munmap");
816                 report_failure(191);
817         }
818 }
819
820 void
821 domapread(unsigned offset, unsigned size)
822 {
823         unsigned pg_offset;
824         unsigned map_size;
825         char    *p;
826
827         offset -= offset % readbdy;
828         if (size == 0) {
829                 if (!quiet && testcalls > simulatedopcount)
830                         prt("skipping zero size read\n");
831                 log4(OP_MAPREAD, offset, size, FL_SKIPPED);
832                 return;
833         }
834         if (size + offset > file_size) {
835                 if (!quiet && testcalls > simulatedopcount)
836                         prt("skipping seek/read past end of file\n");
837                 log4(OP_MAPREAD, offset, size, FL_SKIPPED);
838                 return;
839         }
840
841         log4(OP_MAPREAD, offset, size, FL_NONE);
842
843         if (testcalls <= simulatedopcount)
844                 return;
845
846         if (!quiet &&
847                 ((progressinterval && testcalls % progressinterval == 0) ||
848                        (debug &&
849                        (monitorstart == -1 ||
850                         (offset + size > monitorstart &&
851                         (monitorend == -1 || offset <= monitorend))))))
852                 prt("%lu mapread\t0x%x thru\t0x%x\t(0x%x bytes)\n", testcalls,
853                     offset, offset + size - 1, size);
854
855         pg_offset = offset & PAGE_MASK;
856         map_size  = pg_offset + size;
857
858         if ((p = (char *)mmap(0, map_size, PROT_READ, MAP_SHARED, fd,
859                               (off_t)(offset - pg_offset))) == (char *)-1) {
860                 prterr("domapread: mmap");
861                 report_failure(190);
862         }
863         memcpy(temp_buf, p + pg_offset, size);
864
865         check_eofpage("Read", offset, p, size);
866
867         if (munmap(p, map_size) != 0) {
868                 prterr("domapread: munmap");
869                 report_failure(191);
870         }
871
872         check_buffers(temp_buf, offset, size);
873 }
874
875
876 void
877 gendata(char *original_buf, char *good_buf, unsigned offset, unsigned size)
878 {
879         while (size--) {
880                 if (filldata) {
881                         good_buf[offset] = filldata;
882                 } else {
883                         good_buf[offset] = testcalls % 256;
884                         if (offset % 2)
885                                 good_buf[offset] += original_buf[offset];
886                 }
887                 offset++;
888         }
889 }
890
891
892 void
893 dowrite(unsigned offset, unsigned size)
894 {
895         off_t ret;
896         unsigned iret;
897
898         offset -= offset % writebdy;
899         if (o_direct)
900                 size -= size % writebdy;
901         if (size == 0) {
902                 if (!quiet && testcalls > simulatedopcount && !o_direct)
903                         prt("skipping zero size write\n");
904                 log4(OP_WRITE, offset, size, FL_SKIPPED);
905                 return;
906         }
907
908         log4(OP_WRITE, offset, size, FL_NONE);
909
910         gendata(original_buf, good_buf, offset, size);
911         if (file_size < offset + size) {
912                 if (file_size < offset)
913                         memset(good_buf + file_size, '\0', offset - file_size);
914                 file_size = offset + size;
915                 if (lite) {
916                         warn("Lite file size bug in fsx!");
917                         report_failure(149);
918                 }
919         }
920
921         if (testcalls <= simulatedopcount)
922                 return;
923
924         if (!quiet &&
925                 ((progressinterval && testcalls % progressinterval == 0) ||
926                        (debug &&
927                        (monitorstart == -1 ||
928                         (offset + size > monitorstart &&
929                         (monitorend == -1 || offset <= monitorend))))))
930                 prt("%lu write\t0x%x thru\t0x%x\t(0x%x bytes)\n", testcalls,
931                     offset, offset + size - 1, size);
932         ret = lseek(fd, (off_t)offset, SEEK_SET);
933         if (ret == (off_t)-1) {
934                 prterr("dowrite: lseek");
935                 report_failure(150);
936         }
937         iret = fsxwrite(fd, good_buf + offset, size, offset);
938         if (iret != size) {
939                 if (iret == -1)
940                         prterr("dowrite: write");
941                 else
942                         prt("short write: 0x%x bytes instead of 0x%x\n",
943                             iret, size);
944                 report_failure(151);
945         }
946         if (do_fsync) {
947                 if (fsync(fd)) {
948                         prt("fsync() failed: %s\n", strerror(errno));
949                         report_failure(152);
950                 }
951         }
952         if (flush) {
953                 doflush(offset, size);
954         }
955 }
956
957
958 void
959 domapwrite(unsigned offset, unsigned size)
960 {
961         unsigned pg_offset;
962         unsigned map_size;
963         off_t    cur_filesize;
964         char    *p;
965
966         offset -= offset % writebdy;
967         if (size == 0) {
968                 if (!quiet && testcalls > simulatedopcount)
969                         prt("skipping zero size write\n");
970                 log4(OP_MAPWRITE, offset, size, FL_SKIPPED);
971                 return;
972         }
973         cur_filesize = file_size;
974
975         log4(OP_MAPWRITE, offset, size, FL_NONE);
976
977         gendata(original_buf, good_buf, offset, size);
978         if (file_size < offset + size) {
979                 if (file_size < offset)
980                         memset(good_buf + file_size, '\0', offset - file_size);
981                 file_size = offset + size;
982                 if (lite) {
983                         warn("Lite file size bug in fsx!");
984                         report_failure(200);
985                 }
986         }
987
988         if (testcalls <= simulatedopcount)
989                 return;
990
991         if (!quiet &&
992                 ((progressinterval && testcalls % progressinterval == 0) ||
993                        (debug &&
994                        (monitorstart == -1 ||
995                         (offset + size > monitorstart &&
996                         (monitorend == -1 || offset <= monitorend))))))
997                 prt("%lu mapwrite\t0x%x thru\t0x%x\t(0x%x bytes)\n", testcalls,
998                     offset, offset + size - 1, size);
999
1000         if (file_size > cur_filesize) {
1001                 if (ftruncate(fd, file_size) == -1) {
1002                         prterr("domapwrite: ftruncate");
1003                         exit(201);
1004                 }
1005         }
1006         pg_offset = offset & PAGE_MASK;
1007         map_size  = pg_offset + size;
1008
1009         if ((p = (char *)mmap(0, map_size, PROT_READ | PROT_WRITE,
1010                               MAP_FILE | MAP_SHARED, fd,
1011                               (off_t)(offset - pg_offset))) == (char *)-1) {
1012                 prterr("domapwrite: mmap");
1013                 report_failure(202);
1014         }
1015         memcpy(p + pg_offset, good_buf + offset, size);
1016         if (msync(p, map_size, MS_SYNC) != 0) {
1017                 prterr("domapwrite: msync");
1018                 report_failure(203);
1019         }
1020
1021         check_eofpage("Write", offset, p, size);
1022
1023         if (munmap(p, map_size) != 0) {
1024                 prterr("domapwrite: munmap");
1025                 report_failure(204);
1026         }
1027 }
1028
1029
1030 void
1031 dotruncate(unsigned size)
1032 {
1033         int oldsize = file_size;
1034
1035         size -= size % truncbdy;
1036         if (size > biggest) {
1037                 biggest = size;
1038                 if (!quiet && testcalls > simulatedopcount)
1039                         prt("truncating to largest ever: 0x%x\n", size);
1040         }
1041
1042         log4(OP_TRUNCATE, 0, size, FL_NONE);
1043
1044         if (size > file_size)
1045                 memset(good_buf + file_size, '\0', size - file_size);
1046         file_size = size;
1047
1048         if (testcalls <= simulatedopcount)
1049                 return;
1050         
1051         if ((progressinterval && testcalls % progressinterval == 0) ||
1052             (debug && (monitorstart == -1 || monitorend == -1 ||
1053                       size <= monitorend)))
1054                 prt("%lu trunc\tfrom 0x%x to 0x%x\n", testcalls, oldsize, size);
1055         if (ftruncate(fd, (off_t)size) == -1) {
1056                 prt("ftruncate1: %x\n", size);
1057                 prterr("dotruncate: ftruncate");
1058                 report_failure(160);
1059         }
1060 }
1061
1062 #ifdef FALLOC_FL_PUNCH_HOLE
1063 void
1064 do_punch_hole(unsigned offset, unsigned length)
1065 {
1066         unsigned end_offset;
1067         int max_offset = 0;
1068         int max_len = 0;
1069         int mode = FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE;
1070
1071         if (length == 0) {
1072                 if (!quiet && testcalls > simulatedopcount)
1073                         prt("skipping zero length punch hole\n");
1074                 log4(OP_PUNCH_HOLE, offset, length, FL_SKIPPED);
1075                 return;
1076         }
1077
1078         if (file_size <= (loff_t)offset) {
1079                 if (!quiet && testcalls > simulatedopcount)
1080                         prt("skipping hole punch off the end of the file\n");
1081                 log4(OP_PUNCH_HOLE, offset, length, FL_SKIPPED);
1082                 return;
1083         }
1084
1085         end_offset = offset + length;
1086
1087         log4(OP_PUNCH_HOLE, offset, length, FL_NONE);
1088
1089         if (testcalls <= simulatedopcount)
1090                 return;
1091
1092         if ((progressinterval && testcalls % progressinterval == 0) ||
1093             (debug && (monitorstart == -1 || monitorend == -1 ||
1094                       end_offset <= monitorend))) {
1095                 prt("%lu punch\tfrom 0x%x to 0x%x, (0x%x bytes)\n", testcalls,
1096                         offset, offset+length, length);
1097         }
1098         if (fallocate(fd, mode, (loff_t)offset, (loff_t)length) == -1) {
1099                 prt("punch hole: 0x%x to 0x%x\n", offset, offset + length);
1100                 prterr("do_punch_hole: fallocate");
1101                 report_failure(161);
1102         }
1103
1104
1105         max_offset = offset < file_size ? offset : file_size;
1106         max_len = max_offset + length <= file_size ? length :
1107                         file_size - max_offset;
1108         memset(good_buf + max_offset, '\0', max_len);
1109 }
1110
1111 #else
1112 void
1113 do_punch_hole(unsigned offset, unsigned length)
1114 {
1115         return;
1116 }
1117 #endif
1118
1119 #ifdef FALLOC_FL_ZERO_RANGE
1120 void
1121 do_zero_range(unsigned offset, unsigned length, int keep_size)
1122 {
1123         unsigned end_offset;
1124         int mode = FALLOC_FL_ZERO_RANGE;
1125
1126         if (length == 0) {
1127                 if (!quiet && testcalls > simulatedopcount)
1128                         prt("skipping zero length zero range\n");
1129                 log4(OP_ZERO_RANGE, offset, length, FL_SKIPPED |
1130                      (keep_size ? FL_KEEP_SIZE : FL_NONE));
1131                 return;
1132         }
1133
1134         end_offset = keep_size ? 0 : offset + length;
1135
1136         if (end_offset > biggest) {
1137                 biggest = end_offset;
1138                 if (!quiet && testcalls > simulatedopcount)
1139                         prt("zero_range to largest ever: 0x%x\n", end_offset);
1140         }
1141
1142         /*
1143          * last arg matches fallocate string array index in logdump:
1144          *      0: allocate past EOF
1145          *      1: extending prealloc
1146          *      2: interior prealloc
1147          */
1148         log4(OP_ZERO_RANGE, offset, length,
1149              keep_size ? FL_KEEP_SIZE : FL_NONE);
1150
1151         if (testcalls <= simulatedopcount)
1152                 return;
1153
1154         if ((progressinterval && testcalls % progressinterval == 0) ||
1155             (debug && (monitorstart == -1 || monitorend == -1 ||
1156                       end_offset <= monitorend))) {
1157                 prt("%lu zero\tfrom 0x%x to 0x%x, (0x%x bytes)\n", testcalls,
1158                         offset, offset+length, length);
1159         }
1160         if (fallocate(fd, mode, (loff_t)offset, (loff_t)length) == -1) {
1161                 prt("zero range: 0x%x to 0x%x\n", offset, offset + length);
1162                 prterr("do_zero_range: fallocate");
1163                 report_failure(161);
1164         }
1165
1166         memset(good_buf + offset, '\0', length);
1167 }
1168
1169 #else
1170 void
1171 do_zero_range(unsigned offset, unsigned length, int keep_size)
1172 {
1173         return;
1174 }
1175 #endif
1176
1177 #ifdef FALLOC_FL_COLLAPSE_RANGE
1178 void
1179 do_collapse_range(unsigned offset, unsigned length)
1180 {
1181         unsigned end_offset;
1182         int mode = FALLOC_FL_COLLAPSE_RANGE;
1183
1184         if (length == 0) {
1185                 if (!quiet && testcalls > simulatedopcount)
1186                         prt("skipping zero length collapse range\n");
1187                 log4(OP_COLLAPSE_RANGE, offset, length, FL_SKIPPED);
1188                 return;
1189         }
1190
1191         end_offset = offset + length;
1192         if ((loff_t)end_offset >= file_size) {
1193                 if (!quiet && testcalls > simulatedopcount)
1194                         prt("skipping collapse range behind EOF\n");
1195                 log4(OP_COLLAPSE_RANGE, offset, length, FL_SKIPPED);
1196                 return;
1197         }
1198
1199         log4(OP_COLLAPSE_RANGE, offset, length, FL_NONE);
1200
1201         if (testcalls <= simulatedopcount)
1202                 return;
1203
1204         if ((progressinterval && testcalls % progressinterval == 0) ||
1205             (debug && (monitorstart == -1 || monitorend == -1 ||
1206                       end_offset <= monitorend))) {
1207                 prt("%lu collapse\tfrom 0x%x to 0x%x, (0x%x bytes)\n", testcalls,
1208                         offset, offset+length, length);
1209         }
1210         if (fallocate(fd, mode, (loff_t)offset, (loff_t)length) == -1) {
1211                 prt("collapse range: 0x%x to 0x%x\n", offset, offset + length);
1212                 prterr("do_collapse_range: fallocate");
1213                 report_failure(161);
1214         }
1215
1216         memmove(good_buf + offset, good_buf + end_offset,
1217                 file_size - end_offset);
1218         file_size -= length;
1219 }
1220
1221 #else
1222 void
1223 do_collapse_range(unsigned offset, unsigned length)
1224 {
1225         return;
1226 }
1227 #endif
1228
1229 #ifdef FALLOC_FL_INSERT_RANGE
1230 void
1231 do_insert_range(unsigned offset, unsigned length)
1232 {
1233         unsigned end_offset;
1234         int mode = FALLOC_FL_INSERT_RANGE;
1235
1236         if (length == 0) {
1237                 if (!quiet && testcalls > simulatedopcount)
1238                         prt("skipping zero length insert range\n");
1239                 log4(OP_INSERT_RANGE, offset, length, FL_SKIPPED);
1240                 return;
1241         }
1242
1243         if ((loff_t)offset >= file_size) {
1244                 if (!quiet && testcalls > simulatedopcount)
1245                         prt("skipping insert range behind EOF\n");
1246                 log4(OP_INSERT_RANGE, offset, length, FL_SKIPPED);
1247                 return;
1248         }
1249
1250         log4(OP_INSERT_RANGE, offset, length, FL_NONE);
1251
1252         if (testcalls <= simulatedopcount)
1253                 return;
1254
1255         end_offset = offset + length;
1256         if ((progressinterval && testcalls % progressinterval == 0) ||
1257             (debug && (monitorstart == -1 || monitorend == -1 ||
1258                       end_offset <= monitorend))) {
1259                 prt("%lu insert\tfrom 0x%x to 0x%x, (0x%x bytes)\n", testcalls,
1260                         offset, offset+length, length);
1261         }
1262         if (fallocate(fd, mode, (loff_t)offset, (loff_t)length) == -1) {
1263                 prt("insert range: 0x%x to 0x%x\n", offset, offset + length);
1264                 prterr("do_insert_range: fallocate");
1265                 report_failure(161);
1266         }
1267
1268         memmove(good_buf + end_offset, good_buf + offset,
1269                 file_size - offset);
1270         memset(good_buf + offset, '\0', length);
1271         file_size += length;
1272 }
1273
1274 #else
1275 void
1276 do_insert_range(unsigned offset, unsigned length)
1277 {
1278         return;
1279 }
1280 #endif
1281
1282 #ifdef HAVE_LINUX_FALLOC_H
1283 /* fallocate is basically a no-op unless extending, then a lot like a truncate */
1284 void
1285 do_preallocate(unsigned offset, unsigned length, int keep_size)
1286 {
1287         unsigned end_offset;
1288
1289         if (length == 0) {
1290                 if (!quiet && testcalls > simulatedopcount)
1291                         prt("skipping zero length fallocate\n");
1292                 log4(OP_FALLOCATE, offset, length, FL_SKIPPED |
1293                      (keep_size ? FL_KEEP_SIZE : FL_NONE));
1294                 return;
1295         }
1296
1297         end_offset = keep_size ? 0 : offset + length;
1298
1299         if (end_offset > biggest) {
1300                 biggest = end_offset;
1301                 if (!quiet && testcalls > simulatedopcount)
1302                         prt("fallocating to largest ever: 0x%x\n", end_offset);
1303         }
1304
1305         /*
1306          * last arg matches fallocate string array index in logdump:
1307          *      0: allocate past EOF
1308          *      1: extending prealloc
1309          *      2: interior prealloc
1310          */
1311         log4(OP_FALLOCATE, offset, length,
1312              keep_size ? FL_KEEP_SIZE : FL_NONE);
1313
1314         if (end_offset > file_size) {
1315                 memset(good_buf + file_size, '\0', end_offset - file_size);
1316                 file_size = end_offset;
1317         }
1318
1319         if (testcalls <= simulatedopcount)
1320                 return;
1321         
1322         if ((progressinterval && testcalls % progressinterval == 0) ||
1323             (debug && (monitorstart == -1 || monitorend == -1 ||
1324                       end_offset <= monitorend)))
1325                 prt("%lu falloc\tfrom 0x%x to 0x%x (0x%x bytes)\n", testcalls,
1326                                 offset, offset + length, length);
1327         if (fallocate(fd, keep_size ? FALLOC_FL_KEEP_SIZE : 0, (loff_t)offset, (loff_t)length) == -1) {
1328                 prt("fallocate: 0x%x to 0x%x\n", offset, offset + length);
1329                 prterr("do_preallocate: fallocate");
1330                 report_failure(161);
1331         }
1332 }
1333 #else
1334 void
1335 do_preallocate(unsigned offset, unsigned length, int keep_size)
1336 {
1337         return;
1338 }
1339 #endif
1340
1341 void
1342 writefileimage()
1343 {
1344         ssize_t iret;
1345
1346         if (lseek(fd, (off_t)0, SEEK_SET) == (off_t)-1) {
1347                 prterr("writefileimage: lseek");
1348                 report_failure(171);
1349         }
1350         iret = write(fd, good_buf, file_size);
1351         if ((off_t)iret != file_size) {
1352                 if (iret == -1)
1353                         prterr("writefileimage: write");
1354                 else
1355                         prt("short write: 0x%x bytes instead of 0x%llx\n",
1356                             iret, (unsigned long long)file_size);
1357                 report_failure(172);
1358         }
1359         if (lite ? 0 : ftruncate(fd, file_size) == -1) {
1360                 prt("ftruncate2: %llx\n", (unsigned long long)file_size);
1361                 prterr("writefileimage: ftruncate");
1362                 report_failure(173);
1363         }
1364 }
1365
1366
1367 void
1368 docloseopen(void)
1369
1370         if (testcalls <= simulatedopcount)
1371                 return;
1372
1373         if (debug)
1374                 prt("%lu close/open\n", testcalls);
1375         if (close(fd)) {
1376                 prterr("docloseopen: close");
1377                 report_failure(180);
1378         }
1379         fd = open(fname, O_RDWR|o_direct, 0);
1380         if (fd < 0) {
1381                 prterr("docloseopen: open");
1382                 report_failure(181);
1383         }
1384 }
1385
1386 void
1387 dofsync(void)
1388 {
1389         int ret;
1390
1391         if (testcalls <= simulatedopcount)
1392                 return;
1393         if (debug)
1394                 prt("%lu fsync\n", testcalls);
1395         log4(OP_FSYNC, 0, 0, 0);
1396         ret = fsync(fd);
1397         if (ret < 0) {
1398                 prterr("dofsync");
1399                 report_failure(210);
1400         }
1401         mark_log();
1402         dump_fsync_buffer();
1403         mark_nr++;
1404 }
1405
1406 #define TRIM_OFF(off, size)                     \
1407 do {                                            \
1408         if (size)                               \
1409                 (off) %= (size);                \
1410         else                                    \
1411                 (off) = 0;                      \
1412 } while (0)
1413
1414 #define TRIM_LEN(off, len, size)                \
1415 do {                                            \
1416         if ((off) + (len) > (size))             \
1417                 (len) = (size) - (off);         \
1418 } while (0)
1419
1420 #define TRIM_OFF_LEN(off, len, size)            \
1421 do {                                            \
1422         TRIM_OFF(off, size);                    \
1423         TRIM_LEN(off, len, size);               \
1424 } while (0)
1425
1426 void
1427 cleanup(int sig)
1428 {
1429         if (sig)
1430                 prt("signal %d\n", sig);
1431         prt("testcalls = %lu\n", testcalls);
1432         exit(sig);
1433 }
1434
1435 static int
1436 read_op(struct log_entry *log_entry)
1437 {
1438         char line[256];
1439
1440         memset(log_entry, 0, sizeof(*log_entry));
1441         log_entry->operation = -1;
1442
1443         while (log_entry->operation == -1) {
1444                 char *str;
1445                 int i;
1446
1447                 do {
1448                         if (!fgets(line, sizeof(line), replayopsf)) {
1449                                 if (feof(replayopsf)) {
1450                                         replayopsf = NULL;
1451                                         return 0;
1452                                 }
1453                                 goto fail;
1454                         }
1455                         str = strtok(line, " \t\n");
1456                 } while (!str || str[0] == '#');
1457
1458                 if (strcmp(str, "skip") == 0) {
1459                         log_entry->flags |= FL_SKIPPED;
1460                         str = strtok(NULL, " \t\n");
1461                         if (!str)
1462                                 goto fail;
1463                 }
1464                 log_entry->operation = op_code(str);
1465                 if (log_entry->operation == -1)
1466                         goto fail;
1467                 for (i = 0; i < 3; i++) {
1468                         char *end;
1469
1470                         str = strtok(NULL, " \t\n");
1471                         if (!str)
1472                                 goto fail;
1473                         log_entry->args[i] = strtoul(str, &end, 0);
1474                         if (*end)
1475                                 goto fail;
1476                 }
1477                 while ((str = strtok(NULL, " \t\n"))) {
1478                         if (strcmp(str, "keep_size") == 0)
1479                                 log_entry->flags |= FL_KEEP_SIZE;
1480                         else if (strcmp(str, "close_open") == 0)
1481                                 log_entry->flags |= FL_CLOSE_OPEN;
1482                         else if (strcmp(str, "*") == 0)
1483                                 ;  /* overlap marker; ignore */
1484                         else
1485                                 goto fail;
1486                 }
1487         }
1488         return 1;
1489
1490 fail:
1491         fprintf(stderr, "%s: parse error\n", replayops);
1492         fclose(replayopsf);
1493         replayopsf = NULL;
1494         cleanup(100);  /* doesn't return */
1495         return 0;
1496 }
1497
1498
1499 int
1500 test(void)
1501 {
1502         unsigned long   offset;
1503         unsigned long   size;
1504         unsigned long   rv;
1505         unsigned long   op;
1506         int             keep_size = 0;
1507
1508         if (simulatedopcount > 0 && testcalls == simulatedopcount)
1509                 writefileimage();
1510
1511         testcalls++;
1512
1513         if (debugstart > 0 && testcalls >= debugstart)
1514                 debug = 1;
1515
1516         if (!quiet && testcalls < simulatedopcount && testcalls % 100000 == 0)
1517                 prt("%lu...\n", testcalls);
1518
1519         if (replayopsf) {
1520                 struct log_entry log_entry;
1521
1522                 while (read_op(&log_entry)) {
1523                         if (log_entry.flags & FL_SKIPPED) {
1524                                 log4(log_entry.operation,
1525                                      log_entry.args[0], log_entry.args[1],
1526                                      log_entry.flags);
1527                                 continue;
1528                         }
1529
1530                         op = log_entry.operation;
1531                         offset = log_entry.args[0];
1532                         size = log_entry.args[1];
1533                         closeopen = !!(log_entry.flags & FL_CLOSE_OPEN);
1534                         keep_size = !!(log_entry.flags & FL_KEEP_SIZE);
1535                         goto have_op;
1536                 }
1537                 return 0;
1538         }
1539
1540         rv = random();
1541         if (closeprob)
1542                 closeopen = (rv >> 3) < (1 << 28) / closeprob;
1543
1544         offset = random();
1545         size = maxoplen;
1546         if (randomoplen)
1547                 size = random() % (maxoplen + 1);
1548
1549         /* calculate appropriate op to run */
1550         if (lite)
1551                 op = rv % OP_MAX_LITE;
1552         else if (!integrity)
1553                 op = rv % OP_MAX_FULL;
1554         else
1555                 op = rv % OP_MAX_INTEGRITY;
1556
1557         switch(op) {
1558         case OP_TRUNCATE:
1559                 if (!style)
1560                         size = random() % maxfilelen;
1561                 break;
1562         case OP_FALLOCATE:
1563                 if (fallocate_calls && size && keep_size_calls)
1564                         keep_size = random() % 2;
1565                 break;
1566         case OP_ZERO_RANGE:
1567                 if (zero_range_calls && size && keep_size_calls)
1568                         keep_size = random() % 2;
1569                 break;
1570         }
1571
1572 have_op:
1573
1574         switch (op) {
1575         case OP_MAPREAD:
1576                 if (!mapped_reads)
1577                         op = OP_READ;
1578                 break;
1579         case OP_MAPWRITE:
1580                 if (!mapped_writes)
1581                         op = OP_WRITE;
1582                 break;
1583         case OP_FALLOCATE:
1584                 if (!fallocate_calls) {
1585                         log4(OP_FALLOCATE, offset, size, FL_SKIPPED);
1586                         goto out;
1587                 }
1588                 break;
1589         case OP_PUNCH_HOLE:
1590                 if (!punch_hole_calls) {
1591                         log4(OP_PUNCH_HOLE, offset, size, FL_SKIPPED);
1592                         goto out;
1593                 }
1594                 break;
1595         case OP_ZERO_RANGE:
1596                 if (!zero_range_calls) {
1597                         log4(OP_ZERO_RANGE, offset, size, FL_SKIPPED);
1598                         goto out;
1599                 }
1600                 break;
1601         case OP_COLLAPSE_RANGE:
1602                 if (!collapse_range_calls) {
1603                         log4(OP_COLLAPSE_RANGE, offset, size, FL_SKIPPED);
1604                         goto out;
1605                 }
1606                 break;
1607         case OP_INSERT_RANGE:
1608                 if (!insert_range_calls) {
1609                         log4(OP_INSERT_RANGE, offset, size, FL_SKIPPED);
1610                         goto out;
1611                 }
1612                 break;
1613         }
1614
1615         switch (op) {
1616         case OP_READ:
1617                 TRIM_OFF_LEN(offset, size, file_size);
1618                 doread(offset, size);
1619                 break;
1620
1621         case OP_WRITE:
1622                 TRIM_OFF_LEN(offset, size, maxfilelen);
1623                 dowrite(offset, size);
1624                 break;
1625
1626         case OP_MAPREAD:
1627                 TRIM_OFF_LEN(offset, size, file_size);
1628                 domapread(offset, size);
1629                 break;
1630
1631         case OP_MAPWRITE:
1632                 TRIM_OFF_LEN(offset, size, maxfilelen);
1633                 domapwrite(offset, size);
1634                 break;
1635
1636         case OP_TRUNCATE:
1637                 dotruncate(size);
1638                 break;
1639
1640         case OP_FALLOCATE:
1641                 TRIM_OFF_LEN(offset, size, maxfilelen);
1642                 do_preallocate(offset, size, keep_size);
1643                 break;
1644
1645         case OP_PUNCH_HOLE:
1646                 TRIM_OFF_LEN(offset, size, file_size);
1647                 do_punch_hole(offset, size);
1648                 break;
1649         case OP_ZERO_RANGE:
1650                 TRIM_OFF_LEN(offset, size, file_size);
1651                 do_zero_range(offset, size, keep_size);
1652                 break;
1653         case OP_COLLAPSE_RANGE:
1654                 TRIM_OFF_LEN(offset, size, file_size - 1);
1655                 offset = offset & ~(block_size - 1);
1656                 size = size & ~(block_size - 1);
1657                 if (size == 0) {
1658                         log4(OP_COLLAPSE_RANGE, offset, size, FL_SKIPPED);
1659                         goto out;
1660                 }
1661                 do_collapse_range(offset, size);
1662                 break;
1663         case OP_INSERT_RANGE:
1664                 TRIM_OFF(offset, file_size);
1665                 TRIM_LEN(file_size, size, maxfilelen);
1666                 offset = offset & ~(block_size - 1);
1667                 size = size & ~(block_size - 1);
1668                 if (size == 0) {
1669                         log4(OP_INSERT_RANGE, offset, size, FL_SKIPPED);
1670                         goto out;
1671                 }
1672                 if (file_size + size > maxfilelen) {
1673                         log4(OP_INSERT_RANGE, offset, size, FL_SKIPPED);
1674                         goto out;
1675                 }
1676
1677                 do_insert_range(offset, size);
1678                 break;
1679         case OP_FSYNC:
1680                 dofsync();
1681                 break;
1682         default:
1683                 prterr("test: unknown operation");
1684                 report_failure(42);
1685                 break;
1686         }
1687
1688         if (check_file && testcalls > simulatedopcount)
1689                 check_contents();
1690
1691 out:
1692         if (sizechecks && testcalls > simulatedopcount)
1693                 check_size();
1694         if (closeopen)
1695                 docloseopen();
1696         return 1;
1697 }
1698
1699
1700 void
1701 usage(void)
1702 {
1703         fprintf(stdout, "usage: %s",
1704                 "fsx [-dknqxAFLOWZ] [-b opnum] [-c Prob] [-g filldata] [-i logdev] [-j logid] [-l flen] [-m start:end] [-o oplen] [-p progressinterval] [-r readbdy] [-s style] [-t truncbdy] [-w writebdy] [-D startingop] [-N numops] [-P dirpath] [-S seed] fname\n\
1705         -b opnum: beginning operation number (default 1)\n\
1706         -c P: 1 in P chance of file close+open at each op (default infinity)\n\
1707         -d: debug output for all operations\n\
1708         -f flush and invalidate cache after I/O\n\
1709         -g X: write character X instead of random generated data\n\
1710         -i logdev: do integrity testing, logdev is the dm log writes device\n\
1711         -j logid: prefix debug log messsages with this id\n\
1712         -k: do not truncate existing file and use its size as upper bound on file size\n\
1713         -l flen: the upper bound on file size (default 262144)\n\
1714         -m startop:endop: monitor (print debug output) specified byte range (default 0:infinity)\n\
1715         -n: no verifications of file size\n\
1716         -o oplen: the upper bound on operation size (default 65536)\n\
1717         -p progressinterval: debug output at specified operation interval\n\
1718         -q: quieter operation\n\
1719         -r readbdy: 4096 would make reads page aligned (default 1)\n\
1720         -s style: 1 gives smaller truncates (default 0)\n\
1721         -t truncbdy: 4096 would make truncates page aligned (default 1)\n\
1722         -w writebdy: 4096 would make writes page aligned (default 1)\n\
1723         -x: preallocate file space before starting, XFS only (default 0)\n\
1724         -y synchronize changes to a file\n"
1725
1726 #ifdef AIO
1727 "       -A: Use the AIO system calls\n"
1728 #endif
1729 "       -D startingop: debug output starting at specified operation\n"
1730 #ifdef HAVE_LINUX_FALLOC_H
1731 "       -F: Do not use fallocate (preallocation) calls\n"
1732 #endif
1733 #ifdef FALLOC_FL_PUNCH_HOLE
1734 "       -H: Do not use punch hole calls\n"
1735 #endif
1736 #ifdef FALLOC_FL_ZERO_RANGE
1737 "       -z: Do not use zero range calls\n"
1738 #endif
1739 #ifdef FALLOC_FL_COLLAPSE_RANGE
1740 "       -C: Do not use collapse range calls\n"
1741 #endif
1742 #ifdef FALLOC_FL_INSERT_RANGE
1743 "       -I: Do not use insert range calls\n"
1744 #endif
1745 "       -L: fsxLite - no file creations & no file size changes\n\
1746         -N numops: total # operations to do (default infinity)\n\
1747         -O: use oplen (see -o flag) for every op (default random)\n\
1748         -P: save .fsxlog .fsxops and .fsxgood files in dirpath (default ./)\n\
1749         -S seed: for random # generator (default 1) 0 gets timestamp\n\
1750         -W: mapped write operations DISabled\n\
1751         -X: Read file and compare to good buffer after every operation.\n\
1752         -R: read() system calls only (mapped reads disabled)\n\
1753         -Z: O_DIRECT (use -R, -W, -r and -w too)\n\
1754         --replay-ops opsfile: replay ops from recorded .fsxops file\n\
1755         --record-ops[=opsfile]: dump ops file also on success. optionally specify ops file name\n\
1756         fname: this filename is REQUIRED (no default)\n");
1757         exit(90);
1758 }
1759
1760
1761 int
1762 getnum(char *s, char **e)
1763 {
1764         int ret;
1765
1766         *e = (char *) 0;
1767         ret = strtol(s, e, 0);
1768         if (*e)
1769                 switch (**e) {
1770                 case 'b':
1771                 case 'B':
1772                         ret *= 512;
1773                         *e = *e + 1;
1774                         break;
1775                 case 'k':
1776                 case 'K':
1777                         ret *= 1024;
1778                         *e = *e + 1;
1779                         break;
1780                 case 'm':
1781                 case 'M':
1782                         ret *= 1024*1024;
1783                         *e = *e + 1;
1784                         break;
1785                 case 'w':
1786                 case 'W':
1787                         ret *= 4;
1788                         *e = *e + 1;
1789                         break;
1790                 }
1791         return (ret);
1792 }
1793
1794 #ifdef AIO
1795
1796 #define QSZ     1024
1797 io_context_t    io_ctx;
1798 struct iocb     iocb;
1799
1800 int aio_setup()
1801 {
1802         int ret;
1803         ret = io_queue_init(QSZ, &io_ctx);
1804         if (ret != 0) {
1805                 fprintf(stderr, "aio_setup: io_queue_init failed: %s\n",
1806                         strerror(ret));
1807                 return(-1);
1808         }
1809         return(0);
1810 }
1811
1812 int
1813 __aio_rw(int rw, int fd, char *buf, unsigned len, unsigned offset)
1814 {
1815         struct io_event event;
1816         static struct timespec ts;
1817         struct iocb *iocbs[] = { &iocb };
1818         int ret;
1819         long res;
1820
1821         if (rw == READ) {
1822                 io_prep_pread(&iocb, fd, buf, len, offset);
1823         } else {
1824                 io_prep_pwrite(&iocb, fd, buf, len, offset);
1825         }
1826
1827         ts.tv_sec = 30;
1828         ts.tv_nsec = 0;
1829         ret = io_submit(io_ctx, 1, iocbs);
1830         if (ret != 1) {
1831                 fprintf(stderr, "errcode=%d\n", ret);
1832                 fprintf(stderr, "aio_rw: io_submit failed: %s\n",
1833                                 strerror(ret));
1834                 goto out_error;
1835         }
1836
1837         ret = io_getevents(io_ctx, 1, 1, &event, &ts);
1838         if (ret != 1) {
1839                 if (ret == 0)
1840                         fprintf(stderr, "aio_rw: no events available\n");
1841                 else {
1842                         fprintf(stderr, "errcode=%d\n", -ret);
1843                         fprintf(stderr, "aio_rw: io_getevents failed: %s\n",
1844                                         strerror(-ret));
1845                 }
1846                 goto out_error;
1847         }
1848         if (len != event.res) {
1849                 /*
1850                  * The b0rked libaio defines event.res as unsigned.
1851                  * However the kernel strucuture has it signed,
1852                  * and it's used to pass negated error value.
1853                  * Till the library is fixed use the temp var.
1854                  */
1855                 res = (long)event.res;
1856                 if (res >= 0)
1857                         fprintf(stderr, "bad io length: %lu instead of %u\n",
1858                                         res, len);
1859                 else {
1860                         fprintf(stderr, "errcode=%ld\n", -res);
1861                         fprintf(stderr, "aio_rw: async io failed: %s\n",
1862                                         strerror(-res));
1863                         ret = res;
1864                         goto out_error;
1865                 }
1866
1867         }
1868         return event.res;
1869
1870 out_error:
1871         /*
1872          * The caller expects error return in traditional libc
1873          * convention, i.e. -1 and the errno set to error.
1874          */
1875         errno = -ret;
1876         return -1;
1877 }
1878
1879 int aio_rw(int rw, int fd, char *buf, unsigned len, unsigned offset)
1880 {
1881         int ret;
1882
1883         if (aio) {
1884                 ret = __aio_rw(rw, fd, buf, len, offset);
1885         } else {
1886                 if (rw == READ)
1887                         ret = read(fd, buf, len);
1888                 else
1889                         ret = write(fd, buf, len);
1890         }
1891         return ret;
1892 }
1893
1894 #endif
1895
1896 #define test_fallocate(mode) __test_fallocate(mode, #mode)
1897
1898 int
1899 __test_fallocate(int mode, const char *mode_str)
1900 {
1901 #ifdef HAVE_LINUX_FALLOC_H
1902         int ret = 0;
1903         if (!lite) {
1904                 if (fallocate(fd, mode, file_size, 1) && errno == EOPNOTSUPP) {
1905                         if(!quiet)
1906                                 fprintf(stderr,
1907                                         "main: filesystem does not support "
1908                                         "fallocate mode %s, disabling!\n",
1909                                         mode_str);
1910                 } else {
1911                         ret = 1;
1912                         if (ftruncate(fd, file_size)) {
1913                                 warn("main: ftruncate");
1914                                 exit(132);
1915                         }
1916                 }
1917         }
1918         return ret;
1919 #endif
1920 }
1921
1922 static struct option longopts[] = {
1923         {"replay-ops", required_argument, 0, 256},
1924         {"record-ops", optional_argument, 0, 255},
1925         { }
1926 };
1927
1928 int
1929 main(int argc, char **argv)
1930 {
1931         int     i, style, ch;
1932         char    *endp, *tmp;
1933         char logfile[PATH_MAX];
1934         struct stat statbuf;
1935         int o_flags = O_RDWR|O_CREAT|O_TRUNC;
1936
1937         logfile[0] = 0;
1938         dname[0] = 0;
1939
1940         page_size = getpagesize();
1941         page_mask = page_size - 1;
1942         mmap_mask = page_mask;
1943         
1944
1945         setvbuf(stdout, (char *)0, _IOLBF, 0); /* line buffered stdout */
1946
1947         while ((ch = getopt_long(argc, argv,
1948                                  "b:c:dfg:i:j:kl:m:no:p:qr:s:t:w:xyAD:FKHzCILN:OP:RS:WXZ",
1949                                  longopts, NULL)) != EOF)
1950                 switch (ch) {
1951                 case 'b':
1952                         simulatedopcount = getnum(optarg, &endp);
1953                         if (!quiet)
1954                                 prt("Will begin at operation %ld\n", simulatedopcount);
1955                         if (simulatedopcount == 0)
1956                                 usage();
1957                         simulatedopcount -= 1;
1958                         break;
1959                 case 'c':
1960                         closeprob = getnum(optarg, &endp);
1961                         if (!quiet)
1962                                 prt("Chance of close/open is 1 in %d\n", closeprob);
1963                         if (closeprob <= 0)
1964                                 usage();
1965                         break;
1966                 case 'd':
1967                         debug = 1;
1968                         break;
1969                 case 'f':
1970                         flush = 1;
1971                         break;
1972                 case 'g':
1973                         filldata = *optarg;
1974                         break;
1975                 case 'i':
1976                         integrity = 1;
1977                         logdev = strdup(optarg);
1978                         if (!logdev) {
1979                                 prterr("strdup");
1980                                 exit(101);
1981                         }
1982                         break;
1983                 case 'j':
1984                         logid = strdup(optarg);
1985                         if (!logid) {
1986                                 prterr("strdup");
1987                                 exit(101);
1988                         }
1989                         break;
1990                 case 'k':
1991                         o_flags &= ~O_TRUNC;
1992                         break;
1993                 case 'l':
1994                         maxfilelen = getnum(optarg, &endp);
1995                         if (maxfilelen <= 0)
1996                                 usage();
1997                         break;
1998                 case 'm':
1999                         monitorstart = getnum(optarg, &endp);
2000                         if (monitorstart < 0)
2001                                 usage();
2002                         if (!endp || *endp++ != ':')
2003                                 usage();
2004                         monitorend = getnum(endp, &endp);
2005                         if (monitorend < 0)
2006                                 usage();
2007                         if (monitorend == 0)
2008                                 monitorend = -1; /* aka infinity */
2009                         debug = 1;
2010                 case 'n':
2011                         sizechecks = 0;
2012                         break;
2013                 case 'o':
2014                         maxoplen = getnum(optarg, &endp);
2015                         if (maxoplen <= 0)
2016                                 usage();
2017                         break;
2018                 case 'p':
2019                         progressinterval = getnum(optarg, &endp);
2020                         if (progressinterval == 0)
2021                                 usage();
2022                         break;
2023                 case 'q':
2024                         quiet = 1;
2025                         break;
2026                 case 'r':
2027                         readbdy = getnum(optarg, &endp);
2028                         if (readbdy <= 0)
2029                                 usage();
2030                         break;
2031                 case 's':
2032                         style = getnum(optarg, &endp);
2033                         if (style < 0 || style > 1)
2034                                 usage();
2035                         break;
2036                 case 't':
2037                         truncbdy = getnum(optarg, &endp);
2038                         if (truncbdy <= 0)
2039                                 usage();
2040                         break;
2041                 case 'w':
2042                         writebdy = getnum(optarg, &endp);
2043                         if (writebdy <= 0)
2044                                 usage();
2045                         break;
2046                 case 'x':
2047                         prealloc = 1;
2048                         break;
2049                 case 'y':
2050                         do_fsync = 1;
2051                         break;
2052                 case 'A':
2053                         aio = 1;
2054                         break;
2055                 case 'D':
2056                         debugstart = getnum(optarg, &endp);
2057                         if (debugstart < 1)
2058                                 usage();
2059                         break;
2060                 case 'F':
2061                         fallocate_calls = 0;
2062                         break;
2063                 case 'K':
2064                         keep_size_calls = 0;
2065                         break;
2066                 case 'H':
2067                         punch_hole_calls = 0;
2068                         break;
2069                 case 'z':
2070                         zero_range_calls = 0;
2071                         break;
2072                 case 'C':
2073                         collapse_range_calls = 0;
2074                         break;
2075                 case 'I':
2076                         insert_range_calls = 0;
2077                         break;
2078                 case 'L':
2079                         lite = 1;
2080                         o_flags &= ~(O_CREAT|O_TRUNC);
2081                         break;
2082                 case 'N':
2083                         numops = getnum(optarg, &endp);
2084                         if (numops < 0)
2085                                 usage();
2086                         break;
2087                 case 'O':
2088                         randomoplen = 0;
2089                         break;
2090                 case 'P':
2091                         strncpy(dname, optarg, sizeof(dname));
2092                         strcat(dname, "/");
2093                         dirpath = strlen(dname);
2094                         break;
2095                 case 'R':
2096                         mapped_reads = 0;
2097                         break;
2098                 case 'S':
2099                         seed = getnum(optarg, &endp);
2100                         if (seed == 0) {
2101                                 seed = time(0) % 10000;
2102                                 seed += (int)getpid();
2103                         }
2104                         if (seed < 0)
2105                                 usage();
2106                         break;
2107                 case 'W':
2108                         mapped_writes = 0;
2109                         if (!quiet)
2110                                 prt("mapped writes DISABLED\n");
2111                         break;
2112                 case 'X':
2113                         check_file = 1;
2114                         break;
2115                 case 'Z':
2116                         o_direct = O_DIRECT;
2117                         o_flags |= O_DIRECT;
2118                         break;
2119                 case 255:  /* --record-ops */
2120                         if (optarg)
2121                                 strncpy(opsfile, optarg, sizeof(opsfile));
2122                         recordops = opsfile;
2123                         break;
2124                 case 256:  /* --replay-ops */
2125                         replayops = optarg;
2126                         break;
2127                 default:
2128                         usage();
2129                         /* NOTREACHED */
2130                 }
2131         argc -= optind;
2132         argv += optind;
2133         if (argc != 1)
2134                 usage();
2135
2136         if (integrity && !dirpath) {
2137                 fprintf(stderr, "option -i <logdev> requires -P <dirpath>\n");
2138                 usage();
2139         }
2140
2141         fname = argv[0];
2142         tmp = strdup(fname);
2143         if (!tmp) {
2144                 prterr("strdup");
2145                 exit(101);
2146         }
2147         bname = basename(tmp);
2148
2149         signal(SIGHUP,  cleanup);
2150         signal(SIGINT,  cleanup);
2151         signal(SIGPIPE, cleanup);
2152         signal(SIGALRM, cleanup);
2153         signal(SIGTERM, cleanup);
2154         signal(SIGXCPU, cleanup);
2155         signal(SIGXFSZ, cleanup);
2156         signal(SIGVTALRM,       cleanup);
2157         signal(SIGUSR1, cleanup);
2158         signal(SIGUSR2, cleanup);
2159
2160         if (!quiet && seed)
2161                 prt("Seed set to %d\n", seed);
2162         srandom(seed);
2163         fd = open(fname, o_flags, 0666);
2164         if (fd < 0) {
2165                 prterr(fname);
2166                 exit(91);
2167         }
2168         if (fstat(fd, &statbuf)) {
2169                 prterr("check_size: fstat");
2170                 exit(91);
2171         }
2172         block_size = statbuf.st_blksize;
2173 #ifdef XFS
2174         if (prealloc) {
2175                 xfs_flock64_t   resv = { 0 };
2176 #ifdef HAVE_XFS_PLATFORM_DEFS_H
2177                 if (!platform_test_xfs_fd(fd)) {
2178                         prterr(fname);
2179                         fprintf(stderr, "main: cannot prealloc, non XFS\n");
2180                         exit(96);
2181                 }
2182 #endif
2183                 resv.l_len = maxfilelen;
2184                 if ((xfsctl(fname, fd, XFS_IOC_RESVSP, &resv)) < 0) {
2185                         prterr(fname);
2186                         exit(97);
2187                 }
2188         }
2189 #endif
2190
2191         if (dirpath) {
2192                 snprintf(goodfile, sizeof(goodfile), "%s%s.fsxgood", dname, bname);
2193                 snprintf(logfile, sizeof(logfile), "%s%s.fsxlog", dname, bname);
2194                 if (!*opsfile)
2195                         snprintf(opsfile, sizeof(opsfile), "%s%s.fsxops", dname, bname);
2196         } else {
2197                 snprintf(goodfile, sizeof(goodfile), "%s.fsxgood", fname);
2198                 snprintf(logfile, sizeof(logfile), "%s.fsxlog", fname);
2199                 if (!*opsfile)
2200                         snprintf(opsfile, sizeof(opsfile), "%s.fsxops", fname);
2201         }
2202         fsxgoodfd = open(goodfile, O_RDWR|O_CREAT|O_TRUNC, 0666);
2203         if (fsxgoodfd < 0) {
2204                 prterr(goodfile);
2205                 exit(92);
2206         }
2207         fsxlogf = fopen(logfile, "w");
2208         if (fsxlogf == NULL) {
2209                 prterr(logfile);
2210                 exit(93);
2211         }
2212         unlink(opsfile);
2213
2214         if (replayops) {
2215                 replayopsf = fopen(replayops, "r");
2216                 if (!replayopsf) {
2217                         prterr(replayops);
2218                         exit(93);
2219                 }
2220         }
2221
2222 #ifdef AIO
2223         if (aio) 
2224                 aio_setup();
2225 #endif
2226
2227         if (!(o_flags & O_TRUNC)) {
2228                 off_t ret;
2229                 file_size = maxfilelen = biggest = lseek(fd, (off_t)0, SEEK_END);
2230                 if (file_size == (off_t)-1) {
2231                         prterr(fname);
2232                         warn("main: lseek eof");
2233                         exit(94);
2234                 }
2235                 ret = lseek(fd, (off_t)0, SEEK_SET);
2236                 if (ret == (off_t)-1) {
2237                         prterr(fname);
2238                         warn("main: lseek 0");
2239                         exit(95);
2240                 }
2241         }
2242         original_buf = (char *) malloc(maxfilelen);
2243         for (i = 0; i < maxfilelen; i++)
2244                 original_buf[i] = random() % 256;
2245         good_buf = (char *) malloc(maxfilelen + writebdy);
2246         good_buf = round_ptr_up(good_buf, writebdy, 0);
2247         memset(good_buf, '\0', maxfilelen);
2248         temp_buf = (char *) malloc(maxoplen + readbdy);
2249         temp_buf = round_ptr_up(temp_buf, readbdy, 0);
2250         memset(temp_buf, '\0', maxoplen);
2251         if (lite) {     /* zero entire existing file */
2252                 ssize_t written;
2253
2254                 written = write(fd, good_buf, (size_t)maxfilelen);
2255                 if (written != maxfilelen) {
2256                         if (written == -1) {
2257                                 prterr(fname);
2258                                 warn("main: error on write");
2259                         } else
2260                                 warn("main: short write, 0x%x bytes instead "
2261                                         "of 0x%lx\n",
2262                                         (unsigned)written,
2263                                         maxfilelen);
2264                         exit(98);
2265                 }
2266         } else {
2267                 ssize_t ret, len = file_size;
2268                 off_t off = 0;
2269
2270                 while (len > 0) {
2271                         ret = read(fd, good_buf + off, len);
2272                         if (ret == -1) {
2273                                 prterr(fname);
2274                                 warn("main: error on read");
2275                                 exit(98);
2276                         }
2277                         len -= ret;
2278                         off += ret;
2279                 }
2280
2281                 check_trunc_hack();
2282         }
2283
2284         if (fallocate_calls)
2285                 fallocate_calls = test_fallocate(0);
2286         if (keep_size_calls)
2287                 keep_size_calls = test_fallocate(FALLOC_FL_KEEP_SIZE);
2288         if (punch_hole_calls)
2289                 punch_hole_calls = test_fallocate(FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE);
2290         if (zero_range_calls)
2291                 zero_range_calls = test_fallocate(FALLOC_FL_ZERO_RANGE);
2292         if (collapse_range_calls)
2293                 collapse_range_calls = test_fallocate(FALLOC_FL_COLLAPSE_RANGE);
2294         if (insert_range_calls)
2295                 insert_range_calls = test_fallocate(FALLOC_FL_INSERT_RANGE);
2296
2297         while (numops == -1 || numops--)
2298                 if (!test())
2299                         break;
2300
2301         free(tmp);
2302         if (close(fd)) {
2303                 prterr("close");
2304                 report_failure(99);
2305         }
2306         prt("All %lu operations completed A-OK!\n", testcalls);
2307         if (recordops)
2308                 logdump();
2309
2310         exit(0);
2311         return 0;
2312 }