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