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