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