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