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