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