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