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