Whamcloud - gitweb
LU-15460 test: wait quota pool to be prepared
[fs/lustre-release.git] / lustre / tests / fsx.c
1 /*
2  * Copyright (C) 1991, NeXT Computer, Inc.  All Rights Reserverd.
3  * Copyright (c) 1998-2001 Apple Computer, Inc. All rights reserved.
4  *
5  * Copyright (c) 2012, Intel Corporation.
6  *
7  * @APPLE_LICENSE_HEADER_START@
8  *
9  * The contents of this file constitute Original Code as defined in and
10  * are subject to the Apple Public Source License Version 1.1 (the
11  * "License").  You may not use this file except in compliance with the
12  * License.  Please obtain a copy of the License at
13  * http://www.apple.com/publicsource and read it before using this file.
14  *
15  * This Original Code and all software distributed under the License are
16  * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER
17  * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
18  * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
19  * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT.  Please see the
20  * License for the specific language governing rights and limitations
21  * under the License.
22  *
23  * @APPLE_LICENSE_HEADER_END@
24  *
25  *      File:   fsx.c
26  *      Author: Avadis Tevanian, Jr.
27  *
28  *      File system exerciser.
29  *
30  *      Rewrite and enhancements 1998-2001 Conrad Minshall -- conrad@mac.com
31  *
32  *      Various features from Joe Sokol, Pat Dirks, and Clark Warner.
33  *
34  *      Small changes to work under Linux -- davej.
35  *
36  *      Sundry porting patches from Guy Harris 12/2001
37  * $FreeBSD: src/tools/regression/fsx/fsx.c,v 1.1 2001/12/20 04:15:57 jkh Exp $
38  *
39  *      Checks for mmap last-page zero fill.
40  *
41  *      Add multi-file testing feature -- Zach Brown <zab@clusterfs.com>
42  *
43  *      Add random preallocation calls - Eric Sandeen <sandeen@redhat.com>
44  *
45  * $FreeBSD: src/tools/regression/fsx/fsx.c,v 1.2 2003/04/23 23:42:23 jkh Exp $
46  * $DragonFly: src/test/stress/fsx/fsx.c,v 1.2 2005/05/02 19:31:56 dillon Exp $
47  */
48 #ifndef _GNU_SOURCE
49 #define _GNU_SOURCE
50 #endif
51
52 #include <sys/types.h>
53 #include <sys/stat.h>
54 #if defined(_UWIN) || defined(__linux__)
55 # include <sys/param.h>
56 # include <limits.h>
57 # include <time.h>
58 # include <strings.h>
59 #endif
60 #include <sys/time.h>
61 #include <fcntl.h>
62 #include <sys/mman.h>
63 #ifndef MAP_FILE
64 # define MAP_FILE 0
65 #endif
66 #include <limits.h>
67 #include <signal.h>
68 #include <stdio.h>
69 #include <stddef.h>
70 #include <stdlib.h>
71 #include <string.h>
72 #include <unistd.h>
73 #include <stdarg.h>
74 #include <errno.h>
75 #include <libcfs/util/string.h>
76 #include <setjmp.h>
77
78 /*
79  * Each test run will work with one or more separate file descriptors for the
80  * same file.  This allows testing cache coherency across multiple mountpoints
81  * of the same network filesystem on a single client.
82  */
83 struct test_file {
84         char *path;
85         int fd;
86         int o_direct;
87 } *test_files = NULL, *tf;
88
89 int num_test_files;
90
91 enum fd_iteration_policy {
92         FD_SINGLE,
93         FD_ROTATE,
94         FD_RANDOM,
95 };
96
97 int fd_policy = FD_RANDOM;
98 int fd_last;
99
100 /*
101  *      A log entry is an operation and a bunch of arguments.
102  */
103
104 struct log_entry {
105         int operation;
106         int args[3];
107         struct timeval tv;
108         const struct test_file *tf;
109 };
110
111 #define LOGSIZE 100000
112
113 struct log_entry oplog[LOGSIZE]; /* the log */
114 int logptr; /* current position in log */
115 int logcount; /* total ops */
116 int jmpbuf_good;
117 jmp_buf jmpbuf;
118
119 /*
120  * Define operations
121  */
122
123 /* common operations */
124 #define OP_READ         0
125 #define OP_WRITE        1
126 #define OP_MAPREAD      2
127 #define OP_MAPWRITE     3
128 #define OP_MAX_LITE     4
129
130 /* !lite operations */
131 #define OP_TRUNCATE             4
132 #define OP_FALLOCATE            5
133 #define OP_PUNCH_HOLE           6
134 #define OP_ZERO_RANGE           7
135 #define OP_CLOSEOPEN            8
136 #define OP_MAX_FULL             9
137
138 #define OP_SKIPPED 101
139 #define OP_DIRECT O_DIRECT
140
141 #ifndef FALLOC_FL_PUNCH_HOLE
142 #define FALLOC_FL_PUNCH_HOLE 0x02 /* de-allocates range */
143 #endif
144
145 #ifndef FALLOC_FL_KEEP_SIZE
146 #define FALLOC_FL_KEEP_SIZE 0x01 /* default is extend size */
147 #endif
148
149 #ifndef FALLOC_FL_ZERO_RANGE
150 #define FALLOC_FL_ZERO_RANGE 0x10 /* convert range to zeros */
151 #endif
152
153
154 char *original_buf; /* a pointer to the original data */
155 char *good_buf; /* a pointer to the correct data */
156 char *temp_buf; /* a pointer to the current data */
157 char *fname; /* name of our test file */
158 char logfile[PATH_MAX]; /* name of our log file */
159 char goodfile[PATH_MAX]; /* name of our test file */
160
161 struct timeval tv; /* time current operation started */
162 off_t file_size;
163 off_t biggest;
164 char state[256];
165 unsigned long testcalls; /* calls to function "test" */
166
167 long simulatedopcount;                  /* -b flag */
168 int closeprob;                          /* -c flag */
169 int debug ;                             /* -d flag */
170 long debugstart;                        /* -D flag */
171 int flush;                              /* -f flag */
172 int do_fsync;                           /* -y flag */
173 long maxfilelen = 256 * 1024;           /* -l flag */
174 int sizechecks = 1;                     /* -n flag disables them */
175 int maxoplen = 64 * 1024;               /* -o flag */
176 int quiet;                              /* -q flag */
177 long progressinterval;                  /* -p flag */
178 int readbdy = 1;                        /* -r flag */
179 int style;                              /* -s flag */
180 int truncbdy = 1;                       /* -t flag */
181 int writebdy = 1;                       /* -w flag */
182 long monitorstart = -1;                 /* -m flag */
183 long monitorend = -1;                   /* -m flag */
184 int lite;                               /* -L flag */
185 long numops = -1;                       /* -N flag */
186 int randomoplen = 1;                    /* -O flag disables it */
187 int seed = 1;                           /* -S flag */
188 int mapped_writes = 1;                  /* -W flag disables */
189 int fallocate_calls = 1;                /* -F flag disables */
190 int punch_hole_calls = 1;               /* -H flag disables */
191 int zero_range_calls = 1;               /* -z flag disables */
192 int mapped_reads = 1;                   /* -R flag disables it */
193 int fsxgoodfd;
194 int o_direct;                           /* -Z */
195 int fl_keep_size;
196
197 int page_size;
198 int page_mask;
199
200 FILE *fsxlogf;
201 int badoff = -1;
202
203 void
204 vwarnc(code, fmt, ap)
205         int code;
206         const char *fmt;
207         va_list ap;
208 {
209         fprintf(stderr, "fsx: ");
210         if (fmt) {
211                 vfprintf(stderr, fmt, ap);
212                 fprintf(stderr, ": ");
213         }
214         fprintf(stderr, "%s\n", strerror(code));
215 }
216
217 void
218 __attribute__((format(__printf__, 1, 2)))
219 warn(const char *fmt, ...)
220 {
221         va_list ap;
222
223         va_start(ap, fmt);
224         vwarnc(errno, fmt, ap);
225         va_end(ap);
226 }
227
228 void
229 __attribute__((format(__printf__, 1, 2)))
230 prt(char *fmt, ...)
231 {
232         va_list args;
233
234         va_start(args, fmt);
235         vfprintf(stdout, fmt, args);
236         va_end(args);
237
238         if (fsxlogf) {
239                 va_start(args, fmt);
240                 vfprintf(fsxlogf, fmt, args);
241                 va_end(args);
242         }
243 }
244
245 /*
246  * prterr() is now a macro. It internally calls ptrerr_func()
247  * which transparently handles passing of function name.
248  * This version also keeps checkpatch happy.
249  */
250 void
251 ptrerr_func(const char *func, const char *prefix)
252 {
253         prt("%s: %s%s%s\n", func, prefix, prefix ? ": " : "", strerror(errno));
254 }
255 #define prterr(prefix) ptrerr_func(__func__, prefix)
256
257 void
258 log4(int operation, int arg0, int arg1, int arg2)
259 {
260         struct log_entry *le;
261
262         le = &oplog[logptr];
263         le->operation = operation;
264         le->args[0] = arg0;
265         le->args[1] = arg1;
266         le->args[2] = arg2;
267         gettimeofday(&tv, NULL);
268         le->tv = tv;
269         le->tf = tf;
270         logptr++;
271         logcount++;
272         if (logptr >= LOGSIZE)
273                 logptr = 0;
274 }
275
276 const char *
277 fill_tf_buf(const struct test_file *tf)
278 {
279         static int max_tf_len;
280         static char tf_buf[32];
281
282         if (fd_policy == FD_SINGLE)
283                 return "";
284
285         if (max_tf_len == 0)
286                 max_tf_len = scnprintf(tf_buf, sizeof(tf_buf) - 1,
287                                       "%u", num_test_files - 1);
288
289         snprintf(tf_buf, sizeof(tf_buf), "[%0*lu]", max_tf_len,
290                 (unsigned long)(tf - test_files));
291
292         return tf_buf;
293 }
294
295 void
296 logdump(void)
297 {
298         int i, count, down;
299         struct log_entry *lp;
300         char *falloc_type[3] = {"PAST_EOF", "EXTENDING", "INTERIOR"};
301
302         prt("LOG DUMP (%d total operations):\n", logcount);
303         if (logcount < LOGSIZE) {
304                 i = 0;
305                 count = logcount;
306         } else {
307                 i = logptr;
308                 count = LOGSIZE;
309         }
310         for ( ; count > 0; count--) {
311                 int opnum;
312
313                 opnum = i + 1 + (logcount / LOGSIZE) * LOGSIZE;
314                 lp = &oplog[i];
315                 prt("%d%s: %lu.%06u ", opnum, fill_tf_buf(lp->tf),
316                     lp->tv.tv_sec, (int)lp->tv.tv_usec);
317
318                 switch (lp->operation) {
319                 case OP_MAPREAD:
320                         prt("MAPREAD  0x%05x thru 0x%05x (0x%05x bytes)",
321                             lp->args[0], lp->args[0] + lp->args[1] - 1,
322                             lp->args[1]);
323                         if (badoff >= lp->args[0] && badoff <
324                                                      lp->args[0] + lp->args[1])
325                                 prt("\t***RRRR***");
326                         break;
327                 case OP_MAPWRITE:
328                         prt("MAPWRITE 0x%05x thru 0x%05x (0x%05x bytes)",
329                             lp->args[0], lp->args[0] + lp->args[1] - 1,
330                             lp->args[1]);
331                         if (badoff >= lp->args[0] && badoff <
332                                                      lp->args[0] + lp->args[1])
333                                 prt("\t******WWWW");
334                         break;
335                 case OP_READ:
336                 case OP_READ + OP_DIRECT:
337                         prt("READ%s  0x%05x thru 0x%05x (0x%05x bytes)",
338                             lp->operation & OP_DIRECT ? "_OD" : "   ",
339                             lp->args[0], lp->args[0] + lp->args[1] - 1,
340                             lp->args[1]);
341                         if (badoff >= lp->args[0] &&
342                             badoff < lp->args[0] + lp->args[1])
343                                 prt("\t***RRRR***");
344                         break;
345                 case OP_WRITE:
346                 case OP_WRITE + OP_DIRECT:
347                         prt("WRITE%s 0x%05x thru 0x%05x (0x%05x bytes)",
348                             lp->operation & OP_DIRECT ? "_OD" : "   ",
349                             lp->args[0], lp->args[0] + lp->args[1] - 1,
350                             lp->args[1]);
351                         if (lp->args[0] > lp->args[2])
352                                 prt(" HOLE");
353                         else if (lp->args[0] + lp->args[1] > lp->args[2])
354                                 prt(" EXTEND");
355                         if ((badoff >= lp->args[0] || badoff >= lp->args[2]) &&
356                             badoff < lp->args[0] + lp->args[1])
357                                 prt("\t***WWWW");
358                         break;
359                 case OP_TRUNCATE:
360                         down = lp->args[0] < lp->args[1];
361                         prt("TRUNC%s 0x%05x to 0x%05x",
362                             down ? "_DN" : "_UP", lp->args[1], lp->args[0]);
363                         if (badoff >= lp->args[!down] &&
364                             badoff < lp->args[!!down])
365                                 prt("\t******TTTT");
366                         break;
367                 case OP_FALLOCATE:
368                         /* 0: offset 1: length 2: where alloced */
369                         prt("FALLOC   0x%05x thru 0x%05x\t(0x%05x bytes)%s",
370                             lp->args[0], lp->args[0] + lp->args[1],
371                             lp->args[1], falloc_type[lp->args[2]]);
372                         if (badoff >= lp->args[0] &&
373                             badoff < lp->args[0] + lp->args[1])
374                                 prt("\t******FFFF");
375                         break;
376                 case OP_PUNCH_HOLE:
377                         prt("PUNCH    0x%05x thru 0x%05x\t(0x%05x bytes)",
378                             lp->args[0], lp->args[0] + lp->args[1] - 1,
379                             lp->args[1]);
380                         if (badoff >= lp->args[0] && badoff <
381                                                      lp->args[0] + lp->args[1])
382                                 prt("\t******PPPP");
383                         break;
384                 case OP_ZERO_RANGE:
385                         prt("ZERO     0x%05x thru 0x%05x\t(0x%05x bytes)",
386                             lp->args[0], lp->args[0] + lp->args[1] - 1,
387                             lp->args[1]);
388                         if (badoff >= lp->args[0] && badoff <
389                                                      lp->args[0] + lp->args[1])
390                                 prt("\t******ZZZZ");
391                         break;
392                 case OP_CLOSEOPEN:
393                 case OP_CLOSEOPEN + OP_DIRECT:
394                         prt("CLOSE/OPEN%s",
395                             lp->operation & OP_DIRECT ? "_OD" : "   ");
396                         break;
397                 case OP_SKIPPED:
398                         prt("SKIPPED (no operation)");
399                         break;
400                 default:
401                         prt("BOGUS LOG ENTRY (operation code = %d)!",
402                             lp->operation);
403                 }
404                 prt("\n");
405                 i++;
406                 if (i == LOGSIZE)
407                         i = 0;
408         }
409 }
410
411 void
412 save_buffer(char *buffer, off_t bufferlength, int fd)
413 {
414         off_t ret;
415         ssize_t byteswritten;
416
417         if (fd <= 0 || bufferlength == 0)
418                 return;
419
420         if (bufferlength > INT_MAX) {
421                 prt("fsx flaw: overflow in %s\n", __func__);
422                 exit(67);
423         }
424         if (lite) {
425                 off_t size_by_seek = lseek(fd, (off_t)0, SEEK_END);
426
427                 if (size_by_seek == (off_t)-1) {
428                         prterr("lseek eof");
429                 } else if (bufferlength > size_by_seek) {
430                         warn("%s: .fsxgood file too short... will save 0x%llx bytes instead of 0x%llx\n",
431                              __func__, (unsigned long long)size_by_seek,
432                              (unsigned long long)bufferlength);
433                         bufferlength = size_by_seek;
434                 }
435         }
436
437         ret = lseek(fd, (off_t)0, SEEK_SET);
438         if (ret == (off_t)-1)
439                 prterr("lseek 0");
440
441         byteswritten = write(fd, buffer, (size_t)bufferlength);
442         if (byteswritten != bufferlength) {
443                 if (byteswritten == -1)
444                         prterr("write");
445                 else
446                         warn("%s: short write, 0x%x bytes instead of 0x%llx\n",
447                              __func__, (unsigned int)byteswritten,
448                              (unsigned long long)bufferlength);
449         }
450 }
451
452 void
453 report_failure(int status)
454 {
455         logdump();
456
457         if (fsxgoodfd) {
458                 if (good_buf) {
459                         save_buffer(good_buf, file_size, fsxgoodfd);
460                         prt("Correct content saved for comparison\n");
461                         prt("(maybe hexdump \"%s\" vs \"%s\")\n",
462                             fname, goodfile);
463                 }
464                 close(fsxgoodfd);
465         }
466         exit(status);
467 }
468
469 #define short_at(cp) ((unsigned short)((*((unsigned char *)(cp)) << 8) | \
470                       *(((unsigned char *)(cp)) + 1)))
471
472 void
473 check_buffers(unsigned int offset, unsigned int size)
474 {
475         unsigned char c, t;
476         unsigned int i = 0;
477         unsigned int n = 0;
478         unsigned int op = 0;
479         unsigned int bad = 0;
480
481         if (memcmp(good_buf + offset, temp_buf, size) != 0) {
482                 prt("READ BAD DATA: offset = 0x%x, size = 0x%x\n",
483                     offset, size);
484                 prt("OFFSET\tGOOD\tBAD\tRANGE\n");
485                 while (size > 0) {
486                         c = good_buf[offset];
487                         t = temp_buf[i];
488                         if (c != t) {
489                                 if (n == 0) {
490                                         bad = short_at(&temp_buf[i]);
491                                         prt("%#07x\t%#06x\t%#06x", offset,
492                                             short_at(&good_buf[offset]), bad);
493                                         op = temp_buf[offset & 1 ? i + 1 : i];
494                                 }
495                                 n++;
496                                 badoff = offset;
497                         }
498                         offset++;
499                         i++;
500                         size--;
501                 }
502                 if (n) {
503                         prt("\t%#7x\n", n);
504                         if (bad)
505                                 prt("operation# (mod 256) for the bad data may be %u\n",
506                                     ((unsigned int)op & 0xff));
507                         else
508                                 prt("operation# (mod 256) for the bad data unknown, check HOLE and EXTEND ops\n");
509                 } else {
510                         prt("????????????????\n");
511                 }
512                 report_failure(110);
513         }
514 }
515
516 struct test_file *
517 get_tf(void)
518 {
519         unsigned int index = 0;
520
521         switch (fd_policy) {
522         case FD_ROTATE:
523                 index = fd_last++;
524                 break;
525         case FD_RANDOM:
526                 index = random();
527                 break;
528         case FD_SINGLE:
529                 index = 0;
530                 break;
531         default:
532                 prt("unknown policy");
533                 exit(1);
534                 break;
535         }
536         return &test_files[index % num_test_files];
537 }
538
539 void
540 assign_fd_policy(char *policy)
541 {
542         if (!strcmp(policy, "random")) {
543                 fd_policy = FD_RANDOM;
544         } else if (!strcmp(policy, "rotate")) {
545                 fd_policy = FD_ROTATE;
546         } else {
547                 prt("unknown -I policy: '%s'\n", policy);
548                 exit(1);
549         }
550 }
551
552 int
553 get_fd(void)
554 {
555         struct test_file *tf = get_tf();
556
557         return tf->fd;
558 }
559
560 static const char *my_basename(const char *path)
561 {
562         char *c = strrchr(path, '/');
563
564         return c ? c++ : path;
565 }
566
567 void
568 open_test_files(char **argv, int argc)
569 {
570         struct test_file *tf;
571         int i;
572
573         num_test_files = argc;
574         if (num_test_files == 1)
575                 fd_policy = FD_SINGLE;
576
577         test_files = calloc(num_test_files, sizeof(*test_files));
578         if (!test_files) {
579                 prterr("reallocating space for test files");
580                 exit(1);
581         }
582
583         for (i = 0, tf = test_files; i < num_test_files; i++, tf++) {
584                 tf->path = argv[i];
585                 tf->o_direct = (random() % (o_direct + 1)) ? OP_DIRECT : 0;
586                 tf->fd = open(tf->path,
587                               O_RDWR | (lite ? 0 : O_CREAT | O_TRUNC) |
588                               tf->o_direct, 0666);
589                 if (tf->fd < 0) {
590                         prterr(tf->path);
591                         exit(91);
592                 }
593         }
594
595         if (quiet || fd_policy == FD_SINGLE)
596                 return;
597
598         for (i = 0, tf = test_files; i < num_test_files; i++, tf++)
599                 prt("fd %d: %s\n", i, tf->path);
600 }
601
602 void
603 close_test_files(void)
604 {
605         int i;
606         struct test_file *tf;
607
608         for (i = 0, tf = test_files; i < num_test_files; i++, tf++) {
609                 if (close(tf->fd)) {
610                         prterr("close");
611                         report_failure(99);
612                 }
613         }
614 }
615
616 void
617 check_size(void)
618 {
619         struct stat statbuf;
620         off_t size_by_seek;
621         int fd = get_fd();
622
623         if (fstat(fd, &statbuf)) {
624                 prterr("fstat");
625                 statbuf.st_size = -1;
626         }
627         size_by_seek = lseek(fd, (off_t)0, SEEK_END);
628         if (file_size != statbuf.st_size || file_size != size_by_seek) {
629                 prt("Size error: expected 0x%llx stat 0x%llx seek 0x%llx\n",
630                     (unsigned long long)file_size,
631                     (unsigned long long)statbuf.st_size,
632                     (unsigned long long)size_by_seek);
633                 report_failure(120);
634         }
635 }
636
637 void
638 check_trunc_hack(void)
639 {
640         struct stat statbuf;
641         int fd = get_fd();
642
643         /* should not ignore ftruncate(2)'s return value */
644         if (ftruncate(fd, (off_t)0) < 0) {
645                 prterr("trunc_hack: ftruncate(0)");
646                 exit(1);
647         }
648         if (ftruncate(fd, (off_t)100000) < 0) {
649                 prterr("trunc_hack: ftruncate(100000)");
650                 exit(1);
651         }
652         if (fstat(fd, &statbuf)) {
653                 prterr("trunc_hack: fstat");
654                 statbuf.st_size = -1;
655         }
656         if (statbuf.st_size != (off_t)100000) {
657                 prt("no extend on truncate! not posix!\n");
658                 exit(130);
659         }
660         if (ftruncate(fd, 0) < 0) {
661                 prterr("trunc_hack: ftruncate(0) (2nd call)");
662                 exit(1);
663         }
664 }
665
666 void
667 output_line(struct test_file *tf, int op, unsigned int offset,
668             unsigned int size)
669 {
670         char *ops[] = {
671                 [OP_READ] = "read",
672                 [OP_WRITE] = "write",
673                 [OP_TRUNCATE] = "trunc from",
674                 [OP_MAPREAD] = "mapread",
675                 [OP_MAPWRITE] = "mapwrite",
676                 [OP_READ + OP_DIRECT] = "read_OD",
677                 [OP_WRITE + OP_DIRECT] = "write_OD",
678                 [OP_FALLOCATE] = "fallocate",
679                 [OP_PUNCH_HOLE] = "punch from",
680         };
681
682         /* W. */
683         if (!(!quiet &&
684             ((progressinterval && testcalls % progressinterval == 0) ||
685             (debug && (monitorstart == -1 ||
686             (offset + size > monitorstart &&
687             (monitorend == -1 || offset <= monitorend)))))))
688                 return;
689
690         prt("%06lu%s %lu.%06u %-10s %#08x %s %#08x\t(0x%x bytes)\n",
691             testcalls, fill_tf_buf(tf), tv.tv_sec, (int)tv.tv_usec,
692             ops[op], offset, op == OP_TRUNCATE || op == OP_PUNCH_HOLE ?
693             " to " : "thru", offset + size - 1,
694              (int)size < 0 ? -(int)size : size);
695 }
696
697 void output_debug(unsigned int offset, unsigned int size, const char *what)
698 {
699         struct timeval t;
700
701         if (!quiet && (debug > 1 && (monitorstart == -1 ||
702             (offset + size >= monitorstart &&
703              (monitorend == -1 || offset <= monitorend))))) {
704                 gettimeofday(&t, NULL);
705                 prt("       %lu.%06u %s\n", t.tv_sec, (int)t.tv_usec, what);
706         }
707 }
708
709 void
710 doflush(unsigned int offset, unsigned int size)
711 {
712         unsigned int pg_offset;
713         unsigned int map_size;
714         char *p;
715         struct test_file *tf = get_tf();
716         int fd = tf->fd;
717
718         if (tf->o_direct)
719                 return;
720
721         pg_offset = offset & page_mask;
722         map_size  = pg_offset + size;
723
724         p = (char *)mmap(0, map_size, PROT_READ | PROT_WRITE,
725                          MAP_FILE | MAP_SHARED, fd,
726                          (off_t)(offset - pg_offset));
727         if (p == (char *)-1) {
728                 prterr("mmap");
729                 report_failure(202);
730         }
731         if (msync(p, map_size, MS_INVALIDATE) != 0) {
732                 prterr("msync");
733                 report_failure(203);
734         }
735         if (munmap(p, map_size) != 0) {
736                 prterr("munmap");
737                 report_failure(204);
738         }
739         output_debug(offset, size, "flush done");
740 }
741
742 void
743 doread(unsigned int offset, unsigned int size)
744 {
745         off_t ret;
746         unsigned int iret;
747         struct test_file *tf = get_tf();
748         int fd = tf->fd;
749
750         offset -= offset % readbdy;
751         if (tf->o_direct)
752                 size -= size % readbdy;
753
754         if (size == 0) {
755                 if (!quiet && testcalls > simulatedopcount && !tf->o_direct)
756                         prt("skipping zero size read\n");
757                 log4(OP_SKIPPED, OP_READ, offset, size);
758                 return;
759         }
760         if (size + offset > file_size) {
761                 if (!quiet && testcalls > simulatedopcount)
762                         prt("skipping seek/read past end of file\n");
763                 log4(OP_SKIPPED, OP_READ, offset, size);
764                 return;
765         }
766
767         log4(OP_READ + tf->o_direct, offset, size, 0);
768
769         if (testcalls <= simulatedopcount)
770                 return;
771
772         output_line(tf, OP_READ + tf->o_direct, offset, size);
773
774         ret = lseek(fd, (off_t)offset, SEEK_SET);
775         if (ret == (off_t)-1) {
776                 prterr("lseek");
777                 report_failure(140);
778         }
779         iret = read(fd, temp_buf, size);
780         output_debug(offset, size, "read done");
781         if (iret != size) {
782                 if (iret == -1)
783                         prterr("read");
784                 else
785                         prt("short read: 0x%x bytes instead of 0x%x\n",
786                             iret, size);
787                 report_failure(141);
788         }
789         check_buffers(offset, size);
790 }
791
792 void
793 check_eofpage(char *s, unsigned int offset, char *p, int size)
794 {
795         long last_page, should_be_zero;
796
797         if (offset + size <= (file_size & ~page_mask))
798                 return;
799         /*
800          * we landed in the last page of the file
801          * test to make sure the VM system provided 0's
802          * beyond the true end of the file mapping
803          * (as required by mmap def in 1996 posix 1003.1)
804          */
805         last_page = ((long)p + (offset & page_mask) + size) & ~page_mask;
806
807         for (should_be_zero = last_page + (file_size & page_mask);
808              should_be_zero < last_page + page_size;
809              should_be_zero++)
810                 if (*(char *)should_be_zero) {
811                         prt("Mapped %s: non-zero data past EOF (0x%llx) page offset 0x%lx is 0x%04x\n",
812                             s, (long long)file_size - 1,
813                             should_be_zero & page_mask,
814                             short_at(should_be_zero));
815                         report_failure(205);
816                 }
817 }
818
819 void
820 domapread(unsigned int offset, unsigned int size)
821 {
822         unsigned int pg_offset;
823         unsigned int map_size;
824         char *p;
825         int fd;
826
827         offset -= offset % readbdy;
828         tf = get_tf();
829         fd = tf->fd;
830         if (size == 0) {
831                 if (!quiet && testcalls > simulatedopcount)
832                         prt("skipping zero size read\n");
833                 log4(OP_SKIPPED, OP_MAPREAD, offset, size);
834                 return;
835         }
836         if (size + offset > file_size) {
837                 if (!quiet && testcalls > simulatedopcount)
838                         prt("skipping seek/read past end of file\n");
839                 log4(OP_SKIPPED, OP_MAPREAD, offset, size);
840                 return;
841         }
842
843         log4(OP_MAPREAD, offset, size, 0);
844
845         if (testcalls <= simulatedopcount)
846                 return;
847
848         output_line(tf, OP_MAPREAD, offset, size);
849
850         pg_offset = offset & page_mask;
851         map_size  = pg_offset + size;
852
853         p = mmap(0, map_size, PROT_READ, MAP_FILE | MAP_SHARED, fd,
854                  (off_t)(offset - pg_offset));
855         if (p == MAP_FAILED) {
856                 prterr("mmap");
857                 report_failure(190);
858         }
859         output_debug(offset, size, "mmap done");
860         if (setjmp(jmpbuf) == 0) {
861                 jmpbuf_good = 1;
862                 memcpy(temp_buf, p + pg_offset, size);
863                 check_eofpage("Read", offset, p, size);
864                 jmpbuf_good = 0;
865         } else {
866                 report_failure(1901);
867         }
868         output_debug(offset, size, "memcpy done");
869         if (munmap(p, map_size) != 0) {
870                 prterr("munmap");
871                 report_failure(191);
872         }
873         output_debug(offset, size, "munmap done");
874
875         check_buffers(offset, size);
876 }
877
878 void
879 gendata(char *original_buf, char *good_buf, unsigned int offset,
880         unsigned int size)
881 {
882         while (size--) {
883                 good_buf[offset] = testcalls % 256;
884                 if (offset % 2)
885                         good_buf[offset] += original_buf[offset];
886                 offset++;
887         }
888 }
889
890 void
891 dowrite(unsigned int offset, unsigned int size)
892 {
893         off_t ret;
894         unsigned int iret;
895         int fd;
896
897         tf = get_tf();
898         fd = tf->fd;
899         offset -= offset % writebdy;
900         if (tf->o_direct)
901                 size -= size % writebdy;
902         if (size == 0) {
903                 if (!quiet && testcalls > simulatedopcount && !tf->o_direct)
904                         prt("skipping zero size write\n");
905                 log4(OP_SKIPPED, OP_WRITE, offset, size);
906                 return;
907         }
908
909         log4(OP_WRITE + tf->o_direct, offset, size, file_size);
910
911         gendata(original_buf, good_buf, offset, size);
912         if (file_size < offset + size) {
913                 if (file_size < offset)
914                         memset(good_buf + file_size, '\0', offset - file_size);
915                 file_size = offset + size;
916                 if (lite) {
917                         warn("Lite file size bug in fsx!");
918                         report_failure(149);
919                 }
920         }
921
922         if (testcalls <= simulatedopcount)
923                 return;
924
925         output_line(tf, OP_WRITE + tf->o_direct, offset, size);
926
927         ret = lseek(fd, (off_t)offset, SEEK_SET);
928         if (ret == (off_t)-1) {
929                 prterr("lseek");
930                 report_failure(150);
931         }
932         iret = write(fd, good_buf + offset, size);
933         output_debug(offset, size, "write done");
934         if (iret != size) {
935                 if (iret == -1)
936                         prterr("write");
937                 else
938                         prt("short write: 0x%x bytes instead of 0x%x\n",
939                             iret, size);
940                 report_failure(151);
941         }
942         if (do_fsync) {
943                 if (fsync(fd)) {
944                         prt("fsync() failed: %s\n", strerror(errno));
945                         report_failure(152);
946                 }
947                 output_debug(offset, size, "fsync done");
948         }
949         if (flush) {
950                 doflush(offset, size);
951                 output_debug(offset, size, "flush done");
952         }
953 }
954
955 void
956 domapwrite(unsigned int offset, unsigned int size)
957 {
958         unsigned int pg_offset;
959         unsigned int map_size;
960         off_t cur_filesize;
961         char *p;
962         int fd;
963
964         tf = get_tf();
965         fd = tf->fd;
966         offset -= offset % writebdy;
967         if (size == 0) {
968                 if (!quiet && testcalls > simulatedopcount)
969                         prt("skipping zero size write\n");
970                 log4(OP_SKIPPED, OP_MAPWRITE, offset, size);
971                 return;
972         }
973         cur_filesize = file_size;
974
975         log4(OP_MAPWRITE, offset, size, 0);
976
977         gendata(original_buf, good_buf, offset, size);
978         if (file_size < offset + size) {
979                 if (file_size < offset)
980                         memset(good_buf + file_size, '\0', offset - file_size);
981                 file_size = offset + size;
982                 if (lite) {
983                         warn("Lite file size bug in fsx!");
984                         report_failure(200);
985                 }
986         }
987
988         if (testcalls <= simulatedopcount)
989                 return;
990
991         output_line(tf, OP_MAPWRITE, offset, size);
992
993         if (file_size > cur_filesize) {
994                 if (ftruncate(fd, file_size) == -1) {
995                         prterr("ftruncate");
996                         exit(201);
997                 }
998                 output_debug(offset, size, "truncate done");
999         }
1000         pg_offset = offset & page_mask;
1001         map_size  = pg_offset + size;
1002
1003         p = mmap(0, map_size, PROT_READ | PROT_WRITE, MAP_FILE | MAP_SHARED,
1004                  fd, (off_t)(offset - pg_offset));
1005         if (p == MAP_FAILED) {
1006                 prterr("mmap");
1007                 report_failure(202);
1008         }
1009         output_debug(offset, map_size, "mmap done");
1010         if (setjmp(jmpbuf) == 0) {
1011                 jmpbuf_good = 1;
1012                 memcpy(p + pg_offset, good_buf + offset, size);
1013                 if (msync(p, map_size, MS_SYNC) != 0) {
1014                         prterr("msync");
1015                         report_failure(203);
1016                 }
1017                 check_eofpage("Write", offset, p, size);
1018                 jmpbuf_good = 0;
1019         } else {
1020                 report_failure(2021);
1021         }
1022         output_debug(offset, map_size, "msync done");
1023         if (munmap(p, map_size) != 0) {
1024                 prterr("munmap");
1025                 report_failure(204);
1026         }
1027         output_debug(offset, map_size, "munmap done");
1028 }
1029
1030 void
1031 dotruncate(unsigned int size)
1032 {
1033         int oldsize = file_size;
1034         int fd;
1035
1036         tf = get_tf();
1037         fd = tf->fd;
1038         size -= size % truncbdy;
1039         if (size > biggest) {
1040                 biggest = size;
1041                 if (!quiet && testcalls > simulatedopcount)
1042                         prt("truncating to largest ever: 0x%x\n", size);
1043         }
1044
1045         log4(OP_TRUNCATE, size, (unsigned int)file_size, 0);
1046
1047         if (size > file_size)
1048                 memset(good_buf + file_size, '\0', size - file_size);
1049         file_size = size;
1050
1051         if (testcalls <= simulatedopcount)
1052                 return;
1053
1054         output_line(tf, OP_TRUNCATE, oldsize, size - oldsize);
1055
1056         if (ftruncate(fd, (off_t)size) == -1) {
1057                 prt("ftruncate: 0x%x\n", size);
1058                 prterr("ftruncate");
1059                 report_failure(160);
1060         }
1061         output_debug(size, 0, "truncate done");
1062 }
1063
1064 void
1065 do_punch_hole(unsigned int offset, unsigned int length)
1066 {
1067         int max_offset = 0;
1068         int max_len = 0;
1069         int mode = FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE;
1070         int fd;
1071
1072         tf = get_tf();
1073         fd = tf->fd;
1074         if (length == 0) {
1075                 if (!quiet && testcalls > simulatedopcount) {
1076                         prt("skipping zero length punch hole\n");
1077                         log4(OP_SKIPPED, OP_PUNCH_HOLE, offset, length);
1078                 }
1079                 return;
1080         }
1081
1082         if (file_size <= (loff_t)offset) {
1083                 if (!quiet && testcalls > simulatedopcount) {
1084                         prt("skipping hole punch off the end of the file\n");
1085                         log4(OP_SKIPPED, OP_PUNCH_HOLE, offset, length);
1086                 }
1087                 return;
1088         }
1089
1090         log4(OP_PUNCH_HOLE, offset, length, 0);
1091
1092         if (testcalls <= simulatedopcount)
1093                 return;
1094
1095         output_line(tf, OP_PUNCH_HOLE, offset, length);
1096         if (fallocate(fd, mode, (loff_t)offset, (loff_t)length) == -1) {
1097                 prt("punch hole: %x to %x\n", offset, length);
1098                 prterr("fallocate");
1099                 report_failure(161);
1100         }
1101         output_debug(offset, length, "zero_range done");
1102
1103         max_offset = offset < file_size ? offset : file_size;
1104         max_len = max_offset + length <= file_size ? length :
1105                         file_size - max_offset;
1106         memset(good_buf + max_offset, '\0', max_len);
1107 }
1108
1109 void
1110 do_zero_range(unsigned int offset, unsigned int length)
1111 {
1112         unsigned int end_offset;
1113         int mode = FALLOC_FL_ZERO_RANGE;
1114         int keep_size;
1115         int fd;
1116
1117         tf = get_tf();
1118         fd = tf->fd;
1119         if (length == 0) {
1120                 if (!quiet && testcalls > simulatedopcount) {
1121                         prt("skipping zero length zero range\n");
1122                         log4(OP_SKIPPED, OP_ZERO_RANGE, offset, length);
1123                 }
1124                 return;
1125         }
1126
1127         keep_size = random() % 2;
1128
1129         end_offset = keep_size ? 0 : offset + length;
1130
1131         if (end_offset > biggest) {
1132                 biggest = end_offset;
1133                 if (!quiet && testcalls > simulatedopcount)
1134                         prt("zero_range to largest ever: 0x%x\n", end_offset);
1135         }
1136
1137         /*
1138          * last arg matches fallocate string array index in logdump:
1139          * 0: allocate past EOF
1140          * 1: extending prealloc
1141          * 2: interior prealloc
1142          */
1143         log4(OP_ZERO_RANGE, offset, length,
1144              (end_offset > file_size) ? (keep_size ? 0 : 1) : 2);
1145
1146         if (testcalls <= simulatedopcount)
1147                 return;
1148
1149         output_line(tf, OP_TRUNCATE, offset, length);
1150
1151         if (fallocate(fd, mode, (loff_t)offset, (loff_t)length) == -1) {
1152                 prt("pzero range: %x to %x\n", offset, length);
1153                 prterr("fallocate");
1154                 report_failure(161);
1155         }
1156         output_debug(offset, length, "zero_range done");
1157
1158         memset(good_buf + offset, '\0', length);
1159 }
1160
1161 /*
1162  * fallocate is basically a no-op unless extending,
1163  * then a lot like a truncate
1164  */
1165 void
1166 do_preallocate(unsigned int offset, unsigned int length)
1167 {
1168         off_t end_offset;
1169         int keep_size;
1170         int fd;
1171         struct stat statbufs;
1172
1173         tf = get_tf();
1174         fd = tf->fd;
1175         if (length == 0) {
1176                 if (!quiet && testcalls > simulatedopcount)
1177                         prt("skipping zero length fallocate\n");
1178                 log4(OP_SKIPPED, OP_FALLOCATE, offset, length);
1179                 return;
1180         }
1181
1182         keep_size = fl_keep_size && (random() % 2);
1183
1184         end_offset = offset + length;
1185         if (end_offset > biggest) {
1186                 biggest = end_offset;
1187                 if (!quiet && testcalls > simulatedopcount)
1188                         prt("fallocating to largest ever: 0x%jx\n", end_offset);
1189         }
1190
1191         /*
1192          * last arg matches fallocate string array index in logdump:
1193          * 0: allocate past EOF
1194          * 1: extending prealloc
1195          * 2: interior prealloc
1196          */
1197         log4(OP_FALLOCATE, offset, length, (end_offset > file_size) ?
1198              (keep_size ? 0 : 1) : 2);
1199
1200         if (end_offset > file_size && !keep_size) {
1201                 memset(good_buf + file_size, '\0', end_offset - file_size);
1202                 file_size = end_offset;
1203         }
1204
1205         if (testcalls <= simulatedopcount)
1206                 return;
1207
1208         fstat(fd, &statbufs);
1209         if (fallocate(fd, keep_size ? FALLOC_FL_KEEP_SIZE : 0, (loff_t)offset,
1210                       (loff_t)length) == -1) {
1211                 prt("fallocate: %x to %x\n", offset, length);
1212                 prterr("fallocate");
1213                 report_failure(161);
1214         }
1215         output_line(tf, OP_FALLOCATE, offset, length);
1216         output_debug(offset, length, "fallocate done");
1217 }
1218
1219 void
1220 writefileimage()
1221 {
1222         ssize_t iret;
1223         int fd = get_fd();
1224
1225         if (lseek(fd, (off_t)0, SEEK_SET) == (off_t)-1) {
1226                 prterr("lseek");
1227                 report_failure(171);
1228         }
1229         iret = write(fd, good_buf, file_size);
1230         if ((off_t)iret != file_size) {
1231                 if (iret == -1)
1232                         prterr("write");
1233                 else
1234                         prt("short write: 0x%lx bytes instead of 0x%llx\n",
1235                             (unsigned long)iret, (unsigned long long)file_size);
1236                 report_failure(172);
1237         }
1238         if (lite ? 0 : ftruncate(fd, file_size) == -1) {
1239                 prt("ftruncate2: %llx\n", (unsigned long long)file_size);
1240                 prterr("ftruncate");
1241                 report_failure(173);
1242         }
1243 }
1244
1245 void
1246 docloseopen(void)
1247 {
1248         int direct = 0;
1249         const char *tf_num = "";
1250
1251         if (testcalls <= simulatedopcount)
1252                 return;
1253
1254         tf = get_tf();
1255         direct = (random() % (o_direct + 1)) ? OP_DIRECT : 0;
1256         log4(OP_CLOSEOPEN + direct, file_size, (unsigned int)file_size, 0);
1257
1258         if (fd_policy != FD_SINGLE)
1259                 tf_num = fill_tf_buf(tf);
1260
1261         if (debug)
1262                 prt("%06lu %lu.%06u %sclose/open%s\n", testcalls, tv.tv_sec,
1263                     (int)tv.tv_usec, tf_num, direct ? "(O_DIRECT)" : "");
1264         if (close(tf->fd))
1265                 report_failure(180);
1266
1267         output_debug(monitorstart, 0, "close done");
1268         tf->o_direct = direct;
1269         tf->fd = open(tf->path, O_RDWR | tf->o_direct, 0);
1270         if (tf->fd < 0) {
1271                 prterr(tf->o_direct ? "open(O_DIRECT)" : "open");
1272                 report_failure(181);
1273         }
1274         output_debug(monitorstart, 0,
1275                      tf->o_direct ? "open(O_DIRECT) done" : "open done");
1276 }
1277
1278 #define TRIM_OFF_LEN(off, len, size)    \
1279 do {                                    \
1280         if (size)                       \
1281                 (off) %= (size);        \
1282         else                            \
1283                 (off) = 0;              \
1284         if ((off) + (len) > (size))     \
1285                 (len) = (size) - (off); \
1286 } while (0)
1287
1288 void
1289 test(void)
1290 {
1291         unsigned long offset;
1292         unsigned long size = maxoplen;
1293         unsigned long rv = random();
1294         unsigned long op;
1295         int closeopen = 0;
1296
1297         if (simulatedopcount > 0 && testcalls == simulatedopcount)
1298                 writefileimage();
1299
1300         testcalls++;
1301
1302         if (closeprob)
1303                 closeopen = (rv >> 3) < (1 << 28) / closeprob;
1304
1305         if (debugstart > 0 && testcalls >= debugstart)
1306                 debug = 1;
1307
1308         if (!quiet && testcalls < simulatedopcount && testcalls % 100000 == 0)
1309                 prt("%lu...\n", testcalls);
1310
1311         offset = random();
1312         if (randomoplen)
1313                 size = random() % (maxoplen + 1);
1314
1315         /* calculate appropriate op to run */
1316         if (lite)
1317                 op = rv % OP_MAX_LITE;
1318         else
1319                 op = rv % OP_MAX_FULL;
1320
1321         switch (op) {
1322         case OP_MAPREAD:
1323                 if (!mapped_reads)
1324                         op = OP_READ;
1325                 break;
1326         case OP_MAPWRITE:
1327                 if (!mapped_writes)
1328                         op = OP_WRITE;
1329                 break;
1330         case OP_FALLOCATE:
1331                 if (!fallocate_calls) {
1332                         log4(OP_SKIPPED, OP_FALLOCATE, offset, size);
1333                         goto out;
1334                 }
1335                 break;
1336         case OP_PUNCH_HOLE:
1337                 if (!punch_hole_calls) {
1338                         log4(OP_SKIPPED, OP_PUNCH_HOLE, offset, size);
1339                         goto out;
1340                 }
1341                 break;
1342         case OP_ZERO_RANGE:
1343                 if (!zero_range_calls) {
1344                         log4(OP_SKIPPED, OP_ZERO_RANGE, offset, size);
1345                         goto out;
1346                 }
1347                 break;
1348         }
1349
1350         switch (op) {
1351         case OP_READ:
1352                 TRIM_OFF_LEN(offset, size, file_size);
1353                 doread(offset, size);
1354                 break;
1355         case OP_WRITE:
1356                 TRIM_OFF_LEN(offset, size, maxfilelen);
1357                 dowrite(offset, size);
1358                 break;
1359         case OP_MAPREAD:
1360                 TRIM_OFF_LEN(offset, size, file_size);
1361                 domapread(offset, size);
1362                 break;
1363         case OP_MAPWRITE:
1364                 TRIM_OFF_LEN(offset, size, maxfilelen);
1365                 domapwrite(offset, size);
1366                 break;
1367         case OP_TRUNCATE:
1368                 if (!style)
1369                         size = random() % maxfilelen;
1370                 dotruncate(size);
1371                 break;
1372         case OP_FALLOCATE:
1373                 TRIM_OFF_LEN(offset, size, maxfilelen);
1374                 do_preallocate(offset, size);
1375                 break;
1376         case OP_PUNCH_HOLE:
1377                 TRIM_OFF_LEN(offset, size, file_size);
1378                 do_punch_hole(offset, size);
1379                 break;
1380         case OP_ZERO_RANGE:
1381                 TRIM_OFF_LEN(offset, size, file_size);
1382                 do_zero_range(offset, size);
1383                 break;
1384         case OP_CLOSEOPEN:
1385                 if (closeopen)
1386                         docloseopen();
1387                 break;
1388         default:
1389                 prterr("unknown operation %d: Operation not supported");
1390                 report_failure(42);
1391                 break;
1392         }
1393
1394 out:
1395         if (sizechecks && testcalls > simulatedopcount)
1396                 check_size();
1397 }
1398
1399 void
1400 segv(int sig)
1401 {
1402         if (jmpbuf_good) {
1403                 jmpbuf_good = 0;
1404                 longjmp(jmpbuf, 1);
1405         }
1406         report_failure(9999);
1407 }
1408
1409 void
1410 cleanup(sig)
1411         int     sig;
1412 {
1413         if (sig)
1414                 prt("signal %d\n", sig);
1415         prt("testcalls = %lu\n", testcalls);
1416         exit(sig);
1417 }
1418
1419 void
1420 usage(void)
1421 {
1422         fprintf(stdout,
1423                 "usage: fsx [-dfnqFLOW] [-b opnum] [-c Prob] [-l flen] [-m start:end] [-o oplen] [-p progressinterval] [-r readbdy] [-s style] [-t truncbdy] [-w writebdy] [-D startingop] [ -I random|rotate ] [-N numops] [-P dirpath] [-S seed] [-Z [prob]] fname [additional paths to fname..]\n"
1424 "       -b opnum: beginning operation number (default 1)\n"
1425 "       -c P: 1 in P chance of file close+open at each op (default infinity)\n"
1426 "       -d: debug output for all operations [-d -d = more debugging]\n"
1427 "       -f flush and invalidate cache after I/O\n"
1428 /* OSX: -d duration: number of hours for the tool to run\n\ */
1429 /* OSX: -e: tests using an extended attribute rather than a file\n\ */
1430 /* OSX: -f forkname: test the named fork of fname\n\ */
1431 /* OSX: -g logpath: path for .fsxlog file\n\ */
1432 /* OSX: -h: write 0s instead of creating holes (i.e. sparse file)\n\ */
1433 /* OSX: -i: interactive mode, hit return before performing each operation\n\ */
1434 "       -l flen: the upper bound on file size (default 262144)\n"
1435 "       -m startop:endop: monitor (print debug output) specified byte range\n"
1436 "          (default 0:infinity)\n"
1437 "       -n: no verifications of file size\n"
1438 "       -o oplen: the upper bound on operation size (default 65536)\n"
1439 "       -p progressinterval: debug output at specified operation interval\n"
1440 "       -q: quieter operation\n"
1441 "       -r readbdy: %1$u would make reads page aligned (default 1)\n"
1442 "       -s style: 1 gives smaller truncates (default 0)\n"
1443 "       -t truncbdy: %1$u would make truncates page aligned (default 1)\n"
1444 "       -w writebdy: %1$u would make writes page aligned (default 1)\n"
1445 /* XFS: -x: preallocate file space before starting, XFS only (default 0)\n\ */
1446 "       -y synchronize changes to a file\n"
1447 /* OSX: -v: debug output for all operations\n\ */
1448 /* XFS: -A: Use the AIO system calls\n" */
1449 /* OSX: -C mix cached and un-cached read/write ops\n\ */
1450 "       -D startingop: debug output starting at specified operation\n"
1451 "       -F: Do not use fallocate (preallocation) calls\n"
1452 /* OSX: -G logsize: #entries in oplog (default 1024)\n\ */
1453 #ifdef FALLOC_FL_PUNCH_HOLE
1454 "       -H: Do not use punch hole calls\n"
1455 #endif
1456 #ifdef FALLOC_FL_ZERO_RANGE
1457 "       -z: Do not use zero range calls\n"
1458 #endif
1459 /* XFS: -C: Do not use collapse range calls\n\ */
1460 "       -I [rotate|random]: When multiple paths to the file are given,\n"
1461 "           each operation uses a different path.  Iterate through them in\n"
1462 "           order with 'rotate' or chose them at 'random'.  (default random)\n"
1463 "       -L: fsxLite - no file creations & no file size changes\n"
1464 /* OSX: -I: start interactive mode since operation opnum\n\ */
1465 /* OSX: -M: slow motion mode, wait 1 second before each op\n\ */
1466 "       -N numops: total # operations to do (default infinity)\n"
1467 "       -O: use oplen (see -o flag) for every op (default random)\n"
1468 "       -P: save .fsxlog and .fsxgood files in dirpath (default ./)\n"
1469 "       -R: read() system calls only (mapped reads disabled)\n"
1470 "       -S seed: for random # generator (default 1) 0 gets timestamp\n"
1471 /* OSX: -T datasize: atomic data element write size [1,2,4] (default 4)\n\ */
1472 "       -W: mapped write operations DISabled\n"
1473 "       -Z[P]: O_DIRECT file IO [1 in P chance for each open] (default off)\n"
1474 "       fname: this filename is REQUIRED (no default)\n",
1475         page_size);
1476         exit(90);
1477 }
1478
1479 int
1480 getnum(char *s, char **e)
1481 {
1482         int ret = -1;
1483
1484         *e = (char *)0;
1485         ret = strtol(s, e, 0);
1486         if (*e)
1487                 switch (**e) {
1488                 case 'b':
1489                 case 'B':
1490                         ret *= 512;
1491                         *e = *e + 1;
1492                         break;
1493                 case 'k':
1494                 case 'K':
1495                         ret *= 1024;
1496                         *e = *e + 1;
1497                         break;
1498                 case 'm':
1499                 case 'M':
1500                         ret *= 1024 * 1024;
1501                         *e = *e + 1;
1502                         break;
1503                 case 'w':
1504                 case 'W':
1505                         ret *= 4;
1506                         *e = *e + 1;
1507                         break;
1508                 }
1509         return (ret);
1510 }
1511
1512 int
1513 test_fallocate(int mode)
1514 {
1515         int ret = 0;
1516         int fd = get_fd();
1517
1518         if (!lite) {
1519                 /* Must go more than a page away so let's go 4M to be sure */
1520                 if (fallocate(fd, mode, 0, 4096*1024) && errno == EOPNOTSUPP) {
1521                         if (!quiet)
1522                                 warn("%s: filesystem does not support fallocate mode 0x%x, disabling!",
1523                                      __func__, mode);
1524                 } else {
1525                         ret = 1;
1526                 }
1527
1528                 /* Always call ftruncate since file size might be adjusted
1529                  * by fallocate even on error
1530                  */
1531                 if (ftruncate(fd, 0) == -1)
1532                         warn("ftruncate to 0 size failed");
1533         }
1534         return ret;
1535 }
1536
1537 int
1538 main(int argc, char **argv)
1539 {
1540         int i, style, ch;
1541         char *endp;
1542         int dirpath = 0;
1543
1544         goodfile[0] = 0;
1545         logfile[0] = 0;
1546
1547         page_size = getpagesize();
1548         page_mask = page_size - 1;
1549
1550         setvbuf(stdout, (char *)0, _IOLBF, 0); /* line buffered stdout */
1551
1552         while ((ch = getopt(argc, argv,
1553                             "b:c:dfl:m:no:p:qr:s:t:w:xyzD:FHI:LN:OP:RS:WZ::"))
1554                != EOF)
1555                 switch (ch) {
1556                 case 'b':
1557                         simulatedopcount = getnum(optarg, &endp);
1558                         if (!quiet)
1559                                 fprintf(stdout, "Will begin at operation %ld\n",
1560                                         simulatedopcount);
1561                         if (simulatedopcount == 0)
1562                                 usage();
1563                         simulatedopcount -= 1;
1564                         break;
1565                 case 'c':
1566                         closeprob = getnum(optarg, &endp);
1567                         if (!quiet)
1568                                 fprintf(stdout,
1569                                         "Chance of close/open is 1 in %d\n",
1570                                         closeprob);
1571                         if (closeprob <= 0)
1572                                 usage();
1573                         break;
1574                 case 'd':
1575                         debug++;
1576                         break;
1577                 case 'f':
1578                         flush = 1;
1579                         break;
1580                 case 'l':
1581                         maxfilelen = getnum(optarg, &endp);
1582                         if (maxfilelen <= 0)
1583                                 usage();
1584                         break;
1585                 case 'm':
1586                         monitorstart = getnum(optarg, &endp);
1587                         if (monitorstart < 0)
1588                                 usage();
1589                         if (!endp || *endp++ != ':')
1590                                 usage();
1591                         monitorend = getnum(endp, &endp);
1592                         if (monitorend < 0)
1593                                 usage();
1594                         if (monitorend == 0)
1595                                 monitorend = -1; /* aka infinity */
1596                         debug = 1;
1597                 case 'n':
1598                         sizechecks = 0;
1599                         break;
1600                 case 'o':
1601                         maxoplen = getnum(optarg, &endp);
1602                         if (maxoplen <= 0)
1603                                 usage();
1604                         break;
1605                 case 'p':
1606                         progressinterval = getnum(optarg, &endp);
1607                         if (progressinterval <= 0)
1608                                 usage();
1609                         break;
1610                 case 'q':
1611                         quiet = 1;
1612                         break;
1613                 case 'r':
1614                         readbdy = getnum(optarg, &endp);
1615                         if (readbdy <= 0)
1616                                 usage();
1617                         break;
1618                 case 's':
1619                         style = getnum(optarg, &endp);
1620                         if (style < 0 || style > 1)
1621                                 usage();
1622                         break;
1623                 case 't':
1624                         truncbdy = getnum(optarg, &endp);
1625                         if (truncbdy <= 0)
1626                                 usage();
1627                         break;
1628                 case 'w':
1629                         writebdy = getnum(optarg, &endp);
1630                         if (writebdy <= 0)
1631                                 usage();
1632                         break;
1633                 case 'y':
1634                         do_fsync = 1;
1635                         break;
1636                 case 'D':
1637                         debugstart = getnum(optarg, &endp);
1638                         if (debugstart < 1)
1639                                 usage();
1640                         break;
1641                 case 'F':
1642                         fallocate_calls = 0;
1643                         break;
1644                 case 'H':
1645                         punch_hole_calls = 0;
1646                         break;
1647                 case 'z':
1648                         zero_range_calls = 0;
1649                         break;
1650                 case 'I':
1651                         assign_fd_policy(optarg);
1652                         break;
1653                 case 'L':
1654                         lite = 1;
1655                         break;
1656                 case 'N':
1657                         numops = getnum(optarg, &endp);
1658                         if (numops < 0)
1659                                 usage();
1660                         break;
1661                 case 'O':
1662                         randomoplen = 0;
1663                         break;
1664                 case 'P':
1665                         strncpy(goodfile, optarg, sizeof(goodfile) - 1);
1666                         strncat(goodfile, "/", PATH_MAX - strlen(goodfile) - 1);
1667                         strncpy(logfile, optarg, sizeof(logfile) - 1);
1668                         strncat(logfile, "/", PATH_MAX - strlen(logfile) - 1);
1669                         dirpath = 1;
1670                         break;
1671                 case 'R':
1672                         mapped_reads = 0;
1673                         break;
1674                 case 'S':
1675                         seed = getnum(optarg, &endp);
1676                         if (seed == 0)
1677                                 seed = time(0) % 10000;
1678                         if (!quiet)
1679                                 fprintf(stdout, "Seed set to %d\n", seed);
1680                         if (seed < 0)
1681                                 usage();
1682                         break;
1683                 case 'W':
1684                         mapped_writes = 0;
1685                         if (!quiet)
1686                                 fprintf(stdout, "mapped writes DISABLED\n");
1687                         break;
1688                 case 'Z':
1689                         if (optarg)
1690                                 o_direct = getnum(optarg, &endp);
1691                         if (!optarg || o_direct == 0)
1692                                 o_direct = 1;
1693                         break;
1694                 default:
1695                         usage();
1696                         /* NOTREACHED */
1697                 }
1698         argc -= optind;
1699         argv += optind;
1700         if (argc < 1)
1701                 usage();
1702         fname = argv[0];
1703
1704         signal(SIGHUP, cleanup);
1705         signal(SIGINT, cleanup);
1706         signal(SIGPIPE, cleanup);
1707         signal(SIGALRM, cleanup);
1708         signal(SIGTERM, cleanup);
1709         signal(SIGXCPU, cleanup);
1710         signal(SIGXFSZ, cleanup);
1711         signal(SIGVTALRM, cleanup);
1712         signal(SIGUSR1, cleanup);
1713         signal(SIGUSR2, cleanup);
1714         signal(SIGBUS, segv);
1715         signal(SIGSEGV, segv);
1716
1717         initstate(seed, state, 256);
1718         setstate(state);
1719
1720         open_test_files(argv, argc);
1721
1722         strncat(goodfile, dirpath ? my_basename(fname) : fname, 256);
1723         strncat(goodfile, ".fsxgood", PATH_MAX - strlen(goodfile) - 1);
1724         fsxgoodfd = open(goodfile, O_RDWR | O_CREAT | O_TRUNC, 0666);
1725         if (fsxgoodfd < 0) {
1726                 prterr(goodfile);
1727                 exit(92);
1728         }
1729         strncat(logfile, dirpath ? my_basename(fname) : fname, 256);
1730         strncat(logfile, ".fsxlog", PATH_MAX - strlen(logfile) - 1);
1731         fsxlogf = fopen(logfile, "w");
1732         if (!fsxlogf) {
1733                 prterr(logfile);
1734                 exit(93);
1735         }
1736         if (lite) {
1737                 off_t ret;
1738                 int fd = get_fd();
1739
1740                 maxfilelen = lseek(fd, (off_t)0, SEEK_END);
1741                 file_size = maxfilelen;
1742                 if (file_size == (off_t)-1) {
1743                         prterr(fname);
1744                         warn("%s: lseek eof", __func__);
1745                         exit(94);
1746                 }
1747                 ret = lseek(fd, (off_t)0, SEEK_SET);
1748                 if (ret == (off_t)-1) {
1749                         prterr(fname);
1750                         warn("%s: lseek 0", __func__);
1751                         exit(95);
1752                 }
1753         }
1754         original_buf = (char *)malloc(maxfilelen);
1755         if (!original_buf)
1756                 exit(96);
1757         for (i = 0; i < maxfilelen; i++)
1758                 original_buf[i] = random() % 256;
1759         if (o_direct) {
1760                 int ret;
1761
1762                 ret = posix_memalign((void **)&good_buf, writebdy, maxfilelen);
1763                 if (ret) {
1764                         prt("%s: posix_memalign failed: %s\n", __func__,
1765                             strerror(ret));
1766                         exit(96);
1767                 }
1768
1769                 ret = posix_memalign((void **)&temp_buf, readbdy, maxoplen);
1770                 if (ret) {
1771                         prt("%s: posix_memalign failed: %s\n", __func__,
1772                             strerror(ret));
1773                         exit(97);
1774                 }
1775         } else {
1776                 good_buf = malloc(maxfilelen);
1777                 if (!good_buf) {
1778                         prt("malloc failed.\n");
1779                         exit(98);
1780                 }
1781
1782                 temp_buf = malloc(maxoplen);
1783                 if (!temp_buf) {
1784                         prt("malloc failed.\n");
1785                         exit(99);
1786                 }
1787         }
1788         memset(good_buf, 0, maxfilelen);
1789         memset(temp_buf, 0, maxoplen);
1790
1791         if (lite) {     /* zero entire existing file */
1792                 ssize_t written;
1793                 int fd = get_fd();
1794
1795                 written = write(fd, good_buf, (size_t)maxfilelen);
1796                 if (written != maxfilelen) {
1797                         if (written == -1) {
1798                                 prterr(fname);
1799                                 warn("%s: error on write", __func__);
1800                         } else {
1801                                 warn("%s: short write, 0x%x bytes instead of 0x%lx\n",
1802                                      __func__, (unsigned int)written,
1803                                      maxfilelen);
1804                         }
1805                         exit(98);
1806                 }
1807         } else {
1808                 check_trunc_hack();
1809         }
1810
1811         if (fallocate_calls)
1812                 fallocate_calls = test_fallocate(0);
1813
1814         if (punch_hole_calls)
1815                 punch_hole_calls = test_fallocate(FALLOC_FL_PUNCH_HOLE |
1816                                                   FALLOC_FL_KEEP_SIZE);
1817
1818         if (zero_range_calls)
1819                 zero_range_calls = test_fallocate(FALLOC_FL_ZERO_RANGE);
1820
1821         fl_keep_size = test_fallocate(FALLOC_FL_KEEP_SIZE);
1822
1823         while (numops == -1 || numops--)
1824                 test();
1825
1826         close_test_files();
1827         prt("All operations completed A-OK!\n");
1828
1829         free(original_buf);
1830         free(good_buf);
1831         free(temp_buf);
1832
1833         return 0;
1834 }