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