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