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