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