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