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