xref: /titanic_44/usr/src/cmd/ztest/ztest.c (revision 9df12a23948bd40cbe37ce88d84e272c3894e675)
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 	txg_wait_synced(dmu_objset_pool(os), 0);
1252 	zil_close(zilog);
1253 	dmu_objset_close(os);
1254 
1255 	error = dmu_objset_destroy(name);
1256 	if (error)
1257 		fatal(0, "dmu_objset_destroy(%s) = %d", name, error);
1258 
1259 	(void) rw_unlock(&ztest_shared->zs_name_lock);
1260 }
1261 
1262 /*
1263  * Verify that dmu_snapshot_{create,destroy,open,close} work as expected.
1264  */
1265 void
1266 ztest_dmu_snapshot_create_destroy(ztest_args_t *za)
1267 {
1268 	int error;
1269 	objset_t *os = za->za_os;
1270 	char snapname[100];
1271 	char osname[MAXNAMELEN];
1272 
1273 	(void) rw_rdlock(&ztest_shared->zs_name_lock);
1274 	dmu_objset_name(os, osname);
1275 	(void) snprintf(snapname, 100, "%s@%llu", osname,
1276 	    (u_longlong_t)za->za_instance);
1277 
1278 	error = dmu_objset_destroy(snapname);
1279 	if (error != 0 && error != ENOENT)
1280 		fatal(0, "dmu_objset_destroy() = %d", error);
1281 	error = dmu_objset_create(snapname, DMU_OST_OTHER, NULL, NULL, NULL);
1282 	if (error == ENOSPC)
1283 		ztest_record_enospc("dmu_take_snapshot");
1284 	else if (error != 0 && error != EEXIST)
1285 		fatal(0, "dmu_take_snapshot() = %d", error);
1286 	(void) rw_unlock(&ztest_shared->zs_name_lock);
1287 }
1288 
1289 #define	ZTEST_TRAVERSE_BLOCKS	1000
1290 
1291 static int
1292 ztest_blk_cb(traverse_blk_cache_t *bc, spa_t *spa, void *arg)
1293 {
1294 	ztest_args_t *za = arg;
1295 	zbookmark_t *zb = &bc->bc_bookmark;
1296 	blkptr_t *bp = &bc->bc_blkptr;
1297 	dnode_phys_t *dnp = bc->bc_dnode;
1298 	traverse_handle_t *th = za->za_th;
1299 	uint64_t size = BP_GET_LSIZE(bp);
1300 
1301 	/*
1302 	 * Level -1 indicates the objset_phys_t or something in its intent log.
1303 	 */
1304 	if (zb->zb_level == -1) {
1305 		if (BP_GET_TYPE(bp) == DMU_OT_OBJSET) {
1306 			ASSERT3U(zb->zb_object, ==, 0);
1307 			ASSERT3U(zb->zb_blkid, ==, 0);
1308 			ASSERT3U(size, ==, sizeof (objset_phys_t));
1309 			za->za_zil_seq = 0;
1310 		} else if (BP_GET_TYPE(bp) == DMU_OT_INTENT_LOG) {
1311 			ASSERT3U(zb->zb_object, ==, 0);
1312 			ASSERT3U(zb->zb_blkid, >, za->za_zil_seq);
1313 			za->za_zil_seq = zb->zb_blkid;
1314 		} else {
1315 			ASSERT3U(zb->zb_object, !=, 0);	/* lr_write_t */
1316 		}
1317 
1318 		return (0);
1319 	}
1320 
1321 	ASSERT(dnp != NULL);
1322 
1323 	if (bc->bc_errno)
1324 		return (ERESTART);
1325 
1326 	/*
1327 	 * Once in a while, abort the traverse.   We only do this to odd
1328 	 * instance numbers to ensure that even ones can run to completion.
1329 	 */
1330 	if ((za->za_instance & 1) && ztest_random(10000) == 0)
1331 		return (EINTR);
1332 
1333 	if (bp->blk_birth == 0) {
1334 		ASSERT(th->th_advance & ADVANCE_HOLES);
1335 		return (0);
1336 	}
1337 
1338 	if (zb->zb_level == 0 && !(th->th_advance & ADVANCE_DATA) &&
1339 	    bc == &th->th_cache[ZB_DN_CACHE][0]) {
1340 		ASSERT(bc->bc_data == NULL);
1341 		return (0);
1342 	}
1343 
1344 	ASSERT(bc->bc_data != NULL);
1345 
1346 	/*
1347 	 * This is an expensive question, so don't ask it too often.
1348 	 */
1349 	if (((za->za_random ^ th->th_callbacks) & 0xff) == 0) {
1350 		void *xbuf = umem_alloc(size, UMEM_NOFAIL);
1351 		if (arc_tryread(spa, bp, xbuf) == 0) {
1352 			ASSERT(bcmp(bc->bc_data, xbuf, size) == 0);
1353 		}
1354 		umem_free(xbuf, size);
1355 	}
1356 
1357 	if (zb->zb_level > 0) {
1358 		ASSERT3U(size, ==, 1ULL << dnp->dn_indblkshift);
1359 		return (0);
1360 	}
1361 
1362 	ASSERT(zb->zb_level == 0);
1363 	ASSERT3U(size, ==, dnp->dn_datablkszsec << DEV_BSHIFT);
1364 
1365 	return (0);
1366 }
1367 
1368 /*
1369  * Verify that live pool traversal works.
1370  */
1371 void
1372 ztest_traverse(ztest_args_t *za)
1373 {
1374 	spa_t *spa = dmu_objset_spa(za->za_os);
1375 	traverse_handle_t *th = za->za_th;
1376 	int rc, advance;
1377 	uint64_t cbstart, cblimit;
1378 
1379 	if (th == NULL) {
1380 		advance = 0;
1381 
1382 		if (ztest_random(2) == 0)
1383 			advance |= ADVANCE_PRE;
1384 
1385 		if (ztest_random(2) == 0)
1386 			advance |= ADVANCE_PRUNE;
1387 
1388 		if (ztest_random(2) == 0)
1389 			advance |= ADVANCE_DATA;
1390 
1391 		if (ztest_random(2) == 0)
1392 			advance |= ADVANCE_HOLES;
1393 
1394 		if (ztest_random(2) == 0)
1395 			advance |= ADVANCE_ZIL;
1396 
1397 		th = za->za_th = traverse_init(spa, ztest_blk_cb, za, advance,
1398 		    ZIO_FLAG_CANFAIL);
1399 
1400 		traverse_add_pool(th, 0, -1ULL);
1401 	}
1402 
1403 	advance = th->th_advance;
1404 	cbstart = th->th_callbacks;
1405 	cblimit = cbstart + ((advance & ADVANCE_DATA) ? 100 : 1000);
1406 
1407 	while ((rc = traverse_more(th)) == EAGAIN && th->th_callbacks < cblimit)
1408 		continue;
1409 
1410 	if (zopt_verbose >= 5)
1411 		(void) printf("traverse %s%s%s%s %llu blocks to "
1412 		    "<%llu, %llu, %lld, %llx>%s\n",
1413 		    (advance & ADVANCE_PRE) ? "pre" : "post",
1414 		    (advance & ADVANCE_PRUNE) ? "|prune" : "",
1415 		    (advance & ADVANCE_DATA) ? "|data" : "",
1416 		    (advance & ADVANCE_HOLES) ? "|holes" : "",
1417 		    (u_longlong_t)(th->th_callbacks - cbstart),
1418 		    (u_longlong_t)th->th_lastcb.zb_objset,
1419 		    (u_longlong_t)th->th_lastcb.zb_object,
1420 		    (u_longlong_t)th->th_lastcb.zb_level,
1421 		    (u_longlong_t)th->th_lastcb.zb_blkid,
1422 		    rc == 0 ? " [done]" :
1423 		    rc == EINTR ? " [aborted]" :
1424 		    rc == EAGAIN ? "" :
1425 		    strerror(rc));
1426 
1427 	if (rc != EAGAIN) {
1428 		if (rc != 0 && rc != EINTR)
1429 			fatal(0, "traverse_more(%p) = %d", th, rc);
1430 		traverse_fini(th);
1431 		za->za_th = NULL;
1432 	}
1433 }
1434 
1435 /*
1436  * Verify that dmu_object_{alloc,free} work as expected.
1437  */
1438 void
1439 ztest_dmu_object_alloc_free(ztest_args_t *za)
1440 {
1441 	objset_t *os = za->za_os;
1442 	dmu_buf_t *db;
1443 	dmu_tx_t *tx;
1444 	uint64_t batchobj, object, batchsize, endoff, temp;
1445 	int b, c, error, bonuslen;
1446 	dmu_object_info_t doi;
1447 	char osname[MAXNAMELEN];
1448 
1449 	dmu_objset_name(os, osname);
1450 
1451 	endoff = -8ULL;
1452 	batchsize = 2;
1453 
1454 	/*
1455 	 * Create a batch object if necessary, and record it in the directory.
1456 	 */
1457 	VERIFY(0 == dmu_read(os, ZTEST_DIROBJ, za->za_diroff,
1458 	    sizeof (uint64_t), &batchobj));
1459 	if (batchobj == 0) {
1460 		tx = dmu_tx_create(os);
1461 		dmu_tx_hold_write(tx, ZTEST_DIROBJ, za->za_diroff,
1462 		    sizeof (uint64_t));
1463 		dmu_tx_hold_bonus(tx, DMU_NEW_OBJECT);
1464 		error = dmu_tx_assign(tx, TXG_WAIT);
1465 		if (error) {
1466 			ztest_record_enospc("create a batch object");
1467 			dmu_tx_abort(tx);
1468 			return;
1469 		}
1470 		batchobj = dmu_object_alloc(os, DMU_OT_UINT64_OTHER, 0,
1471 		    DMU_OT_NONE, 0, tx);
1472 		ztest_set_random_blocksize(os, batchobj, tx);
1473 		dmu_write(os, ZTEST_DIROBJ, za->za_diroff,
1474 		    sizeof (uint64_t), &batchobj, tx);
1475 		dmu_tx_commit(tx);
1476 	}
1477 
1478 	/*
1479 	 * Destroy the previous batch of objects.
1480 	 */
1481 	for (b = 0; b < batchsize; b++) {
1482 		VERIFY(0 == dmu_read(os, batchobj, b * sizeof (uint64_t),
1483 		    sizeof (uint64_t), &object));
1484 		if (object == 0)
1485 			continue;
1486 		/*
1487 		 * Read and validate contents.
1488 		 * We expect the nth byte of the bonus buffer to be n.
1489 		 */
1490 		VERIFY(0 == dmu_bonus_hold(os, object, FTAG, &db));
1491 
1492 		dmu_object_info_from_db(db, &doi);
1493 		ASSERT(doi.doi_type == DMU_OT_UINT64_OTHER);
1494 		ASSERT(doi.doi_bonus_type == DMU_OT_PLAIN_OTHER);
1495 		ASSERT3S(doi.doi_physical_blks, >=, 0);
1496 
1497 		bonuslen = db->db_size;
1498 
1499 		for (c = 0; c < bonuslen; c++) {
1500 			if (((uint8_t *)db->db_data)[c] !=
1501 			    (uint8_t)(c + bonuslen)) {
1502 				fatal(0,
1503 				    "bad bonus: %s, obj %llu, off %d: %u != %u",
1504 				    osname, object, c,
1505 				    ((uint8_t *)db->db_data)[c],
1506 				    (uint8_t)(c + bonuslen));
1507 			}
1508 		}
1509 
1510 		dmu_buf_rele(db, FTAG);
1511 
1512 		/*
1513 		 * We expect the word at endoff to be our object number.
1514 		 */
1515 		VERIFY(0 == dmu_read(os, object, endoff,
1516 		    sizeof (uint64_t), &temp));
1517 
1518 		if (temp != object) {
1519 			fatal(0, "bad data in %s, got %llu, expected %llu",
1520 			    osname, temp, object);
1521 		}
1522 
1523 		/*
1524 		 * Destroy old object and clear batch entry.
1525 		 */
1526 		tx = dmu_tx_create(os);
1527 		dmu_tx_hold_write(tx, batchobj,
1528 		    b * sizeof (uint64_t), sizeof (uint64_t));
1529 		dmu_tx_hold_free(tx, object, 0, DMU_OBJECT_END);
1530 		error = dmu_tx_assign(tx, TXG_WAIT);
1531 		if (error) {
1532 			ztest_record_enospc("free object");
1533 			dmu_tx_abort(tx);
1534 			return;
1535 		}
1536 		error = dmu_object_free(os, object, tx);
1537 		if (error) {
1538 			fatal(0, "dmu_object_free('%s', %llu) = %d",
1539 			    osname, object, error);
1540 		}
1541 		object = 0;
1542 
1543 		dmu_object_set_checksum(os, batchobj,
1544 		    ztest_random_checksum(), tx);
1545 		dmu_object_set_compress(os, batchobj,
1546 		    ztest_random_compress(), tx);
1547 
1548 		dmu_write(os, batchobj, b * sizeof (uint64_t),
1549 		    sizeof (uint64_t), &object, tx);
1550 
1551 		dmu_tx_commit(tx);
1552 	}
1553 
1554 	/*
1555 	 * Before creating the new batch of objects, generate a bunch of churn.
1556 	 */
1557 	for (b = ztest_random(100); b > 0; b--) {
1558 		tx = dmu_tx_create(os);
1559 		dmu_tx_hold_bonus(tx, DMU_NEW_OBJECT);
1560 		error = dmu_tx_assign(tx, TXG_WAIT);
1561 		if (error) {
1562 			ztest_record_enospc("churn objects");
1563 			dmu_tx_abort(tx);
1564 			return;
1565 		}
1566 		object = dmu_object_alloc(os, DMU_OT_UINT64_OTHER, 0,
1567 		    DMU_OT_NONE, 0, tx);
1568 		ztest_set_random_blocksize(os, object, tx);
1569 		error = dmu_object_free(os, object, tx);
1570 		if (error) {
1571 			fatal(0, "dmu_object_free('%s', %llu) = %d",
1572 			    osname, object, error);
1573 		}
1574 		dmu_tx_commit(tx);
1575 	}
1576 
1577 	/*
1578 	 * Create a new batch of objects with randomly chosen
1579 	 * blocksizes and record them in the batch directory.
1580 	 */
1581 	for (b = 0; b < batchsize; b++) {
1582 		uint32_t va_blksize;
1583 		u_longlong_t va_nblocks;
1584 
1585 		tx = dmu_tx_create(os);
1586 		dmu_tx_hold_write(tx, batchobj, b * sizeof (uint64_t),
1587 		    sizeof (uint64_t));
1588 		dmu_tx_hold_bonus(tx, DMU_NEW_OBJECT);
1589 		dmu_tx_hold_write(tx, DMU_NEW_OBJECT, endoff,
1590 		    sizeof (uint64_t));
1591 		error = dmu_tx_assign(tx, TXG_WAIT);
1592 		if (error) {
1593 			ztest_record_enospc("create batchobj");
1594 			dmu_tx_abort(tx);
1595 			return;
1596 		}
1597 		bonuslen = (int)ztest_random(dmu_bonus_max()) + 1;
1598 
1599 		object = dmu_object_alloc(os, DMU_OT_UINT64_OTHER, 0,
1600 		    DMU_OT_PLAIN_OTHER, bonuslen, tx);
1601 
1602 		ztest_set_random_blocksize(os, object, tx);
1603 
1604 		dmu_object_set_checksum(os, object,
1605 		    ztest_random_checksum(), tx);
1606 		dmu_object_set_compress(os, object,
1607 		    ztest_random_compress(), tx);
1608 
1609 		dmu_write(os, batchobj, b * sizeof (uint64_t),
1610 		    sizeof (uint64_t), &object, tx);
1611 
1612 		/*
1613 		 * Write to both the bonus buffer and the regular data.
1614 		 */
1615 		VERIFY(0 == dmu_bonus_hold(os, object, FTAG, &db));
1616 		ASSERT3U(bonuslen, ==, db->db_size);
1617 
1618 		dmu_object_size_from_db(db, &va_blksize, &va_nblocks);
1619 		ASSERT3S(va_nblocks, >=, 0);
1620 
1621 		dmu_buf_will_dirty(db, tx);
1622 
1623 		/*
1624 		 * See comments above regarding the contents of
1625 		 * the bonus buffer and the word at endoff.
1626 		 */
1627 		for (c = 0; c < db->db_size; c++)
1628 			((uint8_t *)db->db_data)[c] = (uint8_t)(c + bonuslen);
1629 
1630 		dmu_buf_rele(db, FTAG);
1631 
1632 		/*
1633 		 * Write to a large offset to increase indirection.
1634 		 */
1635 		dmu_write(os, object, endoff, sizeof (uint64_t), &object, tx);
1636 
1637 		dmu_tx_commit(tx);
1638 	}
1639 }
1640 
1641 /*
1642  * Verify that dmu_{read,write} work as expected.
1643  */
1644 typedef struct bufwad {
1645 	uint64_t	bw_index;
1646 	uint64_t	bw_txg;
1647 	uint64_t	bw_data;
1648 } bufwad_t;
1649 
1650 typedef struct dmu_read_write_dir {
1651 	uint64_t	dd_packobj;
1652 	uint64_t	dd_bigobj;
1653 	uint64_t	dd_chunk;
1654 } dmu_read_write_dir_t;
1655 
1656 void
1657 ztest_dmu_read_write(ztest_args_t *za)
1658 {
1659 	objset_t *os = za->za_os;
1660 	dmu_read_write_dir_t dd;
1661 	dmu_tx_t *tx;
1662 	int i, freeit, error;
1663 	uint64_t n, s, txg;
1664 	bufwad_t *packbuf, *bigbuf, *pack, *bigH, *bigT;
1665 	uint64_t packoff, packsize, bigoff, bigsize;
1666 	uint64_t regions = 997;
1667 	uint64_t stride = 123456789ULL;
1668 	uint64_t width = 40;
1669 	int free_percent = 5;
1670 
1671 	/*
1672 	 * This test uses two objects, packobj and bigobj, that are always
1673 	 * updated together (i.e. in the same tx) so that their contents are
1674 	 * in sync and can be compared.  Their contents relate to each other
1675 	 * in a simple way: packobj is a dense array of 'bufwad' structures,
1676 	 * while bigobj is a sparse array of the same bufwads.  Specifically,
1677 	 * for any index n, there are three bufwads that should be identical:
1678 	 *
1679 	 *	packobj, at offset n * sizeof (bufwad_t)
1680 	 *	bigobj, at the head of the nth chunk
1681 	 *	bigobj, at the tail of the nth chunk
1682 	 *
1683 	 * The chunk size is arbitrary. It doesn't have to be a power of two,
1684 	 * and it doesn't have any relation to the object blocksize.
1685 	 * The only requirement is that it can hold at least two bufwads.
1686 	 *
1687 	 * Normally, we write the bufwad to each of these locations.
1688 	 * However, free_percent of the time we instead write zeroes to
1689 	 * packobj and perform a dmu_free_range() on bigobj.  By comparing
1690 	 * bigobj to packobj, we can verify that the DMU is correctly
1691 	 * tracking which parts of an object are allocated and free,
1692 	 * and that the contents of the allocated blocks are correct.
1693 	 */
1694 
1695 	/*
1696 	 * Read the directory info.  If it's the first time, set things up.
1697 	 */
1698 	VERIFY(0 == dmu_read(os, ZTEST_DIROBJ, za->za_diroff,
1699 	    sizeof (dd), &dd));
1700 	if (dd.dd_chunk == 0) {
1701 		ASSERT(dd.dd_packobj == 0);
1702 		ASSERT(dd.dd_bigobj == 0);
1703 		tx = dmu_tx_create(os);
1704 		dmu_tx_hold_write(tx, ZTEST_DIROBJ, za->za_diroff, sizeof (dd));
1705 		dmu_tx_hold_bonus(tx, DMU_NEW_OBJECT);
1706 		error = dmu_tx_assign(tx, TXG_WAIT);
1707 		if (error) {
1708 			ztest_record_enospc("create r/w directory");
1709 			dmu_tx_abort(tx);
1710 			return;
1711 		}
1712 
1713 		dd.dd_packobj = dmu_object_alloc(os, DMU_OT_UINT64_OTHER, 0,
1714 		    DMU_OT_NONE, 0, tx);
1715 		dd.dd_bigobj = dmu_object_alloc(os, DMU_OT_UINT64_OTHER, 0,
1716 		    DMU_OT_NONE, 0, tx);
1717 		dd.dd_chunk = (1000 + ztest_random(1000)) * sizeof (uint64_t);
1718 
1719 		ztest_set_random_blocksize(os, dd.dd_packobj, tx);
1720 		ztest_set_random_blocksize(os, dd.dd_bigobj, tx);
1721 
1722 		dmu_write(os, ZTEST_DIROBJ, za->za_diroff, sizeof (dd), &dd,
1723 		    tx);
1724 		dmu_tx_commit(tx);
1725 	}
1726 
1727 	/*
1728 	 * Prefetch a random chunk of the big object.
1729 	 * Our aim here is to get some async reads in flight
1730 	 * for blocks that we may free below; the DMU should
1731 	 * handle this race correctly.
1732 	 */
1733 	n = ztest_random(regions) * stride + ztest_random(width);
1734 	s = 1 + ztest_random(2 * width - 1);
1735 	dmu_prefetch(os, dd.dd_bigobj, n * dd.dd_chunk, s * dd.dd_chunk);
1736 
1737 	/*
1738 	 * Pick a random index and compute the offsets into packobj and bigobj.
1739 	 */
1740 	n = ztest_random(regions) * stride + ztest_random(width);
1741 	s = 1 + ztest_random(width - 1);
1742 
1743 	packoff = n * sizeof (bufwad_t);
1744 	packsize = s * sizeof (bufwad_t);
1745 
1746 	bigoff = n * dd.dd_chunk;
1747 	bigsize = s * dd.dd_chunk;
1748 
1749 	packbuf = umem_alloc(packsize, UMEM_NOFAIL);
1750 	bigbuf = umem_alloc(bigsize, UMEM_NOFAIL);
1751 
1752 	/*
1753 	 * free_percent of the time, free a range of bigobj rather than
1754 	 * overwriting it.
1755 	 */
1756 	freeit = (ztest_random(100) < free_percent);
1757 
1758 	/*
1759 	 * Read the current contents of our objects.
1760 	 */
1761 	error = dmu_read(os, dd.dd_packobj, packoff, packsize, packbuf);
1762 	ASSERT3U(error, ==, 0);
1763 	error = dmu_read(os, dd.dd_bigobj, bigoff, bigsize, bigbuf);
1764 	ASSERT3U(error, ==, 0);
1765 
1766 	/*
1767 	 * Get a tx for the mods to both packobj and bigobj.
1768 	 */
1769 	tx = dmu_tx_create(os);
1770 
1771 	dmu_tx_hold_write(tx, dd.dd_packobj, packoff, packsize);
1772 
1773 	if (freeit)
1774 		dmu_tx_hold_free(tx, dd.dd_bigobj, bigoff, bigsize);
1775 	else
1776 		dmu_tx_hold_write(tx, dd.dd_bigobj, bigoff, bigsize);
1777 
1778 	error = dmu_tx_assign(tx, TXG_WAIT);
1779 
1780 	if (error) {
1781 		ztest_record_enospc("dmu r/w range");
1782 		dmu_tx_abort(tx);
1783 		umem_free(packbuf, packsize);
1784 		umem_free(bigbuf, bigsize);
1785 		return;
1786 	}
1787 
1788 	txg = dmu_tx_get_txg(tx);
1789 
1790 	/*
1791 	 * For each index from n to n + s, verify that the existing bufwad
1792 	 * in packobj matches the bufwads at the head and tail of the
1793 	 * corresponding chunk in bigobj.  Then update all three bufwads
1794 	 * with the new values we want to write out.
1795 	 */
1796 	for (i = 0; i < s; i++) {
1797 		/* LINTED */
1798 		pack = (bufwad_t *)((char *)packbuf + i * sizeof (bufwad_t));
1799 		/* LINTED */
1800 		bigH = (bufwad_t *)((char *)bigbuf + i * dd.dd_chunk);
1801 		/* LINTED */
1802 		bigT = (bufwad_t *)((char *)bigH + dd.dd_chunk) - 1;
1803 
1804 		ASSERT((uintptr_t)bigH - (uintptr_t)bigbuf < bigsize);
1805 		ASSERT((uintptr_t)bigT - (uintptr_t)bigbuf < bigsize);
1806 
1807 		if (pack->bw_txg > txg)
1808 			fatal(0, "future leak: got %llx, open txg is %llx",
1809 			    pack->bw_txg, txg);
1810 
1811 		if (pack->bw_data != 0 && pack->bw_index != n + i)
1812 			fatal(0, "wrong index: got %llx, wanted %llx+%llx",
1813 			    pack->bw_index, n, i);
1814 
1815 		if (bcmp(pack, bigH, sizeof (bufwad_t)) != 0)
1816 			fatal(0, "pack/bigH mismatch in %p/%p", pack, bigH);
1817 
1818 		if (bcmp(pack, bigT, sizeof (bufwad_t)) != 0)
1819 			fatal(0, "pack/bigT mismatch in %p/%p", pack, bigT);
1820 
1821 		if (freeit) {
1822 			bzero(pack, sizeof (bufwad_t));
1823 		} else {
1824 			pack->bw_index = n + i;
1825 			pack->bw_txg = txg;
1826 			pack->bw_data = 1 + ztest_random(-2ULL);
1827 		}
1828 		*bigH = *pack;
1829 		*bigT = *pack;
1830 	}
1831 
1832 	/*
1833 	 * We've verified all the old bufwads, and made new ones.
1834 	 * Now write them out.
1835 	 */
1836 	dmu_write(os, dd.dd_packobj, packoff, packsize, packbuf, tx);
1837 
1838 	if (freeit) {
1839 		if (zopt_verbose >= 6) {
1840 			(void) printf("freeing offset %llx size %llx"
1841 			    " txg %llx\n",
1842 			    (u_longlong_t)bigoff,
1843 			    (u_longlong_t)bigsize,
1844 			    (u_longlong_t)txg);
1845 		}
1846 		VERIFY(0 == dmu_free_range(os, dd.dd_bigobj, bigoff,
1847 		    bigsize, tx));
1848 	} else {
1849 		if (zopt_verbose >= 6) {
1850 			(void) printf("writing offset %llx size %llx"
1851 			    " txg %llx\n",
1852 			    (u_longlong_t)bigoff,
1853 			    (u_longlong_t)bigsize,
1854 			    (u_longlong_t)txg);
1855 		}
1856 		dmu_write(os, dd.dd_bigobj, bigoff, bigsize, bigbuf, tx);
1857 	}
1858 
1859 	dmu_tx_commit(tx);
1860 
1861 	/*
1862 	 * Sanity check the stuff we just wrote.
1863 	 */
1864 	{
1865 		void *packcheck = umem_alloc(packsize, UMEM_NOFAIL);
1866 		void *bigcheck = umem_alloc(bigsize, UMEM_NOFAIL);
1867 
1868 		VERIFY(0 == dmu_read(os, dd.dd_packobj, packoff,
1869 		    packsize, packcheck));
1870 		VERIFY(0 == dmu_read(os, dd.dd_bigobj, bigoff,
1871 		    bigsize, bigcheck));
1872 
1873 		ASSERT(bcmp(packbuf, packcheck, packsize) == 0);
1874 		ASSERT(bcmp(bigbuf, bigcheck, bigsize) == 0);
1875 
1876 		umem_free(packcheck, packsize);
1877 		umem_free(bigcheck, bigsize);
1878 	}
1879 
1880 	umem_free(packbuf, packsize);
1881 	umem_free(bigbuf, bigsize);
1882 }
1883 
1884 void
1885 ztest_dmu_write_parallel(ztest_args_t *za)
1886 {
1887 	objset_t *os = za->za_os;
1888 	dmu_tx_t *tx;
1889 	dmu_buf_t *db;
1890 	int i, b, error, do_free, bs;
1891 	uint64_t off, txg_how, txg;
1892 	mutex_t *lp;
1893 	char osname[MAXNAMELEN];
1894 	char iobuf[SPA_MAXBLOCKSIZE];
1895 	ztest_block_tag_t rbt, wbt;
1896 
1897 	dmu_objset_name(os, osname);
1898 	bs = ZTEST_DIROBJ_BLOCKSIZE;
1899 
1900 	/*
1901 	 * Have multiple threads write to large offsets in ZTEST_DIROBJ
1902 	 * to verify that having multiple threads writing to the same object
1903 	 * in parallel doesn't cause any trouble.
1904 	 * Also do parallel writes to the bonus buffer on occasion.
1905 	 */
1906 	for (i = 0; i < 50; i++) {
1907 		b = ztest_random(ZTEST_SYNC_LOCKS);
1908 		lp = &ztest_shared->zs_sync_lock[b];
1909 
1910 		do_free = (ztest_random(4) == 0);
1911 
1912 		off = za->za_diroff_shared + ((uint64_t)b << SPA_MAXBLOCKSHIFT);
1913 
1914 		if (ztest_random(4) == 0) {
1915 			/*
1916 			 * Do the bonus buffer instead of a regular block.
1917 			 */
1918 			do_free = 0;
1919 			off = -1ULL;
1920 		}
1921 
1922 		tx = dmu_tx_create(os);
1923 
1924 		if (off == -1ULL)
1925 			dmu_tx_hold_bonus(tx, ZTEST_DIROBJ);
1926 		else if (do_free)
1927 			dmu_tx_hold_free(tx, ZTEST_DIROBJ, off, bs);
1928 		else
1929 			dmu_tx_hold_write(tx, ZTEST_DIROBJ, off, bs);
1930 
1931 		txg_how = ztest_random(2) == 0 ? TXG_WAIT : TXG_NOWAIT;
1932 		error = dmu_tx_assign(tx, txg_how);
1933 		if (error) {
1934 			dmu_tx_abort(tx);
1935 			if (error == ERESTART) {
1936 				ASSERT(txg_how == TXG_NOWAIT);
1937 				txg_wait_open(dmu_objset_pool(os), 0);
1938 				continue;
1939 			}
1940 			ztest_record_enospc("dmu write parallel");
1941 			return;
1942 		}
1943 		txg = dmu_tx_get_txg(tx);
1944 
1945 		if (do_free) {
1946 			(void) mutex_lock(lp);
1947 			VERIFY(0 == dmu_free_range(os, ZTEST_DIROBJ, off,
1948 			    bs, tx));
1949 			(void) mutex_unlock(lp);
1950 			dmu_tx_commit(tx);
1951 			continue;
1952 		}
1953 
1954 		wbt.bt_objset = dmu_objset_id(os);
1955 		wbt.bt_object = ZTEST_DIROBJ;
1956 		wbt.bt_offset = off;
1957 		wbt.bt_txg = txg;
1958 		wbt.bt_thread = za->za_instance;
1959 
1960 		if (off == -1ULL) {
1961 			wbt.bt_seq = 0;
1962 			VERIFY(0 == dmu_bonus_hold(os, ZTEST_DIROBJ,
1963 			    FTAG, &db));
1964 			ASSERT3U(db->db_size, ==, sizeof (wbt));
1965 			bcopy(db->db_data, &rbt, db->db_size);
1966 			if (rbt.bt_objset != 0) {
1967 				ASSERT3U(rbt.bt_objset, ==, wbt.bt_objset);
1968 				ASSERT3U(rbt.bt_object, ==, wbt.bt_object);
1969 				ASSERT3U(rbt.bt_offset, ==, wbt.bt_offset);
1970 				ASSERT3U(rbt.bt_txg, <=, wbt.bt_txg);
1971 			}
1972 			dmu_buf_will_dirty(db, tx);
1973 			bcopy(&wbt, db->db_data, db->db_size);
1974 			dmu_buf_rele(db, FTAG);
1975 			dmu_tx_commit(tx);
1976 			continue;
1977 		}
1978 
1979 		(void) mutex_lock(lp);
1980 
1981 		wbt.bt_seq = ztest_shared->zs_seq[b]++;
1982 
1983 		dmu_write(os, ZTEST_DIROBJ, off, sizeof (wbt), &wbt, tx);
1984 
1985 		(void) mutex_unlock(lp);
1986 
1987 		if (ztest_random(100) == 0)
1988 			(void) poll(NULL, 0, 1); /* open dn_notxholds window */
1989 
1990 		dmu_tx_commit(tx);
1991 
1992 		if (ztest_random(1000) == 0)
1993 			txg_wait_synced(dmu_objset_pool(os), txg);
1994 
1995 		if (ztest_random(2) == 0) {
1996 			blkptr_t blk = { 0 };
1997 			uint64_t blkoff;
1998 			zbookmark_t zb;
1999 
2000 			txg_suspend(dmu_objset_pool(os));
2001 			(void) mutex_lock(lp);
2002 			error = dmu_sync(os, ZTEST_DIROBJ, off, &blkoff, &blk,
2003 			    txg);
2004 			(void) mutex_unlock(lp);
2005 			if (error) {
2006 				txg_resume(dmu_objset_pool(os));
2007 				dprintf("dmu_sync(%s, %d, %llx) = %d\n",
2008 				    osname, ZTEST_DIROBJ, off, error);
2009 				continue;
2010 			}
2011 
2012 			if (blk.blk_birth == 0)	{	/* concurrent free */
2013 				txg_resume(dmu_objset_pool(os));
2014 				continue;
2015 			}
2016 
2017 			ASSERT(blk.blk_fill == 1);
2018 			ASSERT3U(BP_GET_TYPE(&blk), ==, DMU_OT_UINT64_OTHER);
2019 			ASSERT3U(BP_GET_LEVEL(&blk), ==, 0);
2020 			ASSERT3U(BP_GET_LSIZE(&blk), ==, bs);
2021 
2022 			/*
2023 			 * Read the block that dmu_sync() returned to
2024 			 * make sure its contents match what we wrote.
2025 			 * We do this while still txg_suspend()ed to ensure
2026 			 * that the block can't be reused before we read it.
2027 			 */
2028 			zb.zb_objset = dmu_objset_id(os);
2029 			zb.zb_object = ZTEST_DIROBJ;
2030 			zb.zb_level = 0;
2031 			zb.zb_blkid = off / bs;
2032 			error = zio_wait(zio_read(NULL, dmu_objset_spa(os),
2033 			    &blk, iobuf, bs, NULL, NULL,
2034 			    ZIO_PRIORITY_SYNC_READ, ZIO_FLAG_MUSTSUCCEED, &zb));
2035 			ASSERT(error == 0);
2036 
2037 			txg_resume(dmu_objset_pool(os));
2038 
2039 			bcopy(&iobuf[blkoff], &rbt, sizeof (rbt));
2040 
2041 			if (rbt.bt_objset == 0)		/* concurrent free */
2042 				continue;
2043 
2044 			ASSERT3U(rbt.bt_objset, ==, wbt.bt_objset);
2045 			ASSERT3U(rbt.bt_object, ==, wbt.bt_object);
2046 			ASSERT3U(rbt.bt_offset, ==, wbt.bt_offset);
2047 
2048 			/*
2049 			 * The semantic of dmu_sync() is that we always
2050 			 * push the most recent version of the data,
2051 			 * so in the face of concurrent updates we may
2052 			 * see a newer version of the block.  That's OK.
2053 			 */
2054 			ASSERT3U(rbt.bt_txg, >=, wbt.bt_txg);
2055 			if (rbt.bt_thread == wbt.bt_thread)
2056 				ASSERT3U(rbt.bt_seq, ==, wbt.bt_seq);
2057 			else
2058 				ASSERT3U(rbt.bt_seq, >, wbt.bt_seq);
2059 		}
2060 	}
2061 }
2062 
2063 /*
2064  * Verify that zap_{create,destroy,add,remove,update} work as expected.
2065  */
2066 #define	ZTEST_ZAP_MIN_INTS	1
2067 #define	ZTEST_ZAP_MAX_INTS	4
2068 #define	ZTEST_ZAP_MAX_PROPS	1000
2069 
2070 void
2071 ztest_zap(ztest_args_t *za)
2072 {
2073 	objset_t *os = za->za_os;
2074 	uint64_t object;
2075 	uint64_t txg, last_txg;
2076 	uint64_t value[ZTEST_ZAP_MAX_INTS];
2077 	uint64_t zl_ints, zl_intsize, prop;
2078 	int i, ints;
2079 	int iters = 100;
2080 	dmu_tx_t *tx;
2081 	char propname[100], txgname[100];
2082 	int error;
2083 	char osname[MAXNAMELEN];
2084 	char *hc[2] = { "s.acl.h", ".s.open.h.hyLZlg" };
2085 
2086 	dmu_objset_name(os, osname);
2087 
2088 	/*
2089 	 * Create a new object if necessary, and record it in the directory.
2090 	 */
2091 	VERIFY(0 == dmu_read(os, ZTEST_DIROBJ, za->za_diroff,
2092 	    sizeof (uint64_t), &object));
2093 
2094 	if (object == 0) {
2095 		tx = dmu_tx_create(os);
2096 		dmu_tx_hold_write(tx, ZTEST_DIROBJ, za->za_diroff,
2097 		    sizeof (uint64_t));
2098 		dmu_tx_hold_zap(tx, DMU_NEW_OBJECT, TRUE, NULL);
2099 		error = dmu_tx_assign(tx, TXG_WAIT);
2100 		if (error) {
2101 			ztest_record_enospc("create zap test obj");
2102 			dmu_tx_abort(tx);
2103 			return;
2104 		}
2105 		object = zap_create(os, DMU_OT_ZAP_OTHER, DMU_OT_NONE, 0, tx);
2106 		if (error) {
2107 			fatal(0, "zap_create('%s', %llu) = %d",
2108 			    osname, object, error);
2109 		}
2110 		ASSERT(object != 0);
2111 		dmu_write(os, ZTEST_DIROBJ, za->za_diroff,
2112 		    sizeof (uint64_t), &object, tx);
2113 		/*
2114 		 * Generate a known hash collision, and verify that
2115 		 * we can lookup and remove both entries.
2116 		 */
2117 		for (i = 0; i < 2; i++) {
2118 			value[i] = i;
2119 			error = zap_add(os, object, hc[i], sizeof (uint64_t),
2120 			    1, &value[i], tx);
2121 			ASSERT3U(error, ==, 0);
2122 		}
2123 		for (i = 0; i < 2; i++) {
2124 			error = zap_add(os, object, hc[i], sizeof (uint64_t),
2125 			    1, &value[i], tx);
2126 			ASSERT3U(error, ==, EEXIST);
2127 			error = zap_length(os, object, hc[i],
2128 			    &zl_intsize, &zl_ints);
2129 			ASSERT3U(error, ==, 0);
2130 			ASSERT3U(zl_intsize, ==, sizeof (uint64_t));
2131 			ASSERT3U(zl_ints, ==, 1);
2132 		}
2133 		for (i = 0; i < 2; i++) {
2134 			error = zap_remove(os, object, hc[i], tx);
2135 			ASSERT3U(error, ==, 0);
2136 		}
2137 
2138 		dmu_tx_commit(tx);
2139 	}
2140 
2141 	ints = MAX(ZTEST_ZAP_MIN_INTS, object % ZTEST_ZAP_MAX_INTS);
2142 
2143 	while (--iters >= 0) {
2144 		prop = ztest_random(ZTEST_ZAP_MAX_PROPS);
2145 		(void) sprintf(propname, "prop_%llu", (u_longlong_t)prop);
2146 		(void) sprintf(txgname, "txg_%llu", (u_longlong_t)prop);
2147 		bzero(value, sizeof (value));
2148 		last_txg = 0;
2149 
2150 		/*
2151 		 * If these zap entries already exist, validate their contents.
2152 		 */
2153 		error = zap_length(os, object, txgname, &zl_intsize, &zl_ints);
2154 		if (error == 0) {
2155 			ASSERT3U(zl_intsize, ==, sizeof (uint64_t));
2156 			ASSERT3U(zl_ints, ==, 1);
2157 
2158 			error = zap_lookup(os, object, txgname, zl_intsize,
2159 			    zl_ints, &last_txg);
2160 
2161 			ASSERT3U(error, ==, 0);
2162 
2163 			error = zap_length(os, object, propname, &zl_intsize,
2164 			    &zl_ints);
2165 
2166 			ASSERT3U(error, ==, 0);
2167 			ASSERT3U(zl_intsize, ==, sizeof (uint64_t));
2168 			ASSERT3U(zl_ints, ==, ints);
2169 
2170 			error = zap_lookup(os, object, propname, zl_intsize,
2171 			    zl_ints, value);
2172 
2173 			ASSERT3U(error, ==, 0);
2174 
2175 			for (i = 0; i < ints; i++) {
2176 				ASSERT3U(value[i], ==, last_txg + object + i);
2177 			}
2178 		} else {
2179 			ASSERT3U(error, ==, ENOENT);
2180 		}
2181 
2182 		/*
2183 		 * Atomically update two entries in our zap object.
2184 		 * The first is named txg_%llu, and contains the txg
2185 		 * in which the property was last updated.  The second
2186 		 * is named prop_%llu, and the nth element of its value
2187 		 * should be txg + object + n.
2188 		 */
2189 		tx = dmu_tx_create(os);
2190 		dmu_tx_hold_zap(tx, object, TRUE, NULL);
2191 		error = dmu_tx_assign(tx, TXG_WAIT);
2192 		if (error) {
2193 			ztest_record_enospc("create zap entry");
2194 			dmu_tx_abort(tx);
2195 			return;
2196 		}
2197 		txg = dmu_tx_get_txg(tx);
2198 
2199 		if (last_txg > txg)
2200 			fatal(0, "zap future leak: old %llu new %llu",
2201 			    last_txg, txg);
2202 
2203 		for (i = 0; i < ints; i++)
2204 			value[i] = txg + object + i;
2205 
2206 		error = zap_update(os, object, txgname, sizeof (uint64_t),
2207 		    1, &txg, tx);
2208 		if (error)
2209 			fatal(0, "zap_update('%s', %llu, '%s') = %d",
2210 			    osname, object, txgname, error);
2211 
2212 		error = zap_update(os, object, propname, sizeof (uint64_t),
2213 		    ints, value, tx);
2214 		if (error)
2215 			fatal(0, "zap_update('%s', %llu, '%s') = %d",
2216 			    osname, object, propname, error);
2217 
2218 		dmu_tx_commit(tx);
2219 
2220 		/*
2221 		 * Remove a random pair of entries.
2222 		 */
2223 		prop = ztest_random(ZTEST_ZAP_MAX_PROPS);
2224 		(void) sprintf(propname, "prop_%llu", (u_longlong_t)prop);
2225 		(void) sprintf(txgname, "txg_%llu", (u_longlong_t)prop);
2226 
2227 		error = zap_length(os, object, txgname, &zl_intsize, &zl_ints);
2228 
2229 		if (error == ENOENT)
2230 			continue;
2231 
2232 		ASSERT3U(error, ==, 0);
2233 
2234 		tx = dmu_tx_create(os);
2235 		dmu_tx_hold_zap(tx, object, TRUE, NULL);
2236 		error = dmu_tx_assign(tx, TXG_WAIT);
2237 		if (error) {
2238 			ztest_record_enospc("remove zap entry");
2239 			dmu_tx_abort(tx);
2240 			return;
2241 		}
2242 		error = zap_remove(os, object, txgname, tx);
2243 		if (error)
2244 			fatal(0, "zap_remove('%s', %llu, '%s') = %d",
2245 			    osname, object, txgname, error);
2246 
2247 		error = zap_remove(os, object, propname, tx);
2248 		if (error)
2249 			fatal(0, "zap_remove('%s', %llu, '%s') = %d",
2250 			    osname, object, propname, error);
2251 
2252 		dmu_tx_commit(tx);
2253 	}
2254 
2255 	/*
2256 	 * Once in a while, destroy the object.
2257 	 */
2258 	if (ztest_random(100) != 0)
2259 		return;
2260 
2261 	tx = dmu_tx_create(os);
2262 	dmu_tx_hold_write(tx, ZTEST_DIROBJ, za->za_diroff, sizeof (uint64_t));
2263 	dmu_tx_hold_free(tx, object, 0, DMU_OBJECT_END);
2264 	error = dmu_tx_assign(tx, TXG_WAIT);
2265 	if (error) {
2266 		ztest_record_enospc("destroy zap object");
2267 		dmu_tx_abort(tx);
2268 		return;
2269 	}
2270 	error = zap_destroy(os, object, tx);
2271 	if (error)
2272 		fatal(0, "zap_destroy('%s', %llu) = %d",
2273 		    osname, object, error);
2274 	object = 0;
2275 	dmu_write(os, ZTEST_DIROBJ, za->za_diroff, sizeof (uint64_t),
2276 	    &object, tx);
2277 	dmu_tx_commit(tx);
2278 }
2279 
2280 void
2281 ztest_zap_parallel(ztest_args_t *za)
2282 {
2283 	objset_t *os = za->za_os;
2284 	uint64_t txg, object, count, wsize, wc, zl_wsize, zl_wc;
2285 	int iters = 100;
2286 	dmu_tx_t *tx;
2287 	int i, namelen, error;
2288 	char name[20], string_value[20];
2289 	void *data;
2290 
2291 	while (--iters >= 0) {
2292 		/*
2293 		 * Generate a random name of the form 'xxx.....' where each
2294 		 * x is a random printable character and the dots are dots.
2295 		 * There are 94 such characters, and the name length goes from
2296 		 * 6 to 20, so there are 94^3 * 15 = 12,458,760 possible names.
2297 		 */
2298 		namelen = ztest_random(sizeof (name) - 5) + 5 + 1;
2299 
2300 		for (i = 0; i < 3; i++)
2301 			name[i] = '!' + ztest_random('~' - '!' + 1);
2302 		for (; i < namelen - 1; i++)
2303 			name[i] = '.';
2304 		name[i] = '\0';
2305 
2306 		if (ztest_random(2) == 0)
2307 			object = ZTEST_MICROZAP_OBJ;
2308 		else
2309 			object = ZTEST_FATZAP_OBJ;
2310 
2311 		if ((namelen & 1) || object == ZTEST_MICROZAP_OBJ) {
2312 			wsize = sizeof (txg);
2313 			wc = 1;
2314 			data = &txg;
2315 		} else {
2316 			wsize = 1;
2317 			wc = namelen;
2318 			data = string_value;
2319 		}
2320 
2321 		count = -1ULL;
2322 		VERIFY(zap_count(os, object, &count) == 0);
2323 		ASSERT(count != -1ULL);
2324 
2325 		/*
2326 		 * Select an operation: length, lookup, add, update, remove.
2327 		 */
2328 		i = ztest_random(5);
2329 
2330 		if (i >= 2) {
2331 			tx = dmu_tx_create(os);
2332 			dmu_tx_hold_zap(tx, object, TRUE, NULL);
2333 			error = dmu_tx_assign(tx, TXG_WAIT);
2334 			if (error) {
2335 				ztest_record_enospc("zap parallel");
2336 				dmu_tx_abort(tx);
2337 				return;
2338 			}
2339 			txg = dmu_tx_get_txg(tx);
2340 			bcopy(name, string_value, namelen);
2341 		} else {
2342 			tx = NULL;
2343 			txg = 0;
2344 			bzero(string_value, namelen);
2345 		}
2346 
2347 		switch (i) {
2348 
2349 		case 0:
2350 			error = zap_length(os, object, name, &zl_wsize, &zl_wc);
2351 			if (error == 0) {
2352 				ASSERT3U(wsize, ==, zl_wsize);
2353 				ASSERT3U(wc, ==, zl_wc);
2354 			} else {
2355 				ASSERT3U(error, ==, ENOENT);
2356 			}
2357 			break;
2358 
2359 		case 1:
2360 			error = zap_lookup(os, object, name, wsize, wc, data);
2361 			if (error == 0) {
2362 				if (data == string_value &&
2363 				    bcmp(name, data, namelen) != 0)
2364 					fatal(0, "name '%s' != val '%s' len %d",
2365 					    name, data, namelen);
2366 			} else {
2367 				ASSERT3U(error, ==, ENOENT);
2368 			}
2369 			break;
2370 
2371 		case 2:
2372 			error = zap_add(os, object, name, wsize, wc, data, tx);
2373 			ASSERT(error == 0 || error == EEXIST);
2374 			break;
2375 
2376 		case 3:
2377 			VERIFY(zap_update(os, object, name, wsize, wc,
2378 			    data, tx) == 0);
2379 			break;
2380 
2381 		case 4:
2382 			error = zap_remove(os, object, name, tx);
2383 			ASSERT(error == 0 || error == ENOENT);
2384 			break;
2385 		}
2386 
2387 		if (tx != NULL)
2388 			dmu_tx_commit(tx);
2389 	}
2390 }
2391 
2392 void
2393 ztest_dsl_prop_get_set(ztest_args_t *za)
2394 {
2395 	objset_t *os = za->za_os;
2396 	int i, inherit;
2397 	uint64_t value;
2398 	const char *prop, *valname;
2399 	char setpoint[MAXPATHLEN];
2400 	char osname[MAXNAMELEN];
2401 	int error;
2402 
2403 	(void) rw_rdlock(&ztest_shared->zs_name_lock);
2404 
2405 	dmu_objset_name(os, osname);
2406 
2407 	for (i = 0; i < 2; i++) {
2408 		if (i == 0) {
2409 			prop = "checksum";
2410 			value = ztest_random_checksum();
2411 			inherit = (value == ZIO_CHECKSUM_INHERIT);
2412 		} else {
2413 			prop = "compression";
2414 			value = ztest_random_compress();
2415 			inherit = (value == ZIO_COMPRESS_INHERIT);
2416 		}
2417 
2418 		error = dsl_prop_set(osname, prop, sizeof (value),
2419 		    !inherit, &value);
2420 
2421 		if (error == ENOSPC) {
2422 			ztest_record_enospc("dsl_prop_set");
2423 			break;
2424 		}
2425 
2426 		ASSERT3U(error, ==, 0);
2427 
2428 		VERIFY3U(dsl_prop_get(osname, prop, sizeof (value),
2429 		    1, &value, setpoint), ==, 0);
2430 
2431 		if (i == 0)
2432 			valname = zio_checksum_table[value].ci_name;
2433 		else
2434 			valname = zio_compress_table[value].ci_name;
2435 
2436 		if (zopt_verbose >= 6) {
2437 			(void) printf("%s %s = %s for '%s'\n",
2438 			    osname, prop, valname, setpoint);
2439 		}
2440 	}
2441 
2442 	(void) rw_unlock(&ztest_shared->zs_name_lock);
2443 }
2444 
2445 static void
2446 ztest_error_setup(vdev_t *vd, int mode, int mask, uint64_t arg)
2447 {
2448 	int c;
2449 
2450 	for (c = 0; c < vd->vdev_children; c++)
2451 		ztest_error_setup(vd->vdev_child[c], mode, mask, arg);
2452 
2453 	if (vd->vdev_path != NULL) {
2454 		vd->vdev_fault_mode = mode;
2455 		vd->vdev_fault_mask = mask;
2456 		vd->vdev_fault_arg = arg;
2457 	}
2458 }
2459 
2460 /*
2461  * Inject random faults into the on-disk data.
2462  */
2463 void
2464 ztest_fault_inject(ztest_args_t *za)
2465 {
2466 	int fd;
2467 	uint64_t offset;
2468 	uint64_t leaves = MAX(zopt_mirrors, 1) * zopt_raidz;
2469 	uint64_t bad = 0x1990c0ffeedecade;
2470 	uint64_t top, leaf;
2471 	char path0[MAXPATHLEN];
2472 	char pathrand[MAXPATHLEN];
2473 	size_t fsize;
2474 	spa_t *spa = dmu_objset_spa(za->za_os);
2475 	int bshift = SPA_MAXBLOCKSHIFT + 2;	/* don't scrog all labels */
2476 	int iters = 1000;
2477 	vdev_t *vd0;
2478 	uint64_t guid0 = 0;
2479 
2480 	/*
2481 	 * We can't inject faults when we have no fault tolerance.
2482 	 */
2483 	if (zopt_maxfaults == 0)
2484 		return;
2485 
2486 	ASSERT(leaves >= 2);
2487 
2488 	/*
2489 	 * Pick a random top-level vdev.
2490 	 */
2491 	spa_config_enter(spa, RW_READER, FTAG);
2492 	top = ztest_random(spa->spa_root_vdev->vdev_children);
2493 	spa_config_exit(spa, FTAG);
2494 
2495 	/*
2496 	 * Pick a random leaf.
2497 	 */
2498 	leaf = ztest_random(leaves);
2499 
2500 	/*
2501 	 * Generate paths to the first two leaves in this top-level vdev,
2502 	 * and to the random leaf we selected.  We'll induce transient
2503 	 * I/O errors and random online/offline activity on leaf 0,
2504 	 * and we'll write random garbage to the randomly chosen leaf.
2505 	 */
2506 	(void) snprintf(path0, sizeof (path0),
2507 	    ztest_dev_template, zopt_dir, zopt_pool, top * leaves + 0);
2508 	(void) snprintf(pathrand, sizeof (pathrand),
2509 	    ztest_dev_template, zopt_dir, zopt_pool, top * leaves + leaf);
2510 
2511 	dprintf("damaging %s and %s\n", path0, pathrand);
2512 
2513 	spa_config_enter(spa, RW_READER, FTAG);
2514 
2515 	/*
2516 	 * If we can tolerate two or more faults, make vd0 fail randomly.
2517 	 */
2518 	vd0 = vdev_lookup_by_path(spa->spa_root_vdev, path0);
2519 	if (vd0 != NULL && zopt_maxfaults >= 2) {
2520 		guid0 = vd0->vdev_guid;
2521 		ztest_error_setup(vd0, VDEV_FAULT_COUNT,
2522 		    (1U << ZIO_TYPE_READ) | (1U << ZIO_TYPE_WRITE), 100);
2523 	}
2524 
2525 	spa_config_exit(spa, FTAG);
2526 
2527 	/*
2528 	 * If we can tolerate two or more faults, randomly online/offline vd0.
2529 	 */
2530 	if (zopt_maxfaults >= 2 && guid0 != 0) {
2531 		if (ztest_random(10) < 6)
2532 			(void) vdev_offline(spa, guid0, B_TRUE);
2533 		else
2534 			(void) vdev_online(spa, guid0);
2535 	}
2536 
2537 	/*
2538 	 * We have at least single-fault tolerance, so inject data corruption.
2539 	 */
2540 	fd = open(pathrand, O_RDWR);
2541 
2542 	if (fd == -1)	/* we hit a gap in the device namespace */
2543 		return;
2544 
2545 	fsize = lseek(fd, 0, SEEK_END);
2546 
2547 	while (--iters != 0) {
2548 		offset = ztest_random(fsize / (leaves << bshift)) *
2549 		    (leaves << bshift) + (leaf << bshift) +
2550 		    (ztest_random(1ULL << (bshift - 1)) & -8ULL);
2551 
2552 		if (offset >= fsize)
2553 			continue;
2554 
2555 		if (zopt_verbose >= 6)
2556 			(void) printf("injecting bad word into %s,"
2557 			    " offset 0x%llx\n", pathrand, (u_longlong_t)offset);
2558 
2559 		if (pwrite(fd, &bad, sizeof (bad), offset) != sizeof (bad))
2560 			fatal(1, "can't inject bad word at 0x%llx in %s",
2561 			    offset, pathrand);
2562 	}
2563 
2564 	(void) close(fd);
2565 }
2566 
2567 /*
2568  * Scrub the pool.
2569  */
2570 void
2571 ztest_scrub(ztest_args_t *za)
2572 {
2573 	spa_t *spa = dmu_objset_spa(za->za_os);
2574 
2575 	(void) spa_scrub(spa, POOL_SCRUB_EVERYTHING, B_FALSE);
2576 	(void) poll(NULL, 0, 1000); /* wait a second, then force a restart */
2577 	(void) spa_scrub(spa, POOL_SCRUB_EVERYTHING, B_FALSE);
2578 }
2579 
2580 /*
2581  * Rename the pool to a different name and then rename it back.
2582  */
2583 void
2584 ztest_spa_rename(ztest_args_t *za)
2585 {
2586 	char *oldname, *newname;
2587 	int error;
2588 	spa_t *spa;
2589 
2590 	(void) rw_wrlock(&ztest_shared->zs_name_lock);
2591 
2592 	oldname = za->za_pool;
2593 	newname = umem_alloc(strlen(oldname) + 5, UMEM_NOFAIL);
2594 	(void) strcpy(newname, oldname);
2595 	(void) strcat(newname, "_tmp");
2596 
2597 	/*
2598 	 * Do the rename
2599 	 */
2600 	error = spa_rename(oldname, newname);
2601 	if (error)
2602 		fatal(0, "spa_rename('%s', '%s') = %d", oldname,
2603 		    newname, error);
2604 
2605 	/*
2606 	 * Try to open it under the old name, which shouldn't exist
2607 	 */
2608 	error = spa_open(oldname, &spa, FTAG);
2609 	if (error != ENOENT)
2610 		fatal(0, "spa_open('%s') = %d", oldname, error);
2611 
2612 	/*
2613 	 * Open it under the new name and make sure it's still the same spa_t.
2614 	 */
2615 	error = spa_open(newname, &spa, FTAG);
2616 	if (error != 0)
2617 		fatal(0, "spa_open('%s') = %d", newname, error);
2618 
2619 	ASSERT(spa == dmu_objset_spa(za->za_os));
2620 	spa_close(spa, FTAG);
2621 
2622 	/*
2623 	 * Rename it back to the original
2624 	 */
2625 	error = spa_rename(newname, oldname);
2626 	if (error)
2627 		fatal(0, "spa_rename('%s', '%s') = %d", newname,
2628 		    oldname, error);
2629 
2630 	/*
2631 	 * Make sure it can still be opened
2632 	 */
2633 	error = spa_open(oldname, &spa, FTAG);
2634 	if (error != 0)
2635 		fatal(0, "spa_open('%s') = %d", oldname, error);
2636 
2637 	ASSERT(spa == dmu_objset_spa(za->za_os));
2638 	spa_close(spa, FTAG);
2639 
2640 	umem_free(newname, strlen(newname) + 1);
2641 
2642 	(void) rw_unlock(&ztest_shared->zs_name_lock);
2643 }
2644 
2645 
2646 /*
2647  * Completely obliterate one disk.
2648  */
2649 static void
2650 ztest_obliterate_one_disk(uint64_t vdev)
2651 {
2652 	int fd;
2653 	char dev_name[MAXPATHLEN];
2654 	size_t fsize;
2655 
2656 	if (zopt_maxfaults < 2)
2657 		return;
2658 
2659 	(void) sprintf(dev_name, ztest_dev_template, zopt_dir, zopt_pool, vdev);
2660 
2661 	fd = open(dev_name, O_RDWR);
2662 
2663 	if (fd == -1)
2664 		fatal(1, "can't open %s", dev_name);
2665 
2666 	/*
2667 	 * Determine the size.
2668 	 */
2669 	fsize = lseek(fd, 0, SEEK_END);
2670 	(void) close(fd);
2671 
2672 	/*
2673 	 * Remove it.
2674 	 */
2675 	VERIFY(remove(dev_name) == 0);
2676 
2677 	/*
2678 	 * Create a new one.
2679 	 */
2680 	VERIFY((fd = open(dev_name, O_RDWR | O_CREAT | O_TRUNC, 0666)) >= 0);
2681 	VERIFY(ftruncate(fd, fsize) == 0);
2682 	(void) close(fd);
2683 }
2684 
2685 static void
2686 ztest_replace_one_disk(spa_t *spa, uint64_t vdev)
2687 {
2688 	char dev_name[MAXPATHLEN];
2689 	nvlist_t *file, *root;
2690 	int error;
2691 	uint64_t guid;
2692 	vdev_t *vd;
2693 
2694 	(void) sprintf(dev_name, ztest_dev_template, zopt_dir, zopt_pool, vdev);
2695 
2696 	/*
2697 	 * Build the nvlist describing dev_name.
2698 	 */
2699 	VERIFY(nvlist_alloc(&file, NV_UNIQUE_NAME, 0) == 0);
2700 	VERIFY(nvlist_add_string(file, ZPOOL_CONFIG_TYPE, VDEV_TYPE_FILE) == 0);
2701 	VERIFY(nvlist_add_string(file, ZPOOL_CONFIG_PATH, dev_name) == 0);
2702 
2703 	VERIFY(nvlist_alloc(&root, NV_UNIQUE_NAME, 0) == 0);
2704 	VERIFY(nvlist_add_string(root, ZPOOL_CONFIG_TYPE, VDEV_TYPE_ROOT) == 0);
2705 	VERIFY(nvlist_add_nvlist_array(root, ZPOOL_CONFIG_CHILDREN,
2706 	    &file, 1) == 0);
2707 
2708 	spa_config_enter(spa, RW_READER, FTAG);
2709 	if ((vd = vdev_lookup_by_path(spa->spa_root_vdev, dev_name)) == NULL)
2710 		guid = 0;
2711 	else
2712 		guid = vd->vdev_guid;
2713 	spa_config_exit(spa, FTAG);
2714 	error = spa_vdev_attach(spa, guid, root, B_TRUE);
2715 	if (error != 0 && error != EBUSY && error != ENOTSUP && error != ENODEV)
2716 		fatal(0, "spa_vdev_attach(in-place) = %d", error);
2717 
2718 	nvlist_free(file);
2719 	nvlist_free(root);
2720 }
2721 
2722 static void
2723 ztest_verify_blocks(char *pool)
2724 {
2725 	int status;
2726 	char zdb[MAXPATHLEN + MAXNAMELEN + 20];
2727 	char zbuf[1024];
2728 	char *bin;
2729 	FILE *fp;
2730 
2731 	(void) realpath(getexecname(), zdb);
2732 
2733 	/* zdb lives in /usr/sbin, while ztest lives in /usr/bin */
2734 	bin = strstr(zdb, "/usr/bin/");
2735 	/* LINTED */
2736 	(void) sprintf(bin, "/usr/sbin/zdb -bc%s%s -U -O %s %s",
2737 	    zopt_verbose >= 3 ? "s" : "",
2738 	    zopt_verbose >= 4 ? "v" : "",
2739 	    ztest_random(2) == 0 ? "pre" : "post", pool);
2740 
2741 	if (zopt_verbose >= 5)
2742 		(void) printf("Executing %s\n", strstr(zdb, "zdb "));
2743 
2744 	fp = popen(zdb, "r");
2745 
2746 	while (fgets(zbuf, sizeof (zbuf), fp) != NULL)
2747 		if (zopt_verbose >= 3)
2748 			(void) printf("%s", zbuf);
2749 
2750 	status = pclose(fp);
2751 
2752 	if (status == 0)
2753 		return;
2754 
2755 	ztest_dump_core = 0;
2756 	if (WIFEXITED(status))
2757 		fatal(0, "'%s' exit code %d", zdb, WEXITSTATUS(status));
2758 	else
2759 		fatal(0, "'%s' died with signal %d", zdb, WTERMSIG(status));
2760 }
2761 
2762 static void
2763 ztest_walk_pool_directory(char *header)
2764 {
2765 	spa_t *spa = NULL;
2766 
2767 	if (zopt_verbose >= 6)
2768 		(void) printf("%s\n", header);
2769 
2770 	mutex_enter(&spa_namespace_lock);
2771 	while ((spa = spa_next(spa)) != NULL)
2772 		if (zopt_verbose >= 6)
2773 			(void) printf("\t%s\n", spa_name(spa));
2774 	mutex_exit(&spa_namespace_lock);
2775 }
2776 
2777 static void
2778 ztest_spa_import_export(char *oldname, char *newname)
2779 {
2780 	nvlist_t *config;
2781 	uint64_t pool_guid;
2782 	spa_t *spa;
2783 	int error;
2784 
2785 	if (zopt_verbose >= 4) {
2786 		(void) printf("import/export: old = %s, new = %s\n",
2787 		    oldname, newname);
2788 	}
2789 
2790 	/*
2791 	 * Clean up from previous runs.
2792 	 */
2793 	(void) spa_destroy(newname);
2794 
2795 	/*
2796 	 * Get the pool's configuration and guid.
2797 	 */
2798 	error = spa_open(oldname, &spa, FTAG);
2799 	if (error)
2800 		fatal(0, "spa_open('%s') = %d", oldname, error);
2801 
2802 	ASSERT(spa->spa_config != NULL);
2803 
2804 	VERIFY(nvlist_dup(spa->spa_config, &config, 0) == 0);
2805 	pool_guid = spa_guid(spa);
2806 	spa_close(spa, FTAG);
2807 
2808 	ztest_walk_pool_directory("pools before export");
2809 
2810 	/*
2811 	 * Export it.
2812 	 */
2813 	error = spa_export(oldname);
2814 	if (error)
2815 		fatal(0, "spa_export('%s') = %d", oldname, error);
2816 
2817 	ztest_walk_pool_directory("pools after export");
2818 
2819 	/*
2820 	 * Import it under the new name.
2821 	 */
2822 	error = spa_import(newname, config, NULL);
2823 	if (error)
2824 		fatal(0, "spa_import('%s') = %d", newname, error);
2825 
2826 	ztest_walk_pool_directory("pools after import");
2827 
2828 	/*
2829 	 * Try to import it again -- should fail with EEXIST.
2830 	 */
2831 	error = spa_import(newname, config, NULL);
2832 	if (error != EEXIST)
2833 		fatal(0, "spa_import('%s') twice", newname);
2834 
2835 	/*
2836 	 * Try to import it under a different name -- should fail with EEXIST.
2837 	 */
2838 	error = spa_import(oldname, config, NULL);
2839 	if (error != EEXIST)
2840 		fatal(0, "spa_import('%s') under multiple names", newname);
2841 
2842 	/*
2843 	 * Verify that the pool is no longer visible under the old name.
2844 	 */
2845 	error = spa_open(oldname, &spa, FTAG);
2846 	if (error != ENOENT)
2847 		fatal(0, "spa_open('%s') = %d", newname, error);
2848 
2849 	/*
2850 	 * Verify that we can open and close the pool using the new name.
2851 	 */
2852 	error = spa_open(newname, &spa, FTAG);
2853 	if (error)
2854 		fatal(0, "spa_open('%s') = %d", newname, error);
2855 	ASSERT(pool_guid == spa_guid(spa));
2856 	spa_close(spa, FTAG);
2857 
2858 	nvlist_free(config);
2859 }
2860 
2861 static void *
2862 ztest_thread(void *arg)
2863 {
2864 	ztest_args_t *za = arg;
2865 	ztest_shared_t *zs = ztest_shared;
2866 	hrtime_t now, functime;
2867 	ztest_info_t *zi;
2868 	int f;
2869 
2870 	while ((now = gethrtime()) < za->za_stop) {
2871 		/*
2872 		 * See if it's time to force a crash.
2873 		 */
2874 		if (now > za->za_kill) {
2875 			zs->zs_alloc = spa_get_alloc(dmu_objset_spa(za->za_os));
2876 			zs->zs_space = spa_get_space(dmu_objset_spa(za->za_os));
2877 			(void) kill(getpid(), SIGKILL);
2878 		}
2879 
2880 		/*
2881 		 * Pick a random function.
2882 		 */
2883 		f = ztest_random(ZTEST_FUNCS);
2884 		zi = &zs->zs_info[f];
2885 
2886 		/*
2887 		 * Decide whether to call it, based on the requested frequency.
2888 		 */
2889 		if (zi->zi_call_target == 0 ||
2890 		    (double)zi->zi_call_total / zi->zi_call_target >
2891 		    (double)(now - zs->zs_start_time) / (zopt_time * NANOSEC))
2892 			continue;
2893 
2894 		atomic_add_64(&zi->zi_calls, 1);
2895 		atomic_add_64(&zi->zi_call_total, 1);
2896 
2897 		za->za_diroff = (za->za_instance * ZTEST_FUNCS + f) *
2898 		    ZTEST_DIRSIZE;
2899 		za->za_diroff_shared = (1ULL << 63);
2900 
2901 		ztest_dmu_write_parallel(za);
2902 
2903 		zi->zi_func(za);
2904 
2905 		functime = gethrtime() - now;
2906 
2907 		atomic_add_64(&zi->zi_call_time, functime);
2908 
2909 		if (zopt_verbose >= 4) {
2910 			Dl_info dli;
2911 			(void) dladdr((void *)zi->zi_func, &dli);
2912 			(void) printf("%6.2f sec in %s\n",
2913 			    (double)functime / NANOSEC, dli.dli_sname);
2914 		}
2915 
2916 		/*
2917 		 * If we're getting ENOSPC with some regularity, stop.
2918 		 */
2919 		if (zs->zs_enospc_count > 10)
2920 			break;
2921 	}
2922 
2923 	return (NULL);
2924 }
2925 
2926 /*
2927  * Kick off threads to run tests on all datasets in parallel.
2928  */
2929 static void
2930 ztest_run(char *pool)
2931 {
2932 	int t, d, error;
2933 	ztest_shared_t *zs = ztest_shared;
2934 	ztest_args_t *za;
2935 	spa_t *spa;
2936 	char name[100];
2937 
2938 	(void) _mutex_init(&zs->zs_vdev_lock, USYNC_THREAD, NULL);
2939 	(void) rwlock_init(&zs->zs_name_lock, USYNC_THREAD, NULL);
2940 
2941 	for (t = 0; t < ZTEST_SYNC_LOCKS; t++)
2942 		(void) _mutex_init(&zs->zs_sync_lock[t], USYNC_THREAD, NULL);
2943 
2944 	/*
2945 	 * Destroy one disk before we even start.
2946 	 * It's mirrored, so everything should work just fine.
2947 	 * This makes us exercise fault handling very early in spa_load().
2948 	 */
2949 	ztest_obliterate_one_disk(0);
2950 
2951 	/*
2952 	 * Verify that the sum of the sizes of all blocks in the pool
2953 	 * equals the SPA's allocated space total.
2954 	 */
2955 	ztest_verify_blocks(pool);
2956 
2957 	/*
2958 	 * Kick off a replacement of the disk we just obliterated.
2959 	 */
2960 	kernel_init(FREAD | FWRITE);
2961 	error = spa_open(pool, &spa, FTAG);
2962 	if (error)
2963 		fatal(0, "spa_open(%s) = %d", pool, error);
2964 	ztest_replace_one_disk(spa, 0);
2965 	if (zopt_verbose >= 5)
2966 		show_pool_stats(spa);
2967 	spa_close(spa, FTAG);
2968 	kernel_fini();
2969 
2970 	kernel_init(FREAD | FWRITE);
2971 
2972 	/*
2973 	 * Verify that we can export the pool and reimport it under a
2974 	 * different name.
2975 	 */
2976 	if (ztest_random(2) == 0) {
2977 		(void) snprintf(name, 100, "%s_import", pool);
2978 		ztest_spa_import_export(pool, name);
2979 		ztest_spa_import_export(name, pool);
2980 	}
2981 
2982 	/*
2983 	 * Verify that we can loop over all pools.
2984 	 */
2985 	mutex_enter(&spa_namespace_lock);
2986 	for (spa = spa_next(NULL); spa != NULL; spa = spa_next(spa)) {
2987 		if (zopt_verbose > 3) {
2988 			(void) printf("spa_next: found %s\n", spa_name(spa));
2989 		}
2990 	}
2991 	mutex_exit(&spa_namespace_lock);
2992 
2993 	/*
2994 	 * Open our pool.
2995 	 */
2996 	error = spa_open(pool, &spa, FTAG);
2997 	if (error)
2998 		fatal(0, "spa_open() = %d", error);
2999 
3000 	/*
3001 	 * Verify that we can safely inquire about about any object,
3002 	 * whether it's allocated or not.  To make it interesting,
3003 	 * we probe a 5-wide window around each power of two.
3004 	 * This hits all edge cases, including zero and the max.
3005 	 */
3006 	for (t = 0; t < 64; t++) {
3007 		for (d = -5; d <= 5; d++) {
3008 			error = dmu_object_info(spa->spa_meta_objset,
3009 			    (1ULL << t) + d, NULL);
3010 			ASSERT(error == 0 || error == ENOENT ||
3011 			    error == EINVAL);
3012 		}
3013 	}
3014 
3015 	/*
3016 	 * Now kick off all the tests that run in parallel.
3017 	 */
3018 	zs->zs_enospc_count = 0;
3019 
3020 	za = umem_zalloc(zopt_threads * sizeof (ztest_args_t), UMEM_NOFAIL);
3021 
3022 	if (zopt_verbose >= 4)
3023 		(void) printf("starting main threads...\n");
3024 
3025 	za[0].za_start = gethrtime();
3026 	za[0].za_stop = za[0].za_start + zopt_passtime * NANOSEC;
3027 	za[0].za_stop = MIN(za[0].za_stop, zs->zs_stop_time);
3028 	za[0].za_kill = za[0].za_stop;
3029 	if (ztest_random(100) < zopt_killrate)
3030 		za[0].za_kill -= ztest_random(zopt_passtime * NANOSEC);
3031 
3032 	for (t = 0; t < zopt_threads; t++) {
3033 		d = t % zopt_dirs;
3034 		if (t < zopt_dirs) {
3035 			ztest_replay_t zr;
3036 			(void) rw_rdlock(&ztest_shared->zs_name_lock);
3037 			(void) snprintf(name, 100, "%s/%s_%d", pool, pool, d);
3038 			error = dmu_objset_create(name, DMU_OST_OTHER, NULL,
3039 			    ztest_create_cb, NULL);
3040 			if (error != 0 && error != EEXIST) {
3041 				if (error == ENOSPC) {
3042 					zs->zs_enospc_count++;
3043 					(void) rw_unlock(
3044 					    &ztest_shared->zs_name_lock);
3045 					break;
3046 				}
3047 				fatal(0, "dmu_objset_create(%s) = %d",
3048 				    name, error);
3049 			}
3050 			error = dmu_objset_open(name, DMU_OST_OTHER,
3051 			    DS_MODE_STANDARD, &za[d].za_os);
3052 			if (error)
3053 				fatal(0, "dmu_objset_open('%s') = %d",
3054 				    name, error);
3055 			(void) rw_unlock(&ztest_shared->zs_name_lock);
3056 			zr.zr_os = za[d].za_os;
3057 			zil_replay(zr.zr_os, &zr, &zr.zr_assign,
3058 			    ztest_replay_vector, NULL);
3059 			za[d].za_zilog = zil_open(za[d].za_os, NULL);
3060 		}
3061 		za[t].za_pool = spa_strdup(pool);
3062 		za[t].za_os = za[d].za_os;
3063 		za[t].za_zilog = za[d].za_zilog;
3064 		za[t].za_instance = t;
3065 		za[t].za_random = ztest_random(-1ULL);
3066 		za[t].za_start = za[0].za_start;
3067 		za[t].za_stop = za[0].za_stop;
3068 		za[t].za_kill = za[0].za_kill;
3069 
3070 		error = thr_create(0, 0, ztest_thread, &za[t], THR_BOUND,
3071 		    &za[t].za_thread);
3072 		if (error)
3073 			fatal(0, "can't create thread %d: error %d",
3074 			    t, error);
3075 	}
3076 
3077 	while (--t >= 0) {
3078 		error = thr_join(za[t].za_thread, NULL, NULL);
3079 		if (error)
3080 			fatal(0, "thr_join(%d) = %d", t, error);
3081 		if (za[t].za_th)
3082 			traverse_fini(za[t].za_th);
3083 		if (t < zopt_dirs) {
3084 			txg_wait_synced(spa_get_dsl(spa), 0);
3085 			zil_close(za[t].za_zilog);
3086 			dmu_objset_close(za[t].za_os);
3087 		}
3088 		spa_strfree(za[t].za_pool);
3089 	}
3090 
3091 	umem_free(za, zopt_threads * sizeof (ztest_args_t));
3092 
3093 	if (zopt_verbose >= 3)
3094 		show_pool_stats(spa);
3095 
3096 	txg_wait_synced(spa_get_dsl(spa), 0);
3097 
3098 	zs->zs_alloc = spa_get_alloc(spa);
3099 	zs->zs_space = spa_get_space(spa);
3100 
3101 	/*
3102 	 * Did we have out-of-space errors?  If so, destroy a random objset.
3103 	 */
3104 	if (zs->zs_enospc_count != 0) {
3105 		(void) rw_rdlock(&ztest_shared->zs_name_lock);
3106 		(void) snprintf(name, 100, "%s/%s_%d", pool, pool,
3107 		    (int)ztest_random(zopt_dirs));
3108 		if (zopt_verbose >= 3)
3109 			(void) printf("Destroying %s to free up space\n", name);
3110 		dmu_objset_find(name, ztest_destroy_cb, NULL,
3111 		    DS_FIND_SNAPSHOTS);
3112 		(void) rw_unlock(&ztest_shared->zs_name_lock);
3113 	}
3114 
3115 	txg_wait_synced(spa_get_dsl(spa), 0);
3116 
3117 	/*
3118 	 * Right before closing the pool, kick off a bunch of async I/O;
3119 	 * spa_close() should wait for it to complete.
3120 	 */
3121 	for (t = 1; t < 50; t++)
3122 		dmu_prefetch(spa->spa_meta_objset, t, 0, 1 << 15);
3123 
3124 	spa_close(spa, FTAG);
3125 
3126 	kernel_fini();
3127 }
3128 
3129 void
3130 print_time(hrtime_t t, char *timebuf)
3131 {
3132 	hrtime_t s = t / NANOSEC;
3133 	hrtime_t m = s / 60;
3134 	hrtime_t h = m / 60;
3135 	hrtime_t d = h / 24;
3136 
3137 	s -= m * 60;
3138 	m -= h * 60;
3139 	h -= d * 24;
3140 
3141 	timebuf[0] = '\0';
3142 
3143 	if (d)
3144 		(void) sprintf(timebuf,
3145 		    "%llud%02lluh%02llum%02llus", d, h, m, s);
3146 	else if (h)
3147 		(void) sprintf(timebuf, "%lluh%02llum%02llus", h, m, s);
3148 	else if (m)
3149 		(void) sprintf(timebuf, "%llum%02llus", m, s);
3150 	else
3151 		(void) sprintf(timebuf, "%llus", s);
3152 }
3153 
3154 /*
3155  * Create a storage pool with the given name and initial vdev size.
3156  * Then create the specified number of datasets in the pool.
3157  */
3158 static void
3159 ztest_init(char *pool)
3160 {
3161 	spa_t *spa;
3162 	int error;
3163 	nvlist_t *nvroot;
3164 
3165 	kernel_init(FREAD | FWRITE);
3166 
3167 	/*
3168 	 * Create the storage pool.
3169 	 */
3170 	(void) spa_destroy(pool);
3171 	ztest_shared->zs_vdev_primaries = 0;
3172 	nvroot = make_vdev_root(zopt_vdev_size, zopt_raidz, zopt_mirrors, 1);
3173 	error = spa_create(pool, nvroot, NULL);
3174 	nvlist_free(nvroot);
3175 
3176 	if (error)
3177 		fatal(0, "spa_create() = %d", error);
3178 	error = spa_open(pool, &spa, FTAG);
3179 	if (error)
3180 		fatal(0, "spa_open() = %d", error);
3181 
3182 	if (zopt_verbose >= 3)
3183 		show_pool_stats(spa);
3184 
3185 	spa_close(spa, FTAG);
3186 
3187 	kernel_fini();
3188 }
3189 
3190 int
3191 main(int argc, char **argv)
3192 {
3193 	int kills = 0;
3194 	int iters = 0;
3195 	int i, f;
3196 	ztest_shared_t *zs;
3197 	ztest_info_t *zi;
3198 	char timebuf[100];
3199 	char numbuf[6];
3200 
3201 	(void) setvbuf(stdout, NULL, _IOLBF, 0);
3202 
3203 	/* Override location of zpool.cache */
3204 	spa_config_dir = "/tmp";
3205 
3206 	ztest_random_fd = open("/dev/urandom", O_RDONLY);
3207 
3208 	process_options(argc, argv);
3209 
3210 	argc -= optind;
3211 	argv += optind;
3212 
3213 	dprintf_setup(&argc, argv);
3214 
3215 	/*
3216 	 * Blow away any existing copy of zpool.cache
3217 	 */
3218 	if (zopt_init != 0)
3219 		(void) remove("/tmp/zpool.cache");
3220 
3221 	zs = ztest_shared = (void *)mmap(0,
3222 	    P2ROUNDUP(sizeof (ztest_shared_t), getpagesize()),
3223 	    PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANON, -1, 0);
3224 
3225 	if (zopt_verbose >= 1) {
3226 		(void) printf("%llu vdevs, %d datasets, %d threads,"
3227 		    " %llu seconds...\n",
3228 		    (u_longlong_t)zopt_vdevs, zopt_dirs, zopt_threads,
3229 		    (u_longlong_t)zopt_time);
3230 	}
3231 
3232 	/*
3233 	 * Create and initialize our storage pool.
3234 	 */
3235 	for (i = 1; i <= zopt_init; i++) {
3236 		bzero(zs, sizeof (ztest_shared_t));
3237 		if (zopt_verbose >= 3 && zopt_init != 1)
3238 			(void) printf("ztest_init(), pass %d\n", i);
3239 		ztest_init(zopt_pool);
3240 	}
3241 
3242 	/*
3243 	 * Initialize the call targets for each function.
3244 	 */
3245 	for (f = 0; f < ZTEST_FUNCS; f++) {
3246 		zi = &zs->zs_info[f];
3247 
3248 		*zi = ztest_info[f];
3249 
3250 		if (*zi->zi_interval == 0)
3251 			zi->zi_call_target = UINT64_MAX;
3252 		else
3253 			zi->zi_call_target = zopt_time / *zi->zi_interval;
3254 	}
3255 
3256 	zs->zs_start_time = gethrtime();
3257 	zs->zs_stop_time = zs->zs_start_time + zopt_time * NANOSEC;
3258 
3259 	/*
3260 	 * Run the tests in a loop.  These tests include fault injection
3261 	 * to verify that self-healing data works, and forced crashes
3262 	 * to verify that we never lose on-disk consistency.
3263 	 */
3264 	while (gethrtime() < zs->zs_stop_time) {
3265 		int status;
3266 		pid_t pid;
3267 		char *tmp;
3268 
3269 		/*
3270 		 * Initialize the workload counters for each function.
3271 		 */
3272 		for (f = 0; f < ZTEST_FUNCS; f++) {
3273 			zi = &zs->zs_info[f];
3274 			zi->zi_calls = 0;
3275 			zi->zi_call_time = 0;
3276 		}
3277 
3278 		pid = fork();
3279 
3280 		if (pid == -1)
3281 			fatal(1, "fork failed");
3282 
3283 		if (pid == 0) {	/* child */
3284 			struct rlimit rl = { 1024, 1024 };
3285 			(void) setrlimit(RLIMIT_NOFILE, &rl);
3286 			ztest_run(zopt_pool);
3287 			exit(0);
3288 		}
3289 
3290 		while (waitpid(pid, &status, WEXITED) != pid)
3291 			continue;
3292 
3293 		if (WIFEXITED(status)) {
3294 			if (WEXITSTATUS(status) != 0) {
3295 				(void) fprintf(stderr,
3296 				    "child exited with code %d\n",
3297 				    WEXITSTATUS(status));
3298 				exit(2);
3299 			}
3300 		} else {
3301 			if (WTERMSIG(status) != SIGKILL) {
3302 				(void) fprintf(stderr,
3303 				    "child died with signal %d\n",
3304 				    WTERMSIG(status));
3305 				exit(3);
3306 			}
3307 			kills++;
3308 		}
3309 
3310 		iters++;
3311 
3312 		if (zopt_verbose >= 1) {
3313 			hrtime_t now = gethrtime();
3314 
3315 			now = MIN(now, zs->zs_stop_time);
3316 			print_time(zs->zs_stop_time - now, timebuf);
3317 			nicenum(zs->zs_space, numbuf);
3318 
3319 			(void) printf("Pass %3d, %8s, %3llu ENOSPC, "
3320 			    "%4.1f%% of %5s used, %3.0f%% done, %8s to go\n",
3321 			    iters,
3322 			    WIFEXITED(status) ? "Complete" : "SIGKILL",
3323 			    (u_longlong_t)zs->zs_enospc_count,
3324 			    100.0 * zs->zs_alloc / zs->zs_space,
3325 			    numbuf,
3326 			    100.0 * (now - zs->zs_start_time) /
3327 			    (zopt_time * NANOSEC), timebuf);
3328 		}
3329 
3330 		if (zopt_verbose >= 2) {
3331 			(void) printf("\nWorkload summary:\n\n");
3332 			(void) printf("%7s %9s   %s\n",
3333 			    "Calls", "Time", "Function");
3334 			(void) printf("%7s %9s   %s\n",
3335 			    "-----", "----", "--------");
3336 			for (f = 0; f < ZTEST_FUNCS; f++) {
3337 				Dl_info dli;
3338 
3339 				zi = &zs->zs_info[f];
3340 				print_time(zi->zi_call_time, timebuf);
3341 				(void) dladdr((void *)zi->zi_func, &dli);
3342 				(void) printf("%7llu %9s   %s\n",
3343 				    (u_longlong_t)zi->zi_calls, timebuf,
3344 				    dli.dli_sname);
3345 			}
3346 			(void) printf("\n");
3347 		}
3348 
3349 		/*
3350 		 * It's possible that we killed a child during a rename test, in
3351 		 * which case we'll have a 'ztest_tmp' pool lying around instead
3352 		 * of 'ztest'.  Do a blind rename in case this happened.
3353 		 */
3354 		tmp = umem_alloc(strlen(zopt_pool) + 5, UMEM_NOFAIL);
3355 		(void) strcpy(tmp, zopt_pool);
3356 		(void) strcat(tmp, "_tmp");
3357 		kernel_init(FREAD | FWRITE);
3358 		(void) spa_rename(tmp, zopt_pool);
3359 		kernel_fini();
3360 		umem_free(tmp, strlen(tmp) + 1);
3361 	}
3362 
3363 	ztest_verify_blocks(zopt_pool);
3364 
3365 	if (zopt_verbose >= 1) {
3366 		(void) printf("%d killed, %d completed, %.0f%% kill rate\n",
3367 		    kills, iters - kills, (100.0 * kills) / MAX(1, iters));
3368 	}
3369 
3370 	return (0);
3371 }
3372