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