fsstress: consistently index the ops array by OP_ type
[xfstests-dev.git] / ltp / fsstress.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (c) 2000-2002 Silicon Graphics, Inc.
4  * All Rights Reserved.
5  */
6
7 #include <linux/fs.h>
8 #include <setjmp.h>
9 #include <sys/uio.h>
10 #include <stddef.h>
11 #include <stdbool.h>
12 #include <string.h>
13 #include "global.h"
14
15 #ifdef HAVE_BTRFSUTIL_H
16 #include <btrfsutil.h>
17 #endif
18 #ifdef HAVE_LINUX_FIEMAP_H
19 #include <linux/fiemap.h>
20 #endif
21 #ifdef HAVE_SYS_PRCTL_H
22 #include <sys/prctl.h>
23 #endif
24 #ifdef AIO
25 #include <libaio.h>
26 #define AIO_ENTRIES     1
27 io_context_t    io_ctx;
28 #endif
29 #ifdef URING
30 #include <liburing.h>
31 #define URING_ENTRIES   1
32 struct io_uring ring;
33 bool have_io_uring;                     /* to indicate runtime availability */
34 #endif
35 #include <sys/syscall.h>
36 #include <sys/xattr.h>
37
38 #ifndef FS_IOC_GETFLAGS
39 #define FS_IOC_GETFLAGS                 _IOR('f', 1, long)
40 #endif
41 #ifndef FS_IOC_SETFLAGS
42 #define FS_IOC_SETFLAGS                 _IOW('f', 2, long)
43 #endif
44
45 #include <math.h>
46 #define XFS_ERRTAG_MAX          17
47 #define XFS_IDMODULO_MAX        31      /* user/group IDs (1 << x)  */
48 #define XFS_PROJIDMODULO_MAX    16      /* project IDs (1 << x)     */
49 #ifndef IOV_MAX
50 #define IOV_MAX 1024
51 #endif
52
53 #ifndef HAVE_RENAMEAT2
54 #if !defined(SYS_renameat2) && defined(__x86_64__)
55 #define SYS_renameat2 316
56 #endif
57
58 #if !defined(SYS_renameat2) && defined(__i386__)
59 #define SYS_renameat2 353
60 #endif
61
62 static int renameat2(int dfd1, const char *path1,
63                      int dfd2, const char *path2,
64                      unsigned int flags)
65 {
66 #ifdef SYS_renameat2
67         return syscall(SYS_renameat2, dfd1, path1, dfd2, path2, flags);
68 #else
69         errno = ENOSYS;
70         return -1;
71 #endif
72 }
73 #endif
74
75 #ifndef RENAME_NOREPLACE
76 #define RENAME_NOREPLACE        (1 << 0)        /* Don't overwrite target */
77 #endif
78 #ifndef RENAME_EXCHANGE
79 #define RENAME_EXCHANGE         (1 << 1)        /* Exchange source and dest */
80 #endif
81 #ifndef RENAME_WHITEOUT
82 #define RENAME_WHITEOUT         (1 << 2)        /* Whiteout source */
83 #endif
84
85 #define FILELEN_MAX             (32*4096)
86
87 typedef enum {
88         OP_AFSYNC,
89         OP_ALLOCSP,
90         OP_AREAD,
91         OP_ATTR_REMOVE,
92         OP_ATTR_SET,
93         OP_AWRITE,
94         OP_BULKSTAT,
95         OP_BULKSTAT1,
96         OP_CHOWN,
97         OP_CLONERANGE,
98         OP_COPYRANGE,
99         OP_CREAT,
100         OP_DEDUPERANGE,
101         OP_DREAD,
102         OP_DWRITE,
103         OP_FALLOCATE,
104         OP_FDATASYNC,
105         OP_FIEMAP,
106         OP_FREESP,
107         OP_FSYNC,
108         OP_GETATTR,
109         OP_GETDENTS,
110         OP_GETFATTR,
111         OP_LINK,
112         OP_LISTFATTR,
113         OP_MKDIR,
114         OP_MKNOD,
115         OP_MREAD,
116         OP_MWRITE,
117         OP_PUNCH,
118         OP_ZERO,
119         OP_COLLAPSE,
120         OP_INSERT,
121         OP_READ,
122         OP_READLINK,
123         OP_READV,
124         OP_REMOVEFATTR,
125         OP_RENAME,
126         OP_RNOREPLACE,
127         OP_REXCHANGE,
128         OP_RWHITEOUT,
129         OP_RESVSP,
130         OP_RMDIR,
131         OP_SETATTR,
132         OP_SETFATTR,
133         OP_SETXATTR,
134         OP_SNAPSHOT,
135         OP_SPLICE,
136         OP_STAT,
137         OP_SUBVOL_CREATE,
138         OP_SUBVOL_DELETE,
139         OP_SYMLINK,
140         OP_SYNC,
141         OP_TRUNCATE,
142         OP_UNLINK,
143         OP_UNRESVSP,
144         OP_URING_READ,
145         OP_URING_WRITE,
146         OP_WRITE,
147         OP_WRITEV,
148         OP_LAST
149 } opty_t;
150
151 typedef long long opnum_t;
152
153 typedef void (*opfnc_t)(opnum_t, long);
154
155 typedef struct opdesc {
156         char    *name;
157         opfnc_t func;
158         int     freq;
159         int     iswrite;
160 } opdesc_t;
161
162 typedef struct fent {
163         int     id;
164         int     ft;
165         int     parent;
166         int     xattr_counter;
167 } fent_t;
168
169 typedef struct flist {
170         int     nfiles;
171         int     nslots;
172         int     tag;
173         fent_t  *fents;
174 } flist_t;
175
176 typedef struct pathname {
177         int     len;
178         char    *path;
179 } pathname_t;
180
181 struct print_flags {
182         unsigned long mask;
183         const char *name;
184 };
185
186 struct print_string {
187         char *buffer;
188         int len;
189         int max;
190 };
191
192 #define FT_DIR          0
193 #define FT_DIRm         (1 << FT_DIR)
194 #define FT_REG          1
195 #define FT_REGm         (1 << FT_REG)
196 #define FT_SYM          2
197 #define FT_SYMm         (1 << FT_SYM)
198 #define FT_DEV          3
199 #define FT_DEVm         (1 << FT_DEV)
200 #define FT_RTF          4
201 #define FT_RTFm         (1 << FT_RTF)
202 #define FT_SUBVOL       5
203 #define FT_SUBVOLm      (1 << FT_SUBVOL)
204 #define FT_nft          6
205 #define FT_ANYm         ((1 << FT_nft) - 1)
206 #define FT_REGFILE      (FT_REGm | FT_RTFm)
207 #define FT_NOTDIR       (FT_ANYm & (~FT_DIRm & ~FT_SUBVOLm))
208 #define FT_ANYDIR       (FT_DIRm | FT_SUBVOLm)
209
210 #define FLIST_SLOT_INCR 16
211 #define NDCACHE 64
212
213 #define MAXFSIZE        ((1ULL << 63) - 1ULL)
214 #define MAXFSIZE32      ((1ULL << 40) - 1ULL)
215
216 #define XATTR_NAME_BUF_SIZE 18
217
218 void    afsync_f(opnum_t, long);
219 void    allocsp_f(opnum_t, long);
220 void    aread_f(opnum_t, long);
221 void    attr_remove_f(opnum_t, long);
222 void    attr_set_f(opnum_t, long);
223 void    awrite_f(opnum_t, long);
224 void    bulkstat_f(opnum_t, long);
225 void    bulkstat1_f(opnum_t, long);
226 void    chown_f(opnum_t, long);
227 void    clonerange_f(opnum_t, long);
228 void    copyrange_f(opnum_t, long);
229 void    creat_f(opnum_t, long);
230 void    deduperange_f(opnum_t, long);
231 void    dread_f(opnum_t, long);
232 void    dwrite_f(opnum_t, long);
233 void    fallocate_f(opnum_t, long);
234 void    fdatasync_f(opnum_t, long);
235 void    fiemap_f(opnum_t, long);
236 void    freesp_f(opnum_t, long);
237 void    fsync_f(opnum_t, long);
238 char    *gen_random_string(int);
239 void    getattr_f(opnum_t, long);
240 void    getdents_f(opnum_t, long);
241 void    getfattr_f(opnum_t, long);
242 void    link_f(opnum_t, long);
243 void    listfattr_f(opnum_t, long);
244 void    mkdir_f(opnum_t, long);
245 void    mknod_f(opnum_t, long);
246 void    mread_f(opnum_t, long);
247 void    mwrite_f(opnum_t, long);
248 void    punch_f(opnum_t, long);
249 void    zero_f(opnum_t, long);
250 void    collapse_f(opnum_t, long);
251 void    insert_f(opnum_t, long);
252 void    read_f(opnum_t, long);
253 void    readlink_f(opnum_t, long);
254 void    readv_f(opnum_t, long);
255 void    removefattr_f(opnum_t, long);
256 void    rename_f(opnum_t, long);
257 void    rnoreplace_f(opnum_t, long);
258 void    rexchange_f(opnum_t, long);
259 void    rwhiteout_f(opnum_t, long);
260 void    resvsp_f(opnum_t, long);
261 void    rmdir_f(opnum_t, long);
262 void    setattr_f(opnum_t, long);
263 void    setfattr_f(opnum_t, long);
264 void    setxattr_f(opnum_t, long);
265 void    snapshot_f(opnum_t, long);
266 void    splice_f(opnum_t, long);
267 void    stat_f(opnum_t, long);
268 void    subvol_create_f(opnum_t, long);
269 void    subvol_delete_f(opnum_t, long);
270 void    symlink_f(opnum_t, long);
271 void    sync_f(opnum_t, long);
272 void    truncate_f(opnum_t, long);
273 void    unlink_f(opnum_t, long);
274 void    unresvsp_f(opnum_t, long);
275 void    uring_read_f(opnum_t, long);
276 void    uring_write_f(opnum_t, long);
277 void    write_f(opnum_t, long);
278 void    writev_f(opnum_t, long);
279 char    *xattr_flag_to_string(int);
280
281 struct opdesc   ops[OP_LAST]    = {
282      /* [OP_ENUM]          = {"name",          function,        freq, iswrite }, */
283         [OP_AFSYNC]        = {"afsync",        afsync_f,        0, 1 },
284         [OP_ALLOCSP]       = {"allocsp",       allocsp_f,       1, 1 },
285         [OP_AREAD]         = {"aread",         aread_f,         1, 0 },
286         [OP_ATTR_REMOVE]   = {"attr_remove",   attr_remove_f,   0, 1 },
287         [OP_ATTR_SET]      = {"attr_set",      attr_set_f,      0, 1 },
288         [OP_AWRITE]        = {"awrite",        awrite_f,        1, 1 },
289         [OP_BULKSTAT]      = {"bulkstat",      bulkstat_f,      1, 0 },
290         [OP_BULKSTAT1]     = {"bulkstat1",     bulkstat1_f,     1, 0 },
291         [OP_CHOWN]         = {"chown",         chown_f,         3, 1 },
292         [OP_CLONERANGE]    = {"clonerange",    clonerange_f,    4, 1 },
293         [OP_COPYRANGE]     = {"copyrange",     copyrange_f,     4, 1 },
294         [OP_CREAT]         = {"creat",         creat_f,         4, 1 },
295         [OP_DEDUPERANGE]   = {"deduperange",   deduperange_f,   4, 1 },
296         [OP_DREAD]         = {"dread",         dread_f,         4, 0 },
297         [OP_DWRITE]        = {"dwrite",        dwrite_f,        4, 1 },
298         [OP_FALLOCATE]     = {"fallocate",     fallocate_f,     1, 1 },
299         [OP_FDATASYNC]     = {"fdatasync",     fdatasync_f,     1, 1 },
300         [OP_FIEMAP]        = {"fiemap",        fiemap_f,        1, 1 },
301         [OP_FREESP]        = {"freesp",        freesp_f,        1, 1 },
302         [OP_FSYNC]         = {"fsync",         fsync_f,         1, 1 },
303         [OP_GETATTR]       = {"getattr",       getattr_f,       1, 0 },
304         [OP_GETDENTS]      = {"getdents",      getdents_f,      1, 0 },
305         /* get extended attribute */
306         [OP_GETFATTR]      = {"getfattr",      getfattr_f,      1, 0 },
307         [OP_LINK]          = {"link",          link_f,          1, 1 },
308         /* list extent attributes */
309         [OP_LISTFATTR]     = {"listfattr",     listfattr_f,     1, 0 },
310         [OP_MKDIR]         = {"mkdir",         mkdir_f,         2, 1 },
311         [OP_MKNOD]         = {"mknod",         mknod_f,         2, 1 },
312         [OP_MREAD]         = {"mread",         mread_f,         2, 0 },
313         [OP_MWRITE]        = {"mwrite",        mwrite_f,        2, 1 },
314         [OP_PUNCH]         = {"punch",         punch_f,         1, 1 },
315         [OP_ZERO]          = {"zero",          zero_f,          1, 1 },
316         [OP_COLLAPSE]      = {"collapse",      collapse_f,      1, 1 },
317         [OP_INSERT]        = {"insert",        insert_f,        1, 1 },
318         [OP_READ]          = {"read",          read_f,          1, 0 },
319         [OP_READLINK]      = {"readlink",      readlink_f,      1, 0 },
320         [OP_READV]         = {"readv",         readv_f,         1, 0 },
321         /* remove (delete) extended attribute */
322         [OP_REMOVEFATTR]   = {"removefattr",   removefattr_f,   1, 1 },
323         [OP_RENAME]        = {"rename",        rename_f,        2, 1 },
324         [OP_RNOREPLACE]    = {"rnoreplace",    rnoreplace_f,    2, 1 },
325         [OP_REXCHANGE]     = {"rexchange",     rexchange_f,     2, 1 },
326         [OP_RWHITEOUT]     = {"rwhiteout",     rwhiteout_f,     2, 1 },
327         [OP_RESVSP]        = {"resvsp",        resvsp_f,        1, 1 },
328         [OP_RMDIR]         = {"rmdir",         rmdir_f,         1, 1 },
329         /* set attribute flag (FS_IOC_SETFLAGS ioctl) */
330         [OP_SETATTR]       = {"setattr",       setattr_f,       0, 1 },
331         /* set extended attribute */
332         [OP_SETFATTR]      = {"setfattr",      setfattr_f,      2, 1 },
333         /* set project id (XFS_IOC_FSSETXATTR ioctl) */
334         [OP_SETXATTR]      = {"setxattr",      setxattr_f,      1, 1 },
335         [OP_SNAPSHOT]      = {"snapshot",      snapshot_f,      1, 1 },
336         [OP_SPLICE]        = {"splice",        splice_f,        1, 1 },
337         [OP_STAT]          = {"stat",          stat_f,          1, 0 },
338         [OP_SUBVOL_CREATE] = {"subvol_create", subvol_create_f, 1, 1 },
339         [OP_SUBVOL_DELETE] = {"subvol_delete", subvol_delete_f, 1, 1 },
340         [OP_SYMLINK]       = {"symlink",       symlink_f,       2, 1 },
341         [OP_SYNC]          = {"sync",          sync_f,          1, 1 },
342         [OP_TRUNCATE]      = {"truncate",      truncate_f,      2, 1 },
343         [OP_UNLINK]        = {"unlink",        unlink_f,        1, 1 },
344         [OP_UNRESVSP]      = {"unresvsp",      unresvsp_f,      1, 1 },
345         [OP_URING_READ]    = {"uring_read",    uring_read_f,    1, 0 },
346         [OP_URING_WRITE]   = {"uring_write",   uring_write_f,   1, 1 },
347         [OP_WRITE]         = {"write",         write_f,         4, 1 },
348         [OP_WRITEV]        = {"writev",        writev_f,        4, 1 },
349 }, *ops_end;
350
351 flist_t flist[FT_nft] = {
352         { 0, 0, 'd', NULL },
353         { 0, 0, 'f', NULL },
354         { 0, 0, 'l', NULL },
355         { 0, 0, 'c', NULL },
356         { 0, 0, 'r', NULL },
357         { 0, 0, 's', NULL },
358 };
359
360 int             dcache[NDCACHE];
361 int             errrange;
362 int             errtag;
363 opty_t          *freq_table;
364 int             freq_table_size;
365 struct xfs_fsop_geom    geom;
366 char            *homedir;
367 int             *ilist;
368 int             ilistlen;
369 off64_t         maxfsize;
370 char            *myprog;
371 int             namerand;
372 int             nameseq;
373 int             nops;
374 int             nproc = 1;
375 opnum_t         operations = 1;
376 unsigned int    idmodulo = XFS_IDMODULO_MAX;
377 unsigned int    attr_mask = ~0;
378 int             procid;
379 int             rtpct;
380 unsigned long   seed = 0;
381 ino_t           top_ino;
382 int             cleanup = 0;
383 int             verbose = 0;
384 int             verifiable_log = 0;
385 sig_atomic_t    should_stop = 0;
386 sigjmp_buf      *sigbus_jmp = NULL;
387 char            *execute_cmd = NULL;
388 int             execute_freq = 1;
389 struct print_string     flag_str = {0};
390
391 void    add_to_flist(int, int, int, int);
392 void    append_pathname(pathname_t *, char *);
393 int     attr_list_path(pathname_t *, char *, const int);
394 int     attr_remove_path(pathname_t *, const char *);
395 int     attr_set_path(pathname_t *, const char *, const char *, const int);
396 void    check_cwd(void);
397 void    cleanup_flist(void);
398 int     creat_path(pathname_t *, mode_t);
399 void    dcache_enter(int, int);
400 void    dcache_init(void);
401 fent_t  *dcache_lookup(int);
402 void    dcache_purge(int, int);
403 void    del_from_flist(int, int);
404 int     dirid_to_name(char *, int);
405 void    doproc(void);
406 int     fent_to_name(pathname_t *, fent_t *);
407 bool    fents_ancestor_check(fent_t *, fent_t *);
408 void    fix_parent(int, int, bool);
409 void    free_pathname(pathname_t *);
410 int     generate_fname(fent_t *, int, pathname_t *, int *, int *);
411 int     generate_xattr_name(int, char *, int);
412 int     get_fname(int, long, pathname_t *, flist_t **, fent_t **, int *);
413 void    init_pathname(pathname_t *);
414 int     lchown_path(pathname_t *, uid_t, gid_t);
415 int     link_path(pathname_t *, pathname_t *);
416 int     lstat64_path(pathname_t *, struct stat64 *);
417 void    make_freq_table(void);
418 int     mkdir_path(pathname_t *, mode_t);
419 int     mknod_path(pathname_t *, mode_t, dev_t);
420 void    namerandpad(int, char *, int);
421 int     open_file_or_dir(pathname_t *, int);
422 int     open_path(pathname_t *, int);
423 DIR     *opendir_path(pathname_t *);
424 void    process_freq(char *);
425 int     readlink_path(pathname_t *, char *, size_t);
426 int     rename_path(pathname_t *, pathname_t *, int);
427 int     rmdir_path(pathname_t *);
428 void    separate_pathname(pathname_t *, char *, pathname_t *);
429 void    show_ops(int, char *);
430 int     stat64_path(pathname_t *, struct stat64 *);
431 int     symlink_path(const char *, pathname_t *);
432 int     truncate64_path(pathname_t *, off64_t);
433 int     unlink_path(pathname_t *);
434 void    usage(void);
435 void    write_freq(void);
436 void    zero_freq(void);
437 void    non_btrfs_freq(const char *);
438
439 void sg_handler(int signum)
440 {
441         switch (signum) {
442         case SIGTERM:
443                 should_stop = 1;
444                 break;
445         case SIGBUS:
446                 /*
447                  * Only handle SIGBUS when mmap write to a hole and no
448                  * block can be allocated due to ENOSPC, abort otherwise.
449                  */
450                 if (sigbus_jmp) {
451                         siglongjmp(*sigbus_jmp, -1);
452                 } else {
453                         printf("Unknown SIGBUS is caught, Abort!\n");
454                         abort();
455                 }
456                 /* should not reach here */
457                 break;
458         default:
459                 break;
460         }
461 }
462
463 int main(int argc, char **argv)
464 {
465         char            buf[10];
466         int             c;
467         char            *dirname = NULL;
468         char            *logname = NULL;
469         char            rpath[PATH_MAX];
470         int             fd;
471         int             i;
472         int             j;
473         char            *p;
474         int             stat;
475         struct timeval  t;
476         ptrdiff_t       srval;
477         int             nousage = 0;
478         xfs_error_injection_t           err_inj;
479         struct sigaction action;
480         int             loops = 1;
481         const char      *allopts = "cd:e:f:i:l:m:M:n:o:p:rs:S:vVwx:X:zH";
482
483         errrange = errtag = 0;
484         umask(0);
485         nops = sizeof(ops) / sizeof(ops[0]);
486         ops_end = &ops[nops];
487         myprog = argv[0];
488         while ((c = getopt(argc, argv, allopts)) != -1) {
489                 switch (c) {
490                 case 'c':
491                         cleanup = 1;
492                         break;
493                 case 'd':
494                         dirname = optarg;
495                         break;
496                 case 'e':
497                         sscanf(optarg, "%d", &errtag);
498                         if (errtag < 0) {
499                                 errtag = -errtag;
500                                 errrange = 1;
501                         } else if (errtag == 0)
502                                 errtag = -1;
503                         if (errtag >= XFS_ERRTAG_MAX) {
504                                 fprintf(stderr,
505                                         "error tag %d too large (max %d)\n",
506                                         errtag, XFS_ERRTAG_MAX - 1);
507                                 exit(1);
508                         }
509                         break;
510                 case 'f':
511                         process_freq(optarg);
512                         break;
513                 case 'i':
514                         ilist = realloc(ilist, ++ilistlen * sizeof(*ilist));
515                         ilist[ilistlen - 1] = strtol(optarg, &p, 16);
516                         break;
517                 case 'm':
518                         idmodulo = strtoul(optarg, NULL, 0);
519                         if (idmodulo > XFS_IDMODULO_MAX) {
520                                 fprintf(stderr,
521                                         "chown modulo %d too big (max %d)\n",
522                                         idmodulo, XFS_IDMODULO_MAX);
523                                 exit(1);
524                         }
525                         break;
526                 case 'l':
527                         loops = atoi(optarg);
528                         break;
529                 case 'n':
530                         errno = 0;
531                         operations = strtoll(optarg, NULL, 0);
532                         if (errno) {
533                                 perror(optarg);
534                                 exit(1);
535                         }
536                         break;
537                 case 'o':
538                         logname = optarg;
539                         break;
540
541                 case 'p':
542                         nproc = atoi(optarg);
543                         break;
544                 case 'r':
545                         namerand = 1;
546                         break;
547                 case 's':
548                         seed = strtoul(optarg, NULL, 0);
549                         break;
550                 case 'v':
551                         verbose = 1;
552                         break;
553                 case 'w':
554                         write_freq();
555                         break;
556                 case 'x':
557                         execute_cmd = optarg;
558                         break;
559                 case 'z':
560                         zero_freq();
561                         break;
562                 case 'M':
563                         attr_mask = strtoul(optarg, NULL, 0);
564                         break;
565                 case 'S':
566                         i = 0;
567                         if (optarg[0] == 'c')
568                                 i = 1;
569                         show_ops(i, NULL);
570                         printf("\n");
571                         nousage=1;
572                         break;
573                 case 'V':
574                         verifiable_log = 1;
575                         break;
576
577                 case 'X':
578                         execute_freq = strtoul(optarg, NULL, 0);
579                         break;
580                 case '?':
581                         fprintf(stderr, "%s - invalid parameters\n",
582                                 myprog);
583                         /* fall through */
584                 case 'H':
585                         usage();
586                         exit(1);
587                 }
588         }
589
590         if (!dirname) {
591             /* no directory specified */
592             if (!nousage) usage();
593             exit(1);
594         }
595
596         non_btrfs_freq(dirname);
597         (void)mkdir(dirname, 0777);
598         if (logname && logname[0] != '/') {
599                 if (!getcwd(rpath, sizeof(rpath))){
600                         perror("getcwd failed");
601                         exit(1);
602                 }
603         } else {
604                 rpath[0] = '\0';
605         }
606         if (chdir(dirname) < 0) {
607                 perror(dirname);
608                 exit(1);
609         }
610         if (logname) {
611                 char path[PATH_MAX + NAME_MAX + 1];
612                 snprintf(path, sizeof(path), "%s/%s", rpath, logname);
613                 if (freopen(path, "a", stdout) == NULL) {
614                         perror("freopen logfile failed");
615                         exit(1);
616                 }
617         }
618         sprintf(buf, "fss%x", (unsigned int)getpid());
619         fd = creat(buf, 0666);
620         if (lseek64(fd, (off64_t)(MAXFSIZE32 + 1ULL), SEEK_SET) < 0)
621                 maxfsize = (off64_t)MAXFSIZE32;
622         else
623                 maxfsize = (off64_t)MAXFSIZE;
624         make_freq_table();
625         dcache_init();
626         setlinebuf(stdout);
627         if (!seed) {
628                 gettimeofday(&t, (void *)NULL);
629                 seed = (int)t.tv_sec ^ (int)t.tv_usec;
630                 printf("seed = %ld\n", seed);
631         }
632         i = xfsctl(buf, fd, XFS_IOC_FSGEOMETRY, &geom);
633         if (i >= 0 && geom.rtblocks)
634                 rtpct = MIN(MAX(geom.rtblocks * 100 /
635                                 (geom.rtblocks + geom.datablocks), 1), 99);
636         else
637                 rtpct = 0;
638         if (errtag != 0) {
639                 if (errrange == 0) {
640                         if (errtag <= 0) {
641                                 srandom(seed);
642                                 j = random() % 100;
643
644                                 for (i = 0; i < j; i++)
645                                         (void) random();
646
647                                 errtag = (random() % (XFS_ERRTAG_MAX-1)) + 1;
648                         }
649                 } else {
650                         srandom(seed);
651                         j = random() % 100;
652
653                         for (i = 0; i < j; i++)
654                                 (void) random();
655
656                         errtag += (random() % (XFS_ERRTAG_MAX - errtag));
657                 }
658                 printf("Injecting failure on tag #%d\n", errtag);
659                 err_inj.errtag = errtag;
660                 err_inj.fd = fd;
661                 srval = xfsctl(buf, fd, XFS_IOC_ERROR_INJECTION, &err_inj);
662                 if (srval < -1) {
663                         perror("fsstress - XFS_SYSSGI error injection call");
664                         close(fd);
665                         unlink(buf);
666                         exit(1);
667                 }
668         } else
669                 close(fd);
670
671         setpgid(0, 0);
672         action.sa_handler = sg_handler;
673         sigemptyset(&action.sa_mask);
674         action.sa_flags = 0;
675         if (sigaction(SIGTERM, &action, 0)) {
676                 perror("sigaction failed");
677                 exit(1);
678         }
679
680         for (i = 0; i < nproc; i++) {
681                 if (fork() == 0) {
682                         sigemptyset(&action.sa_mask);
683                         action.sa_handler = SIG_DFL;
684                         if (sigaction(SIGTERM, &action, 0))
685                                 return 1;
686                         action.sa_handler = sg_handler;
687                         if (sigaction(SIGBUS, &action, 0))
688                                 return 1;
689 #ifdef HAVE_SYS_PRCTL_H
690                         prctl(PR_SET_PDEATHSIG, SIGKILL);
691                         if (getppid() == 1) /* parent died already? */
692                                 return 0;
693 #endif
694                         if (logname) {
695                                 char path[PATH_MAX + NAME_MAX + 2 + 11];
696                                 snprintf(path, sizeof(path), "%s/%s.%d",
697                                          rpath, logname, i);
698                                 if (freopen(path, "a", stdout) == NULL) {
699                                         perror("freopen logfile failed");
700                                         exit(1);
701                                 }
702                         }
703                         procid = i;
704 #ifdef AIO
705                         if (io_setup(AIO_ENTRIES, &io_ctx) != 0) {
706                                 fprintf(stderr, "io_setup failed\n");
707                                 exit(1);
708                         }
709 #endif
710 #ifdef URING
711                         have_io_uring = true;
712                         /* If ENOSYS, just ignore uring, other errors are fatal. */
713                         if (io_uring_queue_init(URING_ENTRIES, &ring, 0)) {
714                                 if (errno == ENOSYS) {
715                                         have_io_uring = false;
716                                 } else {
717                                         fprintf(stderr, "io_uring_queue_init failed\n");
718                                         exit(1);
719                                 }
720                         }
721 #endif
722                         for (i = 0; !loops || (i < loops); i++)
723                                 doproc();
724 #ifdef AIO
725                         if(io_destroy(io_ctx) != 0) {
726                                 fprintf(stderr, "io_destroy failed");
727                                 return 1;
728                         }
729 #endif
730 #ifdef URING
731                         if (have_io_uring)
732                                 io_uring_queue_exit(&ring);
733 #endif
734                         cleanup_flist();
735                         free(freq_table);
736                         return 0;
737                 }
738         }
739         while (wait(&stat) > 0 && !should_stop) {
740                 continue;
741         }
742         action.sa_flags = SA_RESTART;
743         sigaction(SIGTERM, &action, 0);
744         kill(-getpid(), SIGTERM);
745         while (wait(&stat) > 0)
746                 continue;
747
748         if (errtag != 0) {
749                 err_inj.errtag = 0;
750                 err_inj.fd = fd;
751                 srval = xfsctl(buf, fd, XFS_IOC_ERROR_CLEARALL, &err_inj);
752                 if (srval != 0) {
753                         fprintf(stderr, "Bad ej clear on %s fd=%d (%d).\n",
754                                 buf, fd, errno);
755                         perror("xfsctl(XFS_IOC_ERROR_CLEARALL)");
756                         close(fd);
757                         exit(1);
758                 }
759                 close(fd);
760         }
761
762         free(freq_table);
763         unlink(buf);
764         return 0;
765 }
766
767 int
768 add_string(struct print_string *str, const char *add)
769 {
770         int len = strlen(add);
771
772         if (len <= 0)
773                 return 0;
774
775         if (len > (str->max - 1) - str->len) {
776                 str->len = str->max - 1;
777                 return 0;
778         }
779
780         memcpy(str->buffer + str->len, add, len);
781         str->len += len;
782         str->buffer[str->len] = '\0';
783
784         return len;
785 }
786
787 char *
788 translate_flags(int flags, const char *delim,
789                 const struct print_flags *flag_array)
790 {
791         int i, mask, first = 1;
792         const char *add;
793
794         if (!flag_str.buffer) {
795                 flag_str.buffer = malloc(4096);
796                 flag_str.max = 4096;
797                 flag_str.len = 0;
798         }
799         if (!flag_str.buffer)
800                 return NULL;
801         flag_str.len = 0;
802         flag_str.buffer[0] = '\0';
803
804         for (i = 0;  flag_array[i].name && flags; i++) {
805                 mask = flag_array[i].mask;
806                 if ((flags & mask) != mask)
807                         continue;
808
809                 add = flag_array[i].name;
810                 flags &= ~mask;
811                 if (!first && delim)
812                         add_string(&flag_str, delim);
813                 else
814                         first = 0;
815                 add_string(&flag_str, add);
816         }
817
818         /* Check whether there are any leftover flags. */
819         if (flags) {
820                 int ret;
821                 char number[11];
822
823                 if (!first && delim)
824                         add_string(&flag_str, delim);
825
826                 ret = snprintf(number, 11, "0x%x", flags) > 0;
827                 if (ret > 0 && ret <= 11)
828                         add_string(&flag_str, number);
829         }
830
831         return flag_str.buffer;
832 }
833
834 void
835 add_to_flist(int ft, int id, int parent, int xattr_counter)
836 {
837         fent_t  *fep;
838         flist_t *ftp;
839
840         ftp = &flist[ft];
841         if (ftp->nfiles == ftp->nslots) {
842                 ftp->nslots += FLIST_SLOT_INCR;
843                 ftp->fents = realloc(ftp->fents, ftp->nslots * sizeof(fent_t));
844         }
845         fep = &ftp->fents[ftp->nfiles++];
846         fep->id = id;
847         fep->ft = ft;
848         fep->parent = parent;
849         fep->xattr_counter = xattr_counter;
850 }
851
852 void
853 append_pathname(pathname_t *name, char *str)
854 {
855         int     len;
856
857         len = strlen(str);
858 #ifdef DEBUG
859         /* attempting to append to a dir a zero length path */
860         if (len && *str == '/' && name->len == 0) {
861                 fprintf(stderr, "fsstress: append_pathname failure\n");
862                 assert(chdir(homedir) == 0);
863                 abort();
864                 /* NOTREACHED */
865         }
866 #endif
867         name->path = realloc(name->path, name->len + 1 + len);
868         strcpy(&name->path[name->len], str);
869         name->len += len;
870 }
871
872 int
873 attr_list_count(char *buffer, int buffersize)
874 {
875         char *p = buffer;
876         char *end = buffer + buffersize;
877         int count = 0;
878
879         while (p < end && *p != 0) {
880                 count++;
881                 p += strlen(p) + 1;
882         }
883
884         return count;
885 }
886
887 int
888 attr_list_path(pathname_t *name,
889                char *buffer,
890                const int buffersize)
891 {
892         char            buf[NAME_MAX + 1];
893         pathname_t      newname;
894         int             rval;
895
896         rval = llistxattr(name->path, buffer, buffersize);
897         if (rval >= 0 || errno != ENAMETOOLONG)
898                 return rval;
899         separate_pathname(name, buf, &newname);
900         if (chdir(buf) == 0) {
901                 rval = attr_list_path(&newname, buffer, buffersize);
902                 assert(chdir("..") == 0);
903         }
904         free_pathname(&newname);
905         return rval;
906 }
907
908 int
909 attr_remove_path(pathname_t *name, const char *attrname)
910 {
911         char            buf[NAME_MAX + 1];
912         pathname_t      newname;
913         int             rval;
914
915         rval = lremovexattr(name->path, attrname);
916         if (rval >= 0 || errno != ENAMETOOLONG)
917                 return rval;
918         separate_pathname(name, buf, &newname);
919         if (chdir(buf) == 0) {
920                 rval = attr_remove_path(&newname, attrname);
921                 assert(chdir("..") == 0);
922         }
923         free_pathname(&newname);
924         return rval;
925 }
926
927 int
928 attr_set_path(pathname_t *name, const char *attrname, const char *attrvalue,
929               const int valuelength)
930 {
931         char            buf[NAME_MAX + 1];
932         pathname_t      newname;
933         int             rval;
934
935         rval = lsetxattr(name->path, attrname, attrvalue, valuelength, 0);
936         if (rval >= 0 || errno != ENAMETOOLONG)
937                 return rval;
938         separate_pathname(name, buf, &newname);
939         if (chdir(buf) == 0) {
940                 rval = attr_set_path(&newname, attrname, attrvalue,
941                                      valuelength);
942                 assert(chdir("..") == 0);
943         }
944         free_pathname(&newname);
945         return rval;
946 }
947
948 void
949 check_cwd(void)
950 {
951 #ifdef DEBUG
952         struct stat64   statbuf;
953         int ret;
954
955         ret = stat64(".", &statbuf);
956         if (ret != 0) {
957                 fprintf(stderr, "fsstress: check_cwd stat64() returned %d with errno: %d (%s)\n",
958                         ret, errno, strerror(errno));
959                 goto out;
960         }
961
962         if (statbuf.st_ino == top_ino)
963                 return;
964
965         fprintf(stderr, "fsstress: check_cwd statbuf.st_ino (%llu) != top_ino (%llu)\n",
966                 (unsigned long long) statbuf.st_ino,
967                 (unsigned long long) top_ino);
968 out:
969         assert(chdir(homedir) == 0);
970         fprintf(stderr, "fsstress: check_cwd failure\n");
971         abort();
972         /* NOTREACHED */
973 #endif
974 }
975
976 /*
977  * go thru flist and release all entries
978  *
979  * NOTE: this function shouldn't be called until the end of a process
980  */
981 void
982 cleanup_flist(void)
983 {
984         flist_t *flp;
985         int     i;
986
987         for (i = 0, flp = flist; i < FT_nft; i++, flp++) {
988                 flp->nslots = 0;
989                 flp->nfiles = 0;
990                 free(flp->fents);
991                 flp->fents = NULL;
992         }
993 }
994
995 int
996 creat_path(pathname_t *name, mode_t mode)
997 {
998         char            buf[NAME_MAX + 1];
999         pathname_t      newname;
1000         int             rval;
1001
1002         rval = creat(name->path, mode);
1003         if (rval >= 0 || errno != ENAMETOOLONG)
1004                 return rval;
1005         separate_pathname(name, buf, &newname);
1006         if (chdir(buf) == 0) {
1007                 rval = creat_path(&newname, mode);
1008                 assert(chdir("..") == 0);
1009         }
1010         free_pathname(&newname);
1011         return rval;
1012 }
1013
1014 void
1015 dcache_enter(int dirid, int slot)
1016 {
1017         dcache[dirid % NDCACHE] = slot;
1018 }
1019
1020 void
1021 dcache_init(void)
1022 {
1023         int     i;
1024
1025         for (i = 0; i < NDCACHE; i++)
1026                 dcache[i] = -1;
1027 }
1028
1029 fent_t *
1030 dcache_lookup(int dirid)
1031 {
1032         fent_t  *fep;
1033         int     i;
1034
1035         i = dcache[dirid % NDCACHE];
1036         if (i >= 0 && i < flist[FT_DIR].nfiles &&
1037             (fep = &flist[FT_DIR].fents[i])->id == dirid)
1038                 return fep;
1039         if (i >= 0 && i < flist[FT_SUBVOL].nfiles &&
1040             (fep = &flist[FT_SUBVOL].fents[i])->id == dirid)
1041                 return fep;
1042         return NULL;
1043 }
1044
1045 void
1046 dcache_purge(int dirid, int ft)
1047 {
1048         int     *dcp;
1049         dcp = &dcache[dirid % NDCACHE];
1050         if (*dcp >= 0 && *dcp < flist[ft].nfiles &&
1051             flist[ft].fents[*dcp].id == dirid)
1052                 *dcp = -1;
1053 }
1054
1055 /*
1056  * Delete the item from the list by
1057  * moving last entry over the deleted one;
1058  * unless deleted entry is the last one.
1059  * Input: which file list array and which slot in array
1060  */
1061 void
1062 del_from_flist(int ft, int slot)
1063 {
1064         flist_t *ftp;
1065
1066         ftp = &flist[ft];
1067         if (ft == FT_DIR || ft == FT_SUBVOL)
1068                 dcache_purge(ftp->fents[slot].id, ft);
1069         if (slot != ftp->nfiles - 1) {
1070                 if (ft == FT_DIR || ft == FT_SUBVOL)
1071                         dcache_purge(ftp->fents[ftp->nfiles - 1].id, ft);
1072                 ftp->fents[slot] = ftp->fents[--ftp->nfiles];
1073         } else
1074                 ftp->nfiles--;
1075 }
1076
1077 void
1078 delete_subvol_children(int parid)
1079 {
1080         flist_t *flp;
1081         int     i;
1082 again:
1083         for (i = 0, flp = flist; i < FT_nft; i++, flp++) {
1084                 int c;
1085                 for (c = 0; c < flp->nfiles; c++) {
1086                         if (flp->fents[c].parent == parid) {
1087                                 int id = flp->fents[c].id;
1088                                 del_from_flist(i, c);
1089                                 if (i == FT_DIR || i == FT_SUBVOL)
1090                                         delete_subvol_children(id);
1091                                 goto again;
1092                         }
1093                 }
1094         }
1095 }
1096
1097 fent_t *
1098 dirid_to_fent(int dirid)
1099 {
1100         fent_t  *efep;
1101         fent_t  *fep;
1102         flist_t *flp;
1103         int     ft = FT_DIR;
1104
1105         if ((fep = dcache_lookup(dirid)))
1106                 return fep;
1107 again:
1108         flp = &flist[ft];
1109         for (fep = flp->fents, efep = &fep[flp->nfiles]; fep < efep; fep++) {
1110                 if (fep->id == dirid) {
1111                         dcache_enter(dirid, fep - flp->fents);
1112                         return fep;
1113                 }
1114         }
1115         if (ft == FT_DIR) {
1116                 ft = FT_SUBVOL;
1117                 goto again;
1118         }
1119         return NULL;
1120 }
1121
1122 void
1123 doproc(void)
1124 {
1125         struct stat64   statbuf;
1126         char            buf[10];
1127         char            cmd[64];
1128         opnum_t         opno;
1129         int             rval;
1130         opdesc_t        *p;
1131         long long       dividend;
1132
1133         dividend = (operations + execute_freq) / (execute_freq + 1);
1134         sprintf(buf, "p%x", procid);
1135         (void)mkdir(buf, 0777);
1136         if (chdir(buf) < 0 || stat64(".", &statbuf) < 0) {
1137                 perror(buf);
1138                 _exit(1);
1139         }
1140         top_ino = statbuf.st_ino;
1141         homedir = getcwd(NULL, 0);
1142         if (!homedir) {
1143                 perror("getcwd failed");
1144                 _exit(1);
1145         }
1146         seed += procid;
1147         srandom(seed);
1148         if (namerand)
1149                 namerand = random();
1150         for (opno = 0; opno < operations; opno++) {
1151                 if (execute_cmd && opno && opno % dividend == 0) {
1152                         if (verbose)
1153                                 printf("%lld: execute command %s\n", opno,
1154                                         execute_cmd);
1155                         rval = system(execute_cmd);
1156                         if (rval)
1157                                 fprintf(stderr, "execute command failed with "
1158                                         "%d\n", rval);
1159                 }
1160                 p = &ops[freq_table[random() % freq_table_size]];
1161                 p->func(opno, random());
1162                 /*
1163                  * test for forced shutdown by stat'ing the test
1164                  * directory.  If this stat returns EIO, assume
1165                  * the forced shutdown happened.
1166                  */
1167                 if (errtag != 0 && opno % 100 == 0)  {
1168                         rval = stat64(".", &statbuf);
1169                         if (rval == EIO)  {
1170                                 fprintf(stderr, "Detected EIO\n");
1171                                 goto errout;
1172                         }
1173                 }
1174         }
1175 errout:
1176         assert(chdir("..") == 0);
1177         free(homedir);
1178         if (cleanup) {
1179                 int ret;
1180
1181                 sprintf(cmd, "rm -rf %s", buf);
1182                 ret = system(cmd);
1183                 if (ret != 0)
1184                         perror("cleaning up");
1185                 cleanup_flist();
1186         }
1187 }
1188
1189 /*
1190  * build up a pathname going thru the file entry and all
1191  * its parent entries
1192  * Return 0 on error, 1 on success;
1193  */
1194 int
1195 fent_to_name(pathname_t *name, fent_t *fep)
1196 {
1197         flist_t *flp = &flist[fep->ft];
1198         char    buf[NAME_MAX + 1];
1199         int     i;
1200         fent_t  *pfep;
1201         int     e;
1202
1203         if (fep == NULL)
1204                 return 0;
1205
1206         /* build up parent directory name */
1207         if (fep->parent != -1) {
1208                 pfep = dirid_to_fent(fep->parent);
1209 #ifdef DEBUG
1210                 if (pfep == NULL) {
1211                         fprintf(stderr, "%d: fent-id = %d: can't find parent id: %d\n",
1212                                 procid, fep->id, fep->parent);
1213                 } 
1214 #endif
1215                 if (pfep == NULL)
1216                         return 0;
1217                 e = fent_to_name(name, pfep);
1218                 if (!e)
1219                         return 0;
1220                 append_pathname(name, "/");
1221         }
1222
1223         i = sprintf(buf, "%c%x", flp->tag, fep->id);
1224         namerandpad(fep->id, buf, i);
1225         append_pathname(name, buf);
1226         return 1;
1227 }
1228
1229 bool
1230 fents_ancestor_check(fent_t *fep, fent_t *dfep)
1231 {
1232         fent_t  *tmpfep;
1233
1234         for (tmpfep = fep; tmpfep->parent != -1;
1235              tmpfep = dirid_to_fent(tmpfep->parent)) {
1236                 if (tmpfep->parent == dfep->id)
1237                         return true;
1238         }
1239
1240         return false;
1241 }
1242
1243 void
1244 fix_parent(int oldid, int newid, bool swap)
1245 {
1246         fent_t  *fep;
1247         flist_t *flp;
1248         int     i;
1249         int     j;
1250
1251         for (i = 0, flp = flist; i < FT_nft; i++, flp++) {
1252                 for (j = 0, fep = flp->fents; j < flp->nfiles; j++, fep++) {
1253                         if (fep->parent == oldid)
1254                                 fep->parent = newid;
1255                         else if (swap && fep->parent == newid)
1256                                 fep->parent = oldid;
1257                 }
1258         }
1259 }
1260
1261 void
1262 free_pathname(pathname_t *name)
1263 {
1264         if (name->path) {
1265                 free(name->path);
1266                 name->path = NULL;
1267                 name->len = 0;
1268         }
1269 }
1270
1271 /*
1272  * Generate a filename of type ft.
1273  * If we have a fep which should be a directory then use it
1274  * as the parent path for this new filename i.e. prepend with it.
1275  */
1276 int
1277 generate_fname(fent_t *fep, int ft, pathname_t *name, int *idp, int *v)
1278 {
1279         char    buf[NAME_MAX + 1];
1280         flist_t *flp;
1281         int     id;
1282         int     j;
1283         int     len;
1284         int     e;
1285
1286         /* create name */
1287         flp = &flist[ft];
1288         len = sprintf(buf, "%c%x", flp->tag, id = nameseq++);
1289         namerandpad(id, buf, len);
1290
1291         /* prepend fep parent dir-name to it */
1292         if (fep) {
1293                 e = fent_to_name(name, fep);
1294                 if (!e)
1295                         return 0;
1296                 append_pathname(name, "/");
1297         }
1298         append_pathname(name, buf);
1299
1300         *idp = id;
1301         *v = verbose;
1302         for (j = 0; !*v && j < ilistlen; j++) {
1303                 if (ilist[j] == id) {
1304                         *v = 1;
1305                         break;
1306                 }
1307         }
1308         return 1;
1309 }
1310
1311 int generate_xattr_name(int xattr_num, char *buffer, int buflen)
1312 {
1313         int ret;
1314
1315         ret = snprintf(buffer, buflen, "user.x%d", xattr_num);
1316         if (ret < 0)
1317                 return ret;
1318         if (ret < buflen)
1319                 return 0;
1320         return -EOVERFLOW;
1321 }
1322
1323 /*
1324  * Get file 
1325  * Input: "which" to choose the file-types eg. non-directory
1326  * Input: "r" to choose which file
1327  * Output: file-list, file-entry, name for the chosen file.
1328  * Output: verbose if chosen file is on the ilist.
1329  */
1330 int
1331 get_fname(int which, long r, pathname_t *name, flist_t **flpp, fent_t **fepp,
1332           int *v)
1333 {
1334         int     totalsum = 0; /* total number of matching files */
1335         int     partialsum = 0; /* partial sum of matching files */
1336         fent_t  *fep;
1337         flist_t *flp;
1338         int     i;
1339         int     j;
1340         int     x;
1341         int     e = 1; /* success */
1342
1343         /*
1344          * go thru flist and add up number of files for each
1345          * category that matches with <which>.
1346          */
1347         for (i = 0, flp = flist; i < FT_nft; i++, flp++) {
1348                 if (which & (1 << i))
1349                         totalsum += flp->nfiles;
1350         }
1351         if (totalsum == 0) {
1352                 if (flpp)
1353                         *flpp = NULL;
1354                 if (fepp)
1355                         *fepp = NULL;
1356                 *v = verbose;
1357                 return 0;
1358         }
1359
1360         /*
1361          * Now we have possible matches between 0..totalsum-1.
1362          * And we use r to help us choose which one we want,
1363          * which when bounded by totalsum becomes x.
1364          */ 
1365         x = (int)(r % totalsum);
1366         for (i = 0, flp = flist; i < FT_nft; i++, flp++) {
1367                 if (which & (1 << i)) {
1368                         if (x < partialsum + flp->nfiles) {
1369
1370                                 /* found the matching file entry */
1371                                 fep = &flp->fents[x - partialsum];
1372
1373                                 /* fill-in what we were asked for */
1374                                 if (name) {
1375                                         e = fent_to_name(name, fep);
1376 #ifdef DEBUG
1377                                         if (!e) {
1378                                                 fprintf(stderr, "%d: failed to get path for entry:"
1379                                                                 " id=%d,parent=%d\n",   
1380                                                         procid, fep->id, fep->parent);
1381                                         }
1382 #endif
1383                                 }
1384                                 if (flpp)
1385                                         *flpp = flp;
1386                                 if (fepp)
1387                                         *fepp = fep;
1388
1389                                 /* turn on verbose if its an ilisted file */
1390                                 *v = verbose;
1391                                 for (j = 0; !*v && j < ilistlen; j++) {
1392                                         if (ilist[j] == fep->id) {
1393                                                 *v = 1;
1394                                                 break;
1395                                         }
1396                                 }
1397                                 return e;
1398                         }
1399                         partialsum += flp->nfiles;
1400                 }
1401         }
1402 #ifdef DEBUG
1403         fprintf(stderr, "fsstress: get_fname failure\n");
1404         abort();
1405 #endif
1406         return 0;
1407 }
1408
1409 void
1410 init_pathname(pathname_t *name)
1411 {
1412         name->len = 0;
1413         name->path = NULL;
1414 }
1415
1416 int
1417 lchown_path(pathname_t *name, uid_t owner, gid_t group)
1418 {
1419         char            buf[NAME_MAX + 1];
1420         pathname_t      newname;
1421         int             rval;
1422
1423         rval = lchown(name->path, owner, group);
1424         if (rval >= 0 || errno != ENAMETOOLONG)
1425                 return rval;
1426         separate_pathname(name, buf, &newname);
1427         if (chdir(buf) == 0) {
1428                 rval = lchown_path(&newname, owner, group);
1429                 assert(chdir("..") == 0);
1430         }
1431         free_pathname(&newname);
1432         return rval;
1433 }
1434
1435 int
1436 link_path(pathname_t *name1, pathname_t *name2)
1437 {
1438         char            buf1[NAME_MAX + 1];
1439         char            buf2[NAME_MAX + 1];
1440         int             down1;
1441         pathname_t      newname1;
1442         pathname_t      newname2;
1443         int             rval;
1444
1445         rval = link(name1->path, name2->path);
1446         if (rval >= 0 || errno != ENAMETOOLONG)
1447                 return rval;
1448         separate_pathname(name1, buf1, &newname1);
1449         separate_pathname(name2, buf2, &newname2);
1450         if (strcmp(buf1, buf2) == 0) {
1451                 if (chdir(buf1) == 0) {
1452                         rval = link_path(&newname1, &newname2);
1453                         assert(chdir("..") == 0);
1454                 }
1455         } else {
1456                 if (strcmp(buf1, "..") == 0)
1457                         down1 = 0;
1458                 else if (strcmp(buf2, "..") == 0)
1459                         down1 = 1;
1460                 else if (strlen(buf1) == 0)
1461                         down1 = 0;
1462                 else if (strlen(buf2) == 0)
1463                         down1 = 1;
1464                 else
1465                         down1 = MAX(newname1.len, 3 + name2->len) <=
1466                                 MAX(3 + name1->len, newname2.len);
1467                 if (down1) {
1468                         free_pathname(&newname2);
1469                         append_pathname(&newname2, "../");
1470                         append_pathname(&newname2, name2->path);
1471                         if (chdir(buf1) == 0) {
1472                                 rval = link_path(&newname1, &newname2);
1473                                 assert(chdir("..") == 0);
1474                         }
1475                 } else {
1476                         free_pathname(&newname1);
1477                         append_pathname(&newname1, "../");
1478                         append_pathname(&newname1, name1->path);
1479                         if (chdir(buf2) == 0) {
1480                                 rval = link_path(&newname1, &newname2);
1481                                 assert(chdir("..") == 0);
1482                         }
1483                 }
1484         }
1485         free_pathname(&newname1);
1486         free_pathname(&newname2);
1487         return rval;
1488 }
1489
1490 int
1491 lstat64_path(pathname_t *name, struct stat64 *sbuf)
1492 {
1493         char            buf[NAME_MAX + 1];
1494         pathname_t      newname;
1495         int             rval;
1496
1497         rval = lstat64(name->path, sbuf);
1498         if (rval >= 0 || errno != ENAMETOOLONG)
1499                 return rval;
1500         separate_pathname(name, buf, &newname);
1501         if (chdir(buf) == 0) {
1502                 rval = lstat64_path(&newname, sbuf);
1503                 assert(chdir("..") == 0);
1504         }
1505         free_pathname(&newname);
1506         return rval;
1507 }
1508
1509 void
1510 make_freq_table(void)
1511 {
1512         int             f;
1513         int             i;
1514         opdesc_t        *p;
1515
1516         for (p = ops, f = 0; p < ops_end; p++)
1517                 f += p->freq;
1518         freq_table = malloc(f * sizeof(*freq_table));
1519         freq_table_size = f;
1520         for (p = ops, i = 0; p < ops_end; p++) {
1521                 for (f = 0; f < p->freq; f++, i++)
1522                         freq_table[i] = p - ops;
1523         }
1524 }
1525
1526 int
1527 mkdir_path(pathname_t *name, mode_t mode)
1528 {
1529         char            buf[NAME_MAX + 1];
1530         pathname_t      newname;
1531         int             rval;
1532
1533         rval = mkdir(name->path, mode);
1534         if (rval >= 0 || errno != ENAMETOOLONG)
1535                 return rval;
1536         separate_pathname(name, buf, &newname);
1537         if (chdir(buf) == 0) {
1538                 rval = mkdir_path(&newname, mode);
1539                 assert(chdir("..") == 0);
1540         }
1541         free_pathname(&newname);
1542         return rval;
1543 }
1544
1545 int
1546 mknod_path(pathname_t *name, mode_t mode, dev_t dev)
1547 {
1548         char            buf[NAME_MAX + 1];
1549         pathname_t      newname;
1550         int             rval;
1551
1552         rval = mknod(name->path, mode, dev);
1553         if (rval >= 0 || errno != ENAMETOOLONG)
1554                 return rval;
1555         separate_pathname(name, buf, &newname);
1556         if (chdir(buf) == 0) {
1557                 rval = mknod_path(&newname, mode, dev);
1558                 assert(chdir("..") == 0);
1559         }
1560         free_pathname(&newname);
1561         return rval;
1562 }
1563
1564 void
1565 namerandpad(int id, char *buf, int i)
1566 {
1567         int             bucket;
1568         static int      buckets[] =
1569                                 { 2, 4, 8, 16, 32, 64, 128, NAME_MAX };
1570         int             padlen;
1571         int             padmod;
1572
1573         if (namerand == 0)
1574                 return;
1575         bucket = (id ^ namerand) % (sizeof(buckets) / sizeof(buckets[0]));
1576         padmod = buckets[bucket] + 1 - i;
1577         if (padmod <= 0)
1578                 return;
1579         padlen = (id ^ namerand) % padmod;
1580         if (padlen) {
1581                 memset(&buf[i], 'X', padlen);
1582                 buf[i + padlen] = '\0';
1583         }
1584 }
1585
1586 int
1587 open_file_or_dir(pathname_t *name, int flags)
1588 {
1589         int fd;
1590
1591         fd = open_path(name, flags);
1592         if (fd != -1)
1593                 return fd;
1594         if (fd == -1 && errno != EISDIR)
1595                 return fd;
1596         /* Directories can not be opened in write mode nor direct mode. */
1597         flags &= ~(O_WRONLY | O_DIRECT);
1598         flags |= O_RDONLY | O_DIRECTORY;
1599         return open_path(name, flags);
1600 }
1601
1602 int
1603 open_path(pathname_t *name, int oflag)
1604 {
1605         char            buf[NAME_MAX + 1];
1606         pathname_t      newname;
1607         int             rval;
1608
1609         rval = open(name->path, oflag);
1610         if (rval >= 0 || errno != ENAMETOOLONG)
1611                 return rval;
1612         separate_pathname(name, buf, &newname);
1613         if (chdir(buf) == 0) {
1614                 rval = open_path(&newname, oflag);
1615                 assert(chdir("..") == 0);
1616         }
1617         free_pathname(&newname);
1618         return rval;
1619 }
1620
1621 DIR *
1622 opendir_path(pathname_t *name)
1623 {
1624         char            buf[NAME_MAX + 1];
1625         pathname_t      newname;
1626         DIR             *rval;
1627
1628         rval = opendir(name->path);
1629         if (rval || errno != ENAMETOOLONG)
1630                 return rval;
1631         separate_pathname(name, buf, &newname);
1632         if (chdir(buf) == 0) {
1633                 rval = opendir_path(&newname);
1634                 assert(chdir("..") == 0);
1635         }
1636         free_pathname(&newname);
1637         return rval;
1638 }
1639
1640 void
1641 process_freq(char *arg)
1642 {
1643         opdesc_t        *p;
1644         char            *s;
1645
1646         s = strchr(arg, '=');
1647         if (s == NULL) {
1648                 fprintf(stderr, "bad argument '%s'\n", arg);
1649                 exit(1);
1650         }
1651         *s++ = '\0';
1652         for (p = ops; p < ops_end; p++) {
1653                 if (strcmp(arg, p->name) == 0) {
1654                         p->freq = atoi(s);
1655                         return;
1656                 }
1657         }
1658         fprintf(stderr, "can't find op type %s for -f\n", arg);
1659         exit(1);
1660 }
1661
1662 int
1663 readlink_path(pathname_t *name, char *lbuf, size_t lbufsiz)
1664 {
1665         char            buf[NAME_MAX + 1];
1666         pathname_t      newname;
1667         int             rval;
1668
1669         rval = readlink(name->path, lbuf, lbufsiz);
1670         if (rval >= 0 || errno != ENAMETOOLONG)
1671                 return rval;
1672         separate_pathname(name, buf, &newname);
1673         if (chdir(buf) == 0) {
1674                 rval = readlink_path(&newname, lbuf, lbufsiz);
1675                 assert(chdir("..") == 0);
1676         }
1677         free_pathname(&newname);
1678         return rval;
1679 }
1680
1681 int
1682 rename_path(pathname_t *name1, pathname_t *name2, int mode)
1683 {
1684         char            buf1[NAME_MAX + 1];
1685         char            buf2[NAME_MAX + 1];
1686         int             down1;
1687         pathname_t      newname1;
1688         pathname_t      newname2;
1689         int             rval;
1690
1691         if (mode == 0)
1692                 rval = rename(name1->path, name2->path);
1693         else
1694                 rval = renameat2(AT_FDCWD, name1->path,
1695                                  AT_FDCWD, name2->path, mode);
1696         if (rval >= 0 || errno != ENAMETOOLONG)
1697                 return rval;
1698         separate_pathname(name1, buf1, &newname1);
1699         separate_pathname(name2, buf2, &newname2);
1700         if (strcmp(buf1, buf2) == 0) {
1701                 if (chdir(buf1) == 0) {
1702                         rval = rename_path(&newname1, &newname2, mode);
1703                         assert(chdir("..") == 0);
1704                 }
1705         } else {
1706                 if (strcmp(buf1, "..") == 0)
1707                         down1 = 0;
1708                 else if (strcmp(buf2, "..") == 0)
1709                         down1 = 1;
1710                 else if (strlen(buf1) == 0)
1711                         down1 = 0;
1712                 else if (strlen(buf2) == 0)
1713                         down1 = 1;
1714                 else
1715                         down1 = MAX(newname1.len, 3 + name2->len) <=
1716                                 MAX(3 + name1->len, newname2.len);
1717                 if (down1) {
1718                         free_pathname(&newname2);
1719                         append_pathname(&newname2, "../");
1720                         append_pathname(&newname2, name2->path);
1721                         if (chdir(buf1) == 0) {
1722                                 rval = rename_path(&newname1, &newname2, mode);
1723                                 assert(chdir("..") == 0);
1724                         }
1725                 } else {
1726                         free_pathname(&newname1);
1727                         append_pathname(&newname1, "../");
1728                         append_pathname(&newname1, name1->path);
1729                         if (chdir(buf2) == 0) {
1730                                 rval = rename_path(&newname1, &newname2, mode);
1731                                 assert(chdir("..") == 0);
1732                         }
1733                 }
1734         }
1735         free_pathname(&newname1);
1736         free_pathname(&newname2);
1737         return rval;
1738 }
1739
1740 int
1741 rmdir_path(pathname_t *name)
1742 {
1743         char            buf[NAME_MAX + 1];
1744         pathname_t      newname;
1745         int             rval;
1746
1747         rval = rmdir(name->path);
1748         if (rval >= 0 || errno != ENAMETOOLONG)
1749                 return rval;
1750         separate_pathname(name, buf, &newname);
1751         if (chdir(buf) == 0) {
1752                 rval = rmdir_path(&newname);
1753                 assert(chdir("..") == 0);
1754         }
1755         free_pathname(&newname);
1756         return rval;
1757 }
1758
1759 void
1760 separate_pathname(pathname_t *name, char *buf, pathname_t *newname)
1761 {
1762         char    *slash;
1763
1764         init_pathname(newname);
1765         slash = strchr(name->path, '/');
1766         if (slash == NULL) {
1767                 buf[0] = '\0';
1768                 return;
1769         }
1770         *slash = '\0';
1771         strcpy(buf, name->path);
1772         *slash = '/';
1773         append_pathname(newname, slash + 1);
1774 }
1775
1776 #define WIDTH 80
1777
1778 void
1779 show_ops(int flag, char *lead_str)
1780 {
1781         opdesc_t        *p;
1782
1783         if (flag<0) {
1784                 /* print in list form */
1785                 int             x = WIDTH;
1786                 
1787                 for (p = ops; p < ops_end; p++) {
1788                         if (lead_str != NULL && x+strlen(p->name)>=WIDTH-5)
1789                                 x=printf("%s%s", (p==ops)?"":"\n", lead_str);
1790                         x+=printf("%s ", p->name);
1791                 }
1792                 printf("\n");
1793         } else if (flag == 0) {
1794                 /* Table view style */
1795                 int             f;
1796                 for (f = 0, p = ops; p < ops_end; p++)
1797                         f += p->freq;
1798
1799                 if (f == 0)
1800                         flag = 1;
1801
1802                 for (p = ops; p < ops_end; p++) {
1803                         if (flag != 0 || p->freq > 0) {
1804                                 if (lead_str != NULL)
1805                                         printf("%s", lead_str);
1806                                 printf("%20s %d/%d %s\n",
1807                                 p->name, p->freq, f,
1808                                 (p->iswrite == 0) ? " " : "write op");
1809                         }
1810                 }
1811         } else {
1812                 /* Command line style */
1813                 if (lead_str != NULL)
1814                         printf("%s", lead_str);
1815                 printf ("-z -s %ld -m %d -n %lld -p %d \\\n", seed, idmodulo,
1816                         operations, nproc);
1817                 for (p = ops; p < ops_end; p++)
1818                         if (p->freq > 0)
1819                                 printf("-f %s=%d \\\n",p->name, p->freq);
1820         }
1821 }
1822
1823 int
1824 stat64_path(pathname_t *name, struct stat64 *sbuf)
1825 {
1826         char            buf[NAME_MAX + 1];
1827         pathname_t      newname;
1828         int             rval;
1829
1830         rval = stat64(name->path, sbuf);
1831         if (rval >= 0 || errno != ENAMETOOLONG)
1832                 return rval;
1833         separate_pathname(name, buf, &newname);
1834         if (chdir(buf) == 0) {
1835                 rval = stat64_path(&newname, sbuf);
1836                 assert(chdir("..") == 0);
1837         }
1838         free_pathname(&newname);
1839         return rval;
1840 }
1841
1842 int
1843 symlink_path(const char *name1, pathname_t *name)
1844 {
1845         char            buf[NAME_MAX + 1];
1846         pathname_t      newname;
1847         int             rval;
1848         
1849         if (!strcmp(name1, name->path)) {
1850             printf("yikes! %s %s\n", name1, name->path);
1851             return 0;
1852         }
1853
1854         rval = symlink(name1, name->path);
1855         if (rval >= 0 || errno != ENAMETOOLONG)
1856                 return rval;
1857         separate_pathname(name, buf, &newname);
1858         if (chdir(buf) == 0) {
1859                 rval = symlink_path(name1, &newname);
1860                 assert(chdir("..") == 0);
1861         }
1862         free_pathname(&newname);
1863         return rval;
1864 }
1865
1866 int
1867 truncate64_path(pathname_t *name, off64_t length)
1868 {
1869         char            buf[NAME_MAX + 1];
1870         pathname_t      newname;
1871         int             rval;
1872
1873         rval = truncate64(name->path, length);
1874         if (rval >= 0 || errno != ENAMETOOLONG)
1875                 return rval;
1876         separate_pathname(name, buf, &newname);
1877         if (chdir(buf) == 0) {
1878                 rval = truncate64_path(&newname, length);
1879                 assert(chdir("..") == 0);
1880         }
1881         free_pathname(&newname);
1882         return rval;
1883 }
1884
1885 int
1886 unlink_path(pathname_t *name)
1887 {
1888         char            buf[NAME_MAX + 1];
1889         pathname_t      newname;
1890         int             rval;
1891
1892         rval = unlink(name->path);
1893         if (rval >= 0 || errno != ENAMETOOLONG)
1894                 return rval;
1895         separate_pathname(name, buf, &newname);
1896         if (chdir(buf) == 0) {
1897                 rval = unlink_path(&newname);
1898                 assert(chdir("..") == 0);
1899         }
1900         free_pathname(&newname);
1901         return rval;
1902 }
1903
1904 void
1905 usage(void)
1906 {
1907         printf("Usage: %s -H   or\n", myprog);
1908         printf("       %s [-c][-d dir][-e errtg][-f op_name=freq][-l loops][-n nops]\n",
1909                 myprog);
1910         printf("          [-p nproc][-r len][-s seed][-v][-w][-x cmd][-z][-S][-X ncmd]\n");
1911         printf("where\n");
1912         printf("   -c               clean up the test directory after each run\n");
1913         printf("   -d dir           specifies the base directory for operations\n");
1914         printf("   -e errtg         specifies error injection stuff\n");
1915         printf("   -f op_name=freq  changes the frequency of option name to freq\n");
1916         printf("                    the valid operation names are:\n");
1917         show_ops(-1, "                        ");
1918         printf("   -i filenum       get verbose output for this nth file object\n");
1919         printf("   -l loops         specifies the no. of times the testrun should loop.\n");
1920         printf("                     *use 0 for infinite (default 1)\n");
1921         printf("   -m modulo        uid/gid modulo for chown/chgrp (default 32)\n");
1922         printf("   -n nops          specifies the no. of operations per process (default 1)\n");
1923         printf("   -o logfile       specifies logfile name\n");
1924         printf("   -p nproc         specifies the no. of processes (default 1)\n");
1925         printf("   -r               specifies random name padding\n");
1926         printf("   -s seed          specifies the seed for the random generator (default random)\n");
1927         printf("   -v               specifies verbose mode\n");
1928         printf("   -w               zeros frequencies of non-write operations\n");
1929         printf("   -x cmd           execute command in the middle of operations\n");
1930         printf("   -z               zeros frequencies of all operations\n");
1931         printf("   -S [c,t]         prints the list of operations (omitting zero frequency) in command line or table style\n");
1932         printf("   -V               specifies verifiable logging mode (omitting inode numbers)\n");
1933         printf("   -X ncmd          number of calls to the -x command (default 1)\n");
1934         printf("   -H               prints usage and exits\n");
1935 }
1936
1937 void
1938 write_freq(void)
1939 {
1940         opdesc_t        *p;
1941
1942         for (p = ops; p < ops_end; p++) {
1943                 if (!p->iswrite)
1944                         p->freq = 0;
1945         }
1946 }
1947
1948 void
1949 zero_freq(void)
1950 {
1951         opdesc_t        *p;
1952
1953         for (p = ops; p < ops_end; p++)
1954                 p->freq = 0;
1955 }
1956
1957 #define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
1958
1959 opty_t btrfs_ops[] = {
1960         OP_SNAPSHOT,
1961         OP_SUBVOL_CREATE,
1962         OP_SUBVOL_DELETE,
1963 };
1964
1965 void
1966 non_btrfs_freq(const char *path)
1967 {
1968         int                     i;
1969 #ifdef HAVE_BTRFSUTIL_H
1970         enum btrfs_util_error   e;
1971
1972         e = btrfs_util_is_subvolume(path);
1973         if (e != BTRFS_UTIL_ERROR_NOT_BTRFS)
1974                 return;
1975 #endif
1976         for (i = 0; i < ARRAY_SIZE(btrfs_ops); i++)
1977                 ops[btrfs_ops[i]].freq = 0;
1978 }
1979
1980 void inode_info(char *str, size_t sz, struct stat64 *s, int verbose)
1981 {
1982         if (verbose)
1983                 snprintf(str, sz, "[%ld %ld %d %d %lld %lld]",
1984                          verifiable_log ? -1: (long)s->st_ino,
1985                          (long)s->st_nlink,  s->st_uid, s->st_gid,
1986                          (long long) s->st_blocks, (long long) s->st_size);
1987 }
1988
1989 void
1990 afsync_f(opnum_t opno, long r)
1991 {
1992 #ifdef AIO
1993         int             e;
1994         pathname_t      f;
1995         int             fd;
1996         int             v;
1997         struct iocb     iocb;
1998         struct iocb     *iocbs[] = { &iocb };
1999         struct io_event event;
2000
2001         init_pathname(&f);
2002         if (!get_fname(FT_REGFILE | FT_DIRm, r, &f, NULL, NULL, &v)) {
2003                 if (v)
2004                         printf("%d/%lld: afsync - no filename\n", procid, opno);
2005                 free_pathname(&f);
2006                 return;
2007         }
2008         fd = open_file_or_dir(&f, O_WRONLY | O_DIRECT);
2009         e = fd < 0 ? errno : 0;
2010         check_cwd();
2011         if (fd < 0) {
2012                 if (v)
2013                         printf("%d/%lld: afsync - open %s failed %d\n",
2014                                procid, opno, f.path, e);
2015                 free_pathname(&f);
2016                 return;
2017         }
2018
2019         io_prep_fsync(&iocb, fd);
2020         if ((e = io_submit(io_ctx, 1, iocbs)) != 1) {
2021                 if (v)
2022                         printf("%d/%lld: afsync - io_submit %s %d\n",
2023                                procid, opno, f.path, e);
2024                 free_pathname(&f);
2025                 close(fd);
2026                 return;
2027         }
2028         if ((e = io_getevents(io_ctx, 1, 1, &event, NULL)) != 1) {
2029                 if (v)
2030                         printf("%d/%lld: afsync - io_getevents failed %d\n",
2031                                procid, opno, e);
2032                 free_pathname(&f);
2033                 close(fd);
2034                 return;
2035         }
2036
2037         e = event.res2;
2038         if (v)
2039                 printf("%d/%lld: afsync %s %d\n", procid, opno, f.path, e);
2040         free_pathname(&f);
2041         close(fd);
2042 #endif
2043 }
2044
2045 void
2046 allocsp_f(opnum_t opno, long r)
2047 {
2048         int             e;
2049         pathname_t      f;
2050         int             fd;
2051         struct xfs_flock64      fl;
2052         int64_t         lr;
2053         off64_t         off;
2054         struct stat64   stb;
2055         int             v;
2056         char            st[1024];
2057
2058         init_pathname(&f);
2059         if (!get_fname(FT_REGFILE, r, &f, NULL, NULL, &v)) {
2060                 if (v)
2061                         printf("%d/%lld: allocsp - no filename\n", procid, opno);
2062                 free_pathname(&f);
2063                 return;
2064         }
2065         fd = open_path(&f, O_RDWR);
2066         e = fd < 0 ? errno : 0;
2067         check_cwd();
2068         if (fd < 0) {
2069                 if (v)
2070                         printf("%d/%lld: allocsp - open %s failed %d\n",
2071                                 procid, opno, f.path, e);
2072                 free_pathname(&f);
2073                 return;
2074         }
2075         if (fstat64(fd, &stb) < 0) {
2076                 if (v)
2077                         printf("%d/%lld: allocsp - fstat64 %s failed %d\n",
2078                                 procid, opno, f.path, errno);
2079                 free_pathname(&f);
2080                 close(fd);
2081                 return;
2082         }
2083         inode_info(st, sizeof(st), &stb, v);
2084         lr = ((int64_t)random() << 32) + random();
2085         off = (off64_t)(lr % MIN(stb.st_size + (1024 * 1024), MAXFSIZE));
2086         off %= maxfsize;
2087         fl.l_whence = SEEK_SET;
2088         fl.l_start = off;
2089         fl.l_len = 0;
2090         e = xfsctl(f.path, fd, XFS_IOC_ALLOCSP64, &fl) < 0 ? errno : 0;
2091         if (v) {
2092                 printf("%d/%lld: xfsctl(XFS_IOC_ALLOCSP64) %s%s %lld 0 %d\n",
2093                        procid, opno, f.path, st, (long long)off, e);
2094         }
2095         free_pathname(&f);
2096         close(fd);
2097 }
2098
2099 #ifdef AIO
2100 void
2101 do_aio_rw(opnum_t opno, long r, int flags)
2102 {
2103         int64_t         align;
2104         char            *buf = NULL;
2105         struct dioattr  diob;
2106         int             e;
2107         pathname_t      f;
2108         int             fd = -1;
2109         size_t          len;
2110         int64_t         lr;
2111         off64_t         off;
2112         struct stat64   stb;
2113         int             v;
2114         char            st[1024];
2115         char            *dio_env;
2116         struct iocb     iocb;
2117         struct io_event event;
2118         struct iocb     *iocbs[] = { &iocb };
2119         int             iswrite = (flags & (O_WRONLY | O_RDWR)) ? 1 : 0;
2120
2121         init_pathname(&f);
2122         if (!get_fname(FT_REGFILE, r, &f, NULL, NULL, &v)) {
2123                 if (v)
2124                         printf("%d/%lld: do_aio_rw - no filename\n", procid, opno);
2125                 goto aio_out;
2126         }
2127         fd = open_path(&f, flags|O_DIRECT);
2128         e = fd < 0 ? errno : 0;
2129         check_cwd();
2130         if (fd < 0) {
2131                 if (v)
2132                         printf("%d/%lld: do_aio_rw - open %s failed %d\n",
2133                                procid, opno, f.path, e);
2134                 goto aio_out;
2135         }
2136         if (fstat64(fd, &stb) < 0) {
2137                 if (v)
2138                         printf("%d/%lld: do_aio_rw - fstat64 %s failed %d\n",
2139                                procid, opno, f.path, errno);
2140                 goto aio_out;
2141         }
2142         inode_info(st, sizeof(st), &stb, v);
2143         if (!iswrite && stb.st_size == 0) {
2144                 if (v)
2145                         printf("%d/%lld: do_aio_rw - %s%s zero size\n", procid, opno,
2146                                f.path, st);
2147                 goto aio_out;
2148         }
2149         if (xfsctl(f.path, fd, XFS_IOC_DIOINFO, &diob) < 0) {
2150                 if (v)
2151                         printf(
2152                         "%d/%lld: do_aio_rw - xfsctl(XFS_IOC_DIOINFO) %s%s return %d,"
2153                         " fallback to stat()\n",
2154                                 procid, opno, f.path, st, errno);
2155                 diob.d_mem = diob.d_miniosz = stb.st_blksize;
2156                 diob.d_maxiosz = rounddown_64(INT_MAX, diob.d_miniosz);
2157         }
2158         dio_env = getenv("XFS_DIO_MIN");
2159         if (dio_env)
2160                 diob.d_mem = diob.d_miniosz = atoi(dio_env);
2161         align = (int64_t)diob.d_miniosz;
2162         lr = ((int64_t)random() << 32) + random();
2163         len = (random() % FILELEN_MAX) + 1;
2164         len -= (len % align);
2165         if (len <= 0)
2166                 len = align;
2167         else if (len > diob.d_maxiosz)
2168                 len = diob.d_maxiosz;
2169         buf = memalign(diob.d_mem, len);
2170         if (!buf) {
2171                 if (v)
2172                         printf("%d/%lld: do_aio_rw - memalign failed\n",
2173                                procid, opno);
2174                 goto aio_out;
2175         }
2176
2177         if (iswrite) {
2178                 off = (off64_t)(lr % MIN(stb.st_size + (1024 * 1024), MAXFSIZE));
2179                 off -= (off % align);
2180                 off %= maxfsize;
2181                 memset(buf, nameseq & 0xff, len);
2182                 io_prep_pwrite(&iocb, fd, buf, len, off);
2183         } else {
2184                 off = (off64_t)(lr % stb.st_size);
2185                 off -= (off % align);
2186                 io_prep_pread(&iocb, fd, buf, len, off);
2187         }
2188         if ((e = io_submit(io_ctx, 1, iocbs)) != 1) {
2189                 if (v)
2190                         printf("%d/%lld: %s - io_submit failed %d\n",
2191                                procid, opno, iswrite ? "awrite" : "aread", e);
2192                 goto aio_out;
2193         }
2194         if ((e = io_getevents(io_ctx, 1, 1, &event, NULL)) != 1) {
2195                 if (v)
2196                         printf("%d/%lld: %s - io_getevents failed %d\n",
2197                                procid, opno, iswrite ? "awrite" : "aread", e);
2198                 goto aio_out;
2199         }
2200
2201         e = event.res != len ? event.res2 : 0;
2202         if (v)
2203                 printf("%d/%lld: %s %s%s [%lld,%d] %d\n",
2204                        procid, opno, iswrite ? "awrite" : "aread",
2205                        f.path, st, (long long)off, (int)len, e);
2206  aio_out:
2207         if (buf)
2208                 free(buf);
2209         if (fd != -1)
2210                 close(fd);
2211         free_pathname(&f);
2212 }
2213 #endif
2214
2215 #ifdef URING
2216 void
2217 do_uring_rw(opnum_t opno, long r, int flags)
2218 {
2219         char            *buf = NULL;
2220         int             e;
2221         pathname_t      f;
2222         int             fd = -1;
2223         size_t          len;
2224         int64_t         lr;
2225         off64_t         off;
2226         struct stat64   stb;
2227         int             v;
2228         char            st[1024];
2229         struct io_uring_sqe     *sqe;
2230         struct io_uring_cqe     *cqe;
2231         struct iovec    iovec;
2232         int             iswrite = (flags & (O_WRONLY | O_RDWR)) ? 1 : 0;
2233
2234         if (!have_io_uring)
2235                 return;
2236
2237         init_pathname(&f);
2238         if (!get_fname(FT_REGFILE, r, &f, NULL, NULL, &v)) {
2239                 if (v)
2240                         printf("%d/%lld: do_uring_rw - no filename\n", procid, opno);
2241                 goto uring_out;
2242         }
2243         fd = open_path(&f, flags);
2244         e = fd < 0 ? errno : 0;
2245         check_cwd();
2246         if (fd < 0) {
2247                 if (v)
2248                         printf("%d/%lld: do_uring_rw - open %s failed %d\n",
2249                                procid, opno, f.path, e);
2250                 goto uring_out;
2251         }
2252         if (fstat64(fd, &stb) < 0) {
2253                 if (v)
2254                         printf("%d/%lld: do_uring_rw - fstat64 %s failed %d\n",
2255                                procid, opno, f.path, errno);
2256                 goto uring_out;
2257         }
2258         inode_info(st, sizeof(st), &stb, v);
2259         if (!iswrite && stb.st_size == 0) {
2260                 if (v)
2261                         printf("%d/%lld: do_uring_rw - %s%s zero size\n", procid, opno,
2262                                f.path, st);
2263                 goto uring_out;
2264         }
2265         sqe = io_uring_get_sqe(&ring);
2266         if (!sqe) {
2267                 if (v)
2268                         printf("%d/%lld: do_uring_rw - io_uring_get_sqe failed\n",
2269                                procid, opno);
2270                 goto uring_out;
2271         }
2272         lr = ((int64_t)random() << 32) + random();
2273         len = (random() % FILELEN_MAX) + 1;
2274         buf = malloc(len);
2275         if (!buf) {
2276                 if (v)
2277                         printf("%d/%lld: do_uring_rw - malloc failed\n",
2278                                procid, opno);
2279                 goto uring_out;
2280         }
2281         iovec.iov_base = buf;
2282         iovec.iov_len = len;
2283         if (iswrite) {
2284                 off = (off64_t)(lr % MIN(stb.st_size + (1024 * 1024), MAXFSIZE));
2285                 off %= maxfsize;
2286                 memset(buf, nameseq & 0xff, len);
2287                 io_uring_prep_writev(sqe, fd, &iovec, 1, off);
2288         } else {
2289                 off = (off64_t)(lr % stb.st_size);
2290                 io_uring_prep_readv(sqe, fd, &iovec, 1, off);
2291         }
2292
2293         if ((e = io_uring_submit_and_wait(&ring, 1)) != 1) {
2294                 if (v)
2295                         printf("%d/%lld: %s - io_uring_submit failed %d\n", procid, opno,
2296                                iswrite ? "uring_write" : "uring_read", e);
2297                 goto uring_out;
2298         }
2299         if ((e = io_uring_wait_cqe(&ring, &cqe)) < 0) {
2300                 if (v)
2301                         printf("%d/%lld: %s - io_uring_wait_cqe failed %d\n", procid, opno,
2302                                iswrite ? "uring_write" : "uring_read", e);
2303                 goto uring_out;
2304         }
2305         if (v)
2306                 printf("%d/%lld: %s %s%s [%lld, %d(res=%d)] %d\n",
2307                        procid, opno, iswrite ? "uring_write" : "uring_read",
2308                        f.path, st, (long long)off, (int)len, cqe->res, e);
2309         io_uring_cqe_seen(&ring, cqe);
2310
2311  uring_out:
2312         if (buf)
2313                 free(buf);
2314         if (fd != -1)
2315                 close(fd);
2316         free_pathname(&f);
2317 }
2318 #endif
2319
2320 void
2321 aread_f(opnum_t opno, long r)
2322 {
2323 #ifdef AIO
2324         do_aio_rw(opno, r, O_RDONLY);
2325 #endif
2326 }
2327
2328 void
2329 attr_remove_f(opnum_t opno, long r)
2330 {
2331         char                    *bufname;
2332         char                    *bufend;
2333         char                    *aname = NULL;
2334         char                    buf[XATTR_LIST_MAX];
2335         int                     e;
2336         int                     ent;
2337         pathname_t              f;
2338         int                     total = 0;
2339         int                     v;
2340         int                     which;
2341
2342         init_pathname(&f);
2343         if (!get_fname(FT_ANYm, r, &f, NULL, NULL, &v))
2344                 append_pathname(&f, ".");
2345         e = attr_list_path(&f, buf, sizeof(buf));
2346         check_cwd();
2347         if (e > 0)
2348                 total = attr_list_count(buf, e);
2349         if (total == 0) {
2350                 if (v)
2351                         printf("%d/%lld: attr_remove - no attrs for %s\n",
2352                                 procid, opno, f.path);
2353                 free_pathname(&f);
2354                 return;
2355         }
2356
2357         which = (int)(random() % total);
2358         bufname = buf;
2359         bufend = buf + e;
2360         ent = 0;
2361         while (bufname < bufend) {
2362                 if (which < ent) {
2363                         aname = bufname;
2364                         break;
2365                 }
2366                 ent++;
2367                 bufname += strlen(bufname) + 1;
2368         }
2369         if (aname == NULL) {
2370                 if (v)
2371                         printf(
2372                         "%d/%lld: attr_remove - name %d not found at %s\n",
2373                                 procid, opno, which, f.path);
2374                 free_pathname(&f);
2375                 return;
2376         }
2377         if (attr_remove_path(&f, aname) < 0)
2378                 e = errno;
2379         else
2380                 e = 0;
2381         check_cwd();
2382         if (v)
2383                 printf("%d/%lld: attr_remove %s %s %d\n",
2384                         procid, opno, f.path, aname, e);
2385         free_pathname(&f);
2386 }
2387
2388 void
2389 attr_set_f(opnum_t opno, long r)
2390 {
2391         char            aname[10];
2392         char            *aval;
2393         int             e;
2394         pathname_t      f;
2395         int             len;
2396         static int      lengths[] = { 10, 100, 1000, 10000 };
2397         int             li;
2398         int             v;
2399
2400         init_pathname(&f);
2401         if (!get_fname(FT_ANYm, r, &f, NULL, NULL, &v))
2402                 append_pathname(&f, ".");
2403         sprintf(aname, "a%x", nameseq++);
2404         li = (int)(random() % (sizeof(lengths) / sizeof(lengths[0])));
2405         len = (int)(random() % lengths[li]);
2406         if (len == 0)
2407                 len = 1;
2408         aval = malloc(len);
2409         memset(aval, nameseq & 0xff, len);
2410         if (attr_set_path(&f, aname, aval, len) < 0)
2411                 e = errno;
2412         else
2413                 e = 0;
2414         check_cwd();
2415         free(aval);
2416         if (v)
2417                 printf("%d/%lld: attr_set %s %s %d\n", procid, opno, f.path,
2418                         aname, e);
2419         free_pathname(&f);
2420 }
2421
2422 void
2423 awrite_f(opnum_t opno, long r)
2424 {
2425 #ifdef AIO
2426         do_aio_rw(opno, r, O_WRONLY);
2427 #endif
2428 }
2429
2430 void
2431 bulkstat_f(opnum_t opno, long r)
2432 {
2433         int             count;
2434         int             fd;
2435         __u64           last;
2436         int             nent;
2437         struct xfs_bstat        *t;
2438         int64_t         total;
2439         struct xfs_fsop_bulkreq bsr;
2440
2441         last = 0;
2442         nent = (r % 999) + 2;
2443         t = malloc(nent * sizeof(*t));
2444         fd = open(".", O_RDONLY);
2445         total = 0;
2446
2447         bsr.lastip=&last;
2448         bsr.icount=nent;
2449         bsr.ubuffer=t;
2450         bsr.ocount=&count;
2451             
2452         while (xfsctl(".", fd, XFS_IOC_FSBULKSTAT, &bsr) == 0 && count > 0)
2453                 total += count;
2454         free(t);
2455         if (verbose)
2456                 printf("%d/%lld: bulkstat nent %d total %lld\n",
2457                         procid, opno, nent, (long long)total);
2458         close(fd);
2459 }
2460
2461 void
2462 bulkstat1_f(opnum_t opno, long r)
2463 {
2464         int             e;
2465         pathname_t      f;
2466         int             fd;
2467         int             good;
2468         __u64           ino;
2469         struct stat64   s;
2470         struct xfs_bstat        t;
2471         int             v;
2472         struct xfs_fsop_bulkreq bsr;
2473         
2474
2475         good = random() & 1;
2476         if (good) {
2477                /* use an inode we know exists */
2478                 init_pathname(&f);
2479                 if (!get_fname(FT_ANYm, r, &f, NULL, NULL, &v))
2480                         append_pathname(&f, ".");
2481                 ino = stat64_path(&f, &s) < 0 ? (ino64_t)r : s.st_ino;
2482                 check_cwd();
2483                 free_pathname(&f);
2484         } else {
2485                 /* 
2486                  * pick a random inode 
2487                  *
2488                  * note this can generate kernel warning messages
2489                  * since bulkstat_one will read the disk block that
2490                  * would contain a given inode even if that disk
2491                  * block doesn't contain inodes.
2492                  *
2493                  * this is detected later, but not until after the
2494                  * warning is displayed.
2495                  *
2496                  * "XFS: device 0x825- bad inode magic/vsn daddr 0x0 #0"
2497                  *
2498                  */
2499                 ino = (ino64_t)r;
2500                 v = verbose;
2501         }
2502         fd = open(".", O_RDONLY);
2503         
2504         bsr.lastip=&ino;
2505         bsr.icount=1;
2506         bsr.ubuffer=&t;
2507         bsr.ocount=NULL;
2508         e = xfsctl(".", fd, XFS_IOC_FSBULKSTAT_SINGLE, &bsr) < 0 ? errno : 0;
2509         if (v)
2510                 printf("%d/%lld: bulkstat1 %s ino %lld %d\n",
2511                        procid, opno, good?"real":"random",
2512                        verifiable_log ? -1LL : (long long)ino, e);
2513         close(fd);
2514 }
2515
2516 void
2517 chown_f(opnum_t opno, long r)
2518 {
2519         int             e;
2520         pathname_t      f;
2521         int             nbits;
2522         uid_t           u;
2523         gid_t           g;
2524         int             v;
2525
2526         init_pathname(&f);
2527         if (!get_fname(FT_ANYm, r, &f, NULL, NULL, &v))
2528                 append_pathname(&f, ".");
2529         u = (uid_t)random();
2530         g = (gid_t)random();
2531         nbits = (int)(random() % idmodulo);
2532         u &= (1 << nbits) - 1;
2533         g &= (1 << nbits) - 1;
2534         e = lchown_path(&f, u, g) < 0 ? errno : 0;
2535         check_cwd();
2536         if (v)
2537                 printf("%d/%lld: chown %s %d/%d %d\n", procid, opno, f.path, (int)u, (int)g, e);
2538         free_pathname(&f);
2539 }
2540
2541 /* reflink some arbitrary range of f1 to f2. */
2542 void
2543 clonerange_f(
2544         opnum_t                 opno,
2545         long                    r)
2546 {
2547 #ifdef FICLONERANGE
2548         struct file_clone_range fcr;
2549         struct pathname         fpath1;
2550         struct pathname         fpath2;
2551         struct stat64           stat1;
2552         struct stat64           stat2;
2553         char                    inoinfo1[1024];
2554         char                    inoinfo2[1024];
2555         off64_t                 lr;
2556         off64_t                 off1;
2557         off64_t                 off2;
2558         off64_t                 max_off2;
2559         size_t                  len;
2560         int                     v1;
2561         int                     v2;
2562         int                     fd1;
2563         int                     fd2;
2564         int                     ret;
2565         int                     e;
2566
2567         /* Load paths */
2568         init_pathname(&fpath1);
2569         if (!get_fname(FT_REGm, r, &fpath1, NULL, NULL, &v1)) {
2570                 if (v1)
2571                         printf("%d/%lld: clonerange read - no filename\n",
2572                                 procid, opno);
2573                 goto out_fpath1;
2574         }
2575
2576         init_pathname(&fpath2);
2577         if (!get_fname(FT_REGm, random(), &fpath2, NULL, NULL, &v2)) {
2578                 if (v2)
2579                         printf("%d/%lld: clonerange write - no filename\n",
2580                                 procid, opno);
2581                 goto out_fpath2;
2582         }
2583
2584         /* Open files */
2585         fd1 = open_path(&fpath1, O_RDONLY);
2586         e = fd1 < 0 ? errno : 0;
2587         check_cwd();
2588         if (fd1 < 0) {
2589                 if (v1)
2590                         printf("%d/%lld: clonerange read - open %s failed %d\n",
2591                                 procid, opno, fpath1.path, e);
2592                 goto out_fpath2;
2593         }
2594
2595         fd2 = open_path(&fpath2, O_WRONLY);
2596         e = fd2 < 0 ? errno : 0;
2597         check_cwd();
2598         if (fd2 < 0) {
2599                 if (v2)
2600                         printf("%d/%lld: clonerange write - open %s failed %d\n",
2601                                 procid, opno, fpath2.path, e);
2602                 goto out_fd1;
2603         }
2604
2605         /* Get file stats */
2606         if (fstat64(fd1, &stat1) < 0) {
2607                 if (v1)
2608                         printf("%d/%lld: clonerange read - fstat64 %s failed %d\n",
2609                                 procid, opno, fpath1.path, errno);
2610                 goto out_fd2;
2611         }
2612         inode_info(inoinfo1, sizeof(inoinfo1), &stat1, v1);
2613
2614         if (fstat64(fd2, &stat2) < 0) {
2615                 if (v2)
2616                         printf("%d/%lld: clonerange write - fstat64 %s failed %d\n",
2617                                 procid, opno, fpath2.path, errno);
2618                 goto out_fd2;
2619         }
2620         inode_info(inoinfo2, sizeof(inoinfo2), &stat2, v2);
2621
2622         /* Calculate offsets */
2623         len = (random() % FILELEN_MAX) + 1;
2624         len = rounddown_64(len, stat1.st_blksize);
2625         if (len == 0)
2626                 len = stat1.st_blksize;
2627         if (len > stat1.st_size)
2628                 len = stat1.st_size;
2629
2630         lr = ((int64_t)random() << 32) + random();
2631         if (stat1.st_size == len)
2632                 off1 = 0;
2633         else
2634                 off1 = (off64_t)(lr % MIN(stat1.st_size - len, MAXFSIZE));
2635         off1 %= maxfsize;
2636         off1 = rounddown_64(off1, stat1.st_blksize);
2637
2638         /*
2639          * If srcfile == destfile, randomly generate destination ranges
2640          * until we find one that doesn't overlap the source range.
2641          */
2642         max_off2 = MIN(stat2.st_size + (1024ULL * stat2.st_blksize), MAXFSIZE);
2643         do {
2644                 lr = ((int64_t)random() << 32) + random();
2645                 off2 = (off64_t)(lr % max_off2);
2646                 off2 %= maxfsize;
2647                 off2 = rounddown_64(off2, stat2.st_blksize);
2648         } while (stat1.st_ino == stat2.st_ino && llabs(off2 - off1) < len);
2649
2650         /* Clone data blocks */
2651         fcr.src_fd = fd1;
2652         fcr.src_offset = off1;
2653         fcr.src_length = len;
2654         fcr.dest_offset = off2;
2655
2656         ret = ioctl(fd2, FICLONERANGE, &fcr);
2657         e = ret < 0 ? errno : 0;
2658         if (v1 || v2) {
2659                 printf("%d/%lld: clonerange %s%s [%lld,%lld] -> %s%s [%lld,%lld]",
2660                         procid, opno,
2661                         fpath1.path, inoinfo1, (long long)off1, (long long)len,
2662                         fpath2.path, inoinfo2, (long long)off2, (long long)len);
2663
2664                 if (ret < 0)
2665                         printf(" error %d", e);
2666                 printf("\n");
2667         }
2668
2669 out_fd2:
2670         close(fd2);
2671 out_fd1:
2672         close(fd1);
2673 out_fpath2:
2674         free_pathname(&fpath2);
2675 out_fpath1:
2676         free_pathname(&fpath1);
2677 #endif
2678 }
2679
2680 /* copy some arbitrary range of f1 to f2. */
2681 void
2682 copyrange_f(
2683         opnum_t                 opno,
2684         long                    r)
2685 {
2686 #ifdef HAVE_COPY_FILE_RANGE
2687         struct pathname         fpath1;
2688         struct pathname         fpath2;
2689         struct stat64           stat1;
2690         struct stat64           stat2;
2691         char                    inoinfo1[1024];
2692         char                    inoinfo2[1024];
2693         loff_t                  lr;
2694         loff_t                  off1;
2695         loff_t                  off2;
2696         loff_t                  offset1;
2697         loff_t                  offset2;
2698         loff_t                  max_off2;
2699         size_t                  len;
2700         size_t                  length;
2701         int                     tries = 0;
2702         int                     v1;
2703         int                     v2;
2704         int                     fd1;
2705         int                     fd2;
2706         size_t                  ret = 0;
2707         int                     e;
2708
2709         /* Load paths */
2710         init_pathname(&fpath1);
2711         if (!get_fname(FT_REGm, r, &fpath1, NULL, NULL, &v1)) {
2712                 if (v1)
2713                         printf("%d/%lld: copyrange read - no filename\n",
2714                                 procid, opno);
2715                 goto out_fpath1;
2716         }
2717
2718         init_pathname(&fpath2);
2719         if (!get_fname(FT_REGm, random(), &fpath2, NULL, NULL, &v2)) {
2720                 if (v2)
2721                         printf("%d/%lld: copyrange write - no filename\n",
2722                                 procid, opno);
2723                 goto out_fpath2;
2724         }
2725
2726         /* Open files */
2727         fd1 = open_path(&fpath1, O_RDONLY);
2728         e = fd1 < 0 ? errno : 0;
2729         check_cwd();
2730         if (fd1 < 0) {
2731                 if (v1)
2732                         printf("%d/%lld: copyrange read - open %s failed %d\n",
2733                                 procid, opno, fpath1.path, e);
2734                 goto out_fpath2;
2735         }
2736
2737         fd2 = open_path(&fpath2, O_WRONLY);
2738         e = fd2 < 0 ? errno : 0;
2739         check_cwd();
2740         if (fd2 < 0) {
2741                 if (v2)
2742                         printf("%d/%lld: copyrange write - open %s failed %d\n",
2743                                 procid, opno, fpath2.path, e);
2744                 goto out_fd1;
2745         }
2746
2747         /* Get file stats */
2748         if (fstat64(fd1, &stat1) < 0) {
2749                 if (v1)
2750                         printf("%d/%lld: copyrange read - fstat64 %s failed %d\n",
2751                                 procid, opno, fpath1.path, errno);
2752                 goto out_fd2;
2753         }
2754         inode_info(inoinfo1, sizeof(inoinfo1), &stat1, v1);
2755
2756         if (fstat64(fd2, &stat2) < 0) {
2757                 if (v2)
2758                         printf("%d/%lld: copyrange write - fstat64 %s failed %d\n",
2759                                 procid, opno, fpath2.path, errno);
2760                 goto out_fd2;
2761         }
2762         inode_info(inoinfo2, sizeof(inoinfo2), &stat2, v2);
2763
2764         /* Calculate offsets */
2765         len = (random() % FILELEN_MAX) + 1;
2766         if (len == 0)
2767                 len = stat1.st_blksize;
2768         if (len > stat1.st_size)
2769                 len = stat1.st_size;
2770
2771         lr = ((int64_t)random() << 32) + random();
2772         if (stat1.st_size == len)
2773                 off1 = 0;
2774         else
2775                 off1 = (off64_t)(lr % MIN(stat1.st_size - len, MAXFSIZE));
2776         off1 %= maxfsize;
2777
2778         /*
2779          * If srcfile == destfile, randomly generate destination ranges
2780          * until we find one that doesn't overlap the source range.
2781          */
2782         max_off2 = MIN(stat2.st_size + (1024ULL * stat2.st_blksize), MAXFSIZE);
2783         do {
2784                 lr = ((int64_t)random() << 32) + random();
2785                 off2 = (off64_t)(lr % max_off2);
2786                 off2 %= maxfsize;
2787         } while (stat1.st_ino == stat2.st_ino && llabs(off2 - off1) < len);
2788
2789         /*
2790          * Since len, off1 and off2 will be changed later, preserve their
2791          * original values.
2792          */
2793         length = len;
2794         offset1 = off1;
2795         offset2 = off2;
2796
2797         while (len > 0) {
2798                 ret = syscall(__NR_copy_file_range, fd1, &off1, fd2, &off2,
2799                               len, 0);
2800                 if (ret < 0) {
2801                         if (errno != EAGAIN || tries++ >= 300)
2802                                 break;
2803                 } else if (ret > len || ret == 0)
2804                         break;
2805                 else if (ret > 0)
2806                         len -= ret;
2807         }
2808         e = ret < 0 ? errno : 0;
2809         if (v1 || v2) {
2810                 printf("%d/%lld: copyrange %s%s [%lld,%lld] -> %s%s [%lld,%lld]",
2811                         procid, opno,
2812                         fpath1.path, inoinfo1,
2813                         (long long)offset1, (long long)length,
2814                         fpath2.path, inoinfo2,
2815                         (long long)offset2, (long long)length);
2816
2817                 if (ret < 0)
2818                         printf(" error %d", e);
2819                 else if (len && ret > len)
2820                         printf(" asked for %lld, copied %lld??\n",
2821                                 (long long)len, (long long)ret);
2822                 printf("\n");
2823         }
2824
2825 out_fd2:
2826         close(fd2);
2827 out_fd1:
2828         close(fd1);
2829 out_fpath2:
2830         free_pathname(&fpath2);
2831 out_fpath1:
2832         free_pathname(&fpath1);
2833 #endif
2834 }
2835
2836 /* dedupe some arbitrary range of f1 to f2...fn. */
2837 void
2838 deduperange_f(
2839         opnum_t                 opno,
2840         long                    r)
2841 {
2842 #ifdef FIDEDUPERANGE
2843 #define INFO_SZ                 1024
2844         struct file_dedupe_range *fdr;
2845         struct pathname         *fpath;
2846         struct stat64           *stat;
2847         char                    *info;
2848         off64_t                 *off;
2849         int                     *v;
2850         int                     *fd;
2851         int                     nr;
2852         off64_t                 lr;
2853         size_t                  len;
2854         int                     ret;
2855         int                     i;
2856         int                     e;
2857
2858         if (flist[FT_REG].nfiles < 2)
2859                 return;
2860
2861         /* Pick somewhere between 2 and 128 files. */
2862         do {
2863                 nr = random() % (flist[FT_REG].nfiles + 1);
2864         } while (nr < 2 || nr > 128);
2865
2866         /* Alloc memory */
2867         fdr = malloc(nr * sizeof(struct file_dedupe_range_info) +
2868                      sizeof(struct file_dedupe_range));
2869         if (!fdr) {
2870                 printf("%d/%lld: line %d error %d\n",
2871                         procid, opno, __LINE__, errno);
2872                 return;
2873         }
2874         memset(fdr, 0, (nr * sizeof(struct file_dedupe_range_info) +
2875                         sizeof(struct file_dedupe_range)));
2876
2877         fpath = calloc(nr, sizeof(struct pathname));
2878         if (!fpath) {
2879                 printf("%d/%lld: line %d error %d\n",
2880                         procid, opno, __LINE__, errno);
2881                 goto out_fdr;
2882         }
2883
2884         stat = calloc(nr, sizeof(struct stat64));
2885         if (!stat) {
2886                 printf("%d/%lld: line %d error %d\n",
2887                         procid, opno, __LINE__, errno);
2888                 goto out_paths;
2889         }
2890
2891         info = calloc(nr, INFO_SZ);
2892         if (!info) {
2893                 printf("%d/%lld: line %d error %d\n",
2894                         procid, opno, __LINE__, errno);
2895                 goto out_stats;
2896         }
2897
2898         off = calloc(nr, sizeof(off64_t));
2899         if (!off) {
2900                 printf("%d/%lld: line %d error %d\n",
2901                         procid, opno, __LINE__, errno);
2902                 goto out_info;
2903         }
2904
2905         v = calloc(nr, sizeof(int));
2906         if (!v) {
2907                 printf("%d/%lld: line %d error %d\n",
2908                         procid, opno, __LINE__, errno);
2909                 goto out_offsets;
2910         }
2911         fd = calloc(nr, sizeof(int));
2912         if (!fd) {
2913                 printf("%d/%lld: line %d error %d\n",
2914                         procid, opno, __LINE__, errno);
2915                 goto out_v;
2916         }
2917         memset(fd, 0xFF, nr * sizeof(int));
2918
2919         /* Get paths for all files */
2920         for (i = 0; i < nr; i++)
2921                 init_pathname(&fpath[i]);
2922
2923         if (!get_fname(FT_REGm, r, &fpath[0], NULL, NULL, &v[0])) {
2924                 if (v[0])
2925                         printf("%d/%lld: deduperange read - no filename\n",
2926                                 procid, opno);
2927                 goto out_pathnames;
2928         }
2929
2930         for (i = 1; i < nr; i++) {
2931                 if (!get_fname(FT_REGm, random(), &fpath[i], NULL, NULL, &v[i])) {
2932                         if (v[i])
2933                                 printf("%d/%lld: deduperange write - no filename\n",
2934                                         procid, opno);
2935                         goto out_pathnames;
2936                 }
2937         }
2938
2939         /* Open files */
2940         fd[0] = open_path(&fpath[0], O_RDONLY);
2941         e = fd[0] < 0 ? errno : 0;
2942         check_cwd();
2943         if (fd[0] < 0) {
2944                 if (v[0])
2945                         printf("%d/%lld: deduperange read - open %s failed %d\n",
2946                                 procid, opno, fpath[0].path, e);
2947                 goto out_pathnames;
2948         }
2949
2950         for (i = 1; i < nr; i++) {
2951                 fd[i] = open_path(&fpath[i], O_WRONLY);
2952                 e = fd[i] < 0 ? errno : 0;
2953                 check_cwd();
2954                 if (fd[i] < 0) {
2955                         if (v[i])
2956                                 printf("%d/%lld: deduperange write - open %s failed %d\n",
2957                                         procid, opno, fpath[i].path, e);
2958                         goto out_fds;
2959                 }
2960         }
2961
2962         /* Get file stats */
2963         if (fstat64(fd[0], &stat[0]) < 0) {
2964                 if (v[0])
2965                         printf("%d/%lld: deduperange read - fstat64 %s failed %d\n",
2966                                 procid, opno, fpath[0].path, errno);
2967                 goto out_fds;
2968         }
2969
2970         inode_info(&info[0], INFO_SZ, &stat[0], v[0]);
2971
2972         for (i = 1; i < nr; i++) {
2973                 if (fstat64(fd[i], &stat[i]) < 0) {
2974                         if (v[i])
2975                                 printf("%d/%lld: deduperange write - fstat64 %s failed %d\n",
2976                                         procid, opno, fpath[i].path, errno);
2977                         goto out_fds;
2978                 }
2979                 inode_info(&info[i * INFO_SZ], INFO_SZ, &stat[i], v[i]);
2980         }
2981
2982         /* Never try to dedupe more than half of the src file. */
2983         len = (random() % FILELEN_MAX) + 1;
2984         len = rounddown_64(len, stat[0].st_blksize);
2985         if (len == 0)
2986                 len = stat[0].st_blksize / 2;
2987         if (len > stat[0].st_size / 2)
2988                 len = stat[0].st_size / 2;
2989
2990         /* Calculate offsets */
2991         lr = ((int64_t)random() << 32) + random();
2992         if (stat[0].st_size == len)
2993                 off[0] = 0;
2994         else
2995                 off[0] = (off64_t)(lr % MIN(stat[0].st_size - len, MAXFSIZE));
2996         off[0] %= maxfsize;
2997         off[0] = rounddown_64(off[0], stat[0].st_blksize);
2998
2999         /*
3000          * If srcfile == destfile[i], randomly generate destination ranges
3001          * until we find one that doesn't overlap the source range.
3002          */
3003         for (i = 1; i < nr; i++) {
3004                 int     tries = 0;
3005
3006                 do {
3007                         lr = ((int64_t)random() << 32) + random();
3008                         if (stat[i].st_size <= len)
3009                                 off[i] = 0;
3010                         else
3011                                 off[i] = (off64_t)(lr % MIN(stat[i].st_size - len, MAXFSIZE));
3012                         off[i] %= maxfsize;
3013                         off[i] = rounddown_64(off[i], stat[i].st_blksize);
3014                 } while (stat[0].st_ino == stat[i].st_ino &&
3015                          llabs(off[i] - off[0]) < len &&
3016                          tries++ < 10);
3017         }
3018
3019         /* Clone data blocks */
3020         fdr->src_offset = off[0];
3021         fdr->src_length = len;
3022         fdr->dest_count = nr - 1;
3023         for (i = 1; i < nr; i++) {
3024                 fdr->info[i - 1].dest_fd = fd[i];
3025                 fdr->info[i - 1].dest_offset = off[i];
3026         }
3027
3028         ret = ioctl(fd[0], FIDEDUPERANGE, fdr);
3029         e = ret < 0 ? errno : 0;
3030         if (v[0]) {
3031                 printf("%d/%lld: deduperange from %s%s [%lld,%lld]",
3032                         procid, opno,
3033                         fpath[0].path, &info[0], (long long)off[0],
3034                         (long long)len);
3035                 if (ret < 0)
3036                         printf(" error %d", e);
3037                 printf("\n");
3038         }
3039         if (ret < 0)
3040                 goto out_fds;
3041
3042         for (i = 1; i < nr; i++) {
3043                 e = fdr->info[i - 1].status < 0 ? fdr->info[i - 1].status : 0;
3044                 if (v[i]) {
3045                         printf("%d/%lld: ...to %s%s [%lld,%lld]",
3046                                 procid, opno,
3047                                 fpath[i].path, &info[i * INFO_SZ],
3048                                 (long long)off[i], (long long)len);
3049                         if (fdr->info[i - 1].status < 0)
3050                                 printf(" error %d", e);
3051                         if (fdr->info[i - 1].status == FILE_DEDUPE_RANGE_SAME)
3052                                 printf(" %llu bytes deduplicated",
3053                                         fdr->info[i - 1].bytes_deduped);
3054                         if (fdr->info[i - 1].status == FILE_DEDUPE_RANGE_DIFFERS)
3055                                 printf(" differed");
3056                         printf("\n");
3057                 }
3058         }
3059
3060 out_fds:
3061         for (i = 0; i < nr; i++)
3062                 if (fd[i] >= 0)
3063                         close(fd[i]);
3064 out_pathnames:
3065         for (i = 0; i < nr; i++)
3066                 free_pathname(&fpath[i]);
3067
3068         free(fd);
3069 out_v:
3070         free(v);
3071 out_offsets:
3072         free(off);
3073 out_info:
3074         free(info);
3075 out_stats:
3076         free(stat);
3077 out_paths:
3078         free(fpath);
3079 out_fdr:
3080         free(fdr);
3081 #endif
3082 }
3083
3084 void
3085 setxattr_f(opnum_t opno, long r)
3086 {
3087 #ifdef XFS_XFLAG_EXTSIZE
3088         struct fsxattr  fsx;
3089         int             fd;
3090         int             e;
3091         pathname_t      f;
3092         int             nbits;
3093         uint            p;
3094         int             v;
3095
3096         init_pathname(&f);
3097         if (!get_fname(FT_ANYm, r, &f, NULL, NULL, &v))
3098                 append_pathname(&f, ".");
3099         fd = open_path(&f, O_RDWR);
3100         e = fd < 0 ? errno : 0;
3101         check_cwd();
3102
3103         /* project ID */
3104         p = (uint)random();
3105         e = MIN(idmodulo, XFS_PROJIDMODULO_MAX);
3106         nbits = (int)(random() % e);
3107         p &= (1 << nbits) - 1;
3108
3109         if ((e = xfsctl(f.path, fd, XFS_IOC_FSGETXATTR, &fsx)) == 0) {
3110                 fsx.fsx_projid = p;
3111                 e = xfsctl(f.path, fd, XFS_IOC_FSSETXATTR, &fsx);
3112         }
3113         if (v)
3114                 printf("%d/%lld: setxattr %s %u %d\n", procid, opno, f.path, p, e);
3115         free_pathname(&f);
3116         close(fd);
3117 #endif
3118 }
3119
3120 void
3121 splice_f(opnum_t opno, long r)
3122 {
3123         struct pathname         fpath1;
3124         struct pathname         fpath2;
3125         struct stat64           stat1;
3126         struct stat64           stat2;
3127         char                    inoinfo1[1024];
3128         char                    inoinfo2[1024];
3129         loff_t                  lr;
3130         loff_t                  off1, off2;
3131         size_t                  len;
3132         loff_t                  offset1, offset2;
3133         size_t                  length;
3134         size_t                  total;
3135         int                     v1;
3136         int                     v2;
3137         int                     fd1;
3138         int                     fd2;
3139         ssize_t                 ret1 = 0, ret2 = 0;
3140         size_t                  bytes;
3141         int                     e;
3142         int                     filedes[2];
3143
3144         /* Load paths */
3145         init_pathname(&fpath1);
3146         if (!get_fname(FT_REGm, r, &fpath1, NULL, NULL, &v1)) {
3147                 if (v1)
3148                         printf("%d/%lld: splice read - no filename\n",
3149                                 procid, opno);
3150                 goto out_fpath1;
3151         }
3152
3153         init_pathname(&fpath2);
3154         if (!get_fname(FT_REGm, random(), &fpath2, NULL, NULL, &v2)) {
3155                 if (v2)
3156                         printf("%d/%lld: splice write - no filename\n",
3157                                 procid, opno);
3158                 goto out_fpath2;
3159         }
3160
3161         /* Open files */
3162         fd1 = open_path(&fpath1, O_RDONLY);
3163         e = fd1 < 0 ? errno : 0;
3164         check_cwd();
3165         if (fd1 < 0) {
3166                 if (v1)
3167                         printf("%d/%lld: splice read - open %s failed %d\n",
3168                                 procid, opno, fpath1.path, e);
3169                 goto out_fpath2;
3170         }
3171
3172         fd2 = open_path(&fpath2, O_WRONLY);
3173         e = fd2 < 0 ? errno : 0;
3174         check_cwd();
3175         if (fd2 < 0) {
3176                 if (v2)
3177                         printf("%d/%lld: splice write - open %s failed %d\n",
3178                                 procid, opno, fpath2.path, e);
3179                 goto out_fd1;
3180         }
3181
3182         /* Get file stats */
3183         if (fstat64(fd1, &stat1) < 0) {
3184                 if (v1)
3185                         printf("%d/%lld: splice read - fstat64 %s failed %d\n",
3186                                 procid, opno, fpath1.path, errno);
3187                 goto out_fd2;
3188         }
3189         inode_info(inoinfo1, sizeof(inoinfo1), &stat1, v1);
3190
3191         if (fstat64(fd2, &stat2) < 0) {
3192                 if (v2)
3193                         printf("%d/%lld: splice write - fstat64 %s failed %d\n",
3194                                 procid, opno, fpath2.path, errno);
3195                 goto out_fd2;
3196         }
3197         inode_info(inoinfo2, sizeof(inoinfo2), &stat2, v2);
3198
3199         /* Calculate offsets */
3200         len = (random() % FILELEN_MAX) + 1;
3201         if (len == 0)
3202                 len = stat1.st_blksize;
3203         if (len > stat1.st_size)
3204                 len = stat1.st_size;
3205
3206         lr = ((int64_t)random() << 32) + random();
3207         if (stat1.st_size == len)
3208                 off1 = 0;
3209         else
3210                 off1 = (off64_t)(lr % MIN(stat1.st_size - len, MAXFSIZE));
3211         off1 %= maxfsize;
3212
3213         /*
3214          * splice can overlap write, so the offset of the target file can be
3215          * any number. But to avoid too large offset, add a clamp of 1024 blocks
3216          * past the current dest file EOF
3217          */
3218         lr = ((int64_t)random() << 32) + random();
3219         off2 = (off64_t)(lr % MIN(stat2.st_size + (1024ULL * stat2.st_blksize), MAXFSIZE));
3220
3221         /*
3222          * Since len, off1 and off2 will be changed later, preserve their
3223          * original values.
3224          */
3225         length = len;
3226         offset1 = off1;
3227         offset2 = off2;
3228
3229         /* Pipe initialize */
3230         if (pipe(filedes) < 0) {
3231                 if (v1 || v2) {
3232                         printf("%d/%lld: splice - pipe failed %d\n",
3233                                 procid, opno, errno);
3234                         goto out_fd2;
3235                 }
3236         }
3237
3238         bytes = 0;
3239         total = 0;
3240         while (len > 0) {
3241                 /* move to pipe buffer */
3242                 ret1 = splice(fd1, &off1, filedes[1], NULL, len, 0);
3243                 if (ret1 <= 0) {
3244                         break;
3245                 }
3246                 bytes = ret1;
3247
3248                 /* move from pipe buffer to dst file */
3249                 while (bytes > 0) {
3250                         ret2 = splice(filedes[0], NULL, fd2, &off2, bytes, 0);
3251                         if (ret2 < 0) {
3252                                 break;
3253                         }
3254                         bytes -= ret2;
3255                 }
3256                 if (ret2 < 0)
3257                         break;
3258
3259                 len -= ret1;
3260                 total += ret1;
3261         }
3262
3263         if (ret1 < 0 || ret2 < 0)
3264                 e = errno;
3265         else
3266                 e = 0;
3267         if (v1 || v2) {
3268                 printf("%d/%lld: splice %s%s [%lld,%lld] -> %s%s [%lld,%lld] %d",
3269                         procid, opno,
3270                         fpath1.path, inoinfo1, (long long)offset1, (long long)length,
3271                         fpath2.path, inoinfo2, (long long)offset2, (long long)length, e);
3272
3273                 if (length && length > total)
3274                         printf(" asked for %lld, spliced %lld??\n",
3275                                 (long long)length, (long long)total);
3276                 printf("\n");
3277         }
3278
3279         close(filedes[0]);
3280         close(filedes[1]);
3281 out_fd2:
3282         close(fd2);
3283 out_fd1:
3284         close(fd1);
3285 out_fpath2:
3286         free_pathname(&fpath2);
3287 out_fpath1:
3288         free_pathname(&fpath1);
3289 }
3290
3291 void
3292 creat_f(opnum_t opno, long r)
3293 {
3294         struct fsxattr  a;
3295         int             e;
3296         int             e1;
3297         int             extsize;
3298         pathname_t      f;
3299         int             fd;
3300         fent_t          *fep;
3301         int             id;
3302         int             parid;
3303         int             type;
3304         int             v;
3305         int             v1;
3306
3307         if (!get_fname(FT_ANYDIR, r, NULL, NULL, &fep, &v1))
3308                 parid = -1;
3309         else
3310                 parid = fep->id;
3311         init_pathname(&f);
3312         e1 = (random() % 100);
3313         type = rtpct ? ((e1 > rtpct) ? FT_REG : FT_RTF) : FT_REG;
3314 #ifdef NOTYET
3315         if (type == FT_RTF)     /* rt always gets an extsize */
3316                 extsize = (random() % 10) + 1;
3317         else if (e1 < 10)       /* one-in-ten get an extsize */
3318                 extsize = random() % 1024;
3319         else
3320 #endif
3321                 extsize = 0;
3322         e = generate_fname(fep, type, &f, &id, &v);
3323         v |= v1;
3324         if (!e) {
3325                 if (v) {
3326                         (void)fent_to_name(&f, fep);
3327                         printf("%d/%lld: creat - no filename from %s\n",
3328                                 procid, opno, f.path);
3329                 }
3330                 free_pathname(&f);
3331                 return;
3332         }
3333         fd = creat_path(&f, 0666);
3334         e = fd < 0 ? errno : 0;
3335         e1 = 0;
3336         check_cwd();
3337         if (fd >= 0) {
3338                 if (extsize &&
3339                     xfsctl(f.path, fd, XFS_IOC_FSGETXATTR, &a) >= 0) {
3340                         if (type == FT_RTF) {
3341                                 a.fsx_xflags |= XFS_XFLAG_REALTIME;
3342                                 a.fsx_extsize = extsize *
3343                                                 geom.rtextsize * geom.blocksize;
3344 #ifdef NOTYET
3345                         } else if (extsize) {
3346                                 a.fsx_xflags |= XFS_XFLAG_EXTSIZE;
3347                                 a.fsx_extsize = extsize * geom.blocksize;
3348 #endif
3349                         }
3350                         if (xfsctl(f.path, fd, XFS_IOC_FSSETXATTR, &a) < 0)
3351                                 e1 = errno;
3352                 }
3353                 add_to_flist(type, id, parid, 0);
3354                 close(fd);
3355         }
3356         if (v) {
3357                 printf("%d/%lld: creat %s x:%d %d %d\n", procid, opno, f.path,
3358                         extsize ? a.fsx_extsize : 0, e, e1);
3359                 printf("%d/%lld: creat add id=%d,parent=%d\n", procid, opno, id, parid);
3360         }
3361         free_pathname(&f);
3362 }
3363
3364 void
3365 dread_f(opnum_t opno, long r)
3366 {
3367         int64_t         align;
3368         char            *buf;
3369         struct dioattr  diob;
3370         int             e;
3371         pathname_t      f;
3372         int             fd;
3373         size_t          len;
3374         int64_t         lr;
3375         off64_t         off;
3376         struct stat64   stb;
3377         int             v;
3378         char            st[1024];
3379         char            *dio_env;
3380
3381         init_pathname(&f);
3382         if (!get_fname(FT_REGFILE, r, &f, NULL, NULL, &v)) {
3383                 if (v)
3384                         printf("%d/%lld: dread - no filename\n", procid, opno);
3385                 free_pathname(&f);
3386                 return;
3387         }
3388         fd = open_path(&f, O_RDONLY|O_DIRECT);
3389         e = fd < 0 ? errno : 0;
3390         check_cwd();
3391         if (fd < 0) {
3392                 if (v)
3393                         printf("%d/%lld: dread - open %s failed %d\n",
3394                                 procid, opno, f.path, e);
3395                 free_pathname(&f);
3396                 return;
3397         }
3398         if (fstat64(fd, &stb) < 0) {
3399                 if (v)
3400                         printf("%d/%lld: dread - fstat64 %s failed %d\n",
3401                                procid, opno, f.path, errno);
3402                 free_pathname(&f);
3403                 close(fd);
3404                 return;
3405         }
3406         inode_info(st, sizeof(st), &stb, v);
3407         if (stb.st_size == 0) {
3408                 if (v)
3409                         printf("%d/%lld: dread - %s%s zero size\n", procid, opno,
3410                                f.path, st);
3411                 free_pathname(&f);
3412                 close(fd);
3413                 return;
3414         }
3415         if (xfsctl(f.path, fd, XFS_IOC_DIOINFO, &diob) < 0) {
3416                 if (v)
3417                         printf(
3418                         "%d/%lld: dread - xfsctl(XFS_IOC_DIOINFO) %s%s return %d,"
3419                         " fallback to stat()\n",
3420                                 procid, opno, f.path, st, errno);
3421                 diob.d_mem = diob.d_miniosz = stb.st_blksize;
3422                 diob.d_maxiosz = rounddown_64(INT_MAX, diob.d_miniosz);
3423         }
3424
3425         dio_env = getenv("XFS_DIO_MIN");
3426         if (dio_env)
3427                 diob.d_mem = diob.d_miniosz = atoi(dio_env);
3428
3429         align = (int64_t)diob.d_miniosz;
3430         lr = ((int64_t)random() << 32) + random();
3431         off = (off64_t)(lr % stb.st_size);
3432         off -= (off % align);
3433         lseek64(fd, off, SEEK_SET);
3434         len = (random() % FILELEN_MAX) + 1;
3435         len -= (len % align);
3436         if (len <= 0)
3437                 len = align;
3438         else if (len > diob.d_maxiosz) 
3439                 len = diob.d_maxiosz;
3440         buf = memalign(diob.d_mem, len);
3441         e = read(fd, buf, len) < 0 ? errno : 0;
3442         free(buf);
3443         if (v)
3444                 printf("%d/%lld: dread %s%s [%lld,%d] %d\n",
3445                        procid, opno, f.path, st, (long long)off, (int)len, e);
3446         free_pathname(&f);
3447         close(fd);
3448 }
3449
3450 void
3451 dwrite_f(opnum_t opno, long r)
3452 {
3453         int64_t         align;
3454         char            *buf;
3455         struct dioattr  diob;
3456         int             e;
3457         pathname_t      f;
3458         int             fd;
3459         size_t          len;
3460         int64_t         lr;
3461         off64_t         off;
3462         struct stat64   stb;
3463         int             v;
3464         char            st[1024];
3465         char            *dio_env;
3466
3467         init_pathname(&f);
3468         if (!get_fname(FT_REGFILE, r, &f, NULL, NULL, &v)) {
3469                 if (v)
3470                         printf("%d/%lld: dwrite - no filename\n", procid, opno);
3471                 free_pathname(&f);
3472                 return;
3473         }
3474         fd = open_path(&f, O_WRONLY|O_DIRECT);
3475         e = fd < 0 ? errno : 0;
3476         check_cwd();
3477         if (fd < 0) {
3478                 if (v)
3479                         printf("%d/%lld: dwrite - open %s failed %d\n",
3480                                 procid, opno, f.path, e);
3481                 free_pathname(&f);
3482                 return;
3483         }
3484         if (fstat64(fd, &stb) < 0) {
3485                 if (v)
3486                         printf("%d/%lld: dwrite - fstat64 %s failed %d\n",
3487                                 procid, opno, f.path, errno);
3488                 free_pathname(&f);
3489                 close(fd);
3490                 return;
3491         }
3492         inode_info(st, sizeof(st), &stb, v);
3493         if (xfsctl(f.path, fd, XFS_IOC_DIOINFO, &diob) < 0) {
3494                 if (v)
3495                         printf("%d/%lld: dwrite - xfsctl(XFS_IOC_DIOINFO)"
3496                                 " %s%s return %d, fallback to stat()\n",
3497                                procid, opno, f.path, st, errno);
3498                 diob.d_mem = diob.d_miniosz = stb.st_blksize;
3499                 diob.d_maxiosz = rounddown_64(INT_MAX, diob.d_miniosz);
3500         }
3501
3502         dio_env = getenv("XFS_DIO_MIN");
3503         if (dio_env)
3504                 diob.d_mem = diob.d_miniosz = atoi(dio_env);
3505
3506         align = (int64_t)diob.d_miniosz;
3507         lr = ((int64_t)random() << 32) + random();
3508         off = (off64_t)(lr % MIN(stb.st_size + (1024 * 1024), MAXFSIZE));
3509         off -= (off % align);
3510         lseek64(fd, off, SEEK_SET);
3511         len = (random() % FILELEN_MAX) + 1;
3512         len -= (len % align);
3513         if (len <= 0)
3514                 len = align;
3515         else if (len > diob.d_maxiosz) 
3516                 len = diob.d_maxiosz;
3517         buf = memalign(diob.d_mem, len);
3518         off %= maxfsize;
3519         lseek64(fd, off, SEEK_SET);
3520         memset(buf, nameseq & 0xff, len);
3521         e = write(fd, buf, len) < 0 ? errno : 0;
3522         free(buf);
3523         if (v)
3524                 printf("%d/%lld: dwrite %s%s [%lld,%d] %d\n",
3525                        procid, opno, f.path, st, (long long)off, (int)len, e);
3526         free_pathname(&f);
3527         close(fd);
3528 }
3529
3530
3531 #ifdef HAVE_LINUX_FALLOC_H
3532 struct print_flags falloc_flags [] = {
3533         { FALLOC_FL_KEEP_SIZE, "KEEP_SIZE"},
3534         { FALLOC_FL_PUNCH_HOLE, "PUNCH_HOLE"},
3535         { FALLOC_FL_NO_HIDE_STALE, "NO_HIDE_STALE"},
3536         { FALLOC_FL_COLLAPSE_RANGE, "COLLAPSE_RANGE"},
3537         { FALLOC_FL_ZERO_RANGE, "ZERO_RANGE"},
3538         { FALLOC_FL_INSERT_RANGE, "INSERT_RANGE"},
3539         { -1, NULL}
3540 };
3541
3542 #define translate_falloc_flags(mode)    \
3543         ({translate_flags(mode, "|", falloc_flags);})
3544 #endif
3545
3546 void
3547 do_fallocate(opnum_t opno, long r, int mode)
3548 {
3549 #ifdef HAVE_LINUX_FALLOC_H
3550         int             e;
3551         pathname_t      f;
3552         int             fd;
3553         int64_t         lr;
3554         off64_t         off;
3555         off64_t         len;
3556         struct stat64   stb;
3557         int             v;
3558         char            st[1024];
3559
3560         init_pathname(&f);
3561         if (!get_fname(FT_REGFILE, r, &f, NULL, NULL, &v)) {
3562                 if (v)
3563                         printf("%d/%lld: do_fallocate - no filename\n", procid, opno);
3564                 free_pathname(&f);
3565                 return;
3566         }
3567         fd = open_path(&f, O_RDWR);
3568         if (fd < 0) {
3569                 if (v)
3570                         printf("%d/%lld: do_fallocate - open %s failed %d\n",
3571                                 procid, opno, f.path, errno);
3572                 free_pathname(&f);
3573                 return;
3574         }
3575         check_cwd();
3576         if (fstat64(fd, &stb) < 0) {
3577                 if (v)
3578                         printf("%d/%lld: do_fallocate - fstat64 %s failed %d\n",
3579                                 procid, opno, f.path, errno);
3580                 free_pathname(&f);
3581                 close(fd);
3582                 return;
3583         }
3584         inode_info(st, sizeof(st), &stb, v);
3585         lr = ((int64_t)random() << 32) + random();
3586         off = (off64_t)(lr % MIN(stb.st_size + (1024 * 1024), MAXFSIZE));
3587         off %= maxfsize;
3588         len = (off64_t)(random() % (1024 * 1024));
3589         /*
3590          * Collapse/insert range requires off and len to be block aligned,
3591          * make it more likely to be the case.
3592          */
3593         if ((mode & (FALLOC_FL_COLLAPSE_RANGE | FALLOC_FL_INSERT_RANGE)) &&
3594                 (opno % 2)) {
3595                 off = roundup_64(off, stb.st_blksize);
3596                 len = roundup_64(len, stb.st_blksize);
3597         }
3598         mode |= FALLOC_FL_KEEP_SIZE & random();
3599         e = fallocate(fd, mode, (loff_t)off, (loff_t)len) < 0 ? errno : 0;
3600         if (v)
3601                 printf("%d/%lld: fallocate(%s) %s %st %lld %lld %d\n",
3602                        procid, opno, translate_falloc_flags(mode),
3603                        f.path, st, (long long)off, (long long)len, e);
3604         free_pathname(&f);
3605         close(fd);
3606 #endif
3607 }
3608
3609 void
3610 fallocate_f(opnum_t opno, long r)
3611 {
3612 #ifdef HAVE_LINUX_FALLOC_H
3613         do_fallocate(opno, r, 0);
3614 #endif
3615 }
3616
3617 void
3618 fdatasync_f(opnum_t opno, long r)
3619 {
3620         int             e;
3621         pathname_t      f;
3622         int             fd;
3623         int             v;
3624
3625         init_pathname(&f);
3626         if (!get_fname(FT_REGFILE, r, &f, NULL, NULL, &v)) {
3627                 if (v)
3628                         printf("%d/%lld: fdatasync - no filename\n",
3629                                 procid, opno);
3630                 free_pathname(&f);
3631                 return;
3632         }
3633         fd = open_path(&f, O_WRONLY);
3634         e = fd < 0 ? errno : 0;
3635         check_cwd();
3636         if (fd < 0) {
3637                 if (v)
3638                         printf("%d/%lld: fdatasync - open %s failed %d\n",
3639                                 procid, opno, f.path, e);
3640                 free_pathname(&f);
3641                 return;
3642         }
3643         e = fdatasync(fd) < 0 ? errno : 0;
3644         if (v)
3645                 printf("%d/%lld: fdatasync %s %d\n", procid, opno, f.path, e);
3646         free_pathname(&f);
3647         close(fd);
3648 }
3649
3650 #ifdef HAVE_LINUX_FIEMAP_H
3651 struct print_flags fiemap_flags[] = {
3652         { FIEMAP_FLAG_SYNC, "SYNC"},
3653         { FIEMAP_FLAG_XATTR, "XATTR"},
3654         { -1, NULL}
3655 };
3656
3657 #define translate_fiemap_flags(mode)    \
3658         ({translate_flags(mode, "|", fiemap_flags);})
3659 #endif
3660
3661 void
3662 fiemap_f(opnum_t opno, long r)
3663 {
3664 #ifdef HAVE_LINUX_FIEMAP_H
3665         int             e;
3666         pathname_t      f;
3667         int             fd;
3668         int64_t         lr;
3669         off64_t         off;
3670         struct stat64   stb;
3671         int             v;
3672         char            st[1024];
3673         int blocks_to_map;
3674         struct fiemap *fiemap;
3675
3676         init_pathname(&f);
3677         if (!get_fname(FT_REGFILE, r, &f, NULL, NULL, &v)) {
3678                 if (v)
3679                         printf("%d/%lld: fiemap - no filename\n", procid, opno);
3680                 free_pathname(&f);
3681                 return;
3682         }
3683         fd = open_path(&f, O_RDWR);
3684         e = fd < 0 ? errno : 0;
3685         check_cwd();
3686         if (fd < 0) {
3687                 if (v)
3688                         printf("%d/%lld: fiemap - open %s failed %d\n",
3689                                 procid, opno, f.path, e);
3690                 free_pathname(&f);
3691                 return;
3692         }
3693         if (fstat64(fd, &stb) < 0) {
3694                 if (v)
3695                         printf("%d/%lld: fiemap - fstat64 %s failed %d\n",
3696                                 procid, opno, f.path, errno);
3697                 free_pathname(&f);
3698                 close(fd);
3699                 return;
3700         }
3701         inode_info(st, sizeof(st), &stb, v);
3702         blocks_to_map = random() & 0xffff;
3703         fiemap = (struct fiemap *)malloc(sizeof(struct fiemap) +
3704                         (blocks_to_map * sizeof(struct fiemap_extent)));
3705         if (!fiemap) {
3706                 if (v)
3707                         printf("%d/%lld: malloc failed \n", procid, opno);
3708                 free_pathname(&f);
3709                 close(fd);
3710                 return;
3711         }
3712         lr = ((int64_t)random() << 32) + random();
3713         off = (off64_t)(lr % MIN(stb.st_size + (1024 * 1024), MAXFSIZE));
3714         off %= maxfsize;
3715         fiemap->fm_flags = random() & (FIEMAP_FLAGS_COMPAT | 0x10000);
3716         fiemap->fm_extent_count = blocks_to_map;
3717         fiemap->fm_mapped_extents = random() & 0xffff;
3718         fiemap->fm_start = off;
3719         fiemap->fm_length = ((int64_t)random() << 32) + random();
3720
3721         e = ioctl(fd, FS_IOC_FIEMAP, (unsigned long)fiemap);
3722         if (v)
3723                 printf("%d/%lld: ioctl(FIEMAP) %s%s %lld %lld (%s) %d\n",
3724                        procid, opno, f.path, st, (long long)fiemap->fm_start,
3725                        (long long) fiemap->fm_length,
3726                        translate_fiemap_flags(fiemap->fm_flags), e);
3727         free(fiemap);
3728         free_pathname(&f);
3729         close(fd);
3730 #endif
3731 }
3732
3733 void
3734 freesp_f(opnum_t opno, long r)
3735 {
3736         int             e;
3737         pathname_t      f;
3738         int             fd;
3739         struct xfs_flock64      fl;
3740         int64_t         lr;
3741         off64_t         off;
3742         struct stat64   stb;
3743         int             v;
3744         char            st[1024];
3745
3746         init_pathname(&f);
3747         if (!get_fname(FT_REGFILE, r, &f, NULL, NULL, &v)) {
3748                 if (v)
3749                         printf("%d/%lld: freesp - no filename\n", procid, opno);
3750                 free_pathname(&f);
3751                 return;
3752         }
3753         fd = open_path(&f, O_RDWR);
3754         e = fd < 0 ? errno : 0;
3755         check_cwd();
3756         if (fd < 0) {
3757                 if (v)
3758                         printf("%d/%lld: freesp - open %s failed %d\n",
3759                                 procid, opno, f.path, e);
3760                 free_pathname(&f);
3761                 return;
3762         }
3763         if (fstat64(fd, &stb) < 0) {
3764                 if (v)
3765                         printf("%d/%lld: freesp - fstat64 %s failed %d\n",
3766                                 procid, opno, f.path, errno);
3767                 free_pathname(&f);
3768                 close(fd);
3769                 return;
3770         }
3771         inode_info(st, sizeof(st), &stb, v);
3772         lr = ((int64_t)random() << 32) + random();
3773         off = (off64_t)(lr % MIN(stb.st_size + (1024 * 1024), MAXFSIZE));
3774         off %= maxfsize;
3775         fl.l_whence = SEEK_SET;
3776         fl.l_start = off;
3777         fl.l_len = 0;
3778         e = xfsctl(f.path, fd, XFS_IOC_FREESP64, &fl) < 0 ? errno : 0;
3779         if (v)
3780                 printf("%d/%lld: xfsctl(XFS_IOC_FREESP64) %s%s %lld 0 %d\n",
3781                        procid, opno, f.path, st, (long long)off, e);
3782         free_pathname(&f);
3783         close(fd);
3784 }
3785
3786 void
3787 fsync_f(opnum_t opno, long r)
3788 {
3789         int             e;
3790         pathname_t      f;
3791         int             fd;
3792         int             v;
3793
3794         init_pathname(&f);
3795         if (!get_fname(FT_REGFILE | FT_DIRm, r, &f, NULL, NULL, &v)) {
3796                 if (v)
3797                         printf("%d/%lld: fsync - no filename\n", procid, opno);
3798                 free_pathname(&f);
3799                 return;
3800         }
3801         fd = open_file_or_dir(&f, O_WRONLY);
3802         e = fd < 0 ? errno : 0;
3803         check_cwd();
3804         if (fd < 0) {
3805                 if (v)
3806                         printf("%d/%lld: fsync - open %s failed %d\n",
3807                                 procid, opno, f.path, e);
3808                 free_pathname(&f);
3809                 return;
3810         }
3811         e = fsync(fd) < 0 ? errno : 0;
3812         if (v)
3813                 printf("%d/%lld: fsync %s %d\n", procid, opno, f.path, e);
3814         free_pathname(&f);
3815         close(fd);
3816 }
3817
3818 char *
3819 gen_random_string(int len)
3820 {
3821         static const char charset[] = "0123456789"
3822                 "abcdefghijklmnopqrstuvwxyz"
3823                 "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
3824         int i;
3825         char *s;
3826
3827         if (len == 0)
3828                 return NULL;
3829
3830         s = malloc(len);
3831         if (!s)
3832                 return NULL;
3833
3834         for (i = 0; i < len; i++)
3835                 s[i] = charset[random() % sizeof(charset)];
3836
3837         return s;
3838 }
3839
3840 void
3841 getattr_f(opnum_t opno, long r)
3842 {
3843         int             fd;
3844         int             e;
3845         pathname_t      f;
3846         uint            fl;
3847         int             v;
3848
3849         init_pathname(&f);
3850         if (!get_fname(FT_ANYm, r, &f, NULL, NULL, &v))
3851                 append_pathname(&f, ".");
3852         fd = open_path(&f, O_RDWR);
3853         e = fd < 0 ? errno : 0;
3854         check_cwd();
3855
3856         e = ioctl(fd, FS_IOC_GETFLAGS, &fl);
3857         if (v)
3858                 printf("%d/%lld: getattr %s %u %d\n", procid, opno, f.path, fl, e);
3859         free_pathname(&f);
3860         close(fd);
3861 }
3862
3863 void
3864 getdents_f(opnum_t opno, long r)
3865 {
3866         DIR             *dir;
3867         pathname_t      f;
3868         int             v;
3869
3870         init_pathname(&f);
3871         if (!get_fname(FT_ANYDIR, r, &f, NULL, NULL, &v))
3872                 append_pathname(&f, ".");
3873         dir = opendir_path(&f);
3874         check_cwd();
3875         if (dir == NULL) {
3876                 if (v)
3877                         printf("%d/%lld: getdents - can't open %s\n",
3878                                 procid, opno, f.path);
3879                 free_pathname(&f);
3880                 return;
3881         }
3882         while (readdir64(dir) != NULL)
3883                 continue;
3884         if (v)
3885                 printf("%d/%lld: getdents %s 0\n", procid, opno, f.path);
3886         free_pathname(&f);
3887         closedir(dir);
3888 }
3889
3890 void
3891 getfattr_f(opnum_t opno, long r)
3892 {
3893         fent_t          *fep;
3894         int             e;
3895         pathname_t      f;
3896         int             v;
3897         char            name[XATTR_NAME_BUF_SIZE];
3898         char            *value = NULL;
3899         int             value_len;
3900         int             xattr_num;
3901
3902         init_pathname(&f);
3903         if (!get_fname(FT_REGFILE | FT_ANYDIR, r, &f, NULL, &fep, &v)) {
3904                 if (v)
3905                         printf("%d/%lld: getfattr - no filename\n", procid, opno);
3906                 goto out;
3907         }
3908         check_cwd();
3909
3910         /*
3911          * If the file/dir has xattrs, pick one randomly, otherwise attempt
3912          * to read a xattr that doesn't exist (fgetxattr should fail with
3913          * errno set to ENOATTR (61) in this case).
3914          */
3915         if (fep->xattr_counter > 0)
3916                 xattr_num = (random() % fep->xattr_counter) + 1;
3917         else
3918                 xattr_num = 0;
3919
3920         e = generate_xattr_name(xattr_num, name, sizeof(name));
3921         if (e < 0) {
3922                 printf("%d/%lld: getfattr - file %s failed to generate xattr name: %d\n",
3923                        procid, opno, f.path, e);
3924                 goto out;
3925         }
3926
3927         value_len = getxattr(f.path, name, NULL, 0);
3928         if (value_len < 0) {
3929                 if (v)
3930                         printf("%d/%lld: getfattr file %s name %s failed %d\n",
3931                                procid, opno, f.path, name, errno);
3932                 goto out;
3933         }
3934
3935         /* A xattr without value.*/
3936         if (value_len == 0) {
3937                 e = 0;
3938                 goto out_log;
3939         }
3940
3941         value = malloc(value_len);
3942         if (!value) {
3943                 if (v)
3944                         printf("%d/%lld: getfattr file %s failed to allocate buffer with %d bytes\n",
3945                                procid, opno, f.path, value_len);
3946                 goto out;
3947         }
3948
3949         e = getxattr(f.path, name, value, value_len) < 0 ? errno : 0;
3950 out_log:
3951         if (v)
3952                 printf("%d/%lld: getfattr file %s name %s value length %d %d\n",
3953                        procid, opno, f.path, name, value_len, e);
3954 out:
3955         free(value);
3956         free_pathname(&f);
3957 }
3958
3959 void
3960 link_f(opnum_t opno, long r)
3961 {
3962         int             e;
3963         pathname_t      f;
3964         fent_t          *fep;
3965         fent_t          *fep_src;
3966         flist_t         *flp;
3967         int             id;
3968         pathname_t      l;
3969         int             parid;
3970         int             v;
3971         int             v1;
3972
3973         init_pathname(&f);
3974         if (!get_fname(FT_NOTDIR, r, &f, &flp, &fep_src, &v1)) {
3975                 if (v1)
3976                         printf("%d/%lld: link - no file\n", procid, opno);
3977                 free_pathname(&f);
3978                 return;
3979         }
3980         if (!get_fname(FT_DIRm, random(), NULL, NULL, &fep, &v))
3981                 parid = -1;
3982         else
3983                 parid = fep->id;
3984         v |= v1;
3985         init_pathname(&l);
3986         e = generate_fname(fep, flp - flist, &l, &id, &v1);
3987         v |= v1;
3988         if (!e) {
3989                 if (v) {
3990                         (void)fent_to_name(&l, fep);
3991                         printf("%d/%lld: link - no filename from %s\n",
3992                                 procid, opno, l.path);
3993                 }
3994                 free_pathname(&l);
3995                 free_pathname(&f);
3996                 return;
3997         }
3998         e = link_path(&f, &l) < 0 ? errno : 0;
3999         check_cwd();
4000         if (e == 0)
4001                 add_to_flist(flp - flist, id, parid, fep_src->xattr_counter);
4002         if (v) {
4003                 printf("%d/%lld: link %s %s %d\n", procid, opno, f.path, l.path,
4004                         e);
4005                 printf("%d/%lld: link add id=%d,parent=%d\n", procid, opno, id, parid);
4006         }
4007         free_pathname(&l);
4008         free_pathname(&f);
4009 }
4010
4011 void
4012 listfattr_f(opnum_t opno, long r)
4013 {
4014         fent_t          *fep;
4015         int             e;
4016         pathname_t      f;
4017         int             v;
4018         char            *buffer = NULL;
4019         int             buffer_len;
4020
4021         init_pathname(&f);
4022         if (!get_fname(FT_REGFILE | FT_ANYDIR, r, &f, NULL, &fep, &v)) {
4023                 if (v)
4024                         printf("%d/%lld: listfattr - no filename\n", procid, opno);
4025                 goto out;
4026         }
4027         check_cwd();
4028
4029         e = listxattr(f.path, NULL, 0);
4030         if (e < 0) {
4031                 if (v)
4032                         printf("%d/%lld: listfattr %s failed %d\n",
4033                                procid, opno, f.path, errno);
4034                 goto out;
4035         }
4036         buffer_len = e;
4037         if (buffer_len == 0) {
4038                 if (v)
4039                         printf("%d/%lld: listfattr %s - has no extended attributes\n",
4040                                procid, opno, f.path);
4041                 goto out;
4042         }
4043
4044         buffer = malloc(buffer_len);
4045         if (!buffer) {
4046                 if (v)
4047                         printf("%d/%lld: listfattr %s failed to allocate buffer with %d bytes\n",
4048                                procid, opno, f.path, buffer_len);
4049                 goto out;
4050         }
4051
4052         e = listxattr(f.path, buffer, buffer_len) < 0 ? errno : 0;
4053         if (v)
4054                 printf("%d/%lld: listfattr %s buffer length %d %d\n",
4055                        procid, opno, f.path, buffer_len, e);
4056 out:
4057         free(buffer);
4058         free_pathname(&f);
4059 }
4060
4061 void
4062 mkdir_f(opnum_t opno, long r)
4063 {
4064         int             e;
4065         pathname_t      f;
4066         fent_t          *fep;
4067         int             id;
4068         int             parid;
4069         int             v;
4070         int             v1;
4071
4072         if (!get_fname(FT_ANYDIR, r, NULL, NULL, &fep, &v))
4073                 parid = -1;
4074         else
4075                 parid = fep->id;
4076         init_pathname(&f);
4077         e = generate_fname(fep, FT_DIR, &f, &id, &v1);
4078         v |= v1;
4079         if (!e) {
4080                 if (v) {
4081                         (void)fent_to_name(&f, fep);
4082                         printf("%d/%lld: mkdir - no filename from %s\n",
4083                                 procid, opno, f.path);
4084                 }
4085                 free_pathname(&f);
4086                 return;
4087         }
4088         e = mkdir_path(&f, 0777) < 0 ? errno : 0;
4089         check_cwd();
4090         if (e == 0)
4091                 add_to_flist(FT_DIR, id, parid, 0);
4092         if (v) {
4093                 printf("%d/%lld: mkdir %s %d\n", procid, opno, f.path, e);
4094                 printf("%d/%lld: mkdir add id=%d,parent=%d\n", procid, opno, id, parid);
4095         }
4096         free_pathname(&f);
4097 }
4098
4099 void
4100 mknod_f(opnum_t opno, long r)
4101 {
4102         int             e;
4103         pathname_t      f;
4104         fent_t          *fep;
4105         int             id;
4106         int             parid;
4107         int             v;
4108         int             v1;
4109
4110         if (!get_fname(FT_ANYDIR, r, NULL, NULL, &fep, &v))
4111                 parid = -1;
4112         else
4113                 parid = fep->id;
4114         init_pathname(&f);
4115         e = generate_fname(fep, FT_DEV, &f, &id, &v1);
4116         v |= v1;
4117         if (!e) {
4118                 if (v) {
4119                         (void)fent_to_name(&f, fep);
4120                         printf("%d/%lld: mknod - no filename from %s\n",
4121                                 procid, opno, f.path);
4122                 }
4123                 free_pathname(&f);
4124                 return;
4125         }
4126         e = mknod_path(&f, S_IFCHR|0444, 0) < 0 ? errno : 0;
4127         check_cwd();
4128         if (e == 0)
4129                 add_to_flist(FT_DEV, id, parid, 0);
4130         if (v) {
4131                 printf("%d/%lld: mknod %s %d\n", procid, opno, f.path, e);
4132                 printf("%d/%lld: mknod add id=%d,parent=%d\n", procid, opno, id, parid);
4133         }
4134         free_pathname(&f);
4135 }
4136
4137 #ifdef HAVE_SYS_MMAN_H
4138 struct print_flags mmap_flags[] = {
4139         { MAP_SHARED, "SHARED"},
4140         { MAP_PRIVATE, "PRIVATE"},
4141         { -1, NULL}
4142 };
4143
4144 #define translate_mmap_flags(flags)       \
4145         ({translate_flags(flags, "|", mmap_flags);})
4146 #endif
4147
4148 void
4149 do_mmap(opnum_t opno, long r, int prot)
4150 {
4151 #ifdef HAVE_SYS_MMAN_H
4152         char            *addr;
4153         int             e;
4154         pathname_t      f;
4155         int             fd;
4156         size_t          len;
4157         int64_t         lr;
4158         off64_t         off;
4159         int             flags;
4160         struct stat64   stb;
4161         int             v;
4162         char            st[1024];
4163         sigjmp_buf      sigbus_jmpbuf;
4164
4165         init_pathname(&f);
4166         if (!get_fname(FT_REGFILE, r, &f, NULL, NULL, &v)) {
4167                 if (v)
4168                         printf("%d/%lld: do_mmap - no filename\n", procid, opno);
4169                 free_pathname(&f);
4170                 return;
4171         }
4172         fd = open_path(&f, O_RDWR);
4173         e = fd < 0 ? errno : 0;
4174         check_cwd();
4175         if (fd < 0) {
4176                 if (v)
4177                         printf("%d/%lld: do_mmap - open %s failed %d\n",
4178                                procid, opno, f.path, e);
4179                 free_pathname(&f);
4180                 return;
4181         }
4182         if (fstat64(fd, &stb) < 0) {
4183                 if (v)
4184                         printf("%d/%lld: do_mmap - fstat64 %s failed %d\n",
4185                                procid, opno, f.path, errno);
4186                 free_pathname(&f);
4187                 close(fd);
4188                 return;
4189         }
4190         inode_info(st, sizeof(st), &stb, v);
4191         if (stb.st_size == 0) {
4192                 if (v)
4193                         printf("%d/%lld: do_mmap - %s%s zero size\n", procid, opno,
4194                                f.path, st);
4195                 free_pathname(&f);
4196                 close(fd);
4197                 return;
4198         }
4199
4200         lr = ((int64_t)random() << 32) + random();
4201         off = (off64_t)(lr % stb.st_size);
4202         off = rounddown_64(off, sysconf(_SC_PAGE_SIZE));
4203         len = (size_t)(random() % MIN(stb.st_size - off, FILELEN_MAX)) + 1;
4204
4205         flags = (random() % 2) ? MAP_SHARED : MAP_PRIVATE;
4206         addr = mmap(NULL, len, prot, flags, fd, off);
4207         e = (addr == MAP_FAILED) ? errno : 0;
4208         if (e) {
4209                 if (v)
4210                         printf("%d/%lld: do_mmap - mmap failed %s%s [%lld,%d,%s] %d\n",
4211                                procid, opno, f.path, st, (long long)off,
4212                                (int)len, translate_mmap_flags(flags), e);
4213                 free_pathname(&f);
4214                 close(fd);
4215                 return;
4216         }
4217
4218         if (prot & PROT_WRITE) {
4219                 if ((e = sigsetjmp(sigbus_jmpbuf, 1)) == 0) {
4220                         sigbus_jmp = &sigbus_jmpbuf;
4221                         memset(addr, nameseq & 0xff, len);
4222                 }
4223         } else {
4224                 char *buf;
4225                 if ((buf = malloc(len)) != NULL) {
4226                         memcpy(buf, addr, len);
4227                         free(buf);
4228                 }
4229         }
4230         munmap(addr, len);
4231         /* set NULL to stop other functions from doing siglongjmp */
4232         sigbus_jmp = NULL;
4233
4234         if (v)
4235                 printf("%d/%lld: %s %s%s [%lld,%d,%s] %s\n",
4236                        procid, opno, (prot & PROT_WRITE) ? "mwrite" : "mread",
4237                        f.path, st, (long long)off, (int)len,
4238                        translate_mmap_flags(flags),
4239                        (e == 0) ? "0" : "Bus error");
4240
4241         free_pathname(&f);
4242         close(fd);
4243 #endif
4244 }
4245
4246 void
4247 mread_f(opnum_t opno, long r)
4248 {
4249 #ifdef HAVE_SYS_MMAN_H
4250         do_mmap(opno, r, PROT_READ);
4251 #endif
4252 }
4253
4254 void
4255 mwrite_f(opnum_t opno, long r)
4256 {
4257 #ifdef HAVE_SYS_MMAN_H
4258         do_mmap(opno, r, PROT_WRITE);
4259 #endif
4260 }
4261
4262 void
4263 punch_f(opnum_t opno, long r)
4264 {
4265 #ifdef HAVE_LINUX_FALLOC_H
4266         do_fallocate(opno, r, FALLOC_FL_PUNCH_HOLE);
4267 #endif
4268 }
4269
4270 void
4271 zero_f(opnum_t opno, long r)
4272 {
4273 #ifdef HAVE_LINUX_FALLOC_H
4274         do_fallocate(opno, r, FALLOC_FL_ZERO_RANGE);
4275 #endif
4276 }
4277
4278 void
4279 collapse_f(opnum_t opno, long r)
4280 {
4281 #ifdef HAVE_LINUX_FALLOC_H
4282         do_fallocate(opno, r, FALLOC_FL_COLLAPSE_RANGE);
4283 #endif
4284 }
4285
4286 void
4287 insert_f(opnum_t opno, long r)
4288 {
4289 #ifdef HAVE_LINUX_FALLOC_H
4290         do_fallocate(opno, r, FALLOC_FL_INSERT_RANGE);
4291 #endif
4292 }
4293
4294 void
4295 read_f(opnum_t opno, long r)
4296 {
4297         char            *buf;
4298         int             e;
4299         pathname_t      f;
4300         int             fd;
4301         size_t          len;
4302         int64_t         lr;
4303         off64_t         off;
4304         struct stat64   stb;
4305         int             v;
4306         char            st[1024];
4307
4308         init_pathname(&f);
4309         if (!get_fname(FT_REGFILE, r, &f, NULL, NULL, &v)) {
4310                 if (v)
4311                         printf("%d/%lld: read - no filename\n", procid, opno);
4312                 free_pathname(&f);
4313                 return;
4314         }
4315         fd = open_path(&f, O_RDONLY);
4316         e = fd < 0 ? errno : 0;
4317         check_cwd();
4318         if (fd < 0) {
4319                 if (v)
4320                         printf("%d/%lld: read - open %s failed %d\n",
4321                                 procid, opno, f.path, e);
4322                 free_pathname(&f);
4323                 return;
4324         }
4325         if (fstat64(fd, &stb) < 0) {
4326                 if (v)
4327                         printf("%d/%lld: read - fstat64 %s failed %d\n",
4328                                 procid, opno, f.path, errno);
4329                 free_pathname(&f);
4330                 close(fd);
4331                 return;
4332         }
4333         inode_info(st, sizeof(st), &stb, v);
4334         if (stb.st_size == 0) {
4335                 if (v)
4336                         printf("%d/%lld: read - %s%s zero size\n", procid, opno,
4337                                f.path, st);
4338                 free_pathname(&f);
4339                 close(fd);
4340                 return;
4341         }
4342         lr = ((int64_t)random() << 32) + random();
4343         off = (off64_t)(lr % stb.st_size);
4344         lseek64(fd, off, SEEK_SET);
4345         len = (random() % FILELEN_MAX) + 1;
4346         buf = malloc(len);
4347         e = read(fd, buf, len) < 0 ? errno : 0;
4348         free(buf);
4349         if (v)
4350                 printf("%d/%lld: read %s%s [%lld,%d] %d\n",
4351                        procid, opno, f.path, st, (long long)off, (int)len, e);
4352         free_pathname(&f);
4353         close(fd);
4354 }
4355
4356 void
4357 readlink_f(opnum_t opno, long r)
4358 {
4359         char            buf[PATH_MAX];
4360         int             e;
4361         pathname_t      f;
4362         int             v;
4363
4364         init_pathname(&f);
4365         if (!get_fname(FT_SYMm, r, &f, NULL, NULL, &v)) {
4366                 if (v)
4367                         printf("%d/%lld: readlink - no filename\n", procid, opno);
4368                 free_pathname(&f);
4369                 return;
4370         }
4371         e = readlink_path(&f, buf, PATH_MAX) < 0 ? errno : 0;
4372         check_cwd();
4373         if (v)
4374                 printf("%d/%lld: readlink %s %d\n", procid, opno, f.path, e);
4375         free_pathname(&f);
4376 }
4377
4378 void
4379 readv_f(opnum_t opno, long r)
4380 {
4381         char            *buf;
4382         int             e;
4383         pathname_t      f;
4384         int             fd;
4385         size_t          len;
4386         int64_t         lr;
4387         off64_t         off;
4388         struct stat64   stb;
4389         int             v;
4390         char            st[1024];
4391         struct iovec    *iov = NULL;
4392         int             iovcnt;
4393         size_t          iovb;
4394         size_t          iovl;
4395         int             i;
4396
4397         init_pathname(&f);
4398         if (!get_fname(FT_REGFILE, r, &f, NULL, NULL, &v)) {
4399                 if (v)
4400                         printf("%d/%lld: readv - no filename\n", procid, opno);
4401                 free_pathname(&f);
4402                 return;
4403         }
4404         fd = open_path(&f, O_RDONLY);
4405         e = fd < 0 ? errno : 0;
4406         check_cwd();
4407         if (fd < 0) {
4408                 if (v)
4409                         printf("%d/%lld: readv - open %s failed %d\n",
4410                                 procid, opno, f.path, e);
4411                 free_pathname(&f);
4412                 return;
4413         }
4414         if (fstat64(fd, &stb) < 0) {
4415                 if (v)
4416                         printf("%d/%lld: readv - fstat64 %s failed %d\n",
4417                                 procid, opno, f.path, errno);
4418                 free_pathname(&f);
4419                 close(fd);
4420                 return;
4421         }
4422         inode_info(st, sizeof(st), &stb, v);
4423         if (stb.st_size == 0) {
4424                 if (v)
4425                         printf("%d/%lld: readv - %s%s zero size\n", procid, opno,
4426                                f.path, st);
4427                 free_pathname(&f);
4428                 close(fd);
4429                 return;
4430         }
4431         lr = ((int64_t)random() << 32) + random();
4432         off = (off64_t)(lr % stb.st_size);
4433         lseek64(fd, off, SEEK_SET);
4434         len = (random() % FILELEN_MAX) + 1;
4435         buf = malloc(len);
4436
4437         iovcnt = (random() % MIN(len, IOV_MAX)) + 1;
4438         iov = calloc(iovcnt, sizeof(struct iovec));
4439         iovl = len / iovcnt;
4440         iovb = 0;
4441         for (i=0; i<iovcnt; i++) {
4442                 (iov + i)->iov_base = (buf + iovb);
4443                 (iov + i)->iov_len  = iovl;
4444                 iovb += iovl;
4445         }
4446
4447         e = readv(fd, iov, iovcnt) < 0 ? errno : 0;
4448         free(buf);
4449         if (v)
4450                 printf("%d/%lld: readv %s%s [%lld,%d,%d] %d\n",
4451                        procid, opno, f.path, st, (long long)off, (int)iovl,
4452                        iovcnt, e);
4453         free_pathname(&f);
4454         close(fd);
4455 }
4456
4457 void
4458 removefattr_f(opnum_t opno, long r)
4459 {
4460         fent_t          *fep;
4461         int             e;
4462         pathname_t      f;
4463         int             v;
4464         char            name[XATTR_NAME_BUF_SIZE];
4465         int             xattr_num;
4466
4467         init_pathname(&f);
4468         if (!get_fname(FT_REGFILE | FT_ANYDIR, r, &f, NULL, &fep, &v)) {
4469                 if (v)
4470                         printf("%d/%lld: removefattr - no filename\n", procid, opno);
4471                 goto out;
4472         }
4473         check_cwd();
4474
4475         /*
4476          * If the file/dir has xattrs, pick one randomly, otherwise attempt to
4477          * remove a xattr that doesn't exist (fremovexattr should fail with
4478          * errno set to ENOATTR (61) in this case).
4479          */
4480         if (fep->xattr_counter > 0)
4481                 xattr_num = (random() % fep->xattr_counter) + 1;
4482         else
4483                 xattr_num = 0;
4484
4485         e = generate_xattr_name(xattr_num, name, sizeof(name));
4486         if (e < 0) {
4487                 printf("%d/%lld: removefattr - file %s failed to generate xattr name: %d\n",
4488                        procid, opno, f.path, e);
4489                 goto out;
4490         }
4491
4492         e = removexattr(f.path, name) < 0 ? errno : 0;
4493         if (v)
4494                 printf("%d/%lld: removefattr file %s name %s %d\n",
4495                        procid, opno, f.path, name, e);
4496 out:
4497         free_pathname(&f);
4498 }
4499
4500 struct print_flags renameat2_flags [] = {
4501         { RENAME_NOREPLACE, "NOREPLACE"},
4502         { RENAME_EXCHANGE, "EXCHANGE"},
4503         { RENAME_WHITEOUT, "WHITEOUT"},
4504         { -1, NULL}
4505 };
4506
4507 #define translate_renameat2_flags(mode)        \
4508         ({translate_flags(mode, "|", renameat2_flags);})
4509
4510 void
4511 do_renameat2(opnum_t opno, long r, int mode)
4512 {
4513         fent_t          *dfep;
4514         int             e;
4515         pathname_t      f;
4516         fent_t          *fep;
4517         flist_t         *flp;
4518         int             id;
4519         pathname_t      newf;
4520         int             oldid = 0;
4521         int             parid;
4522         int             oldparid = 0;
4523         int             which;
4524         int             v;
4525         int             v1;
4526
4527         /* get an existing path for the source of the rename */
4528         init_pathname(&f);
4529         which = (mode == RENAME_WHITEOUT) ? FT_DEVm : FT_ANYm;
4530         if (!get_fname(which, r, &f, &flp, &fep, &v1)) {
4531                 if (v1)
4532                         printf("%d/%lld: rename - no source filename\n",
4533                                 procid, opno);
4534                 free_pathname(&f);
4535                 return;
4536         }
4537
4538         /*
4539          * Both pathnames must exist for the RENAME_EXCHANGE, and in
4540          * order to maintain filelist/filename integrity, we should
4541          * restrict exchange operation to files of the same type.
4542          */
4543         if (mode == RENAME_EXCHANGE) {
4544                 which = 1 << (flp - flist);
4545                 init_pathname(&newf);
4546                 if (!get_fname(which, random(), &newf, NULL, &dfep, &v)) {
4547                         if (v)
4548                                 printf("%d/%lld: rename - no target filename\n",
4549                                         procid, opno);
4550                         free_pathname(&newf);
4551                         free_pathname(&f);
4552                         return;
4553                 }
4554                 if (which == FT_DIRm && (fents_ancestor_check(fep, dfep) ||
4555                     fents_ancestor_check(dfep, fep))) {
4556                         if (v)
4557                                 printf("%d/%lld: rename(REXCHANGE) %s and %s "
4558                                         "have ancestor-descendant relationship\n",
4559                                         procid, opno, f.path, newf.path);
4560                         free_pathname(&newf);
4561                         free_pathname(&f);
4562                         return;
4563                 }
4564                 v |= v1;
4565                 id = dfep->id;
4566                 parid = dfep->parent;
4567         } else {
4568                 /*
4569                  * Get an existing directory for the destination parent
4570                  * directory name.
4571                  */
4572                 if (!get_fname(FT_DIRm, random(), NULL, NULL, &dfep, &v))
4573                         parid = -1;
4574                 else
4575                         parid = dfep->id;
4576                 v |= v1;
4577
4578                 /*
4579                  * Generate a new path using an existing parent directory
4580                  * in name.
4581                  */
4582                 init_pathname(&newf);
4583                 e = generate_fname(dfep, flp - flist, &newf, &id, &v1);
4584                 v |= v1;
4585                 if (!e) {
4586                         if (v) {
4587                                 (void)fent_to_name(&f, dfep);
4588                                 printf("%d/%lld: rename - no filename from %s\n",
4589                                         procid, opno, f.path);
4590                         }
4591                         free_pathname(&newf);
4592                         free_pathname(&f);
4593                         return;
4594                 }
4595         }
4596         e = rename_path(&f, &newf, mode) < 0 ? errno : 0;
4597         check_cwd();
4598         if (e == 0) {
4599                 int xattr_counter = fep->xattr_counter;
4600                 bool swap = (mode == RENAME_EXCHANGE) ? true : false;
4601                 int ft = flp - flist;
4602
4603                 oldid = fep->id;
4604                 oldparid = fep->parent;
4605
4606                 /*
4607                  * Swap the parent ids for RENAME_EXCHANGE, and replace the
4608                  * old parent id for the others.
4609                  */
4610                 if (ft == FT_DIR || ft == FT_SUBVOL)
4611                         fix_parent(oldid, id, swap);
4612
4613                 if (mode == RENAME_WHITEOUT) {
4614                         fep->xattr_counter = 0;
4615                         add_to_flist(flp - flist, id, parid, xattr_counter);
4616                 } else if (mode == RENAME_EXCHANGE) {
4617                         fep->xattr_counter = dfep->xattr_counter;
4618                         dfep->xattr_counter = xattr_counter;
4619                 } else {
4620                         del_from_flist(flp - flist, fep - flp->fents);
4621                         add_to_flist(flp - flist, id, parid, xattr_counter);
4622                 }
4623         }
4624         if (v) {
4625                 printf("%d/%lld: rename(%s) %s to %s %d\n", procid,
4626                         opno, translate_renameat2_flags(mode), f.path,
4627                         newf.path, e);
4628                 if (e == 0) {
4629                         printf("%d/%lld: rename source entry: id=%d,parent=%d\n",
4630                                 procid, opno, oldid, oldparid);
4631                         printf("%d/%lld: rename target entry: id=%d,parent=%d\n",
4632                                 procid, opno, id, parid);
4633                 }
4634         }
4635         free_pathname(&newf);
4636         free_pathname(&f);
4637 }
4638
4639 void
4640 rename_f(opnum_t opno, long r)
4641 {
4642         do_renameat2(opno, r, 0);
4643 }
4644
4645 void
4646 rnoreplace_f(opnum_t opno, long r)
4647 {
4648         do_renameat2(opno, r, RENAME_NOREPLACE);
4649 }
4650
4651 void
4652 rexchange_f(opnum_t opno, long r)
4653 {
4654         do_renameat2(opno, r, RENAME_EXCHANGE);
4655 }
4656
4657 void
4658 rwhiteout_f(opnum_t opno, long r)
4659 {
4660         do_renameat2(opno, r, RENAME_WHITEOUT);
4661 }
4662
4663 void
4664 resvsp_f(opnum_t opno, long r)
4665 {
4666         int             e;
4667         pathname_t      f;
4668         int             fd;
4669         struct xfs_flock64      fl;
4670         int64_t         lr;
4671         off64_t         off;
4672         struct stat64   stb;
4673         int             v;
4674         char            st[1024];
4675
4676         init_pathname(&f);
4677         if (!get_fname(FT_REGFILE, r, &f, NULL, NULL, &v)) {
4678                 if (v)
4679                         printf("%d/%lld: resvsp - no filename\n", procid, opno);
4680                 free_pathname(&f);
4681                 return;
4682         }
4683         fd = open_path(&f, O_RDWR);
4684         e = fd < 0 ? errno : 0;
4685         check_cwd();
4686         if (fd < 0) {
4687                 if (v)
4688                         printf("%d/%lld: resvsp - open %s failed %d\n",
4689                                 procid, opno, f.path, e);
4690                 free_pathname(&f);
4691                 return;
4692         }
4693         if (fstat64(fd, &stb) < 0) {
4694                 if (v)
4695                         printf("%d/%lld: resvsp - fstat64 %s failed %d\n",
4696                                 procid, opno, f.path, errno);
4697                 free_pathname(&f);
4698                 close(fd);
4699                 return;
4700         }
4701         inode_info(st, sizeof(st), &stb, v);
4702         lr = ((int64_t)random() << 32) + random();
4703         off = (off64_t)(lr % MIN(stb.st_size + (1024 * 1024), MAXFSIZE));
4704         off %= maxfsize;
4705         fl.l_whence = SEEK_SET;
4706         fl.l_start = off;
4707         fl.l_len = (off64_t)(random() % (1024 * 1024));
4708         e = xfsctl(f.path, fd, XFS_IOC_RESVSP64, &fl) < 0 ? errno : 0;
4709         if (v)
4710                 printf("%d/%lld: xfsctl(XFS_IOC_RESVSP64) %s%s %lld %lld %d\n",
4711                        procid, opno, f.path, st,
4712                         (long long)off, (long long)fl.l_len, e);
4713         free_pathname(&f);
4714         close(fd);
4715 }
4716
4717 void
4718 rmdir_f(opnum_t opno, long r)
4719 {
4720         int             e;
4721         pathname_t      f;
4722         fent_t          *fep;
4723         int             oldid;
4724         int             oldparid;
4725         int             v;
4726
4727         init_pathname(&f);
4728         if (!get_fname(FT_DIRm, r, &f, NULL, &fep, &v)) {
4729                 if (v)
4730                         printf("%d/%lld: rmdir - no directory\n", procid, opno);
4731                 free_pathname(&f);
4732                 return;
4733         }
4734         e = rmdir_path(&f) < 0 ? errno : 0;
4735         check_cwd();
4736         if (e == 0) {
4737                 oldid = fep->id;
4738                 oldparid = fep->parent;
4739                 del_from_flist(FT_DIR, fep - flist[FT_DIR].fents);
4740         }
4741         if (v) {
4742                 printf("%d/%lld: rmdir %s %d\n", procid, opno, f.path, e);
4743                 if (e == 0)
4744                         printf("%d/%lld: rmdir del entry: id=%d,parent=%d\n",
4745                                 procid, opno, oldid, oldparid);
4746         }
4747         free_pathname(&f);
4748 }
4749
4750 void
4751 setattr_f(opnum_t opno, long r)
4752 {
4753         int             fd;
4754         int             e;
4755         pathname_t      f;
4756         uint            fl;
4757         int             v;
4758
4759         init_pathname(&f);
4760         if (!get_fname(FT_ANYm, r, &f, NULL, NULL, &v))
4761                 append_pathname(&f, ".");
4762         fd = open_path(&f, O_RDWR);
4763         e = fd < 0 ? errno : 0;
4764         check_cwd();
4765
4766         fl = attr_mask & (uint)random();
4767         e = ioctl(fd, FS_IOC_SETFLAGS, &fl);
4768         if (v)
4769                 printf("%d/%lld: setattr %s %x %d\n", procid, opno, f.path, fl, e);
4770         free_pathname(&f);
4771         close(fd);
4772 }
4773
4774 void
4775 setfattr_f(opnum_t opno, long r)
4776 {
4777         int             e;
4778         pathname_t      f;
4779         fent_t          *fep;
4780         int             v;
4781         int             value_len;
4782         char            name[XATTR_NAME_BUF_SIZE];
4783         char            *value = NULL;
4784         int             flag = 0;
4785         int             xattr_num;
4786
4787         init_pathname(&f);
4788         if (!get_fname(FT_REGFILE | FT_ANYDIR, r, &f, NULL, &fep, &v)) {
4789                 if (v)
4790                         printf("%d/%lld: setfattr - no filename\n", procid, opno);
4791                 goto out;
4792         }
4793         check_cwd();
4794
4795         if ((fep->xattr_counter > 0) && (random() % 2)) {
4796                 /*
4797                  * Use an existing xattr name for replacing its value or
4798                  * create again a xattr that was previously deleted.
4799                  */
4800                 xattr_num = (random() % fep->xattr_counter) + 1;
4801                 if (random() % 2)
4802                         flag = XATTR_REPLACE;
4803         } else {
4804                 /* Use a new xattr name. */
4805                 xattr_num = fep->xattr_counter + 1;
4806                 /*
4807                  * Don't always use the create flag because even if our xattr
4808                  * counter is 0, we may still have xattrs associated to this
4809                  * file (this happens when xattrs are added to a file through
4810                  * one of its other hard links), so we can end up updating an
4811                  * existing xattr too.
4812                  */
4813                 if (random() % 2)
4814                         flag = XATTR_CREATE;
4815         }
4816
4817         /*
4818          * The maximum supported value size depends on the filesystem
4819          * implementation, but 100 bytes is a safe value for most filesystems
4820          * at least.
4821          */
4822         value_len = random() % 101;
4823         value = gen_random_string(value_len);
4824         if (!value && value_len > 0) {
4825                 if (v)
4826                         printf("%d/%lld: setfattr - file %s failed to allocate value with %d bytes\n",
4827                                procid, opno, f.path, value_len);
4828                 goto out;
4829         }
4830         e = generate_xattr_name(xattr_num, name, sizeof(name));
4831         if (e < 0) {
4832                 printf("%d/%lld: setfattr - file %s failed to generate xattr name: %d\n",
4833                        procid, opno, f.path, e);
4834                 goto out;
4835         }
4836
4837         e = setxattr(f.path, name, value, value_len, flag) < 0 ? errno : 0;
4838         if (e == 0)
4839                 fep->xattr_counter++;
4840         if (v)
4841                 printf("%d/%lld: setfattr file %s name %s flag %s value length %d: %d\n",
4842                        procid, opno, f.path, name, xattr_flag_to_string(flag),
4843                        value_len, e);
4844 out:
4845         free(value);
4846         free_pathname(&f);
4847 }
4848
4849 void
4850 snapshot_f(opnum_t opno, long r)
4851 {
4852 #ifdef HAVE_BTRFSUTIL_H
4853         enum btrfs_util_error   e;
4854         pathname_t              f;
4855         pathname_t              newf;
4856         fent_t                  *fep;
4857         int                     id;
4858         int                     parid;
4859         int                     v;
4860         int                     v1;
4861         int                     err;
4862
4863         init_pathname(&f);
4864         if (!get_fname(FT_SUBVOLm, r, &f, NULL, &fep, &v)) {
4865                 if (v)
4866                         printf("%d/%lld: snapshot - no subvolume\n", procid,
4867                                opno);
4868                 free_pathname(&f);
4869                 return;
4870         }
4871         init_pathname(&newf);
4872         parid = fep->id;
4873         err = generate_fname(fep, FT_SUBVOL, &newf, &id, &v1);
4874         v |= v1;
4875         if (!err) {
4876                 if (v) {
4877                         (void)fent_to_name(&f, fep);
4878                         printf("%d/%lld: snapshot - no filename from %s\n",
4879                                procid, opno, f.path);
4880                 }
4881                 free_pathname(&f);
4882                 return;
4883         }
4884         e = btrfs_util_create_snapshot(f.path, newf.path, 0, NULL, NULL);
4885         if (e == BTRFS_UTIL_OK)
4886                 add_to_flist(FT_SUBVOL, id, parid, 0);
4887         if (v) {
4888                 printf("%d/%lld: snapshot %s->%s %d(%s)\n", procid, opno,
4889                        f.path, newf.path, e, btrfs_util_strerror(e));
4890                 printf("%d/%lld: snapshot add id=%d,parent=%d\n", procid, opno,
4891                        id, parid);
4892         }
4893         free_pathname(&newf);
4894         free_pathname(&f);
4895 #endif
4896 }
4897
4898 void
4899 stat_f(opnum_t opno, long r)
4900 {
4901         int             e;
4902         pathname_t      f;
4903         struct stat64   stb;
4904         int             v;
4905
4906         init_pathname(&f);
4907         if (!get_fname(FT_ANYm, r, &f, NULL, NULL, &v)) {
4908                 if (v)
4909                         printf("%d/%lld: stat - no entries\n", procid, opno);
4910                 free_pathname(&f);
4911                 return;
4912         }
4913         e = lstat64_path(&f, &stb) < 0 ? errno : 0;
4914         check_cwd();
4915         if (v)
4916                 printf("%d/%lld: stat %s %d\n", procid, opno, f.path, e);
4917         free_pathname(&f);
4918 }
4919
4920 void
4921 subvol_create_f(opnum_t opno, long r)
4922 {
4923 #ifdef HAVE_BTRFSUTIL_H
4924         enum btrfs_util_error   e;
4925         pathname_t              f;
4926         fent_t                  *fep;
4927         int                     id;
4928         int                     parid;
4929         int                     v;
4930         int                     v1;
4931         int                     err;
4932
4933         init_pathname(&f);
4934         if (!get_fname(FT_ANYDIR, r, NULL, NULL, &fep, &v))
4935                 parid = -1;
4936         else
4937                 parid = fep->id;
4938         err = generate_fname(fep, FT_SUBVOL, &f, &id, &v1);
4939         v |= v1;
4940         if (!err) {
4941                 if (v) {
4942                         (void)fent_to_name(&f, fep);
4943                         printf("%d/%lld: subvol_create - no filename from %s\n",
4944                                procid, opno, f.path);
4945                 }
4946                 free_pathname(&f);
4947                 return;
4948         }
4949         e = btrfs_util_create_subvolume(f.path, 0, NULL, NULL);
4950         if (e == BTRFS_UTIL_OK)
4951                 add_to_flist(FT_SUBVOL, id, parid, 0);
4952         if (v) {
4953                 printf("%d/%lld: subvol_create %s %d(%s)\n", procid, opno,
4954                        f.path, e, btrfs_util_strerror(e));
4955                 printf("%d/%lld: subvol_create add id=%d,parent=%d\n", procid,
4956                        opno, id, parid);
4957         }
4958         free_pathname(&f);
4959 #endif
4960 }
4961
4962 void
4963 subvol_delete_f(opnum_t opno, long r)
4964 {
4965 #ifdef HAVE_BTRFSUTIL_H
4966         enum btrfs_util_error   e;
4967         pathname_t              f;
4968         fent_t                  *fep;
4969         int                     v;
4970         int                     oldid;
4971         int                     oldparid;
4972
4973         init_pathname(&f);
4974         if (!get_fname(FT_SUBVOLm, r, &f, NULL, &fep, &v)) {
4975                 if (v)
4976                         printf("%d:%lld: subvol_delete - no subvolume\n", procid,
4977                                opno);
4978                 free_pathname(&f);
4979                 return;
4980         }
4981         e = btrfs_util_delete_subvolume(f.path, 0);
4982         check_cwd();
4983         if (e == BTRFS_UTIL_OK) {
4984                 oldid = fep->id;
4985                 oldparid = fep->parent;
4986                 delete_subvol_children(oldid);
4987                 del_from_flist(FT_SUBVOL, fep - flist[FT_SUBVOL].fents);
4988         }
4989         if (v) {
4990                 printf("%d/%lld: subvol_delete %s %d(%s)\n", procid, opno, f.path,
4991                        e, btrfs_util_strerror(e));
4992                 if (e == BTRFS_UTIL_OK)
4993                         printf("%d/%lld: subvol_delete del entry: id=%d,parent=%d\n",
4994                                procid, opno, oldid, oldparid);
4995         }
4996         free_pathname(&f);
4997 #endif
4998 }
4999
5000 void
5001 symlink_f(opnum_t opno, long r)
5002 {
5003         int             e;
5004         pathname_t      f;
5005         fent_t          *fep;
5006         int             i;
5007         int             id;
5008         int             len;
5009         int             parid;
5010         int             v;
5011         int             v1;
5012         char            *val;
5013
5014         if (!get_fname(FT_ANYDIR, r, NULL, NULL, &fep, &v))
5015                 parid = -1;
5016         else
5017                 parid = fep->id;
5018         init_pathname(&f);
5019         e = generate_fname(fep, FT_SYM, &f, &id, &v1);
5020         v |= v1;
5021         if (!e) {
5022                 if (v) {
5023                         (void)fent_to_name(&f, fep);
5024                         printf("%d/%lld: symlink - no filename from %s\n",
5025                                 procid, opno, f.path);
5026                 }
5027                 free_pathname(&f);
5028                 return;
5029         }
5030         len = (int)(random() % PATH_MAX);
5031         val = malloc(len + 1);
5032         if (len)
5033                 memset(val, 'x', len);
5034         val[len] = '\0';
5035         for (i = 10; i < len - 1; i += 10)
5036                 val[i] = '/';
5037         e = symlink_path(val, &f) < 0 ? errno : 0;
5038         check_cwd();
5039         if (e == 0)
5040                 add_to_flist(FT_SYM, id, parid, 0);
5041         free(val);
5042         if (v) {
5043                 printf("%d/%lld: symlink %s %d\n", procid, opno, f.path, e);
5044                 printf("%d/%lld: symlink add id=%d,parent=%d\n", procid, opno, id, parid);
5045         }
5046         free_pathname(&f);
5047 }
5048
5049 /* ARGSUSED */
5050 void
5051 sync_f(opnum_t opno, long r)
5052 {
5053         sync();
5054         if (verbose)
5055                 printf("%d/%lld: sync\n", procid, opno);
5056 }
5057
5058 void
5059 truncate_f(opnum_t opno, long r)
5060 {
5061         int             e;
5062         pathname_t      f;
5063         int64_t         lr;
5064         off64_t         off;
5065         struct stat64   stb;
5066         int             v;
5067         char            st[1024];
5068
5069         init_pathname(&f);
5070         if (!get_fname(FT_REGFILE, r, &f, NULL, NULL, &v)) {
5071                 if (v)
5072                         printf("%d/%lld: truncate - no filename\n", procid, opno);
5073                 free_pathname(&f);
5074                 return;
5075         }
5076         e = stat64_path(&f, &stb) < 0 ? errno : 0;
5077         check_cwd();
5078         if (e > 0) {
5079                 if (v)
5080                         printf("%d/%lld: truncate - stat64 %s failed %d\n",
5081                                 procid, opno, f.path, e);
5082                 free_pathname(&f);
5083                 return;
5084         }
5085         inode_info(st, sizeof(st), &stb, v);
5086         lr = ((int64_t)random() << 32) + random();
5087         off = (off64_t)(lr % MIN(stb.st_size + (1024 * 1024), MAXFSIZE));
5088         off %= maxfsize;
5089         e = truncate64_path(&f, off) < 0 ? errno : 0;
5090         check_cwd();
5091         if (v)
5092                 printf("%d/%lld: truncate %s%s %lld %d\n", procid, opno, f.path,
5093                        st, (long long)off, e);
5094         free_pathname(&f);
5095 }
5096
5097 void
5098 unlink_f(opnum_t opno, long r)
5099 {
5100         int             e;
5101         pathname_t      f;
5102         fent_t          *fep;
5103         flist_t         *flp;
5104         int             oldid;
5105         int             oldparid;
5106         int             v;
5107
5108         init_pathname(&f);
5109         if (!get_fname(FT_NOTDIR, r, &f, &flp, &fep, &v)) {
5110                 if (v)
5111                         printf("%d/%lld: unlink - no file\n", procid, opno);
5112                 free_pathname(&f);
5113                 return;
5114         }
5115         e = unlink_path(&f) < 0 ? errno : 0;
5116         check_cwd();
5117         if (e == 0) {
5118                 oldid = fep->id;
5119                 oldparid = fep->parent;
5120                 del_from_flist(flp - flist, fep - flp->fents);
5121         }
5122         if (v) {
5123                 printf("%d/%lld: unlink %s %d\n", procid, opno, f.path, e);
5124                 if (e == 0)
5125                         printf("%d/%lld: unlink del entry: id=%d,parent=%d\n",
5126                                 procid, opno, oldid, oldparid);
5127         }
5128         free_pathname(&f);
5129 }
5130
5131 void
5132 unresvsp_f(opnum_t opno, long r)
5133 {
5134         int             e;
5135         pathname_t      f;
5136         int             fd;
5137         struct xfs_flock64      fl;
5138         int64_t         lr;
5139         off64_t         off;
5140         struct stat64   stb;
5141         int             v;
5142         char            st[1024];
5143
5144         init_pathname(&f);
5145         if (!get_fname(FT_REGFILE, r, &f, NULL, NULL, &v)) {
5146                 if (v)
5147                         printf("%d/%lld: unresvsp - no filename\n", procid, opno);
5148                 free_pathname(&f);
5149                 return;
5150         }
5151         fd = open_path(&f, O_RDWR);
5152         e = fd < 0 ? errno : 0;
5153         check_cwd();
5154         if (fd < 0) {
5155                 if (v)
5156                         printf("%d/%lld: unresvsp - open %s failed %d\n",
5157                                 procid, opno, f.path, e);
5158                 free_pathname(&f);
5159                 return;
5160         }
5161         if (fstat64(fd, &stb) < 0) {
5162                 if (v)
5163                         printf("%d/%lld: unresvsp - fstat64 %s failed %d\n",
5164                                 procid, opno, f.path, errno);
5165                 free_pathname(&f);
5166                 close(fd);
5167                 return;
5168         }
5169         inode_info(st, sizeof(st), &stb, v);
5170         lr = ((int64_t)random() << 32) + random();
5171         off = (off64_t)(lr % MIN(stb.st_size + (1024 * 1024), MAXFSIZE));
5172         off %= maxfsize;
5173         fl.l_whence = SEEK_SET;
5174         fl.l_start = off;
5175         fl.l_len = (off64_t)(random() % (1 << 20));
5176         e = xfsctl(f.path, fd, XFS_IOC_UNRESVSP64, &fl) < 0 ? errno : 0;
5177         if (v)
5178                 printf("%d/%lld: xfsctl(XFS_IOC_UNRESVSP64) %s%s %lld %lld %d\n",
5179                        procid, opno, f.path, st,
5180                         (long long)off, (long long)fl.l_len, e);
5181         free_pathname(&f);
5182         close(fd);
5183 }
5184
5185 void
5186 uring_read_f(opnum_t opno, long r)
5187 {
5188 #ifdef URING
5189         do_uring_rw(opno, r, O_RDONLY);
5190 #endif
5191 }
5192
5193 void
5194 uring_write_f(opnum_t opno, long r)
5195 {
5196 #ifdef URING
5197         do_uring_rw(opno, r, O_WRONLY);
5198 #endif
5199 }
5200
5201 void
5202 write_f(opnum_t opno, long r)
5203 {
5204         char            *buf;
5205         int             e;
5206         pathname_t      f;
5207         int             fd;
5208         size_t          len;
5209         int64_t         lr;
5210         off64_t         off;
5211         struct stat64   stb;
5212         int             v;
5213         char            st[1024];
5214
5215         init_pathname(&f);
5216         if (!get_fname(FT_REGm, r, &f, NULL, NULL, &v)) {
5217                 if (v)
5218                         printf("%d/%lld: write - no filename\n", procid, opno);
5219                 free_pathname(&f);
5220                 return;
5221         }
5222         fd = open_path(&f, O_WRONLY);
5223         e = fd < 0 ? errno : 0;
5224         check_cwd();
5225         if (fd < 0) {
5226                 if (v)
5227                         printf("%d/%lld: write - open %s failed %d\n",
5228                                 procid, opno, f.path, e);
5229                 free_pathname(&f);
5230                 return;
5231         }
5232         if (fstat64(fd, &stb) < 0) {
5233                 if (v)
5234                         printf("%d/%lld: write - fstat64 %s failed %d\n",
5235                                 procid, opno, f.path, errno);
5236                 free_pathname(&f);
5237                 close(fd);
5238                 return;
5239         }
5240         inode_info(st, sizeof(st), &stb, v);
5241         lr = ((int64_t)random() << 32) + random();
5242         off = (off64_t)(lr % MIN(stb.st_size + (1024 * 1024), MAXFSIZE));
5243         off %= maxfsize;
5244         lseek64(fd, off, SEEK_SET);
5245         len = (random() % FILELEN_MAX) + 1;
5246         buf = malloc(len);
5247         memset(buf, nameseq & 0xff, len);
5248         e = write(fd, buf, len) < 0 ? errno : 0;
5249         free(buf);
5250         if (v)
5251                 printf("%d/%lld: write %s%s [%lld,%d] %d\n",
5252                        procid, opno, f.path, st, (long long)off, (int)len, e);
5253         free_pathname(&f);
5254         close(fd);
5255 }
5256
5257 void
5258 writev_f(opnum_t opno, long r)
5259 {
5260         char            *buf;
5261         int             e;
5262         pathname_t      f;
5263         int             fd;
5264         size_t          len;
5265         int64_t         lr;
5266         off64_t         off;
5267         struct stat64   stb;
5268         int             v;
5269         char            st[1024];
5270         struct iovec    *iov = NULL;
5271         int             iovcnt;
5272         size_t          iovb;
5273         size_t          iovl;
5274         int             i;
5275
5276         init_pathname(&f);
5277         if (!get_fname(FT_REGm, r, &f, NULL, NULL, &v)) {
5278                 if (v)
5279                         printf("%d/%lld: writev - no filename\n", procid, opno);
5280                 free_pathname(&f);
5281                 return;
5282         }
5283         fd = open_path(&f, O_WRONLY);
5284         e = fd < 0 ? errno : 0;
5285         check_cwd();
5286         if (fd < 0) {
5287                 if (v)
5288                         printf("%d/%lld: writev - open %s failed %d\n",
5289                                 procid, opno, f.path, e);
5290                 free_pathname(&f);
5291                 return;
5292         }
5293         if (fstat64(fd, &stb) < 0) {
5294                 if (v)
5295                         printf("%d/%lld: writev - fstat64 %s failed %d\n",
5296                                 procid, opno, f.path, errno);
5297                 free_pathname(&f);
5298                 close(fd);
5299                 return;
5300         }
5301         inode_info(st, sizeof(st), &stb, v);
5302         lr = ((int64_t)random() << 32) + random();
5303         off = (off64_t)(lr % MIN(stb.st_size + (1024 * 1024), MAXFSIZE));
5304         off %= maxfsize;
5305         lseek64(fd, off, SEEK_SET);
5306         len = (random() % FILELEN_MAX) + 1;
5307         buf = malloc(len);
5308         memset(buf, nameseq & 0xff, len);
5309
5310         iovcnt = (random() % MIN(len, IOV_MAX)) + 1;
5311         iov = calloc(iovcnt, sizeof(struct iovec));
5312         iovl = len / iovcnt;
5313         iovb = 0;
5314         for (i=0; i<iovcnt; i++) {
5315                 (iov + i)->iov_base = (buf + iovb);
5316                 (iov + i)->iov_len  = iovl;
5317                 iovb += iovl;
5318         }
5319
5320         e = writev(fd, iov, iovcnt) < 0 ? errno : 0;
5321         free(buf);
5322         free(iov);
5323         if (v)
5324                 printf("%d/%lld: writev %s%s [%lld,%d,%d] %d\n",
5325                        procid, opno, f.path, st, (long long)off, (int)iovl,
5326                        iovcnt, e);
5327         free_pathname(&f);
5328         close(fd);
5329 }
5330
5331 char *
5332 xattr_flag_to_string(int flag)
5333 {
5334         if (flag == XATTR_CREATE)
5335                 return "create";
5336         if (flag == XATTR_REPLACE)
5337                 return "replace";
5338         return "none";
5339 }