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