xref: /illumos-gate/usr/src/cmd/ztest/ztest.c (revision 2caf0dcd2abc26b477e317999994020212790d38)
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 			ASSERT3U(rbt.bt_objset, ==, wbt.bt_objset);
2042 			ASSERT3U(rbt.bt_object, ==, wbt.bt_object);
2043 			ASSERT3U(rbt.bt_offset, ==, wbt.bt_offset);
2044 
2045 			/*
2046 			 * The semantic of dmu_sync() is that we always
2047 			 * push the most recent version of the data,
2048 			 * so in the face of concurrent updates we may
2049 			 * see a newer version of the block.  That's OK.
2050 			 */
2051 			ASSERT3U(rbt.bt_txg, >=, wbt.bt_txg);
2052 			if (rbt.bt_thread == wbt.bt_thread)
2053 				ASSERT3U(rbt.bt_seq, ==, wbt.bt_seq);
2054 			else
2055 				ASSERT3U(rbt.bt_seq, >, wbt.bt_seq);
2056 		}
2057 	}
2058 }
2059 
2060 /*
2061  * Verify that zap_{create,destroy,add,remove,update} work as expected.
2062  */
2063 #define	ZTEST_ZAP_MIN_INTS	1
2064 #define	ZTEST_ZAP_MAX_INTS	4
2065 #define	ZTEST_ZAP_MAX_PROPS	1000
2066 
2067 void
2068 ztest_zap(ztest_args_t *za)
2069 {
2070 	objset_t *os = za->za_os;
2071 	uint64_t object;
2072 	uint64_t txg, last_txg;
2073 	uint64_t value[ZTEST_ZAP_MAX_INTS];
2074 	uint64_t zl_ints, zl_intsize, prop;
2075 	int i, ints;
2076 	int iters = 100;
2077 	dmu_tx_t *tx;
2078 	char propname[100], txgname[100];
2079 	int error;
2080 	char osname[MAXNAMELEN];
2081 	char *hc[2] = { "s.acl.h", ".s.open.h.hyLZlg" };
2082 
2083 	dmu_objset_name(os, osname);
2084 
2085 	/*
2086 	 * Create a new object if necessary, and record it in the directory.
2087 	 */
2088 	VERIFY(0 == dmu_read(os, ZTEST_DIROBJ, za->za_diroff,
2089 	    sizeof (uint64_t), &object));
2090 
2091 	if (object == 0) {
2092 		tx = dmu_tx_create(os);
2093 		dmu_tx_hold_write(tx, ZTEST_DIROBJ, za->za_diroff,
2094 		    sizeof (uint64_t));
2095 		dmu_tx_hold_zap(tx, DMU_NEW_OBJECT, TRUE, NULL);
2096 		error = dmu_tx_assign(tx, TXG_WAIT);
2097 		if (error) {
2098 			ztest_record_enospc("create zap test obj");
2099 			dmu_tx_abort(tx);
2100 			return;
2101 		}
2102 		object = zap_create(os, DMU_OT_ZAP_OTHER, DMU_OT_NONE, 0, tx);
2103 		if (error) {
2104 			fatal(0, "zap_create('%s', %llu) = %d",
2105 			    osname, object, error);
2106 		}
2107 		ASSERT(object != 0);
2108 		dmu_write(os, ZTEST_DIROBJ, za->za_diroff,
2109 		    sizeof (uint64_t), &object, tx);
2110 		/*
2111 		 * Generate a known hash collision, and verify that
2112 		 * we can lookup and remove both entries.
2113 		 */
2114 		for (i = 0; i < 2; i++) {
2115 			value[i] = i;
2116 			error = zap_add(os, object, hc[i], sizeof (uint64_t),
2117 			    1, &value[i], tx);
2118 			ASSERT3U(error, ==, 0);
2119 		}
2120 		for (i = 0; i < 2; i++) {
2121 			error = zap_add(os, object, hc[i], sizeof (uint64_t),
2122 			    1, &value[i], tx);
2123 			ASSERT3U(error, ==, EEXIST);
2124 			error = zap_length(os, object, hc[i],
2125 			    &zl_intsize, &zl_ints);
2126 			ASSERT3U(error, ==, 0);
2127 			ASSERT3U(zl_intsize, ==, sizeof (uint64_t));
2128 			ASSERT3U(zl_ints, ==, 1);
2129 		}
2130 		for (i = 0; i < 2; i++) {
2131 			error = zap_remove(os, object, hc[i], tx);
2132 			ASSERT3U(error, ==, 0);
2133 		}
2134 
2135 		dmu_tx_commit(tx);
2136 	}
2137 
2138 	ints = MAX(ZTEST_ZAP_MIN_INTS, object % ZTEST_ZAP_MAX_INTS);
2139 
2140 	while (--iters >= 0) {
2141 		prop = ztest_random(ZTEST_ZAP_MAX_PROPS);
2142 		(void) sprintf(propname, "prop_%llu", (u_longlong_t)prop);
2143 		(void) sprintf(txgname, "txg_%llu", (u_longlong_t)prop);
2144 		bzero(value, sizeof (value));
2145 		last_txg = 0;
2146 
2147 		/*
2148 		 * If these zap entries already exist, validate their contents.
2149 		 */
2150 		error = zap_length(os, object, txgname, &zl_intsize, &zl_ints);
2151 		if (error == 0) {
2152 			ASSERT3U(zl_intsize, ==, sizeof (uint64_t));
2153 			ASSERT3U(zl_ints, ==, 1);
2154 
2155 			error = zap_lookup(os, object, txgname, zl_intsize,
2156 			    zl_ints, &last_txg);
2157 
2158 			ASSERT3U(error, ==, 0);
2159 
2160 			error = zap_length(os, object, propname, &zl_intsize,
2161 			    &zl_ints);
2162 
2163 			ASSERT3U(error, ==, 0);
2164 			ASSERT3U(zl_intsize, ==, sizeof (uint64_t));
2165 			ASSERT3U(zl_ints, ==, ints);
2166 
2167 			error = zap_lookup(os, object, propname, zl_intsize,
2168 			    zl_ints, value);
2169 
2170 			ASSERT3U(error, ==, 0);
2171 
2172 			for (i = 0; i < ints; i++) {
2173 				ASSERT3U(value[i], ==, last_txg + object + i);
2174 			}
2175 		} else {
2176 			ASSERT3U(error, ==, ENOENT);
2177 		}
2178 
2179 		/*
2180 		 * Atomically update two entries in our zap object.
2181 		 * The first is named txg_%llu, and contains the txg
2182 		 * in which the property was last updated.  The second
2183 		 * is named prop_%llu, and the nth element of its value
2184 		 * should be txg + object + n.
2185 		 */
2186 		tx = dmu_tx_create(os);
2187 		dmu_tx_hold_zap(tx, object, TRUE, NULL);
2188 		error = dmu_tx_assign(tx, TXG_WAIT);
2189 		if (error) {
2190 			ztest_record_enospc("create zap entry");
2191 			dmu_tx_abort(tx);
2192 			return;
2193 		}
2194 		txg = dmu_tx_get_txg(tx);
2195 
2196 		if (last_txg > txg)
2197 			fatal(0, "zap future leak: old %llu new %llu",
2198 			    last_txg, txg);
2199 
2200 		for (i = 0; i < ints; i++)
2201 			value[i] = txg + object + i;
2202 
2203 		error = zap_update(os, object, txgname, sizeof (uint64_t),
2204 		    1, &txg, tx);
2205 		if (error)
2206 			fatal(0, "zap_update('%s', %llu, '%s') = %d",
2207 			    osname, object, txgname, error);
2208 
2209 		error = zap_update(os, object, propname, sizeof (uint64_t),
2210 		    ints, value, tx);
2211 		if (error)
2212 			fatal(0, "zap_update('%s', %llu, '%s') = %d",
2213 			    osname, object, propname, error);
2214 
2215 		dmu_tx_commit(tx);
2216 
2217 		/*
2218 		 * Remove a random pair of entries.
2219 		 */
2220 		prop = ztest_random(ZTEST_ZAP_MAX_PROPS);
2221 		(void) sprintf(propname, "prop_%llu", (u_longlong_t)prop);
2222 		(void) sprintf(txgname, "txg_%llu", (u_longlong_t)prop);
2223 
2224 		error = zap_length(os, object, txgname, &zl_intsize, &zl_ints);
2225 
2226 		if (error == ENOENT)
2227 			continue;
2228 
2229 		ASSERT3U(error, ==, 0);
2230 
2231 		tx = dmu_tx_create(os);
2232 		dmu_tx_hold_zap(tx, object, TRUE, NULL);
2233 		error = dmu_tx_assign(tx, TXG_WAIT);
2234 		if (error) {
2235 			ztest_record_enospc("remove zap entry");
2236 			dmu_tx_abort(tx);
2237 			return;
2238 		}
2239 		error = zap_remove(os, object, txgname, tx);
2240 		if (error)
2241 			fatal(0, "zap_remove('%s', %llu, '%s') = %d",
2242 			    osname, object, txgname, error);
2243 
2244 		error = zap_remove(os, object, propname, tx);
2245 		if (error)
2246 			fatal(0, "zap_remove('%s', %llu, '%s') = %d",
2247 			    osname, object, propname, error);
2248 
2249 		dmu_tx_commit(tx);
2250 	}
2251 
2252 	/*
2253 	 * Once in a while, destroy the object.
2254 	 */
2255 	if (ztest_random(100) != 0)
2256 		return;
2257 
2258 	tx = dmu_tx_create(os);
2259 	dmu_tx_hold_write(tx, ZTEST_DIROBJ, za->za_diroff, sizeof (uint64_t));
2260 	dmu_tx_hold_free(tx, object, 0, DMU_OBJECT_END);
2261 	error = dmu_tx_assign(tx, TXG_WAIT);
2262 	if (error) {
2263 		ztest_record_enospc("destroy zap object");
2264 		dmu_tx_abort(tx);
2265 		return;
2266 	}
2267 	error = zap_destroy(os, object, tx);
2268 	if (error)
2269 		fatal(0, "zap_destroy('%s', %llu) = %d",
2270 		    osname, object, error);
2271 	object = 0;
2272 	dmu_write(os, ZTEST_DIROBJ, za->za_diroff, sizeof (uint64_t),
2273 	    &object, tx);
2274 	dmu_tx_commit(tx);
2275 }
2276 
2277 void
2278 ztest_zap_parallel(ztest_args_t *za)
2279 {
2280 	objset_t *os = za->za_os;
2281 	uint64_t txg, object, count, wsize, wc, zl_wsize, zl_wc;
2282 	int iters = 100;
2283 	dmu_tx_t *tx;
2284 	int i, namelen, error;
2285 	char name[20], string_value[20];
2286 	void *data;
2287 
2288 	while (--iters >= 0) {
2289 		/*
2290 		 * Generate a random name of the form 'xxx.....' where each
2291 		 * x is a random printable character and the dots are dots.
2292 		 * There are 94 such characters, and the name length goes from
2293 		 * 6 to 20, so there are 94^3 * 15 = 12,458,760 possible names.
2294 		 */
2295 		namelen = ztest_random(sizeof (name) - 5) + 5 + 1;
2296 
2297 		for (i = 0; i < 3; i++)
2298 			name[i] = '!' + ztest_random('~' - '!' + 1);
2299 		for (; i < namelen - 1; i++)
2300 			name[i] = '.';
2301 		name[i] = '\0';
2302 
2303 		if (ztest_random(2) == 0)
2304 			object = ZTEST_MICROZAP_OBJ;
2305 		else
2306 			object = ZTEST_FATZAP_OBJ;
2307 
2308 		if ((namelen & 1) || object == ZTEST_MICROZAP_OBJ) {
2309 			wsize = sizeof (txg);
2310 			wc = 1;
2311 			data = &txg;
2312 		} else {
2313 			wsize = 1;
2314 			wc = namelen;
2315 			data = string_value;
2316 		}
2317 
2318 		count = -1ULL;
2319 		VERIFY(zap_count(os, object, &count) == 0);
2320 		ASSERT(count != -1ULL);
2321 
2322 		/*
2323 		 * Select an operation: length, lookup, add, update, remove.
2324 		 */
2325 		i = ztest_random(5);
2326 
2327 		if (i >= 2) {
2328 			tx = dmu_tx_create(os);
2329 			dmu_tx_hold_zap(tx, object, TRUE, NULL);
2330 			error = dmu_tx_assign(tx, TXG_WAIT);
2331 			if (error) {
2332 				ztest_record_enospc("zap parallel");
2333 				dmu_tx_abort(tx);
2334 				return;
2335 			}
2336 			txg = dmu_tx_get_txg(tx);
2337 			bcopy(name, string_value, namelen);
2338 		} else {
2339 			tx = NULL;
2340 			txg = 0;
2341 			bzero(string_value, namelen);
2342 		}
2343 
2344 		switch (i) {
2345 
2346 		case 0:
2347 			error = zap_length(os, object, name, &zl_wsize, &zl_wc);
2348 			if (error == 0) {
2349 				ASSERT3U(wsize, ==, zl_wsize);
2350 				ASSERT3U(wc, ==, zl_wc);
2351 			} else {
2352 				ASSERT3U(error, ==, ENOENT);
2353 			}
2354 			break;
2355 
2356 		case 1:
2357 			error = zap_lookup(os, object, name, wsize, wc, data);
2358 			if (error == 0) {
2359 				if (data == string_value &&
2360 				    bcmp(name, data, namelen) != 0)
2361 					fatal(0, "name '%s' != val '%s' len %d",
2362 					    name, data, namelen);
2363 			} else {
2364 				ASSERT3U(error, ==, ENOENT);
2365 			}
2366 			break;
2367 
2368 		case 2:
2369 			error = zap_add(os, object, name, wsize, wc, data, tx);
2370 			ASSERT(error == 0 || error == EEXIST);
2371 			break;
2372 
2373 		case 3:
2374 			VERIFY(zap_update(os, object, name, wsize, wc,
2375 			    data, tx) == 0);
2376 			break;
2377 
2378 		case 4:
2379 			error = zap_remove(os, object, name, tx);
2380 			ASSERT(error == 0 || error == ENOENT);
2381 			break;
2382 		}
2383 
2384 		if (tx != NULL)
2385 			dmu_tx_commit(tx);
2386 	}
2387 }
2388 
2389 void
2390 ztest_dsl_prop_get_set(ztest_args_t *za)
2391 {
2392 	objset_t *os = za->za_os;
2393 	int i, inherit;
2394 	uint64_t value;
2395 	const char *prop, *valname;
2396 	char setpoint[MAXPATHLEN];
2397 	char osname[MAXNAMELEN];
2398 	int error;
2399 
2400 	(void) rw_rdlock(&ztest_shared->zs_name_lock);
2401 
2402 	dmu_objset_name(os, osname);
2403 
2404 	for (i = 0; i < 2; i++) {
2405 		if (i == 0) {
2406 			prop = "checksum";
2407 			value = ztest_random_checksum();
2408 			inherit = (value == ZIO_CHECKSUM_INHERIT);
2409 		} else {
2410 			prop = "compression";
2411 			value = ztest_random_compress();
2412 			inherit = (value == ZIO_COMPRESS_INHERIT);
2413 		}
2414 
2415 		error = dsl_prop_set(osname, prop, sizeof (value),
2416 		    !inherit, &value);
2417 
2418 		if (error == ENOSPC) {
2419 			ztest_record_enospc("dsl_prop_set");
2420 			break;
2421 		}
2422 
2423 		ASSERT3U(error, ==, 0);
2424 
2425 		VERIFY3U(dsl_prop_get(osname, prop, sizeof (value),
2426 		    1, &value, setpoint), ==, 0);
2427 
2428 		if (i == 0)
2429 			valname = zio_checksum_table[value].ci_name;
2430 		else
2431 			valname = zio_compress_table[value].ci_name;
2432 
2433 		if (zopt_verbose >= 6) {
2434 			(void) printf("%s %s = %s for '%s'\n",
2435 			    osname, prop, valname, setpoint);
2436 		}
2437 	}
2438 
2439 	(void) rw_unlock(&ztest_shared->zs_name_lock);
2440 }
2441 
2442 static void
2443 ztest_error_setup(vdev_t *vd, int mode, int mask, uint64_t arg)
2444 {
2445 	int c;
2446 
2447 	for (c = 0; c < vd->vdev_children; c++)
2448 		ztest_error_setup(vd->vdev_child[c], mode, mask, arg);
2449 
2450 	if (vd->vdev_path != NULL) {
2451 		vd->vdev_fault_mode = mode;
2452 		vd->vdev_fault_mask = mask;
2453 		vd->vdev_fault_arg = arg;
2454 	}
2455 }
2456 
2457 /*
2458  * Inject random faults into the on-disk data.
2459  */
2460 void
2461 ztest_fault_inject(ztest_args_t *za)
2462 {
2463 	int fd;
2464 	uint64_t offset;
2465 	uint64_t leaves = MAX(zopt_mirrors, 1) * zopt_raidz;
2466 	uint64_t bad = 0x1990c0ffeedecade;
2467 	uint64_t top, leaf;
2468 	char path0[MAXPATHLEN];
2469 	char pathrand[MAXPATHLEN];
2470 	size_t fsize;
2471 	spa_t *spa = dmu_objset_spa(za->za_os);
2472 	int bshift = SPA_MAXBLOCKSHIFT + 2;	/* don't scrog all labels */
2473 	int iters = 1000;
2474 	vdev_t *vd0;
2475 	uint64_t guid0 = 0;
2476 
2477 	/*
2478 	 * We can't inject faults when we have no fault tolerance.
2479 	 */
2480 	if (zopt_maxfaults == 0)
2481 		return;
2482 
2483 	ASSERT(leaves >= 2);
2484 
2485 	/*
2486 	 * Pick a random top-level vdev.
2487 	 */
2488 	spa_config_enter(spa, RW_READER, FTAG);
2489 	top = ztest_random(spa->spa_root_vdev->vdev_children);
2490 	spa_config_exit(spa, FTAG);
2491 
2492 	/*
2493 	 * Pick a random leaf.
2494 	 */
2495 	leaf = ztest_random(leaves);
2496 
2497 	/*
2498 	 * Generate paths to the first two leaves in this top-level vdev,
2499 	 * and to the random leaf we selected.  We'll induce transient
2500 	 * I/O errors and random online/offline activity on leaf 0,
2501 	 * and we'll write random garbage to the randomly chosen leaf.
2502 	 */
2503 	(void) snprintf(path0, sizeof (path0),
2504 	    ztest_dev_template, zopt_dir, zopt_pool, top * leaves + 0);
2505 	(void) snprintf(pathrand, sizeof (pathrand),
2506 	    ztest_dev_template, zopt_dir, zopt_pool, top * leaves + leaf);
2507 
2508 	dprintf("damaging %s and %s\n", path0, pathrand);
2509 
2510 	spa_config_enter(spa, RW_READER, FTAG);
2511 
2512 	/*
2513 	 * If we can tolerate two or more faults, make vd0 fail randomly.
2514 	 */
2515 	vd0 = vdev_lookup_by_path(spa->spa_root_vdev, path0);
2516 	if (vd0 != NULL && zopt_maxfaults >= 2) {
2517 		guid0 = vd0->vdev_guid;
2518 		ztest_error_setup(vd0, VDEV_FAULT_COUNT,
2519 		    (1U << ZIO_TYPE_READ) | (1U << ZIO_TYPE_WRITE), 100);
2520 	}
2521 
2522 	spa_config_exit(spa, FTAG);
2523 
2524 	/*
2525 	 * If we can tolerate two or more faults, randomly online/offline vd0.
2526 	 */
2527 	if (zopt_maxfaults >= 2 && guid0 != 0) {
2528 		if (ztest_random(10) < 6)
2529 			(void) vdev_offline(spa, guid0, B_TRUE);
2530 		else
2531 			(void) vdev_online(spa, guid0);
2532 	}
2533 
2534 	/*
2535 	 * We have at least single-fault tolerance, so inject data corruption.
2536 	 */
2537 	fd = open(pathrand, O_RDWR);
2538 
2539 	if (fd == -1)	/* we hit a gap in the device namespace */
2540 		return;
2541 
2542 	fsize = lseek(fd, 0, SEEK_END);
2543 
2544 	while (--iters != 0) {
2545 		offset = ztest_random(fsize / (leaves << bshift)) *
2546 		    (leaves << bshift) + (leaf << bshift) +
2547 		    (ztest_random(1ULL << (bshift - 1)) & -8ULL);
2548 
2549 		if (offset >= fsize)
2550 			continue;
2551 
2552 		if (zopt_verbose >= 6)
2553 			(void) printf("injecting bad word into %s,"
2554 			    " offset 0x%llx\n", pathrand, (u_longlong_t)offset);
2555 
2556 		if (pwrite(fd, &bad, sizeof (bad), offset) != sizeof (bad))
2557 			fatal(1, "can't inject bad word at 0x%llx in %s",
2558 			    offset, pathrand);
2559 	}
2560 
2561 	(void) close(fd);
2562 }
2563 
2564 /*
2565  * Scrub the pool.
2566  */
2567 void
2568 ztest_scrub(ztest_args_t *za)
2569 {
2570 	spa_t *spa = dmu_objset_spa(za->za_os);
2571 
2572 	(void) spa_scrub(spa, POOL_SCRUB_EVERYTHING, B_FALSE);
2573 	(void) poll(NULL, 0, 1000); /* wait a second, then force a restart */
2574 	(void) spa_scrub(spa, POOL_SCRUB_EVERYTHING, B_FALSE);
2575 }
2576 
2577 /*
2578  * Rename the pool to a different name and then rename it back.
2579  */
2580 void
2581 ztest_spa_rename(ztest_args_t *za)
2582 {
2583 	char *oldname, *newname;
2584 	int error;
2585 	spa_t *spa;
2586 
2587 	(void) rw_wrlock(&ztest_shared->zs_name_lock);
2588 
2589 	oldname = za->za_pool;
2590 	newname = umem_alloc(strlen(oldname) + 5, UMEM_NOFAIL);
2591 	(void) strcpy(newname, oldname);
2592 	(void) strcat(newname, "_tmp");
2593 
2594 	/*
2595 	 * Do the rename
2596 	 */
2597 	error = spa_rename(oldname, newname);
2598 	if (error)
2599 		fatal(0, "spa_rename('%s', '%s') = %d", oldname,
2600 		    newname, error);
2601 
2602 	/*
2603 	 * Try to open it under the old name, which shouldn't exist
2604 	 */
2605 	error = spa_open(oldname, &spa, FTAG);
2606 	if (error != ENOENT)
2607 		fatal(0, "spa_open('%s') = %d", oldname, error);
2608 
2609 	/*
2610 	 * Open it under the new name and make sure it's still the same spa_t.
2611 	 */
2612 	error = spa_open(newname, &spa, FTAG);
2613 	if (error != 0)
2614 		fatal(0, "spa_open('%s') = %d", newname, error);
2615 
2616 	ASSERT(spa == dmu_objset_spa(za->za_os));
2617 	spa_close(spa, FTAG);
2618 
2619 	/*
2620 	 * Rename it back to the original
2621 	 */
2622 	error = spa_rename(newname, oldname);
2623 	if (error)
2624 		fatal(0, "spa_rename('%s', '%s') = %d", newname,
2625 		    oldname, error);
2626 
2627 	/*
2628 	 * Make sure it can still be opened
2629 	 */
2630 	error = spa_open(oldname, &spa, FTAG);
2631 	if (error != 0)
2632 		fatal(0, "spa_open('%s') = %d", oldname, error);
2633 
2634 	ASSERT(spa == dmu_objset_spa(za->za_os));
2635 	spa_close(spa, FTAG);
2636 
2637 	umem_free(newname, strlen(newname) + 1);
2638 
2639 	(void) rw_unlock(&ztest_shared->zs_name_lock);
2640 }
2641 
2642 
2643 /*
2644  * Completely obliterate one disk.
2645  */
2646 static void
2647 ztest_obliterate_one_disk(uint64_t vdev)
2648 {
2649 	int fd;
2650 	char dev_name[MAXPATHLEN];
2651 	size_t fsize;
2652 
2653 	if (zopt_maxfaults < 2)
2654 		return;
2655 
2656 	(void) sprintf(dev_name, ztest_dev_template, zopt_dir, zopt_pool, vdev);
2657 
2658 	fd = open(dev_name, O_RDWR);
2659 
2660 	if (fd == -1)
2661 		fatal(1, "can't open %s", dev_name);
2662 
2663 	/*
2664 	 * Determine the size.
2665 	 */
2666 	fsize = lseek(fd, 0, SEEK_END);
2667 	(void) close(fd);
2668 
2669 	/*
2670 	 * Remove it.
2671 	 */
2672 	VERIFY(remove(dev_name) == 0);
2673 
2674 	/*
2675 	 * Create a new one.
2676 	 */
2677 	VERIFY((fd = open(dev_name, O_RDWR | O_CREAT | O_TRUNC, 0666)) >= 0);
2678 	VERIFY(ftruncate(fd, fsize) == 0);
2679 	(void) close(fd);
2680 }
2681 
2682 static void
2683 ztest_replace_one_disk(spa_t *spa, uint64_t vdev)
2684 {
2685 	char dev_name[MAXPATHLEN];
2686 	nvlist_t *file, *root;
2687 	int error;
2688 	uint64_t guid;
2689 	vdev_t *vd;
2690 
2691 	(void) sprintf(dev_name, ztest_dev_template, zopt_dir, zopt_pool, vdev);
2692 
2693 	/*
2694 	 * Build the nvlist describing dev_name.
2695 	 */
2696 	VERIFY(nvlist_alloc(&file, NV_UNIQUE_NAME, 0) == 0);
2697 	VERIFY(nvlist_add_string(file, ZPOOL_CONFIG_TYPE, VDEV_TYPE_FILE) == 0);
2698 	VERIFY(nvlist_add_string(file, ZPOOL_CONFIG_PATH, dev_name) == 0);
2699 
2700 	VERIFY(nvlist_alloc(&root, NV_UNIQUE_NAME, 0) == 0);
2701 	VERIFY(nvlist_add_string(root, ZPOOL_CONFIG_TYPE, VDEV_TYPE_ROOT) == 0);
2702 	VERIFY(nvlist_add_nvlist_array(root, ZPOOL_CONFIG_CHILDREN,
2703 	    &file, 1) == 0);
2704 
2705 	spa_config_enter(spa, RW_READER, FTAG);
2706 	if ((vd = vdev_lookup_by_path(spa->spa_root_vdev, dev_name)) == NULL)
2707 		guid = 0;
2708 	else
2709 		guid = vd->vdev_guid;
2710 	spa_config_exit(spa, FTAG);
2711 	error = spa_vdev_attach(spa, guid, root, B_TRUE);
2712 	if (error != 0 && error != EBUSY && error != ENOTSUP && error != ENODEV)
2713 		fatal(0, "spa_vdev_attach(in-place) = %d", error);
2714 
2715 	nvlist_free(file);
2716 	nvlist_free(root);
2717 }
2718 
2719 static void
2720 ztest_verify_blocks(char *pool)
2721 {
2722 	int status;
2723 	char zdb[MAXPATHLEN + MAXNAMELEN + 20];
2724 	char zbuf[1024];
2725 	char *bin;
2726 	FILE *fp;
2727 
2728 	(void) realpath(getexecname(), zdb);
2729 
2730 	/* zdb lives in /usr/sbin, while ztest lives in /usr/bin */
2731 	bin = strstr(zdb, "/usr/bin/");
2732 	/* LINTED */
2733 	(void) sprintf(bin, "/usr/sbin/zdb -bc%s%s -U -O %s %s",
2734 	    zopt_verbose >= 3 ? "s" : "",
2735 	    zopt_verbose >= 4 ? "v" : "",
2736 	    ztest_random(2) == 0 ? "pre" : "post", pool);
2737 
2738 	if (zopt_verbose >= 5)
2739 		(void) printf("Executing %s\n", strstr(zdb, "zdb "));
2740 
2741 	fp = popen(zdb, "r");
2742 
2743 	while (fgets(zbuf, sizeof (zbuf), fp) != NULL)
2744 		if (zopt_verbose >= 3)
2745 			(void) printf("%s", zbuf);
2746 
2747 	status = pclose(fp);
2748 
2749 	if (status == 0)
2750 		return;
2751 
2752 	ztest_dump_core = 0;
2753 	if (WIFEXITED(status))
2754 		fatal(0, "'%s' exit code %d", zdb, WEXITSTATUS(status));
2755 	else
2756 		fatal(0, "'%s' died with signal %d", zdb, WTERMSIG(status));
2757 }
2758 
2759 static void
2760 ztest_walk_pool_directory(char *header)
2761 {
2762 	spa_t *spa = NULL;
2763 
2764 	if (zopt_verbose >= 6)
2765 		(void) printf("%s\n", header);
2766 
2767 	mutex_enter(&spa_namespace_lock);
2768 	while ((spa = spa_next(spa)) != NULL)
2769 		if (zopt_verbose >= 6)
2770 			(void) printf("\t%s\n", spa_name(spa));
2771 	mutex_exit(&spa_namespace_lock);
2772 }
2773 
2774 static void
2775 ztest_spa_import_export(char *oldname, char *newname)
2776 {
2777 	nvlist_t *config;
2778 	uint64_t pool_guid;
2779 	spa_t *spa;
2780 	int error;
2781 
2782 	if (zopt_verbose >= 4) {
2783 		(void) printf("import/export: old = %s, new = %s\n",
2784 		    oldname, newname);
2785 	}
2786 
2787 	/*
2788 	 * Clean up from previous runs.
2789 	 */
2790 	(void) spa_destroy(newname);
2791 
2792 	/*
2793 	 * Get the pool's configuration and guid.
2794 	 */
2795 	error = spa_open(oldname, &spa, FTAG);
2796 	if (error)
2797 		fatal(0, "spa_open('%s') = %d", oldname, error);
2798 
2799 	ASSERT(spa->spa_config != NULL);
2800 
2801 	VERIFY(nvlist_dup(spa->spa_config, &config, 0) == 0);
2802 	pool_guid = spa_guid(spa);
2803 	spa_close(spa, FTAG);
2804 
2805 	ztest_walk_pool_directory("pools before export");
2806 
2807 	/*
2808 	 * Export it.
2809 	 */
2810 	error = spa_export(oldname);
2811 	if (error)
2812 		fatal(0, "spa_export('%s') = %d", oldname, error);
2813 
2814 	ztest_walk_pool_directory("pools after export");
2815 
2816 	/*
2817 	 * Import it under the new name.
2818 	 */
2819 	error = spa_import(newname, config, NULL);
2820 	if (error)
2821 		fatal(0, "spa_import('%s') = %d", newname, error);
2822 
2823 	ztest_walk_pool_directory("pools after import");
2824 
2825 	/*
2826 	 * Try to import it again -- should fail with EEXIST.
2827 	 */
2828 	error = spa_import(newname, config, NULL);
2829 	if (error != EEXIST)
2830 		fatal(0, "spa_import('%s') twice", newname);
2831 
2832 	/*
2833 	 * Try to import it under a different name -- should fail with EEXIST.
2834 	 */
2835 	error = spa_import(oldname, config, NULL);
2836 	if (error != EEXIST)
2837 		fatal(0, "spa_import('%s') under multiple names", newname);
2838 
2839 	/*
2840 	 * Verify that the pool is no longer visible under the old name.
2841 	 */
2842 	error = spa_open(oldname, &spa, FTAG);
2843 	if (error != ENOENT)
2844 		fatal(0, "spa_open('%s') = %d", newname, error);
2845 
2846 	/*
2847 	 * Verify that we can open and close the pool using the new name.
2848 	 */
2849 	error = spa_open(newname, &spa, FTAG);
2850 	if (error)
2851 		fatal(0, "spa_open('%s') = %d", newname, error);
2852 	ASSERT(pool_guid == spa_guid(spa));
2853 	spa_close(spa, FTAG);
2854 
2855 	nvlist_free(config);
2856 }
2857 
2858 static void *
2859 ztest_thread(void *arg)
2860 {
2861 	ztest_args_t *za = arg;
2862 	ztest_shared_t *zs = ztest_shared;
2863 	hrtime_t now, functime;
2864 	ztest_info_t *zi;
2865 	int f;
2866 
2867 	while ((now = gethrtime()) < za->za_stop) {
2868 		/*
2869 		 * See if it's time to force a crash.
2870 		 */
2871 		if (now > za->za_kill) {
2872 			zs->zs_alloc = spa_get_alloc(dmu_objset_spa(za->za_os));
2873 			zs->zs_space = spa_get_space(dmu_objset_spa(za->za_os));
2874 			(void) kill(getpid(), SIGKILL);
2875 		}
2876 
2877 		/*
2878 		 * Pick a random function.
2879 		 */
2880 		f = ztest_random(ZTEST_FUNCS);
2881 		zi = &zs->zs_info[f];
2882 
2883 		/*
2884 		 * Decide whether to call it, based on the requested frequency.
2885 		 */
2886 		if (zi->zi_call_target == 0 ||
2887 		    (double)zi->zi_call_total / zi->zi_call_target >
2888 		    (double)(now - zs->zs_start_time) / (zopt_time * NANOSEC))
2889 			continue;
2890 
2891 		atomic_add_64(&zi->zi_calls, 1);
2892 		atomic_add_64(&zi->zi_call_total, 1);
2893 
2894 		za->za_diroff = (za->za_instance * ZTEST_FUNCS + f) *
2895 		    ZTEST_DIRSIZE;
2896 		za->za_diroff_shared = (1ULL << 63);
2897 
2898 		ztest_dmu_write_parallel(za);
2899 
2900 		zi->zi_func(za);
2901 
2902 		functime = gethrtime() - now;
2903 
2904 		atomic_add_64(&zi->zi_call_time, functime);
2905 
2906 		if (zopt_verbose >= 4) {
2907 			Dl_info dli;
2908 			(void) dladdr((void *)zi->zi_func, &dli);
2909 			(void) printf("%6.2f sec in %s\n",
2910 			    (double)functime / NANOSEC, dli.dli_sname);
2911 		}
2912 
2913 		/*
2914 		 * If we're getting ENOSPC with some regularity, stop.
2915 		 */
2916 		if (zs->zs_enospc_count > 10)
2917 			break;
2918 	}
2919 
2920 	return (NULL);
2921 }
2922 
2923 /*
2924  * Kick off threads to run tests on all datasets in parallel.
2925  */
2926 static void
2927 ztest_run(char *pool)
2928 {
2929 	int t, d, error;
2930 	ztest_shared_t *zs = ztest_shared;
2931 	ztest_args_t *za;
2932 	spa_t *spa;
2933 	char name[100];
2934 
2935 	(void) _mutex_init(&zs->zs_vdev_lock, USYNC_THREAD, NULL);
2936 	(void) rwlock_init(&zs->zs_name_lock, USYNC_THREAD, NULL);
2937 
2938 	for (t = 0; t < ZTEST_SYNC_LOCKS; t++)
2939 		(void) _mutex_init(&zs->zs_sync_lock[t], USYNC_THREAD, NULL);
2940 
2941 	/*
2942 	 * Destroy one disk before we even start.
2943 	 * It's mirrored, so everything should work just fine.
2944 	 * This makes us exercise fault handling very early in spa_load().
2945 	 */
2946 	ztest_obliterate_one_disk(0);
2947 
2948 	/*
2949 	 * Verify that the sum of the sizes of all blocks in the pool
2950 	 * equals the SPA's allocated space total.
2951 	 */
2952 	ztest_verify_blocks(pool);
2953 
2954 	/*
2955 	 * Kick off a replacement of the disk we just obliterated.
2956 	 */
2957 	kernel_init(FREAD | FWRITE);
2958 	error = spa_open(pool, &spa, FTAG);
2959 	if (error)
2960 		fatal(0, "spa_open(%s) = %d", pool, error);
2961 	ztest_replace_one_disk(spa, 0);
2962 	if (zopt_verbose >= 5)
2963 		show_pool_stats(spa);
2964 	spa_close(spa, FTAG);
2965 	kernel_fini();
2966 
2967 	kernel_init(FREAD | FWRITE);
2968 
2969 	/*
2970 	 * Verify that we can export the pool and reimport it under a
2971 	 * different name.
2972 	 */
2973 	(void) snprintf(name, 100, "%s_import", pool);
2974 	ztest_spa_import_export(pool, name);
2975 	ztest_spa_import_export(name, pool);
2976 
2977 	/*
2978 	 * Verify that we can loop over all pools.
2979 	 */
2980 	mutex_enter(&spa_namespace_lock);
2981 	for (spa = spa_next(NULL); spa != NULL; spa = spa_next(spa)) {
2982 		if (zopt_verbose > 3) {
2983 			(void) printf("spa_next: found %s\n", spa_name(spa));
2984 		}
2985 	}
2986 	mutex_exit(&spa_namespace_lock);
2987 
2988 	/*
2989 	 * Open our pool.
2990 	 */
2991 	error = spa_open(pool, &spa, FTAG);
2992 	if (error)
2993 		fatal(0, "spa_open() = %d", error);
2994 
2995 	/*
2996 	 * Verify that we can safely inquire about about any object,
2997 	 * whether it's allocated or not.  To make it interesting,
2998 	 * we probe a 5-wide window around each power of two.
2999 	 * This hits all edge cases, including zero and the max.
3000 	 */
3001 	for (t = 0; t < 64; t++) {
3002 		for (d = -5; d <= 5; d++) {
3003 			error = dmu_object_info(spa->spa_meta_objset,
3004 			    (1ULL << t) + d, NULL);
3005 			ASSERT(error == 0 || error == ENOENT ||
3006 			    error == EINVAL);
3007 		}
3008 	}
3009 
3010 	/*
3011 	 * Now kick off all the tests that run in parallel.
3012 	 */
3013 	zs->zs_enospc_count = 0;
3014 
3015 	za = umem_zalloc(zopt_threads * sizeof (ztest_args_t), UMEM_NOFAIL);
3016 
3017 	if (zopt_verbose >= 4)
3018 		(void) printf("starting main threads...\n");
3019 
3020 	za[0].za_start = gethrtime();
3021 	za[0].za_stop = za[0].za_start + zopt_passtime * NANOSEC;
3022 	za[0].za_stop = MIN(za[0].za_stop, zs->zs_stop_time);
3023 	za[0].za_kill = za[0].za_stop;
3024 	if (ztest_random(100) < zopt_killrate)
3025 		za[0].za_kill -= ztest_random(zopt_passtime * NANOSEC);
3026 
3027 	for (t = 0; t < zopt_threads; t++) {
3028 		d = t % zopt_dirs;
3029 		if (t < zopt_dirs) {
3030 			ztest_replay_t zr;
3031 			(void) rw_rdlock(&ztest_shared->zs_name_lock);
3032 			(void) snprintf(name, 100, "%s/%s_%d", pool, pool, d);
3033 			error = dmu_objset_create(name, DMU_OST_OTHER, NULL,
3034 			    ztest_create_cb, NULL);
3035 			if (error != 0 && error != EEXIST) {
3036 				if (error == ENOSPC) {
3037 					zs->zs_enospc_count++;
3038 					(void) rw_unlock(
3039 					    &ztest_shared->zs_name_lock);
3040 					break;
3041 				}
3042 				fatal(0, "dmu_objset_create(%s) = %d",
3043 				    name, error);
3044 			}
3045 			error = dmu_objset_open(name, DMU_OST_OTHER,
3046 			    DS_MODE_STANDARD, &za[d].za_os);
3047 			if (error)
3048 				fatal(0, "dmu_objset_open('%s') = %d",
3049 				    name, error);
3050 			(void) rw_unlock(&ztest_shared->zs_name_lock);
3051 			zr.zr_os = za[d].za_os;
3052 			zil_replay(zr.zr_os, &zr, &zr.zr_assign,
3053 			    ztest_replay_vector, NULL);
3054 			za[d].za_zilog = zil_open(za[d].za_os, NULL);
3055 		}
3056 		za[t].za_pool = spa_strdup(pool);
3057 		za[t].za_os = za[d].za_os;
3058 		za[t].za_zilog = za[d].za_zilog;
3059 		za[t].za_instance = t;
3060 		za[t].za_random = ztest_random(-1ULL);
3061 		za[t].za_start = za[0].za_start;
3062 		za[t].za_stop = za[0].za_stop;
3063 		za[t].za_kill = za[0].za_kill;
3064 
3065 		error = thr_create(0, 0, ztest_thread, &za[t], THR_BOUND,
3066 		    &za[t].za_thread);
3067 		if (error)
3068 			fatal(0, "can't create thread %d: error %d",
3069 			    t, error);
3070 	}
3071 
3072 	while (--t >= 0) {
3073 		error = thr_join(za[t].za_thread, NULL, NULL);
3074 		if (error)
3075 			fatal(0, "thr_join(%d) = %d", t, error);
3076 		if (za[t].za_th)
3077 			traverse_fini(za[t].za_th);
3078 		if (t < zopt_dirs) {
3079 			txg_wait_synced(spa_get_dsl(spa), 0);
3080 			zil_close(za[t].za_zilog);
3081 			dmu_objset_close(za[t].za_os);
3082 		}
3083 		spa_strfree(za[t].za_pool);
3084 	}
3085 
3086 	umem_free(za, zopt_threads * sizeof (ztest_args_t));
3087 
3088 	if (zopt_verbose >= 3)
3089 		show_pool_stats(spa);
3090 
3091 	txg_wait_synced(spa_get_dsl(spa), 0);
3092 
3093 	zs->zs_alloc = spa_get_alloc(spa);
3094 	zs->zs_space = spa_get_space(spa);
3095 
3096 	/*
3097 	 * Did we have out-of-space errors?  If so, destroy a random objset.
3098 	 */
3099 	if (zs->zs_enospc_count != 0) {
3100 		(void) rw_rdlock(&ztest_shared->zs_name_lock);
3101 		(void) snprintf(name, 100, "%s/%s_%d", pool, pool,
3102 		    (int)ztest_random(zopt_dirs));
3103 		if (zopt_verbose >= 3)
3104 			(void) printf("Destroying %s to free up space\n", name);
3105 		dmu_objset_find(name, ztest_destroy_cb, NULL,
3106 		    DS_FIND_SNAPSHOTS);
3107 		(void) rw_unlock(&ztest_shared->zs_name_lock);
3108 	}
3109 
3110 	txg_wait_synced(spa_get_dsl(spa), 0);
3111 
3112 	/*
3113 	 * Right before closing the pool, kick off a bunch of async I/O;
3114 	 * spa_close() should wait for it to complete.
3115 	 */
3116 	for (t = 1; t < 50; t++)
3117 		dmu_prefetch(spa->spa_meta_objset, t, 0, 1 << 15);
3118 
3119 	spa_close(spa, FTAG);
3120 
3121 	kernel_fini();
3122 }
3123 
3124 void
3125 print_time(hrtime_t t, char *timebuf)
3126 {
3127 	hrtime_t s = t / NANOSEC;
3128 	hrtime_t m = s / 60;
3129 	hrtime_t h = m / 60;
3130 	hrtime_t d = h / 24;
3131 
3132 	s -= m * 60;
3133 	m -= h * 60;
3134 	h -= d * 24;
3135 
3136 	timebuf[0] = '\0';
3137 
3138 	if (d)
3139 		(void) sprintf(timebuf,
3140 		    "%llud%02lluh%02llum%02llus", d, h, m, s);
3141 	else if (h)
3142 		(void) sprintf(timebuf, "%lluh%02llum%02llus", h, m, s);
3143 	else if (m)
3144 		(void) sprintf(timebuf, "%llum%02llus", m, s);
3145 	else
3146 		(void) sprintf(timebuf, "%llus", s);
3147 }
3148 
3149 /*
3150  * Create a storage pool with the given name and initial vdev size.
3151  * Then create the specified number of datasets in the pool.
3152  */
3153 static void
3154 ztest_init(char *pool)
3155 {
3156 	spa_t *spa;
3157 	int error;
3158 	nvlist_t *nvroot;
3159 
3160 	kernel_init(FREAD | FWRITE);
3161 
3162 	/*
3163 	 * Create the storage pool.
3164 	 */
3165 	(void) spa_destroy(pool);
3166 	ztest_shared->zs_vdev_primaries = 0;
3167 	nvroot = make_vdev_root(zopt_vdev_size, zopt_raidz, zopt_mirrors, 1);
3168 	error = spa_create(pool, nvroot, NULL);
3169 	nvlist_free(nvroot);
3170 
3171 	if (error)
3172 		fatal(0, "spa_create() = %d", error);
3173 	error = spa_open(pool, &spa, FTAG);
3174 	if (error)
3175 		fatal(0, "spa_open() = %d", error);
3176 
3177 	if (zopt_verbose >= 3)
3178 		show_pool_stats(spa);
3179 
3180 	spa_close(spa, FTAG);
3181 
3182 	kernel_fini();
3183 }
3184 
3185 int
3186 main(int argc, char **argv)
3187 {
3188 	int kills = 0;
3189 	int iters = 0;
3190 	int i, f;
3191 	ztest_shared_t *zs;
3192 	ztest_info_t *zi;
3193 	char timebuf[100];
3194 	char numbuf[6];
3195 
3196 	(void) setvbuf(stdout, NULL, _IOLBF, 0);
3197 
3198 	/* Override location of zpool.cache */
3199 	spa_config_dir = "/tmp";
3200 
3201 	ztest_random_fd = open("/dev/urandom", O_RDONLY);
3202 
3203 	process_options(argc, argv);
3204 
3205 	argc -= optind;
3206 	argv += optind;
3207 
3208 	dprintf_setup(&argc, argv);
3209 
3210 	/*
3211 	 * Blow away any existing copy of zpool.cache
3212 	 */
3213 	if (zopt_init != 0)
3214 		(void) remove("/tmp/zpool.cache");
3215 
3216 	zs = ztest_shared = (void *)mmap(0,
3217 	    P2ROUNDUP(sizeof (ztest_shared_t), getpagesize()),
3218 	    PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANON, -1, 0);
3219 
3220 	if (zopt_verbose >= 1) {
3221 		(void) printf("%llu vdevs, %d datasets, %d threads,"
3222 		    " %llu seconds...\n",
3223 		    (u_longlong_t)zopt_vdevs, zopt_dirs, zopt_threads,
3224 		    (u_longlong_t)zopt_time);
3225 	}
3226 
3227 	/*
3228 	 * Create and initialize our storage pool.
3229 	 */
3230 	for (i = 1; i <= zopt_init; i++) {
3231 		bzero(zs, sizeof (ztest_shared_t));
3232 		if (zopt_verbose >= 3 && zopt_init != 1)
3233 			(void) printf("ztest_init(), pass %d\n", i);
3234 		ztest_init(zopt_pool);
3235 	}
3236 
3237 	/*
3238 	 * Initialize the call targets for each function.
3239 	 */
3240 	for (f = 0; f < ZTEST_FUNCS; f++) {
3241 		zi = &zs->zs_info[f];
3242 
3243 		*zi = ztest_info[f];
3244 
3245 		if (*zi->zi_interval == 0)
3246 			zi->zi_call_target = UINT64_MAX;
3247 		else
3248 			zi->zi_call_target = zopt_time / *zi->zi_interval;
3249 	}
3250 
3251 	zs->zs_start_time = gethrtime();
3252 	zs->zs_stop_time = zs->zs_start_time + zopt_time * NANOSEC;
3253 
3254 	/*
3255 	 * Run the tests in a loop.  These tests include fault injection
3256 	 * to verify that self-healing data works, and forced crashes
3257 	 * to verify that we never lose on-disk consistency.
3258 	 */
3259 	while (gethrtime() < zs->zs_stop_time) {
3260 		int status;
3261 		pid_t pid;
3262 		char *tmp;
3263 
3264 		/*
3265 		 * Initialize the workload counters for each function.
3266 		 */
3267 		for (f = 0; f < ZTEST_FUNCS; f++) {
3268 			zi = &zs->zs_info[f];
3269 			zi->zi_calls = 0;
3270 			zi->zi_call_time = 0;
3271 		}
3272 
3273 		pid = fork();
3274 
3275 		if (pid == -1)
3276 			fatal(1, "fork failed");
3277 
3278 		if (pid == 0) {	/* child */
3279 			struct rlimit rl = { 1024, 1024 };
3280 			(void) setrlimit(RLIMIT_NOFILE, &rl);
3281 			ztest_run(zopt_pool);
3282 			exit(0);
3283 		}
3284 
3285 		while (waitpid(pid, &status, WEXITED) != pid)
3286 			continue;
3287 
3288 		if (WIFEXITED(status)) {
3289 			if (WEXITSTATUS(status) != 0) {
3290 				(void) fprintf(stderr,
3291 				    "child exited with code %d\n",
3292 				    WEXITSTATUS(status));
3293 				exit(2);
3294 			}
3295 		} else {
3296 			if (WTERMSIG(status) != SIGKILL) {
3297 				(void) fprintf(stderr,
3298 				    "child died with signal %d\n",
3299 				    WTERMSIG(status));
3300 				exit(3);
3301 			}
3302 			kills++;
3303 		}
3304 
3305 		iters++;
3306 
3307 		if (zopt_verbose >= 1) {
3308 			hrtime_t now = gethrtime();
3309 
3310 			now = MIN(now, zs->zs_stop_time);
3311 			print_time(zs->zs_stop_time - now, timebuf);
3312 			nicenum(zs->zs_space, numbuf);
3313 
3314 			(void) printf("Pass %3d, %8s, %3llu ENOSPC, "
3315 			    "%4.1f%% of %5s used, %3.0f%% done, %8s to go\n",
3316 			    iters,
3317 			    WIFEXITED(status) ? "Complete" : "SIGKILL",
3318 			    (u_longlong_t)zs->zs_enospc_count,
3319 			    100.0 * zs->zs_alloc / zs->zs_space,
3320 			    numbuf,
3321 			    100.0 * (now - zs->zs_start_time) /
3322 			    (zopt_time * NANOSEC), timebuf);
3323 		}
3324 
3325 		if (zopt_verbose >= 2) {
3326 			(void) printf("\nWorkload summary:\n\n");
3327 			(void) printf("%7s %9s   %s\n",
3328 			    "Calls", "Time", "Function");
3329 			(void) printf("%7s %9s   %s\n",
3330 			    "-----", "----", "--------");
3331 			for (f = 0; f < ZTEST_FUNCS; f++) {
3332 				Dl_info dli;
3333 
3334 				zi = &zs->zs_info[f];
3335 				print_time(zi->zi_call_time, timebuf);
3336 				(void) dladdr((void *)zi->zi_func, &dli);
3337 				(void) printf("%7llu %9s   %s\n",
3338 				    (u_longlong_t)zi->zi_calls, timebuf,
3339 				    dli.dli_sname);
3340 			}
3341 			(void) printf("\n");
3342 		}
3343 
3344 		/*
3345 		 * It's possible that we killed a child during a rename test, in
3346 		 * which case we'll have a 'ztest_tmp' pool lying around instead
3347 		 * of 'ztest'.  Do a blind rename in case this happened.
3348 		 */
3349 		tmp = umem_alloc(strlen(zopt_pool) + 5, UMEM_NOFAIL);
3350 		(void) strcpy(tmp, zopt_pool);
3351 		(void) strcat(tmp, "_tmp");
3352 		kernel_init(FREAD | FWRITE);
3353 		(void) spa_rename(tmp, zopt_pool);
3354 		kernel_fini();
3355 		umem_free(tmp, strlen(tmp) + 1);
3356 	}
3357 
3358 	ztest_verify_blocks(zopt_pool);
3359 
3360 	if (zopt_verbose >= 1) {
3361 		(void) printf("%d killed, %d completed, %.0f%% kill rate\n",
3362 		    kills, iters - kills, (100.0 * kills) / MAX(1, iters));
3363 	}
3364 
3365 	return (0);
3366 }
3367