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