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