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