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