4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License (the "License").
6 * You may not use this file except in compliance with the License.
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or https://opensource.org/licenses/CDDL-1.0.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
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.
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.
35 * The overall design of the ztest program is as follows:
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".
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.
46 * (3) While all this is happening, we inject faults into the pool to
47 * verify that self-healing data really works.
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.
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.
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.
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.
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.
75 * To turn this into an overnight stress test, use -T to specify run time.
77 * You can ask more vdevs [-v], datasets [-d], or threads [-t]
78 * to increase the pool capacity, fanout, and overall stress level.
80 * Use the -k option to set the desired frequency of kills.
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).
91 #include <sys/zfs_context.h>
97 #include <sys/dmu_objset.h>
100 #include <sys/time.h>
101 #include <sys/wait.h>
102 #include <sys/mman.h>
103 #include <sys/resource.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>
124 #include <sys/blake3.h>
133 #include <sys/fs/zfs.h>
134 #include <zfs_fletcher.h>
135 #include <libnvpair.h>
136 #include <libzutil.h>
137 #include <sys/crypto/icp.h>
138 #if (__GLIBC__ && !__UCLIBC__)
139 #include <execinfo.h> /* for backtrace() */
142 static int ztest_fd_data = -1;
143 static int ztest_fd_rand = -1;
145 typedef struct ztest_shared_hdr {
146 uint64_t zh_hdr_size;
147 uint64_t zh_opts_size;
149 uint64_t zh_stats_size;
150 uint64_t zh_stats_count;
152 uint64_t zh_ds_count;
153 } ztest_shared_hdr_t;
155 static ztest_shared_hdr_t *ztest_shared_hdr;
157 enum ztest_class_state {
158 ZTEST_VDEV_CLASS_OFF,
163 #define ZO_GVARS_MAX_ARGLEN ((size_t)64)
164 #define ZO_GVARS_MAX_COUNT ((size_t)10)
166 typedef struct ztest_shared_opts {
167 char zo_pool[ZFS_MAX_DATASET_NAME_LEN];
168 char zo_dir[ZFS_MAX_DATASET_NAME_LEN];
169 char zo_alt_ztest[MAXNAMELEN];
170 char zo_alt_libpath[MAXNAMELEN];
172 uint64_t zo_vdevtime;
176 int zo_raid_children;
178 char zo_raid_type[8];
183 uint64_t zo_passtime;
184 uint64_t zo_killrate;
188 uint64_t zo_maxloops;
189 uint64_t zo_metaslab_force_ganging;
191 int zo_special_vdevs;
194 char zo_gvars[ZO_GVARS_MAX_COUNT][ZO_GVARS_MAX_ARGLEN];
195 } ztest_shared_opts_t;
197 /* Default values for command line options. */
198 #define DEFAULT_POOL "ztest"
199 #define DEFAULT_VDEV_DIR "/tmp"
200 #define DEFAULT_VDEV_COUNT 5
201 #define DEFAULT_VDEV_SIZE (SPA_MINDEVSIZE * 4) /* 256m default size */
202 #define DEFAULT_VDEV_SIZE_STR "256M"
203 #define DEFAULT_ASHIFT SPA_MINBLOCKSHIFT
204 #define DEFAULT_MIRRORS 2
205 #define DEFAULT_RAID_CHILDREN 4
206 #define DEFAULT_RAID_PARITY 1
207 #define DEFAULT_DRAID_DATA 4
208 #define DEFAULT_DRAID_SPARES 1
209 #define DEFAULT_DATASETS_COUNT 7
210 #define DEFAULT_THREADS 23
211 #define DEFAULT_RUN_TIME 300 /* 300 seconds */
212 #define DEFAULT_RUN_TIME_STR "300 sec"
213 #define DEFAULT_PASS_TIME 60 /* 60 seconds */
214 #define DEFAULT_PASS_TIME_STR "60 sec"
215 #define DEFAULT_KILL_RATE 70 /* 70% kill rate */
216 #define DEFAULT_KILLRATE_STR "70%"
217 #define DEFAULT_INITS 1
218 #define DEFAULT_MAX_LOOPS 50 /* 5 minutes */
219 #define DEFAULT_FORCE_GANGING (64 << 10)
220 #define DEFAULT_FORCE_GANGING_STR "64K"
222 /* Simplifying assumption: -1 is not a valid default. */
223 #define NO_DEFAULT -1
225 static const ztest_shared_opts_t ztest_opts_defaults = {
226 .zo_pool = DEFAULT_POOL,
227 .zo_dir = DEFAULT_VDEV_DIR,
228 .zo_alt_ztest = { '\0' },
229 .zo_alt_libpath = { '\0' },
230 .zo_vdevs = DEFAULT_VDEV_COUNT,
231 .zo_ashift = DEFAULT_ASHIFT,
232 .zo_mirrors = DEFAULT_MIRRORS,
233 .zo_raid_children = DEFAULT_RAID_CHILDREN,
234 .zo_raid_parity = DEFAULT_RAID_PARITY,
235 .zo_raid_type = VDEV_TYPE_RAIDZ,
236 .zo_vdev_size = DEFAULT_VDEV_SIZE,
237 .zo_draid_data = DEFAULT_DRAID_DATA, /* data drives */
238 .zo_draid_spares = DEFAULT_DRAID_SPARES, /* distributed spares */
239 .zo_datasets = DEFAULT_DATASETS_COUNT,
240 .zo_threads = DEFAULT_THREADS,
241 .zo_passtime = DEFAULT_PASS_TIME,
242 .zo_killrate = DEFAULT_KILL_RATE,
245 .zo_init = DEFAULT_INITS,
246 .zo_time = DEFAULT_RUN_TIME,
247 .zo_maxloops = DEFAULT_MAX_LOOPS, /* max loops during spa_freeze() */
248 .zo_metaslab_force_ganging = DEFAULT_FORCE_GANGING,
249 .zo_special_vdevs = ZTEST_VDEV_CLASS_RND,
253 extern uint64_t metaslab_force_ganging;
254 extern uint64_t metaslab_df_alloc_threshold;
255 extern uint64_t zfs_deadman_synctime_ms;
256 extern uint_t metaslab_preload_limit;
257 extern int zfs_compressed_arc_enabled;
258 extern int zfs_abd_scatter_enabled;
259 extern uint_t dmu_object_alloc_chunk_shift;
260 extern boolean_t zfs_force_some_double_word_sm_entries;
261 extern unsigned long zio_decompress_fail_fraction;
262 extern unsigned long zfs_reconstruct_indirect_damage_fraction;
265 static ztest_shared_opts_t *ztest_shared_opts;
266 static ztest_shared_opts_t ztest_opts;
267 static const char *const ztest_wkeydata = "abcdefghijklmnopqrstuvwxyz012345";
269 typedef struct ztest_shared_ds {
273 static ztest_shared_ds_t *ztest_shared_ds;
274 #define ZTEST_GET_SHARED_DS(d) (&ztest_shared_ds[d])
276 #define BT_MAGIC 0x123456789abcdefULL
277 #define MAXFAULTS(zs) \
278 (MAX((zs)->zs_mirrors, 1) * (ztest_opts.zo_raid_parity + 1) - 1)
282 ZTEST_IO_WRITE_PATTERN,
283 ZTEST_IO_WRITE_ZEROES,
290 typedef struct ztest_block_tag {
294 uint64_t bt_dnodesize;
301 typedef struct bufwad {
308 * It would be better to use a rangelock_t per object. Unfortunately
309 * the rangelock_t is not a drop-in replacement for rl_t, because we
310 * still need to map from object ID to rangelock_t.
332 #define ZTEST_RANGE_LOCKS 64
333 #define ZTEST_OBJECT_LOCKS 64
336 * Object descriptor. Used as a template for object lookup/create/remove.
338 typedef struct ztest_od {
341 dmu_object_type_t od_type;
342 dmu_object_type_t od_crtype;
343 uint64_t od_blocksize;
344 uint64_t od_crblocksize;
345 uint64_t od_crdnodesize;
348 char od_name[ZFS_MAX_DATASET_NAME_LEN];
354 typedef struct ztest_ds {
355 ztest_shared_ds_t *zd_shared;
357 pthread_rwlock_t zd_zilog_lock;
359 ztest_od_t *zd_od; /* debugging aid */
360 char zd_name[ZFS_MAX_DATASET_NAME_LEN];
361 kmutex_t zd_dirobj_lock;
362 rll_t zd_object_lock[ZTEST_OBJECT_LOCKS];
363 rll_t zd_range_lock[ZTEST_RANGE_LOCKS];
367 * Per-iteration state.
369 typedef void ztest_func_t(ztest_ds_t *zd, uint64_t id);
371 typedef struct ztest_info {
372 ztest_func_t *zi_func; /* test function */
373 uint64_t zi_iters; /* iterations per execution */
374 uint64_t *zi_interval; /* execute every <interval> seconds */
375 const char *zi_funcname; /* name of test function */
378 typedef struct ztest_shared_callstate {
379 uint64_t zc_count; /* per-pass count */
380 uint64_t zc_time; /* per-pass time */
381 uint64_t zc_next; /* next time to call this function */
382 } ztest_shared_callstate_t;
384 static ztest_shared_callstate_t *ztest_shared_callstate;
385 #define ZTEST_GET_SHARED_CALLSTATE(c) (&ztest_shared_callstate[c])
387 ztest_func_t ztest_dmu_read_write;
388 ztest_func_t ztest_dmu_write_parallel;
389 ztest_func_t ztest_dmu_object_alloc_free;
390 ztest_func_t ztest_dmu_object_next_chunk;
391 ztest_func_t ztest_dmu_commit_callbacks;
392 ztest_func_t ztest_zap;
393 ztest_func_t ztest_zap_parallel;
394 ztest_func_t ztest_zil_commit;
395 ztest_func_t ztest_zil_remount;
396 ztest_func_t ztest_dmu_read_write_zcopy;
397 ztest_func_t ztest_dmu_objset_create_destroy;
398 ztest_func_t ztest_dmu_prealloc;
399 ztest_func_t ztest_fzap;
400 ztest_func_t ztest_dmu_snapshot_create_destroy;
401 ztest_func_t ztest_dsl_prop_get_set;
402 ztest_func_t ztest_spa_prop_get_set;
403 ztest_func_t ztest_spa_create_destroy;
404 ztest_func_t ztest_fault_inject;
405 ztest_func_t ztest_dmu_snapshot_hold;
406 ztest_func_t ztest_mmp_enable_disable;
407 ztest_func_t ztest_scrub;
408 ztest_func_t ztest_dsl_dataset_promote_busy;
409 ztest_func_t ztest_vdev_attach_detach;
410 ztest_func_t ztest_vdev_LUN_growth;
411 ztest_func_t ztest_vdev_add_remove;
412 ztest_func_t ztest_vdev_class_add;
413 ztest_func_t ztest_vdev_aux_add_remove;
414 ztest_func_t ztest_split_pool;
415 ztest_func_t ztest_reguid;
416 ztest_func_t ztest_spa_upgrade;
417 ztest_func_t ztest_device_removal;
418 ztest_func_t ztest_spa_checkpoint_create_discard;
419 ztest_func_t ztest_initialize;
420 ztest_func_t ztest_trim;
421 ztest_func_t ztest_blake3;
422 ztest_func_t ztest_fletcher;
423 ztest_func_t ztest_fletcher_incr;
424 ztest_func_t ztest_verify_dnode_bt;
426 static uint64_t zopt_always = 0ULL * NANOSEC; /* all the time */
427 static uint64_t zopt_incessant = 1ULL * NANOSEC / 10; /* every 1/10 second */
428 static uint64_t zopt_often = 1ULL * NANOSEC; /* every second */
429 static uint64_t zopt_sometimes = 10ULL * NANOSEC; /* every 10 seconds */
430 static uint64_t zopt_rarely = 60ULL * NANOSEC; /* every 60 seconds */
432 #define ZTI_INIT(func, iters, interval) \
433 { .zi_func = (func), \
434 .zi_iters = (iters), \
435 .zi_interval = (interval), \
436 .zi_funcname = # func }
438 static ztest_info_t ztest_info[] = {
439 ZTI_INIT(ztest_dmu_read_write, 1, &zopt_always),
440 ZTI_INIT(ztest_dmu_write_parallel, 10, &zopt_always),
441 ZTI_INIT(ztest_dmu_object_alloc_free, 1, &zopt_always),
442 ZTI_INIT(ztest_dmu_object_next_chunk, 1, &zopt_sometimes),
443 ZTI_INIT(ztest_dmu_commit_callbacks, 1, &zopt_always),
444 ZTI_INIT(ztest_zap, 30, &zopt_always),
445 ZTI_INIT(ztest_zap_parallel, 100, &zopt_always),
446 ZTI_INIT(ztest_split_pool, 1, &zopt_sometimes),
447 ZTI_INIT(ztest_zil_commit, 1, &zopt_incessant),
448 ZTI_INIT(ztest_zil_remount, 1, &zopt_sometimes),
449 ZTI_INIT(ztest_dmu_read_write_zcopy, 1, &zopt_often),
450 ZTI_INIT(ztest_dmu_objset_create_destroy, 1, &zopt_often),
451 ZTI_INIT(ztest_dsl_prop_get_set, 1, &zopt_often),
452 ZTI_INIT(ztest_spa_prop_get_set, 1, &zopt_sometimes),
454 ZTI_INIT(ztest_dmu_prealloc, 1, &zopt_sometimes),
456 ZTI_INIT(ztest_fzap, 1, &zopt_sometimes),
457 ZTI_INIT(ztest_dmu_snapshot_create_destroy, 1, &zopt_sometimes),
458 ZTI_INIT(ztest_spa_create_destroy, 1, &zopt_sometimes),
459 ZTI_INIT(ztest_fault_inject, 1, &zopt_sometimes),
460 ZTI_INIT(ztest_dmu_snapshot_hold, 1, &zopt_sometimes),
461 ZTI_INIT(ztest_mmp_enable_disable, 1, &zopt_sometimes),
462 ZTI_INIT(ztest_reguid, 1, &zopt_rarely),
463 ZTI_INIT(ztest_scrub, 1, &zopt_rarely),
464 ZTI_INIT(ztest_spa_upgrade, 1, &zopt_rarely),
465 ZTI_INIT(ztest_dsl_dataset_promote_busy, 1, &zopt_rarely),
466 ZTI_INIT(ztest_vdev_attach_detach, 1, &zopt_sometimes),
467 ZTI_INIT(ztest_vdev_LUN_growth, 1, &zopt_rarely),
468 ZTI_INIT(ztest_vdev_add_remove, 1, &ztest_opts.zo_vdevtime),
469 ZTI_INIT(ztest_vdev_class_add, 1, &ztest_opts.zo_vdevtime),
470 ZTI_INIT(ztest_vdev_aux_add_remove, 1, &ztest_opts.zo_vdevtime),
471 ZTI_INIT(ztest_device_removal, 1, &zopt_sometimes),
472 ZTI_INIT(ztest_spa_checkpoint_create_discard, 1, &zopt_rarely),
473 ZTI_INIT(ztest_initialize, 1, &zopt_sometimes),
474 ZTI_INIT(ztest_trim, 1, &zopt_sometimes),
475 ZTI_INIT(ztest_blake3, 1, &zopt_rarely),
476 ZTI_INIT(ztest_fletcher, 1, &zopt_rarely),
477 ZTI_INIT(ztest_fletcher_incr, 1, &zopt_rarely),
478 ZTI_INIT(ztest_verify_dnode_bt, 1, &zopt_sometimes),
481 #define ZTEST_FUNCS (sizeof (ztest_info) / sizeof (ztest_info_t))
484 * The following struct is used to hold a list of uncalled commit callbacks.
485 * The callbacks are ordered by txg number.
487 typedef struct ztest_cb_list {
488 kmutex_t zcl_callbacks_lock;
489 list_t zcl_callbacks;
493 * Stuff we need to share writably between parent and child.
495 typedef struct ztest_shared {
496 boolean_t zs_do_init;
497 hrtime_t zs_proc_start;
498 hrtime_t zs_proc_stop;
499 hrtime_t zs_thread_start;
500 hrtime_t zs_thread_stop;
501 hrtime_t zs_thread_kill;
502 uint64_t zs_enospc_count;
503 uint64_t zs_vdev_next_leaf;
504 uint64_t zs_vdev_aux;
509 uint64_t zs_metaslab_sz;
510 uint64_t zs_metaslab_df_alloc_threshold;
514 #define ID_PARALLEL -1ULL
516 static char ztest_dev_template[] = "%s/%s.%llua";
517 static char ztest_aux_template[] = "%s/%s.%s.%llu";
518 static ztest_shared_t *ztest_shared;
520 static spa_t *ztest_spa = NULL;
521 static ztest_ds_t *ztest_ds;
523 static kmutex_t ztest_vdev_lock;
524 static boolean_t ztest_device_removal_active = B_FALSE;
525 static boolean_t ztest_pool_scrubbed = B_FALSE;
526 static kmutex_t ztest_checkpoint_lock;
529 * The ztest_name_lock protects the pool and dataset namespace used by
530 * the individual tests. To modify the namespace, consumers must grab
531 * this lock as writer. Grabbing the lock as reader will ensure that the
532 * namespace does not change while the lock is held.
534 static pthread_rwlock_t ztest_name_lock;
536 static boolean_t ztest_dump_core = B_TRUE;
537 static boolean_t ztest_exiting;
539 /* Global commit callback list */
540 static ztest_cb_list_t zcl;
541 /* Commit cb delay */
542 static uint64_t zc_min_txg_delay = UINT64_MAX;
543 static int zc_cb_counter = 0;
546 * Minimum number of commit callbacks that need to be registered for us to check
547 * whether the minimum txg delay is acceptable.
549 #define ZTEST_COMMIT_CB_MIN_REG 100
552 * If a number of txgs equal to this threshold have been created after a commit
553 * callback has been registered but not called, then we assume there is an
554 * implementation bug.
556 #define ZTEST_COMMIT_CB_THRESH (TXG_CONCURRENT_STATES + 1000)
559 ZTEST_META_DNODE = 0,
564 static __attribute__((noreturn)) void usage(boolean_t requested);
565 static int ztest_scrub_impl(spa_t *spa);
568 * These libumem hooks provide a reasonable set of defaults for the allocator's
569 * debugging facilities.
572 _umem_debug_init(void)
574 return ("default,verbose"); /* $UMEM_DEBUG setting */
578 _umem_logging_init(void)
580 return ("fail,contents"); /* $UMEM_LOGGING setting */
584 dump_debug_buffer(void)
586 ssize_t ret __attribute__((unused));
588 if (!ztest_opts.zo_dump_dbgmsg)
592 * We use write() instead of printf() so that this function
593 * is safe to call from a signal handler.
595 ret = write(STDOUT_FILENO, "\n", 1);
596 zfs_dbgmsg_print("ztest");
599 #define BACKTRACE_SZ 100
601 static void sig_handler(int signo)
603 struct sigaction action;
604 #if (__GLIBC__ && !__UCLIBC__) /* backtrace() is a GNU extension */
606 void *buffer[BACKTRACE_SZ];
608 nptrs = backtrace(buffer, BACKTRACE_SZ);
609 backtrace_symbols_fd(buffer, nptrs, STDERR_FILENO);
614 * Restore default action and re-raise signal so SIGSEGV and
615 * SIGABRT can trigger a core dump.
617 action.sa_handler = SIG_DFL;
618 sigemptyset(&action.sa_mask);
620 (void) sigaction(signo, &action, NULL);
624 #define FATAL_MSG_SZ 1024
626 static const char *fatal_msg;
628 static __attribute__((format(printf, 2, 3))) __attribute__((noreturn)) void
629 fatal(int do_perror, const char *message, ...)
632 int save_errno = errno;
635 (void) fflush(stdout);
636 buf = umem_alloc(FATAL_MSG_SZ, UMEM_NOFAIL);
640 va_start(args, message);
641 (void) sprintf(buf, "ztest: ");
643 (void) vsprintf(buf + strlen(buf), message, args);
646 (void) snprintf(buf + strlen(buf), FATAL_MSG_SZ - strlen(buf),
647 ": %s", strerror(save_errno));
649 (void) fprintf(stderr, "%s\n", buf);
650 fatal_msg = buf; /* to ease debugging */
662 str2shift(const char *buf)
664 const char *ends = "BKMGTPEZ";
669 for (i = 0; i < strlen(ends); i++) {
670 if (toupper(buf[0]) == ends[i])
673 if (i == strlen(ends)) {
674 (void) fprintf(stderr, "ztest: invalid bytes suffix: %s\n",
678 if (buf[1] == '\0' || (toupper(buf[1]) == 'B' && buf[2] == '\0')) {
681 (void) fprintf(stderr, "ztest: invalid bytes suffix: %s\n", buf);
686 nicenumtoull(const char *buf)
691 val = strtoull(buf, &end, 0);
693 (void) fprintf(stderr, "ztest: bad numeric value: %s\n", buf);
695 } else if (end[0] == '.') {
696 double fval = strtod(buf, &end);
697 fval *= pow(2, str2shift(end));
699 * UINT64_MAX is not exactly representable as a double.
700 * The closest representation is UINT64_MAX + 1, so we
701 * use a >= comparison instead of > for the bounds check.
703 if (fval >= (double)UINT64_MAX) {
704 (void) fprintf(stderr, "ztest: value too large: %s\n",
708 val = (uint64_t)fval;
710 int shift = str2shift(end);
711 if (shift >= 64 || (val << shift) >> shift != val) {
712 (void) fprintf(stderr, "ztest: value too large: %s\n",
721 typedef struct ztest_option {
722 const char short_opt;
723 const char *long_opt;
724 const char *long_opt_param;
726 unsigned int default_int;
727 const char *default_str;
731 * The following option_table is used for generating the usage info as well as
732 * the long and short option information for calling getopt_long().
734 static ztest_option_t option_table[] = {
735 { 'v', "vdevs", "INTEGER", "Number of vdevs", DEFAULT_VDEV_COUNT,
737 { 's', "vdev-size", "INTEGER", "Size of each vdev",
738 NO_DEFAULT, DEFAULT_VDEV_SIZE_STR},
739 { 'a', "alignment-shift", "INTEGER",
740 "Alignment shift; use 0 for random", DEFAULT_ASHIFT, NULL},
741 { 'm', "mirror-copies", "INTEGER", "Number of mirror copies",
742 DEFAULT_MIRRORS, NULL},
743 { 'r', "raid-disks", "INTEGER", "Number of raidz/draid disks",
744 DEFAULT_RAID_CHILDREN, NULL},
745 { 'R', "raid-parity", "INTEGER", "Raid parity",
746 DEFAULT_RAID_PARITY, NULL},
747 { 'K', "raid-kind", "raidz|draid|random", "Raid kind",
748 NO_DEFAULT, "random"},
749 { 'D', "draid-data", "INTEGER", "Number of draid data drives",
750 DEFAULT_DRAID_DATA, NULL},
751 { 'S', "draid-spares", "INTEGER", "Number of draid spares",
752 DEFAULT_DRAID_SPARES, NULL},
753 { 'd', "datasets", "INTEGER", "Number of datasets",
754 DEFAULT_DATASETS_COUNT, NULL},
755 { 't', "threads", "INTEGER", "Number of ztest threads",
756 DEFAULT_THREADS, NULL},
757 { 'g', "gang-block-threshold", "INTEGER",
758 "Metaslab gang block threshold",
759 NO_DEFAULT, DEFAULT_FORCE_GANGING_STR},
760 { 'i', "init-count", "INTEGER", "Number of times to initialize pool",
761 DEFAULT_INITS, NULL},
762 { 'k', "kill-percentage", "INTEGER", "Kill percentage",
763 NO_DEFAULT, DEFAULT_KILLRATE_STR},
764 { 'p', "pool-name", "STRING", "Pool name",
765 NO_DEFAULT, DEFAULT_POOL},
766 { 'f', "vdev-file-directory", "PATH", "File directory for vdev files",
767 NO_DEFAULT, DEFAULT_VDEV_DIR},
768 { 'M', "multi-host", NULL,
769 "Multi-host; simulate pool imported on remote host",
771 { 'E', "use-existing-pool", NULL,
772 "Use existing pool instead of creating new one", NO_DEFAULT, NULL},
773 { 'T', "run-time", "INTEGER", "Total run time",
774 NO_DEFAULT, DEFAULT_RUN_TIME_STR},
775 { 'P', "pass-time", "INTEGER", "Time per pass",
776 NO_DEFAULT, DEFAULT_PASS_TIME_STR},
777 { 'F', "freeze-loops", "INTEGER", "Max loops in spa_freeze()",
778 DEFAULT_MAX_LOOPS, NULL},
779 { 'B', "alt-ztest", "PATH", "Alternate ztest path",
781 { 'C', "vdev-class-state", "on|off|random", "vdev class state",
782 NO_DEFAULT, "random"},
783 { 'o', "option", "\"OPTION=INTEGER\"",
784 "Set global variable to an unsigned 32-bit integer value",
786 { 'G', "dump-debug-msg", NULL,
787 "Dump zfs_dbgmsg buffer before exiting due to an error",
789 { 'V', "verbose", NULL,
790 "Verbose (use multiple times for ever more verbosity)",
792 { 'h', "help", NULL, "Show this help",
797 static struct option *long_opts = NULL;
798 static char *short_opts = NULL;
803 ASSERT3P(long_opts, ==, NULL);
804 ASSERT3P(short_opts, ==, NULL);
806 int count = sizeof (option_table) / sizeof (option_table[0]);
807 long_opts = umem_alloc(sizeof (struct option) * count, UMEM_NOFAIL);
809 short_opts = umem_alloc(sizeof (char) * 2 * count, UMEM_NOFAIL);
810 int short_opt_index = 0;
812 for (int i = 0; i < count; i++) {
813 long_opts[i].val = option_table[i].short_opt;
814 long_opts[i].name = option_table[i].long_opt;
815 long_opts[i].has_arg = option_table[i].long_opt_param != NULL
816 ? required_argument : no_argument;
817 long_opts[i].flag = NULL;
818 short_opts[short_opt_index++] = option_table[i].short_opt;
819 if (option_table[i].long_opt_param != NULL) {
820 short_opts[short_opt_index++] = ':';
828 int count = sizeof (option_table) / sizeof (option_table[0]);
830 umem_free(long_opts, sizeof (struct option) * count);
831 umem_free(short_opts, sizeof (char) * 2 * count);
837 static __attribute__((noreturn)) void
838 usage(boolean_t requested)
841 FILE *fp = requested ? stdout : stderr;
843 (void) fprintf(fp, "Usage: %s [OPTIONS...]\n", DEFAULT_POOL);
844 for (int i = 0; option_table[i].short_opt != 0; i++) {
845 if (option_table[i].long_opt_param != NULL) {
846 (void) sprintf(option, " -%c --%s=%s",
847 option_table[i].short_opt,
848 option_table[i].long_opt,
849 option_table[i].long_opt_param);
851 (void) sprintf(option, " -%c --%s",
852 option_table[i].short_opt,
853 option_table[i].long_opt);
855 (void) fprintf(fp, " %-40s%s", option,
856 option_table[i].comment);
858 if (option_table[i].long_opt_param != NULL) {
859 if (option_table[i].default_str != NULL) {
860 (void) fprintf(fp, " (default: %s)",
861 option_table[i].default_str);
862 } else if (option_table[i].default_int != NO_DEFAULT) {
863 (void) fprintf(fp, " (default: %u)",
864 option_table[i].default_int);
867 (void) fprintf(fp, "\n");
869 exit(requested ? 0 : 1);
873 ztest_random(uint64_t range)
877 ASSERT3S(ztest_fd_rand, >=, 0);
882 if (read(ztest_fd_rand, &r, sizeof (r)) != sizeof (r))
883 fatal(B_TRUE, "short read from /dev/urandom");
889 ztest_parse_name_value(const char *input, ztest_shared_opts_t *zo)
893 int state = ZTEST_VDEV_CLASS_RND;
895 (void) strlcpy(name, input, sizeof (name));
897 value = strchr(name, '=');
899 (void) fprintf(stderr, "missing value in property=value "
900 "'-C' argument (%s)\n", input);
906 if (strcmp(value, "on") == 0) {
907 state = ZTEST_VDEV_CLASS_ON;
908 } else if (strcmp(value, "off") == 0) {
909 state = ZTEST_VDEV_CLASS_OFF;
910 } else if (strcmp(value, "random") == 0) {
911 state = ZTEST_VDEV_CLASS_RND;
913 (void) fprintf(stderr, "invalid property value '%s'\n", value);
917 if (strcmp(name, "special") == 0) {
918 zo->zo_special_vdevs = state;
920 (void) fprintf(stderr, "invalid property name '%s'\n", name);
923 if (zo->zo_verbose >= 3)
924 (void) printf("%s vdev state is '%s'\n", name, value);
928 process_options(int argc, char **argv)
931 ztest_shared_opts_t *zo = &ztest_opts;
935 const char *raid_kind = "random";
937 memcpy(zo, &ztest_opts_defaults, sizeof (*zo));
941 while ((opt = getopt_long(argc, argv, short_opts, long_opts,
961 value = nicenumtoull(optarg);
965 zo->zo_vdevs = value;
968 zo->zo_vdev_size = MAX(SPA_MINDEVSIZE, value);
971 zo->zo_ashift = value;
974 zo->zo_mirrors = value;
977 zo->zo_raid_children = MAX(1, value);
980 zo->zo_raid_parity = MIN(MAX(value, 1), 3);
986 zo->zo_draid_data = MAX(1, value);
989 zo->zo_draid_spares = MAX(1, value);
992 zo->zo_datasets = MAX(1, value);
995 zo->zo_threads = MAX(1, value);
998 zo->zo_metaslab_force_ganging =
999 MAX(SPA_MINBLOCKSIZE << 1, value);
1002 zo->zo_init = value;
1005 zo->zo_killrate = value;
1008 (void) strlcpy(zo->zo_pool, optarg,
1009 sizeof (zo->zo_pool));
1012 path = realpath(optarg, NULL);
1014 (void) fprintf(stderr, "error: %s: %s\n",
1015 optarg, strerror(errno));
1018 (void) strlcpy(zo->zo_dir, path,
1019 sizeof (zo->zo_dir));
1024 zo->zo_mmp_test = 1;
1033 zo->zo_time = value;
1036 zo->zo_passtime = MAX(1, value);
1039 zo->zo_maxloops = MAX(1, value);
1042 (void) strlcpy(zo->zo_alt_ztest, optarg,
1043 sizeof (zo->zo_alt_ztest));
1046 ztest_parse_name_value(optarg, zo);
1049 if (zo->zo_gvars_count >= ZO_GVARS_MAX_COUNT) {
1050 (void) fprintf(stderr,
1051 "max global var count (%zu) exceeded\n",
1052 ZO_GVARS_MAX_COUNT);
1055 char *v = zo->zo_gvars[zo->zo_gvars_count];
1056 if (strlcpy(v, optarg, ZO_GVARS_MAX_ARGLEN) >=
1057 ZO_GVARS_MAX_ARGLEN) {
1058 (void) fprintf(stderr,
1059 "global var option '%s' is too long\n",
1063 zo->zo_gvars_count++;
1066 zo->zo_dump_dbgmsg = 1;
1080 /* When raid choice is 'random' add a draid pool 50% of the time */
1081 if (strcmp(raid_kind, "random") == 0) {
1082 raid_kind = (ztest_random(2) == 0) ? "draid" : "raidz";
1084 if (ztest_opts.zo_verbose >= 3)
1085 (void) printf("choosing RAID type '%s'\n", raid_kind);
1088 if (strcmp(raid_kind, "draid") == 0) {
1089 uint64_t min_devsize;
1091 /* With fewer disk use 256M, otherwise 128M is OK */
1092 min_devsize = (ztest_opts.zo_raid_children < 16) ?
1093 (256ULL << 20) : (128ULL << 20);
1095 /* No top-level mirrors with dRAID for now */
1098 /* Use more appropriate defaults for dRAID */
1099 if (zo->zo_vdevs == ztest_opts_defaults.zo_vdevs)
1101 if (zo->zo_raid_children ==
1102 ztest_opts_defaults.zo_raid_children)
1103 zo->zo_raid_children = 16;
1104 if (zo->zo_ashift < 12)
1106 if (zo->zo_vdev_size < min_devsize)
1107 zo->zo_vdev_size = min_devsize;
1109 if (zo->zo_draid_data + zo->zo_raid_parity >
1110 zo->zo_raid_children - zo->zo_draid_spares) {
1111 (void) fprintf(stderr, "error: too few draid "
1112 "children (%d) for stripe width (%d)\n",
1113 zo->zo_raid_children,
1114 zo->zo_draid_data + zo->zo_raid_parity);
1118 (void) strlcpy(zo->zo_raid_type, VDEV_TYPE_DRAID,
1119 sizeof (zo->zo_raid_type));
1121 } else /* using raidz */ {
1122 ASSERT0(strcmp(raid_kind, "raidz"));
1124 zo->zo_raid_parity = MIN(zo->zo_raid_parity,
1125 zo->zo_raid_children - 1);
1129 (zo->zo_vdevs > 0 ? zo->zo_time * NANOSEC / zo->zo_vdevs :
1132 if (*zo->zo_alt_ztest) {
1133 const char *invalid_what = "ztest";
1134 char *val = zo->zo_alt_ztest;
1135 if (0 != access(val, X_OK) ||
1136 (strrchr(val, '/') == NULL && (errno == EINVAL)))
1139 int dirlen = strrchr(val, '/') - val;
1140 strlcpy(zo->zo_alt_libpath, val,
1141 MIN(sizeof (zo->zo_alt_libpath), dirlen + 1));
1142 invalid_what = "library path", val = zo->zo_alt_libpath;
1143 if (strrchr(val, '/') == NULL && (errno == EINVAL))
1145 *strrchr(val, '/') = '\0';
1146 strlcat(val, "/lib", sizeof (zo->zo_alt_libpath));
1148 if (0 != access(zo->zo_alt_libpath, X_OK))
1153 ztest_dump_core = B_FALSE;
1154 fatal(B_TRUE, "invalid alternate %s %s", invalid_what, val);
1159 ztest_kill(ztest_shared_t *zs)
1161 zs->zs_alloc = metaslab_class_get_alloc(spa_normal_class(ztest_spa));
1162 zs->zs_space = metaslab_class_get_space(spa_normal_class(ztest_spa));
1165 * Before we kill ourselves, make sure that the config is updated.
1166 * See comment above spa_write_cachefile().
1168 mutex_enter(&spa_namespace_lock);
1169 spa_write_cachefile(ztest_spa, B_FALSE, B_FALSE, B_FALSE);
1170 mutex_exit(&spa_namespace_lock);
1172 (void) raise(SIGKILL);
1176 ztest_record_enospc(const char *s)
1179 ztest_shared->zs_enospc_count++;
1183 ztest_get_ashift(void)
1185 if (ztest_opts.zo_ashift == 0)
1186 return (SPA_MINBLOCKSHIFT + ztest_random(5));
1187 return (ztest_opts.zo_ashift);
1191 ztest_is_draid_spare(const char *name)
1193 uint64_t spare_id = 0, parity = 0, vdev_id = 0;
1195 if (sscanf(name, VDEV_TYPE_DRAID "%"PRIu64"-%"PRIu64"-%"PRIu64"",
1196 &parity, &vdev_id, &spare_id) == 3) {
1204 make_vdev_file(const char *path, const char *aux, const char *pool,
1205 size_t size, uint64_t ashift)
1207 char *pathbuf = NULL;
1210 boolean_t draid_spare = B_FALSE;
1214 ashift = ztest_get_ashift();
1217 pathbuf = umem_alloc(MAXPATHLEN, UMEM_NOFAIL);
1221 vdev = ztest_shared->zs_vdev_aux;
1222 (void) snprintf(pathbuf, MAXPATHLEN,
1223 ztest_aux_template, ztest_opts.zo_dir,
1224 pool == NULL ? ztest_opts.zo_pool : pool,
1227 vdev = ztest_shared->zs_vdev_next_leaf++;
1228 (void) snprintf(pathbuf, MAXPATHLEN,
1229 ztest_dev_template, ztest_opts.zo_dir,
1230 pool == NULL ? ztest_opts.zo_pool : pool, vdev);
1233 draid_spare = ztest_is_draid_spare(path);
1236 if (size != 0 && !draid_spare) {
1237 int fd = open(path, O_RDWR | O_CREAT | O_TRUNC, 0666);
1239 fatal(B_TRUE, "can't open %s", path);
1240 if (ftruncate(fd, size) != 0)
1241 fatal(B_TRUE, "can't ftruncate %s", path);
1245 file = fnvlist_alloc();
1246 fnvlist_add_string(file, ZPOOL_CONFIG_TYPE,
1247 draid_spare ? VDEV_TYPE_DRAID_SPARE : VDEV_TYPE_FILE);
1248 fnvlist_add_string(file, ZPOOL_CONFIG_PATH, path);
1249 fnvlist_add_uint64(file, ZPOOL_CONFIG_ASHIFT, ashift);
1250 umem_free(pathbuf, MAXPATHLEN);
1256 make_vdev_raid(const char *path, const char *aux, const char *pool, size_t size,
1257 uint64_t ashift, int r)
1259 nvlist_t *raid, **child;
1263 return (make_vdev_file(path, aux, pool, size, ashift));
1264 child = umem_alloc(r * sizeof (nvlist_t *), UMEM_NOFAIL);
1266 for (c = 0; c < r; c++)
1267 child[c] = make_vdev_file(path, aux, pool, size, ashift);
1269 raid = fnvlist_alloc();
1270 fnvlist_add_string(raid, ZPOOL_CONFIG_TYPE,
1271 ztest_opts.zo_raid_type);
1272 fnvlist_add_uint64(raid, ZPOOL_CONFIG_NPARITY,
1273 ztest_opts.zo_raid_parity);
1274 fnvlist_add_nvlist_array(raid, ZPOOL_CONFIG_CHILDREN,
1275 (const nvlist_t **)child, r);
1277 if (strcmp(ztest_opts.zo_raid_type, VDEV_TYPE_DRAID) == 0) {
1278 uint64_t ndata = ztest_opts.zo_draid_data;
1279 uint64_t nparity = ztest_opts.zo_raid_parity;
1280 uint64_t nspares = ztest_opts.zo_draid_spares;
1281 uint64_t children = ztest_opts.zo_raid_children;
1282 uint64_t ngroups = 1;
1285 * Calculate the minimum number of groups required to fill a
1286 * slice. This is the LCM of the stripe width (data + parity)
1287 * and the number of data drives (children - spares).
1289 while (ngroups * (ndata + nparity) % (children - nspares) != 0)
1292 /* Store the basic dRAID configuration. */
1293 fnvlist_add_uint64(raid, ZPOOL_CONFIG_DRAID_NDATA, ndata);
1294 fnvlist_add_uint64(raid, ZPOOL_CONFIG_DRAID_NSPARES, nspares);
1295 fnvlist_add_uint64(raid, ZPOOL_CONFIG_DRAID_NGROUPS, ngroups);
1298 for (c = 0; c < r; c++)
1299 fnvlist_free(child[c]);
1301 umem_free(child, r * sizeof (nvlist_t *));
1307 make_vdev_mirror(const char *path, const char *aux, const char *pool,
1308 size_t size, uint64_t ashift, int r, int m)
1310 nvlist_t *mirror, **child;
1314 return (make_vdev_raid(path, aux, pool, size, ashift, r));
1316 child = umem_alloc(m * sizeof (nvlist_t *), UMEM_NOFAIL);
1318 for (c = 0; c < m; c++)
1319 child[c] = make_vdev_raid(path, aux, pool, size, ashift, r);
1321 mirror = fnvlist_alloc();
1322 fnvlist_add_string(mirror, ZPOOL_CONFIG_TYPE, VDEV_TYPE_MIRROR);
1323 fnvlist_add_nvlist_array(mirror, ZPOOL_CONFIG_CHILDREN,
1324 (const nvlist_t **)child, m);
1326 for (c = 0; c < m; c++)
1327 fnvlist_free(child[c]);
1329 umem_free(child, m * sizeof (nvlist_t *));
1335 make_vdev_root(const char *path, const char *aux, const char *pool, size_t size,
1336 uint64_t ashift, const char *class, int r, int m, int t)
1338 nvlist_t *root, **child;
1344 log = (class != NULL && strcmp(class, "log") == 0);
1346 child = umem_alloc(t * sizeof (nvlist_t *), UMEM_NOFAIL);
1348 for (c = 0; c < t; c++) {
1349 child[c] = make_vdev_mirror(path, aux, pool, size, ashift,
1351 fnvlist_add_uint64(child[c], ZPOOL_CONFIG_IS_LOG, log);
1353 if (class != NULL && class[0] != '\0') {
1354 ASSERT(m > 1 || log); /* expecting a mirror */
1355 fnvlist_add_string(child[c],
1356 ZPOOL_CONFIG_ALLOCATION_BIAS, class);
1360 root = fnvlist_alloc();
1361 fnvlist_add_string(root, ZPOOL_CONFIG_TYPE, VDEV_TYPE_ROOT);
1362 fnvlist_add_nvlist_array(root, aux ? aux : ZPOOL_CONFIG_CHILDREN,
1363 (const nvlist_t **)child, t);
1365 for (c = 0; c < t; c++)
1366 fnvlist_free(child[c]);
1368 umem_free(child, t * sizeof (nvlist_t *));
1374 * Find a random spa version. Returns back a random spa version in the
1375 * range [initial_version, SPA_VERSION_FEATURES].
1378 ztest_random_spa_version(uint64_t initial_version)
1380 uint64_t version = initial_version;
1382 if (version <= SPA_VERSION_BEFORE_FEATURES) {
1384 ztest_random(SPA_VERSION_BEFORE_FEATURES - version + 1);
1387 if (version > SPA_VERSION_BEFORE_FEATURES)
1388 version = SPA_VERSION_FEATURES;
1390 ASSERT(SPA_VERSION_IS_SUPPORTED(version));
1395 ztest_random_blocksize(void)
1397 ASSERT3U(ztest_spa->spa_max_ashift, !=, 0);
1400 * Choose a block size >= the ashift.
1401 * If the SPA supports new MAXBLOCKSIZE, test up to 1MB blocks.
1403 int maxbs = SPA_OLD_MAXBLOCKSHIFT;
1404 if (spa_maxblocksize(ztest_spa) == SPA_MAXBLOCKSIZE)
1406 uint64_t block_shift =
1407 ztest_random(maxbs - ztest_spa->spa_max_ashift + 1);
1408 return (1 << (SPA_MINBLOCKSHIFT + block_shift));
1412 ztest_random_dnodesize(void)
1415 int max_slots = spa_maxdnodesize(ztest_spa) >> DNODE_SHIFT;
1417 if (max_slots == DNODE_MIN_SLOTS)
1418 return (DNODE_MIN_SIZE);
1421 * Weight the random distribution more heavily toward smaller
1422 * dnode sizes since that is more likely to reflect real-world
1425 ASSERT3U(max_slots, >, 4);
1426 switch (ztest_random(10)) {
1428 slots = 5 + ztest_random(max_slots - 4);
1431 slots = 2 + ztest_random(3);
1438 return (slots << DNODE_SHIFT);
1442 ztest_random_ibshift(void)
1444 return (DN_MIN_INDBLKSHIFT +
1445 ztest_random(DN_MAX_INDBLKSHIFT - DN_MIN_INDBLKSHIFT + 1));
1449 ztest_random_vdev_top(spa_t *spa, boolean_t log_ok)
1452 vdev_t *rvd = spa->spa_root_vdev;
1455 ASSERT3U(spa_config_held(spa, SCL_ALL, RW_READER), !=, 0);
1458 top = ztest_random(rvd->vdev_children);
1459 tvd = rvd->vdev_child[top];
1460 } while (!vdev_is_concrete(tvd) || (tvd->vdev_islog && !log_ok) ||
1461 tvd->vdev_mg == NULL || tvd->vdev_mg->mg_class == NULL);
1467 ztest_random_dsl_prop(zfs_prop_t prop)
1472 value = zfs_prop_random_value(prop, ztest_random(-1ULL));
1473 } while (prop == ZFS_PROP_CHECKSUM && value == ZIO_CHECKSUM_OFF);
1479 ztest_dsl_prop_set_uint64(char *osname, zfs_prop_t prop, uint64_t value,
1482 const char *propname = zfs_prop_to_name(prop);
1483 const char *valname;
1488 error = dsl_prop_set_int(osname, propname,
1489 (inherit ? ZPROP_SRC_NONE : ZPROP_SRC_LOCAL), value);
1491 if (error == ENOSPC) {
1492 ztest_record_enospc(FTAG);
1497 setpoint = umem_alloc(MAXPATHLEN, UMEM_NOFAIL);
1498 VERIFY0(dsl_prop_get_integer(osname, propname, &curval, setpoint));
1500 if (ztest_opts.zo_verbose >= 6) {
1503 err = zfs_prop_index_to_string(prop, curval, &valname);
1505 (void) printf("%s %s = %llu at '%s'\n", osname,
1506 propname, (unsigned long long)curval, setpoint);
1508 (void) printf("%s %s = %s at '%s'\n",
1509 osname, propname, valname, setpoint);
1511 umem_free(setpoint, MAXPATHLEN);
1517 ztest_spa_prop_set_uint64(zpool_prop_t prop, uint64_t value)
1519 spa_t *spa = ztest_spa;
1520 nvlist_t *props = NULL;
1523 props = fnvlist_alloc();
1524 fnvlist_add_uint64(props, zpool_prop_to_name(prop), value);
1526 error = spa_prop_set(spa, props);
1528 fnvlist_free(props);
1530 if (error == ENOSPC) {
1531 ztest_record_enospc(FTAG);
1540 ztest_dmu_objset_own(const char *name, dmu_objset_type_t type,
1541 boolean_t readonly, boolean_t decrypt, const void *tag, objset_t **osp)
1545 char ddname[ZFS_MAX_DATASET_NAME_LEN];
1547 strlcpy(ddname, name, sizeof (ddname));
1548 cp = strchr(ddname, '@');
1552 err = dmu_objset_own(name, type, readonly, decrypt, tag, osp);
1553 while (decrypt && err == EACCES) {
1554 dsl_crypto_params_t *dcp;
1555 nvlist_t *crypto_args = fnvlist_alloc();
1557 fnvlist_add_uint8_array(crypto_args, "wkeydata",
1558 (uint8_t *)ztest_wkeydata, WRAPPING_KEY_LEN);
1559 VERIFY0(dsl_crypto_params_create_nvlist(DCP_CMD_NONE, NULL,
1560 crypto_args, &dcp));
1561 err = spa_keystore_load_wkey(ddname, dcp, B_FALSE);
1563 * Note: if there was an error loading, the wkey was not
1564 * consumed, and needs to be freed.
1566 dsl_crypto_params_free(dcp, (err != 0));
1567 fnvlist_free(crypto_args);
1569 if (err == EINVAL) {
1571 * We couldn't load a key for this dataset so try
1572 * the parent. This loop will eventually hit the
1573 * encryption root since ztest only makes clones
1574 * as children of their origin datasets.
1576 cp = strrchr(ddname, '/');
1583 } else if (err != 0) {
1587 err = dmu_objset_own(name, type, readonly, decrypt, tag, osp);
1595 ztest_rll_init(rll_t *rll)
1597 rll->rll_writer = NULL;
1598 rll->rll_readers = 0;
1599 mutex_init(&rll->rll_lock, NULL, MUTEX_DEFAULT, NULL);
1600 cv_init(&rll->rll_cv, NULL, CV_DEFAULT, NULL);
1604 ztest_rll_destroy(rll_t *rll)
1606 ASSERT3P(rll->rll_writer, ==, NULL);
1607 ASSERT0(rll->rll_readers);
1608 mutex_destroy(&rll->rll_lock);
1609 cv_destroy(&rll->rll_cv);
1613 ztest_rll_lock(rll_t *rll, rl_type_t type)
1615 mutex_enter(&rll->rll_lock);
1617 if (type == RL_READER) {
1618 while (rll->rll_writer != NULL)
1619 (void) cv_wait(&rll->rll_cv, &rll->rll_lock);
1622 while (rll->rll_writer != NULL || rll->rll_readers)
1623 (void) cv_wait(&rll->rll_cv, &rll->rll_lock);
1624 rll->rll_writer = curthread;
1627 mutex_exit(&rll->rll_lock);
1631 ztest_rll_unlock(rll_t *rll)
1633 mutex_enter(&rll->rll_lock);
1635 if (rll->rll_writer) {
1636 ASSERT0(rll->rll_readers);
1637 rll->rll_writer = NULL;
1639 ASSERT3S(rll->rll_readers, >, 0);
1640 ASSERT3P(rll->rll_writer, ==, NULL);
1644 if (rll->rll_writer == NULL && rll->rll_readers == 0)
1645 cv_broadcast(&rll->rll_cv);
1647 mutex_exit(&rll->rll_lock);
1651 ztest_object_lock(ztest_ds_t *zd, uint64_t object, rl_type_t type)
1653 rll_t *rll = &zd->zd_object_lock[object & (ZTEST_OBJECT_LOCKS - 1)];
1655 ztest_rll_lock(rll, type);
1659 ztest_object_unlock(ztest_ds_t *zd, uint64_t object)
1661 rll_t *rll = &zd->zd_object_lock[object & (ZTEST_OBJECT_LOCKS - 1)];
1663 ztest_rll_unlock(rll);
1667 ztest_range_lock(ztest_ds_t *zd, uint64_t object, uint64_t offset,
1668 uint64_t size, rl_type_t type)
1670 uint64_t hash = object ^ (offset % (ZTEST_RANGE_LOCKS + 1));
1671 rll_t *rll = &zd->zd_range_lock[hash & (ZTEST_RANGE_LOCKS - 1)];
1674 rl = umem_alloc(sizeof (*rl), UMEM_NOFAIL);
1675 rl->rl_object = object;
1676 rl->rl_offset = offset;
1680 ztest_rll_lock(rll, type);
1686 ztest_range_unlock(rl_t *rl)
1688 rll_t *rll = rl->rl_lock;
1690 ztest_rll_unlock(rll);
1692 umem_free(rl, sizeof (*rl));
1696 ztest_zd_init(ztest_ds_t *zd, ztest_shared_ds_t *szd, objset_t *os)
1699 zd->zd_zilog = dmu_objset_zil(os);
1700 zd->zd_shared = szd;
1701 dmu_objset_name(os, zd->zd_name);
1704 if (zd->zd_shared != NULL)
1705 zd->zd_shared->zd_seq = 0;
1707 VERIFY0(pthread_rwlock_init(&zd->zd_zilog_lock, NULL));
1708 mutex_init(&zd->zd_dirobj_lock, NULL, MUTEX_DEFAULT, NULL);
1710 for (l = 0; l < ZTEST_OBJECT_LOCKS; l++)
1711 ztest_rll_init(&zd->zd_object_lock[l]);
1713 for (l = 0; l < ZTEST_RANGE_LOCKS; l++)
1714 ztest_rll_init(&zd->zd_range_lock[l]);
1718 ztest_zd_fini(ztest_ds_t *zd)
1722 mutex_destroy(&zd->zd_dirobj_lock);
1723 (void) pthread_rwlock_destroy(&zd->zd_zilog_lock);
1725 for (l = 0; l < ZTEST_OBJECT_LOCKS; l++)
1726 ztest_rll_destroy(&zd->zd_object_lock[l]);
1728 for (l = 0; l < ZTEST_RANGE_LOCKS; l++)
1729 ztest_rll_destroy(&zd->zd_range_lock[l]);
1732 #define TXG_MIGHTWAIT (ztest_random(10) == 0 ? TXG_NOWAIT : TXG_WAIT)
1735 ztest_tx_assign(dmu_tx_t *tx, uint64_t txg_how, const char *tag)
1741 * Attempt to assign tx to some transaction group.
1743 error = dmu_tx_assign(tx, txg_how);
1745 if (error == ERESTART) {
1746 ASSERT3U(txg_how, ==, TXG_NOWAIT);
1749 ASSERT3U(error, ==, ENOSPC);
1750 ztest_record_enospc(tag);
1755 txg = dmu_tx_get_txg(tx);
1756 ASSERT3U(txg, !=, 0);
1761 ztest_bt_generate(ztest_block_tag_t *bt, objset_t *os, uint64_t object,
1762 uint64_t dnodesize, uint64_t offset, uint64_t gen, uint64_t txg,
1765 bt->bt_magic = BT_MAGIC;
1766 bt->bt_objset = dmu_objset_id(os);
1767 bt->bt_object = object;
1768 bt->bt_dnodesize = dnodesize;
1769 bt->bt_offset = offset;
1772 bt->bt_crtxg = crtxg;
1776 ztest_bt_verify(ztest_block_tag_t *bt, objset_t *os, uint64_t object,
1777 uint64_t dnodesize, uint64_t offset, uint64_t gen, uint64_t txg,
1780 ASSERT3U(bt->bt_magic, ==, BT_MAGIC);
1781 ASSERT3U(bt->bt_objset, ==, dmu_objset_id(os));
1782 ASSERT3U(bt->bt_object, ==, object);
1783 ASSERT3U(bt->bt_dnodesize, ==, dnodesize);
1784 ASSERT3U(bt->bt_offset, ==, offset);
1785 ASSERT3U(bt->bt_gen, <=, gen);
1786 ASSERT3U(bt->bt_txg, <=, txg);
1787 ASSERT3U(bt->bt_crtxg, ==, crtxg);
1790 static ztest_block_tag_t *
1791 ztest_bt_bonus(dmu_buf_t *db)
1793 dmu_object_info_t doi;
1794 ztest_block_tag_t *bt;
1796 dmu_object_info_from_db(db, &doi);
1797 ASSERT3U(doi.doi_bonus_size, <=, db->db_size);
1798 ASSERT3U(doi.doi_bonus_size, >=, sizeof (*bt));
1799 bt = (void *)((char *)db->db_data + doi.doi_bonus_size - sizeof (*bt));
1805 * Generate a token to fill up unused bonus buffer space. Try to make
1806 * it unique to the object, generation, and offset to verify that data
1807 * is not getting overwritten by data from other dnodes.
1809 #define ZTEST_BONUS_FILL_TOKEN(obj, ds, gen, offset) \
1810 (((ds) << 48) | ((gen) << 32) | ((obj) << 8) | (offset))
1813 * Fill up the unused bonus buffer region before the block tag with a
1814 * verifiable pattern. Filling the whole bonus area with non-zero data
1815 * helps ensure that all dnode traversal code properly skips the
1816 * interior regions of large dnodes.
1819 ztest_fill_unused_bonus(dmu_buf_t *db, void *end, uint64_t obj,
1820 objset_t *os, uint64_t gen)
1824 ASSERT(IS_P2ALIGNED((char *)end - (char *)db->db_data, 8));
1826 for (bonusp = db->db_data; bonusp < (uint64_t *)end; bonusp++) {
1827 uint64_t token = ZTEST_BONUS_FILL_TOKEN(obj, dmu_objset_id(os),
1828 gen, bonusp - (uint64_t *)db->db_data);
1834 * Verify that the unused area of a bonus buffer is filled with the
1838 ztest_verify_unused_bonus(dmu_buf_t *db, void *end, uint64_t obj,
1839 objset_t *os, uint64_t gen)
1843 for (bonusp = db->db_data; bonusp < (uint64_t *)end; bonusp++) {
1844 uint64_t token = ZTEST_BONUS_FILL_TOKEN(obj, dmu_objset_id(os),
1845 gen, bonusp - (uint64_t *)db->db_data);
1846 VERIFY3U(*bonusp, ==, token);
1854 #define lrz_type lr_mode
1855 #define lrz_blocksize lr_uid
1856 #define lrz_ibshift lr_gid
1857 #define lrz_bonustype lr_rdev
1858 #define lrz_dnodesize lr_crtime[1]
1861 ztest_log_create(ztest_ds_t *zd, dmu_tx_t *tx, lr_create_t *lr)
1863 char *name = (void *)(lr + 1); /* name follows lr */
1864 size_t namesize = strlen(name) + 1;
1867 if (zil_replaying(zd->zd_zilog, tx))
1870 itx = zil_itx_create(TX_CREATE, sizeof (*lr) + namesize);
1871 memcpy(&itx->itx_lr + 1, &lr->lr_common + 1,
1872 sizeof (*lr) + namesize - sizeof (lr_t));
1874 zil_itx_assign(zd->zd_zilog, itx, tx);
1878 ztest_log_remove(ztest_ds_t *zd, dmu_tx_t *tx, lr_remove_t *lr, uint64_t object)
1880 char *name = (void *)(lr + 1); /* name follows lr */
1881 size_t namesize = strlen(name) + 1;
1884 if (zil_replaying(zd->zd_zilog, tx))
1887 itx = zil_itx_create(TX_REMOVE, sizeof (*lr) + namesize);
1888 memcpy(&itx->itx_lr + 1, &lr->lr_common + 1,
1889 sizeof (*lr) + namesize - sizeof (lr_t));
1891 itx->itx_oid = object;
1892 zil_itx_assign(zd->zd_zilog, itx, tx);
1896 ztest_log_write(ztest_ds_t *zd, dmu_tx_t *tx, lr_write_t *lr)
1899 itx_wr_state_t write_state = ztest_random(WR_NUM_STATES);
1901 if (zil_replaying(zd->zd_zilog, tx))
1904 if (lr->lr_length > zil_max_log_data(zd->zd_zilog))
1905 write_state = WR_INDIRECT;
1907 itx = zil_itx_create(TX_WRITE,
1908 sizeof (*lr) + (write_state == WR_COPIED ? lr->lr_length : 0));
1910 if (write_state == WR_COPIED &&
1911 dmu_read(zd->zd_os, lr->lr_foid, lr->lr_offset, lr->lr_length,
1912 ((lr_write_t *)&itx->itx_lr) + 1, DMU_READ_NO_PREFETCH) != 0) {
1913 zil_itx_destroy(itx);
1914 itx = zil_itx_create(TX_WRITE, sizeof (*lr));
1915 write_state = WR_NEED_COPY;
1917 itx->itx_private = zd;
1918 itx->itx_wr_state = write_state;
1919 itx->itx_sync = (ztest_random(8) == 0);
1921 memcpy(&itx->itx_lr + 1, &lr->lr_common + 1,
1922 sizeof (*lr) - sizeof (lr_t));
1924 zil_itx_assign(zd->zd_zilog, itx, tx);
1928 ztest_log_truncate(ztest_ds_t *zd, dmu_tx_t *tx, lr_truncate_t *lr)
1932 if (zil_replaying(zd->zd_zilog, tx))
1935 itx = zil_itx_create(TX_TRUNCATE, sizeof (*lr));
1936 memcpy(&itx->itx_lr + 1, &lr->lr_common + 1,
1937 sizeof (*lr) - sizeof (lr_t));
1939 itx->itx_sync = B_FALSE;
1940 zil_itx_assign(zd->zd_zilog, itx, tx);
1944 ztest_log_setattr(ztest_ds_t *zd, dmu_tx_t *tx, lr_setattr_t *lr)
1948 if (zil_replaying(zd->zd_zilog, tx))
1951 itx = zil_itx_create(TX_SETATTR, sizeof (*lr));
1952 memcpy(&itx->itx_lr + 1, &lr->lr_common + 1,
1953 sizeof (*lr) - sizeof (lr_t));
1955 itx->itx_sync = B_FALSE;
1956 zil_itx_assign(zd->zd_zilog, itx, tx);
1963 ztest_replay_create(void *arg1, void *arg2, boolean_t byteswap)
1965 ztest_ds_t *zd = arg1;
1966 lr_create_t *lr = arg2;
1967 char *name = (void *)(lr + 1); /* name follows lr */
1968 objset_t *os = zd->zd_os;
1969 ztest_block_tag_t *bbt;
1977 byteswap_uint64_array(lr, sizeof (*lr));
1979 ASSERT3U(lr->lr_doid, ==, ZTEST_DIROBJ);
1980 ASSERT3S(name[0], !=, '\0');
1982 tx = dmu_tx_create(os);
1984 dmu_tx_hold_zap(tx, lr->lr_doid, B_TRUE, name);
1986 if (lr->lrz_type == DMU_OT_ZAP_OTHER) {
1987 dmu_tx_hold_zap(tx, DMU_NEW_OBJECT, B_TRUE, NULL);
1989 dmu_tx_hold_bonus(tx, DMU_NEW_OBJECT);
1992 txg = ztest_tx_assign(tx, TXG_WAIT, FTAG);
1996 ASSERT3U(dmu_objset_zil(os)->zl_replay, ==, !!lr->lr_foid);
1997 bonuslen = DN_BONUS_SIZE(lr->lrz_dnodesize);
1999 if (lr->lrz_type == DMU_OT_ZAP_OTHER) {
2000 if (lr->lr_foid == 0) {
2001 lr->lr_foid = zap_create_dnsize(os,
2002 lr->lrz_type, lr->lrz_bonustype,
2003 bonuslen, lr->lrz_dnodesize, tx);
2005 error = zap_create_claim_dnsize(os, lr->lr_foid,
2006 lr->lrz_type, lr->lrz_bonustype,
2007 bonuslen, lr->lrz_dnodesize, tx);
2010 if (lr->lr_foid == 0) {
2011 lr->lr_foid = dmu_object_alloc_dnsize(os,
2012 lr->lrz_type, 0, lr->lrz_bonustype,
2013 bonuslen, lr->lrz_dnodesize, tx);
2015 error = dmu_object_claim_dnsize(os, lr->lr_foid,
2016 lr->lrz_type, 0, lr->lrz_bonustype,
2017 bonuslen, lr->lrz_dnodesize, tx);
2022 ASSERT3U(error, ==, EEXIST);
2023 ASSERT(zd->zd_zilog->zl_replay);
2028 ASSERT3U(lr->lr_foid, !=, 0);
2030 if (lr->lrz_type != DMU_OT_ZAP_OTHER)
2031 VERIFY0(dmu_object_set_blocksize(os, lr->lr_foid,
2032 lr->lrz_blocksize, lr->lrz_ibshift, tx));
2034 VERIFY0(dmu_bonus_hold(os, lr->lr_foid, FTAG, &db));
2035 bbt = ztest_bt_bonus(db);
2036 dmu_buf_will_dirty(db, tx);
2037 ztest_bt_generate(bbt, os, lr->lr_foid, lr->lrz_dnodesize, -1ULL,
2038 lr->lr_gen, txg, txg);
2039 ztest_fill_unused_bonus(db, bbt, lr->lr_foid, os, lr->lr_gen);
2040 dmu_buf_rele(db, FTAG);
2042 VERIFY0(zap_add(os, lr->lr_doid, name, sizeof (uint64_t), 1,
2045 (void) ztest_log_create(zd, tx, lr);
2053 ztest_replay_remove(void *arg1, void *arg2, boolean_t byteswap)
2055 ztest_ds_t *zd = arg1;
2056 lr_remove_t *lr = arg2;
2057 char *name = (void *)(lr + 1); /* name follows lr */
2058 objset_t *os = zd->zd_os;
2059 dmu_object_info_t doi;
2061 uint64_t object, txg;
2064 byteswap_uint64_array(lr, sizeof (*lr));
2066 ASSERT3U(lr->lr_doid, ==, ZTEST_DIROBJ);
2067 ASSERT3S(name[0], !=, '\0');
2070 zap_lookup(os, lr->lr_doid, name, sizeof (object), 1, &object));
2071 ASSERT3U(object, !=, 0);
2073 ztest_object_lock(zd, object, RL_WRITER);
2075 VERIFY0(dmu_object_info(os, object, &doi));
2077 tx = dmu_tx_create(os);
2079 dmu_tx_hold_zap(tx, lr->lr_doid, B_FALSE, name);
2080 dmu_tx_hold_free(tx, object, 0, DMU_OBJECT_END);
2082 txg = ztest_tx_assign(tx, TXG_WAIT, FTAG);
2084 ztest_object_unlock(zd, object);
2088 if (doi.doi_type == DMU_OT_ZAP_OTHER) {
2089 VERIFY0(zap_destroy(os, object, tx));
2091 VERIFY0(dmu_object_free(os, object, tx));
2094 VERIFY0(zap_remove(os, lr->lr_doid, name, tx));
2096 (void) ztest_log_remove(zd, tx, lr, object);
2100 ztest_object_unlock(zd, object);
2106 ztest_replay_write(void *arg1, void *arg2, boolean_t byteswap)
2108 ztest_ds_t *zd = arg1;
2109 lr_write_t *lr = arg2;
2110 objset_t *os = zd->zd_os;
2111 void *data = lr + 1; /* data follows lr */
2112 uint64_t offset, length;
2113 ztest_block_tag_t *bt = data;
2114 ztest_block_tag_t *bbt;
2115 uint64_t gen, txg, lrtxg, crtxg;
2116 dmu_object_info_t doi;
2119 arc_buf_t *abuf = NULL;
2123 byteswap_uint64_array(lr, sizeof (*lr));
2125 offset = lr->lr_offset;
2126 length = lr->lr_length;
2128 /* If it's a dmu_sync() block, write the whole block */
2129 if (lr->lr_common.lrc_reclen == sizeof (lr_write_t)) {
2130 uint64_t blocksize = BP_GET_LSIZE(&lr->lr_blkptr);
2131 if (length < blocksize) {
2132 offset -= offset % blocksize;
2137 if (bt->bt_magic == BSWAP_64(BT_MAGIC))
2138 byteswap_uint64_array(bt, sizeof (*bt));
2140 if (bt->bt_magic != BT_MAGIC)
2143 ztest_object_lock(zd, lr->lr_foid, RL_READER);
2144 rl = ztest_range_lock(zd, lr->lr_foid, offset, length, RL_WRITER);
2146 VERIFY0(dmu_bonus_hold(os, lr->lr_foid, FTAG, &db));
2148 dmu_object_info_from_db(db, &doi);
2150 bbt = ztest_bt_bonus(db);
2151 ASSERT3U(bbt->bt_magic, ==, BT_MAGIC);
2153 crtxg = bbt->bt_crtxg;
2154 lrtxg = lr->lr_common.lrc_txg;
2156 tx = dmu_tx_create(os);
2158 dmu_tx_hold_write(tx, lr->lr_foid, offset, length);
2160 if (ztest_random(8) == 0 && length == doi.doi_data_block_size &&
2161 P2PHASE(offset, length) == 0)
2162 abuf = dmu_request_arcbuf(db, length);
2164 txg = ztest_tx_assign(tx, TXG_WAIT, FTAG);
2167 dmu_return_arcbuf(abuf);
2168 dmu_buf_rele(db, FTAG);
2169 ztest_range_unlock(rl);
2170 ztest_object_unlock(zd, lr->lr_foid);
2176 * Usually, verify the old data before writing new data --
2177 * but not always, because we also want to verify correct
2178 * behavior when the data was not recently read into cache.
2180 ASSERT(doi.doi_data_block_size);
2181 ASSERT0(offset % doi.doi_data_block_size);
2182 if (ztest_random(4) != 0) {
2183 int prefetch = ztest_random(2) ?
2184 DMU_READ_PREFETCH : DMU_READ_NO_PREFETCH;
2185 ztest_block_tag_t rbt;
2187 VERIFY(dmu_read(os, lr->lr_foid, offset,
2188 sizeof (rbt), &rbt, prefetch) == 0);
2189 if (rbt.bt_magic == BT_MAGIC) {
2190 ztest_bt_verify(&rbt, os, lr->lr_foid, 0,
2191 offset, gen, txg, crtxg);
2196 * Writes can appear to be newer than the bonus buffer because
2197 * the ztest_get_data() callback does a dmu_read() of the
2198 * open-context data, which may be different than the data
2199 * as it was when the write was generated.
2201 if (zd->zd_zilog->zl_replay) {
2202 ztest_bt_verify(bt, os, lr->lr_foid, 0, offset,
2203 MAX(gen, bt->bt_gen), MAX(txg, lrtxg),
2208 * Set the bt's gen/txg to the bonus buffer's gen/txg
2209 * so that all of the usual ASSERTs will work.
2211 ztest_bt_generate(bt, os, lr->lr_foid, 0, offset, gen, txg,
2216 dmu_write(os, lr->lr_foid, offset, length, data, tx);
2218 memcpy(abuf->b_data, data, length);
2219 VERIFY0(dmu_assign_arcbuf_by_dbuf(db, offset, abuf, tx));
2222 (void) ztest_log_write(zd, tx, lr);
2224 dmu_buf_rele(db, FTAG);
2228 ztest_range_unlock(rl);
2229 ztest_object_unlock(zd, lr->lr_foid);
2235 ztest_replay_truncate(void *arg1, void *arg2, boolean_t byteswap)
2237 ztest_ds_t *zd = arg1;
2238 lr_truncate_t *lr = arg2;
2239 objset_t *os = zd->zd_os;
2245 byteswap_uint64_array(lr, sizeof (*lr));
2247 ztest_object_lock(zd, lr->lr_foid, RL_READER);
2248 rl = ztest_range_lock(zd, lr->lr_foid, lr->lr_offset, lr->lr_length,
2251 tx = dmu_tx_create(os);
2253 dmu_tx_hold_free(tx, lr->lr_foid, lr->lr_offset, lr->lr_length);
2255 txg = ztest_tx_assign(tx, TXG_WAIT, FTAG);
2257 ztest_range_unlock(rl);
2258 ztest_object_unlock(zd, lr->lr_foid);
2262 VERIFY0(dmu_free_range(os, lr->lr_foid, lr->lr_offset,
2263 lr->lr_length, tx));
2265 (void) ztest_log_truncate(zd, tx, lr);
2269 ztest_range_unlock(rl);
2270 ztest_object_unlock(zd, lr->lr_foid);
2276 ztest_replay_setattr(void *arg1, void *arg2, boolean_t byteswap)
2278 ztest_ds_t *zd = arg1;
2279 lr_setattr_t *lr = arg2;
2280 objset_t *os = zd->zd_os;
2283 ztest_block_tag_t *bbt;
2284 uint64_t txg, lrtxg, crtxg, dnodesize;
2287 byteswap_uint64_array(lr, sizeof (*lr));
2289 ztest_object_lock(zd, lr->lr_foid, RL_WRITER);
2291 VERIFY0(dmu_bonus_hold(os, lr->lr_foid, FTAG, &db));
2293 tx = dmu_tx_create(os);
2294 dmu_tx_hold_bonus(tx, lr->lr_foid);
2296 txg = ztest_tx_assign(tx, TXG_WAIT, FTAG);
2298 dmu_buf_rele(db, FTAG);
2299 ztest_object_unlock(zd, lr->lr_foid);
2303 bbt = ztest_bt_bonus(db);
2304 ASSERT3U(bbt->bt_magic, ==, BT_MAGIC);
2305 crtxg = bbt->bt_crtxg;
2306 lrtxg = lr->lr_common.lrc_txg;
2307 dnodesize = bbt->bt_dnodesize;
2309 if (zd->zd_zilog->zl_replay) {
2310 ASSERT3U(lr->lr_size, !=, 0);
2311 ASSERT3U(lr->lr_mode, !=, 0);
2312 ASSERT3U(lrtxg, !=, 0);
2315 * Randomly change the size and increment the generation.
2317 lr->lr_size = (ztest_random(db->db_size / sizeof (*bbt)) + 1) *
2319 lr->lr_mode = bbt->bt_gen + 1;
2324 * Verify that the current bonus buffer is not newer than our txg.
2326 ztest_bt_verify(bbt, os, lr->lr_foid, dnodesize, -1ULL, lr->lr_mode,
2327 MAX(txg, lrtxg), crtxg);
2329 dmu_buf_will_dirty(db, tx);
2331 ASSERT3U(lr->lr_size, >=, sizeof (*bbt));
2332 ASSERT3U(lr->lr_size, <=, db->db_size);
2333 VERIFY0(dmu_set_bonus(db, lr->lr_size, tx));
2334 bbt = ztest_bt_bonus(db);
2336 ztest_bt_generate(bbt, os, lr->lr_foid, dnodesize, -1ULL, lr->lr_mode,
2338 ztest_fill_unused_bonus(db, bbt, lr->lr_foid, os, bbt->bt_gen);
2339 dmu_buf_rele(db, FTAG);
2341 (void) ztest_log_setattr(zd, tx, lr);
2345 ztest_object_unlock(zd, lr->lr_foid);
2350 static zil_replay_func_t *ztest_replay_vector[TX_MAX_TYPE] = {
2351 NULL, /* 0 no such transaction type */
2352 ztest_replay_create, /* TX_CREATE */
2353 NULL, /* TX_MKDIR */
2354 NULL, /* TX_MKXATTR */
2355 NULL, /* TX_SYMLINK */
2356 ztest_replay_remove, /* TX_REMOVE */
2357 NULL, /* TX_RMDIR */
2359 NULL, /* TX_RENAME */
2360 ztest_replay_write, /* TX_WRITE */
2361 ztest_replay_truncate, /* TX_TRUNCATE */
2362 ztest_replay_setattr, /* TX_SETATTR */
2364 NULL, /* TX_CREATE_ACL */
2365 NULL, /* TX_CREATE_ATTR */
2366 NULL, /* TX_CREATE_ACL_ATTR */
2367 NULL, /* TX_MKDIR_ACL */
2368 NULL, /* TX_MKDIR_ATTR */
2369 NULL, /* TX_MKDIR_ACL_ATTR */
2370 NULL, /* TX_WRITE2 */
2371 NULL, /* TX_SETSAXATTR */
2372 NULL, /* TX_RENAME_EXCHANGE */
2373 NULL, /* TX_RENAME_WHITEOUT */
2377 * ZIL get_data callbacks
2381 ztest_get_done(zgd_t *zgd, int error)
2384 ztest_ds_t *zd = zgd->zgd_private;
2385 uint64_t object = ((rl_t *)zgd->zgd_lr)->rl_object;
2388 dmu_buf_rele(zgd->zgd_db, zgd);
2390 ztest_range_unlock((rl_t *)zgd->zgd_lr);
2391 ztest_object_unlock(zd, object);
2393 umem_free(zgd, sizeof (*zgd));
2397 ztest_get_data(void *arg, uint64_t arg2, lr_write_t *lr, char *buf,
2398 struct lwb *lwb, zio_t *zio)
2401 ztest_ds_t *zd = arg;
2402 objset_t *os = zd->zd_os;
2403 uint64_t object = lr->lr_foid;
2404 uint64_t offset = lr->lr_offset;
2405 uint64_t size = lr->lr_length;
2406 uint64_t txg = lr->lr_common.lrc_txg;
2408 dmu_object_info_t doi;
2413 ASSERT3P(lwb, !=, NULL);
2414 ASSERT3P(zio, !=, NULL);
2415 ASSERT3U(size, !=, 0);
2417 ztest_object_lock(zd, object, RL_READER);
2418 error = dmu_bonus_hold(os, object, FTAG, &db);
2420 ztest_object_unlock(zd, object);
2424 crtxg = ztest_bt_bonus(db)->bt_crtxg;
2426 if (crtxg == 0 || crtxg > txg) {
2427 dmu_buf_rele(db, FTAG);
2428 ztest_object_unlock(zd, object);
2432 dmu_object_info_from_db(db, &doi);
2433 dmu_buf_rele(db, FTAG);
2436 zgd = umem_zalloc(sizeof (*zgd), UMEM_NOFAIL);
2438 zgd->zgd_private = zd;
2440 if (buf != NULL) { /* immediate write */
2441 zgd->zgd_lr = (struct zfs_locked_range *)ztest_range_lock(zd,
2442 object, offset, size, RL_READER);
2444 error = dmu_read(os, object, offset, size, buf,
2445 DMU_READ_NO_PREFETCH);
2448 size = doi.doi_data_block_size;
2450 offset = P2ALIGN(offset, size);
2452 ASSERT3U(offset, <, size);
2456 zgd->zgd_lr = (struct zfs_locked_range *)ztest_range_lock(zd,
2457 object, offset, size, RL_READER);
2459 error = dmu_buf_hold(os, object, offset, zgd, &db,
2460 DMU_READ_NO_PREFETCH);
2463 blkptr_t *bp = &lr->lr_blkptr;
2468 ASSERT3U(db->db_offset, ==, offset);
2469 ASSERT3U(db->db_size, ==, size);
2471 error = dmu_sync(zio, lr->lr_common.lrc_txg,
2472 ztest_get_done, zgd);
2479 ztest_get_done(zgd, error);
2485 ztest_lr_alloc(size_t lrsize, char *name)
2488 size_t namesize = name ? strlen(name) + 1 : 0;
2490 lr = umem_zalloc(lrsize + namesize, UMEM_NOFAIL);
2493 memcpy(lr + lrsize, name, namesize);
2499 ztest_lr_free(void *lr, size_t lrsize, char *name)
2501 size_t namesize = name ? strlen(name) + 1 : 0;
2503 umem_free(lr, lrsize + namesize);
2507 * Lookup a bunch of objects. Returns the number of objects not found.
2510 ztest_lookup(ztest_ds_t *zd, ztest_od_t *od, int count)
2516 ASSERT(MUTEX_HELD(&zd->zd_dirobj_lock));
2518 for (i = 0; i < count; i++, od++) {
2520 error = zap_lookup(zd->zd_os, od->od_dir, od->od_name,
2521 sizeof (uint64_t), 1, &od->od_object);
2523 ASSERT3S(error, ==, ENOENT);
2524 ASSERT0(od->od_object);
2528 ztest_block_tag_t *bbt;
2529 dmu_object_info_t doi;
2531 ASSERT3U(od->od_object, !=, 0);
2532 ASSERT0(missing); /* there should be no gaps */
2534 ztest_object_lock(zd, od->od_object, RL_READER);
2535 VERIFY0(dmu_bonus_hold(zd->zd_os, od->od_object,
2537 dmu_object_info_from_db(db, &doi);
2538 bbt = ztest_bt_bonus(db);
2539 ASSERT3U(bbt->bt_magic, ==, BT_MAGIC);
2540 od->od_type = doi.doi_type;
2541 od->od_blocksize = doi.doi_data_block_size;
2542 od->od_gen = bbt->bt_gen;
2543 dmu_buf_rele(db, FTAG);
2544 ztest_object_unlock(zd, od->od_object);
2552 ztest_create(ztest_ds_t *zd, ztest_od_t *od, int count)
2557 ASSERT(MUTEX_HELD(&zd->zd_dirobj_lock));
2559 for (i = 0; i < count; i++, od++) {
2566 lr_create_t *lr = ztest_lr_alloc(sizeof (*lr), od->od_name);
2568 lr->lr_doid = od->od_dir;
2569 lr->lr_foid = 0; /* 0 to allocate, > 0 to claim */
2570 lr->lrz_type = od->od_crtype;
2571 lr->lrz_blocksize = od->od_crblocksize;
2572 lr->lrz_ibshift = ztest_random_ibshift();
2573 lr->lrz_bonustype = DMU_OT_UINT64_OTHER;
2574 lr->lrz_dnodesize = od->od_crdnodesize;
2575 lr->lr_gen = od->od_crgen;
2576 lr->lr_crtime[0] = time(NULL);
2578 if (ztest_replay_create(zd, lr, B_FALSE) != 0) {
2583 od->od_object = lr->lr_foid;
2584 od->od_type = od->od_crtype;
2585 od->od_blocksize = od->od_crblocksize;
2586 od->od_gen = od->od_crgen;
2587 ASSERT3U(od->od_object, !=, 0);
2590 ztest_lr_free(lr, sizeof (*lr), od->od_name);
2597 ztest_remove(ztest_ds_t *zd, ztest_od_t *od, int count)
2603 ASSERT(MUTEX_HELD(&zd->zd_dirobj_lock));
2607 for (i = count - 1; i >= 0; i--, od--) {
2614 * No object was found.
2616 if (od->od_object == 0)
2619 lr_remove_t *lr = ztest_lr_alloc(sizeof (*lr), od->od_name);
2621 lr->lr_doid = od->od_dir;
2623 if ((error = ztest_replay_remove(zd, lr, B_FALSE)) != 0) {
2624 ASSERT3U(error, ==, ENOSPC);
2629 ztest_lr_free(lr, sizeof (*lr), od->od_name);
2636 ztest_write(ztest_ds_t *zd, uint64_t object, uint64_t offset, uint64_t size,
2642 lr = ztest_lr_alloc(sizeof (*lr) + size, NULL);
2644 lr->lr_foid = object;
2645 lr->lr_offset = offset;
2646 lr->lr_length = size;
2648 BP_ZERO(&lr->lr_blkptr);
2650 memcpy(lr + 1, data, size);
2652 error = ztest_replay_write(zd, lr, B_FALSE);
2654 ztest_lr_free(lr, sizeof (*lr) + size, NULL);
2660 ztest_truncate(ztest_ds_t *zd, uint64_t object, uint64_t offset, uint64_t size)
2665 lr = ztest_lr_alloc(sizeof (*lr), NULL);
2667 lr->lr_foid = object;
2668 lr->lr_offset = offset;
2669 lr->lr_length = size;
2671 error = ztest_replay_truncate(zd, lr, B_FALSE);
2673 ztest_lr_free(lr, sizeof (*lr), NULL);
2679 ztest_setattr(ztest_ds_t *zd, uint64_t object)
2684 lr = ztest_lr_alloc(sizeof (*lr), NULL);
2686 lr->lr_foid = object;
2690 error = ztest_replay_setattr(zd, lr, B_FALSE);
2692 ztest_lr_free(lr, sizeof (*lr), NULL);
2698 ztest_prealloc(ztest_ds_t *zd, uint64_t object, uint64_t offset, uint64_t size)
2700 objset_t *os = zd->zd_os;
2705 txg_wait_synced(dmu_objset_pool(os), 0);
2707 ztest_object_lock(zd, object, RL_READER);
2708 rl = ztest_range_lock(zd, object, offset, size, RL_WRITER);
2710 tx = dmu_tx_create(os);
2712 dmu_tx_hold_write(tx, object, offset, size);
2714 txg = ztest_tx_assign(tx, TXG_WAIT, FTAG);
2717 dmu_prealloc(os, object, offset, size, tx);
2719 txg_wait_synced(dmu_objset_pool(os), txg);
2721 (void) dmu_free_long_range(os, object, offset, size);
2724 ztest_range_unlock(rl);
2725 ztest_object_unlock(zd, object);
2729 ztest_io(ztest_ds_t *zd, uint64_t object, uint64_t offset)
2732 ztest_block_tag_t wbt;
2733 dmu_object_info_t doi;
2734 enum ztest_io_type io_type;
2738 VERIFY0(dmu_object_info(zd->zd_os, object, &doi));
2739 blocksize = doi.doi_data_block_size;
2740 data = umem_alloc(blocksize, UMEM_NOFAIL);
2743 * Pick an i/o type at random, biased toward writing block tags.
2745 io_type = ztest_random(ZTEST_IO_TYPES);
2746 if (ztest_random(2) == 0)
2747 io_type = ZTEST_IO_WRITE_TAG;
2749 (void) pthread_rwlock_rdlock(&zd->zd_zilog_lock);
2753 case ZTEST_IO_WRITE_TAG:
2754 ztest_bt_generate(&wbt, zd->zd_os, object, doi.doi_dnodesize,
2756 (void) ztest_write(zd, object, offset, sizeof (wbt), &wbt);
2759 case ZTEST_IO_WRITE_PATTERN:
2760 (void) memset(data, 'a' + (object + offset) % 5, blocksize);
2761 if (ztest_random(2) == 0) {
2763 * Induce fletcher2 collisions to ensure that
2764 * zio_ddt_collision() detects and resolves them
2765 * when using fletcher2-verify for deduplication.
2767 ((uint64_t *)data)[0] ^= 1ULL << 63;
2768 ((uint64_t *)data)[4] ^= 1ULL << 63;
2770 (void) ztest_write(zd, object, offset, blocksize, data);
2773 case ZTEST_IO_WRITE_ZEROES:
2774 memset(data, 0, blocksize);
2775 (void) ztest_write(zd, object, offset, blocksize, data);
2778 case ZTEST_IO_TRUNCATE:
2779 (void) ztest_truncate(zd, object, offset, blocksize);
2782 case ZTEST_IO_SETATTR:
2783 (void) ztest_setattr(zd, object);
2788 case ZTEST_IO_REWRITE:
2789 (void) pthread_rwlock_rdlock(&ztest_name_lock);
2790 err = ztest_dsl_prop_set_uint64(zd->zd_name,
2791 ZFS_PROP_CHECKSUM, spa_dedup_checksum(ztest_spa),
2793 ASSERT(err == 0 || err == ENOSPC);
2794 err = ztest_dsl_prop_set_uint64(zd->zd_name,
2795 ZFS_PROP_COMPRESSION,
2796 ztest_random_dsl_prop(ZFS_PROP_COMPRESSION),
2798 ASSERT(err == 0 || err == ENOSPC);
2799 (void) pthread_rwlock_unlock(&ztest_name_lock);
2801 VERIFY0(dmu_read(zd->zd_os, object, offset, blocksize, data,
2802 DMU_READ_NO_PREFETCH));
2804 (void) ztest_write(zd, object, offset, blocksize, data);
2808 (void) pthread_rwlock_unlock(&zd->zd_zilog_lock);
2810 umem_free(data, blocksize);
2814 * Initialize an object description template.
2817 ztest_od_init(ztest_od_t *od, uint64_t id, const char *tag, uint64_t index,
2818 dmu_object_type_t type, uint64_t blocksize, uint64_t dnodesize,
2821 od->od_dir = ZTEST_DIROBJ;
2824 od->od_crtype = type;
2825 od->od_crblocksize = blocksize ? blocksize : ztest_random_blocksize();
2826 od->od_crdnodesize = dnodesize ? dnodesize : ztest_random_dnodesize();
2829 od->od_type = DMU_OT_NONE;
2830 od->od_blocksize = 0;
2833 (void) snprintf(od->od_name, sizeof (od->od_name),
2834 "%s(%"PRId64")[%"PRIu64"]",
2839 * Lookup or create the objects for a test using the od template.
2840 * If the objects do not all exist, or if 'remove' is specified,
2841 * remove any existing objects and create new ones. Otherwise,
2842 * use the existing objects.
2845 ztest_object_init(ztest_ds_t *zd, ztest_od_t *od, size_t size, boolean_t remove)
2847 int count = size / sizeof (*od);
2850 mutex_enter(&zd->zd_dirobj_lock);
2851 if ((ztest_lookup(zd, od, count) != 0 || remove) &&
2852 (ztest_remove(zd, od, count) != 0 ||
2853 ztest_create(zd, od, count) != 0))
2856 mutex_exit(&zd->zd_dirobj_lock);
2862 ztest_zil_commit(ztest_ds_t *zd, uint64_t id)
2865 zilog_t *zilog = zd->zd_zilog;
2867 (void) pthread_rwlock_rdlock(&zd->zd_zilog_lock);
2869 zil_commit(zilog, ztest_random(ZTEST_OBJECTS));
2872 * Remember the committed values in zd, which is in parent/child
2873 * shared memory. If we die, the next iteration of ztest_run()
2874 * will verify that the log really does contain this record.
2876 mutex_enter(&zilog->zl_lock);
2877 ASSERT3P(zd->zd_shared, !=, NULL);
2878 ASSERT3U(zd->zd_shared->zd_seq, <=, zilog->zl_commit_lr_seq);
2879 zd->zd_shared->zd_seq = zilog->zl_commit_lr_seq;
2880 mutex_exit(&zilog->zl_lock);
2882 (void) pthread_rwlock_unlock(&zd->zd_zilog_lock);
2886 * This function is designed to simulate the operations that occur during a
2887 * mount/unmount operation. We hold the dataset across these operations in an
2888 * attempt to expose any implicit assumptions about ZIL management.
2891 ztest_zil_remount(ztest_ds_t *zd, uint64_t id)
2894 objset_t *os = zd->zd_os;
2897 * We hold the ztest_vdev_lock so we don't cause problems with
2898 * other threads that wish to remove a log device, such as
2899 * ztest_device_removal().
2901 mutex_enter(&ztest_vdev_lock);
2904 * We grab the zd_dirobj_lock to ensure that no other thread is
2905 * updating the zil (i.e. adding in-memory log records) and the
2906 * zd_zilog_lock to block any I/O.
2908 mutex_enter(&zd->zd_dirobj_lock);
2909 (void) pthread_rwlock_wrlock(&zd->zd_zilog_lock);
2911 /* zfsvfs_teardown() */
2912 zil_close(zd->zd_zilog);
2914 /* zfsvfs_setup() */
2915 VERIFY3P(zil_open(os, ztest_get_data, NULL), ==, zd->zd_zilog);
2916 zil_replay(os, zd, ztest_replay_vector);
2918 (void) pthread_rwlock_unlock(&zd->zd_zilog_lock);
2919 mutex_exit(&zd->zd_dirobj_lock);
2920 mutex_exit(&ztest_vdev_lock);
2924 * Verify that we can't destroy an active pool, create an existing pool,
2925 * or create a pool with a bad vdev spec.
2928 ztest_spa_create_destroy(ztest_ds_t *zd, uint64_t id)
2930 (void) zd, (void) id;
2931 ztest_shared_opts_t *zo = &ztest_opts;
2935 if (zo->zo_mmp_test)
2939 * Attempt to create using a bad file.
2941 nvroot = make_vdev_root("/dev/bogus", NULL, NULL, 0, 0, NULL, 0, 0, 1);
2942 VERIFY3U(ENOENT, ==,
2943 spa_create("ztest_bad_file", nvroot, NULL, NULL, NULL));
2944 fnvlist_free(nvroot);
2947 * Attempt to create using a bad mirror.
2949 nvroot = make_vdev_root("/dev/bogus", NULL, NULL, 0, 0, NULL, 0, 2, 1);
2950 VERIFY3U(ENOENT, ==,
2951 spa_create("ztest_bad_mirror", nvroot, NULL, NULL, NULL));
2952 fnvlist_free(nvroot);
2955 * Attempt to create an existing pool. It shouldn't matter
2956 * what's in the nvroot; we should fail with EEXIST.
2958 (void) pthread_rwlock_rdlock(&ztest_name_lock);
2959 nvroot = make_vdev_root("/dev/bogus", NULL, NULL, 0, 0, NULL, 0, 0, 1);
2960 VERIFY3U(EEXIST, ==,
2961 spa_create(zo->zo_pool, nvroot, NULL, NULL, NULL));
2962 fnvlist_free(nvroot);
2965 * We open a reference to the spa and then we try to export it
2966 * expecting one of the following errors:
2969 * Because of the reference we just opened.
2971 * ZFS_ERR_EXPORT_IN_PROGRESS
2972 * For the case that there is another ztest thread doing
2973 * an export concurrently.
2975 VERIFY0(spa_open(zo->zo_pool, &spa, FTAG));
2976 int error = spa_destroy(zo->zo_pool);
2977 if (error != EBUSY && error != ZFS_ERR_EXPORT_IN_PROGRESS) {
2978 fatal(B_FALSE, "spa_destroy(%s) returned unexpected value %d",
2979 spa->spa_name, error);
2981 spa_close(spa, FTAG);
2983 (void) pthread_rwlock_unlock(&ztest_name_lock);
2987 * Start and then stop the MMP threads to ensure the startup and shutdown code
2988 * works properly. Actual protection and property-related code tested via ZTS.
2991 ztest_mmp_enable_disable(ztest_ds_t *zd, uint64_t id)
2993 (void) zd, (void) id;
2994 ztest_shared_opts_t *zo = &ztest_opts;
2995 spa_t *spa = ztest_spa;
2997 if (zo->zo_mmp_test)
3001 * Since enabling MMP involves setting a property, it could not be done
3002 * while the pool is suspended.
3004 if (spa_suspended(spa))
3007 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
3008 mutex_enter(&spa->spa_props_lock);
3010 zfs_multihost_fail_intervals = 0;
3012 if (!spa_multihost(spa)) {
3013 spa->spa_multihost = B_TRUE;
3014 mmp_thread_start(spa);
3017 mutex_exit(&spa->spa_props_lock);
3018 spa_config_exit(spa, SCL_CONFIG, FTAG);
3020 txg_wait_synced(spa_get_dsl(spa), 0);
3021 mmp_signal_all_threads();
3022 txg_wait_synced(spa_get_dsl(spa), 0);
3024 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
3025 mutex_enter(&spa->spa_props_lock);
3027 if (spa_multihost(spa)) {
3028 mmp_thread_stop(spa);
3029 spa->spa_multihost = B_FALSE;
3032 mutex_exit(&spa->spa_props_lock);
3033 spa_config_exit(spa, SCL_CONFIG, FTAG);
3037 ztest_spa_upgrade(ztest_ds_t *zd, uint64_t id)
3039 (void) zd, (void) id;
3041 uint64_t initial_version = SPA_VERSION_INITIAL;
3042 uint64_t version, newversion;
3043 nvlist_t *nvroot, *props;
3046 if (ztest_opts.zo_mmp_test)
3049 /* dRAID added after feature flags, skip upgrade test. */
3050 if (strcmp(ztest_opts.zo_raid_type, VDEV_TYPE_DRAID) == 0)
3053 mutex_enter(&ztest_vdev_lock);
3054 name = kmem_asprintf("%s_upgrade", ztest_opts.zo_pool);
3057 * Clean up from previous runs.
3059 (void) spa_destroy(name);
3061 nvroot = make_vdev_root(NULL, NULL, name, ztest_opts.zo_vdev_size, 0,
3062 NULL, ztest_opts.zo_raid_children, ztest_opts.zo_mirrors, 1);
3065 * If we're configuring a RAIDZ device then make sure that the
3066 * initial version is capable of supporting that feature.
3068 switch (ztest_opts.zo_raid_parity) {
3071 initial_version = SPA_VERSION_INITIAL;
3074 initial_version = SPA_VERSION_RAIDZ2;
3077 initial_version = SPA_VERSION_RAIDZ3;
3082 * Create a pool with a spa version that can be upgraded. Pick
3083 * a value between initial_version and SPA_VERSION_BEFORE_FEATURES.
3086 version = ztest_random_spa_version(initial_version);
3087 } while (version > SPA_VERSION_BEFORE_FEATURES);
3089 props = fnvlist_alloc();
3090 fnvlist_add_uint64(props,
3091 zpool_prop_to_name(ZPOOL_PROP_VERSION), version);
3092 VERIFY0(spa_create(name, nvroot, props, NULL, NULL));
3093 fnvlist_free(nvroot);
3094 fnvlist_free(props);
3096 VERIFY0(spa_open(name, &spa, FTAG));
3097 VERIFY3U(spa_version(spa), ==, version);
3098 newversion = ztest_random_spa_version(version + 1);
3100 if (ztest_opts.zo_verbose >= 4) {
3101 (void) printf("upgrading spa version from "
3102 "%"PRIu64" to %"PRIu64"\n",
3103 version, newversion);
3106 spa_upgrade(spa, newversion);
3107 VERIFY3U(spa_version(spa), >, version);
3108 VERIFY3U(spa_version(spa), ==, fnvlist_lookup_uint64(spa->spa_config,
3109 zpool_prop_to_name(ZPOOL_PROP_VERSION)));
3110 spa_close(spa, FTAG);
3113 mutex_exit(&ztest_vdev_lock);
3117 ztest_spa_checkpoint(spa_t *spa)
3119 ASSERT(MUTEX_HELD(&ztest_checkpoint_lock));
3121 int error = spa_checkpoint(spa->spa_name);
3125 case ZFS_ERR_DEVRM_IN_PROGRESS:
3126 case ZFS_ERR_DISCARDING_CHECKPOINT:
3127 case ZFS_ERR_CHECKPOINT_EXISTS:
3130 ztest_record_enospc(FTAG);
3133 fatal(B_FALSE, "spa_checkpoint(%s) = %d", spa->spa_name, error);
3138 ztest_spa_discard_checkpoint(spa_t *spa)
3140 ASSERT(MUTEX_HELD(&ztest_checkpoint_lock));
3142 int error = spa_checkpoint_discard(spa->spa_name);
3146 case ZFS_ERR_DISCARDING_CHECKPOINT:
3147 case ZFS_ERR_NO_CHECKPOINT:
3150 fatal(B_FALSE, "spa_discard_checkpoint(%s) = %d",
3151 spa->spa_name, error);
3157 ztest_spa_checkpoint_create_discard(ztest_ds_t *zd, uint64_t id)
3159 (void) zd, (void) id;
3160 spa_t *spa = ztest_spa;
3162 mutex_enter(&ztest_checkpoint_lock);
3163 if (ztest_random(2) == 0) {
3164 ztest_spa_checkpoint(spa);
3166 ztest_spa_discard_checkpoint(spa);
3168 mutex_exit(&ztest_checkpoint_lock);
3173 vdev_lookup_by_path(vdev_t *vd, const char *path)
3178 if (vd->vdev_path != NULL && strcmp(path, vd->vdev_path) == 0)
3181 for (c = 0; c < vd->vdev_children; c++)
3182 if ((mvd = vdev_lookup_by_path(vd->vdev_child[c], path)) !=
3190 spa_num_top_vdevs(spa_t *spa)
3192 vdev_t *rvd = spa->spa_root_vdev;
3193 ASSERT3U(spa_config_held(spa, SCL_VDEV, RW_READER), ==, SCL_VDEV);
3194 return (rvd->vdev_children);
3198 * Verify that vdev_add() works as expected.
3201 ztest_vdev_add_remove(ztest_ds_t *zd, uint64_t id)
3203 (void) zd, (void) id;
3204 ztest_shared_t *zs = ztest_shared;
3205 spa_t *spa = ztest_spa;
3211 if (ztest_opts.zo_mmp_test)
3214 mutex_enter(&ztest_vdev_lock);
3215 leaves = MAX(zs->zs_mirrors + zs->zs_splits, 1) *
3216 ztest_opts.zo_raid_children;
3218 spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
3220 ztest_shared->zs_vdev_next_leaf = spa_num_top_vdevs(spa) * leaves;
3223 * If we have slogs then remove them 1/4 of the time.
3225 if (spa_has_slogs(spa) && ztest_random(4) == 0) {
3226 metaslab_group_t *mg;
3229 * find the first real slog in log allocation class
3231 mg = spa_log_class(spa)->mc_allocator[0].mca_rotor;
3232 while (!mg->mg_vd->vdev_islog)
3235 guid = mg->mg_vd->vdev_guid;
3237 spa_config_exit(spa, SCL_VDEV, FTAG);
3240 * We have to grab the zs_name_lock as writer to
3241 * prevent a race between removing a slog (dmu_objset_find)
3242 * and destroying a dataset. Removing the slog will
3243 * grab a reference on the dataset which may cause
3244 * dsl_destroy_head() to fail with EBUSY thus
3245 * leaving the dataset in an inconsistent state.
3247 pthread_rwlock_wrlock(&ztest_name_lock);
3248 error = spa_vdev_remove(spa, guid, B_FALSE);
3249 pthread_rwlock_unlock(&ztest_name_lock);
3253 case EEXIST: /* Generic zil_reset() error */
3254 case EBUSY: /* Replay required */
3255 case EACCES: /* Crypto key not loaded */
3256 case ZFS_ERR_CHECKPOINT_EXISTS:
3257 case ZFS_ERR_DISCARDING_CHECKPOINT:
3260 fatal(B_FALSE, "spa_vdev_remove() = %d", error);
3263 spa_config_exit(spa, SCL_VDEV, FTAG);
3266 * Make 1/4 of the devices be log devices
3268 nvroot = make_vdev_root(NULL, NULL, NULL,
3269 ztest_opts.zo_vdev_size, 0, (ztest_random(4) == 0) ?
3270 "log" : NULL, ztest_opts.zo_raid_children, zs->zs_mirrors,
3273 error = spa_vdev_add(spa, nvroot);
3274 fnvlist_free(nvroot);
3280 ztest_record_enospc("spa_vdev_add");
3283 fatal(B_FALSE, "spa_vdev_add() = %d", error);
3287 mutex_exit(&ztest_vdev_lock);
3291 ztest_vdev_class_add(ztest_ds_t *zd, uint64_t id)
3293 (void) zd, (void) id;
3294 ztest_shared_t *zs = ztest_shared;
3295 spa_t *spa = ztest_spa;
3298 const char *class = (ztest_random(2) == 0) ?
3299 VDEV_ALLOC_BIAS_SPECIAL : VDEV_ALLOC_BIAS_DEDUP;
3303 * By default add a special vdev 50% of the time
3305 if ((ztest_opts.zo_special_vdevs == ZTEST_VDEV_CLASS_OFF) ||
3306 (ztest_opts.zo_special_vdevs == ZTEST_VDEV_CLASS_RND &&
3307 ztest_random(2) == 0)) {
3311 mutex_enter(&ztest_vdev_lock);
3313 /* Only test with mirrors */
3314 if (zs->zs_mirrors < 2) {
3315 mutex_exit(&ztest_vdev_lock);
3319 /* requires feature@allocation_classes */
3320 if (!spa_feature_is_enabled(spa, SPA_FEATURE_ALLOCATION_CLASSES)) {
3321 mutex_exit(&ztest_vdev_lock);
3325 leaves = MAX(zs->zs_mirrors + zs->zs_splits, 1) *
3326 ztest_opts.zo_raid_children;
3328 spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
3329 ztest_shared->zs_vdev_next_leaf = spa_num_top_vdevs(spa) * leaves;
3330 spa_config_exit(spa, SCL_VDEV, FTAG);
3332 nvroot = make_vdev_root(NULL, NULL, NULL, ztest_opts.zo_vdev_size, 0,
3333 class, ztest_opts.zo_raid_children, zs->zs_mirrors, 1);
3335 error = spa_vdev_add(spa, nvroot);
3336 fnvlist_free(nvroot);
3338 if (error == ENOSPC)
3339 ztest_record_enospc("spa_vdev_add");
3340 else if (error != 0)
3341 fatal(B_FALSE, "spa_vdev_add() = %d", error);
3344 * 50% of the time allow small blocks in the special class
3347 spa_special_class(spa)->mc_groups == 1 && ztest_random(2) == 0) {
3348 if (ztest_opts.zo_verbose >= 3)
3349 (void) printf("Enabling special VDEV small blocks\n");
3350 error = ztest_dsl_prop_set_uint64(zd->zd_name,
3351 ZFS_PROP_SPECIAL_SMALL_BLOCKS, 32768, B_FALSE);
3352 ASSERT(error == 0 || error == ENOSPC);
3355 mutex_exit(&ztest_vdev_lock);
3357 if (ztest_opts.zo_verbose >= 3) {
3358 metaslab_class_t *mc;
3360 if (strcmp(class, VDEV_ALLOC_BIAS_SPECIAL) == 0)
3361 mc = spa_special_class(spa);
3363 mc = spa_dedup_class(spa);
3364 (void) printf("Added a %s mirrored vdev (of %d)\n",
3365 class, (int)mc->mc_groups);
3370 * Verify that adding/removing aux devices (l2arc, hot spare) works as expected.
3373 ztest_vdev_aux_add_remove(ztest_ds_t *zd, uint64_t id)
3375 (void) zd, (void) id;
3376 ztest_shared_t *zs = ztest_shared;
3377 spa_t *spa = ztest_spa;
3378 vdev_t *rvd = spa->spa_root_vdev;
3379 spa_aux_vdev_t *sav;
3383 int error, ignore_err = 0;
3385 if (ztest_opts.zo_mmp_test)
3388 path = umem_alloc(MAXPATHLEN, UMEM_NOFAIL);
3390 if (ztest_random(2) == 0) {
3391 sav = &spa->spa_spares;
3392 aux = ZPOOL_CONFIG_SPARES;
3394 sav = &spa->spa_l2cache;
3395 aux = ZPOOL_CONFIG_L2CACHE;
3398 mutex_enter(&ztest_vdev_lock);
3400 spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
3402 if (sav->sav_count != 0 && ztest_random(4) == 0) {
3404 * Pick a random device to remove.
3406 vdev_t *svd = sav->sav_vdevs[ztest_random(sav->sav_count)];
3408 /* dRAID spares cannot be removed; try anyways to see ENOTSUP */
3409 if (strstr(svd->vdev_path, VDEV_TYPE_DRAID) != NULL)
3410 ignore_err = ENOTSUP;
3412 guid = svd->vdev_guid;
3415 * Find an unused device we can add.
3417 zs->zs_vdev_aux = 0;
3420 (void) snprintf(path, MAXPATHLEN, ztest_aux_template,
3421 ztest_opts.zo_dir, ztest_opts.zo_pool, aux,
3423 for (c = 0; c < sav->sav_count; c++)
3424 if (strcmp(sav->sav_vdevs[c]->vdev_path,
3427 if (c == sav->sav_count &&
3428 vdev_lookup_by_path(rvd, path) == NULL)
3434 spa_config_exit(spa, SCL_VDEV, FTAG);
3440 nvlist_t *nvroot = make_vdev_root(NULL, aux, NULL,
3441 (ztest_opts.zo_vdev_size * 5) / 4, 0, NULL, 0, 0, 1);
3442 error = spa_vdev_add(spa, nvroot);
3448 fatal(B_FALSE, "spa_vdev_add(%p) = %d", nvroot, error);
3450 fnvlist_free(nvroot);
3453 * Remove an existing device. Sometimes, dirty its
3454 * vdev state first to make sure we handle removal
3455 * of devices that have pending state changes.
3457 if (ztest_random(2) == 0)
3458 (void) vdev_online(spa, guid, 0, NULL);
3460 error = spa_vdev_remove(spa, guid, B_FALSE);
3465 case ZFS_ERR_CHECKPOINT_EXISTS:
3466 case ZFS_ERR_DISCARDING_CHECKPOINT:
3469 if (error != ignore_err)
3471 "spa_vdev_remove(%"PRIu64") = %d",
3476 mutex_exit(&ztest_vdev_lock);
3478 umem_free(path, MAXPATHLEN);
3482 * split a pool if it has mirror tlvdevs
3485 ztest_split_pool(ztest_ds_t *zd, uint64_t id)
3487 (void) zd, (void) id;
3488 ztest_shared_t *zs = ztest_shared;
3489 spa_t *spa = ztest_spa;
3490 vdev_t *rvd = spa->spa_root_vdev;
3491 nvlist_t *tree, **child, *config, *split, **schild;
3492 uint_t c, children, schildren = 0, lastlogid = 0;
3495 if (ztest_opts.zo_mmp_test)
3498 mutex_enter(&ztest_vdev_lock);
3500 /* ensure we have a usable config; mirrors of raidz aren't supported */
3501 if (zs->zs_mirrors < 3 || ztest_opts.zo_raid_children > 1) {
3502 mutex_exit(&ztest_vdev_lock);
3506 /* clean up the old pool, if any */
3507 (void) spa_destroy("splitp");
3509 spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
3511 /* generate a config from the existing config */
3512 mutex_enter(&spa->spa_props_lock);
3513 tree = fnvlist_lookup_nvlist(spa->spa_config, ZPOOL_CONFIG_VDEV_TREE);
3514 mutex_exit(&spa->spa_props_lock);
3516 VERIFY0(nvlist_lookup_nvlist_array(tree, ZPOOL_CONFIG_CHILDREN,
3517 &child, &children));
3519 schild = umem_alloc(rvd->vdev_children * sizeof (nvlist_t *),
3521 for (c = 0; c < children; c++) {
3522 vdev_t *tvd = rvd->vdev_child[c];
3526 if (tvd->vdev_islog || tvd->vdev_ops == &vdev_hole_ops) {
3527 schild[schildren] = fnvlist_alloc();
3528 fnvlist_add_string(schild[schildren],
3529 ZPOOL_CONFIG_TYPE, VDEV_TYPE_HOLE);
3530 fnvlist_add_uint64(schild[schildren],
3531 ZPOOL_CONFIG_IS_HOLE, 1);
3533 lastlogid = schildren;
3538 VERIFY0(nvlist_lookup_nvlist_array(child[c],
3539 ZPOOL_CONFIG_CHILDREN, &mchild, &mchildren));
3540 schild[schildren++] = fnvlist_dup(mchild[0]);
3543 /* OK, create a config that can be used to split */
3544 split = fnvlist_alloc();
3545 fnvlist_add_string(split, ZPOOL_CONFIG_TYPE, VDEV_TYPE_ROOT);
3546 fnvlist_add_nvlist_array(split, ZPOOL_CONFIG_CHILDREN,
3547 (const nvlist_t **)schild, lastlogid != 0 ? lastlogid : schildren);
3549 config = fnvlist_alloc();
3550 fnvlist_add_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, split);
3552 for (c = 0; c < schildren; c++)
3553 fnvlist_free(schild[c]);
3554 umem_free(schild, rvd->vdev_children * sizeof (nvlist_t *));
3555 fnvlist_free(split);
3557 spa_config_exit(spa, SCL_VDEV, FTAG);
3559 (void) pthread_rwlock_wrlock(&ztest_name_lock);
3560 error = spa_vdev_split_mirror(spa, "splitp", config, NULL, B_FALSE);
3561 (void) pthread_rwlock_unlock(&ztest_name_lock);
3563 fnvlist_free(config);
3566 (void) printf("successful split - results:\n");
3567 mutex_enter(&spa_namespace_lock);
3568 show_pool_stats(spa);
3569 show_pool_stats(spa_lookup("splitp"));
3570 mutex_exit(&spa_namespace_lock);
3574 mutex_exit(&ztest_vdev_lock);
3578 * Verify that we can attach and detach devices.
3581 ztest_vdev_attach_detach(ztest_ds_t *zd, uint64_t id)
3583 (void) zd, (void) id;
3584 ztest_shared_t *zs = ztest_shared;
3585 spa_t *spa = ztest_spa;
3586 spa_aux_vdev_t *sav = &spa->spa_spares;
3587 vdev_t *rvd = spa->spa_root_vdev;
3588 vdev_t *oldvd, *newvd, *pvd;
3592 uint64_t ashift = ztest_get_ashift();
3593 uint64_t oldguid, pguid;
3594 uint64_t oldsize, newsize;
3595 char *oldpath, *newpath;
3597 int oldvd_has_siblings = B_FALSE;
3598 int newvd_is_spare = B_FALSE;
3599 int newvd_is_dspare = B_FALSE;
3601 int oldvd_is_special;
3602 int error, expected_error;
3604 if (ztest_opts.zo_mmp_test)
3607 oldpath = umem_alloc(MAXPATHLEN, UMEM_NOFAIL);
3608 newpath = umem_alloc(MAXPATHLEN, UMEM_NOFAIL);
3610 mutex_enter(&ztest_vdev_lock);
3611 leaves = MAX(zs->zs_mirrors, 1) * ztest_opts.zo_raid_children;
3613 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3616 * If a vdev is in the process of being removed, its removal may
3617 * finish while we are in progress, leading to an unexpected error
3618 * value. Don't bother trying to attach while we are in the middle
3621 if (ztest_device_removal_active) {
3622 spa_config_exit(spa, SCL_ALL, FTAG);
3627 * Decide whether to do an attach or a replace.
3629 replacing = ztest_random(2);
3632 * Pick a random top-level vdev.
3634 top = ztest_random_vdev_top(spa, B_TRUE);
3637 * Pick a random leaf within it.
3639 leaf = ztest_random(leaves);
3644 oldvd = rvd->vdev_child[top];
3646 /* pick a child from the mirror */
3647 if (zs->zs_mirrors >= 1) {
3648 ASSERT3P(oldvd->vdev_ops, ==, &vdev_mirror_ops);
3649 ASSERT3U(oldvd->vdev_children, >=, zs->zs_mirrors);
3650 oldvd = oldvd->vdev_child[leaf / ztest_opts.zo_raid_children];
3653 /* pick a child out of the raidz group */
3654 if (ztest_opts.zo_raid_children > 1) {
3655 if (strcmp(oldvd->vdev_ops->vdev_op_type, "raidz") == 0)
3656 ASSERT3P(oldvd->vdev_ops, ==, &vdev_raidz_ops);
3658 ASSERT3P(oldvd->vdev_ops, ==, &vdev_draid_ops);
3659 ASSERT3U(oldvd->vdev_children, ==, ztest_opts.zo_raid_children);
3660 oldvd = oldvd->vdev_child[leaf % ztest_opts.zo_raid_children];
3664 * If we're already doing an attach or replace, oldvd may be a
3665 * mirror vdev -- in which case, pick a random child.
3667 while (oldvd->vdev_children != 0) {
3668 oldvd_has_siblings = B_TRUE;
3669 ASSERT3U(oldvd->vdev_children, >=, 2);
3670 oldvd = oldvd->vdev_child[ztest_random(oldvd->vdev_children)];
3673 oldguid = oldvd->vdev_guid;
3674 oldsize = vdev_get_min_asize(oldvd);
3675 oldvd_is_log = oldvd->vdev_top->vdev_islog;
3677 oldvd->vdev_top->vdev_alloc_bias == VDEV_BIAS_SPECIAL ||
3678 oldvd->vdev_top->vdev_alloc_bias == VDEV_BIAS_DEDUP;
3679 (void) strlcpy(oldpath, oldvd->vdev_path, MAXPATHLEN);
3680 pvd = oldvd->vdev_parent;
3681 pguid = pvd->vdev_guid;
3684 * If oldvd has siblings, then half of the time, detach it. Prior
3685 * to the detach the pool is scrubbed in order to prevent creating
3686 * unrepairable blocks as a result of the data corruption injection.
3688 if (oldvd_has_siblings && ztest_random(2) == 0) {
3689 spa_config_exit(spa, SCL_ALL, FTAG);
3691 error = ztest_scrub_impl(spa);
3695 error = spa_vdev_detach(spa, oldguid, pguid, B_FALSE);
3696 if (error != 0 && error != ENODEV && error != EBUSY &&
3697 error != ENOTSUP && error != ZFS_ERR_CHECKPOINT_EXISTS &&
3698 error != ZFS_ERR_DISCARDING_CHECKPOINT)
3699 fatal(B_FALSE, "detach (%s) returned %d",
3705 * For the new vdev, choose with equal probability between the two
3706 * standard paths (ending in either 'a' or 'b') or a random hot spare.
3708 if (sav->sav_count != 0 && ztest_random(3) == 0) {
3709 newvd = sav->sav_vdevs[ztest_random(sav->sav_count)];
3710 newvd_is_spare = B_TRUE;
3712 if (newvd->vdev_ops == &vdev_draid_spare_ops)
3713 newvd_is_dspare = B_TRUE;
3715 (void) strlcpy(newpath, newvd->vdev_path, MAXPATHLEN);
3717 (void) snprintf(newpath, MAXPATHLEN, ztest_dev_template,
3718 ztest_opts.zo_dir, ztest_opts.zo_pool,
3719 top * leaves + leaf);
3720 if (ztest_random(2) == 0)
3721 newpath[strlen(newpath) - 1] = 'b';
3722 newvd = vdev_lookup_by_path(rvd, newpath);
3727 * Reopen to ensure the vdev's asize field isn't stale.
3730 newsize = vdev_get_min_asize(newvd);
3733 * Make newsize a little bigger or smaller than oldsize.
3734 * If it's smaller, the attach should fail.
3735 * If it's larger, and we're doing a replace,
3736 * we should get dynamic LUN growth when we're done.
3738 newsize = 10 * oldsize / (9 + ztest_random(3));
3742 * If pvd is not a mirror or root, the attach should fail with ENOTSUP,
3743 * unless it's a replace; in that case any non-replacing parent is OK.
3745 * If newvd is already part of the pool, it should fail with EBUSY.
3747 * If newvd is too small, it should fail with EOVERFLOW.
3749 * If newvd is a distributed spare and it's being attached to a
3750 * dRAID which is not its parent it should fail with EINVAL.
3752 if (pvd->vdev_ops != &vdev_mirror_ops &&
3753 pvd->vdev_ops != &vdev_root_ops && (!replacing ||
3754 pvd->vdev_ops == &vdev_replacing_ops ||
3755 pvd->vdev_ops == &vdev_spare_ops))
3756 expected_error = ENOTSUP;
3757 else if (newvd_is_spare &&
3758 (!replacing || oldvd_is_log || oldvd_is_special))
3759 expected_error = ENOTSUP;
3760 else if (newvd == oldvd)
3761 expected_error = replacing ? 0 : EBUSY;
3762 else if (vdev_lookup_by_path(rvd, newpath) != NULL)
3763 expected_error = EBUSY;
3764 else if (!newvd_is_dspare && newsize < oldsize)
3765 expected_error = EOVERFLOW;
3766 else if (ashift > oldvd->vdev_top->vdev_ashift)
3767 expected_error = EDOM;
3768 else if (newvd_is_dspare && pvd != vdev_draid_spare_get_parent(newvd))
3769 expected_error = ENOTSUP;
3773 spa_config_exit(spa, SCL_ALL, FTAG);
3776 * Build the nvlist describing newpath.
3778 root = make_vdev_root(newpath, NULL, NULL, newvd == NULL ? newsize : 0,
3779 ashift, NULL, 0, 0, 1);
3782 * When supported select either a healing or sequential resilver.
3784 boolean_t rebuilding = B_FALSE;
3785 if (pvd->vdev_ops == &vdev_mirror_ops ||
3786 pvd->vdev_ops == &vdev_root_ops) {
3787 rebuilding = !!ztest_random(2);
3790 error = spa_vdev_attach(spa, oldguid, root, replacing, rebuilding);
3795 * If our parent was the replacing vdev, but the replace completed,
3796 * then instead of failing with ENOTSUP we may either succeed,
3797 * fail with ENODEV, or fail with EOVERFLOW.
3799 if (expected_error == ENOTSUP &&
3800 (error == 0 || error == ENODEV || error == EOVERFLOW))
3801 expected_error = error;
3804 * If someone grew the LUN, the replacement may be too small.
3806 if (error == EOVERFLOW || error == EBUSY)
3807 expected_error = error;
3809 if (error == ZFS_ERR_CHECKPOINT_EXISTS ||
3810 error == ZFS_ERR_DISCARDING_CHECKPOINT ||
3811 error == ZFS_ERR_RESILVER_IN_PROGRESS ||
3812 error == ZFS_ERR_REBUILD_IN_PROGRESS)
3813 expected_error = error;
3815 if (error != expected_error && expected_error != EBUSY) {
3816 fatal(B_FALSE, "attach (%s %"PRIu64", %s %"PRIu64", %d) "
3817 "returned %d, expected %d",
3818 oldpath, oldsize, newpath,
3819 newsize, replacing, error, expected_error);
3822 mutex_exit(&ztest_vdev_lock);
3824 umem_free(oldpath, MAXPATHLEN);
3825 umem_free(newpath, MAXPATHLEN);
3829 ztest_device_removal(ztest_ds_t *zd, uint64_t id)
3831 (void) zd, (void) id;
3832 spa_t *spa = ztest_spa;
3837 mutex_enter(&ztest_vdev_lock);
3839 if (ztest_device_removal_active) {
3840 mutex_exit(&ztest_vdev_lock);
3845 * Remove a random top-level vdev and wait for removal to finish.
3847 spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
3848 vd = vdev_lookup_top(spa, ztest_random_vdev_top(spa, B_FALSE));
3849 guid = vd->vdev_guid;
3850 spa_config_exit(spa, SCL_VDEV, FTAG);
3852 error = spa_vdev_remove(spa, guid, B_FALSE);
3854 ztest_device_removal_active = B_TRUE;
3855 mutex_exit(&ztest_vdev_lock);
3858 * spa->spa_vdev_removal is created in a sync task that
3859 * is initiated via dsl_sync_task_nowait(). Since the
3860 * task may not run before spa_vdev_remove() returns, we
3861 * must wait at least 1 txg to ensure that the removal
3862 * struct has been created.
3864 txg_wait_synced(spa_get_dsl(spa), 0);
3866 while (spa->spa_removing_phys.sr_state == DSS_SCANNING)
3867 txg_wait_synced(spa_get_dsl(spa), 0);
3869 mutex_exit(&ztest_vdev_lock);
3874 * The pool needs to be scrubbed after completing device removal.
3875 * Failure to do so may result in checksum errors due to the
3876 * strategy employed by ztest_fault_inject() when selecting which
3877 * offset are redundant and can be damaged.
3879 error = spa_scan(spa, POOL_SCAN_SCRUB);
3881 while (dsl_scan_scrubbing(spa_get_dsl(spa)))
3882 txg_wait_synced(spa_get_dsl(spa), 0);
3885 mutex_enter(&ztest_vdev_lock);
3886 ztest_device_removal_active = B_FALSE;
3887 mutex_exit(&ztest_vdev_lock);
3891 * Callback function which expands the physical size of the vdev.
3894 grow_vdev(vdev_t *vd, void *arg)
3896 spa_t *spa __maybe_unused = vd->vdev_spa;
3897 size_t *newsize = arg;
3901 ASSERT3S(spa_config_held(spa, SCL_STATE, RW_READER), ==, SCL_STATE);
3902 ASSERT(vd->vdev_ops->vdev_op_leaf);
3904 if ((fd = open(vd->vdev_path, O_RDWR)) == -1)
3907 fsize = lseek(fd, 0, SEEK_END);
3908 VERIFY0(ftruncate(fd, *newsize));
3910 if (ztest_opts.zo_verbose >= 6) {
3911 (void) printf("%s grew from %lu to %lu bytes\n",
3912 vd->vdev_path, (ulong_t)fsize, (ulong_t)*newsize);
3919 * Callback function which expands a given vdev by calling vdev_online().
3922 online_vdev(vdev_t *vd, void *arg)
3925 spa_t *spa = vd->vdev_spa;
3926 vdev_t *tvd = vd->vdev_top;
3927 uint64_t guid = vd->vdev_guid;
3928 uint64_t generation = spa->spa_config_generation + 1;
3929 vdev_state_t newstate = VDEV_STATE_UNKNOWN;
3932 ASSERT3S(spa_config_held(spa, SCL_STATE, RW_READER), ==, SCL_STATE);
3933 ASSERT(vd->vdev_ops->vdev_op_leaf);
3935 /* Calling vdev_online will initialize the new metaslabs */
3936 spa_config_exit(spa, SCL_STATE, spa);
3937 error = vdev_online(spa, guid, ZFS_ONLINE_EXPAND, &newstate);
3938 spa_config_enter(spa, SCL_STATE, spa, RW_READER);
3941 * If vdev_online returned an error or the underlying vdev_open
3942 * failed then we abort the expand. The only way to know that
3943 * vdev_open fails is by checking the returned newstate.
3945 if (error || newstate != VDEV_STATE_HEALTHY) {
3946 if (ztest_opts.zo_verbose >= 5) {
3947 (void) printf("Unable to expand vdev, state %u, "
3948 "error %d\n", newstate, error);
3952 ASSERT3U(newstate, ==, VDEV_STATE_HEALTHY);
3955 * Since we dropped the lock we need to ensure that we're
3956 * still talking to the original vdev. It's possible this
3957 * vdev may have been detached/replaced while we were
3958 * trying to online it.
3960 if (generation != spa->spa_config_generation) {
3961 if (ztest_opts.zo_verbose >= 5) {
3962 (void) printf("vdev configuration has changed, "
3963 "guid %"PRIu64", state %"PRIu64", "
3964 "expected gen %"PRIu64", got gen %"PRIu64"\n",
3968 spa->spa_config_generation);
3976 * Traverse the vdev tree calling the supplied function.
3977 * We continue to walk the tree until we either have walked all
3978 * children or we receive a non-NULL return from the callback.
3979 * If a NULL callback is passed, then we just return back the first
3980 * leaf vdev we encounter.
3983 vdev_walk_tree(vdev_t *vd, vdev_t *(*func)(vdev_t *, void *), void *arg)
3987 if (vd->vdev_ops->vdev_op_leaf) {
3991 return (func(vd, arg));
3994 for (c = 0; c < vd->vdev_children; c++) {
3995 vdev_t *cvd = vd->vdev_child[c];
3996 if ((cvd = vdev_walk_tree(cvd, func, arg)) != NULL)
4003 * Verify that dynamic LUN growth works as expected.
4006 ztest_vdev_LUN_growth(ztest_ds_t *zd, uint64_t id)
4008 (void) zd, (void) id;
4009 spa_t *spa = ztest_spa;
4011 metaslab_class_t *mc;
4012 metaslab_group_t *mg;
4013 size_t psize, newsize;
4015 uint64_t old_class_space, new_class_space, old_ms_count, new_ms_count;
4017 mutex_enter(&ztest_checkpoint_lock);
4018 mutex_enter(&ztest_vdev_lock);
4019 spa_config_enter(spa, SCL_STATE, spa, RW_READER);
4022 * If there is a vdev removal in progress, it could complete while
4023 * we are running, in which case we would not be able to verify
4024 * that the metaslab_class space increased (because it decreases
4025 * when the device removal completes).
4027 if (ztest_device_removal_active) {
4028 spa_config_exit(spa, SCL_STATE, spa);
4029 mutex_exit(&ztest_vdev_lock);
4030 mutex_exit(&ztest_checkpoint_lock);
4034 top = ztest_random_vdev_top(spa, B_TRUE);
4036 tvd = spa->spa_root_vdev->vdev_child[top];
4039 old_ms_count = tvd->vdev_ms_count;
4040 old_class_space = metaslab_class_get_space(mc);
4043 * Determine the size of the first leaf vdev associated with
4044 * our top-level device.
4046 vd = vdev_walk_tree(tvd, NULL, NULL);
4047 ASSERT3P(vd, !=, NULL);
4048 ASSERT(vd->vdev_ops->vdev_op_leaf);
4050 psize = vd->vdev_psize;
4053 * We only try to expand the vdev if it's healthy, less than 4x its
4054 * original size, and it has a valid psize.
4056 if (tvd->vdev_state != VDEV_STATE_HEALTHY ||
4057 psize == 0 || psize >= 4 * ztest_opts.zo_vdev_size) {
4058 spa_config_exit(spa, SCL_STATE, spa);
4059 mutex_exit(&ztest_vdev_lock);
4060 mutex_exit(&ztest_checkpoint_lock);
4063 ASSERT3U(psize, >, 0);
4064 newsize = psize + MAX(psize / 8, SPA_MAXBLOCKSIZE);
4065 ASSERT3U(newsize, >, psize);
4067 if (ztest_opts.zo_verbose >= 6) {
4068 (void) printf("Expanding LUN %s from %lu to %lu\n",
4069 vd->vdev_path, (ulong_t)psize, (ulong_t)newsize);
4073 * Growing the vdev is a two step process:
4074 * 1). expand the physical size (i.e. relabel)
4075 * 2). online the vdev to create the new metaslabs
4077 if (vdev_walk_tree(tvd, grow_vdev, &newsize) != NULL ||
4078 vdev_walk_tree(tvd, online_vdev, NULL) != NULL ||
4079 tvd->vdev_state != VDEV_STATE_HEALTHY) {
4080 if (ztest_opts.zo_verbose >= 5) {
4081 (void) printf("Could not expand LUN because "
4082 "the vdev configuration changed.\n");
4084 spa_config_exit(spa, SCL_STATE, spa);
4085 mutex_exit(&ztest_vdev_lock);
4086 mutex_exit(&ztest_checkpoint_lock);
4090 spa_config_exit(spa, SCL_STATE, spa);
4093 * Expanding the LUN will update the config asynchronously,
4094 * thus we must wait for the async thread to complete any
4095 * pending tasks before proceeding.
4099 mutex_enter(&spa->spa_async_lock);
4100 done = (spa->spa_async_thread == NULL && !spa->spa_async_tasks);
4101 mutex_exit(&spa->spa_async_lock);
4104 txg_wait_synced(spa_get_dsl(spa), 0);
4105 (void) poll(NULL, 0, 100);
4108 spa_config_enter(spa, SCL_STATE, spa, RW_READER);
4110 tvd = spa->spa_root_vdev->vdev_child[top];
4111 new_ms_count = tvd->vdev_ms_count;
4112 new_class_space = metaslab_class_get_space(mc);
4114 if (tvd->vdev_mg != mg || mg->mg_class != mc) {
4115 if (ztest_opts.zo_verbose >= 5) {
4116 (void) printf("Could not verify LUN expansion due to "
4117 "intervening vdev offline or remove.\n");
4119 spa_config_exit(spa, SCL_STATE, spa);
4120 mutex_exit(&ztest_vdev_lock);
4121 mutex_exit(&ztest_checkpoint_lock);
4126 * Make sure we were able to grow the vdev.
4128 if (new_ms_count <= old_ms_count) {
4130 "LUN expansion failed: ms_count %"PRIu64" < %"PRIu64"\n",
4131 old_ms_count, new_ms_count);
4135 * Make sure we were able to grow the pool.
4137 if (new_class_space <= old_class_space) {
4139 "LUN expansion failed: class_space %"PRIu64" < %"PRIu64"\n",
4140 old_class_space, new_class_space);
4143 if (ztest_opts.zo_verbose >= 5) {
4144 char oldnumbuf[NN_NUMBUF_SZ], newnumbuf[NN_NUMBUF_SZ];
4146 nicenum(old_class_space, oldnumbuf, sizeof (oldnumbuf));
4147 nicenum(new_class_space, newnumbuf, sizeof (newnumbuf));
4148 (void) printf("%s grew from %s to %s\n",
4149 spa->spa_name, oldnumbuf, newnumbuf);
4152 spa_config_exit(spa, SCL_STATE, spa);
4153 mutex_exit(&ztest_vdev_lock);
4154 mutex_exit(&ztest_checkpoint_lock);
4158 * Verify that dmu_objset_{create,destroy,open,close} work as expected.
4161 ztest_objset_create_cb(objset_t *os, void *arg, cred_t *cr, dmu_tx_t *tx)
4163 (void) arg, (void) cr;
4166 * Create the objects common to all ztest datasets.
4168 VERIFY0(zap_create_claim(os, ZTEST_DIROBJ,
4169 DMU_OT_ZAP_OTHER, DMU_OT_NONE, 0, tx));
4173 ztest_dataset_create(char *dsname)
4177 dsl_crypto_params_t *dcp = NULL;
4180 * 50% of the time, we create encrypted datasets
4181 * using a random cipher suite and a hard-coded
4184 rand = ztest_random(2);
4186 nvlist_t *crypto_args = fnvlist_alloc();
4187 nvlist_t *props = fnvlist_alloc();
4189 /* slight bias towards the default cipher suite */
4190 rand = ztest_random(ZIO_CRYPT_FUNCTIONS);
4191 if (rand < ZIO_CRYPT_AES_128_CCM)
4192 rand = ZIO_CRYPT_ON;
4194 fnvlist_add_uint64(props,
4195 zfs_prop_to_name(ZFS_PROP_ENCRYPTION), rand);
4196 fnvlist_add_uint8_array(crypto_args, "wkeydata",
4197 (uint8_t *)ztest_wkeydata, WRAPPING_KEY_LEN);
4200 * These parameters aren't really used by the kernel. They
4201 * are simply stored so that userspace knows how to load
4204 fnvlist_add_uint64(props,
4205 zfs_prop_to_name(ZFS_PROP_KEYFORMAT), ZFS_KEYFORMAT_RAW);
4206 fnvlist_add_string(props,
4207 zfs_prop_to_name(ZFS_PROP_KEYLOCATION), "prompt");
4208 fnvlist_add_uint64(props,
4209 zfs_prop_to_name(ZFS_PROP_PBKDF2_SALT), 0ULL);
4210 fnvlist_add_uint64(props,
4211 zfs_prop_to_name(ZFS_PROP_PBKDF2_ITERS), 0ULL);
4213 VERIFY0(dsl_crypto_params_create_nvlist(DCP_CMD_NONE, props,
4214 crypto_args, &dcp));
4217 * Cycle through all available encryption implementations
4218 * to verify interoperability.
4220 VERIFY0(gcm_impl_set("cycle"));
4221 VERIFY0(aes_impl_set("cycle"));
4223 fnvlist_free(crypto_args);
4224 fnvlist_free(props);
4227 err = dmu_objset_create(dsname, DMU_OST_OTHER, 0, dcp,
4228 ztest_objset_create_cb, NULL);
4229 dsl_crypto_params_free(dcp, !!err);
4231 rand = ztest_random(100);
4232 if (err || rand < 80)
4235 if (ztest_opts.zo_verbose >= 5)
4236 (void) printf("Setting dataset %s to sync always\n", dsname);
4237 return (ztest_dsl_prop_set_uint64(dsname, ZFS_PROP_SYNC,
4238 ZFS_SYNC_ALWAYS, B_FALSE));
4242 ztest_objset_destroy_cb(const char *name, void *arg)
4246 dmu_object_info_t doi;
4250 * Verify that the dataset contains a directory object.
4252 VERIFY0(ztest_dmu_objset_own(name, DMU_OST_OTHER, B_TRUE,
4253 B_TRUE, FTAG, &os));
4254 error = dmu_object_info(os, ZTEST_DIROBJ, &doi);
4255 if (error != ENOENT) {
4256 /* We could have crashed in the middle of destroying it */
4258 ASSERT3U(doi.doi_type, ==, DMU_OT_ZAP_OTHER);
4259 ASSERT3S(doi.doi_physical_blocks_512, >=, 0);
4261 dmu_objset_disown(os, B_TRUE, FTAG);
4264 * Destroy the dataset.
4266 if (strchr(name, '@') != NULL) {
4267 error = dsl_destroy_snapshot(name, B_TRUE);
4268 if (error != ECHRNG) {
4270 * The program was executed, but encountered a runtime
4271 * error, such as insufficient slop, or a hold on the
4277 error = dsl_destroy_head(name);
4278 if (error == ENOSPC) {
4279 /* There could be checkpoint or insufficient slop */
4280 ztest_record_enospc(FTAG);
4281 } else if (error != EBUSY) {
4282 /* There could be a hold on this dataset */
4290 ztest_snapshot_create(char *osname, uint64_t id)
4292 char snapname[ZFS_MAX_DATASET_NAME_LEN];
4295 (void) snprintf(snapname, sizeof (snapname), "%"PRIu64"", id);
4297 error = dmu_objset_snapshot_one(osname, snapname);
4298 if (error == ENOSPC) {
4299 ztest_record_enospc(FTAG);
4302 if (error != 0 && error != EEXIST && error != ECHRNG) {
4303 fatal(B_FALSE, "ztest_snapshot_create(%s@%s) = %d", osname,
4310 ztest_snapshot_destroy(char *osname, uint64_t id)
4312 char snapname[ZFS_MAX_DATASET_NAME_LEN];
4315 (void) snprintf(snapname, sizeof (snapname), "%s@%"PRIu64"",
4318 error = dsl_destroy_snapshot(snapname, B_FALSE);
4319 if (error != 0 && error != ENOENT && error != ECHRNG)
4320 fatal(B_FALSE, "ztest_snapshot_destroy(%s) = %d",
4326 ztest_dmu_objset_create_destroy(ztest_ds_t *zd, uint64_t id)
4333 char name[ZFS_MAX_DATASET_NAME_LEN];
4337 zdtmp = umem_alloc(sizeof (ztest_ds_t), UMEM_NOFAIL);
4339 (void) pthread_rwlock_rdlock(&ztest_name_lock);
4341 (void) snprintf(name, sizeof (name), "%s/temp_%"PRIu64"",
4342 ztest_opts.zo_pool, id);
4345 * If this dataset exists from a previous run, process its replay log
4346 * half of the time. If we don't replay it, then dsl_destroy_head()
4347 * (invoked from ztest_objset_destroy_cb()) should just throw it away.
4349 if (ztest_random(2) == 0 &&
4350 ztest_dmu_objset_own(name, DMU_OST_OTHER, B_FALSE,
4351 B_TRUE, FTAG, &os) == 0) {
4352 ztest_zd_init(zdtmp, NULL, os);
4353 zil_replay(os, zdtmp, ztest_replay_vector);
4354 ztest_zd_fini(zdtmp);
4355 dmu_objset_disown(os, B_TRUE, FTAG);
4359 * There may be an old instance of the dataset we're about to
4360 * create lying around from a previous run. If so, destroy it
4361 * and all of its snapshots.
4363 (void) dmu_objset_find(name, ztest_objset_destroy_cb, NULL,
4364 DS_FIND_CHILDREN | DS_FIND_SNAPSHOTS);
4367 * Verify that the destroyed dataset is no longer in the namespace.
4368 * It may still be present if the destroy above fails with ENOSPC.
4370 error = ztest_dmu_objset_own(name, DMU_OST_OTHER, B_TRUE, B_TRUE,
4373 dmu_objset_disown(os, B_TRUE, FTAG);
4374 ztest_record_enospc(FTAG);
4377 VERIFY3U(ENOENT, ==, error);
4380 * Verify that we can create a new dataset.
4382 error = ztest_dataset_create(name);
4384 if (error == ENOSPC) {
4385 ztest_record_enospc(FTAG);
4388 fatal(B_FALSE, "dmu_objset_create(%s) = %d", name, error);
4391 VERIFY0(ztest_dmu_objset_own(name, DMU_OST_OTHER, B_FALSE, B_TRUE,
4394 ztest_zd_init(zdtmp, NULL, os);
4397 * Open the intent log for it.
4399 zilog = zil_open(os, ztest_get_data, NULL);
4402 * Put some objects in there, do a little I/O to them,
4403 * and randomly take a couple of snapshots along the way.
4405 iters = ztest_random(5);
4406 for (i = 0; i < iters; i++) {
4407 ztest_dmu_object_alloc_free(zdtmp, id);
4408 if (ztest_random(iters) == 0)
4409 (void) ztest_snapshot_create(name, i);
4413 * Verify that we cannot create an existing dataset.
4415 VERIFY3U(EEXIST, ==,
4416 dmu_objset_create(name, DMU_OST_OTHER, 0, NULL, NULL, NULL));
4419 * Verify that we can hold an objset that is also owned.
4421 VERIFY0(dmu_objset_hold(name, FTAG, &os2));
4422 dmu_objset_rele(os2, FTAG);
4425 * Verify that we cannot own an objset that is already owned.
4427 VERIFY3U(EBUSY, ==, ztest_dmu_objset_own(name, DMU_OST_OTHER,
4428 B_FALSE, B_TRUE, FTAG, &os2));
4431 dmu_objset_disown(os, B_TRUE, FTAG);
4432 ztest_zd_fini(zdtmp);
4434 (void) pthread_rwlock_unlock(&ztest_name_lock);
4436 umem_free(zdtmp, sizeof (ztest_ds_t));
4440 * Verify that dmu_snapshot_{create,destroy,open,close} work as expected.
4443 ztest_dmu_snapshot_create_destroy(ztest_ds_t *zd, uint64_t id)
4445 (void) pthread_rwlock_rdlock(&ztest_name_lock);
4446 (void) ztest_snapshot_destroy(zd->zd_name, id);
4447 (void) ztest_snapshot_create(zd->zd_name, id);
4448 (void) pthread_rwlock_unlock(&ztest_name_lock);
4452 * Cleanup non-standard snapshots and clones.
4455 ztest_dsl_dataset_cleanup(char *osname, uint64_t id)
4464 snap1name = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
4465 clone1name = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
4466 snap2name = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
4467 clone2name = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
4468 snap3name = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
4470 (void) snprintf(snap1name, ZFS_MAX_DATASET_NAME_LEN, "%s@s1_%"PRIu64"",
4472 (void) snprintf(clone1name, ZFS_MAX_DATASET_NAME_LEN, "%s/c1_%"PRIu64"",
4474 (void) snprintf(snap2name, ZFS_MAX_DATASET_NAME_LEN, "%s@s2_%"PRIu64"",
4476 (void) snprintf(clone2name, ZFS_MAX_DATASET_NAME_LEN, "%s/c2_%"PRIu64"",
4478 (void) snprintf(snap3name, ZFS_MAX_DATASET_NAME_LEN, "%s@s3_%"PRIu64"",
4481 error = dsl_destroy_head(clone2name);
4482 if (error && error != ENOENT)
4483 fatal(B_FALSE, "dsl_destroy_head(%s) = %d", clone2name, error);
4484 error = dsl_destroy_snapshot(snap3name, B_FALSE);
4485 if (error && error != ENOENT)
4486 fatal(B_FALSE, "dsl_destroy_snapshot(%s) = %d",
4488 error = dsl_destroy_snapshot(snap2name, B_FALSE);
4489 if (error && error != ENOENT)
4490 fatal(B_FALSE, "dsl_destroy_snapshot(%s) = %d",
4492 error = dsl_destroy_head(clone1name);
4493 if (error && error != ENOENT)
4494 fatal(B_FALSE, "dsl_destroy_head(%s) = %d", clone1name, error);
4495 error = dsl_destroy_snapshot(snap1name, B_FALSE);
4496 if (error && error != ENOENT)
4497 fatal(B_FALSE, "dsl_destroy_snapshot(%s) = %d",
4500 umem_free(snap1name, ZFS_MAX_DATASET_NAME_LEN);
4501 umem_free(clone1name, ZFS_MAX_DATASET_NAME_LEN);
4502 umem_free(snap2name, ZFS_MAX_DATASET_NAME_LEN);
4503 umem_free(clone2name, ZFS_MAX_DATASET_NAME_LEN);
4504 umem_free(snap3name, ZFS_MAX_DATASET_NAME_LEN);
4508 * Verify dsl_dataset_promote handles EBUSY
4511 ztest_dsl_dataset_promote_busy(ztest_ds_t *zd, uint64_t id)
4519 char *osname = zd->zd_name;
4522 snap1name = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
4523 clone1name = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
4524 snap2name = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
4525 clone2name = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
4526 snap3name = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
4528 (void) pthread_rwlock_rdlock(&ztest_name_lock);
4530 ztest_dsl_dataset_cleanup(osname, id);
4532 (void) snprintf(snap1name, ZFS_MAX_DATASET_NAME_LEN, "%s@s1_%"PRIu64"",
4534 (void) snprintf(clone1name, ZFS_MAX_DATASET_NAME_LEN, "%s/c1_%"PRIu64"",
4536 (void) snprintf(snap2name, ZFS_MAX_DATASET_NAME_LEN, "%s@s2_%"PRIu64"",
4538 (void) snprintf(clone2name, ZFS_MAX_DATASET_NAME_LEN, "%s/c2_%"PRIu64"",
4540 (void) snprintf(snap3name, ZFS_MAX_DATASET_NAME_LEN, "%s@s3_%"PRIu64"",
4543 error = dmu_objset_snapshot_one(osname, strchr(snap1name, '@') + 1);
4544 if (error && error != EEXIST) {
4545 if (error == ENOSPC) {
4546 ztest_record_enospc(FTAG);
4549 fatal(B_FALSE, "dmu_take_snapshot(%s) = %d", snap1name, error);
4552 error = dmu_objset_clone(clone1name, snap1name);
4554 if (error == ENOSPC) {
4555 ztest_record_enospc(FTAG);
4558 fatal(B_FALSE, "dmu_objset_create(%s) = %d", clone1name, error);
4561 error = dmu_objset_snapshot_one(clone1name, strchr(snap2name, '@') + 1);
4562 if (error && error != EEXIST) {
4563 if (error == ENOSPC) {
4564 ztest_record_enospc(FTAG);
4567 fatal(B_FALSE, "dmu_open_snapshot(%s) = %d", snap2name, error);
4570 error = dmu_objset_snapshot_one(clone1name, strchr(snap3name, '@') + 1);
4571 if (error && error != EEXIST) {
4572 if (error == ENOSPC) {
4573 ztest_record_enospc(FTAG);
4576 fatal(B_FALSE, "dmu_open_snapshot(%s) = %d", snap3name, error);
4579 error = dmu_objset_clone(clone2name, snap3name);
4581 if (error == ENOSPC) {
4582 ztest_record_enospc(FTAG);
4585 fatal(B_FALSE, "dmu_objset_create(%s) = %d", clone2name, error);
4588 error = ztest_dmu_objset_own(snap2name, DMU_OST_ANY, B_TRUE, B_TRUE,
4591 fatal(B_FALSE, "dmu_objset_own(%s) = %d", snap2name, error);
4592 error = dsl_dataset_promote(clone2name, NULL);
4593 if (error == ENOSPC) {
4594 dmu_objset_disown(os, B_TRUE, FTAG);
4595 ztest_record_enospc(FTAG);
4599 fatal(B_FALSE, "dsl_dataset_promote(%s), %d, not EBUSY",
4601 dmu_objset_disown(os, B_TRUE, FTAG);
4604 ztest_dsl_dataset_cleanup(osname, id);
4606 (void) pthread_rwlock_unlock(&ztest_name_lock);
4608 umem_free(snap1name, ZFS_MAX_DATASET_NAME_LEN);
4609 umem_free(clone1name, ZFS_MAX_DATASET_NAME_LEN);
4610 umem_free(snap2name, ZFS_MAX_DATASET_NAME_LEN);
4611 umem_free(clone2name, ZFS_MAX_DATASET_NAME_LEN);
4612 umem_free(snap3name, ZFS_MAX_DATASET_NAME_LEN);
4615 #undef OD_ARRAY_SIZE
4616 #define OD_ARRAY_SIZE 4
4619 * Verify that dmu_object_{alloc,free} work as expected.
4622 ztest_dmu_object_alloc_free(ztest_ds_t *zd, uint64_t id)
4629 size = sizeof (ztest_od_t) * OD_ARRAY_SIZE;
4630 od = umem_alloc(size, UMEM_NOFAIL);
4631 batchsize = OD_ARRAY_SIZE;
4633 for (b = 0; b < batchsize; b++)
4634 ztest_od_init(od + b, id, FTAG, b, DMU_OT_UINT64_OTHER,
4638 * Destroy the previous batch of objects, create a new batch,
4639 * and do some I/O on the new objects.
4641 if (ztest_object_init(zd, od, size, B_TRUE) != 0)
4644 while (ztest_random(4 * batchsize) != 0)
4645 ztest_io(zd, od[ztest_random(batchsize)].od_object,
4646 ztest_random(ZTEST_RANGE_LOCKS) << SPA_MAXBLOCKSHIFT);
4648 umem_free(od, size);
4652 * Rewind the global allocator to verify object allocation backfilling.
4655 ztest_dmu_object_next_chunk(ztest_ds_t *zd, uint64_t id)
4658 objset_t *os = zd->zd_os;
4659 uint_t dnodes_per_chunk = 1 << dmu_object_alloc_chunk_shift;
4663 * Rewind the global allocator randomly back to a lower object number
4664 * to force backfilling and reclamation of recently freed dnodes.
4666 mutex_enter(&os->os_obj_lock);
4667 object = ztest_random(os->os_obj_next_chunk);
4668 os->os_obj_next_chunk = P2ALIGN(object, dnodes_per_chunk);
4669 mutex_exit(&os->os_obj_lock);
4672 #undef OD_ARRAY_SIZE
4673 #define OD_ARRAY_SIZE 2
4676 * Verify that dmu_{read,write} work as expected.
4679 ztest_dmu_read_write(ztest_ds_t *zd, uint64_t id)
4684 objset_t *os = zd->zd_os;
4685 size = sizeof (ztest_od_t) * OD_ARRAY_SIZE;
4686 od = umem_alloc(size, UMEM_NOFAIL);
4689 uint64_t i, n, s, txg;
4690 bufwad_t *packbuf, *bigbuf, *pack, *bigH, *bigT;
4691 uint64_t packobj, packoff, packsize, bigobj, bigoff, bigsize;
4692 uint64_t chunksize = (1000 + ztest_random(1000)) * sizeof (uint64_t);
4693 uint64_t regions = 997;
4694 uint64_t stride = 123456789ULL;
4695 uint64_t width = 40;
4696 int free_percent = 5;
4699 * This test uses two objects, packobj and bigobj, that are always
4700 * updated together (i.e. in the same tx) so that their contents are
4701 * in sync and can be compared. Their contents relate to each other
4702 * in a simple way: packobj is a dense array of 'bufwad' structures,
4703 * while bigobj is a sparse array of the same bufwads. Specifically,
4704 * for any index n, there are three bufwads that should be identical:
4706 * packobj, at offset n * sizeof (bufwad_t)
4707 * bigobj, at the head of the nth chunk
4708 * bigobj, at the tail of the nth chunk
4710 * The chunk size is arbitrary. It doesn't have to be a power of two,
4711 * and it doesn't have any relation to the object blocksize.
4712 * The only requirement is that it can hold at least two bufwads.
4714 * Normally, we write the bufwad to each of these locations.
4715 * However, free_percent of the time we instead write zeroes to
4716 * packobj and perform a dmu_free_range() on bigobj. By comparing
4717 * bigobj to packobj, we can verify that the DMU is correctly
4718 * tracking which parts of an object are allocated and free,
4719 * and that the contents of the allocated blocks are correct.
4723 * Read the directory info. If it's the first time, set things up.
4725 ztest_od_init(od, id, FTAG, 0, DMU_OT_UINT64_OTHER, 0, 0, chunksize);
4726 ztest_od_init(od + 1, id, FTAG, 1, DMU_OT_UINT64_OTHER, 0, 0,
4729 if (ztest_object_init(zd, od, size, B_FALSE) != 0) {
4730 umem_free(od, size);
4734 bigobj = od[0].od_object;
4735 packobj = od[1].od_object;
4736 chunksize = od[0].od_gen;
4737 ASSERT3U(chunksize, ==, od[1].od_gen);
4740 * Prefetch a random chunk of the big object.
4741 * Our aim here is to get some async reads in flight
4742 * for blocks that we may free below; the DMU should
4743 * handle this race correctly.
4745 n = ztest_random(regions) * stride + ztest_random(width);
4746 s = 1 + ztest_random(2 * width - 1);
4747 dmu_prefetch(os, bigobj, 0, n * chunksize, s * chunksize,
4748 ZIO_PRIORITY_SYNC_READ);
4751 * Pick a random index and compute the offsets into packobj and bigobj.
4753 n = ztest_random(regions) * stride + ztest_random(width);
4754 s = 1 + ztest_random(width - 1);
4756 packoff = n * sizeof (bufwad_t);
4757 packsize = s * sizeof (bufwad_t);
4759 bigoff = n * chunksize;
4760 bigsize = s * chunksize;
4762 packbuf = umem_alloc(packsize, UMEM_NOFAIL);
4763 bigbuf = umem_alloc(bigsize, UMEM_NOFAIL);
4766 * free_percent of the time, free a range of bigobj rather than
4769 freeit = (ztest_random(100) < free_percent);
4772 * Read the current contents of our objects.
4774 error = dmu_read(os, packobj, packoff, packsize, packbuf,
4777 error = dmu_read(os, bigobj, bigoff, bigsize, bigbuf,
4782 * Get a tx for the mods to both packobj and bigobj.
4784 tx = dmu_tx_create(os);
4786 dmu_tx_hold_write(tx, packobj, packoff, packsize);
4789 dmu_tx_hold_free(tx, bigobj, bigoff, bigsize);
4791 dmu_tx_hold_write(tx, bigobj, bigoff, bigsize);
4793 /* This accounts for setting the checksum/compression. */
4794 dmu_tx_hold_bonus(tx, bigobj);
4796 txg = ztest_tx_assign(tx, TXG_MIGHTWAIT, FTAG);
4798 umem_free(packbuf, packsize);
4799 umem_free(bigbuf, bigsize);
4800 umem_free(od, size);
4804 enum zio_checksum cksum;
4806 cksum = (enum zio_checksum)
4807 ztest_random_dsl_prop(ZFS_PROP_CHECKSUM);
4808 } while (cksum >= ZIO_CHECKSUM_LEGACY_FUNCTIONS);
4809 dmu_object_set_checksum(os, bigobj, cksum, tx);
4811 enum zio_compress comp;
4813 comp = (enum zio_compress)
4814 ztest_random_dsl_prop(ZFS_PROP_COMPRESSION);
4815 } while (comp >= ZIO_COMPRESS_LEGACY_FUNCTIONS);
4816 dmu_object_set_compress(os, bigobj, comp, tx);
4819 * For each index from n to n + s, verify that the existing bufwad
4820 * in packobj matches the bufwads at the head and tail of the
4821 * corresponding chunk in bigobj. Then update all three bufwads
4822 * with the new values we want to write out.
4824 for (i = 0; i < s; i++) {
4826 pack = (bufwad_t *)((char *)packbuf + i * sizeof (bufwad_t));
4828 bigH = (bufwad_t *)((char *)bigbuf + i * chunksize);
4830 bigT = (bufwad_t *)((char *)bigH + chunksize) - 1;
4832 ASSERT3U((uintptr_t)bigH - (uintptr_t)bigbuf, <, bigsize);
4833 ASSERT3U((uintptr_t)bigT - (uintptr_t)bigbuf, <, bigsize);
4835 if (pack->bw_txg > txg)
4837 "future leak: got %"PRIx64", open txg is %"PRIx64"",
4840 if (pack->bw_data != 0 && pack->bw_index != n + i)
4841 fatal(B_FALSE, "wrong index: "
4842 "got %"PRIx64", wanted %"PRIx64"+%"PRIx64"",
4843 pack->bw_index, n, i);
4845 if (memcmp(pack, bigH, sizeof (bufwad_t)) != 0)
4846 fatal(B_FALSE, "pack/bigH mismatch in %p/%p",
4849 if (memcmp(pack, bigT, sizeof (bufwad_t)) != 0)
4850 fatal(B_FALSE, "pack/bigT mismatch in %p/%p",
4854 memset(pack, 0, sizeof (bufwad_t));
4856 pack->bw_index = n + i;
4858 pack->bw_data = 1 + ztest_random(-2ULL);
4865 * We've verified all the old bufwads, and made new ones.
4866 * Now write them out.
4868 dmu_write(os, packobj, packoff, packsize, packbuf, tx);
4871 if (ztest_opts.zo_verbose >= 7) {
4872 (void) printf("freeing offset %"PRIx64" size %"PRIx64""
4874 bigoff, bigsize, txg);
4876 VERIFY0(dmu_free_range(os, bigobj, bigoff, bigsize, tx));
4878 if (ztest_opts.zo_verbose >= 7) {
4879 (void) printf("writing offset %"PRIx64" size %"PRIx64""
4881 bigoff, bigsize, txg);
4883 dmu_write(os, bigobj, bigoff, bigsize, bigbuf, tx);
4889 * Sanity check the stuff we just wrote.
4892 void *packcheck = umem_alloc(packsize, UMEM_NOFAIL);
4893 void *bigcheck = umem_alloc(bigsize, UMEM_NOFAIL);
4895 VERIFY0(dmu_read(os, packobj, packoff,
4896 packsize, packcheck, DMU_READ_PREFETCH));
4897 VERIFY0(dmu_read(os, bigobj, bigoff,
4898 bigsize, bigcheck, DMU_READ_PREFETCH));
4900 ASSERT0(memcmp(packbuf, packcheck, packsize));
4901 ASSERT0(memcmp(bigbuf, bigcheck, bigsize));
4903 umem_free(packcheck, packsize);
4904 umem_free(bigcheck, bigsize);
4907 umem_free(packbuf, packsize);
4908 umem_free(bigbuf, bigsize);
4909 umem_free(od, size);
4913 compare_and_update_pbbufs(uint64_t s, bufwad_t *packbuf, bufwad_t *bigbuf,
4914 uint64_t bigsize, uint64_t n, uint64_t chunksize, uint64_t txg)
4922 * For each index from n to n + s, verify that the existing bufwad
4923 * in packobj matches the bufwads at the head and tail of the
4924 * corresponding chunk in bigobj. Then update all three bufwads
4925 * with the new values we want to write out.
4927 for (i = 0; i < s; i++) {
4929 pack = (bufwad_t *)((char *)packbuf + i * sizeof (bufwad_t));
4931 bigH = (bufwad_t *)((char *)bigbuf + i * chunksize);
4933 bigT = (bufwad_t *)((char *)bigH + chunksize) - 1;
4935 ASSERT3U((uintptr_t)bigH - (uintptr_t)bigbuf, <, bigsize);
4936 ASSERT3U((uintptr_t)bigT - (uintptr_t)bigbuf, <, bigsize);
4938 if (pack->bw_txg > txg)
4940 "future leak: got %"PRIx64", open txg is %"PRIx64"",
4943 if (pack->bw_data != 0 && pack->bw_index != n + i)
4944 fatal(B_FALSE, "wrong index: "
4945 "got %"PRIx64", wanted %"PRIx64"+%"PRIx64"",
4946 pack->bw_index, n, i);
4948 if (memcmp(pack, bigH, sizeof (bufwad_t)) != 0)
4949 fatal(B_FALSE, "pack/bigH mismatch in %p/%p",
4952 if (memcmp(pack, bigT, sizeof (bufwad_t)) != 0)
4953 fatal(B_FALSE, "pack/bigT mismatch in %p/%p",
4956 pack->bw_index = n + i;
4958 pack->bw_data = 1 + ztest_random(-2ULL);
4965 #undef OD_ARRAY_SIZE
4966 #define OD_ARRAY_SIZE 2
4969 ztest_dmu_read_write_zcopy(ztest_ds_t *zd, uint64_t id)
4971 objset_t *os = zd->zd_os;
4978 bufwad_t *packbuf, *bigbuf;
4979 uint64_t packobj, packoff, packsize, bigobj, bigoff, bigsize;
4980 uint64_t blocksize = ztest_random_blocksize();
4981 uint64_t chunksize = blocksize;
4982 uint64_t regions = 997;
4983 uint64_t stride = 123456789ULL;
4985 dmu_buf_t *bonus_db;
4986 arc_buf_t **bigbuf_arcbufs;
4987 dmu_object_info_t doi;
4989 size = sizeof (ztest_od_t) * OD_ARRAY_SIZE;
4990 od = umem_alloc(size, UMEM_NOFAIL);
4993 * This test uses two objects, packobj and bigobj, that are always
4994 * updated together (i.e. in the same tx) so that their contents are
4995 * in sync and can be compared. Their contents relate to each other
4996 * in a simple way: packobj is a dense array of 'bufwad' structures,
4997 * while bigobj is a sparse array of the same bufwads. Specifically,
4998 * for any index n, there are three bufwads that should be identical:
5000 * packobj, at offset n * sizeof (bufwad_t)
5001 * bigobj, at the head of the nth chunk
5002 * bigobj, at the tail of the nth chunk
5004 * The chunk size is set equal to bigobj block size so that
5005 * dmu_assign_arcbuf_by_dbuf() can be tested for object updates.
5009 * Read the directory info. If it's the first time, set things up.
5011 ztest_od_init(od, id, FTAG, 0, DMU_OT_UINT64_OTHER, blocksize, 0, 0);
5012 ztest_od_init(od + 1, id, FTAG, 1, DMU_OT_UINT64_OTHER, 0, 0,
5016 if (ztest_object_init(zd, od, size, B_FALSE) != 0) {
5017 umem_free(od, size);
5021 bigobj = od[0].od_object;
5022 packobj = od[1].od_object;
5023 blocksize = od[0].od_blocksize;
5024 chunksize = blocksize;
5025 ASSERT3U(chunksize, ==, od[1].od_gen);
5027 VERIFY0(dmu_object_info(os, bigobj, &doi));
5028 VERIFY(ISP2(doi.doi_data_block_size));
5029 VERIFY3U(chunksize, ==, doi.doi_data_block_size);
5030 VERIFY3U(chunksize, >=, 2 * sizeof (bufwad_t));
5033 * Pick a random index and compute the offsets into packobj and bigobj.
5035 n = ztest_random(regions) * stride + ztest_random(width);
5036 s = 1 + ztest_random(width - 1);
5038 packoff = n * sizeof (bufwad_t);
5039 packsize = s * sizeof (bufwad_t);
5041 bigoff = n * chunksize;
5042 bigsize = s * chunksize;
5044 packbuf = umem_zalloc(packsize, UMEM_NOFAIL);
5045 bigbuf = umem_zalloc(bigsize, UMEM_NOFAIL);
5047 VERIFY0(dmu_bonus_hold(os, bigobj, FTAG, &bonus_db));
5049 bigbuf_arcbufs = umem_zalloc(2 * s * sizeof (arc_buf_t *), UMEM_NOFAIL);
5052 * Iteration 0 test zcopy for DB_UNCACHED dbufs.
5053 * Iteration 1 test zcopy to already referenced dbufs.
5054 * Iteration 2 test zcopy to dirty dbuf in the same txg.
5055 * Iteration 3 test zcopy to dbuf dirty in previous txg.
5056 * Iteration 4 test zcopy when dbuf is no longer dirty.
5057 * Iteration 5 test zcopy when it can't be done.
5058 * Iteration 6 one more zcopy write.
5060 for (i = 0; i < 7; i++) {
5065 * In iteration 5 (i == 5) use arcbufs
5066 * that don't match bigobj blksz to test
5067 * dmu_assign_arcbuf_by_dbuf() when it can't directly
5068 * assign an arcbuf to a dbuf.
5070 for (j = 0; j < s; j++) {
5071 if (i != 5 || chunksize < (SPA_MINBLOCKSIZE * 2)) {
5073 dmu_request_arcbuf(bonus_db, chunksize);
5075 bigbuf_arcbufs[2 * j] =
5076 dmu_request_arcbuf(bonus_db, chunksize / 2);
5077 bigbuf_arcbufs[2 * j + 1] =
5078 dmu_request_arcbuf(bonus_db, chunksize / 2);
5083 * Get a tx for the mods to both packobj and bigobj.
5085 tx = dmu_tx_create(os);
5087 dmu_tx_hold_write(tx, packobj, packoff, packsize);
5088 dmu_tx_hold_write(tx, bigobj, bigoff, bigsize);
5090 txg = ztest_tx_assign(tx, TXG_MIGHTWAIT, FTAG);
5092 umem_free(packbuf, packsize);
5093 umem_free(bigbuf, bigsize);
5094 for (j = 0; j < s; j++) {
5096 chunksize < (SPA_MINBLOCKSIZE * 2)) {
5097 dmu_return_arcbuf(bigbuf_arcbufs[j]);
5100 bigbuf_arcbufs[2 * j]);
5102 bigbuf_arcbufs[2 * j + 1]);
5105 umem_free(bigbuf_arcbufs, 2 * s * sizeof (arc_buf_t *));
5106 umem_free(od, size);
5107 dmu_buf_rele(bonus_db, FTAG);
5112 * 50% of the time don't read objects in the 1st iteration to
5113 * test dmu_assign_arcbuf_by_dbuf() for the case when there are
5114 * no existing dbufs for the specified offsets.
5116 if (i != 0 || ztest_random(2) != 0) {
5117 error = dmu_read(os, packobj, packoff,
5118 packsize, packbuf, DMU_READ_PREFETCH);
5120 error = dmu_read(os, bigobj, bigoff, bigsize,
5121 bigbuf, DMU_READ_PREFETCH);
5124 compare_and_update_pbbufs(s, packbuf, bigbuf, bigsize,
5128 * We've verified all the old bufwads, and made new ones.
5129 * Now write them out.
5131 dmu_write(os, packobj, packoff, packsize, packbuf, tx);
5132 if (ztest_opts.zo_verbose >= 7) {
5133 (void) printf("writing offset %"PRIx64" size %"PRIx64""
5135 bigoff, bigsize, txg);
5137 for (off = bigoff, j = 0; j < s; j++, off += chunksize) {
5139 if (i != 5 || chunksize < (SPA_MINBLOCKSIZE * 2)) {
5140 memcpy(bigbuf_arcbufs[j]->b_data,
5141 (caddr_t)bigbuf + (off - bigoff),
5144 memcpy(bigbuf_arcbufs[2 * j]->b_data,
5145 (caddr_t)bigbuf + (off - bigoff),
5147 memcpy(bigbuf_arcbufs[2 * j + 1]->b_data,
5148 (caddr_t)bigbuf + (off - bigoff) +
5154 VERIFY(dmu_buf_hold(os, bigobj, off,
5155 FTAG, &dbt, DMU_READ_NO_PREFETCH) == 0);
5157 if (i != 5 || chunksize < (SPA_MINBLOCKSIZE * 2)) {
5158 VERIFY0(dmu_assign_arcbuf_by_dbuf(bonus_db,
5159 off, bigbuf_arcbufs[j], tx));
5161 VERIFY0(dmu_assign_arcbuf_by_dbuf(bonus_db,
5162 off, bigbuf_arcbufs[2 * j], tx));
5163 VERIFY0(dmu_assign_arcbuf_by_dbuf(bonus_db,
5164 off + chunksize / 2,
5165 bigbuf_arcbufs[2 * j + 1], tx));
5168 dmu_buf_rele(dbt, FTAG);
5174 * Sanity check the stuff we just wrote.
5177 void *packcheck = umem_alloc(packsize, UMEM_NOFAIL);
5178 void *bigcheck = umem_alloc(bigsize, UMEM_NOFAIL);
5180 VERIFY0(dmu_read(os, packobj, packoff,
5181 packsize, packcheck, DMU_READ_PREFETCH));
5182 VERIFY0(dmu_read(os, bigobj, bigoff,
5183 bigsize, bigcheck, DMU_READ_PREFETCH));
5185 ASSERT0(memcmp(packbuf, packcheck, packsize));
5186 ASSERT0(memcmp(bigbuf, bigcheck, bigsize));
5188 umem_free(packcheck, packsize);
5189 umem_free(bigcheck, bigsize);
5192 txg_wait_open(dmu_objset_pool(os), 0, B_TRUE);
5193 } else if (i == 3) {
5194 txg_wait_synced(dmu_objset_pool(os), 0);
5198 dmu_buf_rele(bonus_db, FTAG);
5199 umem_free(packbuf, packsize);
5200 umem_free(bigbuf, bigsize);
5201 umem_free(bigbuf_arcbufs, 2 * s * sizeof (arc_buf_t *));
5202 umem_free(od, size);
5206 ztest_dmu_write_parallel(ztest_ds_t *zd, uint64_t id)
5211 od = umem_alloc(sizeof (ztest_od_t), UMEM_NOFAIL);
5212 uint64_t offset = (1ULL << (ztest_random(20) + 43)) +
5213 (ztest_random(ZTEST_RANGE_LOCKS) << SPA_MAXBLOCKSHIFT);
5216 * Have multiple threads write to large offsets in an object
5217 * to verify that parallel writes to an object -- even to the
5218 * same blocks within the object -- doesn't cause any trouble.
5220 ztest_od_init(od, ID_PARALLEL, FTAG, 0, DMU_OT_UINT64_OTHER, 0, 0, 0);
5222 if (ztest_object_init(zd, od, sizeof (ztest_od_t), B_FALSE) != 0)
5225 while (ztest_random(10) != 0)
5226 ztest_io(zd, od->od_object, offset);
5228 umem_free(od, sizeof (ztest_od_t));
5232 ztest_dmu_prealloc(ztest_ds_t *zd, uint64_t id)
5235 uint64_t offset = (1ULL << (ztest_random(4) + SPA_MAXBLOCKSHIFT)) +
5236 (ztest_random(ZTEST_RANGE_LOCKS) << SPA_MAXBLOCKSHIFT);
5237 uint64_t count = ztest_random(20) + 1;
5238 uint64_t blocksize = ztest_random_blocksize();
5241 od = umem_alloc(sizeof (ztest_od_t), UMEM_NOFAIL);
5243 ztest_od_init(od, id, FTAG, 0, DMU_OT_UINT64_OTHER, blocksize, 0, 0);
5245 if (ztest_object_init(zd, od, sizeof (ztest_od_t),
5246 !ztest_random(2)) != 0) {
5247 umem_free(od, sizeof (ztest_od_t));
5251 if (ztest_truncate(zd, od->od_object, offset, count * blocksize) != 0) {
5252 umem_free(od, sizeof (ztest_od_t));
5256 ztest_prealloc(zd, od->od_object, offset, count * blocksize);
5258 data = umem_zalloc(blocksize, UMEM_NOFAIL);
5260 while (ztest_random(count) != 0) {
5261 uint64_t randoff = offset + (ztest_random(count) * blocksize);
5262 if (ztest_write(zd, od->od_object, randoff, blocksize,
5265 while (ztest_random(4) != 0)
5266 ztest_io(zd, od->od_object, randoff);
5269 umem_free(data, blocksize);
5270 umem_free(od, sizeof (ztest_od_t));
5274 * Verify that zap_{create,destroy,add,remove,update} work as expected.
5276 #define ZTEST_ZAP_MIN_INTS 1
5277 #define ZTEST_ZAP_MAX_INTS 4
5278 #define ZTEST_ZAP_MAX_PROPS 1000
5281 ztest_zap(ztest_ds_t *zd, uint64_t id)
5283 objset_t *os = zd->zd_os;
5286 uint64_t txg, last_txg;
5287 uint64_t value[ZTEST_ZAP_MAX_INTS];
5288 uint64_t zl_ints, zl_intsize, prop;
5291 char propname[100], txgname[100];
5293 const char *const hc[2] = { "s.acl.h", ".s.open.h.hyLZlg" };
5295 od = umem_alloc(sizeof (ztest_od_t), UMEM_NOFAIL);
5296 ztest_od_init(od, id, FTAG, 0, DMU_OT_ZAP_OTHER, 0, 0, 0);
5298 if (ztest_object_init(zd, od, sizeof (ztest_od_t),
5299 !ztest_random(2)) != 0)
5302 object = od->od_object;
5305 * Generate a known hash collision, and verify that
5306 * we can lookup and remove both entries.
5308 tx = dmu_tx_create(os);
5309 dmu_tx_hold_zap(tx, object, B_TRUE, NULL);
5310 txg = ztest_tx_assign(tx, TXG_MIGHTWAIT, FTAG);
5313 for (i = 0; i < 2; i++) {
5315 VERIFY0(zap_add(os, object, hc[i], sizeof (uint64_t),
5318 for (i = 0; i < 2; i++) {
5319 VERIFY3U(EEXIST, ==, zap_add(os, object, hc[i],
5320 sizeof (uint64_t), 1, &value[i], tx));
5322 zap_length(os, object, hc[i], &zl_intsize, &zl_ints));
5323 ASSERT3U(zl_intsize, ==, sizeof (uint64_t));
5324 ASSERT3U(zl_ints, ==, 1);
5326 for (i = 0; i < 2; i++) {
5327 VERIFY0(zap_remove(os, object, hc[i], tx));
5332 * Generate a bunch of random entries.
5334 ints = MAX(ZTEST_ZAP_MIN_INTS, object % ZTEST_ZAP_MAX_INTS);
5336 prop = ztest_random(ZTEST_ZAP_MAX_PROPS);
5337 (void) sprintf(propname, "prop_%"PRIu64"", prop);
5338 (void) sprintf(txgname, "txg_%"PRIu64"", prop);
5339 memset(value, 0, sizeof (value));
5343 * If these zap entries already exist, validate their contents.
5345 error = zap_length(os, object, txgname, &zl_intsize, &zl_ints);
5347 ASSERT3U(zl_intsize, ==, sizeof (uint64_t));
5348 ASSERT3U(zl_ints, ==, 1);
5350 VERIFY0(zap_lookup(os, object, txgname, zl_intsize,
5351 zl_ints, &last_txg));
5353 VERIFY0(zap_length(os, object, propname, &zl_intsize,
5356 ASSERT3U(zl_intsize, ==, sizeof (uint64_t));
5357 ASSERT3U(zl_ints, ==, ints);
5359 VERIFY0(zap_lookup(os, object, propname, zl_intsize,
5362 for (i = 0; i < ints; i++) {
5363 ASSERT3U(value[i], ==, last_txg + object + i);
5366 ASSERT3U(error, ==, ENOENT);
5370 * Atomically update two entries in our zap object.
5371 * The first is named txg_%llu, and contains the txg
5372 * in which the property was last updated. The second
5373 * is named prop_%llu, and the nth element of its value
5374 * should be txg + object + n.
5376 tx = dmu_tx_create(os);
5377 dmu_tx_hold_zap(tx, object, B_TRUE, NULL);
5378 txg = ztest_tx_assign(tx, TXG_MIGHTWAIT, FTAG);
5383 fatal(B_FALSE, "zap future leak: old %"PRIu64" new %"PRIu64"",
5386 for (i = 0; i < ints; i++)
5387 value[i] = txg + object + i;
5389 VERIFY0(zap_update(os, object, txgname, sizeof (uint64_t),
5391 VERIFY0(zap_update(os, object, propname, sizeof (uint64_t),
5397 * Remove a random pair of entries.
5399 prop = ztest_random(ZTEST_ZAP_MAX_PROPS);
5400 (void) sprintf(propname, "prop_%"PRIu64"", prop);
5401 (void) sprintf(txgname, "txg_%"PRIu64"", prop);
5403 error = zap_length(os, object, txgname, &zl_intsize, &zl_ints);
5405 if (error == ENOENT)
5410 tx = dmu_tx_create(os);
5411 dmu_tx_hold_zap(tx, object, B_TRUE, NULL);
5412 txg = ztest_tx_assign(tx, TXG_MIGHTWAIT, FTAG);
5415 VERIFY0(zap_remove(os, object, txgname, tx));
5416 VERIFY0(zap_remove(os, object, propname, tx));
5419 umem_free(od, sizeof (ztest_od_t));
5423 * Test case to test the upgrading of a microzap to fatzap.
5426 ztest_fzap(ztest_ds_t *zd, uint64_t id)
5428 objset_t *os = zd->zd_os;
5430 uint64_t object, txg, value;
5432 od = umem_alloc(sizeof (ztest_od_t), UMEM_NOFAIL);
5433 ztest_od_init(od, id, FTAG, 0, DMU_OT_ZAP_OTHER, 0, 0, 0);
5435 if (ztest_object_init(zd, od, sizeof (ztest_od_t),
5436 !ztest_random(2)) != 0)
5438 object = od->od_object;
5441 * Add entries to this ZAP and make sure it spills over
5442 * and gets upgraded to a fatzap. Also, since we are adding
5443 * 2050 entries we should see ptrtbl growth and leaf-block split.
5445 for (value = 0; value < 2050; value++) {
5446 char name[ZFS_MAX_DATASET_NAME_LEN];
5450 (void) snprintf(name, sizeof (name), "fzap-%"PRIu64"-%"PRIu64"",
5453 tx = dmu_tx_create(os);
5454 dmu_tx_hold_zap(tx, object, B_TRUE, name);
5455 txg = ztest_tx_assign(tx, TXG_MIGHTWAIT, FTAG);
5458 error = zap_add(os, object, name, sizeof (uint64_t), 1,
5460 ASSERT(error == 0 || error == EEXIST);
5464 umem_free(od, sizeof (ztest_od_t));
5468 ztest_zap_parallel(ztest_ds_t *zd, uint64_t id)
5471 objset_t *os = zd->zd_os;
5473 uint64_t txg, object, count, wsize, wc, zl_wsize, zl_wc;
5475 int i, namelen, error;
5476 int micro = ztest_random(2);
5477 char name[20], string_value[20];
5480 od = umem_alloc(sizeof (ztest_od_t), UMEM_NOFAIL);
5481 ztest_od_init(od, ID_PARALLEL, FTAG, micro, DMU_OT_ZAP_OTHER, 0, 0, 0);
5483 if (ztest_object_init(zd, od, sizeof (ztest_od_t), B_FALSE) != 0) {
5484 umem_free(od, sizeof (ztest_od_t));
5488 object = od->od_object;
5491 * Generate a random name of the form 'xxx.....' where each
5492 * x is a random printable character and the dots are dots.
5493 * There are 94 such characters, and the name length goes from
5494 * 6 to 20, so there are 94^3 * 15 = 12,458,760 possible names.
5496 namelen = ztest_random(sizeof (name) - 5) + 5 + 1;
5498 for (i = 0; i < 3; i++)
5499 name[i] = '!' + ztest_random('~' - '!' + 1);
5500 for (; i < namelen - 1; i++)
5504 if ((namelen & 1) || micro) {
5505 wsize = sizeof (txg);
5511 data = string_value;
5515 VERIFY0(zap_count(os, object, &count));
5516 ASSERT3S(count, !=, -1ULL);
5519 * Select an operation: length, lookup, add, update, remove.
5521 i = ztest_random(5);
5524 tx = dmu_tx_create(os);
5525 dmu_tx_hold_zap(tx, object, B_TRUE, NULL);
5526 txg = ztest_tx_assign(tx, TXG_MIGHTWAIT, FTAG);
5528 umem_free(od, sizeof (ztest_od_t));
5531 memcpy(string_value, name, namelen);
5535 memset(string_value, 0, namelen);
5541 error = zap_length(os, object, name, &zl_wsize, &zl_wc);
5543 ASSERT3U(wsize, ==, zl_wsize);
5544 ASSERT3U(wc, ==, zl_wc);
5546 ASSERT3U(error, ==, ENOENT);
5551 error = zap_lookup(os, object, name, wsize, wc, data);
5553 if (data == string_value &&
5554 memcmp(name, data, namelen) != 0)
5555 fatal(B_FALSE, "name '%s' != val '%s' len %d",
5556 name, (char *)data, namelen);
5558 ASSERT3U(error, ==, ENOENT);
5563 error = zap_add(os, object, name, wsize, wc, data, tx);
5564 ASSERT(error == 0 || error == EEXIST);
5568 VERIFY0(zap_update(os, object, name, wsize, wc, data, tx));
5572 error = zap_remove(os, object, name, tx);
5573 ASSERT(error == 0 || error == ENOENT);
5580 umem_free(od, sizeof (ztest_od_t));
5584 * Commit callback data.
5586 typedef struct ztest_cb_data {
5587 list_node_t zcd_node;
5589 int zcd_expected_err;
5590 boolean_t zcd_added;
5591 boolean_t zcd_called;
5595 /* This is the actual commit callback function */
5597 ztest_commit_callback(void *arg, int error)
5599 ztest_cb_data_t *data = arg;
5600 uint64_t synced_txg;
5602 VERIFY3P(data, !=, NULL);
5603 VERIFY3S(data->zcd_expected_err, ==, error);
5604 VERIFY(!data->zcd_called);
5606 synced_txg = spa_last_synced_txg(data->zcd_spa);
5607 if (data->zcd_txg > synced_txg)
5609 "commit callback of txg %"PRIu64" called prematurely, "
5610 "last synced txg = %"PRIu64"\n",
5611 data->zcd_txg, synced_txg);
5613 data->zcd_called = B_TRUE;
5615 if (error == ECANCELED) {
5616 ASSERT0(data->zcd_txg);
5617 ASSERT(!data->zcd_added);
5620 * The private callback data should be destroyed here, but
5621 * since we are going to check the zcd_called field after
5622 * dmu_tx_abort(), we will destroy it there.
5627 ASSERT(data->zcd_added);
5628 ASSERT3U(data->zcd_txg, !=, 0);
5630 (void) mutex_enter(&zcl.zcl_callbacks_lock);
5632 /* See if this cb was called more quickly */
5633 if ((synced_txg - data->zcd_txg) < zc_min_txg_delay)
5634 zc_min_txg_delay = synced_txg - data->zcd_txg;
5636 /* Remove our callback from the list */
5637 list_remove(&zcl.zcl_callbacks, data);
5639 (void) mutex_exit(&zcl.zcl_callbacks_lock);
5641 umem_free(data, sizeof (ztest_cb_data_t));
5644 /* Allocate and initialize callback data structure */
5645 static ztest_cb_data_t *
5646 ztest_create_cb_data(objset_t *os, uint64_t txg)
5648 ztest_cb_data_t *cb_data;
5650 cb_data = umem_zalloc(sizeof (ztest_cb_data_t), UMEM_NOFAIL);
5652 cb_data->zcd_txg = txg;
5653 cb_data->zcd_spa = dmu_objset_spa(os);
5654 list_link_init(&cb_data->zcd_node);
5660 * Commit callback test.
5663 ztest_dmu_commit_callbacks(ztest_ds_t *zd, uint64_t id)
5665 objset_t *os = zd->zd_os;
5668 ztest_cb_data_t *cb_data[3], *tmp_cb;
5669 uint64_t old_txg, txg;
5672 od = umem_alloc(sizeof (ztest_od_t), UMEM_NOFAIL);
5673 ztest_od_init(od, id, FTAG, 0, DMU_OT_UINT64_OTHER, 0, 0, 0);
5675 if (ztest_object_init(zd, od, sizeof (ztest_od_t), B_FALSE) != 0) {
5676 umem_free(od, sizeof (ztest_od_t));
5680 tx = dmu_tx_create(os);
5682 cb_data[0] = ztest_create_cb_data(os, 0);
5683 dmu_tx_callback_register(tx, ztest_commit_callback, cb_data[0]);
5685 dmu_tx_hold_write(tx, od->od_object, 0, sizeof (uint64_t));
5687 /* Every once in a while, abort the transaction on purpose */
5688 if (ztest_random(100) == 0)
5692 error = dmu_tx_assign(tx, TXG_NOWAIT);
5694 txg = error ? 0 : dmu_tx_get_txg(tx);
5696 cb_data[0]->zcd_txg = txg;
5697 cb_data[1] = ztest_create_cb_data(os, txg);
5698 dmu_tx_callback_register(tx, ztest_commit_callback, cb_data[1]);
5702 * It's not a strict requirement to call the registered
5703 * callbacks from inside dmu_tx_abort(), but that's what
5704 * it's supposed to happen in the current implementation
5705 * so we will check for that.
5707 for (i = 0; i < 2; i++) {
5708 cb_data[i]->zcd_expected_err = ECANCELED;
5709 VERIFY(!cb_data[i]->zcd_called);
5714 for (i = 0; i < 2; i++) {
5715 VERIFY(cb_data[i]->zcd_called);
5716 umem_free(cb_data[i], sizeof (ztest_cb_data_t));
5719 umem_free(od, sizeof (ztest_od_t));
5723 cb_data[2] = ztest_create_cb_data(os, txg);
5724 dmu_tx_callback_register(tx, ztest_commit_callback, cb_data[2]);
5727 * Read existing data to make sure there isn't a future leak.
5729 VERIFY0(dmu_read(os, od->od_object, 0, sizeof (uint64_t),
5730 &old_txg, DMU_READ_PREFETCH));
5734 "future leak: got %"PRIu64", open txg is %"PRIu64"",
5737 dmu_write(os, od->od_object, 0, sizeof (uint64_t), &txg, tx);
5739 (void) mutex_enter(&zcl.zcl_callbacks_lock);
5742 * Since commit callbacks don't have any ordering requirement and since
5743 * it is theoretically possible for a commit callback to be called
5744 * after an arbitrary amount of time has elapsed since its txg has been
5745 * synced, it is difficult to reliably determine whether a commit
5746 * callback hasn't been called due to high load or due to a flawed
5749 * In practice, we will assume that if after a certain number of txgs a
5750 * commit callback hasn't been called, then most likely there's an
5751 * implementation bug..
5753 tmp_cb = list_head(&zcl.zcl_callbacks);
5754 if (tmp_cb != NULL &&
5755 tmp_cb->zcd_txg + ZTEST_COMMIT_CB_THRESH < txg) {
5757 "Commit callback threshold exceeded, "
5758 "oldest txg: %"PRIu64", open txg: %"PRIu64"\n",
5759 tmp_cb->zcd_txg, txg);
5763 * Let's find the place to insert our callbacks.
5765 * Even though the list is ordered by txg, it is possible for the
5766 * insertion point to not be the end because our txg may already be
5767 * quiescing at this point and other callbacks in the open txg
5768 * (from other objsets) may have sneaked in.
5770 tmp_cb = list_tail(&zcl.zcl_callbacks);
5771 while (tmp_cb != NULL && tmp_cb->zcd_txg > txg)
5772 tmp_cb = list_prev(&zcl.zcl_callbacks, tmp_cb);
5774 /* Add the 3 callbacks to the list */
5775 for (i = 0; i < 3; i++) {
5777 list_insert_head(&zcl.zcl_callbacks, cb_data[i]);
5779 list_insert_after(&zcl.zcl_callbacks, tmp_cb,
5782 cb_data[i]->zcd_added = B_TRUE;
5783 VERIFY(!cb_data[i]->zcd_called);
5785 tmp_cb = cb_data[i];
5790 (void) mutex_exit(&zcl.zcl_callbacks_lock);
5794 umem_free(od, sizeof (ztest_od_t));
5798 * Visit each object in the dataset. Verify that its properties
5799 * are consistent what was stored in the block tag when it was created,
5800 * and that its unused bonus buffer space has not been overwritten.
5803 ztest_verify_dnode_bt(ztest_ds_t *zd, uint64_t id)
5806 objset_t *os = zd->zd_os;
5810 for (obj = 0; err == 0; err = dmu_object_next(os, &obj, FALSE, 0)) {
5811 ztest_block_tag_t *bt = NULL;
5812 dmu_object_info_t doi;
5815 ztest_object_lock(zd, obj, RL_READER);
5816 if (dmu_bonus_hold(os, obj, FTAG, &db) != 0) {
5817 ztest_object_unlock(zd, obj);
5821 dmu_object_info_from_db(db, &doi);
5822 if (doi.doi_bonus_size >= sizeof (*bt))
5823 bt = ztest_bt_bonus(db);
5825 if (bt && bt->bt_magic == BT_MAGIC) {
5826 ztest_bt_verify(bt, os, obj, doi.doi_dnodesize,
5827 bt->bt_offset, bt->bt_gen, bt->bt_txg,
5829 ztest_verify_unused_bonus(db, bt, obj, os, bt->bt_gen);
5832 dmu_buf_rele(db, FTAG);
5833 ztest_object_unlock(zd, obj);
5838 ztest_dsl_prop_get_set(ztest_ds_t *zd, uint64_t id)
5841 zfs_prop_t proplist[] = {
5843 ZFS_PROP_COMPRESSION,
5848 (void) pthread_rwlock_rdlock(&ztest_name_lock);
5850 for (int p = 0; p < sizeof (proplist) / sizeof (proplist[0]); p++) {
5851 int error = ztest_dsl_prop_set_uint64(zd->zd_name, proplist[p],
5852 ztest_random_dsl_prop(proplist[p]), (int)ztest_random(2));
5853 ASSERT(error == 0 || error == ENOSPC);
5856 int error = ztest_dsl_prop_set_uint64(zd->zd_name, ZFS_PROP_RECORDSIZE,
5857 ztest_random_blocksize(), (int)ztest_random(2));
5858 ASSERT(error == 0 || error == ENOSPC);
5860 (void) pthread_rwlock_unlock(&ztest_name_lock);
5864 ztest_spa_prop_get_set(ztest_ds_t *zd, uint64_t id)
5866 (void) zd, (void) id;
5867 nvlist_t *props = NULL;
5869 (void) pthread_rwlock_rdlock(&ztest_name_lock);
5871 (void) ztest_spa_prop_set_uint64(ZPOOL_PROP_AUTOTRIM, ztest_random(2));
5873 VERIFY0(spa_prop_get(ztest_spa, &props));
5875 if (ztest_opts.zo_verbose >= 6)
5876 dump_nvlist(props, 4);
5878 fnvlist_free(props);
5880 (void) pthread_rwlock_unlock(&ztest_name_lock);
5884 user_release_one(const char *snapname, const char *holdname)
5886 nvlist_t *snaps, *holds;
5889 snaps = fnvlist_alloc();
5890 holds = fnvlist_alloc();
5891 fnvlist_add_boolean(holds, holdname);
5892 fnvlist_add_nvlist(snaps, snapname, holds);
5893 fnvlist_free(holds);
5894 error = dsl_dataset_user_release(snaps, NULL);
5895 fnvlist_free(snaps);
5900 * Test snapshot hold/release and deferred destroy.
5903 ztest_dmu_snapshot_hold(ztest_ds_t *zd, uint64_t id)
5906 objset_t *os = zd->zd_os;
5910 char clonename[100];
5912 char osname[ZFS_MAX_DATASET_NAME_LEN];
5915 (void) pthread_rwlock_rdlock(&ztest_name_lock);
5917 dmu_objset_name(os, osname);
5919 (void) snprintf(snapname, sizeof (snapname), "sh1_%"PRIu64"", id);
5920 (void) snprintf(fullname, sizeof (fullname), "%s@%s", osname, snapname);
5921 (void) snprintf(clonename, sizeof (clonename), "%s/ch1_%"PRIu64"",
5923 (void) snprintf(tag, sizeof (tag), "tag_%"PRIu64"", id);
5926 * Clean up from any previous run.
5928 error = dsl_destroy_head(clonename);
5929 if (error != ENOENT)
5931 error = user_release_one(fullname, tag);
5932 if (error != ESRCH && error != ENOENT)
5934 error = dsl_destroy_snapshot(fullname, B_FALSE);
5935 if (error != ENOENT)
5939 * Create snapshot, clone it, mark snap for deferred destroy,
5940 * destroy clone, verify snap was also destroyed.
5942 error = dmu_objset_snapshot_one(osname, snapname);
5944 if (error == ENOSPC) {
5945 ztest_record_enospc("dmu_objset_snapshot");
5948 fatal(B_FALSE, "dmu_objset_snapshot(%s) = %d", fullname, error);
5951 error = dmu_objset_clone(clonename, fullname);
5953 if (error == ENOSPC) {
5954 ztest_record_enospc("dmu_objset_clone");
5957 fatal(B_FALSE, "dmu_objset_clone(%s) = %d", clonename, error);
5960 error = dsl_destroy_snapshot(fullname, B_TRUE);
5962 fatal(B_FALSE, "dsl_destroy_snapshot(%s, B_TRUE) = %d",
5966 error = dsl_destroy_head(clonename);
5968 fatal(B_FALSE, "dsl_destroy_head(%s) = %d", clonename, error);
5970 error = dmu_objset_hold(fullname, FTAG, &origin);
5971 if (error != ENOENT)
5972 fatal(B_FALSE, "dmu_objset_hold(%s) = %d", fullname, error);
5975 * Create snapshot, add temporary hold, verify that we can't
5976 * destroy a held snapshot, mark for deferred destroy,
5977 * release hold, verify snapshot was destroyed.
5979 error = dmu_objset_snapshot_one(osname, snapname);
5981 if (error == ENOSPC) {
5982 ztest_record_enospc("dmu_objset_snapshot");
5985 fatal(B_FALSE, "dmu_objset_snapshot(%s) = %d", fullname, error);
5988 holds = fnvlist_alloc();
5989 fnvlist_add_string(holds, fullname, tag);
5990 error = dsl_dataset_user_hold(holds, 0, NULL);
5991 fnvlist_free(holds);
5993 if (error == ENOSPC) {
5994 ztest_record_enospc("dsl_dataset_user_hold");
5997 fatal(B_FALSE, "dsl_dataset_user_hold(%s, %s) = %u",
5998 fullname, tag, error);
6001 error = dsl_destroy_snapshot(fullname, B_FALSE);
6002 if (error != EBUSY) {
6003 fatal(B_FALSE, "dsl_destroy_snapshot(%s, B_FALSE) = %d",
6007 error = dsl_destroy_snapshot(fullname, B_TRUE);
6009 fatal(B_FALSE, "dsl_destroy_snapshot(%s, B_TRUE) = %d",
6013 error = user_release_one(fullname, tag);
6015 fatal(B_FALSE, "user_release_one(%s, %s) = %d",
6016 fullname, tag, error);
6018 VERIFY3U(dmu_objset_hold(fullname, FTAG, &origin), ==, ENOENT);
6021 (void) pthread_rwlock_unlock(&ztest_name_lock);
6025 * Inject random faults into the on-disk data.
6028 ztest_fault_inject(ztest_ds_t *zd, uint64_t id)
6030 (void) zd, (void) id;
6031 ztest_shared_t *zs = ztest_shared;
6032 spa_t *spa = ztest_spa;
6036 uint64_t bad = 0x1990c0ffeedecadeull;
6041 int bshift = SPA_MAXBLOCKSHIFT + 2;
6047 boolean_t islog = B_FALSE;
6049 path0 = umem_alloc(MAXPATHLEN, UMEM_NOFAIL);
6050 pathrand = umem_alloc(MAXPATHLEN, UMEM_NOFAIL);
6052 mutex_enter(&ztest_vdev_lock);
6055 * Device removal is in progress, fault injection must be disabled
6056 * until it completes and the pool is scrubbed. The fault injection
6057 * strategy for damaging blocks does not take in to account evacuated
6058 * blocks which may have already been damaged.
6060 if (ztest_device_removal_active) {
6061 mutex_exit(&ztest_vdev_lock);
6065 maxfaults = MAXFAULTS(zs);
6066 leaves = MAX(zs->zs_mirrors, 1) * ztest_opts.zo_raid_children;
6067 mirror_save = zs->zs_mirrors;
6068 mutex_exit(&ztest_vdev_lock);
6070 ASSERT3U(leaves, >=, 1);
6073 * While ztest is running the number of leaves will not change. This
6074 * is critical for the fault injection logic as it determines where
6075 * errors can be safely injected such that they are always repairable.
6077 * When restarting ztest a different number of leaves may be requested
6078 * which will shift the regions to be damaged. This is fine as long
6079 * as the pool has been scrubbed prior to using the new mapping.
6080 * Failure to do can result in non-repairable damage being injected.
6082 if (ztest_pool_scrubbed == B_FALSE)
6086 * Grab the name lock as reader. There are some operations
6087 * which don't like to have their vdevs changed while
6088 * they are in progress (i.e. spa_change_guid). Those
6089 * operations will have grabbed the name lock as writer.
6091 (void) pthread_rwlock_rdlock(&ztest_name_lock);
6094 * We need SCL_STATE here because we're going to look at vd0->vdev_tsd.
6096 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
6098 if (ztest_random(2) == 0) {
6100 * Inject errors on a normal data device or slog device.
6102 top = ztest_random_vdev_top(spa, B_TRUE);
6103 leaf = ztest_random(leaves) + zs->zs_splits;
6106 * Generate paths to the first leaf in this top-level vdev,
6107 * and to the random leaf we selected. We'll induce transient
6108 * write failures and random online/offline activity on leaf 0,
6109 * and we'll write random garbage to the randomly chosen leaf.
6111 (void) snprintf(path0, MAXPATHLEN, ztest_dev_template,
6112 ztest_opts.zo_dir, ztest_opts.zo_pool,
6113 top * leaves + zs->zs_splits);
6114 (void) snprintf(pathrand, MAXPATHLEN, ztest_dev_template,
6115 ztest_opts.zo_dir, ztest_opts.zo_pool,
6116 top * leaves + leaf);
6118 vd0 = vdev_lookup_by_path(spa->spa_root_vdev, path0);
6119 if (vd0 != NULL && vd0->vdev_top->vdev_islog)
6123 * If the top-level vdev needs to be resilvered
6124 * then we only allow faults on the device that is
6127 if (vd0 != NULL && maxfaults != 1 &&
6128 (!vdev_resilver_needed(vd0->vdev_top, NULL, NULL) ||
6129 vd0->vdev_resilver_txg != 0)) {
6131 * Make vd0 explicitly claim to be unreadable,
6132 * or unwritable, or reach behind its back
6133 * and close the underlying fd. We can do this if
6134 * maxfaults == 0 because we'll fail and reexecute,
6135 * and we can do it if maxfaults >= 2 because we'll
6136 * have enough redundancy. If maxfaults == 1, the
6137 * combination of this with injection of random data
6138 * corruption below exceeds the pool's fault tolerance.
6140 vdev_file_t *vf = vd0->vdev_tsd;
6142 zfs_dbgmsg("injecting fault to vdev %llu; maxfaults=%d",
6143 (long long)vd0->vdev_id, (int)maxfaults);
6145 if (vf != NULL && ztest_random(3) == 0) {
6146 (void) close(vf->vf_file->f_fd);
6147 vf->vf_file->f_fd = -1;
6148 } else if (ztest_random(2) == 0) {
6149 vd0->vdev_cant_read = B_TRUE;
6151 vd0->vdev_cant_write = B_TRUE;
6153 guid0 = vd0->vdev_guid;
6157 * Inject errors on an l2cache device.
6159 spa_aux_vdev_t *sav = &spa->spa_l2cache;
6161 if (sav->sav_count == 0) {
6162 spa_config_exit(spa, SCL_STATE, FTAG);
6163 (void) pthread_rwlock_unlock(&ztest_name_lock);
6166 vd0 = sav->sav_vdevs[ztest_random(sav->sav_count)];
6167 guid0 = vd0->vdev_guid;
6168 (void) strlcpy(path0, vd0->vdev_path, MAXPATHLEN);
6169 (void) strlcpy(pathrand, vd0->vdev_path, MAXPATHLEN);
6173 maxfaults = INT_MAX; /* no limit on cache devices */
6176 spa_config_exit(spa, SCL_STATE, FTAG);
6177 (void) pthread_rwlock_unlock(&ztest_name_lock);
6180 * If we can tolerate two or more faults, or we're dealing
6181 * with a slog, randomly online/offline vd0.
6183 if ((maxfaults >= 2 || islog) && guid0 != 0) {
6184 if (ztest_random(10) < 6) {
6185 int flags = (ztest_random(2) == 0 ?
6186 ZFS_OFFLINE_TEMPORARY : 0);
6189 * We have to grab the zs_name_lock as writer to
6190 * prevent a race between offlining a slog and
6191 * destroying a dataset. Offlining the slog will
6192 * grab a reference on the dataset which may cause
6193 * dsl_destroy_head() to fail with EBUSY thus
6194 * leaving the dataset in an inconsistent state.
6197 (void) pthread_rwlock_wrlock(&ztest_name_lock);
6199 VERIFY3U(vdev_offline(spa, guid0, flags), !=, EBUSY);
6202 (void) pthread_rwlock_unlock(&ztest_name_lock);
6205 * Ideally we would like to be able to randomly
6206 * call vdev_[on|off]line without holding locks
6207 * to force unpredictable failures but the side
6208 * effects of vdev_[on|off]line prevent us from
6209 * doing so. We grab the ztest_vdev_lock here to
6210 * prevent a race between injection testing and
6213 mutex_enter(&ztest_vdev_lock);
6214 (void) vdev_online(spa, guid0, 0, NULL);
6215 mutex_exit(&ztest_vdev_lock);
6223 * We have at least single-fault tolerance, so inject data corruption.
6225 fd = open(pathrand, O_RDWR);
6227 if (fd == -1) /* we hit a gap in the device namespace */
6230 fsize = lseek(fd, 0, SEEK_END);
6232 while (--iters != 0) {
6234 * The offset must be chosen carefully to ensure that
6235 * we do not inject a given logical block with errors
6236 * on two different leaf devices, because ZFS can not
6237 * tolerate that (if maxfaults==1).
6239 * To achieve this we divide each leaf device into
6240 * chunks of size (# leaves * SPA_MAXBLOCKSIZE * 4).
6241 * Each chunk is further divided into error-injection
6242 * ranges (can accept errors) and clear ranges (we do
6243 * not inject errors in those). Each error-injection
6244 * range can accept errors only for a single leaf vdev.
6245 * Error-injection ranges are separated by clear ranges.
6247 * For example, with 3 leaves, each chunk looks like:
6248 * 0 to 32M: injection range for leaf 0
6249 * 32M to 64M: clear range - no injection allowed
6250 * 64M to 96M: injection range for leaf 1
6251 * 96M to 128M: clear range - no injection allowed
6252 * 128M to 160M: injection range for leaf 2
6253 * 160M to 192M: clear range - no injection allowed
6255 * Each clear range must be large enough such that a
6256 * single block cannot straddle it. This way a block
6257 * can't be a target in two different injection ranges
6258 * (on different leaf vdevs).
6260 offset = ztest_random(fsize / (leaves << bshift)) *
6261 (leaves << bshift) + (leaf << bshift) +
6262 (ztest_random(1ULL << (bshift - 1)) & -8ULL);
6265 * Only allow damage to the labels at one end of the vdev.
6267 * If all labels are damaged, the device will be totally
6268 * inaccessible, which will result in loss of data,
6269 * because we also damage (parts of) the other side of
6272 * Additionally, we will always have both an even and an
6273 * odd label, so that we can handle crashes in the
6274 * middle of vdev_config_sync().
6276 if ((leaf & 1) == 0 && offset < VDEV_LABEL_START_SIZE)
6280 * The two end labels are stored at the "end" of the disk, but
6281 * the end of the disk (vdev_psize) is aligned to
6282 * sizeof (vdev_label_t).
6284 uint64_t psize = P2ALIGN(fsize, sizeof (vdev_label_t));
6285 if ((leaf & 1) == 1 &&
6286 offset + sizeof (bad) > psize - VDEV_LABEL_END_SIZE)
6289 mutex_enter(&ztest_vdev_lock);
6290 if (mirror_save != zs->zs_mirrors) {
6291 mutex_exit(&ztest_vdev_lock);
6296 if (pwrite(fd, &bad, sizeof (bad), offset) != sizeof (bad))
6298 "can't inject bad word at 0x%"PRIx64" in %s",
6301 mutex_exit(&ztest_vdev_lock);
6303 if (ztest_opts.zo_verbose >= 7)
6304 (void) printf("injected bad word into %s,"
6305 " offset 0x%"PRIx64"\n", pathrand, offset);
6310 umem_free(path0, MAXPATHLEN);
6311 umem_free(pathrand, MAXPATHLEN);
6315 * By design ztest will never inject uncorrectable damage in to the pool.
6316 * Issue a scrub, wait for it to complete, and verify there is never any
6317 * persistent damage.
6319 * Only after a full scrub has been completed is it safe to start injecting
6320 * data corruption. See the comment in zfs_fault_inject().
6323 ztest_scrub_impl(spa_t *spa)
6325 int error = spa_scan(spa, POOL_SCAN_SCRUB);
6329 while (dsl_scan_scrubbing(spa_get_dsl(spa)))
6330 txg_wait_synced(spa_get_dsl(spa), 0);
6332 if (spa_approx_errlog_size(spa) > 0)
6335 ztest_pool_scrubbed = B_TRUE;
6344 ztest_scrub(ztest_ds_t *zd, uint64_t id)
6346 (void) zd, (void) id;
6347 spa_t *spa = ztest_spa;
6351 * Scrub in progress by device removal.
6353 if (ztest_device_removal_active)
6357 * Start a scrub, wait a moment, then force a restart.
6359 (void) spa_scan(spa, POOL_SCAN_SCRUB);
6360 (void) poll(NULL, 0, 100);
6362 error = ztest_scrub_impl(spa);
6369 * Change the guid for the pool.
6372 ztest_reguid(ztest_ds_t *zd, uint64_t id)
6374 (void) zd, (void) id;
6375 spa_t *spa = ztest_spa;
6376 uint64_t orig, load;
6379 if (ztest_opts.zo_mmp_test)
6382 orig = spa_guid(spa);
6383 load = spa_load_guid(spa);
6385 (void) pthread_rwlock_wrlock(&ztest_name_lock);
6386 error = spa_change_guid(spa);
6387 (void) pthread_rwlock_unlock(&ztest_name_lock);
6392 if (ztest_opts.zo_verbose >= 4) {
6393 (void) printf("Changed guid old %"PRIu64" -> %"PRIu64"\n",
6394 orig, spa_guid(spa));
6397 VERIFY3U(orig, !=, spa_guid(spa));
6398 VERIFY3U(load, ==, spa_load_guid(spa));
6402 ztest_blake3(ztest_ds_t *zd, uint64_t id)
6404 (void) zd, (void) id;
6405 hrtime_t end = gethrtime() + NANOSEC;
6406 zio_cksum_salt_t salt;
6407 void *salt_ptr = &salt.zcs_bytes;
6408 struct abd *abd_data, *abd_meta;
6414 size = ztest_random_blocksize();
6415 buf = umem_alloc(size, UMEM_NOFAIL);
6416 abd_data = abd_alloc(size, B_FALSE);
6417 abd_meta = abd_alloc(size, B_TRUE);
6419 for (i = 0, ptr = buf; i < size / sizeof (*ptr); i++, ptr++)
6420 *ptr = ztest_random(UINT_MAX);
6421 memset(salt_ptr, 'A', 32);
6423 abd_copy_from_buf_off(abd_data, buf, 0, size);
6424 abd_copy_from_buf_off(abd_meta, buf, 0, size);
6426 while (gethrtime() <= end) {
6427 int run_count = 100;
6428 zio_cksum_t zc_ref1, zc_ref2;
6429 zio_cksum_t zc_res1, zc_res2;
6431 void *ref1 = &zc_ref1;
6432 void *ref2 = &zc_ref2;
6433 void *res1 = &zc_res1;
6434 void *res2 = &zc_res2;
6436 /* BLAKE3_KEY_LEN = 32 */
6437 VERIFY0(blake3_impl_setname("generic"));
6438 templ = abd_checksum_blake3_tmpl_init(&salt);
6439 Blake3_InitKeyed(&ctx, salt_ptr);
6440 Blake3_Update(&ctx, buf, size);
6441 Blake3_Final(&ctx, ref1);
6443 ZIO_CHECKSUM_BSWAP(&zc_ref2);
6444 abd_checksum_blake3_tmpl_free(templ);
6446 VERIFY0(blake3_impl_setname("cycle"));
6447 while (run_count-- > 0) {
6449 /* Test current implementation */
6450 Blake3_InitKeyed(&ctx, salt_ptr);
6451 Blake3_Update(&ctx, buf, size);
6452 Blake3_Final(&ctx, res1);
6454 ZIO_CHECKSUM_BSWAP(&zc_res2);
6456 VERIFY0(memcmp(ref1, res1, 32));
6457 VERIFY0(memcmp(ref2, res2, 32));
6459 /* Test ABD - data */
6460 templ = abd_checksum_blake3_tmpl_init(&salt);
6461 abd_checksum_blake3_native(abd_data, size,
6463 abd_checksum_blake3_byteswap(abd_data, size,
6466 VERIFY0(memcmp(ref1, res1, 32));
6467 VERIFY0(memcmp(ref2, res2, 32));
6469 /* Test ABD - metadata */
6470 abd_checksum_blake3_native(abd_meta, size,
6472 abd_checksum_blake3_byteswap(abd_meta, size,
6474 abd_checksum_blake3_tmpl_free(templ);
6476 VERIFY0(memcmp(ref1, res1, 32));
6477 VERIFY0(memcmp(ref2, res2, 32));
6484 umem_free(buf, size);
6488 ztest_fletcher(ztest_ds_t *zd, uint64_t id)
6490 (void) zd, (void) id;
6491 hrtime_t end = gethrtime() + NANOSEC;
6493 while (gethrtime() <= end) {
6494 int run_count = 100;
6496 struct abd *abd_data, *abd_meta;
6501 zio_cksum_t zc_ref_byteswap;
6503 size = ztest_random_blocksize();
6505 buf = umem_alloc(size, UMEM_NOFAIL);
6506 abd_data = abd_alloc(size, B_FALSE);
6507 abd_meta = abd_alloc(size, B_TRUE);
6509 for (i = 0, ptr = buf; i < size / sizeof (*ptr); i++, ptr++)
6510 *ptr = ztest_random(UINT_MAX);
6512 abd_copy_from_buf_off(abd_data, buf, 0, size);
6513 abd_copy_from_buf_off(abd_meta, buf, 0, size);
6515 VERIFY0(fletcher_4_impl_set("scalar"));
6516 fletcher_4_native(buf, size, NULL, &zc_ref);
6517 fletcher_4_byteswap(buf, size, NULL, &zc_ref_byteswap);
6519 VERIFY0(fletcher_4_impl_set("cycle"));
6520 while (run_count-- > 0) {
6522 zio_cksum_t zc_byteswap;
6524 fletcher_4_byteswap(buf, size, NULL, &zc_byteswap);
6525 fletcher_4_native(buf, size, NULL, &zc);
6527 VERIFY0(memcmp(&zc, &zc_ref, sizeof (zc)));
6528 VERIFY0(memcmp(&zc_byteswap, &zc_ref_byteswap,
6529 sizeof (zc_byteswap)));
6531 /* Test ABD - data */
6532 abd_fletcher_4_byteswap(abd_data, size, NULL,
6534 abd_fletcher_4_native(abd_data, size, NULL, &zc);
6536 VERIFY0(memcmp(&zc, &zc_ref, sizeof (zc)));
6537 VERIFY0(memcmp(&zc_byteswap, &zc_ref_byteswap,
6538 sizeof (zc_byteswap)));
6540 /* Test ABD - metadata */
6541 abd_fletcher_4_byteswap(abd_meta, size, NULL,
6543 abd_fletcher_4_native(abd_meta, size, NULL, &zc);
6545 VERIFY0(memcmp(&zc, &zc_ref, sizeof (zc)));
6546 VERIFY0(memcmp(&zc_byteswap, &zc_ref_byteswap,
6547 sizeof (zc_byteswap)));
6551 umem_free(buf, size);
6558 ztest_fletcher_incr(ztest_ds_t *zd, uint64_t id)
6560 (void) zd, (void) id;
6566 zio_cksum_t zc_ref_bswap;
6568 hrtime_t end = gethrtime() + NANOSEC;
6570 while (gethrtime() <= end) {
6571 int run_count = 100;
6573 size = ztest_random_blocksize();
6574 buf = umem_alloc(size, UMEM_NOFAIL);
6576 for (i = 0, ptr = buf; i < size / sizeof (*ptr); i++, ptr++)
6577 *ptr = ztest_random(UINT_MAX);
6579 VERIFY0(fletcher_4_impl_set("scalar"));
6580 fletcher_4_native(buf, size, NULL, &zc_ref);
6581 fletcher_4_byteswap(buf, size, NULL, &zc_ref_bswap);
6583 VERIFY0(fletcher_4_impl_set("cycle"));
6585 while (run_count-- > 0) {
6587 zio_cksum_t zc_bswap;
6590 ZIO_SET_CHECKSUM(&zc, 0, 0, 0, 0);
6591 ZIO_SET_CHECKSUM(&zc_bswap, 0, 0, 0, 0);
6593 while (pos < size) {
6594 size_t inc = 64 * ztest_random(size / 67);
6595 /* sometimes add few bytes to test non-simd */
6596 if (ztest_random(100) < 10)
6597 inc += P2ALIGN(ztest_random(64),
6600 if (inc > (size - pos))
6603 fletcher_4_incremental_native(buf + pos, inc,
6605 fletcher_4_incremental_byteswap(buf + pos, inc,
6611 VERIFY3U(pos, ==, size);
6613 VERIFY(ZIO_CHECKSUM_EQUAL(zc, zc_ref));
6614 VERIFY(ZIO_CHECKSUM_EQUAL(zc_bswap, zc_ref_bswap));
6617 * verify if incremental on the whole buffer is
6618 * equivalent to non-incremental version
6620 ZIO_SET_CHECKSUM(&zc, 0, 0, 0, 0);
6621 ZIO_SET_CHECKSUM(&zc_bswap, 0, 0, 0, 0);
6623 fletcher_4_incremental_native(buf, size, &zc);
6624 fletcher_4_incremental_byteswap(buf, size, &zc_bswap);
6626 VERIFY(ZIO_CHECKSUM_EQUAL(zc, zc_ref));
6627 VERIFY(ZIO_CHECKSUM_EQUAL(zc_bswap, zc_ref_bswap));
6630 umem_free(buf, size);
6635 ztest_set_global_vars(void)
6637 for (size_t i = 0; i < ztest_opts.zo_gvars_count; i++) {
6638 char *kv = ztest_opts.zo_gvars[i];
6639 VERIFY3U(strlen(kv), <=, ZO_GVARS_MAX_ARGLEN);
6640 VERIFY3U(strlen(kv), >, 0);
6641 int err = set_global_var(kv);
6642 if (ztest_opts.zo_verbose > 0) {
6643 (void) printf("setting global var %s ... %s\n", kv,
6644 err ? "failed" : "ok");
6647 (void) fprintf(stderr,
6648 "failed to set global var '%s'\n", kv);
6656 ztest_global_vars_to_zdb_args(void)
6658 char **args = calloc(2*ztest_opts.zo_gvars_count + 1, sizeof (char *));
6662 for (size_t i = 0; i < ztest_opts.zo_gvars_count; i++) {
6663 *cur++ = (char *)"-o";
6664 *cur++ = ztest_opts.zo_gvars[i];
6666 ASSERT3P(cur, ==, &args[2*ztest_opts.zo_gvars_count]);
6671 /* The end of strings is indicated by a NULL element */
6673 join_strings(char **strings, const char *sep)
6675 size_t totallen = 0;
6676 for (char **sp = strings; *sp != NULL; sp++) {
6677 totallen += strlen(*sp);
6678 totallen += strlen(sep);
6681 ASSERT(totallen >= strlen(sep));
6682 totallen -= strlen(sep);
6685 size_t buflen = totallen + 1;
6686 char *o = umem_alloc(buflen, UMEM_NOFAIL); /* trailing 0 byte */
6688 for (char **sp = strings; *sp != NULL; sp++) {
6690 would = strlcat(o, *sp, buflen);
6691 VERIFY3U(would, <, buflen);
6692 if (*(sp+1) == NULL) {
6695 would = strlcat(o, sep, buflen);
6696 VERIFY3U(would, <, buflen);
6698 ASSERT3S(strlen(o), ==, totallen);
6703 ztest_check_path(char *path)
6706 /* return true on success */
6707 return (!stat(path, &s));
6711 ztest_get_zdb_bin(char *bin, int len)
6715 * Try to use $ZDB and in-tree zdb path. If not successful, just
6716 * let popen to search through PATH.
6718 if ((zdb_path = getenv("ZDB"))) {
6719 strlcpy(bin, zdb_path, len); /* In env */
6720 if (!ztest_check_path(bin)) {
6721 ztest_dump_core = 0;
6722 fatal(B_TRUE, "invalid ZDB '%s'", bin);
6727 VERIFY3P(realpath(getexecname(), bin), !=, NULL);
6728 if (strstr(bin, ".libs/ztest")) {
6729 strstr(bin, ".libs/ztest")[0] = '\0'; /* In-tree */
6731 if (ztest_check_path(bin))
6738 ztest_random_concrete_vdev_leaf(vdev_t *vd)
6743 if (vd->vdev_children == 0)
6746 vdev_t *eligible[vd->vdev_children];
6747 int eligible_idx = 0, i;
6748 for (i = 0; i < vd->vdev_children; i++) {
6749 vdev_t *cvd = vd->vdev_child[i];
6750 if (cvd->vdev_top->vdev_removing)
6752 if (cvd->vdev_children > 0 ||
6753 (vdev_is_concrete(cvd) && !cvd->vdev_detached)) {
6754 eligible[eligible_idx++] = cvd;
6757 VERIFY3S(eligible_idx, >, 0);
6759 uint64_t child_no = ztest_random(eligible_idx);
6760 return (ztest_random_concrete_vdev_leaf(eligible[child_no]));
6764 ztest_initialize(ztest_ds_t *zd, uint64_t id)
6766 (void) zd, (void) id;
6767 spa_t *spa = ztest_spa;
6770 mutex_enter(&ztest_vdev_lock);
6772 spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
6774 /* Random leaf vdev */
6775 vdev_t *rand_vd = ztest_random_concrete_vdev_leaf(spa->spa_root_vdev);
6776 if (rand_vd == NULL) {
6777 spa_config_exit(spa, SCL_VDEV, FTAG);
6778 mutex_exit(&ztest_vdev_lock);
6783 * The random vdev we've selected may change as soon as we
6784 * drop the spa_config_lock. We create local copies of things
6785 * we're interested in.
6787 uint64_t guid = rand_vd->vdev_guid;
6788 char *path = strdup(rand_vd->vdev_path);
6789 boolean_t active = rand_vd->vdev_initialize_thread != NULL;
6791 zfs_dbgmsg("vd %px, guid %llu", rand_vd, (u_longlong_t)guid);
6792 spa_config_exit(spa, SCL_VDEV, FTAG);
6794 uint64_t cmd = ztest_random(POOL_INITIALIZE_FUNCS);
6796 nvlist_t *vdev_guids = fnvlist_alloc();
6797 nvlist_t *vdev_errlist = fnvlist_alloc();
6798 fnvlist_add_uint64(vdev_guids, path, guid);
6799 error = spa_vdev_initialize(spa, vdev_guids, cmd, vdev_errlist);
6800 fnvlist_free(vdev_guids);
6801 fnvlist_free(vdev_errlist);
6804 case POOL_INITIALIZE_CANCEL:
6805 if (ztest_opts.zo_verbose >= 4) {
6806 (void) printf("Cancel initialize %s", path);
6808 (void) printf(" failed (no initialize active)");
6809 (void) printf("\n");
6812 case POOL_INITIALIZE_START:
6813 if (ztest_opts.zo_verbose >= 4) {
6814 (void) printf("Start initialize %s", path);
6815 if (active && error == 0)
6816 (void) printf(" failed (already active)");
6817 else if (error != 0)
6818 (void) printf(" failed (error %d)", error);
6819 (void) printf("\n");
6822 case POOL_INITIALIZE_SUSPEND:
6823 if (ztest_opts.zo_verbose >= 4) {
6824 (void) printf("Suspend initialize %s", path);
6826 (void) printf(" failed (no initialize active)");
6827 (void) printf("\n");
6832 mutex_exit(&ztest_vdev_lock);
6836 ztest_trim(ztest_ds_t *zd, uint64_t id)
6838 (void) zd, (void) id;
6839 spa_t *spa = ztest_spa;
6842 mutex_enter(&ztest_vdev_lock);
6844 spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
6846 /* Random leaf vdev */
6847 vdev_t *rand_vd = ztest_random_concrete_vdev_leaf(spa->spa_root_vdev);
6848 if (rand_vd == NULL) {
6849 spa_config_exit(spa, SCL_VDEV, FTAG);
6850 mutex_exit(&ztest_vdev_lock);
6855 * The random vdev we've selected may change as soon as we
6856 * drop the spa_config_lock. We create local copies of things
6857 * we're interested in.
6859 uint64_t guid = rand_vd->vdev_guid;
6860 char *path = strdup(rand_vd->vdev_path);
6861 boolean_t active = rand_vd->vdev_trim_thread != NULL;
6863 zfs_dbgmsg("vd %p, guid %llu", rand_vd, (u_longlong_t)guid);
6864 spa_config_exit(spa, SCL_VDEV, FTAG);
6866 uint64_t cmd = ztest_random(POOL_TRIM_FUNCS);
6867 uint64_t rate = 1 << ztest_random(30);
6868 boolean_t partial = (ztest_random(5) > 0);
6869 boolean_t secure = (ztest_random(5) > 0);
6871 nvlist_t *vdev_guids = fnvlist_alloc();
6872 nvlist_t *vdev_errlist = fnvlist_alloc();
6873 fnvlist_add_uint64(vdev_guids, path, guid);
6874 error = spa_vdev_trim(spa, vdev_guids, cmd, rate, partial,
6875 secure, vdev_errlist);
6876 fnvlist_free(vdev_guids);
6877 fnvlist_free(vdev_errlist);
6880 case POOL_TRIM_CANCEL:
6881 if (ztest_opts.zo_verbose >= 4) {
6882 (void) printf("Cancel TRIM %s", path);
6884 (void) printf(" failed (no TRIM active)");
6885 (void) printf("\n");
6888 case POOL_TRIM_START:
6889 if (ztest_opts.zo_verbose >= 4) {
6890 (void) printf("Start TRIM %s", path);
6891 if (active && error == 0)
6892 (void) printf(" failed (already active)");
6893 else if (error != 0)
6894 (void) printf(" failed (error %d)", error);
6895 (void) printf("\n");
6898 case POOL_TRIM_SUSPEND:
6899 if (ztest_opts.zo_verbose >= 4) {
6900 (void) printf("Suspend TRIM %s", path);
6902 (void) printf(" failed (no TRIM active)");
6903 (void) printf("\n");
6908 mutex_exit(&ztest_vdev_lock);
6912 * Verify pool integrity by running zdb.
6915 ztest_run_zdb(const char *pool)
6921 const int len = MAXPATHLEN + MAXNAMELEN + 20;
6924 bin = umem_alloc(len, UMEM_NOFAIL);
6925 zdb = umem_alloc(len, UMEM_NOFAIL);
6926 zbuf = umem_alloc(1024, UMEM_NOFAIL);
6928 ztest_get_zdb_bin(bin, len);
6930 char **set_gvars_args = ztest_global_vars_to_zdb_args();
6931 if (set_gvars_args == NULL) {
6932 fatal(B_FALSE, "Failed to allocate memory in "
6933 "ztest_global_vars_to_zdb_args(). Cannot run zdb.\n");
6935 char *set_gvars_args_joined = join_strings(set_gvars_args, " ");
6936 free(set_gvars_args);
6938 size_t would = snprintf(zdb, len,
6939 "%s -bcc%s%s -G -d -Y -e -y %s -p %s %s",
6941 ztest_opts.zo_verbose >= 3 ? "s" : "",
6942 ztest_opts.zo_verbose >= 4 ? "v" : "",
6943 set_gvars_args_joined,
6946 ASSERT3U(would, <, len);
6948 umem_free(set_gvars_args_joined, strlen(set_gvars_args_joined) + 1);
6950 if (ztest_opts.zo_verbose >= 5)
6951 (void) printf("Executing %s\n", zdb);
6953 fp = popen(zdb, "r");
6955 while (fgets(zbuf, 1024, fp) != NULL)
6956 if (ztest_opts.zo_verbose >= 3)
6957 (void) printf("%s", zbuf);
6959 status = pclose(fp);
6964 ztest_dump_core = 0;
6965 if (WIFEXITED(status))
6966 fatal(B_FALSE, "'%s' exit code %d", zdb, WEXITSTATUS(status));
6968 fatal(B_FALSE, "'%s' died with signal %d",
6969 zdb, WTERMSIG(status));
6971 umem_free(bin, len);
6972 umem_free(zdb, len);
6973 umem_free(zbuf, 1024);
6977 ztest_walk_pool_directory(const char *header)
6981 if (ztest_opts.zo_verbose >= 6)
6982 (void) puts(header);
6984 mutex_enter(&spa_namespace_lock);
6985 while ((spa = spa_next(spa)) != NULL)
6986 if (ztest_opts.zo_verbose >= 6)
6987 (void) printf("\t%s\n", spa_name(spa));
6988 mutex_exit(&spa_namespace_lock);
6992 ztest_spa_import_export(char *oldname, char *newname)
6994 nvlist_t *config, *newconfig;
6999 if (ztest_opts.zo_verbose >= 4) {
7000 (void) printf("import/export: old = %s, new = %s\n",
7005 * Clean up from previous runs.
7007 (void) spa_destroy(newname);
7010 * Get the pool's configuration and guid.
7012 VERIFY0(spa_open(oldname, &spa, FTAG));
7015 * Kick off a scrub to tickle scrub/export races.
7017 if (ztest_random(2) == 0)
7018 (void) spa_scan(spa, POOL_SCAN_SCRUB);
7020 pool_guid = spa_guid(spa);
7021 spa_close(spa, FTAG);
7023 ztest_walk_pool_directory("pools before export");
7028 VERIFY0(spa_export(oldname, &config, B_FALSE, B_FALSE));
7030 ztest_walk_pool_directory("pools after export");
7035 newconfig = spa_tryimport(config);
7036 ASSERT3P(newconfig, !=, NULL);
7037 fnvlist_free(newconfig);
7040 * Import it under the new name.
7042 error = spa_import(newname, config, NULL, 0);
7044 dump_nvlist(config, 0);
7045 fatal(B_FALSE, "couldn't import pool %s as %s: error %u",
7046 oldname, newname, error);
7049 ztest_walk_pool_directory("pools after import");
7052 * Try to import it again -- should fail with EEXIST.
7054 VERIFY3U(EEXIST, ==, spa_import(newname, config, NULL, 0));
7057 * Try to import it under a different name -- should fail with EEXIST.
7059 VERIFY3U(EEXIST, ==, spa_import(oldname, config, NULL, 0));
7062 * Verify that the pool is no longer visible under the old name.
7064 VERIFY3U(ENOENT, ==, spa_open(oldname, &spa, FTAG));
7067 * Verify that we can open and close the pool using the new name.
7069 VERIFY0(spa_open(newname, &spa, FTAG));
7070 ASSERT3U(pool_guid, ==, spa_guid(spa));
7071 spa_close(spa, FTAG);
7073 fnvlist_free(config);
7077 ztest_resume(spa_t *spa)
7079 if (spa_suspended(spa) && ztest_opts.zo_verbose >= 6)
7080 (void) printf("resuming from suspended state\n");
7081 spa_vdev_state_enter(spa, SCL_NONE);
7082 vdev_clear(spa, NULL);
7083 (void) spa_vdev_state_exit(spa, NULL, 0);
7084 (void) zio_resume(spa);
7087 static __attribute__((noreturn)) void
7088 ztest_resume_thread(void *arg)
7092 while (!ztest_exiting) {
7093 if (spa_suspended(spa))
7095 (void) poll(NULL, 0, 100);
7098 * Periodically change the zfs_compressed_arc_enabled setting.
7100 if (ztest_random(10) == 0)
7101 zfs_compressed_arc_enabled = ztest_random(2);
7104 * Periodically change the zfs_abd_scatter_enabled setting.
7106 if (ztest_random(10) == 0)
7107 zfs_abd_scatter_enabled = ztest_random(2);
7113 static __attribute__((noreturn)) void
7114 ztest_deadman_thread(void *arg)
7116 ztest_shared_t *zs = arg;
7117 spa_t *spa = ztest_spa;
7118 hrtime_t delay, overdue, last_run = gethrtime();
7120 delay = (zs->zs_thread_stop - zs->zs_thread_start) +
7121 MSEC2NSEC(zfs_deadman_synctime_ms);
7123 while (!ztest_exiting) {
7125 * Wait for the delay timer while checking occasionally
7126 * if we should stop.
7128 if (gethrtime() < last_run + delay) {
7129 (void) poll(NULL, 0, 1000);
7134 * If the pool is suspended then fail immediately. Otherwise,
7135 * check to see if the pool is making any progress. If
7136 * vdev_deadman() discovers that there hasn't been any recent
7137 * I/Os then it will end up aborting the tests.
7139 if (spa_suspended(spa) || spa->spa_root_vdev == NULL) {
7141 "aborting test after %llu seconds because "
7142 "pool has transitioned to a suspended state.",
7143 (u_longlong_t)zfs_deadman_synctime_ms / 1000);
7145 vdev_deadman(spa->spa_root_vdev, FTAG);
7148 * If the process doesn't complete within a grace period of
7149 * zfs_deadman_synctime_ms over the expected finish time,
7150 * then it may be hung and is terminated.
7152 overdue = zs->zs_proc_stop + MSEC2NSEC(zfs_deadman_synctime_ms);
7153 if (gethrtime() > overdue) {
7155 "aborting test after %llu seconds because "
7156 "the process is overdue for termination.",
7157 (gethrtime() - zs->zs_proc_start) / NANOSEC);
7160 (void) printf("ztest has been running for %lld seconds\n",
7161 (gethrtime() - zs->zs_proc_start) / NANOSEC);
7163 last_run = gethrtime();
7164 delay = MSEC2NSEC(zfs_deadman_checktime_ms);
7171 ztest_execute(int test, ztest_info_t *zi, uint64_t id)
7173 ztest_ds_t *zd = &ztest_ds[id % ztest_opts.zo_datasets];
7174 ztest_shared_callstate_t *zc = ZTEST_GET_SHARED_CALLSTATE(test);
7175 hrtime_t functime = gethrtime();
7178 for (i = 0; i < zi->zi_iters; i++)
7179 zi->zi_func(zd, id);
7181 functime = gethrtime() - functime;
7183 atomic_add_64(&zc->zc_count, 1);
7184 atomic_add_64(&zc->zc_time, functime);
7186 if (ztest_opts.zo_verbose >= 4)
7187 (void) printf("%6.2f sec in %s\n",
7188 (double)functime / NANOSEC, zi->zi_funcname);
7191 static __attribute__((noreturn)) void
7192 ztest_thread(void *arg)
7195 uint64_t id = (uintptr_t)arg;
7196 ztest_shared_t *zs = ztest_shared;
7200 ztest_shared_callstate_t *zc;
7202 while ((now = gethrtime()) < zs->zs_thread_stop) {
7204 * See if it's time to force a crash.
7206 if (now > zs->zs_thread_kill)
7210 * If we're getting ENOSPC with some regularity, stop.
7212 if (zs->zs_enospc_count > 10)
7216 * Pick a random function to execute.
7218 rand = ztest_random(ZTEST_FUNCS);
7219 zi = &ztest_info[rand];
7220 zc = ZTEST_GET_SHARED_CALLSTATE(rand);
7221 call_next = zc->zc_next;
7223 if (now >= call_next &&
7224 atomic_cas_64(&zc->zc_next, call_next, call_next +
7225 ztest_random(2 * zi->zi_interval[0] + 1)) == call_next) {
7226 ztest_execute(rand, zi, id);
7234 ztest_dataset_name(char *dsname, const char *pool, int d)
7236 (void) snprintf(dsname, ZFS_MAX_DATASET_NAME_LEN, "%s/ds_%d", pool, d);
7240 ztest_dataset_destroy(int d)
7242 char name[ZFS_MAX_DATASET_NAME_LEN];
7245 ztest_dataset_name(name, ztest_opts.zo_pool, d);
7247 if (ztest_opts.zo_verbose >= 3)
7248 (void) printf("Destroying %s to free up space\n", name);
7251 * Cleanup any non-standard clones and snapshots. In general,
7252 * ztest thread t operates on dataset (t % zopt_datasets),
7253 * so there may be more than one thing to clean up.
7255 for (t = d; t < ztest_opts.zo_threads;
7256 t += ztest_opts.zo_datasets)
7257 ztest_dsl_dataset_cleanup(name, t);
7259 (void) dmu_objset_find(name, ztest_objset_destroy_cb, NULL,
7260 DS_FIND_SNAPSHOTS | DS_FIND_CHILDREN);
7264 ztest_dataset_dirobj_verify(ztest_ds_t *zd)
7266 uint64_t usedobjs, dirobjs, scratch;
7269 * ZTEST_DIROBJ is the object directory for the entire dataset.
7270 * Therefore, the number of objects in use should equal the
7271 * number of ZTEST_DIROBJ entries, +1 for ZTEST_DIROBJ itself.
7272 * If not, we have an object leak.
7274 * Note that we can only check this in ztest_dataset_open(),
7275 * when the open-context and syncing-context values agree.
7276 * That's because zap_count() returns the open-context value,
7277 * while dmu_objset_space() returns the rootbp fill count.
7279 VERIFY0(zap_count(zd->zd_os, ZTEST_DIROBJ, &dirobjs));
7280 dmu_objset_space(zd->zd_os, &scratch, &scratch, &usedobjs, &scratch);
7281 ASSERT3U(dirobjs + 1, ==, usedobjs);
7285 ztest_dataset_open(int d)
7287 ztest_ds_t *zd = &ztest_ds[d];
7288 uint64_t committed_seq = ZTEST_GET_SHARED_DS(d)->zd_seq;
7291 char name[ZFS_MAX_DATASET_NAME_LEN];
7294 ztest_dataset_name(name, ztest_opts.zo_pool, d);
7296 (void) pthread_rwlock_rdlock(&ztest_name_lock);
7298 error = ztest_dataset_create(name);
7299 if (error == ENOSPC) {
7300 (void) pthread_rwlock_unlock(&ztest_name_lock);
7301 ztest_record_enospc(FTAG);
7304 ASSERT(error == 0 || error == EEXIST);
7306 VERIFY0(ztest_dmu_objset_own(name, DMU_OST_OTHER, B_FALSE,
7308 (void) pthread_rwlock_unlock(&ztest_name_lock);
7310 ztest_zd_init(zd, ZTEST_GET_SHARED_DS(d), os);
7312 zilog = zd->zd_zilog;
7314 if (zilog->zl_header->zh_claim_lr_seq != 0 &&
7315 zilog->zl_header->zh_claim_lr_seq < committed_seq)
7316 fatal(B_FALSE, "missing log records: "
7317 "claimed %"PRIu64" < committed %"PRIu64"",
7318 zilog->zl_header->zh_claim_lr_seq, committed_seq);
7320 ztest_dataset_dirobj_verify(zd);
7322 zil_replay(os, zd, ztest_replay_vector);
7324 ztest_dataset_dirobj_verify(zd);
7326 if (ztest_opts.zo_verbose >= 6)
7327 (void) printf("%s replay %"PRIu64" blocks, "
7328 "%"PRIu64" records, seq %"PRIu64"\n",
7330 zilog->zl_parse_blk_count,
7331 zilog->zl_parse_lr_count,
7332 zilog->zl_replaying_seq);
7334 zilog = zil_open(os, ztest_get_data, NULL);
7336 if (zilog->zl_replaying_seq != 0 &&
7337 zilog->zl_replaying_seq < committed_seq)
7338 fatal(B_FALSE, "missing log records: "
7339 "replayed %"PRIu64" < committed %"PRIu64"",
7340 zilog->zl_replaying_seq, committed_seq);
7346 ztest_dataset_close(int d)
7348 ztest_ds_t *zd = &ztest_ds[d];
7350 zil_close(zd->zd_zilog);
7351 dmu_objset_disown(zd->zd_os, B_TRUE, zd);
7357 ztest_replay_zil_cb(const char *name, void *arg)
7363 VERIFY0(ztest_dmu_objset_own(name, DMU_OST_ANY, B_TRUE,
7364 B_TRUE, FTAG, &os));
7366 zdtmp = umem_alloc(sizeof (ztest_ds_t), UMEM_NOFAIL);
7368 ztest_zd_init(zdtmp, NULL, os);
7369 zil_replay(os, zdtmp, ztest_replay_vector);
7370 ztest_zd_fini(zdtmp);
7372 if (dmu_objset_zil(os)->zl_parse_lr_count != 0 &&
7373 ztest_opts.zo_verbose >= 6) {
7374 zilog_t *zilog = dmu_objset_zil(os);
7376 (void) printf("%s replay %"PRIu64" blocks, "
7377 "%"PRIu64" records, seq %"PRIu64"\n",
7379 zilog->zl_parse_blk_count,
7380 zilog->zl_parse_lr_count,
7381 zilog->zl_replaying_seq);
7384 umem_free(zdtmp, sizeof (ztest_ds_t));
7386 dmu_objset_disown(os, B_TRUE, FTAG);
7393 ztest_ds_t *zd = &ztest_ds[0];
7397 if (ztest_opts.zo_verbose >= 3)
7398 (void) printf("testing spa_freeze()...\n");
7400 kernel_init(SPA_MODE_READ | SPA_MODE_WRITE);
7401 VERIFY0(spa_open(ztest_opts.zo_pool, &spa, FTAG));
7402 VERIFY0(ztest_dataset_open(0));
7406 * Force the first log block to be transactionally allocated.
7407 * We have to do this before we freeze the pool -- otherwise
7408 * the log chain won't be anchored.
7410 while (BP_IS_HOLE(&zd->zd_zilog->zl_header->zh_log)) {
7411 ztest_dmu_object_alloc_free(zd, 0);
7412 zil_commit(zd->zd_zilog, 0);
7415 txg_wait_synced(spa_get_dsl(spa), 0);
7418 * Freeze the pool. This stops spa_sync() from doing anything,
7419 * so that the only way to record changes from now on is the ZIL.
7424 * Because it is hard to predict how much space a write will actually
7425 * require beforehand, we leave ourselves some fudge space to write over
7428 uint64_t capacity = metaslab_class_get_space(spa_normal_class(spa)) / 2;
7431 * Run tests that generate log records but don't alter the pool config
7432 * or depend on DSL sync tasks (snapshots, objset create/destroy, etc).
7433 * We do a txg_wait_synced() after each iteration to force the txg
7434 * to increase well beyond the last synced value in the uberblock.
7435 * The ZIL should be OK with that.
7437 * Run a random number of times less than zo_maxloops and ensure we do
7438 * not run out of space on the pool.
7440 while (ztest_random(10) != 0 &&
7441 numloops++ < ztest_opts.zo_maxloops &&
7442 metaslab_class_get_alloc(spa_normal_class(spa)) < capacity) {
7444 ztest_od_init(&od, 0, FTAG, 0, DMU_OT_UINT64_OTHER, 0, 0, 0);
7445 VERIFY0(ztest_object_init(zd, &od, sizeof (od), B_FALSE));
7446 ztest_io(zd, od.od_object,
7447 ztest_random(ZTEST_RANGE_LOCKS) << SPA_MAXBLOCKSHIFT);
7448 txg_wait_synced(spa_get_dsl(spa), 0);
7452 * Commit all of the changes we just generated.
7454 zil_commit(zd->zd_zilog, 0);
7455 txg_wait_synced(spa_get_dsl(spa), 0);
7458 * Close our dataset and close the pool.
7460 ztest_dataset_close(0);
7461 spa_close(spa, FTAG);
7465 * Open and close the pool and dataset to induce log replay.
7467 kernel_init(SPA_MODE_READ | SPA_MODE_WRITE);
7468 VERIFY0(spa_open(ztest_opts.zo_pool, &spa, FTAG));
7469 ASSERT3U(spa_freeze_txg(spa), ==, UINT64_MAX);
7470 VERIFY0(ztest_dataset_open(0));
7472 txg_wait_synced(spa_get_dsl(spa), 0);
7473 ztest_dataset_close(0);
7474 ztest_reguid(NULL, 0);
7476 spa_close(spa, FTAG);
7481 ztest_import_impl(void)
7483 importargs_t args = { 0 };
7484 nvlist_t *cfg = NULL;
7486 char *searchdirs[nsearch];
7487 int flags = ZFS_IMPORT_MISSING_LOG;
7489 searchdirs[0] = ztest_opts.zo_dir;
7490 args.paths = nsearch;
7491 args.path = searchdirs;
7492 args.can_be_active = B_FALSE;
7494 libpc_handle_t lpch = {
7495 .lpc_lib_handle = NULL,
7496 .lpc_ops = &libzpool_config_ops,
7497 .lpc_printerr = B_TRUE
7499 VERIFY0(zpool_find_config(&lpch, ztest_opts.zo_pool, &cfg, &args));
7500 VERIFY0(spa_import(ztest_opts.zo_pool, cfg, NULL, flags));
7505 * Import a storage pool with the given name.
7508 ztest_import(ztest_shared_t *zs)
7512 mutex_init(&ztest_vdev_lock, NULL, MUTEX_DEFAULT, NULL);
7513 mutex_init(&ztest_checkpoint_lock, NULL, MUTEX_DEFAULT, NULL);
7514 VERIFY0(pthread_rwlock_init(&ztest_name_lock, NULL));
7516 kernel_init(SPA_MODE_READ | SPA_MODE_WRITE);
7518 ztest_import_impl();
7520 VERIFY0(spa_open(ztest_opts.zo_pool, &spa, FTAG));
7521 zs->zs_metaslab_sz =
7522 1ULL << spa->spa_root_vdev->vdev_child[0]->vdev_ms_shift;
7523 spa_close(spa, FTAG);
7527 if (!ztest_opts.zo_mmp_test) {
7528 ztest_run_zdb(ztest_opts.zo_pool);
7530 ztest_run_zdb(ztest_opts.zo_pool);
7533 (void) pthread_rwlock_destroy(&ztest_name_lock);
7534 mutex_destroy(&ztest_vdev_lock);
7535 mutex_destroy(&ztest_checkpoint_lock);
7539 * Kick off threads to run tests on all datasets in parallel.
7542 ztest_run(ztest_shared_t *zs)
7546 kthread_t *resume_thread, *deadman_thread;
7547 kthread_t **run_threads;
7552 ztest_exiting = B_FALSE;
7555 * Initialize parent/child shared state.
7557 mutex_init(&ztest_vdev_lock, NULL, MUTEX_DEFAULT, NULL);
7558 mutex_init(&ztest_checkpoint_lock, NULL, MUTEX_DEFAULT, NULL);
7559 VERIFY0(pthread_rwlock_init(&ztest_name_lock, NULL));
7561 zs->zs_thread_start = gethrtime();
7562 zs->zs_thread_stop =
7563 zs->zs_thread_start + ztest_opts.zo_passtime * NANOSEC;
7564 zs->zs_thread_stop = MIN(zs->zs_thread_stop, zs->zs_proc_stop);
7565 zs->zs_thread_kill = zs->zs_thread_stop;
7566 if (ztest_random(100) < ztest_opts.zo_killrate) {
7567 zs->zs_thread_kill -=
7568 ztest_random(ztest_opts.zo_passtime * NANOSEC);
7571 mutex_init(&zcl.zcl_callbacks_lock, NULL, MUTEX_DEFAULT, NULL);
7573 list_create(&zcl.zcl_callbacks, sizeof (ztest_cb_data_t),
7574 offsetof(ztest_cb_data_t, zcd_node));
7577 * Open our pool. It may need to be imported first depending on
7578 * what tests were running when the previous pass was terminated.
7580 kernel_init(SPA_MODE_READ | SPA_MODE_WRITE);
7581 error = spa_open(ztest_opts.zo_pool, &spa, FTAG);
7583 VERIFY3S(error, ==, ENOENT);
7584 ztest_import_impl();
7585 VERIFY0(spa_open(ztest_opts.zo_pool, &spa, FTAG));
7586 zs->zs_metaslab_sz =
7587 1ULL << spa->spa_root_vdev->vdev_child[0]->vdev_ms_shift;
7590 metaslab_preload_limit = ztest_random(20) + 1;
7593 VERIFY0(vdev_raidz_impl_set("cycle"));
7595 dmu_objset_stats_t dds;
7596 VERIFY0(ztest_dmu_objset_own(ztest_opts.zo_pool,
7597 DMU_OST_ANY, B_TRUE, B_TRUE, FTAG, &os));
7598 dsl_pool_config_enter(dmu_objset_pool(os), FTAG);
7599 dmu_objset_fast_stat(os, &dds);
7600 dsl_pool_config_exit(dmu_objset_pool(os), FTAG);
7601 zs->zs_guid = dds.dds_guid;
7602 dmu_objset_disown(os, B_TRUE, FTAG);
7605 * Create a thread to periodically resume suspended I/O.
7607 resume_thread = thread_create(NULL, 0, ztest_resume_thread,
7608 spa, 0, NULL, TS_RUN | TS_JOINABLE, defclsyspri);
7611 * Create a deadman thread and set to panic if we hang.
7613 deadman_thread = thread_create(NULL, 0, ztest_deadman_thread,
7614 zs, 0, NULL, TS_RUN | TS_JOINABLE, defclsyspri);
7616 spa->spa_deadman_failmode = ZIO_FAILURE_MODE_PANIC;
7619 * Verify that we can safely inquire about any object,
7620 * whether it's allocated or not. To make it interesting,
7621 * we probe a 5-wide window around each power of two.
7622 * This hits all edge cases, including zero and the max.
7624 for (t = 0; t < 64; t++) {
7625 for (d = -5; d <= 5; d++) {
7626 error = dmu_object_info(spa->spa_meta_objset,
7627 (1ULL << t) + d, NULL);
7628 ASSERT(error == 0 || error == ENOENT ||
7634 * If we got any ENOSPC errors on the previous run, destroy something.
7636 if (zs->zs_enospc_count != 0) {
7637 int d = ztest_random(ztest_opts.zo_datasets);
7638 ztest_dataset_destroy(d);
7640 zs->zs_enospc_count = 0;
7643 * If we were in the middle of ztest_device_removal() and were killed
7644 * we need to ensure the removal and scrub complete before running
7645 * any tests that check ztest_device_removal_active. The removal will
7646 * be restarted automatically when the spa is opened, but we need to
7647 * initiate the scrub manually if it is not already in progress. Note
7648 * that we always run the scrub whenever an indirect vdev exists
7649 * because we have no way of knowing for sure if ztest_device_removal()
7650 * fully completed its scrub before the pool was reimported.
7652 if (spa->spa_removing_phys.sr_state == DSS_SCANNING ||
7653 spa->spa_removing_phys.sr_prev_indirect_vdev != -1) {
7654 while (spa->spa_removing_phys.sr_state == DSS_SCANNING)
7655 txg_wait_synced(spa_get_dsl(spa), 0);
7657 error = ztest_scrub_impl(spa);
7663 run_threads = umem_zalloc(ztest_opts.zo_threads * sizeof (kthread_t *),
7666 if (ztest_opts.zo_verbose >= 4)
7667 (void) printf("starting main threads...\n");
7670 * Replay all logs of all datasets in the pool. This is primarily for
7671 * temporary datasets which wouldn't otherwise get replayed, which
7672 * can trigger failures when attempting to offline a SLOG in
7673 * ztest_fault_inject().
7675 (void) dmu_objset_find(ztest_opts.zo_pool, ztest_replay_zil_cb,
7676 NULL, DS_FIND_CHILDREN);
7679 * Kick off all the tests that run in parallel.
7681 for (t = 0; t < ztest_opts.zo_threads; t++) {
7682 if (t < ztest_opts.zo_datasets && ztest_dataset_open(t) != 0) {
7683 umem_free(run_threads, ztest_opts.zo_threads *
7684 sizeof (kthread_t *));
7688 run_threads[t] = thread_create(NULL, 0, ztest_thread,
7689 (void *)(uintptr_t)t, 0, NULL, TS_RUN | TS_JOINABLE,
7694 * Wait for all of the tests to complete.
7696 for (t = 0; t < ztest_opts.zo_threads; t++)
7697 VERIFY0(thread_join(run_threads[t]));
7700 * Close all datasets. This must be done after all the threads
7701 * are joined so we can be sure none of the datasets are in-use
7702 * by any of the threads.
7704 for (t = 0; t < ztest_opts.zo_threads; t++) {
7705 if (t < ztest_opts.zo_datasets)
7706 ztest_dataset_close(t);
7709 txg_wait_synced(spa_get_dsl(spa), 0);
7711 zs->zs_alloc = metaslab_class_get_alloc(spa_normal_class(spa));
7712 zs->zs_space = metaslab_class_get_space(spa_normal_class(spa));
7714 umem_free(run_threads, ztest_opts.zo_threads * sizeof (kthread_t *));
7716 /* Kill the resume and deadman threads */
7717 ztest_exiting = B_TRUE;
7718 VERIFY0(thread_join(resume_thread));
7719 VERIFY0(thread_join(deadman_thread));
7723 * Right before closing the pool, kick off a bunch of async I/O;
7724 * spa_close() should wait for it to complete.
7726 for (object = 1; object < 50; object++) {
7727 dmu_prefetch(spa->spa_meta_objset, object, 0, 0, 1ULL << 20,
7728 ZIO_PRIORITY_SYNC_READ);
7731 /* Verify that at least one commit cb was called in a timely fashion */
7732 if (zc_cb_counter >= ZTEST_COMMIT_CB_MIN_REG)
7733 VERIFY0(zc_min_txg_delay);
7735 spa_close(spa, FTAG);
7738 * Verify that we can loop over all pools.
7740 mutex_enter(&spa_namespace_lock);
7741 for (spa = spa_next(NULL); spa != NULL; spa = spa_next(spa))
7742 if (ztest_opts.zo_verbose > 3)
7743 (void) printf("spa_next: found %s\n", spa_name(spa));
7744 mutex_exit(&spa_namespace_lock);
7747 * Verify that we can export the pool and reimport it under a
7750 if ((ztest_random(2) == 0) && !ztest_opts.zo_mmp_test) {
7751 char name[ZFS_MAX_DATASET_NAME_LEN];
7752 (void) snprintf(name, sizeof (name), "%s_import",
7753 ztest_opts.zo_pool);
7754 ztest_spa_import_export(ztest_opts.zo_pool, name);
7755 ztest_spa_import_export(name, ztest_opts.zo_pool);
7760 list_destroy(&zcl.zcl_callbacks);
7761 mutex_destroy(&zcl.zcl_callbacks_lock);
7762 (void) pthread_rwlock_destroy(&ztest_name_lock);
7763 mutex_destroy(&ztest_vdev_lock);
7764 mutex_destroy(&ztest_checkpoint_lock);
7768 print_time(hrtime_t t, char *timebuf)
7770 hrtime_t s = t / NANOSEC;
7771 hrtime_t m = s / 60;
7772 hrtime_t h = m / 60;
7773 hrtime_t d = h / 24;
7782 (void) sprintf(timebuf,
7783 "%llud%02lluh%02llum%02llus", d, h, m, s);
7785 (void) sprintf(timebuf, "%lluh%02llum%02llus", h, m, s);
7787 (void) sprintf(timebuf, "%llum%02llus", m, s);
7789 (void) sprintf(timebuf, "%llus", s);
7793 make_random_props(void)
7797 props = fnvlist_alloc();
7799 if (ztest_random(2) == 0)
7802 fnvlist_add_uint64(props,
7803 zpool_prop_to_name(ZPOOL_PROP_AUTOREPLACE), 1);
7809 * Create a storage pool with the given name and initial vdev size.
7810 * Then test spa_freeze() functionality.
7813 ztest_init(ztest_shared_t *zs)
7816 nvlist_t *nvroot, *props;
7819 mutex_init(&ztest_vdev_lock, NULL, MUTEX_DEFAULT, NULL);
7820 mutex_init(&ztest_checkpoint_lock, NULL, MUTEX_DEFAULT, NULL);
7821 VERIFY0(pthread_rwlock_init(&ztest_name_lock, NULL));
7823 kernel_init(SPA_MODE_READ | SPA_MODE_WRITE);
7826 * Create the storage pool.
7828 (void) spa_destroy(ztest_opts.zo_pool);
7829 ztest_shared->zs_vdev_next_leaf = 0;
7831 zs->zs_mirrors = ztest_opts.zo_mirrors;
7832 nvroot = make_vdev_root(NULL, NULL, NULL, ztest_opts.zo_vdev_size, 0,
7833 NULL, ztest_opts.zo_raid_children, zs->zs_mirrors, 1);
7834 props = make_random_props();
7837 * We don't expect the pool to suspend unless maxfaults == 0,
7838 * in which case ztest_fault_inject() temporarily takes away
7839 * the only valid replica.
7841 fnvlist_add_uint64(props,
7842 zpool_prop_to_name(ZPOOL_PROP_FAILUREMODE),
7843 MAXFAULTS(zs) ? ZIO_FAILURE_MODE_PANIC : ZIO_FAILURE_MODE_WAIT);
7845 for (i = 0; i < SPA_FEATURES; i++) {
7848 if (!spa_feature_table[i].fi_zfs_mod_supported)
7852 * 75% chance of using the log space map feature. We want ztest
7853 * to exercise both the code paths that use the log space map
7854 * feature and the ones that don't.
7856 if (i == SPA_FEATURE_LOG_SPACEMAP && ztest_random(4) == 0)
7859 VERIFY3S(-1, !=, asprintf(&buf, "feature@%s",
7860 spa_feature_table[i].fi_uname));
7861 fnvlist_add_uint64(props, buf, 0);
7865 VERIFY0(spa_create(ztest_opts.zo_pool, nvroot, props, NULL, NULL));
7866 fnvlist_free(nvroot);
7867 fnvlist_free(props);
7869 VERIFY0(spa_open(ztest_opts.zo_pool, &spa, FTAG));
7870 zs->zs_metaslab_sz =
7871 1ULL << spa->spa_root_vdev->vdev_child[0]->vdev_ms_shift;
7872 spa_close(spa, FTAG);
7876 if (!ztest_opts.zo_mmp_test) {
7877 ztest_run_zdb(ztest_opts.zo_pool);
7879 ztest_run_zdb(ztest_opts.zo_pool);
7882 (void) pthread_rwlock_destroy(&ztest_name_lock);
7883 mutex_destroy(&ztest_vdev_lock);
7884 mutex_destroy(&ztest_checkpoint_lock);
7890 static char ztest_name_data[] = "/tmp/ztest.data.XXXXXX";
7892 ztest_fd_data = mkstemp(ztest_name_data);
7893 ASSERT3S(ztest_fd_data, >=, 0);
7894 (void) unlink(ztest_name_data);
7898 shared_data_size(ztest_shared_hdr_t *hdr)
7902 size = hdr->zh_hdr_size;
7903 size += hdr->zh_opts_size;
7904 size += hdr->zh_size;
7905 size += hdr->zh_stats_size * hdr->zh_stats_count;
7906 size += hdr->zh_ds_size * hdr->zh_ds_count;
7915 ztest_shared_hdr_t *hdr;
7917 hdr = (void *)mmap(0, P2ROUNDUP(sizeof (*hdr), getpagesize()),
7918 PROT_READ | PROT_WRITE, MAP_SHARED, ztest_fd_data, 0);
7919 ASSERT3P(hdr, !=, MAP_FAILED);
7921 VERIFY0(ftruncate(ztest_fd_data, sizeof (ztest_shared_hdr_t)));
7923 hdr->zh_hdr_size = sizeof (ztest_shared_hdr_t);
7924 hdr->zh_opts_size = sizeof (ztest_shared_opts_t);
7925 hdr->zh_size = sizeof (ztest_shared_t);
7926 hdr->zh_stats_size = sizeof (ztest_shared_callstate_t);
7927 hdr->zh_stats_count = ZTEST_FUNCS;
7928 hdr->zh_ds_size = sizeof (ztest_shared_ds_t);
7929 hdr->zh_ds_count = ztest_opts.zo_datasets;
7931 size = shared_data_size(hdr);
7932 VERIFY0(ftruncate(ztest_fd_data, size));
7934 (void) munmap((caddr_t)hdr, P2ROUNDUP(sizeof (*hdr), getpagesize()));
7941 ztest_shared_hdr_t *hdr;
7944 hdr = (void *)mmap(0, P2ROUNDUP(sizeof (*hdr), getpagesize()),
7945 PROT_READ, MAP_SHARED, ztest_fd_data, 0);
7946 ASSERT3P(hdr, !=, MAP_FAILED);
7948 size = shared_data_size(hdr);
7950 (void) munmap((caddr_t)hdr, P2ROUNDUP(sizeof (*hdr), getpagesize()));
7951 hdr = ztest_shared_hdr = (void *)mmap(0, P2ROUNDUP(size, getpagesize()),
7952 PROT_READ | PROT_WRITE, MAP_SHARED, ztest_fd_data, 0);
7953 ASSERT3P(hdr, !=, MAP_FAILED);
7954 buf = (uint8_t *)hdr;
7956 offset = hdr->zh_hdr_size;
7957 ztest_shared_opts = (void *)&buf[offset];
7958 offset += hdr->zh_opts_size;
7959 ztest_shared = (void *)&buf[offset];
7960 offset += hdr->zh_size;
7961 ztest_shared_callstate = (void *)&buf[offset];
7962 offset += hdr->zh_stats_size * hdr->zh_stats_count;
7963 ztest_shared_ds = (void *)&buf[offset];
7967 exec_child(char *cmd, char *libpath, boolean_t ignorekill, int *statusp)
7971 char *cmdbuf = NULL;
7976 cmdbuf = umem_alloc(MAXPATHLEN, UMEM_NOFAIL);
7977 (void) strlcpy(cmdbuf, getexecname(), MAXPATHLEN);
7982 fatal(B_TRUE, "fork failed");
7984 if (pid == 0) { /* child */
7985 char fd_data_str[12];
7988 snprintf(fd_data_str, 12, "%d", ztest_fd_data));
7989 VERIFY0(setenv("ZTEST_FD_DATA", fd_data_str, 1));
7991 if (libpath != NULL) {
7992 const char *curlp = getenv("LD_LIBRARY_PATH");
7994 VERIFY0(setenv("LD_LIBRARY_PATH", libpath, 1));
7998 asprintf(&newlp, "%s:%s", libpath, curlp));
7999 VERIFY0(setenv("LD_LIBRARY_PATH", newlp, 1));
8003 (void) execl(cmd, cmd, (char *)NULL);
8004 ztest_dump_core = B_FALSE;
8005 fatal(B_TRUE, "exec failed: %s", cmd);
8008 if (cmdbuf != NULL) {
8009 umem_free(cmdbuf, MAXPATHLEN);
8013 while (waitpid(pid, &status, 0) != pid)
8015 if (statusp != NULL)
8018 if (WIFEXITED(status)) {
8019 if (WEXITSTATUS(status) != 0) {
8020 (void) fprintf(stderr, "child exited with code %d\n",
8021 WEXITSTATUS(status));
8025 } else if (WIFSIGNALED(status)) {
8026 if (!ignorekill || WTERMSIG(status) != SIGKILL) {
8027 (void) fprintf(stderr, "child died with signal %d\n",
8033 (void) fprintf(stderr, "something strange happened to child\n");
8039 ztest_run_init(void)
8043 ztest_shared_t *zs = ztest_shared;
8046 * Blow away any existing copy of zpool.cache
8048 (void) remove(spa_config_path);
8050 if (ztest_opts.zo_init == 0) {
8051 if (ztest_opts.zo_verbose >= 1)
8052 (void) printf("Importing pool %s\n",
8053 ztest_opts.zo_pool);
8059 * Create and initialize our storage pool.
8061 for (i = 1; i <= ztest_opts.zo_init; i++) {
8062 memset(zs, 0, sizeof (*zs));
8063 if (ztest_opts.zo_verbose >= 3 &&
8064 ztest_opts.zo_init != 1) {
8065 (void) printf("ztest_init(), pass %d\n", i);
8072 main(int argc, char **argv)
8080 ztest_shared_callstate_t *zc;
8082 char numbuf[NN_NUMBUF_SZ];
8086 char *fd_data_str = getenv("ZTEST_FD_DATA");
8087 struct sigaction action;
8089 (void) setvbuf(stdout, NULL, _IOLBF, 0);
8091 dprintf_setup(&argc, argv);
8092 zfs_deadman_synctime_ms = 300000;
8093 zfs_deadman_checktime_ms = 30000;
8095 * As two-word space map entries may not come up often (especially
8096 * if pool and vdev sizes are small) we want to force at least some
8097 * of them so the feature get tested.
8099 zfs_force_some_double_word_sm_entries = B_TRUE;
8102 * Verify that even extensively damaged split blocks with many
8103 * segments can be reconstructed in a reasonable amount of time
8104 * when reconstruction is known to be possible.
8106 * Note: the lower this value is, the more damage we inflict, and
8107 * the more time ztest spends in recovering that damage. We chose
8108 * to induce damage 1/100th of the time so recovery is tested but
8109 * not so frequently that ztest doesn't get to test other code paths.
8111 zfs_reconstruct_indirect_damage_fraction = 100;
8113 action.sa_handler = sig_handler;
8114 sigemptyset(&action.sa_mask);
8115 action.sa_flags = 0;
8117 if (sigaction(SIGSEGV, &action, NULL) < 0) {
8118 (void) fprintf(stderr, "ztest: cannot catch SIGSEGV: %s.\n",
8123 if (sigaction(SIGABRT, &action, NULL) < 0) {
8124 (void) fprintf(stderr, "ztest: cannot catch SIGABRT: %s.\n",
8130 * Force random_get_bytes() to use /dev/urandom in order to prevent
8131 * ztest from needlessly depleting the system entropy pool.
8133 random_path = "/dev/urandom";
8134 ztest_fd_rand = open(random_path, O_RDONLY | O_CLOEXEC);
8135 ASSERT3S(ztest_fd_rand, >=, 0);
8138 process_options(argc, argv);
8143 memcpy(ztest_shared_opts, &ztest_opts,
8144 sizeof (*ztest_shared_opts));
8146 ztest_fd_data = atoi(fd_data_str);
8148 memcpy(&ztest_opts, ztest_shared_opts, sizeof (ztest_opts));
8150 ASSERT3U(ztest_opts.zo_datasets, ==, ztest_shared_hdr->zh_ds_count);
8152 err = ztest_set_global_vars();
8153 if (err != 0 && !fd_data_str) {
8154 /* error message done by ztest_set_global_vars */
8157 /* children should not be spawned if setting gvars fails */
8158 VERIFY3S(err, ==, 0);
8161 /* Override location of zpool.cache */
8162 VERIFY3S(asprintf((char **)&spa_config_path, "%s/zpool.cache",
8163 ztest_opts.zo_dir), !=, -1);
8165 ztest_ds = umem_alloc(ztest_opts.zo_datasets * sizeof (ztest_ds_t),
8170 metaslab_force_ganging = ztest_opts.zo_metaslab_force_ganging;
8171 metaslab_df_alloc_threshold =
8172 zs->zs_metaslab_df_alloc_threshold;
8181 hasalt = (strlen(ztest_opts.zo_alt_ztest) != 0);
8183 if (ztest_opts.zo_verbose >= 1) {
8184 (void) printf("%"PRIu64" vdevs, %d datasets, %d threads,"
8185 "%d %s disks, %"PRIu64" seconds...\n\n",
8186 ztest_opts.zo_vdevs,
8187 ztest_opts.zo_datasets,
8188 ztest_opts.zo_threads,
8189 ztest_opts.zo_raid_children,
8190 ztest_opts.zo_raid_type,
8191 ztest_opts.zo_time);
8194 cmd = umem_alloc(MAXNAMELEN, UMEM_NOFAIL);
8195 (void) strlcpy(cmd, getexecname(), MAXNAMELEN);
8197 zs->zs_do_init = B_TRUE;
8198 if (strlen(ztest_opts.zo_alt_ztest) != 0) {
8199 if (ztest_opts.zo_verbose >= 1) {
8200 (void) printf("Executing older ztest for "
8201 "initialization: %s\n", ztest_opts.zo_alt_ztest);
8203 VERIFY(!exec_child(ztest_opts.zo_alt_ztest,
8204 ztest_opts.zo_alt_libpath, B_FALSE, NULL));
8206 VERIFY(!exec_child(NULL, NULL, B_FALSE, NULL));
8208 zs->zs_do_init = B_FALSE;
8210 zs->zs_proc_start = gethrtime();
8211 zs->zs_proc_stop = zs->zs_proc_start + ztest_opts.zo_time * NANOSEC;
8213 for (f = 0; f < ZTEST_FUNCS; f++) {
8214 zi = &ztest_info[f];
8215 zc = ZTEST_GET_SHARED_CALLSTATE(f);
8216 if (zs->zs_proc_start + zi->zi_interval[0] > zs->zs_proc_stop)
8217 zc->zc_next = UINT64_MAX;
8219 zc->zc_next = zs->zs_proc_start +
8220 ztest_random(2 * zi->zi_interval[0] + 1);
8224 * Run the tests in a loop. These tests include fault injection
8225 * to verify that self-healing data works, and forced crashes
8226 * to verify that we never lose on-disk consistency.
8228 while (gethrtime() < zs->zs_proc_stop) {
8233 * Initialize the workload counters for each function.
8235 for (f = 0; f < ZTEST_FUNCS; f++) {
8236 zc = ZTEST_GET_SHARED_CALLSTATE(f);
8241 /* Set the allocation switch size */
8242 zs->zs_metaslab_df_alloc_threshold =
8243 ztest_random(zs->zs_metaslab_sz / 4) + 1;
8245 if (!hasalt || ztest_random(2) == 0) {
8246 if (hasalt && ztest_opts.zo_verbose >= 1) {
8247 (void) printf("Executing newer ztest: %s\n",
8251 killed = exec_child(cmd, NULL, B_TRUE, &status);
8253 if (hasalt && ztest_opts.zo_verbose >= 1) {
8254 (void) printf("Executing older ztest: %s\n",
8255 ztest_opts.zo_alt_ztest);
8258 killed = exec_child(ztest_opts.zo_alt_ztest,
8259 ztest_opts.zo_alt_libpath, B_TRUE, &status);
8266 if (ztest_opts.zo_verbose >= 1) {
8267 hrtime_t now = gethrtime();
8269 now = MIN(now, zs->zs_proc_stop);
8270 print_time(zs->zs_proc_stop - now, timebuf);
8271 nicenum(zs->zs_space, numbuf, sizeof (numbuf));
8273 (void) printf("Pass %3d, %8s, %3"PRIu64" ENOSPC, "
8274 "%4.1f%% of %5s used, %3.0f%% done, %8s to go\n",
8276 WIFEXITED(status) ? "Complete" : "SIGKILL",
8277 zs->zs_enospc_count,
8278 100.0 * zs->zs_alloc / zs->zs_space,
8280 100.0 * (now - zs->zs_proc_start) /
8281 (ztest_opts.zo_time * NANOSEC), timebuf);
8284 if (ztest_opts.zo_verbose >= 2) {
8285 (void) printf("\nWorkload summary:\n\n");
8286 (void) printf("%7s %9s %s\n",
8287 "Calls", "Time", "Function");
8288 (void) printf("%7s %9s %s\n",
8289 "-----", "----", "--------");
8290 for (f = 0; f < ZTEST_FUNCS; f++) {
8291 zi = &ztest_info[f];
8292 zc = ZTEST_GET_SHARED_CALLSTATE(f);
8293 print_time(zc->zc_time, timebuf);
8294 (void) printf("%7"PRIu64" %9s %s\n",
8295 zc->zc_count, timebuf,
8298 (void) printf("\n");
8301 if (!ztest_opts.zo_mmp_test)
8302 ztest_run_zdb(ztest_opts.zo_pool);
8305 if (ztest_opts.zo_verbose >= 1) {
8307 (void) printf("%d runs of older ztest: %s\n", older,
8308 ztest_opts.zo_alt_ztest);
8309 (void) printf("%d runs of newer ztest: %s\n", newer,
8312 (void) printf("%d killed, %d completed, %.0f%% kill rate\n",
8313 kills, iters - kills, (100.0 * kills) / MAX(1, iters));
8316 umem_free(cmd, MAXNAMELEN);