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