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