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