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