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