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