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