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