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