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