xref: /illumos-gate/usr/src/cmd/ztest/ztest.c (revision fa9e4066f08beec538e775443c5be79dd423fcab)
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, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 /*
30  * The objective of this program is to provide a DMU/ZAP/SPA stress test
31  * that runs entirely in userland, is easy to use, and easy to extend.
32  *
33  * The overall design of the ztest program is as follows:
34  *
35  * (1) For each major functional area (e.g. adding vdevs to a pool,
36  *     creating and destroying datasets, reading and writing objects, etc)
37  *     we have a simple routine to test that functionality.  These
38  *     individual routines do not have to do anything "stressful".
39  *
40  * (2) We turn these simple functionality tests into a stress test by
41  *     running them all in parallel, with as many threads as desired,
42  *     and spread across as many datasets, objects, and vdevs as desired.
43  *
44  * (3) While all this is happening, we inject faults into the pool to
45  *     verify that self-healing data really works.
46  *
47  * (4) Every time we open a dataset, we change its checksum and compression
48  *     functions.  Thus even individual objects vary from block to block
49  *     in which checksum they use and whether they're compressed.
50  *
51  * (5) To verify that we never lose on-disk consistency after a crash,
52  *     we run the entire test in a child of the main process.
53  *     At random times, the child self-immolates with a SIGKILL.
54  *     This is the software equivalent of pulling the power cord.
55  *     The parent then runs the test again, using the existing
56  *     storage pool, as many times as desired.
57  *
58  * (6) To verify that we don't have future leaks or temporal incursions,
59  *     many of the functional tests record the transaction group number
60  *     as part of their data.  When reading old data, they verify that
61  *     the transaction group number is less than the current, open txg.
62  *     If you add a new test, please do this if applicable.
63  *
64  * When run with no arguments, ztest runs for about five minutes and
65  * produces no output if successful.  To get a little bit of information,
66  * specify -V.  To get more information, specify -VV, and so on.
67  *
68  * To turn this into an overnight stress test, use -T to specify run time.
69  *
70  * You can ask more more vdevs [-v], datasets [-d], or threads [-t]
71  * to increase the pool capacity, fanout, and overall stress level.
72  *
73  * The -N(okill) option will suppress kills, so each child runs to completion.
74  * This can be useful when you're trying to distinguish temporal incursions
75  * from plain old race conditions.
76  */
77 
78 #include <sys/zfs_context.h>
79 #include <sys/spa.h>
80 #include <sys/dmu.h>
81 #include <sys/txg.h>
82 #include <sys/zap.h>
83 #include <sys/dmu_traverse.h>
84 #include <sys/dmu_objset.h>
85 #include <sys/poll.h>
86 #include <sys/stat.h>
87 #include <sys/time.h>
88 #include <sys/wait.h>
89 #include <sys/mman.h>
90 #include <sys/resource.h>
91 #include <sys/zio.h>
92 #include <sys/zio_checksum.h>
93 #include <sys/zio_compress.h>
94 #include <sys/zil.h>
95 #include <sys/vdev_impl.h>
96 #include <sys/spa_impl.h>
97 #include <sys/dsl_prop.h>
98 #include <sys/refcount.h>
99 #include <stdio.h>
100 #include <stdlib.h>
101 #include <unistd.h>
102 #include <signal.h>
103 #include <umem.h>
104 #include <dlfcn.h>
105 #include <ctype.h>
106 #include <math.h>
107 #include <sys/fs/zfs.h>
108 
109 static char cmdname[] = "ztest";
110 static char *zopt_pool = cmdname;
111 
112 static uint64_t zopt_vdevs = 5;
113 static uint64_t zopt_vdevtime;
114 static int zopt_mirrors = 2;
115 static int zopt_raidz = 4;
116 static size_t zopt_vdev_size = SPA_MINDEVSIZE;
117 static int zopt_dirs = 7;
118 static int zopt_threads = 23;
119 static uint64_t zopt_passtime = 60;	/* 60 seconds */
120 static uint64_t zopt_killrate = 70;	/* 70% kill rate */
121 static int zopt_verbose = 0;
122 static int zopt_init = 1;
123 static char *zopt_dir = "/tmp";
124 static uint64_t zopt_time = 300;	/* 5 minutes */
125 static int zopt_maxfaults;
126 
127 typedef struct ztest_args {
128 	char		*za_pool;
129 	objset_t	*za_os;
130 	zilog_t		*za_zilog;
131 	thread_t	za_thread;
132 	uint64_t	za_instance;
133 	uint64_t	za_random;
134 	uint64_t	za_diroff;
135 	uint64_t	za_diroff_shared;
136 	hrtime_t	za_start;
137 	hrtime_t	za_stop;
138 	hrtime_t	za_kill;
139 	traverse_handle_t *za_th;
140 } ztest_args_t;
141 
142 typedef void ztest_func_t(ztest_args_t *);
143 
144 /*
145  * Note: these aren't static because we want dladdr() to work.
146  */
147 ztest_func_t ztest_dmu_read_write;
148 ztest_func_t ztest_dmu_write_parallel;
149 ztest_func_t ztest_dmu_object_alloc_free;
150 ztest_func_t ztest_zap;
151 ztest_func_t ztest_zap_parallel;
152 ztest_func_t ztest_traverse;
153 ztest_func_t ztest_dsl_prop_get_set;
154 ztest_func_t ztest_dmu_objset_create_destroy;
155 ztest_func_t ztest_dmu_snapshot_create_destroy;
156 ztest_func_t ztest_spa_create_destroy;
157 ztest_func_t ztest_fault_inject;
158 ztest_func_t ztest_vdev_attach_detach;
159 ztest_func_t ztest_vdev_LUN_growth;
160 ztest_func_t ztest_vdev_add_remove;
161 ztest_func_t ztest_scrub;
162 ztest_func_t ztest_spa_rename;
163 
164 typedef struct ztest_info {
165 	ztest_func_t	*zi_func;	/* test function */
166 	uint64_t	*zi_interval;	/* execute every <interval> seconds */
167 	uint64_t	zi_calls;	/* per-pass count */
168 	uint64_t	zi_call_time;	/* per-pass time */
169 	uint64_t	zi_call_total;	/* cumulative total */
170 	uint64_t	zi_call_target;	/* target cumulative total */
171 } ztest_info_t;
172 
173 uint64_t zopt_always = 0;		/* all the time */
174 uint64_t zopt_often = 1;		/* every second */
175 uint64_t zopt_sometimes = 10;		/* every 10 seconds */
176 uint64_t zopt_rarely = 60;		/* every 60 seconds */
177 
178 ztest_info_t ztest_info[] = {
179 	{ ztest_dmu_read_write,			&zopt_always	},
180 	{ ztest_dmu_write_parallel,		&zopt_always	},
181 	{ ztest_dmu_object_alloc_free,		&zopt_always	},
182 	{ ztest_zap,				&zopt_always	},
183 	{ ztest_zap_parallel,			&zopt_always	},
184 	{ ztest_traverse,			&zopt_often	},
185 	{ ztest_dsl_prop_get_set,		&zopt_sometimes	},
186 	{ ztest_dmu_objset_create_destroy,	&zopt_sometimes	},
187 	{ ztest_dmu_snapshot_create_destroy,	&zopt_sometimes	},
188 	{ ztest_spa_create_destroy,		&zopt_sometimes	},
189 	{ ztest_fault_inject,			&zopt_sometimes	},
190 	{ ztest_spa_rename,			&zopt_rarely	},
191 	{ ztest_vdev_attach_detach,		&zopt_rarely	},
192 	{ ztest_vdev_LUN_growth,		&zopt_rarely	},
193 	{ ztest_vdev_add_remove,		&zopt_vdevtime	},
194 	{ ztest_scrub,				&zopt_vdevtime	},
195 };
196 
197 #define	ZTEST_FUNCS	(sizeof (ztest_info) / sizeof (ztest_info_t))
198 
199 #define	ZTEST_SYNC_LOCKS	16
200 
201 /*
202  * Stuff we need to share writably between parent and child.
203  */
204 typedef struct ztest_shared {
205 	mutex_t		zs_vdev_lock;
206 	rwlock_t	zs_name_lock;
207 	uint64_t	zs_vdev_primaries;
208 	uint64_t	zs_enospc_count;
209 	hrtime_t	zs_start_time;
210 	hrtime_t	zs_stop_time;
211 	uint64_t	zs_alloc;
212 	uint64_t	zs_space;
213 	ztest_info_t	zs_info[ZTEST_FUNCS];
214 	mutex_t		zs_sync_lock[ZTEST_SYNC_LOCKS];
215 	uint64_t	zs_seq[ZTEST_SYNC_LOCKS];
216 } ztest_shared_t;
217 
218 typedef struct ztest_block_tag {
219 	uint64_t	bt_objset;
220 	uint64_t	bt_object;
221 	uint64_t	bt_offset;
222 	uint64_t	bt_txg;
223 	uint64_t	bt_thread;
224 	uint64_t	bt_seq;
225 } ztest_block_tag_t;
226 
227 static char ztest_dev_template[] = "%s/%s.%llua";
228 static ztest_shared_t *ztest_shared;
229 
230 static int ztest_random_fd;
231 static int ztest_dump_core = 1;
232 
233 extern uint64_t zio_gang_bang;
234 
235 #define	ZTEST_DIROBJ		1
236 #define	ZTEST_MICROZAP_OBJ	2
237 #define	ZTEST_FATZAP_OBJ	3
238 
239 #define	ZTEST_DIROBJ_BLOCKSIZE	(1 << 10)
240 #define	ZTEST_DIRSIZE		256
241 
242 /*
243  * These libumem hooks provide a reasonable set of defaults for the allocator's
244  * debugging facilities.
245  */
246 const char *
247 _umem_debug_init()
248 {
249 	return ("default,verbose"); /* $UMEM_DEBUG setting */
250 }
251 
252 const char *
253 _umem_logging_init(void)
254 {
255 	return ("fail,contents"); /* $UMEM_LOGGING setting */
256 }
257 
258 #define	FATAL_MSG_SZ	1024
259 
260 char *fatal_msg;
261 
262 static void
263 fatal(int do_perror, char *message, ...)
264 {
265 	va_list args;
266 	int save_errno = errno;
267 	char buf[FATAL_MSG_SZ];
268 
269 	(void) fflush(stdout);
270 
271 	va_start(args, message);
272 	(void) sprintf(buf, "ztest: ");
273 	/* LINTED */
274 	(void) vsprintf(buf + strlen(buf), message, args);
275 	va_end(args);
276 	if (do_perror) {
277 		(void) snprintf(buf + strlen(buf), FATAL_MSG_SZ - strlen(buf),
278 		    ": %s", strerror(save_errno));
279 	}
280 	(void) fprintf(stderr, "%s\n", buf);
281 	fatal_msg = buf;			/* to ease debugging */
282 	if (ztest_dump_core)
283 		abort();
284 	exit(3);
285 }
286 
287 static int
288 str2shift(const char *buf)
289 {
290 	const char *ends = "BKMGTPEZ";
291 	int i;
292 
293 	if (buf[0] == '\0')
294 		return (0);
295 	for (i = 0; i < strlen(ends); i++) {
296 		if (toupper(buf[0]) == ends[i])
297 			break;
298 	}
299 	if (i == strlen(ends))
300 		fatal(0, "invalid bytes suffix: %s", buf);
301 	if (buf[1] == '\0' || (toupper(buf[1]) == 'B' && buf[2] == '\0')) {
302 		return (10*i);
303 	}
304 	fatal(0, "invalid bytes suffix: %s", buf);
305 	return (-1);
306 }
307 
308 static uint64_t
309 nicenumtoull(const char *buf)
310 {
311 	char *end;
312 	uint64_t val;
313 
314 	val = strtoull(buf, &end, 0);
315 	if (end == buf) {
316 		fatal(0, "bad numeric value: %s", buf);
317 	} else if (end[0] == '.') {
318 		double fval = strtod(buf, &end);
319 		fval *= pow(2, str2shift(end));
320 		if (fval > UINT64_MAX)
321 			fatal(0, "value too large: %s", buf);
322 		val = (uint64_t)fval;
323 	} else {
324 		int shift = str2shift(end);
325 		if (shift >= 64 || (val << shift) >> shift != val)
326 			fatal(0, "value too large: %s", buf);
327 		val <<= shift;
328 	}
329 	return (val);
330 }
331 
332 static void
333 usage(void)
334 {
335 	char nice_vdev_size[10];
336 	char nice_gang_bang[10];
337 
338 	nicenum(zopt_vdev_size, nice_vdev_size);
339 	nicenum(zio_gang_bang, nice_gang_bang);
340 
341 	(void) printf("Usage: %s\n"
342 	    "\t[-v vdevs (default: %llu)]\n"
343 	    "\t[-s size_of_each_vdev (default: %s)]\n"
344 	    "\t[-m mirror_copies (default: %d)]\n"
345 	    "\t[-r raidz_disks (default: %d)]\n"
346 	    "\t[-d datasets (default: %d)]\n"
347 	    "\t[-t threads (default: %d)]\n"
348 	    "\t[-g gang_block_threshold (default: %s)]\n"
349 	    "\t[-i initialize pool i times (default: %d)]\n"
350 	    "\t[-k kill percentage (default: %llu%%)]\n"
351 	    "\t[-p pool_name (default: %s)]\n"
352 	    "\t[-f file directory for vdev files (default: %s)]\n"
353 	    "\t[-V(erbose)] (use multiple times for ever more blather)\n"
354 	    "\t[-E(xisting)] (use existing pool instead of creating new one\n"
355 	    "\t[-I(mport)] (discover and import existing pools)\n"
356 	    "\t[-T time] total run time (default: %llu sec)\n"
357 	    "\t[-P passtime] time per pass (default: %llu sec)\n"
358 	    "",
359 	    cmdname,
360 	    (u_longlong_t)zopt_vdevs,		/* -v */
361 	    nice_vdev_size,			/* -s */
362 	    zopt_mirrors,			/* -m */
363 	    zopt_raidz,				/* -r */
364 	    zopt_dirs,			/* -d */
365 	    zopt_threads,			/* -t */
366 	    nice_gang_bang,			/* -g */
367 	    zopt_init,				/* -i */
368 	    (u_longlong_t)zopt_killrate,	/* -k */
369 	    zopt_pool,				/* -p */
370 	    zopt_dir,				/* -f */
371 	    (u_longlong_t)zopt_time,		/* -T */
372 	    (u_longlong_t)zopt_passtime);	/* -P */
373 	exit(1);
374 }
375 
376 static uint64_t
377 ztest_random(uint64_t range)
378 {
379 	uint64_t r;
380 
381 	if (range == 0)
382 		return (0);
383 
384 	if (read(ztest_random_fd, &r, sizeof (r)) != sizeof (r))
385 		fatal(1, "short read from /dev/urandom");
386 
387 	return (r % range);
388 }
389 
390 static void
391 ztest_record_enospc(char *s)
392 {
393 	dprintf("ENOSPC doing: %s\n", s ? s : "<unknown>");
394 	ztest_shared->zs_enospc_count++;
395 }
396 
397 static void
398 process_options(int argc, char **argv)
399 {
400 	int opt;
401 	uint64_t value;
402 
403 	/* By default, test gang blocks for blocks 32K and greater */
404 	zio_gang_bang = 32 << 10;
405 
406 	while ((opt = getopt(argc, argv,
407 	    "v:s:m:r:c:d:t:g:i:k:p:f:VEIT:P:S")) != EOF) {
408 		value = 0;
409 		switch (opt) {
410 		    case 'v':
411 		    case 's':
412 		    case 'm':
413 		    case 'r':
414 		    case 'c':
415 		    case 'd':
416 		    case 't':
417 		    case 'g':
418 		    case 'i':
419 		    case 'k':
420 		    case 'T':
421 		    case 'P':
422 			value = nicenumtoull(optarg);
423 		}
424 		switch (opt) {
425 		    case 'v':
426 			zopt_vdevs = value;
427 			break;
428 		    case 's':
429 			zopt_vdev_size = MAX(SPA_MINDEVSIZE, value);
430 			break;
431 		    case 'm':
432 			zopt_mirrors = value;
433 			break;
434 		    case 'r':
435 			zopt_raidz = MAX(1, value);
436 			break;
437 		    case 'd':
438 			zopt_dirs = MAX(1, value);
439 			break;
440 		    case 't':
441 			zopt_threads = MAX(1, value);
442 			break;
443 		    case 'g':
444 			zio_gang_bang = MAX(SPA_MINBLOCKSIZE << 1, value);
445 			break;
446 		    case 'i':
447 			zopt_init = value;
448 			break;
449 		    case 'k':
450 			zopt_killrate = value;
451 			break;
452 		    case 'p':
453 			zopt_pool = strdup(optarg);
454 			break;
455 		    case 'f':
456 			zopt_dir = strdup(optarg);
457 			break;
458 		    case 'V':
459 			zopt_verbose++;
460 			break;
461 		    case 'E':
462 			zopt_init = 0;
463 			break;
464 		    case 'T':
465 			zopt_time = value;
466 			break;
467 		    case 'P':
468 			zopt_passtime = MAX(1, value);
469 			break;
470 		    case '?':
471 		    default:
472 			usage();
473 			break;
474 		}
475 	}
476 
477 	zopt_vdevtime = (zopt_vdevs > 0 ? zopt_time / zopt_vdevs : UINT64_MAX);
478 	zopt_maxfaults = MAX(zopt_mirrors, 1) * (zopt_raidz >= 2 ? 2 : 1) - 1;
479 }
480 
481 static nvlist_t *
482 make_vdev_file(size_t size)
483 {
484 	char dev_name[MAXPATHLEN];
485 	uint64_t vdev;
486 	int fd;
487 	nvlist_t *file;
488 
489 	if (size == 0) {
490 		(void) snprintf(dev_name, sizeof (dev_name), "%s",
491 		    "/dev/bogus");
492 	} else {
493 		vdev = ztest_shared->zs_vdev_primaries++;
494 		(void) sprintf(dev_name, ztest_dev_template,
495 		    zopt_dir, zopt_pool, vdev);
496 
497 		fd = open(dev_name, O_RDWR | O_CREAT | O_TRUNC, 0666);
498 		if (fd == -1)
499 			fatal(1, "can't open %s", dev_name);
500 		if (ftruncate(fd, size) != 0)
501 			fatal(1, "can't ftruncate %s", dev_name);
502 		(void) close(fd);
503 	}
504 
505 	VERIFY(nvlist_alloc(&file, NV_UNIQUE_NAME, 0) == 0);
506 	VERIFY(nvlist_add_string(file, ZPOOL_CONFIG_TYPE, VDEV_TYPE_FILE) == 0);
507 	VERIFY(nvlist_add_string(file, ZPOOL_CONFIG_PATH, dev_name) == 0);
508 
509 	return (file);
510 }
511 
512 static nvlist_t *
513 make_vdev_raidz(size_t size, int r)
514 {
515 	nvlist_t *raidz, **child;
516 	int c;
517 
518 	if (r < 2)
519 		return (make_vdev_file(size));
520 
521 	child = umem_alloc(r * sizeof (nvlist_t *), UMEM_NOFAIL);
522 
523 	for (c = 0; c < r; c++)
524 		child[c] = make_vdev_file(size);
525 
526 	VERIFY(nvlist_alloc(&raidz, NV_UNIQUE_NAME, 0) == 0);
527 	VERIFY(nvlist_add_string(raidz, ZPOOL_CONFIG_TYPE,
528 	    VDEV_TYPE_RAIDZ) == 0);
529 	VERIFY(nvlist_add_nvlist_array(raidz, ZPOOL_CONFIG_CHILDREN,
530 	    child, r) == 0);
531 
532 	for (c = 0; c < r; c++)
533 		nvlist_free(child[c]);
534 
535 	umem_free(child, r * sizeof (nvlist_t *));
536 
537 	return (raidz);
538 }
539 
540 static nvlist_t *
541 make_vdev_mirror(size_t size, int r, int m)
542 {
543 	nvlist_t *mirror, **child;
544 	int c;
545 
546 	if (m < 1)
547 		return (make_vdev_raidz(size, r));
548 
549 	child = umem_alloc(m * sizeof (nvlist_t *), UMEM_NOFAIL);
550 
551 	for (c = 0; c < m; c++)
552 		child[c] = make_vdev_raidz(size, r);
553 
554 	VERIFY(nvlist_alloc(&mirror, NV_UNIQUE_NAME, 0) == 0);
555 	VERIFY(nvlist_add_string(mirror, ZPOOL_CONFIG_TYPE,
556 	    VDEV_TYPE_MIRROR) == 0);
557 	VERIFY(nvlist_add_nvlist_array(mirror, ZPOOL_CONFIG_CHILDREN,
558 	    child, m) == 0);
559 
560 	for (c = 0; c < m; c++)
561 		nvlist_free(child[c]);
562 
563 	umem_free(child, m * sizeof (nvlist_t *));
564 
565 	return (mirror);
566 }
567 
568 static nvlist_t *
569 make_vdev_root(size_t size, int r, int m, int t)
570 {
571 	nvlist_t *root, **child;
572 	int c;
573 
574 	ASSERT(t > 0);
575 
576 	child = umem_alloc(t * sizeof (nvlist_t *), UMEM_NOFAIL);
577 
578 	for (c = 0; c < t; c++)
579 		child[c] = make_vdev_mirror(size, r, m);
580 
581 	VERIFY(nvlist_alloc(&root, NV_UNIQUE_NAME, 0) == 0);
582 	VERIFY(nvlist_add_string(root, ZPOOL_CONFIG_TYPE, VDEV_TYPE_ROOT) == 0);
583 	VERIFY(nvlist_add_nvlist_array(root, ZPOOL_CONFIG_CHILDREN,
584 	    child, t) == 0);
585 
586 	for (c = 0; c < t; c++)
587 		nvlist_free(child[c]);
588 
589 	umem_free(child, t * sizeof (nvlist_t *));
590 
591 	return (root);
592 }
593 
594 static void
595 ztest_set_random_blocksize(objset_t *os, uint64_t object, dmu_tx_t *tx)
596 {
597 	int bs = SPA_MINBLOCKSHIFT +
598 	    ztest_random(SPA_MAXBLOCKSHIFT - SPA_MINBLOCKSHIFT + 1);
599 	int ibs = DN_MIN_INDBLKSHIFT +
600 	    ztest_random(DN_MAX_INDBLKSHIFT - DN_MIN_INDBLKSHIFT + 1);
601 	int error;
602 
603 	error = dmu_object_set_blocksize(os, object, 1ULL << bs, ibs, tx);
604 	if (error) {
605 		char osname[300];
606 		dmu_objset_name(os, osname);
607 		fatal(0, "dmu_object_set_blocksize('%s', %llu, %d, %d) = %d",
608 		    osname, object, 1 << bs, ibs, error);
609 	}
610 }
611 
612 static uint8_t
613 ztest_random_checksum(void)
614 {
615 	uint8_t checksum;
616 
617 	do {
618 		checksum = ztest_random(ZIO_CHECKSUM_FUNCTIONS);
619 	} while (zio_checksum_table[checksum].ci_zbt);
620 
621 	if (checksum == ZIO_CHECKSUM_OFF)
622 		checksum = ZIO_CHECKSUM_ON;
623 
624 	return (checksum);
625 }
626 
627 static uint8_t
628 ztest_random_compress(void)
629 {
630 	return ((uint8_t)ztest_random(ZIO_COMPRESS_FUNCTIONS));
631 }
632 
633 typedef struct ztest_replay {
634 	objset_t	*zr_os;
635 	uint64_t	zr_assign;
636 } ztest_replay_t;
637 
638 static int
639 ztest_replay_create(ztest_replay_t *zr, lr_create_t *lr, boolean_t byteswap)
640 {
641 	objset_t *os = zr->zr_os;
642 	dmu_tx_t *tx;
643 	int error;
644 
645 	if (byteswap)
646 		byteswap_uint64_array(lr, sizeof (*lr));
647 
648 	tx = dmu_tx_create(os);
649 	dmu_tx_hold_bonus(tx, DMU_NEW_OBJECT);
650 	error = dmu_tx_assign(tx, zr->zr_assign);
651 	if (error) {
652 		dmu_tx_abort(tx);
653 		return (error);
654 	}
655 
656 	error = dmu_object_claim(os, lr->lr_doid, lr->lr_mode, 0,
657 	    DMU_OT_NONE, 0, tx);
658 	ASSERT(error == 0);
659 	dmu_tx_commit(tx);
660 
661 	if (zopt_verbose >= 5) {
662 		char osname[MAXNAMELEN];
663 		dmu_objset_name(os, osname);
664 		(void) printf("replay create of %s object %llu"
665 		    " in txg %llu = %d\n",
666 		    osname, (u_longlong_t)lr->lr_doid,
667 		    (u_longlong_t)zr->zr_assign, error);
668 	}
669 
670 	return (error);
671 }
672 
673 static int
674 ztest_replay_remove(ztest_replay_t *zr, lr_remove_t *lr, boolean_t byteswap)
675 {
676 	objset_t *os = zr->zr_os;
677 	dmu_tx_t *tx;
678 	int error;
679 
680 	if (byteswap)
681 		byteswap_uint64_array(lr, sizeof (*lr));
682 
683 	tx = dmu_tx_create(os);
684 	dmu_tx_hold_free(tx, lr->lr_doid, 0, DMU_OBJECT_END);
685 	error = dmu_tx_assign(tx, zr->zr_assign);
686 	if (error) {
687 		dmu_tx_abort(tx);
688 		return (error);
689 	}
690 
691 	error = dmu_object_free(os, lr->lr_doid, tx);
692 	dmu_tx_commit(tx);
693 
694 	return (error);
695 }
696 
697 zil_replay_func_t *ztest_replay_vector[TX_MAX_TYPE] = {
698 	NULL,			/* 0 no such transaction type */
699 	ztest_replay_create,	/* TX_CREATE */
700 	NULL,			/* TX_MKDIR */
701 	NULL,			/* TX_MKXATTR */
702 	NULL,			/* TX_SYMLINK */
703 	ztest_replay_remove,	/* TX_REMOVE */
704 	NULL,			/* TX_RMDIR */
705 	NULL,			/* TX_LINK */
706 	NULL,			/* TX_RENAME */
707 	NULL,			/* TX_WRITE */
708 	NULL,			/* TX_TRUNCATE */
709 	NULL,			/* TX_SETATTR */
710 	NULL,			/* TX_ACL */
711 };
712 
713 /*
714  * Verify that we can't destroy an active pool, create an existing pool,
715  * or create a pool with a bad vdev spec.
716  */
717 void
718 ztest_spa_create_destroy(ztest_args_t *za)
719 {
720 	int error;
721 	spa_t *spa;
722 	nvlist_t *nvroot;
723 
724 	/*
725 	 * Attempt to create using a bad file.
726 	 */
727 	nvroot = make_vdev_root(0, 0, 0, 1);
728 	error = spa_create("ztest_bad_file", nvroot, NULL);
729 	nvlist_free(nvroot);
730 	if (error != ENOENT)
731 		fatal(0, "spa_create(bad_file) = %d", error);
732 
733 	/*
734 	 * Attempt to create using a bad mirror.
735 	 */
736 	nvroot = make_vdev_root(0, 0, 2, 1);
737 	error = spa_create("ztest_bad_mirror", nvroot, NULL);
738 	nvlist_free(nvroot);
739 	if (error != ENOENT)
740 		fatal(0, "spa_create(bad_mirror) = %d", error);
741 
742 	/*
743 	 * Attempt to create an existing pool.  It shouldn't matter
744 	 * what's in the nvroot; we should fail with EEXIST.
745 	 */
746 	(void) rw_rdlock(&ztest_shared->zs_name_lock);
747 	nvroot = make_vdev_root(0, 0, 0, 1);
748 	error = spa_create(za->za_pool, nvroot, NULL);
749 	nvlist_free(nvroot);
750 	if (error != EEXIST)
751 		fatal(0, "spa_create(whatever) = %d", error);
752 
753 	error = spa_open(za->za_pool, &spa, FTAG);
754 	if (error)
755 		fatal(0, "spa_open() = %d", error);
756 
757 	error = spa_destroy(za->za_pool);
758 	if (error != EBUSY)
759 		fatal(0, "spa_destroy() = %d", error);
760 
761 	spa_close(spa, FTAG);
762 	(void) rw_unlock(&ztest_shared->zs_name_lock);
763 }
764 
765 /*
766  * Verify that vdev_add() works as expected.
767  */
768 void
769 ztest_vdev_add_remove(ztest_args_t *za)
770 {
771 	spa_t *spa = dmu_objset_spa(za->za_os);
772 	uint64_t leaves = MAX(zopt_mirrors, 1) * zopt_raidz;
773 	nvlist_t *nvroot;
774 	int error;
775 
776 	if (zopt_verbose >= 6)
777 		(void) printf("adding vdev\n");
778 
779 	(void) mutex_lock(&ztest_shared->zs_vdev_lock);
780 
781 	spa_config_enter(spa, RW_READER);
782 
783 	ztest_shared->zs_vdev_primaries =
784 	    spa->spa_root_vdev->vdev_children * leaves;
785 
786 	spa_config_exit(spa);
787 
788 	nvroot = make_vdev_root(zopt_vdev_size, zopt_raidz, zopt_mirrors, 1);
789 	error = spa_vdev_add(spa, nvroot);
790 	nvlist_free(nvroot);
791 
792 	(void) mutex_unlock(&ztest_shared->zs_vdev_lock);
793 
794 	if (error == ENOSPC)
795 		ztest_record_enospc("spa_vdev_add");
796 	else if (error != 0)
797 		fatal(0, "spa_vdev_add() = %d", error);
798 
799 	if (zopt_verbose >= 6)
800 		(void) printf("spa_vdev_add = %d, as expected\n", error);
801 }
802 
803 /*
804  * Verify that we can attach and detach devices.
805  */
806 void
807 ztest_vdev_attach_detach(ztest_args_t *za)
808 {
809 	spa_t *spa = dmu_objset_spa(za->za_os);
810 	vdev_t *rvd = spa->spa_root_vdev;
811 	vdev_t *vd0, *vd1, *pvd;
812 	nvlist_t *root, *file;
813 	uint64_t leaves = MAX(zopt_mirrors, 1) * zopt_raidz;
814 	uint64_t leaf, top;
815 	size_t size0, size1;
816 	char path0[MAXPATHLEN], path1[MAXPATHLEN];
817 	int replacing;
818 	int error, expected_error;
819 	int fd;
820 
821 	(void) mutex_lock(&ztest_shared->zs_vdev_lock);
822 
823 	spa_config_enter(spa, RW_READER);
824 
825 	/*
826 	 * Decide whether to do an attach or a replace.
827 	 */
828 	replacing = ztest_random(2);
829 
830 	/*
831 	 * Pick a random top-level vdev.
832 	 */
833 	top = ztest_random(rvd->vdev_children);
834 
835 	/*
836 	 * Pick a random leaf within it.
837 	 */
838 	leaf = ztest_random(leaves);
839 
840 	/*
841 	 * Generate the path to this leaf.  The filename will end with 'a'.
842 	 * We'll alternate replacements with a filename that ends with 'b'.
843 	 */
844 	(void) snprintf(path0, sizeof (path0),
845 	    ztest_dev_template, zopt_dir, zopt_pool, top * leaves + leaf);
846 
847 	bcopy(path0, path1, MAXPATHLEN);
848 
849 	/*
850 	 * If the 'a' file isn't part of the pool, the 'b' file must be.
851 	 */
852 	if (vdev_lookup_by_path(rvd, path0) == NULL)
853 		path0[strlen(path0) - 1] = 'b';
854 	else
855 		path1[strlen(path1) - 1] = 'b';
856 
857 	/*
858 	 * Now path0 represents something that's already in the pool,
859 	 * and path1 is the thing we'll try to attach.
860 	 */
861 	vd0 = vdev_lookup_by_path(rvd, path0);
862 	vd1 = vdev_lookup_by_path(rvd, path1);
863 	ASSERT(vd0 != NULL);
864 	pvd = vd0->vdev_parent;
865 
866 
867 	/*
868 	 * Make size1 a little bigger or smaller than size0.
869 	 * If it's smaller, the attach should fail.
870 	 * If it's larger, and we're doing a replace,
871 	 * we should get dynamic LUN growth when we're done.
872 	 */
873 	size0 = vd0->vdev_psize;
874 	size1 = 10 * size0 / (9 + ztest_random(3));
875 
876 	/*
877 	 * If pvd is not a mirror or root, the attach should fail with ENOTSUP,
878 	 * unless it's a replace; in that case any non-replacing parent is OK.
879 	 *
880 	 * If vd1 is already part of the pool, it should fail with EBUSY.
881 	 *
882 	 * If vd1 is too small, it should fail with EOVERFLOW.
883 	 */
884 	if (pvd->vdev_ops != &vdev_mirror_ops &&
885 	    pvd->vdev_ops != &vdev_root_ops &&
886 	    (!replacing || pvd->vdev_ops == &vdev_replacing_ops))
887 		expected_error = ENOTSUP;
888 	else if (vd1 != NULL)
889 		expected_error = EBUSY;
890 	else if (size1 < size0)
891 		expected_error = EOVERFLOW;
892 	else
893 		expected_error = 0;
894 
895 	/*
896 	 * If vd1 isn't already part of the pool, create it.
897 	 */
898 	if (vd1 == NULL) {
899 		fd = open(path1, O_RDWR | O_CREAT | O_TRUNC, 0666);
900 		if (fd == -1)
901 			fatal(1, "can't open %s", path1);
902 		if (ftruncate(fd, size1) != 0)
903 			fatal(1, "can't ftruncate %s", path1);
904 		(void) close(fd);
905 	}
906 
907 	spa_config_exit(spa);
908 
909 	/*
910 	 * Build the nvlist describing path1.
911 	 */
912 	VERIFY(nvlist_alloc(&file, NV_UNIQUE_NAME, 0) == 0);
913 	VERIFY(nvlist_add_string(file, ZPOOL_CONFIG_TYPE, VDEV_TYPE_FILE) == 0);
914 	VERIFY(nvlist_add_string(file, ZPOOL_CONFIG_PATH, path1) == 0);
915 
916 	VERIFY(nvlist_alloc(&root, NV_UNIQUE_NAME, 0) == 0);
917 	VERIFY(nvlist_add_string(root, ZPOOL_CONFIG_TYPE, VDEV_TYPE_ROOT) == 0);
918 	VERIFY(nvlist_add_nvlist_array(root, ZPOOL_CONFIG_CHILDREN,
919 	    &file, 1) == 0);
920 
921 	error = spa_vdev_attach(spa, path0, root, replacing);
922 
923 	nvlist_free(file);
924 	nvlist_free(root);
925 
926 	/*
927 	 * If our parent was the replacing vdev, but the replace completed,
928 	 * then instead of failing with ENOTSUP we may either succeed,
929 	 * fail with ENODEV, or fail with EOVERFLOW.
930 	 */
931 	if (expected_error == ENOTSUP &&
932 	    (error == 0 || error == ENODEV || error == EOVERFLOW))
933 		expected_error = error;
934 
935 	if (error != expected_error) {
936 		fatal(0, "attach (%s, %s, %d) returned %d, expected %d",
937 		    path0, path1, replacing, error, expected_error);
938 	}
939 
940 	(void) mutex_unlock(&ztest_shared->zs_vdev_lock);
941 }
942 
943 /*
944  * Verify that dynamic LUN growth works as expected.
945  */
946 /* ARGSUSED */
947 void
948 ztest_vdev_LUN_growth(ztest_args_t *za)
949 {
950 	spa_t *spa = dmu_objset_spa(za->za_os);
951 	char dev_name[MAXPATHLEN];
952 	uint64_t leaves = MAX(zopt_mirrors, 1) * zopt_raidz;
953 	uint64_t vdev;
954 	size_t fsize;
955 	int fd;
956 
957 	(void) mutex_lock(&ztest_shared->zs_vdev_lock);
958 
959 	/*
960 	 * Pick a random leaf vdev.
961 	 */
962 	spa_config_enter(spa, RW_READER);
963 	vdev = ztest_random(spa->spa_root_vdev->vdev_children * leaves);
964 	spa_config_exit(spa);
965 
966 	(void) sprintf(dev_name, ztest_dev_template, zopt_dir, zopt_pool, vdev);
967 
968 	if ((fd = open(dev_name, O_RDWR)) != -1) {
969 		/*
970 		 * Determine the size.
971 		 */
972 		fsize = lseek(fd, 0, SEEK_END);
973 
974 		/*
975 		 * If it's less than 2x the original size, grow by around 3%.
976 		 */
977 		if (fsize < 2 * zopt_vdev_size) {
978 			size_t newsize = fsize + ztest_random(fsize / 32);
979 			(void) ftruncate(fd, newsize);
980 			if (zopt_verbose >= 6) {
981 				(void) printf("%s grew from %lu to %lu bytes\n",
982 				    dev_name, (ulong_t)fsize, (ulong_t)newsize);
983 			}
984 		}
985 		(void) close(fd);
986 	}
987 
988 	(void) mutex_unlock(&ztest_shared->zs_vdev_lock);
989 }
990 
991 /* ARGSUSED */
992 static void
993 ztest_create_cb(objset_t *os, void *arg, dmu_tx_t *tx)
994 {
995 	/*
996 	 * Create the directory object.
997 	 */
998 	VERIFY(dmu_object_claim(os, ZTEST_DIROBJ,
999 	    DMU_OT_UINT64_OTHER, ZTEST_DIROBJ_BLOCKSIZE,
1000 	    DMU_OT_UINT64_OTHER, sizeof (ztest_block_tag_t), tx) == 0);
1001 
1002 	VERIFY(zap_create_claim(os, ZTEST_MICROZAP_OBJ,
1003 	    DMU_OT_ZAP_OTHER, DMU_OT_NONE, 0, tx) == 0);
1004 
1005 	VERIFY(zap_create_claim(os, ZTEST_FATZAP_OBJ,
1006 	    DMU_OT_ZAP_OTHER, DMU_OT_NONE, 0, tx) == 0);
1007 }
1008 
1009 /* ARGSUSED */
1010 static void
1011 ztest_destroy_cb(char *name, void *arg)
1012 {
1013 	objset_t *os;
1014 	dmu_object_info_t doi;
1015 	int error;
1016 
1017 	/*
1018 	 * Verify that the dataset contains a directory object.
1019 	 */
1020 	error = dmu_objset_open(name, DMU_OST_OTHER,
1021 	    DS_MODE_STANDARD | DS_MODE_READONLY, &os);
1022 	ASSERT3U(error, ==, 0);
1023 	error = dmu_object_info(os, ZTEST_DIROBJ, &doi);
1024 	ASSERT3U(error, ==, 0);
1025 	ASSERT3U(doi.doi_type, ==, DMU_OT_UINT64_OTHER);
1026 	ASSERT3S(doi.doi_physical_blks, >=, 0);
1027 	dmu_objset_close(os);
1028 
1029 	/*
1030 	 * Destroy the dataset.
1031 	 */
1032 	error = dmu_objset_destroy(name);
1033 	ASSERT3U(error, ==, 0);
1034 }
1035 
1036 /*
1037  * Verify that dmu_objset_{create,destroy,open,close} work as expected.
1038  */
1039 static uint64_t
1040 ztest_log_create(zilog_t *zilog, dmu_tx_t *tx, uint64_t object, int mode)
1041 {
1042 	itx_t *itx;
1043 	lr_create_t *lr;
1044 	size_t namesize;
1045 	char name[24];
1046 
1047 	(void) sprintf(name, "ZOBJ_%llu", (u_longlong_t)object);
1048 	namesize = strlen(name) + 1;
1049 
1050 	itx = zil_itx_create(TX_CREATE, sizeof (*lr) + namesize +
1051 	    ztest_random(ZIL_MAX_BLKSZ));
1052 	lr = (lr_create_t *)&itx->itx_lr;
1053 	bzero(lr + 1, lr->lr_common.lrc_reclen - sizeof (*lr));
1054 	lr->lr_doid = object;
1055 	lr->lr_foid = 0;
1056 	lr->lr_mode = mode;
1057 	lr->lr_uid = 0;
1058 	lr->lr_gid = 0;
1059 	lr->lr_gen = dmu_tx_get_txg(tx);
1060 	lr->lr_crtime[0] = time(NULL);
1061 	lr->lr_crtime[1] = 0;
1062 	lr->lr_rdev = 0;
1063 	bcopy(name, (char *)(lr + 1), namesize);
1064 
1065 	return (zil_itx_assign(zilog, itx, tx));
1066 }
1067 
1068 #ifndef lint
1069 static uint64_t
1070 ztest_log_remove(zilog_t *zilog, dmu_tx_t *tx, uint64_t object)
1071 {
1072 	itx_t *itx;
1073 	lr_remove_t *lr;
1074 	size_t namesize;
1075 	char name[24];
1076 
1077 	(void) sprintf(name, "ZOBJ_%llu", (u_longlong_t)object);
1078 	namesize = strlen(name) + 1;
1079 
1080 	itx = zil_itx_create(TX_REMOVE, sizeof (*lr) + namesize +
1081 	    ztest_random(8000));
1082 	lr = (lr_remove_t *)&itx->itx_lr;
1083 	lr->lr_doid = object;
1084 	bcopy(name, (char *)(lr + 1), namesize);
1085 
1086 	return (zil_itx_assign(zilog, itx, tx));
1087 }
1088 #endif /* lint */
1089 
1090 void
1091 ztest_dmu_objset_create_destroy(ztest_args_t *za)
1092 {
1093 	int error;
1094 	objset_t *os;
1095 	char name[100];
1096 	int mode, basemode, expected_error;
1097 	zilog_t *zilog;
1098 	uint64_t seq;
1099 	uint64_t objects;
1100 	ztest_replay_t zr;
1101 
1102 	(void) rw_rdlock(&ztest_shared->zs_name_lock);
1103 	(void) snprintf(name, 100, "%s/%s_temp_%llu", za->za_pool, za->za_pool,
1104 	    (u_longlong_t)za->za_instance);
1105 
1106 	basemode = DS_MODE_LEVEL(za->za_instance);
1107 	if (basemode == DS_MODE_NONE)
1108 		basemode++;
1109 
1110 	/*
1111 	 * If this dataset exists from a previous run, process its replay log
1112 	 * half of the time.  If we don't replay it, then dmu_objset_destroy()
1113 	 * (invoked from ztest_destroy_cb() below) should just throw it away.
1114 	 */
1115 	if (ztest_random(2) == 0 &&
1116 	    dmu_objset_open(name, DMU_OST_OTHER, DS_MODE_PRIMARY, &os) == 0) {
1117 		zr.zr_os = os;
1118 		zil_replay(os, &zr, &zr.zr_assign, ztest_replay_vector, NULL);
1119 		dmu_objset_close(os);
1120 	}
1121 
1122 	/*
1123 	 * There may be an old instance of the dataset we're about to
1124 	 * create lying around from a previous run.  If so, destroy it
1125 	 * and all of its snapshots.
1126 	 */
1127 	dmu_objset_find(name, ztest_destroy_cb, NULL, DS_FIND_SNAPSHOTS);
1128 
1129 	/*
1130 	 * Verify that the destroyed dataset is no longer in the namespace.
1131 	 */
1132 	error = dmu_objset_open(name, DMU_OST_OTHER, basemode, &os);
1133 	if (error != ENOENT)
1134 		fatal(1, "dmu_objset_open(%s) found destroyed dataset %p",
1135 		    name, os);
1136 
1137 	/*
1138 	 * Verify that we can create a new dataset.
1139 	 */
1140 	error = dmu_objset_create(name, DMU_OST_OTHER, NULL, ztest_create_cb,
1141 	    NULL);
1142 	if (error) {
1143 		if (error == ENOSPC) {
1144 			ztest_record_enospc("dmu_objset_create");
1145 			(void) rw_unlock(&ztest_shared->zs_name_lock);
1146 			return;
1147 		}
1148 		fatal(0, "dmu_objset_create(%s) = %d", name, error);
1149 	}
1150 
1151 	error = dmu_objset_open(name, DMU_OST_OTHER, basemode, &os);
1152 	if (error) {
1153 		fatal(0, "dmu_objset_open(%s) = %d", name, error);
1154 	}
1155 
1156 	/*
1157 	 * Open the intent log for it.
1158 	 */
1159 	zilog = zil_open(os, NULL);
1160 
1161 	/*
1162 	 * Put a random number of objects in there.
1163 	 */
1164 	objects = ztest_random(50);
1165 	seq = 0;
1166 	while (objects-- != 0) {
1167 		uint64_t object;
1168 		dmu_tx_t *tx = dmu_tx_create(os);
1169 		dmu_tx_hold_write(tx, DMU_NEW_OBJECT, 0, sizeof (name));
1170 		error = dmu_tx_assign(tx, TXG_WAIT);
1171 		if (error) {
1172 			dmu_tx_abort(tx);
1173 		} else {
1174 			object = dmu_object_alloc(os, DMU_OT_UINT64_OTHER, 0,
1175 			    DMU_OT_NONE, 0, tx);
1176 			ztest_set_random_blocksize(os, object, tx);
1177 			seq = ztest_log_create(zilog, tx, object,
1178 			    DMU_OT_UINT64_OTHER);
1179 			dmu_write(os, object, 0, sizeof (name), name, tx);
1180 			dmu_tx_commit(tx);
1181 		}
1182 		if (ztest_random(5) == 0) {
1183 			zil_commit(zilog, seq, FSYNC);
1184 		}
1185 		if (ztest_random(5) == 0) {
1186 			error = zil_suspend(zilog);
1187 			if (error == 0) {
1188 				zil_resume(zilog);
1189 			}
1190 		}
1191 	}
1192 
1193 	/*
1194 	 * Verify that we cannot create an existing dataset.
1195 	 */
1196 	error = dmu_objset_create(name, DMU_OST_OTHER, NULL, NULL, NULL);
1197 	if (error != EEXIST)
1198 		fatal(0, "created existing dataset, error = %d", error);
1199 
1200 	/*
1201 	 * Verify that multiple dataset opens are allowed, but only when
1202 	 * the new access mode is compatible with the base mode.
1203 	 * We use a mixture of typed and typeless opens, and when the
1204 	 * open succeeds, verify that the discovered type is correct.
1205 	 */
1206 	for (mode = DS_MODE_STANDARD; mode < DS_MODE_LEVELS; mode++) {
1207 		objset_t *os2;
1208 		error = dmu_objset_open(name, DMU_OST_OTHER, mode, &os2);
1209 		expected_error = (basemode + mode < DS_MODE_LEVELS) ? 0 : EBUSY;
1210 		if (error != expected_error)
1211 			fatal(0, "dmu_objset_open('%s') = %d, expected %d",
1212 			    name, error, expected_error);
1213 		if (error == 0)
1214 			dmu_objset_close(os2);
1215 	}
1216 
1217 	zil_close(zilog);
1218 	dmu_objset_close(os);
1219 
1220 	error = dmu_objset_destroy(name);
1221 	if (error)
1222 		fatal(0, "dmu_objset_destroy(%s) = %d", name, error);
1223 
1224 	(void) rw_unlock(&ztest_shared->zs_name_lock);
1225 }
1226 
1227 /*
1228  * Verify that dmu_snapshot_{create,destroy,open,close} work as expected.
1229  */
1230 void
1231 ztest_dmu_snapshot_create_destroy(ztest_args_t *za)
1232 {
1233 	int error;
1234 	objset_t *os = za->za_os;
1235 	char snapname[100];
1236 	char osname[MAXNAMELEN];
1237 
1238 	(void) rw_rdlock(&ztest_shared->zs_name_lock);
1239 	dmu_objset_name(os, osname);
1240 	(void) snprintf(snapname, 100, "%s@%llu", osname,
1241 	    (u_longlong_t)za->za_instance);
1242 
1243 	error = dmu_objset_destroy(snapname);
1244 	if (error != 0 && error != ENOENT)
1245 		fatal(0, "dmu_objset_destroy() = %d", error);
1246 	error = dmu_objset_create(snapname, DMU_OST_OTHER, NULL, NULL, NULL);
1247 	if (error == ENOSPC)
1248 		ztest_record_enospc("dmu_take_snapshot");
1249 	else if (error != 0 && error != EEXIST)
1250 		fatal(0, "dmu_take_snapshot() = %d", error);
1251 	(void) rw_unlock(&ztest_shared->zs_name_lock);
1252 }
1253 
1254 #define	ZTEST_TRAVERSE_BLOCKS	1000
1255 
1256 static int
1257 ztest_blk_cb(traverse_blk_cache_t *bc, spa_t *spa, void *arg)
1258 {
1259 	ztest_args_t *za = arg;
1260 	zbookmark_t *zb = &bc->bc_bookmark;
1261 	blkptr_t *bp = &bc->bc_blkptr;
1262 	dnode_phys_t *dnp = bc->bc_dnode;
1263 	traverse_handle_t *th = za->za_th;
1264 	uint64_t size = BP_GET_LSIZE(bp);
1265 
1266 	ASSERT(dnp != NULL);
1267 
1268 	if (bc->bc_errno)
1269 		return (ERESTART);
1270 
1271 	/*
1272 	 * Once in a while, abort the traverse.   We only do this to odd
1273 	 * instance numbers to ensure that even ones can run to completion.
1274 	 */
1275 	if ((za->za_instance & 1) && ztest_random(10000) == 0)
1276 		return (EINTR);
1277 
1278 	if (bp->blk_birth == 0) {
1279 		ASSERT(th->th_advance & ADVANCE_HOLES);
1280 		return (0);
1281 	}
1282 
1283 	if (zb->zb_level == 0 && !(th->th_advance & ADVANCE_DATA) &&
1284 	    bc == &th->th_cache[ZB_DN_CACHE][0]) {
1285 		ASSERT(bc->bc_data == NULL);
1286 		return (0);
1287 	}
1288 
1289 	ASSERT(bc->bc_data != NULL);
1290 
1291 	/*
1292 	 * This is an expensive question, so don't ask it too often.
1293 	 */
1294 	if (((za->za_random ^ th->th_callbacks) & 0xff) == 0) {
1295 		void *xbuf = umem_alloc(size, UMEM_NOFAIL);
1296 		if (arc_tryread(spa, bp, xbuf) == 0) {
1297 			ASSERT(bcmp(bc->bc_data, xbuf, size) == 0);
1298 		}
1299 		umem_free(xbuf, size);
1300 	}
1301 
1302 	if (zb->zb_level > 0) {
1303 		ASSERT3U(size, ==, 1ULL << dnp->dn_indblkshift);
1304 		return (0);
1305 	}
1306 
1307 	if (zb->zb_level == -1) {
1308 		ASSERT3U(size, ==, sizeof (objset_phys_t));
1309 		return (0);
1310 	}
1311 
1312 	ASSERT(zb->zb_level == 0);
1313 	ASSERT3U(size, ==, dnp->dn_datablkszsec << DEV_BSHIFT);
1314 
1315 	return (0);
1316 }
1317 
1318 /*
1319  * Verify that live pool traversal works.
1320  */
1321 void
1322 ztest_traverse(ztest_args_t *za)
1323 {
1324 	spa_t *spa = dmu_objset_spa(za->za_os);
1325 	traverse_handle_t *th = za->za_th;
1326 	int rc, advance;
1327 	uint64_t cbstart, cblimit;
1328 
1329 	if (th == NULL) {
1330 		advance = 0;
1331 
1332 		if (ztest_random(2) == 0)
1333 			advance |= ADVANCE_PRE;
1334 
1335 		if (ztest_random(2) == 0)
1336 			advance |= ADVANCE_PRUNE;
1337 
1338 		if (ztest_random(2) == 0)
1339 			advance |= ADVANCE_DATA;
1340 
1341 		if (ztest_random(2) == 0)
1342 			advance |= ADVANCE_HOLES;
1343 
1344 		th = za->za_th = traverse_init(spa, ztest_blk_cb, za, advance,
1345 		    ZIO_FLAG_CANFAIL);
1346 
1347 		traverse_add_pool(th, 0, -1ULL);
1348 	}
1349 
1350 	advance = th->th_advance;
1351 	cbstart = th->th_callbacks;
1352 	cblimit = cbstart + ((advance & ADVANCE_DATA) ? 100 : 1000);
1353 
1354 	while ((rc = traverse_more(th)) == EAGAIN && th->th_callbacks < cblimit)
1355 		continue;
1356 
1357 	if (zopt_verbose >= 5)
1358 		(void) printf("traverse %s%s%s%s %llu blocks to "
1359 		    "<%llu, %llu, %d, %llx>%s\n",
1360 		    (advance & ADVANCE_PRE) ? "pre" : "post",
1361 		    (advance & ADVANCE_PRUNE) ? "|prune" : "",
1362 		    (advance & ADVANCE_DATA) ? "|data" : "",
1363 		    (advance & ADVANCE_HOLES) ? "|holes" : "",
1364 		    (u_longlong_t)(th->th_callbacks - cbstart),
1365 		    (u_longlong_t)th->th_lastcb.zb_objset,
1366 		    (u_longlong_t)th->th_lastcb.zb_object,
1367 		    th->th_lastcb.zb_level,
1368 		    (u_longlong_t)th->th_lastcb.zb_blkid,
1369 		    rc == 0 ? " [done]" :
1370 		    rc == EINTR ? " [aborted]" :
1371 		    rc == EAGAIN ? "" :
1372 		    strerror(rc));
1373 
1374 	if (rc != EAGAIN) {
1375 		if (rc != 0 && rc != EINTR)
1376 			fatal(0, "traverse_more(%p) = %d", th, rc);
1377 		traverse_fini(th);
1378 		za->za_th = NULL;
1379 	}
1380 }
1381 
1382 /*
1383  * Verify that dmu_object_{alloc,free} work as expected.
1384  */
1385 void
1386 ztest_dmu_object_alloc_free(ztest_args_t *za)
1387 {
1388 	objset_t *os = za->za_os;
1389 	dmu_buf_t *db;
1390 	dmu_tx_t *tx;
1391 	uint64_t batchobj, object, batchsize, endoff, temp;
1392 	int b, c, error, bonuslen;
1393 	dmu_object_info_t doi;
1394 	char osname[MAXNAMELEN];
1395 
1396 	dmu_objset_name(os, osname);
1397 
1398 	endoff = -8ULL;
1399 	batchsize = 2;
1400 
1401 	/*
1402 	 * Create a batch object if necessary, and record it in the directory.
1403 	 */
1404 	dmu_read(os, ZTEST_DIROBJ, za->za_diroff, sizeof (uint64_t), &batchobj);
1405 	if (batchobj == 0) {
1406 		tx = dmu_tx_create(os);
1407 		dmu_tx_hold_write(tx, ZTEST_DIROBJ, za->za_diroff,
1408 		    sizeof (uint64_t));
1409 		dmu_tx_hold_bonus(tx, DMU_NEW_OBJECT);
1410 		error = dmu_tx_assign(tx, TXG_WAIT);
1411 		if (error) {
1412 			ztest_record_enospc("create a batch object");
1413 			dmu_tx_abort(tx);
1414 			return;
1415 		}
1416 		batchobj = dmu_object_alloc(os, DMU_OT_UINT64_OTHER, 0,
1417 		    DMU_OT_NONE, 0, tx);
1418 		ztest_set_random_blocksize(os, batchobj, tx);
1419 		dmu_write(os, ZTEST_DIROBJ, za->za_diroff,
1420 		    sizeof (uint64_t), &batchobj, tx);
1421 		dmu_tx_commit(tx);
1422 	}
1423 
1424 	/*
1425 	 * Destroy the previous batch of objects.
1426 	 */
1427 	for (b = 0; b < batchsize; b++) {
1428 		dmu_read(os, batchobj, b * sizeof (uint64_t),
1429 		    sizeof (uint64_t), &object);
1430 		if (object == 0)
1431 			continue;
1432 		/*
1433 		 * Read and validate contents.
1434 		 * We expect the nth byte of the bonus buffer to be n.
1435 		 */
1436 		db = dmu_bonus_hold(os, object);
1437 
1438 		dmu_object_info_from_db(db, &doi);
1439 		ASSERT(doi.doi_type == DMU_OT_UINT64_OTHER);
1440 		ASSERT(doi.doi_bonus_type == DMU_OT_PLAIN_OTHER);
1441 		ASSERT3S(doi.doi_physical_blks, >=, 0);
1442 
1443 		dmu_buf_read(db);
1444 
1445 		bonuslen = db->db_size;
1446 
1447 		for (c = 0; c < bonuslen; c++) {
1448 			if (((uint8_t *)db->db_data)[c] !=
1449 			    (uint8_t)(c + bonuslen)) {
1450 				fatal(0,
1451 				    "bad bonus: %s, obj %llu, off %d: %u != %u",
1452 				    osname, object, c,
1453 				    ((uint8_t *)db->db_data)[c],
1454 				    (uint8_t)(c + bonuslen));
1455 			}
1456 		}
1457 
1458 		dmu_buf_rele(db);
1459 
1460 		/*
1461 		 * We expect the word at endoff to be our object number.
1462 		 */
1463 		dmu_read(os, object, endoff, sizeof (uint64_t), &temp);
1464 
1465 		if (temp != object) {
1466 			fatal(0, "bad data in %s, got %llu, expected %llu",
1467 			    osname, temp, object);
1468 		}
1469 
1470 		/*
1471 		 * Destroy old object and clear batch entry.
1472 		 */
1473 		tx = dmu_tx_create(os);
1474 		dmu_tx_hold_write(tx, batchobj,
1475 		    b * sizeof (uint64_t), sizeof (uint64_t));
1476 		dmu_tx_hold_free(tx, object, 0, DMU_OBJECT_END);
1477 		error = dmu_tx_assign(tx, TXG_WAIT);
1478 		if (error) {
1479 			ztest_record_enospc("free object");
1480 			dmu_tx_abort(tx);
1481 			return;
1482 		}
1483 		error = dmu_object_free(os, object, tx);
1484 		if (error) {
1485 			fatal(0, "dmu_object_free('%s', %llu) = %d",
1486 			    osname, object, error);
1487 		}
1488 		object = 0;
1489 
1490 		dmu_object_set_checksum(os, batchobj,
1491 		    ztest_random_checksum(), tx);
1492 		dmu_object_set_compress(os, batchobj,
1493 		    ztest_random_compress(), tx);
1494 
1495 		dmu_write(os, batchobj, b * sizeof (uint64_t),
1496 		    sizeof (uint64_t), &object, tx);
1497 
1498 		dmu_tx_commit(tx);
1499 	}
1500 
1501 	/*
1502 	 * Before creating the new batch of objects, generate a bunch of churn.
1503 	 */
1504 	for (b = ztest_random(100); b > 0; b--) {
1505 		tx = dmu_tx_create(os);
1506 		dmu_tx_hold_bonus(tx, DMU_NEW_OBJECT);
1507 		error = dmu_tx_assign(tx, TXG_WAIT);
1508 		if (error) {
1509 			ztest_record_enospc("churn objects");
1510 			dmu_tx_abort(tx);
1511 			return;
1512 		}
1513 		object = dmu_object_alloc(os, DMU_OT_UINT64_OTHER, 0,
1514 		    DMU_OT_NONE, 0, tx);
1515 		ztest_set_random_blocksize(os, object, tx);
1516 		error = dmu_object_free(os, object, tx);
1517 		if (error) {
1518 			fatal(0, "dmu_object_free('%s', %llu) = %d",
1519 			    osname, object, error);
1520 		}
1521 		dmu_tx_commit(tx);
1522 	}
1523 
1524 	/*
1525 	 * Create a new batch of objects with randomly chosen
1526 	 * blocksizes and record them in the batch directory.
1527 	 */
1528 	for (b = 0; b < batchsize; b++) {
1529 		uint32_t va_blksize;
1530 		u_longlong_t va_nblocks;
1531 
1532 		tx = dmu_tx_create(os);
1533 		dmu_tx_hold_write(tx, batchobj, b * sizeof (uint64_t),
1534 		    sizeof (uint64_t));
1535 		dmu_tx_hold_bonus(tx, DMU_NEW_OBJECT);
1536 		dmu_tx_hold_write(tx, DMU_NEW_OBJECT, endoff,
1537 		    sizeof (uint64_t));
1538 		error = dmu_tx_assign(tx, TXG_WAIT);
1539 		if (error) {
1540 			ztest_record_enospc("create batchobj");
1541 			dmu_tx_abort(tx);
1542 			return;
1543 		}
1544 		bonuslen = (int)ztest_random(dmu_bonus_max()) + 1;
1545 
1546 		object = dmu_object_alloc(os, DMU_OT_UINT64_OTHER, 0,
1547 		    DMU_OT_PLAIN_OTHER, bonuslen, tx);
1548 
1549 		ztest_set_random_blocksize(os, object, tx);
1550 
1551 		dmu_object_set_checksum(os, object,
1552 		    ztest_random_checksum(), tx);
1553 		dmu_object_set_compress(os, object,
1554 		    ztest_random_compress(), tx);
1555 
1556 		dmu_write(os, batchobj, b * sizeof (uint64_t),
1557 		    sizeof (uint64_t), &object, tx);
1558 
1559 		/*
1560 		 * Write to both the bonus buffer and the regular data.
1561 		 */
1562 		db = dmu_bonus_hold(os, object);
1563 		ASSERT3U(bonuslen, ==, db->db_size);
1564 
1565 		dmu_object_size_from_db(db, &va_blksize, &va_nblocks);
1566 		ASSERT3S(va_nblocks, >=, 0);
1567 
1568 		dmu_buf_will_dirty(db, tx);
1569 
1570 		/*
1571 		 * See comments above regarding the contents of
1572 		 * the bonus buffer and the word at endoff.
1573 		 */
1574 		for (c = 0; c < db->db_size; c++)
1575 			((uint8_t *)db->db_data)[c] = (uint8_t)(c + bonuslen);
1576 
1577 		dmu_buf_rele(db);
1578 
1579 		/*
1580 		 * Write to a large offset to increase indirection.
1581 		 */
1582 		dmu_write(os, object, endoff, sizeof (uint64_t), &object, tx);
1583 
1584 		dmu_tx_commit(tx);
1585 	}
1586 }
1587 
1588 /*
1589  * Verify that dmu_{read,write} work as expected.
1590  */
1591 typedef struct bufwad {
1592 	uint64_t	bw_index;
1593 	uint64_t	bw_txg;
1594 	uint64_t	bw_data;
1595 } bufwad_t;
1596 
1597 typedef struct dmu_read_write_dir {
1598 	uint64_t	dd_packobj;
1599 	uint64_t	dd_bigobj;
1600 	uint64_t	dd_chunk;
1601 } dmu_read_write_dir_t;
1602 
1603 void
1604 ztest_dmu_read_write(ztest_args_t *za)
1605 {
1606 	objset_t *os = za->za_os;
1607 	dmu_read_write_dir_t dd;
1608 	dmu_tx_t *tx;
1609 	int i, freeit, error;
1610 	uint64_t n, s, txg;
1611 	bufwad_t *packbuf, *bigbuf, *pack, *bigH, *bigT;
1612 	uint64_t packoff, packsize, bigoff, bigsize;
1613 	uint64_t regions = 997;
1614 	uint64_t stride = 123456789ULL;
1615 	uint64_t width = 40;
1616 	int free_percent = 5;
1617 
1618 	/*
1619 	 * This test uses two objects, packobj and bigobj, that are always
1620 	 * updated together (i.e. in the same tx) so that their contents are
1621 	 * in sync and can be compared.  Their contents relate to each other
1622 	 * in a simple way: packobj is a dense array of 'bufwad' structures,
1623 	 * while bigobj is a sparse array of the same bufwads.  Specifically,
1624 	 * for any index n, there are three bufwads that should be identical:
1625 	 *
1626 	 *	packobj, at offset n * sizeof (bufwad_t)
1627 	 *	bigobj, at the head of the nth chunk
1628 	 *	bigobj, at the tail of the nth chunk
1629 	 *
1630 	 * The chunk size is arbitrary. It doesn't have to be a power of two,
1631 	 * and it doesn't have any relation to the object blocksize.
1632 	 * The only requirement is that it can hold at least two bufwads.
1633 	 *
1634 	 * Normally, we write the bufwad to each of these locations.
1635 	 * However, free_percent of the time we instead write zeroes to
1636 	 * packobj and perform a dmu_free_range() on bigobj.  By comparing
1637 	 * bigobj to packobj, we can verify that the DMU is correctly
1638 	 * tracking which parts of an object are allocated and free,
1639 	 * and that the contents of the allocated blocks are correct.
1640 	 */
1641 
1642 	/*
1643 	 * Read the directory info.  If it's the first time, set things up.
1644 	 */
1645 	dmu_read(os, ZTEST_DIROBJ, za->za_diroff, sizeof (dd), &dd);
1646 	if (dd.dd_chunk == 0) {
1647 		ASSERT(dd.dd_packobj == 0);
1648 		ASSERT(dd.dd_bigobj == 0);
1649 		tx = dmu_tx_create(os);
1650 		dmu_tx_hold_write(tx, ZTEST_DIROBJ, za->za_diroff, sizeof (dd));
1651 		dmu_tx_hold_bonus(tx, DMU_NEW_OBJECT);
1652 		error = dmu_tx_assign(tx, TXG_WAIT);
1653 		if (error) {
1654 			ztest_record_enospc("create r/w directory");
1655 			dmu_tx_abort(tx);
1656 			return;
1657 		}
1658 
1659 		dd.dd_packobj = dmu_object_alloc(os, DMU_OT_UINT64_OTHER, 0,
1660 		    DMU_OT_NONE, 0, tx);
1661 		dd.dd_bigobj = dmu_object_alloc(os, DMU_OT_UINT64_OTHER, 0,
1662 		    DMU_OT_NONE, 0, tx);
1663 		dd.dd_chunk = (1000 + ztest_random(1000)) * sizeof (uint64_t);
1664 
1665 		ztest_set_random_blocksize(os, dd.dd_packobj, tx);
1666 		ztest_set_random_blocksize(os, dd.dd_bigobj, tx);
1667 
1668 		dmu_write(os, ZTEST_DIROBJ, za->za_diroff, sizeof (dd), &dd,
1669 		    tx);
1670 		dmu_tx_commit(tx);
1671 	}
1672 
1673 	/*
1674 	 * Prefetch a random chunk of the big object.
1675 	 * Our aim here is to get some async reads in flight
1676 	 * for blocks that we may free below; the DMU should
1677 	 * handle this race correctly.
1678 	 */
1679 	n = ztest_random(regions) * stride + ztest_random(width);
1680 	s = 1 + ztest_random(2 * width - 1);
1681 	dmu_prefetch(os, dd.dd_bigobj, n * dd.dd_chunk, s * dd.dd_chunk);
1682 
1683 	/*
1684 	 * Pick a random index and compute the offsets into packobj and bigobj.
1685 	 */
1686 	n = ztest_random(regions) * stride + ztest_random(width);
1687 	s = 1 + ztest_random(width - 1);
1688 
1689 	packoff = n * sizeof (bufwad_t);
1690 	packsize = s * sizeof (bufwad_t);
1691 
1692 	bigoff = n * dd.dd_chunk;
1693 	bigsize = s * dd.dd_chunk;
1694 
1695 	packbuf = umem_alloc(packsize, UMEM_NOFAIL);
1696 	bigbuf = umem_alloc(bigsize, UMEM_NOFAIL);
1697 
1698 	/*
1699 	 * free_percent of the time, free a range of bigobj rather than
1700 	 * overwriting it.
1701 	 */
1702 	freeit = (ztest_random(100) < free_percent);
1703 
1704 	/*
1705 	 * Read the current contents of our objects.
1706 	 */
1707 	dmu_read(os, dd.dd_packobj, packoff, packsize, packbuf);
1708 	dmu_read(os, dd.dd_bigobj, bigoff, bigsize, bigbuf);
1709 
1710 	/*
1711 	 * Get a tx for the mods to both packobj and bigobj.
1712 	 */
1713 	tx = dmu_tx_create(os);
1714 
1715 	dmu_tx_hold_write(tx, dd.dd_packobj, packoff, packsize);
1716 
1717 	if (freeit)
1718 		dmu_tx_hold_free(tx, dd.dd_bigobj, bigoff, bigsize);
1719 	else
1720 		dmu_tx_hold_write(tx, dd.dd_bigobj, bigoff, bigsize);
1721 
1722 	error = dmu_tx_assign(tx, TXG_WAIT);
1723 
1724 	if (error) {
1725 		ztest_record_enospc("dmu r/w range");
1726 		dmu_tx_abort(tx);
1727 		umem_free(packbuf, packsize);
1728 		umem_free(bigbuf, bigsize);
1729 		return;
1730 	}
1731 
1732 	txg = dmu_tx_get_txg(tx);
1733 
1734 	/*
1735 	 * For each index from n to n + s, verify that the existing bufwad
1736 	 * in packobj matches the bufwads at the head and tail of the
1737 	 * corresponding chunk in bigobj.  Then update all three bufwads
1738 	 * with the new values we want to write out.
1739 	 */
1740 	for (i = 0; i < s; i++) {
1741 		/* LINTED */
1742 		pack = (bufwad_t *)((char *)packbuf + i * sizeof (bufwad_t));
1743 		/* LINTED */
1744 		bigH = (bufwad_t *)((char *)bigbuf + i * dd.dd_chunk);
1745 		/* LINTED */
1746 		bigT = (bufwad_t *)((char *)bigH + dd.dd_chunk) - 1;
1747 
1748 		ASSERT((uintptr_t)bigH - (uintptr_t)bigbuf < bigsize);
1749 		ASSERT((uintptr_t)bigT - (uintptr_t)bigbuf < bigsize);
1750 
1751 		if (pack->bw_txg > txg)
1752 			fatal(0, "future leak: got %llx, open txg is %llx",
1753 			    pack->bw_txg, txg);
1754 
1755 		if (pack->bw_data != 0 && pack->bw_index != n + i)
1756 			fatal(0, "wrong index: got %llx, wanted %llx+%llx",
1757 			    pack->bw_index, n, i);
1758 
1759 		if (bcmp(pack, bigH, sizeof (bufwad_t)) != 0)
1760 			fatal(0, "pack/bigH mismatch in %p/%p", pack, bigH);
1761 
1762 		if (bcmp(pack, bigT, sizeof (bufwad_t)) != 0)
1763 			fatal(0, "pack/bigT mismatch in %p/%p", pack, bigT);
1764 
1765 		if (freeit) {
1766 			bzero(pack, sizeof (bufwad_t));
1767 		} else {
1768 			pack->bw_index = n + i;
1769 			pack->bw_txg = txg;
1770 			pack->bw_data = 1 + ztest_random(-2ULL);
1771 		}
1772 		*bigH = *pack;
1773 		*bigT = *pack;
1774 	}
1775 
1776 	/*
1777 	 * We've verified all the old bufwads, and made new ones.
1778 	 * Now write them out.
1779 	 */
1780 	dmu_write(os, dd.dd_packobj, packoff, packsize, packbuf, tx);
1781 
1782 	if (freeit) {
1783 		if (zopt_verbose >= 6) {
1784 			(void) printf("freeing offset %llx size %llx"
1785 			    " txg %llx\n",
1786 			    (u_longlong_t)bigoff,
1787 			    (u_longlong_t)bigsize,
1788 			    (u_longlong_t)txg);
1789 		}
1790 		dmu_free_range(os, dd.dd_bigobj, bigoff, bigsize, tx);
1791 	} else {
1792 		if (zopt_verbose >= 6) {
1793 			(void) printf("writing offset %llx size %llx"
1794 			    " txg %llx\n",
1795 			    (u_longlong_t)bigoff,
1796 			    (u_longlong_t)bigsize,
1797 			    (u_longlong_t)txg);
1798 		}
1799 		dmu_write(os, dd.dd_bigobj, bigoff, bigsize, bigbuf, tx);
1800 	}
1801 
1802 	dmu_tx_commit(tx);
1803 
1804 	/*
1805 	 * Sanity check the stuff we just wrote.
1806 	 */
1807 	{
1808 		void *packcheck = umem_alloc(packsize, UMEM_NOFAIL);
1809 		void *bigcheck = umem_alloc(bigsize, UMEM_NOFAIL);
1810 
1811 		dmu_read(os, dd.dd_packobj, packoff, packsize, packcheck);
1812 		dmu_read(os, dd.dd_bigobj, bigoff, bigsize, bigcheck);
1813 
1814 		ASSERT(bcmp(packbuf, packcheck, packsize) == 0);
1815 		ASSERT(bcmp(bigbuf, bigcheck, bigsize) == 0);
1816 
1817 		umem_free(packcheck, packsize);
1818 		umem_free(bigcheck, bigsize);
1819 	}
1820 
1821 	umem_free(packbuf, packsize);
1822 	umem_free(bigbuf, bigsize);
1823 }
1824 
1825 void
1826 ztest_dmu_write_parallel(ztest_args_t *za)
1827 {
1828 	objset_t *os = za->za_os;
1829 	dmu_tx_t *tx;
1830 	dmu_buf_t *db;
1831 	int i, b, error, do_free, bs;
1832 	uint64_t off, txg_how, txg;
1833 	mutex_t *lp;
1834 	char osname[MAXNAMELEN];
1835 	char iobuf[SPA_MAXBLOCKSIZE];
1836 	ztest_block_tag_t rbt, wbt;
1837 
1838 	dmu_objset_name(os, osname);
1839 	bs = ZTEST_DIROBJ_BLOCKSIZE;
1840 
1841 	/*
1842 	 * Have multiple threads write to large offsets in ZTEST_DIROBJ
1843 	 * to verify that having multiple threads writing to the same object
1844 	 * in parallel doesn't cause any trouble.
1845 	 * Also do parallel writes to the bonus buffer on occasion.
1846 	 */
1847 	for (i = 0; i < 50; i++) {
1848 		b = ztest_random(ZTEST_SYNC_LOCKS);
1849 		lp = &ztest_shared->zs_sync_lock[b];
1850 
1851 		do_free = (ztest_random(4) == 0);
1852 
1853 		off = za->za_diroff_shared + ((uint64_t)b << SPA_MAXBLOCKSHIFT);
1854 
1855 		if (ztest_random(4) == 0) {
1856 			/*
1857 			 * Do the bonus buffer instead of a regular block.
1858 			 */
1859 			do_free = 0;
1860 			off = -1ULL;
1861 		}
1862 
1863 		tx = dmu_tx_create(os);
1864 
1865 		if (off == -1ULL)
1866 			dmu_tx_hold_bonus(tx, ZTEST_DIROBJ);
1867 		else if (do_free)
1868 			dmu_tx_hold_free(tx, ZTEST_DIROBJ, off, bs);
1869 		else
1870 			dmu_tx_hold_write(tx, ZTEST_DIROBJ, off, bs);
1871 
1872 		txg_how = ztest_random(2) == 0 ? TXG_WAIT : TXG_NOWAIT;
1873 		error = dmu_tx_assign(tx, txg_how);
1874 		if (error) {
1875 			dmu_tx_abort(tx);
1876 			if (error == ERESTART) {
1877 				ASSERT(txg_how == TXG_NOWAIT);
1878 				txg_wait_open(dmu_objset_pool(os), 0);
1879 				continue;
1880 			}
1881 			ztest_record_enospc("dmu write parallel");
1882 			return;
1883 		}
1884 		txg = dmu_tx_get_txg(tx);
1885 
1886 		if (do_free) {
1887 			(void) mutex_lock(lp);
1888 			dmu_free_range(os, ZTEST_DIROBJ, off, bs, tx);
1889 			(void) mutex_unlock(lp);
1890 			dmu_tx_commit(tx);
1891 			continue;
1892 		}
1893 
1894 		wbt.bt_objset = dmu_objset_id(os);
1895 		wbt.bt_object = ZTEST_DIROBJ;
1896 		wbt.bt_offset = off;
1897 		wbt.bt_txg = txg;
1898 		wbt.bt_thread = za->za_instance;
1899 
1900 		if (off == -1ULL) {
1901 			wbt.bt_seq = 0;
1902 			db = dmu_bonus_hold(os, ZTEST_DIROBJ);
1903 			ASSERT3U(db->db_size, ==, sizeof (wbt));
1904 			dmu_buf_read(db);
1905 			bcopy(db->db_data, &rbt, db->db_size);
1906 			if (rbt.bt_objset != 0) {
1907 				ASSERT3U(rbt.bt_objset, ==, wbt.bt_objset);
1908 				ASSERT3U(rbt.bt_object, ==, wbt.bt_object);
1909 				ASSERT3U(rbt.bt_offset, ==, wbt.bt_offset);
1910 				ASSERT3U(rbt.bt_txg, <=, wbt.bt_txg);
1911 			}
1912 			dmu_buf_will_dirty(db, tx);
1913 			bcopy(&wbt, db->db_data, db->db_size);
1914 			dmu_buf_rele(db);
1915 			dmu_tx_commit(tx);
1916 			continue;
1917 		}
1918 
1919 		(void) mutex_lock(lp);
1920 
1921 		wbt.bt_seq = ztest_shared->zs_seq[b]++;
1922 
1923 		dmu_write(os, ZTEST_DIROBJ, off, sizeof (wbt), &wbt, tx);
1924 
1925 		(void) mutex_unlock(lp);
1926 
1927 		if (ztest_random(100) == 0)
1928 			(void) poll(NULL, 0, 1); /* open dn_notxholds window */
1929 
1930 		dmu_tx_commit(tx);
1931 
1932 		if (ztest_random(1000) == 0)
1933 			txg_wait_synced(dmu_objset_pool(os), txg);
1934 
1935 		if (ztest_random(2) == 0) {
1936 			blkptr_t blk = { 0 };
1937 			uint64_t blkoff;
1938 
1939 			txg_suspend(dmu_objset_pool(os));
1940 			(void) mutex_lock(lp);
1941 			error = dmu_sync(os, ZTEST_DIROBJ, off, &blkoff, &blk,
1942 			    txg);
1943 			(void) mutex_unlock(lp);
1944 			if (error) {
1945 				txg_resume(dmu_objset_pool(os));
1946 				dprintf("dmu_sync(%s, %d, %llx) = %d\n",
1947 				    osname, ZTEST_DIROBJ, off, error);
1948 				continue;
1949 			}
1950 
1951 			if (blk.blk_birth == 0)	{	/* concurrent free */
1952 				txg_resume(dmu_objset_pool(os));
1953 				continue;
1954 			}
1955 
1956 			ASSERT(blk.blk_fill == 1);
1957 			ASSERT3U(BP_GET_TYPE(&blk), ==, DMU_OT_UINT64_OTHER);
1958 			ASSERT3U(BP_GET_LEVEL(&blk), ==, 0);
1959 			ASSERT3U(BP_GET_LSIZE(&blk), ==, bs);
1960 
1961 			/*
1962 			 * Read the block that dmu_sync() returned to
1963 			 * make sure its contents match what we wrote.
1964 			 * We do this while still txg_suspend()ed to ensure
1965 			 * that the block can't be reused before we read it.
1966 			 */
1967 			error = zio_wait(zio_read(NULL, dmu_objset_spa(os),
1968 			    &blk, iobuf, bs, NULL, NULL,
1969 			    ZIO_PRIORITY_SYNC_READ, ZIO_FLAG_MUSTSUCCEED));
1970 			ASSERT(error == 0);
1971 
1972 			txg_resume(dmu_objset_pool(os));
1973 
1974 			bcopy(&iobuf[blkoff], &rbt, sizeof (rbt));
1975 
1976 			ASSERT3U(rbt.bt_objset, ==, wbt.bt_objset);
1977 			ASSERT3U(rbt.bt_object, ==, wbt.bt_object);
1978 			ASSERT3U(rbt.bt_offset, ==, wbt.bt_offset);
1979 
1980 			/*
1981 			 * The semantic of dmu_sync() is that we always
1982 			 * push the most recent version of the data,
1983 			 * so in the face of concurrent updates we may
1984 			 * see a newer version of the block.  That's OK.
1985 			 */
1986 			ASSERT3U(rbt.bt_txg, >=, wbt.bt_txg);
1987 			if (rbt.bt_thread == wbt.bt_thread)
1988 				ASSERT3U(rbt.bt_seq, ==, wbt.bt_seq);
1989 			else
1990 				ASSERT3U(rbt.bt_seq, >, wbt.bt_seq);
1991 		}
1992 	}
1993 }
1994 
1995 /*
1996  * Verify that zap_{create,destroy,add,remove,update} work as expected.
1997  */
1998 #define	ZTEST_ZAP_MIN_INTS	1
1999 #define	ZTEST_ZAP_MAX_INTS	4
2000 #define	ZTEST_ZAP_MAX_PROPS	1000
2001 
2002 void
2003 ztest_zap(ztest_args_t *za)
2004 {
2005 	objset_t *os = za->za_os;
2006 	uint64_t object;
2007 	uint64_t txg, last_txg;
2008 	uint64_t value[ZTEST_ZAP_MAX_INTS];
2009 	uint64_t zl_ints, zl_intsize, prop;
2010 	int i, ints;
2011 	int iters = 100;
2012 	dmu_tx_t *tx;
2013 	char propname[100], txgname[100];
2014 	int error;
2015 	char osname[MAXNAMELEN];
2016 	char *hc[2] = { "s.acl.h", ".s.open.h.hyLZlg" };
2017 
2018 	dmu_objset_name(os, osname);
2019 
2020 	/*
2021 	 * Create a new object if necessary, and record it in the directory.
2022 	 */
2023 	dmu_read(os, ZTEST_DIROBJ, za->za_diroff, sizeof (uint64_t), &object);
2024 
2025 	if (object == 0) {
2026 		tx = dmu_tx_create(os);
2027 		dmu_tx_hold_write(tx, ZTEST_DIROBJ, za->za_diroff,
2028 		    sizeof (uint64_t));
2029 		dmu_tx_hold_zap(tx, DMU_NEW_OBJECT, 2);
2030 		error = dmu_tx_assign(tx, TXG_WAIT);
2031 		if (error) {
2032 			ztest_record_enospc("create zap test obj");
2033 			dmu_tx_abort(tx);
2034 			return;
2035 		}
2036 		object = zap_create(os, DMU_OT_ZAP_OTHER, DMU_OT_NONE, 0, tx);
2037 		if (error) {
2038 			fatal(0, "zap_create('%s', %llu) = %d",
2039 			    osname, object, error);
2040 		}
2041 		ASSERT(object != 0);
2042 		dmu_write(os, ZTEST_DIROBJ, za->za_diroff,
2043 		    sizeof (uint64_t), &object, tx);
2044 		/*
2045 		 * Generate a known hash collision, and verify that
2046 		 * we can lookup and remove both entries.
2047 		 */
2048 		for (i = 0; i < 2; i++) {
2049 			value[i] = i;
2050 			error = zap_add(os, object, hc[i], sizeof (uint64_t),
2051 			    1, &value[i], tx);
2052 			ASSERT3U(error, ==, 0);
2053 		}
2054 		for (i = 0; i < 2; i++) {
2055 			error = zap_add(os, object, hc[i], sizeof (uint64_t),
2056 			    1, &value[i], tx);
2057 			ASSERT3U(error, ==, EEXIST);
2058 			error = zap_length(os, object, hc[i],
2059 			    &zl_intsize, &zl_ints);
2060 			ASSERT3U(error, ==, 0);
2061 			ASSERT3U(zl_intsize, ==, sizeof (uint64_t));
2062 			ASSERT3U(zl_ints, ==, 1);
2063 		}
2064 		for (i = 0; i < 2; i++) {
2065 			error = zap_remove(os, object, hc[i], tx);
2066 			ASSERT3U(error, ==, 0);
2067 		}
2068 
2069 		dmu_tx_commit(tx);
2070 	}
2071 
2072 	ints = MAX(ZTEST_ZAP_MIN_INTS, object % ZTEST_ZAP_MAX_INTS);
2073 
2074 	while (--iters >= 0) {
2075 		prop = ztest_random(ZTEST_ZAP_MAX_PROPS);
2076 		(void) sprintf(propname, "prop_%llu", (u_longlong_t)prop);
2077 		(void) sprintf(txgname, "txg_%llu", (u_longlong_t)prop);
2078 		bzero(value, sizeof (value));
2079 		last_txg = 0;
2080 
2081 		/*
2082 		 * If these zap entries already exist, validate their contents.
2083 		 */
2084 		error = zap_length(os, object, txgname, &zl_intsize, &zl_ints);
2085 		if (error == 0) {
2086 			ASSERT3U(zl_intsize, ==, sizeof (uint64_t));
2087 			ASSERT3U(zl_ints, ==, 1);
2088 
2089 			error = zap_lookup(os, object, txgname, zl_intsize,
2090 			    zl_ints, &last_txg);
2091 
2092 			ASSERT3U(error, ==, 0);
2093 
2094 			error = zap_length(os, object, propname, &zl_intsize,
2095 			    &zl_ints);
2096 
2097 			ASSERT3U(error, ==, 0);
2098 			ASSERT3U(zl_intsize, ==, sizeof (uint64_t));
2099 			ASSERT3U(zl_ints, ==, ints);
2100 
2101 			error = zap_lookup(os, object, propname, zl_intsize,
2102 			    zl_ints, value);
2103 
2104 			ASSERT3U(error, ==, 0);
2105 
2106 			for (i = 0; i < ints; i++) {
2107 				ASSERT3U(value[i], ==, last_txg + object + i);
2108 			}
2109 		} else {
2110 			ASSERT3U(error, ==, ENOENT);
2111 		}
2112 
2113 		/*
2114 		 * Atomically update two entries in our zap object.
2115 		 * The first is named txg_%llu, and contains the txg
2116 		 * in which the property was last updated.  The second
2117 		 * is named prop_%llu, and the nth element of its value
2118 		 * should be txg + object + n.
2119 		 */
2120 		tx = dmu_tx_create(os);
2121 		dmu_tx_hold_zap(tx, object, 2);
2122 		error = dmu_tx_assign(tx, TXG_WAIT);
2123 		if (error) {
2124 			ztest_record_enospc("create zap entry");
2125 			dmu_tx_abort(tx);
2126 			return;
2127 		}
2128 		txg = dmu_tx_get_txg(tx);
2129 
2130 		if (last_txg > txg)
2131 			fatal(0, "zap future leak: old %llu new %llu",
2132 			    last_txg, txg);
2133 
2134 		for (i = 0; i < ints; i++)
2135 			value[i] = txg + object + i;
2136 
2137 		error = zap_update(os, object, txgname, sizeof (uint64_t),
2138 		    1, &txg, tx);
2139 		if (error)
2140 			fatal(0, "zap_update('%s', %llu, '%s') = %d",
2141 			    osname, object, txgname, error);
2142 
2143 		error = zap_update(os, object, propname, sizeof (uint64_t),
2144 		    ints, value, tx);
2145 		if (error)
2146 			fatal(0, "zap_update('%s', %llu, '%s') = %d",
2147 			    osname, object, propname, error);
2148 
2149 		dmu_tx_commit(tx);
2150 
2151 		/*
2152 		 * Remove a random pair of entries.
2153 		 */
2154 		prop = ztest_random(ZTEST_ZAP_MAX_PROPS);
2155 		(void) sprintf(propname, "prop_%llu", (u_longlong_t)prop);
2156 		(void) sprintf(txgname, "txg_%llu", (u_longlong_t)prop);
2157 
2158 		error = zap_length(os, object, txgname, &zl_intsize, &zl_ints);
2159 
2160 		if (error == ENOENT)
2161 			continue;
2162 
2163 		ASSERT3U(error, ==, 0);
2164 
2165 		tx = dmu_tx_create(os);
2166 		dmu_tx_hold_zap(tx, object, 2);
2167 		error = dmu_tx_assign(tx, TXG_WAIT);
2168 		if (error) {
2169 			ztest_record_enospc("remove zap entry");
2170 			dmu_tx_abort(tx);
2171 			return;
2172 		}
2173 		error = zap_remove(os, object, txgname, tx);
2174 		if (error)
2175 			fatal(0, "zap_remove('%s', %llu, '%s') = %d",
2176 			    osname, object, txgname, error);
2177 
2178 		error = zap_remove(os, object, propname, tx);
2179 		if (error)
2180 			fatal(0, "zap_remove('%s', %llu, '%s') = %d",
2181 			    osname, object, propname, error);
2182 
2183 		dmu_tx_commit(tx);
2184 	}
2185 
2186 	/*
2187 	 * Once in a while, destroy the object.
2188 	 */
2189 	if (ztest_random(100) != 0)
2190 		return;
2191 
2192 	tx = dmu_tx_create(os);
2193 	dmu_tx_hold_write(tx, ZTEST_DIROBJ, za->za_diroff, sizeof (uint64_t));
2194 	dmu_tx_hold_free(tx, object, 0, DMU_OBJECT_END);
2195 	error = dmu_tx_assign(tx, TXG_WAIT);
2196 	if (error) {
2197 		ztest_record_enospc("destroy zap object");
2198 		dmu_tx_abort(tx);
2199 		return;
2200 	}
2201 	error = zap_destroy(os, object, tx);
2202 	if (error)
2203 		fatal(0, "zap_destroy('%s', %llu) = %d",
2204 		    osname, object, error);
2205 	object = 0;
2206 	dmu_write(os, ZTEST_DIROBJ, za->za_diroff, sizeof (uint64_t),
2207 	    &object, tx);
2208 	dmu_tx_commit(tx);
2209 }
2210 
2211 void
2212 ztest_zap_parallel(ztest_args_t *za)
2213 {
2214 	objset_t *os = za->za_os;
2215 	uint64_t txg, object, count, wsize, wc, zl_wsize, zl_wc;
2216 	int iters = 100;
2217 	dmu_tx_t *tx;
2218 	int i, namelen, error;
2219 	char name[20], string_value[20];
2220 	void *data;
2221 
2222 	while (--iters >= 0) {
2223 		/*
2224 		 * Generate a random name of the form 'xxx.....' where each
2225 		 * x is a random printable character and the dots are dots.
2226 		 * There are 94 such characters, and the name length goes from
2227 		 * 6 to 20, so there are 94^3 * 15 = 12,458,760 possible names.
2228 		 */
2229 		namelen = ztest_random(sizeof (name) - 5) + 5 + 1;
2230 
2231 		for (i = 0; i < 3; i++)
2232 			name[i] = '!' + ztest_random('~' - '!' + 1);
2233 		for (; i < namelen - 1; i++)
2234 			name[i] = '.';
2235 		name[i] = '\0';
2236 
2237 		if (ztest_random(2) == 0)
2238 			object = ZTEST_MICROZAP_OBJ;
2239 		else
2240 			object = ZTEST_FATZAP_OBJ;
2241 
2242 		if ((namelen & 1) || object == ZTEST_MICROZAP_OBJ) {
2243 			wsize = sizeof (txg);
2244 			wc = 1;
2245 			data = &txg;
2246 		} else {
2247 			wsize = 1;
2248 			wc = namelen;
2249 			data = string_value;
2250 		}
2251 
2252 		count = -1ULL;
2253 		VERIFY(zap_count(os, object, &count) == 0);
2254 		ASSERT(count != -1ULL);
2255 
2256 		/*
2257 		 * Select an operation: length, lookup, add, update, remove.
2258 		 */
2259 		i = ztest_random(5);
2260 
2261 		if (i >= 2) {
2262 			tx = dmu_tx_create(os);
2263 			dmu_tx_hold_zap(tx, object, 1);
2264 			error = dmu_tx_assign(tx, TXG_WAIT);
2265 			if (error) {
2266 				ztest_record_enospc("zap parallel");
2267 				dmu_tx_abort(tx);
2268 				return;
2269 			}
2270 			txg = dmu_tx_get_txg(tx);
2271 			bcopy(name, string_value, namelen);
2272 		} else {
2273 			tx = NULL;
2274 			txg = 0;
2275 			bzero(string_value, namelen);
2276 		}
2277 
2278 		switch (i) {
2279 
2280 		case 0:
2281 			error = zap_length(os, object, name, &zl_wsize, &zl_wc);
2282 			if (error == 0) {
2283 				ASSERT3U(wsize, ==, zl_wsize);
2284 				ASSERT3U(wc, ==, zl_wc);
2285 			} else {
2286 				ASSERT3U(error, ==, ENOENT);
2287 			}
2288 			break;
2289 
2290 		case 1:
2291 			error = zap_lookup(os, object, name, wsize, wc, data);
2292 			if (error == 0) {
2293 				if (data == string_value &&
2294 				    bcmp(name, data, namelen) != 0)
2295 					fatal(0, "name '%s' != val '%s' len %d",
2296 					    name, data, namelen);
2297 			} else {
2298 				ASSERT3U(error, ==, ENOENT);
2299 			}
2300 			break;
2301 
2302 		case 2:
2303 			error = zap_add(os, object, name, wsize, wc, data, tx);
2304 			ASSERT(error == 0 || error == EEXIST);
2305 			break;
2306 
2307 		case 3:
2308 			VERIFY(zap_update(os, object, name, wsize, wc,
2309 			    data, tx) == 0);
2310 			break;
2311 
2312 		case 4:
2313 			error = zap_remove(os, object, name, tx);
2314 			ASSERT(error == 0 || error == ENOENT);
2315 			break;
2316 		}
2317 
2318 		if (tx != NULL)
2319 			dmu_tx_commit(tx);
2320 	}
2321 }
2322 
2323 void
2324 ztest_dsl_prop_get_set(ztest_args_t *za)
2325 {
2326 	objset_t *os = za->za_os;
2327 	int i, inherit;
2328 	uint64_t value;
2329 	const char *prop, *valname;
2330 	char setpoint[MAXPATHLEN];
2331 	char osname[MAXNAMELEN];
2332 
2333 	(void) rw_rdlock(&ztest_shared->zs_name_lock);
2334 
2335 	dmu_objset_name(os, osname);
2336 
2337 	for (i = 0; i < 2; i++) {
2338 		if (i == 0) {
2339 			prop = "checksum";
2340 			value = ztest_random_checksum();
2341 			inherit = (value == ZIO_CHECKSUM_INHERIT);
2342 		} else {
2343 			prop = "compression";
2344 			value = ztest_random_compress();
2345 			inherit = (value == ZIO_COMPRESS_INHERIT);
2346 		}
2347 
2348 		VERIFY3U(dsl_prop_set(osname, prop, sizeof (value),
2349 		    !inherit, &value), ==, 0);
2350 
2351 		VERIFY3U(dsl_prop_get(osname, prop, sizeof (value),
2352 		    1, &value, setpoint), ==, 0);
2353 
2354 		if (i == 0)
2355 			valname = zio_checksum_table[value].ci_name;
2356 		else
2357 			valname = zio_compress_table[value].ci_name;
2358 
2359 		if (zopt_verbose >= 6) {
2360 			(void) printf("%s %s = %s for '%s'\n",
2361 			    osname, prop, valname, setpoint);
2362 		}
2363 	}
2364 
2365 	(void) rw_unlock(&ztest_shared->zs_name_lock);
2366 }
2367 
2368 /*
2369  * Inject random faults into the on-disk data.
2370  */
2371 void
2372 ztest_fault_inject(ztest_args_t *za)
2373 {
2374 	int fd;
2375 	uint64_t offset;
2376 	uint64_t leaves = MAX(zopt_mirrors, 1) * zopt_raidz;
2377 	uint64_t bad = 0x1990c0ffeedecade;
2378 	uint64_t top, leaf;
2379 	char path0[MAXPATHLEN];
2380 	char path1[MAXPATHLEN];
2381 	char pathrand[MAXPATHLEN];
2382 	size_t fsize;
2383 	spa_t *spa = dmu_objset_spa(za->za_os);
2384 	int bshift = SPA_MAXBLOCKSHIFT + 2;	/* don't scrog all labels */
2385 	int iters = 1000;
2386 	int ftype;
2387 
2388 	/*
2389 	 * Pick a random top-level vdev.
2390 	 */
2391 	spa_config_enter(spa, RW_READER);
2392 	top = ztest_random(spa->spa_root_vdev->vdev_children);
2393 	spa_config_exit(spa);
2394 
2395 	/*
2396 	 * Pick a random leaf.
2397 	 */
2398 	leaf = ztest_random(leaves);
2399 
2400 	/*
2401 	 * Generate paths to the first to leaves in this top-level vdev,
2402 	 * and to the random leaf we selected.  We'll induce transient
2403 	 * faults on leaves 0 and 1, we'll online/offline leaf 1,
2404 	 * and we'll write random garbage to the randomly chosen leaf.
2405 	 */
2406 	(void) snprintf(path0, sizeof (path0),
2407 	    ztest_dev_template, zopt_dir, zopt_pool, top * leaves + 0);
2408 	(void) snprintf(path1, sizeof (path1),
2409 	    ztest_dev_template, zopt_dir, zopt_pool, top * leaves + 1);
2410 	(void) snprintf(pathrand, sizeof (pathrand),
2411 	    ztest_dev_template, zopt_dir, zopt_pool, top * leaves + leaf);
2412 
2413 	if (leaves < 2)			/* there is no second leaf */
2414 		path1[0] = '\0';
2415 
2416 	dprintf("damaging %s, %s, and %s\n", path0, path1, pathrand);
2417 
2418 	/*
2419 	 * If we have exactly one-fault tolerance, just randomly offline
2420 	 * and online one device.
2421 	 */
2422 	if (zopt_maxfaults == 1 && path1[0] != '\0') {
2423 		if (ztest_random(10) < 6)
2424 			(void) vdev_offline(spa, path1);
2425 		else
2426 			(void) vdev_online(spa, path1);
2427 		return;
2428 	}
2429 
2430 	/*
2431 	 * Always inject a little random device failure, regardless of
2432 	 * the replication level.  The I/Os should be retried successfully.
2433 	 * If we only have single-fault tolerance, don't inject write
2434 	 * faults, because then we'll be doing partial writes and won't
2435 	 * be able to recover when we inject data corruption.
2436 	 */
2437 	if (zopt_maxfaults <= 1)
2438 		ftype = (1U << ZIO_TYPE_READ);
2439 	else
2440 		ftype = (1U << ZIO_TYPE_READ) | (1U << ZIO_TYPE_WRITE);
2441 
2442 	(void) vdev_error_setup(spa, path0, VDEV_FAULT_COUNT, ftype, 10);
2443 
2444 	/*
2445 	 * If we can tolerate three or more faults, make one of the
2446 	 * devices fail quite a lot.
2447 	 */
2448 	if (zopt_maxfaults >= 3 && path1[0] != '\0')
2449 		(void) vdev_error_setup(spa, path1, VDEV_FAULT_COUNT,
2450 		    ftype, 100);
2451 
2452 	/*
2453 	 * If we can tolerate four or more faults, offline one of the devices.
2454 	 */
2455 	if (zopt_maxfaults >= 4 && path1[0] != '\0') {
2456 		if (ztest_random(10) < 6)
2457 			(void) vdev_offline(spa, path1);
2458 		else
2459 			(void) vdev_online(spa, path1);
2460 	}
2461 
2462 	/*
2463 	 * If we have at least single-fault tolerance, inject data corruption.
2464 	 */
2465 	if (zopt_maxfaults < 1)
2466 		return;
2467 
2468 	fd = open(pathrand, O_RDWR);
2469 
2470 	if (fd == -1)	/* we hit a gap in the device namespace */
2471 		return;
2472 
2473 	fsize = lseek(fd, 0, SEEK_END);
2474 
2475 	while (--iters != 0) {
2476 		offset = ztest_random(fsize / (leaves << bshift)) *
2477 		    (leaves << bshift) + (leaf << bshift) +
2478 		    (ztest_random(1ULL << (bshift - 1)) & -8ULL);
2479 
2480 		if (offset >= fsize)
2481 			continue;
2482 
2483 		if (zopt_verbose >= 6)
2484 			(void) printf("injecting bad word into %s,"
2485 			    " offset 0x%llx\n", pathrand, (u_longlong_t)offset);
2486 
2487 		if (pwrite(fd, &bad, sizeof (bad), offset) != sizeof (bad))
2488 			fatal(1, "can't inject bad word at 0x%llx in %s",
2489 			    offset, pathrand);
2490 	}
2491 
2492 	(void) close(fd);
2493 }
2494 
2495 static void
2496 ztest_error_setup(vdev_t *vd, int mode, int mask, uint64_t arg)
2497 {
2498 	int c;
2499 
2500 	for (c = 0; c < vd->vdev_children; c++)
2501 		ztest_error_setup(vd->vdev_child[c], mode, mask, arg);
2502 
2503 	if (vd->vdev_path != NULL)
2504 		(void) vdev_error_setup(vd->vdev_spa, vd->vdev_path,
2505 		    mode, mask, arg);
2506 }
2507 
2508 /*
2509  * Scrub the pool.
2510  */
2511 void
2512 ztest_scrub(ztest_args_t *za)
2513 {
2514 	spa_t *spa = dmu_objset_spa(za->za_os);
2515 
2516 	(void) spa_scrub(spa, POOL_SCRUB_EVERYTHING, B_FALSE);
2517 	(void) poll(NULL, 0, 1000); /* wait a second, then force a restart */
2518 	(void) spa_scrub(spa, POOL_SCRUB_EVERYTHING, B_FALSE);
2519 }
2520 
2521 /*
2522  * Rename the pool to a different name and then rename it back.
2523  */
2524 void
2525 ztest_spa_rename(ztest_args_t *za)
2526 {
2527 	char *oldname, *newname;
2528 	int error;
2529 	spa_t *spa;
2530 
2531 	(void) rw_wrlock(&ztest_shared->zs_name_lock);
2532 
2533 	oldname = za->za_pool;
2534 	newname = umem_alloc(strlen(oldname) + 5, UMEM_NOFAIL);
2535 	(void) strcpy(newname, oldname);
2536 	(void) strcat(newname, "_tmp");
2537 
2538 	/*
2539 	 * Do the rename
2540 	 */
2541 	error = spa_rename(oldname, newname);
2542 	if (error)
2543 		fatal(0, "spa_rename('%s', '%s') = %d", oldname,
2544 		    newname, error);
2545 
2546 	/*
2547 	 * Try to open it under the old name, which shouldn't exist
2548 	 */
2549 	error = spa_open(oldname, &spa, FTAG);
2550 	if (error != ENOENT)
2551 		fatal(0, "spa_open('%s') = %d", oldname, error);
2552 
2553 	/*
2554 	 * Open it under the new name and make sure it's still the same spa_t.
2555 	 */
2556 	error = spa_open(newname, &spa, FTAG);
2557 	if (error != 0)
2558 		fatal(0, "spa_open('%s') = %d", newname, error);
2559 
2560 	ASSERT(spa == dmu_objset_spa(za->za_os));
2561 	spa_close(spa, FTAG);
2562 
2563 	/*
2564 	 * Rename it back to the original
2565 	 */
2566 	error = spa_rename(newname, oldname);
2567 	if (error)
2568 		fatal(0, "spa_rename('%s', '%s') = %d", newname,
2569 		    oldname, error);
2570 
2571 	/*
2572 	 * Make sure it can still be opened
2573 	 */
2574 	error = spa_open(oldname, &spa, FTAG);
2575 	if (error != 0)
2576 		fatal(0, "spa_open('%s') = %d", oldname, error);
2577 
2578 	ASSERT(spa == dmu_objset_spa(za->za_os));
2579 	spa_close(spa, FTAG);
2580 
2581 	umem_free(newname, strlen(newname) + 1);
2582 
2583 	(void) rw_unlock(&ztest_shared->zs_name_lock);
2584 }
2585 
2586 
2587 /*
2588  * Completely obliterate one disk.
2589  */
2590 static void
2591 ztest_obliterate_one_disk(uint64_t vdev)
2592 {
2593 	int fd;
2594 	char dev_name[MAXPATHLEN];
2595 	size_t fsize;
2596 
2597 	if (zopt_maxfaults < 2)
2598 		return;
2599 
2600 	(void) sprintf(dev_name, ztest_dev_template, zopt_dir, zopt_pool, vdev);
2601 
2602 	fd = open(dev_name, O_RDWR);
2603 
2604 	if (fd == -1)
2605 		fatal(1, "can't open %s", dev_name);
2606 
2607 	/*
2608 	 * Determine the size.
2609 	 */
2610 	fsize = lseek(fd, 0, SEEK_END);
2611 	(void) close(fd);
2612 
2613 	/*
2614 	 * Remove it.
2615 	 */
2616 	VERIFY(remove(dev_name) == 0);
2617 
2618 	/*
2619 	 * Create a new one.
2620 	 */
2621 	VERIFY((fd = open(dev_name, O_RDWR | O_CREAT | O_TRUNC, 0666)) >= 0);
2622 	VERIFY(ftruncate(fd, fsize) == 0);
2623 	(void) close(fd);
2624 }
2625 
2626 static void
2627 ztest_replace_one_disk(spa_t *spa, uint64_t vdev)
2628 {
2629 	char dev_name[MAXPATHLEN];
2630 	nvlist_t *file, *root;
2631 	int error;
2632 
2633 	(void) sprintf(dev_name, ztest_dev_template, zopt_dir, zopt_pool, vdev);
2634 
2635 	/*
2636 	 * Build the nvlist describing dev_name.
2637 	 */
2638 	VERIFY(nvlist_alloc(&file, NV_UNIQUE_NAME, 0) == 0);
2639 	VERIFY(nvlist_add_string(file, ZPOOL_CONFIG_TYPE, VDEV_TYPE_FILE) == 0);
2640 	VERIFY(nvlist_add_string(file, ZPOOL_CONFIG_PATH, dev_name) == 0);
2641 
2642 	VERIFY(nvlist_alloc(&root, NV_UNIQUE_NAME, 0) == 0);
2643 	VERIFY(nvlist_add_string(root, ZPOOL_CONFIG_TYPE, VDEV_TYPE_ROOT) == 0);
2644 	VERIFY(nvlist_add_nvlist_array(root, ZPOOL_CONFIG_CHILDREN,
2645 	    &file, 1) == 0);
2646 
2647 	error = spa_vdev_attach(spa, dev_name, root, B_TRUE);
2648 	if (error != 0 && error != EBUSY && error != ENOTSUP && error != ENODEV)
2649 		fatal(0, "spa_vdev_attach(in-place) = %d", error);
2650 
2651 	nvlist_free(file);
2652 	nvlist_free(root);
2653 }
2654 
2655 static void
2656 ztest_verify_blocks(char *pool)
2657 {
2658 	int status;
2659 	char zdb[MAXPATHLEN + MAXNAMELEN + 20];
2660 	char zbuf[1024];
2661 	char *bin;
2662 	FILE *fp;
2663 
2664 	(void) realpath(getexecname(), zdb);
2665 
2666 	/* zdb lives in /usr/sbin, while ztest lives in /usr/bin */
2667 	bin = strstr(zdb, "/usr/bin/");
2668 	/* LINTED */
2669 	(void) sprintf(bin, "/usr/sbin/zdb -bc%s%s -U -O %s %s",
2670 	    zopt_verbose >= 3 ? "s" : "",
2671 	    zopt_verbose >= 4 ? "v" : "",
2672 	    ztest_random(2) == 0 ? "pre" : "post", pool);
2673 
2674 	if (zopt_verbose >= 5)
2675 		(void) printf("Executing %s\n", strstr(zdb, "zdb "));
2676 
2677 	fp = popen(zdb, "r");
2678 
2679 	while (fgets(zbuf, sizeof (zbuf), fp) != NULL)
2680 		if (zopt_verbose >= 3)
2681 			(void) printf("%s", zbuf);
2682 
2683 	status = pclose(fp);
2684 
2685 	if (status == 0)
2686 		return;
2687 
2688 	ztest_dump_core = 0;
2689 	if (WIFEXITED(status))
2690 		fatal(0, "'%s' exit code %d", zdb, WEXITSTATUS(status));
2691 	else
2692 		fatal(0, "'%s' died with signal %d", zdb, WTERMSIG(status));
2693 }
2694 
2695 static void
2696 ztest_walk_pool_directory(char *header)
2697 {
2698 	spa_t *spa = NULL;
2699 
2700 	if (zopt_verbose >= 6)
2701 		(void) printf("%s\n", header);
2702 
2703 	mutex_enter(&spa_namespace_lock);
2704 	while ((spa = spa_next(spa)) != NULL)
2705 		if (zopt_verbose >= 6)
2706 			(void) printf("\t%s\n", spa_name(spa));
2707 	mutex_exit(&spa_namespace_lock);
2708 }
2709 
2710 static void
2711 ztest_spa_import_export(char *oldname, char *newname)
2712 {
2713 	nvlist_t *config;
2714 	uint64_t pool_guid;
2715 	spa_t *spa;
2716 	int error;
2717 
2718 	if (zopt_verbose >= 4) {
2719 		(void) printf("import/export: old = %s, new = %s\n",
2720 		    oldname, newname);
2721 	}
2722 
2723 	/*
2724 	 * Clean up from previous runs.
2725 	 */
2726 	(void) spa_destroy(newname);
2727 
2728 	/*
2729 	 * Get the pool's configuration and guid.
2730 	 */
2731 	error = spa_open(oldname, &spa, FTAG);
2732 	if (error)
2733 		fatal(0, "spa_open('%s') = %d", oldname, error);
2734 
2735 	ASSERT(spa->spa_config != NULL);
2736 
2737 	VERIFY(nvlist_dup(spa->spa_config, &config, 0) == 0);
2738 	pool_guid = spa_guid(spa);
2739 	spa_close(spa, FTAG);
2740 
2741 	ztest_walk_pool_directory("pools before export");
2742 
2743 	/*
2744 	 * Export it.
2745 	 */
2746 	error = spa_export(oldname);
2747 	if (error)
2748 		fatal(0, "spa_export('%s') = %d", oldname, error);
2749 
2750 	ztest_walk_pool_directory("pools after export");
2751 
2752 	/*
2753 	 * Import it under the new name.
2754 	 */
2755 	error = spa_import(newname, config, NULL);
2756 	if (error)
2757 		fatal(0, "spa_import('%s') = %d", newname, error);
2758 
2759 	ztest_walk_pool_directory("pools after import");
2760 
2761 	/*
2762 	 * Try to import it again -- should fail with EEXIST.
2763 	 */
2764 	error = spa_import(newname, config, NULL);
2765 	if (error != EEXIST)
2766 		fatal(0, "spa_import('%s') twice", newname);
2767 
2768 	/*
2769 	 * Try to import it under a different name -- should fail with EEXIST.
2770 	 */
2771 	error = spa_import(oldname, config, NULL);
2772 	if (error != EEXIST)
2773 		fatal(0, "spa_import('%s') under multiple names", newname);
2774 
2775 	/*
2776 	 * Verify that the pool is no longer visible under the old name.
2777 	 */
2778 	error = spa_open(oldname, &spa, FTAG);
2779 	if (error != ENOENT)
2780 		fatal(0, "spa_open('%s') = %d", newname, error);
2781 
2782 	/*
2783 	 * Verify that we can open and close the pool using the new name.
2784 	 */
2785 	error = spa_open(newname, &spa, FTAG);
2786 	if (error)
2787 		fatal(0, "spa_open('%s') = %d", newname, error);
2788 	ASSERT(pool_guid == spa_guid(spa));
2789 	spa_close(spa, FTAG);
2790 
2791 	nvlist_free(config);
2792 }
2793 
2794 static void *
2795 ztest_thread(void *arg)
2796 {
2797 	ztest_args_t *za = arg;
2798 	ztest_shared_t *zs = ztest_shared;
2799 	hrtime_t now, functime;
2800 	ztest_info_t *zi;
2801 	int f;
2802 
2803 	while ((now = gethrtime()) < za->za_stop) {
2804 		/*
2805 		 * See if it's time to force a crash.
2806 		 */
2807 		if (now > za->za_kill) {
2808 			zs->zs_alloc = spa_get_alloc(dmu_objset_spa(za->za_os));
2809 			zs->zs_space = spa_get_space(dmu_objset_spa(za->za_os));
2810 			(void) kill(getpid(), SIGKILL);
2811 		}
2812 
2813 		/*
2814 		 * Pick a random function.
2815 		 */
2816 		f = ztest_random(ZTEST_FUNCS);
2817 		zi = &zs->zs_info[f];
2818 
2819 		/*
2820 		 * Decide whether to call it, based on the requested frequency.
2821 		 */
2822 		if (zi->zi_call_target == 0 ||
2823 		    (double)zi->zi_call_total / zi->zi_call_target >
2824 		    (double)(now - zs->zs_start_time) / (zopt_time * NANOSEC))
2825 			continue;
2826 
2827 		atomic_add_64(&zi->zi_calls, 1);
2828 		atomic_add_64(&zi->zi_call_total, 1);
2829 
2830 		za->za_diroff = (za->za_instance * ZTEST_FUNCS + f) *
2831 		    ZTEST_DIRSIZE;
2832 		za->za_diroff_shared = (1ULL << 63);
2833 
2834 		ztest_dmu_write_parallel(za);
2835 
2836 		zi->zi_func(za);
2837 
2838 		functime = gethrtime() - now;
2839 
2840 		atomic_add_64(&zi->zi_call_time, functime);
2841 
2842 		if (zopt_verbose >= 4) {
2843 			Dl_info dli;
2844 			(void) dladdr((void *)zi->zi_func, &dli);
2845 			(void) printf("%6.2f sec in %s\n",
2846 			    (double)functime / NANOSEC, dli.dli_sname);
2847 		}
2848 
2849 		/*
2850 		 * If we're getting ENOSPC with some regularity, stop.
2851 		 */
2852 		if (zs->zs_enospc_count > 10)
2853 			break;
2854 	}
2855 
2856 	return (NULL);
2857 }
2858 
2859 /*
2860  * Kick off threads to run tests on all datasets in parallel.
2861  */
2862 static void
2863 ztest_run(char *pool)
2864 {
2865 	int t, d, error;
2866 	ztest_shared_t *zs = ztest_shared;
2867 	ztest_args_t *za;
2868 	spa_t *spa;
2869 	char name[100];
2870 
2871 	(void) _mutex_init(&zs->zs_vdev_lock, USYNC_THREAD, NULL);
2872 	(void) rwlock_init(&zs->zs_name_lock, USYNC_THREAD, NULL);
2873 
2874 	for (t = 0; t < ZTEST_SYNC_LOCKS; t++)
2875 		(void) _mutex_init(&zs->zs_sync_lock[t], USYNC_THREAD, NULL);
2876 
2877 	/*
2878 	 * Destroy one disk before we even start.
2879 	 * It's mirrored, so everything should work just fine.
2880 	 * This makes us exercise fault handling very early in spa_load().
2881 	 */
2882 	ztest_obliterate_one_disk(0);
2883 
2884 	/*
2885 	 * Verify that the sum of the sizes of all blocks in the pool
2886 	 * equals the SPA's allocated space total.
2887 	 */
2888 	ztest_verify_blocks(pool);
2889 
2890 	/*
2891 	 * Kick off a replacement of the disk we just obliterated.
2892 	 */
2893 	kernel_init(FREAD | FWRITE);
2894 	error = spa_open(pool, &spa, FTAG);
2895 	if (error)
2896 		fatal(0, "spa_open(%s) = %d", pool, error);
2897 	ztest_replace_one_disk(spa, 0);
2898 	if (zopt_verbose >= 5)
2899 		show_pool_stats(spa);
2900 	spa_close(spa, FTAG);
2901 	kernel_fini();
2902 
2903 	kernel_init(FREAD | FWRITE);
2904 
2905 	/*
2906 	 * Verify that we can export the pool and reimport it under a
2907 	 * different name.
2908 	 */
2909 	(void) snprintf(name, 100, "%s_import", pool);
2910 	ztest_spa_import_export(pool, name);
2911 	ztest_spa_import_export(name, pool);
2912 
2913 	/*
2914 	 * Verify that we can loop over all pools.
2915 	 */
2916 	mutex_enter(&spa_namespace_lock);
2917 	for (spa = spa_next(NULL); spa != NULL; spa = spa_next(spa)) {
2918 		if (zopt_verbose > 3) {
2919 			(void) printf("spa_next: found %s\n", spa_name(spa));
2920 		}
2921 	}
2922 	mutex_exit(&spa_namespace_lock);
2923 
2924 	/*
2925 	 * Open our pool.
2926 	 */
2927 	error = spa_open(pool, &spa, FTAG);
2928 	if (error)
2929 		fatal(0, "spa_open() = %d", error);
2930 
2931 	/*
2932 	 * Verify that we can safely inquire about about any object,
2933 	 * whether it's allocated or not.  To make it interesting,
2934 	 * we probe a 5-wide window around each power of two.
2935 	 * This hits all edge cases, including zero and the max.
2936 	 */
2937 	for (t = 0; t < 64; t++) {
2938 		for (d = -5; d <= 5; d++) {
2939 			error = dmu_object_info(spa->spa_meta_objset,
2940 			    (1ULL << t) + d, NULL);
2941 			ASSERT(error == 0 || error == ENOENT);
2942 		}
2943 	}
2944 
2945 	/*
2946 	 * Now kick off all the tests that run in parallel.
2947 	 */
2948 	zs->zs_enospc_count = 0;
2949 
2950 	za = umem_zalloc(zopt_threads * sizeof (ztest_args_t), UMEM_NOFAIL);
2951 
2952 	if (zopt_verbose >= 4)
2953 		(void) printf("starting main threads...\n");
2954 
2955 	za[0].za_start = gethrtime();
2956 	za[0].za_stop = za[0].za_start + zopt_passtime * NANOSEC;
2957 	za[0].za_stop = MIN(za[0].za_stop, zs->zs_stop_time);
2958 	za[0].za_kill = za[0].za_stop;
2959 	if (ztest_random(100) < zopt_killrate)
2960 		za[0].za_kill -= ztest_random(zopt_passtime * NANOSEC);
2961 
2962 	for (t = 0; t < zopt_threads; t++) {
2963 		d = t % zopt_dirs;
2964 		if (t < zopt_dirs) {
2965 			ztest_replay_t zr;
2966 			(void) rw_rdlock(&ztest_shared->zs_name_lock);
2967 			(void) snprintf(name, 100, "%s/%s_%d", pool, pool, d);
2968 			error = dmu_objset_create(name, DMU_OST_OTHER, NULL,
2969 			    ztest_create_cb, NULL);
2970 			if (error != 0 && error != EEXIST) {
2971 				if (error == ENOSPC) {
2972 					zs->zs_enospc_count++;
2973 					(void) rw_unlock(
2974 					    &ztest_shared->zs_name_lock);
2975 					break;
2976 				}
2977 				fatal(0, "dmu_objset_create(%s) = %d",
2978 				    name, error);
2979 			}
2980 			error = dmu_objset_open(name, DMU_OST_OTHER,
2981 			    DS_MODE_STANDARD, &za[d].za_os);
2982 			if (error)
2983 				fatal(0, "dmu_objset_open('%s') = %d",
2984 				    name, error);
2985 			(void) rw_unlock(&ztest_shared->zs_name_lock);
2986 			zr.zr_os = za[d].za_os;
2987 			zil_replay(zr.zr_os, &zr, &zr.zr_assign,
2988 			    ztest_replay_vector, NULL);
2989 			za[d].za_zilog = zil_open(za[d].za_os, NULL);
2990 		}
2991 		za[t].za_pool = spa_strdup(pool);
2992 		za[t].za_os = za[d].za_os;
2993 		za[t].za_zilog = za[d].za_zilog;
2994 		za[t].za_instance = t;
2995 		za[t].za_random = ztest_random(-1ULL);
2996 		za[t].za_start = za[0].za_start;
2997 		za[t].za_stop = za[0].za_stop;
2998 		za[t].za_kill = za[0].za_kill;
2999 
3000 		error = thr_create(0, 0, ztest_thread, &za[t], THR_BOUND,
3001 		    &za[t].za_thread);
3002 		if (error)
3003 			fatal(0, "can't create thread %d: error %d",
3004 			    t, error);
3005 	}
3006 
3007 	while (--t >= 0) {
3008 		error = thr_join(za[t].za_thread, NULL, NULL);
3009 		if (error)
3010 			fatal(0, "thr_join(%d) = %d", t, error);
3011 		if (za[t].za_th)
3012 			traverse_fini(za[t].za_th);
3013 		if (t < zopt_dirs) {
3014 			zil_close(za[t].za_zilog);
3015 			dmu_objset_close(za[t].za_os);
3016 		}
3017 		spa_strfree(za[t].za_pool);
3018 	}
3019 
3020 	umem_free(za, zopt_threads * sizeof (ztest_args_t));
3021 
3022 	if (zopt_verbose >= 3)
3023 		show_pool_stats(spa);
3024 
3025 	txg_wait_synced(spa_get_dsl(spa), 0);
3026 
3027 	zs->zs_alloc = spa_get_alloc(spa);
3028 	zs->zs_space = spa_get_space(spa);
3029 
3030 	/*
3031 	 * Did we have out-of-space errors?  If so, destroy a random objset.
3032 	 */
3033 	if (zs->zs_enospc_count != 0) {
3034 		(void) rw_rdlock(&ztest_shared->zs_name_lock);
3035 		(void) snprintf(name, 100, "%s/%s_%d", pool, pool,
3036 		    (int)ztest_random(zopt_dirs));
3037 		if (zopt_verbose >= 3)
3038 			(void) printf("Destroying %s to free up space\n", name);
3039 		dmu_objset_find(name, ztest_destroy_cb, NULL,
3040 		    DS_FIND_SNAPSHOTS);
3041 		(void) rw_unlock(&ztest_shared->zs_name_lock);
3042 	}
3043 
3044 	/*
3045 	 * Prepare every leaf device to inject a few random read faults.
3046 	 */
3047 	ztest_error_setup(spa->spa_root_vdev, VDEV_FAULT_COUNT,
3048 	    (1U << ZIO_TYPE_READ), 10);
3049 
3050 	/*
3051 	 * Right before closing the pool, kick off a bunch of async I/O;
3052 	 * spa_close() should wait for it to complete.
3053 	 */
3054 	for (t = 1; t < 50; t++)
3055 		dmu_prefetch(spa->spa_meta_objset, t, 0, 1 << 15);
3056 
3057 	spa_close(spa, FTAG);
3058 
3059 	kernel_fini();
3060 }
3061 
3062 void
3063 print_time(hrtime_t t, char *timebuf)
3064 {
3065 	hrtime_t s = t / NANOSEC;
3066 	hrtime_t m = s / 60;
3067 	hrtime_t h = m / 60;
3068 	hrtime_t d = h / 24;
3069 
3070 	s -= m * 60;
3071 	m -= h * 60;
3072 	h -= d * 24;
3073 
3074 	timebuf[0] = '\0';
3075 
3076 	if (d)
3077 		(void) sprintf(timebuf,
3078 		    "%llud%02lluh%02llum%02llus", d, h, m, s);
3079 	else if (h)
3080 		(void) sprintf(timebuf, "%lluh%02llum%02llus", h, m, s);
3081 	else if (m)
3082 		(void) sprintf(timebuf, "%llum%02llus", m, s);
3083 	else
3084 		(void) sprintf(timebuf, "%llus", s);
3085 }
3086 
3087 /*
3088  * Create a storage pool with the given name and initial vdev size.
3089  * Then create the specified number of datasets in the pool.
3090  */
3091 static void
3092 ztest_init(char *pool)
3093 {
3094 	spa_t *spa;
3095 	int error;
3096 	nvlist_t *nvroot;
3097 
3098 	kernel_init(FREAD | FWRITE);
3099 
3100 	/*
3101 	 * Create the storage pool.
3102 	 */
3103 	(void) spa_destroy(pool);
3104 	ztest_shared->zs_vdev_primaries = 0;
3105 	nvroot = make_vdev_root(zopt_vdev_size, zopt_raidz, zopt_mirrors, 1);
3106 	error = spa_create(pool, nvroot, NULL);
3107 	nvlist_free(nvroot);
3108 
3109 	if (error)
3110 		fatal(0, "spa_create() = %d", error);
3111 	error = spa_open(pool, &spa, FTAG);
3112 	if (error)
3113 		fatal(0, "spa_open() = %d", error);
3114 
3115 	if (zopt_verbose >= 3)
3116 		show_pool_stats(spa);
3117 
3118 	spa_close(spa, FTAG);
3119 
3120 	kernel_fini();
3121 }
3122 
3123 int
3124 main(int argc, char **argv)
3125 {
3126 	int kills = 0;
3127 	int iters = 0;
3128 	int i, f;
3129 	ztest_shared_t *zs;
3130 	ztest_info_t *zi;
3131 	char timebuf[100];
3132 	char numbuf[6];
3133 
3134 	(void) setvbuf(stdout, NULL, _IOLBF, 0);
3135 
3136 	/* Override location of zpool.cache */
3137 	spa_config_dir = "/tmp";
3138 
3139 	/*
3140 	 * Blow away any existing copy of zpool.cache
3141 	 */
3142 	(void) remove("/tmp/zpool.cache");
3143 
3144 	ztest_random_fd = open("/dev/urandom", O_RDONLY);
3145 
3146 	process_options(argc, argv);
3147 
3148 	argc -= optind;
3149 	argv += optind;
3150 
3151 	dprintf_setup(&argc, argv);
3152 
3153 	zs = ztest_shared = (void *)mmap(0,
3154 	    P2ROUNDUP(sizeof (ztest_shared_t), getpagesize()),
3155 	    PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANON, -1, 0);
3156 
3157 	if (zopt_verbose >= 1) {
3158 		(void) printf("%llu vdevs, %d datasets, %d threads,"
3159 		    " %llu seconds...\n",
3160 		    (u_longlong_t)zopt_vdevs, zopt_dirs, zopt_threads,
3161 		    (u_longlong_t)zopt_time);
3162 	}
3163 
3164 	/*
3165 	 * Create and initialize our storage pool.
3166 	 */
3167 	for (i = 1; i <= zopt_init; i++) {
3168 		bzero(zs, sizeof (ztest_shared_t));
3169 		if (zopt_verbose >= 3 && zopt_init != 1)
3170 			(void) printf("ztest_init(), pass %d\n", i);
3171 		ztest_init(zopt_pool);
3172 	}
3173 
3174 	/*
3175 	 * Initialize the call targets for each function.
3176 	 */
3177 	for (f = 0; f < ZTEST_FUNCS; f++) {
3178 		zi = &zs->zs_info[f];
3179 
3180 		*zi = ztest_info[f];
3181 
3182 		if (*zi->zi_interval == 0)
3183 			zi->zi_call_target = UINT64_MAX;
3184 		else
3185 			zi->zi_call_target = zopt_time / *zi->zi_interval;
3186 	}
3187 
3188 	zs->zs_start_time = gethrtime();
3189 	zs->zs_stop_time = zs->zs_start_time + zopt_time * NANOSEC;
3190 
3191 	/*
3192 	 * Run the tests in a loop.  These tests include fault injection
3193 	 * to verify that self-healing data works, and forced crashes
3194 	 * to verify that we never lose on-disk consistency.
3195 	 */
3196 	while (gethrtime() < zs->zs_stop_time) {
3197 		int status;
3198 		pid_t pid;
3199 		char *tmp;
3200 
3201 		/*
3202 		 * Initialize the workload counters for each function.
3203 		 */
3204 		for (f = 0; f < ZTEST_FUNCS; f++) {
3205 			zi = &zs->zs_info[f];
3206 			zi->zi_calls = 0;
3207 			zi->zi_call_time = 0;
3208 		}
3209 
3210 		pid = fork();
3211 
3212 		if (pid == -1)
3213 			fatal(1, "fork failed");
3214 
3215 		if (pid == 0) {	/* child */
3216 			struct rlimit rl = { 1024, 1024 };
3217 			(void) setrlimit(RLIMIT_NOFILE, &rl);
3218 			ztest_run(zopt_pool);
3219 			exit(0);
3220 		}
3221 
3222 		while (waitpid(pid, &status, WEXITED) != pid)
3223 			continue;
3224 
3225 		if (WIFEXITED(status)) {
3226 			if (WEXITSTATUS(status) != 0) {
3227 				(void) fprintf(stderr,
3228 				    "child exited with code %d\n",
3229 				    WEXITSTATUS(status));
3230 				exit(2);
3231 			}
3232 		} else {
3233 			if (WTERMSIG(status) != SIGKILL) {
3234 				(void) fprintf(stderr,
3235 				    "child died with signal %d\n",
3236 				    WTERMSIG(status));
3237 				exit(3);
3238 			}
3239 			kills++;
3240 		}
3241 
3242 		iters++;
3243 
3244 		if (zopt_verbose >= 1) {
3245 			hrtime_t now = gethrtime();
3246 
3247 			now = MIN(now, zs->zs_stop_time);
3248 			print_time(zs->zs_stop_time - now, timebuf);
3249 			nicenum(zs->zs_space, numbuf);
3250 
3251 			(void) printf("Pass %3d, %8s, %3llu ENOSPC, "
3252 			    "%4.1f%% of %5s used, %3.0f%% done, %8s to go\n",
3253 			    iters,
3254 			    WIFEXITED(status) ? "Complete" : "SIGKILL",
3255 			    (u_longlong_t)zs->zs_enospc_count,
3256 			    100.0 * zs->zs_alloc / zs->zs_space,
3257 			    numbuf,
3258 			    100.0 * (now - zs->zs_start_time) /
3259 			    (zopt_time * NANOSEC), timebuf);
3260 		}
3261 
3262 		if (zopt_verbose >= 2) {
3263 			(void) printf("\nWorkload summary:\n\n");
3264 			(void) printf("%7s %9s   %s\n",
3265 			    "Calls", "Time", "Function");
3266 			(void) printf("%7s %9s   %s\n",
3267 			    "-----", "----", "--------");
3268 			for (f = 0; f < ZTEST_FUNCS; f++) {
3269 				Dl_info dli;
3270 
3271 				zi = &zs->zs_info[f];
3272 				print_time(zi->zi_call_time, timebuf);
3273 				(void) dladdr((void *)zi->zi_func, &dli);
3274 				(void) printf("%7llu %9s   %s\n",
3275 				    (u_longlong_t)zi->zi_calls, timebuf,
3276 				    dli.dli_sname);
3277 			}
3278 			(void) printf("\n");
3279 		}
3280 
3281 		/*
3282 		 * It's possible that we killed a child during a rename test, in
3283 		 * which case we'll have a 'ztest_tmp' pool lying around instead
3284 		 * of 'ztest'.  Do a blind rename in case this happened.
3285 		 */
3286 		tmp = umem_alloc(strlen(zopt_pool) + 5, UMEM_NOFAIL);
3287 		(void) strcpy(tmp, zopt_pool);
3288 		(void) strcat(tmp, "_tmp");
3289 		kernel_init(FREAD | FWRITE);
3290 		(void) spa_rename(tmp, zopt_pool);
3291 		kernel_fini();
3292 		umem_free(tmp, strlen(tmp) + 1);
3293 	}
3294 
3295 	ztest_verify_blocks(zopt_pool);
3296 
3297 	if (zopt_verbose >= 1) {
3298 		(void) printf("%d killed, %d completed, %.0f%% kill rate\n",
3299 		    kills, iters - kills, (100.0 * kills) / MAX(1, iters));
3300 	}
3301 
3302 	return (0);
3303 }
3304