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