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