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