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