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