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