]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - cddl/contrib/opensolaris/cmd/ztest/ztest.c
MFC r209962, r211970-r211972, r212050, r212605, r212611
[FreeBSD/stable/8.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 2009 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25
26 /*
27  * The objective of this program is to provide a DMU/ZAP/SPA stress test
28  * that runs entirely in userland, is easy to use, and easy to extend.
29  *
30  * The overall design of the ztest program is as follows:
31  *
32  * (1) For each major functional area (e.g. adding vdevs to a pool,
33  *     creating and destroying datasets, reading and writing objects, etc)
34  *     we have a simple routine to test that functionality.  These
35  *     individual routines do not have to do anything "stressful".
36  *
37  * (2) We turn these simple functionality tests into a stress test by
38  *     running them all in parallel, with as many threads as desired,
39  *     and spread across as many datasets, objects, and vdevs as desired.
40  *
41  * (3) While all this is happening, we inject faults into the pool to
42  *     verify that self-healing data really works.
43  *
44  * (4) Every time we open a dataset, we change its checksum and compression
45  *     functions.  Thus even individual objects vary from block to block
46  *     in which checksum they use and whether they're compressed.
47  *
48  * (5) To verify that we never lose on-disk consistency after a crash,
49  *     we run the entire test in a child of the main process.
50  *     At random times, the child self-immolates with a SIGKILL.
51  *     This is the software equivalent of pulling the power cord.
52  *     The parent then runs the test again, using the existing
53  *     storage pool, as many times as desired.
54  *
55  * (6) To verify that we don't have future leaks or temporal incursions,
56  *     many of the functional tests record the transaction group number
57  *     as part of their data.  When reading old data, they verify that
58  *     the transaction group number is less than the current, open txg.
59  *     If you add a new test, please do this if applicable.
60  *
61  * When run with no arguments, ztest runs for about five minutes and
62  * produces no output if successful.  To get a little bit of information,
63  * specify -V.  To get more information, specify -VV, and so on.
64  *
65  * To turn this into an overnight stress test, use -T to specify run time.
66  *
67  * You can ask more more vdevs [-v], datasets [-d], or threads [-t]
68  * to increase the pool capacity, fanout, and overall stress level.
69  *
70  * The -N(okill) option will suppress kills, so each child runs to completion.
71  * This can be useful when you're trying to distinguish temporal incursions
72  * from plain old race conditions.
73  */
74
75 #include <sys/zfs_context.h>
76 #include <sys/spa.h>
77 #include <sys/dmu.h>
78 #include <sys/txg.h>
79 #include <sys/dbuf.h>
80 #include <sys/zap.h>
81 #include <sys/dmu_objset.h>
82 #include <sys/poll.h>
83 #include <sys/stat.h>
84 #include <sys/time.h>
85 #include <sys/wait.h>
86 #include <sys/mman.h>
87 #include <sys/resource.h>
88 #include <sys/zio.h>
89 #include <sys/zio_checksum.h>
90 #include <sys/zio_compress.h>
91 #include <sys/zil.h>
92 #include <sys/vdev_impl.h>
93 #include <sys/vdev_file.h>
94 #include <sys/spa_impl.h>
95 #include <sys/dsl_prop.h>
96 #include <sys/dsl_dataset.h>
97 #include <sys/refcount.h>
98 #include <stdio.h>
99 #include <stdio_ext.h>
100 #include <stdlib.h>
101 #include <unistd.h>
102 #include <signal.h>
103 #include <umem.h>
104 #include <dlfcn.h>
105 #include <ctype.h>
106 #include <math.h>
107 #include <errno.h>
108 #include <sys/fs/zfs.h>
109
110 static char cmdname[] = "ztest";
111 static char *zopt_pool = cmdname;
112 static char *progname;
113
114 static uint64_t zopt_vdevs = 5;
115 static uint64_t zopt_vdevtime;
116 static int zopt_ashift = SPA_MINBLOCKSHIFT;
117 static int zopt_mirrors = 2;
118 static int zopt_raidz = 4;
119 static int zopt_raidz_parity = 1;
120 static size_t zopt_vdev_size = SPA_MINDEVSIZE;
121 static int zopt_datasets = 7;
122 static int zopt_threads = 23;
123 static uint64_t zopt_passtime = 60;     /* 60 seconds */
124 static uint64_t zopt_killrate = 70;     /* 70% kill rate */
125 static int zopt_verbose = 0;
126 static int zopt_init = 1;
127 static char *zopt_dir = "/tmp";
128 static uint64_t zopt_time = 300;        /* 5 minutes */
129 static int zopt_maxfaults;
130
131 typedef struct ztest_block_tag {
132         uint64_t        bt_objset;
133         uint64_t        bt_object;
134         uint64_t        bt_offset;
135         uint64_t        bt_txg;
136         uint64_t        bt_thread;
137         uint64_t        bt_seq;
138 } ztest_block_tag_t;
139
140 typedef struct ztest_args {
141         char            za_pool[MAXNAMELEN];
142         spa_t           *za_spa;
143         objset_t        *za_os;
144         zilog_t         *za_zilog;
145         thread_t        za_thread;
146         uint64_t        za_instance;
147         uint64_t        za_random;
148         uint64_t        za_diroff;
149         uint64_t        za_diroff_shared;
150         uint64_t        za_zil_seq;
151         hrtime_t        za_start;
152         hrtime_t        za_stop;
153         hrtime_t        za_kill;
154         /*
155          * Thread-local variables can go here to aid debugging.
156          */
157         ztest_block_tag_t za_rbt;
158         ztest_block_tag_t za_wbt;
159         dmu_object_info_t za_doi;
160         dmu_buf_t       *za_dbuf;
161 } ztest_args_t;
162
163 typedef void ztest_func_t(ztest_args_t *);
164
165 /*
166  * Note: these aren't static because we want dladdr() to work.
167  */
168 ztest_func_t ztest_dmu_read_write;
169 ztest_func_t ztest_dmu_read_write_zcopy;
170 ztest_func_t ztest_dmu_write_parallel;
171 ztest_func_t ztest_dmu_object_alloc_free;
172 ztest_func_t ztest_zap;
173 ztest_func_t ztest_fzap;
174 ztest_func_t ztest_zap_parallel;
175 ztest_func_t ztest_traverse;
176 ztest_func_t ztest_dsl_prop_get_set;
177 ztest_func_t ztest_dmu_objset_create_destroy;
178 ztest_func_t ztest_dmu_snapshot_create_destroy;
179 ztest_func_t ztest_dsl_dataset_promote_busy;
180 ztest_func_t ztest_spa_create_destroy;
181 ztest_func_t ztest_fault_inject;
182 ztest_func_t ztest_spa_rename;
183 ztest_func_t ztest_vdev_attach_detach;
184 ztest_func_t ztest_vdev_LUN_growth;
185 ztest_func_t ztest_vdev_add_remove;
186 ztest_func_t ztest_vdev_aux_add_remove;
187 ztest_func_t ztest_scrub;
188
189 typedef struct ztest_info {
190         ztest_func_t    *zi_func;       /* test function */
191         uint64_t        zi_iters;       /* iterations per execution */
192         uint64_t        *zi_interval;   /* execute every <interval> seconds */
193         uint64_t        zi_calls;       /* per-pass count */
194         uint64_t        zi_call_time;   /* per-pass time */
195         uint64_t        zi_call_total;  /* cumulative total */
196         uint64_t        zi_call_target; /* target cumulative total */
197 } ztest_info_t;
198
199 uint64_t zopt_always = 0;               /* all the time */
200 uint64_t zopt_often = 1;                /* every second */
201 uint64_t zopt_sometimes = 10;           /* every 10 seconds */
202 uint64_t zopt_rarely = 60;              /* every 60 seconds */
203
204 ztest_info_t ztest_info[] = {
205         { ztest_dmu_read_write,                 1,      &zopt_always    },
206         { ztest_dmu_read_write_zcopy,           1,      &zopt_always    },
207         { ztest_dmu_write_parallel,             30,     &zopt_always    },
208         { ztest_dmu_object_alloc_free,          1,      &zopt_always    },
209         { ztest_zap,                            30,     &zopt_always    },
210         { ztest_fzap,                           30,     &zopt_always    },
211         { ztest_zap_parallel,                   100,    &zopt_always    },
212         { ztest_dsl_prop_get_set,               1,      &zopt_sometimes },
213         { ztest_dmu_objset_create_destroy,      1,      &zopt_sometimes },
214         { ztest_dmu_snapshot_create_destroy,    1,      &zopt_sometimes },
215         { ztest_spa_create_destroy,             1,      &zopt_sometimes },
216         { ztest_fault_inject,                   1,      &zopt_sometimes },
217         { ztest_spa_rename,                     1,      &zopt_rarely    },
218         { ztest_vdev_attach_detach,             1,      &zopt_rarely    },
219         { ztest_vdev_LUN_growth,                1,      &zopt_rarely    },
220         { ztest_dsl_dataset_promote_busy,       1,      &zopt_rarely    },
221         { ztest_vdev_add_remove,                1,      &zopt_vdevtime  },
222         { ztest_vdev_aux_add_remove,            1,      &zopt_vdevtime  },
223         { ztest_scrub,                          1,      &zopt_vdevtime  },
224 };
225
226 #define ZTEST_FUNCS     (sizeof (ztest_info) / sizeof (ztest_info_t))
227
228 #define ZTEST_SYNC_LOCKS        16
229
230 /*
231  * Stuff we need to share writably between parent and child.
232  */
233 typedef struct ztest_shared {
234         mutex_t         zs_vdev_lock;
235         rwlock_t        zs_name_lock;
236         uint64_t        zs_vdev_primaries;
237         uint64_t        zs_vdev_aux;
238         uint64_t        zs_enospc_count;
239         hrtime_t        zs_start_time;
240         hrtime_t        zs_stop_time;
241         uint64_t        zs_alloc;
242         uint64_t        zs_space;
243         ztest_info_t    zs_info[ZTEST_FUNCS];
244         mutex_t         zs_sync_lock[ZTEST_SYNC_LOCKS];
245         uint64_t        zs_seq[ZTEST_SYNC_LOCKS];
246 } ztest_shared_t;
247
248 static char ztest_dev_template[] = "%s/%s.%llua";
249 static char ztest_aux_template[] = "%s/%s.%s.%llu";
250 static ztest_shared_t *ztest_shared;
251
252 static int ztest_random_fd;
253 static int ztest_dump_core = 1;
254
255 static uint64_t metaslab_sz;
256 static boolean_t ztest_exiting;
257
258 extern uint64_t metaslab_gang_bang;
259 extern uint64_t metaslab_df_alloc_threshold;
260
261 #define ZTEST_DIROBJ            1
262 #define ZTEST_MICROZAP_OBJ      2
263 #define ZTEST_FATZAP_OBJ        3
264
265 #define ZTEST_DIROBJ_BLOCKSIZE  (1 << 10)
266 #define ZTEST_DIRSIZE           256
267
268 static void usage(boolean_t) __NORETURN;
269
270 /*
271  * These libumem hooks provide a reasonable set of defaults for the allocator's
272  * debugging facilities.
273  */
274 const char *
275 _umem_debug_init()
276 {
277         return ("default,verbose"); /* $UMEM_DEBUG setting */
278 }
279
280 const char *
281 _umem_logging_init(void)
282 {
283         return ("fail,contents"); /* $UMEM_LOGGING setting */
284 }
285
286 #define FATAL_MSG_SZ    1024
287
288 char *fatal_msg;
289
290 static void
291 fatal(int do_perror, char *message, ...)
292 {
293         va_list args;
294         int save_errno = errno;
295         char buf[FATAL_MSG_SZ];
296
297         (void) fflush(stdout);
298
299         va_start(args, message);
300         (void) sprintf(buf, "ztest: ");
301         /* LINTED */
302         (void) vsprintf(buf + strlen(buf), message, args);
303         va_end(args);
304         if (do_perror) {
305                 (void) snprintf(buf + strlen(buf), FATAL_MSG_SZ - strlen(buf),
306                     ": %s", strerror(save_errno));
307         }
308         (void) fprintf(stderr, "%s\n", buf);
309         fatal_msg = buf;                        /* to ease debugging */
310         if (ztest_dump_core)
311                 abort();
312         exit(3);
313 }
314
315 static int
316 str2shift(const char *buf)
317 {
318         const char *ends = "BKMGTPEZ";
319         int i;
320
321         if (buf[0] == '\0')
322                 return (0);
323         for (i = 0; i < strlen(ends); i++) {
324                 if (toupper(buf[0]) == ends[i])
325                         break;
326         }
327         if (i == strlen(ends)) {
328                 (void) fprintf(stderr, "ztest: invalid bytes suffix: %s\n",
329                     buf);
330                 usage(B_FALSE);
331         }
332         if (buf[1] == '\0' || (toupper(buf[1]) == 'B' && buf[2] == '\0')) {
333                 return (10*i);
334         }
335         (void) fprintf(stderr, "ztest: invalid bytes suffix: %s\n", buf);
336         usage(B_FALSE);
337         /* NOTREACHED */
338 }
339
340 static uint64_t
341 nicenumtoull(const char *buf)
342 {
343         char *end;
344         uint64_t val;
345
346         val = strtoull(buf, &end, 0);
347         if (end == buf) {
348                 (void) fprintf(stderr, "ztest: bad numeric value: %s\n", buf);
349                 usage(B_FALSE);
350         } else if (end[0] == '.') {
351                 double fval = strtod(buf, &end);
352                 fval *= pow(2, str2shift(end));
353                 if (fval > UINT64_MAX) {
354                         (void) fprintf(stderr, "ztest: value too large: %s\n",
355                             buf);
356                         usage(B_FALSE);
357                 }
358                 val = (uint64_t)fval;
359         } else {
360                 int shift = str2shift(end);
361                 if (shift >= 64 || (val << shift) >> shift != val) {
362                         (void) fprintf(stderr, "ztest: value too large: %s\n",
363                             buf);
364                         usage(B_FALSE);
365                 }
366                 val <<= shift;
367         }
368         return (val);
369 }
370
371 static void
372 usage(boolean_t requested)
373 {
374         char nice_vdev_size[10];
375         char nice_gang_bang[10];
376         FILE *fp = requested ? stdout : stderr;
377
378         nicenum(zopt_vdev_size, nice_vdev_size);
379         nicenum(metaslab_gang_bang, nice_gang_bang);
380
381         (void) fprintf(fp, "Usage: %s\n"
382             "\t[-v vdevs (default: %llu)]\n"
383             "\t[-s size_of_each_vdev (default: %s)]\n"
384             "\t[-a alignment_shift (default: %d) (use 0 for random)]\n"
385             "\t[-m mirror_copies (default: %d)]\n"
386             "\t[-r raidz_disks (default: %d)]\n"
387             "\t[-R raidz_parity (default: %d)]\n"
388             "\t[-d datasets (default: %d)]\n"
389             "\t[-t threads (default: %d)]\n"
390             "\t[-g gang_block_threshold (default: %s)]\n"
391             "\t[-i initialize pool i times (default: %d)]\n"
392             "\t[-k kill percentage (default: %llu%%)]\n"
393             "\t[-p pool_name (default: %s)]\n"
394             "\t[-f file directory for vdev files (default: %s)]\n"
395             "\t[-V(erbose)] (use multiple times for ever more blather)\n"
396             "\t[-E(xisting)] (use existing pool instead of creating new one)\n"
397             "\t[-T time] total run time (default: %llu sec)\n"
398             "\t[-P passtime] time per pass (default: %llu sec)\n"
399             "\t[-h] (print help)\n"
400             "",
401             cmdname,
402             (u_longlong_t)zopt_vdevs,                   /* -v */
403             nice_vdev_size,                             /* -s */
404             zopt_ashift,                                /* -a */
405             zopt_mirrors,                               /* -m */
406             zopt_raidz,                                 /* -r */
407             zopt_raidz_parity,                          /* -R */
408             zopt_datasets,                              /* -d */
409             zopt_threads,                               /* -t */
410             nice_gang_bang,                             /* -g */
411             zopt_init,                                  /* -i */
412             (u_longlong_t)zopt_killrate,                /* -k */
413             zopt_pool,                                  /* -p */
414             zopt_dir,                                   /* -f */
415             (u_longlong_t)zopt_time,                    /* -T */
416             (u_longlong_t)zopt_passtime);               /* -P */
417         exit(requested ? 0 : 1);
418 }
419
420 static uint64_t
421 ztest_random(uint64_t range)
422 {
423         uint64_t r;
424
425         if (range == 0)
426                 return (0);
427
428         if (read(ztest_random_fd, &r, sizeof (r)) != sizeof (r))
429                 fatal(1, "short read from /dev/urandom");
430
431         return (r % range);
432 }
433
434 /* ARGSUSED */
435 static void
436 ztest_record_enospc(char *s)
437 {
438         ztest_shared->zs_enospc_count++;
439 }
440
441 static void
442 process_options(int argc, char **argv)
443 {
444         int opt;
445         uint64_t value;
446
447         /* Remember program name. */
448         progname = argv[0];
449
450         /* By default, test gang blocks for blocks 32K and greater */
451         metaslab_gang_bang = 32 << 10;
452
453         while ((opt = getopt(argc, argv,
454             "v:s:a:m:r:R:d:t:g:i:k:p:f:VET:P:h")) != EOF) {
455                 value = 0;
456                 switch (opt) {
457                 case 'v':
458                 case 's':
459                 case 'a':
460                 case 'm':
461                 case 'r':
462                 case 'R':
463                 case 'd':
464                 case 't':
465                 case 'g':
466                 case 'i':
467                 case 'k':
468                 case 'T':
469                 case 'P':
470                         value = nicenumtoull(optarg);
471                 }
472                 switch (opt) {
473                 case 'v':
474                         zopt_vdevs = value;
475                         break;
476                 case 's':
477                         zopt_vdev_size = MAX(SPA_MINDEVSIZE, value);
478                         break;
479                 case 'a':
480                         zopt_ashift = value;
481                         break;
482                 case 'm':
483                         zopt_mirrors = value;
484                         break;
485                 case 'r':
486                         zopt_raidz = MAX(1, value);
487                         break;
488                 case 'R':
489                         zopt_raidz_parity = MIN(MAX(value, 1), 2);
490                         break;
491                 case 'd':
492                         zopt_datasets = MAX(1, value);
493                         break;
494                 case 't':
495                         zopt_threads = MAX(1, value);
496                         break;
497                 case 'g':
498                         metaslab_gang_bang = MAX(SPA_MINBLOCKSIZE << 1, value);
499                         break;
500                 case 'i':
501                         zopt_init = value;
502                         break;
503                 case 'k':
504                         zopt_killrate = value;
505                         break;
506                 case 'p':
507                         zopt_pool = strdup(optarg);
508                         break;
509                 case 'f':
510                         zopt_dir = strdup(optarg);
511                         break;
512                 case 'V':
513                         zopt_verbose++;
514                         break;
515                 case 'E':
516                         zopt_init = 0;
517                         break;
518                 case 'T':
519                         zopt_time = value;
520                         break;
521                 case 'P':
522                         zopt_passtime = MAX(1, value);
523                         break;
524                 case 'h':
525                         usage(B_TRUE);
526                         break;
527                 case '?':
528                 default:
529                         usage(B_FALSE);
530                         break;
531                 }
532         }
533
534         zopt_raidz_parity = MIN(zopt_raidz_parity, zopt_raidz - 1);
535
536         zopt_vdevtime = (zopt_vdevs > 0 ? zopt_time / zopt_vdevs : UINT64_MAX);
537         zopt_maxfaults = MAX(zopt_mirrors, 1) * (zopt_raidz_parity + 1) - 1;
538 }
539
540 static uint64_t
541 ztest_get_ashift(void)
542 {
543         if (zopt_ashift == 0)
544                 return (SPA_MINBLOCKSHIFT + ztest_random(3));
545         return (zopt_ashift);
546 }
547
548 static nvlist_t *
549 make_vdev_file(char *path, char *aux, size_t size, uint64_t ashift)
550 {
551         char pathbuf[MAXPATHLEN];
552         uint64_t vdev;
553         nvlist_t *file;
554
555         if (ashift == 0)
556                 ashift = ztest_get_ashift();
557
558         if (path == NULL) {
559                 path = pathbuf;
560
561                 if (aux != NULL) {
562                         vdev = ztest_shared->zs_vdev_aux;
563                         (void) sprintf(path, ztest_aux_template,
564                             zopt_dir, zopt_pool, aux, vdev);
565                 } else {
566                         vdev = ztest_shared->zs_vdev_primaries++;
567                         (void) sprintf(path, ztest_dev_template,
568                             zopt_dir, zopt_pool, vdev);
569                 }
570         }
571
572         if (size != 0) {
573                 int fd = open(path, O_RDWR | O_CREAT | O_TRUNC, 0666);
574                 if (fd == -1)
575                         fatal(1, "can't open %s", path);
576                 if (ftruncate(fd, size) != 0)
577                         fatal(1, "can't ftruncate %s", path);
578                 (void) close(fd);
579         }
580
581         VERIFY(nvlist_alloc(&file, NV_UNIQUE_NAME, 0) == 0);
582         VERIFY(nvlist_add_string(file, ZPOOL_CONFIG_TYPE, VDEV_TYPE_FILE) == 0);
583         VERIFY(nvlist_add_string(file, ZPOOL_CONFIG_PATH, path) == 0);
584         VERIFY(nvlist_add_uint64(file, ZPOOL_CONFIG_ASHIFT, ashift) == 0);
585
586         return (file);
587 }
588
589 static nvlist_t *
590 make_vdev_raidz(char *path, char *aux, size_t size, uint64_t ashift, int r)
591 {
592         nvlist_t *raidz, **child;
593         int c;
594
595         if (r < 2)
596                 return (make_vdev_file(path, aux, size, ashift));
597         child = umem_alloc(r * sizeof (nvlist_t *), UMEM_NOFAIL);
598
599         for (c = 0; c < r; c++)
600                 child[c] = make_vdev_file(path, aux, size, ashift);
601
602         VERIFY(nvlist_alloc(&raidz, NV_UNIQUE_NAME, 0) == 0);
603         VERIFY(nvlist_add_string(raidz, ZPOOL_CONFIG_TYPE,
604             VDEV_TYPE_RAIDZ) == 0);
605         VERIFY(nvlist_add_uint64(raidz, ZPOOL_CONFIG_NPARITY,
606             zopt_raidz_parity) == 0);
607         VERIFY(nvlist_add_nvlist_array(raidz, ZPOOL_CONFIG_CHILDREN,
608             child, r) == 0);
609
610         for (c = 0; c < r; c++)
611                 nvlist_free(child[c]);
612
613         umem_free(child, r * sizeof (nvlist_t *));
614
615         return (raidz);
616 }
617
618 static nvlist_t *
619 make_vdev_mirror(char *path, char *aux, size_t size, uint64_t ashift,
620         int r, int m)
621 {
622         nvlist_t *mirror, **child;
623         int c;
624
625         if (m < 1)
626                 return (make_vdev_raidz(path, aux, size, ashift, r));
627
628         child = umem_alloc(m * sizeof (nvlist_t *), UMEM_NOFAIL);
629
630         for (c = 0; c < m; c++)
631                 child[c] = make_vdev_raidz(path, aux, size, ashift, r);
632
633         VERIFY(nvlist_alloc(&mirror, NV_UNIQUE_NAME, 0) == 0);
634         VERIFY(nvlist_add_string(mirror, ZPOOL_CONFIG_TYPE,
635             VDEV_TYPE_MIRROR) == 0);
636         VERIFY(nvlist_add_nvlist_array(mirror, ZPOOL_CONFIG_CHILDREN,
637             child, m) == 0);
638
639         for (c = 0; c < m; c++)
640                 nvlist_free(child[c]);
641
642         umem_free(child, m * sizeof (nvlist_t *));
643
644         return (mirror);
645 }
646
647 static nvlist_t *
648 make_vdev_root(char *path, char *aux, size_t size, uint64_t ashift,
649         int log, int r, int m, int t)
650 {
651         nvlist_t *root, **child;
652         int c;
653
654         ASSERT(t > 0);
655
656         child = umem_alloc(t * sizeof (nvlist_t *), UMEM_NOFAIL);
657
658         for (c = 0; c < t; c++) {
659                 child[c] = make_vdev_mirror(path, aux, size, ashift, r, m);
660                 VERIFY(nvlist_add_uint64(child[c], ZPOOL_CONFIG_IS_LOG,
661                     log) == 0);
662         }
663
664         VERIFY(nvlist_alloc(&root, NV_UNIQUE_NAME, 0) == 0);
665         VERIFY(nvlist_add_string(root, ZPOOL_CONFIG_TYPE, VDEV_TYPE_ROOT) == 0);
666         VERIFY(nvlist_add_nvlist_array(root, aux ? aux : ZPOOL_CONFIG_CHILDREN,
667             child, t) == 0);
668
669         for (c = 0; c < t; c++)
670                 nvlist_free(child[c]);
671
672         umem_free(child, t * sizeof (nvlist_t *));
673
674         return (root);
675 }
676
677 static void
678 ztest_set_random_blocksize(objset_t *os, uint64_t object, dmu_tx_t *tx)
679 {
680         int bs = SPA_MINBLOCKSHIFT +
681             ztest_random(SPA_MAXBLOCKSHIFT - SPA_MINBLOCKSHIFT + 1);
682         int ibs = DN_MIN_INDBLKSHIFT +
683             ztest_random(DN_MAX_INDBLKSHIFT - DN_MIN_INDBLKSHIFT + 1);
684         int error;
685
686         error = dmu_object_set_blocksize(os, object, 1ULL << bs, ibs, tx);
687         if (error) {
688                 char osname[300];
689                 dmu_objset_name(os, osname);
690                 fatal(0, "dmu_object_set_blocksize('%s', %llu, %d, %d) = %d",
691                     osname, object, 1 << bs, ibs, error);
692         }
693 }
694
695 static uint8_t
696 ztest_random_checksum(void)
697 {
698         uint8_t checksum;
699
700         do {
701                 checksum = ztest_random(ZIO_CHECKSUM_FUNCTIONS);
702         } while (zio_checksum_table[checksum].ci_zbt);
703
704         if (checksum == ZIO_CHECKSUM_OFF)
705                 checksum = ZIO_CHECKSUM_ON;
706
707         return (checksum);
708 }
709
710 static uint8_t
711 ztest_random_compress(void)
712 {
713         return ((uint8_t)ztest_random(ZIO_COMPRESS_FUNCTIONS));
714 }
715
716 static int
717 ztest_replay_create(objset_t *os, lr_create_t *lr, boolean_t byteswap)
718 {
719         dmu_tx_t *tx;
720         int error;
721
722         if (byteswap)
723                 byteswap_uint64_array(lr, sizeof (*lr));
724
725         tx = dmu_tx_create(os);
726         dmu_tx_hold_bonus(tx, DMU_NEW_OBJECT);
727         error = dmu_tx_assign(tx, TXG_WAIT);
728         if (error) {
729                 dmu_tx_abort(tx);
730                 return (error);
731         }
732
733         error = dmu_object_claim(os, lr->lr_doid, lr->lr_mode, 0,
734             DMU_OT_NONE, 0, tx);
735         ASSERT3U(error, ==, 0);
736         dmu_tx_commit(tx);
737
738         if (zopt_verbose >= 5) {
739                 char osname[MAXNAMELEN];
740                 dmu_objset_name(os, osname);
741                 (void) printf("replay create of %s object %llu"
742                     " in txg %llu = %d\n",
743                     osname, (u_longlong_t)lr->lr_doid,
744                     (u_longlong_t)dmu_tx_get_txg(tx), error);
745         }
746
747         return (error);
748 }
749
750 static int
751 ztest_replay_remove(objset_t *os, lr_remove_t *lr, boolean_t byteswap)
752 {
753         dmu_tx_t *tx;
754         int error;
755
756         if (byteswap)
757                 byteswap_uint64_array(lr, sizeof (*lr));
758
759         tx = dmu_tx_create(os);
760         dmu_tx_hold_free(tx, lr->lr_doid, 0, DMU_OBJECT_END);
761         error = dmu_tx_assign(tx, TXG_WAIT);
762         if (error) {
763                 dmu_tx_abort(tx);
764                 return (error);
765         }
766
767         error = dmu_object_free(os, lr->lr_doid, tx);
768         dmu_tx_commit(tx);
769
770         return (error);
771 }
772
773 zil_replay_func_t *ztest_replay_vector[TX_MAX_TYPE] = {
774         NULL,                   /* 0 no such transaction type */
775         ztest_replay_create,    /* TX_CREATE */
776         NULL,                   /* TX_MKDIR */
777         NULL,                   /* TX_MKXATTR */
778         NULL,                   /* TX_SYMLINK */
779         ztest_replay_remove,    /* TX_REMOVE */
780         NULL,                   /* TX_RMDIR */
781         NULL,                   /* TX_LINK */
782         NULL,                   /* TX_RENAME */
783         NULL,                   /* TX_WRITE */
784         NULL,                   /* TX_TRUNCATE */
785         NULL,                   /* TX_SETATTR */
786         NULL,                   /* TX_ACL */
787         NULL,                   /* TX_CREATE_ACL */
788         NULL,                   /* TX_CREATE_ATTR */
789         NULL,                   /* TX_CREATE_ACL_ATTR */
790         NULL,                   /* TX_MKDIR_ACL */
791         NULL,                   /* TX_MKDIR_ATTR */
792         NULL,                   /* TX_MKDIR_ACL_ATTR */
793         NULL,                   /* TX_WRITE2 */
794 };
795
796 /*
797  * Verify that we can't destroy an active pool, create an existing pool,
798  * or create a pool with a bad vdev spec.
799  */
800 void
801 ztest_spa_create_destroy(ztest_args_t *za)
802 {
803         int error;
804         spa_t *spa;
805         nvlist_t *nvroot;
806
807         /*
808          * Attempt to create using a bad file.
809          */
810         nvroot = make_vdev_root("/dev/bogus", NULL, 0, 0, 0, 0, 0, 1);
811         error = spa_create("ztest_bad_file", nvroot, NULL, NULL, NULL);
812         nvlist_free(nvroot);
813         if (error != ENOENT)
814                 fatal(0, "spa_create(bad_file) = %d", error);
815
816         /*
817          * Attempt to create using a bad mirror.
818          */
819         nvroot = make_vdev_root("/dev/bogus", NULL, 0, 0, 0, 0, 2, 1);
820         error = spa_create("ztest_bad_mirror", nvroot, NULL, NULL, NULL);
821         nvlist_free(nvroot);
822         if (error != ENOENT)
823                 fatal(0, "spa_create(bad_mirror) = %d", error);
824
825         /*
826          * Attempt to create an existing pool.  It shouldn't matter
827          * what's in the nvroot; we should fail with EEXIST.
828          */
829         (void) rw_rdlock(&ztest_shared->zs_name_lock);
830         nvroot = make_vdev_root("/dev/bogus", NULL, 0, 0, 0, 0, 0, 1);
831         error = spa_create(za->za_pool, nvroot, NULL, NULL, NULL);
832         nvlist_free(nvroot);
833         if (error != EEXIST)
834                 fatal(0, "spa_create(whatever) = %d", error);
835
836         error = spa_open(za->za_pool, &spa, FTAG);
837         if (error)
838                 fatal(0, "spa_open() = %d", error);
839
840         error = spa_destroy(za->za_pool);
841         if (error != EBUSY)
842                 fatal(0, "spa_destroy() = %d", error);
843
844         spa_close(spa, FTAG);
845         (void) rw_unlock(&ztest_shared->zs_name_lock);
846 }
847
848 static vdev_t *
849 vdev_lookup_by_path(vdev_t *vd, const char *path)
850 {
851         vdev_t *mvd;
852
853         if (vd->vdev_path != NULL && strcmp(path, vd->vdev_path) == 0)
854                 return (vd);
855
856         for (int c = 0; c < vd->vdev_children; c++)
857                 if ((mvd = vdev_lookup_by_path(vd->vdev_child[c], path)) !=
858                     NULL)
859                         return (mvd);
860
861         return (NULL);
862 }
863
864 /*
865  * Verify that vdev_add() works as expected.
866  */
867 void
868 ztest_vdev_add_remove(ztest_args_t *za)
869 {
870         spa_t *spa = za->za_spa;
871         uint64_t leaves = MAX(zopt_mirrors, 1) * zopt_raidz;
872         nvlist_t *nvroot;
873         int error;
874
875         (void) mutex_lock(&ztest_shared->zs_vdev_lock);
876
877         spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
878
879         ztest_shared->zs_vdev_primaries =
880             spa->spa_root_vdev->vdev_children * leaves;
881
882         spa_config_exit(spa, SCL_VDEV, FTAG);
883
884         /*
885          * Make 1/4 of the devices be log devices.
886          */
887         nvroot = make_vdev_root(NULL, NULL, zopt_vdev_size, 0,
888             ztest_random(4) == 0, zopt_raidz, zopt_mirrors, 1);
889
890         error = spa_vdev_add(spa, nvroot);
891         nvlist_free(nvroot);
892
893         (void) mutex_unlock(&ztest_shared->zs_vdev_lock);
894
895         if (error == ENOSPC)
896                 ztest_record_enospc("spa_vdev_add");
897         else if (error != 0)
898                 fatal(0, "spa_vdev_add() = %d", error);
899 }
900
901 /*
902  * Verify that adding/removing aux devices (l2arc, hot spare) works as expected.
903  */
904 void
905 ztest_vdev_aux_add_remove(ztest_args_t *za)
906 {
907         spa_t *spa = za->za_spa;
908         vdev_t *rvd = spa->spa_root_vdev;
909         spa_aux_vdev_t *sav;
910         char *aux;
911         uint64_t guid = 0;
912         int error;
913
914         if (ztest_random(2) == 0) {
915                 sav = &spa->spa_spares;
916                 aux = ZPOOL_CONFIG_SPARES;
917         } else {
918                 sav = &spa->spa_l2cache;
919                 aux = ZPOOL_CONFIG_L2CACHE;
920         }
921
922         (void) mutex_lock(&ztest_shared->zs_vdev_lock);
923
924         spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
925
926         if (sav->sav_count != 0 && ztest_random(4) == 0) {
927                 /*
928                  * Pick a random device to remove.
929                  */
930                 guid = sav->sav_vdevs[ztest_random(sav->sav_count)]->vdev_guid;
931         } else {
932                 /*
933                  * Find an unused device we can add.
934                  */
935                 ztest_shared->zs_vdev_aux = 0;
936                 for (;;) {
937                         char path[MAXPATHLEN];
938                         int c;
939                         (void) sprintf(path, ztest_aux_template, zopt_dir,
940                             zopt_pool, aux, ztest_shared->zs_vdev_aux);
941                         for (c = 0; c < sav->sav_count; c++)
942                                 if (strcmp(sav->sav_vdevs[c]->vdev_path,
943                                     path) == 0)
944                                         break;
945                         if (c == sav->sav_count &&
946                             vdev_lookup_by_path(rvd, path) == NULL)
947                                 break;
948                         ztest_shared->zs_vdev_aux++;
949                 }
950         }
951
952         spa_config_exit(spa, SCL_VDEV, FTAG);
953
954         if (guid == 0) {
955                 /*
956                  * Add a new device.
957                  */
958                 nvlist_t *nvroot = make_vdev_root(NULL, aux,
959                     (zopt_vdev_size * 5) / 4, 0, 0, 0, 0, 1);
960                 error = spa_vdev_add(spa, nvroot);
961                 if (error != 0)
962                         fatal(0, "spa_vdev_add(%p) = %d", nvroot, error);
963                 nvlist_free(nvroot);
964         } else {
965                 /*
966                  * Remove an existing device.  Sometimes, dirty its
967                  * vdev state first to make sure we handle removal
968                  * of devices that have pending state changes.
969                  */
970                 if (ztest_random(2) == 0)
971                         (void) vdev_online(spa, guid, B_FALSE, NULL);
972
973                 error = spa_vdev_remove(spa, guid, B_FALSE);
974                 if (error != 0 && error != EBUSY)
975                         fatal(0, "spa_vdev_remove(%llu) = %d", guid, error);
976         }
977
978         (void) mutex_unlock(&ztest_shared->zs_vdev_lock);
979 }
980
981 /*
982  * Verify that we can attach and detach devices.
983  */
984 void
985 ztest_vdev_attach_detach(ztest_args_t *za)
986 {
987         spa_t *spa = za->za_spa;
988         spa_aux_vdev_t *sav = &spa->spa_spares;
989         vdev_t *rvd = spa->spa_root_vdev;
990         vdev_t *oldvd, *newvd, *pvd;
991         nvlist_t *root;
992         uint64_t leaves = MAX(zopt_mirrors, 1) * zopt_raidz;
993         uint64_t leaf, top;
994         uint64_t ashift = ztest_get_ashift();
995         uint64_t oldguid, pguid;
996         size_t oldsize, newsize;
997         char oldpath[MAXPATHLEN], newpath[MAXPATHLEN];
998         int replacing;
999         int oldvd_has_siblings = B_FALSE;
1000         int newvd_is_spare = B_FALSE;
1001         int oldvd_is_log;
1002         int error, expected_error;
1003
1004         (void) mutex_lock(&ztest_shared->zs_vdev_lock);
1005
1006         spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
1007
1008         /*
1009          * Decide whether to do an attach or a replace.
1010          */
1011         replacing = ztest_random(2);
1012
1013         /*
1014          * Pick a random top-level vdev.
1015          */
1016         top = ztest_random(rvd->vdev_children);
1017
1018         /*
1019          * Pick a random leaf within it.
1020          */
1021         leaf = ztest_random(leaves);
1022
1023         /*
1024          * Locate this vdev.
1025          */
1026         oldvd = rvd->vdev_child[top];
1027         if (zopt_mirrors >= 1) {
1028                 ASSERT(oldvd->vdev_ops == &vdev_mirror_ops);
1029                 ASSERT(oldvd->vdev_children >= zopt_mirrors);
1030                 oldvd = oldvd->vdev_child[leaf / zopt_raidz];
1031         }
1032         if (zopt_raidz > 1) {
1033                 ASSERT(oldvd->vdev_ops == &vdev_raidz_ops);
1034                 ASSERT(oldvd->vdev_children == zopt_raidz);
1035                 oldvd = oldvd->vdev_child[leaf % zopt_raidz];
1036         }
1037
1038         /*
1039          * If we're already doing an attach or replace, oldvd may be a
1040          * mirror vdev -- in which case, pick a random child.
1041          */
1042         while (oldvd->vdev_children != 0) {
1043                 oldvd_has_siblings = B_TRUE;
1044                 ASSERT(oldvd->vdev_children >= 2);
1045                 oldvd = oldvd->vdev_child[ztest_random(oldvd->vdev_children)];
1046         }
1047
1048         oldguid = oldvd->vdev_guid;
1049         oldsize = vdev_get_rsize(oldvd);
1050         oldvd_is_log = oldvd->vdev_top->vdev_islog;
1051         (void) strcpy(oldpath, oldvd->vdev_path);
1052         pvd = oldvd->vdev_parent;
1053         pguid = pvd->vdev_guid;
1054
1055         /*
1056          * If oldvd has siblings, then half of the time, detach it.
1057          */
1058         if (oldvd_has_siblings && ztest_random(2) == 0) {
1059                 spa_config_exit(spa, SCL_VDEV, FTAG);
1060                 error = spa_vdev_detach(spa, oldguid, pguid, B_FALSE);
1061                 if (error != 0 && error != ENODEV && error != EBUSY &&
1062                     error != ENOTSUP)
1063                         fatal(0, "detach (%s) returned %d", oldpath, error);
1064                 (void) mutex_unlock(&ztest_shared->zs_vdev_lock);
1065                 return;
1066         }
1067
1068         /*
1069          * For the new vdev, choose with equal probability between the two
1070          * standard paths (ending in either 'a' or 'b') or a random hot spare.
1071          */
1072         if (sav->sav_count != 0 && ztest_random(3) == 0) {
1073                 newvd = sav->sav_vdevs[ztest_random(sav->sav_count)];
1074                 newvd_is_spare = B_TRUE;
1075                 (void) strcpy(newpath, newvd->vdev_path);
1076         } else {
1077                 (void) snprintf(newpath, sizeof (newpath), ztest_dev_template,
1078                     zopt_dir, zopt_pool, top * leaves + leaf);
1079                 if (ztest_random(2) == 0)
1080                         newpath[strlen(newpath) - 1] = 'b';
1081                 newvd = vdev_lookup_by_path(rvd, newpath);
1082         }
1083
1084         if (newvd) {
1085                 newsize = vdev_get_rsize(newvd);
1086         } else {
1087                 /*
1088                  * Make newsize a little bigger or smaller than oldsize.
1089                  * If it's smaller, the attach should fail.
1090                  * If it's larger, and we're doing a replace,
1091                  * we should get dynamic LUN growth when we're done.
1092                  */
1093                 newsize = 10 * oldsize / (9 + ztest_random(3));
1094         }
1095
1096         /*
1097          * If pvd is not a mirror or root, the attach should fail with ENOTSUP,
1098          * unless it's a replace; in that case any non-replacing parent is OK.
1099          *
1100          * If newvd is already part of the pool, it should fail with EBUSY.
1101          *
1102          * If newvd is too small, it should fail with EOVERFLOW.
1103          */
1104         if (pvd->vdev_ops != &vdev_mirror_ops &&
1105             pvd->vdev_ops != &vdev_root_ops && (!replacing ||
1106             pvd->vdev_ops == &vdev_replacing_ops ||
1107             pvd->vdev_ops == &vdev_spare_ops))
1108                 expected_error = ENOTSUP;
1109         else if (newvd_is_spare && (!replacing || oldvd_is_log))
1110                 expected_error = ENOTSUP;
1111         else if (newvd == oldvd)
1112                 expected_error = replacing ? 0 : EBUSY;
1113         else if (vdev_lookup_by_path(rvd, newpath) != NULL)
1114                 expected_error = EBUSY;
1115         else if (newsize < oldsize)
1116                 expected_error = EOVERFLOW;
1117         else if (ashift > oldvd->vdev_top->vdev_ashift)
1118                 expected_error = EDOM;
1119         else
1120                 expected_error = 0;
1121
1122         spa_config_exit(spa, SCL_VDEV, FTAG);
1123
1124         /*
1125          * Build the nvlist describing newpath.
1126          */
1127         root = make_vdev_root(newpath, NULL, newvd == NULL ? newsize : 0,
1128             ashift, 0, 0, 0, 1);
1129
1130         error = spa_vdev_attach(spa, oldguid, root, replacing);
1131
1132         nvlist_free(root);
1133
1134         /*
1135          * If our parent was the replacing vdev, but the replace completed,
1136          * then instead of failing with ENOTSUP we may either succeed,
1137          * fail with ENODEV, or fail with EOVERFLOW.
1138          */
1139         if (expected_error == ENOTSUP &&
1140             (error == 0 || error == ENODEV || error == EOVERFLOW))
1141                 expected_error = error;
1142
1143         /*
1144          * If someone grew the LUN, the replacement may be too small.
1145          */
1146         if (error == EOVERFLOW || error == EBUSY)
1147                 expected_error = error;
1148
1149         /* XXX workaround 6690467 */
1150         if (error != expected_error && expected_error != EBUSY) {
1151                 fatal(0, "attach (%s %llu, %s %llu, %d) "
1152                     "returned %d, expected %d",
1153                     oldpath, (longlong_t)oldsize, newpath,
1154                     (longlong_t)newsize, replacing, error, expected_error);
1155         }
1156
1157         (void) mutex_unlock(&ztest_shared->zs_vdev_lock);
1158 }
1159
1160 /*
1161  * Verify that dynamic LUN growth works as expected.
1162  */
1163 void
1164 ztest_vdev_LUN_growth(ztest_args_t *za)
1165 {
1166         spa_t *spa = za->za_spa;
1167         char dev_name[MAXPATHLEN];
1168         uint64_t leaves = MAX(zopt_mirrors, 1) * zopt_raidz;
1169         uint64_t vdev;
1170         size_t fsize;
1171         int fd;
1172
1173         (void) mutex_lock(&ztest_shared->zs_vdev_lock);
1174
1175         /*
1176          * Pick a random leaf vdev.
1177          */
1178         spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
1179         vdev = ztest_random(spa->spa_root_vdev->vdev_children * leaves);
1180         spa_config_exit(spa, SCL_VDEV, FTAG);
1181
1182         (void) sprintf(dev_name, ztest_dev_template, zopt_dir, zopt_pool, vdev);
1183
1184         if ((fd = open(dev_name, O_RDWR)) != -1) {
1185                 /*
1186                  * Determine the size.
1187                  */
1188                 fsize = lseek(fd, 0, SEEK_END);
1189
1190                 /*
1191                  * If it's less than 2x the original size, grow by around 3%.
1192                  */
1193                 if (fsize < 2 * zopt_vdev_size) {
1194                         size_t newsize = fsize + ztest_random(fsize / 32);
1195                         (void) ftruncate(fd, newsize);
1196                         if (zopt_verbose >= 6) {
1197                                 (void) printf("%s grew from %lu to %lu bytes\n",
1198                                     dev_name, (ulong_t)fsize, (ulong_t)newsize);
1199                         }
1200                 }
1201                 (void) close(fd);
1202         }
1203
1204         (void) mutex_unlock(&ztest_shared->zs_vdev_lock);
1205 }
1206
1207 /* ARGSUSED */
1208 static void
1209 ztest_create_cb(objset_t *os, void *arg, cred_t *cr, dmu_tx_t *tx)
1210 {
1211         /*
1212          * Create the directory object.
1213          */
1214         VERIFY(dmu_object_claim(os, ZTEST_DIROBJ,
1215             DMU_OT_UINT64_OTHER, ZTEST_DIROBJ_BLOCKSIZE,
1216             DMU_OT_UINT64_OTHER, 5 * sizeof (ztest_block_tag_t), tx) == 0);
1217
1218         VERIFY(zap_create_claim(os, ZTEST_MICROZAP_OBJ,
1219             DMU_OT_ZAP_OTHER, DMU_OT_NONE, 0, tx) == 0);
1220
1221         VERIFY(zap_create_claim(os, ZTEST_FATZAP_OBJ,
1222             DMU_OT_ZAP_OTHER, DMU_OT_NONE, 0, tx) == 0);
1223 }
1224
1225 static int
1226 ztest_destroy_cb(char *name, void *arg)
1227 {
1228         ztest_args_t *za = arg;
1229         objset_t *os;
1230         dmu_object_info_t *doi = &za->za_doi;
1231         int error;
1232
1233         /*
1234          * Verify that the dataset contains a directory object.
1235          */
1236         error = dmu_objset_open(name, DMU_OST_OTHER,
1237             DS_MODE_USER | DS_MODE_READONLY, &os);
1238         ASSERT3U(error, ==, 0);
1239         error = dmu_object_info(os, ZTEST_DIROBJ, doi);
1240         if (error != ENOENT) {
1241                 /* We could have crashed in the middle of destroying it */
1242                 ASSERT3U(error, ==, 0);
1243                 ASSERT3U(doi->doi_type, ==, DMU_OT_UINT64_OTHER);
1244                 ASSERT3S(doi->doi_physical_blks, >=, 0);
1245         }
1246         dmu_objset_close(os);
1247
1248         /*
1249          * Destroy the dataset.
1250          */
1251         error = dmu_objset_destroy(name);
1252         if (error) {
1253                 (void) dmu_objset_open(name, DMU_OST_OTHER,
1254                     DS_MODE_USER | DS_MODE_READONLY, &os);
1255                 fatal(0, "dmu_objset_destroy(os=%p) = %d\n", &os, error);
1256         }
1257         return (0);
1258 }
1259
1260 /*
1261  * Verify that dmu_objset_{create,destroy,open,close} work as expected.
1262  */
1263 static uint64_t
1264 ztest_log_create(zilog_t *zilog, dmu_tx_t *tx, uint64_t object, int mode)
1265 {
1266         itx_t *itx;
1267         lr_create_t *lr;
1268         size_t namesize;
1269         char name[24];
1270
1271         (void) sprintf(name, "ZOBJ_%llu", (u_longlong_t)object);
1272         namesize = strlen(name) + 1;
1273
1274         itx = zil_itx_create(TX_CREATE, sizeof (*lr) + namesize +
1275             ztest_random(ZIL_MAX_BLKSZ));
1276         lr = (lr_create_t *)&itx->itx_lr;
1277         bzero(lr + 1, lr->lr_common.lrc_reclen - sizeof (*lr));
1278         lr->lr_doid = object;
1279         lr->lr_foid = 0;
1280         lr->lr_mode = mode;
1281         lr->lr_uid = 0;
1282         lr->lr_gid = 0;
1283         lr->lr_gen = dmu_tx_get_txg(tx);
1284         lr->lr_crtime[0] = time(NULL);
1285         lr->lr_crtime[1] = 0;
1286         lr->lr_rdev = 0;
1287         bcopy(name, (char *)(lr + 1), namesize);
1288
1289         return (zil_itx_assign(zilog, itx, tx));
1290 }
1291
1292 void
1293 ztest_dmu_objset_create_destroy(ztest_args_t *za)
1294 {
1295         int error;
1296         objset_t *os, *os2;
1297         char name[100];
1298         int basemode, expected_error;
1299         zilog_t *zilog;
1300         uint64_t seq;
1301         uint64_t objects;
1302
1303         (void) rw_rdlock(&ztest_shared->zs_name_lock);
1304         (void) snprintf(name, 100, "%s/%s_temp_%llu", za->za_pool, za->za_pool,
1305             (u_longlong_t)za->za_instance);
1306
1307         basemode = DS_MODE_TYPE(za->za_instance);
1308         if (basemode != DS_MODE_USER && basemode != DS_MODE_OWNER)
1309                 basemode = DS_MODE_USER;
1310
1311         /*
1312          * If this dataset exists from a previous run, process its replay log
1313          * half of the time.  If we don't replay it, then dmu_objset_destroy()
1314          * (invoked from ztest_destroy_cb() below) should just throw it away.
1315          */
1316         if (ztest_random(2) == 0 &&
1317             dmu_objset_open(name, DMU_OST_OTHER, DS_MODE_OWNER, &os) == 0) {
1318                 zil_replay(os, os, ztest_replay_vector);
1319                 dmu_objset_close(os);
1320         }
1321
1322         /*
1323          * There may be an old instance of the dataset we're about to
1324          * create lying around from a previous run.  If so, destroy it
1325          * and all of its snapshots.
1326          */
1327         (void) dmu_objset_find(name, ztest_destroy_cb, za,
1328             DS_FIND_CHILDREN | DS_FIND_SNAPSHOTS);
1329
1330         /*
1331          * Verify that the destroyed dataset is no longer in the namespace.
1332          */
1333         error = dmu_objset_open(name, DMU_OST_OTHER, basemode, &os);
1334         if (error != ENOENT)
1335                 fatal(1, "dmu_objset_open(%s) found destroyed dataset %p",
1336                     name, os);
1337
1338         /*
1339          * Verify that we can create a new dataset.
1340          */
1341         error = dmu_objset_create(name, DMU_OST_OTHER, NULL, 0,
1342             ztest_create_cb, NULL);
1343         if (error) {
1344                 if (error == ENOSPC) {
1345                         ztest_record_enospc("dmu_objset_create");
1346                         (void) rw_unlock(&ztest_shared->zs_name_lock);
1347                         return;
1348                 }
1349                 fatal(0, "dmu_objset_create(%s) = %d", name, error);
1350         }
1351
1352         error = dmu_objset_open(name, DMU_OST_OTHER, basemode, &os);
1353         if (error) {
1354                 fatal(0, "dmu_objset_open(%s) = %d", name, error);
1355         }
1356
1357         /*
1358          * Open the intent log for it.
1359          */
1360         zilog = zil_open(os, NULL);
1361
1362         /*
1363          * Put a random number of objects in there.
1364          */
1365         objects = ztest_random(20);
1366         seq = 0;
1367         while (objects-- != 0) {
1368                 uint64_t object;
1369                 dmu_tx_t *tx = dmu_tx_create(os);
1370                 dmu_tx_hold_write(tx, DMU_NEW_OBJECT, 0, sizeof (name));
1371                 error = dmu_tx_assign(tx, TXG_WAIT);
1372                 if (error) {
1373                         dmu_tx_abort(tx);
1374                 } else {
1375                         object = dmu_object_alloc(os, DMU_OT_UINT64_OTHER, 0,
1376                             DMU_OT_NONE, 0, tx);
1377                         ztest_set_random_blocksize(os, object, tx);
1378                         seq = ztest_log_create(zilog, tx, object,
1379                             DMU_OT_UINT64_OTHER);
1380                         dmu_write(os, object, 0, sizeof (name), name, tx);
1381                         dmu_tx_commit(tx);
1382                 }
1383                 if (ztest_random(5) == 0) {
1384                         zil_commit(zilog, seq, object);
1385                 }
1386                 if (ztest_random(100) == 0) {
1387                         error = zil_suspend(zilog);
1388                         if (error == 0) {
1389                                 zil_resume(zilog);
1390                         }
1391                 }
1392         }
1393
1394         /*
1395          * Verify that we cannot create an existing dataset.
1396          */
1397         error = dmu_objset_create(name, DMU_OST_OTHER, NULL, 0, NULL, NULL);
1398         if (error != EEXIST)
1399                 fatal(0, "created existing dataset, error = %d", error);
1400
1401         /*
1402          * Verify that multiple dataset holds are allowed, but only when
1403          * the new access mode is compatible with the base mode.
1404          */
1405         if (basemode == DS_MODE_OWNER) {
1406                 error = dmu_objset_open(name, DMU_OST_OTHER, DS_MODE_USER,
1407                     &os2);
1408                 if (error)
1409                         fatal(0, "dmu_objset_open('%s') = %d", name, error);
1410                 else
1411                         dmu_objset_close(os2);
1412         }
1413         error = dmu_objset_open(name, DMU_OST_OTHER, DS_MODE_OWNER, &os2);
1414         expected_error = (basemode == DS_MODE_OWNER) ? EBUSY : 0;
1415         if (error != expected_error)
1416                 fatal(0, "dmu_objset_open('%s') = %d, expected %d",
1417                     name, error, expected_error);
1418         if (error == 0)
1419                 dmu_objset_close(os2);
1420
1421         zil_close(zilog);
1422         dmu_objset_close(os);
1423
1424         error = dmu_objset_destroy(name);
1425         if (error)
1426                 fatal(0, "dmu_objset_destroy(%s) = %d", name, error);
1427
1428         (void) rw_unlock(&ztest_shared->zs_name_lock);
1429 }
1430
1431 /*
1432  * Verify that dmu_snapshot_{create,destroy,open,close} work as expected.
1433  */
1434 void
1435 ztest_dmu_snapshot_create_destroy(ztest_args_t *za)
1436 {
1437         int error;
1438         objset_t *os = za->za_os;
1439         char snapname[100];
1440         char osname[MAXNAMELEN];
1441
1442         (void) rw_rdlock(&ztest_shared->zs_name_lock);
1443         dmu_objset_name(os, osname);
1444         (void) snprintf(snapname, 100, "%s@%llu", osname,
1445             (u_longlong_t)za->za_instance);
1446
1447         error = dmu_objset_destroy(snapname);
1448         if (error != 0 && error != ENOENT)
1449                 fatal(0, "dmu_objset_destroy() = %d", error);
1450         error = dmu_objset_snapshot(osname, strchr(snapname, '@')+1,
1451             NULL, FALSE);
1452         if (error == ENOSPC)
1453                 ztest_record_enospc("dmu_take_snapshot");
1454         else if (error != 0 && error != EEXIST)
1455                 fatal(0, "dmu_take_snapshot() = %d", error);
1456         (void) rw_unlock(&ztest_shared->zs_name_lock);
1457 }
1458
1459 /*
1460  * Verify dsl_dataset_promote handles EBUSY
1461  */
1462 void
1463 ztest_dsl_dataset_promote_busy(ztest_args_t *za)
1464 {
1465         int error;
1466         objset_t *os = za->za_os;
1467         objset_t *clone;
1468         dsl_dataset_t *ds;
1469         char snap1name[100];
1470         char clone1name[100];
1471         char snap2name[100];
1472         char clone2name[100];
1473         char snap3name[100];
1474         char osname[MAXNAMELEN];
1475         static uint64_t uniq = 0;
1476         uint64_t curval;
1477
1478         curval = atomic_add_64_nv(&uniq, 5) - 5;
1479
1480         (void) rw_rdlock(&ztest_shared->zs_name_lock);
1481
1482         dmu_objset_name(os, osname);
1483         (void) snprintf(snap1name, 100, "%s@s1_%llu", osname, curval++);
1484         (void) snprintf(clone1name, 100, "%s/c1_%llu", osname, curval++);
1485         (void) snprintf(snap2name, 100, "%s@s2_%llu", clone1name, curval++);
1486         (void) snprintf(clone2name, 100, "%s/c2_%llu", osname, curval++);
1487         (void) snprintf(snap3name, 100, "%s@s3_%llu", clone1name, curval++);
1488
1489         error = dmu_objset_snapshot(osname, strchr(snap1name, '@')+1,
1490             NULL, FALSE);
1491         if (error && error != EEXIST) {
1492                 if (error == ENOSPC) {
1493                         ztest_record_enospc(FTAG);
1494                         goto out;
1495                 }
1496                 fatal(0, "dmu_take_snapshot(%s) = %d", snap1name, error);
1497         }
1498
1499         error = dmu_objset_open(snap1name, DMU_OST_OTHER,
1500             DS_MODE_USER | DS_MODE_READONLY, &clone);
1501         if (error)
1502                 fatal(0, "dmu_open_snapshot(%s) = %d", snap1name, error);
1503
1504         error = dmu_objset_create(clone1name, DMU_OST_OTHER, clone, 0,
1505             NULL, NULL);
1506         dmu_objset_close(clone);
1507         if (error) {
1508                 if (error == ENOSPC) {
1509                         ztest_record_enospc(FTAG);
1510                         goto out;
1511                 }
1512                 fatal(0, "dmu_objset_create(%s) = %d", clone1name, error);
1513         }
1514
1515         error = dmu_objset_snapshot(clone1name, strchr(snap2name, '@')+1,
1516             NULL, FALSE);
1517         if (error && error != EEXIST) {
1518                 if (error == ENOSPC) {
1519                         ztest_record_enospc(FTAG);
1520                         goto out;
1521                 }
1522                 fatal(0, "dmu_open_snapshot(%s) = %d", snap2name, error);
1523         }
1524
1525         error = dmu_objset_snapshot(clone1name, strchr(snap3name, '@')+1,
1526             NULL, FALSE);
1527         if (error && error != EEXIST) {
1528                 if (error == ENOSPC) {
1529                         ztest_record_enospc(FTAG);
1530                         goto out;
1531                 }
1532                 fatal(0, "dmu_open_snapshot(%s) = %d", snap3name, error);
1533         }
1534
1535         error = dmu_objset_open(snap3name, DMU_OST_OTHER,
1536             DS_MODE_USER | DS_MODE_READONLY, &clone);
1537         if (error)
1538                 fatal(0, "dmu_open_snapshot(%s) = %d", snap3name, error);
1539
1540         error = dmu_objset_create(clone2name, DMU_OST_OTHER, clone, 0,
1541             NULL, NULL);
1542         dmu_objset_close(clone);
1543         if (error) {
1544                 if (error == ENOSPC) {
1545                         ztest_record_enospc("dmu_objset_create");
1546                         goto out;
1547                 }
1548                 fatal(0, "dmu_objset_create(%s) = %d", clone2name, error);
1549         }
1550
1551         error = dsl_dataset_own(snap1name, 0, FTAG, &ds);
1552         if (error)
1553                 fatal(0, "dsl_dataset_own(%s) = %d", snap1name, error);
1554         error = dsl_dataset_promote(clone2name);
1555         if (error != EBUSY)
1556                 fatal(0, "dsl_dataset_promote(%s), %d, not EBUSY", clone2name,
1557                     error);
1558         dsl_dataset_disown(ds, FTAG);
1559
1560 out:
1561         error = dmu_objset_destroy(clone2name);
1562         if (error && error != ENOENT)
1563                 fatal(0, "dmu_objset_destroy(%s) = %d", clone2name, error);
1564
1565         error = dmu_objset_destroy(snap3name);
1566         if (error && error != ENOENT)
1567                 fatal(0, "dmu_objset_destroy(%s) = %d", snap2name, error);
1568
1569         error = dmu_objset_destroy(snap2name);
1570         if (error && error != ENOENT)
1571                 fatal(0, "dmu_objset_destroy(%s) = %d", snap2name, error);
1572
1573         error = dmu_objset_destroy(clone1name);
1574         if (error && error != ENOENT)
1575                 fatal(0, "dmu_objset_destroy(%s) = %d", clone1name, error);
1576         error = dmu_objset_destroy(snap1name);
1577         if (error && error != ENOENT)
1578                 fatal(0, "dmu_objset_destroy(%s) = %d", snap1name, error);
1579
1580         (void) rw_unlock(&ztest_shared->zs_name_lock);
1581 }
1582
1583 /*
1584  * Verify that dmu_object_{alloc,free} work as expected.
1585  */
1586 void
1587 ztest_dmu_object_alloc_free(ztest_args_t *za)
1588 {
1589         objset_t *os = za->za_os;
1590         dmu_buf_t *db;
1591         dmu_tx_t *tx;
1592         uint64_t batchobj, object, batchsize, endoff, temp;
1593         int b, c, error, bonuslen;
1594         dmu_object_info_t *doi = &za->za_doi;
1595         char osname[MAXNAMELEN];
1596
1597         dmu_objset_name(os, osname);
1598
1599         endoff = -8ULL;
1600         batchsize = 2;
1601
1602         /*
1603          * Create a batch object if necessary, and record it in the directory.
1604          */
1605         VERIFY3U(0, ==, dmu_read(os, ZTEST_DIROBJ, za->za_diroff,
1606             sizeof (uint64_t), &batchobj, DMU_READ_PREFETCH));
1607         if (batchobj == 0) {
1608                 tx = dmu_tx_create(os);
1609                 dmu_tx_hold_write(tx, ZTEST_DIROBJ, za->za_diroff,
1610                     sizeof (uint64_t));
1611                 dmu_tx_hold_bonus(tx, DMU_NEW_OBJECT);
1612                 error = dmu_tx_assign(tx, TXG_WAIT);
1613                 if (error) {
1614                         ztest_record_enospc("create a batch object");
1615                         dmu_tx_abort(tx);
1616                         return;
1617                 }
1618                 batchobj = dmu_object_alloc(os, DMU_OT_UINT64_OTHER, 0,
1619                     DMU_OT_NONE, 0, tx);
1620                 ztest_set_random_blocksize(os, batchobj, tx);
1621                 dmu_write(os, ZTEST_DIROBJ, za->za_diroff,
1622                     sizeof (uint64_t), &batchobj, tx);
1623                 dmu_tx_commit(tx);
1624         }
1625
1626         /*
1627          * Destroy the previous batch of objects.
1628          */
1629         for (b = 0; b < batchsize; b++) {
1630                 VERIFY3U(0, ==, dmu_read(os, batchobj, b * sizeof (uint64_t),
1631                     sizeof (uint64_t), &object, DMU_READ_PREFETCH));
1632                 if (object == 0)
1633                         continue;
1634                 /*
1635                  * Read and validate contents.
1636                  * We expect the nth byte of the bonus buffer to be n.
1637                  */
1638                 VERIFY(0 == dmu_bonus_hold(os, object, FTAG, &db));
1639                 za->za_dbuf = db;
1640
1641                 dmu_object_info_from_db(db, doi);
1642                 ASSERT(doi->doi_type == DMU_OT_UINT64_OTHER);
1643                 ASSERT(doi->doi_bonus_type == DMU_OT_PLAIN_OTHER);
1644                 ASSERT3S(doi->doi_physical_blks, >=, 0);
1645
1646                 bonuslen = doi->doi_bonus_size;
1647
1648                 for (c = 0; c < bonuslen; c++) {
1649                         if (((uint8_t *)db->db_data)[c] !=
1650                             (uint8_t)(c + bonuslen)) {
1651                                 fatal(0,
1652                                     "bad bonus: %s, obj %llu, off %d: %u != %u",
1653                                     osname, object, c,
1654                                     ((uint8_t *)db->db_data)[c],
1655                                     (uint8_t)(c + bonuslen));
1656                         }
1657                 }
1658
1659                 dmu_buf_rele(db, FTAG);
1660                 za->za_dbuf = NULL;
1661
1662                 /*
1663                  * We expect the word at endoff to be our object number.
1664                  */
1665                 VERIFY(0 == dmu_read(os, object, endoff,
1666                     sizeof (uint64_t), &temp, DMU_READ_PREFETCH));
1667
1668                 if (temp != object) {
1669                         fatal(0, "bad data in %s, got %llu, expected %llu",
1670                             osname, temp, object);
1671                 }
1672
1673                 /*
1674                  * Destroy old object and clear batch entry.
1675                  */
1676                 tx = dmu_tx_create(os);
1677                 dmu_tx_hold_write(tx, batchobj,
1678                     b * sizeof (uint64_t), sizeof (uint64_t));
1679                 dmu_tx_hold_free(tx, object, 0, DMU_OBJECT_END);
1680                 error = dmu_tx_assign(tx, TXG_WAIT);
1681                 if (error) {
1682                         ztest_record_enospc("free object");
1683                         dmu_tx_abort(tx);
1684                         return;
1685                 }
1686                 error = dmu_object_free(os, object, tx);
1687                 if (error) {
1688                         fatal(0, "dmu_object_free('%s', %llu) = %d",
1689                             osname, object, error);
1690                 }
1691                 object = 0;
1692
1693                 dmu_object_set_checksum(os, batchobj,
1694                     ztest_random_checksum(), tx);
1695                 dmu_object_set_compress(os, batchobj,
1696                     ztest_random_compress(), tx);
1697
1698                 dmu_write(os, batchobj, b * sizeof (uint64_t),
1699                     sizeof (uint64_t), &object, tx);
1700
1701                 dmu_tx_commit(tx);
1702         }
1703
1704         /*
1705          * Before creating the new batch of objects, generate a bunch of churn.
1706          */
1707         for (b = ztest_random(100); b > 0; b--) {
1708                 tx = dmu_tx_create(os);
1709                 dmu_tx_hold_bonus(tx, DMU_NEW_OBJECT);
1710                 error = dmu_tx_assign(tx, TXG_WAIT);
1711                 if (error) {
1712                         ztest_record_enospc("churn objects");
1713                         dmu_tx_abort(tx);
1714                         return;
1715                 }
1716                 object = dmu_object_alloc(os, DMU_OT_UINT64_OTHER, 0,
1717                     DMU_OT_NONE, 0, tx);
1718                 ztest_set_random_blocksize(os, object, tx);
1719                 error = dmu_object_free(os, object, tx);
1720                 if (error) {
1721                         fatal(0, "dmu_object_free('%s', %llu) = %d",
1722                             osname, object, error);
1723                 }
1724                 dmu_tx_commit(tx);
1725         }
1726
1727         /*
1728          * Create a new batch of objects with randomly chosen
1729          * blocksizes and record them in the batch directory.
1730          */
1731         for (b = 0; b < batchsize; b++) {
1732                 uint32_t va_blksize;
1733                 u_longlong_t va_nblocks;
1734
1735                 tx = dmu_tx_create(os);
1736                 dmu_tx_hold_write(tx, batchobj, b * sizeof (uint64_t),
1737                     sizeof (uint64_t));
1738                 dmu_tx_hold_bonus(tx, DMU_NEW_OBJECT);
1739                 dmu_tx_hold_write(tx, DMU_NEW_OBJECT, endoff,
1740                     sizeof (uint64_t));
1741                 error = dmu_tx_assign(tx, TXG_WAIT);
1742                 if (error) {
1743                         ztest_record_enospc("create batchobj");
1744                         dmu_tx_abort(tx);
1745                         return;
1746                 }
1747                 bonuslen = (int)ztest_random(dmu_bonus_max()) + 1;
1748
1749                 object = dmu_object_alloc(os, DMU_OT_UINT64_OTHER, 0,
1750                     DMU_OT_PLAIN_OTHER, bonuslen, tx);
1751
1752                 ztest_set_random_blocksize(os, object, tx);
1753
1754                 dmu_object_set_checksum(os, object,
1755                     ztest_random_checksum(), tx);
1756                 dmu_object_set_compress(os, object,
1757                     ztest_random_compress(), tx);
1758
1759                 dmu_write(os, batchobj, b * sizeof (uint64_t),
1760                     sizeof (uint64_t), &object, tx);
1761
1762                 /*
1763                  * Write to both the bonus buffer and the regular data.
1764                  */
1765                 VERIFY(dmu_bonus_hold(os, object, FTAG, &db) == 0);
1766                 za->za_dbuf = db;
1767                 ASSERT3U(bonuslen, <=, db->db_size);
1768
1769                 dmu_object_size_from_db(db, &va_blksize, &va_nblocks);
1770                 ASSERT3S(va_nblocks, >=, 0);
1771
1772                 dmu_buf_will_dirty(db, tx);
1773
1774                 /*
1775                  * See comments above regarding the contents of
1776                  * the bonus buffer and the word at endoff.
1777                  */
1778                 for (c = 0; c < bonuslen; c++)
1779                         ((uint8_t *)db->db_data)[c] = (uint8_t)(c + bonuslen);
1780
1781                 dmu_buf_rele(db, FTAG);
1782                 za->za_dbuf = NULL;
1783
1784                 /*
1785                  * Write to a large offset to increase indirection.
1786                  */
1787                 dmu_write(os, object, endoff, sizeof (uint64_t), &object, tx);
1788
1789                 dmu_tx_commit(tx);
1790         }
1791 }
1792
1793 /*
1794  * Verify that dmu_{read,write} work as expected.
1795  */
1796 typedef struct bufwad {
1797         uint64_t        bw_index;
1798         uint64_t        bw_txg;
1799         uint64_t        bw_data;
1800 } bufwad_t;
1801
1802 typedef struct dmu_read_write_dir {
1803         uint64_t        dd_packobj;
1804         uint64_t        dd_bigobj;
1805         uint64_t        dd_chunk;
1806 } dmu_read_write_dir_t;
1807
1808 void
1809 ztest_dmu_read_write(ztest_args_t *za)
1810 {
1811         objset_t *os = za->za_os;
1812         dmu_read_write_dir_t dd;
1813         dmu_tx_t *tx;
1814         int i, freeit, error;
1815         uint64_t n, s, txg;
1816         bufwad_t *packbuf, *bigbuf, *pack, *bigH, *bigT;
1817         uint64_t packoff, packsize, bigoff, bigsize;
1818         uint64_t regions = 997;
1819         uint64_t stride = 123456789ULL;
1820         uint64_t width = 40;
1821         int free_percent = 5;
1822
1823         /*
1824          * This test uses two objects, packobj and bigobj, that are always
1825          * updated together (i.e. in the same tx) so that their contents are
1826          * in sync and can be compared.  Their contents relate to each other
1827          * in a simple way: packobj is a dense array of 'bufwad' structures,
1828          * while bigobj is a sparse array of the same bufwads.  Specifically,
1829          * for any index n, there are three bufwads that should be identical:
1830          *
1831          *      packobj, at offset n * sizeof (bufwad_t)
1832          *      bigobj, at the head of the nth chunk
1833          *      bigobj, at the tail of the nth chunk
1834          *
1835          * The chunk size is arbitrary. It doesn't have to be a power of two,
1836          * and it doesn't have any relation to the object blocksize.
1837          * The only requirement is that it can hold at least two bufwads.
1838          *
1839          * Normally, we write the bufwad to each of these locations.
1840          * However, free_percent of the time we instead write zeroes to
1841          * packobj and perform a dmu_free_range() on bigobj.  By comparing
1842          * bigobj to packobj, we can verify that the DMU is correctly
1843          * tracking which parts of an object are allocated and free,
1844          * and that the contents of the allocated blocks are correct.
1845          */
1846
1847         /*
1848          * Read the directory info.  If it's the first time, set things up.
1849          */
1850         VERIFY(0 == dmu_read(os, ZTEST_DIROBJ, za->za_diroff,
1851             sizeof (dd), &dd, DMU_READ_PREFETCH));
1852         if (dd.dd_chunk == 0) {
1853                 ASSERT(dd.dd_packobj == 0);
1854                 ASSERT(dd.dd_bigobj == 0);
1855                 tx = dmu_tx_create(os);
1856                 dmu_tx_hold_write(tx, ZTEST_DIROBJ, za->za_diroff, sizeof (dd));
1857                 dmu_tx_hold_bonus(tx, DMU_NEW_OBJECT);
1858                 error = dmu_tx_assign(tx, TXG_WAIT);
1859                 if (error) {
1860                         ztest_record_enospc("create r/w directory");
1861                         dmu_tx_abort(tx);
1862                         return;
1863                 }
1864
1865                 dd.dd_packobj = dmu_object_alloc(os, DMU_OT_UINT64_OTHER, 0,
1866                     DMU_OT_NONE, 0, tx);
1867                 dd.dd_bigobj = dmu_object_alloc(os, DMU_OT_UINT64_OTHER, 0,
1868                     DMU_OT_NONE, 0, tx);
1869                 dd.dd_chunk = (1000 + ztest_random(1000)) * sizeof (uint64_t);
1870
1871                 ztest_set_random_blocksize(os, dd.dd_packobj, tx);
1872                 ztest_set_random_blocksize(os, dd.dd_bigobj, tx);
1873
1874                 dmu_write(os, ZTEST_DIROBJ, za->za_diroff, sizeof (dd), &dd,
1875                     tx);
1876                 dmu_tx_commit(tx);
1877         }
1878
1879         /*
1880          * Prefetch a random chunk of the big object.
1881          * Our aim here is to get some async reads in flight
1882          * for blocks that we may free below; the DMU should
1883          * handle this race correctly.
1884          */
1885         n = ztest_random(regions) * stride + ztest_random(width);
1886         s = 1 + ztest_random(2 * width - 1);
1887         dmu_prefetch(os, dd.dd_bigobj, n * dd.dd_chunk, s * dd.dd_chunk);
1888
1889         /*
1890          * Pick a random index and compute the offsets into packobj and bigobj.
1891          */
1892         n = ztest_random(regions) * stride + ztest_random(width);
1893         s = 1 + ztest_random(width - 1);
1894
1895         packoff = n * sizeof (bufwad_t);
1896         packsize = s * sizeof (bufwad_t);
1897
1898         bigoff = n * dd.dd_chunk;
1899         bigsize = s * dd.dd_chunk;
1900
1901         packbuf = umem_alloc(packsize, UMEM_NOFAIL);
1902         bigbuf = umem_alloc(bigsize, UMEM_NOFAIL);
1903
1904         /*
1905          * free_percent of the time, free a range of bigobj rather than
1906          * overwriting it.
1907          */
1908         freeit = (ztest_random(100) < free_percent);
1909
1910         /*
1911          * Read the current contents of our objects.
1912          */
1913         error = dmu_read(os, dd.dd_packobj, packoff, packsize, packbuf,
1914             DMU_READ_PREFETCH);
1915         ASSERT3U(error, ==, 0);
1916         error = dmu_read(os, dd.dd_bigobj, bigoff, bigsize, bigbuf,
1917             DMU_READ_PREFETCH);
1918         ASSERT3U(error, ==, 0);
1919
1920         /*
1921          * Get a tx for the mods to both packobj and bigobj.
1922          */
1923         tx = dmu_tx_create(os);
1924
1925         dmu_tx_hold_write(tx, dd.dd_packobj, packoff, packsize);
1926
1927         if (freeit)
1928                 dmu_tx_hold_free(tx, dd.dd_bigobj, bigoff, bigsize);
1929         else
1930                 dmu_tx_hold_write(tx, dd.dd_bigobj, bigoff, bigsize);
1931
1932         error = dmu_tx_assign(tx, TXG_WAIT);
1933
1934         if (error) {
1935                 ztest_record_enospc("dmu r/w range");
1936                 dmu_tx_abort(tx);
1937                 umem_free(packbuf, packsize);
1938                 umem_free(bigbuf, bigsize);
1939                 return;
1940         }
1941
1942         txg = dmu_tx_get_txg(tx);
1943
1944         /*
1945          * For each index from n to n + s, verify that the existing bufwad
1946          * in packobj matches the bufwads at the head and tail of the
1947          * corresponding chunk in bigobj.  Then update all three bufwads
1948          * with the new values we want to write out.
1949          */
1950         for (i = 0; i < s; i++) {
1951                 /* LINTED */
1952                 pack = (bufwad_t *)((char *)packbuf + i * sizeof (bufwad_t));
1953                 /* LINTED */
1954                 bigH = (bufwad_t *)((char *)bigbuf + i * dd.dd_chunk);
1955                 /* LINTED */
1956                 bigT = (bufwad_t *)((char *)bigH + dd.dd_chunk) - 1;
1957
1958                 ASSERT((uintptr_t)bigH - (uintptr_t)bigbuf < bigsize);
1959                 ASSERT((uintptr_t)bigT - (uintptr_t)bigbuf < bigsize);
1960
1961                 if (pack->bw_txg > txg)
1962                         fatal(0, "future leak: got %llx, open txg is %llx",
1963                             pack->bw_txg, txg);
1964
1965                 if (pack->bw_data != 0 && pack->bw_index != n + i)
1966                         fatal(0, "wrong index: got %llx, wanted %llx+%llx",
1967                             pack->bw_index, n, i);
1968
1969                 if (bcmp(pack, bigH, sizeof (bufwad_t)) != 0)
1970                         fatal(0, "pack/bigH mismatch in %p/%p", pack, bigH);
1971
1972                 if (bcmp(pack, bigT, sizeof (bufwad_t)) != 0)
1973                         fatal(0, "pack/bigT mismatch in %p/%p", pack, bigT);
1974
1975                 if (freeit) {
1976                         bzero(pack, sizeof (bufwad_t));
1977                 } else {
1978                         pack->bw_index = n + i;
1979                         pack->bw_txg = txg;
1980                         pack->bw_data = 1 + ztest_random(-2ULL);
1981                 }
1982                 *bigH = *pack;
1983                 *bigT = *pack;
1984         }
1985
1986         /*
1987          * We've verified all the old bufwads, and made new ones.
1988          * Now write them out.
1989          */
1990         dmu_write(os, dd.dd_packobj, packoff, packsize, packbuf, tx);
1991
1992         if (freeit) {
1993                 if (zopt_verbose >= 6) {
1994                         (void) printf("freeing offset %llx size %llx"
1995                             " txg %llx\n",
1996                             (u_longlong_t)bigoff,
1997                             (u_longlong_t)bigsize,
1998                             (u_longlong_t)txg);
1999                 }
2000                 VERIFY(0 == dmu_free_range(os, dd.dd_bigobj, bigoff,
2001                     bigsize, tx));
2002         } else {
2003                 if (zopt_verbose >= 6) {
2004                         (void) printf("writing offset %llx size %llx"
2005                             " txg %llx\n",
2006                             (u_longlong_t)bigoff,
2007                             (u_longlong_t)bigsize,
2008                             (u_longlong_t)txg);
2009                 }
2010                 dmu_write(os, dd.dd_bigobj, bigoff, bigsize, bigbuf, tx);
2011         }
2012
2013         dmu_tx_commit(tx);
2014
2015         /*
2016          * Sanity check the stuff we just wrote.
2017          */
2018         {
2019                 void *packcheck = umem_alloc(packsize, UMEM_NOFAIL);
2020                 void *bigcheck = umem_alloc(bigsize, UMEM_NOFAIL);
2021
2022                 VERIFY(0 == dmu_read(os, dd.dd_packobj, packoff,
2023                     packsize, packcheck, DMU_READ_PREFETCH));
2024                 VERIFY(0 == dmu_read(os, dd.dd_bigobj, bigoff,
2025                     bigsize, bigcheck, DMU_READ_PREFETCH));
2026
2027                 ASSERT(bcmp(packbuf, packcheck, packsize) == 0);
2028                 ASSERT(bcmp(bigbuf, bigcheck, bigsize) == 0);
2029
2030                 umem_free(packcheck, packsize);
2031                 umem_free(bigcheck, bigsize);
2032         }
2033
2034         umem_free(packbuf, packsize);
2035         umem_free(bigbuf, bigsize);
2036 }
2037
2038 void
2039 compare_and_update_pbbufs(uint64_t s, bufwad_t *packbuf, bufwad_t *bigbuf,
2040     uint64_t bigsize, uint64_t n, dmu_read_write_dir_t dd, uint64_t txg)
2041 {
2042         uint64_t i;
2043         bufwad_t *pack;
2044         bufwad_t *bigH;
2045         bufwad_t *bigT;
2046
2047         /*
2048          * For each index from n to n + s, verify that the existing bufwad
2049          * in packobj matches the bufwads at the head and tail of the
2050          * corresponding chunk in bigobj.  Then update all three bufwads
2051          * with the new values we want to write out.
2052          */
2053         for (i = 0; i < s; i++) {
2054                 /* LINTED */
2055                 pack = (bufwad_t *)((char *)packbuf + i * sizeof (bufwad_t));
2056                 /* LINTED */
2057                 bigH = (bufwad_t *)((char *)bigbuf + i * dd.dd_chunk);
2058                 /* LINTED */
2059                 bigT = (bufwad_t *)((char *)bigH + dd.dd_chunk) - 1;
2060
2061                 ASSERT((uintptr_t)bigH - (uintptr_t)bigbuf < bigsize);
2062                 ASSERT((uintptr_t)bigT - (uintptr_t)bigbuf < bigsize);
2063
2064                 if (pack->bw_txg > txg)
2065                         fatal(0, "future leak: got %llx, open txg is %llx",
2066                             pack->bw_txg, txg);
2067
2068                 if (pack->bw_data != 0 && pack->bw_index != n + i)
2069                         fatal(0, "wrong index: got %llx, wanted %llx+%llx",
2070                             pack->bw_index, n, i);
2071
2072                 if (bcmp(pack, bigH, sizeof (bufwad_t)) != 0)
2073                         fatal(0, "pack/bigH mismatch in %p/%p", pack, bigH);
2074
2075                 if (bcmp(pack, bigT, sizeof (bufwad_t)) != 0)
2076                         fatal(0, "pack/bigT mismatch in %p/%p", pack, bigT);
2077
2078                 pack->bw_index = n + i;
2079                 pack->bw_txg = txg;
2080                 pack->bw_data = 1 + ztest_random(-2ULL);
2081
2082                 *bigH = *pack;
2083                 *bigT = *pack;
2084         }
2085 }
2086
2087 void
2088 ztest_dmu_read_write_zcopy(ztest_args_t *za)
2089 {
2090         objset_t *os = za->za_os;
2091         dmu_read_write_dir_t dd;
2092         dmu_tx_t *tx;
2093         uint64_t i;
2094         int error;
2095         uint64_t n, s, txg;
2096         bufwad_t *packbuf, *bigbuf;
2097         uint64_t packoff, packsize, bigoff, bigsize;
2098         uint64_t regions = 997;
2099         uint64_t stride = 123456789ULL;
2100         uint64_t width = 9;
2101         dmu_buf_t *bonus_db;
2102         arc_buf_t **bigbuf_arcbufs;
2103         dmu_object_info_t *doi = &za->za_doi;
2104
2105         /*
2106          * This test uses two objects, packobj and bigobj, that are always
2107          * updated together (i.e. in the same tx) so that their contents are
2108          * in sync and can be compared.  Their contents relate to each other
2109          * in a simple way: packobj is a dense array of 'bufwad' structures,
2110          * while bigobj is a sparse array of the same bufwads.  Specifically,
2111          * for any index n, there are three bufwads that should be identical:
2112          *
2113          *      packobj, at offset n * sizeof (bufwad_t)
2114          *      bigobj, at the head of the nth chunk
2115          *      bigobj, at the tail of the nth chunk
2116          *
2117          * The chunk size is set equal to bigobj block size so that
2118          * dmu_assign_arcbuf() can be tested for object updates.
2119          */
2120
2121         /*
2122          * Read the directory info.  If it's the first time, set things up.
2123          */
2124         VERIFY(0 == dmu_read(os, ZTEST_DIROBJ, za->za_diroff,
2125             sizeof (dd), &dd, DMU_READ_PREFETCH));
2126         if (dd.dd_chunk == 0) {
2127                 ASSERT(dd.dd_packobj == 0);
2128                 ASSERT(dd.dd_bigobj == 0);
2129                 tx = dmu_tx_create(os);
2130                 dmu_tx_hold_write(tx, ZTEST_DIROBJ, za->za_diroff, sizeof (dd));
2131                 dmu_tx_hold_bonus(tx, DMU_NEW_OBJECT);
2132                 error = dmu_tx_assign(tx, TXG_WAIT);
2133                 if (error) {
2134                         ztest_record_enospc("create r/w directory");
2135                         dmu_tx_abort(tx);
2136                         return;
2137                 }
2138
2139                 dd.dd_packobj = dmu_object_alloc(os, DMU_OT_UINT64_OTHER, 0,
2140                     DMU_OT_NONE, 0, tx);
2141                 dd.dd_bigobj = dmu_object_alloc(os, DMU_OT_UINT64_OTHER, 0,
2142                     DMU_OT_NONE, 0, tx);
2143                 ztest_set_random_blocksize(os, dd.dd_packobj, tx);
2144                 ztest_set_random_blocksize(os, dd.dd_bigobj, tx);
2145
2146                 VERIFY(dmu_object_info(os, dd.dd_bigobj, doi) == 0);
2147                 ASSERT(doi->doi_data_block_size >= 2 * sizeof (bufwad_t));
2148                 ASSERT(ISP2(doi->doi_data_block_size));
2149                 dd.dd_chunk = doi->doi_data_block_size;
2150
2151                 dmu_write(os, ZTEST_DIROBJ, za->za_diroff, sizeof (dd), &dd,
2152                     tx);
2153                 dmu_tx_commit(tx);
2154         } else {
2155                 VERIFY(dmu_object_info(os, dd.dd_bigobj, doi) == 0);
2156                 VERIFY(ISP2(doi->doi_data_block_size));
2157                 VERIFY(dd.dd_chunk == doi->doi_data_block_size);
2158                 VERIFY(dd.dd_chunk >= 2 * sizeof (bufwad_t));
2159         }
2160
2161         /*
2162          * Pick a random index and compute the offsets into packobj and bigobj.
2163          */
2164         n = ztest_random(regions) * stride + ztest_random(width);
2165         s = 1 + ztest_random(width - 1);
2166
2167         packoff = n * sizeof (bufwad_t);
2168         packsize = s * sizeof (bufwad_t);
2169
2170         bigoff = n * dd.dd_chunk;
2171         bigsize = s * dd.dd_chunk;
2172
2173         packbuf = umem_zalloc(packsize, UMEM_NOFAIL);
2174         bigbuf = umem_zalloc(bigsize, UMEM_NOFAIL);
2175
2176         VERIFY(dmu_bonus_hold(os, dd.dd_bigobj, FTAG, &bonus_db) == 0);
2177
2178         bigbuf_arcbufs = umem_zalloc(2 * s * sizeof (arc_buf_t *), UMEM_NOFAIL);
2179
2180         /*
2181          * Iteration 0 test zcopy for DB_UNCACHED dbufs.
2182          * Iteration 1 test zcopy to already referenced dbufs.
2183          * Iteration 2 test zcopy to dirty dbuf in the same txg.
2184          * Iteration 3 test zcopy to dbuf dirty in previous txg.
2185          * Iteration 4 test zcopy when dbuf is no longer dirty.
2186          * Iteration 5 test zcopy when it can't be done.
2187          * Iteration 6 one more zcopy write.
2188          */
2189         for (i = 0; i < 7; i++) {
2190                 uint64_t j;
2191                 uint64_t off;
2192
2193                 /*
2194                  * In iteration 5 (i == 5) use arcbufs
2195                  * that don't match bigobj blksz to test
2196                  * dmu_assign_arcbuf() when it can't directly
2197                  * assign an arcbuf to a dbuf.
2198                  */
2199                 for (j = 0; j < s; j++) {
2200                         if (i != 5) {
2201                                 bigbuf_arcbufs[j] =
2202                                     dmu_request_arcbuf(bonus_db,
2203                                     dd.dd_chunk);
2204                         } else {
2205                                 bigbuf_arcbufs[2 * j] =
2206                                     dmu_request_arcbuf(bonus_db,
2207                                     dd.dd_chunk / 2);
2208                                 bigbuf_arcbufs[2 * j + 1] =
2209                                     dmu_request_arcbuf(bonus_db,
2210                                     dd.dd_chunk / 2);
2211                         }
2212                 }
2213
2214                 /*
2215                  * Get a tx for the mods to both packobj and bigobj.
2216                  */
2217                 tx = dmu_tx_create(os);
2218
2219                 dmu_tx_hold_write(tx, dd.dd_packobj, packoff, packsize);
2220                 dmu_tx_hold_write(tx, dd.dd_bigobj, bigoff, bigsize);
2221
2222                 if (ztest_random(100) == 0) {
2223                         error = -1;
2224                 } else {
2225                         error = dmu_tx_assign(tx, TXG_WAIT);
2226                 }
2227
2228                 if (error) {
2229                         if (error != -1) {
2230                                 ztest_record_enospc("dmu r/w range");
2231                         }
2232                         dmu_tx_abort(tx);
2233                         umem_free(packbuf, packsize);
2234                         umem_free(bigbuf, bigsize);
2235                         for (j = 0; j < s; j++) {
2236                                 if (i != 5) {
2237                                         dmu_return_arcbuf(bigbuf_arcbufs[j]);
2238                                 } else {
2239                                         dmu_return_arcbuf(
2240                                             bigbuf_arcbufs[2 * j]);
2241                                         dmu_return_arcbuf(
2242                                             bigbuf_arcbufs[2 * j + 1]);
2243                                 }
2244                         }
2245                         umem_free(bigbuf_arcbufs, 2 * s * sizeof (arc_buf_t *));
2246                         dmu_buf_rele(bonus_db, FTAG);
2247                         return;
2248                 }
2249
2250                 txg = dmu_tx_get_txg(tx);
2251
2252                 /*
2253                  * 50% of the time don't read objects in the 1st iteration to
2254                  * test dmu_assign_arcbuf() for the case when there're no
2255                  * existing dbufs for the specified offsets.
2256                  */
2257                 if (i != 0 || ztest_random(2) != 0) {
2258                         error = dmu_read(os, dd.dd_packobj, packoff,
2259                             packsize, packbuf, DMU_READ_PREFETCH);
2260                         ASSERT3U(error, ==, 0);
2261                         error = dmu_read(os, dd.dd_bigobj, bigoff, bigsize,
2262                             bigbuf, DMU_READ_PREFETCH);
2263                         ASSERT3U(error, ==, 0);
2264                 }
2265                 compare_and_update_pbbufs(s, packbuf, bigbuf, bigsize,
2266                     n, dd, txg);
2267
2268                 /*
2269                  * We've verified all the old bufwads, and made new ones.
2270                  * Now write them out.
2271                  */
2272                 dmu_write(os, dd.dd_packobj, packoff, packsize, packbuf, tx);
2273                 if (zopt_verbose >= 6) {
2274                         (void) printf("writing offset %llx size %llx"
2275                             " txg %llx\n",
2276                             (u_longlong_t)bigoff,
2277                             (u_longlong_t)bigsize,
2278                             (u_longlong_t)txg);
2279                 }
2280                 for (off = bigoff, j = 0; j < s; j++, off += dd.dd_chunk) {
2281                         dmu_buf_t *dbt;
2282                         if (i != 5) {
2283                                 bcopy((caddr_t)bigbuf + (off - bigoff),
2284                                     bigbuf_arcbufs[j]->b_data, dd.dd_chunk);
2285                         } else {
2286                                 bcopy((caddr_t)bigbuf + (off - bigoff),
2287                                     bigbuf_arcbufs[2 * j]->b_data,
2288                                     dd.dd_chunk / 2);
2289                                 bcopy((caddr_t)bigbuf + (off - bigoff) +
2290                                     dd.dd_chunk / 2,
2291                                     bigbuf_arcbufs[2 * j + 1]->b_data,
2292                                     dd.dd_chunk / 2);
2293                         }
2294
2295                         if (i == 1) {
2296                                 VERIFY(dmu_buf_hold(os, dd.dd_bigobj, off,
2297                                     FTAG, &dbt) == 0);
2298                         }
2299                         if (i != 5) {
2300                                 dmu_assign_arcbuf(bonus_db, off,
2301                                     bigbuf_arcbufs[j], tx);
2302                         } else {
2303                                 dmu_assign_arcbuf(bonus_db, off,
2304                                     bigbuf_arcbufs[2 * j], tx);
2305                                 dmu_assign_arcbuf(bonus_db,
2306                                     off + dd.dd_chunk / 2,
2307                                     bigbuf_arcbufs[2 * j + 1], tx);
2308                         }
2309                         if (i == 1) {
2310                                 dmu_buf_rele(dbt, FTAG);
2311                         }
2312                 }
2313                 dmu_tx_commit(tx);
2314
2315                 /*
2316                  * Sanity check the stuff we just wrote.
2317                  */
2318                 {
2319                         void *packcheck = umem_alloc(packsize, UMEM_NOFAIL);
2320                         void *bigcheck = umem_alloc(bigsize, UMEM_NOFAIL);
2321
2322                         VERIFY(0 == dmu_read(os, dd.dd_packobj, packoff,
2323                             packsize, packcheck, DMU_READ_PREFETCH));
2324                         VERIFY(0 == dmu_read(os, dd.dd_bigobj, bigoff,
2325                             bigsize, bigcheck, DMU_READ_PREFETCH));
2326
2327                         ASSERT(bcmp(packbuf, packcheck, packsize) == 0);
2328                         ASSERT(bcmp(bigbuf, bigcheck, bigsize) == 0);
2329
2330                         umem_free(packcheck, packsize);
2331                         umem_free(bigcheck, bigsize);
2332                 }
2333                 if (i == 2) {
2334                         txg_wait_open(dmu_objset_pool(os), 0);
2335                 } else if (i == 3) {
2336                         txg_wait_synced(dmu_objset_pool(os), 0);
2337                 }
2338         }
2339
2340         dmu_buf_rele(bonus_db, FTAG);
2341         umem_free(packbuf, packsize);
2342         umem_free(bigbuf, bigsize);
2343         umem_free(bigbuf_arcbufs, 2 * s * sizeof (arc_buf_t *));
2344 }
2345
2346 void
2347 ztest_dmu_check_future_leak(ztest_args_t *za)
2348 {
2349         objset_t *os = za->za_os;
2350         dmu_buf_t *db;
2351         ztest_block_tag_t *bt;
2352         dmu_object_info_t *doi = &za->za_doi;
2353
2354         /*
2355          * Make sure that, if there is a write record in the bonus buffer
2356          * of the ZTEST_DIROBJ, that the txg for this record is <= the
2357          * last synced txg of the pool.
2358          */
2359         VERIFY(dmu_bonus_hold(os, ZTEST_DIROBJ, FTAG, &db) == 0);
2360         za->za_dbuf = db;
2361         VERIFY(dmu_object_info(os, ZTEST_DIROBJ, doi) == 0);
2362         ASSERT3U(doi->doi_bonus_size, >=, sizeof (*bt));
2363         ASSERT3U(doi->doi_bonus_size, <=, db->db_size);
2364         ASSERT3U(doi->doi_bonus_size % sizeof (*bt), ==, 0);
2365         bt = (void *)((char *)db->db_data + doi->doi_bonus_size - sizeof (*bt));
2366         if (bt->bt_objset != 0) {
2367                 ASSERT3U(bt->bt_objset, ==, dmu_objset_id(os));
2368                 ASSERT3U(bt->bt_object, ==, ZTEST_DIROBJ);
2369                 ASSERT3U(bt->bt_offset, ==, -1ULL);
2370                 ASSERT3U(bt->bt_txg, <, spa_first_txg(za->za_spa));
2371         }
2372         dmu_buf_rele(db, FTAG);
2373         za->za_dbuf = NULL;
2374 }
2375
2376 void
2377 ztest_dmu_write_parallel(ztest_args_t *za)
2378 {
2379         objset_t *os = za->za_os;
2380         ztest_block_tag_t *rbt = &za->za_rbt;
2381         ztest_block_tag_t *wbt = &za->za_wbt;
2382         const size_t btsize = sizeof (ztest_block_tag_t);
2383         dmu_buf_t *db;
2384         int b, error;
2385         int bs = ZTEST_DIROBJ_BLOCKSIZE;
2386         int do_free = 0;
2387         uint64_t off, txg, txg_how;
2388         mutex_t *lp;
2389         char osname[MAXNAMELEN];
2390         char iobuf[SPA_MAXBLOCKSIZE];
2391         blkptr_t blk = { 0 };
2392         uint64_t blkoff;
2393         zbookmark_t zb;
2394         dmu_tx_t *tx = dmu_tx_create(os);
2395         dmu_buf_t *bonus_db;
2396         arc_buf_t *abuf = NULL;
2397
2398         dmu_objset_name(os, osname);
2399
2400         /*
2401          * Have multiple threads write to large offsets in ZTEST_DIROBJ
2402          * to verify that having multiple threads writing to the same object
2403          * in parallel doesn't cause any trouble.
2404          */
2405         if (ztest_random(4) == 0) {
2406                 /*
2407                  * Do the bonus buffer instead of a regular block.
2408                  * We need a lock to serialize resize vs. others,
2409                  * so we hash on the objset ID.
2410                  */
2411                 b = dmu_objset_id(os) % ZTEST_SYNC_LOCKS;
2412                 off = -1ULL;
2413                 dmu_tx_hold_bonus(tx, ZTEST_DIROBJ);
2414         } else {
2415                 b = ztest_random(ZTEST_SYNC_LOCKS);
2416                 off = za->za_diroff_shared + (b << SPA_MAXBLOCKSHIFT);
2417                 if (ztest_random(4) == 0) {
2418                         do_free = 1;
2419                         dmu_tx_hold_free(tx, ZTEST_DIROBJ, off, bs);
2420                 } else {
2421                         dmu_tx_hold_write(tx, ZTEST_DIROBJ, off, bs);
2422                 }
2423         }
2424
2425         if (off != -1ULL && P2PHASE(off, bs) == 0 && !do_free &&
2426             ztest_random(8) == 0) {
2427                 VERIFY(dmu_bonus_hold(os, ZTEST_DIROBJ, FTAG, &bonus_db) == 0);
2428                 abuf = dmu_request_arcbuf(bonus_db, bs);
2429         }
2430
2431         txg_how = ztest_random(2) == 0 ? TXG_WAIT : TXG_NOWAIT;
2432         error = dmu_tx_assign(tx, txg_how);
2433         if (error) {
2434                 if (error == ERESTART) {
2435                         ASSERT(txg_how == TXG_NOWAIT);
2436                         dmu_tx_wait(tx);
2437                 } else {
2438                         ztest_record_enospc("dmu write parallel");
2439                 }
2440                 dmu_tx_abort(tx);
2441                 if (abuf != NULL) {
2442                         dmu_return_arcbuf(abuf);
2443                         dmu_buf_rele(bonus_db, FTAG);
2444                 }
2445                 return;
2446         }
2447         txg = dmu_tx_get_txg(tx);
2448
2449         lp = &ztest_shared->zs_sync_lock[b];
2450         (void) mutex_lock(lp);
2451
2452         wbt->bt_objset = dmu_objset_id(os);
2453         wbt->bt_object = ZTEST_DIROBJ;
2454         wbt->bt_offset = off;
2455         wbt->bt_txg = txg;
2456         wbt->bt_thread = za->za_instance;
2457         wbt->bt_seq = ztest_shared->zs_seq[b]++;        /* protected by lp */
2458
2459         /*
2460          * Occasionally, write an all-zero block to test the behavior
2461          * of blocks that compress into holes.
2462          */
2463         if (off != -1ULL && ztest_random(8) == 0)
2464                 bzero(wbt, btsize);
2465
2466         if (off == -1ULL) {
2467                 dmu_object_info_t *doi = &za->za_doi;
2468                 char *dboff;
2469
2470                 VERIFY(dmu_bonus_hold(os, ZTEST_DIROBJ, FTAG, &db) == 0);
2471                 za->za_dbuf = db;
2472                 dmu_object_info_from_db(db, doi);
2473                 ASSERT3U(doi->doi_bonus_size, <=, db->db_size);
2474                 ASSERT3U(doi->doi_bonus_size, >=, btsize);
2475                 ASSERT3U(doi->doi_bonus_size % btsize, ==, 0);
2476                 dboff = (char *)db->db_data + doi->doi_bonus_size - btsize;
2477                 bcopy(dboff, rbt, btsize);
2478                 if (rbt->bt_objset != 0) {
2479                         ASSERT3U(rbt->bt_objset, ==, wbt->bt_objset);
2480                         ASSERT3U(rbt->bt_object, ==, wbt->bt_object);
2481                         ASSERT3U(rbt->bt_offset, ==, wbt->bt_offset);
2482                         ASSERT3U(rbt->bt_txg, <=, wbt->bt_txg);
2483                 }
2484                 if (ztest_random(10) == 0) {
2485                         int newsize = (ztest_random(db->db_size /
2486                             btsize) + 1) * btsize;
2487
2488                         ASSERT3U(newsize, >=, btsize);
2489                         ASSERT3U(newsize, <=, db->db_size);
2490                         VERIFY3U(dmu_set_bonus(db, newsize, tx), ==, 0);
2491                         dboff = (char *)db->db_data + newsize - btsize;
2492                 }
2493                 dmu_buf_will_dirty(db, tx);
2494                 bcopy(wbt, dboff, btsize);
2495                 dmu_buf_rele(db, FTAG);
2496                 za->za_dbuf = NULL;
2497         } else if (do_free) {
2498                 VERIFY(dmu_free_range(os, ZTEST_DIROBJ, off, bs, tx) == 0);
2499         } else if (abuf == NULL) {
2500                 dmu_write(os, ZTEST_DIROBJ, off, btsize, wbt, tx);
2501         } else {
2502                 bcopy(wbt, abuf->b_data, btsize);
2503                 dmu_assign_arcbuf(bonus_db, off, abuf, tx);
2504                 dmu_buf_rele(bonus_db, FTAG);
2505         }
2506
2507         (void) mutex_unlock(lp);
2508
2509         if (ztest_random(1000) == 0)
2510                 (void) poll(NULL, 0, 1); /* open dn_notxholds window */
2511
2512         dmu_tx_commit(tx);
2513
2514         if (ztest_random(10000) == 0)
2515                 txg_wait_synced(dmu_objset_pool(os), txg);
2516
2517         if (off == -1ULL || do_free)
2518                 return;
2519
2520         if (ztest_random(2) != 0)
2521                 return;
2522
2523         /*
2524          * dmu_sync() the block we just wrote.
2525          */
2526         (void) mutex_lock(lp);
2527
2528         blkoff = P2ALIGN_TYPED(off, bs, uint64_t);
2529         error = dmu_buf_hold(os, ZTEST_DIROBJ, blkoff, FTAG, &db);
2530         za->za_dbuf = db;
2531         if (error) {
2532                 (void) mutex_unlock(lp);
2533                 return;
2534         }
2535         blkoff = off - blkoff;
2536         error = dmu_sync(NULL, db, &blk, txg, NULL, NULL);
2537         dmu_buf_rele(db, FTAG);
2538         za->za_dbuf = NULL;
2539
2540         if (error) {
2541                 (void) mutex_unlock(lp);
2542                 return;
2543         }
2544
2545         if (blk.blk_birth == 0) {       /* concurrent free */
2546                 (void) mutex_unlock(lp);
2547                 return;
2548         }
2549
2550         txg_suspend(dmu_objset_pool(os));
2551
2552         (void) mutex_unlock(lp);
2553
2554         ASSERT(blk.blk_fill == 1);
2555         ASSERT3U(BP_GET_TYPE(&blk), ==, DMU_OT_UINT64_OTHER);
2556         ASSERT3U(BP_GET_LEVEL(&blk), ==, 0);
2557         ASSERT3U(BP_GET_LSIZE(&blk), ==, bs);
2558
2559         /*
2560          * Read the block that dmu_sync() returned to make sure its contents
2561          * match what we wrote.  We do this while still txg_suspend()ed
2562          * to ensure that the block can't be reused before we read it.
2563          */
2564         zb.zb_objset = dmu_objset_id(os);
2565         zb.zb_object = ZTEST_DIROBJ;
2566         zb.zb_level = 0;
2567         zb.zb_blkid = off / bs;
2568         error = zio_wait(zio_read(NULL, za->za_spa, &blk, iobuf, bs,
2569             NULL, NULL, ZIO_PRIORITY_SYNC_READ, ZIO_FLAG_MUSTSUCCEED, &zb));
2570         ASSERT3U(error, ==, 0);
2571
2572         txg_resume(dmu_objset_pool(os));
2573
2574         bcopy(&iobuf[blkoff], rbt, btsize);
2575
2576         if (rbt->bt_objset == 0)                /* concurrent free */
2577                 return;
2578
2579         if (wbt->bt_objset == 0)                /* all-zero overwrite */
2580                 return;
2581
2582         ASSERT3U(rbt->bt_objset, ==, wbt->bt_objset);
2583         ASSERT3U(rbt->bt_object, ==, wbt->bt_object);
2584         ASSERT3U(rbt->bt_offset, ==, wbt->bt_offset);
2585
2586         /*
2587          * The semantic of dmu_sync() is that we always push the most recent
2588          * version of the data, so in the face of concurrent updates we may
2589          * see a newer version of the block.  That's OK.
2590          */
2591         ASSERT3U(rbt->bt_txg, >=, wbt->bt_txg);
2592         if (rbt->bt_thread == wbt->bt_thread)
2593                 ASSERT3U(rbt->bt_seq, ==, wbt->bt_seq);
2594         else
2595                 ASSERT3U(rbt->bt_seq, >, wbt->bt_seq);
2596 }
2597
2598 /*
2599  * Verify that zap_{create,destroy,add,remove,update} work as expected.
2600  */
2601 #define ZTEST_ZAP_MIN_INTS      1
2602 #define ZTEST_ZAP_MAX_INTS      4
2603 #define ZTEST_ZAP_MAX_PROPS     1000
2604
2605 void
2606 ztest_zap(ztest_args_t *za)
2607 {
2608         objset_t *os = za->za_os;
2609         uint64_t object;
2610         uint64_t txg, last_txg;
2611         uint64_t value[ZTEST_ZAP_MAX_INTS];
2612         uint64_t zl_ints, zl_intsize, prop;
2613         int i, ints;
2614         dmu_tx_t *tx;
2615         char propname[100], txgname[100];
2616         int error;
2617         char osname[MAXNAMELEN];
2618         char *hc[2] = { "s.acl.h", ".s.open.h.hyLZlg" };
2619
2620         dmu_objset_name(os, osname);
2621
2622         /*
2623          * Create a new object if necessary, and record it in the directory.
2624          */
2625         VERIFY(0 == dmu_read(os, ZTEST_DIROBJ, za->za_diroff,
2626             sizeof (uint64_t), &object, DMU_READ_PREFETCH));
2627
2628         if (object == 0) {
2629                 tx = dmu_tx_create(os);
2630                 dmu_tx_hold_write(tx, ZTEST_DIROBJ, za->za_diroff,
2631                     sizeof (uint64_t));
2632                 dmu_tx_hold_zap(tx, DMU_NEW_OBJECT, TRUE, NULL);
2633                 error = dmu_tx_assign(tx, TXG_WAIT);
2634                 if (error) {
2635                         ztest_record_enospc("create zap test obj");
2636                         dmu_tx_abort(tx);
2637                         return;
2638                 }
2639                 object = zap_create(os, DMU_OT_ZAP_OTHER, DMU_OT_NONE, 0, tx);
2640                 if (error) {
2641                         fatal(0, "zap_create('%s', %llu) = %d",
2642                             osname, object, error);
2643                 }
2644                 ASSERT(object != 0);
2645                 dmu_write(os, ZTEST_DIROBJ, za->za_diroff,
2646                     sizeof (uint64_t), &object, tx);
2647                 /*
2648                  * Generate a known hash collision, and verify that
2649                  * we can lookup and remove both entries.
2650                  */
2651                 for (i = 0; i < 2; i++) {
2652                         value[i] = i;
2653                         error = zap_add(os, object, hc[i], sizeof (uint64_t),
2654                             1, &value[i], tx);
2655                         ASSERT3U(error, ==, 0);
2656                 }
2657                 for (i = 0; i < 2; i++) {
2658                         error = zap_add(os, object, hc[i], sizeof (uint64_t),
2659                             1, &value[i], tx);
2660                         ASSERT3U(error, ==, EEXIST);
2661                         error = zap_length(os, object, hc[i],
2662                             &zl_intsize, &zl_ints);
2663                         ASSERT3U(error, ==, 0);
2664                         ASSERT3U(zl_intsize, ==, sizeof (uint64_t));
2665                         ASSERT3U(zl_ints, ==, 1);
2666                 }
2667                 for (i = 0; i < 2; i++) {
2668                         error = zap_remove(os, object, hc[i], tx);
2669                         ASSERT3U(error, ==, 0);
2670                 }
2671
2672                 dmu_tx_commit(tx);
2673         }
2674
2675         ints = MAX(ZTEST_ZAP_MIN_INTS, object % ZTEST_ZAP_MAX_INTS);
2676
2677         prop = ztest_random(ZTEST_ZAP_MAX_PROPS);
2678         (void) sprintf(propname, "prop_%llu", (u_longlong_t)prop);
2679         (void) sprintf(txgname, "txg_%llu", (u_longlong_t)prop);
2680         bzero(value, sizeof (value));
2681         last_txg = 0;
2682
2683         /*
2684          * If these zap entries already exist, validate their contents.
2685          */
2686         error = zap_length(os, object, txgname, &zl_intsize, &zl_ints);
2687         if (error == 0) {
2688                 ASSERT3U(zl_intsize, ==, sizeof (uint64_t));
2689                 ASSERT3U(zl_ints, ==, 1);
2690
2691                 VERIFY(zap_lookup(os, object, txgname, zl_intsize,
2692                     zl_ints, &last_txg) == 0);
2693
2694                 VERIFY(zap_length(os, object, propname, &zl_intsize,
2695                     &zl_ints) == 0);
2696
2697                 ASSERT3U(zl_intsize, ==, sizeof (uint64_t));
2698                 ASSERT3U(zl_ints, ==, ints);
2699
2700                 VERIFY(zap_lookup(os, object, propname, zl_intsize,
2701                     zl_ints, value) == 0);
2702
2703                 for (i = 0; i < ints; i++) {
2704                         ASSERT3U(value[i], ==, last_txg + object + i);
2705                 }
2706         } else {
2707                 ASSERT3U(error, ==, ENOENT);
2708         }
2709
2710         /*
2711          * Atomically update two entries in our zap object.
2712          * The first is named txg_%llu, and contains the txg
2713          * in which the property was last updated.  The second
2714          * is named prop_%llu, and the nth element of its value
2715          * should be txg + object + n.
2716          */
2717         tx = dmu_tx_create(os);
2718         dmu_tx_hold_zap(tx, object, TRUE, NULL);
2719         error = dmu_tx_assign(tx, TXG_WAIT);
2720         if (error) {
2721                 ztest_record_enospc("create zap entry");
2722                 dmu_tx_abort(tx);
2723                 return;
2724         }
2725         txg = dmu_tx_get_txg(tx);
2726
2727         if (last_txg > txg)
2728                 fatal(0, "zap future leak: old %llu new %llu", last_txg, txg);
2729
2730         for (i = 0; i < ints; i++)
2731                 value[i] = txg + object + i;
2732
2733         error = zap_update(os, object, txgname, sizeof (uint64_t), 1, &txg, tx);
2734         if (error)
2735                 fatal(0, "zap_update('%s', %llu, '%s') = %d",
2736                     osname, object, txgname, error);
2737
2738         error = zap_update(os, object, propname, sizeof (uint64_t),
2739             ints, value, tx);
2740         if (error)
2741                 fatal(0, "zap_update('%s', %llu, '%s') = %d",
2742                     osname, object, propname, error);
2743
2744         dmu_tx_commit(tx);
2745
2746         /*
2747          * Remove a random pair of entries.
2748          */
2749         prop = ztest_random(ZTEST_ZAP_MAX_PROPS);
2750         (void) sprintf(propname, "prop_%llu", (u_longlong_t)prop);
2751         (void) sprintf(txgname, "txg_%llu", (u_longlong_t)prop);
2752
2753         error = zap_length(os, object, txgname, &zl_intsize, &zl_ints);
2754
2755         if (error == ENOENT)
2756                 return;
2757
2758         ASSERT3U(error, ==, 0);
2759
2760         tx = dmu_tx_create(os);
2761         dmu_tx_hold_zap(tx, object, TRUE, NULL);
2762         error = dmu_tx_assign(tx, TXG_WAIT);
2763         if (error) {
2764                 ztest_record_enospc("remove zap entry");
2765                 dmu_tx_abort(tx);
2766                 return;
2767         }
2768         error = zap_remove(os, object, txgname, tx);
2769         if (error)
2770                 fatal(0, "zap_remove('%s', %llu, '%s') = %d",
2771                     osname, object, txgname, error);
2772
2773         error = zap_remove(os, object, propname, tx);
2774         if (error)
2775                 fatal(0, "zap_remove('%s', %llu, '%s') = %d",
2776                     osname, object, propname, error);
2777
2778         dmu_tx_commit(tx);
2779
2780         /*
2781          * Once in a while, destroy the object.
2782          */
2783         if (ztest_random(1000) != 0)
2784                 return;
2785
2786         tx = dmu_tx_create(os);
2787         dmu_tx_hold_write(tx, ZTEST_DIROBJ, za->za_diroff, sizeof (uint64_t));
2788         dmu_tx_hold_free(tx, object, 0, DMU_OBJECT_END);
2789         error = dmu_tx_assign(tx, TXG_WAIT);
2790         if (error) {
2791                 ztest_record_enospc("destroy zap object");
2792                 dmu_tx_abort(tx);
2793                 return;
2794         }
2795         error = zap_destroy(os, object, tx);
2796         if (error)
2797                 fatal(0, "zap_destroy('%s', %llu) = %d",
2798                     osname, object, error);
2799         object = 0;
2800         dmu_write(os, ZTEST_DIROBJ, za->za_diroff, sizeof (uint64_t),
2801             &object, tx);
2802         dmu_tx_commit(tx);
2803 }
2804
2805 /*
2806  * Testcase to test the upgrading of a microzap to fatzap.
2807  */
2808 void
2809 ztest_fzap(ztest_args_t *za)
2810 {
2811         objset_t *os = za->za_os;
2812         uint64_t object;
2813         uint64_t value;
2814         dmu_tx_t *tx;
2815         int i, error;
2816         char osname[MAXNAMELEN];
2817         char *name = "aaa";
2818         char entname[MAXNAMELEN];
2819
2820         dmu_objset_name(os, osname);
2821
2822         /*
2823          * Create a new object if necessary, and record it in the directory.
2824          */
2825         VERIFY(0 == dmu_read(os, ZTEST_DIROBJ, za->za_diroff,
2826             sizeof (uint64_t), &object, DMU_READ_PREFETCH));
2827
2828         if (object == 0) {
2829                 tx = dmu_tx_create(os);
2830                 dmu_tx_hold_write(tx, ZTEST_DIROBJ, za->za_diroff,
2831                     sizeof (uint64_t));
2832                 dmu_tx_hold_zap(tx, DMU_NEW_OBJECT, TRUE, NULL);
2833                 error = dmu_tx_assign(tx, TXG_WAIT);
2834                 if (error) {
2835                         ztest_record_enospc("create zap test obj");
2836                         dmu_tx_abort(tx);
2837                         return;
2838                 }
2839                 object = zap_create(os, DMU_OT_ZAP_OTHER, DMU_OT_NONE, 0, tx);
2840                 if (error) {
2841                         fatal(0, "zap_create('%s', %llu) = %d",
2842                             osname, object, error);
2843                 }
2844                 ASSERT(object != 0);
2845                 dmu_write(os, ZTEST_DIROBJ, za->za_diroff,
2846                     sizeof (uint64_t), &object, tx);
2847                 dmu_tx_commit(tx);
2848         }
2849
2850         /*
2851          * Add entries to this ZAP amd make sure it spills over
2852          * and gets upgraded to a fatzap. Also, since we are adding
2853          * 2050 entries we should see ptrtbl growth and leaf-block
2854          * split.
2855          */
2856         for (i = 0; i < 2050; i++) {
2857                 (void) snprintf(entname, sizeof (entname), "%s-%d", name, i);
2858                 value = i;
2859
2860                 tx = dmu_tx_create(os);
2861                 dmu_tx_hold_zap(tx, object, TRUE, entname);
2862                 error = dmu_tx_assign(tx, TXG_WAIT);
2863
2864                 if (error) {
2865                         ztest_record_enospc("create zap entry");
2866                         dmu_tx_abort(tx);
2867                         return;
2868                 }
2869                 error = zap_add(os, object, entname, sizeof (uint64_t),
2870                     1, &value, tx);
2871
2872                 ASSERT(error == 0 || error == EEXIST);
2873                 dmu_tx_commit(tx);
2874         }
2875
2876         /*
2877          * Once in a while, destroy the object.
2878          */
2879         if (ztest_random(1000) != 0)
2880                 return;
2881
2882         tx = dmu_tx_create(os);
2883         dmu_tx_hold_write(tx, ZTEST_DIROBJ, za->za_diroff, sizeof (uint64_t));
2884         dmu_tx_hold_free(tx, object, 0, DMU_OBJECT_END);
2885         error = dmu_tx_assign(tx, TXG_WAIT);
2886         if (error) {
2887                 ztest_record_enospc("destroy zap object");
2888                 dmu_tx_abort(tx);
2889                 return;
2890         }
2891         error = zap_destroy(os, object, tx);
2892         if (error)
2893                 fatal(0, "zap_destroy('%s', %llu) = %d",
2894                     osname, object, error);
2895         object = 0;
2896         dmu_write(os, ZTEST_DIROBJ, za->za_diroff, sizeof (uint64_t),
2897             &object, tx);
2898         dmu_tx_commit(tx);
2899 }
2900
2901 void
2902 ztest_zap_parallel(ztest_args_t *za)
2903 {
2904         objset_t *os = za->za_os;
2905         uint64_t txg, object, count, wsize, wc, zl_wsize, zl_wc;
2906         dmu_tx_t *tx;
2907         int i, namelen, error;
2908         char name[20], string_value[20];
2909         void *data;
2910
2911         /*
2912          * Generate a random name of the form 'xxx.....' where each
2913          * x is a random printable character and the dots are dots.
2914          * There are 94 such characters, and the name length goes from
2915          * 6 to 20, so there are 94^3 * 15 = 12,458,760 possible names.
2916          */
2917         namelen = ztest_random(sizeof (name) - 5) + 5 + 1;
2918
2919         for (i = 0; i < 3; i++)
2920                 name[i] = '!' + ztest_random('~' - '!' + 1);
2921         for (; i < namelen - 1; i++)
2922                 name[i] = '.';
2923         name[i] = '\0';
2924
2925         if (ztest_random(2) == 0)
2926                 object = ZTEST_MICROZAP_OBJ;
2927         else
2928                 object = ZTEST_FATZAP_OBJ;
2929
2930         if ((namelen & 1) || object == ZTEST_MICROZAP_OBJ) {
2931                 wsize = sizeof (txg);
2932                 wc = 1;
2933                 data = &txg;
2934         } else {
2935                 wsize = 1;
2936                 wc = namelen;
2937                 data = string_value;
2938         }
2939
2940         count = -1ULL;
2941         VERIFY(zap_count(os, object, &count) == 0);
2942         ASSERT(count != -1ULL);
2943
2944         /*
2945          * Select an operation: length, lookup, add, update, remove.
2946          */
2947         i = ztest_random(5);
2948
2949         if (i >= 2) {
2950                 tx = dmu_tx_create(os);
2951                 dmu_tx_hold_zap(tx, object, TRUE, NULL);
2952                 error = dmu_tx_assign(tx, TXG_WAIT);
2953                 if (error) {
2954                         ztest_record_enospc("zap parallel");
2955                         dmu_tx_abort(tx);
2956                         return;
2957                 }
2958                 txg = dmu_tx_get_txg(tx);
2959                 bcopy(name, string_value, namelen);
2960         } else {
2961                 tx = NULL;
2962                 txg = 0;
2963                 bzero(string_value, namelen);
2964         }
2965
2966         switch (i) {
2967
2968         case 0:
2969                 error = zap_length(os, object, name, &zl_wsize, &zl_wc);
2970                 if (error == 0) {
2971                         ASSERT3U(wsize, ==, zl_wsize);
2972                         ASSERT3U(wc, ==, zl_wc);
2973                 } else {
2974                         ASSERT3U(error, ==, ENOENT);
2975                 }
2976                 break;
2977
2978         case 1:
2979                 error = zap_lookup(os, object, name, wsize, wc, data);
2980                 if (error == 0) {
2981                         if (data == string_value &&
2982                             bcmp(name, data, namelen) != 0)
2983                                 fatal(0, "name '%s' != val '%s' len %d",
2984                                     name, data, namelen);
2985                 } else {
2986                         ASSERT3U(error, ==, ENOENT);
2987                 }
2988                 break;
2989
2990         case 2:
2991                 error = zap_add(os, object, name, wsize, wc, data, tx);
2992                 ASSERT(error == 0 || error == EEXIST);
2993                 break;
2994
2995         case 3:
2996                 VERIFY(zap_update(os, object, name, wsize, wc, data, tx) == 0);
2997                 break;
2998
2999         case 4:
3000                 error = zap_remove(os, object, name, tx);
3001                 ASSERT(error == 0 || error == ENOENT);
3002                 break;
3003         }
3004
3005         if (tx != NULL)
3006                 dmu_tx_commit(tx);
3007 }
3008
3009 void
3010 ztest_dsl_prop_get_set(ztest_args_t *za)
3011 {
3012         objset_t *os = za->za_os;
3013         int i, inherit;
3014         uint64_t value;
3015         const char *prop, *valname;
3016         char setpoint[MAXPATHLEN];
3017         char osname[MAXNAMELEN];
3018         int error;
3019
3020         (void) rw_rdlock(&ztest_shared->zs_name_lock);
3021
3022         dmu_objset_name(os, osname);
3023
3024         for (i = 0; i < 2; i++) {
3025                 if (i == 0) {
3026                         prop = "checksum";
3027                         value = ztest_random_checksum();
3028                         inherit = (value == ZIO_CHECKSUM_INHERIT);
3029                 } else {
3030                         prop = "compression";
3031                         value = ztest_random_compress();
3032                         inherit = (value == ZIO_COMPRESS_INHERIT);
3033                 }
3034
3035                 error = dsl_prop_set(osname, prop, sizeof (value),
3036                     !inherit, &value);
3037
3038                 if (error == ENOSPC) {
3039                         ztest_record_enospc("dsl_prop_set");
3040                         break;
3041                 }
3042
3043                 ASSERT3U(error, ==, 0);
3044
3045                 VERIFY3U(dsl_prop_get(osname, prop, sizeof (value),
3046                     1, &value, setpoint), ==, 0);
3047
3048                 if (i == 0)
3049                         valname = zio_checksum_table[value].ci_name;
3050                 else
3051                         valname = zio_compress_table[value].ci_name;
3052
3053                 if (zopt_verbose >= 6) {
3054                         (void) printf("%s %s = %s for '%s'\n",
3055                             osname, prop, valname, setpoint);
3056                 }
3057         }
3058
3059         (void) rw_unlock(&ztest_shared->zs_name_lock);
3060 }
3061
3062 /*
3063  * Inject random faults into the on-disk data.
3064  */
3065 void
3066 ztest_fault_inject(ztest_args_t *za)
3067 {
3068         int fd;
3069         uint64_t offset;
3070         uint64_t leaves = MAX(zopt_mirrors, 1) * zopt_raidz;
3071         uint64_t bad = 0x1990c0ffeedecadeULL;
3072         uint64_t top, leaf;
3073         char path0[MAXPATHLEN];
3074         char pathrand[MAXPATHLEN];
3075         size_t fsize;
3076         spa_t *spa = za->za_spa;
3077         int bshift = SPA_MAXBLOCKSHIFT + 2;     /* don't scrog all labels */
3078         int iters = 1000;
3079         int maxfaults = zopt_maxfaults;
3080         vdev_t *vd0 = NULL;
3081         uint64_t guid0 = 0;
3082
3083         ASSERT(leaves >= 1);
3084
3085         /*
3086          * We need SCL_STATE here because we're going to look at vd0->vdev_tsd.
3087          */
3088         spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
3089
3090         if (ztest_random(2) == 0) {
3091                 /*
3092                  * Inject errors on a normal data device.
3093                  */
3094                 top = ztest_random(spa->spa_root_vdev->vdev_children);
3095                 leaf = ztest_random(leaves);
3096
3097                 /*
3098                  * Generate paths to the first leaf in this top-level vdev,
3099                  * and to the random leaf we selected.  We'll induce transient
3100                  * write failures and random online/offline activity on leaf 0,
3101                  * and we'll write random garbage to the randomly chosen leaf.
3102                  */
3103                 (void) snprintf(path0, sizeof (path0), ztest_dev_template,
3104                     zopt_dir, zopt_pool, top * leaves + 0);
3105                 (void) snprintf(pathrand, sizeof (pathrand), ztest_dev_template,
3106                     zopt_dir, zopt_pool, top * leaves + leaf);
3107
3108                 vd0 = vdev_lookup_by_path(spa->spa_root_vdev, path0);
3109                 if (vd0 != NULL && maxfaults != 1) {
3110                         /*
3111                          * Make vd0 explicitly claim to be unreadable,
3112                          * or unwriteable, or reach behind its back
3113                          * and close the underlying fd.  We can do this if
3114                          * maxfaults == 0 because we'll fail and reexecute,
3115                          * and we can do it if maxfaults >= 2 because we'll
3116                          * have enough redundancy.  If maxfaults == 1, the
3117                          * combination of this with injection of random data
3118                          * corruption below exceeds the pool's fault tolerance.
3119                          */
3120                         vdev_file_t *vf = vd0->vdev_tsd;
3121
3122                         if (vf != NULL && ztest_random(3) == 0) {
3123                                 (void) close(vf->vf_vnode->v_fd);
3124                                 vf->vf_vnode->v_fd = -1;
3125                         } else if (ztest_random(2) == 0) {
3126                                 vd0->vdev_cant_read = B_TRUE;
3127                         } else {
3128                                 vd0->vdev_cant_write = B_TRUE;
3129                         }
3130                         guid0 = vd0->vdev_guid;
3131                 }
3132         } else {
3133                 /*
3134                  * Inject errors on an l2cache device.
3135                  */
3136                 spa_aux_vdev_t *sav = &spa->spa_l2cache;
3137
3138                 if (sav->sav_count == 0) {
3139                         spa_config_exit(spa, SCL_STATE, FTAG);
3140                         return;
3141                 }
3142                 vd0 = sav->sav_vdevs[ztest_random(sav->sav_count)];
3143                 guid0 = vd0->vdev_guid;
3144                 (void) strcpy(path0, vd0->vdev_path);
3145                 (void) strcpy(pathrand, vd0->vdev_path);
3146
3147                 leaf = 0;
3148                 leaves = 1;
3149                 maxfaults = INT_MAX;    /* no limit on cache devices */
3150         }
3151
3152         spa_config_exit(spa, SCL_STATE, FTAG);
3153
3154         if (maxfaults == 0)
3155                 return;
3156
3157         /*
3158          * If we can tolerate two or more faults, randomly online/offline vd0.
3159          */
3160         if (maxfaults >= 2 && guid0 != 0) {
3161                 if (ztest_random(10) < 6) {
3162                         int flags = (ztest_random(2) == 0 ?
3163                             ZFS_OFFLINE_TEMPORARY : 0);
3164                         VERIFY(vdev_offline(spa, guid0, flags) != EBUSY);
3165                 } else {
3166                         (void) vdev_online(spa, guid0, 0, NULL);
3167                 }
3168         }
3169
3170         /*
3171          * We have at least single-fault tolerance, so inject data corruption.
3172          */
3173         fd = open(pathrand, O_RDWR);
3174
3175         if (fd == -1)   /* we hit a gap in the device namespace */
3176                 return;
3177
3178         fsize = lseek(fd, 0, SEEK_END);
3179
3180         while (--iters != 0) {
3181                 offset = ztest_random(fsize / (leaves << bshift)) *
3182                     (leaves << bshift) + (leaf << bshift) +
3183                     (ztest_random(1ULL << (bshift - 1)) & -8ULL);
3184
3185                 if (offset >= fsize)
3186                         continue;
3187
3188                 if (zopt_verbose >= 6)
3189                         (void) printf("injecting bad word into %s,"
3190                             " offset 0x%llx\n", pathrand, (u_longlong_t)offset);
3191
3192                 if (pwrite(fd, &bad, sizeof (bad), offset) != sizeof (bad))
3193                         fatal(1, "can't inject bad word at 0x%llx in %s",
3194                             offset, pathrand);
3195         }
3196
3197         (void) close(fd);
3198 }
3199
3200 /*
3201  * Scrub the pool.
3202  */
3203 void
3204 ztest_scrub(ztest_args_t *za)
3205 {
3206         spa_t *spa = za->za_spa;
3207
3208         (void) spa_scrub(spa, POOL_SCRUB_EVERYTHING);
3209         (void) poll(NULL, 0, 1000); /* wait a second, then force a restart */
3210         (void) spa_scrub(spa, POOL_SCRUB_EVERYTHING);
3211 }
3212
3213 /*
3214  * Rename the pool to a different name and then rename it back.
3215  */
3216 void
3217 ztest_spa_rename(ztest_args_t *za)
3218 {
3219         char *oldname, *newname;
3220         int error;
3221         spa_t *spa;
3222
3223         (void) rw_wrlock(&ztest_shared->zs_name_lock);
3224
3225         oldname = za->za_pool;
3226         newname = umem_alloc(strlen(oldname) + 5, UMEM_NOFAIL);
3227         (void) strcpy(newname, oldname);
3228         (void) strcat(newname, "_tmp");
3229
3230         /*
3231          * Do the rename
3232          */
3233         error = spa_rename(oldname, newname);
3234         if (error)
3235                 fatal(0, "spa_rename('%s', '%s') = %d", oldname,
3236                     newname, error);
3237
3238         /*
3239          * Try to open it under the old name, which shouldn't exist
3240          */
3241         error = spa_open(oldname, &spa, FTAG);
3242         if (error != ENOENT)
3243                 fatal(0, "spa_open('%s') = %d", oldname, error);
3244
3245         /*
3246          * Open it under the new name and make sure it's still the same spa_t.
3247          */
3248         error = spa_open(newname, &spa, FTAG);
3249         if (error != 0)
3250                 fatal(0, "spa_open('%s') = %d", newname, error);
3251
3252         ASSERT(spa == za->za_spa);
3253         spa_close(spa, FTAG);
3254
3255         /*
3256          * Rename it back to the original
3257          */
3258         error = spa_rename(newname, oldname);
3259         if (error)
3260                 fatal(0, "spa_rename('%s', '%s') = %d", newname,
3261                     oldname, error);
3262
3263         /*
3264          * Make sure it can still be opened
3265          */
3266         error = spa_open(oldname, &spa, FTAG);
3267         if (error != 0)
3268                 fatal(0, "spa_open('%s') = %d", oldname, error);
3269
3270         ASSERT(spa == za->za_spa);
3271         spa_close(spa, FTAG);
3272
3273         umem_free(newname, strlen(newname) + 1);
3274
3275         (void) rw_unlock(&ztest_shared->zs_name_lock);
3276 }
3277
3278
3279 /*
3280  * Completely obliterate one disk.
3281  */
3282 static void
3283 ztest_obliterate_one_disk(uint64_t vdev)
3284 {
3285         int fd;
3286         char dev_name[MAXPATHLEN], copy_name[MAXPATHLEN];
3287         size_t fsize;
3288
3289         if (zopt_maxfaults < 2)
3290                 return;
3291
3292         (void) sprintf(dev_name, ztest_dev_template, zopt_dir, zopt_pool, vdev);
3293         (void) snprintf(copy_name, MAXPATHLEN, "%s.old", dev_name);
3294
3295         fd = open(dev_name, O_RDWR);
3296
3297         if (fd == -1)
3298                 fatal(1, "can't open %s", dev_name);
3299
3300         /*
3301          * Determine the size.
3302          */
3303         fsize = lseek(fd, 0, SEEK_END);
3304
3305         (void) close(fd);
3306
3307         /*
3308          * Rename the old device to dev_name.old (useful for debugging).
3309          */
3310         VERIFY(rename(dev_name, copy_name) == 0);
3311
3312         /*
3313          * Create a new one.
3314          */
3315         VERIFY((fd = open(dev_name, O_RDWR | O_CREAT | O_TRUNC, 0666)) >= 0);
3316         VERIFY(ftruncate(fd, fsize) == 0);
3317         (void) close(fd);
3318 }
3319
3320 static void
3321 ztest_replace_one_disk(spa_t *spa, uint64_t vdev)
3322 {
3323         char dev_name[MAXPATHLEN];
3324         nvlist_t *root;
3325         int error;
3326         uint64_t guid;
3327         vdev_t *vd;
3328
3329         (void) sprintf(dev_name, ztest_dev_template, zopt_dir, zopt_pool, vdev);
3330
3331         /*
3332          * Build the nvlist describing dev_name.
3333          */
3334         root = make_vdev_root(dev_name, NULL, 0, 0, 0, 0, 0, 1);
3335
3336         spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
3337         if ((vd = vdev_lookup_by_path(spa->spa_root_vdev, dev_name)) == NULL)
3338                 guid = 0;
3339         else
3340                 guid = vd->vdev_guid;
3341         spa_config_exit(spa, SCL_VDEV, FTAG);
3342         error = spa_vdev_attach(spa, guid, root, B_TRUE);
3343         if (error != 0 &&
3344             error != EBUSY &&
3345             error != ENOTSUP &&
3346             error != ENODEV &&
3347             error != EDOM)
3348                 fatal(0, "spa_vdev_attach(in-place) = %d", error);
3349
3350         nvlist_free(root);
3351 }
3352
3353 static void
3354 ztest_verify_blocks(char *pool)
3355 {
3356         int status;
3357         char zdb[MAXPATHLEN + MAXNAMELEN + 20];
3358         char zbuf[1024];
3359         char *bin;
3360         char *ztest;
3361         char *isa;
3362         int isalen;
3363         FILE *fp;
3364
3365         if (realpath(progname, zdb) == NULL)
3366                 assert(!"realpath() failed");
3367
3368         /* zdb lives in /usr/sbin, while ztest lives in /usr/bin */
3369         bin = strstr(zdb, "/usr/bin/");
3370         ztest = strstr(bin, "/ztest");
3371         isa = bin + 8;
3372         isalen = ztest - isa;
3373         isa = strdup(isa);
3374         /* LINTED */
3375         (void) sprintf(bin,
3376             "/usr/sbin%.*s/zdb -bcc%s%s -U /tmp/zpool.cache %s",
3377             isalen,
3378             isa,
3379             zopt_verbose >= 3 ? "s" : "",
3380             zopt_verbose >= 4 ? "v" : "",
3381             pool);
3382         free(isa);
3383
3384         if (zopt_verbose >= 5)
3385                 (void) printf("Executing %s\n", strstr(zdb, "zdb "));
3386
3387         fp = popen(zdb, "r");
3388         assert(fp != NULL);
3389
3390         while (fgets(zbuf, sizeof (zbuf), fp) != NULL)
3391                 if (zopt_verbose >= 3)
3392                         (void) printf("%s", zbuf);
3393
3394         status = pclose(fp);
3395
3396         if (status == 0)
3397                 return;
3398
3399         ztest_dump_core = 0;
3400         if (WIFEXITED(status))
3401                 fatal(0, "'%s' exit code %d", zdb, WEXITSTATUS(status));
3402         else
3403                 fatal(0, "'%s' died with signal %d", zdb, WTERMSIG(status));
3404 }
3405
3406 static void
3407 ztest_walk_pool_directory(char *header)
3408 {
3409         spa_t *spa = NULL;
3410
3411         if (zopt_verbose >= 6)
3412                 (void) printf("%s\n", header);
3413
3414         mutex_enter(&spa_namespace_lock);
3415         while ((spa = spa_next(spa)) != NULL)
3416                 if (zopt_verbose >= 6)
3417                         (void) printf("\t%s\n", spa_name(spa));
3418         mutex_exit(&spa_namespace_lock);
3419 }
3420
3421 static void
3422 ztest_spa_import_export(char *oldname, char *newname)
3423 {
3424         nvlist_t *config, *newconfig;
3425         uint64_t pool_guid;
3426         spa_t *spa;
3427         int error;
3428
3429         if (zopt_verbose >= 4) {
3430                 (void) printf("import/export: old = %s, new = %s\n",
3431                     oldname, newname);
3432         }
3433
3434         /*
3435          * Clean up from previous runs.
3436          */
3437         (void) spa_destroy(newname);
3438
3439         /*
3440          * Get the pool's configuration and guid.
3441          */
3442         error = spa_open(oldname, &spa, FTAG);
3443         if (error)
3444                 fatal(0, "spa_open('%s') = %d", oldname, error);
3445
3446         /*
3447          * Kick off a scrub to tickle scrub/export races.
3448          */
3449         if (ztest_random(2) == 0)
3450                 (void) spa_scrub(spa, POOL_SCRUB_EVERYTHING);
3451
3452         pool_guid = spa_guid(spa);
3453         spa_close(spa, FTAG);
3454
3455         ztest_walk_pool_directory("pools before export");
3456
3457         /*
3458          * Export it.
3459          */
3460         error = spa_export(oldname, &config, B_FALSE, B_FALSE);
3461         if (error)
3462                 fatal(0, "spa_export('%s') = %d", oldname, error);
3463
3464         ztest_walk_pool_directory("pools after export");
3465
3466         /*
3467          * Try to import it.
3468          */
3469         newconfig = spa_tryimport(config);
3470         ASSERT(newconfig != NULL);
3471         nvlist_free(newconfig);
3472
3473         /*
3474          * Import it under the new name.
3475          */
3476         error = spa_import(newname, config, NULL);
3477         if (error)
3478                 fatal(0, "spa_import('%s') = %d", newname, error);
3479
3480         ztest_walk_pool_directory("pools after import");
3481
3482         /*
3483          * Try to import it again -- should fail with EEXIST.
3484          */
3485         error = spa_import(newname, config, NULL);
3486         if (error != EEXIST)
3487                 fatal(0, "spa_import('%s') twice", newname);
3488
3489         /*
3490          * Try to import it under a different name -- should fail with EEXIST.
3491          */
3492         error = spa_import(oldname, config, NULL);
3493         if (error != EEXIST)
3494                 fatal(0, "spa_import('%s') under multiple names", newname);
3495
3496         /*
3497          * Verify that the pool is no longer visible under the old name.
3498          */
3499         error = spa_open(oldname, &spa, FTAG);
3500         if (error != ENOENT)
3501                 fatal(0, "spa_open('%s') = %d", newname, error);
3502
3503         /*
3504          * Verify that we can open and close the pool using the new name.
3505          */
3506         error = spa_open(newname, &spa, FTAG);
3507         if (error)
3508                 fatal(0, "spa_open('%s') = %d", newname, error);
3509         ASSERT(pool_guid == spa_guid(spa));
3510         spa_close(spa, FTAG);
3511
3512         nvlist_free(config);
3513 }
3514
3515 static void
3516 ztest_resume(spa_t *spa)
3517 {
3518         if (spa_suspended(spa)) {
3519                 spa_vdev_state_enter(spa);
3520                 vdev_clear(spa, NULL);
3521                 (void) spa_vdev_state_exit(spa, NULL, 0);
3522                 (void) zio_resume(spa);
3523         }
3524 }
3525
3526 static void *
3527 ztest_resume_thread(void *arg)
3528 {
3529         spa_t *spa = arg;
3530
3531         while (!ztest_exiting) {
3532                 (void) poll(NULL, 0, 1000);
3533                 ztest_resume(spa);
3534         }
3535         return (NULL);
3536 }
3537
3538 static void *
3539 ztest_thread(void *arg)
3540 {
3541         ztest_args_t *za = arg;
3542         ztest_shared_t *zs = ztest_shared;
3543         hrtime_t now, functime;
3544         ztest_info_t *zi;
3545         int f, i;
3546
3547         while ((now = gethrtime()) < za->za_stop) {
3548                 /*
3549                  * See if it's time to force a crash.
3550                  */
3551                 if (now > za->za_kill) {
3552                         zs->zs_alloc = spa_get_alloc(za->za_spa);
3553                         zs->zs_space = spa_get_space(za->za_spa);
3554                         (void) kill(getpid(), SIGKILL);
3555                 }
3556
3557                 /*
3558                  * Pick a random function.
3559                  */
3560                 f = ztest_random(ZTEST_FUNCS);
3561                 zi = &zs->zs_info[f];
3562
3563                 /*
3564                  * Decide whether to call it, based on the requested frequency.
3565                  */
3566                 if (zi->zi_call_target == 0 ||
3567                     (double)zi->zi_call_total / zi->zi_call_target >
3568                     (double)(now - zs->zs_start_time) / (zopt_time * NANOSEC))
3569                         continue;
3570
3571                 atomic_add_64(&zi->zi_calls, 1);
3572                 atomic_add_64(&zi->zi_call_total, 1);
3573
3574                 za->za_diroff = (za->za_instance * ZTEST_FUNCS + f) *
3575                     ZTEST_DIRSIZE;
3576                 za->za_diroff_shared = (1ULL << 63);
3577
3578                 for (i = 0; i < zi->zi_iters; i++)
3579                         zi->zi_func(za);
3580
3581                 functime = gethrtime() - now;
3582
3583                 atomic_add_64(&zi->zi_call_time, functime);
3584
3585                 if (zopt_verbose >= 4) {
3586                         Dl_info dli;
3587                         (void) dladdr((void *)zi->zi_func, &dli);
3588                         (void) printf("%6.2f sec in %s\n",
3589                             (double)functime / NANOSEC, dli.dli_sname);
3590                 }
3591
3592                 /*
3593                  * If we're getting ENOSPC with some regularity, stop.
3594                  */
3595                 if (zs->zs_enospc_count > 10)
3596                         break;
3597         }
3598
3599         return (NULL);
3600 }
3601
3602 /*
3603  * Kick off threads to run tests on all datasets in parallel.
3604  */
3605 static void
3606 ztest_run(char *pool)
3607 {
3608         int t, d, error;
3609         ztest_shared_t *zs = ztest_shared;
3610         ztest_args_t *za;
3611         spa_t *spa;
3612         char name[100];
3613         thread_t resume_tid;
3614
3615         ztest_exiting = B_FALSE;
3616
3617         (void) _mutex_init(&zs->zs_vdev_lock, USYNC_THREAD, NULL);
3618         (void) rwlock_init(&zs->zs_name_lock, USYNC_THREAD, NULL);
3619
3620         for (t = 0; t < ZTEST_SYNC_LOCKS; t++)
3621                 (void) _mutex_init(&zs->zs_sync_lock[t], USYNC_THREAD, NULL);
3622
3623         /*
3624          * Destroy one disk before we even start.
3625          * It's mirrored, so everything should work just fine.
3626          * This makes us exercise fault handling very early in spa_load().
3627          */
3628         ztest_obliterate_one_disk(0);
3629
3630         /*
3631          * Verify that the sum of the sizes of all blocks in the pool
3632          * equals the SPA's allocated space total.
3633          */
3634         ztest_verify_blocks(pool);
3635
3636         /*
3637          * Kick off a replacement of the disk we just obliterated.
3638          */
3639         kernel_init(FREAD | FWRITE);
3640         VERIFY(spa_open(pool, &spa, FTAG) == 0);
3641         ztest_replace_one_disk(spa, 0);
3642         if (zopt_verbose >= 5)
3643                 show_pool_stats(spa);
3644         spa_close(spa, FTAG);
3645         kernel_fini();
3646
3647         kernel_init(FREAD | FWRITE);
3648
3649         /*
3650          * Verify that we can export the pool and reimport it under a
3651          * different name.
3652          */
3653         if (ztest_random(2) == 0) {
3654                 (void) snprintf(name, 100, "%s_import", pool);
3655                 ztest_spa_import_export(pool, name);
3656                 ztest_spa_import_export(name, pool);
3657         }
3658
3659         /*
3660          * Verify that we can loop over all pools.
3661          */
3662         mutex_enter(&spa_namespace_lock);
3663         for (spa = spa_next(NULL); spa != NULL; spa = spa_next(spa)) {
3664                 if (zopt_verbose > 3) {
3665                         (void) printf("spa_next: found %s\n", spa_name(spa));
3666                 }
3667         }
3668         mutex_exit(&spa_namespace_lock);
3669
3670         /*
3671          * Open our pool.
3672          */
3673         VERIFY(spa_open(pool, &spa, FTAG) == 0);
3674
3675         /*
3676          * We don't expect the pool to suspend unless maxfaults == 0,
3677          * in which case ztest_fault_inject() temporarily takes away
3678          * the only valid replica.
3679          */
3680         if (zopt_maxfaults == 0)
3681                 spa->spa_failmode = ZIO_FAILURE_MODE_WAIT;
3682         else
3683                 spa->spa_failmode = ZIO_FAILURE_MODE_PANIC;
3684
3685         /*
3686          * Create a thread to periodically resume suspended I/O.
3687          */
3688         VERIFY(thr_create(0, 0, ztest_resume_thread, spa, THR_BOUND,
3689             &resume_tid) == 0);
3690
3691         /*
3692          * Verify that we can safely inquire about about any object,
3693          * whether it's allocated or not.  To make it interesting,
3694          * we probe a 5-wide window around each power of two.
3695          * This hits all edge cases, including zero and the max.
3696          */
3697         for (t = 0; t < 64; t++) {
3698                 for (d = -5; d <= 5; d++) {
3699                         error = dmu_object_info(spa->spa_meta_objset,
3700                             (1ULL << t) + d, NULL);
3701                         ASSERT(error == 0 || error == ENOENT ||
3702                             error == EINVAL);
3703                 }
3704         }
3705
3706         /*
3707          * Now kick off all the tests that run in parallel.
3708          */
3709         zs->zs_enospc_count = 0;
3710
3711         za = umem_zalloc(zopt_threads * sizeof (ztest_args_t), UMEM_NOFAIL);
3712
3713         if (zopt_verbose >= 4)
3714                 (void) printf("starting main threads...\n");
3715
3716         za[0].za_start = gethrtime();
3717         za[0].za_stop = za[0].za_start + zopt_passtime * NANOSEC;
3718         za[0].za_stop = MIN(za[0].za_stop, zs->zs_stop_time);
3719         za[0].za_kill = za[0].za_stop;
3720         if (ztest_random(100) < zopt_killrate)
3721                 za[0].za_kill -= ztest_random(zopt_passtime * NANOSEC);
3722
3723         for (t = 0; t < zopt_threads; t++) {
3724                 d = t % zopt_datasets;
3725
3726                 (void) strcpy(za[t].za_pool, pool);
3727                 za[t].za_os = za[d].za_os;
3728                 za[t].za_spa = spa;
3729                 za[t].za_zilog = za[d].za_zilog;
3730                 za[t].za_instance = t;
3731                 za[t].za_random = ztest_random(-1ULL);
3732                 za[t].za_start = za[0].za_start;
3733                 za[t].za_stop = za[0].za_stop;
3734                 za[t].za_kill = za[0].za_kill;
3735
3736                 if (t < zopt_datasets) {
3737                         int test_future = FALSE;
3738                         (void) rw_rdlock(&ztest_shared->zs_name_lock);
3739                         (void) snprintf(name, 100, "%s/%s_%d", pool, pool, d);
3740                         error = dmu_objset_create(name, DMU_OST_OTHER, NULL, 0,
3741                             ztest_create_cb, NULL);
3742                         if (error == EEXIST) {
3743                                 test_future = TRUE;
3744                         } else if (error == ENOSPC) {
3745                                 zs->zs_enospc_count++;
3746                                 (void) rw_unlock(&ztest_shared->zs_name_lock);
3747                                 break;
3748                         } else if (error != 0) {
3749                                 fatal(0, "dmu_objset_create(%s) = %d",
3750                                     name, error);
3751                         }
3752                         error = dmu_objset_open(name, DMU_OST_OTHER,
3753                             DS_MODE_USER, &za[d].za_os);
3754                         if (error)
3755                                 fatal(0, "dmu_objset_open('%s') = %d",
3756                                     name, error);
3757                         (void) rw_unlock(&ztest_shared->zs_name_lock);
3758                         if (test_future)
3759                                 ztest_dmu_check_future_leak(&za[t]);
3760                         zil_replay(za[d].za_os, za[d].za_os,
3761                             ztest_replay_vector);
3762                         za[d].za_zilog = zil_open(za[d].za_os, NULL);
3763                 }
3764
3765                 VERIFY(thr_create(0, 0, ztest_thread, &za[t], THR_BOUND,
3766                     &za[t].za_thread) == 0);
3767         }
3768
3769         while (--t >= 0) {
3770                 VERIFY(thr_join(za[t].za_thread, NULL, NULL) == 0);
3771                 if (t < zopt_datasets) {
3772                         zil_close(za[t].za_zilog);
3773                         dmu_objset_close(za[t].za_os);
3774                 }
3775         }
3776
3777         if (zopt_verbose >= 3)
3778                 show_pool_stats(spa);
3779
3780         txg_wait_synced(spa_get_dsl(spa), 0);
3781
3782         zs->zs_alloc = spa_get_alloc(spa);
3783         zs->zs_space = spa_get_space(spa);
3784
3785         /*
3786          * If we had out-of-space errors, destroy a random objset.
3787          */
3788         if (zs->zs_enospc_count != 0) {
3789                 (void) rw_rdlock(&ztest_shared->zs_name_lock);
3790                 d = (int)ztest_random(zopt_datasets);
3791                 (void) snprintf(name, 100, "%s/%s_%d", pool, pool, d);
3792                 if (zopt_verbose >= 3)
3793                         (void) printf("Destroying %s to free up space\n", name);
3794                 (void) dmu_objset_find(name, ztest_destroy_cb, &za[d],
3795                     DS_FIND_SNAPSHOTS | DS_FIND_CHILDREN);
3796                 (void) rw_unlock(&ztest_shared->zs_name_lock);
3797         }
3798
3799         txg_wait_synced(spa_get_dsl(spa), 0);
3800
3801         umem_free(za, zopt_threads * sizeof (ztest_args_t));
3802
3803         /* Kill the resume thread */
3804         ztest_exiting = B_TRUE;
3805         VERIFY(thr_join(resume_tid, NULL, NULL) == 0);
3806         ztest_resume(spa);
3807
3808         /*
3809          * Right before closing the pool, kick off a bunch of async I/O;
3810          * spa_close() should wait for it to complete.
3811          */
3812         for (t = 1; t < 50; t++)
3813                 dmu_prefetch(spa->spa_meta_objset, t, 0, 1 << 15);
3814
3815         spa_close(spa, FTAG);
3816
3817         kernel_fini();
3818 }
3819
3820 void
3821 print_time(hrtime_t t, char *timebuf)
3822 {
3823         hrtime_t s = t / NANOSEC;
3824         hrtime_t m = s / 60;
3825         hrtime_t h = m / 60;
3826         hrtime_t d = h / 24;
3827
3828         s -= m * 60;
3829         m -= h * 60;
3830         h -= d * 24;
3831
3832         timebuf[0] = '\0';
3833
3834         if (d)
3835                 (void) sprintf(timebuf,
3836                     "%llud%02lluh%02llum%02llus", d, h, m, s);
3837         else if (h)
3838                 (void) sprintf(timebuf, "%lluh%02llum%02llus", h, m, s);
3839         else if (m)
3840                 (void) sprintf(timebuf, "%llum%02llus", m, s);
3841         else
3842                 (void) sprintf(timebuf, "%llus", s);
3843 }
3844
3845 /*
3846  * Create a storage pool with the given name and initial vdev size.
3847  * Then create the specified number of datasets in the pool.
3848  */
3849 static void
3850 ztest_init(char *pool)
3851 {
3852         spa_t *spa;
3853         int error;
3854         nvlist_t *nvroot;
3855
3856         kernel_init(FREAD | FWRITE);
3857
3858         /*
3859          * Create the storage pool.
3860          */
3861         (void) spa_destroy(pool);
3862         ztest_shared->zs_vdev_primaries = 0;
3863         nvroot = make_vdev_root(NULL, NULL, zopt_vdev_size, 0,
3864             0, zopt_raidz, zopt_mirrors, 1);
3865         error = spa_create(pool, nvroot, NULL, NULL, NULL);
3866         nvlist_free(nvroot);
3867
3868         if (error)
3869                 fatal(0, "spa_create() = %d", error);
3870         error = spa_open(pool, &spa, FTAG);
3871         if (error)
3872                 fatal(0, "spa_open() = %d", error);
3873
3874         metaslab_sz = 1ULL << spa->spa_root_vdev->vdev_child[0]->vdev_ms_shift;
3875
3876         if (zopt_verbose >= 3)
3877                 show_pool_stats(spa);
3878
3879         spa_close(spa, FTAG);
3880
3881         kernel_fini();
3882 }
3883
3884 int
3885 main(int argc, char **argv)
3886 {
3887         int kills = 0;
3888         int iters = 0;
3889         int i, f;
3890         ztest_shared_t *zs;
3891         ztest_info_t *zi;
3892         char timebuf[100];
3893         char numbuf[6];
3894
3895         (void) setvbuf(stdout, NULL, _IOLBF, 0);
3896
3897         /* Override location of zpool.cache */
3898         spa_config_path = "/tmp/zpool.cache";
3899
3900         ztest_random_fd = open("/dev/urandom", O_RDONLY);
3901
3902         process_options(argc, argv);
3903
3904         /*
3905          * Blow away any existing copy of zpool.cache
3906          */
3907         if (zopt_init != 0)
3908                 (void) remove("/tmp/zpool.cache");
3909
3910         zs = ztest_shared = (void *)mmap(0,
3911             P2ROUNDUP(sizeof (ztest_shared_t), getpagesize()),
3912             PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANON, -1, 0);
3913
3914         if (zopt_verbose >= 1) {
3915                 (void) printf("%llu vdevs, %d datasets, %d threads,"
3916                     " %llu seconds...\n",
3917                     (u_longlong_t)zopt_vdevs, zopt_datasets, zopt_threads,
3918                     (u_longlong_t)zopt_time);
3919         }
3920
3921         /*
3922          * Create and initialize our storage pool.
3923          */
3924         for (i = 1; i <= zopt_init; i++) {
3925                 bzero(zs, sizeof (ztest_shared_t));
3926                 if (zopt_verbose >= 3 && zopt_init != 1)
3927                         (void) printf("ztest_init(), pass %d\n", i);
3928                 ztest_init(zopt_pool);
3929         }
3930
3931         /*
3932          * Initialize the call targets for each function.
3933          */
3934         for (f = 0; f < ZTEST_FUNCS; f++) {
3935                 zi = &zs->zs_info[f];
3936
3937                 *zi = ztest_info[f];
3938
3939                 if (*zi->zi_interval == 0)
3940                         zi->zi_call_target = UINT64_MAX;
3941                 else
3942                         zi->zi_call_target = zopt_time / *zi->zi_interval;
3943         }
3944
3945         zs->zs_start_time = gethrtime();
3946         zs->zs_stop_time = zs->zs_start_time + zopt_time * NANOSEC;
3947
3948         /*
3949          * Run the tests in a loop.  These tests include fault injection
3950          * to verify that self-healing data works, and forced crashes
3951          * to verify that we never lose on-disk consistency.
3952          */
3953         while (gethrtime() < zs->zs_stop_time) {
3954                 int status;
3955                 pid_t pid;
3956                 char *tmp;
3957
3958                 /*
3959                  * Initialize the workload counters for each function.
3960                  */
3961                 for (f = 0; f < ZTEST_FUNCS; f++) {
3962                         zi = &zs->zs_info[f];
3963                         zi->zi_calls = 0;
3964                         zi->zi_call_time = 0;
3965                 }
3966
3967                 /* Set the allocation switch size */
3968                 metaslab_df_alloc_threshold = ztest_random(metaslab_sz / 4) + 1;
3969
3970                 pid = fork();
3971
3972                 if (pid == -1)
3973                         fatal(1, "fork failed");
3974
3975                 if (pid == 0) { /* child */
3976                         struct rlimit rl = { 1024, 1024 };
3977                         (void) setrlimit(RLIMIT_NOFILE, &rl);
3978                         (void) enable_extended_FILE_stdio(-1, -1);
3979                         ztest_run(zopt_pool);
3980                         exit(0);
3981                 }
3982
3983                 while (waitpid(pid, &status, 0) != pid)
3984                         continue;
3985
3986                 if (WIFEXITED(status)) {
3987                         if (WEXITSTATUS(status) != 0) {
3988                                 (void) fprintf(stderr,
3989                                     "child exited with code %d\n",
3990                                     WEXITSTATUS(status));
3991                                 exit(2);
3992                         }
3993                 } else if (WIFSIGNALED(status)) {
3994                         if (WTERMSIG(status) != SIGKILL) {
3995                                 (void) fprintf(stderr,
3996                                     "child died with signal %d\n",
3997                                     WTERMSIG(status));
3998                                 exit(3);
3999                         }
4000                         kills++;
4001                 } else {
4002                         (void) fprintf(stderr, "something strange happened "
4003                             "to child\n");
4004                         exit(4);
4005                 }
4006
4007                 iters++;
4008
4009                 if (zopt_verbose >= 1) {
4010                         hrtime_t now = gethrtime();
4011
4012                         now = MIN(now, zs->zs_stop_time);
4013                         print_time(zs->zs_stop_time - now, timebuf);
4014                         nicenum(zs->zs_space, numbuf);
4015
4016                         (void) printf("Pass %3d, %8s, %3llu ENOSPC, "
4017                             "%4.1f%% of %5s used, %3.0f%% done, %8s to go\n",
4018                             iters,
4019                             WIFEXITED(status) ? "Complete" : "SIGKILL",
4020                             (u_longlong_t)zs->zs_enospc_count,
4021                             100.0 * zs->zs_alloc / zs->zs_space,
4022                             numbuf,
4023                             100.0 * (now - zs->zs_start_time) /
4024                             (zopt_time * NANOSEC), timebuf);
4025                 }
4026
4027                 if (zopt_verbose >= 2) {
4028                         (void) printf("\nWorkload summary:\n\n");
4029                         (void) printf("%7s %9s   %s\n",
4030                             "Calls", "Time", "Function");
4031                         (void) printf("%7s %9s   %s\n",
4032                             "-----", "----", "--------");
4033                         for (f = 0; f < ZTEST_FUNCS; f++) {
4034                                 Dl_info dli;
4035
4036                                 zi = &zs->zs_info[f];
4037                                 print_time(zi->zi_call_time, timebuf);
4038                                 (void) dladdr((void *)zi->zi_func, &dli);
4039                                 (void) printf("%7llu %9s   %s\n",
4040                                     (u_longlong_t)zi->zi_calls, timebuf,
4041                                     dli.dli_sname);
4042                         }
4043                         (void) printf("\n");
4044                 }
4045
4046                 /*
4047                  * It's possible that we killed a child during a rename test, in
4048                  * which case we'll have a 'ztest_tmp' pool lying around instead
4049                  * of 'ztest'.  Do a blind rename in case this happened.
4050                  */
4051                 tmp = umem_alloc(strlen(zopt_pool) + 5, UMEM_NOFAIL);
4052                 (void) strcpy(tmp, zopt_pool);
4053                 (void) strcat(tmp, "_tmp");
4054                 kernel_init(FREAD | FWRITE);
4055                 (void) spa_rename(tmp, zopt_pool);
4056                 kernel_fini();
4057                 umem_free(tmp, strlen(tmp) + 1);
4058         }
4059
4060         ztest_verify_blocks(zopt_pool);
4061
4062         if (zopt_verbose >= 1) {
4063                 (void) printf("%d killed, %d completed, %.0f%% kill rate\n",
4064                     kills, iters - kills, (100.0 * kills) / MAX(1, iters));
4065         }
4066
4067         return (0);
4068 }