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