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