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