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