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