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