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