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