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