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