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