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