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