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