c9c8dba8285a7b8a45f1a5a664336308d578e895
[dragonfly.git] / test / stress / fsx / fsx.c
1 /*
2  * Copyright (c) 1998-2001 Apple Computer, Inc. All rights reserved.
3  *
4  * @APPLE_LICENSE_HEADER_START@
5  *
6  * The contents of this file constitute Original Code as defined in and
7  * are subject to the Apple Public Source License Version 1.2 (the
8  * "License").  You may not use this file except in compliance with the
9  * License.  Please obtain a copy of the License at
10  * http://www.apple.com/publicsource and read it before using this file.
11  *
12  * This Original Code and all software distributed under the License are
13  * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER
14  * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
15  * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
16  * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT.  Please see the
17  * License for the specific language governing rights and limitations
18  * under the License.
19  *
20  * @APPLE_LICENSE_HEADER_END@
21  *
22  *      File:   fsx.c
23  *      Author: Avadis Tevanian, Jr.
24  *
25  *      File system exerciser. 
26  *
27  *      Rewrite and enhancements 1998-2001 Conrad Minshall -- conrad@mac.com
28  *
29  *      Various features from Joe Sokol, Pat Dirks, and Clark Warner.
30  *
31  *      Small changes to work under Linux -- davej@suse.de
32  *
33  *      Sundry porting patches from Guy Harris 12/2001
34  *
35  *      Checks for mmap last-page zero fill.
36  *
37  * $FreeBSD: src/tools/regression/fsx/fsx.c,v 1.2 2003/04/23 23:42:23 jkh Exp $
38  * $DragonFly: src/test/stress/fsx/fsx.c,v 1.2 2005/05/02 19:31:56 dillon Exp $
39  *
40  */
41
42 #include <sys/types.h>
43 #include <sys/stat.h>
44 #ifdef _UWIN
45 # include <sys/param.h>
46 # include <limits.h>
47 # include <time.h>
48 # include <strings.h>
49 #endif
50 #include <fcntl.h>
51 #include <sys/mman.h>
52 #ifndef MAP_FILE
53 # define MAP_FILE 0
54 #endif
55 #include <limits.h>
56 #include <signal.h>
57 #include <stdio.h>
58 #include <stdlib.h>
59 #include <string.h>
60 #include <unistd.h>
61 #include <stdarg.h>
62 #include <errno.h>
63 #include <setjmp.h>
64
65 #define NUMPRINTCOLUMNS 32      /* # columns of data to print on each line */
66
67 /*
68  *      A log entry is an operation and a bunch of arguments.
69  */
70
71 struct log_entry {
72         int     operation;
73         int     args[3];
74 };
75
76 #define LOGSIZE 1000
77
78 struct log_entry        oplog[LOGSIZE]; /* the log */
79 int                     logptr = 0;     /* current position in log */
80 int                     logcount = 0;   /* total ops */
81 int                     jmpbuf_good;
82 jmp_buf                 jmpbuf;
83
84 /*
85  *      Define operations
86  */
87
88 #define OP_READ         1
89 #define OP_WRITE        2
90 #define OP_TRUNCATE     3
91 #define OP_CLOSEOPEN    4
92 #define OP_MAPREAD      5
93 #define OP_MAPWRITE     6
94 #define OP_SKIPPED      7
95
96 int page_size;
97 int page_mask;
98
99 char    *original_buf;                  /* a pointer to the original data */
100 char    *good_buf;                      /* a pointer to the correct data */
101 char    *temp_buf;                      /* a pointer to the current data */
102 char    *fname;                         /* name of our test file */
103 int     fd;                             /* fd for our test file */
104
105 off_t           file_size = 0;
106 off_t           biggest = 0;
107 char            state[256];
108 unsigned long   testcalls = 0;          /* calls to function "test" */
109
110 unsigned long   simulatedopcount = 0;   /* -b flag */
111 int     closeprob = 0;                  /* -c flag */
112 int     debug = 0;                      /* -d flag */
113 unsigned long   debugstart = 0;         /* -D flag */
114 unsigned long   maxfilelen = 256 * 1024;        /* -l flag */
115 int     sizechecks = 1;                 /* -n flag disables them */
116 int     maxoplen = 64 * 1024;           /* -o flag */
117 int     quiet = 0;                      /* -q flag */
118 unsigned long progressinterval = 0;     /* -p flag */
119 int     readbdy = 1;                    /* -r flag */
120 int     style = 0;                      /* -s flag */
121 int     truncbdy = 1;                   /* -t flag */
122 int     writebdy = 1;                   /* -w flag */
123 long    monitorstart = -1;              /* -m flag */
124 long    monitorend = -1;                /* -m flag */
125 int     lite = 0;                       /* -L flag */
126 long    numops = -1;                    /* -N flag */
127 int     randomoplen = 1;                /* -O flag disables it */
128 int     seed = 1;                       /* -S flag */
129 int     mapped_writes = 1;            /* -W flag disables */
130 int     mapped_reads = 1;               /* -R flag disables it */
131 int     fsxgoodfd = 0;
132 FILE *  fsxlogf = NULL;
133 int badoff = -1;
134 int closeopen = 0;
135
136
137 void
138 vwarnc(code, fmt, ap)
139         int code;
140         const char *fmt;
141         va_list ap;
142 {
143         fprintf(stderr, "fsx: ");
144         if (fmt != NULL) {
145                 vfprintf(stderr, fmt, ap);
146                 fprintf(stderr, ": ");
147         }
148         fprintf(stderr, "%s\n", strerror(code));
149 }
150
151
152 void
153 warn(const char * fmt, ...)
154 {
155         va_list ap;
156         va_start(ap, fmt);
157         vwarnc(errno, fmt, ap);
158         va_end(ap);
159 }
160
161
162 void
163 prt(char *fmt, ...)
164 {
165         va_list args;
166
167         va_start(args, fmt);
168         vfprintf(stdout, fmt, args);
169         if (fsxlogf)
170                 vfprintf(fsxlogf, fmt, args);
171         va_end(args);
172 }
173
174 void
175 prterr(char *prefix)
176 {
177         prt("%s%s%s\n", prefix, prefix ? ": " : "", strerror(errno));
178 }
179
180
181 void
182 log4(int operation, int arg0, int arg1, int arg2)
183 {
184         struct log_entry *le;
185
186         le = &oplog[logptr];
187         le->operation = operation;
188         if (closeopen)
189                 le->operation = ~ le->operation;
190         le->args[0] = arg0;
191         le->args[1] = arg1;
192         le->args[2] = arg2;
193         logptr++;
194         logcount++;
195         if (logptr >= LOGSIZE)
196                 logptr = 0;
197 }
198
199
200 void
201 logdump(void)
202 {
203         int     i, count, down;
204         struct log_entry        *lp;
205
206         prt("LOG DUMP (%d total operations):\n", logcount);
207         if (logcount < LOGSIZE) {
208                 i = 0;
209                 count = logcount;
210         } else {
211                 i = logptr;
212                 count = LOGSIZE;
213         }
214         for ( ; count > 0; count--) {
215                 int opnum;
216
217                 opnum = i+1 + (logcount/LOGSIZE)*LOGSIZE;
218                 prt("%d(%d mod 256): ", opnum, opnum%256);
219                 lp = &oplog[i];
220                 if ((closeopen = lp->operation < 0))
221                         lp->operation = ~ lp->operation;
222                         
223                 switch (lp->operation) {
224                 case OP_MAPREAD:
225                         prt("MAPREAD\t0x%x thru 0x%x\t(0x%x bytes)",
226                             lp->args[0], lp->args[0] + lp->args[1] - 1,
227                             lp->args[1]);
228                         if (badoff >= lp->args[0] && badoff <
229                                                      lp->args[0] + lp->args[1])
230                                 prt("\t***RRRR***");
231                         break;
232                 case OP_MAPWRITE:
233                         prt("MAPWRITE 0x%x thru 0x%x\t(0x%x bytes)",
234                             lp->args[0], lp->args[0] + lp->args[1] - 1,
235                             lp->args[1]);
236                         if (badoff >= lp->args[0] && badoff <
237                                                      lp->args[0] + lp->args[1])
238                                 prt("\t******WWWW");
239                         break;
240                 case OP_READ:
241                         prt("READ\t0x%x thru 0x%x\t(0x%x bytes)",
242                             lp->args[0], lp->args[0] + lp->args[1] - 1,
243                             lp->args[1]);
244                         if (badoff >= lp->args[0] &&
245                             badoff < lp->args[0] + lp->args[1])
246                                 prt("\t***RRRR***");
247                         break;
248                 case OP_WRITE:
249                         prt("WRITE\t0x%x thru 0x%x\t(0x%x bytes)",
250                             lp->args[0], lp->args[0] + lp->args[1] - 1,
251                             lp->args[1]);
252                         if (lp->args[0] > lp->args[2])
253                                 prt(" HOLE");
254                         else if (lp->args[0] + lp->args[1] > lp->args[2])
255                                 prt(" EXTEND");
256                         if ((badoff >= lp->args[0] || badoff >=lp->args[2]) &&
257                             badoff < lp->args[0] + lp->args[1])
258                                 prt("\t***WWWW");
259                         break;
260                 case OP_TRUNCATE:
261                         down = lp->args[0] < lp->args[1];
262                         prt("TRUNCATE %s\tfrom 0x%x to 0x%x",
263                             down ? "DOWN" : "UP", lp->args[1], lp->args[0]);
264                         if (badoff >= lp->args[!down] &&
265                             badoff < lp->args[!!down])
266                                 prt("\t******WWWW");
267                         break;
268                 case OP_SKIPPED:
269                         prt("SKIPPED (no operation)");
270                         break;
271                 default:
272                         prt("BOGUS LOG ENTRY (operation code = %d)!",
273                             lp->operation);
274                 }
275                 if (closeopen)
276                         prt("\n\t\tCLOSE/OPEN");
277                 prt("\n");
278                 i++;
279                 if (i == LOGSIZE)
280                         i = 0;
281         }
282 }
283
284
285 void
286 save_buffer(char *buffer, off_t bufferlength, int fd)
287 {
288         off_t ret;
289         ssize_t byteswritten;
290
291         if (fd <= 0 || bufferlength == 0)
292                 return;
293
294         if (bufferlength > SSIZE_MAX) {
295                 prt("fsx flaw: overflow in save_buffer\n");
296                 exit(67);
297         }
298         if (lite) {
299                 off_t size_by_seek = lseek(fd, (off_t)0, SEEK_END);
300                 if (size_by_seek == (off_t)-1)
301                         prterr("save_buffer: lseek eof");
302                 else if (bufferlength > size_by_seek) {
303                         warn("save_buffer: .fsxgood file too short... "
304                              "will save 0x%jx bytes instead of 0x%llx\n",
305                              (intmax_t)size_by_seek,
306                              (intmax_t)bufferlength);
307                         bufferlength = size_by_seek;
308                 }
309         }
310
311         ret = lseek(fd, (off_t)0, SEEK_SET);
312         if (ret == (off_t)-1)
313                 prterr("save_buffer: lseek 0");
314         
315         byteswritten = write(fd, buffer, (size_t)bufferlength);
316         if (byteswritten != bufferlength) {
317                 if (byteswritten == -1)
318                         prterr("save_buffer write");
319                 else
320                         warn("save_buffer: short write, "
321                              "0x%x bytes instead of 0x%jx\n",
322                              (unsigned)byteswritten,
323                              (intmax_t)bufferlength);
324         }
325 }
326
327
328 void
329 report_failure(int status)
330 {
331         logdump();
332         
333         if (fsxgoodfd) {
334                 if (good_buf) {
335                         save_buffer(good_buf, file_size, fsxgoodfd);
336                         prt("Correct content saved for comparison\n");
337                         prt("(maybe hexdump \"%s\" vs \"%s.fsxgood\")\n",
338                             fname, fname);
339                 }
340                 close(fsxgoodfd);
341         }
342         exit(status);
343 }
344
345
346 #define short_at(cp) ((unsigned short)((*((unsigned char *)(cp)) << 8) | \
347                                         *(((unsigned char *)(cp)) + 1)))
348
349 void
350 check_buffers(unsigned offset, unsigned size)
351 {
352         unsigned char c, t;
353         unsigned i = 0;
354         unsigned n = 0;
355         unsigned op = 0;
356         unsigned bad = 0;
357
358         if (memcmp(good_buf + offset, temp_buf, size) != 0) {
359                 prt("READ BAD DATA: offset = 0x%x, size = 0x%x\n",
360                     offset, size);
361                 prt("OFFSET\tGOOD\tBAD\tRANGE\n");
362                 while (size > 0) {
363                         c = good_buf[offset];
364                         t = temp_buf[i];
365                         if (c != t) {
366                                 if (n == 0) {
367                                         bad = short_at(&temp_buf[i]);
368                                         prt("0x%5x\t0x%04x\t0x%04x", offset,
369                                             short_at(&good_buf[offset]), bad);
370                                         op = temp_buf[offset & 1 ? i+1 : i];
371                                 }
372                                 n++;
373                                 badoff = offset;
374                         }
375                         offset++;
376                         i++;
377                         size--;
378                 }
379                 if (n) {
380                         prt("\t0x%5x\n", n);
381                         if (bad)
382                                 prt("operation# (mod 256) for the bad data may be %u\n", ((unsigned)op & 0xff));
383                         else
384                                 prt("operation# (mod 256) for the bad data unknown, check HOLE and EXTEND ops\n");
385                 } else
386                         prt("????????????????\n");
387                 report_failure(110);
388         }
389 }
390
391
392 void
393 check_size(void)
394 {
395         struct stat     statbuf;
396         off_t   size_by_seek;
397
398         if (fstat(fd, &statbuf)) {
399                 prterr("check_size: fstat");
400                 statbuf.st_size = -1;
401         }
402         size_by_seek = lseek(fd, (off_t)0, SEEK_END);
403         if (file_size != statbuf.st_size || file_size != size_by_seek) {
404                 prt("Size error: expected 0x%llx stat 0x%llx seek 0x%llx\n",
405                     (unsigned long long)file_size,
406                     (unsigned long long)statbuf.st_size,
407                     (unsigned long long)size_by_seek);
408                 report_failure(120);
409         }
410 }
411
412
413 void
414 check_trunc_hack(void)
415 {
416         struct stat statbuf;
417
418         ftruncate(fd, (off_t)0);
419         ftruncate(fd, (off_t)100000);
420         fstat(fd, &statbuf);
421         if (statbuf.st_size != (off_t)100000) {
422                 prt("no extend on truncate! not posix!\n");
423                 exit(130);
424         }
425         ftruncate(fd, (off_t)0);
426 }
427
428
429 void
430 doread(unsigned offset, unsigned size)
431 {
432         off_t ret;
433         unsigned iret;
434
435         offset -= offset % readbdy;
436         if (size == 0) {
437                 if (!quiet && testcalls > simulatedopcount)
438                         prt("skipping zero size read\n");
439                 log4(OP_SKIPPED, OP_READ, offset, size);
440                 return;
441         }
442         if (size + offset > file_size) {
443                 if (!quiet && testcalls > simulatedopcount)
444                         prt("skipping seek/read past end of file\n");
445                 log4(OP_SKIPPED, OP_READ, offset, size);
446                 return;
447         }
448
449         log4(OP_READ, offset, size, 0);
450
451         if (testcalls <= simulatedopcount)
452                 return;
453
454         if (!quiet && ((progressinterval &&
455                         testcalls % progressinterval == 0) ||
456                        (debug &&
457                         (monitorstart == -1 ||
458                          (offset + size > monitorstart &&
459                           (monitorend == -1 || offset <= monitorend))))))
460                 prt("%lu read\t0x%x thru\t0x%x\t(0x%x bytes)\n", testcalls,
461                     offset, offset + size - 1, size);
462         ret = lseek(fd, (off_t)offset, SEEK_SET);
463         if (ret == (off_t)-1) {
464                 prterr("doread: lseek");
465                 report_failure(140);
466         }
467         iret = read(fd, temp_buf, size);
468         if (iret != size) {
469                 if (iret == -1)
470                         prterr("doread: read");
471                 else
472                         prt("short read: 0x%x bytes instead of 0x%x\n",
473                             iret, size);
474                 report_failure(141);
475         }
476         check_buffers(offset, size);
477 }
478
479
480 void
481 check_eofpage(char *s, unsigned offset, char *p, int size)
482 {
483         intptr_t last_page, should_be_zero;
484
485         if (offset + size <= (file_size & ~page_mask))
486                 return;
487         /*
488          * we landed in the last page of the file
489          * test to make sure the VM system provided 0's 
490          * beyond the true end of the file mapping
491          * (as required by mmap def in 1996 posix 1003.1)
492          */
493         last_page = ((intptr_t)p + (offset & page_mask) + size) & ~(intptr_t)page_mask;
494
495         for (should_be_zero = last_page + (file_size & page_mask);
496              should_be_zero < last_page + page_size;
497              should_be_zero++) {
498                 if (*(char *)should_be_zero) {
499                         prt("Mapped %s: non-zero data past EOF (0x%llx) page offset 0x%x is 0x%04x\n",
500                             s, file_size - 1, should_be_zero & page_mask,
501                             *(char *)(should_be_zero));
502                         report_failure(205);
503                 }
504         }
505 }
506
507
508 void
509 domapread(unsigned offset, unsigned size)
510 {
511         unsigned pg_offset;
512         unsigned map_size;
513         char    *p;
514
515         offset -= offset % readbdy;
516         if (size == 0) {
517                 if (!quiet && testcalls > simulatedopcount)
518                         prt("skipping zero size read\n");
519                 log4(OP_SKIPPED, OP_MAPREAD, 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_MAPREAD, offset, size);
526                 return;
527         }
528
529         log4(OP_MAPREAD, offset, size, 0);
530
531         if (testcalls <= simulatedopcount)
532                 return;
533
534         if (!quiet && ((progressinterval &&
535                         testcalls % progressinterval == 0) ||
536                        (debug &&
537                         (monitorstart == -1 ||
538                          (offset + size > monitorstart &&
539                           (monitorend == -1 || offset <= monitorend))))))
540                 prt("%lu mapread\t0x%x thru\t0x%x\t(0x%x bytes)\n", testcalls,
541                     offset, offset + size - 1, size);
542
543         pg_offset = offset & page_mask;
544         map_size  = pg_offset + size;
545
546         if ((p = (char *)mmap(0, map_size, PROT_READ, MAP_FILE | MAP_SHARED, fd,
547                               (off_t)(offset - pg_offset))) == (char *)-1) {
548                 prterr("domapread: mmap");
549                 report_failure(190);
550         }
551         if (setjmp(jmpbuf) == 0) {
552             jmpbuf_good = 1;
553             memcpy(temp_buf, p + pg_offset, size);
554             check_eofpage("Read", offset, p, size);
555             jmpbuf_good = 0;
556         } else {
557             report_failure(1901);
558         }
559
560         if (munmap(p, map_size) != 0) {
561                 prterr("domapread: munmap");
562                 report_failure(191);
563         }
564
565         check_buffers(offset, size);
566 }
567
568
569 void
570 gendata(char *original_buf, char *good_buf, unsigned offset, unsigned size)
571 {
572         while (size--) {
573                 good_buf[offset] = testcalls % 256; 
574                 if (offset % 2)
575                         good_buf[offset] += original_buf[offset];
576                 offset++;
577         }
578 }
579
580
581 void
582 dowrite(unsigned offset, unsigned size)
583 {
584         off_t ret;
585         unsigned iret;
586
587         offset -= offset % writebdy;
588         if (size == 0) {
589                 if (!quiet && testcalls > simulatedopcount)
590                         prt("skipping zero size write\n");
591                 log4(OP_SKIPPED, OP_WRITE, offset, size);
592                 return;
593         }
594
595         log4(OP_WRITE, offset, size, file_size);
596
597         gendata(original_buf, good_buf, offset, size);
598         if (file_size < offset + size) {
599                 if (file_size < offset)
600                         memset(good_buf + file_size, '\0', offset - file_size);
601                 file_size = offset + size;
602                 if (lite) {
603                         warn("Lite file size bug in fsx!");
604                         report_failure(149);
605                 }
606         }
607
608         if (testcalls <= simulatedopcount)
609                 return;
610
611         if (!quiet && ((progressinterval &&
612                         testcalls % progressinterval == 0) ||
613                        (debug &&
614                         (monitorstart == -1 ||
615                          (offset + size > monitorstart &&
616                           (monitorend == -1 || offset <= monitorend))))))
617                 prt("%lu write\t0x%x thru\t0x%x\t(0x%x bytes)\n", testcalls,
618                     offset, offset + size - 1, size);
619         ret = lseek(fd, (off_t)offset, SEEK_SET);
620         if (ret == (off_t)-1) {
621                 prterr("dowrite: lseek");
622                 report_failure(150);
623         }
624         iret = write(fd, good_buf + offset, size);
625         if (iret != size) {
626                 if (iret == -1)
627                         prterr("dowrite: write");
628                 else
629                         prt("short write: 0x%x bytes instead of 0x%x\n",
630                             iret, size);
631                 report_failure(151);
632         }
633 }
634
635
636 void
637 domapwrite(unsigned offset, unsigned size)
638 {
639         unsigned pg_offset;
640         unsigned map_size;
641         off_t    cur_filesize;
642         char    *p;
643
644         offset -= offset % writebdy;
645         if (size == 0) {
646                 if (!quiet && testcalls > simulatedopcount)
647                         prt("skipping zero size write\n");
648                 log4(OP_SKIPPED, OP_MAPWRITE, offset, size);
649                 return;
650         }
651         cur_filesize = file_size;
652
653         log4(OP_MAPWRITE, offset, size, 0);
654
655         gendata(original_buf, good_buf, offset, size);
656         if (file_size < offset + size) {
657                 if (file_size < offset)
658                         memset(good_buf + file_size, '\0', offset - file_size);
659                 file_size = offset + size;
660                 if (lite) {
661                         warn("Lite file size bug in fsx!");
662                         report_failure(200);
663                 }
664         }
665
666         if (testcalls <= simulatedopcount)
667                 return;
668
669         if (!quiet && ((progressinterval &&
670                         testcalls % progressinterval == 0) ||
671                        (debug &&
672                         (monitorstart == -1 ||
673                          (offset + size > monitorstart &&
674                           (monitorend == -1 || offset <= monitorend))))))
675                 prt("%lu mapwrite\t0x%x thru\t0x%x\t(0x%x bytes)\n", testcalls,
676                     offset, offset + size - 1, size);
677
678         if (file_size > cur_filesize) {
679                 if (ftruncate(fd, file_size) == -1) {
680                         prterr("domapwrite: ftruncate");
681                         exit(201);
682                 }
683         }
684         pg_offset = offset & page_mask;
685         map_size  = pg_offset + size;
686
687         if ((p = (char *)mmap(0, map_size, PROT_READ | PROT_WRITE,
688                               MAP_FILE | MAP_SHARED, fd,
689                               (off_t)(offset - pg_offset))) == (char *)-1) {
690                 prterr("domapwrite: mmap");
691                 report_failure(202);
692         }
693         if (setjmp(jmpbuf) == 0) {
694             jmpbuf_good = 1;
695             memcpy(p + pg_offset, good_buf + offset, size);
696             if (msync(p, map_size, 0) != 0) {
697                     prterr("domapwrite: msync");
698                     report_failure(203);
699             }
700             check_eofpage("Write", offset, p, size);
701             jmpbuf_good = 0;
702         } else {
703             report_failure(2021);
704         }
705
706         if (munmap(p, map_size) != 0) {
707                 prterr("domapwrite: munmap");
708                 report_failure(204);
709         }
710 }
711
712
713 void
714 dotruncate(unsigned size)
715 {
716         int oldsize = file_size;
717
718         size -= size % truncbdy;
719         if (size > biggest) {
720                 biggest = size;
721                 if (!quiet && testcalls > simulatedopcount)
722                         prt("truncating to largest ever: 0x%x\n", size);
723         }
724
725         log4(OP_TRUNCATE, size, (unsigned)file_size, 0);
726
727         if (size > file_size)
728                 memset(good_buf + file_size, '\0', size - file_size);
729         file_size = size;
730
731         if (testcalls <= simulatedopcount)
732                 return;
733         
734         if ((progressinterval && testcalls % progressinterval == 0) ||
735             (debug && (monitorstart == -1 || monitorend == -1 ||
736                        size <= monitorend)))
737                 prt("%lu trunc\tfrom 0x%x to 0x%x\n", testcalls, oldsize, size);
738         if (ftruncate(fd, (off_t)size) == -1) {
739                 prt("ftruncate1: %x\n", size);
740                 prterr("dotruncate: ftruncate");
741                 report_failure(160);
742         }
743 }
744
745
746 void
747 writefileimage()
748 {
749         ssize_t iret;
750
751         if (lseek(fd, (off_t)0, SEEK_SET) == (off_t)-1) {
752                 prterr("writefileimage: lseek");
753                 report_failure(171);
754         }
755         iret = write(fd, good_buf, file_size);
756         if ((off_t)iret != file_size) {
757                 if (iret == -1)
758                         prterr("writefileimage: write");
759                 else
760                         prt("short write: 0x%x bytes instead of 0x%jx\n",
761                             iret, (intmax_t)file_size);
762                 report_failure(172);
763         }
764         if (lite ? 0 : ftruncate(fd, file_size) == -1) {
765                 prt("ftruncate2: %jx\n", (intmax_t)file_size);
766                 prterr("writefileimage: ftruncate");
767                 report_failure(173);
768         }
769 }
770
771
772 void
773 docloseopen(void)
774
775         if (testcalls <= simulatedopcount)
776                 return;
777
778         if (debug)
779                 prt("%lu close/open\n", testcalls);
780         if (close(fd)) {
781                 prterr("docloseopen: close");
782                 report_failure(180);
783         }
784         fd = open(fname, O_RDWR, 0);
785         if (fd < 0) {
786                 prterr("docloseopen: open");
787                 report_failure(181);
788         }
789 }
790
791
792 void
793 test(void)
794 {
795         unsigned long   offset;
796         unsigned long   size = maxoplen;
797         unsigned long   rv = random();
798         unsigned long   op = rv % (3 + !lite + mapped_writes);
799
800         /* turn off the map read if necessary */
801
802         if (op == 2 && !mapped_reads)
803             op = 0;
804
805         if (simulatedopcount > 0 && testcalls == simulatedopcount)
806                 writefileimage();
807
808         testcalls++;
809
810         if (closeprob)
811                 closeopen = (rv >> 3) < (1 << 28) / closeprob;
812
813         if (debugstart > 0 && testcalls >= debugstart)
814                 debug = 1;
815
816         if (!quiet && testcalls < simulatedopcount && testcalls % 100000 == 0)
817                 prt("%lu...\n", testcalls);
818
819         /*
820          * READ:        op = 0
821          * WRITE:       op = 1
822          * MAPREAD:     op = 2
823          * TRUNCATE:    op = 3
824          * MAPWRITE:    op = 3 or 4
825          */
826         if (lite ? 0 : op == 3 && style == 0) /* vanilla truncate? */
827                 dotruncate(random() % maxfilelen);
828         else {
829                 if (randomoplen)
830                         size = random() % (maxoplen+1);
831                 if (lite ? 0 : op == 3)
832                         dotruncate(size);
833                 else {
834                         offset = random();
835                         if (op == 1 || op == (lite ? 3 : 4)) {
836                                 offset %= maxfilelen;
837                                 if (offset + size > maxfilelen)
838                                         size = maxfilelen - offset;
839                                 if (op != 1)
840                                         domapwrite(offset, size);
841                                 else
842                                         dowrite(offset, size);
843                         } else {
844                                 if (file_size)
845                                         offset %= file_size;
846                                 else
847                                         offset = 0;
848                                 if (offset + size > file_size)
849                                         size = file_size - offset;
850                                 if (op != 0)
851                                         domapread(offset, size);
852                                 else
853                                         doread(offset, size);
854                         }
855                 }
856         }
857         if (sizechecks && testcalls > simulatedopcount)
858                 check_size();
859         if (closeopen)
860                 docloseopen();
861 }
862
863 void
864 segv(int sig)
865 {
866         if (jmpbuf_good) {
867             jmpbuf_good = 0;
868             longjmp(jmpbuf, 1);
869         }
870         report_failure(9999);
871 }
872
873 void
874 cleanup(sig)
875         int     sig;
876 {
877         if (sig)
878                 prt("signal %d\n", sig);
879         prt("testcalls = %lu\n", testcalls);
880         exit(sig);
881 }
882
883
884 void
885 usage(void)
886 {
887         fprintf(stdout, "usage: %s",
888                 "fsx [-dnqLOW] [-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\
889         -b opnum: beginning operation number (default 1)\n\
890         -c P: 1 in P chance of file close+open at each op (default infinity)\n\
891         -d: debug output for all operations\n\
892         -l flen: the upper bound on file size (default 262144)\n\
893         -m startop:endop: monitor (print debug output) specified byte range (default 0:infinity)\n\
894         -n: no verifications of file size\n\
895         -o oplen: the upper bound on operation size (default 65536)\n\
896         -p progressinterval: debug output at specified operation interval\n\
897         -q: quieter operation\n\
898         -r readbdy: 4096 would make reads page aligned (default 1)\n\
899         -s style: 1 gives smaller truncates (default 0)\n\
900         -t truncbdy: 4096 would make truncates page aligned (default 1)\n\
901         -w writebdy: 4096 would make writes page aligned (default 1)\n\
902         -D startingop: debug output starting at specified operation\n\
903         -L: fsxLite - no file creations & no file size changes\n\
904         -N numops: total # operations to do (default infinity)\n\
905         -O: use oplen (see -o flag) for every op (default random)\n\
906         -P dirpath: save .fsxlog and .fsxgood files in dirpath (default ./)\n\
907         -S seed: for random # generator (default 1) 0 gets timestamp\n\
908         -W: mapped write operations DISabled\n\
909         -R: mapped read operations DISabled)\n\
910         fname: this filename is REQUIRED (no default)\n");
911         exit(90);
912 }
913
914
915 int
916 getnum(char *s, char **e)
917 {
918         int ret = -1;
919
920         *e = NULL;
921         ret = strtol(s, e, 0);
922         if (*e)
923                 switch (**e) {
924                 case 'b':
925                 case 'B':
926                         ret *= 512;
927                         *e = *e + 1;
928                         break;
929                 case 'k':
930                 case 'K':
931                         ret *= 1024;
932                         *e = *e + 1;
933                         break;
934                 case 'm':
935                 case 'M':
936                         ret *= 1024*1024;
937                         *e = *e + 1;
938                         break;
939                 case 'w':
940                 case 'W':
941                         ret *= 4;
942                         *e = *e + 1;
943                         break;
944                 }
945         return (ret);
946 }
947
948
949 int
950 main(int argc, char **argv)
951 {
952         int     i, ch;
953         char    *endp;
954         char goodfile[1024];
955         char logfile[1024];
956
957         goodfile[0] = 0;
958         logfile[0] = 0;
959
960         page_size = getpagesize();
961         page_mask = page_size - 1;
962
963         setvbuf(stdout, NULL, _IOLBF, 0); /* line buffered stdout */
964
965         while ((ch = getopt(argc, argv, "b:c:dl:m:no:p:qr:s:t:w:D:LN:OP:RS:W"))
966                != EOF)
967                 switch (ch) {
968                 case 'b':
969                         simulatedopcount = getnum(optarg, &endp);
970                         if (!quiet)
971                                 fprintf(stdout, "Will begin at operation %ld\n",
972                                         simulatedopcount);
973                         if (simulatedopcount == 0)
974                                 usage();
975                         simulatedopcount -= 1;
976                         break;
977                 case 'c':
978                         closeprob = getnum(optarg, &endp);
979                         if (!quiet)
980                                 fprintf(stdout,
981                                         "Chance of close/open is 1 in %d\n",
982                                         closeprob);
983                         if (closeprob <= 0)
984                                 usage();
985                         break;
986                 case 'd':
987                         debug = 1;
988                         break;
989                 case 'l':
990                         maxfilelen = getnum(optarg, &endp);
991                         if (maxfilelen <= 0)
992                                 usage();
993                         break;
994                 case 'm':
995                         monitorstart = getnum(optarg, &endp);
996                         if (monitorstart < 0)
997                                 usage();
998                         if (!endp || *endp++ != ':')
999                                 usage();
1000                         monitorend = getnum(endp, &endp);
1001                         if (monitorend < 0)
1002                                 usage();
1003                         if (monitorend == 0)
1004                                 monitorend = -1; /* aka infinity */
1005                         debug = 1;
1006                 case 'n':
1007                         sizechecks = 0;
1008                         break;
1009                 case 'o':
1010                         maxoplen = getnum(optarg, &endp);
1011                         if (maxoplen <= 0)
1012                                 usage();
1013                         break;
1014                 case 'p':
1015                         progressinterval = getnum(optarg, &endp);
1016                         if (progressinterval < 0)
1017                                 usage();
1018                         break;
1019                 case 'q':
1020                         quiet = 1;
1021                         break;
1022                 case 'r':
1023                         readbdy = getnum(optarg, &endp);
1024                         if (readbdy <= 0)
1025                                 usage();
1026                         break;
1027                 case 's':
1028                         style = getnum(optarg, &endp);
1029                         if (style < 0 || style > 1)
1030                                 usage();
1031                         break;
1032                 case 't':
1033                         truncbdy = getnum(optarg, &endp);
1034                         if (truncbdy <= 0)
1035                                 usage();
1036                         break;
1037                 case 'w':
1038                         writebdy = getnum(optarg, &endp);
1039                         if (writebdy <= 0)
1040                                 usage();
1041                         break;
1042                 case 'D':
1043                         debugstart = getnum(optarg, &endp);
1044                         if (debugstart < 1)
1045                                 usage();
1046                         break;
1047                 case 'L':
1048                         lite = 1;
1049                         break;
1050                 case 'N':
1051                         numops = getnum(optarg, &endp);
1052                         if (numops < 0)
1053                                 usage();
1054                         break;
1055                 case 'O':
1056                         randomoplen = 0;
1057                         break;
1058                 case 'P':
1059                         strncpy(goodfile, optarg, sizeof(goodfile));
1060                         strcat(goodfile, "/");
1061                         strncpy(logfile, optarg, sizeof(logfile));
1062                         strcat(logfile, "/");
1063                         break;
1064                 case 'R':
1065                         mapped_reads = 0;
1066                         break;
1067                 case 'S':
1068                         seed = getnum(optarg, &endp);
1069                         if (seed == 0)
1070                                 seed = time(0) % 10000;
1071                         if (!quiet)
1072                                 fprintf(stdout, "Seed set to %d\n", seed);
1073                         if (seed < 0)
1074                                 usage();
1075                         break;
1076                 case 'W':
1077                         mapped_writes = 0;
1078                         if (!quiet)
1079                                 fprintf(stdout, "mapped writes DISABLED\n");
1080                         break;
1081
1082                 default:
1083                         usage();
1084                         /* NOTREACHED */
1085                 }
1086         argc -= optind;
1087         argv += optind;
1088         if (argc != 1)
1089                 usage();
1090         fname = argv[0];
1091
1092         signal(SIGHUP,  cleanup);
1093         signal(SIGINT,  cleanup);
1094         signal(SIGPIPE, cleanup);
1095         signal(SIGALRM, cleanup);
1096         signal(SIGTERM, cleanup);
1097         signal(SIGXCPU, cleanup);
1098         signal(SIGXFSZ, cleanup);
1099         signal(SIGVTALRM,       cleanup);
1100         signal(SIGUSR1, cleanup);
1101         signal(SIGUSR2, cleanup);
1102         signal(SIGSEGV, segv);
1103
1104         initstate(seed, state, 256);
1105         setstate(state);
1106         fd = open(fname, O_RDWR|(lite ? 0 : O_CREAT|O_TRUNC), 0666);
1107         if (fd < 0) {
1108                 prterr(fname);
1109                 exit(91);
1110         }
1111         strncat(goodfile, fname, 256);
1112         strcat (goodfile, ".fsxgood");
1113         fsxgoodfd = open(goodfile, O_RDWR|O_CREAT|O_TRUNC, 0666);
1114         if (fsxgoodfd < 0) {
1115                 prterr(goodfile);
1116                 exit(92);
1117         }
1118         strncat(logfile, fname, 256);
1119         strcat (logfile, ".fsxlog");
1120         fsxlogf = fopen(logfile, "w");
1121         if (fsxlogf == NULL) {
1122                 prterr(logfile);
1123                 exit(93);
1124         }
1125         if (lite) {
1126                 off_t ret;
1127                 file_size = maxfilelen = lseek(fd, (off_t)0, SEEK_END);
1128                 if (file_size == (off_t)-1) {
1129                         prterr(fname);
1130                         warn("main: lseek eof");
1131                         exit(94);
1132                 }
1133                 ret = lseek(fd, (off_t)0, SEEK_SET);
1134                 if (ret == (off_t)-1) {
1135                         prterr(fname);
1136                         warn("main: lseek 0");
1137                         exit(95);
1138                 }
1139         }
1140         original_buf = (char *) malloc(maxfilelen);
1141         for (i = 0; i < maxfilelen; i++)
1142                 original_buf[i] = random() % 256;
1143         good_buf = (char *) malloc(maxfilelen);
1144         memset(good_buf, '\0', maxfilelen);
1145         temp_buf = (char *) malloc(maxoplen);
1146         memset(temp_buf, '\0', maxoplen);
1147         if (lite) {     /* zero entire existing file */
1148                 ssize_t written;
1149
1150                 written = write(fd, good_buf, (size_t)maxfilelen);
1151                 if (written != maxfilelen) {
1152                         if (written == -1) {
1153                                 prterr(fname);
1154                                 warn("main: error on write");
1155                         } else
1156                                 warn("main: short write, 0x%x bytes instead of 0x%x\n",
1157                                      (unsigned)written, maxfilelen);
1158                         exit(98);
1159                 }
1160         } else 
1161                 check_trunc_hack();
1162
1163         while (numops == -1 || numops--)
1164                 test();
1165
1166         if (close(fd)) {
1167                 prterr("close");
1168                 report_failure(99);
1169         }
1170         prt("All operations completed A-OK!\n");
1171
1172         exit(0);
1173         return 0;
1174 }
1175