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