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