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