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