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