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