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