]> git.proxmox.com Git - mirror_zfs.git/blob - cmd/ztest/ztest.c
Disable 'zfs remap' command
[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/vdev_initialize.h>
110 #include <sys/spa_impl.h>
111 #include <sys/metaslab_impl.h>
112 #include <sys/dsl_prop.h>
113 #include <sys/dsl_dataset.h>
114 #include <sys/dsl_destroy.h>
115 #include <sys/dsl_scan.h>
116 #include <sys/zio_checksum.h>
117 #include <sys/refcount.h>
118 #include <sys/zfeature.h>
119 #include <sys/dsl_userhold.h>
120 #include <sys/abd.h>
121 #include <stdio.h>
122 #include <stdio_ext.h>
123 #include <stdlib.h>
124 #include <unistd.h>
125 #include <signal.h>
126 #include <umem.h>
127 #include <ctype.h>
128 #include <math.h>
129 #include <sys/fs/zfs.h>
130 #include <zfs_fletcher.h>
131 #include <libnvpair.h>
132 #include <libzutil.h>
133 #include <sys/crypto/icp.h>
134 #ifdef __GLIBC__
135 #include <execinfo.h> /* for backtrace() */
136 #endif
137
138 static int ztest_fd_data = -1;
139 static int ztest_fd_rand = -1;
140
141 typedef struct ztest_shared_hdr {
142 uint64_t zh_hdr_size;
143 uint64_t zh_opts_size;
144 uint64_t zh_size;
145 uint64_t zh_stats_size;
146 uint64_t zh_stats_count;
147 uint64_t zh_ds_size;
148 uint64_t zh_ds_count;
149 } ztest_shared_hdr_t;
150
151 static ztest_shared_hdr_t *ztest_shared_hdr;
152
153 enum ztest_class_state {
154 ZTEST_VDEV_CLASS_OFF,
155 ZTEST_VDEV_CLASS_ON,
156 ZTEST_VDEV_CLASS_RND
157 };
158
159 typedef struct ztest_shared_opts {
160 char zo_pool[ZFS_MAX_DATASET_NAME_LEN];
161 char zo_dir[ZFS_MAX_DATASET_NAME_LEN];
162 char zo_alt_ztest[MAXNAMELEN];
163 char zo_alt_libpath[MAXNAMELEN];
164 uint64_t zo_vdevs;
165 uint64_t zo_vdevtime;
166 size_t zo_vdev_size;
167 int zo_ashift;
168 int zo_mirrors;
169 int zo_raidz;
170 int zo_raidz_parity;
171 int zo_datasets;
172 int zo_threads;
173 uint64_t zo_passtime;
174 uint64_t zo_killrate;
175 int zo_verbose;
176 int zo_init;
177 uint64_t zo_time;
178 uint64_t zo_maxloops;
179 uint64_t zo_metaslab_force_ganging;
180 int zo_mmp_test;
181 int zo_special_vdevs;
182 int zo_dump_dbgmsg;
183 } ztest_shared_opts_t;
184
185 static const ztest_shared_opts_t ztest_opts_defaults = {
186 .zo_pool = { 'z', 't', 'e', 's', 't', '\0' },
187 .zo_dir = { '/', 't', 'm', 'p', '\0' },
188 .zo_alt_ztest = { '\0' },
189 .zo_alt_libpath = { '\0' },
190 .zo_vdevs = 5,
191 .zo_ashift = SPA_MINBLOCKSHIFT,
192 .zo_mirrors = 2,
193 .zo_raidz = 4,
194 .zo_raidz_parity = 1,
195 .zo_vdev_size = SPA_MINDEVSIZE * 4, /* 256m default size */
196 .zo_datasets = 7,
197 .zo_threads = 23,
198 .zo_passtime = 60, /* 60 seconds */
199 .zo_killrate = 70, /* 70% kill rate */
200 .zo_verbose = 0,
201 .zo_mmp_test = 0,
202 .zo_init = 1,
203 .zo_time = 300, /* 5 minutes */
204 .zo_maxloops = 50, /* max loops during spa_freeze() */
205 .zo_metaslab_force_ganging = 64 << 10,
206 .zo_special_vdevs = ZTEST_VDEV_CLASS_RND,
207 };
208
209 extern uint64_t metaslab_force_ganging;
210 extern uint64_t metaslab_df_alloc_threshold;
211 extern unsigned long zfs_deadman_synctime_ms;
212 extern int metaslab_preload_limit;
213 extern boolean_t zfs_compressed_arc_enabled;
214 extern int zfs_abd_scatter_enabled;
215 extern int dmu_object_alloc_chunk_shift;
216 extern boolean_t zfs_force_some_double_word_sm_entries;
217 extern unsigned long zio_decompress_fail_fraction;
218 extern unsigned long zfs_reconstruct_indirect_damage_fraction;
219
220
221 static ztest_shared_opts_t *ztest_shared_opts;
222 static ztest_shared_opts_t ztest_opts;
223 static char *ztest_wkeydata = "abcdefghijklmnopqrstuvwxyz012345";
224
225 typedef struct ztest_shared_ds {
226 uint64_t zd_seq;
227 } ztest_shared_ds_t;
228
229 static ztest_shared_ds_t *ztest_shared_ds;
230 #define ZTEST_GET_SHARED_DS(d) (&ztest_shared_ds[d])
231
232 #define BT_MAGIC 0x123456789abcdefULL
233 #define MAXFAULTS(zs) \
234 (MAX((zs)->zs_mirrors, 1) * (ztest_opts.zo_raidz_parity + 1) - 1)
235
236 enum ztest_io_type {
237 ZTEST_IO_WRITE_TAG,
238 ZTEST_IO_WRITE_PATTERN,
239 ZTEST_IO_WRITE_ZEROES,
240 ZTEST_IO_TRUNCATE,
241 ZTEST_IO_SETATTR,
242 ZTEST_IO_REWRITE,
243 ZTEST_IO_TYPES
244 };
245
246 typedef struct ztest_block_tag {
247 uint64_t bt_magic;
248 uint64_t bt_objset;
249 uint64_t bt_object;
250 uint64_t bt_dnodesize;
251 uint64_t bt_offset;
252 uint64_t bt_gen;
253 uint64_t bt_txg;
254 uint64_t bt_crtxg;
255 } ztest_block_tag_t;
256
257 typedef struct bufwad {
258 uint64_t bw_index;
259 uint64_t bw_txg;
260 uint64_t bw_data;
261 } bufwad_t;
262
263 /*
264 * It would be better to use a rangelock_t per object. Unfortunately
265 * the rangelock_t is not a drop-in replacement for rl_t, because we
266 * still need to map from object ID to rangelock_t.
267 */
268 typedef enum {
269 RL_READER,
270 RL_WRITER,
271 RL_APPEND
272 } rl_type_t;
273
274 typedef struct rll {
275 void *rll_writer;
276 int rll_readers;
277 kmutex_t rll_lock;
278 kcondvar_t rll_cv;
279 } rll_t;
280
281 typedef struct rl {
282 uint64_t rl_object;
283 uint64_t rl_offset;
284 uint64_t rl_size;
285 rll_t *rl_lock;
286 } rl_t;
287
288 #define ZTEST_RANGE_LOCKS 64
289 #define ZTEST_OBJECT_LOCKS 64
290
291 /*
292 * Object descriptor. Used as a template for object lookup/create/remove.
293 */
294 typedef struct ztest_od {
295 uint64_t od_dir;
296 uint64_t od_object;
297 dmu_object_type_t od_type;
298 dmu_object_type_t od_crtype;
299 uint64_t od_blocksize;
300 uint64_t od_crblocksize;
301 uint64_t od_crdnodesize;
302 uint64_t od_gen;
303 uint64_t od_crgen;
304 char od_name[ZFS_MAX_DATASET_NAME_LEN];
305 } ztest_od_t;
306
307 /*
308 * Per-dataset state.
309 */
310 typedef struct ztest_ds {
311 ztest_shared_ds_t *zd_shared;
312 objset_t *zd_os;
313 pthread_rwlock_t zd_zilog_lock;
314 zilog_t *zd_zilog;
315 ztest_od_t *zd_od; /* debugging aid */
316 char zd_name[ZFS_MAX_DATASET_NAME_LEN];
317 kmutex_t zd_dirobj_lock;
318 rll_t zd_object_lock[ZTEST_OBJECT_LOCKS];
319 rll_t zd_range_lock[ZTEST_RANGE_LOCKS];
320 } ztest_ds_t;
321
322 /*
323 * Per-iteration state.
324 */
325 typedef void ztest_func_t(ztest_ds_t *zd, uint64_t id);
326
327 typedef struct ztest_info {
328 ztest_func_t *zi_func; /* test function */
329 uint64_t zi_iters; /* iterations per execution */
330 uint64_t *zi_interval; /* execute every <interval> seconds */
331 const char *zi_funcname; /* name of test function */
332 } ztest_info_t;
333
334 typedef struct ztest_shared_callstate {
335 uint64_t zc_count; /* per-pass count */
336 uint64_t zc_time; /* per-pass time */
337 uint64_t zc_next; /* next time to call this function */
338 } ztest_shared_callstate_t;
339
340 static ztest_shared_callstate_t *ztest_shared_callstate;
341 #define ZTEST_GET_SHARED_CALLSTATE(c) (&ztest_shared_callstate[c])
342
343 ztest_func_t ztest_dmu_read_write;
344 ztest_func_t ztest_dmu_write_parallel;
345 ztest_func_t ztest_dmu_object_alloc_free;
346 ztest_func_t ztest_dmu_object_next_chunk;
347 ztest_func_t ztest_dmu_commit_callbacks;
348 ztest_func_t ztest_zap;
349 ztest_func_t ztest_zap_parallel;
350 ztest_func_t ztest_zil_commit;
351 ztest_func_t ztest_zil_remount;
352 ztest_func_t ztest_dmu_read_write_zcopy;
353 ztest_func_t ztest_dmu_objset_create_destroy;
354 ztest_func_t ztest_dmu_prealloc;
355 ztest_func_t ztest_fzap;
356 ztest_func_t ztest_dmu_snapshot_create_destroy;
357 ztest_func_t ztest_dsl_prop_get_set;
358 ztest_func_t ztest_spa_prop_get_set;
359 ztest_func_t ztest_spa_create_destroy;
360 ztest_func_t ztest_fault_inject;
361 ztest_func_t ztest_ddt_repair;
362 ztest_func_t ztest_dmu_snapshot_hold;
363 ztest_func_t ztest_mmp_enable_disable;
364 ztest_func_t ztest_scrub;
365 ztest_func_t ztest_dsl_dataset_promote_busy;
366 ztest_func_t ztest_vdev_attach_detach;
367 ztest_func_t ztest_vdev_LUN_growth;
368 ztest_func_t ztest_vdev_add_remove;
369 ztest_func_t ztest_vdev_class_add;
370 ztest_func_t ztest_vdev_aux_add_remove;
371 ztest_func_t ztest_split_pool;
372 ztest_func_t ztest_reguid;
373 ztest_func_t ztest_spa_upgrade;
374 ztest_func_t ztest_device_removal;
375 ztest_func_t ztest_spa_checkpoint_create_discard;
376 ztest_func_t ztest_initialize;
377 ztest_func_t ztest_fletcher;
378 ztest_func_t ztest_fletcher_incr;
379 ztest_func_t ztest_verify_dnode_bt;
380
381 uint64_t zopt_always = 0ULL * NANOSEC; /* all the time */
382 uint64_t zopt_incessant = 1ULL * NANOSEC / 10; /* every 1/10 second */
383 uint64_t zopt_often = 1ULL * NANOSEC; /* every second */
384 uint64_t zopt_sometimes = 10ULL * NANOSEC; /* every 10 seconds */
385 uint64_t zopt_rarely = 60ULL * NANOSEC; /* every 60 seconds */
386
387 #define ZTI_INIT(func, iters, interval) \
388 { .zi_func = (func), \
389 .zi_iters = (iters), \
390 .zi_interval = (interval), \
391 .zi_funcname = # func }
392
393 ztest_info_t ztest_info[] = {
394 ZTI_INIT(ztest_dmu_read_write, 1, &zopt_always),
395 ZTI_INIT(ztest_dmu_write_parallel, 10, &zopt_always),
396 ZTI_INIT(ztest_dmu_object_alloc_free, 1, &zopt_always),
397 ZTI_INIT(ztest_dmu_object_next_chunk, 1, &zopt_sometimes),
398 ZTI_INIT(ztest_dmu_commit_callbacks, 1, &zopt_always),
399 ZTI_INIT(ztest_zap, 30, &zopt_always),
400 ZTI_INIT(ztest_zap_parallel, 100, &zopt_always),
401 ZTI_INIT(ztest_split_pool, 1, &zopt_always),
402 ZTI_INIT(ztest_zil_commit, 1, &zopt_incessant),
403 ZTI_INIT(ztest_zil_remount, 1, &zopt_sometimes),
404 ZTI_INIT(ztest_dmu_read_write_zcopy, 1, &zopt_often),
405 ZTI_INIT(ztest_dmu_objset_create_destroy, 1, &zopt_often),
406 ZTI_INIT(ztest_dsl_prop_get_set, 1, &zopt_often),
407 ZTI_INIT(ztest_spa_prop_get_set, 1, &zopt_sometimes),
408 #if 0
409 ZTI_INIT(ztest_dmu_prealloc, 1, &zopt_sometimes),
410 #endif
411 ZTI_INIT(ztest_fzap, 1, &zopt_sometimes),
412 ZTI_INIT(ztest_dmu_snapshot_create_destroy, 1, &zopt_sometimes),
413 ZTI_INIT(ztest_spa_create_destroy, 1, &zopt_sometimes),
414 ZTI_INIT(ztest_fault_inject, 1, &zopt_sometimes),
415 ZTI_INIT(ztest_ddt_repair, 1, &zopt_sometimes),
416 ZTI_INIT(ztest_dmu_snapshot_hold, 1, &zopt_sometimes),
417 ZTI_INIT(ztest_mmp_enable_disable, 1, &zopt_sometimes),
418 ZTI_INIT(ztest_reguid, 1, &zopt_rarely),
419 ZTI_INIT(ztest_scrub, 1, &zopt_rarely),
420 ZTI_INIT(ztest_spa_upgrade, 1, &zopt_rarely),
421 ZTI_INIT(ztest_dsl_dataset_promote_busy, 1, &zopt_rarely),
422 ZTI_INIT(ztest_vdev_attach_detach, 1, &zopt_sometimes),
423 ZTI_INIT(ztest_vdev_LUN_growth, 1, &zopt_rarely),
424 ZTI_INIT(ztest_vdev_add_remove, 1, &ztest_opts.zo_vdevtime),
425 ZTI_INIT(ztest_vdev_class_add, 1, &ztest_opts.zo_vdevtime),
426 ZTI_INIT(ztest_vdev_aux_add_remove, 1, &ztest_opts.zo_vdevtime),
427 ZTI_INIT(ztest_device_removal, 1, &zopt_sometimes),
428 ZTI_INIT(ztest_spa_checkpoint_create_discard, 1, &zopt_rarely),
429 ZTI_INIT(ztest_initialize, 1, &zopt_sometimes),
430 ZTI_INIT(ztest_fletcher, 1, &zopt_rarely),
431 ZTI_INIT(ztest_fletcher_incr, 1, &zopt_rarely),
432 ZTI_INIT(ztest_verify_dnode_bt, 1, &zopt_sometimes),
433 };
434
435 #define ZTEST_FUNCS (sizeof (ztest_info) / sizeof (ztest_info_t))
436
437 /*
438 * The following struct is used to hold a list of uncalled commit callbacks.
439 * The callbacks are ordered by txg number.
440 */
441 typedef struct ztest_cb_list {
442 kmutex_t zcl_callbacks_lock;
443 list_t zcl_callbacks;
444 } ztest_cb_list_t;
445
446 /*
447 * Stuff we need to share writably between parent and child.
448 */
449 typedef struct ztest_shared {
450 boolean_t zs_do_init;
451 hrtime_t zs_proc_start;
452 hrtime_t zs_proc_stop;
453 hrtime_t zs_thread_start;
454 hrtime_t zs_thread_stop;
455 hrtime_t zs_thread_kill;
456 uint64_t zs_enospc_count;
457 uint64_t zs_vdev_next_leaf;
458 uint64_t zs_vdev_aux;
459 uint64_t zs_alloc;
460 uint64_t zs_space;
461 uint64_t zs_splits;
462 uint64_t zs_mirrors;
463 uint64_t zs_metaslab_sz;
464 uint64_t zs_metaslab_df_alloc_threshold;
465 uint64_t zs_guid;
466 } ztest_shared_t;
467
468 #define ID_PARALLEL -1ULL
469
470 static char ztest_dev_template[] = "%s/%s.%llua";
471 static char ztest_aux_template[] = "%s/%s.%s.%llu";
472 ztest_shared_t *ztest_shared;
473
474 static spa_t *ztest_spa = NULL;
475 static ztest_ds_t *ztest_ds;
476
477 static kmutex_t ztest_vdev_lock;
478 static boolean_t ztest_device_removal_active = B_FALSE;
479 static kmutex_t ztest_checkpoint_lock;
480
481 /*
482 * The ztest_name_lock protects the pool and dataset namespace used by
483 * the individual tests. To modify the namespace, consumers must grab
484 * this lock as writer. Grabbing the lock as reader will ensure that the
485 * namespace does not change while the lock is held.
486 */
487 static pthread_rwlock_t ztest_name_lock;
488
489 static boolean_t ztest_dump_core = B_TRUE;
490 static boolean_t ztest_exiting;
491
492 /* Global commit callback list */
493 static ztest_cb_list_t zcl;
494 /* Commit cb delay */
495 static uint64_t zc_min_txg_delay = UINT64_MAX;
496 static int zc_cb_counter = 0;
497
498 /*
499 * Minimum number of commit callbacks that need to be registered for us to check
500 * whether the minimum txg delay is acceptable.
501 */
502 #define ZTEST_COMMIT_CB_MIN_REG 100
503
504 /*
505 * If a number of txgs equal to this threshold have been created after a commit
506 * callback has been registered but not called, then we assume there is an
507 * implementation bug.
508 */
509 #define ZTEST_COMMIT_CB_THRESH (TXG_CONCURRENT_STATES + 1000)
510
511 enum ztest_object {
512 ZTEST_META_DNODE = 0,
513 ZTEST_DIROBJ,
514 ZTEST_OBJECTS
515 };
516
517 static void usage(boolean_t) __NORETURN;
518
519 /*
520 * These libumem hooks provide a reasonable set of defaults for the allocator's
521 * debugging facilities.
522 */
523 const char *
524 _umem_debug_init(void)
525 {
526 return ("default,verbose"); /* $UMEM_DEBUG setting */
527 }
528
529 const char *
530 _umem_logging_init(void)
531 {
532 return ("fail,contents"); /* $UMEM_LOGGING setting */
533 }
534
535 static void
536 dump_debug_buffer(void)
537 {
538 ssize_t ret __attribute__((unused));
539
540 if (!ztest_opts.zo_dump_dbgmsg)
541 return;
542
543 /*
544 * We use write() instead of printf() so that this function
545 * is safe to call from a signal handler.
546 */
547 ret = write(STDOUT_FILENO, "\n", 1);
548 zfs_dbgmsg_print("ztest");
549 }
550
551 #define BACKTRACE_SZ 100
552
553 static void sig_handler(int signo)
554 {
555 struct sigaction action;
556 #ifdef __GLIBC__ /* backtrace() is a GNU extension */
557 int nptrs;
558 void *buffer[BACKTRACE_SZ];
559
560 nptrs = backtrace(buffer, BACKTRACE_SZ);
561 backtrace_symbols_fd(buffer, nptrs, STDERR_FILENO);
562 #endif
563 dump_debug_buffer();
564
565 /*
566 * Restore default action and re-raise signal so SIGSEGV and
567 * SIGABRT can trigger a core dump.
568 */
569 action.sa_handler = SIG_DFL;
570 sigemptyset(&action.sa_mask);
571 action.sa_flags = 0;
572 (void) sigaction(signo, &action, NULL);
573 raise(signo);
574 }
575
576 #define FATAL_MSG_SZ 1024
577
578 char *fatal_msg;
579
580 static void
581 fatal(int do_perror, char *message, ...)
582 {
583 va_list args;
584 int save_errno = errno;
585 char *buf;
586
587 (void) fflush(stdout);
588 buf = umem_alloc(FATAL_MSG_SZ, UMEM_NOFAIL);
589
590 va_start(args, message);
591 (void) sprintf(buf, "ztest: ");
592 /* LINTED */
593 (void) vsprintf(buf + strlen(buf), message, args);
594 va_end(args);
595 if (do_perror) {
596 (void) snprintf(buf + strlen(buf), FATAL_MSG_SZ - strlen(buf),
597 ": %s", strerror(save_errno));
598 }
599 (void) fprintf(stderr, "%s\n", buf);
600 fatal_msg = buf; /* to ease debugging */
601
602 if (ztest_dump_core)
603 abort();
604 else
605 dump_debug_buffer();
606
607 exit(3);
608 }
609
610 static int
611 str2shift(const char *buf)
612 {
613 const char *ends = "BKMGTPEZ";
614 int i;
615
616 if (buf[0] == '\0')
617 return (0);
618 for (i = 0; i < strlen(ends); i++) {
619 if (toupper(buf[0]) == ends[i])
620 break;
621 }
622 if (i == strlen(ends)) {
623 (void) fprintf(stderr, "ztest: invalid bytes suffix: %s\n",
624 buf);
625 usage(B_FALSE);
626 }
627 if (buf[1] == '\0' || (toupper(buf[1]) == 'B' && buf[2] == '\0')) {
628 return (10*i);
629 }
630 (void) fprintf(stderr, "ztest: invalid bytes suffix: %s\n", buf);
631 usage(B_FALSE);
632 /* NOTREACHED */
633 }
634
635 static uint64_t
636 nicenumtoull(const char *buf)
637 {
638 char *end;
639 uint64_t val;
640
641 val = strtoull(buf, &end, 0);
642 if (end == buf) {
643 (void) fprintf(stderr, "ztest: bad numeric value: %s\n", buf);
644 usage(B_FALSE);
645 } else if (end[0] == '.') {
646 double fval = strtod(buf, &end);
647 fval *= pow(2, str2shift(end));
648 if (fval > UINT64_MAX) {
649 (void) fprintf(stderr, "ztest: value too large: %s\n",
650 buf);
651 usage(B_FALSE);
652 }
653 val = (uint64_t)fval;
654 } else {
655 int shift = str2shift(end);
656 if (shift >= 64 || (val << shift) >> shift != val) {
657 (void) fprintf(stderr, "ztest: value too large: %s\n",
658 buf);
659 usage(B_FALSE);
660 }
661 val <<= shift;
662 }
663 return (val);
664 }
665
666 static void
667 usage(boolean_t requested)
668 {
669 const ztest_shared_opts_t *zo = &ztest_opts_defaults;
670
671 char nice_vdev_size[NN_NUMBUF_SZ];
672 char nice_force_ganging[NN_NUMBUF_SZ];
673 FILE *fp = requested ? stdout : stderr;
674
675 nicenum(zo->zo_vdev_size, nice_vdev_size, sizeof (nice_vdev_size));
676 nicenum(zo->zo_metaslab_force_ganging, nice_force_ganging,
677 sizeof (nice_force_ganging));
678
679 (void) fprintf(fp, "Usage: %s\n"
680 "\t[-v vdevs (default: %llu)]\n"
681 "\t[-s size_of_each_vdev (default: %s)]\n"
682 "\t[-a alignment_shift (default: %d)] use 0 for random\n"
683 "\t[-m mirror_copies (default: %d)]\n"
684 "\t[-r raidz_disks (default: %d)]\n"
685 "\t[-R raidz_parity (default: %d)]\n"
686 "\t[-d datasets (default: %d)]\n"
687 "\t[-t threads (default: %d)]\n"
688 "\t[-g gang_block_threshold (default: %s)]\n"
689 "\t[-i init_count (default: %d)] initialize pool i times\n"
690 "\t[-k kill_percentage (default: %llu%%)]\n"
691 "\t[-p pool_name (default: %s)]\n"
692 "\t[-f dir (default: %s)] file directory for vdev files\n"
693 "\t[-M] Multi-host simulate pool imported on remote host\n"
694 "\t[-V] verbose (use multiple times for ever more blather)\n"
695 "\t[-E] use existing pool instead of creating new one\n"
696 "\t[-T time (default: %llu sec)] total run time\n"
697 "\t[-F freezeloops (default: %llu)] max loops in spa_freeze()\n"
698 "\t[-P passtime (default: %llu sec)] time per pass\n"
699 "\t[-B alt_ztest (default: <none>)] alternate ztest path\n"
700 "\t[-C vdev class state (default: random)] special=on|off|random\n"
701 "\t[-o variable=value] ... set global variable to an unsigned\n"
702 "\t 32-bit integer value\n"
703 "\t[-G dump zfs_dbgmsg buffer before exiting due to an error\n"
704 "\t[-h] (print help)\n"
705 "",
706 zo->zo_pool,
707 (u_longlong_t)zo->zo_vdevs, /* -v */
708 nice_vdev_size, /* -s */
709 zo->zo_ashift, /* -a */
710 zo->zo_mirrors, /* -m */
711 zo->zo_raidz, /* -r */
712 zo->zo_raidz_parity, /* -R */
713 zo->zo_datasets, /* -d */
714 zo->zo_threads, /* -t */
715 nice_force_ganging, /* -g */
716 zo->zo_init, /* -i */
717 (u_longlong_t)zo->zo_killrate, /* -k */
718 zo->zo_pool, /* -p */
719 zo->zo_dir, /* -f */
720 (u_longlong_t)zo->zo_time, /* -T */
721 (u_longlong_t)zo->zo_maxloops, /* -F */
722 (u_longlong_t)zo->zo_passtime);
723 exit(requested ? 0 : 1);
724 }
725
726
727 static void
728 ztest_parse_name_value(const char *input, ztest_shared_opts_t *zo)
729 {
730 char name[32];
731 char *value;
732 int state = ZTEST_VDEV_CLASS_RND;
733
734 (void) strlcpy(name, input, sizeof (name));
735
736 value = strchr(name, '=');
737 if (value == NULL) {
738 (void) fprintf(stderr, "missing value in property=value "
739 "'-C' argument (%s)\n", input);
740 usage(B_FALSE);
741 }
742 *(value) = '\0';
743 value++;
744
745 if (strcmp(value, "on") == 0) {
746 state = ZTEST_VDEV_CLASS_ON;
747 } else if (strcmp(value, "off") == 0) {
748 state = ZTEST_VDEV_CLASS_OFF;
749 } else if (strcmp(value, "random") == 0) {
750 state = ZTEST_VDEV_CLASS_RND;
751 } else {
752 (void) fprintf(stderr, "invalid property value '%s'\n", value);
753 usage(B_FALSE);
754 }
755
756 if (strcmp(name, "special") == 0) {
757 zo->zo_special_vdevs = state;
758 } else {
759 (void) fprintf(stderr, "invalid property name '%s'\n", name);
760 usage(B_FALSE);
761 }
762 if (zo->zo_verbose >= 3)
763 (void) printf("%s vdev state is '%s'\n", name, value);
764 }
765
766 static void
767 process_options(int argc, char **argv)
768 {
769 char *path;
770 ztest_shared_opts_t *zo = &ztest_opts;
771
772 int opt;
773 uint64_t value;
774 char altdir[MAXNAMELEN] = { 0 };
775
776 bcopy(&ztest_opts_defaults, zo, sizeof (*zo));
777
778 while ((opt = getopt(argc, argv,
779 "v:s:a:m:r:R:d:t:g:i:k:p:f:MVET:P:hF:B:C:o:G")) != EOF) {
780 value = 0;
781 switch (opt) {
782 case 'v':
783 case 's':
784 case 'a':
785 case 'm':
786 case 'r':
787 case 'R':
788 case 'd':
789 case 't':
790 case 'g':
791 case 'i':
792 case 'k':
793 case 'T':
794 case 'P':
795 case 'F':
796 value = nicenumtoull(optarg);
797 }
798 switch (opt) {
799 case 'v':
800 zo->zo_vdevs = value;
801 break;
802 case 's':
803 zo->zo_vdev_size = MAX(SPA_MINDEVSIZE, value);
804 break;
805 case 'a':
806 zo->zo_ashift = value;
807 break;
808 case 'm':
809 zo->zo_mirrors = value;
810 break;
811 case 'r':
812 zo->zo_raidz = MAX(1, value);
813 break;
814 case 'R':
815 zo->zo_raidz_parity = MIN(MAX(value, 1), 3);
816 break;
817 case 'd':
818 zo->zo_datasets = MAX(1, value);
819 break;
820 case 't':
821 zo->zo_threads = MAX(1, value);
822 break;
823 case 'g':
824 zo->zo_metaslab_force_ganging =
825 MAX(SPA_MINBLOCKSIZE << 1, value);
826 break;
827 case 'i':
828 zo->zo_init = value;
829 break;
830 case 'k':
831 zo->zo_killrate = value;
832 break;
833 case 'p':
834 (void) strlcpy(zo->zo_pool, optarg,
835 sizeof (zo->zo_pool));
836 break;
837 case 'f':
838 path = realpath(optarg, NULL);
839 if (path == NULL) {
840 (void) fprintf(stderr, "error: %s: %s\n",
841 optarg, strerror(errno));
842 usage(B_FALSE);
843 } else {
844 (void) strlcpy(zo->zo_dir, path,
845 sizeof (zo->zo_dir));
846 free(path);
847 }
848 break;
849 case 'M':
850 zo->zo_mmp_test = 1;
851 break;
852 case 'V':
853 zo->zo_verbose++;
854 break;
855 case 'E':
856 zo->zo_init = 0;
857 break;
858 case 'T':
859 zo->zo_time = value;
860 break;
861 case 'P':
862 zo->zo_passtime = MAX(1, value);
863 break;
864 case 'F':
865 zo->zo_maxloops = MAX(1, value);
866 break;
867 case 'B':
868 (void) strlcpy(altdir, optarg, sizeof (altdir));
869 break;
870 case 'C':
871 ztest_parse_name_value(optarg, zo);
872 break;
873 case 'o':
874 if (set_global_var(optarg) != 0)
875 usage(B_FALSE);
876 break;
877 case 'G':
878 zo->zo_dump_dbgmsg = 1;
879 break;
880 case 'h':
881 usage(B_TRUE);
882 break;
883 case '?':
884 default:
885 usage(B_FALSE);
886 break;
887 }
888 }
889
890 zo->zo_raidz_parity = MIN(zo->zo_raidz_parity, zo->zo_raidz - 1);
891
892 zo->zo_vdevtime =
893 (zo->zo_vdevs > 0 ? zo->zo_time * NANOSEC / zo->zo_vdevs :
894 UINT64_MAX >> 2);
895
896 if (strlen(altdir) > 0) {
897 char *cmd;
898 char *realaltdir;
899 char *bin;
900 char *ztest;
901 char *isa;
902 int isalen;
903
904 cmd = umem_alloc(MAXPATHLEN, UMEM_NOFAIL);
905 realaltdir = umem_alloc(MAXPATHLEN, UMEM_NOFAIL);
906
907 VERIFY(NULL != realpath(getexecname(), cmd));
908 if (0 != access(altdir, F_OK)) {
909 ztest_dump_core = B_FALSE;
910 fatal(B_TRUE, "invalid alternate ztest path: %s",
911 altdir);
912 }
913 VERIFY(NULL != realpath(altdir, realaltdir));
914
915 /*
916 * 'cmd' should be of the form "<anything>/usr/bin/<isa>/ztest".
917 * We want to extract <isa> to determine if we should use
918 * 32 or 64 bit binaries.
919 */
920 bin = strstr(cmd, "/usr/bin/");
921 ztest = strstr(bin, "/ztest");
922 isa = bin + 9;
923 isalen = ztest - isa;
924 (void) snprintf(zo->zo_alt_ztest, sizeof (zo->zo_alt_ztest),
925 "%s/usr/bin/%.*s/ztest", realaltdir, isalen, isa);
926 (void) snprintf(zo->zo_alt_libpath, sizeof (zo->zo_alt_libpath),
927 "%s/usr/lib/%.*s", realaltdir, isalen, isa);
928
929 if (0 != access(zo->zo_alt_ztest, X_OK)) {
930 ztest_dump_core = B_FALSE;
931 fatal(B_TRUE, "invalid alternate ztest: %s",
932 zo->zo_alt_ztest);
933 } else if (0 != access(zo->zo_alt_libpath, X_OK)) {
934 ztest_dump_core = B_FALSE;
935 fatal(B_TRUE, "invalid alternate lib directory %s",
936 zo->zo_alt_libpath);
937 }
938
939 umem_free(cmd, MAXPATHLEN);
940 umem_free(realaltdir, MAXPATHLEN);
941 }
942 }
943
944 static void
945 ztest_kill(ztest_shared_t *zs)
946 {
947 zs->zs_alloc = metaslab_class_get_alloc(spa_normal_class(ztest_spa));
948 zs->zs_space = metaslab_class_get_space(spa_normal_class(ztest_spa));
949
950 /*
951 * Before we kill off ztest, make sure that the config is updated.
952 * See comment above spa_write_cachefile().
953 */
954 mutex_enter(&spa_namespace_lock);
955 spa_write_cachefile(ztest_spa, B_FALSE, B_FALSE);
956 mutex_exit(&spa_namespace_lock);
957
958 (void) kill(getpid(), SIGKILL);
959 }
960
961 static uint64_t
962 ztest_random(uint64_t range)
963 {
964 uint64_t r;
965
966 ASSERT3S(ztest_fd_rand, >=, 0);
967
968 if (range == 0)
969 return (0);
970
971 if (read(ztest_fd_rand, &r, sizeof (r)) != sizeof (r))
972 fatal(1, "short read from /dev/urandom");
973
974 return (r % range);
975 }
976
977 /* ARGSUSED */
978 static void
979 ztest_record_enospc(const char *s)
980 {
981 ztest_shared->zs_enospc_count++;
982 }
983
984 static uint64_t
985 ztest_get_ashift(void)
986 {
987 if (ztest_opts.zo_ashift == 0)
988 return (SPA_MINBLOCKSHIFT + ztest_random(5));
989 return (ztest_opts.zo_ashift);
990 }
991
992 static nvlist_t *
993 make_vdev_file(char *path, char *aux, char *pool, size_t size, uint64_t ashift)
994 {
995 char *pathbuf;
996 uint64_t vdev;
997 nvlist_t *file;
998
999 pathbuf = umem_alloc(MAXPATHLEN, UMEM_NOFAIL);
1000
1001 if (ashift == 0)
1002 ashift = ztest_get_ashift();
1003
1004 if (path == NULL) {
1005 path = pathbuf;
1006
1007 if (aux != NULL) {
1008 vdev = ztest_shared->zs_vdev_aux;
1009 (void) snprintf(path, MAXPATHLEN,
1010 ztest_aux_template, ztest_opts.zo_dir,
1011 pool == NULL ? ztest_opts.zo_pool : pool,
1012 aux, vdev);
1013 } else {
1014 vdev = ztest_shared->zs_vdev_next_leaf++;
1015 (void) snprintf(path, MAXPATHLEN,
1016 ztest_dev_template, ztest_opts.zo_dir,
1017 pool == NULL ? ztest_opts.zo_pool : pool, vdev);
1018 }
1019 }
1020
1021 if (size != 0) {
1022 int fd = open(path, O_RDWR | O_CREAT | O_TRUNC, 0666);
1023 if (fd == -1)
1024 fatal(1, "can't open %s", path);
1025 if (ftruncate(fd, size) != 0)
1026 fatal(1, "can't ftruncate %s", path);
1027 (void) close(fd);
1028 }
1029
1030 VERIFY(nvlist_alloc(&file, NV_UNIQUE_NAME, 0) == 0);
1031 VERIFY(nvlist_add_string(file, ZPOOL_CONFIG_TYPE, VDEV_TYPE_FILE) == 0);
1032 VERIFY(nvlist_add_string(file, ZPOOL_CONFIG_PATH, path) == 0);
1033 VERIFY(nvlist_add_uint64(file, ZPOOL_CONFIG_ASHIFT, ashift) == 0);
1034 umem_free(pathbuf, MAXPATHLEN);
1035
1036 return (file);
1037 }
1038
1039 static nvlist_t *
1040 make_vdev_raidz(char *path, char *aux, char *pool, size_t size,
1041 uint64_t ashift, int r)
1042 {
1043 nvlist_t *raidz, **child;
1044 int c;
1045
1046 if (r < 2)
1047 return (make_vdev_file(path, aux, pool, size, ashift));
1048 child = umem_alloc(r * sizeof (nvlist_t *), UMEM_NOFAIL);
1049
1050 for (c = 0; c < r; c++)
1051 child[c] = make_vdev_file(path, aux, pool, size, ashift);
1052
1053 VERIFY(nvlist_alloc(&raidz, NV_UNIQUE_NAME, 0) == 0);
1054 VERIFY(nvlist_add_string(raidz, ZPOOL_CONFIG_TYPE,
1055 VDEV_TYPE_RAIDZ) == 0);
1056 VERIFY(nvlist_add_uint64(raidz, ZPOOL_CONFIG_NPARITY,
1057 ztest_opts.zo_raidz_parity) == 0);
1058 VERIFY(nvlist_add_nvlist_array(raidz, ZPOOL_CONFIG_CHILDREN,
1059 child, r) == 0);
1060
1061 for (c = 0; c < r; c++)
1062 nvlist_free(child[c]);
1063
1064 umem_free(child, r * sizeof (nvlist_t *));
1065
1066 return (raidz);
1067 }
1068
1069 static nvlist_t *
1070 make_vdev_mirror(char *path, char *aux, char *pool, size_t size,
1071 uint64_t ashift, int r, int m)
1072 {
1073 nvlist_t *mirror, **child;
1074 int c;
1075
1076 if (m < 1)
1077 return (make_vdev_raidz(path, aux, pool, size, ashift, r));
1078
1079 child = umem_alloc(m * sizeof (nvlist_t *), UMEM_NOFAIL);
1080
1081 for (c = 0; c < m; c++)
1082 child[c] = make_vdev_raidz(path, aux, pool, size, ashift, r);
1083
1084 VERIFY(nvlist_alloc(&mirror, NV_UNIQUE_NAME, 0) == 0);
1085 VERIFY(nvlist_add_string(mirror, ZPOOL_CONFIG_TYPE,
1086 VDEV_TYPE_MIRROR) == 0);
1087 VERIFY(nvlist_add_nvlist_array(mirror, ZPOOL_CONFIG_CHILDREN,
1088 child, m) == 0);
1089
1090 for (c = 0; c < m; c++)
1091 nvlist_free(child[c]);
1092
1093 umem_free(child, m * sizeof (nvlist_t *));
1094
1095 return (mirror);
1096 }
1097
1098 static nvlist_t *
1099 make_vdev_root(char *path, char *aux, char *pool, size_t size, uint64_t ashift,
1100 const char *class, int r, int m, int t)
1101 {
1102 nvlist_t *root, **child;
1103 int c;
1104 boolean_t log;
1105
1106 ASSERT(t > 0);
1107
1108 log = (class != NULL && strcmp(class, "log") == 0);
1109
1110 child = umem_alloc(t * sizeof (nvlist_t *), UMEM_NOFAIL);
1111
1112 for (c = 0; c < t; c++) {
1113 child[c] = make_vdev_mirror(path, aux, pool, size, ashift,
1114 r, m);
1115 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
1116 log) == 0);
1117
1118 if (class != NULL && class[0] != '\0') {
1119 ASSERT(m > 1 || log); /* expecting a mirror */
1120 VERIFY(nvlist_add_string(child[c],
1121 ZPOOL_CONFIG_ALLOCATION_BIAS, class) == 0);
1122 }
1123 }
1124
1125 VERIFY(nvlist_alloc(&root, NV_UNIQUE_NAME, 0) == 0);
1126 VERIFY(nvlist_add_string(root, ZPOOL_CONFIG_TYPE, VDEV_TYPE_ROOT) == 0);
1127 VERIFY(nvlist_add_nvlist_array(root, aux ? aux : ZPOOL_CONFIG_CHILDREN,
1128 child, t) == 0);
1129
1130 for (c = 0; c < t; c++)
1131 nvlist_free(child[c]);
1132
1133 umem_free(child, t * sizeof (nvlist_t *));
1134
1135 return (root);
1136 }
1137
1138 /*
1139 * Find a random spa version. Returns back a random spa version in the
1140 * range [initial_version, SPA_VERSION_FEATURES].
1141 */
1142 static uint64_t
1143 ztest_random_spa_version(uint64_t initial_version)
1144 {
1145 uint64_t version = initial_version;
1146
1147 if (version <= SPA_VERSION_BEFORE_FEATURES) {
1148 version = version +
1149 ztest_random(SPA_VERSION_BEFORE_FEATURES - version + 1);
1150 }
1151
1152 if (version > SPA_VERSION_BEFORE_FEATURES)
1153 version = SPA_VERSION_FEATURES;
1154
1155 ASSERT(SPA_VERSION_IS_SUPPORTED(version));
1156 return (version);
1157 }
1158
1159 static int
1160 ztest_random_blocksize(void)
1161 {
1162 ASSERT(ztest_spa->spa_max_ashift != 0);
1163
1164 /*
1165 * Choose a block size >= the ashift.
1166 * If the SPA supports new MAXBLOCKSIZE, test up to 1MB blocks.
1167 */
1168 int maxbs = SPA_OLD_MAXBLOCKSHIFT;
1169 if (spa_maxblocksize(ztest_spa) == SPA_MAXBLOCKSIZE)
1170 maxbs = 20;
1171 uint64_t block_shift =
1172 ztest_random(maxbs - ztest_spa->spa_max_ashift + 1);
1173 return (1 << (SPA_MINBLOCKSHIFT + block_shift));
1174 }
1175
1176 static int
1177 ztest_random_dnodesize(void)
1178 {
1179 int slots;
1180 int max_slots = spa_maxdnodesize(ztest_spa) >> DNODE_SHIFT;
1181
1182 if (max_slots == DNODE_MIN_SLOTS)
1183 return (DNODE_MIN_SIZE);
1184
1185 /*
1186 * Weight the random distribution more heavily toward smaller
1187 * dnode sizes since that is more likely to reflect real-world
1188 * usage.
1189 */
1190 ASSERT3U(max_slots, >, 4);
1191 switch (ztest_random(10)) {
1192 case 0:
1193 slots = 5 + ztest_random(max_slots - 4);
1194 break;
1195 case 1 ... 4:
1196 slots = 2 + ztest_random(3);
1197 break;
1198 default:
1199 slots = 1;
1200 break;
1201 }
1202
1203 return (slots << DNODE_SHIFT);
1204 }
1205
1206 static int
1207 ztest_random_ibshift(void)
1208 {
1209 return (DN_MIN_INDBLKSHIFT +
1210 ztest_random(DN_MAX_INDBLKSHIFT - DN_MIN_INDBLKSHIFT + 1));
1211 }
1212
1213 static uint64_t
1214 ztest_random_vdev_top(spa_t *spa, boolean_t log_ok)
1215 {
1216 uint64_t top;
1217 vdev_t *rvd = spa->spa_root_vdev;
1218 vdev_t *tvd;
1219
1220 ASSERT(spa_config_held(spa, SCL_ALL, RW_READER) != 0);
1221
1222 do {
1223 top = ztest_random(rvd->vdev_children);
1224 tvd = rvd->vdev_child[top];
1225 } while (!vdev_is_concrete(tvd) || (tvd->vdev_islog && !log_ok) ||
1226 tvd->vdev_mg == NULL || tvd->vdev_mg->mg_class == NULL);
1227
1228 return (top);
1229 }
1230
1231 static uint64_t
1232 ztest_random_dsl_prop(zfs_prop_t prop)
1233 {
1234 uint64_t value;
1235
1236 do {
1237 value = zfs_prop_random_value(prop, ztest_random(-1ULL));
1238 } while (prop == ZFS_PROP_CHECKSUM && value == ZIO_CHECKSUM_OFF);
1239
1240 return (value);
1241 }
1242
1243 static int
1244 ztest_dsl_prop_set_uint64(char *osname, zfs_prop_t prop, uint64_t value,
1245 boolean_t inherit)
1246 {
1247 const char *propname = zfs_prop_to_name(prop);
1248 const char *valname;
1249 char *setpoint;
1250 uint64_t curval;
1251 int error;
1252
1253 error = dsl_prop_set_int(osname, propname,
1254 (inherit ? ZPROP_SRC_NONE : ZPROP_SRC_LOCAL), value);
1255
1256 if (error == ENOSPC) {
1257 ztest_record_enospc(FTAG);
1258 return (error);
1259 }
1260 ASSERT0(error);
1261
1262 setpoint = umem_alloc(MAXPATHLEN, UMEM_NOFAIL);
1263 VERIFY0(dsl_prop_get_integer(osname, propname, &curval, setpoint));
1264
1265 if (ztest_opts.zo_verbose >= 6) {
1266 int err;
1267
1268 err = zfs_prop_index_to_string(prop, curval, &valname);
1269 if (err)
1270 (void) printf("%s %s = %llu at '%s'\n", osname,
1271 propname, (unsigned long long)curval, setpoint);
1272 else
1273 (void) printf("%s %s = %s at '%s'\n",
1274 osname, propname, valname, setpoint);
1275 }
1276 umem_free(setpoint, MAXPATHLEN);
1277
1278 return (error);
1279 }
1280
1281 static int
1282 ztest_spa_prop_set_uint64(zpool_prop_t prop, uint64_t value)
1283 {
1284 spa_t *spa = ztest_spa;
1285 nvlist_t *props = NULL;
1286 int error;
1287
1288 VERIFY(nvlist_alloc(&props, NV_UNIQUE_NAME, 0) == 0);
1289 VERIFY(nvlist_add_uint64(props, zpool_prop_to_name(prop), value) == 0);
1290
1291 error = spa_prop_set(spa, props);
1292
1293 nvlist_free(props);
1294
1295 if (error == ENOSPC) {
1296 ztest_record_enospc(FTAG);
1297 return (error);
1298 }
1299 ASSERT0(error);
1300
1301 return (error);
1302 }
1303
1304 static int
1305 ztest_dmu_objset_own(const char *name, dmu_objset_type_t type,
1306 boolean_t readonly, boolean_t decrypt, void *tag, objset_t **osp)
1307 {
1308 int err;
1309 char *cp = NULL;
1310 char ddname[ZFS_MAX_DATASET_NAME_LEN];
1311
1312 strcpy(ddname, name);
1313 cp = strchr(ddname, '@');
1314 if (cp != NULL)
1315 *cp = '\0';
1316
1317 err = dmu_objset_own(name, type, readonly, decrypt, tag, osp);
1318 while (decrypt && err == EACCES) {
1319 dsl_crypto_params_t *dcp;
1320 nvlist_t *crypto_args = fnvlist_alloc();
1321
1322 fnvlist_add_uint8_array(crypto_args, "wkeydata",
1323 (uint8_t *)ztest_wkeydata, WRAPPING_KEY_LEN);
1324 VERIFY0(dsl_crypto_params_create_nvlist(DCP_CMD_NONE, NULL,
1325 crypto_args, &dcp));
1326 err = spa_keystore_load_wkey(ddname, dcp, B_FALSE);
1327 dsl_crypto_params_free(dcp, B_FALSE);
1328 fnvlist_free(crypto_args);
1329
1330 if (err == EINVAL) {
1331 /*
1332 * We couldn't load a key for this dataset so try
1333 * the parent. This loop will eventually hit the
1334 * encryption root since ztest only makes clones
1335 * as children of their origin datasets.
1336 */
1337 cp = strrchr(ddname, '/');
1338 if (cp == NULL)
1339 return (err);
1340
1341 *cp = '\0';
1342 err = EACCES;
1343 continue;
1344 } else if (err != 0) {
1345 break;
1346 }
1347
1348 err = dmu_objset_own(name, type, readonly, decrypt, tag, osp);
1349 break;
1350 }
1351
1352 return (err);
1353 }
1354
1355 static void
1356 ztest_rll_init(rll_t *rll)
1357 {
1358 rll->rll_writer = NULL;
1359 rll->rll_readers = 0;
1360 mutex_init(&rll->rll_lock, NULL, MUTEX_DEFAULT, NULL);
1361 cv_init(&rll->rll_cv, NULL, CV_DEFAULT, NULL);
1362 }
1363
1364 static void
1365 ztest_rll_destroy(rll_t *rll)
1366 {
1367 ASSERT(rll->rll_writer == NULL);
1368 ASSERT(rll->rll_readers == 0);
1369 mutex_destroy(&rll->rll_lock);
1370 cv_destroy(&rll->rll_cv);
1371 }
1372
1373 static void
1374 ztest_rll_lock(rll_t *rll, rl_type_t type)
1375 {
1376 mutex_enter(&rll->rll_lock);
1377
1378 if (type == RL_READER) {
1379 while (rll->rll_writer != NULL)
1380 (void) cv_wait(&rll->rll_cv, &rll->rll_lock);
1381 rll->rll_readers++;
1382 } else {
1383 while (rll->rll_writer != NULL || rll->rll_readers)
1384 (void) cv_wait(&rll->rll_cv, &rll->rll_lock);
1385 rll->rll_writer = curthread;
1386 }
1387
1388 mutex_exit(&rll->rll_lock);
1389 }
1390
1391 static void
1392 ztest_rll_unlock(rll_t *rll)
1393 {
1394 mutex_enter(&rll->rll_lock);
1395
1396 if (rll->rll_writer) {
1397 ASSERT(rll->rll_readers == 0);
1398 rll->rll_writer = NULL;
1399 } else {
1400 ASSERT(rll->rll_readers != 0);
1401 ASSERT(rll->rll_writer == NULL);
1402 rll->rll_readers--;
1403 }
1404
1405 if (rll->rll_writer == NULL && rll->rll_readers == 0)
1406 cv_broadcast(&rll->rll_cv);
1407
1408 mutex_exit(&rll->rll_lock);
1409 }
1410
1411 static void
1412 ztest_object_lock(ztest_ds_t *zd, uint64_t object, rl_type_t type)
1413 {
1414 rll_t *rll = &zd->zd_object_lock[object & (ZTEST_OBJECT_LOCKS - 1)];
1415
1416 ztest_rll_lock(rll, type);
1417 }
1418
1419 static void
1420 ztest_object_unlock(ztest_ds_t *zd, uint64_t object)
1421 {
1422 rll_t *rll = &zd->zd_object_lock[object & (ZTEST_OBJECT_LOCKS - 1)];
1423
1424 ztest_rll_unlock(rll);
1425 }
1426
1427 static rl_t *
1428 ztest_range_lock(ztest_ds_t *zd, uint64_t object, uint64_t offset,
1429 uint64_t size, rl_type_t type)
1430 {
1431 uint64_t hash = object ^ (offset % (ZTEST_RANGE_LOCKS + 1));
1432 rll_t *rll = &zd->zd_range_lock[hash & (ZTEST_RANGE_LOCKS - 1)];
1433 rl_t *rl;
1434
1435 rl = umem_alloc(sizeof (*rl), UMEM_NOFAIL);
1436 rl->rl_object = object;
1437 rl->rl_offset = offset;
1438 rl->rl_size = size;
1439 rl->rl_lock = rll;
1440
1441 ztest_rll_lock(rll, type);
1442
1443 return (rl);
1444 }
1445
1446 static void
1447 ztest_range_unlock(rl_t *rl)
1448 {
1449 rll_t *rll = rl->rl_lock;
1450
1451 ztest_rll_unlock(rll);
1452
1453 umem_free(rl, sizeof (*rl));
1454 }
1455
1456 static void
1457 ztest_zd_init(ztest_ds_t *zd, ztest_shared_ds_t *szd, objset_t *os)
1458 {
1459 zd->zd_os = os;
1460 zd->zd_zilog = dmu_objset_zil(os);
1461 zd->zd_shared = szd;
1462 dmu_objset_name(os, zd->zd_name);
1463 int l;
1464
1465 if (zd->zd_shared != NULL)
1466 zd->zd_shared->zd_seq = 0;
1467
1468 VERIFY0(pthread_rwlock_init(&zd->zd_zilog_lock, NULL));
1469 mutex_init(&zd->zd_dirobj_lock, NULL, MUTEX_DEFAULT, NULL);
1470
1471 for (l = 0; l < ZTEST_OBJECT_LOCKS; l++)
1472 ztest_rll_init(&zd->zd_object_lock[l]);
1473
1474 for (l = 0; l < ZTEST_RANGE_LOCKS; l++)
1475 ztest_rll_init(&zd->zd_range_lock[l]);
1476 }
1477
1478 static void
1479 ztest_zd_fini(ztest_ds_t *zd)
1480 {
1481 int l;
1482
1483 mutex_destroy(&zd->zd_dirobj_lock);
1484 (void) pthread_rwlock_destroy(&zd->zd_zilog_lock);
1485
1486 for (l = 0; l < ZTEST_OBJECT_LOCKS; l++)
1487 ztest_rll_destroy(&zd->zd_object_lock[l]);
1488
1489 for (l = 0; l < ZTEST_RANGE_LOCKS; l++)
1490 ztest_rll_destroy(&zd->zd_range_lock[l]);
1491 }
1492
1493 #define TXG_MIGHTWAIT (ztest_random(10) == 0 ? TXG_NOWAIT : TXG_WAIT)
1494
1495 static uint64_t
1496 ztest_tx_assign(dmu_tx_t *tx, uint64_t txg_how, const char *tag)
1497 {
1498 uint64_t txg;
1499 int error;
1500
1501 /*
1502 * Attempt to assign tx to some transaction group.
1503 */
1504 error = dmu_tx_assign(tx, txg_how);
1505 if (error) {
1506 if (error == ERESTART) {
1507 ASSERT(txg_how == TXG_NOWAIT);
1508 dmu_tx_wait(tx);
1509 } else {
1510 ASSERT3U(error, ==, ENOSPC);
1511 ztest_record_enospc(tag);
1512 }
1513 dmu_tx_abort(tx);
1514 return (0);
1515 }
1516 txg = dmu_tx_get_txg(tx);
1517 ASSERT(txg != 0);
1518 return (txg);
1519 }
1520
1521 static void
1522 ztest_pattern_set(void *buf, uint64_t size, uint64_t value)
1523 {
1524 uint64_t *ip = buf;
1525 uint64_t *ip_end = (uint64_t *)((uintptr_t)buf + (uintptr_t)size);
1526
1527 while (ip < ip_end)
1528 *ip++ = value;
1529 }
1530
1531 #ifndef NDEBUG
1532 static boolean_t
1533 ztest_pattern_match(void *buf, uint64_t size, uint64_t value)
1534 {
1535 uint64_t *ip = buf;
1536 uint64_t *ip_end = (uint64_t *)((uintptr_t)buf + (uintptr_t)size);
1537 uint64_t diff = 0;
1538
1539 while (ip < ip_end)
1540 diff |= (value - *ip++);
1541
1542 return (diff == 0);
1543 }
1544 #endif
1545
1546 static void
1547 ztest_bt_generate(ztest_block_tag_t *bt, objset_t *os, uint64_t object,
1548 uint64_t dnodesize, uint64_t offset, uint64_t gen, uint64_t txg,
1549 uint64_t crtxg)
1550 {
1551 bt->bt_magic = BT_MAGIC;
1552 bt->bt_objset = dmu_objset_id(os);
1553 bt->bt_object = object;
1554 bt->bt_dnodesize = dnodesize;
1555 bt->bt_offset = offset;
1556 bt->bt_gen = gen;
1557 bt->bt_txg = txg;
1558 bt->bt_crtxg = crtxg;
1559 }
1560
1561 static void
1562 ztest_bt_verify(ztest_block_tag_t *bt, objset_t *os, uint64_t object,
1563 uint64_t dnodesize, uint64_t offset, uint64_t gen, uint64_t txg,
1564 uint64_t crtxg)
1565 {
1566 ASSERT3U(bt->bt_magic, ==, BT_MAGIC);
1567 ASSERT3U(bt->bt_objset, ==, dmu_objset_id(os));
1568 ASSERT3U(bt->bt_object, ==, object);
1569 ASSERT3U(bt->bt_dnodesize, ==, dnodesize);
1570 ASSERT3U(bt->bt_offset, ==, offset);
1571 ASSERT3U(bt->bt_gen, <=, gen);
1572 ASSERT3U(bt->bt_txg, <=, txg);
1573 ASSERT3U(bt->bt_crtxg, ==, crtxg);
1574 }
1575
1576 static ztest_block_tag_t *
1577 ztest_bt_bonus(dmu_buf_t *db)
1578 {
1579 dmu_object_info_t doi;
1580 ztest_block_tag_t *bt;
1581
1582 dmu_object_info_from_db(db, &doi);
1583 ASSERT3U(doi.doi_bonus_size, <=, db->db_size);
1584 ASSERT3U(doi.doi_bonus_size, >=, sizeof (*bt));
1585 bt = (void *)((char *)db->db_data + doi.doi_bonus_size - sizeof (*bt));
1586
1587 return (bt);
1588 }
1589
1590 /*
1591 * Generate a token to fill up unused bonus buffer space. Try to make
1592 * it unique to the object, generation, and offset to verify that data
1593 * is not getting overwritten by data from other dnodes.
1594 */
1595 #define ZTEST_BONUS_FILL_TOKEN(obj, ds, gen, offset) \
1596 (((ds) << 48) | ((gen) << 32) | ((obj) << 8) | (offset))
1597
1598 /*
1599 * Fill up the unused bonus buffer region before the block tag with a
1600 * verifiable pattern. Filling the whole bonus area with non-zero data
1601 * helps ensure that all dnode traversal code properly skips the
1602 * interior regions of large dnodes.
1603 */
1604 void
1605 ztest_fill_unused_bonus(dmu_buf_t *db, void *end, uint64_t obj,
1606 objset_t *os, uint64_t gen)
1607 {
1608 uint64_t *bonusp;
1609
1610 ASSERT(IS_P2ALIGNED((char *)end - (char *)db->db_data, 8));
1611
1612 for (bonusp = db->db_data; bonusp < (uint64_t *)end; bonusp++) {
1613 uint64_t token = ZTEST_BONUS_FILL_TOKEN(obj, dmu_objset_id(os),
1614 gen, bonusp - (uint64_t *)db->db_data);
1615 *bonusp = token;
1616 }
1617 }
1618
1619 /*
1620 * Verify that the unused area of a bonus buffer is filled with the
1621 * expected tokens.
1622 */
1623 void
1624 ztest_verify_unused_bonus(dmu_buf_t *db, void *end, uint64_t obj,
1625 objset_t *os, uint64_t gen)
1626 {
1627 uint64_t *bonusp;
1628
1629 for (bonusp = db->db_data; bonusp < (uint64_t *)end; bonusp++) {
1630 uint64_t token = ZTEST_BONUS_FILL_TOKEN(obj, dmu_objset_id(os),
1631 gen, bonusp - (uint64_t *)db->db_data);
1632 VERIFY3U(*bonusp, ==, token);
1633 }
1634 }
1635
1636 /*
1637 * ZIL logging ops
1638 */
1639
1640 #define lrz_type lr_mode
1641 #define lrz_blocksize lr_uid
1642 #define lrz_ibshift lr_gid
1643 #define lrz_bonustype lr_rdev
1644 #define lrz_dnodesize lr_crtime[1]
1645
1646 static void
1647 ztest_log_create(ztest_ds_t *zd, dmu_tx_t *tx, lr_create_t *lr)
1648 {
1649 char *name = (void *)(lr + 1); /* name follows lr */
1650 size_t namesize = strlen(name) + 1;
1651 itx_t *itx;
1652
1653 if (zil_replaying(zd->zd_zilog, tx))
1654 return;
1655
1656 itx = zil_itx_create(TX_CREATE, sizeof (*lr) + namesize);
1657 bcopy(&lr->lr_common + 1, &itx->itx_lr + 1,
1658 sizeof (*lr) + namesize - sizeof (lr_t));
1659
1660 zil_itx_assign(zd->zd_zilog, itx, tx);
1661 }
1662
1663 static void
1664 ztest_log_remove(ztest_ds_t *zd, dmu_tx_t *tx, lr_remove_t *lr, uint64_t object)
1665 {
1666 char *name = (void *)(lr + 1); /* name follows lr */
1667 size_t namesize = strlen(name) + 1;
1668 itx_t *itx;
1669
1670 if (zil_replaying(zd->zd_zilog, tx))
1671 return;
1672
1673 itx = zil_itx_create(TX_REMOVE, sizeof (*lr) + namesize);
1674 bcopy(&lr->lr_common + 1, &itx->itx_lr + 1,
1675 sizeof (*lr) + namesize - sizeof (lr_t));
1676
1677 itx->itx_oid = object;
1678 zil_itx_assign(zd->zd_zilog, itx, tx);
1679 }
1680
1681 static void
1682 ztest_log_write(ztest_ds_t *zd, dmu_tx_t *tx, lr_write_t *lr)
1683 {
1684 itx_t *itx;
1685 itx_wr_state_t write_state = ztest_random(WR_NUM_STATES);
1686
1687 if (zil_replaying(zd->zd_zilog, tx))
1688 return;
1689
1690 if (lr->lr_length > ZIL_MAX_LOG_DATA)
1691 write_state = WR_INDIRECT;
1692
1693 itx = zil_itx_create(TX_WRITE,
1694 sizeof (*lr) + (write_state == WR_COPIED ? lr->lr_length : 0));
1695
1696 if (write_state == WR_COPIED &&
1697 dmu_read(zd->zd_os, lr->lr_foid, lr->lr_offset, lr->lr_length,
1698 ((lr_write_t *)&itx->itx_lr) + 1, DMU_READ_NO_PREFETCH) != 0) {
1699 zil_itx_destroy(itx);
1700 itx = zil_itx_create(TX_WRITE, sizeof (*lr));
1701 write_state = WR_NEED_COPY;
1702 }
1703 itx->itx_private = zd;
1704 itx->itx_wr_state = write_state;
1705 itx->itx_sync = (ztest_random(8) == 0);
1706
1707 bcopy(&lr->lr_common + 1, &itx->itx_lr + 1,
1708 sizeof (*lr) - sizeof (lr_t));
1709
1710 zil_itx_assign(zd->zd_zilog, itx, tx);
1711 }
1712
1713 static void
1714 ztest_log_truncate(ztest_ds_t *zd, dmu_tx_t *tx, lr_truncate_t *lr)
1715 {
1716 itx_t *itx;
1717
1718 if (zil_replaying(zd->zd_zilog, tx))
1719 return;
1720
1721 itx = zil_itx_create(TX_TRUNCATE, sizeof (*lr));
1722 bcopy(&lr->lr_common + 1, &itx->itx_lr + 1,
1723 sizeof (*lr) - sizeof (lr_t));
1724
1725 itx->itx_sync = B_FALSE;
1726 zil_itx_assign(zd->zd_zilog, itx, tx);
1727 }
1728
1729 static void
1730 ztest_log_setattr(ztest_ds_t *zd, dmu_tx_t *tx, lr_setattr_t *lr)
1731 {
1732 itx_t *itx;
1733
1734 if (zil_replaying(zd->zd_zilog, tx))
1735 return;
1736
1737 itx = zil_itx_create(TX_SETATTR, sizeof (*lr));
1738 bcopy(&lr->lr_common + 1, &itx->itx_lr + 1,
1739 sizeof (*lr) - sizeof (lr_t));
1740
1741 itx->itx_sync = B_FALSE;
1742 zil_itx_assign(zd->zd_zilog, itx, tx);
1743 }
1744
1745 /*
1746 * ZIL replay ops
1747 */
1748 static int
1749 ztest_replay_create(void *arg1, void *arg2, boolean_t byteswap)
1750 {
1751 ztest_ds_t *zd = arg1;
1752 lr_create_t *lr = arg2;
1753 char *name = (void *)(lr + 1); /* name follows lr */
1754 objset_t *os = zd->zd_os;
1755 ztest_block_tag_t *bbt;
1756 dmu_buf_t *db;
1757 dmu_tx_t *tx;
1758 uint64_t txg;
1759 int error = 0;
1760 int bonuslen;
1761
1762 if (byteswap)
1763 byteswap_uint64_array(lr, sizeof (*lr));
1764
1765 ASSERT(lr->lr_doid == ZTEST_DIROBJ);
1766 ASSERT(name[0] != '\0');
1767
1768 tx = dmu_tx_create(os);
1769
1770 dmu_tx_hold_zap(tx, lr->lr_doid, B_TRUE, name);
1771
1772 if (lr->lrz_type == DMU_OT_ZAP_OTHER) {
1773 dmu_tx_hold_zap(tx, DMU_NEW_OBJECT, B_TRUE, NULL);
1774 } else {
1775 dmu_tx_hold_bonus(tx, DMU_NEW_OBJECT);
1776 }
1777
1778 txg = ztest_tx_assign(tx, TXG_WAIT, FTAG);
1779 if (txg == 0)
1780 return (ENOSPC);
1781
1782 ASSERT(dmu_objset_zil(os)->zl_replay == !!lr->lr_foid);
1783 bonuslen = DN_BONUS_SIZE(lr->lrz_dnodesize);
1784
1785 if (lr->lrz_type == DMU_OT_ZAP_OTHER) {
1786 if (lr->lr_foid == 0) {
1787 lr->lr_foid = zap_create_dnsize(os,
1788 lr->lrz_type, lr->lrz_bonustype,
1789 bonuslen, lr->lrz_dnodesize, tx);
1790 } else {
1791 error = zap_create_claim_dnsize(os, lr->lr_foid,
1792 lr->lrz_type, lr->lrz_bonustype,
1793 bonuslen, lr->lrz_dnodesize, tx);
1794 }
1795 } else {
1796 if (lr->lr_foid == 0) {
1797 lr->lr_foid = dmu_object_alloc_dnsize(os,
1798 lr->lrz_type, 0, lr->lrz_bonustype,
1799 bonuslen, lr->lrz_dnodesize, tx);
1800 } else {
1801 error = dmu_object_claim_dnsize(os, lr->lr_foid,
1802 lr->lrz_type, 0, lr->lrz_bonustype,
1803 bonuslen, lr->lrz_dnodesize, tx);
1804 }
1805 }
1806
1807 if (error) {
1808 ASSERT3U(error, ==, EEXIST);
1809 ASSERT(zd->zd_zilog->zl_replay);
1810 dmu_tx_commit(tx);
1811 return (error);
1812 }
1813
1814 ASSERT(lr->lr_foid != 0);
1815
1816 if (lr->lrz_type != DMU_OT_ZAP_OTHER)
1817 VERIFY3U(0, ==, dmu_object_set_blocksize(os, lr->lr_foid,
1818 lr->lrz_blocksize, lr->lrz_ibshift, tx));
1819
1820 VERIFY3U(0, ==, dmu_bonus_hold(os, lr->lr_foid, FTAG, &db));
1821 bbt = ztest_bt_bonus(db);
1822 dmu_buf_will_dirty(db, tx);
1823 ztest_bt_generate(bbt, os, lr->lr_foid, lr->lrz_dnodesize, -1ULL,
1824 lr->lr_gen, txg, txg);
1825 ztest_fill_unused_bonus(db, bbt, lr->lr_foid, os, lr->lr_gen);
1826 dmu_buf_rele(db, FTAG);
1827
1828 VERIFY3U(0, ==, zap_add(os, lr->lr_doid, name, sizeof (uint64_t), 1,
1829 &lr->lr_foid, tx));
1830
1831 (void) ztest_log_create(zd, tx, lr);
1832
1833 dmu_tx_commit(tx);
1834
1835 return (0);
1836 }
1837
1838 static int
1839 ztest_replay_remove(void *arg1, void *arg2, boolean_t byteswap)
1840 {
1841 ztest_ds_t *zd = arg1;
1842 lr_remove_t *lr = arg2;
1843 char *name = (void *)(lr + 1); /* name follows lr */
1844 objset_t *os = zd->zd_os;
1845 dmu_object_info_t doi;
1846 dmu_tx_t *tx;
1847 uint64_t object, txg;
1848
1849 if (byteswap)
1850 byteswap_uint64_array(lr, sizeof (*lr));
1851
1852 ASSERT(lr->lr_doid == ZTEST_DIROBJ);
1853 ASSERT(name[0] != '\0');
1854
1855 VERIFY3U(0, ==,
1856 zap_lookup(os, lr->lr_doid, name, sizeof (object), 1, &object));
1857 ASSERT(object != 0);
1858
1859 ztest_object_lock(zd, object, RL_WRITER);
1860
1861 VERIFY3U(0, ==, dmu_object_info(os, object, &doi));
1862
1863 tx = dmu_tx_create(os);
1864
1865 dmu_tx_hold_zap(tx, lr->lr_doid, B_FALSE, name);
1866 dmu_tx_hold_free(tx, object, 0, DMU_OBJECT_END);
1867
1868 txg = ztest_tx_assign(tx, TXG_WAIT, FTAG);
1869 if (txg == 0) {
1870 ztest_object_unlock(zd, object);
1871 return (ENOSPC);
1872 }
1873
1874 if (doi.doi_type == DMU_OT_ZAP_OTHER) {
1875 VERIFY3U(0, ==, zap_destroy(os, object, tx));
1876 } else {
1877 VERIFY3U(0, ==, dmu_object_free(os, object, tx));
1878 }
1879
1880 VERIFY3U(0, ==, zap_remove(os, lr->lr_doid, name, tx));
1881
1882 (void) ztest_log_remove(zd, tx, lr, object);
1883
1884 dmu_tx_commit(tx);
1885
1886 ztest_object_unlock(zd, object);
1887
1888 return (0);
1889 }
1890
1891 static int
1892 ztest_replay_write(void *arg1, void *arg2, boolean_t byteswap)
1893 {
1894 ztest_ds_t *zd = arg1;
1895 lr_write_t *lr = arg2;
1896 objset_t *os = zd->zd_os;
1897 void *data = lr + 1; /* data follows lr */
1898 uint64_t offset, length;
1899 ztest_block_tag_t *bt = data;
1900 ztest_block_tag_t *bbt;
1901 uint64_t gen, txg, lrtxg, crtxg;
1902 dmu_object_info_t doi;
1903 dmu_tx_t *tx;
1904 dmu_buf_t *db;
1905 arc_buf_t *abuf = NULL;
1906 rl_t *rl;
1907
1908 if (byteswap)
1909 byteswap_uint64_array(lr, sizeof (*lr));
1910
1911 offset = lr->lr_offset;
1912 length = lr->lr_length;
1913
1914 /* If it's a dmu_sync() block, write the whole block */
1915 if (lr->lr_common.lrc_reclen == sizeof (lr_write_t)) {
1916 uint64_t blocksize = BP_GET_LSIZE(&lr->lr_blkptr);
1917 if (length < blocksize) {
1918 offset -= offset % blocksize;
1919 length = blocksize;
1920 }
1921 }
1922
1923 if (bt->bt_magic == BSWAP_64(BT_MAGIC))
1924 byteswap_uint64_array(bt, sizeof (*bt));
1925
1926 if (bt->bt_magic != BT_MAGIC)
1927 bt = NULL;
1928
1929 ztest_object_lock(zd, lr->lr_foid, RL_READER);
1930 rl = ztest_range_lock(zd, lr->lr_foid, offset, length, RL_WRITER);
1931
1932 VERIFY3U(0, ==, dmu_bonus_hold(os, lr->lr_foid, FTAG, &db));
1933
1934 dmu_object_info_from_db(db, &doi);
1935
1936 bbt = ztest_bt_bonus(db);
1937 ASSERT3U(bbt->bt_magic, ==, BT_MAGIC);
1938 gen = bbt->bt_gen;
1939 crtxg = bbt->bt_crtxg;
1940 lrtxg = lr->lr_common.lrc_txg;
1941
1942 tx = dmu_tx_create(os);
1943
1944 dmu_tx_hold_write(tx, lr->lr_foid, offset, length);
1945
1946 if (ztest_random(8) == 0 && length == doi.doi_data_block_size &&
1947 P2PHASE(offset, length) == 0)
1948 abuf = dmu_request_arcbuf(db, length);
1949
1950 txg = ztest_tx_assign(tx, TXG_WAIT, FTAG);
1951 if (txg == 0) {
1952 if (abuf != NULL)
1953 dmu_return_arcbuf(abuf);
1954 dmu_buf_rele(db, FTAG);
1955 ztest_range_unlock(rl);
1956 ztest_object_unlock(zd, lr->lr_foid);
1957 return (ENOSPC);
1958 }
1959
1960 if (bt != NULL) {
1961 /*
1962 * Usually, verify the old data before writing new data --
1963 * but not always, because we also want to verify correct
1964 * behavior when the data was not recently read into cache.
1965 */
1966 ASSERT(offset % doi.doi_data_block_size == 0);
1967 if (ztest_random(4) != 0) {
1968 int prefetch = ztest_random(2) ?
1969 DMU_READ_PREFETCH : DMU_READ_NO_PREFETCH;
1970 ztest_block_tag_t rbt;
1971
1972 VERIFY(dmu_read(os, lr->lr_foid, offset,
1973 sizeof (rbt), &rbt, prefetch) == 0);
1974 if (rbt.bt_magic == BT_MAGIC) {
1975 ztest_bt_verify(&rbt, os, lr->lr_foid, 0,
1976 offset, gen, txg, crtxg);
1977 }
1978 }
1979
1980 /*
1981 * Writes can appear to be newer than the bonus buffer because
1982 * the ztest_get_data() callback does a dmu_read() of the
1983 * open-context data, which may be different than the data
1984 * as it was when the write was generated.
1985 */
1986 if (zd->zd_zilog->zl_replay) {
1987 ztest_bt_verify(bt, os, lr->lr_foid, 0, offset,
1988 MAX(gen, bt->bt_gen), MAX(txg, lrtxg),
1989 bt->bt_crtxg);
1990 }
1991
1992 /*
1993 * Set the bt's gen/txg to the bonus buffer's gen/txg
1994 * so that all of the usual ASSERTs will work.
1995 */
1996 ztest_bt_generate(bt, os, lr->lr_foid, 0, offset, gen, txg,
1997 crtxg);
1998 }
1999
2000 if (abuf == NULL) {
2001 dmu_write(os, lr->lr_foid, offset, length, data, tx);
2002 } else {
2003 bcopy(data, abuf->b_data, length);
2004 dmu_assign_arcbuf_by_dbuf(db, offset, abuf, tx);
2005 }
2006
2007 (void) ztest_log_write(zd, tx, lr);
2008
2009 dmu_buf_rele(db, FTAG);
2010
2011 dmu_tx_commit(tx);
2012
2013 ztest_range_unlock(rl);
2014 ztest_object_unlock(zd, lr->lr_foid);
2015
2016 return (0);
2017 }
2018
2019 static int
2020 ztest_replay_truncate(void *arg1, void *arg2, boolean_t byteswap)
2021 {
2022 ztest_ds_t *zd = arg1;
2023 lr_truncate_t *lr = arg2;
2024 objset_t *os = zd->zd_os;
2025 dmu_tx_t *tx;
2026 uint64_t txg;
2027 rl_t *rl;
2028
2029 if (byteswap)
2030 byteswap_uint64_array(lr, sizeof (*lr));
2031
2032 ztest_object_lock(zd, lr->lr_foid, RL_READER);
2033 rl = ztest_range_lock(zd, lr->lr_foid, lr->lr_offset, lr->lr_length,
2034 RL_WRITER);
2035
2036 tx = dmu_tx_create(os);
2037
2038 dmu_tx_hold_free(tx, lr->lr_foid, lr->lr_offset, lr->lr_length);
2039
2040 txg = ztest_tx_assign(tx, TXG_WAIT, FTAG);
2041 if (txg == 0) {
2042 ztest_range_unlock(rl);
2043 ztest_object_unlock(zd, lr->lr_foid);
2044 return (ENOSPC);
2045 }
2046
2047 VERIFY(dmu_free_range(os, lr->lr_foid, lr->lr_offset,
2048 lr->lr_length, tx) == 0);
2049
2050 (void) ztest_log_truncate(zd, tx, lr);
2051
2052 dmu_tx_commit(tx);
2053
2054 ztest_range_unlock(rl);
2055 ztest_object_unlock(zd, lr->lr_foid);
2056
2057 return (0);
2058 }
2059
2060 static int
2061 ztest_replay_setattr(void *arg1, void *arg2, boolean_t byteswap)
2062 {
2063 ztest_ds_t *zd = arg1;
2064 lr_setattr_t *lr = arg2;
2065 objset_t *os = zd->zd_os;
2066 dmu_tx_t *tx;
2067 dmu_buf_t *db;
2068 ztest_block_tag_t *bbt;
2069 uint64_t txg, lrtxg, crtxg, dnodesize;
2070
2071 if (byteswap)
2072 byteswap_uint64_array(lr, sizeof (*lr));
2073
2074 ztest_object_lock(zd, lr->lr_foid, RL_WRITER);
2075
2076 VERIFY3U(0, ==, dmu_bonus_hold(os, lr->lr_foid, FTAG, &db));
2077
2078 tx = dmu_tx_create(os);
2079 dmu_tx_hold_bonus(tx, lr->lr_foid);
2080
2081 txg = ztest_tx_assign(tx, TXG_WAIT, FTAG);
2082 if (txg == 0) {
2083 dmu_buf_rele(db, FTAG);
2084 ztest_object_unlock(zd, lr->lr_foid);
2085 return (ENOSPC);
2086 }
2087
2088 bbt = ztest_bt_bonus(db);
2089 ASSERT3U(bbt->bt_magic, ==, BT_MAGIC);
2090 crtxg = bbt->bt_crtxg;
2091 lrtxg = lr->lr_common.lrc_txg;
2092 dnodesize = bbt->bt_dnodesize;
2093
2094 if (zd->zd_zilog->zl_replay) {
2095 ASSERT(lr->lr_size != 0);
2096 ASSERT(lr->lr_mode != 0);
2097 ASSERT(lrtxg != 0);
2098 } else {
2099 /*
2100 * Randomly change the size and increment the generation.
2101 */
2102 lr->lr_size = (ztest_random(db->db_size / sizeof (*bbt)) + 1) *
2103 sizeof (*bbt);
2104 lr->lr_mode = bbt->bt_gen + 1;
2105 ASSERT(lrtxg == 0);
2106 }
2107
2108 /*
2109 * Verify that the current bonus buffer is not newer than our txg.
2110 */
2111 ztest_bt_verify(bbt, os, lr->lr_foid, dnodesize, -1ULL, lr->lr_mode,
2112 MAX(txg, lrtxg), crtxg);
2113
2114 dmu_buf_will_dirty(db, tx);
2115
2116 ASSERT3U(lr->lr_size, >=, sizeof (*bbt));
2117 ASSERT3U(lr->lr_size, <=, db->db_size);
2118 VERIFY0(dmu_set_bonus(db, lr->lr_size, tx));
2119 bbt = ztest_bt_bonus(db);
2120
2121 ztest_bt_generate(bbt, os, lr->lr_foid, dnodesize, -1ULL, lr->lr_mode,
2122 txg, crtxg);
2123 ztest_fill_unused_bonus(db, bbt, lr->lr_foid, os, bbt->bt_gen);
2124 dmu_buf_rele(db, FTAG);
2125
2126 (void) ztest_log_setattr(zd, tx, lr);
2127
2128 dmu_tx_commit(tx);
2129
2130 ztest_object_unlock(zd, lr->lr_foid);
2131
2132 return (0);
2133 }
2134
2135 zil_replay_func_t *ztest_replay_vector[TX_MAX_TYPE] = {
2136 NULL, /* 0 no such transaction type */
2137 ztest_replay_create, /* TX_CREATE */
2138 NULL, /* TX_MKDIR */
2139 NULL, /* TX_MKXATTR */
2140 NULL, /* TX_SYMLINK */
2141 ztest_replay_remove, /* TX_REMOVE */
2142 NULL, /* TX_RMDIR */
2143 NULL, /* TX_LINK */
2144 NULL, /* TX_RENAME */
2145 ztest_replay_write, /* TX_WRITE */
2146 ztest_replay_truncate, /* TX_TRUNCATE */
2147 ztest_replay_setattr, /* TX_SETATTR */
2148 NULL, /* TX_ACL */
2149 NULL, /* TX_CREATE_ACL */
2150 NULL, /* TX_CREATE_ATTR */
2151 NULL, /* TX_CREATE_ACL_ATTR */
2152 NULL, /* TX_MKDIR_ACL */
2153 NULL, /* TX_MKDIR_ATTR */
2154 NULL, /* TX_MKDIR_ACL_ATTR */
2155 NULL, /* TX_WRITE2 */
2156 };
2157
2158 /*
2159 * ZIL get_data callbacks
2160 */
2161
2162 /* ARGSUSED */
2163 static void
2164 ztest_get_done(zgd_t *zgd, int error)
2165 {
2166 ztest_ds_t *zd = zgd->zgd_private;
2167 uint64_t object = ((rl_t *)zgd->zgd_lr)->rl_object;
2168
2169 if (zgd->zgd_db)
2170 dmu_buf_rele(zgd->zgd_db, zgd);
2171
2172 ztest_range_unlock((rl_t *)zgd->zgd_lr);
2173 ztest_object_unlock(zd, object);
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 * 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 usable 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 if (error == ENOSPC) {
3986 /* There could be checkpoint or insufficient slop */
3987 ztest_record_enospc(FTAG);
3988 } else if (error != EBUSY) {
3989 /* There could be a hold on this dataset */
3990 ASSERT0(error);
3991 }
3992 }
3993 return (0);
3994 }
3995
3996 static boolean_t
3997 ztest_snapshot_create(char *osname, uint64_t id)
3998 {
3999 char snapname[ZFS_MAX_DATASET_NAME_LEN];
4000 int error;
4001
4002 (void) snprintf(snapname, sizeof (snapname), "%llu", (u_longlong_t)id);
4003
4004 error = dmu_objset_snapshot_one(osname, snapname);
4005 if (error == ENOSPC) {
4006 ztest_record_enospc(FTAG);
4007 return (B_FALSE);
4008 }
4009 if (error != 0 && error != EEXIST) {
4010 fatal(0, "ztest_snapshot_create(%s@%s) = %d", osname,
4011 snapname, error);
4012 }
4013 return (B_TRUE);
4014 }
4015
4016 static boolean_t
4017 ztest_snapshot_destroy(char *osname, uint64_t id)
4018 {
4019 char snapname[ZFS_MAX_DATASET_NAME_LEN];
4020 int error;
4021
4022 (void) snprintf(snapname, sizeof (snapname), "%s@%llu", osname,
4023 (u_longlong_t)id);
4024
4025 error = dsl_destroy_snapshot(snapname, B_FALSE);
4026 if (error != 0 && error != ENOENT)
4027 fatal(0, "ztest_snapshot_destroy(%s) = %d", snapname, error);
4028 return (B_TRUE);
4029 }
4030
4031 /* ARGSUSED */
4032 void
4033 ztest_dmu_objset_create_destroy(ztest_ds_t *zd, uint64_t id)
4034 {
4035 ztest_ds_t *zdtmp;
4036 int iters;
4037 int error;
4038 objset_t *os, *os2;
4039 char name[ZFS_MAX_DATASET_NAME_LEN];
4040 zilog_t *zilog;
4041 int i;
4042
4043 zdtmp = umem_alloc(sizeof (ztest_ds_t), UMEM_NOFAIL);
4044
4045 (void) pthread_rwlock_rdlock(&ztest_name_lock);
4046
4047 (void) snprintf(name, sizeof (name), "%s/temp_%llu",
4048 ztest_opts.zo_pool, (u_longlong_t)id);
4049
4050 /*
4051 * If this dataset exists from a previous run, process its replay log
4052 * half of the time. If we don't replay it, then dsl_destroy_head()
4053 * (invoked from ztest_objset_destroy_cb()) should just throw it away.
4054 */
4055 if (ztest_random(2) == 0 &&
4056 ztest_dmu_objset_own(name, DMU_OST_OTHER, B_FALSE,
4057 B_TRUE, FTAG, &os) == 0) {
4058 ztest_zd_init(zdtmp, NULL, os);
4059 zil_replay(os, zdtmp, ztest_replay_vector);
4060 ztest_zd_fini(zdtmp);
4061 dmu_objset_disown(os, B_TRUE, FTAG);
4062 }
4063
4064 /*
4065 * There may be an old instance of the dataset we're about to
4066 * create lying around from a previous run. If so, destroy it
4067 * and all of its snapshots.
4068 */
4069 (void) dmu_objset_find(name, ztest_objset_destroy_cb, NULL,
4070 DS_FIND_CHILDREN | DS_FIND_SNAPSHOTS);
4071
4072 /*
4073 * Verify that the destroyed dataset is no longer in the namespace.
4074 */
4075 VERIFY3U(ENOENT, ==, ztest_dmu_objset_own(name, DMU_OST_OTHER, B_TRUE,
4076 B_TRUE, FTAG, &os));
4077
4078 /*
4079 * Verify that we can create a new dataset.
4080 */
4081 error = ztest_dataset_create(name);
4082 if (error) {
4083 if (error == ENOSPC) {
4084 ztest_record_enospc(FTAG);
4085 goto out;
4086 }
4087 fatal(0, "dmu_objset_create(%s) = %d", name, error);
4088 }
4089
4090 VERIFY0(ztest_dmu_objset_own(name, DMU_OST_OTHER, B_FALSE, B_TRUE,
4091 FTAG, &os));
4092
4093 ztest_zd_init(zdtmp, NULL, os);
4094
4095 /*
4096 * Open the intent log for it.
4097 */
4098 zilog = zil_open(os, ztest_get_data);
4099
4100 /*
4101 * Put some objects in there, do a little I/O to them,
4102 * and randomly take a couple of snapshots along the way.
4103 */
4104 iters = ztest_random(5);
4105 for (i = 0; i < iters; i++) {
4106 ztest_dmu_object_alloc_free(zdtmp, id);
4107 if (ztest_random(iters) == 0)
4108 (void) ztest_snapshot_create(name, i);
4109 }
4110
4111 /*
4112 * Verify that we cannot create an existing dataset.
4113 */
4114 VERIFY3U(EEXIST, ==,
4115 dmu_objset_create(name, DMU_OST_OTHER, 0, NULL, NULL, NULL));
4116
4117 /*
4118 * Verify that we can hold an objset that is also owned.
4119 */
4120 VERIFY3U(0, ==, dmu_objset_hold(name, FTAG, &os2));
4121 dmu_objset_rele(os2, FTAG);
4122
4123 /*
4124 * Verify that we cannot own an objset that is already owned.
4125 */
4126 VERIFY3U(EBUSY, ==, ztest_dmu_objset_own(name, DMU_OST_OTHER,
4127 B_FALSE, B_TRUE, FTAG, &os2));
4128
4129 zil_close(zilog);
4130 dmu_objset_disown(os, B_TRUE, FTAG);
4131 ztest_zd_fini(zdtmp);
4132 out:
4133 (void) pthread_rwlock_unlock(&ztest_name_lock);
4134
4135 umem_free(zdtmp, sizeof (ztest_ds_t));
4136 }
4137
4138 /*
4139 * Verify that dmu_snapshot_{create,destroy,open,close} work as expected.
4140 */
4141 void
4142 ztest_dmu_snapshot_create_destroy(ztest_ds_t *zd, uint64_t id)
4143 {
4144 (void) pthread_rwlock_rdlock(&ztest_name_lock);
4145 (void) ztest_snapshot_destroy(zd->zd_name, id);
4146 (void) ztest_snapshot_create(zd->zd_name, id);
4147 (void) pthread_rwlock_unlock(&ztest_name_lock);
4148 }
4149
4150 /*
4151 * Cleanup non-standard snapshots and clones.
4152 */
4153 void
4154 ztest_dsl_dataset_cleanup(char *osname, uint64_t id)
4155 {
4156 char *snap1name;
4157 char *clone1name;
4158 char *snap2name;
4159 char *clone2name;
4160 char *snap3name;
4161 int error;
4162
4163 snap1name = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
4164 clone1name = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
4165 snap2name = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
4166 clone2name = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
4167 snap3name = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
4168
4169 (void) snprintf(snap1name, ZFS_MAX_DATASET_NAME_LEN,
4170 "%s@s1_%llu", osname, (u_longlong_t)id);
4171 (void) snprintf(clone1name, ZFS_MAX_DATASET_NAME_LEN,
4172 "%s/c1_%llu", osname, (u_longlong_t)id);
4173 (void) snprintf(snap2name, ZFS_MAX_DATASET_NAME_LEN,
4174 "%s@s2_%llu", clone1name, (u_longlong_t)id);
4175 (void) snprintf(clone2name, ZFS_MAX_DATASET_NAME_LEN,
4176 "%s/c2_%llu", osname, (u_longlong_t)id);
4177 (void) snprintf(snap3name, ZFS_MAX_DATASET_NAME_LEN,
4178 "%s@s3_%llu", clone1name, (u_longlong_t)id);
4179
4180 error = dsl_destroy_head(clone2name);
4181 if (error && error != ENOENT)
4182 fatal(0, "dsl_destroy_head(%s) = %d", clone2name, error);
4183 error = dsl_destroy_snapshot(snap3name, B_FALSE);
4184 if (error && error != ENOENT)
4185 fatal(0, "dsl_destroy_snapshot(%s) = %d", snap3name, error);
4186 error = dsl_destroy_snapshot(snap2name, B_FALSE);
4187 if (error && error != ENOENT)
4188 fatal(0, "dsl_destroy_snapshot(%s) = %d", snap2name, error);
4189 error = dsl_destroy_head(clone1name);
4190 if (error && error != ENOENT)
4191 fatal(0, "dsl_destroy_head(%s) = %d", clone1name, error);
4192 error = dsl_destroy_snapshot(snap1name, B_FALSE);
4193 if (error && error != ENOENT)
4194 fatal(0, "dsl_destroy_snapshot(%s) = %d", snap1name, error);
4195
4196 umem_free(snap1name, ZFS_MAX_DATASET_NAME_LEN);
4197 umem_free(clone1name, ZFS_MAX_DATASET_NAME_LEN);
4198 umem_free(snap2name, ZFS_MAX_DATASET_NAME_LEN);
4199 umem_free(clone2name, ZFS_MAX_DATASET_NAME_LEN);
4200 umem_free(snap3name, ZFS_MAX_DATASET_NAME_LEN);
4201 }
4202
4203 /*
4204 * Verify dsl_dataset_promote handles EBUSY
4205 */
4206 void
4207 ztest_dsl_dataset_promote_busy(ztest_ds_t *zd, uint64_t id)
4208 {
4209 objset_t *os;
4210 char *snap1name;
4211 char *clone1name;
4212 char *snap2name;
4213 char *clone2name;
4214 char *snap3name;
4215 char *osname = zd->zd_name;
4216 int error;
4217
4218 snap1name = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
4219 clone1name = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
4220 snap2name = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
4221 clone2name = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
4222 snap3name = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
4223
4224 (void) pthread_rwlock_rdlock(&ztest_name_lock);
4225
4226 ztest_dsl_dataset_cleanup(osname, id);
4227
4228 (void) snprintf(snap1name, ZFS_MAX_DATASET_NAME_LEN,
4229 "%s@s1_%llu", osname, (u_longlong_t)id);
4230 (void) snprintf(clone1name, ZFS_MAX_DATASET_NAME_LEN,
4231 "%s/c1_%llu", osname, (u_longlong_t)id);
4232 (void) snprintf(snap2name, ZFS_MAX_DATASET_NAME_LEN,
4233 "%s@s2_%llu", clone1name, (u_longlong_t)id);
4234 (void) snprintf(clone2name, ZFS_MAX_DATASET_NAME_LEN,
4235 "%s/c2_%llu", osname, (u_longlong_t)id);
4236 (void) snprintf(snap3name, ZFS_MAX_DATASET_NAME_LEN,
4237 "%s@s3_%llu", clone1name, (u_longlong_t)id);
4238
4239 error = dmu_objset_snapshot_one(osname, strchr(snap1name, '@') + 1);
4240 if (error && error != EEXIST) {
4241 if (error == ENOSPC) {
4242 ztest_record_enospc(FTAG);
4243 goto out;
4244 }
4245 fatal(0, "dmu_take_snapshot(%s) = %d", snap1name, error);
4246 }
4247
4248 error = dmu_objset_clone(clone1name, snap1name);
4249 if (error) {
4250 if (error == ENOSPC) {
4251 ztest_record_enospc(FTAG);
4252 goto out;
4253 }
4254 fatal(0, "dmu_objset_create(%s) = %d", clone1name, error);
4255 }
4256
4257 error = dmu_objset_snapshot_one(clone1name, strchr(snap2name, '@') + 1);
4258 if (error && error != EEXIST) {
4259 if (error == ENOSPC) {
4260 ztest_record_enospc(FTAG);
4261 goto out;
4262 }
4263 fatal(0, "dmu_open_snapshot(%s) = %d", snap2name, error);
4264 }
4265
4266 error = dmu_objset_snapshot_one(clone1name, strchr(snap3name, '@') + 1);
4267 if (error && error != EEXIST) {
4268 if (error == ENOSPC) {
4269 ztest_record_enospc(FTAG);
4270 goto out;
4271 }
4272 fatal(0, "dmu_open_snapshot(%s) = %d", snap3name, error);
4273 }
4274
4275 error = dmu_objset_clone(clone2name, snap3name);
4276 if (error) {
4277 if (error == ENOSPC) {
4278 ztest_record_enospc(FTAG);
4279 goto out;
4280 }
4281 fatal(0, "dmu_objset_create(%s) = %d", clone2name, error);
4282 }
4283
4284 error = ztest_dmu_objset_own(snap2name, DMU_OST_ANY, B_TRUE, B_TRUE,
4285 FTAG, &os);
4286 if (error)
4287 fatal(0, "dmu_objset_own(%s) = %d", snap2name, error);
4288 error = dsl_dataset_promote(clone2name, NULL);
4289 if (error == ENOSPC) {
4290 dmu_objset_disown(os, B_TRUE, FTAG);
4291 ztest_record_enospc(FTAG);
4292 goto out;
4293 }
4294 if (error != EBUSY)
4295 fatal(0, "dsl_dataset_promote(%s), %d, not EBUSY", clone2name,
4296 error);
4297 dmu_objset_disown(os, B_TRUE, FTAG);
4298
4299 out:
4300 ztest_dsl_dataset_cleanup(osname, id);
4301
4302 (void) pthread_rwlock_unlock(&ztest_name_lock);
4303
4304 umem_free(snap1name, ZFS_MAX_DATASET_NAME_LEN);
4305 umem_free(clone1name, ZFS_MAX_DATASET_NAME_LEN);
4306 umem_free(snap2name, ZFS_MAX_DATASET_NAME_LEN);
4307 umem_free(clone2name, ZFS_MAX_DATASET_NAME_LEN);
4308 umem_free(snap3name, ZFS_MAX_DATASET_NAME_LEN);
4309 }
4310
4311 #undef OD_ARRAY_SIZE
4312 #define OD_ARRAY_SIZE 4
4313
4314 /*
4315 * Verify that dmu_object_{alloc,free} work as expected.
4316 */
4317 void
4318 ztest_dmu_object_alloc_free(ztest_ds_t *zd, uint64_t id)
4319 {
4320 ztest_od_t *od;
4321 int batchsize;
4322 int size;
4323 int b;
4324
4325 size = sizeof (ztest_od_t) * OD_ARRAY_SIZE;
4326 od = umem_alloc(size, UMEM_NOFAIL);
4327 batchsize = OD_ARRAY_SIZE;
4328
4329 for (b = 0; b < batchsize; b++)
4330 ztest_od_init(od + b, id, FTAG, b, DMU_OT_UINT64_OTHER,
4331 0, 0, 0);
4332
4333 /*
4334 * Destroy the previous batch of objects, create a new batch,
4335 * and do some I/O on the new objects.
4336 */
4337 if (ztest_object_init(zd, od, size, B_TRUE) != 0)
4338 return;
4339
4340 while (ztest_random(4 * batchsize) != 0)
4341 ztest_io(zd, od[ztest_random(batchsize)].od_object,
4342 ztest_random(ZTEST_RANGE_LOCKS) << SPA_MAXBLOCKSHIFT);
4343
4344 umem_free(od, size);
4345 }
4346
4347 /*
4348 * Rewind the global allocator to verify object allocation backfilling.
4349 */
4350 void
4351 ztest_dmu_object_next_chunk(ztest_ds_t *zd, uint64_t id)
4352 {
4353 objset_t *os = zd->zd_os;
4354 int dnodes_per_chunk = 1 << dmu_object_alloc_chunk_shift;
4355 uint64_t object;
4356
4357 /*
4358 * Rewind the global allocator randomly back to a lower object number
4359 * to force backfilling and reclamation of recently freed dnodes.
4360 */
4361 mutex_enter(&os->os_obj_lock);
4362 object = ztest_random(os->os_obj_next_chunk);
4363 os->os_obj_next_chunk = P2ALIGN(object, dnodes_per_chunk);
4364 mutex_exit(&os->os_obj_lock);
4365 }
4366
4367 #undef OD_ARRAY_SIZE
4368 #define OD_ARRAY_SIZE 2
4369
4370 /*
4371 * Verify that dmu_{read,write} work as expected.
4372 */
4373 void
4374 ztest_dmu_read_write(ztest_ds_t *zd, uint64_t id)
4375 {
4376 int size;
4377 ztest_od_t *od;
4378
4379 objset_t *os = zd->zd_os;
4380 size = sizeof (ztest_od_t) * OD_ARRAY_SIZE;
4381 od = umem_alloc(size, UMEM_NOFAIL);
4382 dmu_tx_t *tx;
4383 int i, freeit, error;
4384 uint64_t n, s, txg;
4385 bufwad_t *packbuf, *bigbuf, *pack, *bigH, *bigT;
4386 uint64_t packobj, packoff, packsize, bigobj, bigoff, bigsize;
4387 uint64_t chunksize = (1000 + ztest_random(1000)) * sizeof (uint64_t);
4388 uint64_t regions = 997;
4389 uint64_t stride = 123456789ULL;
4390 uint64_t width = 40;
4391 int free_percent = 5;
4392
4393 /*
4394 * This test uses two objects, packobj and bigobj, that are always
4395 * updated together (i.e. in the same tx) so that their contents are
4396 * in sync and can be compared. Their contents relate to each other
4397 * in a simple way: packobj is a dense array of 'bufwad' structures,
4398 * while bigobj is a sparse array of the same bufwads. Specifically,
4399 * for any index n, there are three bufwads that should be identical:
4400 *
4401 * packobj, at offset n * sizeof (bufwad_t)
4402 * bigobj, at the head of the nth chunk
4403 * bigobj, at the tail of the nth chunk
4404 *
4405 * The chunk size is arbitrary. It doesn't have to be a power of two,
4406 * and it doesn't have any relation to the object blocksize.
4407 * The only requirement is that it can hold at least two bufwads.
4408 *
4409 * Normally, we write the bufwad to each of these locations.
4410 * However, free_percent of the time we instead write zeroes to
4411 * packobj and perform a dmu_free_range() on bigobj. By comparing
4412 * bigobj to packobj, we can verify that the DMU is correctly
4413 * tracking which parts of an object are allocated and free,
4414 * and that the contents of the allocated blocks are correct.
4415 */
4416
4417 /*
4418 * Read the directory info. If it's the first time, set things up.
4419 */
4420 ztest_od_init(od, id, FTAG, 0, DMU_OT_UINT64_OTHER, 0, 0, chunksize);
4421 ztest_od_init(od + 1, id, FTAG, 1, DMU_OT_UINT64_OTHER, 0, 0,
4422 chunksize);
4423
4424 if (ztest_object_init(zd, od, size, B_FALSE) != 0) {
4425 umem_free(od, size);
4426 return;
4427 }
4428
4429 bigobj = od[0].od_object;
4430 packobj = od[1].od_object;
4431 chunksize = od[0].od_gen;
4432 ASSERT(chunksize == od[1].od_gen);
4433
4434 /*
4435 * Prefetch a random chunk of the big object.
4436 * Our aim here is to get some async reads in flight
4437 * for blocks that we may free below; the DMU should
4438 * handle this race correctly.
4439 */
4440 n = ztest_random(regions) * stride + ztest_random(width);
4441 s = 1 + ztest_random(2 * width - 1);
4442 dmu_prefetch(os, bigobj, 0, n * chunksize, s * chunksize,
4443 ZIO_PRIORITY_SYNC_READ);
4444
4445 /*
4446 * Pick a random index and compute the offsets into packobj and bigobj.
4447 */
4448 n = ztest_random(regions) * stride + ztest_random(width);
4449 s = 1 + ztest_random(width - 1);
4450
4451 packoff = n * sizeof (bufwad_t);
4452 packsize = s * sizeof (bufwad_t);
4453
4454 bigoff = n * chunksize;
4455 bigsize = s * chunksize;
4456
4457 packbuf = umem_alloc(packsize, UMEM_NOFAIL);
4458 bigbuf = umem_alloc(bigsize, UMEM_NOFAIL);
4459
4460 /*
4461 * free_percent of the time, free a range of bigobj rather than
4462 * overwriting it.
4463 */
4464 freeit = (ztest_random(100) < free_percent);
4465
4466 /*
4467 * Read the current contents of our objects.
4468 */
4469 error = dmu_read(os, packobj, packoff, packsize, packbuf,
4470 DMU_READ_PREFETCH);
4471 ASSERT0(error);
4472 error = dmu_read(os, bigobj, bigoff, bigsize, bigbuf,
4473 DMU_READ_PREFETCH);
4474 ASSERT0(error);
4475
4476 /*
4477 * Get a tx for the mods to both packobj and bigobj.
4478 */
4479 tx = dmu_tx_create(os);
4480
4481 dmu_tx_hold_write(tx, packobj, packoff, packsize);
4482
4483 if (freeit)
4484 dmu_tx_hold_free(tx, bigobj, bigoff, bigsize);
4485 else
4486 dmu_tx_hold_write(tx, bigobj, bigoff, bigsize);
4487
4488 /* This accounts for setting the checksum/compression. */
4489 dmu_tx_hold_bonus(tx, bigobj);
4490
4491 txg = ztest_tx_assign(tx, TXG_MIGHTWAIT, FTAG);
4492 if (txg == 0) {
4493 umem_free(packbuf, packsize);
4494 umem_free(bigbuf, bigsize);
4495 umem_free(od, size);
4496 return;
4497 }
4498
4499 enum zio_checksum cksum;
4500 do {
4501 cksum = (enum zio_checksum)
4502 ztest_random_dsl_prop(ZFS_PROP_CHECKSUM);
4503 } while (cksum >= ZIO_CHECKSUM_LEGACY_FUNCTIONS);
4504 dmu_object_set_checksum(os, bigobj, cksum, tx);
4505
4506 enum zio_compress comp;
4507 do {
4508 comp = (enum zio_compress)
4509 ztest_random_dsl_prop(ZFS_PROP_COMPRESSION);
4510 } while (comp >= ZIO_COMPRESS_LEGACY_FUNCTIONS);
4511 dmu_object_set_compress(os, bigobj, comp, tx);
4512
4513 /*
4514 * For each index from n to n + s, verify that the existing bufwad
4515 * in packobj matches the bufwads at the head and tail of the
4516 * corresponding chunk in bigobj. Then update all three bufwads
4517 * with the new values we want to write out.
4518 */
4519 for (i = 0; i < s; i++) {
4520 /* LINTED */
4521 pack = (bufwad_t *)((char *)packbuf + i * sizeof (bufwad_t));
4522 /* LINTED */
4523 bigH = (bufwad_t *)((char *)bigbuf + i * chunksize);
4524 /* LINTED */
4525 bigT = (bufwad_t *)((char *)bigH + chunksize) - 1;
4526
4527 ASSERT((uintptr_t)bigH - (uintptr_t)bigbuf < bigsize);
4528 ASSERT((uintptr_t)bigT - (uintptr_t)bigbuf < bigsize);
4529
4530 if (pack->bw_txg > txg)
4531 fatal(0, "future leak: got %llx, open txg is %llx",
4532 pack->bw_txg, txg);
4533
4534 if (pack->bw_data != 0 && pack->bw_index != n + i)
4535 fatal(0, "wrong index: got %llx, wanted %llx+%llx",
4536 pack->bw_index, n, i);
4537
4538 if (bcmp(pack, bigH, sizeof (bufwad_t)) != 0)
4539 fatal(0, "pack/bigH mismatch in %p/%p", pack, bigH);
4540
4541 if (bcmp(pack, bigT, sizeof (bufwad_t)) != 0)
4542 fatal(0, "pack/bigT mismatch in %p/%p", pack, bigT);
4543
4544 if (freeit) {
4545 bzero(pack, sizeof (bufwad_t));
4546 } else {
4547 pack->bw_index = n + i;
4548 pack->bw_txg = txg;
4549 pack->bw_data = 1 + ztest_random(-2ULL);
4550 }
4551 *bigH = *pack;
4552 *bigT = *pack;
4553 }
4554
4555 /*
4556 * We've verified all the old bufwads, and made new ones.
4557 * Now write them out.
4558 */
4559 dmu_write(os, packobj, packoff, packsize, packbuf, tx);
4560
4561 if (freeit) {
4562 if (ztest_opts.zo_verbose >= 7) {
4563 (void) printf("freeing offset %llx size %llx"
4564 " txg %llx\n",
4565 (u_longlong_t)bigoff,
4566 (u_longlong_t)bigsize,
4567 (u_longlong_t)txg);
4568 }
4569 VERIFY(0 == dmu_free_range(os, bigobj, bigoff, bigsize, tx));
4570 } else {
4571 if (ztest_opts.zo_verbose >= 7) {
4572 (void) printf("writing offset %llx size %llx"
4573 " txg %llx\n",
4574 (u_longlong_t)bigoff,
4575 (u_longlong_t)bigsize,
4576 (u_longlong_t)txg);
4577 }
4578 dmu_write(os, bigobj, bigoff, bigsize, bigbuf, tx);
4579 }
4580
4581 dmu_tx_commit(tx);
4582
4583 /*
4584 * Sanity check the stuff we just wrote.
4585 */
4586 {
4587 void *packcheck = umem_alloc(packsize, UMEM_NOFAIL);
4588 void *bigcheck = umem_alloc(bigsize, UMEM_NOFAIL);
4589
4590 VERIFY(0 == dmu_read(os, packobj, packoff,
4591 packsize, packcheck, DMU_READ_PREFETCH));
4592 VERIFY(0 == dmu_read(os, bigobj, bigoff,
4593 bigsize, bigcheck, DMU_READ_PREFETCH));
4594
4595 ASSERT(bcmp(packbuf, packcheck, packsize) == 0);
4596 ASSERT(bcmp(bigbuf, bigcheck, bigsize) == 0);
4597
4598 umem_free(packcheck, packsize);
4599 umem_free(bigcheck, bigsize);
4600 }
4601
4602 umem_free(packbuf, packsize);
4603 umem_free(bigbuf, bigsize);
4604 umem_free(od, size);
4605 }
4606
4607 void
4608 compare_and_update_pbbufs(uint64_t s, bufwad_t *packbuf, bufwad_t *bigbuf,
4609 uint64_t bigsize, uint64_t n, uint64_t chunksize, uint64_t txg)
4610 {
4611 uint64_t i;
4612 bufwad_t *pack;
4613 bufwad_t *bigH;
4614 bufwad_t *bigT;
4615
4616 /*
4617 * For each index from n to n + s, verify that the existing bufwad
4618 * in packobj matches the bufwads at the head and tail of the
4619 * corresponding chunk in bigobj. Then update all three bufwads
4620 * with the new values we want to write out.
4621 */
4622 for (i = 0; i < s; i++) {
4623 /* LINTED */
4624 pack = (bufwad_t *)((char *)packbuf + i * sizeof (bufwad_t));
4625 /* LINTED */
4626 bigH = (bufwad_t *)((char *)bigbuf + i * chunksize);
4627 /* LINTED */
4628 bigT = (bufwad_t *)((char *)bigH + chunksize) - 1;
4629
4630 ASSERT((uintptr_t)bigH - (uintptr_t)bigbuf < bigsize);
4631 ASSERT((uintptr_t)bigT - (uintptr_t)bigbuf < bigsize);
4632
4633 if (pack->bw_txg > txg)
4634 fatal(0, "future leak: got %llx, open txg is %llx",
4635 pack->bw_txg, txg);
4636
4637 if (pack->bw_data != 0 && pack->bw_index != n + i)
4638 fatal(0, "wrong index: got %llx, wanted %llx+%llx",
4639 pack->bw_index, n, i);
4640
4641 if (bcmp(pack, bigH, sizeof (bufwad_t)) != 0)
4642 fatal(0, "pack/bigH mismatch in %p/%p", pack, bigH);
4643
4644 if (bcmp(pack, bigT, sizeof (bufwad_t)) != 0)
4645 fatal(0, "pack/bigT mismatch in %p/%p", pack, bigT);
4646
4647 pack->bw_index = n + i;
4648 pack->bw_txg = txg;
4649 pack->bw_data = 1 + ztest_random(-2ULL);
4650
4651 *bigH = *pack;
4652 *bigT = *pack;
4653 }
4654 }
4655
4656 #undef OD_ARRAY_SIZE
4657 #define OD_ARRAY_SIZE 2
4658
4659 void
4660 ztest_dmu_read_write_zcopy(ztest_ds_t *zd, uint64_t id)
4661 {
4662 objset_t *os = zd->zd_os;
4663 ztest_od_t *od;
4664 dmu_tx_t *tx;
4665 uint64_t i;
4666 int error;
4667 int size;
4668 uint64_t n, s, txg;
4669 bufwad_t *packbuf, *bigbuf;
4670 uint64_t packobj, packoff, packsize, bigobj, bigoff, bigsize;
4671 uint64_t blocksize = ztest_random_blocksize();
4672 uint64_t chunksize = blocksize;
4673 uint64_t regions = 997;
4674 uint64_t stride = 123456789ULL;
4675 uint64_t width = 9;
4676 dmu_buf_t *bonus_db;
4677 arc_buf_t **bigbuf_arcbufs;
4678 dmu_object_info_t doi;
4679
4680 size = sizeof (ztest_od_t) * OD_ARRAY_SIZE;
4681 od = umem_alloc(size, UMEM_NOFAIL);
4682
4683 /*
4684 * This test uses two objects, packobj and bigobj, that are always
4685 * updated together (i.e. in the same tx) so that their contents are
4686 * in sync and can be compared. Their contents relate to each other
4687 * in a simple way: packobj is a dense array of 'bufwad' structures,
4688 * while bigobj is a sparse array of the same bufwads. Specifically,
4689 * for any index n, there are three bufwads that should be identical:
4690 *
4691 * packobj, at offset n * sizeof (bufwad_t)
4692 * bigobj, at the head of the nth chunk
4693 * bigobj, at the tail of the nth chunk
4694 *
4695 * The chunk size is set equal to bigobj block size so that
4696 * dmu_assign_arcbuf_by_dbuf() can be tested for object updates.
4697 */
4698
4699 /*
4700 * Read the directory info. If it's the first time, set things up.
4701 */
4702 ztest_od_init(od, id, FTAG, 0, DMU_OT_UINT64_OTHER, blocksize, 0, 0);
4703 ztest_od_init(od + 1, id, FTAG, 1, DMU_OT_UINT64_OTHER, 0, 0,
4704 chunksize);
4705
4706
4707 if (ztest_object_init(zd, od, size, B_FALSE) != 0) {
4708 umem_free(od, size);
4709 return;
4710 }
4711
4712 bigobj = od[0].od_object;
4713 packobj = od[1].od_object;
4714 blocksize = od[0].od_blocksize;
4715 chunksize = blocksize;
4716 ASSERT(chunksize == od[1].od_gen);
4717
4718 VERIFY(dmu_object_info(os, bigobj, &doi) == 0);
4719 VERIFY(ISP2(doi.doi_data_block_size));
4720 VERIFY(chunksize == doi.doi_data_block_size);
4721 VERIFY(chunksize >= 2 * sizeof (bufwad_t));
4722
4723 /*
4724 * Pick a random index and compute the offsets into packobj and bigobj.
4725 */
4726 n = ztest_random(regions) * stride + ztest_random(width);
4727 s = 1 + ztest_random(width - 1);
4728
4729 packoff = n * sizeof (bufwad_t);
4730 packsize = s * sizeof (bufwad_t);
4731
4732 bigoff = n * chunksize;
4733 bigsize = s * chunksize;
4734
4735 packbuf = umem_zalloc(packsize, UMEM_NOFAIL);
4736 bigbuf = umem_zalloc(bigsize, UMEM_NOFAIL);
4737
4738 VERIFY3U(0, ==, dmu_bonus_hold(os, bigobj, FTAG, &bonus_db));
4739
4740 bigbuf_arcbufs = umem_zalloc(2 * s * sizeof (arc_buf_t *), UMEM_NOFAIL);
4741
4742 /*
4743 * Iteration 0 test zcopy for DB_UNCACHED dbufs.
4744 * Iteration 1 test zcopy to already referenced dbufs.
4745 * Iteration 2 test zcopy to dirty dbuf in the same txg.
4746 * Iteration 3 test zcopy to dbuf dirty in previous txg.
4747 * Iteration 4 test zcopy when dbuf is no longer dirty.
4748 * Iteration 5 test zcopy when it can't be done.
4749 * Iteration 6 one more zcopy write.
4750 */
4751 for (i = 0; i < 7; i++) {
4752 uint64_t j;
4753 uint64_t off;
4754
4755 /*
4756 * In iteration 5 (i == 5) use arcbufs
4757 * that don't match bigobj blksz to test
4758 * dmu_assign_arcbuf_by_dbuf() when it can't directly
4759 * assign an arcbuf to a dbuf.
4760 */
4761 for (j = 0; j < s; j++) {
4762 if (i != 5 || chunksize < (SPA_MINBLOCKSIZE * 2)) {
4763 bigbuf_arcbufs[j] =
4764 dmu_request_arcbuf(bonus_db, chunksize);
4765 } else {
4766 bigbuf_arcbufs[2 * j] =
4767 dmu_request_arcbuf(bonus_db, chunksize / 2);
4768 bigbuf_arcbufs[2 * j + 1] =
4769 dmu_request_arcbuf(bonus_db, chunksize / 2);
4770 }
4771 }
4772
4773 /*
4774 * Get a tx for the mods to both packobj and bigobj.
4775 */
4776 tx = dmu_tx_create(os);
4777
4778 dmu_tx_hold_write(tx, packobj, packoff, packsize);
4779 dmu_tx_hold_write(tx, bigobj, bigoff, bigsize);
4780
4781 txg = ztest_tx_assign(tx, TXG_MIGHTWAIT, FTAG);
4782 if (txg == 0) {
4783 umem_free(packbuf, packsize);
4784 umem_free(bigbuf, bigsize);
4785 for (j = 0; j < s; j++) {
4786 if (i != 5 ||
4787 chunksize < (SPA_MINBLOCKSIZE * 2)) {
4788 dmu_return_arcbuf(bigbuf_arcbufs[j]);
4789 } else {
4790 dmu_return_arcbuf(
4791 bigbuf_arcbufs[2 * j]);
4792 dmu_return_arcbuf(
4793 bigbuf_arcbufs[2 * j + 1]);
4794 }
4795 }
4796 umem_free(bigbuf_arcbufs, 2 * s * sizeof (arc_buf_t *));
4797 umem_free(od, size);
4798 dmu_buf_rele(bonus_db, FTAG);
4799 return;
4800 }
4801
4802 /*
4803 * 50% of the time don't read objects in the 1st iteration to
4804 * test dmu_assign_arcbuf_by_dbuf() for the case when there are
4805 * no existing dbufs for the specified offsets.
4806 */
4807 if (i != 0 || ztest_random(2) != 0) {
4808 error = dmu_read(os, packobj, packoff,
4809 packsize, packbuf, DMU_READ_PREFETCH);
4810 ASSERT0(error);
4811 error = dmu_read(os, bigobj, bigoff, bigsize,
4812 bigbuf, DMU_READ_PREFETCH);
4813 ASSERT0(error);
4814 }
4815 compare_and_update_pbbufs(s, packbuf, bigbuf, bigsize,
4816 n, chunksize, txg);
4817
4818 /*
4819 * We've verified all the old bufwads, and made new ones.
4820 * Now write them out.
4821 */
4822 dmu_write(os, packobj, packoff, packsize, packbuf, tx);
4823 if (ztest_opts.zo_verbose >= 7) {
4824 (void) printf("writing offset %llx size %llx"
4825 " txg %llx\n",
4826 (u_longlong_t)bigoff,
4827 (u_longlong_t)bigsize,
4828 (u_longlong_t)txg);
4829 }
4830 for (off = bigoff, j = 0; j < s; j++, off += chunksize) {
4831 dmu_buf_t *dbt;
4832 if (i != 5 || chunksize < (SPA_MINBLOCKSIZE * 2)) {
4833 bcopy((caddr_t)bigbuf + (off - bigoff),
4834 bigbuf_arcbufs[j]->b_data, chunksize);
4835 } else {
4836 bcopy((caddr_t)bigbuf + (off - bigoff),
4837 bigbuf_arcbufs[2 * j]->b_data,
4838 chunksize / 2);
4839 bcopy((caddr_t)bigbuf + (off - bigoff) +
4840 chunksize / 2,
4841 bigbuf_arcbufs[2 * j + 1]->b_data,
4842 chunksize / 2);
4843 }
4844
4845 if (i == 1) {
4846 VERIFY(dmu_buf_hold(os, bigobj, off,
4847 FTAG, &dbt, DMU_READ_NO_PREFETCH) == 0);
4848 }
4849 if (i != 5 || chunksize < (SPA_MINBLOCKSIZE * 2)) {
4850 dmu_assign_arcbuf_by_dbuf(bonus_db, off,
4851 bigbuf_arcbufs[j], tx);
4852 } else {
4853 dmu_assign_arcbuf_by_dbuf(bonus_db, off,
4854 bigbuf_arcbufs[2 * j], tx);
4855 dmu_assign_arcbuf_by_dbuf(bonus_db,
4856 off + chunksize / 2,
4857 bigbuf_arcbufs[2 * j + 1], tx);
4858 }
4859 if (i == 1) {
4860 dmu_buf_rele(dbt, FTAG);
4861 }
4862 }
4863 dmu_tx_commit(tx);
4864
4865 /*
4866 * Sanity check the stuff we just wrote.
4867 */
4868 {
4869 void *packcheck = umem_alloc(packsize, UMEM_NOFAIL);
4870 void *bigcheck = umem_alloc(bigsize, UMEM_NOFAIL);
4871
4872 VERIFY(0 == dmu_read(os, packobj, packoff,
4873 packsize, packcheck, DMU_READ_PREFETCH));
4874 VERIFY(0 == dmu_read(os, bigobj, bigoff,
4875 bigsize, bigcheck, DMU_READ_PREFETCH));
4876
4877 ASSERT(bcmp(packbuf, packcheck, packsize) == 0);
4878 ASSERT(bcmp(bigbuf, bigcheck, bigsize) == 0);
4879
4880 umem_free(packcheck, packsize);
4881 umem_free(bigcheck, bigsize);
4882 }
4883 if (i == 2) {
4884 txg_wait_open(dmu_objset_pool(os), 0);
4885 } else if (i == 3) {
4886 txg_wait_synced(dmu_objset_pool(os), 0);
4887 }
4888 }
4889
4890 dmu_buf_rele(bonus_db, FTAG);
4891 umem_free(packbuf, packsize);
4892 umem_free(bigbuf, bigsize);
4893 umem_free(bigbuf_arcbufs, 2 * s * sizeof (arc_buf_t *));
4894 umem_free(od, size);
4895 }
4896
4897 /* ARGSUSED */
4898 void
4899 ztest_dmu_write_parallel(ztest_ds_t *zd, uint64_t id)
4900 {
4901 ztest_od_t *od;
4902
4903 od = umem_alloc(sizeof (ztest_od_t), UMEM_NOFAIL);
4904 uint64_t offset = (1ULL << (ztest_random(20) + 43)) +
4905 (ztest_random(ZTEST_RANGE_LOCKS) << SPA_MAXBLOCKSHIFT);
4906
4907 /*
4908 * Have multiple threads write to large offsets in an object
4909 * to verify that parallel writes to an object -- even to the
4910 * same blocks within the object -- doesn't cause any trouble.
4911 */
4912 ztest_od_init(od, ID_PARALLEL, FTAG, 0, DMU_OT_UINT64_OTHER, 0, 0, 0);
4913
4914 if (ztest_object_init(zd, od, sizeof (ztest_od_t), B_FALSE) != 0)
4915 return;
4916
4917 while (ztest_random(10) != 0)
4918 ztest_io(zd, od->od_object, offset);
4919
4920 umem_free(od, sizeof (ztest_od_t));
4921 }
4922
4923 void
4924 ztest_dmu_prealloc(ztest_ds_t *zd, uint64_t id)
4925 {
4926 ztest_od_t *od;
4927 uint64_t offset = (1ULL << (ztest_random(4) + SPA_MAXBLOCKSHIFT)) +
4928 (ztest_random(ZTEST_RANGE_LOCKS) << SPA_MAXBLOCKSHIFT);
4929 uint64_t count = ztest_random(20) + 1;
4930 uint64_t blocksize = ztest_random_blocksize();
4931 void *data;
4932
4933 od = umem_alloc(sizeof (ztest_od_t), UMEM_NOFAIL);
4934
4935 ztest_od_init(od, id, FTAG, 0, DMU_OT_UINT64_OTHER, blocksize, 0, 0);
4936
4937 if (ztest_object_init(zd, od, sizeof (ztest_od_t),
4938 !ztest_random(2)) != 0) {
4939 umem_free(od, sizeof (ztest_od_t));
4940 return;
4941 }
4942
4943 if (ztest_truncate(zd, od->od_object, offset, count * blocksize) != 0) {
4944 umem_free(od, sizeof (ztest_od_t));
4945 return;
4946 }
4947
4948 ztest_prealloc(zd, od->od_object, offset, count * blocksize);
4949
4950 data = umem_zalloc(blocksize, UMEM_NOFAIL);
4951
4952 while (ztest_random(count) != 0) {
4953 uint64_t randoff = offset + (ztest_random(count) * blocksize);
4954 if (ztest_write(zd, od->od_object, randoff, blocksize,
4955 data) != 0)
4956 break;
4957 while (ztest_random(4) != 0)
4958 ztest_io(zd, od->od_object, randoff);
4959 }
4960
4961 umem_free(data, blocksize);
4962 umem_free(od, sizeof (ztest_od_t));
4963 }
4964
4965 /*
4966 * Verify that zap_{create,destroy,add,remove,update} work as expected.
4967 */
4968 #define ZTEST_ZAP_MIN_INTS 1
4969 #define ZTEST_ZAP_MAX_INTS 4
4970 #define ZTEST_ZAP_MAX_PROPS 1000
4971
4972 void
4973 ztest_zap(ztest_ds_t *zd, uint64_t id)
4974 {
4975 objset_t *os = zd->zd_os;
4976 ztest_od_t *od;
4977 uint64_t object;
4978 uint64_t txg, last_txg;
4979 uint64_t value[ZTEST_ZAP_MAX_INTS];
4980 uint64_t zl_ints, zl_intsize, prop;
4981 int i, ints;
4982 dmu_tx_t *tx;
4983 char propname[100], txgname[100];
4984 int error;
4985 char *hc[2] = { "s.acl.h", ".s.open.h.hyLZlg" };
4986
4987 od = umem_alloc(sizeof (ztest_od_t), UMEM_NOFAIL);
4988 ztest_od_init(od, id, FTAG, 0, DMU_OT_ZAP_OTHER, 0, 0, 0);
4989
4990 if (ztest_object_init(zd, od, sizeof (ztest_od_t),
4991 !ztest_random(2)) != 0)
4992 goto out;
4993
4994 object = od->od_object;
4995
4996 /*
4997 * Generate a known hash collision, and verify that
4998 * we can lookup and remove both entries.
4999 */
5000 tx = dmu_tx_create(os);
5001 dmu_tx_hold_zap(tx, object, B_TRUE, NULL);
5002 txg = ztest_tx_assign(tx, TXG_MIGHTWAIT, FTAG);
5003 if (txg == 0)
5004 goto out;
5005 for (i = 0; i < 2; i++) {
5006 value[i] = i;
5007 VERIFY3U(0, ==, zap_add(os, object, hc[i], sizeof (uint64_t),
5008 1, &value[i], tx));
5009 }
5010 for (i = 0; i < 2; i++) {
5011 VERIFY3U(EEXIST, ==, zap_add(os, object, hc[i],
5012 sizeof (uint64_t), 1, &value[i], tx));
5013 VERIFY3U(0, ==,
5014 zap_length(os, object, hc[i], &zl_intsize, &zl_ints));
5015 ASSERT3U(zl_intsize, ==, sizeof (uint64_t));
5016 ASSERT3U(zl_ints, ==, 1);
5017 }
5018 for (i = 0; i < 2; i++) {
5019 VERIFY3U(0, ==, zap_remove(os, object, hc[i], tx));
5020 }
5021 dmu_tx_commit(tx);
5022
5023 /*
5024 * Generate a bunch of random entries.
5025 */
5026 ints = MAX(ZTEST_ZAP_MIN_INTS, object % ZTEST_ZAP_MAX_INTS);
5027
5028 prop = ztest_random(ZTEST_ZAP_MAX_PROPS);
5029 (void) sprintf(propname, "prop_%llu", (u_longlong_t)prop);
5030 (void) sprintf(txgname, "txg_%llu", (u_longlong_t)prop);
5031 bzero(value, sizeof (value));
5032 last_txg = 0;
5033
5034 /*
5035 * If these zap entries already exist, validate their contents.
5036 */
5037 error = zap_length(os, object, txgname, &zl_intsize, &zl_ints);
5038 if (error == 0) {
5039 ASSERT3U(zl_intsize, ==, sizeof (uint64_t));
5040 ASSERT3U(zl_ints, ==, 1);
5041
5042 VERIFY(zap_lookup(os, object, txgname, zl_intsize,
5043 zl_ints, &last_txg) == 0);
5044
5045 VERIFY(zap_length(os, object, propname, &zl_intsize,
5046 &zl_ints) == 0);
5047
5048 ASSERT3U(zl_intsize, ==, sizeof (uint64_t));
5049 ASSERT3U(zl_ints, ==, ints);
5050
5051 VERIFY(zap_lookup(os, object, propname, zl_intsize,
5052 zl_ints, value) == 0);
5053
5054 for (i = 0; i < ints; i++) {
5055 ASSERT3U(value[i], ==, last_txg + object + i);
5056 }
5057 } else {
5058 ASSERT3U(error, ==, ENOENT);
5059 }
5060
5061 /*
5062 * Atomically update two entries in our zap object.
5063 * The first is named txg_%llu, and contains the txg
5064 * in which the property was last updated. The second
5065 * is named prop_%llu, and the nth element of its value
5066 * should be txg + object + n.
5067 */
5068 tx = dmu_tx_create(os);
5069 dmu_tx_hold_zap(tx, object, B_TRUE, NULL);
5070 txg = ztest_tx_assign(tx, TXG_MIGHTWAIT, FTAG);
5071 if (txg == 0)
5072 goto out;
5073
5074 if (last_txg > txg)
5075 fatal(0, "zap future leak: old %llu new %llu", last_txg, txg);
5076
5077 for (i = 0; i < ints; i++)
5078 value[i] = txg + object + i;
5079
5080 VERIFY3U(0, ==, zap_update(os, object, txgname, sizeof (uint64_t),
5081 1, &txg, tx));
5082 VERIFY3U(0, ==, zap_update(os, object, propname, sizeof (uint64_t),
5083 ints, value, tx));
5084
5085 dmu_tx_commit(tx);
5086
5087 /*
5088 * Remove a random pair of entries.
5089 */
5090 prop = ztest_random(ZTEST_ZAP_MAX_PROPS);
5091 (void) sprintf(propname, "prop_%llu", (u_longlong_t)prop);
5092 (void) sprintf(txgname, "txg_%llu", (u_longlong_t)prop);
5093
5094 error = zap_length(os, object, txgname, &zl_intsize, &zl_ints);
5095
5096 if (error == ENOENT)
5097 goto out;
5098
5099 ASSERT0(error);
5100
5101 tx = dmu_tx_create(os);
5102 dmu_tx_hold_zap(tx, object, B_TRUE, NULL);
5103 txg = ztest_tx_assign(tx, TXG_MIGHTWAIT, FTAG);
5104 if (txg == 0)
5105 goto out;
5106 VERIFY3U(0, ==, zap_remove(os, object, txgname, tx));
5107 VERIFY3U(0, ==, zap_remove(os, object, propname, tx));
5108 dmu_tx_commit(tx);
5109 out:
5110 umem_free(od, sizeof (ztest_od_t));
5111 }
5112
5113 /*
5114 * Test case to test the upgrading of a microzap to fatzap.
5115 */
5116 void
5117 ztest_fzap(ztest_ds_t *zd, uint64_t id)
5118 {
5119 objset_t *os = zd->zd_os;
5120 ztest_od_t *od;
5121 uint64_t object, txg;
5122 int i;
5123
5124 od = umem_alloc(sizeof (ztest_od_t), UMEM_NOFAIL);
5125 ztest_od_init(od, id, FTAG, 0, DMU_OT_ZAP_OTHER, 0, 0, 0);
5126
5127 if (ztest_object_init(zd, od, sizeof (ztest_od_t),
5128 !ztest_random(2)) != 0)
5129 goto out;
5130 object = od->od_object;
5131
5132 /*
5133 * Add entries to this ZAP and make sure it spills over
5134 * and gets upgraded to a fatzap. Also, since we are adding
5135 * 2050 entries we should see ptrtbl growth and leaf-block split.
5136 */
5137 for (i = 0; i < 2050; i++) {
5138 char name[ZFS_MAX_DATASET_NAME_LEN];
5139 uint64_t value = i;
5140 dmu_tx_t *tx;
5141 int error;
5142
5143 (void) snprintf(name, sizeof (name), "fzap-%llu-%llu",
5144 (u_longlong_t)id, (u_longlong_t)value);
5145
5146 tx = dmu_tx_create(os);
5147 dmu_tx_hold_zap(tx, object, B_TRUE, name);
5148 txg = ztest_tx_assign(tx, TXG_MIGHTWAIT, FTAG);
5149 if (txg == 0)
5150 goto out;
5151 error = zap_add(os, object, name, sizeof (uint64_t), 1,
5152 &value, tx);
5153 ASSERT(error == 0 || error == EEXIST);
5154 dmu_tx_commit(tx);
5155 }
5156 out:
5157 umem_free(od, sizeof (ztest_od_t));
5158 }
5159
5160 /* ARGSUSED */
5161 void
5162 ztest_zap_parallel(ztest_ds_t *zd, uint64_t id)
5163 {
5164 objset_t *os = zd->zd_os;
5165 ztest_od_t *od;
5166 uint64_t txg, object, count, wsize, wc, zl_wsize, zl_wc;
5167 dmu_tx_t *tx;
5168 int i, namelen, error;
5169 int micro = ztest_random(2);
5170 char name[20], string_value[20];
5171 void *data;
5172
5173 od = umem_alloc(sizeof (ztest_od_t), UMEM_NOFAIL);
5174 ztest_od_init(od, ID_PARALLEL, FTAG, micro, DMU_OT_ZAP_OTHER, 0, 0, 0);
5175
5176 if (ztest_object_init(zd, od, sizeof (ztest_od_t), B_FALSE) != 0) {
5177 umem_free(od, sizeof (ztest_od_t));
5178 return;
5179 }
5180
5181 object = od->od_object;
5182
5183 /*
5184 * Generate a random name of the form 'xxx.....' where each
5185 * x is a random printable character and the dots are dots.
5186 * There are 94 such characters, and the name length goes from
5187 * 6 to 20, so there are 94^3 * 15 = 12,458,760 possible names.
5188 */
5189 namelen = ztest_random(sizeof (name) - 5) + 5 + 1;
5190
5191 for (i = 0; i < 3; i++)
5192 name[i] = '!' + ztest_random('~' - '!' + 1);
5193 for (; i < namelen - 1; i++)
5194 name[i] = '.';
5195 name[i] = '\0';
5196
5197 if ((namelen & 1) || micro) {
5198 wsize = sizeof (txg);
5199 wc = 1;
5200 data = &txg;
5201 } else {
5202 wsize = 1;
5203 wc = namelen;
5204 data = string_value;
5205 }
5206
5207 count = -1ULL;
5208 VERIFY0(zap_count(os, object, &count));
5209 ASSERT(count != -1ULL);
5210
5211 /*
5212 * Select an operation: length, lookup, add, update, remove.
5213 */
5214 i = ztest_random(5);
5215
5216 if (i >= 2) {
5217 tx = dmu_tx_create(os);
5218 dmu_tx_hold_zap(tx, object, B_TRUE, NULL);
5219 txg = ztest_tx_assign(tx, TXG_MIGHTWAIT, FTAG);
5220 if (txg == 0) {
5221 umem_free(od, sizeof (ztest_od_t));
5222 return;
5223 }
5224 bcopy(name, string_value, namelen);
5225 } else {
5226 tx = NULL;
5227 txg = 0;
5228 bzero(string_value, namelen);
5229 }
5230
5231 switch (i) {
5232
5233 case 0:
5234 error = zap_length(os, object, name, &zl_wsize, &zl_wc);
5235 if (error == 0) {
5236 ASSERT3U(wsize, ==, zl_wsize);
5237 ASSERT3U(wc, ==, zl_wc);
5238 } else {
5239 ASSERT3U(error, ==, ENOENT);
5240 }
5241 break;
5242
5243 case 1:
5244 error = zap_lookup(os, object, name, wsize, wc, data);
5245 if (error == 0) {
5246 if (data == string_value &&
5247 bcmp(name, data, namelen) != 0)
5248 fatal(0, "name '%s' != val '%s' len %d",
5249 name, data, namelen);
5250 } else {
5251 ASSERT3U(error, ==, ENOENT);
5252 }
5253 break;
5254
5255 case 2:
5256 error = zap_add(os, object, name, wsize, wc, data, tx);
5257 ASSERT(error == 0 || error == EEXIST);
5258 break;
5259
5260 case 3:
5261 VERIFY(zap_update(os, object, name, wsize, wc, data, tx) == 0);
5262 break;
5263
5264 case 4:
5265 error = zap_remove(os, object, name, tx);
5266 ASSERT(error == 0 || error == ENOENT);
5267 break;
5268 }
5269
5270 if (tx != NULL)
5271 dmu_tx_commit(tx);
5272
5273 umem_free(od, sizeof (ztest_od_t));
5274 }
5275
5276 /*
5277 * Commit callback data.
5278 */
5279 typedef struct ztest_cb_data {
5280 list_node_t zcd_node;
5281 uint64_t zcd_txg;
5282 int zcd_expected_err;
5283 boolean_t zcd_added;
5284 boolean_t zcd_called;
5285 spa_t *zcd_spa;
5286 } ztest_cb_data_t;
5287
5288 /* This is the actual commit callback function */
5289 static void
5290 ztest_commit_callback(void *arg, int error)
5291 {
5292 ztest_cb_data_t *data = arg;
5293 uint64_t synced_txg;
5294
5295 VERIFY(data != NULL);
5296 VERIFY3S(data->zcd_expected_err, ==, error);
5297 VERIFY(!data->zcd_called);
5298
5299 synced_txg = spa_last_synced_txg(data->zcd_spa);
5300 if (data->zcd_txg > synced_txg)
5301 fatal(0, "commit callback of txg %" PRIu64 " called prematurely"
5302 ", last synced txg = %" PRIu64 "\n", data->zcd_txg,
5303 synced_txg);
5304
5305 data->zcd_called = B_TRUE;
5306
5307 if (error == ECANCELED) {
5308 ASSERT0(data->zcd_txg);
5309 ASSERT(!data->zcd_added);
5310
5311 /*
5312 * The private callback data should be destroyed here, but
5313 * since we are going to check the zcd_called field after
5314 * dmu_tx_abort(), we will destroy it there.
5315 */
5316 return;
5317 }
5318
5319 ASSERT(data->zcd_added);
5320 ASSERT3U(data->zcd_txg, !=, 0);
5321
5322 (void) mutex_enter(&zcl.zcl_callbacks_lock);
5323
5324 /* See if this cb was called more quickly */
5325 if ((synced_txg - data->zcd_txg) < zc_min_txg_delay)
5326 zc_min_txg_delay = synced_txg - data->zcd_txg;
5327
5328 /* Remove our callback from the list */
5329 list_remove(&zcl.zcl_callbacks, data);
5330
5331 (void) mutex_exit(&zcl.zcl_callbacks_lock);
5332
5333 umem_free(data, sizeof (ztest_cb_data_t));
5334 }
5335
5336 /* Allocate and initialize callback data structure */
5337 static ztest_cb_data_t *
5338 ztest_create_cb_data(objset_t *os, uint64_t txg)
5339 {
5340 ztest_cb_data_t *cb_data;
5341
5342 cb_data = umem_zalloc(sizeof (ztest_cb_data_t), UMEM_NOFAIL);
5343
5344 cb_data->zcd_txg = txg;
5345 cb_data->zcd_spa = dmu_objset_spa(os);
5346 list_link_init(&cb_data->zcd_node);
5347
5348 return (cb_data);
5349 }
5350
5351 /*
5352 * Commit callback test.
5353 */
5354 void
5355 ztest_dmu_commit_callbacks(ztest_ds_t *zd, uint64_t id)
5356 {
5357 objset_t *os = zd->zd_os;
5358 ztest_od_t *od;
5359 dmu_tx_t *tx;
5360 ztest_cb_data_t *cb_data[3], *tmp_cb;
5361 uint64_t old_txg, txg;
5362 int i, error = 0;
5363
5364 od = umem_alloc(sizeof (ztest_od_t), UMEM_NOFAIL);
5365 ztest_od_init(od, id, FTAG, 0, DMU_OT_UINT64_OTHER, 0, 0, 0);
5366
5367 if (ztest_object_init(zd, od, sizeof (ztest_od_t), B_FALSE) != 0) {
5368 umem_free(od, sizeof (ztest_od_t));
5369 return;
5370 }
5371
5372 tx = dmu_tx_create(os);
5373
5374 cb_data[0] = ztest_create_cb_data(os, 0);
5375 dmu_tx_callback_register(tx, ztest_commit_callback, cb_data[0]);
5376
5377 dmu_tx_hold_write(tx, od->od_object, 0, sizeof (uint64_t));
5378
5379 /* Every once in a while, abort the transaction on purpose */
5380 if (ztest_random(100) == 0)
5381 error = -1;
5382
5383 if (!error)
5384 error = dmu_tx_assign(tx, TXG_NOWAIT);
5385
5386 txg = error ? 0 : dmu_tx_get_txg(tx);
5387
5388 cb_data[0]->zcd_txg = txg;
5389 cb_data[1] = ztest_create_cb_data(os, txg);
5390 dmu_tx_callback_register(tx, ztest_commit_callback, cb_data[1]);
5391
5392 if (error) {
5393 /*
5394 * It's not a strict requirement to call the registered
5395 * callbacks from inside dmu_tx_abort(), but that's what
5396 * it's supposed to happen in the current implementation
5397 * so we will check for that.
5398 */
5399 for (i = 0; i < 2; i++) {
5400 cb_data[i]->zcd_expected_err = ECANCELED;
5401 VERIFY(!cb_data[i]->zcd_called);
5402 }
5403
5404 dmu_tx_abort(tx);
5405
5406 for (i = 0; i < 2; i++) {
5407 VERIFY(cb_data[i]->zcd_called);
5408 umem_free(cb_data[i], sizeof (ztest_cb_data_t));
5409 }
5410
5411 umem_free(od, sizeof (ztest_od_t));
5412 return;
5413 }
5414
5415 cb_data[2] = ztest_create_cb_data(os, txg);
5416 dmu_tx_callback_register(tx, ztest_commit_callback, cb_data[2]);
5417
5418 /*
5419 * Read existing data to make sure there isn't a future leak.
5420 */
5421 VERIFY(0 == dmu_read(os, od->od_object, 0, sizeof (uint64_t),
5422 &old_txg, DMU_READ_PREFETCH));
5423
5424 if (old_txg > txg)
5425 fatal(0, "future leak: got %" PRIu64 ", open txg is %" PRIu64,
5426 old_txg, txg);
5427
5428 dmu_write(os, od->od_object, 0, sizeof (uint64_t), &txg, tx);
5429
5430 (void) mutex_enter(&zcl.zcl_callbacks_lock);
5431
5432 /*
5433 * Since commit callbacks don't have any ordering requirement and since
5434 * it is theoretically possible for a commit callback to be called
5435 * after an arbitrary amount of time has elapsed since its txg has been
5436 * synced, it is difficult to reliably determine whether a commit
5437 * callback hasn't been called due to high load or due to a flawed
5438 * implementation.
5439 *
5440 * In practice, we will assume that if after a certain number of txgs a
5441 * commit callback hasn't been called, then most likely there's an
5442 * implementation bug..
5443 */
5444 tmp_cb = list_head(&zcl.zcl_callbacks);
5445 if (tmp_cb != NULL &&
5446 tmp_cb->zcd_txg + ZTEST_COMMIT_CB_THRESH < txg) {
5447 fatal(0, "Commit callback threshold exceeded, oldest txg: %"
5448 PRIu64 ", open txg: %" PRIu64 "\n", tmp_cb->zcd_txg, txg);
5449 }
5450
5451 /*
5452 * Let's find the place to insert our callbacks.
5453 *
5454 * Even though the list is ordered by txg, it is possible for the
5455 * insertion point to not be the end because our txg may already be
5456 * quiescing at this point and other callbacks in the open txg
5457 * (from other objsets) may have sneaked in.
5458 */
5459 tmp_cb = list_tail(&zcl.zcl_callbacks);
5460 while (tmp_cb != NULL && tmp_cb->zcd_txg > txg)
5461 tmp_cb = list_prev(&zcl.zcl_callbacks, tmp_cb);
5462
5463 /* Add the 3 callbacks to the list */
5464 for (i = 0; i < 3; i++) {
5465 if (tmp_cb == NULL)
5466 list_insert_head(&zcl.zcl_callbacks, cb_data[i]);
5467 else
5468 list_insert_after(&zcl.zcl_callbacks, tmp_cb,
5469 cb_data[i]);
5470
5471 cb_data[i]->zcd_added = B_TRUE;
5472 VERIFY(!cb_data[i]->zcd_called);
5473
5474 tmp_cb = cb_data[i];
5475 }
5476
5477 zc_cb_counter += 3;
5478
5479 (void) mutex_exit(&zcl.zcl_callbacks_lock);
5480
5481 dmu_tx_commit(tx);
5482
5483 umem_free(od, sizeof (ztest_od_t));
5484 }
5485
5486 /*
5487 * Visit each object in the dataset. Verify that its properties
5488 * are consistent what was stored in the block tag when it was created,
5489 * and that its unused bonus buffer space has not been overwritten.
5490 */
5491 /* ARGSUSED */
5492 void
5493 ztest_verify_dnode_bt(ztest_ds_t *zd, uint64_t id)
5494 {
5495 objset_t *os = zd->zd_os;
5496 uint64_t obj;
5497 int err = 0;
5498
5499 for (obj = 0; err == 0; err = dmu_object_next(os, &obj, FALSE, 0)) {
5500 ztest_block_tag_t *bt = NULL;
5501 dmu_object_info_t doi;
5502 dmu_buf_t *db;
5503
5504 ztest_object_lock(zd, obj, RL_READER);
5505 if (dmu_bonus_hold(os, obj, FTAG, &db) != 0) {
5506 ztest_object_unlock(zd, obj);
5507 continue;
5508 }
5509
5510 dmu_object_info_from_db(db, &doi);
5511 if (doi.doi_bonus_size >= sizeof (*bt))
5512 bt = ztest_bt_bonus(db);
5513
5514 if (bt && bt->bt_magic == BT_MAGIC) {
5515 ztest_bt_verify(bt, os, obj, doi.doi_dnodesize,
5516 bt->bt_offset, bt->bt_gen, bt->bt_txg,
5517 bt->bt_crtxg);
5518 ztest_verify_unused_bonus(db, bt, obj, os, bt->bt_gen);
5519 }
5520
5521 dmu_buf_rele(db, FTAG);
5522 ztest_object_unlock(zd, obj);
5523 }
5524 }
5525
5526 /* ARGSUSED */
5527 void
5528 ztest_dsl_prop_get_set(ztest_ds_t *zd, uint64_t id)
5529 {
5530 zfs_prop_t proplist[] = {
5531 ZFS_PROP_CHECKSUM,
5532 ZFS_PROP_COMPRESSION,
5533 ZFS_PROP_COPIES,
5534 ZFS_PROP_DEDUP
5535 };
5536 int p;
5537
5538 (void) pthread_rwlock_rdlock(&ztest_name_lock);
5539
5540 for (p = 0; p < sizeof (proplist) / sizeof (proplist[0]); p++)
5541 (void) ztest_dsl_prop_set_uint64(zd->zd_name, proplist[p],
5542 ztest_random_dsl_prop(proplist[p]), (int)ztest_random(2));
5543
5544 VERIFY0(ztest_dsl_prop_set_uint64(zd->zd_name, ZFS_PROP_RECORDSIZE,
5545 ztest_random_blocksize(), (int)ztest_random(2)));
5546
5547 (void) pthread_rwlock_unlock(&ztest_name_lock);
5548 }
5549
5550 /* ARGSUSED */
5551 void
5552 ztest_spa_prop_get_set(ztest_ds_t *zd, uint64_t id)
5553 {
5554 nvlist_t *props = NULL;
5555
5556 (void) pthread_rwlock_rdlock(&ztest_name_lock);
5557
5558 (void) ztest_spa_prop_set_uint64(ZPOOL_PROP_DEDUPDITTO,
5559 ZIO_DEDUPDITTO_MIN + ztest_random(ZIO_DEDUPDITTO_MIN));
5560
5561 VERIFY0(spa_prop_get(ztest_spa, &props));
5562
5563 if (ztest_opts.zo_verbose >= 6)
5564 dump_nvlist(props, 4);
5565
5566 nvlist_free(props);
5567
5568 (void) pthread_rwlock_unlock(&ztest_name_lock);
5569 }
5570
5571 static int
5572 user_release_one(const char *snapname, const char *holdname)
5573 {
5574 nvlist_t *snaps, *holds;
5575 int error;
5576
5577 snaps = fnvlist_alloc();
5578 holds = fnvlist_alloc();
5579 fnvlist_add_boolean(holds, holdname);
5580 fnvlist_add_nvlist(snaps, snapname, holds);
5581 fnvlist_free(holds);
5582 error = dsl_dataset_user_release(snaps, NULL);
5583 fnvlist_free(snaps);
5584 return (error);
5585 }
5586
5587 /*
5588 * Test snapshot hold/release and deferred destroy.
5589 */
5590 void
5591 ztest_dmu_snapshot_hold(ztest_ds_t *zd, uint64_t id)
5592 {
5593 int error;
5594 objset_t *os = zd->zd_os;
5595 objset_t *origin;
5596 char snapname[100];
5597 char fullname[100];
5598 char clonename[100];
5599 char tag[100];
5600 char osname[ZFS_MAX_DATASET_NAME_LEN];
5601 nvlist_t *holds;
5602
5603 (void) pthread_rwlock_rdlock(&ztest_name_lock);
5604
5605 dmu_objset_name(os, osname);
5606
5607 (void) snprintf(snapname, sizeof (snapname), "sh1_%llu",
5608 (u_longlong_t)id);
5609 (void) snprintf(fullname, sizeof (fullname), "%s@%s", osname, snapname);
5610 (void) snprintf(clonename, sizeof (clonename),
5611 "%s/ch1_%llu", osname, (u_longlong_t)id);
5612 (void) snprintf(tag, sizeof (tag), "tag_%llu", (u_longlong_t)id);
5613
5614 /*
5615 * Clean up from any previous run.
5616 */
5617 error = dsl_destroy_head(clonename);
5618 if (error != ENOENT)
5619 ASSERT0(error);
5620 error = user_release_one(fullname, tag);
5621 if (error != ESRCH && error != ENOENT)
5622 ASSERT0(error);
5623 error = dsl_destroy_snapshot(fullname, B_FALSE);
5624 if (error != ENOENT)
5625 ASSERT0(error);
5626
5627 /*
5628 * Create snapshot, clone it, mark snap for deferred destroy,
5629 * destroy clone, verify snap was also destroyed.
5630 */
5631 error = dmu_objset_snapshot_one(osname, snapname);
5632 if (error) {
5633 if (error == ENOSPC) {
5634 ztest_record_enospc("dmu_objset_snapshot");
5635 goto out;
5636 }
5637 fatal(0, "dmu_objset_snapshot(%s) = %d", fullname, error);
5638 }
5639
5640 error = dmu_objset_clone(clonename, fullname);
5641 if (error) {
5642 if (error == ENOSPC) {
5643 ztest_record_enospc("dmu_objset_clone");
5644 goto out;
5645 }
5646 fatal(0, "dmu_objset_clone(%s) = %d", clonename, error);
5647 }
5648
5649 error = dsl_destroy_snapshot(fullname, B_TRUE);
5650 if (error) {
5651 fatal(0, "dsl_destroy_snapshot(%s, B_TRUE) = %d",
5652 fullname, error);
5653 }
5654
5655 error = dsl_destroy_head(clonename);
5656 if (error)
5657 fatal(0, "dsl_destroy_head(%s) = %d", clonename, error);
5658
5659 error = dmu_objset_hold(fullname, FTAG, &origin);
5660 if (error != ENOENT)
5661 fatal(0, "dmu_objset_hold(%s) = %d", fullname, error);
5662
5663 /*
5664 * Create snapshot, add temporary hold, verify that we can't
5665 * destroy a held snapshot, mark for deferred destroy,
5666 * release hold, verify snapshot was destroyed.
5667 */
5668 error = dmu_objset_snapshot_one(osname, snapname);
5669 if (error) {
5670 if (error == ENOSPC) {
5671 ztest_record_enospc("dmu_objset_snapshot");
5672 goto out;
5673 }
5674 fatal(0, "dmu_objset_snapshot(%s) = %d", fullname, error);
5675 }
5676
5677 holds = fnvlist_alloc();
5678 fnvlist_add_string(holds, fullname, tag);
5679 error = dsl_dataset_user_hold(holds, 0, NULL);
5680 fnvlist_free(holds);
5681
5682 if (error == ENOSPC) {
5683 ztest_record_enospc("dsl_dataset_user_hold");
5684 goto out;
5685 } else if (error) {
5686 fatal(0, "dsl_dataset_user_hold(%s, %s) = %u",
5687 fullname, tag, error);
5688 }
5689
5690 error = dsl_destroy_snapshot(fullname, B_FALSE);
5691 if (error != EBUSY) {
5692 fatal(0, "dsl_destroy_snapshot(%s, B_FALSE) = %d",
5693 fullname, error);
5694 }
5695
5696 error = dsl_destroy_snapshot(fullname, B_TRUE);
5697 if (error) {
5698 fatal(0, "dsl_destroy_snapshot(%s, B_TRUE) = %d",
5699 fullname, error);
5700 }
5701
5702 error = user_release_one(fullname, tag);
5703 if (error)
5704 fatal(0, "user_release_one(%s, %s) = %d", fullname, tag, error);
5705
5706 VERIFY3U(dmu_objset_hold(fullname, FTAG, &origin), ==, ENOENT);
5707
5708 out:
5709 (void) pthread_rwlock_unlock(&ztest_name_lock);
5710 }
5711
5712 /*
5713 * Inject random faults into the on-disk data.
5714 */
5715 /* ARGSUSED */
5716 void
5717 ztest_fault_inject(ztest_ds_t *zd, uint64_t id)
5718 {
5719 ztest_shared_t *zs = ztest_shared;
5720 spa_t *spa = ztest_spa;
5721 int fd;
5722 uint64_t offset;
5723 uint64_t leaves;
5724 uint64_t bad = 0x1990c0ffeedecadeull;
5725 uint64_t top, leaf;
5726 char *path0;
5727 char *pathrand;
5728 size_t fsize;
5729 int bshift = SPA_MAXBLOCKSHIFT + 2;
5730 int iters = 1000;
5731 int maxfaults;
5732 int mirror_save;
5733 vdev_t *vd0 = NULL;
5734 uint64_t guid0 = 0;
5735 boolean_t islog = B_FALSE;
5736
5737 path0 = umem_alloc(MAXPATHLEN, UMEM_NOFAIL);
5738 pathrand = umem_alloc(MAXPATHLEN, UMEM_NOFAIL);
5739
5740 mutex_enter(&ztest_vdev_lock);
5741
5742 /*
5743 * Device removal is in progress, fault injection must be disabled
5744 * until it completes and the pool is scrubbed. The fault injection
5745 * strategy for damaging blocks does not take in to account evacuated
5746 * blocks which may have already been damaged.
5747 */
5748 if (ztest_device_removal_active) {
5749 mutex_exit(&ztest_vdev_lock);
5750 goto out;
5751 }
5752
5753 maxfaults = MAXFAULTS(zs);
5754 leaves = MAX(zs->zs_mirrors, 1) * ztest_opts.zo_raidz;
5755 mirror_save = zs->zs_mirrors;
5756 mutex_exit(&ztest_vdev_lock);
5757
5758 ASSERT(leaves >= 1);
5759
5760 /*
5761 * Grab the name lock as reader. There are some operations
5762 * which don't like to have their vdevs changed while
5763 * they are in progress (i.e. spa_change_guid). Those
5764 * operations will have grabbed the name lock as writer.
5765 */
5766 (void) pthread_rwlock_rdlock(&ztest_name_lock);
5767
5768 /*
5769 * We need SCL_STATE here because we're going to look at vd0->vdev_tsd.
5770 */
5771 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
5772
5773 if (ztest_random(2) == 0) {
5774 /*
5775 * Inject errors on a normal data device or slog device.
5776 */
5777 top = ztest_random_vdev_top(spa, B_TRUE);
5778 leaf = ztest_random(leaves) + zs->zs_splits;
5779
5780 /*
5781 * Generate paths to the first leaf in this top-level vdev,
5782 * and to the random leaf we selected. We'll induce transient
5783 * write failures and random online/offline activity on leaf 0,
5784 * and we'll write random garbage to the randomly chosen leaf.
5785 */
5786 (void) snprintf(path0, MAXPATHLEN, ztest_dev_template,
5787 ztest_opts.zo_dir, ztest_opts.zo_pool,
5788 top * leaves + zs->zs_splits);
5789 (void) snprintf(pathrand, MAXPATHLEN, ztest_dev_template,
5790 ztest_opts.zo_dir, ztest_opts.zo_pool,
5791 top * leaves + leaf);
5792
5793 vd0 = vdev_lookup_by_path(spa->spa_root_vdev, path0);
5794 if (vd0 != NULL && vd0->vdev_top->vdev_islog)
5795 islog = B_TRUE;
5796
5797 /*
5798 * If the top-level vdev needs to be resilvered
5799 * then we only allow faults on the device that is
5800 * resilvering.
5801 */
5802 if (vd0 != NULL && maxfaults != 1 &&
5803 (!vdev_resilver_needed(vd0->vdev_top, NULL, NULL) ||
5804 vd0->vdev_resilver_txg != 0)) {
5805 /*
5806 * Make vd0 explicitly claim to be unreadable,
5807 * or unwriteable, or reach behind its back
5808 * and close the underlying fd. We can do this if
5809 * maxfaults == 0 because we'll fail and reexecute,
5810 * and we can do it if maxfaults >= 2 because we'll
5811 * have enough redundancy. If maxfaults == 1, the
5812 * combination of this with injection of random data
5813 * corruption below exceeds the pool's fault tolerance.
5814 */
5815 vdev_file_t *vf = vd0->vdev_tsd;
5816
5817 zfs_dbgmsg("injecting fault to vdev %llu; maxfaults=%d",
5818 (long long)vd0->vdev_id, (int)maxfaults);
5819
5820 if (vf != NULL && ztest_random(3) == 0) {
5821 (void) close(vf->vf_vnode->v_fd);
5822 vf->vf_vnode->v_fd = -1;
5823 } else if (ztest_random(2) == 0) {
5824 vd0->vdev_cant_read = B_TRUE;
5825 } else {
5826 vd0->vdev_cant_write = B_TRUE;
5827 }
5828 guid0 = vd0->vdev_guid;
5829 }
5830 } else {
5831 /*
5832 * Inject errors on an l2cache device.
5833 */
5834 spa_aux_vdev_t *sav = &spa->spa_l2cache;
5835
5836 if (sav->sav_count == 0) {
5837 spa_config_exit(spa, SCL_STATE, FTAG);
5838 (void) pthread_rwlock_unlock(&ztest_name_lock);
5839 goto out;
5840 }
5841 vd0 = sav->sav_vdevs[ztest_random(sav->sav_count)];
5842 guid0 = vd0->vdev_guid;
5843 (void) strcpy(path0, vd0->vdev_path);
5844 (void) strcpy(pathrand, vd0->vdev_path);
5845
5846 leaf = 0;
5847 leaves = 1;
5848 maxfaults = INT_MAX; /* no limit on cache devices */
5849 }
5850
5851 spa_config_exit(spa, SCL_STATE, FTAG);
5852 (void) pthread_rwlock_unlock(&ztest_name_lock);
5853
5854 /*
5855 * If we can tolerate two or more faults, or we're dealing
5856 * with a slog, randomly online/offline vd0.
5857 */
5858 if ((maxfaults >= 2 || islog) && guid0 != 0) {
5859 if (ztest_random(10) < 6) {
5860 int flags = (ztest_random(2) == 0 ?
5861 ZFS_OFFLINE_TEMPORARY : 0);
5862
5863 /*
5864 * We have to grab the zs_name_lock as writer to
5865 * prevent a race between offlining a slog and
5866 * destroying a dataset. Offlining the slog will
5867 * grab a reference on the dataset which may cause
5868 * dsl_destroy_head() to fail with EBUSY thus
5869 * leaving the dataset in an inconsistent state.
5870 */
5871 if (islog)
5872 (void) pthread_rwlock_wrlock(&ztest_name_lock);
5873
5874 VERIFY(vdev_offline(spa, guid0, flags) != EBUSY);
5875
5876 if (islog)
5877 (void) pthread_rwlock_unlock(&ztest_name_lock);
5878 } else {
5879 /*
5880 * Ideally we would like to be able to randomly
5881 * call vdev_[on|off]line without holding locks
5882 * to force unpredictable failures but the side
5883 * effects of vdev_[on|off]line prevent us from
5884 * doing so. We grab the ztest_vdev_lock here to
5885 * prevent a race between injection testing and
5886 * aux_vdev removal.
5887 */
5888 mutex_enter(&ztest_vdev_lock);
5889 (void) vdev_online(spa, guid0, 0, NULL);
5890 mutex_exit(&ztest_vdev_lock);
5891 }
5892 }
5893
5894 if (maxfaults == 0)
5895 goto out;
5896
5897 /*
5898 * We have at least single-fault tolerance, so inject data corruption.
5899 */
5900 fd = open(pathrand, O_RDWR);
5901
5902 if (fd == -1) /* we hit a gap in the device namespace */
5903 goto out;
5904
5905 fsize = lseek(fd, 0, SEEK_END);
5906
5907 while (--iters != 0) {
5908 /*
5909 * The offset must be chosen carefully to ensure that
5910 * we do not inject a given logical block with errors
5911 * on two different leaf devices, because ZFS can not
5912 * tolerate that (if maxfaults==1).
5913 *
5914 * We divide each leaf into chunks of size
5915 * (# leaves * SPA_MAXBLOCKSIZE * 4). Within each chunk
5916 * there is a series of ranges to which we can inject errors.
5917 * Each range can accept errors on only a single leaf vdev.
5918 * The error injection ranges are separated by ranges
5919 * which we will not inject errors on any device (DMZs).
5920 * Each DMZ must be large enough such that a single block
5921 * can not straddle it, so that a single block can not be
5922 * a target in two different injection ranges (on different
5923 * leaf vdevs).
5924 *
5925 * For example, with 3 leaves, each chunk looks like:
5926 * 0 to 32M: injection range for leaf 0
5927 * 32M to 64M: DMZ - no injection allowed
5928 * 64M to 96M: injection range for leaf 1
5929 * 96M to 128M: DMZ - no injection allowed
5930 * 128M to 160M: injection range for leaf 2
5931 * 160M to 192M: DMZ - no injection allowed
5932 */
5933 offset = ztest_random(fsize / (leaves << bshift)) *
5934 (leaves << bshift) + (leaf << bshift) +
5935 (ztest_random(1ULL << (bshift - 1)) & -8ULL);
5936
5937 /*
5938 * Only allow damage to the labels at one end of the vdev.
5939 *
5940 * If all labels are damaged, the device will be totally
5941 * inaccessible, which will result in loss of data,
5942 * because we also damage (parts of) the other side of
5943 * the mirror/raidz.
5944 *
5945 * Additionally, we will always have both an even and an
5946 * odd label, so that we can handle crashes in the
5947 * middle of vdev_config_sync().
5948 */
5949 if ((leaf & 1) == 0 && offset < VDEV_LABEL_START_SIZE)
5950 continue;
5951
5952 /*
5953 * The two end labels are stored at the "end" of the disk, but
5954 * the end of the disk (vdev_psize) is aligned to
5955 * sizeof (vdev_label_t).
5956 */
5957 uint64_t psize = P2ALIGN(fsize, sizeof (vdev_label_t));
5958 if ((leaf & 1) == 1 &&
5959 offset + sizeof (bad) > psize - VDEV_LABEL_END_SIZE)
5960 continue;
5961
5962 mutex_enter(&ztest_vdev_lock);
5963 if (mirror_save != zs->zs_mirrors) {
5964 mutex_exit(&ztest_vdev_lock);
5965 (void) close(fd);
5966 goto out;
5967 }
5968
5969 if (pwrite(fd, &bad, sizeof (bad), offset) != sizeof (bad))
5970 fatal(1, "can't inject bad word at 0x%llx in %s",
5971 offset, pathrand);
5972
5973 mutex_exit(&ztest_vdev_lock);
5974
5975 if (ztest_opts.zo_verbose >= 7)
5976 (void) printf("injected bad word into %s,"
5977 " offset 0x%llx\n", pathrand, (u_longlong_t)offset);
5978 }
5979
5980 (void) close(fd);
5981 out:
5982 umem_free(path0, MAXPATHLEN);
5983 umem_free(pathrand, MAXPATHLEN);
5984 }
5985
5986 /*
5987 * Verify that DDT repair works as expected.
5988 */
5989 void
5990 ztest_ddt_repair(ztest_ds_t *zd, uint64_t id)
5991 {
5992 ztest_shared_t *zs = ztest_shared;
5993 spa_t *spa = ztest_spa;
5994 objset_t *os = zd->zd_os;
5995 ztest_od_t *od;
5996 uint64_t object, blocksize, txg, pattern, psize;
5997 enum zio_checksum checksum = spa_dedup_checksum(spa);
5998 dmu_buf_t *db;
5999 dmu_tx_t *tx;
6000 abd_t *abd;
6001 blkptr_t blk;
6002 int copies = 2 * ZIO_DEDUPDITTO_MIN;
6003 int i;
6004
6005 blocksize = ztest_random_blocksize();
6006 blocksize = MIN(blocksize, 2048); /* because we write so many */
6007
6008 od = umem_alloc(sizeof (ztest_od_t), UMEM_NOFAIL);
6009 ztest_od_init(od, id, FTAG, 0, DMU_OT_UINT64_OTHER, blocksize, 0, 0);
6010
6011 if (ztest_object_init(zd, od, sizeof (ztest_od_t), B_FALSE) != 0) {
6012 umem_free(od, sizeof (ztest_od_t));
6013 return;
6014 }
6015
6016 /*
6017 * Take the name lock as writer to prevent anyone else from changing
6018 * the pool and dataset properies we need to maintain during this test.
6019 */
6020 (void) pthread_rwlock_wrlock(&ztest_name_lock);
6021
6022 if (ztest_dsl_prop_set_uint64(zd->zd_name, ZFS_PROP_DEDUP, checksum,
6023 B_FALSE) != 0 ||
6024 ztest_dsl_prop_set_uint64(zd->zd_name, ZFS_PROP_COPIES, 1,
6025 B_FALSE) != 0) {
6026 (void) pthread_rwlock_unlock(&ztest_name_lock);
6027 umem_free(od, sizeof (ztest_od_t));
6028 return;
6029 }
6030
6031 dmu_objset_stats_t dds;
6032 dsl_pool_config_enter(dmu_objset_pool(os), FTAG);
6033 dmu_objset_fast_stat(os, &dds);
6034 dsl_pool_config_exit(dmu_objset_pool(os), FTAG);
6035
6036 object = od[0].od_object;
6037 blocksize = od[0].od_blocksize;
6038 pattern = zs->zs_guid ^ dds.dds_guid;
6039
6040 ASSERT(object != 0);
6041
6042 tx = dmu_tx_create(os);
6043 dmu_tx_hold_write(tx, object, 0, copies * blocksize);
6044 txg = ztest_tx_assign(tx, TXG_WAIT, FTAG);
6045 if (txg == 0) {
6046 (void) pthread_rwlock_unlock(&ztest_name_lock);
6047 umem_free(od, sizeof (ztest_od_t));
6048 return;
6049 }
6050
6051 /*
6052 * Write all the copies of our block.
6053 */
6054 for (i = 0; i < copies; i++) {
6055 uint64_t offset = i * blocksize;
6056 int error = dmu_buf_hold(os, object, offset, FTAG, &db,
6057 DMU_READ_NO_PREFETCH);
6058 if (error != 0) {
6059 fatal(B_FALSE, "dmu_buf_hold(%p, %llu, %llu) = %u",
6060 os, (long long)object, (long long) offset, error);
6061 }
6062 ASSERT(db->db_offset == offset);
6063 ASSERT(db->db_size == blocksize);
6064 ASSERT(ztest_pattern_match(db->db_data, db->db_size, pattern) ||
6065 ztest_pattern_match(db->db_data, db->db_size, 0ULL));
6066 dmu_buf_will_fill(db, tx);
6067 ztest_pattern_set(db->db_data, db->db_size, pattern);
6068 dmu_buf_rele(db, FTAG);
6069 }
6070
6071 dmu_tx_commit(tx);
6072 txg_wait_synced(spa_get_dsl(spa), txg);
6073
6074 /*
6075 * Find out what block we got.
6076 */
6077 VERIFY0(dmu_buf_hold(os, object, 0, FTAG, &db,
6078 DMU_READ_NO_PREFETCH));
6079 blk = *((dmu_buf_impl_t *)db)->db_blkptr;
6080 dmu_buf_rele(db, FTAG);
6081
6082 /*
6083 * Damage the block. Dedup-ditto will save us when we read it later.
6084 */
6085 psize = BP_GET_PSIZE(&blk);
6086 abd = abd_alloc_linear(psize, B_TRUE);
6087 ztest_pattern_set(abd_to_buf(abd), psize, ~pattern);
6088
6089 (void) zio_wait(zio_rewrite(NULL, spa, 0, &blk,
6090 abd, psize, NULL, NULL, ZIO_PRIORITY_SYNC_WRITE,
6091 ZIO_FLAG_CANFAIL | ZIO_FLAG_INDUCE_DAMAGE, NULL));
6092
6093 abd_free(abd);
6094
6095 (void) pthread_rwlock_unlock(&ztest_name_lock);
6096 umem_free(od, sizeof (ztest_od_t));
6097 }
6098
6099 /*
6100 * Scrub the pool.
6101 */
6102 /* ARGSUSED */
6103 void
6104 ztest_scrub(ztest_ds_t *zd, uint64_t id)
6105 {
6106 spa_t *spa = ztest_spa;
6107
6108 /*
6109 * Scrub in progress by device removal.
6110 */
6111 if (ztest_device_removal_active)
6112 return;
6113
6114 (void) spa_scan(spa, POOL_SCAN_SCRUB);
6115 (void) poll(NULL, 0, 100); /* wait a moment, then force a restart */
6116 (void) spa_scan(spa, POOL_SCAN_SCRUB);
6117 }
6118
6119 /*
6120 * Change the guid for the pool.
6121 */
6122 /* ARGSUSED */
6123 void
6124 ztest_reguid(ztest_ds_t *zd, uint64_t id)
6125 {
6126 spa_t *spa = ztest_spa;
6127 uint64_t orig, load;
6128 int error;
6129
6130 if (ztest_opts.zo_mmp_test)
6131 return;
6132
6133 orig = spa_guid(spa);
6134 load = spa_load_guid(spa);
6135
6136 (void) pthread_rwlock_wrlock(&ztest_name_lock);
6137 error = spa_change_guid(spa);
6138 (void) pthread_rwlock_unlock(&ztest_name_lock);
6139
6140 if (error != 0)
6141 return;
6142
6143 if (ztest_opts.zo_verbose >= 4) {
6144 (void) printf("Changed guid old %llu -> %llu\n",
6145 (u_longlong_t)orig, (u_longlong_t)spa_guid(spa));
6146 }
6147
6148 VERIFY3U(orig, !=, spa_guid(spa));
6149 VERIFY3U(load, ==, spa_load_guid(spa));
6150 }
6151
6152 void
6153 ztest_fletcher(ztest_ds_t *zd, uint64_t id)
6154 {
6155 hrtime_t end = gethrtime() + NANOSEC;
6156
6157 while (gethrtime() <= end) {
6158 int run_count = 100;
6159 void *buf;
6160 struct abd *abd_data, *abd_meta;
6161 uint32_t size;
6162 int *ptr;
6163 int i;
6164 zio_cksum_t zc_ref;
6165 zio_cksum_t zc_ref_byteswap;
6166
6167 size = ztest_random_blocksize();
6168
6169 buf = umem_alloc(size, UMEM_NOFAIL);
6170 abd_data = abd_alloc(size, B_FALSE);
6171 abd_meta = abd_alloc(size, B_TRUE);
6172
6173 for (i = 0, ptr = buf; i < size / sizeof (*ptr); i++, ptr++)
6174 *ptr = ztest_random(UINT_MAX);
6175
6176 abd_copy_from_buf_off(abd_data, buf, 0, size);
6177 abd_copy_from_buf_off(abd_meta, buf, 0, size);
6178
6179 VERIFY0(fletcher_4_impl_set("scalar"));
6180 fletcher_4_native(buf, size, NULL, &zc_ref);
6181 fletcher_4_byteswap(buf, size, NULL, &zc_ref_byteswap);
6182
6183 VERIFY0(fletcher_4_impl_set("cycle"));
6184 while (run_count-- > 0) {
6185 zio_cksum_t zc;
6186 zio_cksum_t zc_byteswap;
6187
6188 fletcher_4_byteswap(buf, size, NULL, &zc_byteswap);
6189 fletcher_4_native(buf, size, NULL, &zc);
6190
6191 VERIFY0(bcmp(&zc, &zc_ref, sizeof (zc)));
6192 VERIFY0(bcmp(&zc_byteswap, &zc_ref_byteswap,
6193 sizeof (zc_byteswap)));
6194
6195 /* Test ABD - data */
6196 abd_fletcher_4_byteswap(abd_data, size, NULL,
6197 &zc_byteswap);
6198 abd_fletcher_4_native(abd_data, size, NULL, &zc);
6199
6200 VERIFY0(bcmp(&zc, &zc_ref, sizeof (zc)));
6201 VERIFY0(bcmp(&zc_byteswap, &zc_ref_byteswap,
6202 sizeof (zc_byteswap)));
6203
6204 /* Test ABD - metadata */
6205 abd_fletcher_4_byteswap(abd_meta, size, NULL,
6206 &zc_byteswap);
6207 abd_fletcher_4_native(abd_meta, size, NULL, &zc);
6208
6209 VERIFY0(bcmp(&zc, &zc_ref, sizeof (zc)));
6210 VERIFY0(bcmp(&zc_byteswap, &zc_ref_byteswap,
6211 sizeof (zc_byteswap)));
6212
6213 }
6214
6215 umem_free(buf, size);
6216 abd_free(abd_data);
6217 abd_free(abd_meta);
6218 }
6219 }
6220
6221 void
6222 ztest_fletcher_incr(ztest_ds_t *zd, uint64_t id)
6223 {
6224 void *buf;
6225 size_t size;
6226 int *ptr;
6227 int i;
6228 zio_cksum_t zc_ref;
6229 zio_cksum_t zc_ref_bswap;
6230
6231 hrtime_t end = gethrtime() + NANOSEC;
6232
6233 while (gethrtime() <= end) {
6234 int run_count = 100;
6235
6236 size = ztest_random_blocksize();
6237 buf = umem_alloc(size, UMEM_NOFAIL);
6238
6239 for (i = 0, ptr = buf; i < size / sizeof (*ptr); i++, ptr++)
6240 *ptr = ztest_random(UINT_MAX);
6241
6242 VERIFY0(fletcher_4_impl_set("scalar"));
6243 fletcher_4_native(buf, size, NULL, &zc_ref);
6244 fletcher_4_byteswap(buf, size, NULL, &zc_ref_bswap);
6245
6246 VERIFY0(fletcher_4_impl_set("cycle"));
6247
6248 while (run_count-- > 0) {
6249 zio_cksum_t zc;
6250 zio_cksum_t zc_bswap;
6251 size_t pos = 0;
6252
6253 ZIO_SET_CHECKSUM(&zc, 0, 0, 0, 0);
6254 ZIO_SET_CHECKSUM(&zc_bswap, 0, 0, 0, 0);
6255
6256 while (pos < size) {
6257 size_t inc = 64 * ztest_random(size / 67);
6258 /* sometimes add few bytes to test non-simd */
6259 if (ztest_random(100) < 10)
6260 inc += P2ALIGN(ztest_random(64),
6261 sizeof (uint32_t));
6262
6263 if (inc > (size - pos))
6264 inc = size - pos;
6265
6266 fletcher_4_incremental_native(buf + pos, inc,
6267 &zc);
6268 fletcher_4_incremental_byteswap(buf + pos, inc,
6269 &zc_bswap);
6270
6271 pos += inc;
6272 }
6273
6274 VERIFY3U(pos, ==, size);
6275
6276 VERIFY(ZIO_CHECKSUM_EQUAL(zc, zc_ref));
6277 VERIFY(ZIO_CHECKSUM_EQUAL(zc_bswap, zc_ref_bswap));
6278
6279 /*
6280 * verify if incremental on the whole buffer is
6281 * equivalent to non-incremental version
6282 */
6283 ZIO_SET_CHECKSUM(&zc, 0, 0, 0, 0);
6284 ZIO_SET_CHECKSUM(&zc_bswap, 0, 0, 0, 0);
6285
6286 fletcher_4_incremental_native(buf, size, &zc);
6287 fletcher_4_incremental_byteswap(buf, size, &zc_bswap);
6288
6289 VERIFY(ZIO_CHECKSUM_EQUAL(zc, zc_ref));
6290 VERIFY(ZIO_CHECKSUM_EQUAL(zc_bswap, zc_ref_bswap));
6291 }
6292
6293 umem_free(buf, size);
6294 }
6295 }
6296
6297 static int
6298 ztest_check_path(char *path)
6299 {
6300 struct stat s;
6301 /* return true on success */
6302 return (!stat(path, &s));
6303 }
6304
6305 static void
6306 ztest_get_zdb_bin(char *bin, int len)
6307 {
6308 char *zdb_path;
6309 /*
6310 * Try to use ZDB_PATH and in-tree zdb path. If not successful, just
6311 * let popen to search through PATH.
6312 */
6313 if ((zdb_path = getenv("ZDB_PATH"))) {
6314 strlcpy(bin, zdb_path, len); /* In env */
6315 if (!ztest_check_path(bin)) {
6316 ztest_dump_core = 0;
6317 fatal(1, "invalid ZDB_PATH '%s'", bin);
6318 }
6319 return;
6320 }
6321
6322 VERIFY(realpath(getexecname(), bin) != NULL);
6323 if (strstr(bin, "/ztest/")) {
6324 strstr(bin, "/ztest/")[0] = '\0'; /* In-tree */
6325 strcat(bin, "/zdb/zdb");
6326 if (ztest_check_path(bin))
6327 return;
6328 }
6329 strcpy(bin, "zdb");
6330 }
6331
6332 static vdev_t *
6333 ztest_random_concrete_vdev_leaf(vdev_t *vd)
6334 {
6335 if (vd == NULL)
6336 return (NULL);
6337
6338 if (vd->vdev_children == 0)
6339 return (vd);
6340
6341 vdev_t *eligible[vd->vdev_children];
6342 int eligible_idx = 0, i;
6343 for (i = 0; i < vd->vdev_children; i++) {
6344 vdev_t *cvd = vd->vdev_child[i];
6345 if (cvd->vdev_top->vdev_removing)
6346 continue;
6347 if (cvd->vdev_children > 0 ||
6348 (vdev_is_concrete(cvd) && !cvd->vdev_detached)) {
6349 eligible[eligible_idx++] = cvd;
6350 }
6351 }
6352 VERIFY(eligible_idx > 0);
6353
6354 uint64_t child_no = ztest_random(eligible_idx);
6355 return (ztest_random_concrete_vdev_leaf(eligible[child_no]));
6356 }
6357
6358 /* ARGSUSED */
6359 void
6360 ztest_initialize(ztest_ds_t *zd, uint64_t id)
6361 {
6362 spa_t *spa = ztest_spa;
6363 int error = 0;
6364
6365 mutex_enter(&ztest_vdev_lock);
6366
6367 spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
6368
6369 /* Random leaf vdev */
6370 vdev_t *rand_vd = ztest_random_concrete_vdev_leaf(spa->spa_root_vdev);
6371 if (rand_vd == NULL) {
6372 spa_config_exit(spa, SCL_VDEV, FTAG);
6373 mutex_exit(&ztest_vdev_lock);
6374 return;
6375 }
6376
6377 /*
6378 * The random vdev we've selected may change as soon as we
6379 * drop the spa_config_lock. We create local copies of things
6380 * we're interested in.
6381 */
6382 uint64_t guid = rand_vd->vdev_guid;
6383 char *path = strdup(rand_vd->vdev_path);
6384 boolean_t active = rand_vd->vdev_initialize_thread != NULL;
6385
6386 zfs_dbgmsg("vd %p, guid %llu", rand_vd, guid);
6387 spa_config_exit(spa, SCL_VDEV, FTAG);
6388
6389 uint64_t cmd = ztest_random(POOL_INITIALIZE_FUNCS);
6390
6391 nvlist_t *vdev_guids = fnvlist_alloc();
6392 nvlist_t *vdev_errlist = fnvlist_alloc();
6393 fnvlist_add_uint64(vdev_guids, path, guid);
6394 error = spa_vdev_initialize(spa, vdev_guids, cmd, vdev_errlist);
6395 fnvlist_free(vdev_guids);
6396 fnvlist_free(vdev_errlist);
6397
6398 switch (cmd) {
6399 case POOL_INITIALIZE_CANCEL:
6400 if (ztest_opts.zo_verbose >= 4) {
6401 (void) printf("Cancel initialize %s", path);
6402 if (!active)
6403 (void) printf(" failed (no initialize active)");
6404 (void) printf("\n");
6405 }
6406 break;
6407 case POOL_INITIALIZE_DO:
6408 if (ztest_opts.zo_verbose >= 4) {
6409 (void) printf("Start initialize %s", path);
6410 if (active && error == 0)
6411 (void) printf(" failed (already active)");
6412 else if (error != 0)
6413 (void) printf(" failed (error %d)", error);
6414 (void) printf("\n");
6415 }
6416 break;
6417 case POOL_INITIALIZE_SUSPEND:
6418 if (ztest_opts.zo_verbose >= 4) {
6419 (void) printf("Suspend initialize %s", path);
6420 if (!active)
6421 (void) printf(" failed (no initialize active)");
6422 (void) printf("\n");
6423 }
6424 break;
6425 }
6426 free(path);
6427 mutex_exit(&ztest_vdev_lock);
6428 }
6429
6430 /*
6431 * Verify pool integrity by running zdb.
6432 */
6433 static void
6434 ztest_run_zdb(char *pool)
6435 {
6436 int status;
6437 char *bin;
6438 char *zdb;
6439 char *zbuf;
6440 const int len = MAXPATHLEN + MAXNAMELEN + 20;
6441 FILE *fp;
6442
6443 bin = umem_alloc(len, UMEM_NOFAIL);
6444 zdb = umem_alloc(len, UMEM_NOFAIL);
6445 zbuf = umem_alloc(1024, UMEM_NOFAIL);
6446
6447 ztest_get_zdb_bin(bin, len);
6448
6449 (void) sprintf(zdb,
6450 "%s -bcc%s%s -G -d -U %s "
6451 "-o zfs_reconstruct_indirect_combinations_max=65536 %s",
6452 bin,
6453 ztest_opts.zo_verbose >= 3 ? "s" : "",
6454 ztest_opts.zo_verbose >= 4 ? "v" : "",
6455 spa_config_path,
6456 pool);
6457
6458 if (ztest_opts.zo_verbose >= 5)
6459 (void) printf("Executing %s\n", strstr(zdb, "zdb "));
6460
6461 fp = popen(zdb, "r");
6462
6463 while (fgets(zbuf, 1024, fp) != NULL)
6464 if (ztest_opts.zo_verbose >= 3)
6465 (void) printf("%s", zbuf);
6466
6467 status = pclose(fp);
6468
6469 if (status == 0)
6470 goto out;
6471
6472 ztest_dump_core = 0;
6473 if (WIFEXITED(status))
6474 fatal(0, "'%s' exit code %d", zdb, WEXITSTATUS(status));
6475 else
6476 fatal(0, "'%s' died with signal %d", zdb, WTERMSIG(status));
6477 out:
6478 umem_free(bin, len);
6479 umem_free(zdb, len);
6480 umem_free(zbuf, 1024);
6481 }
6482
6483 static void
6484 ztest_walk_pool_directory(char *header)
6485 {
6486 spa_t *spa = NULL;
6487
6488 if (ztest_opts.zo_verbose >= 6)
6489 (void) printf("%s\n", header);
6490
6491 mutex_enter(&spa_namespace_lock);
6492 while ((spa = spa_next(spa)) != NULL)
6493 if (ztest_opts.zo_verbose >= 6)
6494 (void) printf("\t%s\n", spa_name(spa));
6495 mutex_exit(&spa_namespace_lock);
6496 }
6497
6498 static void
6499 ztest_spa_import_export(char *oldname, char *newname)
6500 {
6501 nvlist_t *config, *newconfig;
6502 uint64_t pool_guid;
6503 spa_t *spa;
6504 int error;
6505
6506 if (ztest_opts.zo_verbose >= 4) {
6507 (void) printf("import/export: old = %s, new = %s\n",
6508 oldname, newname);
6509 }
6510
6511 /*
6512 * Clean up from previous runs.
6513 */
6514 (void) spa_destroy(newname);
6515
6516 /*
6517 * Get the pool's configuration and guid.
6518 */
6519 VERIFY3U(0, ==, spa_open(oldname, &spa, FTAG));
6520
6521 /*
6522 * Kick off a scrub to tickle scrub/export races.
6523 */
6524 if (ztest_random(2) == 0)
6525 (void) spa_scan(spa, POOL_SCAN_SCRUB);
6526
6527 pool_guid = spa_guid(spa);
6528 spa_close(spa, FTAG);
6529
6530 ztest_walk_pool_directory("pools before export");
6531
6532 /*
6533 * Export it.
6534 */
6535 VERIFY3U(0, ==, spa_export(oldname, &config, B_FALSE, B_FALSE));
6536
6537 ztest_walk_pool_directory("pools after export");
6538
6539 /*
6540 * Try to import it.
6541 */
6542 newconfig = spa_tryimport(config);
6543 ASSERT(newconfig != NULL);
6544 nvlist_free(newconfig);
6545
6546 /*
6547 * Import it under the new name.
6548 */
6549 error = spa_import(newname, config, NULL, 0);
6550 if (error != 0) {
6551 dump_nvlist(config, 0);
6552 fatal(B_FALSE, "couldn't import pool %s as %s: error %u",
6553 oldname, newname, error);
6554 }
6555
6556 ztest_walk_pool_directory("pools after import");
6557
6558 /*
6559 * Try to import it again -- should fail with EEXIST.
6560 */
6561 VERIFY3U(EEXIST, ==, spa_import(newname, config, NULL, 0));
6562
6563 /*
6564 * Try to import it under a different name -- should fail with EEXIST.
6565 */
6566 VERIFY3U(EEXIST, ==, spa_import(oldname, config, NULL, 0));
6567
6568 /*
6569 * Verify that the pool is no longer visible under the old name.
6570 */
6571 VERIFY3U(ENOENT, ==, spa_open(oldname, &spa, FTAG));
6572
6573 /*
6574 * Verify that we can open and close the pool using the new name.
6575 */
6576 VERIFY3U(0, ==, spa_open(newname, &spa, FTAG));
6577 ASSERT(pool_guid == spa_guid(spa));
6578 spa_close(spa, FTAG);
6579
6580 nvlist_free(config);
6581 }
6582
6583 static void
6584 ztest_resume(spa_t *spa)
6585 {
6586 if (spa_suspended(spa) && ztest_opts.zo_verbose >= 6)
6587 (void) printf("resuming from suspended state\n");
6588 spa_vdev_state_enter(spa, SCL_NONE);
6589 vdev_clear(spa, NULL);
6590 (void) spa_vdev_state_exit(spa, NULL, 0);
6591 (void) zio_resume(spa);
6592 }
6593
6594 static void
6595 ztest_resume_thread(void *arg)
6596 {
6597 spa_t *spa = arg;
6598
6599 while (!ztest_exiting) {
6600 if (spa_suspended(spa))
6601 ztest_resume(spa);
6602 (void) poll(NULL, 0, 100);
6603
6604 /*
6605 * Periodically change the zfs_compressed_arc_enabled setting.
6606 */
6607 if (ztest_random(10) == 0)
6608 zfs_compressed_arc_enabled = ztest_random(2);
6609
6610 /*
6611 * Periodically change the zfs_abd_scatter_enabled setting.
6612 */
6613 if (ztest_random(10) == 0)
6614 zfs_abd_scatter_enabled = ztest_random(2);
6615 }
6616
6617 thread_exit();
6618 }
6619
6620 static void
6621 ztest_deadman_thread(void *arg)
6622 {
6623 ztest_shared_t *zs = arg;
6624 spa_t *spa = ztest_spa;
6625 hrtime_t delay, overdue, last_run = gethrtime();
6626
6627 delay = (zs->zs_thread_stop - zs->zs_thread_start) +
6628 MSEC2NSEC(zfs_deadman_synctime_ms);
6629
6630 while (!ztest_exiting) {
6631 /*
6632 * Wait for the delay timer while checking occasionally
6633 * if we should stop.
6634 */
6635 if (gethrtime() < last_run + delay) {
6636 (void) poll(NULL, 0, 1000);
6637 continue;
6638 }
6639
6640 /*
6641 * If the pool is suspended then fail immediately. Otherwise,
6642 * check to see if the pool is making any progress. If
6643 * vdev_deadman() discovers that there hasn't been any recent
6644 * I/Os then it will end up aborting the tests.
6645 */
6646 if (spa_suspended(spa) || spa->spa_root_vdev == NULL) {
6647 fatal(0, "aborting test after %llu seconds because "
6648 "pool has transitioned to a suspended state.",
6649 zfs_deadman_synctime_ms / 1000);
6650 }
6651 vdev_deadman(spa->spa_root_vdev, FTAG);
6652
6653 /*
6654 * If the process doesn't complete within a grace period of
6655 * zfs_deadman_synctime_ms over the expected finish time,
6656 * then it may be hung and is terminated.
6657 */
6658 overdue = zs->zs_proc_stop + MSEC2NSEC(zfs_deadman_synctime_ms);
6659 if (gethrtime() > overdue) {
6660 fatal(0, "aborting test after %llu seconds because "
6661 "the process is overdue for termination.",
6662 (gethrtime() - zs->zs_proc_start) / NANOSEC);
6663 }
6664
6665 (void) printf("ztest has been running for %lld seconds\n",
6666 (gethrtime() - zs->zs_proc_start) / NANOSEC);
6667
6668 last_run = gethrtime();
6669 delay = MSEC2NSEC(zfs_deadman_checktime_ms);
6670 }
6671
6672 thread_exit();
6673 }
6674
6675 static void
6676 ztest_execute(int test, ztest_info_t *zi, uint64_t id)
6677 {
6678 ztest_ds_t *zd = &ztest_ds[id % ztest_opts.zo_datasets];
6679 ztest_shared_callstate_t *zc = ZTEST_GET_SHARED_CALLSTATE(test);
6680 hrtime_t functime = gethrtime();
6681 int i;
6682
6683 for (i = 0; i < zi->zi_iters; i++)
6684 zi->zi_func(zd, id);
6685
6686 functime = gethrtime() - functime;
6687
6688 atomic_add_64(&zc->zc_count, 1);
6689 atomic_add_64(&zc->zc_time, functime);
6690
6691 if (ztest_opts.zo_verbose >= 4)
6692 (void) printf("%6.2f sec in %s\n",
6693 (double)functime / NANOSEC, zi->zi_funcname);
6694 }
6695
6696 static void
6697 ztest_thread(void *arg)
6698 {
6699 int rand;
6700 uint64_t id = (uintptr_t)arg;
6701 ztest_shared_t *zs = ztest_shared;
6702 uint64_t call_next;
6703 hrtime_t now;
6704 ztest_info_t *zi;
6705 ztest_shared_callstate_t *zc;
6706
6707 while ((now = gethrtime()) < zs->zs_thread_stop) {
6708 /*
6709 * See if it's time to force a crash.
6710 */
6711 if (now > zs->zs_thread_kill)
6712 ztest_kill(zs);
6713
6714 /*
6715 * If we're getting ENOSPC with some regularity, stop.
6716 */
6717 if (zs->zs_enospc_count > 10)
6718 break;
6719
6720 /*
6721 * Pick a random function to execute.
6722 */
6723 rand = ztest_random(ZTEST_FUNCS);
6724 zi = &ztest_info[rand];
6725 zc = ZTEST_GET_SHARED_CALLSTATE(rand);
6726 call_next = zc->zc_next;
6727
6728 if (now >= call_next &&
6729 atomic_cas_64(&zc->zc_next, call_next, call_next +
6730 ztest_random(2 * zi->zi_interval[0] + 1)) == call_next) {
6731 ztest_execute(rand, zi, id);
6732 }
6733 }
6734
6735 thread_exit();
6736 }
6737
6738 static void
6739 ztest_dataset_name(char *dsname, char *pool, int d)
6740 {
6741 (void) snprintf(dsname, ZFS_MAX_DATASET_NAME_LEN, "%s/ds_%d", pool, d);
6742 }
6743
6744 static void
6745 ztest_dataset_destroy(int d)
6746 {
6747 char name[ZFS_MAX_DATASET_NAME_LEN];
6748 int t;
6749
6750 ztest_dataset_name(name, ztest_opts.zo_pool, d);
6751
6752 if (ztest_opts.zo_verbose >= 3)
6753 (void) printf("Destroying %s to free up space\n", name);
6754
6755 /*
6756 * Cleanup any non-standard clones and snapshots. In general,
6757 * ztest thread t operates on dataset (t % zopt_datasets),
6758 * so there may be more than one thing to clean up.
6759 */
6760 for (t = d; t < ztest_opts.zo_threads;
6761 t += ztest_opts.zo_datasets)
6762 ztest_dsl_dataset_cleanup(name, t);
6763
6764 (void) dmu_objset_find(name, ztest_objset_destroy_cb, NULL,
6765 DS_FIND_SNAPSHOTS | DS_FIND_CHILDREN);
6766 }
6767
6768 static void
6769 ztest_dataset_dirobj_verify(ztest_ds_t *zd)
6770 {
6771 uint64_t usedobjs, dirobjs, scratch;
6772
6773 /*
6774 * ZTEST_DIROBJ is the object directory for the entire dataset.
6775 * Therefore, the number of objects in use should equal the
6776 * number of ZTEST_DIROBJ entries, +1 for ZTEST_DIROBJ itself.
6777 * If not, we have an object leak.
6778 *
6779 * Note that we can only check this in ztest_dataset_open(),
6780 * when the open-context and syncing-context values agree.
6781 * That's because zap_count() returns the open-context value,
6782 * while dmu_objset_space() returns the rootbp fill count.
6783 */
6784 VERIFY3U(0, ==, zap_count(zd->zd_os, ZTEST_DIROBJ, &dirobjs));
6785 dmu_objset_space(zd->zd_os, &scratch, &scratch, &usedobjs, &scratch);
6786 ASSERT3U(dirobjs + 1, ==, usedobjs);
6787 }
6788
6789 static int
6790 ztest_dataset_open(int d)
6791 {
6792 ztest_ds_t *zd = &ztest_ds[d];
6793 uint64_t committed_seq = ZTEST_GET_SHARED_DS(d)->zd_seq;
6794 objset_t *os;
6795 zilog_t *zilog;
6796 char name[ZFS_MAX_DATASET_NAME_LEN];
6797 int error;
6798
6799 ztest_dataset_name(name, ztest_opts.zo_pool, d);
6800
6801 (void) pthread_rwlock_rdlock(&ztest_name_lock);
6802
6803 error = ztest_dataset_create(name);
6804 if (error == ENOSPC) {
6805 (void) pthread_rwlock_unlock(&ztest_name_lock);
6806 ztest_record_enospc(FTAG);
6807 return (error);
6808 }
6809 ASSERT(error == 0 || error == EEXIST);
6810
6811 VERIFY0(ztest_dmu_objset_own(name, DMU_OST_OTHER, B_FALSE,
6812 B_TRUE, zd, &os));
6813 (void) pthread_rwlock_unlock(&ztest_name_lock);
6814
6815 ztest_zd_init(zd, ZTEST_GET_SHARED_DS(d), os);
6816
6817 zilog = zd->zd_zilog;
6818
6819 if (zilog->zl_header->zh_claim_lr_seq != 0 &&
6820 zilog->zl_header->zh_claim_lr_seq < committed_seq)
6821 fatal(0, "missing log records: claimed %llu < committed %llu",
6822 zilog->zl_header->zh_claim_lr_seq, committed_seq);
6823
6824 ztest_dataset_dirobj_verify(zd);
6825
6826 zil_replay(os, zd, ztest_replay_vector);
6827
6828 ztest_dataset_dirobj_verify(zd);
6829
6830 if (ztest_opts.zo_verbose >= 6)
6831 (void) printf("%s replay %llu blocks, %llu records, seq %llu\n",
6832 zd->zd_name,
6833 (u_longlong_t)zilog->zl_parse_blk_count,
6834 (u_longlong_t)zilog->zl_parse_lr_count,
6835 (u_longlong_t)zilog->zl_replaying_seq);
6836
6837 zilog = zil_open(os, ztest_get_data);
6838
6839 if (zilog->zl_replaying_seq != 0 &&
6840 zilog->zl_replaying_seq < committed_seq)
6841 fatal(0, "missing log records: replayed %llu < committed %llu",
6842 zilog->zl_replaying_seq, committed_seq);
6843
6844 return (0);
6845 }
6846
6847 static void
6848 ztest_dataset_close(int d)
6849 {
6850 ztest_ds_t *zd = &ztest_ds[d];
6851
6852 zil_close(zd->zd_zilog);
6853 dmu_objset_disown(zd->zd_os, B_TRUE, zd);
6854
6855 ztest_zd_fini(zd);
6856 }
6857
6858 /* ARGSUSED */
6859 static int
6860 ztest_replay_zil_cb(const char *name, void *arg)
6861 {
6862 objset_t *os;
6863 ztest_ds_t *zdtmp;
6864
6865 VERIFY0(ztest_dmu_objset_own(name, DMU_OST_ANY, B_TRUE,
6866 B_TRUE, FTAG, &os));
6867
6868 zdtmp = umem_alloc(sizeof (ztest_ds_t), UMEM_NOFAIL);
6869
6870 ztest_zd_init(zdtmp, NULL, os);
6871 zil_replay(os, zdtmp, ztest_replay_vector);
6872 ztest_zd_fini(zdtmp);
6873
6874 if (dmu_objset_zil(os)->zl_parse_lr_count != 0 &&
6875 ztest_opts.zo_verbose >= 6) {
6876 zilog_t *zilog = dmu_objset_zil(os);
6877
6878 (void) printf("%s replay %llu blocks, %llu records, seq %llu\n",
6879 name,
6880 (u_longlong_t)zilog->zl_parse_blk_count,
6881 (u_longlong_t)zilog->zl_parse_lr_count,
6882 (u_longlong_t)zilog->zl_replaying_seq);
6883 }
6884
6885 umem_free(zdtmp, sizeof (ztest_ds_t));
6886
6887 dmu_objset_disown(os, B_TRUE, FTAG);
6888 return (0);
6889 }
6890
6891 /*
6892 * Kick off threads to run tests on all datasets in parallel.
6893 */
6894 static void
6895 ztest_run(ztest_shared_t *zs)
6896 {
6897 spa_t *spa;
6898 objset_t *os;
6899 kthread_t *resume_thread, *deadman_thread;
6900 kthread_t **run_threads;
6901 uint64_t object;
6902 int error;
6903 int t, d;
6904
6905 ztest_exiting = B_FALSE;
6906
6907 /*
6908 * Initialize parent/child shared state.
6909 */
6910 mutex_init(&ztest_vdev_lock, NULL, MUTEX_DEFAULT, NULL);
6911 mutex_init(&ztest_checkpoint_lock, NULL, MUTEX_DEFAULT, NULL);
6912 VERIFY0(pthread_rwlock_init(&ztest_name_lock, NULL));
6913
6914 zs->zs_thread_start = gethrtime();
6915 zs->zs_thread_stop =
6916 zs->zs_thread_start + ztest_opts.zo_passtime * NANOSEC;
6917 zs->zs_thread_stop = MIN(zs->zs_thread_stop, zs->zs_proc_stop);
6918 zs->zs_thread_kill = zs->zs_thread_stop;
6919 if (ztest_random(100) < ztest_opts.zo_killrate) {
6920 zs->zs_thread_kill -=
6921 ztest_random(ztest_opts.zo_passtime * NANOSEC);
6922 }
6923
6924 mutex_init(&zcl.zcl_callbacks_lock, NULL, MUTEX_DEFAULT, NULL);
6925
6926 list_create(&zcl.zcl_callbacks, sizeof (ztest_cb_data_t),
6927 offsetof(ztest_cb_data_t, zcd_node));
6928
6929 /*
6930 * Open our pool.
6931 */
6932 kernel_init(FREAD | FWRITE);
6933 VERIFY0(spa_open(ztest_opts.zo_pool, &spa, FTAG));
6934 metaslab_preload_limit = ztest_random(20) + 1;
6935 ztest_spa = spa;
6936
6937 dmu_objset_stats_t dds;
6938 VERIFY0(ztest_dmu_objset_own(ztest_opts.zo_pool,
6939 DMU_OST_ANY, B_TRUE, B_TRUE, FTAG, &os));
6940 dsl_pool_config_enter(dmu_objset_pool(os), FTAG);
6941 dmu_objset_fast_stat(os, &dds);
6942 dsl_pool_config_exit(dmu_objset_pool(os), FTAG);
6943 zs->zs_guid = dds.dds_guid;
6944 dmu_objset_disown(os, B_TRUE, FTAG);
6945
6946 spa->spa_dedup_ditto = 2 * ZIO_DEDUPDITTO_MIN;
6947
6948 /*
6949 * Create a thread to periodically resume suspended I/O.
6950 */
6951 resume_thread = thread_create(NULL, 0, ztest_resume_thread,
6952 spa, 0, NULL, TS_RUN | TS_JOINABLE, defclsyspri);
6953
6954 /*
6955 * Create a deadman thread and set to panic if we hang.
6956 */
6957 deadman_thread = thread_create(NULL, 0, ztest_deadman_thread,
6958 zs, 0, NULL, TS_RUN | TS_JOINABLE, defclsyspri);
6959
6960 spa->spa_deadman_failmode = ZIO_FAILURE_MODE_PANIC;
6961
6962 /*
6963 * Verify that we can safely inquire about any object,
6964 * whether it's allocated or not. To make it interesting,
6965 * we probe a 5-wide window around each power of two.
6966 * This hits all edge cases, including zero and the max.
6967 */
6968 for (t = 0; t < 64; t++) {
6969 for (d = -5; d <= 5; d++) {
6970 error = dmu_object_info(spa->spa_meta_objset,
6971 (1ULL << t) + d, NULL);
6972 ASSERT(error == 0 || error == ENOENT ||
6973 error == EINVAL);
6974 }
6975 }
6976
6977 /*
6978 * If we got any ENOSPC errors on the previous run, destroy something.
6979 */
6980 if (zs->zs_enospc_count != 0) {
6981 int d = ztest_random(ztest_opts.zo_datasets);
6982 ztest_dataset_destroy(d);
6983 }
6984 zs->zs_enospc_count = 0;
6985
6986 /*
6987 * If we were in the middle of ztest_device_removal() and were killed
6988 * we need to ensure the removal and scrub complete before running
6989 * any tests that check ztest_device_removal_active. The removal will
6990 * be restarted automatically when the spa is opened, but we need to
6991 * initiate the scrub manually if it is not already in progress. Note
6992 * that we always run the scrub whenever an indirect vdev exists
6993 * because we have no way of knowing for sure if ztest_device_removal()
6994 * fully completed its scrub before the pool was reimported.
6995 */
6996 if (spa->spa_removing_phys.sr_state == DSS_SCANNING ||
6997 spa->spa_removing_phys.sr_prev_indirect_vdev != -1) {
6998 while (spa->spa_removing_phys.sr_state == DSS_SCANNING)
6999 txg_wait_synced(spa_get_dsl(spa), 0);
7000
7001 (void) spa_scan(spa, POOL_SCAN_SCRUB);
7002 while (dsl_scan_scrubbing(spa_get_dsl(spa)))
7003 txg_wait_synced(spa_get_dsl(spa), 0);
7004 }
7005
7006 run_threads = umem_zalloc(ztest_opts.zo_threads * sizeof (kthread_t *),
7007 UMEM_NOFAIL);
7008
7009 if (ztest_opts.zo_verbose >= 4)
7010 (void) printf("starting main threads...\n");
7011
7012 /*
7013 * Replay all logs of all datasets in the pool. This is primarily for
7014 * temporary datasets which wouldn't otherwise get replayed, which
7015 * can trigger failures when attempting to offline a SLOG in
7016 * ztest_fault_inject().
7017 */
7018 (void) dmu_objset_find(ztest_opts.zo_pool, ztest_replay_zil_cb,
7019 NULL, DS_FIND_CHILDREN);
7020
7021 /*
7022 * Kick off all the tests that run in parallel.
7023 */
7024 for (t = 0; t < ztest_opts.zo_threads; t++) {
7025 if (t < ztest_opts.zo_datasets && ztest_dataset_open(t) != 0) {
7026 umem_free(run_threads, ztest_opts.zo_threads *
7027 sizeof (kthread_t *));
7028 return;
7029 }
7030
7031 run_threads[t] = thread_create(NULL, 0, ztest_thread,
7032 (void *)(uintptr_t)t, 0, NULL, TS_RUN | TS_JOINABLE,
7033 defclsyspri);
7034 }
7035
7036 /*
7037 * Wait for all of the tests to complete.
7038 */
7039 for (t = 0; t < ztest_opts.zo_threads; t++)
7040 VERIFY0(thread_join(run_threads[t]));
7041
7042 /*
7043 * Close all datasets. This must be done after all the threads
7044 * are joined so we can be sure none of the datasets are in-use
7045 * by any of the threads.
7046 */
7047 for (t = 0; t < ztest_opts.zo_threads; t++) {
7048 if (t < ztest_opts.zo_datasets)
7049 ztest_dataset_close(t);
7050 }
7051
7052 txg_wait_synced(spa_get_dsl(spa), 0);
7053
7054 zs->zs_alloc = metaslab_class_get_alloc(spa_normal_class(spa));
7055 zs->zs_space = metaslab_class_get_space(spa_normal_class(spa));
7056
7057 umem_free(run_threads, ztest_opts.zo_threads * sizeof (kthread_t *));
7058
7059 /* Kill the resume and deadman threads */
7060 ztest_exiting = B_TRUE;
7061 VERIFY0(thread_join(resume_thread));
7062 VERIFY0(thread_join(deadman_thread));
7063 ztest_resume(spa);
7064
7065 /*
7066 * Right before closing the pool, kick off a bunch of async I/O;
7067 * spa_close() should wait for it to complete.
7068 */
7069 for (object = 1; object < 50; object++) {
7070 dmu_prefetch(spa->spa_meta_objset, object, 0, 0, 1ULL << 20,
7071 ZIO_PRIORITY_SYNC_READ);
7072 }
7073
7074 /* Verify that at least one commit cb was called in a timely fashion */
7075 if (zc_cb_counter >= ZTEST_COMMIT_CB_MIN_REG)
7076 VERIFY0(zc_min_txg_delay);
7077
7078 spa_close(spa, FTAG);
7079
7080 /*
7081 * Verify that we can loop over all pools.
7082 */
7083 mutex_enter(&spa_namespace_lock);
7084 for (spa = spa_next(NULL); spa != NULL; spa = spa_next(spa))
7085 if (ztest_opts.zo_verbose > 3)
7086 (void) printf("spa_next: found %s\n", spa_name(spa));
7087 mutex_exit(&spa_namespace_lock);
7088
7089 /*
7090 * Verify that we can export the pool and reimport it under a
7091 * different name.
7092 */
7093 if ((ztest_random(2) == 0) && !ztest_opts.zo_mmp_test) {
7094 char name[ZFS_MAX_DATASET_NAME_LEN];
7095 (void) snprintf(name, sizeof (name), "%s_import",
7096 ztest_opts.zo_pool);
7097 ztest_spa_import_export(ztest_opts.zo_pool, name);
7098 ztest_spa_import_export(name, ztest_opts.zo_pool);
7099 }
7100
7101 kernel_fini();
7102
7103 list_destroy(&zcl.zcl_callbacks);
7104 mutex_destroy(&zcl.zcl_callbacks_lock);
7105 (void) pthread_rwlock_destroy(&ztest_name_lock);
7106 mutex_destroy(&ztest_vdev_lock);
7107 mutex_destroy(&ztest_checkpoint_lock);
7108 }
7109
7110 static void
7111 ztest_freeze(void)
7112 {
7113 ztest_ds_t *zd = &ztest_ds[0];
7114 spa_t *spa;
7115 int numloops = 0;
7116
7117 if (ztest_opts.zo_verbose >= 3)
7118 (void) printf("testing spa_freeze()...\n");
7119
7120 kernel_init(FREAD | FWRITE);
7121 VERIFY3U(0, ==, spa_open(ztest_opts.zo_pool, &spa, FTAG));
7122 VERIFY3U(0, ==, ztest_dataset_open(0));
7123 ztest_spa = spa;
7124
7125 /*
7126 * Force the first log block to be transactionally allocated.
7127 * We have to do this before we freeze the pool -- otherwise
7128 * the log chain won't be anchored.
7129 */
7130 while (BP_IS_HOLE(&zd->zd_zilog->zl_header->zh_log)) {
7131 ztest_dmu_object_alloc_free(zd, 0);
7132 zil_commit(zd->zd_zilog, 0);
7133 }
7134
7135 txg_wait_synced(spa_get_dsl(spa), 0);
7136
7137 /*
7138 * Freeze the pool. This stops spa_sync() from doing anything,
7139 * so that the only way to record changes from now on is the ZIL.
7140 */
7141 spa_freeze(spa);
7142
7143 /*
7144 * Because it is hard to predict how much space a write will actually
7145 * require beforehand, we leave ourselves some fudge space to write over
7146 * capacity.
7147 */
7148 uint64_t capacity = metaslab_class_get_space(spa_normal_class(spa)) / 2;
7149
7150 /*
7151 * Run tests that generate log records but don't alter the pool config
7152 * or depend on DSL sync tasks (snapshots, objset create/destroy, etc).
7153 * We do a txg_wait_synced() after each iteration to force the txg
7154 * to increase well beyond the last synced value in the uberblock.
7155 * The ZIL should be OK with that.
7156 *
7157 * Run a random number of times less than zo_maxloops and ensure we do
7158 * not run out of space on the pool.
7159 */
7160 while (ztest_random(10) != 0 &&
7161 numloops++ < ztest_opts.zo_maxloops &&
7162 metaslab_class_get_alloc(spa_normal_class(spa)) < capacity) {
7163 ztest_od_t od;
7164 ztest_od_init(&od, 0, FTAG, 0, DMU_OT_UINT64_OTHER, 0, 0, 0);
7165 VERIFY0(ztest_object_init(zd, &od, sizeof (od), B_FALSE));
7166 ztest_io(zd, od.od_object,
7167 ztest_random(ZTEST_RANGE_LOCKS) << SPA_MAXBLOCKSHIFT);
7168 txg_wait_synced(spa_get_dsl(spa), 0);
7169 }
7170
7171 /*
7172 * Commit all of the changes we just generated.
7173 */
7174 zil_commit(zd->zd_zilog, 0);
7175 txg_wait_synced(spa_get_dsl(spa), 0);
7176
7177 /*
7178 * Close our dataset and close the pool.
7179 */
7180 ztest_dataset_close(0);
7181 spa_close(spa, FTAG);
7182 kernel_fini();
7183
7184 /*
7185 * Open and close the pool and dataset to induce log replay.
7186 */
7187 kernel_init(FREAD | FWRITE);
7188 VERIFY3U(0, ==, spa_open(ztest_opts.zo_pool, &spa, FTAG));
7189 ASSERT(spa_freeze_txg(spa) == UINT64_MAX);
7190 VERIFY3U(0, ==, ztest_dataset_open(0));
7191 ztest_spa = spa;
7192 txg_wait_synced(spa_get_dsl(spa), 0);
7193 ztest_dataset_close(0);
7194 ztest_reguid(NULL, 0);
7195
7196 spa_close(spa, FTAG);
7197 kernel_fini();
7198 }
7199
7200 void
7201 print_time(hrtime_t t, char *timebuf)
7202 {
7203 hrtime_t s = t / NANOSEC;
7204 hrtime_t m = s / 60;
7205 hrtime_t h = m / 60;
7206 hrtime_t d = h / 24;
7207
7208 s -= m * 60;
7209 m -= h * 60;
7210 h -= d * 24;
7211
7212 timebuf[0] = '\0';
7213
7214 if (d)
7215 (void) sprintf(timebuf,
7216 "%llud%02lluh%02llum%02llus", d, h, m, s);
7217 else if (h)
7218 (void) sprintf(timebuf, "%lluh%02llum%02llus", h, m, s);
7219 else if (m)
7220 (void) sprintf(timebuf, "%llum%02llus", m, s);
7221 else
7222 (void) sprintf(timebuf, "%llus", s);
7223 }
7224
7225 static nvlist_t *
7226 make_random_props(void)
7227 {
7228 nvlist_t *props;
7229
7230 VERIFY0(nvlist_alloc(&props, NV_UNIQUE_NAME, 0));
7231
7232 if (ztest_random(2) == 0)
7233 return (props);
7234
7235 VERIFY0(nvlist_add_uint64(props,
7236 zpool_prop_to_name(ZPOOL_PROP_AUTOREPLACE), 1));
7237
7238 return (props);
7239 }
7240
7241 /*
7242 * Import a storage pool with the given name.
7243 */
7244 static void
7245 ztest_import(ztest_shared_t *zs)
7246 {
7247 importargs_t args = { 0 };
7248 spa_t *spa;
7249 nvlist_t *cfg = NULL;
7250 int nsearch = 1;
7251 char *searchdirs[nsearch];
7252 char *name = ztest_opts.zo_pool;
7253 int flags = ZFS_IMPORT_MISSING_LOG;
7254 int error;
7255
7256 mutex_init(&ztest_vdev_lock, NULL, MUTEX_DEFAULT, NULL);
7257 mutex_init(&ztest_checkpoint_lock, NULL, MUTEX_DEFAULT, NULL);
7258 VERIFY0(pthread_rwlock_init(&ztest_name_lock, NULL));
7259
7260 kernel_init(FREAD | FWRITE);
7261
7262 searchdirs[0] = ztest_opts.zo_dir;
7263 args.paths = nsearch;
7264 args.path = searchdirs;
7265 args.can_be_active = B_FALSE;
7266
7267 error = zpool_find_config(NULL, name, &cfg, &args,
7268 &libzpool_config_ops);
7269 if (error)
7270 (void) fatal(0, "No pools found\n");
7271
7272 VERIFY0(spa_import(name, cfg, NULL, flags));
7273 VERIFY0(spa_open(name, &spa, FTAG));
7274 zs->zs_metaslab_sz =
7275 1ULL << spa->spa_root_vdev->vdev_child[0]->vdev_ms_shift;
7276 spa_close(spa, FTAG);
7277
7278 kernel_fini();
7279
7280 if (!ztest_opts.zo_mmp_test) {
7281 ztest_run_zdb(ztest_opts.zo_pool);
7282 ztest_freeze();
7283 ztest_run_zdb(ztest_opts.zo_pool);
7284 }
7285
7286 (void) pthread_rwlock_destroy(&ztest_name_lock);
7287 mutex_destroy(&ztest_vdev_lock);
7288 mutex_destroy(&ztest_checkpoint_lock);
7289 }
7290
7291 /*
7292 * Create a storage pool with the given name and initial vdev size.
7293 * Then test spa_freeze() functionality.
7294 */
7295 static void
7296 ztest_init(ztest_shared_t *zs)
7297 {
7298 spa_t *spa;
7299 nvlist_t *nvroot, *props;
7300 int i;
7301
7302 mutex_init(&ztest_vdev_lock, NULL, MUTEX_DEFAULT, NULL);
7303 mutex_init(&ztest_checkpoint_lock, NULL, MUTEX_DEFAULT, NULL);
7304 VERIFY0(pthread_rwlock_init(&ztest_name_lock, NULL));
7305
7306 kernel_init(FREAD | FWRITE);
7307
7308 /*
7309 * Create the storage pool.
7310 */
7311 (void) spa_destroy(ztest_opts.zo_pool);
7312 ztest_shared->zs_vdev_next_leaf = 0;
7313 zs->zs_splits = 0;
7314 zs->zs_mirrors = ztest_opts.zo_mirrors;
7315 nvroot = make_vdev_root(NULL, NULL, NULL, ztest_opts.zo_vdev_size, 0,
7316 NULL, ztest_opts.zo_raidz, zs->zs_mirrors, 1);
7317 props = make_random_props();
7318
7319 /*
7320 * We don't expect the pool to suspend unless maxfaults == 0,
7321 * in which case ztest_fault_inject() temporarily takes away
7322 * the only valid replica.
7323 */
7324 VERIFY0(nvlist_add_uint64(props,
7325 zpool_prop_to_name(ZPOOL_PROP_FAILUREMODE),
7326 MAXFAULTS(zs) ? ZIO_FAILURE_MODE_PANIC : ZIO_FAILURE_MODE_WAIT));
7327
7328 for (i = 0; i < SPA_FEATURES; i++) {
7329 char *buf;
7330 VERIFY3S(-1, !=, asprintf(&buf, "feature@%s",
7331 spa_feature_table[i].fi_uname));
7332 VERIFY3U(0, ==, nvlist_add_uint64(props, buf, 0));
7333 free(buf);
7334 }
7335
7336 VERIFY0(spa_create(ztest_opts.zo_pool, nvroot, props, NULL, NULL));
7337 nvlist_free(nvroot);
7338 nvlist_free(props);
7339
7340 VERIFY3U(0, ==, spa_open(ztest_opts.zo_pool, &spa, FTAG));
7341 zs->zs_metaslab_sz =
7342 1ULL << spa->spa_root_vdev->vdev_child[0]->vdev_ms_shift;
7343 spa_close(spa, FTAG);
7344
7345 kernel_fini();
7346
7347 if (!ztest_opts.zo_mmp_test) {
7348 ztest_run_zdb(ztest_opts.zo_pool);
7349 ztest_freeze();
7350 ztest_run_zdb(ztest_opts.zo_pool);
7351 }
7352
7353 (void) pthread_rwlock_destroy(&ztest_name_lock);
7354 mutex_destroy(&ztest_vdev_lock);
7355 mutex_destroy(&ztest_checkpoint_lock);
7356 }
7357
7358 static void
7359 setup_data_fd(void)
7360 {
7361 static char ztest_name_data[] = "/tmp/ztest.data.XXXXXX";
7362
7363 ztest_fd_data = mkstemp(ztest_name_data);
7364 ASSERT3S(ztest_fd_data, >=, 0);
7365 (void) unlink(ztest_name_data);
7366 }
7367
7368 static int
7369 shared_data_size(ztest_shared_hdr_t *hdr)
7370 {
7371 int size;
7372
7373 size = hdr->zh_hdr_size;
7374 size += hdr->zh_opts_size;
7375 size += hdr->zh_size;
7376 size += hdr->zh_stats_size * hdr->zh_stats_count;
7377 size += hdr->zh_ds_size * hdr->zh_ds_count;
7378
7379 return (size);
7380 }
7381
7382 static void
7383 setup_hdr(void)
7384 {
7385 int size;
7386 ztest_shared_hdr_t *hdr;
7387
7388 hdr = (void *)mmap(0, P2ROUNDUP(sizeof (*hdr), getpagesize()),
7389 PROT_READ | PROT_WRITE, MAP_SHARED, ztest_fd_data, 0);
7390 ASSERT(hdr != MAP_FAILED);
7391
7392 VERIFY3U(0, ==, ftruncate(ztest_fd_data, sizeof (ztest_shared_hdr_t)));
7393
7394 hdr->zh_hdr_size = sizeof (ztest_shared_hdr_t);
7395 hdr->zh_opts_size = sizeof (ztest_shared_opts_t);
7396 hdr->zh_size = sizeof (ztest_shared_t);
7397 hdr->zh_stats_size = sizeof (ztest_shared_callstate_t);
7398 hdr->zh_stats_count = ZTEST_FUNCS;
7399 hdr->zh_ds_size = sizeof (ztest_shared_ds_t);
7400 hdr->zh_ds_count = ztest_opts.zo_datasets;
7401
7402 size = shared_data_size(hdr);
7403 VERIFY3U(0, ==, ftruncate(ztest_fd_data, size));
7404
7405 (void) munmap((caddr_t)hdr, P2ROUNDUP(sizeof (*hdr), getpagesize()));
7406 }
7407
7408 static void
7409 setup_data(void)
7410 {
7411 int size, offset;
7412 ztest_shared_hdr_t *hdr;
7413 uint8_t *buf;
7414
7415 hdr = (void *)mmap(0, P2ROUNDUP(sizeof (*hdr), getpagesize()),
7416 PROT_READ, MAP_SHARED, ztest_fd_data, 0);
7417 ASSERT(hdr != MAP_FAILED);
7418
7419 size = shared_data_size(hdr);
7420
7421 (void) munmap((caddr_t)hdr, P2ROUNDUP(sizeof (*hdr), getpagesize()));
7422 hdr = ztest_shared_hdr = (void *)mmap(0, P2ROUNDUP(size, getpagesize()),
7423 PROT_READ | PROT_WRITE, MAP_SHARED, ztest_fd_data, 0);
7424 ASSERT(hdr != MAP_FAILED);
7425 buf = (uint8_t *)hdr;
7426
7427 offset = hdr->zh_hdr_size;
7428 ztest_shared_opts = (void *)&buf[offset];
7429 offset += hdr->zh_opts_size;
7430 ztest_shared = (void *)&buf[offset];
7431 offset += hdr->zh_size;
7432 ztest_shared_callstate = (void *)&buf[offset];
7433 offset += hdr->zh_stats_size * hdr->zh_stats_count;
7434 ztest_shared_ds = (void *)&buf[offset];
7435 }
7436
7437 static boolean_t
7438 exec_child(char *cmd, char *libpath, boolean_t ignorekill, int *statusp)
7439 {
7440 pid_t pid;
7441 int status;
7442 char *cmdbuf = NULL;
7443
7444 pid = fork();
7445
7446 if (cmd == NULL) {
7447 cmdbuf = umem_alloc(MAXPATHLEN, UMEM_NOFAIL);
7448 (void) strlcpy(cmdbuf, getexecname(), MAXPATHLEN);
7449 cmd = cmdbuf;
7450 }
7451
7452 if (pid == -1)
7453 fatal(1, "fork failed");
7454
7455 if (pid == 0) { /* child */
7456 char *emptyargv[2] = { cmd, NULL };
7457 char fd_data_str[12];
7458
7459 struct rlimit rl = { 1024, 1024 };
7460 (void) setrlimit(RLIMIT_NOFILE, &rl);
7461
7462 (void) close(ztest_fd_rand);
7463 VERIFY(11 >= snprintf(fd_data_str, 12, "%d", ztest_fd_data));
7464 VERIFY(0 == setenv("ZTEST_FD_DATA", fd_data_str, 1));
7465
7466 (void) enable_extended_FILE_stdio(-1, -1);
7467 if (libpath != NULL)
7468 VERIFY(0 == setenv("LD_LIBRARY_PATH", libpath, 1));
7469 (void) execv(cmd, emptyargv);
7470 ztest_dump_core = B_FALSE;
7471 fatal(B_TRUE, "exec failed: %s", cmd);
7472 }
7473
7474 if (cmdbuf != NULL) {
7475 umem_free(cmdbuf, MAXPATHLEN);
7476 cmd = NULL;
7477 }
7478
7479 while (waitpid(pid, &status, 0) != pid)
7480 continue;
7481 if (statusp != NULL)
7482 *statusp = status;
7483
7484 if (WIFEXITED(status)) {
7485 if (WEXITSTATUS(status) != 0) {
7486 (void) fprintf(stderr, "child exited with code %d\n",
7487 WEXITSTATUS(status));
7488 exit(2);
7489 }
7490 return (B_FALSE);
7491 } else if (WIFSIGNALED(status)) {
7492 if (!ignorekill || WTERMSIG(status) != SIGKILL) {
7493 (void) fprintf(stderr, "child died with signal %d\n",
7494 WTERMSIG(status));
7495 exit(3);
7496 }
7497 return (B_TRUE);
7498 } else {
7499 (void) fprintf(stderr, "something strange happened to child\n");
7500 exit(4);
7501 /* NOTREACHED */
7502 }
7503 }
7504
7505 static void
7506 ztest_run_init(void)
7507 {
7508 int i;
7509
7510 ztest_shared_t *zs = ztest_shared;
7511
7512 /*
7513 * Blow away any existing copy of zpool.cache
7514 */
7515 (void) remove(spa_config_path);
7516
7517 if (ztest_opts.zo_init == 0) {
7518 if (ztest_opts.zo_verbose >= 1)
7519 (void) printf("Importing pool %s\n",
7520 ztest_opts.zo_pool);
7521 ztest_import(zs);
7522 return;
7523 }
7524
7525 /*
7526 * Create and initialize our storage pool.
7527 */
7528 for (i = 1; i <= ztest_opts.zo_init; i++) {
7529 bzero(zs, sizeof (ztest_shared_t));
7530 if (ztest_opts.zo_verbose >= 3 &&
7531 ztest_opts.zo_init != 1) {
7532 (void) printf("ztest_init(), pass %d\n", i);
7533 }
7534 ztest_init(zs);
7535 }
7536 }
7537
7538 int
7539 main(int argc, char **argv)
7540 {
7541 int kills = 0;
7542 int iters = 0;
7543 int older = 0;
7544 int newer = 0;
7545 ztest_shared_t *zs;
7546 ztest_info_t *zi;
7547 ztest_shared_callstate_t *zc;
7548 char timebuf[100];
7549 char numbuf[NN_NUMBUF_SZ];
7550 char *cmd;
7551 boolean_t hasalt;
7552 int f;
7553 char *fd_data_str = getenv("ZTEST_FD_DATA");
7554 struct sigaction action;
7555
7556 (void) setvbuf(stdout, NULL, _IOLBF, 0);
7557
7558 dprintf_setup(&argc, argv);
7559 zfs_deadman_synctime_ms = 300000;
7560 zfs_deadman_checktime_ms = 30000;
7561 /*
7562 * As two-word space map entries may not come up often (especially
7563 * if pool and vdev sizes are small) we want to force at least some
7564 * of them so the feature get tested.
7565 */
7566 zfs_force_some_double_word_sm_entries = B_TRUE;
7567
7568 /*
7569 * Verify that even extensively damaged split blocks with many
7570 * segments can be reconstructed in a reasonable amount of time
7571 * when reconstruction is known to be possible.
7572 *
7573 * Note: the lower this value is, the more damage we inflict, and
7574 * the more time ztest spends in recovering that damage. We chose
7575 * to induce damage 1/100th of the time so recovery is tested but
7576 * not so frequently that ztest doesn't get to test other code paths.
7577 */
7578 zfs_reconstruct_indirect_damage_fraction = 100;
7579
7580 action.sa_handler = sig_handler;
7581 sigemptyset(&action.sa_mask);
7582 action.sa_flags = 0;
7583
7584 if (sigaction(SIGSEGV, &action, NULL) < 0) {
7585 (void) fprintf(stderr, "ztest: cannot catch SIGSEGV: %s.\n",
7586 strerror(errno));
7587 exit(EXIT_FAILURE);
7588 }
7589
7590 if (sigaction(SIGABRT, &action, NULL) < 0) {
7591 (void) fprintf(stderr, "ztest: cannot catch SIGABRT: %s.\n",
7592 strerror(errno));
7593 exit(EXIT_FAILURE);
7594 }
7595
7596 /*
7597 * Force random_get_bytes() to use /dev/urandom in order to prevent
7598 * ztest from needlessly depleting the system entropy pool.
7599 */
7600 random_path = "/dev/urandom";
7601 ztest_fd_rand = open(random_path, O_RDONLY);
7602 ASSERT3S(ztest_fd_rand, >=, 0);
7603
7604 if (!fd_data_str) {
7605 process_options(argc, argv);
7606
7607 setup_data_fd();
7608 setup_hdr();
7609 setup_data();
7610 bcopy(&ztest_opts, ztest_shared_opts,
7611 sizeof (*ztest_shared_opts));
7612 } else {
7613 ztest_fd_data = atoi(fd_data_str);
7614 setup_data();
7615 bcopy(ztest_shared_opts, &ztest_opts, sizeof (ztest_opts));
7616 }
7617 ASSERT3U(ztest_opts.zo_datasets, ==, ztest_shared_hdr->zh_ds_count);
7618
7619 /* Override location of zpool.cache */
7620 VERIFY(asprintf((char **)&spa_config_path, "%s/zpool.cache",
7621 ztest_opts.zo_dir) != -1);
7622
7623 ztest_ds = umem_alloc(ztest_opts.zo_datasets * sizeof (ztest_ds_t),
7624 UMEM_NOFAIL);
7625 zs = ztest_shared;
7626
7627 if (fd_data_str) {
7628 metaslab_force_ganging = ztest_opts.zo_metaslab_force_ganging;
7629 metaslab_df_alloc_threshold =
7630 zs->zs_metaslab_df_alloc_threshold;
7631
7632 if (zs->zs_do_init)
7633 ztest_run_init();
7634 else
7635 ztest_run(zs);
7636 exit(0);
7637 }
7638
7639 hasalt = (strlen(ztest_opts.zo_alt_ztest) != 0);
7640
7641 if (ztest_opts.zo_verbose >= 1) {
7642 (void) printf("%llu vdevs, %d datasets, %d threads,"
7643 " %llu seconds...\n",
7644 (u_longlong_t)ztest_opts.zo_vdevs,
7645 ztest_opts.zo_datasets,
7646 ztest_opts.zo_threads,
7647 (u_longlong_t)ztest_opts.zo_time);
7648 }
7649
7650 cmd = umem_alloc(MAXNAMELEN, UMEM_NOFAIL);
7651 (void) strlcpy(cmd, getexecname(), MAXNAMELEN);
7652
7653 zs->zs_do_init = B_TRUE;
7654 if (strlen(ztest_opts.zo_alt_ztest) != 0) {
7655 if (ztest_opts.zo_verbose >= 1) {
7656 (void) printf("Executing older ztest for "
7657 "initialization: %s\n", ztest_opts.zo_alt_ztest);
7658 }
7659 VERIFY(!exec_child(ztest_opts.zo_alt_ztest,
7660 ztest_opts.zo_alt_libpath, B_FALSE, NULL));
7661 } else {
7662 VERIFY(!exec_child(NULL, NULL, B_FALSE, NULL));
7663 }
7664 zs->zs_do_init = B_FALSE;
7665
7666 zs->zs_proc_start = gethrtime();
7667 zs->zs_proc_stop = zs->zs_proc_start + ztest_opts.zo_time * NANOSEC;
7668
7669 for (f = 0; f < ZTEST_FUNCS; f++) {
7670 zi = &ztest_info[f];
7671 zc = ZTEST_GET_SHARED_CALLSTATE(f);
7672 if (zs->zs_proc_start + zi->zi_interval[0] > zs->zs_proc_stop)
7673 zc->zc_next = UINT64_MAX;
7674 else
7675 zc->zc_next = zs->zs_proc_start +
7676 ztest_random(2 * zi->zi_interval[0] + 1);
7677 }
7678
7679 /*
7680 * Run the tests in a loop. These tests include fault injection
7681 * to verify that self-healing data works, and forced crashes
7682 * to verify that we never lose on-disk consistency.
7683 */
7684 while (gethrtime() < zs->zs_proc_stop) {
7685 int status;
7686 boolean_t killed;
7687
7688 /*
7689 * Initialize the workload counters for each function.
7690 */
7691 for (f = 0; f < ZTEST_FUNCS; f++) {
7692 zc = ZTEST_GET_SHARED_CALLSTATE(f);
7693 zc->zc_count = 0;
7694 zc->zc_time = 0;
7695 }
7696
7697 /* Set the allocation switch size */
7698 zs->zs_metaslab_df_alloc_threshold =
7699 ztest_random(zs->zs_metaslab_sz / 4) + 1;
7700
7701 if (!hasalt || ztest_random(2) == 0) {
7702 if (hasalt && ztest_opts.zo_verbose >= 1) {
7703 (void) printf("Executing newer ztest: %s\n",
7704 cmd);
7705 }
7706 newer++;
7707 killed = exec_child(cmd, NULL, B_TRUE, &status);
7708 } else {
7709 if (hasalt && ztest_opts.zo_verbose >= 1) {
7710 (void) printf("Executing older ztest: %s\n",
7711 ztest_opts.zo_alt_ztest);
7712 }
7713 older++;
7714 killed = exec_child(ztest_opts.zo_alt_ztest,
7715 ztest_opts.zo_alt_libpath, B_TRUE, &status);
7716 }
7717
7718 if (killed)
7719 kills++;
7720 iters++;
7721
7722 if (ztest_opts.zo_verbose >= 1) {
7723 hrtime_t now = gethrtime();
7724
7725 now = MIN(now, zs->zs_proc_stop);
7726 print_time(zs->zs_proc_stop - now, timebuf);
7727 nicenum(zs->zs_space, numbuf, sizeof (numbuf));
7728
7729 (void) printf("Pass %3d, %8s, %3llu ENOSPC, "
7730 "%4.1f%% of %5s used, %3.0f%% done, %8s to go\n",
7731 iters,
7732 WIFEXITED(status) ? "Complete" : "SIGKILL",
7733 (u_longlong_t)zs->zs_enospc_count,
7734 100.0 * zs->zs_alloc / zs->zs_space,
7735 numbuf,
7736 100.0 * (now - zs->zs_proc_start) /
7737 (ztest_opts.zo_time * NANOSEC), timebuf);
7738 }
7739
7740 if (ztest_opts.zo_verbose >= 2) {
7741 (void) printf("\nWorkload summary:\n\n");
7742 (void) printf("%7s %9s %s\n",
7743 "Calls", "Time", "Function");
7744 (void) printf("%7s %9s %s\n",
7745 "-----", "----", "--------");
7746 for (f = 0; f < ZTEST_FUNCS; f++) {
7747 zi = &ztest_info[f];
7748 zc = ZTEST_GET_SHARED_CALLSTATE(f);
7749 print_time(zc->zc_time, timebuf);
7750 (void) printf("%7llu %9s %s\n",
7751 (u_longlong_t)zc->zc_count, timebuf,
7752 zi->zi_funcname);
7753 }
7754 (void) printf("\n");
7755 }
7756
7757 if (!ztest_opts.zo_mmp_test)
7758 ztest_run_zdb(ztest_opts.zo_pool);
7759 }
7760
7761 if (ztest_opts.zo_verbose >= 1) {
7762 if (hasalt) {
7763 (void) printf("%d runs of older ztest: %s\n", older,
7764 ztest_opts.zo_alt_ztest);
7765 (void) printf("%d runs of newer ztest: %s\n", newer,
7766 cmd);
7767 }
7768 (void) printf("%d killed, %d completed, %.0f%% kill rate\n",
7769 kills, iters - kills, (100.0 * kills) / MAX(1, iters));
7770 }
7771
7772 umem_free(cmd, MAXNAMELEN);
7773
7774 return (0);
7775 }