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