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