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