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