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