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