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