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