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