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