xref: /illumos-gate/usr/src/cmd/ztest/ztest.c (revision d8ab6e12)
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 <libzutil.h>
132 #include <libcmdutils.h>
133 
134 static int ztest_fd_data = -1;
135 static int ztest_fd_rand = -1;
136 
137 typedef 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 
147 static ztest_shared_hdr_t *ztest_shared_hdr;
148 
149 enum ztest_class_state {
150 	ZTEST_VDEV_CLASS_OFF,
151 	ZTEST_VDEV_CLASS_ON,
152 	ZTEST_VDEV_CLASS_RND
153 };
154 
155 typedef 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 
180 static 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 
204 extern uint64_t metaslab_force_ganging;
205 extern uint64_t metaslab_df_alloc_threshold;
206 extern uint64_t zfs_deadman_synctime_ms;
207 extern int metaslab_preload_limit;
208 extern boolean_t zfs_compressed_arc_enabled;
209 extern boolean_t zfs_abd_scatter_enabled;
210 extern int dmu_object_alloc_chunk_shift;
211 extern boolean_t zfs_force_some_double_word_sm_entries;
212 extern unsigned long zfs_reconstruct_indirect_damage_fraction;
213 
214 static ztest_shared_opts_t *ztest_shared_opts;
215 static ztest_shared_opts_t ztest_opts;
216 static char *ztest_wkeydata = "abcdefghijklmnopqrstuvwxyz012345";
217 
218 typedef struct ztest_shared_ds {
219 	uint64_t	zd_seq;
220 } ztest_shared_ds_t;
221 
222 static 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 
229 enum 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 
239 typedef 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 
250 typedef 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  */
261 typedef enum {
262 	RL_READER,
263 	RL_WRITER,
264 	RL_APPEND
265 } rl_type_t;
266 
267 typedef struct rll {
268 	void		*rll_writer;
269 	int		rll_readers;
270 	kmutex_t	rll_lock;
271 	kcondvar_t	rll_cv;
272 } rll_t;
273 
274 typedef 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  */
287 typedef 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  */
303 typedef 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  */
318 typedef void ztest_func_t(ztest_ds_t *zd, uint64_t id);
319 
320 typedef 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 
326 typedef 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 
332 static 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  */
338 ztest_func_t ztest_dmu_read_write;
339 ztest_func_t ztest_dmu_write_parallel;
340 ztest_func_t ztest_dmu_object_alloc_free;
341 ztest_func_t ztest_dmu_object_next_chunk;
342 ztest_func_t ztest_dmu_commit_callbacks;
343 ztest_func_t ztest_zap;
344 ztest_func_t ztest_zap_parallel;
345 ztest_func_t ztest_zil_commit;
346 ztest_func_t ztest_zil_remount;
347 ztest_func_t ztest_dmu_read_write_zcopy;
348 ztest_func_t ztest_dmu_objset_create_destroy;
349 ztest_func_t ztest_dmu_prealloc;
350 ztest_func_t ztest_fzap;
351 ztest_func_t ztest_dmu_snapshot_create_destroy;
352 ztest_func_t ztest_dsl_prop_get_set;
353 ztest_func_t ztest_spa_prop_get_set;
354 ztest_func_t ztest_spa_create_destroy;
355 ztest_func_t ztest_fault_inject;
356 ztest_func_t ztest_ddt_repair;
357 ztest_func_t ztest_dmu_snapshot_hold;
358 ztest_func_t ztest_mmp_enable_disable;
359 ztest_func_t ztest_scrub;
360 ztest_func_t ztest_dsl_dataset_promote_busy;
361 ztest_func_t ztest_vdev_attach_detach;
362 ztest_func_t ztest_vdev_LUN_growth;
363 ztest_func_t ztest_vdev_add_remove;
364 ztest_func_t ztest_vdev_class_add;
365 ztest_func_t ztest_vdev_aux_add_remove;
366 ztest_func_t ztest_split_pool;
367 ztest_func_t ztest_reguid;
368 ztest_func_t ztest_spa_upgrade;
369 ztest_func_t ztest_device_removal;
370 ztest_func_t ztest_remap_blocks;
371 ztest_func_t ztest_spa_checkpoint_create_discard;
372 ztest_func_t ztest_initialize;
373 ztest_func_t ztest_trim;
374 ztest_func_t ztest_verify_dnode_bt;
375 
376 uint64_t zopt_always = 0ULL * NANOSEC;		/* all the time */
377 uint64_t zopt_incessant = 1ULL * NANOSEC / 10;	/* every 1/10 second */
378 uint64_t zopt_often = 1ULL * NANOSEC;		/* every second */
379 uint64_t zopt_sometimes = 10ULL * NANOSEC;	/* every 10 seconds */
380 uint64_t zopt_rarely = 60ULL * NANOSEC;		/* every 60 seconds */
381 
382 ztest_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  */
433 typedef 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  */
441 typedef 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 
462 static char ztest_dev_template[] = "%s/%s.%llua";
463 static char ztest_aux_template[] = "%s/%s.%s.%llu";
464 ztest_shared_t *ztest_shared;
465 
466 static spa_t *ztest_spa = NULL;
467 static ztest_ds_t *ztest_ds;
468 
469 static kmutex_t ztest_vdev_lock;
470 static boolean_t ztest_device_removal_active = B_FALSE;
471 static 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  */
479 static krwlock_t ztest_name_lock;
480 
481 static boolean_t ztest_dump_core = B_TRUE;
482 static boolean_t ztest_exiting;
483 
484 /* Global commit callback list */
485 static ztest_cb_list_t zcl;
486 
487 enum ztest_object {
488 	ZTEST_META_DNODE = 0,
489 	ZTEST_DIROBJ,
490 	ZTEST_OBJECTS
491 };
492 
493 static 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  */
499 const char *
_umem_debug_init()500 _umem_debug_init()
501 {
502 	return ("default,verbose"); /* $UMEM_DEBUG setting */
503 }
504 
505 const char *
_umem_logging_init(void)506 _umem_logging_init(void)
507 {
508 	return ("fail,contents"); /* $UMEM_LOGGING setting */
509 }
510 
511 #define	FATAL_MSG_SZ	1024
512 
513 char *fatal_msg;
514 
515 static void
fatal(int do_perror,char * message,...)516 fatal(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 
540 static int
str2shift(const char * buf)541 str2shift(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 
565 static uint64_t
nicenumtoull(const char * buf)566 nicenumtoull(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 
596 static void
usage(boolean_t requested)597 usage(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 
656 static void
ztest_parse_name_value(const char * input,ztest_shared_opts_t * zo)657 ztest_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 
695 static void
process_options(int argc,char ** argv)696 process_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 
869 static void
ztest_kill(ztest_shared_t * zs)870 ztest_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 
887 static uint64_t
ztest_random(uint64_t range)888 ztest_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 */
904 static void
ztest_record_enospc(const char * s)905 ztest_record_enospc(const char *s)
906 {
907 	ztest_shared->zs_enospc_count++;
908 }
909 
910 static uint64_t
ztest_get_ashift(void)911 ztest_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 
918 static nvlist_t *
make_vdev_file(char * path,char * aux,char * pool,size_t size,uint64_t ashift)919 make_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 
962 static nvlist_t *
make_vdev_raidz(char * path,char * aux,char * pool,size_t size,uint64_t ashift,int r)963 make_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 
992 static nvlist_t *
make_vdev_mirror(char * path,char * aux,char * pool,size_t size,uint64_t ashift,int r,int m)993 make_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 
1021 static nvlist_t *
make_vdev_root(char * path,char * aux,char * pool,size_t size,uint64_t ashift,const char * class,int r,int m,int t)1022 make_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  */
1065 static uint64_t
ztest_random_spa_version(uint64_t initial_version)1066 ztest_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 
1082 static int
ztest_random_blocksize(void)1083 ztest_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 
1100 static int
ztest_random_dnodesize(void)1101 ztest_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 
1130 static int
ztest_random_ibshift(void)1131 ztest_random_ibshift(void)
1132 {
1133 	return (DN_MIN_INDBLKSHIFT +
1134 	    ztest_random(DN_MAX_INDBLKSHIFT - DN_MIN_INDBLKSHIFT + 1));
1135 }
1136 
1137 static uint64_t
ztest_random_vdev_top(spa_t * spa,boolean_t log_ok)1138 ztest_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 
1155 static uint64_t
ztest_random_dsl_prop(zfs_prop_t prop)1156 ztest_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 
1167 static int
ztest_dsl_prop_set_uint64(char * osname,zfs_prop_t prop,uint64_t value,boolean_t inherit)1168 ztest_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 
1197 static int
ztest_spa_prop_set_uint64(zpool_prop_t prop,uint64_t value)1198 ztest_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 
1220 static int
ztest_dmu_objset_own(const char * name,dmu_objset_type_t type,boolean_t readonly,boolean_t decrypt,void * tag,objset_t ** osp)1221 ztest_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 
1256 static void
ztest_rll_init(rll_t * rll)1257 ztest_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 
1265 static void
ztest_rll_destroy(rll_t * rll)1266 ztest_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 
1274 static void
ztest_rll_lock(rll_t * rll,rl_type_t type)1275 ztest_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 
1292 static void
ztest_rll_unlock(rll_t * rll)1293 ztest_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 
1312 static void
ztest_object_lock(ztest_ds_t * zd,uint64_t object,rl_type_t type)1313 ztest_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 
1320 static void
ztest_object_unlock(ztest_ds_t * zd,uint64_t object)1321 ztest_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 
1328 static rl_t *
ztest_range_lock(ztest_ds_t * zd,uint64_t object,uint64_t offset,uint64_t size,rl_type_t type)1329 ztest_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 
1347 static void
ztest_range_unlock(rl_t * rl)1348 ztest_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 
1357 static void
ztest_zd_init(ztest_ds_t * zd,ztest_shared_ds_t * szd,objset_t * os)1358 ztest_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 
1378 static void
ztest_zd_fini(ztest_ds_t * zd)1379 ztest_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 
1392 static uint64_t
ztest_tx_assign(dmu_tx_t * tx,uint64_t txg_how,const char * tag)1393 ztest_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 
1418 static void
ztest_pattern_set(void * buf,uint64_t size,uint64_t value)1419 ztest_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 
1428 static boolean_t
ztest_pattern_match(void * buf,uint64_t size,uint64_t value)1429 ztest_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 
1441 static void
ztest_bt_generate(ztest_block_tag_t * bt,objset_t * os,uint64_t object,uint64_t dnodesize,uint64_t offset,uint64_t gen,uint64_t txg,uint64_t crtxg)1442 ztest_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 
1456 static void
ztest_bt_verify(ztest_block_tag_t * bt,objset_t * os,uint64_t object,uint64_t dnodesize,uint64_t offset,uint64_t gen,uint64_t txg,uint64_t crtxg)1457 ztest_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 
1471 static ztest_block_tag_t *
ztest_bt_bonus(dmu_buf_t * db)1472 ztest_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  */
1499 void
ztest_fill_unused_bonus(dmu_buf_t * db,void * end,uint64_t obj,objset_t * os,uint64_t gen)1500 ztest_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  */
1518 void
ztest_verify_unused_bonus(dmu_buf_t * db,void * end,uint64_t obj,objset_t * os,uint64_t gen)1519 ztest_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 
1541 static void
ztest_log_create(ztest_ds_t * zd,dmu_tx_t * tx,lr_create_t * lr)1542 ztest_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 
1558 static void
ztest_log_remove(ztest_ds_t * zd,dmu_tx_t * tx,lr_remove_t * lr,uint64_t object)1559 ztest_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 
1576 static void
ztest_log_write(ztest_ds_t * zd,dmu_tx_t * tx,lr_write_t * lr)1577 ztest_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 
1608 static void
ztest_log_truncate(ztest_ds_t * zd,dmu_tx_t * tx,lr_truncate_t * lr)1609 ztest_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 
1624 static void
ztest_log_setattr(ztest_ds_t * zd,dmu_tx_t * tx,lr_setattr_t * lr)1625 ztest_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  */
1643 static int
ztest_replay_create(void * arg1,void * arg2,boolean_t byteswap)1644 ztest_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 
1733 static int
ztest_replay_remove(void * arg1,void * arg2,boolean_t byteswap)1734 ztest_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 
1786 static int
ztest_replay_write(void * arg1,void * arg2,boolean_t byteswap)1787 ztest_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 
1914 static int
ztest_replay_truncate(void * arg1,void * arg2,boolean_t byteswap)1915 ztest_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 
1955 static int
ztest_replay_setattr(void * arg1,void * arg2,boolean_t byteswap)1956 ztest_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 
2031 zil_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 */
2059 static void
ztest_get_done(zgd_t * zgd,int error)2060 ztest_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 
2074 static int
ztest_get_data(void * arg,lr_write_t * lr,char * buf,struct lwb * lwb,zio_t * zio)2075 ztest_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 
2161 static void *
ztest_lr_alloc(size_t lrsize,char * name)2162 ztest_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 
2175 void
ztest_lr_free(void * lr,size_t lrsize,char * name)2176 ztest_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  */
2186 static int
ztest_lookup(ztest_ds_t * zd,ztest_od_t * od,int count)2187 ztest_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 
2227 static int
ztest_create(ztest_ds_t * zd,ztest_od_t * od,int count)2228 ztest_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 
2271 static int
ztest_remove(ztest_ds_t * zd,ztest_od_t * od,int count)2272 ztest_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 
2309 static int
ztest_write(ztest_ds_t * zd,uint64_t object,uint64_t offset,uint64_t size,void * data)2310 ztest_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 
2333 static int
ztest_truncate(ztest_ds_t * zd,uint64_t object,uint64_t offset,uint64_t size)2334 ztest_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 
2352 static int
ztest_setattr(ztest_ds_t * zd,uint64_t object)2353 ztest_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 
2371 static void
ztest_prealloc(ztest_ds_t * zd,uint64_t object,uint64_t offset,uint64_t size)2372 ztest_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 
2402 static void
ztest_io(ztest_ds_t * zd,uint64_t object,uint64_t offset)2403 ztest_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  */
2488 static void
ztest_od_init(ztest_od_t * od,uint64_t id,char * tag,uint64_t index,dmu_object_type_t type,uint64_t blocksize,uint64_t dnodesize,uint64_t gen)2489 ztest_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  */
2515 static int
ztest_object_init(ztest_ds_t * zd,ztest_od_t * od,size_t size,boolean_t remove)2516 ztest_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 */
2533 void
ztest_zil_commit(ztest_ds_t * zd,uint64_t id)2534 ztest_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 */
2562 void
ztest_zil_remount(ztest_ds_t * zd,uint64_t id)2563 ztest_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 */
2591 void
ztest_spa_create_destroy(ztest_ds_t * zd,uint64_t id)2592 ztest_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 */
2638 void
ztest_mmp_enable_disable(ztest_ds_t * zd,uint64_t id)2639 ztest_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 */
2684 void
ztest_spa_upgrade(ztest_ds_t * zd,uint64_t id)2685 ztest_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 
2758 static void
ztest_spa_checkpoint(spa_t * spa)2759 ztest_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 
2779 static void
ztest_spa_discard_checkpoint(spa_t * spa)2780 ztest_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 */
2799 void
ztest_spa_checkpoint_create_discard(ztest_ds_t * zd,uint64_t id)2800 ztest_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 
2814 static vdev_t *
vdev_lookup_by_path(vdev_t * vd,const char * path)2815 vdev_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 
2830 static int
spa_num_top_vdevs(spa_t * spa)2831 spa_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 */
2842 void
ztest_vdev_add_remove(ztest_ds_t * zd,uint64_t id)2843 ztest_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 */
2928 void
ztest_vdev_class_add(ztest_ds_t * zd,uint64_t id)2929 ztest_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 */
3008 void
ztest_vdev_aux_add_remove(ztest_ds_t * zd,uint64_t id)3009 ztest_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 */
3107 void
ztest_split_pool(ztest_ds_t * zd,uint64_t id)3108 ztest_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 *