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