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