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