]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - cddl/contrib/opensolaris/cmd/zdb/zdb.c
MFV r329502: 7614 zfs device evacuation/removal
[FreeBSD/FreeBSD.git] / cddl / contrib / opensolaris / cmd / zdb / zdb.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 /*
23  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright (c) 2011, 2017 by Delphix. All rights reserved.
25  * Copyright (c) 2014 Integros [integros.com]
26  * Copyright 2017 Nexenta Systems, Inc.
27  */
28
29 #include <stdio.h>
30 #include <unistd.h>
31 #include <stdio_ext.h>
32 #include <stdlib.h>
33 #include <ctype.h>
34 #include <sys/zfs_context.h>
35 #include <sys/spa.h>
36 #include <sys/spa_impl.h>
37 #include <sys/dmu.h>
38 #include <sys/zap.h>
39 #include <sys/fs/zfs.h>
40 #include <sys/zfs_znode.h>
41 #include <sys/zfs_sa.h>
42 #include <sys/sa.h>
43 #include <sys/sa_impl.h>
44 #include <sys/vdev.h>
45 #include <sys/vdev_impl.h>
46 #include <sys/metaslab_impl.h>
47 #include <sys/dmu_objset.h>
48 #include <sys/dsl_dir.h>
49 #include <sys/dsl_dataset.h>
50 #include <sys/dsl_pool.h>
51 #include <sys/dbuf.h>
52 #include <sys/zil.h>
53 #include <sys/zil_impl.h>
54 #include <sys/stat.h>
55 #include <sys/resource.h>
56 #include <sys/dmu_traverse.h>
57 #include <sys/zio_checksum.h>
58 #include <sys/zio_compress.h>
59 #include <sys/zfs_fuid.h>
60 #include <sys/arc.h>
61 #include <sys/ddt.h>
62 #include <sys/zfeature.h>
63 #include <sys/abd.h>
64 #include <sys/blkptr.h>
65 #include <zfs_comutil.h>
66 #include <libcmdutils.h>
67 #undef verify
68 #include <libzfs.h>
69
70 #include "zdb.h"
71
72 #define ZDB_COMPRESS_NAME(idx) ((idx) < ZIO_COMPRESS_FUNCTIONS ?        \
73         zio_compress_table[(idx)].ci_name : "UNKNOWN")
74 #define ZDB_CHECKSUM_NAME(idx) ((idx) < ZIO_CHECKSUM_FUNCTIONS ?        \
75         zio_checksum_table[(idx)].ci_name : "UNKNOWN")
76 #define ZDB_OT_NAME(idx) ((idx) < DMU_OT_NUMTYPES ?     \
77         dmu_ot[(idx)].ot_name : DMU_OT_IS_VALID(idx) ?  \
78         dmu_ot_byteswap[DMU_OT_BYTESWAP(idx)].ob_name : "UNKNOWN")
79 #define ZDB_OT_TYPE(idx) ((idx) < DMU_OT_NUMTYPES ? (idx) :             \
80         (idx) == DMU_OTN_ZAP_DATA || (idx) == DMU_OTN_ZAP_METADATA ?    \
81         DMU_OT_ZAP_OTHER : \
82         (idx) == DMU_OTN_UINT64_DATA || (idx) == DMU_OTN_UINT64_METADATA ? \
83         DMU_OT_UINT64_OTHER : DMU_OT_NUMTYPES)
84
85 #ifndef lint
86 extern int reference_tracking_enable;
87 extern boolean_t zfs_recover;
88 extern uint64_t zfs_arc_max, zfs_arc_meta_limit;
89 extern int zfs_vdev_async_read_max_active;
90 #else
91 int reference_tracking_enable;
92 boolean_t zfs_recover;
93 uint64_t zfs_arc_max, zfs_arc_meta_limit;
94 int zfs_vdev_async_read_max_active;
95 #endif
96
97 static const char cmdname[] = "zdb";
98 uint8_t dump_opt[256];
99
100 typedef void object_viewer_t(objset_t *, uint64_t, void *data, size_t size);
101
102 static uint64_t *zopt_object = NULL;
103 static unsigned zopt_objects = 0;
104 static libzfs_handle_t *g_zfs;
105 static uint64_t max_inflight = 1000;
106
107 static void snprintf_blkptr_compact(char *, size_t, const blkptr_t *);
108
109 /*
110  * These libumem hooks provide a reasonable set of defaults for the allocator's
111  * debugging facilities.
112  */
113 const char *
114 _umem_debug_init()
115 {
116         return ("default,verbose"); /* $UMEM_DEBUG setting */
117 }
118
119 const char *
120 _umem_logging_init(void)
121 {
122         return ("fail,contents"); /* $UMEM_LOGGING setting */
123 }
124
125 static void
126 usage(void)
127 {
128         (void) fprintf(stderr,
129             "Usage:\t%s [-AbcdDFGhiLMPsvX] [-e [-V] [-p <path> ...]] "
130             "[-I <inflight I/Os>]\n"
131             "\t\t[-o <var>=<value>]... [-t <txg>] [-U <cache>] [-x <dumpdir>]\n"
132             "\t\t[<poolname> [<object> ...]]\n"
133             "\t%s [-AdiPv] [-e [-V] [-p <path> ...]] [-U <cache>] <dataset> "
134             "[<object> ...]\n"
135             "\t%s -C [-A] [-U <cache>]\n"
136             "\t%s -l [-Aqu] <device>\n"
137             "\t%s -m [-AFLPX] [-e [-V] [-p <path> ...]] [-t <txg>] "
138             "[-U <cache>]\n\t\t<poolname> [<vdev> [<metaslab> ...]]\n"
139             "\t%s -O <dataset> <path>\n"
140             "\t%s -R [-A] [-e [-V] [-p <path> ...]] [-U <cache>]\n"
141             "\t\t<poolname> <vdev>:<offset>:<size>[:<flags>]\n"
142             "\t%s -E [-A] word0:word1:...:word15\n"
143             "\t%s -S [-AP] [-e [-V] [-p <path> ...]] [-U <cache>] "
144             "<poolname>\n\n",
145             cmdname, cmdname, cmdname, cmdname, cmdname, cmdname, cmdname,
146             cmdname, cmdname);
147
148         (void) fprintf(stderr, "    Dataset name must include at least one "
149             "separator character '/' or '@'\n");
150         (void) fprintf(stderr, "    If dataset name is specified, only that "
151             "dataset is dumped\n");
152         (void) fprintf(stderr, "    If object numbers are specified, only "
153             "those objects are dumped\n\n");
154         (void) fprintf(stderr, "    Options to control amount of output:\n");
155         (void) fprintf(stderr, "        -b block statistics\n");
156         (void) fprintf(stderr, "        -c checksum all metadata (twice for "
157             "all data) blocks\n");
158         (void) fprintf(stderr, "        -C config (or cachefile if alone)\n");
159         (void) fprintf(stderr, "        -d dataset(s)\n");
160         (void) fprintf(stderr, "        -D dedup statistics\n");
161         (void) fprintf(stderr, "        -E decode and display block from an "
162             "embedded block pointer\n");
163         (void) fprintf(stderr, "        -h pool history\n");
164         (void) fprintf(stderr, "        -i intent logs\n");
165         (void) fprintf(stderr, "        -l read label contents\n");
166         (void) fprintf(stderr, "        -L disable leak tracking (do not "
167             "load spacemaps)\n");
168         (void) fprintf(stderr, "        -m metaslabs\n");
169         (void) fprintf(stderr, "        -M metaslab groups\n");
170         (void) fprintf(stderr, "        -O perform object lookups by path\n");
171         (void) fprintf(stderr, "        -R read and display block from a "
172             "device\n");
173         (void) fprintf(stderr, "        -s report stats on zdb's I/O\n");
174         (void) fprintf(stderr, "        -S simulate dedup to measure effect\n");
175         (void) fprintf(stderr, "        -v verbose (applies to all "
176             "others)\n\n");
177         (void) fprintf(stderr, "    Below options are intended for use "
178             "with other options:\n");
179         (void) fprintf(stderr, "        -A ignore assertions (-A), enable "
180             "panic recovery (-AA) or both (-AAA)\n");
181         (void) fprintf(stderr, "        -e pool is exported/destroyed/"
182             "has altroot/not in a cachefile\n");
183         (void) fprintf(stderr, "        -F attempt automatic rewind within "
184             "safe range of transaction groups\n");
185         (void) fprintf(stderr, "        -G dump zfs_dbgmsg buffer before "
186             "exiting\n");
187         (void) fprintf(stderr, "        -I <number of inflight I/Os> -- "
188             "specify the maximum number of "
189             "checksumming I/Os [default is 200]\n");
190         (void) fprintf(stderr, "        -o <variable>=<value> set global "
191             "variable to an unsigned 32-bit integer value\n");
192         (void) fprintf(stderr, "        -p <path> -- use one or more with "
193             "-e to specify path to vdev dir\n");
194         (void) fprintf(stderr, "        -P print numbers in parseable form\n");
195         (void) fprintf(stderr, "        -q don't print label contents\n");
196         (void) fprintf(stderr, "        -t <txg> -- highest txg to use when "
197             "searching for uberblocks\n");
198         (void) fprintf(stderr, "        -u uberblock\n");
199         (void) fprintf(stderr, "        -U <cachefile_path> -- use alternate "
200             "cachefile\n");
201         (void) fprintf(stderr, "        -V do verbatim import\n");
202         (void) fprintf(stderr, "        -x <dumpdir> -- "
203             "dump all read blocks into specified directory\n");
204         (void) fprintf(stderr, "        -X attempt extreme rewind (does not "
205             "work with dataset)\n\n");
206         (void) fprintf(stderr, "Specify an option more than once (e.g. -bb) "
207             "to make only that option verbose\n");
208         (void) fprintf(stderr, "Default is to dump everything non-verbosely\n");
209         exit(1);
210 }
211
212 static void
213 dump_debug_buffer()
214 {
215         if (dump_opt['G']) {
216                 (void) printf("\n");
217                 zfs_dbgmsg_print("zdb");
218         }
219 }
220
221 /*
222  * Called for usage errors that are discovered after a call to spa_open(),
223  * dmu_bonus_hold(), or pool_match().  abort() is called for other errors.
224  */
225
226 static void
227 fatal(const char *fmt, ...)
228 {
229         va_list ap;
230
231         va_start(ap, fmt);
232         (void) fprintf(stderr, "%s: ", cmdname);
233         (void) vfprintf(stderr, fmt, ap);
234         va_end(ap);
235         (void) fprintf(stderr, "\n");
236
237         dump_debug_buffer();
238
239         exit(1);
240 }
241
242 /* ARGSUSED */
243 static void
244 dump_packed_nvlist(objset_t *os, uint64_t object, void *data, size_t size)
245 {
246         nvlist_t *nv;
247         size_t nvsize = *(uint64_t *)data;
248         char *packed = umem_alloc(nvsize, UMEM_NOFAIL);
249
250         VERIFY(0 == dmu_read(os, object, 0, nvsize, packed, DMU_READ_PREFETCH));
251
252         VERIFY(nvlist_unpack(packed, nvsize, &nv, 0) == 0);
253
254         umem_free(packed, nvsize);
255
256         dump_nvlist(nv, 8);
257
258         nvlist_free(nv);
259 }
260
261 /* ARGSUSED */
262 static void
263 dump_history_offsets(objset_t *os, uint64_t object, void *data, size_t size)
264 {
265         spa_history_phys_t *shp = data;
266
267         if (shp == NULL)
268                 return;
269
270         (void) printf("\t\tpool_create_len = %llu\n",
271             (u_longlong_t)shp->sh_pool_create_len);
272         (void) printf("\t\tphys_max_off = %llu\n",
273             (u_longlong_t)shp->sh_phys_max_off);
274         (void) printf("\t\tbof = %llu\n",
275             (u_longlong_t)shp->sh_bof);
276         (void) printf("\t\teof = %llu\n",
277             (u_longlong_t)shp->sh_eof);
278         (void) printf("\t\trecords_lost = %llu\n",
279             (u_longlong_t)shp->sh_records_lost);
280 }
281
282 static void
283 zdb_nicenum(uint64_t num, char *buf, size_t buflen)
284 {
285         if (dump_opt['P'])
286                 (void) snprintf(buf, buflen, "%llu", (longlong_t)num);
287         else
288                 nicenum(num, buf, sizeof (buf));
289 }
290
291 static const char histo_stars[] = "****************************************";
292 static const uint64_t histo_width = sizeof (histo_stars) - 1;
293
294 static void
295 dump_histogram(const uint64_t *histo, int size, int offset)
296 {
297         int i;
298         int minidx = size - 1;
299         int maxidx = 0;
300         uint64_t max = 0;
301
302         for (i = 0; i < size; i++) {
303                 if (histo[i] > max)
304                         max = histo[i];
305                 if (histo[i] > 0 && i > maxidx)
306                         maxidx = i;
307                 if (histo[i] > 0 && i < minidx)
308                         minidx = i;
309         }
310
311         if (max < histo_width)
312                 max = histo_width;
313
314         for (i = minidx; i <= maxidx; i++) {
315                 (void) printf("\t\t\t%3u: %6llu %s\n",
316                     i + offset, (u_longlong_t)histo[i],
317                     &histo_stars[(max - histo[i]) * histo_width / max]);
318         }
319 }
320
321 static void
322 dump_zap_stats(objset_t *os, uint64_t object)
323 {
324         int error;
325         zap_stats_t zs;
326
327         error = zap_get_stats(os, object, &zs);
328         if (error)
329                 return;
330
331         if (zs.zs_ptrtbl_len == 0) {
332                 ASSERT(zs.zs_num_blocks == 1);
333                 (void) printf("\tmicrozap: %llu bytes, %llu entries\n",
334                     (u_longlong_t)zs.zs_blocksize,
335                     (u_longlong_t)zs.zs_num_entries);
336                 return;
337         }
338
339         (void) printf("\tFat ZAP stats:\n");
340
341         (void) printf("\t\tPointer table:\n");
342         (void) printf("\t\t\t%llu elements\n",
343             (u_longlong_t)zs.zs_ptrtbl_len);
344         (void) printf("\t\t\tzt_blk: %llu\n",
345             (u_longlong_t)zs.zs_ptrtbl_zt_blk);
346         (void) printf("\t\t\tzt_numblks: %llu\n",
347             (u_longlong_t)zs.zs_ptrtbl_zt_numblks);
348         (void) printf("\t\t\tzt_shift: %llu\n",
349             (u_longlong_t)zs.zs_ptrtbl_zt_shift);
350         (void) printf("\t\t\tzt_blks_copied: %llu\n",
351             (u_longlong_t)zs.zs_ptrtbl_blks_copied);
352         (void) printf("\t\t\tzt_nextblk: %llu\n",
353             (u_longlong_t)zs.zs_ptrtbl_nextblk);
354
355         (void) printf("\t\tZAP entries: %llu\n",
356             (u_longlong_t)zs.zs_num_entries);
357         (void) printf("\t\tLeaf blocks: %llu\n",
358             (u_longlong_t)zs.zs_num_leafs);
359         (void) printf("\t\tTotal blocks: %llu\n",
360             (u_longlong_t)zs.zs_num_blocks);
361         (void) printf("\t\tzap_block_type: 0x%llx\n",
362             (u_longlong_t)zs.zs_block_type);
363         (void) printf("\t\tzap_magic: 0x%llx\n",
364             (u_longlong_t)zs.zs_magic);
365         (void) printf("\t\tzap_salt: 0x%llx\n",
366             (u_longlong_t)zs.zs_salt);
367
368         (void) printf("\t\tLeafs with 2^n pointers:\n");
369         dump_histogram(zs.zs_leafs_with_2n_pointers, ZAP_HISTOGRAM_SIZE, 0);
370
371         (void) printf("\t\tBlocks with n*5 entries:\n");
372         dump_histogram(zs.zs_blocks_with_n5_entries, ZAP_HISTOGRAM_SIZE, 0);
373
374         (void) printf("\t\tBlocks n/10 full:\n");
375         dump_histogram(zs.zs_blocks_n_tenths_full, ZAP_HISTOGRAM_SIZE, 0);
376
377         (void) printf("\t\tEntries with n chunks:\n");
378         dump_histogram(zs.zs_entries_using_n_chunks, ZAP_HISTOGRAM_SIZE, 0);
379
380         (void) printf("\t\tBuckets with n entries:\n");
381         dump_histogram(zs.zs_buckets_with_n_entries, ZAP_HISTOGRAM_SIZE, 0);
382 }
383
384 /*ARGSUSED*/
385 static void
386 dump_none(objset_t *os, uint64_t object, void *data, size_t size)
387 {
388 }
389
390 /*ARGSUSED*/
391 static void
392 dump_unknown(objset_t *os, uint64_t object, void *data, size_t size)
393 {
394         (void) printf("\tUNKNOWN OBJECT TYPE\n");
395 }
396
397 /*ARGSUSED*/
398 static void
399 dump_uint8(objset_t *os, uint64_t object, void *data, size_t size)
400 {
401 }
402
403 /*ARGSUSED*/
404 static void
405 dump_uint64(objset_t *os, uint64_t object, void *data, size_t size)
406 {
407 }
408
409 /*ARGSUSED*/
410 static void
411 dump_zap(objset_t *os, uint64_t object, void *data, size_t size)
412 {
413         zap_cursor_t zc;
414         zap_attribute_t attr;
415         void *prop;
416         unsigned i;
417
418         dump_zap_stats(os, object);
419         (void) printf("\n");
420
421         for (zap_cursor_init(&zc, os, object);
422             zap_cursor_retrieve(&zc, &attr) == 0;
423             zap_cursor_advance(&zc)) {
424                 (void) printf("\t\t%s = ", attr.za_name);
425                 if (attr.za_num_integers == 0) {
426                         (void) printf("\n");
427                         continue;
428                 }
429                 prop = umem_zalloc(attr.za_num_integers *
430                     attr.za_integer_length, UMEM_NOFAIL);
431                 (void) zap_lookup(os, object, attr.za_name,
432                     attr.za_integer_length, attr.za_num_integers, prop);
433                 if (attr.za_integer_length == 1) {
434                         (void) printf("%s", (char *)prop);
435                 } else {
436                         for (i = 0; i < attr.za_num_integers; i++) {
437                                 switch (attr.za_integer_length) {
438                                 case 2:
439                                         (void) printf("%u ",
440                                             ((uint16_t *)prop)[i]);
441                                         break;
442                                 case 4:
443                                         (void) printf("%u ",
444                                             ((uint32_t *)prop)[i]);
445                                         break;
446                                 case 8:
447                                         (void) printf("%lld ",
448                                             (u_longlong_t)((int64_t *)prop)[i]);
449                                         break;
450                                 }
451                         }
452                 }
453                 (void) printf("\n");
454                 umem_free(prop, attr.za_num_integers * attr.za_integer_length);
455         }
456         zap_cursor_fini(&zc);
457 }
458
459 static void
460 dump_bpobj(objset_t *os, uint64_t object, void *data, size_t size)
461 {
462         bpobj_phys_t *bpop = data;
463         char bytes[32], comp[32], uncomp[32];
464
465         /* make sure the output won't get truncated */
466         CTASSERT(sizeof (bytes) >= NN_NUMBUF_SZ);
467         CTASSERT(sizeof (comp) >= NN_NUMBUF_SZ);
468         CTASSERT(sizeof (uncomp) >= NN_NUMBUF_SZ);
469
470         if (bpop == NULL)
471                 return;
472
473         zdb_nicenum(bpop->bpo_bytes, bytes, sizeof (bytes));
474         zdb_nicenum(bpop->bpo_comp, comp, sizeof (comp));
475         zdb_nicenum(bpop->bpo_uncomp, uncomp, sizeof (uncomp));
476
477         (void) printf("\t\tnum_blkptrs = %llu\n",
478             (u_longlong_t)bpop->bpo_num_blkptrs);
479         (void) printf("\t\tbytes = %s\n", bytes);
480         if (size >= BPOBJ_SIZE_V1) {
481                 (void) printf("\t\tcomp = %s\n", comp);
482                 (void) printf("\t\tuncomp = %s\n", uncomp);
483         }
484         if (size >= sizeof (*bpop)) {
485                 (void) printf("\t\tsubobjs = %llu\n",
486                     (u_longlong_t)bpop->bpo_subobjs);
487                 (void) printf("\t\tnum_subobjs = %llu\n",
488                     (u_longlong_t)bpop->bpo_num_subobjs);
489         }
490
491         if (dump_opt['d'] < 5)
492                 return;
493
494         for (uint64_t i = 0; i < bpop->bpo_num_blkptrs; i++) {
495                 char blkbuf[BP_SPRINTF_LEN];
496                 blkptr_t bp;
497
498                 int err = dmu_read(os, object,
499                     i * sizeof (bp), sizeof (bp), &bp, 0);
500                 if (err != 0) {
501                         (void) printf("got error %u from dmu_read\n", err);
502                         break;
503                 }
504                 snprintf_blkptr_compact(blkbuf, sizeof (blkbuf), &bp);
505                 (void) printf("\t%s\n", blkbuf);
506         }
507 }
508
509 /* ARGSUSED */
510 static void
511 dump_bpobj_subobjs(objset_t *os, uint64_t object, void *data, size_t size)
512 {
513         dmu_object_info_t doi;
514
515         VERIFY0(dmu_object_info(os, object, &doi));
516         uint64_t *subobjs = kmem_alloc(doi.doi_max_offset, KM_SLEEP);
517
518         int err = dmu_read(os, object, 0, doi.doi_max_offset, subobjs, 0);
519         if (err != 0) {
520                 (void) printf("got error %u from dmu_read\n", err);
521                 kmem_free(subobjs, doi.doi_max_offset);
522                 return;
523         }
524
525         int64_t last_nonzero = -1;
526         for (uint64_t i = 0; i < doi.doi_max_offset / 8; i++) {
527                 if (subobjs[i] != 0)
528                         last_nonzero = i;
529         }
530
531         for (int64_t i = 0; i <= last_nonzero; i++) {
532                 (void) printf("\t%llu\n", (longlong_t)subobjs[i]);
533         }
534         kmem_free(subobjs, doi.doi_max_offset);
535 }
536
537 /*ARGSUSED*/
538 static void
539 dump_ddt_zap(objset_t *os, uint64_t object, void *data, size_t size)
540 {
541         dump_zap_stats(os, object);
542         /* contents are printed elsewhere, properly decoded */
543 }
544
545 /*ARGSUSED*/
546 static void
547 dump_sa_attrs(objset_t *os, uint64_t object, void *data, size_t size)
548 {
549         zap_cursor_t zc;
550         zap_attribute_t attr;
551
552         dump_zap_stats(os, object);
553         (void) printf("\n");
554
555         for (zap_cursor_init(&zc, os, object);
556             zap_cursor_retrieve(&zc, &attr) == 0;
557             zap_cursor_advance(&zc)) {
558                 (void) printf("\t\t%s = ", attr.za_name);
559                 if (attr.za_num_integers == 0) {
560                         (void) printf("\n");
561                         continue;
562                 }
563                 (void) printf(" %llx : [%d:%d:%d]\n",
564                     (u_longlong_t)attr.za_first_integer,
565                     (int)ATTR_LENGTH(attr.za_first_integer),
566                     (int)ATTR_BSWAP(attr.za_first_integer),
567                     (int)ATTR_NUM(attr.za_first_integer));
568         }
569         zap_cursor_fini(&zc);
570 }
571
572 /*ARGSUSED*/
573 static void
574 dump_sa_layouts(objset_t *os, uint64_t object, void *data, size_t size)
575 {
576         zap_cursor_t zc;
577         zap_attribute_t attr;
578         uint16_t *layout_attrs;
579         unsigned i;
580
581         dump_zap_stats(os, object);
582         (void) printf("\n");
583
584         for (zap_cursor_init(&zc, os, object);
585             zap_cursor_retrieve(&zc, &attr) == 0;
586             zap_cursor_advance(&zc)) {
587                 (void) printf("\t\t%s = [", attr.za_name);
588                 if (attr.za_num_integers == 0) {
589                         (void) printf("\n");
590                         continue;
591                 }
592
593                 VERIFY(attr.za_integer_length == 2);
594                 layout_attrs = umem_zalloc(attr.za_num_integers *
595                     attr.za_integer_length, UMEM_NOFAIL);
596
597                 VERIFY(zap_lookup(os, object, attr.za_name,
598                     attr.za_integer_length,
599                     attr.za_num_integers, layout_attrs) == 0);
600
601                 for (i = 0; i != attr.za_num_integers; i++)
602                         (void) printf(" %d ", (int)layout_attrs[i]);
603                 (void) printf("]\n");
604                 umem_free(layout_attrs,
605                     attr.za_num_integers * attr.za_integer_length);
606         }
607         zap_cursor_fini(&zc);
608 }
609
610 /*ARGSUSED*/
611 static void
612 dump_zpldir(objset_t *os, uint64_t object, void *data, size_t size)
613 {
614         zap_cursor_t zc;
615         zap_attribute_t attr;
616         const char *typenames[] = {
617                 /* 0 */ "not specified",
618                 /* 1 */ "FIFO",
619                 /* 2 */ "Character Device",
620                 /* 3 */ "3 (invalid)",
621                 /* 4 */ "Directory",
622                 /* 5 */ "5 (invalid)",
623                 /* 6 */ "Block Device",
624                 /* 7 */ "7 (invalid)",
625                 /* 8 */ "Regular File",
626                 /* 9 */ "9 (invalid)",
627                 /* 10 */ "Symbolic Link",
628                 /* 11 */ "11 (invalid)",
629                 /* 12 */ "Socket",
630                 /* 13 */ "Door",
631                 /* 14 */ "Event Port",
632                 /* 15 */ "15 (invalid)",
633         };
634
635         dump_zap_stats(os, object);
636         (void) printf("\n");
637
638         for (zap_cursor_init(&zc, os, object);
639             zap_cursor_retrieve(&zc, &attr) == 0;
640             zap_cursor_advance(&zc)) {
641                 (void) printf("\t\t%s = %lld (type: %s)\n",
642                     attr.za_name, ZFS_DIRENT_OBJ(attr.za_first_integer),
643                     typenames[ZFS_DIRENT_TYPE(attr.za_first_integer)]);
644         }
645         zap_cursor_fini(&zc);
646 }
647
648 static int
649 get_dtl_refcount(vdev_t *vd)
650 {
651         int refcount = 0;
652
653         if (vd->vdev_ops->vdev_op_leaf) {
654                 space_map_t *sm = vd->vdev_dtl_sm;
655
656                 if (sm != NULL &&
657                     sm->sm_dbuf->db_size == sizeof (space_map_phys_t))
658                         return (1);
659                 return (0);
660         }
661
662         for (unsigned c = 0; c < vd->vdev_children; c++)
663                 refcount += get_dtl_refcount(vd->vdev_child[c]);
664         return (refcount);
665 }
666
667 static int
668 get_metaslab_refcount(vdev_t *vd)
669 {
670         int refcount = 0;
671
672         if (vd->vdev_top == vd) {
673                 for (uint64_t m = 0; m < vd->vdev_ms_count; m++) {
674                         space_map_t *sm = vd->vdev_ms[m]->ms_sm;
675
676                         if (sm != NULL &&
677                             sm->sm_dbuf->db_size == sizeof (space_map_phys_t))
678                                 refcount++;
679                 }
680         }
681         for (unsigned c = 0; c < vd->vdev_children; c++)
682                 refcount += get_metaslab_refcount(vd->vdev_child[c]);
683
684         return (refcount);
685 }
686
687 static int
688 get_obsolete_refcount(vdev_t *vd)
689 {
690         int refcount = 0;
691
692         uint64_t obsolete_sm_obj = vdev_obsolete_sm_object(vd);
693         if (vd->vdev_top == vd && obsolete_sm_obj != 0) {
694                 dmu_object_info_t doi;
695                 VERIFY0(dmu_object_info(vd->vdev_spa->spa_meta_objset,
696                     obsolete_sm_obj, &doi));
697                 if (doi.doi_bonus_size == sizeof (space_map_phys_t)) {
698                         refcount++;
699                 }
700         } else {
701                 ASSERT3P(vd->vdev_obsolete_sm, ==, NULL);
702                 ASSERT3U(obsolete_sm_obj, ==, 0);
703         }
704         for (unsigned c = 0; c < vd->vdev_children; c++) {
705                 refcount += get_obsolete_refcount(vd->vdev_child[c]);
706         }
707
708         return (refcount);
709 }
710
711 static int
712 get_prev_obsolete_spacemap_refcount(spa_t *spa)
713 {
714         uint64_t prev_obj =
715             spa->spa_condensing_indirect_phys.scip_prev_obsolete_sm_object;
716         if (prev_obj != 0) {
717                 dmu_object_info_t doi;
718                 VERIFY0(dmu_object_info(spa->spa_meta_objset, prev_obj, &doi));
719                 if (doi.doi_bonus_size == sizeof (space_map_phys_t)) {
720                         return (1);
721                 }
722         }
723         return (0);
724 }
725
726 static int
727 verify_spacemap_refcounts(spa_t *spa)
728 {
729         uint64_t expected_refcount = 0;
730         uint64_t actual_refcount;
731
732         (void) feature_get_refcount(spa,
733             &spa_feature_table[SPA_FEATURE_SPACEMAP_HISTOGRAM],
734             &expected_refcount);
735         actual_refcount = get_dtl_refcount(spa->spa_root_vdev);
736         actual_refcount += get_metaslab_refcount(spa->spa_root_vdev);
737         actual_refcount += get_obsolete_refcount(spa->spa_root_vdev);
738         actual_refcount += get_prev_obsolete_spacemap_refcount(spa);
739
740         if (expected_refcount != actual_refcount) {
741                 (void) printf("space map refcount mismatch: expected %lld != "
742                     "actual %lld\n",
743                     (longlong_t)expected_refcount,
744                     (longlong_t)actual_refcount);
745                 return (2);
746         }
747         return (0);
748 }
749
750 static void
751 dump_spacemap(objset_t *os, space_map_t *sm)
752 {
753         uint64_t alloc, offset, entry;
754         char *ddata[] = { "ALLOC", "FREE", "CONDENSE", "INVALID",
755             "INVALID", "INVALID", "INVALID", "INVALID" };
756
757         if (sm == NULL)
758                 return;
759
760         (void) printf("space map object %llu:\n",
761             (longlong_t)sm->sm_phys->smp_object);
762         (void) printf("  smp_objsize = 0x%llx\n",
763             (longlong_t)sm->sm_phys->smp_objsize);
764         (void) printf("  smp_alloc = 0x%llx\n",
765             (longlong_t)sm->sm_phys->smp_alloc);
766
767         /*
768          * Print out the freelist entries in both encoded and decoded form.
769          */
770         alloc = 0;
771         for (offset = 0; offset < space_map_length(sm);
772             offset += sizeof (entry)) {
773                 uint8_t mapshift = sm->sm_shift;
774
775                 VERIFY0(dmu_read(os, space_map_object(sm), offset,
776                     sizeof (entry), &entry, DMU_READ_PREFETCH));
777                 if (SM_DEBUG_DECODE(entry)) {
778
779                         (void) printf("\t    [%6llu] %s: txg %llu, pass %llu\n",
780                             (u_longlong_t)(offset / sizeof (entry)),
781                             ddata[SM_DEBUG_ACTION_DECODE(entry)],
782                             (u_longlong_t)SM_DEBUG_TXG_DECODE(entry),
783                             (u_longlong_t)SM_DEBUG_SYNCPASS_DECODE(entry));
784                 } else {
785                         (void) printf("\t    [%6llu]    %c  range:"
786                             " %010llx-%010llx  size: %06llx\n",
787                             (u_longlong_t)(offset / sizeof (entry)),
788                             SM_TYPE_DECODE(entry) == SM_ALLOC ? 'A' : 'F',
789                             (u_longlong_t)((SM_OFFSET_DECODE(entry) <<
790                             mapshift) + sm->sm_start),
791                             (u_longlong_t)((SM_OFFSET_DECODE(entry) <<
792                             mapshift) + sm->sm_start +
793                             (SM_RUN_DECODE(entry) << mapshift)),
794                             (u_longlong_t)(SM_RUN_DECODE(entry) << mapshift));
795                         if (SM_TYPE_DECODE(entry) == SM_ALLOC)
796                                 alloc += SM_RUN_DECODE(entry) << mapshift;
797                         else
798                                 alloc -= SM_RUN_DECODE(entry) << mapshift;
799                 }
800         }
801         if (alloc != space_map_allocated(sm)) {
802                 (void) printf("space_map_object alloc (%llu) INCONSISTENT "
803                     "with space map summary (%llu)\n",
804                     (u_longlong_t)space_map_allocated(sm), (u_longlong_t)alloc);
805         }
806 }
807
808 static void
809 dump_metaslab_stats(metaslab_t *msp)
810 {
811         char maxbuf[32];
812         range_tree_t *rt = msp->ms_tree;
813         avl_tree_t *t = &msp->ms_size_tree;
814         int free_pct = range_tree_space(rt) * 100 / msp->ms_size;
815
816         /* max sure nicenum has enough space */
817         CTASSERT(sizeof (maxbuf) >= NN_NUMBUF_SZ);
818
819         zdb_nicenum(metaslab_block_maxsize(msp), maxbuf, sizeof (maxbuf));
820
821         (void) printf("\t %25s %10lu   %7s  %6s   %4s %4d%%\n",
822             "segments", avl_numnodes(t), "maxsize", maxbuf,
823             "freepct", free_pct);
824         (void) printf("\tIn-memory histogram:\n");
825         dump_histogram(rt->rt_histogram, RANGE_TREE_HISTOGRAM_SIZE, 0);
826 }
827
828 static void
829 dump_metaslab(metaslab_t *msp)
830 {
831         vdev_t *vd = msp->ms_group->mg_vd;
832         spa_t *spa = vd->vdev_spa;
833         space_map_t *sm = msp->ms_sm;
834         char freebuf[32];
835
836         zdb_nicenum(msp->ms_size - space_map_allocated(sm), freebuf,
837             sizeof (freebuf));
838
839         (void) printf(
840             "\tmetaslab %6llu   offset %12llx   spacemap %6llu   free    %5s\n",
841             (u_longlong_t)msp->ms_id, (u_longlong_t)msp->ms_start,
842             (u_longlong_t)space_map_object(sm), freebuf);
843
844         if (dump_opt['m'] > 2 && !dump_opt['L']) {
845                 mutex_enter(&msp->ms_lock);
846                 metaslab_load_wait(msp);
847                 if (!msp->ms_loaded) {
848                         VERIFY0(metaslab_load(msp));
849                         range_tree_stat_verify(msp->ms_tree);
850                 }
851                 dump_metaslab_stats(msp);
852                 metaslab_unload(msp);
853                 mutex_exit(&msp->ms_lock);
854         }
855
856         if (dump_opt['m'] > 1 && sm != NULL &&
857             spa_feature_is_active(spa, SPA_FEATURE_SPACEMAP_HISTOGRAM)) {
858                 /*
859                  * The space map histogram represents free space in chunks
860                  * of sm_shift (i.e. bucket 0 refers to 2^sm_shift).
861                  */
862                 (void) printf("\tOn-disk histogram:\t\tfragmentation %llu\n",
863                     (u_longlong_t)msp->ms_fragmentation);
864                 dump_histogram(sm->sm_phys->smp_histogram,
865                     SPACE_MAP_HISTOGRAM_SIZE, sm->sm_shift);
866         }
867
868         if (dump_opt['d'] > 5 || dump_opt['m'] > 3) {
869                 ASSERT(msp->ms_size == (1ULL << vd->vdev_ms_shift));
870
871                 dump_spacemap(spa->spa_meta_objset, msp->ms_sm);
872         }
873 }
874
875 static void
876 print_vdev_metaslab_header(vdev_t *vd)
877 {
878         (void) printf("\tvdev %10llu\n\t%-10s%5llu   %-19s   %-15s   %-10s\n",
879             (u_longlong_t)vd->vdev_id,
880             "metaslabs", (u_longlong_t)vd->vdev_ms_count,
881             "offset", "spacemap", "free");
882         (void) printf("\t%15s   %19s   %15s   %10s\n",
883             "---------------", "-------------------",
884             "---------------", "-------------");
885 }
886
887 static void
888 dump_metaslab_groups(spa_t *spa)
889 {
890         vdev_t *rvd = spa->spa_root_vdev;
891         metaslab_class_t *mc = spa_normal_class(spa);
892         uint64_t fragmentation;
893
894         metaslab_class_histogram_verify(mc);
895
896         for (unsigned c = 0; c < rvd->vdev_children; c++) {
897                 vdev_t *tvd = rvd->vdev_child[c];
898                 metaslab_group_t *mg = tvd->vdev_mg;
899
900                 if (mg->mg_class != mc)
901                         continue;
902
903                 metaslab_group_histogram_verify(mg);
904                 mg->mg_fragmentation = metaslab_group_fragmentation(mg);
905
906                 (void) printf("\tvdev %10llu\t\tmetaslabs%5llu\t\t"
907                     "fragmentation",
908                     (u_longlong_t)tvd->vdev_id,
909                     (u_longlong_t)tvd->vdev_ms_count);
910                 if (mg->mg_fragmentation == ZFS_FRAG_INVALID) {
911                         (void) printf("%3s\n", "-");
912                 } else {
913                         (void) printf("%3llu%%\n",
914                             (u_longlong_t)mg->mg_fragmentation);
915                 }
916                 dump_histogram(mg->mg_histogram, RANGE_TREE_HISTOGRAM_SIZE, 0);
917         }
918
919         (void) printf("\tpool %s\tfragmentation", spa_name(spa));
920         fragmentation = metaslab_class_fragmentation(mc);
921         if (fragmentation == ZFS_FRAG_INVALID)
922                 (void) printf("\t%3s\n", "-");
923         else
924                 (void) printf("\t%3llu%%\n", (u_longlong_t)fragmentation);
925         dump_histogram(mc->mc_histogram, RANGE_TREE_HISTOGRAM_SIZE, 0);
926 }
927
928 static void
929 print_vdev_indirect(vdev_t *vd)
930 {
931         vdev_indirect_config_t *vic = &vd->vdev_indirect_config;
932         vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
933         vdev_indirect_births_t *vib = vd->vdev_indirect_births;
934
935         if (vim == NULL) {
936                 ASSERT3P(vib, ==, NULL);
937                 return;
938         }
939
940         ASSERT3U(vdev_indirect_mapping_object(vim), ==,
941             vic->vic_mapping_object);
942         ASSERT3U(vdev_indirect_births_object(vib), ==,
943             vic->vic_births_object);
944
945         (void) printf("indirect births obj %llu:\n",
946             (longlong_t)vic->vic_births_object);
947         (void) printf("    vib_count = %llu\n",
948             (longlong_t)vdev_indirect_births_count(vib));
949         for (uint64_t i = 0; i < vdev_indirect_births_count(vib); i++) {
950                 vdev_indirect_birth_entry_phys_t *cur_vibe =
951                     &vib->vib_entries[i];
952                 (void) printf("\toffset %llx -> txg %llu\n",
953                     (longlong_t)cur_vibe->vibe_offset,
954                     (longlong_t)cur_vibe->vibe_phys_birth_txg);
955         }
956         (void) printf("\n");
957
958         (void) printf("indirect mapping obj %llu:\n",
959             (longlong_t)vic->vic_mapping_object);
960         (void) printf("    vim_max_offset = 0x%llx\n",
961             (longlong_t)vdev_indirect_mapping_max_offset(vim));
962         (void) printf("    vim_bytes_mapped = 0x%llx\n",
963             (longlong_t)vdev_indirect_mapping_bytes_mapped(vim));
964         (void) printf("    vim_count = %llu\n",
965             (longlong_t)vdev_indirect_mapping_num_entries(vim));
966
967         if (dump_opt['d'] <= 5 && dump_opt['m'] <= 3)
968                 return;
969
970         uint32_t *counts = vdev_indirect_mapping_load_obsolete_counts(vim);
971
972         for (uint64_t i = 0; i < vdev_indirect_mapping_num_entries(vim); i++) {
973                 vdev_indirect_mapping_entry_phys_t *vimep =
974                     &vim->vim_entries[i];
975                 (void) printf("\t<%llx:%llx:%llx> -> "
976                     "<%llx:%llx:%llx> (%x obsolete)\n",
977                     (longlong_t)vd->vdev_id,
978                     (longlong_t)DVA_MAPPING_GET_SRC_OFFSET(vimep),
979                     (longlong_t)DVA_GET_ASIZE(&vimep->vimep_dst),
980                     (longlong_t)DVA_GET_VDEV(&vimep->vimep_dst),
981                     (longlong_t)DVA_GET_OFFSET(&vimep->vimep_dst),
982                     (longlong_t)DVA_GET_ASIZE(&vimep->vimep_dst),
983                     counts[i]);
984         }
985         (void) printf("\n");
986
987         uint64_t obsolete_sm_object = vdev_obsolete_sm_object(vd);
988         if (obsolete_sm_object != 0) {
989                 objset_t *mos = vd->vdev_spa->spa_meta_objset;
990                 (void) printf("obsolete space map object %llu:\n",
991                     (u_longlong_t)obsolete_sm_object);
992                 ASSERT(vd->vdev_obsolete_sm != NULL);
993                 ASSERT3U(space_map_object(vd->vdev_obsolete_sm), ==,
994                     obsolete_sm_object);
995                 dump_spacemap(mos, vd->vdev_obsolete_sm);
996                 (void) printf("\n");
997         }
998 }
999
1000 static void
1001 dump_metaslabs(spa_t *spa)
1002 {
1003         vdev_t *vd, *rvd = spa->spa_root_vdev;
1004         uint64_t m, c = 0, children = rvd->vdev_children;
1005
1006         (void) printf("\nMetaslabs:\n");
1007
1008         if (!dump_opt['d'] && zopt_objects > 0) {
1009                 c = zopt_object[0];
1010
1011                 if (c >= children)
1012                         (void) fatal("bad vdev id: %llu", (u_longlong_t)c);
1013
1014                 if (zopt_objects > 1) {
1015                         vd = rvd->vdev_child[c];
1016                         print_vdev_metaslab_header(vd);
1017
1018                         for (m = 1; m < zopt_objects; m++) {
1019                                 if (zopt_object[m] < vd->vdev_ms_count)
1020                                         dump_metaslab(
1021                                             vd->vdev_ms[zopt_object[m]]);
1022                                 else
1023                                         (void) fprintf(stderr, "bad metaslab "
1024                                             "number %llu\n",
1025                                             (u_longlong_t)zopt_object[m]);
1026                         }
1027                         (void) printf("\n");
1028                         return;
1029                 }
1030                 children = c + 1;
1031         }
1032         for (; c < children; c++) {
1033                 vd = rvd->vdev_child[c];
1034                 print_vdev_metaslab_header(vd);
1035
1036                 print_vdev_indirect(vd);
1037
1038                 for (m = 0; m < vd->vdev_ms_count; m++)
1039                         dump_metaslab(vd->vdev_ms[m]);
1040                 (void) printf("\n");
1041         }
1042 }
1043
1044 static void
1045 dump_dde(const ddt_t *ddt, const ddt_entry_t *dde, uint64_t index)
1046 {
1047         const ddt_phys_t *ddp = dde->dde_phys;
1048         const ddt_key_t *ddk = &dde->dde_key;
1049         const char *types[4] = { "ditto", "single", "double", "triple" };
1050         char blkbuf[BP_SPRINTF_LEN];
1051         blkptr_t blk;
1052
1053         for (int p = 0; p < DDT_PHYS_TYPES; p++, ddp++) {
1054                 if (ddp->ddp_phys_birth == 0)
1055                         continue;
1056                 ddt_bp_create(ddt->ddt_checksum, ddk, ddp, &blk);
1057                 snprintf_blkptr(blkbuf, sizeof (blkbuf), &blk);
1058                 (void) printf("index %llx refcnt %llu %s %s\n",
1059                     (u_longlong_t)index, (u_longlong_t)ddp->ddp_refcnt,
1060                     types[p], blkbuf);
1061         }
1062 }
1063
1064 static void
1065 dump_dedup_ratio(const ddt_stat_t *dds)
1066 {
1067         double rL, rP, rD, D, dedup, compress, copies;
1068
1069         if (dds->dds_blocks == 0)
1070                 return;
1071
1072         rL = (double)dds->dds_ref_lsize;
1073         rP = (double)dds->dds_ref_psize;
1074         rD = (double)dds->dds_ref_dsize;
1075         D = (double)dds->dds_dsize;
1076
1077         dedup = rD / D;
1078         compress = rL / rP;
1079         copies = rD / rP;
1080
1081         (void) printf("dedup = %.2f, compress = %.2f, copies = %.2f, "
1082             "dedup * compress / copies = %.2f\n\n",
1083             dedup, compress, copies, dedup * compress / copies);
1084 }
1085
1086 static void
1087 dump_ddt(ddt_t *ddt, enum ddt_type type, enum ddt_class class)
1088 {
1089         char name[DDT_NAMELEN];
1090         ddt_entry_t dde;
1091         uint64_t walk = 0;
1092         dmu_object_info_t doi;
1093         uint64_t count, dspace, mspace;
1094         int error;
1095
1096         error = ddt_object_info(ddt, type, class, &doi);
1097
1098         if (error == ENOENT)
1099                 return;
1100         ASSERT(error == 0);
1101
1102         error = ddt_object_count(ddt, type, class, &count);
1103         ASSERT(error == 0);
1104         if (count == 0)
1105                 return;
1106
1107         dspace = doi.doi_physical_blocks_512 << 9;
1108         mspace = doi.doi_fill_count * doi.doi_data_block_size;
1109
1110         ddt_object_name(ddt, type, class, name);
1111
1112         (void) printf("%s: %llu entries, size %llu on disk, %llu in core\n",
1113             name,
1114             (u_longlong_t)count,
1115             (u_longlong_t)(dspace / count),
1116             (u_longlong_t)(mspace / count));
1117
1118         if (dump_opt['D'] < 3)
1119                 return;
1120
1121         zpool_dump_ddt(NULL, &ddt->ddt_histogram[type][class]);
1122
1123         if (dump_opt['D'] < 4)
1124                 return;
1125
1126         if (dump_opt['D'] < 5 && class == DDT_CLASS_UNIQUE)
1127                 return;
1128
1129         (void) printf("%s contents:\n\n", name);
1130
1131         while ((error = ddt_object_walk(ddt, type, class, &walk, &dde)) == 0)
1132                 dump_dde(ddt, &dde, walk);
1133
1134         ASSERT(error == ENOENT);
1135
1136         (void) printf("\n");
1137 }
1138
1139 static void
1140 dump_all_ddts(spa_t *spa)
1141 {
1142         ddt_histogram_t ddh_total;
1143         ddt_stat_t dds_total;
1144
1145         bzero(&ddh_total, sizeof (ddh_total));
1146         bzero(&dds_total, sizeof (dds_total));
1147
1148         for (enum zio_checksum c = 0; c < ZIO_CHECKSUM_FUNCTIONS; c++) {
1149                 ddt_t *ddt = spa->spa_ddt[c];
1150                 for (enum ddt_type type = 0; type < DDT_TYPES; type++) {
1151                         for (enum ddt_class class = 0; class < DDT_CLASSES;
1152                             class++) {
1153                                 dump_ddt(ddt, type, class);
1154                         }
1155                 }
1156         }
1157
1158         ddt_get_dedup_stats(spa, &dds_total);
1159
1160         if (dds_total.dds_blocks == 0) {
1161                 (void) printf("All DDTs are empty\n");
1162                 return;
1163         }
1164
1165         (void) printf("\n");
1166
1167         if (dump_opt['D'] > 1) {
1168                 (void) printf("DDT histogram (aggregated over all DDTs):\n");
1169                 ddt_get_dedup_histogram(spa, &ddh_total);
1170                 zpool_dump_ddt(&dds_total, &ddh_total);
1171         }
1172
1173         dump_dedup_ratio(&dds_total);
1174 }
1175
1176 static void
1177 dump_dtl_seg(void *arg, uint64_t start, uint64_t size)
1178 {
1179         char *prefix = arg;
1180
1181         (void) printf("%s [%llu,%llu) length %llu\n",
1182             prefix,
1183             (u_longlong_t)start,
1184             (u_longlong_t)(start + size),
1185             (u_longlong_t)(size));
1186 }
1187
1188 static void
1189 dump_dtl(vdev_t *vd, int indent)
1190 {
1191         spa_t *spa = vd->vdev_spa;
1192         boolean_t required;
1193         const char *name[DTL_TYPES] = { "missing", "partial", "scrub",
1194                 "outage" };
1195         char prefix[256];
1196
1197         spa_vdev_state_enter(spa, SCL_NONE);
1198         required = vdev_dtl_required(vd);
1199         (void) spa_vdev_state_exit(spa, NULL, 0);
1200
1201         if (indent == 0)
1202                 (void) printf("\nDirty time logs:\n\n");
1203
1204         (void) printf("\t%*s%s [%s]\n", indent, "",
1205             vd->vdev_path ? vd->vdev_path :
1206             vd->vdev_parent ? vd->vdev_ops->vdev_op_type : spa_name(spa),
1207             required ? "DTL-required" : "DTL-expendable");
1208
1209         for (int t = 0; t < DTL_TYPES; t++) {
1210                 range_tree_t *rt = vd->vdev_dtl[t];
1211                 if (range_tree_space(rt) == 0)
1212                         continue;
1213                 (void) snprintf(prefix, sizeof (prefix), "\t%*s%s",
1214                     indent + 2, "", name[t]);
1215                 range_tree_walk(rt, dump_dtl_seg, prefix);
1216                 if (dump_opt['d'] > 5 && vd->vdev_children == 0)
1217                         dump_spacemap(spa->spa_meta_objset, vd->vdev_dtl_sm);
1218         }
1219
1220         for (unsigned c = 0; c < vd->vdev_children; c++)
1221                 dump_dtl(vd->vdev_child[c], indent + 4);
1222 }
1223
1224 /* from spa_history.c: spa_history_create_obj() */
1225 #define HIS_BUF_LEN_DEF (128 << 10)
1226 #define HIS_BUF_LEN_MAX (1 << 30)
1227
1228 static void
1229 dump_history(spa_t *spa)
1230 {
1231         nvlist_t **events = NULL;
1232         char *buf = NULL;
1233         uint64_t bufsize = HIS_BUF_LEN_DEF;
1234         uint64_t resid, len, off = 0;
1235         uint_t num = 0;
1236         int error;
1237         time_t tsec;
1238         struct tm t;
1239         char tbuf[30];
1240         char internalstr[MAXPATHLEN];
1241
1242         if ((buf = malloc(bufsize)) == NULL)
1243                 (void) fprintf(stderr, "Unable to read history: "
1244                     "out of memory\n");
1245         do {
1246                 len = bufsize;
1247
1248                 if ((error = spa_history_get(spa, &off, &len, buf)) != 0) {
1249                         (void) fprintf(stderr, "Unable to read history: "
1250                             "error %d\n", error);
1251                         return;
1252                 }
1253
1254                 if (zpool_history_unpack(buf, len, &resid, &events, &num) != 0)
1255                         break;
1256                 off -= resid;
1257
1258                 /*
1259                  * If the history block is too big, double the buffer
1260                  * size and try again.
1261                  */
1262                 if (resid == len) {
1263                         free(buf);
1264                         buf = NULL;
1265
1266                         bufsize <<= 1;
1267                         if ((bufsize >= HIS_BUF_LEN_MAX) ||
1268                             ((buf = malloc(bufsize)) == NULL)) {
1269                                 (void) fprintf(stderr, "Unable to read history: "
1270                                     "out of memory\n");
1271                                 return;
1272                         }
1273                 }
1274         } while (len != 0);
1275         free(buf);
1276
1277         (void) printf("\nHistory:\n");
1278         for (unsigned i = 0; i < num; i++) {
1279                 uint64_t time, txg, ievent;
1280                 char *cmd, *intstr;
1281                 boolean_t printed = B_FALSE;
1282
1283                 if (nvlist_lookup_uint64(events[i], ZPOOL_HIST_TIME,
1284                     &time) != 0)
1285                         goto next;
1286                 if (nvlist_lookup_string(events[i], ZPOOL_HIST_CMD,
1287                     &cmd) != 0) {
1288                         if (nvlist_lookup_uint64(events[i],
1289                             ZPOOL_HIST_INT_EVENT, &ievent) != 0)
1290                                 goto next;
1291                         verify(nvlist_lookup_uint64(events[i],
1292                             ZPOOL_HIST_TXG, &txg) == 0);
1293                         verify(nvlist_lookup_string(events[i],
1294                             ZPOOL_HIST_INT_STR, &intstr) == 0);
1295                         if (ievent >= ZFS_NUM_LEGACY_HISTORY_EVENTS)
1296                                 goto next;
1297
1298                         (void) snprintf(internalstr,
1299                             sizeof (internalstr),
1300                             "[internal %s txg:%ju] %s",
1301                             zfs_history_event_names[ievent], (uintmax_t)txg,
1302                             intstr);
1303                         cmd = internalstr;
1304                 }
1305                 tsec = time;
1306                 (void) localtime_r(&tsec, &t);
1307                 (void) strftime(tbuf, sizeof (tbuf), "%F.%T", &t);
1308                 (void) printf("%s %s\n", tbuf, cmd);
1309                 printed = B_TRUE;
1310
1311 next:
1312                 if (dump_opt['h'] > 1) {
1313                         if (!printed)
1314                                 (void) printf("unrecognized record:\n");
1315                         dump_nvlist(events[i], 2);
1316                 }
1317         }
1318 }
1319
1320 /*ARGSUSED*/
1321 static void
1322 dump_dnode(objset_t *os, uint64_t object, void *data, size_t size)
1323 {
1324 }
1325
1326 static uint64_t
1327 blkid2offset(const dnode_phys_t *dnp, const blkptr_t *bp,
1328     const zbookmark_phys_t *zb)
1329 {
1330         if (dnp == NULL) {
1331                 ASSERT(zb->zb_level < 0);
1332                 if (zb->zb_object == 0)
1333                         return (zb->zb_blkid);
1334                 return (zb->zb_blkid * BP_GET_LSIZE(bp));
1335         }
1336
1337         ASSERT(zb->zb_level >= 0);
1338
1339         return ((zb->zb_blkid <<
1340             (zb->zb_level * (dnp->dn_indblkshift - SPA_BLKPTRSHIFT))) *
1341             dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT);
1342 }
1343
1344 static void
1345 snprintf_blkptr_compact(char *blkbuf, size_t buflen, const blkptr_t *bp)
1346 {
1347         const dva_t *dva = bp->blk_dva;
1348         int ndvas = dump_opt['d'] > 5 ? BP_GET_NDVAS(bp) : 1;
1349
1350         if (dump_opt['b'] >= 6) {
1351                 snprintf_blkptr(blkbuf, buflen, bp);
1352                 return;
1353         }
1354
1355         if (BP_IS_EMBEDDED(bp)) {
1356                 (void) sprintf(blkbuf,
1357                     "EMBEDDED et=%u %llxL/%llxP B=%llu",
1358                     (int)BPE_GET_ETYPE(bp),
1359                     (u_longlong_t)BPE_GET_LSIZE(bp),
1360                     (u_longlong_t)BPE_GET_PSIZE(bp),
1361                     (u_longlong_t)bp->blk_birth);
1362                 return;
1363         }
1364
1365         blkbuf[0] = '\0';
1366         for (int i = 0; i < ndvas; i++)
1367                 (void) snprintf(blkbuf + strlen(blkbuf),
1368                     buflen - strlen(blkbuf), "%llu:%llx:%llx ",
1369                     (u_longlong_t)DVA_GET_VDEV(&dva[i]),
1370                     (u_longlong_t)DVA_GET_OFFSET(&dva[i]),
1371                     (u_longlong_t)DVA_GET_ASIZE(&dva[i]));
1372
1373         if (BP_IS_HOLE(bp)) {
1374                 (void) snprintf(blkbuf + strlen(blkbuf),
1375                     buflen - strlen(blkbuf),
1376                     "%llxL B=%llu",
1377                     (u_longlong_t)BP_GET_LSIZE(bp),
1378                     (u_longlong_t)bp->blk_birth);
1379         } else {
1380                 (void) snprintf(blkbuf + strlen(blkbuf),
1381                     buflen - strlen(blkbuf),
1382                     "%llxL/%llxP F=%llu B=%llu/%llu",
1383                     (u_longlong_t)BP_GET_LSIZE(bp),
1384                     (u_longlong_t)BP_GET_PSIZE(bp),
1385                     (u_longlong_t)BP_GET_FILL(bp),
1386                     (u_longlong_t)bp->blk_birth,
1387                     (u_longlong_t)BP_PHYSICAL_BIRTH(bp));
1388         }
1389 }
1390
1391 static void
1392 print_indirect(blkptr_t *bp, const zbookmark_phys_t *zb,
1393     const dnode_phys_t *dnp)
1394 {
1395         char blkbuf[BP_SPRINTF_LEN];
1396         int l;
1397
1398         if (!BP_IS_EMBEDDED(bp)) {
1399                 ASSERT3U(BP_GET_TYPE(bp), ==, dnp->dn_type);
1400                 ASSERT3U(BP_GET_LEVEL(bp), ==, zb->zb_level);
1401         }
1402
1403         (void) printf("%16llx ", (u_longlong_t)blkid2offset(dnp, bp, zb));
1404
1405         ASSERT(zb->zb_level >= 0);
1406
1407         for (l = dnp->dn_nlevels - 1; l >= -1; l--) {
1408                 if (l == zb->zb_level) {
1409                         (void) printf("L%llx", (u_longlong_t)zb->zb_level);
1410                 } else {
1411                         (void) printf(" ");
1412                 }
1413         }
1414
1415         snprintf_blkptr_compact(blkbuf, sizeof (blkbuf), bp);
1416         (void) printf("%s\n", blkbuf);
1417 }
1418
1419 static int
1420 visit_indirect(spa_t *spa, const dnode_phys_t *dnp,
1421     blkptr_t *bp, const zbookmark_phys_t *zb)
1422 {
1423         int err = 0;
1424
1425         if (bp->blk_birth == 0)
1426                 return (0);
1427
1428         print_indirect(bp, zb, dnp);
1429
1430         if (BP_GET_LEVEL(bp) > 0 && !BP_IS_HOLE(bp)) {
1431                 arc_flags_t flags = ARC_FLAG_WAIT;
1432                 int i;
1433                 blkptr_t *cbp;
1434                 int epb = BP_GET_LSIZE(bp) >> SPA_BLKPTRSHIFT;
1435                 arc_buf_t *buf;
1436                 uint64_t fill = 0;
1437
1438                 err = arc_read(NULL, spa, bp, arc_getbuf_func, &buf,
1439                     ZIO_PRIORITY_ASYNC_READ, ZIO_FLAG_CANFAIL, &flags, zb);
1440                 if (err)
1441                         return (err);
1442                 ASSERT(buf->b_data);
1443
1444                 /* recursively visit blocks below this */
1445                 cbp = buf->b_data;
1446                 for (i = 0; i < epb; i++, cbp++) {
1447                         zbookmark_phys_t czb;
1448
1449                         SET_BOOKMARK(&czb, zb->zb_objset, zb->zb_object,
1450                             zb->zb_level - 1,
1451                             zb->zb_blkid * epb + i);
1452                         err = visit_indirect(spa, dnp, cbp, &czb);
1453                         if (err)
1454                                 break;
1455                         fill += BP_GET_FILL(cbp);
1456                 }
1457                 if (!err)
1458                         ASSERT3U(fill, ==, BP_GET_FILL(bp));
1459                 arc_buf_destroy(buf, &buf);
1460         }
1461
1462         return (err);
1463 }
1464
1465 /*ARGSUSED*/
1466 static void
1467 dump_indirect(dnode_t *dn)
1468 {
1469         dnode_phys_t *dnp = dn->dn_phys;
1470         int j;
1471         zbookmark_phys_t czb;
1472
1473         (void) printf("Indirect blocks:\n");
1474
1475         SET_BOOKMARK(&czb, dmu_objset_id(dn->dn_objset),
1476             dn->dn_object, dnp->dn_nlevels - 1, 0);
1477         for (j = 0; j < dnp->dn_nblkptr; j++) {
1478                 czb.zb_blkid = j;
1479                 (void) visit_indirect(dmu_objset_spa(dn->dn_objset), dnp,
1480                     &dnp->dn_blkptr[j], &czb);
1481         }
1482
1483         (void) printf("\n");
1484 }
1485
1486 /*ARGSUSED*/
1487 static void
1488 dump_dsl_dir(objset_t *os, uint64_t object, void *data, size_t size)
1489 {
1490         dsl_dir_phys_t *dd = data;
1491         time_t crtime;
1492         char nice[32];
1493
1494         /* make sure nicenum has enough space */
1495         CTASSERT(sizeof (nice) >= NN_NUMBUF_SZ);
1496
1497         if (dd == NULL)
1498                 return;
1499
1500         ASSERT3U(size, >=, sizeof (dsl_dir_phys_t));
1501
1502         crtime = dd->dd_creation_time;
1503         (void) printf("\t\tcreation_time = %s", ctime(&crtime));
1504         (void) printf("\t\thead_dataset_obj = %llu\n",
1505             (u_longlong_t)dd->dd_head_dataset_obj);
1506         (void) printf("\t\tparent_dir_obj = %llu\n",
1507             (u_longlong_t)dd->dd_parent_obj);
1508         (void) printf("\t\torigin_obj = %llu\n",
1509             (u_longlong_t)dd->dd_origin_obj);
1510         (void) printf("\t\tchild_dir_zapobj = %llu\n",
1511             (u_longlong_t)dd->dd_child_dir_zapobj);
1512         zdb_nicenum(dd->dd_used_bytes, nice, sizeof (nice));
1513         (void) printf("\t\tused_bytes = %s\n", nice);
1514         zdb_nicenum(dd->dd_compressed_bytes, nice, sizeof (nice));
1515         (void) printf("\t\tcompressed_bytes = %s\n", nice);
1516         zdb_nicenum(dd->dd_uncompressed_bytes, nice, sizeof (nice));
1517         (void) printf("\t\tuncompressed_bytes = %s\n", nice);
1518         zdb_nicenum(dd->dd_quota, nice, sizeof (nice));
1519         (void) printf("\t\tquota = %s\n", nice);
1520         zdb_nicenum(dd->dd_reserved, nice, sizeof (nice));
1521         (void) printf("\t\treserved = %s\n", nice);
1522         (void) printf("\t\tprops_zapobj = %llu\n",
1523             (u_longlong_t)dd->dd_props_zapobj);
1524         (void) printf("\t\tdeleg_zapobj = %llu\n",
1525             (u_longlong_t)dd->dd_deleg_zapobj);
1526         (void) printf("\t\tflags = %llx\n",
1527             (u_longlong_t)dd->dd_flags);
1528
1529 #define DO(which) \
1530         zdb_nicenum(dd->dd_used_breakdown[DD_USED_ ## which], nice, \
1531             sizeof (nice)); \
1532         (void) printf("\t\tused_breakdown[" #which "] = %s\n", nice)
1533         DO(HEAD);
1534         DO(SNAP);
1535         DO(CHILD);
1536         DO(CHILD_RSRV);
1537         DO(REFRSRV);
1538 #undef DO
1539 }
1540
1541 /*ARGSUSED*/
1542 static void
1543 dump_dsl_dataset(objset_t *os, uint64_t object, void *data, size_t size)
1544 {
1545         dsl_dataset_phys_t *ds = data;
1546         time_t crtime;
1547         char used[32], compressed[32], uncompressed[32], unique[32];
1548         char blkbuf[BP_SPRINTF_LEN];
1549
1550         /* make sure nicenum has enough space */
1551         CTASSERT(sizeof (used) >= NN_NUMBUF_SZ);
1552         CTASSERT(sizeof (compressed) >= NN_NUMBUF_SZ);
1553         CTASSERT(sizeof (uncompressed) >= NN_NUMBUF_SZ);
1554         CTASSERT(sizeof (unique) >= NN_NUMBUF_SZ);
1555
1556         if (ds == NULL)
1557                 return;
1558
1559         ASSERT(size == sizeof (*ds));
1560         crtime = ds->ds_creation_time;
1561         zdb_nicenum(ds->ds_referenced_bytes, used, sizeof (used));
1562         zdb_nicenum(ds->ds_compressed_bytes, compressed, sizeof (compressed));
1563         zdb_nicenum(ds->ds_uncompressed_bytes, uncompressed,
1564             sizeof (uncompressed));
1565         zdb_nicenum(ds->ds_unique_bytes, unique, sizeof (unique));
1566         snprintf_blkptr(blkbuf, sizeof (blkbuf), &ds->ds_bp);
1567
1568         (void) printf("\t\tdir_obj = %llu\n",
1569             (u_longlong_t)ds->ds_dir_obj);
1570         (void) printf("\t\tprev_snap_obj = %llu\n",
1571             (u_longlong_t)ds->ds_prev_snap_obj);
1572         (void) printf("\t\tprev_snap_txg = %llu\n",
1573             (u_longlong_t)ds->ds_prev_snap_txg);
1574         (void) printf("\t\tnext_snap_obj = %llu\n",
1575             (u_longlong_t)ds->ds_next_snap_obj);
1576         (void) printf("\t\tsnapnames_zapobj = %llu\n",
1577             (u_longlong_t)ds->ds_snapnames_zapobj);
1578         (void) printf("\t\tnum_children = %llu\n",
1579             (u_longlong_t)ds->ds_num_children);
1580         (void) printf("\t\tuserrefs_obj = %llu\n",
1581             (u_longlong_t)ds->ds_userrefs_obj);
1582         (void) printf("\t\tcreation_time = %s", ctime(&crtime));
1583         (void) printf("\t\tcreation_txg = %llu\n",
1584             (u_longlong_t)ds->ds_creation_txg);
1585         (void) printf("\t\tdeadlist_obj = %llu\n",
1586             (u_longlong_t)ds->ds_deadlist_obj);
1587         (void) printf("\t\tused_bytes = %s\n", used);
1588         (void) printf("\t\tcompressed_bytes = %s\n", compressed);
1589         (void) printf("\t\tuncompressed_bytes = %s\n", uncompressed);
1590         (void) printf("\t\tunique = %s\n", unique);
1591         (void) printf("\t\tfsid_guid = %llu\n",
1592             (u_longlong_t)ds->ds_fsid_guid);
1593         (void) printf("\t\tguid = %llu\n",
1594             (u_longlong_t)ds->ds_guid);
1595         (void) printf("\t\tflags = %llx\n",
1596             (u_longlong_t)ds->ds_flags);
1597         (void) printf("\t\tnext_clones_obj = %llu\n",
1598             (u_longlong_t)ds->ds_next_clones_obj);
1599         (void) printf("\t\tprops_obj = %llu\n",
1600             (u_longlong_t)ds->ds_props_obj);
1601         (void) printf("\t\tbp = %s\n", blkbuf);
1602 }
1603
1604 /* ARGSUSED */
1605 static int
1606 dump_bptree_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
1607 {
1608         char blkbuf[BP_SPRINTF_LEN];
1609
1610         if (bp->blk_birth != 0) {
1611                 snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
1612                 (void) printf("\t%s\n", blkbuf);
1613         }
1614         return (0);
1615 }
1616
1617 static void
1618 dump_bptree(objset_t *os, uint64_t obj, const char *name)
1619 {
1620         char bytes[32];
1621         bptree_phys_t *bt;
1622         dmu_buf_t *db;
1623
1624         /* make sure nicenum has enough space */
1625         CTASSERT(sizeof (bytes) >= NN_NUMBUF_SZ);
1626
1627         if (dump_opt['d'] < 3)
1628                 return;
1629
1630         VERIFY3U(0, ==, dmu_bonus_hold(os, obj, FTAG, &db));
1631         bt = db->db_data;
1632         zdb_nicenum(bt->bt_bytes, bytes, sizeof (bytes));
1633         (void) printf("\n    %s: %llu datasets, %s\n",
1634             name, (unsigned long long)(bt->bt_end - bt->bt_begin), bytes);
1635         dmu_buf_rele(db, FTAG);
1636
1637         if (dump_opt['d'] < 5)
1638                 return;
1639
1640         (void) printf("\n");
1641
1642         (void) bptree_iterate(os, obj, B_FALSE, dump_bptree_cb, NULL, NULL);
1643 }
1644
1645 /* ARGSUSED */
1646 static int
1647 dump_bpobj_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
1648 {
1649         char blkbuf[BP_SPRINTF_LEN];
1650
1651         ASSERT(bp->blk_birth != 0);
1652         snprintf_blkptr_compact(blkbuf, sizeof (blkbuf), bp);
1653         (void) printf("\t%s\n", blkbuf);
1654         return (0);
1655 }
1656
1657 static void
1658 dump_full_bpobj(bpobj_t *bpo, const char *name, int indent)
1659 {
1660         char bytes[32];
1661         char comp[32];
1662         char uncomp[32];
1663
1664         /* make sure nicenum has enough space */
1665         CTASSERT(sizeof (bytes) >= NN_NUMBUF_SZ);
1666         CTASSERT(sizeof (comp) >= NN_NUMBUF_SZ);
1667         CTASSERT(sizeof (uncomp) >= NN_NUMBUF_SZ);
1668
1669         if (dump_opt['d'] < 3)
1670                 return;
1671
1672         zdb_nicenum(bpo->bpo_phys->bpo_bytes, bytes, sizeof (bytes));
1673         if (bpo->bpo_havesubobj && bpo->bpo_phys->bpo_subobjs != 0) {
1674                 zdb_nicenum(bpo->bpo_phys->bpo_comp, comp, sizeof (comp));
1675                 zdb_nicenum(bpo->bpo_phys->bpo_uncomp, uncomp, sizeof (uncomp));
1676                 (void) printf("    %*s: object %llu, %llu local blkptrs, "
1677                     "%llu subobjs in object %llu, %s (%s/%s comp)\n",
1678                     indent * 8, name,
1679                     (u_longlong_t)bpo->bpo_object,
1680                     (u_longlong_t)bpo->bpo_phys->bpo_num_blkptrs,
1681                     (u_longlong_t)bpo->bpo_phys->bpo_num_subobjs,
1682                     (u_longlong_t)bpo->bpo_phys->bpo_subobjs,
1683                     bytes, comp, uncomp);
1684
1685                 for (uint64_t i = 0; i < bpo->bpo_phys->bpo_num_subobjs; i++) {
1686                         uint64_t subobj;
1687                         bpobj_t subbpo;
1688                         int error;
1689                         VERIFY0(dmu_read(bpo->bpo_os,
1690                             bpo->bpo_phys->bpo_subobjs,
1691                             i * sizeof (subobj), sizeof (subobj), &subobj, 0));
1692                         error = bpobj_open(&subbpo, bpo->bpo_os, subobj);
1693                         if (error != 0) {
1694                                 (void) printf("ERROR %u while trying to open "
1695                                     "subobj id %llu\n",
1696                                     error, (u_longlong_t)subobj);
1697                                 continue;
1698                         }
1699                         dump_full_bpobj(&subbpo, "subobj", indent + 1);
1700                         bpobj_close(&subbpo);
1701                 }
1702         } else {
1703                 (void) printf("    %*s: object %llu, %llu blkptrs, %s\n",
1704                     indent * 8, name,
1705                     (u_longlong_t)bpo->bpo_object,
1706                     (u_longlong_t)bpo->bpo_phys->bpo_num_blkptrs,
1707                     bytes);
1708         }
1709
1710         if (dump_opt['d'] < 5)
1711                 return;
1712
1713
1714         if (indent == 0) {
1715                 (void) bpobj_iterate_nofree(bpo, dump_bpobj_cb, NULL, NULL);
1716                 (void) printf("\n");
1717         }
1718 }
1719
1720 static void
1721 dump_deadlist(dsl_deadlist_t *dl)
1722 {
1723         dsl_deadlist_entry_t *dle;
1724         uint64_t unused;
1725         char bytes[32];
1726         char comp[32];
1727         char uncomp[32];
1728
1729         /* make sure nicenum has enough space */
1730         CTASSERT(sizeof (bytes) >= NN_NUMBUF_SZ);
1731         CTASSERT(sizeof (comp) >= NN_NUMBUF_SZ);
1732         CTASSERT(sizeof (uncomp) >= NN_NUMBUF_SZ);
1733
1734         if (dump_opt['d'] < 3)
1735                 return;
1736
1737         if (dl->dl_oldfmt) {
1738                 dump_full_bpobj(&dl->dl_bpobj, "old-format deadlist", 0);
1739                 return;
1740         }
1741
1742         zdb_nicenum(dl->dl_phys->dl_used, bytes, sizeof (bytes));
1743         zdb_nicenum(dl->dl_phys->dl_comp, comp, sizeof (comp));
1744         zdb_nicenum(dl->dl_phys->dl_uncomp, uncomp, sizeof (uncomp));
1745         (void) printf("\n    Deadlist: %s (%s/%s comp)\n",
1746             bytes, comp, uncomp);
1747
1748         if (dump_opt['d'] < 4)
1749                 return;
1750
1751         (void) printf("\n");
1752
1753         /* force the tree to be loaded */
1754         dsl_deadlist_space_range(dl, 0, UINT64_MAX, &unused, &unused, &unused);
1755
1756         for (dle = avl_first(&dl->dl_tree); dle;
1757             dle = AVL_NEXT(&dl->dl_tree, dle)) {
1758                 if (dump_opt['d'] >= 5) {
1759                         char buf[128];
1760                         (void) snprintf(buf, sizeof (buf),
1761                             "mintxg %llu -> obj %llu",
1762                             (longlong_t)dle->dle_mintxg,
1763                             (longlong_t)dle->dle_bpobj.bpo_object);
1764                         dump_full_bpobj(&dle->dle_bpobj, buf, 0);
1765                 } else {
1766                         (void) printf("mintxg %llu -> obj %llu\n",
1767                             (longlong_t)dle->dle_mintxg,
1768                             (longlong_t)dle->dle_bpobj.bpo_object);
1769                 }
1770         }
1771 }
1772
1773 static avl_tree_t idx_tree;
1774 static avl_tree_t domain_tree;
1775 static boolean_t fuid_table_loaded;
1776 static objset_t *sa_os = NULL;
1777 static sa_attr_type_t *sa_attr_table = NULL;
1778
1779 static int
1780 open_objset(const char *path, dmu_objset_type_t type, void *tag, objset_t **osp)
1781 {
1782         int err;
1783         uint64_t sa_attrs = 0;
1784         uint64_t version = 0;
1785
1786         VERIFY3P(sa_os, ==, NULL);
1787         err = dmu_objset_own(path, type, B_TRUE, tag, osp);
1788         if (err != 0) {
1789                 (void) fprintf(stderr, "failed to own dataset '%s': %s\n", path,
1790                     strerror(err));
1791                 return (err);
1792         }
1793
1794         if (dmu_objset_type(*osp) == DMU_OST_ZFS) {
1795                 (void) zap_lookup(*osp, MASTER_NODE_OBJ, ZPL_VERSION_STR,
1796                     8, 1, &version);
1797                 if (version >= ZPL_VERSION_SA) {
1798                         (void) zap_lookup(*osp, MASTER_NODE_OBJ, ZFS_SA_ATTRS,
1799                             8, 1, &sa_attrs);
1800                 }
1801                 err = sa_setup(*osp, sa_attrs, zfs_attr_table, ZPL_END,
1802                     &sa_attr_table);
1803                 if (err != 0) {
1804                         (void) fprintf(stderr, "sa_setup failed: %s\n",
1805                             strerror(err));
1806                         dmu_objset_disown(*osp, tag);
1807                         *osp = NULL;
1808                 }
1809         }
1810         sa_os = *osp;
1811
1812         return (0);
1813 }
1814
1815 static void
1816 close_objset(objset_t *os, void *tag)
1817 {
1818         VERIFY3P(os, ==, sa_os);
1819         if (os->os_sa != NULL)
1820                 sa_tear_down(os);
1821         dmu_objset_disown(os, tag);
1822         sa_attr_table = NULL;
1823         sa_os = NULL;
1824 }
1825
1826 static void
1827 fuid_table_destroy()
1828 {
1829         if (fuid_table_loaded) {
1830                 zfs_fuid_table_destroy(&idx_tree, &domain_tree);
1831                 fuid_table_loaded = B_FALSE;
1832         }
1833 }
1834
1835 /*
1836  * print uid or gid information.
1837  * For normal POSIX id just the id is printed in decimal format.
1838  * For CIFS files with FUID the fuid is printed in hex followed by
1839  * the domain-rid string.
1840  */
1841 static void
1842 print_idstr(uint64_t id, const char *id_type)
1843 {
1844         if (FUID_INDEX(id)) {
1845                 char *domain;
1846
1847                 domain = zfs_fuid_idx_domain(&idx_tree, FUID_INDEX(id));
1848                 (void) printf("\t%s     %llx [%s-%d]\n", id_type,
1849                     (u_longlong_t)id, domain, (int)FUID_RID(id));
1850         } else {
1851                 (void) printf("\t%s     %llu\n", id_type, (u_longlong_t)id);
1852         }
1853
1854 }
1855
1856 static void
1857 dump_uidgid(objset_t *os, uint64_t uid, uint64_t gid)
1858 {
1859         uint32_t uid_idx, gid_idx;
1860
1861         uid_idx = FUID_INDEX(uid);
1862         gid_idx = FUID_INDEX(gid);
1863
1864         /* Load domain table, if not already loaded */
1865         if (!fuid_table_loaded && (uid_idx || gid_idx)) {
1866                 uint64_t fuid_obj;
1867
1868                 /* first find the fuid object.  It lives in the master node */
1869                 VERIFY(zap_lookup(os, MASTER_NODE_OBJ, ZFS_FUID_TABLES,
1870                     8, 1, &fuid_obj) == 0);
1871                 zfs_fuid_avl_tree_create(&idx_tree, &domain_tree);
1872                 (void) zfs_fuid_table_load(os, fuid_obj,
1873                     &idx_tree, &domain_tree);
1874                 fuid_table_loaded = B_TRUE;
1875         }
1876
1877         print_idstr(uid, "uid");
1878         print_idstr(gid, "gid");
1879 }
1880
1881 /*ARGSUSED*/
1882 static void
1883 dump_znode(objset_t *os, uint64_t object, void *data, size_t size)
1884 {
1885         char path[MAXPATHLEN * 2];      /* allow for xattr and failure prefix */
1886         sa_handle_t *hdl;
1887         uint64_t xattr, rdev, gen;
1888         uint64_t uid, gid, mode, fsize, parent, links;
1889         uint64_t pflags;
1890         uint64_t acctm[2], modtm[2], chgtm[2], crtm[2];
1891         time_t z_crtime, z_atime, z_mtime, z_ctime;
1892         sa_bulk_attr_t bulk[12];
1893         int idx = 0;
1894         int error;
1895
1896         VERIFY3P(os, ==, sa_os);
1897         if (sa_handle_get(os, object, NULL, SA_HDL_PRIVATE, &hdl)) {
1898                 (void) printf("Failed to get handle for SA znode\n");
1899                 return;
1900         }
1901
1902         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_UID], NULL, &uid, 8);
1903         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_GID], NULL, &gid, 8);
1904         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_LINKS], NULL,
1905             &links, 8);
1906         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_GEN], NULL, &gen, 8);
1907         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_MODE], NULL,
1908             &mode, 8);
1909         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_PARENT],
1910             NULL, &parent, 8);
1911         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_SIZE], NULL,
1912             &fsize, 8);
1913         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_ATIME], NULL,
1914             acctm, 16);
1915         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_MTIME], NULL,
1916             modtm, 16);
1917         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_CRTIME], NULL,
1918             crtm, 16);
1919         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_CTIME], NULL,
1920             chgtm, 16);
1921         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_FLAGS], NULL,
1922             &pflags, 8);
1923
1924         if (sa_bulk_lookup(hdl, bulk, idx)) {
1925                 (void) sa_handle_destroy(hdl);
1926                 return;
1927         }
1928
1929         z_crtime = (time_t)crtm[0];
1930         z_atime = (time_t)acctm[0];
1931         z_mtime = (time_t)modtm[0];
1932         z_ctime = (time_t)chgtm[0];
1933
1934         if (dump_opt['d'] > 4) {
1935                 error = zfs_obj_to_path(os, object, path, sizeof (path));
1936                 if (error != 0) {
1937                         (void) snprintf(path, sizeof (path),
1938                             "\?\?\?<object#%llu>", (u_longlong_t)object);
1939                 }
1940                 (void) printf("\tpath   %s\n", path);
1941         }
1942         dump_uidgid(os, uid, gid);
1943         (void) printf("\tatime  %s", ctime(&z_atime));
1944         (void) printf("\tmtime  %s", ctime(&z_mtime));
1945         (void) printf("\tctime  %s", ctime(&z_ctime));
1946         (void) printf("\tcrtime %s", ctime(&z_crtime));
1947         (void) printf("\tgen    %llu\n", (u_longlong_t)gen);
1948         (void) printf("\tmode   %llo\n", (u_longlong_t)mode);
1949         (void) printf("\tsize   %llu\n", (u_longlong_t)fsize);
1950         (void) printf("\tparent %llu\n", (u_longlong_t)parent);
1951         (void) printf("\tlinks  %llu\n", (u_longlong_t)links);
1952         (void) printf("\tpflags %llx\n", (u_longlong_t)pflags);
1953         if (sa_lookup(hdl, sa_attr_table[ZPL_XATTR], &xattr,
1954             sizeof (uint64_t)) == 0)
1955                 (void) printf("\txattr  %llu\n", (u_longlong_t)xattr);
1956         if (sa_lookup(hdl, sa_attr_table[ZPL_RDEV], &rdev,
1957             sizeof (uint64_t)) == 0)
1958                 (void) printf("\trdev   0x%016llx\n", (u_longlong_t)rdev);
1959         sa_handle_destroy(hdl);
1960 }
1961
1962 /*ARGSUSED*/
1963 static void
1964 dump_acl(objset_t *os, uint64_t object, void *data, size_t size)
1965 {
1966 }
1967
1968 /*ARGSUSED*/
1969 static void
1970 dump_dmu_objset(objset_t *os, uint64_t object, void *data, size_t size)
1971 {
1972 }
1973
1974 static object_viewer_t *object_viewer[DMU_OT_NUMTYPES + 1] = {
1975         dump_none,              /* unallocated                  */
1976         dump_zap,               /* object directory             */
1977         dump_uint64,            /* object array                 */
1978         dump_none,              /* packed nvlist                */
1979         dump_packed_nvlist,     /* packed nvlist size           */
1980         dump_none,              /* bpobj                        */
1981         dump_bpobj,             /* bpobj header                 */
1982         dump_none,              /* SPA space map header         */
1983         dump_none,              /* SPA space map                */
1984         dump_none,              /* ZIL intent log               */
1985         dump_dnode,             /* DMU dnode                    */
1986         dump_dmu_objset,        /* DMU objset                   */
1987         dump_dsl_dir,           /* DSL directory                */
1988         dump_zap,               /* DSL directory child map      */
1989         dump_zap,               /* DSL dataset snap map         */
1990         dump_zap,               /* DSL props                    */
1991         dump_dsl_dataset,       /* DSL dataset                  */
1992         dump_znode,             /* ZFS znode                    */
1993         dump_acl,               /* ZFS V0 ACL                   */
1994         dump_uint8,             /* ZFS plain file               */
1995         dump_zpldir,            /* ZFS directory                */
1996         dump_zap,               /* ZFS master node              */
1997         dump_zap,               /* ZFS delete queue             */
1998         dump_uint8,             /* zvol object                  */
1999         dump_zap,               /* zvol prop                    */
2000         dump_uint8,             /* other uint8[]                */
2001         dump_uint64,            /* other uint64[]               */
2002         dump_zap,               /* other ZAP                    */
2003         dump_zap,               /* persistent error log         */
2004         dump_uint8,             /* SPA history                  */
2005         dump_history_offsets,   /* SPA history offsets          */
2006         dump_zap,               /* Pool properties              */
2007         dump_zap,               /* DSL permissions              */
2008         dump_acl,               /* ZFS ACL                      */
2009         dump_uint8,             /* ZFS SYSACL                   */
2010         dump_none,              /* FUID nvlist                  */
2011         dump_packed_nvlist,     /* FUID nvlist size             */
2012         dump_zap,               /* DSL dataset next clones      */
2013         dump_zap,               /* DSL scrub queue              */
2014         dump_zap,               /* ZFS user/group used          */
2015         dump_zap,               /* ZFS user/group quota         */
2016         dump_zap,               /* snapshot refcount tags       */
2017         dump_ddt_zap,           /* DDT ZAP object               */
2018         dump_zap,               /* DDT statistics               */
2019         dump_znode,             /* SA object                    */
2020         dump_zap,               /* SA Master Node               */
2021         dump_sa_attrs,          /* SA attribute registration    */
2022         dump_sa_layouts,        /* SA attribute layouts         */
2023         dump_zap,               /* DSL scrub translations       */
2024         dump_none,              /* fake dedup BP                */
2025         dump_zap,               /* deadlist                     */
2026         dump_none,              /* deadlist hdr                 */
2027         dump_zap,               /* dsl clones                   */
2028         dump_bpobj_subobjs,     /* bpobj subobjs                */
2029         dump_unknown,           /* Unknown type, must be last   */
2030 };
2031
2032 static void
2033 dump_object(objset_t *os, uint64_t object, int verbosity, int *print_header)
2034 {
2035         dmu_buf_t *db = NULL;
2036         dmu_object_info_t doi;
2037         dnode_t *dn;
2038         void *bonus = NULL;
2039         size_t bsize = 0;
2040         char iblk[32], dblk[32], lsize[32], asize[32], fill[32];
2041         char bonus_size[32];
2042         char aux[50];
2043         int error;
2044
2045         /* make sure nicenum has enough space */
2046         CTASSERT(sizeof (iblk) >= NN_NUMBUF_SZ);
2047         CTASSERT(sizeof (dblk) >= NN_NUMBUF_SZ);
2048         CTASSERT(sizeof (lsize) >= NN_NUMBUF_SZ);
2049         CTASSERT(sizeof (asize) >= NN_NUMBUF_SZ);
2050         CTASSERT(sizeof (bonus_size) >= NN_NUMBUF_SZ);
2051
2052         if (*print_header) {
2053                 (void) printf("\n%10s  %3s  %5s  %5s  %5s  %5s  %6s  %s\n",
2054                     "Object", "lvl", "iblk", "dblk", "dsize", "lsize",
2055                     "%full", "type");
2056                 *print_header = 0;
2057         }
2058
2059         if (object == 0) {
2060                 dn = DMU_META_DNODE(os);
2061         } else {
2062                 error = dmu_bonus_hold(os, object, FTAG, &db);
2063                 if (error)
2064                         fatal("dmu_bonus_hold(%llu) failed, errno %u",
2065                             object, error);
2066                 bonus = db->db_data;
2067                 bsize = db->db_size;
2068                 dn = DB_DNODE((dmu_buf_impl_t *)db);
2069         }
2070         dmu_object_info_from_dnode(dn, &doi);
2071
2072         zdb_nicenum(doi.doi_metadata_block_size, iblk, sizeof (iblk));
2073         zdb_nicenum(doi.doi_data_block_size, dblk, sizeof (dblk));
2074         zdb_nicenum(doi.doi_max_offset, lsize, sizeof (lsize));
2075         zdb_nicenum(doi.doi_physical_blocks_512 << 9, asize, sizeof (asize));
2076         zdb_nicenum(doi.doi_bonus_size, bonus_size, sizeof (bonus_size));
2077         (void) sprintf(fill, "%6.2f", 100.0 * doi.doi_fill_count *
2078             doi.doi_data_block_size / (object == 0 ? DNODES_PER_BLOCK : 1) /
2079             doi.doi_max_offset);
2080
2081         aux[0] = '\0';
2082
2083         if (doi.doi_checksum != ZIO_CHECKSUM_INHERIT || verbosity >= 6) {
2084                 (void) snprintf(aux + strlen(aux), sizeof (aux), " (K=%s)",
2085                     ZDB_CHECKSUM_NAME(doi.doi_checksum));
2086         }
2087
2088         if (doi.doi_compress != ZIO_COMPRESS_INHERIT || verbosity >= 6) {
2089                 (void) snprintf(aux + strlen(aux), sizeof (aux), " (Z=%s)",
2090                     ZDB_COMPRESS_NAME(doi.doi_compress));
2091         }
2092
2093         (void) printf("%10lld  %3u  %5s  %5s  %5s  %5s  %6s  %s%s\n",
2094             (u_longlong_t)object, doi.doi_indirection, iblk, dblk,
2095             asize, lsize, fill, ZDB_OT_NAME(doi.doi_type), aux);
2096
2097         if (doi.doi_bonus_type != DMU_OT_NONE && verbosity > 3) {
2098                 (void) printf("%10s  %3s  %5s  %5s  %5s  %5s  %6s  %s\n",
2099                     "", "", "", "", "", bonus_size, "bonus",
2100                     ZDB_OT_NAME(doi.doi_bonus_type));
2101         }
2102
2103         if (verbosity >= 4) {
2104                 (void) printf("\tdnode flags: %s%s%s\n",
2105                     (dn->dn_phys->dn_flags & DNODE_FLAG_USED_BYTES) ?
2106                     "USED_BYTES " : "",
2107                     (dn->dn_phys->dn_flags & DNODE_FLAG_USERUSED_ACCOUNTED) ?
2108                     "USERUSED_ACCOUNTED " : "",
2109                     (dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR) ?
2110                     "SPILL_BLKPTR" : "");
2111                 (void) printf("\tdnode maxblkid: %llu\n",
2112                     (longlong_t)dn->dn_phys->dn_maxblkid);
2113
2114                 object_viewer[ZDB_OT_TYPE(doi.doi_bonus_type)](os, object,
2115                     bonus, bsize);
2116                 object_viewer[ZDB_OT_TYPE(doi.doi_type)](os, object, NULL, 0);
2117                 *print_header = 1;
2118         }
2119
2120         if (verbosity >= 5)
2121                 dump_indirect(dn);
2122
2123         if (verbosity >= 5) {
2124                 /*
2125                  * Report the list of segments that comprise the object.
2126                  */
2127                 uint64_t start = 0;
2128                 uint64_t end;
2129                 uint64_t blkfill = 1;
2130                 int minlvl = 1;
2131
2132                 if (dn->dn_type == DMU_OT_DNODE) {
2133                         minlvl = 0;
2134                         blkfill = DNODES_PER_BLOCK;
2135                 }
2136
2137                 for (;;) {
2138                         char segsize[32];
2139                         /* make sure nicenum has enough space */
2140                         CTASSERT(sizeof (segsize) >= NN_NUMBUF_SZ);
2141                         error = dnode_next_offset(dn,
2142                             0, &start, minlvl, blkfill, 0);
2143                         if (error)
2144                                 break;
2145                         end = start;
2146                         error = dnode_next_offset(dn,
2147                             DNODE_FIND_HOLE, &end, minlvl, blkfill, 0);
2148                         zdb_nicenum(end - start, segsize, sizeof (segsize));
2149                         (void) printf("\t\tsegment [%016llx, %016llx)"
2150                             " size %5s\n", (u_longlong_t)start,
2151                             (u_longlong_t)end, segsize);
2152                         if (error)
2153                                 break;
2154                         start = end;
2155                 }
2156         }
2157
2158         if (db != NULL)
2159                 dmu_buf_rele(db, FTAG);
2160 }
2161
2162 static const char *objset_types[DMU_OST_NUMTYPES] = {
2163         "NONE", "META", "ZPL", "ZVOL", "OTHER", "ANY" };
2164
2165 static void
2166 dump_dir(objset_t *os)
2167 {
2168         dmu_objset_stats_t dds;
2169         uint64_t object, object_count;
2170         uint64_t refdbytes, usedobjs, scratch;
2171         char numbuf[32];
2172         char blkbuf[BP_SPRINTF_LEN + 20];
2173         char osname[ZFS_MAX_DATASET_NAME_LEN];
2174         const char *type = "UNKNOWN";
2175         int verbosity = dump_opt['d'];
2176         int print_header = 1;
2177         unsigned i;
2178         int error;
2179
2180         /* make sure nicenum has enough space */
2181         CTASSERT(sizeof (numbuf) >= NN_NUMBUF_SZ);
2182
2183         dsl_pool_config_enter(dmu_objset_pool(os), FTAG);
2184         dmu_objset_fast_stat(os, &dds);
2185         dsl_pool_config_exit(dmu_objset_pool(os), FTAG);
2186
2187         if (dds.dds_type < DMU_OST_NUMTYPES)
2188                 type = objset_types[dds.dds_type];
2189
2190         if (dds.dds_type == DMU_OST_META) {
2191                 dds.dds_creation_txg = TXG_INITIAL;
2192                 usedobjs = BP_GET_FILL(os->os_rootbp);
2193                 refdbytes = dsl_dir_phys(os->os_spa->spa_dsl_pool->dp_mos_dir)->
2194                     dd_used_bytes;
2195         } else {
2196                 dmu_objset_space(os, &refdbytes, &scratch, &usedobjs, &scratch);
2197         }
2198
2199         ASSERT3U(usedobjs, ==, BP_GET_FILL(os->os_rootbp));
2200
2201         zdb_nicenum(refdbytes, numbuf, sizeof (numbuf));
2202
2203         if (verbosity >= 4) {
2204                 (void) snprintf(blkbuf, sizeof (blkbuf), ", rootbp ");
2205                 (void) snprintf_blkptr(blkbuf + strlen(blkbuf),
2206                     sizeof (blkbuf) - strlen(blkbuf), os->os_rootbp);
2207         } else {
2208                 blkbuf[0] = '\0';
2209         }
2210
2211         dmu_objset_name(os, osname);
2212
2213         (void) printf("Dataset %s [%s], ID %llu, cr_txg %llu, "
2214             "%s, %llu objects%s\n",
2215             osname, type, (u_longlong_t)dmu_objset_id(os),
2216             (u_longlong_t)dds.dds_creation_txg,
2217             numbuf, (u_longlong_t)usedobjs, blkbuf);
2218
2219         if (zopt_objects != 0) {
2220                 for (i = 0; i < zopt_objects; i++)
2221                         dump_object(os, zopt_object[i], verbosity,
2222                             &print_header);
2223                 (void) printf("\n");
2224                 return;
2225         }
2226
2227         if (dump_opt['i'] != 0 || verbosity >= 2)
2228                 dump_intent_log(dmu_objset_zil(os));
2229
2230         if (dmu_objset_ds(os) != NULL) {
2231                 dsl_dataset_t *ds = dmu_objset_ds(os);
2232                 dump_deadlist(&ds->ds_deadlist);
2233
2234                 if (dsl_dataset_remap_deadlist_exists(ds)) {
2235                         (void) printf("ds_remap_deadlist:\n");
2236                         dump_deadlist(&ds->ds_remap_deadlist);
2237                 }
2238         }
2239
2240         if (verbosity < 2)
2241                 return;
2242
2243         if (BP_IS_HOLE(os->os_rootbp))
2244                 return;
2245
2246         dump_object(os, 0, verbosity, &print_header);
2247         object_count = 0;
2248         if (DMU_USERUSED_DNODE(os) != NULL &&
2249             DMU_USERUSED_DNODE(os)->dn_type != 0) {
2250                 dump_object(os, DMU_USERUSED_OBJECT, verbosity, &print_header);
2251                 dump_object(os, DMU_GROUPUSED_OBJECT, verbosity, &print_header);
2252         }
2253
2254         object = 0;
2255         while ((error = dmu_object_next(os, &object, B_FALSE, 0)) == 0) {
2256                 dump_object(os, object, verbosity, &print_header);
2257                 object_count++;
2258         }
2259
2260         ASSERT3U(object_count, ==, usedobjs);
2261
2262         (void) printf("\n");
2263
2264         if (error != ESRCH) {
2265                 (void) fprintf(stderr, "dmu_object_next() = %d\n", error);
2266                 abort();
2267         }
2268 }
2269
2270 static void
2271 dump_uberblock(uberblock_t *ub, const char *header, const char *footer)
2272 {
2273         time_t timestamp = ub->ub_timestamp;
2274
2275         (void) printf("%s", header ? header : "");
2276         (void) printf("\tmagic = %016llx\n", (u_longlong_t)ub->ub_magic);
2277         (void) printf("\tversion = %llu\n", (u_longlong_t)ub->ub_version);
2278         (void) printf("\ttxg = %llu\n", (u_longlong_t)ub->ub_txg);
2279         (void) printf("\tguid_sum = %llu\n", (u_longlong_t)ub->ub_guid_sum);
2280         (void) printf("\ttimestamp = %llu UTC = %s",
2281             (u_longlong_t)ub->ub_timestamp, asctime(localtime(&timestamp)));
2282         if (dump_opt['u'] >= 3) {
2283                 char blkbuf[BP_SPRINTF_LEN];
2284                 snprintf_blkptr(blkbuf, sizeof (blkbuf), &ub->ub_rootbp);
2285                 (void) printf("\trootbp = %s\n", blkbuf);
2286         }
2287         (void) printf("%s", footer ? footer : "");
2288 }
2289
2290 static void
2291 dump_config(spa_t *spa)
2292 {
2293         dmu_buf_t *db;
2294         size_t nvsize = 0;
2295         int error = 0;
2296
2297
2298         error = dmu_bonus_hold(spa->spa_meta_objset,
2299             spa->spa_config_object, FTAG, &db);
2300
2301         if (error == 0) {
2302                 nvsize = *(uint64_t *)db->db_data;
2303                 dmu_buf_rele(db, FTAG);
2304
2305                 (void) printf("\nMOS Configuration:\n");
2306                 dump_packed_nvlist(spa->spa_meta_objset,
2307                     spa->spa_config_object, (void *)&nvsize, 1);
2308         } else {
2309                 (void) fprintf(stderr, "dmu_bonus_hold(%llu) failed, errno %d",
2310                     (u_longlong_t)spa->spa_config_object, error);
2311         }
2312 }
2313
2314 static void
2315 dump_cachefile(const char *cachefile)
2316 {
2317         int fd;
2318         struct stat64 statbuf;
2319         char *buf;
2320         nvlist_t *config;
2321
2322         if ((fd = open64(cachefile, O_RDONLY)) < 0) {
2323                 (void) fprintf(stderr, "cannot open '%s': %s\n", cachefile,
2324                     strerror(errno));
2325                 exit(1);
2326         }
2327
2328         if (fstat64(fd, &statbuf) != 0) {
2329                 (void) fprintf(stderr, "failed to stat '%s': %s\n", cachefile,
2330                     strerror(errno));
2331                 exit(1);
2332         }
2333
2334         if ((buf = malloc(statbuf.st_size)) == NULL) {
2335                 (void) fprintf(stderr, "failed to allocate %llu bytes\n",
2336                     (u_longlong_t)statbuf.st_size);
2337                 exit(1);
2338         }
2339
2340         if (read(fd, buf, statbuf.st_size) != statbuf.st_size) {
2341                 (void) fprintf(stderr, "failed to read %llu bytes\n",
2342                     (u_longlong_t)statbuf.st_size);
2343                 exit(1);
2344         }
2345
2346         (void) close(fd);
2347
2348         if (nvlist_unpack(buf, statbuf.st_size, &config, 0) != 0) {
2349                 (void) fprintf(stderr, "failed to unpack nvlist\n");
2350                 exit(1);
2351         }
2352
2353         free(buf);
2354
2355         dump_nvlist(config, 0);
2356
2357         nvlist_free(config);
2358 }
2359
2360 #define ZDB_MAX_UB_HEADER_SIZE 32
2361
2362 static void
2363 dump_label_uberblocks(vdev_label_t *lbl, uint64_t ashift)
2364 {
2365         vdev_t vd;
2366         vdev_t *vdp = &vd;
2367         char header[ZDB_MAX_UB_HEADER_SIZE];
2368
2369         vd.vdev_ashift = ashift;
2370         vdp->vdev_top = vdp;
2371
2372         for (int i = 0; i < VDEV_UBERBLOCK_COUNT(vdp); i++) {
2373                 uint64_t uoff = VDEV_UBERBLOCK_OFFSET(vdp, i);
2374                 uberblock_t *ub = (void *)((char *)lbl + uoff);
2375
2376                 if (uberblock_verify(ub))
2377                         continue;
2378                 (void) snprintf(header, ZDB_MAX_UB_HEADER_SIZE,
2379                     "Uberblock[%d]\n", i);
2380                 dump_uberblock(ub, header, "");
2381         }
2382 }
2383
2384 static char curpath[PATH_MAX];
2385
2386 /*
2387  * Iterate through the path components, recursively passing
2388  * current one's obj and remaining path until we find the obj
2389  * for the last one.
2390  */
2391 static int
2392 dump_path_impl(objset_t *os, uint64_t obj, char *name)
2393 {
2394         int err;
2395         int header = 1;
2396         uint64_t child_obj;
2397         char *s;
2398         dmu_buf_t *db;
2399         dmu_object_info_t doi;
2400
2401         if ((s = strchr(name, '/')) != NULL)
2402                 *s = '\0';
2403         err = zap_lookup(os, obj, name, 8, 1, &child_obj);
2404
2405         (void) strlcat(curpath, name, sizeof (curpath));
2406
2407         if (err != 0) {
2408                 (void) fprintf(stderr, "failed to lookup %s: %s\n",
2409                     curpath, strerror(err));
2410                 return (err);
2411         }
2412
2413         child_obj = ZFS_DIRENT_OBJ(child_obj);
2414         err = sa_buf_hold(os, child_obj, FTAG, &db);
2415         if (err != 0) {
2416                 (void) fprintf(stderr,
2417                     "failed to get SA dbuf for obj %llu: %s\n",
2418                     (u_longlong_t)child_obj, strerror(err));
2419                 return (EINVAL);
2420         }
2421         dmu_object_info_from_db(db, &doi);
2422         sa_buf_rele(db, FTAG);
2423
2424         if (doi.doi_bonus_type != DMU_OT_SA &&
2425             doi.doi_bonus_type != DMU_OT_ZNODE) {
2426                 (void) fprintf(stderr, "invalid bonus type %d for obj %llu\n",
2427                     doi.doi_bonus_type, (u_longlong_t)child_obj);
2428                 return (EINVAL);
2429         }
2430
2431         if (dump_opt['v'] > 6) {
2432                 (void) printf("obj=%llu %s type=%d bonustype=%d\n",
2433                     (u_longlong_t)child_obj, curpath, doi.doi_type,
2434                     doi.doi_bonus_type);
2435         }
2436
2437         (void) strlcat(curpath, "/", sizeof (curpath));
2438
2439         switch (doi.doi_type) {
2440         case DMU_OT_DIRECTORY_CONTENTS:
2441                 if (s != NULL && *(s + 1) != '\0')
2442                         return (dump_path_impl(os, child_obj, s + 1));
2443                 /*FALLTHROUGH*/
2444         case DMU_OT_PLAIN_FILE_CONTENTS:
2445                 dump_object(os, child_obj, dump_opt['v'], &header);
2446                 return (0);
2447         default:
2448                 (void) fprintf(stderr, "object %llu has non-file/directory "
2449                     "type %d\n", (u_longlong_t)obj, doi.doi_type);
2450                 break;
2451         }
2452
2453         return (EINVAL);
2454 }
2455
2456 /*
2457  * Dump the blocks for the object specified by path inside the dataset.
2458  */
2459 static int
2460 dump_path(char *ds, char *path)
2461 {
2462         int err;
2463         objset_t *os;
2464         uint64_t root_obj;
2465
2466         err = open_objset(ds, DMU_OST_ZFS, FTAG, &os);
2467         if (err != 0)
2468                 return (err);
2469
2470         err = zap_lookup(os, MASTER_NODE_OBJ, ZFS_ROOT_OBJ, 8, 1, &root_obj);
2471         if (err != 0) {
2472                 (void) fprintf(stderr, "can't lookup root znode: %s\n",
2473                     strerror(err));
2474                 dmu_objset_disown(os, FTAG);
2475                 return (EINVAL);
2476         }
2477
2478         (void) snprintf(curpath, sizeof (curpath), "dataset=%s path=/", ds);
2479
2480         err = dump_path_impl(os, root_obj, path);
2481
2482         close_objset(os, FTAG);
2483         return (err);
2484 }
2485
2486 static int
2487 dump_label(const char *dev)
2488 {
2489         int fd;
2490         vdev_label_t label;
2491         char path[MAXPATHLEN];
2492         char *buf = label.vl_vdev_phys.vp_nvlist;
2493         size_t buflen = sizeof (label.vl_vdev_phys.vp_nvlist);
2494         struct stat64 statbuf;
2495         uint64_t psize, ashift;
2496         boolean_t label_found = B_FALSE;
2497
2498         (void) strlcpy(path, dev, sizeof (path));
2499         if (dev[0] == '/') {
2500                 if (strncmp(dev, ZFS_DISK_ROOTD,
2501                     strlen(ZFS_DISK_ROOTD)) == 0) {
2502                         (void) snprintf(path, sizeof (path), "%s%s",
2503                             ZFS_RDISK_ROOTD, dev + strlen(ZFS_DISK_ROOTD));
2504                 }
2505         } else if (stat64(path, &statbuf) != 0) {
2506                 char *s;
2507
2508                 (void) snprintf(path, sizeof (path), "%s%s", ZFS_RDISK_ROOTD,
2509                     dev);
2510                 if (((s = strrchr(dev, 's')) == NULL &&
2511                     (s = strchr(dev, 'p')) == NULL) ||
2512                     !isdigit(*(s + 1)))
2513                         (void) strlcat(path, "s0", sizeof (path));
2514         }
2515
2516         if ((fd = open64(path, O_RDONLY)) < 0) {
2517                 (void) fprintf(stderr, "cannot open '%s': %s\n", path,
2518                     strerror(errno));
2519                 exit(1);
2520         }
2521
2522         if (fstat64(fd, &statbuf) != 0) {
2523                 (void) fprintf(stderr, "failed to stat '%s': %s\n", path,
2524                     strerror(errno));
2525                 (void) close(fd);
2526                 exit(1);
2527         }
2528
2529         if (S_ISBLK(statbuf.st_mode)) {
2530                 (void) fprintf(stderr,
2531                     "cannot use '%s': character device required\n", path);
2532                 (void) close(fd);
2533                 exit(1);
2534         }
2535
2536         psize = statbuf.st_size;
2537         psize = P2ALIGN(psize, (uint64_t)sizeof (vdev_label_t));
2538
2539         for (int l = 0; l < VDEV_LABELS; l++) {
2540                 nvlist_t *config = NULL;
2541
2542                 if (!dump_opt['q']) {
2543                         (void) printf("------------------------------------\n");
2544                         (void) printf("LABEL %d\n", l);
2545                         (void) printf("------------------------------------\n");
2546                 }
2547
2548                 if (pread64(fd, &label, sizeof (label),
2549                     vdev_label_offset(psize, l, 0)) != sizeof (label)) {
2550                         if (!dump_opt['q'])
2551                                 (void) printf("failed to read label %d\n", l);
2552                         continue;
2553                 }
2554
2555                 if (nvlist_unpack(buf, buflen, &config, 0) != 0) {
2556                         if (!dump_opt['q'])
2557                                 (void) printf("failed to unpack label %d\n", l);
2558                         ashift = SPA_MINBLOCKSHIFT;
2559                 } else {
2560                         nvlist_t *vdev_tree = NULL;
2561
2562                         if (!dump_opt['q'])
2563                                 dump_nvlist(config, 4);
2564                         if ((nvlist_lookup_nvlist(config,
2565                             ZPOOL_CONFIG_VDEV_TREE, &vdev_tree) != 0) ||
2566                             (nvlist_lookup_uint64(vdev_tree,
2567                             ZPOOL_CONFIG_ASHIFT, &ashift) != 0))
2568                                 ashift = SPA_MINBLOCKSHIFT;
2569                         nvlist_free(config);
2570                         label_found = B_TRUE;
2571                 }
2572                 if (dump_opt['u'])
2573                         dump_label_uberblocks(&label, ashift);
2574         }
2575
2576         (void) close(fd);
2577
2578         return (label_found ? 0 : 2);
2579 }
2580
2581 static uint64_t dataset_feature_count[SPA_FEATURES];
2582 static uint64_t remap_deadlist_count = 0;
2583
2584 /*ARGSUSED*/
2585 static int
2586 dump_one_dir(const char *dsname, void *arg)
2587 {
2588         int error;
2589         objset_t *os;
2590
2591         error = open_objset(dsname, DMU_OST_ANY, FTAG, &os);
2592         if (error != 0)
2593                 return (0);
2594
2595         for (spa_feature_t f = 0; f < SPA_FEATURES; f++) {
2596                 if (!dmu_objset_ds(os)->ds_feature_inuse[f])
2597                         continue;
2598                 ASSERT(spa_feature_table[f].fi_flags &
2599                     ZFEATURE_FLAG_PER_DATASET);
2600                 dataset_feature_count[f]++;
2601         }
2602
2603         if (dsl_dataset_remap_deadlist_exists(dmu_objset_ds(os))) {
2604                 remap_deadlist_count++;
2605         }
2606
2607         dump_dir(os);
2608         close_objset(os, FTAG);
2609         fuid_table_destroy();
2610         return (0);
2611 }
2612
2613 /*
2614  * Block statistics.
2615  */
2616 #define PSIZE_HISTO_SIZE (SPA_OLD_MAXBLOCKSIZE / SPA_MINBLOCKSIZE + 2)
2617 typedef struct zdb_blkstats {
2618         uint64_t zb_asize;
2619         uint64_t zb_lsize;
2620         uint64_t zb_psize;
2621         uint64_t zb_count;
2622         uint64_t zb_gangs;
2623         uint64_t zb_ditto_samevdev;
2624         uint64_t zb_psize_histogram[PSIZE_HISTO_SIZE];
2625 } zdb_blkstats_t;
2626
2627 /*
2628  * Extended object types to report deferred frees and dedup auto-ditto blocks.
2629  */
2630 #define ZDB_OT_DEFERRED (DMU_OT_NUMTYPES + 0)
2631 #define ZDB_OT_DITTO    (DMU_OT_NUMTYPES + 1)
2632 #define ZDB_OT_OTHER    (DMU_OT_NUMTYPES + 2)
2633 #define ZDB_OT_TOTAL    (DMU_OT_NUMTYPES + 3)
2634
2635 static const char *zdb_ot_extname[] = {
2636         "deferred free",
2637         "dedup ditto",
2638         "other",
2639         "Total",
2640 };
2641
2642 #define ZB_TOTAL        DN_MAX_LEVELS
2643
2644 typedef struct zdb_cb {
2645         zdb_blkstats_t  zcb_type[ZB_TOTAL + 1][ZDB_OT_TOTAL + 1];
2646         uint64_t        zcb_removing_size;
2647         uint64_t        zcb_dedup_asize;
2648         uint64_t        zcb_dedup_blocks;
2649         uint64_t        zcb_embedded_blocks[NUM_BP_EMBEDDED_TYPES];
2650         uint64_t        zcb_embedded_histogram[NUM_BP_EMBEDDED_TYPES]
2651             [BPE_PAYLOAD_SIZE];
2652         uint64_t        zcb_start;
2653         hrtime_t        zcb_lastprint;
2654         uint64_t        zcb_totalasize;
2655         uint64_t        zcb_errors[256];
2656         int             zcb_readfails;
2657         int             zcb_haderrors;
2658         spa_t           *zcb_spa;
2659         uint32_t        **zcb_vd_obsolete_counts;
2660 } zdb_cb_t;
2661
2662 static void
2663 zdb_count_block(zdb_cb_t *zcb, zilog_t *zilog, const blkptr_t *bp,
2664     dmu_object_type_t type)
2665 {
2666         uint64_t refcnt = 0;
2667
2668         ASSERT(type < ZDB_OT_TOTAL);
2669
2670         if (zilog && zil_bp_tree_add(zilog, bp) != 0)
2671                 return;
2672
2673         for (int i = 0; i < 4; i++) {
2674                 int l = (i < 2) ? BP_GET_LEVEL(bp) : ZB_TOTAL;
2675                 int t = (i & 1) ? type : ZDB_OT_TOTAL;
2676                 int equal;
2677                 zdb_blkstats_t *zb = &zcb->zcb_type[l][t];
2678
2679                 zb->zb_asize += BP_GET_ASIZE(bp);
2680                 zb->zb_lsize += BP_GET_LSIZE(bp);
2681                 zb->zb_psize += BP_GET_PSIZE(bp);
2682                 zb->zb_count++;
2683
2684                 /*
2685                  * The histogram is only big enough to record blocks up to
2686                  * SPA_OLD_MAXBLOCKSIZE; larger blocks go into the last,
2687                  * "other", bucket.
2688                  */
2689                 unsigned idx = BP_GET_PSIZE(bp) >> SPA_MINBLOCKSHIFT;
2690                 idx = MIN(idx, SPA_OLD_MAXBLOCKSIZE / SPA_MINBLOCKSIZE + 1);
2691                 zb->zb_psize_histogram[idx]++;
2692
2693                 zb->zb_gangs += BP_COUNT_GANG(bp);
2694
2695                 switch (BP_GET_NDVAS(bp)) {
2696                 case 2:
2697                         if (DVA_GET_VDEV(&bp->blk_dva[0]) ==
2698                             DVA_GET_VDEV(&bp->blk_dva[1]))
2699                                 zb->zb_ditto_samevdev++;
2700                         break;
2701                 case 3:
2702                         equal = (DVA_GET_VDEV(&bp->blk_dva[0]) ==
2703                             DVA_GET_VDEV(&bp->blk_dva[1])) +
2704                             (DVA_GET_VDEV(&bp->blk_dva[0]) ==
2705                             DVA_GET_VDEV(&bp->blk_dva[2])) +
2706                             (DVA_GET_VDEV(&bp->blk_dva[1]) ==
2707                             DVA_GET_VDEV(&bp->blk_dva[2]));
2708                         if (equal != 0)
2709                                 zb->zb_ditto_samevdev++;
2710                         break;
2711                 }
2712
2713         }
2714
2715         if (BP_IS_EMBEDDED(bp)) {
2716                 zcb->zcb_embedded_blocks[BPE_GET_ETYPE(bp)]++;
2717                 zcb->zcb_embedded_histogram[BPE_GET_ETYPE(bp)]
2718                     [BPE_GET_PSIZE(bp)]++;
2719                 return;
2720         }
2721
2722         if (dump_opt['L'])
2723                 return;
2724
2725         if (BP_GET_DEDUP(bp)) {
2726                 ddt_t *ddt;
2727                 ddt_entry_t *dde;
2728
2729                 ddt = ddt_select(zcb->zcb_spa, bp);
2730                 ddt_enter(ddt);
2731                 dde = ddt_lookup(ddt, bp, B_FALSE);
2732
2733                 if (dde == NULL) {
2734                         refcnt = 0;
2735                 } else {
2736                         ddt_phys_t *ddp = ddt_phys_select(dde, bp);
2737                         ddt_phys_decref(ddp);
2738                         refcnt = ddp->ddp_refcnt;
2739                         if (ddt_phys_total_refcnt(dde) == 0)
2740                                 ddt_remove(ddt, dde);
2741                 }
2742                 ddt_exit(ddt);
2743         }
2744
2745         VERIFY3U(zio_wait(zio_claim(NULL, zcb->zcb_spa,
2746             refcnt ? 0 : spa_first_txg(zcb->zcb_spa),
2747             bp, NULL, NULL, ZIO_FLAG_CANFAIL)), ==, 0);
2748 }
2749
2750 /* ARGSUSED */
2751 static void
2752 zdb_blkptr_done(zio_t *zio)
2753 {
2754         spa_t *spa = zio->io_spa;
2755         blkptr_t *bp = zio->io_bp;
2756         int ioerr = zio->io_error;
2757         zdb_cb_t *zcb = zio->io_private;
2758         zbookmark_phys_t *zb = &zio->io_bookmark;
2759
2760         abd_free(zio->io_abd);
2761
2762         mutex_enter(&spa->spa_scrub_lock);
2763         spa->spa_scrub_inflight--;
2764         cv_broadcast(&spa->spa_scrub_io_cv);
2765
2766         if (ioerr && !(zio->io_flags & ZIO_FLAG_SPECULATIVE)) {
2767                 char blkbuf[BP_SPRINTF_LEN];
2768
2769                 zcb->zcb_haderrors = 1;
2770                 zcb->zcb_errors[ioerr]++;
2771
2772                 if (dump_opt['b'] >= 2)
2773                         snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
2774                 else
2775                         blkbuf[0] = '\0';
2776
2777                 (void) printf("zdb_blkptr_cb: "
2778                     "Got error %d reading "
2779                     "<%llu, %llu, %lld, %llx> %s -- skipping\n",
2780                     ioerr,
2781                     (u_longlong_t)zb->zb_objset,
2782                     (u_longlong_t)zb->zb_object,
2783                     (u_longlong_t)zb->zb_level,
2784                     (u_longlong_t)zb->zb_blkid,
2785                     blkbuf);
2786         }
2787         mutex_exit(&spa->spa_scrub_lock);
2788 }
2789
2790 /* ARGSUSED */
2791 static int
2792 zdb_blkptr_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
2793     const zbookmark_phys_t *zb, const dnode_phys_t *dnp, void *arg)
2794 {
2795         zdb_cb_t *zcb = arg;
2796         dmu_object_type_t type;
2797         boolean_t is_metadata;
2798
2799         if (bp == NULL)
2800                 return (0);
2801
2802         if (dump_opt['b'] >= 5 && bp->blk_birth > 0) {
2803                 char blkbuf[BP_SPRINTF_LEN];
2804                 snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
2805                 (void) printf("objset %llu object %llu "
2806                     "level %lld offset 0x%llx %s\n",
2807                     (u_longlong_t)zb->zb_objset,
2808                     (u_longlong_t)zb->zb_object,
2809                     (longlong_t)zb->zb_level,
2810                     (u_longlong_t)blkid2offset(dnp, bp, zb),
2811                     blkbuf);
2812         }
2813
2814         if (BP_IS_HOLE(bp))
2815                 return (0);
2816
2817         type = BP_GET_TYPE(bp);
2818
2819         zdb_count_block(zcb, zilog, bp,
2820             (type & DMU_OT_NEWTYPE) ? ZDB_OT_OTHER : type);
2821
2822         is_metadata = (BP_GET_LEVEL(bp) != 0 || DMU_OT_IS_METADATA(type));
2823
2824         if (!BP_IS_EMBEDDED(bp) &&
2825             (dump_opt['c'] > 1 || (dump_opt['c'] && is_metadata))) {
2826                 size_t size = BP_GET_PSIZE(bp);
2827                 abd_t *abd = abd_alloc(size, B_FALSE);
2828                 int flags = ZIO_FLAG_CANFAIL | ZIO_FLAG_SCRUB | ZIO_FLAG_RAW;
2829
2830                 /* If it's an intent log block, failure is expected. */
2831                 if (zb->zb_level == ZB_ZIL_LEVEL)
2832                         flags |= ZIO_FLAG_SPECULATIVE;
2833
2834                 mutex_enter(&spa->spa_scrub_lock);
2835                 while (spa->spa_scrub_inflight > max_inflight)
2836                         cv_wait(&spa->spa_scrub_io_cv, &spa->spa_scrub_lock);
2837                 spa->spa_scrub_inflight++;
2838                 mutex_exit(&spa->spa_scrub_lock);
2839
2840                 zio_nowait(zio_read(NULL, spa, bp, abd, size,
2841                     zdb_blkptr_done, zcb, ZIO_PRIORITY_ASYNC_READ, flags, zb));
2842         }
2843
2844         zcb->zcb_readfails = 0;
2845
2846         /* only call gethrtime() every 100 blocks */
2847         static int iters;
2848         if (++iters > 100)
2849                 iters = 0;
2850         else
2851                 return (0);
2852
2853         if (dump_opt['b'] < 5 && gethrtime() > zcb->zcb_lastprint + NANOSEC) {
2854                 uint64_t now = gethrtime();
2855                 char buf[10];
2856                 uint64_t bytes = zcb->zcb_type[ZB_TOTAL][ZDB_OT_TOTAL].zb_asize;
2857                 int kb_per_sec =
2858                     1 + bytes / (1 + ((now - zcb->zcb_start) / 1000 / 1000));
2859                 int sec_remaining =
2860                     (zcb->zcb_totalasize - bytes) / 1024 / kb_per_sec;
2861
2862                 /* make sure nicenum has enough space */
2863                 CTASSERT(sizeof (buf) >= NN_NUMBUF_SZ);
2864
2865                 zfs_nicenum(bytes, buf, sizeof (buf));
2866                 (void) fprintf(stderr,
2867                     "\r%5s completed (%4dMB/s) "
2868                     "estimated time remaining: %uhr %02umin %02usec        ",
2869                     buf, kb_per_sec / 1024,
2870                     sec_remaining / 60 / 60,
2871                     sec_remaining / 60 % 60,
2872                     sec_remaining % 60);
2873
2874                 zcb->zcb_lastprint = now;
2875         }
2876
2877         return (0);
2878 }
2879
2880 static void
2881 zdb_leak(void *arg, uint64_t start, uint64_t size)
2882 {
2883         vdev_t *vd = arg;
2884
2885         (void) printf("leaked space: vdev %llu, offset 0x%llx, size %llu\n",
2886             (u_longlong_t)vd->vdev_id, (u_longlong_t)start, (u_longlong_t)size);
2887 }
2888
2889 static metaslab_ops_t zdb_metaslab_ops = {
2890         NULL    /* alloc */
2891 };
2892
2893 static void
2894 zdb_ddt_leak_init(spa_t *spa, zdb_cb_t *zcb)
2895 {
2896         ddt_bookmark_t ddb;
2897         ddt_entry_t dde;
2898         int error;
2899
2900         bzero(&ddb, sizeof (ddb));
2901         while ((error = ddt_walk(spa, &ddb, &dde)) == 0) {
2902                 blkptr_t blk;
2903                 ddt_phys_t *ddp = dde.dde_phys;
2904
2905                 if (ddb.ddb_class == DDT_CLASS_UNIQUE)
2906                         return;
2907
2908                 ASSERT(ddt_phys_total_refcnt(&dde) > 1);
2909
2910                 for (int p = 0; p < DDT_PHYS_TYPES; p++, ddp++) {
2911                         if (ddp->ddp_phys_birth == 0)
2912                                 continue;
2913                         ddt_bp_create(ddb.ddb_checksum,
2914                             &dde.dde_key, ddp, &blk);
2915                         if (p == DDT_PHYS_DITTO) {
2916                                 zdb_count_block(zcb, NULL, &blk, ZDB_OT_DITTO);
2917                         } else {
2918                                 zcb->zcb_dedup_asize +=
2919                                     BP_GET_ASIZE(&blk) * (ddp->ddp_refcnt - 1);
2920                                 zcb->zcb_dedup_blocks++;
2921                         }
2922                 }
2923                 if (!dump_opt['L']) {
2924                         ddt_t *ddt = spa->spa_ddt[ddb.ddb_checksum];
2925                         ddt_enter(ddt);
2926                         VERIFY(ddt_lookup(ddt, &blk, B_TRUE) != NULL);
2927                         ddt_exit(ddt);
2928                 }
2929         }
2930
2931         ASSERT(error == ENOENT);
2932 }
2933
2934 /* ARGSUSED */
2935 static void
2936 claim_segment_impl_cb(uint64_t inner_offset, vdev_t *vd, uint64_t offset,
2937     uint64_t size, void *arg)
2938 {
2939         /*
2940          * This callback was called through a remap from
2941          * a device being removed. Therefore, the vdev that
2942          * this callback is applied to is a concrete
2943          * vdev.
2944          */
2945         ASSERT(vdev_is_concrete(vd));
2946
2947         VERIFY0(metaslab_claim_impl(vd, offset, size,
2948             spa_first_txg(vd->vdev_spa)));
2949 }
2950
2951 static void
2952 claim_segment_cb(void *arg, uint64_t offset, uint64_t size)
2953 {
2954         vdev_t *vd = arg;
2955
2956         vdev_indirect_ops.vdev_op_remap(vd, offset, size,
2957             claim_segment_impl_cb, NULL);
2958 }
2959
2960 /*
2961  * After accounting for all allocated blocks that are directly referenced,
2962  * we might have missed a reference to a block from a partially complete
2963  * (and thus unused) indirect mapping object. We perform a secondary pass
2964  * through the metaslabs we have already mapped and claim the destination
2965  * blocks.
2966  */
2967 static void
2968 zdb_claim_removing(spa_t *spa, zdb_cb_t *zcb)
2969 {
2970         if (spa->spa_vdev_removal == NULL)
2971                 return;
2972
2973         spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
2974
2975         spa_vdev_removal_t *svr = spa->spa_vdev_removal;
2976         vdev_t *vd = svr->svr_vdev;
2977         vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
2978
2979         for (uint64_t msi = 0; msi < vd->vdev_ms_count; msi++) {
2980                 metaslab_t *msp = vd->vdev_ms[msi];
2981
2982                 if (msp->ms_start >= vdev_indirect_mapping_max_offset(vim))
2983                         break;
2984
2985                 ASSERT0(range_tree_space(svr->svr_allocd_segs));
2986
2987                 if (msp->ms_sm != NULL) {
2988                         VERIFY0(space_map_load(msp->ms_sm,
2989                             svr->svr_allocd_segs, SM_ALLOC));
2990
2991                         /*
2992                          * Clear everything past what has been synced,
2993                          * because we have not allocated mappings for it yet.
2994                          */
2995                         range_tree_clear(svr->svr_allocd_segs,
2996                             vdev_indirect_mapping_max_offset(vim),
2997                             msp->ms_sm->sm_start + msp->ms_sm->sm_size -
2998                             vdev_indirect_mapping_max_offset(vim));
2999                 }
3000
3001                 zcb->zcb_removing_size +=
3002                     range_tree_space(svr->svr_allocd_segs);
3003                 range_tree_vacate(svr->svr_allocd_segs, claim_segment_cb, vd);
3004         }
3005
3006         spa_config_exit(spa, SCL_CONFIG, FTAG);
3007 }
3008
3009 /*
3010  * vm_idxp is an in-out parameter which (for indirect vdevs) is the
3011  * index in vim_entries that has the first entry in this metaslab.  On
3012  * return, it will be set to the first entry after this metaslab.
3013  */
3014 static void
3015 zdb_leak_init_ms(metaslab_t *msp, uint64_t *vim_idxp)
3016 {
3017         metaslab_group_t *mg = msp->ms_group;
3018         vdev_t *vd = mg->mg_vd;
3019         vdev_t *rvd = vd->vdev_spa->spa_root_vdev;
3020
3021         mutex_enter(&msp->ms_lock);
3022         metaslab_unload(msp);
3023
3024         /*
3025          * We don't want to spend the CPU manipulating the size-ordered
3026          * tree, so clear the range_tree ops.
3027          */
3028         msp->ms_tree->rt_ops = NULL;
3029
3030         (void) fprintf(stderr,
3031             "\rloading vdev %llu of %llu, metaslab %llu of %llu ...",
3032             (longlong_t)vd->vdev_id,
3033             (longlong_t)rvd->vdev_children,
3034             (longlong_t)msp->ms_id,
3035             (longlong_t)vd->vdev_ms_count);
3036
3037         /*
3038          * For leak detection, we overload the metaslab ms_tree to
3039          * contain allocated segments instead of free segments. As a
3040          * result, we can't use the normal metaslab_load/unload
3041          * interfaces.
3042          */
3043         if (vd->vdev_ops == &vdev_indirect_ops) {
3044                 vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
3045                 for (; *vim_idxp < vdev_indirect_mapping_num_entries(vim);
3046                     (*vim_idxp)++) {
3047                         vdev_indirect_mapping_entry_phys_t *vimep =
3048                             &vim->vim_entries[*vim_idxp];
3049                         uint64_t ent_offset = DVA_MAPPING_GET_SRC_OFFSET(vimep);
3050                         uint64_t ent_len = DVA_GET_ASIZE(&vimep->vimep_dst);
3051                         ASSERT3U(ent_offset, >=, msp->ms_start);
3052                         if (ent_offset >= msp->ms_start + msp->ms_size)
3053                                 break;
3054
3055                         /*
3056                          * Mappings do not cross metaslab boundaries,
3057                          * because we create them by walking the metaslabs.
3058                          */
3059                         ASSERT3U(ent_offset + ent_len, <=,
3060                             msp->ms_start + msp->ms_size);
3061                         range_tree_add(msp->ms_tree, ent_offset, ent_len);
3062                 }
3063         } else if (msp->ms_sm != NULL) {
3064                 VERIFY0(space_map_load(msp->ms_sm, msp->ms_tree, SM_ALLOC));
3065         }
3066
3067         if (!msp->ms_loaded) {
3068                 msp->ms_loaded = B_TRUE;
3069         }
3070         mutex_exit(&msp->ms_lock);
3071 }
3072
3073 /* ARGSUSED */
3074 static int
3075 increment_indirect_mapping_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
3076 {
3077         zdb_cb_t *zcb = arg;
3078         spa_t *spa = zcb->zcb_spa;
3079         vdev_t *vd;
3080         const dva_t *dva = &bp->blk_dva[0];
3081
3082         ASSERT(!dump_opt['L']);
3083         ASSERT3U(BP_GET_NDVAS(bp), ==, 1);
3084
3085         spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
3086         vd = vdev_lookup_top(zcb->zcb_spa, DVA_GET_VDEV(dva));
3087         ASSERT3P(vd, !=, NULL);
3088         spa_config_exit(spa, SCL_VDEV, FTAG);
3089
3090         ASSERT(vd->vdev_indirect_config.vic_mapping_object != 0);
3091         ASSERT3P(zcb->zcb_vd_obsolete_counts[vd->vdev_id], !=, NULL);
3092
3093         vdev_indirect_mapping_increment_obsolete_count(
3094             vd->vdev_indirect_mapping,
3095             DVA_GET_OFFSET(dva), DVA_GET_ASIZE(dva),
3096             zcb->zcb_vd_obsolete_counts[vd->vdev_id]);
3097
3098         return (0);
3099 }
3100
3101 static uint32_t *
3102 zdb_load_obsolete_counts(vdev_t *vd)
3103 {
3104         vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
3105         spa_t *spa = vd->vdev_spa;
3106         spa_condensing_indirect_phys_t *scip =
3107             &spa->spa_condensing_indirect_phys;
3108         uint32_t *counts;
3109
3110         EQUIV(vdev_obsolete_sm_object(vd) != 0, vd->vdev_obsolete_sm != NULL);
3111         counts = vdev_indirect_mapping_load_obsolete_counts(vim);
3112         if (vd->vdev_obsolete_sm != NULL) {
3113                 vdev_indirect_mapping_load_obsolete_spacemap(vim, counts,
3114                     vd->vdev_obsolete_sm);
3115         }
3116         if (scip->scip_vdev == vd->vdev_id &&
3117             scip->scip_prev_obsolete_sm_object != 0) {
3118                 space_map_t *prev_obsolete_sm = NULL;
3119                 VERIFY0(space_map_open(&prev_obsolete_sm, spa->spa_meta_objset,
3120                     scip->scip_prev_obsolete_sm_object, 0, vd->vdev_asize, 0));
3121                 space_map_update(prev_obsolete_sm);
3122                 vdev_indirect_mapping_load_obsolete_spacemap(vim, counts,
3123                     prev_obsolete_sm);
3124                 space_map_close(prev_obsolete_sm);
3125         }
3126         return (counts);
3127 }
3128
3129 static void
3130 zdb_leak_init(spa_t *spa, zdb_cb_t *zcb)
3131 {
3132         zcb->zcb_spa = spa;
3133
3134         if (!dump_opt['L']) {
3135                 dsl_pool_t *dp = spa->spa_dsl_pool;
3136                 vdev_t *rvd = spa->spa_root_vdev;
3137
3138                 /*
3139                  * We are going to be changing the meaning of the metaslab's
3140                  * ms_tree.  Ensure that the allocator doesn't try to
3141                  * use the tree.
3142                  */
3143                 spa->spa_normal_class->mc_ops = &zdb_metaslab_ops;
3144                 spa->spa_log_class->mc_ops = &zdb_metaslab_ops;
3145
3146                 zcb->zcb_vd_obsolete_counts =
3147                     umem_zalloc(rvd->vdev_children * sizeof (uint32_t *),
3148                     UMEM_NOFAIL);
3149
3150
3151                 for (uint64_t c = 0; c < rvd->vdev_children; c++) {
3152                         vdev_t *vd = rvd->vdev_child[c];
3153                         uint64_t vim_idx = 0;
3154
3155                         ASSERT3U(c, ==, vd->vdev_id);
3156
3157                         /*
3158                          * Note: we don't check for mapping leaks on
3159                          * removing vdevs because their ms_tree's are
3160                          * used to look for leaks in allocated space.
3161                          */
3162                         if (vd->vdev_ops == &vdev_indirect_ops) {
3163                                 zcb->zcb_vd_obsolete_counts[c] =
3164                                     zdb_load_obsolete_counts(vd);
3165
3166                                 /*
3167                                  * Normally, indirect vdevs don't have any
3168                                  * metaslabs.  We want to set them up for
3169                                  * zio_claim().
3170                                  */
3171                                 VERIFY0(vdev_metaslab_init(vd, 0));
3172                         }
3173
3174                         for (uint64_t m = 0; m < vd->vdev_ms_count; m++) {
3175                                 zdb_leak_init_ms(vd->vdev_ms[m], &vim_idx);
3176                         }
3177                         if (vd->vdev_ops == &vdev_indirect_ops) {
3178                                 ASSERT3U(vim_idx, ==,
3179                                     vdev_indirect_mapping_num_entries(
3180                                     vd->vdev_indirect_mapping));
3181                         }
3182                 }
3183                 (void) fprintf(stderr, "\n");
3184
3185                 if (bpobj_is_open(&dp->dp_obsolete_bpobj)) {
3186                         ASSERT(spa_feature_is_enabled(spa,
3187                             SPA_FEATURE_DEVICE_REMOVAL));
3188                         (void) bpobj_iterate_nofree(&dp->dp_obsolete_bpobj,
3189                             increment_indirect_mapping_cb, zcb, NULL);
3190                 }
3191         }
3192
3193         spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
3194
3195         zdb_ddt_leak_init(spa, zcb);
3196
3197         spa_config_exit(spa, SCL_CONFIG, FTAG);
3198 }
3199
3200 static boolean_t
3201 zdb_check_for_obsolete_leaks(vdev_t *vd, zdb_cb_t *zcb)
3202 {
3203         boolean_t leaks = B_FALSE;
3204         vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
3205         uint64_t total_leaked = 0;
3206
3207         ASSERT(vim != NULL);
3208
3209         for (uint64_t i = 0; i < vdev_indirect_mapping_num_entries(vim); i++) {
3210                 vdev_indirect_mapping_entry_phys_t *vimep =
3211                     &vim->vim_entries[i];
3212                 uint64_t obsolete_bytes = 0;
3213                 uint64_t offset = DVA_MAPPING_GET_SRC_OFFSET(vimep);
3214                 metaslab_t *msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
3215
3216                 /*
3217                  * This is not very efficient but it's easy to
3218                  * verify correctness.
3219                  */
3220                 for (uint64_t inner_offset = 0;
3221                     inner_offset < DVA_GET_ASIZE(&vimep->vimep_dst);
3222                     inner_offset += 1 << vd->vdev_ashift) {
3223                         if (range_tree_contains(msp->ms_tree,
3224                             offset + inner_offset, 1 << vd->vdev_ashift)) {
3225                                 obsolete_bytes += 1 << vd->vdev_ashift;
3226                         }
3227                 }
3228
3229                 int64_t bytes_leaked = obsolete_bytes -
3230                     zcb->zcb_vd_obsolete_counts[vd->vdev_id][i];
3231                 ASSERT3U(DVA_GET_ASIZE(&vimep->vimep_dst), >=,
3232                     zcb->zcb_vd_obsolete_counts[vd->vdev_id][i]);
3233                 if (bytes_leaked != 0 &&
3234                     (vdev_obsolete_counts_are_precise(vd) ||
3235                     dump_opt['d'] >= 5)) {
3236                         (void) printf("obsolete indirect mapping count "
3237                             "mismatch on %llu:%llx:%llx : %llx bytes leaked\n",
3238                             (u_longlong_t)vd->vdev_id,
3239                             (u_longlong_t)DVA_MAPPING_GET_SRC_OFFSET(vimep),
3240                             (u_longlong_t)DVA_GET_ASIZE(&vimep->vimep_dst),
3241                             (u_longlong_t)bytes_leaked);
3242                 }
3243                 total_leaked += ABS(bytes_leaked);
3244         }
3245
3246         if (!vdev_obsolete_counts_are_precise(vd) && total_leaked > 0) {
3247                 int pct_leaked = total_leaked * 100 /
3248                     vdev_indirect_mapping_bytes_mapped(vim);
3249                 (void) printf("cannot verify obsolete indirect mapping "
3250                     "counts of vdev %llu because precise feature was not "
3251                     "enabled when it was removed: %d%% (%llx bytes) of mapping"
3252                     "unreferenced\n",
3253                     (u_longlong_t)vd->vdev_id, pct_leaked,
3254                     (u_longlong_t)total_leaked);
3255         } else if (total_leaked > 0) {
3256                 (void) printf("obsolete indirect mapping count mismatch "
3257                     "for vdev %llu -- %llx total bytes mismatched\n",
3258                     (u_longlong_t)vd->vdev_id,
3259                     (u_longlong_t)total_leaked);
3260                 leaks |= B_TRUE;
3261         }
3262
3263         vdev_indirect_mapping_free_obsolete_counts(vim,
3264             zcb->zcb_vd_obsolete_counts[vd->vdev_id]);
3265         zcb->zcb_vd_obsolete_counts[vd->vdev_id] = NULL;
3266
3267         return (leaks);
3268 }
3269
3270 static boolean_t
3271 zdb_leak_fini(spa_t *spa, zdb_cb_t *zcb)
3272 {
3273         boolean_t leaks = B_FALSE;
3274         if (!dump_opt['L']) {
3275                 vdev_t *rvd = spa->spa_root_vdev;
3276                 for (unsigned c = 0; c < rvd->vdev_children; c++) {
3277                         vdev_t *vd = rvd->vdev_child[c];
3278                         metaslab_group_t *mg = vd->vdev_mg;
3279
3280                         if (zcb->zcb_vd_obsolete_counts[c] != NULL) {
3281                                 leaks |= zdb_check_for_obsolete_leaks(vd, zcb);
3282                         }
3283
3284                         for (uint64_t m = 0; m < vd->vdev_ms_count; m++) {
3285                                 metaslab_t *msp = vd->vdev_ms[m];
3286                                 ASSERT3P(mg, ==, msp->ms_group);
3287
3288                                 /*
3289                                  * The ms_tree has been overloaded to
3290                                  * contain allocated segments. Now that we
3291                                  * finished traversing all blocks, any
3292                                  * block that remains in the ms_tree
3293                                  * represents an allocated block that we
3294                                  * did not claim during the traversal.
3295                                  * Claimed blocks would have been removed
3296                                  * from the ms_tree.  For indirect vdevs,
3297                                  * space remaining in the tree represents
3298                                  * parts of the mapping that are not
3299                                  * referenced, which is not a bug.
3300                                  */
3301                                 if (vd->vdev_ops == &vdev_indirect_ops) {
3302                                         range_tree_vacate(msp->ms_tree,
3303                                             NULL, NULL);
3304                                 } else {
3305                                         range_tree_vacate(msp->ms_tree,
3306                                             zdb_leak, vd);
3307                                 }
3308
3309                                 if (msp->ms_loaded) {
3310                                         msp->ms_loaded = B_FALSE;
3311                                 }
3312                         }
3313                 }
3314
3315                 umem_free(zcb->zcb_vd_obsolete_counts,
3316                     rvd->vdev_children * sizeof (uint32_t *));
3317                 zcb->zcb_vd_obsolete_counts = NULL;
3318         }
3319         return (leaks);
3320 }
3321
3322 /* ARGSUSED */
3323 static int
3324 count_block_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
3325 {
3326         zdb_cb_t *zcb = arg;
3327
3328         if (dump_opt['b'] >= 5) {
3329                 char blkbuf[BP_SPRINTF_LEN];
3330                 snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
3331                 (void) printf("[%s] %s\n",
3332                     "deferred free", blkbuf);
3333         }
3334         zdb_count_block(zcb, NULL, bp, ZDB_OT_DEFERRED);
3335         return (0);
3336 }
3337
3338 static int
3339 dump_block_stats(spa_t *spa)
3340 {
3341         zdb_cb_t zcb;
3342         zdb_blkstats_t *zb, *tzb;
3343         uint64_t norm_alloc, norm_space, total_alloc, total_found;
3344         int flags = TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA | TRAVERSE_HARD;
3345         boolean_t leaks = B_FALSE;
3346
3347         bzero(&zcb, sizeof (zcb));
3348         (void) printf("\nTraversing all blocks %s%s%s%s%s...\n\n",
3349             (dump_opt['c'] || !dump_opt['L']) ? "to verify " : "",
3350             (dump_opt['c'] == 1) ? "metadata " : "",
3351             dump_opt['c'] ? "checksums " : "",
3352             (dump_opt['c'] && !dump_opt['L']) ? "and verify " : "",
3353             !dump_opt['L'] ? "nothing leaked " : "");
3354
3355         /*
3356          * Load all space maps as SM_ALLOC maps, then traverse the pool
3357          * claiming each block we discover.  If the pool is perfectly
3358          * consistent, the space maps will be empty when we're done.
3359          * Anything left over is a leak; any block we can't claim (because
3360          * it's not part of any space map) is a double allocation,
3361          * reference to a freed block, or an unclaimed log block.
3362          */
3363         zdb_leak_init(spa, &zcb);
3364
3365         /*
3366          * If there's a deferred-free bplist, process that first.
3367          */
3368         (void) bpobj_iterate_nofree(&spa->spa_deferred_bpobj,
3369             count_block_cb, &zcb, NULL);
3370
3371         if (spa_version(spa) >= SPA_VERSION_DEADLISTS) {
3372                 (void) bpobj_iterate_nofree(&spa->spa_dsl_pool->dp_free_bpobj,
3373                     count_block_cb, &zcb, NULL);
3374         }
3375
3376         zdb_claim_removing(spa, &zcb);
3377
3378         if (spa_feature_is_active(spa, SPA_FEATURE_ASYNC_DESTROY)) {
3379                 VERIFY3U(0, ==, bptree_iterate(spa->spa_meta_objset,
3380                     spa->spa_dsl_pool->dp_bptree_obj, B_FALSE, count_block_cb,
3381                     &zcb, NULL));
3382         }
3383
3384         if (dump_opt['c'] > 1)
3385                 flags |= TRAVERSE_PREFETCH_DATA;
3386
3387         zcb.zcb_totalasize = metaslab_class_get_alloc(spa_normal_class(spa));
3388         zcb.zcb_start = zcb.zcb_lastprint = gethrtime();
3389         zcb.zcb_haderrors |= traverse_pool(spa, 0, flags, zdb_blkptr_cb, &zcb);
3390
3391         /*
3392          * If we've traversed the data blocks then we need to wait for those
3393          * I/Os to complete. We leverage "The Godfather" zio to wait on
3394          * all async I/Os to complete.
3395          */
3396         if (dump_opt['c']) {
3397                 for (int i = 0; i < max_ncpus; i++) {
3398                         (void) zio_wait(spa->spa_async_zio_root[i]);
3399                         spa->spa_async_zio_root[i] = zio_root(spa, NULL, NULL,
3400                             ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
3401                             ZIO_FLAG_GODFATHER);
3402                 }
3403         }
3404
3405         if (zcb.zcb_haderrors) {
3406                 (void) printf("\nError counts:\n\n");
3407                 (void) printf("\t%5s  %s\n", "errno", "count");
3408                 for (int e = 0; e < 256; e++) {
3409                         if (zcb.zcb_errors[e] != 0) {
3410                                 (void) printf("\t%5d  %llu\n",
3411                                     e, (u_longlong_t)zcb.zcb_errors[e]);
3412                         }
3413                 }
3414         }
3415
3416         /*
3417          * Report any leaked segments.
3418          */
3419         leaks |= zdb_leak_fini(spa, &zcb);
3420
3421         tzb = &zcb.zcb_type[ZB_TOTAL][ZDB_OT_TOTAL];
3422
3423         norm_alloc = metaslab_class_get_alloc(spa_normal_class(spa));
3424         norm_space = metaslab_class_get_space(spa_normal_class(spa));
3425
3426         total_alloc = norm_alloc + metaslab_class_get_alloc(spa_log_class(spa));
3427         total_found = tzb->zb_asize - zcb.zcb_dedup_asize +
3428             zcb.zcb_removing_size;
3429
3430         if (total_found == total_alloc) {
3431                 if (!dump_opt['L'])
3432                         (void) printf("\n\tNo leaks (block sum matches space"
3433                             " maps exactly)\n");
3434         } else {
3435                 (void) printf("block traversal size %llu != alloc %llu "
3436                     "(%s %lld)\n",
3437                     (u_longlong_t)total_found,
3438                     (u_longlong_t)total_alloc,
3439                     (dump_opt['L']) ? "unreachable" : "leaked",
3440                     (longlong_t)(total_alloc - total_found));
3441                 leaks = B_TRUE;
3442         }
3443
3444         if (tzb->zb_count == 0)
3445                 return (2);
3446
3447         (void) printf("\n");
3448         (void) printf("\tbp count:      %10llu\n",
3449             (u_longlong_t)tzb->zb_count);
3450         (void) printf("\tganged count:  %10llu\n",
3451             (longlong_t)tzb->zb_gangs);
3452         (void) printf("\tbp logical:    %10llu      avg: %6llu\n",
3453             (u_longlong_t)tzb->zb_lsize,
3454             (u_longlong_t)(tzb->zb_lsize / tzb->zb_count));
3455         (void) printf("\tbp physical:   %10llu      avg:"
3456             " %6llu     compression: %6.2f\n",
3457             (u_longlong_t)tzb->zb_psize,
3458             (u_longlong_t)(tzb->zb_psize / tzb->zb_count),
3459             (double)tzb->zb_lsize / tzb->zb_psize);
3460         (void) printf("\tbp allocated:  %10llu      avg:"
3461             " %6llu     compression: %6.2f\n",
3462             (u_longlong_t)tzb->zb_asize,
3463             (u_longlong_t)(tzb->zb_asize / tzb->zb_count),
3464             (double)tzb->zb_lsize / tzb->zb_asize);
3465         (void) printf("\tbp deduped:    %10llu    ref>1:"
3466             " %6llu   deduplication: %6.2f\n",
3467             (u_longlong_t)zcb.zcb_dedup_asize,
3468             (u_longlong_t)zcb.zcb_dedup_blocks,
3469             (double)zcb.zcb_dedup_asize / tzb->zb_asize + 1.0);
3470         (void) printf("\tSPA allocated: %10llu     used: %5.2f%%\n",
3471             (u_longlong_t)norm_alloc, 100.0 * norm_alloc / norm_space);
3472
3473         for (bp_embedded_type_t i = 0; i < NUM_BP_EMBEDDED_TYPES; i++) {
3474                 if (zcb.zcb_embedded_blocks[i] == 0)
3475                         continue;
3476                 (void) printf("\n");
3477                 (void) printf("\tadditional, non-pointer bps of type %u: "
3478                     "%10llu\n",
3479                     i, (u_longlong_t)zcb.zcb_embedded_blocks[i]);
3480
3481                 if (dump_opt['b'] >= 3) {
3482                         (void) printf("\t number of (compressed) bytes:  "
3483                             "number of bps\n");
3484                         dump_histogram(zcb.zcb_embedded_histogram[i],
3485                             sizeof (zcb.zcb_embedded_histogram[i]) /
3486                             sizeof (zcb.zcb_embedded_histogram[i][0]), 0);
3487                 }
3488         }
3489
3490         if (tzb->zb_ditto_samevdev != 0) {
3491                 (void) printf("\tDittoed blocks on same vdev: %llu\n",
3492                     (longlong_t)tzb->zb_ditto_samevdev);
3493         }
3494
3495         for (uint64_t v = 0; v < spa->spa_root_vdev->vdev_children; v++) {
3496                 vdev_t *vd = spa->spa_root_vdev->vdev_child[v];
3497                 vdev_indirect_mapping_t *vim = vd->vdev_indirect_mapping;
3498
3499                 if (vim == NULL) {
3500                         continue;
3501                 }
3502
3503                 char mem[32];
3504                 zdb_nicenum(vdev_indirect_mapping_num_entries(vim),
3505                     mem, vdev_indirect_mapping_size(vim));
3506
3507                 (void) printf("\tindirect vdev id %llu has %llu segments "
3508                     "(%s in memory)\n",
3509                     (longlong_t)vd->vdev_id,
3510                     (longlong_t)vdev_indirect_mapping_num_entries(vim), mem);
3511         }
3512
3513         if (dump_opt['b'] >= 2) {
3514                 int l, t, level;
3515                 (void) printf("\nBlocks\tLSIZE\tPSIZE\tASIZE"
3516                     "\t  avg\t comp\t%%Total\tType\n");
3517
3518                 for (t = 0; t <= ZDB_OT_TOTAL; t++) {
3519                         char csize[32], lsize[32], psize[32], asize[32];
3520                         char avg[32], gang[32];
3521                         const char *typename;
3522
3523                         /* make sure nicenum has enough space */
3524                         CTASSERT(sizeof (csize) >= NN_NUMBUF_SZ);
3525                         CTASSERT(sizeof (lsize) >= NN_NUMBUF_SZ);
3526                         CTASSERT(sizeof (psize) >= NN_NUMBUF_SZ);
3527                         CTASSERT(sizeof (asize) >= NN_NUMBUF_SZ);
3528                         CTASSERT(sizeof (avg) >= NN_NUMBUF_SZ);
3529                         CTASSERT(sizeof (gang) >= NN_NUMBUF_SZ);
3530
3531                         if (t < DMU_OT_NUMTYPES)
3532                                 typename = dmu_ot[t].ot_name;
3533                         else
3534                                 typename = zdb_ot_extname[t - DMU_OT_NUMTYPES];
3535
3536                         if (zcb.zcb_type[ZB_TOTAL][t].zb_asize == 0) {
3537                                 (void) printf("%6s\t%5s\t%5s\t%5s"
3538                                     "\t%5s\t%5s\t%6s\t%s\n",
3539                                     "-",
3540                                     "-",
3541                                     "-",
3542                                     "-",
3543                                     "-",
3544                                     "-",
3545                                     "-",
3546                                     typename);
3547                                 continue;
3548                         }
3549
3550                         for (l = ZB_TOTAL - 1; l >= -1; l--) {
3551                                 level = (l == -1 ? ZB_TOTAL : l);
3552                                 zb = &zcb.zcb_type[level][t];
3553
3554                                 if (zb->zb_asize == 0)
3555                                         continue;
3556
3557                                 if (dump_opt['b'] < 3 && level != ZB_TOTAL)
3558                                         continue;
3559
3560                                 if (level == 0 && zb->zb_asize ==
3561                                     zcb.zcb_type[ZB_TOTAL][t].zb_asize)
3562                                         continue;
3563
3564                                 zdb_nicenum(zb->zb_count, csize,
3565                                     sizeof (csize));
3566                                 zdb_nicenum(zb->zb_lsize, lsize,
3567                                     sizeof (lsize));
3568                                 zdb_nicenum(zb->zb_psize, psize,
3569                                     sizeof (psize));
3570                                 zdb_nicenum(zb->zb_asize, asize,
3571                                     sizeof (asize));
3572                                 zdb_nicenum(zb->zb_asize / zb->zb_count, avg,
3573                                     sizeof (avg));
3574                                 zdb_nicenum(zb->zb_gangs, gang, sizeof (gang));
3575
3576                                 (void) printf("%6s\t%5s\t%5s\t%5s\t%5s"
3577                                     "\t%5.2f\t%6.2f\t",
3578                                     csize, lsize, psize, asize, avg,
3579                                     (double)zb->zb_lsize / zb->zb_psize,
3580                                     100.0 * zb->zb_asize / tzb->zb_asize);
3581
3582                                 if (level == ZB_TOTAL)
3583                                         (void) printf("%s\n", typename);
3584                                 else
3585                                         (void) printf("    L%d %s\n",
3586                                             level, typename);
3587
3588                                 if (dump_opt['b'] >= 3 && zb->zb_gangs > 0) {
3589                                         (void) printf("\t number of ganged "
3590                                             "blocks: %s\n", gang);
3591                                 }
3592
3593                                 if (dump_opt['b'] >= 4) {
3594                                         (void) printf("psize "
3595                                             "(in 512-byte sectors): "
3596                                             "number of blocks\n");
3597                                         dump_histogram(zb->zb_psize_histogram,
3598                                             PSIZE_HISTO_SIZE, 0);
3599                                 }
3600                         }
3601                 }
3602         }
3603
3604         (void) printf("\n");
3605
3606         if (leaks)
3607                 return (2);
3608
3609         if (zcb.zcb_haderrors)
3610                 return (3);
3611
3612         return (0);
3613 }
3614
3615 typedef struct zdb_ddt_entry {
3616         ddt_key_t       zdde_key;
3617         uint64_t        zdde_ref_blocks;
3618         uint64_t        zdde_ref_lsize;
3619         uint64_t        zdde_ref_psize;
3620         uint64_t        zdde_ref_dsize;
3621         avl_node_t      zdde_node;
3622 } zdb_ddt_entry_t;
3623
3624 /* ARGSUSED */
3625 static int
3626 zdb_ddt_add_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
3627     const zbookmark_phys_t *zb, const dnode_phys_t *dnp, void *arg)
3628 {
3629         avl_tree_t *t = arg;
3630         avl_index_t where;
3631         zdb_ddt_entry_t *zdde, zdde_search;
3632
3633         if (bp == NULL || BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp))
3634                 return (0);
3635
3636         if (dump_opt['S'] > 1 && zb->zb_level == ZB_ROOT_LEVEL) {
3637                 (void) printf("traversing objset %llu, %llu objects, "
3638                     "%lu blocks so far\n",
3639                     (u_longlong_t)zb->zb_objset,
3640                     (u_longlong_t)BP_GET_FILL(bp),
3641                     avl_numnodes(t));
3642         }
3643
3644         if (BP_IS_HOLE(bp) || BP_GET_CHECKSUM(bp) == ZIO_CHECKSUM_OFF ||
3645             BP_GET_LEVEL(bp) > 0 || DMU_OT_IS_METADATA(BP_GET_TYPE(bp)))
3646                 return (0);
3647
3648         ddt_key_fill(&zdde_search.zdde_key, bp);
3649
3650         zdde = avl_find(t, &zdde_search, &where);
3651
3652         if (zdde == NULL) {
3653                 zdde = umem_zalloc(sizeof (*zdde), UMEM_NOFAIL);
3654                 zdde->zdde_key = zdde_search.zdde_key;
3655                 avl_insert(t, zdde, where);
3656         }
3657
3658         zdde->zdde_ref_blocks += 1;
3659         zdde->zdde_ref_lsize += BP_GET_LSIZE(bp);
3660         zdde->zdde_ref_psize += BP_GET_PSIZE(bp);
3661         zdde->zdde_ref_dsize += bp_get_dsize_sync(spa, bp);
3662
3663         return (0);
3664 }
3665
3666 static void
3667 dump_simulated_ddt(spa_t *spa)
3668 {
3669         avl_tree_t t;
3670         void *cookie = NULL;
3671         zdb_ddt_entry_t *zdde;
3672         ddt_histogram_t ddh_total;
3673         ddt_stat_t dds_total;
3674
3675         bzero(&ddh_total, sizeof (ddh_total));
3676         bzero(&dds_total, sizeof (dds_total));
3677         avl_create(&t, ddt_entry_compare,
3678             sizeof (zdb_ddt_entry_t), offsetof(zdb_ddt_entry_t, zdde_node));
3679
3680         spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
3681
3682         (void) traverse_pool(spa, 0, TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA,
3683             zdb_ddt_add_cb, &t);
3684
3685         spa_config_exit(spa, SCL_CONFIG, FTAG);
3686
3687         while ((zdde = avl_destroy_nodes(&t, &cookie)) != NULL) {
3688                 ddt_stat_t dds;
3689                 uint64_t refcnt = zdde->zdde_ref_blocks;
3690                 ASSERT(refcnt != 0);
3691
3692                 dds.dds_blocks = zdde->zdde_ref_blocks / refcnt;
3693                 dds.dds_lsize = zdde->zdde_ref_lsize / refcnt;
3694                 dds.dds_psize = zdde->zdde_ref_psize / refcnt;
3695                 dds.dds_dsize = zdde->zdde_ref_dsize / refcnt;
3696
3697                 dds.dds_ref_blocks = zdde->zdde_ref_blocks;
3698                 dds.dds_ref_lsize = zdde->zdde_ref_lsize;
3699                 dds.dds_ref_psize = zdde->zdde_ref_psize;
3700                 dds.dds_ref_dsize = zdde->zdde_ref_dsize;
3701
3702                 ddt_stat_add(&ddh_total.ddh_stat[highbit64(refcnt) - 1],
3703                     &dds, 0);
3704
3705                 umem_free(zdde, sizeof (*zdde));
3706         }
3707
3708         avl_destroy(&t);
3709
3710         ddt_histogram_stat(&dds_total, &ddh_total);
3711
3712         (void) printf("Simulated DDT histogram:\n");
3713
3714         zpool_dump_ddt(&dds_total, &ddh_total);
3715
3716         dump_dedup_ratio(&dds_total);
3717 }
3718
3719 static int
3720 verify_device_removal_feature_counts(spa_t *spa)
3721 {
3722         uint64_t dr_feature_refcount = 0;
3723         uint64_t oc_feature_refcount = 0;
3724         uint64_t indirect_vdev_count = 0;
3725         uint64_t precise_vdev_count = 0;
3726         uint64_t obsolete_counts_object_count = 0;
3727         uint64_t obsolete_sm_count = 0;
3728         uint64_t obsolete_counts_count = 0;
3729         uint64_t scip_count = 0;
3730         uint64_t obsolete_bpobj_count = 0;
3731         int ret = 0;
3732
3733         spa_condensing_indirect_phys_t *scip =
3734             &spa->spa_condensing_indirect_phys;
3735         if (scip->scip_next_mapping_object != 0) {
3736                 vdev_t *vd = spa->spa_root_vdev->vdev_child[scip->scip_vdev];
3737                 ASSERT(scip->scip_prev_obsolete_sm_object != 0);
3738                 ASSERT3P(vd->vdev_ops, ==, &vdev_indirect_ops);
3739
3740                 (void) printf("Condensing indirect vdev %llu: new mapping "
3741                     "object %llu, prev obsolete sm %llu\n",
3742                     (u_longlong_t)scip->scip_vdev,
3743                     (u_longlong_t)scip->scip_next_mapping_object,
3744                     (u_longlong_t)scip->scip_prev_obsolete_sm_object);
3745                 if (scip->scip_prev_obsolete_sm_object != 0) {
3746                         space_map_t *prev_obsolete_sm = NULL;
3747                         VERIFY0(space_map_open(&prev_obsolete_sm,
3748                             spa->spa_meta_objset,
3749                             scip->scip_prev_obsolete_sm_object,
3750                             0, vd->vdev_asize, 0));
3751                         space_map_update(prev_obsolete_sm);
3752                         dump_spacemap(spa->spa_meta_objset, prev_obsolete_sm);
3753                         (void) printf("\n");
3754                         space_map_close(prev_obsolete_sm);
3755                 }
3756
3757                 scip_count += 2;
3758         }
3759
3760         for (uint64_t i = 0; i < spa->spa_root_vdev->vdev_children; i++) {
3761                 vdev_t *vd = spa->spa_root_vdev->vdev_child[i];
3762                 vdev_indirect_config_t *vic = &vd->vdev_indirect_config;
3763
3764                 if (vic->vic_mapping_object != 0) {
3765                         ASSERT(vd->vdev_ops == &vdev_indirect_ops ||
3766                             vd->vdev_removing);
3767                         indirect_vdev_count++;
3768
3769                         if (vd->vdev_indirect_mapping->vim_havecounts) {
3770                                 obsolete_counts_count++;
3771                         }
3772                 }
3773                 if (vdev_obsolete_counts_are_precise(vd)) {
3774                         ASSERT(vic->vic_mapping_object != 0);
3775                         precise_vdev_count++;
3776                 }
3777                 if (vdev_obsolete_sm_object(vd) != 0) {
3778                         ASSERT(vic->vic_mapping_object != 0);
3779                         obsolete_sm_count++;
3780                 }
3781         }
3782
3783         (void) feature_get_refcount(spa,
3784             &spa_feature_table[SPA_FEATURE_DEVICE_REMOVAL],
3785             &dr_feature_refcount);
3786         (void) feature_get_refcount(spa,
3787             &spa_feature_table[SPA_FEATURE_OBSOLETE_COUNTS],
3788             &oc_feature_refcount);
3789
3790         if (dr_feature_refcount != indirect_vdev_count) {
3791                 ret = 1;
3792                 (void) printf("Number of indirect vdevs (%llu) " \
3793                     "does not match feature count (%llu)\n",
3794                     (u_longlong_t)indirect_vdev_count,
3795                     (u_longlong_t)dr_feature_refcount);
3796         } else {
3797                 (void) printf("Verified device_removal feature refcount " \
3798                     "of %llu is correct\n",
3799                     (u_longlong_t)dr_feature_refcount);
3800         }
3801
3802         if (zap_contains(spa_meta_objset(spa), DMU_POOL_DIRECTORY_OBJECT,
3803             DMU_POOL_OBSOLETE_BPOBJ) == 0) {
3804                 obsolete_bpobj_count++;
3805         }
3806
3807
3808         obsolete_counts_object_count = precise_vdev_count;
3809         obsolete_counts_object_count += obsolete_sm_count;
3810         obsolete_counts_object_count += obsolete_counts_count;
3811         obsolete_counts_object_count += scip_count;
3812         obsolete_counts_object_count += obsolete_bpobj_count;
3813         obsolete_counts_object_count += remap_deadlist_count;
3814
3815         if (oc_feature_refcount != obsolete_counts_object_count) {
3816                 ret = 1;
3817                 (void) printf("Number of obsolete counts objects (%llu) " \
3818                     "does not match feature count (%llu)\n",
3819                     (u_longlong_t)obsolete_counts_object_count,
3820                     (u_longlong_t)oc_feature_refcount);
3821                 (void) printf("pv:%llu os:%llu oc:%llu sc:%llu "
3822                     "ob:%llu rd:%llu\n",
3823                     (u_longlong_t)precise_vdev_count,
3824                     (u_longlong_t)obsolete_sm_count,
3825                     (u_longlong_t)obsolete_counts_count,
3826                     (u_longlong_t)scip_count,
3827                     (u_longlong_t)obsolete_bpobj_count,
3828                     (u_longlong_t)remap_deadlist_count);
3829         } else {
3830                 (void) printf("Verified indirect_refcount feature refcount " \
3831                     "of %llu is correct\n",
3832                     (u_longlong_t)oc_feature_refcount);
3833         }
3834         return (ret);
3835 }
3836
3837 static void
3838 dump_zpool(spa_t *spa)
3839 {
3840         dsl_pool_t *dp = spa_get_dsl(spa);
3841         int rc = 0;
3842
3843         if (dump_opt['S']) {
3844                 dump_simulated_ddt(spa);
3845                 return;
3846         }
3847
3848         if (!dump_opt['e'] && dump_opt['C'] > 1) {
3849                 (void) printf("\nCached configuration:\n");
3850                 dump_nvlist(spa->spa_config, 8);
3851         }
3852
3853         if (dump_opt['C'])
3854                 dump_config(spa);
3855
3856         if (dump_opt['u'])
3857                 dump_uberblock(&spa->spa_uberblock, "\nUberblock:\n", "\n");
3858
3859         if (dump_opt['D'])
3860                 dump_all_ddts(spa);
3861
3862         if (dump_opt['d'] > 2 || dump_opt['m'])
3863                 dump_metaslabs(spa);
3864         if (dump_opt['M'])
3865                 dump_metaslab_groups(spa);
3866
3867         if (dump_opt['d'] || dump_opt['i']) {
3868                 dump_dir(dp->dp_meta_objset);
3869                 if (dump_opt['d'] >= 3) {
3870                         dsl_pool_t *dp = spa->spa_dsl_pool;
3871                         dump_full_bpobj(&spa->spa_deferred_bpobj,
3872                             "Deferred frees", 0);
3873                         if (spa_version(spa) >= SPA_VERSION_DEADLISTS) {
3874                                 dump_full_bpobj(&dp->dp_free_bpobj,
3875                                     "Pool snapshot frees", 0);
3876                         }
3877                         if (bpobj_is_open(&dp->dp_obsolete_bpobj)) {
3878                                 ASSERT(spa_feature_is_enabled(spa,
3879                                     SPA_FEATURE_DEVICE_REMOVAL));
3880                                 dump_full_bpobj(&dp->dp_obsolete_bpobj,
3881                                     "Pool obsolete blocks", 0);
3882                         }
3883
3884                         if (spa_feature_is_active(spa,
3885                             SPA_FEATURE_ASYNC_DESTROY)) {
3886                                 dump_bptree(spa->spa_meta_objset,
3887                                     dp->dp_bptree_obj,
3888                                     "Pool dataset frees");
3889                         }
3890                         dump_dtl(spa->spa_root_vdev, 0);
3891                 }
3892                 (void) dmu_objset_find(spa_name(spa), dump_one_dir,
3893                     NULL, DS_FIND_SNAPSHOTS | DS_FIND_CHILDREN);
3894
3895                 for (spa_feature_t f = 0; f < SPA_FEATURES; f++) {
3896                         uint64_t refcount;
3897
3898                         if (!(spa_feature_table[f].fi_flags &
3899                             ZFEATURE_FLAG_PER_DATASET)) {
3900                                 ASSERT0(dataset_feature_count[f]);
3901                                 continue;
3902                         }
3903                         (void) feature_get_refcount(spa,
3904                             &spa_feature_table[f], &refcount);
3905                         if (dataset_feature_count[f] != refcount) {
3906                                 (void) printf("%s feature refcount mismatch: "
3907                                     "%lld datasets != %lld refcount\n",
3908                                     spa_feature_table[f].fi_uname,
3909                                     (longlong_t)dataset_feature_count[f],
3910                                     (longlong_t)refcount);
3911                                 rc = 2;
3912                         } else {
3913                                 (void) printf("Verified %s feature refcount "
3914                                     "of %llu is correct\n",
3915                                     spa_feature_table[f].fi_uname,
3916                                     (longlong_t)refcount);
3917                         }
3918                 }
3919
3920                 if (rc == 0) {
3921                         rc = verify_device_removal_feature_counts(spa);
3922                 }
3923         }
3924         if (rc == 0 && (dump_opt['b'] || dump_opt['c']))
3925                 rc = dump_block_stats(spa);
3926
3927         if (rc == 0)
3928                 rc = verify_spacemap_refcounts(spa);
3929
3930         if (dump_opt['s'])
3931                 show_pool_stats(spa);
3932
3933         if (dump_opt['h'])
3934                 dump_history(spa);
3935
3936         if (rc != 0) {
3937                 dump_debug_buffer();
3938                 exit(rc);
3939         }
3940 }
3941
3942 #define ZDB_FLAG_CHECKSUM       0x0001
3943 #define ZDB_FLAG_DECOMPRESS     0x0002
3944 #define ZDB_FLAG_BSWAP          0x0004
3945 #define ZDB_FLAG_GBH            0x0008
3946 #define ZDB_FLAG_INDIRECT       0x0010
3947 #define ZDB_FLAG_PHYS           0x0020
3948 #define ZDB_FLAG_RAW            0x0040
3949 #define ZDB_FLAG_PRINT_BLKPTR   0x0080
3950
3951 static int flagbits[256];
3952
3953 static void
3954 zdb_print_blkptr(blkptr_t *bp, int flags)
3955 {
3956         char blkbuf[BP_SPRINTF_LEN];
3957
3958         if (flags & ZDB_FLAG_BSWAP)
3959                 byteswap_uint64_array((void *)bp, sizeof (blkptr_t));
3960
3961         snprintf_blkptr(blkbuf, sizeof (blkbuf), bp);
3962         (void) printf("%s\n", blkbuf);
3963 }
3964
3965 static void
3966 zdb_dump_indirect(blkptr_t *bp, int nbps, int flags)
3967 {
3968         int i;
3969
3970         for (i = 0; i < nbps; i++)
3971                 zdb_print_blkptr(&bp[i], flags);
3972 }
3973
3974 static void
3975 zdb_dump_gbh(void *buf, int flags)
3976 {
3977         zdb_dump_indirect((blkptr_t *)buf, SPA_GBH_NBLKPTRS, flags);
3978 }
3979
3980 static void
3981 zdb_dump_block_raw(void *buf, uint64_t size, int flags)
3982 {
3983         if (flags & ZDB_FLAG_BSWAP)
3984                 byteswap_uint64_array(buf, size);
3985         (void) write(1, buf, size);
3986 }
3987
3988 static void
3989 zdb_dump_block(char *label, void *buf, uint64_t size, int flags)
3990 {
3991         uint64_t *d = (uint64_t *)buf;
3992         unsigned nwords = size / sizeof (uint64_t);
3993         int do_bswap = !!(flags & ZDB_FLAG_BSWAP);
3994         unsigned i, j;
3995         const char *hdr;
3996         char *c;
3997
3998
3999         if (do_bswap)
4000                 hdr = " 7 6 5 4 3 2 1 0   f e d c b a 9 8";
4001         else
4002                 hdr = " 0 1 2 3 4 5 6 7   8 9 a b c d e f";
4003
4004         (void) printf("\n%s\n%6s   %s  0123456789abcdef\n", label, "", hdr);
4005
4006         for (i = 0; i < nwords; i += 2) {
4007                 (void) printf("%06llx:  %016llx  %016llx  ",
4008                     (u_longlong_t)(i * sizeof (uint64_t)),
4009                     (u_longlong_t)(do_bswap ? BSWAP_64(d[i]) : d[i]),
4010                     (u_longlong_t)(do_bswap ? BSWAP_64(d[i + 1]) : d[i + 1]));
4011
4012                 c = (char *)&d[i];
4013                 for (j = 0; j < 2 * sizeof (uint64_t); j++)
4014                         (void) printf("%c", isprint(c[j]) ? c[j] : '.');
4015                 (void) printf("\n");
4016         }
4017 }
4018
4019 /*
4020  * There are two acceptable formats:
4021  *      leaf_name         - For example: c1t0d0 or /tmp/ztest.0a
4022  *      child[.child]*    - For example: 0.1.1
4023  *
4024  * The second form can be used to specify arbitrary vdevs anywhere
4025  * in the heirarchy.  For example, in a pool with a mirror of
4026  * RAID-Zs, you can specify either RAID-Z vdev with 0.0 or 0.1 .
4027  */
4028 static vdev_t *
4029 zdb_vdev_lookup(vdev_t *vdev, const char *path)
4030 {
4031         char *s, *p, *q;
4032         unsigned i;
4033
4034         if (vdev == NULL)
4035                 return (NULL);
4036
4037         /* First, assume the x.x.x.x format */
4038         i = strtoul(path, &s, 10);
4039         if (s == path || (s && *s != '.' && *s != '\0'))
4040                 goto name;
4041         if (i >= vdev->vdev_children)
4042                 return (NULL);
4043
4044         vdev = vdev->vdev_child[i];
4045         if (*s == '\0')
4046                 return (vdev);
4047         return (zdb_vdev_lookup(vdev, s+1));
4048
4049 name:
4050         for (i = 0; i < vdev->vdev_children; i++) {
4051                 vdev_t *vc = vdev->vdev_child[i];
4052
4053                 if (vc->vdev_path == NULL) {
4054                         vc = zdb_vdev_lookup(vc, path);
4055                         if (vc == NULL)
4056                                 continue;
4057                         else
4058                                 return (vc);
4059                 }
4060
4061                 p = strrchr(vc->vdev_path, '/');
4062                 p = p ? p + 1 : vc->vdev_path;
4063                 q = &vc->vdev_path[strlen(vc->vdev_path) - 2];
4064
4065                 if (strcmp(vc->vdev_path, path) == 0)
4066                         return (vc);
4067                 if (strcmp(p, path) == 0)
4068                         return (vc);
4069                 if (strcmp(q, "s0") == 0 && strncmp(p, path, q - p) == 0)
4070                         return (vc);
4071         }
4072
4073         return (NULL);
4074 }
4075
4076 /* ARGSUSED */
4077 static int
4078 random_get_pseudo_bytes_cb(void *buf, size_t len, void *unused)
4079 {
4080         return (random_get_pseudo_bytes(buf, len));
4081 }
4082
4083 /*
4084  * Read a block from a pool and print it out.  The syntax of the
4085  * block descriptor is:
4086  *
4087  *      pool:vdev_specifier:offset:size[:flags]
4088  *
4089  *      pool           - The name of the pool you wish to read from
4090  *      vdev_specifier - Which vdev (see comment for zdb_vdev_lookup)
4091  *      offset         - offset, in hex, in bytes
4092  *      size           - Amount of data to read, in hex, in bytes
4093  *      flags          - A string of characters specifying options
4094  *               b: Decode a blkptr at given offset within block
4095  *              *c: Calculate and display checksums
4096  *               d: Decompress data before dumping
4097  *               e: Byteswap data before dumping
4098  *               g: Display data as a gang block header
4099  *               i: Display as an indirect block
4100  *               p: Do I/O to physical offset
4101  *               r: Dump raw data to stdout
4102  *
4103  *              * = not yet implemented
4104  */
4105 static void
4106 zdb_read_block(char *thing, spa_t *spa)
4107 {
4108         blkptr_t blk, *bp = &blk;
4109         dva_t *dva = bp->blk_dva;
4110         int flags = 0;
4111         uint64_t offset = 0, size = 0, psize = 0, lsize = 0, blkptr_offset = 0;
4112         zio_t *zio;
4113         vdev_t *vd;
4114         abd_t *pabd;
4115         void *lbuf, *buf;
4116         const char *s, *vdev;
4117         char *p, *dup, *flagstr;
4118         int i, error;
4119
4120         dup = strdup(thing);
4121         s = strtok(dup, ":");
4122         vdev = s ? s : "";
4123         s = strtok(NULL, ":");
4124         offset = strtoull(s ? s : "", NULL, 16);
4125         s = strtok(NULL, ":");
4126         size = strtoull(s ? s : "", NULL, 16);
4127         s = strtok(NULL, ":");
4128         if (s)
4129                 flagstr = strdup(s);
4130         else
4131                 flagstr = strdup("");
4132
4133         s = NULL;
4134         if (size == 0)
4135                 s = "size must not be zero";
4136         if (!IS_P2ALIGNED(size, DEV_BSIZE))
4137                 s = "size must be a multiple of sector size";
4138         if (!IS_P2ALIGNED(offset, DEV_BSIZE))
4139                 s = "offset must be a multiple of sector size";
4140         if (s) {
4141                 (void) printf("Invalid block specifier: %s  - %s\n", thing, s);
4142                 free(flagstr);
4143                 free(dup);
4144                 return;
4145         }
4146
4147         for (s = strtok(flagstr, ":"); s; s = strtok(NULL, ":")) {
4148                 for (i = 0; flagstr[i]; i++) {
4149                         int bit = flagbits[(uchar_t)flagstr[i]];
4150
4151                         if (bit == 0) {
4152                                 (void) printf("***Invalid flag: %c\n",
4153                                     flagstr[i]);
4154                                 continue;
4155                         }
4156                         flags |= bit;
4157
4158                         /* If it's not something with an argument, keep going */
4159                         if ((bit & (ZDB_FLAG_CHECKSUM |
4160                             ZDB_FLAG_PRINT_BLKPTR)) == 0)
4161                                 continue;
4162
4163                         p = &flagstr[i + 1];
4164                         if (bit == ZDB_FLAG_PRINT_BLKPTR)
4165                                 blkptr_offset = strtoull(p, &p, 16);
4166                         if (*p != ':' && *p != '\0') {
4167                                 (void) printf("***Invalid flag arg: '%s'\n", s);
4168                                 free(flagstr);
4169                                 free(dup);
4170                                 return;
4171                         }
4172                         i += p - &flagstr[i + 1]; /* skip over the number */
4173                 }
4174         }
4175         free(flagstr);
4176
4177         vd = zdb_vdev_lookup(spa->spa_root_vdev, vdev);
4178         if (vd == NULL) {
4179                 (void) printf("***Invalid vdev: %s\n", vdev);
4180                 free(dup);
4181                 return;
4182         } else {
4183                 if (vd->vdev_path)
4184                         (void) fprintf(stderr, "Found vdev: %s\n",
4185                             vd->vdev_path);
4186                 else
4187                         (void) fprintf(stderr, "Found vdev type: %s\n",
4188                             vd->vdev_ops->vdev_op_type);
4189         }
4190
4191         psize = size;
4192         lsize = size;
4193
4194         pabd = abd_alloc_linear(SPA_MAXBLOCKSIZE, B_FALSE);
4195         lbuf = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
4196
4197         BP_ZERO(bp);
4198
4199         DVA_SET_VDEV(&dva[0], vd->vdev_id);
4200         DVA_SET_OFFSET(&dva[0], offset);
4201         DVA_SET_GANG(&dva[0], !!(flags & ZDB_FLAG_GBH));
4202         DVA_SET_ASIZE(&dva[0], vdev_psize_to_asize(vd, psize));
4203
4204         BP_SET_BIRTH(bp, TXG_INITIAL, TXG_INITIAL);
4205
4206         BP_SET_LSIZE(bp, lsize);
4207         BP_SET_PSIZE(bp, psize);
4208         BP_SET_COMPRESS(bp, ZIO_COMPRESS_OFF);
4209         BP_SET_CHECKSUM(bp, ZIO_CHECKSUM_OFF);
4210         BP_SET_TYPE(bp, DMU_OT_NONE);
4211         BP_SET_LEVEL(bp, 0);
4212         BP_SET_DEDUP(bp, 0);
4213         BP_SET_BYTEORDER(bp, ZFS_HOST_BYTEORDER);
4214
4215         spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
4216         zio = zio_root(spa, NULL, NULL, 0);
4217
4218         if (vd == vd->vdev_top) {
4219                 /*
4220                  * Treat this as a normal block read.
4221                  */
4222                 zio_nowait(zio_read(zio, spa, bp, pabd, psize, NULL, NULL,
4223                     ZIO_PRIORITY_SYNC_READ,
4224                     ZIO_FLAG_CANFAIL | ZIO_FLAG_RAW, NULL));
4225         } else {
4226                 /*
4227                  * Treat this as a vdev child I/O.
4228                  */
4229                 zio_nowait(zio_vdev_child_io(zio, bp, vd, offset, pabd,
4230                     psize, ZIO_TYPE_READ, ZIO_PRIORITY_SYNC_READ,
4231                     ZIO_FLAG_DONT_CACHE | ZIO_FLAG_DONT_QUEUE |
4232                     ZIO_FLAG_DONT_PROPAGATE | ZIO_FLAG_DONT_RETRY |
4233                     ZIO_FLAG_CANFAIL | ZIO_FLAG_RAW | ZIO_FLAG_OPTIONAL,
4234                     NULL, NULL));
4235         }
4236
4237         error = zio_wait(zio);
4238         spa_config_exit(spa, SCL_STATE, FTAG);
4239
4240         if (error) {
4241                 (void) printf("Read of %s failed, error: %d\n", thing, error);
4242                 goto out;
4243         }
4244
4245         if (flags & ZDB_FLAG_DECOMPRESS) {
4246                 /*
4247                  * We don't know how the data was compressed, so just try
4248                  * every decompress function at every inflated blocksize.
4249                  */
4250                 enum zio_compress c;
4251                 void *pbuf2 = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
4252                 void *lbuf2 = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
4253
4254                 abd_copy_to_buf(pbuf2, pabd, psize);
4255
4256                 VERIFY0(abd_iterate_func(pabd, psize, SPA_MAXBLOCKSIZE - psize,
4257                     random_get_pseudo_bytes_cb, NULL));
4258
4259                 VERIFY0(random_get_pseudo_bytes((uint8_t *)pbuf2 + psize,
4260                     SPA_MAXBLOCKSIZE - psize));
4261
4262                 for (lsize = SPA_MAXBLOCKSIZE; lsize > psize;
4263                     lsize -= SPA_MINBLOCKSIZE) {
4264                         for (c = 0; c < ZIO_COMPRESS_FUNCTIONS; c++) {
4265                                 if (zio_decompress_data(c, pabd,
4266                                     lbuf, psize, lsize) == 0 &&
4267                                     zio_decompress_data_buf(c, pbuf2,
4268                                     lbuf2, psize, lsize) == 0 &&
4269                                     bcmp(lbuf, lbuf2, lsize) == 0)
4270                                         break;
4271                         }
4272                         if (c != ZIO_COMPRESS_FUNCTIONS)
4273                                 break;
4274                         lsize -= SPA_MINBLOCKSIZE;
4275                 }
4276
4277                 umem_free(pbuf2, SPA_MAXBLOCKSIZE);
4278                 umem_free(lbuf2, SPA_MAXBLOCKSIZE);
4279
4280                 if (lsize <= psize) {
4281                         (void) printf("Decompress of %s failed\n", thing);
4282                         goto out;
4283                 }
4284                 buf = lbuf;
4285                 size = lsize;
4286         } else {
4287                 buf = abd_to_buf(pabd);
4288                 size = psize;
4289         }
4290
4291         if (flags & ZDB_FLAG_PRINT_BLKPTR)
4292                 zdb_print_blkptr((blkptr_t *)(void *)
4293                     ((uintptr_t)buf + (uintptr_t)blkptr_offset), flags);
4294         else if (flags & ZDB_FLAG_RAW)
4295                 zdb_dump_block_raw(buf, size, flags);
4296         else if (flags & ZDB_FLAG_INDIRECT)
4297                 zdb_dump_indirect((blkptr_t *)buf, size / sizeof (blkptr_t),
4298                     flags);
4299         else if (flags & ZDB_FLAG_GBH)
4300                 zdb_dump_gbh(buf, flags);
4301         else
4302                 zdb_dump_block(thing, buf, size, flags);
4303
4304 out:
4305         abd_free(pabd);
4306         umem_free(lbuf, SPA_MAXBLOCKSIZE);
4307         free(dup);
4308 }
4309
4310 static void
4311 zdb_embedded_block(char *thing)
4312 {
4313         blkptr_t bp;
4314         unsigned long long *words = (void *)&bp;
4315         char *buf;
4316         int err;
4317
4318         bzero(&bp, sizeof (bp));
4319         err = sscanf(thing, "%llx:%llx:%llx:%llx:%llx:%llx:%llx:%llx:"
4320             "%llx:%llx:%llx:%llx:%llx:%llx:%llx:%llx",
4321             words + 0, words + 1, words + 2, words + 3,
4322             words + 4, words + 5, words + 6, words + 7,
4323             words + 8, words + 9, words + 10, words + 11,
4324             words + 12, words + 13, words + 14, words + 15);
4325         if (err != 16) {
4326                 (void) printf("invalid input format\n");
4327                 exit(1);
4328         }
4329         ASSERT3U(BPE_GET_LSIZE(&bp), <=, SPA_MAXBLOCKSIZE);
4330         buf = malloc(SPA_MAXBLOCKSIZE);
4331         if (buf == NULL) {
4332                 (void) fprintf(stderr, "%s: failed to allocate %llu bytes\n",
4333                     __func__, SPA_MAXBLOCKSIZE);
4334                 exit(1);
4335         }
4336         err = decode_embedded_bp(&bp, buf, BPE_GET_LSIZE(&bp));
4337         if (err != 0) {
4338                 (void) printf("decode failed: %u\n", err);
4339                 free(buf);
4340                 exit(1);
4341         }
4342         zdb_dump_block_raw(buf, BPE_GET_LSIZE(&bp), 0);
4343         free(buf);
4344 }
4345
4346 static boolean_t
4347 pool_match(nvlist_t *cfg, char *tgt)
4348 {
4349         uint64_t v, guid = strtoull(tgt, NULL, 0);
4350         char *s;
4351
4352         if (guid != 0) {
4353                 if (nvlist_lookup_uint64(cfg, ZPOOL_CONFIG_POOL_GUID, &v) == 0)
4354                         return (v == guid);
4355         } else {
4356                 if (nvlist_lookup_string(cfg, ZPOOL_CONFIG_POOL_NAME, &s) == 0)
4357                         return (strcmp(s, tgt) == 0);
4358         }
4359         return (B_FALSE);
4360 }
4361
4362 static char *
4363 find_zpool(char **target, nvlist_t **configp, int dirc, char **dirv)
4364 {
4365         nvlist_t *pools;
4366         nvlist_t *match = NULL;
4367         char *name = NULL;
4368         char *sepp = NULL;
4369         char sep = '\0';
4370         int count = 0;
4371         importargs_t args;
4372
4373         bzero(&args, sizeof (args));
4374         args.paths = dirc;
4375         args.path = dirv;
4376         args.can_be_active = B_TRUE;
4377
4378         if ((sepp = strpbrk(*target, "/@")) != NULL) {
4379                 sep = *sepp;
4380                 *sepp = '\0';
4381         }
4382
4383         pools = zpool_search_import(g_zfs, &args);
4384
4385         if (pools != NULL) {
4386                 nvpair_t *elem = NULL;
4387                 while ((elem = nvlist_next_nvpair(pools, elem)) != NULL) {
4388                         verify(nvpair_value_nvlist(elem, configp) == 0);
4389                         if (pool_match(*configp, *target)) {
4390                                 count++;
4391                                 if (match != NULL) {
4392                                         /* print previously found config */
4393                                         if (name != NULL) {
4394                                                 (void) printf("%s\n", name);
4395                                                 dump_nvlist(match, 8);
4396                                                 name = NULL;
4397                                         }
4398                                         (void) printf("%s\n",
4399                                             nvpair_name(elem));
4400                                         dump_nvlist(*configp, 8);
4401                                 } else {
4402                                         match = *configp;
4403                                         name = nvpair_name(elem);
4404                                 }
4405                         }
4406                 }
4407         }
4408         if (count > 1)
4409                 (void) fatal("\tMatched %d pools - use pool GUID "
4410                     "instead of pool name or \n"
4411                     "\tpool name part of a dataset name to select pool", count);
4412
4413         if (sepp)
4414                 *sepp = sep;
4415         /*
4416          * If pool GUID was specified for pool id, replace it with pool name
4417          */
4418         if (name && (strstr(*target, name) != *target)) {
4419                 int sz = 1 + strlen(name) + ((sepp) ? strlen(sepp) : 0);
4420
4421                 *target = umem_alloc(sz, UMEM_NOFAIL);
4422                 (void) snprintf(*target, sz, "%s%s", name, sepp ? sepp : "");
4423         }
4424
4425         *configp = name ? match : NULL;
4426
4427         return (name);
4428 }
4429
4430 int
4431 main(int argc, char **argv)
4432 {
4433         int c;
4434         struct rlimit rl = { 1024, 1024 };
4435         spa_t *spa = NULL;
4436         objset_t *os = NULL;
4437         int dump_all = 1;
4438         int verbose = 0;
4439         int error = 0;
4440         char **searchdirs = NULL;
4441         int nsearch = 0;
4442         char *target;
4443         nvlist_t *policy = NULL;
4444         uint64_t max_txg = UINT64_MAX;
4445         int flags = ZFS_IMPORT_MISSING_LOG;
4446         int rewind = ZPOOL_NEVER_REWIND;
4447         char *spa_config_path_env;
4448         boolean_t target_is_spa = B_TRUE;
4449
4450         (void) setrlimit(RLIMIT_NOFILE, &rl);
4451         (void) enable_extended_FILE_stdio(-1, -1);
4452
4453         dprintf_setup(&argc, argv);
4454
4455         /*
4456          * If there is an environment variable SPA_CONFIG_PATH it overrides
4457          * default spa_config_path setting. If -U flag is specified it will
4458          * override this environment variable settings once again.
4459          */
4460         spa_config_path_env = getenv("SPA_CONFIG_PATH");
4461         if (spa_config_path_env != NULL)
4462                 spa_config_path = spa_config_path_env;
4463
4464         while ((c = getopt(argc, argv,
4465             "AbcCdDeEFGhiI:lLmMo:Op:PqRsSt:uU:vVx:X")) != -1) {
4466                 switch (c) {
4467                 case 'b':
4468                 case 'c':
4469                 case 'C':
4470                 case 'd':
4471                 case 'D':
4472                 case 'E':
4473                 case 'G':
4474                 case 'h':
4475                 case 'i':
4476                 case 'l':
4477                 case 'm':
4478                 case 'M':
4479                 case 'O':
4480                 case 'R':
4481                 case 's':
4482                 case 'S':
4483                 case 'u':
4484                         dump_opt[c]++;
4485                         dump_all = 0;
4486                         break;
4487                 case 'A':
4488                 case 'e':
4489                 case 'F':
4490                 case 'L':
4491                 case 'P':
4492                 case 'q':
4493                 case 'X':
4494                         dump_opt[c]++;
4495                         break;
4496                 /* NB: Sort single match options below. */
4497                 case 'I':
4498                         max_inflight = strtoull(optarg, NULL, 0);
4499                         if (max_inflight == 0) {
4500                                 (void) fprintf(stderr, "maximum number "
4501                                     "of inflight I/Os must be greater "
4502                                     "than 0\n");
4503                                 usage();
4504                         }
4505                         break;
4506                 case 'o':
4507                         error = set_global_var(optarg);
4508                         if (error != 0)
4509                                 usage();
4510                         break;
4511                 case 'p':
4512                         if (searchdirs == NULL) {
4513                                 searchdirs = umem_alloc(sizeof (char *),
4514                                     UMEM_NOFAIL);
4515                         } else {
4516                                 char **tmp = umem_alloc((nsearch + 1) *
4517                                     sizeof (char *), UMEM_NOFAIL);
4518                                 bcopy(searchdirs, tmp, nsearch *
4519                                     sizeof (char *));
4520                                 umem_free(searchdirs,
4521                                     nsearch * sizeof (char *));
4522                                 searchdirs = tmp;
4523                         }
4524                         searchdirs[nsearch++] = optarg;
4525                         break;
4526                 case 't':
4527                         max_txg = strtoull(optarg, NULL, 0);
4528                         if (max_txg < TXG_INITIAL) {
4529                                 (void) fprintf(stderr, "incorrect txg "
4530                                     "specified: %s\n", optarg);
4531                                 usage();
4532                         }
4533                         break;
4534                 case 'U':
4535                         spa_config_path = optarg;
4536                         if (spa_config_path[0] != '/') {
4537                                 (void) fprintf(stderr,
4538                                     "cachefile must be an absolute path "
4539                                     "(i.e. start with a slash)\n");
4540                                 usage();
4541                         }
4542                         break;
4543                 case 'v':
4544                         verbose++;
4545                         break;
4546                 case 'V':
4547                         flags = ZFS_IMPORT_VERBATIM;
4548                         break;
4549                 case 'x':
4550                         vn_dumpdir = optarg;
4551                         break;
4552                 default:
4553                         usage();
4554                         break;
4555                 }
4556         }
4557
4558         if (!dump_opt['e'] && searchdirs != NULL) {
4559                 (void) fprintf(stderr, "-p option requires use of -e\n");
4560                 usage();
4561         }
4562
4563         /*
4564          * ZDB does not typically re-read blocks; therefore limit the ARC
4565          * to 256 MB, which can be used entirely for metadata.
4566          */
4567         zfs_arc_max = zfs_arc_meta_limit = 256 * 1024 * 1024;
4568
4569         /*
4570          * "zdb -c" uses checksum-verifying scrub i/os which are async reads.
4571          * "zdb -b" uses traversal prefetch which uses async reads.
4572          * For good performance, let several of them be active at once.
4573          */
4574         zfs_vdev_async_read_max_active = 10;
4575
4576         /*
4577          * Disable reference tracking for better performance.
4578          */
4579         reference_tracking_enable = B_FALSE;
4580
4581         kernel_init(FREAD);
4582         g_zfs = libzfs_init();
4583         if (g_zfs == NULL)
4584                 fatal("Fail to initialize zfs");
4585
4586         if (dump_all)
4587                 verbose = MAX(verbose, 1);
4588
4589         for (c = 0; c < 256; c++) {
4590                 if (dump_all && strchr("AeEFlLOPRSX", c) == NULL)
4591                         dump_opt[c] = 1;
4592                 if (dump_opt[c])
4593                         dump_opt[c] += verbose;
4594         }
4595
4596         aok = (dump_opt['A'] == 1) || (dump_opt['A'] > 2);
4597         zfs_recover = (dump_opt['A'] > 1);
4598
4599         argc -= optind;
4600         argv += optind;
4601
4602         if (argc < 2 && dump_opt['R'])
4603                 usage();
4604
4605         if (dump_opt['E']) {
4606                 if (argc != 1)
4607                         usage();
4608                 zdb_embedded_block(argv[0]);
4609                 return (0);
4610         }
4611
4612         if (argc < 1) {
4613                 if (!dump_opt['e'] && dump_opt['C']) {
4614                         dump_cachefile(spa_config_path);
4615                         return (0);
4616                 }
4617                 usage();
4618         }
4619
4620         if (dump_opt['l'])
4621                 return (dump_label(argv[0]));
4622
4623         if (dump_opt['O']) {
4624                 if (argc != 2)
4625                         usage();
4626                 dump_opt['v'] = verbose + 3;
4627                 return (dump_path(argv[0], argv[1]));
4628         }
4629
4630         if (dump_opt['X'] || dump_opt['F'])
4631                 rewind = ZPOOL_DO_REWIND |
4632                     (dump_opt['X'] ? ZPOOL_EXTREME_REWIND : 0);
4633
4634         if (nvlist_alloc(&policy, NV_UNIQUE_NAME_TYPE, 0) != 0 ||
4635             nvlist_add_uint64(policy, ZPOOL_REWIND_REQUEST_TXG, max_txg) != 0 ||
4636             nvlist_add_uint32(policy, ZPOOL_REWIND_REQUEST, rewind) != 0)
4637                 fatal("internal error: %s", strerror(ENOMEM));
4638
4639         error = 0;
4640         target = argv[0];
4641
4642         if (dump_opt['e']) {
4643                 nvlist_t *cfg = NULL;
4644                 char *name = find_zpool(&target, &cfg, nsearch, searchdirs);
4645
4646                 error = ENOENT;
4647                 if (name) {
4648                         if (dump_opt['C'] > 1) {
4649                                 (void) printf("\nConfiguration for import:\n");
4650                                 dump_nvlist(cfg, 8);
4651                         }
4652                         if (nvlist_add_nvlist(cfg,
4653                             ZPOOL_REWIND_POLICY, policy) != 0) {
4654                                 fatal("can't open '%s': %s",
4655                                     target, strerror(ENOMEM));
4656                         }
4657                         error = spa_import(name, cfg, NULL, flags);
4658                 }
4659         }
4660
4661         if (strpbrk(target, "/@") != NULL) {
4662                 size_t targetlen;
4663
4664                 target_is_spa = B_FALSE;
4665                 /*
4666                  * Remove any trailing slash.  Later code would get confused
4667                  * by it, but we want to allow it so that "pool/" can
4668                  * indicate that we want to dump the topmost filesystem,
4669                  * rather than the whole pool.
4670                  */
4671                 targetlen = strlen(target);
4672                 if (targetlen != 0 && target[targetlen - 1] == '/')
4673                         target[targetlen - 1] = '\0';
4674         }
4675
4676         if (error == 0) {
4677                 if (target_is_spa || dump_opt['R']) {
4678                         error = spa_open_rewind(target, &spa, FTAG, policy,
4679                             NULL);
4680                         if (error) {
4681                                 /*
4682                                  * If we're missing the log device then
4683                                  * try opening the pool after clearing the
4684                                  * log state.
4685                                  */
4686                                 mutex_enter(&spa_namespace_lock);
4687                                 if ((spa = spa_lookup(target)) != NULL &&
4688                                     spa->spa_log_state == SPA_LOG_MISSING) {
4689                                         spa->spa_log_state = SPA_LOG_CLEAR;
4690                                         error = 0;
4691                                 }
4692                                 mutex_exit(&spa_namespace_lock);
4693
4694                                 if (!error) {
4695                                         error = spa_open_rewind(target, &spa,
4696                                             FTAG, policy, NULL);
4697                                 }
4698                         }
4699                 } else {
4700                         error = open_objset(target, DMU_OST_ANY, FTAG, &os);
4701                 }
4702         }
4703         nvlist_free(policy);
4704
4705         if (error)
4706                 fatal("can't open '%s': %s", target, strerror(error));
4707
4708         argv++;
4709         argc--;
4710         if (!dump_opt['R']) {
4711                 if (argc > 0) {
4712                         zopt_objects = argc;
4713                         zopt_object = calloc(zopt_objects, sizeof (uint64_t));
4714                         for (unsigned i = 0; i < zopt_objects; i++) {
4715                                 errno = 0;
4716                                 zopt_object[i] = strtoull(argv[i], NULL, 0);
4717                                 if (zopt_object[i] == 0 && errno != 0)
4718                                         fatal("bad number %s: %s",
4719                                             argv[i], strerror(errno));
4720                         }
4721                 }
4722                 if (os != NULL) {
4723                         dump_dir(os);
4724                 } else if (zopt_objects > 0 && !dump_opt['m']) {
4725                         dump_dir(spa->spa_meta_objset);
4726                 } else {
4727                         dump_zpool(spa);
4728                 }
4729         } else {
4730                 flagbits['b'] = ZDB_FLAG_PRINT_BLKPTR;
4731                 flagbits['c'] = ZDB_FLAG_CHECKSUM;
4732                 flagbits['d'] = ZDB_FLAG_DECOMPRESS;
4733                 flagbits['e'] = ZDB_FLAG_BSWAP;
4734                 flagbits['g'] = ZDB_FLAG_GBH;
4735                 flagbits['i'] = ZDB_FLAG_INDIRECT;
4736                 flagbits['p'] = ZDB_FLAG_PHYS;
4737                 flagbits['r'] = ZDB_FLAG_RAW;
4738
4739                 for (int i = 0; i < argc; i++)
4740                         zdb_read_block(argv[i], spa);
4741         }
4742
4743         if (os != NULL)
4744                 close_objset(os, FTAG);
4745         else
4746                 spa_close(spa, FTAG);
4747
4748         fuid_table_destroy();
4749
4750         dump_debug_buffer();
4751
4752         libzfs_fini(g_zfs);
4753         kernel_fini();
4754
4755         return (0);
4756 }