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