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