Linux 6.12: PG_error flag was removed
[zfs.git] / cmd / ztest.c
blobc58d35c9909c25bac765bc60f0aea9a00f1e53c1
1 /*
2 * CDDL HEADER START
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.
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or https://opensource.org/licenses/CDDL-1.0.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
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]
19 * CDDL HEADER END
22 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23 * Copyright (c) 2011, 2024 by Delphix. All rights reserved.
24 * Copyright 2011 Nexenta Systems, Inc. All rights reserved.
25 * Copyright (c) 2013 Steven Hartland. All rights reserved.
26 * Copyright (c) 2014 Integros [integros.com]
27 * Copyright 2017 Joyent, Inc.
28 * Copyright (c) 2017, Intel Corporation.
29 * Copyright (c) 2023, Klara, Inc.
33 * The objective of this program is to provide a DMU/ZAP/SPA stress test
34 * that runs entirely in userland, is easy to use, and easy to extend.
36 * The overall design of the ztest program is as follows:
38 * (1) For each major functional area (e.g. adding vdevs to a pool,
39 * creating and destroying datasets, reading and writing objects, etc)
40 * we have a simple routine to test that functionality. These
41 * individual routines do not have to do anything "stressful".
43 * (2) We turn these simple functionality tests into a stress test by
44 * running them all in parallel, with as many threads as desired,
45 * and spread across as many datasets, objects, and vdevs as desired.
47 * (3) While all this is happening, we inject faults into the pool to
48 * verify that self-healing data really works.
50 * (4) Every time we open a dataset, we change its checksum and compression
51 * functions. Thus even individual objects vary from block to block
52 * in which checksum they use and whether they're compressed.
54 * (5) To verify that we never lose on-disk consistency after a crash,
55 * we run the entire test in a child of the main process.
56 * At random times, the child self-immolates with a SIGKILL.
57 * This is the software equivalent of pulling the power cord.
58 * The parent then runs the test again, using the existing
59 * storage pool, as many times as desired. If backwards compatibility
60 * testing is enabled ztest will sometimes run the "older" version
61 * of ztest after a SIGKILL.
63 * (6) To verify that we don't have future leaks or temporal incursions,
64 * many of the functional tests record the transaction group number
65 * as part of their data. When reading old data, they verify that
66 * the transaction group number is less than the current, open txg.
67 * If you add a new test, please do this if applicable.
69 * (7) Threads are created with a reduced stack size, for sanity checking.
70 * Therefore, it's important not to allocate huge buffers on the stack.
72 * When run with no arguments, ztest runs for about five minutes and
73 * produces no output if successful. To get a little bit of information,
74 * specify -V. To get more information, specify -VV, and so on.
76 * To turn this into an overnight stress test, use -T to specify run time.
78 * You can ask more vdevs [-v], datasets [-d], or threads [-t]
79 * to increase the pool capacity, fanout, and overall stress level.
81 * Use the -k option to set the desired frequency of kills.
83 * When ztest invokes itself it passes all relevant information through a
84 * temporary file which is mmap-ed in the child process. This allows shared
85 * memory to survive the exec syscall. The ztest_shared_hdr_t struct is always
86 * stored at offset 0 of this file and contains information on the size and
87 * number of shared structures in the file. The information stored in this file
88 * must remain backwards compatible with older versions of ztest so that
89 * ztest can invoke them during backwards compatibility testing (-B).
92 #include <sys/zfs_context.h>
93 #include <sys/spa.h>
94 #include <sys/dmu.h>
95 #include <sys/txg.h>
96 #include <sys/dbuf.h>
97 #include <sys/zap.h>
98 #include <sys/dmu_objset.h>
99 #include <sys/poll.h>
100 #include <sys/stat.h>
101 #include <sys/time.h>
102 #include <sys/wait.h>
103 #include <sys/mman.h>
104 #include <sys/resource.h>
105 #include <sys/zio.h>
106 #include <sys/zil.h>
107 #include <sys/zil_impl.h>
108 #include <sys/vdev_draid.h>
109 #include <sys/vdev_impl.h>
110 #include <sys/vdev_file.h>
111 #include <sys/vdev_initialize.h>
112 #include <sys/vdev_raidz.h>
113 #include <sys/vdev_trim.h>
114 #include <sys/spa_impl.h>
115 #include <sys/metaslab_impl.h>
116 #include <sys/dsl_prop.h>
117 #include <sys/dsl_dataset.h>
118 #include <sys/dsl_destroy.h>
119 #include <sys/dsl_scan.h>
120 #include <sys/zio_checksum.h>
121 #include <sys/zfs_refcount.h>
122 #include <sys/zfeature.h>
123 #include <sys/dsl_userhold.h>
124 #include <sys/abd.h>
125 #include <sys/blake3.h>
126 #include <stdio.h>
127 #include <stdlib.h>
128 #include <unistd.h>
129 #include <getopt.h>
130 #include <signal.h>
131 #include <umem.h>
132 #include <ctype.h>
133 #include <math.h>
134 #include <sys/fs/zfs.h>
135 #include <zfs_fletcher.h>
136 #include <libnvpair.h>
137 #include <libzutil.h>
138 #include <sys/crypto/icp.h>
139 #include <sys/zfs_impl.h>
140 #include <sys/backtrace.h>
142 static int ztest_fd_data = -1;
143 static int ztest_fd_rand = -1;
145 typedef struct ztest_shared_hdr {
146 uint64_t zh_hdr_size;
147 uint64_t zh_opts_size;
148 uint64_t zh_size;
149 uint64_t zh_stats_size;
150 uint64_t zh_stats_count;
151 uint64_t zh_ds_size;
152 uint64_t zh_ds_count;
153 uint64_t zh_scratch_state_size;
154 } ztest_shared_hdr_t;
156 static ztest_shared_hdr_t *ztest_shared_hdr;
158 enum ztest_class_state {
159 ZTEST_VDEV_CLASS_OFF,
160 ZTEST_VDEV_CLASS_ON,
161 ZTEST_VDEV_CLASS_RND
164 /* Dedicated RAIDZ Expansion test states */
165 typedef enum {
166 RAIDZ_EXPAND_NONE, /* Default is none, must opt-in */
167 RAIDZ_EXPAND_REQUESTED, /* The '-X' option was used */
168 RAIDZ_EXPAND_STARTED, /* Testing has commenced */
169 RAIDZ_EXPAND_KILLED, /* Reached the proccess kill */
170 RAIDZ_EXPAND_CHECKED, /* Pool scrub verification done */
171 } raidz_expand_test_state_t;
174 #define ZO_GVARS_MAX_ARGLEN ((size_t)64)
175 #define ZO_GVARS_MAX_COUNT ((size_t)10)
177 typedef struct ztest_shared_opts {
178 char zo_pool[ZFS_MAX_DATASET_NAME_LEN];
179 char zo_dir[ZFS_MAX_DATASET_NAME_LEN];
180 char zo_alt_ztest[MAXNAMELEN];
181 char zo_alt_libpath[MAXNAMELEN];
182 uint64_t zo_vdevs;
183 uint64_t zo_vdevtime;
184 size_t zo_vdev_size;
185 int zo_ashift;
186 int zo_mirrors;
187 int zo_raid_do_expand;
188 int zo_raid_children;
189 int zo_raid_parity;
190 char zo_raid_type[8];
191 int zo_draid_data;
192 int zo_draid_spares;
193 int zo_datasets;
194 int zo_threads;
195 uint64_t zo_passtime;
196 uint64_t zo_killrate;
197 int zo_verbose;
198 int zo_init;
199 uint64_t zo_time;
200 uint64_t zo_maxloops;
201 uint64_t zo_metaslab_force_ganging;
202 raidz_expand_test_state_t zo_raidz_expand_test;
203 int zo_mmp_test;
204 int zo_special_vdevs;
205 int zo_dump_dbgmsg;
206 int zo_gvars_count;
207 char zo_gvars[ZO_GVARS_MAX_COUNT][ZO_GVARS_MAX_ARGLEN];
208 } ztest_shared_opts_t;
210 /* Default values for command line options. */
211 #define DEFAULT_POOL "ztest"
212 #define DEFAULT_VDEV_DIR "/tmp"
213 #define DEFAULT_VDEV_COUNT 5
214 #define DEFAULT_VDEV_SIZE (SPA_MINDEVSIZE * 4) /* 256m default size */
215 #define DEFAULT_VDEV_SIZE_STR "256M"
216 #define DEFAULT_ASHIFT SPA_MINBLOCKSHIFT
217 #define DEFAULT_MIRRORS 2
218 #define DEFAULT_RAID_CHILDREN 4
219 #define DEFAULT_RAID_PARITY 1
220 #define DEFAULT_DRAID_DATA 4
221 #define DEFAULT_DRAID_SPARES 1
222 #define DEFAULT_DATASETS_COUNT 7
223 #define DEFAULT_THREADS 23
224 #define DEFAULT_RUN_TIME 300 /* 300 seconds */
225 #define DEFAULT_RUN_TIME_STR "300 sec"
226 #define DEFAULT_PASS_TIME 60 /* 60 seconds */
227 #define DEFAULT_PASS_TIME_STR "60 sec"
228 #define DEFAULT_KILL_RATE 70 /* 70% kill rate */
229 #define DEFAULT_KILLRATE_STR "70%"
230 #define DEFAULT_INITS 1
231 #define DEFAULT_MAX_LOOPS 50 /* 5 minutes */
232 #define DEFAULT_FORCE_GANGING (64 << 10)
233 #define DEFAULT_FORCE_GANGING_STR "64K"
235 /* Simplifying assumption: -1 is not a valid default. */
236 #define NO_DEFAULT -1
238 static const ztest_shared_opts_t ztest_opts_defaults = {
239 .zo_pool = DEFAULT_POOL,
240 .zo_dir = DEFAULT_VDEV_DIR,
241 .zo_alt_ztest = { '\0' },
242 .zo_alt_libpath = { '\0' },
243 .zo_vdevs = DEFAULT_VDEV_COUNT,
244 .zo_ashift = DEFAULT_ASHIFT,
245 .zo_mirrors = DEFAULT_MIRRORS,
246 .zo_raid_children = DEFAULT_RAID_CHILDREN,
247 .zo_raid_parity = DEFAULT_RAID_PARITY,
248 .zo_raid_type = VDEV_TYPE_RAIDZ,
249 .zo_vdev_size = DEFAULT_VDEV_SIZE,
250 .zo_draid_data = DEFAULT_DRAID_DATA, /* data drives */
251 .zo_draid_spares = DEFAULT_DRAID_SPARES, /* distributed spares */
252 .zo_datasets = DEFAULT_DATASETS_COUNT,
253 .zo_threads = DEFAULT_THREADS,
254 .zo_passtime = DEFAULT_PASS_TIME,
255 .zo_killrate = DEFAULT_KILL_RATE,
256 .zo_verbose = 0,
257 .zo_mmp_test = 0,
258 .zo_init = DEFAULT_INITS,
259 .zo_time = DEFAULT_RUN_TIME,
260 .zo_maxloops = DEFAULT_MAX_LOOPS, /* max loops during spa_freeze() */
261 .zo_metaslab_force_ganging = DEFAULT_FORCE_GANGING,
262 .zo_special_vdevs = ZTEST_VDEV_CLASS_RND,
263 .zo_gvars_count = 0,
264 .zo_raidz_expand_test = RAIDZ_EXPAND_NONE,
267 extern uint64_t metaslab_force_ganging;
268 extern uint64_t metaslab_df_alloc_threshold;
269 extern uint64_t zfs_deadman_synctime_ms;
270 extern uint_t metaslab_preload_limit;
271 extern int zfs_compressed_arc_enabled;
272 extern int zfs_abd_scatter_enabled;
273 extern uint_t dmu_object_alloc_chunk_shift;
274 extern boolean_t zfs_force_some_double_word_sm_entries;
275 extern unsigned long zio_decompress_fail_fraction;
276 extern unsigned long zfs_reconstruct_indirect_damage_fraction;
277 extern uint64_t raidz_expand_max_reflow_bytes;
278 extern uint_t raidz_expand_pause_point;
279 extern boolean_t ddt_prune_artificial_age;
280 extern boolean_t ddt_dump_prune_histogram;
283 static ztest_shared_opts_t *ztest_shared_opts;
284 static ztest_shared_opts_t ztest_opts;
285 static const char *const ztest_wkeydata = "abcdefghijklmnopqrstuvwxyz012345";
287 typedef struct ztest_shared_ds {
288 uint64_t zd_seq;
289 } ztest_shared_ds_t;
291 static ztest_shared_ds_t *ztest_shared_ds;
292 #define ZTEST_GET_SHARED_DS(d) (&ztest_shared_ds[d])
294 typedef struct ztest_scratch_state {
295 uint64_t zs_raidz_scratch_verify_pause;
296 } ztest_shared_scratch_state_t;
298 static ztest_shared_scratch_state_t *ztest_scratch_state;
300 #define BT_MAGIC 0x123456789abcdefULL
301 #define MAXFAULTS(zs) \
302 (MAX((zs)->zs_mirrors, 1) * (ztest_opts.zo_raid_parity + 1) - 1)
304 enum ztest_io_type {
305 ZTEST_IO_WRITE_TAG,
306 ZTEST_IO_WRITE_PATTERN,
307 ZTEST_IO_WRITE_ZEROES,
308 ZTEST_IO_TRUNCATE,
309 ZTEST_IO_SETATTR,
310 ZTEST_IO_REWRITE,
311 ZTEST_IO_TYPES
314 typedef struct ztest_block_tag {
315 uint64_t bt_magic;
316 uint64_t bt_objset;
317 uint64_t bt_object;
318 uint64_t bt_dnodesize;
319 uint64_t bt_offset;
320 uint64_t bt_gen;
321 uint64_t bt_txg;
322 uint64_t bt_crtxg;
323 } ztest_block_tag_t;
325 typedef struct bufwad {
326 uint64_t bw_index;
327 uint64_t bw_txg;
328 uint64_t bw_data;
329 } bufwad_t;
332 * It would be better to use a rangelock_t per object. Unfortunately
333 * the rangelock_t is not a drop-in replacement for rl_t, because we
334 * still need to map from object ID to rangelock_t.
336 typedef enum {
337 ZTRL_READER,
338 ZTRL_WRITER,
339 ZTRL_APPEND
340 } rl_type_t;
342 typedef struct rll {
343 void *rll_writer;
344 int rll_readers;
345 kmutex_t rll_lock;
346 kcondvar_t rll_cv;
347 } rll_t;
349 typedef struct rl {
350 uint64_t rl_object;
351 uint64_t rl_offset;
352 uint64_t rl_size;
353 rll_t *rl_lock;
354 } rl_t;
356 #define ZTEST_RANGE_LOCKS 64
357 #define ZTEST_OBJECT_LOCKS 64
360 * Object descriptor. Used as a template for object lookup/create/remove.
362 typedef struct ztest_od {
363 uint64_t od_dir;
364 uint64_t od_object;
365 dmu_object_type_t od_type;
366 dmu_object_type_t od_crtype;
367 uint64_t od_blocksize;
368 uint64_t od_crblocksize;
369 uint64_t od_crdnodesize;
370 uint64_t od_gen;
371 uint64_t od_crgen;
372 char od_name[ZFS_MAX_DATASET_NAME_LEN];
373 } ztest_od_t;
376 * Per-dataset state.
378 typedef struct ztest_ds {
379 ztest_shared_ds_t *zd_shared;
380 objset_t *zd_os;
381 pthread_rwlock_t zd_zilog_lock;
382 zilog_t *zd_zilog;
383 ztest_od_t *zd_od; /* debugging aid */
384 char zd_name[ZFS_MAX_DATASET_NAME_LEN];
385 kmutex_t zd_dirobj_lock;
386 rll_t zd_object_lock[ZTEST_OBJECT_LOCKS];
387 rll_t zd_range_lock[ZTEST_RANGE_LOCKS];
388 } ztest_ds_t;
391 * Per-iteration state.
393 typedef void ztest_func_t(ztest_ds_t *zd, uint64_t id);
395 typedef struct ztest_info {
396 ztest_func_t *zi_func; /* test function */
397 uint64_t zi_iters; /* iterations per execution */
398 uint64_t *zi_interval; /* execute every <interval> seconds */
399 const char *zi_funcname; /* name of test function */
400 } ztest_info_t;
402 typedef struct ztest_shared_callstate {
403 uint64_t zc_count; /* per-pass count */
404 uint64_t zc_time; /* per-pass time */
405 uint64_t zc_next; /* next time to call this function */
406 } ztest_shared_callstate_t;
408 static ztest_shared_callstate_t *ztest_shared_callstate;
409 #define ZTEST_GET_SHARED_CALLSTATE(c) (&ztest_shared_callstate[c])
411 ztest_func_t ztest_dmu_read_write;
412 ztest_func_t ztest_dmu_write_parallel;
413 ztest_func_t ztest_dmu_object_alloc_free;
414 ztest_func_t ztest_dmu_object_next_chunk;
415 ztest_func_t ztest_dmu_commit_callbacks;
416 ztest_func_t ztest_zap;
417 ztest_func_t ztest_zap_parallel;
418 ztest_func_t ztest_zil_commit;
419 ztest_func_t ztest_zil_remount;
420 ztest_func_t ztest_dmu_read_write_zcopy;
421 ztest_func_t ztest_dmu_objset_create_destroy;
422 ztest_func_t ztest_dmu_prealloc;
423 ztest_func_t ztest_fzap;
424 ztest_func_t ztest_dmu_snapshot_create_destroy;
425 ztest_func_t ztest_dsl_prop_get_set;
426 ztest_func_t ztest_spa_prop_get_set;
427 ztest_func_t ztest_spa_create_destroy;
428 ztest_func_t ztest_fault_inject;
429 ztest_func_t ztest_dmu_snapshot_hold;
430 ztest_func_t ztest_mmp_enable_disable;
431 ztest_func_t ztest_scrub;
432 ztest_func_t ztest_dsl_dataset_promote_busy;
433 ztest_func_t ztest_vdev_attach_detach;
434 ztest_func_t ztest_vdev_raidz_attach;
435 ztest_func_t ztest_vdev_LUN_growth;
436 ztest_func_t ztest_vdev_add_remove;
437 ztest_func_t ztest_vdev_class_add;
438 ztest_func_t ztest_vdev_aux_add_remove;
439 ztest_func_t ztest_split_pool;
440 ztest_func_t ztest_reguid;
441 ztest_func_t ztest_spa_upgrade;
442 ztest_func_t ztest_device_removal;
443 ztest_func_t ztest_spa_checkpoint_create_discard;
444 ztest_func_t ztest_initialize;
445 ztest_func_t ztest_trim;
446 ztest_func_t ztest_blake3;
447 ztest_func_t ztest_fletcher;
448 ztest_func_t ztest_fletcher_incr;
449 ztest_func_t ztest_verify_dnode_bt;
450 ztest_func_t ztest_pool_prefetch_ddt;
451 ztest_func_t ztest_ddt_prune;
453 static uint64_t zopt_always = 0ULL * NANOSEC; /* all the time */
454 static uint64_t zopt_incessant = 1ULL * NANOSEC / 10; /* every 1/10 second */
455 static uint64_t zopt_often = 1ULL * NANOSEC; /* every second */
456 static uint64_t zopt_sometimes = 10ULL * NANOSEC; /* every 10 seconds */
457 static uint64_t zopt_rarely = 60ULL * NANOSEC; /* every 60 seconds */
459 #define ZTI_INIT(func, iters, interval) \
460 { .zi_func = (func), \
461 .zi_iters = (iters), \
462 .zi_interval = (interval), \
463 .zi_funcname = # func }
465 static ztest_info_t ztest_info[] = {
466 ZTI_INIT(ztest_dmu_read_write, 1, &zopt_always),
467 ZTI_INIT(ztest_dmu_write_parallel, 10, &zopt_always),
468 ZTI_INIT(ztest_dmu_object_alloc_free, 1, &zopt_always),
469 ZTI_INIT(ztest_dmu_object_next_chunk, 1, &zopt_sometimes),
470 ZTI_INIT(ztest_dmu_commit_callbacks, 1, &zopt_always),
471 ZTI_INIT(ztest_zap, 30, &zopt_always),
472 ZTI_INIT(ztest_zap_parallel, 100, &zopt_always),
473 ZTI_INIT(ztest_split_pool, 1, &zopt_sometimes),
474 ZTI_INIT(ztest_zil_commit, 1, &zopt_incessant),
475 ZTI_INIT(ztest_zil_remount, 1, &zopt_sometimes),
476 ZTI_INIT(ztest_dmu_read_write_zcopy, 1, &zopt_often),
477 ZTI_INIT(ztest_dmu_objset_create_destroy, 1, &zopt_often),
478 ZTI_INIT(ztest_dsl_prop_get_set, 1, &zopt_often),
479 ZTI_INIT(ztest_spa_prop_get_set, 1, &zopt_sometimes),
480 #if 0
481 ZTI_INIT(ztest_dmu_prealloc, 1, &zopt_sometimes),
482 #endif
483 ZTI_INIT(ztest_fzap, 1, &zopt_sometimes),
484 ZTI_INIT(ztest_dmu_snapshot_create_destroy, 1, &zopt_sometimes),
485 ZTI_INIT(ztest_spa_create_destroy, 1, &zopt_sometimes),
486 ZTI_INIT(ztest_fault_inject, 1, &zopt_sometimes),
487 ZTI_INIT(ztest_dmu_snapshot_hold, 1, &zopt_sometimes),
488 ZTI_INIT(ztest_mmp_enable_disable, 1, &zopt_sometimes),
489 ZTI_INIT(ztest_reguid, 1, &zopt_rarely),
490 ZTI_INIT(ztest_scrub, 1, &zopt_rarely),
491 ZTI_INIT(ztest_spa_upgrade, 1, &zopt_rarely),
492 ZTI_INIT(ztest_dsl_dataset_promote_busy, 1, &zopt_rarely),
493 ZTI_INIT(ztest_vdev_attach_detach, 1, &zopt_sometimes),
494 ZTI_INIT(ztest_vdev_raidz_attach, 1, &zopt_sometimes),
495 ZTI_INIT(ztest_vdev_LUN_growth, 1, &zopt_rarely),
496 ZTI_INIT(ztest_vdev_add_remove, 1, &ztest_opts.zo_vdevtime),
497 ZTI_INIT(ztest_vdev_class_add, 1, &ztest_opts.zo_vdevtime),
498 ZTI_INIT(ztest_vdev_aux_add_remove, 1, &ztest_opts.zo_vdevtime),
499 ZTI_INIT(ztest_device_removal, 1, &zopt_sometimes),
500 ZTI_INIT(ztest_spa_checkpoint_create_discard, 1, &zopt_rarely),
501 ZTI_INIT(ztest_initialize, 1, &zopt_sometimes),
502 ZTI_INIT(ztest_trim, 1, &zopt_sometimes),
503 ZTI_INIT(ztest_blake3, 1, &zopt_rarely),
504 ZTI_INIT(ztest_fletcher, 1, &zopt_rarely),
505 ZTI_INIT(ztest_fletcher_incr, 1, &zopt_rarely),
506 ZTI_INIT(ztest_verify_dnode_bt, 1, &zopt_sometimes),
507 ZTI_INIT(ztest_pool_prefetch_ddt, 1, &zopt_rarely),
508 ZTI_INIT(ztest_ddt_prune, 1, &zopt_rarely),
511 #define ZTEST_FUNCS (sizeof (ztest_info) / sizeof (ztest_info_t))
514 * The following struct is used to hold a list of uncalled commit callbacks.
515 * The callbacks are ordered by txg number.
517 typedef struct ztest_cb_list {
518 kmutex_t zcl_callbacks_lock;
519 list_t zcl_callbacks;
520 } ztest_cb_list_t;
523 * Stuff we need to share writably between parent and child.
525 typedef struct ztest_shared {
526 boolean_t zs_do_init;
527 hrtime_t zs_proc_start;
528 hrtime_t zs_proc_stop;
529 hrtime_t zs_thread_start;
530 hrtime_t zs_thread_stop;
531 hrtime_t zs_thread_kill;
532 uint64_t zs_enospc_count;
533 uint64_t zs_vdev_next_leaf;
534 uint64_t zs_vdev_aux;
535 uint64_t zs_alloc;
536 uint64_t zs_space;
537 uint64_t zs_splits;
538 uint64_t zs_mirrors;
539 uint64_t zs_metaslab_sz;
540 uint64_t zs_metaslab_df_alloc_threshold;
541 uint64_t zs_guid;
542 } ztest_shared_t;
544 #define ID_PARALLEL -1ULL
546 static char ztest_dev_template[] = "%s/%s.%llua";
547 static char ztest_aux_template[] = "%s/%s.%s.%llu";
548 static ztest_shared_t *ztest_shared;
550 static spa_t *ztest_spa = NULL;
551 static ztest_ds_t *ztest_ds;
553 static kmutex_t ztest_vdev_lock;
554 static boolean_t ztest_device_removal_active = B_FALSE;
555 static boolean_t ztest_pool_scrubbed = B_FALSE;
556 static kmutex_t ztest_checkpoint_lock;
559 * The ztest_name_lock protects the pool and dataset namespace used by
560 * the individual tests. To modify the namespace, consumers must grab
561 * this lock as writer. Grabbing the lock as reader will ensure that the
562 * namespace does not change while the lock is held.
564 static pthread_rwlock_t ztest_name_lock;
566 static boolean_t ztest_dump_core = B_TRUE;
567 static boolean_t ztest_exiting;
569 /* Global commit callback list */
570 static ztest_cb_list_t zcl;
571 /* Commit cb delay */
572 static uint64_t zc_min_txg_delay = UINT64_MAX;
573 static int zc_cb_counter = 0;
576 * Minimum number of commit callbacks that need to be registered for us to check
577 * whether the minimum txg delay is acceptable.
579 #define ZTEST_COMMIT_CB_MIN_REG 100
582 * If a number of txgs equal to this threshold have been created after a commit
583 * callback has been registered but not called, then we assume there is an
584 * implementation bug.
586 #define ZTEST_COMMIT_CB_THRESH (TXG_CONCURRENT_STATES + 1000)
588 enum ztest_object {
589 ZTEST_META_DNODE = 0,
590 ZTEST_DIROBJ,
591 ZTEST_OBJECTS
594 static __attribute__((noreturn)) void usage(boolean_t requested);
595 static int ztest_scrub_impl(spa_t *spa);
598 * These libumem hooks provide a reasonable set of defaults for the allocator's
599 * debugging facilities.
601 const char *
602 _umem_debug_init(void)
604 return ("default,verbose"); /* $UMEM_DEBUG setting */
607 const char *
608 _umem_logging_init(void)
610 return ("fail,contents"); /* $UMEM_LOGGING setting */
613 static void
614 dump_debug_buffer(void)
616 ssize_t ret __attribute__((unused));
618 if (!ztest_opts.zo_dump_dbgmsg)
619 return;
622 * We use write() instead of printf() so that this function
623 * is safe to call from a signal handler.
625 ret = write(STDERR_FILENO, "\n", 1);
626 zfs_dbgmsg_print(STDERR_FILENO, "ztest");
629 static void sig_handler(int signo)
631 struct sigaction action;
633 libspl_backtrace(STDERR_FILENO);
634 dump_debug_buffer();
637 * Restore default action and re-raise signal so SIGSEGV and
638 * SIGABRT can trigger a core dump.
640 action.sa_handler = SIG_DFL;
641 sigemptyset(&action.sa_mask);
642 action.sa_flags = 0;
643 (void) sigaction(signo, &action, NULL);
644 raise(signo);
647 #define FATAL_MSG_SZ 1024
649 static const char *fatal_msg;
651 static __attribute__((format(printf, 2, 3))) __attribute__((noreturn)) void
652 fatal(int do_perror, const char *message, ...)
654 va_list args;
655 int save_errno = errno;
656 char *buf;
658 (void) fflush(stdout);
659 buf = umem_alloc(FATAL_MSG_SZ, UMEM_NOFAIL);
660 if (buf == NULL)
661 goto out;
663 va_start(args, message);
664 (void) sprintf(buf, "ztest: ");
665 /* LINTED */
666 (void) vsprintf(buf + strlen(buf), message, args);
667 va_end(args);
668 if (do_perror) {
669 (void) snprintf(buf + strlen(buf), FATAL_MSG_SZ - strlen(buf),
670 ": %s", strerror(save_errno));
672 (void) fprintf(stderr, "%s\n", buf);
673 fatal_msg = buf; /* to ease debugging */
675 out:
676 if (ztest_dump_core)
677 abort();
678 else
679 dump_debug_buffer();
681 exit(3);
684 static int
685 str2shift(const char *buf)
687 const char *ends = "BKMGTPEZ";
688 int i;
690 if (buf[0] == '\0')
691 return (0);
692 for (i = 0; i < strlen(ends); i++) {
693 if (toupper(buf[0]) == ends[i])
694 break;
696 if (i == strlen(ends)) {
697 (void) fprintf(stderr, "ztest: invalid bytes suffix: %s\n",
698 buf);
699 usage(B_FALSE);
701 if (buf[1] == '\0' || (toupper(buf[1]) == 'B' && buf[2] == '\0')) {
702 return (10*i);
704 (void) fprintf(stderr, "ztest: invalid bytes suffix: %s\n", buf);
705 usage(B_FALSE);
708 static uint64_t
709 nicenumtoull(const char *buf)
711 char *end;
712 uint64_t val;
714 val = strtoull(buf, &end, 0);
715 if (end == buf) {
716 (void) fprintf(stderr, "ztest: bad numeric value: %s\n", buf);
717 usage(B_FALSE);
718 } else if (end[0] == '.') {
719 double fval = strtod(buf, &end);
720 fval *= pow(2, str2shift(end));
722 * UINT64_MAX is not exactly representable as a double.
723 * The closest representation is UINT64_MAX + 1, so we
724 * use a >= comparison instead of > for the bounds check.
726 if (fval >= (double)UINT64_MAX) {
727 (void) fprintf(stderr, "ztest: value too large: %s\n",
728 buf);
729 usage(B_FALSE);
731 val = (uint64_t)fval;
732 } else {
733 int shift = str2shift(end);
734 if (shift >= 64 || (val << shift) >> shift != val) {
735 (void) fprintf(stderr, "ztest: value too large: %s\n",
736 buf);
737 usage(B_FALSE);
739 val <<= shift;
741 return (val);
744 typedef struct ztest_option {
745 const char short_opt;
746 const char *long_opt;
747 const char *long_opt_param;
748 const char *comment;
749 unsigned int default_int;
750 const char *default_str;
751 } ztest_option_t;
754 * The following option_table is used for generating the usage info as well as
755 * the long and short option information for calling getopt_long().
757 static ztest_option_t option_table[] = {
758 { 'v', "vdevs", "INTEGER", "Number of vdevs", DEFAULT_VDEV_COUNT,
759 NULL},
760 { 's', "vdev-size", "INTEGER", "Size of each vdev",
761 NO_DEFAULT, DEFAULT_VDEV_SIZE_STR},
762 { 'a', "alignment-shift", "INTEGER",
763 "Alignment shift; use 0 for random", DEFAULT_ASHIFT, NULL},
764 { 'm', "mirror-copies", "INTEGER", "Number of mirror copies",
765 DEFAULT_MIRRORS, NULL},
766 { 'r', "raid-disks", "INTEGER", "Number of raidz/draid disks",
767 DEFAULT_RAID_CHILDREN, NULL},
768 { 'R', "raid-parity", "INTEGER", "Raid parity",
769 DEFAULT_RAID_PARITY, NULL},
770 { 'K', "raid-kind", "raidz|eraidz|draid|random", "Raid kind",
771 NO_DEFAULT, "random"},
772 { 'D', "draid-data", "INTEGER", "Number of draid data drives",
773 DEFAULT_DRAID_DATA, NULL},
774 { 'S', "draid-spares", "INTEGER", "Number of draid spares",
775 DEFAULT_DRAID_SPARES, NULL},
776 { 'd', "datasets", "INTEGER", "Number of datasets",
777 DEFAULT_DATASETS_COUNT, NULL},
778 { 't', "threads", "INTEGER", "Number of ztest threads",
779 DEFAULT_THREADS, NULL},
780 { 'g', "gang-block-threshold", "INTEGER",
781 "Metaslab gang block threshold",
782 NO_DEFAULT, DEFAULT_FORCE_GANGING_STR},
783 { 'i', "init-count", "INTEGER", "Number of times to initialize pool",
784 DEFAULT_INITS, NULL},
785 { 'k', "kill-percentage", "INTEGER", "Kill percentage",
786 NO_DEFAULT, DEFAULT_KILLRATE_STR},
787 { 'p', "pool-name", "STRING", "Pool name",
788 NO_DEFAULT, DEFAULT_POOL},
789 { 'f', "vdev-file-directory", "PATH", "File directory for vdev files",
790 NO_DEFAULT, DEFAULT_VDEV_DIR},
791 { 'M', "multi-host", NULL,
792 "Multi-host; simulate pool imported on remote host",
793 NO_DEFAULT, NULL},
794 { 'E', "use-existing-pool", NULL,
795 "Use existing pool instead of creating new one", NO_DEFAULT, NULL},
796 { 'T', "run-time", "INTEGER", "Total run time",
797 NO_DEFAULT, DEFAULT_RUN_TIME_STR},
798 { 'P', "pass-time", "INTEGER", "Time per pass",
799 NO_DEFAULT, DEFAULT_PASS_TIME_STR},
800 { 'F', "freeze-loops", "INTEGER", "Max loops in spa_freeze()",
801 DEFAULT_MAX_LOOPS, NULL},
802 { 'B', "alt-ztest", "PATH", "Alternate ztest path",
803 NO_DEFAULT, NULL},
804 { 'C', "vdev-class-state", "on|off|random", "vdev class state",
805 NO_DEFAULT, "random"},
806 { 'X', "raidz-expansion", NULL,
807 "Perform a dedicated raidz expansion test",
808 NO_DEFAULT, NULL},
809 { 'o', "option", "\"OPTION=INTEGER\"",
810 "Set global variable to an unsigned 32-bit integer value",
811 NO_DEFAULT, NULL},
812 { 'G', "dump-debug-msg", NULL,
813 "Dump zfs_dbgmsg buffer before exiting due to an error",
814 NO_DEFAULT, NULL},
815 { 'V', "verbose", NULL,
816 "Verbose (use multiple times for ever more verbosity)",
817 NO_DEFAULT, NULL},
818 { 'h', "help", NULL, "Show this help",
819 NO_DEFAULT, NULL},
820 {0, 0, 0, 0, 0, 0}
823 static struct option *long_opts = NULL;
824 static char *short_opts = NULL;
826 static void
827 init_options(void)
829 ASSERT3P(long_opts, ==, NULL);
830 ASSERT3P(short_opts, ==, NULL);
832 int count = sizeof (option_table) / sizeof (option_table[0]);
833 long_opts = umem_alloc(sizeof (struct option) * count, UMEM_NOFAIL);
835 short_opts = umem_alloc(sizeof (char) * 2 * count, UMEM_NOFAIL);
836 int short_opt_index = 0;
838 for (int i = 0; i < count; i++) {
839 long_opts[i].val = option_table[i].short_opt;
840 long_opts[i].name = option_table[i].long_opt;
841 long_opts[i].has_arg = option_table[i].long_opt_param != NULL
842 ? required_argument : no_argument;
843 long_opts[i].flag = NULL;
844 short_opts[short_opt_index++] = option_table[i].short_opt;
845 if (option_table[i].long_opt_param != NULL) {
846 short_opts[short_opt_index++] = ':';
851 static void
852 fini_options(void)
854 int count = sizeof (option_table) / sizeof (option_table[0]);
856 umem_free(long_opts, sizeof (struct option) * count);
857 umem_free(short_opts, sizeof (char) * 2 * count);
859 long_opts = NULL;
860 short_opts = NULL;
863 static __attribute__((noreturn)) void
864 usage(boolean_t requested)
866 char option[80];
867 FILE *fp = requested ? stdout : stderr;
869 (void) fprintf(fp, "Usage: %s [OPTIONS...]\n", DEFAULT_POOL);
870 for (int i = 0; option_table[i].short_opt != 0; i++) {
871 if (option_table[i].long_opt_param != NULL) {
872 (void) sprintf(option, " -%c --%s=%s",
873 option_table[i].short_opt,
874 option_table[i].long_opt,
875 option_table[i].long_opt_param);
876 } else {
877 (void) sprintf(option, " -%c --%s",
878 option_table[i].short_opt,
879 option_table[i].long_opt);
881 (void) fprintf(fp, " %-43s%s", option,
882 option_table[i].comment);
884 if (option_table[i].long_opt_param != NULL) {
885 if (option_table[i].default_str != NULL) {
886 (void) fprintf(fp, " (default: %s)",
887 option_table[i].default_str);
888 } else if (option_table[i].default_int != NO_DEFAULT) {
889 (void) fprintf(fp, " (default: %u)",
890 option_table[i].default_int);
893 (void) fprintf(fp, "\n");
895 exit(requested ? 0 : 1);
898 static uint64_t
899 ztest_random(uint64_t range)
901 uint64_t r;
903 ASSERT3S(ztest_fd_rand, >=, 0);
905 if (range == 0)
906 return (0);
908 if (read(ztest_fd_rand, &r, sizeof (r)) != sizeof (r))
909 fatal(B_TRUE, "short read from /dev/urandom");
911 return (r % range);
914 static void
915 ztest_parse_name_value(const char *input, ztest_shared_opts_t *zo)
917 char name[32];
918 char *value;
919 int state = ZTEST_VDEV_CLASS_RND;
921 (void) strlcpy(name, input, sizeof (name));
923 value = strchr(name, '=');
924 if (value == NULL) {
925 (void) fprintf(stderr, "missing value in property=value "
926 "'-C' argument (%s)\n", input);
927 usage(B_FALSE);
929 *(value) = '\0';
930 value++;
932 if (strcmp(value, "on") == 0) {
933 state = ZTEST_VDEV_CLASS_ON;
934 } else if (strcmp(value, "off") == 0) {
935 state = ZTEST_VDEV_CLASS_OFF;
936 } else if (strcmp(value, "random") == 0) {
937 state = ZTEST_VDEV_CLASS_RND;
938 } else {
939 (void) fprintf(stderr, "invalid property value '%s'\n", value);
940 usage(B_FALSE);
943 if (strcmp(name, "special") == 0) {
944 zo->zo_special_vdevs = state;
945 } else {
946 (void) fprintf(stderr, "invalid property name '%s'\n", name);
947 usage(B_FALSE);
949 if (zo->zo_verbose >= 3)
950 (void) printf("%s vdev state is '%s'\n", name, value);
953 static void
954 process_options(int argc, char **argv)
956 char *path;
957 ztest_shared_opts_t *zo = &ztest_opts;
959 int opt;
960 uint64_t value;
961 const char *raid_kind = "random";
963 memcpy(zo, &ztest_opts_defaults, sizeof (*zo));
965 init_options();
967 while ((opt = getopt_long(argc, argv, short_opts, long_opts,
968 NULL)) != EOF) {
969 value = 0;
970 switch (opt) {
971 case 'v':
972 case 's':
973 case 'a':
974 case 'm':
975 case 'r':
976 case 'R':
977 case 'D':
978 case 'S':
979 case 'd':
980 case 't':
981 case 'g':
982 case 'i':
983 case 'k':
984 case 'T':
985 case 'P':
986 case 'F':
987 value = nicenumtoull(optarg);
989 switch (opt) {
990 case 'v':
991 zo->zo_vdevs = value;
992 break;
993 case 's':
994 zo->zo_vdev_size = MAX(SPA_MINDEVSIZE, value);
995 break;
996 case 'a':
997 zo->zo_ashift = value;
998 break;
999 case 'm':
1000 zo->zo_mirrors = value;
1001 break;
1002 case 'r':
1003 zo->zo_raid_children = MAX(1, value);
1004 break;
1005 case 'R':
1006 zo->zo_raid_parity = MIN(MAX(value, 1), 3);
1007 break;
1008 case 'K':
1009 raid_kind = optarg;
1010 break;
1011 case 'D':
1012 zo->zo_draid_data = MAX(1, value);
1013 break;
1014 case 'S':
1015 zo->zo_draid_spares = MAX(1, value);
1016 break;
1017 case 'd':
1018 zo->zo_datasets = MAX(1, value);
1019 break;
1020 case 't':
1021 zo->zo_threads = MAX(1, value);
1022 break;
1023 case 'g':
1024 zo->zo_metaslab_force_ganging =
1025 MAX(SPA_MINBLOCKSIZE << 1, value);
1026 break;
1027 case 'i':
1028 zo->zo_init = value;
1029 break;
1030 case 'k':
1031 zo->zo_killrate = value;
1032 break;
1033 case 'p':
1034 (void) strlcpy(zo->zo_pool, optarg,
1035 sizeof (zo->zo_pool));
1036 break;
1037 case 'f':
1038 path = realpath(optarg, NULL);
1039 if (path == NULL) {
1040 (void) fprintf(stderr, "error: %s: %s\n",
1041 optarg, strerror(errno));
1042 usage(B_FALSE);
1043 } else {
1044 (void) strlcpy(zo->zo_dir, path,
1045 sizeof (zo->zo_dir));
1046 free(path);
1048 break;
1049 case 'M':
1050 zo->zo_mmp_test = 1;
1051 break;
1052 case 'V':
1053 zo->zo_verbose++;
1054 break;
1055 case 'X':
1056 zo->zo_raidz_expand_test = RAIDZ_EXPAND_REQUESTED;
1057 break;
1058 case 'E':
1059 zo->zo_init = 0;
1060 break;
1061 case 'T':
1062 zo->zo_time = value;
1063 break;
1064 case 'P':
1065 zo->zo_passtime = MAX(1, value);
1066 break;
1067 case 'F':
1068 zo->zo_maxloops = MAX(1, value);
1069 break;
1070 case 'B':
1071 (void) strlcpy(zo->zo_alt_ztest, optarg,
1072 sizeof (zo->zo_alt_ztest));
1073 break;
1074 case 'C':
1075 ztest_parse_name_value(optarg, zo);
1076 break;
1077 case 'o':
1078 if (zo->zo_gvars_count >= ZO_GVARS_MAX_COUNT) {
1079 (void) fprintf(stderr,
1080 "max global var count (%zu) exceeded\n",
1081 ZO_GVARS_MAX_COUNT);
1082 usage(B_FALSE);
1084 char *v = zo->zo_gvars[zo->zo_gvars_count];
1085 if (strlcpy(v, optarg, ZO_GVARS_MAX_ARGLEN) >=
1086 ZO_GVARS_MAX_ARGLEN) {
1087 (void) fprintf(stderr,
1088 "global var option '%s' is too long\n",
1089 optarg);
1090 usage(B_FALSE);
1092 zo->zo_gvars_count++;
1093 break;
1094 case 'G':
1095 zo->zo_dump_dbgmsg = 1;
1096 break;
1097 case 'h':
1098 usage(B_TRUE);
1099 break;
1100 case '?':
1101 default:
1102 usage(B_FALSE);
1103 break;
1107 fini_options();
1109 /* Force compatible options for raidz expansion run */
1110 if (zo->zo_raidz_expand_test == RAIDZ_EXPAND_REQUESTED) {
1111 zo->zo_mmp_test = 0;
1112 zo->zo_mirrors = 0;
1113 zo->zo_vdevs = 1;
1114 zo->zo_vdev_size = DEFAULT_VDEV_SIZE * 2;
1115 zo->zo_raid_do_expand = B_FALSE;
1116 raid_kind = "raidz";
1119 if (strcmp(raid_kind, "random") == 0) {
1120 switch (ztest_random(3)) {
1121 case 0:
1122 raid_kind = "raidz";
1123 break;
1124 case 1:
1125 raid_kind = "eraidz";
1126 break;
1127 case 2:
1128 raid_kind = "draid";
1129 break;
1132 if (ztest_opts.zo_verbose >= 3)
1133 (void) printf("choosing RAID type '%s'\n", raid_kind);
1136 if (strcmp(raid_kind, "draid") == 0) {
1137 uint64_t min_devsize;
1139 /* With fewer disk use 256M, otherwise 128M is OK */
1140 min_devsize = (ztest_opts.zo_raid_children < 16) ?
1141 (256ULL << 20) : (128ULL << 20);
1143 /* No top-level mirrors with dRAID for now */
1144 zo->zo_mirrors = 0;
1146 /* Use more appropriate defaults for dRAID */
1147 if (zo->zo_vdevs == ztest_opts_defaults.zo_vdevs)
1148 zo->zo_vdevs = 1;
1149 if (zo->zo_raid_children ==
1150 ztest_opts_defaults.zo_raid_children)
1151 zo->zo_raid_children = 16;
1152 if (zo->zo_ashift < 12)
1153 zo->zo_ashift = 12;
1154 if (zo->zo_vdev_size < min_devsize)
1155 zo->zo_vdev_size = min_devsize;
1157 if (zo->zo_draid_data + zo->zo_raid_parity >
1158 zo->zo_raid_children - zo->zo_draid_spares) {
1159 (void) fprintf(stderr, "error: too few draid "
1160 "children (%d) for stripe width (%d)\n",
1161 zo->zo_raid_children,
1162 zo->zo_draid_data + zo->zo_raid_parity);
1163 usage(B_FALSE);
1166 (void) strlcpy(zo->zo_raid_type, VDEV_TYPE_DRAID,
1167 sizeof (zo->zo_raid_type));
1169 } else if (strcmp(raid_kind, "eraidz") == 0) {
1170 /* using eraidz (expandable raidz) */
1171 zo->zo_raid_do_expand = B_TRUE;
1173 /* tests expect top-level to be raidz */
1174 zo->zo_mirrors = 0;
1175 zo->zo_vdevs = 1;
1177 /* Make sure parity is less than data columns */
1178 zo->zo_raid_parity = MIN(zo->zo_raid_parity,
1179 zo->zo_raid_children - 1);
1181 } else /* using raidz */ {
1182 ASSERT0(strcmp(raid_kind, "raidz"));
1184 zo->zo_raid_parity = MIN(zo->zo_raid_parity,
1185 zo->zo_raid_children - 1);
1188 zo->zo_vdevtime =
1189 (zo->zo_vdevs > 0 ? zo->zo_time * NANOSEC / zo->zo_vdevs :
1190 UINT64_MAX >> 2);
1192 if (*zo->zo_alt_ztest) {
1193 const char *invalid_what = "ztest";
1194 char *val = zo->zo_alt_ztest;
1195 if (0 != access(val, X_OK) ||
1196 (strrchr(val, '/') == NULL && (errno == EINVAL)))
1197 goto invalid;
1199 int dirlen = strrchr(val, '/') - val;
1200 strlcpy(zo->zo_alt_libpath, val,
1201 MIN(sizeof (zo->zo_alt_libpath), dirlen + 1));
1202 invalid_what = "library path", val = zo->zo_alt_libpath;
1203 if (strrchr(val, '/') == NULL && (errno == EINVAL))
1204 goto invalid;
1205 *strrchr(val, '/') = '\0';
1206 strlcat(val, "/lib", sizeof (zo->zo_alt_libpath));
1208 if (0 != access(zo->zo_alt_libpath, X_OK))
1209 goto invalid;
1210 return;
1212 invalid:
1213 ztest_dump_core = B_FALSE;
1214 fatal(B_TRUE, "invalid alternate %s %s", invalid_what, val);
1218 static void
1219 ztest_kill(ztest_shared_t *zs)
1221 zs->zs_alloc = metaslab_class_get_alloc(spa_normal_class(ztest_spa));
1222 zs->zs_space = metaslab_class_get_space(spa_normal_class(ztest_spa));
1225 * Before we kill ourselves, make sure that the config is updated.
1226 * See comment above spa_write_cachefile().
1228 if (raidz_expand_pause_point != RAIDZ_EXPAND_PAUSE_NONE) {
1229 if (mutex_tryenter(&spa_namespace_lock)) {
1230 spa_write_cachefile(ztest_spa, B_FALSE, B_FALSE,
1231 B_FALSE);
1232 mutex_exit(&spa_namespace_lock);
1234 ztest_scratch_state->zs_raidz_scratch_verify_pause =
1235 raidz_expand_pause_point;
1236 } else {
1238 * Do not verify scratch object in case if
1239 * spa_namespace_lock cannot be acquired,
1240 * it can cause deadlock in spa_config_update().
1242 raidz_expand_pause_point = RAIDZ_EXPAND_PAUSE_NONE;
1244 return;
1246 } else {
1247 mutex_enter(&spa_namespace_lock);
1248 spa_write_cachefile(ztest_spa, B_FALSE, B_FALSE, B_FALSE);
1249 mutex_exit(&spa_namespace_lock);
1252 (void) raise(SIGKILL);
1255 static void
1256 ztest_record_enospc(const char *s)
1258 (void) s;
1259 ztest_shared->zs_enospc_count++;
1262 static uint64_t
1263 ztest_get_ashift(void)
1265 if (ztest_opts.zo_ashift == 0)
1266 return (SPA_MINBLOCKSHIFT + ztest_random(5));
1267 return (ztest_opts.zo_ashift);
1270 static boolean_t
1271 ztest_is_draid_spare(const char *name)
1273 uint64_t spare_id = 0, parity = 0, vdev_id = 0;
1275 if (sscanf(name, VDEV_TYPE_DRAID "%"PRIu64"-%"PRIu64"-%"PRIu64"",
1276 &parity, &vdev_id, &spare_id) == 3) {
1277 return (B_TRUE);
1280 return (B_FALSE);
1283 static nvlist_t *
1284 make_vdev_file(const char *path, const char *aux, const char *pool,
1285 size_t size, uint64_t ashift)
1287 char *pathbuf = NULL;
1288 uint64_t vdev;
1289 nvlist_t *file;
1290 boolean_t draid_spare = B_FALSE;
1293 if (ashift == 0)
1294 ashift = ztest_get_ashift();
1296 if (path == NULL) {
1297 pathbuf = umem_alloc(MAXPATHLEN, UMEM_NOFAIL);
1298 path = pathbuf;
1300 if (aux != NULL) {
1301 vdev = ztest_shared->zs_vdev_aux;
1302 (void) snprintf(pathbuf, MAXPATHLEN,
1303 ztest_aux_template, ztest_opts.zo_dir,
1304 pool == NULL ? ztest_opts.zo_pool : pool,
1305 aux, vdev);
1306 } else {
1307 vdev = ztest_shared->zs_vdev_next_leaf++;
1308 (void) snprintf(pathbuf, MAXPATHLEN,
1309 ztest_dev_template, ztest_opts.zo_dir,
1310 pool == NULL ? ztest_opts.zo_pool : pool, vdev);
1312 } else {
1313 draid_spare = ztest_is_draid_spare(path);
1316 if (size != 0 && !draid_spare) {
1317 int fd = open(path, O_RDWR | O_CREAT | O_TRUNC, 0666);
1318 if (fd == -1)
1319 fatal(B_TRUE, "can't open %s", path);
1320 if (ftruncate(fd, size) != 0)
1321 fatal(B_TRUE, "can't ftruncate %s", path);
1322 (void) close(fd);
1325 file = fnvlist_alloc();
1326 fnvlist_add_string(file, ZPOOL_CONFIG_TYPE,
1327 draid_spare ? VDEV_TYPE_DRAID_SPARE : VDEV_TYPE_FILE);
1328 fnvlist_add_string(file, ZPOOL_CONFIG_PATH, path);
1329 fnvlist_add_uint64(file, ZPOOL_CONFIG_ASHIFT, ashift);
1330 umem_free(pathbuf, MAXPATHLEN);
1332 return (file);
1335 static nvlist_t *
1336 make_vdev_raid(const char *path, const char *aux, const char *pool, size_t size,
1337 uint64_t ashift, int r)
1339 nvlist_t *raid, **child;
1340 int c;
1342 if (r < 2)
1343 return (make_vdev_file(path, aux, pool, size, ashift));
1344 child = umem_alloc(r * sizeof (nvlist_t *), UMEM_NOFAIL);
1346 for (c = 0; c < r; c++)
1347 child[c] = make_vdev_file(path, aux, pool, size, ashift);
1349 raid = fnvlist_alloc();
1350 fnvlist_add_string(raid, ZPOOL_CONFIG_TYPE,
1351 ztest_opts.zo_raid_type);
1352 fnvlist_add_uint64(raid, ZPOOL_CONFIG_NPARITY,
1353 ztest_opts.zo_raid_parity);
1354 fnvlist_add_nvlist_array(raid, ZPOOL_CONFIG_CHILDREN,
1355 (const nvlist_t **)child, r);
1357 if (strcmp(ztest_opts.zo_raid_type, VDEV_TYPE_DRAID) == 0) {
1358 uint64_t ndata = ztest_opts.zo_draid_data;
1359 uint64_t nparity = ztest_opts.zo_raid_parity;
1360 uint64_t nspares = ztest_opts.zo_draid_spares;
1361 uint64_t children = ztest_opts.zo_raid_children;
1362 uint64_t ngroups = 1;
1365 * Calculate the minimum number of groups required to fill a
1366 * slice. This is the LCM of the stripe width (data + parity)
1367 * and the number of data drives (children - spares).
1369 while (ngroups * (ndata + nparity) % (children - nspares) != 0)
1370 ngroups++;
1372 /* Store the basic dRAID configuration. */
1373 fnvlist_add_uint64(raid, ZPOOL_CONFIG_DRAID_NDATA, ndata);
1374 fnvlist_add_uint64(raid, ZPOOL_CONFIG_DRAID_NSPARES, nspares);
1375 fnvlist_add_uint64(raid, ZPOOL_CONFIG_DRAID_NGROUPS, ngroups);
1378 for (c = 0; c < r; c++)
1379 fnvlist_free(child[c]);
1381 umem_free(child, r * sizeof (nvlist_t *));
1383 return (raid);
1386 static nvlist_t *
1387 make_vdev_mirror(const char *path, const char *aux, const char *pool,
1388 size_t size, uint64_t ashift, int r, int m)
1390 nvlist_t *mirror, **child;
1391 int c;
1393 if (m < 1)
1394 return (make_vdev_raid(path, aux, pool, size, ashift, r));
1396 child = umem_alloc(m * sizeof (nvlist_t *), UMEM_NOFAIL);
1398 for (c = 0; c < m; c++)
1399 child[c] = make_vdev_raid(path, aux, pool, size, ashift, r);
1401 mirror = fnvlist_alloc();
1402 fnvlist_add_string(mirror, ZPOOL_CONFIG_TYPE, VDEV_TYPE_MIRROR);
1403 fnvlist_add_nvlist_array(mirror, ZPOOL_CONFIG_CHILDREN,
1404 (const nvlist_t **)child, m);
1406 for (c = 0; c < m; c++)
1407 fnvlist_free(child[c]);
1409 umem_free(child, m * sizeof (nvlist_t *));
1411 return (mirror);
1414 static nvlist_t *
1415 make_vdev_root(const char *path, const char *aux, const char *pool, size_t size,
1416 uint64_t ashift, const char *class, int r, int m, int t)
1418 nvlist_t *root, **child;
1419 int c;
1420 boolean_t log;
1422 ASSERT3S(t, >, 0);
1424 log = (class != NULL && strcmp(class, "log") == 0);
1426 child = umem_alloc(t * sizeof (nvlist_t *), UMEM_NOFAIL);
1428 for (c = 0; c < t; c++) {
1429 child[c] = make_vdev_mirror(path, aux, pool, size, ashift,
1430 r, m);
1431 fnvlist_add_uint64(child[c], ZPOOL_CONFIG_IS_LOG, log);
1433 if (class != NULL && class[0] != '\0') {
1434 ASSERT(m > 1 || log); /* expecting a mirror */
1435 fnvlist_add_string(child[c],
1436 ZPOOL_CONFIG_ALLOCATION_BIAS, class);
1440 root = fnvlist_alloc();
1441 fnvlist_add_string(root, ZPOOL_CONFIG_TYPE, VDEV_TYPE_ROOT);
1442 fnvlist_add_nvlist_array(root, aux ? aux : ZPOOL_CONFIG_CHILDREN,
1443 (const nvlist_t **)child, t);
1445 for (c = 0; c < t; c++)
1446 fnvlist_free(child[c]);
1448 umem_free(child, t * sizeof (nvlist_t *));
1450 return (root);
1454 * Find a random spa version. Returns back a random spa version in the
1455 * range [initial_version, SPA_VERSION_FEATURES].
1457 static uint64_t
1458 ztest_random_spa_version(uint64_t initial_version)
1460 uint64_t version = initial_version;
1462 if (version <= SPA_VERSION_BEFORE_FEATURES) {
1463 version = version +
1464 ztest_random(SPA_VERSION_BEFORE_FEATURES - version + 1);
1467 if (version > SPA_VERSION_BEFORE_FEATURES)
1468 version = SPA_VERSION_FEATURES;
1470 ASSERT(SPA_VERSION_IS_SUPPORTED(version));
1471 return (version);
1474 static int
1475 ztest_random_blocksize(void)
1477 ASSERT3U(ztest_spa->spa_max_ashift, !=, 0);
1480 * Choose a block size >= the ashift.
1481 * If the SPA supports new MAXBLOCKSIZE, test up to 1MB blocks.
1483 int maxbs = SPA_OLD_MAXBLOCKSHIFT;
1484 if (spa_maxblocksize(ztest_spa) == SPA_MAXBLOCKSIZE)
1485 maxbs = 20;
1486 uint64_t block_shift =
1487 ztest_random(maxbs - ztest_spa->spa_max_ashift + 1);
1488 return (1 << (SPA_MINBLOCKSHIFT + block_shift));
1491 static int
1492 ztest_random_dnodesize(void)
1494 int slots;
1495 int max_slots = spa_maxdnodesize(ztest_spa) >> DNODE_SHIFT;
1497 if (max_slots == DNODE_MIN_SLOTS)
1498 return (DNODE_MIN_SIZE);
1501 * Weight the random distribution more heavily toward smaller
1502 * dnode sizes since that is more likely to reflect real-world
1503 * usage.
1505 ASSERT3U(max_slots, >, 4);
1506 switch (ztest_random(10)) {
1507 case 0:
1508 slots = 5 + ztest_random(max_slots - 4);
1509 break;
1510 case 1 ... 4:
1511 slots = 2 + ztest_random(3);
1512 break;
1513 default:
1514 slots = 1;
1515 break;
1518 return (slots << DNODE_SHIFT);
1521 static int
1522 ztest_random_ibshift(void)
1524 return (DN_MIN_INDBLKSHIFT +
1525 ztest_random(DN_MAX_INDBLKSHIFT - DN_MIN_INDBLKSHIFT + 1));
1528 static uint64_t
1529 ztest_random_vdev_top(spa_t *spa, boolean_t log_ok)
1531 uint64_t top;
1532 vdev_t *rvd = spa->spa_root_vdev;
1533 vdev_t *tvd;
1535 ASSERT3U(spa_config_held(spa, SCL_ALL, RW_READER), !=, 0);
1537 do {
1538 top = ztest_random(rvd->vdev_children);
1539 tvd = rvd->vdev_child[top];
1540 } while (!vdev_is_concrete(tvd) || (tvd->vdev_islog && !log_ok) ||
1541 tvd->vdev_mg == NULL || tvd->vdev_mg->mg_class == NULL);
1543 return (top);
1546 static uint64_t
1547 ztest_random_dsl_prop(zfs_prop_t prop)
1549 uint64_t value;
1551 do {
1552 value = zfs_prop_random_value(prop, ztest_random(-1ULL));
1553 } while (prop == ZFS_PROP_CHECKSUM && value == ZIO_CHECKSUM_OFF);
1555 return (value);
1558 static int
1559 ztest_dsl_prop_set_uint64(char *osname, zfs_prop_t prop, uint64_t value,
1560 boolean_t inherit)
1562 const char *propname = zfs_prop_to_name(prop);
1563 const char *valname;
1564 char *setpoint;
1565 uint64_t curval;
1566 int error;
1568 error = dsl_prop_set_int(osname, propname,
1569 (inherit ? ZPROP_SRC_NONE : ZPROP_SRC_LOCAL), value);
1571 if (error == ENOSPC) {
1572 ztest_record_enospc(FTAG);
1573 return (error);
1575 ASSERT0(error);
1577 setpoint = umem_alloc(MAXPATHLEN, UMEM_NOFAIL);
1578 VERIFY0(dsl_prop_get_integer(osname, propname, &curval, setpoint));
1580 if (ztest_opts.zo_verbose >= 6) {
1581 int err;
1583 err = zfs_prop_index_to_string(prop, curval, &valname);
1584 if (err)
1585 (void) printf("%s %s = %llu at '%s'\n", osname,
1586 propname, (unsigned long long)curval, setpoint);
1587 else
1588 (void) printf("%s %s = %s at '%s'\n",
1589 osname, propname, valname, setpoint);
1591 umem_free(setpoint, MAXPATHLEN);
1593 return (error);
1596 static int
1597 ztest_spa_prop_set_uint64(zpool_prop_t prop, uint64_t value)
1599 spa_t *spa = ztest_spa;
1600 nvlist_t *props = NULL;
1601 int error;
1603 props = fnvlist_alloc();
1604 fnvlist_add_uint64(props, zpool_prop_to_name(prop), value);
1606 error = spa_prop_set(spa, props);
1608 fnvlist_free(props);
1610 if (error == ENOSPC) {
1611 ztest_record_enospc(FTAG);
1612 return (error);
1614 ASSERT0(error);
1616 return (error);
1619 static int
1620 ztest_dmu_objset_own(const char *name, dmu_objset_type_t type,
1621 boolean_t readonly, boolean_t decrypt, const void *tag, objset_t **osp)
1623 int err;
1624 char *cp = NULL;
1625 char ddname[ZFS_MAX_DATASET_NAME_LEN];
1627 strlcpy(ddname, name, sizeof (ddname));
1628 cp = strchr(ddname, '@');
1629 if (cp != NULL)
1630 *cp = '\0';
1632 err = dmu_objset_own(name, type, readonly, decrypt, tag, osp);
1633 while (decrypt && err == EACCES) {
1634 dsl_crypto_params_t *dcp;
1635 nvlist_t *crypto_args = fnvlist_alloc();
1637 fnvlist_add_uint8_array(crypto_args, "wkeydata",
1638 (uint8_t *)ztest_wkeydata, WRAPPING_KEY_LEN);
1639 VERIFY0(dsl_crypto_params_create_nvlist(DCP_CMD_NONE, NULL,
1640 crypto_args, &dcp));
1641 err = spa_keystore_load_wkey(ddname, dcp, B_FALSE);
1643 * Note: if there was an error loading, the wkey was not
1644 * consumed, and needs to be freed.
1646 dsl_crypto_params_free(dcp, (err != 0));
1647 fnvlist_free(crypto_args);
1649 if (err == EINVAL) {
1651 * We couldn't load a key for this dataset so try
1652 * the parent. This loop will eventually hit the
1653 * encryption root since ztest only makes clones
1654 * as children of their origin datasets.
1656 cp = strrchr(ddname, '/');
1657 if (cp == NULL)
1658 return (err);
1660 *cp = '\0';
1661 err = EACCES;
1662 continue;
1663 } else if (err != 0) {
1664 break;
1667 err = dmu_objset_own(name, type, readonly, decrypt, tag, osp);
1668 break;
1671 return (err);
1674 static void
1675 ztest_rll_init(rll_t *rll)
1677 rll->rll_writer = NULL;
1678 rll->rll_readers = 0;
1679 mutex_init(&rll->rll_lock, NULL, MUTEX_DEFAULT, NULL);
1680 cv_init(&rll->rll_cv, NULL, CV_DEFAULT, NULL);
1683 static void
1684 ztest_rll_destroy(rll_t *rll)
1686 ASSERT3P(rll->rll_writer, ==, NULL);
1687 ASSERT0(rll->rll_readers);
1688 mutex_destroy(&rll->rll_lock);
1689 cv_destroy(&rll->rll_cv);
1692 static void
1693 ztest_rll_lock(rll_t *rll, rl_type_t type)
1695 mutex_enter(&rll->rll_lock);
1697 if (type == ZTRL_READER) {
1698 while (rll->rll_writer != NULL)
1699 (void) cv_wait(&rll->rll_cv, &rll->rll_lock);
1700 rll->rll_readers++;
1701 } else {
1702 while (rll->rll_writer != NULL || rll->rll_readers)
1703 (void) cv_wait(&rll->rll_cv, &rll->rll_lock);
1704 rll->rll_writer = curthread;
1707 mutex_exit(&rll->rll_lock);
1710 static void
1711 ztest_rll_unlock(rll_t *rll)
1713 mutex_enter(&rll->rll_lock);
1715 if (rll->rll_writer) {
1716 ASSERT0(rll->rll_readers);
1717 rll->rll_writer = NULL;
1718 } else {
1719 ASSERT3S(rll->rll_readers, >, 0);
1720 ASSERT3P(rll->rll_writer, ==, NULL);
1721 rll->rll_readers--;
1724 if (rll->rll_writer == NULL && rll->rll_readers == 0)
1725 cv_broadcast(&rll->rll_cv);
1727 mutex_exit(&rll->rll_lock);
1730 static void
1731 ztest_object_lock(ztest_ds_t *zd, uint64_t object, rl_type_t type)
1733 rll_t *rll = &zd->zd_object_lock[object & (ZTEST_OBJECT_LOCKS - 1)];
1735 ztest_rll_lock(rll, type);
1738 static void
1739 ztest_object_unlock(ztest_ds_t *zd, uint64_t object)
1741 rll_t *rll = &zd->zd_object_lock[object & (ZTEST_OBJECT_LOCKS - 1)];
1743 ztest_rll_unlock(rll);
1746 static rl_t *
1747 ztest_range_lock(ztest_ds_t *zd, uint64_t object, uint64_t offset,
1748 uint64_t size, rl_type_t type)
1750 uint64_t hash = object ^ (offset % (ZTEST_RANGE_LOCKS + 1));
1751 rll_t *rll = &zd->zd_range_lock[hash & (ZTEST_RANGE_LOCKS - 1)];
1752 rl_t *rl;
1754 rl = umem_alloc(sizeof (*rl), UMEM_NOFAIL);
1755 rl->rl_object = object;
1756 rl->rl_offset = offset;
1757 rl->rl_size = size;
1758 rl->rl_lock = rll;
1760 ztest_rll_lock(rll, type);
1762 return (rl);
1765 static void
1766 ztest_range_unlock(rl_t *rl)
1768 rll_t *rll = rl->rl_lock;
1770 ztest_rll_unlock(rll);
1772 umem_free(rl, sizeof (*rl));
1775 static void
1776 ztest_zd_init(ztest_ds_t *zd, ztest_shared_ds_t *szd, objset_t *os)
1778 zd->zd_os = os;
1779 zd->zd_zilog = dmu_objset_zil(os);
1780 zd->zd_shared = szd;
1781 dmu_objset_name(os, zd->zd_name);
1782 int l;
1784 if (zd->zd_shared != NULL)
1785 zd->zd_shared->zd_seq = 0;
1787 VERIFY0(pthread_rwlock_init(&zd->zd_zilog_lock, NULL));
1788 mutex_init(&zd->zd_dirobj_lock, NULL, MUTEX_DEFAULT, NULL);
1790 for (l = 0; l < ZTEST_OBJECT_LOCKS; l++)
1791 ztest_rll_init(&zd->zd_object_lock[l]);
1793 for (l = 0; l < ZTEST_RANGE_LOCKS; l++)
1794 ztest_rll_init(&zd->zd_range_lock[l]);
1797 static void
1798 ztest_zd_fini(ztest_ds_t *zd)
1800 int l;
1802 mutex_destroy(&zd->zd_dirobj_lock);
1803 (void) pthread_rwlock_destroy(&zd->zd_zilog_lock);
1805 for (l = 0; l < ZTEST_OBJECT_LOCKS; l++)
1806 ztest_rll_destroy(&zd->zd_object_lock[l]);
1808 for (l = 0; l < ZTEST_RANGE_LOCKS; l++)
1809 ztest_rll_destroy(&zd->zd_range_lock[l]);
1812 #define TXG_MIGHTWAIT (ztest_random(10) == 0 ? TXG_NOWAIT : TXG_WAIT)
1814 static uint64_t
1815 ztest_tx_assign(dmu_tx_t *tx, uint64_t txg_how, const char *tag)
1817 uint64_t txg;
1818 int error;
1821 * Attempt to assign tx to some transaction group.
1823 error = dmu_tx_assign(tx, txg_how);
1824 if (error) {
1825 if (error == ERESTART) {
1826 ASSERT3U(txg_how, ==, TXG_NOWAIT);
1827 dmu_tx_wait(tx);
1828 } else {
1829 ASSERT3U(error, ==, ENOSPC);
1830 ztest_record_enospc(tag);
1832 dmu_tx_abort(tx);
1833 return (0);
1835 txg = dmu_tx_get_txg(tx);
1836 ASSERT3U(txg, !=, 0);
1837 return (txg);
1840 static void
1841 ztest_bt_generate(ztest_block_tag_t *bt, objset_t *os, uint64_t object,
1842 uint64_t dnodesize, uint64_t offset, uint64_t gen, uint64_t txg,
1843 uint64_t crtxg)
1845 bt->bt_magic = BT_MAGIC;
1846 bt->bt_objset = dmu_objset_id(os);
1847 bt->bt_object = object;
1848 bt->bt_dnodesize = dnodesize;
1849 bt->bt_offset = offset;
1850 bt->bt_gen = gen;
1851 bt->bt_txg = txg;
1852 bt->bt_crtxg = crtxg;
1855 static void
1856 ztest_bt_verify(ztest_block_tag_t *bt, objset_t *os, uint64_t object,
1857 uint64_t dnodesize, uint64_t offset, uint64_t gen, uint64_t txg,
1858 uint64_t crtxg)
1860 ASSERT3U(bt->bt_magic, ==, BT_MAGIC);
1861 ASSERT3U(bt->bt_objset, ==, dmu_objset_id(os));
1862 ASSERT3U(bt->bt_object, ==, object);
1863 ASSERT3U(bt->bt_dnodesize, ==, dnodesize);
1864 ASSERT3U(bt->bt_offset, ==, offset);
1865 ASSERT3U(bt->bt_gen, <=, gen);
1866 ASSERT3U(bt->bt_txg, <=, txg);
1867 ASSERT3U(bt->bt_crtxg, ==, crtxg);
1870 static ztest_block_tag_t *
1871 ztest_bt_bonus(dmu_buf_t *db)
1873 dmu_object_info_t doi;
1874 ztest_block_tag_t *bt;
1876 dmu_object_info_from_db(db, &doi);
1877 ASSERT3U(doi.doi_bonus_size, <=, db->db_size);
1878 ASSERT3U(doi.doi_bonus_size, >=, sizeof (*bt));
1879 bt = (void *)((char *)db->db_data + doi.doi_bonus_size - sizeof (*bt));
1881 return (bt);
1885 * Generate a token to fill up unused bonus buffer space. Try to make
1886 * it unique to the object, generation, and offset to verify that data
1887 * is not getting overwritten by data from other dnodes.
1889 #define ZTEST_BONUS_FILL_TOKEN(obj, ds, gen, offset) \
1890 (((ds) << 48) | ((gen) << 32) | ((obj) << 8) | (offset))
1893 * Fill up the unused bonus buffer region before the block tag with a
1894 * verifiable pattern. Filling the whole bonus area with non-zero data
1895 * helps ensure that all dnode traversal code properly skips the
1896 * interior regions of large dnodes.
1898 static void
1899 ztest_fill_unused_bonus(dmu_buf_t *db, void *end, uint64_t obj,
1900 objset_t *os, uint64_t gen)
1902 uint64_t *bonusp;
1904 ASSERT(IS_P2ALIGNED((char *)end - (char *)db->db_data, 8));
1906 for (bonusp = db->db_data; bonusp < (uint64_t *)end; bonusp++) {
1907 uint64_t token = ZTEST_BONUS_FILL_TOKEN(obj, dmu_objset_id(os),
1908 gen, bonusp - (uint64_t *)db->db_data);
1909 *bonusp = token;
1914 * Verify that the unused area of a bonus buffer is filled with the
1915 * expected tokens.
1917 static void
1918 ztest_verify_unused_bonus(dmu_buf_t *db, void *end, uint64_t obj,
1919 objset_t *os, uint64_t gen)
1921 uint64_t *bonusp;
1923 for (bonusp = db->db_data; bonusp < (uint64_t *)end; bonusp++) {
1924 uint64_t token = ZTEST_BONUS_FILL_TOKEN(obj, dmu_objset_id(os),
1925 gen, bonusp - (uint64_t *)db->db_data);
1926 VERIFY3U(*bonusp, ==, token);
1931 * ZIL logging ops
1934 #define lrz_type lr_mode
1935 #define lrz_blocksize lr_uid
1936 #define lrz_ibshift lr_gid
1937 #define lrz_bonustype lr_rdev
1938 #define lrz_dnodesize lr_crtime[1]
1940 static void
1941 ztest_log_create(ztest_ds_t *zd, dmu_tx_t *tx, lr_create_t *lr)
1943 char *name = (char *)&lr->lr_data[0]; /* name follows lr */
1944 size_t namesize = strlen(name) + 1;
1945 itx_t *itx;
1947 if (zil_replaying(zd->zd_zilog, tx))
1948 return;
1950 itx = zil_itx_create(TX_CREATE, sizeof (*lr) + namesize);
1951 memcpy(&itx->itx_lr + 1, &lr->lr_create.lr_common + 1,
1952 sizeof (*lr) + namesize - sizeof (lr_t));
1954 zil_itx_assign(zd->zd_zilog, itx, tx);
1957 static void
1958 ztest_log_remove(ztest_ds_t *zd, dmu_tx_t *tx, lr_remove_t *lr, uint64_t object)
1960 char *name = (char *)&lr->lr_data[0]; /* name follows lr */
1961 size_t namesize = strlen(name) + 1;
1962 itx_t *itx;
1964 if (zil_replaying(zd->zd_zilog, tx))
1965 return;
1967 itx = zil_itx_create(TX_REMOVE, sizeof (*lr) + namesize);
1968 memcpy(&itx->itx_lr + 1, &lr->lr_common + 1,
1969 sizeof (*lr) + namesize - sizeof (lr_t));
1971 itx->itx_oid = object;
1972 zil_itx_assign(zd->zd_zilog, itx, tx);
1975 static void
1976 ztest_log_write(ztest_ds_t *zd, dmu_tx_t *tx, lr_write_t *lr)
1978 itx_t *itx;
1979 itx_wr_state_t write_state = ztest_random(WR_NUM_STATES);
1981 if (zil_replaying(zd->zd_zilog, tx))
1982 return;
1984 if (lr->lr_length > zil_max_log_data(zd->zd_zilog, sizeof (lr_write_t)))
1985 write_state = WR_INDIRECT;
1987 itx = zil_itx_create(TX_WRITE,
1988 sizeof (*lr) + (write_state == WR_COPIED ? lr->lr_length : 0));
1990 if (write_state == WR_COPIED &&
1991 dmu_read(zd->zd_os, lr->lr_foid, lr->lr_offset, lr->lr_length,
1992 ((lr_write_t *)&itx->itx_lr) + 1, DMU_READ_NO_PREFETCH) != 0) {
1993 zil_itx_destroy(itx);
1994 itx = zil_itx_create(TX_WRITE, sizeof (*lr));
1995 write_state = WR_NEED_COPY;
1997 itx->itx_private = zd;
1998 itx->itx_wr_state = write_state;
1999 itx->itx_sync = (ztest_random(8) == 0);
2001 memcpy(&itx->itx_lr + 1, &lr->lr_common + 1,
2002 sizeof (*lr) - sizeof (lr_t));
2004 zil_itx_assign(zd->zd_zilog, itx, tx);
2007 static void
2008 ztest_log_truncate(ztest_ds_t *zd, dmu_tx_t *tx, lr_truncate_t *lr)
2010 itx_t *itx;
2012 if (zil_replaying(zd->zd_zilog, tx))
2013 return;
2015 itx = zil_itx_create(TX_TRUNCATE, sizeof (*lr));
2016 memcpy(&itx->itx_lr + 1, &lr->lr_common + 1,
2017 sizeof (*lr) - sizeof (lr_t));
2019 itx->itx_sync = B_FALSE;
2020 zil_itx_assign(zd->zd_zilog, itx, tx);
2023 static void
2024 ztest_log_setattr(ztest_ds_t *zd, dmu_tx_t *tx, lr_setattr_t *lr)
2026 itx_t *itx;
2028 if (zil_replaying(zd->zd_zilog, tx))
2029 return;
2031 itx = zil_itx_create(TX_SETATTR, sizeof (*lr));
2032 memcpy(&itx->itx_lr + 1, &lr->lr_common + 1,
2033 sizeof (*lr) - sizeof (lr_t));
2035 itx->itx_sync = B_FALSE;
2036 zil_itx_assign(zd->zd_zilog, itx, tx);
2040 * ZIL replay ops
2042 static int
2043 ztest_replay_create(void *arg1, void *arg2, boolean_t byteswap)
2045 ztest_ds_t *zd = arg1;
2046 lr_create_t *lrc = arg2;
2047 _lr_create_t *lr = &lrc->lr_create;
2048 char *name = (char *)&lrc->lr_data[0]; /* name follows lr */
2049 objset_t *os = zd->zd_os;
2050 ztest_block_tag_t *bbt;
2051 dmu_buf_t *db;
2052 dmu_tx_t *tx;
2053 uint64_t txg;
2054 int error = 0;
2055 int bonuslen;
2057 if (byteswap)
2058 byteswap_uint64_array(lr, sizeof (*lr));
2060 ASSERT3U(lr->lr_doid, ==, ZTEST_DIROBJ);
2061 ASSERT3S(name[0], !=, '\0');
2063 tx = dmu_tx_create(os);
2065 dmu_tx_hold_zap(tx, lr->lr_doid, B_TRUE, name);
2067 if (lr->lrz_type == DMU_OT_ZAP_OTHER) {
2068 dmu_tx_hold_zap(tx, DMU_NEW_OBJECT, B_TRUE, NULL);
2069 } else {
2070 dmu_tx_hold_bonus(tx, DMU_NEW_OBJECT);
2073 txg = ztest_tx_assign(tx, TXG_WAIT, FTAG);
2074 if (txg == 0)
2075 return (ENOSPC);
2077 ASSERT3U(dmu_objset_zil(os)->zl_replay, ==, !!lr->lr_foid);
2078 bonuslen = DN_BONUS_SIZE(lr->lrz_dnodesize);
2080 if (lr->lrz_type == DMU_OT_ZAP_OTHER) {
2081 if (lr->lr_foid == 0) {
2082 lr->lr_foid = zap_create_dnsize(os,
2083 lr->lrz_type, lr->lrz_bonustype,
2084 bonuslen, lr->lrz_dnodesize, tx);
2085 } else {
2086 error = zap_create_claim_dnsize(os, lr->lr_foid,
2087 lr->lrz_type, lr->lrz_bonustype,
2088 bonuslen, lr->lrz_dnodesize, tx);
2090 } else {
2091 if (lr->lr_foid == 0) {
2092 lr->lr_foid = dmu_object_alloc_dnsize(os,
2093 lr->lrz_type, 0, lr->lrz_bonustype,
2094 bonuslen, lr->lrz_dnodesize, tx);
2095 } else {
2096 error = dmu_object_claim_dnsize(os, lr->lr_foid,
2097 lr->lrz_type, 0, lr->lrz_bonustype,
2098 bonuslen, lr->lrz_dnodesize, tx);
2102 if (error) {
2103 ASSERT3U(error, ==, EEXIST);
2104 ASSERT(zd->zd_zilog->zl_replay);
2105 dmu_tx_commit(tx);
2106 return (error);
2109 ASSERT3U(lr->lr_foid, !=, 0);
2111 if (lr->lrz_type != DMU_OT_ZAP_OTHER)
2112 VERIFY0(dmu_object_set_blocksize(os, lr->lr_foid,
2113 lr->lrz_blocksize, lr->lrz_ibshift, tx));
2115 VERIFY0(dmu_bonus_hold(os, lr->lr_foid, FTAG, &db));
2116 bbt = ztest_bt_bonus(db);
2117 dmu_buf_will_dirty(db, tx);
2118 ztest_bt_generate(bbt, os, lr->lr_foid, lr->lrz_dnodesize, -1ULL,
2119 lr->lr_gen, txg, txg);
2120 ztest_fill_unused_bonus(db, bbt, lr->lr_foid, os, lr->lr_gen);
2121 dmu_buf_rele(db, FTAG);
2123 VERIFY0(zap_add(os, lr->lr_doid, name, sizeof (uint64_t), 1,
2124 &lr->lr_foid, tx));
2126 (void) ztest_log_create(zd, tx, lrc);
2128 dmu_tx_commit(tx);
2130 return (0);
2133 static int
2134 ztest_replay_remove(void *arg1, void *arg2, boolean_t byteswap)
2136 ztest_ds_t *zd = arg1;
2137 lr_remove_t *lr = arg2;
2138 char *name = (char *)&lr->lr_data[0]; /* name follows lr */
2139 objset_t *os = zd->zd_os;
2140 dmu_object_info_t doi;
2141 dmu_tx_t *tx;
2142 uint64_t object, txg;
2144 if (byteswap)
2145 byteswap_uint64_array(lr, sizeof (*lr));
2147 ASSERT3U(lr->lr_doid, ==, ZTEST_DIROBJ);
2148 ASSERT3S(name[0], !=, '\0');
2150 VERIFY0(
2151 zap_lookup(os, lr->lr_doid, name, sizeof (object), 1, &object));
2152 ASSERT3U(object, !=, 0);
2154 ztest_object_lock(zd, object, ZTRL_WRITER);
2156 VERIFY0(dmu_object_info(os, object, &doi));
2158 tx = dmu_tx_create(os);
2160 dmu_tx_hold_zap(tx, lr->lr_doid, B_FALSE, name);
2161 dmu_tx_hold_free(tx, object, 0, DMU_OBJECT_END);
2163 txg = ztest_tx_assign(tx, TXG_WAIT, FTAG);
2164 if (txg == 0) {
2165 ztest_object_unlock(zd, object);
2166 return (ENOSPC);
2169 if (doi.doi_type == DMU_OT_ZAP_OTHER) {
2170 VERIFY0(zap_destroy(os, object, tx));
2171 } else {
2172 VERIFY0(dmu_object_free(os, object, tx));
2175 VERIFY0(zap_remove(os, lr->lr_doid, name, tx));
2177 (void) ztest_log_remove(zd, tx, lr, object);
2179 dmu_tx_commit(tx);
2181 ztest_object_unlock(zd, object);
2183 return (0);
2186 static int
2187 ztest_replay_write(void *arg1, void *arg2, boolean_t byteswap)
2189 ztest_ds_t *zd = arg1;
2190 lr_write_t *lr = arg2;
2191 objset_t *os = zd->zd_os;
2192 uint8_t *data = &lr->lr_data[0]; /* data follows lr */
2193 uint64_t offset, length;
2194 ztest_block_tag_t *bt = (ztest_block_tag_t *)data;
2195 ztest_block_tag_t *bbt;
2196 uint64_t gen, txg, lrtxg, crtxg;
2197 dmu_object_info_t doi;
2198 dmu_tx_t *tx;
2199 dmu_buf_t *db;
2200 arc_buf_t *abuf = NULL;
2201 rl_t *rl;
2203 if (byteswap)
2204 byteswap_uint64_array(lr, sizeof (*lr));
2206 offset = lr->lr_offset;
2207 length = lr->lr_length;
2209 /* If it's a dmu_sync() block, write the whole block */
2210 if (lr->lr_common.lrc_reclen == sizeof (lr_write_t)) {
2211 uint64_t blocksize = BP_GET_LSIZE(&lr->lr_blkptr);
2212 if (length < blocksize) {
2213 offset -= offset % blocksize;
2214 length = blocksize;
2218 if (bt->bt_magic == BSWAP_64(BT_MAGIC))
2219 byteswap_uint64_array(bt, sizeof (*bt));
2221 if (bt->bt_magic != BT_MAGIC)
2222 bt = NULL;
2224 ztest_object_lock(zd, lr->lr_foid, ZTRL_READER);
2225 rl = ztest_range_lock(zd, lr->lr_foid, offset, length, ZTRL_WRITER);
2227 VERIFY0(dmu_bonus_hold(os, lr->lr_foid, FTAG, &db));
2229 dmu_object_info_from_db(db, &doi);
2231 bbt = ztest_bt_bonus(db);
2232 ASSERT3U(bbt->bt_magic, ==, BT_MAGIC);
2233 gen = bbt->bt_gen;
2234 crtxg = bbt->bt_crtxg;
2235 lrtxg = lr->lr_common.lrc_txg;
2237 tx = dmu_tx_create(os);
2239 dmu_tx_hold_write(tx, lr->lr_foid, offset, length);
2241 if (ztest_random(8) == 0 && length == doi.doi_data_block_size &&
2242 P2PHASE(offset, length) == 0)
2243 abuf = dmu_request_arcbuf(db, length);
2245 txg = ztest_tx_assign(tx, TXG_WAIT, FTAG);
2246 if (txg == 0) {
2247 if (abuf != NULL)
2248 dmu_return_arcbuf(abuf);
2249 dmu_buf_rele(db, FTAG);
2250 ztest_range_unlock(rl);
2251 ztest_object_unlock(zd, lr->lr_foid);
2252 return (ENOSPC);
2255 if (bt != NULL) {
2257 * Usually, verify the old data before writing new data --
2258 * but not always, because we also want to verify correct
2259 * behavior when the data was not recently read into cache.
2261 ASSERT(doi.doi_data_block_size);
2262 ASSERT0(offset % doi.doi_data_block_size);
2263 if (ztest_random(4) != 0) {
2264 int prefetch = ztest_random(2) ?
2265 DMU_READ_PREFETCH : DMU_READ_NO_PREFETCH;
2268 * We will randomly set when to do O_DIRECT on a read.
2270 if (ztest_random(4) == 0)
2271 prefetch |= DMU_DIRECTIO;
2273 ztest_block_tag_t rbt;
2275 VERIFY(dmu_read(os, lr->lr_foid, offset,
2276 sizeof (rbt), &rbt, prefetch) == 0);
2277 if (rbt.bt_magic == BT_MAGIC) {
2278 ztest_bt_verify(&rbt, os, lr->lr_foid, 0,
2279 offset, gen, txg, crtxg);
2284 * Writes can appear to be newer than the bonus buffer because
2285 * the ztest_get_data() callback does a dmu_read() of the
2286 * open-context data, which may be different than the data
2287 * as it was when the write was generated.
2289 if (zd->zd_zilog->zl_replay) {
2290 ztest_bt_verify(bt, os, lr->lr_foid, 0, offset,
2291 MAX(gen, bt->bt_gen), MAX(txg, lrtxg),
2292 bt->bt_crtxg);
2296 * Set the bt's gen/txg to the bonus buffer's gen/txg
2297 * so that all of the usual ASSERTs will work.
2299 ztest_bt_generate(bt, os, lr->lr_foid, 0, offset, gen, txg,
2300 crtxg);
2303 if (abuf == NULL) {
2304 dmu_write(os, lr->lr_foid, offset, length, data, tx);
2305 } else {
2306 memcpy(abuf->b_data, data, length);
2307 VERIFY0(dmu_assign_arcbuf_by_dbuf(db, offset, abuf, tx));
2310 (void) ztest_log_write(zd, tx, lr);
2312 dmu_buf_rele(db, FTAG);
2314 dmu_tx_commit(tx);
2316 ztest_range_unlock(rl);
2317 ztest_object_unlock(zd, lr->lr_foid);
2319 return (0);
2322 static int
2323 ztest_replay_truncate(void *arg1, void *arg2, boolean_t byteswap)
2325 ztest_ds_t *zd = arg1;
2326 lr_truncate_t *lr = arg2;
2327 objset_t *os = zd->zd_os;
2328 dmu_tx_t *tx;
2329 uint64_t txg;
2330 rl_t *rl;
2332 if (byteswap)
2333 byteswap_uint64_array(lr, sizeof (*lr));
2335 ztest_object_lock(zd, lr->lr_foid, ZTRL_READER);
2336 rl = ztest_range_lock(zd, lr->lr_foid, lr->lr_offset, lr->lr_length,
2337 ZTRL_WRITER);
2339 tx = dmu_tx_create(os);
2341 dmu_tx_hold_free(tx, lr->lr_foid, lr->lr_offset, lr->lr_length);
2343 txg = ztest_tx_assign(tx, TXG_WAIT, FTAG);
2344 if (txg == 0) {
2345 ztest_range_unlock(rl);
2346 ztest_object_unlock(zd, lr->lr_foid);
2347 return (ENOSPC);
2350 VERIFY0(dmu_free_range(os, lr->lr_foid, lr->lr_offset,
2351 lr->lr_length, tx));
2353 (void) ztest_log_truncate(zd, tx, lr);
2355 dmu_tx_commit(tx);
2357 ztest_range_unlock(rl);
2358 ztest_object_unlock(zd, lr->lr_foid);
2360 return (0);
2363 static int
2364 ztest_replay_setattr(void *arg1, void *arg2, boolean_t byteswap)
2366 ztest_ds_t *zd = arg1;
2367 lr_setattr_t *lr = arg2;
2368 objset_t *os = zd->zd_os;
2369 dmu_tx_t *tx;
2370 dmu_buf_t *db;
2371 ztest_block_tag_t *bbt;
2372 uint64_t txg, lrtxg, crtxg, dnodesize;
2374 if (byteswap)
2375 byteswap_uint64_array(lr, sizeof (*lr));
2377 ztest_object_lock(zd, lr->lr_foid, ZTRL_WRITER);
2379 VERIFY0(dmu_bonus_hold(os, lr->lr_foid, FTAG, &db));
2381 tx = dmu_tx_create(os);
2382 dmu_tx_hold_bonus(tx, lr->lr_foid);
2384 txg = ztest_tx_assign(tx, TXG_WAIT, FTAG);
2385 if (txg == 0) {
2386 dmu_buf_rele(db, FTAG);
2387 ztest_object_unlock(zd, lr->lr_foid);
2388 return (ENOSPC);
2391 bbt = ztest_bt_bonus(db);
2392 ASSERT3U(bbt->bt_magic, ==, BT_MAGIC);
2393 crtxg = bbt->bt_crtxg;
2394 lrtxg = lr->lr_common.lrc_txg;
2395 dnodesize = bbt->bt_dnodesize;
2397 if (zd->zd_zilog->zl_replay) {
2398 ASSERT3U(lr->lr_size, !=, 0);
2399 ASSERT3U(lr->lr_mode, !=, 0);
2400 ASSERT3U(lrtxg, !=, 0);
2401 } else {
2403 * Randomly change the size and increment the generation.
2405 lr->lr_size = (ztest_random(db->db_size / sizeof (*bbt)) + 1) *
2406 sizeof (*bbt);
2407 lr->lr_mode = bbt->bt_gen + 1;
2408 ASSERT0(lrtxg);
2412 * Verify that the current bonus buffer is not newer than our txg.
2414 ztest_bt_verify(bbt, os, lr->lr_foid, dnodesize, -1ULL, lr->lr_mode,
2415 MAX(txg, lrtxg), crtxg);
2417 dmu_buf_will_dirty(db, tx);
2419 ASSERT3U(lr->lr_size, >=, sizeof (*bbt));
2420 ASSERT3U(lr->lr_size, <=, db->db_size);
2421 VERIFY0(dmu_set_bonus(db, lr->lr_size, tx));
2422 bbt = ztest_bt_bonus(db);
2424 ztest_bt_generate(bbt, os, lr->lr_foid, dnodesize, -1ULL, lr->lr_mode,
2425 txg, crtxg);
2426 ztest_fill_unused_bonus(db, bbt, lr->lr_foid, os, bbt->bt_gen);
2427 dmu_buf_rele(db, FTAG);
2429 (void) ztest_log_setattr(zd, tx, lr);
2431 dmu_tx_commit(tx);
2433 ztest_object_unlock(zd, lr->lr_foid);
2435 return (0);
2438 static zil_replay_func_t *ztest_replay_vector[TX_MAX_TYPE] = {
2439 NULL, /* 0 no such transaction type */
2440 ztest_replay_create, /* TX_CREATE */
2441 NULL, /* TX_MKDIR */
2442 NULL, /* TX_MKXATTR */
2443 NULL, /* TX_SYMLINK */
2444 ztest_replay_remove, /* TX_REMOVE */
2445 NULL, /* TX_RMDIR */
2446 NULL, /* TX_LINK */
2447 NULL, /* TX_RENAME */
2448 ztest_replay_write, /* TX_WRITE */
2449 ztest_replay_truncate, /* TX_TRUNCATE */
2450 ztest_replay_setattr, /* TX_SETATTR */
2451 NULL, /* TX_ACL */
2452 NULL, /* TX_CREATE_ACL */
2453 NULL, /* TX_CREATE_ATTR */
2454 NULL, /* TX_CREATE_ACL_ATTR */
2455 NULL, /* TX_MKDIR_ACL */
2456 NULL, /* TX_MKDIR_ATTR */
2457 NULL, /* TX_MKDIR_ACL_ATTR */
2458 NULL, /* TX_WRITE2 */
2459 NULL, /* TX_SETSAXATTR */
2460 NULL, /* TX_RENAME_EXCHANGE */
2461 NULL, /* TX_RENAME_WHITEOUT */
2465 * ZIL get_data callbacks
2468 static void
2469 ztest_get_done(zgd_t *zgd, int error)
2471 (void) error;
2472 ztest_ds_t *zd = zgd->zgd_private;
2473 uint64_t object = ((rl_t *)zgd->zgd_lr)->rl_object;
2475 if (zgd->zgd_db)
2476 dmu_buf_rele(zgd->zgd_db, zgd);
2478 ztest_range_unlock((rl_t *)zgd->zgd_lr);
2479 ztest_object_unlock(zd, object);
2481 umem_free(zgd, sizeof (*zgd));
2484 static int
2485 ztest_get_data(void *arg, uint64_t arg2, lr_write_t *lr, char *buf,
2486 struct lwb *lwb, zio_t *zio)
2488 (void) arg2;
2489 ztest_ds_t *zd = arg;
2490 objset_t *os = zd->zd_os;
2491 uint64_t object = lr->lr_foid;
2492 uint64_t offset = lr->lr_offset;
2493 uint64_t size = lr->lr_length;
2494 uint64_t txg = lr->lr_common.lrc_txg;
2495 uint64_t crtxg;
2496 dmu_object_info_t doi;
2497 dmu_buf_t *db;
2498 zgd_t *zgd;
2499 int error;
2501 ASSERT3P(lwb, !=, NULL);
2502 ASSERT3U(size, !=, 0);
2504 ztest_object_lock(zd, object, ZTRL_READER);
2505 error = dmu_bonus_hold(os, object, FTAG, &db);
2506 if (error) {
2507 ztest_object_unlock(zd, object);
2508 return (error);
2511 crtxg = ztest_bt_bonus(db)->bt_crtxg;
2513 if (crtxg == 0 || crtxg > txg) {
2514 dmu_buf_rele(db, FTAG);
2515 ztest_object_unlock(zd, object);
2516 return (ENOENT);
2519 dmu_object_info_from_db(db, &doi);
2520 dmu_buf_rele(db, FTAG);
2521 db = NULL;
2523 zgd = umem_zalloc(sizeof (*zgd), UMEM_NOFAIL);
2524 zgd->zgd_lwb = lwb;
2525 zgd->zgd_private = zd;
2527 if (buf != NULL) { /* immediate write */
2528 zgd->zgd_lr = (struct zfs_locked_range *)ztest_range_lock(zd,
2529 object, offset, size, ZTRL_READER);
2531 error = dmu_read(os, object, offset, size, buf,
2532 DMU_READ_NO_PREFETCH);
2533 ASSERT0(error);
2534 } else {
2535 ASSERT3P(zio, !=, NULL);
2536 size = doi.doi_data_block_size;
2537 if (ISP2(size)) {
2538 offset = P2ALIGN_TYPED(offset, size, uint64_t);
2539 } else {
2540 ASSERT3U(offset, <, size);
2541 offset = 0;
2544 zgd->zgd_lr = (struct zfs_locked_range *)ztest_range_lock(zd,
2545 object, offset, size, ZTRL_READER);
2547 error = dmu_buf_hold_noread(os, object, offset, zgd, &db);
2549 if (error == 0) {
2550 blkptr_t *bp = &lr->lr_blkptr;
2552 zgd->zgd_db = db;
2553 zgd->zgd_bp = bp;
2555 ASSERT3U(db->db_offset, ==, offset);
2556 ASSERT3U(db->db_size, ==, size);
2558 error = dmu_sync(zio, lr->lr_common.lrc_txg,
2559 ztest_get_done, zgd);
2561 if (error == 0)
2562 return (0);
2566 ztest_get_done(zgd, error);
2568 return (error);
2571 static void *
2572 ztest_lr_alloc(size_t lrsize, char *name)
2574 char *lr;
2575 size_t namesize = name ? strlen(name) + 1 : 0;
2577 lr = umem_zalloc(lrsize + namesize, UMEM_NOFAIL);
2579 if (name)
2580 memcpy(lr + lrsize, name, namesize);
2582 return (lr);
2585 static void
2586 ztest_lr_free(void *lr, size_t lrsize, char *name)
2588 size_t namesize = name ? strlen(name) + 1 : 0;
2590 umem_free(lr, lrsize + namesize);
2594 * Lookup a bunch of objects. Returns the number of objects not found.
2596 static int
2597 ztest_lookup(ztest_ds_t *zd, ztest_od_t *od, int count)
2599 int missing = 0;
2600 int error;
2601 int i;
2603 ASSERT(MUTEX_HELD(&zd->zd_dirobj_lock));
2605 for (i = 0; i < count; i++, od++) {
2606 od->od_object = 0;
2607 error = zap_lookup(zd->zd_os, od->od_dir, od->od_name,
2608 sizeof (uint64_t), 1, &od->od_object);
2609 if (error) {
2610 ASSERT3S(error, ==, ENOENT);
2611 ASSERT0(od->od_object);
2612 missing++;
2613 } else {
2614 dmu_buf_t *db;
2615 ztest_block_tag_t *bbt;
2616 dmu_object_info_t doi;
2618 ASSERT3U(od->od_object, !=, 0);
2619 ASSERT0(missing); /* there should be no gaps */
2621 ztest_object_lock(zd, od->od_object, ZTRL_READER);
2622 VERIFY0(dmu_bonus_hold(zd->zd_os, od->od_object,
2623 FTAG, &db));
2624 dmu_object_info_from_db(db, &doi);
2625 bbt = ztest_bt_bonus(db);
2626 ASSERT3U(bbt->bt_magic, ==, BT_MAGIC);
2627 od->od_type = doi.doi_type;
2628 od->od_blocksize = doi.doi_data_block_size;
2629 od->od_gen = bbt->bt_gen;
2630 dmu_buf_rele(db, FTAG);
2631 ztest_object_unlock(zd, od->od_object);
2635 return (missing);
2638 static int
2639 ztest_create(ztest_ds_t *zd, ztest_od_t *od, int count)
2641 int missing = 0;
2642 int i;
2644 ASSERT(MUTEX_HELD(&zd->zd_dirobj_lock));
2646 for (i = 0; i < count; i++, od++) {
2647 if (missing) {
2648 od->od_object = 0;
2649 missing++;
2650 continue;
2653 lr_create_t *lrc = ztest_lr_alloc(sizeof (*lrc), od->od_name);
2654 _lr_create_t *lr = &lrc->lr_create;
2656 lr->lr_doid = od->od_dir;
2657 lr->lr_foid = 0; /* 0 to allocate, > 0 to claim */
2658 lr->lrz_type = od->od_crtype;
2659 lr->lrz_blocksize = od->od_crblocksize;
2660 lr->lrz_ibshift = ztest_random_ibshift();
2661 lr->lrz_bonustype = DMU_OT_UINT64_OTHER;
2662 lr->lrz_dnodesize = od->od_crdnodesize;
2663 lr->lr_gen = od->od_crgen;
2664 lr->lr_crtime[0] = time(NULL);
2666 if (ztest_replay_create(zd, lr, B_FALSE) != 0) {
2667 ASSERT0(missing);
2668 od->od_object = 0;
2669 missing++;
2670 } else {
2671 od->od_object = lr->lr_foid;
2672 od->od_type = od->od_crtype;
2673 od->od_blocksize = od->od_crblocksize;
2674 od->od_gen = od->od_crgen;
2675 ASSERT3U(od->od_object, !=, 0);
2678 ztest_lr_free(lr, sizeof (*lr), od->od_name);
2681 return (missing);
2684 static int
2685 ztest_remove(ztest_ds_t *zd, ztest_od_t *od, int count)
2687 int missing = 0;
2688 int error;
2689 int i;
2691 ASSERT(MUTEX_HELD(&zd->zd_dirobj_lock));
2693 od += count - 1;
2695 for (i = count - 1; i >= 0; i--, od--) {
2696 if (missing) {
2697 missing++;
2698 continue;
2702 * No object was found.
2704 if (od->od_object == 0)
2705 continue;
2707 lr_remove_t *lr = ztest_lr_alloc(sizeof (*lr), od->od_name);
2709 lr->lr_doid = od->od_dir;
2711 if ((error = ztest_replay_remove(zd, lr, B_FALSE)) != 0) {
2712 ASSERT3U(error, ==, ENOSPC);
2713 missing++;
2714 } else {
2715 od->od_object = 0;
2717 ztest_lr_free(lr, sizeof (*lr), od->od_name);
2720 return (missing);
2723 static int
2724 ztest_write(ztest_ds_t *zd, uint64_t object, uint64_t offset, uint64_t size,
2725 const void *data)
2727 lr_write_t *lr;
2728 int error;
2730 lr = ztest_lr_alloc(sizeof (*lr) + size, NULL);
2732 lr->lr_foid = object;
2733 lr->lr_offset = offset;
2734 lr->lr_length = size;
2735 lr->lr_blkoff = 0;
2736 BP_ZERO(&lr->lr_blkptr);
2738 memcpy(&lr->lr_data[0], data, size);
2740 error = ztest_replay_write(zd, lr, B_FALSE);
2742 ztest_lr_free(lr, sizeof (*lr) + size, NULL);
2744 return (error);
2747 static int
2748 ztest_truncate(ztest_ds_t *zd, uint64_t object, uint64_t offset, uint64_t size)
2750 lr_truncate_t *lr;
2751 int error;
2753 lr = ztest_lr_alloc(sizeof (*lr), NULL);
2755 lr->lr_foid = object;
2756 lr->lr_offset = offset;
2757 lr->lr_length = size;
2759 error = ztest_replay_truncate(zd, lr, B_FALSE);
2761 ztest_lr_free(lr, sizeof (*lr), NULL);
2763 return (error);
2766 static int
2767 ztest_setattr(ztest_ds_t *zd, uint64_t object)
2769 lr_setattr_t *lr;
2770 int error;
2772 lr = ztest_lr_alloc(sizeof (*lr), NULL);
2774 lr->lr_foid = object;
2775 lr->lr_size = 0;
2776 lr->lr_mode = 0;
2778 error = ztest_replay_setattr(zd, lr, B_FALSE);
2780 ztest_lr_free(lr, sizeof (*lr), NULL);
2782 return (error);
2785 static void
2786 ztest_prealloc(ztest_ds_t *zd, uint64_t object, uint64_t offset, uint64_t size)
2788 objset_t *os = zd->zd_os;
2789 dmu_tx_t *tx;
2790 uint64_t txg;
2791 rl_t *rl;
2793 txg_wait_synced(dmu_objset_pool(os), 0);
2795 ztest_object_lock(zd, object, ZTRL_READER);
2796 rl = ztest_range_lock(zd, object, offset, size, ZTRL_WRITER);
2798 tx = dmu_tx_create(os);
2800 dmu_tx_hold_write(tx, object, offset, size);
2802 txg = ztest_tx_assign(tx, TXG_WAIT, FTAG);
2804 if (txg != 0) {
2805 dmu_prealloc(os, object, offset, size, tx);
2806 dmu_tx_commit(tx);
2807 txg_wait_synced(dmu_objset_pool(os), txg);
2808 } else {
2809 (void) dmu_free_long_range(os, object, offset, size);
2812 ztest_range_unlock(rl);
2813 ztest_object_unlock(zd, object);
2816 static void
2817 ztest_io(ztest_ds_t *zd, uint64_t object, uint64_t offset)
2819 int err;
2820 ztest_block_tag_t wbt;
2821 dmu_object_info_t doi;
2822 enum ztest_io_type io_type;
2823 uint64_t blocksize;
2824 void *data;
2825 uint32_t dmu_read_flags = DMU_READ_NO_PREFETCH;
2828 * We will randomly set when to do O_DIRECT on a read.
2830 if (ztest_random(4) == 0)
2831 dmu_read_flags |= DMU_DIRECTIO;
2833 VERIFY0(dmu_object_info(zd->zd_os, object, &doi));
2834 blocksize = doi.doi_data_block_size;
2835 data = umem_alloc(blocksize, UMEM_NOFAIL);
2838 * Pick an i/o type at random, biased toward writing block tags.
2840 io_type = ztest_random(ZTEST_IO_TYPES);
2841 if (ztest_random(2) == 0)
2842 io_type = ZTEST_IO_WRITE_TAG;
2844 (void) pthread_rwlock_rdlock(&zd->zd_zilog_lock);
2846 switch (io_type) {
2848 case ZTEST_IO_WRITE_TAG:
2849 ztest_bt_generate(&wbt, zd->zd_os, object, doi.doi_dnodesize,
2850 offset, 0, 0, 0);
2851 (void) ztest_write(zd, object, offset, sizeof (wbt), &wbt);
2852 break;
2854 case ZTEST_IO_WRITE_PATTERN:
2855 (void) memset(data, 'a' + (object + offset) % 5, blocksize);
2856 if (ztest_random(2) == 0) {
2858 * Induce fletcher2 collisions to ensure that
2859 * zio_ddt_collision() detects and resolves them
2860 * when using fletcher2-verify for deduplication.
2862 ((uint64_t *)data)[0] ^= 1ULL << 63;
2863 ((uint64_t *)data)[4] ^= 1ULL << 63;
2865 (void) ztest_write(zd, object, offset, blocksize, data);
2866 break;
2868 case ZTEST_IO_WRITE_ZEROES:
2869 memset(data, 0, blocksize);
2870 (void) ztest_write(zd, object, offset, blocksize, data);
2871 break;
2873 case ZTEST_IO_TRUNCATE:
2874 (void) ztest_truncate(zd, object, offset, blocksize);
2875 break;
2877 case ZTEST_IO_SETATTR:
2878 (void) ztest_setattr(zd, object);
2879 break;
2880 default:
2881 break;
2883 case ZTEST_IO_REWRITE:
2884 (void) pthread_rwlock_rdlock(&ztest_name_lock);
2885 err = ztest_dsl_prop_set_uint64(zd->zd_name,
2886 ZFS_PROP_CHECKSUM, spa_dedup_checksum(ztest_spa),
2887 B_FALSE);
2888 ASSERT(err == 0 || err == ENOSPC);
2889 err = ztest_dsl_prop_set_uint64(zd->zd_name,
2890 ZFS_PROP_COMPRESSION,
2891 ztest_random_dsl_prop(ZFS_PROP_COMPRESSION),
2892 B_FALSE);
2893 ASSERT(err == 0 || err == ENOSPC);
2894 (void) pthread_rwlock_unlock(&ztest_name_lock);
2896 VERIFY0(dmu_read(zd->zd_os, object, offset, blocksize, data,
2897 dmu_read_flags));
2899 (void) ztest_write(zd, object, offset, blocksize, data);
2900 break;
2903 (void) pthread_rwlock_unlock(&zd->zd_zilog_lock);
2905 umem_free(data, blocksize);
2909 * Initialize an object description template.
2911 static void
2912 ztest_od_init(ztest_od_t *od, uint64_t id, const char *tag, uint64_t index,
2913 dmu_object_type_t type, uint64_t blocksize, uint64_t dnodesize,
2914 uint64_t gen)
2916 od->od_dir = ZTEST_DIROBJ;
2917 od->od_object = 0;
2919 od->od_crtype = type;
2920 od->od_crblocksize = blocksize ? blocksize : ztest_random_blocksize();
2921 od->od_crdnodesize = dnodesize ? dnodesize : ztest_random_dnodesize();
2922 od->od_crgen = gen;
2924 od->od_type = DMU_OT_NONE;
2925 od->od_blocksize = 0;
2926 od->od_gen = 0;
2928 (void) snprintf(od->od_name, sizeof (od->od_name),
2929 "%s(%"PRId64")[%"PRIu64"]",
2930 tag, id, index);
2934 * Lookup or create the objects for a test using the od template.
2935 * If the objects do not all exist, or if 'remove' is specified,
2936 * remove any existing objects and create new ones. Otherwise,
2937 * use the existing objects.
2939 static int
2940 ztest_object_init(ztest_ds_t *zd, ztest_od_t *od, size_t size, boolean_t remove)
2942 int count = size / sizeof (*od);
2943 int rv = 0;
2945 mutex_enter(&zd->zd_dirobj_lock);
2946 if ((ztest_lookup(zd, od, count) != 0 || remove) &&
2947 (ztest_remove(zd, od, count) != 0 ||
2948 ztest_create(zd, od, count) != 0))
2949 rv = -1;
2950 zd->zd_od = od;
2951 mutex_exit(&zd->zd_dirobj_lock);
2953 return (rv);
2956 void
2957 ztest_zil_commit(ztest_ds_t *zd, uint64_t id)
2959 (void) id;
2960 zilog_t *zilog = zd->zd_zilog;
2962 (void) pthread_rwlock_rdlock(&zd->zd_zilog_lock);
2964 zil_commit(zilog, ztest_random(ZTEST_OBJECTS));
2967 * Remember the committed values in zd, which is in parent/child
2968 * shared memory. If we die, the next iteration of ztest_run()
2969 * will verify that the log really does contain this record.
2971 mutex_enter(&zilog->zl_lock);
2972 ASSERT3P(zd->zd_shared, !=, NULL);
2973 ASSERT3U(zd->zd_shared->zd_seq, <=, zilog->zl_commit_lr_seq);
2974 zd->zd_shared->zd_seq = zilog->zl_commit_lr_seq;
2975 mutex_exit(&zilog->zl_lock);
2977 (void) pthread_rwlock_unlock(&zd->zd_zilog_lock);
2981 * This function is designed to simulate the operations that occur during a
2982 * mount/unmount operation. We hold the dataset across these operations in an
2983 * attempt to expose any implicit assumptions about ZIL management.
2985 void
2986 ztest_zil_remount(ztest_ds_t *zd, uint64_t id)
2988 (void) id;
2989 objset_t *os = zd->zd_os;
2992 * We hold the ztest_vdev_lock so we don't cause problems with
2993 * other threads that wish to remove a log device, such as
2994 * ztest_device_removal().
2996 mutex_enter(&ztest_vdev_lock);
2999 * We grab the zd_dirobj_lock to ensure that no other thread is
3000 * updating the zil (i.e. adding in-memory log records) and the
3001 * zd_zilog_lock to block any I/O.
3003 mutex_enter(&zd->zd_dirobj_lock);
3004 (void) pthread_rwlock_wrlock(&zd->zd_zilog_lock);
3006 /* zfsvfs_teardown() */
3007 zil_close(zd->zd_zilog);
3009 /* zfsvfs_setup() */
3010 VERIFY3P(zil_open(os, ztest_get_data, NULL), ==, zd->zd_zilog);
3011 zil_replay(os, zd, ztest_replay_vector);
3013 (void) pthread_rwlock_unlock(&zd->zd_zilog_lock);
3014 mutex_exit(&zd->zd_dirobj_lock);
3015 mutex_exit(&ztest_vdev_lock);
3019 * Verify that we can't destroy an active pool, create an existing pool,
3020 * or create a pool with a bad vdev spec.
3022 void
3023 ztest_spa_create_destroy(ztest_ds_t *zd, uint64_t id)
3025 (void) zd, (void) id;
3026 ztest_shared_opts_t *zo = &ztest_opts;
3027 spa_t *spa;
3028 nvlist_t *nvroot;
3030 if (zo->zo_mmp_test)
3031 return;
3034 * Attempt to create using a bad file.
3036 nvroot = make_vdev_root("/dev/bogus", NULL, NULL, 0, 0, NULL, 0, 0, 1);
3037 VERIFY3U(ENOENT, ==,
3038 spa_create("ztest_bad_file", nvroot, NULL, NULL, NULL));
3039 fnvlist_free(nvroot);
3042 * Attempt to create using a bad mirror.
3044 nvroot = make_vdev_root("/dev/bogus", NULL, NULL, 0, 0, NULL, 0, 2, 1);
3045 VERIFY3U(ENOENT, ==,
3046 spa_create("ztest_bad_mirror", nvroot, NULL, NULL, NULL));
3047 fnvlist_free(nvroot);
3050 * Attempt to create an existing pool. It shouldn't matter
3051 * what's in the nvroot; we should fail with EEXIST.
3053 (void) pthread_rwlock_rdlock(&ztest_name_lock);
3054 nvroot = make_vdev_root("/dev/bogus", NULL, NULL, 0, 0, NULL, 0, 0, 1);
3055 VERIFY3U(EEXIST, ==,
3056 spa_create(zo->zo_pool, nvroot, NULL, NULL, NULL));
3057 fnvlist_free(nvroot);
3060 * We open a reference to the spa and then we try to export it
3061 * expecting one of the following errors:
3063 * EBUSY
3064 * Because of the reference we just opened.
3066 * ZFS_ERR_EXPORT_IN_PROGRESS
3067 * For the case that there is another ztest thread doing
3068 * an export concurrently.
3070 VERIFY0(spa_open(zo->zo_pool, &spa, FTAG));
3071 int error = spa_destroy(zo->zo_pool);
3072 if (error != EBUSY && error != ZFS_ERR_EXPORT_IN_PROGRESS) {
3073 fatal(B_FALSE, "spa_destroy(%s) returned unexpected value %d",
3074 spa->spa_name, error);
3076 spa_close(spa, FTAG);
3078 (void) pthread_rwlock_unlock(&ztest_name_lock);
3082 * Start and then stop the MMP threads to ensure the startup and shutdown code
3083 * works properly. Actual protection and property-related code tested via ZTS.
3085 void
3086 ztest_mmp_enable_disable(ztest_ds_t *zd, uint64_t id)
3088 (void) zd, (void) id;
3089 ztest_shared_opts_t *zo = &ztest_opts;
3090 spa_t *spa = ztest_spa;
3092 if (zo->zo_mmp_test)
3093 return;
3096 * Since enabling MMP involves setting a property, it could not be done
3097 * while the pool is suspended.
3099 if (spa_suspended(spa))
3100 return;
3102 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
3103 mutex_enter(&spa->spa_props_lock);
3105 zfs_multihost_fail_intervals = 0;
3107 if (!spa_multihost(spa)) {
3108 spa->spa_multihost = B_TRUE;
3109 mmp_thread_start(spa);
3112 mutex_exit(&spa->spa_props_lock);
3113 spa_config_exit(spa, SCL_CONFIG, FTAG);
3115 txg_wait_synced(spa_get_dsl(spa), 0);
3116 mmp_signal_all_threads();
3117 txg_wait_synced(spa_get_dsl(spa), 0);
3119 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
3120 mutex_enter(&spa->spa_props_lock);
3122 if (spa_multihost(spa)) {
3123 mmp_thread_stop(spa);
3124 spa->spa_multihost = B_FALSE;
3127 mutex_exit(&spa->spa_props_lock);
3128 spa_config_exit(spa, SCL_CONFIG, FTAG);
3131 static int
3132 ztest_get_raidz_children(spa_t *spa)
3134 (void) spa;
3135 vdev_t *raidvd;
3137 ASSERT(MUTEX_HELD(&ztest_vdev_lock));
3139 if (ztest_opts.zo_raid_do_expand) {
3140 raidvd = ztest_spa->spa_root_vdev->vdev_child[0];
3142 ASSERT(raidvd->vdev_ops == &vdev_raidz_ops);
3144 return (raidvd->vdev_children);
3147 return (ztest_opts.zo_raid_children);
3150 void
3151 ztest_spa_upgrade(ztest_ds_t *zd, uint64_t id)
3153 (void) zd, (void) id;
3154 spa_t *spa;
3155 uint64_t initial_version = SPA_VERSION_INITIAL;
3156 uint64_t raidz_children, version, newversion;
3157 nvlist_t *nvroot, *props;
3158 char *name;
3160 if (ztest_opts.zo_mmp_test)
3161 return;
3163 /* dRAID added after feature flags, skip upgrade test. */
3164 if (strcmp(ztest_opts.zo_raid_type, VDEV_TYPE_DRAID) == 0)
3165 return;
3167 mutex_enter(&ztest_vdev_lock);
3168 name = kmem_asprintf("%s_upgrade", ztest_opts.zo_pool);
3171 * Clean up from previous runs.
3173 (void) spa_destroy(name);
3175 raidz_children = ztest_get_raidz_children(ztest_spa);
3177 nvroot = make_vdev_root(NULL, NULL, name, ztest_opts.zo_vdev_size, 0,
3178 NULL, raidz_children, ztest_opts.zo_mirrors, 1);
3181 * If we're configuring a RAIDZ device then make sure that the
3182 * initial version is capable of supporting that feature.
3184 switch (ztest_opts.zo_raid_parity) {
3185 case 0:
3186 case 1:
3187 initial_version = SPA_VERSION_INITIAL;
3188 break;
3189 case 2:
3190 initial_version = SPA_VERSION_RAIDZ2;
3191 break;
3192 case 3:
3193 initial_version = SPA_VERSION_RAIDZ3;
3194 break;
3198 * Create a pool with a spa version that can be upgraded. Pick
3199 * a value between initial_version and SPA_VERSION_BEFORE_FEATURES.
3201 do {
3202 version = ztest_random_spa_version(initial_version);
3203 } while (version > SPA_VERSION_BEFORE_FEATURES);
3205 props = fnvlist_alloc();
3206 fnvlist_add_uint64(props,
3207 zpool_prop_to_name(ZPOOL_PROP_VERSION), version);
3208 VERIFY0(spa_create(name, nvroot, props, NULL, NULL));
3209 fnvlist_free(nvroot);
3210 fnvlist_free(props);
3212 VERIFY0(spa_open(name, &spa, FTAG));
3213 VERIFY3U(spa_version(spa), ==, version);
3214 newversion = ztest_random_spa_version(version + 1);
3216 if (ztest_opts.zo_verbose >= 4) {
3217 (void) printf("upgrading spa version from "
3218 "%"PRIu64" to %"PRIu64"\n",
3219 version, newversion);
3222 spa_upgrade(spa, newversion);
3223 VERIFY3U(spa_version(spa), >, version);
3224 VERIFY3U(spa_version(spa), ==, fnvlist_lookup_uint64(spa->spa_config,
3225 zpool_prop_to_name(ZPOOL_PROP_VERSION)));
3226 spa_close(spa, FTAG);
3228 kmem_strfree(name);
3229 mutex_exit(&ztest_vdev_lock);
3232 static void
3233 ztest_spa_checkpoint(spa_t *spa)
3235 ASSERT(MUTEX_HELD(&ztest_checkpoint_lock));
3237 int error = spa_checkpoint(spa->spa_name);
3239 switch (error) {
3240 case 0:
3241 case ZFS_ERR_DEVRM_IN_PROGRESS:
3242 case ZFS_ERR_DISCARDING_CHECKPOINT:
3243 case ZFS_ERR_CHECKPOINT_EXISTS:
3244 case ZFS_ERR_RAIDZ_EXPAND_IN_PROGRESS:
3245 break;
3246 case ENOSPC:
3247 ztest_record_enospc(FTAG);
3248 break;
3249 default:
3250 fatal(B_FALSE, "spa_checkpoint(%s) = %d", spa->spa_name, error);
3254 static void
3255 ztest_spa_discard_checkpoint(spa_t *spa)
3257 ASSERT(MUTEX_HELD(&ztest_checkpoint_lock));
3259 int error = spa_checkpoint_discard(spa->spa_name);
3261 switch (error) {
3262 case 0:
3263 case ZFS_ERR_DISCARDING_CHECKPOINT:
3264 case ZFS_ERR_NO_CHECKPOINT:
3265 break;
3266 default:
3267 fatal(B_FALSE, "spa_discard_checkpoint(%s) = %d",
3268 spa->spa_name, error);
3273 void
3274 ztest_spa_checkpoint_create_discard(ztest_ds_t *zd, uint64_t id)
3276 (void) zd, (void) id;
3277 spa_t *spa = ztest_spa;
3279 mutex_enter(&ztest_checkpoint_lock);
3280 if (ztest_random(2) == 0) {
3281 ztest_spa_checkpoint(spa);
3282 } else {
3283 ztest_spa_discard_checkpoint(spa);
3285 mutex_exit(&ztest_checkpoint_lock);
3289 static vdev_t *
3290 vdev_lookup_by_path(vdev_t *vd, const char *path)
3292 vdev_t *mvd;
3293 int c;
3295 if (vd->vdev_path != NULL && strcmp(path, vd->vdev_path) == 0)
3296 return (vd);
3298 for (c = 0; c < vd->vdev_children; c++)
3299 if ((mvd = vdev_lookup_by_path(vd->vdev_child[c], path)) !=
3300 NULL)
3301 return (mvd);
3303 return (NULL);
3306 static int
3307 spa_num_top_vdevs(spa_t *spa)
3309 vdev_t *rvd = spa->spa_root_vdev;
3310 ASSERT3U(spa_config_held(spa, SCL_VDEV, RW_READER), ==, SCL_VDEV);
3311 return (rvd->vdev_children);
3315 * Verify that vdev_add() works as expected.
3317 void
3318 ztest_vdev_add_remove(ztest_ds_t *zd, uint64_t id)
3320 (void) zd, (void) id;
3321 ztest_shared_t *zs = ztest_shared;
3322 spa_t *spa = ztest_spa;
3323 uint64_t leaves;
3324 uint64_t guid;
3325 uint64_t raidz_children;
3327 nvlist_t *nvroot;
3328 int error;
3330 if (ztest_opts.zo_mmp_test)
3331 return;
3333 mutex_enter(&ztest_vdev_lock);
3334 raidz_children = ztest_get_raidz_children(spa);
3335 leaves = MAX(zs->zs_mirrors + zs->zs_splits, 1) * raidz_children;
3337 spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
3339 ztest_shared->zs_vdev_next_leaf = spa_num_top_vdevs(spa) * leaves;
3342 * If we have slogs then remove them 1/4 of the time.
3344 if (spa_has_slogs(spa) && ztest_random(4) == 0) {
3345 metaslab_group_t *mg;
3348 * find the first real slog in log allocation class
3350 mg = spa_log_class(spa)->mc_allocator[0].mca_rotor;
3351 while (!mg->mg_vd->vdev_islog)
3352 mg = mg->mg_next;
3354 guid = mg->mg_vd->vdev_guid;
3356 spa_config_exit(spa, SCL_VDEV, FTAG);
3359 * We have to grab the zs_name_lock as writer to
3360 * prevent a race between removing a slog (dmu_objset_find)
3361 * and destroying a dataset. Removing the slog will
3362 * grab a reference on the dataset which may cause
3363 * dsl_destroy_head() to fail with EBUSY thus
3364 * leaving the dataset in an inconsistent state.
3366 pthread_rwlock_wrlock(&ztest_name_lock);
3367 error = spa_vdev_remove(spa, guid, B_FALSE);
3368 pthread_rwlock_unlock(&ztest_name_lock);
3370 switch (error) {
3371 case 0:
3372 case EEXIST: /* Generic zil_reset() error */
3373 case EBUSY: /* Replay required */
3374 case EACCES: /* Crypto key not loaded */
3375 case ZFS_ERR_CHECKPOINT_EXISTS:
3376 case ZFS_ERR_DISCARDING_CHECKPOINT:
3377 break;
3378 default:
3379 fatal(B_FALSE, "spa_vdev_remove() = %d", error);
3381 } else {
3382 spa_config_exit(spa, SCL_VDEV, FTAG);
3385 * Make 1/4 of the devices be log devices
3387 nvroot = make_vdev_root(NULL, NULL, NULL,
3388 ztest_opts.zo_vdev_size, 0, (ztest_random(4) == 0) ?
3389 "log" : NULL, raidz_children, zs->zs_mirrors,
3392 error = spa_vdev_add(spa, nvroot, B_FALSE);
3393 fnvlist_free(nvroot);
3395 switch (error) {
3396 case 0:
3397 break;
3398 case ENOSPC:
3399 ztest_record_enospc("spa_vdev_add");
3400 break;
3401 default:
3402 fatal(B_FALSE, "spa_vdev_add() = %d", error);
3406 mutex_exit(&ztest_vdev_lock);
3409 void
3410 ztest_vdev_class_add(ztest_ds_t *zd, uint64_t id)
3412 (void) zd, (void) id;
3413 ztest_shared_t *zs = ztest_shared;
3414 spa_t *spa = ztest_spa;
3415 uint64_t leaves;
3416 nvlist_t *nvroot;
3417 uint64_t raidz_children;
3418 const char *class = (ztest_random(2) == 0) ?
3419 VDEV_ALLOC_BIAS_SPECIAL : VDEV_ALLOC_BIAS_DEDUP;
3420 int error;
3423 * By default add a special vdev 50% of the time
3425 if ((ztest_opts.zo_special_vdevs == ZTEST_VDEV_CLASS_OFF) ||
3426 (ztest_opts.zo_special_vdevs == ZTEST_VDEV_CLASS_RND &&
3427 ztest_random(2) == 0)) {
3428 return;
3431 mutex_enter(&ztest_vdev_lock);
3433 /* Only test with mirrors */
3434 if (zs->zs_mirrors < 2) {
3435 mutex_exit(&ztest_vdev_lock);
3436 return;
3439 /* requires feature@allocation_classes */
3440 if (!spa_feature_is_enabled(spa, SPA_FEATURE_ALLOCATION_CLASSES)) {
3441 mutex_exit(&ztest_vdev_lock);
3442 return;
3445 raidz_children = ztest_get_raidz_children(spa);
3446 leaves = MAX(zs->zs_mirrors + zs->zs_splits, 1) * raidz_children;
3448 spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
3449 ztest_shared->zs_vdev_next_leaf = spa_num_top_vdevs(spa) * leaves;
3450 spa_config_exit(spa, SCL_VDEV, FTAG);
3452 nvroot = make_vdev_root(NULL, NULL, NULL, ztest_opts.zo_vdev_size, 0,
3453 class, raidz_children, zs->zs_mirrors, 1);
3455 error = spa_vdev_add(spa, nvroot, B_FALSE);
3456 fnvlist_free(nvroot);
3458 if (error == ENOSPC)
3459 ztest_record_enospc("spa_vdev_add");
3460 else if (error != 0)
3461 fatal(B_FALSE, "spa_vdev_add() = %d", error);
3464 * 50% of the time allow small blocks in the special class
3466 if (error == 0 &&
3467 spa_special_class(spa)->mc_groups == 1 && ztest_random(2) == 0) {
3468 if (ztest_opts.zo_verbose >= 3)
3469 (void) printf("Enabling special VDEV small blocks\n");
3470 error = ztest_dsl_prop_set_uint64(zd->zd_name,
3471 ZFS_PROP_SPECIAL_SMALL_BLOCKS, 32768, B_FALSE);
3472 ASSERT(error == 0 || error == ENOSPC);
3475 mutex_exit(&ztest_vdev_lock);
3477 if (ztest_opts.zo_verbose >= 3) {
3478 metaslab_class_t *mc;
3480 if (strcmp(class, VDEV_ALLOC_BIAS_SPECIAL) == 0)
3481 mc = spa_special_class(spa);
3482 else
3483 mc = spa_dedup_class(spa);
3484 (void) printf("Added a %s mirrored vdev (of %d)\n",
3485 class, (int)mc->mc_groups);
3490 * Verify that adding/removing aux devices (l2arc, hot spare) works as expected.
3492 void
3493 ztest_vdev_aux_add_remove(ztest_ds_t *zd, uint64_t id)
3495 (void) zd, (void) id;
3496 ztest_shared_t *zs = ztest_shared;
3497 spa_t *spa = ztest_spa;
3498 vdev_t *rvd = spa->spa_root_vdev;
3499 spa_aux_vdev_t *sav;
3500 const char *aux;
3501 char *path;
3502 uint64_t guid = 0;
3503 int error, ignore_err = 0;
3505 if (ztest_opts.zo_mmp_test)
3506 return;
3508 path = umem_alloc(MAXPATHLEN, UMEM_NOFAIL);
3510 if (ztest_random(2) == 0) {
3511 sav = &spa->spa_spares;
3512 aux = ZPOOL_CONFIG_SPARES;
3513 } else {
3514 sav = &spa->spa_l2cache;
3515 aux = ZPOOL_CONFIG_L2CACHE;
3518 mutex_enter(&ztest_vdev_lock);
3520 spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
3522 if (sav->sav_count != 0 && ztest_random(4) == 0) {
3524 * Pick a random device to remove.
3526 vdev_t *svd = sav->sav_vdevs[ztest_random(sav->sav_count)];
3528 /* dRAID spares cannot be removed; try anyways to see ENOTSUP */
3529 if (strstr(svd->vdev_path, VDEV_TYPE_DRAID) != NULL)
3530 ignore_err = ENOTSUP;
3532 guid = svd->vdev_guid;
3533 } else {
3535 * Find an unused device we can add.
3537 zs->zs_vdev_aux = 0;
3538 for (;;) {
3539 int c;
3540 (void) snprintf(path, MAXPATHLEN, ztest_aux_template,
3541 ztest_opts.zo_dir, ztest_opts.zo_pool, aux,
3542 zs->zs_vdev_aux);
3543 for (c = 0; c < sav->sav_count; c++)
3544 if (strcmp(sav->sav_vdevs[c]->vdev_path,
3545 path) == 0)
3546 break;
3547 if (c == sav->sav_count &&
3548 vdev_lookup_by_path(rvd, path) == NULL)
3549 break;
3550 zs->zs_vdev_aux++;
3554 spa_config_exit(spa, SCL_VDEV, FTAG);
3556 if (guid == 0) {
3558 * Add a new device.
3560 nvlist_t *nvroot = make_vdev_root(NULL, aux, NULL,
3561 (ztest_opts.zo_vdev_size * 5) / 4, 0, NULL, 0, 0, 1);
3562 error = spa_vdev_add(spa, nvroot, B_FALSE);
3564 switch (error) {
3565 case 0:
3566 break;
3567 default:
3568 fatal(B_FALSE, "spa_vdev_add(%p) = %d", nvroot, error);
3570 fnvlist_free(nvroot);
3571 } else {
3573 * Remove an existing device. Sometimes, dirty its
3574 * vdev state first to make sure we handle removal
3575 * of devices that have pending state changes.
3577 if (ztest_random(2) == 0)
3578 (void) vdev_online(spa, guid, 0, NULL);
3580 error = spa_vdev_remove(spa, guid, B_FALSE);
3582 switch (error) {
3583 case 0:
3584 case EBUSY:
3585 case ZFS_ERR_CHECKPOINT_EXISTS:
3586 case ZFS_ERR_DISCARDING_CHECKPOINT:
3587 break;
3588 default:
3589 if (error != ignore_err)
3590 fatal(B_FALSE,
3591 "spa_vdev_remove(%"PRIu64") = %d",
3592 guid, error);
3596 mutex_exit(&ztest_vdev_lock);
3598 umem_free(path, MAXPATHLEN);
3602 * split a pool if it has mirror tlvdevs
3604 void
3605 ztest_split_pool(ztest_ds_t *zd, uint64_t id)
3607 (void) zd, (void) id;
3608 ztest_shared_t *zs = ztest_shared;
3609 spa_t *spa = ztest_spa;
3610 vdev_t *rvd = spa->spa_root_vdev;
3611 nvlist_t *tree, **child, *config, *split, **schild;
3612 uint_t c, children, schildren = 0, lastlogid = 0;
3613 int error = 0;
3615 if (ztest_opts.zo_mmp_test)
3616 return;
3618 mutex_enter(&ztest_vdev_lock);
3620 /* ensure we have a usable config; mirrors of raidz aren't supported */
3621 if (zs->zs_mirrors < 3 || ztest_opts.zo_raid_children > 1) {
3622 mutex_exit(&ztest_vdev_lock);
3623 return;
3626 /* clean up the old pool, if any */
3627 (void) spa_destroy("splitp");
3629 spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
3631 /* generate a config from the existing config */
3632 mutex_enter(&spa->spa_props_lock);
3633 tree = fnvlist_lookup_nvlist(spa->spa_config, ZPOOL_CONFIG_VDEV_TREE);
3634 mutex_exit(&spa->spa_props_lock);
3636 VERIFY0(nvlist_lookup_nvlist_array(tree, ZPOOL_CONFIG_CHILDREN,
3637 &child, &children));
3639 schild = umem_alloc(rvd->vdev_children * sizeof (nvlist_t *),
3640 UMEM_NOFAIL);
3641 for (c = 0; c < children; c++) {
3642 vdev_t *tvd = rvd->vdev_child[c];
3643 nvlist_t **mchild;
3644 uint_t mchildren;
3646 if (tvd->vdev_islog || tvd->vdev_ops == &vdev_hole_ops) {
3647 schild[schildren] = fnvlist_alloc();
3648 fnvlist_add_string(schild[schildren],
3649 ZPOOL_CONFIG_TYPE, VDEV_TYPE_HOLE);
3650 fnvlist_add_uint64(schild[schildren],
3651 ZPOOL_CONFIG_IS_HOLE, 1);
3652 if (lastlogid == 0)
3653 lastlogid = schildren;
3654 ++schildren;
3655 continue;
3657 lastlogid = 0;
3658 VERIFY0(nvlist_lookup_nvlist_array(child[c],
3659 ZPOOL_CONFIG_CHILDREN, &mchild, &mchildren));
3660 schild[schildren++] = fnvlist_dup(mchild[0]);
3663 /* OK, create a config that can be used to split */
3664 split = fnvlist_alloc();
3665 fnvlist_add_string(split, ZPOOL_CONFIG_TYPE, VDEV_TYPE_ROOT);
3666 fnvlist_add_nvlist_array(split, ZPOOL_CONFIG_CHILDREN,
3667 (const nvlist_t **)schild, lastlogid != 0 ? lastlogid : schildren);
3669 config = fnvlist_alloc();
3670 fnvlist_add_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, split);
3672 for (c = 0; c < schildren; c++)
3673 fnvlist_free(schild[c]);
3674 umem_free(schild, rvd->vdev_children * sizeof (nvlist_t *));
3675 fnvlist_free(split);
3677 spa_config_exit(spa, SCL_VDEV, FTAG);
3679 (void) pthread_rwlock_wrlock(&ztest_name_lock);
3680 error = spa_vdev_split_mirror(spa, "splitp", config, NULL, B_FALSE);
3681 (void) pthread_rwlock_unlock(&ztest_name_lock);
3683 fnvlist_free(config);
3685 if (error == 0) {
3686 (void) printf("successful split - results:\n");
3687 mutex_enter(&spa_namespace_lock);
3688 show_pool_stats(spa);
3689 show_pool_stats(spa_lookup("splitp"));
3690 mutex_exit(&spa_namespace_lock);
3691 ++zs->zs_splits;
3692 --zs->zs_mirrors;
3694 mutex_exit(&ztest_vdev_lock);
3698 * Verify that we can attach and detach devices.
3700 void
3701 ztest_vdev_attach_detach(ztest_ds_t *zd, uint64_t id)
3703 (void) zd, (void) id;
3704 ztest_shared_t *zs = ztest_shared;
3705 spa_t *spa = ztest_spa;
3706 spa_aux_vdev_t *sav = &spa->spa_spares;
3707 vdev_t *rvd = spa->spa_root_vdev;
3708 vdev_t *oldvd, *newvd, *pvd;
3709 nvlist_t *root;
3710 uint64_t leaves;
3711 uint64_t leaf, top;
3712 uint64_t ashift = ztest_get_ashift();
3713 uint64_t oldguid, pguid;
3714 uint64_t oldsize, newsize;
3715 uint64_t raidz_children;
3716 char *oldpath, *newpath;
3717 int replacing;
3718 int oldvd_has_siblings = B_FALSE;
3719 int newvd_is_spare = B_FALSE;
3720 int newvd_is_dspare = B_FALSE;
3721 int oldvd_is_log;
3722 int oldvd_is_special;
3723 int error, expected_error;
3725 if (ztest_opts.zo_mmp_test)
3726 return;
3728 oldpath = umem_alloc(MAXPATHLEN, UMEM_NOFAIL);
3729 newpath = umem_alloc(MAXPATHLEN, UMEM_NOFAIL);
3731 mutex_enter(&ztest_vdev_lock);
3732 raidz_children = ztest_get_raidz_children(spa);
3733 leaves = MAX(zs->zs_mirrors, 1) * raidz_children;
3735 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3738 * If a vdev is in the process of being removed, its removal may
3739 * finish while we are in progress, leading to an unexpected error
3740 * value. Don't bother trying to attach while we are in the middle
3741 * of removal.
3743 if (ztest_device_removal_active) {
3744 spa_config_exit(spa, SCL_ALL, FTAG);
3745 goto out;
3749 * RAIDZ leaf VDEV mirrors are not currently supported while a
3750 * RAIDZ expansion is in progress.
3752 if (ztest_opts.zo_raid_do_expand) {
3753 spa_config_exit(spa, SCL_ALL, FTAG);
3754 goto out;
3758 * Decide whether to do an attach or a replace.
3760 replacing = ztest_random(2);
3763 * Pick a random top-level vdev.
3765 top = ztest_random_vdev_top(spa, B_TRUE);
3768 * Pick a random leaf within it.
3770 leaf = ztest_random(leaves);
3773 * Locate this vdev.
3775 oldvd = rvd->vdev_child[top];
3777 /* pick a child from the mirror */
3778 if (zs->zs_mirrors >= 1) {
3779 ASSERT3P(oldvd->vdev_ops, ==, &vdev_mirror_ops);
3780 ASSERT3U(oldvd->vdev_children, >=, zs->zs_mirrors);
3781 oldvd = oldvd->vdev_child[leaf / raidz_children];
3784 /* pick a child out of the raidz group */
3785 if (ztest_opts.zo_raid_children > 1) {
3786 if (strcmp(oldvd->vdev_ops->vdev_op_type, "raidz") == 0)
3787 ASSERT3P(oldvd->vdev_ops, ==, &vdev_raidz_ops);
3788 else
3789 ASSERT3P(oldvd->vdev_ops, ==, &vdev_draid_ops);
3790 oldvd = oldvd->vdev_child[leaf % raidz_children];
3794 * If we're already doing an attach or replace, oldvd may be a
3795 * mirror vdev -- in which case, pick a random child.
3797 while (oldvd->vdev_children != 0) {
3798 oldvd_has_siblings = B_TRUE;
3799 ASSERT3U(oldvd->vdev_children, >=, 2);
3800 oldvd = oldvd->vdev_child[ztest_random(oldvd->vdev_children)];
3803 oldguid = oldvd->vdev_guid;
3804 oldsize = vdev_get_min_asize(oldvd);
3805 oldvd_is_log = oldvd->vdev_top->vdev_islog;
3806 oldvd_is_special =
3807 oldvd->vdev_top->vdev_alloc_bias == VDEV_BIAS_SPECIAL ||
3808 oldvd->vdev_top->vdev_alloc_bias == VDEV_BIAS_DEDUP;
3809 (void) strlcpy(oldpath, oldvd->vdev_path, MAXPATHLEN);
3810 pvd = oldvd->vdev_parent;
3811 pguid = pvd->vdev_guid;
3814 * If oldvd has siblings, then half of the time, detach it. Prior
3815 * to the detach the pool is scrubbed in order to prevent creating
3816 * unrepairable blocks as a result of the data corruption injection.
3818 if (oldvd_has_siblings && ztest_random(2) == 0) {
3819 spa_config_exit(spa, SCL_ALL, FTAG);
3821 error = ztest_scrub_impl(spa);
3822 if (error)
3823 goto out;
3825 error = spa_vdev_detach(spa, oldguid, pguid, B_FALSE);
3826 if (error != 0 && error != ENODEV && error != EBUSY &&
3827 error != ENOTSUP && error != ZFS_ERR_CHECKPOINT_EXISTS &&
3828 error != ZFS_ERR_DISCARDING_CHECKPOINT)
3829 fatal(B_FALSE, "detach (%s) returned %d",
3830 oldpath, error);
3831 goto out;
3835 * For the new vdev, choose with equal probability between the two
3836 * standard paths (ending in either 'a' or 'b') or a random hot spare.
3838 if (sav->sav_count != 0 && ztest_random(3) == 0) {
3839 newvd = sav->sav_vdevs[ztest_random(sav->sav_count)];
3840 newvd_is_spare = B_TRUE;
3842 if (newvd->vdev_ops == &vdev_draid_spare_ops)
3843 newvd_is_dspare = B_TRUE;
3845 (void) strlcpy(newpath, newvd->vdev_path, MAXPATHLEN);
3846 } else {
3847 (void) snprintf(newpath, MAXPATHLEN, ztest_dev_template,
3848 ztest_opts.zo_dir, ztest_opts.zo_pool,
3849 top * leaves + leaf);
3850 if (ztest_random(2) == 0)
3851 newpath[strlen(newpath) - 1] = 'b';
3852 newvd = vdev_lookup_by_path(rvd, newpath);
3855 if (newvd) {
3857 * Reopen to ensure the vdev's asize field isn't stale.
3859 vdev_reopen(newvd);
3860 newsize = vdev_get_min_asize(newvd);
3861 } else {
3863 * Make newsize a little bigger or smaller than oldsize.
3864 * If it's smaller, the attach should fail.
3865 * If it's larger, and we're doing a replace,
3866 * we should get dynamic LUN growth when we're done.
3868 newsize = 10 * oldsize / (9 + ztest_random(3));
3872 * If pvd is not a mirror or root, the attach should fail with ENOTSUP,
3873 * unless it's a replace; in that case any non-replacing parent is OK.
3875 * If newvd is already part of the pool, it should fail with EBUSY.
3877 * If newvd is too small, it should fail with EOVERFLOW.
3879 * If newvd is a distributed spare and it's being attached to a
3880 * dRAID which is not its parent it should fail with EINVAL.
3882 if (pvd->vdev_ops != &vdev_mirror_ops &&
3883 pvd->vdev_ops != &vdev_root_ops && (!replacing ||
3884 pvd->vdev_ops == &vdev_replacing_ops ||
3885 pvd->vdev_ops == &vdev_spare_ops))
3886 expected_error = ENOTSUP;
3887 else if (newvd_is_spare &&
3888 (!replacing || oldvd_is_log || oldvd_is_special))
3889 expected_error = ENOTSUP;
3890 else if (newvd == oldvd)
3891 expected_error = replacing ? 0 : EBUSY;
3892 else if (vdev_lookup_by_path(rvd, newpath) != NULL)
3893 expected_error = EBUSY;
3894 else if (!newvd_is_dspare && newsize < oldsize)
3895 expected_error = EOVERFLOW;
3896 else if (ashift > oldvd->vdev_top->vdev_ashift)
3897 expected_error = EDOM;
3898 else if (newvd_is_dspare && pvd != vdev_draid_spare_get_parent(newvd))
3899 expected_error = EINVAL;
3900 else
3901 expected_error = 0;
3903 spa_config_exit(spa, SCL_ALL, FTAG);
3906 * Build the nvlist describing newpath.
3908 root = make_vdev_root(newpath, NULL, NULL, newvd == NULL ? newsize : 0,
3909 ashift, NULL, 0, 0, 1);
3912 * When supported select either a healing or sequential resilver.
3914 boolean_t rebuilding = B_FALSE;
3915 if (pvd->vdev_ops == &vdev_mirror_ops ||
3916 pvd->vdev_ops == &vdev_root_ops) {
3917 rebuilding = !!ztest_random(2);
3920 error = spa_vdev_attach(spa, oldguid, root, replacing, rebuilding);
3922 fnvlist_free(root);
3925 * If our parent was the replacing vdev, but the replace completed,
3926 * then instead of failing with ENOTSUP we may either succeed,
3927 * fail with ENODEV, or fail with EOVERFLOW.
3929 if (expected_error == ENOTSUP &&
3930 (error == 0 || error == ENODEV || error == EOVERFLOW))
3931 expected_error = error;
3934 * If someone grew the LUN, the replacement may be too small.
3936 if (error == EOVERFLOW || error == EBUSY)
3937 expected_error = error;
3939 if (error == ZFS_ERR_CHECKPOINT_EXISTS ||
3940 error == ZFS_ERR_DISCARDING_CHECKPOINT ||
3941 error == ZFS_ERR_RESILVER_IN_PROGRESS ||
3942 error == ZFS_ERR_REBUILD_IN_PROGRESS)
3943 expected_error = error;
3945 if (error != expected_error && expected_error != EBUSY) {
3946 fatal(B_FALSE, "attach (%s %"PRIu64", %s %"PRIu64", %d) "
3947 "returned %d, expected %d",
3948 oldpath, oldsize, newpath,
3949 newsize, replacing, error, expected_error);
3951 out:
3952 mutex_exit(&ztest_vdev_lock);
3954 umem_free(oldpath, MAXPATHLEN);
3955 umem_free(newpath, MAXPATHLEN);
3958 static void
3959 raidz_scratch_verify(void)
3961 spa_t *spa;
3962 uint64_t write_size, logical_size, offset;
3963 raidz_reflow_scratch_state_t state;
3964 vdev_raidz_expand_t *vre;
3965 vdev_t *raidvd;
3967 ASSERT(raidz_expand_pause_point == RAIDZ_EXPAND_PAUSE_NONE);
3969 if (ztest_scratch_state->zs_raidz_scratch_verify_pause == 0)
3970 return;
3972 kernel_init(SPA_MODE_READ);
3974 mutex_enter(&spa_namespace_lock);
3975 spa = spa_lookup(ztest_opts.zo_pool);
3976 ASSERT(spa);
3977 spa->spa_import_flags |= ZFS_IMPORT_SKIP_MMP;
3978 mutex_exit(&spa_namespace_lock);
3980 VERIFY0(spa_open(ztest_opts.zo_pool, &spa, FTAG));
3982 ASSERT3U(RRSS_GET_OFFSET(&spa->spa_uberblock), !=, UINT64_MAX);
3984 mutex_enter(&ztest_vdev_lock);
3986 spa_config_enter(spa, SCL_ALL, FTAG, RW_READER);
3988 vre = spa->spa_raidz_expand;
3989 if (vre == NULL)
3990 goto out;
3992 raidvd = vdev_lookup_top(spa, vre->vre_vdev_id);
3993 offset = RRSS_GET_OFFSET(&spa->spa_uberblock);
3994 state = RRSS_GET_STATE(&spa->spa_uberblock);
3995 write_size = P2ALIGN_TYPED(VDEV_BOOT_SIZE, 1 << raidvd->vdev_ashift,
3996 uint64_t);
3997 logical_size = write_size * raidvd->vdev_children;
3999 switch (state) {
4001 * Initial state of reflow process. RAIDZ expansion was
4002 * requested by user, but scratch object was not created.
4004 case RRSS_SCRATCH_NOT_IN_USE:
4005 ASSERT3U(offset, ==, 0);
4006 break;
4009 * Scratch object was synced and stored in boot area.
4011 case RRSS_SCRATCH_VALID:
4014 * Scratch object was synced back to raidz start offset,
4015 * raidz is ready for sector by sector reflow process.
4017 case RRSS_SCRATCH_INVALID_SYNCED:
4020 * Scratch object was synced back to raidz start offset
4021 * on zpool importing, raidz is ready for sector by sector
4022 * reflow process.
4024 case RRSS_SCRATCH_INVALID_SYNCED_ON_IMPORT:
4025 ASSERT3U(offset, ==, logical_size);
4026 break;
4029 * Sector by sector reflow process started.
4031 case RRSS_SCRATCH_INVALID_SYNCED_REFLOW:
4032 ASSERT3U(offset, >=, logical_size);
4033 break;
4036 out:
4037 spa_config_exit(spa, SCL_ALL, FTAG);
4039 mutex_exit(&ztest_vdev_lock);
4041 ztest_scratch_state->zs_raidz_scratch_verify_pause = 0;
4043 spa_close(spa, FTAG);
4044 kernel_fini();
4047 static void
4048 ztest_scratch_thread(void *arg)
4050 (void) arg;
4052 /* wait up to 10 seconds */
4053 for (int t = 100; t > 0; t -= 1) {
4054 if (raidz_expand_pause_point == RAIDZ_EXPAND_PAUSE_NONE)
4055 thread_exit();
4057 (void) poll(NULL, 0, 100);
4060 /* killed when the scratch area progress reached a certain point */
4061 ztest_kill(ztest_shared);
4065 * Verify that we can attach raidz device.
4067 void
4068 ztest_vdev_raidz_attach(ztest_ds_t *zd, uint64_t id)
4070 (void) zd, (void) id;
4071 ztest_shared_t *zs = ztest_shared;
4072 spa_t *spa = ztest_spa;
4073 uint64_t leaves, raidz_children, newsize, ashift = ztest_get_ashift();
4074 kthread_t *scratch_thread = NULL;
4075 vdev_t *newvd, *pvd;
4076 nvlist_t *root;
4077 char *newpath = umem_alloc(MAXPATHLEN, UMEM_NOFAIL);
4078 int error, expected_error = 0;
4080 mutex_enter(&ztest_vdev_lock);
4082 spa_config_enter(spa, SCL_ALL, FTAG, RW_READER);
4084 /* Only allow attach when raid-kind = 'eraidz' */
4085 if (!ztest_opts.zo_raid_do_expand) {
4086 spa_config_exit(spa, SCL_ALL, FTAG);
4087 goto out;
4090 if (ztest_opts.zo_mmp_test) {
4091 spa_config_exit(spa, SCL_ALL, FTAG);
4092 goto out;
4095 if (ztest_device_removal_active) {
4096 spa_config_exit(spa, SCL_ALL, FTAG);
4097 goto out;
4100 pvd = vdev_lookup_top(spa, 0);
4102 ASSERT(pvd->vdev_ops == &vdev_raidz_ops);
4105 * Get size of a child of the raidz group,
4106 * make sure device is a bit bigger
4108 newvd = pvd->vdev_child[ztest_random(pvd->vdev_children)];
4109 newsize = 10 * vdev_get_min_asize(newvd) / (9 + ztest_random(2));
4112 * Get next attached leaf id
4114 raidz_children = ztest_get_raidz_children(spa);
4115 leaves = MAX(zs->zs_mirrors + zs->zs_splits, 1) * raidz_children;
4116 zs->zs_vdev_next_leaf = spa_num_top_vdevs(spa) * leaves;
4118 if (spa->spa_raidz_expand)
4119 expected_error = ZFS_ERR_RAIDZ_EXPAND_IN_PROGRESS;
4121 spa_config_exit(spa, SCL_ALL, FTAG);
4124 * Path to vdev to be attached
4126 (void) snprintf(newpath, MAXPATHLEN, ztest_dev_template,
4127 ztest_opts.zo_dir, ztest_opts.zo_pool, zs->zs_vdev_next_leaf);
4130 * Build the nvlist describing newpath.
4132 root = make_vdev_root(newpath, NULL, NULL, newsize, ashift, NULL,
4133 0, 0, 1);
4136 * 50% of the time, set raidz_expand_pause_point to cause
4137 * raidz_reflow_scratch_sync() to pause at a certain point and
4138 * then kill the test after 10 seconds so raidz_scratch_verify()
4139 * can confirm consistency when the pool is imported.
4141 if (ztest_random(2) == 0 && expected_error == 0) {
4142 raidz_expand_pause_point =
4143 ztest_random(RAIDZ_EXPAND_PAUSE_SCRATCH_POST_REFLOW_2) + 1;
4144 scratch_thread = thread_create(NULL, 0, ztest_scratch_thread,
4145 ztest_shared, 0, NULL, TS_RUN | TS_JOINABLE, defclsyspri);
4148 error = spa_vdev_attach(spa, pvd->vdev_guid, root, B_FALSE, B_FALSE);
4150 nvlist_free(root);
4152 if (error == EOVERFLOW || error == ENXIO ||
4153 error == ZFS_ERR_CHECKPOINT_EXISTS ||
4154 error == ZFS_ERR_DISCARDING_CHECKPOINT)
4155 expected_error = error;
4157 if (error != 0 && error != expected_error) {
4158 fatal(0, "raidz attach (%s %"PRIu64") returned %d, expected %d",
4159 newpath, newsize, error, expected_error);
4162 if (raidz_expand_pause_point) {
4163 if (error != 0) {
4165 * Do not verify scratch object in case of error
4166 * returned by vdev attaching.
4168 raidz_expand_pause_point = RAIDZ_EXPAND_PAUSE_NONE;
4171 VERIFY0(thread_join(scratch_thread));
4173 out:
4174 mutex_exit(&ztest_vdev_lock);
4176 umem_free(newpath, MAXPATHLEN);
4179 void
4180 ztest_device_removal(ztest_ds_t *zd, uint64_t id)
4182 (void) zd, (void) id;
4183 spa_t *spa = ztest_spa;
4184 vdev_t *vd;
4185 uint64_t guid;
4186 int error;
4188 mutex_enter(&ztest_vdev_lock);
4190 if (ztest_device_removal_active) {
4191 mutex_exit(&ztest_vdev_lock);
4192 return;
4196 * Remove a random top-level vdev and wait for removal to finish.
4198 spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
4199 vd = vdev_lookup_top(spa, ztest_random_vdev_top(spa, B_FALSE));
4200 guid = vd->vdev_guid;
4201 spa_config_exit(spa, SCL_VDEV, FTAG);
4203 error = spa_vdev_remove(spa, guid, B_FALSE);
4204 if (error == 0) {
4205 ztest_device_removal_active = B_TRUE;
4206 mutex_exit(&ztest_vdev_lock);
4209 * spa->spa_vdev_removal is created in a sync task that
4210 * is initiated via dsl_sync_task_nowait(). Since the
4211 * task may not run before spa_vdev_remove() returns, we
4212 * must wait at least 1 txg to ensure that the removal
4213 * struct has been created.
4215 txg_wait_synced(spa_get_dsl(spa), 0);
4217 while (spa->spa_removing_phys.sr_state == DSS_SCANNING)
4218 txg_wait_synced(spa_get_dsl(spa), 0);
4219 } else {
4220 mutex_exit(&ztest_vdev_lock);
4221 return;
4225 * The pool needs to be scrubbed after completing device removal.
4226 * Failure to do so may result in checksum errors due to the
4227 * strategy employed by ztest_fault_inject() when selecting which
4228 * offset are redundant and can be damaged.
4230 error = spa_scan(spa, POOL_SCAN_SCRUB);
4231 if (error == 0) {
4232 while (dsl_scan_scrubbing(spa_get_dsl(spa)))
4233 txg_wait_synced(spa_get_dsl(spa), 0);
4236 mutex_enter(&ztest_vdev_lock);
4237 ztest_device_removal_active = B_FALSE;
4238 mutex_exit(&ztest_vdev_lock);
4242 * Callback function which expands the physical size of the vdev.
4244 static vdev_t *
4245 grow_vdev(vdev_t *vd, void *arg)
4247 spa_t *spa __maybe_unused = vd->vdev_spa;
4248 size_t *newsize = arg;
4249 size_t fsize;
4250 int fd;
4252 ASSERT3S(spa_config_held(spa, SCL_STATE, RW_READER), ==, SCL_STATE);
4253 ASSERT(vd->vdev_ops->vdev_op_leaf);
4255 if ((fd = open(vd->vdev_path, O_RDWR)) == -1)
4256 return (vd);
4258 fsize = lseek(fd, 0, SEEK_END);
4259 VERIFY0(ftruncate(fd, *newsize));
4261 if (ztest_opts.zo_verbose >= 6) {
4262 (void) printf("%s grew from %lu to %lu bytes\n",
4263 vd->vdev_path, (ulong_t)fsize, (ulong_t)*newsize);
4265 (void) close(fd);
4266 return (NULL);
4270 * Callback function which expands a given vdev by calling vdev_online().
4272 static vdev_t *
4273 online_vdev(vdev_t *vd, void *arg)
4275 (void) arg;
4276 spa_t *spa = vd->vdev_spa;
4277 vdev_t *tvd = vd->vdev_top;
4278 uint64_t guid = vd->vdev_guid;
4279 uint64_t generation = spa->spa_config_generation + 1;
4280 vdev_state_t newstate = VDEV_STATE_UNKNOWN;
4281 int error;
4283 ASSERT3S(spa_config_held(spa, SCL_STATE, RW_READER), ==, SCL_STATE);
4284 ASSERT(vd->vdev_ops->vdev_op_leaf);
4286 /* Calling vdev_online will initialize the new metaslabs */
4287 spa_config_exit(spa, SCL_STATE, spa);
4288 error = vdev_online(spa, guid, ZFS_ONLINE_EXPAND, &newstate);
4289 spa_config_enter(spa, SCL_STATE, spa, RW_READER);
4292 * If vdev_online returned an error or the underlying vdev_open
4293 * failed then we abort the expand. The only way to know that
4294 * vdev_open fails is by checking the returned newstate.
4296 if (error || newstate != VDEV_STATE_HEALTHY) {
4297 if (ztest_opts.zo_verbose >= 5) {
4298 (void) printf("Unable to expand vdev, state %u, "
4299 "error %d\n", newstate, error);
4301 return (vd);
4303 ASSERT3U(newstate, ==, VDEV_STATE_HEALTHY);
4306 * Since we dropped the lock we need to ensure that we're
4307 * still talking to the original vdev. It's possible this
4308 * vdev may have been detached/replaced while we were
4309 * trying to online it.
4311 if (generation != spa->spa_config_generation) {
4312 if (ztest_opts.zo_verbose >= 5) {
4313 (void) printf("vdev configuration has changed, "
4314 "guid %"PRIu64", state %"PRIu64", "
4315 "expected gen %"PRIu64", got gen %"PRIu64"\n",
4316 guid,
4317 tvd->vdev_state,
4318 generation,
4319 spa->spa_config_generation);
4321 return (vd);
4323 return (NULL);
4327 * Traverse the vdev tree calling the supplied function.
4328 * We continue to walk the tree until we either have walked all
4329 * children or we receive a non-NULL return from the callback.
4330 * If a NULL callback is passed, then we just return back the first
4331 * leaf vdev we encounter.
4333 static vdev_t *
4334 vdev_walk_tree(vdev_t *vd, vdev_t *(*func)(vdev_t *, void *), void *arg)
4336 uint_t c;
4338 if (vd->vdev_ops->vdev_op_leaf) {
4339 if (func == NULL)
4340 return (vd);
4341 else
4342 return (func(vd, arg));
4345 for (c = 0; c < vd->vdev_children; c++) {
4346 vdev_t *cvd = vd->vdev_child[c];
4347 if ((cvd = vdev_walk_tree(cvd, func, arg)) != NULL)
4348 return (cvd);
4350 return (NULL);
4354 * Verify that dynamic LUN growth works as expected.
4356 void
4357 ztest_vdev_LUN_growth(ztest_ds_t *zd, uint64_t id)
4359 (void) zd, (void) id;
4360 spa_t *spa = ztest_spa;
4361 vdev_t *vd, *tvd;
4362 metaslab_class_t *mc;
4363 metaslab_group_t *mg;
4364 size_t psize, newsize;
4365 uint64_t top;
4366 uint64_t old_class_space, new_class_space, old_ms_count, new_ms_count;
4368 mutex_enter(&ztest_checkpoint_lock);
4369 mutex_enter(&ztest_vdev_lock);
4370 spa_config_enter(spa, SCL_STATE, spa, RW_READER);
4373 * If there is a vdev removal in progress, it could complete while
4374 * we are running, in which case we would not be able to verify
4375 * that the metaslab_class space increased (because it decreases
4376 * when the device removal completes).
4378 if (ztest_device_removal_active) {
4379 spa_config_exit(spa, SCL_STATE, spa);
4380 mutex_exit(&ztest_vdev_lock);
4381 mutex_exit(&ztest_checkpoint_lock);
4382 return;
4386 * If we are under raidz expansion, the test can failed because the
4387 * metaslabs count will not increase immediately after the vdev is
4388 * expanded. It will happen only after raidz expansion completion.
4390 if (spa->spa_raidz_expand) {
4391 spa_config_exit(spa, SCL_STATE, spa);
4392 mutex_exit(&ztest_vdev_lock);
4393 mutex_exit(&ztest_checkpoint_lock);
4394 return;
4397 top = ztest_random_vdev_top(spa, B_TRUE);
4399 tvd = spa->spa_root_vdev->vdev_child[top];
4400 mg = tvd->vdev_mg;
4401 mc = mg->mg_class;
4402 old_ms_count = tvd->vdev_ms_count;
4403 old_class_space = metaslab_class_get_space(mc);
4406 * Determine the size of the first leaf vdev associated with
4407 * our top-level device.
4409 vd = vdev_walk_tree(tvd, NULL, NULL);
4410 ASSERT3P(vd, !=, NULL);
4411 ASSERT(vd->vdev_ops->vdev_op_leaf);
4413 psize = vd->vdev_psize;
4416 * We only try to expand the vdev if it's healthy, less than 4x its
4417 * original size, and it has a valid psize.
4419 if (tvd->vdev_state != VDEV_STATE_HEALTHY ||
4420 psize == 0 || psize >= 4 * ztest_opts.zo_vdev_size) {
4421 spa_config_exit(spa, SCL_STATE, spa);
4422 mutex_exit(&ztest_vdev_lock);
4423 mutex_exit(&ztest_checkpoint_lock);
4424 return;
4426 ASSERT3U(psize, >, 0);
4427 newsize = psize + MAX(psize / 8, SPA_MAXBLOCKSIZE);
4428 ASSERT3U(newsize, >, psize);
4430 if (ztest_opts.zo_verbose >= 6) {
4431 (void) printf("Expanding LUN %s from %lu to %lu\n",
4432 vd->vdev_path, (ulong_t)psize, (ulong_t)newsize);
4436 * Growing the vdev is a two step process:
4437 * 1). expand the physical size (i.e. relabel)
4438 * 2). online the vdev to create the new metaslabs
4440 if (vdev_walk_tree(tvd, grow_vdev, &newsize) != NULL ||
4441 vdev_walk_tree(tvd, online_vdev, NULL) != NULL ||
4442 tvd->vdev_state != VDEV_STATE_HEALTHY) {
4443 if (ztest_opts.zo_verbose >= 5) {
4444 (void) printf("Could not expand LUN because "
4445 "the vdev configuration changed.\n");
4447 spa_config_exit(spa, SCL_STATE, spa);
4448 mutex_exit(&ztest_vdev_lock);
4449 mutex_exit(&ztest_checkpoint_lock);
4450 return;
4453 spa_config_exit(spa, SCL_STATE, spa);
4456 * Expanding the LUN will update the config asynchronously,
4457 * thus we must wait for the async thread to complete any
4458 * pending tasks before proceeding.
4460 for (;;) {
4461 boolean_t done;
4462 mutex_enter(&spa->spa_async_lock);
4463 done = (spa->spa_async_thread == NULL && !spa->spa_async_tasks);
4464 mutex_exit(&spa->spa_async_lock);
4465 if (done)
4466 break;
4467 txg_wait_synced(spa_get_dsl(spa), 0);
4468 (void) poll(NULL, 0, 100);
4471 spa_config_enter(spa, SCL_STATE, spa, RW_READER);
4473 tvd = spa->spa_root_vdev->vdev_child[top];
4474 new_ms_count = tvd->vdev_ms_count;
4475 new_class_space = metaslab_class_get_space(mc);
4477 if (tvd->vdev_mg != mg || mg->mg_class != mc) {
4478 if (ztest_opts.zo_verbose >= 5) {
4479 (void) printf("Could not verify LUN expansion due to "
4480 "intervening vdev offline or remove.\n");
4482 spa_config_exit(spa, SCL_STATE, spa);
4483 mutex_exit(&ztest_vdev_lock);
4484 mutex_exit(&ztest_checkpoint_lock);
4485 return;
4489 * Make sure we were able to grow the vdev.
4491 if (new_ms_count <= old_ms_count) {
4492 fatal(B_FALSE,
4493 "LUN expansion failed: ms_count %"PRIu64" < %"PRIu64"\n",
4494 old_ms_count, new_ms_count);
4498 * Make sure we were able to grow the pool.
4500 if (new_class_space <= old_class_space) {
4501 fatal(B_FALSE,
4502 "LUN expansion failed: class_space %"PRIu64" < %"PRIu64"\n",
4503 old_class_space, new_class_space);
4506 if (ztest_opts.zo_verbose >= 5) {
4507 char oldnumbuf[NN_NUMBUF_SZ], newnumbuf[NN_NUMBUF_SZ];
4509 nicenum(old_class_space, oldnumbuf, sizeof (oldnumbuf));
4510 nicenum(new_class_space, newnumbuf, sizeof (newnumbuf));
4511 (void) printf("%s grew from %s to %s\n",
4512 spa->spa_name, oldnumbuf, newnumbuf);
4515 spa_config_exit(spa, SCL_STATE, spa);
4516 mutex_exit(&ztest_vdev_lock);
4517 mutex_exit(&ztest_checkpoint_lock);
4521 * Verify that dmu_objset_{create,destroy,open,close} work as expected.
4523 static void
4524 ztest_objset_create_cb(objset_t *os, void *arg, cred_t *cr, dmu_tx_t *tx)
4526 (void) arg, (void) cr;
4529 * Create the objects common to all ztest datasets.
4531 VERIFY0(zap_create_claim(os, ZTEST_DIROBJ,
4532 DMU_OT_ZAP_OTHER, DMU_OT_NONE, 0, tx));
4535 static int
4536 ztest_dataset_create(char *dsname)
4538 int err;
4539 uint64_t rand;
4540 dsl_crypto_params_t *dcp = NULL;
4543 * 50% of the time, we create encrypted datasets
4544 * using a random cipher suite and a hard-coded
4545 * wrapping key.
4547 rand = ztest_random(2);
4548 if (rand != 0) {
4549 nvlist_t *crypto_args = fnvlist_alloc();
4550 nvlist_t *props = fnvlist_alloc();
4552 /* slight bias towards the default cipher suite */
4553 rand = ztest_random(ZIO_CRYPT_FUNCTIONS);
4554 if (rand < ZIO_CRYPT_AES_128_CCM)
4555 rand = ZIO_CRYPT_ON;
4557 fnvlist_add_uint64(props,
4558 zfs_prop_to_name(ZFS_PROP_ENCRYPTION), rand);
4559 fnvlist_add_uint8_array(crypto_args, "wkeydata",
4560 (uint8_t *)ztest_wkeydata, WRAPPING_KEY_LEN);
4563 * These parameters aren't really used by the kernel. They
4564 * are simply stored so that userspace knows how to load
4565 * the wrapping key.
4567 fnvlist_add_uint64(props,
4568 zfs_prop_to_name(ZFS_PROP_KEYFORMAT), ZFS_KEYFORMAT_RAW);
4569 fnvlist_add_string(props,
4570 zfs_prop_to_name(ZFS_PROP_KEYLOCATION), "prompt");
4571 fnvlist_add_uint64(props,
4572 zfs_prop_to_name(ZFS_PROP_PBKDF2_SALT), 0ULL);
4573 fnvlist_add_uint64(props,
4574 zfs_prop_to_name(ZFS_PROP_PBKDF2_ITERS), 0ULL);
4576 VERIFY0(dsl_crypto_params_create_nvlist(DCP_CMD_NONE, props,
4577 crypto_args, &dcp));
4580 * Cycle through all available encryption implementations
4581 * to verify interoperability.
4583 VERIFY0(gcm_impl_set("cycle"));
4584 VERIFY0(aes_impl_set("cycle"));
4586 fnvlist_free(crypto_args);
4587 fnvlist_free(props);
4590 err = dmu_objset_create(dsname, DMU_OST_OTHER, 0, dcp,
4591 ztest_objset_create_cb, NULL);
4592 dsl_crypto_params_free(dcp, !!err);
4594 rand = ztest_random(100);
4595 if (err || rand < 80)
4596 return (err);
4598 if (ztest_opts.zo_verbose >= 5)
4599 (void) printf("Setting dataset %s to sync always\n", dsname);
4600 return (ztest_dsl_prop_set_uint64(dsname, ZFS_PROP_SYNC,
4601 ZFS_SYNC_ALWAYS, B_FALSE));
4604 static int
4605 ztest_objset_destroy_cb(const char *name, void *arg)
4607 (void) arg;
4608 objset_t *os;
4609 dmu_object_info_t doi;
4610 int error;
4613 * Verify that the dataset contains a directory object.
4615 VERIFY0(ztest_dmu_objset_own(name, DMU_OST_OTHER, B_TRUE,
4616 B_TRUE, FTAG, &os));
4617 error = dmu_object_info(os, ZTEST_DIROBJ, &doi);
4618 if (error != ENOENT) {
4619 /* We could have crashed in the middle of destroying it */
4620 ASSERT0(error);
4621 ASSERT3U(doi.doi_type, ==, DMU_OT_ZAP_OTHER);
4622 ASSERT3S(doi.doi_physical_blocks_512, >=, 0);
4624 dmu_objset_disown(os, B_TRUE, FTAG);
4627 * Destroy the dataset.
4629 if (strchr(name, '@') != NULL) {
4630 error = dsl_destroy_snapshot(name, B_TRUE);
4631 if (error != ECHRNG) {
4633 * The program was executed, but encountered a runtime
4634 * error, such as insufficient slop, or a hold on the
4635 * dataset.
4637 ASSERT0(error);
4639 } else {
4640 error = dsl_destroy_head(name);
4641 if (error == ENOSPC) {
4642 /* There could be checkpoint or insufficient slop */
4643 ztest_record_enospc(FTAG);
4644 } else if (error != EBUSY) {
4645 /* There could be a hold on this dataset */
4646 ASSERT0(error);
4649 return (0);
4652 static boolean_t
4653 ztest_snapshot_create(char *osname, uint64_t id)
4655 char snapname[ZFS_MAX_DATASET_NAME_LEN];
4656 int error;
4658 (void) snprintf(snapname, sizeof (snapname), "%"PRIu64"", id);
4660 error = dmu_objset_snapshot_one(osname, snapname);
4661 if (error == ENOSPC) {
4662 ztest_record_enospc(FTAG);
4663 return (B_FALSE);
4665 if (error != 0 && error != EEXIST && error != ECHRNG) {
4666 fatal(B_FALSE, "ztest_snapshot_create(%s@%s) = %d", osname,
4667 snapname, error);
4669 return (B_TRUE);
4672 static boolean_t
4673 ztest_snapshot_destroy(char *osname, uint64_t id)
4675 char snapname[ZFS_MAX_DATASET_NAME_LEN];
4676 int error;
4678 (void) snprintf(snapname, sizeof (snapname), "%s@%"PRIu64"",
4679 osname, id);
4681 error = dsl_destroy_snapshot(snapname, B_FALSE);
4682 if (error != 0 && error != ENOENT && error != ECHRNG)
4683 fatal(B_FALSE, "ztest_snapshot_destroy(%s) = %d",
4684 snapname, error);
4685 return (B_TRUE);
4688 void
4689 ztest_dmu_objset_create_destroy(ztest_ds_t *zd, uint64_t id)
4691 (void) zd;
4692 ztest_ds_t *zdtmp;
4693 int iters;
4694 int error;
4695 objset_t *os, *os2;
4696 char name[ZFS_MAX_DATASET_NAME_LEN];
4697 zilog_t *zilog;
4698 int i;
4700 zdtmp = umem_alloc(sizeof (ztest_ds_t), UMEM_NOFAIL);
4702 (void) pthread_rwlock_rdlock(&ztest_name_lock);
4704 (void) snprintf(name, sizeof (name), "%s/temp_%"PRIu64"",
4705 ztest_opts.zo_pool, id);
4708 * If this dataset exists from a previous run, process its replay log
4709 * half of the time. If we don't replay it, then dsl_destroy_head()
4710 * (invoked from ztest_objset_destroy_cb()) should just throw it away.
4712 if (ztest_random(2) == 0 &&
4713 ztest_dmu_objset_own(name, DMU_OST_OTHER, B_FALSE,
4714 B_TRUE, FTAG, &os) == 0) {
4715 ztest_zd_init(zdtmp, NULL, os);
4716 zil_replay(os, zdtmp, ztest_replay_vector);
4717 ztest_zd_fini(zdtmp);
4718 dmu_objset_disown(os, B_TRUE, FTAG);
4722 * There may be an old instance of the dataset we're about to
4723 * create lying around from a previous run. If so, destroy it
4724 * and all of its snapshots.
4726 (void) dmu_objset_find(name, ztest_objset_destroy_cb, NULL,
4727 DS_FIND_CHILDREN | DS_FIND_SNAPSHOTS);
4730 * Verify that the destroyed dataset is no longer in the namespace.
4731 * It may still be present if the destroy above fails with ENOSPC.
4733 error = ztest_dmu_objset_own(name, DMU_OST_OTHER, B_TRUE, B_TRUE,
4734 FTAG, &os);
4735 if (error == 0) {
4736 dmu_objset_disown(os, B_TRUE, FTAG);
4737 ztest_record_enospc(FTAG);
4738 goto out;
4740 VERIFY3U(ENOENT, ==, error);
4743 * Verify that we can create a new dataset.
4745 error = ztest_dataset_create(name);
4746 if (error) {
4747 if (error == ENOSPC) {
4748 ztest_record_enospc(FTAG);
4749 goto out;
4751 fatal(B_FALSE, "dmu_objset_create(%s) = %d", name, error);
4754 VERIFY0(ztest_dmu_objset_own(name, DMU_OST_OTHER, B_FALSE, B_TRUE,
4755 FTAG, &os));
4757 ztest_zd_init(zdtmp, NULL, os);
4760 * Open the intent log for it.
4762 zilog = zil_open(os, ztest_get_data, NULL);
4765 * Put some objects in there, do a little I/O to them,
4766 * and randomly take a couple of snapshots along the way.
4768 iters = ztest_random(5);
4769 for (i = 0; i < iters; i++) {
4770 ztest_dmu_object_alloc_free(zdtmp, id);
4771 if (ztest_random(iters) == 0)
4772 (void) ztest_snapshot_create(name, i);
4776 * Verify that we cannot create an existing dataset.
4778 VERIFY3U(EEXIST, ==,
4779 dmu_objset_create(name, DMU_OST_OTHER, 0, NULL, NULL, NULL));
4782 * Verify that we can hold an objset that is also owned.
4784 VERIFY0(dmu_objset_hold(name, FTAG, &os2));
4785 dmu_objset_rele(os2, FTAG);
4788 * Verify that we cannot own an objset that is already owned.
4790 VERIFY3U(EBUSY, ==, ztest_dmu_objset_own(name, DMU_OST_OTHER,
4791 B_FALSE, B_TRUE, FTAG, &os2));
4793 zil_close(zilog);
4794 dmu_objset_disown(os, B_TRUE, FTAG);
4795 ztest_zd_fini(zdtmp);
4796 out:
4797 (void) pthread_rwlock_unlock(&ztest_name_lock);
4799 umem_free(zdtmp, sizeof (ztest_ds_t));
4803 * Verify that dmu_snapshot_{create,destroy,open,close} work as expected.
4805 void
4806 ztest_dmu_snapshot_create_destroy(ztest_ds_t *zd, uint64_t id)
4808 (void) pthread_rwlock_rdlock(&ztest_name_lock);
4809 (void) ztest_snapshot_destroy(zd->zd_name, id);
4810 (void) ztest_snapshot_create(zd->zd_name, id);
4811 (void) pthread_rwlock_unlock(&ztest_name_lock);
4815 * Cleanup non-standard snapshots and clones.
4817 static void
4818 ztest_dsl_dataset_cleanup(char *osname, uint64_t id)
4820 char *snap1name;
4821 char *clone1name;
4822 char *snap2name;
4823 char *clone2name;
4824 char *snap3name;
4825 int error;
4827 snap1name = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
4828 clone1name = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
4829 snap2name = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
4830 clone2name = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
4831 snap3name = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
4833 (void) snprintf(snap1name, ZFS_MAX_DATASET_NAME_LEN, "%s@s1_%"PRIu64"",
4834 osname, id);
4835 (void) snprintf(clone1name, ZFS_MAX_DATASET_NAME_LEN, "%s/c1_%"PRIu64"",
4836 osname, id);
4837 (void) snprintf(snap2name, ZFS_MAX_DATASET_NAME_LEN, "%s@s2_%"PRIu64"",
4838 clone1name, id);
4839 (void) snprintf(clone2name, ZFS_MAX_DATASET_NAME_LEN, "%s/c2_%"PRIu64"",
4840 osname, id);
4841 (void) snprintf(snap3name, ZFS_MAX_DATASET_NAME_LEN, "%s@s3_%"PRIu64"",
4842 clone1name, id);
4844 error = dsl_destroy_head(clone2name);
4845 if (error && error != ENOENT)
4846 fatal(B_FALSE, "dsl_destroy_head(%s) = %d", clone2name, error);
4847 error = dsl_destroy_snapshot(snap3name, B_FALSE);
4848 if (error && error != ENOENT)
4849 fatal(B_FALSE, "dsl_destroy_snapshot(%s) = %d",
4850 snap3name, error);
4851 error = dsl_destroy_snapshot(snap2name, B_FALSE);
4852 if (error && error != ENOENT)
4853 fatal(B_FALSE, "dsl_destroy_snapshot(%s) = %d",
4854 snap2name, error);
4855 error = dsl_destroy_head(clone1name);
4856 if (error && error != ENOENT)
4857 fatal(B_FALSE, "dsl_destroy_head(%s) = %d", clone1name, error);
4858 error = dsl_destroy_snapshot(snap1name, B_FALSE);
4859 if (error && error != ENOENT)
4860 fatal(B_FALSE, "dsl_destroy_snapshot(%s) = %d",
4861 snap1name, error);
4863 umem_free(snap1name, ZFS_MAX_DATASET_NAME_LEN);
4864 umem_free(clone1name, ZFS_MAX_DATASET_NAME_LEN);
4865 umem_free(snap2name, ZFS_MAX_DATASET_NAME_LEN);
4866 umem_free(clone2name, ZFS_MAX_DATASET_NAME_LEN);
4867 umem_free(snap3name, ZFS_MAX_DATASET_NAME_LEN);
4871 * Verify dsl_dataset_promote handles EBUSY
4873 void
4874 ztest_dsl_dataset_promote_busy(ztest_ds_t *zd, uint64_t id)
4876 objset_t *os;
4877 char *snap1name;
4878 char *clone1name;
4879 char *snap2name;
4880 char *clone2name;
4881 char *snap3name;
4882 char *osname = zd->zd_name;
4883 int error;
4885 snap1name = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
4886 clone1name = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
4887 snap2name = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
4888 clone2name = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
4889 snap3name = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
4891 (void) pthread_rwlock_rdlock(&ztest_name_lock);
4893 ztest_dsl_dataset_cleanup(osname, id);
4895 (void) snprintf(snap1name, ZFS_MAX_DATASET_NAME_LEN, "%s@s1_%"PRIu64"",
4896 osname, id);
4897 (void) snprintf(clone1name, ZFS_MAX_DATASET_NAME_LEN, "%s/c1_%"PRIu64"",
4898 osname, id);
4899 (void) snprintf(snap2name, ZFS_MAX_DATASET_NAME_LEN, "%s@s2_%"PRIu64"",
4900 clone1name, id);
4901 (void) snprintf(clone2name, ZFS_MAX_DATASET_NAME_LEN, "%s/c2_%"PRIu64"",
4902 osname, id);
4903 (void) snprintf(snap3name, ZFS_MAX_DATASET_NAME_LEN, "%s@s3_%"PRIu64"",
4904 clone1name, id);
4906 error = dmu_objset_snapshot_one(osname, strchr(snap1name, '@') + 1);
4907 if (error && error != EEXIST) {
4908 if (error == ENOSPC) {
4909 ztest_record_enospc(FTAG);
4910 goto out;
4912 fatal(B_FALSE, "dmu_take_snapshot(%s) = %d", snap1name, error);
4915 error = dmu_objset_clone(clone1name, snap1name);
4916 if (error) {
4917 if (error == ENOSPC) {
4918 ztest_record_enospc(FTAG);
4919 goto out;
4921 fatal(B_FALSE, "dmu_objset_create(%s) = %d", clone1name, error);
4924 error = dmu_objset_snapshot_one(clone1name, strchr(snap2name, '@') + 1);
4925 if (error && error != EEXIST) {
4926 if (error == ENOSPC) {
4927 ztest_record_enospc(FTAG);
4928 goto out;
4930 fatal(B_FALSE, "dmu_open_snapshot(%s) = %d", snap2name, error);
4933 error = dmu_objset_snapshot_one(clone1name, strchr(snap3name, '@') + 1);
4934 if (error && error != EEXIST) {
4935 if (error == ENOSPC) {
4936 ztest_record_enospc(FTAG);
4937 goto out;
4939 fatal(B_FALSE, "dmu_open_snapshot(%s) = %d", snap3name, error);
4942 error = dmu_objset_clone(clone2name, snap3name);
4943 if (error) {
4944 if (error == ENOSPC) {
4945 ztest_record_enospc(FTAG);
4946 goto out;
4948 fatal(B_FALSE, "dmu_objset_create(%s) = %d", clone2name, error);
4951 error = ztest_dmu_objset_own(snap2name, DMU_OST_ANY, B_TRUE, B_TRUE,
4952 FTAG, &os);
4953 if (error)
4954 fatal(B_FALSE, "dmu_objset_own(%s) = %d", snap2name, error);
4955 error = dsl_dataset_promote(clone2name, NULL);
4956 if (error == ENOSPC) {
4957 dmu_objset_disown(os, B_TRUE, FTAG);
4958 ztest_record_enospc(FTAG);
4959 goto out;
4961 if (error != EBUSY)
4962 fatal(B_FALSE, "dsl_dataset_promote(%s), %d, not EBUSY",
4963 clone2name, error);
4964 dmu_objset_disown(os, B_TRUE, FTAG);
4966 out:
4967 ztest_dsl_dataset_cleanup(osname, id);
4969 (void) pthread_rwlock_unlock(&ztest_name_lock);
4971 umem_free(snap1name, ZFS_MAX_DATASET_NAME_LEN);
4972 umem_free(clone1name, ZFS_MAX_DATASET_NAME_LEN);
4973 umem_free(snap2name, ZFS_MAX_DATASET_NAME_LEN);
4974 umem_free(clone2name, ZFS_MAX_DATASET_NAME_LEN);
4975 umem_free(snap3name, ZFS_MAX_DATASET_NAME_LEN);
4978 #undef OD_ARRAY_SIZE
4979 #define OD_ARRAY_SIZE 4
4982 * Verify that dmu_object_{alloc,free} work as expected.
4984 void
4985 ztest_dmu_object_alloc_free(ztest_ds_t *zd, uint64_t id)
4987 ztest_od_t *od;
4988 int batchsize;
4989 int size;
4990 int b;
4992 size = sizeof (ztest_od_t) * OD_ARRAY_SIZE;
4993 od = umem_alloc(size, UMEM_NOFAIL);
4994 batchsize = OD_ARRAY_SIZE;
4996 for (b = 0; b < batchsize; b++)
4997 ztest_od_init(od + b, id, FTAG, b, DMU_OT_UINT64_OTHER,
4998 0, 0, 0);
5001 * Destroy the previous batch of objects, create a new batch,
5002 * and do some I/O on the new objects.
5004 if (ztest_object_init(zd, od, size, B_TRUE) != 0) {
5005 zd->zd_od = NULL;
5006 umem_free(od, size);
5007 return;
5010 while (ztest_random(4 * batchsize) != 0)
5011 ztest_io(zd, od[ztest_random(batchsize)].od_object,
5012 ztest_random(ZTEST_RANGE_LOCKS) << SPA_MAXBLOCKSHIFT);
5014 umem_free(od, size);
5018 * Rewind the global allocator to verify object allocation backfilling.
5020 void
5021 ztest_dmu_object_next_chunk(ztest_ds_t *zd, uint64_t id)
5023 (void) id;
5024 objset_t *os = zd->zd_os;
5025 uint_t dnodes_per_chunk = 1 << dmu_object_alloc_chunk_shift;
5026 uint64_t object;
5029 * Rewind the global allocator randomly back to a lower object number
5030 * to force backfilling and reclamation of recently freed dnodes.
5032 mutex_enter(&os->os_obj_lock);
5033 object = ztest_random(os->os_obj_next_chunk);
5034 os->os_obj_next_chunk = P2ALIGN_TYPED(object, dnodes_per_chunk,
5035 uint64_t);
5036 mutex_exit(&os->os_obj_lock);
5039 #undef OD_ARRAY_SIZE
5040 #define OD_ARRAY_SIZE 2
5043 * Verify that dmu_{read,write} work as expected.
5045 void
5046 ztest_dmu_read_write(ztest_ds_t *zd, uint64_t id)
5048 int size;
5049 ztest_od_t *od;
5051 objset_t *os = zd->zd_os;
5052 size = sizeof (ztest_od_t) * OD_ARRAY_SIZE;
5053 od = umem_alloc(size, UMEM_NOFAIL);
5054 dmu_tx_t *tx;
5055 int freeit, error;
5056 uint64_t i, n, s, txg;
5057 bufwad_t *packbuf, *bigbuf, *pack, *bigH, *bigT;
5058 uint64_t packobj, packoff, packsize, bigobj, bigoff, bigsize;
5059 uint64_t chunksize = (1000 + ztest_random(1000)) * sizeof (uint64_t);
5060 uint64_t regions = 997;
5061 uint64_t stride = 123456789ULL;
5062 uint64_t width = 40;
5063 int free_percent = 5;
5064 uint32_t dmu_read_flags = DMU_READ_PREFETCH;
5067 * We will randomly set when to do O_DIRECT on a read.
5069 if (ztest_random(4) == 0)
5070 dmu_read_flags |= DMU_DIRECTIO;
5073 * This test uses two objects, packobj and bigobj, that are always
5074 * updated together (i.e. in the same tx) so that their contents are
5075 * in sync and can be compared. Their contents relate to each other
5076 * in a simple way: packobj is a dense array of 'bufwad' structures,
5077 * while bigobj is a sparse array of the same bufwads. Specifically,
5078 * for any index n, there are three bufwads that should be identical:
5080 * packobj, at offset n * sizeof (bufwad_t)
5081 * bigobj, at the head of the nth chunk
5082 * bigobj, at the tail of the nth chunk
5084 * The chunk size is arbitrary. It doesn't have to be a power of two,
5085 * and it doesn't have any relation to the object blocksize.
5086 * The only requirement is that it can hold at least two bufwads.
5088 * Normally, we write the bufwad to each of these locations.
5089 * However, free_percent of the time we instead write zeroes to
5090 * packobj and perform a dmu_free_range() on bigobj. By comparing
5091 * bigobj to packobj, we can verify that the DMU is correctly
5092 * tracking which parts of an object are allocated and free,
5093 * and that the contents of the allocated blocks are correct.
5097 * Read the directory info. If it's the first time, set things up.
5099 ztest_od_init(od, id, FTAG, 0, DMU_OT_UINT64_OTHER, 0, 0, chunksize);
5100 ztest_od_init(od + 1, id, FTAG, 1, DMU_OT_UINT64_OTHER, 0, 0,
5101 chunksize);
5103 if (ztest_object_init(zd, od, size, B_FALSE) != 0) {
5104 umem_free(od, size);
5105 return;
5108 bigobj = od[0].od_object;
5109 packobj = od[1].od_object;
5110 chunksize = od[0].od_gen;
5111 ASSERT3U(chunksize, ==, od[1].od_gen);
5114 * Prefetch a random chunk of the big object.
5115 * Our aim here is to get some async reads in flight
5116 * for blocks that we may free below; the DMU should
5117 * handle this race correctly.
5119 n = ztest_random(regions) * stride + ztest_random(width);
5120 s = 1 + ztest_random(2 * width - 1);
5121 dmu_prefetch(os, bigobj, 0, n * chunksize, s * chunksize,
5122 ZIO_PRIORITY_SYNC_READ);
5125 * Pick a random index and compute the offsets into packobj and bigobj.
5127 n = ztest_random(regions) * stride + ztest_random(width);
5128 s = 1 + ztest_random(width - 1);
5130 packoff = n * sizeof (bufwad_t);
5131 packsize = s * sizeof (bufwad_t);
5133 bigoff = n * chunksize;
5134 bigsize = s * chunksize;
5136 packbuf = umem_alloc(packsize, UMEM_NOFAIL);
5137 bigbuf = umem_alloc(bigsize, UMEM_NOFAIL);
5140 * free_percent of the time, free a range of bigobj rather than
5141 * overwriting it.
5143 freeit = (ztest_random(100) < free_percent);
5146 * Read the current contents of our objects.
5148 error = dmu_read(os, packobj, packoff, packsize, packbuf,
5149 dmu_read_flags);
5150 ASSERT0(error);
5151 error = dmu_read(os, bigobj, bigoff, bigsize, bigbuf,
5152 dmu_read_flags);
5153 ASSERT0(error);
5156 * Get a tx for the mods to both packobj and bigobj.
5158 tx = dmu_tx_create(os);
5160 dmu_tx_hold_write(tx, packobj, packoff, packsize);
5162 if (freeit)
5163 dmu_tx_hold_free(tx, bigobj, bigoff, bigsize);
5164 else
5165 dmu_tx_hold_write(tx, bigobj, bigoff, bigsize);
5167 /* This accounts for setting the checksum/compression. */
5168 dmu_tx_hold_bonus(tx, bigobj);
5170 txg = ztest_tx_assign(tx, TXG_MIGHTWAIT, FTAG);
5171 if (txg == 0) {
5172 umem_free(packbuf, packsize);
5173 umem_free(bigbuf, bigsize);
5174 umem_free(od, size);
5175 return;
5178 enum zio_checksum cksum;
5179 do {
5180 cksum = (enum zio_checksum)
5181 ztest_random_dsl_prop(ZFS_PROP_CHECKSUM);
5182 } while (cksum >= ZIO_CHECKSUM_LEGACY_FUNCTIONS);
5183 dmu_object_set_checksum(os, bigobj, cksum, tx);
5185 enum zio_compress comp;
5186 do {
5187 comp = (enum zio_compress)
5188 ztest_random_dsl_prop(ZFS_PROP_COMPRESSION);
5189 } while (comp >= ZIO_COMPRESS_LEGACY_FUNCTIONS);
5190 dmu_object_set_compress(os, bigobj, comp, tx);
5193 * For each index from n to n + s, verify that the existing bufwad
5194 * in packobj matches the bufwads at the head and tail of the
5195 * corresponding chunk in bigobj. Then update all three bufwads
5196 * with the new values we want to write out.
5198 for (i = 0; i < s; i++) {
5199 /* LINTED */
5200 pack = (bufwad_t *)((char *)packbuf + i * sizeof (bufwad_t));
5201 /* LINTED */
5202 bigH = (bufwad_t *)((char *)bigbuf + i * chunksize);
5203 /* LINTED */
5204 bigT = (bufwad_t *)((char *)bigH + chunksize) - 1;
5206 ASSERT3U((uintptr_t)bigH - (uintptr_t)bigbuf, <, bigsize);
5207 ASSERT3U((uintptr_t)bigT - (uintptr_t)bigbuf, <, bigsize);
5209 if (pack->bw_txg > txg)
5210 fatal(B_FALSE,
5211 "future leak: got %"PRIx64", open txg is %"PRIx64"",
5212 pack->bw_txg, txg);
5214 if (pack->bw_data != 0 && pack->bw_index != n + i)
5215 fatal(B_FALSE, "wrong index: "
5216 "got %"PRIx64", wanted %"PRIx64"+%"PRIx64"",
5217 pack->bw_index, n, i);
5219 if (memcmp(pack, bigH, sizeof (bufwad_t)) != 0)
5220 fatal(B_FALSE, "pack/bigH mismatch in %p/%p",
5221 pack, bigH);
5223 if (memcmp(pack, bigT, sizeof (bufwad_t)) != 0)
5224 fatal(B_FALSE, "pack/bigT mismatch in %p/%p",
5225 pack, bigT);
5227 if (freeit) {
5228 memset(pack, 0, sizeof (bufwad_t));
5229 } else {
5230 pack->bw_index = n + i;
5231 pack->bw_txg = txg;
5232 pack->bw_data = 1 + ztest_random(-2ULL);
5234 *bigH = *pack;
5235 *bigT = *pack;
5239 * We've verified all the old bufwads, and made new ones.
5240 * Now write them out.
5242 dmu_write(os, packobj, packoff, packsize, packbuf, tx);
5244 if (freeit) {
5245 if (ztest_opts.zo_verbose >= 7) {
5246 (void) printf("freeing offset %"PRIx64" size %"PRIx64""
5247 " txg %"PRIx64"\n",
5248 bigoff, bigsize, txg);
5250 VERIFY0(dmu_free_range(os, bigobj, bigoff, bigsize, tx));
5251 } else {
5252 if (ztest_opts.zo_verbose >= 7) {
5253 (void) printf("writing offset %"PRIx64" size %"PRIx64""
5254 " txg %"PRIx64"\n",
5255 bigoff, bigsize, txg);
5257 dmu_write(os, bigobj, bigoff, bigsize, bigbuf, tx);
5260 dmu_tx_commit(tx);
5263 * Sanity check the stuff we just wrote.
5266 void *packcheck = umem_alloc(packsize, UMEM_NOFAIL);
5267 void *bigcheck = umem_alloc(bigsize, UMEM_NOFAIL);
5269 VERIFY0(dmu_read(os, packobj, packoff,
5270 packsize, packcheck, dmu_read_flags));
5271 VERIFY0(dmu_read(os, bigobj, bigoff,
5272 bigsize, bigcheck, dmu_read_flags));
5274 ASSERT0(memcmp(packbuf, packcheck, packsize));
5275 ASSERT0(memcmp(bigbuf, bigcheck, bigsize));
5277 umem_free(packcheck, packsize);
5278 umem_free(bigcheck, bigsize);
5281 umem_free(packbuf, packsize);
5282 umem_free(bigbuf, bigsize);
5283 umem_free(od, size);
5286 static void
5287 compare_and_update_pbbufs(uint64_t s, bufwad_t *packbuf, bufwad_t *bigbuf,
5288 uint64_t bigsize, uint64_t n, uint64_t chunksize, uint64_t txg)
5290 uint64_t i;
5291 bufwad_t *pack;
5292 bufwad_t *bigH;
5293 bufwad_t *bigT;
5296 * For each index from n to n + s, verify that the existing bufwad
5297 * in packobj matches the bufwads at the head and tail of the
5298 * corresponding chunk in bigobj. Then update all three bufwads
5299 * with the new values we want to write out.
5301 for (i = 0; i < s; i++) {
5302 /* LINTED */
5303 pack = (bufwad_t *)((char *)packbuf + i * sizeof (bufwad_t));
5304 /* LINTED */
5305 bigH = (bufwad_t *)((char *)bigbuf + i * chunksize);
5306 /* LINTED */
5307 bigT = (bufwad_t *)((char *)bigH + chunksize) - 1;
5309 ASSERT3U((uintptr_t)bigH - (uintptr_t)bigbuf, <, bigsize);
5310 ASSERT3U((uintptr_t)bigT - (uintptr_t)bigbuf, <, bigsize);
5312 if (pack->bw_txg > txg)
5313 fatal(B_FALSE,
5314 "future leak: got %"PRIx64", open txg is %"PRIx64"",
5315 pack->bw_txg, txg);
5317 if (pack->bw_data != 0 && pack->bw_index != n + i)
5318 fatal(B_FALSE, "wrong index: "
5319 "got %"PRIx64", wanted %"PRIx64"+%"PRIx64"",
5320 pack->bw_index, n, i);
5322 if (memcmp(pack, bigH, sizeof (bufwad_t)) != 0)
5323 fatal(B_FALSE, "pack/bigH mismatch in %p/%p",
5324 pack, bigH);
5326 if (memcmp(pack, bigT, sizeof (bufwad_t)) != 0)
5327 fatal(B_FALSE, "pack/bigT mismatch in %p/%p",
5328 pack, bigT);
5330 pack->bw_index = n + i;
5331 pack->bw_txg = txg;
5332 pack->bw_data = 1 + ztest_random(-2ULL);
5334 *bigH = *pack;
5335 *bigT = *pack;
5339 #undef OD_ARRAY_SIZE
5340 #define OD_ARRAY_SIZE 2
5342 void
5343 ztest_dmu_read_write_zcopy(ztest_ds_t *zd, uint64_t id)
5345 objset_t *os = zd->zd_os;
5346 ztest_od_t *od;
5347 dmu_tx_t *tx;
5348 uint64_t i;
5349 int error;
5350 int size;
5351 uint64_t n, s, txg;
5352 bufwad_t *packbuf, *bigbuf;
5353 uint64_t packobj, packoff, packsize, bigobj, bigoff, bigsize;
5354 uint64_t blocksize = ztest_random_blocksize();
5355 uint64_t chunksize = blocksize;
5356 uint64_t regions = 997;
5357 uint64_t stride = 123456789ULL;
5358 uint64_t width = 9;
5359 dmu_buf_t *bonus_db;
5360 arc_buf_t **bigbuf_arcbufs;
5361 dmu_object_info_t doi;
5362 uint32_t dmu_read_flags = DMU_READ_PREFETCH;
5365 * We will randomly set when to do O_DIRECT on a read.
5367 if (ztest_random(4) == 0)
5368 dmu_read_flags |= DMU_DIRECTIO;
5370 size = sizeof (ztest_od_t) * OD_ARRAY_SIZE;
5371 od = umem_alloc(size, UMEM_NOFAIL);
5374 * This test uses two objects, packobj and bigobj, that are always
5375 * updated together (i.e. in the same tx) so that their contents are
5376 * in sync and can be compared. Their contents relate to each other
5377 * in a simple way: packobj is a dense array of 'bufwad' structures,
5378 * while bigobj is a sparse array of the same bufwads. Specifically,
5379 * for any index n, there are three bufwads that should be identical:
5381 * packobj, at offset n * sizeof (bufwad_t)
5382 * bigobj, at the head of the nth chunk
5383 * bigobj, at the tail of the nth chunk
5385 * The chunk size is set equal to bigobj block size so that
5386 * dmu_assign_arcbuf_by_dbuf() can be tested for object updates.
5390 * Read the directory info. If it's the first time, set things up.
5392 ztest_od_init(od, id, FTAG, 0, DMU_OT_UINT64_OTHER, blocksize, 0, 0);
5393 ztest_od_init(od + 1, id, FTAG, 1, DMU_OT_UINT64_OTHER, 0, 0,
5394 chunksize);
5397 if (ztest_object_init(zd, od, size, B_FALSE) != 0) {
5398 umem_free(od, size);
5399 return;
5402 bigobj = od[0].od_object;
5403 packobj = od[1].od_object;
5404 blocksize = od[0].od_blocksize;
5405 chunksize = blocksize;
5406 ASSERT3U(chunksize, ==, od[1].od_gen);
5408 VERIFY0(dmu_object_info(os, bigobj, &doi));
5409 VERIFY(ISP2(doi.doi_data_block_size));
5410 VERIFY3U(chunksize, ==, doi.doi_data_block_size);
5411 VERIFY3U(chunksize, >=, 2 * sizeof (bufwad_t));
5414 * Pick a random index and compute the offsets into packobj and bigobj.
5416 n = ztest_random(regions) * stride + ztest_random(width);
5417 s = 1 + ztest_random(width - 1);
5419 packoff = n * sizeof (bufwad_t);
5420 packsize = s * sizeof (bufwad_t);
5422 bigoff = n * chunksize;
5423 bigsize = s * chunksize;
5425 packbuf = umem_zalloc(packsize, UMEM_NOFAIL);
5426 bigbuf = umem_zalloc(bigsize, UMEM_NOFAIL);
5428 VERIFY0(dmu_bonus_hold(os, bigobj, FTAG, &bonus_db));
5430 bigbuf_arcbufs = umem_zalloc(2 * s * sizeof (arc_buf_t *), UMEM_NOFAIL);
5433 * Iteration 0 test zcopy for DB_UNCACHED dbufs.
5434 * Iteration 1 test zcopy to already referenced dbufs.
5435 * Iteration 2 test zcopy to dirty dbuf in the same txg.
5436 * Iteration 3 test zcopy to dbuf dirty in previous txg.
5437 * Iteration 4 test zcopy when dbuf is no longer dirty.
5438 * Iteration 5 test zcopy when it can't be done.
5439 * Iteration 6 one more zcopy write.
5441 for (i = 0; i < 7; i++) {
5442 uint64_t j;
5443 uint64_t off;
5446 * In iteration 5 (i == 5) use arcbufs
5447 * that don't match bigobj blksz to test
5448 * dmu_assign_arcbuf_by_dbuf() when it can't directly
5449 * assign an arcbuf to a dbuf.
5451 for (j = 0; j < s; j++) {
5452 if (i != 5 || chunksize < (SPA_MINBLOCKSIZE * 2)) {
5453 bigbuf_arcbufs[j] =
5454 dmu_request_arcbuf(bonus_db, chunksize);
5455 } else {
5456 bigbuf_arcbufs[2 * j] =
5457 dmu_request_arcbuf(bonus_db, chunksize / 2);
5458 bigbuf_arcbufs[2 * j + 1] =
5459 dmu_request_arcbuf(bonus_db, chunksize / 2);
5464 * Get a tx for the mods to both packobj and bigobj.
5466 tx = dmu_tx_create(os);
5468 dmu_tx_hold_write(tx, packobj, packoff, packsize);
5469 dmu_tx_hold_write(tx, bigobj, bigoff, bigsize);
5471 txg = ztest_tx_assign(tx, TXG_MIGHTWAIT, FTAG);
5472 if (txg == 0) {
5473 umem_free(packbuf, packsize);
5474 umem_free(bigbuf, bigsize);
5475 for (j = 0; j < s; j++) {
5476 if (i != 5 ||
5477 chunksize < (SPA_MINBLOCKSIZE * 2)) {
5478 dmu_return_arcbuf(bigbuf_arcbufs[j]);
5479 } else {
5480 dmu_return_arcbuf(
5481 bigbuf_arcbufs[2 * j]);
5482 dmu_return_arcbuf(
5483 bigbuf_arcbufs[2 * j + 1]);
5486 umem_free(bigbuf_arcbufs, 2 * s * sizeof (arc_buf_t *));
5487 umem_free(od, size);
5488 dmu_buf_rele(bonus_db, FTAG);
5489 return;
5493 * 50% of the time don't read objects in the 1st iteration to
5494 * test dmu_assign_arcbuf_by_dbuf() for the case when there are
5495 * no existing dbufs for the specified offsets.
5497 if (i != 0 || ztest_random(2) != 0) {
5498 error = dmu_read(os, packobj, packoff,
5499 packsize, packbuf, dmu_read_flags);
5500 ASSERT0(error);
5501 error = dmu_read(os, bigobj, bigoff, bigsize,
5502 bigbuf, dmu_read_flags);
5503 ASSERT0(error);
5505 compare_and_update_pbbufs(s, packbuf, bigbuf, bigsize,
5506 n, chunksize, txg);
5509 * We've verified all the old bufwads, and made new ones.
5510 * Now write them out.
5512 dmu_write(os, packobj, packoff, packsize, packbuf, tx);
5513 if (ztest_opts.zo_verbose >= 7) {
5514 (void) printf("writing offset %"PRIx64" size %"PRIx64""
5515 " txg %"PRIx64"\n",
5516 bigoff, bigsize, txg);
5518 for (off = bigoff, j = 0; j < s; j++, off += chunksize) {
5519 dmu_buf_t *dbt;
5520 if (i != 5 || chunksize < (SPA_MINBLOCKSIZE * 2)) {
5521 memcpy(bigbuf_arcbufs[j]->b_data,
5522 (caddr_t)bigbuf + (off - bigoff),
5523 chunksize);
5524 } else {
5525 memcpy(bigbuf_arcbufs[2 * j]->b_data,
5526 (caddr_t)bigbuf + (off - bigoff),
5527 chunksize / 2);
5528 memcpy(bigbuf_arcbufs[2 * j + 1]->b_data,
5529 (caddr_t)bigbuf + (off - bigoff) +
5530 chunksize / 2,
5531 chunksize / 2);
5534 if (i == 1) {
5535 VERIFY(dmu_buf_hold(os, bigobj, off,
5536 FTAG, &dbt, DMU_READ_NO_PREFETCH) == 0);
5538 if (i != 5 || chunksize < (SPA_MINBLOCKSIZE * 2)) {
5539 VERIFY0(dmu_assign_arcbuf_by_dbuf(bonus_db,
5540 off, bigbuf_arcbufs[j], tx));
5541 } else {
5542 VERIFY0(dmu_assign_arcbuf_by_dbuf(bonus_db,
5543 off, bigbuf_arcbufs[2 * j], tx));
5544 VERIFY0(dmu_assign_arcbuf_by_dbuf(bonus_db,
5545 off + chunksize / 2,
5546 bigbuf_arcbufs[2 * j + 1], tx));
5548 if (i == 1) {
5549 dmu_buf_rele(dbt, FTAG);
5552 dmu_tx_commit(tx);
5555 * Sanity check the stuff we just wrote.
5558 void *packcheck = umem_alloc(packsize, UMEM_NOFAIL);
5559 void *bigcheck = umem_alloc(bigsize, UMEM_NOFAIL);
5561 VERIFY0(dmu_read(os, packobj, packoff,
5562 packsize, packcheck, dmu_read_flags));
5563 VERIFY0(dmu_read(os, bigobj, bigoff,
5564 bigsize, bigcheck, dmu_read_flags));
5566 ASSERT0(memcmp(packbuf, packcheck, packsize));
5567 ASSERT0(memcmp(bigbuf, bigcheck, bigsize));
5569 umem_free(packcheck, packsize);
5570 umem_free(bigcheck, bigsize);
5572 if (i == 2) {
5573 txg_wait_open(dmu_objset_pool(os), 0, B_TRUE);
5574 } else if (i == 3) {
5575 txg_wait_synced(dmu_objset_pool(os), 0);
5579 dmu_buf_rele(bonus_db, FTAG);
5580 umem_free(packbuf, packsize);
5581 umem_free(bigbuf, bigsize);
5582 umem_free(bigbuf_arcbufs, 2 * s * sizeof (arc_buf_t *));
5583 umem_free(od, size);
5586 void
5587 ztest_dmu_write_parallel(ztest_ds_t *zd, uint64_t id)
5589 (void) id;
5590 ztest_od_t *od;
5592 od = umem_alloc(sizeof (ztest_od_t), UMEM_NOFAIL);
5593 uint64_t offset = (1ULL << (ztest_random(20) + 43)) +
5594 (ztest_random(ZTEST_RANGE_LOCKS) << SPA_MAXBLOCKSHIFT);
5597 * Have multiple threads write to large offsets in an object
5598 * to verify that parallel writes to an object -- even to the
5599 * same blocks within the object -- doesn't cause any trouble.
5601 ztest_od_init(od, ID_PARALLEL, FTAG, 0, DMU_OT_UINT64_OTHER, 0, 0, 0);
5603 if (ztest_object_init(zd, od, sizeof (ztest_od_t), B_FALSE) != 0)
5604 return;
5606 while (ztest_random(10) != 0)
5607 ztest_io(zd, od->od_object, offset);
5609 umem_free(od, sizeof (ztest_od_t));
5612 void
5613 ztest_dmu_prealloc(ztest_ds_t *zd, uint64_t id)
5615 ztest_od_t *od;
5616 uint64_t offset = (1ULL << (ztest_random(4) + SPA_MAXBLOCKSHIFT)) +
5617 (ztest_random(ZTEST_RANGE_LOCKS) << SPA_MAXBLOCKSHIFT);
5618 uint64_t count = ztest_random(20) + 1;
5619 uint64_t blocksize = ztest_random_blocksize();
5620 void *data;
5622 od = umem_alloc(sizeof (ztest_od_t), UMEM_NOFAIL);
5624 ztest_od_init(od, id, FTAG, 0, DMU_OT_UINT64_OTHER, blocksize, 0, 0);
5626 if (ztest_object_init(zd, od, sizeof (ztest_od_t),
5627 !ztest_random(2)) != 0) {
5628 umem_free(od, sizeof (ztest_od_t));
5629 return;
5632 if (ztest_truncate(zd, od->od_object, offset, count * blocksize) != 0) {
5633 umem_free(od, sizeof (ztest_od_t));
5634 return;
5637 ztest_prealloc(zd, od->od_object, offset, count * blocksize);
5639 data = umem_zalloc(blocksize, UMEM_NOFAIL);
5641 while (ztest_random(count) != 0) {
5642 uint64_t randoff = offset + (ztest_random(count) * blocksize);
5643 if (ztest_write(zd, od->od_object, randoff, blocksize,
5644 data) != 0)
5645 break;
5646 while (ztest_random(4) != 0)
5647 ztest_io(zd, od->od_object, randoff);
5650 umem_free(data, blocksize);
5651 umem_free(od, sizeof (ztest_od_t));
5655 * Verify that zap_{create,destroy,add,remove,update} work as expected.
5657 #define ZTEST_ZAP_MIN_INTS 1
5658 #define ZTEST_ZAP_MAX_INTS 4
5659 #define ZTEST_ZAP_MAX_PROPS 1000
5661 void
5662 ztest_zap(ztest_ds_t *zd, uint64_t id)
5664 objset_t *os = zd->zd_os;
5665 ztest_od_t *od;
5666 uint64_t object;
5667 uint64_t txg, last_txg;
5668 uint64_t value[ZTEST_ZAP_MAX_INTS];
5669 uint64_t zl_ints, zl_intsize, prop;
5670 int i, ints;
5671 dmu_tx_t *tx;
5672 char propname[100], txgname[100];
5673 int error;
5674 const char *const hc[2] = { "s.acl.h", ".s.open.h.hyLZlg" };
5676 od = umem_alloc(sizeof (ztest_od_t), UMEM_NOFAIL);
5677 ztest_od_init(od, id, FTAG, 0, DMU_OT_ZAP_OTHER, 0, 0, 0);
5679 if (ztest_object_init(zd, od, sizeof (ztest_od_t),
5680 !ztest_random(2)) != 0)
5681 goto out;
5683 object = od->od_object;
5686 * Generate a known hash collision, and verify that
5687 * we can lookup and remove both entries.
5689 tx = dmu_tx_create(os);
5690 dmu_tx_hold_zap(tx, object, B_TRUE, NULL);
5691 txg = ztest_tx_assign(tx, TXG_MIGHTWAIT, FTAG);
5692 if (txg == 0)
5693 goto out;
5694 for (i = 0; i < 2; i++) {
5695 value[i] = i;
5696 VERIFY0(zap_add(os, object, hc[i], sizeof (uint64_t),
5697 1, &value[i], tx));
5699 for (i = 0; i < 2; i++) {
5700 VERIFY3U(EEXIST, ==, zap_add(os, object, hc[i],
5701 sizeof (uint64_t), 1, &value[i], tx));
5702 VERIFY0(
5703 zap_length(os, object, hc[i], &zl_intsize, &zl_ints));
5704 ASSERT3U(zl_intsize, ==, sizeof (uint64_t));
5705 ASSERT3U(zl_ints, ==, 1);
5707 for (i = 0; i < 2; i++) {
5708 VERIFY0(zap_remove(os, object, hc[i], tx));
5710 dmu_tx_commit(tx);
5713 * Generate a bunch of random entries.
5715 ints = MAX(ZTEST_ZAP_MIN_INTS, object % ZTEST_ZAP_MAX_INTS);
5717 prop = ztest_random(ZTEST_ZAP_MAX_PROPS);
5718 (void) sprintf(propname, "prop_%"PRIu64"", prop);
5719 (void) sprintf(txgname, "txg_%"PRIu64"", prop);
5720 memset(value, 0, sizeof (value));
5721 last_txg = 0;
5724 * If these zap entries already exist, validate their contents.
5726 error = zap_length(os, object, txgname, &zl_intsize, &zl_ints);
5727 if (error == 0) {
5728 ASSERT3U(zl_intsize, ==, sizeof (uint64_t));
5729 ASSERT3U(zl_ints, ==, 1);
5731 VERIFY0(zap_lookup(os, object, txgname, zl_intsize,
5732 zl_ints, &last_txg));
5734 VERIFY0(zap_length(os, object, propname, &zl_intsize,
5735 &zl_ints));
5737 ASSERT3U(zl_intsize, ==, sizeof (uint64_t));
5738 ASSERT3U(zl_ints, ==, ints);
5740 VERIFY0(zap_lookup(os, object, propname, zl_intsize,
5741 zl_ints, value));
5743 for (i = 0; i < ints; i++) {
5744 ASSERT3U(value[i], ==, last_txg + object + i);
5746 } else {
5747 ASSERT3U(error, ==, ENOENT);
5751 * Atomically update two entries in our zap object.
5752 * The first is named txg_%llu, and contains the txg
5753 * in which the property was last updated. The second
5754 * is named prop_%llu, and the nth element of its value
5755 * should be txg + object + n.
5757 tx = dmu_tx_create(os);
5758 dmu_tx_hold_zap(tx, object, B_TRUE, NULL);
5759 txg = ztest_tx_assign(tx, TXG_MIGHTWAIT, FTAG);
5760 if (txg == 0)
5761 goto out;
5763 if (last_txg > txg)
5764 fatal(B_FALSE, "zap future leak: old %"PRIu64" new %"PRIu64"",
5765 last_txg, txg);
5767 for (i = 0; i < ints; i++)
5768 value[i] = txg + object + i;
5770 VERIFY0(zap_update(os, object, txgname, sizeof (uint64_t),
5771 1, &txg, tx));
5772 VERIFY0(zap_update(os, object, propname, sizeof (uint64_t),
5773 ints, value, tx));
5775 dmu_tx_commit(tx);
5778 * Remove a random pair of entries.
5780 prop = ztest_random(ZTEST_ZAP_MAX_PROPS);
5781 (void) sprintf(propname, "prop_%"PRIu64"", prop);
5782 (void) sprintf(txgname, "txg_%"PRIu64"", prop);
5784 error = zap_length(os, object, txgname, &zl_intsize, &zl_ints);
5786 if (error == ENOENT)
5787 goto out;
5789 ASSERT0(error);
5791 tx = dmu_tx_create(os);
5792 dmu_tx_hold_zap(tx, object, B_TRUE, NULL);
5793 txg = ztest_tx_assign(tx, TXG_MIGHTWAIT, FTAG);
5794 if (txg == 0)
5795 goto out;
5796 VERIFY0(zap_remove(os, object, txgname, tx));
5797 VERIFY0(zap_remove(os, object, propname, tx));
5798 dmu_tx_commit(tx);
5799 out:
5800 umem_free(od, sizeof (ztest_od_t));
5804 * Test case to test the upgrading of a microzap to fatzap.
5806 void
5807 ztest_fzap(ztest_ds_t *zd, uint64_t id)
5809 objset_t *os = zd->zd_os;
5810 ztest_od_t *od;
5811 uint64_t object, txg, value;
5813 od = umem_alloc(sizeof (ztest_od_t), UMEM_NOFAIL);
5814 ztest_od_init(od, id, FTAG, 0, DMU_OT_ZAP_OTHER, 0, 0, 0);
5816 if (ztest_object_init(zd, od, sizeof (ztest_od_t),
5817 !ztest_random(2)) != 0)
5818 goto out;
5819 object = od->od_object;
5822 * Add entries to this ZAP and make sure it spills over
5823 * and gets upgraded to a fatzap. Also, since we are adding
5824 * 2050 entries we should see ptrtbl growth and leaf-block split.
5826 for (value = 0; value < 2050; value++) {
5827 char name[ZFS_MAX_DATASET_NAME_LEN];
5828 dmu_tx_t *tx;
5829 int error;
5831 (void) snprintf(name, sizeof (name), "fzap-%"PRIu64"-%"PRIu64"",
5832 id, value);
5834 tx = dmu_tx_create(os);
5835 dmu_tx_hold_zap(tx, object, B_TRUE, name);
5836 txg = ztest_tx_assign(tx, TXG_MIGHTWAIT, FTAG);
5837 if (txg == 0)
5838 goto out;
5839 error = zap_add(os, object, name, sizeof (uint64_t), 1,
5840 &value, tx);
5841 ASSERT(error == 0 || error == EEXIST);
5842 dmu_tx_commit(tx);
5844 out:
5845 umem_free(od, sizeof (ztest_od_t));
5848 void
5849 ztest_zap_parallel(ztest_ds_t *zd, uint64_t id)
5851 (void) id;
5852 objset_t *os = zd->zd_os;
5853 ztest_od_t *od;
5854 uint64_t txg, object, count, wsize, wc, zl_wsize, zl_wc;
5855 dmu_tx_t *tx;
5856 int i, namelen, error;
5857 int micro = ztest_random(2);
5858 char name[20], string_value[20];
5859 void *data;
5861 od = umem_alloc(sizeof (ztest_od_t), UMEM_NOFAIL);
5862 ztest_od_init(od, ID_PARALLEL, FTAG, micro, DMU_OT_ZAP_OTHER, 0, 0, 0);
5864 if (ztest_object_init(zd, od, sizeof (ztest_od_t), B_FALSE) != 0) {
5865 umem_free(od, sizeof (ztest_od_t));
5866 return;
5869 object = od->od_object;
5872 * Generate a random name of the form 'xxx.....' where each
5873 * x is a random printable character and the dots are dots.
5874 * There are 94 such characters, and the name length goes from
5875 * 6 to 20, so there are 94^3 * 15 = 12,458,760 possible names.
5877 namelen = ztest_random(sizeof (name) - 5) + 5 + 1;
5879 for (i = 0; i < 3; i++)
5880 name[i] = '!' + ztest_random('~' - '!' + 1);
5881 for (; i < namelen - 1; i++)
5882 name[i] = '.';
5883 name[i] = '\0';
5885 if ((namelen & 1) || micro) {
5886 wsize = sizeof (txg);
5887 wc = 1;
5888 data = &txg;
5889 } else {
5890 wsize = 1;
5891 wc = namelen;
5892 data = string_value;
5895 count = -1ULL;
5896 VERIFY0(zap_count(os, object, &count));
5897 ASSERT3S(count, !=, -1ULL);
5900 * Select an operation: length, lookup, add, update, remove.
5902 i = ztest_random(5);
5904 if (i >= 2) {
5905 tx = dmu_tx_create(os);
5906 dmu_tx_hold_zap(tx, object, B_TRUE, NULL);
5907 txg = ztest_tx_assign(tx, TXG_MIGHTWAIT, FTAG);
5908 if (txg == 0) {
5909 umem_free(od, sizeof (ztest_od_t));
5910 return;
5912 memcpy(string_value, name, namelen);
5913 } else {
5914 tx = NULL;
5915 txg = 0;
5916 memset(string_value, 0, namelen);
5919 switch (i) {
5921 case 0:
5922 error = zap_length(os, object, name, &zl_wsize, &zl_wc);
5923 if (error == 0) {
5924 ASSERT3U(wsize, ==, zl_wsize);
5925 ASSERT3U(wc, ==, zl_wc);
5926 } else {
5927 ASSERT3U(error, ==, ENOENT);
5929 break;
5931 case 1:
5932 error = zap_lookup(os, object, name, wsize, wc, data);
5933 if (error == 0) {
5934 if (data == string_value &&
5935 memcmp(name, data, namelen) != 0)
5936 fatal(B_FALSE, "name '%s' != val '%s' len %d",
5937 name, (char *)data, namelen);
5938 } else {
5939 ASSERT3U(error, ==, ENOENT);
5941 break;
5943 case 2:
5944 error = zap_add(os, object, name, wsize, wc, data, tx);
5945 ASSERT(error == 0 || error == EEXIST);
5946 break;
5948 case 3:
5949 VERIFY0(zap_update(os, object, name, wsize, wc, data, tx));
5950 break;
5952 case 4:
5953 error = zap_remove(os, object, name, tx);
5954 ASSERT(error == 0 || error == ENOENT);
5955 break;
5958 if (tx != NULL)
5959 dmu_tx_commit(tx);
5961 umem_free(od, sizeof (ztest_od_t));
5965 * Commit callback data.
5967 typedef struct ztest_cb_data {
5968 list_node_t zcd_node;
5969 uint64_t zcd_txg;
5970 int zcd_expected_err;
5971 boolean_t zcd_added;
5972 boolean_t zcd_called;
5973 spa_t *zcd_spa;
5974 } ztest_cb_data_t;
5976 /* This is the actual commit callback function */
5977 static void
5978 ztest_commit_callback(void *arg, int error)
5980 ztest_cb_data_t *data = arg;
5981 uint64_t synced_txg;
5983 VERIFY3P(data, !=, NULL);
5984 VERIFY3S(data->zcd_expected_err, ==, error);
5985 VERIFY(!data->zcd_called);
5987 synced_txg = spa_last_synced_txg(data->zcd_spa);
5988 if (data->zcd_txg > synced_txg)
5989 fatal(B_FALSE,
5990 "commit callback of txg %"PRIu64" called prematurely, "
5991 "last synced txg = %"PRIu64"\n",
5992 data->zcd_txg, synced_txg);
5994 data->zcd_called = B_TRUE;
5996 if (error == ECANCELED) {
5997 ASSERT0(data->zcd_txg);
5998 ASSERT(!data->zcd_added);
6001 * The private callback data should be destroyed here, but
6002 * since we are going to check the zcd_called field after
6003 * dmu_tx_abort(), we will destroy it there.
6005 return;
6008 ASSERT(data->zcd_added);
6009 ASSERT3U(data->zcd_txg, !=, 0);
6011 (void) mutex_enter(&zcl.zcl_callbacks_lock);
6013 /* See if this cb was called more quickly */
6014 if ((synced_txg - data->zcd_txg) < zc_min_txg_delay)
6015 zc_min_txg_delay = synced_txg - data->zcd_txg;
6017 /* Remove our callback from the list */
6018 list_remove(&zcl.zcl_callbacks, data);
6020 (void) mutex_exit(&zcl.zcl_callbacks_lock);
6022 umem_free(data, sizeof (ztest_cb_data_t));
6025 /* Allocate and initialize callback data structure */
6026 static ztest_cb_data_t *
6027 ztest_create_cb_data(objset_t *os, uint64_t txg)
6029 ztest_cb_data_t *cb_data;
6031 cb_data = umem_zalloc(sizeof (ztest_cb_data_t), UMEM_NOFAIL);
6033 cb_data->zcd_txg = txg;
6034 cb_data->zcd_spa = dmu_objset_spa(os);
6035 list_link_init(&cb_data->zcd_node);
6037 return (cb_data);
6041 * Commit callback test.
6043 void
6044 ztest_dmu_commit_callbacks(ztest_ds_t *zd, uint64_t id)
6046 objset_t *os = zd->zd_os;
6047 ztest_od_t *od;
6048 dmu_tx_t *tx;
6049 ztest_cb_data_t *cb_data[3], *tmp_cb;
6050 uint64_t old_txg, txg;
6051 int i, error = 0;
6053 od = umem_alloc(sizeof (ztest_od_t), UMEM_NOFAIL);
6054 ztest_od_init(od, id, FTAG, 0, DMU_OT_UINT64_OTHER, 0, 0, 0);
6056 if (ztest_object_init(zd, od, sizeof (ztest_od_t), B_FALSE) != 0) {
6057 umem_free(od, sizeof (ztest_od_t));
6058 return;
6061 tx = dmu_tx_create(os);
6063 cb_data[0] = ztest_create_cb_data(os, 0);
6064 dmu_tx_callback_register(tx, ztest_commit_callback, cb_data[0]);
6066 dmu_tx_hold_write(tx, od->od_object, 0, sizeof (uint64_t));
6068 /* Every once in a while, abort the transaction on purpose */
6069 if (ztest_random(100) == 0)
6070 error = -1;
6072 if (!error)
6073 error = dmu_tx_assign(tx, TXG_NOWAIT);
6075 txg = error ? 0 : dmu_tx_get_txg(tx);
6077 cb_data[0]->zcd_txg = txg;
6078 cb_data[1] = ztest_create_cb_data(os, txg);
6079 dmu_tx_callback_register(tx, ztest_commit_callback, cb_data[1]);
6081 if (error) {
6083 * It's not a strict requirement to call the registered
6084 * callbacks from inside dmu_tx_abort(), but that's what
6085 * it's supposed to happen in the current implementation
6086 * so we will check for that.
6088 for (i = 0; i < 2; i++) {
6089 cb_data[i]->zcd_expected_err = ECANCELED;
6090 VERIFY(!cb_data[i]->zcd_called);
6093 dmu_tx_abort(tx);
6095 for (i = 0; i < 2; i++) {
6096 VERIFY(cb_data[i]->zcd_called);
6097 umem_free(cb_data[i], sizeof (ztest_cb_data_t));
6100 umem_free(od, sizeof (ztest_od_t));
6101 return;
6104 cb_data[2] = ztest_create_cb_data(os, txg);
6105 dmu_tx_callback_register(tx, ztest_commit_callback, cb_data[2]);
6108 * Read existing data to make sure there isn't a future leak.
6110 VERIFY0(dmu_read(os, od->od_object, 0, sizeof (uint64_t),
6111 &old_txg, DMU_READ_PREFETCH));
6113 if (old_txg > txg)
6114 fatal(B_FALSE,
6115 "future leak: got %"PRIu64", open txg is %"PRIu64"",
6116 old_txg, txg);
6118 dmu_write(os, od->od_object, 0, sizeof (uint64_t), &txg, tx);
6120 (void) mutex_enter(&zcl.zcl_callbacks_lock);
6123 * Since commit callbacks don't have any ordering requirement and since
6124 * it is theoretically possible for a commit callback to be called
6125 * after an arbitrary amount of time has elapsed since its txg has been
6126 * synced, it is difficult to reliably determine whether a commit
6127 * callback hasn't been called due to high load or due to a flawed
6128 * implementation.
6130 * In practice, we will assume that if after a certain number of txgs a
6131 * commit callback hasn't been called, then most likely there's an
6132 * implementation bug..
6134 tmp_cb = list_head(&zcl.zcl_callbacks);
6135 if (tmp_cb != NULL &&
6136 tmp_cb->zcd_txg + ZTEST_COMMIT_CB_THRESH < txg) {
6137 fatal(B_FALSE,
6138 "Commit callback threshold exceeded, "
6139 "oldest txg: %"PRIu64", open txg: %"PRIu64"\n",
6140 tmp_cb->zcd_txg, txg);
6144 * Let's find the place to insert our callbacks.
6146 * Even though the list is ordered by txg, it is possible for the
6147 * insertion point to not be the end because our txg may already be
6148 * quiescing at this point and other callbacks in the open txg
6149 * (from other objsets) may have sneaked in.
6151 tmp_cb = list_tail(&zcl.zcl_callbacks);
6152 while (tmp_cb != NULL && tmp_cb->zcd_txg > txg)
6153 tmp_cb = list_prev(&zcl.zcl_callbacks, tmp_cb);
6155 /* Add the 3 callbacks to the list */
6156 for (i = 0; i < 3; i++) {
6157 if (tmp_cb == NULL)
6158 list_insert_head(&zcl.zcl_callbacks, cb_data[i]);
6159 else
6160 list_insert_after(&zcl.zcl_callbacks, tmp_cb,
6161 cb_data[i]);
6163 cb_data[i]->zcd_added = B_TRUE;
6164 VERIFY(!cb_data[i]->zcd_called);
6166 tmp_cb = cb_data[i];
6169 zc_cb_counter += 3;
6171 (void) mutex_exit(&zcl.zcl_callbacks_lock);
6173 dmu_tx_commit(tx);
6175 umem_free(od, sizeof (ztest_od_t));
6179 * Visit each object in the dataset. Verify that its properties
6180 * are consistent what was stored in the block tag when it was created,
6181 * and that its unused bonus buffer space has not been overwritten.
6183 void
6184 ztest_verify_dnode_bt(ztest_ds_t *zd, uint64_t id)
6186 (void) id;
6187 objset_t *os = zd->zd_os;
6188 uint64_t obj;
6189 int err = 0;
6191 for (obj = 0; err == 0; err = dmu_object_next(os, &obj, FALSE, 0)) {
6192 ztest_block_tag_t *bt = NULL;
6193 dmu_object_info_t doi;
6194 dmu_buf_t *db;
6196 ztest_object_lock(zd, obj, ZTRL_READER);
6197 if (dmu_bonus_hold(os, obj, FTAG, &db) != 0) {
6198 ztest_object_unlock(zd, obj);
6199 continue;
6202 dmu_object_info_from_db(db, &doi);
6203 if (doi.doi_bonus_size >= sizeof (*bt))
6204 bt = ztest_bt_bonus(db);
6206 if (bt && bt->bt_magic == BT_MAGIC) {
6207 ztest_bt_verify(bt, os, obj, doi.doi_dnodesize,
6208 bt->bt_offset, bt->bt_gen, bt->bt_txg,
6209 bt->bt_crtxg);
6210 ztest_verify_unused_bonus(db, bt, obj, os, bt->bt_gen);
6213 dmu_buf_rele(db, FTAG);
6214 ztest_object_unlock(zd, obj);
6218 void
6219 ztest_dsl_prop_get_set(ztest_ds_t *zd, uint64_t id)
6221 (void) id;
6222 zfs_prop_t proplist[] = {
6223 ZFS_PROP_CHECKSUM,
6224 ZFS_PROP_COMPRESSION,
6225 ZFS_PROP_COPIES,
6226 ZFS_PROP_DEDUP
6229 (void) pthread_rwlock_rdlock(&ztest_name_lock);
6231 for (int p = 0; p < sizeof (proplist) / sizeof (proplist[0]); p++) {
6232 int error = ztest_dsl_prop_set_uint64(zd->zd_name, proplist[p],
6233 ztest_random_dsl_prop(proplist[p]), (int)ztest_random(2));
6234 ASSERT(error == 0 || error == ENOSPC);
6237 int error = ztest_dsl_prop_set_uint64(zd->zd_name, ZFS_PROP_RECORDSIZE,
6238 ztest_random_blocksize(), (int)ztest_random(2));
6239 ASSERT(error == 0 || error == ENOSPC);
6241 (void) pthread_rwlock_unlock(&ztest_name_lock);
6244 void
6245 ztest_spa_prop_get_set(ztest_ds_t *zd, uint64_t id)
6247 (void) zd, (void) id;
6249 (void) pthread_rwlock_rdlock(&ztest_name_lock);
6251 (void) ztest_spa_prop_set_uint64(ZPOOL_PROP_AUTOTRIM, ztest_random(2));
6253 nvlist_t *props = fnvlist_alloc();
6255 VERIFY0(spa_prop_get(ztest_spa, props));
6257 if (ztest_opts.zo_verbose >= 6)
6258 dump_nvlist(props, 4);
6260 fnvlist_free(props);
6262 (void) pthread_rwlock_unlock(&ztest_name_lock);
6265 static int
6266 user_release_one(const char *snapname, const char *holdname)
6268 nvlist_t *snaps, *holds;
6269 int error;
6271 snaps = fnvlist_alloc();
6272 holds = fnvlist_alloc();
6273 fnvlist_add_boolean(holds, holdname);
6274 fnvlist_add_nvlist(snaps, snapname, holds);
6275 fnvlist_free(holds);
6276 error = dsl_dataset_user_release(snaps, NULL);
6277 fnvlist_free(snaps);
6278 return (error);
6282 * Test snapshot hold/release and deferred destroy.
6284 void
6285 ztest_dmu_snapshot_hold(ztest_ds_t *zd, uint64_t id)
6287 int error;
6288 objset_t *os = zd->zd_os;
6289 objset_t *origin;
6290 char snapname[100];
6291 char fullname[100];
6292 char clonename[100];
6293 char tag[100];
6294 char osname[ZFS_MAX_DATASET_NAME_LEN];
6295 nvlist_t *holds;
6297 (void) pthread_rwlock_rdlock(&ztest_name_lock);
6299 dmu_objset_name(os, osname);
6301 (void) snprintf(snapname, sizeof (snapname), "sh1_%"PRIu64"", id);
6302 (void) snprintf(fullname, sizeof (fullname), "%s@%s", osname, snapname);
6303 (void) snprintf(clonename, sizeof (clonename), "%s/ch1_%"PRIu64"",
6304 osname, id);
6305 (void) snprintf(tag, sizeof (tag), "tag_%"PRIu64"", id);
6308 * Clean up from any previous run.
6310 error = dsl_destroy_head(clonename);
6311 if (error != ENOENT)
6312 ASSERT0(error);
6313 error = user_release_one(fullname, tag);
6314 if (error != ESRCH && error != ENOENT)
6315 ASSERT0(error);
6316 error = dsl_destroy_snapshot(fullname, B_FALSE);
6317 if (error != ENOENT)
6318 ASSERT0(error);
6321 * Create snapshot, clone it, mark snap for deferred destroy,
6322 * destroy clone, verify snap was also destroyed.
6324 error = dmu_objset_snapshot_one(osname, snapname);
6325 if (error) {
6326 if (error == ENOSPC) {
6327 ztest_record_enospc("dmu_objset_snapshot");
6328 goto out;
6330 fatal(B_FALSE, "dmu_objset_snapshot(%s) = %d", fullname, error);
6333 error = dmu_objset_clone(clonename, fullname);
6334 if (error) {
6335 if (error == ENOSPC) {
6336 ztest_record_enospc("dmu_objset_clone");
6337 goto out;
6339 fatal(B_FALSE, "dmu_objset_clone(%s) = %d", clonename, error);
6342 error = dsl_destroy_snapshot(fullname, B_TRUE);
6343 if (error) {
6344 fatal(B_FALSE, "dsl_destroy_snapshot(%s, B_TRUE) = %d",
6345 fullname, error);
6348 error = dsl_destroy_head(clonename);
6349 if (error)
6350 fatal(B_FALSE, "dsl_destroy_head(%s) = %d", clonename, error);
6352 error = dmu_objset_hold(fullname, FTAG, &origin);
6353 if (error != ENOENT)
6354 fatal(B_FALSE, "dmu_objset_hold(%s) = %d", fullname, error);
6357 * Create snapshot, add temporary hold, verify that we can't
6358 * destroy a held snapshot, mark for deferred destroy,
6359 * release hold, verify snapshot was destroyed.
6361 error = dmu_objset_snapshot_one(osname, snapname);
6362 if (error) {
6363 if (error == ENOSPC) {
6364 ztest_record_enospc("dmu_objset_snapshot");
6365 goto out;
6367 fatal(B_FALSE, "dmu_objset_snapshot(%s) = %d", fullname, error);
6370 holds = fnvlist_alloc();
6371 fnvlist_add_string(holds, fullname, tag);
6372 error = dsl_dataset_user_hold(holds, 0, NULL);
6373 fnvlist_free(holds);
6375 if (error == ENOSPC) {
6376 ztest_record_enospc("dsl_dataset_user_hold");
6377 goto out;
6378 } else if (error) {
6379 fatal(B_FALSE, "dsl_dataset_user_hold(%s, %s) = %u",
6380 fullname, tag, error);
6383 error = dsl_destroy_snapshot(fullname, B_FALSE);
6384 if (error != EBUSY) {
6385 fatal(B_FALSE, "dsl_destroy_snapshot(%s, B_FALSE) = %d",
6386 fullname, error);
6389 error = dsl_destroy_snapshot(fullname, B_TRUE);
6390 if (error) {
6391 fatal(B_FALSE, "dsl_destroy_snapshot(%s, B_TRUE) = %d",
6392 fullname, error);
6395 error = user_release_one(fullname, tag);
6396 if (error)
6397 fatal(B_FALSE, "user_release_one(%s, %s) = %d",
6398 fullname, tag, error);
6400 VERIFY3U(dmu_objset_hold(fullname, FTAG, &origin), ==, ENOENT);
6402 out:
6403 (void) pthread_rwlock_unlock(&ztest_name_lock);
6407 * Inject random faults into the on-disk data.
6409 void
6410 ztest_fault_inject(ztest_ds_t *zd, uint64_t id)
6412 (void) zd, (void) id;
6413 ztest_shared_t *zs = ztest_shared;
6414 spa_t *spa = ztest_spa;
6415 int fd;
6416 uint64_t offset;
6417 uint64_t leaves;
6418 uint64_t bad = 0x1990c0ffeedecadeull;
6419 uint64_t top, leaf;
6420 uint64_t raidz_children;
6421 char *path0;
6422 char *pathrand;
6423 size_t fsize;
6424 int bshift = SPA_MAXBLOCKSHIFT + 2;
6425 int iters = 1000;
6426 int maxfaults;
6427 int mirror_save;
6428 vdev_t *vd0 = NULL;
6429 uint64_t guid0 = 0;
6430 boolean_t islog = B_FALSE;
6431 boolean_t injected = B_FALSE;
6433 path0 = umem_alloc(MAXPATHLEN, UMEM_NOFAIL);
6434 pathrand = umem_alloc(MAXPATHLEN, UMEM_NOFAIL);
6436 mutex_enter(&ztest_vdev_lock);
6439 * Device removal is in progress, fault injection must be disabled
6440 * until it completes and the pool is scrubbed. The fault injection
6441 * strategy for damaging blocks does not take in to account evacuated
6442 * blocks which may have already been damaged.
6444 if (ztest_device_removal_active)
6445 goto out;
6448 * The fault injection strategy for damaging blocks cannot be used
6449 * if raidz expansion is in progress. The leaves value
6450 * (attached raidz children) is variable and strategy for damaging
6451 * blocks will corrupt same data blocks on different child vdevs
6452 * because of the reflow process.
6454 if (spa->spa_raidz_expand != NULL)
6455 goto out;
6457 maxfaults = MAXFAULTS(zs);
6458 raidz_children = ztest_get_raidz_children(spa);
6459 leaves = MAX(zs->zs_mirrors, 1) * raidz_children;
6460 mirror_save = zs->zs_mirrors;
6462 ASSERT3U(leaves, >=, 1);
6465 * While ztest is running the number of leaves will not change. This
6466 * is critical for the fault injection logic as it determines where
6467 * errors can be safely injected such that they are always repairable.
6469 * When restarting ztest a different number of leaves may be requested
6470 * which will shift the regions to be damaged. This is fine as long
6471 * as the pool has been scrubbed prior to using the new mapping.
6472 * Failure to do can result in non-repairable damage being injected.
6474 if (ztest_pool_scrubbed == B_FALSE)
6475 goto out;
6478 * Grab the name lock as reader. There are some operations
6479 * which don't like to have their vdevs changed while
6480 * they are in progress (i.e. spa_change_guid). Those
6481 * operations will have grabbed the name lock as writer.
6483 (void) pthread_rwlock_rdlock(&ztest_name_lock);
6486 * We need SCL_STATE here because we're going to look at vd0->vdev_tsd.
6488 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
6490 if (ztest_random(2) == 0) {
6492 * Inject errors on a normal data device or slog device.
6494 top = ztest_random_vdev_top(spa, B_TRUE);
6495 leaf = ztest_random(leaves) + zs->zs_splits;
6498 * Generate paths to the first leaf in this top-level vdev,
6499 * and to the random leaf we selected. We'll induce transient
6500 * write failures and random online/offline activity on leaf 0,
6501 * and we'll write random garbage to the randomly chosen leaf.
6503 (void) snprintf(path0, MAXPATHLEN, ztest_dev_template,
6504 ztest_opts.zo_dir, ztest_opts.zo_pool,
6505 top * leaves + zs->zs_splits);
6506 (void) snprintf(pathrand, MAXPATHLEN, ztest_dev_template,
6507 ztest_opts.zo_dir, ztest_opts.zo_pool,
6508 top * leaves + leaf);
6510 vd0 = vdev_lookup_by_path(spa->spa_root_vdev, path0);
6511 if (vd0 != NULL && vd0->vdev_top->vdev_islog)
6512 islog = B_TRUE;
6515 * If the top-level vdev needs to be resilvered
6516 * then we only allow faults on the device that is
6517 * resilvering.
6519 if (vd0 != NULL && maxfaults != 1 &&
6520 (!vdev_resilver_needed(vd0->vdev_top, NULL, NULL) ||
6521 vd0->vdev_resilver_txg != 0)) {
6523 * Make vd0 explicitly claim to be unreadable,
6524 * or unwritable, or reach behind its back
6525 * and close the underlying fd. We can do this if
6526 * maxfaults == 0 because we'll fail and reexecute,
6527 * and we can do it if maxfaults >= 2 because we'll
6528 * have enough redundancy. If maxfaults == 1, the
6529 * combination of this with injection of random data
6530 * corruption below exceeds the pool's fault tolerance.
6532 vdev_file_t *vf = vd0->vdev_tsd;
6534 zfs_dbgmsg("injecting fault to vdev %llu; maxfaults=%d",
6535 (long long)vd0->vdev_id, (int)maxfaults);
6537 if (vf != NULL && ztest_random(3) == 0) {
6538 (void) close(vf->vf_file->f_fd);
6539 vf->vf_file->f_fd = -1;
6540 } else if (ztest_random(2) == 0) {
6541 vd0->vdev_cant_read = B_TRUE;
6542 } else {
6543 vd0->vdev_cant_write = B_TRUE;
6545 guid0 = vd0->vdev_guid;
6547 } else {
6549 * Inject errors on an l2cache device.
6551 spa_aux_vdev_t *sav = &spa->spa_l2cache;
6553 if (sav->sav_count == 0) {
6554 spa_config_exit(spa, SCL_STATE, FTAG);
6555 (void) pthread_rwlock_unlock(&ztest_name_lock);
6556 goto out;
6558 vd0 = sav->sav_vdevs[ztest_random(sav->sav_count)];
6559 guid0 = vd0->vdev_guid;
6560 (void) strlcpy(path0, vd0->vdev_path, MAXPATHLEN);
6561 (void) strlcpy(pathrand, vd0->vdev_path, MAXPATHLEN);
6563 leaf = 0;
6564 leaves = 1;
6565 maxfaults = INT_MAX; /* no limit on cache devices */
6568 spa_config_exit(spa, SCL_STATE, FTAG);
6569 (void) pthread_rwlock_unlock(&ztest_name_lock);
6572 * If we can tolerate two or more faults, or we're dealing
6573 * with a slog, randomly online/offline vd0.
6575 if ((maxfaults >= 2 || islog) && guid0 != 0) {
6576 if (ztest_random(10) < 6) {
6577 int flags = (ztest_random(2) == 0 ?
6578 ZFS_OFFLINE_TEMPORARY : 0);
6581 * We have to grab the zs_name_lock as writer to
6582 * prevent a race between offlining a slog and
6583 * destroying a dataset. Offlining the slog will
6584 * grab a reference on the dataset which may cause
6585 * dsl_destroy_head() to fail with EBUSY thus
6586 * leaving the dataset in an inconsistent state.
6588 if (islog)
6589 (void) pthread_rwlock_wrlock(&ztest_name_lock);
6591 VERIFY3U(vdev_offline(spa, guid0, flags), !=, EBUSY);
6593 if (islog)
6594 (void) pthread_rwlock_unlock(&ztest_name_lock);
6595 } else {
6597 * Ideally we would like to be able to randomly
6598 * call vdev_[on|off]line without holding locks
6599 * to force unpredictable failures but the side
6600 * effects of vdev_[on|off]line prevent us from
6601 * doing so.
6603 (void) vdev_online(spa, guid0, 0, NULL);
6607 if (maxfaults == 0)
6608 goto out;
6611 * We have at least single-fault tolerance, so inject data corruption.
6613 fd = open(pathrand, O_RDWR);
6615 if (fd == -1) /* we hit a gap in the device namespace */
6616 goto out;
6618 fsize = lseek(fd, 0, SEEK_END);
6620 while (--iters != 0) {
6622 * The offset must be chosen carefully to ensure that
6623 * we do not inject a given logical block with errors
6624 * on two different leaf devices, because ZFS can not
6625 * tolerate that (if maxfaults==1).
6627 * To achieve this we divide each leaf device into
6628 * chunks of size (# leaves * SPA_MAXBLOCKSIZE * 4).
6629 * Each chunk is further divided into error-injection
6630 * ranges (can accept errors) and clear ranges (we do
6631 * not inject errors in those). Each error-injection
6632 * range can accept errors only for a single leaf vdev.
6633 * Error-injection ranges are separated by clear ranges.
6635 * For example, with 3 leaves, each chunk looks like:
6636 * 0 to 32M: injection range for leaf 0
6637 * 32M to 64M: clear range - no injection allowed
6638 * 64M to 96M: injection range for leaf 1
6639 * 96M to 128M: clear range - no injection allowed
6640 * 128M to 160M: injection range for leaf 2
6641 * 160M to 192M: clear range - no injection allowed
6643 * Each clear range must be large enough such that a
6644 * single block cannot straddle it. This way a block
6645 * can't be a target in two different injection ranges
6646 * (on different leaf vdevs).
6648 offset = ztest_random(fsize / (leaves << bshift)) *
6649 (leaves << bshift) + (leaf << bshift) +
6650 (ztest_random(1ULL << (bshift - 1)) & -8ULL);
6653 * Only allow damage to the labels at one end of the vdev.
6655 * If all labels are damaged, the device will be totally
6656 * inaccessible, which will result in loss of data,
6657 * because we also damage (parts of) the other side of
6658 * the mirror/raidz.
6660 * Additionally, we will always have both an even and an
6661 * odd label, so that we can handle crashes in the
6662 * middle of vdev_config_sync().
6664 if ((leaf & 1) == 0 && offset < VDEV_LABEL_START_SIZE)
6665 continue;
6668 * The two end labels are stored at the "end" of the disk, but
6669 * the end of the disk (vdev_psize) is aligned to
6670 * sizeof (vdev_label_t).
6672 uint64_t psize = P2ALIGN_TYPED(fsize, sizeof (vdev_label_t),
6673 uint64_t);
6674 if ((leaf & 1) == 1 &&
6675 offset + sizeof (bad) > psize - VDEV_LABEL_END_SIZE)
6676 continue;
6678 if (mirror_save != zs->zs_mirrors) {
6679 (void) close(fd);
6680 goto out;
6683 if (pwrite(fd, &bad, sizeof (bad), offset) != sizeof (bad))
6684 fatal(B_TRUE,
6685 "can't inject bad word at 0x%"PRIx64" in %s",
6686 offset, pathrand);
6688 if (ztest_opts.zo_verbose >= 7)
6689 (void) printf("injected bad word into %s,"
6690 " offset 0x%"PRIx64"\n", pathrand, offset);
6692 injected = B_TRUE;
6695 (void) close(fd);
6696 out:
6697 mutex_exit(&ztest_vdev_lock);
6699 if (injected && ztest_opts.zo_raid_do_expand) {
6700 int error = spa_scan(spa, POOL_SCAN_SCRUB);
6701 if (error == 0) {
6702 while (dsl_scan_scrubbing(spa_get_dsl(spa)))
6703 txg_wait_synced(spa_get_dsl(spa), 0);
6707 umem_free(path0, MAXPATHLEN);
6708 umem_free(pathrand, MAXPATHLEN);
6712 * By design ztest will never inject uncorrectable damage in to the pool.
6713 * Issue a scrub, wait for it to complete, and verify there is never any
6714 * persistent damage.
6716 * Only after a full scrub has been completed is it safe to start injecting
6717 * data corruption. See the comment in zfs_fault_inject().
6719 static int
6720 ztest_scrub_impl(spa_t *spa)
6722 int error = spa_scan(spa, POOL_SCAN_SCRUB);
6723 if (error)
6724 return (error);
6726 while (dsl_scan_scrubbing(spa_get_dsl(spa)))
6727 txg_wait_synced(spa_get_dsl(spa), 0);
6729 if (spa_approx_errlog_size(spa) > 0)
6730 return (ECKSUM);
6732 ztest_pool_scrubbed = B_TRUE;
6734 return (0);
6738 * Scrub the pool.
6740 void
6741 ztest_scrub(ztest_ds_t *zd, uint64_t id)
6743 (void) zd, (void) id;
6744 spa_t *spa = ztest_spa;
6745 int error;
6748 * Scrub in progress by device removal.
6750 if (ztest_device_removal_active)
6751 return;
6754 * Start a scrub, wait a moment, then force a restart.
6756 (void) spa_scan(spa, POOL_SCAN_SCRUB);
6757 (void) poll(NULL, 0, 100);
6759 error = ztest_scrub_impl(spa);
6760 if (error == EBUSY)
6761 error = 0;
6762 ASSERT0(error);
6766 * Change the guid for the pool.
6768 void
6769 ztest_reguid(ztest_ds_t *zd, uint64_t id)
6771 (void) zd, (void) id;
6772 spa_t *spa = ztest_spa;
6773 uint64_t orig, load;
6774 int error;
6775 ztest_shared_t *zs = ztest_shared;
6777 if (ztest_opts.zo_mmp_test)
6778 return;
6780 orig = spa_guid(spa);
6781 load = spa_load_guid(spa);
6783 (void) pthread_rwlock_wrlock(&ztest_name_lock);
6784 error = spa_change_guid(spa, NULL);
6785 zs->zs_guid = spa_guid(spa);
6786 (void) pthread_rwlock_unlock(&ztest_name_lock);
6788 if (error != 0)
6789 return;
6791 if (ztest_opts.zo_verbose >= 4) {
6792 (void) printf("Changed guid old %"PRIu64" -> %"PRIu64"\n",
6793 orig, spa_guid(spa));
6796 VERIFY3U(orig, !=, spa_guid(spa));
6797 VERIFY3U(load, ==, spa_load_guid(spa));
6800 void
6801 ztest_blake3(ztest_ds_t *zd, uint64_t id)
6803 (void) zd, (void) id;
6804 hrtime_t end = gethrtime() + NANOSEC;
6805 zio_cksum_salt_t salt;
6806 void *salt_ptr = &salt.zcs_bytes;
6807 struct abd *abd_data, *abd_meta;
6808 void *buf, *templ;
6809 int i, *ptr;
6810 uint32_t size;
6811 BLAKE3_CTX ctx;
6812 const zfs_impl_t *blake3 = zfs_impl_get_ops("blake3");
6814 size = ztest_random_blocksize();
6815 buf = umem_alloc(size, UMEM_NOFAIL);
6816 abd_data = abd_alloc(size, B_FALSE);
6817 abd_meta = abd_alloc(size, B_TRUE);
6819 for (i = 0, ptr = buf; i < size / sizeof (*ptr); i++, ptr++)
6820 *ptr = ztest_random(UINT_MAX);
6821 memset(salt_ptr, 'A', 32);
6823 abd_copy_from_buf_off(abd_data, buf, 0, size);
6824 abd_copy_from_buf_off(abd_meta, buf, 0, size);
6826 while (gethrtime() <= end) {
6827 int run_count = 100;
6828 zio_cksum_t zc_ref1, zc_ref2;
6829 zio_cksum_t zc_res1, zc_res2;
6831 void *ref1 = &zc_ref1;
6832 void *ref2 = &zc_ref2;
6833 void *res1 = &zc_res1;
6834 void *res2 = &zc_res2;
6836 /* BLAKE3_KEY_LEN = 32 */
6837 VERIFY0(blake3->setname("generic"));
6838 templ = abd_checksum_blake3_tmpl_init(&salt);
6839 Blake3_InitKeyed(&ctx, salt_ptr);
6840 Blake3_Update(&ctx, buf, size);
6841 Blake3_Final(&ctx, ref1);
6842 zc_ref2 = zc_ref1;
6843 ZIO_CHECKSUM_BSWAP(&zc_ref2);
6844 abd_checksum_blake3_tmpl_free(templ);
6846 VERIFY0(blake3->setname("cycle"));
6847 while (run_count-- > 0) {
6849 /* Test current implementation */
6850 Blake3_InitKeyed(&ctx, salt_ptr);
6851 Blake3_Update(&ctx, buf, size);
6852 Blake3_Final(&ctx, res1);
6853 zc_res2 = zc_res1;
6854 ZIO_CHECKSUM_BSWAP(&zc_res2);
6856 VERIFY0(memcmp(ref1, res1, 32));
6857 VERIFY0(memcmp(ref2, res2, 32));
6859 /* Test ABD - data */
6860 templ = abd_checksum_blake3_tmpl_init(&salt);
6861 abd_checksum_blake3_native(abd_data, size,
6862 templ, &zc_res1);
6863 abd_checksum_blake3_byteswap(abd_data, size,
6864 templ, &zc_res2);
6866 VERIFY0(memcmp(ref1, res1, 32));
6867 VERIFY0(memcmp(ref2, res2, 32));
6869 /* Test ABD - metadata */
6870 abd_checksum_blake3_native(abd_meta, size,
6871 templ, &zc_res1);
6872 abd_checksum_blake3_byteswap(abd_meta, size,
6873 templ, &zc_res2);
6874 abd_checksum_blake3_tmpl_free(templ);
6876 VERIFY0(memcmp(ref1, res1, 32));
6877 VERIFY0(memcmp(ref2, res2, 32));
6882 abd_free(abd_data);
6883 abd_free(abd_meta);
6884 umem_free(buf, size);
6887 void
6888 ztest_fletcher(ztest_ds_t *zd, uint64_t id)
6890 (void) zd, (void) id;
6891 hrtime_t end = gethrtime() + NANOSEC;
6893 while (gethrtime() <= end) {
6894 int run_count = 100;
6895 void *buf;
6896 struct abd *abd_data, *abd_meta;
6897 uint32_t size;
6898 int *ptr;
6899 int i;
6900 zio_cksum_t zc_ref;
6901 zio_cksum_t zc_ref_byteswap;
6903 size = ztest_random_blocksize();
6905 buf = umem_alloc(size, UMEM_NOFAIL);
6906 abd_data = abd_alloc(size, B_FALSE);
6907 abd_meta = abd_alloc(size, B_TRUE);
6909 for (i = 0, ptr = buf; i < size / sizeof (*ptr); i++, ptr++)
6910 *ptr = ztest_random(UINT_MAX);
6912 abd_copy_from_buf_off(abd_data, buf, 0, size);
6913 abd_copy_from_buf_off(abd_meta, buf, 0, size);
6915 VERIFY0(fletcher_4_impl_set("scalar"));
6916 fletcher_4_native(buf, size, NULL, &zc_ref);
6917 fletcher_4_byteswap(buf, size, NULL, &zc_ref_byteswap);
6919 VERIFY0(fletcher_4_impl_set("cycle"));
6920 while (run_count-- > 0) {
6921 zio_cksum_t zc;
6922 zio_cksum_t zc_byteswap;
6924 fletcher_4_byteswap(buf, size, NULL, &zc_byteswap);
6925 fletcher_4_native(buf, size, NULL, &zc);
6927 VERIFY0(memcmp(&zc, &zc_ref, sizeof (zc)));
6928 VERIFY0(memcmp(&zc_byteswap, &zc_ref_byteswap,
6929 sizeof (zc_byteswap)));
6931 /* Test ABD - data */
6932 abd_fletcher_4_byteswap(abd_data, size, NULL,
6933 &zc_byteswap);
6934 abd_fletcher_4_native(abd_data, size, NULL, &zc);
6936 VERIFY0(memcmp(&zc, &zc_ref, sizeof (zc)));
6937 VERIFY0(memcmp(&zc_byteswap, &zc_ref_byteswap,
6938 sizeof (zc_byteswap)));
6940 /* Test ABD - metadata */
6941 abd_fletcher_4_byteswap(abd_meta, size, NULL,
6942 &zc_byteswap);
6943 abd_fletcher_4_native(abd_meta, size, NULL, &zc);
6945 VERIFY0(memcmp(&zc, &zc_ref, sizeof (zc)));
6946 VERIFY0(memcmp(&zc_byteswap, &zc_ref_byteswap,
6947 sizeof (zc_byteswap)));
6951 umem_free(buf, size);
6952 abd_free(abd_data);
6953 abd_free(abd_meta);
6957 void
6958 ztest_fletcher_incr(ztest_ds_t *zd, uint64_t id)
6960 (void) zd, (void) id;
6961 void *buf;
6962 size_t size;
6963 int *ptr;
6964 int i;
6965 zio_cksum_t zc_ref;
6966 zio_cksum_t zc_ref_bswap;
6968 hrtime_t end = gethrtime() + NANOSEC;
6970 while (gethrtime() <= end) {
6971 int run_count = 100;
6973 size = ztest_random_blocksize();
6974 buf = umem_alloc(size, UMEM_NOFAIL);
6976 for (i = 0, ptr = buf; i < size / sizeof (*ptr); i++, ptr++)
6977 *ptr = ztest_random(UINT_MAX);
6979 VERIFY0(fletcher_4_impl_set("scalar"));
6980 fletcher_4_native(buf, size, NULL, &zc_ref);
6981 fletcher_4_byteswap(buf, size, NULL, &zc_ref_bswap);
6983 VERIFY0(fletcher_4_impl_set("cycle"));
6985 while (run_count-- > 0) {
6986 zio_cksum_t zc;
6987 zio_cksum_t zc_bswap;
6988 size_t pos = 0;
6990 ZIO_SET_CHECKSUM(&zc, 0, 0, 0, 0);
6991 ZIO_SET_CHECKSUM(&zc_bswap, 0, 0, 0, 0);
6993 while (pos < size) {
6994 size_t inc = 64 * ztest_random(size / 67);
6995 /* sometimes add few bytes to test non-simd */
6996 if (ztest_random(100) < 10)
6997 inc += P2ALIGN_TYPED(ztest_random(64),
6998 sizeof (uint32_t), uint64_t);
7000 if (inc > (size - pos))
7001 inc = size - pos;
7003 fletcher_4_incremental_native(buf + pos, inc,
7004 &zc);
7005 fletcher_4_incremental_byteswap(buf + pos, inc,
7006 &zc_bswap);
7008 pos += inc;
7011 VERIFY3U(pos, ==, size);
7013 VERIFY(ZIO_CHECKSUM_EQUAL(zc, zc_ref));
7014 VERIFY(ZIO_CHECKSUM_EQUAL(zc_bswap, zc_ref_bswap));
7017 * verify if incremental on the whole buffer is
7018 * equivalent to non-incremental version
7020 ZIO_SET_CHECKSUM(&zc, 0, 0, 0, 0);
7021 ZIO_SET_CHECKSUM(&zc_bswap, 0, 0, 0, 0);
7023 fletcher_4_incremental_native(buf, size, &zc);
7024 fletcher_4_incremental_byteswap(buf, size, &zc_bswap);
7026 VERIFY(ZIO_CHECKSUM_EQUAL(zc, zc_ref));
7027 VERIFY(ZIO_CHECKSUM_EQUAL(zc_bswap, zc_ref_bswap));
7030 umem_free(buf, size);
7034 void
7035 ztest_pool_prefetch_ddt(ztest_ds_t *zd, uint64_t id)
7037 (void) zd, (void) id;
7038 spa_t *spa;
7040 (void) pthread_rwlock_rdlock(&ztest_name_lock);
7041 VERIFY0(spa_open(ztest_opts.zo_pool, &spa, FTAG));
7043 ddt_prefetch_all(spa);
7045 spa_close(spa, FTAG);
7046 (void) pthread_rwlock_unlock(&ztest_name_lock);
7049 static int
7050 ztest_set_global_vars(void)
7052 for (size_t i = 0; i < ztest_opts.zo_gvars_count; i++) {
7053 char *kv = ztest_opts.zo_gvars[i];
7054 VERIFY3U(strlen(kv), <=, ZO_GVARS_MAX_ARGLEN);
7055 VERIFY3U(strlen(kv), >, 0);
7056 int err = set_global_var(kv);
7057 if (ztest_opts.zo_verbose > 0) {
7058 (void) printf("setting global var %s ... %s\n", kv,
7059 err ? "failed" : "ok");
7061 if (err != 0) {
7062 (void) fprintf(stderr,
7063 "failed to set global var '%s'\n", kv);
7064 return (err);
7067 return (0);
7070 static char **
7071 ztest_global_vars_to_zdb_args(void)
7073 char **args = calloc(2*ztest_opts.zo_gvars_count + 1, sizeof (char *));
7074 char **cur = args;
7075 if (args == NULL)
7076 return (NULL);
7077 for (size_t i = 0; i < ztest_opts.zo_gvars_count; i++) {
7078 *cur++ = (char *)"-o";
7079 *cur++ = ztest_opts.zo_gvars[i];
7081 ASSERT3P(cur, ==, &args[2*ztest_opts.zo_gvars_count]);
7082 *cur = NULL;
7083 return (args);
7086 /* The end of strings is indicated by a NULL element */
7087 static char *
7088 join_strings(char **strings, const char *sep)
7090 size_t totallen = 0;
7091 for (char **sp = strings; *sp != NULL; sp++) {
7092 totallen += strlen(*sp);
7093 totallen += strlen(sep);
7095 if (totallen > 0) {
7096 ASSERT(totallen >= strlen(sep));
7097 totallen -= strlen(sep);
7100 size_t buflen = totallen + 1;
7101 char *o = umem_alloc(buflen, UMEM_NOFAIL); /* trailing 0 byte */
7102 o[0] = '\0';
7103 for (char **sp = strings; *sp != NULL; sp++) {
7104 size_t would;
7105 would = strlcat(o, *sp, buflen);
7106 VERIFY3U(would, <, buflen);
7107 if (*(sp+1) == NULL) {
7108 break;
7110 would = strlcat(o, sep, buflen);
7111 VERIFY3U(would, <, buflen);
7113 ASSERT3S(strlen(o), ==, totallen);
7114 return (o);
7117 static int
7118 ztest_check_path(char *path)
7120 struct stat s;
7121 /* return true on success */
7122 return (!stat(path, &s));
7125 static void
7126 ztest_get_zdb_bin(char *bin, int len)
7128 char *zdb_path;
7130 * Try to use $ZDB and in-tree zdb path. If not successful, just
7131 * let popen to search through PATH.
7133 if ((zdb_path = getenv("ZDB"))) {
7134 strlcpy(bin, zdb_path, len); /* In env */
7135 if (!ztest_check_path(bin)) {
7136 ztest_dump_core = 0;
7137 fatal(B_TRUE, "invalid ZDB '%s'", bin);
7139 return;
7142 VERIFY3P(realpath(getexecname(), bin), !=, NULL);
7143 if (strstr(bin, ".libs/ztest")) {
7144 strstr(bin, ".libs/ztest")[0] = '\0'; /* In-tree */
7145 strcat(bin, "zdb");
7146 if (ztest_check_path(bin))
7147 return;
7149 strcpy(bin, "zdb");
7152 static vdev_t *
7153 ztest_random_concrete_vdev_leaf(vdev_t *vd)
7155 if (vd == NULL)
7156 return (NULL);
7158 if (vd->vdev_children == 0)
7159 return (vd);
7161 vdev_t *eligible[vd->vdev_children];
7162 int eligible_idx = 0, i;
7163 for (i = 0; i < vd->vdev_children; i++) {
7164 vdev_t *cvd = vd->vdev_child[i];
7165 if (cvd->vdev_top->vdev_removing)
7166 continue;
7167 if (cvd->vdev_children > 0 ||
7168 (vdev_is_concrete(cvd) && !cvd->vdev_detached)) {
7169 eligible[eligible_idx++] = cvd;
7172 VERIFY3S(eligible_idx, >, 0);
7174 uint64_t child_no = ztest_random(eligible_idx);
7175 return (ztest_random_concrete_vdev_leaf(eligible[child_no]));
7178 void
7179 ztest_initialize(ztest_ds_t *zd, uint64_t id)
7181 (void) zd, (void) id;
7182 spa_t *spa = ztest_spa;
7183 int error = 0;
7185 mutex_enter(&ztest_vdev_lock);
7187 spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
7189 /* Random leaf vdev */
7190 vdev_t *rand_vd = ztest_random_concrete_vdev_leaf(spa->spa_root_vdev);
7191 if (rand_vd == NULL) {
7192 spa_config_exit(spa, SCL_VDEV, FTAG);
7193 mutex_exit(&ztest_vdev_lock);
7194 return;
7198 * The random vdev we've selected may change as soon as we
7199 * drop the spa_config_lock. We create local copies of things
7200 * we're interested in.
7202 uint64_t guid = rand_vd->vdev_guid;
7203 char *path = strdup(rand_vd->vdev_path);
7204 boolean_t active = rand_vd->vdev_initialize_thread != NULL;
7206 zfs_dbgmsg("vd %px, guid %llu", rand_vd, (u_longlong_t)guid);
7207 spa_config_exit(spa, SCL_VDEV, FTAG);
7209 uint64_t cmd = ztest_random(POOL_INITIALIZE_FUNCS);
7211 nvlist_t *vdev_guids = fnvlist_alloc();
7212 nvlist_t *vdev_errlist = fnvlist_alloc();
7213 fnvlist_add_uint64(vdev_guids, path, guid);
7214 error = spa_vdev_initialize(spa, vdev_guids, cmd, vdev_errlist);
7215 fnvlist_free(vdev_guids);
7216 fnvlist_free(vdev_errlist);
7218 switch (cmd) {
7219 case POOL_INITIALIZE_CANCEL:
7220 if (ztest_opts.zo_verbose >= 4) {
7221 (void) printf("Cancel initialize %s", path);
7222 if (!active)
7223 (void) printf(" failed (no initialize active)");
7224 (void) printf("\n");
7226 break;
7227 case POOL_INITIALIZE_START:
7228 if (ztest_opts.zo_verbose >= 4) {
7229 (void) printf("Start initialize %s", path);
7230 if (active && error == 0)
7231 (void) printf(" failed (already active)");
7232 else if (error != 0)
7233 (void) printf(" failed (error %d)", error);
7234 (void) printf("\n");
7236 break;
7237 case POOL_INITIALIZE_SUSPEND:
7238 if (ztest_opts.zo_verbose >= 4) {
7239 (void) printf("Suspend initialize %s", path);
7240 if (!active)
7241 (void) printf(" failed (no initialize active)");
7242 (void) printf("\n");
7244 break;
7246 free(path);
7247 mutex_exit(&ztest_vdev_lock);
7250 void
7251 ztest_trim(ztest_ds_t *zd, uint64_t id)
7253 (void) zd, (void) id;
7254 spa_t *spa = ztest_spa;
7255 int error = 0;
7257 mutex_enter(&ztest_vdev_lock);
7259 spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
7261 /* Random leaf vdev */
7262 vdev_t *rand_vd = ztest_random_concrete_vdev_leaf(spa->spa_root_vdev);
7263 if (rand_vd == NULL) {
7264 spa_config_exit(spa, SCL_VDEV, FTAG);
7265 mutex_exit(&ztest_vdev_lock);
7266 return;
7270 * The random vdev we've selected may change as soon as we
7271 * drop the spa_config_lock. We create local copies of things
7272 * we're interested in.
7274 uint64_t guid = rand_vd->vdev_guid;
7275 char *path = strdup(rand_vd->vdev_path);
7276 boolean_t active = rand_vd->vdev_trim_thread != NULL;
7278 zfs_dbgmsg("vd %p, guid %llu", rand_vd, (u_longlong_t)guid);
7279 spa_config_exit(spa, SCL_VDEV, FTAG);
7281 uint64_t cmd = ztest_random(POOL_TRIM_FUNCS);
7282 uint64_t rate = 1 << ztest_random(30);
7283 boolean_t partial = (ztest_random(5) > 0);
7284 boolean_t secure = (ztest_random(5) > 0);
7286 nvlist_t *vdev_guids = fnvlist_alloc();
7287 nvlist_t *vdev_errlist = fnvlist_alloc();
7288 fnvlist_add_uint64(vdev_guids, path, guid);
7289 error = spa_vdev_trim(spa, vdev_guids, cmd, rate, partial,
7290 secure, vdev_errlist);
7291 fnvlist_free(vdev_guids);
7292 fnvlist_free(vdev_errlist);
7294 switch (cmd) {
7295 case POOL_TRIM_CANCEL:
7296 if (ztest_opts.zo_verbose >= 4) {
7297 (void) printf("Cancel TRIM %s", path);
7298 if (!active)
7299 (void) printf(" failed (no TRIM active)");
7300 (void) printf("\n");
7302 break;
7303 case POOL_TRIM_START:
7304 if (ztest_opts.zo_verbose >= 4) {
7305 (void) printf("Start TRIM %s", path);
7306 if (active && error == 0)
7307 (void) printf(" failed (already active)");
7308 else if (error != 0)
7309 (void) printf(" failed (error %d)", error);
7310 (void) printf("\n");
7312 break;
7313 case POOL_TRIM_SUSPEND:
7314 if (ztest_opts.zo_verbose >= 4) {
7315 (void) printf("Suspend TRIM %s", path);
7316 if (!active)
7317 (void) printf(" failed (no TRIM active)");
7318 (void) printf("\n");
7320 break;
7322 free(path);
7323 mutex_exit(&ztest_vdev_lock);
7326 void
7327 ztest_ddt_prune(ztest_ds_t *zd, uint64_t id)
7329 (void) zd, (void) id;
7331 spa_t *spa = ztest_spa;
7332 uint64_t pct = ztest_random(15) + 1;
7334 (void) ddt_prune_unique_entries(spa, ZPOOL_DDT_PRUNE_PERCENTAGE, pct);
7338 * Verify pool integrity by running zdb.
7340 static void
7341 ztest_run_zdb(uint64_t guid)
7343 int status;
7344 char *bin;
7345 char *zdb;
7346 char *zbuf;
7347 const int len = MAXPATHLEN + MAXNAMELEN + 20;
7348 FILE *fp;
7350 bin = umem_alloc(len, UMEM_NOFAIL);
7351 zdb = umem_alloc(len, UMEM_NOFAIL);
7352 zbuf = umem_alloc(1024, UMEM_NOFAIL);
7354 ztest_get_zdb_bin(bin, len);
7356 char **set_gvars_args = ztest_global_vars_to_zdb_args();
7357 if (set_gvars_args == NULL) {
7358 fatal(B_FALSE, "Failed to allocate memory in "
7359 "ztest_global_vars_to_zdb_args(). Cannot run zdb.\n");
7361 char *set_gvars_args_joined = join_strings(set_gvars_args, " ");
7362 free(set_gvars_args);
7364 size_t would = snprintf(zdb, len,
7365 "%s -bcc%s%s -G -d -Y -e -y %s -p %s %"PRIu64,
7366 bin,
7367 ztest_opts.zo_verbose >= 3 ? "s" : "",
7368 ztest_opts.zo_verbose >= 4 ? "v" : "",
7369 set_gvars_args_joined,
7370 ztest_opts.zo_dir,
7371 guid);
7372 ASSERT3U(would, <, len);
7374 umem_free(set_gvars_args_joined, strlen(set_gvars_args_joined) + 1);
7376 if (ztest_opts.zo_verbose >= 5)
7377 (void) printf("Executing %s\n", zdb);
7379 fp = popen(zdb, "r");
7381 while (fgets(zbuf, 1024, fp) != NULL)
7382 if (ztest_opts.zo_verbose >= 3)
7383 (void) printf("%s", zbuf);
7385 status = pclose(fp);
7387 if (status == 0)
7388 goto out;
7390 ztest_dump_core = 0;
7391 if (WIFEXITED(status))
7392 fatal(B_FALSE, "'%s' exit code %d", zdb, WEXITSTATUS(status));
7393 else
7394 fatal(B_FALSE, "'%s' died with signal %d",
7395 zdb, WTERMSIG(status));
7396 out:
7397 umem_free(bin, len);
7398 umem_free(zdb, len);
7399 umem_free(zbuf, 1024);
7402 static void
7403 ztest_walk_pool_directory(const char *header)
7405 spa_t *spa = NULL;
7407 if (ztest_opts.zo_verbose >= 6)
7408 (void) puts(header);
7410 mutex_enter(&spa_namespace_lock);
7411 while ((spa = spa_next(spa)) != NULL)
7412 if (ztest_opts.zo_verbose >= 6)
7413 (void) printf("\t%s\n", spa_name(spa));
7414 mutex_exit(&spa_namespace_lock);
7417 static void
7418 ztest_spa_import_export(char *oldname, char *newname)
7420 nvlist_t *config, *newconfig;
7421 uint64_t pool_guid;
7422 spa_t *spa;
7423 int error;
7425 if (ztest_opts.zo_verbose >= 4) {
7426 (void) printf("import/export: old = %s, new = %s\n",
7427 oldname, newname);
7431 * Clean up from previous runs.
7433 (void) spa_destroy(newname);
7436 * Get the pool's configuration and guid.
7438 VERIFY0(spa_open(oldname, &spa, FTAG));
7441 * Kick off a scrub to tickle scrub/export races.
7443 if (ztest_random(2) == 0)
7444 (void) spa_scan(spa, POOL_SCAN_SCRUB);
7446 pool_guid = spa_guid(spa);
7447 spa_close(spa, FTAG);
7449 ztest_walk_pool_directory("pools before export");
7452 * Export it.
7454 VERIFY0(spa_export(oldname, &config, B_FALSE, B_FALSE));
7456 ztest_walk_pool_directory("pools after export");
7459 * Try to import it.
7461 newconfig = spa_tryimport(config);
7462 ASSERT3P(newconfig, !=, NULL);
7463 fnvlist_free(newconfig);
7466 * Import it under the new name.
7468 error = spa_import(newname, config, NULL, 0);
7469 if (error != 0) {
7470 dump_nvlist(config, 0);
7471 fatal(B_FALSE, "couldn't import pool %s as %s: error %u",
7472 oldname, newname, error);
7475 ztest_walk_pool_directory("pools after import");
7478 * Try to import it again -- should fail with EEXIST.
7480 VERIFY3U(EEXIST, ==, spa_import(newname, config, NULL, 0));
7483 * Try to import it under a different name -- should fail with EEXIST.
7485 VERIFY3U(EEXIST, ==, spa_import(oldname, config, NULL, 0));
7488 * Verify that the pool is no longer visible under the old name.
7490 VERIFY3U(ENOENT, ==, spa_open(oldname, &spa, FTAG));
7493 * Verify that we can open and close the pool using the new name.
7495 VERIFY0(spa_open(newname, &spa, FTAG));
7496 ASSERT3U(pool_guid, ==, spa_guid(spa));
7497 spa_close(spa, FTAG);
7499 fnvlist_free(config);
7502 static void
7503 ztest_resume(spa_t *spa)
7505 if (spa_suspended(spa) && ztest_opts.zo_verbose >= 6)
7506 (void) printf("resuming from suspended state\n");
7507 spa_vdev_state_enter(spa, SCL_NONE);
7508 vdev_clear(spa, NULL);
7509 (void) spa_vdev_state_exit(spa, NULL, 0);
7510 (void) zio_resume(spa);
7513 static __attribute__((noreturn)) void
7514 ztest_resume_thread(void *arg)
7516 spa_t *spa = arg;
7519 * Synthesize aged DDT entries for ddt prune testing
7521 ddt_prune_artificial_age = B_TRUE;
7522 if (ztest_opts.zo_verbose >= 3)
7523 ddt_dump_prune_histogram = B_TRUE;
7525 while (!ztest_exiting) {
7526 if (spa_suspended(spa))
7527 ztest_resume(spa);
7528 (void) poll(NULL, 0, 100);
7531 * Periodically change the zfs_compressed_arc_enabled setting.
7533 if (ztest_random(10) == 0)
7534 zfs_compressed_arc_enabled = ztest_random(2);
7537 * Periodically change the zfs_abd_scatter_enabled setting.
7539 if (ztest_random(10) == 0)
7540 zfs_abd_scatter_enabled = ztest_random(2);
7543 thread_exit();
7546 static __attribute__((noreturn)) void
7547 ztest_deadman_thread(void *arg)
7549 ztest_shared_t *zs = arg;
7550 spa_t *spa = ztest_spa;
7551 hrtime_t delay, overdue, last_run = gethrtime();
7553 delay = (zs->zs_thread_stop - zs->zs_thread_start) +
7554 MSEC2NSEC(zfs_deadman_synctime_ms);
7556 while (!ztest_exiting) {
7558 * Wait for the delay timer while checking occasionally
7559 * if we should stop.
7561 if (gethrtime() < last_run + delay) {
7562 (void) poll(NULL, 0, 1000);
7563 continue;
7567 * If the pool is suspended then fail immediately. Otherwise,
7568 * check to see if the pool is making any progress. If
7569 * vdev_deadman() discovers that there hasn't been any recent
7570 * I/Os then it will end up aborting the tests.
7572 if (spa_suspended(spa) || spa->spa_root_vdev == NULL) {
7573 fatal(B_FALSE,
7574 "aborting test after %llu seconds because "
7575 "pool has transitioned to a suspended state.",
7576 (u_longlong_t)zfs_deadman_synctime_ms / 1000);
7578 vdev_deadman(spa->spa_root_vdev, FTAG);
7581 * If the process doesn't complete within a grace period of
7582 * zfs_deadman_synctime_ms over the expected finish time,
7583 * then it may be hung and is terminated.
7585 overdue = zs->zs_proc_stop + MSEC2NSEC(zfs_deadman_synctime_ms);
7586 if (gethrtime() > overdue) {
7587 fatal(B_FALSE,
7588 "aborting test after %llu seconds because "
7589 "the process is overdue for termination.",
7590 (gethrtime() - zs->zs_proc_start) / NANOSEC);
7593 (void) printf("ztest has been running for %lld seconds\n",
7594 (gethrtime() - zs->zs_proc_start) / NANOSEC);
7596 last_run = gethrtime();
7597 delay = MSEC2NSEC(zfs_deadman_checktime_ms);
7600 thread_exit();
7603 static void
7604 ztest_execute(int test, ztest_info_t *zi, uint64_t id)
7606 ztest_ds_t *zd = &ztest_ds[id % ztest_opts.zo_datasets];
7607 ztest_shared_callstate_t *zc = ZTEST_GET_SHARED_CALLSTATE(test);
7608 hrtime_t functime = gethrtime();
7609 int i;
7611 for (i = 0; i < zi->zi_iters; i++)
7612 zi->zi_func(zd, id);
7614 functime = gethrtime() - functime;
7616 atomic_add_64(&zc->zc_count, 1);
7617 atomic_add_64(&zc->zc_time, functime);
7619 if (ztest_opts.zo_verbose >= 4)
7620 (void) printf("%6.2f sec in %s\n",
7621 (double)functime / NANOSEC, zi->zi_funcname);
7624 typedef struct ztest_raidz_expand_io {
7625 uint64_t rzx_id;
7626 uint64_t rzx_amount;
7627 uint64_t rzx_bufsize;
7628 const void *rzx_buffer;
7629 uint64_t rzx_alloc_max;
7630 spa_t *rzx_spa;
7631 } ztest_expand_io_t;
7633 #undef OD_ARRAY_SIZE
7634 #define OD_ARRAY_SIZE 10
7637 * Write a request amount of data to some dataset objects.
7638 * There will be ztest_opts.zo_threads count of these running in parallel.
7640 static __attribute__((noreturn)) void
7641 ztest_rzx_thread(void *arg)
7643 ztest_expand_io_t *info = (ztest_expand_io_t *)arg;
7644 ztest_od_t *od;
7645 int batchsize;
7646 int od_size;
7647 ztest_ds_t *zd = &ztest_ds[info->rzx_id % ztest_opts.zo_datasets];
7648 spa_t *spa = info->rzx_spa;
7650 od_size = sizeof (ztest_od_t) * OD_ARRAY_SIZE;
7651 od = umem_alloc(od_size, UMEM_NOFAIL);
7652 batchsize = OD_ARRAY_SIZE;
7654 /* Create objects to write to */
7655 for (int b = 0; b < batchsize; b++) {
7656 ztest_od_init(od + b, info->rzx_id, FTAG, b,
7657 DMU_OT_UINT64_OTHER, 0, 0, 0);
7659 if (ztest_object_init(zd, od, od_size, B_FALSE) != 0) {
7660 umem_free(od, od_size);
7661 thread_exit();
7664 for (uint64_t offset = 0, written = 0; written < info->rzx_amount;
7665 offset += info->rzx_bufsize) {
7666 /* write to 10 objects */
7667 for (int i = 0; i < batchsize && written < info->rzx_amount;
7668 i++) {
7669 (void) pthread_rwlock_rdlock(&zd->zd_zilog_lock);
7670 ztest_write(zd, od[i].od_object, offset,
7671 info->rzx_bufsize, info->rzx_buffer);
7672 (void) pthread_rwlock_unlock(&zd->zd_zilog_lock);
7673 written += info->rzx_bufsize;
7675 txg_wait_synced(spa_get_dsl(spa), 0);
7676 /* due to inflation, we'll typically bail here */
7677 if (metaslab_class_get_alloc(spa_normal_class(spa)) >
7678 info->rzx_alloc_max) {
7679 break;
7683 /* Remove a few objects to leave some holes in allocation space */
7684 mutex_enter(&zd->zd_dirobj_lock);
7685 (void) ztest_remove(zd, od, 2);
7686 mutex_exit(&zd->zd_dirobj_lock);
7688 umem_free(od, od_size);
7690 thread_exit();
7693 static __attribute__((noreturn)) void
7694 ztest_thread(void *arg)
7696 int rand;
7697 uint64_t id = (uintptr_t)arg;
7698 ztest_shared_t *zs = ztest_shared;
7699 uint64_t call_next;
7700 hrtime_t now;
7701 ztest_info_t *zi;
7702 ztest_shared_callstate_t *zc;
7704 while ((now = gethrtime()) < zs->zs_thread_stop) {
7706 * See if it's time to force a crash.
7708 if (now > zs->zs_thread_kill &&
7709 raidz_expand_pause_point == RAIDZ_EXPAND_PAUSE_NONE) {
7710 ztest_kill(zs);
7714 * If we're getting ENOSPC with some regularity, stop.
7716 if (zs->zs_enospc_count > 10)
7717 break;
7720 * Pick a random function to execute.
7722 rand = ztest_random(ZTEST_FUNCS);
7723 zi = &ztest_info[rand];
7724 zc = ZTEST_GET_SHARED_CALLSTATE(rand);
7725 call_next = zc->zc_next;
7727 if (now >= call_next &&
7728 atomic_cas_64(&zc->zc_next, call_next, call_next +
7729 ztest_random(2 * zi->zi_interval[0] + 1)) == call_next) {
7730 ztest_execute(rand, zi, id);
7734 thread_exit();
7737 static void
7738 ztest_dataset_name(char *dsname, const char *pool, int d)
7740 (void) snprintf(dsname, ZFS_MAX_DATASET_NAME_LEN, "%s/ds_%d", pool, d);
7743 static void
7744 ztest_dataset_destroy(int d)
7746 char name[ZFS_MAX_DATASET_NAME_LEN];
7747 int t;
7749 ztest_dataset_name(name, ztest_opts.zo_pool, d);
7751 if (ztest_opts.zo_verbose >= 3)
7752 (void) printf("Destroying %s to free up space\n", name);
7755 * Cleanup any non-standard clones and snapshots. In general,
7756 * ztest thread t operates on dataset (t % zopt_datasets),
7757 * so there may be more than one thing to clean up.
7759 for (t = d; t < ztest_opts.zo_threads;
7760 t += ztest_opts.zo_datasets)
7761 ztest_dsl_dataset_cleanup(name, t);
7763 (void) dmu_objset_find(name, ztest_objset_destroy_cb, NULL,
7764 DS_FIND_SNAPSHOTS | DS_FIND_CHILDREN);
7767 static void
7768 ztest_dataset_dirobj_verify(ztest_ds_t *zd)
7770 uint64_t usedobjs, dirobjs, scratch;
7773 * ZTEST_DIROBJ is the object directory for the entire dataset.
7774 * Therefore, the number of objects in use should equal the
7775 * number of ZTEST_DIROBJ entries, +1 for ZTEST_DIROBJ itself.
7776 * If not, we have an object leak.
7778 * Note that we can only check this in ztest_dataset_open(),
7779 * when the open-context and syncing-context values agree.
7780 * That's because zap_count() returns the open-context value,
7781 * while dmu_objset_space() returns the rootbp fill count.
7783 VERIFY0(zap_count(zd->zd_os, ZTEST_DIROBJ, &dirobjs));
7784 dmu_objset_space(zd->zd_os, &scratch, &scratch, &usedobjs, &scratch);
7785 ASSERT3U(dirobjs + 1, ==, usedobjs);
7788 static int
7789 ztest_dataset_open(int d)
7791 ztest_ds_t *zd = &ztest_ds[d];
7792 uint64_t committed_seq = ZTEST_GET_SHARED_DS(d)->zd_seq;
7793 objset_t *os;
7794 zilog_t *zilog;
7795 char name[ZFS_MAX_DATASET_NAME_LEN];
7796 int error;
7798 ztest_dataset_name(name, ztest_opts.zo_pool, d);
7800 (void) pthread_rwlock_rdlock(&ztest_name_lock);
7802 error = ztest_dataset_create(name);
7803 if (error == ENOSPC) {
7804 (void) pthread_rwlock_unlock(&ztest_name_lock);
7805 ztest_record_enospc(FTAG);
7806 return (error);
7808 ASSERT(error == 0 || error == EEXIST);
7810 VERIFY0(ztest_dmu_objset_own(name, DMU_OST_OTHER, B_FALSE,
7811 B_TRUE, zd, &os));
7812 (void) pthread_rwlock_unlock(&ztest_name_lock);
7814 ztest_zd_init(zd, ZTEST_GET_SHARED_DS(d), os);
7816 zilog = zd->zd_zilog;
7818 if (zilog->zl_header->zh_claim_lr_seq != 0 &&
7819 zilog->zl_header->zh_claim_lr_seq < committed_seq)
7820 fatal(B_FALSE, "missing log records: "
7821 "claimed %"PRIu64" < committed %"PRIu64"",
7822 zilog->zl_header->zh_claim_lr_seq, committed_seq);
7824 ztest_dataset_dirobj_verify(zd);
7826 zil_replay(os, zd, ztest_replay_vector);
7828 ztest_dataset_dirobj_verify(zd);
7830 if (ztest_opts.zo_verbose >= 6)
7831 (void) printf("%s replay %"PRIu64" blocks, "
7832 "%"PRIu64" records, seq %"PRIu64"\n",
7833 zd->zd_name,
7834 zilog->zl_parse_blk_count,
7835 zilog->zl_parse_lr_count,
7836 zilog->zl_replaying_seq);
7838 zilog = zil_open(os, ztest_get_data, NULL);
7840 if (zilog->zl_replaying_seq != 0 &&
7841 zilog->zl_replaying_seq < committed_seq)
7842 fatal(B_FALSE, "missing log records: "
7843 "replayed %"PRIu64" < committed %"PRIu64"",
7844 zilog->zl_replaying_seq, committed_seq);
7846 return (0);
7849 static void
7850 ztest_dataset_close(int d)
7852 ztest_ds_t *zd = &ztest_ds[d];
7854 zil_close(zd->zd_zilog);
7855 dmu_objset_disown(zd->zd_os, B_TRUE, zd);
7857 ztest_zd_fini(zd);
7860 static int
7861 ztest_replay_zil_cb(const char *name, void *arg)
7863 (void) arg;
7864 objset_t *os;
7865 ztest_ds_t *zdtmp;
7867 VERIFY0(ztest_dmu_objset_own(name, DMU_OST_ANY, B_TRUE,
7868 B_TRUE, FTAG, &os));
7870 zdtmp = umem_alloc(sizeof (ztest_ds_t), UMEM_NOFAIL);
7872 ztest_zd_init(zdtmp, NULL, os);
7873 zil_replay(os, zdtmp, ztest_replay_vector);
7874 ztest_zd_fini(zdtmp);
7876 if (dmu_objset_zil(os)->zl_parse_lr_count != 0 &&
7877 ztest_opts.zo_verbose >= 6) {
7878 zilog_t *zilog = dmu_objset_zil(os);
7880 (void) printf("%s replay %"PRIu64" blocks, "
7881 "%"PRIu64" records, seq %"PRIu64"\n",
7882 name,
7883 zilog->zl_parse_blk_count,
7884 zilog->zl_parse_lr_count,
7885 zilog->zl_replaying_seq);
7888 umem_free(zdtmp, sizeof (ztest_ds_t));
7890 dmu_objset_disown(os, B_TRUE, FTAG);
7891 return (0);
7894 static void
7895 ztest_freeze(void)
7897 ztest_ds_t *zd = &ztest_ds[0];
7898 spa_t *spa;
7899 int numloops = 0;
7901 /* freeze not supported during RAIDZ expansion */
7902 if (ztest_opts.zo_raid_do_expand)
7903 return;
7905 if (ztest_opts.zo_verbose >= 3)
7906 (void) printf("testing spa_freeze()...\n");
7908 raidz_scratch_verify();
7909 kernel_init(SPA_MODE_READ | SPA_MODE_WRITE);
7910 VERIFY0(spa_open(ztest_opts.zo_pool, &spa, FTAG));
7911 VERIFY0(ztest_dataset_open(0));
7912 ztest_spa = spa;
7915 * Force the first log block to be transactionally allocated.
7916 * We have to do this before we freeze the pool -- otherwise
7917 * the log chain won't be anchored.
7919 while (BP_IS_HOLE(&zd->zd_zilog->zl_header->zh_log)) {
7920 ztest_dmu_object_alloc_free(zd, 0);
7921 zil_commit(zd->zd_zilog, 0);
7924 txg_wait_synced(spa_get_dsl(spa), 0);
7927 * Freeze the pool. This stops spa_sync() from doing anything,
7928 * so that the only way to record changes from now on is the ZIL.
7930 spa_freeze(spa);
7933 * Because it is hard to predict how much space a write will actually
7934 * require beforehand, we leave ourselves some fudge space to write over
7935 * capacity.
7937 uint64_t capacity = metaslab_class_get_space(spa_normal_class(spa)) / 2;
7940 * Run tests that generate log records but don't alter the pool config
7941 * or depend on DSL sync tasks (snapshots, objset create/destroy, etc).
7942 * We do a txg_wait_synced() after each iteration to force the txg
7943 * to increase well beyond the last synced value in the uberblock.
7944 * The ZIL should be OK with that.
7946 * Run a random number of times less than zo_maxloops and ensure we do
7947 * not run out of space on the pool.
7949 while (ztest_random(10) != 0 &&
7950 numloops++ < ztest_opts.zo_maxloops &&
7951 metaslab_class_get_alloc(spa_normal_class(spa)) < capacity) {
7952 ztest_od_t od;
7953 ztest_od_init(&od, 0, FTAG, 0, DMU_OT_UINT64_OTHER, 0, 0, 0);
7954 VERIFY0(ztest_object_init(zd, &od, sizeof (od), B_FALSE));
7955 ztest_io(zd, od.od_object,
7956 ztest_random(ZTEST_RANGE_LOCKS) << SPA_MAXBLOCKSHIFT);
7957 txg_wait_synced(spa_get_dsl(spa), 0);
7961 * Commit all of the changes we just generated.
7963 zil_commit(zd->zd_zilog, 0);
7964 txg_wait_synced(spa_get_dsl(spa), 0);
7967 * Close our dataset and close the pool.
7969 ztest_dataset_close(0);
7970 spa_close(spa, FTAG);
7971 kernel_fini();
7974 * Open and close the pool and dataset to induce log replay.
7976 raidz_scratch_verify();
7977 kernel_init(SPA_MODE_READ | SPA_MODE_WRITE);
7978 VERIFY0(spa_open(ztest_opts.zo_pool, &spa, FTAG));
7979 ASSERT3U(spa_freeze_txg(spa), ==, UINT64_MAX);
7980 VERIFY0(ztest_dataset_open(0));
7981 ztest_spa = spa;
7982 txg_wait_synced(spa_get_dsl(spa), 0);
7983 ztest_dataset_close(0);
7984 ztest_reguid(NULL, 0);
7986 spa_close(spa, FTAG);
7987 kernel_fini();
7990 static void
7991 ztest_import_impl(void)
7993 importargs_t args = { 0 };
7994 nvlist_t *cfg = NULL;
7995 int nsearch = 1;
7996 char *searchdirs[nsearch];
7997 int flags = ZFS_IMPORT_MISSING_LOG;
7999 searchdirs[0] = ztest_opts.zo_dir;
8000 args.paths = nsearch;
8001 args.path = searchdirs;
8002 args.can_be_active = B_FALSE;
8004 libpc_handle_t lpch = {
8005 .lpc_lib_handle = NULL,
8006 .lpc_ops = &libzpool_config_ops,
8007 .lpc_printerr = B_TRUE
8009 VERIFY0(zpool_find_config(&lpch, ztest_opts.zo_pool, &cfg, &args));
8010 VERIFY0(spa_import(ztest_opts.zo_pool, cfg, NULL, flags));
8011 fnvlist_free(cfg);
8015 * Import a storage pool with the given name.
8017 static void
8018 ztest_import(ztest_shared_t *zs)
8020 spa_t *spa;
8022 mutex_init(&ztest_vdev_lock, NULL, MUTEX_DEFAULT, NULL);
8023 mutex_init(&ztest_checkpoint_lock, NULL, MUTEX_DEFAULT, NULL);
8024 VERIFY0(pthread_rwlock_init(&ztest_name_lock, NULL));
8026 raidz_scratch_verify();
8027 kernel_init(SPA_MODE_READ | SPA_MODE_WRITE);
8029 ztest_import_impl();
8031 VERIFY0(spa_open(ztest_opts.zo_pool, &spa, FTAG));
8032 zs->zs_metaslab_sz =
8033 1ULL << spa->spa_root_vdev->vdev_child[0]->vdev_ms_shift;
8034 zs->zs_guid = spa_guid(spa);
8035 spa_close(spa, FTAG);
8037 kernel_fini();
8039 if (!ztest_opts.zo_mmp_test) {
8040 ztest_run_zdb(zs->zs_guid);
8041 ztest_freeze();
8042 ztest_run_zdb(zs->zs_guid);
8045 (void) pthread_rwlock_destroy(&ztest_name_lock);
8046 mutex_destroy(&ztest_vdev_lock);
8047 mutex_destroy(&ztest_checkpoint_lock);
8051 * After the expansion was killed, check that the pool is healthy
8053 static void
8054 ztest_raidz_expand_check(spa_t *spa)
8056 ASSERT3U(ztest_opts.zo_raidz_expand_test, ==, RAIDZ_EXPAND_KILLED);
8058 * Set pool check done flag, main program will run a zdb check
8059 * of the pool when we exit.
8061 ztest_shared_opts->zo_raidz_expand_test = RAIDZ_EXPAND_CHECKED;
8063 /* Wait for reflow to finish */
8064 if (ztest_opts.zo_verbose >= 1) {
8065 (void) printf("\nwaiting for reflow to finish ...\n");
8067 pool_raidz_expand_stat_t rzx_stats;
8068 pool_raidz_expand_stat_t *pres = &rzx_stats;
8069 do {
8070 txg_wait_synced(spa_get_dsl(spa), 0);
8071 (void) poll(NULL, 0, 500); /* wait 1/2 second */
8073 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
8074 (void) spa_raidz_expand_get_stats(spa, pres);
8075 spa_config_exit(spa, SCL_CONFIG, FTAG);
8076 } while (pres->pres_state != DSS_FINISHED &&
8077 pres->pres_reflowed < pres->pres_to_reflow);
8079 if (ztest_opts.zo_verbose >= 1) {
8080 (void) printf("verifying an interrupted raidz "
8081 "expansion using a pool scrub ...\n");
8083 /* Will fail here if there is non-recoverable corruption detected */
8084 VERIFY0(ztest_scrub_impl(spa));
8085 if (ztest_opts.zo_verbose >= 1) {
8086 (void) printf("raidz expansion scrub check complete\n");
8091 * Start a raidz expansion test. We run some I/O on the pool for a while
8092 * to get some data in the pool. Then we grow the raidz and
8093 * kill the test at the requested offset into the reflow, verifying that
8094 * doing such does not lead to pool corruption.
8096 static void
8097 ztest_raidz_expand_run(ztest_shared_t *zs, spa_t *spa)
8099 nvlist_t *root;
8100 pool_raidz_expand_stat_t rzx_stats;
8101 pool_raidz_expand_stat_t *pres = &rzx_stats;
8102 kthread_t **run_threads;
8103 vdev_t *cvd, *rzvd = spa->spa_root_vdev->vdev_child[0];
8104 int total_disks = rzvd->vdev_children;
8105 int data_disks = total_disks - vdev_get_nparity(rzvd);
8106 uint64_t alloc_goal;
8107 uint64_t csize;
8108 int error, t;
8109 int threads = ztest_opts.zo_threads;
8110 ztest_expand_io_t *thread_args;
8112 ASSERT3U(ztest_opts.zo_raidz_expand_test, !=, RAIDZ_EXPAND_NONE);
8113 ASSERT3P(rzvd->vdev_ops, ==, &vdev_raidz_ops);
8114 ztest_opts.zo_raidz_expand_test = RAIDZ_EXPAND_STARTED;
8116 /* Setup a 1 MiB buffer of random data */
8117 uint64_t bufsize = 1024 * 1024;
8118 void *buffer = umem_alloc(bufsize, UMEM_NOFAIL);
8120 if (read(ztest_fd_rand, buffer, bufsize) != bufsize) {
8121 fatal(B_TRUE, "short read from /dev/urandom");
8124 * Put some data in the pool and then attach a vdev to initiate
8125 * reflow.
8127 run_threads = umem_zalloc(threads * sizeof (kthread_t *), UMEM_NOFAIL);
8128 thread_args = umem_zalloc(threads * sizeof (ztest_expand_io_t),
8129 UMEM_NOFAIL);
8130 /* Aim for roughly 25% of allocatable space up to 1GB */
8131 alloc_goal = (vdev_get_min_asize(rzvd) * data_disks) / total_disks;
8132 alloc_goal = MIN(alloc_goal >> 2, 1024*1024*1024);
8133 if (ztest_opts.zo_verbose >= 1) {
8134 (void) printf("adding data to pool '%s', goal %llu bytes\n",
8135 ztest_opts.zo_pool, (u_longlong_t)alloc_goal);
8139 * Kick off all the I/O generators that run in parallel.
8141 for (t = 0; t < threads; t++) {
8142 if (t < ztest_opts.zo_datasets && ztest_dataset_open(t) != 0) {
8143 umem_free(run_threads, threads * sizeof (kthread_t *));
8144 umem_free(buffer, bufsize);
8145 return;
8147 thread_args[t].rzx_id = t;
8148 thread_args[t].rzx_amount = alloc_goal / threads;
8149 thread_args[t].rzx_bufsize = bufsize;
8150 thread_args[t].rzx_buffer = buffer;
8151 thread_args[t].rzx_alloc_max = alloc_goal;
8152 thread_args[t].rzx_spa = spa;
8153 run_threads[t] = thread_create(NULL, 0, ztest_rzx_thread,
8154 &thread_args[t], 0, NULL, TS_RUN | TS_JOINABLE,
8155 defclsyspri);
8159 * Wait for all of the writers to complete.
8161 for (t = 0; t < threads; t++)
8162 VERIFY0(thread_join(run_threads[t]));
8165 * Close all datasets. This must be done after all the threads
8166 * are joined so we can be sure none of the datasets are in-use
8167 * by any of the threads.
8169 for (t = 0; t < ztest_opts.zo_threads; t++) {
8170 if (t < ztest_opts.zo_datasets)
8171 ztest_dataset_close(t);
8174 txg_wait_synced(spa_get_dsl(spa), 0);
8176 zs->zs_alloc = metaslab_class_get_alloc(spa_normal_class(spa));
8177 zs->zs_space = metaslab_class_get_space(spa_normal_class(spa));
8179 umem_free(buffer, bufsize);
8180 umem_free(run_threads, threads * sizeof (kthread_t *));
8181 umem_free(thread_args, threads * sizeof (ztest_expand_io_t));
8183 /* Set our reflow target to 25%, 50% or 75% of allocated size */
8184 uint_t multiple = ztest_random(3) + 1;
8185 uint64_t reflow_max = (rzvd->vdev_stat.vs_alloc * multiple) / 4;
8186 raidz_expand_max_reflow_bytes = reflow_max;
8188 if (ztest_opts.zo_verbose >= 1) {
8189 (void) printf("running raidz expansion test, killing when "
8190 "reflow reaches %llu bytes (%u/4 of allocated space)\n",
8191 (u_longlong_t)reflow_max, multiple);
8194 /* XXX - do we want some I/O load during the reflow? */
8197 * Use a disk size that is larger than existing ones
8199 cvd = rzvd->vdev_child[0];
8200 csize = vdev_get_min_asize(cvd);
8201 csize += csize / 10;
8203 * Path to vdev to be attached
8205 char *newpath = umem_alloc(MAXPATHLEN, UMEM_NOFAIL);
8206 (void) snprintf(newpath, MAXPATHLEN, ztest_dev_template,
8207 ztest_opts.zo_dir, ztest_opts.zo_pool, rzvd->vdev_children);
8209 * Build the nvlist describing newpath.
8211 root = make_vdev_root(newpath, NULL, NULL, csize, ztest_get_ashift(),
8212 NULL, 0, 0, 1);
8214 * Expand the raidz vdev by attaching the new disk
8216 if (ztest_opts.zo_verbose >= 1) {
8217 (void) printf("expanding raidz: %d wide to %d wide with '%s'\n",
8218 (int)rzvd->vdev_children, (int)rzvd->vdev_children + 1,
8219 newpath);
8221 error = spa_vdev_attach(spa, rzvd->vdev_guid, root, B_FALSE, B_FALSE);
8222 nvlist_free(root);
8223 if (error != 0) {
8224 fatal(0, "raidz expand: attach (%s %llu) returned %d",
8225 newpath, (long long)csize, error);
8229 * Wait for reflow to begin
8231 while (spa->spa_raidz_expand == NULL) {
8232 txg_wait_synced(spa_get_dsl(spa), 0);
8233 (void) poll(NULL, 0, 100); /* wait 1/10 second */
8235 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
8236 (void) spa_raidz_expand_get_stats(spa, pres);
8237 spa_config_exit(spa, SCL_CONFIG, FTAG);
8238 while (pres->pres_state != DSS_SCANNING) {
8239 txg_wait_synced(spa_get_dsl(spa), 0);
8240 (void) poll(NULL, 0, 100); /* wait 1/10 second */
8241 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
8242 (void) spa_raidz_expand_get_stats(spa, pres);
8243 spa_config_exit(spa, SCL_CONFIG, FTAG);
8246 ASSERT3U(pres->pres_state, ==, DSS_SCANNING);
8247 ASSERT3U(pres->pres_to_reflow, !=, 0);
8249 * Set so when we are killed we go to raidz checking rather than
8250 * restarting test.
8252 ztest_shared_opts->zo_raidz_expand_test = RAIDZ_EXPAND_KILLED;
8253 if (ztest_opts.zo_verbose >= 1) {
8254 (void) printf("raidz expansion reflow started, waiting for "
8255 "%llu bytes to be copied\n", (u_longlong_t)reflow_max);
8259 * Wait for reflow maximum to be reached and then kill the test
8261 while (pres->pres_reflowed < reflow_max) {
8262 txg_wait_synced(spa_get_dsl(spa), 0);
8263 (void) poll(NULL, 0, 100); /* wait 1/10 second */
8264 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
8265 (void) spa_raidz_expand_get_stats(spa, pres);
8266 spa_config_exit(spa, SCL_CONFIG, FTAG);
8269 /* Reset the reflow pause before killing */
8270 raidz_expand_max_reflow_bytes = 0;
8272 if (ztest_opts.zo_verbose >= 1) {
8273 (void) printf("killing raidz expansion test after reflow "
8274 "reached %llu bytes\n", (u_longlong_t)pres->pres_reflowed);
8278 * Kill ourself to simulate a panic during a reflow. Our parent will
8279 * restart the test and the changed flag value will drive the test
8280 * through the scrub/check code to verify the pool is not corrupted.
8282 ztest_kill(zs);
8285 static void
8286 ztest_generic_run(ztest_shared_t *zs, spa_t *spa)
8288 kthread_t **run_threads;
8289 int t;
8291 run_threads = umem_zalloc(ztest_opts.zo_threads * sizeof (kthread_t *),
8292 UMEM_NOFAIL);
8295 * Kick off all the tests that run in parallel.
8297 for (t = 0; t < ztest_opts.zo_threads; t++) {
8298 if (t < ztest_opts.zo_datasets && ztest_dataset_open(t) != 0) {
8299 umem_free(run_threads, ztest_opts.zo_threads *
8300 sizeof (kthread_t *));
8301 return;
8304 run_threads[t] = thread_create(NULL, 0, ztest_thread,
8305 (void *)(uintptr_t)t, 0, NULL, TS_RUN | TS_JOINABLE,
8306 defclsyspri);
8310 * Wait for all of the tests to complete.
8312 for (t = 0; t < ztest_opts.zo_threads; t++)
8313 VERIFY0(thread_join(run_threads[t]));
8316 * Close all datasets. This must be done after all the threads
8317 * are joined so we can be sure none of the datasets are in-use
8318 * by any of the threads.
8320 for (t = 0; t < ztest_opts.zo_threads; t++) {
8321 if (t < ztest_opts.zo_datasets)
8322 ztest_dataset_close(t);
8325 txg_wait_synced(spa_get_dsl(spa), 0);
8327 zs->zs_alloc = metaslab_class_get_alloc(spa_normal_class(spa));
8328 zs->zs_space = metaslab_class_get_space(spa_normal_class(spa));
8330 umem_free(run_threads, ztest_opts.zo_threads * sizeof (kthread_t *));
8334 * Setup our test context and kick off threads to run tests on all datasets
8335 * in parallel.
8337 static void
8338 ztest_run(ztest_shared_t *zs)
8340 spa_t *spa;
8341 objset_t *os;
8342 kthread_t *resume_thread, *deadman_thread;
8343 uint64_t object;
8344 int error;
8345 int t, d;
8347 ztest_exiting = B_FALSE;
8350 * Initialize parent/child shared state.
8352 mutex_init(&ztest_vdev_lock, NULL, MUTEX_DEFAULT, NULL);
8353 mutex_init(&ztest_checkpoint_lock, NULL, MUTEX_DEFAULT, NULL);
8354 VERIFY0(pthread_rwlock_init(&ztest_name_lock, NULL));
8356 zs->zs_thread_start = gethrtime();
8357 zs->zs_thread_stop =
8358 zs->zs_thread_start + ztest_opts.zo_passtime * NANOSEC;
8359 zs->zs_thread_stop = MIN(zs->zs_thread_stop, zs->zs_proc_stop);
8360 zs->zs_thread_kill = zs->zs_thread_stop;
8361 if (ztest_random(100) < ztest_opts.zo_killrate) {
8362 zs->zs_thread_kill -=
8363 ztest_random(ztest_opts.zo_passtime * NANOSEC);
8366 mutex_init(&zcl.zcl_callbacks_lock, NULL, MUTEX_DEFAULT, NULL);
8368 list_create(&zcl.zcl_callbacks, sizeof (ztest_cb_data_t),
8369 offsetof(ztest_cb_data_t, zcd_node));
8372 * Open our pool. It may need to be imported first depending on
8373 * what tests were running when the previous pass was terminated.
8375 raidz_scratch_verify();
8376 kernel_init(SPA_MODE_READ | SPA_MODE_WRITE);
8377 error = spa_open(ztest_opts.zo_pool, &spa, FTAG);
8378 if (error) {
8379 VERIFY3S(error, ==, ENOENT);
8380 ztest_import_impl();
8381 VERIFY0(spa_open(ztest_opts.zo_pool, &spa, FTAG));
8382 zs->zs_metaslab_sz =
8383 1ULL << spa->spa_root_vdev->vdev_child[0]->vdev_ms_shift;
8386 metaslab_preload_limit = ztest_random(20) + 1;
8387 ztest_spa = spa;
8390 * XXX - BUGBUG raidz expansion do not run this for generic for now
8392 if (ztest_opts.zo_raidz_expand_test != RAIDZ_EXPAND_NONE)
8393 VERIFY0(vdev_raidz_impl_set("cycle"));
8395 dmu_objset_stats_t dds;
8396 VERIFY0(ztest_dmu_objset_own(ztest_opts.zo_pool,
8397 DMU_OST_ANY, B_TRUE, B_TRUE, FTAG, &os));
8398 dsl_pool_config_enter(dmu_objset_pool(os), FTAG);
8399 dmu_objset_fast_stat(os, &dds);
8400 dsl_pool_config_exit(dmu_objset_pool(os), FTAG);
8401 dmu_objset_disown(os, B_TRUE, FTAG);
8403 /* Give the dedicated raidz expansion test more grace time */
8404 if (ztest_opts.zo_raidz_expand_test != RAIDZ_EXPAND_NONE)
8405 zfs_deadman_synctime_ms *= 2;
8408 * Create a thread to periodically resume suspended I/O.
8410 resume_thread = thread_create(NULL, 0, ztest_resume_thread,
8411 spa, 0, NULL, TS_RUN | TS_JOINABLE, defclsyspri);
8414 * Create a deadman thread and set to panic if we hang.
8416 deadman_thread = thread_create(NULL, 0, ztest_deadman_thread,
8417 zs, 0, NULL, TS_RUN | TS_JOINABLE, defclsyspri);
8419 spa->spa_deadman_failmode = ZIO_FAILURE_MODE_PANIC;
8422 * Verify that we can safely inquire about any object,
8423 * whether it's allocated or not. To make it interesting,
8424 * we probe a 5-wide window around each power of two.
8425 * This hits all edge cases, including zero and the max.
8427 for (t = 0; t < 64; t++) {
8428 for (d = -5; d <= 5; d++) {
8429 error = dmu_object_info(spa->spa_meta_objset,
8430 (1ULL << t) + d, NULL);
8431 ASSERT(error == 0 || error == ENOENT ||
8432 error == EINVAL);
8437 * If we got any ENOSPC errors on the previous run, destroy something.
8439 if (zs->zs_enospc_count != 0) {
8440 /* Not expecting ENOSPC errors during raidz expansion tests */
8441 ASSERT3U(ztest_opts.zo_raidz_expand_test, ==,
8442 RAIDZ_EXPAND_NONE);
8444 int d = ztest_random(ztest_opts.zo_datasets);
8445 ztest_dataset_destroy(d);
8447 zs->zs_enospc_count = 0;
8450 * If we were in the middle of ztest_device_removal() and were killed
8451 * we need to ensure the removal and scrub complete before running
8452 * any tests that check ztest_device_removal_active. The removal will
8453 * be restarted automatically when the spa is opened, but we need to
8454 * initiate the scrub manually if it is not already in progress. Note
8455 * that we always run the scrub whenever an indirect vdev exists
8456 * because we have no way of knowing for sure if ztest_device_removal()
8457 * fully completed its scrub before the pool was reimported.
8459 * Does not apply for the RAIDZ expansion specific test runs
8461 if (ztest_opts.zo_raidz_expand_test == RAIDZ_EXPAND_NONE &&
8462 (spa->spa_removing_phys.sr_state == DSS_SCANNING ||
8463 spa->spa_removing_phys.sr_prev_indirect_vdev != -1)) {
8464 while (spa->spa_removing_phys.sr_state == DSS_SCANNING)
8465 txg_wait_synced(spa_get_dsl(spa), 0);
8467 error = ztest_scrub_impl(spa);
8468 if (error == EBUSY)
8469 error = 0;
8470 ASSERT0(error);
8473 if (ztest_opts.zo_verbose >= 4)
8474 (void) printf("starting main threads...\n");
8477 * Replay all logs of all datasets in the pool. This is primarily for
8478 * temporary datasets which wouldn't otherwise get replayed, which
8479 * can trigger failures when attempting to offline a SLOG in
8480 * ztest_fault_inject().
8482 (void) dmu_objset_find(ztest_opts.zo_pool, ztest_replay_zil_cb,
8483 NULL, DS_FIND_CHILDREN);
8485 if (ztest_opts.zo_raidz_expand_test == RAIDZ_EXPAND_REQUESTED)
8486 ztest_raidz_expand_run(zs, spa);
8487 else if (ztest_opts.zo_raidz_expand_test == RAIDZ_EXPAND_KILLED)
8488 ztest_raidz_expand_check(spa);
8489 else
8490 ztest_generic_run(zs, spa);
8492 /* Kill the resume and deadman threads */
8493 ztest_exiting = B_TRUE;
8494 VERIFY0(thread_join(resume_thread));
8495 VERIFY0(thread_join(deadman_thread));
8496 ztest_resume(spa);
8499 * Right before closing the pool, kick off a bunch of async I/O;
8500 * spa_close() should wait for it to complete.
8502 for (object = 1; object < 50; object++) {
8503 dmu_prefetch(spa->spa_meta_objset, object, 0, 0, 1ULL << 20,
8504 ZIO_PRIORITY_SYNC_READ);
8507 /* Verify that at least one commit cb was called in a timely fashion */
8508 if (zc_cb_counter >= ZTEST_COMMIT_CB_MIN_REG)
8509 VERIFY0(zc_min_txg_delay);
8511 spa_close(spa, FTAG);
8514 * Verify that we can loop over all pools.
8516 mutex_enter(&spa_namespace_lock);
8517 for (spa = spa_next(NULL); spa != NULL; spa = spa_next(spa))
8518 if (ztest_opts.zo_verbose > 3)
8519 (void) printf("spa_next: found %s\n", spa_name(spa));
8520 mutex_exit(&spa_namespace_lock);
8523 * Verify that we can export the pool and reimport it under a
8524 * different name.
8526 if ((ztest_random(2) == 0) && !ztest_opts.zo_mmp_test) {
8527 char name[ZFS_MAX_DATASET_NAME_LEN];
8528 (void) snprintf(name, sizeof (name), "%s_import",
8529 ztest_opts.zo_pool);
8530 ztest_spa_import_export(ztest_opts.zo_pool, name);
8531 ztest_spa_import_export(name, ztest_opts.zo_pool);
8534 kernel_fini();
8536 list_destroy(&zcl.zcl_callbacks);
8537 mutex_destroy(&zcl.zcl_callbacks_lock);
8538 (void) pthread_rwlock_destroy(&ztest_name_lock);
8539 mutex_destroy(&ztest_vdev_lock);
8540 mutex_destroy(&ztest_checkpoint_lock);
8543 static void
8544 print_time(hrtime_t t, char *timebuf)
8546 hrtime_t s = t / NANOSEC;
8547 hrtime_t m = s / 60;
8548 hrtime_t h = m / 60;
8549 hrtime_t d = h / 24;
8551 s -= m * 60;
8552 m -= h * 60;
8553 h -= d * 24;
8555 timebuf[0] = '\0';
8557 if (d)
8558 (void) sprintf(timebuf,
8559 "%llud%02lluh%02llum%02llus", d, h, m, s);
8560 else if (h)
8561 (void) sprintf(timebuf, "%lluh%02llum%02llus", h, m, s);
8562 else if (m)
8563 (void) sprintf(timebuf, "%llum%02llus", m, s);
8564 else
8565 (void) sprintf(timebuf, "%llus", s);
8568 static nvlist_t *
8569 make_random_pool_props(void)
8571 nvlist_t *props;
8573 props = fnvlist_alloc();
8575 /* Twenty percent of the time enable ZPOOL_PROP_DEDUP_TABLE_QUOTA */
8576 if (ztest_random(5) == 0) {
8577 fnvlist_add_uint64(props,
8578 zpool_prop_to_name(ZPOOL_PROP_DEDUP_TABLE_QUOTA),
8579 2 * 1024 * 1024);
8582 /* Fifty percent of the time enable ZPOOL_PROP_AUTOREPLACE */
8583 if (ztest_random(2) == 0) {
8584 fnvlist_add_uint64(props,
8585 zpool_prop_to_name(ZPOOL_PROP_AUTOREPLACE), 1);
8588 return (props);
8592 * Create a storage pool with the given name and initial vdev size.
8593 * Then test spa_freeze() functionality.
8595 static void
8596 ztest_init(ztest_shared_t *zs)
8598 spa_t *spa;
8599 nvlist_t *nvroot, *props;
8600 int i;
8602 mutex_init(&ztest_vdev_lock, NULL, MUTEX_DEFAULT, NULL);
8603 mutex_init(&ztest_checkpoint_lock, NULL, MUTEX_DEFAULT, NULL);
8604 VERIFY0(pthread_rwlock_init(&ztest_name_lock, NULL));
8606 raidz_scratch_verify();
8607 kernel_init(SPA_MODE_READ | SPA_MODE_WRITE);
8610 * Create the storage pool.
8612 (void) spa_destroy(ztest_opts.zo_pool);
8613 ztest_shared->zs_vdev_next_leaf = 0;
8614 zs->zs_splits = 0;
8615 zs->zs_mirrors = ztest_opts.zo_mirrors;
8616 nvroot = make_vdev_root(NULL, NULL, NULL, ztest_opts.zo_vdev_size, 0,
8617 NULL, ztest_opts.zo_raid_children, zs->zs_mirrors, 1);
8618 props = make_random_pool_props();
8621 * We don't expect the pool to suspend unless maxfaults == 0,
8622 * in which case ztest_fault_inject() temporarily takes away
8623 * the only valid replica.
8625 fnvlist_add_uint64(props,
8626 zpool_prop_to_name(ZPOOL_PROP_FAILUREMODE),
8627 MAXFAULTS(zs) ? ZIO_FAILURE_MODE_PANIC : ZIO_FAILURE_MODE_WAIT);
8629 for (i = 0; i < SPA_FEATURES; i++) {
8630 char *buf;
8632 if (!spa_feature_table[i].fi_zfs_mod_supported)
8633 continue;
8636 * 75% chance of using the log space map feature. We want ztest
8637 * to exercise both the code paths that use the log space map
8638 * feature and the ones that don't.
8640 if (i == SPA_FEATURE_LOG_SPACEMAP && ztest_random(4) == 0)
8641 continue;
8644 * split 50/50 between legacy and fast dedup
8646 if (i == SPA_FEATURE_FAST_DEDUP && ztest_random(2) != 0)
8647 continue;
8649 VERIFY3S(-1, !=, asprintf(&buf, "feature@%s",
8650 spa_feature_table[i].fi_uname));
8651 fnvlist_add_uint64(props, buf, 0);
8652 free(buf);
8655 VERIFY0(spa_create(ztest_opts.zo_pool, nvroot, props, NULL, NULL));
8656 fnvlist_free(nvroot);
8657 fnvlist_free(props);
8659 VERIFY0(spa_open(ztest_opts.zo_pool, &spa, FTAG));
8660 zs->zs_metaslab_sz =
8661 1ULL << spa->spa_root_vdev->vdev_child[0]->vdev_ms_shift;
8662 zs->zs_guid = spa_guid(spa);
8663 spa_close(spa, FTAG);
8665 kernel_fini();
8667 if (!ztest_opts.zo_mmp_test) {
8668 ztest_run_zdb(zs->zs_guid);
8669 ztest_freeze();
8670 ztest_run_zdb(zs->zs_guid);
8673 (void) pthread_rwlock_destroy(&ztest_name_lock);
8674 mutex_destroy(&ztest_vdev_lock);
8675 mutex_destroy(&ztest_checkpoint_lock);
8678 static void
8679 setup_data_fd(void)
8681 static char ztest_name_data[] = "/tmp/ztest.data.XXXXXX";
8683 ztest_fd_data = mkstemp(ztest_name_data);
8684 ASSERT3S(ztest_fd_data, >=, 0);
8685 (void) unlink(ztest_name_data);
8688 static int
8689 shared_data_size(ztest_shared_hdr_t *hdr)
8691 int size;
8693 size = hdr->zh_hdr_size;
8694 size += hdr->zh_opts_size;
8695 size += hdr->zh_size;
8696 size += hdr->zh_stats_size * hdr->zh_stats_count;
8697 size += hdr->zh_ds_size * hdr->zh_ds_count;
8698 size += hdr->zh_scratch_state_size;
8700 return (size);
8703 static void
8704 setup_hdr(void)
8706 int size;
8707 ztest_shared_hdr_t *hdr;
8709 hdr = (void *)mmap(0, P2ROUNDUP(sizeof (*hdr), getpagesize()),
8710 PROT_READ | PROT_WRITE, MAP_SHARED, ztest_fd_data, 0);
8711 ASSERT3P(hdr, !=, MAP_FAILED);
8713 VERIFY0(ftruncate(ztest_fd_data, sizeof (ztest_shared_hdr_t)));
8715 hdr->zh_hdr_size = sizeof (ztest_shared_hdr_t);
8716 hdr->zh_opts_size = sizeof (ztest_shared_opts_t);
8717 hdr->zh_size = sizeof (ztest_shared_t);
8718 hdr->zh_stats_size = sizeof (ztest_shared_callstate_t);
8719 hdr->zh_stats_count = ZTEST_FUNCS;
8720 hdr->zh_ds_size = sizeof (ztest_shared_ds_t);
8721 hdr->zh_ds_count = ztest_opts.zo_datasets;
8722 hdr->zh_scratch_state_size = sizeof (ztest_shared_scratch_state_t);
8724 size = shared_data_size(hdr);
8725 VERIFY0(ftruncate(ztest_fd_data, size));
8727 (void) munmap((caddr_t)hdr, P2ROUNDUP(sizeof (*hdr), getpagesize()));
8730 static void
8731 setup_data(void)
8733 int size, offset;
8734 ztest_shared_hdr_t *hdr;
8735 uint8_t *buf;
8737 hdr = (void *)mmap(0, P2ROUNDUP(sizeof (*hdr), getpagesize()),
8738 PROT_READ, MAP_SHARED, ztest_fd_data, 0);
8739 ASSERT3P(hdr, !=, MAP_FAILED);
8741 size = shared_data_size(hdr);
8743 (void) munmap((caddr_t)hdr, P2ROUNDUP(sizeof (*hdr), getpagesize()));
8744 hdr = ztest_shared_hdr = (void *)mmap(0, P2ROUNDUP(size, getpagesize()),
8745 PROT_READ | PROT_WRITE, MAP_SHARED, ztest_fd_data, 0);
8746 ASSERT3P(hdr, !=, MAP_FAILED);
8747 buf = (uint8_t *)hdr;
8749 offset = hdr->zh_hdr_size;
8750 ztest_shared_opts = (void *)&buf[offset];
8751 offset += hdr->zh_opts_size;
8752 ztest_shared = (void *)&buf[offset];
8753 offset += hdr->zh_size;
8754 ztest_shared_callstate = (void *)&buf[offset];
8755 offset += hdr->zh_stats_size * hdr->zh_stats_count;
8756 ztest_shared_ds = (void *)&buf[offset];
8757 offset += hdr->zh_ds_size * hdr->zh_ds_count;
8758 ztest_scratch_state = (void *)&buf[offset];
8761 static boolean_t
8762 exec_child(char *cmd, char *libpath, boolean_t ignorekill, int *statusp)
8764 pid_t pid;
8765 int status;
8766 char *cmdbuf = NULL;
8768 pid = fork();
8770 if (cmd == NULL) {
8771 cmdbuf = umem_alloc(MAXPATHLEN, UMEM_NOFAIL);
8772 (void) strlcpy(cmdbuf, getexecname(), MAXPATHLEN);
8773 cmd = cmdbuf;
8776 if (pid == -1)
8777 fatal(B_TRUE, "fork failed");
8779 if (pid == 0) { /* child */
8780 char fd_data_str[12];
8782 VERIFY3S(11, >=,
8783 snprintf(fd_data_str, 12, "%d", ztest_fd_data));
8784 VERIFY0(setenv("ZTEST_FD_DATA", fd_data_str, 1));
8786 if (libpath != NULL) {
8787 const char *curlp = getenv("LD_LIBRARY_PATH");
8788 if (curlp == NULL)
8789 VERIFY0(setenv("LD_LIBRARY_PATH", libpath, 1));
8790 else {
8791 char *newlp = NULL;
8792 VERIFY3S(-1, !=,
8793 asprintf(&newlp, "%s:%s", libpath, curlp));
8794 VERIFY0(setenv("LD_LIBRARY_PATH", newlp, 1));
8795 free(newlp);
8798 (void) execl(cmd, cmd, (char *)NULL);
8799 ztest_dump_core = B_FALSE;
8800 fatal(B_TRUE, "exec failed: %s", cmd);
8803 if (cmdbuf != NULL) {
8804 umem_free(cmdbuf, MAXPATHLEN);
8805 cmd = NULL;
8808 while (waitpid(pid, &status, 0) != pid)
8809 continue;
8810 if (statusp != NULL)
8811 *statusp = status;
8813 if (WIFEXITED(status)) {
8814 if (WEXITSTATUS(status) != 0) {
8815 (void) fprintf(stderr, "child exited with code %d\n",
8816 WEXITSTATUS(status));
8817 exit(2);
8819 return (B_FALSE);
8820 } else if (WIFSIGNALED(status)) {
8821 if (!ignorekill || WTERMSIG(status) != SIGKILL) {
8822 (void) fprintf(stderr, "child died with signal %d\n",
8823 WTERMSIG(status));
8824 exit(3);
8826 return (B_TRUE);
8827 } else {
8828 (void) fprintf(stderr, "something strange happened to child\n");
8829 exit(4);
8833 static void
8834 ztest_run_init(void)
8836 int i;
8838 ztest_shared_t *zs = ztest_shared;
8841 * Blow away any existing copy of zpool.cache
8843 (void) remove(spa_config_path);
8845 if (ztest_opts.zo_init == 0) {
8846 if (ztest_opts.zo_verbose >= 1)
8847 (void) printf("Importing pool %s\n",
8848 ztest_opts.zo_pool);
8849 ztest_import(zs);
8850 return;
8854 * Create and initialize our storage pool.
8856 for (i = 1; i <= ztest_opts.zo_init; i++) {
8857 memset(zs, 0, sizeof (*zs));
8858 if (ztest_opts.zo_verbose >= 3 &&
8859 ztest_opts.zo_init != 1) {
8860 (void) printf("ztest_init(), pass %d\n", i);
8862 ztest_init(zs);
8867 main(int argc, char **argv)
8869 int kills = 0;
8870 int iters = 0;
8871 int older = 0;
8872 int newer = 0;
8873 ztest_shared_t *zs;
8874 ztest_info_t *zi;
8875 ztest_shared_callstate_t *zc;
8876 char timebuf[100];
8877 char numbuf[NN_NUMBUF_SZ];
8878 char *cmd;
8879 boolean_t hasalt;
8880 int f, err;
8881 char *fd_data_str = getenv("ZTEST_FD_DATA");
8882 struct sigaction action;
8884 (void) setvbuf(stdout, NULL, _IOLBF, 0);
8886 dprintf_setup(&argc, argv);
8887 zfs_deadman_synctime_ms = 300000;
8888 zfs_deadman_checktime_ms = 30000;
8890 * As two-word space map entries may not come up often (especially
8891 * if pool and vdev sizes are small) we want to force at least some
8892 * of them so the feature get tested.
8894 zfs_force_some_double_word_sm_entries = B_TRUE;
8897 * Verify that even extensively damaged split blocks with many
8898 * segments can be reconstructed in a reasonable amount of time
8899 * when reconstruction is known to be possible.
8901 * Note: the lower this value is, the more damage we inflict, and
8902 * the more time ztest spends in recovering that damage. We chose
8903 * to induce damage 1/100th of the time so recovery is tested but
8904 * not so frequently that ztest doesn't get to test other code paths.
8906 zfs_reconstruct_indirect_damage_fraction = 100;
8908 action.sa_handler = sig_handler;
8909 sigemptyset(&action.sa_mask);
8910 action.sa_flags = 0;
8912 if (sigaction(SIGSEGV, &action, NULL) < 0) {
8913 (void) fprintf(stderr, "ztest: cannot catch SIGSEGV: %s.\n",
8914 strerror(errno));
8915 exit(EXIT_FAILURE);
8918 if (sigaction(SIGABRT, &action, NULL) < 0) {
8919 (void) fprintf(stderr, "ztest: cannot catch SIGABRT: %s.\n",
8920 strerror(errno));
8921 exit(EXIT_FAILURE);
8925 * Force random_get_bytes() to use /dev/urandom in order to prevent
8926 * ztest from needlessly depleting the system entropy pool.
8928 random_path = "/dev/urandom";
8929 ztest_fd_rand = open(random_path, O_RDONLY | O_CLOEXEC);
8930 ASSERT3S(ztest_fd_rand, >=, 0);
8932 if (!fd_data_str) {
8933 process_options(argc, argv);
8935 setup_data_fd();
8936 setup_hdr();
8937 setup_data();
8938 memcpy(ztest_shared_opts, &ztest_opts,
8939 sizeof (*ztest_shared_opts));
8940 } else {
8941 ztest_fd_data = atoi(fd_data_str);
8942 setup_data();
8943 memcpy(&ztest_opts, ztest_shared_opts, sizeof (ztest_opts));
8945 ASSERT3U(ztest_opts.zo_datasets, ==, ztest_shared_hdr->zh_ds_count);
8947 err = ztest_set_global_vars();
8948 if (err != 0 && !fd_data_str) {
8949 /* error message done by ztest_set_global_vars */
8950 exit(EXIT_FAILURE);
8951 } else {
8952 /* children should not be spawned if setting gvars fails */
8953 VERIFY3S(err, ==, 0);
8956 /* Override location of zpool.cache */
8957 VERIFY3S(asprintf((char **)&spa_config_path, "%s/zpool.cache",
8958 ztest_opts.zo_dir), !=, -1);
8960 ztest_ds = umem_alloc(ztest_opts.zo_datasets * sizeof (ztest_ds_t),
8961 UMEM_NOFAIL);
8962 zs = ztest_shared;
8964 if (fd_data_str) {
8965 metaslab_force_ganging = ztest_opts.zo_metaslab_force_ganging;
8966 metaslab_df_alloc_threshold =
8967 zs->zs_metaslab_df_alloc_threshold;
8969 if (zs->zs_do_init)
8970 ztest_run_init();
8971 else
8972 ztest_run(zs);
8973 exit(0);
8976 hasalt = (strlen(ztest_opts.zo_alt_ztest) != 0);
8978 if (ztest_opts.zo_verbose >= 1) {
8979 (void) printf("%"PRIu64" vdevs, %d datasets, %d threads, "
8980 "%d %s disks, parity %d, %"PRIu64" seconds...\n\n",
8981 ztest_opts.zo_vdevs,
8982 ztest_opts.zo_datasets,
8983 ztest_opts.zo_threads,
8984 ztest_opts.zo_raid_children,
8985 ztest_opts.zo_raid_type,
8986 ztest_opts.zo_raid_parity,
8987 ztest_opts.zo_time);
8990 cmd = umem_alloc(MAXNAMELEN, UMEM_NOFAIL);
8991 (void) strlcpy(cmd, getexecname(), MAXNAMELEN);
8993 zs->zs_do_init = B_TRUE;
8994 if (strlen(ztest_opts.zo_alt_ztest) != 0) {
8995 if (ztest_opts.zo_verbose >= 1) {
8996 (void) printf("Executing older ztest for "
8997 "initialization: %s\n", ztest_opts.zo_alt_ztest);
8999 VERIFY(!exec_child(ztest_opts.zo_alt_ztest,
9000 ztest_opts.zo_alt_libpath, B_FALSE, NULL));
9001 } else {
9002 VERIFY(!exec_child(NULL, NULL, B_FALSE, NULL));
9004 zs->zs_do_init = B_FALSE;
9006 zs->zs_proc_start = gethrtime();
9007 zs->zs_proc_stop = zs->zs_proc_start + ztest_opts.zo_time * NANOSEC;
9009 for (f = 0; f < ZTEST_FUNCS; f++) {
9010 zi = &ztest_info[f];
9011 zc = ZTEST_GET_SHARED_CALLSTATE(f);
9012 if (zs->zs_proc_start + zi->zi_interval[0] > zs->zs_proc_stop)
9013 zc->zc_next = UINT64_MAX;
9014 else
9015 zc->zc_next = zs->zs_proc_start +
9016 ztest_random(2 * zi->zi_interval[0] + 1);
9020 * Run the tests in a loop. These tests include fault injection
9021 * to verify that self-healing data works, and forced crashes
9022 * to verify that we never lose on-disk consistency.
9024 while (gethrtime() < zs->zs_proc_stop) {
9025 int status;
9026 boolean_t killed;
9029 * Initialize the workload counters for each function.
9031 for (f = 0; f < ZTEST_FUNCS; f++) {
9032 zc = ZTEST_GET_SHARED_CALLSTATE(f);
9033 zc->zc_count = 0;
9034 zc->zc_time = 0;
9037 /* Set the allocation switch size */
9038 zs->zs_metaslab_df_alloc_threshold =
9039 ztest_random(zs->zs_metaslab_sz / 4) + 1;
9041 if (!hasalt || ztest_random(2) == 0) {
9042 if (hasalt && ztest_opts.zo_verbose >= 1) {
9043 (void) printf("Executing newer ztest: %s\n",
9044 cmd);
9046 newer++;
9047 killed = exec_child(cmd, NULL, B_TRUE, &status);
9048 } else {
9049 if (hasalt && ztest_opts.zo_verbose >= 1) {
9050 (void) printf("Executing older ztest: %s\n",
9051 ztest_opts.zo_alt_ztest);
9053 older++;
9054 killed = exec_child(ztest_opts.zo_alt_ztest,
9055 ztest_opts.zo_alt_libpath, B_TRUE, &status);
9058 if (killed)
9059 kills++;
9060 iters++;
9062 if (ztest_opts.zo_verbose >= 1) {
9063 hrtime_t now = gethrtime();
9065 now = MIN(now, zs->zs_proc_stop);
9066 print_time(zs->zs_proc_stop - now, timebuf);
9067 nicenum(zs->zs_space, numbuf, sizeof (numbuf));
9069 (void) printf("Pass %3d, %8s, %3"PRIu64" ENOSPC, "
9070 "%4.1f%% of %5s used, %3.0f%% done, %8s to go\n",
9071 iters,
9072 WIFEXITED(status) ? "Complete" : "SIGKILL",
9073 zs->zs_enospc_count,
9074 100.0 * zs->zs_alloc / zs->zs_space,
9075 numbuf,
9076 100.0 * (now - zs->zs_proc_start) /
9077 (ztest_opts.zo_time * NANOSEC), timebuf);
9080 if (ztest_opts.zo_verbose >= 2) {
9081 (void) printf("\nWorkload summary:\n\n");
9082 (void) printf("%7s %9s %s\n",
9083 "Calls", "Time", "Function");
9084 (void) printf("%7s %9s %s\n",
9085 "-----", "----", "--------");
9086 for (f = 0; f < ZTEST_FUNCS; f++) {
9087 zi = &ztest_info[f];
9088 zc = ZTEST_GET_SHARED_CALLSTATE(f);
9089 print_time(zc->zc_time, timebuf);
9090 (void) printf("%7"PRIu64" %9s %s\n",
9091 zc->zc_count, timebuf,
9092 zi->zi_funcname);
9094 (void) printf("\n");
9097 if (!ztest_opts.zo_mmp_test)
9098 ztest_run_zdb(zs->zs_guid);
9099 if (ztest_shared_opts->zo_raidz_expand_test ==
9100 RAIDZ_EXPAND_CHECKED)
9101 break; /* raidz expand test complete */
9104 if (ztest_opts.zo_verbose >= 1) {
9105 if (hasalt) {
9106 (void) printf("%d runs of older ztest: %s\n", older,
9107 ztest_opts.zo_alt_ztest);
9108 (void) printf("%d runs of newer ztest: %s\n", newer,
9109 cmd);
9111 (void) printf("%d killed, %d completed, %.0f%% kill rate\n",
9112 kills, iters - kills, (100.0 * kills) / MAX(1, iters));
9115 umem_free(cmd, MAXNAMELEN);
9117 return (0);