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