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