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