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