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