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