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