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