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