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