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