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