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