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 (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23 * Copyright (c) 2011, 2017 by Delphix. All rights reserved.
24 * Copyright 2011 Nexenta Systems, Inc.  All rights reserved.
25 * Copyright (c) 2012 Martin Matuska <mm@FreeBSD.org>.  All rights reserved.
26 * Copyright (c) 2013 Steven Hartland. All rights reserved.
27 * Copyright (c) 2014 Integros [integros.com]
28 * Copyright 2017 Joyent, Inc.
29 * Copyright 2017 RackTop Systems.
30 */
31
32/*
33 * The objective of this program is to provide a DMU/ZAP/SPA stress test
34 * that runs entirely in userland, is easy to use, and easy to extend.
35 *
36 * The overall design of the ztest program is as follows:
37 *
38 * (1) For each major functional area (e.g. adding vdevs to a pool,
39 *     creating and destroying datasets, reading and writing objects, etc)
40 *     we have a simple routine to test that functionality.  These
41 *     individual routines do not have to do anything "stressful".
42 *
43 * (2) We turn these simple functionality tests into a stress test by
44 *     running them all in parallel, with as many threads as desired,
45 *     and spread across as many datasets, objects, and vdevs as desired.
46 *
47 * (3) While all this is happening, we inject faults into the pool to
48 *     verify that self-healing data really works.
49 *
50 * (4) Every time we open a dataset, we change its checksum and compression
51 *     functions.  Thus even individual objects vary from block to block
52 *     in which checksum they use and whether they're compressed.
53 *
54 * (5) To verify that we never lose on-disk consistency after a crash,
55 *     we run the entire test in a child of the main process.
56 *     At random times, the child self-immolates with a SIGKILL.
57 *     This is the software equivalent of pulling the power cord.
58 *     The parent then runs the test again, using the existing
59 *     storage pool, as many times as desired. If backwards compatibility
60 *     testing is enabled ztest will sometimes run the "older" version
61 *     of ztest after a SIGKILL.
62 *
63 * (6) To verify that we don't have future leaks or temporal incursions,
64 *     many of the functional tests record the transaction group number
65 *     as part of their data.  When reading old data, they verify that
66 *     the transaction group number is less than the current, open txg.
67 *     If you add a new test, please do this if applicable.
68 *
69 * When run with no arguments, ztest runs for about five minutes and
70 * produces no output if successful.  To get a little bit of information,
71 * specify -V.  To get more information, specify -VV, and so on.
72 *
73 * To turn this into an overnight stress test, use -T to specify run time.
74 *
75 * You can ask more more vdevs [-v], datasets [-d], or threads [-t]
76 * to increase the pool capacity, fanout, and overall stress level.
77 *
78 * Use the -k option to set the desired frequency of kills.
79 *
80 * When ztest invokes itself it passes all relevant information through a
81 * temporary file which is mmap-ed in the child process. This allows shared
82 * memory to survive the exec syscall. The ztest_shared_hdr_t struct is always
83 * stored at offset 0 of this file and contains information on the size and
84 * number of shared structures in the file. The information stored in this file
85 * must remain backwards compatible with older versions of ztest so that
86 * ztest can invoke them during backwards compatibility testing (-B).
87 */
88
89#include <sys/zfs_context.h>
90#include <sys/spa.h>
91#include <sys/dmu.h>
92#include <sys/txg.h>
93#include <sys/dbuf.h>
94#include <sys/zap.h>
95#include <sys/dmu_objset.h>
96#include <sys/poll.h>
97#include <sys/stat.h>
98#include <sys/time.h>
99#include <sys/wait.h>
100#include <sys/mman.h>
101#include <sys/resource.h>
102#include <sys/zio.h>
103#include <sys/zil.h>
104#include <sys/zil_impl.h>
105#include <sys/vdev_impl.h>
106#include <sys/vdev_file.h>
107#include <sys/vdev_initialize.h>
108#include <sys/spa_impl.h>
109#include <sys/metaslab_impl.h>
110#include <sys/dsl_prop.h>
111#include <sys/dsl_dataset.h>
112#include <sys/dsl_destroy.h>
113#include <sys/dsl_scan.h>
114#include <sys/zio_checksum.h>
115#include <sys/refcount.h>
116#include <sys/zfeature.h>
117#include <sys/dsl_userhold.h>
118#include <sys/abd.h>
119#include <stdio.h>
120#include <stdio_ext.h>
121#include <stdlib.h>
122#include <unistd.h>
123#include <signal.h>
124#include <umem.h>
125#include <dlfcn.h>
126#include <ctype.h>
127#include <math.h>
128#include <errno.h>
129#include <sys/fs/zfs.h>
130#include <libnvpair.h>
131#include <libcmdutils.h>
132
133static int ztest_fd_data = -1;
134static int ztest_fd_rand = -1;
135
136typedef struct ztest_shared_hdr {
137	uint64_t	zh_hdr_size;
138	uint64_t	zh_opts_size;
139	uint64_t	zh_size;
140	uint64_t	zh_stats_size;
141	uint64_t	zh_stats_count;
142	uint64_t	zh_ds_size;
143	uint64_t	zh_ds_count;
144} ztest_shared_hdr_t;
145
146static ztest_shared_hdr_t *ztest_shared_hdr;
147
148typedef struct ztest_shared_opts {
149	char zo_pool[ZFS_MAX_DATASET_NAME_LEN];
150	char zo_dir[ZFS_MAX_DATASET_NAME_LEN];
151	char zo_alt_ztest[MAXNAMELEN];
152	char zo_alt_libpath[MAXNAMELEN];
153	uint64_t zo_vdevs;
154	uint64_t zo_vdevtime;
155	size_t zo_vdev_size;
156	int zo_ashift;
157	int zo_mirrors;
158	int zo_raidz;
159	int zo_raidz_parity;
160	int zo_datasets;
161	int zo_threads;
162	uint64_t zo_passtime;
163	uint64_t zo_killrate;
164	int zo_verbose;
165	int zo_init;
166	uint64_t zo_time;
167	uint64_t zo_maxloops;
168	uint64_t zo_metaslab_force_ganging;
169} ztest_shared_opts_t;
170
171static const ztest_shared_opts_t ztest_opts_defaults = {
172	.zo_pool = { 'z', 't', 'e', 's', 't', '\0' },
173	.zo_dir = { '/', 't', 'm', 'p', '\0' },
174	.zo_alt_ztest = { '\0' },
175	.zo_alt_libpath = { '\0' },
176	.zo_vdevs = 5,
177	.zo_ashift = SPA_MINBLOCKSHIFT,
178	.zo_mirrors = 2,
179	.zo_raidz = 4,
180	.zo_raidz_parity = 1,
181	.zo_vdev_size = SPA_MINDEVSIZE * 4,	/* 256m default size */
182	.zo_datasets = 7,
183	.zo_threads = 23,
184	.zo_passtime = 60,		/* 60 seconds */
185	.zo_killrate = 70,		/* 70% kill rate */
186	.zo_verbose = 0,
187	.zo_init = 1,
188	.zo_time = 300,			/* 5 minutes */
189	.zo_maxloops = 50,		/* max loops during spa_freeze() */
190	.zo_metaslab_force_ganging = 32 << 10
191};
192
193extern uint64_t metaslab_force_ganging;
194extern uint64_t metaslab_df_alloc_threshold;
195extern uint64_t zfs_deadman_synctime_ms;
196extern int metaslab_preload_limit;
197extern boolean_t zfs_compressed_arc_enabled;
198extern boolean_t zfs_abd_scatter_enabled;
199extern boolean_t zfs_force_some_double_word_sm_entries;
200
201static ztest_shared_opts_t *ztest_shared_opts;
202static ztest_shared_opts_t ztest_opts;
203
204typedef struct ztest_shared_ds {
205	uint64_t	zd_seq;
206} ztest_shared_ds_t;
207
208static ztest_shared_ds_t *ztest_shared_ds;
209#define	ZTEST_GET_SHARED_DS(d) (&ztest_shared_ds[d])
210
211#define	BT_MAGIC	0x123456789abcdefULL
212#define	MAXFAULTS() \
213	(MAX(zs->zs_mirrors, 1) * (ztest_opts.zo_raidz_parity + 1) - 1)
214
215enum ztest_io_type {
216	ZTEST_IO_WRITE_TAG,
217	ZTEST_IO_WRITE_PATTERN,
218	ZTEST_IO_WRITE_ZEROES,
219	ZTEST_IO_TRUNCATE,
220	ZTEST_IO_SETATTR,
221	ZTEST_IO_REWRITE,
222	ZTEST_IO_TYPES
223};
224
225typedef struct ztest_block_tag {
226	uint64_t	bt_magic;
227	uint64_t	bt_objset;
228	uint64_t	bt_object;
229	uint64_t	bt_offset;
230	uint64_t	bt_gen;
231	uint64_t	bt_txg;
232	uint64_t	bt_crtxg;
233} ztest_block_tag_t;
234
235typedef struct bufwad {
236	uint64_t	bw_index;
237	uint64_t	bw_txg;
238	uint64_t	bw_data;
239} bufwad_t;
240
241/*
242 * XXX -- fix zfs range locks to be generic so we can use them here.
243 */
244typedef enum {
245	RL_READER,
246	RL_WRITER,
247	RL_APPEND
248} rl_type_t;
249
250typedef struct rll {
251	void		*rll_writer;
252	int		rll_readers;
253	kmutex_t	rll_lock;
254	kcondvar_t	rll_cv;
255} rll_t;
256
257typedef struct rl {
258	uint64_t	rl_object;
259	uint64_t	rl_offset;
260	uint64_t	rl_size;
261	rll_t		*rl_lock;
262} rl_t;
263
264#define	ZTEST_RANGE_LOCKS	64
265#define	ZTEST_OBJECT_LOCKS	64
266
267/*
268 * Object descriptor.  Used as a template for object lookup/create/remove.
269 */
270typedef struct ztest_od {
271	uint64_t	od_dir;
272	uint64_t	od_object;
273	dmu_object_type_t od_type;
274	dmu_object_type_t od_crtype;
275	uint64_t	od_blocksize;
276	uint64_t	od_crblocksize;
277	uint64_t	od_gen;
278	uint64_t	od_crgen;
279	char		od_name[ZFS_MAX_DATASET_NAME_LEN];
280} ztest_od_t;
281
282/*
283 * Per-dataset state.
284 */
285typedef struct ztest_ds {
286	ztest_shared_ds_t *zd_shared;
287	objset_t	*zd_os;
288	krwlock_t	zd_zilog_lock;
289	zilog_t		*zd_zilog;
290	ztest_od_t	*zd_od;		/* debugging aid */
291	char		zd_name[ZFS_MAX_DATASET_NAME_LEN];
292	kmutex_t	zd_dirobj_lock;
293	rll_t		zd_object_lock[ZTEST_OBJECT_LOCKS];
294	rll_t		zd_range_lock[ZTEST_RANGE_LOCKS];
295} ztest_ds_t;
296
297/*
298 * Per-iteration state.
299 */
300typedef void ztest_func_t(ztest_ds_t *zd, uint64_t id);
301
302typedef struct ztest_info {
303	ztest_func_t	*zi_func;	/* test function */
304	uint64_t	zi_iters;	/* iterations per execution */
305	uint64_t	*zi_interval;	/* execute every <interval> seconds */
306} ztest_info_t;
307
308typedef struct ztest_shared_callstate {
309	uint64_t	zc_count;	/* per-pass count */
310	uint64_t	zc_time;	/* per-pass time */
311	uint64_t	zc_next;	/* next time to call this function */
312} ztest_shared_callstate_t;
313
314static ztest_shared_callstate_t *ztest_shared_callstate;
315#define	ZTEST_GET_SHARED_CALLSTATE(c) (&ztest_shared_callstate[c])
316
317/*
318 * Note: these aren't static because we want dladdr() to work.
319 */
320ztest_func_t ztest_dmu_read_write;
321ztest_func_t ztest_dmu_write_parallel;
322ztest_func_t ztest_dmu_object_alloc_free;
323ztest_func_t ztest_dmu_commit_callbacks;
324ztest_func_t ztest_zap;
325ztest_func_t ztest_zap_parallel;
326ztest_func_t ztest_zil_commit;
327ztest_func_t ztest_zil_remount;
328ztest_func_t ztest_dmu_read_write_zcopy;
329ztest_func_t ztest_dmu_objset_create_destroy;
330ztest_func_t ztest_dmu_prealloc;
331ztest_func_t ztest_fzap;
332ztest_func_t ztest_dmu_snapshot_create_destroy;
333ztest_func_t ztest_dsl_prop_get_set;
334ztest_func_t ztest_spa_prop_get_set;
335ztest_func_t ztest_spa_create_destroy;
336ztest_func_t ztest_fault_inject;
337ztest_func_t ztest_ddt_repair;
338ztest_func_t ztest_dmu_snapshot_hold;
339ztest_func_t ztest_spa_rename;
340ztest_func_t ztest_scrub;
341ztest_func_t ztest_dsl_dataset_promote_busy;
342ztest_func_t ztest_vdev_attach_detach;
343ztest_func_t ztest_vdev_LUN_growth;
344ztest_func_t ztest_vdev_add_remove;
345ztest_func_t ztest_vdev_aux_add_remove;
346ztest_func_t ztest_split_pool;
347ztest_func_t ztest_reguid;
348ztest_func_t ztest_spa_upgrade;
349ztest_func_t ztest_device_removal;
350ztest_func_t ztest_remap_blocks;
351ztest_func_t ztest_spa_checkpoint_create_discard;
352ztest_func_t ztest_initialize;
353
354uint64_t zopt_always = 0ULL * NANOSEC;		/* all the time */
355uint64_t zopt_incessant = 1ULL * NANOSEC / 10;	/* every 1/10 second */
356uint64_t zopt_often = 1ULL * NANOSEC;		/* every second */
357uint64_t zopt_sometimes = 10ULL * NANOSEC;	/* every 10 seconds */
358uint64_t zopt_rarely = 60ULL * NANOSEC;		/* every 60 seconds */
359
360ztest_info_t ztest_info[] = {
361	{ ztest_dmu_read_write,			1,	&zopt_always	},
362	{ ztest_dmu_write_parallel,		10,	&zopt_always	},
363	{ ztest_dmu_object_alloc_free,		1,	&zopt_always	},
364	{ ztest_dmu_commit_callbacks,		1,	&zopt_always	},
365	{ ztest_zap,				30,	&zopt_always	},
366	{ ztest_zap_parallel,			100,	&zopt_always	},
367	{ ztest_split_pool,			1,	&zopt_always	},
368	{ ztest_zil_commit,			1,	&zopt_incessant	},
369	{ ztest_zil_remount,			1,	&zopt_sometimes	},
370	{ ztest_dmu_read_write_zcopy,		1,	&zopt_often	},
371	{ ztest_dmu_objset_create_destroy,	1,	&zopt_often	},
372	{ ztest_dsl_prop_get_set,		1,	&zopt_often	},
373	{ ztest_spa_prop_get_set,		1,	&zopt_sometimes	},
374#if 0
375	{ ztest_dmu_prealloc,			1,	&zopt_sometimes	},
376#endif
377	{ ztest_fzap,				1,	&zopt_sometimes	},
378	{ ztest_dmu_snapshot_create_destroy,	1,	&zopt_sometimes	},
379	{ ztest_spa_create_destroy,		1,	&zopt_sometimes	},
380	{ ztest_fault_inject,			1,	&zopt_incessant	},
381	{ ztest_ddt_repair,			1,	&zopt_sometimes	},
382	{ ztest_dmu_snapshot_hold,		1,	&zopt_sometimes	},
383	{ ztest_reguid,				1,	&zopt_rarely	},
384	{ ztest_spa_rename,			1,	&zopt_rarely	},
385	{ ztest_scrub,				1,	&zopt_often	},
386	{ ztest_spa_upgrade,			1,	&zopt_rarely	},
387	{ ztest_dsl_dataset_promote_busy,	1,	&zopt_rarely	},
388	{ ztest_vdev_attach_detach,		1,	&zopt_incessant	},
389	{ ztest_vdev_LUN_growth,		1,	&zopt_rarely	},
390	{ ztest_vdev_add_remove,		1,
391	    &ztest_opts.zo_vdevtime				},
392	{ ztest_vdev_aux_add_remove,		1,
393	    &ztest_opts.zo_vdevtime				},
394	{ ztest_device_removal,			1,	&zopt_sometimes	},
395	{ ztest_remap_blocks,			1,	&zopt_sometimes },
396	{ ztest_spa_checkpoint_create_discard,	1,	&zopt_rarely	},
397	{ ztest_initialize,			1,	&zopt_sometimes }
398};
399
400#define	ZTEST_FUNCS	(sizeof (ztest_info) / sizeof (ztest_info_t))
401
402/*
403 * The following struct is used to hold a list of uncalled commit callbacks.
404 * The callbacks are ordered by txg number.
405 */
406typedef struct ztest_cb_list {
407	kmutex_t zcl_callbacks_lock;
408	list_t	zcl_callbacks;
409} ztest_cb_list_t;
410
411/*
412 * Stuff we need to share writably between parent and child.
413 */
414typedef struct ztest_shared {
415	boolean_t	zs_do_init;
416	hrtime_t	zs_proc_start;
417	hrtime_t	zs_proc_stop;
418	hrtime_t	zs_thread_start;
419	hrtime_t	zs_thread_stop;
420	hrtime_t	zs_thread_kill;
421	uint64_t	zs_enospc_count;
422	uint64_t	zs_vdev_next_leaf;
423	uint64_t	zs_vdev_aux;
424	uint64_t	zs_alloc;
425	uint64_t	zs_space;
426	uint64_t	zs_splits;
427	uint64_t	zs_mirrors;
428	uint64_t	zs_metaslab_sz;
429	uint64_t	zs_metaslab_df_alloc_threshold;
430	uint64_t	zs_guid;
431} ztest_shared_t;
432
433#define	ID_PARALLEL	-1ULL
434
435static char ztest_dev_template[] = "%s/%s.%llua";
436static char ztest_aux_template[] = "%s/%s.%s.%llu";
437ztest_shared_t *ztest_shared;
438
439static spa_t *ztest_spa = NULL;
440static ztest_ds_t *ztest_ds;
441
442static kmutex_t ztest_vdev_lock;
443static kmutex_t ztest_checkpoint_lock;
444static boolean_t ztest_device_removal_active = B_FALSE;
445
446/*
447 * The ztest_name_lock protects the pool and dataset namespace used by
448 * the individual tests. To modify the namespace, consumers must grab
449 * this lock as writer. Grabbing the lock as reader will ensure that the
450 * namespace does not change while the lock is held.
451 */
452static krwlock_t ztest_name_lock;
453
454static boolean_t ztest_dump_core = B_TRUE;
455static boolean_t ztest_exiting;
456
457/* Global commit callback list */
458static ztest_cb_list_t zcl;
459
460enum ztest_object {
461	ZTEST_META_DNODE = 0,
462	ZTEST_DIROBJ,
463	ZTEST_OBJECTS
464};
465
466static void usage(boolean_t) __NORETURN;
467
468/*
469 * These libumem hooks provide a reasonable set of defaults for the allocator's
470 * debugging facilities.
471 */
472const char *
473_umem_debug_init()
474{
475	return ("default,verbose"); /* $UMEM_DEBUG setting */
476}
477
478const char *
479_umem_logging_init(void)
480{
481	return ("fail,contents"); /* $UMEM_LOGGING setting */
482}
483
484#define	FATAL_MSG_SZ	1024
485
486char *fatal_msg;
487
488static void
489fatal(int do_perror, char *message, ...)
490{
491	va_list args;
492	int save_errno = errno;
493	char buf[FATAL_MSG_SZ];
494
495	(void) fflush(stdout);
496
497	va_start(args, message);
498	(void) sprintf(buf, "ztest: ");
499	/* LINTED */
500	(void) vsprintf(buf + strlen(buf), message, args);
501	va_end(args);
502	if (do_perror) {
503		(void) snprintf(buf + strlen(buf), FATAL_MSG_SZ - strlen(buf),
504		    ": %s", strerror(save_errno));
505	}
506	(void) fprintf(stderr, "%s\n", buf);
507	fatal_msg = buf;			/* to ease debugging */
508	if (ztest_dump_core)
509		abort();
510	exit(3);
511}
512
513static int
514str2shift(const char *buf)
515{
516	const char *ends = "BKMGTPEZ";
517	int i;
518
519	if (buf[0] == '\0')
520		return (0);
521	for (i = 0; i < strlen(ends); i++) {
522		if (toupper(buf[0]) == ends[i])
523			break;
524	}
525	if (i == strlen(ends)) {
526		(void) fprintf(stderr, "ztest: invalid bytes suffix: %s\n",
527		    buf);
528		usage(B_FALSE);
529	}
530	if (buf[1] == '\0' || (toupper(buf[1]) == 'B' && buf[2] == '\0')) {
531		return (10*i);
532	}
533	(void) fprintf(stderr, "ztest: invalid bytes suffix: %s\n", buf);
534	usage(B_FALSE);
535	/* NOTREACHED */
536}
537
538static uint64_t
539nicenumtoull(const char *buf)
540{
541	char *end;
542	uint64_t val;
543
544	val = strtoull(buf, &end, 0);
545	if (end == buf) {
546		(void) fprintf(stderr, "ztest: bad numeric value: %s\n", buf);
547		usage(B_FALSE);
548	} else if (end[0] == '.') {
549		double fval = strtod(buf, &end);
550		fval *= pow(2, str2shift(end));
551		if (fval > UINT64_MAX) {
552			(void) fprintf(stderr, "ztest: value too large: %s\n",
553			    buf);
554			usage(B_FALSE);
555		}
556		val = (uint64_t)fval;
557	} else {
558		int shift = str2shift(end);
559		if (shift >= 64 || (val << shift) >> shift != val) {
560			(void) fprintf(stderr, "ztest: value too large: %s\n",
561			    buf);
562			usage(B_FALSE);
563		}
564		val <<= shift;
565	}
566	return (val);
567}
568
569static void
570usage(boolean_t requested)
571{
572	const ztest_shared_opts_t *zo = &ztest_opts_defaults;
573
574	char nice_vdev_size[NN_NUMBUF_SZ];
575	char nice_force_ganging[NN_NUMBUF_SZ];
576	FILE *fp = requested ? stdout : stderr;
577
578	nicenum(zo->zo_vdev_size, nice_vdev_size, sizeof (nice_vdev_size));
579	nicenum(zo->zo_metaslab_force_ganging, nice_force_ganging,
580	    sizeof (nice_force_ganging));
581
582	(void) fprintf(fp, "Usage: %s\n"
583	    "\t[-v vdevs (default: %llu)]\n"
584	    "\t[-s size_of_each_vdev (default: %s)]\n"
585	    "\t[-a alignment_shift (default: %d)] use 0 for random\n"
586	    "\t[-m mirror_copies (default: %d)]\n"
587	    "\t[-r raidz_disks (default: %d)]\n"
588	    "\t[-R raidz_parity (default: %d)]\n"
589	    "\t[-d datasets (default: %d)]\n"
590	    "\t[-t threads (default: %d)]\n"
591	    "\t[-g gang_block_threshold (default: %s)]\n"
592	    "\t[-i init_count (default: %d)] initialize pool i times\n"
593	    "\t[-k kill_percentage (default: %llu%%)]\n"
594	    "\t[-p pool_name (default: %s)]\n"
595	    "\t[-f dir (default: %s)] file directory for vdev files\n"
596	    "\t[-V] verbose (use multiple times for ever more blather)\n"
597	    "\t[-E] use existing pool instead of creating new one\n"
598	    "\t[-T time (default: %llu sec)] total run time\n"
599	    "\t[-F freezeloops (default: %llu)] max loops in spa_freeze()\n"
600	    "\t[-P passtime (default: %llu sec)] time per pass\n"
601	    "\t[-B alt_ztest (default: <none>)] alternate ztest path\n"
602	    "\t[-o variable=value] ... set global variable to an unsigned\n"
603	    "\t    32-bit integer value\n"
604	    "\t[-h] (print help)\n"
605	    "",
606	    zo->zo_pool,
607	    (u_longlong_t)zo->zo_vdevs,			/* -v */
608	    nice_vdev_size,				/* -s */
609	    zo->zo_ashift,				/* -a */
610	    zo->zo_mirrors,				/* -m */
611	    zo->zo_raidz,				/* -r */
612	    zo->zo_raidz_parity,			/* -R */
613	    zo->zo_datasets,				/* -d */
614	    zo->zo_threads,				/* -t */
615	    nice_force_ganging,				/* -g */
616	    zo->zo_init,				/* -i */
617	    (u_longlong_t)zo->zo_killrate,		/* -k */
618	    zo->zo_pool,				/* -p */
619	    zo->zo_dir,					/* -f */
620	    (u_longlong_t)zo->zo_time,			/* -T */
621	    (u_longlong_t)zo->zo_maxloops,		/* -F */
622	    (u_longlong_t)zo->zo_passtime);
623	exit(requested ? 0 : 1);
624}
625
626static void
627process_options(int argc, char **argv)
628{
629	char *path;
630	ztest_shared_opts_t *zo = &ztest_opts;
631
632	int opt;
633	uint64_t value;
634	char altdir[MAXNAMELEN] = { 0 };
635
636	bcopy(&ztest_opts_defaults, zo, sizeof (*zo));
637
638	while ((opt = getopt(argc, argv,
639	    "v:s:a:m:r:R:d:t:g:i:k:p:f:VET:P:hF:B:o:")) != EOF) {
640		value = 0;
641		switch (opt) {
642		case 'v':
643		case 's':
644		case 'a':
645		case 'm':
646		case 'r':
647		case 'R':
648		case 'd':
649		case 't':
650		case 'g':
651		case 'i':
652		case 'k':
653		case 'T':
654		case 'P':
655		case 'F':
656			value = nicenumtoull(optarg);
657		}
658		switch (opt) {
659		case 'v':
660			zo->zo_vdevs = value;
661			break;
662		case 's':
663			zo->zo_vdev_size = MAX(SPA_MINDEVSIZE, value);
664			break;
665		case 'a':
666			zo->zo_ashift = value;
667			break;
668		case 'm':
669			zo->zo_mirrors = value;
670			break;
671		case 'r':
672			zo->zo_raidz = MAX(1, value);
673			break;
674		case 'R':
675			zo->zo_raidz_parity = MIN(MAX(value, 1), 3);
676			break;
677		case 'd':
678			zo->zo_datasets = MAX(1, value);
679			break;
680		case 't':
681			zo->zo_threads = MAX(1, value);
682			break;
683		case 'g':
684			zo->zo_metaslab_force_ganging =
685			    MAX(SPA_MINBLOCKSIZE << 1, value);
686			break;
687		case 'i':
688			zo->zo_init = value;
689			break;
690		case 'k':
691			zo->zo_killrate = value;
692			break;
693		case 'p':
694			(void) strlcpy(zo->zo_pool, optarg,
695			    sizeof (zo->zo_pool));
696			break;
697		case 'f':
698			path = realpath(optarg, NULL);
699			if (path == NULL) {
700				(void) fprintf(stderr, "error: %s: %s\n",
701				    optarg, strerror(errno));
702				usage(B_FALSE);
703			} else {
704				(void) strlcpy(zo->zo_dir, path,
705				    sizeof (zo->zo_dir));
706			}
707			break;
708		case 'V':
709			zo->zo_verbose++;
710			break;
711		case 'E':
712			zo->zo_init = 0;
713			break;
714		case 'T':
715			zo->zo_time = value;
716			break;
717		case 'P':
718			zo->zo_passtime = MAX(1, value);
719			break;
720		case 'F':
721			zo->zo_maxloops = MAX(1, value);
722			break;
723		case 'B':
724			(void) strlcpy(altdir, optarg, sizeof (altdir));
725			break;
726		case 'o':
727			if (set_global_var(optarg) != 0)
728				usage(B_FALSE);
729			break;
730		case 'h':
731			usage(B_TRUE);
732			break;
733		case '?':
734		default:
735			usage(B_FALSE);
736			break;
737		}
738	}
739
740	zo->zo_raidz_parity = MIN(zo->zo_raidz_parity, zo->zo_raidz - 1);
741
742	zo->zo_vdevtime =
743	    (zo->zo_vdevs > 0 ? zo->zo_time * NANOSEC / zo->zo_vdevs :
744	    UINT64_MAX >> 2);
745
746	if (strlen(altdir) > 0) {
747		char *cmd;
748		char *realaltdir;
749		char *bin;
750		char *ztest;
751		char *isa;
752		int isalen;
753
754		cmd = umem_alloc(MAXPATHLEN, UMEM_NOFAIL);
755		realaltdir = umem_alloc(MAXPATHLEN, UMEM_NOFAIL);
756
757		VERIFY(NULL != realpath(getexecname(), cmd));
758		if (0 != access(altdir, F_OK)) {
759			ztest_dump_core = B_FALSE;
760			fatal(B_TRUE, "invalid alternate ztest path: %s",
761			    altdir);
762		}
763		VERIFY(NULL != realpath(altdir, realaltdir));
764
765		/*
766		 * 'cmd' should be of the form "<anything>/usr/bin/<isa>/ztest".
767		 * We want to extract <isa> to determine if we should use
768		 * 32 or 64 bit binaries.
769		 */
770		bin = strstr(cmd, "/usr/bin/");
771		ztest = strstr(bin, "/ztest");
772		isa = bin + 9;
773		isalen = ztest - isa;
774		(void) snprintf(zo->zo_alt_ztest, sizeof (zo->zo_alt_ztest),
775		    "%s/usr/bin/%.*s/ztest", realaltdir, isalen, isa);
776		(void) snprintf(zo->zo_alt_libpath, sizeof (zo->zo_alt_libpath),
777		    "%s/usr/lib/%.*s", realaltdir, isalen, isa);
778
779		if (0 != access(zo->zo_alt_ztest, X_OK)) {
780			ztest_dump_core = B_FALSE;
781			fatal(B_TRUE, "invalid alternate ztest: %s",
782			    zo->zo_alt_ztest);
783		} else if (0 != access(zo->zo_alt_libpath, X_OK)) {
784			ztest_dump_core = B_FALSE;
785			fatal(B_TRUE, "invalid alternate lib directory %s",
786			    zo->zo_alt_libpath);
787		}
788
789		umem_free(cmd, MAXPATHLEN);
790		umem_free(realaltdir, MAXPATHLEN);
791	}
792}
793
794static void
795ztest_kill(ztest_shared_t *zs)
796{
797	zs->zs_alloc = metaslab_class_get_alloc(spa_normal_class(ztest_spa));
798	zs->zs_space = metaslab_class_get_space(spa_normal_class(ztest_spa));
799
800	/*
801	 * Before we kill off ztest, make sure that the config is updated.
802	 * See comment above spa_write_cachefile().
803	 */
804	mutex_enter(&spa_namespace_lock);
805	spa_write_cachefile(ztest_spa, B_FALSE, B_FALSE);
806	mutex_exit(&spa_namespace_lock);
807
808	zfs_dbgmsg_print(FTAG);
809	(void) kill(getpid(), SIGKILL);
810}
811
812static uint64_t
813ztest_random(uint64_t range)
814{
815	uint64_t r;
816
817	ASSERT3S(ztest_fd_rand, >=, 0);
818
819	if (range == 0)
820		return (0);
821
822	if (read(ztest_fd_rand, &r, sizeof (r)) != sizeof (r))
823		fatal(1, "short read from /dev/urandom");
824
825	return (r % range);
826}
827
828/* ARGSUSED */
829static void
830ztest_record_enospc(const char *s)
831{
832	ztest_shared->zs_enospc_count++;
833}
834
835static uint64_t
836ztest_get_ashift(void)
837{
838	if (ztest_opts.zo_ashift == 0)
839		return (SPA_MINBLOCKSHIFT + ztest_random(5));
840	return (ztest_opts.zo_ashift);
841}
842
843static nvlist_t *
844make_vdev_file(char *path, char *aux, char *pool, size_t size, uint64_t ashift)
845{
846	char pathbuf[MAXPATHLEN];
847	uint64_t vdev;
848	nvlist_t *file;
849
850	if (ashift == 0)
851		ashift = ztest_get_ashift();
852
853	if (path == NULL) {
854		path = pathbuf;
855
856		if (aux != NULL) {
857			vdev = ztest_shared->zs_vdev_aux;
858			(void) snprintf(path, sizeof (pathbuf),
859			    ztest_aux_template, ztest_opts.zo_dir,
860			    pool == NULL ? ztest_opts.zo_pool : pool,
861			    aux, vdev);
862		} else {
863			vdev = ztest_shared->zs_vdev_next_leaf++;
864			(void) snprintf(path, sizeof (pathbuf),
865			    ztest_dev_template, ztest_opts.zo_dir,
866			    pool == NULL ? ztest_opts.zo_pool : pool, vdev);
867		}
868	}
869
870	if (size != 0) {
871		int fd = open(path, O_RDWR | O_CREAT | O_TRUNC, 0666);
872		if (fd == -1)
873			fatal(1, "can't open %s", path);
874		if (ftruncate(fd, size) != 0)
875			fatal(1, "can't ftruncate %s", path);
876		(void) close(fd);
877	}
878
879	VERIFY(nvlist_alloc(&file, NV_UNIQUE_NAME, 0) == 0);
880	VERIFY(nvlist_add_string(file, ZPOOL_CONFIG_TYPE, VDEV_TYPE_FILE) == 0);
881	VERIFY(nvlist_add_string(file, ZPOOL_CONFIG_PATH, path) == 0);
882	VERIFY(nvlist_add_uint64(file, ZPOOL_CONFIG_ASHIFT, ashift) == 0);
883
884	return (file);
885}
886
887static nvlist_t *
888make_vdev_raidz(char *path, char *aux, char *pool, size_t size,
889    uint64_t ashift, int r)
890{
891	nvlist_t *raidz, **child;
892	int c;
893
894	if (r < 2)
895		return (make_vdev_file(path, aux, pool, size, ashift));
896	child = umem_alloc(r * sizeof (nvlist_t *), UMEM_NOFAIL);
897
898	for (c = 0; c < r; c++)
899		child[c] = make_vdev_file(path, aux, pool, size, ashift);
900
901	VERIFY(nvlist_alloc(&raidz, NV_UNIQUE_NAME, 0) == 0);
902	VERIFY(nvlist_add_string(raidz, ZPOOL_CONFIG_TYPE,
903	    VDEV_TYPE_RAIDZ) == 0);
904	VERIFY(nvlist_add_uint64(raidz, ZPOOL_CONFIG_NPARITY,
905	    ztest_opts.zo_raidz_parity) == 0);
906	VERIFY(nvlist_add_nvlist_array(raidz, ZPOOL_CONFIG_CHILDREN,
907	    child, r) == 0);
908
909	for (c = 0; c < r; c++)
910		nvlist_free(child[c]);
911
912	umem_free(child, r * sizeof (nvlist_t *));
913
914	return (raidz);
915}
916
917static nvlist_t *
918make_vdev_mirror(char *path, char *aux, char *pool, size_t size,
919    uint64_t ashift, int r, int m)
920{
921	nvlist_t *mirror, **child;
922	int c;
923
924	if (m < 1)
925		return (make_vdev_raidz(path, aux, pool, size, ashift, r));
926
927	child = umem_alloc(m * sizeof (nvlist_t *), UMEM_NOFAIL);
928
929	for (c = 0; c < m; c++)
930		child[c] = make_vdev_raidz(path, aux, pool, size, ashift, r);
931
932	VERIFY(nvlist_alloc(&mirror, NV_UNIQUE_NAME, 0) == 0);
933	VERIFY(nvlist_add_string(mirror, ZPOOL_CONFIG_TYPE,
934	    VDEV_TYPE_MIRROR) == 0);
935	VERIFY(nvlist_add_nvlist_array(mirror, ZPOOL_CONFIG_CHILDREN,
936	    child, m) == 0);
937
938	for (c = 0; c < m; c++)
939		nvlist_free(child[c]);
940
941	umem_free(child, m * sizeof (nvlist_t *));
942
943	return (mirror);
944}
945
946static nvlist_t *
947make_vdev_root(char *path, char *aux, char *pool, size_t size, uint64_t ashift,
948    int log, int r, int m, int t)
949{
950	nvlist_t *root, **child;
951	int c;
952
953	ASSERT(t > 0);
954
955	child = umem_alloc(t * sizeof (nvlist_t *), UMEM_NOFAIL);
956
957	for (c = 0; c < t; c++) {
958		child[c] = make_vdev_mirror(path, aux, pool, size, ashift,
959		    r, m);
960		VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
961		    log) == 0);
962	}
963
964	VERIFY(nvlist_alloc(&root, NV_UNIQUE_NAME, 0) == 0);
965	VERIFY(nvlist_add_string(root, ZPOOL_CONFIG_TYPE, VDEV_TYPE_ROOT) == 0);
966	VERIFY(nvlist_add_nvlist_array(root, aux ? aux : ZPOOL_CONFIG_CHILDREN,
967	    child, t) == 0);
968
969	for (c = 0; c < t; c++)
970		nvlist_free(child[c]);
971
972	umem_free(child, t * sizeof (nvlist_t *));
973
974	return (root);
975}
976
977/*
978 * Find a random spa version. Returns back a random spa version in the
979 * range [initial_version, SPA_VERSION_FEATURES].
980 */
981static uint64_t
982ztest_random_spa_version(uint64_t initial_version)
983{
984	uint64_t version = initial_version;
985
986	if (version <= SPA_VERSION_BEFORE_FEATURES) {
987		version = version +
988		    ztest_random(SPA_VERSION_BEFORE_FEATURES - version + 1);
989	}
990
991	if (version > SPA_VERSION_BEFORE_FEATURES)
992		version = SPA_VERSION_FEATURES;
993
994	ASSERT(SPA_VERSION_IS_SUPPORTED(version));
995	return (version);
996}
997
998static int
999ztest_random_blocksize(void)
1000{
1001	uint64_t block_shift;
1002	/*
1003	 * Choose a block size >= the ashift.
1004	 * If the SPA supports new MAXBLOCKSIZE, test up to 1MB blocks.
1005	 */
1006	int maxbs = SPA_OLD_MAXBLOCKSHIFT;
1007	if (spa_maxblocksize(ztest_spa) == SPA_MAXBLOCKSIZE)
1008		maxbs = 20;
1009	block_shift = ztest_random(maxbs - ztest_spa->spa_max_ashift + 1);
1010	return (1 << (SPA_MINBLOCKSHIFT + block_shift));
1011}
1012
1013static int
1014ztest_random_ibshift(void)
1015{
1016	return (DN_MIN_INDBLKSHIFT +
1017	    ztest_random(DN_MAX_INDBLKSHIFT - DN_MIN_INDBLKSHIFT + 1));
1018}
1019
1020static uint64_t
1021ztest_random_vdev_top(spa_t *spa, boolean_t log_ok)
1022{
1023	uint64_t top;
1024	vdev_t *rvd = spa->spa_root_vdev;
1025	vdev_t *tvd;
1026
1027	ASSERT(spa_config_held(spa, SCL_ALL, RW_READER) != 0);
1028
1029	do {
1030		top = ztest_random(rvd->vdev_children);
1031		tvd = rvd->vdev_child[top];
1032	} while (!vdev_is_concrete(tvd) || (tvd->vdev_islog && !log_ok) ||
1033	    tvd->vdev_mg == NULL || tvd->vdev_mg->mg_class == NULL);
1034
1035	return (top);
1036}
1037
1038static uint64_t
1039ztest_random_dsl_prop(zfs_prop_t prop)
1040{
1041	uint64_t value;
1042
1043	do {
1044		value = zfs_prop_random_value(prop, ztest_random(-1ULL));
1045	} while (prop == ZFS_PROP_CHECKSUM && value == ZIO_CHECKSUM_OFF);
1046
1047	return (value);
1048}
1049
1050static int
1051ztest_dsl_prop_set_uint64(char *osname, zfs_prop_t prop, uint64_t value,
1052    boolean_t inherit)
1053{
1054	const char *propname = zfs_prop_to_name(prop);
1055	const char *valname;
1056	char setpoint[MAXPATHLEN];
1057	uint64_t curval;
1058	int error;
1059
1060	error = dsl_prop_set_int(osname, propname,
1061	    (inherit ? ZPROP_SRC_NONE : ZPROP_SRC_LOCAL), value);
1062
1063	if (error == ENOSPC) {
1064		ztest_record_enospc(FTAG);
1065		return (error);
1066	}
1067	ASSERT0(error);
1068
1069	VERIFY0(dsl_prop_get_integer(osname, propname, &curval, setpoint));
1070
1071	if (ztest_opts.zo_verbose >= 6) {
1072		VERIFY(zfs_prop_index_to_string(prop, curval, &valname) == 0);
1073		(void) printf("%s %s = %s at '%s'\n",
1074		    osname, propname, valname, setpoint);
1075	}
1076
1077	return (error);
1078}
1079
1080static int
1081ztest_spa_prop_set_uint64(zpool_prop_t prop, uint64_t value)
1082{
1083	spa_t *spa = ztest_spa;
1084	nvlist_t *props = NULL;
1085	int error;
1086
1087	VERIFY(nvlist_alloc(&props, NV_UNIQUE_NAME, 0) == 0);
1088	VERIFY(nvlist_add_uint64(props, zpool_prop_to_name(prop), value) == 0);
1089
1090	error = spa_prop_set(spa, props);
1091
1092	nvlist_free(props);
1093
1094	if (error == ENOSPC) {
1095		ztest_record_enospc(FTAG);
1096		return (error);
1097	}
1098	ASSERT0(error);
1099
1100	return (error);
1101}
1102
1103static void
1104ztest_rll_init(rll_t *rll)
1105{
1106	rll->rll_writer = NULL;
1107	rll->rll_readers = 0;
1108	mutex_init(&rll->rll_lock, NULL, USYNC_THREAD, NULL);
1109	cv_init(&rll->rll_cv, NULL, USYNC_THREAD, NULL);
1110}
1111
1112static void
1113ztest_rll_destroy(rll_t *rll)
1114{
1115	ASSERT(rll->rll_writer == NULL);
1116	ASSERT(rll->rll_readers == 0);
1117	mutex_destroy(&rll->rll_lock);
1118	cv_destroy(&rll->rll_cv);
1119}
1120
1121static void
1122ztest_rll_lock(rll_t *rll, rl_type_t type)
1123{
1124	mutex_enter(&rll->rll_lock);
1125
1126	if (type == RL_READER) {
1127		while (rll->rll_writer != NULL)
1128			cv_wait(&rll->rll_cv, &rll->rll_lock);
1129		rll->rll_readers++;
1130	} else {
1131		while (rll->rll_writer != NULL || rll->rll_readers)
1132			cv_wait(&rll->rll_cv, &rll->rll_lock);
1133		rll->rll_writer = curthread;
1134	}
1135
1136	mutex_exit(&rll->rll_lock);
1137}
1138
1139static void
1140ztest_rll_unlock(rll_t *rll)
1141{
1142	mutex_enter(&rll->rll_lock);
1143
1144	if (rll->rll_writer) {
1145		ASSERT(rll->rll_readers == 0);
1146		rll->rll_writer = NULL;
1147	} else {
1148		ASSERT(rll->rll_readers != 0);
1149		ASSERT(rll->rll_writer == NULL);
1150		rll->rll_readers--;
1151	}
1152
1153	if (rll->rll_writer == NULL && rll->rll_readers == 0)
1154		cv_broadcast(&rll->rll_cv);
1155
1156	mutex_exit(&rll->rll_lock);
1157}
1158
1159static void
1160ztest_object_lock(ztest_ds_t *zd, uint64_t object, rl_type_t type)
1161{
1162	rll_t *rll = &zd->zd_object_lock[object & (ZTEST_OBJECT_LOCKS - 1)];
1163
1164	ztest_rll_lock(rll, type);
1165}
1166
1167static void
1168ztest_object_unlock(ztest_ds_t *zd, uint64_t object)
1169{
1170	rll_t *rll = &zd->zd_object_lock[object & (ZTEST_OBJECT_LOCKS - 1)];
1171
1172	ztest_rll_unlock(rll);
1173}
1174
1175static rl_t *
1176ztest_range_lock(ztest_ds_t *zd, uint64_t object, uint64_t offset,
1177    uint64_t size, rl_type_t type)
1178{
1179	uint64_t hash = object ^ (offset % (ZTEST_RANGE_LOCKS + 1));
1180	rll_t *rll = &zd->zd_range_lock[hash & (ZTEST_RANGE_LOCKS - 1)];
1181	rl_t *rl;
1182
1183	rl = umem_alloc(sizeof (*rl), UMEM_NOFAIL);
1184	rl->rl_object = object;
1185	rl->rl_offset = offset;
1186	rl->rl_size = size;
1187	rl->rl_lock = rll;
1188
1189	ztest_rll_lock(rll, type);
1190
1191	return (rl);
1192}
1193
1194static void
1195ztest_range_unlock(rl_t *rl)
1196{
1197	rll_t *rll = rl->rl_lock;
1198
1199	ztest_rll_unlock(rll);
1200
1201	umem_free(rl, sizeof (*rl));
1202}
1203
1204static void
1205ztest_zd_init(ztest_ds_t *zd, ztest_shared_ds_t *szd, objset_t *os)
1206{
1207	zd->zd_os = os;
1208	zd->zd_zilog = dmu_objset_zil(os);
1209	zd->zd_shared = szd;
1210	dmu_objset_name(os, zd->zd_name);
1211
1212	if (zd->zd_shared != NULL)
1213		zd->zd_shared->zd_seq = 0;
1214
1215	rw_init(&zd->zd_zilog_lock, NULL, USYNC_THREAD, NULL);
1216	mutex_init(&zd->zd_dirobj_lock, NULL, USYNC_THREAD, NULL);
1217
1218	for (int l = 0; l < ZTEST_OBJECT_LOCKS; l++)
1219		ztest_rll_init(&zd->zd_object_lock[l]);
1220
1221	for (int l = 0; l < ZTEST_RANGE_LOCKS; l++)
1222		ztest_rll_init(&zd->zd_range_lock[l]);
1223}
1224
1225static void
1226ztest_zd_fini(ztest_ds_t *zd)
1227{
1228	mutex_destroy(&zd->zd_dirobj_lock);
1229
1230	for (int l = 0; l < ZTEST_OBJECT_LOCKS; l++)
1231		ztest_rll_destroy(&zd->zd_object_lock[l]);
1232
1233	for (int l = 0; l < ZTEST_RANGE_LOCKS; l++)
1234		ztest_rll_destroy(&zd->zd_range_lock[l]);
1235}
1236
1237#define	TXG_MIGHTWAIT	(ztest_random(10) == 0 ? TXG_NOWAIT : TXG_WAIT)
1238
1239static uint64_t
1240ztest_tx_assign(dmu_tx_t *tx, uint64_t txg_how, const char *tag)
1241{
1242	uint64_t txg;
1243	int error;
1244
1245	/*
1246	 * Attempt to assign tx to some transaction group.
1247	 */
1248	error = dmu_tx_assign(tx, txg_how);
1249	if (error) {
1250		if (error == ERESTART) {
1251			ASSERT(txg_how == TXG_NOWAIT);
1252			dmu_tx_wait(tx);
1253		} else {
1254			ASSERT3U(error, ==, ENOSPC);
1255			ztest_record_enospc(tag);
1256		}
1257		dmu_tx_abort(tx);
1258		return (0);
1259	}
1260	txg = dmu_tx_get_txg(tx);
1261	ASSERT(txg != 0);
1262	return (txg);
1263}
1264
1265static void
1266ztest_pattern_set(void *buf, uint64_t size, uint64_t value)
1267{
1268	uint64_t *ip = buf;
1269	uint64_t *ip_end = (uint64_t *)((uintptr_t)buf + (uintptr_t)size);
1270
1271	while (ip < ip_end)
1272		*ip++ = value;
1273}
1274
1275static boolean_t
1276ztest_pattern_match(void *buf, uint64_t size, uint64_t value)
1277{
1278	uint64_t *ip = buf;
1279	uint64_t *ip_end = (uint64_t *)((uintptr_t)buf + (uintptr_t)size);
1280	uint64_t diff = 0;
1281
1282	while (ip < ip_end)
1283		diff |= (value - *ip++);
1284
1285	return (diff == 0);
1286}
1287
1288static void
1289ztest_bt_generate(ztest_block_tag_t *bt, objset_t *os, uint64_t object,
1290    uint64_t offset, uint64_t gen, uint64_t txg, uint64_t crtxg)
1291{
1292	bt->bt_magic = BT_MAGIC;
1293	bt->bt_objset = dmu_objset_id(os);
1294	bt->bt_object = object;
1295	bt->bt_offset = offset;
1296	bt->bt_gen = gen;
1297	bt->bt_txg = txg;
1298	bt->bt_crtxg = crtxg;
1299}
1300
1301static void
1302ztest_bt_verify(ztest_block_tag_t *bt, objset_t *os, uint64_t object,
1303    uint64_t offset, uint64_t gen, uint64_t txg, uint64_t crtxg)
1304{
1305	ASSERT3U(bt->bt_magic, ==, BT_MAGIC);
1306	ASSERT3U(bt->bt_objset, ==, dmu_objset_id(os));
1307	ASSERT3U(bt->bt_object, ==, object);
1308	ASSERT3U(bt->bt_offset, ==, offset);
1309	ASSERT3U(bt->bt_gen, <=, gen);
1310	ASSERT3U(bt->bt_txg, <=, txg);
1311	ASSERT3U(bt->bt_crtxg, ==, crtxg);
1312}
1313
1314static ztest_block_tag_t *
1315ztest_bt_bonus(dmu_buf_t *db)
1316{
1317	dmu_object_info_t doi;
1318	ztest_block_tag_t *bt;
1319
1320	dmu_object_info_from_db(db, &doi);
1321	ASSERT3U(doi.doi_bonus_size, <=, db->db_size);
1322	ASSERT3U(doi.doi_bonus_size, >=, sizeof (*bt));
1323	bt = (void *)((char *)db->db_data + doi.doi_bonus_size - sizeof (*bt));
1324
1325	return (bt);
1326}
1327
1328/*
1329 * ZIL logging ops
1330 */
1331
1332#define	lrz_type	lr_mode
1333#define	lrz_blocksize	lr_uid
1334#define	lrz_ibshift	lr_gid
1335#define	lrz_bonustype	lr_rdev
1336#define	lrz_bonuslen	lr_crtime[1]
1337
1338static void
1339ztest_log_create(ztest_ds_t *zd, dmu_tx_t *tx, lr_create_t *lr)
1340{
1341	char *name = (void *)(lr + 1);		/* name follows lr */
1342	size_t namesize = strlen(name) + 1;
1343	itx_t *itx;
1344
1345	if (zil_replaying(zd->zd_zilog, tx))
1346		return;
1347
1348	itx = zil_itx_create(TX_CREATE, sizeof (*lr) + namesize);
1349	bcopy(&lr->lr_common + 1, &itx->itx_lr + 1,
1350	    sizeof (*lr) + namesize - sizeof (lr_t));
1351
1352	zil_itx_assign(zd->zd_zilog, itx, tx);
1353}
1354
1355static void
1356ztest_log_remove(ztest_ds_t *zd, dmu_tx_t *tx, lr_remove_t *lr, uint64_t object)
1357{
1358	char *name = (void *)(lr + 1);		/* name follows lr */
1359	size_t namesize = strlen(name) + 1;
1360	itx_t *itx;
1361
1362	if (zil_replaying(zd->zd_zilog, tx))
1363		return;
1364
1365	itx = zil_itx_create(TX_REMOVE, sizeof (*lr) + namesize);
1366	bcopy(&lr->lr_common + 1, &itx->itx_lr + 1,
1367	    sizeof (*lr) + namesize - sizeof (lr_t));
1368
1369	itx->itx_oid = object;
1370	zil_itx_assign(zd->zd_zilog, itx, tx);
1371}
1372
1373static void
1374ztest_log_write(ztest_ds_t *zd, dmu_tx_t *tx, lr_write_t *lr)
1375{
1376	itx_t *itx;
1377	itx_wr_state_t write_state = ztest_random(WR_NUM_STATES);
1378
1379	if (zil_replaying(zd->zd_zilog, tx))
1380		return;
1381
1382	if (lr->lr_length > zil_max_log_data(zd->zd_zilog))
1383		write_state = WR_INDIRECT;
1384
1385	itx = zil_itx_create(TX_WRITE,
1386	    sizeof (*lr) + (write_state == WR_COPIED ? lr->lr_length : 0));
1387
1388	if (write_state == WR_COPIED &&
1389	    dmu_read(zd->zd_os, lr->lr_foid, lr->lr_offset, lr->lr_length,
1390	    ((lr_write_t *)&itx->itx_lr) + 1, DMU_READ_NO_PREFETCH) != 0) {
1391		zil_itx_destroy(itx);
1392		itx = zil_itx_create(TX_WRITE, sizeof (*lr));
1393		write_state = WR_NEED_COPY;
1394	}
1395	itx->itx_private = zd;
1396	itx->itx_wr_state = write_state;
1397	itx->itx_sync = (ztest_random(8) == 0);
1398
1399	bcopy(&lr->lr_common + 1, &itx->itx_lr + 1,
1400	    sizeof (*lr) - sizeof (lr_t));
1401
1402	zil_itx_assign(zd->zd_zilog, itx, tx);
1403}
1404
1405static void
1406ztest_log_truncate(ztest_ds_t *zd, dmu_tx_t *tx, lr_truncate_t *lr)
1407{
1408	itx_t *itx;
1409
1410	if (zil_replaying(zd->zd_zilog, tx))
1411		return;
1412
1413	itx = zil_itx_create(TX_TRUNCATE, sizeof (*lr));
1414	bcopy(&lr->lr_common + 1, &itx->itx_lr + 1,
1415	    sizeof (*lr) - sizeof (lr_t));
1416
1417	itx->itx_sync = B_FALSE;
1418	zil_itx_assign(zd->zd_zilog, itx, tx);
1419}
1420
1421static void
1422ztest_log_setattr(ztest_ds_t *zd, dmu_tx_t *tx, lr_setattr_t *lr)
1423{
1424	itx_t *itx;
1425
1426	if (zil_replaying(zd->zd_zilog, tx))
1427		return;
1428
1429	itx = zil_itx_create(TX_SETATTR, sizeof (*lr));
1430	bcopy(&lr->lr_common + 1, &itx->itx_lr + 1,
1431	    sizeof (*lr) - sizeof (lr_t));
1432
1433	itx->itx_sync = B_FALSE;
1434	zil_itx_assign(zd->zd_zilog, itx, tx);
1435}
1436
1437/*
1438 * ZIL replay ops
1439 */
1440static int
1441ztest_replay_create(void *arg1, void *arg2, boolean_t byteswap)
1442{
1443	ztest_ds_t *zd = arg1;
1444	lr_create_t *lr = arg2;
1445	char *name = (void *)(lr + 1);		/* name follows lr */
1446	objset_t *os = zd->zd_os;
1447	ztest_block_tag_t *bbt;
1448	dmu_buf_t *db;
1449	dmu_tx_t *tx;
1450	uint64_t txg;
1451	int error = 0;
1452
1453	if (byteswap)
1454		byteswap_uint64_array(lr, sizeof (*lr));
1455
1456	ASSERT(lr->lr_doid == ZTEST_DIROBJ);
1457	ASSERT(name[0] != '\0');
1458
1459	tx = dmu_tx_create(os);
1460
1461	dmu_tx_hold_zap(tx, lr->lr_doid, B_TRUE, name);
1462
1463	if (lr->lrz_type == DMU_OT_ZAP_OTHER) {
1464		dmu_tx_hold_zap(tx, DMU_NEW_OBJECT, B_TRUE, NULL);
1465	} else {
1466		dmu_tx_hold_bonus(tx, DMU_NEW_OBJECT);
1467	}
1468
1469	txg = ztest_tx_assign(tx, TXG_WAIT, FTAG);
1470	if (txg == 0)
1471		return (ENOSPC);
1472
1473	ASSERT(dmu_objset_zil(os)->zl_replay == !!lr->lr_foid);
1474
1475	if (lr->lrz_type == DMU_OT_ZAP_OTHER) {
1476		if (lr->lr_foid == 0) {
1477			lr->lr_foid = zap_create(os,
1478			    lr->lrz_type, lr->lrz_bonustype,
1479			    lr->lrz_bonuslen, tx);
1480		} else {
1481			error = zap_create_claim(os, lr->lr_foid,
1482			    lr->lrz_type, lr->lrz_bonustype,
1483			    lr->lrz_bonuslen, tx);
1484		}
1485	} else {
1486		if (lr->lr_foid == 0) {
1487			lr->lr_foid = dmu_object_alloc(os,
1488			    lr->lrz_type, 0, lr->lrz_bonustype,
1489			    lr->lrz_bonuslen, tx);
1490		} else {
1491			error = dmu_object_claim(os, lr->lr_foid,
1492			    lr->lrz_type, 0, lr->lrz_bonustype,
1493			    lr->lrz_bonuslen, tx);
1494		}
1495	}
1496
1497	if (error) {
1498		ASSERT3U(error, ==, EEXIST);
1499		ASSERT(zd->zd_zilog->zl_replay);
1500		dmu_tx_commit(tx);
1501		return (error);
1502	}
1503
1504	ASSERT(lr->lr_foid != 0);
1505
1506	if (lr->lrz_type != DMU_OT_ZAP_OTHER)
1507		VERIFY3U(0, ==, dmu_object_set_blocksize(os, lr->lr_foid,
1508		    lr->lrz_blocksize, lr->lrz_ibshift, tx));
1509
1510	VERIFY3U(0, ==, dmu_bonus_hold(os, lr->lr_foid, FTAG, &db));
1511	bbt = ztest_bt_bonus(db);
1512	dmu_buf_will_dirty(db, tx);
1513	ztest_bt_generate(bbt, os, lr->lr_foid, -1ULL, lr->lr_gen, txg, txg);
1514	dmu_buf_rele(db, FTAG);
1515
1516	VERIFY3U(0, ==, zap_add(os, lr->lr_doid, name, sizeof (uint64_t), 1,
1517	    &lr->lr_foid, tx));
1518
1519	(void) ztest_log_create(zd, tx, lr);
1520
1521	dmu_tx_commit(tx);
1522
1523	return (0);
1524}
1525
1526static int
1527ztest_replay_remove(void *arg1, void *arg2, boolean_t byteswap)
1528{
1529	ztest_ds_t *zd = arg1;
1530	lr_remove_t *lr = arg2;
1531	char *name = (void *)(lr + 1);		/* name follows lr */
1532	objset_t *os = zd->zd_os;
1533	dmu_object_info_t doi;
1534	dmu_tx_t *tx;
1535	uint64_t object, txg;
1536
1537	if (byteswap)
1538		byteswap_uint64_array(lr, sizeof (*lr));
1539
1540	ASSERT(lr->lr_doid == ZTEST_DIROBJ);
1541	ASSERT(name[0] != '\0');
1542
1543	VERIFY3U(0, ==,
1544	    zap_lookup(os, lr->lr_doid, name, sizeof (object), 1, &object));
1545	ASSERT(object != 0);
1546
1547	ztest_object_lock(zd, object, RL_WRITER);
1548
1549	VERIFY3U(0, ==, dmu_object_info(os, object, &doi));
1550
1551	tx = dmu_tx_create(os);
1552
1553	dmu_tx_hold_zap(tx, lr->lr_doid, B_FALSE, name);
1554	dmu_tx_hold_free(tx, object, 0, DMU_OBJECT_END);
1555
1556	txg = ztest_tx_assign(tx, TXG_WAIT, FTAG);
1557	if (txg == 0) {
1558		ztest_object_unlock(zd, object);
1559		return (ENOSPC);
1560	}
1561
1562	if (doi.doi_type == DMU_OT_ZAP_OTHER) {
1563		VERIFY3U(0, ==, zap_destroy(os, object, tx));
1564	} else {
1565		VERIFY3U(0, ==, dmu_object_free(os, object, tx));
1566	}
1567
1568	VERIFY3U(0, ==, zap_remove(os, lr->lr_doid, name, tx));
1569
1570	(void) ztest_log_remove(zd, tx, lr, object);
1571
1572	dmu_tx_commit(tx);
1573
1574	ztest_object_unlock(zd, object);
1575
1576	return (0);
1577}
1578
1579static int
1580ztest_replay_write(void *arg1, void *arg2, boolean_t byteswap)
1581{
1582	ztest_ds_t *zd = arg1;
1583	lr_write_t *lr = arg2;
1584	objset_t *os = zd->zd_os;
1585	void *data = lr + 1;			/* data follows lr */
1586	uint64_t offset, length;
1587	ztest_block_tag_t *bt = data;
1588	ztest_block_tag_t *bbt;
1589	uint64_t gen, txg, lrtxg, crtxg;
1590	dmu_object_info_t doi;
1591	dmu_tx_t *tx;
1592	dmu_buf_t *db;
1593	arc_buf_t *abuf = NULL;
1594	rl_t *rl;
1595
1596	if (byteswap)
1597		byteswap_uint64_array(lr, sizeof (*lr));
1598
1599	offset = lr->lr_offset;
1600	length = lr->lr_length;
1601
1602	/* If it's a dmu_sync() block, write the whole block */
1603	if (lr->lr_common.lrc_reclen == sizeof (lr_write_t)) {
1604		uint64_t blocksize = BP_GET_LSIZE(&lr->lr_blkptr);
1605		if (length < blocksize) {
1606			offset -= offset % blocksize;
1607			length = blocksize;
1608		}
1609	}
1610
1611	if (bt->bt_magic == BSWAP_64(BT_MAGIC))
1612		byteswap_uint64_array(bt, sizeof (*bt));
1613
1614	if (bt->bt_magic != BT_MAGIC)
1615		bt = NULL;
1616
1617	ztest_object_lock(zd, lr->lr_foid, RL_READER);
1618	rl = ztest_range_lock(zd, lr->lr_foid, offset, length, RL_WRITER);
1619
1620	VERIFY3U(0, ==, dmu_bonus_hold(os, lr->lr_foid, FTAG, &db));
1621
1622	dmu_object_info_from_db(db, &doi);
1623
1624	bbt = ztest_bt_bonus(db);
1625	ASSERT3U(bbt->bt_magic, ==, BT_MAGIC);
1626	gen = bbt->bt_gen;
1627	crtxg = bbt->bt_crtxg;
1628	lrtxg = lr->lr_common.lrc_txg;
1629
1630	tx = dmu_tx_create(os);
1631
1632	dmu_tx_hold_write(tx, lr->lr_foid, offset, length);
1633
1634	if (ztest_random(8) == 0 && length == doi.doi_data_block_size &&
1635	    P2PHASE(offset, length) == 0)
1636		abuf = dmu_request_arcbuf(db, length);
1637
1638	txg = ztest_tx_assign(tx, TXG_WAIT, FTAG);
1639	if (txg == 0) {
1640		if (abuf != NULL)
1641			dmu_return_arcbuf(abuf);
1642		dmu_buf_rele(db, FTAG);
1643		ztest_range_unlock(rl);
1644		ztest_object_unlock(zd, lr->lr_foid);
1645		return (ENOSPC);
1646	}
1647
1648	if (bt != NULL) {
1649		/*
1650		 * Usually, verify the old data before writing new data --
1651		 * but not always, because we also want to verify correct
1652		 * behavior when the data was not recently read into cache.
1653		 */
1654		ASSERT(offset % doi.doi_data_block_size == 0);
1655		if (ztest_random(4) != 0) {
1656			int prefetch = ztest_random(2) ?
1657			    DMU_READ_PREFETCH : DMU_READ_NO_PREFETCH;
1658			ztest_block_tag_t rbt;
1659
1660			VERIFY(dmu_read(os, lr->lr_foid, offset,
1661			    sizeof (rbt), &rbt, prefetch) == 0);
1662			if (rbt.bt_magic == BT_MAGIC) {
1663				ztest_bt_verify(&rbt, os, lr->lr_foid,
1664				    offset, gen, txg, crtxg);
1665			}
1666		}
1667
1668		/*
1669		 * Writes can appear to be newer than the bonus buffer because
1670		 * the ztest_get_data() callback does a dmu_read() of the
1671		 * open-context data, which may be different than the data
1672		 * as it was when the write was generated.
1673		 */
1674		if (zd->zd_zilog->zl_replay) {
1675			ztest_bt_verify(bt, os, lr->lr_foid, offset,
1676			    MAX(gen, bt->bt_gen), MAX(txg, lrtxg),
1677			    bt->bt_crtxg);
1678		}
1679
1680		/*
1681		 * Set the bt's gen/txg to the bonus buffer's gen/txg
1682		 * so that all of the usual ASSERTs will work.
1683		 */
1684		ztest_bt_generate(bt, os, lr->lr_foid, offset, gen, txg, crtxg);
1685	}
1686
1687	if (abuf == NULL) {
1688		dmu_write(os, lr->lr_foid, offset, length, data, tx);
1689	} else {
1690		bcopy(data, abuf->b_data, length);
1691		dmu_assign_arcbuf(db, offset, abuf, tx);
1692	}
1693
1694	(void) ztest_log_write(zd, tx, lr);
1695
1696	dmu_buf_rele(db, FTAG);
1697
1698	dmu_tx_commit(tx);
1699
1700	ztest_range_unlock(rl);
1701	ztest_object_unlock(zd, lr->lr_foid);
1702
1703	return (0);
1704}
1705
1706static int
1707ztest_replay_truncate(void *arg1, void *arg2, boolean_t byteswap)
1708{
1709	ztest_ds_t *zd = arg1;
1710	lr_truncate_t *lr = arg2;
1711	objset_t *os = zd->zd_os;
1712	dmu_tx_t *tx;
1713	uint64_t txg;
1714	rl_t *rl;
1715
1716	if (byteswap)
1717		byteswap_uint64_array(lr, sizeof (*lr));
1718
1719	ztest_object_lock(zd, lr->lr_foid, RL_READER);
1720	rl = ztest_range_lock(zd, lr->lr_foid, lr->lr_offset, lr->lr_length,
1721	    RL_WRITER);
1722
1723	tx = dmu_tx_create(os);
1724
1725	dmu_tx_hold_free(tx, lr->lr_foid, lr->lr_offset, lr->lr_length);
1726
1727	txg = ztest_tx_assign(tx, TXG_WAIT, FTAG);
1728	if (txg == 0) {
1729		ztest_range_unlock(rl);
1730		ztest_object_unlock(zd, lr->lr_foid);
1731		return (ENOSPC);
1732	}
1733
1734	VERIFY(dmu_free_range(os, lr->lr_foid, lr->lr_offset,
1735	    lr->lr_length, tx) == 0);
1736
1737	(void) ztest_log_truncate(zd, tx, lr);
1738
1739	dmu_tx_commit(tx);
1740
1741	ztest_range_unlock(rl);
1742	ztest_object_unlock(zd, lr->lr_foid);
1743
1744	return (0);
1745}
1746
1747static int
1748ztest_replay_setattr(void *arg1, void *arg2, boolean_t byteswap)
1749{
1750	ztest_ds_t *zd = arg1;
1751	lr_setattr_t *lr = arg2;
1752	objset_t *os = zd->zd_os;
1753	dmu_tx_t *tx;
1754	dmu_buf_t *db;
1755	ztest_block_tag_t *bbt;
1756	uint64_t txg, lrtxg, crtxg;
1757
1758	if (byteswap)
1759		byteswap_uint64_array(lr, sizeof (*lr));
1760
1761	ztest_object_lock(zd, lr->lr_foid, RL_WRITER);
1762
1763	VERIFY3U(0, ==, dmu_bonus_hold(os, lr->lr_foid, FTAG, &db));
1764
1765	tx = dmu_tx_create(os);
1766	dmu_tx_hold_bonus(tx, lr->lr_foid);
1767
1768	txg = ztest_tx_assign(tx, TXG_WAIT, FTAG);
1769	if (txg == 0) {
1770		dmu_buf_rele(db, FTAG);
1771		ztest_object_unlock(zd, lr->lr_foid);
1772		return (ENOSPC);
1773	}
1774
1775	bbt = ztest_bt_bonus(db);
1776	ASSERT3U(bbt->bt_magic, ==, BT_MAGIC);
1777	crtxg = bbt->bt_crtxg;
1778	lrtxg = lr->lr_common.lrc_txg;
1779
1780	if (zd->zd_zilog->zl_replay) {
1781		ASSERT(lr->lr_size != 0);
1782		ASSERT(lr->lr_mode != 0);
1783		ASSERT(lrtxg != 0);
1784	} else {
1785		/*
1786		 * Randomly change the size and increment the generation.
1787		 */
1788		lr->lr_size = (ztest_random(db->db_size / sizeof (*bbt)) + 1) *
1789		    sizeof (*bbt);
1790		lr->lr_mode = bbt->bt_gen + 1;
1791		ASSERT(lrtxg == 0);
1792	}
1793
1794	/*
1795	 * Verify that the current bonus buffer is not newer than our txg.
1796	 */
1797	ztest_bt_verify(bbt, os, lr->lr_foid, -1ULL, lr->lr_mode,
1798	    MAX(txg, lrtxg), crtxg);
1799
1800	dmu_buf_will_dirty(db, tx);
1801
1802	ASSERT3U(lr->lr_size, >=, sizeof (*bbt));
1803	ASSERT3U(lr->lr_size, <=, db->db_size);
1804	VERIFY0(dmu_set_bonus(db, lr->lr_size, tx));
1805	bbt = ztest_bt_bonus(db);
1806
1807	ztest_bt_generate(bbt, os, lr->lr_foid, -1ULL, lr->lr_mode, txg, crtxg);
1808
1809	dmu_buf_rele(db, FTAG);
1810
1811	(void) ztest_log_setattr(zd, tx, lr);
1812
1813	dmu_tx_commit(tx);
1814
1815	ztest_object_unlock(zd, lr->lr_foid);
1816
1817	return (0);
1818}
1819
1820zil_replay_func_t *ztest_replay_vector[TX_MAX_TYPE] = {
1821	NULL,			/* 0 no such transaction type */
1822	ztest_replay_create,	/* TX_CREATE */
1823	NULL,			/* TX_MKDIR */
1824	NULL,			/* TX_MKXATTR */
1825	NULL,			/* TX_SYMLINK */
1826	ztest_replay_remove,	/* TX_REMOVE */
1827	NULL,			/* TX_RMDIR */
1828	NULL,			/* TX_LINK */
1829	NULL,			/* TX_RENAME */
1830	ztest_replay_write,	/* TX_WRITE */
1831	ztest_replay_truncate,	/* TX_TRUNCATE */
1832	ztest_replay_setattr,	/* TX_SETATTR */
1833	NULL,			/* TX_ACL */
1834	NULL,			/* TX_CREATE_ACL */
1835	NULL,			/* TX_CREATE_ATTR */
1836	NULL,			/* TX_CREATE_ACL_ATTR */
1837	NULL,			/* TX_MKDIR_ACL */
1838	NULL,			/* TX_MKDIR_ATTR */
1839	NULL,			/* TX_MKDIR_ACL_ATTR */
1840	NULL,			/* TX_WRITE2 */
1841};
1842
1843/*
1844 * ZIL get_data callbacks
1845 */
1846
1847static void
1848ztest_get_done(zgd_t *zgd, int error)
1849{
1850	ztest_ds_t *zd = zgd->zgd_private;
1851	uint64_t object = zgd->zgd_rl->rl_object;
1852
1853	if (zgd->zgd_db)
1854		dmu_buf_rele(zgd->zgd_db, zgd);
1855
1856	ztest_range_unlock(zgd->zgd_rl);
1857	ztest_object_unlock(zd, object);
1858
1859	if (error == 0 && zgd->zgd_bp)
1860		zil_lwb_add_block(zgd->zgd_lwb, zgd->zgd_bp);
1861
1862	umem_free(zgd, sizeof (*zgd));
1863}
1864
1865static int
1866ztest_get_data(void *arg, lr_write_t *lr, char *buf, struct lwb *lwb,
1867    zio_t *zio)
1868{
1869	ztest_ds_t *zd = arg;
1870	objset_t *os = zd->zd_os;
1871	uint64_t object = lr->lr_foid;
1872	uint64_t offset = lr->lr_offset;
1873	uint64_t size = lr->lr_length;
1874	uint64_t txg = lr->lr_common.lrc_txg;
1875	uint64_t crtxg;
1876	dmu_object_info_t doi;
1877	dmu_buf_t *db;
1878	zgd_t *zgd;
1879	int error;
1880
1881	ASSERT3P(lwb, !=, NULL);
1882	ASSERT3P(zio, !=, NULL);
1883	ASSERT3U(size, !=, 0);
1884
1885	ztest_object_lock(zd, object, RL_READER);
1886	error = dmu_bonus_hold(os, object, FTAG, &db);
1887	if (error) {
1888		ztest_object_unlock(zd, object);
1889		return (error);
1890	}
1891
1892	crtxg = ztest_bt_bonus(db)->bt_crtxg;
1893
1894	if (crtxg == 0 || crtxg > txg) {
1895		dmu_buf_rele(db, FTAG);
1896		ztest_object_unlock(zd, object);
1897		return (ENOENT);
1898	}
1899
1900	dmu_object_info_from_db(db, &doi);
1901	dmu_buf_rele(db, FTAG);
1902	db = NULL;
1903
1904	zgd = umem_zalloc(sizeof (*zgd), UMEM_NOFAIL);
1905	zgd->zgd_lwb = lwb;
1906	zgd->zgd_private = zd;
1907
1908	if (buf != NULL) {	/* immediate write */
1909		zgd->zgd_rl = ztest_range_lock(zd, object, offset, size,
1910		    RL_READER);
1911
1912		error = dmu_read(os, object, offset, size, buf,
1913		    DMU_READ_NO_PREFETCH);
1914		ASSERT(error == 0);
1915	} else {
1916		size = doi.doi_data_block_size;
1917		if (ISP2(size)) {
1918			offset = P2ALIGN(offset, size);
1919		} else {
1920			ASSERT(offset < size);
1921			offset = 0;
1922		}
1923
1924		zgd->zgd_rl = ztest_range_lock(zd, object, offset, size,
1925		    RL_READER);
1926
1927		error = dmu_buf_hold(os, object, offset, zgd, &db,
1928		    DMU_READ_NO_PREFETCH);
1929
1930		if (error == 0) {
1931			blkptr_t *bp = &lr->lr_blkptr;
1932
1933			zgd->zgd_db = db;
1934			zgd->zgd_bp = bp;
1935
1936			ASSERT(db->db_offset == offset);
1937			ASSERT(db->db_size == size);
1938
1939			error = dmu_sync(zio, lr->lr_common.lrc_txg,
1940			    ztest_get_done, zgd);
1941
1942			if (error == 0)
1943				return (0);
1944		}
1945	}
1946
1947	ztest_get_done(zgd, error);
1948
1949	return (error);
1950}
1951
1952static void *
1953ztest_lr_alloc(size_t lrsize, char *name)
1954{
1955	char *lr;
1956	size_t namesize = name ? strlen(name) + 1 : 0;
1957
1958	lr = umem_zalloc(lrsize + namesize, UMEM_NOFAIL);
1959
1960	if (name)
1961		bcopy(name, lr + lrsize, namesize);
1962
1963	return (lr);
1964}
1965
1966void
1967ztest_lr_free(void *lr, size_t lrsize, char *name)
1968{
1969	size_t namesize = name ? strlen(name) + 1 : 0;
1970
1971	umem_free(lr, lrsize + namesize);
1972}
1973
1974/*
1975 * Lookup a bunch of objects.  Returns the number of objects not found.
1976 */
1977static int
1978ztest_lookup(ztest_ds_t *zd, ztest_od_t *od, int count)
1979{
1980	int missing = 0;
1981	int error;
1982
1983	ASSERT(MUTEX_HELD(&zd->zd_dirobj_lock));
1984
1985	for (int i = 0; i < count; i++, od++) {
1986		od->od_object = 0;
1987		error = zap_lookup(zd->zd_os, od->od_dir, od->od_name,
1988		    sizeof (uint64_t), 1, &od->od_object);
1989		if (error) {
1990			ASSERT(error == ENOENT);
1991			ASSERT(od->od_object == 0);
1992			missing++;
1993		} else {
1994			dmu_buf_t *db;
1995			ztest_block_tag_t *bbt;
1996			dmu_object_info_t doi;
1997
1998			ASSERT(od->od_object != 0);
1999			ASSERT(missing == 0);	/* there should be no gaps */
2000
2001			ztest_object_lock(zd, od->od_object, RL_READER);
2002			VERIFY3U(0, ==, dmu_bonus_hold(zd->zd_os,
2003			    od->od_object, FTAG, &db));
2004			dmu_object_info_from_db(db, &doi);
2005			bbt = ztest_bt_bonus(db);
2006			ASSERT3U(bbt->bt_magic, ==, BT_MAGIC);
2007			od->od_type = doi.doi_type;
2008			od->od_blocksize = doi.doi_data_block_size;
2009			od->od_gen = bbt->bt_gen;
2010			dmu_buf_rele(db, FTAG);
2011			ztest_object_unlock(zd, od->od_object);
2012		}
2013	}
2014
2015	return (missing);
2016}
2017
2018static int
2019ztest_create(ztest_ds_t *zd, ztest_od_t *od, int count)
2020{
2021	int missing = 0;
2022
2023	ASSERT(MUTEX_HELD(&zd->zd_dirobj_lock));
2024
2025	for (int i = 0; i < count; i++, od++) {
2026		if (missing) {
2027			od->od_object = 0;
2028			missing++;
2029			continue;
2030		}
2031
2032		lr_create_t *lr = ztest_lr_alloc(sizeof (*lr), od->od_name);
2033
2034		lr->lr_doid = od->od_dir;
2035		lr->lr_foid = 0;	/* 0 to allocate, > 0 to claim */
2036		lr->lrz_type = od->od_crtype;
2037		lr->lrz_blocksize = od->od_crblocksize;
2038		lr->lrz_ibshift = ztest_random_ibshift();
2039		lr->lrz_bonustype = DMU_OT_UINT64_OTHER;
2040		lr->lrz_bonuslen = dmu_bonus_max();
2041		lr->lr_gen = od->od_crgen;
2042		lr->lr_crtime[0] = time(NULL);
2043
2044		if (ztest_replay_create(zd, lr, B_FALSE) != 0) {
2045			ASSERT(missing == 0);
2046			od->od_object = 0;
2047			missing++;
2048		} else {
2049			od->od_object = lr->lr_foid;
2050			od->od_type = od->od_crtype;
2051			od->od_blocksize = od->od_crblocksize;
2052			od->od_gen = od->od_crgen;
2053			ASSERT(od->od_object != 0);
2054		}
2055
2056		ztest_lr_free(lr, sizeof (*lr), od->od_name);
2057	}
2058
2059	return (missing);
2060}
2061
2062static int
2063ztest_remove(ztest_ds_t *zd, ztest_od_t *od, int count)
2064{
2065	int missing = 0;
2066	int error;
2067
2068	ASSERT(MUTEX_HELD(&zd->zd_dirobj_lock));
2069
2070	od += count - 1;
2071
2072	for (int i = count - 1; i >= 0; i--, od--) {
2073		if (missing) {
2074			missing++;
2075			continue;
2076		}
2077
2078		/*
2079		 * No object was found.
2080		 */
2081		if (od->od_object == 0)
2082			continue;
2083
2084		lr_remove_t *lr = ztest_lr_alloc(sizeof (*lr), od->od_name);
2085
2086		lr->lr_doid = od->od_dir;
2087
2088		if ((error = ztest_replay_remove(zd, lr, B_FALSE)) != 0) {
2089			ASSERT3U(error, ==, ENOSPC);
2090			missing++;
2091		} else {
2092			od->od_object = 0;
2093		}
2094		ztest_lr_free(lr, sizeof (*lr), od->od_name);
2095	}
2096
2097	return (missing);
2098}
2099
2100static int
2101ztest_write(ztest_ds_t *zd, uint64_t object, uint64_t offset, uint64_t size,
2102    void *data)
2103{
2104	lr_write_t *lr;
2105	int error;
2106
2107	lr = ztest_lr_alloc(sizeof (*lr) + size, NULL);
2108
2109	lr->lr_foid = object;
2110	lr->lr_offset = offset;
2111	lr->lr_length = size;
2112	lr->lr_blkoff = 0;
2113	BP_ZERO(&lr->lr_blkptr);
2114
2115	bcopy(data, lr + 1, size);
2116
2117	error = ztest_replay_write(zd, lr, B_FALSE);
2118
2119	ztest_lr_free(lr, sizeof (*lr) + size, NULL);
2120
2121	return (error);
2122}
2123
2124static int
2125ztest_truncate(ztest_ds_t *zd, uint64_t object, uint64_t offset, uint64_t size)
2126{
2127	lr_truncate_t *lr;
2128	int error;
2129
2130	lr = ztest_lr_alloc(sizeof (*lr), NULL);
2131
2132	lr->lr_foid = object;
2133	lr->lr_offset = offset;
2134	lr->lr_length = size;
2135
2136	error = ztest_replay_truncate(zd, lr, B_FALSE);
2137
2138	ztest_lr_free(lr, sizeof (*lr), NULL);
2139
2140	return (error);
2141}
2142
2143static int
2144ztest_setattr(ztest_ds_t *zd, uint64_t object)
2145{
2146	lr_setattr_t *lr;
2147	int error;
2148
2149	lr = ztest_lr_alloc(sizeof (*lr), NULL);
2150
2151	lr->lr_foid = object;
2152	lr->lr_size = 0;
2153	lr->lr_mode = 0;
2154
2155	error = ztest_replay_setattr(zd, lr, B_FALSE);
2156
2157	ztest_lr_free(lr, sizeof (*lr), NULL);
2158
2159	return (error);
2160}
2161
2162static void
2163ztest_prealloc(ztest_ds_t *zd, uint64_t object, uint64_t offset, uint64_t size)
2164{
2165	objset_t *os = zd->zd_os;
2166	dmu_tx_t *tx;
2167	uint64_t txg;
2168	rl_t *rl;
2169
2170	txg_wait_synced(dmu_objset_pool(os), 0);
2171
2172	ztest_object_lock(zd, object, RL_READER);
2173	rl = ztest_range_lock(zd, object, offset, size, RL_WRITER);
2174
2175	tx = dmu_tx_create(os);
2176
2177	dmu_tx_hold_write(tx, object, offset, size);
2178
2179	txg = ztest_tx_assign(tx, TXG_WAIT, FTAG);
2180
2181	if (txg != 0) {
2182		dmu_prealloc(os, object, offset, size, tx);
2183		dmu_tx_commit(tx);
2184		txg_wait_synced(dmu_objset_pool(os), txg);
2185	} else {
2186		(void) dmu_free_long_range(os, object, offset, size);
2187	}
2188
2189	ztest_range_unlock(rl);
2190	ztest_object_unlock(zd, object);
2191}
2192
2193static void
2194ztest_io(ztest_ds_t *zd, uint64_t object, uint64_t offset)
2195{
2196	int err;
2197	ztest_block_tag_t wbt;
2198	dmu_object_info_t doi;
2199	enum ztest_io_type io_type;
2200	uint64_t blocksize;
2201	void *data;
2202
2203	VERIFY(dmu_object_info(zd->zd_os, object, &doi) == 0);
2204	blocksize = doi.doi_data_block_size;
2205	data = umem_alloc(blocksize, UMEM_NOFAIL);
2206
2207	/*
2208	 * Pick an i/o type at random, biased toward writing block tags.
2209	 */
2210	io_type = ztest_random(ZTEST_IO_TYPES);
2211	if (ztest_random(2) == 0)
2212		io_type = ZTEST_IO_WRITE_TAG;
2213
2214	rw_enter(&zd->zd_zilog_lock, RW_READER);
2215
2216	switch (io_type) {
2217
2218	case ZTEST_IO_WRITE_TAG:
2219		ztest_bt_generate(&wbt, zd->zd_os, object, offset, 0, 0, 0);
2220		(void) ztest_write(zd, object, offset, sizeof (wbt), &wbt);
2221		break;
2222
2223	case ZTEST_IO_WRITE_PATTERN:
2224		(void) memset(data, 'a' + (object + offset) % 5, blocksize);
2225		if (ztest_random(2) == 0) {
2226			/*
2227			 * Induce fletcher2 collisions to ensure that
2228			 * zio_ddt_collision() detects and resolves them
2229			 * when using fletcher2-verify for deduplication.
2230			 */
2231			((uint64_t *)data)[0] ^= 1ULL << 63;
2232			((uint64_t *)data)[4] ^= 1ULL << 63;
2233		}
2234		(void) ztest_write(zd, object, offset, blocksize, data);
2235		break;
2236
2237	case ZTEST_IO_WRITE_ZEROES:
2238		bzero(data, blocksize);
2239		(void) ztest_write(zd, object, offset, blocksize, data);
2240		break;
2241
2242	case ZTEST_IO_TRUNCATE:
2243		(void) ztest_truncate(zd, object, offset, blocksize);
2244		break;
2245
2246	case ZTEST_IO_SETATTR:
2247		(void) ztest_setattr(zd, object);
2248		break;
2249
2250	case ZTEST_IO_REWRITE:
2251		rw_enter(&ztest_name_lock, RW_READER);
2252		err = ztest_dsl_prop_set_uint64(zd->zd_name,
2253		    ZFS_PROP_CHECKSUM, spa_dedup_checksum(ztest_spa),
2254		    B_FALSE);
2255		VERIFY(err == 0 || err == ENOSPC);
2256		err = ztest_dsl_prop_set_uint64(zd->zd_name,
2257		    ZFS_PROP_COMPRESSION,
2258		    ztest_random_dsl_prop(ZFS_PROP_COMPRESSION),
2259		    B_FALSE);
2260		VERIFY(err == 0 || err == ENOSPC);
2261		rw_exit(&ztest_name_lock);
2262
2263		VERIFY0(dmu_read(zd->zd_os, object, offset, blocksize, data,
2264		    DMU_READ_NO_PREFETCH));
2265
2266		(void) ztest_write(zd, object, offset, blocksize, data);
2267		break;
2268	}
2269
2270	rw_exit(&zd->zd_zilog_lock);
2271
2272	umem_free(data, blocksize);
2273}
2274
2275/*
2276 * Initialize an object description template.
2277 */
2278static void
2279ztest_od_init(ztest_od_t *od, uint64_t id, char *tag, uint64_t index,
2280    dmu_object_type_t type, uint64_t blocksize, uint64_t gen)
2281{
2282	od->od_dir = ZTEST_DIROBJ;
2283	od->od_object = 0;
2284
2285	od->od_crtype = type;
2286	od->od_crblocksize = blocksize ? blocksize : ztest_random_blocksize();
2287	od->od_crgen = gen;
2288
2289	od->od_type = DMU_OT_NONE;
2290	od->od_blocksize = 0;
2291	od->od_gen = 0;
2292
2293	(void) snprintf(od->od_name, sizeof (od->od_name), "%s(%lld)[%llu]",
2294	    tag, (int64_t)id, index);
2295}
2296
2297/*
2298 * Lookup or create the objects for a test using the od template.
2299 * If the objects do not all exist, or if 'remove' is specified,
2300 * remove any existing objects and create new ones.  Otherwise,
2301 * use the existing objects.
2302 */
2303static int
2304ztest_object_init(ztest_ds_t *zd, ztest_od_t *od, size_t size, boolean_t remove)
2305{
2306	int count = size / sizeof (*od);
2307	int rv = 0;
2308
2309	mutex_enter(&zd->zd_dirobj_lock);
2310	if ((ztest_lookup(zd, od, count) != 0 || remove) &&
2311	    (ztest_remove(zd, od, count) != 0 ||
2312	    ztest_create(zd, od, count) != 0))
2313		rv = -1;
2314	zd->zd_od = od;
2315	mutex_exit(&zd->zd_dirobj_lock);
2316
2317	return (rv);
2318}
2319
2320/* ARGSUSED */
2321void
2322ztest_zil_commit(ztest_ds_t *zd, uint64_t id)
2323{
2324	zilog_t *zilog = zd->zd_zilog;
2325
2326	rw_enter(&zd->zd_zilog_lock, RW_READER);
2327
2328	zil_commit(zilog, ztest_random(ZTEST_OBJECTS));
2329
2330	/*
2331	 * Remember the committed values in zd, which is in parent/child
2332	 * shared memory.  If we die, the next iteration of ztest_run()
2333	 * will verify that the log really does contain this record.
2334	 */
2335	mutex_enter(&zilog->zl_lock);
2336	ASSERT(zd->zd_shared != NULL);
2337	ASSERT3U(zd->zd_shared->zd_seq, <=, zilog->zl_commit_lr_seq);
2338	zd->zd_shared->zd_seq = zilog->zl_commit_lr_seq;
2339	mutex_exit(&zilog->zl_lock);
2340
2341	rw_exit(&zd->zd_zilog_lock);
2342}
2343
2344/*
2345 * This function is designed to simulate the operations that occur during a
2346 * mount/unmount operation.  We hold the dataset across these operations in an
2347 * attempt to expose any implicit assumptions about ZIL management.
2348 */
2349/* ARGSUSED */
2350void
2351ztest_zil_remount(ztest_ds_t *zd, uint64_t id)
2352{
2353	objset_t *os = zd->zd_os;
2354
2355	/*
2356	 * We grab the zd_dirobj_lock to ensure that no other thread is
2357	 * updating the zil (i.e. adding in-memory log records) and the
2358	 * zd_zilog_lock to block any I/O.
2359	 */
2360	mutex_enter(&zd->zd_dirobj_lock);
2361	rw_enter(&zd->zd_zilog_lock, RW_WRITER);
2362
2363	/* zfsvfs_teardown() */
2364	zil_close(zd->zd_zilog);
2365
2366	/* zfsvfs_setup() */
2367	VERIFY(zil_open(os, ztest_get_data) == zd->zd_zilog);
2368	zil_replay(os, zd, ztest_replay_vector);
2369
2370	rw_exit(&zd->zd_zilog_lock);
2371	mutex_exit(&zd->zd_dirobj_lock);
2372}
2373
2374/*
2375 * Verify that we can't destroy an active pool, create an existing pool,
2376 * or create a pool with a bad vdev spec.
2377 */
2378/* ARGSUSED */
2379void
2380ztest_spa_create_destroy(ztest_ds_t *zd, uint64_t id)
2381{
2382	ztest_shared_opts_t *zo = &ztest_opts;
2383	spa_t *spa;
2384	nvlist_t *nvroot;
2385
2386	/*
2387	 * Attempt to create using a bad file.
2388	 */
2389	nvroot = make_vdev_root("/dev/bogus", NULL, NULL, 0, 0, 0, 0, 0, 1);
2390	VERIFY3U(ENOENT, ==,
2391	    spa_create("ztest_bad_file", nvroot, NULL, NULL));
2392	nvlist_free(nvroot);
2393
2394	/*
2395	 * Attempt to create using a bad mirror.
2396	 */
2397	nvroot = make_vdev_root("/dev/bogus", NULL, NULL, 0, 0, 0, 0, 2, 1);
2398	VERIFY3U(ENOENT, ==,
2399	    spa_create("ztest_bad_mirror", nvroot, NULL, NULL));
2400	nvlist_free(nvroot);
2401
2402	/*
2403	 * Attempt to create an existing pool.  It shouldn't matter
2404	 * what's in the nvroot; we should fail with EEXIST.
2405	 */
2406	rw_enter(&ztest_name_lock, RW_READER);
2407	nvroot = make_vdev_root("/dev/bogus", NULL, NULL, 0, 0, 0, 0, 0, 1);
2408	VERIFY3U(EEXIST, ==, spa_create(zo->zo_pool, nvroot, NULL, NULL));
2409	nvlist_free(nvroot);
2410	VERIFY3U(0, ==, spa_open(zo->zo_pool, &spa, FTAG));
2411	VERIFY3U(EBUSY, ==, spa_destroy(zo->zo_pool));
2412	spa_close(spa, FTAG);
2413
2414	rw_exit(&ztest_name_lock);
2415}
2416
2417/* ARGSUSED */
2418void
2419ztest_spa_upgrade(ztest_ds_t *zd, uint64_t id)
2420{
2421	spa_t *spa;
2422	uint64_t initial_version = SPA_VERSION_INITIAL;
2423	uint64_t version, newversion;
2424	nvlist_t *nvroot, *props;
2425	char *name;
2426
2427	mutex_enter(&ztest_vdev_lock);
2428	name = kmem_asprintf("%s_upgrade", ztest_opts.zo_pool);
2429
2430	/*
2431	 * Clean up from previous runs.
2432	 */
2433	(void) spa_destroy(name);
2434
2435	nvroot = make_vdev_root(NULL, NULL, name, ztest_opts.zo_vdev_size, 0,
2436	    0, ztest_opts.zo_raidz, ztest_opts.zo_mirrors, 1);
2437
2438	/*
2439	 * If we're configuring a RAIDZ device then make sure that the
2440	 * the initial version is capable of supporting that feature.
2441	 */
2442	switch (ztest_opts.zo_raidz_parity) {
2443	case 0:
2444	case 1:
2445		initial_version = SPA_VERSION_INITIAL;
2446		break;
2447	case 2:
2448		initial_version = SPA_VERSION_RAIDZ2;
2449		break;
2450	case 3:
2451		initial_version = SPA_VERSION_RAIDZ3;
2452		break;
2453	}
2454
2455	/*
2456	 * Create a pool with a spa version that can be upgraded. Pick
2457	 * a value between initial_version and SPA_VERSION_BEFORE_FEATURES.
2458	 */
2459	do {
2460		version = ztest_random_spa_version(initial_version);
2461	} while (version > SPA_VERSION_BEFORE_FEATURES);
2462
2463	props = fnvlist_alloc();
2464	fnvlist_add_uint64(props,
2465	    zpool_prop_to_name(ZPOOL_PROP_VERSION), version);
2466	VERIFY0(spa_create(name, nvroot, props, NULL));
2467	fnvlist_free(nvroot);
2468	fnvlist_free(props);
2469
2470	VERIFY0(spa_open(name, &spa, FTAG));
2471	VERIFY3U(spa_version(spa), ==, version);
2472	newversion = ztest_random_spa_version(version + 1);
2473
2474	if (ztest_opts.zo_verbose >= 4) {
2475		(void) printf("upgrading spa version from %llu to %llu\n",
2476		    (u_longlong_t)version, (u_longlong_t)newversion);
2477	}
2478
2479	spa_upgrade(spa, newversion);
2480	VERIFY3U(spa_version(spa), >, version);
2481	VERIFY3U(spa_version(spa), ==, fnvlist_lookup_uint64(spa->spa_config,
2482	    zpool_prop_to_name(ZPOOL_PROP_VERSION)));
2483	spa_close(spa, FTAG);
2484
2485	strfree(name);
2486	mutex_exit(&ztest_vdev_lock);
2487}
2488
2489static void
2490ztest_spa_checkpoint(spa_t *spa)
2491{
2492	ASSERT(MUTEX_HELD(&ztest_checkpoint_lock));
2493
2494	int error = spa_checkpoint(spa->spa_name);
2495
2496	switch (error) {
2497	case 0:
2498	case ZFS_ERR_DEVRM_IN_PROGRESS:
2499	case ZFS_ERR_DISCARDING_CHECKPOINT:
2500	case ZFS_ERR_CHECKPOINT_EXISTS:
2501		break;
2502	case ENOSPC:
2503		ztest_record_enospc(FTAG);
2504		break;
2505	default:
2506		fatal(0, "spa_checkpoint(%s) = %d", spa->spa_name, error);
2507	}
2508}
2509
2510static void
2511ztest_spa_discard_checkpoint(spa_t *spa)
2512{
2513	ASSERT(MUTEX_HELD(&ztest_checkpoint_lock));
2514
2515	int error = spa_checkpoint_discard(spa->spa_name);
2516
2517	switch (error) {
2518	case 0:
2519	case ZFS_ERR_DISCARDING_CHECKPOINT:
2520	case ZFS_ERR_NO_CHECKPOINT:
2521		break;
2522	default:
2523		fatal(0, "spa_discard_checkpoint(%s) = %d",
2524		    spa->spa_name, error);
2525	}
2526
2527}
2528
2529/* ARGSUSED */
2530void
2531ztest_spa_checkpoint_create_discard(ztest_ds_t *zd, uint64_t id)
2532{
2533	spa_t *spa = ztest_spa;
2534
2535	mutex_enter(&ztest_checkpoint_lock);
2536	if (ztest_random(2) == 0) {
2537		ztest_spa_checkpoint(spa);
2538	} else {
2539		ztest_spa_discard_checkpoint(spa);
2540	}
2541	mutex_exit(&ztest_checkpoint_lock);
2542}
2543
2544
2545static vdev_t *
2546vdev_lookup_by_path(vdev_t *vd, const char *path)
2547{
2548	vdev_t *mvd;
2549
2550	if (vd->vdev_path != NULL && strcmp(path, vd->vdev_path) == 0)
2551		return (vd);
2552
2553	for (int c = 0; c < vd->vdev_children; c++)
2554		if ((mvd = vdev_lookup_by_path(vd->vdev_child[c], path)) !=
2555		    NULL)
2556			return (mvd);
2557
2558	return (NULL);
2559}
2560
2561/*
2562 * Find the first available hole which can be used as a top-level.
2563 */
2564int
2565find_vdev_hole(spa_t *spa)
2566{
2567	vdev_t *rvd = spa->spa_root_vdev;
2568	int c;
2569
2570	ASSERT(spa_config_held(spa, SCL_VDEV, RW_READER) == SCL_VDEV);
2571
2572	for (c = 0; c < rvd->vdev_children; c++) {
2573		vdev_t *cvd = rvd->vdev_child[c];
2574
2575		if (cvd->vdev_ishole)
2576			break;
2577	}
2578	return (c);
2579}
2580
2581/*
2582 * Verify that vdev_add() works as expected.
2583 */
2584/* ARGSUSED */
2585void
2586ztest_vdev_add_remove(ztest_ds_t *zd, uint64_t id)
2587{
2588	ztest_shared_t *zs = ztest_shared;
2589	spa_t *spa = ztest_spa;
2590	uint64_t leaves;
2591	uint64_t guid;
2592	nvlist_t *nvroot;
2593	int error;
2594
2595	mutex_enter(&ztest_vdev_lock);
2596	leaves = MAX(zs->zs_mirrors + zs->zs_splits, 1) * ztest_opts.zo_raidz;
2597
2598	spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
2599
2600	ztest_shared->zs_vdev_next_leaf = find_vdev_hole(spa) * leaves;
2601
2602	/*
2603	 * If we have slogs then remove them 1/4 of the time.
2604	 */
2605	if (spa_has_slogs(spa) && ztest_random(4) == 0) {
2606		/*
2607		 * Grab the guid from the head of the log class rotor.
2608		 */
2609		guid = spa_log_class(spa)->mc_rotor->mg_vd->vdev_guid;
2610
2611		spa_config_exit(spa, SCL_VDEV, FTAG);
2612
2613		/*
2614		 * We have to grab the zs_name_lock as writer to
2615		 * prevent a race between removing a slog (dmu_objset_find)
2616		 * and destroying a dataset. Removing the slog will
2617		 * grab a reference on the dataset which may cause
2618		 * dmu_objset_destroy() to fail with EBUSY thus
2619		 * leaving the dataset in an inconsistent state.
2620		 */
2621		rw_enter(&ztest_name_lock, RW_WRITER);
2622		error = spa_vdev_remove(spa, guid, B_FALSE);
2623		rw_exit(&ztest_name_lock);
2624
2625		switch (error) {
2626		case 0:
2627		case EEXIST:
2628		case ZFS_ERR_CHECKPOINT_EXISTS:
2629		case ZFS_ERR_DISCARDING_CHECKPOINT:
2630			break;
2631		default:
2632			fatal(0, "spa_vdev_remove() = %d", error);
2633		}
2634	} else {
2635		spa_config_exit(spa, SCL_VDEV, FTAG);
2636
2637		/*
2638		 * Make 1/4 of the devices be log devices.
2639		 */
2640		nvroot = make_vdev_root(NULL, NULL, NULL,
2641		    ztest_opts.zo_vdev_size, 0,
2642		    ztest_random(4) == 0, ztest_opts.zo_raidz,
2643		    zs->zs_mirrors, 1);
2644
2645		error = spa_vdev_add(spa, nvroot);
2646		nvlist_free(nvroot);
2647
2648		switch (error) {
2649		case 0:
2650			break;
2651		case ENOSPC:
2652			ztest_record_enospc("spa_vdev_add");
2653			break;
2654		default:
2655			fatal(0, "spa_vdev_add() = %d", error);
2656		}
2657	}
2658
2659	mutex_exit(&ztest_vdev_lock);
2660}
2661
2662/*
2663 * Verify that adding/removing aux devices (l2arc, hot spare) works as expected.
2664 */
2665/* ARGSUSED */
2666void
2667ztest_vdev_aux_add_remove(ztest_ds_t *zd, uint64_t id)
2668{
2669	ztest_shared_t *zs = ztest_shared;
2670	spa_t *spa = ztest_spa;
2671	vdev_t *rvd = spa->spa_root_vdev;
2672	spa_aux_vdev_t *sav;
2673	char *aux;
2674	uint64_t guid = 0;
2675	int error;
2676
2677	if (ztest_random(2) == 0) {
2678		sav = &spa->spa_spares;
2679		aux = ZPOOL_CONFIG_SPARES;
2680	} else {
2681		sav = &spa->spa_l2cache;
2682		aux = ZPOOL_CONFIG_L2CACHE;
2683	}
2684
2685	mutex_enter(&ztest_vdev_lock);
2686
2687	spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
2688
2689	if (sav->sav_count != 0 && ztest_random(4) == 0) {
2690		/*
2691		 * Pick a random device to remove.
2692		 */
2693		guid = sav->sav_vdevs[ztest_random(sav->sav_count)]->vdev_guid;
2694	} else {
2695		/*
2696		 * Find an unused device we can add.
2697		 */
2698		zs->zs_vdev_aux = 0;
2699		for (;;) {
2700			char path[MAXPATHLEN];
2701			int c;
2702			(void) snprintf(path, sizeof (path), ztest_aux_template,
2703			    ztest_opts.zo_dir, ztest_opts.zo_pool, aux,
2704			    zs->zs_vdev_aux);
2705			for (c = 0; c < sav->sav_count; c++)
2706				if (strcmp(sav->sav_vdevs[c]->vdev_path,
2707				    path) == 0)
2708					break;
2709			if (c == sav->sav_count &&
2710			    vdev_lookup_by_path(rvd, path) == NULL)
2711				break;
2712			zs->zs_vdev_aux++;
2713		}
2714	}
2715
2716	spa_config_exit(spa, SCL_VDEV, FTAG);
2717
2718	if (guid == 0) {
2719		/*
2720		 * Add a new device.
2721		 */
2722		nvlist_t *nvroot = make_vdev_root(NULL, aux, NULL,
2723		    (ztest_opts.zo_vdev_size * 5) / 4, 0, 0, 0, 0, 1);
2724		error = spa_vdev_add(spa, nvroot);
2725
2726		switch (error) {
2727		case 0:
2728			break;
2729		default:
2730			fatal(0, "spa_vdev_add(%p) = %d", nvroot, error);
2731		}
2732		nvlist_free(nvroot);
2733	} else {
2734		/*
2735		 * Remove an existing device.  Sometimes, dirty its
2736		 * vdev state first to make sure we handle removal
2737		 * of devices that have pending state changes.
2738		 */
2739		if (ztest_random(2) == 0)
2740			(void) vdev_online(spa, guid, 0, NULL);
2741
2742		error = spa_vdev_remove(spa, guid, B_FALSE);
2743
2744		switch (error) {
2745		case 0:
2746		case EBUSY:
2747		case ZFS_ERR_CHECKPOINT_EXISTS:
2748		case ZFS_ERR_DISCARDING_CHECKPOINT:
2749			break;
2750		default:
2751			fatal(0, "spa_vdev_remove(%llu) = %d", guid, error);
2752		}
2753	}
2754
2755	mutex_exit(&ztest_vdev_lock);
2756}
2757
2758/*
2759 * split a pool if it has mirror tlvdevs
2760 */
2761/* ARGSUSED */
2762void
2763ztest_split_pool(ztest_ds_t *zd, uint64_t id)
2764{
2765	ztest_shared_t *zs = ztest_shared;
2766	spa_t *spa = ztest_spa;
2767	vdev_t *rvd = spa->spa_root_vdev;
2768	nvlist_t *tree, **child, *config, *split, **schild;
2769	uint_t c, children, schildren = 0, lastlogid = 0;
2770	int error = 0;
2771
2772	mutex_enter(&ztest_vdev_lock);
2773
2774	/* ensure we have a useable config; mirrors of raidz aren't supported */
2775	if (zs->zs_mirrors < 3 || ztest_opts.zo_raidz > 1) {
2776		mutex_exit(&ztest_vdev_lock);
2777		return;
2778	}
2779
2780	/* clean up the old pool, if any */
2781	(void) spa_destroy("splitp");
2782
2783	spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
2784
2785	/* generate a config from the existing config */
2786	mutex_enter(&spa->spa_props_lock);
2787	VERIFY(nvlist_lookup_nvlist(spa->spa_config, ZPOOL_CONFIG_VDEV_TREE,
2788	    &tree) == 0);
2789	mutex_exit(&spa->spa_props_lock);
2790
2791	VERIFY(nvlist_lookup_nvlist_array(tree, ZPOOL_CONFIG_CHILDREN, &child,
2792	    &children) == 0);
2793
2794	schild = malloc(rvd->vdev_children * sizeof (nvlist_t *));
2795	for (c = 0; c < children; c++) {
2796		vdev_t *tvd = rvd->vdev_child[c];
2797		nvlist_t **mchild;
2798		uint_t mchildren;
2799
2800		if (tvd->vdev_islog || tvd->vdev_ops == &vdev_hole_ops) {
2801			VERIFY(nvlist_alloc(&schild[schildren], NV_UNIQUE_NAME,
2802			    0) == 0);
2803			VERIFY(nvlist_add_string(schild[schildren],
2804			    ZPOOL_CONFIG_TYPE, VDEV_TYPE_HOLE) == 0);
2805			VERIFY(nvlist_add_uint64(schild[schildren],
2806			    ZPOOL_CONFIG_IS_HOLE, 1) == 0);
2807			if (lastlogid == 0)
2808				lastlogid = schildren;
2809			++schildren;
2810			continue;
2811		}
2812		lastlogid = 0;
2813		VERIFY(nvlist_lookup_nvlist_array(child[c],
2814		    ZPOOL_CONFIG_CHILDREN, &mchild, &mchildren) == 0);
2815		VERIFY(nvlist_dup(mchild[0], &schild[schildren++], 0) == 0);
2816	}
2817
2818	/* OK, create a config that can be used to split */
2819	VERIFY(nvlist_alloc(&split, NV_UNIQUE_NAME, 0) == 0);
2820	VERIFY(nvlist_add_string(split, ZPOOL_CONFIG_TYPE,
2821	    VDEV_TYPE_ROOT) == 0);
2822	VERIFY(nvlist_add_nvlist_array(split, ZPOOL_CONFIG_CHILDREN, schild,
2823	    lastlogid != 0 ? lastlogid : schildren) == 0);
2824
2825	VERIFY(nvlist_alloc(&config, NV_UNIQUE_NAME, 0) == 0);
2826	VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, split) == 0);
2827
2828	for (c = 0; c < schildren; c++)
2829		nvlist_free(schild[c]);
2830	free(schild);
2831	nvlist_free(split);
2832
2833	spa_config_exit(spa, SCL_VDEV, FTAG);
2834
2835	rw_enter(&ztest_name_lock, RW_WRITER);
2836	error = spa_vdev_split_mirror(spa, "splitp", config, NULL, B_FALSE);
2837	rw_exit(&ztest_name_lock);
2838
2839	nvlist_free(config);
2840
2841	if (error == 0) {
2842		(void) printf("successful split - results:\n");
2843		mutex_enter(&spa_namespace_lock);
2844		show_pool_stats(spa);
2845		show_pool_stats(spa_lookup("splitp"));
2846		mutex_exit(&spa_namespace_lock);
2847		++zs->zs_splits;
2848		--zs->zs_mirrors;
2849	}
2850	mutex_exit(&ztest_vdev_lock);
2851}
2852
2853/*
2854 * Verify that we can attach and detach devices.
2855 */
2856/* ARGSUSED */
2857void
2858ztest_vdev_attach_detach(ztest_ds_t *zd, uint64_t id)
2859{
2860	ztest_shared_t *zs = ztest_shared;
2861	spa_t *spa = ztest_spa;
2862	spa_aux_vdev_t *sav = &spa->spa_spares;
2863	vdev_t *rvd = spa->spa_root_vdev;
2864	vdev_t *oldvd, *newvd, *pvd;
2865	nvlist_t *root;
2866	uint64_t leaves;
2867	uint64_t leaf, top;
2868	uint64_t ashift = ztest_get_ashift();
2869	uint64_t oldguid, pguid;
2870	uint64_t oldsize, newsize;
2871	char oldpath[MAXPATHLEN], newpath[MAXPATHLEN];
2872	int replacing;
2873	int oldvd_has_siblings = B_FALSE;
2874	int newvd_is_spare = B_FALSE;
2875	int oldvd_is_log;
2876	int error, expected_error;
2877
2878	mutex_enter(&ztest_vdev_lock);
2879	leaves = MAX(zs->zs_mirrors, 1) * ztest_opts.zo_raidz;
2880
2881	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
2882
2883	/*
2884	 * If a vdev is in the process of being removed, its removal may
2885	 * finish while we are in progress, leading to an unexpected error
2886	 * value.  Don't bother trying to attach while we are in the middle
2887	 * of removal.
2888	 */
2889	if (ztest_device_removal_active) {
2890		spa_config_exit(spa, SCL_ALL, FTAG);
2891		mutex_exit(&ztest_vdev_lock);
2892		return;
2893	}
2894
2895	/*
2896	 * Decide whether to do an attach or a replace.
2897	 */
2898	replacing = ztest_random(2);
2899
2900	/*
2901	 * Pick a random top-level vdev.
2902	 */
2903	top = ztest_random_vdev_top(spa, B_TRUE);
2904
2905	/*
2906	 * Pick a random leaf within it.
2907	 */
2908	leaf = ztest_random(leaves);
2909
2910	/*
2911	 * Locate this vdev.
2912	 */
2913	oldvd = rvd->vdev_child[top];
2914	if (zs->zs_mirrors >= 1) {
2915		ASSERT(oldvd->vdev_ops == &vdev_mirror_ops);
2916		ASSERT(oldvd->vdev_children >= zs->zs_mirrors);
2917		oldvd = oldvd->vdev_child[leaf / ztest_opts.zo_raidz];
2918	}
2919	if (ztest_opts.zo_raidz > 1) {
2920		ASSERT(oldvd->vdev_ops == &vdev_raidz_ops);
2921		ASSERT(oldvd->vdev_children == ztest_opts.zo_raidz);
2922		oldvd = oldvd->vdev_child[leaf % ztest_opts.zo_raidz];
2923	}
2924
2925	/*
2926	 * If we're already doing an attach or replace, oldvd may be a
2927	 * mirror vdev -- in which case, pick a random child.
2928	 */
2929	while (oldvd->vdev_children != 0) {
2930		oldvd_has_siblings = B_TRUE;
2931		ASSERT(oldvd->vdev_children >= 2);
2932		oldvd = oldvd->vdev_child[ztest_random(oldvd->vdev_children)];
2933	}
2934
2935	oldguid = oldvd->vdev_guid;
2936	oldsize = vdev_get_min_asize(oldvd);
2937	oldvd_is_log = oldvd->vdev_top->vdev_islog;
2938	(void) strcpy(oldpath, oldvd->vdev_path);
2939	pvd = oldvd->vdev_parent;
2940	pguid = pvd->vdev_guid;
2941
2942	/*
2943	 * If oldvd has siblings, then half of the time, detach it.
2944	 */
2945	if (oldvd_has_siblings && ztest_random(2) == 0) {
2946		spa_config_exit(spa, SCL_ALL, FTAG);
2947		error = spa_vdev_detach(spa, oldguid, pguid, B_FALSE);
2948		if (error != 0 && error != ENODEV && error != EBUSY &&
2949		    error != ENOTSUP && error != ZFS_ERR_CHECKPOINT_EXISTS &&
2950		    error != ZFS_ERR_DISCARDING_CHECKPOINT)
2951			fatal(0, "detach (%s) returned %d", oldpath, error);
2952		mutex_exit(&ztest_vdev_lock);
2953		return;
2954	}
2955
2956	/*
2957	 * For the new vdev, choose with equal probability between the two
2958	 * standard paths (ending in either 'a' or 'b') or a random hot spare.
2959	 */
2960	if (sav->sav_count != 0 && ztest_random(3) == 0) {
2961		newvd = sav->sav_vdevs[ztest_random(sav->sav_count)];
2962		newvd_is_spare = B_TRUE;
2963		(void) strcpy(newpath, newvd->vdev_path);
2964	} else {
2965		(void) snprintf(newpath, sizeof (newpath), ztest_dev_template,
2966		    ztest_opts.zo_dir, ztest_opts.zo_pool,
2967		    top * leaves + leaf);
2968		if (ztest_random(2) == 0)
2969			newpath[strlen(newpath) - 1] = 'b';
2970		newvd = vdev_lookup_by_path(rvd, newpath);
2971	}
2972
2973	if (newvd) {
2974		/*
2975		 * Reopen to ensure the vdev's asize field isn't stale.
2976		 */
2977		vdev_reopen(newvd);
2978		newsize = vdev_get_min_asize(newvd);
2979	} else {
2980		/*
2981		 * Make newsize a little bigger or smaller than oldsize.
2982		 * If it's smaller, the attach should fail.
2983		 * If it's larger, and we're doing a replace,
2984		 * we should get dynamic LUN growth when we're done.
2985		 */
2986		newsize = 10 * oldsize / (9 + ztest_random(3));
2987	}
2988
2989	/*
2990	 * If pvd is not a mirror or root, the attach should fail with ENOTSUP,
2991	 * unless it's a replace; in that case any non-replacing parent is OK.
2992	 *
2993	 * If newvd is already part of the pool, it should fail with EBUSY.
2994	 *
2995	 * If newvd is too small, it should fail with EOVERFLOW.
2996	 */
2997	if (pvd->vdev_ops != &vdev_mirror_ops &&
2998	    pvd->vdev_ops != &vdev_root_ops && (!replacing ||
2999	    pvd->vdev_ops == &vdev_replacing_ops ||
3000	    pvd->vdev_ops == &vdev_spare_ops))
3001		expected_error = ENOTSUP;
3002	else if (newvd_is_spare && (!replacing || oldvd_is_log))
3003		expected_error = ENOTSUP;
3004	else if (newvd == oldvd)
3005		expected_error = replacing ? 0 : EBUSY;
3006	else if (vdev_lookup_by_path(rvd, newpath) != NULL)
3007		expected_error = EBUSY;
3008	else if (newsize < oldsize)
3009		expected_error = EOVERFLOW;
3010	else if (ashift > oldvd->vdev_top->vdev_ashift)
3011		expected_error = EDOM;
3012	else
3013		expected_error = 0;
3014
3015	spa_config_exit(spa, SCL_ALL, FTAG);
3016
3017	/*
3018	 * Build the nvlist describing newpath.
3019	 */
3020	root = make_vdev_root(newpath, NULL, NULL, newvd == NULL ? newsize : 0,
3021	    ashift, 0, 0, 0, 1);
3022
3023	error = spa_vdev_attach(spa, oldguid, root, replacing);
3024
3025	nvlist_free(root);
3026
3027	/*
3028	 * If our parent was the replacing vdev, but the replace completed,
3029	 * then instead of failing with ENOTSUP we may either succeed,
3030	 * fail with ENODEV, or fail with EOVERFLOW.
3031	 */
3032	if (expected_error == ENOTSUP &&
3033	    (error == 0 || error == ENODEV || error == EOVERFLOW))
3034		expected_error = error;
3035
3036	/*
3037	 * If someone grew the LUN, the replacement may be too small.
3038	 */
3039	if (error == EOVERFLOW || error == EBUSY)
3040		expected_error = error;
3041
3042	if (error == ZFS_ERR_CHECKPOINT_EXISTS ||
3043	    error == ZFS_ERR_DISCARDING_CHECKPOINT)
3044		expected_error = error;
3045
3046	/* XXX workaround 6690467 */
3047	if (error != expected_error && expected_error != EBUSY) {
3048		fatal(0, "attach (%s %llu, %s %llu, %d) "
3049		    "returned %d, expected %d",
3050		    oldpath, oldsize, newpath,
3051		    newsize, replacing, error, expected_error);
3052	}
3053
3054	mutex_exit(&ztest_vdev_lock);
3055}
3056
3057/* ARGSUSED */
3058void
3059ztest_device_removal(ztest_ds_t *zd, uint64_t id)
3060{
3061	spa_t *spa = ztest_spa;
3062	vdev_t *vd;
3063	uint64_t guid;
3064	int error;
3065
3066	mutex_enter(&ztest_vdev_lock);
3067
3068	if (ztest_device_removal_active) {
3069		mutex_exit(&ztest_vdev_lock);
3070		return;
3071	}
3072
3073	/*
3074	 * Remove a random top-level vdev and wait for removal to finish.
3075	 */
3076	spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
3077	vd = vdev_lookup_top(spa, ztest_random_vdev_top(spa, B_FALSE));
3078	guid = vd->vdev_guid;
3079	spa_config_exit(spa, SCL_VDEV, FTAG);
3080
3081	error = spa_vdev_remove(spa, guid, B_FALSE);
3082	if (error == 0) {
3083		ztest_device_removal_active = B_TRUE;
3084		mutex_exit(&ztest_vdev_lock);
3085
3086		while (spa->spa_vdev_removal != NULL)
3087			txg_wait_synced(spa_get_dsl(spa), 0);
3088	} else {
3089		mutex_exit(&ztest_vdev_lock);
3090		return;
3091	}
3092
3093	/*
3094	 * The pool needs to be scrubbed after completing device removal.
3095	 * Failure to do so may result in checksum errors due to the
3096	 * strategy employed by ztest_fault_inject() when selecting which
3097	 * offset are redundant and can be damaged.
3098	 */
3099	error = spa_scan(spa, POOL_SCAN_SCRUB);
3100	if (error == 0) {
3101		while (dsl_scan_scrubbing(spa_get_dsl(spa)))
3102			txg_wait_synced(spa_get_dsl(spa), 0);
3103	}
3104
3105	mutex_enter(&ztest_vdev_lock);
3106	ztest_device_removal_active = B_FALSE;
3107	mutex_exit(&ztest_vdev_lock);
3108}
3109
3110/*
3111 * Callback function which expands the physical size of the vdev.
3112 */
3113vdev_t *
3114grow_vdev(vdev_t *vd, void *arg)
3115{
3116	spa_t *spa = vd->vdev_spa;
3117	size_t *newsize = arg;
3118	size_t fsize;
3119	int fd;
3120
3121	ASSERT(spa_config_held(spa, SCL_STATE, RW_READER) == SCL_STATE);
3122	ASSERT(vd->vdev_ops->vdev_op_leaf);
3123
3124	if ((fd = open(vd->vdev_path, O_RDWR)) == -1)
3125		return (vd);
3126
3127	fsize = lseek(fd, 0, SEEK_END);
3128	(void) ftruncate(fd, *newsize);
3129
3130	if (ztest_opts.zo_verbose >= 6) {
3131		(void) printf("%s grew from %lu to %lu bytes\n",
3132		    vd->vdev_path, (ulong_t)fsize, (ulong_t)*newsize);
3133	}
3134	(void) close(fd);
3135	return (NULL);
3136}
3137
3138/*
3139 * Callback function which expands a given vdev by calling vdev_online().
3140 */
3141/* ARGSUSED */
3142vdev_t *
3143online_vdev(vdev_t *vd, void *arg)
3144{
3145	spa_t *spa = vd->vdev_spa;
3146	vdev_t *tvd = vd->vdev_top;
3147	uint64_t guid = vd->vdev_guid;
3148	uint64_t generation = spa->spa_config_generation + 1;
3149	vdev_state_t newstate = VDEV_STATE_UNKNOWN;
3150	int error;
3151
3152	ASSERT(spa_config_held(spa, SCL_STATE, RW_READER) == SCL_STATE);
3153	ASSERT(vd->vdev_ops->vdev_op_leaf);
3154
3155	/* Calling vdev_online will initialize the new metaslabs */
3156	spa_config_exit(spa, SCL_STATE, spa);
3157	error = vdev_online(spa, guid, ZFS_ONLINE_EXPAND, &newstate);
3158	spa_config_enter(spa, SCL_STATE, spa, RW_READER);
3159
3160	/*
3161	 * If vdev_online returned an error or the underlying vdev_open
3162	 * failed then we abort the expand. The only way to know that
3163	 * vdev_open fails is by checking the returned newstate.
3164	 */
3165	if (error || newstate != VDEV_STATE_HEALTHY) {
3166		if (ztest_opts.zo_verbose >= 5) {
3167			(void) printf("Unable to expand vdev, state %llu, "
3168			    "error %d\n", (u_longlong_t)newstate, error);
3169		}
3170		return (vd);
3171	}
3172	ASSERT3U(newstate, ==, VDEV_STATE_HEALTHY);
3173
3174	/*
3175	 * Since we dropped the lock we need to ensure that we're
3176	 * still talking to the original vdev. It's possible this
3177	 * vdev may have been detached/replaced while we were
3178	 * trying to online it.
3179	 */
3180	if (generation != spa->spa_config_generation) {
3181		if (ztest_opts.zo_verbose >= 5) {
3182			(void) printf("vdev configuration has changed, "
3183			    "guid %llu, state %llu, expected gen %llu, "
3184			    "got gen %llu\n",
3185			    (u_longlong_t)guid,
3186			    (u_longlong_t)tvd->vdev_state,
3187			    (u_longlong_t)generation,
3188			    (u_longlong_t)spa->spa_config_generation);
3189		}
3190		return (vd);
3191	}
3192	return (NULL);
3193}
3194
3195/*
3196 * Traverse the vdev tree calling the supplied function.
3197 * We continue to walk the tree until we either have walked all
3198 * children or we receive a non-NULL return from the callback.
3199 * If a NULL callback is passed, then we just return back the first
3200 * leaf vdev we encounter.
3201 */
3202vdev_t *
3203vdev_walk_tree(vdev_t *vd, vdev_t *(*func)(vdev_t *, void *), void *arg)
3204{
3205	if (vd->vdev_ops->vdev_op_leaf) {
3206		if (func == NULL)
3207			return (vd);
3208		else
3209			return (func(vd, arg));
3210	}
3211
3212	for (uint_t c = 0; c < vd->vdev_children; c++) {
3213		vdev_t *cvd = vd->vdev_child[c];
3214		if ((cvd = vdev_walk_tree(cvd, func, arg)) != NULL)
3215			return (cvd);
3216	}
3217	return (NULL);
3218}
3219
3220/*
3221 * Verify that dynamic LUN growth works as expected.
3222 */
3223/* ARGSUSED */
3224void
3225ztest_vdev_LUN_growth(ztest_ds_t *zd, uint64_t id)
3226{
3227	spa_t *spa = ztest_spa;
3228	vdev_t *vd, *tvd;
3229	metaslab_class_t *mc;
3230	metaslab_group_t *mg;
3231	size_t psize, newsize;
3232	uint64_t top;
3233	uint64_t old_class_space, new_class_space, old_ms_count, new_ms_count;
3234
3235	mutex_enter(&ztest_checkpoint_lock);
3236	mutex_enter(&ztest_vdev_lock);
3237	spa_config_enter(spa, SCL_STATE, spa, RW_READER);
3238
3239	/*
3240	 * If there is a vdev removal in progress, it could complete while
3241	 * we are running, in which case we would not be able to verify
3242	 * that the metaslab_class space increased (because it decreases
3243	 * when the device removal completes).
3244	 */
3245	if (ztest_device_removal_active) {
3246		spa_config_exit(spa, SCL_STATE, spa);
3247		mutex_exit(&ztest_vdev_lock);
3248		mutex_exit(&ztest_checkpoint_lock);
3249		return;
3250	}
3251
3252	top = ztest_random_vdev_top(spa, B_TRUE);
3253
3254	tvd = spa->spa_root_vdev->vdev_child[top];
3255	mg = tvd->vdev_mg;
3256	mc = mg->mg_class;
3257	old_ms_count = tvd->vdev_ms_count;
3258	old_class_space = metaslab_class_get_space(mc);
3259
3260	/*
3261	 * Determine the size of the first leaf vdev associated with
3262	 * our top-level device.
3263	 */
3264	vd = vdev_walk_tree(tvd, NULL, NULL);
3265	ASSERT3P(vd, !=, NULL);
3266	ASSERT(vd->vdev_ops->vdev_op_leaf);
3267
3268	psize = vd->vdev_psize;
3269
3270	/*
3271	 * We only try to expand the vdev if it's healthy, less than 4x its
3272	 * original size, and it has a valid psize.
3273	 */
3274	if (tvd->vdev_state != VDEV_STATE_HEALTHY ||
3275	    psize == 0 || psize >= 4 * ztest_opts.zo_vdev_size) {
3276		spa_config_exit(spa, SCL_STATE, spa);
3277		mutex_exit(&ztest_vdev_lock);
3278		mutex_exit(&ztest_checkpoint_lock);
3279		return;
3280	}
3281	ASSERT(psize > 0);
3282	newsize = psize + psize / 8;
3283	ASSERT3U(newsize, >, psize);
3284
3285	if (ztest_opts.zo_verbose >= 6) {
3286		(void) printf("Expanding LUN %s from %lu to %lu\n",
3287		    vd->vdev_path, (ulong_t)psize, (ulong_t)newsize);
3288	}
3289
3290	/*
3291	 * Growing the vdev is a two step process:
3292	 *	1). expand the physical size (i.e. relabel)
3293	 *	2). online the vdev to create the new metaslabs
3294	 */
3295	if (vdev_walk_tree(tvd, grow_vdev, &newsize) != NULL ||
3296	    vdev_walk_tree(tvd, online_vdev, NULL) != NULL ||
3297	    tvd->vdev_state != VDEV_STATE_HEALTHY) {
3298		if (ztest_opts.zo_verbose >= 5) {
3299			(void) printf("Could not expand LUN because "
3300			    "the vdev configuration changed.\n");
3301		}
3302		spa_config_exit(spa, SCL_STATE, spa);
3303		mutex_exit(&ztest_vdev_lock);
3304		mutex_exit(&ztest_checkpoint_lock);
3305		return;
3306	}
3307
3308	spa_config_exit(spa, SCL_STATE, spa);
3309
3310	/*
3311	 * Expanding the LUN will update the config asynchronously,
3312	 * thus we must wait for the async thread to complete any
3313	 * pending tasks before proceeding.
3314	 */
3315	for (;;) {
3316		boolean_t done;
3317		mutex_enter(&spa->spa_async_lock);
3318		done = (spa->spa_async_thread == NULL && !spa->spa_async_tasks);
3319		mutex_exit(&spa->spa_async_lock);
3320		if (done)
3321			break;
3322		txg_wait_synced(spa_get_dsl(spa), 0);
3323		(void) poll(NULL, 0, 100);
3324	}
3325
3326	spa_config_enter(spa, SCL_STATE, spa, RW_READER);
3327
3328	tvd = spa->spa_root_vdev->vdev_child[top];
3329	new_ms_count = tvd->vdev_ms_count;
3330	new_class_space = metaslab_class_get_space(mc);
3331
3332	if (tvd->vdev_mg != mg || mg->mg_class != mc) {
3333		if (ztest_opts.zo_verbose >= 5) {
3334			(void) printf("Could not verify LUN expansion due to "
3335			    "intervening vdev offline or remove.\n");
3336		}
3337		spa_config_exit(spa, SCL_STATE, spa);
3338		mutex_exit(&ztest_vdev_lock);
3339		mutex_exit(&ztest_checkpoint_lock);
3340		return;
3341	}
3342
3343	/*
3344	 * Make sure we were able to grow the vdev.
3345	 */
3346	if (new_ms_count <= old_ms_count) {
3347		fatal(0, "LUN expansion failed: ms_count %llu < %llu\n",
3348		    old_ms_count, new_ms_count);
3349	}
3350
3351	/*
3352	 * Make sure we were able to grow the pool.
3353	 */
3354	if (new_class_space <= old_class_space) {
3355		fatal(0, "LUN expansion failed: class_space %llu < %llu\n",
3356		    old_class_space, new_class_space);
3357	}
3358
3359	if (ztest_opts.zo_verbose >= 5) {
3360		char oldnumbuf[NN_NUMBUF_SZ], newnumbuf[NN_NUMBUF_SZ];
3361
3362		nicenum(old_class_space, oldnumbuf, sizeof (oldnumbuf));
3363		nicenum(new_class_space, newnumbuf, sizeof (newnumbuf));
3364		(void) printf("%s grew from %s to %s\n",
3365		    spa->spa_name, oldnumbuf, newnumbuf);
3366	}
3367
3368	spa_config_exit(spa, SCL_STATE, spa);
3369	mutex_exit(&ztest_vdev_lock);
3370	mutex_exit(&ztest_checkpoint_lock);
3371}
3372
3373/*
3374 * Verify that dmu_objset_{create,destroy,open,close} work as expected.
3375 */
3376/* ARGSUSED */
3377static void
3378ztest_objset_create_cb(objset_t *os, void *arg, cred_t *cr, dmu_tx_t *tx)
3379{
3380	/*
3381	 * Create the objects common to all ztest datasets.
3382	 */
3383	VERIFY(zap_create_claim(os, ZTEST_DIROBJ,
3384	    DMU_OT_ZAP_OTHER, DMU_OT_NONE, 0, tx) == 0);
3385}
3386
3387static int
3388ztest_dataset_create(char *dsname)
3389{
3390	uint64_t zilset = ztest_random(100);
3391	int err = dmu_objset_create(dsname, DMU_OST_OTHER, 0,
3392	    ztest_objset_create_cb, NULL);
3393
3394	if (err || zilset < 80)
3395		return (err);
3396
3397	if (ztest_opts.zo_verbose >= 6)
3398		(void) printf("Setting dataset %s to sync always\n", dsname);
3399	return (ztest_dsl_prop_set_uint64(dsname, ZFS_PROP_SYNC,
3400	    ZFS_SYNC_ALWAYS, B_FALSE));
3401}
3402
3403/* ARGSUSED */
3404static int
3405ztest_objset_destroy_cb(const char *name, void *arg)
3406{
3407	objset_t *os;
3408	dmu_object_info_t doi;
3409	int error;
3410
3411	/*
3412	 * Verify that the dataset contains a directory object.
3413	 */
3414	VERIFY0(dmu_objset_own(name, DMU_OST_OTHER, B_TRUE, FTAG, &os));
3415	error = dmu_object_info(os, ZTEST_DIROBJ, &doi);
3416	if (error != ENOENT) {
3417		/* We could have crashed in the middle of destroying it */
3418		ASSERT0(error);
3419		ASSERT3U(doi.doi_type, ==, DMU_OT_ZAP_OTHER);
3420		ASSERT3S(doi.doi_physical_blocks_512, >=, 0);
3421	}
3422	dmu_objset_disown(os, FTAG);
3423
3424	/*
3425	 * Destroy the dataset.
3426	 */
3427	if (strchr(name, '@') != NULL) {
3428		VERIFY0(dsl_destroy_snapshot(name, B_FALSE));
3429	} else {
3430		VERIFY0(dsl_destroy_head(name));
3431	}
3432	return (0);
3433}
3434
3435static boolean_t
3436ztest_snapshot_create(char *osname, uint64_t id)
3437{
3438	char snapname[ZFS_MAX_DATASET_NAME_LEN];
3439	int error;
3440
3441	(void) snprintf(snapname, sizeof (snapname), "%llu", (u_longlong_t)id);
3442
3443	error = dmu_objset_snapshot_one(osname, snapname);
3444	if (error == ENOSPC) {
3445		ztest_record_enospc(FTAG);
3446		return (B_FALSE);
3447	}
3448	if (error != 0 && error != EEXIST) {
3449		fatal(0, "ztest_snapshot_create(%s@%s) = %d", osname,
3450		    snapname, error);
3451	}
3452	return (B_TRUE);
3453}
3454
3455static boolean_t
3456ztest_snapshot_destroy(char *osname, uint64_t id)
3457{
3458	char snapname[ZFS_MAX_DATASET_NAME_LEN];
3459	int error;
3460
3461	(void) snprintf(snapname, sizeof (snapname), "%s@%llu", osname,
3462	    (u_longlong_t)id);
3463
3464	error = dsl_destroy_snapshot(snapname, B_FALSE);
3465	if (error != 0 && error != ENOENT)
3466		fatal(0, "ztest_snapshot_destroy(%s) = %d", snapname, error);
3467	return (B_TRUE);
3468}
3469
3470/* ARGSUSED */
3471void
3472ztest_dmu_objset_create_destroy(ztest_ds_t *zd, uint64_t id)
3473{
3474	ztest_ds_t zdtmp;
3475	int iters;
3476	int error;
3477	objset_t *os, *os2;
3478	char name[ZFS_MAX_DATASET_NAME_LEN];
3479	zilog_t *zilog;
3480
3481	rw_enter(&ztest_name_lock, RW_READER);
3482
3483	(void) snprintf(name, sizeof (name), "%s/temp_%llu",
3484	    ztest_opts.zo_pool, (u_longlong_t)id);
3485
3486	/*
3487	 * If this dataset exists from a previous run, process its replay log
3488	 * half of the time.  If we don't replay it, then dmu_objset_destroy()
3489	 * (invoked from ztest_objset_destroy_cb()) should just throw it away.
3490	 */
3491	if (ztest_random(2) == 0 &&
3492	    dmu_objset_own(name, DMU_OST_OTHER, B_FALSE, FTAG, &os) == 0) {
3493		ztest_zd_init(&zdtmp, NULL, os);
3494		zil_replay(os, &zdtmp, ztest_replay_vector);
3495		ztest_zd_fini(&zdtmp);
3496		dmu_objset_disown(os, FTAG);
3497	}
3498
3499	/*
3500	 * There may be an old instance of the dataset we're about to
3501	 * create lying around from a previous run.  If so, destroy it
3502	 * and all of its snapshots.
3503	 */
3504	(void) dmu_objset_find(name, ztest_objset_destroy_cb, NULL,
3505	    DS_FIND_CHILDREN | DS_FIND_SNAPSHOTS);
3506
3507	/*
3508	 * Verify that the destroyed dataset is no longer in the namespace.
3509	 */
3510	VERIFY3U(ENOENT, ==, dmu_objset_own(name, DMU_OST_OTHER, B_TRUE,
3511	    FTAG, &os));
3512
3513	/*
3514	 * Verify that we can create a new dataset.
3515	 */
3516	error = ztest_dataset_create(name);
3517	if (error) {
3518		if (error == ENOSPC) {
3519			ztest_record_enospc(FTAG);
3520			rw_exit(&ztest_name_lock);
3521			return;
3522		}
3523		fatal(0, "dmu_objset_create(%s) = %d", name, error);
3524	}
3525
3526	VERIFY0(dmu_objset_own(name, DMU_OST_OTHER, B_FALSE, FTAG, &os));
3527
3528	ztest_zd_init(&zdtmp, NULL, os);
3529
3530	/*
3531	 * Open the intent log for it.
3532	 */
3533	zilog = zil_open(os, ztest_get_data);
3534
3535	/*
3536	 * Put some objects in there, do a little I/O to them,
3537	 * and randomly take a couple of snapshots along the way.
3538	 */
3539	iters = ztest_random(5);
3540	for (int i = 0; i < iters; i++) {
3541		ztest_dmu_object_alloc_free(&zdtmp, id);
3542		if (ztest_random(iters) == 0)
3543			(void) ztest_snapshot_create(name, i);
3544	}
3545
3546	/*
3547	 * Verify that we cannot create an existing dataset.
3548	 */
3549	VERIFY3U(EEXIST, ==,
3550	    dmu_objset_create(name, DMU_OST_OTHER, 0, NULL, NULL));
3551
3552	/*
3553	 * Verify that we can hold an objset that is also owned.
3554	 */
3555	VERIFY3U(0, ==, dmu_objset_hold(name, FTAG, &os2));
3556	dmu_objset_rele(os2, FTAG);
3557
3558	/*
3559	 * Verify that we cannot own an objset that is already owned.
3560	 */
3561	VERIFY3U(EBUSY, ==,
3562	    dmu_objset_own(name, DMU_OST_OTHER, B_FALSE, FTAG, &os2));
3563
3564	zil_close(zilog);
3565	dmu_objset_disown(os, FTAG);
3566	ztest_zd_fini(&zdtmp);
3567
3568	rw_exit(&ztest_name_lock);
3569}
3570
3571/*
3572 * Verify that dmu_snapshot_{create,destroy,open,close} work as expected.
3573 */
3574void
3575ztest_dmu_snapshot_create_destroy(ztest_ds_t *zd, uint64_t id)
3576{
3577	rw_enter(&ztest_name_lock, RW_READER);
3578	(void) ztest_snapshot_destroy(zd->zd_name, id);
3579	(void) ztest_snapshot_create(zd->zd_name, id);
3580	rw_exit(&ztest_name_lock);
3581}
3582
3583/*
3584 * Cleanup non-standard snapshots and clones.
3585 */
3586void
3587ztest_dsl_dataset_cleanup(char *osname, uint64_t id)
3588{
3589	char snap1name[ZFS_MAX_DATASET_NAME_LEN];
3590	char clone1name[ZFS_MAX_DATASET_NAME_LEN];
3591	char snap2name[ZFS_MAX_DATASET_NAME_LEN];
3592	char clone2name[ZFS_MAX_DATASET_NAME_LEN];
3593	char snap3name[ZFS_MAX_DATASET_NAME_LEN];
3594	int error;
3595
3596	(void) snprintf(snap1name, sizeof (snap1name),
3597	    "%s@s1_%llu", osname, id);
3598	(void) snprintf(clone1name, sizeof (clone1name),
3599	    "%s/c1_%llu", osname, id);
3600	(void) snprintf(snap2name, sizeof (snap2name),
3601	    "%s@s2_%llu", clone1name, id);
3602	(void) snprintf(clone2name, sizeof (clone2name),
3603	    "%s/c2_%llu", osname, id);
3604	(void) snprintf(snap3name, sizeof (snap3name),
3605	    "%s@s3_%llu", clone1name, id);
3606
3607	error = dsl_destroy_head(clone2name);
3608	if (error && error != ENOENT)
3609		fatal(0, "dsl_destroy_head(%s) = %d", clone2name, error);
3610	error = dsl_destroy_snapshot(snap3name, B_FALSE);
3611	if (error && error != ENOENT)
3612		fatal(0, "dsl_destroy_snapshot(%s) = %d", snap3name, error);
3613	error = dsl_destroy_snapshot(snap2name, B_FALSE);
3614	if (error && error != ENOENT)
3615		fatal(0, "dsl_destroy_snapshot(%s) = %d", snap2name, error);
3616	error = dsl_destroy_head(clone1name);
3617	if (error && error != ENOENT)
3618		fatal(0, "dsl_destroy_head(%s) = %d", clone1name, error);
3619	error = dsl_destroy_snapshot(snap1name, B_FALSE);
3620	if (error && error != ENOENT)
3621		fatal(0, "dsl_destroy_snapshot(%s) = %d", snap1name, error);
3622}
3623
3624/*
3625 * Verify dsl_dataset_promote handles EBUSY
3626 */
3627void
3628ztest_dsl_dataset_promote_busy(ztest_ds_t *zd, uint64_t id)
3629{
3630	objset_t *os;
3631	char snap1name[ZFS_MAX_DATASET_NAME_LEN];
3632	char clone1name[ZFS_MAX_DATASET_NAME_LEN];
3633	char snap2name[ZFS_MAX_DATASET_NAME_LEN];
3634	char clone2name[ZFS_MAX_DATASET_NAME_LEN];
3635	char snap3name[ZFS_MAX_DATASET_NAME_LEN];
3636	char *osname = zd->zd_name;
3637	int error;
3638
3639	rw_enter(&ztest_name_lock, RW_READER);
3640
3641	ztest_dsl_dataset_cleanup(osname, id);
3642
3643	(void) snprintf(snap1name, sizeof (snap1name),
3644	    "%s@s1_%llu", osname, id);
3645	(void) snprintf(clone1name, sizeof (clone1name),
3646	    "%s/c1_%llu", osname, id);
3647	(void) snprintf(snap2name, sizeof (snap2name),
3648	    "%s@s2_%llu", clone1name, id);
3649	(void) snprintf(clone2name, sizeof (clone2name),
3650	    "%s/c2_%llu", osname, id);
3651	(void) snprintf(snap3name, sizeof (snap3name),
3652	    "%s@s3_%llu", clone1name, id);
3653
3654	error = dmu_objset_snapshot_one(osname, strchr(snap1name, '@') + 1);
3655	if (error && error != EEXIST) {
3656		if (error == ENOSPC) {
3657			ztest_record_enospc(FTAG);
3658			goto out;
3659		}
3660		fatal(0, "dmu_take_snapshot(%s) = %d", snap1name, error);
3661	}
3662
3663	error = dmu_objset_clone(clone1name, snap1name);
3664	if (error) {
3665		if (error == ENOSPC) {
3666			ztest_record_enospc(FTAG);
3667			goto out;
3668		}
3669		fatal(0, "dmu_objset_create(%s) = %d", clone1name, error);
3670	}
3671
3672	error = dmu_objset_snapshot_one(clone1name, strchr(snap2name, '@') + 1);
3673	if (error && error != EEXIST) {
3674		if (error == ENOSPC) {
3675			ztest_record_enospc(FTAG);
3676			goto out;
3677		}
3678		fatal(0, "dmu_open_snapshot(%s) = %d", snap2name, error);
3679	}
3680
3681	error = dmu_objset_snapshot_one(clone1name, strchr(snap3name, '@') + 1);
3682	if (error && error != EEXIST) {
3683		if (error == ENOSPC) {
3684			ztest_record_enospc(FTAG);
3685			goto out;
3686		}
3687		fatal(0, "dmu_open_snapshot(%s) = %d", snap3name, error);
3688	}
3689
3690	error = dmu_objset_clone(clone2name, snap3name);
3691	if (error) {
3692		if (error == ENOSPC) {
3693			ztest_record_enospc(FTAG);
3694			goto out;
3695		}
3696		fatal(0, "dmu_objset_create(%s) = %d", clone2name, error);
3697	}
3698
3699	error = dmu_objset_own(snap2name, DMU_OST_ANY, B_TRUE, FTAG, &os);
3700	if (error)
3701		fatal(0, "dmu_objset_own(%s) = %d", snap2name, error);
3702	error = dsl_dataset_promote(clone2name, NULL);
3703	if (error == ENOSPC) {
3704		dmu_objset_disown(os, FTAG);
3705		ztest_record_enospc(FTAG);
3706		goto out;
3707	}
3708	if (error != EBUSY)
3709		fatal(0, "dsl_dataset_promote(%s), %d, not EBUSY", clone2name,
3710		    error);
3711	dmu_objset_disown(os, FTAG);
3712
3713out:
3714	ztest_dsl_dataset_cleanup(osname, id);
3715
3716	rw_exit(&ztest_name_lock);
3717}
3718
3719/*
3720 * Verify that dmu_object_{alloc,free} work as expected.
3721 */
3722void
3723ztest_dmu_object_alloc_free(ztest_ds_t *zd, uint64_t id)
3724{
3725	ztest_od_t od[4];
3726	int batchsize = sizeof (od) / sizeof (od[0]);
3727
3728	for (int b = 0; b < batchsize; b++)
3729		ztest_od_init(&od[b], id, FTAG, b, DMU_OT_UINT64_OTHER, 0, 0);
3730
3731	/*
3732	 * Destroy the previous batch of objects, create a new batch,
3733	 * and do some I/O on the new objects.
3734	 */
3735	if (ztest_object_init(zd, od, sizeof (od), B_TRUE) != 0)
3736		return;
3737
3738	while (ztest_random(4 * batchsize) != 0)
3739		ztest_io(zd, od[ztest_random(batchsize)].od_object,
3740		    ztest_random(ZTEST_RANGE_LOCKS) << SPA_MAXBLOCKSHIFT);
3741}
3742
3743/*
3744 * Verify that dmu_{read,write} work as expected.
3745 */
3746void
3747ztest_dmu_read_write(ztest_ds_t *zd, uint64_t id)
3748{
3749	objset_t *os = zd->zd_os;
3750	ztest_od_t od[2];
3751	dmu_tx_t *tx;
3752	int i, freeit, error;
3753	uint64_t n, s, txg;
3754	bufwad_t *packbuf, *bigbuf, *pack, *bigH, *bigT;
3755	uint64_t packobj, packoff, packsize, bigobj, bigoff, bigsize;
3756	uint64_t chunksize = (1000 + ztest_random(1000)) * sizeof (uint64_t);
3757	uint64_t regions = 997;
3758	uint64_t stride = 123456789ULL;
3759	uint64_t width = 40;
3760	int free_percent = 5;
3761
3762	/*
3763	 * This test uses two objects, packobj and bigobj, that are always
3764	 * updated together (i.e. in the same tx) so that their contents are
3765	 * in sync and can be compared.  Their contents relate to each other
3766	 * in a simple way: packobj is a dense array of 'bufwad' structures,
3767	 * while bigobj is a sparse array of the same bufwads.  Specifically,
3768	 * for any index n, there are three bufwads that should be identical:
3769	 *
3770	 *	packobj, at offset n * sizeof (bufwad_t)
3771	 *	bigobj, at the head of the nth chunk
3772	 *	bigobj, at the tail of the nth chunk
3773	 *
3774	 * The chunk size is arbitrary. It doesn't have to be a power of two,
3775	 * and it doesn't have any relation to the object blocksize.
3776	 * The only requirement is that it can hold at least two bufwads.
3777	 *
3778	 * Normally, we write the bufwad to each of these locations.
3779	 * However, free_percent of the time we instead write zeroes to
3780	 * packobj and perform a dmu_free_range() on bigobj.  By comparing
3781	 * bigobj to packobj, we can verify that the DMU is correctly
3782	 * tracking which parts of an object are allocated and free,
3783	 * and that the contents of the allocated blocks are correct.
3784	 */
3785
3786	/*
3787	 * Read the directory info.  If it's the first time, set things up.
3788	 */
3789	ztest_od_init(&od[0], id, FTAG, 0, DMU_OT_UINT64_OTHER, 0, chunksize);
3790	ztest_od_init(&od[1], id, FTAG, 1, DMU_OT_UINT64_OTHER, 0, chunksize);
3791
3792	if (ztest_object_init(zd, od, sizeof (od), B_FALSE) != 0)
3793		return;
3794
3795	bigobj = od[0].od_object;
3796	packobj = od[1].od_object;
3797	chunksize = od[0].od_gen;
3798	ASSERT(chunksize == od[1].od_gen);
3799
3800	/*
3801	 * Prefetch a random chunk of the big object.
3802	 * Our aim here is to get some async reads in flight
3803	 * for blocks that we may free below; the DMU should
3804	 * handle this race correctly.
3805	 */
3806	n = ztest_random(regions) * stride + ztest_random(width);
3807	s = 1 + ztest_random(2 * width - 1);
3808	dmu_prefetch(os, bigobj, 0, n * chunksize, s * chunksize,
3809	    ZIO_PRIORITY_SYNC_READ);
3810
3811	/*
3812	 * Pick a random index and compute the offsets into packobj and bigobj.
3813	 */
3814	n = ztest_random(regions) * stride + ztest_random(width);
3815	s = 1 + ztest_random(width - 1);
3816
3817	packoff = n * sizeof (bufwad_t);
3818	packsize = s * sizeof (bufwad_t);
3819
3820	bigoff = n * chunksize;
3821	bigsize = s * chunksize;
3822
3823	packbuf = umem_alloc(packsize, UMEM_NOFAIL);
3824	bigbuf = umem_alloc(bigsize, UMEM_NOFAIL);
3825
3826	/*
3827	 * free_percent of the time, free a range of bigobj rather than
3828	 * overwriting it.
3829	 */
3830	freeit = (ztest_random(100) < free_percent);
3831
3832	/*
3833	 * Read the current contents of our objects.
3834	 */
3835	error = dmu_read(os, packobj, packoff, packsize, packbuf,
3836	    DMU_READ_PREFETCH);
3837	ASSERT0(error);
3838	error = dmu_read(os, bigobj, bigoff, bigsize, bigbuf,
3839	    DMU_READ_PREFETCH);
3840	ASSERT0(error);
3841
3842	/*
3843	 * Get a tx for the mods to both packobj and bigobj.
3844	 */
3845	tx = dmu_tx_create(os);
3846
3847	dmu_tx_hold_write(tx, packobj, packoff, packsize);
3848
3849	if (freeit)
3850		dmu_tx_hold_free(tx, bigobj, bigoff, bigsize);
3851	else
3852		dmu_tx_hold_write(tx, bigobj, bigoff, bigsize);
3853
3854	/* This accounts for setting the checksum/compression. */
3855	dmu_tx_hold_bonus(tx, bigobj);
3856
3857	txg = ztest_tx_assign(tx, TXG_MIGHTWAIT, FTAG);
3858	if (txg == 0) {
3859		umem_free(packbuf, packsize);
3860		umem_free(bigbuf, bigsize);
3861		return;
3862	}
3863
3864	enum zio_checksum cksum;
3865	do {
3866		cksum = (enum zio_checksum)
3867		    ztest_random_dsl_prop(ZFS_PROP_CHECKSUM);
3868	} while (cksum >= ZIO_CHECKSUM_LEGACY_FUNCTIONS);
3869	dmu_object_set_checksum(os, bigobj, cksum, tx);
3870
3871	enum zio_compress comp;
3872	do {
3873		comp = (enum zio_compress)
3874		    ztest_random_dsl_prop(ZFS_PROP_COMPRESSION);
3875	} while (comp >= ZIO_COMPRESS_LEGACY_FUNCTIONS);
3876	dmu_object_set_compress(os, bigobj, comp, tx);
3877
3878	/*
3879	 * For each index from n to n + s, verify that the existing bufwad
3880	 * in packobj matches the bufwads at the head and tail of the
3881	 * corresponding chunk in bigobj.  Then update all three bufwads
3882	 * with the new values we want to write out.
3883	 */
3884	for (i = 0; i < s; i++) {
3885		/* LINTED */
3886		pack = (bufwad_t *)((char *)packbuf + i * sizeof (bufwad_t));
3887		/* LINTED */
3888		bigH = (bufwad_t *)((char *)bigbuf + i * chunksize);
3889		/* LINTED */
3890		bigT = (bufwad_t *)((char *)bigH + chunksize) - 1;
3891
3892		ASSERT((uintptr_t)bigH - (uintptr_t)bigbuf < bigsize);
3893		ASSERT((uintptr_t)bigT - (uintptr_t)bigbuf < bigsize);
3894
3895		if (pack->bw_txg > txg)
3896			fatal(0, "future leak: got %llx, open txg is %llx",
3897			    pack->bw_txg, txg);
3898
3899		if (pack->bw_data != 0 && pack->bw_index != n + i)
3900			fatal(0, "wrong index: got %llx, wanted %llx+%llx",
3901			    pack->bw_index, n, i);
3902
3903		if (bcmp(pack, bigH, sizeof (bufwad_t)) != 0)
3904			fatal(0, "pack/bigH mismatch in %p/%p", pack, bigH);
3905
3906		if (bcmp(pack, bigT, sizeof (bufwad_t)) != 0)
3907			fatal(0, "pack/bigT mismatch in %p/%p", pack, bigT);
3908
3909		if (freeit) {
3910			bzero(pack, sizeof (bufwad_t));
3911		} else {
3912			pack->bw_index = n + i;
3913			pack->bw_txg = txg;
3914			pack->bw_data = 1 + ztest_random(-2ULL);
3915		}
3916		*bigH = *pack;
3917		*bigT = *pack;
3918	}
3919
3920	/*
3921	 * We've verified all the old bufwads, and made new ones.
3922	 * Now write them out.
3923	 */
3924	dmu_write(os, packobj, packoff, packsize, packbuf, tx);
3925
3926	if (freeit) {
3927		if (ztest_opts.zo_verbose >= 7) {
3928			(void) printf("freeing offset %llx size %llx"
3929			    " txg %llx\n",
3930			    (u_longlong_t)bigoff,
3931			    (u_longlong_t)bigsize,
3932			    (u_longlong_t)txg);
3933		}
3934		VERIFY(0 == dmu_free_range(os, bigobj, bigoff, bigsize, tx));
3935	} else {
3936		if (ztest_opts.zo_verbose >= 7) {
3937			(void) printf("writing offset %llx size %llx"
3938			    " txg %llx\n",
3939			    (u_longlong_t)bigoff,
3940			    (u_longlong_t)bigsize,
3941			    (u_longlong_t)txg);
3942		}
3943		dmu_write(os, bigobj, bigoff, bigsize, bigbuf, tx);
3944	}
3945
3946	dmu_tx_commit(tx);
3947
3948	/*
3949	 * Sanity check the stuff we just wrote.
3950	 */
3951	{
3952		void *packcheck = umem_alloc(packsize, UMEM_NOFAIL);
3953		void *bigcheck = umem_alloc(bigsize, UMEM_NOFAIL);
3954
3955		VERIFY(0 == dmu_read(os, packobj, packoff,
3956		    packsize, packcheck, DMU_READ_PREFETCH));
3957		VERIFY(0 == dmu_read(os, bigobj, bigoff,
3958		    bigsize, bigcheck, DMU_READ_PREFETCH));
3959
3960		ASSERT(bcmp(packbuf, packcheck, packsize) == 0);
3961		ASSERT(bcmp(bigbuf, bigcheck, bigsize) == 0);
3962
3963		umem_free(packcheck, packsize);
3964		umem_free(bigcheck, bigsize);
3965	}
3966
3967	umem_free(packbuf, packsize);
3968	umem_free(bigbuf, bigsize);
3969}
3970
3971void
3972compare_and_update_pbbufs(uint64_t s, bufwad_t *packbuf, bufwad_t *bigbuf,
3973    uint64_t bigsize, uint64_t n, uint64_t chunksize, uint64_t txg)
3974{
3975	uint64_t i;
3976	bufwad_t *pack;
3977	bufwad_t *bigH;
3978	bufwad_t *bigT;
3979
3980	/*
3981	 * For each index from n to n + s, verify that the existing bufwad
3982	 * in packobj matches the bufwads at the head and tail of the
3983	 * corresponding chunk in bigobj.  Then update all three bufwads
3984	 * with the new values we want to write out.
3985	 */
3986	for (i = 0; i < s; i++) {
3987		/* LINTED */
3988		pack = (bufwad_t *)((char *)packbuf + i * sizeof (bufwad_t));
3989		/* LINTED */
3990		bigH = (bufwad_t *)((char *)bigbuf + i * chunksize);
3991		/* LINTED */
3992		bigT = (bufwad_t *)((char *)bigH + chunksize) - 1;
3993
3994		ASSERT((uintptr_t)bigH - (uintptr_t)bigbuf < bigsize);
3995		ASSERT((uintptr_t)bigT - (uintptr_t)bigbuf < bigsize);
3996
3997		if (pack->bw_txg > txg)
3998			fatal(0, "future leak: got %llx, open txg is %llx",
3999			    pack->bw_txg, txg);
4000
4001		if (pack->bw_data != 0 && pack->bw_index != n + i)
4002			fatal(0, "wrong index: got %llx, wanted %llx+%llx",
4003			    pack->bw_index, n, i);
4004
4005		if (bcmp(pack, bigH, sizeof (bufwad_t)) != 0)
4006			fatal(0, "pack/bigH mismatch in %p/%p", pack, bigH);
4007
4008		if (bcmp(pack, bigT, sizeof (bufwad_t)) != 0)
4009			fatal(0, "pack/bigT mismatch in %p/%p", pack, bigT);
4010
4011		pack->bw_index = n + i;
4012		pack->bw_txg = txg;
4013		pack->bw_data = 1 + ztest_random(-2ULL);
4014
4015		*bigH = *pack;
4016		*bigT = *pack;
4017	}
4018}
4019
4020void
4021ztest_dmu_read_write_zcopy(ztest_ds_t *zd, uint64_t id)
4022{
4023	objset_t *os = zd->zd_os;
4024	ztest_od_t od[2];
4025	dmu_tx_t *tx;
4026	uint64_t i;
4027	int error;
4028	uint64_t n, s, txg;
4029	bufwad_t *packbuf, *bigbuf;
4030	uint64_t packobj, packoff, packsize, bigobj, bigoff, bigsize;
4031	uint64_t blocksize = ztest_random_blocksize();
4032	uint64_t chunksize = blocksize;
4033	uint64_t regions = 997;
4034	uint64_t stride = 123456789ULL;
4035	uint64_t width = 9;
4036	dmu_buf_t *bonus_db;
4037	arc_buf_t **bigbuf_arcbufs;
4038	dmu_object_info_t doi;
4039
4040	/*
4041	 * This test uses two objects, packobj and bigobj, that are always
4042	 * updated together (i.e. in the same tx) so that their contents are
4043	 * in sync and can be compared.  Their contents relate to each other
4044	 * in a simple way: packobj is a dense array of 'bufwad' structures,
4045	 * while bigobj is a sparse array of the same bufwads.  Specifically,
4046	 * for any index n, there are three bufwads that should be identical:
4047	 *
4048	 *	packobj, at offset n * sizeof (bufwad_t)
4049	 *	bigobj, at the head of the nth chunk
4050	 *	bigobj, at the tail of the nth chunk
4051	 *
4052	 * The chunk size is set equal to bigobj block size so that
4053	 * dmu_assign_arcbuf() can be tested for object updates.
4054	 */
4055
4056	/*
4057	 * Read the directory info.  If it's the first time, set things up.
4058	 */
4059	ztest_od_init(&od[0], id, FTAG, 0, DMU_OT_UINT64_OTHER, blocksize, 0);
4060	ztest_od_init(&od[1], id, FTAG, 1, DMU_OT_UINT64_OTHER, 0, chunksize);
4061
4062	if (ztest_object_init(zd, od, sizeof (od), B_FALSE) != 0)
4063		return;
4064
4065	bigobj = od[0].od_object;
4066	packobj = od[1].od_object;
4067	blocksize = od[0].od_blocksize;
4068	chunksize = blocksize;
4069	ASSERT(chunksize == od[1].od_gen);
4070
4071	VERIFY(dmu_object_info(os, bigobj, &doi) == 0);
4072	VERIFY(ISP2(doi.doi_data_block_size));
4073	VERIFY(chunksize == doi.doi_data_block_size);
4074	VERIFY(chunksize >= 2 * sizeof (bufwad_t));
4075
4076	/*
4077	 * Pick a random index and compute the offsets into packobj and bigobj.
4078	 */
4079	n = ztest_random(regions) * stride + ztest_random(width);
4080	s = 1 + ztest_random(width - 1);
4081
4082	packoff = n * sizeof (bufwad_t);
4083	packsize = s * sizeof (bufwad_t);
4084
4085	bigoff = n * chunksize;
4086	bigsize = s * chunksize;
4087
4088	packbuf = umem_zalloc(packsize, UMEM_NOFAIL);
4089	bigbuf = umem_zalloc(bigsize, UMEM_NOFAIL);
4090
4091	VERIFY3U(0, ==, dmu_bonus_hold(os, bigobj, FTAG, &bonus_db));
4092
4093	bigbuf_arcbufs = umem_zalloc(2 * s * sizeof (arc_buf_t *), UMEM_NOFAIL);
4094
4095	/*
4096	 * Iteration 0 test zcopy for DB_UNCACHED dbufs.
4097	 * Iteration 1 test zcopy to already referenced dbufs.
4098	 * Iteration 2 test zcopy to dirty dbuf in the same txg.
4099	 * Iteration 3 test zcopy to dbuf dirty in previous txg.
4100	 * Iteration 4 test zcopy when dbuf is no longer dirty.
4101	 * Iteration 5 test zcopy when it can't be done.
4102	 * Iteration 6 one more zcopy write.
4103	 */
4104	for (i = 0; i < 7; i++) {
4105		uint64_t j;
4106		uint64_t off;
4107
4108		/*
4109		 * In iteration 5 (i == 5) use arcbufs
4110		 * that don't match bigobj blksz to test
4111		 * dmu_assign_arcbuf() when it can't directly
4112		 * assign an arcbuf to a dbuf.
4113		 */
4114		for (j = 0; j < s; j++) {
4115			if (i != 5) {
4116				bigbuf_arcbufs[j] =
4117				    dmu_request_arcbuf(bonus_db, chunksize);
4118			} else {
4119				bigbuf_arcbufs[2 * j] =
4120				    dmu_request_arcbuf(bonus_db, chunksize / 2);
4121				bigbuf_arcbufs[2 * j + 1] =
4122				    dmu_request_arcbuf(bonus_db, chunksize / 2);
4123			}
4124		}
4125
4126		/*
4127		 * Get a tx for the mods to both packobj and bigobj.
4128		 */
4129		tx = dmu_tx_create(os);
4130
4131		dmu_tx_hold_write(tx, packobj, packoff, packsize);
4132		dmu_tx_hold_write(tx, bigobj, bigoff, bigsize);
4133
4134		txg = ztest_tx_assign(tx, TXG_MIGHTWAIT, FTAG);
4135		if (txg == 0) {
4136			umem_free(packbuf, packsize);
4137			umem_free(bigbuf, bigsize);
4138			for (j = 0; j < s; j++) {
4139				if (i != 5) {
4140					dmu_return_arcbuf(bigbuf_arcbufs[j]);
4141				} else {
4142					dmu_return_arcbuf(
4143					    bigbuf_arcbufs[2 * j]);
4144					dmu_return_arcbuf(
4145					    bigbuf_arcbufs[2 * j + 1]);
4146				}
4147			}
4148			umem_free(bigbuf_arcbufs, 2 * s * sizeof (arc_buf_t *));
4149			dmu_buf_rele(bonus_db, FTAG);
4150			return;
4151		}
4152
4153		/*
4154		 * 50% of the time don't read objects in the 1st iteration to
4155		 * test dmu_assign_arcbuf() for the case when there're no
4156		 * existing dbufs for the specified offsets.
4157		 */
4158		if (i != 0 || ztest_random(2) != 0) {
4159			error = dmu_read(os, packobj, packoff,
4160			    packsize, packbuf, DMU_READ_PREFETCH);
4161			ASSERT0(error);
4162			error = dmu_read(os, bigobj, bigoff, bigsize,
4163			    bigbuf, DMU_READ_PREFETCH);
4164			ASSERT0(error);
4165		}
4166		compare_and_update_pbbufs(s, packbuf, bigbuf, bigsize,
4167		    n, chunksize, txg);
4168
4169		/*
4170		 * We've verified all the old bufwads, and made new ones.
4171		 * Now write them out.
4172		 */
4173		dmu_write(os, packobj, packoff, packsize, packbuf, tx);
4174		if (ztest_opts.zo_verbose >= 7) {
4175			(void) printf("writing offset %llx size %llx"
4176			    " txg %llx\n",
4177			    (u_longlong_t)bigoff,
4178			    (u_longlong_t)bigsize,
4179			    (u_longlong_t)txg);
4180		}
4181		for (off = bigoff, j = 0; j < s; j++, off += chunksize) {
4182			dmu_buf_t *dbt;
4183			if (i != 5) {
4184				bcopy((caddr_t)bigbuf + (off - bigoff),
4185				    bigbuf_arcbufs[j]->b_data, chunksize);
4186			} else {
4187				bcopy((caddr_t)bigbuf + (off - bigoff),
4188				    bigbuf_arcbufs[2 * j]->b_data,
4189				    chunksize / 2);
4190				bcopy((caddr_t)bigbuf + (off - bigoff) +
4191				    chunksize / 2,
4192				    bigbuf_arcbufs[2 * j + 1]->b_data,
4193				    chunksize / 2);
4194			}
4195
4196			if (i == 1) {
4197				VERIFY(dmu_buf_hold(os, bigobj, off,
4198				    FTAG, &dbt, DMU_READ_NO_PREFETCH) == 0);
4199			}
4200			if (i != 5) {
4201				dmu_assign_arcbuf(bonus_db, off,
4202				    bigbuf_arcbufs[j], tx);
4203			} else {
4204				dmu_assign_arcbuf(bonus_db, off,
4205				    bigbuf_arcbufs[2 * j], tx);
4206				dmu_assign_arcbuf(bonus_db,
4207				    off + chunksize / 2,
4208				    bigbuf_arcbufs[2 * j + 1], tx);
4209			}
4210			if (i == 1) {
4211				dmu_buf_rele(dbt, FTAG);
4212			}
4213		}
4214		dmu_tx_commit(tx);
4215
4216		/*
4217		 * Sanity check the stuff we just wrote.
4218		 */
4219		{
4220			void *packcheck = umem_alloc(packsize, UMEM_NOFAIL);
4221			void *bigcheck = umem_alloc(bigsize, UMEM_NOFAIL);
4222
4223			VERIFY(0 == dmu_read(os, packobj, packoff,
4224			    packsize, packcheck, DMU_READ_PREFETCH));
4225			VERIFY(0 == dmu_read(os, bigobj, bigoff,
4226			    bigsize, bigcheck, DMU_READ_PREFETCH));
4227
4228			ASSERT(bcmp(packbuf, packcheck, packsize) == 0);
4229			ASSERT(bcmp(bigbuf, bigcheck, bigsize) == 0);
4230
4231			umem_free(packcheck, packsize);
4232			umem_free(bigcheck, bigsize);
4233		}
4234		if (i == 2) {
4235			txg_wait_open(dmu_objset_pool(os), 0);
4236		} else if (i == 3) {
4237			txg_wait_synced(dmu_objset_pool(os), 0);
4238		}
4239	}
4240
4241	dmu_buf_rele(bonus_db, FTAG);
4242	umem_free(packbuf, packsize);
4243	umem_free(bigbuf, bigsize);
4244	umem_free(bigbuf_arcbufs, 2 * s * sizeof (arc_buf_t *));
4245}
4246
4247/* ARGSUSED */
4248void
4249ztest_dmu_write_parallel(ztest_ds_t *zd, uint64_t id)
4250{
4251	ztest_od_t od[1];
4252	uint64_t offset = (1ULL << (ztest_random(20) + 43)) +
4253	    (ztest_random(ZTEST_RANGE_LOCKS) << SPA_MAXBLOCKSHIFT);
4254
4255	/*
4256	 * Have multiple threads write to large offsets in an object
4257	 * to verify that parallel writes to an object -- even to the
4258	 * same blocks within the object -- doesn't cause any trouble.
4259	 */
4260	ztest_od_init(&od[0], ID_PARALLEL, FTAG, 0, DMU_OT_UINT64_OTHER, 0, 0);
4261
4262	if (ztest_object_init(zd, od, sizeof (od), B_FALSE) != 0)
4263		return;
4264
4265	while (ztest_random(10) != 0)
4266		ztest_io(zd, od[0].od_object, offset);
4267}
4268
4269void
4270ztest_dmu_prealloc(ztest_ds_t *zd, uint64_t id)
4271{
4272	ztest_od_t od[1];
4273	uint64_t offset = (1ULL << (ztest_random(4) + SPA_MAXBLOCKSHIFT)) +
4274	    (ztest_random(ZTEST_RANGE_LOCKS) << SPA_MAXBLOCKSHIFT);
4275	uint64_t count = ztest_random(20) + 1;
4276	uint64_t blocksize = ztest_random_blocksize();
4277	void *data;
4278
4279	ztest_od_init(&od[0], id, FTAG, 0, DMU_OT_UINT64_OTHER, blocksize, 0);
4280
4281	if (ztest_object_init(zd, od, sizeof (od), !ztest_random(2)) != 0)
4282		return;
4283
4284	if (ztest_truncate(zd, od[0].od_object, offset, count * blocksize) != 0)
4285		return;
4286
4287	ztest_prealloc(zd, od[0].od_object, offset, count * blocksize);
4288
4289	data = umem_zalloc(blocksize, UMEM_NOFAIL);
4290
4291	while (ztest_random(count) != 0) {
4292		uint64_t randoff = offset + (ztest_random(count) * blocksize);
4293		if (ztest_write(zd, od[0].od_object, randoff, blocksize,
4294		    data) != 0)
4295			break;
4296		while (ztest_random(4) != 0)
4297			ztest_io(zd, od[0].od_object, randoff);
4298	}
4299
4300	umem_free(data, blocksize);
4301}
4302
4303/*
4304 * Verify that zap_{create,destroy,add,remove,update} work as expected.
4305 */
4306#define	ZTEST_ZAP_MIN_INTS	1
4307#define	ZTEST_ZAP_MAX_INTS	4
4308#define	ZTEST_ZAP_MAX_PROPS	1000
4309
4310void
4311ztest_zap(ztest_ds_t *zd, uint64_t id)
4312{
4313	objset_t *os = zd->zd_os;
4314	ztest_od_t od[1];
4315	uint64_t object;
4316	uint64_t txg, last_txg;
4317	uint64_t value[ZTEST_ZAP_MAX_INTS];
4318	uint64_t zl_ints, zl_intsize, prop;
4319	int i, ints;
4320	dmu_tx_t *tx;
4321	char propname[100], txgname[100];
4322	int error;
4323	char *hc[2] = { "s.acl.h", ".s.open.h.hyLZlg" };
4324
4325	ztest_od_init(&od[0], id, FTAG, 0, DMU_OT_ZAP_OTHER, 0, 0);
4326
4327	if (ztest_object_init(zd, od, sizeof (od), !ztest_random(2)) != 0)
4328		return;
4329
4330	object = od[0].od_object;
4331
4332	/*
4333	 * Generate a known hash collision, and verify that
4334	 * we can lookup and remove both entries.
4335	 */
4336	tx = dmu_tx_create(os);
4337	dmu_tx_hold_zap(tx, object, B_TRUE, NULL);
4338	txg = ztest_tx_assign(tx, TXG_MIGHTWAIT, FTAG);
4339	if (txg == 0)
4340		return;
4341	for (i = 0; i < 2; i++) {
4342		value[i] = i;
4343		VERIFY3U(0, ==, zap_add(os, object, hc[i], sizeof (uint64_t),
4344		    1, &value[i], tx));
4345	}
4346	for (i = 0; i < 2; i++) {
4347		VERIFY3U(EEXIST, ==, zap_add(os, object, hc[i],
4348		    sizeof (uint64_t), 1, &value[i], tx));
4349		VERIFY3U(0, ==,
4350		    zap_length(os, object, hc[i], &zl_intsize, &zl_ints));
4351		ASSERT3U(zl_intsize, ==, sizeof (uint64_t));
4352		ASSERT3U(zl_ints, ==, 1);
4353	}
4354	for (i = 0; i < 2; i++) {
4355		VERIFY3U(0, ==, zap_remove(os, object, hc[i], tx));
4356	}
4357	dmu_tx_commit(tx);
4358
4359	/*
4360	 * Generate a buch of random entries.
4361	 */
4362	ints = MAX(ZTEST_ZAP_MIN_INTS, object % ZTEST_ZAP_MAX_INTS);
4363
4364	prop = ztest_random(ZTEST_ZAP_MAX_PROPS);
4365	(void) sprintf(propname, "prop_%llu", (u_longlong_t)prop);
4366	(void) sprintf(txgname, "txg_%llu", (u_longlong_t)prop);
4367	bzero(value, sizeof (value));
4368	last_txg = 0;
4369
4370	/*
4371	 * If these zap entries already exist, validate their contents.
4372	 */
4373	error = zap_length(os, object, txgname, &zl_intsize, &zl_ints);
4374	if (error == 0) {
4375		ASSERT3U(zl_intsize, ==, sizeof (uint64_t));
4376		ASSERT3U(zl_ints, ==, 1);
4377
4378		VERIFY(zap_lookup(os, object, txgname, zl_intsize,
4379		    zl_ints, &last_txg) == 0);
4380
4381		VERIFY(zap_length(os, object, propname, &zl_intsize,
4382		    &zl_ints) == 0);
4383
4384		ASSERT3U(zl_intsize, ==, sizeof (uint64_t));
4385		ASSERT3U(zl_ints, ==, ints);
4386
4387		VERIFY(zap_lookup(os, object, propname, zl_intsize,
4388		    zl_ints, value) == 0);
4389
4390		for (i = 0; i < ints; i++) {
4391			ASSERT3U(value[i], ==, last_txg + object + i);
4392		}
4393	} else {
4394		ASSERT3U(error, ==, ENOENT);
4395	}
4396
4397	/*
4398	 * Atomically update two entries in our zap object.
4399	 * The first is named txg_%llu, and contains the txg
4400	 * in which the property was last updated.  The second
4401	 * is named prop_%llu, and the nth element of its value
4402	 * should be txg + object + n.
4403	 */
4404	tx = dmu_tx_create(os);
4405	dmu_tx_hold_zap(tx, object, B_TRUE, NULL);
4406	txg = ztest_tx_assign(tx, TXG_MIGHTWAIT, FTAG);
4407	if (txg == 0)
4408		return;
4409
4410	if (last_txg > txg)
4411		fatal(0, "zap future leak: old %llu new %llu", last_txg, txg);
4412
4413	for (i = 0; i < ints; i++)
4414		value[i] = txg + object + i;
4415
4416	VERIFY3U(0, ==, zap_update(os, object, txgname, sizeof (uint64_t),
4417	    1, &txg, tx));
4418	VERIFY3U(0, ==, zap_update(os, object, propname, sizeof (uint64_t),
4419	    ints, value, tx));
4420
4421	dmu_tx_commit(tx);
4422
4423	/*
4424	 * Remove a random pair of entries.
4425	 */
4426	prop = ztest_random(ZTEST_ZAP_MAX_PROPS);
4427	(void) sprintf(propname, "prop_%llu", (u_longlong_t)prop);
4428	(void) sprintf(txgname, "txg_%llu", (u_longlong_t)prop);
4429
4430	error = zap_length(os, object, txgname, &zl_intsize, &zl_ints);
4431
4432	if (error == ENOENT)
4433		return;
4434
4435	ASSERT0(error);
4436
4437	tx = dmu_tx_create(os);
4438	dmu_tx_hold_zap(tx, object, B_TRUE, NULL);
4439	txg = ztest_tx_assign(tx, TXG_MIGHTWAIT, FTAG);
4440	if (txg == 0)
4441		return;
4442	VERIFY3U(0, ==, zap_remove(os, object, txgname, tx));
4443	VERIFY3U(0, ==, zap_remove(os, object, propname, tx));
4444	dmu_tx_commit(tx);
4445}
4446
4447/*
4448 * Testcase to test the upgrading of a microzap to fatzap.
4449 */
4450void
4451ztest_fzap(ztest_ds_t *zd, uint64_t id)
4452{
4453	objset_t *os = zd->zd_os;
4454	ztest_od_t od[1];
4455	uint64_t object, txg;
4456
4457	ztest_od_init(&od[0], id, FTAG, 0, DMU_OT_ZAP_OTHER, 0, 0);
4458
4459	if (ztest_object_init(zd, od, sizeof (od), !ztest_random(2)) != 0)
4460		return;
4461
4462	object = od[0].od_object;
4463
4464	/*
4465	 * Add entries to this ZAP and make sure it spills over
4466	 * and gets upgraded to a fatzap. Also, since we are adding
4467	 * 2050 entries we should see ptrtbl growth and leaf-block split.
4468	 */
4469	for (int i = 0; i < 2050; i++) {
4470		char name[ZFS_MAX_DATASET_NAME_LEN];
4471		uint64_t value = i;
4472		dmu_tx_t *tx;
4473		int error;
4474
4475		(void) snprintf(name, sizeof (name), "fzap-%llu-%llu",
4476		    id, value);
4477
4478		tx = dmu_tx_create(os);
4479		dmu_tx_hold_zap(tx, object, B_TRUE, name);
4480		txg = ztest_tx_assign(tx, TXG_MIGHTWAIT, FTAG);
4481		if (txg == 0)
4482			return;
4483		error = zap_add(os, object, name, sizeof (uint64_t), 1,
4484		    &value, tx);
4485		ASSERT(error == 0 || error == EEXIST);
4486		dmu_tx_commit(tx);
4487	}
4488}
4489
4490/* ARGSUSED */
4491void
4492ztest_zap_parallel(ztest_ds_t *zd, uint64_t id)
4493{
4494	objset_t *os = zd->zd_os;
4495	ztest_od_t od[1];
4496	uint64_t txg, object, count, wsize, wc, zl_wsize, zl_wc;
4497	dmu_tx_t *tx;
4498	int i, namelen, error;
4499	int micro = ztest_random(2);
4500	char name[20], string_value[20];
4501	void *data;
4502
4503	ztest_od_init(&od[0], ID_PARALLEL, FTAG, micro, DMU_OT_ZAP_OTHER, 0, 0);
4504
4505	if (ztest_object_init(zd, od, sizeof (od), B_FALSE) != 0)
4506		return;
4507
4508	object = od[0].od_object;
4509
4510	/*
4511	 * Generate a random name of the form 'xxx.....' where each
4512	 * x is a random printable character and the dots are dots.
4513	 * There are 94 such characters, and the name length goes from
4514	 * 6 to 20, so there are 94^3 * 15 = 12,458,760 possible names.
4515	 */
4516	namelen = ztest_random(sizeof (name) - 5) + 5 + 1;
4517
4518	for (i = 0; i < 3; i++)
4519		name[i] = '!' + ztest_random('~' - '!' + 1);
4520	for (; i < namelen - 1; i++)
4521		name[i] = '.';
4522	name[i] = '\0';
4523
4524	if ((namelen & 1) || micro) {
4525		wsize = sizeof (txg);
4526		wc = 1;
4527		data = &txg;
4528	} else {
4529		wsize = 1;
4530		wc = namelen;
4531		data = string_value;
4532	}
4533
4534	count = -1ULL;
4535	VERIFY0(zap_count(os, object, &count));
4536	ASSERT(count != -1ULL);
4537
4538	/*
4539	 * Select an operation: length, lookup, add, update, remove.
4540	 */
4541	i = ztest_random(5);
4542
4543	if (i >= 2) {
4544		tx = dmu_tx_create(os);
4545		dmu_tx_hold_zap(tx, object, B_TRUE, NULL);
4546		txg = ztest_tx_assign(tx, TXG_MIGHTWAIT, FTAG);
4547		if (txg == 0)
4548			return;
4549		bcopy(name, string_value, namelen);
4550	} else {
4551		tx = NULL;
4552		txg = 0;
4553		bzero(string_value, namelen);
4554	}
4555
4556	switch (i) {
4557
4558	case 0:
4559		error = zap_length(os, object, name, &zl_wsize, &zl_wc);
4560		if (error == 0) {
4561			ASSERT3U(wsize, ==, zl_wsize);
4562			ASSERT3U(wc, ==, zl_wc);
4563		} else {
4564			ASSERT3U(error, ==, ENOENT);
4565		}
4566		break;
4567
4568	case 1:
4569		error = zap_lookup(os, object, name, wsize, wc, data);
4570		if (error == 0) {
4571			if (data == string_value &&
4572			    bcmp(name, data, namelen) != 0)
4573				fatal(0, "name '%s' != val '%s' len %d",
4574				    name, data, namelen);
4575		} else {
4576			ASSERT3U(error, ==, ENOENT);
4577		}
4578		break;
4579
4580	case 2:
4581		error = zap_add(os, object, name, wsize, wc, data, tx);
4582		ASSERT(error == 0 || error == EEXIST);
4583		break;
4584
4585	case 3:
4586		VERIFY(zap_update(os, object, name, wsize, wc, data, tx) == 0);
4587		break;
4588
4589	case 4:
4590		error = zap_remove(os, object, name, tx);
4591		ASSERT(error == 0 || error == ENOENT);
4592		break;
4593	}
4594
4595	if (tx != NULL)
4596		dmu_tx_commit(tx);
4597}
4598
4599/*
4600 * Commit callback data.
4601 */
4602typedef struct ztest_cb_data {
4603	list_node_t		zcd_node;
4604	uint64_t		zcd_txg;
4605	int			zcd_expected_err;
4606	boolean_t		zcd_added;
4607	boolean_t		zcd_called;
4608	spa_t			*zcd_spa;
4609} ztest_cb_data_t;
4610
4611/* This is the actual commit callback function */
4612static void
4613ztest_commit_callback(void *arg, int error)
4614{
4615	ztest_cb_data_t *data = arg;
4616	uint64_t synced_txg;
4617
4618	VERIFY(data != NULL);
4619	VERIFY3S(data->zcd_expected_err, ==, error);
4620	VERIFY(!data->zcd_called);
4621
4622	synced_txg = spa_last_synced_txg(data->zcd_spa);
4623	if (data->zcd_txg > synced_txg)
4624		fatal(0, "commit callback of txg %" PRIu64 " called prematurely"
4625		    ", last synced txg = %" PRIu64 "\n", data->zcd_txg,
4626		    synced_txg);
4627
4628	data->zcd_called = B_TRUE;
4629
4630	if (error == ECANCELED) {
4631		ASSERT0(data->zcd_txg);
4632		ASSERT(!data->zcd_added);
4633
4634		/*
4635		 * The private callback data should be destroyed here, but
4636		 * since we are going to check the zcd_called field after
4637		 * dmu_tx_abort(), we will destroy it there.
4638		 */
4639		return;
4640	}
4641
4642	/* Was this callback added to the global callback list? */
4643	if (!data->zcd_added)
4644		goto out;
4645
4646	ASSERT3U(data->zcd_txg, !=, 0);
4647
4648	/* Remove our callback from the list */
4649	mutex_enter(&zcl.zcl_callbacks_lock);
4650	list_remove(&zcl.zcl_callbacks, data);
4651	mutex_exit(&zcl.zcl_callbacks_lock);
4652
4653out:
4654	umem_free(data, sizeof (ztest_cb_data_t));
4655}
4656
4657/* Allocate and initialize callback data structure */
4658static ztest_cb_data_t *
4659ztest_create_cb_data(objset_t *os, uint64_t txg)
4660{
4661	ztest_cb_data_t *cb_data;
4662
4663	cb_data = umem_zalloc(sizeof (ztest_cb_data_t), UMEM_NOFAIL);
4664
4665	cb_data->zcd_txg = txg;
4666	cb_data->zcd_spa = dmu_objset_spa(os);
4667
4668	return (cb_data);
4669}
4670
4671/*
4672 * If a number of txgs equal to this threshold have been created after a commit
4673 * callback has been registered but not called, then we assume there is an
4674 * implementation bug.
4675 */
4676#define	ZTEST_COMMIT_CALLBACK_THRESH	(TXG_CONCURRENT_STATES + 2)
4677
4678/*
4679 * Commit callback test.
4680 */
4681void
4682ztest_dmu_commit_callbacks(ztest_ds_t *zd, uint64_t id)
4683{
4684	objset_t *os = zd->zd_os;
4685	ztest_od_t od[1];
4686	dmu_tx_t *tx;
4687	ztest_cb_data_t *cb_data[3], *tmp_cb;
4688	uint64_t old_txg, txg;
4689	int i, error;
4690
4691	ztest_od_init(&od[0], id, FTAG, 0, DMU_OT_UINT64_OTHER, 0, 0);
4692
4693	if (ztest_object_init(zd, od, sizeof (od), B_FALSE) != 0)
4694		return;
4695
4696	tx = dmu_tx_create(os);
4697
4698	cb_data[0] = ztest_create_cb_data(os, 0);
4699	dmu_tx_callback_register(tx, ztest_commit_callback, cb_data[0]);
4700
4701	dmu_tx_hold_write(tx, od[0].od_object, 0, sizeof (uint64_t));
4702
4703	/* Every once in a while, abort the transaction on purpose */
4704	if (ztest_random(100) == 0)
4705		error = -1;
4706
4707	if (!error)
4708		error = dmu_tx_assign(tx, TXG_NOWAIT);
4709
4710	txg = error ? 0 : dmu_tx_get_txg(tx);
4711
4712	cb_data[0]->zcd_txg = txg;
4713	cb_data[1] = ztest_create_cb_data(os, txg);
4714	dmu_tx_callback_register(tx, ztest_commit_callback, cb_data[1]);
4715
4716	if (error) {
4717		/*
4718		 * It's not a strict requirement to call the registered
4719		 * callbacks from inside dmu_tx_abort(), but that's what
4720		 * it's supposed to happen in the current implementation
4721		 * so we will check for that.
4722		 */
4723		for (i = 0; i < 2; i++) {
4724			cb_data[i]->zcd_expected_err = ECANCELED;
4725			VERIFY(!cb_data[i]->zcd_called);
4726		}
4727
4728		dmu_tx_abort(tx);
4729
4730		for (i = 0; i < 2; i++) {
4731			VERIFY(cb_data[i]->zcd_called);
4732			umem_free(cb_data[i], sizeof (ztest_cb_data_t));
4733		}
4734
4735		return;
4736	}
4737
4738	cb_data[2] = ztest_create_cb_data(os, txg);
4739	dmu_tx_callback_register(tx, ztest_commit_callback, cb_data[2]);
4740
4741	/*
4742	 * Read existing data to make sure there isn't a future leak.
4743	 */
4744	VERIFY(0 == dmu_read(os, od[0].od_object, 0, sizeof (uint64_t),
4745	    &old_txg, DMU_READ_PREFETCH));
4746
4747	if (old_txg > txg)
4748		fatal(0, "future leak: got %" PRIu64 ", open txg is %" PRIu64,
4749		    old_txg, txg);
4750
4751	dmu_write(os, od[0].od_object, 0, sizeof (uint64_t), &txg, tx);
4752
4753	mutex_enter(&zcl.zcl_callbacks_lock);
4754
4755	/*
4756	 * Since commit callbacks don't have any ordering requirement and since
4757	 * it is theoretically possible for a commit callback to be called
4758	 * after an arbitrary amount of time has elapsed since its txg has been
4759	 * synced, it is difficult to reliably determine whether a commit
4760	 * callback hasn't been called due to high load or due to a flawed
4761	 * implementation.
4762	 *
4763	 * In practice, we will assume that if after a certain number of txgs a
4764	 * commit callback hasn't been called, then most likely there's an
4765	 * implementation bug..
4766	 */
4767	tmp_cb = list_head(&zcl.zcl_callbacks);
4768	if (tmp_cb != NULL &&
4769	    (txg - ZTEST_COMMIT_CALLBACK_THRESH) > tmp_cb->zcd_txg) {
4770		fatal(0, "Commit callback threshold exceeded, oldest txg: %"
4771		    PRIu64 ", open txg: %" PRIu64 "\n", tmp_cb->zcd_txg, txg);
4772	}
4773
4774	/*
4775	 * Let's find the place to insert our callbacks.
4776	 *
4777	 * Even though the list is ordered by txg, it is possible for the
4778	 * insertion point to not be the end because our txg may already be
4779	 * quiescing at this point and other callbacks in the open txg
4780	 * (from other objsets) may have sneaked in.
4781	 */
4782	tmp_cb = list_tail(&zcl.zcl_callbacks);
4783	while (tmp_cb != NULL && tmp_cb->zcd_txg > txg)
4784		tmp_cb = list_prev(&zcl.zcl_callbacks, tmp_cb);
4785
4786	/* Add the 3 callbacks to the list */
4787	for (i = 0; i < 3; i++) {
4788		if (tmp_cb == NULL)
4789			list_insert_head(&zcl.zcl_callbacks, cb_data[i]);
4790		else
4791			list_insert_after(&zcl.zcl_callbacks, tmp_cb,
4792			    cb_data[i]);
4793
4794		cb_data[i]->zcd_added = B_TRUE;
4795		VERIFY(!cb_data[i]->zcd_called);
4796
4797		tmp_cb = cb_data[i];
4798	}
4799
4800	mutex_exit(&zcl.zcl_callbacks_lock);
4801
4802	dmu_tx_commit(tx);
4803}
4804
4805/* ARGSUSED */
4806void
4807ztest_dsl_prop_get_set(ztest_ds_t *zd, uint64_t id)
4808{
4809	zfs_prop_t proplist[] = {
4810		ZFS_PROP_CHECKSUM,
4811		ZFS_PROP_COMPRESSION,
4812		ZFS_PROP_COPIES,
4813		ZFS_PROP_DEDUP
4814	};
4815
4816	rw_enter(&ztest_name_lock, RW_READER);
4817
4818	for (int p = 0; p < sizeof (proplist) / sizeof (proplist[0]); p++)
4819		(void) ztest_dsl_prop_set_uint64(zd->zd_name, proplist[p],
4820		    ztest_random_dsl_prop(proplist[p]), (int)ztest_random(2));
4821
4822	rw_exit(&ztest_name_lock);
4823}
4824
4825/* ARGSUSED */
4826void
4827ztest_remap_blocks(ztest_ds_t *zd, uint64_t id)
4828{
4829	rw_enter(&ztest_name_lock, RW_READER);
4830
4831	int error = dmu_objset_remap_indirects(zd->zd_name);
4832	if (error == ENOSPC)
4833		error = 0;
4834	ASSERT0(error);
4835
4836	rw_exit(&ztest_name_lock);
4837}
4838
4839/* ARGSUSED */
4840void
4841ztest_spa_prop_get_set(ztest_ds_t *zd, uint64_t id)
4842{
4843	nvlist_t *props = NULL;
4844
4845	rw_enter(&ztest_name_lock, RW_READER);
4846
4847	(void) ztest_spa_prop_set_uint64(ZPOOL_PROP_DEDUPDITTO,
4848	    ZIO_DEDUPDITTO_MIN + ztest_random(ZIO_DEDUPDITTO_MIN));
4849
4850	VERIFY0(spa_prop_get(ztest_spa, &props));
4851
4852	if (ztest_opts.zo_verbose >= 6)
4853		dump_nvlist(props, 4);
4854
4855	nvlist_free(props);
4856
4857	rw_exit(&ztest_name_lock);
4858}
4859
4860static int
4861user_release_one(const char *snapname, const char *holdname)
4862{
4863	nvlist_t *snaps, *holds;
4864	int error;
4865
4866	snaps = fnvlist_alloc();
4867	holds = fnvlist_alloc();
4868	fnvlist_add_boolean(holds, holdname);
4869	fnvlist_add_nvlist(snaps, snapname, holds);
4870	fnvlist_free(holds);
4871	error = dsl_dataset_user_release(snaps, NULL);
4872	fnvlist_free(snaps);
4873	return (error);
4874}
4875
4876/*
4877 * Test snapshot hold/release and deferred destroy.
4878 */
4879void
4880ztest_dmu_snapshot_hold(ztest_ds_t *zd, uint64_t id)
4881{
4882	int error;
4883	objset_t *os = zd->zd_os;
4884	objset_t *origin;
4885	char snapname[100];
4886	char fullname[100];
4887	char clonename[100];
4888	char tag[100];
4889	char osname[ZFS_MAX_DATASET_NAME_LEN];
4890	nvlist_t *holds;
4891
4892	rw_enter(&ztest_name_lock, RW_READER);
4893
4894	dmu_objset_name(os, osname);
4895
4896	(void) snprintf(snapname, sizeof (snapname), "sh1_%llu", id);
4897	(void) snprintf(fullname, sizeof (fullname), "%s@%s", osname, snapname);
4898	(void) snprintf(clonename, sizeof (clonename),
4899	    "%s/ch1_%llu", osname, id);
4900	(void) snprintf(tag, sizeof (tag), "tag_%llu", id);
4901
4902	/*
4903	 * Clean up from any previous run.
4904	 */
4905	error = dsl_destroy_head(clonename);
4906	if (error != ENOENT)
4907		ASSERT0(error);
4908	error = user_release_one(fullname, tag);
4909	if (error != ESRCH && error != ENOENT)
4910		ASSERT0(error);
4911	error = dsl_destroy_snapshot(fullname, B_FALSE);
4912	if (error != ENOENT)
4913		ASSERT0(error);
4914
4915	/*
4916	 * Create snapshot, clone it, mark snap for deferred destroy,
4917	 * destroy clone, verify snap was also destroyed.
4918	 */
4919	error = dmu_objset_snapshot_one(osname, snapname);
4920	if (error) {
4921		if (error == ENOSPC) {
4922			ztest_record_enospc("dmu_objset_snapshot");
4923			goto out;
4924		}
4925		fatal(0, "dmu_objset_snapshot(%s) = %d", fullname, error);
4926	}
4927
4928	error = dmu_objset_clone(clonename, fullname);
4929	if (error) {
4930		if (error == ENOSPC) {
4931			ztest_record_enospc("dmu_objset_clone");
4932			goto out;
4933		}
4934		fatal(0, "dmu_objset_clone(%s) = %d", clonename, error);
4935	}
4936
4937	error = dsl_destroy_snapshot(fullname, B_TRUE);
4938	if (error) {
4939		fatal(0, "dsl_destroy_snapshot(%s, B_TRUE) = %d",
4940		    fullname, error);
4941	}
4942
4943	error = dsl_destroy_head(clonename);
4944	if (error)
4945		fatal(0, "dsl_destroy_head(%s) = %d", clonename, error);
4946
4947	error = dmu_objset_hold(fullname, FTAG, &origin);
4948	if (error != ENOENT)
4949		fatal(0, "dmu_objset_hold(%s) = %d", fullname, error);
4950
4951	/*
4952	 * Create snapshot, add temporary hold, verify that we can't
4953	 * destroy a held snapshot, mark for deferred destroy,
4954	 * release hold, verify snapshot was destroyed.
4955	 */
4956	error = dmu_objset_snapshot_one(osname, snapname);
4957	if (error) {
4958		if (error == ENOSPC) {
4959			ztest_record_enospc("dmu_objset_snapshot");
4960			goto out;
4961		}
4962		fatal(0, "dmu_objset_snapshot(%s) = %d", fullname, error);
4963	}
4964
4965	holds = fnvlist_alloc();
4966	fnvlist_add_string(holds, fullname, tag);
4967	error = dsl_dataset_user_hold(holds, 0, NULL);
4968	fnvlist_free(holds);
4969
4970	if (error == ENOSPC) {
4971		ztest_record_enospc("dsl_dataset_user_hold");
4972		goto out;
4973	} else if (error) {
4974		fatal(0, "dsl_dataset_user_hold(%s, %s) = %u",
4975		    fullname, tag, error);
4976	}
4977
4978	error = dsl_destroy_snapshot(fullname, B_FALSE);
4979	if (error != EBUSY) {
4980		fatal(0, "dsl_destroy_snapshot(%s, B_FALSE) = %d",
4981		    fullname, error);
4982	}
4983
4984	error = dsl_destroy_snapshot(fullname, B_TRUE);
4985	if (error) {
4986		fatal(0, "dsl_destroy_snapshot(%s, B_TRUE) = %d",
4987		    fullname, error);
4988	}
4989
4990	error = user_release_one(fullname, tag);
4991	if (error)
4992		fatal(0, "user_release_one(%s, %s) = %d", fullname, tag, error);
4993
4994	VERIFY3U(dmu_objset_hold(fullname, FTAG, &origin), ==, ENOENT);
4995
4996out:
4997	rw_exit(&ztest_name_lock);
4998}
4999
5000/*
5001 * Inject random faults into the on-disk data.
5002 */
5003/* ARGSUSED */
5004void
5005ztest_fault_inject(ztest_ds_t *zd, uint64_t id)
5006{
5007	ztest_shared_t *zs = ztest_shared;
5008	spa_t *spa = ztest_spa;
5009	int fd;
5010	uint64_t offset;
5011	uint64_t leaves;
5012	uint64_t bad = 0x1990c0ffeedecadeULL;
5013	uint64_t top, leaf;
5014	char path0[MAXPATHLEN];
5015	char pathrand[MAXPATHLEN];
5016	size_t fsize;
5017	int bshift = SPA_MAXBLOCKSHIFT + 2;
5018	int iters = 1000;
5019	int maxfaults;
5020	int mirror_save;
5021	vdev_t *vd0 = NULL;
5022	uint64_t guid0 = 0;
5023	boolean_t islog = B_FALSE;
5024
5025	mutex_enter(&ztest_vdev_lock);
5026
5027	/*
5028	 * Device removal is in progress, fault injection must be disabled
5029	 * until it completes and the pool is scrubbed.  The fault injection
5030	 * strategy for damaging blocks does not take in to account evacuated
5031	 * blocks which may have already been damaged.
5032	 */
5033	if (ztest_device_removal_active) {
5034		mutex_exit(&ztest_vdev_lock);
5035		return;
5036	}
5037
5038	maxfaults = MAXFAULTS();
5039	leaves = MAX(zs->zs_mirrors, 1) * ztest_opts.zo_raidz;
5040	mirror_save = zs->zs_mirrors;
5041	mutex_exit(&ztest_vdev_lock);
5042
5043	ASSERT(leaves >= 1);
5044
5045	/*
5046	 * Grab the name lock as reader. There are some operations
5047	 * which don't like to have their vdevs changed while
5048	 * they are in progress (i.e. spa_change_guid). Those
5049	 * operations will have grabbed the name lock as writer.
5050	 */
5051	rw_enter(&ztest_name_lock, RW_READER);
5052
5053	/*
5054	 * We need SCL_STATE here because we're going to look at vd0->vdev_tsd.
5055	 */
5056	spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
5057
5058	if (ztest_random(2) == 0) {
5059		/*
5060		 * Inject errors on a normal data device or slog device.
5061		 */
5062		top = ztest_random_vdev_top(spa, B_TRUE);
5063		leaf = ztest_random(leaves) + zs->zs_splits;
5064
5065		/*
5066		 * Generate paths to the first leaf in this top-level vdev,
5067		 * and to the random leaf we selected.  We'll induce transient
5068		 * write failures and random online/offline activity on leaf 0,
5069		 * and we'll write random garbage to the randomly chosen leaf.
5070		 */
5071		(void) snprintf(path0, sizeof (path0), ztest_dev_template,
5072		    ztest_opts.zo_dir, ztest_opts.zo_pool,
5073		    top * leaves + zs->zs_splits);
5074		(void) snprintf(pathrand, sizeof (pathrand), ztest_dev_template,
5075		    ztest_opts.zo_dir, ztest_opts.zo_pool,
5076		    top * leaves + leaf);
5077
5078		vd0 = vdev_lookup_by_path(spa->spa_root_vdev, path0);
5079		if (vd0 != NULL && vd0->vdev_top->vdev_islog)
5080			islog = B_TRUE;
5081
5082		/*
5083		 * If the top-level vdev needs to be resilvered
5084		 * then we only allow faults on the device that is
5085		 * resilvering.
5086		 */
5087		if (vd0 != NULL && maxfaults != 1 &&
5088		    (!vdev_resilver_needed(vd0->vdev_top, NULL, NULL) ||
5089		    vd0->vdev_resilver_txg != 0)) {
5090			/*
5091			 * Make vd0 explicitly claim to be unreadable,
5092			 * or unwriteable, or reach behind its back
5093			 * and close the underlying fd.  We can do this if
5094			 * maxfaults == 0 because we'll fail and reexecute,
5095			 * and we can do it if maxfaults >= 2 because we'll
5096			 * have enough redundancy.  If maxfaults == 1, the
5097			 * combination of this with injection of random data
5098			 * corruption below exceeds the pool's fault tolerance.
5099			 */
5100			vdev_file_t *vf = vd0->vdev_tsd;
5101
5102			zfs_dbgmsg("injecting fault to vdev %llu; maxfaults=%d",
5103			    (long long)vd0->vdev_id, (int)maxfaults);
5104
5105			if (vf != NULL && ztest_random(3) == 0) {
5106				(void) close(vf->vf_vnode->v_fd);
5107				vf->vf_vnode->v_fd = -1;
5108			} else if (ztest_random(2) == 0) {
5109				vd0->vdev_cant_read = B_TRUE;
5110			} else {
5111				vd0->vdev_cant_write = B_TRUE;
5112			}
5113			guid0 = vd0->vdev_guid;
5114		}
5115	} else {
5116		/*
5117		 * Inject errors on an l2cache device.
5118		 */
5119		spa_aux_vdev_t *sav = &spa->spa_l2cache;
5120
5121		if (sav->sav_count == 0) {
5122			spa_config_exit(spa, SCL_STATE, FTAG);
5123			rw_exit(&ztest_name_lock);
5124			return;
5125		}
5126		vd0 = sav->sav_vdevs[ztest_random(sav->sav_count)];
5127		guid0 = vd0->vdev_guid;
5128		(void) strcpy(path0, vd0->vdev_path);
5129		(void) strcpy(pathrand, vd0->vdev_path);
5130
5131		leaf = 0;
5132		leaves = 1;
5133		maxfaults = INT_MAX;	/* no limit on cache devices */
5134	}
5135
5136	spa_config_exit(spa, SCL_STATE, FTAG);
5137	rw_exit(&ztest_name_lock);
5138
5139	/*
5140	 * If we can tolerate two or more faults, or we're dealing
5141	 * with a slog, randomly online/offline vd0.
5142	 */
5143	if ((maxfaults >= 2 || islog) && guid0 != 0) {
5144		if (ztest_random(10) < 6) {
5145			int flags = (ztest_random(2) == 0 ?
5146			    ZFS_OFFLINE_TEMPORARY : 0);
5147
5148			/*
5149			 * We have to grab the zs_name_lock as writer to
5150			 * prevent a race between offlining a slog and
5151			 * destroying a dataset. Offlining the slog will
5152			 * grab a reference on the dataset which may cause
5153			 * dmu_objset_destroy() to fail with EBUSY thus
5154			 * leaving the dataset in an inconsistent state.
5155			 */
5156			if (islog)
5157				rw_enter(&ztest_name_lock, RW_WRITER);
5158
5159			VERIFY(vdev_offline(spa, guid0, flags) != EBUSY);
5160
5161			if (islog)
5162				rw_exit(&ztest_name_lock);
5163		} else {
5164			/*
5165			 * Ideally we would like to be able to randomly
5166			 * call vdev_[on|off]line without holding locks
5167			 * to force unpredictable failures but the side
5168			 * effects of vdev_[on|off]line prevent us from
5169			 * doing so. We grab the ztest_vdev_lock here to
5170			 * prevent a race between injection testing and
5171			 * aux_vdev removal.
5172			 */
5173			mutex_enter(&ztest_vdev_lock);
5174			(void) vdev_online(spa, guid0, 0, NULL);
5175			mutex_exit(&ztest_vdev_lock);
5176		}
5177	}
5178
5179	if (maxfaults == 0)
5180		return;
5181
5182	/*
5183	 * We have at least single-fault tolerance, so inject data corruption.
5184	 */
5185	fd = open(pathrand, O_RDWR);
5186
5187	if (fd == -1) /* we hit a gap in the device namespace */
5188		return;
5189
5190	fsize = lseek(fd, 0, SEEK_END);
5191
5192	while (--iters != 0) {
5193		/*
5194		 * The offset must be chosen carefully to ensure that
5195		 * we do not inject a given logical block with errors
5196		 * on two different leaf devices, because ZFS can not
5197		 * tolerate that (if maxfaults==1).
5198		 *
5199		 * We divide each leaf into chunks of size
5200		 * (# leaves * SPA_MAXBLOCKSIZE * 4).  Within each chunk
5201		 * there is a series of ranges to which we can inject errors.
5202		 * Each range can accept errors on only a single leaf vdev.
5203		 * The error injection ranges are separated by ranges
5204		 * which we will not inject errors on any device (DMZs).
5205		 * Each DMZ must be large enough such that a single block
5206		 * can not straddle it, so that a single block can not be
5207		 * a target in two different injection ranges (on different
5208		 * leaf vdevs).
5209		 *
5210		 * For example, with 3 leaves, each chunk looks like:
5211		 *    0 to  32M: injection range for leaf 0
5212		 *  32M to  64M: DMZ - no injection allowed
5213		 *  64M to  96M: injection range for leaf 1
5214		 *  96M to 128M: DMZ - no injection allowed
5215		 * 128M to 160M: injection range for leaf 2
5216		 * 160M to 192M: DMZ - no injection allowed
5217		 */
5218		offset = ztest_random(fsize / (leaves << bshift)) *
5219		    (leaves << bshift) + (leaf << bshift) +
5220		    (ztest_random(1ULL << (bshift - 1)) & -8ULL);
5221
5222		/*
5223		 * Only allow damage to the labels at one end of the vdev.
5224		 *
5225		 * If all labels are damaged, the device will be totally
5226		 * inaccessible, which will result in loss of data,
5227		 * because we also damage (parts of) the other side of
5228		 * the mirror/raidz.
5229		 *
5230		 * Additionally, we will always have both an even and an
5231		 * odd label, so that we can handle crashes in the
5232		 * middle of vdev_config_sync().
5233		 */
5234		if ((leaf & 1) == 0 && offset < VDEV_LABEL_START_SIZE)
5235			continue;
5236
5237		/*
5238		 * The two end labels are stored at the "end" of the disk, but
5239		 * the end of the disk (vdev_psize) is aligned to
5240		 * sizeof (vdev_label_t).
5241		 */
5242		uint64_t psize = P2ALIGN(fsize, sizeof (vdev_label_t));
5243		if ((leaf & 1) == 1 &&
5244		    offset + sizeof (bad) > psize - VDEV_LABEL_END_SIZE)
5245			continue;
5246
5247		mutex_enter(&ztest_vdev_lock);
5248		if (mirror_save != zs->zs_mirrors) {
5249			mutex_exit(&ztest_vdev_lock);
5250			(void) close(fd);
5251			return;
5252		}
5253
5254		if (pwrite(fd, &bad, sizeof (bad), offset) != sizeof (bad))
5255			fatal(1, "can't inject bad word at 0x%llx in %s",
5256			    offset, pathrand);
5257
5258		mutex_exit(&ztest_vdev_lock);
5259
5260		if (ztest_opts.zo_verbose >= 7)
5261			(void) printf("injected bad word into %s,"
5262			    " offset 0x%llx\n", pathrand, (u_longlong_t)offset);
5263	}
5264
5265	(void) close(fd);
5266}
5267
5268/*
5269 * Verify that DDT repair works as expected.
5270 */
5271void
5272ztest_ddt_repair(ztest_ds_t *zd, uint64_t id)
5273{
5274	ztest_shared_t *zs = ztest_shared;
5275	spa_t *spa = ztest_spa;
5276	objset_t *os = zd->zd_os;
5277	ztest_od_t od[1];
5278	uint64_t object, blocksize, txg, pattern, psize;
5279	enum zio_checksum checksum = spa_dedup_checksum(spa);
5280	dmu_buf_t *db;
5281	dmu_tx_t *tx;
5282	abd_t *abd;
5283	blkptr_t blk;
5284	int copies = 2 * ZIO_DEDUPDITTO_MIN;
5285
5286	blocksize = ztest_random_blocksize();
5287	blocksize = MIN(blocksize, 2048);	/* because we write so many */
5288
5289	ztest_od_init(&od[0], id, FTAG, 0, DMU_OT_UINT64_OTHER, blocksize, 0);
5290
5291	if (ztest_object_init(zd, od, sizeof (od), B_FALSE) != 0)
5292		return;
5293
5294	/*
5295	 * Take the name lock as writer to prevent anyone else from changing
5296	 * the pool and dataset properies we need to maintain during this test.
5297	 */
5298	rw_enter(&ztest_name_lock, RW_WRITER);
5299
5300	if (ztest_dsl_prop_set_uint64(zd->zd_name, ZFS_PROP_DEDUP, checksum,
5301	    B_FALSE) != 0 ||
5302	    ztest_dsl_prop_set_uint64(zd->zd_name, ZFS_PROP_COPIES, 1,
5303	    B_FALSE) != 0) {
5304		rw_exit(&ztest_name_lock);
5305		return;
5306	}
5307
5308	dmu_objset_stats_t dds;
5309	dsl_pool_config_enter(dmu_objset_pool(os), FTAG);
5310	dmu_objset_fast_stat(os, &dds);
5311	dsl_pool_config_exit(dmu_objset_pool(os), FTAG);
5312
5313	object = od[0].od_object;
5314	blocksize = od[0].od_blocksize;
5315	pattern = zs->zs_guid ^ dds.dds_guid;
5316
5317	ASSERT(object != 0);
5318
5319	tx = dmu_tx_create(os);
5320	dmu_tx_hold_write(tx, object, 0, copies * blocksize);
5321	txg = ztest_tx_assign(tx, TXG_WAIT, FTAG);
5322	if (txg == 0) {
5323		rw_exit(&ztest_name_lock);
5324		return;
5325	}
5326
5327	/*
5328	 * Write all the copies of our block.
5329	 */
5330	for (int i = 0; i < copies; i++) {
5331		uint64_t offset = i * blocksize;
5332		int error = dmu_buf_hold(os, object, offset, FTAG, &db,
5333		    DMU_READ_NO_PREFETCH);
5334		if (error != 0) {
5335			fatal(B_FALSE, "dmu_buf_hold(%p, %llu, %llu) = %u",
5336			    os, (long long)object, (long long) offset, error);
5337		}
5338		ASSERT(db->db_offset == offset);
5339		ASSERT(db->db_size == blocksize);
5340		ASSERT(ztest_pattern_match(db->db_data, db->db_size, pattern) ||
5341		    ztest_pattern_match(db->db_data, db->db_size, 0ULL));
5342		dmu_buf_will_fill(db, tx);
5343		ztest_pattern_set(db->db_data, db->db_size, pattern);
5344		dmu_buf_rele(db, FTAG);
5345	}
5346
5347	dmu_tx_commit(tx);
5348	txg_wait_synced(spa_get_dsl(spa), txg);
5349
5350	/*
5351	 * Find out what block we got.
5352	 */
5353	VERIFY0(dmu_buf_hold(os, object, 0, FTAG, &db,
5354	    DMU_READ_NO_PREFETCH));
5355	blk = *((dmu_buf_impl_t *)db)->db_blkptr;
5356	dmu_buf_rele(db, FTAG);
5357
5358	/*
5359	 * Damage the block.  Dedup-ditto will save us when we read it later.
5360	 */
5361	psize = BP_GET_PSIZE(&blk);
5362	abd = abd_alloc_linear(psize, B_TRUE);
5363	ztest_pattern_set(abd_to_buf(abd), psize, ~pattern);
5364
5365	(void) zio_wait(zio_rewrite(NULL, spa, 0, &blk,
5366	    abd, psize, NULL, NULL, ZIO_PRIORITY_SYNC_WRITE,
5367	    ZIO_FLAG_CANFAIL | ZIO_FLAG_INDUCE_DAMAGE, NULL));
5368
5369	abd_free(abd);
5370
5371	rw_exit(&ztest_name_lock);
5372}
5373
5374/*
5375 * Scrub the pool.
5376 */
5377/* ARGSUSED */
5378void
5379ztest_scrub(ztest_ds_t *zd, uint64_t id)
5380{
5381	spa_t *spa = ztest_spa;
5382
5383	/*
5384	 * Scrub in progress by device removal.
5385	 */
5386	if (ztest_device_removal_active)
5387		return;
5388
5389	(void) spa_scan(spa, POOL_SCAN_SCRUB);
5390	(void) poll(NULL, 0, 100); /* wait a moment, then force a restart */
5391	(void) spa_scan(spa, POOL_SCAN_SCRUB);
5392}
5393
5394/*
5395 * Change the guid for the pool.
5396 */
5397/* ARGSUSED */
5398void
5399ztest_reguid(ztest_ds_t *zd, uint64_t id)
5400{
5401	spa_t *spa = ztest_spa;
5402	uint64_t orig, load;
5403	int error;
5404
5405	orig = spa_guid(spa);
5406	load = spa_load_guid(spa);
5407
5408	rw_enter(&ztest_name_lock, RW_WRITER);
5409	error = spa_change_guid(spa);
5410	rw_exit(&ztest_name_lock);
5411
5412	if (error != 0)
5413		return;
5414
5415	if (ztest_opts.zo_verbose >= 4) {
5416		(void) printf("Changed guid old %llu -> %llu\n",
5417		    (u_longlong_t)orig, (u_longlong_t)spa_guid(spa));
5418	}
5419
5420	VERIFY3U(orig, !=, spa_guid(spa));
5421	VERIFY3U(load, ==, spa_load_guid(spa));
5422}
5423
5424/*
5425 * Rename the pool to a different name and then rename it back.
5426 */
5427/* ARGSUSED */
5428void
5429ztest_spa_rename(ztest_ds_t *zd, uint64_t id)
5430{
5431	char *oldname, *newname;
5432	spa_t *spa;
5433
5434	rw_enter(&ztest_name_lock, RW_WRITER);
5435
5436	oldname = ztest_opts.zo_pool;
5437	newname = umem_alloc(strlen(oldname) + 5, UMEM_NOFAIL);
5438	(void) strcpy(newname, oldname);
5439	(void) strcat(newname, "_tmp");
5440
5441	/*
5442	 * Do the rename
5443	 */
5444	VERIFY3U(0, ==, spa_rename(oldname, newname));
5445
5446	/*
5447	 * Try to open it under the old name, which shouldn't exist
5448	 */
5449	VERIFY3U(ENOENT, ==, spa_open(oldname, &spa, FTAG));
5450
5451	/*
5452	 * Open it under the new name and make sure it's still the same spa_t.
5453	 */
5454	VERIFY3U(0, ==, spa_open(newname, &spa, FTAG));
5455
5456	ASSERT(spa == ztest_spa);
5457	spa_close(spa, FTAG);
5458
5459	/*
5460	 * Rename it back to the original
5461	 */
5462	VERIFY3U(0, ==, spa_rename(newname, oldname));
5463
5464	/*
5465	 * Make sure it can still be opened
5466	 */
5467	VERIFY3U(0, ==, spa_open(oldname, &spa, FTAG));
5468
5469	ASSERT(spa == ztest_spa);
5470	spa_close(spa, FTAG);
5471
5472	umem_free(newname, strlen(newname) + 1);
5473
5474	rw_exit(&ztest_name_lock);
5475}
5476
5477static vdev_t *
5478ztest_random_concrete_vdev_leaf(vdev_t *vd)
5479{
5480	if (vd == NULL)
5481		return (NULL);
5482
5483	if (vd->vdev_children == 0)
5484		return (vd);
5485
5486	vdev_t *eligible[vd->vdev_children];
5487	int eligible_idx = 0, i;
5488	for (i = 0; i < vd->vdev_children; i++) {
5489		vdev_t *cvd = vd->vdev_child[i];
5490		if (cvd->vdev_top->vdev_removing)
5491			continue;
5492		if (cvd->vdev_children > 0 ||
5493		    (vdev_is_concrete(cvd) && !cvd->vdev_detached)) {
5494			eligible[eligible_idx++] = cvd;
5495		}
5496	}
5497	VERIFY(eligible_idx > 0);
5498
5499	uint64_t child_no = ztest_random(eligible_idx);
5500	return (ztest_random_concrete_vdev_leaf(eligible[child_no]));
5501}
5502
5503/* ARGSUSED */
5504void
5505ztest_initialize(ztest_ds_t *zd, uint64_t id)
5506{
5507	spa_t *spa = ztest_spa;
5508	int error = 0;
5509
5510	mutex_enter(&ztest_vdev_lock);
5511
5512	spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
5513
5514	/* Random leaf vdev */
5515	vdev_t *rand_vd = ztest_random_concrete_vdev_leaf(spa->spa_root_vdev);
5516	if (rand_vd == NULL) {
5517		spa_config_exit(spa, SCL_VDEV, FTAG);
5518		mutex_exit(&ztest_vdev_lock);
5519		return;
5520	}
5521
5522	/*
5523	 * The random vdev we've selected may change as soon as we
5524	 * drop the spa_config_lock. We create local copies of things
5525	 * we're interested in.
5526	 */
5527	uint64_t guid = rand_vd->vdev_guid;
5528	char *path = strdup(rand_vd->vdev_path);
5529	boolean_t active = rand_vd->vdev_initialize_thread != NULL;
5530
5531	zfs_dbgmsg("vd %p, guid %llu", rand_vd, guid);
5532	spa_config_exit(spa, SCL_VDEV, FTAG);
5533
5534	uint64_t cmd = ztest_random(POOL_INITIALIZE_FUNCS);
5535	error = spa_vdev_initialize(spa, guid, cmd);
5536	switch (cmd) {
5537	case POOL_INITIALIZE_CANCEL:
5538		if (ztest_opts.zo_verbose >= 4) {
5539			(void) printf("Cancel initialize %s", path);
5540			if (!active)
5541				(void) printf(" failed (no initialize active)");
5542			(void) printf("\n");
5543		}
5544		break;
5545	case POOL_INITIALIZE_DO:
5546		if (ztest_opts.zo_verbose >= 4) {
5547			(void) printf("Start initialize %s", path);
5548			if (active && error == 0)
5549				(void) printf(" failed (already active)");
5550			else if (error != 0)
5551				(void) printf(" failed (error %d)", error);
5552			(void) printf("\n");
5553		}
5554		break;
5555	case POOL_INITIALIZE_SUSPEND:
5556		if (ztest_opts.zo_verbose >= 4) {
5557			(void) printf("Suspend initialize %s", path);
5558			if (!active)
5559				(void) printf(" failed (no initialize active)");
5560			(void) printf("\n");
5561		}
5562		break;
5563	}
5564	free(path);
5565	mutex_exit(&ztest_vdev_lock);
5566}
5567
5568/*
5569 * Verify pool integrity by running zdb.
5570 */
5571static void
5572ztest_run_zdb(char *pool)
5573{
5574	int status;
5575	char zdb[MAXPATHLEN + MAXNAMELEN + 20];
5576	char zbuf[1024];
5577	char *bin;
5578	char *ztest;
5579	char *isa;
5580	int isalen;
5581	FILE *fp;
5582
5583	strlcpy(zdb, "/usr/bin/ztest", sizeof(zdb));
5584
5585	/* zdb lives in /usr/sbin, while ztest lives in /usr/bin */
5586	bin = strstr(zdb, "/usr/bin/");
5587	ztest = strstr(bin, "/ztest");
5588	isa = bin + 8;
5589	isalen = ztest - isa;
5590	isa = strdup(isa);
5591	/* LINTED */
5592	(void) sprintf(bin,
5593	    "/usr/sbin%.*s/zdb -bcc%s%s -G -d -U %s %s",
5594	    isalen,
5595	    isa,
5596	    ztest_opts.zo_verbose >= 3 ? "s" : "",
5597	    ztest_opts.zo_verbose >= 4 ? "v" : "",
5598	    spa_config_path,
5599	    pool);
5600	free(isa);
5601
5602	if (ztest_opts.zo_verbose >= 5)
5603		(void) printf("Executing %s\n", strstr(zdb, "zdb "));
5604
5605	fp = popen(zdb, "r");
5606	assert(fp != NULL);
5607
5608	while (fgets(zbuf, sizeof (zbuf), fp) != NULL)
5609		if (ztest_opts.zo_verbose >= 3)
5610			(void) printf("%s", zbuf);
5611
5612	status = pclose(fp);
5613
5614	if (status == 0)
5615		return;
5616
5617	ztest_dump_core = 0;
5618	if (WIFEXITED(status))
5619		fatal(0, "'%s' exit code %d", zdb, WEXITSTATUS(status));
5620	else
5621		fatal(0, "'%s' died with signal %d", zdb, WTERMSIG(status));
5622}
5623
5624static void
5625ztest_walk_pool_directory(char *header)
5626{
5627	spa_t *spa = NULL;
5628
5629	if (ztest_opts.zo_verbose >= 6)
5630		(void) printf("%s\n", header);
5631
5632	mutex_enter(&spa_namespace_lock);
5633	while ((spa = spa_next(spa)) != NULL)
5634		if (ztest_opts.zo_verbose >= 6)
5635			(void) printf("\t%s\n", spa_name(spa));
5636	mutex_exit(&spa_namespace_lock);
5637}
5638
5639static void
5640ztest_spa_import_export(char *oldname, char *newname)
5641{
5642	nvlist_t *config, *newconfig;
5643	uint64_t pool_guid;
5644	spa_t *spa;
5645	int error;
5646
5647	if (ztest_opts.zo_verbose >= 4) {
5648		(void) printf("import/export: old = %s, new = %s\n",
5649		    oldname, newname);
5650	}
5651
5652	/*
5653	 * Clean up from previous runs.
5654	 */
5655	(void) spa_destroy(newname);
5656
5657	/*
5658	 * Get the pool's configuration and guid.
5659	 */
5660	VERIFY3U(0, ==, spa_open(oldname, &spa, FTAG));
5661
5662	/*
5663	 * Kick off a scrub to tickle scrub/export races.
5664	 */
5665	if (ztest_random(2) == 0)
5666		(void) spa_scan(spa, POOL_SCAN_SCRUB);
5667
5668	pool_guid = spa_guid(spa);
5669	spa_close(spa, FTAG);
5670
5671	ztest_walk_pool_directory("pools before export");
5672
5673	/*
5674	 * Export it.
5675	 */
5676	VERIFY3U(0, ==, spa_export(oldname, &config, B_FALSE, B_FALSE));
5677
5678	ztest_walk_pool_directory("pools after export");
5679
5680	/*
5681	 * Try to import it.
5682	 */
5683	newconfig = spa_tryimport(config);
5684	ASSERT(newconfig != NULL);
5685	nvlist_free(newconfig);
5686
5687	/*
5688	 * Import it under the new name.
5689	 */
5690	error = spa_import(newname, config, NULL, 0);
5691	if (error != 0) {
5692		dump_nvlist(config, 0);
5693		fatal(B_FALSE, "couldn't import pool %s as %s: error %u",
5694		    oldname, newname, error);
5695	}
5696
5697	ztest_walk_pool_directory("pools after import");
5698
5699	/*
5700	 * Try to import it again -- should fail with EEXIST.
5701	 */
5702	VERIFY3U(EEXIST, ==, spa_import(newname, config, NULL, 0));
5703
5704	/*
5705	 * Try to import it under a different name -- should fail with EEXIST.
5706	 */
5707	VERIFY3U(EEXIST, ==, spa_import(oldname, config, NULL, 0));
5708
5709	/*
5710	 * Verify that the pool is no longer visible under the old name.
5711	 */
5712	VERIFY3U(ENOENT, ==, spa_open(oldname, &spa, FTAG));
5713
5714	/*
5715	 * Verify that we can open and close the pool using the new name.
5716	 */
5717	VERIFY3U(0, ==, spa_open(newname, &spa, FTAG));
5718	ASSERT(pool_guid == spa_guid(spa));
5719	spa_close(spa, FTAG);
5720
5721	nvlist_free(config);
5722}
5723
5724static void
5725ztest_resume(spa_t *spa)
5726{
5727	if (spa_suspended(spa) && ztest_opts.zo_verbose >= 6)
5728		(void) printf("resuming from suspended state\n");
5729	spa_vdev_state_enter(spa, SCL_NONE);
5730	vdev_clear(spa, NULL);
5731	(void) spa_vdev_state_exit(spa, NULL, 0);
5732	(void) zio_resume(spa);
5733}
5734
5735static void *
5736ztest_resume_thread(void *arg)
5737{
5738	spa_t *spa = arg;
5739
5740	while (!ztest_exiting) {
5741		if (spa_suspended(spa))
5742			ztest_resume(spa);
5743		(void) poll(NULL, 0, 100);
5744
5745		/*
5746		 * Periodically change the zfs_compressed_arc_enabled setting.
5747		 */
5748		if (ztest_random(10) == 0)
5749			zfs_compressed_arc_enabled = ztest_random(2);
5750
5751		/*
5752		 * Periodically change the zfs_abd_scatter_enabled setting.
5753		 */
5754		if (ztest_random(10) == 0)
5755			zfs_abd_scatter_enabled = ztest_random(2);
5756	}
5757	return (NULL);
5758}
5759
5760static void *
5761ztest_deadman_thread(void *arg)
5762{
5763	ztest_shared_t *zs = arg;
5764	spa_t *spa = ztest_spa;
5765	hrtime_t delta, total = 0;
5766
5767	for (;;) {
5768		delta = zs->zs_thread_stop - zs->zs_thread_start +
5769		    MSEC2NSEC(zfs_deadman_synctime_ms);
5770
5771		(void) poll(NULL, 0, (int)NSEC2MSEC(delta));
5772
5773		/*
5774		 * If the pool is suspended then fail immediately. Otherwise,
5775		 * check to see if the pool is making any progress. If
5776		 * vdev_deadman() discovers that there hasn't been any recent
5777		 * I/Os then it will end up aborting the tests.
5778		 */
5779		if (spa_suspended(spa) || spa->spa_root_vdev == NULL) {
5780			fatal(0, "aborting test after %llu seconds because "
5781			    "pool has transitioned to a suspended state.",
5782			    zfs_deadman_synctime_ms / 1000);
5783			return (NULL);
5784		}
5785		vdev_deadman(spa->spa_root_vdev);
5786
5787		total += zfs_deadman_synctime_ms/1000;
5788		(void) printf("ztest has been running for %lld seconds\n",
5789		    total);
5790	}
5791}
5792
5793static void
5794ztest_execute(int test, ztest_info_t *zi, uint64_t id)
5795{
5796	ztest_ds_t *zd = &ztest_ds[id % ztest_opts.zo_datasets];
5797	ztest_shared_callstate_t *zc = ZTEST_GET_SHARED_CALLSTATE(test);
5798	hrtime_t functime = gethrtime();
5799
5800	for (int i = 0; i < zi->zi_iters; i++)
5801		zi->zi_func(zd, id);
5802
5803	functime = gethrtime() - functime;
5804
5805	atomic_add_64(&zc->zc_count, 1);
5806	atomic_add_64(&zc->zc_time, functime);
5807
5808	if (ztest_opts.zo_verbose >= 4) {
5809		Dl_info dli;
5810		(void) dladdr((void *)zi->zi_func, &dli);
5811		(void) printf("%6.2f sec in %s\n",
5812		    (double)functime / NANOSEC, dli.dli_sname);
5813	}
5814}
5815
5816static void *
5817ztest_thread(void *arg)
5818{
5819	int rand;
5820	uint64_t id = (uintptr_t)arg;
5821	ztest_shared_t *zs = ztest_shared;
5822	uint64_t call_next;
5823	hrtime_t now;
5824	ztest_info_t *zi;
5825	ztest_shared_callstate_t *zc;
5826
5827	while ((now = gethrtime()) < zs->zs_thread_stop) {
5828		/*
5829		 * See if it's time to force a crash.
5830		 */
5831		if (now > zs->zs_thread_kill)
5832			ztest_kill(zs);
5833
5834		/*
5835		 * If we're getting ENOSPC with some regularity, stop.
5836		 */
5837		if (zs->zs_enospc_count > 10)
5838			break;
5839
5840		/*
5841		 * Pick a random function to execute.
5842		 */
5843		rand = ztest_random(ZTEST_FUNCS);
5844		zi = &ztest_info[rand];
5845		zc = ZTEST_GET_SHARED_CALLSTATE(rand);
5846		call_next = zc->zc_next;
5847
5848		if (now >= call_next &&
5849		    atomic_cas_64(&zc->zc_next, call_next, call_next +
5850		    ztest_random(2 * zi->zi_interval[0] + 1)) == call_next) {
5851			ztest_execute(rand, zi, id);
5852		}
5853	}
5854
5855	return (NULL);
5856}
5857
5858static void
5859ztest_dataset_name(char *dsname, char *pool, int d)
5860{
5861	(void) snprintf(dsname, ZFS_MAX_DATASET_NAME_LEN, "%s/ds_%d", pool, d);
5862}
5863
5864static void
5865ztest_dataset_destroy(int d)
5866{
5867	char name[ZFS_MAX_DATASET_NAME_LEN];
5868
5869	ztest_dataset_name(name, ztest_opts.zo_pool, d);
5870
5871	if (ztest_opts.zo_verbose >= 3)
5872		(void) printf("Destroying %s to free up space\n", name);
5873
5874	/*
5875	 * Cleanup any non-standard clones and snapshots.  In general,
5876	 * ztest thread t operates on dataset (t % zopt_datasets),
5877	 * so there may be more than one thing to clean up.
5878	 */
5879	for (int t = d; t < ztest_opts.zo_threads;
5880	    t += ztest_opts.zo_datasets) {
5881		ztest_dsl_dataset_cleanup(name, t);
5882	}
5883
5884	(void) dmu_objset_find(name, ztest_objset_destroy_cb, NULL,
5885	    DS_FIND_SNAPSHOTS | DS_FIND_CHILDREN);
5886}
5887
5888static void
5889ztest_dataset_dirobj_verify(ztest_ds_t *zd)
5890{
5891	uint64_t usedobjs, dirobjs, scratch;
5892
5893	/*
5894	 * ZTEST_DIROBJ is the object directory for the entire dataset.
5895	 * Therefore, the number of objects in use should equal the
5896	 * number of ZTEST_DIROBJ entries, +1 for ZTEST_DIROBJ itself.
5897	 * If not, we have an object leak.
5898	 *
5899	 * Note that we can only check this in ztest_dataset_open(),
5900	 * when the open-context and syncing-context values agree.
5901	 * That's because zap_count() returns the open-context value,
5902	 * while dmu_objset_space() returns the rootbp fill count.
5903	 */
5904	VERIFY3U(0, ==, zap_count(zd->zd_os, ZTEST_DIROBJ, &dirobjs));
5905	dmu_objset_space(zd->zd_os, &scratch, &scratch, &usedobjs, &scratch);
5906	ASSERT3U(dirobjs + 1, ==, usedobjs);
5907}
5908
5909static int
5910ztest_dataset_open(int d)
5911{
5912	ztest_ds_t *zd = &ztest_ds[d];
5913	uint64_t committed_seq = ZTEST_GET_SHARED_DS(d)->zd_seq;
5914	objset_t *os;
5915	zilog_t *zilog;
5916	char name[ZFS_MAX_DATASET_NAME_LEN];
5917	int error;
5918
5919	ztest_dataset_name(name, ztest_opts.zo_pool, d);
5920
5921	rw_enter(&ztest_name_lock, RW_READER);
5922
5923	error = ztest_dataset_create(name);
5924	if (error == ENOSPC) {
5925		rw_exit(&ztest_name_lock);
5926		ztest_record_enospc(FTAG);
5927		return (error);
5928	}
5929	ASSERT(error == 0 || error == EEXIST);
5930
5931	VERIFY0(dmu_objset_own(name, DMU_OST_OTHER, B_FALSE, zd, &os));
5932	rw_exit(&ztest_name_lock);
5933
5934	ztest_zd_init(zd, ZTEST_GET_SHARED_DS(d), os);
5935
5936	zilog = zd->zd_zilog;
5937
5938	if (zilog->zl_header->zh_claim_lr_seq != 0 &&
5939	    zilog->zl_header->zh_claim_lr_seq < committed_seq)
5940		fatal(0, "missing log records: claimed %llu < committed %llu",
5941		    zilog->zl_header->zh_claim_lr_seq, committed_seq);
5942
5943	ztest_dataset_dirobj_verify(zd);
5944
5945	zil_replay(os, zd, ztest_replay_vector);
5946
5947	ztest_dataset_dirobj_verify(zd);
5948
5949	if (ztest_opts.zo_verbose >= 6)
5950		(void) printf("%s replay %llu blocks, %llu records, seq %llu\n",
5951		    zd->zd_name,
5952		    (u_longlong_t)zilog->zl_parse_blk_count,
5953		    (u_longlong_t)zilog->zl_parse_lr_count,
5954		    (u_longlong_t)zilog->zl_replaying_seq);
5955
5956	zilog = zil_open(os, ztest_get_data);
5957
5958	if (zilog->zl_replaying_seq != 0 &&
5959	    zilog->zl_replaying_seq < committed_seq)
5960		fatal(0, "missing log records: replayed %llu < committed %llu",
5961		    zilog->zl_replaying_seq, committed_seq);
5962
5963	return (0);
5964}
5965
5966static void
5967ztest_dataset_close(int d)
5968{
5969	ztest_ds_t *zd = &ztest_ds[d];
5970
5971	zil_close(zd->zd_zilog);
5972	dmu_objset_disown(zd->zd_os, zd);
5973
5974	ztest_zd_fini(zd);
5975}
5976
5977/*
5978 * Kick off threads to run tests on all datasets in parallel.
5979 */
5980static void
5981ztest_run(ztest_shared_t *zs)
5982{
5983	thread_t *tid;
5984	spa_t *spa;
5985	objset_t *os;
5986	thread_t resume_tid;
5987	int error;
5988
5989	ztest_exiting = B_FALSE;
5990
5991	/*
5992	 * Initialize parent/child shared state.
5993	 */
5994	mutex_init(&ztest_checkpoint_lock, NULL, USYNC_THREAD, NULL);
5995	mutex_init(&ztest_vdev_lock, NULL, USYNC_THREAD, NULL);
5996	rw_init(&ztest_name_lock, NULL, USYNC_THREAD, NULL);
5997
5998	zs->zs_thread_start = gethrtime();
5999	zs->zs_thread_stop =
6000	    zs->zs_thread_start + ztest_opts.zo_passtime * NANOSEC;
6001	zs->zs_thread_stop = MIN(zs->zs_thread_stop, zs->zs_proc_stop);
6002	zs->zs_thread_kill = zs->zs_thread_stop;
6003	if (ztest_random(100) < ztest_opts.zo_killrate) {
6004		zs->zs_thread_kill -=
6005		    ztest_random(ztest_opts.zo_passtime * NANOSEC);
6006	}
6007
6008	mutex_init(&zcl.zcl_callbacks_lock, NULL, USYNC_THREAD, NULL);
6009
6010	list_create(&zcl.zcl_callbacks, sizeof (ztest_cb_data_t),
6011	    offsetof(ztest_cb_data_t, zcd_node));
6012
6013	/*
6014	 * Open our pool.
6015	 */
6016	kernel_init(FREAD | FWRITE);
6017	VERIFY0(spa_open(ztest_opts.zo_pool, &spa, FTAG));
6018	metaslab_preload_limit = ztest_random(20) + 1;
6019	ztest_spa = spa;
6020
6021	dmu_objset_stats_t dds;
6022	VERIFY0(dmu_objset_own(ztest_opts.zo_pool,
6023	    DMU_OST_ANY, B_TRUE, FTAG, &os));
6024	dsl_pool_config_enter(dmu_objset_pool(os), FTAG);
6025	dmu_objset_fast_stat(os, &dds);
6026	dsl_pool_config_exit(dmu_objset_pool(os), FTAG);
6027	zs->zs_guid = dds.dds_guid;
6028	dmu_objset_disown(os, FTAG);
6029
6030	spa->spa_dedup_ditto = 2 * ZIO_DEDUPDITTO_MIN;
6031
6032	/*
6033	 * We don't expect the pool to suspend unless maxfaults == 0,
6034	 * in which case ztest_fault_inject() temporarily takes away
6035	 * the only valid replica.
6036	 */
6037	if (MAXFAULTS() == 0)
6038		spa->spa_failmode = ZIO_FAILURE_MODE_WAIT;
6039	else
6040		spa->spa_failmode = ZIO_FAILURE_MODE_PANIC;
6041
6042	/*
6043	 * Create a thread to periodically resume suspended I/O.
6044	 */
6045	VERIFY(thr_create(0, 0, ztest_resume_thread, spa, THR_BOUND,
6046	    &resume_tid) == 0);
6047
6048	/*
6049	 * Create a deadman thread to abort() if we hang.
6050	 */
6051	VERIFY(thr_create(0, 0, ztest_deadman_thread, zs, THR_BOUND,
6052	    NULL) == 0);
6053
6054	/*
6055	 * Verify that we can safely inquire about any object,
6056	 * whether it's allocated or not.  To make it interesting,
6057	 * we probe a 5-wide window around each power of two.
6058	 * This hits all edge cases, including zero and the max.
6059	 */
6060	for (int t = 0; t < 64; t++) {
6061		for (int d = -5; d <= 5; d++) {
6062			error = dmu_object_info(spa->spa_meta_objset,
6063			    (1ULL << t) + d, NULL);
6064			ASSERT(error == 0 || error == ENOENT ||
6065			    error == EINVAL);
6066		}
6067	}
6068
6069	/*
6070	 * If we got any ENOSPC errors on the previous run, destroy something.
6071	 */
6072	if (zs->zs_enospc_count != 0) {
6073		int d = ztest_random(ztest_opts.zo_datasets);
6074		ztest_dataset_destroy(d);
6075	}
6076	zs->zs_enospc_count = 0;
6077
6078	tid = umem_zalloc(ztest_opts.zo_threads * sizeof (thread_t),
6079	    UMEM_NOFAIL);
6080
6081	if (ztest_opts.zo_verbose >= 4)
6082		(void) printf("starting main threads...\n");
6083
6084	/*
6085	 * Kick off all the tests that run in parallel.
6086	 */
6087	for (int t = 0; t < ztest_opts.zo_threads; t++) {
6088		if (t < ztest_opts.zo_datasets &&
6089		    ztest_dataset_open(t) != 0)
6090			return;
6091		VERIFY(thr_create(0, 0, ztest_thread, (void *)(uintptr_t)t,
6092		    THR_BOUND, &tid[t]) == 0);
6093	}
6094
6095	/*
6096	 * Wait for all of the tests to complete.  We go in reverse order
6097	 * so we don't close datasets while threads are still using them.
6098	 */
6099	for (int t = ztest_opts.zo_threads - 1; t >= 0; t--) {
6100		VERIFY(thr_join(tid[t], NULL, NULL) == 0);
6101		if (t < ztest_opts.zo_datasets)
6102			ztest_dataset_close(t);
6103	}
6104
6105	txg_wait_synced(spa_get_dsl(spa), 0);
6106
6107	zs->zs_alloc = metaslab_class_get_alloc(spa_normal_class(spa));
6108	zs->zs_space = metaslab_class_get_space(spa_normal_class(spa));
6109	zfs_dbgmsg_print(FTAG);
6110
6111	umem_free(tid, ztest_opts.zo_threads * sizeof (thread_t));
6112
6113	/* Kill the resume thread */
6114	ztest_exiting = B_TRUE;
6115	VERIFY(thr_join(resume_tid, NULL, NULL) == 0);
6116	ztest_resume(spa);
6117
6118	/*
6119	 * Right before closing the pool, kick off a bunch of async I/O;
6120	 * spa_close() should wait for it to complete.
6121	 */
6122	for (uint64_t object = 1; object < 50; object++) {
6123		dmu_prefetch(spa->spa_meta_objset, object, 0, 0, 1ULL << 20,
6124		    ZIO_PRIORITY_SYNC_READ);
6125	}
6126
6127	spa_close(spa, FTAG);
6128
6129	/*
6130	 * Verify that we can loop over all pools.
6131	 */
6132	mutex_enter(&spa_namespace_lock);
6133	for (spa = spa_next(NULL); spa != NULL; spa = spa_next(spa))
6134		if (ztest_opts.zo_verbose > 3)
6135			(void) printf("spa_next: found %s\n", spa_name(spa));
6136	mutex_exit(&spa_namespace_lock);
6137
6138	/*
6139	 * Verify that we can export the pool and reimport it under a
6140	 * different name.
6141	 */
6142	if (ztest_random(2) == 0) {
6143		char name[ZFS_MAX_DATASET_NAME_LEN];
6144		(void) snprintf(name, sizeof (name), "%s_import",
6145		    ztest_opts.zo_pool);
6146		ztest_spa_import_export(ztest_opts.zo_pool, name);
6147		ztest_spa_import_export(name, ztest_opts.zo_pool);
6148	}
6149
6150	kernel_fini();
6151
6152	list_destroy(&zcl.zcl_callbacks);
6153
6154	mutex_destroy(&zcl.zcl_callbacks_lock);
6155
6156	rw_destroy(&ztest_name_lock);
6157	mutex_destroy(&ztest_vdev_lock);
6158	mutex_destroy(&ztest_checkpoint_lock);
6159}
6160
6161static void
6162ztest_freeze(void)
6163{
6164	ztest_ds_t *zd = &ztest_ds[0];
6165	spa_t *spa;
6166	int numloops = 0;
6167
6168	if (ztest_opts.zo_verbose >= 3)
6169		(void) printf("testing spa_freeze()...\n");
6170
6171	kernel_init(FREAD | FWRITE);
6172	VERIFY3U(0, ==, spa_open(ztest_opts.zo_pool, &spa, FTAG));
6173	VERIFY3U(0, ==, ztest_dataset_open(0));
6174	ztest_spa = spa;
6175
6176	/*
6177	 * Force the first log block to be transactionally allocated.
6178	 * We have to do this before we freeze the pool -- otherwise
6179	 * the log chain won't be anchored.
6180	 */
6181	while (BP_IS_HOLE(&zd->zd_zilog->zl_header->zh_log)) {
6182		ztest_dmu_object_alloc_free(zd, 0);
6183		zil_commit(zd->zd_zilog, 0);
6184	}
6185
6186	txg_wait_synced(spa_get_dsl(spa), 0);
6187
6188	/*
6189	 * Freeze the pool.  This stops spa_sync() from doing anything,
6190	 * so that the only way to record changes from now on is the ZIL.
6191	 */
6192	spa_freeze(spa);
6193
6194	/*
6195	 * Because it is hard to predict how much space a write will actually
6196	 * require beforehand, we leave ourselves some fudge space to write over
6197	 * capacity.
6198	 */
6199	uint64_t capacity = metaslab_class_get_space(spa_normal_class(spa)) / 2;
6200
6201	/*
6202	 * Run tests that generate log records but don't alter the pool config
6203	 * or depend on DSL sync tasks (snapshots, objset create/destroy, etc).
6204	 * We do a txg_wait_synced() after each iteration to force the txg
6205	 * to increase well beyond the last synced value in the uberblock.
6206	 * The ZIL should be OK with that.
6207	 *
6208	 * Run a random number of times less than zo_maxloops and ensure we do
6209	 * not run out of space on the pool.
6210	 */
6211	while (ztest_random(10) != 0 &&
6212	    numloops++ < ztest_opts.zo_maxloops &&
6213	    metaslab_class_get_alloc(spa_normal_class(spa)) < capacity) {
6214		ztest_od_t od;
6215		ztest_od_init(&od, 0, FTAG, 0, DMU_OT_UINT64_OTHER, 0, 0);
6216		VERIFY0(ztest_object_init(zd, &od, sizeof (od), B_FALSE));
6217		ztest_io(zd, od.od_object,
6218		    ztest_random(ZTEST_RANGE_LOCKS) << SPA_MAXBLOCKSHIFT);
6219		txg_wait_synced(spa_get_dsl(spa), 0);
6220	}
6221
6222	/*
6223	 * Commit all of the changes we just generated.
6224	 */
6225	zil_commit(zd->zd_zilog, 0);
6226	txg_wait_synced(spa_get_dsl(spa), 0);
6227
6228	/*
6229	 * Close our dataset and close the pool.
6230	 */
6231	ztest_dataset_close(0);
6232	spa_close(spa, FTAG);
6233	kernel_fini();
6234
6235	/*
6236	 * Open and close the pool and dataset to induce log replay.
6237	 */
6238	kernel_init(FREAD | FWRITE);
6239	VERIFY3U(0, ==, spa_open(ztest_opts.zo_pool, &spa, FTAG));
6240	ASSERT(spa_freeze_txg(spa) == UINT64_MAX);
6241	VERIFY3U(0, ==, ztest_dataset_open(0));
6242	ztest_dataset_close(0);
6243
6244	ztest_spa = spa;
6245	txg_wait_synced(spa_get_dsl(spa), 0);
6246	ztest_reguid(NULL, 0);
6247
6248	spa_close(spa, FTAG);
6249	kernel_fini();
6250}
6251
6252void
6253print_time(hrtime_t t, char *timebuf)
6254{
6255	hrtime_t s = t / NANOSEC;
6256	hrtime_t m = s / 60;
6257	hrtime_t h = m / 60;
6258	hrtime_t d = h / 24;
6259
6260	s -= m * 60;
6261	m -= h * 60;
6262	h -= d * 24;
6263
6264	timebuf[0] = '\0';
6265
6266	if (d)
6267		(void) sprintf(timebuf,
6268		    "%llud%02lluh%02llum%02llus", d, h, m, s);
6269	else if (h)
6270		(void) sprintf(timebuf, "%lluh%02llum%02llus", h, m, s);
6271	else if (m)
6272		(void) sprintf(timebuf, "%llum%02llus", m, s);
6273	else
6274		(void) sprintf(timebuf, "%llus", s);
6275}
6276
6277static nvlist_t *
6278make_random_props()
6279{
6280	nvlist_t *props;
6281
6282	VERIFY(nvlist_alloc(&props, NV_UNIQUE_NAME, 0) == 0);
6283	if (ztest_random(2) == 0)
6284		return (props);
6285	VERIFY(nvlist_add_uint64(props, "autoreplace", 1) == 0);
6286
6287	return (props);
6288}
6289
6290/*
6291 * Create a storage pool with the given name and initial vdev size.
6292 * Then test spa_freeze() functionality.
6293 */
6294static void
6295ztest_init(ztest_shared_t *zs)
6296{
6297	spa_t *spa;
6298	nvlist_t *nvroot, *props;
6299
6300	mutex_init(&ztest_vdev_lock, NULL, USYNC_THREAD, NULL);
6301	mutex_init(&ztest_checkpoint_lock, NULL, USYNC_THREAD, NULL);
6302	rw_init(&ztest_name_lock, NULL, USYNC_THREAD, NULL);
6303
6304	kernel_init(FREAD | FWRITE);
6305
6306	/*
6307	 * Create the storage pool.
6308	 */
6309	(void) spa_destroy(ztest_opts.zo_pool);
6310	ztest_shared->zs_vdev_next_leaf = 0;
6311	zs->zs_splits = 0;
6312	zs->zs_mirrors = ztest_opts.zo_mirrors;
6313	nvroot = make_vdev_root(NULL, NULL, NULL, ztest_opts.zo_vdev_size, 0,
6314	    0, ztest_opts.zo_raidz, zs->zs_mirrors, 1);
6315	props = make_random_props();
6316	for (int i = 0; i < SPA_FEATURES; i++) {
6317		char buf[1024];
6318		(void) snprintf(buf, sizeof (buf), "feature@%s",
6319		    spa_feature_table[i].fi_uname);
6320		VERIFY3U(0, ==, nvlist_add_uint64(props, buf, 0));
6321	}
6322	VERIFY3U(0, ==, spa_create(ztest_opts.zo_pool, nvroot, props, NULL));
6323	nvlist_free(nvroot);
6324	nvlist_free(props);
6325
6326	VERIFY3U(0, ==, spa_open(ztest_opts.zo_pool, &spa, FTAG));
6327	zs->zs_metaslab_sz =
6328	    1ULL << spa->spa_root_vdev->vdev_child[0]->vdev_ms_shift;
6329
6330	spa_close(spa, FTAG);
6331
6332	kernel_fini();
6333
6334	ztest_run_zdb(ztest_opts.zo_pool);
6335
6336	ztest_freeze();
6337
6338	ztest_run_zdb(ztest_opts.zo_pool);
6339
6340	rw_destroy(&ztest_name_lock);
6341	mutex_destroy(&ztest_vdev_lock);
6342	mutex_destroy(&ztest_checkpoint_lock);
6343}
6344
6345static void
6346setup_data_fd(void)
6347{
6348	static char ztest_name_data[] = "/tmp/ztest.data.XXXXXX";
6349
6350	ztest_fd_data = mkstemp(ztest_name_data);
6351	ASSERT3S(ztest_fd_data, >=, 0);
6352	(void) unlink(ztest_name_data);
6353}
6354
6355
6356static int
6357shared_data_size(ztest_shared_hdr_t *hdr)
6358{
6359	int size;
6360
6361	size = hdr->zh_hdr_size;
6362	size += hdr->zh_opts_size;
6363	size += hdr->zh_size;
6364	size += hdr->zh_stats_size * hdr->zh_stats_count;
6365	size += hdr->zh_ds_size * hdr->zh_ds_count;
6366
6367	return (size);
6368}
6369
6370static void
6371setup_hdr(void)
6372{
6373	int size;
6374	ztest_shared_hdr_t *hdr;
6375
6376	hdr = (void *)mmap(0, P2ROUNDUP(sizeof (*hdr), getpagesize()),
6377	    PROT_READ | PROT_WRITE, MAP_SHARED, ztest_fd_data, 0);
6378	ASSERT(hdr != MAP_FAILED);
6379
6380	VERIFY3U(0, ==, ftruncate(ztest_fd_data, sizeof (ztest_shared_hdr_t)));
6381
6382	hdr->zh_hdr_size = sizeof (ztest_shared_hdr_t);
6383	hdr->zh_opts_size = sizeof (ztest_shared_opts_t);
6384	hdr->zh_size = sizeof (ztest_shared_t);
6385	hdr->zh_stats_size = sizeof (ztest_shared_callstate_t);
6386	hdr->zh_stats_count = ZTEST_FUNCS;
6387	hdr->zh_ds_size = sizeof (ztest_shared_ds_t);
6388	hdr->zh_ds_count = ztest_opts.zo_datasets;
6389
6390	size = shared_data_size(hdr);
6391	VERIFY3U(0, ==, ftruncate(ztest_fd_data, size));
6392
6393	(void) munmap((caddr_t)hdr, P2ROUNDUP(sizeof (*hdr), getpagesize()));
6394}
6395
6396static void
6397setup_data(void)
6398{
6399	int size, offset;
6400	ztest_shared_hdr_t *hdr;
6401	uint8_t *buf;
6402
6403	hdr = (void *)mmap(0, P2ROUNDUP(sizeof (*hdr), getpagesize()),
6404	    PROT_READ, MAP_SHARED, ztest_fd_data, 0);
6405	ASSERT(hdr != MAP_FAILED);
6406
6407	size = shared_data_size(hdr);
6408
6409	(void) munmap((caddr_t)hdr, P2ROUNDUP(sizeof (*hdr), getpagesize()));
6410	hdr = ztest_shared_hdr = (void *)mmap(0, P2ROUNDUP(size, getpagesize()),
6411	    PROT_READ | PROT_WRITE, MAP_SHARED, ztest_fd_data, 0);
6412	ASSERT(hdr != MAP_FAILED);
6413	buf = (uint8_t *)hdr;
6414
6415	offset = hdr->zh_hdr_size;
6416	ztest_shared_opts = (void *)&buf[offset];
6417	offset += hdr->zh_opts_size;
6418	ztest_shared = (void *)&buf[offset];
6419	offset += hdr->zh_size;
6420	ztest_shared_callstate = (void *)&buf[offset];
6421	offset += hdr->zh_stats_size * hdr->zh_stats_count;
6422	ztest_shared_ds = (void *)&buf[offset];
6423}
6424
6425static boolean_t
6426exec_child(char *cmd, char *libpath, boolean_t ignorekill, int *statusp)
6427{
6428	pid_t pid;
6429	int status;
6430	char *cmdbuf = NULL;
6431
6432	pid = fork();
6433
6434	if (cmd == NULL) {
6435		cmdbuf = umem_alloc(MAXPATHLEN, UMEM_NOFAIL);
6436		(void) strlcpy(cmdbuf, getexecname(), MAXPATHLEN);
6437		cmd = cmdbuf;
6438	}
6439
6440	if (pid == -1)
6441		fatal(1, "fork failed");
6442
6443	if (pid == 0) {	/* child */
6444		char *emptyargv[2] = { cmd, NULL };
6445		char fd_data_str[12];
6446
6447		struct rlimit rl = { 1024, 1024 };
6448		(void) setrlimit(RLIMIT_NOFILE, &rl);
6449
6450		(void) close(ztest_fd_rand);
6451		VERIFY3U(11, >=,
6452		    snprintf(fd_data_str, 12, "%d", ztest_fd_data));
6453		VERIFY0(setenv("ZTEST_FD_DATA", fd_data_str, 1));
6454
6455		(void) enable_extended_FILE_stdio(-1, -1);
6456		if (libpath != NULL)
6457			VERIFY(0 == setenv("LD_LIBRARY_PATH", libpath, 1));
6458#ifdef illumos
6459		(void) execv(cmd, emptyargv);
6460#else
6461		(void) execvp(cmd, emptyargv);
6462#endif
6463		ztest_dump_core = B_FALSE;
6464		fatal(B_TRUE, "exec failed: %s", cmd);
6465	}
6466
6467	if (cmdbuf != NULL) {
6468		umem_free(cmdbuf, MAXPATHLEN);
6469		cmd = NULL;
6470	}
6471
6472	while (waitpid(pid, &status, 0) != pid)
6473		continue;
6474	if (statusp != NULL)
6475		*statusp = status;
6476
6477	if (WIFEXITED(status)) {
6478		if (WEXITSTATUS(status) != 0) {
6479			(void) fprintf(stderr, "child exited with code %d\n",
6480			    WEXITSTATUS(status));
6481			exit(2);
6482		}
6483		return (B_FALSE);
6484	} else if (WIFSIGNALED(status)) {
6485		if (!ignorekill || WTERMSIG(status) != SIGKILL) {
6486			(void) fprintf(stderr, "child died with signal %d\n",
6487			    WTERMSIG(status));
6488			exit(3);
6489		}
6490		return (B_TRUE);
6491	} else {
6492		(void) fprintf(stderr, "something strange happened to child\n");
6493		exit(4);
6494		/* NOTREACHED */
6495	}
6496}
6497
6498static void
6499ztest_run_init(void)
6500{
6501	ztest_shared_t *zs = ztest_shared;
6502
6503	ASSERT(ztest_opts.zo_init != 0);
6504
6505	/*
6506	 * Blow away any existing copy of zpool.cache
6507	 */
6508	(void) remove(spa_config_path);
6509
6510	/*
6511	 * Create and initialize our storage pool.
6512	 */
6513	for (int i = 1; i <= ztest_opts.zo_init; i++) {
6514		bzero(zs, sizeof (ztest_shared_t));
6515		if (ztest_opts.zo_verbose >= 3 &&
6516		    ztest_opts.zo_init != 1) {
6517			(void) printf("ztest_init(), pass %d\n", i);
6518		}
6519		ztest_init(zs);
6520	}
6521}
6522
6523int
6524main(int argc, char **argv)
6525{
6526	int kills = 0;
6527	int iters = 0;
6528	int older = 0;
6529	int newer = 0;
6530	ztest_shared_t *zs;
6531	ztest_info_t *zi;
6532	ztest_shared_callstate_t *zc;
6533	char timebuf[100];
6534	char numbuf[NN_NUMBUF_SZ];
6535	spa_t *spa;
6536	char *cmd;
6537	boolean_t hasalt;
6538	char *fd_data_str = getenv("ZTEST_FD_DATA");
6539
6540	(void) setvbuf(stdout, NULL, _IOLBF, 0);
6541
6542	dprintf_setup(&argc, argv);
6543	zfs_deadman_synctime_ms = 300000;
6544	/*
6545	 * As two-word space map entries may not come up often (especially
6546	 * if pool and vdev sizes are small) we want to force at least some
6547	 * of them so the feature get tested.
6548	 */
6549	zfs_force_some_double_word_sm_entries = B_TRUE;
6550
6551	ztest_fd_rand = open("/dev/urandom", O_RDONLY);
6552	ASSERT3S(ztest_fd_rand, >=, 0);
6553
6554	if (!fd_data_str) {
6555		process_options(argc, argv);
6556
6557		setup_data_fd();
6558		setup_hdr();
6559		setup_data();
6560		bcopy(&ztest_opts, ztest_shared_opts,
6561		    sizeof (*ztest_shared_opts));
6562	} else {
6563		ztest_fd_data = atoi(fd_data_str);
6564		setup_data();
6565		bcopy(ztest_shared_opts, &ztest_opts, sizeof (ztest_opts));
6566	}
6567	ASSERT3U(ztest_opts.zo_datasets, ==, ztest_shared_hdr->zh_ds_count);
6568
6569	/* Override location of zpool.cache */
6570	VERIFY3U(asprintf((char **)&spa_config_path, "%s/zpool.cache",
6571	    ztest_opts.zo_dir), !=, -1);
6572
6573	ztest_ds = umem_alloc(ztest_opts.zo_datasets * sizeof (ztest_ds_t),
6574	    UMEM_NOFAIL);
6575	zs = ztest_shared;
6576
6577	if (fd_data_str) {
6578		metaslab_force_ganging = ztest_opts.zo_metaslab_force_ganging;
6579		metaslab_df_alloc_threshold =
6580		    zs->zs_metaslab_df_alloc_threshold;
6581
6582		if (zs->zs_do_init)
6583			ztest_run_init();
6584		else
6585			ztest_run(zs);
6586		exit(0);
6587	}
6588
6589	hasalt = (strlen(ztest_opts.zo_alt_ztest) != 0);
6590
6591	if (ztest_opts.zo_verbose >= 1) {
6592		(void) printf("%llu vdevs, %d datasets, %d threads,"
6593		    " %llu seconds...\n",
6594		    (u_longlong_t)ztest_opts.zo_vdevs,
6595		    ztest_opts.zo_datasets,
6596		    ztest_opts.zo_threads,
6597		    (u_longlong_t)ztest_opts.zo_time);
6598	}
6599
6600	cmd = umem_alloc(MAXNAMELEN, UMEM_NOFAIL);
6601	(void) strlcpy(cmd, getexecname(), MAXNAMELEN);
6602
6603	zs->zs_do_init = B_TRUE;
6604	if (strlen(ztest_opts.zo_alt_ztest) != 0) {
6605		if (ztest_opts.zo_verbose >= 1) {
6606			(void) printf("Executing older ztest for "
6607			    "initialization: %s\n", ztest_opts.zo_alt_ztest);
6608		}
6609		VERIFY(!exec_child(ztest_opts.zo_alt_ztest,
6610		    ztest_opts.zo_alt_libpath, B_FALSE, NULL));
6611	} else {
6612		VERIFY(!exec_child(NULL, NULL, B_FALSE, NULL));
6613	}
6614	zs->zs_do_init = B_FALSE;
6615
6616	zs->zs_proc_start = gethrtime();
6617	zs->zs_proc_stop = zs->zs_proc_start + ztest_opts.zo_time * NANOSEC;
6618
6619	for (int f = 0; f < ZTEST_FUNCS; f++) {
6620		zi = &ztest_info[f];
6621		zc = ZTEST_GET_SHARED_CALLSTATE(f);
6622		if (zs->zs_proc_start + zi->zi_interval[0] > zs->zs_proc_stop)
6623			zc->zc_next = UINT64_MAX;
6624		else
6625			zc->zc_next = zs->zs_proc_start +
6626			    ztest_random(2 * zi->zi_interval[0] + 1);
6627	}
6628
6629	/*
6630	 * Run the tests in a loop.  These tests include fault injection
6631	 * to verify that self-healing data works, and forced crashes
6632	 * to verify that we never lose on-disk consistency.
6633	 */
6634	while (gethrtime() < zs->zs_proc_stop) {
6635		int status;
6636		boolean_t killed;
6637
6638		/*
6639		 * Initialize the workload counters for each function.
6640		 */
6641		for (int f = 0; f < ZTEST_FUNCS; f++) {
6642			zc = ZTEST_GET_SHARED_CALLSTATE(f);
6643			zc->zc_count = 0;
6644			zc->zc_time = 0;
6645		}
6646
6647		/* Set the allocation switch size */
6648		zs->zs_metaslab_df_alloc_threshold =
6649		    ztest_random(zs->zs_metaslab_sz / 4) + 1;
6650
6651		if (!hasalt || ztest_random(2) == 0) {
6652			if (hasalt && ztest_opts.zo_verbose >= 1) {
6653				(void) printf("Executing newer ztest: %s\n",
6654				    cmd);
6655			}
6656			newer++;
6657			killed = exec_child(cmd, NULL, B_TRUE, &status);
6658		} else {
6659			if (hasalt && ztest_opts.zo_verbose >= 1) {
6660				(void) printf("Executing older ztest: %s\n",
6661				    ztest_opts.zo_alt_ztest);
6662			}
6663			older++;
6664			killed = exec_child(ztest_opts.zo_alt_ztest,
6665			    ztest_opts.zo_alt_libpath, B_TRUE, &status);
6666		}
6667
6668		if (killed)
6669			kills++;
6670		iters++;
6671
6672		if (ztest_opts.zo_verbose >= 1) {
6673			hrtime_t now = gethrtime();
6674
6675			now = MIN(now, zs->zs_proc_stop);
6676			print_time(zs->zs_proc_stop - now, timebuf);
6677			nicenum(zs->zs_space, numbuf, sizeof (numbuf));
6678
6679			(void) printf("Pass %3d, %8s, %3llu ENOSPC, "
6680			    "%4.1f%% of %5s used, %3.0f%% done, %8s to go\n",
6681			    iters,
6682			    WIFEXITED(status) ? "Complete" : "SIGKILL",
6683			    (u_longlong_t)zs->zs_enospc_count,
6684			    100.0 * zs->zs_alloc / zs->zs_space,
6685			    numbuf,
6686			    100.0 * (now - zs->zs_proc_start) /
6687			    (ztest_opts.zo_time * NANOSEC), timebuf);
6688		}
6689
6690		if (ztest_opts.zo_verbose >= 2) {
6691			(void) printf("\nWorkload summary:\n\n");
6692			(void) printf("%7s %9s   %s\n",
6693			    "Calls", "Time", "Function");
6694			(void) printf("%7s %9s   %s\n",
6695			    "-----", "----", "--------");
6696			for (int f = 0; f < ZTEST_FUNCS; f++) {
6697				Dl_info dli;
6698
6699				zi = &ztest_info[f];
6700				zc = ZTEST_GET_SHARED_CALLSTATE(f);
6701				print_time(zc->zc_time, timebuf);
6702				(void) dladdr((void *)zi->zi_func, &dli);
6703				(void) printf("%7llu %9s   %s\n",
6704				    (u_longlong_t)zc->zc_count, timebuf,
6705				    dli.dli_sname);
6706			}
6707			(void) printf("\n");
6708		}
6709
6710		/*
6711		 * It's possible that we killed a child during a rename test,
6712		 * in which case we'll have a 'ztest_tmp' pool lying around
6713		 * instead of 'ztest'.  Do a blind rename in case this happened.
6714		 */
6715		kernel_init(FREAD);
6716		if (spa_open(ztest_opts.zo_pool, &spa, FTAG) == 0) {
6717			spa_close(spa, FTAG);
6718		} else {
6719			char tmpname[ZFS_MAX_DATASET_NAME_LEN];
6720			kernel_fini();
6721			kernel_init(FREAD | FWRITE);
6722			(void) snprintf(tmpname, sizeof (tmpname), "%s_tmp",
6723			    ztest_opts.zo_pool);
6724			(void) spa_rename(tmpname, ztest_opts.zo_pool);
6725		}
6726		kernel_fini();
6727
6728		ztest_run_zdb(ztest_opts.zo_pool);
6729	}
6730
6731	if (ztest_opts.zo_verbose >= 1) {
6732		if (hasalt) {
6733			(void) printf("%d runs of older ztest: %s\n", older,
6734			    ztest_opts.zo_alt_ztest);
6735			(void) printf("%d runs of newer ztest: %s\n", newer,
6736			    cmd);
6737		}
6738		(void) printf("%d killed, %d completed, %.0f%% kill rate\n",
6739		    kills, iters - kills, (100.0 * kills) / MAX(1, iters));
6740	}
6741
6742	umem_free(cmd, MAXNAMELEN);
6743
6744	return (0);
6745}
6746