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