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