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