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