build: Move fallocate include into global.h
[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 #ifdef HAVE_ERR_H
24 #include <err.h>
25 #endif
26 #include <signal.h>
27 #include <stdio.h>
28 #include <stddef.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <stdarg.h>
32 #include <errno.h>
33 #ifdef AIO
34 #include <libaio.h>
35 #endif
36
37 #ifndef MAP_FILE
38 # define MAP_FILE 0
39 #endif
40
41 #define NUMPRINTCOLUMNS 32      /* # columns of data to print on each line */
42
43 /*
44  *      A log entry is an operation and a bunch of arguments.
45  */
46
47 struct log_entry {
48         int     operation;
49         int     args[3];
50 };
51
52 #define LOGSIZE 1000
53
54 struct log_entry        oplog[LOGSIZE]; /* the log */
55 int                     logptr = 0;     /* current position in log */
56 int                     logcount = 0;   /* total ops */
57
58 /*
59  * The operation matrix is complex due to conditional execution of different
60  * features. Hence when we come to deciding what operation to run, we need to
61  * be careful in how we select the different operations. The active operations
62  * are mapped to numbers as follows:
63  *
64  *              lite    !lite
65  * READ:        0       0
66  * WRITE:       1       1
67  * MAPREAD:     2       2
68  * MAPWRITE:    3       3
69  * TRUNCATE:    -       4
70  * FALLOCATE:   -       5
71  * PUNCH HOLE:  -       6
72  *
73  * When mapped read/writes are disabled, they are simply converted to normal
74  * reads and writes. When fallocate/fpunch calls are disabled, they are
75  * converted to OP_SKIPPED. Hence OP_SKIPPED needs to have a number higher than
76  * the operation selction matrix, as does the OP_CLOSEOPEN which is an
77  * operation modifier rather than an operation in itself.
78  *
79  * Because of the "lite" version, we also need to have different "maximum
80  * operation" defines to allow the ops to be selected correctly based on the
81  * mode being run.
82  */
83
84 /* common operations */
85 #define OP_READ         0
86 #define OP_WRITE        1
87 #define OP_MAPREAD      2
88 #define OP_MAPWRITE     3
89 #define OP_MAX_LITE     4
90
91 /* !lite operations */
92 #define OP_TRUNCATE     4
93 #define OP_FALLOCATE    5
94 #define OP_PUNCH_HOLE   6
95 #define OP_MAX_FULL     7
96
97 /* operation modifiers */
98 #define OP_CLOSEOPEN    100
99 #define OP_SKIPPED      101
100
101 #undef PAGE_SIZE
102 #define PAGE_SIZE       getpagesize()
103 #undef PAGE_MASK
104 #define PAGE_MASK       (PAGE_SIZE - 1)
105
106 char    *original_buf;                  /* a pointer to the original data */
107 char    *good_buf;                      /* a pointer to the correct data */
108 char    *temp_buf;                      /* a pointer to the current data */
109 char    *fname;                         /* name of our test file */
110 int     fd;                             /* fd for our test file */
111
112 off_t           file_size = 0;
113 off_t           biggest = 0;
114 char            state[256];
115 unsigned long   testcalls = 0;          /* calls to function "test" */
116
117 unsigned long   simulatedopcount = 0;   /* -b flag */
118 int     closeprob = 0;                  /* -c flag */
119 int     debug = 0;                      /* -d flag */
120 unsigned long   debugstart = 0;         /* -D flag */
121 int     flush = 0;                      /* -f flag */
122 int     do_fsync = 0;                   /* -y flag */
123 unsigned long   maxfilelen = 256 * 1024;        /* -l flag */
124 int     sizechecks = 1;                 /* -n flag disables them */
125 int     maxoplen = 64 * 1024;           /* -o flag */
126 int     quiet = 0;                      /* -q flag */
127 unsigned long progressinterval = 0;     /* -p flag */
128 int     readbdy = 1;                    /* -r flag */
129 int     style = 0;                      /* -s flag */
130 int     prealloc = 0;                   /* -x flag */
131 int     truncbdy = 1;                   /* -t flag */
132 int     writebdy = 1;                   /* -w flag */
133 long    monitorstart = -1;              /* -m flag */
134 long    monitorend = -1;                /* -m flag */
135 int     lite = 0;                       /* -L flag */
136 long    numops = -1;                    /* -N flag */
137 int     randomoplen = 1;                /* -O flag disables it */
138 int     seed = 1;                       /* -S flag */
139 int     mapped_writes = 1;              /* -W flag disables */
140 int     fallocate_calls = 1;            /* -F flag disables */
141 int     punch_hole_calls = 1;           /* -H flag disables */
142 int     mapped_reads = 1;               /* -R flag disables it */
143 int     fsxgoodfd = 0;
144 int     o_direct;                       /* -Z */
145 int     aio = 0;
146
147 int page_size;
148 int page_mask;
149 int mmap_mask;
150 #ifdef AIO
151 int aio_rw(int rw, int fd, char *buf, unsigned len, unsigned offset);
152 #define READ 0
153 #define WRITE 1
154 #define fsxread(a,b,c,d)        aio_rw(READ, a,b,c,d)
155 #define fsxwrite(a,b,c,d)       aio_rw(WRITE, a,b,c,d)
156 #else
157 #define fsxread(a,b,c,d)        read(a,b,c)
158 #define fsxwrite(a,b,c,d)       write(a,b,c)
159 #endif
160
161 FILE *  fsxlogf = NULL;
162 int badoff = -1;
163 int closeopen = 0;
164
165 static void *round_ptr_up(void *ptr, unsigned long align, unsigned long offset)
166 {
167         unsigned long ret = (unsigned long)ptr;
168
169         ret = ((ret + align - 1) & ~(align - 1));
170         ret += offset;
171         return (void *)ret;
172 }
173
174 void
175 vwarnc(int code, const char *fmt, va_list ap) {
176   fprintf(stderr, "fsx: ");
177   if (fmt != NULL) {
178         vfprintf(stderr, fmt, ap);
179         fprintf(stderr, ": ");
180   }
181   fprintf(stderr, "%s\n", strerror(code));
182 }
183
184 void
185 warn(const char * fmt, ...)  {
186         va_list ap;
187         va_start(ap, fmt);
188         vwarnc(errno, fmt, ap);
189         va_end(ap);
190 }
191
192 #define BUF_SIZE 1024
193
194 void
195 prt(char *fmt, ...)
196 {
197         va_list args;
198         char buffer[BUF_SIZE];
199
200         va_start(args, fmt);
201         vsnprintf(buffer, BUF_SIZE, fmt, args);
202         va_end(args);
203         fprintf(stdout, buffer);
204         if (fsxlogf)
205                 fprintf(fsxlogf, buffer);
206 }
207
208 void
209 prterr(char *prefix)
210 {
211         prt("%s%s%s\n", prefix, prefix ? ": " : "", strerror(errno));
212 }
213
214
215 void
216 log4(int operation, int arg0, int arg1, int arg2)
217 {
218         struct log_entry *le;
219
220         le = &oplog[logptr];
221         le->operation = operation;
222         if (closeopen)
223                 le->operation = ~ le->operation;
224         le->args[0] = arg0;
225         le->args[1] = arg1;
226         le->args[2] = arg2;
227         logptr++;
228         logcount++;
229         if (logptr >= LOGSIZE)
230                 logptr = 0;
231 }
232
233
234 void
235 logdump(void)
236 {
237         int     i, count, down;
238         struct log_entry        *lp;
239         char *falloc_type[3] = {"PAST_EOF", "EXTENDING", "INTERIOR"};
240
241         prt("LOG DUMP (%d total operations):\n", logcount);
242         if (logcount < LOGSIZE) {
243                 i = 0;
244                 count = logcount;
245         } else {
246                 i = logptr;
247                 count = LOGSIZE;
248         }
249         for ( ; count > 0; count--) {
250                 int opnum;
251
252                 opnum = i+1 + (logcount/LOGSIZE)*LOGSIZE;
253                 prt("%d(%3d mod 256): ", opnum, opnum%256);
254                 lp = &oplog[i];
255                 if ((closeopen = lp->operation < 0))
256                         lp->operation = ~ lp->operation;
257                         
258                 switch (lp->operation) {
259                 case OP_MAPREAD:
260                         prt("MAPREAD  0x%x thru 0x%x\t(0x%x bytes)",
261                             lp->args[0], lp->args[0] + lp->args[1] - 1,
262                             lp->args[1]);
263                         if (badoff >= lp->args[0] && badoff <
264                                                      lp->args[0] + lp->args[1])
265                                 prt("\t***RRRR***");
266                         break;
267                 case OP_MAPWRITE:
268                         prt("MAPWRITE 0x%x thru 0x%x\t(0x%x bytes)",
269                             lp->args[0], lp->args[0] + lp->args[1] - 1,
270                             lp->args[1]);
271                         if (badoff >= lp->args[0] && badoff <
272                                                      lp->args[0] + lp->args[1])
273                                 prt("\t******WWWW");
274                         break;
275                 case OP_READ:
276                         prt("READ     0x%x thru 0x%x\t(0x%x bytes)",
277                             lp->args[0], lp->args[0] + lp->args[1] - 1,
278                             lp->args[1]);
279                         if (badoff >= lp->args[0] &&
280                             badoff < lp->args[0] + lp->args[1])
281                                 prt("\t***RRRR***");
282                         break;
283                 case OP_WRITE:
284                         prt("WRITE    0x%x thru 0x%x\t(0x%x bytes)",
285                             lp->args[0], lp->args[0] + lp->args[1] - 1,
286                             lp->args[1]);
287                         if (lp->args[0] > lp->args[2])
288                                 prt(" HOLE");
289                         else if (lp->args[0] + lp->args[1] > lp->args[2])
290                                 prt(" EXTEND");
291                         if ((badoff >= lp->args[0] || badoff >=lp->args[2]) &&
292                             badoff < lp->args[0] + lp->args[1])
293                                 prt("\t***WWWW");
294                         break;
295                 case OP_TRUNCATE:
296                         down = lp->args[0] < lp->args[1];
297                         prt("TRUNCATE %s\tfrom 0x%x to 0x%x",
298                             down ? "DOWN" : "UP", lp->args[1], lp->args[0]);
299                         if (badoff >= lp->args[!down] &&
300                             badoff < lp->args[!!down])
301                                 prt("\t******WWWW");
302                         break;
303                 case OP_FALLOCATE:
304                         /* 0: offset 1: length 2: where alloced */
305                         prt("FALLOC   0x%x thru 0x%x\t(0x%x bytes) %s",
306                                 lp->args[0], lp->args[0] + lp->args[1],
307                                 lp->args[1], falloc_type[lp->args[2]]);
308                         if (badoff >= lp->args[0] &&
309                             badoff < lp->args[0] + lp->args[1])
310                                 prt("\t******FFFF");
311                         break;
312                 case OP_PUNCH_HOLE:
313                         prt("PUNCH    0x%x thru 0x%x\t(0x%x bytes)",
314                             lp->args[0], lp->args[0] + lp->args[1] - 1,
315                             lp->args[1]);
316                         if (badoff >= lp->args[0] && badoff <
317                                                      lp->args[0] + lp->args[1])
318                                 prt("\t******PPPP");
319                         break;
320                 case OP_SKIPPED:
321                         prt("SKIPPED (no operation)");
322                         break;
323                 default:
324                         prt("BOGUS LOG ENTRY (operation code = %d)!",
325                             lp->operation);
326                 }
327                 if (closeopen)
328                         prt("\n\t\tCLOSE/OPEN");
329                 prt("\n");
330                 i++;
331                 if (i == LOGSIZE)
332                         i = 0;
333         }
334 }
335
336
337 void
338 save_buffer(char *buffer, off_t bufferlength, int fd)
339 {
340         off_t ret;
341         ssize_t byteswritten;
342
343         if (fd <= 0 || bufferlength == 0)
344                 return;
345
346         if (bufferlength > SSIZE_MAX) {
347                 prt("fsx flaw: overflow in save_buffer\n");
348                 exit(67);
349         }
350         if (lite) {
351                 off_t size_by_seek = lseek(fd, (off_t)0, SEEK_END);
352                 if (size_by_seek == (off_t)-1)
353                         prterr("save_buffer: lseek eof");
354                 else if (bufferlength > size_by_seek) {
355                         warn("save_buffer: .fsxgood file too short... will save 0x%llx bytes instead of 0x%llx\n", (unsigned long long)size_by_seek,
356                              (unsigned long long)bufferlength);
357                         bufferlength = size_by_seek;
358                 }
359         }
360
361         ret = lseek(fd, (off_t)0, SEEK_SET);
362         if (ret == (off_t)-1)
363                 prterr("save_buffer: lseek 0");
364         
365         byteswritten = write(fd, buffer, (size_t)bufferlength);
366         if (byteswritten != bufferlength) {
367                 if (byteswritten == -1)
368                         prterr("save_buffer write");
369                 else
370                         warn("save_buffer: short write, 0x%x bytes instead of 0x%llx\n",
371                              (unsigned)byteswritten,
372                              (unsigned long long)bufferlength);
373         }
374 }
375
376
377 void
378 report_failure(int status)
379 {
380         logdump();
381         
382         if (fsxgoodfd) {
383                 if (good_buf) {
384                         save_buffer(good_buf, file_size, fsxgoodfd);
385                         prt("Correct content saved for comparison\n");
386                         prt("(maybe hexdump \"%s\" vs \"%s.fsxgood\")\n",
387                             fname, fname);
388                 }
389                 close(fsxgoodfd);
390         }
391         exit(status);
392 }
393
394
395 #define short_at(cp) ((unsigned short)((*((unsigned char *)(cp)) << 8) | \
396                                         *(((unsigned char *)(cp)) + 1)))
397
398 void
399 check_buffers(unsigned offset, unsigned size)
400 {
401         unsigned char c, t;
402         unsigned i = 0;
403         unsigned n = 0;
404         unsigned op = 0;
405         unsigned bad = 0;
406
407         if (memcmp(good_buf + offset, temp_buf, size) != 0) {
408                 prt("READ BAD DATA: offset = 0x%x, size = 0x%x, fname = %s\n",
409                     offset, size, fname);
410                 prt("OFFSET\tGOOD\tBAD\tRANGE\n");
411                 while (size > 0) {
412                         c = good_buf[offset];
413                         t = temp_buf[i];
414                         if (c != t) {
415                                 if (n < 16) {
416                                         bad = short_at(&temp_buf[i]);
417                                         prt("0x%5x\t0x%04x\t0x%04x", offset,
418                                             short_at(&good_buf[offset]), bad);
419                                         op = temp_buf[offset & 1 ? i+1 : i];
420                                         prt("\t0x%5x\n", n);
421                                         if (op)
422                                                 prt("operation# (mod 256) for "
423                                                   "the bad data may be %u\n",
424                                                 ((unsigned)op & 0xff));
425                                         else
426                                                 prt("operation# (mod 256) for "
427                                                   "the bad data unknown, check"
428                                                   " HOLE and EXTEND ops\n");
429                                 }
430                                 n++;
431                                 badoff = offset;
432                         }
433                         offset++;
434                         i++;
435                         size--;
436                 }
437                 report_failure(110);
438         }
439 }
440
441
442 void
443 check_size(void)
444 {
445         struct stat     statbuf;
446         off_t   size_by_seek;
447
448         if (fstat(fd, &statbuf)) {
449                 prterr("check_size: fstat");
450                 statbuf.st_size = -1;
451         }
452         size_by_seek = lseek(fd, (off_t)0, SEEK_END);
453         if (file_size != statbuf.st_size || file_size != size_by_seek) {
454                 prt("Size error: expected 0x%llx stat 0x%llx seek 0x%llx\n",
455                     (unsigned long long)file_size,
456                     (unsigned long long)statbuf.st_size,
457                     (unsigned long long)size_by_seek);
458                 report_failure(120);
459         }
460 }
461
462
463 void
464 check_trunc_hack(void)
465 {
466         struct stat statbuf;
467
468         ftruncate(fd, (off_t)0);
469         ftruncate(fd, (off_t)100000);
470         fstat(fd, &statbuf);
471         if (statbuf.st_size != (off_t)100000) {
472                 prt("no extend on truncate! not posix!\n");
473                 exit(130);
474         }
475         ftruncate(fd, 0);
476 }
477
478 void
479 doflush(unsigned offset, unsigned size)
480 {
481         unsigned pg_offset;
482         unsigned map_size;
483         char    *p;
484
485         if (o_direct == O_DIRECT)
486                 return;
487
488         pg_offset = offset & mmap_mask;
489         map_size  = pg_offset + size;
490
491         if ((p = (char *)mmap(0, map_size, PROT_READ | PROT_WRITE,
492                               MAP_FILE | MAP_SHARED, fd,
493                               (off_t)(offset - pg_offset))) == (char *)-1) {
494                 prterr("doflush: mmap");
495                 report_failure(202);
496         }
497         if (msync(p, map_size, MS_INVALIDATE) != 0) {
498                 prterr("doflush: msync");
499                 report_failure(203);
500         }
501         if (munmap(p, map_size) != 0) {
502                 prterr("doflush: munmap");
503                 report_failure(204);
504         }
505 }
506
507 void
508 doread(unsigned offset, unsigned size)
509 {
510         off_t ret;
511         unsigned iret;
512
513         offset -= offset % readbdy;
514         if (o_direct)
515                 size -= size % readbdy;
516         if (size == 0) {
517                 if (!quiet && testcalls > simulatedopcount && !o_direct)
518                         prt("skipping zero size read\n");
519                 log4(OP_SKIPPED, OP_READ, offset, size);
520                 return;
521         }
522         if (size + offset > file_size) {
523                 if (!quiet && testcalls > simulatedopcount)
524                         prt("skipping seek/read past end of file\n");
525                 log4(OP_SKIPPED, OP_READ, offset, size);
526                 return;
527         }
528
529         log4(OP_READ, offset, size, 0);
530
531         if (testcalls <= simulatedopcount)
532                 return;
533
534         if (!quiet &&
535                 ((progressinterval && testcalls % progressinterval == 0)  ||
536                 (debug &&
537                        (monitorstart == -1 ||
538                         (offset + size > monitorstart &&
539                         (monitorend == -1 || offset <= monitorend))))))
540                 prt("%lu read\t0x%x thru\t0x%x\t(0x%x bytes)\n", testcalls,
541                     offset, offset + size - 1, size);
542         ret = lseek(fd, (off_t)offset, SEEK_SET);
543         if (ret == (off_t)-1) {
544                 prterr("doread: lseek");
545                 report_failure(140);
546         }
547         iret = fsxread(fd, temp_buf, size, offset);
548         if (iret != size) {
549                 if (iret == -1)
550                         prterr("doread: read");
551                 else
552                         prt("short read: 0x%x bytes instead of 0x%x\n",
553                             iret, size);
554                 report_failure(141);
555         }
556         check_buffers(offset, size);
557 }
558
559
560 void
561 check_eofpage(char *s, unsigned offset, char *p, int size)
562 {
563         unsigned long last_page, should_be_zero;
564
565         if (offset + size <= (file_size & ~page_mask))
566                 return;
567         /*
568          * we landed in the last page of the file
569          * test to make sure the VM system provided 0's 
570          * beyond the true end of the file mapping
571          * (as required by mmap def in 1996 posix 1003.1)
572          */
573         last_page = ((unsigned long)p + (offset & page_mask) + size) & ~page_mask;
574
575         for (should_be_zero = last_page + (file_size & page_mask);
576              should_be_zero < last_page + page_size;
577              should_be_zero++)
578                 if (*(char *)should_be_zero) {
579                         prt("Mapped %s: non-zero data past EOF (0x%llx) page offset 0x%x is 0x%04x\n",
580                             s, file_size - 1, should_be_zero & page_mask,
581                             short_at(should_be_zero));
582                         report_failure(205);
583                 }
584 }
585
586
587 void
588 domapread(unsigned offset, unsigned size)
589 {
590         unsigned pg_offset;
591         unsigned map_size;
592         char    *p;
593
594         offset -= offset % readbdy;
595         if (size == 0) {
596                 if (!quiet && testcalls > simulatedopcount)
597                         prt("skipping zero size read\n");
598                 log4(OP_SKIPPED, OP_MAPREAD, offset, size);
599                 return;
600         }
601         if (size + offset > file_size) {
602                 if (!quiet && testcalls > simulatedopcount)
603                         prt("skipping seek/read past end of file\n");
604                 log4(OP_SKIPPED, OP_MAPREAD, offset, size);
605                 return;
606         }
607
608         log4(OP_MAPREAD, offset, size, 0);
609
610         if (testcalls <= simulatedopcount)
611                 return;
612
613         if (!quiet &&
614                 ((progressinterval && testcalls % progressinterval == 0) ||
615                        (debug &&
616                        (monitorstart == -1 ||
617                         (offset + size > monitorstart &&
618                         (monitorend == -1 || offset <= monitorend))))))
619                 prt("%lu mapread\t0x%x thru\t0x%x\t(0x%x bytes)\n", testcalls,
620                     offset, offset + size - 1, size);
621
622         pg_offset = offset & PAGE_MASK;
623         map_size  = pg_offset + size;
624
625         if ((p = (char *)mmap(0, map_size, PROT_READ, MAP_SHARED, fd,
626                               (off_t)(offset - pg_offset))) == (char *)-1) {
627                 prterr("domapread: mmap");
628                 report_failure(190);
629         }
630         memcpy(temp_buf, p + pg_offset, size);
631
632         check_eofpage("Read", offset, p, size);
633
634         if (munmap(p, map_size) != 0) {
635                 prterr("domapread: munmap");
636                 report_failure(191);
637         }
638
639         check_buffers(offset, size);
640 }
641
642
643 void
644 gendata(char *original_buf, char *good_buf, unsigned offset, unsigned size)
645 {
646         while (size--) {
647                 good_buf[offset] = testcalls % 256; 
648                 if (offset % 2)
649                         good_buf[offset] += original_buf[offset];
650                 offset++;
651         }
652 }
653
654
655 void
656 dowrite(unsigned offset, unsigned size)
657 {
658         off_t ret;
659         unsigned iret;
660
661         offset -= offset % writebdy;
662         if (o_direct)
663                 size -= size % writebdy;
664         if (size == 0) {
665                 if (!quiet && testcalls > simulatedopcount && !o_direct)
666                         prt("skipping zero size write\n");
667                 log4(OP_SKIPPED, OP_WRITE, offset, size);
668                 return;
669         }
670
671         log4(OP_WRITE, offset, size, file_size);
672
673         gendata(original_buf, good_buf, offset, size);
674         if (file_size < offset + size) {
675                 if (file_size < offset)
676                         memset(good_buf + file_size, '\0', offset - file_size);
677                 file_size = offset + size;
678                 if (lite) {
679                         warn("Lite file size bug in fsx!");
680                         report_failure(149);
681                 }
682         }
683
684         if (testcalls <= simulatedopcount)
685                 return;
686
687         if (!quiet &&
688                 ((progressinterval && testcalls % progressinterval == 0) ||
689                        (debug &&
690                        (monitorstart == -1 ||
691                         (offset + size > monitorstart &&
692                         (monitorend == -1 || offset <= monitorend))))))
693                 prt("%lu write\t0x%x thru\t0x%x\t(0x%x bytes)\n", testcalls,
694                     offset, offset + size - 1, size);
695         ret = lseek(fd, (off_t)offset, SEEK_SET);
696         if (ret == (off_t)-1) {
697                 prterr("dowrite: lseek");
698                 report_failure(150);
699         }
700         iret = fsxwrite(fd, good_buf + offset, size, offset);
701         if (iret != size) {
702                 if (iret == -1)
703                         prterr("dowrite: write");
704                 else
705                         prt("short write: 0x%x bytes instead of 0x%x\n",
706                             iret, size);
707                 report_failure(151);
708         }
709         if (do_fsync) {
710                 if (fsync(fd)) {
711                         prt("fsync() failed: %s\n", strerror(errno));
712                         report_failure(152);
713                 }
714         }
715         if (flush) {
716                 doflush(offset, size);
717         }
718 }
719
720
721 void
722 domapwrite(unsigned offset, unsigned size)
723 {
724         unsigned pg_offset;
725         unsigned map_size;
726         off_t    cur_filesize;
727         char    *p;
728
729         offset -= offset % writebdy;
730         if (size == 0) {
731                 if (!quiet && testcalls > simulatedopcount)
732                         prt("skipping zero size write\n");
733                 log4(OP_SKIPPED, OP_MAPWRITE, offset, size);
734                 return;
735         }
736         cur_filesize = file_size;
737
738         log4(OP_MAPWRITE, offset, size, 0);
739
740         gendata(original_buf, good_buf, offset, size);
741         if (file_size < offset + size) {
742                 if (file_size < offset)
743                         memset(good_buf + file_size, '\0', offset - file_size);
744                 file_size = offset + size;
745                 if (lite) {
746                         warn("Lite file size bug in fsx!");
747                         report_failure(200);
748                 }
749         }
750
751         if (testcalls <= simulatedopcount)
752                 return;
753
754         if (!quiet &&
755                 ((progressinterval && testcalls % progressinterval == 0) ||
756                        (debug &&
757                        (monitorstart == -1 ||
758                         (offset + size > monitorstart &&
759                         (monitorend == -1 || offset <= monitorend))))))
760                 prt("%lu mapwrite\t0x%x thru\t0x%x\t(0x%x bytes)\n", testcalls,
761                     offset, offset + size - 1, size);
762
763         if (file_size > cur_filesize) {
764                 if (ftruncate(fd, file_size) == -1) {
765                         prterr("domapwrite: ftruncate");
766                         exit(201);
767                 }
768         }
769         pg_offset = offset & PAGE_MASK;
770         map_size  = pg_offset + size;
771
772         if ((p = (char *)mmap(0, map_size, PROT_READ | PROT_WRITE,
773                               MAP_FILE | MAP_SHARED, fd,
774                               (off_t)(offset - pg_offset))) == (char *)-1) {
775                 prterr("domapwrite: mmap");
776                 report_failure(202);
777         }
778         memcpy(p + pg_offset, good_buf + offset, size);
779         if (msync(p, map_size, MS_SYNC) != 0) {
780                 prterr("domapwrite: msync");
781                 report_failure(203);
782         }
783
784         check_eofpage("Write", offset, p, size);
785
786         if (munmap(p, map_size) != 0) {
787                 prterr("domapwrite: munmap");
788                 report_failure(204);
789         }
790 }
791
792
793 void
794 dotruncate(unsigned size)
795 {
796         int oldsize = file_size;
797
798         size -= size % truncbdy;
799         if (size > biggest) {
800                 biggest = size;
801                 if (!quiet && testcalls > simulatedopcount)
802                         prt("truncating to largest ever: 0x%x\n", size);
803         }
804
805         log4(OP_TRUNCATE, size, (unsigned)file_size, 0);
806
807         if (size > file_size)
808                 memset(good_buf + file_size, '\0', size - file_size);
809         file_size = size;
810
811         if (testcalls <= simulatedopcount)
812                 return;
813         
814         if ((progressinterval && testcalls % progressinterval == 0) ||
815             (debug && (monitorstart == -1 || monitorend == -1 ||
816                       size <= monitorend)))
817                 prt("%lu trunc\tfrom 0x%x to 0x%x\n", testcalls, oldsize, size);
818         if (ftruncate(fd, (off_t)size) == -1) {
819                 prt("ftruncate1: %x\n", size);
820                 prterr("dotruncate: ftruncate");
821                 report_failure(160);
822         }
823 }
824
825 #ifdef FALLOC_FL_PUNCH_HOLE
826 void
827 do_punch_hole(unsigned offset, unsigned length)
828 {
829         unsigned end_offset;
830         int max_offset = 0;
831         int max_len = 0;
832         int mode = FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE;
833
834         if (length == 0) {
835                 if (!quiet && testcalls > simulatedopcount)
836                         prt("skipping zero length punch hole\n");
837                         log4(OP_SKIPPED, OP_PUNCH_HOLE, offset, length);
838                 return;
839         }
840
841         if (file_size <= (loff_t)offset) {
842                 if (!quiet && testcalls > simulatedopcount)
843                         prt("skipping hole punch off the end of the file\n");
844                         log4(OP_SKIPPED, OP_PUNCH_HOLE, offset, length);
845                 return;
846         }
847
848         end_offset = offset + length;
849
850         log4(OP_PUNCH_HOLE, offset, length, 0);
851
852         if (testcalls <= simulatedopcount)
853                 return;
854
855         if ((progressinterval && testcalls % progressinterval == 0) ||
856             (debug && (monitorstart == -1 || monitorend == -1 ||
857                       end_offset <= monitorend))) {
858                 prt("%lu punch\tfrom 0x%x to 0x%x, (0x%x bytes)\n", testcalls,
859                         offset, offset+length, length);
860         }
861         if (fallocate(fd, mode, (loff_t)offset, (loff_t)length) == -1) {
862                 prt("%punch hole: %x to %x\n", offset, length);
863                 prterr("do_punch_hole: fallocate");
864                 report_failure(161);
865         }
866
867
868         max_offset = offset < file_size ? offset : file_size;
869         max_len = max_offset + length <= file_size ? length :
870                         file_size - max_offset;
871         memset(good_buf + max_offset, '\0', max_len);
872 }
873
874 #else
875 void
876 do_punch_hole(unsigned offset, unsigned length)
877 {
878         return;
879 }
880 #endif
881
882 #ifdef HAVE_LINUX_FALLOC_H
883 /* fallocate is basically a no-op unless extending, then a lot like a truncate */
884 void
885 do_preallocate(unsigned offset, unsigned length)
886 {
887         unsigned end_offset;
888         int keep_size;
889
890         if (length == 0) {
891                 if (!quiet && testcalls > simulatedopcount)
892                         prt("skipping zero length fallocate\n");
893                 log4(OP_SKIPPED, OP_FALLOCATE, offset, length);
894                 return;
895         }
896
897         keep_size = random() % 2;
898
899         end_offset = keep_size ? 0 : offset + length;
900
901         if (end_offset > biggest) {
902                 biggest = end_offset;
903                 if (!quiet && testcalls > simulatedopcount)
904                         prt("fallocating to largest ever: 0x%x\n", end_offset);
905         }
906
907         /*
908          * last arg matches fallocate string array index in logdump:
909          *      0: allocate past EOF
910          *      1: extending prealloc
911          *      2: interior prealloc
912          */
913         log4(OP_FALLOCATE, offset, length, (end_offset > file_size) ? (keep_size ? 0 : 1) : 2);
914
915         if (end_offset > file_size) {
916                 memset(good_buf + file_size, '\0', end_offset - file_size);
917                 file_size = end_offset;
918         }
919
920         if (testcalls <= simulatedopcount)
921                 return;
922         
923         if ((progressinterval && testcalls % progressinterval == 0) ||
924             (debug && (monitorstart == -1 || monitorend == -1 ||
925                       end_offset <= monitorend)))
926                 prt("%lu falloc\tfrom 0x%x to 0x%x (0x%x bytes)\n", testcalls,
927                                 offset, offset + length, length);
928         if (fallocate(fd, keep_size ? FALLOC_FL_KEEP_SIZE : 0, (loff_t)offset, (loff_t)length) == -1) {
929                 prt("fallocate: %x to %x\n", offset, length);
930                 prterr("do_preallocate: fallocate");
931                 report_failure(161);
932         }
933 }
934 #else
935 void
936 do_preallocate(unsigned offset, unsigned length)
937 {
938         return;
939 }
940 #endif
941
942 void
943 writefileimage()
944 {
945         ssize_t iret;
946
947         if (lseek(fd, (off_t)0, SEEK_SET) == (off_t)-1) {
948                 prterr("writefileimage: lseek");
949                 report_failure(171);
950         }
951         iret = write(fd, good_buf, file_size);
952         if ((off_t)iret != file_size) {
953                 if (iret == -1)
954                         prterr("writefileimage: write");
955                 else
956                         prt("short write: 0x%x bytes instead of 0x%llx\n",
957                             iret, (unsigned long long)file_size);
958                 report_failure(172);
959         }
960         if (lite ? 0 : ftruncate(fd, file_size) == -1) {
961                 prt("ftruncate2: %llx\n", (unsigned long long)file_size);
962                 prterr("writefileimage: ftruncate");
963                 report_failure(173);
964         }
965 }
966
967
968 void
969 docloseopen(void)
970
971         if (testcalls <= simulatedopcount)
972                 return;
973
974         if (debug)
975                 prt("%lu close/open\n", testcalls);
976         if (close(fd)) {
977                 prterr("docloseopen: close");
978                 report_failure(180);
979         }
980         fd = open(fname, O_RDWR|o_direct, 0);
981         if (fd < 0) {
982                 prterr("docloseopen: open");
983                 report_failure(181);
984         }
985 }
986
987 #define TRIM_OFF_LEN(off, len, size)    \
988 do {                                    \
989         if (size)                       \
990                 (off) %= (size);        \
991         else                            \
992                 (off) = 0;              \
993         if ((off) + (len) > (size))     \
994                 (len) = (size) - (off); \
995 } while (0)
996
997 void
998 test(void)
999 {
1000         unsigned long   offset;
1001         unsigned long   size = maxoplen;
1002         unsigned long   rv = random();
1003         unsigned long   op;
1004
1005         if (simulatedopcount > 0 && testcalls == simulatedopcount)
1006                 writefileimage();
1007
1008         testcalls++;
1009
1010         if (closeprob)
1011                 closeopen = (rv >> 3) < (1 << 28) / closeprob;
1012
1013         if (debugstart > 0 && testcalls >= debugstart)
1014                 debug = 1;
1015
1016         if (!quiet && testcalls < simulatedopcount && testcalls % 100000 == 0)
1017                 prt("%lu...\n", testcalls);
1018
1019         offset = random();
1020         if (randomoplen)
1021                 size = random() % (maxoplen + 1);
1022
1023         /* calculate appropriate op to run */
1024         if (lite)
1025                 op = rv % OP_MAX_LITE;
1026         else
1027                 op = rv % OP_MAX_FULL;
1028
1029         switch (op) {
1030         case OP_MAPREAD:
1031                 if (!mapped_reads)
1032                         op = OP_READ;
1033                 break;
1034         case OP_MAPWRITE:
1035                 if (!mapped_writes)
1036                         op = OP_WRITE;
1037                 break;
1038         case OP_FALLOCATE:
1039                 if (!fallocate_calls) {
1040                         log4(OP_SKIPPED, OP_FALLOCATE, offset, size);
1041                         goto out;
1042                 }
1043                 break;
1044         case OP_PUNCH_HOLE:
1045                 if (!punch_hole_calls) {
1046                         log4(OP_SKIPPED, OP_PUNCH_HOLE, offset, size);
1047                         goto out;
1048                 }
1049                 break;
1050         }
1051
1052         switch (op) {
1053         case OP_READ:
1054                 TRIM_OFF_LEN(offset, size, file_size);
1055                 doread(offset, size);
1056                 break;
1057
1058         case OP_WRITE:
1059                 TRIM_OFF_LEN(offset, size, maxfilelen);
1060                 dowrite(offset, size);
1061                 break;
1062
1063         case OP_MAPREAD:
1064                 TRIM_OFF_LEN(offset, size, file_size);
1065                 domapread(offset, size);
1066                 break;
1067
1068         case OP_MAPWRITE:
1069                 TRIM_OFF_LEN(offset, size, maxfilelen);
1070                 domapwrite(offset, size);
1071                 break;
1072
1073         case OP_TRUNCATE:
1074                 if (!style)
1075                         size = random() % maxfilelen;
1076                 dotruncate(size);
1077                 break;
1078
1079         case OP_FALLOCATE:
1080                 TRIM_OFF_LEN(offset, size, maxfilelen);
1081                 do_preallocate(offset, size);
1082                 break;
1083
1084         case OP_PUNCH_HOLE:
1085                 TRIM_OFF_LEN(offset, size, file_size);
1086                 do_punch_hole(offset, size);
1087                 break;
1088         default:
1089                 prterr("test: unknown operation");
1090                 report_failure(42);
1091                 break;
1092         }
1093
1094 out:
1095         if (sizechecks && testcalls > simulatedopcount)
1096                 check_size();
1097         if (closeopen)
1098                 docloseopen();
1099 }
1100
1101
1102 void
1103 cleanup(sig)
1104         int     sig;
1105 {
1106         if (sig)
1107                 prt("signal %d\n", sig);
1108         prt("testcalls = %lu\n", testcalls);
1109         exit(sig);
1110 }
1111
1112
1113 void
1114 usage(void)
1115 {
1116         fprintf(stdout, "usage: %s",
1117                 "fsx [-dnqxAFLOWZ] [-b opnum] [-c Prob] [-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\
1118         -b opnum: beginning operation number (default 1)\n\
1119         -c P: 1 in P chance of file close+open at each op (default infinity)\n\
1120         -d: debug output for all operations\n\
1121         -f flush and invalidate cache after I/O\n\
1122         -l flen: the upper bound on file size (default 262144)\n\
1123         -m startop:endop: monitor (print debug output) specified byte range (default 0:infinity)\n\
1124         -n: no verifications of file size\n\
1125         -o oplen: the upper bound on operation size (default 65536)\n\
1126         -p progressinterval: debug output at specified operation interval\n\
1127         -q: quieter operation\n\
1128         -r readbdy: 4096 would make reads page aligned (default 1)\n\
1129         -s style: 1 gives smaller truncates (default 0)\n\
1130         -t truncbdy: 4096 would make truncates page aligned (default 1)\n\
1131         -w writebdy: 4096 would make writes page aligned (default 1)\n\
1132         -x: preallocate file space before starting, XFS only (default 0)\n\
1133         -y synchronize changes to a file\n"
1134
1135 #ifdef AIO
1136 "       -A: Use the AIO system calls\n"
1137 #endif
1138 "       -D startingop: debug output starting at specified operation\n"
1139 #ifdef HAVE_LINUX_FALLOC_H
1140 "       -F: Do not use fallocate (preallocation) calls\n"
1141 #endif
1142 #ifdef FALLOC_FL_PUNCH_HOLE
1143 "       -H: Do not use punch hole calls\n"
1144 #endif
1145 "       -L: fsxLite - no file creations & no file size changes\n\
1146         -N numops: total # operations to do (default infinity)\n\
1147         -O: use oplen (see -o flag) for every op (default random)\n\
1148         -P: save .fsxlog and .fsxgood files in dirpath (default ./)\n\
1149         -S seed: for random # generator (default 1) 0 gets timestamp\n\
1150         -W: mapped write operations DISabled\n\
1151         -R: read() system calls only (mapped reads disabled)\n\
1152         -Z: O_DIRECT (use -R, -W, -r and -w too)\n\
1153         fname: this filename is REQUIRED (no default)\n");
1154         exit(90);
1155 }
1156
1157
1158 int
1159 getnum(char *s, char **e)
1160 {
1161         int ret;
1162
1163         *e = (char *) 0;
1164         ret = strtol(s, e, 0);
1165         if (*e)
1166                 switch (**e) {
1167                 case 'b':
1168                 case 'B':
1169                         ret *= 512;
1170                         *e = *e + 1;
1171                         break;
1172                 case 'k':
1173                 case 'K':
1174                         ret *= 1024;
1175                         *e = *e + 1;
1176                         break;
1177                 case 'm':
1178                 case 'M':
1179                         ret *= 1024*1024;
1180                         *e = *e + 1;
1181                         break;
1182                 case 'w':
1183                 case 'W':
1184                         ret *= 4;
1185                         *e = *e + 1;
1186                         break;
1187                 }
1188         return (ret);
1189 }
1190
1191 #ifdef AIO
1192
1193 #define QSZ     1024
1194 io_context_t    io_ctx;
1195 struct iocb     iocb;
1196
1197 int aio_setup()
1198 {
1199         int ret;
1200         ret = io_queue_init(QSZ, &io_ctx);
1201         if (ret != 0) {
1202                 fprintf(stderr, "aio_setup: io_queue_init failed: %s\n",
1203                         strerror(ret));
1204                 return(-1);
1205         }
1206         return(0);
1207 }
1208
1209 int
1210 __aio_rw(int rw, int fd, char *buf, unsigned len, unsigned offset)
1211 {
1212         struct io_event event;
1213         static struct timespec ts;
1214         struct iocb *iocbs[] = { &iocb };
1215         int ret;
1216         long res;
1217
1218         if (rw == READ) {
1219                 io_prep_pread(&iocb, fd, buf, len, offset);
1220         } else {
1221                 io_prep_pwrite(&iocb, fd, buf, len, offset);
1222         }
1223
1224         ts.tv_sec = 30;
1225         ts.tv_nsec = 0;
1226         ret = io_submit(io_ctx, 1, iocbs);
1227         if (ret != 1) {
1228                 fprintf(stderr, "errcode=%d\n", ret);
1229                 fprintf(stderr, "aio_rw: io_submit failed: %s\n",
1230                                 strerror(ret));
1231                 goto out_error;
1232         }
1233
1234         ret = io_getevents(io_ctx, 1, 1, &event, &ts);
1235         if (ret != 1) {
1236                 if (ret == 0)
1237                         fprintf(stderr, "aio_rw: no events available\n");
1238                 else {
1239                         fprintf(stderr, "errcode=%d\n", -ret);
1240                         fprintf(stderr, "aio_rw: io_getevents failed: %s\n",
1241                                         strerror(-ret));
1242                 }
1243                 goto out_error;
1244         }
1245         if (len != event.res) {
1246                 /*
1247                  * The b0rked libaio defines event.res as unsigned.
1248                  * However the kernel strucuture has it signed,
1249                  * and it's used to pass negated error value.
1250                  * Till the library is fixed use the temp var.
1251                  */
1252                 res = (long)event.res;
1253                 if (res >= 0)
1254                         fprintf(stderr, "bad io length: %lu instead of %u\n",
1255                                         res, len);
1256                 else {
1257                         fprintf(stderr, "errcode=%ld\n", -res);
1258                         fprintf(stderr, "aio_rw: async io failed: %s\n",
1259                                         strerror(-res));
1260                         ret = res;
1261                         goto out_error;
1262                 }
1263
1264         }
1265         return event.res;
1266
1267 out_error:
1268         /*
1269          * The caller expects error return in traditional libc
1270          * convention, i.e. -1 and the errno set to error.
1271          */
1272         errno = -ret;
1273         return -1;
1274 }
1275
1276 int aio_rw(int rw, int fd, char *buf, unsigned len, unsigned offset)
1277 {
1278         int ret;
1279
1280         if (aio) {
1281                 ret = __aio_rw(rw, fd, buf, len, offset);
1282         } else {
1283                 if (rw == READ)
1284                         ret = read(fd, buf, len);
1285                 else
1286                         ret = write(fd, buf, len);
1287         }
1288         return ret;
1289 }
1290
1291 #endif
1292
1293 void
1294 test_fallocate()
1295 {
1296 #ifdef HAVE_LINUX_FALLOC_H
1297         if (!lite && fallocate_calls) {
1298                 if (fallocate(fd, 0, 0, 1) && errno == EOPNOTSUPP) {
1299                         if(!quiet)
1300                                 warn("main: filesystem does not support fallocate, disabling\n");
1301                         fallocate_calls = 0;
1302                 } else {
1303                         ftruncate(fd, 0);
1304                 }
1305         }
1306 #else /* ! HAVE_LINUX_FALLOC_H */
1307         fallocate_calls = 0;
1308 #endif
1309
1310 }
1311
1312 void
1313 test_punch_hole()
1314 {
1315 #ifdef FALLOC_FL_PUNCH_HOLE
1316         if (!lite && punch_hole_calls) {
1317                 if (fallocate(fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE,
1318                                 0, 1) && errno == EOPNOTSUPP) {
1319                         if(!quiet)
1320                                 warn("main: filesystem does not support fallocate punch hole, disabling");
1321                         punch_hole_calls = 0;
1322                 } else
1323                         ftruncate(fd, 0);
1324         }
1325 #else /* ! PUNCH HOLE */
1326         punch_hole_calls = 0;
1327 #endif
1328 }
1329
1330 int
1331 main(int argc, char **argv)
1332 {
1333         int     i, style, ch;
1334         char    *endp;
1335         char goodfile[1024];
1336         char logfile[1024];
1337
1338         goodfile[0] = 0;
1339         logfile[0] = 0;
1340
1341         page_size = getpagesize();
1342         page_mask = page_size - 1;
1343         mmap_mask = page_mask;
1344         
1345
1346         setvbuf(stdout, (char *)0, _IOLBF, 0); /* line buffered stdout */
1347
1348         while ((ch = getopt(argc, argv, "b:c:dfl:m:no:p:qr:s:t:w:xyAD:FHLN:OP:RS:WZ"))
1349                != EOF)
1350                 switch (ch) {
1351                 case 'b':
1352                         simulatedopcount = getnum(optarg, &endp);
1353                         if (!quiet)
1354                                 fprintf(stdout, "Will begin at operation %ld\n",
1355                                         simulatedopcount);
1356                         if (simulatedopcount == 0)
1357                                 usage();
1358                         simulatedopcount -= 1;
1359                         break;
1360                 case 'c':
1361                         closeprob = getnum(optarg, &endp);
1362                         if (!quiet)
1363                                 fprintf(stdout,
1364                                         "Chance of close/open is 1 in %d\n",
1365                                         closeprob);
1366                         if (closeprob <= 0)
1367                                 usage();
1368                         break;
1369                 case 'd':
1370                         debug = 1;
1371                         break;
1372                 case 'f':
1373                         flush = 1;
1374                         break;
1375                 case 'l':
1376                         maxfilelen = getnum(optarg, &endp);
1377                         if (maxfilelen <= 0)
1378                                 usage();
1379                         break;
1380                 case 'm':
1381                         monitorstart = getnum(optarg, &endp);
1382                         if (monitorstart < 0)
1383                                 usage();
1384                         if (!endp || *endp++ != ':')
1385                                 usage();
1386                         monitorend = getnum(endp, &endp);
1387                         if (monitorend < 0)
1388                                 usage();
1389                         if (monitorend == 0)
1390                                 monitorend = -1; /* aka infinity */
1391                         debug = 1;
1392                 case 'n':
1393                         sizechecks = 0;
1394                         break;
1395                 case 'o':
1396                         maxoplen = getnum(optarg, &endp);
1397                         if (maxoplen <= 0)
1398                                 usage();
1399                         break;
1400                 case 'p':
1401                         progressinterval = getnum(optarg, &endp);
1402                         if (progressinterval == 0)
1403                                 usage();
1404                         break;
1405                 case 'q':
1406                         quiet = 1;
1407                         break;
1408                 case 'r':
1409                         readbdy = getnum(optarg, &endp);
1410                         if (readbdy <= 0)
1411                                 usage();
1412                         break;
1413                 case 's':
1414                         style = getnum(optarg, &endp);
1415                         if (style < 0 || style > 1)
1416                                 usage();
1417                         break;
1418                 case 't':
1419                         truncbdy = getnum(optarg, &endp);
1420                         if (truncbdy <= 0)
1421                                 usage();
1422                         break;
1423                 case 'w':
1424                         writebdy = getnum(optarg, &endp);
1425                         if (writebdy <= 0)
1426                                 usage();
1427                         break;
1428                 case 'x':
1429                         prealloc = 1;
1430                         break;
1431                 case 'y':
1432                         do_fsync = 1;
1433                         break;
1434                 case 'A':
1435                         aio = 1;
1436                         break;
1437                 case 'D':
1438                         debugstart = getnum(optarg, &endp);
1439                         if (debugstart < 1)
1440                                 usage();
1441                         break;
1442                 case 'F':
1443                         fallocate_calls = 0;
1444                         break;
1445                 case 'H':
1446                         punch_hole_calls = 0;
1447                         break;
1448                 case 'L':
1449                         lite = 1;
1450                         break;
1451                 case 'N':
1452                         numops = getnum(optarg, &endp);
1453                         if (numops < 0)
1454                                 usage();
1455                         break;
1456                 case 'O':
1457                         randomoplen = 0;
1458                         break;
1459                 case 'P':
1460                         strncpy(goodfile, optarg, sizeof(goodfile));
1461                         strcat(goodfile, "/");
1462                         strncpy(logfile, optarg, sizeof(logfile));
1463                         strcat(logfile, "/");
1464                         break;
1465                 case 'R':
1466                         mapped_reads = 0;
1467                         break;
1468                 case 'S':
1469                         seed = getnum(optarg, &endp);
1470                         if (seed == 0)
1471                                 seed = time(0) % 10000;
1472                         if (!quiet)
1473                                 fprintf(stdout, "Seed set to %d\n", seed);
1474                         if (seed < 0)
1475                                 usage();
1476                         break;
1477                 case 'W':
1478                         mapped_writes = 0;
1479                         if (!quiet)
1480                                 fprintf(stdout, "mapped writes DISABLED\n");
1481                         break;
1482                 case 'Z':
1483                         o_direct = O_DIRECT;
1484                         break;
1485                 default:
1486                         usage();
1487                         /* NOTREACHED */
1488                 }
1489         argc -= optind;
1490         argv += optind;
1491         if (argc != 1)
1492                 usage();
1493         fname = argv[0];
1494
1495         signal(SIGHUP,  cleanup);
1496         signal(SIGINT,  cleanup);
1497         signal(SIGPIPE, cleanup);
1498         signal(SIGALRM, cleanup);
1499         signal(SIGTERM, cleanup);
1500         signal(SIGXCPU, cleanup);
1501         signal(SIGXFSZ, cleanup);
1502         signal(SIGVTALRM,       cleanup);
1503         signal(SIGUSR1, cleanup);
1504         signal(SIGUSR2, cleanup);
1505
1506         initstate(seed, state, 256);
1507         setstate(state);
1508         fd = open(fname,
1509                 O_RDWR|(lite ? 0 : O_CREAT|O_TRUNC)|o_direct, 0666);
1510         if (fd < 0) {
1511                 prterr(fname);
1512                 exit(91);
1513         }
1514 #ifdef XFS
1515         if (prealloc) {
1516                 xfs_flock64_t   resv = { 0 };
1517 #ifdef HAVE_XFS_PLATFORM_DEFS_H
1518                 if (!platform_test_xfs_fd(fd)) {
1519                         prterr(fname);
1520                         fprintf(stderr, "main: cannot prealloc, non XFS\n");
1521                         exit(96);
1522                 }
1523 #endif
1524                 resv.l_len = maxfilelen;
1525                 if ((xfsctl(fname, fd, XFS_IOC_RESVSP, &resv)) < 0) {
1526                         prterr(fname);
1527                         exit(97);
1528                 }
1529         }
1530 #endif
1531         strncat(goodfile, fname, 256);
1532         strcat (goodfile, ".fsxgood");
1533         fsxgoodfd = open(goodfile, O_RDWR|O_CREAT|O_TRUNC, 0666);
1534         if (fsxgoodfd < 0) {
1535                 prterr(goodfile);
1536                 exit(92);
1537         }
1538         strncat(logfile, fname, 256);
1539         strcat (logfile, ".fsxlog");
1540         fsxlogf = fopen(logfile, "w");
1541         if (fsxlogf == NULL) {
1542                 prterr(logfile);
1543                 exit(93);
1544         }
1545
1546 #ifdef AIO
1547         if (aio) 
1548                 aio_setup();
1549 #endif
1550
1551         if (lite) {
1552                 off_t ret;
1553                 file_size = maxfilelen = lseek(fd, (off_t)0, SEEK_END);
1554                 if (file_size == (off_t)-1) {
1555                         prterr(fname);
1556                         warn("main: lseek eof");
1557                         exit(94);
1558                 }
1559                 ret = lseek(fd, (off_t)0, SEEK_SET);
1560                 if (ret == (off_t)-1) {
1561                         prterr(fname);
1562                         warn("main: lseek 0");
1563                         exit(95);
1564                 }
1565         }
1566         original_buf = (char *) malloc(maxfilelen);
1567         for (i = 0; i < maxfilelen; i++)
1568                 original_buf[i] = random() % 256;
1569         good_buf = (char *) malloc(maxfilelen + writebdy);
1570         good_buf = round_ptr_up(good_buf, writebdy, 0);
1571         memset(good_buf, '\0', maxfilelen);
1572         temp_buf = (char *) malloc(maxoplen + readbdy);
1573         temp_buf = round_ptr_up(temp_buf, readbdy, 0);
1574         memset(temp_buf, '\0', maxoplen);
1575         if (lite) {     /* zero entire existing file */
1576                 ssize_t written;
1577
1578                 written = write(fd, good_buf, (size_t)maxfilelen);
1579                 if (written != maxfilelen) {
1580                         if (written == -1) {
1581                                 prterr(fname);
1582                                 warn("main: error on write");
1583                         } else
1584                                 warn("main: short write, 0x%x bytes instead "
1585                                         "of 0x%lx\n",
1586                                         (unsigned)written,
1587                                         maxfilelen);
1588                         exit(98);
1589                 }
1590         } else 
1591                 check_trunc_hack();
1592
1593         test_fallocate();
1594         test_punch_hole();
1595
1596         while (numops == -1 || numops--)
1597                 test();
1598
1599         if (close(fd)) {
1600                 prterr("close");
1601                 report_failure(99);
1602         }
1603         prt("All operations completed A-OK!\n");
1604
1605         exit(0);
1606         return 0;
1607 }