xfstests: fsx fallocate support is b0rked
[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 <stdlib.h>
29 #include <string.h>
30 #include <stdarg.h>
31 #include <errno.h>
32 #ifdef AIO
33 #include <libaio.h>
34 #endif
35 #ifdef FALLOCATE
36 #include <linux/falloc.h>
37 #endif
38
39 #ifndef MAP_FILE
40 # define MAP_FILE 0
41 #endif
42
43 #define NUMPRINTCOLUMNS 32      /* # columns of data to print on each line */
44
45 /*
46  *      A log entry is an operation and a bunch of arguments.
47  */
48
49 struct log_entry {
50         int     operation;
51         int     args[3];
52 };
53
54 #define LOGSIZE 1000
55
56 struct log_entry        oplog[LOGSIZE]; /* the log */
57 int                     logptr = 0;     /* current position in log */
58 int                     logcount = 0;   /* total ops */
59
60 /*
61  * The operation matrix is complex due to conditional execution of different
62  * features. Hence when we come to deciding what operation to run, we need to
63  * be careful in how we select the different operations. The active operations
64  * are mapped to numbers as follows:
65  *
66  *              lite    !lite
67  * READ:        0       0
68  * WRITE:       1       1
69  * MAPREAD:     2       2
70  * MAPWRITE:    3       3
71  * TRUNCATE:    -       4
72  * FALLOCATE:   -       5
73  * PUNCH HOLE:  -       6
74  *
75  * When mapped read/writes are disabled, they are simply converted to normal
76  * reads and writes. When fallocate/fpunch calls are disabled, they are
77  * converted to OP_SKIPPED. Hence OP_SKIPPED needs to have a number higher than
78  * the operation selction matrix, as does the OP_CLOSEOPEN which is an
79  * operation modifier rather than an operation in itself.
80  *
81  * Because of the "lite" version, we also need to have different "maximum
82  * operation" defines to allow the ops to be selected correctly based on the
83  * mode being run.
84  */
85
86 /* common operations */
87 #define OP_READ         0
88 #define OP_WRITE        1
89 #define OP_MAPREAD      2
90 #define OP_MAPWRITE     3
91 #define OP_MAX_LITE     4
92
93 /* !lite operations */
94 #define OP_TRUNCATE     4
95 #define OP_FALLOCATE    5
96 #define OP_PUNCH_HOLE   6
97 #define OP_MAX_FULL     7
98
99 /* operation modifiers */
100 #define OP_CLOSEOPEN    100
101 #define OP_SKIPPED      101
102
103 #undef PAGE_SIZE
104 #define PAGE_SIZE       getpagesize()
105 #undef PAGE_MASK
106 #define PAGE_MASK       (PAGE_SIZE - 1)
107
108 char    *original_buf;                  /* a pointer to the original data */
109 char    *good_buf;                      /* a pointer to the correct data */
110 char    *temp_buf;                      /* a pointer to the current data */
111 char    *fname;                         /* name of our test file */
112 int     fd;                             /* fd for our test file */
113
114 off_t           file_size = 0;
115 off_t           biggest = 0;
116 char            state[256];
117 unsigned long   testcalls = 0;          /* calls to function "test" */
118
119 unsigned long   simulatedopcount = 0;   /* -b flag */
120 int     closeprob = 0;                  /* -c flag */
121 int     debug = 0;                      /* -d flag */
122 unsigned long   debugstart = 0;         /* -D flag */
123 int     flush = 0;                      /* -f flag */
124 int     do_fsync = 0;                   /* -y flag */
125 unsigned long   maxfilelen = 256 * 1024;        /* -l flag */
126 int     sizechecks = 1;                 /* -n flag disables them */
127 int     maxoplen = 64 * 1024;           /* -o flag */
128 int     quiet = 0;                      /* -q flag */
129 unsigned long progressinterval = 0;     /* -p flag */
130 int     readbdy = 1;                    /* -r flag */
131 int     style = 0;                      /* -s flag */
132 int     prealloc = 0;                   /* -x flag */
133 int     truncbdy = 1;                   /* -t flag */
134 int     writebdy = 1;                   /* -w flag */
135 long    monitorstart = -1;              /* -m flag */
136 long    monitorend = -1;                /* -m flag */
137 int     lite = 0;                       /* -L flag */
138 long    numops = -1;                    /* -N flag */
139 int     randomoplen = 1;                /* -O flag disables it */
140 int     seed = 1;                       /* -S flag */
141 int     mapped_writes = 1;              /* -W flag disables */
142 int     fallocate_calls = 1;            /* -F flag disables */
143 int     punch_hole_calls = 1;           /* -H flag disables */
144 int     mapped_reads = 1;               /* -R flag disables it */
145 int     fsxgoodfd = 0;
146 int     o_direct;                       /* -Z */
147 int     aio = 0;
148
149 int page_size;
150 int page_mask;
151 int mmap_mask;
152 #ifdef AIO
153 int aio_rw(int rw, int fd, char *buf, unsigned len, unsigned offset);
154 #define READ 0
155 #define WRITE 1
156 #define fsxread(a,b,c,d)        aio_rw(READ, a,b,c,d)
157 #define fsxwrite(a,b,c,d)       aio_rw(WRITE, a,b,c,d)
158 #else
159 #define fsxread(a,b,c,d)        read(a,b,c)
160 #define fsxwrite(a,b,c,d)       write(a,b,c)
161 #endif
162
163 FILE *  fsxlogf = NULL;
164 int badoff = -1;
165 int closeopen = 0;
166
167 static void *round_up(void *ptr, unsigned long align, unsigned long offset)
168 {
169         unsigned long ret = (unsigned long)ptr;
170
171         ret = ((ret + align - 1) & ~(align - 1));
172         ret += offset;
173         return (void *)ret;
174 }
175
176 void
177 vwarnc(int code, const char *fmt, va_list ap) {
178   fprintf(stderr, "fsx: ");
179   if (fmt != NULL) {
180         vfprintf(stderr, fmt, ap);
181         fprintf(stderr, ": ");
182   }
183   fprintf(stderr, "%s\n", strerror(code));
184 }
185
186 void
187 warn(const char * fmt, ...)  {
188         va_list ap;
189         va_start(ap, fmt);
190         vwarnc(errno, fmt, ap);
191         va_end(ap);
192 }
193
194 #define BUF_SIZE 1024
195
196 void
197 prt(char *fmt, ...)
198 {
199         va_list args;
200         char buffer[BUF_SIZE];
201
202         va_start(args, fmt);
203         vsnprintf(buffer, BUF_SIZE, fmt, args);
204         va_end(args);
205         fprintf(stdout, buffer);
206         if (fsxlogf)
207                 fprintf(fsxlogf, buffer);
208 }
209
210 void
211 prterr(char *prefix)
212 {
213         prt("%s%s%s\n", prefix, prefix ? ": " : "", strerror(errno));
214 }
215
216
217 void
218 log4(int operation, int arg0, int arg1, int arg2)
219 {
220         struct log_entry *le;
221
222         le = &oplog[logptr];
223         le->operation = operation;
224         if (closeopen)
225                 le->operation = ~ le->operation;
226         le->args[0] = arg0;
227         le->args[1] = arg1;
228         le->args[2] = arg2;
229         logptr++;
230         logcount++;
231         if (logptr >= LOGSIZE)
232                 logptr = 0;
233 }
234
235
236 void
237 logdump(void)
238 {
239         int     i, count, down;
240         struct log_entry        *lp;
241         char *falloc_type[3] = {"PAST_EOF", "EXTENDING", "INTERIOR"};
242
243         prt("LOG DUMP (%d total operations):\n", logcount);
244         if (logcount < LOGSIZE) {
245                 i = 0;
246                 count = logcount;
247         } else {
248                 i = logptr;
249                 count = LOGSIZE;
250         }
251         for ( ; count > 0; count--) {
252                 int opnum;
253
254                 opnum = i+1 + (logcount/LOGSIZE)*LOGSIZE;
255                 prt("%d(%d mod 256): ", opnum, opnum%256);
256                 lp = &oplog[i];
257                 if ((closeopen = lp->operation < 0))
258                         lp->operation = ~ lp->operation;
259                         
260                 switch (lp->operation) {
261                 case OP_MAPREAD:
262                         prt("MAPREAD\t0x%x thru 0x%x\t(0x%x bytes)",
263                             lp->args[0], lp->args[0] + lp->args[1] - 1,
264                             lp->args[1]);
265                         if (badoff >= lp->args[0] && badoff <
266                                                      lp->args[0] + lp->args[1])
267                                 prt("\t***RRRR***");
268                         break;
269                 case OP_MAPWRITE:
270                         prt("MAPWRITE 0x%x thru 0x%x\t(0x%x bytes)",
271                             lp->args[0], lp->args[0] + lp->args[1] - 1,
272                             lp->args[1]);
273                         if (badoff >= lp->args[0] && badoff <
274                                                      lp->args[0] + lp->args[1])
275                                 prt("\t******WWWW");
276                         break;
277                 case OP_READ:
278                         prt("READ\t0x%x thru 0x%x\t(0x%x bytes)",
279                             lp->args[0], lp->args[0] + lp->args[1] - 1,
280                             lp->args[1]);
281                         if (badoff >= lp->args[0] &&
282                             badoff < lp->args[0] + lp->args[1])
283                                 prt("\t***RRRR***");
284                         break;
285                 case OP_WRITE:
286                         prt("WRITE\t0x%x thru 0x%x\t(0x%x bytes)",
287                             lp->args[0], lp->args[0] + lp->args[1] - 1,
288                             lp->args[1]);
289                         if (lp->args[0] > lp->args[2])
290                                 prt(" HOLE");
291                         else if (lp->args[0] + lp->args[1] > lp->args[2])
292                                 prt(" EXTEND");
293                         if ((badoff >= lp->args[0] || badoff >=lp->args[2]) &&
294                             badoff < lp->args[0] + lp->args[1])
295                                 prt("\t***WWWW");
296                         break;
297                 case OP_TRUNCATE:
298                         down = lp->args[0] < lp->args[1];
299                         prt("TRUNCATE %s\tfrom 0x%x to 0x%x",
300                             down ? "DOWN" : "UP", lp->args[1], lp->args[0]);
301                         if (badoff >= lp->args[!down] &&
302                             badoff < lp->args[!!down])
303                                 prt("\t******WWWW");
304                         break;
305                 case OP_FALLOCATE:
306                         /* 0: offset 1: length 2: where alloced */
307                         prt("FALLOCATE %s\tfrom 0x%x to 0x%x",
308                             falloc_type[lp->args[2]], lp->args[0], lp->args[0] + lp->args[1]);
309                         if (badoff >= lp->args[0] &&
310                             badoff < lp->args[0] + lp->args[1])
311                                 prt("\t******FFFF");
312                         break;
313                 case OP_PUNCH_HOLE:
314                         prt("PUNCH HOLE\t0x%x thru 0x%x\t(0x%x bytes)",
315                             lp->args[0], lp->args[0] + lp->args[1] - 1,
316                             lp->args[1]);
317                         if (badoff >= lp->args[0] && badoff <
318                                                      lp->args[0] + lp->args[1])
319                                 prt("\t******PPPP");
320                         break;
321                 case OP_SKIPPED:
322                         prt("SKIPPED (no operation)");
323                         break;
324                 default:
325                         prt("BOGUS LOG ENTRY (operation code = %d)!",
326                             lp->operation);
327                 }
328                 if (closeopen)
329                         prt("\n\t\tCLOSE/OPEN");
330                 prt("\n");
331                 i++;
332                 if (i == LOGSIZE)
333                         i = 0;
334         }
335 }
336
337
338 void
339 save_buffer(char *buffer, off_t bufferlength, int fd)
340 {
341         off_t ret;
342         ssize_t byteswritten;
343
344         if (fd <= 0 || bufferlength == 0)
345                 return;
346
347         if (bufferlength > SSIZE_MAX) {
348                 prt("fsx flaw: overflow in save_buffer\n");
349                 exit(67);
350         }
351         if (lite) {
352                 off_t size_by_seek = lseek(fd, (off_t)0, SEEK_END);
353                 if (size_by_seek == (off_t)-1)
354                         prterr("save_buffer: lseek eof");
355                 else if (bufferlength > size_by_seek) {
356                         warn("save_buffer: .fsxgood file too short... will save 0x%llx bytes instead of 0x%llx\n", (unsigned long long)size_by_seek,
357                              (unsigned long long)bufferlength);
358                         bufferlength = size_by_seek;
359                 }
360         }
361
362         ret = lseek(fd, (off_t)0, SEEK_SET);
363         if (ret == (off_t)-1)
364                 prterr("save_buffer: lseek 0");
365         
366         byteswritten = write(fd, buffer, (size_t)bufferlength);
367         if (byteswritten != bufferlength) {
368                 if (byteswritten == -1)
369                         prterr("save_buffer write");
370                 else
371                         warn("save_buffer: short write, 0x%x bytes instead of 0x%llx\n",
372                              (unsigned)byteswritten,
373                              (unsigned long long)bufferlength);
374         }
375 }
376
377
378 void
379 report_failure(int status)
380 {
381         logdump();
382         
383         if (fsxgoodfd) {
384                 if (good_buf) {
385                         save_buffer(good_buf, file_size, fsxgoodfd);
386                         prt("Correct content saved for comparison\n");
387                         prt("(maybe hexdump \"%s\" vs \"%s.fsxgood\")\n",
388                             fname, fname);
389                 }
390                 close(fsxgoodfd);
391         }
392         exit(status);
393 }
394
395
396 #define short_at(cp) ((unsigned short)((*((unsigned char *)(cp)) << 8) | \
397                                         *(((unsigned char *)(cp)) + 1)))
398
399 void
400 check_buffers(unsigned offset, unsigned size)
401 {
402         unsigned char c, t;
403         unsigned i = 0;
404         unsigned n = 0;
405         unsigned op = 0;
406         unsigned bad = 0;
407
408         if (memcmp(good_buf + offset, temp_buf, size) != 0) {
409                 prt("READ BAD DATA: offset = 0x%x, size = 0x%x, fname = %s\n",
410                     offset, size, fname);
411                 prt("OFFSET\tGOOD\tBAD\tRANGE\n");
412                 while (size > 0) {
413                         c = good_buf[offset];
414                         t = temp_buf[i];
415                         if (c != t) {
416                                 if (n < 16) {
417                                         bad = short_at(&temp_buf[i]);
418                                         prt("0x%5x\t0x%04x\t0x%04x", offset,
419                                             short_at(&good_buf[offset]), bad);
420                                         op = temp_buf[offset & 1 ? i+1 : i];
421                                         prt("\t0x%5x\n", n);
422                                         if (op)
423                                                 prt("operation# (mod 256) for "
424                                                   "the bad data may be %u\n",
425                                                 ((unsigned)op & 0xff));
426                                         else
427                                                 prt("operation# (mod 256) for "
428                                                   "the bad data unknown, check"
429                                                   " HOLE and EXTEND ops\n");
430                                 }
431                                 n++;
432                                 badoff = offset;
433                         }
434                         offset++;
435                         i++;
436                         size--;
437                 }
438                 report_failure(110);
439         }
440 }
441
442
443 void
444 check_size(void)
445 {
446         struct stat     statbuf;
447         off_t   size_by_seek;
448
449         if (fstat(fd, &statbuf)) {
450                 prterr("check_size: fstat");
451                 statbuf.st_size = -1;
452         }
453         size_by_seek = lseek(fd, (off_t)0, SEEK_END);
454         if (file_size != statbuf.st_size || file_size != size_by_seek) {
455                 prt("Size error: expected 0x%llx stat 0x%llx seek 0x%llx\n",
456                     (unsigned long long)file_size,
457                     (unsigned long long)statbuf.st_size,
458                     (unsigned long long)size_by_seek);
459                 report_failure(120);
460         }
461 }
462
463
464 void
465 check_trunc_hack(void)
466 {
467         struct stat statbuf;
468
469         ftruncate(fd, (off_t)0);
470         ftruncate(fd, (off_t)100000);
471         fstat(fd, &statbuf);
472         if (statbuf.st_size != (off_t)100000) {
473                 prt("no extend on truncate! not posix!\n");
474                 exit(130);
475         }
476         ftruncate(fd, 0);
477 }
478
479 void
480 doflush(unsigned offset, unsigned size)
481 {
482         unsigned pg_offset;
483         unsigned map_size;
484         char    *p;
485
486         if (o_direct == O_DIRECT)
487                 return;
488
489         pg_offset = offset & mmap_mask;
490         map_size  = pg_offset + size;
491
492         if ((p = (char *)mmap(0, map_size, PROT_READ | PROT_WRITE,
493                               MAP_FILE | MAP_SHARED, fd,
494                               (off_t)(offset - pg_offset))) == (char *)-1) {
495                 prterr("doflush: mmap");
496                 report_failure(202);
497         }
498         if (msync(p, map_size, MS_INVALIDATE) != 0) {
499                 prterr("doflush: msync");
500                 report_failure(203);
501         }
502         if (munmap(p, map_size) != 0) {
503                 prterr("doflush: munmap");
504                 report_failure(204);
505         }
506 }
507
508 void
509 doread(unsigned offset, unsigned size)
510 {
511         off_t ret;
512         unsigned iret;
513
514         offset -= offset % readbdy;
515         if (o_direct)
516                 size -= size % readbdy;
517         if (size == 0) {
518                 if (!quiet && testcalls > simulatedopcount && !o_direct)
519                         prt("skipping zero size read\n");
520                 log4(OP_SKIPPED, OP_READ, offset, size);
521                 return;
522         }
523         if (size + offset > file_size) {
524                 if (!quiet && testcalls > simulatedopcount)
525                         prt("skipping seek/read past end of file\n");
526                 log4(OP_SKIPPED, OP_READ, offset, size);
527                 return;
528         }
529
530         log4(OP_READ, offset, size, 0);
531
532         if (testcalls <= simulatedopcount)
533                 return;
534
535         if (!quiet &&
536                 ((progressinterval && testcalls % progressinterval == 0)  ||
537                 (debug &&
538                        (monitorstart == -1 ||
539                         (offset + size > monitorstart &&
540                         (monitorend == -1 || offset <= monitorend))))))
541                 prt("%lu read\t0x%x thru\t0x%x\t(0x%x bytes)\n", testcalls,
542                     offset, offset + size - 1, size);
543         ret = lseek(fd, (off_t)offset, SEEK_SET);
544         if (ret == (off_t)-1) {
545                 prterr("doread: lseek");
546                 report_failure(140);
547         }
548         iret = fsxread(fd, temp_buf, size, offset);
549         if (iret != size) {
550                 if (iret == -1)
551                         prterr("doread: read");
552                 else
553                         prt("short read: 0x%x bytes instead of 0x%x\n",
554                             iret, size);
555                 report_failure(141);
556         }
557         check_buffers(offset, size);
558 }
559
560
561 void
562 check_eofpage(char *s, unsigned offset, char *p, int size)
563 {
564         unsigned long last_page, should_be_zero;
565
566         if (offset + size <= (file_size & ~page_mask))
567                 return;
568         /*
569          * we landed in the last page of the file
570          * test to make sure the VM system provided 0's 
571          * beyond the true end of the file mapping
572          * (as required by mmap def in 1996 posix 1003.1)
573          */
574         last_page = ((unsigned long)p + (offset & page_mask) + size) & ~page_mask;
575
576         for (should_be_zero = last_page + (file_size & page_mask);
577              should_be_zero < last_page + page_size;
578              should_be_zero++)
579                 if (*(char *)should_be_zero) {
580                         prt("Mapped %s: non-zero data past EOF (0x%llx) page offset 0x%x is 0x%04x\n",
581                             s, file_size - 1, should_be_zero & page_mask,
582                             short_at(should_be_zero));
583                         report_failure(205);
584                 }
585 }
586
587
588 void
589 domapread(unsigned offset, unsigned size)
590 {
591         unsigned pg_offset;
592         unsigned map_size;
593         char    *p;
594
595         offset -= offset % readbdy;
596         if (size == 0) {
597                 if (!quiet && testcalls > simulatedopcount)
598                         prt("skipping zero size read\n");
599                 log4(OP_SKIPPED, OP_MAPREAD, offset, size);
600                 return;
601         }
602         if (size + offset > file_size) {
603                 if (!quiet && testcalls > simulatedopcount)
604                         prt("skipping seek/read past end of file\n");
605                 log4(OP_SKIPPED, OP_MAPREAD, offset, size);
606                 return;
607         }
608
609         log4(OP_MAPREAD, offset, size, 0);
610
611         if (testcalls <= simulatedopcount)
612                 return;
613
614         if (!quiet &&
615                 ((progressinterval && testcalls % progressinterval == 0) ||
616                        (debug &&
617                        (monitorstart == -1 ||
618                         (offset + size > monitorstart &&
619                         (monitorend == -1 || offset <= monitorend))))))
620                 prt("%lu mapread\t0x%x thru\t0x%x\t(0x%x bytes)\n", testcalls,
621                     offset, offset + size - 1, size);
622
623         pg_offset = offset & PAGE_MASK;
624         map_size  = pg_offset + size;
625
626         if ((p = (char *)mmap(0, map_size, PROT_READ, MAP_SHARED, fd,
627                               (off_t)(offset - pg_offset))) == (char *)-1) {
628                 prterr("domapread: mmap");
629                 report_failure(190);
630         }
631         memcpy(temp_buf, p + pg_offset, size);
632
633         check_eofpage("Read", offset, p, size);
634
635         if (munmap(p, map_size) != 0) {
636                 prterr("domapread: munmap");
637                 report_failure(191);
638         }
639
640         check_buffers(offset, size);
641 }
642
643
644 void
645 gendata(char *original_buf, char *good_buf, unsigned offset, unsigned size)
646 {
647         while (size--) {
648                 good_buf[offset] = testcalls % 256; 
649                 if (offset % 2)
650                         good_buf[offset] += original_buf[offset];
651                 offset++;
652         }
653 }
654
655
656 void
657 dowrite(unsigned offset, unsigned size)
658 {
659         off_t ret;
660         unsigned iret;
661
662         offset -= offset % writebdy;
663         if (o_direct)
664                 size -= size % writebdy;
665         if (size == 0) {
666                 if (!quiet && testcalls > simulatedopcount && !o_direct)
667                         prt("skipping zero size write\n");
668                 log4(OP_SKIPPED, OP_WRITE, offset, size);
669                 return;
670         }
671
672         log4(OP_WRITE, offset, size, file_size);
673
674         gendata(original_buf, good_buf, offset, size);
675         if (file_size < offset + size) {
676                 if (file_size < offset)
677                         memset(good_buf + file_size, '\0', offset - file_size);
678                 file_size = offset + size;
679                 if (lite) {
680                         warn("Lite file size bug in fsx!");
681                         report_failure(149);
682                 }
683         }
684
685         if (testcalls <= simulatedopcount)
686                 return;
687
688         if (!quiet &&
689                 ((progressinterval && testcalls % progressinterval == 0) ||
690                        (debug &&
691                        (monitorstart == -1 ||
692                         (offset + size > monitorstart &&
693                         (monitorend == -1 || offset <= monitorend))))))
694                 prt("%lu write\t0x%x thru\t0x%x\t(0x%x bytes)\n", testcalls,
695                     offset, offset + size - 1, size);
696         ret = lseek(fd, (off_t)offset, SEEK_SET);
697         if (ret == (off_t)-1) {
698                 prterr("dowrite: lseek");
699                 report_failure(150);
700         }
701         iret = fsxwrite(fd, good_buf + offset, size, offset);
702         if (iret != size) {
703                 if (iret == -1)
704                         prterr("dowrite: write");
705                 else
706                         prt("short write: 0x%x bytes instead of 0x%x\n",
707                             iret, size);
708                 report_failure(151);
709         }
710         if (do_fsync) {
711                 if (fsync(fd)) {
712                         prt("fsync() failed: %s\n", strerror(errno));
713                         report_failure(152);
714                 }
715         }
716         if (flush) {
717                 doflush(offset, size);
718         }
719 }
720
721
722 void
723 domapwrite(unsigned offset, unsigned size)
724 {
725         unsigned pg_offset;
726         unsigned map_size;
727         off_t    cur_filesize;
728         char    *p;
729
730         offset -= offset % writebdy;
731         if (size == 0) {
732                 if (!quiet && testcalls > simulatedopcount)
733                         prt("skipping zero size write\n");
734                 log4(OP_SKIPPED, OP_MAPWRITE, offset, size);
735                 return;
736         }
737         cur_filesize = file_size;
738
739         log4(OP_MAPWRITE, offset, size, 0);
740
741         gendata(original_buf, good_buf, offset, size);
742         if (file_size < offset + size) {
743                 if (file_size < offset)
744                         memset(good_buf + file_size, '\0', offset - file_size);
745                 file_size = offset + size;
746                 if (lite) {
747                         warn("Lite file size bug in fsx!");
748                         report_failure(200);
749                 }
750         }
751
752         if (testcalls <= simulatedopcount)
753                 return;
754
755         if (!quiet &&
756                 ((progressinterval && testcalls % progressinterval == 0) ||
757                        (debug &&
758                        (monitorstart == -1 ||
759                         (offset + size > monitorstart &&
760                         (monitorend == -1 || offset <= monitorend))))))
761                 prt("%lu mapwrite\t0x%x thru\t0x%x\t(0x%x bytes)\n", testcalls,
762                     offset, offset + size - 1, size);
763
764         if (file_size > cur_filesize) {
765                 if (ftruncate(fd, file_size) == -1) {
766                         prterr("domapwrite: ftruncate");
767                         exit(201);
768                 }
769         }
770         pg_offset = offset & PAGE_MASK;
771         map_size  = pg_offset + size;
772
773         if ((p = (char *)mmap(0, map_size, PROT_READ | PROT_WRITE,
774                               MAP_FILE | MAP_SHARED, fd,
775                               (off_t)(offset - pg_offset))) == (char *)-1) {
776                 prterr("domapwrite: mmap");
777                 report_failure(202);
778         }
779         memcpy(p + pg_offset, good_buf + offset, size);
780         if (msync(p, map_size, 0) != 0) {
781                 prterr("domapwrite: msync");
782                 report_failure(203);
783         }
784
785         check_eofpage("Write", offset, p, size);
786
787         if (munmap(p, map_size) != 0) {
788                 prterr("domapwrite: munmap");
789                 report_failure(204);
790         }
791 }
792
793
794 void
795 dotruncate(unsigned size)
796 {
797         int oldsize = file_size;
798
799         size -= size % truncbdy;
800         if (size > biggest) {
801                 biggest = size;
802                 if (!quiet && testcalls > simulatedopcount)
803                         prt("truncating to largest ever: 0x%x\n", size);
804         }
805
806         log4(OP_TRUNCATE, size, (unsigned)file_size, 0);
807
808         if (size > file_size)
809                 memset(good_buf + file_size, '\0', size - file_size);
810         file_size = size;
811
812         if (testcalls <= simulatedopcount)
813                 return;
814         
815         if ((progressinterval && testcalls % progressinterval == 0) ||
816             (debug && (monitorstart == -1 || monitorend == -1 ||
817                       size <= monitorend)))
818                 prt("%lu trunc\tfrom 0x%x to 0x%x\n", testcalls, oldsize, size);
819         if (ftruncate(fd, (off_t)size) == -1) {
820                 prt("ftruncate1: %x\n", size);
821                 prterr("dotruncate: ftruncate");
822                 report_failure(160);
823         }
824 }
825
826 #ifdef FALLOC_FL_PUNCH_HOLE
827 void
828 do_punch_hole(unsigned offset, unsigned length)
829 {
830         unsigned end_offset;
831         int max_offset = 0;
832         int max_len = 0;
833         int mode = FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE;
834
835         if (length == 0) {
836                 if (!quiet && testcalls > simulatedopcount)
837                         prt("skipping zero length punch hole\n");
838                         log4(OP_SKIPPED, OP_PUNCH_HOLE, offset, length);
839                 return;
840         }
841
842         if (file_size <= (loff_t)offset) {
843                 if (!quiet && testcalls > simulatedopcount)
844                         prt("skipping hole punch off the end of the file\n");
845                         log4(OP_SKIPPED, OP_PUNCH_HOLE, offset, length);
846                 return;
847         }
848
849         end_offset = offset + length;
850
851         log4(OP_PUNCH_HOLE, offset, length, 0);
852
853         if (testcalls <= simulatedopcount)
854                 return;
855
856         if ((progressinterval && testcalls % progressinterval == 0) ||
857             (debug && (monitorstart == -1 || monitorend == -1 ||
858                       end_offset <= monitorend))) {
859                 prt("%lu punch\tfrom 0x%x to 0x%x, (0x%x bytes)\n", testcalls,
860                         offset, offset+length, length);
861         }
862         if (fallocate(fd, mode, (loff_t)offset, (loff_t)length) == -1) {
863                 prt("%punch hole: %x to %x\n", offset, length);
864                 prterr("do_punch_hole: fallocate");
865                 report_failure(161);
866         }
867
868
869         max_offset = offset < file_size ? offset : file_size;
870         max_len = max_offset + length <= file_size ? length :
871                         file_size - max_offset;
872         memset(good_buf + max_offset, '\0', max_len);
873 }
874
875 #else
876 void
877 do_punch_hole(unsigned offset, unsigned length)
878 {
879         return;
880 }
881 #endif
882
883 #ifdef FALLOCATE
884 /* fallocate is basically a no-op unless extending, then a lot like a truncate */
885 void
886 do_preallocate(unsigned offset, unsigned length)
887 {
888         unsigned end_offset;
889         int keep_size;
890
891         if (length == 0) {
892                 if (!quiet && testcalls > simulatedopcount)
893                         prt("skipping zero length fallocate\n");
894                 log4(OP_SKIPPED, OP_FALLOCATE, offset, length);
895                 return;
896         }
897
898         keep_size = random() % 2;
899
900         end_offset = keep_size ? 0 : offset + length;
901
902         if (end_offset > biggest) {
903                 biggest = end_offset;
904                 if (!quiet && testcalls > simulatedopcount)
905                         prt("fallocating to largest ever: 0x%x\n", end_offset);
906         }
907
908         /*
909          * last arg:
910          *      1: allocate past EOF
911          *      2: extending prealloc
912          *      3: interior prealloc
913          */
914         log4(OP_FALLOCATE, offset, length, (end_offset > file_size) ? (keep_size ? 1 : 2) : 3);
915
916         if (end_offset > file_size) {
917                 memset(good_buf + file_size, '\0', end_offset - file_size);
918                 file_size = end_offset;
919         }
920
921         if (testcalls <= simulatedopcount)
922                 return;
923         
924         if ((progressinterval && testcalls % progressinterval == 0) ||
925             (debug && (monitorstart == -1 || monitorend == -1 ||
926                       end_offset <= monitorend)))
927                 prt("%lu falloc\tfrom 0x%x to 0x%x\n", testcalls, offset, 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, zero_offset)       \
988 do {                                    \
989         if (!zero_offset || file_size)  \
990                 offset %= size;         \
991         else                            \
992                 offset = 0;             \
993         if (offset + len > size)        \
994                 len = size - offset;    \
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, false);
1055                 doread(offset, size);
1056                 break;
1057
1058         case OP_WRITE:
1059                 TRIM_OFF_LEN(offset, size, maxfilelen, true);
1060                 dowrite(offset, size);
1061                 break;
1062
1063         case OP_MAPREAD:
1064                 TRIM_OFF_LEN(offset, size, file_size, false);
1065                 domapread(offset, size);
1066                 break;
1067
1068         case OP_MAPWRITE:
1069                 TRIM_OFF_LEN(offset, size, maxfilelen, true);
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, true);
1081                 do_preallocate(offset, size);
1082                 break;
1083
1084         case OP_PUNCH_HOLE:
1085                 TRIM_OFF_LEN(offset, size, maxfilelen, true);
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 FALLOCATE
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 FALLOCATE
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 /* ! FALLOCATE */
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_up(good_buf, writebdy, 0);
1571         memset(good_buf, '\0', maxfilelen);
1572         temp_buf = (char *) malloc(maxoplen + readbdy);
1573         temp_buf = round_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 }