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