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