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