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