1 /*
   2  * CDDL HEADER START
   3  *
   4  * The contents of this file are subject to the terms of the
   5  * Common Development and Distribution License (the "License").
   6  * You may not use this file except in compliance with the License.
   7  *
   8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
   9  * or http://www.opensolaris.org/os/licensing.
  10  * See the License for the specific language governing permissions
  11  * and limitations under the License.
  12  *
  13  * When distributing Covered Code, include this CDDL HEADER in each
  14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
  15  * If applicable, add the following below this CDDL HEADER, with the
  16  * fields enclosed by brackets "[]" replaced with your own identifying
  17  * information: Portions Copyright [yyyy] [name of copyright owner]
  18  *
  19  * CDDL HEADER END
  20  */
  21 /*
  22  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
  23  * Copyright (c) 2011, 2016 by Delphix. All rights reserved.
  24  * Copyright 2011 Nexenta Systems, Inc.  All rights reserved.
  25  * Copyright (c) 2013 Steven Hartland. All rights reserved.
  26  * Copyright (c) 2014 Integros [integros.com]
  27  * Copyright 2017 Joyent, Inc.
  28  * Copyright 2017 RackTop Systems.
  29  */
  30 
  31 /*
  32  * The objective of this program is to provide a DMU/ZAP/SPA stress test
  33  * that runs entirely in userland, is easy to use, and easy to extend.
  34  *
  35  * The overall design of the ztest program is as follows:
  36  *
  37  * (1) For each major functional area (e.g. adding vdevs to a pool,
  38  *     creating and destroying datasets, reading and writing objects, etc)
  39  *     we have a simple routine to test that functionality.  These
  40  *     individual routines do not have to do anything "stressful".
  41  *
  42  * (2) We turn these simple functionality tests into a stress test by
  43  *     running them all in parallel, with as many threads as desired,
  44  *     and spread across as many datasets, objects, and vdevs as desired.
  45  *
  46  * (3) While all this is happening, we inject faults into the pool to
  47  *     verify that self-healing data really works.
  48  *
  49  * (4) Every time we open a dataset, we change its checksum and compression
  50  *     functions.  Thus even individual objects vary from block to block
  51  *     in which checksum they use and whether they're compressed.
  52  *
  53  * (5) To verify that we never lose on-disk consistency after a crash,
  54  *     we run the entire test in a child of the main process.
  55  *     At random times, the child self-immolates with a SIGKILL.
  56  *     This is the software equivalent of pulling the power cord.
  57  *     The parent then runs the test again, using the existing
  58  *     storage pool, as many times as desired. If backwards compatibility
  59  *     testing is enabled ztest will sometimes run the "older" version
  60  *     of ztest after a SIGKILL.
  61  *
  62  * (6) To verify that we don't have future leaks or temporal incursions,
  63  *     many of the functional tests record the transaction group number
  64  *     as part of their data.  When reading old data, they verify that
  65  *     the transaction group number is less than the current, open txg.
  66  *     If you add a new test, please do this if applicable.
  67  *
  68  * When run with no arguments, ztest runs for about five minutes and
  69  * produces no output if successful.  To get a little bit of information,
  70  * specify -V.  To get more information, specify -VV, and so on.
  71  *
  72  * To turn this into an overnight stress test, use -T to specify run time.
  73  *
  74  * You can ask more more vdevs [-v], datasets [-d], or threads [-t]
  75  * to increase the pool capacity, fanout, and overall stress level.
  76  *
  77  * Use the -k option to set the desired frequency of kills.
  78  *
  79  * When ztest invokes itself it passes all relevant information through a
  80  * temporary file which is mmap-ed in the child process. This allows shared
  81  * memory to survive the exec syscall. The ztest_shared_hdr_t struct is always
  82  * stored at offset 0 of this file and contains information on the size and
  83  * number of shared structures in the file. The information stored in this file
  84  * must remain backwards compatible with older versions of ztest so that
  85  * ztest can invoke them during backwards compatibility testing (-B).
  86  */
  87 
  88 #include <sys/zfs_context.h>
  89 #include <sys/spa.h>
  90 #include <sys/dmu.h>
  91 #include <sys/txg.h>
  92 #include <sys/dbuf.h>
  93 #include <sys/zap.h>
  94 #include <sys/dmu_objset.h>
  95 #include <sys/poll.h>
  96 #include <sys/stat.h>
  97 #include <sys/time.h>
  98 #include <sys/wait.h>
  99 #include <sys/mman.h>
 100 #include <sys/resource.h>
 101 #include <sys/zio.h>
 102 #include <sys/zil.h>
 103 #include <sys/zil_impl.h>
 104 #include <sys/vdev_impl.h>
 105 #include <sys/vdev_file.h>
 106 #include <sys/spa_impl.h>
 107 #include <sys/metaslab_impl.h>
 108 #include <sys/dsl_prop.h>
 109 #include <sys/dsl_dataset.h>
 110 #include <sys/dsl_destroy.h>
 111 #include <sys/dsl_scan.h>
 112 #include <sys/zio_checksum.h>
 113 #include <sys/refcount.h>
 114 #include <sys/zfeature.h>
 115 #include <sys/dsl_userhold.h>
 116 #include <sys/abd.h>
 117 #include <stdio.h>
 118 #include <stdio_ext.h>
 119 #include <stdlib.h>
 120 #include <unistd.h>
 121 #include <signal.h>
 122 #include <umem.h>
 123 #include <dlfcn.h>
 124 #include <ctype.h>
 125 #include <math.h>
 126 #include <sys/fs/zfs.h>
 127 #include <libnvpair.h>
 128 #include <libcmdutils.h>
 129 
 130 static int ztest_fd_data = -1;
 131 static int ztest_fd_rand = -1;
 132 
 133 typedef struct ztest_shared_hdr {
 134         uint64_t        zh_hdr_size;
 135         uint64_t        zh_opts_size;
 136         uint64_t        zh_size;
 137         uint64_t        zh_stats_size;
 138         uint64_t        zh_stats_count;
 139         uint64_t        zh_ds_size;
 140         uint64_t        zh_ds_count;
 141 } ztest_shared_hdr_t;
 142 
 143 static ztest_shared_hdr_t *ztest_shared_hdr;
 144 
 145 typedef struct ztest_shared_opts {
 146         char zo_pool[ZFS_MAX_DATASET_NAME_LEN];
 147         char zo_dir[ZFS_MAX_DATASET_NAME_LEN];
 148         char zo_alt_ztest[MAXNAMELEN];
 149         char zo_alt_libpath[MAXNAMELEN];
 150         uint64_t zo_vdevs;
 151         uint64_t zo_vdevtime;
 152         size_t zo_vdev_size;
 153         int zo_ashift;
 154         int zo_mirrors;
 155         int zo_raidz;
 156         int zo_raidz_parity;
 157         int zo_datasets;
 158         int zo_threads;
 159         uint64_t zo_passtime;
 160         uint64_t zo_killrate;
 161         int zo_verbose;
 162         int zo_init;
 163         uint64_t zo_time;
 164         uint64_t zo_maxloops;
 165         uint64_t zo_metaslab_gang_bang;
 166 } ztest_shared_opts_t;
 167 
 168 static const ztest_shared_opts_t ztest_opts_defaults = {
 169         .zo_pool = { 'z', 't', 'e', 's', 't', '\0' },
 170         .zo_dir = { '/', 't', 'm', 'p', '\0' },
 171         .zo_alt_ztest = { '\0' },
 172         .zo_alt_libpath = { '\0' },
 173         .zo_vdevs = 5,
 174         .zo_ashift = SPA_MINBLOCKSHIFT,
 175         .zo_mirrors = 2,
 176         .zo_raidz = 4,
 177         .zo_raidz_parity = 1,
 178         .zo_vdev_size = SPA_MINDEVSIZE * 4,     /* 256m default size */
 179         .zo_datasets = 7,
 180         .zo_threads = 23,
 181         .zo_passtime = 60,              /* 60 seconds */
 182         .zo_killrate = 70,              /* 70% kill rate */
 183         .zo_verbose = 0,
 184         .zo_init = 1,
 185         .zo_time = 300,                 /* 5 minutes */
 186         .zo_maxloops = 50,              /* max loops during spa_freeze() */
 187         .zo_metaslab_gang_bang = 32 << 10
 188 };
 189 
 190 extern uint64_t metaslab_gang_bang;
 191 extern uint64_t metaslab_df_alloc_threshold;
 192 extern uint64_t zfs_deadman_synctime_ms;
 193 extern int metaslab_preload_limit;
 194 extern boolean_t zfs_compressed_arc_enabled;
 195 extern boolean_t zfs_abd_scatter_enabled;
 196 
 197 static ztest_shared_opts_t *ztest_shared_opts;
 198 static ztest_shared_opts_t ztest_opts;
 199 
 200 typedef struct ztest_shared_ds {
 201         uint64_t        zd_seq;
 202 } ztest_shared_ds_t;
 203 
 204 static ztest_shared_ds_t *ztest_shared_ds;
 205 #define ZTEST_GET_SHARED_DS(d) (&ztest_shared_ds[d])
 206 
 207 #define BT_MAGIC        0x123456789abcdefULL
 208 #define MAXFAULTS() \
 209         (MAX(zs->zs_mirrors, 1) * (ztest_opts.zo_raidz_parity + 1) - 1)
 210 
 211 enum ztest_io_type {
 212         ZTEST_IO_WRITE_TAG,
 213         ZTEST_IO_WRITE_PATTERN,
 214         ZTEST_IO_WRITE_ZEROES,
 215         ZTEST_IO_TRUNCATE,
 216         ZTEST_IO_SETATTR,
 217         ZTEST_IO_REWRITE,
 218         ZTEST_IO_TYPES
 219 };
 220 
 221 typedef struct ztest_block_tag {
 222         uint64_t        bt_magic;
 223         uint64_t        bt_objset;
 224         uint64_t        bt_object;
 225         uint64_t        bt_offset;
 226         uint64_t        bt_gen;
 227         uint64_t        bt_txg;
 228         uint64_t        bt_crtxg;
 229 } ztest_block_tag_t;
 230 
 231 typedef struct bufwad {
 232         uint64_t        bw_index;
 233         uint64_t        bw_txg;
 234         uint64_t        bw_data;
 235 } bufwad_t;
 236 
 237 /*
 238  * XXX -- fix zfs range locks to be generic so we can use them here.
 239  */
 240 typedef enum {
 241         RL_READER,
 242         RL_WRITER,
 243         RL_APPEND
 244 } rl_type_t;
 245 
 246 typedef struct rll {
 247         void            *rll_writer;
 248         int             rll_readers;
 249         kmutex_t        rll_lock;
 250         kcondvar_t      rll_cv;
 251 } rll_t;
 252 
 253 typedef struct rl {
 254         uint64_t        rl_object;
 255         uint64_t        rl_offset;
 256         uint64_t        rl_size;
 257         rll_t           *rl_lock;
 258 } rl_t;
 259 
 260 #define ZTEST_RANGE_LOCKS       64
 261 #define ZTEST_OBJECT_LOCKS      64
 262 
 263 /*
 264  * Object descriptor.  Used as a template for object lookup/create/remove.
 265  */
 266 typedef struct ztest_od {
 267         uint64_t        od_dir;
 268         uint64_t        od_object;
 269         dmu_object_type_t od_type;
 270         dmu_object_type_t od_crtype;
 271         uint64_t        od_blocksize;
 272         uint64_t        od_crblocksize;
 273         uint64_t        od_gen;
 274         uint64_t        od_crgen;
 275         char            od_name[ZFS_MAX_DATASET_NAME_LEN];
 276 } ztest_od_t;
 277 
 278 /*
 279  * Per-dataset state.
 280  */
 281 typedef struct ztest_ds {
 282         ztest_shared_ds_t *zd_shared;
 283         objset_t        *zd_os;
 284         krwlock_t       zd_zilog_lock;
 285         zilog_t         *zd_zilog;
 286         ztest_od_t      *zd_od;         /* debugging aid */
 287         char            zd_name[ZFS_MAX_DATASET_NAME_LEN];
 288         kmutex_t        zd_dirobj_lock;
 289         rll_t           zd_object_lock[ZTEST_OBJECT_LOCKS];
 290         rll_t           zd_range_lock[ZTEST_RANGE_LOCKS];
 291 } ztest_ds_t;
 292 
 293 /*
 294  * Per-iteration state.
 295  */
 296 typedef void ztest_func_t(ztest_ds_t *zd, uint64_t id);
 297 
 298 typedef struct ztest_info {
 299         ztest_func_t    *zi_func;       /* test function */
 300         uint64_t        zi_iters;       /* iterations per execution */
 301         uint64_t        *zi_interval;   /* execute every <interval> seconds */
 302 } ztest_info_t;
 303 
 304 typedef struct ztest_shared_callstate {
 305         uint64_t        zc_count;       /* per-pass count */
 306         uint64_t        zc_time;        /* per-pass time */
 307         uint64_t        zc_next;        /* next time to call this function */
 308 } ztest_shared_callstate_t;
 309 
 310 static ztest_shared_callstate_t *ztest_shared_callstate;
 311 #define ZTEST_GET_SHARED_CALLSTATE(c) (&ztest_shared_callstate[c])
 312 
 313 /*
 314  * Note: these aren't static because we want dladdr() to work.
 315  */
 316 ztest_func_t ztest_dmu_read_write;
 317 ztest_func_t ztest_dmu_write_parallel;
 318 ztest_func_t ztest_dmu_object_alloc_free;
 319 ztest_func_t ztest_dmu_commit_callbacks;
 320 ztest_func_t ztest_zap;
 321 ztest_func_t ztest_zap_parallel;
 322 ztest_func_t ztest_zil_commit;
 323 ztest_func_t ztest_zil_remount;
 324 ztest_func_t ztest_dmu_read_write_zcopy;
 325 ztest_func_t ztest_dmu_objset_create_destroy;
 326 ztest_func_t ztest_dmu_prealloc;
 327 ztest_func_t ztest_fzap;
 328 ztest_func_t ztest_dmu_snapshot_create_destroy;
 329 ztest_func_t ztest_dsl_prop_get_set;
 330 ztest_func_t ztest_spa_prop_get_set;
 331 ztest_func_t ztest_spa_create_destroy;
 332 ztest_func_t ztest_fault_inject;
 333 ztest_func_t ztest_ddt_repair;
 334 ztest_func_t ztest_dmu_snapshot_hold;
 335 ztest_func_t ztest_spa_rename;
 336 ztest_func_t ztest_scrub;
 337 ztest_func_t ztest_dsl_dataset_promote_busy;
 338 ztest_func_t ztest_vdev_attach_detach;
 339 ztest_func_t ztest_vdev_LUN_growth;
 340 ztest_func_t ztest_vdev_add_remove;
 341 ztest_func_t ztest_vdev_aux_add_remove;
 342 ztest_func_t ztest_split_pool;
 343 ztest_func_t ztest_reguid;
 344 ztest_func_t ztest_spa_upgrade;
 345 
 346 uint64_t zopt_always = 0ULL * NANOSEC;          /* all the time */
 347 uint64_t zopt_incessant = 1ULL * NANOSEC / 10;  /* every 1/10 second */
 348 uint64_t zopt_often = 1ULL * NANOSEC;           /* every second */
 349 uint64_t zopt_sometimes = 10ULL * NANOSEC;      /* every 10 seconds */
 350 uint64_t zopt_rarely = 60ULL * NANOSEC;         /* every 60 seconds */
 351 
 352 ztest_info_t ztest_info[] = {
 353         { ztest_dmu_read_write,                 1,      &zopt_always        },
 354         { ztest_dmu_write_parallel,             10,     &zopt_always        },
 355         { ztest_dmu_object_alloc_free,          1,      &zopt_always        },
 356         { ztest_dmu_commit_callbacks,           1,      &zopt_always        },
 357         { ztest_zap,                            30,     &zopt_always        },
 358         { ztest_zap_parallel,                   100,    &zopt_always        },
 359         { ztest_split_pool,                     1,      &zopt_always        },
 360         { ztest_zil_commit,                     1,      &zopt_incessant     },
 361         { ztest_zil_remount,                    1,      &zopt_sometimes     },
 362         { ztest_dmu_read_write_zcopy,           1,      &zopt_often },
 363         { ztest_dmu_objset_create_destroy,      1,      &zopt_often },
 364         { ztest_dsl_prop_get_set,               1,      &zopt_often },
 365         { ztest_spa_prop_get_set,               1,      &zopt_sometimes     },
 366 #if 0
 367         { ztest_dmu_prealloc,                   1,      &zopt_sometimes     },
 368 #endif
 369         { ztest_fzap,                           1,      &zopt_sometimes     },
 370         { ztest_dmu_snapshot_create_destroy,    1,      &zopt_sometimes     },
 371         { ztest_spa_create_destroy,             1,      &zopt_sometimes     },
 372         { ztest_fault_inject,                   1,      &zopt_sometimes     },
 373         { ztest_ddt_repair,                     1,      &zopt_sometimes     },
 374         { ztest_dmu_snapshot_hold,              1,      &zopt_sometimes     },
 375         { ztest_reguid,                         1,      &zopt_rarely        },
 376         { ztest_spa_rename,                     1,      &zopt_rarely        },
 377         { ztest_scrub,                          1,      &zopt_rarely        },
 378         { ztest_spa_upgrade,                    1,      &zopt_rarely        },
 379         { ztest_dsl_dataset_promote_busy,       1,      &zopt_rarely        },
 380         { ztest_vdev_attach_detach,             1,      &zopt_sometimes     },
 381         { ztest_vdev_LUN_growth,                1,      &zopt_rarely        },
 382         { ztest_vdev_add_remove,                1,
 383             &ztest_opts.zo_vdevtime                         },
 384         { ztest_vdev_aux_add_remove,            1,
 385             &ztest_opts.zo_vdevtime                         },
 386 };
 387 
 388 #define ZTEST_FUNCS     (sizeof (ztest_info) / sizeof (ztest_info_t))
 389 
 390 /*
 391  * The following struct is used to hold a list of uncalled commit callbacks.
 392  * The callbacks are ordered by txg number.
 393  */
 394 typedef struct ztest_cb_list {
 395         kmutex_t zcl_callbacks_lock;
 396         list_t  zcl_callbacks;
 397 } ztest_cb_list_t;
 398 
 399 /*
 400  * Stuff we need to share writably between parent and child.
 401  */
 402 typedef struct ztest_shared {
 403         boolean_t       zs_do_init;
 404         hrtime_t        zs_proc_start;
 405         hrtime_t        zs_proc_stop;
 406         hrtime_t        zs_thread_start;
 407         hrtime_t        zs_thread_stop;
 408         hrtime_t        zs_thread_kill;
 409         uint64_t        zs_enospc_count;
 410         uint64_t        zs_vdev_next_leaf;
 411         uint64_t        zs_vdev_aux;
 412         uint64_t        zs_alloc;
 413         uint64_t        zs_space;
 414         uint64_t        zs_splits;
 415         uint64_t        zs_mirrors;
 416         uint64_t        zs_metaslab_sz;
 417         uint64_t        zs_metaslab_df_alloc_threshold;
 418         uint64_t        zs_guid;
 419 } ztest_shared_t;
 420 
 421 #define ID_PARALLEL     -1ULL
 422 
 423 static char ztest_dev_template[] = "%s/%s.%llua";
 424 static char ztest_aux_template[] = "%s/%s.%s.%llu";
 425 ztest_shared_t *ztest_shared;
 426 
 427 static spa_t *ztest_spa = NULL;
 428 static ztest_ds_t *ztest_ds;
 429 
 430 static kmutex_t ztest_vdev_lock;
 431 
 432 /*
 433  * The ztest_name_lock protects the pool and dataset namespace used by
 434  * the individual tests. To modify the namespace, consumers must grab
 435  * this lock as writer. Grabbing the lock as reader will ensure that the
 436  * namespace does not change while the lock is held.
 437  */
 438 static krwlock_t ztest_name_lock;
 439 
 440 static boolean_t ztest_dump_core = B_TRUE;
 441 static boolean_t ztest_exiting;
 442 
 443 /* Global commit callback list */
 444 static ztest_cb_list_t zcl;
 445 
 446 enum ztest_object {
 447         ZTEST_META_DNODE = 0,
 448         ZTEST_DIROBJ,
 449         ZTEST_OBJECTS
 450 };
 451 
 452 static void usage(boolean_t) __NORETURN;
 453 
 454 /*
 455  * These libumem hooks provide a reasonable set of defaults for the allocator's
 456  * debugging facilities.
 457  */
 458 const char *
 459 _umem_debug_init()
 460 {
 461         return ("default,verbose"); /* $UMEM_DEBUG setting */
 462 }
 463 
 464 const char *
 465 _umem_logging_init(void)
 466 {
 467         return ("fail,contents"); /* $UMEM_LOGGING setting */
 468 }
 469 
 470 #define FATAL_MSG_SZ    1024
 471 
 472 char *fatal_msg;
 473 
 474 static void
 475 fatal(int do_perror, char *message, ...)
 476 {
 477         va_list args;
 478         int save_errno = errno;
 479         char buf[FATAL_MSG_SZ];
 480 
 481         (void) fflush(stdout);
 482 
 483         va_start(args, message);
 484         (void) sprintf(buf, "ztest: ");
 485         /* LINTED */
 486         (void) vsprintf(buf + strlen(buf), message, args);
 487         va_end(args);
 488         if (do_perror) {
 489                 (void) snprintf(buf + strlen(buf), FATAL_MSG_SZ - strlen(buf),
 490                     ": %s", strerror(save_errno));
 491         }
 492         (void) fprintf(stderr, "%s\n", buf);
 493         fatal_msg = buf;                        /* to ease debugging */
 494         if (ztest_dump_core)
 495                 abort();
 496         exit(3);
 497 }
 498 
 499 static int
 500 str2shift(const char *buf)
 501 {
 502         const char *ends = "BKMGTPEZ";
 503         int i;
 504 
 505         if (buf[0] == '\0')
 506                 return (0);
 507         for (i = 0; i < strlen(ends); i++) {
 508                 if (toupper(buf[0]) == ends[i])
 509                         break;
 510         }
 511         if (i == strlen(ends)) {
 512                 (void) fprintf(stderr, "ztest: invalid bytes suffix: %s\n",
 513                     buf);
 514                 usage(B_FALSE);
 515         }
 516         if (buf[1] == '\0' || (toupper(buf[1]) == 'B' && buf[2] == '\0')) {
 517                 return (10*i);
 518         }
 519         (void) fprintf(stderr, "ztest: invalid bytes suffix: %s\n", buf);
 520         usage(B_FALSE);
 521         /* NOTREACHED */
 522 }
 523 
 524 static uint64_t
 525 nicenumtoull(const char *buf)
 526 {
 527         char *end;
 528         uint64_t val;
 529 
 530         val = strtoull(buf, &end, 0);
 531         if (end == buf) {
 532                 (void) fprintf(stderr, "ztest: bad numeric value: %s\n", buf);
 533                 usage(B_FALSE);
 534         } else if (end[0] == '.') {
 535                 double fval = strtod(buf, &end);
 536                 fval *= pow(2, str2shift(end));
 537                 if (fval > UINT64_MAX) {
 538                         (void) fprintf(stderr, "ztest: value too large: %s\n",
 539                             buf);
 540                         usage(B_FALSE);
 541                 }
 542                 val = (uint64_t)fval;
 543         } else {
 544                 int shift = str2shift(end);
 545                 if (shift >= 64 || (val << shift) >> shift != val) {
 546                         (void) fprintf(stderr, "ztest: value too large: %s\n",
 547                             buf);
 548                         usage(B_FALSE);
 549                 }
 550                 val <<= shift;
 551         }
 552         return (val);
 553 }
 554 
 555 static void
 556 usage(boolean_t requested)
 557 {
 558         const ztest_shared_opts_t *zo = &ztest_opts_defaults;
 559 
 560         char nice_vdev_size[NN_NUMBUF_SZ];
 561         char nice_gang_bang[NN_NUMBUF_SZ];
 562         FILE *fp = requested ? stdout : stderr;
 563 
 564         nicenum(zo->zo_vdev_size, nice_vdev_size, sizeof (nice_vdev_size));
 565         nicenum(zo->zo_metaslab_gang_bang, nice_gang_bang,
 566             sizeof (nice_gang_bang));
 567 
 568         (void) fprintf(fp, "Usage: %s\n"
 569             "\t[-v vdevs (default: %llu)]\n"
 570             "\t[-s size_of_each_vdev (default: %s)]\n"
 571             "\t[-a alignment_shift (default: %d)] use 0 for random\n"
 572             "\t[-m mirror_copies (default: %d)]\n"
 573             "\t[-r raidz_disks (default: %d)]\n"
 574             "\t[-R raidz_parity (default: %d)]\n"
 575             "\t[-d datasets (default: %d)]\n"
 576             "\t[-t threads (default: %d)]\n"
 577             "\t[-g gang_block_threshold (default: %s)]\n"
 578             "\t[-i init_count (default: %d)] initialize pool i times\n"
 579             "\t[-k kill_percentage (default: %llu%%)]\n"
 580             "\t[-p pool_name (default: %s)]\n"
 581             "\t[-f dir (default: %s)] file directory for vdev files\n"
 582             "\t[-V] verbose (use multiple times for ever more blather)\n"
 583             "\t[-E] use existing pool instead of creating new one\n"
 584             "\t[-T time (default: %llu sec)] total run time\n"
 585             "\t[-F freezeloops (default: %llu)] max loops in spa_freeze()\n"
 586             "\t[-P passtime (default: %llu sec)] time per pass\n"
 587             "\t[-B alt_ztest (default: <none>)] alternate ztest path\n"
 588             "\t[-o variable=value] ... set global variable to an unsigned\n"
 589             "\t    32-bit integer value\n"
 590             "\t[-h] (print help)\n"
 591             "",
 592             zo->zo_pool,
 593             (u_longlong_t)zo->zo_vdevs,                      /* -v */
 594             nice_vdev_size,                             /* -s */
 595             zo->zo_ashift,                           /* -a */
 596             zo->zo_mirrors,                          /* -m */
 597             zo->zo_raidz,                            /* -r */
 598             zo->zo_raidz_parity,                     /* -R */
 599             zo->zo_datasets,                         /* -d */
 600             zo->zo_threads,                          /* -t */
 601             nice_gang_bang,                             /* -g */
 602             zo->zo_init,                             /* -i */
 603             (u_longlong_t)zo->zo_killrate,           /* -k */
 604             zo->zo_pool,                             /* -p */
 605             zo->zo_dir,                                      /* -f */
 606             (u_longlong_t)zo->zo_time,                       /* -T */
 607             (u_longlong_t)zo->zo_maxloops,           /* -F */
 608             (u_longlong_t)zo->zo_passtime);
 609         exit(requested ? 0 : 1);
 610 }
 611 
 612 static void
 613 process_options(int argc, char **argv)
 614 {
 615         char *path;
 616         ztest_shared_opts_t *zo = &ztest_opts;
 617 
 618         int opt;
 619         uint64_t value;
 620         char altdir[MAXNAMELEN] = { 0 };
 621 
 622         bcopy(&ztest_opts_defaults, zo, sizeof (*zo));
 623 
 624         while ((opt = getopt(argc, argv,
 625             "v:s:a:m:r:R:d:t:g:i:k:p:f:VET:P:hF:B:o:")) != EOF) {
 626                 value = 0;
 627                 switch (opt) {
 628                 case 'v':
 629                 case 's':
 630                 case 'a':
 631                 case 'm':
 632                 case 'r':
 633                 case 'R':
 634                 case 'd':
 635                 case 't':
 636                 case 'g':
 637                 case 'i':
 638                 case 'k':
 639                 case 'T':
 640                 case 'P':
 641                 case 'F':
 642                         value = nicenumtoull(optarg);
 643                 }
 644                 switch (opt) {
 645                 case 'v':
 646                         zo->zo_vdevs = value;
 647                         break;
 648                 case 's':
 649                         zo->zo_vdev_size = MAX(SPA_MINDEVSIZE, value);
 650                         break;
 651                 case 'a':
 652                         zo->zo_ashift = value;
 653                         break;
 654                 case 'm':
 655                         zo->zo_mirrors = value;
 656                         break;
 657                 case 'r':
 658                         zo->zo_raidz = MAX(1, value);
 659                         break;
 660                 case 'R':
 661                         zo->zo_raidz_parity = MIN(MAX(value, 1), 3);
 662                         break;
 663                 case 'd':
 664                         zo->zo_datasets = MAX(1, value);
 665                         break;
 666                 case 't':
 667                         zo->zo_threads = MAX(1, value);
 668                         break;
 669                 case 'g':
 670                         zo->zo_metaslab_gang_bang = MAX(SPA_MINBLOCKSIZE << 1,
 671                             value);
 672                         break;
 673                 case 'i':
 674                         zo->zo_init = value;
 675                         break;
 676                 case 'k':
 677                         zo->zo_killrate = value;
 678                         break;
 679                 case 'p':
 680                         (void) strlcpy(zo->zo_pool, optarg,
 681                             sizeof (zo->zo_pool));
 682                         break;
 683                 case 'f':
 684                         path = realpath(optarg, NULL);
 685                         if (path == NULL) {
 686                                 (void) fprintf(stderr, "error: %s: %s\n",
 687                                     optarg, strerror(errno));
 688                                 usage(B_FALSE);
 689                         } else {
 690                                 (void) strlcpy(zo->zo_dir, path,
 691                                     sizeof (zo->zo_dir));
 692                         }
 693                         break;
 694                 case 'V':
 695                         zo->zo_verbose++;
 696                         break;
 697                 case 'E':
 698                         zo->zo_init = 0;
 699                         break;
 700                 case 'T':
 701                         zo->zo_time = value;
 702                         break;
 703                 case 'P':
 704                         zo->zo_passtime = MAX(1, value);
 705                         break;
 706                 case 'F':
 707                         zo->zo_maxloops = MAX(1, value);
 708                         break;
 709                 case 'B':
 710                         (void) strlcpy(altdir, optarg, sizeof (altdir));
 711                         break;
 712                 case 'o':
 713                         if (set_global_var(optarg) != 0)
 714                                 usage(B_FALSE);
 715                         break;
 716                 case 'h':
 717                         usage(B_TRUE);
 718                         break;
 719                 case '?':
 720                 default:
 721                         usage(B_FALSE);
 722                         break;
 723                 }
 724         }
 725 
 726         zo->zo_raidz_parity = MIN(zo->zo_raidz_parity, zo->zo_raidz - 1);
 727 
 728         zo->zo_vdevtime =
 729             (zo->zo_vdevs > 0 ? zo->zo_time * NANOSEC / zo->zo_vdevs :
 730             UINT64_MAX >> 2);
 731 
 732         if (strlen(altdir) > 0) {
 733                 char *cmd;
 734                 char *realaltdir;
 735                 char *bin;
 736                 char *ztest;
 737                 char *isa;
 738                 int isalen;
 739 
 740                 cmd = umem_alloc(MAXPATHLEN, UMEM_NOFAIL);
 741                 realaltdir = umem_alloc(MAXPATHLEN, UMEM_NOFAIL);
 742 
 743                 VERIFY(NULL != realpath(getexecname(), cmd));
 744                 if (0 != access(altdir, F_OK)) {
 745                         ztest_dump_core = B_FALSE;
 746                         fatal(B_TRUE, "invalid alternate ztest path: %s",
 747                             altdir);
 748                 }
 749                 VERIFY(NULL != realpath(altdir, realaltdir));
 750 
 751                 /*
 752                  * 'cmd' should be of the form "<anything>/usr/bin/<isa>/ztest".
 753                  * We want to extract <isa> to determine if we should use
 754                  * 32 or 64 bit binaries.
 755                  */
 756                 bin = strstr(cmd, "/usr/bin/");
 757                 ztest = strstr(bin, "/ztest");
 758                 isa = bin + 9;
 759                 isalen = ztest - isa;
 760                 (void) snprintf(zo->zo_alt_ztest, sizeof (zo->zo_alt_ztest),
 761                     "%s/usr/bin/%.*s/ztest", realaltdir, isalen, isa);
 762                 (void) snprintf(zo->zo_alt_libpath, sizeof (zo->zo_alt_libpath),
 763                     "%s/usr/lib/%.*s", realaltdir, isalen, isa);
 764 
 765                 if (0 != access(zo->zo_alt_ztest, X_OK)) {
 766                         ztest_dump_core = B_FALSE;
 767                         fatal(B_TRUE, "invalid alternate ztest: %s",
 768                             zo->zo_alt_ztest);
 769                 } else if (0 != access(zo->zo_alt_libpath, X_OK)) {
 770                         ztest_dump_core = B_FALSE;
 771                         fatal(B_TRUE, "invalid alternate lib directory %s",
 772                             zo->zo_alt_libpath);
 773                 }
 774 
 775                 umem_free(cmd, MAXPATHLEN);
 776                 umem_free(realaltdir, MAXPATHLEN);
 777         }
 778 }
 779 
 780 static void
 781 ztest_kill(ztest_shared_t *zs)
 782 {
 783         zs->zs_alloc = metaslab_class_get_alloc(spa_normal_class(ztest_spa));
 784         zs->zs_space = metaslab_class_get_space(spa_normal_class(ztest_spa));
 785 
 786         /*
 787          * Before we kill off ztest, make sure that the config is updated.
 788          * See comment above spa_config_sync().
 789          */
 790         mutex_enter(&spa_namespace_lock);
 791         spa_config_sync(ztest_spa, B_FALSE, B_FALSE);
 792         mutex_exit(&spa_namespace_lock);
 793 
 794         zfs_dbgmsg_print(FTAG);
 795         (void) kill(getpid(), SIGKILL);
 796 }
 797 
 798 static uint64_t
 799 ztest_random(uint64_t range)
 800 {
 801         uint64_t r;
 802 
 803         ASSERT3S(ztest_fd_rand, >=, 0);
 804 
 805         if (range == 0)
 806                 return (0);
 807 
 808         if (read(ztest_fd_rand, &r, sizeof (r)) != sizeof (r))
 809                 fatal(1, "short read from /dev/urandom");
 810 
 811         return (r % range);
 812 }
 813 
 814 /* ARGSUSED */
 815 static void
 816 ztest_record_enospc(const char *s)
 817 {
 818         ztest_shared->zs_enospc_count++;
 819 }
 820 
 821 static uint64_t
 822 ztest_get_ashift(void)
 823 {
 824         if (ztest_opts.zo_ashift == 0)
 825                 return (SPA_MINBLOCKSHIFT + ztest_random(5));
 826         return (ztest_opts.zo_ashift);
 827 }
 828 
 829 static nvlist_t *
 830 make_vdev_file(char *path, char *aux, char *pool, size_t size, uint64_t ashift)
 831 {
 832         char pathbuf[MAXPATHLEN];
 833         uint64_t vdev;
 834         nvlist_t *file;
 835 
 836         if (ashift == 0)
 837                 ashift = ztest_get_ashift();
 838 
 839         if (path == NULL) {
 840                 path = pathbuf;
 841 
 842                 if (aux != NULL) {
 843                         vdev = ztest_shared->zs_vdev_aux;
 844                         (void) snprintf(path, sizeof (pathbuf),
 845                             ztest_aux_template, ztest_opts.zo_dir,
 846                             pool == NULL ? ztest_opts.zo_pool : pool,
 847                             aux, vdev);
 848                 } else {
 849                         vdev = ztest_shared->zs_vdev_next_leaf++;
 850                         (void) snprintf(path, sizeof (pathbuf),
 851                             ztest_dev_template, ztest_opts.zo_dir,
 852                             pool == NULL ? ztest_opts.zo_pool : pool, vdev);
 853                 }
 854         }
 855 
 856         if (size != 0) {
 857                 int fd = open(path, O_RDWR | O_CREAT | O_TRUNC, 0666);
 858                 if (fd == -1)
 859                         fatal(1, "can't open %s", path);
 860                 if (ftruncate(fd, size) != 0)
 861                         fatal(1, "can't ftruncate %s", path);
 862                 (void) close(fd);
 863         }
 864 
 865         VERIFY(nvlist_alloc(&file, NV_UNIQUE_NAME, 0) == 0);
 866         VERIFY(nvlist_add_string(file, ZPOOL_CONFIG_TYPE, VDEV_TYPE_FILE) == 0);
 867         VERIFY(nvlist_add_string(file, ZPOOL_CONFIG_PATH, path) == 0);
 868         VERIFY(nvlist_add_uint64(file, ZPOOL_CONFIG_ASHIFT, ashift) == 0);
 869 
 870         return (file);
 871 }
 872 
 873 static nvlist_t *
 874 make_vdev_raidz(char *path, char *aux, char *pool, size_t size,
 875     uint64_t ashift, int r)
 876 {
 877         nvlist_t *raidz, **child;
 878         int c;
 879 
 880         if (r < 2)
 881                 return (make_vdev_file(path, aux, pool, size, ashift));
 882         child = umem_alloc(r * sizeof (nvlist_t *), UMEM_NOFAIL);
 883 
 884         for (c = 0; c < r; c++)
 885                 child[c] = make_vdev_file(path, aux, pool, size, ashift);
 886 
 887         VERIFY(nvlist_alloc(&raidz, NV_UNIQUE_NAME, 0) == 0);
 888         VERIFY(nvlist_add_string(raidz, ZPOOL_CONFIG_TYPE,
 889             VDEV_TYPE_RAIDZ) == 0);
 890         VERIFY(nvlist_add_uint64(raidz, ZPOOL_CONFIG_NPARITY,
 891             ztest_opts.zo_raidz_parity) == 0);
 892         VERIFY(nvlist_add_nvlist_array(raidz, ZPOOL_CONFIG_CHILDREN,
 893             child, r) == 0);
 894 
 895         for (c = 0; c < r; c++)
 896                 nvlist_free(child[c]);
 897 
 898         umem_free(child, r * sizeof (nvlist_t *));
 899 
 900         return (raidz);
 901 }
 902 
 903 static nvlist_t *
 904 make_vdev_mirror(char *path, char *aux, char *pool, size_t size,
 905     uint64_t ashift, int r, int m)
 906 {
 907         nvlist_t *mirror, **child;
 908         int c;
 909 
 910         if (m < 1)
 911                 return (make_vdev_raidz(path, aux, pool, size, ashift, r));
 912 
 913         child = umem_alloc(m * sizeof (nvlist_t *), UMEM_NOFAIL);
 914 
 915         for (c = 0; c < m; c++)
 916                 child[c] = make_vdev_raidz(path, aux, pool, size, ashift, r);
 917 
 918         VERIFY(nvlist_alloc(&mirror, NV_UNIQUE_NAME, 0) == 0);
 919         VERIFY(nvlist_add_string(mirror, ZPOOL_CONFIG_TYPE,
 920             VDEV_TYPE_MIRROR) == 0);
 921         VERIFY(nvlist_add_nvlist_array(mirror, ZPOOL_CONFIG_CHILDREN,
 922             child, m) == 0);
 923 
 924         for (c = 0; c < m; c++)
 925                 nvlist_free(child[c]);
 926 
 927         umem_free(child, m * sizeof (nvlist_t *));
 928 
 929         return (mirror);
 930 }
 931 
 932 static nvlist_t *
 933 make_vdev_root(char *path, char *aux, char *pool, size_t size, uint64_t ashift,
 934     int log, int r, int m, int t)
 935 {
 936         nvlist_t *root, **child;
 937         int c;
 938 
 939         ASSERT(t > 0);
 940 
 941         child = umem_alloc(t * sizeof (nvlist_t *), UMEM_NOFAIL);
 942 
 943         for (c = 0; c < t; c++) {
 944                 child[c] = make_vdev_mirror(path, aux, pool, size, ashift,
 945                     r, m);
 946                 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
 947                     log) == 0);
 948         }
 949 
 950         VERIFY(nvlist_alloc(&root, NV_UNIQUE_NAME, 0) == 0);
 951         VERIFY(nvlist_add_string(root, ZPOOL_CONFIG_TYPE, VDEV_TYPE_ROOT) == 0);
 952         VERIFY(nvlist_add_nvlist_array(root, aux ? aux : ZPOOL_CONFIG_CHILDREN,
 953             child, t) == 0);
 954 
 955         for (c = 0; c < t; c++)
 956                 nvlist_free(child[c]);
 957 
 958         umem_free(child, t * sizeof (nvlist_t *));
 959 
 960         return (root);
 961 }
 962 
 963 /*
 964  * Find a random spa version. Returns back a random spa version in the
 965  * range [initial_version, SPA_VERSION_FEATURES].
 966  */
 967 static uint64_t
 968 ztest_random_spa_version(uint64_t initial_version)
 969 {
 970         uint64_t version = initial_version;
 971 
 972         if (version <= SPA_VERSION_BEFORE_FEATURES) {
 973                 version = version +
 974                     ztest_random(SPA_VERSION_BEFORE_FEATURES - version + 1);
 975         }
 976 
 977         if (version > SPA_VERSION_BEFORE_FEATURES)
 978                 version = SPA_VERSION_FEATURES;
 979 
 980         ASSERT(SPA_VERSION_IS_SUPPORTED(version));
 981         return (version);
 982 }
 983 
 984 static int
 985 ztest_random_blocksize(void)
 986 {
 987         uint64_t block_shift;
 988         /*
 989          * Choose a block size >= the ashift.
 990          * If the SPA supports new MAXBLOCKSIZE, test up to 1MB blocks.
 991          */
 992         int maxbs = SPA_OLD_MAXBLOCKSHIFT;
 993         if (spa_maxblocksize(ztest_spa) == SPA_MAXBLOCKSIZE)
 994                 maxbs = 20;
 995         block_shift = ztest_random(maxbs - ztest_spa->spa_max_ashift + 1);
 996         return (1 << (SPA_MINBLOCKSHIFT + block_shift));
 997 }
 998 
 999 static int
