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