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