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