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