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