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