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