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