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