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