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