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