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