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