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