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