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