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