xref: /titanic_51/usr/src/cmd/ztest/ztest.c (revision c7e764a768ca0fd0b1061d79d1d33548a9ad15b4)
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), 2);
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, B_FALSE, 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_rsize(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_rsize(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  * Verify that dynamic LUN growth works as expected.
1148  */
1149 void
1150 ztest_vdev_LUN_growth(ztest_args_t *za)
1151 {
1152 	spa_t *spa = za->za_spa;
1153 	char dev_name[MAXPATHLEN];
1154 	uint64_t leaves = MAX(zopt_mirrors, 1) * zopt_raidz;
1155 	uint64_t vdev;
1156 	size_t fsize;
1157 	int fd;
1158 
1159 	(void) mutex_lock(&ztest_shared->zs_vdev_lock);
1160 
1161 	/*
1162 	 * Pick a random leaf vdev.
1163 	 */
1164 	spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
1165 	vdev = ztest_random(spa->spa_root_vdev->vdev_children * leaves);
1166 	spa_config_exit(spa, SCL_VDEV, FTAG);
1167 
1168 	(void) sprintf(dev_name, ztest_dev_template, zopt_dir, zopt_pool, vdev);
1169 
1170 	if ((fd = open(dev_name, O_RDWR)) != -1) {
1171 		/*
1172 		 * Determine the size.
1173 		 */
1174 		fsize = lseek(fd, 0, SEEK_END);
1175 
1176 		/*
1177 		 * If it's less than 2x the original size, grow by around 3%.
1178 		 */
1179 		if (fsize < 2 * zopt_vdev_size) {
1180 			size_t newsize = fsize + ztest_random(fsize / 32);
1181 			(void) ftruncate(fd, newsize);
1182 			if (zopt_verbose >= 6) {
1183 				(void) printf("%s grew from %lu to %lu bytes\n",
1184 				    dev_name, (ulong_t)fsize, (ulong_t)newsize);
1185 			}
1186 		}
1187 		(void) close(fd);
1188 	}
1189 
1190 	(void) mutex_unlock(&ztest_shared->zs_vdev_lock);
1191 }
1192 
1193 /* ARGSUSED */
1194 static void
1195 ztest_create_cb(objset_t *os, void *arg, cred_t *cr, dmu_tx_t *tx)
1196 {
1197 	/*
1198 	 * Create the directory object.
1199 	 */
1200 	VERIFY(dmu_object_claim(os, ZTEST_DIROBJ,
1201 	    DMU_OT_UINT64_OTHER, ZTEST_DIROBJ_BLOCKSIZE,
1202 	    DMU_OT_UINT64_OTHER, 5 * sizeof (ztest_block_tag_t), tx) == 0);
1203 
1204 	VERIFY(zap_create_claim(os, ZTEST_MICROZAP_OBJ,
1205 	    DMU_OT_ZAP_OTHER, DMU_OT_NONE, 0, tx) == 0);
1206 
1207 	VERIFY(zap_create_claim(os, ZTEST_FATZAP_OBJ,
1208 	    DMU_OT_ZAP_OTHER, DMU_OT_NONE, 0, tx) == 0);
1209 }
1210 
1211 static int
1212 ztest_destroy_cb(char *name, void *arg)
1213 {
1214 	ztest_args_t *za = arg;
1215 	objset_t *os;
1216 	dmu_object_info_t *doi = &za->za_doi;
1217 	int error;
1218 
1219 	/*
1220 	 * Verify that the dataset contains a directory object.
1221 	 */
1222 	error = dmu_objset_open(name, DMU_OST_OTHER,
1223 	    DS_MODE_USER | DS_MODE_READONLY, &os);
1224 	ASSERT3U(error, ==, 0);
1225 	error = dmu_object_info(os, ZTEST_DIROBJ, doi);
1226 	if (error != ENOENT) {
1227 		/* We could have crashed in the middle of destroying it */
1228 		ASSERT3U(error, ==, 0);
1229 		ASSERT3U(doi->doi_type, ==, DMU_OT_UINT64_OTHER);
1230 		ASSERT3S(doi->doi_physical_blks, >=, 0);
1231 	}
1232 	dmu_objset_close(os);
1233 
1234 	/*
1235 	 * Destroy the dataset.
1236 	 */
1237 	error = dmu_objset_destroy(name);
1238 	if (error) {
1239 		(void) dmu_objset_open(name, DMU_OST_OTHER,
1240 		    DS_MODE_USER | DS_MODE_READONLY, &os);
1241 		fatal(0, "dmu_objset_destroy(os=%p) = %d\n", &os, error);
1242 	}
1243 	return (0);
1244 }
1245 
1246 /*
1247  * Verify that dmu_objset_{create,destroy,open,close} work as expected.
1248  */
1249 static uint64_t
1250 ztest_log_create(zilog_t *zilog, dmu_tx_t *tx, uint64_t object, int mode)
1251 {
1252 	itx_t *itx;
1253 	lr_create_t *lr;
1254 	size_t namesize;
1255 	char name[24];
1256 
1257 	(void) sprintf(name, "ZOBJ_%llu", (u_longlong_t)object);
1258 	namesize = strlen(name) + 1;
1259 
1260 	itx = zil_itx_create(TX_CREATE, sizeof (*lr) + namesize +
1261 	    ztest_random(ZIL_MAX_BLKSZ));
1262 	lr = (lr_create_t *)&itx->itx_lr;
1263 	bzero(lr + 1, lr->lr_common.lrc_reclen - sizeof (*lr));
1264 	lr->lr_doid = object;
1265 	lr->lr_foid = 0;
1266 	lr->lr_mode = mode;
1267 	lr->lr_uid = 0;
1268 	lr->lr_gid = 0;
1269 	lr->lr_gen = dmu_tx_get_txg(tx);
1270 	lr->lr_crtime[0] = time(NULL);
1271 	lr->lr_crtime[1] = 0;
1272 	lr->lr_rdev = 0;
1273 	bcopy(name, (char *)(lr + 1), namesize);
1274 
1275 	return (zil_itx_assign(zilog, itx, tx));
1276 }
1277 
1278 void
1279 ztest_dmu_objset_create_destroy(ztest_args_t *za)
1280 {
1281 	int error;
1282 	objset_t *os, *os2;
1283 	char name[100];
1284 	int basemode, expected_error;
1285 	zilog_t *zilog;
1286 	uint64_t seq;
1287 	uint64_t objects;
1288 
1289 	(void) rw_rdlock(&ztest_shared->zs_name_lock);
1290 	(void) snprintf(name, 100, "%s/%s_temp_%llu", za->za_pool, za->za_pool,
1291 	    (u_longlong_t)za->za_instance);
1292 
1293 	basemode = DS_MODE_TYPE(za->za_instance);
1294 	if (basemode != DS_MODE_USER && basemode != DS_MODE_OWNER)
1295 		basemode = DS_MODE_USER;
1296 
1297 	/*
1298 	 * If this dataset exists from a previous run, process its replay log
1299 	 * half of the time.  If we don't replay it, then dmu_objset_destroy()
1300 	 * (invoked from ztest_destroy_cb() below) should just throw it away.
1301 	 */
1302 	if (ztest_random(2) == 0 &&
1303 	    dmu_objset_open(name, DMU_OST_OTHER, DS_MODE_OWNER, &os) == 0) {
1304 		zil_replay(os, os, ztest_replay_vector);
1305 		dmu_objset_close(os);
1306 	}
1307 
1308 	/*
1309 	 * There may be an old instance of the dataset we're about to
1310 	 * create lying around from a previous run.  If so, destroy it
1311 	 * and all of its snapshots.
1312 	 */
1313 	(void) dmu_objset_find(name, ztest_destroy_cb, za,
1314 	    DS_FIND_CHILDREN | DS_FIND_SNAPSHOTS);
1315 
1316 	/*
1317 	 * Verify that the destroyed dataset is no longer in the namespace.
1318 	 */
1319 	error = dmu_objset_open(name, DMU_OST_OTHER, basemode, &os);
1320 	if (error != ENOENT)
1321 		fatal(1, "dmu_objset_open(%s) found destroyed dataset %p",
1322 		    name, os);
1323 
1324 	/*
1325 	 * Verify that we can create a new dataset.
1326 	 */
1327 	error = dmu_objset_create(name, DMU_OST_OTHER, NULL, 0,
1328 	    ztest_create_cb, NULL);
1329 	if (error) {
1330 		if (error == ENOSPC) {
1331 			ztest_record_enospc("dmu_objset_create");
1332 			(void) rw_unlock(&ztest_shared->zs_name_lock);
1333 			return;
1334 		}
1335 		fatal(0, "dmu_objset_create(%s) = %d", name, error);
1336 	}
1337 
1338 	error = dmu_objset_open(name, DMU_OST_OTHER, basemode, &os);
1339 	if (error) {
1340 		fatal(0, "dmu_objset_open(%s) = %d", name, error);
1341 	}
1342 
1343 	/*
1344 	 * Open the intent log for it.
1345 	 */
1346 	zilog = zil_open(os, NULL);
1347 
1348 	/*
1349 	 * Put a random number of objects in there.
1350 	 */
1351 	objects = ztest_random(20);
1352 	seq = 0;
1353 	while (objects-- != 0) {
1354 		uint64_t object;
1355 		dmu_tx_t *tx = dmu_tx_create(os);
1356 		dmu_tx_hold_write(tx, DMU_NEW_OBJECT, 0, sizeof (name));
1357 		error = dmu_tx_assign(tx, TXG_WAIT);
1358 		if (error) {
1359 			dmu_tx_abort(tx);
1360 		} else {
1361 			object = dmu_object_alloc(os, DMU_OT_UINT64_OTHER, 0,
1362 			    DMU_OT_NONE, 0, tx);
1363 			ztest_set_random_blocksize(os, object, tx);
1364 			seq = ztest_log_create(zilog, tx, object,
1365 			    DMU_OT_UINT64_OTHER);
1366 			dmu_write(os, object, 0, sizeof (name), name, tx);
1367 			dmu_tx_commit(tx);
1368 		}
1369 		if (ztest_random(5) == 0) {
1370 			zil_commit(zilog, seq, object);
1371 		}
1372 		if (ztest_random(100) == 0) {
1373 			error = zil_suspend(zilog);
1374 			if (error == 0) {
1375 				zil_resume(zilog);
1376 			}
1377 		}
1378 	}
1379 
1380 	/*
1381 	 * Verify that we cannot create an existing dataset.
1382 	 */
1383 	error = dmu_objset_create(name, DMU_OST_OTHER, NULL, 0, NULL, NULL);
1384 	if (error != EEXIST)
1385 		fatal(0, "created existing dataset, error = %d", error);
1386 
1387 	/*
1388 	 * Verify that multiple dataset holds are allowed, but only when
1389 	 * the new access mode is compatible with the base mode.
1390 	 */
1391 	if (basemode == DS_MODE_OWNER) {
1392 		error = dmu_objset_open(name, DMU_OST_OTHER, DS_MODE_USER,
1393 		    &os2);
1394 		if (error)
1395 			fatal(0, "dmu_objset_open('%s') = %d", name, error);
1396 		else
1397 			dmu_objset_close(os2);
1398 	}
1399 	error = dmu_objset_open(name, DMU_OST_OTHER, DS_MODE_OWNER, &os2);
1400 	expected_error = (basemode == DS_MODE_OWNER) ? EBUSY : 0;
1401 	if (error != expected_error)
1402 		fatal(0, "dmu_objset_open('%s') = %d, expected %d",
1403 		    name, error, expected_error);
1404 	if (error == 0)
1405 		dmu_objset_close(os2);
1406 
1407 	zil_close(zilog);
1408 	dmu_objset_close(os);
1409 
1410 	error = dmu_objset_destroy(name);
1411 	if (error)
1412 		fatal(0, "dmu_objset_destroy(%s) = %d", name, error);
1413 
1414 	(void) rw_unlock(&ztest_shared->zs_name_lock);
1415 }
1416 
1417 /*
1418  * Verify that dmu_snapshot_{create,destroy,open,close} work as expected.
1419  */
1420 void
1421 ztest_dmu_snapshot_create_destroy(ztest_args_t *za)
1422 {
1423 	int error;
1424 	objset_t *os = za->za_os;
1425 	char snapname[100];
1426 	char osname[MAXNAMELEN];
1427 
1428 	(void) rw_rdlock(&ztest_shared->zs_name_lock);
1429 	dmu_objset_name(os, osname);
1430 	(void) snprintf(snapname, 100, "%s@%llu", osname,
1431 	    (u_longlong_t)za->za_instance);
1432 
1433 	error = dmu_objset_destroy(snapname);
1434 	if (error != 0 && error != ENOENT)
1435 		fatal(0, "dmu_objset_destroy() = %d", error);
1436 	error = dmu_objset_snapshot(osname, strchr(snapname, '@')+1,
1437 	    NULL, FALSE);
1438 	if (error == ENOSPC)
1439 		ztest_record_enospc("dmu_take_snapshot");
1440 	else if (error != 0 && error != EEXIST)
1441 		fatal(0, "dmu_take_snapshot() = %d", error);
1442 	(void) rw_unlock(&ztest_shared->zs_name_lock);
1443 }
1444 
1445 /*
1446  * Cleanup non-standard snapshots and clones.
1447  */
1448 void
1449 ztest_dsl_dataset_cleanup(char *osname, uint64_t curval)
1450 {
1451 	char snap1name[100];
1452 	char clone1name[100];
1453 	char snap2name[100];
1454 	char clone2name[100];
1455 	char snap3name[100];
1456 	int error;
1457 
1458 	(void) snprintf(snap1name, 100, "%s@s1_%llu", osname, curval);
1459 	(void) snprintf(clone1name, 100, "%s/c1_%llu", osname, curval);
1460 	(void) snprintf(snap2name, 100, "%s@s2_%llu", clone1name, curval);
1461 	(void) snprintf(clone2name, 100, "%s/c2_%llu", osname, curval);
1462 	(void) snprintf(snap3name, 100, "%s@s3_%llu", clone1name, curval);
1463 
1464 	error = dmu_objset_destroy(clone2name);
1465 	if (error && error != ENOENT)
1466 		fatal(0, "dmu_objset_destroy(%s) = %d", clone2name, error);
1467 	error = dmu_objset_destroy(snap3name);
1468 	if (error && error != ENOENT)
1469 		fatal(0, "dmu_objset_destroy(%s) = %d", snap3name, error);
1470 	error = dmu_objset_destroy(snap2name);
1471 	if (error && error != ENOENT)
1472 		fatal(0, "dmu_objset_destroy(%s) = %d", snap2name, error);
1473 	error = dmu_objset_destroy(clone1name);
1474 	if (error && error != ENOENT)
1475 		fatal(0, "dmu_objset_destroy(%s) = %d", clone1name, error);
1476 	error = dmu_objset_destroy(snap1name);
1477 	if (error && error != ENOENT)
1478 		fatal(0, "dmu_objset_destroy(%s) = %d", snap1name, error);
1479 }
1480 
1481 /*
1482  * Verify dsl_dataset_promote handles EBUSY
1483  */
1484 void
1485 ztest_dsl_dataset_promote_busy(ztest_args_t *za)
1486 {
1487 	int error;
1488 	objset_t *os = za->za_os;
1489 	objset_t *clone;
1490 	dsl_dataset_t *ds;
1491 	char snap1name[100];
1492 	char clone1name[100];
1493 	char snap2name[100];
1494 	char clone2name[100];
1495 	char snap3name[100];
1496 	char osname[MAXNAMELEN];
1497 	uint64_t curval = za->za_instance;
1498 
1499 	(void) rw_rdlock(&ztest_shared->zs_name_lock);
1500 
1501 	dmu_objset_name(os, osname);
1502 	ztest_dsl_dataset_cleanup(osname, curval);
1503 
1504 	(void) snprintf(snap1name, 100, "%s@s1_%llu", osname, curval);
1505 	(void) snprintf(clone1name, 100, "%s/c1_%llu", osname, curval);
1506 	(void) snprintf(snap2name, 100, "%s@s2_%llu", clone1name, curval);
1507 	(void) snprintf(clone2name, 100, "%s/c2_%llu", osname, curval);
1508 	(void) snprintf(snap3name, 100, "%s@s3_%llu", clone1name, curval);
1509 
1510 	error = dmu_objset_snapshot(osname, strchr(snap1name, '@')+1,
1511 	    NULL, FALSE);
1512 	if (error && error != EEXIST) {
1513 		if (error == ENOSPC) {
1514 			ztest_record_enospc("dmu_take_snapshot");
1515 			goto out;
1516 		}
1517 		fatal(0, "dmu_take_snapshot(%s) = %d", snap1name, error);
1518 	}
1519 
1520 	error = dmu_objset_open(snap1name, DMU_OST_OTHER,
1521 	    DS_MODE_USER | DS_MODE_READONLY, &clone);
1522 	if (error)
1523 		fatal(0, "dmu_open_snapshot(%s) = %d", snap1name, error);
1524 
1525 	error = dmu_objset_create(clone1name, DMU_OST_OTHER, clone, 0,
1526 	    NULL, NULL);
1527 	dmu_objset_close(clone);
1528 	if (error) {
1529 		if (error == ENOSPC) {
1530 			ztest_record_enospc("dmu_objset_create");
1531 			goto out;
1532 		}
1533 		fatal(0, "dmu_objset_create(%s) = %d", clone1name, error);
1534 	}
1535 
1536 	error = dmu_objset_snapshot(clone1name, strchr(snap2name, '@')+1,
1537 	    NULL, FALSE);
1538 	if (error && error != EEXIST) {
1539 		if (error == ENOSPC) {
1540 			ztest_record_enospc("dmu_take_snapshot");
1541 			goto out;
1542 		}
1543 		fatal(0, "dmu_open_snapshot(%s) = %d", snap2name, error);
1544 	}
1545 
1546 	error = dmu_objset_snapshot(clone1name, strchr(snap3name, '@')+1,
1547 	    NULL, FALSE);
1548 	if (error && error != EEXIST) {
1549 		if (error == ENOSPC) {
1550 			ztest_record_enospc("dmu_take_snapshot");
1551 			goto out;
1552 		}
1553 		fatal(0, "dmu_open_snapshot(%s) = %d", snap3name, error);
1554 	}
1555 
1556 	error = dmu_objset_open(snap3name, DMU_OST_OTHER,
1557 	    DS_MODE_USER | DS_MODE_READONLY, &clone);
1558 	if (error)
1559 		fatal(0, "dmu_open_snapshot(%s) = %d", snap3name, error);
1560 
1561 	error = dmu_objset_create(clone2name, DMU_OST_OTHER, clone, 0,
1562 	    NULL, NULL);
1563 	dmu_objset_close(clone);
1564 	if (error) {
1565 		if (error == ENOSPC) {
1566 			ztest_record_enospc("dmu_objset_create");
1567 			goto out;
1568 		}
1569 		fatal(0, "dmu_objset_create(%s) = %d", clone2name, error);
1570 	}
1571 
1572 	error = dsl_dataset_own(snap1name, DS_MODE_READONLY, FTAG, &ds);
1573 	if (error)
1574 		fatal(0, "dsl_dataset_own(%s) = %d", snap1name, error);
1575 	error = dsl_dataset_promote(clone2name);
1576 	if (error != EBUSY)
1577 		fatal(0, "dsl_dataset_promote(%s), %d, not EBUSY", clone2name,
1578 		    error);
1579 	dsl_dataset_disown(ds, FTAG);
1580 
1581 out:
1582 	ztest_dsl_dataset_cleanup(osname, curval);
1583 
1584 	(void) rw_unlock(&ztest_shared->zs_name_lock);
1585 }
1586 
1587 /*
1588  * Verify that dmu_object_{alloc,free} work as expected.
1589  */
1590 void
1591 ztest_dmu_object_alloc_free(ztest_args_t *za)
1592 {
1593 	objset_t *os = za->za_os;
1594 	dmu_buf_t *db;
1595 	dmu_tx_t *tx;
1596 	uint64_t batchobj, object, batchsize, endoff, temp;
1597 	int b, c, error, bonuslen;
1598 	dmu_object_info_t *doi = &za->za_doi;
1599 	char osname[MAXNAMELEN];
1600 
1601 	dmu_objset_name(os, osname);
1602 
1603 	endoff = -8ULL;
1604 	batchsize = 2;
1605 
1606 	/*
1607 	 * Create a batch object if necessary, and record it in the directory.
1608 	 */
1609 	VERIFY3U(0, ==, dmu_read(os, ZTEST_DIROBJ, za->za_diroff,
1610 	    sizeof (uint64_t), &batchobj, DMU_READ_PREFETCH));
1611 	if (batchobj == 0) {
1612 		tx = dmu_tx_create(os);
1613 		dmu_tx_hold_write(tx, ZTEST_DIROBJ, za->za_diroff,
1614 		    sizeof (uint64_t));
1615 		dmu_tx_hold_bonus(tx, DMU_NEW_OBJECT);
1616 		error = dmu_tx_assign(tx, TXG_WAIT);
1617 		if (error) {
1618 			ztest_record_enospc("create a batch object");
1619 			dmu_tx_abort(tx);
1620 			return;
1621 		}
1622 		batchobj = dmu_object_alloc(os, DMU_OT_UINT64_OTHER, 0,
1623 		    DMU_OT_NONE, 0, tx);
1624 		ztest_set_random_blocksize(os, batchobj, tx);
1625 		dmu_write(os, ZTEST_DIROBJ, za->za_diroff,
1626 		    sizeof (uint64_t), &batchobj, tx);
1627 		dmu_tx_commit(tx);
1628 	}
1629 
1630 	/*
1631 	 * Destroy the previous batch of objects.
1632 	 */
1633 	for (b = 0; b < batchsize; b++) {
1634 		VERIFY3U(0, ==, dmu_read(os, batchobj, b * sizeof (uint64_t),
1635 		    sizeof (uint64_t), &object, DMU_READ_PREFETCH));
1636 		if (object == 0)
1637 			continue;
1638 		/*
1639 		 * Read and validate contents.
1640 		 * We expect the nth byte of the bonus buffer to be n.
1641 		 */
1642 		VERIFY(0 == dmu_bonus_hold(os, object, FTAG, &db));
1643 		za->za_dbuf = db;
1644 
1645 		dmu_object_info_from_db(db, doi);
1646 		ASSERT(doi->doi_type == DMU_OT_UINT64_OTHER);
1647 		ASSERT(doi->doi_bonus_type == DMU_OT_PLAIN_OTHER);
1648 		ASSERT3S(doi->doi_physical_blks, >=, 0);
1649 
1650 		bonuslen = doi->doi_bonus_size;
1651 
1652 		for (c = 0; c < bonuslen; c++) {
1653 			if (((uint8_t *)db->db_data)[c] !=
1654 			    (uint8_t)(c + bonuslen)) {
1655 				fatal(0,
1656 				    "bad bonus: %s, obj %llu, off %d: %u != %u",
1657 				    osname, object, c,
1658 				    ((uint8_t *)db->db_data)[c],
1659 				    (uint8_t)(c + bonuslen));
1660 			}
1661 		}
1662 
1663 		dmu_buf_rele(db, FTAG);
1664 		za->za_dbuf = NULL;
1665 
1666 		/*
1667 		 * We expect the word at endoff to be our object number.
1668 		 */
1669 		VERIFY(0 == dmu_read(os, object, endoff,
1670 		    sizeof (uint64_t), &temp, DMU_READ_PREFETCH));
1671 
1672 		if (temp != object) {
1673 			fatal(0, "bad data in %s, got %llu, expected %llu",
1674 			    osname, temp, object);
1675 		}
1676 
1677 		/*
1678 		 * Destroy old object and clear batch entry.
1679 		 */
1680 		tx = dmu_tx_create(os);
1681 		dmu_tx_hold_write(tx, batchobj,
1682 		    b * sizeof (uint64_t), sizeof (uint64_t));
1683 		dmu_tx_hold_free(tx, object, 0, DMU_OBJECT_END);
1684 		error = dmu_tx_assign(tx, TXG_WAIT);
1685 		if (error) {
1686 			ztest_record_enospc("free object");
1687 			dmu_tx_abort(tx);
1688 			return;
1689 		}
1690 		error = dmu_object_free(os, object, tx);
1691 		if (error) {
1692 			fatal(0, "dmu_object_free('%s', %llu) = %d",
1693 			    osname, object, error);
1694 		}
1695 		object = 0;
1696 
1697 		dmu_object_set_checksum(os, batchobj,
1698 		    ztest_random_checksum(), tx);
1699 		dmu_object_set_compress(os, batchobj,
1700 		    ztest_random_compress(), tx);
1701 
1702 		dmu_write(os, batchobj, b * sizeof (uint64_t),
1703 		    sizeof (uint64_t), &object, tx);
1704 
1705 		dmu_tx_commit(tx);
1706 	}
1707 
1708 	/*
1709 	 * Before creating the new batch of objects, generate a bunch of churn.
1710 	 */
1711 	for (b = ztest_random(100); b > 0; b--) {
1712 		tx = dmu_tx_create(os);
1713 		dmu_tx_hold_bonus(tx, DMU_NEW_OBJECT);
1714 		error = dmu_tx_assign(tx, TXG_WAIT);
1715 		if (error) {
1716 			ztest_record_enospc("churn objects");
1717 			dmu_tx_abort(tx);
1718 			return;
1719 		}
1720 		object = dmu_object_alloc(os, DMU_OT_UINT64_OTHER, 0,
1721 		    DMU_OT_NONE, 0, tx);
1722 		ztest_set_random_blocksize(os, object, tx);
1723 		error = dmu_object_free(os, object, tx);
1724 		if (error) {
1725 			fatal(0, "dmu_object_free('%s', %llu) = %d",
1726 			    osname, object, error);
1727 		}
1728 		dmu_tx_commit(tx);
1729 	}
1730 
1731 	/*
1732 	 * Create a new batch of objects with randomly chosen
1733 	 * blocksizes and record them in the batch directory.
1734 	 */
1735 	for (b = 0; b < batchsize; b++) {
1736 		uint32_t va_blksize;
1737 		u_longlong_t va_nblocks;
1738 
1739 		tx = dmu_tx_create(os);
1740 		dmu_tx_hold_write(tx, batchobj, b * sizeof (uint64_t),
1741 		    sizeof (uint64_t));
1742 		dmu_tx_hold_bonus(tx, DMU_NEW_OBJECT);
1743 		dmu_tx_hold_write(tx, DMU_NEW_OBJECT, endoff,
1744 		    sizeof (uint64_t));
1745 		error = dmu_tx_assign(tx, TXG_WAIT);
1746 		if (error) {
1747 			ztest_record_enospc("create batchobj");
1748 			dmu_tx_abort(tx);
1749 			return;
1750 		}
1751 		bonuslen = (int)ztest_random(dmu_bonus_max()) + 1;
1752 
1753 		object = dmu_object_alloc(os, DMU_OT_UINT64_OTHER, 0,
1754 		    DMU_OT_PLAIN_OTHER, bonuslen, tx);
1755 
1756 		ztest_set_random_blocksize(os, object, tx);
1757 
1758 		dmu_object_set_checksum(os, object,
1759 		    ztest_random_checksum(), tx);
1760 		dmu_object_set_compress(os, object,
1761 		    ztest_random_compress(), tx);
1762 
1763 		dmu_write(os, batchobj, b * sizeof (uint64_t),
1764 		    sizeof (uint64_t), &object, tx);
1765 
1766 		/*
1767 		 * Write to both the bonus buffer and the regular data.
1768 		 */
1769 		VERIFY(dmu_bonus_hold(os, object, FTAG, &db) == 0);
1770 		za->za_dbuf = db;
1771 		ASSERT3U(bonuslen, <=, db->db_size);
1772 
1773 		dmu_object_size_from_db(db, &va_blksize, &va_nblocks);
1774 		ASSERT3S(va_nblocks, >=, 0);
1775 
1776 		dmu_buf_will_dirty(db, tx);
1777 
1778 		/*
1779 		 * See comments above regarding the contents of
1780 		 * the bonus buffer and the word at endoff.
1781 		 */
1782 		for (c = 0; c < bonuslen; c++)
1783 			((uint8_t *)db->db_data)[c] = (uint8_t)(c + bonuslen);
1784 
1785 		dmu_buf_rele(db, FTAG);
1786 		za->za_dbuf = NULL;
1787 
1788 		/*
1789 		 * Write to a large offset to increase indirection.
1790 		 */
1791 		dmu_write(os, object, endoff, sizeof (uint64_t), &object, tx);
1792 
1793 		dmu_tx_commit(tx);
1794 	}
1795 }
1796 
1797 /*
1798  * Verify that dmu_{read,write} work as expected.
1799  */
1800 typedef struct bufwad {
1801 	uint64_t	bw_index;
1802 	uint64_t	bw_txg;
1803 	uint64_t	bw_data;
1804 } bufwad_t;
1805 
1806 typedef struct dmu_read_write_dir {
1807 	uint64_t	dd_packobj;
1808 	uint64_t	dd_bigobj;
1809 	uint64_t	dd_chunk;
1810 } dmu_read_write_dir_t;
1811 
1812 void
1813 ztest_dmu_read_write(ztest_args_t *za)
1814 {
1815 	objset_t *os = za->za_os;
1816 	dmu_read_write_dir_t dd;
1817 	dmu_tx_t *tx;
1818 	int i, freeit, error;
1819 	uint64_t n, s, txg;
1820 	bufwad_t *packbuf, *bigbuf, *pack, *bigH, *bigT;
1821 	uint64_t packoff, packsize, bigoff, bigsize;
1822 	uint64_t regions = 997;
1823 	uint64_t stride = 123456789ULL;
1824 	uint64_t width = 40;
1825 	int free_percent = 5;
1826 
1827 	/*
1828 	 * This test uses two objects, packobj and bigobj, that are always
1829 	 * updated together (i.e. in the same tx) so that their contents are
1830 	 * in sync and can be compared.  Their contents relate to each other
1831 	 * in a simple way: packobj is a dense array of 'bufwad' structures,
1832 	 * while bigobj is a sparse array of the same bufwads.  Specifically,
1833 	 * for any index n, there are three bufwads that should be identical:
1834 	 *
1835 	 *	packobj, at offset n * sizeof (bufwad_t)
1836 	 *	bigobj, at the head of the nth chunk
1837 	 *	bigobj, at the tail of the nth chunk
1838 	 *
1839 	 * The chunk size is arbitrary. It doesn't have to be a power of two,
1840 	 * and it doesn't have any relation to the object blocksize.
1841 	 * The only requirement is that it can hold at least two bufwads.
1842 	 *
1843 	 * Normally, we write the bufwad to each of these locations.
1844 	 * However, free_percent of the time we instead write zeroes to
1845 	 * packobj and perform a dmu_free_range() on bigobj.  By comparing
1846 	 * bigobj to packobj, we can verify that the DMU is correctly
1847 	 * tracking which parts of an object are allocated and free,
1848 	 * and that the contents of the allocated blocks are correct.
1849 	 */
1850 
1851 	/*
1852 	 * Read the directory info.  If it's the first time, set things up.
1853 	 */
1854 	VERIFY(0 == dmu_read(os, ZTEST_DIROBJ, za->za_diroff,
1855 	    sizeof (dd), &dd, DMU_READ_PREFETCH));
1856 	if (dd.dd_chunk == 0) {
1857 		ASSERT(dd.dd_packobj == 0);
1858 		ASSERT(dd.dd_bigobj == 0);
1859 		tx = dmu_tx_create(os);
1860 		dmu_tx_hold_write(tx, ZTEST_DIROBJ, za->za_diroff, sizeof (dd));
1861 		dmu_tx_hold_bonus(tx, DMU_NEW_OBJECT);
1862 		error = dmu_tx_assign(tx, TXG_WAIT);
1863 		if (error) {
1864 			ztest_record_enospc("create r/w directory");
1865 			dmu_tx_abort(tx);
1866 			return;
1867 		}
1868 
1869 		dd.dd_packobj = dmu_object_alloc(os, DMU_OT_UINT64_OTHER, 0,
1870 		    DMU_OT_NONE, 0, tx);
1871 		dd.dd_bigobj = dmu_object_alloc(os, DMU_OT_UINT64_OTHER, 0,
1872 		    DMU_OT_NONE, 0, tx);
1873 		dd.dd_chunk = (1000 + ztest_random(1000)) * sizeof (uint64_t);
1874 
1875 		ztest_set_random_blocksize(os, dd.dd_packobj, tx);
1876 		ztest_set_random_blocksize(os, dd.dd_bigobj, tx);
1877 
1878 		dmu_write(os, ZTEST_DIROBJ, za->za_diroff, sizeof (dd), &dd,
1879 		    tx);
1880 		dmu_tx_commit(tx);
1881 	}
1882 
1883 	/*
1884 	 * Prefetch a random chunk of the big object.
1885 	 * Our aim here is to get some async reads in flight
1886 	 * for blocks that we may free below; the DMU should
1887 	 * handle this race correctly.
1888 	 */
1889 	n = ztest_random(regions) * stride + ztest_random(width);
1890 	s = 1 + ztest_random(2 * width - 1);
1891 	dmu_prefetch(os, dd.dd_bigobj, n * dd.dd_chunk, s * dd.dd_chunk);
1892 
1893 	/*
1894 	 * Pick a random index and compute the offsets into packobj and bigobj.
1895 	 */
1896 	n = ztest_random(regions) * stride + ztest_random(width);
1897 	s = 1 + ztest_random(width - 1);
1898 
1899 	packoff = n * sizeof (bufwad_t);
1900 	packsize = s * sizeof (bufwad_t);
1901 
1902 	bigoff = n * dd.dd_chunk;
1903 	bigsize = s * dd.dd_chunk;
1904 
1905 	packbuf = umem_alloc(packsize, UMEM_NOFAIL);
1906 	bigbuf = umem_alloc(bigsize, UMEM_NOFAIL);
1907 
1908 	/*
1909 	 * free_percent of the time, free a range of bigobj rather than
1910 	 * overwriting it.
1911 	 */
1912 	freeit = (ztest_random(100) < free_percent);
1913 
1914 	/*
1915 	 * Read the current contents of our objects.
1916 	 */
1917 	error = dmu_read(os, dd.dd_packobj, packoff, packsize, packbuf,
1918 	    DMU_READ_PREFETCH);
1919 	ASSERT3U(error, ==, 0);
1920 	error = dmu_read(os, dd.dd_bigobj, bigoff, bigsize, bigbuf,
1921 	    DMU_READ_PREFETCH);
1922 	ASSERT3U(error, ==, 0);
1923 
1924 	/*
1925 	 * Get a tx for the mods to both packobj and bigobj.
1926 	 */
1927 	tx = dmu_tx_create(os);
1928 
1929 	dmu_tx_hold_write(tx, dd.dd_packobj, packoff, packsize);
1930 
1931 	if (freeit)
1932 		dmu_tx_hold_free(tx, dd.dd_bigobj, bigoff, bigsize);
1933 	else
1934 		dmu_tx_hold_write(tx, dd.dd_bigobj, bigoff, bigsize);
1935 
1936 	error = dmu_tx_assign(tx, TXG_WAIT);
1937 
1938 	if (error) {
1939 		ztest_record_enospc("dmu r/w range");
1940 		dmu_tx_abort(tx);
1941 		umem_free(packbuf, packsize);
1942 		umem_free(bigbuf, bigsize);
1943 		return;
1944 	}
1945 
1946 	txg = dmu_tx_get_txg(tx);
1947 
1948 	/*
1949 	 * For each index from n to n + s, verify that the existing bufwad
1950 	 * in packobj matches the bufwads at the head and tail of the
1951 	 * corresponding chunk in bigobj.  Then update all three bufwads
1952 	 * with the new values we want to write out.
1953 	 */
1954 	for (i = 0; i < s; i++) {
1955 		/* LINTED */
1956 		pack = (bufwad_t *)((char *)packbuf + i * sizeof (bufwad_t));
1957 		/* LINTED */
1958 		bigH = (bufwad_t *)((char *)bigbuf + i * dd.dd_chunk);
1959 		/* LINTED */
1960 		bigT = (bufwad_t *)((char *)bigH + dd.dd_chunk) - 1;
1961 
1962 		ASSERT((uintptr_t)bigH - (uintptr_t)bigbuf < bigsize);
1963 		ASSERT((uintptr_t)bigT - (uintptr_t)bigbuf < bigsize);
1964 
1965 		if (pack->bw_txg > txg)
1966 			fatal(0, "future leak: got %llx, open txg is %llx",
1967 			    pack->bw_txg, txg);
1968 
1969 		if (pack->bw_data != 0 && pack->bw_index != n + i)
1970 			fatal(0, "wrong index: got %llx, wanted %llx+%llx",
1971 			    pack->bw_index, n, i);
1972 
1973 		if (bcmp(pack, bigH, sizeof (bufwad_t)) != 0)
1974 			fatal(0, "pack/bigH mismatch in %p/%p", pack, bigH);
1975 
1976 		if (bcmp(pack, bigT, sizeof (bufwad_t)) != 0)
1977 			fatal(0, "pack/bigT mismatch in %p/%p", pack, bigT);
1978 
1979 		if (freeit) {
1980 			bzero(pack, sizeof (bufwad_t));
1981 		} else {
1982 			pack->bw_index = n + i;
1983 			pack->bw_txg = txg;
1984 			pack->bw_data = 1 + ztest_random(-2ULL);
1985 		}
1986 		*bigH = *pack;
1987 		*bigT = *pack;
1988 	}
1989 
1990 	/*
1991 	 * We've verified all the old bufwads, and made new ones.
1992 	 * Now write them out.
1993 	 */
1994 	dmu_write(os, dd.dd_packobj, packoff, packsize, packbuf, tx);
1995 
1996 	if (freeit) {
1997 		if (zopt_verbose >= 6) {
1998 			(void) printf("freeing offset %llx size %llx"
1999 			    " txg %llx\n",
2000 			    (u_longlong_t)bigoff,
2001 			    (u_longlong_t)bigsize,
2002 			    (u_longlong_t)txg);
2003 		}
2004 		VERIFY(0 == dmu_free_range(os, dd.dd_bigobj, bigoff,
2005 		    bigsize, tx));
2006 	} else {
2007 		if (zopt_verbose >= 6) {
2008 			(void) printf("writing offset %llx size %llx"
2009 			    " txg %llx\n",
2010 			    (u_longlong_t)bigoff,
2011 			    (u_longlong_t)bigsize,
2012 			    (u_longlong_t)txg);
2013 		}
2014 		dmu_write(os, dd.dd_bigobj, bigoff, bigsize, bigbuf, tx);
2015 	}
2016 
2017 	dmu_tx_commit(tx);
2018 
2019 	/*
2020 	 * Sanity check the stuff we just wrote.
2021 	 */
2022 	{
2023 		void *packcheck = umem_alloc(packsize, UMEM_NOFAIL);
2024 		void *bigcheck = umem_alloc(bigsize, UMEM_NOFAIL);
2025 
2026 		VERIFY(0 == dmu_read(os, dd.dd_packobj, packoff,
2027 		    packsize, packcheck, DMU_READ_PREFETCH));
2028 		VERIFY(0 == dmu_read(os, dd.dd_bigobj, bigoff,
2029 		    bigsize, bigcheck, DMU_READ_PREFETCH));
2030 
2031 		ASSERT(bcmp(packbuf, packcheck, packsize) == 0);
2032 		ASSERT(bcmp(bigbuf, bigcheck, bigsize) == 0);
2033 
2034 		umem_free(packcheck, packsize);
2035 		umem_free(bigcheck, bigsize);
2036 	}
2037 
2038 	umem_free(packbuf, packsize);
2039 	umem_free(bigbuf, bigsize);
2040 }
2041 
2042 void
2043 compare_and_update_pbbufs(uint64_t s, bufwad_t *packbuf, bufwad_t *bigbuf,
2044     uint64_t bigsize, uint64_t n, dmu_read_write_dir_t dd, uint64_t txg)
2045 {
2046 	uint64_t i;
2047 	bufwad_t *pack;
2048 	bufwad_t *bigH;
2049 	bufwad_t *bigT;
2050 
2051 	/*
2052 	 * For each index from n to n + s, verify that the existing bufwad
2053 	 * in packobj matches the bufwads at the head and tail of the
2054 	 * corresponding chunk in bigobj.  Then update all three bufwads
2055 	 * with the new values we want to write out.
2056 	 */
2057 	for (i = 0; i < s; i++) {
2058 		/* LINTED */
2059 		pack = (bufwad_t *)((char *)packbuf + i * sizeof (bufwad_t));
2060 		/* LINTED */
2061 		bigH = (bufwad_t *)((char *)bigbuf + i * dd.dd_chunk);
2062 		/* LINTED */
2063 		bigT = (bufwad_t *)((char *)bigH + dd.dd_chunk) - 1;
2064 
2065 		ASSERT((uintptr_t)bigH - (uintptr_t)bigbuf < bigsize);
2066 		ASSERT((uintptr_t)bigT - (uintptr_t)bigbuf < bigsize);
2067 
2068 		if (pack->bw_txg > txg)
2069 			fatal(0, "future leak: got %llx, open txg is %llx",
2070 			    pack->bw_txg, txg);
2071 
2072 		if (pack->bw_data != 0 && pack->bw_index != n + i)
2073 			fatal(0, "wrong index: got %llx, wanted %llx+%llx",
2074 			    pack->bw_index, n, i);
2075 
2076 		if (bcmp(pack, bigH, sizeof (bufwad_t)) != 0)
2077 			fatal(0, "pack/bigH mismatch in %p/%p", pack, bigH);
2078 
2079 		if (bcmp(pack, bigT, sizeof (bufwad_t)) != 0)
2080 			fatal(0, "pack/bigT mismatch in %p/%p", pack, bigT);
2081 
2082 		pack->bw_index = n + i;
2083 		pack->bw_txg = txg;
2084 		pack->bw_data = 1 + ztest_random(-2ULL);
2085 
2086 		*bigH = *pack;
2087 		*bigT = *pack;
2088 	}
2089 }
2090 
2091 void
2092 ztest_dmu_read_write_zcopy(ztest_args_t *za)
2093 {
2094 	objset_t *os = za->za_os;
2095 	dmu_read_write_dir_t dd;
2096 	dmu_tx_t *tx;
2097 	uint64_t i;
2098 	int error;
2099 	uint64_t n, s, txg;
2100 	bufwad_t *packbuf, *bigbuf;
2101 	uint64_t packoff, packsize, bigoff, bigsize;
2102 	uint64_t regions = 997;
2103 	uint64_t stride = 123456789ULL;
2104 	uint64_t width = 9;
2105 	dmu_buf_t *bonus_db;
2106 	arc_buf_t **bigbuf_arcbufs;
2107 	dmu_object_info_t *doi = &za->za_doi;
2108 
2109 	/*
2110 	 * This test uses two objects, packobj and bigobj, that are always
2111 	 * updated together (i.e. in the same tx) so that their contents are
2112 	 * in sync and can be compared.  Their contents relate to each other
2113 	 * in a simple way: packobj is a dense array of 'bufwad' structures,
2114 	 * while bigobj is a sparse array of the same bufwads.  Specifically,
2115 	 * for any index n, there are three bufwads that should be identical:
2116 	 *
2117 	 *	packobj, at offset n * sizeof (bufwad_t)
2118 	 *	bigobj, at the head of the nth chunk
2119 	 *	bigobj, at the tail of the nth chunk
2120 	 *
2121 	 * The chunk size is set equal to bigobj block size so that
2122 	 * dmu_assign_arcbuf() can be tested for object updates.
2123 	 */
2124 
2125 	/*
2126 	 * Read the directory info.  If it's the first time, set things up.
2127 	 */
2128 	VERIFY(0 == dmu_read(os, ZTEST_DIROBJ, za->za_diroff,
2129 	    sizeof (dd), &dd, DMU_READ_PREFETCH));
2130 	if (dd.dd_chunk == 0) {
2131 		ASSERT(dd.dd_packobj == 0);
2132 		ASSERT(dd.dd_bigobj == 0);
2133 		tx = dmu_tx_create(os);
2134 		dmu_tx_hold_write(tx, ZTEST_DIROBJ, za->za_diroff, sizeof (dd));
2135 		dmu_tx_hold_bonus(tx, DMU_NEW_OBJECT);
2136 		error = dmu_tx_assign(tx, TXG_WAIT);
2137 		if (error) {
2138 			ztest_record_enospc("create r/w directory");
2139 			dmu_tx_abort(tx);
2140 			return;
2141 		}
2142 
2143 		dd.dd_packobj = dmu_object_alloc(os, DMU_OT_UINT64_OTHER, 0,
2144 		    DMU_OT_NONE, 0, tx);
2145 		dd.dd_bigobj = dmu_object_alloc(os, DMU_OT_UINT64_OTHER, 0,
2146 		    DMU_OT_NONE, 0, tx);
2147 		ztest_set_random_blocksize(os, dd.dd_packobj, tx);
2148 		ztest_set_random_blocksize(os, dd.dd_bigobj, tx);
2149 
2150 		VERIFY(dmu_object_info(os, dd.dd_bigobj, doi) == 0);
2151 		ASSERT(doi->doi_data_block_size >= 2 * sizeof (bufwad_t));
2152 		ASSERT(ISP2(doi->doi_data_block_size));
2153 		dd.dd_chunk = doi->doi_data_block_size;
2154 
2155 		dmu_write(os, ZTEST_DIROBJ, za->za_diroff, sizeof (dd), &dd,
2156 		    tx);
2157 		dmu_tx_commit(tx);
2158 	} else {
2159 		VERIFY(dmu_object_info(os, dd.dd_bigobj, doi) == 0);
2160 		VERIFY(ISP2(doi->doi_data_block_size));
2161 		VERIFY(dd.dd_chunk == doi->doi_data_block_size);
2162 		VERIFY(dd.dd_chunk >= 2 * sizeof (bufwad_t));
2163 	}
2164 
2165 	/*
2166 	 * Pick a random index and compute the offsets into packobj and bigobj.
2167 	 */
2168 	n = ztest_random(regions) * stride + ztest_random(width);
2169 	s = 1 + ztest_random(width - 1);
2170 
2171 	packoff = n * sizeof (bufwad_t);
2172 	packsize = s * sizeof (bufwad_t);
2173 
2174 	bigoff = n * dd.dd_chunk;
2175 	bigsize = s * dd.dd_chunk;
2176 
2177 	packbuf = umem_zalloc(packsize, UMEM_NOFAIL);
2178 	bigbuf = umem_zalloc(bigsize, UMEM_NOFAIL);
2179 
2180 	VERIFY(dmu_bonus_hold(os, dd.dd_bigobj, FTAG, &bonus_db) == 0);
2181 
2182 	bigbuf_arcbufs = umem_zalloc(2 * s * sizeof (arc_buf_t *), UMEM_NOFAIL);
2183 
2184 	/*
2185 	 * Iteration 0 test zcopy for DB_UNCACHED dbufs.
2186 	 * Iteration 1 test zcopy to already referenced dbufs.
2187 	 * Iteration 2 test zcopy to dirty dbuf in the same txg.
2188 	 * Iteration 3 test zcopy to dbuf dirty in previous txg.
2189 	 * Iteration 4 test zcopy when dbuf is no longer dirty.
2190 	 * Iteration 5 test zcopy when it can't be done.
2191 	 * Iteration 6 one more zcopy write.
2192 	 */
2193 	for (i = 0; i < 7; i++) {
2194 		uint64_t j;
2195 		uint64_t off;
2196 
2197 		/*
2198 		 * In iteration 5 (i == 5) use arcbufs
2199 		 * that don't match bigobj blksz to test
2200 		 * dmu_assign_arcbuf() when it can't directly
2201 		 * assign an arcbuf to a dbuf.
2202 		 */
2203 		for (j = 0; j < s; j++) {
2204 			if (i != 5) {
2205 				bigbuf_arcbufs[j] =
2206 				    dmu_request_arcbuf(bonus_db,
2207 				    dd.dd_chunk);
2208 			} else {
2209 				bigbuf_arcbufs[2 * j] =
2210 				    dmu_request_arcbuf(bonus_db,
2211 				    dd.dd_chunk / 2);
2212 				bigbuf_arcbufs[2 * j + 1] =
2213 				    dmu_request_arcbuf(bonus_db,
2214 				    dd.dd_chunk / 2);
2215 			}
2216 		}
2217 
2218 		/*
2219 		 * Get a tx for the mods to both packobj and bigobj.
2220 		 */
2221 		tx = dmu_tx_create(os);
2222 
2223 		dmu_tx_hold_write(tx, dd.dd_packobj, packoff, packsize);
2224 		dmu_tx_hold_write(tx, dd.dd_bigobj, bigoff, bigsize);
2225 
2226 		if (ztest_random(100) == 0) {
2227 			error = -1;
2228 		} else {
2229 			error = dmu_tx_assign(tx, TXG_WAIT);
2230 		}
2231 
2232 		if (error) {
2233 			if (error != -1) {
2234 				ztest_record_enospc("dmu r/w range");
2235 			}
2236 			dmu_tx_abort(tx);
2237 			umem_free(packbuf, packsize);
2238 			umem_free(bigbuf, bigsize);
2239 			for (j = 0; j < s; j++) {
2240 				if (i != 5) {
2241 					dmu_return_arcbuf(bigbuf_arcbufs[j]);
2242 				} else {
2243 					dmu_return_arcbuf(
2244 					    bigbuf_arcbufs[2 * j]);
2245 					dmu_return_arcbuf(
2246 					    bigbuf_arcbufs[2 * j + 1]);
2247 				}
2248 			}
2249 			umem_free(bigbuf_arcbufs, 2 * s * sizeof (arc_buf_t *));
2250 			dmu_buf_rele(bonus_db, FTAG);
2251 			return;
2252 		}
2253 
2254 		txg = dmu_tx_get_txg(tx);
2255 
2256 		/*
2257 		 * 50% of the time don't read objects in the 1st iteration to
2258 		 * test dmu_assign_arcbuf() for the case when there're no
2259 		 * existing dbufs for the specified offsets.
2260 		 */
2261 		if (i != 0 || ztest_random(2) != 0) {
2262 			error = dmu_read(os, dd.dd_packobj, packoff,
2263 			    packsize, packbuf, DMU_READ_PREFETCH);
2264 			ASSERT3U(error, ==, 0);
2265 			error = dmu_read(os, dd.dd_bigobj, bigoff, bigsize,
2266 			    bigbuf, DMU_READ_PREFETCH);
2267 			ASSERT3U(error, ==, 0);
2268 		}
2269 		compare_and_update_pbbufs(s, packbuf, bigbuf, bigsize,
2270 		    n, dd, txg);
2271 
2272 		/*
2273 		 * We've verified all the old bufwads, and made new ones.
2274 		 * Now write them out.
2275 		 */
2276 		dmu_write(os, dd.dd_packobj, packoff, packsize, packbuf, tx);
2277 		if (zopt_verbose >= 6) {
2278 			(void) printf("writing offset %llx size %llx"
2279 			    " txg %llx\n",
2280 			    (u_longlong_t)bigoff,
2281 			    (u_longlong_t)bigsize,
2282 			    (u_longlong_t)txg);
2283 		}
2284 		for (off = bigoff, j = 0; j < s; j++, off += dd.dd_chunk) {
2285 			dmu_buf_t *dbt;
2286 			if (i != 5) {
2287 				bcopy((caddr_t)bigbuf + (off - bigoff),
2288 				    bigbuf_arcbufs[j]->b_data, dd.dd_chunk);
2289 			} else {
2290 				bcopy((caddr_t)bigbuf + (off - bigoff),
2291 				    bigbuf_arcbufs[2 * j]->b_data,
2292 				    dd.dd_chunk / 2);
2293 				bcopy((caddr_t)bigbuf + (off - bigoff) +
2294 				    dd.dd_chunk / 2,
2295 				    bigbuf_arcbufs[2 * j + 1]->b_data,
2296 				    dd.dd_chunk / 2);
2297 			}
2298 
2299 			if (i == 1) {
2300 				VERIFY(dmu_buf_hold(os, dd.dd_bigobj, off,
2301 				    FTAG, &dbt) == 0);
2302 			}
2303 			if (i != 5) {
2304 				dmu_assign_arcbuf(bonus_db, off,
2305 				    bigbuf_arcbufs[j], tx);
2306 			} else {
2307 				dmu_assign_arcbuf(bonus_db, off,
2308 				    bigbuf_arcbufs[2 * j], tx);
2309 				dmu_assign_arcbuf(bonus_db,
2310 				    off + dd.dd_chunk / 2,
2311 				    bigbuf_arcbufs[2 * j + 1], tx);
2312 			}
2313 			if (i == 1) {
2314 				dmu_buf_rele(dbt, FTAG);
2315 			}
2316 		}
2317 		dmu_tx_commit(tx);
2318 
2319 		/*
2320 		 * Sanity check the stuff we just wrote.
2321 		 */
2322 		{
2323 			void *packcheck = umem_alloc(packsize, UMEM_NOFAIL);
2324 			void *bigcheck = umem_alloc(bigsize, UMEM_NOFAIL);
2325 
2326 			VERIFY(0 == dmu_read(os, dd.dd_packobj, packoff,
2327 			    packsize, packcheck, DMU_READ_PREFETCH));
2328 			VERIFY(0 == dmu_read(os, dd.dd_bigobj, bigoff,
2329 			    bigsize, bigcheck, DMU_READ_PREFETCH));
2330 
2331 			ASSERT(bcmp(packbuf, packcheck, packsize) == 0);
2332 			ASSERT(bcmp(bigbuf, bigcheck, bigsize) == 0);
2333 
2334 			umem_free(packcheck, packsize);
2335 			umem_free(bigcheck, bigsize);
2336 		}
2337 		if (i == 2) {
2338 			txg_wait_open(dmu_objset_pool(os), 0);
2339 		} else if (i == 3) {
2340 			txg_wait_synced(dmu_objset_pool(os), 0);
2341 		}
2342 	}
2343 
2344 	dmu_buf_rele(bonus_db, FTAG);
2345 	umem_free(packbuf, packsize);
2346 	umem_free(bigbuf, bigsize);
2347 	umem_free(bigbuf_arcbufs, 2 * s * sizeof (arc_buf_t *));
2348 }
2349 
2350 void
2351 ztest_dmu_check_future_leak(ztest_args_t *za)
2352 {
2353 	objset_t *os = za->za_os;
2354 	dmu_buf_t *db;
2355 	ztest_block_tag_t *bt;
2356 	dmu_object_info_t *doi = &za->za_doi;
2357 
2358 	/*
2359 	 * Make sure that, if there is a write record in the bonus buffer
2360 	 * of the ZTEST_DIROBJ, that the txg for this record is <= the
2361 	 * last synced txg of the pool.
2362 	 */
2363 	VERIFY(dmu_bonus_hold(os, ZTEST_DIROBJ, FTAG, &db) == 0);
2364 	za->za_dbuf = db;
2365 	VERIFY(dmu_object_info(os, ZTEST_DIROBJ, doi) == 0);
2366 	ASSERT3U(doi->doi_bonus_size, >=, sizeof (*bt));
2367 	ASSERT3U(doi->doi_bonus_size, <=, db->db_size);
2368 	ASSERT3U(doi->doi_bonus_size % sizeof (*bt), ==, 0);
2369 	bt = (void *)((char *)db->db_data + doi->doi_bonus_size - sizeof (*bt));
2370 	if (bt->bt_objset != 0) {
2371 		ASSERT3U(bt->bt_objset, ==, dmu_objset_id(os));
2372 		ASSERT3U(bt->bt_object, ==, ZTEST_DIROBJ);
2373 		ASSERT3U(bt->bt_offset, ==, -1ULL);
2374 		ASSERT3U(bt->bt_txg, <, spa_first_txg(za->za_spa));
2375 	}
2376 	dmu_buf_rele(db, FTAG);
2377 	za->za_dbuf = NULL;
2378 }
2379 
2380 void
2381 ztest_dmu_write_parallel(ztest_args_t *za)
2382 {
2383 	objset_t *os = za->za_os;
2384 	ztest_block_tag_t *rbt = &za->za_rbt;
2385 	ztest_block_tag_t *wbt = &za->za_wbt;
2386 	const size_t btsize = sizeof (ztest_block_tag_t);
2387 	dmu_buf_t *db;
2388 	int b, error;
2389 	int bs = ZTEST_DIROBJ_BLOCKSIZE;
2390 	int do_free = 0;
2391 	uint64_t off, txg, txg_how;
2392 	mutex_t *lp;
2393 	char osname[MAXNAMELEN];
2394 	char iobuf[SPA_MAXBLOCKSIZE];
2395 	blkptr_t blk = { 0 };
2396 	uint64_t blkoff;
2397 	zbookmark_t zb;
2398 	dmu_tx_t *tx = dmu_tx_create(os);
2399 	dmu_buf_t *bonus_db;
2400 	arc_buf_t *abuf = NULL;
2401 
2402 	dmu_objset_name(os, osname);
2403 
2404 	/*
2405 	 * Have multiple threads write to large offsets in ZTEST_DIROBJ
2406 	 * to verify that having multiple threads writing to the same object
2407 	 * in parallel doesn't cause any trouble.
2408 	 */
2409 	if (ztest_random(4) == 0) {
2410 		/*
2411 		 * Do the bonus buffer instead of a regular block.
2412 		 * We need a lock to serialize resize vs. others,
2413 		 * so we hash on the objset ID.
2414 		 */
2415 		b = dmu_objset_id(os) % ZTEST_SYNC_LOCKS;
2416 		off = -1ULL;
2417 		dmu_tx_hold_bonus(tx, ZTEST_DIROBJ);
2418 	} else {
2419 		b = ztest_random(ZTEST_SYNC_LOCKS);
2420 		off = za->za_diroff_shared + (b << SPA_MAXBLOCKSHIFT);
2421 		if (ztest_random(4) == 0) {
2422 			do_free = 1;
2423 			dmu_tx_hold_free(tx, ZTEST_DIROBJ, off, bs);
2424 		} else {
2425 			dmu_tx_hold_write(tx, ZTEST_DIROBJ, off, bs);
2426 		}
2427 	}
2428 
2429 	if (off != -1ULL && P2PHASE(off, bs) == 0 && !do_free &&
2430 	    ztest_random(8) == 0) {
2431 		VERIFY(dmu_bonus_hold(os, ZTEST_DIROBJ, FTAG, &bonus_db) == 0);
2432 		abuf = dmu_request_arcbuf(bonus_db, bs);
2433 	}
2434 
2435 	txg_how = ztest_random(2) == 0 ? TXG_WAIT : TXG_NOWAIT;
2436 	error = dmu_tx_assign(tx, txg_how);
2437 	if (error) {
2438 		if (error == ERESTART) {
2439 			ASSERT(txg_how == TXG_NOWAIT);
2440 			dmu_tx_wait(tx);
2441 		} else {
2442 			ztest_record_enospc("dmu write parallel");
2443 		}
2444 		dmu_tx_abort(tx);
2445 		if (abuf != NULL) {
2446 			dmu_return_arcbuf(abuf);
2447 			dmu_buf_rele(bonus_db, FTAG);
2448 		}
2449 		return;
2450 	}
2451 	txg = dmu_tx_get_txg(tx);
2452 
2453 	lp = &ztest_shared->zs_sync_lock[b];
2454 	(void) mutex_lock(lp);
2455 
2456 	wbt->bt_objset = dmu_objset_id(os);
2457 	wbt->bt_object = ZTEST_DIROBJ;
2458 	wbt->bt_offset = off;
2459 	wbt->bt_txg = txg;
2460 	wbt->bt_thread = za->za_instance;
2461 	wbt->bt_seq = ztest_shared->zs_seq[b]++;	/* protected by lp */
2462 
2463 	/*
2464 	 * Occasionally, write an all-zero block to test the behavior
2465 	 * of blocks that compress into holes.
2466 	 */
2467 	if (off != -1ULL && ztest_random(8) == 0)
2468 		bzero(wbt, btsize);
2469 
2470 	if (off == -1ULL) {
2471 		dmu_object_info_t *doi = &za->za_doi;
2472 		char *dboff;
2473 
2474 		VERIFY(dmu_bonus_hold(os, ZTEST_DIROBJ, FTAG, &db) == 0);
2475 		za->za_dbuf = db;
2476 		dmu_object_info_from_db(db, doi);
2477 		ASSERT3U(doi->doi_bonus_size, <=, db->db_size);
2478 		ASSERT3U(doi->doi_bonus_size, >=, btsize);
2479 		ASSERT3U(doi->doi_bonus_size % btsize, ==, 0);
2480 		dboff = (char *)db->db_data + doi->doi_bonus_size - btsize;
2481 		bcopy(dboff, rbt, btsize);
2482 		if (rbt->bt_objset != 0) {
2483 			ASSERT3U(rbt->bt_objset, ==, wbt->bt_objset);
2484 			ASSERT3U(rbt->bt_object, ==, wbt->bt_object);
2485 			ASSERT3U(rbt->bt_offset, ==, wbt->bt_offset);
2486 			ASSERT3U(rbt->bt_txg, <=, wbt->bt_txg);
2487 		}
2488 		if (ztest_random(10) == 0) {
2489 			int newsize = (ztest_random(db->db_size /
2490 			    btsize) + 1) * btsize;
2491 
2492 			ASSERT3U(newsize, >=, btsize);
2493 			ASSERT3U(newsize, <=, db->db_size);
2494 			VERIFY3U(dmu_set_bonus(db, newsize, tx), ==, 0);
2495 			dboff = (char *)db->db_data + newsize - btsize;
2496 		}
2497 		dmu_buf_will_dirty(db, tx);
2498 		bcopy(wbt, dboff, btsize);
2499 		dmu_buf_rele(db, FTAG);
2500 		za->za_dbuf = NULL;
2501 	} else if (do_free) {
2502 		VERIFY(dmu_free_range(os, ZTEST_DIROBJ, off, bs, tx) == 0);
2503 	} else if (abuf == NULL) {
2504 		dmu_write(os, ZTEST_DIROBJ, off, btsize, wbt, tx);
2505 	} else {
2506 		bcopy(wbt, abuf->b_data, btsize);
2507 		dmu_assign_arcbuf(bonus_db, off, abuf, tx);
2508 		dmu_buf_rele(bonus_db, FTAG);
2509 	}
2510 
2511 	(void) mutex_unlock(lp);
2512 
2513 	if (ztest_random(1000) == 0)
2514 		(void) poll(NULL, 0, 1); /* open dn_notxholds window */
2515 
2516 	dmu_tx_commit(tx);
2517 
2518 	if (ztest_random(10000) == 0)
2519 		txg_wait_synced(dmu_objset_pool(os), txg);
2520 
2521 	if (off == -1ULL || do_free)
2522 		return;
2523 
2524 	if (ztest_random(2) != 0)
2525 		return;
2526 
2527 	/*
2528 	 * dmu_sync() the block we just wrote.
2529 	 */
2530 	(void) mutex_lock(lp);
2531 
2532 	blkoff = P2ALIGN_TYPED(off, bs, uint64_t);
2533 	error = dmu_buf_hold(os, ZTEST_DIROBJ, blkoff, FTAG, &db);
2534 	za->za_dbuf = db;
2535 	if (error) {
2536 		(void) mutex_unlock(lp);
2537 		return;
2538 	}
2539 	blkoff = off - blkoff;
2540 	error = dmu_sync(NULL, db, &blk, txg, NULL, NULL);
2541 	dmu_buf_rele(db, FTAG);
2542 	za->za_dbuf = NULL;
2543 
2544 	if (error) {
2545 		(void) mutex_unlock(lp);
2546 		return;
2547 	}
2548 
2549 	if (blk.blk_birth == 0)	{	/* concurrent free */
2550 		(void) mutex_unlock(lp);
2551 		return;
2552 	}
2553 
2554 	txg_suspend(dmu_objset_pool(os));
2555 
2556 	(void) mutex_unlock(lp);
2557 
2558 	ASSERT(blk.blk_fill == 1);
2559 	ASSERT3U(BP_GET_TYPE(&blk), ==, DMU_OT_UINT64_OTHER);
2560 	ASSERT3U(BP_GET_LEVEL(&blk), ==, 0);
2561 	ASSERT3U(BP_GET_LSIZE(&blk), ==, bs);
2562 
2563 	/*
2564 	 * Read the block that dmu_sync() returned to make sure its contents
2565 	 * match what we wrote.  We do this while still txg_suspend()ed
2566 	 * to ensure that the block can't be reused before we read it.
2567 	 */
2568 	zb.zb_objset = dmu_objset_id(os);
2569 	zb.zb_object = ZTEST_DIROBJ;
2570 	zb.zb_level = 0;
2571 	zb.zb_blkid = off / bs;
2572 	error = zio_wait(zio_read(NULL, za->za_spa, &blk, iobuf, bs,
2573 	    NULL, NULL, ZIO_PRIORITY_SYNC_READ, ZIO_FLAG_MUSTSUCCEED, &zb));
2574 	ASSERT3U(error, ==, 0);
2575 
2576 	txg_resume(dmu_objset_pool(os));
2577 
2578 	bcopy(&iobuf[blkoff], rbt, btsize);
2579 
2580 	if (rbt->bt_objset == 0)		/* concurrent free */
2581 		return;
2582 
2583 	if (wbt->bt_objset == 0)		/* all-zero overwrite */
2584 		return;
2585 
2586 	ASSERT3U(rbt->bt_objset, ==, wbt->bt_objset);
2587 	ASSERT3U(rbt->bt_object, ==, wbt->bt_object);
2588 	ASSERT3U(rbt->bt_offset, ==, wbt->bt_offset);
2589 
2590 	/*
2591 	 * The semantic of dmu_sync() is that we always push the most recent
2592 	 * version of the data, so in the face of concurrent updates we may
2593 	 * see a newer version of the block.  That's OK.
2594 	 */
2595 	ASSERT3U(rbt->bt_txg, >=, wbt->bt_txg);
2596 	if (rbt->bt_thread == wbt->bt_thread)
2597 		ASSERT3U(rbt->bt_seq, ==, wbt->bt_seq);
2598 	else
2599 		ASSERT3U(rbt->bt_seq, >, wbt->bt_seq);
2600 }
2601 
2602 /*
2603  * Verify that zap_{create,destroy,add,remove,update} work as expected.
2604  */
2605 #define	ZTEST_ZAP_MIN_INTS	1
2606 #define	ZTEST_ZAP_MAX_INTS	4
2607 #define	ZTEST_ZAP_MAX_PROPS	1000
2608 
2609 void
2610 ztest_zap(ztest_args_t *za)
2611 {
2612 	objset_t *os = za->za_os;
2613 	uint64_t object;
2614 	uint64_t txg, last_txg;
2615 	uint64_t value[ZTEST_ZAP_MAX_INTS];
2616 	uint64_t zl_ints, zl_intsize, prop;
2617 	int i, ints;
2618 	dmu_tx_t *tx;
2619 	char propname[100], txgname[100];
2620 	int error;
2621 	char osname[MAXNAMELEN];
2622 	char *hc[2] = { "s.acl.h", ".s.open.h.hyLZlg" };
2623 
2624 	dmu_objset_name(os, osname);
2625 
2626 	/*
2627 	 * Create a new object if necessary, and record it in the directory.
2628 	 */
2629 	VERIFY(0 == dmu_read(os, ZTEST_DIROBJ, za->za_diroff,
2630 	    sizeof (uint64_t), &object, DMU_READ_PREFETCH));
2631 
2632 	if (object == 0) {
2633 		tx = dmu_tx_create(os);
2634 		dmu_tx_hold_write(tx, ZTEST_DIROBJ, za->za_diroff,
2635 		    sizeof (uint64_t));
2636 		dmu_tx_hold_zap(tx, DMU_NEW_OBJECT, TRUE, NULL);
2637 		error = dmu_tx_assign(tx, TXG_WAIT);
2638 		if (error) {
2639 			ztest_record_enospc("create zap test obj");
2640 			dmu_tx_abort(tx);
2641 			return;
2642 		}
2643 		object = zap_create(os, DMU_OT_ZAP_OTHER, DMU_OT_NONE, 0, tx);
2644 		if (error) {
2645 			fatal(0, "zap_create('%s', %llu) = %d",
2646 			    osname, object, error);
2647 		}
2648 		ASSERT(object != 0);
2649 		dmu_write(os, ZTEST_DIROBJ, za->za_diroff,
2650 		    sizeof (uint64_t), &object, tx);
2651 		/*
2652 		 * Generate a known hash collision, and verify that
2653 		 * we can lookup and remove both entries.
2654 		 */
2655 		for (i = 0; i < 2; i++) {
2656 			value[i] = i;
2657 			error = zap_add(os, object, hc[i], sizeof (uint64_t),
2658 			    1, &value[i], tx);
2659 			ASSERT3U(error, ==, 0);
2660 		}
2661 		for (i = 0; i < 2; i++) {
2662 			error = zap_add(os, object, hc[i], sizeof (uint64_t),
2663 			    1, &value[i], tx);
2664 			ASSERT3U(error, ==, EEXIST);
2665 			error = zap_length(os, object, hc[i],
2666 			    &zl_intsize, &zl_ints);
2667 			ASSERT3U(error, ==, 0);
2668 			ASSERT3U(zl_intsize, ==, sizeof (uint64_t));
2669 			ASSERT3U(zl_ints, ==, 1);
2670 		}
2671 		for (i = 0; i < 2; i++) {
2672 			error = zap_remove(os, object, hc[i], tx);
2673 			ASSERT3U(error, ==, 0);
2674 		}
2675 
2676 		dmu_tx_commit(tx);
2677 	}
2678 
2679 	ints = MAX(ZTEST_ZAP_MIN_INTS, object % ZTEST_ZAP_MAX_INTS);
2680 
2681 	prop = ztest_random(ZTEST_ZAP_MAX_PROPS);
2682 	(void) sprintf(propname, "prop_%llu", (u_longlong_t)prop);
2683 	(void) sprintf(txgname, "txg_%llu", (u_longlong_t)prop);
2684 	bzero(value, sizeof (value));
2685 	last_txg = 0;
2686 
2687 	/*
2688 	 * If these zap entries already exist, validate their contents.
2689 	 */
2690 	error = zap_length(os, object, txgname, &zl_intsize, &zl_ints);
2691 	if (error == 0) {
2692 		ASSERT3U(zl_intsize, ==, sizeof (uint64_t));
2693 		ASSERT3U(zl_ints, ==, 1);
2694 
2695 		VERIFY(zap_lookup(os, object, txgname, zl_intsize,
2696 		    zl_ints, &last_txg) == 0);
2697 
2698 		VERIFY(zap_length(os, object, propname, &zl_intsize,
2699 		    &zl_ints) == 0);
2700 
2701 		ASSERT3U(zl_intsize, ==, sizeof (uint64_t));
2702 		ASSERT3U(zl_ints, ==, ints);
2703 
2704 		VERIFY(zap_lookup(os, object, propname, zl_intsize,
2705 		    zl_ints, value) == 0);
2706 
2707 		for (i = 0; i < ints; i++) {
2708 			ASSERT3U(value[i], ==, last_txg + object + i);
2709 		}
2710 	} else {
2711 		ASSERT3U(error, ==, ENOENT);
2712 	}
2713 
2714 	/*
2715 	 * Atomically update two entries in our zap object.
2716 	 * The first is named txg_%llu, and contains the txg
2717 	 * in which the property was last updated.  The second
2718 	 * is named prop_%llu, and the nth element of its value
2719 	 * should be txg + object + n.
2720 	 */
2721 	tx = dmu_tx_create(os);
2722 	dmu_tx_hold_zap(tx, object, TRUE, NULL);
2723 	error = dmu_tx_assign(tx, TXG_WAIT);
2724 	if (error) {
2725 		ztest_record_enospc("create zap entry");
2726 		dmu_tx_abort(tx);
2727 		return;
2728 	}
2729 	txg = dmu_tx_get_txg(tx);
2730 
2731 	if (last_txg > txg)
2732 		fatal(0, "zap future leak: old %llu new %llu", last_txg, txg);
2733 
2734 	for (i = 0; i < ints; i++)
2735 		value[i] = txg + object + i;
2736 
2737 	error = zap_update(os, object, txgname, sizeof (uint64_t), 1, &txg, tx);
2738 	if (error)
2739 		fatal(0, "zap_update('%s', %llu, '%s') = %d",
2740 		    osname, object, txgname, error);
2741 
2742 	error = zap_update(os, object, propname, sizeof (uint64_t),
2743 	    ints, value, tx);
2744 	if (error)
2745 		fatal(0, "zap_update('%s', %llu, '%s') = %d",
2746 		    osname, object, propname, error);
2747 
2748 	dmu_tx_commit(tx);
2749 
2750 	/*
2751 	 * Remove a random pair of entries.
2752 	 */
2753 	prop = ztest_random(ZTEST_ZAP_MAX_PROPS);
2754 	(void) sprintf(propname, "prop_%llu", (u_longlong_t)prop);
2755 	(void) sprintf(txgname, "txg_%llu", (u_longlong_t)prop);
2756 
2757 	error = zap_length(os, object, txgname, &zl_intsize, &zl_ints);
2758 
2759 	if (error == ENOENT)
2760 		return;
2761 
2762 	ASSERT3U(error, ==, 0);
2763 
2764 	tx = dmu_tx_create(os);
2765 	dmu_tx_hold_zap(tx, object, TRUE, NULL);
2766 	error = dmu_tx_assign(tx, TXG_WAIT);
2767 	if (error) {
2768 		ztest_record_enospc("remove zap entry");
2769 		dmu_tx_abort(tx);
2770 		return;
2771 	}
2772 	error = zap_remove(os, object, txgname, tx);
2773 	if (error)
2774 		fatal(0, "zap_remove('%s', %llu, '%s') = %d",
2775 		    osname, object, txgname, error);
2776 
2777 	error = zap_remove(os, object, propname, tx);
2778 	if (error)
2779 		fatal(0, "zap_remove('%s', %llu, '%s') = %d",
2780 		    osname, object, propname, error);
2781 
2782 	dmu_tx_commit(tx);
2783 
2784 	/*
2785 	 * Once in a while, destroy the object.
2786 	 */
2787 	if (ztest_random(1000) != 0)
2788 		return;
2789 
2790 	tx = dmu_tx_create(os);
2791 	dmu_tx_hold_write(tx, ZTEST_DIROBJ, za->za_diroff, sizeof (uint64_t));
2792 	dmu_tx_hold_free(tx, object, 0, DMU_OBJECT_END);
2793 	error = dmu_tx_assign(tx, TXG_WAIT);
2794 	if (error) {
2795 		ztest_record_enospc("destroy zap object");
2796 		dmu_tx_abort(tx);
2797 		return;
2798 	}
2799 	error = zap_destroy(os, object, tx);
2800 	if (error)
2801 		fatal(0, "zap_destroy('%s', %llu) = %d",
2802 		    osname, object, error);
2803 	object = 0;
2804 	dmu_write(os, ZTEST_DIROBJ, za->za_diroff, sizeof (uint64_t),
2805 	    &object, tx);
2806 	dmu_tx_commit(tx);
2807 }
2808 
2809 void
2810 ztest_zap_parallel(ztest_args_t *za)
2811 {
2812 	objset_t *os = za->za_os;
2813 	uint64_t txg, object, count, wsize, wc, zl_wsize, zl_wc;
2814 	dmu_tx_t *tx;
2815 	int i, namelen, error;
2816 	char name[20], string_value[20];
2817 	void *data;
2818 
2819 	/*
2820 	 * Generate a random name of the form 'xxx.....' where each
2821 	 * x is a random printable character and the dots are dots.
2822 	 * There are 94 such characters, and the name length goes from
2823 	 * 6 to 20, so there are 94^3 * 15 = 12,458,760 possible names.
2824 	 */
2825 	namelen = ztest_random(sizeof (name) - 5) + 5 + 1;
2826 
2827 	for (i = 0; i < 3; i++)
2828 		name[i] = '!' + ztest_random('~' - '!' + 1);
2829 	for (; i < namelen - 1; i++)
2830 		name[i] = '.';
2831 	name[i] = '\0';
2832 
2833 	if (ztest_random(2) == 0)
2834 		object = ZTEST_MICROZAP_OBJ;
2835 	else
2836 		object = ZTEST_FATZAP_OBJ;
2837 
2838 	if ((namelen & 1) || object == ZTEST_MICROZAP_OBJ) {
2839 		wsize = sizeof (txg);
2840 		wc = 1;
2841 		data = &txg;
2842 	} else {
2843 		wsize = 1;
2844 		wc = namelen;
2845 		data = string_value;
2846 	}
2847 
2848 	count = -1ULL;
2849 	VERIFY(zap_count(os, object, &count) == 0);
2850 	ASSERT(count != -1ULL);
2851 
2852 	/*
2853 	 * Select an operation: length, lookup, add, update, remove.
2854 	 */
2855 	i = ztest_random(5);
2856 
2857 	if (i >= 2) {
2858 		tx = dmu_tx_create(os);
2859 		dmu_tx_hold_zap(tx, object, TRUE, NULL);
2860 		error = dmu_tx_assign(tx, TXG_WAIT);
2861 		if (error) {
2862 			ztest_record_enospc("zap parallel");
2863 			dmu_tx_abort(tx);
2864 			return;
2865 		}
2866 		txg = dmu_tx_get_txg(tx);
2867 		bcopy(name, string_value, namelen);
2868 	} else {
2869 		tx = NULL;
2870 		txg = 0;
2871 		bzero(string_value, namelen);
2872 	}
2873 
2874 	switch (i) {
2875 
2876 	case 0:
2877 		error = zap_length(os, object, name, &zl_wsize, &zl_wc);
2878 		if (error == 0) {
2879 			ASSERT3U(wsize, ==, zl_wsize);
2880 			ASSERT3U(wc, ==, zl_wc);
2881 		} else {
2882 			ASSERT3U(error, ==, ENOENT);
2883 		}
2884 		break;
2885 
2886 	case 1:
2887 		error = zap_lookup(os, object, name, wsize, wc, data);
2888 		if (error == 0) {
2889 			if (data == string_value &&
2890 			    bcmp(name, data, namelen) != 0)
2891 				fatal(0, "name '%s' != val '%s' len %d",
2892 				    name, data, namelen);
2893 		} else {
2894 			ASSERT3U(error, ==, ENOENT);
2895 		}
2896 		break;
2897 
2898 	case 2:
2899 		error = zap_add(os, object, name, wsize, wc, data, tx);
2900 		ASSERT(error == 0 || error == EEXIST);
2901 		break;
2902 
2903 	case 3:
2904 		VERIFY(zap_update(os, object, name, wsize, wc, data, tx) == 0);
2905 		break;
2906 
2907 	case 4:
2908 		error = zap_remove(os, object, name, tx);
2909 		ASSERT(error == 0 || error == ENOENT);
2910 		break;
2911 	}
2912 
2913 	if (tx != NULL)
2914 		dmu_tx_commit(tx);
2915 }
2916 
2917 void
2918 ztest_dsl_prop_get_set(ztest_args_t *za)
2919 {
2920 	objset_t *os = za->za_os;
2921 	int i, inherit;
2922 	uint64_t value;
2923 	const char *prop, *valname;
2924 	char setpoint[MAXPATHLEN];
2925 	char osname[MAXNAMELEN];
2926 	int error;
2927 
2928 	(void) rw_rdlock(&ztest_shared->zs_name_lock);
2929 
2930 	dmu_objset_name(os, osname);
2931 
2932 	for (i = 0; i < 2; i++) {
2933 		if (i == 0) {
2934 			prop = "checksum";
2935 			value = ztest_random_checksum();
2936 			inherit = (value == ZIO_CHECKSUM_INHERIT);
2937 		} else {
2938 			prop = "compression";
2939 			value = ztest_random_compress();
2940 			inherit = (value == ZIO_COMPRESS_INHERIT);
2941 		}
2942 
2943 		error = dsl_prop_set(osname, prop, sizeof (value),
2944 		    !inherit, &value);
2945 
2946 		if (error == ENOSPC) {
2947 			ztest_record_enospc("dsl_prop_set");
2948 			break;
2949 		}
2950 
2951 		ASSERT3U(error, ==, 0);
2952 
2953 		VERIFY3U(dsl_prop_get(osname, prop, sizeof (value),
2954 		    1, &value, setpoint), ==, 0);
2955 
2956 		if (i == 0)
2957 			valname = zio_checksum_table[value].ci_name;
2958 		else
2959 			valname = zio_compress_table[value].ci_name;
2960 
2961 		if (zopt_verbose >= 6) {
2962 			(void) printf("%s %s = %s for '%s'\n",
2963 			    osname, prop, valname, setpoint);
2964 		}
2965 	}
2966 
2967 	(void) rw_unlock(&ztest_shared->zs_name_lock);
2968 }
2969 
2970 /*
2971  * Inject random faults into the on-disk data.
2972  */
2973 void
2974 ztest_fault_inject(ztest_args_t *za)
2975 {
2976 	int fd;
2977 	uint64_t offset;
2978 	uint64_t leaves = MAX(zopt_mirrors, 1) * zopt_raidz;
2979 	uint64_t bad = 0x1990c0ffeedecade;
2980 	uint64_t top, leaf;
2981 	char path0[MAXPATHLEN];
2982 	char pathrand[MAXPATHLEN];
2983 	size_t fsize;
2984 	spa_t *spa = za->za_spa;
2985 	int bshift = SPA_MAXBLOCKSHIFT + 2;	/* don't scrog all labels */
2986 	int iters = 1000;
2987 	int maxfaults = zopt_maxfaults;
2988 	vdev_t *vd0 = NULL;
2989 	uint64_t guid0 = 0;
2990 
2991 	ASSERT(leaves >= 1);
2992 
2993 	/*
2994 	 * We need SCL_STATE here because we're going to look at vd0->vdev_tsd.
2995 	 */
2996 	spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
2997 
2998 	if (ztest_random(2) == 0) {
2999 		/*
3000 		 * Inject errors on a normal data device.
3001 		 */
3002 		top = ztest_random(spa->spa_root_vdev->vdev_children);
3003 		leaf = ztest_random(leaves);
3004 
3005 		/*
3006 		 * Generate paths to the first leaf in this top-level vdev,
3007 		 * and to the random leaf we selected.  We'll induce transient
3008 		 * write failures and random online/offline activity on leaf 0,
3009 		 * and we'll write random garbage to the randomly chosen leaf.
3010 		 */
3011 		(void) snprintf(path0, sizeof (path0), ztest_dev_template,
3012 		    zopt_dir, zopt_pool, top * leaves + 0);
3013 		(void) snprintf(pathrand, sizeof (pathrand), ztest_dev_template,
3014 		    zopt_dir, zopt_pool, top * leaves + leaf);
3015 
3016 		vd0 = vdev_lookup_by_path(spa->spa_root_vdev, path0);
3017 		if (vd0 != NULL && maxfaults != 1) {
3018 			/*
3019 			 * Make vd0 explicitly claim to be unreadable,
3020 			 * or unwriteable, or reach behind its back
3021 			 * and close the underlying fd.  We can do this if
3022 			 * maxfaults == 0 because we'll fail and reexecute,
3023 			 * and we can do it if maxfaults >= 2 because we'll
3024 			 * have enough redundancy.  If maxfaults == 1, the
3025 			 * combination of this with injection of random data
3026 			 * corruption below exceeds the pool's fault tolerance.
3027 			 */
3028 			vdev_file_t *vf = vd0->vdev_tsd;
3029 
3030 			if (vf != NULL && ztest_random(3) == 0) {
3031 				(void) close(vf->vf_vnode->v_fd);
3032 				vf->vf_vnode->v_fd = -1;
3033 			} else if (ztest_random(2) == 0) {
3034 				vd0->vdev_cant_read = B_TRUE;
3035 			} else {
3036 				vd0->vdev_cant_write = B_TRUE;
3037 			}
3038 			guid0 = vd0->vdev_guid;
3039 		}
3040 	} else {
3041 		/*
3042 		 * Inject errors on an l2cache device.
3043 		 */
3044 		spa_aux_vdev_t *sav = &spa->spa_l2cache;
3045 
3046 		if (sav->sav_count == 0) {
3047 			spa_config_exit(spa, SCL_STATE, FTAG);
3048 			return;
3049 		}
3050 		vd0 = sav->sav_vdevs[ztest_random(sav->sav_count)];
3051 		guid0 = vd0->vdev_guid;
3052 		(void) strcpy(path0, vd0->vdev_path);
3053 		(void) strcpy(pathrand, vd0->vdev_path);
3054 
3055 		leaf = 0;
3056 		leaves = 1;
3057 		maxfaults = INT_MAX;	/* no limit on cache devices */
3058 	}
3059 
3060 	spa_config_exit(spa, SCL_STATE, FTAG);
3061 
3062 	if (maxfaults == 0)
3063 		return;
3064 
3065 	/*
3066 	 * If we can tolerate two or more faults, randomly online/offline vd0.
3067 	 */
3068 	if (maxfaults >= 2 && guid0 != 0) {
3069 		if (ztest_random(10) < 6) {
3070 			int flags = (ztest_random(2) == 0 ?
3071 			    ZFS_OFFLINE_TEMPORARY : 0);
3072 			VERIFY(vdev_offline(spa, guid0, flags) != EBUSY);
3073 		} else {
3074 			(void) vdev_online(spa, guid0, 0, NULL);
3075 		}
3076 	}
3077 
3078 	/*
3079 	 * We have at least single-fault tolerance, so inject data corruption.
3080 	 */
3081 	fd = open(pathrand, O_RDWR);
3082 
3083 	if (fd == -1)	/* we hit a gap in the device namespace */
3084 		return;
3085 
3086 	fsize = lseek(fd, 0, SEEK_END);
3087 
3088 	while (--iters != 0) {
3089 		offset = ztest_random(fsize / (leaves << bshift)) *
3090 		    (leaves << bshift) + (leaf << bshift) +
3091 		    (ztest_random(1ULL << (bshift - 1)) & -8ULL);
3092 
3093 		if (offset >= fsize)
3094 			continue;
3095 
3096 		if (zopt_verbose >= 6)
3097 			(void) printf("injecting bad word into %s,"
3098 			    " offset 0x%llx\n", pathrand, (u_longlong_t)offset);
3099 
3100 		if (pwrite(fd, &bad, sizeof (bad), offset) != sizeof (bad))
3101 			fatal(1, "can't inject bad word at 0x%llx in %s",
3102 			    offset, pathrand);
3103 	}
3104 
3105 	(void) close(fd);
3106 }
3107 
3108 /*
3109  * Scrub the pool.
3110  */
3111 void
3112 ztest_scrub(ztest_args_t *za)
3113 {
3114 	spa_t *spa = za->za_spa;
3115 
3116 	(void) spa_scrub(spa, POOL_SCRUB_EVERYTHING);
3117 	(void) poll(NULL, 0, 1000); /* wait a second, then force a restart */
3118 	(void) spa_scrub(spa, POOL_SCRUB_EVERYTHING);
3119 }
3120 
3121 /*
3122  * Rename the pool to a different name and then rename it back.
3123  */
3124 void
3125 ztest_spa_rename(ztest_args_t *za)
3126 {
3127 	char *oldname, *newname;
3128 	int error;
3129 	spa_t *spa;
3130 
3131 	(void) rw_wrlock(&ztest_shared->zs_name_lock);
3132 
3133 	oldname = za->za_pool;
3134 	newname = umem_alloc(strlen(oldname) + 5, UMEM_NOFAIL);
3135 	(void) strcpy(newname, oldname);
3136 	(void) strcat(newname, "_tmp");
3137 
3138 	/*
3139 	 * Do the rename
3140 	 */
3141 	error = spa_rename(oldname, newname);
3142 	if (error)
3143 		fatal(0, "spa_rename('%s', '%s') = %d", oldname,
3144 		    newname, error);
3145 
3146 	/*
3147 	 * Try to open it under the old name, which shouldn't exist
3148 	 */
3149 	error = spa_open(oldname, &spa, FTAG);
3150 	if (error != ENOENT)
3151 		fatal(0, "spa_open('%s') = %d", oldname, error);
3152 
3153 	/*
3154 	 * Open it under the new name and make sure it's still the same spa_t.
3155 	 */
3156 	error = spa_open(newname, &spa, FTAG);
3157 	if (error != 0)
3158 		fatal(0, "spa_open('%s') = %d", newname, error);
3159 
3160 	ASSERT(spa == za->za_spa);
3161 	spa_close(spa, FTAG);
3162 
3163 	/*
3164 	 * Rename it back to the original
3165 	 */
3166 	error = spa_rename(newname, oldname);
3167 	if (error)
3168 		fatal(0, "spa_rename('%s', '%s') = %d", newname,
3169 		    oldname, error);
3170 
3171 	/*
3172 	 * Make sure it can still be opened
3173 	 */
3174 	error = spa_open(oldname, &spa, FTAG);
3175 	if (error != 0)
3176 		fatal(0, "spa_open('%s') = %d", oldname, error);
3177 
3178 	ASSERT(spa == za->za_spa);
3179 	spa_close(spa, FTAG);
3180 
3181 	umem_free(newname, strlen(newname) + 1);
3182 
3183 	(void) rw_unlock(&ztest_shared->zs_name_lock);
3184 }
3185 
3186 
3187 /*
3188  * Completely obliterate one disk.
3189  */
3190 static void
3191 ztest_obliterate_one_disk(uint64_t vdev)
3192 {
3193 	int fd;
3194 	char dev_name[MAXPATHLEN], copy_name[MAXPATHLEN];
3195 	size_t fsize;
3196 
3197 	if (zopt_maxfaults < 2)
3198 		return;
3199 
3200 	(void) sprintf(dev_name, ztest_dev_template, zopt_dir, zopt_pool, vdev);
3201 	(void) snprintf(copy_name, MAXPATHLEN, "%s.old", dev_name);
3202 
3203 	fd = open(dev_name, O_RDWR);
3204 
3205 	if (fd == -1)
3206 		fatal(1, "can't open %s", dev_name);
3207 
3208 	/*
3209 	 * Determine the size.
3210 	 */
3211 	fsize = lseek(fd, 0, SEEK_END);
3212 
3213 	(void) close(fd);
3214 
3215 	/*
3216 	 * Rename the old device to dev_name.old (useful for debugging).
3217 	 */
3218 	VERIFY(rename(dev_name, copy_name) == 0);
3219 
3220 	/*
3221 	 * Create a new one.
3222 	 */
3223 	VERIFY((fd = open(dev_name, O_RDWR | O_CREAT | O_TRUNC, 0666)) >= 0);
3224 	VERIFY(ftruncate(fd, fsize) == 0);
3225 	(void) close(fd);
3226 }
3227 
3228 static void
3229 ztest_replace_one_disk(spa_t *spa, uint64_t vdev)
3230 {
3231 	char dev_name[MAXPATHLEN];
3232 	nvlist_t *root;
3233 	int error;
3234 	uint64_t guid;
3235 	vdev_t *vd;
3236 
3237 	(void) sprintf(dev_name, ztest_dev_template, zopt_dir, zopt_pool, vdev);
3238 
3239 	/*
3240 	 * Build the nvlist describing dev_name.
3241 	 */
3242 	root = make_vdev_root(dev_name, NULL, 0, 0, 0, 0, 0, 1);
3243 
3244 	spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
3245 	if ((vd = vdev_lookup_by_path(spa->spa_root_vdev, dev_name)) == NULL)
3246 		guid = 0;
3247 	else
3248 		guid = vd->vdev_guid;
3249 	spa_config_exit(spa, SCL_VDEV, FTAG);
3250 	error = spa_vdev_attach(spa, guid, root, B_TRUE);
3251 	if (error != 0 &&
3252 	    error != EBUSY &&
3253 	    error != ENOTSUP &&
3254 	    error != ENODEV &&
3255 	    error != EDOM)
3256 		fatal(0, "spa_vdev_attach(in-place) = %d", error);
3257 
3258 	nvlist_free(root);
3259 }
3260 
3261 static void
3262 ztest_verify_blocks(char *pool)
3263 {
3264 	int status;
3265 	char zdb[MAXPATHLEN + MAXNAMELEN + 20];
3266 	char zbuf[1024];
3267 	char *bin;
3268 	char *ztest;
3269 	char *isa;
3270 	int isalen;
3271 	FILE *fp;
3272 
3273 	(void) realpath(getexecname(), zdb);
3274 
3275 	/* zdb lives in /usr/sbin, while ztest lives in /usr/bin */
3276 	bin = strstr(zdb, "/usr/bin/");
3277 	ztest = strstr(bin, "/ztest");
3278 	isa = bin + 8;
3279 	isalen = ztest - isa;
3280 	isa = strdup(isa);
3281 	/* LINTED */
3282 	(void) sprintf(bin,
3283 	    "/usr/sbin%.*s/zdb -bcc%s%s -U /tmp/zpool.cache %s",
3284 	    isalen,
3285 	    isa,
3286 	    zopt_verbose >= 3 ? "s" : "",
3287 	    zopt_verbose >= 4 ? "v" : "",
3288 	    pool);
3289 	free(isa);
3290 
3291 	if (zopt_verbose >= 5)
3292 		(void) printf("Executing %s\n", strstr(zdb, "zdb "));
3293 
3294 	fp = popen(zdb, "r");
3295 
3296 	while (fgets(zbuf, sizeof (zbuf), fp) != NULL)
3297 		if (zopt_verbose >= 3)
3298 			(void) printf("%s", zbuf);
3299 
3300 	status = pclose(fp);
3301 
3302 	if (status == 0)
3303 		return;
3304 
3305 	ztest_dump_core = 0;
3306 	if (WIFEXITED(status))
3307 		fatal(0, "'%s' exit code %d", zdb, WEXITSTATUS(status));
3308 	else
3309 		fatal(0, "'%s' died with signal %d", zdb, WTERMSIG(status));
3310 }
3311 
3312 static void
3313 ztest_walk_pool_directory(char *header)
3314 {
3315 	spa_t *spa = NULL;
3316 
3317 	if (zopt_verbose >= 6)
3318 		(void) printf("%s\n", header);
3319 
3320 	mutex_enter(&spa_namespace_lock);
3321 	while ((spa = spa_next(spa)) != NULL)
3322 		if (zopt_verbose >= 6)
3323 			(void) printf("\t%s\n", spa_name(spa));
3324 	mutex_exit(&spa_namespace_lock);
3325 }
3326 
3327 static void
3328 ztest_spa_import_export(char *oldname, char *newname)
3329 {
3330 	nvlist_t *config, *newconfig;
3331 	uint64_t pool_guid;
3332 	spa_t *spa;
3333 	int error;
3334 
3335 	if (zopt_verbose >= 4) {
3336 		(void) printf("import/export: old = %s, new = %s\n",
3337 		    oldname, newname);
3338 	}
3339 
3340 	/*
3341 	 * Clean up from previous runs.
3342 	 */
3343 	(void) spa_destroy(newname);
3344 
3345 	/*
3346 	 * Get the pool's configuration and guid.
3347 	 */
3348 	error = spa_open(oldname, &spa, FTAG);
3349 	if (error)
3350 		fatal(0, "spa_open('%s') = %d", oldname, error);
3351 
3352 	/*
3353 	 * Kick off a scrub to tickle scrub/export races.
3354 	 */
3355 	if (ztest_random(2) == 0)
3356 		(void) spa_scrub(spa, POOL_SCRUB_EVERYTHING);
3357 
3358 	pool_guid = spa_guid(spa);
3359 	spa_close(spa, FTAG);
3360 
3361 	ztest_walk_pool_directory("pools before export");
3362 
3363 	/*
3364 	 * Export it.
3365 	 */
3366 	error = spa_export(oldname, &config, B_FALSE, B_FALSE);
3367 	if (error)
3368 		fatal(0, "spa_export('%s') = %d", oldname, error);
3369 
3370 	ztest_walk_pool_directory("pools after export");
3371 
3372 	/*
3373 	 * Try to import it.
3374 	 */
3375 	newconfig = spa_tryimport(config);
3376 	ASSERT(newconfig != NULL);
3377 	nvlist_free(newconfig);
3378 
3379 	/*
3380 	 * Import it under the new name.
3381 	 */
3382 	error = spa_import(newname, config, NULL);
3383 	if (error)
3384 		fatal(0, "spa_import('%s') = %d", newname, error);
3385 
3386 	ztest_walk_pool_directory("pools after import");
3387 
3388 	/*
3389 	 * Try to import it again -- should fail with EEXIST.
3390 	 */
3391 	error = spa_import(newname, config, NULL);
3392 	if (error != EEXIST)
3393 		fatal(0, "spa_import('%s') twice", newname);
3394 
3395 	/*
3396 	 * Try to import it under a different name -- should fail with EEXIST.
3397 	 */
3398 	error = spa_import(oldname, config, NULL);
3399 	if (error != EEXIST)
3400 		fatal(0, "spa_import('%s') under multiple names", newname);
3401 
3402 	/*
3403 	 * Verify that the pool is no longer visible under the old name.
3404 	 */
3405 	error = spa_open(oldname, &spa, FTAG);
3406 	if (error != ENOENT)
3407 		fatal(0, "spa_open('%s') = %d", newname, error);
3408 
3409 	/*
3410 	 * Verify that we can open and close the pool using the new name.
3411 	 */
3412 	error = spa_open(newname, &spa, FTAG);
3413 	if (error)
3414 		fatal(0, "spa_open('%s') = %d", newname, error);
3415 	ASSERT(pool_guid == spa_guid(spa));
3416 	spa_close(spa, FTAG);
3417 
3418 	nvlist_free(config);
3419 }
3420 
3421 static void
3422 ztest_resume(spa_t *spa)
3423 {
3424 	if (spa_suspended(spa)) {
3425 		spa_vdev_state_enter(spa);
3426 		vdev_clear(spa, NULL);
3427 		(void) spa_vdev_state_exit(spa, NULL, 0);
3428 		(void) zio_resume(spa);
3429 	}
3430 }
3431 
3432 static void *
3433 ztest_resume_thread(void *arg)
3434 {
3435 	spa_t *spa = arg;
3436 
3437 	while (!ztest_exiting) {
3438 		(void) poll(NULL, 0, 1000);
3439 		ztest_resume(spa);
3440 	}
3441 	return (NULL);
3442 }
3443 
3444 static void *
3445 ztest_thread(void *arg)
3446 {
3447 	ztest_args_t *za = arg;
3448 	ztest_shared_t *zs = ztest_shared;
3449 	hrtime_t now, functime;
3450 	ztest_info_t *zi;
3451 	int f, i;
3452 
3453 	while ((now = gethrtime()) < za->za_stop) {
3454 		/*
3455 		 * See if it's time to force a crash.
3456 		 */
3457 		if (now > za->za_kill) {
3458 			zs->zs_alloc = spa_get_alloc(za->za_spa);
3459 			zs->zs_space = spa_get_space(za->za_spa);
3460 			(void) kill(getpid(), SIGKILL);
3461 		}
3462 
3463 		/*
3464 		 * Pick a random function.
3465 		 */
3466 		f = ztest_random(ZTEST_FUNCS);
3467 		zi = &zs->zs_info[f];
3468 
3469 		/*
3470 		 * Decide whether to call it, based on the requested frequency.
3471 		 */
3472 		if (zi->zi_call_target == 0 ||
3473 		    (double)zi->zi_call_total / zi->zi_call_target >
3474 		    (double)(now - zs->zs_start_time) / (zopt_time * NANOSEC))
3475 			continue;
3476 
3477 		atomic_add_64(&zi->zi_calls, 1);
3478 		atomic_add_64(&zi->zi_call_total, 1);
3479 
3480 		za->za_diroff = (za->za_instance * ZTEST_FUNCS + f) *
3481 		    ZTEST_DIRSIZE;
3482 		za->za_diroff_shared = (1ULL << 63);
3483 
3484 		for (i = 0; i < zi->zi_iters; i++)
3485 			zi->zi_func(za);
3486 
3487 		functime = gethrtime() - now;
3488 
3489 		atomic_add_64(&zi->zi_call_time, functime);
3490 
3491 		if (zopt_verbose >= 4) {
3492 			Dl_info dli;
3493 			(void) dladdr((void *)zi->zi_func, &dli);
3494 			(void) printf("%6.2f sec in %s\n",
3495 			    (double)functime / NANOSEC, dli.dli_sname);
3496 		}
3497 
3498 		/*
3499 		 * If we're getting ENOSPC with some regularity, stop.
3500 		 */
3501 		if (zs->zs_enospc_count > 10)
3502 			break;
3503 	}
3504 
3505 	return (NULL);
3506 }
3507 
3508 /*
3509  * Kick off threads to run tests on all datasets in parallel.
3510  */
3511 static void
3512 ztest_run(char *pool)
3513 {
3514 	int t, d, error;
3515 	ztest_shared_t *zs = ztest_shared;
3516 	ztest_args_t *za;
3517 	spa_t *spa;
3518 	char name[100];
3519 	thread_t resume_tid;
3520 
3521 	ztest_exiting = B_FALSE;
3522 
3523 	(void) _mutex_init(&zs->zs_vdev_lock, USYNC_THREAD, NULL);
3524 	(void) rwlock_init(&zs->zs_name_lock, USYNC_THREAD, NULL);
3525 
3526 	for (t = 0; t < ZTEST_SYNC_LOCKS; t++)
3527 		(void) _mutex_init(&zs->zs_sync_lock[t], USYNC_THREAD, NULL);
3528 
3529 	/*
3530 	 * Destroy one disk before we even start.
3531 	 * It's mirrored, so everything should work just fine.
3532 	 * This makes us exercise fault handling very early in spa_load().
3533 	 */
3534 	ztest_obliterate_one_disk(0);
3535 
3536 	/*
3537 	 * Verify that the sum of the sizes of all blocks in the pool
3538 	 * equals the SPA's allocated space total.
3539 	 */
3540 	ztest_verify_blocks(pool);
3541 
3542 	/*
3543 	 * Kick off a replacement of the disk we just obliterated.
3544 	 */
3545 	kernel_init(FREAD | FWRITE);
3546 	VERIFY(spa_open(pool, &spa, FTAG) == 0);
3547 	ztest_replace_one_disk(spa, 0);
3548 	if (zopt_verbose >= 5)
3549 		show_pool_stats(spa);
3550 	spa_close(spa, FTAG);
3551 	kernel_fini();
3552 
3553 	kernel_init(FREAD | FWRITE);
3554 
3555 	/*
3556 	 * Verify that we can export the pool and reimport it under a
3557 	 * different name.
3558 	 */
3559 	if (ztest_random(2) == 0) {
3560 		(void) snprintf(name, 100, "%s_import", pool);
3561 		ztest_spa_import_export(pool, name);
3562 		ztest_spa_import_export(name, pool);
3563 	}
3564 
3565 	/*
3566 	 * Verify that we can loop over all pools.
3567 	 */
3568 	mutex_enter(&spa_namespace_lock);
3569 	for (spa = spa_next(NULL); spa != NULL; spa = spa_next(spa)) {
3570 		if (zopt_verbose > 3) {
3571 			(void) printf("spa_next: found %s\n", spa_name(spa));
3572 		}
3573 	}
3574 	mutex_exit(&spa_namespace_lock);
3575 
3576 	/*
3577 	 * Open our pool.
3578 	 */
3579 	VERIFY(spa_open(pool, &spa, FTAG) == 0);
3580 
3581 	/*
3582 	 * We don't expect the pool to suspend unless maxfaults == 0,
3583 	 * in which case ztest_fault_inject() temporarily takes away
3584 	 * the only valid replica.
3585 	 */
3586 	if (zopt_maxfaults == 0)
3587 		spa->spa_failmode = ZIO_FAILURE_MODE_WAIT;
3588 	else
3589 		spa->spa_failmode = ZIO_FAILURE_MODE_PANIC;
3590 
3591 	/*
3592 	 * Create a thread to periodically resume suspended I/O.
3593 	 */
3594 	VERIFY(thr_create(0, 0, ztest_resume_thread, spa, THR_BOUND,
3595 	    &resume_tid) == 0);
3596 
3597 	/*
3598 	 * Verify that we can safely inquire about about any object,
3599 	 * whether it's allocated or not.  To make it interesting,
3600 	 * we probe a 5-wide window around each power of two.
3601 	 * This hits all edge cases, including zero and the max.
3602 	 */
3603 	for (t = 0; t < 64; t++) {
3604 		for (d = -5; d <= 5; d++) {
3605 			error = dmu_object_info(spa->spa_meta_objset,
3606 			    (1ULL << t) + d, NULL);
3607 			ASSERT(error == 0 || error == ENOENT ||
3608 			    error == EINVAL);
3609 		}
3610 	}
3611 
3612 	/*
3613 	 * Now kick off all the tests that run in parallel.
3614 	 */
3615 	zs->zs_enospc_count = 0;
3616 
3617 	za = umem_zalloc(zopt_threads * sizeof (ztest_args_t), UMEM_NOFAIL);
3618 
3619 	if (zopt_verbose >= 4)
3620 		(void) printf("starting main threads...\n");
3621 
3622 	za[0].za_start = gethrtime();
3623 	za[0].za_stop = za[0].za_start + zopt_passtime * NANOSEC;
3624 	za[0].za_stop = MIN(za[0].za_stop, zs->zs_stop_time);
3625 	za[0].za_kill = za[0].za_stop;
3626 	if (ztest_random(100) < zopt_killrate)
3627 		za[0].za_kill -= ztest_random(zopt_passtime * NANOSEC);
3628 
3629 	for (t = 0; t < zopt_threads; t++) {
3630 		d = t % zopt_datasets;
3631 
3632 		(void) strcpy(za[t].za_pool, pool);
3633 		za[t].za_os = za[d].za_os;
3634 		za[t].za_spa = spa;
3635 		za[t].za_zilog = za[d].za_zilog;
3636 		za[t].za_instance = t;
3637 		za[t].za_random = ztest_random(-1ULL);
3638 		za[t].za_start = za[0].za_start;
3639 		za[t].za_stop = za[0].za_stop;
3640 		za[t].za_kill = za[0].za_kill;
3641 
3642 		if (t < zopt_datasets) {
3643 			int test_future = FALSE;
3644 			(void) rw_rdlock(&ztest_shared->zs_name_lock);
3645 			(void) snprintf(name, 100, "%s/%s_%d", pool, pool, d);
3646 			error = dmu_objset_create(name, DMU_OST_OTHER, NULL, 0,
3647 			    ztest_create_cb, NULL);
3648 			if (error == EEXIST) {
3649 				test_future = TRUE;
3650 			} else if (error == ENOSPC) {
3651 				zs->zs_enospc_count++;
3652 				(void) rw_unlock(&ztest_shared->zs_name_lock);
3653 				break;
3654 			} else if (error != 0) {
3655 				fatal(0, "dmu_objset_create(%s) = %d",
3656 				    name, error);
3657 			}
3658 			error = dmu_objset_open(name, DMU_OST_OTHER,
3659 			    DS_MODE_USER, &za[d].za_os);
3660 			if (error)
3661 				fatal(0, "dmu_objset_open('%s') = %d",
3662 				    name, error);
3663 			(void) rw_unlock(&ztest_shared->zs_name_lock);
3664 			if (test_future)
3665 				ztest_dmu_check_future_leak(&za[t]);
3666 			zil_replay(za[d].za_os, za[d].za_os,
3667 			    ztest_replay_vector);
3668 			za[d].za_zilog = zil_open(za[d].za_os, NULL);
3669 		}
3670 
3671 		VERIFY(thr_create(0, 0, ztest_thread, &za[t], THR_BOUND,
3672 		    &za[t].za_thread) == 0);
3673 	}
3674 
3675 	while (--t >= 0) {
3676 		VERIFY(thr_join(za[t].za_thread, NULL, NULL) == 0);
3677 		if (t < zopt_datasets) {
3678 			zil_close(za[t].za_zilog);
3679 			dmu_objset_close(za[t].za_os);
3680 		}
3681 	}
3682 
3683 	if (zopt_verbose >= 3)
3684 		show_pool_stats(spa);
3685 
3686 	txg_wait_synced(spa_get_dsl(spa), 0);
3687 
3688 	zs->zs_alloc = spa_get_alloc(spa);
3689 	zs->zs_space = spa_get_space(spa);
3690 
3691 	/*
3692 	 * If we had out-of-space errors, destroy a random objset.
3693 	 */
3694 	if (zs->zs_enospc_count != 0) {
3695 		(void) rw_rdlock(&ztest_shared->zs_name_lock);
3696 		d = (int)ztest_random(zopt_datasets);
3697 		(void) snprintf(name, 100, "%s/%s_%d", pool, pool, d);
3698 		if (zopt_verbose >= 3)
3699 			(void) printf("Destroying %s to free up space\n", name);
3700 
3701 		/* Cleanup any non-standard clones and snapshots */
3702 		ztest_dsl_dataset_cleanup(name, za[d].za_instance);
3703 
3704 		(void) dmu_objset_find(name, ztest_destroy_cb, &za[d],
3705 		    DS_FIND_SNAPSHOTS | DS_FIND_CHILDREN);
3706 		(void) rw_unlock(&ztest_shared->zs_name_lock);
3707 	}
3708 
3709 	txg_wait_synced(spa_get_dsl(spa), 0);
3710 
3711 	umem_free(za, zopt_threads * sizeof (ztest_args_t));
3712 
3713 	/* Kill the resume thread */
3714 	ztest_exiting = B_TRUE;
3715 	VERIFY(thr_join(resume_tid, NULL, NULL) == 0);
3716 	ztest_resume(spa);
3717 
3718 	/*
3719 	 * Right before closing the pool, kick off a bunch of async I/O;
3720 	 * spa_close() should wait for it to complete.
3721 	 */
3722 	for (t = 1; t < 50; t++)
3723 		dmu_prefetch(spa->spa_meta_objset, t, 0, 1 << 15);
3724 
3725 	spa_close(spa, FTAG);
3726 
3727 	kernel_fini();
3728 }
3729 
3730 void
3731 print_time(hrtime_t t, char *timebuf)
3732 {
3733 	hrtime_t s = t / NANOSEC;
3734 	hrtime_t m = s / 60;
3735 	hrtime_t h = m / 60;
3736 	hrtime_t d = h / 24;
3737 
3738 	s -= m * 60;
3739 	m -= h * 60;
3740 	h -= d * 24;
3741 
3742 	timebuf[0] = '\0';
3743 
3744 	if (d)
3745 		(void) sprintf(timebuf,
3746 		    "%llud%02lluh%02llum%02llus", d, h, m, s);
3747 	else if (h)
3748 		(void) sprintf(timebuf, "%lluh%02llum%02llus", h, m, s);
3749 	else if (m)
3750 		(void) sprintf(timebuf, "%llum%02llus", m, s);
3751 	else
3752 		(void) sprintf(timebuf, "%llus", s);
3753 }
3754 
3755 /*
3756  * Create a storage pool with the given name and initial vdev size.
3757  * Then create the specified number of datasets in the pool.
3758  */
3759 static void
3760 ztest_init(char *pool)
3761 {
3762 	spa_t *spa;
3763 	int error;
3764 	nvlist_t *nvroot;
3765 
3766 	kernel_init(FREAD | FWRITE);
3767 
3768 	/*
3769 	 * Create the storage pool.
3770 	 */
3771 	(void) spa_destroy(pool);
3772 	ztest_shared->zs_vdev_primaries = 0;
3773 	nvroot = make_vdev_root(NULL, NULL, zopt_vdev_size, 0,
3774 	    0, zopt_raidz, zopt_mirrors, 1);
3775 	error = spa_create(pool, nvroot, NULL, NULL, NULL);
3776 	nvlist_free(nvroot);
3777 
3778 	if (error)
3779 		fatal(0, "spa_create() = %d", error);
3780 	error = spa_open(pool, &spa, FTAG);
3781 	if (error)
3782 		fatal(0, "spa_open() = %d", error);
3783 
3784 	metaslab_sz = 1ULL << spa->spa_root_vdev->vdev_child[0]->vdev_ms_shift;
3785 
3786 	if (zopt_verbose >= 3)
3787 		show_pool_stats(spa);
3788 
3789 	spa_close(spa, FTAG);
3790 
3791 	kernel_fini();
3792 }
3793 
3794 int
3795 main(int argc, char **argv)
3796 {
3797 	int kills = 0;
3798 	int iters = 0;
3799 	int i, f;
3800 	ztest_shared_t *zs;
3801 	ztest_info_t *zi;
3802 	char timebuf[100];
3803 	char numbuf[6];
3804 
3805 	(void) setvbuf(stdout, NULL, _IOLBF, 0);
3806 
3807 	/* Override location of zpool.cache */
3808 	spa_config_path = "/tmp/zpool.cache";
3809 
3810 	ztest_random_fd = open("/dev/urandom", O_RDONLY);
3811 
3812 	process_options(argc, argv);
3813 
3814 	/*
3815 	 * Blow away any existing copy of zpool.cache
3816 	 */
3817 	if (zopt_init != 0)
3818 		(void) remove("/tmp/zpool.cache");
3819 
3820 	zs = ztest_shared = (void *)mmap(0,
3821 	    P2ROUNDUP(sizeof (ztest_shared_t), getpagesize()),
3822 	    PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANON, -1, 0);
3823 
3824 	if (zopt_verbose >= 1) {
3825 		(void) printf("%llu vdevs, %d datasets, %d threads,"
3826 		    " %llu seconds...\n",
3827 		    (u_longlong_t)zopt_vdevs, zopt_datasets, zopt_threads,
3828 		    (u_longlong_t)zopt_time);
3829 	}
3830 
3831 	/*
3832 	 * Create and initialize our storage pool.
3833 	 */
3834 	for (i = 1; i <= zopt_init; i++) {
3835 		bzero(zs, sizeof (ztest_shared_t));
3836 		if (zopt_verbose >= 3 && zopt_init != 1)
3837 			(void) printf("ztest_init(), pass %d\n", i);
3838 		ztest_init(zopt_pool);
3839 	}
3840 
3841 	/*
3842 	 * Initialize the call targets for each function.
3843 	 */
3844 	for (f = 0; f < ZTEST_FUNCS; f++) {
3845 		zi = &zs->zs_info[f];
3846 
3847 		*zi = ztest_info[f];
3848 
3849 		if (*zi->zi_interval == 0)
3850 			zi->zi_call_target = UINT64_MAX;
3851 		else
3852 			zi->zi_call_target = zopt_time / *zi->zi_interval;
3853 	}
3854 
3855 	zs->zs_start_time = gethrtime();
3856 	zs->zs_stop_time = zs->zs_start_time + zopt_time * NANOSEC;
3857 
3858 	/*
3859 	 * Run the tests in a loop.  These tests include fault injection
3860 	 * to verify that self-healing data works, and forced crashes
3861 	 * to verify that we never lose on-disk consistency.
3862 	 */
3863 	while (gethrtime() < zs->zs_stop_time) {
3864 		int status;
3865 		pid_t pid;
3866 		char *tmp;
3867 
3868 		/*
3869 		 * Initialize the workload counters for each function.
3870 		 */
3871 		for (f = 0; f < ZTEST_FUNCS; f++) {
3872 			zi = &zs->zs_info[f];
3873 			zi->zi_calls = 0;
3874 			zi->zi_call_time = 0;
3875 		}
3876 
3877 		/* Set the allocation switch size */
3878 		metaslab_df_alloc_threshold = ztest_random(metaslab_sz / 4) + 1;
3879 
3880 		pid = fork();
3881 
3882 		if (pid == -1)
3883 			fatal(1, "fork failed");
3884 
3885 		if (pid == 0) {	/* child */
3886 			struct rlimit rl = { 1024, 1024 };
3887 			(void) setrlimit(RLIMIT_NOFILE, &rl);
3888 			(void) enable_extended_FILE_stdio(-1, -1);
3889 			ztest_run(zopt_pool);
3890 			exit(0);
3891 		}
3892 
3893 		while (waitpid(pid, &status, 0) != pid)
3894 			continue;
3895 
3896 		if (WIFEXITED(status)) {
3897 			if (WEXITSTATUS(status) != 0) {
3898 				(void) fprintf(stderr,
3899 				    "child exited with code %d\n",
3900 				    WEXITSTATUS(status));
3901 				exit(2);
3902 			}
3903 		} else if (WIFSIGNALED(status)) {
3904 			if (WTERMSIG(status) != SIGKILL) {
3905 				(void) fprintf(stderr,
3906 				    "child died with signal %d\n",
3907 				    WTERMSIG(status));
3908 				exit(3);
3909 			}
3910 			kills++;
3911 		} else {
3912 			(void) fprintf(stderr, "something strange happened "
3913 			    "to child\n");
3914 			exit(4);
3915 		}
3916 
3917 		iters++;
3918 
3919 		if (zopt_verbose >= 1) {
3920 			hrtime_t now = gethrtime();
3921 
3922 			now = MIN(now, zs->zs_stop_time);
3923 			print_time(zs->zs_stop_time - now, timebuf);
3924 			nicenum(zs->zs_space, numbuf);
3925 
3926 			(void) printf("Pass %3d, %8s, %3llu ENOSPC, "
3927 			    "%4.1f%% of %5s used, %3.0f%% done, %8s to go\n",
3928 			    iters,
3929 			    WIFEXITED(status) ? "Complete" : "SIGKILL",
3930 			    (u_longlong_t)zs->zs_enospc_count,
3931 			    100.0 * zs->zs_alloc / zs->zs_space,
3932 			    numbuf,
3933 			    100.0 * (now - zs->zs_start_time) /
3934 			    (zopt_time * NANOSEC), timebuf);
3935 		}
3936 
3937 		if (zopt_verbose >= 2) {
3938 			(void) printf("\nWorkload summary:\n\n");
3939 			(void) printf("%7s %9s   %s\n",
3940 			    "Calls", "Time", "Function");
3941 			(void) printf("%7s %9s   %s\n",
3942 			    "-----", "----", "--------");
3943 			for (f = 0; f < ZTEST_FUNCS; f++) {
3944 				Dl_info dli;
3945 
3946 				zi = &zs->zs_info[f];
3947 				print_time(zi->zi_call_time, timebuf);
3948 				(void) dladdr((void *)zi->zi_func, &dli);
3949 				(void) printf("%7llu %9s   %s\n",
3950 				    (u_longlong_t)zi->zi_calls, timebuf,
3951 				    dli.dli_sname);
3952 			}
3953 			(void) printf("\n");
3954 		}
3955 
3956 		/*
3957 		 * It's possible that we killed a child during a rename test, in
3958 		 * which case we'll have a 'ztest_tmp' pool lying around instead
3959 		 * of 'ztest'.  Do a blind rename in case this happened.
3960 		 */
3961 		tmp = umem_alloc(strlen(zopt_pool) + 5, UMEM_NOFAIL);
3962 		(void) strcpy(tmp, zopt_pool);
3963 		(void) strcat(tmp, "_tmp");
3964 		kernel_init(FREAD | FWRITE);
3965 		(void) spa_rename(tmp, zopt_pool);
3966 		kernel_fini();
3967 		umem_free(tmp, strlen(tmp) + 1);
3968 	}
3969 
3970 	ztest_verify_blocks(zopt_pool);
3971 
3972 	if (zopt_verbose >= 1) {
3973 		(void) printf("%d killed, %d completed, %.0f%% kill rate\n",
3974 		    kills, iters - kills, (100.0 * kills) / MAX(1, iters));
3975 	}
3976 
3977 	return (0);
3978 }
3979