xref: /freebsd-14-stable/sys/contrib/openzfs/cmd/ztest.c (revision 2ec8b69480708185a273254e4e254140eb2ce633)
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 https://opensource.org/licenses/CDDL-1.0.
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, 2024 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  */
30 
31 /*
32  * The objective of this program is to provide a DMU/ZAP/SPA stress test
33  * that runs entirely in userland, is easy to use, and easy to extend.
34  *
35  * The overall design of the ztest program is as follows:
36  *
37  * (1) For each major functional area (e.g. adding vdevs to a pool,
38  *     creating and destroying datasets, reading and writing objects, etc)
39  *     we have a simple routine to test that functionality.  These
40  *     individual routines do not have to do anything "stressful".
41  *
42  * (2) We turn these simple functionality tests into a stress test by
43  *     running them all in parallel, with as many threads as desired,
44  *     and spread across as many datasets, objects, and vdevs as desired.
45  *
46  * (3) While all this is happening, we inject faults into the pool to
47  *     verify that self-healing data really works.
48  *
49  * (4) Every time we open a dataset, we change its checksum and compression
50  *     functions.  Thus even individual objects vary from block to block
51  *     in which checksum they use and whether they're compressed.
52  *
53  * (5) To verify that we never lose on-disk consistency after a crash,
54  *     we run the entire test in a child of the main process.
55  *     At random times, the child self-immolates with a SIGKILL.
56  *     This is the software equivalent of pulling the power cord.
57  *     The parent then runs the test again, using the existing
58  *     storage pool, as many times as desired. If backwards compatibility
59  *     testing is enabled ztest will sometimes run the "older" version
60  *     of ztest after a SIGKILL.
61  *
62  * (6) To verify that we don't have future leaks or temporal incursions,
63  *     many of the functional tests record the transaction group number
64  *     as part of their data.  When reading old data, they verify that
65  *     the transaction group number is less than the current, open txg.
66  *     If you add a new test, please do this if applicable.
67  *
68  * (7) Threads are created with a reduced stack size, for sanity checking.
69  *     Therefore, it's important not to allocate huge buffers on the stack.
70  *
71  * When run with no arguments, ztest runs for about five minutes and
72  * produces no output if successful.  To get a little bit of information,
73  * specify -V.  To get more information, specify -VV, and so on.
74  *
75  * To turn this into an overnight stress test, use -T to specify run time.
76  *
77  * You can ask more vdevs [-v], datasets [-d], or threads [-t]
78  * to increase the pool capacity, fanout, and overall stress level.
79  *
80  * Use the -k option to set the desired frequency of kills.
81  *
82  * When ztest invokes itself it passes all relevant information through a
83  * temporary file which is mmap-ed in the child process. This allows shared
84  * memory to survive the exec syscall. The ztest_shared_hdr_t struct is always
85  * stored at offset 0 of this file and contains information on the size and
86  * number of shared structures in the file. The information stored in this file
87  * must remain backwards compatible with older versions of ztest so that
88  * ztest can invoke them during backwards compatibility testing (-B).
89  */
90 
91 #include <sys/zfs_context.h>
92 #include <sys/spa.h>
93 #include <sys/dmu.h>
94 #include <sys/txg.h>
95 #include <sys/dbuf.h>
96 #include <sys/zap.h>
97 #include <sys/dmu_objset.h>
98 #include <sys/poll.h>
99 #include <sys/stat.h>
100 #include <sys/time.h>
101 #include <sys/wait.h>
102 #include <sys/mman.h>
103 #include <sys/resource.h>
104 #include <sys/zio.h>
105 #include <sys/zil.h>
106 #include <sys/zil_impl.h>
107 #include <sys/vdev_draid.h>
108 #include <sys/vdev_impl.h>
109 #include <sys/vdev_file.h>
110 #include <sys/vdev_initialize.h>
111 #include <sys/vdev_raidz.h>
112 #include <sys/vdev_trim.h>
113 #include <sys/spa_impl.h>
114 #include <sys/metaslab_impl.h>
115 #include <sys/dsl_prop.h>
116 #include <sys/dsl_dataset.h>
117 #include <sys/dsl_destroy.h>
118 #include <sys/dsl_scan.h>
119 #include <sys/zio_checksum.h>
120 #include <sys/zfs_refcount.h>
121 #include <sys/zfeature.h>
122 #include <sys/dsl_userhold.h>
123 #include <sys/abd.h>
124 #include <sys/blake3.h>
125 #include <stdio.h>
126 #include <stdlib.h>
127 #include <unistd.h>
128 #include <getopt.h>
129 #include <signal.h>
130 #include <umem.h>
131 #include <ctype.h>
132 #include <math.h>
133 #include <sys/fs/zfs.h>
134 #include <zfs_fletcher.h>
135 #include <libnvpair.h>
136 #include <libzutil.h>
137 #include <sys/crypto/icp.h>
138 #include <sys/zfs_impl.h>
139 #if (__GLIBC__ && !__UCLIBC__)
140 #include <execinfo.h> /* for backtrace() */
141 #endif
142 
143 static int ztest_fd_data = -1;
144 static int ztest_fd_rand = -1;
145 
146 typedef struct ztest_shared_hdr {
147 	uint64_t	zh_hdr_size;
148 	uint64_t	zh_opts_size;
149 	uint64_t	zh_size;
150 	uint64_t	zh_stats_size;
151 	uint64_t	zh_stats_count;
152 	uint64_t	zh_ds_size;
153 	uint64_t	zh_ds_count;
154 } ztest_shared_hdr_t;
155 
156 static ztest_shared_hdr_t *ztest_shared_hdr;
157 
158 enum ztest_class_state {
159 	ZTEST_VDEV_CLASS_OFF,
160 	ZTEST_VDEV_CLASS_ON,
161 	ZTEST_VDEV_CLASS_RND
162 };
163 
164 #define	ZO_GVARS_MAX_ARGLEN	((size_t)64)
165 #define	ZO_GVARS_MAX_COUNT	((size_t)10)
166 
167 typedef struct ztest_shared_opts {
168 	char zo_pool[ZFS_MAX_DATASET_NAME_LEN];
169 	char zo_dir[ZFS_MAX_DATASET_NAME_LEN];
170 	char zo_alt_ztest[MAXNAMELEN];
171 	char zo_alt_libpath[MAXNAMELEN];
172 	uint64_t zo_vdevs;
173 	uint64_t zo_vdevtime;
174 	size_t zo_vdev_size;
175 	int zo_ashift;
176 	int zo_mirrors;
177 	int zo_raid_children;
178 	int zo_raid_parity;
179 	char zo_raid_type[8];
180 	int zo_draid_data;
181 	int zo_draid_spares;
182 	int zo_datasets;
183 	int zo_threads;
184 	uint64_t zo_passtime;
185 	uint64_t zo_killrate;
186 	int zo_verbose;
187 	int zo_init;
188 	uint64_t zo_time;
189 	uint64_t zo_maxloops;
190 	uint64_t zo_metaslab_force_ganging;
191 	int zo_mmp_test;
192 	int zo_special_vdevs;
193 	int zo_dump_dbgmsg;
194 	int zo_gvars_count;
195 	char zo_gvars[ZO_GVARS_MAX_COUNT][ZO_GVARS_MAX_ARGLEN];
196 } ztest_shared_opts_t;
197 
198 /* Default values for command line options. */
199 #define	DEFAULT_POOL "ztest"
200 #define	DEFAULT_VDEV_DIR "/tmp"
201 #define	DEFAULT_VDEV_COUNT 5
202 #define	DEFAULT_VDEV_SIZE (SPA_MINDEVSIZE * 4)	/* 256m default size */
203 #define	DEFAULT_VDEV_SIZE_STR "256M"
204 #define	DEFAULT_ASHIFT SPA_MINBLOCKSHIFT
205 #define	DEFAULT_MIRRORS 2
206 #define	DEFAULT_RAID_CHILDREN 4
207 #define	DEFAULT_RAID_PARITY 1
208 #define	DEFAULT_DRAID_DATA 4
209 #define	DEFAULT_DRAID_SPARES 1
210 #define	DEFAULT_DATASETS_COUNT 7
211 #define	DEFAULT_THREADS 23
212 #define	DEFAULT_RUN_TIME 300 /* 300 seconds */
213 #define	DEFAULT_RUN_TIME_STR "300 sec"
214 #define	DEFAULT_PASS_TIME 60 /* 60 seconds */
215 #define	DEFAULT_PASS_TIME_STR "60 sec"
216 #define	DEFAULT_KILL_RATE 70 /* 70% kill rate */
217 #define	DEFAULT_KILLRATE_STR "70%"
218 #define	DEFAULT_INITS 1
219 #define	DEFAULT_MAX_LOOPS 50 /* 5 minutes */
220 #define	DEFAULT_FORCE_GANGING (64 << 10)
221 #define	DEFAULT_FORCE_GANGING_STR "64K"
222 
223 /* Simplifying assumption: -1 is not a valid default. */
224 #define	NO_DEFAULT -1
225 
226 static const ztest_shared_opts_t ztest_opts_defaults = {
227 	.zo_pool = DEFAULT_POOL,
228 	.zo_dir = DEFAULT_VDEV_DIR,
229 	.zo_alt_ztest = { '\0' },
230 	.zo_alt_libpath = { '\0' },
231 	.zo_vdevs = DEFAULT_VDEV_COUNT,
232 	.zo_ashift = DEFAULT_ASHIFT,
233 	.zo_mirrors = DEFAULT_MIRRORS,
234 	.zo_raid_children = DEFAULT_RAID_CHILDREN,
235 	.zo_raid_parity = DEFAULT_RAID_PARITY,
236 	.zo_raid_type = VDEV_TYPE_RAIDZ,
237 	.zo_vdev_size = DEFAULT_VDEV_SIZE,
238 	.zo_draid_data = DEFAULT_DRAID_DATA,	/* data drives */
239 	.zo_draid_spares = DEFAULT_DRAID_SPARES, /* distributed spares */
240 	.zo_datasets = DEFAULT_DATASETS_COUNT,
241 	.zo_threads = DEFAULT_THREADS,
242 	.zo_passtime = DEFAULT_PASS_TIME,
243 	.zo_killrate = DEFAULT_KILL_RATE,
244 	.zo_verbose = 0,
245 	.zo_mmp_test = 0,
246 	.zo_init = DEFAULT_INITS,
247 	.zo_time = DEFAULT_RUN_TIME,
248 	.zo_maxloops = DEFAULT_MAX_LOOPS, /* max loops during spa_freeze() */
249 	.zo_metaslab_force_ganging = DEFAULT_FORCE_GANGING,
250 	.zo_special_vdevs = ZTEST_VDEV_CLASS_RND,
251 	.zo_gvars_count = 0,
252 };
253 
254 extern uint64_t metaslab_force_ganging;
255 extern uint64_t metaslab_df_alloc_threshold;
256 extern uint64_t zfs_deadman_synctime_ms;
257 extern uint_t metaslab_preload_limit;
258 extern int zfs_compressed_arc_enabled;
259 extern int zfs_abd_scatter_enabled;
260 extern uint_t dmu_object_alloc_chunk_shift;
261 extern boolean_t zfs_force_some_double_word_sm_entries;
262 extern unsigned long zio_decompress_fail_fraction;
263 extern unsigned long zfs_reconstruct_indirect_damage_fraction;
264 
265 
266 static ztest_shared_opts_t *ztest_shared_opts;
267 static ztest_shared_opts_t ztest_opts;
268 static const char *const ztest_wkeydata = "abcdefghijklmnopqrstuvwxyz012345";
269 
270 typedef struct ztest_shared_ds {
271 	uint64_t	zd_seq;
272 } ztest_shared_ds_t;
273 
274 static ztest_shared_ds_t *ztest_shared_ds;
275 #define	ZTEST_GET_SHARED_DS(d) (&ztest_shared_ds[d])
276 
277 #define	BT_MAGIC	0x123456789abcdefULL
278 #define	MAXFAULTS(zs) \
279 	(MAX((zs)->zs_mirrors, 1) * (ztest_opts.zo_raid_parity + 1) - 1)
280 
281 enum ztest_io_type {
282 	ZTEST_IO_WRITE_TAG,
283 	ZTEST_IO_WRITE_PATTERN,
284 	ZTEST_IO_WRITE_ZEROES,
285 	ZTEST_IO_TRUNCATE,
286 	ZTEST_IO_SETATTR,
287 	ZTEST_IO_REWRITE,
288 	ZTEST_IO_TYPES
289 };
290 
291 typedef struct ztest_block_tag {
292 	uint64_t	bt_magic;
293 	uint64_t	bt_objset;
294 	uint64_t	bt_object;
295 	uint64_t	bt_dnodesize;
296 	uint64_t	bt_offset;
297 	uint64_t	bt_gen;
298 	uint64_t	bt_txg;
299 	uint64_t	bt_crtxg;
300 } ztest_block_tag_t;
301 
302 typedef struct bufwad {
303 	uint64_t	bw_index;
304 	uint64_t	bw_txg;
305 	uint64_t	bw_data;
306 } bufwad_t;
307 
308 /*
309  * It would be better to use a rangelock_t per object.  Unfortunately
310  * the rangelock_t is not a drop-in replacement for rl_t, because we
311  * still need to map from object ID to rangelock_t.
312  */
313 typedef enum {
314 	RL_READER,
315 	RL_WRITER,
316 	RL_APPEND
317 } rl_type_t;
318 
319 typedef struct rll {
320 	void		*rll_writer;
321 	int		rll_readers;
322 	kmutex_t	rll_lock;
323 	kcondvar_t	rll_cv;
324 } rll_t;
325 
326 typedef struct rl {
327 	uint64_t	rl_object;
328 	uint64_t	rl_offset;
329 	uint64_t	rl_size;
330 	rll_t		*rl_lock;
331 } rl_t;
332 
333 #define	ZTEST_RANGE_LOCKS	64
334 #define	ZTEST_OBJECT_LOCKS	64
335 
336 /*
337  * Object descriptor.  Used as a template for object lookup/create/remove.
338  */
339 typedef struct ztest_od {
340 	uint64_t	od_dir;
341 	uint64_t	od_object;
342 	dmu_object_type_t od_type;
343 	dmu_object_type_t od_crtype;
344 	uint64_t	od_blocksize;
345 	uint64_t	od_crblocksize;
346 	uint64_t	od_crdnodesize;
347 	uint64_t	od_gen;
348 	uint64_t	od_crgen;
349 	char		od_name[ZFS_MAX_DATASET_NAME_LEN];
350 } ztest_od_t;
351 
352 /*
353  * Per-dataset state.
354  */
355 typedef struct ztest_ds {
356 	ztest_shared_ds_t *zd_shared;
357 	objset_t	*zd_os;
358 	pthread_rwlock_t zd_zilog_lock;
359 	zilog_t		*zd_zilog;
360 	ztest_od_t	*zd_od;		/* debugging aid */
361 	char		zd_name[ZFS_MAX_DATASET_NAME_LEN];
362 	kmutex_t	zd_dirobj_lock;
363 	rll_t		zd_object_lock[ZTEST_OBJECT_LOCKS];
364 	rll_t		zd_range_lock[ZTEST_RANGE_LOCKS];
365 } ztest_ds_t;
366 
367 /*
368  * Per-iteration state.
369  */
370 typedef void ztest_func_t(ztest_ds_t *zd, uint64_t id);
371 
372 typedef struct ztest_info {
373 	ztest_func_t	*zi_func;	/* test function */
374 	uint64_t	zi_iters;	/* iterations per execution */
375 	uint64_t	*zi_interval;	/* execute every <interval> seconds */
376 	const char	*zi_funcname;	/* name of test function */
377 } ztest_info_t;
378 
379 typedef struct ztest_shared_callstate {
380 	uint64_t	zc_count;	/* per-pass count */
381 	uint64_t	zc_time;	/* per-pass time */
382 	uint64_t	zc_next;	/* next time to call this function */
383 } ztest_shared_callstate_t;
384 
385 static ztest_shared_callstate_t *ztest_shared_callstate;
386 #define	ZTEST_GET_SHARED_CALLSTATE(c) (&ztest_shared_callstate[c])
387 
388 ztest_func_t ztest_dmu_read_write;
389 ztest_func_t ztest_dmu_write_parallel;
390 ztest_func_t ztest_dmu_object_alloc_free;
391 ztest_func_t ztest_dmu_object_next_chunk;
392 ztest_func_t ztest_dmu_commit_callbacks;
393 ztest_func_t ztest_zap;
394 ztest_func_t ztest_zap_parallel;
395 ztest_func_t ztest_zil_commit;
396 ztest_func_t ztest_zil_remount;
397 ztest_func_t ztest_dmu_read_write_zcopy;
398 ztest_func_t ztest_dmu_objset_create_destroy;
399 ztest_func_t ztest_dmu_prealloc;
400 ztest_func_t ztest_fzap;
401 ztest_func_t ztest_dmu_snapshot_create_destroy;
402 ztest_func_t ztest_dsl_prop_get_set;
403 ztest_func_t ztest_spa_prop_get_set;
404 ztest_func_t ztest_spa_create_destroy;
405 ztest_func_t ztest_fault_inject;
406 ztest_func_t ztest_dmu_snapshot_hold;
407 ztest_func_t ztest_mmp_enable_disable;
408 ztest_func_t ztest_scrub;
409 ztest_func_t ztest_dsl_dataset_promote_busy;
410 ztest_func_t ztest_vdev_attach_detach;
411 ztest_func_t ztest_vdev_LUN_growth;
412 ztest_func_t ztest_vdev_add_remove;
413 ztest_func_t ztest_vdev_class_add;
414 ztest_func_t ztest_vdev_aux_add_remove;
415 ztest_func_t ztest_split_pool;
416 ztest_func_t ztest_reguid;
417 ztest_func_t ztest_spa_upgrade;
418 ztest_func_t ztest_device_removal;
419 ztest_func_t ztest_spa_checkpoint_create_discard;
420 ztest_func_t ztest_initialize;
421 ztest_func_t ztest_trim;
422 ztest_func_t ztest_blake3;
423 ztest_func_t ztest_fletcher;
424 ztest_func_t ztest_fletcher_incr;
425 ztest_func_t ztest_verify_dnode_bt;
426 
427 static uint64_t zopt_always = 0ULL * NANOSEC;		/* all the time */
428 static uint64_t zopt_incessant = 1ULL * NANOSEC / 10;	/* every 1/10 second */
429 static uint64_t zopt_often = 1ULL * NANOSEC;		/* every second */
430 static uint64_t zopt_sometimes = 10ULL * NANOSEC;	/* every 10 seconds */
431 static uint64_t zopt_rarely = 60ULL * NANOSEC;		/* every 60 seconds */
432 
433 #define	ZTI_INIT(func, iters, interval) \
434 	{   .zi_func = (func), \
435 	    .zi_iters = (iters), \
436 	    .zi_interval = (interval), \
437 	    .zi_funcname = # func }
438 
439 static ztest_info_t ztest_info[] = {
440 	ZTI_INIT(ztest_dmu_read_write, 1, &zopt_always),
441 	ZTI_INIT(ztest_dmu_write_parallel, 10, &zopt_always),
442 	ZTI_INIT(ztest_dmu_object_alloc_free, 1, &zopt_always),
443 	ZTI_INIT(ztest_dmu_object_next_chunk, 1, &zopt_sometimes),
444 	ZTI_INIT(ztest_dmu_commit_callbacks, 1, &zopt_always),
445 	ZTI_INIT(ztest_zap, 30, &zopt_always),
446 	ZTI_INIT(ztest_zap_parallel, 100, &zopt_always),
447 	ZTI_INIT(ztest_split_pool, 1, &zopt_sometimes),
448 	ZTI_INIT(ztest_zil_commit, 1, &zopt_incessant),
449 	ZTI_INIT(ztest_zil_remount, 1, &zopt_sometimes),
450 	ZTI_INIT(ztest_dmu_read_write_zcopy, 1, &zopt_often),
451 	ZTI_INIT(ztest_dmu_objset_create_destroy, 1, &zopt_often),
452 	ZTI_INIT(ztest_dsl_prop_get_set, 1, &zopt_often),
453 	ZTI_INIT(ztest_spa_prop_get_set, 1, &zopt_sometimes),
454 #if 0
455 	ZTI_INIT(ztest_dmu_prealloc, 1, &zopt_sometimes),
456 #endif
457 	ZTI_INIT(ztest_fzap, 1, &zopt_sometimes),
458 	ZTI_INIT(ztest_dmu_snapshot_create_destroy, 1, &zopt_sometimes),
459 	ZTI_INIT(ztest_spa_create_destroy, 1, &zopt_sometimes),
460 	ZTI_INIT(ztest_fault_inject, 1, &zopt_sometimes),
461 	ZTI_INIT(ztest_dmu_snapshot_hold, 1, &zopt_sometimes),
462 	ZTI_INIT(ztest_mmp_enable_disable, 1, &zopt_sometimes),
463 	ZTI_INIT(ztest_reguid, 1, &zopt_rarely),
464 	ZTI_INIT(ztest_scrub, 1, &zopt_rarely),
465 	ZTI_INIT(ztest_spa_upgrade, 1, &zopt_rarely),
466 	ZTI_INIT(ztest_dsl_dataset_promote_busy, 1, &zopt_rarely),
467 	ZTI_INIT(ztest_vdev_attach_detach, 1, &zopt_sometimes),
468 	ZTI_INIT(ztest_vdev_LUN_growth, 1, &zopt_rarely),
469 	ZTI_INIT(ztest_vdev_add_remove, 1, &ztest_opts.zo_vdevtime),
470 	ZTI_INIT(ztest_vdev_class_add, 1, &ztest_opts.zo_vdevtime),
471 	ZTI_INIT(ztest_vdev_aux_add_remove, 1, &ztest_opts.zo_vdevtime),
472 	ZTI_INIT(ztest_device_removal, 1, &zopt_sometimes),
473 	ZTI_INIT(ztest_spa_checkpoint_create_discard, 1, &zopt_rarely),
474 	ZTI_INIT(ztest_initialize, 1, &zopt_sometimes),
475 	ZTI_INIT(ztest_trim, 1, &zopt_sometimes),
476 	ZTI_INIT(ztest_blake3, 1, &zopt_rarely),
477 	ZTI_INIT(ztest_fletcher, 1, &zopt_rarely),
478 	ZTI_INIT(ztest_fletcher_incr, 1, &zopt_rarely),
479 	ZTI_INIT(ztest_verify_dnode_bt, 1, &zopt_sometimes),
480 };
481 
482 #define	ZTEST_FUNCS	(sizeof (ztest_info) / sizeof (ztest_info_t))
483 
484 /*
485  * The following struct is used to hold a list of uncalled commit callbacks.
486  * The callbacks are ordered by txg number.
487  */
488 typedef struct ztest_cb_list {
489 	kmutex_t	zcl_callbacks_lock;
490 	list_t		zcl_callbacks;
491 } ztest_cb_list_t;
492 
493 /*
494  * Stuff we need to share writably between parent and child.
495  */
496 typedef struct ztest_shared {
497 	boolean_t	zs_do_init;
498 	hrtime_t	zs_proc_start;
499 	hrtime_t	zs_proc_stop;
500 	hrtime_t	zs_thread_start;
501 	hrtime_t	zs_thread_stop;
502 	hrtime_t	zs_thread_kill;
503 	uint64_t	zs_enospc_count;
504 	uint64_t	zs_vdev_next_leaf;
505 	uint64_t	zs_vdev_aux;
506 	uint64_t	zs_alloc;
507 	uint64_t	zs_space;
508 	uint64_t	zs_splits;
509 	uint64_t	zs_mirrors;
510 	uint64_t	zs_metaslab_sz;
511 	uint64_t	zs_metaslab_df_alloc_threshold;
512 	uint64_t	zs_guid;
513 } ztest_shared_t;
514 
515 #define	ID_PARALLEL	-1ULL
516 
517 static char ztest_dev_template[] = "%s/%s.%llua";
518 static char ztest_aux_template[] = "%s/%s.%s.%llu";
519 static ztest_shared_t *ztest_shared;
520 
521 static spa_t *ztest_spa = NULL;
522 static ztest_ds_t *ztest_ds;
523 
524 static kmutex_t ztest_vdev_lock;
525 static boolean_t ztest_device_removal_active = B_FALSE;
526 static boolean_t ztest_pool_scrubbed = B_FALSE;
527 static kmutex_t ztest_checkpoint_lock;
528 
529 /*
530  * The ztest_name_lock protects the pool and dataset namespace used by
531  * the individual tests. To modify the namespace, consumers must grab
532  * this lock as writer. Grabbing the lock as reader will ensure that the
533  * namespace does not change while the lock is held.
534  */
535 static pthread_rwlock_t ztest_name_lock;
536 
537 static boolean_t ztest_dump_core = B_TRUE;
538 static boolean_t ztest_exiting;
539 
540 /* Global commit callback list */
541 static ztest_cb_list_t zcl;
542 /* Commit cb delay */
543 static uint64_t zc_min_txg_delay = UINT64_MAX;
544 static int zc_cb_counter = 0;
545 
546 /*
547  * Minimum number of commit callbacks that need to be registered for us to check
548  * whether the minimum txg delay is acceptable.
549  */
550 #define	ZTEST_COMMIT_CB_MIN_REG	100
551 
552 /*
553  * If a number of txgs equal to this threshold have been created after a commit
554  * callback has been registered but not called, then we assume there is an
555  * implementation bug.
556  */
557 #define	ZTEST_COMMIT_CB_THRESH	(TXG_CONCURRENT_STATES + 1000)
558 
559 enum ztest_object {
560 	ZTEST_META_DNODE = 0,
561 	ZTEST_DIROBJ,
562 	ZTEST_OBJECTS
563 };
564 
565 static __attribute__((noreturn)) void usage(boolean_t requested);
566 static int ztest_scrub_impl(spa_t *spa);
567 
568 /*
569  * These libumem hooks provide a reasonable set of defaults for the allocator's
570  * debugging facilities.
571  */
572 const char *
_umem_debug_init(void)573 _umem_debug_init(void)
574 {
575 	return ("default,verbose"); /* $UMEM_DEBUG setting */
576 }
577 
578 const char *
_umem_logging_init(void)579 _umem_logging_init(void)
580 {
581 	return ("fail,contents"); /* $UMEM_LOGGING setting */
582 }
583 
584 static void
dump_debug_buffer(void)585 dump_debug_buffer(void)
586 {
587 	ssize_t ret __attribute__((unused));
588 
589 	if (!ztest_opts.zo_dump_dbgmsg)
590 		return;
591 
592 	/*
593 	 * We use write() instead of printf() so that this function
594 	 * is safe to call from a signal handler.
595 	 */
596 	ret = write(STDERR_FILENO, "\n", 1);
597 	zfs_dbgmsg_print(STDERR_FILENO, "ztest");
598 }
599 
600 #define	BACKTRACE_SZ	100
601 
sig_handler(int signo)602 static void sig_handler(int signo)
603 {
604 	struct sigaction action;
605 #if (__GLIBC__ && !__UCLIBC__) /* backtrace() is a GNU extension */
606 	int nptrs;
607 	void *buffer[BACKTRACE_SZ];
608 
609 	nptrs = backtrace(buffer, BACKTRACE_SZ);
610 	backtrace_symbols_fd(buffer, nptrs, STDERR_FILENO);
611 #endif
612 	dump_debug_buffer();
613 
614 	/*
615 	 * Restore default action and re-raise signal so SIGSEGV and
616 	 * SIGABRT can trigger a core dump.
617 	 */
618 	action.sa_handler = SIG_DFL;
619 	sigemptyset(&action.sa_mask);
620 	action.sa_flags = 0;
621 	(void) sigaction(signo, &action, NULL);
622 	raise(signo);
623 }
624 
625 #define	FATAL_MSG_SZ	1024
626 
627 static const char *fatal_msg;
628 
629 static __attribute__((format(printf, 2, 3))) __attribute__((noreturn)) void
fatal(int do_perror,const char * message,...)630 fatal(int do_perror, const char *message, ...)
631 {
632 	va_list args;
633 	int save_errno = errno;
634 	char *buf;
635 
636 	(void) fflush(stdout);
637 	buf = umem_alloc(FATAL_MSG_SZ, UMEM_NOFAIL);
638 	if (buf == NULL)
639 		goto out;
640 
641 	va_start(args, message);
642 	(void) sprintf(buf, "ztest: ");
643 	/* LINTED */
644 	(void) vsprintf(buf + strlen(buf), message, args);
645 	va_end(args);
646 	if (do_perror) {
647 		(void) snprintf(buf + strlen(buf), FATAL_MSG_SZ - strlen(buf),
648 		    ": %s", strerror(save_errno));
649 	}
650 	(void) fprintf(stderr, "%s\n", buf);
651 	fatal_msg = buf;			/* to ease debugging */
652 
653 out:
654 	if (ztest_dump_core)
655 		abort();
656 	else
657 		dump_debug_buffer();
658 
659 	exit(3);
660 }
661 
662 static int
str2shift(const char * buf)663 str2shift(const char *buf)
664 {
665 	const char *ends = "BKMGTPEZ";
666 	int i, len;
667 
668 	if (buf[0] == '\0')
669 		return (0);
670 
671 	len = strlen(ends);
672 	for (i = 0; i < len; i++) {
673 		if (toupper(buf[0]) == ends[i])
674 			break;
675 	}
676 	if (i == len) {
677 		(void) fprintf(stderr, "ztest: invalid bytes suffix: %s\n",
678 		    buf);
679 		usage(B_FALSE);
680 	}
681 	if (buf[1] == '\0' || (toupper(buf[1]) == 'B' && buf[2] == '\0')) {
682 		return (10*i);
683 	}
684 	(void) fprintf(stderr, "ztest: invalid bytes suffix: %s\n", buf);
685 	usage(B_FALSE);
686 }
687 
688 static uint64_t
nicenumtoull(const char * buf)689 nicenumtoull(const char *buf)
690 {
691 	char *end;
692 	uint64_t val;
693 
694 	val = strtoull(buf, &end, 0);
695 	if (end == buf) {
696 		(void) fprintf(stderr, "ztest: bad numeric value: %s\n", buf);
697 		usage(B_FALSE);
698 	} else if (end[0] == '.') {
699 		double fval = strtod(buf, &end);
700 		fval *= pow(2, str2shift(end));
701 		/*
702 		 * UINT64_MAX is not exactly representable as a double.
703 		 * The closest representation is UINT64_MAX + 1, so we
704 		 * use a >= comparison instead of > for the bounds check.
705 		 */
706 		if (fval >= (double)UINT64_MAX) {
707 			(void) fprintf(stderr, "ztest: value too large: %s\n",
708 			    buf);
709 			usage(B_FALSE);
710 		}
711 		val = (uint64_t)fval;
712 	} else {
713 		int shift = str2shift(end);
714 		if (shift >= 64 || (val << shift) >> shift != val) {
715 			(void) fprintf(stderr, "ztest: value too large: %s\n",
716 			    buf);
717 			usage(B_FALSE);
718 		}
719 		val <<= shift;
720 	}
721 	return (val);
722 }
723 
724 typedef struct ztest_option {
725 	const char	short_opt;
726 	const char	*long_opt;
727 	const char	*long_opt_param;
728 	const char	*comment;
729 	unsigned int	default_int;
730 	const char	*default_str;
731 } ztest_option_t;
732 
733 /*
734  * The following option_table is used for generating the usage info as well as
735  * the long and short option information for calling getopt_long().
736  */
737 static ztest_option_t option_table[] = {
738 	{ 'v',	"vdevs", "INTEGER", "Number of vdevs", DEFAULT_VDEV_COUNT,
739 	    NULL},
740 	{ 's',	"vdev-size", "INTEGER", "Size of each vdev",
741 	    NO_DEFAULT, DEFAULT_VDEV_SIZE_STR},
742 	{ 'a',	"alignment-shift", "INTEGER",
743 	    "Alignment shift; use 0 for random", DEFAULT_ASHIFT, NULL},
744 	{ 'm',	"mirror-copies", "INTEGER", "Number of mirror copies",
745 	    DEFAULT_MIRRORS, NULL},
746 	{ 'r',	"raid-disks", "INTEGER", "Number of raidz/draid disks",
747 	    DEFAULT_RAID_CHILDREN, NULL},
748 	{ 'R',	"raid-parity", "INTEGER", "Raid parity",
749 	    DEFAULT_RAID_PARITY, NULL},
750 	{ 'K',	"raid-kind", "raidz|draid|random", "Raid kind",
751 	    NO_DEFAULT, "random"},
752 	{ 'D',	"draid-data", "INTEGER", "Number of draid data drives",
753 	    DEFAULT_DRAID_DATA, NULL},
754 	{ 'S',	"draid-spares", "INTEGER", "Number of draid spares",
755 	    DEFAULT_DRAID_SPARES, NULL},
756 	{ 'd',	"datasets", "INTEGER", "Number of datasets",
757 	    DEFAULT_DATASETS_COUNT, NULL},
758 	{ 't',	"threads", "INTEGER", "Number of ztest threads",
759 	    DEFAULT_THREADS, NULL},
760 	{ 'g',	"gang-block-threshold", "INTEGER",
761 	    "Metaslab gang block threshold",
762 	    NO_DEFAULT, DEFAULT_FORCE_GANGING_STR},
763 	{ 'i',	"init-count", "INTEGER", "Number of times to initialize pool",
764 	    DEFAULT_INITS, NULL},
765 	{ 'k',	"kill-percentage", "INTEGER", "Kill percentage",
766 	    NO_DEFAULT, DEFAULT_KILLRATE_STR},
767 	{ 'p',	"pool-name", "STRING", "Pool name",
768 	    NO_DEFAULT, DEFAULT_POOL},
769 	{ 'f',	"vdev-file-directory", "PATH", "File directory for vdev files",
770 	    NO_DEFAULT, DEFAULT_VDEV_DIR},
771 	{ 'M',	"multi-host", NULL,
772 	    "Multi-host; simulate pool imported on remote host",
773 	    NO_DEFAULT, NULL},
774 	{ 'E',	"use-existing-pool", NULL,
775 	    "Use existing pool instead of creating new one", NO_DEFAULT, NULL},
776 	{ 'T',	"run-time", "INTEGER", "Total run time",
777 	    NO_DEFAULT, DEFAULT_RUN_TIME_STR},
778 	{ 'P',	"pass-time", "INTEGER", "Time per pass",
779 	    NO_DEFAULT, DEFAULT_PASS_TIME_STR},
780 	{ 'F',	"freeze-loops", "INTEGER", "Max loops in spa_freeze()",
781 	    DEFAULT_MAX_LOOPS, NULL},
782 	{ 'B',	"alt-ztest", "PATH", "Alternate ztest path",
783 	    NO_DEFAULT, NULL},
784 	{ 'C',	"vdev-class-state", "on|off|random", "vdev class state",
785 	    NO_DEFAULT, "random"},
786 	{ 'o',	"option", "\"OPTION=INTEGER\"",
787 	    "Set global variable to an unsigned 32-bit integer value",
788 	    NO_DEFAULT, NULL},
789 	{ 'G',	"dump-debug-msg", NULL,
790 	    "Dump zfs_dbgmsg buffer before exiting due to an error",
791 	    NO_DEFAULT, NULL},
792 	{ 'V',	"verbose", NULL,
793 	    "Verbose (use multiple times for ever more verbosity)",
794 	    NO_DEFAULT, NULL},
795 	{ 'h',	"help",	NULL, "Show this help",
796 	    NO_DEFAULT, NULL},
797 	{0, 0, 0, 0, 0, 0}
798 };
799 
800 static struct option *long_opts = NULL;
801 static char *short_opts = NULL;
802 
803 static void
init_options(void)804 init_options(void)
805 {
806 	ASSERT3P(long_opts, ==, NULL);
807 	ASSERT3P(short_opts, ==, NULL);
808 
809 	int count = sizeof (option_table) / sizeof (option_table[0]);
810 	long_opts = umem_alloc(sizeof (struct option) * count, UMEM_NOFAIL);
811 
812 	short_opts = umem_alloc(sizeof (char) * 2 * count, UMEM_NOFAIL);
813 	int short_opt_index = 0;
814 
815 	for (int i = 0; i < count; i++) {
816 		long_opts[i].val = option_table[i].short_opt;
817 		long_opts[i].name = option_table[i].long_opt;
818 		long_opts[i].has_arg = option_table[i].long_opt_param != NULL
819 		    ? required_argument : no_argument;
820 		long_opts[i].flag = NULL;
821 		short_opts[short_opt_index++] = option_table[i].short_opt;
822 		if (option_table[i].long_opt_param != NULL) {
823 			short_opts[short_opt_index++] = ':';
824 		}
825 	}
826 }
827 
828 static void
fini_options(void)829 fini_options(void)
830 {
831 	int count = sizeof (option_table) / sizeof (option_table[0]);
832 
833 	umem_free(long_opts, sizeof (struct option) * count);
834 	umem_free(short_opts, sizeof (char) * 2 * count);
835 
836 	long_opts = NULL;
837 	short_opts = NULL;
838 }
839 
840 static __attribute__((noreturn)) void
usage(boolean_t requested)841 usage(boolean_t requested)
842 {
843 	char option[80];
844 	FILE *fp = requested ? stdout : stderr;
845 
846 	(void) fprintf(fp, "Usage: %s [OPTIONS...]\n", DEFAULT_POOL);
847 	for (int i = 0; option_table[i].short_opt != 0; i++) {
848 		if (option_table[i].long_opt_param != NULL) {
849 			(void) sprintf(option, "  -%c --%s=%s",
850 			    option_table[i].short_opt,
851 			    option_table[i].long_opt,
852 			    option_table[i].long_opt_param);
853 		} else {
854 			(void) sprintf(option, "  -%c --%s",
855 			    option_table[i].short_opt,
856 			    option_table[i].long_opt);
857 		}
858 		(void) fprintf(fp, "  %-40s%s", option,
859 		    option_table[i].comment);
860 
861 		if (option_table[i].long_opt_param != NULL) {
862 			if (option_table[i].default_str != NULL) {
863 				(void) fprintf(fp, " (default: %s)",
864 				    option_table[i].default_str);
865 			} else if (option_table[i].default_int != NO_DEFAULT) {
866 				(void) fprintf(fp, " (default: %u)",
867 				    option_table[i].default_int);
868 			}
869 		}
870 		(void) fprintf(fp, "\n");
871 	}
872 	exit(requested ? 0 : 1);
873 }
874 
875 static uint64_t
ztest_random(uint64_t range)876 ztest_random(uint64_t range)
877 {
878 	uint64_t r;
879 
880 	ASSERT3S(ztest_fd_rand, >=, 0);
881 
882 	if (range == 0)
883 		return (0);
884 
885 	if (read(ztest_fd_rand, &r, sizeof (r)) != sizeof (r))
886 		fatal(B_TRUE, "short read from /dev/urandom");
887 
888 	return (r % range);
889 }
890 
891 static void
ztest_parse_name_value(const char * input,ztest_shared_opts_t * zo)892 ztest_parse_name_value(const char *input, ztest_shared_opts_t *zo)
893 {
894 	char name[32];
895 	char *value;
896 	int state = ZTEST_VDEV_CLASS_RND;
897 
898 	(void) strlcpy(name, input, sizeof (name));
899 
900 	value = strchr(name, '=');
901 	if (value == NULL) {
902 		(void) fprintf(stderr, "missing value in property=value "
903 		    "'-C' argument (%s)\n", input);
904 		usage(B_FALSE);
905 	}
906 	*(value) = '\0';
907 	value++;
908 
909 	if (strcmp(value, "on") == 0) {
910 		state = ZTEST_VDEV_CLASS_ON;
911 	} else if (strcmp(value, "off") == 0) {
912 		state = ZTEST_VDEV_CLASS_OFF;
913 	} else if (strcmp(value, "random") == 0) {
914 		state = ZTEST_VDEV_CLASS_RND;
915 	} else {
916 		(void) fprintf(stderr, "invalid property value '%s'\n", value);
917 		usage(B_FALSE);
918 	}
919 
920 	if (strcmp(name, "special") == 0) {
921 		zo->zo_special_vdevs = state;
922 	} else {
923 		(void) fprintf(stderr, "invalid property name '%s'\n", name);
924 		usage(B_FALSE);
925 	}
926 	if (zo->zo_verbose >= 3)
927 		(void) printf("%s vdev state is '%s'\n", name, value);
928 }
929 
930 static void
process_options(int argc,char ** argv)931 process_options(int argc, char **argv)
932 {
933 	char *path;
934 	ztest_shared_opts_t *zo = &ztest_opts;
935 
936 	int opt;
937 	uint64_t value;
938 	const char *raid_kind = "random";
939 
940 	memcpy(zo, &ztest_opts_defaults, sizeof (*zo));
941 
942 	init_options();
943 
944 	while ((opt = getopt_long(argc, argv, short_opts, long_opts,
945 	    NULL)) != EOF) {
946 		value = 0;
947 		switch (opt) {
948 		case 'v':
949 		case 's':
950 		case 'a':
951 		case 'm':
952 		case 'r':
953 		case 'R':
954 		case 'D':
955 		case 'S':
956 		case 'd':
957 		case 't':
958 		case 'g':
959 		case 'i':
960 		case 'k':
961 		case 'T':
962 		case 'P':
963 		case 'F':
964 			value = nicenumtoull(optarg);
965 		}
966 		switch (opt) {
967 		case 'v':
968 			zo->zo_vdevs = value;
969 			break;
970 		case 's':
971 			zo->zo_vdev_size = MAX(SPA_MINDEVSIZE, value);
972 			break;
973 		case 'a':
974 			zo->zo_ashift = value;
975 			break;
976 		case 'm':
977 			zo->zo_mirrors = value;
978 			break;
979 		case 'r':
980 			zo->zo_raid_children = MAX(1, value);
981 			break;
982 		case 'R':
983 			zo->zo_raid_parity = MIN(MAX(value, 1), 3);
984 			break;
985 		case 'K':
986 			raid_kind = optarg;
987 			break;
988 		case 'D':
989 			zo->zo_draid_data = MAX(1, value);
990 			break;
991 		case 'S':
992 			zo->zo_draid_spares = MAX(1, value);
993 			break;
994 		case 'd':
995 			zo->zo_datasets = MAX(1, value);
996 			break;
997 		case 't':
998 			zo->zo_threads = MAX(1, value);
999 			break;
1000 		case 'g':
1001 			zo->zo_metaslab_force_ganging =
1002 			    MAX(SPA_MINBLOCKSIZE << 1, value);
1003 			break;
1004 		case 'i':
1005 			zo->zo_init = value;
1006 			break;
1007 		case 'k':
1008 			zo->zo_killrate = value;
1009 			break;
1010 		case 'p':
1011 			(void) strlcpy(zo->zo_pool, optarg,
1012 			    sizeof (zo->zo_pool));
1013 			break;
1014 		case 'f':
1015 			path = realpath(optarg, NULL);
1016 			if (path == NULL) {
1017 				(void) fprintf(stderr, "error: %s: %s\n",
1018 				    optarg, strerror(errno));
1019 				usage(B_FALSE);
1020 			} else {
1021 				(void) strlcpy(zo->zo_dir, path,
1022 				    sizeof (zo->zo_dir));
1023 				free(path);
1024 			}
1025 			break;
1026 		case 'M':
1027 			zo->zo_mmp_test = 1;
1028 			break;
1029 		case 'V':
1030 			zo->zo_verbose++;
1031 			break;
1032 		case 'E':
1033 			zo->zo_init = 0;
1034 			break;
1035 		case 'T':
1036 			zo->zo_time = value;
1037 			break;
1038 		case 'P':
1039 			zo->zo_passtime = MAX(1, value);
1040 			break;
1041 		case 'F':
1042 			zo->zo_maxloops = MAX(1, value);
1043 			break;
1044 		case 'B':
1045 			(void) strlcpy(zo->zo_alt_ztest, optarg,
1046 			    sizeof (zo->zo_alt_ztest));
1047 			break;
1048 		case 'C':
1049 			ztest_parse_name_value(optarg, zo);
1050 			break;
1051 		case 'o':
1052 			if (zo->zo_gvars_count >= ZO_GVARS_MAX_COUNT) {
1053 				(void) fprintf(stderr,
1054 				    "max global var count (%zu) exceeded\n",
1055 				    ZO_GVARS_MAX_COUNT);
1056 				usage(B_FALSE);
1057 			}
1058 			char *v = zo->zo_gvars[zo->zo_gvars_count];
1059 			if (strlcpy(v, optarg, ZO_GVARS_MAX_ARGLEN) >=
1060 			    ZO_GVARS_MAX_ARGLEN) {
1061 				(void) fprintf(stderr,
1062 				    "global var option '%s' is too long\n",
1063 				    optarg);
1064 				usage(B_FALSE);
1065 			}
1066 			zo->zo_gvars_count++;
1067 			break;
1068 		case 'G':
1069 			zo->zo_dump_dbgmsg = 1;
1070 			break;
1071 		case 'h':
1072 			usage(B_TRUE);
1073 			break;
1074 		case '?':
1075 		default:
1076 			usage(B_FALSE);
1077 			break;
1078 		}
1079 	}
1080 
1081 	fini_options();
1082 
1083 	/* When raid choice is 'random' add a draid pool 50% of the time */
1084 	if (strcmp(raid_kind, "random") == 0) {
1085 		raid_kind = (ztest_random(2) == 0) ? "draid" : "raidz";
1086 
1087 		if (ztest_opts.zo_verbose >= 3)
1088 			(void) printf("choosing RAID type '%s'\n", raid_kind);
1089 	}
1090 
1091 	if (strcmp(raid_kind, "draid") == 0) {
1092 		uint64_t min_devsize;
1093 
1094 		/* With fewer disk use 256M, otherwise 128M is OK */
1095 		min_devsize = (ztest_opts.zo_raid_children < 16) ?
1096 		    (256ULL << 20) : (128ULL << 20);
1097 
1098 		/* No top-level mirrors with dRAID for now */
1099 		zo->zo_mirrors = 0;
1100 
1101 		/* Use more appropriate defaults for dRAID */
1102 		if (zo->zo_vdevs == ztest_opts_defaults.zo_vdevs)
1103 			zo->zo_vdevs = 1;
1104 		if (zo->zo_raid_children ==
1105 		    ztest_opts_defaults.zo_raid_children)
1106 			zo->zo_raid_children = 16;
1107 		if (zo->zo_ashift < 12)
1108 			zo->zo_ashift = 12;
1109 		if (zo->zo_vdev_size < min_devsize)
1110 			zo->zo_vdev_size = min_devsize;
1111 
1112 		if (zo->zo_draid_data + zo->zo_raid_parity >
1113 		    zo->zo_raid_children - zo->zo_draid_spares) {
1114 			(void) fprintf(stderr, "error: too few draid "
1115 			    "children (%d) for stripe width (%d)\n",
1116 			    zo->zo_raid_children,
1117 			    zo->zo_draid_data + zo->zo_raid_parity);
1118 			usage(B_FALSE);
1119 		}
1120 
1121 		(void) strlcpy(zo->zo_raid_type, VDEV_TYPE_DRAID,
1122 		    sizeof (zo->zo_raid_type));
1123 
1124 	} else /* using raidz */ {
1125 		ASSERT0(strcmp(raid_kind, "raidz"));
1126 
1127 		zo->zo_raid_parity = MIN(zo->zo_raid_parity,
1128 		    zo->zo_raid_children - 1);
1129 	}
1130 
1131 	zo->zo_vdevtime =
1132 	    (zo->zo_vdevs > 0 ? zo->zo_time * NANOSEC / zo->zo_vdevs :
1133 	    UINT64_MAX >> 2);
1134 
1135 	if (*zo->zo_alt_ztest) {
1136 		const char *invalid_what = "ztest";
1137 		char *val = zo->zo_alt_ztest;
1138 		if (0 != access(val, X_OK) ||
1139 		    (strrchr(val, '/') == NULL && (errno == EINVAL)))
1140 			goto invalid;
1141 
1142 		int dirlen = strrchr(val, '/') - val;
1143 		strlcpy(zo->zo_alt_libpath, val,
1144 		    MIN(sizeof (zo->zo_alt_libpath), dirlen + 1));
1145 		invalid_what = "library path", val = zo->zo_alt_libpath;
1146 		if (strrchr(val, '/') == NULL && (errno == EINVAL))
1147 			goto invalid;
1148 		*strrchr(val, '/') = '\0';
1149 		strlcat(val, "/lib", sizeof (zo->zo_alt_libpath));
1150 
1151 		if (0 != access(zo->zo_alt_libpath, X_OK))
1152 			goto invalid;
1153 		return;
1154 
1155 invalid:
1156 		ztest_dump_core = B_FALSE;
1157 		fatal(B_TRUE, "invalid alternate %s %s", invalid_what, val);
1158 	}
1159 }
1160 
1161 static void
ztest_kill(ztest_shared_t * zs)1162 ztest_kill(ztest_shared_t *zs)
1163 {
1164 	zs->zs_alloc = metaslab_class_get_alloc(spa_normal_class(ztest_spa));
1165 	zs->zs_space = metaslab_class_get_space(spa_normal_class(ztest_spa));
1166 
1167 	/*
1168 	 * Before we kill ourselves, make sure that the config is updated.
1169 	 * See comment above spa_write_cachefile().
1170 	 */
1171 	mutex_enter(&spa_namespace_lock);
1172 	spa_write_cachefile(ztest_spa, B_FALSE, B_FALSE, B_FALSE);
1173 	mutex_exit(&spa_namespace_lock);
1174 
1175 	(void) raise(SIGKILL);
1176 }
1177 
1178 static void
ztest_record_enospc(const char * s)1179 ztest_record_enospc(const char *s)
1180 {
1181 	(void) s;
1182 	ztest_shared->zs_enospc_count++;
1183 }
1184 
1185 static uint64_t
ztest_get_ashift(void)1186 ztest_get_ashift(void)
1187 {
1188 	if (ztest_opts.zo_ashift == 0)
1189 		return (SPA_MINBLOCKSHIFT + ztest_random(5));
1190 	return (ztest_opts.zo_ashift);
1191 }
1192 
1193 static boolean_t
ztest_is_draid_spare(const char * name)1194 ztest_is_draid_spare(const char *name)
1195 {
1196 	uint64_t spare_id = 0, parity = 0, vdev_id = 0;
1197 
1198 	if (sscanf(name, VDEV_TYPE_DRAID "%"PRIu64"-%"PRIu64"-%"PRIu64"",
1199 	    &parity, &vdev_id, &spare_id) == 3) {
1200 		return (B_TRUE);
1201 	}
1202 
1203 	return (B_FALSE);
1204 }
1205 
1206 static nvlist_t *
make_vdev_file(const char * path,const char * aux,const char * pool,size_t size,uint64_t ashift)1207 make_vdev_file(const char *path, const char *aux, const char *pool,
1208     size_t size, uint64_t ashift)
1209 {
1210 	char *pathbuf = NULL;
1211 	uint64_t vdev;
1212 	nvlist_t *file;
1213 	boolean_t draid_spare = B_FALSE;
1214 
1215 
1216 	if (ashift == 0)
1217 		ashift = ztest_get_ashift();
1218 
1219 	if (path == NULL) {
1220 		pathbuf = umem_alloc(MAXPATHLEN, UMEM_NOFAIL);
1221 		path = pathbuf;
1222 
1223 		if (aux != NULL) {
1224 			vdev = ztest_shared->zs_vdev_aux;
1225 			(void) snprintf(pathbuf, MAXPATHLEN,
1226 			    ztest_aux_template, ztest_opts.zo_dir,
1227 			    pool == NULL ? ztest_opts.zo_pool : pool,
1228 			    aux, vdev);
1229 		} else {
1230 			vdev = ztest_shared->zs_vdev_next_leaf++;
1231 			(void) snprintf(pathbuf, MAXPATHLEN,
1232 			    ztest_dev_template, ztest_opts.zo_dir,
1233 			    pool == NULL ? ztest_opts.zo_pool : pool, vdev);
1234 		}
1235 	} else {
1236 		draid_spare = ztest_is_draid_spare(path);
1237 	}
1238 
1239 	if (size != 0 && !draid_spare) {
1240 		int fd = open(path, O_RDWR | O_CREAT | O_TRUNC, 0666);
1241 		if (fd == -1)
1242 			fatal(B_TRUE, "can't open %s", path);
1243 		if (ftruncate(fd, size) != 0)
1244 			fatal(B_TRUE, "can't ftruncate %s", path);
1245 		(void) close(fd);
1246 	}
1247 
1248 	file = fnvlist_alloc();
1249 	fnvlist_add_string(file, ZPOOL_CONFIG_TYPE,
1250 	    draid_spare ? VDEV_TYPE_DRAID_SPARE : VDEV_TYPE_FILE);
1251 	fnvlist_add_string(file, ZPOOL_CONFIG_PATH, path);
1252 	fnvlist_add_uint64(file, ZPOOL_CONFIG_ASHIFT, ashift);
1253 	umem_free(pathbuf, MAXPATHLEN);
1254 
1255 	return (file);
1256 }
1257 
1258 static nvlist_t *
make_vdev_raid(const char * path,const char * aux,const char * pool,size_t size,uint64_t ashift,int r)1259 make_vdev_raid(const char *path, const char *aux, const char *pool, size_t size,
1260     uint64_t ashift, int r)
1261 {
1262 	nvlist_t *raid, **child;
1263 	int c;
1264 
1265 	if (r < 2)
1266 		return (make_vdev_file(path, aux, pool, size, ashift));
1267 	child = umem_alloc(r * sizeof (nvlist_t *), UMEM_NOFAIL);
1268 
1269 	for (c = 0; c < r; c++)
1270 		child[c] = make_vdev_file(path, aux, pool, size, ashift);
1271 
1272 	raid = fnvlist_alloc();
1273 	fnvlist_add_string(raid, ZPOOL_CONFIG_TYPE,
1274 	    ztest_opts.zo_raid_type);
1275 	fnvlist_add_uint64(raid, ZPOOL_CONFIG_NPARITY,
1276 	    ztest_opts.zo_raid_parity);
1277 	fnvlist_add_nvlist_array(raid, ZPOOL_CONFIG_CHILDREN,
1278 	    (const nvlist_t **)child, r);
1279 
1280 	if (strcmp(ztest_opts.zo_raid_type, VDEV_TYPE_DRAID) == 0) {
1281 		uint64_t ndata = ztest_opts.zo_draid_data;
1282 		uint64_t nparity = ztest_opts.zo_raid_parity;
1283 		uint64_t nspares = ztest_opts.zo_draid_spares;
1284 		uint64_t children = ztest_opts.zo_raid_children;
1285 		uint64_t ngroups = 1;
1286 
1287 		/*
1288 		 * Calculate the minimum number of groups required to fill a
1289 		 * slice. This is the LCM of the stripe width (data + parity)
1290 		 * and the number of data drives (children - spares).
1291 		 */
1292 		while (ngroups * (ndata + nparity) % (children - nspares) != 0)
1293 			ngroups++;
1294 
1295 		/* Store the basic dRAID configuration. */
1296 		fnvlist_add_uint64(raid, ZPOOL_CONFIG_DRAID_NDATA, ndata);
1297 		fnvlist_add_uint64(raid, ZPOOL_CONFIG_DRAID_NSPARES, nspares);
1298 		fnvlist_add_uint64(raid, ZPOOL_CONFIG_DRAID_NGROUPS, ngroups);
1299 	}
1300 
1301 	for (c = 0; c < r; c++)
1302 		fnvlist_free(child[c]);
1303 
1304 	umem_free(child, r * sizeof (nvlist_t *));
1305 
1306 	return (raid);
1307 }
1308 
1309 static nvlist_t *
make_vdev_mirror(const char * path,const char * aux,const char * pool,size_t size,uint64_t ashift,int r,int m)1310 make_vdev_mirror(const char *path, const char *aux, const char *pool,
1311     size_t size, uint64_t ashift, int r, int m)
1312 {
1313 	nvlist_t *mirror, **child;
1314 	int c;
1315 
1316 	if (m < 1)
1317 		return (make_vdev_raid(path, aux, pool, size, ashift, r));
1318 
1319 	child = umem_alloc(m * sizeof (nvlist_t *), UMEM_NOFAIL);
1320 
1321 	for (c = 0; c < m; c++)
1322 		child[c] = make_vdev_raid(path, aux, pool, size, ashift, r);
1323 
1324 	mirror = fnvlist_alloc();
1325 	fnvlist_add_string(mirror, ZPOOL_CONFIG_TYPE, VDEV_TYPE_MIRROR);
1326 	fnvlist_add_nvlist_array(mirror, ZPOOL_CONFIG_CHILDREN,
1327 	    (const nvlist_t **)child, m);
1328 
1329 	for (c = 0; c < m; c++)
1330 		fnvlist_free(child[c]);
1331 
1332 	umem_free(child, m * sizeof (nvlist_t *));
1333 
1334 	return (mirror);
1335 }
1336 
1337 static nvlist_t *
make_vdev_root(const char * path,const char * aux,const char * pool,size_t size,uint64_t ashift,const char * class,int r,int m,int t)1338 make_vdev_root(const char *path, const char *aux, const char *pool, size_t size,
1339     uint64_t ashift, const char *class, int r, int m, int t)
1340 {
1341 	nvlist_t *root, **child;
1342 	int c;
1343 	boolean_t log;
1344 
1345 	ASSERT3S(t, >, 0);
1346 
1347 	log = (class != NULL && strcmp(class, "log") == 0);
1348 
1349 	child = umem_alloc(t * sizeof (nvlist_t *), UMEM_NOFAIL);
1350 
1351 	for (c = 0; c < t; c++) {
1352 		child[c] = make_vdev_mirror(path, aux, pool, size, ashift,
1353 		    r, m);
1354 		fnvlist_add_uint64(child[c], ZPOOL_CONFIG_IS_LOG, log);
1355 
1356 		if (class != NULL && class[0] != '\0') {
1357 			ASSERT(m > 1 || log);   /* expecting a mirror */
1358 			fnvlist_add_string(child[c],
1359 			    ZPOOL_CONFIG_ALLOCATION_BIAS, class);
1360 		}
1361 	}
1362 
1363 	root = fnvlist_alloc();
1364 	fnvlist_add_string(root, ZPOOL_CONFIG_TYPE, VDEV_TYPE_ROOT);
1365 	fnvlist_add_nvlist_array(root, aux ? aux : ZPOOL_CONFIG_CHILDREN,
1366 	    (const nvlist_t **)child, t);
1367 
1368 	for (c = 0; c < t; c++)
1369 		fnvlist_free(child[c]);
1370 
1371 	umem_free(child, t * sizeof (nvlist_t *));
1372 
1373 	return (root);
1374 }
1375 
1376 /*
1377  * Find a random spa version. Returns back a random spa version in the
1378  * range [initial_version, SPA_VERSION_FEATURES].
1379  */
1380 static uint64_t
ztest_random_spa_version(uint64_t initial_version)1381 ztest_random_spa_version(uint64_t initial_version)
1382 {
1383 	uint64_t version = initial_version;
1384 
1385 	if (version <= SPA_VERSION_BEFORE_FEATURES) {
1386 		version = version +
1387 		    ztest_random(SPA_VERSION_BEFORE_FEATURES - version + 1);
1388 	}
1389 
1390 	if (version > SPA_VERSION_BEFORE_FEATURES)
1391 		version = SPA_VERSION_FEATURES;
1392 
1393 	ASSERT(SPA_VERSION_IS_SUPPORTED(version));
1394 	return (version);
1395 }
1396 
1397 static int
ztest_random_blocksize(void)1398 ztest_random_blocksize(void)
1399 {
1400 	ASSERT3U(ztest_spa->spa_max_ashift, !=, 0);
1401 
1402 	/*
1403 	 * Choose a block size >= the ashift.
1404 	 * If the SPA supports new MAXBLOCKSIZE, test up to 1MB blocks.
1405 	 */
1406 	int maxbs = SPA_OLD_MAXBLOCKSHIFT;
1407 	if (spa_maxblocksize(ztest_spa) == SPA_MAXBLOCKSIZE)
1408 		maxbs = 20;
1409 	uint64_t block_shift =
1410 	    ztest_random(maxbs - ztest_spa->spa_max_ashift + 1);
1411 	return (1 << (SPA_MINBLOCKSHIFT + block_shift));
1412 }
1413 
1414 static int
ztest_random_dnodesize(void)1415 ztest_random_dnodesize(void)
1416 {
1417 	int slots;
1418 	int max_slots = spa_maxdnodesize(ztest_spa) >> DNODE_SHIFT;
1419 
1420 	if (max_slots == DNODE_MIN_SLOTS)
1421 		return (DNODE_MIN_SIZE);
1422 
1423 	/*
1424 	 * Weight the random distribution more heavily toward smaller
1425 	 * dnode sizes since that is more likely to reflect real-world
1426 	 * usage.
1427 	 */
1428 	ASSERT3U(max_slots, >, 4);
1429 	switch (ztest_random(10)) {
1430 	case 0:
1431 		slots = 5 + ztest_random(max_slots - 4);
1432 		break;
1433 	case 1 ... 4:
1434 		slots = 2 + ztest_random(3);
1435 		break;
1436 	default:
1437 		slots = 1;
1438 		break;
1439 	}
1440 
1441 	return (slots << DNODE_SHIFT);
1442 }
1443 
1444 static int
ztest_random_ibshift(void)1445 ztest_random_ibshift(void)
1446 {
1447 	return (DN_MIN_INDBLKSHIFT +
1448 	    ztest_random(DN_MAX_INDBLKSHIFT - DN_MIN_INDBLKSHIFT + 1));
1449 }
1450 
1451 static uint64_t
ztest_random_vdev_top(spa_t * spa,boolean_t log_ok)1452 ztest_random_vdev_top(spa_t *spa, boolean_t log_ok)
1453 {
1454 	uint64_t top;
1455 	vdev_t *rvd = spa->spa_root_vdev;
1456 	vdev_t *tvd;
1457 
1458 	ASSERT3U(spa_config_held(spa, SCL_ALL, RW_READER), !=, 0);
1459 
1460 	do {
1461 		top = ztest_random(rvd->vdev_children);
1462 		tvd = rvd->vdev_child[top];
1463 	} while (!vdev_is_concrete(tvd) || (tvd->vdev_islog && !log_ok) ||
1464 	    tvd->vdev_mg == NULL || tvd->vdev_mg->mg_class == NULL);
1465 
1466 	return (top);
1467 }
1468 
1469 static uint64_t
ztest_random_dsl_prop(zfs_prop_t prop)1470 ztest_random_dsl_prop(zfs_prop_t prop)
1471 {
1472 	uint64_t value;
1473 
1474 	do {
1475 		value = zfs_prop_random_value(prop, ztest_random(-1ULL));
1476 	} while (prop == ZFS_PROP_CHECKSUM && value == ZIO_CHECKSUM_OFF);
1477 
1478 	return (value);
1479 }
1480 
1481 static int
ztest_dsl_prop_set_uint64(char * osname,zfs_prop_t prop,uint64_t value,boolean_t inherit)1482 ztest_dsl_prop_set_uint64(char *osname, zfs_prop_t prop, uint64_t value,
1483     boolean_t inherit)
1484 {
1485 	const char *propname = zfs_prop_to_name(prop);
1486 	const char *valname;
1487 	char *setpoint;
1488 	uint64_t curval;
1489 	int error;
1490 
1491 	error = dsl_prop_set_int(osname, propname,
1492 	    (inherit ? ZPROP_SRC_NONE : ZPROP_SRC_LOCAL), value);
1493 
1494 	if (error == ENOSPC) {
1495 		ztest_record_enospc(FTAG);
1496 		return (error);
1497 	}
1498 	ASSERT0(error);
1499 
1500 	setpoint = umem_alloc(MAXPATHLEN, UMEM_NOFAIL);
1501 	VERIFY0(dsl_prop_get_integer(osname, propname, &curval, setpoint));
1502 
1503 	if (ztest_opts.zo_verbose >= 6) {
1504 		int err;
1505 
1506 		err = zfs_prop_index_to_string(prop, curval, &valname);
1507 		if (err)
1508 			(void) printf("%s %s = %llu at '%s'\n", osname,
1509 			    propname, (unsigned long long)curval, setpoint);
1510 		else
1511 			(void) printf("%s %s = %s at '%s'\n",
1512 			    osname, propname, valname, setpoint);
1513 	}
1514 	umem_free(setpoint, MAXPATHLEN);
1515 
1516 	return (error);
1517 }
1518 
1519 static int
ztest_spa_prop_set_uint64(zpool_prop_t prop,uint64_t value)1520 ztest_spa_prop_set_uint64(zpool_prop_t prop, uint64_t value)
1521 {
1522 	spa_t *spa = ztest_spa;
1523 	nvlist_t *props = NULL;
1524 	int error;
1525 
1526 	props = fnvlist_alloc();
1527 	fnvlist_add_uint64(props, zpool_prop_to_name(prop), value);
1528 
1529 	error = spa_prop_set(spa, props);
1530 
1531 	fnvlist_free(props);
1532 
1533 	if (error == ENOSPC) {
1534 		ztest_record_enospc(FTAG);
1535 		return (error);
1536 	}
1537 	ASSERT0(error);
1538 
1539 	return (error);
1540 }
1541 
1542 static int
ztest_dmu_objset_own(const char * name,dmu_objset_type_t type,boolean_t readonly,boolean_t decrypt,const void * tag,objset_t ** osp)1543 ztest_dmu_objset_own(const char *name, dmu_objset_type_t type,
1544     boolean_t readonly, boolean_t decrypt, const void *tag, objset_t **osp)
1545 {
1546 	int err;
1547 	char *cp = NULL;
1548 	char ddname[ZFS_MAX_DATASET_NAME_LEN];
1549 
1550 	strlcpy(ddname, name, sizeof (ddname));
1551 	cp = strchr(ddname, '@');
1552 	if (cp != NULL)
1553 		*cp = '\0';
1554 
1555 	err = dmu_objset_own(name, type, readonly, decrypt, tag, osp);
1556 	while (decrypt && err == EACCES) {
1557 		dsl_crypto_params_t *dcp;
1558 		nvlist_t *crypto_args = fnvlist_alloc();
1559 
1560 		fnvlist_add_uint8_array(crypto_args, "wkeydata",
1561 		    (uint8_t *)ztest_wkeydata, WRAPPING_KEY_LEN);
1562 		VERIFY0(dsl_crypto_params_create_nvlist(DCP_CMD_NONE, NULL,
1563 		    crypto_args, &dcp));
1564 		err = spa_keystore_load_wkey(ddname, dcp, B_FALSE);
1565 		/*
1566 		 * Note: if there was an error loading, the wkey was not
1567 		 * consumed, and needs to be freed.
1568 		 */
1569 		dsl_crypto_params_free(dcp, (err != 0));
1570 		fnvlist_free(crypto_args);
1571 
1572 		if (err == EINVAL) {
1573 			/*
1574 			 * We couldn't load a key for this dataset so try
1575 			 * the parent. This loop will eventually hit the
1576 			 * encryption root since ztest only makes clones
1577 			 * as children of their origin datasets.
1578 			 */
1579 			cp = strrchr(ddname, '/');
1580 			if (cp == NULL)
1581 				return (err);
1582 
1583 			*cp = '\0';
1584 			err = EACCES;
1585 			continue;
1586 		} else if (err != 0) {
1587 			break;
1588 		}
1589 
1590 		err = dmu_objset_own(name, type, readonly, decrypt, tag, osp);
1591 		break;
1592 	}
1593 
1594 	return (err);
1595 }
1596 
1597 static void
ztest_rll_init(rll_t * rll)1598 ztest_rll_init(rll_t *rll)
1599 {
1600 	rll->rll_writer = NULL;
1601 	rll->rll_readers = 0;
1602 	mutex_init(&rll->rll_lock, NULL, MUTEX_DEFAULT, NULL);
1603 	cv_init(&rll->rll_cv, NULL, CV_DEFAULT, NULL);
1604 }
1605 
1606 static void
ztest_rll_destroy(rll_t * rll)1607 ztest_rll_destroy(rll_t *rll)
1608 {
1609 	ASSERT3P(rll->rll_writer, ==, NULL);
1610 	ASSERT0(rll->rll_readers);
1611 	mutex_destroy(&rll->rll_lock);
1612 	cv_destroy(&rll->rll_cv);
1613 }
1614 
1615 static void
ztest_rll_lock(rll_t * rll,rl_type_t type)1616 ztest_rll_lock(rll_t *rll, rl_type_t type)
1617 {
1618 	mutex_enter(&rll->rll_lock);
1619 
1620 	if (type == RL_READER) {
1621 		while (rll->rll_writer != NULL)
1622 			(void) cv_wait(&rll->rll_cv, &rll->rll_lock);
1623 		rll->rll_readers++;
1624 	} else {
1625 		while (rll->rll_writer != NULL || rll->rll_readers)
1626 			(void) cv_wait(&rll->rll_cv, &rll->rll_lock);
1627 		rll->rll_writer = curthread;
1628 	}
1629 
1630 	mutex_exit(&rll->rll_lock);
1631 }
1632 
1633 static void
ztest_rll_unlock(rll_t * rll)1634 ztest_rll_unlock(rll_t *rll)
1635 {
1636 	mutex_enter(&rll->rll_lock);
1637 
1638 	if (rll->rll_writer) {
1639 		ASSERT0(rll->rll_readers);
1640 		rll->rll_writer = NULL;
1641 	} else {
1642 		ASSERT3S(rll->rll_readers, >, 0);
1643 		ASSERT3P(rll->rll_writer, ==, NULL);
1644 		rll->rll_readers--;
1645 	}
1646 
1647 	if (rll->rll_writer == NULL && rll->rll_readers == 0)
1648 		cv_broadcast(&rll->rll_cv);
1649 
1650 	mutex_exit(&rll->rll_lock);
1651 }
1652 
1653 static void
ztest_object_lock(ztest_ds_t * zd,uint64_t object,rl_type_t type)1654 ztest_object_lock(ztest_ds_t *zd, uint64_t object, rl_type_t type)
1655 {
1656 	rll_t *rll = &zd->zd_object_lock[object & (ZTEST_OBJECT_LOCKS - 1)];
1657 
1658 	ztest_rll_lock(rll, type);
1659 }
1660 
1661 static void
ztest_object_unlock(ztest_ds_t * zd,uint64_t object)1662 ztest_object_unlock(ztest_ds_t *zd, uint64_t object)
1663 {
1664 	rll_t *rll = &zd->zd_object_lock[object & (ZTEST_OBJECT_LOCKS - 1)];
1665 
1666 	ztest_rll_unlock(rll);
1667 }
1668 
1669 static rl_t *
ztest_range_lock(ztest_ds_t * zd,uint64_t object,uint64_t offset,uint64_t size,rl_type_t type)1670 ztest_range_lock(ztest_ds_t *zd, uint64_t object, uint64_t offset,
1671     uint64_t size, rl_type_t type)
1672 {
1673 	uint64_t hash = object ^ (offset % (ZTEST_RANGE_LOCKS + 1));
1674 	rll_t *rll = &zd->zd_range_lock[hash & (ZTEST_RANGE_LOCKS - 1)];
1675 	rl_t *rl;
1676 
1677 	rl = umem_alloc(sizeof (*rl), UMEM_NOFAIL);
1678 	rl->rl_object = object;
1679 	rl->rl_offset = offset;
1680 	rl->rl_size = size;
1681 	rl->rl_lock = rll;
1682 
1683 	ztest_rll_lock(rll, type);
1684 
1685 	return (rl);
1686 }
1687 
1688 static void
ztest_range_unlock(rl_t * rl)1689 ztest_range_unlock(rl_t *rl)
1690 {
1691 	rll_t *rll = rl->rl_lock;
1692 
1693 	ztest_rll_unlock(rll);
1694 
1695 	umem_free(rl, sizeof (*rl));
1696 }
1697 
1698 static void
ztest_zd_init(ztest_ds_t * zd,ztest_shared_ds_t * szd,objset_t * os)1699 ztest_zd_init(ztest_ds_t *zd, ztest_shared_ds_t *szd, objset_t *os)
1700 {
1701 	zd->zd_os = os;
1702 	zd->zd_zilog = dmu_objset_zil(os);
1703 	zd->zd_shared = szd;
1704 	dmu_objset_name(os, zd->zd_name);
1705 	int l;
1706 
1707 	if (zd->zd_shared != NULL)
1708 		zd->zd_shared->zd_seq = 0;
1709 
1710 	VERIFY0(pthread_rwlock_init(&zd->zd_zilog_lock, NULL));
1711 	mutex_init(&zd->zd_dirobj_lock, NULL, MUTEX_DEFAULT, NULL);
1712 
1713 	for (l = 0; l < ZTEST_OBJECT_LOCKS; l++)
1714 		ztest_rll_init(&zd->zd_object_lock[l]);
1715 
1716 	for (l = 0; l < ZTEST_RANGE_LOCKS; l++)
1717 		ztest_rll_init(&zd->zd_range_lock[l]);
1718 }
1719 
1720 static void
ztest_zd_fini(ztest_ds_t * zd)1721 ztest_zd_fini(ztest_ds_t *zd)
1722 {
1723 	int l;
1724 
1725 	mutex_destroy(&zd->zd_dirobj_lock);
1726 	(void) pthread_rwlock_destroy(&zd->zd_zilog_lock);
1727 
1728 	for (l = 0; l < ZTEST_OBJECT_LOCKS; l++)
1729 		ztest_rll_destroy(&zd->zd_object_lock[l]);
1730 
1731 	for (l = 0; l < ZTEST_RANGE_LOCKS; l++)
1732 		ztest_rll_destroy(&zd->zd_range_lock[l]);
1733 }
1734 
1735 #define	TXG_MIGHTWAIT	(ztest_random(10) == 0 ? TXG_NOWAIT : TXG_WAIT)
1736 
1737 static uint64_t
ztest_tx_assign(dmu_tx_t * tx,uint64_t txg_how,const char * tag)1738 ztest_tx_assign(dmu_tx_t *tx, uint64_t txg_how, const char *tag)
1739 {
1740 	uint64_t txg;
1741 	int error;
1742 
1743 	/*
1744 	 * Attempt to assign tx to some transaction group.
1745 	 */
1746 	error = dmu_tx_assign(tx, txg_how);
1747 	if (error) {
1748 		if (error == ERESTART) {
1749 			ASSERT3U(txg_how, ==, TXG_NOWAIT);
1750 			dmu_tx_wait(tx);
1751 		} else {
1752 			ASSERT3U(error, ==, ENOSPC);
1753 			ztest_record_enospc(tag);
1754 		}
1755 		dmu_tx_abort(tx);
1756 		return (0);
1757 	}
1758 	txg = dmu_tx_get_txg(tx);
1759 	ASSERT3U(txg, !=, 0);
1760 	return (txg);
1761 }
1762 
1763 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)1764 ztest_bt_generate(ztest_block_tag_t *bt, objset_t *os, uint64_t object,
1765     uint64_t dnodesize, uint64_t offset, uint64_t gen, uint64_t txg,
1766     uint64_t crtxg)
1767 {
1768 	bt->bt_magic = BT_MAGIC;
1769 	bt->bt_objset = dmu_objset_id(os);
1770 	bt->bt_object = object;
1771 	bt->bt_dnodesize = dnodesize;
1772 	bt->bt_offset = offset;
1773 	bt->bt_gen = gen;
1774 	bt->bt_txg = txg;
1775 	bt->bt_crtxg = crtxg;
1776 }
1777 
1778 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)1779 ztest_bt_verify(ztest_block_tag_t *bt, objset_t *os, uint64_t object,
1780     uint64_t dnodesize, uint64_t offset, uint64_t gen, uint64_t txg,
1781     uint64_t crtxg)
1782 {
1783 	ASSERT3U(bt->bt_magic, ==, BT_MAGIC);
1784 	ASSERT3U(bt->bt_objset, ==, dmu_objset_id(os));
1785 	ASSERT3U(bt->bt_object, ==, object);
1786 	ASSERT3U(bt->bt_dnodesize, ==, dnodesize);
1787 	ASSERT3U(bt->bt_offset, ==, offset);
1788 	ASSERT3U(bt->bt_gen, <=, gen);
1789 	ASSERT3U(bt->bt_txg, <=, txg);
1790 	ASSERT3U(bt->bt_crtxg, ==, crtxg);
1791 }
1792 
1793 static ztest_block_tag_t *
ztest_bt_bonus(dmu_buf_t * db)1794 ztest_bt_bonus(dmu_buf_t *db)
1795 {
1796 	dmu_object_info_t doi;
1797 	ztest_block_tag_t *bt;
1798 
1799 	dmu_object_info_from_db(db, &doi);
1800 	ASSERT3U(doi.doi_bonus_size, <=, db->db_size);
1801 	ASSERT3U(doi.doi_bonus_size, >=, sizeof (*bt));
1802 	bt = (void *)((char *)db->db_data + doi.doi_bonus_size - sizeof (*bt));
1803 
1804 	return (bt);
1805 }
1806 
1807 /*
1808  * Generate a token to fill up unused bonus buffer space.  Try to make
1809  * it unique to the object, generation, and offset to verify that data
1810  * is not getting overwritten by data from other dnodes.
1811  */
1812 #define	ZTEST_BONUS_FILL_TOKEN(obj, ds, gen, offset) \
1813 	(((ds) << 48) | ((gen) << 32) | ((obj) << 8) | (offset))
1814 
1815 /*
1816  * Fill up the unused bonus buffer region before the block tag with a
1817  * verifiable pattern. Filling the whole bonus area with non-zero data
1818  * helps ensure that all dnode traversal code properly skips the
1819  * interior regions of large dnodes.
1820  */
1821 static void
ztest_fill_unused_bonus(dmu_buf_t * db,void * end,uint64_t obj,objset_t * os,uint64_t gen)1822 ztest_fill_unused_bonus(dmu_buf_t *db, void *end, uint64_t obj,
1823     objset_t *os, uint64_t gen)
1824 {
1825 	uint64_t *bonusp;
1826 
1827 	ASSERT(IS_P2ALIGNED((char *)end - (char *)db->db_data, 8));
1828 
1829 	for (bonusp = db->db_data; bonusp < (uint64_t *)end; bonusp++) {
1830 		uint64_t token = ZTEST_BONUS_FILL_TOKEN(obj, dmu_objset_id(os),
1831 		    gen, bonusp - (uint64_t *)db->db_data);
1832 		*bonusp = token;
1833 	}
1834 }
1835 
1836 /*
1837  * Verify that the unused area of a bonus buffer is filled with the
1838  * expected tokens.
1839  */
1840 static void
ztest_verify_unused_bonus(dmu_buf_t * db,void * end,uint64_t obj,objset_t * os,uint64_t gen)1841 ztest_verify_unused_bonus(dmu_buf_t *db, void *end, uint64_t obj,
1842     objset_t *os, uint64_t gen)
1843 {
1844 	uint64_t *bonusp;
1845 
1846 	for (bonusp = db->db_data; bonusp < (uint64_t *)end; bonusp++) {
1847 		uint64_t token = ZTEST_BONUS_FILL_TOKEN(obj, dmu_objset_id(os),
1848 		    gen, bonusp - (uint64_t *)db->db_data);
1849 		VERIFY3U(*bonusp, ==, token);
1850 	}
1851 }
1852 
1853 /*
1854  * ZIL logging ops
1855  */
1856 
1857 #define	lrz_type	lr_mode
1858 #define	lrz_blocksize	lr_uid
1859 #define	lrz_ibshift	lr_gid
1860 #define	lrz_bonustype	lr_rdev
1861 #define	lrz_dnodesize	lr_crtime[1]
1862 
1863 static void
ztest_log_create(ztest_ds_t * zd,dmu_tx_t * tx,lr_create_t * lr)1864 ztest_log_create(ztest_ds_t *zd, dmu_tx_t *tx, lr_create_t *lr)
1865 {
1866 	char *name = (char *)&lr->lr_data[0];		/* name follows lr */
1867 	size_t namesize = strlen(name) + 1;
1868 	itx_t *itx;
1869 
1870 	if (zil_replaying(zd->zd_zilog, tx))
1871 		return;
1872 
1873 	itx = zil_itx_create(TX_CREATE, sizeof (*lr) + namesize);
1874 	memcpy(&itx->itx_lr + 1, &lr->lr_create.lr_common + 1,
1875 	    sizeof (*lr) + namesize - sizeof (lr_t));
1876 
1877 	zil_itx_assign(zd->zd_zilog, itx, tx);
1878 }
1879 
1880 static void
ztest_log_remove(ztest_ds_t * zd,dmu_tx_t * tx,lr_remove_t * lr,uint64_t object)1881 ztest_log_remove(ztest_ds_t *zd, dmu_tx_t *tx, lr_remove_t *lr, uint64_t object)
1882 {
1883 	char *name = (char *)&lr->lr_data[0];		/* name follows lr */
1884 	size_t namesize = strlen(name) + 1;
1885 	itx_t *itx;
1886 
1887 	if (zil_replaying(zd->zd_zilog, tx))
1888 		return;
1889 
1890 	itx = zil_itx_create(TX_REMOVE, sizeof (*lr) + namesize);
1891 	memcpy(&itx->itx_lr + 1, &lr->lr_common + 1,
1892 	    sizeof (*lr) + namesize - sizeof (lr_t));
1893 
1894 	itx->itx_oid = object;
1895 	zil_itx_assign(zd->zd_zilog, itx, tx);
1896 }
1897 
1898 static void
ztest_log_write(ztest_ds_t * zd,dmu_tx_t * tx,lr_write_t * lr)1899 ztest_log_write(ztest_ds_t *zd, dmu_tx_t *tx, lr_write_t *lr)
1900 {
1901 	itx_t *itx;
1902 	itx_wr_state_t write_state = ztest_random(WR_NUM_STATES);
1903 
1904 	if (zil_replaying(zd->zd_zilog, tx))
1905 		return;
1906 
1907 	if (lr->lr_length > zil_max_log_data(zd->zd_zilog, sizeof (lr_write_t)))
1908 		write_state = WR_INDIRECT;
1909 
1910 	itx = zil_itx_create(TX_WRITE,
1911 	    sizeof (*lr) + (write_state == WR_COPIED ? lr->lr_length : 0));
1912 
1913 	if (write_state == WR_COPIED &&
1914 	    dmu_read(zd->zd_os, lr->lr_foid, lr->lr_offset, lr->lr_length,
1915 	    ((lr_write_t *)&itx->itx_lr) + 1, DMU_READ_NO_PREFETCH) != 0) {
1916 		zil_itx_destroy(itx);
1917 		itx = zil_itx_create(TX_WRITE, sizeof (*lr));
1918 		write_state = WR_NEED_COPY;
1919 	}
1920 	itx->itx_private = zd;
1921 	itx->itx_wr_state = write_state;
1922 	itx->itx_sync = (ztest_random(8) == 0);
1923 
1924 	memcpy(&itx->itx_lr + 1, &lr->lr_common + 1,
1925 	    sizeof (*lr) - sizeof (lr_t));
1926 
1927 	zil_itx_assign(zd->zd_zilog, itx, tx);
1928 }
1929 
1930 static void
ztest_log_truncate(ztest_ds_t * zd,dmu_tx_t * tx,lr_truncate_t * lr)1931 ztest_log_truncate(ztest_ds_t *zd, dmu_tx_t *tx, lr_truncate_t *lr)
1932 {
1933 	itx_t *itx;
1934 
1935 	if (zil_replaying(zd->zd_zilog, tx))
1936 		return;
1937 
1938 	itx = zil_itx_create(TX_TRUNCATE, sizeof (*lr));
1939 	memcpy(&itx->itx_lr + 1, &lr->lr_common + 1,
1940 	    sizeof (*lr) - sizeof (lr_t));
1941 
1942 	itx->itx_sync = B_FALSE;
1943 	zil_itx_assign(zd->zd_zilog, itx, tx);
1944 }
1945 
1946 static void
ztest_log_setattr(ztest_ds_t * zd,dmu_tx_t * tx,lr_setattr_t * lr)1947 ztest_log_setattr(ztest_ds_t *zd, dmu_tx_t *tx, lr_setattr_t *lr)
1948 {
1949 	itx_t *itx;
1950 
1951 	if (zil_replaying(zd->zd_zilog, tx))
1952 		return;
1953 
1954 	itx = zil_itx_create(TX_SETATTR, sizeof (*lr));
1955 	memcpy(&itx->itx_lr + 1, &lr->lr_common + 1,
1956 	    sizeof (*lr) - sizeof (lr_t));
1957 
1958 	itx->itx_sync = B_FALSE;
1959 	zil_itx_assign(zd->zd_zilog, itx, tx);
1960 }
1961 
1962 /*
1963  * ZIL replay ops
1964  */
1965 static int
ztest_replay_create(void * arg1,void * arg2,boolean_t byteswap)1966 ztest_replay_create(void *arg1, void *arg2, boolean_t byteswap)
1967 {
1968 	ztest_ds_t *zd = arg1;
1969 	lr_create_t *lrc = arg2;
1970 	_lr_create_t *lr = &lrc->lr_create;
1971 	char *name = (char *)&lrc->lr_data[0];		/* name follows lr */
1972 	objset_t *os = zd->zd_os;
1973 	ztest_block_tag_t *bbt;
1974 	dmu_buf_t *db;
1975 	dmu_tx_t *tx;
1976 	uint64_t txg;
1977 	int error = 0;
1978 	int bonuslen;
1979 
1980 	if (byteswap)
1981 		byteswap_uint64_array(lr, sizeof (*lr));
1982 
1983 	ASSERT3U(lr->lr_doid, ==, ZTEST_DIROBJ);
1984 	ASSERT3S(name[0], !=, '\0');
1985 
1986 	tx = dmu_tx_create(os);
1987 
1988 	dmu_tx_hold_zap(tx, lr->lr_doid, B_TRUE, name);
1989 
1990 	if (lr->lrz_type == DMU_OT_ZAP_OTHER) {
1991 		dmu_tx_hold_zap(tx, DMU_NEW_OBJECT, B_TRUE, NULL);
1992 	} else {
1993 		dmu_tx_hold_bonus(tx, DMU_NEW_OBJECT);
1994 	}
1995 
1996 	txg = ztest_tx_assign(tx, TXG_WAIT, FTAG);
1997 	if (txg == 0)
1998 		return (ENOSPC);
1999 
2000 	ASSERT3U(dmu_objset_zil(os)->zl_replay, ==, !!lr->lr_foid);
2001 	bonuslen = DN_BONUS_SIZE(lr->lrz_dnodesize);
2002 
2003 	if (lr->lrz_type == DMU_OT_ZAP_OTHER) {
2004 		if (lr->lr_foid == 0) {
2005 			lr->lr_foid = zap_create_dnsize(os,
2006 			    lr->lrz_type, lr->lrz_bonustype,
2007 			    bonuslen, lr->lrz_dnodesize, tx);
2008 		} else {
2009 			error = zap_create_claim_dnsize(os, lr->lr_foid,
2010 			    lr->lrz_type, lr->lrz_bonustype,
2011 			    bonuslen, lr->lrz_dnodesize, tx);
2012 		}
2013 	} else {
2014 		if (lr->lr_foid == 0) {
2015 			lr->lr_foid = dmu_object_alloc_dnsize(os,
2016 			    lr->lrz_type, 0, lr->lrz_bonustype,
2017 			    bonuslen, lr->lrz_dnodesize, tx);
2018 		} else {
2019 			error = dmu_object_claim_dnsize(os, lr->lr_foid,
2020 			    lr->lrz_type, 0, lr->lrz_bonustype,
2021 			    bonuslen, lr->lrz_dnodesize, tx);
2022 		}
2023 	}
2024 
2025 	if (error) {
2026 		ASSERT3U(error, ==, EEXIST);
2027 		ASSERT(zd->zd_zilog->zl_replay);
2028 		dmu_tx_commit(tx);
2029 		return (error);
2030 	}
2031 
2032 	ASSERT3U(lr->lr_foid, !=, 0);
2033 
2034 	if (lr->lrz_type != DMU_OT_ZAP_OTHER)
2035 		VERIFY0(dmu_object_set_blocksize(os, lr->lr_foid,
2036 		    lr->lrz_blocksize, lr->lrz_ibshift, tx));
2037 
2038 	VERIFY0(dmu_bonus_hold(os, lr->lr_foid, FTAG, &db));
2039 	bbt = ztest_bt_bonus(db);
2040 	dmu_buf_will_dirty(db, tx);
2041 	ztest_bt_generate(bbt, os, lr->lr_foid, lr->lrz_dnodesize, -1ULL,
2042 	    lr->lr_gen, txg, txg);
2043 	ztest_fill_unused_bonus(db, bbt, lr->lr_foid, os, lr->lr_gen);
2044 	dmu_buf_rele(db, FTAG);
2045 
2046 	VERIFY0(zap_add(os, lr->lr_doid, name, sizeof (uint64_t), 1,
2047 	    &lr->lr_foid, tx));
2048 
2049 	(void) ztest_log_create(zd, tx, lrc);
2050 
2051 	dmu_tx_commit(tx);
2052 
2053 	return (0);
2054 }
2055 
2056 static int
ztest_replay_remove(void * arg1,void * arg2,boolean_t byteswap)2057 ztest_replay_remove(void *arg1, void *arg2, boolean_t byteswap)
2058 {
2059 	ztest_ds_t *zd = arg1;
2060 	lr_remove_t *lr = arg2;
2061 	char *name = (char *)&lr->lr_data[0];		/* name follows lr */
2062 	objset_t *os = zd->zd_os;
2063 	dmu_object_info_t doi;
2064 	dmu_tx_t *tx;
2065 	uint64_t object, txg;
2066 
2067 	if (byteswap)
2068 		byteswap_uint64_array(lr, sizeof (*lr));
2069 
2070 	ASSERT3U(lr->lr_doid, ==, ZTEST_DIROBJ);
2071 	ASSERT3S(name[0], !=, '\0');
2072 
2073 	VERIFY0(
2074 	    zap_lookup(os, lr->lr_doid, name, sizeof (object), 1, &object));
2075 	ASSERT3U(object, !=, 0);
2076 
2077 	ztest_object_lock(zd, object, RL_WRITER);
2078 
2079 	VERIFY0(dmu_object_info(os, object, &doi));
2080 
2081 	tx = dmu_tx_create(os);
2082 
2083 	dmu_tx_hold_zap(tx, lr->lr_doid, B_FALSE, name);
2084 	dmu_tx_hold_free(tx, object, 0, DMU_OBJECT_END);
2085 
2086 	txg = ztest_tx_assign(tx, TXG_WAIT, FTAG);
2087 	if (txg == 0) {
2088 		ztest_object_unlock(zd, object);
2089 		return (ENOSPC);
2090 	}
2091 
2092 	if (doi.doi_type == DMU_OT_ZAP_OTHER) {
2093 		VERIFY0(zap_destroy(os, object, tx));
2094 	} else {
2095 		VERIFY0(dmu_object_free(os, object, tx));
2096 	}
2097 
2098 	VERIFY0(zap_remove(os, lr->lr_doid, name, tx));
2099 
2100 	(void) ztest_log_remove(zd, tx, lr, object);
2101 
2102 	dmu_tx_commit(tx);
2103 
2104 	ztest_object_unlock(zd, object);
2105 
2106 	return (0);
2107 }
2108 
2109 static int
ztest_replay_write(void * arg1,void * arg2,boolean_t byteswap)2110 ztest_replay_write(void *arg1, void *arg2, boolean_t byteswap)
2111 {
2112 	ztest_ds_t *zd = arg1;
2113 	lr_write_t *lr = arg2;
2114 	objset_t *os = zd->zd_os;
2115 	uint8_t *data = &lr->lr_data[0];		/* data follows lr */
2116 	uint64_t offset, length;
2117 	ztest_block_tag_t *bt = (ztest_block_tag_t *)data;
2118 	ztest_block_tag_t *bbt;
2119 	uint64_t gen, txg, lrtxg, crtxg;
2120 	dmu_object_info_t doi;
2121 	dmu_tx_t *tx;
2122 	dmu_buf_t *db;
2123 	arc_buf_t *abuf = NULL;
2124 	rl_t *rl;
2125 
2126 	if (byteswap)
2127 		byteswap_uint64_array(lr, sizeof (*lr));
2128 
2129 	offset = lr->lr_offset;
2130 	length = lr->lr_length;
2131 
2132 	/* If it's a dmu_sync() block, write the whole block */
2133 	if (lr->lr_common.lrc_reclen == sizeof (lr_write_t)) {
2134 		uint64_t blocksize = BP_GET_LSIZE(&lr->lr_blkptr);
2135 		if (length < blocksize) {
2136 			offset -= offset % blocksize;
2137 			length = blocksize;
2138 		}
2139 	}
2140 
2141 	if (bt->bt_magic == BSWAP_64(BT_MAGIC))
2142 		byteswap_uint64_array(bt, sizeof (*bt));
2143 
2144 	if (bt->bt_magic != BT_MAGIC)
2145 		bt = NULL;
2146 
2147 	ztest_object_lock(zd, lr->lr_foid, RL_READER);
2148 	rl = ztest_range_lock(zd, lr->lr_foid, offset, length, RL_WRITER);
2149 
2150 	VERIFY0(dmu_bonus_hold(os, lr->lr_foid, FTAG, &db));
2151 
2152 	dmu_object_info_from_db(db, &doi);
2153 
2154 	bbt = ztest_bt_bonus(db);
2155 	ASSERT3U(bbt->bt_magic, ==, BT_MAGIC);
2156 	gen = bbt->bt_gen;
2157 	crtxg = bbt->bt_crtxg;
2158 	lrtxg = lr->lr_common.lrc_txg;
2159 
2160 	tx = dmu_tx_create(os);
2161 
2162 	dmu_tx_hold_write(tx, lr->lr_foid, offset, length);
2163 
2164 	if (ztest_random(8) == 0 && length == doi.doi_data_block_size &&
2165 	    P2PHASE(offset, length) == 0)
2166 		abuf = dmu_request_arcbuf(db, length);
2167 
2168 	txg = ztest_tx_assign(tx, TXG_WAIT, FTAG);
2169 	if (txg == 0) {
2170 		if (abuf != NULL)
2171 			dmu_return_arcbuf(abuf);
2172 		dmu_buf_rele(db, FTAG);
2173 		ztest_range_unlock(rl);
2174 		ztest_object_unlock(zd, lr->lr_foid);
2175 		return (ENOSPC);
2176 	}
2177 
2178 	if (bt != NULL) {
2179 		/*
2180 		 * Usually, verify the old data before writing new data --
2181 		 * but not always, because we also want to verify correct
2182 		 * behavior when the data was not recently read into cache.
2183 		 */
2184 		ASSERT(doi.doi_data_block_size);
2185 		ASSERT0(offset % doi.doi_data_block_size);
2186 		if (ztest_random(4) != 0) {
2187 			int prefetch = ztest_random(2) ?
2188 			    DMU_READ_PREFETCH : DMU_READ_NO_PREFETCH;
2189 			ztest_block_tag_t rbt;
2190 
2191 			VERIFY(dmu_read(os, lr->lr_foid, offset,
2192 			    sizeof (rbt), &rbt, prefetch) == 0);
2193 			if (rbt.bt_magic == BT_MAGIC) {
2194 				ztest_bt_verify(&rbt, os, lr->lr_foid, 0,
2195 				    offset, gen, txg, crtxg);
2196 			}
2197 		}
2198 
2199 		/*
2200 		 * Writes can appear to be newer than the bonus buffer because
2201 		 * the ztest_get_data() callback does a dmu_read() of the
2202 		 * open-context data, which may be different than the data
2203 		 * as it was when the write was generated.
2204 		 */
2205 		if (zd->zd_zilog->zl_replay) {
2206 			ztest_bt_verify(bt, os, lr->lr_foid, 0, offset,
2207 			    MAX(gen, bt->bt_gen), MAX(txg, lrtxg),
2208 			    bt->bt_crtxg);
2209 		}
2210 
2211 		/*
2212 		 * Set the bt's gen/txg to the bonus buffer's gen/txg
2213 		 * so that all of the usual ASSERTs will work.
2214 		 */
2215 		ztest_bt_generate(bt, os, lr->lr_foid, 0, offset, gen, txg,
2216 		    crtxg);
2217 	}
2218 
2219 	if (abuf == NULL) {
2220 		dmu_write(os, lr->lr_foid, offset, length, data, tx);
2221 	} else {
2222 		memcpy(abuf->b_data, data, length);
2223 		VERIFY0(dmu_assign_arcbuf_by_dbuf(db, offset, abuf, tx));
2224 	}
2225 
2226 	(void) ztest_log_write(zd, tx, lr);
2227 
2228 	dmu_buf_rele(db, FTAG);
2229 
2230 	dmu_tx_commit(tx);
2231 
2232 	ztest_range_unlock(rl);
2233 	ztest_object_unlock(zd, lr->lr_foid);
2234 
2235 	return (0);
2236 }
2237 
2238 static int
ztest_replay_truncate(void * arg1,void * arg2,boolean_t byteswap)2239 ztest_replay_truncate(void *arg1, void *arg2, boolean_t byteswap)
2240 {
2241 	ztest_ds_t *zd = arg1;
2242 	lr_truncate_t *lr = arg2;
2243 	objset_t *os = zd->zd_os;
2244 	dmu_tx_t *tx;
2245 	uint64_t txg;
2246 	rl_t *rl;
2247 
2248 	if (byteswap)
2249 		byteswap_uint64_array(lr, sizeof (*lr));
2250 
2251 	ztest_object_lock(zd, lr->lr_foid, RL_READER);
2252 	rl = ztest_range_lock(zd, lr->lr_foid, lr->lr_offset, lr->lr_length,
2253 	    RL_WRITER);
2254 
2255 	tx = dmu_tx_create(os);
2256 
2257 	dmu_tx_hold_free(tx, lr->lr_foid, lr->lr_offset, lr->lr_length);
2258 
2259 	txg = ztest_tx_assign(tx, TXG_WAIT, FTAG);
2260 	if (txg == 0) {
2261 		ztest_range_unlock(rl);
2262 		ztest_object_unlock(zd, lr->lr_foid);
2263 		return (ENOSPC);
2264 	}
2265 
2266 	VERIFY0(dmu_free_range(os, lr->lr_foid, lr->lr_offset,
2267 	    lr->lr_length, tx));
2268 
2269 	(void) ztest_log_truncate(zd, tx, lr);
2270 
2271 	dmu_tx_commit(tx);
2272 
2273 	ztest_range_unlock(rl);
2274 	ztest_object_unlock(zd, lr->lr_foid);
2275 
2276 	return (0);
2277 }
2278 
2279 static int
ztest_replay_setattr(void * arg1,void * arg2,boolean_t byteswap)2280 ztest_replay_setattr(void *arg1, void *arg2, boolean_t byteswap)
2281 {
2282 	ztest_ds_t *zd = arg1;
2283 	lr_setattr_t *lr = arg2;
2284 	objset_t *os = zd->zd_os;
2285 	dmu_tx_t *tx;
2286 	dmu_buf_t *db;
2287 	ztest_block_tag_t *bbt;
2288 	uint64_t txg, lrtxg, crtxg, dnodesize;
2289 
2290 	if (byteswap)
2291 		byteswap_uint64_array(lr, sizeof (*lr));
2292 
2293 	ztest_object_lock(zd, lr->lr_foid, RL_WRITER);
2294 
2295 	VERIFY0(dmu_bonus_hold(os, lr->lr_foid, FTAG, &db));
2296 
2297 	tx = dmu_tx_create(os);
2298 	dmu_tx_hold_bonus(tx, lr->lr_foid);
2299 
2300 	txg = ztest_tx_assign(tx, TXG_WAIT, FTAG);
2301 	if (txg == 0) {
2302 		dmu_buf_rele(db, FTAG);
2303 		ztest_object_unlock(zd, lr->lr_foid);
2304 		return (ENOSPC);
2305 	}
2306 
2307 	bbt = ztest_bt_bonus(db);
2308 	ASSERT3U(bbt->bt_magic, ==, BT_MAGIC);
2309 	crtxg = bbt->bt_crtxg;
2310 	lrtxg = lr->lr_common.lrc_txg;
2311 	dnodesize = bbt->bt_dnodesize;
2312 
2313 	if (zd->zd_zilog->zl_replay) {
2314 		ASSERT3U(lr->lr_size, !=, 0);
2315 		ASSERT3U(lr->lr_mode, !=, 0);
2316 		ASSERT3U(lrtxg, !=, 0);
2317 	} else {
2318 		/*
2319 		 * Randomly change the size and increment the generation.
2320 		 */
2321 		lr->lr_size = (ztest_random(db->db_size / sizeof (*bbt)) + 1) *
2322 		    sizeof (*bbt);
2323 		lr->lr_mode = bbt->bt_gen + 1;
2324 		ASSERT0(lrtxg);
2325 	}
2326 
2327 	/*
2328 	 * Verify that the current bonus buffer is not newer than our txg.
2329 	 */
2330 	ztest_bt_verify(bbt, os, lr->lr_foid, dnodesize, -1ULL, lr->lr_mode,
2331 	    MAX(txg, lrtxg), crtxg);
2332 
2333 	dmu_buf_will_dirty(db, tx);
2334 
2335 	ASSERT3U(lr->lr_size, >=, sizeof (*bbt));
2336 	ASSERT3U(lr->lr_size, <=, db->db_size);
2337 	VERIFY0(dmu_set_bonus(db, lr->lr_size, tx));
2338 	bbt = ztest_bt_bonus(db);
2339 
2340 	ztest_bt_generate(bbt, os, lr->lr_foid, dnodesize, -1ULL, lr->lr_mode,
2341 	    txg, crtxg);
2342 	ztest_fill_unused_bonus(db, bbt, lr->lr_foid, os, bbt->bt_gen);
2343 	dmu_buf_rele(db, FTAG);
2344 
2345 	(void) ztest_log_setattr(zd, tx, lr);
2346 
2347 	dmu_tx_commit(tx);
2348 
2349 	ztest_object_unlock(zd, lr->lr_foid);
2350 
2351 	return (0);
2352 }
2353 
2354 static zil_replay_func_t *ztest_replay_vector[TX_MAX_TYPE] = {
2355 	NULL,			/* 0 no such transaction type */
2356 	ztest_replay_create,	/* TX_CREATE */
2357 	NULL,			/* TX_MKDIR */
2358 	NULL,			/* TX_MKXATTR */
2359 	NULL,			/* TX_SYMLINK */
2360 	ztest_replay_remove,	/* TX_REMOVE */
2361 	NULL,			/* TX_RMDIR */
2362 	NULL,			/* TX_LINK */
2363 	NULL,			/* TX_RENAME */
2364 	ztest_replay_write,	/* TX_WRITE */
2365 	ztest_replay_truncate,	/* TX_TRUNCATE */
2366 	ztest_replay_setattr,	/* TX_SETATTR */
2367 	NULL,			/* TX_ACL */
2368 	NULL,			/* TX_CREATE_ACL */
2369 	NULL,			/* TX_CREATE_ATTR */
2370 	NULL,			/* TX_CREATE_ACL_ATTR */
2371 	NULL,			/* TX_MKDIR_ACL */
2372 	NULL,			/* TX_MKDIR_ATTR */
2373 	NULL,			/* TX_MKDIR_ACL_ATTR */
2374 	NULL,			/* TX_WRITE2 */
2375 	NULL,			/* TX_SETSAXATTR */
2376 	NULL,			/* TX_RENAME_EXCHANGE */
2377 	NULL,			/* TX_RENAME_WHITEOUT */
2378 };
2379 
2380 /*
2381  * ZIL get_data callbacks
2382  */
2383 
2384 static void
ztest_get_done(zgd_t * zgd,int error)2385 ztest_get_done(zgd_t *zgd, int error)
2386 {
2387 	(void) error;
2388 	ztest_ds_t *zd = zgd->zgd_private;
2389 	uint64_t object = ((rl_t *)zgd->zgd_lr)->rl_object;
2390 
2391 	if (zgd->zgd_db)
2392 		dmu_buf_rele(zgd->zgd_db, zgd);
2393 
2394 	ztest_range_unlock((rl_t *)zgd->zgd_lr);
2395 	ztest_object_unlock(zd, object);
2396 
2397 	umem_free(zgd, sizeof (*zgd));
2398 }
2399 
2400 static int
ztest_get_data(void * arg,uint64_t arg2,lr_write_t * lr,char * buf,struct lwb * lwb,zio_t * zio)2401 ztest_get_data(void *arg, uint64_t arg2, lr_write_t *lr, char *buf,
2402     struct lwb *lwb, zio_t *zio)
2403 {
2404 	(void) arg2;
2405 	ztest_ds_t *zd = arg;
2406 	objset_t *os = zd->zd_os;
2407 	uint64_t object = lr->lr_foid;
2408 	uint64_t offset = lr->lr_offset;
2409 	uint64_t size = lr->lr_length;
2410 	uint64_t txg = lr->lr_common.lrc_txg;
2411 	uint64_t crtxg;
2412 	dmu_object_info_t doi;
2413 	dmu_buf_t *db;
2414 	zgd_t *zgd;
2415 	int error;
2416 
2417 	ASSERT3P(lwb, !=, NULL);
2418 	ASSERT3U(size, !=, 0);
2419 
2420 	ztest_object_lock(zd, object, RL_READER);
2421 	error = dmu_bonus_hold(os, object, FTAG, &db);
2422 	if (error) {
2423 		ztest_object_unlock(zd, object);
2424 		return (error);
2425 	}
2426 
2427 	crtxg = ztest_bt_bonus(db)->bt_crtxg;
2428 
2429 	if (crtxg == 0 || crtxg > txg) {
2430 		dmu_buf_rele(db, FTAG);
2431 		ztest_object_unlock(zd, object);
2432 		return (ENOENT);
2433 	}
2434 
2435 	dmu_object_info_from_db(db, &doi);
2436 	dmu_buf_rele(db, FTAG);
2437 	db = NULL;
2438 
2439 	zgd = umem_zalloc(sizeof (*zgd), UMEM_NOFAIL);
2440 	zgd->zgd_lwb = lwb;
2441 	zgd->zgd_private = zd;
2442 
2443 	if (buf != NULL) {	/* immediate write */
2444 		zgd->zgd_lr = (struct zfs_locked_range *)ztest_range_lock(zd,
2445 		    object, offset, size, RL_READER);
2446 
2447 		error = dmu_read(os, object, offset, size, buf,
2448 		    DMU_READ_NO_PREFETCH);
2449 		ASSERT0(error);
2450 	} else {
2451 		ASSERT3P(zio, !=, NULL);
2452 		size = doi.doi_data_block_size;
2453 		if (ISP2(size)) {
2454 			offset = P2ALIGN_TYPED(offset, size, uint64_t);
2455 		} else {
2456 			ASSERT3U(offset, <, size);
2457 			offset = 0;
2458 		}
2459 
2460 		zgd->zgd_lr = (struct zfs_locked_range *)ztest_range_lock(zd,
2461 		    object, offset, size, RL_READER);
2462 
2463 		error = dmu_buf_hold_noread(os, object, offset, zgd, &db);
2464 
2465 		if (error == 0) {
2466 			blkptr_t *bp = &lr->lr_blkptr;
2467 
2468 			zgd->zgd_db = db;
2469 			zgd->zgd_bp = bp;
2470 
2471 			ASSERT3U(db->db_offset, ==, offset);
2472 			ASSERT3U(db->db_size, ==, size);
2473 
2474 			error = dmu_sync(zio, lr->lr_common.lrc_txg,
2475 			    ztest_get_done, zgd);
2476 
2477 			if (error == 0)
2478 				return (0);
2479 		}
2480 	}
2481 
2482 	ztest_get_done(zgd, error);
2483 
2484 	return (error);
2485 }
2486 
2487 static void *
ztest_lr_alloc(size_t lrsize,char * name)2488 ztest_lr_alloc(size_t lrsize, char *name)
2489 {
2490 	char *lr;
2491 	size_t namesize = name ? strlen(name) + 1 : 0;
2492 
2493 	lr = umem_zalloc(lrsize + namesize, UMEM_NOFAIL);
2494 
2495 	if (name)
2496 		memcpy(lr + lrsize, name, namesize);
2497 
2498 	return (lr);
2499 }
2500 
2501 static void
ztest_lr_free(void * lr,size_t lrsize,char * name)2502 ztest_lr_free(void *lr, size_t lrsize, char *name)
2503 {
2504 	size_t namesize = name ? strlen(name) + 1 : 0;
2505 
2506 	umem_free(lr, lrsize + namesize);
2507 }
2508 
2509 /*
2510  * Lookup a bunch of objects.  Returns the number of objects not found.
2511  */
2512 static int
ztest_lookup(ztest_ds_t * zd,ztest_od_t * od,int count)2513 ztest_lookup(ztest_ds_t *zd, ztest_od_t *od, int count)
2514 {
2515 	int missing = 0;
2516 	int error;
2517 	int i;
2518 
2519 	ASSERT(MUTEX_HELD(&zd->zd_dirobj_lock));
2520 
2521 	for (i = 0; i < count; i++, od++) {
2522 		od->od_object = 0;
2523 		error = zap_lookup(zd->zd_os, od->od_dir, od->od_name,
2524 		    sizeof (uint64_t), 1, &od->od_object);
2525 		if (error) {
2526 			ASSERT3S(error, ==, ENOENT);
2527 			ASSERT0(od->od_object);
2528 			missing++;
2529 		} else {
2530 			dmu_buf_t *db;
2531 			ztest_block_tag_t *bbt;
2532 			dmu_object_info_t doi;
2533 
2534 			ASSERT3U(od->od_object, !=, 0);
2535 			ASSERT0(missing);	/* there should be no gaps */
2536 
2537 			ztest_object_lock(zd, od->od_object, RL_READER);
2538 			VERIFY0(dmu_bonus_hold(zd->zd_os, od->od_object,
2539 			    FTAG, &db));
2540 			dmu_object_info_from_db(db, &doi);
2541 			bbt = ztest_bt_bonus(db);
2542 			ASSERT3U(bbt->bt_magic, ==, BT_MAGIC);
2543 			od->od_type = doi.doi_type;
2544 			od->od_blocksize = doi.doi_data_block_size;
2545 			od->od_gen = bbt->bt_gen;
2546 			dmu_buf_rele(db, FTAG);
2547 			ztest_object_unlock(zd, od->od_object);
2548 		}
2549 	}
2550 
2551 	return (missing);
2552 }
2553 
2554 static int
ztest_create(ztest_ds_t * zd,ztest_od_t * od,int count)2555 ztest_create(ztest_ds_t *zd, ztest_od_t *od, int count)
2556 {
2557 	int missing = 0;
2558 	int i;
2559 
2560 	ASSERT(MUTEX_HELD(&zd->zd_dirobj_lock));
2561 
2562 	for (i = 0; i < count; i++, od++) {
2563 		if (missing) {
2564 			od->od_object = 0;
2565 			missing++;
2566 			continue;
2567 		}
2568 
2569 		lr_create_t *lrc = ztest_lr_alloc(sizeof (*lrc), od->od_name);
2570 		_lr_create_t *lr = &lrc->lr_create;
2571 
2572 		lr->lr_doid = od->od_dir;
2573 		lr->lr_foid = 0;	/* 0 to allocate, > 0 to claim */
2574 		lr->lrz_type = od->od_crtype;
2575 		lr->lrz_blocksize = od->od_crblocksize;
2576 		lr->lrz_ibshift = ztest_random_ibshift();
2577 		lr->lrz_bonustype = DMU_OT_UINT64_OTHER;
2578 		lr->lrz_dnodesize = od->od_crdnodesize;
2579 		lr->lr_gen = od->od_crgen;
2580 		lr->lr_crtime[0] = time(NULL);
2581 
2582 		if (ztest_replay_create(zd, lr, B_FALSE) != 0) {
2583 			ASSERT0(missing);
2584 			od->od_object = 0;
2585 			missing++;
2586 		} else {
2587 			od->od_object = lr->lr_foid;
2588 			od->od_type = od->od_crtype;
2589 			od->od_blocksize = od->od_crblocksize;
2590 			od->od_gen = od->od_crgen;
2591 			ASSERT3U(od->od_object, !=, 0);
2592 		}
2593 
2594 		ztest_lr_free(lr, sizeof (*lr), od->od_name);
2595 	}
2596 
2597 	return (missing);
2598 }
2599 
2600 static int
ztest_remove(ztest_ds_t * zd,ztest_od_t * od,int count)2601 ztest_remove(ztest_ds_t *zd, ztest_od_t *od, int count)
2602 {
2603 	int missing = 0;
2604 	int error;
2605 	int i;
2606 
2607 	ASSERT(MUTEX_HELD(&zd->zd_dirobj_lock));
2608 
2609 	od += count - 1;
2610 
2611 	for (i = count - 1; i >= 0; i--, od--) {
2612 		if (missing) {
2613 			missing++;
2614 			continue;
2615 		}
2616 
2617 		/*
2618 		 * No object was found.
2619 		 */
2620 		if (od->od_object == 0)
2621 			continue;
2622 
2623 		lr_remove_t *lr = ztest_lr_alloc(sizeof (*lr), od->od_name);
2624 
2625 		lr->lr_doid = od->od_dir;
2626 
2627 		if ((error = ztest_replay_remove(zd, lr, B_FALSE)) != 0) {
2628 			ASSERT3U(error, ==, ENOSPC);
2629 			missing++;
2630 		} else {
2631 			od->od_object = 0;
2632 		}
2633 		ztest_lr_free(lr, sizeof (*lr), od->od_name);
2634 	}
2635 
2636 	return (missing);
2637 }
2638 
2639 static int
ztest_write(ztest_ds_t * zd,uint64_t object,uint64_t offset,uint64_t size,void * data)2640 ztest_write(ztest_ds_t *zd, uint64_t object, uint64_t offset, uint64_t size,
2641     void *data)
2642 {
2643 	lr_write_t *lr;
2644 	int error;
2645 
2646 	lr = ztest_lr_alloc(sizeof (*lr) + size, NULL);
2647 
2648 	lr->lr_foid = object;
2649 	lr->lr_offset = offset;
2650 	lr->lr_length = size;
2651 	lr->lr_blkoff = 0;
2652 	BP_ZERO(&lr->lr_blkptr);
2653 
2654 	memcpy(&lr->lr_data[0], data, size);
2655 
2656 	error = ztest_replay_write(zd, lr, B_FALSE);
2657 
2658 	ztest_lr_free(lr, sizeof (*lr) + size, NULL);
2659 
2660 	return (error);
2661 }
2662 
2663 static int
ztest_truncate(ztest_ds_t * zd,uint64_t object,uint64_t offset,uint64_t size)2664 ztest_truncate(ztest_ds_t *zd, uint64_t object, uint64_t offset, uint64_t size)
2665 {
2666 	lr_truncate_t *lr;
2667 	int error;
2668 
2669 	lr = ztest_lr_alloc(sizeof (*lr), NULL);
2670 
2671 	lr->lr_foid = object;
2672 	lr->lr_offset = offset;
2673 	lr->lr_length = size;
2674 
2675 	error = ztest_replay_truncate(zd, lr, B_FALSE);
2676 
2677 	ztest_lr_free(lr, sizeof (*lr), NULL);
2678 
2679 	return (error);
2680 }
2681 
2682 static int
ztest_setattr(ztest_ds_t * zd,uint64_t object)2683 ztest_setattr(ztest_ds_t *zd, uint64_t object)
2684 {
2685 	lr_setattr_t *lr;
2686 	int error;
2687 
2688 	lr = ztest_lr_alloc(sizeof (*lr), NULL);
2689 
2690 	lr->lr_foid = object;
2691 	lr->lr_size = 0;
2692 	lr->lr_mode = 0;
2693 
2694 	error = ztest_replay_setattr(zd, lr, B_FALSE);
2695 
2696 	ztest_lr_free(lr, sizeof (*lr), NULL);
2697 
2698 	return (error);
2699 }
2700 
2701 static void
ztest_prealloc(ztest_ds_t * zd,uint64_t object,uint64_t offset,uint64_t size)2702 ztest_prealloc(ztest_ds_t *zd, uint64_t object, uint64_t offset, uint64_t size)
2703 {
2704 	objset_t *os = zd->zd_os;
2705 	dmu_tx_t *tx;
2706 	uint64_t txg;
2707 	rl_t *rl;
2708 
2709 	txg_wait_synced(dmu_objset_pool(os), 0);
2710 
2711 	ztest_object_lock(zd, object, RL_READER);
2712 	rl = ztest_range_lock(zd, object, offset, size, RL_WRITER);
2713 
2714 	tx = dmu_tx_create(os);
2715 
2716 	dmu_tx_hold_write(tx, object, offset, size);
2717 
2718 	txg = ztest_tx_assign(tx, TXG_WAIT, FTAG);
2719 
2720 	if (txg != 0) {
2721 		dmu_prealloc(os, object, offset, size, tx);
2722 		dmu_tx_commit(tx);
2723 		txg_wait_synced(dmu_objset_pool(os), txg);
2724 	} else {
2725 		(void) dmu_free_long_range(os, object, offset, size);
2726 	}
2727 
2728 	ztest_range_unlock(rl);
2729 	ztest_object_unlock(zd, object);
2730 }
2731 
2732 static void
ztest_io(ztest_ds_t * zd,uint64_t object,uint64_t offset)2733 ztest_io(ztest_ds_t *zd, uint64_t object, uint64_t offset)
2734 {
2735 	int err;
2736 	ztest_block_tag_t wbt;
2737 	dmu_object_info_t doi;
2738 	enum ztest_io_type io_type;
2739 	uint64_t blocksize;
2740 	void *data;
2741 
2742 	VERIFY0(dmu_object_info(zd->zd_os, object, &doi));
2743 	blocksize = doi.doi_data_block_size;
2744 	data = umem_alloc(blocksize, UMEM_NOFAIL);
2745 
2746 	/*
2747 	 * Pick an i/o type at random, biased toward writing block tags.
2748 	 */
2749 	io_type = ztest_random(ZTEST_IO_TYPES);
2750 	if (ztest_random(2) == 0)
2751 		io_type = ZTEST_IO_WRITE_TAG;
2752 
2753 	(void) pthread_rwlock_rdlock(&zd->zd_zilog_lock);
2754 
2755 	switch (io_type) {
2756 
2757 	case ZTEST_IO_WRITE_TAG:
2758 		ztest_bt_generate(&wbt, zd->zd_os, object, doi.doi_dnodesize,
2759 		    offset, 0, 0, 0);
2760 		(void) ztest_write(zd, object, offset, sizeof (wbt), &wbt);
2761 		break;
2762 
2763 	case ZTEST_IO_WRITE_PATTERN:
2764 		(void) memset(data, 'a' + (object + offset) % 5, blocksize);
2765 		if (ztest_random(2) == 0) {
2766 			/*
2767 			 * Induce fletcher2 collisions to ensure that
2768 			 * zio_ddt_collision() detects and resolves them
2769 			 * when using fletcher2-verify for deduplication.
2770 			 */
2771 			((uint64_t *)data)[0] ^= 1ULL << 63;
2772 			((uint64_t *)data)[4] ^= 1ULL << 63;
2773 		}
2774 		(void) ztest_write(zd, object, offset, blocksize, data);
2775 		break;
2776 
2777 	case ZTEST_IO_WRITE_ZEROES:
2778 		memset(data, 0, blocksize);
2779 		(void) ztest_write(zd, object, offset, blocksize, data);
2780 		break;
2781 
2782 	case ZTEST_IO_TRUNCATE:
2783 		(void) ztest_truncate(zd, object, offset, blocksize);
2784 		break;
2785 
2786 	case ZTEST_IO_SETATTR:
2787 		(void) ztest_setattr(zd, object);
2788 		break;
2789 	default:
2790 		break;
2791 
2792 	case ZTEST_IO_REWRITE:
2793 		(void) pthread_rwlock_rdlock(&ztest_name_lock);
2794 		err = ztest_dsl_prop_set_uint64(zd->zd_name,
2795 		    ZFS_PROP_CHECKSUM, spa_dedup_checksum(ztest_spa),
2796 		    B_FALSE);
2797 		ASSERT(err == 0 || err == ENOSPC);
2798 		err = ztest_dsl_prop_set_uint64(zd->zd_name,
2799 		    ZFS_PROP_COMPRESSION,
2800 		    ztest_random_dsl_prop(ZFS_PROP_COMPRESSION),
2801 		    B_FALSE);
2802 		ASSERT(err == 0 || err == ENOSPC);
2803 		(void) pthread_rwlock_unlock(&ztest_name_lock);
2804 
2805 		VERIFY0(dmu_read(zd->zd_os, object, offset, blocksize, data,
2806 		    DMU_READ_NO_PREFETCH));
2807 
2808 		(void) ztest_write(zd, object, offset, blocksize, data);
2809 		break;
2810 	}
2811 
2812 	(void) pthread_rwlock_unlock(&zd->zd_zilog_lock);
2813 
2814 	umem_free(data, blocksize);
2815 }
2816 
2817 /*
2818  * Initialize an object description template.
2819  */
2820 static void
ztest_od_init(ztest_od_t * od,uint64_t id,const char * tag,uint64_t index,dmu_object_type_t type,uint64_t blocksize,uint64_t dnodesize,uint64_t gen)2821 ztest_od_init(ztest_od_t *od, uint64_t id, const char *tag, uint64_t index,
2822     dmu_object_type_t type, uint64_t blocksize, uint64_t dnodesize,
2823     uint64_t gen)
2824 {
2825 	od->od_dir = ZTEST_DIROBJ;
2826 	od->od_object = 0;
2827 
2828 	od->od_crtype = type;
2829 	od->od_crblocksize = blocksize ? blocksize : ztest_random_blocksize();
2830 	od->od_crdnodesize = dnodesize ? dnodesize : ztest_random_dnodesize();
2831 	od->od_crgen = gen;
2832 
2833 	od->od_type = DMU_OT_NONE;
2834 	od->od_blocksize = 0;
2835 	od->od_gen = 0;
2836 
2837 	(void) snprintf(od->od_name, sizeof (od->od_name),
2838 	    "%s(%"PRId64")[%"PRIu64"]",
2839 	    tag, id, index);
2840 }
2841 
2842 /*
2843  * Lookup or create the objects for a test using the od template.
2844  * If the objects do not all exist, or if 'remove' is specified,
2845  * remove any existing objects and create new ones.  Otherwise,
2846  * use the existing objects.
2847  */
2848 static int
ztest_object_init(ztest_ds_t * zd,ztest_od_t * od,size_t size,boolean_t remove)2849 ztest_object_init(ztest_ds_t *zd, ztest_od_t *od, size_t size, boolean_t remove)
2850 {
2851 	int count = size / sizeof (*od);
2852 	int rv = 0;
2853 
2854 	mutex_enter(&zd->zd_dirobj_lock);
2855 	if ((ztest_lookup(zd, od, count) != 0 || remove) &&
2856 	    (ztest_remove(zd, od, count) != 0 ||
2857 	    ztest_create(zd, od, count) != 0))
2858 		rv = -1;
2859 	zd->zd_od = od;
2860 	mutex_exit(&zd->zd_dirobj_lock);
2861 
2862 	return (rv);
2863 }
2864 
2865 void
ztest_zil_commit(ztest_ds_t * zd,uint64_t id)2866 ztest_zil_commit(ztest_ds_t *zd, uint64_t id)
2867 {
2868 	(void) id;
2869 	zilog_t *zilog = zd->zd_zilog;
2870 
2871 	(void) pthread_rwlock_rdlock(&zd->zd_zilog_lock);
2872 
2873 	zil_commit(zilog, ztest_random(ZTEST_OBJECTS));
2874 
2875 	/*
2876 	 * Remember the committed values in zd, which is in parent/child
2877 	 * shared memory.  If we die, the next iteration of ztest_run()
2878 	 * will verify that the log really does contain this record.
2879 	 */
2880 	mutex_enter(&zilog->zl_lock);
2881 	ASSERT3P(zd->zd_shared, !=, NULL);
2882 	ASSERT3U(zd->zd_shared->zd_seq, <=, zilog->zl_commit_lr_seq);
2883 	zd->zd_shared->zd_seq = zilog->zl_commit_lr_seq;
2884 	mutex_exit(&zilog->zl_lock);
2885 
2886 	(void) pthread_rwlock_unlock(&zd->zd_zilog_lock);
2887 }
2888 
2889 /*
2890  * This function is designed to simulate the operations that occur during a
2891  * mount/unmount operation.  We hold the dataset across these operations in an
2892  * attempt to expose any implicit assumptions about ZIL management.
2893  */
2894 void
ztest_zil_remount(ztest_ds_t * zd,uint64_t id)2895 ztest_zil_remount(ztest_ds_t *zd, uint64_t id)
2896 {
2897 	(void) id;
2898 	objset_t *os = zd->zd_os;
2899 
2900 	/*
2901 	 * We hold the ztest_vdev_lock so we don't cause problems with
2902 	 * other threads that wish to remove a log device, such as
2903 	 * ztest_device_removal().
2904 	 */
2905 	mutex_enter(&ztest_vdev_lock);
2906 
2907 	/*
2908 	 * We grab the zd_dirobj_lock to ensure that no other thread is
2909 	 * updating the zil (i.e. adding in-memory log records) and the
2910 	 * zd_zilog_lock to block any I/O.
2911 	 */
2912 	mutex_enter(&zd->zd_dirobj_lock);
2913 	(void) pthread_rwlock_wrlock(&zd->zd_zilog_lock);
2914 
2915 	/* zfsvfs_teardown() */
2916 	zil_close(zd->zd_zilog);
2917 
2918 	/* zfsvfs_setup() */
2919 	VERIFY3P(zil_open(os, ztest_get_data, NULL), ==, zd->zd_zilog);
2920 	zil_replay(os, zd, ztest_replay_vector);
2921 
2922 	(void) pthread_rwlock_unlock(&zd->zd_zilog_lock);
2923 	mutex_exit(&zd->zd_dirobj_lock);
2924 	mutex_exit(&ztest_vdev_lock);
2925 }
2926 
2927 /*
2928  * Verify that we can't destroy an active pool, create an existing pool,
2929  * or create a pool with a bad vdev spec.
2930  */
2931 void
ztest_spa_create_destroy(ztest_ds_t * zd,uint64_t id)2932 ztest_spa_create_destroy(ztest_ds_t *zd, uint64_t id)
2933 {
2934 	(void) zd, (void) id;
2935 	ztest_shared_opts_t *zo = &ztest_opts;
2936 	spa_t *spa;
2937 	nvlist_t *nvroot;
2938 
2939 	if (zo->zo_mmp_test)
2940 		return;
2941 
2942 	/*
2943 	 * Attempt to create using a bad file.
2944 	 */
2945 	nvroot = make_vdev_root("/dev/bogus", NULL, NULL, 0, 0, NULL, 0, 0, 1);
2946 	VERIFY3U(ENOENT, ==,
2947 	    spa_create("ztest_bad_file", nvroot, NULL, NULL, NULL));
2948 	fnvlist_free(nvroot);
2949 
2950 	/*
2951 	 * Attempt to create using a bad mirror.
2952 	 */
2953 	nvroot = make_vdev_root("/dev/bogus", NULL, NULL, 0, 0, NULL, 0, 2, 1);
2954 	VERIFY3U(ENOENT, ==,
2955 	    spa_create("ztest_bad_mirror", nvroot, NULL, NULL, NULL));
2956 	fnvlist_free(nvroot);
2957 
2958 	/*
2959 	 * Attempt to create an existing pool.  It shouldn't matter
2960 	 * what's in the nvroot; we should fail with EEXIST.
2961 	 */
2962 	(void) pthread_rwlock_rdlock(&ztest_name_lock);
2963 	nvroot = make_vdev_root("/dev/bogus", NULL, NULL, 0, 0, NULL, 0, 0, 1);
2964 	VERIFY3U(EEXIST, ==,
2965 	    spa_create(zo->zo_pool, nvroot, NULL, NULL, NULL));
2966 	fnvlist_free(nvroot);
2967 
2968 	/*
2969 	 * We open a reference to the spa and then we try to export it
2970 	 * expecting one of the following errors:
2971 	 *
2972 	 * EBUSY
2973 	 *	Because of the reference we just opened.
2974 	 *
2975 	 * ZFS_ERR_EXPORT_IN_PROGRESS
2976 	 *	For the case that there is another ztest thread doing
2977 	 *	an export concurrently.
2978 	 */
2979 	VERIFY0(spa_open(zo->zo_pool, &spa, FTAG));
2980 	int error = spa_destroy(zo->zo_pool);
2981 	if (error != EBUSY && error != ZFS_ERR_EXPORT_IN_PROGRESS) {
2982 		fatal(B_FALSE, "spa_destroy(%s) returned unexpected value %d",
2983 		    spa->spa_name, error);
2984 	}
2985 	spa_close(spa, FTAG);
2986 
2987 	(void) pthread_rwlock_unlock(&ztest_name_lock);
2988 }
2989 
2990 /*
2991  * Start and then stop the MMP threads to ensure the startup and shutdown code
2992  * works properly.  Actual protection and property-related code tested via ZTS.
2993  */
2994 void
ztest_mmp_enable_disable(ztest_ds_t * zd,uint64_t id)2995 ztest_mmp_enable_disable(ztest_ds_t *zd, uint64_t id)
2996 {
2997 	(void) zd, (void) id;
2998 	ztest_shared_opts_t *zo = &ztest_opts;
2999 	spa_t *spa = ztest_spa;
3000 
3001 	if (zo->zo_mmp_test)
3002 		return;
3003 
3004 	/*
3005 	 * Since enabling MMP involves setting a property, it could not be done
3006 	 * while the pool is suspended.
3007 	 */
3008 	if (spa_suspended(spa))
3009 		return;
3010 
3011 	spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
3012 	mutex_enter(&spa->spa_props_lock);
3013 
3014 	zfs_multihost_fail_intervals = 0;
3015 
3016 	if (!spa_multihost(spa)) {
3017 		spa->spa_multihost = B_TRUE;
3018 		mmp_thread_start(spa);
3019 	}
3020 
3021 	mutex_exit(&spa->spa_props_lock);
3022 	spa_config_exit(spa, SCL_CONFIG, FTAG);
3023 
3024 	txg_wait_synced(spa_get_dsl(spa), 0);
3025 	mmp_signal_all_threads();
3026 	txg_wait_synced(spa_get_dsl(spa), 0);
3027 
3028 	spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
3029 	mutex_enter(&spa->spa_props_lock);
3030 
3031 	if (spa_multihost(spa)) {
3032 		mmp_thread_stop(spa);
3033 		spa->spa_multihost = B_FALSE;
3034 	}
3035 
3036 	mutex_exit(&spa->spa_props_lock);
3037 	spa_config_exit(spa, SCL_CONFIG, FTAG);
3038 }
3039 
3040 void
ztest_spa_upgrade(ztest_ds_t * zd,uint64_t id)3041 ztest_spa_upgrade(ztest_ds_t *zd, uint64_t id)
3042 {
3043 	(void) zd, (void) id;
3044 	spa_t *spa;
3045 	uint64_t initial_version = SPA_VERSION_INITIAL;
3046 	uint64_t version, newversion;
3047 	nvlist_t *nvroot, *props;
3048 	char *name;
3049 
3050 	if (ztest_opts.zo_mmp_test)
3051 		return;
3052 
3053 	/* dRAID added after feature flags, skip upgrade test. */
3054 	if (strcmp(ztest_opts.zo_raid_type, VDEV_TYPE_DRAID) == 0)
3055 		return;
3056 
3057 	mutex_enter(&ztest_vdev_lock);
3058 	name = kmem_asprintf("%s_upgrade", ztest_opts.zo_pool);
3059 
3060 	/*
3061 	 * Clean up from previous runs.
3062 	 */
3063 	(void) spa_destroy(name);
3064 
3065 	nvroot = make_vdev_root(NULL, NULL, name, ztest_opts.zo_vdev_size, 0,
3066 	    NULL, ztest_opts.zo_raid_children, ztest_opts.zo_mirrors, 1);
3067 
3068 	/*
3069 	 * If we're configuring a RAIDZ device then make sure that the
3070 	 * initial version is capable of supporting that feature.
3071 	 */
3072 	switch (ztest_opts.zo_raid_parity) {
3073 	case 0:
3074 	case 1:
3075 		initial_version = SPA_VERSION_INITIAL;
3076 		break;
3077 	case 2:
3078 		initial_version = SPA_VERSION_RAIDZ2;
3079 		break;
3080 	case 3:
3081 		initial_version = SPA_VERSION_RAIDZ3;
3082 		break;
3083 	}
3084 
3085 	/*
3086 	 * Create a pool with a spa version that can be upgraded. Pick
3087 	 * a value between initial_version and SPA_VERSION_BEFORE_FEATURES.
3088 	 */
3089 	do {
3090 		version = ztest_random_spa_version(initial_version);
3091 	} while (version > SPA_VERSION_BEFORE_FEATURES);
3092 
3093 	props = fnvlist_alloc();
3094 	fnvlist_add_uint64(props,
3095 	    zpool_prop_to_name(ZPOOL_PROP_VERSION), version);
3096 	VERIFY0(spa_create(name, nvroot, props, NULL, NULL));
3097 	fnvlist_free(nvroot);
3098 	fnvlist_free(props);
3099 
3100 	VERIFY0(spa_open(name, &spa, FTAG));
3101 	VERIFY3U(spa_version(spa), ==, version);
3102 	newversion = ztest_random_spa_version(version + 1);
3103 
3104 	if (ztest_opts.zo_verbose >= 4) {
3105 		(void) printf("upgrading spa version from "
3106 		    "%"PRIu64" to %"PRIu64"\n",
3107 		    version, newversion);
3108 	}
3109 
3110 	spa_upgrade(spa, newversion);
3111 	VERIFY3U(spa_version(spa), >, version);
3112 	VERIFY3U(spa_version(spa), ==, fnvlist_lookup_uint64(spa->spa_config,
3113 	    zpool_prop_to_name(ZPOOL_PROP_VERSION)));
3114 	spa_close(spa, FTAG);
3115 
3116 	kmem_strfree(name);
3117 	mutex_exit(&ztest_vdev_lock);
3118 }
3119 
3120 static void
ztest_spa_checkpoint(spa_t * spa)3121 ztest_spa_checkpoint(spa_t *spa)
3122 {
3123 	ASSERT(MUTEX_HELD(&ztest_checkpoint_lock));
3124 
3125 	int error = spa_checkpoint(spa->spa_name);
3126 
3127 	switch (error) {
3128 	case 0:
3129 	case ZFS_ERR_DEVRM_IN_PROGRESS:
3130 	case ZFS_ERR_DISCARDING_CHECKPOINT:
3131 	case ZFS_ERR_CHECKPOINT_EXISTS:
3132 		break;
3133 	case ENOSPC:
3134 		ztest_record_enospc(FTAG);
3135 		break;
3136 	default:
3137 		fatal(B_FALSE, "spa_checkpoint(%s) = %d", spa->spa_name, error);
3138 	}
3139 }
3140 
3141 static void
ztest_spa_discard_checkpoint(spa_t * spa)3142 ztest_spa_discard_checkpoint(spa_t *spa)
3143 {
3144 	ASSERT(MUTEX_HELD(&ztest_checkpoint_lock));
3145 
3146 	int error = spa_checkpoint_discard(spa->spa_name);
3147 
3148 	switch (error) {
3149 	case 0:
3150 	case ZFS_ERR_DISCARDING_CHECKPOINT:
3151 	case ZFS_ERR_NO_CHECKPOINT:
3152 		break;
3153 	default:
3154 		fatal(B_FALSE, "spa_discard_checkpoint(%s) = %d",
3155 		    spa->spa_name, error);
3156 	}
3157 
3158 }
3159 
3160 void
ztest_spa_checkpoint_create_discard(ztest_ds_t * zd,uint64_t id)3161 ztest_spa_checkpoint_create_discard(ztest_ds_t *zd, uint64_t id)
3162 {
3163 	(void) zd, (void) id;
3164 	spa_t *spa = ztest_spa;
3165 
3166 	mutex_enter(&ztest_checkpoint_lock);
3167 	if (ztest_random(2) == 0) {
3168 		ztest_spa_checkpoint(spa);
3169 	} else {
3170 		ztest_spa_discard_checkpoint(spa);
3171 	}
3172 	mutex_exit(&ztest_checkpoint_lock);
3173 }
3174 
3175 
3176 static vdev_t *
vdev_lookup_by_path(vdev_t * vd,const char * path)3177 vdev_lookup_by_path(vdev_t *vd, const char *path)
3178 {
3179 	vdev_t *mvd;
3180 	int c;
3181 
3182 	if (vd->vdev_path != NULL && strcmp(path, vd->vdev_path) == 0)
3183 		return (vd);
3184 
3185 	for (c = 0; c < vd->vdev_children; c++)
3186 		if ((mvd = vdev_lookup_by_path(vd->vdev_child[c], path)) !=
3187 		    NULL)
3188 			return (mvd);
3189 
3190 	return (NULL);
3191 }
3192 
3193 static int
spa_num_top_vdevs(spa_t * spa)3194 spa_num_top_vdevs(spa_t *spa)
3195 {
3196 	vdev_t *rvd = spa->spa_root_vdev;
3197 	ASSERT3U(spa_config_held(spa, SCL_VDEV, RW_READER), ==, SCL_VDEV);
3198 	return (rvd->vdev_children);
3199 }
3200 
3201 /*
3202  * Verify that vdev_add() works as expected.
3203  */
3204 void
ztest_vdev_add_remove(ztest_ds_t * zd,uint64_t id)3205 ztest_vdev_add_remove(ztest_ds_t *zd, uint64_t id)
3206 {
3207 	(void) zd, (void) id;
3208 	ztest_shared_t *zs = ztest_shared;
3209 	spa_t *spa = ztest_spa;
3210 	uint64_t leaves;
3211 	uint64_t guid;
3212 	nvlist_t *nvroot;
3213 	int error;
3214 
3215 	if (ztest_opts.zo_mmp_test)
3216 		return;
3217 
3218 	mutex_enter(&ztest_vdev_lock);
3219 	leaves = MAX(zs->zs_mirrors + zs->zs_splits, 1) *
3220 	    ztest_opts.zo_raid_children;
3221 
3222 	spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
3223 
3224 	ztest_shared->zs_vdev_next_leaf = spa_num_top_vdevs(spa) * leaves;
3225 
3226 	/*
3227 	 * If we have slogs then remove them 1/4 of the time.
3228 	 */
3229 	if (spa_has_slogs(spa) && ztest_random(4) == 0) {
3230 		metaslab_group_t *mg;
3231 
3232 		/*
3233 		 * find the first real slog in log allocation class
3234 		 */
3235 		mg =  spa_log_class(spa)->mc_allocator[0].mca_rotor;
3236 		while (!mg->mg_vd->vdev_islog)
3237 			mg = mg->mg_next;
3238 
3239 		guid = mg->mg_vd->vdev_guid;
3240 
3241 		spa_config_exit(spa, SCL_VDEV, FTAG);
3242 
3243 		/*
3244 		 * We have to grab the zs_name_lock as writer to
3245 		 * prevent a race between removing a slog (dmu_objset_find)
3246 		 * and destroying a dataset. Removing the slog will
3247 		 * grab a reference on the dataset which may cause
3248 		 * dsl_destroy_head() to fail with EBUSY thus
3249 		 * leaving the dataset in an inconsistent state.
3250 		 */
3251 		pthread_rwlock_wrlock(&ztest_name_lock);
3252 		error = spa_vdev_remove(spa, guid, B_FALSE);
3253 		pthread_rwlock_unlock(&ztest_name_lock);
3254 
3255 		switch (error) {
3256 		case 0:
3257 		case EEXIST:	/* Generic zil_reset() error */
3258 		case EBUSY:	/* Replay required */
3259 		case EACCES:	/* Crypto key not loaded */
3260 		case ZFS_ERR_CHECKPOINT_EXISTS:
3261 		case ZFS_ERR_DISCARDING_CHECKPOINT:
3262 			break;
3263 		default:
3264 			fatal(B_FALSE, "spa_vdev_remove() = %d", error);
3265 		}
3266 	} else {
3267 		spa_config_exit(spa, SCL_VDEV, FTAG);
3268 
3269 		/*
3270 		 * Make 1/4 of the devices be log devices
3271 		 */
3272 		nvroot = make_vdev_root(NULL, NULL, NULL,
3273 		    ztest_opts.zo_vdev_size, 0, (ztest_random(4) == 0) ?
3274 		    "log" : NULL, ztest_opts.zo_raid_children, zs->zs_mirrors,
3275 		    1);
3276 
3277 		error = spa_vdev_add(spa, nvroot, B_FALSE);
3278 		fnvlist_free(nvroot);
3279 
3280 		switch (error) {
3281 		case 0:
3282 			break;
3283 		case ENOSPC:
3284 			ztest_record_enospc("spa_vdev_add");
3285 			break;
3286 		default:
3287 			fatal(B_FALSE, "spa_vdev_add() = %d", error);
3288 		}
3289 	}
3290 
3291 	mutex_exit(&ztest_vdev_lock);
3292 }
3293 
3294 void
ztest_vdev_class_add(ztest_ds_t * zd,uint64_t id)3295 ztest_vdev_class_add(ztest_ds_t *zd, uint64_t id)
3296 {
3297 	(void) zd, (void) id;
3298 	ztest_shared_t *zs = ztest_shared;
3299 	spa_t *spa = ztest_spa;
3300 	uint64_t leaves;
3301 	nvlist_t *nvroot;
3302 	const char *class = (ztest_random(2) == 0) ?
3303 	    VDEV_ALLOC_BIAS_SPECIAL : VDEV_ALLOC_BIAS_DEDUP;
3304 	int error;
3305 
3306 	/*
3307 	 * By default add a special vdev 50% of the time
3308 	 */
3309 	if ((ztest_opts.zo_special_vdevs == ZTEST_VDEV_CLASS_OFF) ||
3310 	    (ztest_opts.zo_special_vdevs == ZTEST_VDEV_CLASS_RND &&
3311 	    ztest_random(2) == 0)) {
3312 		return;
3313 	}
3314 
3315 	mutex_enter(&ztest_vdev_lock);
3316 
3317 	/* Only test with mirrors */
3318 	if (zs->zs_mirrors < 2) {
3319 		mutex_exit(&ztest_vdev_lock);
3320 		return;
3321 	}
3322 
3323 	/* requires feature@allocation_classes */
3324 	if (!spa_feature_is_enabled(spa, SPA_FEATURE_ALLOCATION_CLASSES)) {
3325 		mutex_exit(&ztest_vdev_lock);
3326 		return;
3327 	}
3328 
3329 	leaves = MAX(zs->zs_mirrors + zs->zs_splits, 1) *
3330 	    ztest_opts.zo_raid_children;
3331 
3332 	spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
3333 	ztest_shared->zs_vdev_next_leaf = spa_num_top_vdevs(spa) * leaves;
3334 	spa_config_exit(spa, SCL_VDEV, FTAG);
3335 
3336 	nvroot = make_vdev_root(NULL, NULL, NULL, ztest_opts.zo_vdev_size, 0,
3337 	    class, ztest_opts.zo_raid_children, zs->zs_mirrors, 1);
3338 
3339 	error = spa_vdev_add(spa, nvroot, B_FALSE);
3340 	fnvlist_free(nvroot);
3341 
3342 	if (error == ENOSPC)
3343 		ztest_record_enospc("spa_vdev_add");
3344 	else if (error != 0)
3345 		fatal(B_FALSE, "spa_vdev_add() = %d", error);
3346 
3347 	/*
3348 	 * 50% of the time allow small blocks in the special class
3349 	 */
3350 	if (error == 0 &&
3351 	    spa_special_class(spa)->mc_groups == 1 && ztest_random(2) == 0) {
3352 		if (ztest_opts.zo_verbose >= 3)
3353 			(void) printf("Enabling special VDEV small blocks\n");
3354 		error = ztest_dsl_prop_set_uint64(zd->zd_name,
3355 		    ZFS_PROP_SPECIAL_SMALL_BLOCKS, 32768, B_FALSE);
3356 		ASSERT(error == 0 || error == ENOSPC);
3357 	}
3358 
3359 	mutex_exit(&ztest_vdev_lock);
3360 
3361 	if (ztest_opts.zo_verbose >= 3) {
3362 		metaslab_class_t *mc;
3363 
3364 		if (strcmp(class, VDEV_ALLOC_BIAS_SPECIAL) == 0)
3365 			mc = spa_special_class(spa);
3366 		else
3367 			mc = spa_dedup_class(spa);
3368 		(void) printf("Added a %s mirrored vdev (of %d)\n",
3369 		    class, (int)mc->mc_groups);
3370 	}
3371 }
3372 
3373 /*
3374  * Verify that adding/removing aux devices (l2arc, hot spare) works as expected.
3375  */
3376 void
ztest_vdev_aux_add_remove(ztest_ds_t * zd,uint64_t id)3377 ztest_vdev_aux_add_remove(ztest_ds_t *zd, uint64_t id)
3378 {
3379 	(void) zd, (void) id;
3380 	ztest_shared_t *zs = ztest_shared;
3381 	spa_t *spa = ztest_spa;
3382 	vdev_t *rvd = spa->spa_root_vdev;
3383 	spa_aux_vdev_t *sav;
3384 	const char *aux;
3385 	char *path;
3386 	uint64_t guid = 0;
3387 	int error, ignore_err = 0;
3388 
3389 	if (ztest_opts.zo_mmp_test)
3390 		return;
3391 
3392 	path = umem_alloc(MAXPATHLEN, UMEM_NOFAIL);
3393 
3394 	if (ztest_random(2) == 0) {
3395 		sav = &spa->spa_spares;
3396 		aux = ZPOOL_CONFIG_SPARES;
3397 	} else {
3398 		sav = &spa->spa_l2cache;
3399 		aux = ZPOOL_CONFIG_L2CACHE;
3400 	}
3401 
3402 	mutex_enter(&ztest_vdev_lock);
3403 
3404 	spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
3405 
3406 	if (sav->sav_count != 0 && ztest_random(4) == 0) {
3407 		/*
3408 		 * Pick a random device to remove.
3409 		 */
3410 		vdev_t *svd = sav->sav_vdevs[ztest_random(sav->sav_count)];
3411 
3412 		/* dRAID spares cannot be removed; try anyways to see ENOTSUP */
3413 		if (strstr(svd->vdev_path, VDEV_TYPE_DRAID) != NULL)
3414 			ignore_err = ENOTSUP;
3415 
3416 		guid = svd->vdev_guid;
3417 	} else {
3418 		/*
3419 		 * Find an unused device we can add.
3420 		 */
3421 		zs->zs_vdev_aux = 0;
3422 		for (;;) {
3423 			int c;
3424 			(void) snprintf(path, MAXPATHLEN, ztest_aux_template,
3425 			    ztest_opts.zo_dir, ztest_opts.zo_pool, aux,
3426 			    zs->zs_vdev_aux);
3427 			for (c = 0; c < sav->sav_count; c++)
3428 				if (strcmp(sav->sav_vdevs[c]->vdev_path,
3429 				    path) == 0)
3430 					break;
3431 			if (c == sav->sav_count &&
3432 			    vdev_lookup_by_path(rvd, path) == NULL)
3433 				break;
3434 			zs->zs_vdev_aux++;
3435 		}
3436 	}
3437 
3438 	spa_config_exit(spa, SCL_VDEV, FTAG);
3439 
3440 	if (guid == 0) {
3441 		/*
3442 		 * Add a new device.
3443 		 */
3444 		nvlist_t *nvroot = make_vdev_root(NULL, aux, NULL,
3445 		    (ztest_opts.zo_vdev_size * 5) / 4, 0, NULL, 0, 0, 1);
3446 		error = spa_vdev_add(spa, nvroot, B_FALSE);
3447 
3448 		switch (error) {
3449 		case 0:
3450 			break;
3451 		default:
3452 			fatal(B_FALSE, "spa_vdev_add(%p) = %d", nvroot, error);
3453 		}
3454 		fnvlist_free(nvroot);
3455 	} else {
3456 		/*
3457 		 * Remove an existing device.  Sometimes, dirty its
3458 		 * vdev state first to make sure we handle removal
3459 		 * of devices that have pending state changes.
3460 		 */
3461 		if (ztest_random(2) == 0)
3462 			(void) vdev_online(spa, guid, 0, NULL);
3463 
3464 		error = spa_vdev_remove(spa, guid, B_FALSE);
3465 
3466 		switch (error) {
3467 		case 0:
3468 		case EBUSY:
3469 		case ZFS_ERR_CHECKPOINT_EXISTS:
3470 		case ZFS_ERR_DISCARDING_CHECKPOINT:
3471 			break;
3472 		default:
3473 			if (error != ignore_err)
3474 				fatal(B_FALSE,
3475 				    "spa_vdev_remove(%"PRIu64") = %d",
3476 				    guid, error);
3477 		}
3478 	}
3479 
3480 	mutex_exit(&ztest_vdev_lock);
3481 
3482 	umem_free(path, MAXPATHLEN);
3483 }
3484 
3485 /*
3486  * split a pool if it has mirror tlvdevs
3487  */
3488 void
ztest_split_pool(ztest_ds_t * zd,uint64_t id)3489 ztest_split_pool(ztest_ds_t *zd, uint64_t id)
3490 {
3491 	(void) zd, (void) id;
3492 	ztest_shared_t *zs = ztest_shared;
3493 	spa_t *spa = ztest_spa;
3494 	vdev_t *rvd = spa->spa_root_vdev;
3495 	nvlist_t *tree, **child, *config, *split, **schild;
3496 	uint_t c, children, schildren = 0, lastlogid = 0;
3497 	int error = 0;
3498 
3499 	if (ztest_opts.zo_mmp_test)
3500 		return;
3501 
3502 	mutex_enter(&ztest_vdev_lock);
3503 
3504 	/* ensure we have a usable config; mirrors of raidz aren't supported */
3505 	if (zs->zs_mirrors < 3 || ztest_opts.zo_raid_children > 1) {
3506 		mutex_exit(&ztest_vdev_lock);
3507 		return;
3508 	}
3509 
3510 	/* clean up the old pool, if any */
3511 	(void) spa_destroy("splitp");
3512 
3513 	spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
3514 
3515 	/* generate a config from the existing config */
3516 	mutex_enter(&spa->spa_props_lock);
3517 	tree = fnvlist_lookup_nvlist(spa->spa_config, ZPOOL_CONFIG_VDEV_TREE);
3518 	mutex_exit(&spa->spa_props_lock);
3519 
3520 	VERIFY0(nvlist_lookup_nvlist_array(tree, ZPOOL_CONFIG_CHILDREN,
3521 	    &child, &children));
3522 
3523 	schild = umem_alloc(rvd->vdev_children * sizeof (nvlist_t *),
3524 	    UMEM_NOFAIL);
3525 	for (c = 0; c < children; c++) {
3526 		vdev_t *tvd = rvd->vdev_child[c];
3527 		nvlist_t **mchild;
3528 		uint_t mchildren;
3529 
3530 		if (tvd->vdev_islog || tvd->vdev_ops == &vdev_hole_ops) {
3531 			schild[schildren] = fnvlist_alloc();
3532 			fnvlist_add_string(schild[schildren],
3533 			    ZPOOL_CONFIG_TYPE, VDEV_TYPE_HOLE);
3534 			fnvlist_add_uint64(schild[schildren],
3535 			    ZPOOL_CONFIG_IS_HOLE, 1);
3536 			if (lastlogid == 0)
3537 				lastlogid = schildren;
3538 			++schildren;
3539 			continue;
3540 		}
3541 		lastlogid = 0;
3542 		VERIFY0(nvlist_lookup_nvlist_array(child[c],
3543 		    ZPOOL_CONFIG_CHILDREN, &mchild, &mchildren));
3544 		schild[schildren++] = fnvlist_dup(mchild[0]);
3545 	}
3546 
3547 	/* OK, create a config that can be used to split */
3548 	split = fnvlist_alloc();
3549 	fnvlist_add_string(split, ZPOOL_CONFIG_TYPE, VDEV_TYPE_ROOT);
3550 	fnvlist_add_nvlist_array(split, ZPOOL_CONFIG_CHILDREN,
3551 	    (const nvlist_t **)schild, lastlogid != 0 ? lastlogid : schildren);
3552 
3553 	config = fnvlist_alloc();
3554 	fnvlist_add_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, split);
3555 
3556 	for (c = 0; c < schildren; c++)
3557 		fnvlist_free(schild[c]);
3558 	umem_free(schild, rvd->vdev_children * sizeof (nvlist_t *));
3559 	fnvlist_free(split);
3560 
3561 	spa_config_exit(spa, SCL_VDEV, FTAG);
3562 
3563 	(void) pthread_rwlock_wrlock(&ztest_name_lock);
3564 	error = spa_vdev_split_mirror(spa, "splitp", config, NULL, B_FALSE);
3565 	(void) pthread_rwlock_unlock(&ztest_name_lock);
3566 
3567 	fnvlist_free(config);
3568 
3569 	if (error == 0) {
3570 		(void) printf("successful split - results:\n");
3571 		mutex_enter(&spa_namespace_lock);
3572 		show_pool_stats(spa);
3573 		show_pool_stats(spa_lookup("splitp"));
3574 		mutex_exit(&spa_namespace_lock);
3575 		++zs->zs_splits;
3576 		--zs->zs_mirrors;
3577 	}
3578 	mutex_exit(&ztest_vdev_lock);
3579 }
3580 
3581 /*
3582  * Verify that we can attach and detach devices.
3583  */
3584 void
ztest_vdev_attach_detach(ztest_ds_t * zd,uint64_t id)3585 ztest_vdev_attach_detach(ztest_ds_t *zd, uint64_t id)
3586 {
3587 	(void) zd, (void) id;
3588 	ztest_shared_t *zs = ztest_shared;
3589 	spa_t *spa = ztest_spa;
3590 	spa_aux_vdev_t *sav = &spa->spa_spares;
3591 	vdev_t *rvd = spa->spa_root_vdev;
3592 	vdev_t *oldvd, *newvd, *pvd;
3593 	nvlist_t *root;
3594 	uint64_t leaves;
3595 	uint64_t leaf, top;
3596 	uint64_t ashift = ztest_get_ashift();
3597 	uint64_t oldguid, pguid;
3598 	uint64_t oldsize, newsize;
3599 	char *oldpath, *newpath;
3600 	int replacing;
3601 	int oldvd_has_siblings = B_FALSE;
3602 	int newvd_is_spare = B_FALSE;
3603 	int newvd_is_dspare = B_FALSE;
3604 	int oldvd_is_log;
3605 	int oldvd_is_special;
3606 	int error, expected_error;
3607 
3608 	if (ztest_opts.zo_mmp_test)
3609 		return;
3610 
3611 	oldpath = umem_alloc(MAXPATHLEN, UMEM_NOFAIL);
3612 	newpath = umem_alloc(MAXPATHLEN, UMEM_NOFAIL);
3613 
3614 	mutex_enter(&ztest_vdev_lock);
3615 	leaves = MAX(zs->zs_mirrors, 1) * ztest_opts.zo_raid_children;
3616 
3617 	spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3618 
3619 	/*
3620 	 * If a vdev is in the process of being removed, its removal may
3621 	 * finish while we are in progress, leading to an unexpected error
3622 	 * value.  Don't bother trying to attach while we are in the middle
3623 	 * of removal.
3624 	 */
3625 	if (ztest_device_removal_active) {
3626 		spa_config_exit(spa, SCL_ALL, FTAG);
3627 		goto out;
3628 	}
3629 
3630 	/*
3631 	 * Decide whether to do an attach or a replace.
3632 	 */
3633 	replacing = ztest_random(2);
3634 
3635 	/*
3636 	 * Pick a random top-level vdev.
3637 	 */
3638 	top = ztest_random_vdev_top(spa, B_TRUE);
3639 
3640 	/*
3641 	 * Pick a random leaf within it.
3642 	 */
3643 	leaf = ztest_random(leaves);
3644 
3645 	/*
3646 	 * Locate this vdev.
3647 	 */
3648 	oldvd = rvd->vdev_child[top];
3649 
3650 	/* pick a child from the mirror */
3651 	if (zs->zs_mirrors >= 1) {
3652 		ASSERT3P(oldvd->vdev_ops, ==, &vdev_mirror_ops);
3653 		ASSERT3U(oldvd->vdev_children, >=, zs->zs_mirrors);
3654 		oldvd = oldvd->vdev_child[leaf / ztest_opts.zo_raid_children];
3655 	}
3656 
3657 	/* pick a child out of the raidz group */
3658 	if (ztest_opts.zo_raid_children > 1) {
3659 		if (strcmp(oldvd->vdev_ops->vdev_op_type, "raidz") == 0)
3660 			ASSERT3P(oldvd->vdev_ops, ==, &vdev_raidz_ops);
3661 		else
3662 			ASSERT3P(oldvd->vdev_ops, ==, &vdev_draid_ops);
3663 		ASSERT3U(oldvd->vdev_children, ==, ztest_opts.zo_raid_children);
3664 		oldvd = oldvd->vdev_child[leaf % ztest_opts.zo_raid_children];
3665 	}
3666 
3667 	/*
3668 	 * If we're already doing an attach or replace, oldvd may be a
3669 	 * mirror vdev -- in which case, pick a random child.
3670 	 */
3671 	while (oldvd->vdev_children != 0) {
3672 		oldvd_has_siblings = B_TRUE;
3673 		ASSERT3U(oldvd->vdev_children, >=, 2);
3674 		oldvd = oldvd->vdev_child[ztest_random(oldvd->vdev_children)];
3675 	}
3676 
3677 	oldguid = oldvd->vdev_guid;
3678 	oldsize = vdev_get_min_asize(oldvd);
3679 	oldvd_is_log = oldvd->vdev_top->vdev_islog;
3680 	oldvd_is_special =
3681 	    oldvd->vdev_top->vdev_alloc_bias == VDEV_BIAS_SPECIAL ||
3682 	    oldvd->vdev_top->vdev_alloc_bias == VDEV_BIAS_DEDUP;
3683 	(void) strlcpy(oldpath, oldvd->vdev_path, MAXPATHLEN);
3684 	pvd = oldvd->vdev_parent;
3685 	pguid = pvd->vdev_guid;
3686 
3687 	/*
3688 	 * If oldvd has siblings, then half of the time, detach it.  Prior
3689 	 * to the detach the pool is scrubbed in order to prevent creating
3690 	 * unrepairable blocks as a result of the data corruption injection.
3691 	 */
3692 	if (oldvd_has_siblings && ztest_random(2) == 0) {
3693 		spa_config_exit(spa, SCL_ALL, FTAG);
3694 
3695 		error = ztest_scrub_impl(spa);
3696 		if (error)
3697 			goto out;
3698 
3699 		error = spa_vdev_detach(spa, oldguid, pguid, B_FALSE);
3700 		if (error != 0 && error != ENODEV && error != EBUSY &&
3701 		    error != ENOTSUP && error != ZFS_ERR_CHECKPOINT_EXISTS &&
3702 		    error != ZFS_ERR_DISCARDING_CHECKPOINT)
3703 			fatal(B_FALSE, "detach (%s) returned %d",
3704 			    oldpath, error);
3705 		goto out;
3706 	}
3707 
3708 	/*
3709 	 * For the new vdev, choose with equal probability between the two
3710 	 * standard paths (ending in either 'a' or 'b') or a random hot spare.
3711 	 */
3712 	if (sav->sav_count != 0 && ztest_random(3) == 0) {
3713 		newvd = sav->sav_vdevs[ztest_random(sav->sav_count)];
3714 		newvd_is_spare = B_TRUE;
3715 
3716 		if (newvd->vdev_ops == &vdev_draid_spare_ops)
3717 			newvd_is_dspare = B_TRUE;
3718 
3719 		(void) strlcpy(newpath, newvd->vdev_path, MAXPATHLEN);
3720 	} else {
3721 		(void) snprintf(newpath, MAXPATHLEN, ztest_dev_template,
3722 		    ztest_opts.zo_dir, ztest_opts.zo_pool,
3723 		    top * leaves + leaf);
3724 		if (ztest_random(2) == 0)
3725 			newpath[strlen(newpath) - 1] = 'b';
3726 		newvd = vdev_lookup_by_path(rvd, newpath);
3727 	}
3728 
3729 	if (newvd) {
3730 		/*
3731 		 * Reopen to ensure the vdev's asize field isn't stale.
3732 		 */
3733 		vdev_reopen(newvd);
3734 		newsize = vdev_get_min_asize(newvd);
3735 	} else {
3736 		/*
3737 		 * Make newsize a little bigger or smaller than oldsize.
3738 		 * If it's smaller, the attach should fail.
3739 		 * If it's larger, and we're doing a replace,
3740 		 * we should get dynamic LUN growth when we're done.
3741 		 */
3742 		newsize = 10 * oldsize / (9 + ztest_random(3));
3743 	}
3744 
3745 	/*
3746 	 * If pvd is not a mirror or root, the attach should fail with ENOTSUP,
3747 	 * unless it's a replace; in that case any non-replacing parent is OK.
3748 	 *
3749 	 * If newvd is already part of the pool, it should fail with EBUSY.
3750 	 *
3751 	 * If newvd is too small, it should fail with EOVERFLOW.
3752 	 *
3753 	 * If newvd is a distributed spare and it's being attached to a
3754 	 * dRAID which is not its parent it should fail with EINVAL.
3755 	 */
3756 	if (pvd->vdev_ops != &vdev_mirror_ops &&
3757 	    pvd->vdev_ops != &vdev_root_ops && (!replacing ||
3758 	    pvd->vdev_ops == &vdev_replacing_ops ||
3759 	    pvd->vdev_ops == &vdev_spare_ops))
3760 		expected_error = ENOTSUP;
3761 	else if (newvd_is_spare &&
3762 	    (!replacing || oldvd_is_log || oldvd_is_special))
3763 		expected_error = ENOTSUP;
3764 	else if (newvd == oldvd)
3765 		expected_error = replacing ? 0 : EBUSY;
3766 	else if (vdev_lookup_by_path(rvd, newpath) != NULL)
3767 		expected_error = EBUSY;
3768 	else if (!newvd_is_dspare && newsize < oldsize)
3769 		expected_error = EOVERFLOW;
3770 	else if (ashift > oldvd->vdev_top->vdev_ashift)
3771 		expected_error = EDOM;
3772 	else if (newvd_is_dspare && pvd != vdev_draid_spare_get_parent(newvd))
3773 		expected_error = EINVAL;
3774 	else
3775 		expected_error = 0;
3776 
3777 	spa_config_exit(spa, SCL_ALL, FTAG);
3778 
3779 	/*
3780 	 * Build the nvlist describing newpath.
3781 	 */
3782 	root = make_vdev_root(newpath, NULL, NULL, newvd == NULL ? newsize : 0,
3783 	    ashift, NULL, 0, 0, 1);
3784 
3785 	/*
3786 	 * When supported select either a healing or sequential resilver.
3787 	 */
3788 	boolean_t rebuilding = B_FALSE;
3789 	if (pvd->vdev_ops == &vdev_mirror_ops ||
3790 	    pvd->vdev_ops ==  &vdev_root_ops) {
3791 		rebuilding = !!ztest_random(2);
3792 	}
3793 
3794 	error = spa_vdev_attach(spa, oldguid, root, replacing, rebuilding);
3795 
3796 	fnvlist_free(root);
3797 
3798 	/*
3799 	 * If our parent was the replacing vdev, but the replace completed,
3800 	 * then instead of failing with ENOTSUP we may either succeed,
3801 	 * fail with ENODEV, or fail with EOVERFLOW.
3802 	 */
3803 	if (expected_error == ENOTSUP &&
3804 	    (error == 0 || error == ENODEV || error == EOVERFLOW))
3805 		expected_error = error;
3806 
3807 	/*
3808 	 * If someone grew the LUN, the replacement may be too small.
3809 	 */
3810 	if (error == EOVERFLOW || error == EBUSY)
3811 		expected_error = error;
3812 
3813 	if (error == ZFS_ERR_CHECKPOINT_EXISTS ||
3814 	    error == ZFS_ERR_DISCARDING_CHECKPOINT ||
3815 	    error == ZFS_ERR_RESILVER_IN_PROGRESS ||
3816 	    error == ZFS_ERR_REBUILD_IN_PROGRESS)
3817 		expected_error = error;
3818 
3819 	if (error != expected_error && expected_error != EBUSY) {
3820 		fatal(B_FALSE, "attach (%s %"PRIu64", %s %"PRIu64", %d) "
3821 		    "returned %d, expected %d",
3822 		    oldpath, oldsize, newpath,
3823 		    newsize, replacing, error, expected_error);
3824 	}
3825 out:
3826 	mutex_exit(&ztest_vdev_lock);
3827 
3828 	umem_free(oldpath, MAXPATHLEN);
3829 	umem_free(newpath, MAXPATHLEN);
3830 }
3831 
3832 void
ztest_device_removal(ztest_ds_t * zd,uint64_t id)3833 ztest_device_removal(ztest_ds_t *zd, uint64_t id)
3834 {
3835 	(void) zd, (void) id;
3836 	spa_t *spa = ztest_spa;
3837 	vdev_t *vd;
3838 	uint64_t guid;
3839 	int error;
3840 
3841 	mutex_enter(&ztest_vdev_lock);
3842 
3843 	if (ztest_device_removal_active) {
3844 		mutex_exit(&ztest_vdev_lock);
3845 		return;
3846 	}
3847 
3848 	/*
3849 	 * Remove a random top-level vdev and wait for removal to finish.
3850 	 */
3851 	spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
3852 	vd = vdev_lookup_top(spa, ztest_random_vdev_top(spa, B_FALSE));
3853 	guid = vd->vdev_guid;
3854 	spa_config_exit(spa, SCL_VDEV, FTAG);
3855 
3856 	error = spa_vdev_remove(spa, guid, B_FALSE);
3857 	if (error == 0) {
3858 		ztest_device_removal_active = B_TRUE;
3859 		mutex_exit(&ztest_vdev_lock);
3860 
3861 		/*
3862 		 * spa->spa_vdev_removal is created in a sync task that
3863 		 * is initiated via dsl_sync_task_nowait(). Since the
3864 		 * task may not run before spa_vdev_remove() returns, we
3865 		 * must wait at least 1 txg to ensure that the removal
3866 		 * struct has been created.
3867 		 */
3868 		txg_wait_synced(spa_get_dsl(spa), 0);
3869 
3870 		while (spa->spa_removing_phys.sr_state == DSS_SCANNING)
3871 			txg_wait_synced(spa_get_dsl(spa), 0);
3872 	} else {
3873 		mutex_exit(&ztest_vdev_lock);
3874 		return;
3875 	}
3876 
3877 	/*
3878 	 * The pool needs to be scrubbed after completing device removal.
3879 	 * Failure to do so may result in checksum errors due to the
3880 	 * strategy employed by ztest_fault_inject() when selecting which
3881 	 * offset are redundant and can be damaged.
3882 	 */
3883 	error = spa_scan(spa, POOL_SCAN_SCRUB);
3884 	if (error == 0) {
3885 		while (dsl_scan_scrubbing(spa_get_dsl(spa)))
3886 			txg_wait_synced(spa_get_dsl(spa), 0);
3887 	}
3888 
3889 	mutex_enter(&ztest_vdev_lock);
3890 	ztest_device_removal_active = B_FALSE;
3891 	mutex_exit(&ztest_vdev_lock);
3892 }
3893 
3894 /*
3895  * Callback function which expands the physical size of the vdev.
3896  */
3897 static vdev_t *
grow_vdev(vdev_t * vd,void * arg)3898 grow_vdev(vdev_t *vd, void *arg)
3899 {
3900 	spa_t *spa __maybe_unused = vd->vdev_spa;
3901 	size_t *newsize = arg;
3902 	size_t fsize;
3903 	int fd;
3904 
3905 	ASSERT3S(spa_config_held(spa, SCL_STATE, RW_READER), ==, SCL_STATE);
3906 	ASSERT(vd->vdev_ops->vdev_op_leaf);
3907 
3908 	if ((fd = open(vd->vdev_path, O_RDWR)) == -1)
3909 		return (vd);
3910 
3911 	fsize = lseek(fd, 0, SEEK_END);
3912 	VERIFY0(ftruncate(fd, *newsize));
3913 
3914 	if (ztest_opts.zo_verbose >= 6) {
3915 		(void) printf("%s grew from %lu to %lu bytes\n",
3916 		    vd->vdev_path, (ulong_t)fsize, (ulong_t)*newsize);
3917 	}
3918 	(void) close(fd);
3919 	return (NULL);
3920 }
3921 
3922 /*
3923  * Callback function which expands a given vdev by calling vdev_online().
3924  */
3925 static vdev_t *
online_vdev(vdev_t * vd,void * arg)3926 online_vdev(vdev_t *vd, void *arg)
3927 {
3928 	(void) arg;
3929 	spa_t *spa = vd->vdev_spa;
3930 	vdev_t *tvd = vd->vdev_top;
3931 	uint64_t guid = vd->vdev_guid;
3932 	uint64_t generation = spa->spa_config_generation + 1;
3933 	vdev_state_t newstate = VDEV_STATE_UNKNOWN;
3934 	int error;
3935 
3936 	ASSERT3S(spa_config_held(spa, SCL_STATE, RW_READER), ==, SCL_STATE);
3937 	ASSERT(vd->vdev_ops->vdev_op_leaf);
3938 
3939 	/* Calling vdev_online will initialize the new metaslabs */
3940 	spa_config_exit(spa, SCL_STATE, spa);
3941 	error = vdev_online(spa, guid, ZFS_ONLINE_EXPAND, &newstate);
3942 	spa_config_enter(spa, SCL_STATE, spa, RW_READER);
3943 
3944 	/*
3945 	 * If vdev_online returned an error or the underlying vdev_open
3946 	 * failed then we abort the expand. The only way to know that
3947 	 * vdev_open fails is by checking the returned newstate.
3948 	 */
3949 	if (error || newstate != VDEV_STATE_HEALTHY) {
3950 		if (ztest_opts.zo_verbose >= 5) {
3951 			(void) printf("Unable to expand vdev, state %u, "
3952 			    "error %d\n", newstate, error);
3953 		}
3954 		return (vd);
3955 	}
3956 	ASSERT3U(newstate, ==, VDEV_STATE_HEALTHY);
3957 
3958 	/*
3959 	 * Since we dropped the lock we need to ensure that we're
3960 	 * still talking to the original vdev. It's possible this
3961 	 * vdev may have been detached/replaced while we were
3962 	 * trying to online it.
3963 	 */
3964 	if (generation != spa->spa_config_generation) {
3965 		if (ztest_opts.zo_verbose >= 5) {
3966 			(void) printf("vdev configuration has changed, "
3967 			    "guid %"PRIu64", state %"PRIu64", "
3968 			    "expected gen %"PRIu64", got gen %"PRIu64"\n",
3969 			    guid,
3970 			    tvd->vdev_state,
3971 			    generation,
3972 			    spa->spa_config_generation);
3973 		}
3974 		return (vd);
3975 	}
3976 	return (NULL);
3977 }
3978 
3979 /*
3980  * Traverse the vdev tree calling the supplied function.
3981  * We continue to walk the tree until we either have walked all
3982  * children or we receive a non-NULL return from the callback.
3983  * If a NULL callback is passed, then we just return back the first
3984  * leaf vdev we encounter.
3985  */
3986 static vdev_t *
vdev_walk_tree(vdev_t * vd,vdev_t * (* func)(vdev_t *,void *),void * arg)3987 vdev_walk_tree(vdev_t *vd, vdev_t *(*func)(vdev_t *, void *), void *arg)
3988 {
3989 	uint_t c;
3990 
3991 	if (vd->vdev_ops->vdev_op_leaf) {
3992 		if (func == NULL)
3993 			return (vd);
3994 		else
3995 			return (func(vd, arg));
3996 	}
3997 
3998 	for (c = 0; c < vd->vdev_children; c++) {
3999 		vdev_t *cvd = vd->vdev_child[c];
4000 		if ((cvd = vdev_walk_tree(cvd, func, arg)) != NULL)
4001 			return (cvd);
4002 	}
4003 	return (NULL);
4004 }
4005 
4006 /*
4007  * Verify that dynamic LUN growth works as expected.
4008  */
4009 void
ztest_vdev_LUN_growth(ztest_ds_t * zd,uint64_t id)4010 ztest_vdev_LUN_growth(ztest_ds_t *zd, uint64_t id)
4011 {
4012 	(void) zd, (void) id;
4013 	spa_t *spa = ztest_spa;
4014 	vdev_t *vd, *tvd;
4015 	metaslab_class_t *mc;
4016 	metaslab_group_t *mg;
4017 	size_t psize, newsize;
4018 	uint64_t top;
4019 	uint64_t old_class_space, new_class_space, old_ms_count, new_ms_count;
4020 
4021 	mutex_enter(&ztest_checkpoint_lock);
4022 	mutex_enter(&ztest_vdev_lock);
4023 	spa_config_enter(spa, SCL_STATE, spa, RW_READER);
4024 
4025 	/*
4026 	 * If there is a vdev removal in progress, it could complete while
4027 	 * we are running, in which case we would not be able to verify
4028 	 * that the metaslab_class space increased (because it decreases
4029 	 * when the device removal completes).
4030 	 */
4031 	if (ztest_device_removal_active) {
4032 		spa_config_exit(spa, SCL_STATE, spa);
4033 		mutex_exit(&ztest_vdev_lock);
4034 		mutex_exit(&ztest_checkpoint_lock);
4035 		return;
4036 	}
4037 
4038 	top = ztest_random_vdev_top(spa, B_TRUE);
4039 
4040 	tvd = spa->spa_root_vdev->vdev_child[top];
4041 	mg = tvd->vdev_mg;
4042 	mc = mg->mg_class;
4043 	old_ms_count = tvd->vdev_ms_count;
4044 	old_class_space = metaslab_class_get_space(mc);
4045 
4046 	/*
4047 	 * Determine the size of the first leaf vdev associated with
4048 	 * our top-level device.
4049 	 */
4050 	vd = vdev_walk_tree(tvd, NULL, NULL);
4051 	ASSERT3P(vd, !=, NULL);
4052 	ASSERT(vd->vdev_ops->vdev_op_leaf);
4053 
4054 	psize = vd->vdev_psize;
4055 
4056 	/*
4057 	 * We only try to expand the vdev if it's healthy, less than 4x its
4058 	 * original size, and it has a valid psize.
4059 	 */
4060 	if (tvd->vdev_state != VDEV_STATE_HEALTHY ||
4061 	    psize == 0 || psize >= 4 * ztest_opts.zo_vdev_size) {
4062 		spa_config_exit(spa, SCL_STATE, spa);
4063 		mutex_exit(&ztest_vdev_lock);
4064 		mutex_exit(&ztest_checkpoint_lock);
4065 		return;
4066 	}
4067 	ASSERT3U(psize, >, 0);
4068 	newsize = psize + MAX(psize / 8, SPA_MAXBLOCKSIZE);
4069 	ASSERT3U(newsize, >, psize);
4070 
4071 	if (ztest_opts.zo_verbose >= 6) {
4072 		(void) printf("Expanding LUN %s from %lu to %lu\n",
4073 		    vd->vdev_path, (ulong_t)psize, (ulong_t)newsize);
4074 	}
4075 
4076 	/*
4077 	 * Growing the vdev is a two step process:
4078 	 *	1). expand the physical size (i.e. relabel)
4079 	 *	2). online the vdev to create the new metaslabs
4080 	 */
4081 	if (vdev_walk_tree(tvd, grow_vdev, &newsize) != NULL ||
4082 	    vdev_walk_tree(tvd, online_vdev, NULL) != NULL ||
4083 	    tvd->vdev_state != VDEV_STATE_HEALTHY) {
4084 		if (ztest_opts.zo_verbose >= 5) {
4085 			(void) printf("Could not expand LUN because "
4086 			    "the vdev configuration changed.\n");
4087 		}
4088 		spa_config_exit(spa, SCL_STATE, spa);
4089 		mutex_exit(&ztest_vdev_lock);
4090 		mutex_exit(&ztest_checkpoint_lock);
4091 		return;
4092 	}
4093 
4094 	spa_config_exit(spa, SCL_STATE, spa);
4095 
4096 	/*
4097 	 * Expanding the LUN will update the config asynchronously,
4098 	 * thus we must wait for the async thread to complete any
4099 	 * pending tasks before proceeding.
4100 	 */
4101 	for (;;) {
4102 		boolean_t done;
4103 		mutex_enter(&spa->spa_async_lock);
4104 		done = (spa->spa_async_thread == NULL && !spa->spa_async_tasks);
4105 		mutex_exit(&spa->spa_async_lock);
4106 		if (done)
4107 			break;
4108 		txg_wait_synced(spa_get_dsl(spa), 0);
4109 		(void) poll(NULL, 0, 100);
4110 	}
4111 
4112 	spa_config_enter(spa, SCL_STATE, spa, RW_READER);
4113 
4114 	tvd = spa->spa_root_vdev->vdev_child[top];
4115 	new_ms_count = tvd->vdev_ms_count;
4116 	new_class_space = metaslab_class_get_space(mc);
4117 
4118 	if (tvd->vdev_mg != mg || mg->mg_class != mc) {
4119 		if (ztest_opts.zo_verbose >= 5) {
4120 			(void) printf("Could not verify LUN expansion due to "
4121 			    "intervening vdev offline or remove.\n");
4122 		}
4123 		spa_config_exit(spa, SCL_STATE, spa);
4124 		mutex_exit(&ztest_vdev_lock);
4125 		mutex_exit(&ztest_checkpoint_lock);
4126 		return;
4127 	}
4128 
4129 	/*
4130 	 * Make sure we were able to grow the vdev.
4131 	 */
4132 	if (new_ms_count <= old_ms_count) {
4133 		fatal(B_FALSE,
4134 		    "LUN expansion failed: ms_count %"PRIu64" < %"PRIu64"\n",
4135 		    old_ms_count, new_ms_count);
4136 	}
4137 
4138 	/*
4139 	 * Make sure we were able to grow the pool.
4140 	 */
4141 	if (new_class_space <= old_class_space) {
4142 		fatal(B_FALSE,
4143 		    "LUN expansion failed: class_space %"PRIu64" < %"PRIu64"\n",
4144 		    old_class_space, new_class_space);
4145 	}
4146 
4147 	if (ztest_opts.zo_verbose >= 5) {
4148 		char oldnumbuf[NN_NUMBUF_SZ], newnumbuf[NN_NUMBUF_SZ];
4149 
4150 		nicenum(old_class_space, oldnumbuf, sizeof (oldnumbuf));
4151 		nicenum(new_class_space, newnumbuf, sizeof (newnumbuf));
4152 		(void) printf("%s grew from %s to %s\n",
4153 		    spa->spa_name, oldnumbuf, newnumbuf);
4154 	}
4155 
4156 	spa_config_exit(spa, SCL_STATE, spa);
4157 	mutex_exit(&ztest_vdev_lock);
4158 	mutex_exit(&ztest_checkpoint_lock);
4159 }
4160 
4161 /*
4162  * Verify that dmu_objset_{create,destroy,open,close} work as expected.
4163  */
4164 static void
ztest_objset_create_cb(objset_t * os,void * arg,cred_t * cr,dmu_tx_t * tx)4165 ztest_objset_create_cb(objset_t *os, void *arg, cred_t *cr, dmu_tx_t *tx)
4166 {
4167 	(void) arg, (void) cr;
4168 
4169 	/*
4170 	 * Create the objects common to all ztest datasets.
4171 	 */
4172 	VERIFY0(zap_create_claim(os, ZTEST_DIROBJ,
4173 	    DMU_OT_ZAP_OTHER, DMU_OT_NONE, 0, tx));
4174 }
4175 
4176 static int
ztest_dataset_create(char * dsname)4177 ztest_dataset_create(char *dsname)
4178 {
4179 	int err;
4180 	uint64_t rand;
4181 	dsl_crypto_params_t *dcp = NULL;
4182 
4183 	/*
4184 	 * 50% of the time, we create encrypted datasets
4185 	 * using a random cipher suite and a hard-coded
4186 	 * wrapping key.
4187 	 */
4188 	rand = ztest_random(2);
4189 	if (rand != 0) {
4190 		nvlist_t *crypto_args = fnvlist_alloc();
4191 		nvlist_t *props = fnvlist_alloc();
4192 
4193 		/* slight bias towards the default cipher suite */
4194 		rand = ztest_random(ZIO_CRYPT_FUNCTIONS);
4195 		if (rand < ZIO_CRYPT_AES_128_CCM)
4196 			rand = ZIO_CRYPT_ON;
4197 
4198 		fnvlist_add_uint64(props,
4199 		    zfs_prop_to_name(ZFS_PROP_ENCRYPTION), rand);
4200 		fnvlist_add_uint8_array(crypto_args, "wkeydata",
4201 		    (uint8_t *)ztest_wkeydata, WRAPPING_KEY_LEN);
4202 
4203 		/*
4204 		 * These parameters aren't really used by the kernel. They
4205 		 * are simply stored so that userspace knows how to load
4206 		 * the wrapping key.
4207 		 */
4208 		fnvlist_add_uint64(props,
4209 		    zfs_prop_to_name(ZFS_PROP_KEYFORMAT), ZFS_KEYFORMAT_RAW);
4210 		fnvlist_add_string(props,
4211 		    zfs_prop_to_name(ZFS_PROP_KEYLOCATION), "prompt");
4212 		fnvlist_add_uint64(props,
4213 		    zfs_prop_to_name(ZFS_PROP_PBKDF2_SALT), 0ULL);
4214 		fnvlist_add_uint64(props,
4215 		    zfs_prop_to_name(ZFS_PROP_PBKDF2_ITERS), 0ULL);
4216 
4217 		VERIFY0(dsl_crypto_params_create_nvlist(DCP_CMD_NONE, props,
4218 		    crypto_args, &dcp));
4219 
4220 		/*
4221 		 * Cycle through all available encryption implementations
4222 		 * to verify interoperability.
4223 		 */
4224 		VERIFY0(gcm_impl_set("cycle"));
4225 		VERIFY0(aes_impl_set("cycle"));
4226 
4227 		fnvlist_free(crypto_args);
4228 		fnvlist_free(props);
4229 	}
4230 
4231 	err = dmu_objset_create(dsname, DMU_OST_OTHER, 0, dcp,
4232 	    ztest_objset_create_cb, NULL);
4233 	dsl_crypto_params_free(dcp, !!err);
4234 
4235 	rand = ztest_random(100);
4236 	if (err || rand < 80)
4237 		return (err);
4238 
4239 	if (ztest_opts.zo_verbose >= 5)
4240 		(void) printf("Setting dataset %s to sync always\n", dsname);
4241 	return (ztest_dsl_prop_set_uint64(dsname, ZFS_PROP_SYNC,
4242 	    ZFS_SYNC_ALWAYS, B_FALSE));
4243 }
4244 
4245 static int
ztest_objset_destroy_cb(const char * name,void * arg)4246 ztest_objset_destroy_cb(const char *name, void *arg)
4247 {
4248 	(void) arg;
4249 	objset_t *os;
4250 	dmu_object_info_t doi;
4251 	int error;
4252 
4253 	/*
4254 	 * Verify that the dataset contains a directory object.
4255 	 */
4256 	VERIFY0(ztest_dmu_objset_own(name, DMU_OST_OTHER, B_TRUE,
4257 	    B_TRUE, FTAG, &os));
4258 	error = dmu_object_info(os, ZTEST_DIROBJ, &doi);
4259 	if (error != ENOENT) {
4260 		/* We could have crashed in the middle of destroying it */
4261 		ASSERT0(error);
4262 		ASSERT3U(doi.doi_type, ==, DMU_OT_ZAP_OTHER);
4263 		ASSERT3S(doi.doi_physical_blocks_512, >=, 0);
4264 	}
4265 	dmu_objset_disown(os, B_TRUE, FTAG);
4266 
4267 	/*
4268 	 * Destroy the dataset.
4269 	 */
4270 	if (strchr(name, '@') != NULL) {
4271 		error = dsl_destroy_snapshot(name, B_TRUE);
4272 		if (error != ECHRNG) {
4273 			/*
4274 			 * The program was executed, but encountered a runtime
4275 			 * error, such as insufficient slop, or a hold on the
4276 			 * dataset.
4277 			 */
4278 			ASSERT0(error);
4279 		}
4280 	} else {
4281 		error = dsl_destroy_head(name);
4282 		if (error == ENOSPC) {
4283 			/* There could be checkpoint or insufficient slop */
4284 			ztest_record_enospc(FTAG);
4285 		} else if (error != EBUSY) {
4286 			/* There could be a hold on this dataset */
4287 			ASSERT0(error);
4288 		}
4289 	}
4290 	return (0);
4291 }
4292 
4293 static boolean_t
ztest_snapshot_create(char * osname,uint64_t id)4294 ztest_snapshot_create(char *osname, uint64_t id)
4295 {
4296 	char snapname[ZFS_MAX_DATASET_NAME_LEN];
4297 	int error;
4298 
4299 	(void) snprintf(snapname, sizeof (snapname), "%"PRIu64"", id);
4300 
4301 	error = dmu_objset_snapshot_one(osname, snapname);
4302 	if (error == ENOSPC) {
4303 		ztest_record_enospc(FTAG);
4304 		return (B_FALSE);
4305 	}
4306 	if (error != 0 && error != EEXIST && error != ECHRNG) {
4307 		fatal(B_FALSE, "ztest_snapshot_create(%s@%s) = %d", osname,
4308 		    snapname, error);
4309 	}
4310 	return (B_TRUE);
4311 }
4312 
4313 static boolean_t
ztest_snapshot_destroy(char * osname,uint64_t id)4314 ztest_snapshot_destroy(char *osname, uint64_t id)
4315 {
4316 	char snapname[ZFS_MAX_DATASET_NAME_LEN];
4317 	int error;
4318 
4319 	(void) snprintf(snapname, sizeof (snapname), "%s@%"PRIu64"",
4320 	    osname, id);
4321 
4322 	error = dsl_destroy_snapshot(snapname, B_FALSE);
4323 	if (error != 0 && error != ENOENT && error != ECHRNG)
4324 		fatal(B_FALSE, "ztest_snapshot_destroy(%s) = %d",
4325 		    snapname, error);
4326 	return (B_TRUE);
4327 }
4328 
4329 void
ztest_dmu_objset_create_destroy(ztest_ds_t * zd,uint64_t id)4330 ztest_dmu_objset_create_destroy(ztest_ds_t *zd, uint64_t id)
4331 {
4332 	(void) zd;
4333 	ztest_ds_t *zdtmp;
4334 	int iters;
4335 	int error;
4336 	objset_t *os, *os2;
4337 	char name[ZFS_MAX_DATASET_NAME_LEN];
4338 	zilog_t *zilog;
4339 	int i;
4340 
4341 	zdtmp = umem_alloc(sizeof (ztest_ds_t), UMEM_NOFAIL);
4342 
4343 	(void) pthread_rwlock_rdlock(&ztest_name_lock);
4344 
4345 	(void) snprintf(name, sizeof (name), "%s/temp_%"PRIu64"",
4346 	    ztest_opts.zo_pool, id);
4347 
4348 	/*
4349 	 * If this dataset exists from a previous run, process its replay log
4350 	 * half of the time.  If we don't replay it, then dsl_destroy_head()
4351 	 * (invoked from ztest_objset_destroy_cb()) should just throw it away.
4352 	 */
4353 	if (ztest_random(2) == 0 &&
4354 	    ztest_dmu_objset_own(name, DMU_OST_OTHER, B_FALSE,
4355 	    B_TRUE, FTAG, &os) == 0) {
4356 		ztest_zd_init(zdtmp, NULL, os);
4357 		zil_replay(os, zdtmp, ztest_replay_vector);
4358 		ztest_zd_fini(zdtmp);
4359 		dmu_objset_disown(os, B_TRUE, FTAG);
4360 	}
4361 
4362 	/*
4363 	 * There may be an old instance of the dataset we're about to
4364 	 * create lying around from a previous run.  If so, destroy it
4365 	 * and all of its snapshots.
4366 	 */
4367 	(void) dmu_objset_find(name, ztest_objset_destroy_cb, NULL,
4368 	    DS_FIND_CHILDREN | DS_FIND_SNAPSHOTS);
4369 
4370 	/*
4371 	 * Verify that the destroyed dataset is no longer in the namespace.
4372 	 * It may still be present if the destroy above fails with ENOSPC.
4373 	 */
4374 	error = ztest_dmu_objset_own(name, DMU_OST_OTHER, B_TRUE, B_TRUE,
4375 	    FTAG, &os);
4376 	if (error == 0) {
4377 		dmu_objset_disown(os, B_TRUE, FTAG);
4378 		ztest_record_enospc(FTAG);
4379 		goto out;
4380 	}
4381 	VERIFY3U(ENOENT, ==, error);
4382 
4383 	/*
4384 	 * Verify that we can create a new dataset.
4385 	 */
4386 	error = ztest_dataset_create(name);
4387 	if (error) {
4388 		if (error == ENOSPC) {
4389 			ztest_record_enospc(FTAG);
4390 			goto out;
4391 		}
4392 		fatal(B_FALSE, "dmu_objset_create(%s) = %d", name, error);
4393 	}
4394 
4395 	VERIFY0(ztest_dmu_objset_own(name, DMU_OST_OTHER, B_FALSE, B_TRUE,
4396 	    FTAG, &os));
4397 
4398 	ztest_zd_init(zdtmp, NULL, os);
4399 
4400 	/*
4401 	 * Open the intent log for it.
4402 	 */
4403 	zilog = zil_open(os, ztest_get_data, NULL);
4404 
4405 	/*
4406 	 * Put some objects in there, do a little I/O to them,
4407 	 * and randomly take a couple of snapshots along the way.
4408 	 */
4409 	iters = ztest_random(5);
4410 	for (i = 0; i < iters; i++) {
4411 		ztest_dmu_object_alloc_free(zdtmp, id);
4412 		if (ztest_random(iters) == 0)
4413 			(void) ztest_snapshot_create(name, i);
4414 	}
4415 
4416 	/*
4417 	 * Verify that we cannot create an existing dataset.
4418 	 */
4419 	VERIFY3U(EEXIST, ==,
4420 	    dmu_objset_create(name, DMU_OST_OTHER, 0, NULL, NULL, NULL));
4421 
4422 	/*
4423 	 * Verify that we can hold an objset that is also owned.
4424 	 */
4425 	VERIFY0(dmu_objset_hold(name, FTAG, &os2));
4426 	dmu_objset_rele(os2, FTAG);
4427 
4428 	/*
4429 	 * Verify that we cannot own an objset that is already owned.
4430 	 */
4431 	VERIFY3U(EBUSY, ==, ztest_dmu_objset_own(name, DMU_OST_OTHER,
4432 	    B_FALSE, B_TRUE, FTAG, &os2));
4433 
4434 	zil_close(zilog);
4435 	dmu_objset_disown(os, B_TRUE, FTAG);
4436 	ztest_zd_fini(zdtmp);
4437 out:
4438 	(void) pthread_rwlock_unlock(&ztest_name_lock);
4439 
4440 	umem_free(zdtmp, sizeof (ztest_ds_t));
4441 }
4442 
4443 /*
4444  * Verify that dmu_snapshot_{create,destroy,open,close} work as expected.
4445  */
4446 void
ztest_dmu_snapshot_create_destroy(ztest_ds_t * zd,uint64_t id)4447 ztest_dmu_snapshot_create_destroy(ztest_ds_t *zd, uint64_t id)
4448 {
4449 	(void) pthread_rwlock_rdlock(&ztest_name_lock);
4450 	(void) ztest_snapshot_destroy(zd->zd_name, id);
4451 	(void) ztest_snapshot_create(zd->zd_name, id);
4452 	(void) pthread_rwlock_unlock(&ztest_name_lock);
4453 }
4454 
4455 /*
4456  * Cleanup non-standard snapshots and clones.
4457  */
4458 static void
ztest_dsl_dataset_cleanup(char * osname,uint64_t id)4459 ztest_dsl_dataset_cleanup(char *osname, uint64_t id)
4460 {
4461 	char *snap1name;
4462 	char *clone1name;
4463 	char *snap2name;
4464 	char *clone2name;
4465 	char *snap3name;
4466 	int error;
4467 
4468 	snap1name  = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
4469 	clone1name = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
4470 	snap2name  = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
4471 	clone2name = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
4472 	snap3name  = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
4473 
4474 	(void) snprintf(snap1name, ZFS_MAX_DATASET_NAME_LEN, "%s@s1_%"PRIu64"",
4475 	    osname, id);
4476 	(void) snprintf(clone1name, ZFS_MAX_DATASET_NAME_LEN, "%s/c1_%"PRIu64"",
4477 	    osname, id);
4478 	(void) snprintf(snap2name, ZFS_MAX_DATASET_NAME_LEN, "%s@s2_%"PRIu64"",
4479 	    clone1name, id);
4480 	(void) snprintf(clone2name, ZFS_MAX_DATASET_NAME_LEN, "%s/c2_%"PRIu64"",
4481 	    osname, id);
4482 	(void) snprintf(snap3name, ZFS_MAX_DATASET_NAME_LEN, "%s@s3_%"PRIu64"",
4483 	    clone1name, id);
4484 
4485 	error = dsl_destroy_head(clone2name);
4486 	if (error && error != ENOENT)
4487 		fatal(B_FALSE, "dsl_destroy_head(%s) = %d", clone2name, error);
4488 	error = dsl_destroy_snapshot(snap3name, B_FALSE);
4489 	if (error && error != ENOENT)
4490 		fatal(B_FALSE, "dsl_destroy_snapshot(%s) = %d",
4491 		    snap3name, error);
4492 	error = dsl_destroy_snapshot(snap2name, B_FALSE);
4493 	if (error && error != ENOENT)
4494 		fatal(B_FALSE, "dsl_destroy_snapshot(%s) = %d",
4495 		    snap2name, error);
4496 	error = dsl_destroy_head(clone1name);
4497 	if (error && error != ENOENT)
4498 		fatal(B_FALSE, "dsl_destroy_head(%s) = %d", clone1name, error);
4499 	error = dsl_destroy_snapshot(snap1name, B_FALSE);
4500 	if (error && error != ENOENT)
4501 		fatal(B_FALSE, "dsl_destroy_snapshot(%s) = %d",
4502 		    snap1name, error);
4503 
4504 	umem_free(snap1name, ZFS_MAX_DATASET_NAME_LEN);
4505 	umem_free(clone1name, ZFS_MAX_DATASET_NAME_LEN);
4506 	umem_free(snap2name, ZFS_MAX_DATASET_NAME_LEN);
4507 	umem_free(clone2name, ZFS_MAX_DATASET_NAME_LEN);
4508 	umem_free(snap3name, ZFS_MAX_DATASET_NAME_LEN);
4509 }
4510 
4511 /*
4512  * Verify dsl_dataset_promote handles EBUSY
4513  */
4514 void
ztest_dsl_dataset_promote_busy(ztest_ds_t * zd,uint64_t id)4515 ztest_dsl_dataset_promote_busy(ztest_ds_t *zd, uint64_t id)
4516 {
4517 	objset_t *os;
4518 	char *snap1name;
4519 	char *clone1name;
4520 	char *snap2name;
4521 	char *clone2name;
4522 	char *snap3name;
4523 	char *osname = zd->zd_name;
4524 	int error;
4525 
4526 	snap1name  = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
4527 	clone1name = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
4528 	snap2name  = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
4529 	clone2name = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
4530 	snap3name  = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
4531 
4532 	(void) pthread_rwlock_rdlock(&ztest_name_lock);
4533 
4534 	ztest_dsl_dataset_cleanup(osname, id);
4535 
4536 	(void) snprintf(snap1name, ZFS_MAX_DATASET_NAME_LEN, "%s@s1_%"PRIu64"",
4537 	    osname, id);
4538 	(void) snprintf(clone1name, ZFS_MAX_DATASET_NAME_LEN, "%s/c1_%"PRIu64"",
4539 	    osname, id);
4540 	(void) snprintf(snap2name, ZFS_MAX_DATASET_NAME_LEN, "%s@s2_%"PRIu64"",
4541 	    clone1name, id);
4542 	(void) snprintf(clone2name, ZFS_MAX_DATASET_NAME_LEN, "%s/c2_%"PRIu64"",
4543 	    osname, id);
4544 	(void) snprintf(snap3name, ZFS_MAX_DATASET_NAME_LEN, "%s@s3_%"PRIu64"",
4545 	    clone1name, id);
4546 
4547 	error = dmu_objset_snapshot_one(osname, strchr(snap1name, '@') + 1);
4548 	if (error && error != EEXIST) {
4549 		if (error == ENOSPC) {
4550 			ztest_record_enospc(FTAG);
4551 			goto out;
4552 		}
4553 		fatal(B_FALSE, "dmu_take_snapshot(%s) = %d", snap1name, error);
4554 	}
4555 
4556 	error = dmu_objset_clone(clone1name, snap1name);
4557 	if (error) {
4558 		if (error == ENOSPC) {
4559 			ztest_record_enospc(FTAG);
4560 			goto out;
4561 		}
4562 		fatal(B_FALSE, "dmu_objset_create(%s) = %d", clone1name, error);
4563 	}
4564 
4565 	error = dmu_objset_snapshot_one(clone1name, strchr(snap2name, '@') + 1);
4566 	if (error && error != EEXIST) {
4567 		if (error == ENOSPC) {
4568 			ztest_record_enospc(FTAG);
4569 			goto out;
4570 		}
4571 		fatal(B_FALSE, "dmu_open_snapshot(%s) = %d", snap2name, error);
4572 	}
4573 
4574 	error = dmu_objset_snapshot_one(clone1name, strchr(snap3name, '@') + 1);
4575 	if (error && error != EEXIST) {
4576 		if (error == ENOSPC) {
4577 			ztest_record_enospc(FTAG);
4578 			goto out;
4579 		}
4580 		fatal(B_FALSE, "dmu_open_snapshot(%s) = %d", snap3name, error);
4581 	}
4582 
4583 	error = dmu_objset_clone(clone2name, snap3name);
4584 	if (error) {
4585 		if (error == ENOSPC) {
4586 			ztest_record_enospc(FTAG);
4587 			goto out;
4588 		}
4589 		fatal(B_FALSE, "dmu_objset_create(%s) = %d", clone2name, error);
4590 	}
4591 
4592 	error = ztest_dmu_objset_own(snap2name, DMU_OST_ANY, B_TRUE, B_TRUE,
4593 	    FTAG, &os);
4594 	if (error)
4595 		fatal(B_FALSE, "dmu_objset_own(%s) = %d", snap2name, error);
4596 	error = dsl_dataset_promote(clone2name, NULL);
4597 	if (error == ENOSPC) {
4598 		dmu_objset_disown(os, B_TRUE, FTAG);
4599 		ztest_record_enospc(FTAG);
4600 		goto out;
4601 	}
4602 	if (error != EBUSY)
4603 		fatal(B_FALSE, "dsl_dataset_promote(%s), %d, not EBUSY",
4604 		    clone2name, error);
4605 	dmu_objset_disown(os, B_TRUE, FTAG);
4606 
4607 out:
4608 	ztest_dsl_dataset_cleanup(osname, id);
4609 
4610 	(void) pthread_rwlock_unlock(&ztest_name_lock);
4611 
4612 	umem_free(snap1name, ZFS_MAX_DATASET_NAME_LEN);
4613 	umem_free(clone1name, ZFS_MAX_DATASET_NAME_LEN);
4614 	umem_free(snap2name, ZFS_MAX_DATASET_NAME_LEN);
4615 	umem_free(clone2name, ZFS_MAX_DATASET_NAME_LEN);
4616 	umem_free(snap3name, ZFS_MAX_DATASET_NAME_LEN);
4617 }
4618 
4619 #undef OD_ARRAY_SIZE
4620 #define	OD_ARRAY_SIZE	4
4621 
4622 /*
4623  * Verify that dmu_object_{alloc,free} work as expected.
4624  */
4625 void
ztest_dmu_object_alloc_free(ztest_ds_t * zd,uint64_t id)4626 ztest_dmu_object_alloc_free(ztest_ds_t *zd, uint64_t id)
4627 {
4628 	ztest_od_t *od;
4629 	int batchsize;
4630 	int size;
4631 	int b;
4632 
4633 	size = sizeof (ztest_od_t) * OD_ARRAY_SIZE;
4634 	od = umem_alloc(size, UMEM_NOFAIL);
4635 	batchsize = OD_ARRAY_SIZE;
4636 
4637 	for (b = 0; b < batchsize; b++)
4638 		ztest_od_init(od + b, id, FTAG, b, DMU_OT_UINT64_OTHER,
4639 		    0, 0, 0);
4640 
4641 	/*
4642 	 * Destroy the previous batch of objects, create a new batch,
4643 	 * and do some I/O on the new objects.
4644 	 */
4645 	if (ztest_object_init(zd, od, size, B_TRUE) != 0) {
4646 		zd->zd_od = NULL;
4647 		umem_free(od, size);
4648 		return;
4649 	}
4650 
4651 	while (ztest_random(4 * batchsize) != 0)
4652 		ztest_io(zd, od[ztest_random(batchsize)].od_object,
4653 		    ztest_random(ZTEST_RANGE_LOCKS) << SPA_MAXBLOCKSHIFT);
4654 
4655 	umem_free(od, size);
4656 }
4657 
4658 /*
4659  * Rewind the global allocator to verify object allocation backfilling.
4660  */
4661 void
ztest_dmu_object_next_chunk(ztest_ds_t * zd,uint64_t id)4662 ztest_dmu_object_next_chunk(ztest_ds_t *zd, uint64_t id)
4663 {
4664 	(void) id;
4665 	objset_t *os = zd->zd_os;
4666 	uint_t dnodes_per_chunk = 1 << dmu_object_alloc_chunk_shift;
4667 	uint64_t object;
4668 
4669 	/*
4670 	 * Rewind the global allocator randomly back to a lower object number
4671 	 * to force backfilling and reclamation of recently freed dnodes.
4672 	 */
4673 	mutex_enter(&os->os_obj_lock);
4674 	object = ztest_random(os->os_obj_next_chunk);
4675 	os->os_obj_next_chunk = P2ALIGN_TYPED(object, dnodes_per_chunk,
4676 	    uint64_t);
4677 	mutex_exit(&os->os_obj_lock);
4678 }
4679 
4680 #undef OD_ARRAY_SIZE
4681 #define	OD_ARRAY_SIZE	2
4682 
4683 /*
4684  * Verify that dmu_{read,write} work as expected.
4685  */
4686 void
ztest_dmu_read_write(ztest_ds_t * zd,uint64_t id)4687 ztest_dmu_read_write(ztest_ds_t *zd, uint64_t id)
4688 {
4689 	int size;
4690 	ztest_od_t *od;
4691 
4692 	objset_t *os = zd->zd_os;
4693 	size = sizeof (ztest_od_t) * OD_ARRAY_SIZE;
4694 	od = umem_alloc(size, UMEM_NOFAIL);
4695 	dmu_tx_t *tx;
4696 	int freeit, error;
4697 	uint64_t i, n, s, txg;
4698 	bufwad_t *packbuf, *bigbuf, *pack, *bigH, *bigT;
4699 	uint64_t packobj, packoff, packsize, bigobj, bigoff, bigsize;
4700 	uint64_t chunksize = (1000 + ztest_random(1000)) * sizeof (uint64_t);
4701 	uint64_t regions = 997;
4702 	uint64_t stride = 123456789ULL;
4703 	uint64_t width = 40;
4704 	int free_percent = 5;
4705 
4706 	/*
4707 	 * This test uses two objects, packobj and bigobj, that are always
4708 	 * updated together (i.e. in the same tx) so that their contents are
4709 	 * in sync and can be compared.  Their contents relate to each other
4710 	 * in a simple way: packobj is a dense array of 'bufwad' structures,
4711 	 * while bigobj is a sparse array of the same bufwads.  Specifically,
4712 	 * for any index n, there are three bufwads that should be identical:
4713 	 *
4714 	 *	packobj, at offset n * sizeof (bufwad_t)
4715 	 *	bigobj, at the head of the nth chunk
4716 	 *	bigobj, at the tail of the nth chunk
4717 	 *
4718 	 * The chunk size is arbitrary. It doesn't have to be a power of two,
4719 	 * and it doesn't have any relation to the object blocksize.
4720 	 * The only requirement is that it can hold at least two bufwads.
4721 	 *
4722 	 * Normally, we write the bufwad to each of these locations.
4723 	 * However, free_percent of the time we instead write zeroes to
4724 	 * packobj and perform a dmu_free_range() on bigobj.  By comparing
4725 	 * bigobj to packobj, we can verify that the DMU is correctly
4726 	 * tracking which parts of an object are allocated and free,
4727 	 * and that the contents of the allocated blocks are correct.
4728 	 */
4729 
4730 	/*
4731 	 * Read the directory info.  If it's the first time, set things up.
4732 	 */
4733 	ztest_od_init(od, id, FTAG, 0, DMU_OT_UINT64_OTHER, 0, 0, chunksize);
4734 	ztest_od_init(od + 1, id, FTAG, 1, DMU_OT_UINT64_OTHER, 0, 0,
4735 	    chunksize);
4736 
4737 	if (ztest_object_init(zd, od, size, B_FALSE) != 0) {
4738 		umem_free(od, size);
4739 		return;
4740 	}
4741 
4742 	bigobj = od[0].od_object;
4743 	packobj = od[1].od_object;
4744 	chunksize = od[0].od_gen;
4745 	ASSERT3U(chunksize, ==, od[1].od_gen);
4746 
4747 	/*
4748 	 * Prefetch a random chunk of the big object.
4749 	 * Our aim here is to get some async reads in flight
4750 	 * for blocks that we may free below; the DMU should
4751 	 * handle this race correctly.
4752 	 */
4753 	n = ztest_random(regions) * stride + ztest_random(width);
4754 	s = 1 + ztest_random(2 * width - 1);
4755 	dmu_prefetch(os, bigobj, 0, n * chunksize, s * chunksize,
4756 	    ZIO_PRIORITY_SYNC_READ);
4757 
4758 	/*
4759 	 * Pick a random index and compute the offsets into packobj and bigobj.
4760 	 */
4761 	n = ztest_random(regions) * stride + ztest_random(width);
4762 	s = 1 + ztest_random(width - 1);
4763 
4764 	packoff = n * sizeof (bufwad_t);
4765 	packsize = s * sizeof (bufwad_t);
4766 
4767 	bigoff = n * chunksize;
4768 	bigsize = s * chunksize;
4769 
4770 	packbuf = umem_alloc(packsize, UMEM_NOFAIL);
4771 	bigbuf = umem_alloc(bigsize, UMEM_NOFAIL);
4772 
4773 	/*
4774 	 * free_percent of the time, free a range of bigobj rather than
4775 	 * overwriting it.
4776 	 */
4777 	freeit = (ztest_random(100) < free_percent);
4778 
4779 	/*
4780 	 * Read the current contents of our objects.
4781 	 */
4782 	error = dmu_read(os, packobj, packoff, packsize, packbuf,
4783 	    DMU_READ_PREFETCH);
4784 	ASSERT0(error);
4785 	error = dmu_read(os, bigobj, bigoff, bigsize, bigbuf,
4786 	    DMU_READ_PREFETCH);
4787 	ASSERT0(error);
4788 
4789 	/*
4790 	 * Get a tx for the mods to both packobj and bigobj.
4791 	 */
4792 	tx = dmu_tx_create(os);
4793 
4794 	dmu_tx_hold_write(tx, packobj, packoff, packsize);
4795 
4796 	if (freeit)
4797 		dmu_tx_hold_free(tx, bigobj, bigoff, bigsize);
4798 	else
4799 		dmu_tx_hold_write(tx, bigobj, bigoff, bigsize);
4800 
4801 	/* This accounts for setting the checksum/compression. */
4802 	dmu_tx_hold_bonus(tx, bigobj);
4803 
4804 	txg = ztest_tx_assign(tx, TXG_MIGHTWAIT, FTAG);
4805 	if (txg == 0) {
4806 		umem_free(packbuf, packsize);
4807 		umem_free(bigbuf, bigsize);
4808 		umem_free(od, size);
4809 		return;
4810 	}
4811 
4812 	enum zio_checksum cksum;
4813 	do {
4814 		cksum = (enum zio_checksum)
4815 		    ztest_random_dsl_prop(ZFS_PROP_CHECKSUM);
4816 	} while (cksum >= ZIO_CHECKSUM_LEGACY_FUNCTIONS);
4817 	dmu_object_set_checksum(os, bigobj, cksum, tx);
4818 
4819 	enum zio_compress comp;
4820 	do {
4821 		comp = (enum zio_compress)
4822 		    ztest_random_dsl_prop(ZFS_PROP_COMPRESSION);
4823 	} while (comp >= ZIO_COMPRESS_LEGACY_FUNCTIONS);
4824 	dmu_object_set_compress(os, bigobj, comp, tx);
4825 
4826 	/*
4827 	 * For each index from n to n + s, verify that the existing bufwad
4828 	 * in packobj matches the bufwads at the head and tail of the
4829 	 * corresponding chunk in bigobj.  Then update all three bufwads
4830 	 * with the new values we want to write out.
4831 	 */
4832 	for (i = 0; i < s; i++) {
4833 		/* LINTED */
4834 		pack = (bufwad_t *)((char *)packbuf + i * sizeof (bufwad_t));
4835 		/* LINTED */
4836 		bigH = (bufwad_t *)((char *)bigbuf + i * chunksize);
4837 		/* LINTED */
4838 		bigT = (bufwad_t *)((char *)bigH + chunksize) - 1;
4839 
4840 		ASSERT3U((uintptr_t)bigH - (uintptr_t)bigbuf, <, bigsize);
4841 		ASSERT3U((uintptr_t)bigT - (uintptr_t)bigbuf, <, bigsize);
4842 
4843 		if (pack->bw_txg > txg)
4844 			fatal(B_FALSE,
4845 			    "future leak: got %"PRIx64", open txg is %"PRIx64"",
4846 			    pack->bw_txg, txg);
4847 
4848 		if (pack->bw_data != 0 && pack->bw_index != n + i)
4849 			fatal(B_FALSE, "wrong index: "
4850 			    "got %"PRIx64", wanted %"PRIx64"+%"PRIx64"",
4851 			    pack->bw_index, n, i);
4852 
4853 		if (memcmp(pack, bigH, sizeof (bufwad_t)) != 0)
4854 			fatal(B_FALSE, "pack/bigH mismatch in %p/%p",
4855 			    pack, bigH);
4856 
4857 		if (memcmp(pack, bigT, sizeof (bufwad_t)) != 0)
4858 			fatal(B_FALSE, "pack/bigT mismatch in %p/%p",
4859 			    pack, bigT);
4860 
4861 		if (freeit) {
4862 			memset(pack, 0, sizeof (bufwad_t));
4863 		} else {
4864 			pack->bw_index = n + i;
4865 			pack->bw_txg = txg;
4866 			pack->bw_data = 1 + ztest_random(-2ULL);
4867 		}
4868 		*bigH = *pack;
4869 		*bigT = *pack;
4870 	}
4871 
4872 	/*
4873 	 * We've verified all the old bufwads, and made new ones.
4874 	 * Now write them out.
4875 	 */
4876 	dmu_write(os, packobj, packoff, packsize, packbuf, tx);
4877 
4878 	if (freeit) {
4879 		if (ztest_opts.zo_verbose >= 7) {
4880 			(void) printf("freeing offset %"PRIx64" size %"PRIx64""
4881 			    " txg %"PRIx64"\n",
4882 			    bigoff, bigsize, txg);
4883 		}
4884 		VERIFY0(dmu_free_range(os, bigobj, bigoff, bigsize, tx));
4885 	} else {
4886 		if (ztest_opts.zo_verbose >= 7) {
4887 			(void) printf("writing offset %"PRIx64" size %"PRIx64""
4888 			    " txg %"PRIx64"\n",
4889 			    bigoff, bigsize, txg);
4890 		}
4891 		dmu_write(os, bigobj, bigoff, bigsize, bigbuf, tx);
4892 	}
4893 
4894 	dmu_tx_commit(tx);
4895 
4896 	/*
4897 	 * Sanity check the stuff we just wrote.
4898 	 */
4899 	{
4900 		void *packcheck = umem_alloc(packsize, UMEM_NOFAIL);
4901 		void *bigcheck = umem_alloc(bigsize, UMEM_NOFAIL);
4902 
4903 		VERIFY0(dmu_read(os, packobj, packoff,
4904 		    packsize, packcheck, DMU_READ_PREFETCH));
4905 		VERIFY0(dmu_read(os, bigobj, bigoff,
4906 		    bigsize, bigcheck, DMU_READ_PREFETCH));
4907 
4908 		ASSERT0(memcmp(packbuf, packcheck, packsize));
4909 		ASSERT0(memcmp(bigbuf, bigcheck, bigsize));
4910 
4911 		umem_free(packcheck, packsize);
4912 		umem_free(bigcheck, bigsize);
4913 	}
4914 
4915 	umem_free(packbuf, packsize);
4916 	umem_free(bigbuf, bigsize);
4917 	umem_free(od, size);
4918 }
4919 
4920 static void
compare_and_update_pbbufs(uint64_t s,bufwad_t * packbuf,bufwad_t * bigbuf,uint64_t bigsize,uint64_t n,uint64_t chunksize,uint64_t txg)4921 compare_and_update_pbbufs(uint64_t s, bufwad_t *packbuf, bufwad_t *bigbuf,
4922     uint64_t bigsize, uint64_t n, uint64_t chunksize, uint64_t txg)
4923 {
4924 	uint64_t i;
4925 	bufwad_t *pack;
4926 	bufwad_t *bigH;
4927 	bufwad_t *bigT;
4928 
4929 	/*
4930 	 * For each index from n to n + s, verify that the existing bufwad
4931 	 * in packobj matches the bufwads at the head and tail of the
4932 	 * corresponding chunk in bigobj.  Then update all three bufwads
4933 	 * with the new values we want to write out.
4934 	 */
4935 	for (i = 0; i < s; i++) {
4936 		/* LINTED */
4937 		pack = (bufwad_t *)((char *)packbuf + i * sizeof (bufwad_t));
4938 		/* LINTED */
4939 		bigH = (bufwad_t *)((char *)bigbuf + i * chunksize);
4940 		/* LINTED */
4941 		bigT = (bufwad_t *)((char *)bigH + chunksize) - 1;
4942 
4943 		ASSERT3U((uintptr_t)bigH - (uintptr_t)bigbuf, <, bigsize);
4944 		ASSERT3U((uintptr_t)bigT - (uintptr_t)bigbuf, <, bigsize);
4945 
4946 		if (pack->bw_txg > txg)
4947 			fatal(B_FALSE,
4948 			    "future leak: got %"PRIx64", open txg is %"PRIx64"",
4949 			    pack->bw_txg, txg);
4950 
4951 		if (pack->bw_data != 0 && pack->bw_index != n + i)
4952 			fatal(B_FALSE, "wrong index: "
4953 			    "got %"PRIx64", wanted %"PRIx64"+%"PRIx64"",
4954 			    pack->bw_index, n, i);
4955 
4956 		if (memcmp(pack, bigH, sizeof (bufwad_t)) != 0)
4957 			fatal(B_FALSE, "pack/bigH mismatch in %p/%p",
4958 			    pack, bigH);
4959 
4960 		if (memcmp(pack, bigT, sizeof (bufwad_t)) != 0)
4961 			fatal(B_FALSE, "pack/bigT mismatch in %p/%p",
4962 			    pack, bigT);
4963 
4964 		pack->bw_index = n + i;
4965 		pack->bw_txg = txg;
4966 		pack->bw_data = 1 + ztest_random(-2ULL);
4967 
4968 		*bigH = *pack;
4969 		*bigT = *pack;
4970 	}
4971 }
4972 
4973 #undef OD_ARRAY_SIZE
4974 #define	OD_ARRAY_SIZE	2
4975 
4976 void
ztest_dmu_read_write_zcopy(ztest_ds_t * zd,uint64_t id)4977 ztest_dmu_read_write_zcopy(ztest_ds_t *zd, uint64_t id)
4978 {
4979 	objset_t *os = zd->zd_os;
4980 	ztest_od_t *od;
4981 	dmu_tx_t *tx;
4982 	uint64_t i;
4983 	int error;
4984 	int size;
4985 	uint64_t n, s, txg;
4986 	bufwad_t *packbuf, *bigbuf;
4987 	uint64_t packobj, packoff, packsize, bigobj, bigoff, bigsize;
4988 	uint64_t blocksize = ztest_random_blocksize();
4989 	uint64_t chunksize = blocksize;
4990 	uint64_t regions = 997;
4991 	uint64_t stride = 123456789ULL;
4992 	uint64_t width = 9;
4993 	dmu_buf_t *bonus_db;
4994 	arc_buf_t **bigbuf_arcbufs;
4995 	dmu_object_info_t doi;
4996 
4997 	size = sizeof (ztest_od_t) * OD_ARRAY_SIZE;
4998 	od = umem_alloc(size, UMEM_NOFAIL);
4999 
5000 	/*
5001 	 * This test uses two objects, packobj and bigobj, that are always
5002 	 * updated together (i.e. in the same tx) so that their contents are
5003 	 * in sync and can be compared.  Their contents relate to each other
5004 	 * in a simple way: packobj is a dense array of 'bufwad' structures,
5005 	 * while bigobj is a sparse array of the same bufwads.  Specifically,
5006 	 * for any index n, there are three bufwads that should be identical:
5007 	 *
5008 	 *	packobj, at offset n * sizeof (bufwad_t)
5009 	 *	bigobj, at the head of the nth chunk
5010 	 *	bigobj, at the tail of the nth chunk
5011 	 *
5012 	 * The chunk size is set equal to bigobj block size so that
5013 	 * dmu_assign_arcbuf_by_dbuf() can be tested for object updates.
5014 	 */
5015 
5016 	/*
5017 	 * Read the directory info.  If it's the first time, set things up.
5018 	 */
5019 	ztest_od_init(od, id, FTAG, 0, DMU_OT_UINT64_OTHER, blocksize, 0, 0);
5020 	ztest_od_init(od + 1, id, FTAG, 1, DMU_OT_UINT64_OTHER, 0, 0,
5021 	    chunksize);
5022 
5023 
5024 	if (ztest_object_init(zd, od, size, B_FALSE) != 0) {
5025 		umem_free(od, size);
5026 		return;
5027 	}
5028 
5029 	bigobj = od[0].od_object;
5030 	packobj = od[1].od_object;
5031 	blocksize = od[0].od_blocksize;
5032 	chunksize = blocksize;
5033 	ASSERT3U(chunksize, ==, od[1].od_gen);
5034 
5035 	VERIFY0(dmu_object_info(os, bigobj, &doi));
5036 	VERIFY(ISP2(doi.doi_data_block_size));
5037 	VERIFY3U(chunksize, ==, doi.doi_data_block_size);
5038 	VERIFY3U(chunksize, >=, 2 * sizeof (bufwad_t));
5039 
5040 	/*
5041 	 * Pick a random index and compute the offsets into packobj and bigobj.
5042 	 */
5043 	n = ztest_random(regions) * stride + ztest_random(width);
5044 	s = 1 + ztest_random(width - 1);
5045 
5046 	packoff = n * sizeof (bufwad_t);
5047 	packsize = s * sizeof (bufwad_t);
5048 
5049 	bigoff = n * chunksize;
5050 	bigsize = s * chunksize;
5051 
5052 	packbuf = umem_zalloc(packsize, UMEM_NOFAIL);
5053 	bigbuf = umem_zalloc(bigsize, UMEM_NOFAIL);
5054 
5055 	VERIFY0(dmu_bonus_hold(os, bigobj, FTAG, &bonus_db));
5056 
5057 	bigbuf_arcbufs = umem_zalloc(2 * s * sizeof (arc_buf_t *), UMEM_NOFAIL);
5058 
5059 	/*
5060 	 * Iteration 0 test zcopy for DB_UNCACHED dbufs.
5061 	 * Iteration 1 test zcopy to already referenced dbufs.
5062 	 * Iteration 2 test zcopy to dirty dbuf in the same txg.
5063 	 * Iteration 3 test zcopy to dbuf dirty in previous txg.
5064 	 * Iteration 4 test zcopy when dbuf is no longer dirty.
5065 	 * Iteration 5 test zcopy when it can't be done.
5066 	 * Iteration 6 one more zcopy write.
5067 	 */
5068 	for (i = 0; i < 7; i++) {
5069 		uint64_t j;
5070 		uint64_t off;
5071 
5072 		/*
5073 		 * In iteration 5 (i == 5) use arcbufs
5074 		 * that don't match bigobj blksz to test
5075 		 * dmu_assign_arcbuf_by_dbuf() when it can't directly
5076 		 * assign an arcbuf to a dbuf.
5077 		 */
5078 		for (j = 0; j < s; j++) {
5079 			if (i != 5 || chunksize < (SPA_MINBLOCKSIZE * 2)) {
5080 				bigbuf_arcbufs[j] =
5081 				    dmu_request_arcbuf(bonus_db, chunksize);
5082 			} else {
5083 				bigbuf_arcbufs[2 * j] =
5084 				    dmu_request_arcbuf(bonus_db, chunksize / 2);
5085 				bigbuf_arcbufs[2 * j + 1] =
5086 				    dmu_request_arcbuf(bonus_db, chunksize / 2);
5087 			}
5088 		}
5089 
5090 		/*
5091 		 * Get a tx for the mods to both packobj and bigobj.
5092 		 */
5093 		tx = dmu_tx_create(os);
5094 
5095 		dmu_tx_hold_write(tx, packobj, packoff, packsize);
5096 		dmu_tx_hold_write(tx, bigobj, bigoff, bigsize);
5097 
5098 		txg = ztest_tx_assign(tx, TXG_MIGHTWAIT, FTAG);
5099 		if (txg == 0) {
5100 			umem_free(packbuf, packsize);
5101 			umem_free(bigbuf, bigsize);
5102 			for (j = 0; j < s; j++) {
5103 				if (i != 5 ||
5104 				    chunksize < (SPA_MINBLOCKSIZE * 2)) {
5105 					dmu_return_arcbuf(bigbuf_arcbufs[j]);
5106 				} else {
5107 					dmu_return_arcbuf(
5108 					    bigbuf_arcbufs[2 * j]);
5109 					dmu_return_arcbuf(
5110 					    bigbuf_arcbufs[2 * j + 1]);
5111 				}
5112 			}
5113 			umem_free(bigbuf_arcbufs, 2 * s * sizeof (arc_buf_t *));
5114 			umem_free(od, size);
5115 			dmu_buf_rele(bonus_db, FTAG);
5116 			return;
5117 		}
5118 
5119 		/*
5120 		 * 50% of the time don't read objects in the 1st iteration to
5121 		 * test dmu_assign_arcbuf_by_dbuf() for the case when there are
5122 		 * no existing dbufs for the specified offsets.
5123 		 */
5124 		if (i != 0 || ztest_random(2) != 0) {
5125 			error = dmu_read(os, packobj, packoff,
5126 			    packsize, packbuf, DMU_READ_PREFETCH);
5127 			ASSERT0(error);
5128 			error = dmu_read(os, bigobj, bigoff, bigsize,
5129 			    bigbuf, DMU_READ_PREFETCH);
5130 			ASSERT0(error);
5131 		}
5132 		compare_and_update_pbbufs(s, packbuf, bigbuf, bigsize,
5133 		    n, chunksize, txg);
5134 
5135 		/*
5136 		 * We've verified all the old bufwads, and made new ones.
5137 		 * Now write them out.
5138 		 */
5139 		dmu_write(os, packobj, packoff, packsize, packbuf, tx);
5140 		if (ztest_opts.zo_verbose >= 7) {
5141 			(void) printf("writing offset %"PRIx64" size %"PRIx64""
5142 			    " txg %"PRIx64"\n",
5143 			    bigoff, bigsize, txg);
5144 		}
5145 		for (off = bigoff, j = 0; j < s; j++, off += chunksize) {
5146 			dmu_buf_t *dbt;
5147 			if (i != 5 || chunksize < (SPA_MINBLOCKSIZE * 2)) {
5148 				memcpy(bigbuf_arcbufs[j]->b_data,
5149 				    (caddr_t)bigbuf + (off - bigoff),
5150 				    chunksize);
5151 			} else {
5152 				memcpy(bigbuf_arcbufs[2 * j]->b_data,
5153 				    (caddr_t)bigbuf + (off - bigoff),
5154 				    chunksize / 2);
5155 				memcpy(bigbuf_arcbufs[2 * j + 1]->b_data,
5156 				    (caddr_t)bigbuf + (off - bigoff) +
5157 				    chunksize / 2,
5158 				    chunksize / 2);
5159 			}
5160 
5161 			if (i == 1) {
5162 				VERIFY(dmu_buf_hold(os, bigobj, off,
5163 				    FTAG, &dbt, DMU_READ_NO_PREFETCH) == 0);
5164 			}
5165 			if (i != 5 || chunksize < (SPA_MINBLOCKSIZE * 2)) {
5166 				VERIFY0(dmu_assign_arcbuf_by_dbuf(bonus_db,
5167 				    off, bigbuf_arcbufs[j], tx));
5168 			} else {
5169 				VERIFY0(dmu_assign_arcbuf_by_dbuf(bonus_db,
5170 				    off, bigbuf_arcbufs[2 * j], tx));
5171 				VERIFY0(dmu_assign_arcbuf_by_dbuf(bonus_db,
5172 				    off + chunksize / 2,
5173 				    bigbuf_arcbufs[2 * j + 1], tx));
5174 			}
5175 			if (i == 1) {
5176 				dmu_buf_rele(dbt, FTAG);
5177 			}
5178 		}
5179 		dmu_tx_commit(tx);
5180 
5181 		/*
5182 		 * Sanity check the stuff we just wrote.
5183 		 */
5184 		{
5185 			void *packcheck = umem_alloc(packsize, UMEM_NOFAIL);
5186 			void *bigcheck = umem_alloc(bigsize, UMEM_NOFAIL);
5187 
5188 			VERIFY0(dmu_read(os, packobj, packoff,
5189 			    packsize, packcheck, DMU_READ_PREFETCH));
5190 			VERIFY0(dmu_read(os, bigobj, bigoff,
5191 			    bigsize, bigcheck, DMU_READ_PREFETCH));
5192 
5193 			ASSERT0(memcmp(packbuf, packcheck, packsize));
5194 			ASSERT0(memcmp(bigbuf, bigcheck, bigsize));
5195 
5196 			umem_free(packcheck, packsize);
5197 			umem_free(bigcheck, bigsize);
5198 		}
5199 		if (i == 2) {
5200 			txg_wait_open(dmu_objset_pool(os), 0, B_TRUE);
5201 		} else if (i == 3) {
5202 			txg_wait_synced(dmu_objset_pool(os), 0);
5203 		}
5204 	}
5205 
5206 	dmu_buf_rele(bonus_db, FTAG);
5207 	umem_free(packbuf, packsize);
5208 	umem_free(bigbuf, bigsize);
5209 	umem_free(bigbuf_arcbufs, 2 * s * sizeof (arc_buf_t *));
5210 	umem_free(od, size);
5211 }
5212 
5213 void
ztest_dmu_write_parallel(ztest_ds_t * zd,uint64_t id)5214 ztest_dmu_write_parallel(ztest_ds_t *zd, uint64_t id)
5215 {
5216 	(void) id;
5217 	ztest_od_t *od;
5218 
5219 	od = umem_alloc(sizeof (ztest_od_t), UMEM_NOFAIL);
5220 	uint64_t offset = (1ULL << (ztest_random(20) + 43)) +
5221 	    (ztest_random(ZTEST_RANGE_LOCKS) << SPA_MAXBLOCKSHIFT);
5222 
5223 	/*
5224 	 * Have multiple threads write to large offsets in an object
5225 	 * to verify that parallel writes to an object -- even to the
5226 	 * same blocks within the object -- doesn't cause any trouble.
5227 	 */
5228 	ztest_od_init(od, ID_PARALLEL, FTAG, 0, DMU_OT_UINT64_OTHER, 0, 0, 0);
5229 
5230 	if (ztest_object_init(zd, od, sizeof (ztest_od_t), B_FALSE) != 0)
5231 		return;
5232 
5233 	while (ztest_random(10) != 0)
5234 		ztest_io(zd, od->od_object, offset);
5235 
5236 	umem_free(od, sizeof (ztest_od_t));
5237 }
5238 
5239 void
ztest_dmu_prealloc(ztest_ds_t * zd,uint64_t id)5240 ztest_dmu_prealloc(ztest_ds_t *zd, uint64_t id)
5241 {
5242 	ztest_od_t *od;
5243 	uint64_t offset = (1ULL << (ztest_random(4) + SPA_MAXBLOCKSHIFT)) +
5244 	    (ztest_random(ZTEST_RANGE_LOCKS) << SPA_MAXBLOCKSHIFT);
5245 	uint64_t count = ztest_random(20) + 1;
5246 	uint64_t blocksize = ztest_random_blocksize();
5247 	void *data;
5248 
5249 	od = umem_alloc(sizeof (ztest_od_t), UMEM_NOFAIL);
5250 
5251 	ztest_od_init(od, id, FTAG, 0, DMU_OT_UINT64_OTHER, blocksize, 0, 0);
5252 
5253 	if (ztest_object_init(zd, od, sizeof (ztest_od_t),
5254 	    !ztest_random(2)) != 0) {
5255 		umem_free(od, sizeof (ztest_od_t));
5256 		return;
5257 	}
5258 
5259 	if (ztest_truncate(zd, od->od_object, offset, count * blocksize) != 0) {
5260 		umem_free(od, sizeof (ztest_od_t));
5261 		return;
5262 	}
5263 
5264 	ztest_prealloc(zd, od->od_object, offset, count * blocksize);
5265 
5266 	data = umem_zalloc(blocksize, UMEM_NOFAIL);
5267 
5268 	while (ztest_random(count) != 0) {
5269 		uint64_t randoff = offset + (ztest_random(count) * blocksize);
5270 		if (ztest_write(zd, od->od_object, randoff, blocksize,
5271 		    data) != 0)
5272 			break;
5273 		while (ztest_random(4) != 0)
5274 			ztest_io(zd, od->od_object, randoff);
5275 	}
5276 
5277 	umem_free(data, blocksize);
5278 	umem_free(od, sizeof (ztest_od_t));
5279 }
5280 
5281 /*
5282  * Verify that zap_{create,destroy,add,remove,update} work as expected.
5283  */
5284 #define	ZTEST_ZAP_MIN_INTS	1
5285 #define	ZTEST_ZAP_MAX_INTS	4
5286 #define	ZTEST_ZAP_MAX_PROPS	1000
5287 
5288 void
ztest_zap(ztest_ds_t * zd,uint64_t id)5289 ztest_zap(ztest_ds_t *zd, uint64_t id)
5290 {
5291 	objset_t *os = zd->zd_os;
5292 	ztest_od_t *od;
5293 	uint64_t object;
5294 	uint64_t txg, last_txg;
5295 	uint64_t value[ZTEST_ZAP_MAX_INTS];
5296 	uint64_t zl_ints, zl_intsize, prop;
5297 	int i, ints;
5298 	dmu_tx_t *tx;
5299 	char propname[100], txgname[100];
5300 	int error;
5301 	const char *const hc[2] = { "s.acl.h", ".s.open.h.hyLZlg" };
5302 
5303 	od = umem_alloc(sizeof (ztest_od_t), UMEM_NOFAIL);
5304 	ztest_od_init(od, id, FTAG, 0, DMU_OT_ZAP_OTHER, 0, 0, 0);
5305 
5306 	if (ztest_object_init(zd, od, sizeof (ztest_od_t),
5307 	    !ztest_random(2)) != 0)
5308 		goto out;
5309 
5310 	object = od->od_object;
5311 
5312 	/*
5313 	 * Generate a known hash collision, and verify that
5314 	 * we can lookup and remove both entries.
5315 	 */
5316 	tx = dmu_tx_create(os);
5317 	dmu_tx_hold_zap(tx, object, B_TRUE, NULL);
5318 	txg = ztest_tx_assign(tx, TXG_MIGHTWAIT, FTAG);
5319 	if (txg == 0)
5320 		goto out;
5321 	for (i = 0; i < 2; i++) {
5322 		value[i] = i;
5323 		VERIFY0(zap_add(os, object, hc[i], sizeof (uint64_t),
5324 		    1, &value[i], tx));
5325 	}
5326 	for (i = 0; i < 2; i++) {
5327 		VERIFY3U(EEXIST, ==, zap_add(os, object, hc[i],
5328 		    sizeof (uint64_t), 1, &value[i], tx));
5329 		VERIFY0(
5330 		    zap_length(os, object, hc[i], &zl_intsize, &zl_ints));
5331 		ASSERT3U(zl_intsize, ==, sizeof (uint64_t));
5332 		ASSERT3U(zl_ints, ==, 1);
5333 	}
5334 	for (i = 0; i < 2; i++) {
5335 		VERIFY0(zap_remove(os, object, hc[i], tx));
5336 	}
5337 	dmu_tx_commit(tx);
5338 
5339 	/*
5340 	 * Generate a bunch of random entries.
5341 	 */
5342 	ints = MAX(ZTEST_ZAP_MIN_INTS, object % ZTEST_ZAP_MAX_INTS);
5343 
5344 	prop = ztest_random(ZTEST_ZAP_MAX_PROPS);
5345 	(void) sprintf(propname, "prop_%"PRIu64"", prop);
5346 	(void) sprintf(txgname, "txg_%"PRIu64"", prop);
5347 	memset(value, 0, sizeof (value));
5348 	last_txg = 0;
5349 
5350 	/*
5351 	 * If these zap entries already exist, validate their contents.
5352 	 */
5353 	error = zap_length(os, object, txgname, &zl_intsize, &zl_ints);
5354 	if (error == 0) {
5355 		ASSERT3U(zl_intsize, ==, sizeof (uint64_t));
5356 		ASSERT3U(zl_ints, ==, 1);
5357 
5358 		VERIFY0(zap_lookup(os, object, txgname, zl_intsize,
5359 		    zl_ints, &last_txg));
5360 
5361 		VERIFY0(zap_length(os, object, propname, &zl_intsize,
5362 		    &zl_ints));
5363 
5364 		ASSERT3U(zl_intsize, ==, sizeof (uint64_t));
5365 		ASSERT3U(zl_ints, ==, ints);
5366 
5367 		VERIFY0(zap_lookup(os, object, propname, zl_intsize,
5368 		    zl_ints, value));
5369 
5370 		for (i = 0; i < ints; i++) {
5371 			ASSERT3U(value[i], ==, last_txg + object + i);
5372 		}
5373 	} else {
5374 		ASSERT3U(error, ==, ENOENT);
5375 	}
5376 
5377 	/*
5378 	 * Atomically update two entries in our zap object.
5379 	 * The first is named txg_%llu, and contains the txg
5380 	 * in which the property was last updated.  The second
5381 	 * is named prop_%llu, and the nth element of its value
5382 	 * should be txg + object + n.
5383 	 */
5384 	tx = dmu_tx_create(os);
5385 	dmu_tx_hold_zap(tx, object, B_TRUE, NULL);
5386 	txg = ztest_tx_assign(tx, TXG_MIGHTWAIT, FTAG);
5387 	if (txg == 0)
5388 		goto out;
5389 
5390 	if (last_txg > txg)
5391 		fatal(B_FALSE, "zap future leak: old %"PRIu64" new %"PRIu64"",
5392 		    last_txg, txg);
5393 
5394 	for (i = 0; i < ints; i++)
5395 		value[i] = txg + object + i;
5396 
5397 	VERIFY0(zap_update(os, object, txgname, sizeof (uint64_t),
5398 	    1, &txg, tx));
5399 	VERIFY0(zap_update(os, object, propname, sizeof (uint64_t),
5400 	    ints, value, tx));
5401 
5402 	dmu_tx_commit(tx);
5403 
5404 	/*
5405 	 * Remove a random pair of entries.
5406 	 */
5407 	prop = ztest_random(ZTEST_ZAP_MAX_PROPS);
5408 	(void) sprintf(propname, "prop_%"PRIu64"", prop);
5409 	(void) sprintf(txgname, "txg_%"PRIu64"", prop);
5410 
5411 	error = zap_length(os, object, txgname, &zl_intsize, &zl_ints);
5412 
5413 	if (error == ENOENT)
5414 		goto out;
5415 
5416 	ASSERT0(error);
5417 
5418 	tx = dmu_tx_create(os);
5419 	dmu_tx_hold_zap(tx, object, B_TRUE, NULL);
5420 	txg = ztest_tx_assign(tx, TXG_MIGHTWAIT, FTAG);
5421 	if (txg == 0)
5422 		goto out;
5423 	VERIFY0(zap_remove(os, object, txgname, tx));
5424 	VERIFY0(zap_remove(os, object, propname, tx));
5425 	dmu_tx_commit(tx);
5426 out:
5427 	umem_free(od, sizeof (ztest_od_t));
5428 }
5429 
5430 /*
5431  * Test case to test the upgrading of a microzap to fatzap.
5432  */
5433 void
ztest_fzap(ztest_ds_t * zd,uint64_t id)5434 ztest_fzap(ztest_ds_t *zd, uint64_t id)
5435 {
5436 	objset_t *os = zd->zd_os;
5437 	ztest_od_t *od;
5438 	uint64_t object, txg, value;
5439 
5440 	od = umem_alloc(sizeof (ztest_od_t), UMEM_NOFAIL);
5441 	ztest_od_init(od, id, FTAG, 0, DMU_OT_ZAP_OTHER, 0, 0, 0);
5442 
5443 	if (ztest_object_init(zd, od, sizeof (ztest_od_t),
5444 	    !ztest_random(2)) != 0)
5445 		goto out;
5446 	object = od->od_object;
5447 
5448 	/*
5449 	 * Add entries to this ZAP and make sure it spills over
5450 	 * and gets upgraded to a fatzap. Also, since we are adding
5451 	 * 2050 entries we should see ptrtbl growth and leaf-block split.
5452 	 */
5453 	for (value = 0; value < 2050; value++) {
5454 		char name[ZFS_MAX_DATASET_NAME_LEN];
5455 		dmu_tx_t *tx;
5456 		int error;
5457 
5458 		(void) snprintf(name, sizeof (name), "fzap-%"PRIu64"-%"PRIu64"",
5459 		    id, value);
5460 
5461 		tx = dmu_tx_create(os);
5462 		dmu_tx_hold_zap(tx, object, B_TRUE, name);
5463 		txg = ztest_tx_assign(tx, TXG_MIGHTWAIT, FTAG);
5464 		if (txg == 0)
5465 			goto out;
5466 		error = zap_add(os, object, name, sizeof (uint64_t), 1,
5467 		    &value, tx);
5468 		ASSERT(error == 0 || error == EEXIST);
5469 		dmu_tx_commit(tx);
5470 	}
5471 out:
5472 	umem_free(od, sizeof (ztest_od_t));
5473 }
5474 
5475 void
ztest_zap_parallel(ztest_ds_t * zd,uint64_t id)5476 ztest_zap_parallel(ztest_ds_t *zd, uint64_t id)
5477 {
5478 	(void) id;
5479 	objset_t *os = zd->zd_os;
5480 	ztest_od_t *od;
5481 	uint64_t txg, object, count, wsize, wc, zl_wsize, zl_wc;
5482 	dmu_tx_t *tx;
5483 	int i, namelen, error;
5484 	int micro = ztest_random(2);
5485 	char name[20], string_value[20];
5486 	void *data;
5487 
5488 	od = umem_alloc(sizeof (ztest_od_t), UMEM_NOFAIL);
5489 	ztest_od_init(od, ID_PARALLEL, FTAG, micro, DMU_OT_ZAP_OTHER, 0, 0, 0);
5490 
5491 	if (ztest_object_init(zd, od, sizeof (ztest_od_t), B_FALSE) != 0) {
5492 		umem_free(od, sizeof (ztest_od_t));
5493 		return;
5494 	}
5495 
5496 	object = od->od_object;
5497 
5498 	/*
5499 	 * Generate a random name of the form 'xxx.....' where each
5500 	 * x is a random printable character and the dots are dots.
5501 	 * There are 94 such characters, and the name length goes from
5502 	 * 6 to 20, so there are 94^3 * 15 = 12,458,760 possible names.
5503 	 */
5504 	namelen = ztest_random(sizeof (name) - 5) + 5 + 1;
5505 
5506 	for (i = 0; i < 3; i++)
5507 		name[i] = '!' + ztest_random('~' - '!' + 1);
5508 	for (; i < namelen - 1; i++)
5509 		name[i] = '.';
5510 	name[i] = '\0';
5511 
5512 	if ((namelen & 1) || micro) {
5513 		wsize = sizeof (txg);
5514 		wc = 1;
5515 		data = &txg;
5516 	} else {
5517 		wsize = 1;
5518 		wc = namelen;
5519 		data = string_value;
5520 	}
5521 
5522 	count = -1ULL;
5523 	VERIFY0(zap_count(os, object, &count));
5524 	ASSERT3S(count, !=, -1ULL);
5525 
5526 	/*
5527 	 * Select an operation: length, lookup, add, update, remove.
5528 	 */
5529 	i = ztest_random(5);
5530 
5531 	if (i >= 2) {
5532 		tx = dmu_tx_create(os);
5533 		dmu_tx_hold_zap(tx, object, B_TRUE, NULL);
5534 		txg = ztest_tx_assign(tx, TXG_MIGHTWAIT, FTAG);
5535 		if (txg == 0) {
5536 			umem_free(od, sizeof (ztest_od_t));
5537 			return;
5538 		}
5539 		memcpy(string_value, name, namelen);
5540 	} else {
5541 		tx = NULL;
5542 		txg = 0;
5543 		memset(string_value, 0, namelen);
5544 	}
5545 
5546 	switch (i) {
5547 
5548 	case 0:
5549 		error = zap_length(os, object, name, &zl_wsize, &zl_wc);
5550 		if (error == 0) {
5551 			ASSERT3U(wsize, ==, zl_wsize);
5552 			ASSERT3U(wc, ==, zl_wc);
5553 		} else {
5554 			ASSERT3U(error, ==, ENOENT);
5555 		}
5556 		break;
5557 
5558 	case 1:
5559 		error = zap_lookup(os, object, name, wsize, wc, data);
5560 		if (error == 0) {
5561 			if (data == string_value &&
5562 			    memcmp(name, data, namelen) != 0)
5563 				fatal(B_FALSE, "name '%s' != val '%s' len %d",
5564 				    name, (char *)data, namelen);
5565 		} else {
5566 			ASSERT3U(error, ==, ENOENT);
5567 		}
5568 		break;
5569 
5570 	case 2:
5571 		error = zap_add(os, object, name, wsize, wc, data, tx);
5572 		ASSERT(error == 0 || error == EEXIST);
5573 		break;
5574 
5575 	case 3:
5576 		VERIFY0(zap_update(os, object, name, wsize, wc, data, tx));
5577 		break;
5578 
5579 	case 4:
5580 		error = zap_remove(os, object, name, tx);
5581 		ASSERT(error == 0 || error == ENOENT);
5582 		break;
5583 	}
5584 
5585 	if (tx != NULL)
5586 		dmu_tx_commit(tx);
5587 
5588 	umem_free(od, sizeof (ztest_od_t));
5589 }
5590 
5591 /*
5592  * Commit callback data.
5593  */
5594 typedef struct ztest_cb_data {
5595 	list_node_t		zcd_node;
5596 	uint64_t		zcd_txg;
5597 	int			zcd_expected_err;
5598 	boolean_t		zcd_added;
5599 	boolean_t		zcd_called;
5600 	spa_t			*zcd_spa;
5601 } ztest_cb_data_t;
5602 
5603 /* This is the actual commit callback function */
5604 static void
ztest_commit_callback(void * arg,int error)5605 ztest_commit_callback(void *arg, int error)
5606 {
5607 	ztest_cb_data_t *data = arg;
5608 	uint64_t synced_txg;
5609 
5610 	VERIFY3P(data, !=, NULL);
5611 	VERIFY3S(data->zcd_expected_err, ==, error);
5612 	VERIFY(!data->zcd_called);
5613 
5614 	synced_txg = spa_last_synced_txg(data->zcd_spa);
5615 	if (data->zcd_txg > synced_txg)
5616 		fatal(B_FALSE,
5617 		    "commit callback of txg %"PRIu64" called prematurely, "
5618 		    "last synced txg = %"PRIu64"\n",
5619 		    data->zcd_txg, synced_txg);
5620 
5621 	data->zcd_called = B_TRUE;
5622 
5623 	if (error == ECANCELED) {
5624 		ASSERT0(data->zcd_txg);
5625 		ASSERT(!data->zcd_added);
5626 
5627 		/*
5628 		 * The private callback data should be destroyed here, but
5629 		 * since we are going to check the zcd_called field after
5630 		 * dmu_tx_abort(), we will destroy it there.
5631 		 */
5632 		return;
5633 	}
5634 
5635 	ASSERT(data->zcd_added);
5636 	ASSERT3U(data->zcd_txg, !=, 0);
5637 
5638 	(void) mutex_enter(&zcl.zcl_callbacks_lock);
5639 
5640 	/* See if this cb was called more quickly */
5641 	if ((synced_txg - data->zcd_txg) < zc_min_txg_delay)
5642 		zc_min_txg_delay = synced_txg - data->zcd_txg;
5643 
5644 	/* Remove our callback from the list */
5645 	list_remove(&zcl.zcl_callbacks, data);
5646 
5647 	(void) mutex_exit(&zcl.zcl_callbacks_lock);
5648 
5649 	umem_free(data, sizeof (ztest_cb_data_t));
5650 }
5651 
5652 /* Allocate and initialize callback data structure */
5653 static ztest_cb_data_t *
ztest_create_cb_data(objset_t * os,uint64_t txg)5654 ztest_create_cb_data(objset_t *os, uint64_t txg)
5655 {
5656 	ztest_cb_data_t *cb_data;
5657 
5658 	cb_data = umem_zalloc(sizeof (ztest_cb_data_t), UMEM_NOFAIL);
5659 
5660 	cb_data->zcd_txg = txg;
5661 	cb_data->zcd_spa = dmu_objset_spa(os);
5662 	list_link_init(&cb_data->zcd_node);
5663 
5664 	return (cb_data);
5665 }
5666 
5667 /*
5668  * Commit callback test.
5669  */
5670 void
ztest_dmu_commit_callbacks(ztest_ds_t * zd,uint64_t id)5671 ztest_dmu_commit_callbacks(ztest_ds_t *zd, uint64_t id)
5672 {
5673 	objset_t *os = zd->zd_os;
5674 	ztest_od_t *od;
5675 	dmu_tx_t *tx;
5676 	ztest_cb_data_t *cb_data[3], *tmp_cb;
5677 	uint64_t old_txg, txg;
5678 	int i, error = 0;
5679 
5680 	od = umem_alloc(sizeof (ztest_od_t), UMEM_NOFAIL);
5681 	ztest_od_init(od, id, FTAG, 0, DMU_OT_UINT64_OTHER, 0, 0, 0);
5682 
5683 	if (ztest_object_init(zd, od, sizeof (ztest_od_t), B_FALSE) != 0) {
5684 		umem_free(od, sizeof (ztest_od_t));
5685 		return;
5686 	}
5687 
5688 	tx = dmu_tx_create(os);
5689 
5690 	cb_data[0] = ztest_create_cb_data(os, 0);
5691 	dmu_tx_callback_register(tx, ztest_commit_callback, cb_data[0]);
5692 
5693 	dmu_tx_hold_write(tx, od->od_object, 0, sizeof (uint64_t));
5694 
5695 	/* Every once in a while, abort the transaction on purpose */
5696 	if (ztest_random(100) == 0)
5697 		error = -1;
5698 
5699 	if (!error)
5700 		error = dmu_tx_assign(tx, TXG_NOWAIT);
5701 
5702 	txg = error ? 0 : dmu_tx_get_txg(tx);
5703 
5704 	cb_data[0]->zcd_txg = txg;
5705 	cb_data[1] = ztest_create_cb_data(os, txg);
5706 	dmu_tx_callback_register(tx, ztest_commit_callback, cb_data[1]);
5707 
5708 	if (error) {
5709 		/*
5710 		 * It's not a strict requirement to call the registered
5711 		 * callbacks from inside dmu_tx_abort(), but that's what
5712 		 * it's supposed to happen in the current implementation
5713 		 * so we will check for that.
5714 		 */
5715 		for (i = 0; i < 2; i++) {
5716 			cb_data[i]->zcd_expected_err = ECANCELED;
5717 			VERIFY(!cb_data[i]->zcd_called);
5718 		}
5719 
5720 		dmu_tx_abort(tx);
5721 
5722 		for (i = 0; i < 2; i++) {
5723 			VERIFY(cb_data[i]->zcd_called);
5724 			umem_free(cb_data[i], sizeof (ztest_cb_data_t));
5725 		}
5726 
5727 		umem_free(od, sizeof (ztest_od_t));
5728 		return;
5729 	}
5730 
5731 	cb_data[2] = ztest_create_cb_data(os, txg);
5732 	dmu_tx_callback_register(tx, ztest_commit_callback, cb_data[2]);
5733 
5734 	/*
5735 	 * Read existing data to make sure there isn't a future leak.
5736 	 */
5737 	VERIFY0(dmu_read(os, od->od_object, 0, sizeof (uint64_t),
5738 	    &old_txg, DMU_READ_PREFETCH));
5739 
5740 	if (old_txg > txg)
5741 		fatal(B_FALSE,
5742 		    "future leak: got %"PRIu64", open txg is %"PRIu64"",
5743 		    old_txg, txg);
5744 
5745 	dmu_write(os, od->od_object, 0, sizeof (uint64_t), &txg, tx);
5746 
5747 	(void) mutex_enter(&zcl.zcl_callbacks_lock);
5748 
5749 	/*
5750 	 * Since commit callbacks don't have any ordering requirement and since
5751 	 * it is theoretically possible for a commit callback to be called
5752 	 * after an arbitrary amount of time has elapsed since its txg has been
5753 	 * synced, it is difficult to reliably determine whether a commit
5754 	 * callback hasn't been called due to high load or due to a flawed
5755 	 * implementation.
5756 	 *
5757 	 * In practice, we will assume that if after a certain number of txgs a
5758 	 * commit callback hasn't been called, then most likely there's an
5759 	 * implementation bug..
5760 	 */
5761 	tmp_cb = list_head(&zcl.zcl_callbacks);
5762 	if (tmp_cb != NULL &&
5763 	    tmp_cb->zcd_txg + ZTEST_COMMIT_CB_THRESH < txg) {
5764 		fatal(B_FALSE,
5765 		    "Commit callback threshold exceeded, "
5766 		    "oldest txg: %"PRIu64", open txg: %"PRIu64"\n",
5767 		    tmp_cb->zcd_txg, txg);
5768 	}
5769 
5770 	/*
5771 	 * Let's find the place to insert our callbacks.
5772 	 *
5773 	 * Even though the list is ordered by txg, it is possible for the
5774 	 * insertion point to not be the end because our txg may already be
5775 	 * quiescing at this point and other callbacks in the open txg
5776 	 * (from other objsets) may have sneaked in.
5777 	 */
5778 	tmp_cb = list_tail(&zcl.zcl_callbacks);
5779 	while (tmp_cb != NULL && tmp_cb->zcd_txg > txg)
5780 		tmp_cb = list_prev(&zcl.zcl_callbacks, tmp_cb);
5781 
5782 	/* Add the 3 callbacks to the list */
5783 	for (i = 0; i < 3; i++) {
5784 		if (tmp_cb == NULL)
5785 			list_insert_head(&zcl.zcl_callbacks, cb_data[i]);
5786 		else
5787 			list_insert_after(&zcl.zcl_callbacks, tmp_cb,
5788 			    cb_data[i]);
5789 
5790 		cb_data[i]->zcd_added = B_TRUE;
5791 		VERIFY(!cb_data[i]->zcd_called);
5792 
5793 		tmp_cb = cb_data[i];
5794 	}
5795 
5796 	zc_cb_counter += 3;
5797 
5798 	(void) mutex_exit(&zcl.zcl_callbacks_lock);
5799 
5800 	dmu_tx_commit(tx);
5801 
5802 	umem_free(od, sizeof (ztest_od_t));
5803 }
5804 
5805 /*
5806  * Visit each object in the dataset. Verify that its properties
5807  * are consistent what was stored in the block tag when it was created,
5808  * and that its unused bonus buffer space has not been overwritten.
5809  */
5810 void
ztest_verify_dnode_bt(ztest_ds_t * zd,uint64_t id)5811 ztest_verify_dnode_bt(ztest_ds_t *zd, uint64_t id)
5812 {
5813 	(void) id;
5814 	objset_t *os = zd->zd_os;
5815 	uint64_t obj;
5816 	int err = 0;
5817 
5818 	for (obj = 0; err == 0; err = dmu_object_next(os, &obj, FALSE, 0)) {
5819 		ztest_block_tag_t *bt = NULL;
5820 		dmu_object_info_t doi;
5821 		dmu_buf_t *db;
5822 
5823 		ztest_object_lock(zd, obj, RL_READER);
5824 		if (dmu_bonus_hold(os, obj, FTAG, &db) != 0) {
5825 			ztest_object_unlock(zd, obj);
5826 			continue;
5827 		}
5828 
5829 		dmu_object_info_from_db(db, &doi);
5830 		if (doi.doi_bonus_size >= sizeof (*bt))
5831 			bt = ztest_bt_bonus(db);
5832 
5833 		if (bt && bt->bt_magic == BT_MAGIC) {
5834 			ztest_bt_verify(bt, os, obj, doi.doi_dnodesize,
5835 			    bt->bt_offset, bt->bt_gen, bt->bt_txg,
5836 			    bt->bt_crtxg);
5837 			ztest_verify_unused_bonus(db, bt, obj, os, bt->bt_gen);
5838 		}
5839 
5840 		dmu_buf_rele(db, FTAG);
5841 		ztest_object_unlock(zd, obj);
5842 	}
5843 }
5844 
5845 void
ztest_dsl_prop_get_set(ztest_ds_t * zd,uint64_t id)5846 ztest_dsl_prop_get_set(ztest_ds_t *zd, uint64_t id)
5847 {
5848 	(void) id;
5849 	zfs_prop_t proplist[] = {
5850 		ZFS_PROP_CHECKSUM,
5851 		ZFS_PROP_COMPRESSION,
5852 		ZFS_PROP_COPIES,
5853 		ZFS_PROP_DEDUP
5854 	};
5855 
5856 	(void) pthread_rwlock_rdlock(&ztest_name_lock);
5857 
5858 	for (int p = 0; p < sizeof (proplist) / sizeof (proplist[0]); p++) {
5859 		int error = ztest_dsl_prop_set_uint64(zd->zd_name, proplist[p],
5860 		    ztest_random_dsl_prop(proplist[p]), (int)ztest_random(2));
5861 		ASSERT(error == 0 || error == ENOSPC);
5862 	}
5863 
5864 	int error = ztest_dsl_prop_set_uint64(zd->zd_name, ZFS_PROP_RECORDSIZE,
5865 	    ztest_random_blocksize(), (int)ztest_random(2));
5866 	ASSERT(error == 0 || error == ENOSPC);
5867 
5868 	(void) pthread_rwlock_unlock(&ztest_name_lock);
5869 }
5870 
5871 void
ztest_spa_prop_get_set(ztest_ds_t * zd,uint64_t id)5872 ztest_spa_prop_get_set(ztest_ds_t *zd, uint64_t id)
5873 {
5874 	(void) zd, (void) id;
5875 	nvlist_t *props = NULL;
5876 
5877 	(void) pthread_rwlock_rdlock(&ztest_name_lock);
5878 
5879 	(void) ztest_spa_prop_set_uint64(ZPOOL_PROP_AUTOTRIM, ztest_random(2));
5880 
5881 	VERIFY0(spa_prop_get(ztest_spa, &props));
5882 
5883 	if (ztest_opts.zo_verbose >= 6)
5884 		dump_nvlist(props, 4);
5885 
5886 	fnvlist_free(props);
5887 
5888 	(void) pthread_rwlock_unlock(&ztest_name_lock);
5889 }
5890 
5891 static int
user_release_one(const char * snapname,const char * holdname)5892 user_release_one(const char *snapname, const char *holdname)
5893 {
5894 	nvlist_t *snaps, *holds;
5895 	int error;
5896 
5897 	snaps = fnvlist_alloc();
5898 	holds = fnvlist_alloc();
5899 	fnvlist_add_boolean(holds, holdname);
5900 	fnvlist_add_nvlist(snaps, snapname, holds);
5901 	fnvlist_free(holds);
5902 	error = dsl_dataset_user_release(snaps, NULL);
5903 	fnvlist_free(snaps);
5904 	return (error);
5905 }
5906 
5907 /*
5908  * Test snapshot hold/release and deferred destroy.
5909  */
5910 void
ztest_dmu_snapshot_hold(ztest_ds_t * zd,uint64_t id)5911 ztest_dmu_snapshot_hold(ztest_ds_t *zd, uint64_t id)
5912 {
5913 	int error;
5914 	objset_t *os = zd->zd_os;
5915 	objset_t *origin;
5916 	char snapname[100];
5917 	char fullname[100];
5918 	char clonename[100];
5919 	char tag[100];
5920 	char osname[ZFS_MAX_DATASET_NAME_LEN];
5921 	nvlist_t *holds;
5922 
5923 	(void) pthread_rwlock_rdlock(&ztest_name_lock);
5924 
5925 	dmu_objset_name(os, osname);
5926 
5927 	(void) snprintf(snapname, sizeof (snapname), "sh1_%"PRIu64"", id);
5928 	(void) snprintf(fullname, sizeof (fullname), "%s@%s", osname, snapname);
5929 	(void) snprintf(clonename, sizeof (clonename), "%s/ch1_%"PRIu64"",
5930 	    osname, id);
5931 	(void) snprintf(tag, sizeof (tag), "tag_%"PRIu64"", id);
5932 
5933 	/*
5934 	 * Clean up from any previous run.
5935 	 */
5936 	error = dsl_destroy_head(clonename);
5937 	if (error != ENOENT)
5938 		ASSERT0(error);
5939 	error = user_release_one(fullname, tag);
5940 	if (error != ESRCH && error != ENOENT)
5941 		ASSERT0(error);
5942 	error = dsl_destroy_snapshot(fullname, B_FALSE);
5943 	if (error != ENOENT)
5944 		ASSERT0(error);
5945 
5946 	/*
5947 	 * Create snapshot, clone it, mark snap for deferred destroy,
5948 	 * destroy clone, verify snap was also destroyed.
5949 	 */
5950 	error = dmu_objset_snapshot_one(osname, snapname);
5951 	if (error) {
5952 		if (error == ENOSPC) {
5953 			ztest_record_enospc("dmu_objset_snapshot");
5954 			goto out;
5955 		}
5956 		fatal(B_FALSE, "dmu_objset_snapshot(%s) = %d", fullname, error);
5957 	}
5958 
5959 	error = dmu_objset_clone(clonename, fullname);
5960 	if (error) {
5961 		if (error == ENOSPC) {
5962 			ztest_record_enospc("dmu_objset_clone");
5963 			goto out;
5964 		}
5965 		fatal(B_FALSE, "dmu_objset_clone(%s) = %d", clonename, error);
5966 	}
5967 
5968 	error = dsl_destroy_snapshot(fullname, B_TRUE);
5969 	if (error) {
5970 		fatal(B_FALSE, "dsl_destroy_snapshot(%s, B_TRUE) = %d",
5971 		    fullname, error);
5972 	}
5973 
5974 	error = dsl_destroy_head(clonename);
5975 	if (error)
5976 		fatal(B_FALSE, "dsl_destroy_head(%s) = %d", clonename, error);
5977 
5978 	error = dmu_objset_hold(fullname, FTAG, &origin);
5979 	if (error != ENOENT)
5980 		fatal(B_FALSE, "dmu_objset_hold(%s) = %d", fullname, error);
5981 
5982 	/*
5983 	 * Create snapshot, add temporary hold, verify that we can't
5984 	 * destroy a held snapshot, mark for deferred destroy,
5985 	 * release hold, verify snapshot was destroyed.
5986 	 */
5987 	error = dmu_objset_snapshot_one(osname, snapname);
5988 	if (error) {
5989 		if (error == ENOSPC) {
5990 			ztest_record_enospc("dmu_objset_snapshot");
5991 			goto out;
5992 		}
5993 		fatal(B_FALSE, "dmu_objset_snapshot(%s) = %d", fullname, error);
5994 	}
5995 
5996 	holds = fnvlist_alloc();
5997 	fnvlist_add_string(holds, fullname, tag);
5998 	error = dsl_dataset_user_hold(holds, 0, NULL);
5999 	fnvlist_free(holds);
6000 
6001 	if (error == ENOSPC) {
6002 		ztest_record_enospc("dsl_dataset_user_hold");
6003 		goto out;
6004 	} else if (error) {
6005 		fatal(B_FALSE, "dsl_dataset_user_hold(%s, %s) = %u",
6006 		    fullname, tag, error);
6007 	}
6008 
6009 	error = dsl_destroy_snapshot(fullname, B_FALSE);
6010 	if (error != EBUSY) {
6011 		fatal(B_FALSE, "dsl_destroy_snapshot(%s, B_FALSE) = %d",
6012 		    fullname, error);
6013 	}
6014 
6015 	error = dsl_destroy_snapshot(fullname, B_TRUE);
6016 	if (error) {
6017 		fatal(B_FALSE, "dsl_destroy_snapshot(%s, B_TRUE) = %d",
6018 		    fullname, error);
6019 	}
6020 
6021 	error = user_release_one(fullname, tag);
6022 	if (error)
6023 		fatal(B_FALSE, "user_release_one(%s, %s) = %d",
6024 		    fullname, tag, error);
6025 
6026 	VERIFY3U(dmu_objset_hold(fullname, FTAG, &origin), ==, ENOENT);
6027 
6028 out:
6029 	(void) pthread_rwlock_unlock(&ztest_name_lock);
6030 }
6031 
6032 /*
6033  * Inject random faults into the on-disk data.
6034  */
6035 void
ztest_fault_inject(ztest_ds_t * zd,uint64_t id)6036 ztest_fault_inject(ztest_ds_t *zd, uint64_t id)
6037 {
6038 	(void) zd, (void) id;
6039 	ztest_shared_t *zs = ztest_shared;
6040 	spa_t *spa = ztest_spa;
6041 	int fd;
6042 	uint64_t offset;
6043 	uint64_t leaves;
6044 	uint64_t bad = 0x1990c0ffeedecadeull;
6045 	uint64_t top, leaf;
6046 	char *path0;
6047 	char *pathrand;
6048 	size_t fsize;
6049 	int bshift = SPA_MAXBLOCKSHIFT + 2;
6050 	int iters = 1000;
6051 	int maxfaults;
6052 	int mirror_save;
6053 	vdev_t *vd0 = NULL;
6054 	uint64_t guid0 = 0;
6055 	boolean_t islog = B_FALSE;
6056 
6057 	path0 = umem_alloc(MAXPATHLEN, UMEM_NOFAIL);
6058 	pathrand = umem_alloc(MAXPATHLEN, UMEM_NOFAIL);
6059 
6060 	mutex_enter(&ztest_vdev_lock);
6061 
6062 	/*
6063 	 * Device removal is in progress, fault injection must be disabled
6064 	 * until it completes and the pool is scrubbed.  The fault injection
6065 	 * strategy for damaging blocks does not take in to account evacuated
6066 	 * blocks which may have already been damaged.
6067 	 */
6068 	if (ztest_device_removal_active) {
6069 		mutex_exit(&ztest_vdev_lock);
6070 		goto out;
6071 	}
6072 
6073 	maxfaults = MAXFAULTS(zs);
6074 	leaves = MAX(zs->zs_mirrors, 1) * ztest_opts.zo_raid_children;
6075 	mirror_save = zs->zs_mirrors;
6076 	mutex_exit(&ztest_vdev_lock);
6077 
6078 	ASSERT3U(leaves, >=, 1);
6079 
6080 	/*
6081 	 * While ztest is running the number of leaves will not change.  This
6082 	 * is critical for the fault injection logic as it determines where
6083 	 * errors can be safely injected such that they are always repairable.
6084 	 *
6085 	 * When restarting ztest a different number of leaves may be requested
6086 	 * which will shift the regions to be damaged.  This is fine as long
6087 	 * as the pool has been scrubbed prior to using the new mapping.
6088 	 * Failure to do can result in non-repairable damage being injected.
6089 	 */
6090 	if (ztest_pool_scrubbed == B_FALSE)
6091 		goto out;
6092 
6093 	/*
6094 	 * Grab the name lock as reader. There are some operations
6095 	 * which don't like to have their vdevs changed while
6096 	 * they are in progress (i.e. spa_change_guid). Those
6097 	 * operations will have grabbed the name lock as writer.
6098 	 */
6099 	(void) pthread_rwlock_rdlock(&ztest_name_lock);
6100 
6101 	/*
6102 	 * We need SCL_STATE here because we're going to look at vd0->vdev_tsd.
6103 	 */
6104 	spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
6105 
6106 	if (ztest_random(2) == 0) {
6107 		/*
6108 		 * Inject errors on a normal data device or slog device.
6109 		 */
6110 		top = ztest_random_vdev_top(spa, B_TRUE);
6111 		leaf = ztest_random(leaves) + zs->zs_splits;
6112 
6113 		/*
6114 		 * Generate paths to the first leaf in this top-level vdev,
6115 		 * and to the random leaf we selected.  We'll induce transient
6116 		 * write failures and random online/offline activity on leaf 0,
6117 		 * and we'll write random garbage to the randomly chosen leaf.
6118 		 */
6119 		(void) snprintf(path0, MAXPATHLEN, ztest_dev_template,
6120 		    ztest_opts.zo_dir, ztest_opts.zo_pool,
6121 		    top * leaves + zs->zs_splits);
6122 		(void) snprintf(pathrand, MAXPATHLEN, ztest_dev_template,
6123 		    ztest_opts.zo_dir, ztest_opts.zo_pool,
6124 		    top * leaves + leaf);
6125 
6126 		vd0 = vdev_lookup_by_path(spa->spa_root_vdev, path0);
6127 		if (vd0 != NULL && vd0->vdev_top->vdev_islog)
6128 			islog = B_TRUE;
6129 
6130 		/*
6131 		 * If the top-level vdev needs to be resilvered
6132 		 * then we only allow faults on the device that is
6133 		 * resilvering.
6134 		 */
6135 		if (vd0 != NULL && maxfaults != 1 &&
6136 		    (!vdev_resilver_needed(vd0->vdev_top, NULL, NULL) ||
6137 		    vd0->vdev_resilver_txg != 0)) {
6138 			/*
6139 			 * Make vd0 explicitly claim to be unreadable,
6140 			 * or unwritable, or reach behind its back
6141 			 * and close the underlying fd.  We can do this if
6142 			 * maxfaults == 0 because we'll fail and reexecute,
6143 			 * and we can do it if maxfaults >= 2 because we'll
6144 			 * have enough redundancy.  If maxfaults == 1, the
6145 			 * combination of this with injection of random data
6146 			 * corruption below exceeds the pool's fault tolerance.
6147 			 */
6148 			vdev_file_t *vf = vd0->vdev_tsd;
6149 
6150 			zfs_dbgmsg("injecting fault to vdev %llu; maxfaults=%d",
6151 			    (long long)vd0->vdev_id, (int)maxfaults);
6152 
6153 			if (vf != NULL && ztest_random(3) == 0) {
6154 				(void) close(vf->vf_file->f_fd);
6155 				vf->vf_file->f_fd = -1;
6156 			} else if (ztest_random(2) == 0) {
6157 				vd0->vdev_cant_read = B_TRUE;
6158 			} else {
6159 				vd0->vdev_cant_write = B_TRUE;
6160 			}
6161 			guid0 = vd0->vdev_guid;
6162 		}
6163 	} else {
6164 		/*
6165 		 * Inject errors on an l2cache device.
6166 		 */
6167 		spa_aux_vdev_t *sav = &spa->spa_l2cache;
6168 
6169 		if (sav->sav_count == 0) {
6170 			spa_config_exit(spa, SCL_STATE, FTAG);
6171 			(void) pthread_rwlock_unlock(&ztest_name_lock);
6172 			goto out;
6173 		}
6174 		vd0 = sav->sav_vdevs[ztest_random(sav->sav_count)];
6175 		guid0 = vd0->vdev_guid;
6176 		(void) strlcpy(path0, vd0->vdev_path, MAXPATHLEN);
6177 		(void) strlcpy(pathrand, vd0->vdev_path, MAXPATHLEN);
6178 
6179 		leaf = 0;
6180 		leaves = 1;
6181 		maxfaults = INT_MAX;	/* no limit on cache devices */
6182 	}
6183 
6184 	spa_config_exit(spa, SCL_STATE, FTAG);
6185 	(void) pthread_rwlock_unlock(&ztest_name_lock);
6186 
6187 	/*
6188 	 * If we can tolerate two or more faults, or we're dealing
6189 	 * with a slog, randomly online/offline vd0.
6190 	 */
6191 	if ((maxfaults >= 2 || islog) && guid0 != 0) {
6192 		if (ztest_random(10) < 6) {
6193 			int flags = (ztest_random(2) == 0 ?
6194 			    ZFS_OFFLINE_TEMPORARY : 0);
6195 
6196 			/*
6197 			 * We have to grab the zs_name_lock as writer to
6198 			 * prevent a race between offlining a slog and
6199 			 * destroying a dataset. Offlining the slog will
6200 			 * grab a reference on the dataset which may cause
6201 			 * dsl_destroy_head() to fail with EBUSY thus
6202 			 * leaving the dataset in an inconsistent state.
6203 			 */
6204 			if (islog)
6205 				(void) pthread_rwlock_wrlock(&ztest_name_lock);
6206 
6207 			VERIFY3U(vdev_offline(spa, guid0, flags), !=, EBUSY);
6208 
6209 			if (islog)
6210 				(void) pthread_rwlock_unlock(&ztest_name_lock);
6211 		} else {
6212 			/*
6213 			 * Ideally we would like to be able to randomly
6214 			 * call vdev_[on|off]line without holding locks
6215 			 * to force unpredictable failures but the side
6216 			 * effects of vdev_[on|off]line prevent us from
6217 			 * doing so. We grab the ztest_vdev_lock here to
6218 			 * prevent a race between injection testing and
6219 			 * aux_vdev removal.
6220 			 */
6221 			mutex_enter(&ztest_vdev_lock);
6222 			(void) vdev_online(spa, guid0, 0, NULL);
6223 			mutex_exit(&ztest_vdev_lock);
6224 		}
6225 	}
6226 
6227 	if (maxfaults == 0)
6228 		goto out;
6229 
6230 	/*
6231 	 * We have at least single-fault tolerance, so inject data corruption.
6232 	 */
6233 	fd = open(pathrand, O_RDWR);
6234 
6235 	if (fd == -1) /* we hit a gap in the device namespace */
6236 		goto out;
6237 
6238 	fsize = lseek(fd, 0, SEEK_END);
6239 
6240 	while (--iters != 0) {
6241 		/*
6242 		 * The offset must be chosen carefully to ensure that
6243 		 * we do not inject a given logical block with errors
6244 		 * on two different leaf devices, because ZFS can not
6245 		 * tolerate that (if maxfaults==1).
6246 		 *
6247 		 * To achieve this we divide each leaf device into
6248 		 * chunks of size (# leaves * SPA_MAXBLOCKSIZE * 4).
6249 		 * Each chunk is further divided into error-injection
6250 		 * ranges (can accept errors) and clear ranges (we do
6251 		 * not inject errors in those). Each error-injection
6252 		 * range can accept errors only for a single leaf vdev.
6253 		 * Error-injection ranges are separated by clear ranges.
6254 		 *
6255 		 * For example, with 3 leaves, each chunk looks like:
6256 		 *    0 to  32M: injection range for leaf 0
6257 		 *  32M to  64M: clear range - no injection allowed
6258 		 *  64M to  96M: injection range for leaf 1
6259 		 *  96M to 128M: clear range - no injection allowed
6260 		 * 128M to 160M: injection range for leaf 2
6261 		 * 160M to 192M: clear range - no injection allowed
6262 		 *
6263 		 * Each clear range must be large enough such that a
6264 		 * single block cannot straddle it. This way a block
6265 		 * can't be a target in two different injection ranges
6266 		 * (on different leaf vdevs).
6267 		 */
6268 		offset = ztest_random(fsize / (leaves << bshift)) *
6269 		    (leaves << bshift) + (leaf << bshift) +
6270 		    (ztest_random(1ULL << (bshift - 1)) & -8ULL);
6271 
6272 		/*
6273 		 * Only allow damage to the labels at one end of the vdev.
6274 		 *
6275 		 * If all labels are damaged, the device will be totally
6276 		 * inaccessible, which will result in loss of data,
6277 		 * because we also damage (parts of) the other side of
6278 		 * the mirror/raidz.
6279 		 *
6280 		 * Additionally, we will always have both an even and an
6281 		 * odd label, so that we can handle crashes in the
6282 		 * middle of vdev_config_sync().
6283 		 */
6284 		if ((leaf & 1) == 0 && offset < VDEV_LABEL_START_SIZE)
6285 			continue;
6286 
6287 		/*
6288 		 * The two end labels are stored at the "end" of the disk, but
6289 		 * the end of the disk (vdev_psize) is aligned to
6290 		 * sizeof (vdev_label_t).
6291 		 */
6292 		uint64_t psize = P2ALIGN_TYPED(fsize, sizeof (vdev_label_t),
6293 		    uint64_t);
6294 		if ((leaf & 1) == 1 &&
6295 		    offset + sizeof (bad) > psize - VDEV_LABEL_END_SIZE)
6296 			continue;
6297 
6298 		mutex_enter(&ztest_vdev_lock);
6299 		if (mirror_save != zs->zs_mirrors) {
6300 			mutex_exit(&ztest_vdev_lock);
6301 			(void) close(fd);
6302 			goto out;
6303 		}
6304 
6305 		if (pwrite(fd, &bad, sizeof (bad), offset) != sizeof (bad))
6306 			fatal(B_TRUE,
6307 			    "can't inject bad word at 0x%"PRIx64" in %s",
6308 			    offset, pathrand);
6309 
6310 		mutex_exit(&ztest_vdev_lock);
6311 
6312 		if (ztest_opts.zo_verbose >= 7)
6313 			(void) printf("injected bad word into %s,"
6314 			    " offset 0x%"PRIx64"\n", pathrand, offset);
6315 	}
6316 
6317 	(void) close(fd);
6318 out:
6319 	umem_free(path0, MAXPATHLEN);
6320 	umem_free(pathrand, MAXPATHLEN);
6321 }
6322 
6323 /*
6324  * By design ztest will never inject uncorrectable damage in to the pool.
6325  * Issue a scrub, wait for it to complete, and verify there is never any
6326  * persistent damage.
6327  *
6328  * Only after a full scrub has been completed is it safe to start injecting
6329  * data corruption.  See the comment in zfs_fault_inject().
6330  */
6331 static int
ztest_scrub_impl(spa_t * spa)6332 ztest_scrub_impl(spa_t *spa)
6333 {
6334 	int error = spa_scan(spa, POOL_SCAN_SCRUB);
6335 	if (error)
6336 		return (error);
6337 
6338 	while (dsl_scan_scrubbing(spa_get_dsl(spa)))
6339 		txg_wait_synced(spa_get_dsl(spa), 0);
6340 
6341 	if (spa_approx_errlog_size(spa) > 0)
6342 		return (ECKSUM);
6343 
6344 	ztest_pool_scrubbed = B_TRUE;
6345 
6346 	return (0);
6347 }
6348 
6349 /*
6350  * Scrub the pool.
6351  */
6352 void
ztest_scrub(ztest_ds_t * zd,uint64_t id)6353 ztest_scrub(ztest_ds_t *zd, uint64_t id)
6354 {
6355 	(void) zd, (void) id;
6356 	spa_t *spa = ztest_spa;
6357 	int error;
6358 
6359 	/*
6360 	 * Scrub in progress by device removal.
6361 	 */
6362 	if (ztest_device_removal_active)
6363 		return;
6364 
6365 	/*
6366 	 * Start a scrub, wait a moment, then force a restart.
6367 	 */
6368 	(void) spa_scan(spa, POOL_SCAN_SCRUB);
6369 	(void) poll(NULL, 0, 100);
6370 
6371 	error = ztest_scrub_impl(spa);
6372 	if (error == EBUSY)
6373 		error = 0;
6374 	ASSERT0(error);
6375 }
6376 
6377 /*
6378  * Change the guid for the pool.
6379  */
6380 void
ztest_reguid(ztest_ds_t * zd,uint64_t id)6381 ztest_reguid(ztest_ds_t *zd, uint64_t id)
6382 {
6383 	(void) zd, (void) id;
6384 	spa_t *spa = ztest_spa;
6385 	uint64_t orig, load;
6386 	int error;
6387 	ztest_shared_t *zs = ztest_shared;
6388 
6389 	if (ztest_opts.zo_mmp_test)
6390 		return;
6391 
6392 	orig = spa_guid(spa);
6393 	load = spa_load_guid(spa);
6394 
6395 	(void) pthread_rwlock_wrlock(&ztest_name_lock);
6396 	error = spa_change_guid(spa);
6397 	zs->zs_guid = spa_guid(spa);
6398 	(void) pthread_rwlock_unlock(&ztest_name_lock);
6399 
6400 	if (error != 0)
6401 		return;
6402 
6403 	if (ztest_opts.zo_verbose >= 4) {
6404 		(void) printf("Changed guid old %"PRIu64" -> %"PRIu64"\n",
6405 		    orig, spa_guid(spa));
6406 	}
6407 
6408 	VERIFY3U(orig, !=, spa_guid(spa));
6409 	VERIFY3U(load, ==, spa_load_guid(spa));
6410 }
6411 
6412 void
ztest_blake3(ztest_ds_t * zd,uint64_t id)6413 ztest_blake3(ztest_ds_t *zd, uint64_t id)
6414 {
6415 	(void) zd, (void) id;
6416 	hrtime_t end = gethrtime() + NANOSEC;
6417 	zio_cksum_salt_t salt;
6418 	void *salt_ptr = &salt.zcs_bytes;
6419 	struct abd *abd_data, *abd_meta;
6420 	void *buf, *templ;
6421 	int i, *ptr;
6422 	uint32_t size;
6423 	BLAKE3_CTX ctx;
6424 	const zfs_impl_t *blake3 = zfs_impl_get_ops("blake3");
6425 
6426 	size = ztest_random_blocksize();
6427 	buf = umem_alloc(size, UMEM_NOFAIL);
6428 	abd_data = abd_alloc(size, B_FALSE);
6429 	abd_meta = abd_alloc(size, B_TRUE);
6430 
6431 	for (i = 0, ptr = buf; i < size / sizeof (*ptr); i++, ptr++)
6432 		*ptr = ztest_random(UINT_MAX);
6433 	memset(salt_ptr, 'A', 32);
6434 
6435 	abd_copy_from_buf_off(abd_data, buf, 0, size);
6436 	abd_copy_from_buf_off(abd_meta, buf, 0, size);
6437 
6438 	while (gethrtime() <= end) {
6439 		int run_count = 100;
6440 		zio_cksum_t zc_ref1, zc_ref2;
6441 		zio_cksum_t zc_res1, zc_res2;
6442 
6443 		void *ref1 = &zc_ref1;
6444 		void *ref2 = &zc_ref2;
6445 		void *res1 = &zc_res1;
6446 		void *res2 = &zc_res2;
6447 
6448 		/* BLAKE3_KEY_LEN = 32 */
6449 		VERIFY0(blake3->setname("generic"));
6450 		templ = abd_checksum_blake3_tmpl_init(&salt);
6451 		Blake3_InitKeyed(&ctx, salt_ptr);
6452 		Blake3_Update(&ctx, buf, size);
6453 		Blake3_Final(&ctx, ref1);
6454 		zc_ref2 = zc_ref1;
6455 		ZIO_CHECKSUM_BSWAP(&zc_ref2);
6456 		abd_checksum_blake3_tmpl_free(templ);
6457 
6458 		VERIFY0(blake3->setname("cycle"));
6459 		while (run_count-- > 0) {
6460 
6461 			/* Test current implementation */
6462 			Blake3_InitKeyed(&ctx, salt_ptr);
6463 			Blake3_Update(&ctx, buf, size);
6464 			Blake3_Final(&ctx, res1);
6465 			zc_res2 = zc_res1;
6466 			ZIO_CHECKSUM_BSWAP(&zc_res2);
6467 
6468 			VERIFY0(memcmp(ref1, res1, 32));
6469 			VERIFY0(memcmp(ref2, res2, 32));
6470 
6471 			/* Test ABD - data */
6472 			templ = abd_checksum_blake3_tmpl_init(&salt);
6473 			abd_checksum_blake3_native(abd_data, size,
6474 			    templ, &zc_res1);
6475 			abd_checksum_blake3_byteswap(abd_data, size,
6476 			    templ, &zc_res2);
6477 
6478 			VERIFY0(memcmp(ref1, res1, 32));
6479 			VERIFY0(memcmp(ref2, res2, 32));
6480 
6481 			/* Test ABD - metadata */
6482 			abd_checksum_blake3_native(abd_meta, size,
6483 			    templ, &zc_res1);
6484 			abd_checksum_blake3_byteswap(abd_meta, size,
6485 			    templ, &zc_res2);
6486 			abd_checksum_blake3_tmpl_free(templ);
6487 
6488 			VERIFY0(memcmp(ref1, res1, 32));
6489 			VERIFY0(memcmp(ref2, res2, 32));
6490 
6491 		}
6492 	}
6493 
6494 	abd_free(abd_data);
6495 	abd_free(abd_meta);
6496 	umem_free(buf, size);
6497 }
6498 
6499 void
ztest_fletcher(ztest_ds_t * zd,uint64_t id)6500 ztest_fletcher(ztest_ds_t *zd, uint64_t id)
6501 {
6502 	(void) zd, (void) id;
6503 	hrtime_t end = gethrtime() + NANOSEC;
6504 
6505 	while (gethrtime() <= end) {
6506 		int run_count = 100;
6507 		void *buf;
6508 		struct abd *abd_data, *abd_meta;
6509 		uint32_t size;
6510 		int *ptr;
6511 		int i;
6512 		zio_cksum_t zc_ref;
6513 		zio_cksum_t zc_ref_byteswap;
6514 
6515 		size = ztest_random_blocksize();
6516 
6517 		buf = umem_alloc(size, UMEM_NOFAIL);
6518 		abd_data = abd_alloc(size, B_FALSE);
6519 		abd_meta = abd_alloc(size, B_TRUE);
6520 
6521 		for (i = 0, ptr = buf; i < size / sizeof (*ptr); i++, ptr++)
6522 			*ptr = ztest_random(UINT_MAX);
6523 
6524 		abd_copy_from_buf_off(abd_data, buf, 0, size);
6525 		abd_copy_from_buf_off(abd_meta, buf, 0, size);
6526 
6527 		VERIFY0(fletcher_4_impl_set("scalar"));
6528 		fletcher_4_native(buf, size, NULL, &zc_ref);
6529 		fletcher_4_byteswap(buf, size, NULL, &zc_ref_byteswap);
6530 
6531 		VERIFY0(fletcher_4_impl_set("cycle"));
6532 		while (run_count-- > 0) {
6533 			zio_cksum_t zc;
6534 			zio_cksum_t zc_byteswap;
6535 
6536 			fletcher_4_byteswap(buf, size, NULL, &zc_byteswap);
6537 			fletcher_4_native(buf, size, NULL, &zc);
6538 
6539 			VERIFY0(memcmp(&zc, &zc_ref, sizeof (zc)));
6540 			VERIFY0(memcmp(&zc_byteswap, &zc_ref_byteswap,
6541 			    sizeof (zc_byteswap)));
6542 
6543 			/* Test ABD - data */
6544 			abd_fletcher_4_byteswap(abd_data, size, NULL,
6545 			    &zc_byteswap);
6546 			abd_fletcher_4_native(abd_data, size, NULL, &zc);
6547 
6548 			VERIFY0(memcmp(&zc, &zc_ref, sizeof (zc)));
6549 			VERIFY0(memcmp(&zc_byteswap, &zc_ref_byteswap,
6550 			    sizeof (zc_byteswap)));
6551 
6552 			/* Test ABD - metadata */
6553 			abd_fletcher_4_byteswap(abd_meta, size, NULL,
6554 			    &zc_byteswap);
6555 			abd_fletcher_4_native(abd_meta, size, NULL, &zc);
6556 
6557 			VERIFY0(memcmp(&zc, &zc_ref, sizeof (zc)));
6558 			VERIFY0(memcmp(&zc_byteswap, &zc_ref_byteswap,
6559 			    sizeof (zc_byteswap)));
6560 
6561 		}
6562 
6563 		umem_free(buf, size);
6564 		abd_free(abd_data);
6565 		abd_free(abd_meta);
6566 	}
6567 }
6568 
6569 void
ztest_fletcher_incr(ztest_ds_t * zd,uint64_t id)6570 ztest_fletcher_incr(ztest_ds_t *zd, uint64_t id)
6571 {
6572 	(void) zd, (void) id;
6573 	void *buf;
6574 	size_t size;
6575 	int *ptr;
6576 	int i;
6577 	zio_cksum_t zc_ref;
6578 	zio_cksum_t zc_ref_bswap;
6579 
6580 	hrtime_t end = gethrtime() + NANOSEC;
6581 
6582 	while (gethrtime() <= end) {
6583 		int run_count = 100;
6584 
6585 		size = ztest_random_blocksize();
6586 		buf = umem_alloc(size, UMEM_NOFAIL);
6587 
6588 		for (i = 0, ptr = buf; i < size / sizeof (*ptr); i++, ptr++)
6589 			*ptr = ztest_random(UINT_MAX);
6590 
6591 		VERIFY0(fletcher_4_impl_set("scalar"));
6592 		fletcher_4_native(buf, size, NULL, &zc_ref);
6593 		fletcher_4_byteswap(buf, size, NULL, &zc_ref_bswap);
6594 
6595 		VERIFY0(fletcher_4_impl_set("cycle"));
6596 
6597 		while (run_count-- > 0) {
6598 			zio_cksum_t zc;
6599 			zio_cksum_t zc_bswap;
6600 			size_t pos = 0;
6601 
6602 			ZIO_SET_CHECKSUM(&zc, 0, 0, 0, 0);
6603 			ZIO_SET_CHECKSUM(&zc_bswap, 0, 0, 0, 0);
6604 
6605 			while (pos < size) {
6606 				size_t inc = 64 * ztest_random(size / 67);
6607 				/* sometimes add few bytes to test non-simd */
6608 				if (ztest_random(100) < 10)
6609 					inc += P2ALIGN_TYPED(ztest_random(64),
6610 					    sizeof (uint32_t), uint64_t);
6611 
6612 				if (inc > (size - pos))
6613 					inc = size - pos;
6614 
6615 				fletcher_4_incremental_native(buf + pos, inc,
6616 				    &zc);
6617 				fletcher_4_incremental_byteswap(buf + pos, inc,
6618 				    &zc_bswap);
6619 
6620 				pos += inc;
6621 			}
6622 
6623 			VERIFY3U(pos, ==, size);
6624 
6625 			VERIFY(ZIO_CHECKSUM_EQUAL(zc, zc_ref));
6626 			VERIFY(ZIO_CHECKSUM_EQUAL(zc_bswap, zc_ref_bswap));
6627 
6628 			/*
6629 			 * verify if incremental on the whole buffer is
6630 			 * equivalent to non-incremental version
6631 			 */
6632 			ZIO_SET_CHECKSUM(&zc, 0, 0, 0, 0);
6633 			ZIO_SET_CHECKSUM(&zc_bswap, 0, 0, 0, 0);
6634 
6635 			fletcher_4_incremental_native(buf, size, &zc);
6636 			fletcher_4_incremental_byteswap(buf, size, &zc_bswap);
6637 
6638 			VERIFY(ZIO_CHECKSUM_EQUAL(zc, zc_ref));
6639 			VERIFY(ZIO_CHECKSUM_EQUAL(zc_bswap, zc_ref_bswap));
6640 		}
6641 
6642 		umem_free(buf, size);
6643 	}
6644 }
6645 
6646 static int
ztest_set_global_vars(void)6647 ztest_set_global_vars(void)
6648 {
6649 	for (size_t i = 0; i < ztest_opts.zo_gvars_count; i++) {
6650 		char *kv = ztest_opts.zo_gvars[i];
6651 		VERIFY3U(strlen(kv), <=, ZO_GVARS_MAX_ARGLEN);
6652 		VERIFY3U(strlen(kv), >, 0);
6653 		int err = set_global_var(kv);
6654 		if (ztest_opts.zo_verbose > 0) {
6655 			(void) printf("setting global var %s ... %s\n", kv,
6656 			    err ? "failed" : "ok");
6657 		}
6658 		if (err != 0) {
6659 			(void) fprintf(stderr,
6660 			    "failed to set global var '%s'\n", kv);
6661 			return (err);
6662 		}
6663 	}
6664 	return (0);
6665 }
6666 
6667 static char **
ztest_global_vars_to_zdb_args(void)6668 ztest_global_vars_to_zdb_args(void)
6669 {
6670 	char **args = calloc(2*ztest_opts.zo_gvars_count + 1, sizeof (char *));
6671 	char **cur = args;
6672 	if (args == NULL)
6673 		return (NULL);
6674 	for (size_t i = 0; i < ztest_opts.zo_gvars_count; i++) {
6675 		*cur++ = (char *)"-o";
6676 		*cur++ = ztest_opts.zo_gvars[i];
6677 	}
6678 	ASSERT3P(cur, ==, &args[2*ztest_opts.zo_gvars_count]);
6679 	*cur = NULL;
6680 	return (args);
6681 }
6682 
6683 /* The end of strings is indicated by a NULL element */
6684 static char *
join_strings(char ** strings,const char * sep)6685 join_strings(char **strings, const char *sep)
6686 {
6687 	size_t totallen = 0;
6688 	for (char **sp = strings; *sp != NULL; sp++) {
6689 		totallen += strlen(*sp);
6690 		totallen += strlen(sep);
6691 	}
6692 	if (totallen > 0) {
6693 		ASSERT(totallen >= strlen(sep));
6694 		totallen -= strlen(sep);
6695 	}
6696 
6697 	size_t buflen = totallen + 1;
6698 	char *o = umem_alloc(buflen, UMEM_NOFAIL); /* trailing 0 byte */
6699 	o[0] = '\0';
6700 	for (char **sp = strings; *sp != NULL; sp++) {
6701 		size_t would;
6702 		would = strlcat(o, *sp, buflen);
6703 		VERIFY3U(would, <, buflen);
6704 		if (*(sp+1) == NULL) {
6705 			break;
6706 		}
6707 		would = strlcat(o, sep, buflen);
6708 		VERIFY3U(would, <, buflen);
6709 	}
6710 	ASSERT3S(strlen(o), ==, totallen);
6711 	return (o);
6712 }
6713 
6714 static int
ztest_check_path(char * path)6715 ztest_check_path(char *path)
6716 {
6717 	struct stat s;
6718 	/* return true on success */
6719 	return (!stat(path, &s));
6720 }
6721 
6722 static void
ztest_get_zdb_bin(char * bin,int len)6723 ztest_get_zdb_bin(char *bin, int len)
6724 {
6725 	char *zdb_path;
6726 	/*
6727 	 * Try to use $ZDB and in-tree zdb path. If not successful, just
6728 	 * let popen to search through PATH.
6729 	 */
6730 	if ((zdb_path = getenv("ZDB"))) {
6731 		strlcpy(bin, zdb_path, len); /* In env */
6732 		if (!ztest_check_path(bin)) {
6733 			ztest_dump_core = 0;
6734 			fatal(B_TRUE, "invalid ZDB '%s'", bin);
6735 		}
6736 		return;
6737 	}
6738 
6739 	VERIFY3P(realpath(getexecname(), bin), !=, NULL);
6740 	if (strstr(bin, ".libs/ztest")) {
6741 		strstr(bin, ".libs/ztest")[0] = '\0'; /* In-tree */
6742 		strcat(bin, "zdb");
6743 		if (ztest_check_path(bin))
6744 			return;
6745 	}
6746 	strcpy(bin, "zdb");
6747 }
6748 
6749 static vdev_t *
ztest_random_concrete_vdev_leaf(vdev_t * vd)6750 ztest_random_concrete_vdev_leaf(vdev_t *vd)
6751 {
6752 	if (vd == NULL)
6753 		return (NULL);
6754 
6755 	if (vd->vdev_children == 0)
6756 		return (vd);
6757 
6758 	vdev_t *eligible[vd->vdev_children];
6759 	int eligible_idx = 0, i;
6760 	for (i = 0; i < vd->vdev_children; i++) {
6761 		vdev_t *cvd = vd->vdev_child[i];
6762 		if (cvd->vdev_top->vdev_removing)
6763 			continue;
6764 		if (cvd->vdev_children > 0 ||
6765 		    (vdev_is_concrete(cvd) && !cvd->vdev_detached)) {
6766 			eligible[eligible_idx++] = cvd;
6767 		}
6768 	}
6769 	VERIFY3S(eligible_idx, >, 0);
6770 
6771 	uint64_t child_no = ztest_random(eligible_idx);
6772 	return (ztest_random_concrete_vdev_leaf(eligible[child_no]));
6773 }
6774 
6775 void
ztest_initialize(ztest_ds_t * zd,uint64_t id)6776 ztest_initialize(ztest_ds_t *zd, uint64_t id)
6777 {
6778 	(void) zd, (void) id;
6779 	spa_t *spa = ztest_spa;
6780 	int error = 0;
6781 
6782 	mutex_enter(&ztest_vdev_lock);
6783 
6784 	spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
6785 
6786 	/* Random leaf vdev */
6787 	vdev_t *rand_vd = ztest_random_concrete_vdev_leaf(spa->spa_root_vdev);
6788 	if (rand_vd == NULL) {
6789 		spa_config_exit(spa, SCL_VDEV, FTAG);
6790 		mutex_exit(&ztest_vdev_lock);
6791 		return;
6792 	}
6793 
6794 	/*
6795 	 * The random vdev we've selected may change as soon as we
6796 	 * drop the spa_config_lock. We create local copies of things
6797 	 * we're interested in.
6798 	 */
6799 	uint64_t guid = rand_vd->vdev_guid;
6800 	char *path = strdup(rand_vd->vdev_path);
6801 	boolean_t active = rand_vd->vdev_initialize_thread != NULL;
6802 
6803 	zfs_dbgmsg("vd %px, guid %llu", rand_vd, (u_longlong_t)guid);
6804 	spa_config_exit(spa, SCL_VDEV, FTAG);
6805 
6806 	uint64_t cmd = ztest_random(POOL_INITIALIZE_FUNCS);
6807 
6808 	nvlist_t *vdev_guids = fnvlist_alloc();
6809 	nvlist_t *vdev_errlist = fnvlist_alloc();
6810 	fnvlist_add_uint64(vdev_guids, path, guid);
6811 	error = spa_vdev_initialize(spa, vdev_guids, cmd, vdev_errlist);
6812 	fnvlist_free(vdev_guids);
6813 	fnvlist_free(vdev_errlist);
6814 
6815 	switch (cmd) {
6816 	case POOL_INITIALIZE_CANCEL:
6817 		if (ztest_opts.zo_verbose >= 4) {
6818 			(void) printf("Cancel initialize %s", path);
6819 			if (!active)
6820 				(void) printf(" failed (no initialize active)");
6821 			(void) printf("\n");
6822 		}
6823 		break;
6824 	case POOL_INITIALIZE_START:
6825 		if (ztest_opts.zo_verbose >= 4) {
6826 			(void) printf("Start initialize %s", path);
6827 			if (active && error == 0)
6828 				(void) printf(" failed (already active)");
6829 			else if (error != 0)
6830 				(void) printf(" failed (error %d)", error);
6831 			(void) printf("\n");
6832 		}
6833 		break;
6834 	case POOL_INITIALIZE_SUSPEND:
6835 		if (ztest_opts.zo_verbose >= 4) {
6836 			(void) printf("Suspend initialize %s", path);
6837 			if (!active)
6838 				(void) printf(" failed (no initialize active)");
6839 			(void) printf("\n");
6840 		}
6841 		break;
6842 	}
6843 	free(path);
6844 	mutex_exit(&ztest_vdev_lock);
6845 }
6846 
6847 void
ztest_trim(ztest_ds_t * zd,uint64_t id)6848 ztest_trim(ztest_ds_t *zd, uint64_t id)
6849 {
6850 	(void) zd, (void) id;
6851 	spa_t *spa = ztest_spa;
6852 	int error = 0;
6853 
6854 	mutex_enter(&ztest_vdev_lock);
6855 
6856 	spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
6857 
6858 	/* Random leaf vdev */
6859 	vdev_t *rand_vd = ztest_random_concrete_vdev_leaf(spa->spa_root_vdev);
6860 	if (rand_vd == NULL) {
6861 		spa_config_exit(spa, SCL_VDEV, FTAG);
6862 		mutex_exit(&ztest_vdev_lock);
6863 		return;
6864 	}
6865 
6866 	/*
6867 	 * The random vdev we've selected may change as soon as we
6868 	 * drop the spa_config_lock. We create local copies of things
6869 	 * we're interested in.
6870 	 */
6871 	uint64_t guid = rand_vd->vdev_guid;
6872 	char *path = strdup(rand_vd->vdev_path);
6873 	boolean_t active = rand_vd->vdev_trim_thread != NULL;
6874 
6875 	zfs_dbgmsg("vd %p, guid %llu", rand_vd, (u_longlong_t)guid);
6876 	spa_config_exit(spa, SCL_VDEV, FTAG);
6877 
6878 	uint64_t cmd = ztest_random(POOL_TRIM_FUNCS);
6879 	uint64_t rate = 1 << ztest_random(30);
6880 	boolean_t partial = (ztest_random(5) > 0);
6881 	boolean_t secure = (ztest_random(5) > 0);
6882 
6883 	nvlist_t *vdev_guids = fnvlist_alloc();
6884 	nvlist_t *vdev_errlist = fnvlist_alloc();
6885 	fnvlist_add_uint64(vdev_guids, path, guid);
6886 	error = spa_vdev_trim(spa, vdev_guids, cmd, rate, partial,
6887 	    secure, vdev_errlist);
6888 	fnvlist_free(vdev_guids);
6889 	fnvlist_free(vdev_errlist);
6890 
6891 	switch (cmd) {
6892 	case POOL_TRIM_CANCEL:
6893 		if (ztest_opts.zo_verbose >= 4) {
6894 			(void) printf("Cancel TRIM %s", path);
6895 			if (!active)
6896 				(void) printf(" failed (no TRIM active)");
6897 			(void) printf("\n");
6898 		}
6899 		break;
6900 	case POOL_TRIM_START:
6901 		if (ztest_opts.zo_verbose >= 4) {
6902 			(void) printf("Start TRIM %s", path);
6903 			if (active && error == 0)
6904 				(void) printf(" failed (already active)");
6905 			else if (error != 0)
6906 				(void) printf(" failed (error %d)", error);
6907 			(void) printf("\n");
6908 		}
6909 		break;
6910 	case POOL_TRIM_SUSPEND:
6911 		if (ztest_opts.zo_verbose >= 4) {
6912 			(void) printf("Suspend TRIM %s", path);
6913 			if (!active)
6914 				(void) printf(" failed (no TRIM active)");
6915 			(void) printf("\n");
6916 		}
6917 		break;
6918 	}
6919 	free(path);
6920 	mutex_exit(&ztest_vdev_lock);
6921 }
6922 
6923 /*
6924  * Verify pool integrity by running zdb.
6925  */
6926 static void
ztest_run_zdb(uint64_t guid)6927 ztest_run_zdb(uint64_t guid)
6928 {
6929 	int status;
6930 	char *bin;
6931 	char *zdb;
6932 	char *zbuf;
6933 	const int len = MAXPATHLEN + MAXNAMELEN + 20;
6934 	FILE *fp;
6935 
6936 	bin = umem_alloc(len, UMEM_NOFAIL);
6937 	zdb = umem_alloc(len, UMEM_NOFAIL);
6938 	zbuf = umem_alloc(1024, UMEM_NOFAIL);
6939 
6940 	ztest_get_zdb_bin(bin, len);
6941 
6942 	char **set_gvars_args = ztest_global_vars_to_zdb_args();
6943 	if (set_gvars_args == NULL) {
6944 		fatal(B_FALSE, "Failed to allocate memory in "
6945 		    "ztest_global_vars_to_zdb_args(). Cannot run zdb.\n");
6946 	}
6947 	char *set_gvars_args_joined = join_strings(set_gvars_args, " ");
6948 	free(set_gvars_args);
6949 
6950 	size_t would = snprintf(zdb, len,
6951 	    "%s -bcc%s%s -G -d -Y -e -y %s -p %s %"PRIu64,
6952 	    bin,
6953 	    ztest_opts.zo_verbose >= 3 ? "s" : "",
6954 	    ztest_opts.zo_verbose >= 4 ? "v" : "",
6955 	    set_gvars_args_joined,
6956 	    ztest_opts.zo_dir,
6957 	    guid);
6958 	ASSERT3U(would, <, len);
6959 
6960 	umem_free(set_gvars_args_joined, strlen(set_gvars_args_joined) + 1);
6961 
6962 	if (ztest_opts.zo_verbose >= 5)
6963 		(void) printf("Executing %s\n", zdb);
6964 
6965 	fp = popen(zdb, "r");
6966 
6967 	while (fgets(zbuf, 1024, fp) != NULL)
6968 		if (ztest_opts.zo_verbose >= 3)
6969 			(void) printf("%s", zbuf);
6970 
6971 	status = pclose(fp);
6972 
6973 	if (status == 0)
6974 		goto out;
6975 
6976 	ztest_dump_core = 0;
6977 	if (WIFEXITED(status))
6978 		fatal(B_FALSE, "'%s' exit code %d", zdb, WEXITSTATUS(status));
6979 	else
6980 		fatal(B_FALSE, "'%s' died with signal %d",
6981 		    zdb, WTERMSIG(status));
6982 out:
6983 	umem_free(bin, len);
6984 	umem_free(zdb, len);
6985 	umem_free(zbuf, 1024);
6986 }
6987 
6988 static void
ztest_walk_pool_directory(const char * header)6989 ztest_walk_pool_directory(const char *header)
6990 {
6991 	spa_t *spa = NULL;
6992 
6993 	if (ztest_opts.zo_verbose >= 6)
6994 		(void) puts(header);
6995 
6996 	mutex_enter(&spa_namespace_lock);
6997 	while ((spa = spa_next(spa)) != NULL)
6998 		if (ztest_opts.zo_verbose >= 6)
6999 			(void) printf("\t%s\n", spa_name(spa));
7000 	mutex_exit(&spa_namespace_lock);
7001 }
7002 
7003 static void
ztest_spa_import_export(char * oldname,char * newname)7004 ztest_spa_import_export(char *oldname, char *newname)
7005 {
7006 	nvlist_t *config, *newconfig;
7007 	uint64_t pool_guid;
7008 	spa_t *spa;
7009 	int error;
7010 
7011 	if (ztest_opts.zo_verbose >= 4) {
7012 		(void) printf("import/export: old = %s, new = %s\n",
7013 		    oldname, newname);
7014 	}
7015 
7016 	/*
7017 	 * Clean up from previous runs.
7018 	 */
7019 	(void) spa_destroy(newname);
7020 
7021 	/*
7022 	 * Get the pool's configuration and guid.
7023 	 */
7024 	VERIFY0(spa_open(oldname, &spa, FTAG));
7025 
7026 	/*
7027 	 * Kick off a scrub to tickle scrub/export races.
7028 	 */
7029 	if (ztest_random(2) == 0)
7030 		(void) spa_scan(spa, POOL_SCAN_SCRUB);
7031 
7032 	pool_guid = spa_guid(spa);
7033 	spa_close(spa, FTAG);
7034 
7035 	ztest_walk_pool_directory("pools before export");
7036 
7037 	/*
7038 	 * Export it.
7039 	 */
7040 	VERIFY0(spa_export(oldname, &config, B_FALSE, B_FALSE));
7041 
7042 	ztest_walk_pool_directory("pools after export");
7043 
7044 	/*
7045 	 * Try to import it.
7046 	 */
7047 	newconfig = spa_tryimport(config);
7048 	ASSERT3P(newconfig, !=, NULL);
7049 	fnvlist_free(newconfig);
7050 
7051 	/*
7052 	 * Import it under the new name.
7053 	 */
7054 	error = spa_import(newname, config, NULL, 0);
7055 	if (error != 0) {
7056 		dump_nvlist(config, 0);
7057 		fatal(B_FALSE, "couldn't import pool %s as %s: error %u",
7058 		    oldname, newname, error);
7059 	}
7060 
7061 	ztest_walk_pool_directory("pools after import");
7062 
7063 	/*
7064 	 * Try to import it again -- should fail with EEXIST.
7065 	 */
7066 	VERIFY3U(EEXIST, ==, spa_import(newname, config, NULL, 0));
7067 
7068 	/*
7069 	 * Try to import it under a different name -- should fail with EEXIST.
7070 	 */
7071 	VERIFY3U(EEXIST, ==, spa_import(oldname, config, NULL, 0));
7072 
7073 	/*
7074 	 * Verify that the pool is no longer visible under the old name.
7075 	 */
7076 	VERIFY3U(ENOENT, ==, spa_open(oldname, &spa, FTAG));
7077 
7078 	/*
7079 	 * Verify that we can open and close the pool using the new name.
7080 	 */
7081 	VERIFY0(spa_open(newname, &spa, FTAG));
7082 	ASSERT3U(pool_guid, ==, spa_guid(spa));
7083 	spa_close(spa, FTAG);
7084 
7085 	fnvlist_free(config);
7086 }
7087 
7088 static void
ztest_resume(spa_t * spa)7089 ztest_resume(spa_t *spa)
7090 {
7091 	if (spa_suspended(spa) && ztest_opts.zo_verbose >= 6)
7092 		(void) printf("resuming from suspended state\n");
7093 	spa_vdev_state_enter(spa, SCL_NONE);
7094 	vdev_clear(spa, NULL);
7095 	(void) spa_vdev_state_exit(spa, NULL, 0);
7096 	(void) zio_resume(spa);
7097 }
7098 
7099 static __attribute__((noreturn)) void
ztest_resume_thread(void * arg)7100 ztest_resume_thread(void *arg)
7101 {
7102 	spa_t *spa = arg;
7103 
7104 	while (!ztest_exiting) {
7105 		if (spa_suspended(spa))
7106 			ztest_resume(spa);
7107 		(void) poll(NULL, 0, 100);
7108 
7109 		/*
7110 		 * Periodically change the zfs_compressed_arc_enabled setting.
7111 		 */
7112 		if (ztest_random(10) == 0)
7113 			zfs_compressed_arc_enabled = ztest_random(2);
7114 
7115 		/*
7116 		 * Periodically change the zfs_abd_scatter_enabled setting.
7117 		 */
7118 		if (ztest_random(10) == 0)
7119 			zfs_abd_scatter_enabled = ztest_random(2);
7120 	}
7121 
7122 	thread_exit();
7123 }
7124 
7125 static __attribute__((noreturn)) void
ztest_deadman_thread(void * arg)7126 ztest_deadman_thread(void *arg)
7127 {
7128 	ztest_shared_t *zs = arg;
7129 	spa_t *spa = ztest_spa;
7130 	hrtime_t delay, overdue, last_run = gethrtime();
7131 
7132 	delay = (zs->zs_thread_stop - zs->zs_thread_start) +
7133 	    MSEC2NSEC(zfs_deadman_synctime_ms);
7134 
7135 	while (!ztest_exiting) {
7136 		/*
7137 		 * Wait for the delay timer while checking occasionally
7138 		 * if we should stop.
7139 		 */
7140 		if (gethrtime() < last_run + delay) {
7141 			(void) poll(NULL, 0, 1000);
7142 			continue;
7143 		}
7144 
7145 		/*
7146 		 * If the pool is suspended then fail immediately. Otherwise,
7147 		 * check to see if the pool is making any progress. If
7148 		 * vdev_deadman() discovers that there hasn't been any recent
7149 		 * I/Os then it will end up aborting the tests.
7150 		 */
7151 		if (spa_suspended(spa) || spa->spa_root_vdev == NULL) {
7152 			fatal(B_FALSE,
7153 			    "aborting test after %llu seconds because "
7154 			    "pool has transitioned to a suspended state.",
7155 			    (u_longlong_t)zfs_deadman_synctime_ms / 1000);
7156 		}
7157 		vdev_deadman(spa->spa_root_vdev, FTAG);
7158 
7159 		/*
7160 		 * If the process doesn't complete within a grace period of
7161 		 * zfs_deadman_synctime_ms over the expected finish time,
7162 		 * then it may be hung and is terminated.
7163 		 */
7164 		overdue = zs->zs_proc_stop + MSEC2NSEC(zfs_deadman_synctime_ms);
7165 		if (gethrtime() > overdue) {
7166 			fatal(B_FALSE,
7167 			    "aborting test after %llu seconds because "
7168 			    "the process is overdue for termination.",
7169 			    (gethrtime() - zs->zs_proc_start) / NANOSEC);
7170 		}
7171 
7172 		(void) printf("ztest has been running for %lld seconds\n",
7173 		    (gethrtime() - zs->zs_proc_start) / NANOSEC);
7174 
7175 		last_run = gethrtime();
7176 		delay = MSEC2NSEC(zfs_deadman_checktime_ms);
7177 	}
7178 
7179 	thread_exit();
7180 }
7181 
7182 static void
ztest_execute(int test,ztest_info_t * zi,uint64_t id)7183 ztest_execute(int test, ztest_info_t *zi, uint64_t id)
7184 {
7185 	ztest_ds_t *zd = &ztest_ds[id % ztest_opts.zo_datasets];
7186 	ztest_shared_callstate_t *zc = ZTEST_GET_SHARED_CALLSTATE(test);
7187 	hrtime_t functime = gethrtime();
7188 	int i;
7189 
7190 	for (i = 0; i < zi->zi_iters; i++)
7191 		zi->zi_func(zd, id);
7192 
7193 	functime = gethrtime() - functime;
7194 
7195 	atomic_add_64(&zc->zc_count, 1);
7196 	atomic_add_64(&zc->zc_time, functime);
7197 
7198 	if (ztest_opts.zo_verbose >= 4)
7199 		(void) printf("%6.2f sec in %s\n",
7200 		    (double)functime / NANOSEC, zi->zi_funcname);
7201 }
7202 
7203 static __attribute__((noreturn)) void
ztest_thread(void * arg)7204 ztest_thread(void *arg)
7205 {
7206 	int rand;
7207 	uint64_t id = (uintptr_t)arg;
7208 	ztest_shared_t *zs = ztest_shared;
7209 	uint64_t call_next;
7210 	hrtime_t now;
7211 	ztest_info_t *zi;
7212 	ztest_shared_callstate_t *zc;
7213 
7214 	while ((now = gethrtime()) < zs->zs_thread_stop) {
7215 		/*
7216 		 * See if it's time to force a crash.
7217 		 */
7218 		if (now > zs->zs_thread_kill)
7219 			ztest_kill(zs);
7220 
7221 		/*
7222 		 * If we're getting ENOSPC with some regularity, stop.
7223 		 */
7224 		if (zs->zs_enospc_count > 10)
7225 			break;
7226 
7227 		/*
7228 		 * Pick a random function to execute.
7229 		 */
7230 		rand = ztest_random(ZTEST_FUNCS);
7231 		zi = &ztest_info[rand];
7232 		zc = ZTEST_GET_SHARED_CALLSTATE(rand);
7233 		call_next = zc->zc_next;
7234 
7235 		if (now >= call_next &&
7236 		    atomic_cas_64(&zc->zc_next, call_next, call_next +
7237 		    ztest_random(2 * zi->zi_interval[0] + 1)) == call_next) {
7238 			ztest_execute(rand, zi, id);
7239 		}
7240 	}
7241 
7242 	thread_exit();
7243 }
7244 
7245 static void
ztest_dataset_name(char * dsname,const char * pool,int d)7246 ztest_dataset_name(char *dsname, const char *pool, int d)
7247 {
7248 	(void) snprintf(dsname, ZFS_MAX_DATASET_NAME_LEN, "%s/ds_%d", pool, d);
7249 }
7250 
7251 static void
ztest_dataset_destroy(int d)7252 ztest_dataset_destroy(int d)
7253 {
7254 	char name[ZFS_MAX_DATASET_NAME_LEN];
7255 	int t;
7256 
7257 	ztest_dataset_name(name, ztest_opts.zo_pool, d);
7258 
7259 	if (ztest_opts.zo_verbose >= 3)
7260 		(void) printf("Destroying %s to free up space\n", name);
7261 
7262 	/*
7263 	 * Cleanup any non-standard clones and snapshots.  In general,
7264 	 * ztest thread t operates on dataset (t % zopt_datasets),
7265 	 * so there may be more than one thing to clean up.
7266 	 */
7267 	for (t = d; t < ztest_opts.zo_threads;
7268 	    t += ztest_opts.zo_datasets)
7269 		ztest_dsl_dataset_cleanup(name, t);
7270 
7271 	(void) dmu_objset_find(name, ztest_objset_destroy_cb, NULL,
7272 	    DS_FIND_SNAPSHOTS | DS_FIND_CHILDREN);
7273 }
7274 
7275 static void
ztest_dataset_dirobj_verify(ztest_ds_t * zd)7276 ztest_dataset_dirobj_verify(ztest_ds_t *zd)
7277 {
7278 	uint64_t usedobjs, dirobjs, scratch;
7279 
7280 	/*
7281 	 * ZTEST_DIROBJ is the object directory for the entire dataset.
7282 	 * Therefore, the number of objects in use should equal the
7283 	 * number of ZTEST_DIROBJ entries, +1 for ZTEST_DIROBJ itself.
7284 	 * If not, we have an object leak.
7285 	 *
7286 	 * Note that we can only check this in ztest_dataset_open(),
7287 	 * when the open-context and syncing-context values agree.
7288 	 * That's because zap_count() returns the open-context value,
7289 	 * while dmu_objset_space() returns the rootbp fill count.
7290 	 */
7291 	VERIFY0(zap_count(zd->zd_os, ZTEST_DIROBJ, &dirobjs));
7292 	dmu_objset_space(zd->zd_os, &scratch, &scratch, &usedobjs, &scratch);
7293 	ASSERT3U(dirobjs + 1, ==, usedobjs);
7294 }
7295 
7296 static int
ztest_dataset_open(int d)7297 ztest_dataset_open(int d)
7298 {
7299 	ztest_ds_t *zd = &ztest_ds[d];
7300 	uint64_t committed_seq = ZTEST_GET_SHARED_DS(d)->zd_seq;
7301 	objset_t *os;
7302 	zilog_t *zilog;
7303 	char name[ZFS_MAX_DATASET_NAME_LEN];
7304 	int error;
7305 
7306 	ztest_dataset_name(name, ztest_opts.zo_pool, d);
7307 
7308 	(void) pthread_rwlock_rdlock(&ztest_name_lock);
7309 
7310 	error = ztest_dataset_create(name);
7311 	if (error == ENOSPC) {
7312 		(void) pthread_rwlock_unlock(&ztest_name_lock);
7313 		ztest_record_enospc(FTAG);
7314 		return (error);
7315 	}
7316 	ASSERT(error == 0 || error == EEXIST);
7317 
7318 	VERIFY0(ztest_dmu_objset_own(name, DMU_OST_OTHER, B_FALSE,
7319 	    B_TRUE, zd, &os));
7320 	(void) pthread_rwlock_unlock(&ztest_name_lock);
7321 
7322 	ztest_zd_init(zd, ZTEST_GET_SHARED_DS(d), os);
7323 
7324 	zilog = zd->zd_zilog;
7325 
7326 	if (zilog->zl_header->zh_claim_lr_seq != 0 &&
7327 	    zilog->zl_header->zh_claim_lr_seq < committed_seq)
7328 		fatal(B_FALSE, "missing log records: "
7329 		    "claimed %"PRIu64" < committed %"PRIu64"",
7330 		    zilog->zl_header->zh_claim_lr_seq, committed_seq);
7331 
7332 	ztest_dataset_dirobj_verify(zd);
7333 
7334 	zil_replay(os, zd, ztest_replay_vector);
7335 
7336 	ztest_dataset_dirobj_verify(zd);
7337 
7338 	if (ztest_opts.zo_verbose >= 6)
7339 		(void) printf("%s replay %"PRIu64" blocks, "
7340 		    "%"PRIu64" records, seq %"PRIu64"\n",
7341 		    zd->zd_name,
7342 		    zilog->zl_parse_blk_count,
7343 		    zilog->zl_parse_lr_count,
7344 		    zilog->zl_replaying_seq);
7345 
7346 	zilog = zil_open(os, ztest_get_data, NULL);
7347 
7348 	if (zilog->zl_replaying_seq != 0 &&
7349 	    zilog->zl_replaying_seq < committed_seq)
7350 		fatal(B_FALSE, "missing log records: "
7351 		    "replayed %"PRIu64" < committed %"PRIu64"",
7352 		    zilog->zl_replaying_seq, committed_seq);
7353 
7354 	return (0);
7355 }
7356 
7357 static void
ztest_dataset_close(int d)7358 ztest_dataset_close(int d)
7359 {
7360 	ztest_ds_t *zd = &ztest_ds[d];
7361 
7362 	zil_close(zd->zd_zilog);
7363 	dmu_objset_disown(zd->zd_os, B_TRUE, zd);
7364 
7365 	ztest_zd_fini(zd);
7366 }
7367 
7368 static int
ztest_replay_zil_cb(const char * name,void * arg)7369 ztest_replay_zil_cb(const char *name, void *arg)
7370 {
7371 	(void) arg;
7372 	objset_t *os;
7373 	ztest_ds_t *zdtmp;
7374 
7375 	VERIFY0(ztest_dmu_objset_own(name, DMU_OST_ANY, B_TRUE,
7376 	    B_TRUE, FTAG, &os));
7377 
7378 	zdtmp = umem_alloc(sizeof (ztest_ds_t), UMEM_NOFAIL);
7379 
7380 	ztest_zd_init(zdtmp, NULL, os);
7381 	zil_replay(os, zdtmp, ztest_replay_vector);
7382 	ztest_zd_fini(zdtmp);
7383 
7384 	if (dmu_objset_zil(os)->zl_parse_lr_count != 0 &&
7385 	    ztest_opts.zo_verbose >= 6) {
7386 		zilog_t *zilog = dmu_objset_zil(os);
7387 
7388 		(void) printf("%s replay %"PRIu64" blocks, "
7389 		    "%"PRIu64" records, seq %"PRIu64"\n",
7390 		    name,
7391 		    zilog->zl_parse_blk_count,
7392 		    zilog->zl_parse_lr_count,
7393 		    zilog->zl_replaying_seq);
7394 	}
7395 
7396 	umem_free(zdtmp, sizeof (ztest_ds_t));
7397 
7398 	dmu_objset_disown(os, B_TRUE, FTAG);
7399 	return (0);
7400 }
7401 
7402 static void
ztest_freeze(void)7403 ztest_freeze(void)
7404 {
7405 	ztest_ds_t *zd = &ztest_ds[0];
7406 	spa_t *spa;
7407 	int numloops = 0;
7408 
7409 	if (ztest_opts.zo_verbose >= 3)
7410 		(void) printf("testing spa_freeze()...\n");
7411 
7412 	kernel_init(SPA_MODE_READ | SPA_MODE_WRITE);
7413 	VERIFY0(spa_open(ztest_opts.zo_pool, &spa, FTAG));
7414 	VERIFY0(ztest_dataset_open(0));
7415 	ztest_spa = spa;
7416 
7417 	/*
7418 	 * Force the first log block to be transactionally allocated.
7419 	 * We have to do this before we freeze the pool -- otherwise
7420 	 * the log chain won't be anchored.
7421 	 */
7422 	while (BP_IS_HOLE(&zd->zd_zilog->zl_header->zh_log)) {
7423 		ztest_dmu_object_alloc_free(zd, 0);
7424 		zil_commit(zd->zd_zilog, 0);
7425 	}
7426 
7427 	txg_wait_synced(spa_get_dsl(spa), 0);
7428 
7429 	/*
7430 	 * Freeze the pool.  This stops spa_sync() from doing anything,
7431 	 * so that the only way to record changes from now on is the ZIL.
7432 	 */
7433 	spa_freeze(spa);
7434 
7435 	/*
7436 	 * Because it is hard to predict how much space a write will actually
7437 	 * require beforehand, we leave ourselves some fudge space to write over
7438 	 * capacity.
7439 	 */
7440 	uint64_t capacity = metaslab_class_get_space(spa_normal_class(spa)) / 2;
7441 
7442 	/*
7443 	 * Run tests that generate log records but don't alter the pool config
7444 	 * or depend on DSL sync tasks (snapshots, objset create/destroy, etc).
7445 	 * We do a txg_wait_synced() after each iteration to force the txg
7446 	 * to increase well beyond the last synced value in the uberblock.
7447 	 * The ZIL should be OK with that.
7448 	 *
7449 	 * Run a random number of times less than zo_maxloops and ensure we do
7450 	 * not run out of space on the pool.
7451 	 */
7452 	while (ztest_random(10) != 0 &&
7453 	    numloops++ < ztest_opts.zo_maxloops &&
7454 	    metaslab_class_get_alloc(spa_normal_class(spa)) < capacity) {
7455 		ztest_od_t od;
7456 		ztest_od_init(&od, 0, FTAG, 0, DMU_OT_UINT64_OTHER, 0, 0, 0);
7457 		VERIFY0(ztest_object_init(zd, &od, sizeof (od), B_FALSE));
7458 		ztest_io(zd, od.od_object,
7459 		    ztest_random(ZTEST_RANGE_LOCKS) << SPA_MAXBLOCKSHIFT);
7460 		txg_wait_synced(spa_get_dsl(spa), 0);
7461 	}
7462 
7463 	/*
7464 	 * Commit all of the changes we just generated.
7465 	 */
7466 	zil_commit(zd->zd_zilog, 0);
7467 	txg_wait_synced(spa_get_dsl(spa), 0);
7468 
7469 	/*
7470 	 * Close our dataset and close the pool.
7471 	 */
7472 	ztest_dataset_close(0);
7473 	spa_close(spa, FTAG);
7474 	kernel_fini();
7475 
7476 	/*
7477 	 * Open and close the pool and dataset to induce log replay.
7478 	 */
7479 	kernel_init(SPA_MODE_READ | SPA_MODE_WRITE);
7480 	VERIFY0(spa_open(ztest_opts.zo_pool, &spa, FTAG));
7481 	ASSERT3U(spa_freeze_txg(spa), ==, UINT64_MAX);
7482 	VERIFY0(ztest_dataset_open(0));
7483 	ztest_spa = spa;
7484 	txg_wait_synced(spa_get_dsl(spa), 0);
7485 	ztest_dataset_close(0);
7486 	ztest_reguid(NULL, 0);
7487 
7488 	spa_close(spa, FTAG);
7489 	kernel_fini();
7490 }
7491 
7492 static void
ztest_import_impl(void)7493 ztest_import_impl(void)
7494 {
7495 	importargs_t args = { 0 };
7496 	nvlist_t *cfg = NULL;
7497 	int nsearch = 1;
7498 	char *searchdirs[nsearch];
7499 	int flags = ZFS_IMPORT_MISSING_LOG;
7500 
7501 	searchdirs[0] = ztest_opts.zo_dir;
7502 	args.paths = nsearch;
7503 	args.path = searchdirs;
7504 	args.can_be_active = B_FALSE;
7505 
7506 	libpc_handle_t lpch = {
7507 		.lpc_lib_handle = NULL,
7508 		.lpc_ops = &libzpool_config_ops,
7509 		.lpc_printerr = B_TRUE
7510 	};
7511 	VERIFY0(zpool_find_config(&lpch, ztest_opts.zo_pool, &cfg, &args));
7512 	VERIFY0(spa_import(ztest_opts.zo_pool, cfg, NULL, flags));
7513 	fnvlist_free(cfg);
7514 }
7515 
7516 /*
7517  * Import a storage pool with the given name.
7518  */
7519 static void
ztest_import(ztest_shared_t * zs)7520 ztest_import(ztest_shared_t *zs)
7521 {
7522 	spa_t *spa;
7523 
7524 	mutex_init(&ztest_vdev_lock, NULL, MUTEX_DEFAULT, NULL);
7525 	mutex_init(&ztest_checkpoint_lock, NULL, MUTEX_DEFAULT, NULL);
7526 	VERIFY0(pthread_rwlock_init(&ztest_name_lock, NULL));
7527 
7528 	kernel_init(SPA_MODE_READ | SPA_MODE_WRITE);
7529 
7530 	ztest_import_impl();
7531 
7532 	VERIFY0(spa_open(ztest_opts.zo_pool, &spa, FTAG));
7533 	zs->zs_metaslab_sz =
7534 	    1ULL << spa->spa_root_vdev->vdev_child[0]->vdev_ms_shift;
7535 	zs->zs_guid = spa_guid(spa);
7536 	spa_close(spa, FTAG);
7537 
7538 	kernel_fini();
7539 
7540 	if (!ztest_opts.zo_mmp_test) {
7541 		ztest_run_zdb(zs->zs_guid);
7542 		ztest_freeze();
7543 		ztest_run_zdb(zs->zs_guid);
7544 	}
7545 
7546 	(void) pthread_rwlock_destroy(&ztest_name_lock);
7547 	mutex_destroy(&ztest_vdev_lock);
7548 	mutex_destroy(&ztest_checkpoint_lock);
7549 }
7550 
7551 /*
7552  * Kick off threads to run tests on all datasets in parallel.
7553  */
7554 static void
ztest_run(ztest_shared_t * zs)7555 ztest_run(ztest_shared_t *zs)
7556 {
7557 	spa_t *spa;
7558 	objset_t *os;
7559 	kthread_t *resume_thread, *deadman_thread;
7560 	kthread_t **run_threads;
7561 	uint64_t object;
7562 	int error;
7563 	int t, d;
7564 
7565 	ztest_exiting = B_FALSE;
7566 
7567 	/*
7568 	 * Initialize parent/child shared state.
7569 	 */
7570 	mutex_init(&ztest_vdev_lock, NULL, MUTEX_DEFAULT, NULL);
7571 	mutex_init(&ztest_checkpoint_lock, NULL, MUTEX_DEFAULT, NULL);
7572 	VERIFY0(pthread_rwlock_init(&ztest_name_lock, NULL));
7573 
7574 	zs->zs_thread_start = gethrtime();
7575 	zs->zs_thread_stop =
7576 	    zs->zs_thread_start + ztest_opts.zo_passtime * NANOSEC;
7577 	zs->zs_thread_stop = MIN(zs->zs_thread_stop, zs->zs_proc_stop);
7578 	zs->zs_thread_kill = zs->zs_thread_stop;
7579 	if (ztest_random(100) < ztest_opts.zo_killrate) {
7580 		zs->zs_thread_kill -=
7581 		    ztest_random(ztest_opts.zo_passtime * NANOSEC);
7582 	}
7583 
7584 	mutex_init(&zcl.zcl_callbacks_lock, NULL, MUTEX_DEFAULT, NULL);
7585 
7586 	list_create(&zcl.zcl_callbacks, sizeof (ztest_cb_data_t),
7587 	    offsetof(ztest_cb_data_t, zcd_node));
7588 
7589 	/*
7590 	 * Open our pool.  It may need to be imported first depending on
7591 	 * what tests were running when the previous pass was terminated.
7592 	 */
7593 	kernel_init(SPA_MODE_READ | SPA_MODE_WRITE);
7594 	error = spa_open(ztest_opts.zo_pool, &spa, FTAG);
7595 	if (error) {
7596 		VERIFY3S(error, ==, ENOENT);
7597 		ztest_import_impl();
7598 		VERIFY0(spa_open(ztest_opts.zo_pool, &spa, FTAG));
7599 		zs->zs_metaslab_sz =
7600 		    1ULL << spa->spa_root_vdev->vdev_child[0]->vdev_ms_shift;
7601 	}
7602 
7603 	metaslab_preload_limit = ztest_random(20) + 1;
7604 	ztest_spa = spa;
7605 
7606 	VERIFY0(vdev_raidz_impl_set("cycle"));
7607 
7608 	dmu_objset_stats_t dds;
7609 	VERIFY0(ztest_dmu_objset_own(ztest_opts.zo_pool,
7610 	    DMU_OST_ANY, B_TRUE, B_TRUE, FTAG, &os));
7611 	dsl_pool_config_enter(dmu_objset_pool(os), FTAG);
7612 	dmu_objset_fast_stat(os, &dds);
7613 	dsl_pool_config_exit(dmu_objset_pool(os), FTAG);
7614 	dmu_objset_disown(os, B_TRUE, FTAG);
7615 
7616 	/*
7617 	 * Create a thread to periodically resume suspended I/O.
7618 	 */
7619 	resume_thread = thread_create(NULL, 0, ztest_resume_thread,
7620 	    spa, 0, NULL, TS_RUN | TS_JOINABLE, defclsyspri);
7621 
7622 	/*
7623 	 * Create a deadman thread and set to panic if we hang.
7624 	 */
7625 	deadman_thread = thread_create(NULL, 0, ztest_deadman_thread,
7626 	    zs, 0, NULL, TS_RUN | TS_JOINABLE, defclsyspri);
7627 
7628 	spa->spa_deadman_failmode = ZIO_FAILURE_MODE_PANIC;
7629 
7630 	/*
7631 	 * Verify that we can safely inquire about any object,
7632 	 * whether it's allocated or not.  To make it interesting,
7633 	 * we probe a 5-wide window around each power of two.
7634 	 * This hits all edge cases, including zero and the max.
7635 	 */
7636 	for (t = 0; t < 64; t++) {
7637 		for (d = -5; d <= 5; d++) {
7638 			error = dmu_object_info(spa->spa_meta_objset,
7639 			    (1ULL << t) + d, NULL);
7640 			ASSERT(error == 0 || error == ENOENT ||
7641 			    error == EINVAL);
7642 		}
7643 	}
7644 
7645 	/*
7646 	 * If we got any ENOSPC errors on the previous run, destroy something.
7647 	 */
7648 	if (zs->zs_enospc_count != 0) {
7649 		int d = ztest_random(ztest_opts.zo_datasets);
7650 		ztest_dataset_destroy(d);
7651 	}
7652 	zs->zs_enospc_count = 0;
7653 
7654 	/*
7655 	 * If we were in the middle of ztest_device_removal() and were killed
7656 	 * we need to ensure the removal and scrub complete before running
7657 	 * any tests that check ztest_device_removal_active. The removal will
7658 	 * be restarted automatically when the spa is opened, but we need to
7659 	 * initiate the scrub manually if it is not already in progress. Note
7660 	 * that we always run the scrub whenever an indirect vdev exists
7661 	 * because we have no way of knowing for sure if ztest_device_removal()
7662 	 * fully completed its scrub before the pool was reimported.
7663 	 */
7664 	if (spa->spa_removing_phys.sr_state == DSS_SCANNING ||
7665 	    spa->spa_removing_phys.sr_prev_indirect_vdev != -1) {
7666 		while (spa->spa_removing_phys.sr_state == DSS_SCANNING)
7667 			txg_wait_synced(spa_get_dsl(spa), 0);
7668 
7669 		error = ztest_scrub_impl(spa);
7670 		if (error == EBUSY)
7671 			error = 0;
7672 		ASSERT0(error);
7673 	}
7674 
7675 	run_threads = umem_zalloc(ztest_opts.zo_threads * sizeof (kthread_t *),
7676 	    UMEM_NOFAIL);
7677 
7678 	if (ztest_opts.zo_verbose >= 4)
7679 		(void) printf("starting main threads...\n");
7680 
7681 	/*
7682 	 * Replay all logs of all datasets in the pool. This is primarily for
7683 	 * temporary datasets which wouldn't otherwise get replayed, which
7684 	 * can trigger failures when attempting to offline a SLOG in
7685 	 * ztest_fault_inject().
7686 	 */
7687 	(void) dmu_objset_find(ztest_opts.zo_pool, ztest_replay_zil_cb,
7688 	    NULL, DS_FIND_CHILDREN);
7689 
7690 	/*
7691 	 * Kick off all the tests that run in parallel.
7692 	 */
7693 	for (t = 0; t < ztest_opts.zo_threads; t++) {
7694 		if (t < ztest_opts.zo_datasets && ztest_dataset_open(t) != 0) {
7695 			umem_free(run_threads, ztest_opts.zo_threads *
7696 			    sizeof (kthread_t *));
7697 			return;
7698 		}
7699 
7700 		run_threads[t] = thread_create(NULL, 0, ztest_thread,
7701 		    (void *)(uintptr_t)t, 0, NULL, TS_RUN | TS_JOINABLE,
7702 		    defclsyspri);
7703 	}
7704 
7705 	/*
7706 	 * Wait for all of the tests to complete.
7707 	 */
7708 	for (t = 0; t < ztest_opts.zo_threads; t++)
7709 		VERIFY0(thread_join(run_threads[t]));
7710 
7711 	/*
7712 	 * Close all datasets. This must be done after all the threads
7713 	 * are joined so we can be sure none of the datasets are in-use
7714 	 * by any of the threads.
7715 	 */
7716 	for (t = 0; t < ztest_opts.zo_threads; t++) {
7717 		if (t < ztest_opts.zo_datasets)
7718 			ztest_dataset_close(t);
7719 	}
7720 
7721 	txg_wait_synced(spa_get_dsl(spa), 0);
7722 
7723 	zs->zs_alloc = metaslab_class_get_alloc(spa_normal_class(spa));
7724 	zs->zs_space = metaslab_class_get_space(spa_normal_class(spa));
7725 
7726 	umem_free(run_threads, ztest_opts.zo_threads * sizeof (kthread_t *));
7727 
7728 	/* Kill the resume and deadman threads */
7729 	ztest_exiting = B_TRUE;
7730 	VERIFY0(thread_join(resume_thread));
7731 	VERIFY0(thread_join(deadman_thread));
7732 	ztest_resume(spa);
7733 
7734 	/*
7735 	 * Right before closing the pool, kick off a bunch of async I/O;
7736 	 * spa_close() should wait for it to complete.
7737 	 */
7738 	for (object = 1; object < 50; object++) {
7739 		dmu_prefetch(spa->spa_meta_objset, object, 0, 0, 1ULL << 20,
7740 		    ZIO_PRIORITY_SYNC_READ);
7741 	}
7742 
7743 	/* Verify that at least one commit cb was called in a timely fashion */
7744 	if (zc_cb_counter >= ZTEST_COMMIT_CB_MIN_REG)
7745 		VERIFY0(zc_min_txg_delay);
7746 
7747 	spa_close(spa, FTAG);
7748 
7749 	/*
7750 	 * Verify that we can loop over all pools.
7751 	 */
7752 	mutex_enter(&spa_namespace_lock);
7753 	for (spa = spa_next(NULL); spa != NULL; spa = spa_next(spa))
7754 		if (ztest_opts.zo_verbose > 3)
7755 			(void) printf("spa_next: found %s\n", spa_name(spa));
7756 	mutex_exit(&spa_namespace_lock);
7757 
7758 	/*
7759 	 * Verify that we can export the pool and reimport it under a
7760 	 * different name.
7761 	 */
7762 	if ((ztest_random(2) == 0) && !ztest_opts.zo_mmp_test) {
7763 		char name[ZFS_MAX_DATASET_NAME_LEN];
7764 		(void) snprintf(name, sizeof (name), "%s_import",
7765 		    ztest_opts.zo_pool);
7766 		ztest_spa_import_export(ztest_opts.zo_pool, name);
7767 		ztest_spa_import_export(name, ztest_opts.zo_pool);
7768 	}
7769 
7770 	kernel_fini();
7771 
7772 	list_destroy(&zcl.zcl_callbacks);
7773 	mutex_destroy(&zcl.zcl_callbacks_lock);
7774 	(void) pthread_rwlock_destroy(&ztest_name_lock);
7775 	mutex_destroy(&ztest_vdev_lock);
7776 	mutex_destroy(&ztest_checkpoint_lock);
7777 }
7778 
7779 static void
print_time(hrtime_t t,char * timebuf)7780 print_time(hrtime_t t, char *timebuf)
7781 {
7782 	hrtime_t s = t / NANOSEC;
7783 	hrtime_t m = s / 60;
7784 	hrtime_t h = m / 60;
7785 	hrtime_t d = h / 24;
7786 
7787 	s -= m * 60;
7788 	m -= h * 60;
7789 	h -= d * 24;
7790 
7791 	timebuf[0] = '\0';
7792 
7793 	if (d)
7794 		(void) sprintf(timebuf,
7795 		    "%llud%02lluh%02llum%02llus", d, h, m, s);
7796 	else if (h)
7797 		(void) sprintf(timebuf, "%lluh%02llum%02llus", h, m, s);
7798 	else if (m)
7799 		(void) sprintf(timebuf, "%llum%02llus", m, s);
7800 	else
7801 		(void) sprintf(timebuf, "%llus", s);
7802 }
7803 
7804 static nvlist_t *
make_random_props(void)7805 make_random_props(void)
7806 {
7807 	nvlist_t *props;
7808 
7809 	props = fnvlist_alloc();
7810 
7811 	if (ztest_random(2) == 0)
7812 		return (props);
7813 
7814 	fnvlist_add_uint64(props,
7815 	    zpool_prop_to_name(ZPOOL_PROP_AUTOREPLACE), 1);
7816 
7817 	return (props);
7818 }
7819 
7820 /*
7821  * Create a storage pool with the given name and initial vdev size.
7822  * Then test spa_freeze() functionality.
7823  */
7824 static void
ztest_init(ztest_shared_t * zs)7825 ztest_init(ztest_shared_t *zs)
7826 {
7827 	spa_t *spa;
7828 	nvlist_t *nvroot, *props;
7829 	int i;
7830 
7831 	mutex_init(&ztest_vdev_lock, NULL, MUTEX_DEFAULT, NULL);
7832 	mutex_init(&ztest_checkpoint_lock, NULL, MUTEX_DEFAULT, NULL);
7833 	VERIFY0(pthread_rwlock_init(&ztest_name_lock, NULL));
7834 
7835 	kernel_init(SPA_MODE_READ | SPA_MODE_WRITE);
7836 
7837 	/*
7838 	 * Create the storage pool.
7839 	 */
7840 	(void) spa_destroy(ztest_opts.zo_pool);
7841 	ztest_shared->zs_vdev_next_leaf = 0;
7842 	zs->zs_splits = 0;
7843 	zs->zs_mirrors = ztest_opts.zo_mirrors;
7844 	nvroot = make_vdev_root(NULL, NULL, NULL, ztest_opts.zo_vdev_size, 0,
7845 	    NULL, ztest_opts.zo_raid_children, zs->zs_mirrors, 1);
7846 	props = make_random_props();
7847 
7848 	/*
7849 	 * We don't expect the pool to suspend unless maxfaults == 0,
7850 	 * in which case ztest_fault_inject() temporarily takes away
7851 	 * the only valid replica.
7852 	 */
7853 	fnvlist_add_uint64(props,
7854 	    zpool_prop_to_name(ZPOOL_PROP_FAILUREMODE),
7855 	    MAXFAULTS(zs) ? ZIO_FAILURE_MODE_PANIC : ZIO_FAILURE_MODE_WAIT);
7856 
7857 	for (i = 0; i < SPA_FEATURES; i++) {
7858 		char *buf;
7859 
7860 		if (!spa_feature_table[i].fi_zfs_mod_supported)
7861 			continue;
7862 
7863 		/*
7864 		 * 75% chance of using the log space map feature. We want ztest
7865 		 * to exercise both the code paths that use the log space map
7866 		 * feature and the ones that don't.
7867 		 */
7868 		if (i == SPA_FEATURE_LOG_SPACEMAP && ztest_random(4) == 0)
7869 			continue;
7870 
7871 		VERIFY3S(-1, !=, asprintf(&buf, "feature@%s",
7872 		    spa_feature_table[i].fi_uname));
7873 		fnvlist_add_uint64(props, buf, 0);
7874 		free(buf);
7875 	}
7876 
7877 	VERIFY0(spa_create(ztest_opts.zo_pool, nvroot, props, NULL, NULL));
7878 	fnvlist_free(nvroot);
7879 	fnvlist_free(props);
7880 
7881 	VERIFY0(spa_open(ztest_opts.zo_pool, &spa, FTAG));
7882 	zs->zs_metaslab_sz =
7883 	    1ULL << spa->spa_root_vdev->vdev_child[0]->vdev_ms_shift;
7884 	zs->zs_guid = spa_guid(spa);
7885 	spa_close(spa, FTAG);
7886 
7887 	kernel_fini();
7888 
7889 	if (!ztest_opts.zo_mmp_test) {
7890 		ztest_run_zdb(zs->zs_guid);
7891 		ztest_freeze();
7892 		ztest_run_zdb(zs->zs_guid);
7893 	}
7894 
7895 	(void) pthread_rwlock_destroy(&ztest_name_lock);
7896 	mutex_destroy(&ztest_vdev_lock);
7897 	mutex_destroy(&ztest_checkpoint_lock);
7898 }
7899 
7900 static void
setup_data_fd(void)7901 setup_data_fd(void)
7902 {
7903 	static char ztest_name_data[] = "/tmp/ztest.data.XXXXXX";
7904 
7905 	ztest_fd_data = mkstemp(ztest_name_data);
7906 	ASSERT3S(ztest_fd_data, >=, 0);
7907 	(void) unlink(ztest_name_data);
7908 }
7909 
7910 static int
shared_data_size(ztest_shared_hdr_t * hdr)7911 shared_data_size(ztest_shared_hdr_t *hdr)
7912 {
7913 	int size;
7914 
7915 	size = hdr->zh_hdr_size;
7916 	size += hdr->zh_opts_size;
7917 	size += hdr->zh_size;
7918 	size += hdr->zh_stats_size * hdr->zh_stats_count;
7919 	size += hdr->zh_ds_size * hdr->zh_ds_count;
7920 
7921 	return (size);
7922 }
7923 
7924 static void
setup_hdr(void)7925 setup_hdr(void)
7926 {
7927 	int size;
7928 	ztest_shared_hdr_t *hdr;
7929 
7930 	hdr = (void *)mmap(0, P2ROUNDUP(sizeof (*hdr), getpagesize()),
7931 	    PROT_READ | PROT_WRITE, MAP_SHARED, ztest_fd_data, 0);
7932 	ASSERT3P(hdr, !=, MAP_FAILED);
7933 
7934 	VERIFY0(ftruncate(ztest_fd_data, sizeof (ztest_shared_hdr_t)));
7935 
7936 	hdr->zh_hdr_size = sizeof (ztest_shared_hdr_t);
7937 	hdr->zh_opts_size = sizeof (ztest_shared_opts_t);
7938 	hdr->zh_size = sizeof (ztest_shared_t);
7939 	hdr->zh_stats_size = sizeof (ztest_shared_callstate_t);
7940 	hdr->zh_stats_count = ZTEST_FUNCS;
7941 	hdr->zh_ds_size = sizeof (ztest_shared_ds_t);
7942 	hdr->zh_ds_count = ztest_opts.zo_datasets;
7943 
7944 	size = shared_data_size(hdr);
7945 	VERIFY0(ftruncate(ztest_fd_data, size));
7946 
7947 	(void) munmap((caddr_t)hdr, P2ROUNDUP(sizeof (*hdr), getpagesize()));
7948 }
7949 
7950 static void
setup_data(void)7951 setup_data(void)
7952 {
7953 	int size, offset;
7954 	ztest_shared_hdr_t *hdr;
7955 	uint8_t *buf;
7956 
7957 	hdr = (void *)mmap(0, P2ROUNDUP(sizeof (*hdr), getpagesize()),
7958 	    PROT_READ, MAP_SHARED, ztest_fd_data, 0);
7959 	ASSERT3P(hdr, !=, MAP_FAILED);
7960 
7961 	size = shared_data_size(hdr);
7962 
7963 	(void) munmap((caddr_t)hdr, P2ROUNDUP(sizeof (*hdr), getpagesize()));
7964 	hdr = ztest_shared_hdr = (void *)mmap(0, P2ROUNDUP(size, getpagesize()),
7965 	    PROT_READ | PROT_WRITE, MAP_SHARED, ztest_fd_data, 0);
7966 	ASSERT3P(hdr, !=, MAP_FAILED);
7967 	buf = (uint8_t *)hdr;
7968 
7969 	offset = hdr->zh_hdr_size;
7970 	ztest_shared_opts = (void *)&buf[offset];
7971 	offset += hdr->zh_opts_size;
7972 	ztest_shared = (void *)&buf[offset];
7973 	offset += hdr->zh_size;
7974 	ztest_shared_callstate = (void *)&buf[offset];
7975 	offset += hdr->zh_stats_size * hdr->zh_stats_count;
7976 	ztest_shared_ds = (void *)&buf[offset];
7977 }
7978 
7979 static boolean_t
exec_child(char * cmd,char * libpath,boolean_t ignorekill,int * statusp)7980 exec_child(char *cmd, char *libpath, boolean_t ignorekill, int *statusp)
7981 {
7982 	pid_t pid;
7983 	int status;
7984 	char *cmdbuf = NULL;
7985 
7986 	pid = fork();
7987 
7988 	if (cmd == NULL) {
7989 		cmdbuf = umem_alloc(MAXPATHLEN, UMEM_NOFAIL);
7990 		(void) strlcpy(cmdbuf, getexecname(), MAXPATHLEN);
7991 		cmd = cmdbuf;
7992 	}
7993 
7994 	if (pid == -1)
7995 		fatal(B_TRUE, "fork failed");
7996 
7997 	if (pid == 0) {	/* child */
7998 		char fd_data_str[12];
7999 
8000 		VERIFY3S(11, >=,
8001 		    snprintf(fd_data_str, 12, "%d", ztest_fd_data));
8002 		VERIFY0(setenv("ZTEST_FD_DATA", fd_data_str, 1));
8003 
8004 		if (libpath != NULL) {
8005 			const char *curlp = getenv("LD_LIBRARY_PATH");
8006 			if (curlp == NULL)
8007 				VERIFY0(setenv("LD_LIBRARY_PATH", libpath, 1));
8008 			else {
8009 				char *newlp = NULL;
8010 				VERIFY3S(-1, !=,
8011 				    asprintf(&newlp, "%s:%s", libpath, curlp));
8012 				VERIFY0(setenv("LD_LIBRARY_PATH", newlp, 1));
8013 				free(newlp);
8014 			}
8015 		}
8016 		(void) execl(cmd, cmd, (char *)NULL);
8017 		ztest_dump_core = B_FALSE;
8018 		fatal(B_TRUE, "exec failed: %s", cmd);
8019 	}
8020 
8021 	if (cmdbuf != NULL) {
8022 		umem_free(cmdbuf, MAXPATHLEN);
8023 		cmd = NULL;
8024 	}
8025 
8026 	while (waitpid(pid, &status, 0) != pid)
8027 		continue;
8028 	if (statusp != NULL)
8029 		*statusp = status;
8030 
8031 	if (WIFEXITED(status)) {
8032 		if (WEXITSTATUS(status) != 0) {
8033 			(void) fprintf(stderr, "child exited with code %d\n",
8034 			    WEXITSTATUS(status));
8035 			exit(2);
8036 		}
8037 		return (B_FALSE);
8038 	} else if (WIFSIGNALED(status)) {
8039 		if (!ignorekill || WTERMSIG(status) != SIGKILL) {
8040 			(void) fprintf(stderr, "child died with signal %d\n",
8041 			    WTERMSIG(status));
8042 			exit(3);
8043 		}
8044 		return (B_TRUE);
8045 	} else {
8046 		(void) fprintf(stderr, "something strange happened to child\n");
8047 		exit(4);
8048 	}
8049 }
8050 
8051 static void
ztest_run_init(void)8052 ztest_run_init(void)
8053 {
8054 	int i;
8055 
8056 	ztest_shared_t *zs = ztest_shared;
8057 
8058 	/*
8059 	 * Blow away any existing copy of zpool.cache
8060 	 */
8061 	(void) remove(spa_config_path);
8062 
8063 	if (ztest_opts.zo_init == 0) {
8064 		if (ztest_opts.zo_verbose >= 1)
8065 			(void) printf("Importing pool %s\n",
8066 			    ztest_opts.zo_pool);
8067 		ztest_import(zs);
8068 		return;
8069 	}
8070 
8071 	/*
8072 	 * Create and initialize our storage pool.
8073 	 */
8074 	for (i = 1; i <= ztest_opts.zo_init; i++) {
8075 		memset(zs, 0, sizeof (*zs));
8076 		if (ztest_opts.zo_verbose >= 3 &&
8077 		    ztest_opts.zo_init != 1) {
8078 			(void) printf("ztest_init(), pass %d\n", i);
8079 		}
8080 		ztest_init(zs);
8081 	}
8082 }
8083 
8084 int
main(int argc,char ** argv)8085 main(int argc, char **argv)
8086 {
8087 	int kills = 0;
8088 	int iters = 0;
8089 	int older = 0;
8090 	int newer = 0;
8091 	ztest_shared_t *zs;
8092 	ztest_info_t *zi;
8093 	ztest_shared_callstate_t *zc;
8094 	char timebuf[100];
8095 	char numbuf[NN_NUMBUF_SZ];
8096 	char *cmd;
8097 	boolean_t hasalt;
8098 	int f, err;
8099 	char *fd_data_str = getenv("ZTEST_FD_DATA");
8100 	struct sigaction action;
8101 
8102 	(void) setvbuf(stdout, NULL, _IOLBF, 0);
8103 
8104 	dprintf_setup(&argc, argv);
8105 	zfs_deadman_synctime_ms = 300000;
8106 	zfs_deadman_checktime_ms = 30000;
8107 	/*
8108 	 * As two-word space map entries may not come up often (especially
8109 	 * if pool and vdev sizes are small) we want to force at least some
8110 	 * of them so the feature get tested.
8111 	 */
8112 	zfs_force_some_double_word_sm_entries = B_TRUE;
8113 
8114 	/*
8115 	 * Verify that even extensively damaged split blocks with many
8116 	 * segments can be reconstructed in a reasonable amount of time
8117 	 * when reconstruction is known to be possible.
8118 	 *
8119 	 * Note: the lower this value is, the more damage we inflict, and
8120 	 * the more time ztest spends in recovering that damage. We chose
8121 	 * to induce damage 1/100th of the time so recovery is tested but
8122 	 * not so frequently that ztest doesn't get to test other code paths.
8123 	 */
8124 	zfs_reconstruct_indirect_damage_fraction = 100;
8125 
8126 	action.sa_handler = sig_handler;
8127 	sigemptyset(&action.sa_mask);
8128 	action.sa_flags = 0;
8129 
8130 	if (sigaction(SIGSEGV, &action, NULL) < 0) {
8131 		(void) fprintf(stderr, "ztest: cannot catch SIGSEGV: %s.\n",
8132 		    strerror(errno));
8133 		exit(EXIT_FAILURE);
8134 	}
8135 
8136 	if (sigaction(SIGABRT, &action, NULL) < 0) {
8137 		(void) fprintf(stderr, "ztest: cannot catch SIGABRT: %s.\n",
8138 		    strerror(errno));
8139 		exit(EXIT_FAILURE);
8140 	}
8141 
8142 	/*
8143 	 * Force random_get_bytes() to use /dev/urandom in order to prevent
8144 	 * ztest from needlessly depleting the system entropy pool.
8145 	 */
8146 	random_path = "/dev/urandom";
8147 	ztest_fd_rand = open(random_path, O_RDONLY | O_CLOEXEC);
8148 	ASSERT3S(ztest_fd_rand, >=, 0);
8149 
8150 	if (!fd_data_str) {
8151 		process_options(argc, argv);
8152 
8153 		setup_data_fd();
8154 		setup_hdr();
8155 		setup_data();
8156 		memcpy(ztest_shared_opts, &ztest_opts,
8157 		    sizeof (*ztest_shared_opts));
8158 	} else {
8159 		ztest_fd_data = atoi(fd_data_str);
8160 		setup_data();
8161 		memcpy(&ztest_opts, ztest_shared_opts, sizeof (ztest_opts));
8162 	}
8163 	ASSERT3U(ztest_opts.zo_datasets, ==, ztest_shared_hdr->zh_ds_count);
8164 
8165 	err = ztest_set_global_vars();
8166 	if (err != 0 && !fd_data_str) {
8167 		/* error message done by ztest_set_global_vars */
8168 		exit(EXIT_FAILURE);
8169 	} else {
8170 		/* children should not be spawned if setting gvars fails */
8171 		VERIFY3S(err, ==, 0);
8172 	}
8173 
8174 	/* Override location of zpool.cache */
8175 	VERIFY3S(asprintf((char **)&spa_config_path, "%s/zpool.cache",
8176 	    ztest_opts.zo_dir), !=, -1);
8177 
8178 	ztest_ds = umem_alloc(ztest_opts.zo_datasets * sizeof (ztest_ds_t),
8179 	    UMEM_NOFAIL);
8180 	zs = ztest_shared;
8181 
8182 	if (fd_data_str) {
8183 		metaslab_force_ganging = ztest_opts.zo_metaslab_force_ganging;
8184 		metaslab_df_alloc_threshold =
8185 		    zs->zs_metaslab_df_alloc_threshold;
8186 
8187 		if (zs->zs_do_init)
8188 			ztest_run_init();
8189 		else
8190 			ztest_run(zs);
8191 		exit(0);
8192 	}
8193 
8194 	hasalt = (strlen(ztest_opts.zo_alt_ztest) != 0);
8195 
8196 	if (ztest_opts.zo_verbose >= 1) {
8197 		(void) printf("%"PRIu64" vdevs, %d datasets, %d threads,"
8198 		    "%d %s disks, %"PRIu64" seconds...\n\n",
8199 		    ztest_opts.zo_vdevs,
8200 		    ztest_opts.zo_datasets,
8201 		    ztest_opts.zo_threads,
8202 		    ztest_opts.zo_raid_children,
8203 		    ztest_opts.zo_raid_type,
8204 		    ztest_opts.zo_time);
8205 	}
8206 
8207 	cmd = umem_alloc(MAXNAMELEN, UMEM_NOFAIL);
8208 	(void) strlcpy(cmd, getexecname(), MAXNAMELEN);
8209 
8210 	zs->zs_do_init = B_TRUE;
8211 	if (strlen(ztest_opts.zo_alt_ztest) != 0) {
8212 		if (ztest_opts.zo_verbose >= 1) {
8213 			(void) printf("Executing older ztest for "
8214 			    "initialization: %s\n", ztest_opts.zo_alt_ztest);
8215 		}
8216 		VERIFY(!exec_child(ztest_opts.zo_alt_ztest,
8217 		    ztest_opts.zo_alt_libpath, B_FALSE, NULL));
8218 	} else {
8219 		VERIFY(!exec_child(NULL, NULL, B_FALSE, NULL));
8220 	}
8221 	zs->zs_do_init = B_FALSE;
8222 
8223 	zs->zs_proc_start = gethrtime();
8224 	zs->zs_proc_stop = zs->zs_proc_start + ztest_opts.zo_time * NANOSEC;
8225 
8226 	for (f = 0; f < ZTEST_FUNCS; f++) {
8227 		zi = &ztest_info[f];
8228 		zc = ZTEST_GET_SHARED_CALLSTATE(f);
8229 		if (zs->zs_proc_start + zi->zi_interval[0] > zs->zs_proc_stop)
8230 			zc->zc_next = UINT64_MAX;
8231 		else
8232 			zc->zc_next = zs->zs_proc_start +
8233 			    ztest_random(2 * zi->zi_interval[0] + 1);
8234 	}
8235 
8236 	/*
8237 	 * Run the tests in a loop.  These tests include fault injection
8238 	 * to verify that self-healing data works, and forced crashes
8239 	 * to verify that we never lose on-disk consistency.
8240 	 */
8241 	while (gethrtime() < zs->zs_proc_stop) {
8242 		int status;
8243 		boolean_t killed;
8244 
8245 		/*
8246 		 * Initialize the workload counters for each function.
8247 		 */
8248 		for (f = 0; f < ZTEST_FUNCS; f++) {
8249 			zc = ZTEST_GET_SHARED_CALLSTATE(f);
8250 			zc->zc_count = 0;
8251 			zc->zc_time = 0;
8252 		}
8253 
8254 		/* Set the allocation switch size */
8255 		zs->zs_metaslab_df_alloc_threshold =
8256 		    ztest_random(zs->zs_metaslab_sz / 4) + 1;
8257 
8258 		if (!hasalt || ztest_random(2) == 0) {
8259 			if (hasalt && ztest_opts.zo_verbose >= 1) {
8260 				(void) printf("Executing newer ztest: %s\n",
8261 				    cmd);
8262 			}
8263 			newer++;
8264 			killed = exec_child(cmd, NULL, B_TRUE, &status);
8265 		} else {
8266 			if (hasalt && ztest_opts.zo_verbose >= 1) {
8267 				(void) printf("Executing older ztest: %s\n",
8268 				    ztest_opts.zo_alt_ztest);
8269 			}
8270 			older++;
8271 			killed = exec_child(ztest_opts.zo_alt_ztest,
8272 			    ztest_opts.zo_alt_libpath, B_TRUE, &status);
8273 		}
8274 
8275 		if (killed)
8276 			kills++;
8277 		iters++;
8278 
8279 		if (ztest_opts.zo_verbose >= 1) {
8280 			hrtime_t now = gethrtime();
8281 
8282 			now = MIN(now, zs->zs_proc_stop);
8283 			print_time(zs->zs_proc_stop - now, timebuf);
8284 			nicenum(zs->zs_space, numbuf, sizeof (numbuf));
8285 
8286 			(void) printf("Pass %3d, %8s, %3"PRIu64" ENOSPC, "
8287 			    "%4.1f%% of %5s used, %3.0f%% done, %8s to go\n",
8288 			    iters,
8289 			    WIFEXITED(status) ? "Complete" : "SIGKILL",
8290 			    zs->zs_enospc_count,
8291 			    100.0 * zs->zs_alloc / zs->zs_space,
8292 			    numbuf,
8293 			    100.0 * (now - zs->zs_proc_start) /
8294 			    (ztest_opts.zo_time * NANOSEC), timebuf);
8295 		}
8296 
8297 		if (ztest_opts.zo_verbose >= 2) {
8298 			(void) printf("\nWorkload summary:\n\n");
8299 			(void) printf("%7s %9s   %s\n",
8300 			    "Calls", "Time", "Function");
8301 			(void) printf("%7s %9s   %s\n",
8302 			    "-----", "----", "--------");
8303 			for (f = 0; f < ZTEST_FUNCS; f++) {
8304 				zi = &ztest_info[f];
8305 				zc = ZTEST_GET_SHARED_CALLSTATE(f);
8306 				print_time(zc->zc_time, timebuf);
8307 				(void) printf("%7"PRIu64" %9s   %s\n",
8308 				    zc->zc_count, timebuf,
8309 				    zi->zi_funcname);
8310 			}
8311 			(void) printf("\n");
8312 		}
8313 
8314 		if (!ztest_opts.zo_mmp_test)
8315 			ztest_run_zdb(zs->zs_guid);
8316 	}
8317 
8318 	if (ztest_opts.zo_verbose >= 1) {
8319 		if (hasalt) {
8320 			(void) printf("%d runs of older ztest: %s\n", older,
8321 			    ztest_opts.zo_alt_ztest);
8322 			(void) printf("%d runs of newer ztest: %s\n", newer,
8323 			    cmd);
8324 		}
8325 		(void) printf("%d killed, %d completed, %.0f%% kill rate\n",
8326 		    kills, iters - kills, (100.0 * kills) / MAX(1, iters));
8327 	}
8328 
8329 	umem_free(cmd, MAXNAMELEN);
8330 
8331 	return (0);
8332 }
8333