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