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