1000 ztest_random_ibshift(void)
1001 {
1002         return (DN_MIN_INDBLKSHIFT +
1003             ztest_random(DN_MAX_INDBLKSHIFT - DN_MIN_INDBLKSHIFT + 1));
1004 }
1005 
1006 static uint64_t
1007 ztest_random_vdev_top(spa_t *spa, boolean_t log_ok)
1008 {
1009         uint64_t top;
1010         vdev_t *rvd = spa->spa_root_vdev;
1011         vdev_t *tvd;
1012 
1013         ASSERT(spa_config_held(spa, SCL_ALL, RW_READER) != 0);
1014 
1015         do {
1016                 top = ztest_random(rvd->vdev_children);
1017                 tvd = rvd->vdev_child[top];
1018         } while (tvd->vdev_ishole || (tvd->vdev_islog && !log_ok) ||
1019             tvd->vdev_mg == NULL || tvd->vdev_mg->mg_class == NULL);
1020 
1021         return (top);
1022 }
1023 
1024 static uint64_t
1025 ztest_random_dsl_prop(zfs_prop_t prop)
1026 {
1027         uint64_t value;
1028 
1029         do {
1030                 value = zfs_prop_random_value(prop, ztest_random(-1ULL));
1031         } while (prop == ZFS_PROP_CHECKSUM && value == ZIO_CHECKSUM_OFF);
1032 
1033         return (value);
1034 }
1035 
1036 static int
1037 ztest_dsl_prop_set_uint64(char *osname, zfs_prop_t prop, uint64_t value,
1038     boolean_t inherit)
1039 {
1040         const char *propname = zfs_prop_to_name(prop);
1041         const char *valname;
1042         char setpoint[MAXPATHLEN];
1043         uint64_t curval;
1044         int error;
1045 
1046         error = dsl_prop_set_int(osname, propname,
1047             (inherit ? ZPROP_SRC_NONE : ZPROP_SRC_LOCAL), value);
1048 
1049         if (error == ENOSPC) {
1050                 ztest_record_enospc(FTAG);
1051                 return (error);
1052         }
1053         ASSERT0(error);
1054 
1055         VERIFY0(dsl_prop_get_integer(osname, propname, &curval, setpoint));
1056 
1057         if (ztest_opts.zo_verbose >= 6) {
1058                 VERIFY(zfs_prop_index_to_string(prop, curval, &valname) == 0);
1059                 (void) printf("%s %s = %s at '%s'\n",
1060                     osname, propname, valname, setpoint);
1061         }
1062 
1063         return (error);
1064 }
1065 
1066 static int
1067 ztest_spa_prop_set_uint64(zpool_prop_t prop, uint64_t value)
1068 {
1069         spa_t *spa = ztest_spa;
1070         nvlist_t *props = NULL;
1071         int error;
1072 
1073         VERIFY(nvlist_alloc(&props, NV_UNIQUE_NAME, 0) == 0);
1074         VERIFY(nvlist_add_uint64(props, zpool_prop_to_name(prop), value) == 0);
1075 
1076         error = spa_prop_set(spa, props);
1077 
1078         nvlist_free(props);
1079 
1080         if (error == ENOSPC) {
1081                 ztest_record_enospc(FTAG);
1082                 return (error);
1083         }
1084         ASSERT0(error);
1085 
1086         return (error);
1087 }
1088 
1089 static void
1090 ztest_rll_init(rll_t *rll)
1091 {
1092         rll->rll_writer = NULL;
1093         rll->rll_readers = 0;
1094         mutex_init(&rll->rll_lock, NULL, USYNC_THREAD, NULL);
1095         cv_init(&rll->rll_cv, NULL, USYNC_THREAD, NULL);
1096 }
1097 
1098 static void
1099 ztest_rll_destroy(rll_t *rll)
1100 {
1101         ASSERT(rll->rll_writer == NULL);
1102         ASSERT(rll->rll_readers == 0);
1103         mutex_destroy(&rll->rll_lock);
1104         cv_destroy(&rll->rll_cv);
1105 }
1106 
1107 static void
1108 ztest_rll_lock(rll_t *rll, rl_type_t type)
1109 {
1110         mutex_enter(&rll->rll_lock);
1111 
1112         if (type == RL_READER) {
1113                 while (rll->rll_writer != NULL)
1114                         cv_wait(&rll->rll_cv, &rll->rll_lock);
1115                 rll->rll_readers++;
1116         } else {
1117                 while (rll->rll_writer != NULL || rll->rll_readers)
1118                         cv_wait(&rll->rll_cv, &rll->rll_lock);
1119                 rll->rll_writer = curthread;
1120         }
1121 
1122         mutex_exit(&rll->rll_lock);
1123 }
1124 
1125 static void
1126 ztest_rll_unlock(rll_t *rll)
1127 {
1128         mutex_enter(&rll->rll_lock);
1129 
1130         if (rll->rll_writer) {
1131                 ASSERT(rll->rll_readers == 0);
1132                 rll->rll_writer = NULL;
1133         } else {
1134                 ASSERT(rll->rll_readers != 0);
1135                 ASSERT(rll->rll_writer == NULL);
1136                 rll->rll_readers--;
1137         }
1138 
1139         if (rll->rll_writer == NULL && rll->rll_readers == 0)
1140                 cv_broadcast(&rll->rll_cv);
1141 
1142         mutex_exit(&rll->rll_lock);
1143 }
1144 
1145 static void
1146 ztest_object_lock(ztest_ds_t *zd, uint64_t object, rl_type_t type)
1147 {
1148         rll_t *rll = &zd->zd_object_lock[object & (ZTEST_OBJECT_LOCKS - 1)];
1149 
1150         ztest_rll_lock(rll, type);
1151 }
1152 
1153 static void
1154 ztest_object_unlock(ztest_ds_t *zd, uint64_t object)
1155 {
1156         rll_t *rll = &zd->zd_object_lock[object & (ZTEST_OBJECT_LOCKS - 1)];
1157 
1158         ztest_rll_unlock(rll);
1159 }
1160 
1161 static rl_t *
1162 ztest_range_lock(ztest_ds_t *zd, uint64_t object, uint64_t offset,
1163     uint64_t size, rl_type_t type)
1164 {
1165         uint64_t hash = object ^ (offset % (ZTEST_RANGE_LOCKS + 1));
1166         rll_t *rll = &zd->zd_range_lock[hash & (ZTEST_RANGE_LOCKS - 1)];
1167         rl_t *rl;
1168 
1169         rl = umem_alloc(sizeof (*rl), UMEM_NOFAIL);
1170         rl->rl_object = object;
1171         rl->rl_offset = offset;
1172         rl->rl_size = size;
1173         rl->rl_lock = rll;
1174 
1175         ztest_rll_lock(rll, type);
1176 
1177         return (rl);
1178 }
1179 
1180 static void
1181 ztest_range_unlock(rl_t *rl)
1182 {
1183         rll_t *rll = rl->rl_lock;
1184 
1185         ztest_rll_unlock(rll);
1186 
1187         umem_free(rl, sizeof (*rl));
1188 }
1189 
1190 static void
1191 ztest_zd_init(ztest_ds_t *zd, ztest_shared_ds_t *szd, objset_t *os)
1192 {
1193         zd->zd_os = os;
1194         zd->zd_zilog = dmu_objset_zil(os);
1195         zd->zd_shared = szd;
1196         dmu_objset_name(os, zd->zd_name);
1197 
1198         if (zd->zd_shared != NULL)
1199                 zd->zd_shared->zd_seq = 0;
1200 
1201         rw_init(&zd->zd_zilog_lock, NULL, USYNC_THREAD, NULL);
1202         mutex_init(&zd->zd_dirobj_lock, NULL, USYNC_THREAD, NULL);
1203 
1204         for (int l = 0; l < ZTEST_OBJECT_LOCKS; l++)
1205                 ztest_rll_init(&zd->zd_object_lock[l]);
1206 
1207         for (int l = 0; l < ZTEST_RANGE_LOCKS; l++)
1208                 ztest_rll_init(&zd->zd_range_lock[l]);
1209 }
1210 
1211 static void
1212 ztest_zd_fini(ztest_ds_t *zd)
1213 {
1214         mutex_destroy(&zd->zd_dirobj_lock);
1215 
1216         for (int l = 0; l < ZTEST_OBJECT_LOCKS; l++)
1217                 ztest_rll_destroy(&zd->zd_object_lock[l]);
1218 
1219         for (int l = 0; l < ZTEST_RANGE_LOCKS; l++)
1220                 ztest_rll_destroy(&zd->zd_range_lock[l]);
1221 }
1222 
1223 #define TXG_MIGHTWAIT   (ztest_random(10) == 0 ? TXG_NOWAIT : TXG_WAIT)
1224 
1225 static uint64_t
1226 ztest_tx_assign(dmu_tx_t *tx, uint64_t txg_how, const char *tag)
1227 {
1228         uint64_t txg;
1229         int error;
1230 
1231         /*
1232          * Attempt to assign tx to some transaction group.
1233          */
1234         error = dmu_tx_assign(tx, txg_how);
1235         if (error) {
1236                 if (error == ERESTART) {
1237                         ASSERT(txg_how == TXG_NOWAIT);
1238                         dmu_tx_wait(tx);
1239                 } else {
1240                         ASSERT3U(error, ==, ENOSPC);
1241                         ztest_record_enospc(tag);
1242                 }
1243                 dmu_tx_abort(tx);
1244                 return (0);
1245         }
1246         txg = dmu_tx_get_txg(tx);
1247         ASSERT(txg != 0);
1248         return (txg);
1249 }
1250 
1251 static void
1252 ztest_pattern_set(void *buf, uint64_t size, uint64_t value)
1253 {
1254         uint64_t *ip = buf;
1255         uint64_t *ip_end = (uint64_t *)((uintptr_t)buf + (uintptr_t)size);
1256 
1257         while (ip < ip_end)
1258                 *ip++ = value;
1259 }
1260 
1261 static boolean_t
1262 ztest_pattern_match(void *buf, uint64_t size, uint64_t value)
1263 {
1264         uint64_t *ip = buf;
1265         uint64_t *ip_end = (uint64_t *)((uintptr_t)buf + (uintptr_t)size);
1266         uint64_t diff = 0;
1267 
1268         while (ip < ip_end)
1269                 diff |= (value - *ip++);
1270 
1271         return (diff == 0);
1272 }
1273 
1274 static void
1275 ztest_bt_generate(ztest_block_tag_t *bt, objset_t *os, uint64_t object,
1276     uint64_t offset, uint64_t gen, uint64_t txg, uint64_t crtxg)
1277 {
1278         bt->bt_magic = BT_MAGIC;
1279         bt->bt_objset = dmu_objset_id(os);
1280         bt->bt_object = object;
1281         bt->bt_offset = offset;
1282         bt->bt_gen = gen;
1283         bt->bt_txg = txg;
1284         bt->bt_crtxg = crtxg;
1285 }
1286 
1287 static void
1288 ztest_bt_verify(ztest_block_tag_t *bt, objset_t *os, uint64_t object,
1289     uint64_t offset, uint64_t gen, uint64_t txg, uint64_t crtxg)
1290 {
1291         ASSERT3U(bt->bt_magic, ==, BT_MAGIC);
1292         ASSERT3U(bt->bt_objset, ==, dmu_objset_id(os));
1293         ASSERT3U(bt->bt_object, ==, object);
1294         ASSERT3U(bt->bt_offset, ==, offset);
1295         ASSERT3U(bt->bt_gen, <=, gen);
1296         ASSERT3U(bt->bt_txg, <=, txg);
1297         ASSERT3U(bt->bt_crtxg, ==, crtxg);
1298 }
1299 
1300 static ztest_block_tag_t *
1301 ztest_bt_bonus(dmu_buf_t *db)
1302 {
1303         dmu_object_info_t doi;
1304         ztest_block_tag_t *bt;
1305 
1306         dmu_object_info_from_db(db, &doi);
1307         ASSERT3U(doi.doi_bonus_size, <=, db->db_size);
1308         ASSERT3U(doi.doi_bonus_size, >=, sizeof (*bt));
1309         bt = (void *)((char *)db->db_data + doi.doi_bonus_size - sizeof (*bt));
1310 
1311         return (bt);
1312 }
1313 
1314 /*
1315  * ZIL logging ops
1316  */
1317 
1318 #define lrz_type        lr_mode
1319 #define lrz_blocksize   lr_uid
1320 #define lrz_ibshift     lr_gid
1321 #define lrz_bonustype   lr_rdev
1322 #define lrz_bonuslen    lr_crtime[1]
1323 
1324 static void
1325 ztest_log_create(ztest_ds_t *zd, dmu_tx_t *tx, lr_create_t *lr)
1326 {
1327         char *name = (void *)(lr + 1);          /* name follows lr */
1328         size_t namesize = strlen(name) + 1;
1329         itx_t *itx;
1330 
1331         if (zil_replaying(zd->zd_zilog, tx))
1332                 return;
1333 
1334         itx = zil_itx_create(TX_CREATE, sizeof (*lr) + namesize);
1335         bcopy(&lr->lr_common + 1, &itx->itx_lr + 1,
1336             sizeof (*lr) + namesize - sizeof (lr_t));
1337 
1338         zil_itx_assign(zd->zd_zilog, itx, tx);
1339 }
1340 
1341 static void
1342 ztest_log_remove(ztest_ds_t *zd, dmu_tx_t *tx, lr_remove_t *lr, uint64_t object)
1343 {
1344         char *name = (void *)(lr + 1);          /* name follows lr */
1345         size_t namesize = strlen(name) + 1;
1346         itx_t *itx;
1347 
1348         if (zil_replaying(zd->zd_zilog, tx))
1349                 return;
1350 
1351         itx = zil_itx_create(TX_REMOVE, sizeof (*lr) + namesize);
1352         bcopy(&lr->lr_common + 1, &itx->itx_lr + 1,
1353             sizeof (*lr) + namesize - sizeof (lr_t));
1354 
1355         itx->itx_oid = object;
1356         zil_itx_assign(zd->zd_zilog, itx, tx);
1357 }
1358 
1359 static void
1360 ztest_log_write(ztest_ds_t *zd, dmu_tx_t *tx, lr_write_t *lr)
1361 {
1362         itx_t *itx;
1363         itx_wr_state_t write_state = ztest_random(WR_NUM_STATES);
1364 
1365         if (zil_replaying(zd->zd_zilog, tx))
1366                 return;
1367 
1368         if (lr->lr_length > ZIL_MAX_LOG_DATA)
1369                 write_state = WR_INDIRECT;
1370 
1371         itx = zil_itx_create(TX_WRITE,
1372             sizeof (*lr) + (write_state == WR_COPIED ? lr->lr_length : 0));
1373 
1374         if (write_state == WR_COPIED &&
1375             dmu_read(zd->zd_os, lr->lr_foid, lr->lr_offset, lr->lr_length,
1376             ((lr_write_t *)&itx->itx_lr) + 1, DMU_READ_NO_PREFETCH) != 0) {
1377                 zil_itx_destroy(itx);
1378                 itx = zil_itx_create(TX_WRITE, sizeof (*lr));
1379                 write_state = WR_NEED_COPY;
1380         }
1381         itx->itx_private = zd;
1382         itx->itx_wr_state = write_state;
1383         itx->itx_sync = (ztest_random(8) == 0);
1384 
1385         bcopy(&lr->lr_common + 1, &itx->itx_lr + 1,
1386             sizeof (*lr) - sizeof (lr_t));
1387 
1388         zil_itx_assign(zd->zd_zilog, itx, tx);
1389 }
1390 
1391 static void
1392 ztest_log_truncate(ztest_ds_t *zd, dmu_tx_t *tx, lr_truncate_t *lr)
1393 {
1394         itx_t *itx;
1395 
1396         if (zil_replaying(zd->zd_zilog, tx))
1397                 return;
1398 
1399         itx = zil_itx_create(TX_TRUNCATE, sizeof (*lr));
1400         bcopy(&lr->lr_common + 1, &itx->itx_lr + 1,
1401             sizeof (*lr) - sizeof (lr_t));
1402 
1403         itx->itx_sync = B_FALSE;
1404         zil_itx_assign(zd->zd_zilog, itx, tx);
1405 }
1406 
1407 static void
1408 ztest_log_setattr(ztest_ds_t *zd, dmu_tx_t *tx, lr_setattr_t *lr)
1409 {
1410         itx_t *itx;
1411 
1412         if (zil_replaying(zd->zd_zilog, tx))
1413                 return;
1414 
1415         itx = zil_itx_create(TX_SETATTR, sizeof (*lr));
1416         bcopy(&lr->lr_common + 1, &itx->itx_lr + 1,
1417             sizeof (*lr) - sizeof (lr_t));
1418 
1419         itx->itx_sync = B_FALSE;
1420         zil_itx_assign(zd->zd_zilog, itx, tx);
1421 }
1422 
1423 /*
1424  * ZIL replay ops
1425  */
1426 static int
1427 ztest_replay_create(void *arg1, void *arg2, boolean_t byteswap)
1428 {
1429         ztest_ds_t *zd = arg1;
1430         lr_create_t *lr = arg2;
1431         char *name = (void *)(lr + 1);          /* name follows lr */
1432         objset_t *os = zd->zd_os;
1433         ztest_block_tag_t *bbt;
1434         dmu_buf_t *db;
1435         dmu_tx_t *tx;
1436         uint64_t txg;
1437         int error = 0;
1438 
1439         if (byteswap)
1440                 byteswap_uint64_array(lr, sizeof (*lr));
1441 
1442         ASSERT(lr->lr_doid == ZTEST_DIROBJ);
1443         ASSERT(name[0] != '\0');
1444 
1445         tx = dmu_tx_create(os);
1446 
1447         dmu_tx_hold_zap(tx, lr->lr_doid, B_TRUE, name);
1448 
1449         if (lr->lrz_type == DMU_OT_ZAP_OTHER) {
1450                 dmu_tx_hold_zap(tx, DMU_NEW_OBJECT, B_TRUE, NULL);
1451         } else {
1452                 dmu_tx_hold_bonus(tx, DMU_NEW_OBJECT);
1453         }
1454 
1455         txg = ztest_tx_assign(tx, TXG_WAIT, FTAG);
1456         if (txg == 0)
1457                 return (ENOSPC);
1458 
1459         ASSERT(dmu_objset_zil(os)->zl_replay == !!lr->lr_foid);
1460 
1461         if (lr->lrz_type == DMU_OT_ZAP_OTHER) {
1462                 if (lr->lr_foid == 0) {
1463                         lr->lr_foid = zap_create(os,
1464                             lr->lrz_type, lr->lrz_bonustype,
1465                             lr->lrz_bonuslen, tx);
1466                 } else {
1467                         error = zap_create_claim(os, lr->lr_foid,
1468                             lr->lrz_type, lr->lrz_bonustype,
1469                             lr->lrz_bonuslen, tx);
1470                 }
1471         } else {
1472                 if (lr->lr_foid == 0) {
1473                         lr->lr_foid = dmu_object_alloc(os,
1474                             lr->lrz_type, 0, lr->lrz_bonustype,
1475                             lr->lrz_bonuslen, tx);
1476                 } else {
1477                         error = dmu_object_claim(os, lr->lr_foid,
1478                             lr->lrz_type, 0, lr->lrz_bonustype,
1479                             lr->lrz_bonuslen, tx);
1480                 }
1481         }
1482 
1483         if (error) {
1484                 ASSERT3U(error, ==, EEXIST);
1485                 ASSERT(zd->zd_zilog->zl_replay);
1486                 dmu_tx_commit(tx);
1487                 return (error);
1488         }
1489 
1490         ASSERT(lr->lr_foid != 0);
1491 
1492         if (lr->lrz_type != DMU_OT_ZAP_OTHER)
1493                 VERIFY3U(0, ==, dmu_object_set_blocksize(os, lr->lr_foid,
1494                     lr->lrz_blocksize, lr->lrz_ibshift, tx));
1495 
1496         VERIFY3U(0, ==, dmu_bonus_hold(os, lr->lr_foid, FTAG, &db));
1497         bbt = ztest_bt_bonus(db);
1498         dmu_buf_will_dirty(db, tx);
1499         ztest_bt_generate(bbt, os, lr->lr_foid, -1ULL, lr->lr_gen, txg, txg);
1500         dmu_buf_rele(db, FTAG);
1501 
1502         VERIFY3U(0, ==, zap_add(os, lr->lr_doid, name, sizeof (uint64_t), 1,
1503             &lr->lr_foid, tx));
1504 
1505         (void) ztest_log_create(zd, tx, lr);
1506 
1507         dmu_tx_commit(tx);
1508 
1509         return (0);
1510 }
1511 
1512 static int
1513 ztest_replay_remove(void *arg1, void *arg2, boolean_t byteswap)
1514 {
1515         ztest_ds_t *zd = arg1;
1516         lr_remove_t *lr = arg2;
1517         char *name = (void *)(lr + 1);          /* name follows lr */
1518         objset_t *os = zd->zd_os;
1519         dmu_object_info_t doi;
1520         dmu_tx_t *tx;
1521         uint64_t object, txg;
1522 
1523         if (byteswap)
1524                 byteswap_uint64_array(lr, sizeof (*lr));
1525 
1526         ASSERT(lr->lr_doid == ZTEST_DIROBJ);
1527         ASSERT(name[0] != '\0');
1528 
1529         VERIFY3U(0, ==,
1530             zap_lookup(os, lr->lr_doid, name, sizeof (object), 1, &object));
1531         ASSERT(object != 0);
1532 
1533         ztest_object_lock(zd, object, RL_WRITER);
1534 
1535         VERIFY3U(0, ==, dmu_object_info(os, object, &doi));
1536 
1537         tx = dmu_tx_create(os);
1538 
1539         dmu_tx_hold_zap(tx, lr->lr_doid, B_FALSE, name);
1540         dmu_tx_hold_free(tx, object, 0, DMU_OBJECT_END);
1541 
1542         txg = ztest_tx_assign(tx, TXG_WAIT, FTAG);
1543         if (txg == 0) {
1544                 ztest_object_unlock(zd, object);
1545                 return (ENOSPC);
1546         }
1547 
1548         if (doi.doi_type == DMU_OT_ZAP_OTHER) {
1549                 VERIFY3U(0, ==, zap_destroy(os, object, tx));
1550         } else {
1551                 VERIFY3U(0, ==, dmu_object_free(os, object, tx));
1552         }
1553 
1554         VERIFY3U(0, ==, zap_remove(os, lr->lr_doid, name, tx));
1555 
1556         (void) ztest_log_remove(zd, tx, lr, object);
1557 
1558         dmu_tx_commit(tx);
1559 
1560         ztest_object_unlock(zd, object);
1561 
1562         return (0);
1563 }
1564 
1565 static int
1566 ztest_replay_write(void *arg1, void *arg2, boolean_t byteswap)
1567 {
1568         ztest_ds_t *zd = arg1;
1569         lr_write_t *lr = arg2;
1570         objset_t *os = zd->zd_os;
1571         void *data = lr + 1;                    /* data follows lr */
1572         uint64_t offset, length;
1573         ztest_block_tag_t *bt = data;
1574         ztest_block_tag_t *bbt;
1575         uint64_t gen, txg, lrtxg, crtxg;
1576         dmu_object_info_t doi;
1577         dmu_tx_t *tx;
1578         dmu_buf_t *db;
1579         arc_buf_t *abuf = NULL;
1580         rl_t *rl;
1581 
1582         if (byteswap)
1583                 byteswap_uint64_array(lr, sizeof (*lr));
1584 
1585         offset = lr->lr_offset;
1586         length = lr->lr_length;
1587 
1588         /* If it's a dmu_sync() block, write the whole block */
1589         if (lr->lr_common.lrc_reclen == sizeof (lr_write_t)) {
1590                 uint64_t blocksize = BP_GET_LSIZE(&lr->lr_blkptr);
1591                 if (length < blocksize) {
1592                         offset -= offset % blocksize;
1593                         length = blocksize;
1594                 }
1595         }
1596 
1597         if (bt->bt_magic == BSWAP_64(BT_MAGIC))
1598                 byteswap_uint64_array(bt, sizeof (*bt));
1599 
1600         if (bt->bt_magic != BT_MAGIC)
1601                 bt = NULL;
1602 
1603         ztest_object_lock(zd, lr->lr_foid, RL_READER);
1604         rl = ztest_range_lock(zd, lr->lr_foid, offset, length, RL_WRITER);
1605 
1606         VERIFY3U(0, ==, dmu_bonus_hold(os, lr->lr_foid, FTAG, &db));
1607 
1608         dmu_object_info_from_db(db, &doi);
1609 
1610         bbt = ztest_bt_bonus(db);
1611         ASSERT3U(bbt->bt_magic, ==, BT_MAGIC);
1612         gen = bbt->bt_gen;
1613         crtxg = bbt->bt_crtxg;
1614         lrtxg = lr->lr_common.lrc_txg;
1615 
1616         tx = dmu_tx_create(os);
1617 
1618         dmu_tx_hold_write(tx, lr->lr_foid, offset, length);
1619 
1620         if (ztest_random(8) == 0 && length == doi.doi_data_block_size &&
1621             P2PHASE(offset, length) == 0)
1622                 abuf = dmu_request_arcbuf(db, length);
1623 
1624         txg = ztest_tx_assign(tx, TXG_WAIT, FTAG);
1625         if (txg == 0) {
1626                 if (abuf != NULL)
1627                         dmu_return_arcbuf(abuf);
1628                 dmu_buf_rele(db, FTAG);
1629                 ztest_range_unlock(rl);
1630                 ztest_object_unlock(zd, lr->lr_foid);
1631                 return (ENOSPC);
1632         }
1633 
1634         if (bt != NULL) {
1635                 /*
1636                  * Usually, verify the old data before writing new data --
1637                  * but not always, because we also want to verify correct
1638                  * behavior when the data was not recently read into cache.
1639                  */
1640                 ASSERT(offset % doi.doi_data_block_size == 0);
1641                 if (ztest_random(4) != 0) {
1642                         int prefetch = ztest_random(2) ?
1643                             DMU_READ_PREFETCH : DMU_READ_NO_PREFETCH;
1644                         ztest_block_tag_t rbt;
1645 
1646                         VERIFY(dmu_read(os, lr->lr_foid, offset,
1647                             sizeof (rbt), &rbt, prefetch) == 0);
1648                         if (rbt.bt_magic == BT_MAGIC) {
1649                                 ztest_bt_verify(&rbt, os, lr->lr_foid,
1650                                     offset, gen, txg, crtxg);
1651                         }
1652                 }
1653 
1654                 /*
1655                  * Writes can appear to be newer than the bonus buffer because
1656                  * the ztest_get_data() callback does a dmu_read() of the
1657                  * open-context data, which may be different than the data
1658                  * as it was when the write was generated.
1659                  */
1660                 if (zd->zd_zilog->zl_replay) {
1661                         ztest_bt_verify(bt, os, lr->lr_foid, offset,
1662                             MAX(gen, bt->bt_gen), MAX(txg, lrtxg),
1663                             bt->bt_crtxg);
1664                 }
1665 
1666                 /*
1667                  * Set the bt's gen/txg to the bonus buffer's gen/txg
1668                  * so that all of the usual ASSERTs will work.
1669                  */
1670                 ztest_bt_generate(bt, os, lr->lr_foid, offset, gen, txg, crtxg);
1671         }
1672 
1673         if (abuf == NULL) {
1674                 dmu_write(os, lr->lr_foid, offset, length, data, tx);
1675         } else {
1676                 bcopy(data, abuf->b_data, length);
1677                 dmu_assign_arcbuf(db, offset, abuf, tx);
1678         }
1679 
1680         (void) ztest_log_write(zd, tx, lr);
1681 
1682         dmu_buf_rele(db, FTAG);
1683 
1684         dmu_tx_commit(tx);
1685 
1686         ztest_range_unlock(rl);
1687         ztest_object_unlock(zd, lr->lr_foid);
1688 
1689         return (0);
1690 }
1691 
1692 static int
1693 ztest_replay_truncate(void *arg1, void *arg2, boolean_t byteswap)
1694 {
1695         ztest_ds_t *zd = arg1;
1696         lr_truncate_t *lr = arg2;
1697         objset_t *os = zd->zd_os;
1698         dmu_tx_t *tx;
1699         uint64_t txg;
1700         rl_t *rl;
1701 
1702         if (byteswap)
1703                 byteswap_uint64_array(lr, sizeof (*lr));
1704 
1705         ztest_object_lock(zd, lr->lr_foid, RL_READER);
1706         rl = ztest_range_lock(zd, lr->lr_foid, lr->lr_offset, lr->lr_length,
1707             RL_WRITER);
1708 
1709         tx = dmu_tx_create(os);
1710 
1711         dmu_tx_hold_free(tx, lr->lr_foid, lr->lr_offset, lr->lr_length);
1712 
1713         txg = ztest_tx_assign(tx, TXG_WAIT, FTAG);
1714         if (txg == 0) {
1715                 ztest_range_unlock(rl);
1716                 ztest_object_unlock(zd, lr->lr_foid);
1717                 return (ENOSPC);
1718         }
1719 
1720         VERIFY(dmu_free_range(os, lr->lr_foid, lr->lr_offset,
1721             lr->lr_length, tx) == 0);
1722 
1723         (void) ztest_log_truncate(zd, tx, lr);
1724 
1725         dmu_tx_commit(tx);
1726 
1727         ztest_range_unlock(rl);
1728         ztest_object_unlock(zd, lr->lr_foid);
1729 
1730         return (0);
1731 }
1732 
1733 static int
1734 ztest_replay_setattr(void *arg1, void *arg2, boolean_t byteswap)
1735 {
1736         ztest_ds_t *zd = arg1;
1737         lr_setattr_t *lr = arg2;
1738         objset_t *os = zd->zd_os;
1739         dmu_tx_t *tx;
1740         dmu_buf_t *db;
1741         ztest_block_tag_t *bbt;
1742         uint64_t txg, lrtxg, crtxg;
1743 
1744         if (byteswap)
1745                 byteswap_uint64_array(lr, sizeof (*lr));
1746 
1747         ztest_object_lock(zd, lr->lr_foid, RL_WRITER);
1748 
1749         VERIFY3U(0, ==, dmu_bonus_hold(os, lr->lr_foid, FTAG, &db));
1750 
1751         tx = dmu_tx_create(os);
1752         dmu_tx_hold_bonus(tx, lr->lr_foid);
1753 
1754         txg = ztest_tx_assign(tx, TXG_WAIT, FTAG);
1755         if (txg == 0) {
1756                 dmu_buf_rele(db, FTAG);
1757                 ztest_object_unlock(zd, lr->lr_foid);
1758                 return (ENOSPC);
1759         }
1760 
1761         bbt = ztest_bt_bonus(db);
1762         ASSERT3U(bbt->bt_magic, ==, BT_MAGIC);
1763         crtxg = bbt->bt_crtxg;
1764         lrtxg = lr->lr_common.lrc_txg;
1765 
1766         if (zd->zd_zilog->zl_replay) {
1767                 ASSERT(lr->lr_size != 0);
1768                 ASSERT(lr->lr_mode != 0);
1769                 ASSERT(lrtxg != 0);
1770         } else {
1771                 /*
1772                  * Randomly change the size and increment the generation.
1773                  */
1774                 lr->lr_size = (ztest_random(db->db_size / sizeof (*bbt)) + 1) *
1775                     sizeof (*bbt);
1776                 lr->lr_mode = bbt->bt_gen + 1;
1777                 ASSERT(lrtxg == 0);
1778         }
1779 
1780         /*
1781          * Verify that the current bonus buffer is not newer than our txg.
1782          */
1783         ztest_bt_verify(bbt, os, lr->lr_foid, -1ULL, lr->lr_mode,
1784             MAX(txg, lrtxg), crtxg);
1785 
1786         dmu_buf_will_dirty(db, tx);
1787 
1788         ASSERT3U(lr->lr_size, >=, sizeof (*bbt));
1789         ASSERT3U(lr->lr_size, <=, db->db_size);
1790         VERIFY0(dmu_set_bonus(db, lr->lr_size, tx));
1791         bbt = ztest_bt_bonus(db);
1792 
1793         ztest_bt_generate(bbt, os, lr->lr_foid, -1ULL, lr->lr_mode, txg, crtxg);
1794 
1795         dmu_buf_rele(db, FTAG);
1796 
1797         (void) ztest_log_setattr(zd, tx, lr);
1798 
1799         dmu_tx_commit(tx);
1800 
1801         ztest_object_unlock(zd, lr->lr_foid);
1802 
1803         return (0);
1804 }
1805 
1806 zil_replay_func_t *ztest_replay_vector[TX_MAX_TYPE] = {
1807         NULL,                   /* 0 no such transaction type */
1808         ztest_replay_create,    /* TX_CREATE */
1809         NULL,                   /* TX_MKDIR */
1810         NULL,                   /* TX_MKXATTR */
1811         NULL,                   /* TX_SYMLINK */
1812         ztest_replay_remove,    /* TX_REMOVE */
1813         NULL,                   /* TX_RMDIR */
1814         NULL,                   /* TX_LINK */
1815         NULL,                   /* TX_RENAME */
1816         ztest_replay_write,     /* TX_WRITE */
1817         ztest_replay_truncate,  /* TX_TRUNCATE */
1818         ztest_replay_setattr,   /* TX_SETATTR */
1819         NULL,                   /* TX_ACL */
1820         NULL,                   /* TX_CREATE_ACL */
1821         NULL,                   /* TX_CREATE_ATTR */
1822         NULL,                   /* TX_CREATE_ACL_ATTR */
1823         NULL,                   /* TX_MKDIR_ACL */
1824         NULL,                   /* TX_MKDIR_ATTR */
1825         NULL,                   /* TX_MKDIR_ACL_ATTR */
1826         NULL,                   /* TX_WRITE2 */
1827 };
1828 
1829 /*
1830  * ZIL get_data callbacks
1831  */
1832 
1833 static void
1834 ztest_get_done(zgd_t *zgd, int error)
1835 {
1836         ztest_ds_t *zd = zgd->zgd_private;
1837         uint64_t object = zgd->zgd_rl->rl_object;
1838 
1839         if (zgd->zgd_db)
1840                 dmu_buf_rele(zgd->zgd_db, zgd);
1841 
1842         ztest_range_unlock(zgd->zgd_rl);
1843         ztest_object_unlock(zd, object);
1844 
1845         if (error == 0 && zgd->zgd_bp)
1846                 zil_lwb_add_block(zgd->zgd_lwb, zgd->zgd_bp);
1847 
1848         umem_free(zgd, sizeof (*zgd));
1849 }
1850 
1851 static int
1852 ztest_get_data(void *arg, lr_write_t *lr, char *buf, struct lwb *lwb,
1853     zio_t *zio)
1854 {
1855         ztest_ds_t *zd = arg;
1856         objset_t *os = zd->zd_os;
1857         uint64_t object = lr->lr_foid;
1858         uint64_t offset = lr->lr_offset;
1859         uint64_t size = lr->lr_length;
1860         uint64_t txg = lr->lr_common.lrc_txg;
1861         uint64_t crtxg;
1862         dmu_object_info_t doi;
1863         dmu_buf_t *db;
1864         zgd_t *zgd;
1865         int error;
1866 
1867         ASSERT3P(lwb, !=, NULL);
1868         ASSERT3P(zio, !=, NULL);
1869         ASSERT3U(size, !=, 0);
1870 
1871         ztest_object_lock(zd, object, RL_READER);
1872         error = dmu_bonus_hold(os, object, FTAG, &db);
1873         if (error) {
1874                 ztest_object_unlock(zd, object);
1875                 return (error);
1876         }
1877 
1878         crtxg = ztest_bt_bonus(db)->bt_crtxg;
1879 
1880         if (crtxg == 0 || crtxg > txg) {
1881                 dmu_buf_rele(db, FTAG);
1882                 ztest_object_unlock(zd, object);
1883                 return (ENOENT);
1884         }
1885 
1886         dmu_object_info_from_db(db, &doi);
1887         dmu_buf_rele(db, FTAG);
1888         db = NULL;
1889 
1890         zgd = umem_zalloc(sizeof (*zgd), UMEM_NOFAIL);
1891         zgd->zgd_lwb = lwb;
1892         zgd->zgd_private = zd;
1893 
1894         if (buf != NULL) {      /* immediate write */
1895                 zgd->zgd_rl = ztest_range_lock(zd, object, offset, size,
1896                     RL_READER);
1897 
1898                 error = dmu_read(os, object, offset, size, buf,
1899                     DMU_READ_NO_PREFETCH);
1900                 ASSERT(error == 0);
1901         } else {
1902                 size = doi.doi_data_block_size;
1903                 if (ISP2(size)) {
1904                         offset = P2ALIGN(offset, size);
1905                 } else {
1906                         ASSERT(offset < size);
1907                         offset = 0;
1908                 }
1909 
1910                 zgd->zgd_rl = ztest_range_lock(zd, object, offset, size,
1911                     RL_READER);
1912 
1913                 error = dmu_buf_hold(os, object, offset, zgd, &db,
1914                     DMU_READ_NO_PREFETCH);
1915 
1916                 if (error == 0) {
1917                         blkptr_t *bp = &lr->lr_blkptr;
1918 
1919                         zgd->zgd_db = db;
1920                         zgd->zgd_bp = bp;
1921 
1922                         ASSERT(db->db_offset == offset);
1923                         ASSERT(db->db_size == size);
1924 
1925                         error = dmu_sync(zio, lr->lr_common.lrc_txg,
1926                             ztest_get_done, zgd);
1927 
1928                         if (error == 0)
1929                                 return (0);
1930                 }
1931         }
1932 
1933         ztest_get_done(zgd, error);
1934 
1935         return (error);
1936 }
1937 
1938 static void *
1939 ztest_lr_alloc(size_t lrsize, char *name)
1940 {
1941         char *lr;
1942         size_t namesize = name ? strlen(name) + 1 : 0;
1943 
1944         lr = umem_zalloc(lrsize + namesize, UMEM_NOFAIL);
1945 
1946         if (name)
1947                 bcopy(name, lr + lrsize, namesize);
1948 
1949         return (lr);
1950 }
1951 
1952 void
1953 ztest_lr_free(void *lr, size_t lrsize, char *name)
1954 {
1955         size_t namesize = name ? strlen(name) + 1 : 0;
1956 
1957         umem_free(lr, lrsize + namesize);
1958 }
1959 
1960 /*
1961  * Lookup a bunch of objects.  Returns the number of objects not found.
1962  */
1963 static int
1964 ztest_lookup(ztest_ds_t *zd, ztest_od_t *od, int count)
1965 {
1966         int missing = 0;
1967         int error;
1968 
1969         ASSERT(MUTEX_HELD(&zd->zd_dirobj_lock));
1970 
1971         for (int i = 0; i < count; i++, od++) {
1972                 od->od_object = 0;
1973                 error = zap_lookup(zd->zd_os, od->od_dir, od->od_name,
1974                     sizeof (uint64_t), 1, &od->od_object);
1975                 if (error) {
1976                         ASSERT(error == ENOENT);
1977                         ASSERT(od->od_object == 0);
1978                         missing++;
1979                 } else {
1980                         dmu_buf_t *db;
1981                         ztest_block_tag_t *bbt;
1982                         dmu_object_info_t doi;
1983 
1984                         ASSERT(od->od_object != 0);
1985                         ASSERT(missing == 0);   /* there should be no gaps */
1986 
1987                         ztest_object_lock(zd, od->od_object, RL_READER);
1988                         VERIFY3U(0, ==, dmu_bonus_hold(zd->zd_os,
1989                             od->od_object, FTAG, &db));
1990                         dmu_object_info_from_db(db, &doi);
1991                         bbt = ztest_bt_bonus(db);
1992                         ASSERT3U(bbt->bt_magic, ==, BT_MAGIC);
1993                         od->od_type = doi.doi_type;
1994                         od->od_blocksize = doi.doi_data_block_size;
1995                         od->od_gen = bbt->bt_gen;
1996                         dmu_buf_rele(db, FTAG);
1997                         ztest_object_unlock(zd, od->od_object);
1998                 }
1999         }
2000 
2001         return (missing);
2002 }
2003 
2004 static int
2005 ztest_create(ztest_ds_t *zd, ztest_od_t *od, int count)
2006 {
2007         int missing = 0;
2008 
2009         ASSERT(MUTEX_HELD(&zd->zd_dirobj_lock));
2010 
2011         for (int i = 0; i < count; i++, od++) {
2012                 if (missing) {
2013                         od->od_object = 0;
2014                         missing++;
2015                         continue;
2016                 }
2017 
2018                 lr_create_t *lr = ztest_lr_alloc(sizeof (*lr), od->od_name);
2019 
2020                 lr->lr_doid = od->od_dir;
2021                 lr->lr_foid = 0;     /* 0 to allocate, > 0 to claim */
2022                 lr->lrz_type = od->od_crtype;
2023                 lr->lrz_blocksize = od->od_crblocksize;
2024                 lr->lrz_ibshift = ztest_random_ibshift();
2025                 lr->lrz_bonustype = DMU_OT_UINT64_OTHER;
2026                 lr->lrz_bonuslen = dmu_bonus_max();
2027                 lr->lr_gen = od->od_crgen;
2028                 lr->lr_crtime[0] = time(NULL);
2029 
2030                 if (ztest_replay_create(zd, lr, B_FALSE) != 0) {
2031                         ASSERT(missing == 0);
2032                         od->od_object = 0;
2033                         missing++;
2034                 } else {
2035                         od->od_object = lr->lr_foid;
2036                         od->od_type = od->od_crtype;
2037                         od->od_blocksize = od->od_crblocksize;
2038                         od->od_gen = od->od_crgen;
2039                         ASSERT(od->od_object != 0);
2040                 }
2041 
2042                 ztest_lr_free(lr, sizeof (*lr), od->od_name);
2043         }
2044 
2045         return (missing);
2046 }
2047 
2048 static int
2049 ztest_remove(ztest_ds_t *zd, ztest_od_t *od, int count)
2050 {
2051         int missing = 0;
2052         int error;
2053 
2054         ASSERT(MUTEX_HELD(&zd->zd_dirobj_lock));
2055 
2056         od += count - 1;
2057 
2058         for (int i = count - 1; i >= 0; i--, od--) {
2059                 if (missing) {
2060                         missing++;
2061                         continue;
2062                 }
2063 
2064                 /*
2065                  * No object was found.
2066                  */
2067                 if (od->od_object == 0)
2068                         continue;
2069 
2070                 lr_remove_t *lr = ztest_lr_alloc(sizeof (*lr), od->od_name);
2071 
2072                 lr->lr_doid = od->od_dir;
2073 
2074                 if ((error = ztest_replay_remove(zd, lr, B_FALSE)) != 0) {
2075                         ASSERT3U(error, ==, ENOSPC);
2076                         missing++;
2077                 } else {
2078                         od->od_object = 0;
2079                 }
2080                 ztest_lr_free(lr, sizeof (*lr), od->od_name);
2081         }
2082 
2083         return (missing);
2084 }
2085 
2086 static int
2087 ztest_write(ztest_ds_t *zd, uint64_t object, uint64_t offset, uint64_t size,
2088     void *data)
2089 {
2090         lr_write_t *lr;
2091         int error;
2092 
2093         lr = ztest_lr_alloc(sizeof (*lr) + size, NULL);
2094 
2095         lr->lr_foid = object;
2096         lr->lr_offset = offset;
2097         lr->lr_length = size;
2098         lr->lr_blkoff = 0;
2099         BP_ZERO(&lr->lr_blkptr);
2100 
2101         bcopy(data, lr + 1, size);
2102 
2103         error = ztest_replay_write(zd, lr, B_FALSE);
2104 
2105         ztest_lr_free(lr, sizeof (*lr) + size, NULL);
2106 
2107         return (error);
2108 }
2109 
2110 static int
2111 ztest_truncate(ztest_ds_t *zd, uint64_t object, uint64_t offset, uint64_t size)
2112 {
2113         lr_truncate_t *lr;
2114         int error;
2115 
2116         lr = ztest_lr_alloc(sizeof (*lr), NULL);
2117 
2118         lr->lr_foid = object;
2119         lr->lr_offset = offset;
2120         lr->lr_length = size;
2121 
2122         error = ztest_replay_truncate(zd, lr, B_FALSE);
2123 
2124         ztest_lr_free(lr, sizeof (*lr), NULL);
2125 
2126         return (error);
2127 }
2128 
2129 static int
2130 ztest_setattr(ztest_ds_t *zd, uint64_t object)
2131 {
2132         lr_setattr_t *lr;
2133         int error;
2134 
2135         lr = ztest_lr_alloc(sizeof (*lr), NULL);
2136 
2137         lr->lr_foid = object;
2138         lr->lr_size = 0;
2139         lr->lr_mode = 0;
2140 
2141         error = ztest_replay_setattr(zd, lr, B_FALSE);
2142 
2143         ztest_lr_free(lr, sizeof (*lr), NULL);
2144 
2145         return (error);
2146 }
2147 
2148 static void
2149 ztest_prealloc(ztest_ds_t *zd, uint64_t object, uint64_t offset, uint64_t size)
2150 {
2151         objset_t *os = zd->zd_os;
2152         dmu_tx_t *tx;
2153         uint64_t txg;
2154         rl_t *rl;
2155 
2156         txg_wait_synced(dmu_objset_pool(os), 0);
2157 
2158         ztest_object_lock(zd, object, RL_READER);
2159         rl = ztest_range_lock(zd, object, offset, size, RL_WRITER);
2160 
2161         tx = dmu_tx_create(os);
2162 
2163         dmu_tx_hold_write(tx, object, offset, size);
2164 
2165         txg = ztest_tx_assign(tx, TXG_WAIT, FTAG);
2166 
2167         if (txg != 0) {
2168                 dmu_prealloc(os, object, offset, size, tx);
2169                 dmu_tx_commit(tx);
2170                 txg_wait_synced(dmu_objset_pool(os), txg);
2171         } else {
2172                 (void) dmu_free_long_range(os, object, offset, size);
2173         }
2174 
2175         ztest_range_unlock(rl);
2176         ztest_object_unlock(zd, object);
2177 }
2178 
2179 static void
2180 ztest_io(ztest_ds_t *zd, uint64_t object, uint64_t offset)
2181 {
2182         int err;
2183         ztest_block_tag_t wbt;
2184         dmu_object_info_t doi;
2185         enum ztest_io_type io_type;
2186         uint64_t blocksize;
2187         void *data;
2188 
2189         VERIFY(dmu_object_info(zd->zd_os, object, &doi) == 0);
2190         blocksize = doi.doi_data_block_size;
2191         data = umem_alloc(blocksize, UMEM_NOFAIL);
2192 
2193         /*
2194          * Pick an i/o type at random, biased toward writing block tags.
2195          */
2196         io_type = ztest_random(ZTEST_IO_TYPES);
2197         if (ztest_random(2) == 0)
2198                 io_type = ZTEST_IO_WRITE_TAG;
2199 
2200         rw_enter(&zd->zd_zilog_lock, RW_READER);
2201 
2202         switch (io_type) {
2203 
2204         case ZTEST_IO_WRITE_TAG:
2205                 ztest_bt_generate(&wbt, zd->zd_os, object, offset, 0, 0, 0);
2206                 (void) ztest_write(zd, object, offset, sizeof (wbt), &wbt);
2207                 break;
2208 
2209         case ZTEST_IO_WRITE_PATTERN:
2210                 (void) memset(data, 'a' + (object + offset) % 5, blocksize);
2211                 if (ztest_random(2) == 0) {
2212                         /*
2213                          * Induce fletcher2 collisions to ensure that
2214                          * zio_ddt_collision() detects and resolves them
2215                          * when using fletcher2-verify for deduplication.
2216                          */
2217                         ((uint64_t *)data)[0] ^= 1ULL << 63;
2218                         ((uint64_t *)data)[4] ^= 1ULL << 63;
2219                 }
2220                 (void) ztest_write(zd, object, offset, blocksize, data);
2221                 break;
2222 
2223         case ZTEST_IO_WRITE_ZEROES:
2224                 bzero(data, blocksize);
2225                 (void) ztest_write(zd, object, offset, blocksize, data);
2226                 break;
2227 
2228         case ZTEST_IO_TRUNCATE:
2229                 (void) ztest_truncate(zd, object, offset, blocksize);
2230                 break;
2231 
2232         case ZTEST_IO_SETATTR:
2233                 (void) ztest_setattr(zd, object);
2234                 break;
2235 
2236         case ZTEST_IO_REWRITE:
2237                 rw_enter(&ztest_name_lock, RW_READER);
2238                 err = ztest_dsl_prop_set_uint64(zd->zd_name,
2239                     ZFS_PROP_CHECKSUM, spa_dedup_checksum(ztest_spa),
2240                     B_FALSE);
2241                 VERIFY(err == 0 || err == ENOSPC);
2242                 err = ztest_dsl_prop_set_uint64(zd->zd_name,
2243                     ZFS_PROP_COMPRESSION,
2244                     ztest_random_dsl_prop(ZFS_PROP_COMPRESSION),
2245                     B_FALSE);
2246                 VERIFY(err == 0 || err == ENOSPC);
2247                 rw_exit(&ztest_name_lock);
2248 
2249                 VERIFY0(dmu_read(zd->zd_os, object, offset, blocksize, data,
2250                     DMU_READ_NO_PREFETCH));
2251 
2252                 (void) ztest_write(zd, object, offset, blocksize, data);
2253                 break;
2254         }
2255 
2256         rw_exit(&zd->zd_zilog_lock);
2257 
2258         umem_free(data, blocksize);
2259 }
2260 
2261 /*
2262  * Initialize an object description template.
2263  */
2264 static void
2265 ztest_od_init(ztest_od_t *od, uint64_t id, char *tag, uint64_t index,
2266     dmu_object_type_t type, uint64_t blocksize, uint64_t gen)
2267 {
2268         od->od_dir = ZTEST_DIROBJ;
2269         od->od_object = 0;
2270 
2271         od->od_crtype = type;
2272         od->od_crblocksize = blocksize ? blocksize : ztest_random_blocksize();
2273         od->od_crgen = gen;
2274 
2275         od->od_type = DMU_OT_NONE;
2276         od->od_blocksize = 0;
2277         od->od_gen = 0;
2278 
2279         (void) snprintf(od->od_name, sizeof (od->od_name), "%s(%lld)[%llu]",
2280             tag, (int64_t)id, index);
2281 }
2282 
2283 /*
2284  * Lookup or create the objects for a test using the od template.
2285  * If the objects do not all exist, or if 'remove' is specified,
2286  * remove any existing objects and create new ones.  Otherwise,
2287  * use the existing objects.
2288  */
2289 static int
2290 ztest_object_init(ztest_ds_t *zd, ztest_od_t *od, size_t size, boolean_t remove)
2291 {
2292         int count = size / sizeof (*od);
2293         int rv = 0;
2294 
2295         mutex_enter(&zd->zd_dirobj_lock);
2296         if ((ztest_lookup(zd, od, count) != 0 || remove) &&
2297             (ztest_remove(zd, od, count) != 0 ||
2298             ztest_create(zd, od, count) != 0))
2299                 rv = -1;
2300         zd->zd_od = od;
2301         mutex_exit(&zd->zd_dirobj_lock);
2302 
2303         return (rv);
2304 }
2305 
2306 /* ARGSUSED */
2307 void
2308 ztest_zil_commit(ztest_ds_t *zd, uint64_t id)
2309 {
2310         zilog_t *zilog = zd->zd_zilog;
2311 
2312         rw_enter(&zd->zd_zilog_lock, RW_READER);
2313 
2314         zil_commit(zilog, ztest_random(ZTEST_OBJECTS));
2315 
2316         /*
2317          * Remember the committed values in zd, which is in parent/child
2318          * shared memory.  If we die, the next iteration of ztest_run()
2319          * will verify that the log really does contain this record.
2320          */
2321         mutex_enter(&zilog->zl_lock);
2322         ASSERT(zd->zd_shared != NULL);
2323         ASSERT3U(zd->zd_shared->zd_seq, <=, zilog->zl_commit_lr_seq);
2324         zd->zd_shared->zd_seq = zilog->zl_commit_lr_seq;
2325         mutex_exit(&zilog->zl_lock);
2326 
2327         rw_exit(&zd->zd_zilog_lock);
2328 }
2329 
2330 /*
2331  * This function is designed to simulate the operations that occur during a
2332  * mount/unmount operation.  We hold the dataset across these operations in an
2333  * attempt to expose any implicit assumptions about ZIL management.
2334  */
2335 /* ARGSUSED */
2336 void
2337 ztest_zil_remount(ztest_ds_t *zd, uint64_t id)
2338 {
2339         objset_t *os = zd->zd_os;
2340 
2341         /*
2342          * We grab the zd_dirobj_lock to ensure that no other thread is
2343          * updating the zil (i.e. adding in-memory log records) and the
2344          * zd_zilog_lock to block any I/O.
2345          */
2346         mutex_enter(&zd->zd_dirobj_lock);
2347         rw_enter(&zd->zd_zilog_lock, RW_WRITER);
2348 
2349         /* zfsvfs_teardown() */
2350         zil_close(zd->zd_zilog);
2351 
2352         /* zfsvfs_setup() */
2353         VERIFY(zil_open(os, ztest_get_data) == zd->zd_zilog);
2354         zil_replay(os, zd, ztest_replay_vector);
2355 
2356         rw_exit(&zd->zd_zilog_lock);
2357         mutex_exit(&zd->zd_dirobj_lock);
2358 }
2359 
2360 /*
2361  * Verify that we can't destroy an active pool, create an existing pool,
2362  * or create a pool with a bad vdev spec.
2363  */
2364 /* ARGSUSED */
2365 void
2366 ztest_spa_create_destroy(ztest_ds_t *zd, uint64_t id)
2367 {
2368         ztest_shared_opts_t *zo = &ztest_opts;
2369         spa_t *spa;
2370         nvlist_t *nvroot;
2371 
2372         /*
2373          * Attempt to create using a bad file.
2374          */
2375         nvroot = make_vdev_root("/dev/bogus", NULL, NULL, 0, 0, 0, 0, 0, 1);
2376         VERIFY3U(ENOENT, ==,
2377             spa_create("ztest_bad_file", nvroot, NULL, NULL));
2378         nvlist_free(nvroot);
2379 
2380         /*
2381          * Attempt to create using a bad mirror.
2382          */
2383         nvroot = make_vdev_root("/dev/bogus", NULL, NULL, 0, 0, 0, 0, 2, 1);
2384         VERIFY3U(ENOENT, ==,
2385             spa_create("ztest_bad_mirror", nvroot, NULL, NULL));
2386         nvlist_free(nvroot);
2387 
2388         /*
2389          * Attempt to create an existing pool.  It shouldn't matter
2390          * what's in the nvroot; we should fail with EEXIST.
2391          */
2392         rw_enter(&ztest_name_lock, RW_READER);
2393         nvroot = make_vdev_root("/dev/bogus", NULL, NULL, 0, 0, 0, 0, 0, 1);
2394         VERIFY3U(EEXIST, ==, spa_create(zo->zo_pool, nvroot, NULL, NULL));
2395         nvlist_free(nvroot);
2396         VERIFY3U(0, ==, spa_open(zo->zo_pool, &spa, FTAG));
2397         VERIFY3U(EBUSY, ==, spa_destroy(zo->zo_pool));
2398         spa_close(spa, FTAG);
2399 
2400         rw_exit(&ztest_name_lock);
2401 }
2402 
2403 /* ARGSUSED */
2404 void
2405 ztest_spa_upgrade(ztest_ds_t *zd, uint64_t id)
2406 {
2407         spa_t *spa;
2408         uint64_t initial_version = SPA_VERSION_INITIAL;
2409         uint64_t version, newversion;
2410         nvlist_t *nvroot, *props;
2411         char *name;
2412 
2413         mutex_enter(&ztest_vdev_lock);
2414         name = kmem_asprintf("%s_upgrade", ztest_opts.zo_pool);
2415 
2416         /*
2417          * Clean up from previous runs.
2418          */
2419         (void) spa_destroy(name);
2420 
2421         nvroot = make_vdev_root(NULL, NULL, name, ztest_opts.zo_vdev_size, 0,
2422             0, ztest_opts.zo_raidz, ztest_opts.zo_mirrors, 1);
2423 
2424         /*
2425          * If we're configuring a RAIDZ device then make sure that the
2426          * the initial version is capable of supporting that feature.
2427          */
2428         switch (ztest_opts.zo_raidz_parity) {
2429         case 0:
2430         case 1:
2431                 initial_version = SPA_VERSION_INITIAL;
2432                 break;
2433         case 2:
2434                 initial_version = SPA_VERSION_RAIDZ2;
2435                 break;
2436         case 3:
2437                 initial_version = SPA_VERSION_RAIDZ3;
2438                 break;
2439         }
2440 
2441         /*
2442          * Create a pool with a spa version that can be upgraded. Pick
2443          * a value between initial_version and SPA_VERSION_BEFORE_FEATURES.
2444          */
2445         do {
2446                 version = ztest_random_spa_version(initial_version);
2447         } while (version > SPA_VERSION_BEFORE_FEATURES);
2448 
2449         props = fnvlist_alloc();
2450         fnvlist_add_uint64(props,
2451             zpool_prop_to_name(ZPOOL_PROP_VERSION), version);
2452         VERIFY0(spa_create(name, nvroot, props, NULL));
2453         fnvlist_free(nvroot);
2454         fnvlist_free(props);
2455 
2456         VERIFY0(spa_open(name, &spa, FTAG));
2457         VERIFY3U(spa_version(spa), ==, version);
2458         newversion = ztest_random_spa_version(version + 1);
2459 
2460         if (ztest_opts.zo_verbose >= 4) {
2461                 (void) printf("upgrading spa version from %llu to %llu\n",
2462                     (u_longlong_t)version, (u_longlong_t)newversion);
2463         }
2464 
2465         spa_upgrade(spa, newversion);
2466         VERIFY3U(spa_version(spa), >, version);
2467         VERIFY3U(spa_version(spa), ==, fnvlist_lookup_uint64(spa->spa_config,
2468             zpool_prop_to_name(ZPOOL_PROP_VERSION)));
2469         spa_close(spa, FTAG);
2470 
2471         strfree(name);
2472         mutex_exit(&ztest_vdev_lock);
2473 }
2474 
2475 static vdev_t *
2476 vdev_lookup_by_path(vdev_t *vd, const char *path)
2477 {
2478         vdev_t *mvd;
2479 
2480         if (vd->vdev_path != NULL && strcmp(path, vd->vdev_path) == 0)
2481                 return (vd);
2482 
2483         for (int c = 0; c < vd->vdev_children; c++)
2484                 if ((mvd = vdev_lookup_by_path(vd->vdev_child[c], path)) !=
2485                     NULL)
2486                         return (mvd);
2487 
2488         return (NULL);
2489 }
2490 
2491 /*
2492  * Find the first available hole which can be used as a top-level.
2493  */
2494 int
2495 find_vdev_hole(spa_t *spa)
2496 {
2497         vdev_t *rvd = spa->spa_root_vdev;
2498         int c;
2499 
2500         ASSERT(spa_config_held(spa, SCL_VDEV, RW_READER) == SCL_VDEV);
2501 
2502         for (c = 0; c < rvd->vdev_children; c++) {
2503                 vdev_t *cvd = rvd->vdev_child[c];
2504 
2505                 if (cvd->vdev_ishole)
2506                         break;
2507         }
2508         return (c);
2509 }
2510 
2511 /*
2512  * Verify that vdev_add() works as expected.
2513  */
2514 /* ARGSUSED */
2515 void
2516 ztest_vdev_add_remove(ztest_ds_t *zd, uint64_t id)
2517 {
2518         ztest_shared_t *zs = ztest_shared;
2519         spa_t *spa = ztest_spa;
2520         uint64_t leaves;
2521         uint64_t guid;
2522         nvlist_t *nvroot;
2523         int error;
2524 
2525         mutex_enter(&ztest_vdev_lock);
2526         leaves = MAX(zs->zs_mirrors + zs->zs_splits, 1) * ztest_opts.zo_raidz;
2527 
2528         spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
2529 
2530         ztest_shared->zs_vdev_next_leaf = find_vdev_hole(spa) * leaves;
2531 
2532         /*
2533          * If we have slogs then remove them 1/4 of the time.
2534          */
2535         if (spa_has_slogs(spa) && ztest_random(4) == 0) {
2536                 /*
2537                  * Grab the guid from the head of the log class rotor.
2538                  */
2539                 guid = spa_log_class(spa)->mc_rotor->mg_vd->vdev_guid;
2540 
2541                 spa_config_exit(spa, SCL_VDEV, FTAG);
2542 
2543                 /*
2544                  * We have to grab the zs_name_lock as writer to
2545                  * prevent a race between removing a slog (dmu_objset_find)
2546                  * and destroying a dataset. Removing the slog will
2547                  * grab a reference on the dataset which may cause
2548                  * dmu_objset_destroy() to fail with EBUSY thus
2549                  * leaving the dataset in an inconsistent state.
2550                  */
2551                 rw_enter(&ztest_name_lock, RW_WRITER);
2552                 error = spa_vdev_remove(spa, guid, B_FALSE);
2553                 rw_exit(&ztest_name_lock);
2554 
2555                 if (error && error != EEXIST)
2556                         fatal(0, "spa_vdev_remove() = %d", error);
2557         } else {
2558                 spa_config_exit(spa, SCL_VDEV, FTAG);
2559 
2560                 /*
2561                  * Make 1/4 of the devices be log devices.
2562                  */
2563                 nvroot = make_vdev_root(NULL, NULL, NULL,
2564                     ztest_opts.zo_vdev_size, 0,
2565                     ztest_random(4) == 0, ztest_opts.zo_raidz,
2566                     zs->zs_mirrors, 1);
2567 
2568                 error = spa_vdev_add(spa, nvroot);
2569                 nvlist_free(nvroot);
2570 
2571                 if (error == ENOSPC)
2572                         ztest_record_enospc("spa_vdev_add");
2573                 else if (error != 0)
2574                         fatal(0, "spa_vdev_add() = %d", error);
2575         }
2576 
2577         mutex_exit(&ztest_vdev_lock);
2578 }
2579 
2580 /*
2581  * Verify that adding/removing aux devices (l2arc, hot spare) works as expected.
2582  */
2583 /* ARGSUSED */
2584 void
2585 ztest_vdev_aux_add_remove(ztest_ds_t *zd, uint64_t id)
2586 {
2587         ztest_shared_t *zs = ztest_shared;
2588         spa_t *spa = ztest_spa;
2589         vdev_t *rvd = spa->spa_root_vdev;
2590         spa_aux_vdev_t *sav;
2591         char *aux;
2592         uint64_t guid = 0;
2593         int error;
2594 
2595         if (ztest_random(2) == 0) {
2596                 sav = &spa->spa_spares;
2597                 aux = ZPOOL_CONFIG_SPARES;
2598         } else {
2599                 sav = &spa->spa_l2cache;
2600                 aux = ZPOOL_CONFIG_L2CACHE;
2601         }
2602 
2603         mutex_enter(&ztest_vdev_lock);
2604 
2605         spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
2606 
2607         if (sav->sav_count != 0 && ztest_random(4) == 0) {
2608                 /*
2609                  * Pick a random device to remove.
2610                  */
2611                 guid = sav->sav_vdevs[ztest_random(sav->sav_count)]->vdev_guid;
2612         } else {
2613                 /*
2614                  * Find an unused device we can add.
2615                  */
2616                 zs->zs_vdev_aux = 0;
2617                 for (;;) {
2618                         char path[MAXPATHLEN];
2619                         int c;
2620                         (void) snprintf(path, sizeof (path), ztest_aux_template,
2621                             ztest_opts.zo_dir, ztest_opts.zo_pool, aux,
2622                             zs->zs_vdev_aux);
2623                         for (c = 0; c < sav->sav_count; c++)
2624                                 if (strcmp(sav->sav_vdevs[c]->vdev_path,
2625                                     path) == 0)
2626                                         break;
2627                         if (c == sav->sav_count &&
2628                             vdev_lookup_by_path(rvd, path) == NULL)
2629                                 break;
2630                         zs->zs_vdev_aux++;
2631                 }
2632         }
2633 
2634         spa_config_exit(spa, SCL_VDEV, FTAG);
2635 
2636         if (guid == 0) {
2637                 /*
2638                  * Add a new device.
2639                  */
2640                 nvlist_t *nvroot = make_vdev_root(NULL, aux, NULL,
2641                     (ztest_opts.zo_vdev_size * 5) / 4, 0, 0, 0, 0, 1);
2642                 error = spa_vdev_add(spa, nvroot);
2643                 if (error != 0)
2644                         fatal(0, "spa_vdev_add(%p) = %d", nvroot, error);
2645                 nvlist_free(nvroot);
2646         } else {
2647                 /*
2648                  * Remove an existing device.  Sometimes, dirty its
2649                  * vdev state first to make sure we handle removal
2650                  * of devices that have pending state changes.
2651                  */
2652                 if (ztest_random(2) == 0)
2653                         (void) vdev_online(spa, guid, 0, NULL);
2654 
2655                 error = spa_vdev_remove(spa, guid, B_FALSE);
2656                 if (error != 0 && error != EBUSY)
2657                         fatal(0, "spa_vdev_remove(%llu) = %d", guid, error);
2658         }
2659 
2660         mutex_exit(&ztest_vdev_lock);
2661 }
2662 
2663 /*
2664  * split a pool if it has mirror tlvdevs
2665  */
2666 /* ARGSUSED */
2667 void
2668 ztest_split_pool(ztest_ds_t *zd, uint64_t id)
2669 {
2670         ztest_shared_t *zs = ztest_shared;
2671         spa_t *spa = ztest_spa;
2672         vdev_t *rvd = spa->spa_root_vdev;
2673         nvlist_t *tree, **child, *config, *split, **schild;
2674         uint_t c, children, schildren = 0, lastlogid = 0;
2675         int error = 0;
2676 
2677         mutex_enter(&ztest_vdev_lock);
2678 
2679         /* ensure we have a useable config; mirrors of raidz aren't supported */
2680         if (zs->zs_mirrors < 3 || ztest_opts.zo_raidz > 1) {
2681                 mutex_exit(&ztest_vdev_lock);
2682                 return;
2683         }
2684 
2685         /* clean up the old pool, if any */
2686         (void) spa_destroy("splitp");
2687 
2688         spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
2689 
2690         /* generate a config from the existing config */
2691         mutex_enter(&spa->spa_props_lock);
2692         VERIFY(nvlist_lookup_nvlist(spa->spa_config, ZPOOL_CONFIG_VDEV_TREE,
2693             &tree) == 0);
2694         mutex_exit(&spa->spa_props_lock);
2695 
2696         VERIFY(nvlist_lookup_nvlist_array(tree, ZPOOL_CONFIG_CHILDREN, &child,
2697             &children) == 0);
2698 
2699         schild = malloc(rvd->vdev_children * sizeof (nvlist_t *));
2700         for (c = 0; c < children; c++) {
2701                 vdev_t *tvd = rvd->vdev_child[c];
2702                 nvlist_t **mchild;
2703                 uint_t mchildren;
2704 
2705                 if (tvd->vdev_islog || tvd->vdev_ops == &vdev_hole_ops) {
2706                         VERIFY(nvlist_alloc(&schild[schildren], NV_UNIQUE_NAME,
2707                             0) == 0);
2708                         VERIFY(nvlist_add_string(schild[schildren],
2709                             ZPOOL_CONFIG_TYPE, VDEV_TYPE_HOLE) == 0);
2710                         VERIFY(nvlist_add_uint64(schild[schildren],
2711                             ZPOOL_CONFIG_IS_HOLE, 1) == 0);
2712                         if (lastlogid == 0)
2713                                 lastlogid = schildren;
2714                         ++schildren;
2715                         continue;
2716                 }
2717                 lastlogid = 0;
2718                 VERIFY(nvlist_lookup_nvlist_array(child[c],
2719                     ZPOOL_CONFIG_CHILDREN, &mchild, &mchildren) == 0);
2720                 VERIFY(nvlist_dup(mchild[0], &schild[schildren++], 0) == 0);
2721         }
2722 
2723         /* OK, create a config that can be used to split */
2724         VERIFY(nvlist_alloc(&split, NV_UNIQUE_NAME, 0) == 0);
2725         VERIFY(nvlist_add_string(split, ZPOOL_CONFIG_TYPE,
2726             VDEV_TYPE_ROOT) == 0);
2727         VERIFY(nvlist_add_nvlist_array(split, ZPOOL_CONFIG_CHILDREN, schild,
2728             lastlogid != 0 ? lastlogid : schildren) == 0);
2729 
2730         VERIFY(nvlist_alloc(&config, NV_UNIQUE_NAME, 0) == 0);
2731         VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, split) == 0);
2732 
2733         for (c = 0; c < schildren; c++)
2734                 nvlist_free(schild[c]);
2735         free(schild);
2736         nvlist_free(split);
2737 
2738         spa_config_exit(spa, SCL_VDEV, FTAG);
2739 
2740         rw_enter(&ztest_name_lock, RW_WRITER);
2741         error = spa_vdev_split_mirror(spa, "splitp", config, NULL, B_FALSE);
2742         rw_exit(&ztest_name_lock);
2743 
2744         nvlist_free(config);
2745 
2746         if (error == 0) {
2747                 (void) printf("successful split - results:\n");
2748                 mutex_enter(&spa_namespace_lock);
2749                 show_pool_stats(spa);
2750                 show_pool_stats(spa_lookup("splitp"));
2751                 mutex_exit(&spa_namespace_lock);
2752                 ++zs->zs_splits;
2753                 --zs->zs_mirrors;
2754         }
2755         mutex_exit(&ztest_vdev_lock);
2756 
2757 }
2758 
2759 /*
2760  * Verify that we can attach and detach devices.
2761  */
2762 /* ARGSUSED */
2763 void
2764 ztest_vdev_attach_detach(ztest_ds_t *zd, uint64_t id)
2765 {
2766         ztest_shared_t *zs = ztest_shared;
2767         spa_t *spa = ztest_spa;
2768         spa_aux_vdev_t *sav = &spa->spa_spares;
2769         vdev_t *rvd = spa->spa_root_vdev;
2770         vdev_t *oldvd, *newvd, *pvd;
2771         nvlist_t *root;
2772         uint64_t leaves;
2773         uint64_t leaf, top;
2774         uint64_t ashift = ztest_get_ashift();
2775         uint64_t oldguid, pguid;
2776         uint64_t oldsize, newsize;
2777         char oldpath[MAXPATHLEN], newpath[MAXPATHLEN];
2778         int replacing;
2779         int oldvd_has_siblings = B_FALSE;
2780         int newvd_is_spare = B_FALSE;
2781         int oldvd_is_log;
2782         int error, expected_error;
2783 
2784         mutex_enter(&ztest_vdev_lock);
2785         leaves = MAX(zs->zs_mirrors, 1) * ztest_opts.zo_raidz;
2786 
2787         spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
2788 
2789         /*
2790          * Decide whether to do an attach or a replace.
2791          */
2792         replacing = ztest_random(2);
2793 
2794         /*
2795          * Pick a random top-level vdev.
2796          */
2797         top = ztest_random_vdev_top(spa, B_TRUE);
2798 
2799         /*
2800          * Pick a random leaf within it.
2801          */
2802         leaf = ztest_random(leaves);
2803 
2804         /*
2805          * Locate this vdev.
2806          */
2807         oldvd = rvd->vdev_child[top];
2808         if (zs->zs_mirrors >= 1) {
2809                 ASSERT(oldvd->vdev_ops == &vdev_mirror_ops);
2810                 ASSERT(oldvd->vdev_children >= zs->zs_mirrors);
2811                 oldvd = oldvd->vdev_child[leaf / ztest_opts.zo_raidz];
2812         }
2813         if (ztest_opts.zo_raidz > 1) {
2814                 ASSERT(oldvd->vdev_ops == &vdev_raidz_ops);
2815                 ASSERT(oldvd->vdev_children == ztest_opts.zo_raidz);
2816                 oldvd = oldvd->vdev_child[leaf % ztest_opts.zo_raidz];
2817         }
2818 
2819         /*
2820          * If we're already doing an attach or replace, oldvd may be a
2821          * mirror vdev -- in which case, pick a random child.
2822          */
2823         while (oldvd->vdev_children != 0) {
2824                 oldvd_has_siblings = B_TRUE;
2825                 ASSERT(oldvd->vdev_children >= 2);
2826                 oldvd = oldvd->vdev_child[ztest_random(oldvd->vdev_children)];
2827         }
2828 
2829         oldguid = oldvd->vdev_guid;
2830         oldsize = vdev_get_min_asize(oldvd);
2831         oldvd_is_log = oldvd->vdev_top->vdev_islog;
2832         (void) strcpy(oldpath, oldvd->vdev_path);
2833         pvd = oldvd->vdev_parent;
2834         pguid = pvd->vdev_guid;
2835 
2836         /*
2837          * If oldvd has siblings, then half of the time, detach it.
2838          */
2839         if (oldvd_has_siblings && ztest_random(2) == 0) {
2840                 spa_config_exit(spa, SCL_VDEV, FTAG);
2841                 error = spa_vdev_detach(spa, oldguid, pguid, B_FALSE);
2842                 if (error != 0 && error != ENODEV && error != EBUSY &&
2843                     error != ENOTSUP)
2844                         fatal(0, "detach (%s) returned %d", oldpath, error);
2845                 mutex_exit(&ztest_vdev_lock);
2846                 return;
2847         }
2848 
2849         /*
2850          * For the new vdev, choose with equal probability between the two
2851          * standard paths (ending in either 'a' or 'b') or a random hot spare.
2852          */
2853         if (sav->sav_count != 0 && ztest_random(3) == 0) {
2854                 newvd = sav->sav_vdevs[ztest_random(sav->sav_count)];
2855                 newvd_is_spare = B_TRUE;
2856                 (void) strcpy(newpath, newvd->vdev_path);
2857         } else {
2858                 (void) snprintf(newpath, sizeof (newpath), ztest_dev_template,
2859                     ztest_opts.zo_dir, ztest_opts.zo_pool,
2860                     top * leaves + leaf);
2861                 if (ztest_random(2) == 0)
2862                         newpath[strlen(newpath) - 1] = 'b';
2863                 newvd = vdev_lookup_by_path(rvd, newpath);
2864         }
2865 
2866         if (newvd) {
2867                 newsize = vdev_get_min_asize(newvd);
2868         } else {
2869                 /*
2870                  * Make newsize a little bigger or smaller than oldsize.
2871                  * If it's smaller, the attach should fail.
2872                  * If it's larger, and we're doing a replace,
2873                  * we should get dynamic LUN growth when we're done.
2874                  */
2875                 newsize = 10 * oldsize / (9 + ztest_random(3));
2876         }
2877 
2878         /*
2879          * If pvd is not a mirror or root, the attach should fail with ENOTSUP,
2880          * unless it's a replace; in that case any non-replacing parent is OK.
2881          *
2882          * If newvd is already part of the pool, it should fail with EBUSY.
2883          *
2884          * If newvd is too small, it should fail with EOVERFLOW.
2885          */
2886         if (pvd->vdev_ops != &vdev_mirror_ops &&
2887             pvd->vdev_ops != &vdev_root_ops && (!replacing ||
2888             pvd->vdev_ops == &vdev_replacing_ops ||
2889             pvd->vdev_ops == &vdev_spare_ops))
2890                 expected_error = ENOTSUP;
2891         else if (newvd_is_spare && (!replacing || oldvd_is_log))
2892                 expected_error = ENOTSUP;
2893         else if (newvd == oldvd)
2894                 expected_error = replacing ? 0 : EBUSY;
2895         else if (vdev_lookup_by_path(rvd, newpath) != NULL)
2896                 expected_error = EBUSY;
2897         else if (newsize < oldsize)
2898                 expected_error = EOVERFLOW;
2899         else if (ashift > oldvd->vdev_top->vdev_ashift)
2900                 expected_error = EDOM;
2901         else
2902                 expected_error = 0;
2903 
2904         spa_config_exit(spa, SCL_VDEV, FTAG);
2905 
2906         /*
2907          * Build the nvlist describing newpath.
2908          */
2909         root = make_vdev_root(newpath, NULL, NULL, newvd == NULL ? newsize : 0,
2910             ashift, 0, 0, 0, 1);
2911 
2912         error = spa_vdev_attach(spa, oldguid, root, replacing);
2913 
2914         nvlist_free(root);
2915 
2916         /*
2917          * If our parent was the replacing vdev, but the replace completed,
2918          * then instead of failing with ENOTSUP we may either succeed,
2919          * fail with ENODEV, or fail with EOVERFLOW.
2920          */
2921         if (expected_error == ENOTSUP &&
2922             (error == 0 || error == ENODEV || error == EOVERFLOW))
2923                 expected_error = error;
2924 
2925         /*
2926          * If someone grew the LUN, the replacement may be too small.
2927          */
2928         if (error == EOVERFLOW || error == EBUSY)
2929                 expected_error = error;
2930 
2931         /* XXX workaround 6690467 */
2932         if (error != expected_error && expected_error != EBUSY) {
2933                 fatal(0, "attach (%s %llu, %s %llu, %d) "
2934                     "returned %d, expected %d",
2935                     oldpath, oldsize, newpath,
2936                     newsize, replacing, error, expected_error);
2937         }
2938 
2939         mutex_exit(&ztest_vdev_lock);
2940 }
2941 
2942 /*
2943  * Callback function which expands the physical size of the vdev.
2944  */
2945 vdev_t *
2946 grow_vdev(vdev_t *vd, void *arg)
2947 {
2948         spa_t *spa = vd->vdev_spa;
2949         size_t *newsize = arg;
2950         size_t fsize;
2951         int fd;
2952 
2953         ASSERT(spa_config_held(spa, SCL_STATE, RW_READER) == SCL_STATE);
2954         ASSERT(vd->vdev_ops->vdev_op_leaf);
2955 
2956         if ((fd = open(vd->vdev_path, O_RDWR)) == -1)
2957                 return (vd);
2958 
2959         fsize = lseek(fd, 0, SEEK_END);
2960         (void) ftruncate(fd, *newsize);
2961 
2962         if (ztest_opts.zo_verbose >= 6) {
2963                 (void) printf("%s grew from %lu to %lu bytes\n",
2964                     vd->vdev_path, (ulong_t)fsize, (ulong_t)*newsize);
2965         }
2966         (void) close(fd);
2967         return (NULL);
2968 }
2969 
2970 /*
2971  * Callback function which expands a given vdev by calling vdev_online().
2972  */
2973 /* ARGSUSED */
2974 vdev_t *
2975 online_vdev(vdev_t *vd, void *arg)
2976 {
2977         spa_t *spa = vd->vdev_spa;
2978         vdev_t *tvd = vd->vdev_top;
2979         uint64_t guid = vd->vdev_guid;
2980         uint64_t generation = spa->spa_config_generation + 1;
2981         vdev_state_t newstate = VDEV_STATE_UNKNOWN;
2982         int error;
2983 
2984         ASSERT(spa_config_held(spa, SCL_STATE, RW_READER) == SCL_STATE);
2985         ASSERT(vd->vdev_ops->vdev_op_leaf);
2986 
2987         /* Calling vdev_online will initialize the new metaslabs */
2988         spa_config_exit(spa, SCL_STATE, spa);
2989         error = vdev_online(spa, guid, ZFS_ONLINE_EXPAND, &newstate);
2990         spa_config_enter(spa, SCL_STATE, spa, RW_READER);
2991 
2992         /*
2993          * If vdev_online returned an error or the underlying vdev_open
2994          * failed then we abort the expand. The only way to know that
2995          * vdev_open fails is by checking the returned newstate.
2996          */
2997         if (error || newstate != VDEV_STATE_HEALTHY) {
2998                 if (ztest_opts.zo_verbose >= 5) {
2999                         (void) printf("Unable to expand vdev, state %llu, "
3000                             "error %d\n", (u_longlong_t)newstate, error);
3001                 }
3002                 return (vd);
3003         }
3004         ASSERT3U(newstate, ==, VDEV_STATE_HEALTHY);
3005 
3006         /*
3007          * Since we dropped the lock we need to ensure that we're
3008          * still talking to the original vdev. It's possible this
3009          * vdev may have been detached/replaced while we were
3010          * trying to online it.
3011          */
3012         if (generation != spa->spa_config_generation) {
3013                 if (ztest_opts.zo_verbose >= 5) {
3014                         (void) printf("vdev configuration has changed, "
3015                             "guid %llu, state %llu, expected gen %llu, "
3016                             "got gen %llu\n",
3017                             (u_longlong_t)guid,
3018                             (u_longlong_t)tvd->vdev_state,
3019                             (u_longlong_t)generation,
3020                             (u_longlong_t)spa->spa_config_generation);
3021                 }
3022                 return (vd);
3023         }
3024         return (NULL);
3025 }
3026 
3027 /*
3028  * Traverse the vdev tree calling the supplied function.
3029  * We continue to walk the tree until we either have walked all
3030  * children or we receive a non-NULL return from the callback.
3031  * If a NULL callback is passed, then we just return back the first
3032  * leaf vdev we encounter.
3033  */
3034 vdev_t *
3035 vdev_walk_tree(vdev_t *vd, vdev_t *(*func)(vdev_t *, void *), void *arg)
3036 {
3037         if (vd->vdev_ops->vdev_op_leaf) {
3038                 if (func == NULL)
3039                         return (vd);
3040                 else
3041                         return (func(vd, arg));
3042         }
3043 
3044         for (uint_t c = 0; c < vd->vdev_children; c++) {
3045                 vdev_t *cvd = vd->vdev_child[c];
3046                 if ((cvd = vdev_walk_tree(cvd, func, arg)) != NULL)
3047                         return (cvd);
3048         }
3049         return (NULL);
3050 }
3051 
3052 /*
3053  * Verify that dynamic LUN growth works as expected.
3054  */
3055 /* ARGSUSED */
3056 void
3057 ztest_vdev_LUN_growth(ztest_ds_t *zd, uint64_t id)
3058 {
3059         spa_t *spa = ztest_spa;
3060         vdev_t *vd, *tvd;
3061         metaslab_class_t *mc;
3062         metaslab_group_t *mg;
3063         size_t psize, newsize;
3064         uint64_t top;
3065         uint64_t old_class_space, new_class_space, old_ms_count, new_ms_count;
3066 
3067         mutex_enter(&ztest_vdev_lock);
3068         spa_config_enter(spa, SCL_STATE, spa, RW_READER);
3069 
3070         top = ztest_random_vdev_top(spa, B_TRUE);
3071 
3072         tvd = spa->spa_root_vdev->vdev_child[top];
3073         mg = tvd->vdev_mg;
3074         mc = mg->mg_class;
3075         old_ms_count = tvd->vdev_ms_count;
3076         old_class_space = metaslab_class_get_space(mc);
3077 
3078         /*
3079          * Determine the size of the first leaf vdev associated with
3080          * our top-level device.
3081          */
3082         vd = vdev_walk_tree(tvd, NULL, NULL);
3083         ASSERT3P(vd, !=, NULL);
3084         ASSERT(vd->vdev_ops->vdev_op_leaf);
3085 
3086         psize = vd->vdev_psize;
3087 
3088         /*
3089          * We only try to expand the vdev if it's healthy, less than 4x its
3090          * original size, and it has a valid psize.
3091          */
3092         if (tvd->vdev_state != VDEV_STATE_HEALTHY ||
3093             psize == 0 || psize >= 4 * ztest_opts.zo_vdev_size) {
3094                 spa_config_exit(spa, SCL_STATE, spa);
3095                 mutex_exit(&ztest_vdev_lock);
3096                 return;
3097         }
3098         ASSERT(psize > 0);
3099         newsize = psize + psize / 8;
3100         ASSERT3U(newsize, >, psize);
3101 
3102         if (ztest_opts.zo_verbose >= 6) {
3103                 (void) printf("Expanding LUN %s from %lu to %lu\n",
3104                     vd->vdev_path, (ulong_t)psize, (ulong_t)newsize);
3105         }
3106 
3107         /*
3108          * Growing the vdev is a two step process:
3109          *      1). expand the physical size (i.e. relabel)
3110          *      2). online the vdev to create the new metaslabs
3111          */
3112         if (vdev_walk_tree(tvd, grow_vdev, &newsize) != NULL ||
3113             vdev_walk_tree(tvd, online_vdev, NULL) != NULL ||
3114             tvd->vdev_state != VDEV_STATE_HEALTHY) {
3115                 if (ztest_opts.zo_verbose >= 5) {
3116                         (void) printf("Could not expand LUN because "
3117                             "the vdev configuration changed.\n");
3118                 }
3119                 spa_config_exit(spa, SCL_STATE, spa);
3120                 mutex_exit(&ztest_vdev_lock);
3121                 return;
3122         }
3123 
3124         spa_config_exit(spa, SCL_STATE, spa);
3125 
3126         /*
3127          * Expanding the LUN will update the config asynchronously,
3128          * thus we must wait for the async thread to complete any
3129          * pending tasks before proceeding.
3130          */
3131         for (;;) {
3132                 boolean_t done;
3133                 mutex_enter(&spa->spa_async_lock);
3134                 done = (spa->spa_async_thread == NULL && !spa->spa_async_tasks);
3135                 mutex_exit(&spa->spa_async_lock);
3136                 if (done)
3137                         break;
3138                 txg_wait_synced(spa_get_dsl(spa), 0);
3139                 (void) poll(NULL, 0, 100);
3140         }
3141 
3142         spa_config_enter(spa, SCL_STATE, spa, RW_READER);
3143 
3144         tvd = spa->spa_root_vdev->vdev_child[top];
3145         new_ms_count = tvd->vdev_ms_count;
3146         new_class_space = metaslab_class_get_space(mc);
3147 
3148         if (tvd->vdev_mg != mg || mg->mg_class != mc) {
3149                 if (ztest_opts.zo_verbose >= 5) {
3150                         (void) printf("Could not verify LUN expansion due to "
3151                             "intervening vdev offline or remove.\n");
3152                 }
3153                 spa_config_exit(spa, SCL_STATE, spa);
3154                 mutex_exit(&ztest_vdev_lock);
3155                 return;
3156         }
3157 
3158         /*
3159          * Make sure we were able to grow the vdev.
3160          */
3161         if (new_ms_count <= old_ms_count)
3162                 fatal(0, "LUN expansion failed: ms_count %llu <= %llu\n",
3163                     old_ms_count, new_ms_count);
3164 
3165         /*
3166          * Make sure we were able to grow the pool.
3167          */
3168         if (new_class_space <= old_class_space)
3169                 fatal(0, "LUN expansion failed: class_space %llu <= %llu\n",
3170                     old_class_space, new_class_space);
3171 
3172         if (ztest_opts.zo_verbose >= 5) {
3173                 char oldnumbuf[NN_NUMBUF_SZ], newnumbuf[NN_NUMBUF_SZ];
3174 
3175                 nicenum(old_class_space, oldnumbuf, sizeof (oldnumbuf));
3176                 nicenum(new_class_space, newnumbuf, sizeof (newnumbuf));
3177                 (void) printf("%s grew from %s to %s\n",
3178                     spa->spa_name, oldnumbuf, newnumbuf);
3179         }
3180 
3181         spa_config_exit(spa, SCL_STATE, spa);
3182         mutex_exit(&ztest_vdev_lock);
3183 }
3184 
3185 /*
3186  * Verify that dmu_objset_{create,destroy,open,close} work as expected.
3187  */
3188 /* ARGSUSED */
3189 static void
3190 ztest_objset_create_cb(objset_t *os, void *arg, cred_t *cr, dmu_tx_t *tx)
3191 {
3192         /*
3193          * Create the objects common to all ztest datasets.
3194          */
3195         VERIFY(zap_create_claim(os, ZTEST_DIROBJ,
3196             DMU_OT_ZAP_OTHER, DMU_OT_NONE, 0, tx) == 0);
3197 }
3198 
3199 static int
3200 ztest_dataset_create(char *dsname)
3201 {
3202         uint64_t zilset = ztest_random(100);
3203         int err = dmu_objset_create(dsname, DMU_OST_OTHER, 0,
3204             ztest_objset_create_cb, NULL);
3205 
3206         if (err || zilset < 80)
3207                 return (err);
3208 
3209         if (ztest_opts.zo_verbose >= 6)
3210                 (void) printf("Setting dataset %s to sync always\n", dsname);
3211         return (ztest_dsl_prop_set_uint64(dsname, ZFS_PROP_SYNC,
3212             ZFS_SYNC_ALWAYS, B_FALSE));
3213 }
3214 
3215 /* ARGSUSED */
3216 static int
3217 ztest_objset_destroy_cb(const char *name, void *arg)
3218 {
3219         objset_t *os;
3220         dmu_object_info_t doi;
3221         int error;
3222 
3223         /*
3224          * Verify that the dataset contains a directory object.
3225          */
3226         VERIFY0(dmu_objset_own(name, DMU_OST_OTHER, B_TRUE, FTAG, &os));
3227         error = dmu_object_info(os, ZTEST_DIROBJ, &doi);
3228         if (error != ENOENT) {
3229                 /* We could have crashed in the middle of destroying it */
3230                 ASSERT0(error);
3231                 ASSERT3U(doi.doi_type, ==, DMU_OT_ZAP_OTHER);
3232                 ASSERT3S(doi.doi_physical_blocks_512, >=, 0);
3233         }
3234         dmu_objset_disown(os, FTAG);
3235 
3236         /*
3237          * Destroy the dataset.
3238          */
3239         if (strchr(name, '@') != NULL) {
3240                 VERIFY0(dsl_destroy_snapshot(name, B_TRUE));
3241         } else {
3242                 error = dsl_destroy_head(name);
3243                 /* There could be a hold on this dataset */
3244                 if (error != EBUSY)
3245                         ASSERT0(error);
3246         }
3247         return (0);
3248 }
3249 
3250 static boolean_t
3251 ztest_snapshot_create(char *osname, uint64_t id)
3252 {
3253         char snapname[ZFS_MAX_DATASET_NAME_LEN];
3254         int error;
3255 
3256         (void) snprintf(snapname, sizeof (snapname), "%llu", (u_longlong_t)id);
3257 
3258         error = dmu_objset_snapshot_one(osname, snapname);
3259         if (error == ENOSPC) {
3260                 ztest_record_enospc(FTAG);
3261                 return (B_FALSE);
3262         }
3263         if (error != 0 && error != EEXIST) {
3264                 fatal(0, "ztest_snapshot_create(%s@%s) = %d", osname,
3265                     snapname, error);
3266         }
3267         return (B_TRUE);
3268 }
3269 
3270 static boolean_t
3271 ztest_snapshot_destroy(char *osname, uint64_t id)
3272 {
3273         char snapname[ZFS_MAX_DATASET_NAME_LEN];
3274         int error;
3275 
3276         (void) snprintf(snapname, sizeof (snapname), "%s@%llu", osname,
3277             (u_longlong_t)id);
3278 
3279         error = dsl_destroy_snapshot(snapname, B_FALSE);
3280         if (error != 0 && error != ENOENT)
3281                 fatal(0, "ztest_snapshot_destroy(%s) = %d", snapname, error);
3282         return (B_TRUE);
3283 }
3284 
3285 /* ARGSUSED */
3286 void
3287 ztest_dmu_objset_create_destroy(ztest_ds_t *zd, uint64_t id)
3288 {
3289         ztest_ds_t zdtmp;
3290         int iters;
3291         int error;
3292         objset_t *os, *os2;
3293         char name[ZFS_MAX_DATASET_NAME_LEN];
3294         zilog_t *zilog;
3295 
3296         rw_enter(&ztest_name_lock, RW_READER);
3297 
3298         (void) snprintf(name, sizeof (name), "%s/temp_%llu",
3299             ztest_opts.zo_pool, (u_longlong_t)id);
3300 
3301         /*
3302          * If this dataset exists from a previous run, process its replay log
3303          * half of the time.  If we don't replay it, then dmu_objset_destroy()
3304          * (invoked from ztest_objset_destroy_cb()) should just throw it away.
3305          */
3306         if (ztest_random(2) == 0 &&
3307             dmu_objset_own(name, DMU_OST_OTHER, B_FALSE, FTAG, &os) == 0) {
3308                 ztest_zd_init(&zdtmp, NULL, os);
3309                 zil_replay(os, &zdtmp, ztest_replay_vector);
3310                 ztest_zd_fini(&zdtmp);
3311                 dmu_objset_disown(os, FTAG);
3312         }
3313 
3314         /*
3315          * There may be an old instance of the dataset we're about to
3316          * create lying around from a previous run.  If so, destroy it
3317          * and all of its snapshots.
3318          */
3319         (void) dmu_objset_find(name, ztest_objset_destroy_cb, NULL,
3320             DS_FIND_CHILDREN | DS_FIND_SNAPSHOTS);
3321 
3322         /*
3323          * Verify that the destroyed dataset is no longer in the namespace.
3324          */
3325         VERIFY3U(ENOENT, ==, dmu_objset_own(name, DMU_OST_OTHER, B_TRUE,
3326             FTAG, &os));
3327 
3328         /*
3329          * Verify that we can create a new dataset.
3330          */
3331         error = ztest_dataset_create(name);
3332         if (error) {
3333                 if (error == ENOSPC) {
3334                         ztest_record_enospc(FTAG);
3335                         rw_exit(&ztest_name_lock);
3336                         return;
3337                 }
3338                 fatal(0, "dmu_objset_create(%s) = %d", name, error);
3339         }
3340 
3341         VERIFY0(dmu_objset_own(name, DMU_OST_OTHER, B_FALSE, FTAG, &os));
3342 
3343         ztest_zd_init(&zdtmp, NULL, os);
3344 
3345         /*
3346          * Open the intent log for it.
3347          */
3348         zilog = zil_open(os, ztest_get_data);
3349 
3350         /*
3351          * Put some objects in there, do a little I/O to them,
3352          * and randomly take a couple of snapshots along the way.
3353          */
3354         iters = ztest_random(5);
3355         for (int i = 0; i < iters; i++) {
3356                 ztest_dmu_object_alloc_free(&zdtmp, id);
3357                 if (ztest_random(iters) == 0)
3358                         (void) ztest_snapshot_create(name, i);
3359         }
3360 
3361         /*
3362          * Verify that we cannot create an existing dataset.
3363          */
3364         VERIFY3U(EEXIST, ==,
3365             dmu_objset_create(name, DMU_OST_OTHER, 0, NULL, NULL));
3366 
3367         /*
3368          * Verify that we can hold an objset that is also owned.
3369          */
3370         VERIFY3U(0, ==, dmu_objset_hold(name, FTAG, &os2));
3371         dmu_objset_rele(os2, FTAG);
3372 
3373         /*
3374          * Verify that we cannot own an objset that is already owned.
3375          */
3376         VERIFY3U(EBUSY, ==,
3377             dmu_objset_own(name, DMU_OST_OTHER, B_FALSE, FTAG, &os2));
3378 
3379         zil_close(zilog);
3380         dmu_objset_disown(os, FTAG);
3381         ztest_zd_fini(&zdtmp);
3382 
3383         rw_exit(&ztest_name_lock);
3384 }
3385 
3386 /*
3387  * Verify that dmu_snapshot_{create,destroy,open,close} work as expected.
3388  */
3389 void
3390 ztest_dmu_snapshot_create_destroy(ztest_ds_t *zd, uint64_t id)
3391 {
3392         rw_enter(&ztest_name_lock, RW_READER);
3393         (void) ztest_snapshot_destroy(zd->zd_name, id);
3394         (void) ztest_snapshot_create(zd->zd_name, id);
3395         rw_exit(&ztest_name_lock);
3396 }
3397 
3398 /*
3399  * Cleanup non-standard snapshots and clones.
3400  */
3401 void
3402 ztest_dsl_dataset_cleanup(char *osname, uint64_t id)
3403 {
3404         char snap1name[ZFS_MAX_DATASET_NAME_LEN];
3405         char clone1name[ZFS_MAX_DATASET_NAME_LEN];
3406         char snap2name[ZFS_MAX_DATASET_NAME_LEN];
3407         char clone2name[ZFS_MAX_DATASET_NAME_LEN];
3408         char snap3name[ZFS_MAX_DATASET_NAME_LEN];
3409         int error;
3410 
3411         (void) snprintf(snap1name, sizeof (snap1name),
3412             "%s@s1_%llu", osname, id);
3413         (void) snprintf(clone1name, sizeof (clone1name),
3414             "%s/c1_%llu", osname, id);
3415         (void) snprintf(snap2name, sizeof (snap2name),
3416             "%s@s2_%llu", clone1name, id);
3417         (void) snprintf(clone2name, sizeof (clone2name),
3418             "%s/c2_%llu", osname, id);
3419         (void) snprintf(snap3name, sizeof (snap3name),
3420             "%s@s3_%llu", clone1name, id);
3421 
3422         error = dsl_destroy_head(clone2name);
3423         if (error && error != ENOENT)
3424                 fatal(0, "dsl_destroy_head(%s) = %d", clone2name, error);
3425         error = dsl_destroy_snapshot(snap3name, B_FALSE);
3426         if (error && error != ENOENT)
3427                 fatal(0, "dsl_destroy_snapshot(%s) = %d", snap3name, error);
3428         error = dsl_destroy_snapshot(snap2name, B_FALSE);
3429         if (error && error != ENOENT)
3430                 fatal(0, "dsl_destroy_snapshot(%s) = %d", snap2name, error);
3431         error = dsl_destroy_head(clone1name);
3432         if (error && error != ENOENT)
3433                 fatal(0, "dsl_destroy_head(%s) = %d", clone1name, error);
3434         error = dsl_destroy_snapshot(snap1name, B_FALSE);
3435         if (error && error != ENOENT)
3436                 fatal(0, "dsl_destroy_snapshot(%s) = %d", snap1name, error);
3437 }
3438 
3439 /*
3440  * Verify dsl_dataset_promote handles EBUSY
3441  */
3442 void
3443 ztest_dsl_dataset_promote_busy(ztest_ds_t *zd, uint64_t id)
3444 {
3445         objset_t *os;
3446         char snap1name[ZFS_MAX_DATASET_NAME_LEN];
3447         char clone1name[ZFS_MAX_DATASET_NAME_LEN];
3448         char snap2name[ZFS_MAX_DATASET_NAME_LEN];
3449         char clone2name[ZFS_MAX_DATASET_NAME_LEN];
3450         char snap3name[ZFS_MAX_DATASET_NAME_LEN];
3451         char *osname = zd->zd_name;
3452         int error;
3453 
3454         rw_enter(&ztest_name_lock, RW_READER);
3455 
3456         ztest_dsl_dataset_cleanup(osname, id);
3457 
3458         (void) snprintf(snap1name, sizeof (snap1name),
3459             "%s@s1_%llu", osname, id);
3460         (void) snprintf(clone1name, sizeof (clone1name),
3461             "%s/c1_%llu", osname, id);
3462         (void) snprintf(snap2name, sizeof (snap2name),
3463             "%s@s2_%llu", clone1name, id);
3464         (void) snprintf(clone2name, sizeof (clone2name),
3465             "%s/c2_%llu", osname, id);
3466         (void) snprintf(snap3name, sizeof (snap3name),
3467             "%s@s3_%llu", clone1name, id);
3468 
3469         error = dmu_objset_snapshot_one(osname, strchr(snap1name, '@') + 1);
3470         if (error && error != EEXIST) {
3471                 if (error == ENOSPC) {
3472                         ztest_record_enospc(FTAG);
3473                         goto out;
3474                 }
3475                 fatal(0, "dmu_take_snapshot(%s) = %d", snap1name, error);
3476         }
3477 
3478         error = dmu_objset_clone(clone1name, snap1name);
3479         if (error) {
3480                 if (error == ENOSPC) {
3481                         ztest_record_enospc(FTAG);
3482                         goto out;
3483                 }
3484                 fatal(0, "dmu_objset_create(%s) = %d", clone1name, error);
3485         }
3486 
3487         error = dmu_objset_snapshot_one(clone1name, strchr(snap2name, '@') + 1);
3488         if (error && error != EEXIST) {
3489                 if (error == ENOSPC) {
3490                         ztest_record_enospc(FTAG);
3491                         goto out;
3492                 }
3493                 fatal(0, "dmu_open_snapshot(%s) = %d", snap2name, error);
3494         }
3495 
3496         error = dmu_objset_snapshot_one(clone1name, strchr(snap3name, '@') + 1);
3497         if (error && error != EEXIST) {
3498                 if (error == ENOSPC) {
3499                         ztest_record_enospc(FTAG);
3500                         goto out;
3501                 }
3502                 fatal(0, "dmu_open_snapshot(%s) = %d", snap3name, error);
3503         }
3504 
3505         error = dmu_objset_clone(clone2name, snap3name);
3506         if (error) {
3507                 if (error == ENOSPC) {
3508                         ztest_record_enospc(FTAG);
3509                         goto out;
3510                 }
3511                 fatal(0, "dmu_objset_create(%s) = %d", clone2name, error);
3512         }
3513 
3514         error = dmu_objset_own(snap2name, DMU_OST_ANY, B_TRUE, FTAG, &os);
3515         if (error)
3516                 fatal(0, "dmu_objset_own(%s) = %d", snap2name, error);
3517         error = dsl_dataset_promote(clone2name, NULL);
3518         if (error == ENOSPC) {
3519                 dmu_objset_disown(os, FTAG);
3520                 ztest_record_enospc(FTAG);
3521                 goto out;
3522         }
3523         if (error != EBUSY)
3524                 fatal(0, "dsl_dataset_promote(%s), %d, not EBUSY", clone2name,
3525                     error);
3526         dmu_objset_disown(os, FTAG);
3527 
3528 out:
3529         ztest_dsl_dataset_cleanup(osname, id);
3530 
3531         rw_exit(&ztest_name_lock);
3532 }
3533 
3534 /*
3535  * Verify that dmu_object_{alloc,free} work as expected.
3536  */
3537 void
3538 ztest_dmu_object_alloc_free(ztest_ds_t *zd, uint64_t id)
3539 {
3540         ztest_od_t od[4];
3541         int batchsize = sizeof (od) / sizeof (od[0]);
3542 
3543         for (int b = 0; b < batchsize; b++)
3544                 ztest_od_init(&od[b], id, FTAG, b, DMU_OT_UINT64_OTHER, 0, 0);
3545 
3546         /*
3547          * Destroy the previous batch of objects, create a new batch,
3548          * and do some I/O on the new objects.
3549          */
3550         if (ztest_object_init(zd, od, sizeof (od), B_TRUE) != 0)
3551                 return;
3552 
3553         while (ztest_random(4 * batchsize) != 0)
3554                 ztest_io(zd, od[ztest_random(batchsize)].od_object,
3555                     ztest_random(ZTEST_RANGE_LOCKS) << SPA_MAXBLOCKSHIFT);
3556 }
3557 
3558 /*
3559  * Verify that dmu_{read,write} work as expected.
3560  */
3561 void
3562 ztest_dmu_read_write(ztest_ds_t *zd, uint64_t id)
3563 {
3564         objset_t *os = zd->zd_os;
3565         ztest_od_t od[2];
3566         dmu_tx_t *tx;
3567         int i, freeit, error;
3568         uint64_t n, s, txg;
3569         bufwad_t *packbuf, *bigbuf, *pack, *bigH, *bigT;
3570         uint64_t packobj, packoff, packsize, bigobj, bigoff, bigsize;
3571         uint64_t chunksize = (1000 + ztest_random(1000)) * sizeof (uint64_t);
3572         uint64_t regions = 997;
3573         uint64_t stride = 123456789ULL;
3574         uint64_t width = 40;
3575         int free_percent = 5;
3576 
3577         /*
3578          * This test uses two objects, packobj and bigobj, that are always
3579          * updated together (i.e. in the same tx) so that their contents are
3580          * in sync and can be compared.  Their contents relate to each other
3581          * in a simple way: packobj is a dense array of 'bufwad' structures,
3582          * while bigobj is a sparse array of the same bufwads.  Specifically,
3583          * for any index n, there are three bufwads that should be identical:
3584          *
3585          *      packobj, at offset n * sizeof (bufwad_t)
3586          *      bigobj, at the head of the nth chunk
3587          *      bigobj, at the tail of the nth chunk
3588          *
3589          * The chunk size is arbitrary. It doesn't have to be a power of two,
3590          * and it doesn't have any relation to the object blocksize.
3591          * The only requirement is that it can hold at least two bufwads.
3592          *
3593          * Normally, we write the bufwad to each of these locations.
3594          * However, free_percent of the time we instead write zeroes to
3595          * packobj and perform a dmu_free_range() on bigobj.  By comparing
3596          * bigobj to packobj, we can verify that the DMU is correctly
3597          * tracking which parts of an object are allocated and free,
3598          * and that the contents of the allocated blocks are correct.
3599          */
3600 
3601         /*
3602          * Read the directory info.  If it's the first time, set things up.
3603          */
3604         ztest_od_init(&od[0], id, FTAG, 0, DMU_OT_UINT64_OTHER, 0, chunksize);
3605         ztest_od_init(&od[1], id, FTAG, 1, DMU_OT_UINT64_OTHER, 0, chunksize);
3606 
3607         if (ztest_object_init(zd, od, sizeof (od), B_FALSE) != 0)
3608                 return;
3609 
3610         bigobj = od[0].od_object;
3611         packobj = od[1].od_object;
3612         chunksize = od[0].od_gen;
3613         ASSERT(chunksize == od[1].od_gen);
3614 
3615         /*
3616          * Prefetch a random chunk of the big object.
3617          * Our aim here is to get some async reads in flight
3618          * for blocks that we may free below; the DMU should
3619          * handle this race correctly.
3620          */
3621         n = ztest_random(regions) * stride + ztest_random(width);
3622         s = 1 + ztest_random(2 * width - 1);
3623         dmu_prefetch(os, bigobj, 0, n * chunksize, s * chunksize,
3624             ZIO_PRIORITY_SYNC_READ);
3625 
3626         /*
3627          * Pick a random index and compute the offsets into packobj and bigobj.
3628          */
3629         n = ztest_random(regions) * stride + ztest_random(width);
3630         s = 1 + ztest_random(width - 1);
3631 
3632         packoff = n * sizeof (bufwad_t);
3633         packsize = s * sizeof (bufwad_t);
3634 
3635         bigoff = n * chunksize;
3636         bigsize = s * chunksize;
3637 
3638         packbuf = umem_alloc(packsize, UMEM_NOFAIL);
3639         bigbuf = umem_alloc(bigsize, UMEM_NOFAIL);
3640 
3641         /*
3642          * free_percent of the time, free a range of bigobj rather than
3643          * overwriting it.
3644          */
3645         freeit = (ztest_random(100) < free_percent);
3646 
3647         /*
3648          * Read the current contents of our objects.
3649          */
3650         error = dmu_read(os, packobj, packoff, packsize, packbuf,
3651             DMU_READ_PREFETCH);
3652         ASSERT0(error);
3653         error = dmu_read(os, bigobj, bigoff, bigsize, bigbuf,
3654             DMU_READ_PREFETCH);
3655         ASSERT0(error);
3656 
3657         /*
3658          * Get a tx for the mods to both packobj and bigobj.
3659          */
3660         tx = dmu_tx_create(os);
3661 
3662         dmu_tx_hold_write(tx, packobj, packoff, packsize);
3663 
3664         if (freeit)
3665                 dmu_tx_hold_free(tx, bigobj, bigoff, bigsize);
3666         else
3667                 dmu_tx_hold_write(tx, bigobj, bigoff, bigsize);
3668 
3669         /* This accounts for setting the checksum/compression. */
3670         dmu_tx_hold_bonus(tx, bigobj);
3671 
3672         txg = ztest_tx_assign(tx, TXG_MIGHTWAIT, FTAG);
3673         if (txg == 0) {
3674                 umem_free(packbuf, packsize);
3675                 umem_free(bigbuf, bigsize);
3676                 return;
3677         }
3678 
3679         enum zio_checksum cksum;
3680         do {
3681                 cksum = (enum zio_checksum)
3682                     ztest_random_dsl_prop(ZFS_PROP_CHECKSUM);
3683         } while (cksum >= ZIO_CHECKSUM_LEGACY_FUNCTIONS);
3684         dmu_object_set_checksum(os, bigobj, cksum, tx);
3685 
3686         enum zio_compress comp;
3687         do {
3688                 comp = (enum zio_compress)
3689                     ztest_random_dsl_prop(ZFS_PROP_COMPRESSION);
3690         } while (comp >= ZIO_COMPRESS_LEGACY_FUNCTIONS);
3691         dmu_object_set_compress(os, bigobj, comp, tx);
3692 
3693         /*
3694          * For each index from n to n + s, verify that the existing bufwad
3695          * in packobj matches the bufwads at the head and tail of the
3696          * corresponding chunk in bigobj.  Then update all three bufwads
3697          * with the new values we want to write out.
3698          */
3699         for (i = 0; i < s; i++) {
3700                 /* LINTED */
3701                 pack = (bufwad_t *)((char *)packbuf + i * sizeof (bufwad_t));
3702                 /* LINTED */
3703                 bigH = (bufwad_t *)((char *)bigbuf + i * chunksize);
3704                 /* LINTED */
3705                 bigT = (bufwad_t *)((char *)bigH + chunksize) - 1;
3706 
3707                 ASSERT((uintptr_t)bigH - (uintptr_t)bigbuf < bigsize);
3708                 ASSERT((uintptr_t)bigT - (uintptr_t)bigbuf < bigsize);
3709 
3710                 if (pack->bw_txg > txg)
3711                         fatal(0, "future leak: got %llx, open txg is %llx",
3712                             pack->bw_txg, txg);
3713 
3714                 if (pack->bw_data != 0 && pack->bw_index != n + i)
3715                         fatal(0, "wrong index: got %llx, wanted %llx+%llx",
3716                             pack->bw_index, n, i);
3717 
3718                 if (bcmp(pack, bigH, sizeof (bufwad_t)) != 0)
3719                         fatal(0, "pack/bigH mismatch in %p/%p", pack, bigH);
3720 
3721                 if (bcmp(pack, bigT, sizeof (bufwad_t)) != 0)
3722                         fatal(0, "pack/bigT mismatch in %p/%p", pack, bigT);
3723 
3724                 if (freeit) {
3725                         bzero(pack, sizeof (bufwad_t));
3726                 } else {
3727                         pack->bw_index = n + i;
3728                         pack->bw_txg = txg;
3729                         pack->bw_data = 1 + ztest_random(-2ULL);
3730                 }
3731                 *bigH = *pack;
3732                 *bigT = *pack;
3733         }
3734 
3735         /*
3736          * We've verified all the old bufwads, and made new ones.
3737          * Now write them out.
3738          */
3739         dmu_write(os, packobj, packoff, packsize, packbuf, tx);
3740 
3741         if (freeit) {
3742                 if (ztest_opts.zo_verbose >= 7) {
3743                         (void) printf("freeing offset %llx size %llx"
3744                             " txg %llx\n",
3745                             (u_longlong_t)bigoff,
3746                             (u_longlong_t)bigsize,
3747                             (u_longlong_t)txg);
3748                 }
3749                 VERIFY(0 == dmu_free_range(os, bigobj, bigoff, bigsize, tx));
3750         } else {
3751                 if (ztest_opts.zo_verbose >= 7) {
3752                         (void) printf("writing offset %llx size %llx"
3753                             " txg %llx\n",
3754                             (u_longlong_t)bigoff,
3755                             (u_longlong_t)bigsize,
3756                             (u_longlong_t)txg);
3757                 }
3758                 dmu_write(os, bigobj, bigoff, bigsize, bigbuf, tx);
3759         }
3760 
3761         dmu_tx_commit(tx);
3762 
3763         /*
3764          * Sanity check the stuff we just wrote.
3765          */
3766         {
3767                 void *packcheck = umem_alloc(packsize, UMEM_NOFAIL);
3768                 void *bigcheck = umem_alloc(bigsize, UMEM_NOFAIL);
3769 
3770                 VERIFY(0 == dmu_read(os, packobj, packoff,
3771                     packsize, packcheck, DMU_READ_PREFETCH));
3772                 VERIFY(0 == dmu_read(os, bigobj, bigoff,
3773                     bigsize, bigcheck, DMU_READ_PREFETCH));
3774 
3775                 ASSERT(bcmp(packbuf, packcheck, packsize) == 0);
3776                 ASSERT(bcmp(bigbuf, bigcheck, bigsize) == 0);
3777 
3778                 umem_free(packcheck, packsize);
3779                 umem_free(bigcheck, bigsize);
3780         }
3781 
3782         umem_free(packbuf, packsize);
3783         umem_free(bigbuf, bigsize);
3784 }
3785 
3786 void
3787 compare_and_update_pbbufs(uint64_t s, bufwad_t *packbuf, bufwad_t *bigbuf,
3788     uint64_t bigsize, uint64_t n, uint64_t chunksize, uint64_t txg)
3789 {
3790         uint64_t i;
3791         bufwad_t *pack;
3792         bufwad_t *bigH;
3793         bufwad_t *bigT;
3794 
3795         /*
3796          * For each index from n to n + s, verify that the existing bufwad
3797          * in packobj matches the bufwads at the head and tail of the
3798          * corresponding chunk in bigobj.  Then update all three bufwads
3799          * with the new values we want to write out.
3800          */
3801         for (i = 0; i < s; i++) {
3802                 /* LINTED */
3803                 pack = (bufwad_t *)((char *)packbuf + i * sizeof (bufwad_t));
3804                 /* LINTED */
3805                 bigH = (bufwad_t *)((char *)bigbuf + i * chunksize);
3806                 /* LINTED */
3807                 bigT = (bufwad_t *)((char *)bigH + chunksize) - 1;
3808 
3809                 ASSERT((uintptr_t)bigH - (uintptr_t)bigbuf < bigsize);
3810                 ASSERT((uintptr_t)bigT - (uintptr_t)bigbuf < bigsize);
3811 
3812                 if (pack->bw_txg > txg)
3813                         fatal(0, "future leak: got %llx, open txg is %llx",
3814                             pack->bw_txg, txg);
3815 
3816                 if (pack->bw_data != 0 && pack->bw_index != n + i)
3817                         fatal(0, "wrong index: got %llx, wanted %llx+%llx",
3818                             pack->bw_index, n, i);
3819 
3820                 if (bcmp(pack, bigH, sizeof (bufwad_t)) != 0)
3821                         fatal(0, "pack/bigH mismatch in %p/%p", pack, bigH);
3822 
3823                 if (bcmp(pack, bigT, sizeof (bufwad_t)) != 0)
3824                         fatal(0, "pack/bigT mismatch in %p/%p", pack, bigT);
3825 
3826                 pack->bw_index = n + i;
3827                 pack->bw_txg = txg;
3828                 pack->bw_data = 1 + ztest_random(-2ULL);
3829 
3830                 *bigH = *pack;
3831                 *bigT = *pack;
3832         }
3833 }
3834 
3835 void
3836 ztest_dmu_read_write_zcopy(ztest_ds_t *zd, uint64_t id)
3837 {
3838         objset_t *os = zd->zd_os;
3839         ztest_od_t od[2];
3840         dmu_tx_t *tx;
3841         uint64_t i;
3842         int error;
3843         uint64_t n, s, txg;
3844         bufwad_t *packbuf, *bigbuf;
3845         uint64_t packobj, packoff, packsize, bigobj, bigoff, bigsize;
3846         uint64_t blocksize = ztest_random_blocksize();
3847         uint64_t chunksize = blocksize;
3848         uint64_t regions = 997;
3849         uint64_t stride = 123456789ULL;
3850         uint64_t width = 9;
3851         dmu_buf_t *bonus_db;
3852         arc_buf_t **bigbuf_arcbufs;
3853         dmu_object_info_t doi;
3854 
3855         /*
3856          * This test uses two objects, packobj and bigobj, that are always
3857          * updated together (i.e. in the same tx) so that their contents are
3858          * in sync and can be compared.  Their contents relate to each other
3859          * in a simple way: packobj is a dense array of 'bufwad' structures,
3860          * while bigobj is a sparse array of the same bufwads.  Specifically,
3861          * for any index n, there are three bufwads that should be identical:
3862          *
3863          *      packobj, at offset n * sizeof (bufwad_t)
3864          *      bigobj, at the head of the nth chunk
3865          *      bigobj, at the tail of the nth chunk
3866          *
3867          * The chunk size is set equal to bigobj block size so that
3868          * dmu_assign_arcbuf() can be tested for object updates.
3869          */
3870 
3871         /*
3872          * Read the directory info.  If it's the first time, set things up.
3873          */
3874         ztest_od_init(&od[0], id, FTAG, 0, DMU_OT_UINT64_OTHER, blocksize, 0);
3875         ztest_od_init(&od[1], id, FTAG, 1, DMU_OT_UINT64_OTHER, 0, chunksize);
3876 
3877         if (ztest_object_init(zd, od, sizeof (od), B_FALSE) != 0)
3878                 return;
3879 
3880         bigobj = od[0].od_object;
3881         packobj = od[1].od_object;
3882         blocksize = od[0].od_blocksize;
3883         chunksize = blocksize;
3884         ASSERT(chunksize == od[1].od_gen);
3885 
3886         VERIFY(dmu_object_info(os, bigobj, &doi) == 0);
3887         VERIFY(ISP2(doi.doi_data_block_size));
3888         VERIFY(chunksize == doi.doi_data_block_size);
3889         VERIFY(chunksize >= 2 * sizeof (bufwad_t));
3890 
3891         /*
3892          * Pick a random index and compute the offsets into packobj and bigobj.
3893          */
3894         n = ztest_random(regions) * stride + ztest_random(width);
3895         s = 1 + ztest_random(width - 1);
3896 
3897         packoff = n * sizeof (bufwad_t);
3898         packsize = s * sizeof (bufwad_t);
3899 
3900         bigoff = n * chunksize;
3901         bigsize = s * chunksize;
3902 
3903         packbuf = umem_zalloc(packsize, UMEM_NOFAIL);
3904         bigbuf = umem_zalloc(bigsize, UMEM_NOFAIL);
3905 
3906         VERIFY3U(0, ==, dmu_bonus_hold(os, bigobj, FTAG, &bonus_db));
3907 
3908         bigbuf_arcbufs = umem_zalloc(2 * s * sizeof (arc_buf_t *), UMEM_NOFAIL);
3909 
3910         /*
3911          * Iteration 0 test zcopy for DB_UNCACHED dbufs.
3912          * Iteration 1 test zcopy to already referenced dbufs.
3913          * Iteration 2 test zcopy to dirty dbuf in the same txg.
3914          * Iteration 3 test zcopy to dbuf dirty in previous txg.
3915          * Iteration 4 test zcopy when dbuf is no longer dirty.
3916          * Iteration 5 test zcopy when it can't be done.
3917          * Iteration 6 one more zcopy write.
3918          */
3919         for (i = 0; i < 7; i++) {
3920                 uint64_t j;
3921                 uint64_t off;
3922 
3923                 /*
3924                  * In iteration 5 (i == 5) use arcbufs
3925                  * that don't match bigobj blksz to test
3926                  * dmu_assign_arcbuf() when it can't directly
3927                  * assign an arcbuf to a dbuf.
3928                  */
3929                 for (j = 0; j < s; j++) {
3930                         if (i != 5 || chunksize < (SPA_MINBLOCKSIZE * 2)) {
3931                                 bigbuf_arcbufs[j] =
3932                                     dmu_request_arcbuf(bonus_db, chunksize);
3933                         } else {
3934                                 bigbuf_arcbufs[2 * j] =
3935                                     dmu_request_arcbuf(bonus_db, chunksize / 2);
3936                                 bigbuf_arcbufs[2 * j + 1] =
3937                                     dmu_request_arcbuf(bonus_db, chunksize / 2);
3938                         }
3939                 }
3940 
3941                 /*
3942                  * Get a tx for the mods to both packobj and bigobj.
3943                  */
3944                 tx = dmu_tx_create(os);
3945 
3946                 dmu_tx_hold_write(tx, packobj, packoff, packsize);
3947                 dmu_tx_hold_write(tx, bigobj, bigoff, bigsize);
3948 
3949                 txg = ztest_tx_assign(tx, TXG_MIGHTWAIT, FTAG);
3950                 if (txg == 0) {
3951                         umem_free(packbuf, packsize);
3952                         umem_free(bigbuf, bigsize);
3953                         for (j = 0; j < s; j++) {
3954                                 if (i != 5 ||
3955                                     chunksize < (SPA_MINBLOCKSIZE * 2)) {
3956                                         dmu_return_arcbuf(bigbuf_arcbufs[j]);
3957                                 } else {
3958                                         dmu_return_arcbuf(
3959                                             bigbuf_arcbufs[2 * j]);
3960                                         dmu_return_arcbuf(
3961                                             bigbuf_arcbufs[2 * j + 1]);
3962                                 }
3963                         }
3964                         umem_free(bigbuf_arcbufs, 2 * s * sizeof (arc_buf_t *));
3965                         dmu_buf_rele(bonus_db, FTAG);
3966                         return;
3967                 }
3968 
3969                 /*
3970                  * 50% of the time don't read objects in the 1st iteration to
3971                  * test dmu_assign_arcbuf() for the case when there're no
3972                  * existing dbufs for the specified offsets.
3973                  */
3974                 if (i != 0 || ztest_random(2) != 0) {
3975                         error = dmu_read(os, packobj, packoff,
3976                             packsize, packbuf, DMU_READ_PREFETCH);
3977                         ASSERT0(error);
3978                         error = dmu_read(os, bigobj, bigoff, bigsize,
3979                             bigbuf, DMU_READ_PREFETCH);
3980                         ASSERT0(error);
3981                 }
3982                 compare_and_update_pbbufs(s, packbuf, bigbuf, bigsize,
3983                     n, chunksize, txg);
3984 
3985                 /*
3986                  * We've verified all the old bufwads, and made new ones.
3987                  * Now write them out.
3988                  */
3989                 dmu_write(os, packobj, packoff, packsize, packbuf, tx);
3990                 if (ztest_opts.zo_verbose >= 7) {
3991                         (void) printf("writing offset %llx size %llx"
3992                             " txg %llx\n",
3993                             (u_longlong_t)bigoff,
3994                             (u_longlong_t)bigsize,
3995                             (u_longlong_t)txg);
3996                 }
3997                 for (off = bigoff, j = 0; j < s; j++, off += chunksize) {
3998                         dmu_buf_t *dbt;
3999                         if (i != 5 || chunksize < (SPA_MINBLOCKSIZE * 2)) {
4000                                 bcopy((caddr_t)bigbuf + (off - bigoff),
4001                                     bigbuf_arcbufs[j]->b_data, chunksize);
4002                         } else {
4003                                 bcopy((caddr_t)bigbuf + (off - bigoff),
4004                                     bigbuf_arcbufs[2 * j]->b_data,
4005                                     chunksize / 2);
4006                                 bcopy((caddr_t)bigbuf + (off - bigoff) +
4007                                     chunksize / 2,
4008                                     bigbuf_arcbufs[2 * j + 1]->b_data,
4009                                     chunksize / 2);
4010                         }
4011 
4012                         if (i == 1) {
4013                                 VERIFY(dmu_buf_hold(os, bigobj, off,
4014                                     FTAG, &dbt, DMU_READ_NO_PREFETCH) == 0);
4015                         }
4016                         if (i != 5 || chunksize < (SPA_MINBLOCKSIZE * 2)) {
4017                                 dmu_assign_arcbuf(bonus_db, off,
4018                                     bigbuf_arcbufs[j], tx);
4019                         } else {
4020                                 dmu_assign_arcbuf(bonus_db, off,
4021                                     bigbuf_arcbufs[2 * j], tx);
4022                                 dmu_assign_arcbuf(bonus_db,
4023                                     off + chunksize / 2,
4024                                     bigbuf_arcbufs[2 * j + 1], tx);
4025                         }
4026                         if (i == 1) {
4027                                 dmu_buf_rele(dbt, FTAG);
4028                         }
4029                 }
4030                 dmu_tx_commit(tx);
4031 
4032                 /*
4033                  * Sanity check the stuff we just wrote.
4034                  */
4035                 {
4036                         void *packcheck = umem_alloc(packsize, UMEM_NOFAIL);
4037                         void *bigcheck = umem_alloc(bigsize, UMEM_NOFAIL);
4038 
4039                         VERIFY(0 == dmu_read(os, packobj, packoff,
4040                             packsize, packcheck, DMU_READ_PREFETCH));
4041                         VERIFY(0 == dmu_read(os, bigobj, bigoff,
4042                             bigsize, bigcheck, DMU_READ_PREFETCH));
4043 
4044                         ASSERT(bcmp(packbuf, packcheck, packsize) == 0);
4045                         ASSERT(bcmp(bigbuf, bigcheck, bigsize) == 0);
4046 
4047                         umem_free(packcheck, packsize);
4048                         umem_free(bigcheck, bigsize);
4049                 }
4050                 if (i == 2) {
4051                         txg_wait_open(dmu_objset_pool(os), 0);
4052                 } else if (i == 3) {
4053                         txg_wait_synced(dmu_objset_pool(os), 0);
4054                 }
4055         }
4056 
4057         dmu_buf_rele(bonus_db, FTAG);
4058         umem_free(packbuf, packsize);
4059         umem_free(bigbuf, bigsize);
4060         umem_free(bigbuf_arcbufs, 2 * s * sizeof (arc_buf_t *));
4061 }
4062 
4063 /* ARGSUSED */
4064 void
4065 ztest_dmu_write_parallel(ztest_ds_t *zd, uint64_t id)
4066 {
4067         ztest_od_t od[1];
4068         uint64_t offset = (1ULL << (ztest_random(20) + 43)) +
4069             (ztest_random(ZTEST_RANGE_LOCKS) << SPA_MAXBLOCKSHIFT);
4070 
4071         /*
4072          * Have multiple threads write to large offsets in an object
4073          * to verify that parallel writes to an object -- even to the
4074          * same blocks within the object -- doesn't cause any trouble.
4075          */
4076         ztest_od_init(&od[0], ID_PARALLEL, FTAG, 0, DMU_OT_UINT64_OTHER, 0, 0);
4077 
4078         if (ztest_object_init(zd, od, sizeof (od), B_FALSE) != 0)
4079                 return;
4080 
4081         while (ztest_random(10) != 0)
4082                 ztest_io(zd, od[0].od_object, offset);
4083 }
4084 
4085 void
4086 ztest_dmu_prealloc(ztest_ds_t *zd, uint64_t id)
4087 {
4088         ztest_od_t od[1];
4089         uint64_t offset = (1ULL << (ztest_random(4) + SPA_MAXBLOCKSHIFT)) +
4090             (ztest_random(ZTEST_RANGE_LOCKS) << SPA_MAXBLOCKSHIFT);
4091         uint64_t count = ztest_random(20) + 1;
4092         uint64_t blocksize = ztest_random_blocksize();
4093         void *data;
4094 
4095         ztest_od_init(&od[0], id, FTAG, 0, DMU_OT_UINT64_OTHER, blocksize, 0);
4096 
4097         if (ztest_object_init(zd, od, sizeof (od), !ztest_random(2)) != 0)
4098                 return;
4099 
4100         if (ztest_truncate(zd, od[0].od_object, offset, count * blocksize) != 0)
4101                 return;
4102 
4103         ztest_prealloc(zd, od[0].od_object, offset, count * blocksize);
4104 
4105         data = umem_zalloc(blocksize, UMEM_NOFAIL);
4106 
4107         while (ztest_random(count) != 0) {
4108                 uint64_t randoff = offset + (ztest_random(count) * blocksize);
4109                 if (ztest_write(zd, od[0].od_object, randoff, blocksize,
4110                     data) != 0)
4111                         break;
4112                 while (ztest_random(4) != 0)
4113                         ztest_io(zd, od[0].od_object, randoff);
4114         }
4115 
4116         umem_free(data, blocksize);
4117 }
4118 
4119 /*
4120  * Verify that zap_{create,destroy,add,remove,update} work as expected.
4121  */
4122 #define ZTEST_ZAP_MIN_INTS      1
4123 #define ZTEST_ZAP_MAX_INTS      4
4124 #define ZTEST_ZAP_MAX_PROPS     1000
4125 
4126 void
4127 ztest_zap(ztest_ds_t *zd, uint64_t id)
4128 {
4129         objset_t *os = zd->zd_os;
4130         ztest_od_t od[1];
4131         uint64_t object;
4132         uint64_t txg, last_txg;
4133         uint64_t value[ZTEST_ZAP_MAX_INTS];
4134         uint64_t zl_ints, zl_intsize, prop;
4135         int i, ints;
4136         dmu_tx_t *tx;
4137         char propname[100], txgname[100];
4138         int error;
4139         char *hc[2] = { "s.acl.h", ".s.open.h.hyLZlg" };
4140 
4141         ztest_od_init(&od[0], id, FTAG, 0, DMU_OT_ZAP_OTHER, 0, 0);
4142 
4143         if (ztest_object_init(zd, od, sizeof (od), !ztest_random(2)) != 0)
4144                 return;
4145 
4146         object = od[0].od_object;
4147 
4148         /*
4149          * Generate a known hash collision, and verify that
4150          * we can lookup and remove both entries.
4151          */
4152         tx = dmu_tx_create(os);
4153         dmu_tx_hold_zap(tx, object, B_TRUE, NULL);
4154         txg = ztest_tx_assign(tx, TXG_MIGHTWAIT, FTAG);
4155         if (txg == 0)
4156                 return;
4157         for (i = 0; i < 2; i++) {
4158                 value[i] = i;
4159                 VERIFY3U(0, ==, zap_add(os, object, hc[i], sizeof (uint64_t),
4160                     1, &value[i], tx));
4161         }
4162         for (i = 0; i < 2; i++) {
4163                 VERIFY3U(EEXIST, ==, zap_add(os, object, hc[i],
4164                     sizeof (uint64_t), 1, &value[i], tx));
4165                 VERIFY3U(0, ==,
4166                     zap_length(os, object, hc[i], &zl_intsize, &zl_ints));
4167                 ASSERT3U(zl_intsize, ==, sizeof (uint64_t));
4168                 ASSERT3U(zl_ints, ==, 1);
4169         }
4170         for (i = 0; i < 2; i++) {
4171                 VERIFY3U(0, ==, zap_remove(os, object, hc[i], tx));
4172         }
4173         dmu_tx_commit(tx);
4174 
4175         /*
4176          * Generate a buch of random entries.
4177          */
4178         ints = MAX(ZTEST_ZAP_MIN_INTS, object % ZTEST_ZAP_MAX_INTS);
4179 
4180         prop = ztest_random(ZTEST_ZAP_MAX_PROPS);
4181         (void) sprintf(propname, "prop_%llu", (u_longlong_t)prop);
4182         (void) sprintf(txgname, "txg_%llu", (u_longlong_t)prop);
4183         bzero(value, sizeof (value));
4184         last_txg = 0;
4185 
4186         /*
4187          * If these zap entries already exist, validate their contents.
4188          */
4189         error = zap_length(os, object, txgname, &zl_intsize, &zl_ints);
4190         if (error == 0) {
4191                 ASSERT3U(zl_intsize, ==, sizeof (uint64_t));
4192                 ASSERT3U(zl_ints, ==, 1);
4193 
4194                 VERIFY(zap_lookup(os, object, txgname, zl_intsize,
4195                     zl_ints, &last_txg) == 0);
4196 
4197                 VERIFY(zap_length(os, object, propname, &zl_intsize,
4198                     &zl_ints) == 0);
4199 
4200                 ASSERT3U(zl_intsize, ==, sizeof (uint64_t));
4201                 ASSERT3U(zl_ints, ==, ints);
4202 
4203                 VERIFY(zap_lookup(os, object, propname, zl_intsize,
4204                     zl_ints, value) == 0);
4205 
4206                 for (i = 0; i < ints; i++) {
4207                         ASSERT3U(value[i], ==, last_txg + object + i);
4208                 }
4209         } else {
4210                 ASSERT3U(error, ==, ENOENT);
4211         }
4212 
4213         /*
4214          * Atomically update two entries in our zap object.
4215          * The first is named txg_%llu, and contains the txg
4216          * in which the property was last updated.  The second
4217          * is named prop_%llu, and the nth element of its value
4218          * should be txg + object + n.
4219          */
4220         tx = dmu_tx_create(os);
4221         dmu_tx_hold_zap(tx, object, B_TRUE, NULL);
4222         txg = ztest_tx_assign(tx, TXG_MIGHTWAIT, FTAG);
4223         if (txg == 0)
4224                 return;
4225 
4226         if (last_txg > txg)
4227                 fatal(0, "zap future leak: old %llu new %llu", last_txg, txg);
4228 
4229         for (i = 0; i < ints; i++)
4230                 value[i] = txg + object + i;
4231 
4232         VERIFY3U(0, ==, zap_update(os, object, txgname, sizeof (uint64_t),
4233             1, &txg, tx));
4234         VERIFY3U(0, ==, zap_update(os, object, propname, sizeof (uint64_t),
4235             ints, value, tx));
4236 
4237         dmu_tx_commit(tx);
4238 
4239         /*
4240          * Remove a random pair of entries.
4241          */
4242         prop = ztest_random(ZTEST_ZAP_MAX_PROPS);
4243         (void) sprintf(propname, "prop_%llu", (u_longlong_t)prop);
4244         (void) sprintf(txgname, "txg_%llu", (u_longlong_t)prop);
4245 
4246         error = zap_length(os, object, txgname, &zl_intsize, &zl_ints);
4247 
4248         if (error == ENOENT)
4249                 return;
4250 
4251         ASSERT0(error);
4252 
4253         tx = dmu_tx_create(os);
4254         dmu_tx_hold_zap(tx, object, B_TRUE, NULL);
4255         txg = ztest_tx_assign(tx, TXG_MIGHTWAIT, FTAG);
4256         if (txg == 0)
4257                 return;
4258         VERIFY3U(0, ==, zap_remove(os, object, txgname, tx));
4259         VERIFY3U(0, ==, zap_remove(os, object, propname, tx));
4260         dmu_tx_commit(tx);
4261 }
4262 
4263 /*
4264  * Testcase to test the upgrading of a microzap to fatzap.
4265  */
4266 void
4267 ztest_fzap(ztest_ds_t *zd, uint64_t id)
4268 {
4269         objset_t *os = zd->zd_os;
4270         ztest_od_t od[1];
4271         uint64_t object, txg;
4272 
4273         ztest_od_init(&od[0], id, FTAG, 0, DMU_OT_ZAP_OTHER, 0, 0);
4274 
4275         if (ztest_object_init(zd, od, sizeof (od), !ztest_random(2)) != 0)
4276                 return;
4277 
4278         object = od[0].od_object;
4279 
4280         /*
4281          * Add entries to this ZAP and make sure it spills over
4282          * and gets upgraded to a fatzap. Also, since we are adding
4283          * 2050 entries we should see ptrtbl growth and leaf-block split.
4284          */
4285         for (int i = 0; i < 2050; i++) {
4286                 char name[ZFS_MAX_DATASET_NAME_LEN];
4287                 uint64_t value = i;
4288                 dmu_tx_t *tx;
4289                 int error;
4290 
4291                 (void) snprintf(name, sizeof (name), "fzap-%llu-%llu",
4292                     id, value);
4293 
4294                 tx = dmu_tx_create(os);
4295                 dmu_tx_hold_zap(tx, object, B_TRUE, name);
4296                 txg = ztest_tx_assign(tx, TXG_MIGHTWAIT, FTAG);
4297                 if (txg == 0)
4298                         return;
4299                 error = zap_add(os, object, name, sizeof (uint64_t), 1,
4300                     &value, tx);
4301                 ASSERT(error == 0 || error == EEXIST);
4302                 dmu_tx_commit(tx);
4303         }
4304 }
4305 
4306 /* ARGSUSED */
4307 void
4308 ztest_zap_parallel(ztest_ds_t *zd, uint64_t id)
4309 {
4310         objset_t *os = zd->zd_os;
4311         ztest_od_t od[1];
4312         uint64_t txg, object, count, wsize, wc, zl_wsize, zl_wc;
4313         dmu_tx_t *tx;
4314         int i, namelen, error;
4315         int micro = ztest_random(2);
4316         char name[20], string_value[20];
4317         void *data;
4318 
4319         ztest_od_init(&od[0], ID_PARALLEL, FTAG, micro, DMU_OT_ZAP_OTHER, 0, 0);
4320 
4321         if (ztest_object_init(zd, od, sizeof (od), B_FALSE) != 0)
4322                 return;
4323 
4324         object = od[0].od_object;
4325 
4326         /*
4327          * Generate a random name of the form 'xxx.....' where each
4328          * x is a random printable character and the dots are dots.
4329          * There are 94 such characters, and the name length goes from
4330          * 6 to 20, so there are 94^3 * 15 = 12,458,760 possible names.
4331          */
4332         namelen = ztest_random(sizeof (name) - 5) + 5 + 1;
4333 
4334         for (i = 0; i < 3; i++)
4335                 name[i] = '!' + ztest_random('~' - '!' + 1);
4336         for (; i < namelen - 1; i++)
4337                 name[i] = '.';
4338         name[i] = '\0';
4339 
4340         if ((namelen & 1) || micro) {
4341                 wsize = sizeof (txg);
4342                 wc = 1;
4343                 data = &txg;
4344         } else {
4345                 wsize = 1;
4346                 wc = namelen;
4347                 data = string_value;
4348         }
4349 
4350         count = -1ULL;
4351         VERIFY0(zap_count(os, object, &count));
4352         ASSERT(count != -1ULL);
4353 
4354         /*
4355          * Select an operation: length, lookup, add, update, remove.
4356          */
4357         i = ztest_random(5);
4358 
4359         if (i >= 2) {
4360                 tx = dmu_tx_create(os);
4361                 dmu_tx_hold_zap(tx, object, B_TRUE, NULL);
4362                 txg = ztest_tx_assign(tx, TXG_MIGHTWAIT, FTAG);
4363                 if (txg == 0)
4364                         return;
4365                 bcopy(name, string_value, namelen);
4366         } else {
4367                 tx = NULL;
4368                 txg = 0;
4369                 bzero(string_value, namelen);
4370         }
4371 
4372         switch (i) {
4373 
4374         case 0:
4375                 error = zap_length(os, object, name, &zl_wsize, &zl_wc);
4376                 if (error == 0) {
4377                         ASSERT3U(wsize, ==, zl_wsize);
4378                         ASSERT3U(wc, ==, zl_wc);
4379                 } else {
4380                         ASSERT3U(error, ==, ENOENT);
4381                 }
4382                 break;
4383 
4384         case 1:
4385                 error = zap_lookup(os, object, name, wsize, wc, data);
4386                 if (error == 0) {
4387                         if (data == string_value &&
4388                             bcmp(name, data, namelen) != 0)
4389                                 fatal(0, "name '%s' != val '%s' len %d",
4390                                     name, data, namelen);
4391                 } else {
4392                         ASSERT3U(error, ==, ENOENT);
4393                 }
4394                 break;
4395 
4396         case 2:
4397                 error = zap_add(os, object, name, wsize, wc, data, tx);
4398                 ASSERT(error == 0 || error == EEXIST);
4399                 break;
4400 
4401         case 3:
4402                 VERIFY(zap_update(os, object, name, wsize, wc, data, tx) == 0);
4403                 break;
4404 
4405         case 4:
4406                 error = zap_remove(os, object, name, tx);
4407                 ASSERT(error == 0 || error == ENOENT);
4408                 break;
4409         }
4410 
4411         if (tx != NULL)
4412                 dmu_tx_commit(tx);
4413 }
4414 
4415 /*
4416  * Commit callback data.
4417  */
4418 typedef struct ztest_cb_data {
4419         list_node_t             zcd_node;
4420         uint64_t                zcd_txg;
4421         int                     zcd_expected_err;
4422         boolean_t               zcd_added;
4423         boolean_t               zcd_called;
4424         spa_t                   *zcd_spa;
4425 } ztest_cb_data_t;
4426 
4427 /* This is the actual commit callback function */
4428 static void
4429 ztest_commit_callback(void *arg, int error)
4430 {
4431         ztest_cb_data_t *data = arg;
4432         uint64_t synced_txg;
4433 
4434         VERIFY(data != NULL);
4435         VERIFY3S(data->zcd_expected_err, ==, error);
4436         VERIFY(!data->zcd_called);
4437 
4438         synced_txg = spa_last_synced_txg(data->zcd_spa);
4439         if (data->zcd_txg > synced_txg)
4440                 fatal(0, "commit callback of txg %" PRIu64 " called prematurely"
4441                     ", last synced txg = %" PRIu64 "\n", data->zcd_txg,
4442                     synced_txg);
4443 
4444         data->zcd_called = B_TRUE;
4445 
4446         if (error == ECANCELED) {
4447                 ASSERT0(data->zcd_txg);
4448                 ASSERT(!data->zcd_added);
4449 
4450                 /*
4451                  * The private callback data should be destroyed here, but
4452                  * since we are going to check the zcd_called field after
4453                  * dmu_tx_abort(), we will destroy it there.
4454                  */
4455                 return;
4456         }
4457 
4458         /* Was this callback added to the global callback list? */
4459         if (!data->zcd_added)
4460                 goto out;
4461 
4462         ASSERT3U(data->zcd_txg, !=, 0);
4463 
4464         /* Remove our callback from the list */
4465         mutex_enter(&zcl.zcl_callbacks_lock);
4466         list_remove(&zcl.zcl_callbacks, data);
4467         mutex_exit(&zcl.zcl_callbacks_lock);
4468 
4469 out:
4470         umem_free(data, sizeof (ztest_cb_data_t));
4471 }
4472 
4473 /* Allocate and initialize callback data structure */
4474 static ztest_cb_data_t *
4475 ztest_create_cb_data(objset_t *os, uint64_t txg)
4476 {
4477         ztest_cb_data_t *cb_data;
4478 
4479         cb_data = umem_zalloc(sizeof (ztest_cb_data_t), UMEM_NOFAIL);
4480 
4481         cb_data->zcd_txg = txg;
4482         cb_data->zcd_spa = dmu_objset_spa(os);
4483 
4484         return (cb_data);
4485 }
4486 
4487 /*
4488  * If a number of txgs equal to this threshold have been created after a commit
4489  * callback has been registered but not called, then we assume there is an
4490  * implementation bug.
4491  */
4492 #define ZTEST_COMMIT_CALLBACK_THRESH    (TXG_CONCURRENT_STATES + 2)
4493 
4494 /*
4495  * Commit callback test.
4496  */
4497 void
4498 ztest_dmu_commit_callbacks(ztest_ds_t *zd, uint64_t id)
4499 {
4500         objset_t *os = zd->zd_os;
4501         ztest_od_t od[1];
4502         dmu_tx_t *tx;
4503         ztest_cb_data_t *cb_data[3], *tmp_cb;
4504         uint64_t old_txg, txg;
4505         int i, error;
4506 
4507         ztest_od_init(&od[0], id, FTAG, 0, DMU_OT_UINT64_OTHER, 0, 0);
4508 
4509         if (ztest_object_init(zd, od, sizeof (od), B_FALSE) != 0)
4510                 return;
4511 
4512         tx = dmu_tx_create(os);
4513 
4514         cb_data[0] = ztest_create_cb_data(os, 0);
4515         dmu_tx_callback_register(tx, ztest_commit_callback, cb_data[0]);
4516 
4517         dmu_tx_hold_write(tx, od[0].od_object, 0, sizeof (uint64_t));
4518 
4519         /* Every once in a while, abort the transaction on purpose */
4520         if (ztest_random(100) == 0)
4521                 error = -1;
4522 
4523         if (!error)
4524                 error = dmu_tx_assign(tx, TXG_NOWAIT);
4525 
4526         txg = error ? 0 : dmu_tx_get_txg(tx);
4527 
4528         cb_data[0]->zcd_txg = txg;
4529         cb_data[1] = ztest_create_cb_data(os, txg);
4530         dmu_tx_callback_register(tx, ztest_commit_callback, cb_data[1]);
4531 
4532         if (error) {
4533                 /*
4534                  * It's not a strict requirement to call the registered
4535                  * callbacks from inside dmu_tx_abort(), but that's what
4536                  * it's supposed to happen in the current implementation
4537                  * so we will check for that.
4538                  */
4539                 for (i = 0; i < 2; i++) {
4540                         cb_data[i]->zcd_expected_err = ECANCELED;
4541                         VERIFY(!cb_data[i]->zcd_called);
4542                 }
4543 
4544                 dmu_tx_abort(tx);
4545 
4546                 for (i = 0; i < 2; i++) {
4547                         VERIFY(cb_data[i]->zcd_called);
4548                         umem_free(cb_data[i], sizeof (ztest_cb_data_t));
4549                 }
4550 
4551                 return;
4552         }
4553 
4554         cb_data[2] = ztest_create_cb_data(os, txg);
4555         dmu_tx_callback_register(tx, ztest_commit_callback, cb_data[2]);
4556 
4557         /*
4558          * Read existing data to make sure there isn't a future leak.
4559          */
4560         VERIFY(0 == dmu_read(os, od[0].od_object, 0, sizeof (uint64_t),
4561             &old_txg, DMU_READ_PREFETCH));
4562 
4563         if (old_txg > txg)
4564                 fatal(0, "future leak: got %" PRIu64 ", open txg is %" PRIu64,
4565                     old_txg, txg);
4566 
4567         dmu_write(os, od[0].od_object, 0, sizeof (uint64_t), &txg, tx);
4568 
4569         mutex_enter(&zcl.zcl_callbacks_lock);
4570 
4571         /*
4572          * Since commit callbacks don't have any ordering requirement and since
4573          * it is theoretically possible for a commit callback to be called
4574          * after an arbitrary amount of time has elapsed since its txg has been
4575          * synced, it is difficult to reliably determine whether a commit
4576          * callback hasn't been called due to high load or due to a flawed
4577          * implementation.
4578          *
4579          * In practice, we will assume that if after a certain number of txgs a
4580          * commit callback hasn't been called, then most likely there's an
4581          * implementation bug..
4582          */
4583         tmp_cb = list_head(&zcl.zcl_callbacks);
4584         if (tmp_cb != NULL &&
4585             (txg - ZTEST_COMMIT_CALLBACK_THRESH) > tmp_cb->zcd_txg) {
4586                 fatal(0, "Commit callback threshold exceeded, oldest txg: %"
4587                     PRIu64 ", open txg: %" PRIu64 "\n", tmp_cb->zcd_txg, txg);
4588         }
4589 
4590         /*
4591          * Let's find the place to insert our callbacks.
4592          *
4593          * Even though the list is ordered by txg, it is possible for the
4594          * insertion point to not be the end because our txg may already be
4595          * quiescing at this point and other callbacks in the open txg
4596          * (from other objsets) may have sneaked in.
4597          */
4598         tmp_cb = list_tail(&zcl.zcl_callbacks);
4599         while (tmp_cb != NULL && tmp_cb->zcd_txg > txg)
4600                 tmp_cb = list_prev(&zcl.zcl_callbacks, tmp_cb);
4601 
4602         /* Add the 3 callbacks to the list */
4603         for (i = 0; i < 3; i++) {
4604                 if (tmp_cb == NULL)
4605                         list_insert_head(&zcl.zcl_callbacks, cb_data[i]);
4606                 else
4607                         list_insert_after(&zcl.zcl_callbacks, tmp_cb,
4608                             cb_data[i]);
4609 
4610                 cb_data[i]->zcd_added = B_TRUE;
4611                 VERIFY(!cb_data[i]->zcd_called);
4612 
4613                 tmp_cb = cb_data[i];
4614         }
4615 
4616         mutex_exit(&zcl.zcl_callbacks_lock);
4617 
4618         dmu_tx_commit(tx);
4619 }
4620 
4621 /* ARGSUSED */
4622 void
4623 ztest_dsl_prop_get_set(ztest_ds_t *zd, uint64_t id)
4624 {
4625         zfs_prop_t proplist[] = {
4626                 ZFS_PROP_CHECKSUM,
4627                 ZFS_PROP_COMPRESSION,
4628                 ZFS_PROP_COPIES,
4629                 ZFS_PROP_DEDUP
4630         };
4631 
4632         rw_enter(&ztest_name_lock, RW_READER);
4633 
4634         for (int p = 0; p < sizeof (proplist) / sizeof (proplist[0]); p++)
4635                 (void) ztest_dsl_prop_set_uint64(zd->zd_name, proplist[p],
4636                     ztest_random_dsl_prop(proplist[p]), (int)ztest_random(2));
4637 
4638         rw_exit(&ztest_name_lock);
4639 }
4640 
4641 /* ARGSUSED */
4642 void
4643 ztest_spa_prop_get_set(ztest_ds_t *zd, uint64_t id)
4644 {
4645         nvlist_t *props = NULL;
4646 
4647         rw_enter(&ztest_name_lock, RW_READER);
4648 
4649         (void) ztest_spa_prop_set_uint64(ZPOOL_PROP_DEDUPDITTO,
4650             ZIO_DEDUPDITTO_MIN + ztest_random(ZIO_DEDUPDITTO_MIN));
4651 
4652         VERIFY0(spa_prop_get(ztest_spa, &props));
4653 
4654         if (ztest_opts.zo_verbose >= 6)
4655                 dump_nvlist(props, 4);
4656 
4657         nvlist_free(props);
4658 
4659         rw_exit(&ztest_name_lock);
4660 }
4661 
4662 static int
4663 user_release_one(const char *snapname, const char *holdname)
4664 {
4665         nvlist_t *snaps, *holds;
4666         int error;
4667 
4668         snaps = fnvlist_alloc();
4669         holds = fnvlist_alloc();
4670         fnvlist_add_boolean(holds, holdname);
4671         fnvlist_add_nvlist(snaps, snapname, holds);
4672         fnvlist_free(holds);
4673         error = dsl_dataset_user_release(snaps, NULL);
4674         fnvlist_free(snaps);
4675         return (error);
4676 }
4677 
4678 /*
4679  * Test snapshot hold/release and deferred destroy.
4680  */
4681 void
4682 ztest_dmu_snapshot_hold(ztest_ds_t *zd, uint64_t id)
4683 {
4684         int error;
4685         objset_t *os = zd->zd_os;
4686         objset_t *origin;
4687         char snapname[100];
4688         char fullname[100];
4689         char clonename[100];
4690         char tag[100];
4691         char osname[ZFS_MAX_DATASET_NAME_LEN];
4692         nvlist_t *holds;
4693 
4694         rw_enter(&ztest_name_lock, RW_READER);
4695 
4696         dmu_objset_name(os, osname);
4697 
4698         (void) snprintf(snapname, sizeof (snapname), "sh1_%llu", id);
4699         (void) snprintf(fullname, sizeof (fullname), "%s@%s", osname, snapname);
4700         (void) snprintf(clonename, sizeof (clonename),
4701             "%s/ch1_%llu", osname, id);
4702         (void) snprintf(tag, sizeof (tag), "tag_%llu", id);
4703 
4704         /*
4705          * Clean up from any previous run.
4706          */
4707         error = dsl_destroy_head(clonename);
4708         if (error != ENOENT)
4709                 ASSERT0(error);
4710         error = user_release_one(fullname, tag);
4711         if (error != ESRCH && error != ENOENT)
4712                 ASSERT0(error);
4713         error = dsl_destroy_snapshot(fullname, B_FALSE);
4714         if (error != ENOENT)
4715                 ASSERT0(error);
4716 
4717         /*
4718          * Create snapshot, clone it, mark snap for deferred destroy,
4719          * destroy clone, verify snap was also destroyed.
4720          */
4721         error = dmu_objset_snapshot_one(osname, snapname);
4722         if (error) {
4723                 if (error == ENOSPC) {
4724                         ztest_record_enospc("dmu_objset_snapshot");
4725                         goto out;
4726                 }
4727                 fatal(0, "dmu_objset_snapshot(%s) = %d", fullname, error);
4728         }
4729 
4730         error = dmu_objset_clone(clonename, fullname);
4731         if (error) {
4732                 if (error == ENOSPC) {
4733                         ztest_record_enospc("dmu_objset_clone");
4734                         goto out;
4735                 }
4736                 fatal(0, "dmu_objset_clone(%s) = %d", clonename, error);
4737         }
4738 
4739         error = dsl_destroy_snapshot(fullname, B_TRUE);
4740         if (error) {
4741                 fatal(0, "dsl_destroy_snapshot(%s, B_TRUE) = %d",
4742                     fullname, error);
4743         }
4744 
4745         error = dsl_destroy_head(clonename);
4746         if (error)
4747                 fatal(0, "dsl_destroy_head(%s) = %d", clonename, error);
4748 
4749         error = dmu_objset_hold(fullname, FTAG, &origin);
4750         if (error != ENOENT)
4751                 fatal(0, "dmu_objset_hold(%s) = %d", fullname, error);
4752 
4753         /*
4754          * Create snapshot, add temporary hold, verify that we can't
4755          * destroy a held snapshot, mark for deferred destroy,
4756          * release hold, verify snapshot was destroyed.
4757          */
4758         error = dmu_objset_snapshot_one(osname, snapname);
4759         if (error) {
4760                 if (error == ENOSPC) {
4761                         ztest_record_enospc("dmu_objset_snapshot");
4762                         goto out;
4763                 }
4764                 fatal(0, "dmu_objset_snapshot(%s) = %d", fullname, error);
4765         }
4766 
4767         holds = fnvlist_alloc();
4768         fnvlist_add_string(holds, fullname, tag);
4769         error = dsl_dataset_user_hold(holds, 0, NULL);
4770         fnvlist_free(holds);
4771 
4772         if (error == ENOSPC) {
4773                 ztest_record_enospc("dsl_dataset_user_hold");
4774                 goto out;
4775         } else if (error) {
4776                 fatal(0, "dsl_dataset_user_hold(%s, %s) = %u",
4777                     fullname, tag, error);
4778         }
4779 
4780         error = dsl_destroy_snapshot(fullname, B_FALSE);
4781         if (error != EBUSY) {
4782                 fatal(0, "dsl_destroy_snapshot(%s, B_FALSE) = %d",
4783                     fullname, error);
4784         }
4785 
4786         error = dsl_destroy_snapshot(fullname, B_TRUE);
4787         if (error) {
4788                 fatal(0, "dsl_destroy_snapshot(%s, B_TRUE) = %d",
4789                     fullname, error);
4790         }
4791 
4792         error = user_release_one(fullname, tag);
4793         if (error)
4794                 fatal(0, "user_release_one(%s, %s) = %d", fullname, tag, error);
4795 
4796         VERIFY3U(dmu_objset_hold(fullname, FTAG, &origin), ==, ENOENT);
4797 
4798 out:
4799         rw_exit(&ztest_name_lock);
4800 }
4801 
4802 /*
4803  * Inject random faults into the on-disk data.
4804  */
4805 /* ARGSUSED */
4806 void
4807 ztest_fault_inject(ztest_ds_t *zd, uint64_t id)
4808 {
4809         ztest_shared_t *zs = ztest_shared;
4810         spa_t *spa = ztest_spa;
4811         int fd;
4812         uint64_t offset;
4813         uint64_t leaves;
4814         uint64_t bad = 0x1990c0ffeedecade;
4815         uint64_t top, leaf;
4816         char path0[MAXPATHLEN];
4817         char pathrand[MAXPATHLEN];
4818         size_t fsize;
4819         int bshift = SPA_MAXBLOCKSHIFT + 2;
4820         int iters = 1000;
4821         int maxfaults;
4822         int mirror_save;
4823         vdev_t *vd0 = NULL;
4824         uint64_t guid0 = 0;
4825         boolean_t islog = B_FALSE;
4826 
4827         mutex_enter(&ztest_vdev_lock);
4828         maxfaults = MAXFAULTS();
4829         leaves = MAX(zs->zs_mirrors, 1) * ztest_opts.zo_raidz;
4830         mirror_save = zs->zs_mirrors;
4831         mutex_exit(&ztest_vdev_lock);
4832 
4833         ASSERT(leaves >= 1);
4834 
4835         /*
4836          * Grab the name lock as reader. There are some operations
4837          * which don't like to have their vdevs changed while
4838          * they are in progress (i.e. spa_change_guid). Those
4839          * operations will have grabbed the name lock as writer.
4840          */
4841         rw_enter(&ztest_name_lock, RW_READER);
4842 
4843         /*
4844          * We need SCL_STATE here because we're going to look at vd0->vdev_tsd.
4845          */
4846         spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
4847 
4848         if (ztest_random(2) == 0) {
4849                 /*
4850                  * Inject errors on a normal data device or slog device.
4851                  */
4852                 top = ztest_random_vdev_top(spa, B_TRUE);
4853                 leaf = ztest_random(leaves) + zs->zs_splits;
4854 
4855                 /*
4856                  * Generate paths to the first leaf in this top-level vdev,
4857                  * and to the random leaf we selected.  We'll induce transient
4858                  * write failures and random online/offline activity on leaf 0,
4859                  * and we'll write random garbage to the randomly chosen leaf.
4860                  */
4861                 (void) snprintf(path0, sizeof (path0), ztest_dev_template,
4862                     ztest_opts.zo_dir, ztest_opts.zo_pool,
4863                     top * leaves + zs->zs_splits);
4864                 (void) snprintf(pathrand, sizeof (pathrand), ztest_dev_template,
4865                     ztest_opts.zo_dir, ztest_opts.zo_pool,
4866                     top * leaves + leaf);
4867 
4868                 vd0 = vdev_lookup_by_path(spa->spa_root_vdev, path0);
4869                 if (vd0 != NULL && vd0->vdev_top->vdev_islog)
4870                         islog = B_TRUE;
4871 
4872                 /*
4873                  * If the top-level vdev needs to be resilvered
4874                  * then we only allow faults on the device that is
4875                  * resilvering.
4876                  */
4877                 if (vd0 != NULL && maxfaults != 1 &&
4878                     (!vdev_resilver_needed(vd0->vdev_top, NULL, NULL) ||
4879                     vd0->vdev_resilver_txg != 0)) {
4880                         /*
4881                          * Make vd0 explicitly claim to be unreadable,
4882                          * or unwriteable, or reach behind its back
4883                          * and close the underlying fd.  We can do this if
4884                          * maxfaults == 0 because we'll fail and reexecute,
4885                          * and we can do it if maxfaults >= 2 because we'll
4886                          * have enough redundancy.  If maxfaults == 1, the
4887                          * combination of this with injection of random data
4888                          * corruption below exceeds the pool's fault tolerance.
4889                          */
4890                         vdev_file_t *vf = vd0->vdev_tsd;
4891 
4892                         if (vf != NULL && ztest_random(3) == 0) {
4893                                 (void) close(vf->vf_vnode->v_fd);
4894                                 vf->vf_vnode->v_fd = -1;
4895                         } else if (ztest_random(2) == 0) {
4896                                 vd0->vdev_cant_read = B_TRUE;
4897                         } else {
4898                                 vd0->vdev_cant_write = B_TRUE;
4899                         }
4900                         guid0 = vd0->vdev_guid;
4901                 }
4902         } else {
4903                 /*
4904                  * Inject errors on an l2cache device.
4905                  */
4906                 spa_aux_vdev_t *sav = &spa->spa_l2cache;
4907 
4908                 if (sav->sav_count == 0) {
4909                         spa_config_exit(spa, SCL_STATE, FTAG);
4910                         rw_exit(&ztest_name_lock);
4911                         return;
4912                 }
4913                 vd0 = sav->sav_vdevs[ztest_random(sav->sav_count)];
4914                 guid0 = vd0->vdev_guid;
4915                 (void) strcpy(path0, vd0->vdev_path);
4916                 (void) strcpy(pathrand, vd0->vdev_path);
4917 
4918                 leaf = 0;
4919                 leaves = 1;
4920                 maxfaults = INT_MAX;    /* no limit on cache devices */
4921         }
4922 
4923         spa_config_exit(spa, SCL_STATE, FTAG);
4924         rw_exit(&ztest_name_lock);
4925 
4926         /*
4927          * If we can tolerate two or more faults, or we're dealing
4928          * with a slog, randomly online/offline vd0.
4929          */
4930         if ((maxfaults >= 2 || islog) && guid0 != 0) {
4931                 if (ztest_random(10) < 6) {
4932                         int flags = (ztest_random(2) == 0 ?
4933                             ZFS_OFFLINE_TEMPORARY : 0);
4934 
4935                         /*
4936                          * We have to grab the zs_name_lock as writer to
4937                          * prevent a race between offlining a slog and
4938                          * destroying a dataset. Offlining the slog will
4939                          * grab a reference on the dataset which may cause
4940                          * dmu_objset_destroy() to fail with EBUSY thus
4941                          * leaving the dataset in an inconsistent state.
4942                          */
4943                         if (islog)
4944                                 rw_enter(&ztest_name_lock, RW_WRITER);
4945 
4946                         VERIFY(vdev_offline(spa, guid0, flags) != EBUSY);
4947 
4948                         if (islog)
4949                                 rw_exit(&ztest_name_lock);
4950                 } else {
4951                         /*
4952                          * Ideally we would like to be able to randomly
4953                          * call vdev_[on|off]line without holding locks
4954                          * to force unpredictable failures but the side
4955                          * effects of vdev_[on|off]line prevent us from
4956                          * doing so. We grab the ztest_vdev_lock here to
4957                          * prevent a race between injection testing and
4958                          * aux_vdev removal.
4959                          */
4960                         mutex_enter(&ztest_vdev_lock);
4961                         (void) vdev_online(spa, guid0, 0, NULL);
4962                         mutex_exit(&ztest_vdev_lock);
4963                 }
4964         }
4965 
4966         if (maxfaults == 0)
4967                 return;
4968 
4969         /*
4970          * We have at least single-fault tolerance, so inject data corruption.
4971          */
4972         fd = open(pathrand, O_RDWR);
4973 
4974         if (fd == -1)   /* we hit a gap in the device namespace */
4975                 return;
4976 
4977         fsize = lseek(fd, 0, SEEK_END);
4978 
4979         while (--iters != 0) {
4980                 /*
4981                  * The offset must be chosen carefully to ensure that
4982                  * we do not inject a given logical block with errors
4983                  * on two different leaf devices, because ZFS can not
4984                  * tolerate that (if maxfaults==1).
4985                  *
4986                  * We divide each leaf into chunks of size
4987                  * (# leaves * SPA_MAXBLOCKSIZE * 4).  Within each chunk
4988                  * there is a series of ranges to which we can inject errors.
4989                  * Each range can accept errors on only a single leaf vdev.
4990                  * The error injection ranges are separated by ranges
4991                  * which we will not inject errors on any device (DMZs).
4992                  * Each DMZ must be large enough such that a single block
4993                  * can not straddle it, so that a single block can not be
4994                  * a target in two different injection ranges (on different
4995                  * leaf vdevs).
4996                  *
4997                  * For example, with 3 leaves, each chunk looks like:
4998                  *    0 to  32M: injection range for leaf 0
4999                  *  32M to  64M: DMZ - no injection allowed
5000                  *  64M to  96M: injection range for leaf 1
5001                  *  96M to 128M: DMZ - no injection allowed
5002                  * 128M to 160M: injection range for leaf 2
5003                  * 160M to 192M: DMZ - no injection allowed
5004                  */
5005                 offset = ztest_random(fsize / (leaves << bshift)) *
5006                     (leaves << bshift) + (leaf << bshift) +
5007                     (ztest_random(1ULL << (bshift - 1)) & -8ULL);
5008 
5009                 /*
5010                  * Only allow damage to the labels at one end of the vdev.
5011                  *
5012                  * If all labels are damaged, the device will be totally
5013                  * inaccessible, which will result in loss of data,
5014                  * because we also damage (parts of) the other side of
5015                  * the mirror/raidz.
5016                  *
5017                  * Additionally, we will always have both an even and an
5018                  * odd label, so that we can handle crashes in the
5019                  * middle of vdev_config_sync().
5020                  */
5021                 if ((leaf & 1) == 0 && offset < VDEV_LABEL_START_SIZE)
5022                         continue;
5023 
5024                 /*
5025                  * The two end labels are stored at the "end" of the disk, but
5026                  * the end of the disk (vdev_psize) is aligned to
5027                  * sizeof (vdev_label_t).
5028                  */
5029                 uint64_t psize = P2ALIGN(fsize, sizeof (vdev_label_t));
5030                 if ((leaf & 1) == 1 &&
5031                     offset + sizeof (bad) > psize - VDEV_LABEL_END_SIZE)
5032                         continue;
5033 
5034                 mutex_enter(&ztest_vdev_lock);
5035                 if (mirror_save != zs->zs_mirrors) {
5036                         mutex_exit(&ztest_vdev_lock);
5037                         (void) close(fd);
5038                         return;
5039                 }
5040 
5041                 if (pwrite(fd, &bad, sizeof (bad), offset) != sizeof (bad))
5042                         fatal(1, "can't inject bad word at 0x%llx in %s",
5043                             offset, pathrand);
5044 
5045                 mutex_exit(&ztest_vdev_lock);
5046 
5047                 if (ztest_opts.zo_verbose >= 7)
5048                         (void) printf("injected bad word into %s,"
5049                             " offset 0x%llx\n", pathrand, (u_longlong_t)offset);
5050         }
5051 
5052         (void) close(fd);
5053 }
5054 
5055 /*
5056  * Verify that DDT repair works as expected.
5057  */
5058 void
5059 ztest_ddt_repair(ztest_ds_t *zd, uint64_t id)
5060 {
5061         ztest_shared_t *zs = ztest_shared;
5062         spa_t *spa = ztest_spa;
5063         objset_t *os = zd->zd_os;
5064         ztest_od_t od[1];
5065         uint64_t object, blocksize, txg, pattern, psize;
5066         enum zio_checksum checksum = spa_dedup_checksum(spa);
5067         dmu_buf_t *db;
5068         dmu_tx_t *tx;
5069         abd_t *abd;
5070         blkptr_t blk;
5071         int copies = 2 * ZIO_DEDUPDITTO_MIN;
5072 
5073         blocksize = ztest_random_blocksize();
5074         blocksize = MIN(blocksize, 2048);       /* because we write so many */
5075 
5076         ztest_od_init(&od[0], id, FTAG, 0, DMU_OT_UINT64_OTHER, blocksize, 0);
5077 
5078         if (ztest_object_init(zd, od, sizeof (od), B_FALSE) != 0)
5079                 return;
5080 
5081         /*
5082          * Take the name lock as writer to prevent anyone else from changing
5083          * the pool and dataset properies we need to maintain during this test.
5084          */
5085         rw_enter(&ztest_name_lock, RW_WRITER);
5086 
5087         if (ztest_dsl_prop_set_uint64(zd->zd_name, ZFS_PROP_DEDUP, checksum,
5088             B_FALSE) != 0 ||
5089             ztest_dsl_prop_set_uint64(zd->zd_name, ZFS_PROP_COPIES, 1,
5090             B_FALSE) != 0) {
5091                 rw_exit(&ztest_name_lock);
5092                 return;
5093         }
5094 
5095         dmu_objset_stats_t dds;
5096         dsl_pool_config_enter(dmu_objset_pool(os), FTAG);
5097         dmu_objset_fast_stat(os, &dds);
5098         dsl_pool_config_exit(dmu_objset_pool(os), FTAG);
5099 
5100         object = od[0].od_object;
5101         blocksize = od[0].od_blocksize;
5102         pattern = zs->zs_guid ^ dds.dds_guid;
5103 
5104         ASSERT(object != 0);
5105 
5106         tx = dmu_tx_create(os);
5107         dmu_tx_hold_write(tx, object, 0, copies * blocksize);
5108         txg = ztest_tx_assign(tx, TXG_WAIT, FTAG);
5109         if (txg == 0) {
5110                 rw_exit(&ztest_name_lock);
5111                 return;
5112         }
5113 
5114         /*
5115          * Write all the copies of our block.
5116          */
5117         for (int i = 0; i < copies; i++) {
5118                 uint64_t offset = i * blocksize;
5119                 int error = dmu_buf_hold(os, object, offset, FTAG, &db,
5120                     DMU_READ_NO_PREFETCH);
5121                 if (error != 0) {
5122                         fatal(B_FALSE, "dmu_buf_hold(%p, %llu, %llu) = %u",
5123                             os, (long long)object, (long long) offset, error);
5124                 }
5125                 ASSERT(db->db_offset == offset);
5126                 ASSERT(db->db_size == blocksize);
5127                 ASSERT(ztest_pattern_match(db->db_data, db->db_size, pattern) ||
5128                     ztest_pattern_match(db->db_data, db->db_size, 0ULL));
5129                 dmu_buf_will_fill(db, tx);
5130                 ztest_pattern_set(db->db_data, db->db_size, pattern);
5131                 dmu_buf_rele(db, FTAG);
5132         }
5133 
5134         dmu_tx_commit(tx);
5135         txg_wait_synced(spa_get_dsl(spa), txg);
5136 
5137         /*
5138          * Find out what block we got.
5139          */
5140         VERIFY0(dmu_buf_hold(os, object, 0, FTAG, &db,
5141             DMU_READ_NO_PREFETCH));
5142         blk = *((dmu_buf_impl_t *)db)->db_blkptr;
5143         dmu_buf_rele(db, FTAG);
5144 
5145         /*
5146          * Damage the block.  Dedup-ditto will save us when we read it later.
5147          */
5148         psize = BP_GET_PSIZE(&blk);
5149         abd = abd_alloc_linear(psize, B_TRUE);
5150         ztest_pattern_set(abd_to_buf(abd), psize, ~pattern);
5151 
5152         (void) zio_wait(zio_rewrite(NULL, spa, 0, &blk,
5153             abd, psize, NULL, NULL, ZIO_PRIORITY_SYNC_WRITE,
5154             ZIO_FLAG_CANFAIL | ZIO_FLAG_INDUCE_DAMAGE, NULL));
5155 
5156         abd_free(abd);
5157 
5158         rw_exit(&ztest_name_lock);
5159 }
5160 
5161 /*
5162  * Scrub the pool.
5163  */
5164 /* ARGSUSED */
5165 void
5166 ztest_scrub(ztest_ds_t *zd, uint64_t id)
5167 {
5168         spa_t *spa = ztest_spa;
5169 
5170         (void) spa_scan(spa, POOL_SCAN_SCRUB);
5171         (void) poll(NULL, 0, 100); /* wait a moment, then force a restart */
5172         (void) spa_scan(spa, POOL_SCAN_SCRUB);
5173 }
5174 
5175 /*
5176  * Change the guid for the pool.
5177  */
5178 /* ARGSUSED */
5179 void
5180 ztest_reguid(ztest_ds_t *zd, uint64_t id)
5181 {
5182         spa_t *spa = ztest_spa;
5183         uint64_t orig, load;
5184         int error;
5185 
5186         orig = spa_guid(spa);
5187         load = spa_load_guid(spa);
5188 
5189         rw_enter(&ztest_name_lock, RW_WRITER);
5190         error = spa_change_guid(spa);
5191         rw_exit(&ztest_name_lock);
5192 
5193         if (error != 0)
5194                 return;
5195 
5196         if (ztest_opts.zo_verbose >= 4) {
5197                 (void) printf("Changed guid old %llu -> %llu\n",
5198                     (u_longlong_t)orig, (u_longlong_t)spa_guid(spa));
5199         }
5200 
5201         VERIFY3U(orig, !=, spa_guid(spa));
5202         VERIFY3U(load, ==, spa_load_guid(spa));
5203 }
5204 
5205 /*
5206  * Rename the pool to a different name and then rename it back.
5207  */
5208 /* ARGSUSED */
5209 void
5210 ztest_spa_rename(ztest_ds_t *zd, uint64_t id)
5211 {
5212         char *oldname, *newname;
5213         spa_t *spa;
5214 
5215         rw_enter(&ztest_name_lock, RW_WRITER);
5216 
5217         oldname = ztest_opts.zo_pool;
5218         newname = umem_alloc(strlen(oldname) + 5, UMEM_NOFAIL);
5219         (void) strcpy(newname, oldname);
5220         (void) strcat(newname, "_tmp");
5221 
5222         /*
5223          * Do the rename
5224          */
5225         VERIFY3U(0, ==, spa_rename(oldname, newname));
5226 
5227         /*
5228          * Try to open it under the old name, which shouldn't exist
5229          */
5230         VERIFY3U(ENOENT, ==, spa_open(oldname, &spa, FTAG));
5231 
5232         /*
5233          * Open it under the new name and make sure it's still the same spa_t.
5234          */
5235         VERIFY3U(0, ==, spa_open(newname, &spa, FTAG));
5236 
5237         ASSERT(spa == ztest_spa);
5238         spa_close(spa, FTAG);
5239 
5240         /*
5241          * Rename it back to the original
5242          */
5243         VERIFY3U(0, ==, spa_rename(newname, oldname));
5244 
5245         /*
5246          * Make sure it can still be opened
5247          */
5248         VERIFY3U(0, ==, spa_open(oldname, &spa, FTAG));
5249 
5250         ASSERT(spa == ztest_spa);
5251         spa_close(spa, FTAG);
5252 
5253         umem_free(newname, strlen(newname) + 1);
5254 
5255         rw_exit(&ztest_name_lock);
5256 }
5257 
5258 /*
5259  * Verify pool integrity by running zdb.
5260  */
5261 static void
5262 ztest_run_zdb(char *pool)
5263 {
5264         int status;
5265         char zdb[MAXPATHLEN + MAXNAMELEN + 20];
5266         char zbuf[1024];
5267         char *bin;
5268         char *ztest;
5269         char *isa;
5270         int isalen;
5271         FILE *fp;
5272 
5273         (void) realpath(getexecname(), zdb);
5274 
5275         /* zdb lives in /usr/sbin, while ztest lives in /usr/bin */
5276         bin = strstr(zdb, "/usr/bin/");
5277         ztest = strstr(bin, "/ztest");
5278         isa = bin + 8;
5279         isalen = ztest - isa;
5280         isa = strdup(isa);
5281         /* LINTED */
5282         (void) sprintf(bin,
5283             "/usr/sbin%.*s/zdb -bcc%s%s -G -d -U %s %s",
5284             isalen,
5285             isa,
5286             ztest_opts.zo_verbose >= 3 ? "s" : "",
5287             ztest_opts.zo_verbose >= 4 ? "v" : "",
5288             spa_config_path,
5289             pool);
5290         free(isa);
5291 
5292         if (ztest_opts.zo_verbose >= 5)
5293                 (void) printf("Executing %s\n", strstr(zdb, "zdb "));
5294 
5295         fp = popen(zdb, "r");
5296 
5297         while (fgets(zbuf, sizeof (zbuf), fp) != NULL)
5298                 if (ztest_opts.zo_verbose >= 3)
5299                         (void) printf("%s", zbuf);
5300 
5301         status = pclose(fp);
5302 
5303         if (status == 0)
5304                 return;
5305 
5306         ztest_dump_core = 0;
5307         if (WIFEXITED(status))
5308                 fatal(0, "'%s' exit code %d", zdb, WEXITSTATUS(status));
5309         else
5310                 fatal(0, "'%s' died with signal %d", zdb, WTERMSIG(status));
5311 }
5312 
5313 static void
5314 ztest_walk_pool_directory(char *header)
5315 {
5316         spa_t *spa = NULL;
5317 
5318         if (ztest_opts.zo_verbose >= 6)
5319                 (void) printf("%s\n", header);
5320 
5321         mutex_enter(&spa_namespace_lock);
5322         while ((spa = spa_next(spa)) != NULL)
5323                 if (ztest_opts.zo_verbose >= 6)
5324                         (void) printf("\t%s\n", spa_name(spa));
5325         mutex_exit(&spa_namespace_lock);
5326 }
5327 
5328 static void
5329 ztest_spa_import_export(char *oldname, char *newname)
5330 {
5331         nvlist_t *config, *newconfig;
5332         uint64_t pool_guid;
5333         spa_t *spa;
5334         int error;
5335 
5336         if (ztest_opts.zo_verbose >= 4) {
5337                 (void) printf("import/export: old = %s, new = %s\n",
5338                     oldname, newname);
5339         }
5340 
5341         /*
5342          * Clean up from previous runs.
5343          */
5344         (void) spa_destroy(newname);
5345 
5346         /*
5347          * Get the pool's configuration and guid.
5348          */
5349         VERIFY3U(0, ==, spa_open(oldname, &spa, FTAG));
5350 
5351         /*
5352          * Kick off a scrub to tickle scrub/export races.
5353          */
5354         if (ztest_random(2) == 0)
5355                 (void) spa_scan(spa, POOL_SCAN_SCRUB);
5356 
5357         pool_guid = spa_guid(spa);
5358         spa_close(spa, FTAG);
5359 
5360         ztest_walk_pool_directory("pools before export");
5361 
5362         /*
5363          * Export it.
5364          */
5365         VERIFY3U(0, ==, spa_export(oldname, &config, B_FALSE, B_FALSE));
5366 
5367         ztest_walk_pool_directory("pools after export");
5368 
5369         /*
5370          * Try to import it.
5371          */
5372         newconfig = spa_tryimport(config);
5373         ASSERT(newconfig != NULL);
5374         nvlist_free(newconfig);
5375 
5376         /*
5377          * Import it under the new name.
5378          */
5379         error = spa_import(newname, config, NULL, 0);
5380         if (error != 0) {
5381                 dump_nvlist(config, 0);
5382                 fatal(B_FALSE, "couldn't import pool %s as %s: error %u",
5383                     oldname, newname, error);
5384         }
5385 
5386         ztest_walk_pool_directory("pools after import");
5387 
5388         /*
5389          * Try to import it again -- should fail with EEXIST.
5390          */
5391         VERIFY3U(EEXIST, ==, spa_import(newname, config, NULL, 0));
5392 
5393         /*
5394          * Try to import it under a different name -- should fail with EEXIST.
5395          */
5396         VERIFY3U(EEXIST, ==, spa_import(oldname, config, NULL, 0));
5397 
5398         /*
5399          * Verify that the pool is no longer visible under the old name.
5400          */
5401         VERIFY3U(ENOENT, ==, spa_open(oldname, &spa, FTAG));
5402 
5403         /*
5404          * Verify that we can open and close the pool using the new name.
5405          */
5406         VERIFY3U(0, ==, spa_open(newname, &spa, FTAG));
5407         ASSERT(pool_guid == spa_guid(spa));
5408         spa_close(spa, FTAG);
5409 
5410         nvlist_free(config);
5411 }
5412 
5413 static void
5414 ztest_resume(spa_t *spa)
5415 {
5416         if (spa_suspended(spa) && ztest_opts.zo_verbose >= 6)
5417                 (void) printf("resuming from suspended state\n");
5418         spa_vdev_state_enter(spa, SCL_NONE);
5419         vdev_clear(spa, NULL);
5420         (void) spa_vdev_state_exit(spa, NULL, 0);
5421         (void) zio_resume(spa);
5422 }
5423 
5424 static void *
5425 ztest_resume_thread(void *arg)
5426 {
5427         spa_t *spa = arg;
5428 
5429         while (!ztest_exiting) {
5430                 if (spa_suspended(spa))
5431                         ztest_resume(spa);
5432                 (void) poll(NULL, 0, 100);
5433 
5434                 /*
5435                  * Periodically change the zfs_compressed_arc_enabled setting.
5436                  */
5437                 if (ztest_random(10) == 0)
5438                         zfs_compressed_arc_enabled = ztest_random(2);
5439 
5440                 /*
5441                  * Periodically change the zfs_abd_scatter_enabled setting.
5442                  */
5443                 if (ztest_random(10) == 0)
5444                         zfs_abd_scatter_enabled = ztest_random(2);
5445         }
5446         return (NULL);
5447 }
5448 
5449 static void *
5450 ztest_deadman_thread(void *arg)
5451 {
5452         ztest_shared_t *zs = arg;
5453         spa_t *spa = ztest_spa;
5454         hrtime_t delta, total = 0;
5455 
5456         for (;;) {
5457                 delta = zs->zs_thread_stop - zs->zs_thread_start +
5458                     MSEC2NSEC(zfs_deadman_synctime_ms);
5459 
5460                 (void) poll(NULL, 0, (int)NSEC2MSEC(delta));
5461 
5462                 /*
5463                  * If the pool is suspended then fail immediately. Otherwise,
5464                  * check to see if the pool is making any progress. If
5465                  * vdev_deadman() discovers that there hasn't been any recent
5466                  * I/Os then it will end up aborting the tests.
5467                  */
5468                 if (spa_suspended(spa) || spa->spa_root_vdev == NULL) {
5469                         fatal(0, "aborting test after %llu seconds because "
5470                             "pool has transitioned to a suspended state.",
5471                             zfs_deadman_synctime_ms / 1000);
5472                         return (NULL);
5473                 }
5474                 vdev_deadman(spa->spa_root_vdev);
5475 
5476                 total += zfs_deadman_synctime_ms/1000;
5477                 (void) printf("ztest has been running for %lld seconds\n",
5478                     total);
5479         }
5480 }
5481 
5482 static void
5483 ztest_execute(int test, ztest_info_t *zi, uint64_t id)
5484 {
5485         ztest_ds_t *zd = &ztest_ds[id % ztest_opts.zo_datasets];
5486         ztest_shared_callstate_t *zc = ZTEST_GET_SHARED_CALLSTATE(test);
5487         hrtime_t functime = gethrtime();
5488 
5489         for (int i = 0; i < zi->zi_iters; i++)
5490                 zi->zi_func(zd, id);
5491 
5492         functime = gethrtime() - functime;
5493 
5494         atomic_add_64(&zc->zc_count, 1);
5495         atomic_add_64(&zc->zc_time, functime);
5496 
5497         if (ztest_opts.zo_verbose >= 4) {
5498                 Dl_info dli;
5499                 (void) dladdr((void *)zi->zi_func, &dli);
5500                 (void) printf("%6.2f sec in %s\n",
5501                     (double)functime / NANOSEC, dli.dli_sname);
5502         }
5503 }
5504 
5505 static void *
5506 ztest_thread(void *arg)
5507 {
5508         int rand;
5509         uint64_t id = (uintptr_t)arg;
5510         ztest_shared_t *zs = ztest_shared;
5511         uint64_t call_next;
5512         hrtime_t now;
5513         ztest_info_t *zi;
5514         ztest_shared_callstate_t *zc;
5515 
5516         while ((now = gethrtime()) < zs->zs_thread_stop) {
5517                 /*
5518                  * See if it's time to force a crash.
5519                  */
5520                 if (now > zs->zs_thread_kill)
5521                         ztest_kill(zs);
5522 
5523                 /*
5524                  * If we're getting ENOSPC with some regularity, stop.
5525                  */
5526                 if (zs->zs_enospc_count > 10)
5527                         break;
5528 
5529                 /*
5530                  * Pick a random function to execute.
5531                  */
5532                 rand = ztest_random(ZTEST_FUNCS);
5533                 zi = &ztest_info[rand];
5534                 zc = ZTEST_GET_SHARED_CALLSTATE(rand);
5535                 call_next = zc->zc_next;
5536 
5537                 if (now >= call_next &&
5538                     atomic_cas_64(&zc->zc_next, call_next, call_next +
5539                     ztest_random(2 * zi->zi_interval[0] + 1)) == call_next) {
5540                         ztest_execute(rand, zi, id);
5541                 }
5542         }
5543 
5544         return (NULL);
5545 }
5546 
5547 static void
5548 ztest_dataset_name(char *dsname, char *pool, int d)
5549 {
5550         (void) snprintf(dsname, ZFS_MAX_DATASET_NAME_LEN, "%s/ds_%d", pool, d);
5551 }
5552 
5553 static void
5554 ztest_dataset_destroy(int d)
5555 {
5556         char name[ZFS_MAX_DATASET_NAME_LEN];
5557 
5558         ztest_dataset_name(name, ztest_opts.zo_pool, d);
5559 
5560         if (ztest_opts.zo_verbose >= 3)
5561                 (void) printf("Destroying %s to free up space\n", name);
5562 
5563         /*
5564          * Cleanup any non-standard clones and snapshots.  In general,
5565          * ztest thread t operates on dataset (t % zopt_datasets),
5566          * so there may be more than one thing to clean up.
5567          */
5568         for (int t = d; t < ztest_opts.zo_threads;
5569             t += ztest_opts.zo_datasets) {
5570                 ztest_dsl_dataset_cleanup(name, t);
5571         }
5572 
5573         (void) dmu_objset_find(name, ztest_objset_destroy_cb, NULL,
5574             DS_FIND_SNAPSHOTS | DS_FIND_CHILDREN);
5575 }
5576 
5577 static void
5578 ztest_dataset_dirobj_verify(ztest_ds_t *zd)
5579 {
5580         uint64_t usedobjs, dirobjs, scratch;
5581 
5582         /*
5583          * ZTEST_DIROBJ is the object directory for the entire dataset.
5584          * Therefore, the number of objects in use should equal the
5585          * number of ZTEST_DIROBJ entries, +1 for ZTEST_DIROBJ itself.
5586          * If not, we have an object leak.
5587          *
5588          * Note that we can only check this in ztest_dataset_open(),
5589          * when the open-context and syncing-context values agree.
5590          * That's because zap_count() returns the open-context value,
5591          * while dmu_objset_space() returns the rootbp fill count.
5592          */
5593         VERIFY3U(0, ==, zap_count(zd->zd_os, ZTEST_DIROBJ, &dirobjs));
5594         dmu_objset_space(zd->zd_os, &scratch, &scratch, &usedobjs, &scratch);
5595         ASSERT3U(dirobjs + 1, ==, usedobjs);
5596 }
5597 
5598 static int
5599 ztest_dataset_open(int d)
5600 {
5601         ztest_ds_t *zd = &ztest_ds[d];
5602         uint64_t committed_seq = ZTEST_GET_SHARED_DS(d)->zd_seq;
5603         objset_t *os;
5604         zilog_t *zilog;
5605         char name[ZFS_MAX_DATASET_NAME_LEN];
5606         int error;
5607 
5608         ztest_dataset_name(name, ztest_opts.zo_pool, d);
5609 
5610         rw_enter(&ztest_name_lock, RW_READER);
5611 
5612         error = ztest_dataset_create(name);
5613         if (error == ENOSPC) {
5614                 rw_exit(&ztest_name_lock);
5615                 ztest_record_enospc(FTAG);
5616                 return (error);
5617         }
5618         ASSERT(error == 0 || error == EEXIST);
5619 
5620         VERIFY0(dmu_objset_own(name, DMU_OST_OTHER, B_FALSE, zd, &os));
5621         rw_exit(&ztest_name_lock);
5622 
5623         ztest_zd_init(zd, ZTEST_GET_SHARED_DS(d), os);
5624 
5625         zilog = zd->zd_zilog;
5626 
5627         if (zilog->zl_header->zh_claim_lr_seq != 0 &&
5628             zilog->zl_header->zh_claim_lr_seq < committed_seq)
5629                 fatal(0, "missing log records: claimed %llu < committed %llu",
5630                     zilog->zl_header->zh_claim_lr_seq, committed_seq);
5631 
5632         ztest_dataset_dirobj_verify(zd);
5633 
5634         zil_replay(os, zd, ztest_replay_vector);
5635 
5636         ztest_dataset_dirobj_verify(zd);
5637 
5638         if (ztest_opts.zo_verbose >= 6)
5639                 (void) printf("%s replay %llu blocks, %llu records, seq %llu\n",
5640                     zd->zd_name,
5641                     (u_longlong_t)zilog->zl_parse_blk_count,
5642                     (u_longlong_t)zilog->zl_parse_lr_count,
5643                     (u_longlong_t)zilog->zl_replaying_seq);
5644 
5645         zilog = zil_open(os, ztest_get_data);
5646 
5647         if (zilog->zl_replaying_seq != 0 &&
5648             zilog->zl_replaying_seq < committed_seq)
5649                 fatal(0, "missing log records: replayed %llu < committed %llu",
5650                     zilog->zl_replaying_seq, committed_seq);
5651 
5652         return (0);
5653 }
5654 
5655 static void
5656 ztest_dataset_close(int d)
5657 {
5658         ztest_ds_t *zd = &ztest_ds[d];
5659 
5660         zil_close(zd->zd_zilog);
5661         dmu_objset_disown(zd->zd_os, zd);
5662 
5663         ztest_zd_fini(zd);
5664 }
5665 
5666 /*
5667  * Kick off threads to run tests on all datasets in parallel.
5668  */
5669 static void
5670 ztest_run(ztest_shared_t *zs)
5671 {
5672         pthread_t *tid;
5673         spa_t *spa;
5674         objset_t *os;
5675         pthread_t resume_tid;
5676         int error;
5677 
5678         ztest_exiting = B_FALSE;
5679 
5680         /*
5681          * Initialize parent/child shared state.
5682          */
5683         mutex_init(&ztest_vdev_lock, NULL, USYNC_THREAD, NULL);
5684         rw_init(&ztest_name_lock, NULL, USYNC_THREAD, NULL);
5685 
5686         zs->zs_thread_start = gethrtime();
5687         zs->zs_thread_stop =
5688             zs->zs_thread_start + ztest_opts.zo_passtime * NANOSEC;
5689         zs->zs_thread_stop = MIN(zs->zs_thread_stop, zs->zs_proc_stop);
5690         zs->zs_thread_kill = zs->zs_thread_stop;
5691         if (ztest_random(100) < ztest_opts.zo_killrate) {
5692                 zs->zs_thread_kill -=
5693                     ztest_random(ztest_opts.zo_passtime * NANOSEC);
5694         }
5695 
5696         mutex_init(&zcl.zcl_callbacks_lock, NULL, USYNC_THREAD, NULL);
5697 
5698         list_create(&zcl.zcl_callbacks, sizeof (ztest_cb_data_t),
5699             offsetof(ztest_cb_data_t, zcd_node));
5700 
5701         /*
5702          * Open our pool.
5703          */
5704         kernel_init(FREAD | FWRITE);
5705         VERIFY0(spa_open(ztest_opts.zo_pool, &spa, FTAG));
5706         spa->spa_debug = B_TRUE;
5707         metaslab_preload_limit = ztest_random(20) + 1;
5708         ztest_spa = spa;
5709 
5710         dmu_objset_stats_t dds;
5711         VERIFY0(dmu_objset_own(ztest_opts.zo_pool,
5712             DMU_OST_ANY, B_TRUE, FTAG, &os));
5713         dsl_pool_config_enter(dmu_objset_pool(os), FTAG);
5714         dmu_objset_fast_stat(os, &dds);
5715         dsl_pool_config_exit(dmu_objset_pool(os), FTAG);
5716         zs->zs_guid = dds.dds_guid;
5717         dmu_objset_disown(os, FTAG);
5718 
5719         spa->spa_dedup_ditto = 2 * ZIO_DEDUPDITTO_MIN;
5720 
5721         /*
5722          * We don't expect the pool to suspend unless maxfaults == 0,
5723          * in which case ztest_fault_inject() temporarily takes away
5724          * the only valid replica.
5725          */
5726         if (MAXFAULTS() == 0)
5727                 spa->spa_failmode = ZIO_FAILURE_MODE_WAIT;
5728         else
5729                 spa->spa_failmode = ZIO_FAILURE_MODE_PANIC;
5730 
5731         /*
5732          * Create a thread to periodically resume suspended I/O.
5733          */
5734         VERIFY(pthread_create(&resume_tid, NULL, ztest_resume_thread,
5735             spa) == 0);
5736 
5737         /*
5738          * Create a deadman thread to abort() if we hang.
5739          */
5740         VERIFY(pthread_create(&resume_tid, NULL, ztest_deadman_thread,
5741             zs) == 0);
5742 
5743         /*
5744          * Verify that we can safely inquire about about any object,
5745          * whether it's allocated or not.  To make it interesting,
5746          * we probe a 5-wide window around each power of two.
5747          * This hits all edge cases, including zero and the max.
5748          */
5749         for (int t = 0; t < 64; t++) {
5750                 for (int d = -5; d <= 5; d++) {
5751                         error = dmu_object_info(spa->spa_meta_objset,
5752                             (1ULL << t) + d, NULL);
5753                         ASSERT(error == 0 || error == ENOENT ||
5754                             error == EINVAL);
5755                 }
5756         }
5757 
5758         /*
5759          * If we got any ENOSPC errors on the previous run, destroy something.
5760          */
5761         if (zs->zs_enospc_count != 0) {
5762                 int d = ztest_random(ztest_opts.zo_datasets);
5763                 ztest_dataset_destroy(d);
5764         }
5765         zs->zs_enospc_count = 0;
5766 
5767         tid = umem_zalloc(ztest_opts.zo_threads * sizeof (pthread_t),
5768             UMEM_NOFAIL);
5769 
5770         if (ztest_opts.zo_verbose >= 4)
5771                 (void) printf("starting main threads...\n");
5772 
5773         /*
5774          * Kick off all the tests that run in parallel.
5775          */
5776         for (int t = 0; t < ztest_opts.zo_threads; t++) {
5777                 if (t < ztest_opts.zo_datasets &&
5778                     ztest_dataset_open(t) != 0)
5779                         return;
5780                 VERIFY(pthread_create(&tid[t], NULL, ztest_thread,
5781                     (void *)(uintptr_t)t) == 0);
5782         }
5783 
5784         /*
5785          * Wait for all of the tests to complete.  We go in reverse order
5786          * so we don't close datasets while threads are still using them.
5787          */
5788         for (int t = ztest_opts.zo_threads - 1; t >= 0; t--) {
5789                 VERIFY(pthread_join(tid[t], NULL) == 0);
5790                 if (t < ztest_opts.zo_datasets)
5791                         ztest_dataset_close(t);
5792         }
5793 
5794         txg_wait_synced(spa_get_dsl(spa), 0);
5795 
5796         zs->zs_alloc = metaslab_class_get_alloc(spa_normal_class(spa));
5797         zs->zs_space = metaslab_class_get_space(spa_normal_class(spa));
5798         zfs_dbgmsg_print(FTAG);
5799 
5800         umem_free(tid, ztest_opts.zo_threads * sizeof (pthread_t));
5801 
5802         /* Kill the resume thread */
5803         ztest_exiting = B_TRUE;
5804         VERIFY(pthread_join(resume_tid, NULL) == 0);
5805         ztest_resume(spa);
5806 
5807         /*
5808          * Right before closing the pool, kick off a bunch of async I/O;
5809          * spa_close() should wait for it to complete.
5810          */
5811         for (uint64_t object = 1; object < 50; object++) {
5812                 dmu_prefetch(spa->spa_meta_objset, object, 0, 0, 1ULL << 20,
5813                     ZIO_PRIORITY_SYNC_READ);
5814         }
5815 
5816         spa_close(spa, FTAG);
5817 
5818         /*
5819          * Verify that we can loop over all pools.
5820          */
5821         mutex_enter(&spa_namespace_lock);
5822         for (spa = spa_next(NULL); spa != NULL; spa = spa_next(spa))
5823                 if (ztest_opts.zo_verbose > 3)
5824                         (void) printf("spa_next: found %s\n", spa_name(spa));
5825         mutex_exit(&spa_namespace_lock);
5826 
5827         /*
5828          * Verify that we can export the pool and reimport it under a
5829          * different name.
5830          */
5831         if (ztest_random(2) == 0) {
5832                 char name[ZFS_MAX_DATASET_NAME_LEN];
5833                 (void) snprintf(name, sizeof (name), "%s_import",
5834                     ztest_opts.zo_pool);
5835                 ztest_spa_import_export(ztest_opts.zo_pool, name);
5836                 ztest_spa_import_export(name, ztest_opts.zo_pool);
5837         }
5838 
5839         kernel_fini();
5840 
5841         list_destroy(&zcl.zcl_callbacks);
5842 
5843         mutex_destroy(&zcl.zcl_callbacks_lock);
5844 
5845         rw_destroy(&ztest_name_lock);
5846         mutex_destroy(&ztest_vdev_lock);
5847 }
5848 
5849 static void
5850 ztest_freeze(void)
5851 {
5852         ztest_ds_t *zd = &ztest_ds[0];
5853         spa_t *spa;
5854         int numloops = 0;
5855 
5856         if (ztest_opts.zo_verbose >= 3)
5857                 (void) printf("testing spa_freeze()...\n");
5858 
5859         kernel_init(FREAD | FWRITE);
5860         VERIFY3U(0, ==, spa_open(ztest_opts.zo_pool, &spa, FTAG));
5861         VERIFY3U(0, ==, ztest_dataset_open(0));
5862         spa->spa_debug = B_TRUE;
5863         ztest_spa = spa;
5864 
5865         /*
5866          * Force the first log block to be transactionally allocated.
5867          * We have to do this before we freeze the pool -- otherwise
5868          * the log chain won't be anchored.
5869          */
5870         while (BP_IS_HOLE(&zd->zd_zilog->zl_header->zh_log)) {
5871                 ztest_dmu_object_alloc_free(zd, 0);
5872                 zil_commit(zd->zd_zilog, 0);
5873         }
5874 
5875         txg_wait_synced(spa_get_dsl(spa), 0);
5876 
5877         /*
5878          * Freeze the pool.  This stops spa_sync() from doing anything,
5879          * so that the only way to record changes from now on is the ZIL.
5880          */
5881         spa_freeze(spa);
5882 
5883         /*
5884          * Because it is hard to predict how much space a write will actually
5885          * require beforehand, we leave ourselves some fudge space to write over
5886          * capacity.
5887          */
5888         uint64_t capacity = metaslab_class_get_space(spa_normal_class(spa)) / 2;
5889 
5890         /*
5891          * Run tests that generate log records but don't alter the pool config
5892          * or depend on DSL sync tasks (snapshots, objset create/destroy, etc).
5893          * We do a txg_wait_synced() after each iteration to force the txg
5894          * to increase well beyond the last synced value in the uberblock.
5895          * The ZIL should be OK with that.
5896          *
5897          * Run a random number of times less than zo_maxloops and ensure we do
5898          * not run out of space on the pool.
5899          */
5900         while (ztest_random(10) != 0 &&
5901             numloops++ < ztest_opts.zo_maxloops &&
5902             metaslab_class_get_alloc(spa_normal_class(spa)) < capacity) {
5903                 ztest_od_t od;
5904                 ztest_od_init(&od, 0, FTAG, 0, DMU_OT_UINT64_OTHER, 0, 0);
5905                 VERIFY0(ztest_object_init(zd, &od, sizeof (od), B_FALSE));
5906                 ztest_io(zd, od.od_object,
5907                     ztest_random(ZTEST_RANGE_LOCKS) << SPA_MAXBLOCKSHIFT);
5908                 txg_wait_synced(spa_get_dsl(spa), 0);
5909         }
5910 
5911         /*
5912          * Commit all of the changes we just generated.
5913          */
5914         zil_commit(zd->zd_zilog, 0);
5915         txg_wait_synced(spa_get_dsl(spa), 0);
5916 
5917         /*
5918          * Close our dataset and close the pool.
5919          */
5920         ztest_dataset_close(0);
5921         spa_close(spa, FTAG);
5922         kernel_fini();
5923 
5924         /*
5925          * Open and close the pool and dataset to induce log replay.
5926          */
5927         kernel_init(FREAD | FWRITE);
5928         VERIFY3U(0, ==, spa_open(ztest_opts.zo_pool, &spa, FTAG));
5929         ASSERT(spa_freeze_txg(spa) == UINT64_MAX);
5930         VERIFY3U(0, ==, ztest_dataset_open(0));
5931         ztest_dataset_close(0);
5932 
5933         spa->spa_debug = B_TRUE;
5934         ztest_spa = spa;
5935         txg_wait_synced(spa_get_dsl(spa), 0);
5936         ztest_reguid(NULL, 0);
5937 
5938         spa_close(spa, FTAG);
5939         kernel_fini();
5940 }
5941 
5942 void
5943 print_time(hrtime_t t, char *timebuf)
5944 {
5945         hrtime_t s = t / NANOSEC;
5946         hrtime_t m = s / 60;
5947         hrtime_t h = m / 60;
5948         hrtime_t d = h / 24;
5949 
5950         s -= m * 60;
5951         m -= h * 60;
5952         h -= d * 24;
5953 
5954         timebuf[0] = '\0';
5955 
5956         if (d)
5957                 (void) sprintf(timebuf,
5958                     "%llud%02lluh%02llum%02llus", d, h, m, s);
5959         else if (h)
5960                 (void) sprintf(timebuf, "%lluh%02llum%02llus", h, m, s);
5961         else if (m)
5962                 (void) sprintf(timebuf, "%llum%02llus", m, s);
5963         else
5964                 (void) sprintf(timebuf, "%llus", s);
5965 }
5966 
5967 static nvlist_t *
5968 make_random_props()
5969 {
5970         nvlist_t *props;
5971 
5972         VERIFY(nvlist_alloc(&props, NV_UNIQUE_NAME, 0) == 0);
5973         if (ztest_random(2) == 0)
5974                 return (props);
5975         VERIFY(nvlist_add_uint64(props, "autoreplace", 1) == 0);
5976 
5977         return (props);
5978 }
5979 
5980 /*
5981  * Create a storage pool with the given name and initial vdev size.
5982  * Then test spa_freeze() functionality.
5983  */
5984 static void
5985 ztest_init(ztest_shared_t *zs)
5986 {
5987         spa_t *spa;
5988         nvlist_t *nvroot, *props;
5989 
5990         mutex_init(&ztest_vdev_lock, NULL, USYNC_THREAD, NULL);
5991         rw_init(&ztest_name_lock, NULL, USYNC_THREAD, NULL);
5992 
5993         kernel_init(FREAD | FWRITE);
5994 
5995         /*
5996          * Create the storage pool.
5997          */
5998         (void) spa_destroy(ztest_opts.zo_pool);
5999         ztest_shared->zs_vdev_next_leaf = 0;
6000         zs->zs_splits = 0;
6001         zs->zs_mirrors = ztest_opts.zo_mirrors;
6002         nvroot = make_vdev_root(NULL, NULL, NULL, ztest_opts.zo_vdev_size, 0,
6003             0, ztest_opts.zo_raidz, zs->zs_mirrors, 1);
6004         props = make_random_props();
6005         for (int i = 0; i < SPA_FEATURES; i++) {
6006                 char buf[1024];
6007                 (void) snprintf(buf, sizeof (buf), "feature@%s",
6008                     spa_feature_table[i].fi_uname);
6009                 VERIFY3U(0, ==, nvlist_add_uint64(props, buf, 0));
6010         }
6011         VERIFY3U(0, ==, spa_create(ztest_opts.zo_pool, nvroot, props, NULL));
6012         nvlist_free(nvroot);
6013         nvlist_free(props);
6014 
6015         VERIFY3U(0, ==, spa_open(ztest_opts.zo_pool, &spa, FTAG));
6016         zs->zs_metaslab_sz =
6017             1ULL << spa->spa_root_vdev->vdev_child[0]->vdev_ms_shift;
6018 
6019         spa_close(spa, FTAG);
6020 
6021         kernel_fini();
6022 
6023         ztest_run_zdb(ztest_opts.zo_pool);
6024 
6025         ztest_freeze();
6026 
6027         ztest_run_zdb(ztest_opts.zo_pool);
6028 
6029         rw_destroy(&ztest_name_lock);
6030         mutex_destroy(&ztest_vdev_lock);
6031 }
6032 
6033 static void
6034 setup_data_fd(void)
6035 {
6036         static char ztest_name_data[] = "/tmp/ztest.data.XXXXXX";
6037 
6038         ztest_fd_data = mkstemp(ztest_name_data);
6039         ASSERT3S(ztest_fd_data, >=, 0);
6040         (void) unlink(ztest_name_data);
6041 }
6042 
6043 
6044 static int
6045 shared_data_size(ztest_shared_hdr_t *hdr)
6046 {
6047         int size;
6048 
6049         size = hdr->zh_hdr_size;
6050         size += hdr->zh_opts_size;
6051         size += hdr->zh_size;
6052         size += hdr->zh_stats_size * hdr->zh_stats_count;
6053         size += hdr->zh_ds_size * hdr->zh_ds_count;
6054 
6055         return (size);
6056 }
6057 
6058 static void
6059 setup_hdr(void)
6060 {
6061         int size;
6062         ztest_shared_hdr_t *hdr;
6063 
6064         hdr = (void *)mmap(0, P2ROUNDUP(sizeof (*hdr), getpagesize()),
6065             PROT_READ | PROT_WRITE, MAP_SHARED, ztest_fd_data, 0);
6066         ASSERT(hdr != MAP_FAILED);
6067 
6068         VERIFY3U(0, ==, ftruncate(ztest_fd_data, sizeof (ztest_shared_hdr_t)));
6069 
6070         hdr->zh_hdr_size = sizeof (ztest_shared_hdr_t);
6071         hdr->zh_opts_size = sizeof (ztest_shared_opts_t);
6072         hdr->zh_size = sizeof (ztest_shared_t);
6073         hdr->zh_stats_size = sizeof (ztest_shared_callstate_t);
6074         hdr->zh_stats_count = ZTEST_FUNCS;
6075         hdr->zh_ds_size = sizeof (ztest_shared_ds_t);
6076         hdr->zh_ds_count = ztest_opts.zo_datasets;
6077 
6078         size = shared_data_size(hdr);
6079         VERIFY3U(0, ==, ftruncate(ztest_fd_data, size));
6080 
6081         (void) munmap((caddr_t)hdr, P2ROUNDUP(sizeof (*hdr), getpagesize()));
6082 }
6083 
6084 static void
6085 setup_data(void)
6086 {
6087         int size, offset;
6088         ztest_shared_hdr_t *hdr;
6089         uint8_t *buf;
6090 
6091         hdr = (void *)mmap(0, P2ROUNDUP(sizeof (*hdr), getpagesize()),
6092             PROT_READ, MAP_SHARED, ztest_fd_data, 0);
6093         ASSERT(hdr != MAP_FAILED);
6094 
6095         size = shared_data_size(hdr);
6096 
6097         (void) munmap((caddr_t)hdr, P2ROUNDUP(sizeof (*hdr), getpagesize()));
6098         hdr = ztest_shared_hdr = (void *)mmap(0, P2ROUNDUP(size, getpagesize()),
6099             PROT_READ | PROT_WRITE, MAP_SHARED, ztest_fd_data, 0);
6100         ASSERT(hdr != MAP_FAILED);
6101         buf = (uint8_t *)hdr;
6102 
6103         offset = hdr->zh_hdr_size;
6104         ztest_shared_opts = (void *)&buf[offset];
6105         offset += hdr->zh_opts_size;
6106         ztest_shared = (void *)&buf[offset];
6107         offset += hdr->zh_size;
6108         ztest_shared_callstate = (void *)&buf[offset];
6109         offset += hdr->zh_stats_size * hdr->zh_stats_count;
6110         ztest_shared_ds = (void *)&buf[offset];
6111 }
6112 
6113 static boolean_t
6114 exec_child(char *cmd, char *libpath, boolean_t ignorekill, int *statusp)
6115 {
6116         pid_t pid;
6117         int status;
6118         char *cmdbuf = NULL;
6119 
6120         pid = fork();
6121 
6122         if (cmd == NULL) {
6123                 cmdbuf = umem_alloc(MAXPATHLEN, UMEM_NOFAIL);
6124                 (void) strlcpy(cmdbuf, getexecname(), MAXPATHLEN);
6125                 cmd = cmdbuf;
6126         }
6127 
6128         if (pid == -1)
6129                 fatal(1, "fork failed");
6130 
6131         if (pid == 0) { /* child */
6132                 char *emptyargv[2] = { cmd, NULL };
6133                 char fd_data_str[12];
6134 
6135                 struct rlimit rl = { 1024, 1024 };
6136                 (void) setrlimit(RLIMIT_NOFILE, &rl);
6137 
6138                 (void) close(ztest_fd_rand);
6139                 VERIFY3U(11, >=,
6140                     snprintf(fd_data_str, 12, "%d", ztest_fd_data));
6141                 VERIFY0(setenv("ZTEST_FD_DATA", fd_data_str, 1));
6142 
6143                 (void) enable_extended_FILE_stdio(-1, -1);
6144                 if (libpath != NULL)
6145                         VERIFY(0 == setenv("LD_LIBRARY_PATH", libpath, 1));
6146                 (void) execv(cmd, emptyargv);
6147                 ztest_dump_core = B_FALSE;
6148                 fatal(B_TRUE, "exec failed: %s", cmd);
6149         }
6150 
6151         if (cmdbuf != NULL) {
6152                 umem_free(cmdbuf, MAXPATHLEN);
6153                 cmd = NULL;
6154         }
6155 
6156         while (waitpid(pid, &status, 0) != pid)
6157                 continue;
6158         if (statusp != NULL)
6159                 *statusp = status;
6160 
6161         if (WIFEXITED(status)) {
6162                 if (WEXITSTATUS(status) != 0) {
6163                         (void) fprintf(stderr, "child exited with code %d\n",
6164                             WEXITSTATUS(status));
6165                         exit(2);
6166                 }
6167                 return (B_FALSE);
6168         } else if (WIFSIGNALED(status)) {
6169                 if (!ignorekill || WTERMSIG(status) != SIGKILL) {
6170                         (void) fprintf(stderr, "child died with signal %d\n",
6171                             WTERMSIG(status));
6172                         exit(3);
6173                 }
6174                 return (B_TRUE);
6175         } else {
6176                 (void) fprintf(stderr, "something strange happened to child\n");
6177                 exit(4);
6178                 /* NOTREACHED */
6179         }
6180 }
6181 
6182 static void
6183 ztest_run_init(void)
6184 {
6185         ztest_shared_t *zs = ztest_shared;
6186 
6187         ASSERT(ztest_opts.zo_init != 0);
6188 
6189         /*
6190          * Blow away any existing copy of zpool.cache
6191          */
6192         (void) remove(spa_config_path);
6193 
6194         /*
6195          * Create and initialize our storage pool.
6196          */
6197         for (int i = 1; i <= ztest_opts.zo_init; i++) {
6198                 bzero(zs, sizeof (ztest_shared_t));
6199                 if (ztest_opts.zo_verbose >= 3 &&
6200                     ztest_opts.zo_init != 1) {
6201                         (void) printf("ztest_init(), pass %d\n", i);
6202                 }
6203                 ztest_init(zs);
6204         }
6205 }
6206 
6207 int
6208 main(int argc, char **argv)
6209 {
6210         int kills = 0;
6211         int iters = 0;
6212         int older = 0;
6213         int newer = 0;
6214         ztest_shared_t *zs;
6215         ztest_info_t *zi;
6216         ztest_shared_callstate_t *zc;
6217         char timebuf[100];
6218         char numbuf[NN_NUMBUF_SZ];
6219         spa_t *spa;
6220         char *cmd;
6221         boolean_t hasalt;
6222         char *fd_data_str = getenv("ZTEST_FD_DATA");
6223 
6224         (void) setvbuf(stdout, NULL, _IOLBF, 0);
6225 
6226         dprintf_setup(&argc, argv);
6227         zfs_deadman_synctime_ms = 300000;
6228 
6229         ztest_fd_rand = open("/dev/urandom", O_RDONLY);
6230         ASSERT3S(ztest_fd_rand, >=, 0);
6231 
6232         if (!fd_data_str) {
6233                 process_options(argc, argv);
6234 
6235                 setup_data_fd();
6236                 setup_hdr();
6237                 setup_data();
6238                 bcopy(&ztest_opts, ztest_shared_opts,
6239                     sizeof (*ztest_shared_opts));
6240         } else {
6241                 ztest_fd_data = atoi(fd_data_str);
6242                 setup_data();
6243                 bcopy(ztest_shared_opts, &ztest_opts, sizeof (ztest_opts));
6244         }
6245         ASSERT3U(ztest_opts.zo_datasets, ==, ztest_shared_hdr->zh_ds_count);
6246 
6247         /* Override location of zpool.cache */
6248         VERIFY3U(asprintf((char **)&spa_config_path, "%s/zpool.cache",
6249             ztest_opts.zo_dir), !=, -1);
6250 
6251         ztest_ds = umem_alloc(ztest_opts.zo_datasets * sizeof (ztest_ds_t),
6252             UMEM_NOFAIL);
6253         zs = ztest_shared;
6254 
6255         if (fd_data_str) {
6256                 metaslab_gang_bang = ztest_opts.zo_metaslab_gang_bang;
6257                 metaslab_df_alloc_threshold =
6258                     zs->zs_metaslab_df_alloc_threshold;
6259 
6260                 if (zs->zs_do_init)
6261                         ztest_run_init();
6262                 else
6263                         ztest_run(zs);
6264                 exit(0);
6265         }
6266 
6267         hasalt = (strlen(ztest_opts.zo_alt_ztest) != 0);
6268 
6269         if (ztest_opts.zo_verbose >= 1) {
6270                 (void) printf("%llu vdevs, %d datasets, %d threads,"
6271                     " %llu seconds...\n",
6272                     (u_longlong_t)ztest_opts.zo_vdevs,
6273                     ztest_opts.zo_datasets,
6274                     ztest_opts.zo_threads,
6275                     (u_longlong_t)ztest_opts.zo_time);
6276         }
6277 
6278         cmd = umem_alloc(MAXNAMELEN, UMEM_NOFAIL);
6279         (void) strlcpy(cmd, getexecname(), MAXNAMELEN);
6280 
6281         zs->zs_do_init = B_TRUE;
6282         if (strlen(ztest_opts.zo_alt_ztest) != 0) {
6283                 if (ztest_opts.zo_verbose >= 1) {
6284                         (void) printf("Executing older ztest for "
6285                             "initialization: %s\n", ztest_opts.zo_alt_ztest);
6286                 }
6287                 VERIFY(!exec_child(ztest_opts.zo_alt_ztest,
6288                     ztest_opts.zo_alt_libpath, B_FALSE, NULL));
6289         } else {
6290                 VERIFY(!exec_child(NULL, NULL, B_FALSE, NULL));
6291         }
6292         zs->zs_do_init = B_FALSE;
6293 
6294         zs->zs_proc_start = gethrtime();
6295         zs->zs_proc_stop = zs->zs_proc_start + ztest_opts.zo_time * NANOSEC;
6296 
6297         for (int f = 0; f < ZTEST_FUNCS; f++) {
6298                 zi = &ztest_info[f];
6299                 zc = ZTEST_GET_SHARED_CALLSTATE(f);
6300                 if (zs->zs_proc_start + zi->zi_interval[0] > zs->zs_proc_stop)
6301                         zc->zc_next = UINT64_MAX;
6302                 else
6303                         zc->zc_next = zs->zs_proc_start +
6304                             ztest_random(2 * zi->zi_interval[0] + 1);
6305         }
6306 
6307         /*
6308          * Run the tests in a loop.  These tests include fault injection
6309          * to verify that self-healing data works, and forced crashes
6310          * to verify that we never lose on-disk consistency.
6311          */
6312         while (gethrtime() < zs->zs_proc_stop) {
6313                 int status;
6314                 boolean_t killed;
6315 
6316                 /*
6317                  * Initialize the workload counters for each function.
6318                  */
6319                 for (int f = 0; f < ZTEST_FUNCS; f++) {
6320                         zc = ZTEST_GET_SHARED_CALLSTATE(f);
6321                         zc->zc_count = 0;
6322                         zc->zc_time = 0;
6323                 }
6324 
6325                 /* Set the allocation switch size */
6326                 zs->zs_metaslab_df_alloc_threshold =
6327                     ztest_random(zs->zs_metaslab_sz / 4) + 1;
6328 
6329                 if (!hasalt || ztest_random(2) == 0) {
6330                         if (hasalt && ztest_opts.zo_verbose >= 1) {
6331                                 (void) printf("Executing newer ztest: %s\n",
6332                                     cmd);
6333                         }
6334                         newer++;
6335                         killed = exec_child(cmd, NULL, B_TRUE, &status);
6336                 } else {
6337                         if (hasalt && ztest_opts.zo_verbose >= 1) {
6338                                 (void) printf("Executing older ztest: %s\n",
6339                                     ztest_opts.zo_alt_ztest);
6340                         }
6341                         older++;
6342                         killed = exec_child(ztest_opts.zo_alt_ztest,
6343                             ztest_opts.zo_alt_libpath, B_TRUE, &status);
6344                 }
6345 
6346                 if (killed)
6347                         kills++;
6348                 iters++;
6349 
6350                 if (ztest_opts.zo_verbose >= 1) {
6351                         hrtime_t now = gethrtime();
6352 
6353                         now = MIN(now, zs->zs_proc_stop);
6354                         print_time(zs->zs_proc_stop - now, timebuf);
6355                         nicenum(zs->zs_space, numbuf, sizeof (numbuf));
6356 
6357                         (void) printf("Pass %3d, %8s, %3llu ENOSPC, "
6358                             "%4.1f%% of %5s used, %3.0f%% done, %8s to go\n",
6359                             iters,
6360                             WIFEXITED(status) ? "Complete" : "SIGKILL",
6361                             (u_longlong_t)zs->zs_enospc_count,
6362                             100.0 * zs->zs_alloc / zs->zs_space,
6363                             numbuf,
6364                             100.0 * (now - zs->zs_proc_start) /
6365                             (ztest_opts.zo_time * NANOSEC), timebuf);
6366                 }
6367 
6368                 if (ztest_opts.zo_verbose >= 2) {
6369                         (void) printf("\nWorkload summary:\n\n");
6370                         (void) printf("%7s %9s   %s\n",
6371                             "Calls", "Time", "Function");
6372                         (void) printf("%7s %9s   %s\n",
6373                             "-----", "----", "--------");
6374                         for (int f = 0; f < ZTEST_FUNCS; f++) {
6375                                 Dl_info dli;
6376 
6377                                 zi = &ztest_info[f];
6378                                 zc = ZTEST_GET_SHARED_CALLSTATE(f);
6379                                 print_time(zc->zc_time, timebuf);
6380                                 (void) dladdr((void *)zi->zi_func, &dli);
6381                                 (void) printf("%7llu %9s   %s\n",
6382                                     (u_longlong_t)zc->zc_count, timebuf,
6383                                     dli.dli_sname);
6384                         }
6385                         (void) printf("\n");
6386                 }
6387 
6388                 /*
6389                  * It's possible that we killed a child during a rename test,
6390                  * in which case we'll have a 'ztest_tmp' pool lying around
6391                  * instead of 'ztest'.  Do a blind rename in case this happened.
6392                  */
6393                 kernel_init(FREAD);
6394                 if (spa_open(ztest_opts.zo_pool, &spa, FTAG) == 0) {
6395                         spa_close(spa, FTAG);
6396                 } else {
6397                         char tmpname[ZFS_MAX_DATASET_NAME_LEN];
6398                         kernel_fini();
6399                         kernel_init(FREAD | FWRITE);
6400                         (void) snprintf(tmpname, sizeof (tmpname), "%s_tmp",
6401                             ztest_opts.zo_pool);
6402                         (void) spa_rename(tmpname, ztest_opts.zo_pool);
6403                 }
6404                 kernel_fini();
6405 
6406                 ztest_run_zdb(ztest_opts.zo_pool);
6407         }
6408 
6409         if (ztest_opts.zo_verbose >= 1) {
6410                 if (hasalt) {
6411                         (void) printf("%d runs of older ztest: %s\n", older,
6412                             ztest_opts.zo_alt_ztest);
6413                         (void) printf("%d runs of newer ztest: %s\n", newer,
6414                             cmd);
6415                 }
6416                 (void) printf("%d killed, %d completed, %.0f%% kill rate\n",
6417                     kills, iters - kills, (100.0 * kills) / MAX(1, iters));
6418         }
6419 
6420         umem_free(cmd, MAXNAMELEN);
6421 
6422         return (0);
6423 }