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