]> git.proxmox.com Git - mirror_zfs-debian.git/blob - cmd/ztest/ztest.c
8613d3d63647463bce913d02190be3e7458a2f02
[mirror_zfs-debian.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 zgd->zgd_rl = zgd_private->z_rl->z_rl;
2149
2150 error = dmu_read(os, object, offset, size, buf,
2151 DMU_READ_NO_PREFETCH);
2152 ASSERT(error == 0);
2153 } else {
2154 size = doi.doi_data_block_size;
2155 if (ISP2(size)) {
2156 offset = P2ALIGN(offset, size);
2157 } else {
2158 ASSERT(offset < size);
2159 offset = 0;
2160 }
2161
2162 zgd_private->z_rl = ztest_range_lock(zd, object, offset, size,
2163 RL_READER);
2164 zgd->zgd_rl = zgd_private->z_rl->z_rl;
2165
2166 error = dmu_buf_hold(os, object, offset, zgd, &db,
2167 DMU_READ_NO_PREFETCH);
2168
2169 if (error == 0) {
2170 blkptr_t *bp = &lr->lr_blkptr;
2171
2172 zgd->zgd_db = db;
2173 zgd->zgd_bp = bp;
2174
2175 ASSERT(db->db_offset == offset);
2176 ASSERT(db->db_size == size);
2177
2178 error = dmu_sync(zio, lr->lr_common.lrc_txg,
2179 ztest_get_done, zgd);
2180
2181 if (error == 0)
2182 return (0);
2183 }
2184 }
2185
2186 ztest_get_done(zgd, error);
2187
2188 return (error);
2189 }
2190
2191 static void *
2192 ztest_lr_alloc(size_t lrsize, char *name)
2193 {
2194 char *lr;
2195 size_t namesize = name ? strlen(name) + 1 : 0;
2196
2197 lr = umem_zalloc(lrsize + namesize, UMEM_NOFAIL);
2198
2199 if (name)
2200 bcopy(name, lr + lrsize, namesize);
2201
2202 return (lr);
2203 }
2204
2205 void
2206 ztest_lr_free(void *lr, size_t lrsize, char *name)
2207 {
2208 size_t namesize = name ? strlen(name) + 1 : 0;
2209
2210 umem_free(lr, lrsize + namesize);
2211 }
2212
2213 /*
2214 * Lookup a bunch of objects. Returns the number of objects not found.
2215 */
2216 static int
2217 ztest_lookup(ztest_ds_t *zd, ztest_od_t *od, int count)
2218 {
2219 int missing = 0;
2220 int error;
2221 int i;
2222
2223 ASSERT(mutex_held(&zd->zd_dirobj_lock));
2224
2225 for (i = 0; i < count; i++, od++) {
2226 od->od_object = 0;
2227 error = zap_lookup(zd->zd_os, od->od_dir, od->od_name,
2228 sizeof (uint64_t), 1, &od->od_object);
2229 if (error) {
2230 ASSERT(error == ENOENT);
2231 ASSERT(od->od_object == 0);
2232 missing++;
2233 } else {
2234 dmu_buf_t *db;
2235 ztest_block_tag_t *bbt;
2236 dmu_object_info_t doi;
2237
2238 ASSERT(od->od_object != 0);
2239 ASSERT(missing == 0); /* there should be no gaps */
2240
2241 ztest_object_lock(zd, od->od_object, RL_READER);
2242 VERIFY3U(0, ==, dmu_bonus_hold(zd->zd_os,
2243 od->od_object, FTAG, &db));
2244 dmu_object_info_from_db(db, &doi);
2245 bbt = ztest_bt_bonus(db);
2246 ASSERT3U(bbt->bt_magic, ==, BT_MAGIC);
2247 od->od_type = doi.doi_type;
2248 od->od_blocksize = doi.doi_data_block_size;
2249 od->od_gen = bbt->bt_gen;
2250 dmu_buf_rele(db, FTAG);
2251 ztest_object_unlock(zd, od->od_object);
2252 }
2253 }
2254
2255 return (missing);
2256 }
2257
2258 static int
2259 ztest_create(ztest_ds_t *zd, ztest_od_t *od, int count)
2260 {
2261 int missing = 0;
2262 int i;
2263
2264 ASSERT(mutex_held(&zd->zd_dirobj_lock));
2265
2266 for (i = 0; i < count; i++, od++) {
2267 if (missing) {
2268 od->od_object = 0;
2269 missing++;
2270 continue;
2271 }
2272
2273 lr_create_t *lr = ztest_lr_alloc(sizeof (*lr), od->od_name);
2274
2275 lr->lr_doid = od->od_dir;
2276 lr->lr_foid = 0; /* 0 to allocate, > 0 to claim */
2277 lr->lrz_type = od->od_crtype;
2278 lr->lrz_blocksize = od->od_crblocksize;
2279 lr->lrz_ibshift = ztest_random_ibshift();
2280 lr->lrz_bonustype = DMU_OT_UINT64_OTHER;
2281 lr->lrz_dnodesize = od->od_crdnodesize;
2282 lr->lr_gen = od->od_crgen;
2283 lr->lr_crtime[0] = time(NULL);
2284
2285 if (ztest_replay_create(zd, lr, B_FALSE) != 0) {
2286 ASSERT(missing == 0);
2287 od->od_object = 0;
2288 missing++;
2289 } else {
2290 od->od_object = lr->lr_foid;
2291 od->od_type = od->od_crtype;
2292 od->od_blocksize = od->od_crblocksize;
2293 od->od_gen = od->od_crgen;
2294 ASSERT(od->od_object != 0);
2295 }
2296
2297 ztest_lr_free(lr, sizeof (*lr), od->od_name);
2298 }
2299
2300 return (missing);
2301 }
2302
2303 static int
2304 ztest_remove(ztest_ds_t *zd, ztest_od_t *od, int count)
2305 {
2306 int missing = 0;
2307 int error;
2308 int i;
2309
2310 ASSERT(mutex_held(&zd->zd_dirobj_lock));
2311
2312 od += count - 1;
2313
2314 for (i = count - 1; i >= 0; i--, od--) {
2315 if (missing) {
2316 missing++;
2317 continue;
2318 }
2319
2320 /*
2321 * No object was found.
2322 */
2323 if (od->od_object == 0)
2324 continue;
2325
2326 lr_remove_t *lr = ztest_lr_alloc(sizeof (*lr), od->od_name);
2327
2328 lr->lr_doid = od->od_dir;
2329
2330 if ((error = ztest_replay_remove(zd, lr, B_FALSE)) != 0) {
2331 ASSERT3U(error, ==, ENOSPC);
2332 missing++;
2333 } else {
2334 od->od_object = 0;
2335 }
2336 ztest_lr_free(lr, sizeof (*lr), od->od_name);
2337 }
2338
2339 return (missing);
2340 }
2341
2342 static int
2343 ztest_write(ztest_ds_t *zd, uint64_t object, uint64_t offset, uint64_t size,
2344 void *data)
2345 {
2346 lr_write_t *lr;
2347 int error;
2348
2349 lr = ztest_lr_alloc(sizeof (*lr) + size, NULL);
2350
2351 lr->lr_foid = object;
2352 lr->lr_offset = offset;
2353 lr->lr_length = size;
2354 lr->lr_blkoff = 0;
2355 BP_ZERO(&lr->lr_blkptr);
2356
2357 bcopy(data, lr + 1, size);
2358
2359 error = ztest_replay_write(zd, lr, B_FALSE);
2360
2361 ztest_lr_free(lr, sizeof (*lr) + size, NULL);
2362
2363 return (error);
2364 }
2365
2366 static int
2367 ztest_truncate(ztest_ds_t *zd, uint64_t object, uint64_t offset, uint64_t size)
2368 {
2369 lr_truncate_t *lr;
2370 int error;
2371
2372 lr = ztest_lr_alloc(sizeof (*lr), NULL);
2373
2374 lr->lr_foid = object;
2375 lr->lr_offset = offset;
2376 lr->lr_length = size;
2377
2378 error = ztest_replay_truncate(zd, lr, B_FALSE);
2379
2380 ztest_lr_free(lr, sizeof (*lr), NULL);
2381
2382 return (error);
2383 }
2384
2385 static int
2386 ztest_setattr(ztest_ds_t *zd, uint64_t object)
2387 {
2388 lr_setattr_t *lr;
2389 int error;
2390
2391 lr = ztest_lr_alloc(sizeof (*lr), NULL);
2392
2393 lr->lr_foid = object;
2394 lr->lr_size = 0;
2395 lr->lr_mode = 0;
2396
2397 error = ztest_replay_setattr(zd, lr, B_FALSE);
2398
2399 ztest_lr_free(lr, sizeof (*lr), NULL);
2400
2401 return (error);
2402 }
2403
2404 static void
2405 ztest_prealloc(ztest_ds_t *zd, uint64_t object, uint64_t offset, uint64_t size)
2406 {
2407 objset_t *os = zd->zd_os;
2408 dmu_tx_t *tx;
2409 uint64_t txg;
2410 ztest_zrl_t *rl;
2411
2412 txg_wait_synced(dmu_objset_pool(os), 0);
2413
2414 ztest_object_lock(zd, object, RL_READER);
2415 rl = ztest_range_lock(zd, object, offset, size, RL_WRITER);
2416
2417 tx = dmu_tx_create(os);
2418
2419 dmu_tx_hold_write(tx, object, offset, size);
2420
2421 txg = ztest_tx_assign(tx, TXG_WAIT, FTAG);
2422
2423 if (txg != 0) {
2424 dmu_prealloc(os, object, offset, size, tx);
2425 dmu_tx_commit(tx);
2426 txg_wait_synced(dmu_objset_pool(os), txg);
2427 } else {
2428 (void) dmu_free_long_range(os, object, offset, size);
2429 }
2430
2431 ztest_range_unlock(zd, rl);
2432 ztest_object_unlock(zd, object);
2433 }
2434
2435 static void
2436 ztest_io(ztest_ds_t *zd, uint64_t object, uint64_t offset)
2437 {
2438 int err;
2439 ztest_block_tag_t wbt;
2440 dmu_object_info_t doi;
2441 enum ztest_io_type io_type;
2442 uint64_t blocksize;
2443 void *data;
2444
2445 VERIFY(dmu_object_info(zd->zd_os, object, &doi) == 0);
2446 blocksize = doi.doi_data_block_size;
2447 data = umem_alloc(blocksize, UMEM_NOFAIL);
2448
2449 /*
2450 * Pick an i/o type at random, biased toward writing block tags.
2451 */
2452 io_type = ztest_random(ZTEST_IO_TYPES);
2453 if (ztest_random(2) == 0)
2454 io_type = ZTEST_IO_WRITE_TAG;
2455
2456 (void) rw_rdlock(&zd->zd_zilog_lock);
2457
2458 switch (io_type) {
2459
2460 case ZTEST_IO_WRITE_TAG:
2461 ztest_bt_generate(&wbt, zd->zd_os, object, doi.doi_dnodesize,
2462 offset, 0, 0, 0);
2463 (void) ztest_write(zd, object, offset, sizeof (wbt), &wbt);
2464 break;
2465
2466 case ZTEST_IO_WRITE_PATTERN:
2467 (void) memset(data, 'a' + (object + offset) % 5, blocksize);
2468 if (ztest_random(2) == 0) {
2469 /*
2470 * Induce fletcher2 collisions to ensure that
2471 * zio_ddt_collision() detects and resolves them
2472 * when using fletcher2-verify for deduplication.
2473 */
2474 ((uint64_t *)data)[0] ^= 1ULL << 63;
2475 ((uint64_t *)data)[4] ^= 1ULL << 63;
2476 }
2477 (void) ztest_write(zd, object, offset, blocksize, data);
2478 break;
2479
2480 case ZTEST_IO_WRITE_ZEROES:
2481 bzero(data, blocksize);
2482 (void) ztest_write(zd, object, offset, blocksize, data);
2483 break;
2484
2485 case ZTEST_IO_TRUNCATE:
2486 (void) ztest_truncate(zd, object, offset, blocksize);
2487 break;
2488
2489 case ZTEST_IO_SETATTR:
2490 (void) ztest_setattr(zd, object);
2491 break;
2492 default:
2493 break;
2494
2495 case ZTEST_IO_REWRITE:
2496 (void) rw_rdlock(&ztest_name_lock);
2497 err = ztest_dsl_prop_set_uint64(zd->zd_name,
2498 ZFS_PROP_CHECKSUM, spa_dedup_checksum(ztest_spa),
2499 B_FALSE);
2500 VERIFY(err == 0 || err == ENOSPC);
2501 err = ztest_dsl_prop_set_uint64(zd->zd_name,
2502 ZFS_PROP_COMPRESSION,
2503 ztest_random_dsl_prop(ZFS_PROP_COMPRESSION),
2504 B_FALSE);
2505 VERIFY(err == 0 || err == ENOSPC);
2506 (void) rw_unlock(&ztest_name_lock);
2507
2508 VERIFY0(dmu_read(zd->zd_os, object, offset, blocksize, data,
2509 DMU_READ_NO_PREFETCH));
2510
2511 (void) ztest_write(zd, object, offset, blocksize, data);
2512 break;
2513 }
2514
2515 (void) rw_unlock(&zd->zd_zilog_lock);
2516
2517 umem_free(data, blocksize);
2518 }
2519
2520 /*
2521 * Initialize an object description template.
2522 */
2523 static void
2524 ztest_od_init(ztest_od_t *od, uint64_t id, char *tag, uint64_t index,
2525 dmu_object_type_t type, uint64_t blocksize, uint64_t dnodesize,
2526 uint64_t gen)
2527 {
2528 od->od_dir = ZTEST_DIROBJ;
2529 od->od_object = 0;
2530
2531 od->od_crtype = type;
2532 od->od_crblocksize = blocksize ? blocksize : ztest_random_blocksize();
2533 od->od_crdnodesize = dnodesize ? dnodesize : ztest_random_dnodesize();
2534 od->od_crgen = gen;
2535
2536 od->od_type = DMU_OT_NONE;
2537 od->od_blocksize = 0;
2538 od->od_gen = 0;
2539
2540 (void) snprintf(od->od_name, sizeof (od->od_name), "%s(%lld)[%llu]",
2541 tag, (longlong_t)id, (u_longlong_t)index);
2542 }
2543
2544 /*
2545 * Lookup or create the objects for a test using the od template.
2546 * If the objects do not all exist, or if 'remove' is specified,
2547 * remove any existing objects and create new ones. Otherwise,
2548 * use the existing objects.
2549 */
2550 static int
2551 ztest_object_init(ztest_ds_t *zd, ztest_od_t *od, size_t size, boolean_t remove)
2552 {
2553 int count = size / sizeof (*od);
2554 int rv = 0;
2555
2556 mutex_enter(&zd->zd_dirobj_lock);
2557 if ((ztest_lookup(zd, od, count) != 0 || remove) &&
2558 (ztest_remove(zd, od, count) != 0 ||
2559 ztest_create(zd, od, count) != 0))
2560 rv = -1;
2561 zd->zd_od = od;
2562 mutex_exit(&zd->zd_dirobj_lock);
2563
2564 return (rv);
2565 }
2566
2567 /* ARGSUSED */
2568 void
2569 ztest_zil_commit(ztest_ds_t *zd, uint64_t id)
2570 {
2571 zilog_t *zilog = zd->zd_zilog;
2572
2573 (void) rw_rdlock(&zd->zd_zilog_lock);
2574
2575 zil_commit(zilog, ztest_random(ZTEST_OBJECTS));
2576
2577 /*
2578 * Remember the committed values in zd, which is in parent/child
2579 * shared memory. If we die, the next iteration of ztest_run()
2580 * will verify that the log really does contain this record.
2581 */
2582 mutex_enter(&zilog->zl_lock);
2583 ASSERT(zd->zd_shared != NULL);
2584 ASSERT3U(zd->zd_shared->zd_seq, <=, zilog->zl_commit_lr_seq);
2585 zd->zd_shared->zd_seq = zilog->zl_commit_lr_seq;
2586 mutex_exit(&zilog->zl_lock);
2587
2588 (void) rw_unlock(&zd->zd_zilog_lock);
2589 }
2590
2591 /*
2592 * This function is designed to simulate the operations that occur during a
2593 * mount/unmount operation. We hold the dataset across these operations in an
2594 * attempt to expose any implicit assumptions about ZIL management.
2595 */
2596 /* ARGSUSED */
2597 void
2598 ztest_zil_remount(ztest_ds_t *zd, uint64_t id)
2599 {
2600 objset_t *os = zd->zd_os;
2601
2602 /*
2603 * We grab the zd_dirobj_lock to ensure that no other thread is
2604 * updating the zil (i.e. adding in-memory log records) and the
2605 * zd_zilog_lock to block any I/O.
2606 */
2607 mutex_enter(&zd->zd_dirobj_lock);
2608 (void) rw_wrlock(&zd->zd_zilog_lock);
2609
2610 /* zfsvfs_teardown() */
2611 zil_close(zd->zd_zilog);
2612
2613 /* zfsvfs_setup() */
2614 VERIFY(zil_open(os, ztest_get_data) == zd->zd_zilog);
2615 zil_replay(os, zd, ztest_replay_vector);
2616
2617 (void) rw_unlock(&zd->zd_zilog_lock);
2618 mutex_exit(&zd->zd_dirobj_lock);
2619 }
2620
2621 /*
2622 * Verify that we can't destroy an active pool, create an existing pool,
2623 * or create a pool with a bad vdev spec.
2624 */
2625 /* ARGSUSED */
2626 void
2627 ztest_spa_create_destroy(ztest_ds_t *zd, uint64_t id)
2628 {
2629 ztest_shared_opts_t *zo = &ztest_opts;
2630 spa_t *spa;
2631 nvlist_t *nvroot;
2632
2633 if (zo->zo_mmp_test)
2634 return;
2635
2636 /*
2637 * Attempt to create using a bad file.
2638 */
2639 nvroot = make_vdev_root("/dev/bogus", NULL, NULL, 0, 0, 0, 0, 0, 1);
2640 VERIFY3U(ENOENT, ==,
2641 spa_create("ztest_bad_file", nvroot, NULL, NULL));
2642 nvlist_free(nvroot);
2643
2644 /*
2645 * Attempt to create using a bad mirror.
2646 */
2647 nvroot = make_vdev_root("/dev/bogus", NULL, NULL, 0, 0, 0, 0, 2, 1);
2648 VERIFY3U(ENOENT, ==,
2649 spa_create("ztest_bad_mirror", nvroot, NULL, NULL));
2650 nvlist_free(nvroot);
2651
2652 /*
2653 * Attempt to create an existing pool. It shouldn't matter
2654 * what's in the nvroot; we should fail with EEXIST.
2655 */
2656 (void) rw_rdlock(&ztest_name_lock);
2657 nvroot = make_vdev_root("/dev/bogus", NULL, NULL, 0, 0, 0, 0, 0, 1);
2658 VERIFY3U(EEXIST, ==, spa_create(zo->zo_pool, nvroot, NULL, NULL));
2659 nvlist_free(nvroot);
2660 VERIFY3U(0, ==, spa_open(zo->zo_pool, &spa, FTAG));
2661 VERIFY3U(EBUSY, ==, spa_destroy(zo->zo_pool));
2662 spa_close(spa, FTAG);
2663
2664 (void) rw_unlock(&ztest_name_lock);
2665 }
2666
2667 /*
2668 * Start and then stop the MMP threads to ensure the startup and shutdown code
2669 * works properly. Actual protection and property-related code tested via ZTS.
2670 */
2671 /* ARGSUSED */
2672 void
2673 ztest_mmp_enable_disable(ztest_ds_t *zd, uint64_t id)
2674 {
2675 ztest_shared_opts_t *zo = &ztest_opts;
2676 spa_t *spa = ztest_spa;
2677
2678 if (zo->zo_mmp_test)
2679 return;
2680
2681 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
2682 mutex_enter(&spa->spa_props_lock);
2683
2684 if (!spa_multihost(spa)) {
2685 spa->spa_multihost = B_TRUE;
2686 mmp_thread_start(spa);
2687 }
2688
2689 mutex_exit(&spa->spa_props_lock);
2690 spa_config_exit(spa, SCL_CONFIG, FTAG);
2691
2692 txg_wait_synced(spa_get_dsl(spa), 0);
2693 mmp_signal_all_threads();
2694 txg_wait_synced(spa_get_dsl(spa), 0);
2695
2696 spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
2697 mutex_enter(&spa->spa_props_lock);
2698
2699 if (spa_multihost(spa)) {
2700 mmp_thread_stop(spa);
2701 spa->spa_multihost = B_FALSE;
2702 }
2703
2704 mutex_exit(&spa->spa_props_lock);
2705 spa_config_exit(spa, SCL_CONFIG, FTAG);
2706 }
2707
2708 /* ARGSUSED */
2709 void
2710 ztest_spa_upgrade(ztest_ds_t *zd, uint64_t id)
2711 {
2712 spa_t *spa;
2713 uint64_t initial_version = SPA_VERSION_INITIAL;
2714 uint64_t version, newversion;
2715 nvlist_t *nvroot, *props;
2716 char *name;
2717
2718 if (ztest_opts.zo_mmp_test)
2719 return;
2720
2721 mutex_enter(&ztest_vdev_lock);
2722 name = kmem_asprintf("%s_upgrade", ztest_opts.zo_pool);
2723
2724 /*
2725 * Clean up from previous runs.
2726 */
2727 (void) spa_destroy(name);
2728
2729 nvroot = make_vdev_root(NULL, NULL, name, ztest_opts.zo_vdev_size, 0,
2730 0, ztest_opts.zo_raidz, ztest_opts.zo_mirrors, 1);
2731
2732 /*
2733 * If we're configuring a RAIDZ device then make sure that the
2734 * the initial version is capable of supporting that feature.
2735 */
2736 switch (ztest_opts.zo_raidz_parity) {
2737 case 0:
2738 case 1:
2739 initial_version = SPA_VERSION_INITIAL;
2740 break;
2741 case 2:
2742 initial_version = SPA_VERSION_RAIDZ2;
2743 break;
2744 case 3:
2745 initial_version = SPA_VERSION_RAIDZ3;
2746 break;
2747 }
2748
2749 /*
2750 * Create a pool with a spa version that can be upgraded. Pick
2751 * a value between initial_version and SPA_VERSION_BEFORE_FEATURES.
2752 */
2753 do {
2754 version = ztest_random_spa_version(initial_version);
2755 } while (version > SPA_VERSION_BEFORE_FEATURES);
2756
2757 props = fnvlist_alloc();
2758 fnvlist_add_uint64(props,
2759 zpool_prop_to_name(ZPOOL_PROP_VERSION), version);
2760 VERIFY3S(spa_create(name, nvroot, props, NULL), ==, 0);
2761 fnvlist_free(nvroot);
2762 fnvlist_free(props);
2763
2764 VERIFY3S(spa_open(name, &spa, FTAG), ==, 0);
2765 VERIFY3U(spa_version(spa), ==, version);
2766 newversion = ztest_random_spa_version(version + 1);
2767
2768 if (ztest_opts.zo_verbose >= 4) {
2769 (void) printf("upgrading spa version from %llu to %llu\n",
2770 (u_longlong_t)version, (u_longlong_t)newversion);
2771 }
2772
2773 spa_upgrade(spa, newversion);
2774 VERIFY3U(spa_version(spa), >, version);
2775 VERIFY3U(spa_version(spa), ==, fnvlist_lookup_uint64(spa->spa_config,
2776 zpool_prop_to_name(ZPOOL_PROP_VERSION)));
2777 spa_close(spa, FTAG);
2778
2779 strfree(name);
2780 mutex_exit(&ztest_vdev_lock);
2781 }
2782
2783 static vdev_t *
2784 vdev_lookup_by_path(vdev_t *vd, const char *path)
2785 {
2786 vdev_t *mvd;
2787 int c;
2788
2789 if (vd->vdev_path != NULL && strcmp(path, vd->vdev_path) == 0)
2790 return (vd);
2791
2792 for (c = 0; c < vd->vdev_children; c++)
2793 if ((mvd = vdev_lookup_by_path(vd->vdev_child[c], path)) !=
2794 NULL)
2795 return (mvd);
2796
2797 return (NULL);
2798 }
2799
2800 /*
2801 * Find the first available hole which can be used as a top-level.
2802 */
2803 int
2804 find_vdev_hole(spa_t *spa)
2805 {
2806 vdev_t *rvd = spa->spa_root_vdev;
2807 int c;
2808
2809 ASSERT(spa_config_held(spa, SCL_VDEV, RW_READER) == SCL_VDEV);
2810
2811 for (c = 0; c < rvd->vdev_children; c++) {
2812 vdev_t *cvd = rvd->vdev_child[c];
2813
2814 if (cvd->vdev_ishole)
2815 break;
2816 }
2817 return (c);
2818 }
2819
2820 /*
2821 * Verify that vdev_add() works as expected.
2822 */
2823 /* ARGSUSED */
2824 void
2825 ztest_vdev_add_remove(ztest_ds_t *zd, uint64_t id)
2826 {
2827 ztest_shared_t *zs = ztest_shared;
2828 spa_t *spa = ztest_spa;
2829 uint64_t leaves;
2830 uint64_t guid;
2831 nvlist_t *nvroot;
2832 int error;
2833
2834 if (ztest_opts.zo_mmp_test)
2835 return;
2836
2837 mutex_enter(&ztest_vdev_lock);
2838 leaves = MAX(zs->zs_mirrors + zs->zs_splits, 1) * ztest_opts.zo_raidz;
2839
2840 spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
2841
2842 ztest_shared->zs_vdev_next_leaf = find_vdev_hole(spa) * leaves;
2843
2844 /*
2845 * If we have slogs then remove them 1/4 of the time.
2846 */
2847 if (spa_has_slogs(spa) && ztest_random(4) == 0) {
2848 /*
2849 * Grab the guid from the head of the log class rotor.
2850 */
2851 guid = spa_log_class(spa)->mc_rotor->mg_vd->vdev_guid;
2852
2853 spa_config_exit(spa, SCL_VDEV, FTAG);
2854
2855 /*
2856 * We have to grab the zs_name_lock as writer to
2857 * prevent a race between removing a slog (dmu_objset_find)
2858 * and destroying a dataset. Removing the slog will
2859 * grab a reference on the dataset which may cause
2860 * dsl_destroy_head() to fail with EBUSY thus
2861 * leaving the dataset in an inconsistent state.
2862 */
2863 rw_wrlock(&ztest_name_lock);
2864 error = spa_vdev_remove(spa, guid, B_FALSE);
2865 rw_unlock(&ztest_name_lock);
2866
2867 if (error && error != EEXIST)
2868 fatal(0, "spa_vdev_remove() = %d", error);
2869 } else {
2870 spa_config_exit(spa, SCL_VDEV, FTAG);
2871
2872 /*
2873 * Make 1/4 of the devices be log devices.
2874 */
2875 nvroot = make_vdev_root(NULL, NULL, NULL,
2876 ztest_opts.zo_vdev_size, 0,
2877 ztest_random(4) == 0, ztest_opts.zo_raidz,
2878 zs->zs_mirrors, 1);
2879
2880 error = spa_vdev_add(spa, nvroot);
2881 nvlist_free(nvroot);
2882
2883 if (error == ENOSPC)
2884 ztest_record_enospc("spa_vdev_add");
2885 else if (error != 0)
2886 fatal(0, "spa_vdev_add() = %d", error);
2887 }
2888
2889 mutex_exit(&ztest_vdev_lock);
2890 }
2891
2892 /*
2893 * Verify that adding/removing aux devices (l2arc, hot spare) works as expected.
2894 */
2895 /* ARGSUSED */
2896 void
2897 ztest_vdev_aux_add_remove(ztest_ds_t *zd, uint64_t id)
2898 {
2899 ztest_shared_t *zs = ztest_shared;
2900 spa_t *spa = ztest_spa;
2901 vdev_t *rvd = spa->spa_root_vdev;
2902 spa_aux_vdev_t *sav;
2903 char *aux;
2904 char *path;
2905 uint64_t guid = 0;
2906 int error;
2907
2908 if (ztest_opts.zo_mmp_test)
2909 return;
2910
2911 path = umem_alloc(MAXPATHLEN, UMEM_NOFAIL);
2912
2913 if (ztest_random(2) == 0) {
2914 sav = &spa->spa_spares;
2915 aux = ZPOOL_CONFIG_SPARES;
2916 } else {
2917 sav = &spa->spa_l2cache;
2918 aux = ZPOOL_CONFIG_L2CACHE;
2919 }
2920
2921 mutex_enter(&ztest_vdev_lock);
2922
2923 spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
2924
2925 if (sav->sav_count != 0 && ztest_random(4) == 0) {
2926 /*
2927 * Pick a random device to remove.
2928 */
2929 guid = sav->sav_vdevs[ztest_random(sav->sav_count)]->vdev_guid;
2930 } else {
2931 /*
2932 * Find an unused device we can add.
2933 */
2934 zs->zs_vdev_aux = 0;
2935 for (;;) {
2936 int c;
2937 (void) snprintf(path, MAXPATHLEN, ztest_aux_template,
2938 ztest_opts.zo_dir, ztest_opts.zo_pool, aux,
2939 zs->zs_vdev_aux);
2940 for (c = 0; c < sav->sav_count; c++)
2941 if (strcmp(sav->sav_vdevs[c]->vdev_path,
2942 path) == 0)
2943 break;
2944 if (c == sav->sav_count &&
2945 vdev_lookup_by_path(rvd, path) == NULL)
2946 break;
2947 zs->zs_vdev_aux++;
2948 }
2949 }
2950
2951 spa_config_exit(spa, SCL_VDEV, FTAG);
2952
2953 if (guid == 0) {
2954 /*
2955 * Add a new device.
2956 */
2957 nvlist_t *nvroot = make_vdev_root(NULL, aux, NULL,
2958 (ztest_opts.zo_vdev_size * 5) / 4, 0, 0, 0, 0, 1);
2959 error = spa_vdev_add(spa, nvroot);
2960 if (error != 0)
2961 fatal(0, "spa_vdev_add(%p) = %d", nvroot, error);
2962 nvlist_free(nvroot);
2963 } else {
2964 /*
2965 * Remove an existing device. Sometimes, dirty its
2966 * vdev state first to make sure we handle removal
2967 * of devices that have pending state changes.
2968 */
2969 if (ztest_random(2) == 0)
2970 (void) vdev_online(spa, guid, 0, NULL);
2971
2972 error = spa_vdev_remove(spa, guid, B_FALSE);
2973 if (error != 0 && error != EBUSY)
2974 fatal(0, "spa_vdev_remove(%llu) = %d", guid, error);
2975 }
2976
2977 mutex_exit(&ztest_vdev_lock);
2978
2979 umem_free(path, MAXPATHLEN);
2980 }
2981
2982 /*
2983 * split a pool if it has mirror tlvdevs
2984 */
2985 /* ARGSUSED */
2986 void
2987 ztest_split_pool(ztest_ds_t *zd, uint64_t id)
2988 {
2989 ztest_shared_t *zs = ztest_shared;
2990 spa_t *spa = ztest_spa;
2991 vdev_t *rvd = spa->spa_root_vdev;
2992 nvlist_t *tree, **child, *config, *split, **schild;
2993 uint_t c, children, schildren = 0, lastlogid = 0;
2994 int error = 0;
2995
2996 if (ztest_opts.zo_mmp_test)
2997 return;
2998
2999 mutex_enter(&ztest_vdev_lock);
3000
3001 /* ensure we have a useable config; mirrors of raidz aren't supported */
3002 if (zs->zs_mirrors < 3 || ztest_opts.zo_raidz > 1) {
3003 mutex_exit(&ztest_vdev_lock);
3004 return;
3005 }
3006
3007 /* clean up the old pool, if any */
3008 (void) spa_destroy("splitp");
3009
3010 spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
3011
3012 /* generate a config from the existing config */
3013 mutex_enter(&spa->spa_props_lock);
3014 VERIFY(nvlist_lookup_nvlist(spa->spa_config, ZPOOL_CONFIG_VDEV_TREE,
3015 &tree) == 0);
3016 mutex_exit(&spa->spa_props_lock);
3017
3018 VERIFY(nvlist_lookup_nvlist_array(tree, ZPOOL_CONFIG_CHILDREN, &child,
3019 &children) == 0);
3020
3021 schild = malloc(rvd->vdev_children * sizeof (nvlist_t *));
3022 for (c = 0; c < children; c++) {
3023 vdev_t *tvd = rvd->vdev_child[c];
3024 nvlist_t **mchild;
3025 uint_t mchildren;
3026
3027 if (tvd->vdev_islog || tvd->vdev_ops == &vdev_hole_ops) {
3028 VERIFY(nvlist_alloc(&schild[schildren], NV_UNIQUE_NAME,
3029 0) == 0);
3030 VERIFY(nvlist_add_string(schild[schildren],
3031 ZPOOL_CONFIG_TYPE, VDEV_TYPE_HOLE) == 0);
3032 VERIFY(nvlist_add_uint64(schild[schildren],
3033 ZPOOL_CONFIG_IS_HOLE, 1) == 0);
3034 if (lastlogid == 0)
3035 lastlogid = schildren;
3036 ++schildren;
3037 continue;
3038 }
3039 lastlogid = 0;
3040 VERIFY(nvlist_lookup_nvlist_array(child[c],
3041 ZPOOL_CONFIG_CHILDREN, &mchild, &mchildren) == 0);
3042 VERIFY(nvlist_dup(mchild[0], &schild[schildren++], 0) == 0);
3043 }
3044
3045 /* OK, create a config that can be used to split */
3046 VERIFY(nvlist_alloc(&split, NV_UNIQUE_NAME, 0) == 0);
3047 VERIFY(nvlist_add_string(split, ZPOOL_CONFIG_TYPE,
3048 VDEV_TYPE_ROOT) == 0);
3049 VERIFY(nvlist_add_nvlist_array(split, ZPOOL_CONFIG_CHILDREN, schild,
3050 lastlogid != 0 ? lastlogid : schildren) == 0);
3051
3052 VERIFY(nvlist_alloc(&config, NV_UNIQUE_NAME, 0) == 0);
3053 VERIFY(nvlist_add_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, split) == 0);
3054
3055 for (c = 0; c < schildren; c++)
3056 nvlist_free(schild[c]);
3057 free(schild);
3058 nvlist_free(split);
3059
3060 spa_config_exit(spa, SCL_VDEV, FTAG);
3061
3062 (void) rw_wrlock(&ztest_name_lock);
3063 error = spa_vdev_split_mirror(spa, "splitp", config, NULL, B_FALSE);
3064 (void) rw_unlock(&ztest_name_lock);
3065
3066 nvlist_free(config);
3067
3068 if (error == 0) {
3069 (void) printf("successful split - results:\n");
3070 mutex_enter(&spa_namespace_lock);
3071 show_pool_stats(spa);
3072 show_pool_stats(spa_lookup("splitp"));
3073 mutex_exit(&spa_namespace_lock);
3074 ++zs->zs_splits;
3075 --zs->zs_mirrors;
3076 }
3077 mutex_exit(&ztest_vdev_lock);
3078
3079 }
3080
3081 /*
3082 * Verify that we can attach and detach devices.
3083 */
3084 /* ARGSUSED */
3085 void
3086 ztest_vdev_attach_detach(ztest_ds_t *zd, uint64_t id)
3087 {
3088 ztest_shared_t *zs = ztest_shared;
3089 spa_t *spa = ztest_spa;
3090 spa_aux_vdev_t *sav = &spa->spa_spares;
3091 vdev_t *rvd = spa->spa_root_vdev;
3092 vdev_t *oldvd, *newvd, *pvd;
3093 nvlist_t *root;
3094 uint64_t leaves;
3095 uint64_t leaf, top;
3096 uint64_t ashift = ztest_get_ashift();
3097 uint64_t oldguid, pguid;
3098 uint64_t oldsize, newsize;
3099 char *oldpath, *newpath;
3100 int replacing;
3101 int oldvd_has_siblings = B_FALSE;
3102 int newvd_is_spare = B_FALSE;
3103 int oldvd_is_log;
3104 int error, expected_error;
3105
3106 if (ztest_opts.zo_mmp_test)
3107 return;
3108
3109 oldpath = umem_alloc(MAXPATHLEN, UMEM_NOFAIL);
3110 newpath = umem_alloc(MAXPATHLEN, UMEM_NOFAIL);
3111
3112 mutex_enter(&ztest_vdev_lock);
3113 leaves = MAX(zs->zs_mirrors, 1) * ztest_opts.zo_raidz;
3114
3115 spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
3116
3117 /*
3118 * Decide whether to do an attach or a replace.
3119 */
3120 replacing = ztest_random(2);
3121
3122 /*
3123 * Pick a random top-level vdev.
3124 */
3125 top = ztest_random_vdev_top(spa, B_TRUE);
3126
3127 /*
3128 * Pick a random leaf within it.
3129 */
3130 leaf = ztest_random(leaves);
3131
3132 /*
3133 * Locate this vdev.
3134 */
3135 oldvd = rvd->vdev_child[top];
3136 if (zs->zs_mirrors >= 1) {
3137 ASSERT(oldvd->vdev_ops == &vdev_mirror_ops);
3138 ASSERT(oldvd->vdev_children >= zs->zs_mirrors);
3139 oldvd = oldvd->vdev_child[leaf / ztest_opts.zo_raidz];
3140 }
3141 if (ztest_opts.zo_raidz > 1) {
3142 ASSERT(oldvd->vdev_ops == &vdev_raidz_ops);
3143 ASSERT(oldvd->vdev_children == ztest_opts.zo_raidz);
3144 oldvd = oldvd->vdev_child[leaf % ztest_opts.zo_raidz];
3145 }
3146
3147 /*
3148 * If we're already doing an attach or replace, oldvd may be a
3149 * mirror vdev -- in which case, pick a random child.
3150 */
3151 while (oldvd->vdev_children != 0) {
3152 oldvd_has_siblings = B_TRUE;
3153 ASSERT(oldvd->vdev_children >= 2);
3154 oldvd = oldvd->vdev_child[ztest_random(oldvd->vdev_children)];
3155 }
3156
3157 oldguid = oldvd->vdev_guid;
3158 oldsize = vdev_get_min_asize(oldvd);
3159 oldvd_is_log = oldvd->vdev_top->vdev_islog;
3160 (void) strcpy(oldpath, oldvd->vdev_path);
3161 pvd = oldvd->vdev_parent;
3162 pguid = pvd->vdev_guid;
3163
3164 /*
3165 * If oldvd has siblings, then half of the time, detach it.
3166 */
3167 if (oldvd_has_siblings && ztest_random(2) == 0) {
3168 spa_config_exit(spa, SCL_VDEV, FTAG);
3169 error = spa_vdev_detach(spa, oldguid, pguid, B_FALSE);
3170 if (error != 0 && error != ENODEV && error != EBUSY &&
3171 error != ENOTSUP)
3172 fatal(0, "detach (%s) returned %d", oldpath, error);
3173 goto out;
3174 }
3175
3176 /*
3177 * For the new vdev, choose with equal probability between the two
3178 * standard paths (ending in either 'a' or 'b') or a random hot spare.
3179 */
3180 if (sav->sav_count != 0 && ztest_random(3) == 0) {
3181 newvd = sav->sav_vdevs[ztest_random(sav->sav_count)];
3182 newvd_is_spare = B_TRUE;
3183 (void) strcpy(newpath, newvd->vdev_path);
3184 } else {
3185 (void) snprintf(newpath, MAXPATHLEN, ztest_dev_template,
3186 ztest_opts.zo_dir, ztest_opts.zo_pool,
3187 top * leaves + leaf);
3188 if (ztest_random(2) == 0)
3189 newpath[strlen(newpath) - 1] = 'b';
3190 newvd = vdev_lookup_by_path(rvd, newpath);
3191 }
3192
3193 if (newvd) {
3194 newsize = vdev_get_min_asize(newvd);
3195 } else {
3196 /*
3197 * Make newsize a little bigger or smaller than oldsize.
3198 * If it's smaller, the attach should fail.
3199 * If it's larger, and we're doing a replace,
3200 * we should get dynamic LUN growth when we're done.
3201 */
3202 newsize = 10 * oldsize / (9 + ztest_random(3));
3203 }
3204
3205 /*
3206 * If pvd is not a mirror or root, the attach should fail with ENOTSUP,
3207 * unless it's a replace; in that case any non-replacing parent is OK.
3208 *
3209 * If newvd is already part of the pool, it should fail with EBUSY.
3210 *
3211 * If newvd is too small, it should fail with EOVERFLOW.
3212 */
3213 if (pvd->vdev_ops != &vdev_mirror_ops &&
3214 pvd->vdev_ops != &vdev_root_ops && (!replacing ||
3215 pvd->vdev_ops == &vdev_replacing_ops ||
3216 pvd->vdev_ops == &vdev_spare_ops))
3217 expected_error = ENOTSUP;
3218 else if (newvd_is_spare && (!replacing || oldvd_is_log))
3219 expected_error = ENOTSUP;
3220 else if (newvd == oldvd)
3221 expected_error = replacing ? 0 : EBUSY;
3222 else if (vdev_lookup_by_path(rvd, newpath) != NULL)
3223 expected_error = EBUSY;
3224 else if (newsize < oldsize)
3225 expected_error = EOVERFLOW;
3226 else if (ashift > oldvd->vdev_top->vdev_ashift)
3227 expected_error = EDOM;
3228 else
3229 expected_error = 0;
3230
3231 spa_config_exit(spa, SCL_VDEV, FTAG);
3232
3233 /*
3234 * Build the nvlist describing newpath.
3235 */
3236 root = make_vdev_root(newpath, NULL, NULL, newvd == NULL ? newsize : 0,
3237 ashift, 0, 0, 0, 1);
3238
3239 error = spa_vdev_attach(spa, oldguid, root, replacing);
3240
3241 nvlist_free(root);
3242
3243 /*
3244 * If our parent was the replacing vdev, but the replace completed,
3245 * then instead of failing with ENOTSUP we may either succeed,
3246 * fail with ENODEV, or fail with EOVERFLOW.
3247 */
3248 if (expected_error == ENOTSUP &&
3249 (error == 0 || error == ENODEV || error == EOVERFLOW))
3250 expected_error = error;
3251
3252 /*
3253 * If someone grew the LUN, the replacement may be too small.
3254 */
3255 if (error == EOVERFLOW || error == EBUSY)
3256 expected_error = error;
3257
3258 /* XXX workaround 6690467 */
3259 if (error != expected_error && expected_error != EBUSY) {
3260 fatal(0, "attach (%s %llu, %s %llu, %d) "
3261 "returned %d, expected %d",
3262 oldpath, oldsize, newpath,
3263 newsize, replacing, error, expected_error);
3264 }
3265 out:
3266 mutex_exit(&ztest_vdev_lock);
3267
3268 umem_free(oldpath, MAXPATHLEN);
3269 umem_free(newpath, MAXPATHLEN);
3270 }
3271
3272 /*
3273 * Callback function which expands the physical size of the vdev.
3274 */
3275 vdev_t *
3276 grow_vdev(vdev_t *vd, void *arg)
3277 {
3278 ASSERTV(spa_t *spa = vd->vdev_spa);
3279 size_t *newsize = arg;
3280 size_t fsize;
3281 int fd;
3282
3283 ASSERT(spa_config_held(spa, SCL_STATE, RW_READER) == SCL_STATE);
3284 ASSERT(vd->vdev_ops->vdev_op_leaf);
3285
3286 if ((fd = open(vd->vdev_path, O_RDWR)) == -1)
3287 return (vd);
3288
3289 fsize = lseek(fd, 0, SEEK_END);
3290 VERIFY(ftruncate(fd, *newsize) == 0);
3291
3292 if (ztest_opts.zo_verbose >= 6) {
3293 (void) printf("%s grew from %lu to %lu bytes\n",
3294 vd->vdev_path, (ulong_t)fsize, (ulong_t)*newsize);
3295 }
3296 (void) close(fd);
3297 return (NULL);
3298 }
3299
3300 /*
3301 * Callback function which expands a given vdev by calling vdev_online().
3302 */
3303 /* ARGSUSED */
3304 vdev_t *
3305 online_vdev(vdev_t *vd, void *arg)
3306 {
3307 spa_t *spa = vd->vdev_spa;
3308 vdev_t *tvd = vd->vdev_top;
3309 uint64_t guid = vd->vdev_guid;
3310 uint64_t generation = spa->spa_config_generation + 1;
3311 vdev_state_t newstate = VDEV_STATE_UNKNOWN;
3312 int error;
3313
3314 ASSERT(spa_config_held(spa, SCL_STATE, RW_READER) == SCL_STATE);
3315 ASSERT(vd->vdev_ops->vdev_op_leaf);
3316
3317 /* Calling vdev_online will initialize the new metaslabs */
3318 spa_config_exit(spa, SCL_STATE, spa);
3319 error = vdev_online(spa, guid, ZFS_ONLINE_EXPAND, &newstate);
3320 spa_config_enter(spa, SCL_STATE, spa, RW_READER);
3321
3322 /*
3323 * If vdev_online returned an error or the underlying vdev_open
3324 * failed then we abort the expand. The only way to know that
3325 * vdev_open fails is by checking the returned newstate.
3326 */
3327 if (error || newstate != VDEV_STATE_HEALTHY) {
3328 if (ztest_opts.zo_verbose >= 5) {
3329 (void) printf("Unable to expand vdev, state %llu, "
3330 "error %d\n", (u_longlong_t)newstate, error);
3331 }
3332 return (vd);
3333 }
3334 ASSERT3U(newstate, ==, VDEV_STATE_HEALTHY);
3335
3336 /*
3337 * Since we dropped the lock we need to ensure that we're
3338 * still talking to the original vdev. It's possible this
3339 * vdev may have been detached/replaced while we were
3340 * trying to online it.
3341 */
3342 if (generation != spa->spa_config_generation) {
3343 if (ztest_opts.zo_verbose >= 5) {
3344 (void) printf("vdev configuration has changed, "
3345 "guid %llu, state %llu, expected gen %llu, "
3346 "got gen %llu\n",
3347 (u_longlong_t)guid,
3348 (u_longlong_t)tvd->vdev_state,
3349 (u_longlong_t)generation,
3350 (u_longlong_t)spa->spa_config_generation);
3351 }
3352 return (vd);
3353 }
3354 return (NULL);
3355 }
3356
3357 /*
3358 * Traverse the vdev tree calling the supplied function.
3359 * We continue to walk the tree until we either have walked all
3360 * children or we receive a non-NULL return from the callback.
3361 * If a NULL callback is passed, then we just return back the first
3362 * leaf vdev we encounter.
3363 */
3364 vdev_t *
3365 vdev_walk_tree(vdev_t *vd, vdev_t *(*func)(vdev_t *, void *), void *arg)
3366 {
3367 uint_t c;
3368
3369 if (vd->vdev_ops->vdev_op_leaf) {
3370 if (func == NULL)
3371 return (vd);
3372 else
3373 return (func(vd, arg));
3374 }
3375
3376 for (c = 0; c < vd->vdev_children; c++) {
3377 vdev_t *cvd = vd->vdev_child[c];
3378 if ((cvd = vdev_walk_tree(cvd, func, arg)) != NULL)
3379 return (cvd);
3380 }
3381 return (NULL);
3382 }
3383
3384 /*
3385 * Verify that dynamic LUN growth works as expected.
3386 */
3387 /* ARGSUSED */
3388 void
3389 ztest_vdev_LUN_growth(ztest_ds_t *zd, uint64_t id)
3390 {
3391 spa_t *spa = ztest_spa;
3392 vdev_t *vd, *tvd;
3393 metaslab_class_t *mc;
3394 metaslab_group_t *mg;
3395 size_t psize, newsize;
3396 uint64_t top;
3397 uint64_t old_class_space, new_class_space, old_ms_count, new_ms_count;
3398
3399 mutex_enter(&ztest_vdev_lock);
3400 spa_config_enter(spa, SCL_STATE, spa, RW_READER);
3401
3402 top = ztest_random_vdev_top(spa, B_TRUE);
3403
3404 tvd = spa->spa_root_vdev->vdev_child[top];
3405 mg = tvd->vdev_mg;
3406 mc = mg->mg_class;
3407 old_ms_count = tvd->vdev_ms_count;
3408 old_class_space = metaslab_class_get_space(mc);
3409
3410 /*
3411 * Determine the size of the first leaf vdev associated with
3412 * our top-level device.
3413 */
3414 vd = vdev_walk_tree(tvd, NULL, NULL);
3415 ASSERT3P(vd, !=, NULL);
3416 ASSERT(vd->vdev_ops->vdev_op_leaf);
3417
3418 psize = vd->vdev_psize;
3419
3420 /*
3421 * We only try to expand the vdev if it's healthy, less than 4x its
3422 * original size, and it has a valid psize.
3423 */
3424 if (tvd->vdev_state != VDEV_STATE_HEALTHY ||
3425 psize == 0 || psize >= 4 * ztest_opts.zo_vdev_size) {
3426 spa_config_exit(spa, SCL_STATE, spa);
3427 mutex_exit(&ztest_vdev_lock);
3428 return;
3429 }
3430 ASSERT(psize > 0);
3431 newsize = psize + psize / 8;
3432 ASSERT3U(newsize, >, psize);
3433
3434 if (ztest_opts.zo_verbose >= 6) {
3435 (void) printf("Expanding LUN %s from %lu to %lu\n",
3436 vd->vdev_path, (ulong_t)psize, (ulong_t)newsize);
3437 }
3438
3439 /*
3440 * Growing the vdev is a two step process:
3441 * 1). expand the physical size (i.e. relabel)
3442 * 2). online the vdev to create the new metaslabs
3443 */
3444 if (vdev_walk_tree(tvd, grow_vdev, &newsize) != NULL ||
3445 vdev_walk_tree(tvd, online_vdev, NULL) != NULL ||
3446 tvd->vdev_state != VDEV_STATE_HEALTHY) {
3447 if (ztest_opts.zo_verbose >= 5) {
3448 (void) printf("Could not expand LUN because "
3449 "the vdev configuration changed.\n");
3450 }
3451 spa_config_exit(spa, SCL_STATE, spa);
3452 mutex_exit(&ztest_vdev_lock);
3453 return;
3454 }
3455
3456 spa_config_exit(spa, SCL_STATE, spa);
3457
3458 /*
3459 * Expanding the LUN will update the config asynchronously,
3460 * thus we must wait for the async thread to complete any
3461 * pending tasks before proceeding.
3462 */
3463 for (;;) {
3464 boolean_t done;
3465 mutex_enter(&spa->spa_async_lock);
3466 done = (spa->spa_async_thread == NULL && !spa->spa_async_tasks);
3467 mutex_exit(&spa->spa_async_lock);
3468 if (done)
3469 break;
3470 txg_wait_synced(spa_get_dsl(spa), 0);
3471 (void) poll(NULL, 0, 100);
3472 }
3473
3474 spa_config_enter(spa, SCL_STATE, spa, RW_READER);
3475
3476 tvd = spa->spa_root_vdev->vdev_child[top];
3477 new_ms_count = tvd->vdev_ms_count;
3478 new_class_space = metaslab_class_get_space(mc);
3479
3480 if (tvd->vdev_mg != mg || mg->mg_class != mc) {
3481 if (ztest_opts.zo_verbose >= 5) {
3482 (void) printf("Could not verify LUN expansion due to "
3483 "intervening vdev offline or remove.\n");
3484 }
3485 spa_config_exit(spa, SCL_STATE, spa);
3486 mutex_exit(&ztest_vdev_lock);
3487 return;
3488 }
3489
3490 /*
3491 * Make sure we were able to grow the vdev.
3492 */
3493 if (new_ms_count <= old_ms_count)
3494 fatal(0, "LUN expansion failed: ms_count %llu <= %llu\n",
3495 old_ms_count, new_ms_count);
3496
3497 /*
3498 * Make sure we were able to grow the pool.
3499 */
3500 if (new_class_space <= old_class_space)
3501 fatal(0, "LUN expansion failed: class_space %llu <= %llu\n",
3502 old_class_space, new_class_space);
3503
3504 if (ztest_opts.zo_verbose >= 5) {
3505 char oldnumbuf[6], newnumbuf[6];
3506
3507 nicenum(old_class_space, oldnumbuf);
3508 nicenum(new_class_space, newnumbuf);
3509 (void) printf("%s grew from %s to %s\n",
3510 spa->spa_name, oldnumbuf, newnumbuf);
3511 }
3512
3513 spa_config_exit(spa, SCL_STATE, spa);
3514 mutex_exit(&ztest_vdev_lock);
3515 }
3516
3517 /*
3518 * Verify that dmu_objset_{create,destroy,open,close} work as expected.
3519 */
3520 /* ARGSUSED */
3521 static void
3522 ztest_objset_create_cb(objset_t *os, void *arg, cred_t *cr, dmu_tx_t *tx)
3523 {
3524 /*
3525 * Create the objects common to all ztest datasets.
3526 */
3527 VERIFY(zap_create_claim(os, ZTEST_DIROBJ,
3528 DMU_OT_ZAP_OTHER, DMU_OT_NONE, 0, tx) == 0);
3529 }
3530
3531 static int
3532 ztest_dataset_create(char *dsname)
3533 {
3534 uint64_t zilset = ztest_random(100);
3535 int err = dmu_objset_create(dsname, DMU_OST_OTHER, 0,
3536 ztest_objset_create_cb, NULL);
3537
3538 if (err || zilset < 80)
3539 return (err);
3540
3541 if (ztest_opts.zo_verbose >= 5)
3542 (void) printf("Setting dataset %s to sync always\n", dsname);
3543 return (ztest_dsl_prop_set_uint64(dsname, ZFS_PROP_SYNC,
3544 ZFS_SYNC_ALWAYS, B_FALSE));
3545 }
3546
3547 /* ARGSUSED */
3548 static int
3549 ztest_objset_destroy_cb(const char *name, void *arg)
3550 {
3551 objset_t *os;
3552 dmu_object_info_t doi;
3553 int error;
3554
3555 /*
3556 * Verify that the dataset contains a directory object.
3557 */
3558 VERIFY0(dmu_objset_own(name, DMU_OST_OTHER, B_TRUE, FTAG, &os));
3559 error = dmu_object_info(os, ZTEST_DIROBJ, &doi);
3560 if (error != ENOENT) {
3561 /* We could have crashed in the middle of destroying it */
3562 ASSERT0(error);
3563 ASSERT3U(doi.doi_type, ==, DMU_OT_ZAP_OTHER);
3564 ASSERT3S(doi.doi_physical_blocks_512, >=, 0);
3565 }
3566 dmu_objset_disown(os, FTAG);
3567
3568 /*
3569 * Destroy the dataset.
3570 */
3571 if (strchr(name, '@') != NULL) {
3572 VERIFY0(dsl_destroy_snapshot(name, B_TRUE));
3573 } else {
3574 error = dsl_destroy_head(name);
3575 /* There could be a hold on this dataset */
3576 if (error != EBUSY)
3577 ASSERT0(error);
3578 }
3579 return (0);
3580 }
3581
3582 static boolean_t
3583 ztest_snapshot_create(char *osname, uint64_t id)
3584 {
3585 char snapname[ZFS_MAX_DATASET_NAME_LEN];
3586 int error;
3587
3588 (void) snprintf(snapname, sizeof (snapname), "%llu", (u_longlong_t)id);
3589
3590 error = dmu_objset_snapshot_one(osname, snapname);
3591 if (error == ENOSPC) {
3592 ztest_record_enospc(FTAG);
3593 return (B_FALSE);
3594 }
3595 if (error != 0 && error != EEXIST) {
3596 fatal(0, "ztest_snapshot_create(%s@%s) = %d", osname,
3597 snapname, error);
3598 }
3599 return (B_TRUE);
3600 }
3601
3602 static boolean_t
3603 ztest_snapshot_destroy(char *osname, uint64_t id)
3604 {
3605 char snapname[ZFS_MAX_DATASET_NAME_LEN];
3606 int error;
3607
3608 (void) snprintf(snapname, sizeof (snapname), "%s@%llu", osname,
3609 (u_longlong_t)id);
3610
3611 error = dsl_destroy_snapshot(snapname, B_FALSE);
3612 if (error != 0 && error != ENOENT)
3613 fatal(0, "ztest_snapshot_destroy(%s) = %d", snapname, error);
3614 return (B_TRUE);
3615 }
3616
3617 /* ARGSUSED */
3618 void
3619 ztest_dmu_objset_create_destroy(ztest_ds_t *zd, uint64_t id)
3620 {
3621 ztest_ds_t *zdtmp;
3622 int iters;
3623 int error;
3624 objset_t *os, *os2;
3625 char name[ZFS_MAX_DATASET_NAME_LEN];
3626 zilog_t *zilog;
3627 int i;
3628
3629 zdtmp = umem_alloc(sizeof (ztest_ds_t), UMEM_NOFAIL);
3630
3631 (void) rw_rdlock(&ztest_name_lock);
3632
3633 (void) snprintf(name, sizeof (name), "%s/temp_%llu",
3634 ztest_opts.zo_pool, (u_longlong_t)id);
3635
3636 /*
3637 * If this dataset exists from a previous run, process its replay log
3638 * half of the time. If we don't replay it, then dsl_destroy_head()
3639 * (invoked from ztest_objset_destroy_cb()) should just throw it away.
3640 */
3641 if (ztest_random(2) == 0 &&
3642 dmu_objset_own(name, DMU_OST_OTHER, B_FALSE, FTAG, &os) == 0) {
3643 ztest_zd_init(zdtmp, NULL, os);
3644 zil_replay(os, zdtmp, ztest_replay_vector);
3645 ztest_zd_fini(zdtmp);
3646 dmu_objset_disown(os, FTAG);
3647 }
3648
3649 /*
3650 * There may be an old instance of the dataset we're about to
3651 * create lying around from a previous run. If so, destroy it
3652 * and all of its snapshots.
3653 */
3654 (void) dmu_objset_find(name, ztest_objset_destroy_cb, NULL,
3655 DS_FIND_CHILDREN | DS_FIND_SNAPSHOTS);
3656
3657 /*
3658 * Verify that the destroyed dataset is no longer in the namespace.
3659 */
3660 VERIFY3U(ENOENT, ==, dmu_objset_own(name, DMU_OST_OTHER, B_TRUE,
3661 FTAG, &os));
3662
3663 /*
3664 * Verify that we can create a new dataset.
3665 */
3666 error = ztest_dataset_create(name);
3667 if (error) {
3668 if (error == ENOSPC) {
3669 ztest_record_enospc(FTAG);
3670 goto out;
3671 }
3672 fatal(0, "dmu_objset_create(%s) = %d", name, error);
3673 }
3674
3675 VERIFY0(dmu_objset_own(name, DMU_OST_OTHER, B_FALSE, FTAG, &os));
3676
3677 ztest_zd_init(zdtmp, NULL, os);
3678
3679 /*
3680 * Open the intent log for it.
3681 */
3682 zilog = zil_open(os, ztest_get_data);
3683
3684 /*
3685 * Put some objects in there, do a little I/O to them,
3686 * and randomly take a couple of snapshots along the way.
3687 */
3688 iters = ztest_random(5);
3689 for (i = 0; i < iters; i++) {
3690 ztest_dmu_object_alloc_free(zdtmp, id);
3691 if (ztest_random(iters) == 0)
3692 (void) ztest_snapshot_create(name, i);
3693 }
3694
3695 /*
3696 * Verify that we cannot create an existing dataset.
3697 */
3698 VERIFY3U(EEXIST, ==,
3699 dmu_objset_create(name, DMU_OST_OTHER, 0, NULL, NULL));
3700
3701 /*
3702 * Verify that we can hold an objset that is also owned.
3703 */
3704 VERIFY3U(0, ==, dmu_objset_hold(name, FTAG, &os2));
3705 dmu_objset_rele(os2, FTAG);
3706
3707 /*
3708 * Verify that we cannot own an objset that is already owned.
3709 */
3710 VERIFY3U(EBUSY, ==,
3711 dmu_objset_own(name, DMU_OST_OTHER, B_FALSE, FTAG, &os2));
3712
3713 zil_close(zilog);
3714 dmu_objset_disown(os, FTAG);
3715 ztest_zd_fini(zdtmp);
3716 out:
3717 (void) rw_unlock(&ztest_name_lock);
3718
3719 umem_free(zdtmp, sizeof (ztest_ds_t));
3720 }
3721
3722 /*
3723 * Verify that dmu_snapshot_{create,destroy,open,close} work as expected.
3724 */
3725 void
3726 ztest_dmu_snapshot_create_destroy(ztest_ds_t *zd, uint64_t id)
3727 {
3728 (void) rw_rdlock(&ztest_name_lock);
3729 (void) ztest_snapshot_destroy(zd->zd_name, id);
3730 (void) ztest_snapshot_create(zd->zd_name, id);
3731 (void) rw_unlock(&ztest_name_lock);
3732 }
3733
3734 /*
3735 * Cleanup non-standard snapshots and clones.
3736 */
3737 void
3738 ztest_dsl_dataset_cleanup(char *osname, uint64_t id)
3739 {
3740 char *snap1name;
3741 char *clone1name;
3742 char *snap2name;
3743 char *clone2name;
3744 char *snap3name;
3745 int error;
3746
3747 snap1name = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
3748 clone1name = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
3749 snap2name = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
3750 clone2name = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
3751 snap3name = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
3752
3753 (void) snprintf(snap1name, ZFS_MAX_DATASET_NAME_LEN,
3754 "%s@s1_%llu", osname, (u_longlong_t)id);
3755 (void) snprintf(clone1name, ZFS_MAX_DATASET_NAME_LEN,
3756 "%s/c1_%llu", osname, (u_longlong_t)id);
3757 (void) snprintf(snap2name, ZFS_MAX_DATASET_NAME_LEN,
3758 "%s@s2_%llu", clone1name, (u_longlong_t)id);
3759 (void) snprintf(clone2name, ZFS_MAX_DATASET_NAME_LEN,
3760 "%s/c2_%llu", osname, (u_longlong_t)id);
3761 (void) snprintf(snap3name, ZFS_MAX_DATASET_NAME_LEN,
3762 "%s@s3_%llu", clone1name, (u_longlong_t)id);
3763
3764 error = dsl_destroy_head(clone2name);
3765 if (error && error != ENOENT)
3766 fatal(0, "dsl_destroy_head(%s) = %d", clone2name, error);
3767 error = dsl_destroy_snapshot(snap3name, B_FALSE);
3768 if (error && error != ENOENT)
3769 fatal(0, "dsl_destroy_snapshot(%s) = %d", snap3name, error);
3770 error = dsl_destroy_snapshot(snap2name, B_FALSE);
3771 if (error && error != ENOENT)
3772 fatal(0, "dsl_destroy_snapshot(%s) = %d", snap2name, error);
3773 error = dsl_destroy_head(clone1name);
3774 if (error && error != ENOENT)
3775 fatal(0, "dsl_destroy_head(%s) = %d", clone1name, error);
3776 error = dsl_destroy_snapshot(snap1name, B_FALSE);
3777 if (error && error != ENOENT)
3778 fatal(0, "dsl_destroy_snapshot(%s) = %d", snap1name, error);
3779
3780 umem_free(snap1name, ZFS_MAX_DATASET_NAME_LEN);
3781 umem_free(clone1name, ZFS_MAX_DATASET_NAME_LEN);
3782 umem_free(snap2name, ZFS_MAX_DATASET_NAME_LEN);
3783 umem_free(clone2name, ZFS_MAX_DATASET_NAME_LEN);
3784 umem_free(snap3name, ZFS_MAX_DATASET_NAME_LEN);
3785 }
3786
3787 /*
3788 * Verify dsl_dataset_promote handles EBUSY
3789 */
3790 void
3791 ztest_dsl_dataset_promote_busy(ztest_ds_t *zd, uint64_t id)
3792 {
3793 objset_t *os;
3794 char *snap1name;
3795 char *clone1name;
3796 char *snap2name;
3797 char *clone2name;
3798 char *snap3name;
3799 char *osname = zd->zd_name;
3800 int error;
3801
3802 snap1name = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
3803 clone1name = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
3804 snap2name = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
3805 clone2name = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
3806 snap3name = umem_alloc(ZFS_MAX_DATASET_NAME_LEN, UMEM_NOFAIL);
3807
3808 (void) rw_rdlock(&ztest_name_lock);
3809
3810 ztest_dsl_dataset_cleanup(osname, id);
3811
3812 (void) snprintf(snap1name, ZFS_MAX_DATASET_NAME_LEN,
3813 "%s@s1_%llu", osname, (u_longlong_t)id);
3814 (void) snprintf(clone1name, ZFS_MAX_DATASET_NAME_LEN,
3815 "%s/c1_%llu", osname, (u_longlong_t)id);
3816 (void) snprintf(snap2name, ZFS_MAX_DATASET_NAME_LEN,
3817 "%s@s2_%llu", clone1name, (u_longlong_t)id);
3818 (void) snprintf(clone2name, ZFS_MAX_DATASET_NAME_LEN,
3819 "%s/c2_%llu", osname, (u_longlong_t)id);
3820 (void) snprintf(snap3name, ZFS_MAX_DATASET_NAME_LEN,
3821 "%s@s3_%llu", clone1name, (u_longlong_t)id);
3822
3823 error = dmu_objset_snapshot_one(osname, strchr(snap1name, '@') + 1);
3824 if (error && error != EEXIST) {
3825 if (error == ENOSPC) {
3826 ztest_record_enospc(FTAG);
3827 goto out;
3828 }
3829 fatal(0, "dmu_take_snapshot(%s) = %d", snap1name, error);
3830 }
3831
3832 error = dmu_objset_clone(clone1name, snap1name);
3833 if (error) {
3834 if (error == ENOSPC) {
3835 ztest_record_enospc(FTAG);
3836 goto out;
3837 }
3838 fatal(0, "dmu_objset_create(%s) = %d", clone1name, error);
3839 }
3840
3841 error = dmu_objset_snapshot_one(clone1name, strchr(snap2name, '@') + 1);
3842 if (error && error != EEXIST) {
3843 if (error == ENOSPC) {
3844 ztest_record_enospc(FTAG);
3845 goto out;
3846 }
3847 fatal(0, "dmu_open_snapshot(%s) = %d", snap2name, error);
3848 }
3849
3850 error = dmu_objset_snapshot_one(clone1name, strchr(snap3name, '@') + 1);
3851 if (error && error != EEXIST) {
3852 if (error == ENOSPC) {
3853 ztest_record_enospc(FTAG);
3854 goto out;
3855 }
3856 fatal(0, "dmu_open_snapshot(%s) = %d", snap3name, error);
3857 }
3858
3859 error = dmu_objset_clone(clone2name, snap3name);
3860 if (error) {
3861 if (error == ENOSPC) {
3862 ztest_record_enospc(FTAG);
3863 goto out;
3864 }
3865 fatal(0, "dmu_objset_create(%s) = %d", clone2name, error);
3866 }
3867
3868 error = dmu_objset_own(snap2name, DMU_OST_ANY, B_TRUE, FTAG, &os);
3869 if (error)
3870 fatal(0, "dmu_objset_own(%s) = %d", snap2name, error);
3871 error = dsl_dataset_promote(clone2name, NULL);
3872 if (error == ENOSPC) {
3873 dmu_objset_disown(os, FTAG);
3874 ztest_record_enospc(FTAG);
3875 goto out;
3876 }
3877 if (error != EBUSY)
3878 fatal(0, "dsl_dataset_promote(%s), %d, not EBUSY", clone2name,
3879 error);
3880 dmu_objset_disown(os, FTAG);
3881
3882 out:
3883 ztest_dsl_dataset_cleanup(osname, id);
3884
3885 (void) rw_unlock(&ztest_name_lock);
3886
3887 umem_free(snap1name, ZFS_MAX_DATASET_NAME_LEN);
3888 umem_free(clone1name, ZFS_MAX_DATASET_NAME_LEN);
3889 umem_free(snap2name, ZFS_MAX_DATASET_NAME_LEN);
3890 umem_free(clone2name, ZFS_MAX_DATASET_NAME_LEN);
3891 umem_free(snap3name, ZFS_MAX_DATASET_NAME_LEN);
3892 }
3893
3894 #undef OD_ARRAY_SIZE
3895 #define OD_ARRAY_SIZE 4
3896
3897 /*
3898 * Verify that dmu_object_{alloc,free} work as expected.
3899 */
3900 void
3901 ztest_dmu_object_alloc_free(ztest_ds_t *zd, uint64_t id)
3902 {
3903 ztest_od_t *od;
3904 int batchsize;
3905 int size;
3906 int b;
3907
3908 size = sizeof (ztest_od_t) * OD_ARRAY_SIZE;
3909 od = umem_alloc(size, UMEM_NOFAIL);
3910 batchsize = OD_ARRAY_SIZE;
3911
3912 for (b = 0; b < batchsize; b++)
3913 ztest_od_init(od + b, id, FTAG, b, DMU_OT_UINT64_OTHER,
3914 0, 0, 0);
3915
3916 /*
3917 * Destroy the previous batch of objects, create a new batch,
3918 * and do some I/O on the new objects.
3919 */
3920 if (ztest_object_init(zd, od, size, B_TRUE) != 0)
3921 return;
3922
3923 while (ztest_random(4 * batchsize) != 0)
3924 ztest_io(zd, od[ztest_random(batchsize)].od_object,
3925 ztest_random(ZTEST_RANGE_LOCKS) << SPA_MAXBLOCKSHIFT);
3926
3927 umem_free(od, size);
3928 }
3929
3930 #undef OD_ARRAY_SIZE
3931 #define OD_ARRAY_SIZE 2
3932
3933 /*
3934 * Verify that dmu_{read,write} work as expected.
3935 */
3936 void
3937 ztest_dmu_read_write(ztest_ds_t *zd, uint64_t id)
3938 {
3939 int size;
3940 ztest_od_t *od;
3941
3942 objset_t *os = zd->zd_os;
3943 size = sizeof (ztest_od_t) * OD_ARRAY_SIZE;
3944 od = umem_alloc(size, UMEM_NOFAIL);
3945 dmu_tx_t *tx;
3946 int i, freeit, error;
3947 uint64_t n, s, txg;
3948 bufwad_t *packbuf, *bigbuf, *pack, *bigH, *bigT;
3949 uint64_t packobj, packoff, packsize, bigobj, bigoff, bigsize;
3950 uint64_t chunksize = (1000 + ztest_random(1000)) * sizeof (uint64_t);
3951 uint64_t regions = 997;
3952 uint64_t stride = 123456789ULL;
3953 uint64_t width = 40;
3954 int free_percent = 5;
3955
3956 /*
3957 * This test uses two objects, packobj and bigobj, that are always
3958 * updated together (i.e. in the same tx) so that their contents are
3959 * in sync and can be compared. Their contents relate to each other
3960 * in a simple way: packobj is a dense array of 'bufwad' structures,
3961 * while bigobj is a sparse array of the same bufwads. Specifically,
3962 * for any index n, there are three bufwads that should be identical:
3963 *
3964 * packobj, at offset n * sizeof (bufwad_t)
3965 * bigobj, at the head of the nth chunk
3966 * bigobj, at the tail of the nth chunk
3967 *
3968 * The chunk size is arbitrary. It doesn't have to be a power of two,
3969 * and it doesn't have any relation to the object blocksize.
3970 * The only requirement is that it can hold at least two bufwads.
3971 *
3972 * Normally, we write the bufwad to each of these locations.
3973 * However, free_percent of the time we instead write zeroes to
3974 * packobj and perform a dmu_free_range() on bigobj. By comparing
3975 * bigobj to packobj, we can verify that the DMU is correctly
3976 * tracking which parts of an object are allocated and free,
3977 * and that the contents of the allocated blocks are correct.
3978 */
3979
3980 /*
3981 * Read the directory info. If it's the first time, set things up.
3982 */
3983 ztest_od_init(od, id, FTAG, 0, DMU_OT_UINT64_OTHER, 0, 0, chunksize);
3984 ztest_od_init(od + 1, id, FTAG, 1, DMU_OT_UINT64_OTHER, 0, 0,
3985 chunksize);
3986
3987 if (ztest_object_init(zd, od, size, B_FALSE) != 0) {
3988 umem_free(od, size);
3989 return;
3990 }
3991
3992 bigobj = od[0].od_object;
3993 packobj = od[1].od_object;
3994 chunksize = od[0].od_gen;
3995 ASSERT(chunksize == od[1].od_gen);
3996
3997 /*
3998 * Prefetch a random chunk of the big object.
3999 * Our aim here is to get some async reads in flight
4000 * for blocks that we may free below; the DMU should
4001 * handle this race correctly.
4002 */
4003 n = ztest_random(regions) * stride + ztest_random(width);
4004 s = 1 + ztest_random(2 * width - 1);
4005 dmu_prefetch(os, bigobj, 0, n * chunksize, s * chunksize,
4006 ZIO_PRIORITY_SYNC_READ);
4007
4008 /*
4009 * Pick a random index and compute the offsets into packobj and bigobj.
4010 */
4011 n = ztest_random(regions) * stride + ztest_random(width);
4012 s = 1 + ztest_random(width - 1);
4013
4014 packoff = n * sizeof (bufwad_t);
4015 packsize = s * sizeof (bufwad_t);
4016
4017 bigoff = n * chunksize;
4018 bigsize = s * chunksize;
4019
4020 packbuf = umem_alloc(packsize, UMEM_NOFAIL);
4021 bigbuf = umem_alloc(bigsize, UMEM_NOFAIL);
4022
4023 /*
4024 * free_percent of the time, free a range of bigobj rather than
4025 * overwriting it.
4026 */
4027 freeit = (ztest_random(100) < free_percent);
4028
4029 /*
4030 * Read the current contents of our objects.
4031 */
4032 error = dmu_read(os, packobj, packoff, packsize, packbuf,
4033 DMU_READ_PREFETCH);
4034 ASSERT0(error);
4035 error = dmu_read(os, bigobj, bigoff, bigsize, bigbuf,
4036 DMU_READ_PREFETCH);
4037 ASSERT0(error);
4038
4039 /*
4040 * Get a tx for the mods to both packobj and bigobj.
4041 */
4042 tx = dmu_tx_create(os);
4043
4044 dmu_tx_hold_write(tx, packobj, packoff, packsize);
4045
4046 if (freeit)
4047 dmu_tx_hold_free(tx, bigobj, bigoff, bigsize);
4048 else
4049 dmu_tx_hold_write(tx, bigobj, bigoff, bigsize);
4050
4051 /* This accounts for setting the checksum/compression. */
4052 dmu_tx_hold_bonus(tx, bigobj);
4053
4054 txg = ztest_tx_assign(tx, TXG_MIGHTWAIT, FTAG);
4055 if (txg == 0) {
4056 umem_free(packbuf, packsize);
4057 umem_free(bigbuf, bigsize);
4058 umem_free(od, size);
4059 return;
4060 }
4061
4062 enum zio_checksum cksum;
4063 do {
4064 cksum = (enum zio_checksum)
4065 ztest_random_dsl_prop(ZFS_PROP_CHECKSUM);
4066 } while (cksum >= ZIO_CHECKSUM_LEGACY_FUNCTIONS);
4067 dmu_object_set_checksum(os, bigobj, cksum, tx);
4068
4069 enum zio_compress comp;
4070 do {
4071 comp = (enum zio_compress)
4072 ztest_random_dsl_prop(ZFS_PROP_COMPRESSION);
4073 } while (comp >= ZIO_COMPRESS_LEGACY_FUNCTIONS);
4074 dmu_object_set_compress(os, bigobj, comp, tx);
4075
4076 /*
4077 * For each index from n to n + s, verify that the existing bufwad
4078 * in packobj matches the bufwads at the head and tail of the
4079 * corresponding chunk in bigobj. Then update all three bufwads
4080 * with the new values we want to write out.
4081 */
4082 for (i = 0; i < s; i++) {
4083 /* LINTED */
4084 pack = (bufwad_t *)((char *)packbuf + i * sizeof (bufwad_t));
4085 /* LINTED */
4086 bigH = (bufwad_t *)((char *)bigbuf + i * chunksize);
4087 /* LINTED */
4088 bigT = (bufwad_t *)((char *)bigH + chunksize) - 1;
4089
4090 ASSERT((uintptr_t)bigH - (uintptr_t)bigbuf < bigsize);
4091 ASSERT((uintptr_t)bigT - (uintptr_t)bigbuf < bigsize);
4092
4093 if (pack->bw_txg > txg)
4094 fatal(0, "future leak: got %llx, open txg is %llx",
4095 pack->bw_txg, txg);
4096
4097 if (pack->bw_data != 0 && pack->bw_index != n + i)
4098 fatal(0, "wrong index: got %llx, wanted %llx+%llx",
4099 pack->bw_index, n, i);
4100
4101 if (bcmp(pack, bigH, sizeof (bufwad_t)) != 0)
4102 fatal(0, "pack/bigH mismatch in %p/%p", pack, bigH);
4103
4104 if (bcmp(pack, bigT, sizeof (bufwad_t)) != 0)
4105 fatal(0, "pack/bigT mismatch in %p/%p", pack, bigT);
4106
4107 if (freeit) {
4108 bzero(pack, sizeof (bufwad_t));
4109 } else {
4110 pack->bw_index = n + i;
4111 pack->bw_txg = txg;
4112 pack->bw_data = 1 + ztest_random(-2ULL);
4113 }
4114 *bigH = *pack;
4115 *bigT = *pack;
4116 }
4117
4118 /*
4119 * We've verified all the old bufwads, and made new ones.
4120 * Now write them out.
4121 */
4122 dmu_write(os, packobj, packoff, packsize, packbuf, tx);
4123
4124 if (freeit) {
4125 if (ztest_opts.zo_verbose >= 7) {
4126 (void) printf("freeing offset %llx size %llx"
4127 " txg %llx\n",
4128 (u_longlong_t)bigoff,
4129 (u_longlong_t)bigsize,
4130 (u_longlong_t)txg);
4131 }
4132 VERIFY(0 == dmu_free_range(os, bigobj, bigoff, bigsize, tx));
4133 } else {
4134 if (ztest_opts.zo_verbose >= 7) {
4135 (void) printf("writing offset %llx size %llx"
4136 " txg %llx\n",
4137 (u_longlong_t)bigoff,
4138 (u_longlong_t)bigsize,
4139 (u_longlong_t)txg);
4140 }
4141 dmu_write(os, bigobj, bigoff, bigsize, bigbuf, tx);
4142 }
4143
4144 dmu_tx_commit(tx);
4145
4146 /*
4147 * Sanity check the stuff we just wrote.
4148 */
4149 {
4150 void *packcheck = umem_alloc(packsize, UMEM_NOFAIL);
4151 void *bigcheck = umem_alloc(bigsize, UMEM_NOFAIL);
4152
4153 VERIFY(0 == dmu_read(os, packobj, packoff,
4154 packsize, packcheck, DMU_READ_PREFETCH));
4155 VERIFY(0 == dmu_read(os, bigobj, bigoff,
4156 bigsize, bigcheck, DMU_READ_PREFETCH));
4157
4158 ASSERT(bcmp(packbuf, packcheck, packsize) == 0);
4159 ASSERT(bcmp(bigbuf, bigcheck, bigsize) == 0);
4160
4161 umem_free(packcheck, packsize);
4162 umem_free(bigcheck, bigsize);
4163 }
4164
4165 umem_free(packbuf, packsize);
4166 umem_free(bigbuf, bigsize);
4167 umem_free(od, size);
4168 }
4169
4170 void
4171 compare_and_update_pbbufs(uint64_t s, bufwad_t *packbuf, bufwad_t *bigbuf,
4172 uint64_t bigsize, uint64_t n, uint64_t chunksize, uint64_t txg)
4173 {
4174 uint64_t i;
4175 bufwad_t *pack;
4176 bufwad_t *bigH;
4177 bufwad_t *bigT;
4178
4179 /*
4180 * For each index from n to n + s, verify that the existing bufwad
4181 * in packobj matches the bufwads at the head and tail of the
4182 * corresponding chunk in bigobj. Then update all three bufwads
4183 * with the new values we want to write out.
4184 */
4185 for (i = 0; i < s; i++) {
4186 /* LINTED */
4187 pack = (bufwad_t *)((char *)packbuf + i * sizeof (bufwad_t));
4188 /* LINTED */
4189 bigH = (bufwad_t *)((char *)bigbuf + i * chunksize);
4190 /* LINTED */
4191 bigT = (bufwad_t *)((char *)bigH + chunksize) - 1;
4192
4193 ASSERT((uintptr_t)bigH - (uintptr_t)bigbuf < bigsize);
4194 ASSERT((uintptr_t)bigT - (uintptr_t)bigbuf < bigsize);
4195
4196 if (pack->bw_txg > txg)
4197 fatal(0, "future leak: got %llx, open txg is %llx",
4198 pack->bw_txg, txg);
4199
4200 if (pack->bw_data != 0 && pack->bw_index != n + i)
4201 fatal(0, "wrong index: got %llx, wanted %llx+%llx",
4202 pack->bw_index, n, i);
4203
4204 if (bcmp(pack, bigH, sizeof (bufwad_t)) != 0)
4205 fatal(0, "pack/bigH mismatch in %p/%p", pack, bigH);
4206
4207 if (bcmp(pack, bigT, sizeof (bufwad_t)) != 0)
4208 fatal(0, "pack/bigT mismatch in %p/%p", pack, bigT);
4209
4210 pack->bw_index = n + i;
4211 pack->bw_txg = txg;
4212 pack->bw_data = 1 + ztest_random(-2ULL);
4213
4214 *bigH = *pack;
4215 *bigT = *pack;
4216 }
4217 }
4218
4219 #undef OD_ARRAY_SIZE
4220 #define OD_ARRAY_SIZE 2
4221
4222 void
4223 ztest_dmu_read_write_zcopy(ztest_ds_t *zd, uint64_t id)
4224 {
4225 objset_t *os = zd->zd_os;
4226 ztest_od_t *od;
4227 dmu_tx_t *tx;
4228 uint64_t i;
4229 int error;
4230 int size;
4231 uint64_t n, s, txg;
4232 bufwad_t *packbuf, *bigbuf;
4233 uint64_t packobj, packoff, packsize, bigobj, bigoff, bigsize;
4234 uint64_t blocksize = ztest_random_blocksize();
4235 uint64_t chunksize = blocksize;
4236 uint64_t regions = 997;
4237 uint64_t stride = 123456789ULL;
4238 uint64_t width = 9;
4239 dmu_buf_t *bonus_db;
4240 arc_buf_t **bigbuf_arcbufs;
4241 dmu_object_info_t doi;
4242
4243 size = sizeof (ztest_od_t) * OD_ARRAY_SIZE;
4244 od = umem_alloc(size, UMEM_NOFAIL);
4245
4246 /*
4247 * This test uses two objects, packobj and bigobj, that are always
4248 * updated together (i.e. in the same tx) so that their contents are
4249 * in sync and can be compared. Their contents relate to each other
4250 * in a simple way: packobj is a dense array of 'bufwad' structures,
4251 * while bigobj is a sparse array of the same bufwads. Specifically,
4252 * for any index n, there are three bufwads that should be identical:
4253 *
4254 * packobj, at offset n * sizeof (bufwad_t)
4255 * bigobj, at the head of the nth chunk
4256 * bigobj, at the tail of the nth chunk
4257 *
4258 * The chunk size is set equal to bigobj block size so that
4259 * dmu_assign_arcbuf() can be tested for object updates.
4260 */
4261
4262 /*
4263 * Read the directory info. If it's the first time, set things up.
4264 */
4265 ztest_od_init(od, id, FTAG, 0, DMU_OT_UINT64_OTHER, blocksize, 0, 0);
4266 ztest_od_init(od + 1, id, FTAG, 1, DMU_OT_UINT64_OTHER, 0, 0,
4267 chunksize);
4268
4269
4270 if (ztest_object_init(zd, od, size, B_FALSE) != 0) {
4271 umem_free(od, size);
4272 return;
4273 }
4274
4275 bigobj = od[0].od_object;
4276 packobj = od[1].od_object;
4277 blocksize = od[0].od_blocksize;
4278 chunksize = blocksize;
4279 ASSERT(chunksize == od[1].od_gen);
4280
4281 VERIFY(dmu_object_info(os, bigobj, &doi) == 0);
4282 VERIFY(ISP2(doi.doi_data_block_size));
4283 VERIFY(chunksize == doi.doi_data_block_size);
4284 VERIFY(chunksize >= 2 * sizeof (bufwad_t));
4285
4286 /*
4287 * Pick a random index and compute the offsets into packobj and bigobj.
4288 */
4289 n = ztest_random(regions) * stride + ztest_random(width);
4290 s = 1 + ztest_random(width - 1);
4291
4292 packoff = n * sizeof (bufwad_t);
4293 packsize = s * sizeof (bufwad_t);
4294
4295 bigoff = n * chunksize;
4296 bigsize = s * chunksize;
4297
4298 packbuf = umem_zalloc(packsize, UMEM_NOFAIL);
4299 bigbuf = umem_zalloc(bigsize, UMEM_NOFAIL);
4300
4301 VERIFY3U(0, ==, dmu_bonus_hold(os, bigobj, FTAG, &bonus_db));
4302
4303 bigbuf_arcbufs = umem_zalloc(2 * s * sizeof (arc_buf_t *), UMEM_NOFAIL);
4304
4305 /*
4306 * Iteration 0 test zcopy for DB_UNCACHED dbufs.
4307 * Iteration 1 test zcopy to already referenced dbufs.
4308 * Iteration 2 test zcopy to dirty dbuf in the same txg.
4309 * Iteration 3 test zcopy to dbuf dirty in previous txg.
4310 * Iteration 4 test zcopy when dbuf is no longer dirty.
4311 * Iteration 5 test zcopy when it can't be done.
4312 * Iteration 6 one more zcopy write.
4313 */
4314 for (i = 0; i < 7; i++) {
4315 uint64_t j;
4316 uint64_t off;
4317
4318 /*
4319 * In iteration 5 (i == 5) use arcbufs
4320 * that don't match bigobj blksz to test
4321 * dmu_assign_arcbuf() when it can't directly
4322 * assign an arcbuf to a dbuf.
4323 */
4324 for (j = 0; j < s; j++) {
4325 if (i != 5 || chunksize < (SPA_MINBLOCKSIZE * 2)) {
4326 bigbuf_arcbufs[j] =
4327 dmu_request_arcbuf(bonus_db, chunksize);
4328 } else {
4329 bigbuf_arcbufs[2 * j] =
4330 dmu_request_arcbuf(bonus_db, chunksize / 2);
4331 bigbuf_arcbufs[2 * j + 1] =
4332 dmu_request_arcbuf(bonus_db, chunksize / 2);
4333 }
4334 }
4335
4336 /*
4337 * Get a tx for the mods to both packobj and bigobj.
4338 */
4339 tx = dmu_tx_create(os);
4340
4341 dmu_tx_hold_write(tx, packobj, packoff, packsize);
4342 dmu_tx_hold_write(tx, bigobj, bigoff, bigsize);
4343
4344 txg = ztest_tx_assign(tx, TXG_MIGHTWAIT, FTAG);
4345 if (txg == 0) {
4346 umem_free(packbuf, packsize);
4347 umem_free(bigbuf, bigsize);
4348 for (j = 0; j < s; j++) {
4349 if (i != 5 ||
4350 chunksize < (SPA_MINBLOCKSIZE * 2)) {
4351 dmu_return_arcbuf(bigbuf_arcbufs[j]);
4352 } else {
4353 dmu_return_arcbuf(
4354 bigbuf_arcbufs[2 * j]);
4355 dmu_return_arcbuf(
4356 bigbuf_arcbufs[2 * j + 1]);
4357 }
4358 }
4359 umem_free(bigbuf_arcbufs, 2 * s * sizeof (arc_buf_t *));
4360 umem_free(od, size);
4361 dmu_buf_rele(bonus_db, FTAG);
4362 return;
4363 }
4364
4365 /*
4366 * 50% of the time don't read objects in the 1st iteration to
4367 * test dmu_assign_arcbuf() for the case when there're no
4368 * existing dbufs for the specified offsets.
4369 */
4370 if (i != 0 || ztest_random(2) != 0) {
4371 error = dmu_read(os, packobj, packoff,
4372 packsize, packbuf, DMU_READ_PREFETCH);
4373 ASSERT0(error);
4374 error = dmu_read(os, bigobj, bigoff, bigsize,
4375 bigbuf, DMU_READ_PREFETCH);
4376 ASSERT0(error);
4377 }
4378 compare_and_update_pbbufs(s, packbuf, bigbuf, bigsize,
4379 n, chunksize, txg);
4380
4381 /*
4382 * We've verified all the old bufwads, and made new ones.
4383 * Now write them out.
4384 */
4385 dmu_write(os, packobj, packoff, packsize, packbuf, tx);
4386 if (ztest_opts.zo_verbose >= 7) {
4387 (void) printf("writing offset %llx size %llx"
4388 " txg %llx\n",
4389 (u_longlong_t)bigoff,
4390 (u_longlong_t)bigsize,
4391 (u_longlong_t)txg);
4392 }
4393 for (off = bigoff, j = 0; j < s; j++, off += chunksize) {
4394 dmu_buf_t *dbt;
4395 if (i != 5 || chunksize < (SPA_MINBLOCKSIZE * 2)) {
4396 bcopy((caddr_t)bigbuf + (off - bigoff),
4397 bigbuf_arcbufs[j]->b_data, chunksize);
4398 } else {
4399 bcopy((caddr_t)bigbuf + (off - bigoff),
4400 bigbuf_arcbufs[2 * j]->b_data,
4401 chunksize / 2);
4402 bcopy((caddr_t)bigbuf + (off - bigoff) +
4403 chunksize / 2,
4404 bigbuf_arcbufs[2 * j + 1]->b_data,
4405 chunksize / 2);
4406 }
4407
4408 if (i == 1) {
4409 VERIFY(dmu_buf_hold(os, bigobj, off,
4410 FTAG, &dbt, DMU_READ_NO_PREFETCH) == 0);
4411 }
4412 if (i != 5 || chunksize < (SPA_MINBLOCKSIZE * 2)) {
4413 dmu_assign_arcbuf(bonus_db, off,
4414 bigbuf_arcbufs[j], tx);
4415 } else {
4416 dmu_assign_arcbuf(bonus_db, off,
4417 bigbuf_arcbufs[2 * j], tx);
4418 dmu_assign_arcbuf(bonus_db,
4419 off + chunksize / 2,
4420 bigbuf_arcbufs[2 * j + 1], tx);
4421 }
4422 if (i == 1) {
4423 dmu_buf_rele(dbt, FTAG);
4424 }
4425 }
4426 dmu_tx_commit(tx);
4427
4428 /*
4429 * Sanity check the stuff we just wrote.
4430 */
4431 {
4432 void *packcheck = umem_alloc(packsize, UMEM_NOFAIL);
4433 void *bigcheck = umem_alloc(bigsize, UMEM_NOFAIL);
4434
4435 VERIFY(0 == dmu_read(os, packobj, packoff,
4436 packsize, packcheck, DMU_READ_PREFETCH));
4437 VERIFY(0 == dmu_read(os, bigobj, bigoff,
4438 bigsize, bigcheck, DMU_READ_PREFETCH));
4439
4440 ASSERT(bcmp(packbuf, packcheck, packsize) == 0);
4441 ASSERT(bcmp(bigbuf, bigcheck, bigsize) == 0);
4442
4443 umem_free(packcheck, packsize);
4444 umem_free(bigcheck, bigsize);
4445 }
4446 if (i == 2) {
4447 txg_wait_open(dmu_objset_pool(os), 0);
4448 } else if (i == 3) {
4449 txg_wait_synced(dmu_objset_pool(os), 0);
4450 }
4451 }
4452
4453 dmu_buf_rele(bonus_db, FTAG);
4454 umem_free(packbuf, packsize);
4455 umem_free(bigbuf, bigsize);
4456 umem_free(bigbuf_arcbufs, 2 * s * sizeof (arc_buf_t *));
4457 umem_free(od, size);
4458 }
4459
4460 /* ARGSUSED */
4461 void
4462 ztest_dmu_write_parallel(ztest_ds_t *zd, uint64_t id)
4463 {
4464 ztest_od_t *od;
4465
4466 od = umem_alloc(sizeof (ztest_od_t), UMEM_NOFAIL);
4467 uint64_t offset = (1ULL << (ztest_random(20) + 43)) +
4468 (ztest_random(ZTEST_RANGE_LOCKS) << SPA_MAXBLOCKSHIFT);
4469
4470 /*
4471 * Have multiple threads write to large offsets in an object
4472 * to verify that parallel writes to an object -- even to the
4473 * same blocks within the object -- doesn't cause any trouble.
4474 */
4475 ztest_od_init(od, ID_PARALLEL, FTAG, 0, DMU_OT_UINT64_OTHER, 0, 0, 0);
4476
4477 if (ztest_object_init(zd, od, sizeof (ztest_od_t), B_FALSE) != 0)
4478 return;
4479
4480 while (ztest_random(10) != 0)
4481 ztest_io(zd, od->od_object, offset);
4482
4483 umem_free(od, sizeof (ztest_od_t));
4484 }
4485
4486 void
4487 ztest_dmu_prealloc(ztest_ds_t *zd, uint64_t id)
4488 {
4489 ztest_od_t *od;
4490 uint64_t offset = (1ULL << (ztest_random(4) + SPA_MAXBLOCKSHIFT)) +
4491 (ztest_random(ZTEST_RANGE_LOCKS) << SPA_MAXBLOCKSHIFT);
4492 uint64_t count = ztest_random(20) + 1;
4493 uint64_t blocksize = ztest_random_blocksize();
4494 void *data;
4495
4496 od = umem_alloc(sizeof (ztest_od_t), UMEM_NOFAIL);
4497
4498 ztest_od_init(od, id, FTAG, 0, DMU_OT_UINT64_OTHER, blocksize, 0, 0);
4499
4500 if (ztest_object_init(zd, od, sizeof (ztest_od_t),
4501 !ztest_random(2)) != 0) {
4502 umem_free(od, sizeof (ztest_od_t));
4503 return;
4504 }
4505
4506 if (ztest_truncate(zd, od->od_object, offset, count * blocksize) != 0) {
4507 umem_free(od, sizeof (ztest_od_t));
4508 return;
4509 }
4510
4511 ztest_prealloc(zd, od->od_object, offset, count * blocksize);
4512
4513 data = umem_zalloc(blocksize, UMEM_NOFAIL);
4514
4515 while (ztest_random(count) != 0) {
4516 uint64_t randoff = offset + (ztest_random(count) * blocksize);
4517 if (ztest_write(zd, od->od_object, randoff, blocksize,
4518 data) != 0)
4519 break;
4520 while (ztest_random(4) != 0)
4521 ztest_io(zd, od->od_object, randoff);
4522 }
4523
4524 umem_free(data, blocksize);
4525 umem_free(od, sizeof (ztest_od_t));
4526 }
4527
4528 /*
4529 * Verify that zap_{create,destroy,add,remove,update} work as expected.
4530 */
4531 #define ZTEST_ZAP_MIN_INTS 1
4532 #define ZTEST_ZAP_MAX_INTS 4
4533 #define ZTEST_ZAP_MAX_PROPS 1000
4534
4535 void
4536 ztest_zap(ztest_ds_t *zd, uint64_t id)
4537 {
4538 objset_t *os = zd->zd_os;
4539 ztest_od_t *od;
4540 uint64_t object;
4541 uint64_t txg, last_txg;
4542 uint64_t value[ZTEST_ZAP_MAX_INTS];
4543 uint64_t zl_ints, zl_intsize, prop;
4544 int i, ints;
4545 dmu_tx_t *tx;
4546 char propname[100], txgname[100];
4547 int error;
4548 char *hc[2] = { "s.acl.h", ".s.open.h.hyLZlg" };
4549
4550 od = umem_alloc(sizeof (ztest_od_t), UMEM_NOFAIL);
4551 ztest_od_init(od, id, FTAG, 0, DMU_OT_ZAP_OTHER, 0, 0, 0);
4552
4553 if (ztest_object_init(zd, od, sizeof (ztest_od_t),
4554 !ztest_random(2)) != 0)
4555 goto out;
4556
4557 object = od->od_object;
4558
4559 /*
4560 * Generate a known hash collision, and verify that
4561 * we can lookup and remove both entries.
4562 */
4563 tx = dmu_tx_create(os);
4564 dmu_tx_hold_zap(tx, object, B_TRUE, NULL);
4565 txg = ztest_tx_assign(tx, TXG_MIGHTWAIT, FTAG);
4566 if (txg == 0)
4567 goto out;
4568 for (i = 0; i < 2; i++) {
4569 value[i] = i;
4570 VERIFY3U(0, ==, zap_add(os, object, hc[i], sizeof (uint64_t),
4571 1, &value[i], tx));
4572 }
4573 for (i = 0; i < 2; i++) {
4574 VERIFY3U(EEXIST, ==, zap_add(os, object, hc[i],
4575 sizeof (uint64_t), 1, &value[i], tx));
4576 VERIFY3U(0, ==,
4577 zap_length(os, object, hc[i], &zl_intsize, &zl_ints));
4578 ASSERT3U(zl_intsize, ==, sizeof (uint64_t));
4579 ASSERT3U(zl_ints, ==, 1);
4580 }
4581 for (i = 0; i < 2; i++) {
4582 VERIFY3U(0, ==, zap_remove(os, object, hc[i], tx));
4583 }
4584 dmu_tx_commit(tx);
4585
4586 /*
4587 * Generate a buch of random entries.
4588 */
4589 ints = MAX(ZTEST_ZAP_MIN_INTS, object % ZTEST_ZAP_MAX_INTS);
4590
4591 prop = ztest_random(ZTEST_ZAP_MAX_PROPS);
4592 (void) sprintf(propname, "prop_%llu", (u_longlong_t)prop);
4593 (void) sprintf(txgname, "txg_%llu", (u_longlong_t)prop);
4594 bzero(value, sizeof (value));
4595 last_txg = 0;
4596
4597 /*
4598 * If these zap entries already exist, validate their contents.
4599 */
4600 error = zap_length(os, object, txgname, &zl_intsize, &zl_ints);
4601 if (error == 0) {
4602 ASSERT3U(zl_intsize, ==, sizeof (uint64_t));
4603 ASSERT3U(zl_ints, ==, 1);
4604
4605 VERIFY(zap_lookup(os, object, txgname, zl_intsize,
4606 zl_ints, &last_txg) == 0);
4607
4608 VERIFY(zap_length(os, object, propname, &zl_intsize,
4609 &zl_ints) == 0);
4610
4611 ASSERT3U(zl_intsize, ==, sizeof (uint64_t));
4612 ASSERT3U(zl_ints, ==, ints);
4613
4614 VERIFY(zap_lookup(os, object, propname, zl_intsize,
4615 zl_ints, value) == 0);
4616
4617 for (i = 0; i < ints; i++) {
4618 ASSERT3U(value[i], ==, last_txg + object + i);
4619 }
4620 } else {
4621 ASSERT3U(error, ==, ENOENT);
4622 }
4623
4624 /*
4625 * Atomically update two entries in our zap object.
4626 * The first is named txg_%llu, and contains the txg
4627 * in which the property was last updated. The second
4628 * is named prop_%llu, and the nth element of its value
4629 * should be txg + object + n.
4630 */
4631 tx = dmu_tx_create(os);
4632 dmu_tx_hold_zap(tx, object, B_TRUE, NULL);
4633 txg = ztest_tx_assign(tx, TXG_MIGHTWAIT, FTAG);
4634 if (txg == 0)
4635 goto out;
4636
4637 if (last_txg > txg)
4638 fatal(0, "zap future leak: old %llu new %llu", last_txg, txg);
4639
4640 for (i = 0; i < ints; i++)
4641 value[i] = txg + object + i;
4642
4643 VERIFY3U(0, ==, zap_update(os, object, txgname, sizeof (uint64_t),
4644 1, &txg, tx));
4645 VERIFY3U(0, ==, zap_update(os, object, propname, sizeof (uint64_t),
4646 ints, value, tx));
4647
4648 dmu_tx_commit(tx);
4649
4650 /*
4651 * Remove a random pair of entries.
4652 */
4653 prop = ztest_random(ZTEST_ZAP_MAX_PROPS);
4654 (void) sprintf(propname, "prop_%llu", (u_longlong_t)prop);
4655 (void) sprintf(txgname, "txg_%llu", (u_longlong_t)prop);
4656
4657 error = zap_length(os, object, txgname, &zl_intsize, &zl_ints);
4658
4659 if (error == ENOENT)
4660 goto out;
4661
4662 ASSERT0(error);
4663
4664 tx = dmu_tx_create(os);
4665 dmu_tx_hold_zap(tx, object, B_TRUE, NULL);
4666 txg = ztest_tx_assign(tx, TXG_MIGHTWAIT, FTAG);
4667 if (txg == 0)
4668 goto out;
4669 VERIFY3U(0, ==, zap_remove(os, object, txgname, tx));
4670 VERIFY3U(0, ==, zap_remove(os, object, propname, tx));
4671 dmu_tx_commit(tx);
4672 out:
4673 umem_free(od, sizeof (ztest_od_t));
4674 }
4675
4676 /*
4677 * Testcase to test the upgrading of a microzap to fatzap.
4678 */
4679 void
4680 ztest_fzap(ztest_ds_t *zd, uint64_t id)
4681 {
4682 objset_t *os = zd->zd_os;
4683 ztest_od_t *od;
4684 uint64_t object, txg;
4685 int i;
4686
4687 od = umem_alloc(sizeof (ztest_od_t), UMEM_NOFAIL);
4688 ztest_od_init(od, id, FTAG, 0, DMU_OT_ZAP_OTHER, 0, 0, 0);
4689
4690 if (ztest_object_init(zd, od, sizeof (ztest_od_t),
4691 !ztest_random(2)) != 0)
4692 goto out;
4693 object = od->od_object;
4694
4695 /*
4696 * Add entries to this ZAP and make sure it spills over
4697 * and gets upgraded to a fatzap. Also, since we are adding
4698 * 2050 entries we should see ptrtbl growth and leaf-block split.
4699 */
4700 for (i = 0; i < 2050; i++) {
4701 char name[ZFS_MAX_DATASET_NAME_LEN];
4702 uint64_t value = i;
4703 dmu_tx_t *tx;
4704 int error;
4705
4706 (void) snprintf(name, sizeof (name), "fzap-%llu-%llu",
4707 (u_longlong_t)id, (u_longlong_t)value);
4708
4709 tx = dmu_tx_create(os);
4710 dmu_tx_hold_zap(tx, object, B_TRUE, name);
4711 txg = ztest_tx_assign(tx, TXG_MIGHTWAIT, FTAG);
4712 if (txg == 0)
4713 goto out;
4714 error = zap_add(os, object, name, sizeof (uint64_t), 1,
4715 &value, tx);
4716 ASSERT(error == 0 || error == EEXIST);
4717 dmu_tx_commit(tx);
4718 }
4719 out:
4720 umem_free(od, sizeof (ztest_od_t));
4721 }
4722
4723 /* ARGSUSED */
4724 void
4725 ztest_zap_parallel(ztest_ds_t *zd, uint64_t id)
4726 {
4727 objset_t *os = zd->zd_os;
4728 ztest_od_t *od;
4729 uint64_t txg, object, count, wsize, wc, zl_wsize, zl_wc;
4730 dmu_tx_t *tx;
4731 int i, namelen, error;
4732 int micro = ztest_random(2);
4733 char name[20], string_value[20];
4734 void *data;
4735
4736 od = umem_alloc(sizeof (ztest_od_t), UMEM_NOFAIL);
4737 ztest_od_init(od, ID_PARALLEL, FTAG, micro, DMU_OT_ZAP_OTHER, 0, 0, 0);
4738
4739 if (ztest_object_init(zd, od, sizeof (ztest_od_t), B_FALSE) != 0) {
4740 umem_free(od, sizeof (ztest_od_t));
4741 return;
4742 }
4743
4744 object = od->od_object;
4745
4746 /*
4747 * Generate a random name of the form 'xxx.....' where each
4748 * x is a random printable character and the dots are dots.
4749 * There are 94 such characters, and the name length goes from
4750 * 6 to 20, so there are 94^3 * 15 = 12,458,760 possible names.
4751 */
4752 namelen = ztest_random(sizeof (name) - 5) + 5 + 1;
4753
4754 for (i = 0; i < 3; i++)
4755 name[i] = '!' + ztest_random('~' - '!' + 1);
4756 for (; i < namelen - 1; i++)
4757 name[i] = '.';
4758 name[i] = '\0';
4759
4760 if ((namelen & 1) || micro) {
4761 wsize = sizeof (txg);
4762 wc = 1;
4763 data = &txg;
4764 } else {
4765 wsize = 1;
4766 wc = namelen;
4767 data = string_value;
4768 }
4769
4770 count = -1ULL;
4771 VERIFY0(zap_count(os, object, &count));
4772 ASSERT(count != -1ULL);
4773
4774 /*
4775 * Select an operation: length, lookup, add, update, remove.
4776 */
4777 i = ztest_random(5);
4778
4779 if (i >= 2) {
4780 tx = dmu_tx_create(os);
4781 dmu_tx_hold_zap(tx, object, B_TRUE, NULL);
4782 txg = ztest_tx_assign(tx, TXG_MIGHTWAIT, FTAG);
4783 if (txg == 0) {
4784 umem_free(od, sizeof (ztest_od_t));
4785 return;
4786 }
4787 bcopy(name, string_value, namelen);
4788 } else {
4789 tx = NULL;
4790 txg = 0;
4791 bzero(string_value, namelen);
4792 }
4793
4794 switch (i) {
4795
4796 case 0:
4797 error = zap_length(os, object, name, &zl_wsize, &zl_wc);
4798 if (error == 0) {
4799 ASSERT3U(wsize, ==, zl_wsize);
4800 ASSERT3U(wc, ==, zl_wc);
4801 } else {
4802 ASSERT3U(error, ==, ENOENT);
4803 }
4804 break;
4805
4806 case 1:
4807 error = zap_lookup(os, object, name, wsize, wc, data);
4808 if (error == 0) {
4809 if (data == string_value &&
4810 bcmp(name, data, namelen) != 0)
4811 fatal(0, "name '%s' != val '%s' len %d",
4812 name, data, namelen);
4813 } else {
4814 ASSERT3U(error, ==, ENOENT);
4815 }
4816 break;
4817
4818 case 2:
4819 error = zap_add(os, object, name, wsize, wc, data, tx);
4820 ASSERT(error == 0 || error == EEXIST);
4821 break;
4822
4823 case 3:
4824 VERIFY(zap_update(os, object, name, wsize, wc, data, tx) == 0);
4825 break;
4826
4827 case 4:
4828 error = zap_remove(os, object, name, tx);
4829 ASSERT(error == 0 || error == ENOENT);
4830 break;
4831 }
4832
4833 if (tx != NULL)
4834 dmu_tx_commit(tx);
4835
4836 umem_free(od, sizeof (ztest_od_t));
4837 }
4838
4839 /*
4840 * Commit callback data.
4841 */
4842 typedef struct ztest_cb_data {
4843 list_node_t zcd_node;
4844 uint64_t zcd_txg;
4845 int zcd_expected_err;
4846 boolean_t zcd_added;
4847 boolean_t zcd_called;
4848 spa_t *zcd_spa;
4849 } ztest_cb_data_t;
4850
4851 /* This is the actual commit callback function */
4852 static void
4853 ztest_commit_callback(void *arg, int error)
4854 {
4855 ztest_cb_data_t *data = arg;
4856 uint64_t synced_txg;
4857
4858 VERIFY(data != NULL);
4859 VERIFY3S(data->zcd_expected_err, ==, error);
4860 VERIFY(!data->zcd_called);
4861
4862 synced_txg = spa_last_synced_txg(data->zcd_spa);
4863 if (data->zcd_txg > synced_txg)
4864 fatal(0, "commit callback of txg %" PRIu64 " called prematurely"
4865 ", last synced txg = %" PRIu64 "\n", data->zcd_txg,
4866 synced_txg);
4867
4868 data->zcd_called = B_TRUE;
4869
4870 if (error == ECANCELED) {
4871 ASSERT0(data->zcd_txg);
4872 ASSERT(!data->zcd_added);
4873
4874 /*
4875 * The private callback data should be destroyed here, but
4876 * since we are going to check the zcd_called field after
4877 * dmu_tx_abort(), we will destroy it there.
4878 */
4879 return;
4880 }
4881
4882 ASSERT(data->zcd_added);
4883 ASSERT3U(data->zcd_txg, !=, 0);
4884
4885 (void) mutex_enter(&zcl.zcl_callbacks_lock);
4886
4887 /* See if this cb was called more quickly */
4888 if ((synced_txg - data->zcd_txg) < zc_min_txg_delay)
4889 zc_min_txg_delay = synced_txg - data->zcd_txg;
4890
4891 /* Remove our callback from the list */
4892 list_remove(&zcl.zcl_callbacks, data);
4893
4894 (void) mutex_exit(&zcl.zcl_callbacks_lock);
4895
4896 umem_free(data, sizeof (ztest_cb_data_t));
4897 }
4898
4899 /* Allocate and initialize callback data structure */
4900 static ztest_cb_data_t *
4901 ztest_create_cb_data(objset_t *os, uint64_t txg)
4902 {
4903 ztest_cb_data_t *cb_data;
4904
4905 cb_data = umem_zalloc(sizeof (ztest_cb_data_t), UMEM_NOFAIL);
4906
4907 cb_data->zcd_txg = txg;
4908 cb_data->zcd_spa = dmu_objset_spa(os);
4909 list_link_init(&cb_data->zcd_node);
4910
4911 return (cb_data);
4912 }
4913
4914 /*
4915 * Commit callback test.
4916 */
4917 void
4918 ztest_dmu_commit_callbacks(ztest_ds_t *zd, uint64_t id)
4919 {
4920 objset_t *os = zd->zd_os;
4921 ztest_od_t *od;
4922 dmu_tx_t *tx;
4923 ztest_cb_data_t *cb_data[3], *tmp_cb;
4924 uint64_t old_txg, txg;
4925 int i, error = 0;
4926
4927 od = umem_alloc(sizeof (ztest_od_t), UMEM_NOFAIL);
4928 ztest_od_init(od, id, FTAG, 0, DMU_OT_UINT64_OTHER, 0, 0, 0);
4929
4930 if (ztest_object_init(zd, od, sizeof (ztest_od_t), B_FALSE) != 0) {
4931 umem_free(od, sizeof (ztest_od_t));
4932 return;
4933 }
4934
4935 tx = dmu_tx_create(os);
4936
4937 cb_data[0] = ztest_create_cb_data(os, 0);
4938 dmu_tx_callback_register(tx, ztest_commit_callback, cb_data[0]);
4939
4940 dmu_tx_hold_write(tx, od->od_object, 0, sizeof (uint64_t));
4941
4942 /* Every once in a while, abort the transaction on purpose */
4943 if (ztest_random(100) == 0)
4944 error = -1;
4945
4946 if (!error)
4947 error = dmu_tx_assign(tx, TXG_NOWAIT);
4948
4949 txg = error ? 0 : dmu_tx_get_txg(tx);
4950
4951 cb_data[0]->zcd_txg = txg;
4952 cb_data[1] = ztest_create_cb_data(os, txg);
4953 dmu_tx_callback_register(tx, ztest_commit_callback, cb_data[1]);
4954
4955 if (error) {
4956 /*
4957 * It's not a strict requirement to call the registered
4958 * callbacks from inside dmu_tx_abort(), but that's what
4959 * it's supposed to happen in the current implementation
4960 * so we will check for that.
4961 */
4962 for (i = 0; i < 2; i++) {
4963 cb_data[i]->zcd_expected_err = ECANCELED;
4964 VERIFY(!cb_data[i]->zcd_called);
4965 }
4966
4967 dmu_tx_abort(tx);
4968
4969 for (i = 0; i < 2; i++) {
4970 VERIFY(cb_data[i]->zcd_called);
4971 umem_free(cb_data[i], sizeof (ztest_cb_data_t));
4972 }
4973
4974 umem_free(od, sizeof (ztest_od_t));
4975 return;
4976 }
4977
4978 cb_data[2] = ztest_create_cb_data(os, txg);
4979 dmu_tx_callback_register(tx, ztest_commit_callback, cb_data[2]);
4980
4981 /*
4982 * Read existing data to make sure there isn't a future leak.
4983 */
4984 VERIFY(0 == dmu_read(os, od->od_object, 0, sizeof (uint64_t),
4985 &old_txg, DMU_READ_PREFETCH));
4986
4987 if (old_txg > txg)
4988 fatal(0, "future leak: got %" PRIu64 ", open txg is %" PRIu64,
4989 old_txg, txg);
4990
4991 dmu_write(os, od->od_object, 0, sizeof (uint64_t), &txg, tx);
4992
4993 (void) mutex_enter(&zcl.zcl_callbacks_lock);
4994
4995 /*
4996 * Since commit callbacks don't have any ordering requirement and since
4997 * it is theoretically possible for a commit callback to be called
4998 * after an arbitrary amount of time has elapsed since its txg has been
4999 * synced, it is difficult to reliably determine whether a commit
5000 * callback hasn't been called due to high load or due to a flawed
5001 * implementation.
5002 *
5003 * In practice, we will assume that if after a certain number of txgs a
5004 * commit callback hasn't been called, then most likely there's an
5005 * implementation bug..
5006 */
5007 tmp_cb = list_head(&zcl.zcl_callbacks);
5008 if (tmp_cb != NULL &&
5009 tmp_cb->zcd_txg + ZTEST_COMMIT_CB_THRESH < txg) {
5010 fatal(0, "Commit callback threshold exceeded, oldest txg: %"
5011 PRIu64 ", open txg: %" PRIu64 "\n", tmp_cb->zcd_txg, txg);
5012 }
5013
5014 /*
5015 * Let's find the place to insert our callbacks.
5016 *
5017 * Even though the list is ordered by txg, it is possible for the
5018 * insertion point to not be the end because our txg may already be
5019 * quiescing at this point and other callbacks in the open txg
5020 * (from other objsets) may have sneaked in.
5021 */
5022 tmp_cb = list_tail(&zcl.zcl_callbacks);
5023 while (tmp_cb != NULL && tmp_cb->zcd_txg > txg)
5024 tmp_cb = list_prev(&zcl.zcl_callbacks, tmp_cb);
5025
5026 /* Add the 3 callbacks to the list */
5027 for (i = 0; i < 3; i++) {
5028 if (tmp_cb == NULL)
5029 list_insert_head(&zcl.zcl_callbacks, cb_data[i]);
5030 else
5031 list_insert_after(&zcl.zcl_callbacks, tmp_cb,
5032 cb_data[i]);
5033
5034 cb_data[i]->zcd_added = B_TRUE;
5035 VERIFY(!cb_data[i]->zcd_called);
5036
5037 tmp_cb = cb_data[i];
5038 }
5039
5040 zc_cb_counter += 3;
5041
5042 (void) mutex_exit(&zcl.zcl_callbacks_lock);
5043
5044 dmu_tx_commit(tx);
5045
5046 umem_free(od, sizeof (ztest_od_t));
5047 }
5048
5049 /*
5050 * Visit each object in the dataset. Verify that its properties
5051 * are consistent what was stored in the block tag when it was created,
5052 * and that its unused bonus buffer space has not been overwritten.
5053 */
5054 /* ARGSUSED */
5055 void
5056 ztest_verify_dnode_bt(ztest_ds_t *zd, uint64_t id)
5057 {
5058 objset_t *os = zd->zd_os;
5059 uint64_t obj;
5060 int err = 0;
5061
5062 for (obj = 0; err == 0; err = dmu_object_next(os, &obj, FALSE, 0)) {
5063 ztest_block_tag_t *bt = NULL;
5064 dmu_object_info_t doi;
5065 dmu_buf_t *db;
5066
5067 if (dmu_bonus_hold(os, obj, FTAG, &db) != 0)
5068 continue;
5069
5070 dmu_object_info_from_db(db, &doi);
5071 if (doi.doi_bonus_size >= sizeof (*bt))
5072 bt = ztest_bt_bonus(db);
5073
5074 if (bt && bt->bt_magic == BT_MAGIC) {
5075 ztest_bt_verify(bt, os, obj, doi.doi_dnodesize,
5076 bt->bt_offset, bt->bt_gen, bt->bt_txg,
5077 bt->bt_crtxg);
5078 ztest_verify_unused_bonus(db, bt, obj, os, bt->bt_gen);
5079 }
5080
5081 dmu_buf_rele(db, FTAG);
5082 }
5083 }
5084
5085 /* ARGSUSED */
5086 void
5087 ztest_dsl_prop_get_set(ztest_ds_t *zd, uint64_t id)
5088 {
5089 zfs_prop_t proplist[] = {
5090 ZFS_PROP_CHECKSUM,
5091 ZFS_PROP_COMPRESSION,
5092 ZFS_PROP_COPIES,
5093 ZFS_PROP_DEDUP
5094 };
5095 int p;
5096
5097 (void) rw_rdlock(&ztest_name_lock);
5098
5099 for (p = 0; p < sizeof (proplist) / sizeof (proplist[0]); p++)
5100 (void) ztest_dsl_prop_set_uint64(zd->zd_name, proplist[p],
5101 ztest_random_dsl_prop(proplist[p]), (int)ztest_random(2));
5102
5103 VERIFY0(ztest_dsl_prop_set_uint64(zd->zd_name, ZFS_PROP_RECORDSIZE,
5104 ztest_random_blocksize(), (int)ztest_random(2)));
5105
5106 (void) rw_unlock(&ztest_name_lock);
5107 }
5108
5109 /* ARGSUSED */
5110 void
5111 ztest_spa_prop_get_set(ztest_ds_t *zd, uint64_t id)
5112 {
5113 nvlist_t *props = NULL;
5114
5115 (void) rw_rdlock(&ztest_name_lock);
5116
5117 (void) ztest_spa_prop_set_uint64(ZPOOL_PROP_DEDUPDITTO,
5118 ZIO_DEDUPDITTO_MIN + ztest_random(ZIO_DEDUPDITTO_MIN));
5119
5120 VERIFY0(spa_prop_get(ztest_spa, &props));
5121
5122 if (ztest_opts.zo_verbose >= 6)
5123 dump_nvlist(props, 4);
5124
5125 nvlist_free(props);
5126
5127 (void) rw_unlock(&ztest_name_lock);
5128 }
5129
5130 static int
5131 user_release_one(const char *snapname, const char *holdname)
5132 {
5133 nvlist_t *snaps, *holds;
5134 int error;
5135
5136 snaps = fnvlist_alloc();
5137 holds = fnvlist_alloc();
5138 fnvlist_add_boolean(holds, holdname);
5139 fnvlist_add_nvlist(snaps, snapname, holds);
5140 fnvlist_free(holds);
5141 error = dsl_dataset_user_release(snaps, NULL);
5142 fnvlist_free(snaps);
5143 return (error);
5144 }
5145
5146 /*
5147 * Test snapshot hold/release and deferred destroy.
5148 */
5149 void
5150 ztest_dmu_snapshot_hold(ztest_ds_t *zd, uint64_t id)
5151 {
5152 int error;
5153 objset_t *os = zd->zd_os;
5154 objset_t *origin;
5155 char snapname[100];
5156 char fullname[100];
5157 char clonename[100];
5158 char tag[100];
5159 char osname[ZFS_MAX_DATASET_NAME_LEN];
5160 nvlist_t *holds;
5161
5162 (void) rw_rdlock(&ztest_name_lock);
5163
5164 dmu_objset_name(os, osname);
5165
5166 (void) snprintf(snapname, sizeof (snapname), "sh1_%llu",
5167 (u_longlong_t)id);
5168 (void) snprintf(fullname, sizeof (fullname), "%s@%s", osname, snapname);
5169 (void) snprintf(clonename, sizeof (clonename),
5170 "%s/ch1_%llu", osname, (u_longlong_t)id);
5171 (void) snprintf(tag, sizeof (tag), "tag_%llu", (u_longlong_t)id);
5172
5173 /*
5174 * Clean up from any previous run.
5175 */
5176 error = dsl_destroy_head(clonename);
5177 if (error != ENOENT)
5178 ASSERT0(error);
5179 error = user_release_one(fullname, tag);
5180 if (error != ESRCH && error != ENOENT)
5181 ASSERT0(error);
5182 error = dsl_destroy_snapshot(fullname, B_FALSE);
5183 if (error != ENOENT)
5184 ASSERT0(error);
5185
5186 /*
5187 * Create snapshot, clone it, mark snap for deferred destroy,
5188 * destroy clone, verify snap was also destroyed.
5189 */
5190 error = dmu_objset_snapshot_one(osname, snapname);
5191 if (error) {
5192 if (error == ENOSPC) {
5193 ztest_record_enospc("dmu_objset_snapshot");
5194 goto out;
5195 }
5196 fatal(0, "dmu_objset_snapshot(%s) = %d", fullname, error);
5197 }
5198
5199 error = dmu_objset_clone(clonename, fullname);
5200 if (error) {
5201 if (error == ENOSPC) {
5202 ztest_record_enospc("dmu_objset_clone");
5203 goto out;
5204 }
5205 fatal(0, "dmu_objset_clone(%s) = %d", clonename, error);
5206 }
5207
5208 error = dsl_destroy_snapshot(fullname, B_TRUE);
5209 if (error) {
5210 fatal(0, "dsl_destroy_snapshot(%s, B_TRUE) = %d",
5211 fullname, error);
5212 }
5213
5214 error = dsl_destroy_head(clonename);
5215 if (error)
5216 fatal(0, "dsl_destroy_head(%s) = %d", clonename, error);
5217
5218 error = dmu_objset_hold(fullname, FTAG, &origin);
5219 if (error != ENOENT)
5220 fatal(0, "dmu_objset_hold(%s) = %d", fullname, error);
5221
5222 /*
5223 * Create snapshot, add temporary hold, verify that we can't
5224 * destroy a held snapshot, mark for deferred destroy,
5225 * release hold, verify snapshot was destroyed.
5226 */
5227 error = dmu_objset_snapshot_one(osname, snapname);
5228 if (error) {
5229 if (error == ENOSPC) {
5230 ztest_record_enospc("dmu_objset_snapshot");
5231 goto out;
5232 }
5233 fatal(0, "dmu_objset_snapshot(%s) = %d", fullname, error);
5234 }
5235
5236 holds = fnvlist_alloc();
5237 fnvlist_add_string(holds, fullname, tag);
5238 error = dsl_dataset_user_hold(holds, 0, NULL);
5239 fnvlist_free(holds);
5240
5241 if (error == ENOSPC) {
5242 ztest_record_enospc("dsl_dataset_user_hold");
5243 goto out;
5244 } else if (error) {
5245 fatal(0, "dsl_dataset_user_hold(%s, %s) = %u",
5246 fullname, tag, error);
5247 }
5248
5249 error = dsl_destroy_snapshot(fullname, B_FALSE);
5250 if (error != EBUSY) {
5251 fatal(0, "dsl_destroy_snapshot(%s, B_FALSE) = %d",
5252 fullname, error);
5253 }
5254
5255 error = dsl_destroy_snapshot(fullname, B_TRUE);
5256 if (error) {
5257 fatal(0, "dsl_destroy_snapshot(%s, B_TRUE) = %d",
5258 fullname, error);
5259 }
5260
5261 error = user_release_one(fullname, tag);
5262 if (error)
5263 fatal(0, "user_release_one(%s, %s) = %d", fullname, tag, error);
5264
5265 VERIFY3U(dmu_objset_hold(fullname, FTAG, &origin), ==, ENOENT);
5266
5267 out:
5268 (void) rw_unlock(&ztest_name_lock);
5269 }
5270
5271 /*
5272 * Inject random faults into the on-disk data.
5273 */
5274 /* ARGSUSED */
5275 void
5276 ztest_fault_inject(ztest_ds_t *zd, uint64_t id)
5277 {
5278 ztest_shared_t *zs = ztest_shared;
5279 spa_t *spa = ztest_spa;
5280 int fd;
5281 uint64_t offset;
5282 uint64_t leaves;
5283 uint64_t bad = 0x1990c0ffeedecadeull;
5284 uint64_t top, leaf;
5285 char *path0;
5286 char *pathrand;
5287 size_t fsize;
5288 int bshift = SPA_MAXBLOCKSHIFT + 2;
5289 int iters = 1000;
5290 int maxfaults;
5291 int mirror_save;
5292 vdev_t *vd0 = NULL;
5293 uint64_t guid0 = 0;
5294 boolean_t islog = B_FALSE;
5295
5296 path0 = umem_alloc(MAXPATHLEN, UMEM_NOFAIL);
5297 pathrand = umem_alloc(MAXPATHLEN, UMEM_NOFAIL);
5298
5299 mutex_enter(&ztest_vdev_lock);
5300 maxfaults = MAXFAULTS();
5301 leaves = MAX(zs->zs_mirrors, 1) * ztest_opts.zo_raidz;
5302 mirror_save = zs->zs_mirrors;
5303 mutex_exit(&ztest_vdev_lock);
5304
5305 ASSERT(leaves >= 1);
5306
5307 /*
5308 * Grab the name lock as reader. There are some operations
5309 * which don't like to have their vdevs changed while
5310 * they are in progress (i.e. spa_change_guid). Those
5311 * operations will have grabbed the name lock as writer.
5312 */
5313 (void) rw_rdlock(&ztest_name_lock);
5314
5315 /*
5316 * We need SCL_STATE here because we're going to look at vd0->vdev_tsd.
5317 */
5318 spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
5319
5320 if (ztest_random(2) == 0) {
5321 /*
5322 * Inject errors on a normal data device or slog device.
5323 */
5324 top = ztest_random_vdev_top(spa, B_TRUE);
5325 leaf = ztest_random(leaves) + zs->zs_splits;
5326
5327 /*
5328 * Generate paths to the first leaf in this top-level vdev,
5329 * and to the random leaf we selected. We'll induce transient
5330 * write failures and random online/offline activity on leaf 0,
5331 * and we'll write random garbage to the randomly chosen leaf.
5332 */
5333 (void) snprintf(path0, MAXPATHLEN, ztest_dev_template,
5334 ztest_opts.zo_dir, ztest_opts.zo_pool,
5335 top * leaves + zs->zs_splits);
5336 (void) snprintf(pathrand, MAXPATHLEN, ztest_dev_template,
5337 ztest_opts.zo_dir, ztest_opts.zo_pool,
5338 top * leaves + leaf);
5339
5340 vd0 = vdev_lookup_by_path(spa->spa_root_vdev, path0);
5341 if (vd0 != NULL && vd0->vdev_top->vdev_islog)
5342 islog = B_TRUE;
5343
5344 /*
5345 * If the top-level vdev needs to be resilvered
5346 * then we only allow faults on the device that is
5347 * resilvering.
5348 */
5349 if (vd0 != NULL && maxfaults != 1 &&
5350 (!vdev_resilver_needed(vd0->vdev_top, NULL, NULL) ||
5351 vd0->vdev_resilver_txg != 0)) {
5352 /*
5353 * Make vd0 explicitly claim to be unreadable,
5354 * or unwriteable, or reach behind its back
5355 * and close the underlying fd. We can do this if
5356 * maxfaults == 0 because we'll fail and reexecute,
5357 * and we can do it if maxfaults >= 2 because we'll
5358 * have enough redundancy. If maxfaults == 1, the
5359 * combination of this with injection of random data
5360 * corruption below exceeds the pool's fault tolerance.
5361 */
5362 vdev_file_t *vf = vd0->vdev_tsd;
5363
5364 if (vf != NULL && ztest_random(3) == 0) {
5365 (void) close(vf->vf_vnode->v_fd);
5366 vf->vf_vnode->v_fd = -1;
5367 } else if (ztest_random(2) == 0) {
5368 vd0->vdev_cant_read = B_TRUE;
5369 } else {
5370 vd0->vdev_cant_write = B_TRUE;
5371 }
5372 guid0 = vd0->vdev_guid;
5373 }
5374 } else {
5375 /*
5376 * Inject errors on an l2cache device.
5377 */
5378 spa_aux_vdev_t *sav = &spa->spa_l2cache;
5379
5380 if (sav->sav_count == 0) {
5381 spa_config_exit(spa, SCL_STATE, FTAG);
5382 (void) rw_unlock(&ztest_name_lock);
5383 goto out;
5384 }
5385 vd0 = sav->sav_vdevs[ztest_random(sav->sav_count)];
5386 guid0 = vd0->vdev_guid;
5387 (void) strcpy(path0, vd0->vdev_path);
5388 (void) strcpy(pathrand, vd0->vdev_path);
5389
5390 leaf = 0;
5391 leaves = 1;
5392 maxfaults = INT_MAX; /* no limit on cache devices */
5393 }
5394
5395 spa_config_exit(spa, SCL_STATE, FTAG);
5396 (void) rw_unlock(&ztest_name_lock);
5397
5398 /*
5399 * If we can tolerate two or more faults, or we're dealing
5400 * with a slog, randomly online/offline vd0.
5401 */
5402 if ((maxfaults >= 2 || islog) && guid0 != 0) {
5403 if (ztest_random(10) < 6) {
5404 int flags = (ztest_random(2) == 0 ?
5405 ZFS_OFFLINE_TEMPORARY : 0);
5406
5407 /*
5408 * We have to grab the zs_name_lock as writer to
5409 * prevent a race between offlining a slog and
5410 * destroying a dataset. Offlining the slog will
5411 * grab a reference on the dataset which may cause
5412 * dsl_destroy_head() to fail with EBUSY thus
5413 * leaving the dataset in an inconsistent state.
5414 */
5415 if (islog)
5416 (void) rw_wrlock(&ztest_name_lock);
5417
5418 VERIFY(vdev_offline(spa, guid0, flags) != EBUSY);
5419
5420 if (islog)
5421 (void) rw_unlock(&ztest_name_lock);
5422 } else {
5423 /*
5424 * Ideally we would like to be able to randomly
5425 * call vdev_[on|off]line without holding locks
5426 * to force unpredictable failures but the side
5427 * effects of vdev_[on|off]line prevent us from
5428 * doing so. We grab the ztest_vdev_lock here to
5429 * prevent a race between injection testing and
5430 * aux_vdev removal.
5431 */
5432 mutex_enter(&ztest_vdev_lock);
5433 (void) vdev_online(spa, guid0, 0, NULL);
5434 mutex_exit(&ztest_vdev_lock);
5435 }
5436 }
5437
5438 if (maxfaults == 0)
5439 goto out;
5440
5441 /*
5442 * We have at least single-fault tolerance, so inject data corruption.
5443 */
5444 fd = open(pathrand, O_RDWR);
5445
5446 if (fd == -1) /* we hit a gap in the device namespace */
5447 goto out;
5448
5449 fsize = lseek(fd, 0, SEEK_END);
5450
5451 while (--iters != 0) {
5452 /*
5453 * The offset must be chosen carefully to ensure that
5454 * we do not inject a given logical block with errors
5455 * on two different leaf devices, because ZFS can not
5456 * tolerate that (if maxfaults==1).
5457 *
5458 * We divide each leaf into chunks of size
5459 * (# leaves * SPA_MAXBLOCKSIZE * 4). Within each chunk
5460 * there is a series of ranges to which we can inject errors.
5461 * Each range can accept errors on only a single leaf vdev.
5462 * The error injection ranges are separated by ranges
5463 * which we will not inject errors on any device (DMZs).
5464 * Each DMZ must be large enough such that a single block
5465 * can not straddle it, so that a single block can not be
5466 * a target in two different injection ranges (on different
5467 * leaf vdevs).
5468 *
5469 * For example, with 3 leaves, each chunk looks like:
5470 * 0 to 32M: injection range for leaf 0
5471 * 32M to 64M: DMZ - no injection allowed
5472 * 64M to 96M: injection range for leaf 1
5473 * 96M to 128M: DMZ - no injection allowed
5474 * 128M to 160M: injection range for leaf 2
5475 * 160M to 192M: DMZ - no injection allowed
5476 */
5477 offset = ztest_random(fsize / (leaves << bshift)) *
5478 (leaves << bshift) + (leaf << bshift) +
5479 (ztest_random(1ULL << (bshift - 1)) & -8ULL);
5480
5481 /*
5482 * Only allow damage to the labels at one end of the vdev.
5483 *
5484 * If all labels are damaged, the device will be totally
5485 * inaccessible, which will result in loss of data,
5486 * because we also damage (parts of) the other side of
5487 * the mirror/raidz.
5488 *
5489 * Additionally, we will always have both an even and an
5490 * odd label, so that we can handle crashes in the
5491 * middle of vdev_config_sync().
5492 */
5493 if ((leaf & 1) == 0 && offset < VDEV_LABEL_START_SIZE)
5494 continue;
5495
5496 /*
5497 * The two end labels are stored at the "end" of the disk, but
5498 * the end of the disk (vdev_psize) is aligned to
5499 * sizeof (vdev_label_t).
5500 */
5501 uint64_t psize = P2ALIGN(fsize, sizeof (vdev_label_t));
5502 if ((leaf & 1) == 1 &&
5503 offset + sizeof (bad) > psize - VDEV_LABEL_END_SIZE)
5504 continue;
5505
5506 mutex_enter(&ztest_vdev_lock);
5507 if (mirror_save != zs->zs_mirrors) {
5508 mutex_exit(&ztest_vdev_lock);
5509 (void) close(fd);
5510 goto out;
5511 }
5512
5513 if (pwrite(fd, &bad, sizeof (bad), offset) != sizeof (bad))
5514 fatal(1, "can't inject bad word at 0x%llx in %s",
5515 offset, pathrand);
5516
5517 mutex_exit(&ztest_vdev_lock);
5518
5519 if (ztest_opts.zo_verbose >= 7)
5520 (void) printf("injected bad word into %s,"
5521 " offset 0x%llx\n", pathrand, (u_longlong_t)offset);
5522 }
5523
5524 (void) close(fd);
5525 out:
5526 umem_free(path0, MAXPATHLEN);
5527 umem_free(pathrand, MAXPATHLEN);
5528 }
5529
5530 /*
5531 * Verify that DDT repair works as expected.
5532 */
5533 void
5534 ztest_ddt_repair(ztest_ds_t *zd, uint64_t id)
5535 {
5536 ztest_shared_t *zs = ztest_shared;
5537 spa_t *spa = ztest_spa;
5538 objset_t *os = zd->zd_os;
5539 ztest_od_t *od;
5540 uint64_t object, blocksize, txg, pattern, psize;
5541 enum zio_checksum checksum = spa_dedup_checksum(spa);
5542 dmu_buf_t *db;
5543 dmu_tx_t *tx;
5544 abd_t *abd;
5545 blkptr_t blk;
5546 int copies = 2 * ZIO_DEDUPDITTO_MIN;
5547 int i;
5548
5549 blocksize = ztest_random_blocksize();
5550 blocksize = MIN(blocksize, 2048); /* because we write so many */
5551
5552 od = umem_alloc(sizeof (ztest_od_t), UMEM_NOFAIL);
5553 ztest_od_init(od, id, FTAG, 0, DMU_OT_UINT64_OTHER, blocksize, 0, 0);
5554
5555 if (ztest_object_init(zd, od, sizeof (ztest_od_t), B_FALSE) != 0) {
5556 umem_free(od, sizeof (ztest_od_t));
5557 return;
5558 }
5559
5560 /*
5561 * Take the name lock as writer to prevent anyone else from changing
5562 * the pool and dataset properies we need to maintain during this test.
5563 */
5564 (void) rw_wrlock(&ztest_name_lock);
5565
5566 if (ztest_dsl_prop_set_uint64(zd->zd_name, ZFS_PROP_DEDUP, checksum,
5567 B_FALSE) != 0 ||
5568 ztest_dsl_prop_set_uint64(zd->zd_name, ZFS_PROP_COPIES, 1,
5569 B_FALSE) != 0) {
5570 (void) rw_unlock(&ztest_name_lock);
5571 umem_free(od, sizeof (ztest_od_t));
5572 return;
5573 }
5574
5575 dmu_objset_stats_t dds;
5576 dsl_pool_config_enter(dmu_objset_pool(os), FTAG);
5577 dmu_objset_fast_stat(os, &dds);
5578 dsl_pool_config_exit(dmu_objset_pool(os), FTAG);
5579
5580 object = od[0].od_object;
5581 blocksize = od[0].od_blocksize;
5582 pattern = zs->zs_guid ^ dds.dds_guid;
5583
5584 ASSERT(object != 0);
5585
5586 tx = dmu_tx_create(os);
5587 dmu_tx_hold_write(tx, object, 0, copies * blocksize);
5588 txg = ztest_tx_assign(tx, TXG_WAIT, FTAG);
5589 if (txg == 0) {
5590 (void) rw_unlock(&ztest_name_lock);
5591 umem_free(od, sizeof (ztest_od_t));
5592 return;
5593 }
5594
5595 /*
5596 * Write all the copies of our block.
5597 */
5598 for (i = 0; i < copies; i++) {
5599 uint64_t offset = i * blocksize;
5600 int error = dmu_buf_hold(os, object, offset, FTAG, &db,
5601 DMU_READ_NO_PREFETCH);
5602 if (error != 0) {
5603 fatal(B_FALSE, "dmu_buf_hold(%p, %llu, %llu) = %u",
5604 os, (long long)object, (long long) offset, error);
5605 }
5606 ASSERT(db->db_offset == offset);
5607 ASSERT(db->db_size == blocksize);
5608 ASSERT(ztest_pattern_match(db->db_data, db->db_size, pattern) ||
5609 ztest_pattern_match(db->db_data, db->db_size, 0ULL));
5610 dmu_buf_will_fill(db, tx);
5611 ztest_pattern_set(db->db_data, db->db_size, pattern);
5612 dmu_buf_rele(db, FTAG);
5613 }
5614
5615 dmu_tx_commit(tx);
5616 txg_wait_synced(spa_get_dsl(spa), txg);
5617
5618 /*
5619 * Find out what block we got.
5620 */
5621 VERIFY0(dmu_buf_hold(os, object, 0, FTAG, &db,
5622 DMU_READ_NO_PREFETCH));
5623 blk = *((dmu_buf_impl_t *)db)->db_blkptr;
5624 dmu_buf_rele(db, FTAG);
5625
5626 /*
5627 * Damage the block. Dedup-ditto will save us when we read it later.
5628 */
5629 psize = BP_GET_PSIZE(&blk);
5630 abd = abd_alloc_linear(psize, B_TRUE);
5631 ztest_pattern_set(abd_to_buf(abd), psize, ~pattern);
5632
5633 (void) zio_wait(zio_rewrite(NULL, spa, 0, &blk,
5634 abd, psize, NULL, NULL, ZIO_PRIORITY_SYNC_WRITE,
5635 ZIO_FLAG_CANFAIL | ZIO_FLAG_INDUCE_DAMAGE, NULL));
5636
5637 abd_free(abd);
5638
5639 (void) rw_unlock(&ztest_name_lock);
5640 umem_free(od, sizeof (ztest_od_t));
5641 }
5642
5643 /*
5644 * Scrub the pool.
5645 */
5646 /* ARGSUSED */
5647 void
5648 ztest_scrub(ztest_ds_t *zd, uint64_t id)
5649 {
5650 spa_t *spa = ztest_spa;
5651
5652 (void) spa_scan(spa, POOL_SCAN_SCRUB);
5653 (void) poll(NULL, 0, 100); /* wait a moment, then force a restart */
5654 (void) spa_scan(spa, POOL_SCAN_SCRUB);
5655 }
5656
5657 /*
5658 * Change the guid for the pool.
5659 */
5660 /* ARGSUSED */
5661 void
5662 ztest_reguid(ztest_ds_t *zd, uint64_t id)
5663 {
5664 spa_t *spa = ztest_spa;
5665 uint64_t orig, load;
5666 int error;
5667
5668 orig = spa_guid(spa);
5669 load = spa_load_guid(spa);
5670
5671 (void) rw_wrlock(&ztest_name_lock);
5672 error = spa_change_guid(spa);
5673 (void) rw_unlock(&ztest_name_lock);
5674
5675 if (error != 0)
5676 return;
5677
5678 if (ztest_opts.zo_verbose >= 4) {
5679 (void) printf("Changed guid old %llu -> %llu\n",
5680 (u_longlong_t)orig, (u_longlong_t)spa_guid(spa));
5681 }
5682
5683 VERIFY3U(orig, !=, spa_guid(spa));
5684 VERIFY3U(load, ==, spa_load_guid(spa));
5685 }
5686
5687 /*
5688 * Rename the pool to a different name and then rename it back.
5689 */
5690 /* ARGSUSED */
5691 void
5692 ztest_spa_rename(ztest_ds_t *zd, uint64_t id)
5693 {
5694 char *oldname, *newname;
5695 spa_t *spa;
5696
5697 if (ztest_opts.zo_mmp_test)
5698 return;
5699
5700 (void) rw_wrlock(&ztest_name_lock);
5701
5702 oldname = ztest_opts.zo_pool;
5703 newname = umem_alloc(strlen(oldname) + 5, UMEM_NOFAIL);
5704 (void) strcpy(newname, oldname);
5705 (void) strcat(newname, "_tmp");
5706
5707 /*
5708 * Do the rename
5709 */
5710 VERIFY3U(0, ==, spa_rename(oldname, newname));
5711
5712 /*
5713 * Try to open it under the old name, which shouldn't exist
5714 */
5715 VERIFY3U(ENOENT, ==, spa_open(oldname, &spa, FTAG));
5716
5717 /*
5718 * Open it under the new name and make sure it's still the same spa_t.
5719 */
5720 VERIFY3U(0, ==, spa_open(newname, &spa, FTAG));
5721
5722 ASSERT(spa == ztest_spa);
5723 spa_close(spa, FTAG);
5724
5725 /*
5726 * Rename it back to the original
5727 */
5728 VERIFY3U(0, ==, spa_rename(newname, oldname));
5729
5730 /*
5731 * Make sure it can still be opened
5732 */
5733 VERIFY3U(0, ==, spa_open(oldname, &spa, FTAG));
5734
5735 ASSERT(spa == ztest_spa);
5736 spa_close(spa, FTAG);
5737
5738 umem_free(newname, strlen(newname) + 1);
5739
5740 (void) rw_unlock(&ztest_name_lock);
5741 }
5742
5743 void
5744 ztest_fletcher(ztest_ds_t *zd, uint64_t id)
5745 {
5746 hrtime_t end = gethrtime() + NANOSEC;
5747
5748 while (gethrtime() <= end) {
5749 int run_count = 100;
5750 void *buf;
5751 struct abd *abd_data, *abd_meta;
5752 uint32_t size;
5753 int *ptr;
5754 int i;
5755 zio_cksum_t zc_ref;
5756 zio_cksum_t zc_ref_byteswap;
5757
5758 size = ztest_random_blocksize();
5759
5760 buf = umem_alloc(size, UMEM_NOFAIL);
5761 abd_data = abd_alloc(size, B_FALSE);
5762 abd_meta = abd_alloc(size, B_TRUE);
5763
5764 for (i = 0, ptr = buf; i < size / sizeof (*ptr); i++, ptr++)
5765 *ptr = ztest_random(UINT_MAX);
5766
5767 abd_copy_from_buf_off(abd_data, buf, 0, size);
5768 abd_copy_from_buf_off(abd_meta, buf, 0, size);
5769
5770 VERIFY0(fletcher_4_impl_set("scalar"));
5771 fletcher_4_native(buf, size, NULL, &zc_ref);
5772 fletcher_4_byteswap(buf, size, NULL, &zc_ref_byteswap);
5773
5774 VERIFY0(fletcher_4_impl_set("cycle"));
5775 while (run_count-- > 0) {
5776 zio_cksum_t zc;
5777 zio_cksum_t zc_byteswap;
5778
5779 fletcher_4_byteswap(buf, size, NULL, &zc_byteswap);
5780 fletcher_4_native(buf, size, NULL, &zc);
5781
5782 VERIFY0(bcmp(&zc, &zc_ref, sizeof (zc)));
5783 VERIFY0(bcmp(&zc_byteswap, &zc_ref_byteswap,
5784 sizeof (zc_byteswap)));
5785
5786 /* Test ABD - data */
5787 abd_fletcher_4_byteswap(abd_data, size, NULL,
5788 &zc_byteswap);
5789 abd_fletcher_4_native(abd_data, size, NULL, &zc);
5790
5791 VERIFY0(bcmp(&zc, &zc_ref, sizeof (zc)));
5792 VERIFY0(bcmp(&zc_byteswap, &zc_ref_byteswap,
5793 sizeof (zc_byteswap)));
5794
5795 /* Test ABD - metadata */
5796 abd_fletcher_4_byteswap(abd_meta, size, NULL,
5797 &zc_byteswap);
5798 abd_fletcher_4_native(abd_meta, size, NULL, &zc);
5799
5800 VERIFY0(bcmp(&zc, &zc_ref, sizeof (zc)));
5801 VERIFY0(bcmp(&zc_byteswap, &zc_ref_byteswap,
5802 sizeof (zc_byteswap)));
5803
5804 }
5805
5806 umem_free(buf, size);
5807 abd_free(abd_data);
5808 abd_free(abd_meta);
5809 }
5810 }
5811
5812 void
5813 ztest_fletcher_incr(ztest_ds_t *zd, uint64_t id)
5814 {
5815 void *buf;
5816 size_t size;
5817 int *ptr;
5818 int i;
5819 zio_cksum_t zc_ref;
5820 zio_cksum_t zc_ref_bswap;
5821
5822 hrtime_t end = gethrtime() + NANOSEC;
5823
5824 while (gethrtime() <= end) {
5825 int run_count = 100;
5826
5827 size = ztest_random_blocksize();
5828 buf = umem_alloc(size, UMEM_NOFAIL);
5829
5830 for (i = 0, ptr = buf; i < size / sizeof (*ptr); i++, ptr++)
5831 *ptr = ztest_random(UINT_MAX);
5832
5833 VERIFY0(fletcher_4_impl_set("scalar"));
5834 fletcher_4_native(buf, size, NULL, &zc_ref);
5835 fletcher_4_byteswap(buf, size, NULL, &zc_ref_bswap);
5836
5837 VERIFY0(fletcher_4_impl_set("cycle"));
5838
5839 while (run_count-- > 0) {
5840 zio_cksum_t zc;
5841 zio_cksum_t zc_bswap;
5842 size_t pos = 0;
5843
5844 ZIO_SET_CHECKSUM(&zc, 0, 0, 0, 0);
5845 ZIO_SET_CHECKSUM(&zc_bswap, 0, 0, 0, 0);
5846
5847 while (pos < size) {
5848 size_t inc = 64 * ztest_random(size / 67);
5849 /* sometimes add few bytes to test non-simd */
5850 if (ztest_random(100) < 10)
5851 inc += P2ALIGN(ztest_random(64),
5852 sizeof (uint32_t));
5853
5854 if (inc > (size - pos))
5855 inc = size - pos;
5856
5857 fletcher_4_incremental_native(buf + pos, inc,
5858 &zc);
5859 fletcher_4_incremental_byteswap(buf + pos, inc,
5860 &zc_bswap);
5861
5862 pos += inc;
5863 }
5864
5865 VERIFY3U(pos, ==, size);
5866
5867 VERIFY(ZIO_CHECKSUM_EQUAL(zc, zc_ref));
5868 VERIFY(ZIO_CHECKSUM_EQUAL(zc_bswap, zc_ref_bswap));
5869
5870 /*
5871 * verify if incremental on the whole buffer is
5872 * equivalent to non-incremental version
5873 */
5874 ZIO_SET_CHECKSUM(&zc, 0, 0, 0, 0);
5875 ZIO_SET_CHECKSUM(&zc_bswap, 0, 0, 0, 0);
5876
5877 fletcher_4_incremental_native(buf, size, &zc);
5878 fletcher_4_incremental_byteswap(buf, size, &zc_bswap);
5879
5880 VERIFY(ZIO_CHECKSUM_EQUAL(zc, zc_ref));
5881 VERIFY(ZIO_CHECKSUM_EQUAL(zc_bswap, zc_ref_bswap));
5882 }
5883
5884 umem_free(buf, size);
5885 }
5886 }
5887
5888 static int
5889 ztest_check_path(char *path)
5890 {
5891 struct stat s;
5892 /* return true on success */
5893 return (!stat(path, &s));
5894 }
5895
5896 static void
5897 ztest_get_zdb_bin(char *bin, int len)
5898 {
5899 char *zdb_path;
5900 /*
5901 * Try to use ZDB_PATH and in-tree zdb path. If not successful, just
5902 * let popen to search through PATH.
5903 */
5904 if ((zdb_path = getenv("ZDB_PATH"))) {
5905 strlcpy(bin, zdb_path, len); /* In env */
5906 if (!ztest_check_path(bin)) {
5907 ztest_dump_core = 0;
5908 fatal(1, "invalid ZDB_PATH '%s'", bin);
5909 }
5910 return;
5911 }
5912
5913 VERIFY(realpath(getexecname(), bin) != NULL);
5914 if (strstr(bin, "/ztest/")) {
5915 strstr(bin, "/ztest/")[0] = '\0'; /* In-tree */
5916 strcat(bin, "/zdb/zdb");
5917 if (ztest_check_path(bin))
5918 return;
5919 }
5920 strcpy(bin, "zdb");
5921 }
5922
5923 /*
5924 * Verify pool integrity by running zdb.
5925 */
5926 static void
5927 ztest_run_zdb(char *pool)
5928 {
5929 int status;
5930 char *bin;
5931 char *zdb;
5932 char *zbuf;
5933 const int len = MAXPATHLEN + MAXNAMELEN + 20;
5934 FILE *fp;
5935
5936 bin = umem_alloc(len, UMEM_NOFAIL);
5937 zdb = umem_alloc(len, UMEM_NOFAIL);
5938 zbuf = umem_alloc(1024, UMEM_NOFAIL);
5939
5940 ztest_get_zdb_bin(bin, len);
5941
5942 (void) sprintf(zdb,
5943 "%s -bcc%s%s -G -d -U %s %s",
5944 bin,
5945 ztest_opts.zo_verbose >= 3 ? "s" : "",
5946 ztest_opts.zo_verbose >= 4 ? "v" : "",
5947 spa_config_path,
5948 pool);
5949
5950 if (ztest_opts.zo_verbose >= 5)
5951 (void) printf("Executing %s\n", strstr(zdb, "zdb "));
5952
5953 fp = popen(zdb, "r");
5954
5955 while (fgets(zbuf, 1024, fp) != NULL)
5956 if (ztest_opts.zo_verbose >= 3)
5957 (void) printf("%s", zbuf);
5958
5959 status = pclose(fp);
5960
5961 if (status == 0)
5962 goto out;
5963
5964 ztest_dump_core = 0;
5965 if (WIFEXITED(status))
5966 fatal(0, "'%s' exit code %d", zdb, WEXITSTATUS(status));
5967 else
5968 fatal(0, "'%s' died with signal %d", zdb, WTERMSIG(status));
5969 out:
5970 umem_free(bin, len);
5971 umem_free(zdb, len);
5972 umem_free(zbuf, 1024);
5973 }
5974
5975 static void
5976 ztest_walk_pool_directory(char *header)
5977 {
5978 spa_t *spa = NULL;
5979
5980 if (ztest_opts.zo_verbose >= 6)
5981 (void) printf("%s\n", header);
5982
5983 mutex_enter(&spa_namespace_lock);
5984 while ((spa = spa_next(spa)) != NULL)
5985 if (ztest_opts.zo_verbose >= 6)
5986 (void) printf("\t%s\n", spa_name(spa));
5987 mutex_exit(&spa_namespace_lock);
5988 }
5989
5990 static void
5991 ztest_spa_import_export(char *oldname, char *newname)
5992 {
5993 nvlist_t *config, *newconfig;
5994 uint64_t pool_guid;
5995 spa_t *spa;
5996 int error;
5997
5998 if (ztest_opts.zo_verbose >= 4) {
5999 (void) printf("import/export: old = %s, new = %s\n",
6000 oldname, newname);
6001 }
6002
6003 /*
6004 * Clean up from previous runs.
6005 */
6006 (void) spa_destroy(newname);
6007
6008 /*
6009 * Get the pool's configuration and guid.
6010 */
6011 VERIFY3U(0, ==, spa_open(oldname, &spa, FTAG));
6012
6013 /*
6014 * Kick off a scrub to tickle scrub/export races.
6015 */
6016 if (ztest_random(2) == 0)
6017 (void) spa_scan(spa, POOL_SCAN_SCRUB);
6018
6019 pool_guid = spa_guid(spa);
6020 spa_close(spa, FTAG);
6021
6022 ztest_walk_pool_directory("pools before export");
6023
6024 /*
6025 * Export it.
6026 */
6027 VERIFY3U(0, ==, spa_export(oldname, &config, B_FALSE, B_FALSE));
6028
6029 ztest_walk_pool_directory("pools after export");
6030
6031 /*
6032 * Try to import it.
6033 */
6034 newconfig = spa_tryimport(config);
6035 ASSERT(newconfig != NULL);
6036 nvlist_free(newconfig);
6037
6038 /*
6039 * Import it under the new name.
6040 */
6041 error = spa_import(newname, config, NULL, 0);
6042 if (error != 0) {
6043 dump_nvlist(config, 0);
6044 fatal(B_FALSE, "couldn't import pool %s as %s: error %u",
6045 oldname, newname, error);
6046 }
6047
6048 ztest_walk_pool_directory("pools after import");
6049
6050 /*
6051 * Try to import it again -- should fail with EEXIST.
6052 */
6053 VERIFY3U(EEXIST, ==, spa_import(newname, config, NULL, 0));
6054
6055 /*
6056 * Try to import it under a different name -- should fail with EEXIST.
6057 */
6058 VERIFY3U(EEXIST, ==, spa_import(oldname, config, NULL, 0));
6059
6060 /*
6061 * Verify that the pool is no longer visible under the old name.
6062 */
6063 VERIFY3U(ENOENT, ==, spa_open(oldname, &spa, FTAG));
6064
6065 /*
6066 * Verify that we can open and close the pool using the new name.
6067 */
6068 VERIFY3U(0, ==, spa_open(newname, &spa, FTAG));
6069 ASSERT(pool_guid == spa_guid(spa));
6070 spa_close(spa, FTAG);
6071
6072 nvlist_free(config);
6073 }
6074
6075 static void
6076 ztest_resume(spa_t *spa)
6077 {
6078 if (spa_suspended(spa) && ztest_opts.zo_verbose >= 6)
6079 (void) printf("resuming from suspended state\n");
6080 spa_vdev_state_enter(spa, SCL_NONE);
6081 vdev_clear(spa, NULL);
6082 (void) spa_vdev_state_exit(spa, NULL, 0);
6083 (void) zio_resume(spa);
6084 }
6085
6086 static void *
6087 ztest_resume_thread(void *arg)
6088 {
6089 spa_t *spa = arg;
6090
6091 while (!ztest_exiting) {
6092 if (spa_suspended(spa))
6093 ztest_resume(spa);
6094 (void) poll(NULL, 0, 100);
6095
6096 /*
6097 * Periodically change the zfs_compressed_arc_enabled setting.
6098 */
6099 if (ztest_random(10) == 0)
6100 zfs_compressed_arc_enabled = ztest_random(2);
6101
6102 /*
6103 * Periodically change the zfs_abd_scatter_enabled setting.
6104 */
6105 if (ztest_random(10) == 0)
6106 zfs_abd_scatter_enabled = ztest_random(2);
6107 }
6108
6109 thread_exit();
6110
6111 return (NULL);
6112 }
6113
6114 #define GRACE 300
6115
6116 #if 0
6117 static void
6118 ztest_deadman_alarm(int sig)
6119 {
6120 fatal(0, "failed to complete within %d seconds of deadline", GRACE);
6121 }
6122 #endif
6123
6124 static void
6125 ztest_execute(int test, ztest_info_t *zi, uint64_t id)
6126 {
6127 ztest_ds_t *zd = &ztest_ds[id % ztest_opts.zo_datasets];
6128 ztest_shared_callstate_t *zc = ZTEST_GET_SHARED_CALLSTATE(test);
6129 hrtime_t functime = gethrtime();
6130 int i;
6131
6132 for (i = 0; i < zi->zi_iters; i++)
6133 zi->zi_func(zd, id);
6134
6135 functime = gethrtime() - functime;
6136
6137 atomic_add_64(&zc->zc_count, 1);
6138 atomic_add_64(&zc->zc_time, functime);
6139
6140 if (ztest_opts.zo_verbose >= 4)
6141 (void) printf("%6.2f sec in %s\n",
6142 (double)functime / NANOSEC, zi->zi_funcname);
6143 }
6144
6145 static void *
6146 ztest_thread(void *arg)
6147 {
6148 int rand;
6149 uint64_t id = (uintptr_t)arg;
6150 ztest_shared_t *zs = ztest_shared;
6151 uint64_t call_next;
6152 hrtime_t now;
6153 ztest_info_t *zi;
6154 ztest_shared_callstate_t *zc;
6155
6156 while ((now = gethrtime()) < zs->zs_thread_stop) {
6157 /*
6158 * See if it's time to force a crash.
6159 */
6160 if (now > zs->zs_thread_kill)
6161 ztest_kill(zs);
6162
6163 /*
6164 * If we're getting ENOSPC with some regularity, stop.
6165 */
6166 if (zs->zs_enospc_count > 10)
6167 break;
6168
6169 /*
6170 * Pick a random function to execute.
6171 */
6172 rand = ztest_random(ZTEST_FUNCS);
6173 zi = &ztest_info[rand];
6174 zc = ZTEST_GET_SHARED_CALLSTATE(rand);
6175 call_next = zc->zc_next;
6176
6177 if (now >= call_next &&
6178 atomic_cas_64(&zc->zc_next, call_next, call_next +
6179 ztest_random(2 * zi->zi_interval[0] + 1)) == call_next) {
6180 ztest_execute(rand, zi, id);
6181 }
6182 }
6183
6184 thread_exit();
6185
6186 return (NULL);
6187 }
6188
6189 static void
6190 ztest_dataset_name(char *dsname, char *pool, int d)
6191 {
6192 (void) snprintf(dsname, ZFS_MAX_DATASET_NAME_LEN, "%s/ds_%d", pool, d);
6193 }
6194
6195 static void
6196 ztest_dataset_destroy(int d)
6197 {
6198 char name[ZFS_MAX_DATASET_NAME_LEN];
6199 int t;
6200
6201 ztest_dataset_name(name, ztest_opts.zo_pool, d);
6202
6203 if (ztest_opts.zo_verbose >= 3)
6204 (void) printf("Destroying %s to free up space\n", name);
6205
6206 /*
6207 * Cleanup any non-standard clones and snapshots. In general,
6208 * ztest thread t operates on dataset (t % zopt_datasets),
6209 * so there may be more than one thing to clean up.
6210 */
6211 for (t = d; t < ztest_opts.zo_threads;
6212 t += ztest_opts.zo_datasets)
6213 ztest_dsl_dataset_cleanup(name, t);
6214
6215 (void) dmu_objset_find(name, ztest_objset_destroy_cb, NULL,
6216 DS_FIND_SNAPSHOTS | DS_FIND_CHILDREN);
6217 }
6218
6219 static void
6220 ztest_dataset_dirobj_verify(ztest_ds_t *zd)
6221 {
6222 uint64_t usedobjs, dirobjs, scratch;
6223
6224 /*
6225 * ZTEST_DIROBJ is the object directory for the entire dataset.
6226 * Therefore, the number of objects in use should equal the
6227 * number of ZTEST_DIROBJ entries, +1 for ZTEST_DIROBJ itself.
6228 * If not, we have an object leak.
6229 *
6230 * Note that we can only check this in ztest_dataset_open(),
6231 * when the open-context and syncing-context values agree.
6232 * That's because zap_count() returns the open-context value,
6233 * while dmu_objset_space() returns the rootbp fill count.
6234 */
6235 VERIFY3U(0, ==, zap_count(zd->zd_os, ZTEST_DIROBJ, &dirobjs));
6236 dmu_objset_space(zd->zd_os, &scratch, &scratch, &usedobjs, &scratch);
6237 ASSERT3U(dirobjs + 1, ==, usedobjs);
6238 }
6239
6240 static int
6241 ztest_dataset_open(int d)
6242 {
6243 ztest_ds_t *zd = &ztest_ds[d];
6244 uint64_t committed_seq = ZTEST_GET_SHARED_DS(d)->zd_seq;
6245 objset_t *os;
6246 zilog_t *zilog;
6247 char name[ZFS_MAX_DATASET_NAME_LEN];
6248 int error;
6249
6250 ztest_dataset_name(name, ztest_opts.zo_pool, d);
6251
6252 (void) rw_rdlock(&ztest_name_lock);
6253
6254 error = ztest_dataset_create(name);
6255 if (error == ENOSPC) {
6256 (void) rw_unlock(&ztest_name_lock);
6257 ztest_record_enospc(FTAG);
6258 return (error);
6259 }
6260 ASSERT(error == 0 || error == EEXIST);
6261
6262 VERIFY0(dmu_objset_own(name, DMU_OST_OTHER, B_FALSE, zd, &os));
6263 (void) rw_unlock(&ztest_name_lock);
6264
6265 ztest_zd_init(zd, ZTEST_GET_SHARED_DS(d), os);
6266
6267 zilog = zd->zd_zilog;
6268
6269 if (zilog->zl_header->zh_claim_lr_seq != 0 &&
6270 zilog->zl_header->zh_claim_lr_seq < committed_seq)
6271 fatal(0, "missing log records: claimed %llu < committed %llu",
6272 zilog->zl_header->zh_claim_lr_seq, committed_seq);
6273
6274 ztest_dataset_dirobj_verify(zd);
6275
6276 zil_replay(os, zd, ztest_replay_vector);
6277
6278 ztest_dataset_dirobj_verify(zd);
6279
6280 if (ztest_opts.zo_verbose >= 6)
6281 (void) printf("%s replay %llu blocks, %llu records, seq %llu\n",
6282 zd->zd_name,
6283 (u_longlong_t)zilog->zl_parse_blk_count,
6284 (u_longlong_t)zilog->zl_parse_lr_count,
6285 (u_longlong_t)zilog->zl_replaying_seq);
6286
6287 zilog = zil_open(os, ztest_get_data);
6288
6289 if (zilog->zl_replaying_seq != 0 &&
6290 zilog->zl_replaying_seq < committed_seq)
6291 fatal(0, "missing log records: replayed %llu < committed %llu",
6292 zilog->zl_replaying_seq, committed_seq);
6293
6294 return (0);
6295 }
6296
6297 static void
6298 ztest_dataset_close(int d)
6299 {
6300 ztest_ds_t *zd = &ztest_ds[d];
6301
6302 zil_close(zd->zd_zilog);
6303 dmu_objset_disown(zd->zd_os, zd);
6304
6305 ztest_zd_fini(zd);
6306 }
6307
6308 /*
6309 * Kick off threads to run tests on all datasets in parallel.
6310 */
6311 static void
6312 ztest_run(ztest_shared_t *zs)
6313 {
6314 kt_did_t *tid;
6315 spa_t *spa;
6316 objset_t *os;
6317 kthread_t *resume_thread;
6318 uint64_t object;
6319 int error;
6320 int t, d;
6321
6322 ztest_exiting = B_FALSE;
6323
6324 /*
6325 * Initialize parent/child shared state.
6326 */
6327 mutex_init(&ztest_vdev_lock, NULL, MUTEX_DEFAULT, NULL);
6328 VERIFY(rwlock_init(&ztest_name_lock, USYNC_THREAD, NULL) == 0);
6329
6330 zs->zs_thread_start = gethrtime();
6331 zs->zs_thread_stop =
6332 zs->zs_thread_start + ztest_opts.zo_passtime * NANOSEC;
6333 zs->zs_thread_stop = MIN(zs->zs_thread_stop, zs->zs_proc_stop);
6334 zs->zs_thread_kill = zs->zs_thread_stop;
6335 if (ztest_random(100) < ztest_opts.zo_killrate) {
6336 zs->zs_thread_kill -=
6337 ztest_random(ztest_opts.zo_passtime * NANOSEC);
6338 }
6339
6340 mutex_init(&zcl.zcl_callbacks_lock, NULL, MUTEX_DEFAULT, NULL);
6341
6342 list_create(&zcl.zcl_callbacks, sizeof (ztest_cb_data_t),
6343 offsetof(ztest_cb_data_t, zcd_node));
6344
6345 /*
6346 * Open our pool.
6347 */
6348 kernel_init(FREAD | FWRITE);
6349 VERIFY0(spa_open(ztest_opts.zo_pool, &spa, FTAG));
6350 spa->spa_debug = B_TRUE;
6351 metaslab_preload_limit = ztest_random(20) + 1;
6352 ztest_spa = spa;
6353
6354 dmu_objset_stats_t dds;
6355 VERIFY0(dmu_objset_own(ztest_opts.zo_pool,
6356 DMU_OST_ANY, B_TRUE, FTAG, &os));
6357 dsl_pool_config_enter(dmu_objset_pool(os), FTAG);
6358 dmu_objset_fast_stat(os, &dds);
6359 dsl_pool_config_exit(dmu_objset_pool(os), FTAG);
6360 zs->zs_guid = dds.dds_guid;
6361 dmu_objset_disown(os, FTAG);
6362
6363 spa->spa_dedup_ditto = 2 * ZIO_DEDUPDITTO_MIN;
6364
6365 /*
6366 * We don't expect the pool to suspend unless maxfaults == 0,
6367 * in which case ztest_fault_inject() temporarily takes away
6368 * the only valid replica.
6369 */
6370 if (MAXFAULTS() == 0)
6371 spa->spa_failmode = ZIO_FAILURE_MODE_WAIT;
6372 else
6373 spa->spa_failmode = ZIO_FAILURE_MODE_PANIC;
6374
6375 /*
6376 * Create a thread to periodically resume suspended I/O.
6377 */
6378 VERIFY3P((resume_thread = zk_thread_create(NULL, 0,
6379 (thread_func_t)ztest_resume_thread, spa, 0, NULL, TS_RUN, 0,
6380 PTHREAD_CREATE_JOINABLE)), !=, NULL);
6381
6382 #if 0
6383 /*
6384 * Set a deadman alarm to abort() if we hang.
6385 */
6386 signal(SIGALRM, ztest_deadman_alarm);
6387 alarm((zs->zs_thread_stop - zs->zs_thread_start) / NANOSEC + GRACE);
6388 #endif
6389
6390 /*
6391 * Verify that we can safely inquire about about any object,
6392 * whether it's allocated or not. To make it interesting,
6393 * we probe a 5-wide window around each power of two.
6394 * This hits all edge cases, including zero and the max.
6395 */
6396 for (t = 0; t < 64; t++) {
6397 for (d = -5; d <= 5; d++) {
6398 error = dmu_object_info(spa->spa_meta_objset,
6399 (1ULL << t) + d, NULL);
6400 ASSERT(error == 0 || error == ENOENT ||
6401 error == EINVAL);
6402 }
6403 }
6404
6405 /*
6406 * If we got any ENOSPC errors on the previous run, destroy something.
6407 */
6408 if (zs->zs_enospc_count != 0) {
6409 int d = ztest_random(ztest_opts.zo_datasets);
6410 ztest_dataset_destroy(d);
6411 }
6412 zs->zs_enospc_count = 0;
6413
6414 tid = umem_zalloc(ztest_opts.zo_threads * sizeof (kt_did_t),
6415 UMEM_NOFAIL);
6416
6417 if (ztest_opts.zo_verbose >= 4)
6418 (void) printf("starting main threads...\n");
6419
6420 /*
6421 * Kick off all the tests that run in parallel.
6422 */
6423 for (t = 0; t < ztest_opts.zo_threads; t++) {
6424 kthread_t *thread;
6425
6426 if (t < ztest_opts.zo_datasets &&
6427 ztest_dataset_open(t) != 0) {
6428 umem_free(tid,
6429 ztest_opts.zo_threads * sizeof (kt_did_t));
6430 return;
6431 }
6432
6433 VERIFY3P(thread = zk_thread_create(NULL, 0,
6434 (thread_func_t)ztest_thread,
6435 (void *)(uintptr_t)t, 0, NULL, TS_RUN, 0,
6436 PTHREAD_CREATE_JOINABLE), !=, NULL);
6437 tid[t] = thread->t_tid;
6438 }
6439
6440 /*
6441 * Wait for all of the tests to complete. We go in reverse order
6442 * so we don't close datasets while threads are still using them.
6443 */
6444 for (t = ztest_opts.zo_threads - 1; t >= 0; t--) {
6445 thread_join(tid[t]);
6446 if (t < ztest_opts.zo_datasets)
6447 ztest_dataset_close(t);
6448 }
6449
6450 txg_wait_synced(spa_get_dsl(spa), 0);
6451
6452 zs->zs_alloc = metaslab_class_get_alloc(spa_normal_class(spa));
6453 zs->zs_space = metaslab_class_get_space(spa_normal_class(spa));
6454
6455 umem_free(tid, ztest_opts.zo_threads * sizeof (kt_did_t));
6456
6457 /* Kill the resume thread */
6458 ztest_exiting = B_TRUE;
6459 thread_join(resume_thread->t_tid);
6460 ztest_resume(spa);
6461
6462 /*
6463 * Right before closing the pool, kick off a bunch of async I/O;
6464 * spa_close() should wait for it to complete.
6465 */
6466 for (object = 1; object < 50; object++) {
6467 dmu_prefetch(spa->spa_meta_objset, object, 0, 0, 1ULL << 20,
6468 ZIO_PRIORITY_SYNC_READ);
6469 }
6470
6471 /* Verify that at least one commit cb was called in a timely fashion */
6472 if (zc_cb_counter >= ZTEST_COMMIT_CB_MIN_REG)
6473 VERIFY0(zc_min_txg_delay);
6474
6475 spa_close(spa, FTAG);
6476
6477 /*
6478 * Verify that we can loop over all pools.
6479 */
6480 mutex_enter(&spa_namespace_lock);
6481 for (spa = spa_next(NULL); spa != NULL; spa = spa_next(spa))
6482 if (ztest_opts.zo_verbose > 3)
6483 (void) printf("spa_next: found %s\n", spa_name(spa));
6484 mutex_exit(&spa_namespace_lock);
6485
6486 /*
6487 * Verify that we can export the pool and reimport it under a
6488 * different name.
6489 */
6490 if ((ztest_random(2) == 0) && !ztest_opts.zo_mmp_test) {
6491 char name[ZFS_MAX_DATASET_NAME_LEN];
6492 (void) snprintf(name, sizeof (name), "%s_import",
6493 ztest_opts.zo_pool);
6494 ztest_spa_import_export(ztest_opts.zo_pool, name);
6495 ztest_spa_import_export(name, ztest_opts.zo_pool);
6496 }
6497
6498 kernel_fini();
6499
6500 list_destroy(&zcl.zcl_callbacks);
6501 mutex_destroy(&zcl.zcl_callbacks_lock);
6502 (void) rwlock_destroy(&ztest_name_lock);
6503 mutex_destroy(&ztest_vdev_lock);
6504 }
6505
6506 static void
6507 ztest_freeze(void)
6508 {
6509 ztest_ds_t *zd = &ztest_ds[0];
6510 spa_t *spa;
6511 int numloops = 0;
6512
6513 if (ztest_opts.zo_verbose >= 3)
6514 (void) printf("testing spa_freeze()...\n");
6515
6516 kernel_init(FREAD | FWRITE);
6517 VERIFY3U(0, ==, spa_open(ztest_opts.zo_pool, &spa, FTAG));
6518 VERIFY3U(0, ==, ztest_dataset_open(0));
6519 spa->spa_debug = B_TRUE;
6520 ztest_spa = spa;
6521
6522 /*
6523 * Force the first log block to be transactionally allocated.
6524 * We have to do this before we freeze the pool -- otherwise
6525 * the log chain won't be anchored.
6526 */
6527 while (BP_IS_HOLE(&zd->zd_zilog->zl_header->zh_log)) {
6528 ztest_dmu_object_alloc_free(zd, 0);
6529 zil_commit(zd->zd_zilog, 0);
6530 }
6531
6532 txg_wait_synced(spa_get_dsl(spa), 0);
6533
6534 /*
6535 * Freeze the pool. This stops spa_sync() from doing anything,
6536 * so that the only way to record changes from now on is the ZIL.
6537 */
6538 spa_freeze(spa);
6539
6540 /*
6541 * Because it is hard to predict how much space a write will actually
6542 * require beforehand, we leave ourselves some fudge space to write over
6543 * capacity.
6544 */
6545 uint64_t capacity = metaslab_class_get_space(spa_normal_class(spa)) / 2;
6546
6547 /*
6548 * Run tests that generate log records but don't alter the pool config
6549 * or depend on DSL sync tasks (snapshots, objset create/destroy, etc).
6550 * We do a txg_wait_synced() after each iteration to force the txg
6551 * to increase well beyond the last synced value in the uberblock.
6552 * The ZIL should be OK with that.
6553 *
6554 * Run a random number of times less than zo_maxloops and ensure we do
6555 * not run out of space on the pool.
6556 */
6557 while (ztest_random(10) != 0 &&
6558 numloops++ < ztest_opts.zo_maxloops &&
6559 metaslab_class_get_alloc(spa_normal_class(spa)) < capacity) {
6560 ztest_od_t od;
6561 ztest_od_init(&od, 0, FTAG, 0, DMU_OT_UINT64_OTHER, 0, 0, 0);
6562 VERIFY0(ztest_object_init(zd, &od, sizeof (od), B_FALSE));
6563 ztest_io(zd, od.od_object,
6564 ztest_random(ZTEST_RANGE_LOCKS) << SPA_MAXBLOCKSHIFT);
6565 txg_wait_synced(spa_get_dsl(spa), 0);
6566 }
6567
6568 /*
6569 * Commit all of the changes we just generated.
6570 */
6571 zil_commit(zd->zd_zilog, 0);
6572 txg_wait_synced(spa_get_dsl(spa), 0);
6573
6574 /*
6575 * Close our dataset and close the pool.
6576 */
6577 ztest_dataset_close(0);
6578 spa_close(spa, FTAG);
6579 kernel_fini();
6580
6581 /*
6582 * Open and close the pool and dataset to induce log replay.
6583 */
6584 kernel_init(FREAD | FWRITE);
6585 VERIFY3U(0, ==, spa_open(ztest_opts.zo_pool, &spa, FTAG));
6586 ASSERT(spa_freeze_txg(spa) == UINT64_MAX);
6587 VERIFY3U(0, ==, ztest_dataset_open(0));
6588 ztest_dataset_close(0);
6589
6590 spa->spa_debug = B_TRUE;
6591 ztest_spa = spa;
6592 txg_wait_synced(spa_get_dsl(spa), 0);
6593 ztest_reguid(NULL, 0);
6594
6595 spa_close(spa, FTAG);
6596 kernel_fini();
6597 }
6598
6599 void
6600 print_time(hrtime_t t, char *timebuf)
6601 {
6602 hrtime_t s = t / NANOSEC;
6603 hrtime_t m = s / 60;
6604 hrtime_t h = m / 60;
6605 hrtime_t d = h / 24;
6606
6607 s -= m * 60;
6608 m -= h * 60;
6609 h -= d * 24;
6610
6611 timebuf[0] = '\0';
6612
6613 if (d)
6614 (void) sprintf(timebuf,
6615 "%llud%02lluh%02llum%02llus", d, h, m, s);
6616 else if (h)
6617 (void) sprintf(timebuf, "%lluh%02llum%02llus", h, m, s);
6618 else if (m)
6619 (void) sprintf(timebuf, "%llum%02llus", m, s);
6620 else
6621 (void) sprintf(timebuf, "%llus", s);
6622 }
6623
6624 static nvlist_t *
6625 make_random_props(void)
6626 {
6627 nvlist_t *props;
6628
6629 VERIFY(nvlist_alloc(&props, NV_UNIQUE_NAME, 0) == 0);
6630 if (ztest_random(2) == 0)
6631 return (props);
6632 VERIFY(nvlist_add_uint64(props, "autoreplace", 1) == 0);
6633
6634 return (props);
6635 }
6636
6637 /*
6638 * Import a storage pool with the given name.
6639 */
6640 static void
6641 ztest_import(ztest_shared_t *zs)
6642 {
6643 libzfs_handle_t *hdl;
6644 importargs_t args = { 0 };
6645 spa_t *spa;
6646 nvlist_t *cfg = NULL;
6647 int nsearch = 1;
6648 char *searchdirs[nsearch];
6649 char *name = ztest_opts.zo_pool;
6650 int flags = ZFS_IMPORT_MISSING_LOG;
6651 int error;
6652
6653 mutex_init(&ztest_vdev_lock, NULL, MUTEX_DEFAULT, NULL);
6654 VERIFY(rwlock_init(&ztest_name_lock, USYNC_THREAD, NULL) == 0);
6655
6656 kernel_init(FREAD | FWRITE);
6657 hdl = libzfs_init();
6658
6659 searchdirs[0] = ztest_opts.zo_dir;
6660 args.paths = nsearch;
6661 args.path = searchdirs;
6662 args.can_be_active = B_FALSE;
6663
6664 error = zpool_tryimport(hdl, name, &cfg, &args);
6665 if (error)
6666 (void) fatal(0, "No pools found\n");
6667
6668 VERIFY0(spa_import(name, cfg, NULL, flags));
6669 VERIFY0(spa_open(name, &spa, FTAG));
6670 zs->zs_metaslab_sz =
6671 1ULL << spa->spa_root_vdev->vdev_child[0]->vdev_ms_shift;
6672 spa_close(spa, FTAG);
6673
6674 libzfs_fini(hdl);
6675 kernel_fini();
6676
6677 if (!ztest_opts.zo_mmp_test) {
6678 ztest_run_zdb(ztest_opts.zo_pool);
6679 ztest_freeze();
6680 ztest_run_zdb(ztest_opts.zo_pool);
6681 }
6682
6683 (void) rwlock_destroy(&ztest_name_lock);
6684 mutex_destroy(&ztest_vdev_lock);
6685 }
6686
6687 /*
6688 * Create a storage pool with the given name and initial vdev size.
6689 * Then test spa_freeze() functionality.
6690 */
6691 static void
6692 ztest_init(ztest_shared_t *zs)
6693 {
6694 spa_t *spa;
6695 nvlist_t *nvroot, *props;
6696 int i;
6697
6698 mutex_init(&ztest_vdev_lock, NULL, MUTEX_DEFAULT, NULL);
6699 VERIFY(rwlock_init(&ztest_name_lock, USYNC_THREAD, NULL) == 0);
6700
6701 kernel_init(FREAD | FWRITE);
6702
6703 /*
6704 * Create the storage pool.
6705 */
6706 (void) spa_destroy(ztest_opts.zo_pool);
6707 ztest_shared->zs_vdev_next_leaf = 0;
6708 zs->zs_splits = 0;
6709 zs->zs_mirrors = ztest_opts.zo_mirrors;
6710 nvroot = make_vdev_root(NULL, NULL, NULL, ztest_opts.zo_vdev_size, 0,
6711 0, ztest_opts.zo_raidz, zs->zs_mirrors, 1);
6712 props = make_random_props();
6713 for (i = 0; i < SPA_FEATURES; i++) {
6714 char *buf;
6715 VERIFY3S(-1, !=, asprintf(&buf, "feature@%s",
6716 spa_feature_table[i].fi_uname));
6717 VERIFY3U(0, ==, nvlist_add_uint64(props, buf, 0));
6718 free(buf);
6719 }
6720 VERIFY3U(0, ==, spa_create(ztest_opts.zo_pool, nvroot, props, NULL));
6721 nvlist_free(nvroot);
6722 nvlist_free(props);
6723
6724 VERIFY3U(0, ==, spa_open(ztest_opts.zo_pool, &spa, FTAG));
6725 zs->zs_metaslab_sz =
6726 1ULL << spa->spa_root_vdev->vdev_child[0]->vdev_ms_shift;
6727 spa_close(spa, FTAG);
6728
6729 kernel_fini();
6730
6731 if (!ztest_opts.zo_mmp_test) {
6732 ztest_run_zdb(ztest_opts.zo_pool);
6733 ztest_freeze();
6734 ztest_run_zdb(ztest_opts.zo_pool);
6735 }
6736
6737 (void) rwlock_destroy(&ztest_name_lock);
6738 mutex_destroy(&ztest_vdev_lock);
6739 }
6740
6741 static void
6742 setup_data_fd(void)
6743 {
6744 static char ztest_name_data[] = "/tmp/ztest.data.XXXXXX";
6745
6746 ztest_fd_data = mkstemp(ztest_name_data);
6747 ASSERT3S(ztest_fd_data, >=, 0);
6748 (void) unlink(ztest_name_data);
6749 }
6750
6751 static int
6752 shared_data_size(ztest_shared_hdr_t *hdr)
6753 {
6754 int size;
6755
6756 size = hdr->zh_hdr_size;
6757 size += hdr->zh_opts_size;
6758 size += hdr->zh_size;
6759 size += hdr->zh_stats_size * hdr->zh_stats_count;
6760 size += hdr->zh_ds_size * hdr->zh_ds_count;
6761
6762 return (size);
6763 }
6764
6765 static void
6766 setup_hdr(void)
6767 {
6768 int size;
6769 ztest_shared_hdr_t *hdr;
6770
6771 hdr = (void *)mmap(0, P2ROUNDUP(sizeof (*hdr), getpagesize()),
6772 PROT_READ | PROT_WRITE, MAP_SHARED, ztest_fd_data, 0);
6773 ASSERT(hdr != MAP_FAILED);
6774
6775 VERIFY3U(0, ==, ftruncate(ztest_fd_data, sizeof (ztest_shared_hdr_t)));
6776
6777 hdr->zh_hdr_size = sizeof (ztest_shared_hdr_t);
6778 hdr->zh_opts_size = sizeof (ztest_shared_opts_t);
6779 hdr->zh_size = sizeof (ztest_shared_t);
6780 hdr->zh_stats_size = sizeof (ztest_shared_callstate_t);
6781 hdr->zh_stats_count = ZTEST_FUNCS;
6782 hdr->zh_ds_size = sizeof (ztest_shared_ds_t);
6783 hdr->zh_ds_count = ztest_opts.zo_datasets;
6784
6785 size = shared_data_size(hdr);
6786 VERIFY3U(0, ==, ftruncate(ztest_fd_data, size));
6787
6788 (void) munmap((caddr_t)hdr, P2ROUNDUP(sizeof (*hdr), getpagesize()));
6789 }
6790
6791 static void
6792 setup_data(void)
6793 {
6794 int size, offset;
6795 ztest_shared_hdr_t *hdr;
6796 uint8_t *buf;
6797
6798 hdr = (void *)mmap(0, P2ROUNDUP(sizeof (*hdr), getpagesize()),
6799 PROT_READ, MAP_SHARED, ztest_fd_data, 0);
6800 ASSERT(hdr != MAP_FAILED);
6801
6802 size = shared_data_size(hdr);
6803
6804 (void) munmap((caddr_t)hdr, P2ROUNDUP(sizeof (*hdr), getpagesize()));
6805 hdr = ztest_shared_hdr = (void *)mmap(0, P2ROUNDUP(size, getpagesize()),
6806 PROT_READ | PROT_WRITE, MAP_SHARED, ztest_fd_data, 0);
6807 ASSERT(hdr != MAP_FAILED);
6808 buf = (uint8_t *)hdr;
6809
6810 offset = hdr->zh_hdr_size;
6811 ztest_shared_opts = (void *)&buf[offset];
6812 offset += hdr->zh_opts_size;
6813 ztest_shared = (void *)&buf[offset];
6814 offset += hdr->zh_size;
6815 ztest_shared_callstate = (void *)&buf[offset];
6816 offset += hdr->zh_stats_size * hdr->zh_stats_count;
6817 ztest_shared_ds = (void *)&buf[offset];
6818 }
6819
6820 static boolean_t
6821 exec_child(char *cmd, char *libpath, boolean_t ignorekill, int *statusp)
6822 {
6823 pid_t pid;
6824 int status;
6825 char *cmdbuf = NULL;
6826
6827 pid = fork();
6828
6829 if (cmd == NULL) {
6830 cmdbuf = umem_alloc(MAXPATHLEN, UMEM_NOFAIL);
6831 (void) strlcpy(cmdbuf, getexecname(), MAXPATHLEN);
6832 cmd = cmdbuf;
6833 }
6834
6835 if (pid == -1)
6836 fatal(1, "fork failed");
6837
6838 if (pid == 0) { /* child */
6839 char *emptyargv[2] = { cmd, NULL };
6840 char fd_data_str[12];
6841
6842 struct rlimit rl = { 1024, 1024 };
6843 (void) setrlimit(RLIMIT_NOFILE, &rl);
6844
6845 (void) close(ztest_fd_rand);
6846 VERIFY(11 >= snprintf(fd_data_str, 12, "%d", ztest_fd_data));
6847 VERIFY(0 == setenv("ZTEST_FD_DATA", fd_data_str, 1));
6848
6849 (void) enable_extended_FILE_stdio(-1, -1);
6850 if (libpath != NULL)
6851 VERIFY(0 == setenv("LD_LIBRARY_PATH", libpath, 1));
6852 (void) execv(cmd, emptyargv);
6853 ztest_dump_core = B_FALSE;
6854 fatal(B_TRUE, "exec failed: %s", cmd);
6855 }
6856
6857 if (cmdbuf != NULL) {
6858 umem_free(cmdbuf, MAXPATHLEN);
6859 cmd = NULL;
6860 }
6861
6862 while (waitpid(pid, &status, 0) != pid)
6863 continue;
6864 if (statusp != NULL)
6865 *statusp = status;
6866
6867 if (WIFEXITED(status)) {
6868 if (WEXITSTATUS(status) != 0) {
6869 (void) fprintf(stderr, "child exited with code %d\n",
6870 WEXITSTATUS(status));
6871 exit(2);
6872 }
6873 return (B_FALSE);
6874 } else if (WIFSIGNALED(status)) {
6875 if (!ignorekill || WTERMSIG(status) != SIGKILL) {
6876 (void) fprintf(stderr, "child died with signal %d\n",
6877 WTERMSIG(status));
6878 exit(3);
6879 }
6880 return (B_TRUE);
6881 } else {
6882 (void) fprintf(stderr, "something strange happened to child\n");
6883 exit(4);
6884 /* NOTREACHED */
6885 }
6886 }
6887
6888 static void
6889 ztest_run_init(void)
6890 {
6891 int i;
6892
6893 ztest_shared_t *zs = ztest_shared;
6894
6895 /*
6896 * Blow away any existing copy of zpool.cache
6897 */
6898 (void) remove(spa_config_path);
6899
6900 if (ztest_opts.zo_init == 0) {
6901 if (ztest_opts.zo_verbose >= 1)
6902 (void) printf("Importing pool %s\n",
6903 ztest_opts.zo_pool);
6904 ztest_import(zs);
6905 return;
6906 }
6907
6908 /*
6909 * Create and initialize our storage pool.
6910 */
6911 for (i = 1; i <= ztest_opts.zo_init; i++) {
6912 bzero(zs, sizeof (ztest_shared_t));
6913 if (ztest_opts.zo_verbose >= 3 &&
6914 ztest_opts.zo_init != 1) {
6915 (void) printf("ztest_init(), pass %d\n", i);
6916 }
6917 ztest_init(zs);
6918 }
6919 }
6920
6921 int
6922 main(int argc, char **argv)
6923 {
6924 int kills = 0;
6925 int iters = 0;
6926 int older = 0;
6927 int newer = 0;
6928 ztest_shared_t *zs;
6929 ztest_info_t *zi;
6930 ztest_shared_callstate_t *zc;
6931 char timebuf[100];
6932 char numbuf[6];
6933 spa_t *spa;
6934 char *cmd;
6935 boolean_t hasalt;
6936 int f;
6937 char *fd_data_str = getenv("ZTEST_FD_DATA");
6938 struct sigaction action;
6939
6940 (void) setvbuf(stdout, NULL, _IOLBF, 0);
6941
6942 dprintf_setup(&argc, argv);
6943
6944 action.sa_handler = sig_handler;
6945 sigemptyset(&action.sa_mask);
6946 action.sa_flags = 0;
6947
6948 if (sigaction(SIGSEGV, &action, NULL) < 0) {
6949 (void) fprintf(stderr, "ztest: cannot catch SIGSEGV: %s.\n",
6950 strerror(errno));
6951 exit(EXIT_FAILURE);
6952 }
6953
6954 if (sigaction(SIGABRT, &action, NULL) < 0) {
6955 (void) fprintf(stderr, "ztest: cannot catch SIGABRT: %s.\n",
6956 strerror(errno));
6957 exit(EXIT_FAILURE);
6958 }
6959
6960 ztest_fd_rand = open("/dev/urandom", O_RDONLY);
6961 ASSERT3S(ztest_fd_rand, >=, 0);
6962
6963 if (!fd_data_str) {
6964 process_options(argc, argv);
6965
6966 setup_data_fd();
6967 setup_hdr();
6968 setup_data();
6969 bcopy(&ztest_opts, ztest_shared_opts,
6970 sizeof (*ztest_shared_opts));
6971 } else {
6972 ztest_fd_data = atoi(fd_data_str);
6973 setup_data();
6974 bcopy(ztest_shared_opts, &ztest_opts, sizeof (ztest_opts));
6975 }
6976 ASSERT3U(ztest_opts.zo_datasets, ==, ztest_shared_hdr->zh_ds_count);
6977
6978 /* Override location of zpool.cache */
6979 VERIFY(asprintf((char **)&spa_config_path, "%s/zpool.cache",
6980 ztest_opts.zo_dir) != -1);
6981
6982 ztest_ds = umem_alloc(ztest_opts.zo_datasets * sizeof (ztest_ds_t),
6983 UMEM_NOFAIL);
6984 zs = ztest_shared;
6985
6986 if (fd_data_str) {
6987 metaslab_gang_bang = ztest_opts.zo_metaslab_gang_bang;
6988 metaslab_df_alloc_threshold =
6989 zs->zs_metaslab_df_alloc_threshold;
6990
6991 if (zs->zs_do_init)
6992 ztest_run_init();
6993 else
6994 ztest_run(zs);
6995 exit(0);
6996 }
6997
6998 hasalt = (strlen(ztest_opts.zo_alt_ztest) != 0);
6999
7000 if (ztest_opts.zo_verbose >= 1) {
7001 (void) printf("%llu vdevs, %d datasets, %d threads,"
7002 " %llu seconds...\n",
7003 (u_longlong_t)ztest_opts.zo_vdevs,
7004 ztest_opts.zo_datasets,
7005 ztest_opts.zo_threads,
7006 (u_longlong_t)ztest_opts.zo_time);
7007 }
7008
7009 cmd = umem_alloc(MAXNAMELEN, UMEM_NOFAIL);
7010 (void) strlcpy(cmd, getexecname(), MAXNAMELEN);
7011
7012 zs->zs_do_init = B_TRUE;
7013 if (strlen(ztest_opts.zo_alt_ztest) != 0) {
7014 if (ztest_opts.zo_verbose >= 1) {
7015 (void) printf("Executing older ztest for "
7016 "initialization: %s\n", ztest_opts.zo_alt_ztest);
7017 }
7018 VERIFY(!exec_child(ztest_opts.zo_alt_ztest,
7019 ztest_opts.zo_alt_libpath, B_FALSE, NULL));
7020 } else {
7021 VERIFY(!exec_child(NULL, NULL, B_FALSE, NULL));
7022 }
7023 zs->zs_do_init = B_FALSE;
7024
7025 zs->zs_proc_start = gethrtime();
7026 zs->zs_proc_stop = zs->zs_proc_start + ztest_opts.zo_time * NANOSEC;
7027
7028 for (f = 0; f < ZTEST_FUNCS; f++) {
7029 zi = &ztest_info[f];
7030 zc = ZTEST_GET_SHARED_CALLSTATE(f);
7031 if (zs->zs_proc_start + zi->zi_interval[0] > zs->zs_proc_stop)
7032 zc->zc_next = UINT64_MAX;
7033 else
7034 zc->zc_next = zs->zs_proc_start +
7035 ztest_random(2 * zi->zi_interval[0] + 1);
7036 }
7037
7038 /*
7039 * Run the tests in a loop. These tests include fault injection
7040 * to verify that self-healing data works, and forced crashes
7041 * to verify that we never lose on-disk consistency.
7042 */
7043 while (gethrtime() < zs->zs_proc_stop) {
7044 int status;
7045 boolean_t killed;
7046
7047 /*
7048 * Initialize the workload counters for each function.
7049 */
7050 for (f = 0; f < ZTEST_FUNCS; f++) {
7051 zc = ZTEST_GET_SHARED_CALLSTATE(f);
7052 zc->zc_count = 0;
7053 zc->zc_time = 0;
7054 }
7055
7056 /* Set the allocation switch size */
7057 zs->zs_metaslab_df_alloc_threshold =
7058 ztest_random(zs->zs_metaslab_sz / 4) + 1;
7059
7060 if (!hasalt || ztest_random(2) == 0) {
7061 if (hasalt && ztest_opts.zo_verbose >= 1) {
7062 (void) printf("Executing newer ztest: %s\n",
7063 cmd);
7064 }
7065 newer++;
7066 killed = exec_child(cmd, NULL, B_TRUE, &status);
7067 } else {
7068 if (hasalt && ztest_opts.zo_verbose >= 1) {
7069 (void) printf("Executing older ztest: %s\n",
7070 ztest_opts.zo_alt_ztest);
7071 }
7072 older++;
7073 killed = exec_child(ztest_opts.zo_alt_ztest,
7074 ztest_opts.zo_alt_libpath, B_TRUE, &status);
7075 }
7076
7077 if (killed)
7078 kills++;
7079 iters++;
7080
7081 if (ztest_opts.zo_verbose >= 1) {
7082 hrtime_t now = gethrtime();
7083
7084 now = MIN(now, zs->zs_proc_stop);
7085 print_time(zs->zs_proc_stop - now, timebuf);
7086 nicenum(zs->zs_space, numbuf);
7087
7088 (void) printf("Pass %3d, %8s, %3llu ENOSPC, "
7089 "%4.1f%% of %5s used, %3.0f%% done, %8s to go\n",
7090 iters,
7091 WIFEXITED(status) ? "Complete" : "SIGKILL",
7092 (u_longlong_t)zs->zs_enospc_count,
7093 100.0 * zs->zs_alloc / zs->zs_space,
7094 numbuf,
7095 100.0 * (now - zs->zs_proc_start) /
7096 (ztest_opts.zo_time * NANOSEC), timebuf);
7097 }
7098
7099 if (ztest_opts.zo_verbose >= 2) {
7100 (void) printf("\nWorkload summary:\n\n");
7101 (void) printf("%7s %9s %s\n",
7102 "Calls", "Time", "Function");
7103 (void) printf("%7s %9s %s\n",
7104 "-----", "----", "--------");
7105 for (f = 0; f < ZTEST_FUNCS; f++) {
7106 zi = &ztest_info[f];
7107 zc = ZTEST_GET_SHARED_CALLSTATE(f);
7108 print_time(zc->zc_time, timebuf);
7109 (void) printf("%7llu %9s %s\n",
7110 (u_longlong_t)zc->zc_count, timebuf,
7111 zi->zi_funcname);
7112 }
7113 (void) printf("\n");
7114 }
7115
7116 /*
7117 * It's possible that we killed a child during a rename test,
7118 * in which case we'll have a 'ztest_tmp' pool lying around
7119 * instead of 'ztest'. Do a blind rename in case this happened.
7120 */
7121 kernel_init(FREAD);
7122 if (spa_open(ztest_opts.zo_pool, &spa, FTAG) == 0) {
7123 spa_close(spa, FTAG);
7124 } else {
7125 char tmpname[ZFS_MAX_DATASET_NAME_LEN];
7126 kernel_fini();
7127 kernel_init(FREAD | FWRITE);
7128 (void) snprintf(tmpname, sizeof (tmpname), "%s_tmp",
7129 ztest_opts.zo_pool);
7130 (void) spa_rename(tmpname, ztest_opts.zo_pool);
7131 }
7132 kernel_fini();
7133
7134 if (!ztest_opts.zo_mmp_test)
7135 ztest_run_zdb(ztest_opts.zo_pool);
7136 }
7137
7138 if (ztest_opts.zo_verbose >= 1) {
7139 if (hasalt) {
7140 (void) printf("%d runs of older ztest: %s\n", older,
7141 ztest_opts.zo_alt_ztest);
7142 (void) printf("%d runs of newer ztest: %s\n", newer,
7143 cmd);
7144 }
7145 (void) printf("%d killed, %d completed, %.0f%% kill rate\n",
7146 kills, iters - kills, (100.0 * kills) / MAX(1, iters));
7147 }
7148
7149 umem_free(cmd, MAXNAMELEN);
7150
7151 return (0);
7152 }