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