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