]> git.proxmox.com Git - mirror_zfs.git/blob - cmd/ztest/ztest.c
Fix consistency of ztest_device_removal_active
[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 static void
2161 ztest_get_done(zgd_t *zgd, int error)
2162 {
2163 ztest_ds_t *zd = zgd->zgd_private;
2164 uint64_t object = ((rl_t *)zgd->zgd_lr)->rl_object;
2165
2166 if (zgd->zgd_db)
2167 dmu_buf_rele(zgd->zgd_db, zgd);
2168
2169 ztest_range_unlock((rl_t *)zgd->zgd_lr);
2170 ztest_object_unlock(zd, object);
2171
2172 if (error == 0 && zgd->zgd_bp)
2173 zil_lwb_add_block(zgd->zgd_lwb, zgd->zgd_bp);
2174
2175 umem_free(zgd, sizeof (*zgd));
2176 }
2177
2178 static int
2179 ztest_get_data(void *arg, lr_write_t *lr, char *buf, struct lwb *lwb,
2180 zio_t *zio)
2181 {
2182 ztest_ds_t *zd = arg;
2183 objset_t *os = zd->zd_os;
2184 uint64_t object = lr->lr_foid;
2185 uint64_t offset = lr->lr_offset;
2186 uint64_t size = lr->lr_length;
2187 uint64_t txg = lr->lr_common.lrc_txg;
2188 uint64_t crtxg;
2189 dmu_object_info_t doi;
2190 dmu_buf_t *db;
2191 zgd_t *zgd;
2192 int error;
2193
2194 ASSERT3P(lwb, !=, NULL);
2195 ASSERT3P(zio, !=, NULL);
2196 ASSERT3U(size, !=, 0);
2197
2198 ztest_object_lock(zd, object, RL_READER);
2199 error = dmu_bonus_hold(os, object, FTAG, &db);
2200 if (error) {
2201 ztest_object_unlock(zd, object);
2202 return (error);
2203 }
2204
2205 crtxg = ztest_bt_bonus(db)->bt_crtxg;
2206
2207 if (crtxg == 0 || crtxg > txg) {
2208 dmu_buf_rele(db, FTAG);
2209 ztest_object_unlock(zd, object);
2210 return (ENOENT);
2211 }
2212
2213 dmu_object_info_from_db(db, &doi);
2214 dmu_buf_rele(db, FTAG);
2215 db = NULL;
2216
2217 zgd = umem_zalloc(sizeof (*zgd), UMEM_NOFAIL);
2218 zgd->zgd_lwb = lwb;
2219 zgd->zgd_private = zd;
2220
2221 if (buf != NULL) { /* immediate write */
2222 zgd->zgd_lr = (struct locked_range *)ztest_range_lock(zd,
2223 object, offset, size, RL_READER);
2224
2225 error = dmu_read(os, object, offset, size, buf,
2226 DMU_READ_NO_PREFETCH);
2227 ASSERT(error == 0);
2228 } else {
2229 size = doi.doi_data_block_size;
2230 if (ISP2(size)) {
2231 offset = P2ALIGN(offset, size);
2232 } else {
2233 ASSERT(offset < size);
2234 offset = 0;
2235 }
2236
2237 zgd->zgd_lr = (struct locked_range *)ztest_range_lock(zd,
2238 object, offset, size, RL_READER);
2239
2240 error = dmu_buf_hold(os, object, offset, zgd, &db,
2241 DMU_READ_NO_PREFETCH);
2242
2243 if (error == 0) {
2244 blkptr_t *bp = &lr->lr_blkptr;
2245
2246 zgd->zgd_db = db;
2247 zgd->zgd_bp = bp;
2248
2249 ASSERT(db->db_offset == offset);
2250 ASSERT(db->db_size == size);
2251
2252 error = dmu_sync(zio, lr->lr_common.lrc_txg,
2253 ztest_get_done, zgd);
2254
2255 if (error == 0)
2256 return (0);
2257 }
2258 }
2259
2260 ztest_get_done(zgd, error);
2261
2262 return (error);
2263 }
2264
2265 static void *
2266 ztest_lr_alloc(size_t lrsize, char *name)
2267 {
2268 char *lr;
2269 size_t namesize = name ? strlen(name) + 1 : 0;
2270
2271 lr = umem_zalloc(lrsize + namesize, UMEM_NOFAIL);
2272
2273 if (name)
2274 bcopy(name, lr + lrsize, namesize);
2275
2276 return (lr);
2277 }
2278
2279 void
2280 ztest_lr_free(void *lr, size_t lrsize, char *name)
2281 {
2282 size_t namesize = name ? strlen(name) + 1 : 0;
2283
2284 umem_free(lr, lrsize + namesize);
2285 }
2286
2287 /*
2288 * Lookup a bunch of objects. Returns the number of objects not found.
2289 */
2290 static int
2291 ztest_lookup(ztest_ds_t *zd, ztest_od_t *od, int count)
2292 {
2293 int missing = 0;
2294 int error;
2295 int i;
2296
2297 ASSERT(MUTEX_HELD(&zd->zd_dirobj_lock));
2298
2299 for (i = 0; i < count; i++, od++) {
2300 od->od_object = 0;
2301 error = zap_lookup(zd->zd_os, od->od_dir, od->od_name,
2302 sizeof (uint64_t), 1, &od->od_object);
2303 if (error) {
2304 ASSERT(error == ENOENT);
2305 ASSERT(od->od_object == 0);
2306 missing++;
2307 } else {
2308 dmu_buf_t *db;
2309 ztest_block_tag_t *bbt;
2310 dmu_object_info_t doi;
2311
2312 ASSERT(od->od_object != 0);
2313 ASSERT(missing == 0); /* there should be no gaps */
2314
2315 ztest_object_lock(zd, od->od_object, RL_READER);
2316 VERIFY3U(0, ==, dmu_bonus_hold(zd->zd_os,
2317 od->od_object, FTAG, &db));
2318 dmu_object_info_from_db(db, &doi);
2319 bbt = ztest_bt_bonus(db);
2320 ASSERT3U(bbt->bt_magic, ==, BT_MAGIC);
2321 od->od_type = doi.doi_type;
2322 od->od_blocksize = doi.doi_data_block_size;
2323 od->od_gen = bbt->bt_gen;
2324 dmu_buf_rele(db, FTAG);
2325 ztest_object_unlock(zd, od->od_object);
2326 }
2327 }
2328
2329 return (missing);
2330 }
2331
2332 static int
2333 ztest_create(ztest_ds_t *zd, ztest_od_t *od, int count)
2334 {
2335 int missing = 0;
2336 int i;
2337
2338 ASSERT(MUTEX_HELD(&zd->zd_dirobj_lock));
2339
2340 for (i = 0; i < count; i++, od++) {
2341 if (missing) {
2342 od->od_object = 0;
2343 missing++;
2344 continue;
2345 }
2346
2347 lr_create_t *lr = ztest_lr_alloc(sizeof (*lr), od->od_name);
2348
2349 lr->lr_doid = od->od_dir;
2350 lr->lr_foid = 0; /* 0 to allocate, > 0 to claim */
2351 lr->lrz_type = od->od_crtype;
2352 lr->lrz_blocksize = od->od_crblocksize;
2353 lr->lrz_ibshift = ztest_random_ibshift();
2354 lr->lrz_bonustype = DMU_OT_UINT64_OTHER;
2355 lr->lrz_dnodesize = od->od_crdnodesize;
2356 lr->lr_gen = od->od_crgen;
2357 lr->lr_crtime[0] = time(NULL);
2358
2359 if (ztest_replay_create(zd, lr, B_FALSE) != 0) {
2360 ASSERT(missing == 0);
2361 od->od_object = 0;
2362 missing++;
2363 } else {
2364 od->od_object = lr->lr_foid;
2365 od->od_type = od->od_crtype;
2366 od->od_blocksize = od->od_crblocksize;
2367 od->od_gen = od->od_crgen;
2368 ASSERT(od->od_object != 0);
2369 }
2370
2371 ztest_lr_free(lr, sizeof (*lr), od->od_name);
2372 }
2373
2374 return (missing);
2375 }
2376
2377 static int
2378 ztest_remove(ztest_ds_t *zd, ztest_od_t *od, int count)
2379 {
2380 int missing = 0;
2381 int error;
2382 int i;
2383
2384 ASSERT(MUTEX_HELD(&zd->zd_dirobj_lock));
2385
2386 od += count - 1;
2387
2388 for (i = count - 1; i >= 0; i--, od--) {
2389 if (missing) {
2390 missing++;
2391 continue;
2392 }
2393
2394 /*
2395 * No object was found.
2396 */
2397 if (od->od_object == 0)
2398 continue;
2399
2400 lr_remove_t *lr = ztest_lr_alloc(sizeof (*lr), od->od_name);
2401
2402 lr->lr_doid = od->od_dir;
2403
2404 if ((error = ztest_replay_remove(zd, lr, B_FALSE)) != 0) {
2405 ASSERT3U(error, ==, ENOSPC);
2406 missing++;
2407 } else {
2408 od->od_object = 0;
2409 }
2410 ztest_lr_free(lr, sizeof (*lr), od->od_name);
2411 }
2412
2413 return (missing);
2414 }
2415
2416 static int
2417 ztest_write(ztest_ds_t *zd, uint64_t object, uint64_t offset, uint64_t size,
2418 void *data)
2419 {
2420 lr_write_t *lr;
2421 int error;
2422
2423 lr = ztest_lr_alloc(sizeof (*lr) + size, NULL);
2424
2425 lr->lr_foid = object;
2426 lr->lr_offset = offset;
2427 lr->lr_length = size;
2428 lr->lr_blkoff = 0;
2429 BP_ZERO(&lr->lr_blkptr);
2430
2431 bcopy(data, lr + 1, size);
2432
2433 error = ztest_replay_write(zd, lr, B_FALSE);
2434
2435 ztest_lr_free(lr, sizeof (*lr) + size, NULL);
2436
2437 return (error);
2438 }
2439
2440 static int
2441 ztest_truncate(ztest_ds_t *zd, uint64_t object, uint64_t offset, uint64_t size)
2442 {
2443 lr_truncate_t *lr;
2444 int error;
2445
2446 lr = ztest_lr_alloc(sizeof (*lr), NULL);
2447
2448 lr->lr_foid = object;
2449 lr->lr_offset = offset;
2450 lr->lr_length = size;
2451
2452 error = ztest_replay_truncate(zd, lr, B_FALSE);
2453
2454 ztest_lr_free(lr, sizeof (*lr), NULL);
2455
2456 return (error);
2457 }
2458
2459 static int
2460 ztest_setattr(ztest_ds_t *zd, uint64_t object)
2461 {
2462 lr_setattr_t *lr;
2463 int error;
2464
2465 lr = ztest_lr_alloc(sizeof (*lr), NULL);
2466
2467 lr->lr_foid = object;
2468 lr->lr_size = 0;
2469 lr->lr_mode = 0;
2470
2471 error = ztest_replay_setattr(zd, lr, B_FALSE);
2472
2473 ztest_lr_free(lr, sizeof (*lr), NULL);
2474
2475 return (error);
2476 }
2477
2478 static void
2479 ztest_prealloc(ztest_ds_t *zd, uint64_t object, uint64_t offset, uint64_t size)
2480 {
2481 objset_t *os = zd->zd_os;
2482 dmu_tx_t *tx;
2483 uint64_t txg;
2484 rl_t *rl;
2485
2486 txg_wait_synced(dmu_objset_pool(os), 0);
2487
2488 ztest_object_lock(zd, object, RL_READER);
2489 rl = ztest_range_lock(zd, object, offset, size, RL_WRITER);
2490
2491 tx = dmu_tx_create(os);
2492
2493 dmu_tx_hold_write(tx, object, offset, size);
2494
2495 txg = ztest_tx_assign(tx, TXG_WAIT, FTAG);
2496
2497 if (txg != 0) {
2498 dmu_prealloc(os, object, offset, size, tx);
2499 dmu_tx_commit(tx);
2500 txg_wait_synced(dmu_objset_pool(os), txg);
2501 } else {
2502 (void) dmu_free_long_range(os, object, offset, size);
2503 }
2504
2505 ztest_range_unlock(rl);
2506 ztest_object_unlock(zd, object);
2507 }
2508
2509 static void
2510 ztest_io(ztest_ds_t *zd, uint64_t object, uint64_t offset)
2511 {
2512 int err;
2513 ztest_block_tag_t wbt;
2514 dmu_object_info_t doi;
2515 enum ztest_io_type io_type;
2516 uint64_t blocksize;
2517 void *data;
2518
2519 VERIFY(dmu_object_info(zd->zd_os, object, &doi) == 0);
2520 blocksize = doi.doi_data_block_size;
2521 data = umem_alloc(blocksize, UMEM_NOFAIL);
2522
2523 /*
2524 * Pick an i/o type at random, biased toward writing block tags.
2525 */
2526 io_type = ztest_random(ZTEST_IO_TYPES);
2527 if (ztest_random(2) == 0)
2528 io_type = ZTEST_IO_WRITE_TAG;
2529
2530 (void) pthread_rwlock_rdlock(&zd->zd_zilog_lock);
2531
2532 switch (io_type) {
2533
2534 case ZTEST_IO_WRITE_TAG:
2535 ztest_bt_generate(&wbt, zd->zd_os, object, doi.doi_dnodesize,
2536 offset, 0, 0, 0);
2537 (void) ztest_write(zd, object, offset, sizeof (wbt), &wbt);
2538 break;
2539
2540 case ZTEST_IO_WRITE_PATTERN:
2541 (void) memset(data, 'a' + (object + offset) % 5, blocksize);
2542 if (ztest_random(2) == 0) {
2543 /*
2544 * Induce fletcher2 collisions to ensure that
2545 * zio_ddt_collision() detects and resolves them
2546 * when using fletcher2-verify for deduplication.
2547 */
2548 ((uint64_t *)data)[0] ^= 1ULL << 63;
2549 ((uint64_t *)data)[4] ^= 1ULL << 63;
2550 }
2551 (void) ztest_write(zd, object, offset, blocksize, data);
2552 break;
2553
2554 case ZTEST_IO_WRITE_ZEROES:
2555 bzero(data, blocksize);
2556 (void) ztest_write(zd, object, offset, blocksize, data);
2557 break;
2558
2559 case ZTEST_IO_TRUNCATE:
2560 (void) ztest_truncate(zd, object, offset, blocksize);
2561 break;
2562
2563 case ZTEST_IO_SETATTR:
2564 (void) ztest_setattr(zd, object);
2565 break;
2566 default:
2567 break;
2568
2569 case ZTEST_IO_REWRITE:
2570 (void) pthread_rwlock_rdlock(&ztest_name_lock);
2571 err = ztest_dsl_prop_set_uint64(zd->zd_name,
2572 ZFS_PROP_CHECKSUM, spa_dedup_checksum(ztest_spa),
2573 B_FALSE);
2574 VERIFY(err == 0 || err == ENOSPC);
2575 err = ztest_dsl_prop_set_uint64(zd->zd_name,
2576 ZFS_PROP_COMPRESSION,
2577 ztest_random_dsl_prop(ZFS_PROP_COMPRESSION),
2578 B_FALSE);
2579 VERIFY(err == 0 || err == ENOSPC);
2580 (void) pthread_rwlock_unlock(&ztest_name_lock);
2581
2582 VERIFY0(dmu_read(zd->zd_os, object, offset, blocksize, data,
2583 DMU_READ_NO_PREFETCH));
2584
2585 (void) ztest_write(zd, object, offset, blocksize, data);
2586 break;
2587 }
2588
2589 (void) pthread_rwlock_unlock(&zd->zd_zilog_lock);
2590
2591 umem_free(data, blocksize);
2592 }
2593
2594 /*
2595 * Initialize an object description template.
2596 */
2597 static void
2598 ztest_od_init(ztest_od_t *od, uint64_t id, char *tag, uint64_t index,
2599 dmu_object_type_t type, uint64_t blocksize, uint64_t dnodesize,
2600 uint64_t gen)
2601 {
2602 od->od_dir = ZTEST_DIROBJ;
2603 od->od_object = 0;
2604
2605 od->od_crtype = type;
2606 od->od_crblocksize = blocksize ? blocksize : ztest_random_blocksize();
2607 od->od_crdnodesize = dnodesize ? dnodesize : ztest_random_dnodesize();
2608 od->od_crgen = gen;
2609
2610 od->od_type = DMU_OT_NONE;
2611 od->od_blocksize = 0;
2612 od->od_gen = 0;
2613
2614 (void) snprintf(od->od_name, sizeof (od->od_name), "%s(%lld)[%llu]",
2615 tag, (longlong_t)id, (u_longlong_t)index);
2616 }
2617
2618 /*
2619 * Lookup or create the objects for a test using the od template.
2620 * If the objects do not all exist, or if 'remove' is specified,
2621 * remove any existing objects and create new ones. Otherwise,
2622 * use the existing objects.
2623 */
2624 static int
2625 ztest_object_init(ztest_ds_t *zd, ztest_od_t *od, size_t size, boolean_t remove)
2626 {
2627 int count = size / sizeof (*od);
2628 int rv = 0;
2629
2630 mutex_enter(&zd->zd_dirobj_lock);
2631 if ((ztest_lookup(zd, od, count) != 0 || remove) &&
2632 (ztest_remove(zd, od, count) != 0 ||
2633 ztest_create(zd, od, count) != 0))
2634 rv = -1;
2635 zd->zd_od = od;
2636 mutex_exit(&zd->zd_dirobj_lock);
2637
2638 return (rv);
2639 }
2640
2641 /* ARGSUSED */
2642 void
2643 ztest_zil_commit(ztest_ds_t *zd, uint64_t id)
2644 {
2645 zilog_t *zilog = zd->zd_zilog;
2646
2647 (void) pthread_rwlock_rdlock(&zd->zd_zilog_lock);
2648
2649 zil_commit(zilog, ztest_random(ZTEST_OBJECTS));
2650
2651 /*
2652 * Remember the committed values in zd, which is in parent/child
2653 * shared memory. If we die, the next iteration of ztest_run()
2654 * will verify that the log really does contain this record.
2655 */
2656 mutex_enter(&zilog->zl_lock);
2657 ASSERT(zd->zd_shared != NULL);
2658 ASSERT3U(zd->zd_shared->zd_seq, <=, zilog->zl_commit_lr_seq);
2659 zd->zd_shared->zd_seq = zilog->zl_commit_lr_seq;
2660 mutex_exit(&zilog->zl_lock);
2661
2662 (void) pthread_rwlock_unlock(&zd->zd_zilog_lock);
2663 }
2664
2665 /*
2666 * This function is designed to simulate the operations that occur during a
2667 * mount/unmount operation. We hold the dataset across these operations in an
2668 * attempt to expose any implicit assumptions about ZIL management.
2669 */
2670 /* ARGSUSED */
2671 void
2672 ztest_zil_remount(ztest_ds_t *zd, uint64_t id)
2673 {
2674 objset_t *os = zd->zd_os;
2675
2676 /*
2677 * We grab the zd_dirobj_lock to ensure that no other thread is
2678 * updating the zil (i.e. adding in-memory log records) and the
2679 * zd_zilog_lock to block any I/O.
2680 */
2681 mutex_enter(&zd->zd_dirobj_lock);
2682 (void) pthread_rwlock_wrlock(&zd->zd_zilog_lock);
2683
2684 /* zfsvfs_teardown() */
2685 zil_close(zd->zd_zilog);
2686
2687 /* zfsvfs_setup() */
2688 VERIFY(zil_open(os, ztest_get_data) == zd->zd_zilog);
2689 zil_replay(os, zd, ztest_replay_vector);
2690
2691 (void) pthread_rwlock_unlock(&zd->zd_zilog_lock);
2692 mutex_exit(&zd->zd_dirobj_lock);
2693 }
2694
2695 /*
2696 * Verify that we can't destroy an active pool, create an existing pool,
2697 * or create a pool with a bad vdev spec.
2698 */
2699 /* ARGSUSED */
2700 void
2701 ztest_spa_create_destroy(ztest_ds_t *zd, uint64_t id)
2702 {
2703 ztest_shared_opts_t *zo = &ztest_opts;
2704 spa_t *spa;
2705 nvlist_t *nvroot;
2706
2707 if (zo->zo_mmp_test)
2708 return;
2709
2710 /*
2711 * Attempt to create using a bad file.
2712 */
2713 nvroot = make_vdev_root("/dev/bogus", NULL, NULL, 0, 0, NULL, 0, 0, 1);
2714 VERIFY3U(ENOENT, ==,
2715 spa_create("ztest_bad_file", nvroot, NULL, NULL, NULL));
2716 nvlist_free(nvroot);
2717
2718 /*
2719 * Attempt to create using a bad mirror.
2720 */
2721 nvroot = make_vdev_root("/dev/bogus", NULL, NULL, 0, 0, NULL, 0, 2, 1);
2722 VERIFY3U(ENOENT, ==,
2723 spa_create("ztest_bad_mirror", nvroot, NULL, NULL, NULL));
2724 nvlist_free(nvroot);
2725
2726 /*
2727 * Attempt to create an existing pool. It shouldn't matter
2728 * what's in the nvroot; we should fail with EEXIST.
2729 */
2730 (void) pthread_rwlock_rdlock(&ztest_name_lock);
2731 nvroot = make_vdev_root("/dev/bogus", NULL, NULL, 0, 0, NULL, 0, 0, 1);
2732 VERIFY3U(EEXIST, ==,
2733 spa_create(zo->zo_pool, nvroot, NULL, NULL, NULL));
2734 nvlist_free(nvroot);
2735 VERIFY3U(0, ==, spa_open(zo->zo_pool, &spa, FTAG));
2736 VERIFY3U(EBUSY, ==, spa_destroy(zo->zo_pool));
2737 spa_close(spa, FTAG);
2738
2739 (void) pthread_rwlock_unlock(&ztest_name_lock);
2740 }
2741
2742 /*
2743 * Start and then stop the MMP threads to ensure the startup and shutdown code
2744 * works properly. Actual protection and property-related code tested via ZTS.
2745 */
2746 /* ARGSUSED */
2747 void
2748 ztest_mmp_enable_disable(ztest_ds_t *zd, uint64_t id)
2749 {
2750 ztest_shared_opts_t *zo = &ztest_opts;
2751 spa_t *spa = ztest_spa;
2752
2753 if (zo->zo_mmp_test)
2754 return;
2755
2756 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
2757 mutex_enter(&spa->spa_props_lock);
2758
2759 zfs_multihost_fail_intervals = 0;
2760
2761 if (!spa_multihost(spa)) {
2762 spa->spa_multihost = B_TRUE;
2763 mmp_thread_start(spa);
2764 }
2765
2766 mutex_exit(&spa->spa_props_lock);
2767 spa_config_exit(spa, SCL_CONFIG, FTAG);
2768
2769 txg_wait_synced(spa_get_dsl(spa), 0);
2770 mmp_signal_all_threads();
2771 txg_wait_synced(spa_get_dsl(spa), 0);
2772
2773 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
2774 mutex_enter(&spa->spa_props_lock);
2775
2776 if (spa_multihost(spa)) {
2777 mmp_thread_stop(spa);
2778 spa->spa_multihost = B_FALSE;
2779 }
2780
2781 mutex_exit(&spa->spa_props_lock);
2782 spa_config_exit(spa, SCL_CONFIG, FTAG);
2783 }
2784
2785 /* ARGSUSED */
2786 void
2787 ztest_spa_upgrade(ztest_ds_t *zd, uint64_t id)
2788 {
2789 spa_t *spa;
2790 uint64_t initial_version = SPA_VERSION_INITIAL;
2791 uint64_t version, newversion;
2792 nvlist_t *nvroot, *props;
2793 char *name;
2794
2795 if (ztest_opts.zo_mmp_test)
2796 return;
2797
2798 mutex_enter(&ztest_vdev_lock);
2799 name = kmem_asprintf("%s_upgrade", ztest_opts.zo_pool);
2800
2801 /*
2802 * Clean up from previous runs.
2803 */
2804 (void) spa_destroy(name);
2805
2806 nvroot = make_vdev_root(NULL, NULL, name, ztest_opts.zo_vdev_size, 0,
2807 NULL, ztest_opts.zo_raidz, ztest_opts.zo_mirrors, 1);
2808
2809 /*
2810 * If we're configuring a RAIDZ device then make sure that the
2811 * the initial version is capable of supporting that feature.
2812 */
2813 switch (ztest_opts.zo_raidz_parity) {
2814 case 0:
2815 case 1:
2816 initial_version = SPA_VERSION_INITIAL;
2817 break;
2818 case 2:
2819 initial_version = SPA_VERSION_RAIDZ2;
2820 break;
2821 case 3:
2822 initial_version = SPA_VERSION_RAIDZ3;
2823 break;
2824 }
2825
2826 /*
2827 * Create a pool with a spa version that can be upgraded. Pick
2828 * a value between initial_version and SPA_VERSION_BEFORE_FEATURES.
2829 */
2830 do {
2831 version = ztest_random_spa_version(initial_version);
2832 } while (version > SPA_VERSION_BEFORE_FEATURES);
2833
2834 props = fnvlist_alloc();
2835 fnvlist_add_uint64(props,
2836 zpool_prop_to_name(ZPOOL_PROP_VERSION), version);
2837 VERIFY3S(spa_create(name, nvroot, props, NULL, NULL), ==, 0);
2838 fnvlist_free(nvroot);
2839 fnvlist_free(props);
2840
2841 VERIFY3S(spa_open(name, &spa, FTAG), ==, 0);
2842 VERIFY3U(spa_version(spa), ==, version);
2843 newversion = ztest_random_spa_version(version + 1);
2844
2845 if (ztest_opts.zo_verbose >= 4) {
2846 (void) printf("upgrading spa version from %llu to %llu\n",
2847 (u_longlong_t)version, (u_longlong_t)newversion);
2848 }
2849
2850 spa_upgrade(spa, newversion);
2851 VERIFY3U(spa_version(spa), >, version);
2852 VERIFY3U(spa_version(spa), ==, fnvlist_lookup_uint64(spa->spa_config,
2853 zpool_prop_to_name(ZPOOL_PROP_VERSION)));
2854 spa_close(spa, FTAG);
2855
2856 strfree(name);
2857 mutex_exit(&ztest_vdev_lock);
2858 }
2859
2860 static void
2861 ztest_spa_checkpoint(spa_t *spa)
2862 {
2863 ASSERT(MUTEX_HELD(&ztest_checkpoint_lock));
2864
2865 int error = spa_checkpoint(spa->spa_name);
2866
2867 switch (error) {
2868 case 0:
2869 case ZFS_ERR_DEVRM_IN_PROGRESS:
2870 case ZFS_ERR_DISCARDING_CHECKPOINT:
2871 case ZFS_ERR_CHECKPOINT_EXISTS:
2872 break;
2873 case ENOSPC:
2874 ztest_record_enospc(FTAG);
2875 break;
2876 default:
2877 fatal(0, "spa_checkpoint(%s) = %d", spa->spa_name, error);
2878 }
2879 }
2880
2881 static void
2882 ztest_spa_discard_checkpoint(spa_t *spa)
2883 {
2884 ASSERT(MUTEX_HELD(&ztest_checkpoint_lock));
2885
2886 int error = spa_checkpoint_discard(spa->spa_name);
2887
2888 switch (error) {
2889 case 0:
2890 case ZFS_ERR_DISCARDING_CHECKPOINT:
2891 case ZFS_ERR_NO_CHECKPOINT:
2892 break;
2893 default:
2894 fatal(0, "spa_discard_checkpoint(%s) = %d",
2895 spa->spa_name, error);
2896 }
2897
2898 }
2899
2900 /* ARGSUSED */
2901 void
2902 ztest_spa_checkpoint_create_discard(ztest_ds_t *zd, uint64_t id)
2903 {
2904 spa_t *spa = ztest_spa;
2905
2906 mutex_enter(&ztest_checkpoint_lock);
2907 if (ztest_random(2) == 0) {
2908 ztest_spa_checkpoint(spa);
2909 } else {
2910 ztest_spa_discard_checkpoint(spa);
2911 }
2912 mutex_exit(&ztest_checkpoint_lock);
2913 }
2914
2915
2916 static vdev_t *
2917 vdev_lookup_by_path(vdev_t *vd, const char *path)
2918 {
2919 vdev_t *mvd;
2920 int c;
2921
2922 if (vd->vdev_path != NULL && strcmp(path, vd->vdev_path) == 0)
2923 return (vd);
2924
2925 for (c = 0; c < vd->vdev_children; c++)
2926 if ((mvd = vdev_lookup_by_path(vd->vdev_child[c], path)) !=
2927 NULL)
2928 return (mvd);
2929
2930 return (NULL);
2931 }
2932
2933 /*
2934 * Find the first available hole which can be used as a top-level.
2935 */
2936 int
2937 find_vdev_hole(spa_t *spa)
2938 {
2939 vdev_t *rvd = spa->spa_root_vdev;
2940 int c;
2941
2942 ASSERT(spa_config_held(spa, SCL_VDEV, RW_READER) == SCL_VDEV);
2943
2944 for (c = 0; c < rvd->vdev_children; c++) {
2945 vdev_t *cvd = rvd->vdev_child[c];
2946
2947 if (cvd->vdev_ishole)
2948 break;
2949 }
2950 return (c);
2951 }
2952
2953 /*
2954 * Verify that vdev_add() works as expected.
2955 */
2956 /* ARGSUSED */
2957 void
2958 ztest_vdev_add_remove(ztest_ds_t *zd, uint64_t id)
2959 {
2960 ztest_shared_t *zs = ztest_shared;
2961 spa_t *spa = ztest_spa;
2962 uint64_t leaves;
2963 uint64_t guid;
2964 nvlist_t *nvroot;
2965 int error;
2966
2967 if (ztest_opts.zo_mmp_test)
2968 return;
2969
2970 mutex_enter(&ztest_vdev_lock);
2971 leaves = MAX(zs->zs_mirrors + zs->zs_splits, 1) * ztest_opts.zo_raidz;
2972
2973 spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
2974
2975 ztest_shared->zs_vdev_next_leaf = find_vdev_hole(spa) * leaves;
2976
2977 /*
2978 * If we have slogs then remove them 1/4 of the time.
2979 */
2980 if (spa_has_slogs(spa) && ztest_random(4) == 0) {
2981 metaslab_group_t *mg;
2982
2983 /*
2984 * find the first real slog in log allocation class
2985 */
2986 mg = spa_log_class(spa)->mc_rotor;
2987 while (!mg->mg_vd->vdev_islog)
2988 mg = mg->mg_next;
2989
2990 guid = mg->mg_vd->vdev_guid;
2991
2992 spa_config_exit(spa, SCL_VDEV, FTAG);
2993
2994 /*
2995 * We have to grab the zs_name_lock as writer to
2996 * prevent a race between removing a slog (dmu_objset_find)
2997 * and destroying a dataset. Removing the slog will
2998 * grab a reference on the dataset which may cause
2999 * dsl_destroy_head() to fail with EBUSY thus
3000 * leaving the dataset in an inconsistent state.
3001 */
3002 pthread_rwlock_wrlock(&ztest_name_lock);
3003 error = spa_vdev_remove(spa, guid, B_FALSE);
3004 pthread_rwlock_unlock(&ztest_name_lock);
3005
3006 switch (error) {
3007 case 0:
3008 case EEXIST: /* Generic zil_reset() error */
3009 case EBUSY: /* Replay required */
3010 case EACCES: /* Crypto key not loaded */
3011 case ZFS_ERR_CHECKPOINT_EXISTS:
3012 case ZFS_ERR_DISCARDING_CHECKPOINT:
3013 break;
3014 default:
3015 fatal(0, "spa_vdev_remove() = %d", error);
3016 }
3017 } else {
3018 spa_config_exit(spa, SCL_VDEV, FTAG);
3019
3020 /*
3021 * Make 1/4 of the devices be log devices
3022 */
3023 nvroot = make_vdev_root(NULL, NULL, NULL,
3024 ztest_opts.zo_vdev_size, 0, (ztest_random(4) == 0) ?
3025 "log" : NULL, ztest_opts.zo_raidz, zs->zs_mirrors, 1);
3026
3027 error = spa_vdev_add(spa, nvroot);
3028 nvlist_free(nvroot);
3029
3030 switch (error) {
3031 case 0:
3032 break;
3033 case ENOSPC:
3034 ztest_record_enospc("spa_vdev_add");
3035 break;
3036 default:
3037 fatal(0, "spa_vdev_add() = %d", error);
3038 }
3039 }
3040
3041 mutex_exit(&ztest_vdev_lock);
3042 }
3043
3044 /* ARGSUSED */
3045 void
3046 ztest_vdev_class_add(ztest_ds_t *zd, uint64_t id)
3047 {
3048 ztest_shared_t *zs = ztest_shared;
3049 spa_t *spa = ztest_spa;
3050 uint64_t leaves;
3051 nvlist_t *nvroot;
3052 const char *class = (ztest_random(2) == 0) ?
3053 VDEV_ALLOC_BIAS_SPECIAL : VDEV_ALLOC_BIAS_DEDUP;
3054 int error;
3055
3056 /*
3057 * By default add a special vdev 50% of the time
3058 */
3059 if ((ztest_opts.zo_special_vdevs == ZTEST_VDEV_CLASS_OFF) ||
3060 (ztest_opts.zo_special_vdevs == ZTEST_VDEV_CLASS_RND &&
3061 ztest_random(2) == 0)) {
3062 return;
3063 }
3064
3065 mutex_enter(&ztest_vdev_lock);
3066
3067 /* Only test with mirrors */
3068 if (zs->zs_mirrors < 2) {
3069 mutex_exit(&ztest_vdev_lock);
3070 return;
3071 }
3072
3073 /* requires feature@allocation_classes */
3074 if (!spa_feature_is_enabled(spa, SPA_FEATURE_ALLOCATION_CLASSES)) {
3075 mutex_exit(&ztest_vdev_lock);
3076 return;
3077 }
3078
3079 leaves = MAX(zs->zs_mirrors + zs->zs_splits, 1) * ztest_opts.zo_raidz;
3080
3081 spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
3082 ztest_shared->zs_vdev_next_leaf = find_vdev_hole(spa) * leaves;
3083 spa_config_exit(spa, SCL_VDEV, FTAG);
3084
3085 nvroot = make_vdev_root(NULL, NULL, NULL, ztest_opts.zo_vdev_size, 0,
3086 class, ztest_opts.zo_raidz, zs->zs_mirrors, 1);
3087
3088 error = spa_vdev_add(spa, nvroot);
3089 nvlist_free(nvroot);
3090
3091 if (error == ENOSPC)
3092 ztest_record_enospc("spa_vdev_add");
3093 else if (error != 0)
3094 fatal(0, "spa_vdev_add() = %d", error);
3095
3096 /*
3097 * 50% of the time allow small blocks in the special class
3098 */
3099 if (error == 0 &&
3100 spa_special_class(spa)->mc_groups == 1 && ztest_random(2) == 0) {
3101 if (ztest_opts.zo_verbose >= 3)
3102 (void) printf("Enabling special VDEV small blocks\n");
3103 (void) ztest_dsl_prop_set_uint64(zd->zd_name,
3104 ZFS_PROP_SPECIAL_SMALL_BLOCKS, 32768, B_FALSE);
3105 }
3106
3107 mutex_exit(&ztest_vdev_lock);
3108
3109 if (ztest_opts.zo_verbose >= 3) {
3110 metaslab_class_t *mc;
3111
3112 if (strcmp(class, VDEV_ALLOC_BIAS_SPECIAL) == 0)
3113 mc = spa_special_class(spa);
3114 else
3115 mc = spa_dedup_class(spa);
3116 (void) printf("Added a %s mirrored vdev (of %d)\n",
3117 class, (int)mc->mc_groups);
3118 }
3119 }
3120
3121 /*
3122 * Verify that adding/removing aux devices (l2arc, hot spare) works as expected.
3123 */
3124 /* ARGSUSED */
3125 void
3126 ztest_vdev_aux_add_remove(ztest_ds_t *zd, uint64_t id)
3127 {
3128 ztest_shared_t *zs = ztest_shared;
3129 spa_t *spa = ztest_spa;
3130 vdev_t *rvd = spa->spa_root_vdev;
3131 spa_aux_vdev_t *sav;
3132 char *aux;
3133 char *path;
3134 uint64_t guid = 0;
3135 int error;
3136
3137 if (ztest_opts.zo_mmp_test)
3138 return;
3139
3140 path = umem_alloc(MAXPATHLEN, UMEM_NOFAIL);
3141
3142 if (ztest_random(2) == 0) {
3143 sav = &spa->spa_spares;
3144 aux = ZPOOL_CONFIG_SPARES;
3145 } else {
3146 sav = &spa->spa_l2cache;
3147 aux = ZPOOL_CONFIG_L2CACHE;
3148 }
3149
3150 mutex_enter(&ztest_vdev_lock);
3151
3152 spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
3153
3154 if (sav->sav_count != 0 && ztest_random(4) == 0) {
3155 /*
3156 * Pick a random device to remove.
3157 */
3158 guid = sav->sav_vdevs[ztest_random(sav->sav_count)]->vdev_guid;
3159 } else {
3160 /*
3161 * Find an unused device we can add.
3162 */
3163 zs->zs_vdev_aux = 0;
3164 for (;;) {
3165 int c;
3166 (void) snprintf(path, MAXPATHLEN, ztest_aux_template,
3167 ztest_opts.zo_dir, ztest_opts.zo_pool, aux,
3168 zs->zs_vdev_aux);
3169 for (c = 0; c < sav->sav_count; c++)
3170 if (strcmp(sav->sav_vdevs[c]->vdev_path,
3171 path) == 0)
3172 break;
3173 if (c == sav->sav_count &&
3174 vdev_lookup_by_path(rvd, path) == NULL)
3175 break;
3176 zs->zs_vdev_aux++;
3177 }
3178 }
3179
3180 spa_config_exit(spa, SCL_VDEV, FTAG);
3181
3182 if (guid == 0) {
3183 /*
3184 * Add a new device.
3185 */
3186 nvlist_t *nvroot = make_vdev_root(NULL, aux, NULL,
3187 (ztest_opts.zo_vdev_size * 5) / 4, 0, NULL, 0, 0, 1);
3188 error = spa_vdev_add(spa, nvroot);
3189
3190 switch (error) {
3191 case 0:
3192 break;
3193 default:
3194 fatal(0, "spa_vdev_add(%p) = %d", nvroot, error);
3195 }
3196 nvlist_free(nvroot);
3197 } else {
3198 /*
3199 * Remove an existing device. Sometimes, dirty its
3200 * vdev state first to make sure we handle removal
3201 * of devices that have pending state changes.
3202 */
3203 if (ztest_random(2) == 0)
3204 (void) vdev_online(spa, guid, 0, NULL);
3205
3206 error = spa_vdev_remove(spa, guid, B_FALSE);
3207
3208 switch (error) {
3209 case 0:
3210 case EBUSY:
3211 case ZFS_ERR_CHECKPOINT_EXISTS:
3212 case ZFS_ERR_DISCARDING_CHECKPOINT:
3213 break;
3214 default:
3215 fatal(0, "spa_vdev_remove(%llu) = %d", guid, error);
3216 }
3217 }
3218
3219 mutex_exit(&ztest_vdev_lock);
3220
3221 umem_free(path, MAXPATHLEN);
3222 }
3223
3224 /*
3225 * split a pool if it has mirror tlvdevs
3226 */
3227 /* ARGSUSED */
3228 void
3229 ztest_split_pool(ztest_ds_t *zd, uint64_t id)
3230 {
3231 ztest_shared_t *zs = ztest_shared;
3232 spa_t *spa = ztest_spa;
3233 vdev_t *rvd = spa->spa_root_vdev;
3234 nvlist_t *tree, **child, *config, *split, **schild;
3235 uint_t c, children, schildren = 0, lastlogid = 0;
3236 int error = 0;
3237
3238 if (ztest_opts.zo_mmp_test)
3239 return;
3240
3241 mutex_enter(&ztest_vdev_lock);
3242
3243 /* ensure we have a useable config; mirrors of raidz aren't supported */
3244 if (zs->zs_mirrors < 3 || ztest_opts.zo_raidz > 1) {
3245 mutex_exit(&ztest_vdev_lock);
3246 return;
3247 }
3248
3249 /* clean up the old pool, if any */
3250 (void) spa_destroy("splitp");
3251
3252 spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
3253
3254 /* generate a config from the existing config */
3255 mutex_enter(&spa->spa_props_lock);
3256 VERIFY(nvlist_lookup_nvlist(spa->spa_config, ZPOOL_CONFIG_VDEV_TREE,
3257 &tree) == 0);
3258 mutex_exit(&spa->spa_props_lock);
3259
3260 VERIFY(nvlist_lookup_nvlist_array(tree, ZPOOL_CONFIG_CHILDREN, &child,
3261 &children) == 0);
3262
3263 schild = malloc(rvd->vdev_children * sizeof (nvlist_t *));
3264 for (c = 0; c < children; c++) {
3265 vdev_t *tvd = rvd->vdev_child[c];
3266 nvlist_t **mchild;
3267 uint_t mchildren;
3268
3269 if (tvd->vdev_islog || tvd->vdev_ops == &vdev_hole_ops) {
3270 VERIFY(nvlist_alloc(&schild[schildren], NV_UNIQUE_NAME,
3271 0) == 0);
3272 VERIFY(nvlist_add_string(schild[schildren],
3273 ZPOOL_CONFIG_TYPE, VDEV_TYPE_HOLE) == 0);
3274 VERIFY(nvlist_add_uint64(schild[schildren],
3275 ZPOOL_CONFIG_IS_HOLE, 1) == 0);
3276 if (lastlogid == 0)
3277 lastlogid = schildren;
3278 ++schildren;
3279 continue;
3280 }
3281 lastlogid = 0;
3282 VERIFY(nvlist_lookup_nvlist_array(child[c],
3283 ZPOOL_CONFIG_CHILDREN, &mchild, &mchildren) == 0);
3284 VERIFY(nvlist_dup(mchild[0], &schild[schildren++], 0) == 0);
3285 }
3286
3287 /* OK, create a config that can be used to split */
3288 VERIFY(nvlist_alloc(&split, NV_UNIQUE_NAME, 0) == 0);
3289 VERIFY(nvlist_add_string(split, ZPOOL_CONFIG_TYPE,
3290 VDEV_TYPE_ROOT) == 0);
3291 VERIFY(nvlist_add_nvlist_array(split, ZPOOL_CONFIG_CHILDREN, schild,
3292 lastlogid != 0 ? lastlogid : schildren) == 0);
3293
3294 VERIFY(nvlist_alloc(&config, NV_UNIQUE_NAME, 0) == 0);
3295 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, split) == 0);
3296
3297 for (c = 0; c < schildren; c++)
3298 nvlist_free(schild[c]);
3299 free(schild);
3300 nvlist_free(split);
3301
3302 spa_config_exit(spa, SCL_VDEV, FTAG);
3303
3304 (void) pthread_rwlock_wrlock(&ztest_name_lock);
3305 error = spa_vdev_split_mirror(spa, "splitp", config, NULL, B_FALSE);
3306 (void) pthread_rwlock_unlock(&ztest_name_lock);
3307
3308 nvlist_free(config);
3309
3310 if (error == 0) {
3311 (void) printf("successful split - results:\n");
3312 mutex_enter(&spa_namespace_lock);
3313 show_pool_stats(spa);
3314 show_pool_stats(spa_lookup("splitp"));
3315 mutex_exit(&spa_namespace_lock);
3316 ++zs->zs_splits;
3317 --zs->zs_mirrors;
3318 }
3319 mutex_exit(&ztest_vdev_lock);
3320 }
3321
3322 /*
3323 * Verify that we can attach and detach devices.
3324 */
3325 /* ARGSUSED */
3326 void
3327 ztest_vdev_attach_detach(ztest_ds_t *zd, uint64_t id)
3328 {
3329 ztest_shared_t *zs = ztest_shared;
3330 spa_t *spa = ztest_spa;
3331 spa_aux_vdev_t *sav = &spa->spa_spares;
3332 vdev_t *rvd = spa->spa_root_vdev;
3333 vdev_t *oldvd, *newvd, *pvd;
3334 nvlist_t *root;
3335 uint64_t leaves;
3336 uint64_t leaf, top;
3337 uint64_t ashift = ztest_get_ashift();
3338 uint64_t oldguid, pguid;
3339 uint64_t oldsize, newsize;
3340 char *oldpath, *newpath;
3341 int replacing;
3342 int oldvd_has_siblings = B_FALSE;
3343 int newvd_is_spare = B_FALSE;
3344 int oldvd_is_log;
3345 int error, expected_error;
3346
3347 if (ztest_opts.zo_mmp_test)
3348 return;
3349
3350 oldpath = umem_alloc(MAXPATHLEN, UMEM_NOFAIL);
3351 newpath = umem_alloc(MAXPATHLEN, UMEM_NOFAIL);
3352
3353 mutex_enter(&ztest_vdev_lock);
3354 leaves = MAX(zs->zs_mirrors, 1) * ztest_opts.zo_raidz;
3355
3356 spa_config_enter(spa, SCL_ALL, FTAG, RW_WRITER);
3357
3358 /*
3359 * If a vdev is in the process of being removed, its removal may
3360 * finish while we are in progress, leading to an unexpected error
3361 * value. Don't bother trying to attach while we are in the middle
3362 * of removal.
3363 */
3364 if (ztest_device_removal_active) {
3365 spa_config_exit(spa, SCL_ALL, FTAG);
3366 mutex_exit(&ztest_vdev_lock);
3367 return;
3368 }
3369
3370 /*
3371 * Decide whether to do an attach or a replace.
3372 */
3373 replacing = ztest_random(2);
3374
3375 /*
3376 * Pick a random top-level vdev.
3377 */
3378 top = ztest_random_vdev_top(spa, B_TRUE);
3379
3380 /*
3381 * Pick a random leaf within it.
3382 */
3383 leaf = ztest_random(leaves);
3384
3385 /*
3386 * Locate this vdev.
3387 */
3388 oldvd = rvd->vdev_child[top];
3389
3390 /* pick a child from the mirror */
3391 if (zs->zs_mirrors >= 1) {
3392 ASSERT(oldvd->vdev_ops == &vdev_mirror_ops);
3393 ASSERT(oldvd->vdev_children >= zs->zs_mirrors);
3394 oldvd = oldvd->vdev_child[leaf / ztest_opts.zo_raidz];
3395 }
3396
3397 /* pick a child out of the raidz group */
3398 if (ztest_opts.zo_raidz > 1) {
3399 ASSERT(oldvd->vdev_ops == &vdev_raidz_ops);
3400 ASSERT(oldvd->vdev_children == ztest_opts.zo_raidz);
3401 oldvd = oldvd->vdev_child[leaf % ztest_opts.zo_raidz];
3402 }
3403
3404 /*
3405 * If we're already doing an attach or replace, oldvd may be a
3406 * mirror vdev -- in which case, pick a random child.
3407 */
3408 while (oldvd->vdev_children != 0) {
3409 oldvd_has_siblings = B_TRUE;
3410 ASSERT(oldvd->vdev_children >= 2);
3411 oldvd = oldvd->vdev_child[ztest_random(oldvd->vdev_children)];
3412 }
3413
3414 oldguid = oldvd->vdev_guid;
3415 oldsize = vdev_get_min_asize(oldvd);
3416 oldvd_is_log = oldvd->vdev_top->vdev_islog;
3417 (void) strcpy(oldpath, oldvd->vdev_path);
3418 pvd = oldvd->vdev_parent;
3419 pguid = pvd->vdev_guid;
3420
3421 /*
3422 * If oldvd has siblings, then half of the time, detach it.
3423 */
3424 if (oldvd_has_siblings && ztest_random(2) == 0) {
3425 spa_config_exit(spa, SCL_ALL, FTAG);
3426 error = spa_vdev_detach(spa, oldguid, pguid, B_FALSE);
3427 if (error != 0 && error != ENODEV && error != EBUSY &&
3428 error != ENOTSUP && error != ZFS_ERR_CHECKPOINT_EXISTS &&
3429 error != ZFS_ERR_DISCARDING_CHECKPOINT)
3430 fatal(0, "detach (%s) returned %d", oldpath, error);
3431 goto out;
3432 }
3433
3434 /*
3435 * For the new vdev, choose with equal probability between the two
3436 * standard paths (ending in either 'a' or 'b') or a random hot spare.
3437 */
3438 if (sav->sav_count != 0 && ztest_random(3) == 0) {
3439 newvd = sav->sav_vdevs[ztest_random(sav->sav_count)];
3440 newvd_is_spare = B_TRUE;
3441 (void) strcpy(newpath, newvd->vdev_path);
3442 } else {
3443 (void) snprintf(newpath, MAXPATHLEN, ztest_dev_template,
3444 ztest_opts.zo_dir, ztest_opts.zo_pool,
3445 top * leaves + leaf);
3446 if (ztest_random(2) == 0)
3447 newpath[strlen(newpath) - 1] = 'b';
3448 newvd = vdev_lookup_by_path(rvd, newpath);
3449 }
3450
3451 if (newvd) {
3452 /*
3453 * Reopen to ensure the vdev's asize field isn't stale.
3454 */
3455 vdev_reopen(newvd);
3456 newsize = vdev_get_min_asize(newvd);
3457 } else {
3458 /*
3459 * Make newsize a little bigger or smaller than oldsize.
3460 * If it's smaller, the attach should fail.
3461 * If it's larger, and we're doing a replace,
3462 * we should get dynamic LUN growth when we're done.
3463 */
3464 newsize = 10 * oldsize / (9 + ztest_random(3));
3465 }
3466
3467 /*
3468 * If pvd is not a mirror or root, the attach should fail with ENOTSUP,
3469 * unless it's a replace; in that case any non-replacing parent is OK.
3470 *
3471 * If newvd is already part of the pool, it should fail with EBUSY.
3472 *
3473 * If newvd is too small, it should fail with EOVERFLOW.
3474 */
3475 if (pvd->vdev_ops != &vdev_mirror_ops &&
3476 pvd->vdev_ops != &vdev_root_ops && (!replacing ||
3477 pvd->vdev_ops == &vdev_replacing_ops ||
3478 pvd->vdev_ops == &vdev_spare_ops))
3479 expected_error = ENOTSUP;
3480 else if (newvd_is_spare && (!replacing || oldvd_is_log))
3481 expected_error = ENOTSUP;
3482 else if (newvd == oldvd)
3483 expected_error = replacing ? 0 : EBUSY;
3484 else if (vdev_lookup_by_path(rvd, newpath) != NULL)
3485 expected_error = EBUSY;
3486 else if (newsize < oldsize)
3487 expected_error = EOVERFLOW;
3488 else if (ashift > oldvd->vdev_top->vdev_ashift)
3489 expected_error = EDOM;
3490 else
3491 expected_error = 0;
3492
3493 spa_config_exit(spa, SCL_ALL, FTAG);
3494
3495 /*
3496 * Build the nvlist describing newpath.
3497 */
3498 root = make_vdev_root(newpath, NULL, NULL, newvd == NULL ? newsize : 0,
3499 ashift, NULL, 0, 0, 1);
3500
3501 error = spa_vdev_attach(spa, oldguid, root, replacing);
3502
3503 nvlist_free(root);
3504
3505 /*
3506 * If our parent was the replacing vdev, but the replace completed,
3507 * then instead of failing with ENOTSUP we may either succeed,
3508 * fail with ENODEV, or fail with EOVERFLOW.
3509 */
3510 if (expected_error == ENOTSUP &&
3511 (error == 0 || error == ENODEV || error == EOVERFLOW))
3512 expected_error = error;
3513
3514 /*
3515 * If someone grew the LUN, the replacement may be too small.
3516 */
3517 if (error == EOVERFLOW || error == EBUSY)
3518 expected_error = error;
3519
3520 if (error == ZFS_ERR_CHECKPOINT_EXISTS ||
3521 error == ZFS_ERR_DISCARDING_CHECKPOINT)
3522 expected_error = error;
3523
3524 /* XXX workaround 6690467 */
3525 if (error != expected_error && expected_error != EBUSY) {
3526 fatal(0, "attach (%s %llu, %s %llu, %d) "
3527 "returned %d, expected %d",
3528 oldpath, oldsize, newpath,
3529 newsize, replacing, error, expected_error);
3530 }
3531 out:
3532 mutex_exit(&ztest_vdev_lock);
3533
3534 umem_free(oldpath, MAXPATHLEN);
3535 umem_free(newpath, MAXPATHLEN);
3536 }
3537
3538 /* ARGSUSED */
3539 void
3540 ztest_device_removal(ztest_ds_t *zd, uint64_t id)
3541 {
3542 spa_t *spa = ztest_spa;
3543 vdev_t *vd;
3544 uint64_t guid;
3545 int error;
3546
3547 mutex_enter(&ztest_vdev_lock);
3548
3549 if (ztest_device_removal_active) {
3550 mutex_exit(&ztest_vdev_lock);
3551 return;
3552 }
3553
3554 /*
3555 * Remove a random top-level vdev and wait for removal to finish.
3556 */
3557 spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
3558 vd = vdev_lookup_top(spa, ztest_random_vdev_top(spa, B_FALSE));
3559 guid = vd->vdev_guid;
3560 spa_config_exit(spa, SCL_VDEV, FTAG);
3561
3562 error = spa_vdev_remove(spa, guid, B_FALSE);
3563 if (error == 0) {
3564 ztest_device_removal_active = B_TRUE;
3565 mutex_exit(&ztest_vdev_lock);
3566
3567 /*
3568 * spa->spa_vdev_removal is created in a sync task that
3569 * is initiated via dsl_sync_task_nowait(). Since the
3570 * task may not run before spa_vdev_remove() returns, we
3571 * must wait at least 1 txg to ensure that the removal
3572 * struct has been created.
3573 */
3574 txg_wait_synced(spa_get_dsl(spa), 0);
3575
3576 while (spa->spa_removing_phys.sr_state == DSS_SCANNING)
3577 txg_wait_synced(spa_get_dsl(spa), 0);
3578 } else {
3579 mutex_exit(&ztest_vdev_lock);
3580 return;
3581 }
3582
3583 /*
3584 * The pool needs to be scrubbed after completing device removal.
3585 * Failure to do so may result in checksum errors due to the
3586 * strategy employed by ztest_fault_inject() when selecting which
3587 * offset are redundant and can be damaged.
3588 */
3589 error = spa_scan(spa, POOL_SCAN_SCRUB);
3590 if (error == 0) {
3591 while (dsl_scan_scrubbing(spa_get_dsl(spa)))
3592 txg_wait_synced(spa_get_dsl(spa), 0);
3593 }
3594
3595 mutex_enter(&ztest_vdev_lock);
3596 ztest_device_removal_active = B_FALSE;
3597 mutex_exit(&ztest_vdev_lock);
3598 }
3599
3600 /*
3601 * Callback function which expands the physical size of the vdev.
3602 */
3603 vdev_t *
3604 grow_vdev(vdev_t *vd, void *arg)
3605 {
3606 ASSERTV(spa_t *spa = vd->vdev_spa);
3607 size_t *newsize = arg;
3608 size_t fsize;
3609 int fd;
3610
3611 ASSERT(spa_config_held(spa, SCL_STATE, RW_READER) == SCL_STATE);
3612 ASSERT(vd->vdev_ops->vdev_op_leaf);
3613
3614 if ((fd = open(vd->vdev_path, O_RDWR)) == -1)
3615 return (vd);
3616
3617 fsize = lseek(fd, 0, SEEK_END);
3618 VERIFY(ftruncate(fd, *newsize) == 0);
3619
3620 if (ztest_opts.zo_verbose >= 6) {
3621 (void) printf("%s grew from %lu to %lu bytes\n",
3622 vd->vdev_path, (ulong_t)fsize, (ulong_t)*newsize);
3623 }
3624 (void) close(fd);
3625 return (NULL);
3626 }
3627
3628 /*
3629 * Callback function which expands a given vdev by calling vdev_online().
3630 */
3631 /* ARGSUSED */
3632 vdev_t *
3633 online_vdev(vdev_t *vd, void *arg)
3634 {
3635 spa_t *spa = vd->vdev_spa;
3636 vdev_t *tvd = vd->vdev_top;
3637 uint64_t guid = vd->vdev_guid;
3638 uint64_t generation = spa->spa_config_generation + 1;
3639 vdev_state_t newstate = VDEV_STATE_UNKNOWN;
3640 int error;
3641
3642 ASSERT(spa_config_held(spa, SCL_STATE, RW_READER) == SCL_STATE);
3643 ASSERT(vd->vdev_ops->vdev_op_leaf);
3644
3645 /* Calling vdev_online will initialize the new metaslabs */
3646 spa_config_exit(spa, SCL_STATE, spa);
3647 error = vdev_online(spa, guid, ZFS_ONLINE_EXPAND, &newstate);
3648 spa_config_enter(spa, SCL_STATE, spa, RW_READER);
3649
3650 /*
3651 * If vdev_online returned an error or the underlying vdev_open
3652 * failed then we abort the expand. The only way to know that
3653 * vdev_open fails is by checking the returned newstate.
3654 */
3655 if (error || newstate != VDEV_STATE_HEALTHY) {
3656 if (ztest_opts.zo_verbose >= 5) {
3657 (void) printf("Unable to expand vdev, state %llu, "
3658 "error %d\n", (u_longlong_t)newstate, error);
3659 }
3660 return (vd);
3661 }
3662 ASSERT3U(newstate, ==, VDEV_STATE_HEALTHY);
3663
3664 /*
3665 * Since we dropped the lock we need to ensure that we're
3666 * still talking to the original vdev. It's possible this
3667 * vdev may have been detached/replaced while we were
3668 * trying to online it.
3669 */
3670 if (generation != spa->spa_config_generation) {
3671 if (ztest_opts.zo_verbose >= 5) {
3672 (void) printf("vdev configuration has changed, "
3673 "guid %llu, state %llu, expected gen %llu, "
3674 "got gen %llu\n",
3675 (u_longlong_t)guid,
3676 (u_longlong_t)tvd->vdev_state,
3677 (u_longlong_t)generation,
3678 (u_longlong_t)spa->spa_config_generation);
3679 }
3680 return (vd);
3681 }
3682 return (NULL);
3683 }
3684
3685 /*
3686 * Traverse the vdev tree calling the supplied function.
3687 * We continue to walk the tree until we either have walked all
3688 * children or we receive a non-NULL return from the callback.
3689 * If a NULL callback is passed, then we just return back the first
3690 * leaf vdev we encounter.
3691 */
3692 vdev_t *
3693 vdev_walk_tree(vdev_t *vd, vdev_t *(*func)(vdev_t *, void *), void *arg)
3694 {
3695 uint_t c;
3696
3697 if (vd->vdev_ops->vdev_op_leaf) {
3698 if (func == NULL)
3699 return (vd);
3700 else
3701 return (func(vd, arg));
3702 }
3703
3704 for (c = 0; c < vd->vdev_children; c++) {
3705 vdev_t *cvd = vd->vdev_child[c];
3706 if ((cvd = vdev_walk_tree(cvd, func, arg)) != NULL)
3707 return (cvd);
3708 }
3709 return (NULL);
3710 }
3711
3712 /*
3713 * Verify that dynamic LUN growth works as expected.
3714 */
3715 /* ARGSUSED */
3716 void
3717 ztest_vdev_LUN_growth(ztest_ds_t *zd, uint64_t id)
3718 {
3719 spa_t *spa = ztest_spa;
3720 vdev_t *vd, *tvd;
3721 metaslab_class_t *mc;
3722 metaslab_group_t *mg;
3723 size_t psize, newsize;
3724 uint64_t top;
3725 uint64_t old_class_space, new_class_space, old_ms_count, new_ms_count;
3726
3727 mutex_enter(&ztest_checkpoint_lock);
3728 mutex_enter(&ztest_vdev_lock);
3729 spa_config_enter(spa, SCL_STATE, spa, RW_READER);
3730
3731 /*
3732 * If there is a vdev removal in progress, it could complete while
3733 * we are running, in which case we would not be able to verify
3734 * that the metaslab_class space increased (because it decreases
3735 * when the device removal completes).
3736 */
3737 if (ztest_device_removal_active) {
3738 spa_config_exit(spa, SCL_STATE, spa);
3739 mutex_exit(&ztest_vdev_lock);
3740 mutex_exit(&ztest_checkpoint_lock);
3741 return;
3742 }
3743
3744 top = ztest_random_vdev_top(spa, B_TRUE);
3745
3746 tvd = spa->spa_root_vdev->vdev_child[top];
3747 mg = tvd->vdev_mg;
3748 mc = mg->mg_class;
3749 old_ms_count = tvd->vdev_ms_count;
3750 old_class_space = metaslab_class_get_space(mc);
3751
3752 /*
3753 * Determine the size of the first leaf vdev associated with
3754 * our top-level device.
3755 */
3756 vd = vdev_walk_tree(tvd, NULL, NULL);
3757 ASSERT3P(vd, !=, NULL);
3758 ASSERT(vd->vdev_ops->vdev_op_leaf);
3759
3760 psize = vd->vdev_psize;
3761
3762 /*
3763 * We only try to expand the vdev if it's healthy, less than 4x its
3764 * original size, and it has a valid psize.
3765 */
3766 if (tvd->vdev_state != VDEV_STATE_HEALTHY ||
3767 psize == 0 || psize >= 4 * ztest_opts.zo_vdev_size) {
3768 spa_config_exit(spa, SCL_STATE, spa);
3769 mutex_exit(&ztest_vdev_lock);
3770 mutex_exit(&ztest_checkpoint_lock);
3771 return;
3772 }
3773 ASSERT(psize > 0);
3774 newsize = psize + MAX(psize / 8, SPA_MAXBLOCKSIZE);
3775 ASSERT3U(newsize, >, psize);
3776
3777 if (ztest_opts.zo_verbose >= 6) {
3778 (void) printf("Expanding LUN %s from %lu to %lu\n",
3779 vd->vdev_path, (ulong_t)psize, (ulong_t)newsize);
3780 }
3781
3782 /*
3783 * Growing the vdev is a two step process:
3784 * 1). expand the physical size (i.e. relabel)
3785 * 2). online the vdev to create the new metaslabs
3786 */
3787 if (vdev_walk_tree(tvd, grow_vdev, &newsize) != NULL ||
3788 vdev_walk_tree(tvd, online_vdev, NULL) != NULL ||
3789 tvd->vdev_state != VDEV_STATE_HEALTHY) {
3790 if (ztest_opts.zo_verbose >= 5) {
3791 (void) printf("Could not expand LUN because "
3792 "the vdev configuration changed.\n");
3793 }
3794 spa_config_exit(spa, SCL_STATE, spa);
3795 mutex_exit(&ztest_vdev_lock);
3796 mutex_exit(&ztest_checkpoint_lock);
3797 return;
3798 }
3799
3800 spa_config_exit(spa, SCL_STATE, spa);
3801
3802 /*
3803 * Expanding the LUN will update the config asynchronously,
3804 * thus we must wait for the async thread to complete any
3805 * pending tasks before proceeding.
3806 */
3807 for (;;) {
3808 boolean_t done;
3809 mutex_enter(&spa->spa_async_lock);
3810 done = (spa->spa_async_thread == NULL && !spa->spa_async_tasks);
3811 mutex_exit(&spa->spa_async_lock);
3812 if (done)
3813 break;
3814 txg_wait_synced(spa_get_dsl(spa), 0);
3815 (void) poll(NULL, 0, 100);
3816 }
3817
3818 spa_config_enter(spa, SCL_STATE, spa, RW_READER);
3819
3820 tvd = spa->spa_root_vdev->vdev_child[top];
3821 new_ms_count = tvd->vdev_ms_count;
3822 new_class_space = metaslab_class_get_space(mc);
3823
3824 if (tvd->vdev_mg != mg || mg->mg_class != mc) {
3825 if (ztest_opts.zo_verbose >= 5) {
3826 (void) printf("Could not verify LUN expansion due to "
3827 "intervening vdev offline or remove.\n");
3828 }
3829 spa_config_exit(spa, SCL_STATE, spa);
3830 mutex_exit(&ztest_vdev_lock);
3831 mutex_exit(&ztest_checkpoint_lock);
3832 return;
3833 }
3834
3835 /*
3836 * Make sure we were able to grow the vdev.
3837 */
3838 if (new_ms_count <= old_ms_count) {
3839 fatal(0, "LUN expansion failed: ms_count %llu < %llu\n",
3840 old_ms_count, new_ms_count);
3841 }
3842
3843 /*
3844 * Make sure we were able to grow the pool.
3845 */
3846 if (new_class_space <= old_class_space) {
3847 fatal(0, "LUN expansion failed: class_space %llu < %llu\n",
3848 old_class_space, new_class_space);
3849 }
3850
3851 if (ztest_opts.zo_verbose >= 5) {
3852 char oldnumbuf[NN_NUMBUF_SZ], newnumbuf[NN_NUMBUF_SZ];
3853
3854 nicenum(old_class_space, oldnumbuf, sizeof (oldnumbuf));
3855 nicenum(new_class_space, newnumbuf, sizeof (newnumbuf));
3856 (void) printf("%s grew from %s to %s\n",
3857 spa->spa_name, oldnumbuf, newnumbuf);
3858 }
3859
3860 spa_config_exit(spa, SCL_STATE, spa);
3861 mutex_exit(&ztest_vdev_lock);
3862 mutex_exit(&ztest_checkpoint_lock);
3863 }
3864
3865 /*
3866 * Verify that dmu_objset_{create,destroy,open,close} work as expected.
3867 */
3868 /* ARGSUSED */
3869 static void
3870 ztest_objset_create_cb(objset_t *os, void *arg, cred_t *cr, dmu_tx_t *tx)
3871 {
3872 /*
3873 * Create the objects common to all ztest datasets.
3874 */
3875 VERIFY(zap_create_claim(os, ZTEST_DIROBJ,
3876 DMU_OT_ZAP_OTHER, DMU_OT_NONE, 0, tx) == 0);
3877 }
3878
3879 static int
3880 ztest_dataset_create(char *dsname)
3881 {
3882 int err;
3883 uint64_t rand;
3884 dsl_crypto_params_t *dcp = NULL;
3885
3886 /*
3887 * 50% of the time, we create encrypted datasets
3888 * using a random cipher suite and a hard-coded
3889 * wrapping key.
3890 */
3891 rand = ztest_random(2);
3892 if (rand != 0) {
3893 nvlist_t *crypto_args = fnvlist_alloc();
3894 nvlist_t *props = fnvlist_alloc();
3895
3896 /* slight bias towards the default cipher suite */
3897 rand = ztest_random(ZIO_CRYPT_FUNCTIONS);
3898 if (rand < ZIO_CRYPT_AES_128_CCM)
3899 rand = ZIO_CRYPT_ON;
3900
3901 fnvlist_add_uint64(props,
3902 zfs_prop_to_name(ZFS_PROP_ENCRYPTION), rand);
3903 fnvlist_add_uint8_array(crypto_args, "wkeydata",
3904 (uint8_t *)ztest_wkeydata, WRAPPING_KEY_LEN);
3905
3906 /*
3907 * These parameters aren't really used by the kernel. They
3908 * are simply stored so that userspace knows how to load
3909 * the wrapping key.
3910 */
3911 fnvlist_add_uint64(props,
3912 zfs_prop_to_name(ZFS_PROP_KEYFORMAT), ZFS_KEYFORMAT_RAW);
3913 fnvlist_add_string(props,
3914 zfs_prop_to_name(ZFS_PROP_KEYLOCATION), "prompt");
3915 fnvlist_add_uint64(props,
3916 zfs_prop_to_name(ZFS_PROP_PBKDF2_SALT), 0ULL);
3917 fnvlist_add_uint64(props,
3918 zfs_prop_to_name(ZFS_PROP_PBKDF2_ITERS), 0ULL);
3919
3920 VERIFY0(dsl_crypto_params_create_nvlist(DCP_CMD_NONE, props,
3921 crypto_args, &dcp));
3922
3923 /*
3924 * Cycle through all available encryption implementations
3925 * to verify interoperability.
3926 */
3927 VERIFY0(gcm_impl_set("cycle"));
3928 VERIFY0(aes_impl_set("cycle"));
3929
3930 fnvlist_free(crypto_args);
3931 fnvlist_free(props);
3932 }
3933
3934 err = dmu_objset_create(dsname, DMU_OST_OTHER, 0, dcp,
3935 ztest_objset_create_cb, NULL);
3936 dsl_crypto_params_free(dcp, !!err);
3937
3938 rand = ztest_random(100);
3939 if (err || rand < 80)
3940 return (err);
3941
3942 if (ztest_opts.zo_verbose >= 5)
3943 (void) printf("Setting dataset %s to sync always\n", dsname);
3944 return (ztest_dsl_prop_set_uint64(dsname, ZFS_PROP_SYNC,
3945 ZFS_SYNC_ALWAYS, B_FALSE));
3946 }
3947
3948 /* ARGSUSED */
3949 static int
3950 ztest_objset_destroy_cb(const char *name, void *arg)
3951 {
3952 objset_t *os;
3953 dmu_object_info_t doi;
3954 int error;
3955
3956 /*
3957 * Verify that the dataset contains a directory object.
3958 */
3959 VERIFY0(ztest_dmu_objset_own(name, DMU_OST_OTHER, B_TRUE,
3960 B_TRUE, FTAG, &os));
3961 error = dmu_object_info(os, ZTEST_DIROBJ, &doi);
3962 if (error != ENOENT) {
3963 /* We could have crashed in the middle of destroying it */
3964 ASSERT0(error);
3965 ASSERT3U(doi.doi_type, ==, DMU_OT_ZAP_OTHER);
3966 ASSERT3S(doi.doi_physical_blocks_512, >=, 0);
3967 }
3968 dmu_objset_disown(os, B_TRUE, FTAG);
3969
3970 /*
3971 * Destroy the dataset.
3972 */
3973 if (strchr(name, '@') != NULL) {
3974 VERIFY0(dsl_destroy_snapshot(name, B_TRUE));
3975 } else {
3976 error = dsl_destroy_head(name);
3977 /* There could be a hold on this dataset */
3978 if (error != EBUSY)
3979 ASSERT0(error);
3980 }
3981 return (0);
3982 }
3983
3984 static boolean_t
3985 ztest_snapshot_create(char *osname, uint64_t id)
3986 {
3987 char snapname[ZFS_MAX_DATASET_NAME_LEN];
3988 int error;
3989
3990 (void) snprintf(snapname, sizeof (snapname), "%llu", (u_longlong_t)id);
3991
3992 error = dmu_objset_snapshot_one(osname, snapname);
3993 if (error == ENOSPC) {
3994 ztest_record_enospc(FTAG);
3995 return (B_FALSE);
3996 }
3997 if (error != 0 && error != EEXIST) {
3998 fatal(0, "ztest_snapshot_create(%s@%s) = %d", osname,
3999 snapname, error);
4000 }
4001 return (B_TRUE);
4002 }
4003
4004 static boolean_t
4005 ztest_snapshot_destroy(char *osname, uint64_t id)
4006 {
4007 char snapname[ZFS_MAX_DATASET_NAME_LEN];
4008 int error;
4009
4010 (void) snprintf(snapname, sizeof (snapname), "%s@%llu", osname,
4011 (u_longlong_t)id);
4012
4013 error = dsl_destroy_snapshot(snapname, B_FALSE);
4014 if (error != 0 && error != ENOENT)
4015 fatal(0, "ztest_snapshot_destroy(%s) = %d", snapname, error);
4016 return (B_TRUE);
4017 }
4018
4019 /* ARGSUSED */
4020 void
4021 ztest_dmu_objset_create_destroy(ztest_ds_t *zd, uint64_t id)
4022 {
4023 ztest_ds_t *zdtmp;
4024 int iters;
4025 int error;
4026 objset_t *os, *os2;
4027 char name[ZFS_MAX_DATASET_NAME_LEN];
4028 zilog_t *zilog;
4029 int i;
4030
4031 zdtmp = umem_alloc(sizeof (ztest_ds_t), UMEM_NOFAIL);
4032
4033 (void) pthread_rwlock_rdlock(&ztest_name_lock);
4034
4035 (void) snprintf(name, sizeof (name), "%s/temp_%llu",
4036 ztest_opts.zo_pool, (u_longlong_t)id);
4037
4038 /*
4039 * If this dataset exists from a previous run, process its replay log
4040 * half of the time. If we don't replay it, then dsl_destroy_head()
4041 * (invoked from ztest_objset_destroy_cb()) should just throw it away.
4042 */
4043 if (ztest_random(2) == 0 &&
4044 ztest_dmu_objset_own(name, DMU_OST_OTHER, B_FALSE,
4045 B_TRUE, FTAG, &os) == 0) {
4046 ztest_zd_init(zdtmp, NULL, os);
4047 zil_replay(os, zdtmp, ztest_replay_vector);
4048 ztest_zd_fini(zdtmp);
4049 dmu_objset_disown(os, B_TRUE, FTAG);
4050 }
4051
4052 /*
4053 * There may be an old instance of the dataset we're about to
4054 * create lying around from a previous run. If so, destroy it
4055 * and all of its snapshots.
4056 */
4057 (void) dmu_objset_find(name, ztest_objset_destroy_cb, NULL,
4058 DS_FIND_CHILDREN | DS_FIND_SNAPSHOTS);
4059
4060 /*
4061 * Verify that the destroyed dataset is no longer in the namespace.
4062 */
4063 VERIFY3U(ENOENT, ==, ztest_dmu_objset_own(name, DMU_OST_OTHER, B_TRUE,
4064 B_TRUE, FTAG, &os));
4065
4066 /*
4067 * Verify that we can create a new dataset.
4068 */
4069 error = ztest_dataset_create(name);
4070 if (error) {
4071 if (error == ENOSPC) {
4072 ztest_record_enospc(FTAG);
4073 goto out;
4074 }
4075 fatal(0, "dmu_objset_create(%s) = %d", name, error);
4076 }
4077
4078 VERIFY0(ztest_dmu_objset_own(name, DMU_OST_OTHER, B_FALSE, B_TRUE,
4079 FTAG, &os));
4080
4081 ztest_zd_init(zdtmp, NULL, os);
4082
4083 /*
4084 * Open the intent log for it.
4085 */
4086 zilog = zil_open(os, ztest_get_data);
4087
4088 /*
4089 * Put some objects in there, do a little I/O to them,
4090 * and randomly take a couple of snapshots along the way.
4091 */
4092 iters = ztest_random(5);
4093 for (i = 0; i < iters; i++) {
4094 ztest_dmu_object_alloc_free(zdtmp, id);
4095 if (ztest_random(iters) == 0)
4096 (void) ztest_snapshot_create(name, i);
4097 }
4098
4099 /*
4100 * Verify that we cannot create an existing dataset.
4101 */
4102 VERIFY3U(EEXIST, ==,
4103 dmu_objset_create(name, DMU_OST_OTHER, 0, NULL, NULL, NULL));
4104
4105 /*
4106 * Verify that we can hold an objset that is also owned.
4107 */
4108 VERIFY3U(0, ==, dmu_objset_hold(name, FTAG, &os2));
4109 dmu_objset_rele(os2, FTAG);
4110
4111 /*
4112 * Verify that we cannot own an objset that is already owned.
4113 */
4114 VERIFY3U(EBUSY, ==, ztest_dmu_objset_own(name, DMU_OST_OTHER,
4115 B_FALSE, B_TRUE, FTAG, &os2));
4116
4117 zil_close(zilog);
4118 dmu_objset_disown(os, B_TRUE, FTAG);
4119 ztest_zd_fini(zdtmp);
4120 out:
4121 (void) pthread_rwlock_unlock(&ztest_name_lock);
4122
4123 umem_free(zdtmp, sizeof (ztest_ds_t));
4124 }
4125
4126 /*
4127 * Verify that dmu_snapshot_{create,destroy,open,close} work as expected.
4128 */
4129 void
4130 ztest_dmu_snapshot_create_destroy(ztest_ds_t *zd, uint64_t id)
4131 {
4132 (void) pthread_rwlock_rdlock(&ztest_name_lock);
4133 (void) ztest_snapshot_destroy(zd->zd_name, id);
4134 (void) ztest_snapshot_create(zd->zd_name, id);
4135 (void) pthread_rwlock_unlock(&ztest_name_lock);
4136 }
4137
4138 /*
4139 * Cleanup non-standard snapshots and clones.
4140 */
4141 void
4142 ztest_dsl_dataset_cleanup(char *osname, uint64_t id)
4143 {
4144 char *snap1name;
4145 char *clone1name;
4146 char *snap2name;
4147 char *clone2name;
4148 char *snap3name;
4149 int error;
4150
4151 snap1name = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
4152 clone1name = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
4153 snap2name = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
4154 clone2name = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
4155 snap3name = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
4156
4157 (void) snprintf(snap1name, ZFS_MAX_DATASET_NAME_LEN,
4158 "%s@s1_%llu", osname, (u_longlong_t)id);
4159 (void) snprintf(clone1name, ZFS_MAX_DATASET_NAME_LEN,
4160 "%s/c1_%llu", osname, (u_longlong_t)id);
4161 (void) snprintf(snap2name, ZFS_MAX_DATASET_NAME_LEN,
4162 "%s@s2_%llu", clone1name, (u_longlong_t)id);
4163 (void) snprintf(clone2name, ZFS_MAX_DATASET_NAME_LEN,
4164 "%s/c2_%llu", osname, (u_longlong_t)id);
4165 (void) snprintf(snap3name, ZFS_MAX_DATASET_NAME_LEN,
4166 "%s@s3_%llu", clone1name, (u_longlong_t)id);
4167
4168 error = dsl_destroy_head(clone2name);
4169 if (error && error != ENOENT)
4170 fatal(0, "dsl_destroy_head(%s) = %d", clone2name, error);
4171 error = dsl_destroy_snapshot(snap3name, B_FALSE);
4172 if (error && error != ENOENT)
4173 fatal(0, "dsl_destroy_snapshot(%s) = %d", snap3name, error);
4174 error = dsl_destroy_snapshot(snap2name, B_FALSE);
4175 if (error && error != ENOENT)
4176 fatal(0, "dsl_destroy_snapshot(%s) = %d", snap2name, error);
4177 error = dsl_destroy_head(clone1name);
4178 if (error && error != ENOENT)
4179 fatal(0, "dsl_destroy_head(%s) = %d", clone1name, error);
4180 error = dsl_destroy_snapshot(snap1name, B_FALSE);
4181 if (error && error != ENOENT)
4182 fatal(0, "dsl_destroy_snapshot(%s) = %d", snap1name, error);
4183
4184 umem_free(snap1name, ZFS_MAX_DATASET_NAME_LEN);
4185 umem_free(clone1name, ZFS_MAX_DATASET_NAME_LEN);
4186 umem_free(snap2name, ZFS_MAX_DATASET_NAME_LEN);
4187 umem_free(clone2name, ZFS_MAX_DATASET_NAME_LEN);
4188 umem_free(snap3name, ZFS_MAX_DATASET_NAME_LEN);
4189 }
4190
4191 /*
4192 * Verify dsl_dataset_promote handles EBUSY
4193 */
4194 void
4195 ztest_dsl_dataset_promote_busy(ztest_ds_t *zd, uint64_t id)
4196 {
4197 objset_t *os;
4198 char *snap1name;
4199 char *clone1name;
4200 char *snap2name;
4201 char *clone2name;
4202 char *snap3name;
4203 char *osname = zd->zd_name;
4204 int error;
4205
4206 snap1name = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
4207 clone1name = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
4208 snap2name = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
4209 clone2name = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
4210 snap3name = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
4211
4212 (void) pthread_rwlock_rdlock(&ztest_name_lock);
4213
4214 ztest_dsl_dataset_cleanup(osname, id);
4215
4216 (void) snprintf(snap1name, ZFS_MAX_DATASET_NAME_LEN,
4217 "%s@s1_%llu", osname, (u_longlong_t)id);
4218 (void) snprintf(clone1name, ZFS_MAX_DATASET_NAME_LEN,
4219 "%s/c1_%llu", osname, (u_longlong_t)id);
4220 (void) snprintf(snap2name, ZFS_MAX_DATASET_NAME_LEN,
4221 "%s@s2_%llu", clone1name, (u_longlong_t)id);
4222 (void) snprintf(clone2name, ZFS_MAX_DATASET_NAME_LEN,
4223 "%s/c2_%llu", osname, (u_longlong_t)id);
4224 (void) snprintf(snap3name, ZFS_MAX_DATASET_NAME_LEN,
4225 "%s@s3_%llu", clone1name, (u_longlong_t)id);
4226
4227 error = dmu_objset_snapshot_one(osname, strchr(snap1name, '@') + 1);
4228 if (error && error != EEXIST) {
4229 if (error == ENOSPC) {
4230 ztest_record_enospc(FTAG);
4231 goto out;
4232 }
4233 fatal(0, "dmu_take_snapshot(%s) = %d", snap1name, error);
4234 }
4235
4236 error = dmu_objset_clone(clone1name, snap1name);
4237 if (error) {
4238 if (error == ENOSPC) {
4239 ztest_record_enospc(FTAG);
4240 goto out;
4241 }
4242 fatal(0, "dmu_objset_create(%s) = %d", clone1name, error);
4243 }
4244
4245 error = dmu_objset_snapshot_one(clone1name, strchr(snap2name, '@') + 1);
4246 if (error && error != EEXIST) {
4247 if (error == ENOSPC) {
4248 ztest_record_enospc(FTAG);
4249 goto out;
4250 }
4251 fatal(0, "dmu_open_snapshot(%s) = %d", snap2name, error);
4252 }
4253
4254 error = dmu_objset_snapshot_one(clone1name, strchr(snap3name, '@') + 1);
4255 if (error && error != EEXIST) {
4256 if (error == ENOSPC) {
4257 ztest_record_enospc(FTAG);
4258 goto out;
4259 }
4260 fatal(0, "dmu_open_snapshot(%s) = %d", snap3name, error);
4261 }
4262
4263 error = dmu_objset_clone(clone2name, snap3name);
4264 if (error) {
4265 if (error == ENOSPC) {
4266 ztest_record_enospc(FTAG);
4267 goto out;
4268 }
4269 fatal(0, "dmu_objset_create(%s) = %d", clone2name, error);
4270 }
4271
4272 error = ztest_dmu_objset_own(snap2name, DMU_OST_ANY, B_TRUE, B_TRUE,
4273 FTAG, &os);
4274 if (error)
4275 fatal(0, "dmu_objset_own(%s) = %d", snap2name, error);
4276 error = dsl_dataset_promote(clone2name, NULL);
4277 if (error == ENOSPC) {
4278 dmu_objset_disown(os, B_TRUE, FTAG);
4279 ztest_record_enospc(FTAG);
4280 goto out;
4281 }
4282 if (error != EBUSY)
4283 fatal(0, "dsl_dataset_promote(%s), %d, not EBUSY", clone2name,
4284 error);
4285 dmu_objset_disown(os, B_TRUE, FTAG);
4286
4287 out:
4288 ztest_dsl_dataset_cleanup(osname, id);
4289
4290 (void) pthread_rwlock_unlock(&ztest_name_lock);
4291
4292 umem_free(snap1name, ZFS_MAX_DATASET_NAME_LEN);
4293 umem_free(clone1name, ZFS_MAX_DATASET_NAME_LEN);
4294 umem_free(snap2name, ZFS_MAX_DATASET_NAME_LEN);
4295 umem_free(clone2name, ZFS_MAX_DATASET_NAME_LEN);
4296 umem_free(snap3name, ZFS_MAX_DATASET_NAME_LEN);
4297 }
4298
4299 #undef OD_ARRAY_SIZE
4300 #define OD_ARRAY_SIZE 4
4301
4302 /*
4303 * Verify that dmu_object_{alloc,free} work as expected.
4304 */
4305 void
4306 ztest_dmu_object_alloc_free(ztest_ds_t *zd, uint64_t id)
4307 {
4308 ztest_od_t *od;
4309 int batchsize;
4310 int size;
4311 int b;
4312
4313 size = sizeof (ztest_od_t) * OD_ARRAY_SIZE;
4314 od = umem_alloc(size, UMEM_NOFAIL);
4315 batchsize = OD_ARRAY_SIZE;
4316
4317 for (b = 0; b < batchsize; b++)
4318 ztest_od_init(od + b, id, FTAG, b, DMU_OT_UINT64_OTHER,
4319 0, 0, 0);
4320
4321 /*
4322 * Destroy the previous batch of objects, create a new batch,
4323 * and do some I/O on the new objects.
4324 */
4325 if (ztest_object_init(zd, od, size, B_TRUE) != 0)
4326 return;
4327
4328 while (ztest_random(4 * batchsize) != 0)
4329 ztest_io(zd, od[ztest_random(batchsize)].od_object,
4330 ztest_random(ZTEST_RANGE_LOCKS) << SPA_MAXBLOCKSHIFT);
4331
4332 umem_free(od, size);
4333 }
4334
4335 /*
4336 * Rewind the global allocator to verify object allocation backfilling.
4337 */
4338 void
4339 ztest_dmu_object_next_chunk(ztest_ds_t *zd, uint64_t id)
4340 {
4341 objset_t *os = zd->zd_os;
4342 int dnodes_per_chunk = 1 << dmu_object_alloc_chunk_shift;
4343 uint64_t object;
4344
4345 /*
4346 * Rewind the global allocator randomly back to a lower object number
4347 * to force backfilling and reclamation of recently freed dnodes.
4348 */
4349 mutex_enter(&os->os_obj_lock);
4350 object = ztest_random(os->os_obj_next_chunk);
4351 os->os_obj_next_chunk = P2ALIGN(object, dnodes_per_chunk);
4352 mutex_exit(&os->os_obj_lock);
4353 }
4354
4355 #undef OD_ARRAY_SIZE
4356 #define OD_ARRAY_SIZE 2
4357
4358 /*
4359 * Verify that dmu_{read,write} work as expected.
4360 */
4361 void
4362 ztest_dmu_read_write(ztest_ds_t *zd, uint64_t id)
4363 {
4364 int size;
4365 ztest_od_t *od;
4366
4367 objset_t *os = zd->zd_os;
4368 size = sizeof (ztest_od_t) * OD_ARRAY_SIZE;
4369 od = umem_alloc(size, UMEM_NOFAIL);
4370 dmu_tx_t *tx;
4371 int i, freeit, error;
4372 uint64_t n, s, txg;
4373 bufwad_t *packbuf, *bigbuf, *pack, *bigH, *bigT;
4374 uint64_t packobj, packoff, packsize, bigobj, bigoff, bigsize;
4375 uint64_t chunksize = (1000 + ztest_random(1000)) * sizeof (uint64_t);
4376 uint64_t regions = 997;
4377 uint64_t stride = 123456789ULL;
4378 uint64_t width = 40;
4379 int free_percent = 5;
4380
4381 /*
4382 * This test uses two objects, packobj and bigobj, that are always
4383 * updated together (i.e. in the same tx) so that their contents are
4384 * in sync and can be compared. Their contents relate to each other
4385 * in a simple way: packobj is a dense array of 'bufwad' structures,
4386 * while bigobj is a sparse array of the same bufwads. Specifically,
4387 * for any index n, there are three bufwads that should be identical:
4388 *
4389 * packobj, at offset n * sizeof (bufwad_t)
4390 * bigobj, at the head of the nth chunk
4391 * bigobj, at the tail of the nth chunk
4392 *
4393 * The chunk size is arbitrary. It doesn't have to be a power of two,
4394 * and it doesn't have any relation to the object blocksize.
4395 * The only requirement is that it can hold at least two bufwads.
4396 *
4397 * Normally, we write the bufwad to each of these locations.
4398 * However, free_percent of the time we instead write zeroes to
4399 * packobj and perform a dmu_free_range() on bigobj. By comparing
4400 * bigobj to packobj, we can verify that the DMU is correctly
4401 * tracking which parts of an object are allocated and free,
4402 * and that the contents of the allocated blocks are correct.
4403 */
4404
4405 /*
4406 * Read the directory info. If it's the first time, set things up.
4407 */
4408 ztest_od_init(od, id, FTAG, 0, DMU_OT_UINT64_OTHER, 0, 0, chunksize);
4409 ztest_od_init(od + 1, id, FTAG, 1, DMU_OT_UINT64_OTHER, 0, 0,
4410 chunksize);
4411
4412 if (ztest_object_init(zd, od, size, B_FALSE) != 0) {
4413 umem_free(od, size);
4414 return;
4415 }
4416
4417 bigobj = od[0].od_object;
4418 packobj = od[1].od_object;
4419 chunksize = od[0].od_gen;
4420 ASSERT(chunksize == od[1].od_gen);
4421
4422 /*
4423 * Prefetch a random chunk of the big object.
4424 * Our aim here is to get some async reads in flight
4425 * for blocks that we may free below; the DMU should
4426 * handle this race correctly.
4427 */
4428 n = ztest_random(regions) * stride + ztest_random(width);
4429 s = 1 + ztest_random(2 * width - 1);
4430 dmu_prefetch(os, bigobj, 0, n * chunksize, s * chunksize,
4431 ZIO_PRIORITY_SYNC_READ);
4432
4433 /*
4434 * Pick a random index and compute the offsets into packobj and bigobj.
4435 */
4436 n = ztest_random(regions) * stride + ztest_random(width);
4437 s = 1 + ztest_random(width - 1);
4438
4439 packoff = n * sizeof (bufwad_t);
4440 packsize = s * sizeof (bufwad_t);
4441
4442 bigoff = n * chunksize;
4443 bigsize = s * chunksize;
4444
4445 packbuf = umem_alloc(packsize, UMEM_NOFAIL);
4446 bigbuf = umem_alloc(bigsize, UMEM_NOFAIL);
4447
4448 /*
4449 * free_percent of the time, free a range of bigobj rather than
4450 * overwriting it.
4451 */
4452 freeit = (ztest_random(100) < free_percent);
4453
4454 /*
4455 * Read the current contents of our objects.
4456 */
4457 error = dmu_read(os, packobj, packoff, packsize, packbuf,
4458 DMU_READ_PREFETCH);
4459 ASSERT0(error);
4460 error = dmu_read(os, bigobj, bigoff, bigsize, bigbuf,
4461 DMU_READ_PREFETCH);
4462 ASSERT0(error);
4463
4464 /*
4465 * Get a tx for the mods to both packobj and bigobj.
4466 */
4467 tx = dmu_tx_create(os);
4468
4469 dmu_tx_hold_write(tx, packobj, packoff, packsize);
4470
4471 if (freeit)
4472 dmu_tx_hold_free(tx, bigobj, bigoff, bigsize);
4473 else
4474 dmu_tx_hold_write(tx, bigobj, bigoff, bigsize);
4475
4476 /* This accounts for setting the checksum/compression. */
4477 dmu_tx_hold_bonus(tx, bigobj);
4478
4479 txg = ztest_tx_assign(tx, TXG_MIGHTWAIT, FTAG);
4480 if (txg == 0) {
4481 umem_free(packbuf, packsize);
4482 umem_free(bigbuf, bigsize);
4483 umem_free(od, size);
4484 return;
4485 }
4486
4487 enum zio_checksum cksum;
4488 do {
4489 cksum = (enum zio_checksum)
4490 ztest_random_dsl_prop(ZFS_PROP_CHECKSUM);
4491 } while (cksum >= ZIO_CHECKSUM_LEGACY_FUNCTIONS);
4492 dmu_object_set_checksum(os, bigobj, cksum, tx);
4493
4494 enum zio_compress comp;
4495 do {
4496 comp = (enum zio_compress)
4497 ztest_random_dsl_prop(ZFS_PROP_COMPRESSION);
4498 } while (comp >= ZIO_COMPRESS_LEGACY_FUNCTIONS);
4499 dmu_object_set_compress(os, bigobj, comp, tx);
4500
4501 /*
4502 * For each index from n to n + s, verify that the existing bufwad
4503 * in packobj matches the bufwads at the head and tail of the
4504 * corresponding chunk in bigobj. Then update all three bufwads
4505 * with the new values we want to write out.
4506 */
4507 for (i = 0; i < s; i++) {
4508 /* LINTED */
4509 pack = (bufwad_t *)((char *)packbuf + i * sizeof (bufwad_t));
4510 /* LINTED */
4511 bigH = (bufwad_t *)((char *)bigbuf + i * chunksize);
4512 /* LINTED */
4513 bigT = (bufwad_t *)((char *)bigH + chunksize) - 1;
4514
4515 ASSERT((uintptr_t)bigH - (uintptr_t)bigbuf < bigsize);
4516 ASSERT((uintptr_t)bigT - (uintptr_t)bigbuf < bigsize);
4517
4518 if (pack->bw_txg > txg)
4519 fatal(0, "future leak: got %llx, open txg is %llx",
4520 pack->bw_txg, txg);
4521
4522 if (pack->bw_data != 0 && pack->bw_index != n + i)
4523 fatal(0, "wrong index: got %llx, wanted %llx+%llx",
4524 pack->bw_index, n, i);
4525
4526 if (bcmp(pack, bigH, sizeof (bufwad_t)) != 0)
4527 fatal(0, "pack/bigH mismatch in %p/%p", pack, bigH);
4528
4529 if (bcmp(pack, bigT, sizeof (bufwad_t)) != 0)
4530 fatal(0, "pack/bigT mismatch in %p/%p", pack, bigT);
4531
4532 if (freeit) {
4533 bzero(pack, sizeof (bufwad_t));
4534 } else {
4535 pack->bw_index = n + i;
4536 pack->bw_txg = txg;
4537 pack->bw_data = 1 + ztest_random(-2ULL);
4538 }
4539 *bigH = *pack;
4540 *bigT = *pack;
4541 }
4542
4543 /*
4544 * We've verified all the old bufwads, and made new ones.
4545 * Now write them out.
4546 */
4547 dmu_write(os, packobj, packoff, packsize, packbuf, tx);
4548
4549 if (freeit) {
4550 if (ztest_opts.zo_verbose >= 7) {
4551 (void) printf("freeing offset %llx size %llx"
4552 " txg %llx\n",
4553 (u_longlong_t)bigoff,
4554 (u_longlong_t)bigsize,
4555 (u_longlong_t)txg);
4556 }
4557 VERIFY(0 == dmu_free_range(os, bigobj, bigoff, bigsize, tx));
4558 } else {
4559 if (ztest_opts.zo_verbose >= 7) {
4560 (void) printf("writing offset %llx size %llx"
4561 " txg %llx\n",
4562 (u_longlong_t)bigoff,
4563 (u_longlong_t)bigsize,
4564 (u_longlong_t)txg);
4565 }
4566 dmu_write(os, bigobj, bigoff, bigsize, bigbuf, tx);
4567 }
4568
4569 dmu_tx_commit(tx);
4570
4571 /*
4572 * Sanity check the stuff we just wrote.
4573 */
4574 {
4575 void *packcheck = umem_alloc(packsize, UMEM_NOFAIL);
4576 void *bigcheck = umem_alloc(bigsize, UMEM_NOFAIL);
4577
4578 VERIFY(0 == dmu_read(os, packobj, packoff,
4579 packsize, packcheck, DMU_READ_PREFETCH));
4580 VERIFY(0 == dmu_read(os, bigobj, bigoff,
4581 bigsize, bigcheck, DMU_READ_PREFETCH));
4582
4583 ASSERT(bcmp(packbuf, packcheck, packsize) == 0);
4584 ASSERT(bcmp(bigbuf, bigcheck, bigsize) == 0);
4585
4586 umem_free(packcheck, packsize);
4587 umem_free(bigcheck, bigsize);
4588 }
4589
4590 umem_free(packbuf, packsize);
4591 umem_free(bigbuf, bigsize);
4592 umem_free(od, size);
4593 }
4594
4595 void
4596 compare_and_update_pbbufs(uint64_t s, bufwad_t *packbuf, bufwad_t *bigbuf,
4597 uint64_t bigsize, uint64_t n, uint64_t chunksize, uint64_t txg)
4598 {
4599 uint64_t i;
4600 bufwad_t *pack;
4601 bufwad_t *bigH;
4602 bufwad_t *bigT;
4603
4604 /*
4605 * For each index from n to n + s, verify that the existing bufwad
4606 * in packobj matches the bufwads at the head and tail of the
4607 * corresponding chunk in bigobj. Then update all three bufwads
4608 * with the new values we want to write out.
4609 */
4610 for (i = 0; i < s; i++) {
4611 /* LINTED */
4612 pack = (bufwad_t *)((char *)packbuf + i * sizeof (bufwad_t));
4613 /* LINTED */
4614 bigH = (bufwad_t *)((char *)bigbuf + i * chunksize);
4615 /* LINTED */
4616 bigT = (bufwad_t *)((char *)bigH + chunksize) - 1;
4617
4618 ASSERT((uintptr_t)bigH - (uintptr_t)bigbuf < bigsize);
4619 ASSERT((uintptr_t)bigT - (uintptr_t)bigbuf < bigsize);
4620
4621 if (pack->bw_txg > txg)
4622 fatal(0, "future leak: got %llx, open txg is %llx",
4623 pack->bw_txg, txg);
4624
4625 if (pack->bw_data != 0 && pack->bw_index != n + i)
4626 fatal(0, "wrong index: got %llx, wanted %llx+%llx",
4627 pack->bw_index, n, i);
4628
4629 if (bcmp(pack, bigH, sizeof (bufwad_t)) != 0)
4630 fatal(0, "pack/bigH mismatch in %p/%p", pack, bigH);
4631
4632 if (bcmp(pack, bigT, sizeof (bufwad_t)) != 0)
4633 fatal(0, "pack/bigT mismatch in %p/%p", pack, bigT);
4634
4635 pack->bw_index = n + i;
4636 pack->bw_txg = txg;
4637 pack->bw_data = 1 + ztest_random(-2ULL);
4638
4639 *bigH = *pack;
4640 *bigT = *pack;
4641 }
4642 }
4643
4644 #undef OD_ARRAY_SIZE
4645 #define OD_ARRAY_SIZE 2
4646
4647 void
4648 ztest_dmu_read_write_zcopy(ztest_ds_t *zd, uint64_t id)
4649 {
4650 objset_t *os = zd->zd_os;
4651 ztest_od_t *od;
4652 dmu_tx_t *tx;
4653 uint64_t i;
4654 int error;
4655 int size;
4656 uint64_t n, s, txg;
4657 bufwad_t *packbuf, *bigbuf;
4658 uint64_t packobj, packoff, packsize, bigobj, bigoff, bigsize;
4659 uint64_t blocksize = ztest_random_blocksize();
4660 uint64_t chunksize = blocksize;
4661 uint64_t regions = 997;
4662 uint64_t stride = 123456789ULL;
4663 uint64_t width = 9;
4664 dmu_buf_t *bonus_db;
4665 arc_buf_t **bigbuf_arcbufs;
4666 dmu_object_info_t doi;
4667
4668 size = sizeof (ztest_od_t) * OD_ARRAY_SIZE;
4669 od = umem_alloc(size, UMEM_NOFAIL);
4670
4671 /*
4672 * This test uses two objects, packobj and bigobj, that are always
4673 * updated together (i.e. in the same tx) so that their contents are
4674 * in sync and can be compared. Their contents relate to each other
4675 * in a simple way: packobj is a dense array of 'bufwad' structures,
4676 * while bigobj is a sparse array of the same bufwads. Specifically,
4677 * for any index n, there are three bufwads that should be identical:
4678 *
4679 * packobj, at offset n * sizeof (bufwad_t)
4680 * bigobj, at the head of the nth chunk
4681 * bigobj, at the tail of the nth chunk
4682 *
4683 * The chunk size is set equal to bigobj block size so that
4684 * dmu_assign_arcbuf_by_dbuf() can be tested for object updates.
4685 */
4686
4687 /*
4688 * Read the directory info. If it's the first time, set things up.
4689 */
4690 ztest_od_init(od, id, FTAG, 0, DMU_OT_UINT64_OTHER, blocksize, 0, 0);
4691 ztest_od_init(od + 1, id, FTAG, 1, DMU_OT_UINT64_OTHER, 0, 0,
4692 chunksize);
4693
4694
4695 if (ztest_object_init(zd, od, size, B_FALSE) != 0) {
4696 umem_free(od, size);
4697 return;
4698 }
4699
4700 bigobj = od[0].od_object;
4701 packobj = od[1].od_object;
4702 blocksize = od[0].od_blocksize;
4703 chunksize = blocksize;
4704 ASSERT(chunksize == od[1].od_gen);
4705
4706 VERIFY(dmu_object_info(os, bigobj, &doi) == 0);
4707 VERIFY(ISP2(doi.doi_data_block_size));
4708 VERIFY(chunksize == doi.doi_data_block_size);
4709 VERIFY(chunksize >= 2 * sizeof (bufwad_t));
4710
4711 /*
4712 * Pick a random index and compute the offsets into packobj and bigobj.
4713 */
4714 n = ztest_random(regions) * stride + ztest_random(width);
4715 s = 1 + ztest_random(width - 1);
4716
4717 packoff = n * sizeof (bufwad_t);
4718 packsize = s * sizeof (bufwad_t);
4719
4720 bigoff = n * chunksize;
4721 bigsize = s * chunksize;
4722
4723 packbuf = umem_zalloc(packsize, UMEM_NOFAIL);
4724 bigbuf = umem_zalloc(bigsize, UMEM_NOFAIL);
4725
4726 VERIFY3U(0, ==, dmu_bonus_hold(os, bigobj, FTAG, &bonus_db));
4727
4728 bigbuf_arcbufs = umem_zalloc(2 * s * sizeof (arc_buf_t *), UMEM_NOFAIL);
4729
4730 /*
4731 * Iteration 0 test zcopy for DB_UNCACHED dbufs.
4732 * Iteration 1 test zcopy to already referenced dbufs.
4733 * Iteration 2 test zcopy to dirty dbuf in the same txg.
4734 * Iteration 3 test zcopy to dbuf dirty in previous txg.
4735 * Iteration 4 test zcopy when dbuf is no longer dirty.
4736 * Iteration 5 test zcopy when it can't be done.
4737 * Iteration 6 one more zcopy write.
4738 */
4739 for (i = 0; i < 7; i++) {
4740 uint64_t j;
4741 uint64_t off;
4742
4743 /*
4744 * In iteration 5 (i == 5) use arcbufs
4745 * that don't match bigobj blksz to test
4746 * dmu_assign_arcbuf_by_dbuf() when it can't directly
4747 * assign an arcbuf to a dbuf.
4748 */
4749 for (j = 0; j < s; j++) {
4750 if (i != 5 || chunksize < (SPA_MINBLOCKSIZE * 2)) {
4751 bigbuf_arcbufs[j] =
4752 dmu_request_arcbuf(bonus_db, chunksize);
4753 } else {
4754 bigbuf_arcbufs[2 * j] =
4755 dmu_request_arcbuf(bonus_db, chunksize / 2);
4756 bigbuf_arcbufs[2 * j + 1] =
4757 dmu_request_arcbuf(bonus_db, chunksize / 2);
4758 }
4759 }
4760
4761 /*
4762 * Get a tx for the mods to both packobj and bigobj.
4763 */
4764 tx = dmu_tx_create(os);
4765
4766 dmu_tx_hold_write(tx, packobj, packoff, packsize);
4767 dmu_tx_hold_write(tx, bigobj, bigoff, bigsize);
4768
4769 txg = ztest_tx_assign(tx, TXG_MIGHTWAIT, FTAG);
4770 if (txg == 0) {
4771 umem_free(packbuf, packsize);
4772 umem_free(bigbuf, bigsize);
4773 for (j = 0; j < s; j++) {
4774 if (i != 5 ||
4775 chunksize < (SPA_MINBLOCKSIZE * 2)) {
4776 dmu_return_arcbuf(bigbuf_arcbufs[j]);
4777 } else {
4778 dmu_return_arcbuf(
4779 bigbuf_arcbufs[2 * j]);
4780 dmu_return_arcbuf(
4781 bigbuf_arcbufs[2 * j + 1]);
4782 }
4783 }
4784 umem_free(bigbuf_arcbufs, 2 * s * sizeof (arc_buf_t *));
4785 umem_free(od, size);
4786 dmu_buf_rele(bonus_db, FTAG);
4787 return;
4788 }
4789
4790 /*
4791 * 50% of the time don't read objects in the 1st iteration to
4792 * test dmu_assign_arcbuf_by_dbuf() for the case when there are
4793 * no existing dbufs for the specified offsets.
4794 */
4795 if (i != 0 || ztest_random(2) != 0) {
4796 error = dmu_read(os, packobj, packoff,
4797 packsize, packbuf, DMU_READ_PREFETCH);
4798 ASSERT0(error);
4799 error = dmu_read(os, bigobj, bigoff, bigsize,
4800 bigbuf, DMU_READ_PREFETCH);
4801 ASSERT0(error);
4802 }
4803 compare_and_update_pbbufs(s, packbuf, bigbuf, bigsize,
4804 n, chunksize, txg);
4805
4806 /*
4807 * We've verified all the old bufwads, and made new ones.
4808 * Now write them out.
4809 */
4810 dmu_write(os, packobj, packoff, packsize, packbuf, tx);
4811 if (ztest_opts.zo_verbose >= 7) {
4812 (void) printf("writing offset %llx size %llx"
4813 " txg %llx\n",
4814 (u_longlong_t)bigoff,
4815 (u_longlong_t)bigsize,
4816 (u_longlong_t)txg);
4817 }
4818 for (off = bigoff, j = 0; j < s; j++, off += chunksize) {
4819 dmu_buf_t *dbt;
4820 if (i != 5 || chunksize < (SPA_MINBLOCKSIZE * 2)) {
4821 bcopy((caddr_t)bigbuf + (off - bigoff),
4822 bigbuf_arcbufs[j]->b_data, chunksize);
4823 } else {
4824 bcopy((caddr_t)bigbuf + (off - bigoff),
4825 bigbuf_arcbufs[2 * j]->b_data,
4826 chunksize / 2);
4827 bcopy((caddr_t)bigbuf + (off - bigoff) +
4828 chunksize / 2,
4829 bigbuf_arcbufs[2 * j + 1]->b_data,
4830 chunksize / 2);
4831 }
4832
4833 if (i == 1) {
4834 VERIFY(dmu_buf_hold(os, bigobj, off,
4835 FTAG, &dbt, DMU_READ_NO_PREFETCH) == 0);
4836 }
4837 if (i != 5 || chunksize < (SPA_MINBLOCKSIZE * 2)) {
4838 dmu_assign_arcbuf_by_dbuf(bonus_db, off,
4839 bigbuf_arcbufs[j], tx);
4840 } else {
4841 dmu_assign_arcbuf_by_dbuf(bonus_db, off,
4842 bigbuf_arcbufs[2 * j], tx);
4843 dmu_assign_arcbuf_by_dbuf(bonus_db,
4844 off + chunksize / 2,
4845 bigbuf_arcbufs[2 * j + 1], tx);
4846 }
4847 if (i == 1) {
4848 dmu_buf_rele(dbt, FTAG);
4849 }
4850 }
4851 dmu_tx_commit(tx);
4852
4853 /*
4854 * Sanity check the stuff we just wrote.
4855 */
4856 {
4857 void *packcheck = umem_alloc(packsize, UMEM_NOFAIL);
4858 void *bigcheck = umem_alloc(bigsize, UMEM_NOFAIL);
4859
4860 VERIFY(0 == dmu_read(os, packobj, packoff,
4861 packsize, packcheck, DMU_READ_PREFETCH));
4862 VERIFY(0 == dmu_read(os, bigobj, bigoff,
4863 bigsize, bigcheck, DMU_READ_PREFETCH));
4864
4865 ASSERT(bcmp(packbuf, packcheck, packsize) == 0);
4866 ASSERT(bcmp(bigbuf, bigcheck, bigsize) == 0);
4867
4868 umem_free(packcheck, packsize);
4869 umem_free(bigcheck, bigsize);
4870 }
4871 if (i == 2) {
4872 txg_wait_open(dmu_objset_pool(os), 0);
4873 } else if (i == 3) {
4874 txg_wait_synced(dmu_objset_pool(os), 0);
4875 }
4876 }
4877
4878 dmu_buf_rele(bonus_db, FTAG);
4879 umem_free(packbuf, packsize);
4880 umem_free(bigbuf, bigsize);
4881 umem_free(bigbuf_arcbufs, 2 * s * sizeof (arc_buf_t *));
4882 umem_free(od, size);
4883 }
4884
4885 /* ARGSUSED */
4886 void
4887 ztest_dmu_write_parallel(ztest_ds_t *zd, uint64_t id)
4888 {
4889 ztest_od_t *od;
4890
4891 od = umem_alloc(sizeof (ztest_od_t), UMEM_NOFAIL);
4892 uint64_t offset = (1ULL << (ztest_random(20) + 43)) +
4893 (ztest_random(ZTEST_RANGE_LOCKS) << SPA_MAXBLOCKSHIFT);
4894
4895 /*
4896 * Have multiple threads write to large offsets in an object
4897 * to verify that parallel writes to an object -- even to the
4898 * same blocks within the object -- doesn't cause any trouble.
4899 */
4900 ztest_od_init(od, ID_PARALLEL, FTAG, 0, DMU_OT_UINT64_OTHER, 0, 0, 0);
4901
4902 if (ztest_object_init(zd, od, sizeof (ztest_od_t), B_FALSE) != 0)
4903 return;
4904
4905 while (ztest_random(10) != 0)
4906 ztest_io(zd, od->od_object, offset);
4907
4908 umem_free(od, sizeof (ztest_od_t));
4909 }
4910
4911 void
4912 ztest_dmu_prealloc(ztest_ds_t *zd, uint64_t id)
4913 {
4914 ztest_od_t *od;
4915 uint64_t offset = (1ULL << (ztest_random(4) + SPA_MAXBLOCKSHIFT)) +
4916 (ztest_random(ZTEST_RANGE_LOCKS) << SPA_MAXBLOCKSHIFT);
4917 uint64_t count = ztest_random(20) + 1;
4918 uint64_t blocksize = ztest_random_blocksize();
4919 void *data;
4920
4921 od = umem_alloc(sizeof (ztest_od_t), UMEM_NOFAIL);
4922
4923 ztest_od_init(od, id, FTAG, 0, DMU_OT_UINT64_OTHER, blocksize, 0, 0);
4924
4925 if (ztest_object_init(zd, od, sizeof (ztest_od_t),
4926 !ztest_random(2)) != 0) {
4927 umem_free(od, sizeof (ztest_od_t));
4928 return;
4929 }
4930
4931 if (ztest_truncate(zd, od->od_object, offset, count * blocksize) != 0) {
4932 umem_free(od, sizeof (ztest_od_t));
4933 return;
4934 }
4935
4936 ztest_prealloc(zd, od->od_object, offset, count * blocksize);
4937
4938 data = umem_zalloc(blocksize, UMEM_NOFAIL);
4939
4940 while (ztest_random(count) != 0) {
4941 uint64_t randoff = offset + (ztest_random(count) * blocksize);
4942 if (ztest_write(zd, od->od_object, randoff, blocksize,
4943 data) != 0)
4944 break;
4945 while (ztest_random(4) != 0)
4946 ztest_io(zd, od->od_object, randoff);
4947 }
4948
4949 umem_free(data, blocksize);
4950 umem_free(od, sizeof (ztest_od_t));
4951 }
4952
4953 /*
4954 * Verify that zap_{create,destroy,add,remove,update} work as expected.
4955 */
4956 #define ZTEST_ZAP_MIN_INTS 1
4957 #define ZTEST_ZAP_MAX_INTS 4
4958 #define ZTEST_ZAP_MAX_PROPS 1000
4959
4960 void
4961 ztest_zap(ztest_ds_t *zd, uint64_t id)
4962 {
4963 objset_t *os = zd->zd_os;
4964 ztest_od_t *od;
4965 uint64_t object;
4966 uint64_t txg, last_txg;
4967 uint64_t value[ZTEST_ZAP_MAX_INTS];
4968 uint64_t zl_ints, zl_intsize, prop;
4969 int i, ints;
4970 dmu_tx_t *tx;
4971 char propname[100], txgname[100];
4972 int error;
4973 char *hc[2] = { "s.acl.h", ".s.open.h.hyLZlg" };
4974
4975 od = umem_alloc(sizeof (ztest_od_t), UMEM_NOFAIL);
4976 ztest_od_init(od, id, FTAG, 0, DMU_OT_ZAP_OTHER, 0, 0, 0);
4977
4978 if (ztest_object_init(zd, od, sizeof (ztest_od_t),
4979 !ztest_random(2)) != 0)
4980 goto out;
4981
4982 object = od->od_object;
4983
4984 /*
4985 * Generate a known hash collision, and verify that
4986 * we can lookup and remove both entries.
4987 */
4988 tx = dmu_tx_create(os);
4989 dmu_tx_hold_zap(tx, object, B_TRUE, NULL);
4990 txg = ztest_tx_assign(tx, TXG_MIGHTWAIT, FTAG);
4991 if (txg == 0)
4992 goto out;
4993 for (i = 0; i < 2; i++) {
4994 value[i] = i;
4995 VERIFY3U(0, ==, zap_add(os, object, hc[i], sizeof (uint64_t),
4996 1, &value[i], tx));
4997 }
4998 for (i = 0; i < 2; i++) {
4999 VERIFY3U(EEXIST, ==, zap_add(os, object, hc[i],
5000 sizeof (uint64_t), 1, &value[i], tx));
5001 VERIFY3U(0, ==,
5002 zap_length(os, object, hc[i], &zl_intsize, &zl_ints));
5003 ASSERT3U(zl_intsize, ==, sizeof (uint64_t));
5004 ASSERT3U(zl_ints, ==, 1);
5005 }
5006 for (i = 0; i < 2; i++) {
5007 VERIFY3U(0, ==, zap_remove(os, object, hc[i], tx));
5008 }
5009 dmu_tx_commit(tx);
5010
5011 /*
5012 * Generate a buch of random entries.
5013 */
5014 ints = MAX(ZTEST_ZAP_MIN_INTS, object % ZTEST_ZAP_MAX_INTS);
5015
5016 prop = ztest_random(ZTEST_ZAP_MAX_PROPS);
5017 (void) sprintf(propname, "prop_%llu", (u_longlong_t)prop);
5018 (void) sprintf(txgname, "txg_%llu", (u_longlong_t)prop);
5019 bzero(value, sizeof (value));
5020 last_txg = 0;
5021
5022 /*
5023 * If these zap entries already exist, validate their contents.
5024 */
5025 error = zap_length(os, object, txgname, &zl_intsize, &zl_ints);
5026 if (error == 0) {
5027 ASSERT3U(zl_intsize, ==, sizeof (uint64_t));
5028 ASSERT3U(zl_ints, ==, 1);
5029
5030 VERIFY(zap_lookup(os, object, txgname, zl_intsize,
5031 zl_ints, &last_txg) == 0);
5032
5033 VERIFY(zap_length(os, object, propname, &zl_intsize,
5034 &zl_ints) == 0);
5035
5036 ASSERT3U(zl_intsize, ==, sizeof (uint64_t));
5037 ASSERT3U(zl_ints, ==, ints);
5038
5039 VERIFY(zap_lookup(os, object, propname, zl_intsize,
5040 zl_ints, value) == 0);
5041
5042 for (i = 0; i < ints; i++) {
5043 ASSERT3U(value[i], ==, last_txg + object + i);
5044 }
5045 } else {
5046 ASSERT3U(error, ==, ENOENT);
5047 }
5048
5049 /*
5050 * Atomically update two entries in our zap object.
5051 * The first is named txg_%llu, and contains the txg
5052 * in which the property was last updated. The second
5053 * is named prop_%llu, and the nth element of its value
5054 * should be txg + object + n.
5055 */
5056 tx = dmu_tx_create(os);
5057 dmu_tx_hold_zap(tx, object, B_TRUE, NULL);
5058 txg = ztest_tx_assign(tx, TXG_MIGHTWAIT, FTAG);
5059 if (txg == 0)
5060 goto out;
5061
5062 if (last_txg > txg)
5063 fatal(0, "zap future leak: old %llu new %llu", last_txg, txg);
5064
5065 for (i = 0; i < ints; i++)
5066 value[i] = txg + object + i;
5067
5068 VERIFY3U(0, ==, zap_update(os, object, txgname, sizeof (uint64_t),
5069 1, &txg, tx));
5070 VERIFY3U(0, ==, zap_update(os, object, propname, sizeof (uint64_t),
5071 ints, value, tx));
5072
5073 dmu_tx_commit(tx);
5074
5075 /*
5076 * Remove a random pair of entries.
5077 */
5078 prop = ztest_random(ZTEST_ZAP_MAX_PROPS);
5079 (void) sprintf(propname, "prop_%llu", (u_longlong_t)prop);
5080 (void) sprintf(txgname, "txg_%llu", (u_longlong_t)prop);
5081
5082 error = zap_length(os, object, txgname, &zl_intsize, &zl_ints);
5083
5084 if (error == ENOENT)
5085 goto out;
5086
5087 ASSERT0(error);
5088
5089 tx = dmu_tx_create(os);
5090 dmu_tx_hold_zap(tx, object, B_TRUE, NULL);
5091 txg = ztest_tx_assign(tx, TXG_MIGHTWAIT, FTAG);
5092 if (txg == 0)
5093 goto out;
5094 VERIFY3U(0, ==, zap_remove(os, object, txgname, tx));
5095 VERIFY3U(0, ==, zap_remove(os, object, propname, tx));
5096 dmu_tx_commit(tx);
5097 out:
5098 umem_free(od, sizeof (ztest_od_t));
5099 }
5100
5101 /*
5102 * Testcase to test the upgrading of a microzap to fatzap.
5103 */
5104 void
5105 ztest_fzap(ztest_ds_t *zd, uint64_t id)
5106 {
5107 objset_t *os = zd->zd_os;
5108 ztest_od_t *od;
5109 uint64_t object, txg;
5110 int i;
5111
5112 od = umem_alloc(sizeof (ztest_od_t), UMEM_NOFAIL);
5113 ztest_od_init(od, id, FTAG, 0, DMU_OT_ZAP_OTHER, 0, 0, 0);
5114
5115 if (ztest_object_init(zd, od, sizeof (ztest_od_t),
5116 !ztest_random(2)) != 0)
5117 goto out;
5118 object = od->od_object;
5119
5120 /*
5121 * Add entries to this ZAP and make sure it spills over
5122 * and gets upgraded to a fatzap. Also, since we are adding
5123 * 2050 entries we should see ptrtbl growth and leaf-block split.
5124 */
5125 for (i = 0; i < 2050; i++) {
5126 char name[ZFS_MAX_DATASET_NAME_LEN];
5127 uint64_t value = i;
5128 dmu_tx_t *tx;
5129 int error;
5130
5131 (void) snprintf(name, sizeof (name), "fzap-%llu-%llu",
5132 (u_longlong_t)id, (u_longlong_t)value);
5133
5134 tx = dmu_tx_create(os);
5135 dmu_tx_hold_zap(tx, object, B_TRUE, name);
5136 txg = ztest_tx_assign(tx, TXG_MIGHTWAIT, FTAG);
5137 if (txg == 0)
5138 goto out;
5139 error = zap_add(os, object, name, sizeof (uint64_t), 1,
5140 &value, tx);
5141 ASSERT(error == 0 || error == EEXIST);
5142 dmu_tx_commit(tx);
5143 }
5144 out:
5145 umem_free(od, sizeof (ztest_od_t));
5146 }
5147
5148 /* ARGSUSED */
5149 void
5150 ztest_zap_parallel(ztest_ds_t *zd, uint64_t id)
5151 {
5152 objset_t *os = zd->zd_os;
5153 ztest_od_t *od;
5154 uint64_t txg, object, count, wsize, wc, zl_wsize, zl_wc;
5155 dmu_tx_t *tx;
5156 int i, namelen, error;
5157 int micro = ztest_random(2);
5158 char name[20], string_value[20];
5159 void *data;
5160
5161 od = umem_alloc(sizeof (ztest_od_t), UMEM_NOFAIL);
5162 ztest_od_init(od, ID_PARALLEL, FTAG, micro, DMU_OT_ZAP_OTHER, 0, 0, 0);
5163
5164 if (ztest_object_init(zd, od, sizeof (ztest_od_t), B_FALSE) != 0) {
5165 umem_free(od, sizeof (ztest_od_t));
5166 return;
5167 }
5168
5169 object = od->od_object;
5170
5171 /*
5172 * Generate a random name of the form 'xxx.....' where each
5173 * x is a random printable character and the dots are dots.
5174 * There are 94 such characters, and the name length goes from
5175 * 6 to 20, so there are 94^3 * 15 = 12,458,760 possible names.
5176 */
5177 namelen = ztest_random(sizeof (name) - 5) + 5 + 1;
5178
5179 for (i = 0; i < 3; i++)
5180 name[i] = '!' + ztest_random('~' - '!' + 1);
5181 for (; i < namelen - 1; i++)
5182 name[i] = '.';
5183 name[i] = '\0';
5184
5185 if ((namelen & 1) || micro) {
5186 wsize = sizeof (txg);
5187 wc = 1;
5188 data = &txg;
5189 } else {
5190 wsize = 1;
5191 wc = namelen;
5192 data = string_value;
5193 }
5194
5195 count = -1ULL;
5196 VERIFY0(zap_count(os, object, &count));
5197 ASSERT(count != -1ULL);
5198
5199 /*
5200 * Select an operation: length, lookup, add, update, remove.
5201 */
5202 i = ztest_random(5);
5203
5204 if (i >= 2) {
5205 tx = dmu_tx_create(os);
5206 dmu_tx_hold_zap(tx, object, B_TRUE, NULL);
5207 txg = ztest_tx_assign(tx, TXG_MIGHTWAIT, FTAG);
5208 if (txg == 0) {
5209 umem_free(od, sizeof (ztest_od_t));
5210 return;
5211 }
5212 bcopy(name, string_value, namelen);
5213 } else {
5214 tx = NULL;
5215 txg = 0;
5216 bzero(string_value, namelen);
5217 }
5218
5219 switch (i) {
5220
5221 case 0:
5222 error = zap_length(os, object, name, &zl_wsize, &zl_wc);
5223 if (error == 0) {
5224 ASSERT3U(wsize, ==, zl_wsize);
5225 ASSERT3U(wc, ==, zl_wc);
5226 } else {
5227 ASSERT3U(error, ==, ENOENT);
5228 }
5229 break;
5230
5231 case 1:
5232 error = zap_lookup(os, object, name, wsize, wc, data);
5233 if (error == 0) {
5234 if (data == string_value &&
5235 bcmp(name, data, namelen) != 0)
5236 fatal(0, "name '%s' != val '%s' len %d",
5237 name, data, namelen);
5238 } else {
5239 ASSERT3U(error, ==, ENOENT);
5240 }
5241 break;
5242
5243 case 2:
5244 error = zap_add(os, object, name, wsize, wc, data, tx);
5245 ASSERT(error == 0 || error == EEXIST);
5246 break;
5247
5248 case 3:
5249 VERIFY(zap_update(os, object, name, wsize, wc, data, tx) == 0);
5250 break;
5251
5252 case 4:
5253 error = zap_remove(os, object, name, tx);
5254 ASSERT(error == 0 || error == ENOENT);
5255 break;
5256 }
5257
5258 if (tx != NULL)
5259 dmu_tx_commit(tx);
5260
5261 umem_free(od, sizeof (ztest_od_t));
5262 }
5263
5264 /*
5265 * Commit callback data.
5266 */
5267 typedef struct ztest_cb_data {
5268 list_node_t zcd_node;
5269 uint64_t zcd_txg;
5270 int zcd_expected_err;
5271 boolean_t zcd_added;
5272 boolean_t zcd_called;
5273 spa_t *zcd_spa;
5274 } ztest_cb_data_t;
5275
5276 /* This is the actual commit callback function */
5277 static void
5278 ztest_commit_callback(void *arg, int error)
5279 {
5280 ztest_cb_data_t *data = arg;
5281 uint64_t synced_txg;
5282
5283 VERIFY(data != NULL);
5284 VERIFY3S(data->zcd_expected_err, ==, error);
5285 VERIFY(!data->zcd_called);
5286
5287 synced_txg = spa_last_synced_txg(data->zcd_spa);
5288 if (data->zcd_txg > synced_txg)
5289 fatal(0, "commit callback of txg %" PRIu64 " called prematurely"
5290 ", last synced txg = %" PRIu64 "\n", data->zcd_txg,
5291 synced_txg);
5292
5293 data->zcd_called = B_TRUE;
5294
5295 if (error == ECANCELED) {
5296 ASSERT0(data->zcd_txg);
5297 ASSERT(!data->zcd_added);
5298
5299 /*
5300 * The private callback data should be destroyed here, but
5301 * since we are going to check the zcd_called field after
5302 * dmu_tx_abort(), we will destroy it there.
5303 */
5304 return;
5305 }
5306
5307 ASSERT(data->zcd_added);
5308 ASSERT3U(data->zcd_txg, !=, 0);
5309
5310 (void) mutex_enter(&zcl.zcl_callbacks_lock);
5311
5312 /* See if this cb was called more quickly */
5313 if ((synced_txg - data->zcd_txg) < zc_min_txg_delay)
5314 zc_min_txg_delay = synced_txg - data->zcd_txg;
5315
5316 /* Remove our callback from the list */
5317 list_remove(&zcl.zcl_callbacks, data);
5318
5319 (void) mutex_exit(&zcl.zcl_callbacks_lock);
5320
5321 umem_free(data, sizeof (ztest_cb_data_t));
5322 }
5323
5324 /* Allocate and initialize callback data structure */
5325 static ztest_cb_data_t *
5326 ztest_create_cb_data(objset_t *os, uint64_t txg)
5327 {
5328 ztest_cb_data_t *cb_data;
5329
5330 cb_data = umem_zalloc(sizeof (ztest_cb_data_t), UMEM_NOFAIL);
5331
5332 cb_data->zcd_txg = txg;
5333 cb_data->zcd_spa = dmu_objset_spa(os);
5334 list_link_init(&cb_data->zcd_node);
5335
5336 return (cb_data);
5337 }
5338
5339 /*
5340 * Commit callback test.
5341 */
5342 void
5343 ztest_dmu_commit_callbacks(ztest_ds_t *zd, uint64_t id)
5344 {
5345 objset_t *os = zd->zd_os;
5346 ztest_od_t *od;
5347 dmu_tx_t *tx;
5348 ztest_cb_data_t *cb_data[3], *tmp_cb;
5349 uint64_t old_txg, txg;
5350 int i, error = 0;
5351
5352 od = umem_alloc(sizeof (ztest_od_t), UMEM_NOFAIL);
5353 ztest_od_init(od, id, FTAG, 0, DMU_OT_UINT64_OTHER, 0, 0, 0);
5354
5355 if (ztest_object_init(zd, od, sizeof (ztest_od_t), B_FALSE) != 0) {
5356 umem_free(od, sizeof (ztest_od_t));
5357 return;
5358 }
5359
5360 tx = dmu_tx_create(os);
5361
5362 cb_data[0] = ztest_create_cb_data(os, 0);
5363 dmu_tx_callback_register(tx, ztest_commit_callback, cb_data[0]);
5364
5365 dmu_tx_hold_write(tx, od->od_object, 0, sizeof (uint64_t));
5366
5367 /* Every once in a while, abort the transaction on purpose */
5368 if (ztest_random(100) == 0)
5369 error = -1;
5370
5371 if (!error)
5372 error = dmu_tx_assign(tx, TXG_NOWAIT);
5373
5374 txg = error ? 0 : dmu_tx_get_txg(tx);
5375
5376 cb_data[0]->zcd_txg = txg;
5377 cb_data[1] = ztest_create_cb_data(os, txg);
5378 dmu_tx_callback_register(tx, ztest_commit_callback, cb_data[1]);
5379
5380 if (error) {
5381 /*
5382 * It's not a strict requirement to call the registered
5383 * callbacks from inside dmu_tx_abort(), but that's what
5384 * it's supposed to happen in the current implementation
5385 * so we will check for that.
5386 */
5387 for (i = 0; i < 2; i++) {
5388 cb_data[i]->zcd_expected_err = ECANCELED;
5389 VERIFY(!cb_data[i]->zcd_called);
5390 }
5391
5392 dmu_tx_abort(tx);
5393
5394 for (i = 0; i < 2; i++) {
5395 VERIFY(cb_data[i]->zcd_called);
5396 umem_free(cb_data[i], sizeof (ztest_cb_data_t));
5397 }
5398
5399 umem_free(od, sizeof (ztest_od_t));
5400 return;
5401 }
5402
5403 cb_data[2] = ztest_create_cb_data(os, txg);
5404 dmu_tx_callback_register(tx, ztest_commit_callback, cb_data[2]);
5405
5406 /*
5407 * Read existing data to make sure there isn't a future leak.
5408 */
5409 VERIFY(0 == dmu_read(os, od->od_object, 0, sizeof (uint64_t),
5410 &old_txg, DMU_READ_PREFETCH));
5411
5412 if (old_txg > txg)
5413 fatal(0, "future leak: got %" PRIu64 ", open txg is %" PRIu64,
5414 old_txg, txg);
5415
5416 dmu_write(os, od->od_object, 0, sizeof (uint64_t), &txg, tx);
5417
5418 (void) mutex_enter(&zcl.zcl_callbacks_lock);
5419
5420 /*
5421 * Since commit callbacks don't have any ordering requirement and since
5422 * it is theoretically possible for a commit callback to be called
5423 * after an arbitrary amount of time has elapsed since its txg has been
5424 * synced, it is difficult to reliably determine whether a commit
5425 * callback hasn't been called due to high load or due to a flawed
5426 * implementation.
5427 *
5428 * In practice, we will assume that if after a certain number of txgs a
5429 * commit callback hasn't been called, then most likely there's an
5430 * implementation bug..
5431 */
5432 tmp_cb = list_head(&zcl.zcl_callbacks);
5433 if (tmp_cb != NULL &&
5434 tmp_cb->zcd_txg + ZTEST_COMMIT_CB_THRESH < txg) {
5435 fatal(0, "Commit callback threshold exceeded, oldest txg: %"
5436 PRIu64 ", open txg: %" PRIu64 "\n", tmp_cb->zcd_txg, txg);
5437 }
5438
5439 /*
5440 * Let's find the place to insert our callbacks.
5441 *
5442 * Even though the list is ordered by txg, it is possible for the
5443 * insertion point to not be the end because our txg may already be
5444 * quiescing at this point and other callbacks in the open txg
5445 * (from other objsets) may have sneaked in.
5446 */
5447 tmp_cb = list_tail(&zcl.zcl_callbacks);
5448 while (tmp_cb != NULL && tmp_cb->zcd_txg > txg)
5449 tmp_cb = list_prev(&zcl.zcl_callbacks, tmp_cb);
5450
5451 /* Add the 3 callbacks to the list */
5452 for (i = 0; i < 3; i++) {
5453 if (tmp_cb == NULL)
5454 list_insert_head(&zcl.zcl_callbacks, cb_data[i]);
5455 else
5456 list_insert_after(&zcl.zcl_callbacks, tmp_cb,
5457 cb_data[i]);
5458
5459 cb_data[i]->zcd_added = B_TRUE;
5460 VERIFY(!cb_data[i]->zcd_called);
5461
5462 tmp_cb = cb_data[i];
5463 }
5464
5465 zc_cb_counter += 3;
5466
5467 (void) mutex_exit(&zcl.zcl_callbacks_lock);
5468
5469 dmu_tx_commit(tx);
5470
5471 umem_free(od, sizeof (ztest_od_t));
5472 }
5473
5474 /*
5475 * Visit each object in the dataset. Verify that its properties
5476 * are consistent what was stored in the block tag when it was created,
5477 * and that its unused bonus buffer space has not been overwritten.
5478 */
5479 /* ARGSUSED */
5480 void
5481 ztest_verify_dnode_bt(ztest_ds_t *zd, uint64_t id)
5482 {
5483 objset_t *os = zd->zd_os;
5484 uint64_t obj;
5485 int err = 0;
5486
5487 for (obj = 0; err == 0; err = dmu_object_next(os, &obj, FALSE, 0)) {
5488 ztest_block_tag_t *bt = NULL;
5489 dmu_object_info_t doi;
5490 dmu_buf_t *db;
5491
5492 ztest_object_lock(zd, obj, RL_READER);
5493 if (dmu_bonus_hold(os, obj, FTAG, &db) != 0) {
5494 ztest_object_unlock(zd, obj);
5495 continue;
5496 }
5497
5498 dmu_object_info_from_db(db, &doi);
5499 if (doi.doi_bonus_size >= sizeof (*bt))
5500 bt = ztest_bt_bonus(db);
5501
5502 if (bt && bt->bt_magic == BT_MAGIC) {
5503 ztest_bt_verify(bt, os, obj, doi.doi_dnodesize,
5504 bt->bt_offset, bt->bt_gen, bt->bt_txg,
5505 bt->bt_crtxg);
5506 ztest_verify_unused_bonus(db, bt, obj, os, bt->bt_gen);
5507 }
5508
5509 dmu_buf_rele(db, FTAG);
5510 ztest_object_unlock(zd, obj);
5511 }
5512 }
5513
5514 /* ARGSUSED */
5515 void
5516 ztest_dsl_prop_get_set(ztest_ds_t *zd, uint64_t id)
5517 {
5518 zfs_prop_t proplist[] = {
5519 ZFS_PROP_CHECKSUM,
5520 ZFS_PROP_COMPRESSION,
5521 ZFS_PROP_COPIES,
5522 ZFS_PROP_DEDUP
5523 };
5524 int p;
5525
5526 (void) pthread_rwlock_rdlock(&ztest_name_lock);
5527
5528 for (p = 0; p < sizeof (proplist) / sizeof (proplist[0]); p++)
5529 (void) ztest_dsl_prop_set_uint64(zd->zd_name, proplist[p],
5530 ztest_random_dsl_prop(proplist[p]), (int)ztest_random(2));
5531
5532 VERIFY0(ztest_dsl_prop_set_uint64(zd->zd_name, ZFS_PROP_RECORDSIZE,
5533 ztest_random_blocksize(), (int)ztest_random(2)));
5534
5535 (void) pthread_rwlock_unlock(&ztest_name_lock);
5536 }
5537
5538 /* ARGSUSED */
5539 void
5540 ztest_remap_blocks(ztest_ds_t *zd, uint64_t id)
5541 {
5542 (void) pthread_rwlock_rdlock(&ztest_name_lock);
5543
5544 int error = dmu_objset_remap_indirects(zd->zd_name);
5545 if (error == ENOSPC)
5546 error = 0;
5547 ASSERT0(error);
5548
5549 (void) pthread_rwlock_unlock(&ztest_name_lock);
5550 }
5551
5552 /* ARGSUSED */
5553 void
5554 ztest_spa_prop_get_set(ztest_ds_t *zd, uint64_t id)
5555 {
5556 nvlist_t *props = NULL;
5557
5558 (void) pthread_rwlock_rdlock(&ztest_name_lock);
5559
5560 (void) ztest_spa_prop_set_uint64(ZPOOL_PROP_DEDUPDITTO,
5561 ZIO_DEDUPDITTO_MIN + ztest_random(ZIO_DEDUPDITTO_MIN));
5562
5563 VERIFY0(spa_prop_get(ztest_spa, &props));
5564
5565 if (ztest_opts.zo_verbose >= 6)
5566 dump_nvlist(props, 4);
5567
5568 nvlist_free(props);
5569
5570 (void) pthread_rwlock_unlock(&ztest_name_lock);
5571 }
5572
5573 static int
5574 user_release_one(const char *snapname, const char *holdname)
5575 {
5576 nvlist_t *snaps, *holds;
5577 int error;
5578
5579 snaps = fnvlist_alloc();
5580 holds = fnvlist_alloc();
5581 fnvlist_add_boolean(holds, holdname);
5582 fnvlist_add_nvlist(snaps, snapname, holds);
5583 fnvlist_free(holds);
5584 error = dsl_dataset_user_release(snaps, NULL);
5585 fnvlist_free(snaps);
5586 return (error);
5587 }
5588
5589 /*
5590 * Test snapshot hold/release and deferred destroy.
5591 */
5592 void
5593 ztest_dmu_snapshot_hold(ztest_ds_t *zd, uint64_t id)
5594 {
5595 int error;
5596 objset_t *os = zd->zd_os;
5597 objset_t *origin;
5598 char snapname[100];
5599 char fullname[100];
5600 char clonename[100];
5601 char tag[100];
5602 char osname[ZFS_MAX_DATASET_NAME_LEN];
5603 nvlist_t *holds;
5604
5605 (void) pthread_rwlock_rdlock(&ztest_name_lock);
5606
5607 dmu_objset_name(os, osname);
5608
5609 (void) snprintf(snapname, sizeof (snapname), "sh1_%llu",
5610 (u_longlong_t)id);
5611 (void) snprintf(fullname, sizeof (fullname), "%s@%s", osname, snapname);
5612 (void) snprintf(clonename, sizeof (clonename),
5613 "%s/ch1_%llu", osname, (u_longlong_t)id);
5614 (void) snprintf(tag, sizeof (tag), "tag_%llu", (u_longlong_t)id);
5615
5616 /*
5617 * Clean up from any previous run.
5618 */
5619 error = dsl_destroy_head(clonename);
5620 if (error != ENOENT)
5621 ASSERT0(error);
5622 error = user_release_one(fullname, tag);
5623 if (error != ESRCH && error != ENOENT)
5624 ASSERT0(error);
5625 error = dsl_destroy_snapshot(fullname, B_FALSE);
5626 if (error != ENOENT)
5627 ASSERT0(error);
5628
5629 /*
5630 * Create snapshot, clone it, mark snap for deferred destroy,
5631 * destroy clone, verify snap was also destroyed.
5632 */
5633 error = dmu_objset_snapshot_one(osname, snapname);
5634 if (error) {
5635 if (error == ENOSPC) {
5636 ztest_record_enospc("dmu_objset_snapshot");
5637 goto out;
5638 }
5639 fatal(0, "dmu_objset_snapshot(%s) = %d", fullname, error);
5640 }
5641
5642 error = dmu_objset_clone(clonename, fullname);
5643 if (error) {
5644 if (error == ENOSPC) {
5645 ztest_record_enospc("dmu_objset_clone");
5646 goto out;
5647 }
5648 fatal(0, "dmu_objset_clone(%s) = %d", clonename, error);
5649 }
5650
5651 error = dsl_destroy_snapshot(fullname, B_TRUE);
5652 if (error) {
5653 fatal(0, "dsl_destroy_snapshot(%s, B_TRUE) = %d",
5654 fullname, error);
5655 }
5656
5657 error = dsl_destroy_head(clonename);
5658 if (error)
5659 fatal(0, "dsl_destroy_head(%s) = %d", clonename, error);
5660
5661 error = dmu_objset_hold(fullname, FTAG, &origin);
5662 if (error != ENOENT)
5663 fatal(0, "dmu_objset_hold(%s) = %d", fullname, error);
5664
5665 /*
5666 * Create snapshot, add temporary hold, verify that we can't
5667 * destroy a held snapshot, mark for deferred destroy,
5668 * release hold, verify snapshot was destroyed.
5669 */
5670 error = dmu_objset_snapshot_one(osname, snapname);
5671 if (error) {
5672 if (error == ENOSPC) {
5673 ztest_record_enospc("dmu_objset_snapshot");
5674 goto out;
5675 }
5676 fatal(0, "dmu_objset_snapshot(%s) = %d", fullname, error);
5677 }
5678
5679 holds = fnvlist_alloc();
5680 fnvlist_add_string(holds, fullname, tag);
5681 error = dsl_dataset_user_hold(holds, 0, NULL);
5682 fnvlist_free(holds);
5683
5684 if (error == ENOSPC) {
5685 ztest_record_enospc("dsl_dataset_user_hold");
5686 goto out;
5687 } else if (error) {
5688 fatal(0, "dsl_dataset_user_hold(%s, %s) = %u",
5689 fullname, tag, error);
5690 }
5691
5692 error = dsl_destroy_snapshot(fullname, B_FALSE);
5693 if (error != EBUSY) {
5694 fatal(0, "dsl_destroy_snapshot(%s, B_FALSE) = %d",
5695 fullname, error);
5696 }
5697
5698 error = dsl_destroy_snapshot(fullname, B_TRUE);
5699 if (error) {
5700 fatal(0, "dsl_destroy_snapshot(%s, B_TRUE) = %d",
5701 fullname, error);
5702 }
5703
5704 error = user_release_one(fullname, tag);
5705 if (error)
5706 fatal(0, "user_release_one(%s, %s) = %d", fullname, tag, error);
5707
5708 VERIFY3U(dmu_objset_hold(fullname, FTAG, &origin), ==, ENOENT);
5709
5710 out:
5711 (void) pthread_rwlock_unlock(&ztest_name_lock);
5712 }
5713
5714 /*
5715 * Inject random faults into the on-disk data.
5716 */
5717 /* ARGSUSED */
5718 void
5719 ztest_fault_inject(ztest_ds_t *zd, uint64_t id)
5720 {
5721 ztest_shared_t *zs = ztest_shared;
5722 spa_t *spa = ztest_spa;
5723 int fd;
5724 uint64_t offset;
5725 uint64_t leaves;
5726 uint64_t bad = 0x1990c0ffeedecadeull;
5727 uint64_t top, leaf;
5728 char *path0;
5729 char *pathrand;
5730 size_t fsize;
5731 int bshift = SPA_MAXBLOCKSHIFT + 2;
5732 int iters = 1000;
5733 int maxfaults;
5734 int mirror_save;
5735 vdev_t *vd0 = NULL;
5736 uint64_t guid0 = 0;
5737 boolean_t islog = B_FALSE;
5738
5739 path0 = umem_alloc(MAXPATHLEN, UMEM_NOFAIL);
5740 pathrand = umem_alloc(MAXPATHLEN, UMEM_NOFAIL);
5741
5742 mutex_enter(&ztest_vdev_lock);
5743
5744 /*
5745 * Device removal is in progress, fault injection must be disabled
5746 * until it completes and the pool is scrubbed. The fault injection
5747 * strategy for damaging blocks does not take in to account evacuated
5748 * blocks which may have already been damaged.
5749 */
5750 if (ztest_device_removal_active) {
5751 mutex_exit(&ztest_vdev_lock);
5752 goto out;
5753 }
5754
5755 maxfaults = MAXFAULTS(zs);
5756 leaves = MAX(zs->zs_mirrors, 1) * ztest_opts.zo_raidz;
5757 mirror_save = zs->zs_mirrors;
5758 mutex_exit(&ztest_vdev_lock);
5759
5760 ASSERT(leaves >= 1);
5761
5762 /*
5763 * Grab the name lock as reader. There are some operations
5764 * which don't like to have their vdevs changed while
5765 * they are in progress (i.e. spa_change_guid). Those
5766 * operations will have grabbed the name lock as writer.
5767 */
5768 (void) pthread_rwlock_rdlock(&ztest_name_lock);
5769
5770 /*
5771 * We need SCL_STATE here because we're going to look at vd0->vdev_tsd.
5772 */
5773 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
5774
5775 if (ztest_random(2) == 0) {
5776 /*
5777 * Inject errors on a normal data device or slog device.
5778 */
5779 top = ztest_random_vdev_top(spa, B_TRUE);
5780 leaf = ztest_random(leaves) + zs->zs_splits;
5781
5782 /*
5783 * Generate paths to the first leaf in this top-level vdev,
5784 * and to the random leaf we selected. We'll induce transient
5785 * write failures and random online/offline activity on leaf 0,
5786 * and we'll write random garbage to the randomly chosen leaf.
5787 */
5788 (void) snprintf(path0, MAXPATHLEN, ztest_dev_template,
5789 ztest_opts.zo_dir, ztest_opts.zo_pool,
5790 top * leaves + zs->zs_splits);
5791 (void) snprintf(pathrand, MAXPATHLEN, ztest_dev_template,
5792 ztest_opts.zo_dir, ztest_opts.zo_pool,
5793 top * leaves + leaf);
5794
5795 vd0 = vdev_lookup_by_path(spa->spa_root_vdev, path0);
5796 if (vd0 != NULL && vd0->vdev_top->vdev_islog)
5797 islog = B_TRUE;
5798
5799 /*
5800 * If the top-level vdev needs to be resilvered
5801 * then we only allow faults on the device that is
5802 * resilvering.
5803 */
5804 if (vd0 != NULL && maxfaults != 1 &&
5805 (!vdev_resilver_needed(vd0->vdev_top, NULL, NULL) ||
5806 vd0->vdev_resilver_txg != 0)) {
5807 /*
5808 * Make vd0 explicitly claim to be unreadable,
5809 * or unwriteable, or reach behind its back
5810 * and close the underlying fd. We can do this if
5811 * maxfaults == 0 because we'll fail and reexecute,
5812 * and we can do it if maxfaults >= 2 because we'll
5813 * have enough redundancy. If maxfaults == 1, the
5814 * combination of this with injection of random data
5815 * corruption below exceeds the pool's fault tolerance.
5816 */
5817 vdev_file_t *vf = vd0->vdev_tsd;
5818
5819 zfs_dbgmsg("injecting fault to vdev %llu; maxfaults=%d",
5820 (long long)vd0->vdev_id, (int)maxfaults);
5821
5822 if (vf != NULL && ztest_random(3) == 0) {
5823 (void) close(vf->vf_vnode->v_fd);
5824 vf->vf_vnode->v_fd = -1;
5825 } else if (ztest_random(2) == 0) {
5826 vd0->vdev_cant_read = B_TRUE;
5827 } else {
5828 vd0->vdev_cant_write = B_TRUE;
5829 }
5830 guid0 = vd0->vdev_guid;
5831 }
5832 } else {
5833 /*
5834 * Inject errors on an l2cache device.
5835 */
5836 spa_aux_vdev_t *sav = &spa->spa_l2cache;
5837
5838 if (sav->sav_count == 0) {
5839 spa_config_exit(spa, SCL_STATE, FTAG);
5840 (void) pthread_rwlock_unlock(&ztest_name_lock);
5841 goto out;
5842 }
5843 vd0 = sav->sav_vdevs[ztest_random(sav->sav_count)];
5844 guid0 = vd0->vdev_guid;
5845 (void) strcpy(path0, vd0->vdev_path);
5846 (void) strcpy(pathrand, vd0->vdev_path);
5847
5848 leaf = 0;
5849 leaves = 1;
5850 maxfaults = INT_MAX; /* no limit on cache devices */
5851 }
5852
5853 spa_config_exit(spa, SCL_STATE, FTAG);
5854 (void) pthread_rwlock_unlock(&ztest_name_lock);
5855
5856 /*
5857 * If we can tolerate two or more faults, or we're dealing
5858 * with a slog, randomly online/offline vd0.
5859 */
5860 if ((maxfaults >= 2 || islog) && guid0 != 0) {
5861 if (ztest_random(10) < 6) {
5862 int flags = (ztest_random(2) == 0 ?
5863 ZFS_OFFLINE_TEMPORARY : 0);
5864
5865 /*
5866 * We have to grab the zs_name_lock as writer to
5867 * prevent a race between offlining a slog and
5868 * destroying a dataset. Offlining the slog will
5869 * grab a reference on the dataset which may cause
5870 * dsl_destroy_head() to fail with EBUSY thus
5871 * leaving the dataset in an inconsistent state.
5872 */
5873 if (islog)
5874 (void) pthread_rwlock_wrlock(&ztest_name_lock);
5875
5876 VERIFY(vdev_offline(spa, guid0, flags) != EBUSY);
5877
5878 if (islog)
5879 (void) pthread_rwlock_unlock(&ztest_name_lock);
5880 } else {
5881 /*
5882 * Ideally we would like to be able to randomly
5883 * call vdev_[on|off]line without holding locks
5884 * to force unpredictable failures but the side
5885 * effects of vdev_[on|off]line prevent us from
5886 * doing so. We grab the ztest_vdev_lock here to
5887 * prevent a race between injection testing and
5888 * aux_vdev removal.
5889 */
5890 mutex_enter(&ztest_vdev_lock);
5891 (void) vdev_online(spa, guid0, 0, NULL);
5892 mutex_exit(&ztest_vdev_lock);
5893 }
5894 }
5895
5896 if (maxfaults == 0)
5897 goto out;
5898
5899 /*
5900 * We have at least single-fault tolerance, so inject data corruption.
5901 */
5902 fd = open(pathrand, O_RDWR);
5903
5904 if (fd == -1) /* we hit a gap in the device namespace */
5905 goto out;
5906
5907 fsize = lseek(fd, 0, SEEK_END);
5908
5909 while (--iters != 0) {
5910 /*
5911 * The offset must be chosen carefully to ensure that
5912 * we do not inject a given logical block with errors
5913 * on two different leaf devices, because ZFS can not
5914 * tolerate that (if maxfaults==1).
5915 *
5916 * We divide each leaf into chunks of size
5917 * (# leaves * SPA_MAXBLOCKSIZE * 4). Within each chunk
5918 * there is a series of ranges to which we can inject errors.
5919 * Each range can accept errors on only a single leaf vdev.
5920 * The error injection ranges are separated by ranges
5921 * which we will not inject errors on any device (DMZs).
5922 * Each DMZ must be large enough such that a single block
5923 * can not straddle it, so that a single block can not be
5924 * a target in two different injection ranges (on different
5925 * leaf vdevs).
5926 *
5927 * For example, with 3 leaves, each chunk looks like:
5928 * 0 to 32M: injection range for leaf 0
5929 * 32M to 64M: DMZ - no injection allowed
5930 * 64M to 96M: injection range for leaf 1
5931 * 96M to 128M: DMZ - no injection allowed
5932 * 128M to 160M: injection range for leaf 2
5933 * 160M to 192M: DMZ - no injection allowed
5934 */
5935 offset = ztest_random(fsize / (leaves << bshift)) *
5936 (leaves << bshift) + (leaf << bshift) +
5937 (ztest_random(1ULL << (bshift - 1)) & -8ULL);
5938
5939 /*
5940 * Only allow damage to the labels at one end of the vdev.
5941 *
5942 * If all labels are damaged, the device will be totally
5943 * inaccessible, which will result in loss of data,
5944 * because we also damage (parts of) the other side of
5945 * the mirror/raidz.
5946 *
5947 * Additionally, we will always have both an even and an
5948 * odd label, so that we can handle crashes in the
5949 * middle of vdev_config_sync().
5950 */
5951 if ((leaf & 1) == 0 && offset < VDEV_LABEL_START_SIZE)
5952 continue;
5953
5954 /*
5955 * The two end labels are stored at the "end" of the disk, but
5956 * the end of the disk (vdev_psize) is aligned to
5957 * sizeof (vdev_label_t).
5958 */
5959 uint64_t psize = P2ALIGN(fsize, sizeof (vdev_label_t));
5960 if ((leaf & 1) == 1 &&
5961 offset + sizeof (bad) > psize - VDEV_LABEL_END_SIZE)
5962 continue;
5963
5964 mutex_enter(&ztest_vdev_lock);
5965 if (mirror_save != zs->zs_mirrors) {
5966 mutex_exit(&ztest_vdev_lock);
5967 (void) close(fd);
5968 goto out;
5969 }
5970
5971 if (pwrite(fd, &bad, sizeof (bad), offset) != sizeof (bad))
5972 fatal(1, "can't inject bad word at 0x%llx in %s",
5973 offset, pathrand);
5974
5975 mutex_exit(&ztest_vdev_lock);
5976
5977 if (ztest_opts.zo_verbose >= 7)
5978 (void) printf("injected bad word into %s,"
5979 " offset 0x%llx\n", pathrand, (u_longlong_t)offset);
5980 }
5981
5982 (void) close(fd);
5983 out:
5984 umem_free(path0, MAXPATHLEN);
5985 umem_free(pathrand, MAXPATHLEN);
5986 }
5987
5988 /*
5989 * Verify that DDT repair works as expected.
5990 */
5991 void
5992 ztest_ddt_repair(ztest_ds_t *zd, uint64_t id)
5993 {
5994 ztest_shared_t *zs = ztest_shared;
5995 spa_t *spa = ztest_spa;
5996 objset_t *os = zd->zd_os;
5997 ztest_od_t *od;
5998 uint64_t object, blocksize, txg, pattern, psize;
5999 enum zio_checksum checksum = spa_dedup_checksum(spa);
6000 dmu_buf_t *db;
6001 dmu_tx_t *tx;
6002 abd_t *abd;
6003 blkptr_t blk;
6004 int copies = 2 * ZIO_DEDUPDITTO_MIN;
6005 int i;
6006
6007 blocksize = ztest_random_blocksize();
6008 blocksize = MIN(blocksize, 2048); /* because we write so many */
6009
6010 od = umem_alloc(sizeof (ztest_od_t), UMEM_NOFAIL);
6011 ztest_od_init(od, id, FTAG, 0, DMU_OT_UINT64_OTHER, blocksize, 0, 0);
6012
6013 if (ztest_object_init(zd, od, sizeof (ztest_od_t), B_FALSE) != 0) {
6014 umem_free(od, sizeof (ztest_od_t));
6015 return;
6016 }
6017
6018 /*
6019 * Take the name lock as writer to prevent anyone else from changing
6020 * the pool and dataset properies we need to maintain during this test.
6021 */
6022 (void) pthread_rwlock_wrlock(&ztest_name_lock);
6023
6024 if (ztest_dsl_prop_set_uint64(zd->zd_name, ZFS_PROP_DEDUP, checksum,
6025 B_FALSE) != 0 ||
6026 ztest_dsl_prop_set_uint64(zd->zd_name, ZFS_PROP_COPIES, 1,
6027 B_FALSE) != 0) {
6028 (void) pthread_rwlock_unlock(&ztest_name_lock);
6029 umem_free(od, sizeof (ztest_od_t));
6030 return;
6031 }
6032
6033 dmu_objset_stats_t dds;
6034 dsl_pool_config_enter(dmu_objset_pool(os), FTAG);
6035 dmu_objset_fast_stat(os, &dds);
6036 dsl_pool_config_exit(dmu_objset_pool(os), FTAG);
6037
6038 object = od[0].od_object;
6039 blocksize = od[0].od_blocksize;
6040 pattern = zs->zs_guid ^ dds.dds_guid;
6041
6042 ASSERT(object != 0);
6043
6044 tx = dmu_tx_create(os);
6045 dmu_tx_hold_write(tx, object, 0, copies * blocksize);
6046 txg = ztest_tx_assign(tx, TXG_WAIT, FTAG);
6047 if (txg == 0) {
6048 (void) pthread_rwlock_unlock(&ztest_name_lock);
6049 umem_free(od, sizeof (ztest_od_t));
6050 return;
6051 }
6052
6053 /*
6054 * Write all the copies of our block.
6055 */
6056 for (i = 0; i < copies; i++) {
6057 uint64_t offset = i * blocksize;
6058 int error = dmu_buf_hold(os, object, offset, FTAG, &db,
6059 DMU_READ_NO_PREFETCH);
6060 if (error != 0) {
6061 fatal(B_FALSE, "dmu_buf_hold(%p, %llu, %llu) = %u",
6062 os, (long long)object, (long long) offset, error);
6063 }
6064 ASSERT(db->db_offset == offset);
6065 ASSERT(db->db_size == blocksize);
6066 ASSERT(ztest_pattern_match(db->db_data, db->db_size, pattern) ||
6067 ztest_pattern_match(db->db_data, db->db_size, 0ULL));
6068 dmu_buf_will_fill(db, tx);
6069 ztest_pattern_set(db->db_data, db->db_size, pattern);
6070 dmu_buf_rele(db, FTAG);
6071 }
6072
6073 dmu_tx_commit(tx);
6074 txg_wait_synced(spa_get_dsl(spa), txg);
6075
6076 /*
6077 * Find out what block we got.
6078 */
6079 VERIFY0(dmu_buf_hold(os, object, 0, FTAG, &db,
6080 DMU_READ_NO_PREFETCH));
6081 blk = *((dmu_buf_impl_t *)db)->db_blkptr;
6082 dmu_buf_rele(db, FTAG);
6083
6084 /*
6085 * Damage the block. Dedup-ditto will save us when we read it later.
6086 */
6087 psize = BP_GET_PSIZE(&blk);
6088 abd = abd_alloc_linear(psize, B_TRUE);
6089 ztest_pattern_set(abd_to_buf(abd), psize, ~pattern);
6090
6091 (void) zio_wait(zio_rewrite(NULL, spa, 0, &blk,
6092 abd, psize, NULL, NULL, ZIO_PRIORITY_SYNC_WRITE,
6093 ZIO_FLAG_CANFAIL | ZIO_FLAG_INDUCE_DAMAGE, NULL));
6094
6095 abd_free(abd);
6096
6097 (void) pthread_rwlock_unlock(&ztest_name_lock);
6098 umem_free(od, sizeof (ztest_od_t));
6099 }
6100
6101 /*
6102 * Scrub the pool.
6103 */
6104 /* ARGSUSED */
6105 void
6106 ztest_scrub(ztest_ds_t *zd, uint64_t id)
6107 {
6108 spa_t *spa = ztest_spa;
6109
6110 /*
6111 * Scrub in progress by device removal.
6112 */
6113 if (ztest_device_removal_active)
6114 return;
6115
6116 (void) spa_scan(spa, POOL_SCAN_SCRUB);
6117 (void) poll(NULL, 0, 100); /* wait a moment, then force a restart */
6118 (void) spa_scan(spa, POOL_SCAN_SCRUB);
6119 }
6120
6121 /*
6122 * Change the guid for the pool.
6123 */
6124 /* ARGSUSED */
6125 void
6126 ztest_reguid(ztest_ds_t *zd, uint64_t id)
6127 {
6128 spa_t *spa = ztest_spa;
6129 uint64_t orig, load;
6130 int error;
6131
6132 if (ztest_opts.zo_mmp_test)
6133 return;
6134
6135 orig = spa_guid(spa);
6136 load = spa_load_guid(spa);
6137
6138 (void) pthread_rwlock_wrlock(&ztest_name_lock);
6139 error = spa_change_guid(spa);
6140 (void) pthread_rwlock_unlock(&ztest_name_lock);
6141
6142 if (error != 0)
6143 return;
6144
6145 if (ztest_opts.zo_verbose >= 4) {
6146 (void) printf("Changed guid old %llu -> %llu\n",
6147 (u_longlong_t)orig, (u_longlong_t)spa_guid(spa));
6148 }
6149
6150 VERIFY3U(orig, !=, spa_guid(spa));
6151 VERIFY3U(load, ==, spa_load_guid(spa));
6152 }
6153
6154 void
6155 ztest_fletcher(ztest_ds_t *zd, uint64_t id)
6156 {
6157 hrtime_t end = gethrtime() + NANOSEC;
6158
6159 while (gethrtime() <= end) {
6160 int run_count = 100;
6161 void *buf;
6162 struct abd *abd_data, *abd_meta;
6163 uint32_t size;
6164 int *ptr;
6165 int i;
6166 zio_cksum_t zc_ref;
6167 zio_cksum_t zc_ref_byteswap;
6168
6169 size = ztest_random_blocksize();
6170
6171 buf = umem_alloc(size, UMEM_NOFAIL);
6172 abd_data = abd_alloc(size, B_FALSE);
6173 abd_meta = abd_alloc(size, B_TRUE);
6174
6175 for (i = 0, ptr = buf; i < size / sizeof (*ptr); i++, ptr++)
6176 *ptr = ztest_random(UINT_MAX);
6177
6178 abd_copy_from_buf_off(abd_data, buf, 0, size);
6179 abd_copy_from_buf_off(abd_meta, buf, 0, size);
6180
6181 VERIFY0(fletcher_4_impl_set("scalar"));
6182 fletcher_4_native(buf, size, NULL, &zc_ref);
6183 fletcher_4_byteswap(buf, size, NULL, &zc_ref_byteswap);
6184
6185 VERIFY0(fletcher_4_impl_set("cycle"));
6186 while (run_count-- > 0) {
6187 zio_cksum_t zc;
6188 zio_cksum_t zc_byteswap;
6189
6190 fletcher_4_byteswap(buf, size, NULL, &zc_byteswap);
6191 fletcher_4_native(buf, size, NULL, &zc);
6192
6193 VERIFY0(bcmp(&zc, &zc_ref, sizeof (zc)));
6194 VERIFY0(bcmp(&zc_byteswap, &zc_ref_byteswap,
6195 sizeof (zc_byteswap)));
6196
6197 /* Test ABD - data */
6198 abd_fletcher_4_byteswap(abd_data, size, NULL,
6199 &zc_byteswap);
6200 abd_fletcher_4_native(abd_data, size, NULL, &zc);
6201
6202 VERIFY0(bcmp(&zc, &zc_ref, sizeof (zc)));
6203 VERIFY0(bcmp(&zc_byteswap, &zc_ref_byteswap,
6204 sizeof (zc_byteswap)));
6205
6206 /* Test ABD - metadata */
6207 abd_fletcher_4_byteswap(abd_meta, size, NULL,
6208 &zc_byteswap);
6209 abd_fletcher_4_native(abd_meta, size, NULL, &zc);
6210
6211 VERIFY0(bcmp(&zc, &zc_ref, sizeof (zc)));
6212 VERIFY0(bcmp(&zc_byteswap, &zc_ref_byteswap,
6213 sizeof (zc_byteswap)));
6214
6215 }
6216
6217 umem_free(buf, size);
6218 abd_free(abd_data);
6219 abd_free(abd_meta);
6220 }
6221 }
6222
6223 void
6224 ztest_fletcher_incr(ztest_ds_t *zd, uint64_t id)
6225 {
6226 void *buf;
6227 size_t size;
6228 int *ptr;
6229 int i;
6230 zio_cksum_t zc_ref;
6231 zio_cksum_t zc_ref_bswap;
6232
6233 hrtime_t end = gethrtime() + NANOSEC;
6234
6235 while (gethrtime() <= end) {
6236 int run_count = 100;
6237
6238 size = ztest_random_blocksize();
6239 buf = umem_alloc(size, UMEM_NOFAIL);
6240
6241 for (i = 0, ptr = buf; i < size / sizeof (*ptr); i++, ptr++)
6242 *ptr = ztest_random(UINT_MAX);
6243
6244 VERIFY0(fletcher_4_impl_set("scalar"));
6245 fletcher_4_native(buf, size, NULL, &zc_ref);
6246 fletcher_4_byteswap(buf, size, NULL, &zc_ref_bswap);
6247
6248 VERIFY0(fletcher_4_impl_set("cycle"));
6249
6250 while (run_count-- > 0) {
6251 zio_cksum_t zc;
6252 zio_cksum_t zc_bswap;
6253 size_t pos = 0;
6254
6255 ZIO_SET_CHECKSUM(&zc, 0, 0, 0, 0);
6256 ZIO_SET_CHECKSUM(&zc_bswap, 0, 0, 0, 0);
6257
6258 while (pos < size) {
6259 size_t inc = 64 * ztest_random(size / 67);
6260 /* sometimes add few bytes to test non-simd */
6261 if (ztest_random(100) < 10)
6262 inc += P2ALIGN(ztest_random(64),
6263 sizeof (uint32_t));
6264
6265 if (inc > (size - pos))
6266 inc = size - pos;
6267
6268 fletcher_4_incremental_native(buf + pos, inc,
6269 &zc);
6270 fletcher_4_incremental_byteswap(buf + pos, inc,
6271 &zc_bswap);
6272
6273 pos += inc;
6274 }
6275
6276 VERIFY3U(pos, ==, size);
6277
6278 VERIFY(ZIO_CHECKSUM_EQUAL(zc, zc_ref));
6279 VERIFY(ZIO_CHECKSUM_EQUAL(zc_bswap, zc_ref_bswap));
6280
6281 /*
6282 * verify if incremental on the whole buffer is
6283 * equivalent to non-incremental version
6284 */
6285 ZIO_SET_CHECKSUM(&zc, 0, 0, 0, 0);
6286 ZIO_SET_CHECKSUM(&zc_bswap, 0, 0, 0, 0);
6287
6288 fletcher_4_incremental_native(buf, size, &zc);
6289 fletcher_4_incremental_byteswap(buf, size, &zc_bswap);
6290
6291 VERIFY(ZIO_CHECKSUM_EQUAL(zc, zc_ref));
6292 VERIFY(ZIO_CHECKSUM_EQUAL(zc_bswap, zc_ref_bswap));
6293 }
6294
6295 umem_free(buf, size);
6296 }
6297 }
6298
6299 static int
6300 ztest_check_path(char *path)
6301 {
6302 struct stat s;
6303 /* return true on success */
6304 return (!stat(path, &s));
6305 }
6306
6307 static void
6308 ztest_get_zdb_bin(char *bin, int len)
6309 {
6310 char *zdb_path;
6311 /*
6312 * Try to use ZDB_PATH and in-tree zdb path. If not successful, just
6313 * let popen to search through PATH.
6314 */
6315 if ((zdb_path = getenv("ZDB_PATH"))) {
6316 strlcpy(bin, zdb_path, len); /* In env */
6317 if (!ztest_check_path(bin)) {
6318 ztest_dump_core = 0;
6319 fatal(1, "invalid ZDB_PATH '%s'", bin);
6320 }
6321 return;
6322 }
6323
6324 VERIFY(realpath(getexecname(), bin) != NULL);
6325 if (strstr(bin, "/ztest/")) {
6326 strstr(bin, "/ztest/")[0] = '\0'; /* In-tree */
6327 strcat(bin, "/zdb/zdb");
6328 if (ztest_check_path(bin))
6329 return;
6330 }
6331 strcpy(bin, "zdb");
6332 }
6333
6334 /*
6335 * Verify pool integrity by running zdb.
6336 */
6337 static void
6338 ztest_run_zdb(char *pool)
6339 {
6340 int status;
6341 char *bin;
6342 char *zdb;
6343 char *zbuf;
6344 const int len = MAXPATHLEN + MAXNAMELEN + 20;
6345 FILE *fp;
6346
6347 bin = umem_alloc(len, UMEM_NOFAIL);
6348 zdb = umem_alloc(len, UMEM_NOFAIL);
6349 zbuf = umem_alloc(1024, UMEM_NOFAIL);
6350
6351 ztest_get_zdb_bin(bin, len);
6352
6353 (void) sprintf(zdb,
6354 "%s -bcc%s%s -G -d -U %s "
6355 "-o zfs_reconstruct_indirect_combinations_max=65536 %s",
6356 bin,
6357 ztest_opts.zo_verbose >= 3 ? "s" : "",
6358 ztest_opts.zo_verbose >= 4 ? "v" : "",
6359 spa_config_path,
6360 pool);
6361
6362 if (ztest_opts.zo_verbose >= 5)
6363 (void) printf("Executing %s\n", strstr(zdb, "zdb "));
6364
6365 fp = popen(zdb, "r");
6366
6367 while (fgets(zbuf, 1024, fp) != NULL)
6368 if (ztest_opts.zo_verbose >= 3)
6369 (void) printf("%s", zbuf);
6370
6371 status = pclose(fp);
6372
6373 if (status == 0)
6374 goto out;
6375
6376 ztest_dump_core = 0;
6377 if (WIFEXITED(status))
6378 fatal(0, "'%s' exit code %d", zdb, WEXITSTATUS(status));
6379 else
6380 fatal(0, "'%s' died with signal %d", zdb, WTERMSIG(status));
6381 out:
6382 umem_free(bin, len);
6383 umem_free(zdb, len);
6384 umem_free(zbuf, 1024);
6385 }
6386
6387 static void
6388 ztest_walk_pool_directory(char *header)
6389 {
6390 spa_t *spa = NULL;
6391
6392 if (ztest_opts.zo_verbose >= 6)
6393 (void) printf("%s\n", header);
6394
6395 mutex_enter(&spa_namespace_lock);
6396 while ((spa = spa_next(spa)) != NULL)
6397 if (ztest_opts.zo_verbose >= 6)
6398 (void) printf("\t%s\n", spa_name(spa));
6399 mutex_exit(&spa_namespace_lock);
6400 }
6401
6402 static void
6403 ztest_spa_import_export(char *oldname, char *newname)
6404 {
6405 nvlist_t *config, *newconfig;
6406 uint64_t pool_guid;
6407 spa_t *spa;
6408 int error;
6409
6410 if (ztest_opts.zo_verbose >= 4) {
6411 (void) printf("import/export: old = %s, new = %s\n",
6412 oldname, newname);
6413 }
6414
6415 /*
6416 * Clean up from previous runs.
6417 */
6418 (void) spa_destroy(newname);
6419
6420 /*
6421 * Get the pool's configuration and guid.
6422 */
6423 VERIFY3U(0, ==, spa_open(oldname, &spa, FTAG));
6424
6425 /*
6426 * Kick off a scrub to tickle scrub/export races.
6427 */
6428 if (ztest_random(2) == 0)
6429 (void) spa_scan(spa, POOL_SCAN_SCRUB);
6430
6431 pool_guid = spa_guid(spa);
6432 spa_close(spa, FTAG);
6433
6434 ztest_walk_pool_directory("pools before export");
6435
6436 /*
6437 * Export it.
6438 */
6439 VERIFY3U(0, ==, spa_export(oldname, &config, B_FALSE, B_FALSE));
6440
6441 ztest_walk_pool_directory("pools after export");
6442
6443 /*
6444 * Try to import it.
6445 */
6446 newconfig = spa_tryimport(config);
6447 ASSERT(newconfig != NULL);
6448 nvlist_free(newconfig);
6449
6450 /*
6451 * Import it under the new name.
6452 */
6453 error = spa_import(newname, config, NULL, 0);
6454 if (error != 0) {
6455 dump_nvlist(config, 0);
6456 fatal(B_FALSE, "couldn't import pool %s as %s: error %u",
6457 oldname, newname, error);
6458 }
6459
6460 ztest_walk_pool_directory("pools after import");
6461
6462 /*
6463 * Try to import it again -- should fail with EEXIST.
6464 */
6465 VERIFY3U(EEXIST, ==, spa_import(newname, config, NULL, 0));
6466
6467 /*
6468 * Try to import it under a different name -- should fail with EEXIST.
6469 */
6470 VERIFY3U(EEXIST, ==, spa_import(oldname, config, NULL, 0));
6471
6472 /*
6473 * Verify that the pool is no longer visible under the old name.
6474 */
6475 VERIFY3U(ENOENT, ==, spa_open(oldname, &spa, FTAG));
6476
6477 /*
6478 * Verify that we can open and close the pool using the new name.
6479 */
6480 VERIFY3U(0, ==, spa_open(newname, &spa, FTAG));
6481 ASSERT(pool_guid == spa_guid(spa));
6482 spa_close(spa, FTAG);
6483
6484 nvlist_free(config);
6485 }
6486
6487 static void
6488 ztest_resume(spa_t *spa)
6489 {
6490 if (spa_suspended(spa) && ztest_opts.zo_verbose >= 6)
6491 (void) printf("resuming from suspended state\n");
6492 spa_vdev_state_enter(spa, SCL_NONE);
6493 vdev_clear(spa, NULL);
6494 (void) spa_vdev_state_exit(spa, NULL, 0);
6495 (void) zio_resume(spa);
6496 }
6497
6498 static void
6499 ztest_resume_thread(void *arg)
6500 {
6501 spa_t *spa = arg;
6502
6503 while (!ztest_exiting) {
6504 if (spa_suspended(spa))
6505 ztest_resume(spa);
6506 (void) poll(NULL, 0, 100);
6507
6508 /*
6509 * Periodically change the zfs_compressed_arc_enabled setting.
6510 */
6511 if (ztest_random(10) == 0)
6512 zfs_compressed_arc_enabled = ztest_random(2);
6513
6514 /*
6515 * Periodically change the zfs_abd_scatter_enabled setting.
6516 */
6517 if (ztest_random(10) == 0)
6518 zfs_abd_scatter_enabled = ztest_random(2);
6519 }
6520
6521 thread_exit();
6522 }
6523
6524 static void
6525 ztest_deadman_thread(void *arg)
6526 {
6527 ztest_shared_t *zs = arg;
6528 spa_t *spa = ztest_spa;
6529 hrtime_t delay, overdue, last_run = gethrtime();
6530
6531 delay = (zs->zs_thread_stop - zs->zs_thread_start) +
6532 MSEC2NSEC(zfs_deadman_synctime_ms);
6533
6534 while (!ztest_exiting) {
6535 /*
6536 * Wait for the delay timer while checking occasionally
6537 * if we should stop.
6538 */
6539 if (gethrtime() < last_run + delay) {
6540 (void) poll(NULL, 0, 1000);
6541 continue;
6542 }
6543
6544 /*
6545 * If the pool is suspended then fail immediately. Otherwise,
6546 * check to see if the pool is making any progress. If
6547 * vdev_deadman() discovers that there hasn't been any recent
6548 * I/Os then it will end up aborting the tests.
6549 */
6550 if (spa_suspended(spa) || spa->spa_root_vdev == NULL) {
6551 fatal(0, "aborting test after %llu seconds because "
6552 "pool has transitioned to a suspended state.",
6553 zfs_deadman_synctime_ms / 1000);
6554 }
6555 vdev_deadman(spa->spa_root_vdev, FTAG);
6556
6557 /*
6558 * If the process doesn't complete within a grace period of
6559 * zfs_deadman_synctime_ms over the expected finish time,
6560 * then it may be hung and is terminated.
6561 */
6562 overdue = zs->zs_proc_stop + MSEC2NSEC(zfs_deadman_synctime_ms);
6563 if (gethrtime() > overdue) {
6564 fatal(0, "aborting test after %llu seconds because "
6565 "the process is overdue for termination.",
6566 (gethrtime() - zs->zs_proc_start) / NANOSEC);
6567 }
6568
6569 (void) printf("ztest has been running for %lld seconds\n",
6570 (gethrtime() - zs->zs_proc_start) / NANOSEC);
6571
6572 last_run = gethrtime();
6573 delay = MSEC2NSEC(zfs_deadman_checktime_ms);
6574 }
6575
6576 thread_exit();
6577 }
6578
6579 static void
6580 ztest_execute(int test, ztest_info_t *zi, uint64_t id)
6581 {
6582 ztest_ds_t *zd = &ztest_ds[id % ztest_opts.zo_datasets];
6583 ztest_shared_callstate_t *zc = ZTEST_GET_SHARED_CALLSTATE(test);
6584 hrtime_t functime = gethrtime();
6585 int i;
6586
6587 for (i = 0; i < zi->zi_iters; i++)
6588 zi->zi_func(zd, id);
6589
6590 functime = gethrtime() - functime;
6591
6592 atomic_add_64(&zc->zc_count, 1);
6593 atomic_add_64(&zc->zc_time, functime);
6594
6595 if (ztest_opts.zo_verbose >= 4)
6596 (void) printf("%6.2f sec in %s\n",
6597 (double)functime / NANOSEC, zi->zi_funcname);
6598 }
6599
6600 static void
6601 ztest_thread(void *arg)
6602 {
6603 int rand;
6604 uint64_t id = (uintptr_t)arg;
6605 ztest_shared_t *zs = ztest_shared;
6606 uint64_t call_next;
6607 hrtime_t now;
6608 ztest_info_t *zi;
6609 ztest_shared_callstate_t *zc;
6610
6611 while ((now = gethrtime()) < zs->zs_thread_stop) {
6612 /*
6613 * See if it's time to force a crash.
6614 */
6615 if (now > zs->zs_thread_kill)
6616 ztest_kill(zs);
6617
6618 /*
6619 * If we're getting ENOSPC with some regularity, stop.
6620 */
6621 if (zs->zs_enospc_count > 10)
6622 break;
6623
6624 /*
6625 * Pick a random function to execute.
6626 */
6627 rand = ztest_random(ZTEST_FUNCS);
6628 zi = &ztest_info[rand];
6629 zc = ZTEST_GET_SHARED_CALLSTATE(rand);
6630 call_next = zc->zc_next;
6631
6632 if (now >= call_next &&
6633 atomic_cas_64(&zc->zc_next, call_next, call_next +
6634 ztest_random(2 * zi->zi_interval[0] + 1)) == call_next) {
6635 ztest_execute(rand, zi, id);
6636 }
6637 }
6638
6639 thread_exit();
6640 }
6641
6642 static void
6643 ztest_dataset_name(char *dsname, char *pool, int d)
6644 {
6645 (void) snprintf(dsname, ZFS_MAX_DATASET_NAME_LEN, "%s/ds_%d", pool, d);
6646 }
6647
6648 static void
6649 ztest_dataset_destroy(int d)
6650 {
6651 char name[ZFS_MAX_DATASET_NAME_LEN];
6652 int t;
6653
6654 ztest_dataset_name(name, ztest_opts.zo_pool, d);
6655
6656 if (ztest_opts.zo_verbose >= 3)
6657 (void) printf("Destroying %s to free up space\n", name);
6658
6659 /*
6660 * Cleanup any non-standard clones and snapshots. In general,
6661 * ztest thread t operates on dataset (t % zopt_datasets),
6662 * so there may be more than one thing to clean up.
6663 */
6664 for (t = d; t < ztest_opts.zo_threads;
6665 t += ztest_opts.zo_datasets)
6666 ztest_dsl_dataset_cleanup(name, t);
6667
6668 (void) dmu_objset_find(name, ztest_objset_destroy_cb, NULL,
6669 DS_FIND_SNAPSHOTS | DS_FIND_CHILDREN);
6670 }
6671
6672 static void
6673 ztest_dataset_dirobj_verify(ztest_ds_t *zd)
6674 {
6675 uint64_t usedobjs, dirobjs, scratch;
6676
6677 /*
6678 * ZTEST_DIROBJ is the object directory for the entire dataset.
6679 * Therefore, the number of objects in use should equal the
6680 * number of ZTEST_DIROBJ entries, +1 for ZTEST_DIROBJ itself.
6681 * If not, we have an object leak.
6682 *
6683 * Note that we can only check this in ztest_dataset_open(),
6684 * when the open-context and syncing-context values agree.
6685 * That's because zap_count() returns the open-context value,
6686 * while dmu_objset_space() returns the rootbp fill count.
6687 */
6688 VERIFY3U(0, ==, zap_count(zd->zd_os, ZTEST_DIROBJ, &dirobjs));
6689 dmu_objset_space(zd->zd_os, &scratch, &scratch, &usedobjs, &scratch);
6690 ASSERT3U(dirobjs + 1, ==, usedobjs);
6691 }
6692
6693 static int
6694 ztest_dataset_open(int d)
6695 {
6696 ztest_ds_t *zd = &ztest_ds[d];
6697 uint64_t committed_seq = ZTEST_GET_SHARED_DS(d)->zd_seq;
6698 objset_t *os;
6699 zilog_t *zilog;
6700 char name[ZFS_MAX_DATASET_NAME_LEN];
6701 int error;
6702
6703 ztest_dataset_name(name, ztest_opts.zo_pool, d);
6704
6705 (void) pthread_rwlock_rdlock(&ztest_name_lock);
6706
6707 error = ztest_dataset_create(name);
6708 if (error == ENOSPC) {
6709 (void) pthread_rwlock_unlock(&ztest_name_lock);
6710 ztest_record_enospc(FTAG);
6711 return (error);
6712 }
6713 ASSERT(error == 0 || error == EEXIST);
6714
6715 VERIFY0(ztest_dmu_objset_own(name, DMU_OST_OTHER, B_FALSE,
6716 B_TRUE, zd, &os));
6717 (void) pthread_rwlock_unlock(&ztest_name_lock);
6718
6719 ztest_zd_init(zd, ZTEST_GET_SHARED_DS(d), os);
6720
6721 zilog = zd->zd_zilog;
6722
6723 if (zilog->zl_header->zh_claim_lr_seq != 0 &&
6724 zilog->zl_header->zh_claim_lr_seq < committed_seq)
6725 fatal(0, "missing log records: claimed %llu < committed %llu",
6726 zilog->zl_header->zh_claim_lr_seq, committed_seq);
6727
6728 ztest_dataset_dirobj_verify(zd);
6729
6730 zil_replay(os, zd, ztest_replay_vector);
6731
6732 ztest_dataset_dirobj_verify(zd);
6733
6734 if (ztest_opts.zo_verbose >= 6)
6735 (void) printf("%s replay %llu blocks, %llu records, seq %llu\n",
6736 zd->zd_name,
6737 (u_longlong_t)zilog->zl_parse_blk_count,
6738 (u_longlong_t)zilog->zl_parse_lr_count,
6739 (u_longlong_t)zilog->zl_replaying_seq);
6740
6741 zilog = zil_open(os, ztest_get_data);
6742
6743 if (zilog->zl_replaying_seq != 0 &&
6744 zilog->zl_replaying_seq < committed_seq)
6745 fatal(0, "missing log records: replayed %llu < committed %llu",
6746 zilog->zl_replaying_seq, committed_seq);
6747
6748 return (0);
6749 }
6750
6751 static void
6752 ztest_dataset_close(int d)
6753 {
6754 ztest_ds_t *zd = &ztest_ds[d];
6755
6756 zil_close(zd->zd_zilog);
6757 dmu_objset_disown(zd->zd_os, B_TRUE, zd);
6758
6759 ztest_zd_fini(zd);
6760 }
6761
6762 /* ARGSUSED */
6763 static int
6764 ztest_replay_zil_cb(const char *name, void *arg)
6765 {
6766 objset_t *os;
6767 ztest_ds_t *zdtmp;
6768
6769 VERIFY0(ztest_dmu_objset_own(name, DMU_OST_ANY, B_TRUE,
6770 B_TRUE, FTAG, &os));
6771
6772 zdtmp = umem_alloc(sizeof (ztest_ds_t), UMEM_NOFAIL);
6773
6774 ztest_zd_init(zdtmp, NULL, os);
6775 zil_replay(os, zdtmp, ztest_replay_vector);
6776 ztest_zd_fini(zdtmp);
6777
6778 if (dmu_objset_zil(os)->zl_parse_lr_count != 0 &&
6779 ztest_opts.zo_verbose >= 6) {
6780 zilog_t *zilog = dmu_objset_zil(os);
6781
6782 (void) printf("%s replay %llu blocks, %llu records, seq %llu\n",
6783 name,
6784 (u_longlong_t)zilog->zl_parse_blk_count,
6785 (u_longlong_t)zilog->zl_parse_lr_count,
6786 (u_longlong_t)zilog->zl_replaying_seq);
6787 }
6788
6789 umem_free(zdtmp, sizeof (ztest_ds_t));
6790
6791 dmu_objset_disown(os, B_TRUE, FTAG);
6792 return (0);
6793 }
6794
6795 /*
6796 * Kick off threads to run tests on all datasets in parallel.
6797 */
6798 static void
6799 ztest_run(ztest_shared_t *zs)
6800 {
6801 spa_t *spa;
6802 objset_t *os;
6803 kthread_t *resume_thread, *deadman_thread;
6804 kthread_t **run_threads;
6805 uint64_t object;
6806 int error;
6807 int t, d;
6808
6809 ztest_exiting = B_FALSE;
6810
6811 /*
6812 * Initialize parent/child shared state.
6813 */
6814 mutex_init(&ztest_vdev_lock, NULL, MUTEX_DEFAULT, NULL);
6815 mutex_init(&ztest_checkpoint_lock, NULL, MUTEX_DEFAULT, NULL);
6816 VERIFY0(pthread_rwlock_init(&ztest_name_lock, NULL));
6817
6818 zs->zs_thread_start = gethrtime();
6819 zs->zs_thread_stop =
6820 zs->zs_thread_start + ztest_opts.zo_passtime * NANOSEC;
6821 zs->zs_thread_stop = MIN(zs->zs_thread_stop, zs->zs_proc_stop);
6822 zs->zs_thread_kill = zs->zs_thread_stop;
6823 if (ztest_random(100) < ztest_opts.zo_killrate) {
6824 zs->zs_thread_kill -=
6825 ztest_random(ztest_opts.zo_passtime * NANOSEC);
6826 }
6827
6828 mutex_init(&zcl.zcl_callbacks_lock, NULL, MUTEX_DEFAULT, NULL);
6829
6830 list_create(&zcl.zcl_callbacks, sizeof (ztest_cb_data_t),
6831 offsetof(ztest_cb_data_t, zcd_node));
6832
6833 /*
6834 * Open our pool.
6835 */
6836 kernel_init(FREAD | FWRITE);
6837 VERIFY0(spa_open(ztest_opts.zo_pool, &spa, FTAG));
6838 metaslab_preload_limit = ztest_random(20) + 1;
6839 ztest_spa = spa;
6840
6841 dmu_objset_stats_t dds;
6842 VERIFY0(ztest_dmu_objset_own(ztest_opts.zo_pool,
6843 DMU_OST_ANY, B_TRUE, B_TRUE, FTAG, &os));
6844 dsl_pool_config_enter(dmu_objset_pool(os), FTAG);
6845 dmu_objset_fast_stat(os, &dds);
6846 dsl_pool_config_exit(dmu_objset_pool(os), FTAG);
6847 zs->zs_guid = dds.dds_guid;
6848 dmu_objset_disown(os, B_TRUE, FTAG);
6849
6850 spa->spa_dedup_ditto = 2 * ZIO_DEDUPDITTO_MIN;
6851
6852 /*
6853 * Create a thread to periodically resume suspended I/O.
6854 */
6855 resume_thread = thread_create(NULL, 0, ztest_resume_thread,
6856 spa, 0, NULL, TS_RUN | TS_JOINABLE, defclsyspri);
6857
6858 /*
6859 * Create a deadman thread and set to panic if we hang.
6860 */
6861 deadman_thread = thread_create(NULL, 0, ztest_deadman_thread,
6862 zs, 0, NULL, TS_RUN | TS_JOINABLE, defclsyspri);
6863
6864 spa->spa_deadman_failmode = ZIO_FAILURE_MODE_PANIC;
6865
6866 /*
6867 * Verify that we can safely inquire about any object,
6868 * whether it's allocated or not. To make it interesting,
6869 * we probe a 5-wide window around each power of two.
6870 * This hits all edge cases, including zero and the max.
6871 */
6872 for (t = 0; t < 64; t++) {
6873 for (d = -5; d <= 5; d++) {
6874 error = dmu_object_info(spa->spa_meta_objset,
6875 (1ULL << t) + d, NULL);
6876 ASSERT(error == 0 || error == ENOENT ||
6877 error == EINVAL);
6878 }
6879 }
6880
6881 /*
6882 * If we got any ENOSPC errors on the previous run, destroy something.
6883 */
6884 if (zs->zs_enospc_count != 0) {
6885 int d = ztest_random(ztest_opts.zo_datasets);
6886 ztest_dataset_destroy(d);
6887 }
6888 zs->zs_enospc_count = 0;
6889
6890 /*
6891 * If we were in the middle of ztest_device_removal() and were killed
6892 * we need to ensure the removal and scrub complete before running
6893 * any tests that check ztest_device_removal_active. The removal will
6894 * be restarted automatically when the spa is opened, but we need to
6895 * initate the scrub manually if it is not already in progress. Note
6896 * that we always run the scrub whenever an indirect vdev exists
6897 * because we have no way of knowing for sure if ztest_device_removal()
6898 * fully completed its scrub before the pool was reimported.
6899 */
6900 if (spa->spa_removing_phys.sr_state == DSS_SCANNING ||
6901 spa->spa_removing_phys.sr_prev_indirect_vdev != -1) {
6902 while (spa->spa_removing_phys.sr_state == DSS_SCANNING)
6903 txg_wait_synced(spa_get_dsl(spa), 0);
6904
6905 (void) spa_scan(spa, POOL_SCAN_SCRUB);
6906 while (dsl_scan_scrubbing(spa_get_dsl(spa)))
6907 txg_wait_synced(spa_get_dsl(spa), 0);
6908 }
6909
6910 run_threads = umem_zalloc(ztest_opts.zo_threads * sizeof (kthread_t *),
6911 UMEM_NOFAIL);
6912
6913 if (ztest_opts.zo_verbose >= 4)
6914 (void) printf("starting main threads...\n");
6915
6916 /*
6917 * Replay all logs of all datasets in the pool. This is primarily for
6918 * temporary datasets which wouldn't otherwise get replayed, which
6919 * can trigger failures when attempting to offline a SLOG in
6920 * ztest_fault_inject().
6921 */
6922 (void) dmu_objset_find(ztest_opts.zo_pool, ztest_replay_zil_cb,
6923 NULL, DS_FIND_CHILDREN);
6924
6925 /*
6926 * Kick off all the tests that run in parallel.
6927 */
6928 for (t = 0; t < ztest_opts.zo_threads; t++) {
6929 if (t < ztest_opts.zo_datasets && ztest_dataset_open(t) != 0) {
6930 umem_free(run_threads, ztest_opts.zo_threads *
6931 sizeof (kthread_t *));
6932 return;
6933 }
6934
6935 run_threads[t] = thread_create(NULL, 0, ztest_thread,
6936 (void *)(uintptr_t)t, 0, NULL, TS_RUN | TS_JOINABLE,
6937 defclsyspri);
6938 }
6939
6940 /*
6941 * Wait for all of the tests to complete.
6942 */
6943 for (t = 0; t < ztest_opts.zo_threads; t++)
6944 VERIFY0(thread_join(run_threads[t]));
6945
6946 /*
6947 * Close all datasets. This must be done after all the threads
6948 * are joined so we can be sure none of the datasets are in-use
6949 * by any of the threads.
6950 */
6951 for (t = 0; t < ztest_opts.zo_threads; t++) {
6952 if (t < ztest_opts.zo_datasets)
6953 ztest_dataset_close(t);
6954 }
6955
6956 txg_wait_synced(spa_get_dsl(spa), 0);
6957
6958 zs->zs_alloc = metaslab_class_get_alloc(spa_normal_class(spa));
6959 zs->zs_space = metaslab_class_get_space(spa_normal_class(spa));
6960
6961 umem_free(run_threads, ztest_opts.zo_threads * sizeof (kthread_t *));
6962
6963 /* Kill the resume and deadman threads */
6964 ztest_exiting = B_TRUE;
6965 VERIFY0(thread_join(resume_thread));
6966 VERIFY0(thread_join(deadman_thread));
6967 ztest_resume(spa);
6968
6969 /*
6970 * Right before closing the pool, kick off a bunch of async I/O;
6971 * spa_close() should wait for it to complete.
6972 */
6973 for (object = 1; object < 50; object++) {
6974 dmu_prefetch(spa->spa_meta_objset, object, 0, 0, 1ULL << 20,
6975 ZIO_PRIORITY_SYNC_READ);
6976 }
6977
6978 /* Verify that at least one commit cb was called in a timely fashion */
6979 if (zc_cb_counter >= ZTEST_COMMIT_CB_MIN_REG)
6980 VERIFY0(zc_min_txg_delay);
6981
6982 spa_close(spa, FTAG);
6983
6984 /*
6985 * Verify that we can loop over all pools.
6986 */
6987 mutex_enter(&spa_namespace_lock);
6988 for (spa = spa_next(NULL); spa != NULL; spa = spa_next(spa))
6989 if (ztest_opts.zo_verbose > 3)
6990 (void) printf("spa_next: found %s\n", spa_name(spa));
6991 mutex_exit(&spa_namespace_lock);
6992
6993 /*
6994 * Verify that we can export the pool and reimport it under a
6995 * different name.
6996 */
6997 if ((ztest_random(2) == 0) && !ztest_opts.zo_mmp_test) {
6998 char name[ZFS_MAX_DATASET_NAME_LEN];
6999 (void) snprintf(name, sizeof (name), "%s_import",
7000 ztest_opts.zo_pool);
7001 ztest_spa_import_export(ztest_opts.zo_pool, name);
7002 ztest_spa_import_export(name, ztest_opts.zo_pool);
7003 }
7004
7005 kernel_fini();
7006
7007 list_destroy(&zcl.zcl_callbacks);
7008 mutex_destroy(&zcl.zcl_callbacks_lock);
7009 (void) pthread_rwlock_destroy(&ztest_name_lock);
7010 mutex_destroy(&ztest_vdev_lock);
7011 mutex_destroy(&ztest_checkpoint_lock);
7012 }
7013
7014 static void
7015 ztest_freeze(void)
7016 {
7017 ztest_ds_t *zd = &ztest_ds[0];
7018 spa_t *spa;
7019 int numloops = 0;
7020
7021 if (ztest_opts.zo_verbose >= 3)
7022 (void) printf("testing spa_freeze()...\n");
7023
7024 kernel_init(FREAD | FWRITE);
7025 VERIFY3U(0, ==, spa_open(ztest_opts.zo_pool, &spa, FTAG));
7026 VERIFY3U(0, ==, ztest_dataset_open(0));
7027 ztest_spa = spa;
7028
7029 /*
7030 * Force the first log block to be transactionally allocated.
7031 * We have to do this before we freeze the pool -- otherwise
7032 * the log chain won't be anchored.
7033 */
7034 while (BP_IS_HOLE(&zd->zd_zilog->zl_header->zh_log)) {
7035 ztest_dmu_object_alloc_free(zd, 0);
7036 zil_commit(zd->zd_zilog, 0);
7037 }
7038
7039 txg_wait_synced(spa_get_dsl(spa), 0);
7040
7041 /*
7042 * Freeze the pool. This stops spa_sync() from doing anything,
7043 * so that the only way to record changes from now on is the ZIL.
7044 */
7045 spa_freeze(spa);
7046
7047 /*
7048 * Because it is hard to predict how much space a write will actually
7049 * require beforehand, we leave ourselves some fudge space to write over
7050 * capacity.
7051 */
7052 uint64_t capacity = metaslab_class_get_space(spa_normal_class(spa)) / 2;
7053
7054 /*
7055 * Run tests that generate log records but don't alter the pool config
7056 * or depend on DSL sync tasks (snapshots, objset create/destroy, etc).
7057 * We do a txg_wait_synced() after each iteration to force the txg
7058 * to increase well beyond the last synced value in the uberblock.
7059 * The ZIL should be OK with that.
7060 *
7061 * Run a random number of times less than zo_maxloops and ensure we do
7062 * not run out of space on the pool.
7063 */
7064 while (ztest_random(10) != 0 &&
7065 numloops++ < ztest_opts.zo_maxloops &&
7066 metaslab_class_get_alloc(spa_normal_class(spa)) < capacity) {
7067 ztest_od_t od;
7068 ztest_od_init(&od, 0, FTAG, 0, DMU_OT_UINT64_OTHER, 0, 0, 0);
7069 VERIFY0(ztest_object_init(zd, &od, sizeof (od), B_FALSE));
7070 ztest_io(zd, od.od_object,
7071 ztest_random(ZTEST_RANGE_LOCKS) << SPA_MAXBLOCKSHIFT);
7072 txg_wait_synced(spa_get_dsl(spa), 0);
7073 }
7074
7075 /*
7076 * Commit all of the changes we just generated.
7077 */
7078 zil_commit(zd->zd_zilog, 0);
7079 txg_wait_synced(spa_get_dsl(spa), 0);
7080
7081 /*
7082 * Close our dataset and close the pool.
7083 */
7084 ztest_dataset_close(0);
7085 spa_close(spa, FTAG);
7086 kernel_fini();
7087
7088 /*
7089 * Open and close the pool and dataset to induce log replay.
7090 */
7091 kernel_init(FREAD | FWRITE);
7092 VERIFY3U(0, ==, spa_open(ztest_opts.zo_pool, &spa, FTAG));
7093 ASSERT(spa_freeze_txg(spa) == UINT64_MAX);
7094 VERIFY3U(0, ==, ztest_dataset_open(0));
7095 ztest_spa = spa;
7096 txg_wait_synced(spa_get_dsl(spa), 0);
7097 ztest_dataset_close(0);
7098 ztest_reguid(NULL, 0);
7099
7100 spa_close(spa, FTAG);
7101 kernel_fini();
7102 }
7103
7104 void
7105 print_time(hrtime_t t, char *timebuf)
7106 {
7107 hrtime_t s = t / NANOSEC;
7108 hrtime_t m = s / 60;
7109 hrtime_t h = m / 60;
7110 hrtime_t d = h / 24;
7111
7112 s -= m * 60;
7113 m -= h * 60;
7114 h -= d * 24;
7115
7116 timebuf[0] = '\0';
7117
7118 if (d)
7119 (void) sprintf(timebuf,
7120 "%llud%02lluh%02llum%02llus", d, h, m, s);
7121 else if (h)
7122 (void) sprintf(timebuf, "%lluh%02llum%02llus", h, m, s);
7123 else if (m)
7124 (void) sprintf(timebuf, "%llum%02llus", m, s);
7125 else
7126 (void) sprintf(timebuf, "%llus", s);
7127 }
7128
7129 static nvlist_t *
7130 make_random_props(void)
7131 {
7132 nvlist_t *props;
7133
7134 VERIFY0(nvlist_alloc(&props, NV_UNIQUE_NAME, 0));
7135
7136 if (ztest_random(2) == 0)
7137 return (props);
7138
7139 VERIFY0(nvlist_add_uint64(props,
7140 zpool_prop_to_name(ZPOOL_PROP_AUTOREPLACE), 1));
7141
7142 return (props);
7143 }
7144
7145 /*
7146 * Import a storage pool with the given name.
7147 */
7148 static void
7149 ztest_import(ztest_shared_t *zs)
7150 {
7151 importargs_t args = { 0 };
7152 spa_t *spa;
7153 nvlist_t *cfg = NULL;
7154 int nsearch = 1;
7155 char *searchdirs[nsearch];
7156 char *name = ztest_opts.zo_pool;
7157 int flags = ZFS_IMPORT_MISSING_LOG;
7158 int error;
7159
7160 mutex_init(&ztest_vdev_lock, NULL, MUTEX_DEFAULT, NULL);
7161 mutex_init(&ztest_checkpoint_lock, NULL, MUTEX_DEFAULT, NULL);
7162 VERIFY0(pthread_rwlock_init(&ztest_name_lock, NULL));
7163
7164 kernel_init(FREAD | FWRITE);
7165
7166 searchdirs[0] = ztest_opts.zo_dir;
7167 args.paths = nsearch;
7168 args.path = searchdirs;
7169 args.can_be_active = B_FALSE;
7170
7171 error = zpool_find_config(NULL, name, &cfg, &args,
7172 &libzpool_config_ops);
7173 if (error)
7174 (void) fatal(0, "No pools found\n");
7175
7176 VERIFY0(spa_import(name, cfg, NULL, flags));
7177 VERIFY0(spa_open(name, &spa, FTAG));
7178 zs->zs_metaslab_sz =
7179 1ULL << spa->spa_root_vdev->vdev_child[0]->vdev_ms_shift;
7180 spa_close(spa, FTAG);
7181
7182 kernel_fini();
7183
7184 if (!ztest_opts.zo_mmp_test) {
7185 ztest_run_zdb(ztest_opts.zo_pool);
7186 ztest_freeze();
7187 ztest_run_zdb(ztest_opts.zo_pool);
7188 }
7189
7190 (void) pthread_rwlock_destroy(&ztest_name_lock);
7191 mutex_destroy(&ztest_vdev_lock);
7192 mutex_destroy(&ztest_checkpoint_lock);
7193 }
7194
7195 /*
7196 * Create a storage pool with the given name and initial vdev size.
7197 * Then test spa_freeze() functionality.
7198 */
7199 static void
7200 ztest_init(ztest_shared_t *zs)
7201 {
7202 spa_t *spa;
7203 nvlist_t *nvroot, *props;
7204 int i;
7205
7206 mutex_init(&ztest_vdev_lock, NULL, MUTEX_DEFAULT, NULL);
7207 mutex_init(&ztest_checkpoint_lock, NULL, MUTEX_DEFAULT, NULL);
7208 VERIFY0(pthread_rwlock_init(&ztest_name_lock, NULL));
7209
7210 kernel_init(FREAD | FWRITE);
7211
7212 /*
7213 * Create the storage pool.
7214 */
7215 (void) spa_destroy(ztest_opts.zo_pool);
7216 ztest_shared->zs_vdev_next_leaf = 0;
7217 zs->zs_splits = 0;
7218 zs->zs_mirrors = ztest_opts.zo_mirrors;
7219 nvroot = make_vdev_root(NULL, NULL, NULL, ztest_opts.zo_vdev_size, 0,
7220 NULL, ztest_opts.zo_raidz, zs->zs_mirrors, 1);
7221 props = make_random_props();
7222
7223 /*
7224 * We don't expect the pool to suspend unless maxfaults == 0,
7225 * in which case ztest_fault_inject() temporarily takes away
7226 * the only valid replica.
7227 */
7228 VERIFY0(nvlist_add_uint64(props,
7229 zpool_prop_to_name(ZPOOL_PROP_FAILUREMODE),
7230 MAXFAULTS(zs) ? ZIO_FAILURE_MODE_PANIC : ZIO_FAILURE_MODE_WAIT));
7231
7232 for (i = 0; i < SPA_FEATURES; i++) {
7233 char *buf;
7234 VERIFY3S(-1, !=, asprintf(&buf, "feature@%s",
7235 spa_feature_table[i].fi_uname));
7236 VERIFY3U(0, ==, nvlist_add_uint64(props, buf, 0));
7237 free(buf);
7238 }
7239
7240 VERIFY0(spa_create(ztest_opts.zo_pool, nvroot, props, NULL, NULL));
7241 nvlist_free(nvroot);
7242 nvlist_free(props);
7243
7244 VERIFY3U(0, ==, spa_open(ztest_opts.zo_pool, &spa, FTAG));
7245 zs->zs_metaslab_sz =
7246 1ULL << spa->spa_root_vdev->vdev_child[0]->vdev_ms_shift;
7247 spa_close(spa, FTAG);
7248
7249 kernel_fini();
7250
7251 if (!ztest_opts.zo_mmp_test) {
7252 ztest_run_zdb(ztest_opts.zo_pool);
7253 ztest_freeze();
7254 ztest_run_zdb(ztest_opts.zo_pool);
7255 }
7256
7257 (void) pthread_rwlock_destroy(&ztest_name_lock);
7258 mutex_destroy(&ztest_vdev_lock);
7259 mutex_destroy(&ztest_checkpoint_lock);
7260 }
7261
7262 static void
7263 setup_data_fd(void)
7264 {
7265 static char ztest_name_data[] = "/tmp/ztest.data.XXXXXX";
7266
7267 ztest_fd_data = mkstemp(ztest_name_data);
7268 ASSERT3S(ztest_fd_data, >=, 0);
7269 (void) unlink(ztest_name_data);
7270 }
7271
7272 static int
7273 shared_data_size(ztest_shared_hdr_t *hdr)
7274 {
7275 int size;
7276
7277 size = hdr->zh_hdr_size;
7278 size += hdr->zh_opts_size;
7279 size += hdr->zh_size;
7280 size += hdr->zh_stats_size * hdr->zh_stats_count;
7281 size += hdr->zh_ds_size * hdr->zh_ds_count;
7282
7283 return (size);
7284 }
7285
7286 static void
7287 setup_hdr(void)
7288 {
7289 int size;
7290 ztest_shared_hdr_t *hdr;
7291
7292 hdr = (void *)mmap(0, P2ROUNDUP(sizeof (*hdr), getpagesize()),
7293 PROT_READ | PROT_WRITE, MAP_SHARED, ztest_fd_data, 0);
7294 ASSERT(hdr != MAP_FAILED);
7295
7296 VERIFY3U(0, ==, ftruncate(ztest_fd_data, sizeof (ztest_shared_hdr_t)));
7297
7298 hdr->zh_hdr_size = sizeof (ztest_shared_hdr_t);
7299 hdr->zh_opts_size = sizeof (ztest_shared_opts_t);
7300 hdr->zh_size = sizeof (ztest_shared_t);
7301 hdr->zh_stats_size = sizeof (ztest_shared_callstate_t);
7302 hdr->zh_stats_count = ZTEST_FUNCS;
7303 hdr->zh_ds_size = sizeof (ztest_shared_ds_t);
7304 hdr->zh_ds_count = ztest_opts.zo_datasets;
7305
7306 size = shared_data_size(hdr);
7307 VERIFY3U(0, ==, ftruncate(ztest_fd_data, size));
7308
7309 (void) munmap((caddr_t)hdr, P2ROUNDUP(sizeof (*hdr), getpagesize()));
7310 }
7311
7312 static void
7313 setup_data(void)
7314 {
7315 int size, offset;
7316 ztest_shared_hdr_t *hdr;
7317 uint8_t *buf;
7318
7319 hdr = (void *)mmap(0, P2ROUNDUP(sizeof (*hdr), getpagesize()),
7320 PROT_READ, MAP_SHARED, ztest_fd_data, 0);
7321 ASSERT(hdr != MAP_FAILED);
7322
7323 size = shared_data_size(hdr);
7324
7325 (void) munmap((caddr_t)hdr, P2ROUNDUP(sizeof (*hdr), getpagesize()));
7326 hdr = ztest_shared_hdr = (void *)mmap(0, P2ROUNDUP(size, getpagesize()),
7327 PROT_READ | PROT_WRITE, MAP_SHARED, ztest_fd_data, 0);
7328 ASSERT(hdr != MAP_FAILED);
7329 buf = (uint8_t *)hdr;
7330
7331 offset = hdr->zh_hdr_size;
7332 ztest_shared_opts = (void *)&buf[offset];
7333 offset += hdr->zh_opts_size;
7334 ztest_shared = (void *)&buf[offset];
7335 offset += hdr->zh_size;
7336 ztest_shared_callstate = (void *)&buf[offset];
7337 offset += hdr->zh_stats_size * hdr->zh_stats_count;
7338 ztest_shared_ds = (void *)&buf[offset];
7339 }
7340
7341 static boolean_t
7342 exec_child(char *cmd, char *libpath, boolean_t ignorekill, int *statusp)
7343 {
7344 pid_t pid;
7345 int status;
7346 char *cmdbuf = NULL;
7347
7348 pid = fork();
7349
7350 if (cmd == NULL) {
7351 cmdbuf = umem_alloc(MAXPATHLEN, UMEM_NOFAIL);
7352 (void) strlcpy(cmdbuf, getexecname(), MAXPATHLEN);
7353 cmd = cmdbuf;
7354 }
7355
7356 if (pid == -1)
7357 fatal(1, "fork failed");
7358
7359 if (pid == 0) { /* child */
7360 char *emptyargv[2] = { cmd, NULL };
7361 char fd_data_str[12];
7362
7363 struct rlimit rl = { 1024, 1024 };
7364 (void) setrlimit(RLIMIT_NOFILE, &rl);
7365
7366 (void) close(ztest_fd_rand);
7367 VERIFY(11 >= snprintf(fd_data_str, 12, "%d", ztest_fd_data));
7368 VERIFY(0 == setenv("ZTEST_FD_DATA", fd_data_str, 1));
7369
7370 (void) enable_extended_FILE_stdio(-1, -1);
7371 if (libpath != NULL)
7372 VERIFY(0 == setenv("LD_LIBRARY_PATH", libpath, 1));
7373 (void) execv(cmd, emptyargv);
7374 ztest_dump_core = B_FALSE;
7375 fatal(B_TRUE, "exec failed: %s", cmd);
7376 }
7377
7378 if (cmdbuf != NULL) {
7379 umem_free(cmdbuf, MAXPATHLEN);
7380 cmd = NULL;
7381 }
7382
7383 while (waitpid(pid, &status, 0) != pid)
7384 continue;
7385 if (statusp != NULL)
7386 *statusp = status;
7387
7388 if (WIFEXITED(status)) {
7389 if (WEXITSTATUS(status) != 0) {
7390 (void) fprintf(stderr, "child exited with code %d\n",
7391 WEXITSTATUS(status));
7392 exit(2);
7393 }
7394 return (B_FALSE);
7395 } else if (WIFSIGNALED(status)) {
7396 if (!ignorekill || WTERMSIG(status) != SIGKILL) {
7397 (void) fprintf(stderr, "child died with signal %d\n",
7398 WTERMSIG(status));
7399 exit(3);
7400 }
7401 return (B_TRUE);
7402 } else {
7403 (void) fprintf(stderr, "something strange happened to child\n");
7404 exit(4);
7405 /* NOTREACHED */
7406 }
7407 }
7408
7409 static void
7410 ztest_run_init(void)
7411 {
7412 int i;
7413
7414 ztest_shared_t *zs = ztest_shared;
7415
7416 /*
7417 * Blow away any existing copy of zpool.cache
7418 */
7419 (void) remove(spa_config_path);
7420
7421 if (ztest_opts.zo_init == 0) {
7422 if (ztest_opts.zo_verbose >= 1)
7423 (void) printf("Importing pool %s\n",
7424 ztest_opts.zo_pool);
7425 ztest_import(zs);
7426 return;
7427 }
7428
7429 /*
7430 * Create and initialize our storage pool.
7431 */
7432 for (i = 1; i <= ztest_opts.zo_init; i++) {
7433 bzero(zs, sizeof (ztest_shared_t));
7434 if (ztest_opts.zo_verbose >= 3 &&
7435 ztest_opts.zo_init != 1) {
7436 (void) printf("ztest_init(), pass %d\n", i);
7437 }
7438 ztest_init(zs);
7439 }
7440 }
7441
7442 int
7443 main(int argc, char **argv)
7444 {
7445 int kills = 0;
7446 int iters = 0;
7447 int older = 0;
7448 int newer = 0;
7449 ztest_shared_t *zs;
7450 ztest_info_t *zi;
7451 ztest_shared_callstate_t *zc;
7452 char timebuf[100];
7453 char numbuf[NN_NUMBUF_SZ];
7454 char *cmd;
7455 boolean_t hasalt;
7456 int f;
7457 char *fd_data_str = getenv("ZTEST_FD_DATA");
7458 struct sigaction action;
7459
7460 (void) setvbuf(stdout, NULL, _IOLBF, 0);
7461
7462 dprintf_setup(&argc, argv);
7463 zfs_deadman_synctime_ms = 300000;
7464 zfs_deadman_checktime_ms = 30000;
7465 /*
7466 * As two-word space map entries may not come up often (especially
7467 * if pool and vdev sizes are small) we want to force at least some
7468 * of them so the feature get tested.
7469 */
7470 zfs_force_some_double_word_sm_entries = B_TRUE;
7471
7472 /*
7473 * Verify that even extensively damaged split blocks with many
7474 * segments can be reconstructed in a reasonable amount of time
7475 * when reconstruction is known to be possible.
7476 *
7477 * Note: the lower this value is, the more damage we inflict, and
7478 * the more time ztest spends in recovering that damage. We chose
7479 * to induce damage 1/100th of the time so recovery is tested but
7480 * not so frequently that ztest doesn't get to test other code paths.
7481 */
7482 zfs_reconstruct_indirect_damage_fraction = 100;
7483
7484 action.sa_handler = sig_handler;
7485 sigemptyset(&action.sa_mask);
7486 action.sa_flags = 0;
7487
7488 if (sigaction(SIGSEGV, &action, NULL) < 0) {
7489 (void) fprintf(stderr, "ztest: cannot catch SIGSEGV: %s.\n",
7490 strerror(errno));
7491 exit(EXIT_FAILURE);
7492 }
7493
7494 if (sigaction(SIGABRT, &action, NULL) < 0) {
7495 (void) fprintf(stderr, "ztest: cannot catch SIGABRT: %s.\n",
7496 strerror(errno));
7497 exit(EXIT_FAILURE);
7498 }
7499
7500 /*
7501 * Force random_get_bytes() to use /dev/urandom in order to prevent
7502 * ztest from needlessly depleting the system entropy pool.
7503 */
7504 random_path = "/dev/urandom";
7505 ztest_fd_rand = open(random_path, O_RDONLY);
7506 ASSERT3S(ztest_fd_rand, >=, 0);
7507
7508 if (!fd_data_str) {
7509 process_options(argc, argv);
7510
7511 setup_data_fd();
7512 setup_hdr();
7513 setup_data();
7514 bcopy(&ztest_opts, ztest_shared_opts,
7515 sizeof (*ztest_shared_opts));
7516 } else {
7517 ztest_fd_data = atoi(fd_data_str);
7518 setup_data();
7519 bcopy(ztest_shared_opts, &ztest_opts, sizeof (ztest_opts));
7520 }
7521 ASSERT3U(ztest_opts.zo_datasets, ==, ztest_shared_hdr->zh_ds_count);
7522
7523 /* Override location of zpool.cache */
7524 VERIFY(asprintf((char **)&spa_config_path, "%s/zpool.cache",
7525 ztest_opts.zo_dir) != -1);
7526
7527 ztest_ds = umem_alloc(ztest_opts.zo_datasets * sizeof (ztest_ds_t),
7528 UMEM_NOFAIL);
7529 zs = ztest_shared;
7530
7531 if (fd_data_str) {
7532 metaslab_force_ganging = ztest_opts.zo_metaslab_force_ganging;
7533 metaslab_df_alloc_threshold =
7534 zs->zs_metaslab_df_alloc_threshold;
7535
7536 if (zs->zs_do_init)
7537 ztest_run_init();
7538 else
7539 ztest_run(zs);
7540 exit(0);
7541 }
7542
7543 hasalt = (strlen(ztest_opts.zo_alt_ztest) != 0);
7544
7545 if (ztest_opts.zo_verbose >= 1) {
7546 (void) printf("%llu vdevs, %d datasets, %d threads,"
7547 " %llu seconds...\n",
7548 (u_longlong_t)ztest_opts.zo_vdevs,
7549 ztest_opts.zo_datasets,
7550 ztest_opts.zo_threads,
7551 (u_longlong_t)ztest_opts.zo_time);
7552 }
7553
7554 cmd = umem_alloc(MAXNAMELEN, UMEM_NOFAIL);
7555 (void) strlcpy(cmd, getexecname(), MAXNAMELEN);
7556
7557 zs->zs_do_init = B_TRUE;
7558 if (strlen(ztest_opts.zo_alt_ztest) != 0) {
7559 if (ztest_opts.zo_verbose >= 1) {
7560 (void) printf("Executing older ztest for "
7561 "initialization: %s\n", ztest_opts.zo_alt_ztest);
7562 }
7563 VERIFY(!exec_child(ztest_opts.zo_alt_ztest,
7564 ztest_opts.zo_alt_libpath, B_FALSE, NULL));
7565 } else {
7566 VERIFY(!exec_child(NULL, NULL, B_FALSE, NULL));
7567 }
7568 zs->zs_do_init = B_FALSE;
7569
7570 zs->zs_proc_start = gethrtime();
7571 zs->zs_proc_stop = zs->zs_proc_start + ztest_opts.zo_time * NANOSEC;
7572
7573 for (f = 0; f < ZTEST_FUNCS; f++) {
7574 zi = &ztest_info[f];
7575 zc = ZTEST_GET_SHARED_CALLSTATE(f);
7576 if (zs->zs_proc_start + zi->zi_interval[0] > zs->zs_proc_stop)
7577 zc->zc_next = UINT64_MAX;
7578 else
7579 zc->zc_next = zs->zs_proc_start +
7580 ztest_random(2 * zi->zi_interval[0] + 1);
7581 }
7582
7583 /*
7584 * Run the tests in a loop. These tests include fault injection
7585 * to verify that self-healing data works, and forced crashes
7586 * to verify that we never lose on-disk consistency.
7587 */
7588 while (gethrtime() < zs->zs_proc_stop) {
7589 int status;
7590 boolean_t killed;
7591
7592 /*
7593 * Initialize the workload counters for each function.
7594 */
7595 for (f = 0; f < ZTEST_FUNCS; f++) {
7596 zc = ZTEST_GET_SHARED_CALLSTATE(f);
7597 zc->zc_count = 0;
7598 zc->zc_time = 0;
7599 }
7600
7601 /* Set the allocation switch size */
7602 zs->zs_metaslab_df_alloc_threshold =
7603 ztest_random(zs->zs_metaslab_sz / 4) + 1;
7604
7605 if (!hasalt || ztest_random(2) == 0) {
7606 if (hasalt && ztest_opts.zo_verbose >= 1) {
7607 (void) printf("Executing newer ztest: %s\n",
7608 cmd);
7609 }
7610 newer++;
7611 killed = exec_child(cmd, NULL, B_TRUE, &status);
7612 } else {
7613 if (hasalt && ztest_opts.zo_verbose >= 1) {
7614 (void) printf("Executing older ztest: %s\n",
7615 ztest_opts.zo_alt_ztest);
7616 }
7617 older++;
7618 killed = exec_child(ztest_opts.zo_alt_ztest,
7619 ztest_opts.zo_alt_libpath, B_TRUE, &status);
7620 }
7621
7622 if (killed)
7623 kills++;
7624 iters++;
7625
7626 if (ztest_opts.zo_verbose >= 1) {
7627 hrtime_t now = gethrtime();
7628
7629 now = MIN(now, zs->zs_proc_stop);
7630 print_time(zs->zs_proc_stop - now, timebuf);
7631 nicenum(zs->zs_space, numbuf, sizeof (numbuf));
7632
7633 (void) printf("Pass %3d, %8s, %3llu ENOSPC, "
7634 "%4.1f%% of %5s used, %3.0f%% done, %8s to go\n",
7635 iters,
7636 WIFEXITED(status) ? "Complete" : "SIGKILL",
7637 (u_longlong_t)zs->zs_enospc_count,
7638 100.0 * zs->zs_alloc / zs->zs_space,
7639 numbuf,
7640 100.0 * (now - zs->zs_proc_start) /
7641 (ztest_opts.zo_time * NANOSEC), timebuf);
7642 }
7643
7644 if (ztest_opts.zo_verbose >= 2) {
7645 (void) printf("\nWorkload summary:\n\n");
7646 (void) printf("%7s %9s %s\n",
7647 "Calls", "Time", "Function");
7648 (void) printf("%7s %9s %s\n",
7649 "-----", "----", "--------");
7650 for (f = 0; f < ZTEST_FUNCS; f++) {
7651 zi = &ztest_info[f];
7652 zc = ZTEST_GET_SHARED_CALLSTATE(f);
7653 print_time(zc->zc_time, timebuf);
7654 (void) printf("%7llu %9s %s\n",
7655 (u_longlong_t)zc->zc_count, timebuf,
7656 zi->zi_funcname);
7657 }
7658 (void) printf("\n");
7659 }
7660
7661 if (!ztest_opts.zo_mmp_test)
7662 ztest_run_zdb(ztest_opts.zo_pool);
7663 }
7664
7665 if (ztest_opts.zo_verbose >= 1) {
7666 if (hasalt) {
7667 (void) printf("%d runs of older ztest: %s\n", older,
7668 ztest_opts.zo_alt_ztest);
7669 (void) printf("%d runs of newer ztest: %s\n", newer,
7670 cmd);
7671 }
7672 (void) printf("%d killed, %d completed, %.0f%% kill rate\n",
7673 kills, iters - kills, (100.0 * kills) / MAX(1, iters));
7674 }
7675
7676 umem_free(cmd, MAXNAMELEN);
7677
7678 return (0);
7679 }