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) 2013 by Delphix. All rights reserved.
  25  */
  26 
  27 #include <stdio.h>
  28 #include <unistd.h>
  29 #include <stdio_ext.h>
  30 #include <stdlib.h>
  31 #include <ctype.h>
  32 #include <sys/zfs_context.h>
  33 #include <sys/spa.h>
  34 #include <sys/spa_impl.h>
  35 #include <sys/dmu.h>
  36 #include <sys/zap.h>
  37 #include <sys/fs/zfs.h>
  38 #include <sys/zfs_znode.h>
  39 #include <sys/zfs_sa.h>
  40 #include <sys/sa.h>
  41 #include <sys/sa_impl.h>
  42 #include <sys/vdev.h>
  43 #include <sys/vdev_impl.h>
  44 #include <sys/metaslab_impl.h>
  45 #include <sys/dmu_objset.h>
  46 #include <sys/dsl_dir.h>
  47 #include <sys/dsl_dataset.h>
  48 #include <sys/dsl_pool.h>
  49 #include <sys/dbuf.h>
  50 #include <sys/zil.h>
  51 #include <sys/zil_impl.h>
  52 #include <sys/stat.h>
  53 #include <sys/resource.h>
  54 #include <sys/dmu_traverse.h>
  55 #include <sys/zio_checksum.h>
  56 #include <sys/zio_compress.h>
  57 #include <sys/zfs_fuid.h>
  58 #include <sys/arc.h>
  59 #include <sys/ddt.h>
  60 #include <sys/zfeature.h>
  61 #include <zfs_comutil.h>
  62 #undef ZFS_MAXNAMELEN
  63 #undef verify
  64 #include <libzfs.h>
  65 
  66 #define ZDB_COMPRESS_NAME(idx) ((idx) < ZIO_COMPRESS_FUNCTIONS ?     \
  67         zio_compress_table[(idx)].ci_name : "UNKNOWN")
  68 #define ZDB_CHECKSUM_NAME(idx) ((idx) < ZIO_CHECKSUM_FUNCTIONS ?     \
  69         zio_checksum_table[(idx)].ci_name : "UNKNOWN")
  70 #define ZDB_OT_NAME(idx) ((idx) < DMU_OT_NUMTYPES ?  \
  71         dmu_ot[(idx)].ot_name : DMU_OT_IS_VALID(idx) ?  \
  72         dmu_ot_byteswap[DMU_OT_BYTESWAP(idx)].ob_name : "UNKNOWN")
  73 #define ZDB_OT_TYPE(idx) ((idx) < DMU_OT_NUMTYPES ? (idx) :          \
  74         (((idx) == DMU_OTN_ZAP_DATA || (idx) == DMU_OTN_ZAP_METADATA) ? \
  75         DMU_OT_ZAP_OTHER : DMU_OT_NUMTYPES))
  76 
  77 #ifndef lint
  78 extern int zfs_recover;
  79 #else
  80 int zfs_recover;
  81 #endif
  82 
  83 const char cmdname[] = "zdb";
  84 uint8_t dump_opt[256];
  85 
  86 typedef void object_viewer_t(objset_t *, uint64_t, void *data, size_t size);
  87 
  88 extern void dump_intent_log(zilog_t *);
  89 uint64_t *zopt_object = NULL;
  90 int zopt_objects = 0;
  91 libzfs_handle_t *g_zfs;
  92 uint64_t max_inflight = 200;
  93 
  94 /*
  95  * These libumem hooks provide a reasonable set of defaults for the allocator's
  96  * debugging facilities.
  97  */
  98 const char *
  99 _umem_debug_init()
 100 {
 101         return ("default,verbose"); /* $UMEM_DEBUG setting */
 102 }
 103 
 104 const char *
 105 _umem_logging_init(void)
 106 {
 107         return ("fail,contents"); /* $UMEM_LOGGING setting */
 108 }
 109 
 110 static void
 111 usage(void)
 112 {
 113         (void) fprintf(stderr,
 114             "Usage: %s [-CumdibcsDvhLXFPA] [-t txg] [-e [-p path...]] "
 115             "[-U config] [-M inflight I/Os] poolname [object...]\n"
 116             "       %s [-divPA] [-e -p path...] [-U config] dataset "
 117             "[object...]\n"
 118             "       %s -m [-LXFPA] [-t txg] [-e [-p path...]] [-U config] "
 119             "poolname [vdev [metaslab...]]\n"
 120             "       %s -R [-A] [-e [-p path...]] poolname "
 121             "vdev:offset:size[:flags]\n"
 122             "       %s -S [-PA] [-e [-p path...]] [-U config] poolname\n"
 123             "       %s -l [-uA] device\n"
 124             "       %s -C [-A] [-U config]\n\n",
 125             cmdname, cmdname, cmdname, cmdname, cmdname, cmdname, cmdname);
 126 
 127         (void) fprintf(stderr, "    Dataset name must include at least one "
 128             "separator character '/' or '@'\n");
 129         (void) fprintf(stderr, "    If dataset name is specified, only that "
 130             "dataset is dumped\n");
 131         (void) fprintf(stderr, "    If object numbers are specified, only "
 132             "those objects are dumped\n\n");
 133         (void) fprintf(stderr, "    Options to control amount of output:\n");
 134         (void) fprintf(stderr, "        -u uberblock\n");
 135         (void) fprintf(stderr, "        -d dataset(s)\n");
 136         (void) fprintf(stderr, "        -i intent logs\n");
 137         (void) fprintf(stderr, "        -C config (or cachefile if alone)\n");
 138         (void) fprintf(stderr, "        -h pool history\n");
 139         (void) fprintf(stderr, "        -b block statistics\n");
 140         (void) fprintf(stderr, "        -m metaslabs\n");
 141         (void) fprintf(stderr, "        -c checksum all metadata (twice for "
 142             "all data) blocks\n");
 143         (void) fprintf(stderr, "        -s report stats on zdb's I/O\n");
 144         (void) fprintf(stderr, "        -D dedup statistics\n");
 145         (void) fprintf(stderr, "        -S simulate dedup to measure effect\n");
 146         (void) fprintf(stderr, "        -v verbose (applies to all others)\n");
 147         (void) fprintf(stderr, "        -l dump label contents\n");
 148         (void) fprintf(stderr, "        -L disable leak tracking (do not "
 149             "load spacemaps)\n");
 150         (void) fprintf(stderr, "        -R read and display block from a "
 151             "device\n\n");
 152         (void) fprintf(stderr, "    Below options are intended for use "
 153             "with other options (except -l):\n");
 154         (void) fprintf(stderr, "        -A ignore assertions (-A), enable "
 155             "panic recovery (-AA) or both (-AAA)\n");
 156         (void) fprintf(stderr, "        -F attempt automatic rewind within "
 157             "safe range of transaction groups\n");
 158         (void) fprintf(stderr, "        -U <cachefile_path> -- use alternate "
 159             "cachefile\n");
 160         (void) fprintf(stderr, "        -X attempt extreme rewind (does not "
 161             "work with dataset)\n");
 162         (void) fprintf(stderr, "        -e pool is exported/destroyed/"
 163             "has altroot/not in a cachefile\n");
 164         (void) fprintf(stderr, "        -p <path> -- use one or more with "
 165             "-e to specify path to vdev dir\n");
 166         (void) fprintf(stderr, "        -P print numbers in parseable form\n");
 167         (void) fprintf(stderr, "        -t <txg> -- highest txg to use when "
 168             "searching for uberblocks\n");
 169         (void) fprintf(stderr, "        -M <number of inflight I/Os> -- "
 170             "specify the maximum number of checksumming I/Os [default is 200]");
 171         (void) fprintf(stderr, "Specify an option more than once (e.g. -bb) "
 172             "to make only that option verbose\n");
 173         (void) fprintf(stderr, "Default is to dump everything non-verbosely\n");
 174         exit(1);
 175 }
 176 
 177 /*
 178  * Called for usage errors that are discovered after a call to spa_open(),
 179  * dmu_bonus_hold(), or pool_match().  abort() is called for other errors.
 180  */
 181 
 182 static void
 183 fatal(const char *fmt, ...)
 184 {
 185         va_list ap;
 186 
 187         va_start(ap, fmt);
 188         (void) fprintf(stderr, "%s: ", cmdname);
 189         (void) vfprintf(stderr, fmt, ap);
 190         va_end(ap);
 191         (void) fprintf(stderr, "\n");
 192 
 193         exit(1);
 194 }
 195 
 196 /* ARGSUSED */
 197 static void
 198 dump_packed_nvlist(objset_t *os, uint64_t object, void *data, size_t size)
 199 {
 200         nvlist_t *nv;
 201         size_t nvsize = *(uint64_t *)data;
 202         char *packed = umem_alloc(nvsize, UMEM_NOFAIL);
 203 
 204         VERIFY(0 == dmu_read(os, object, 0, nvsize, packed, DMU_READ_PREFETCH));
 205 
 206         VERIFY(nvlist_unpack(packed, nvsize, &nv, 0) == 0);
 207 
 208         umem_free(packed, nvsize);
 209 
 210         dump_nvlist(nv, 8);
 211 
 212         nvlist_free(nv);
 213 }
 214 
 215 /* ARGSUSED */
 216 static void
 217 dump_history_offsets(objset_t *os, uint64_t object, void *data, size_t size)
 218 {
 219         spa_history_phys_t *shp = data;
 220 
 221         if (shp == NULL)
 222                 return;
 223 
 224         (void) printf("\t\tpool_create_len = %llu\n",
 225             (u_longlong_t)shp->sh_pool_create_len);
 226         (void) printf("\t\tphys_max_off = %llu\n",
 227             (u_longlong_t)shp->sh_phys_max_off);
 228         (void) printf("\t\tbof = %llu\n",
 229             (u_longlong_t)shp->sh_bof);
 230         (void) printf("\t\teof = %llu\n",
 231             (u_longlong_t)shp->sh_eof);
 232         (void) printf("\t\trecords_lost = %llu\n",
 233             (u_longlong_t)shp->sh_records_lost);
 234 }
 235 
 236 static void
 237 zdb_nicenum(uint64_t num, char *buf)
 238 {
 239         if (dump_opt['P'])
 240                 (void) sprintf(buf, "%llu", (longlong_t)num);
 241         else
 242                 nicenum(num, buf);
 243 }
 244 
 245 const char histo_stars[] = "****************************************";
 246 const int histo_width = sizeof (histo_stars) - 1;
 247 
 248 static void
 249 dump_histogram(const uint64_t *histo, int size, int offset)
 250 {
 251         int i;
 252         int minidx = size - 1;
 253         int maxidx = 0;
 254         uint64_t max = 0;
 255 
 256         for (i = 0; i < size; i++) {
 257                 if (histo[i] > max)
 258                         max = histo[i];
 259                 if (histo[i] > 0 && i > maxidx)
 260                         maxidx = i;
 261                 if (histo[i] > 0 && i < minidx)
 262                         minidx = i;
 263         }
 264 
 265         if (max < histo_width)
 266                 max = histo_width;
 267 
 268         for (i = minidx; i <= maxidx; i++) {
 269                 (void) printf("\t\t\t%3u: %6llu %s\n",
 270                     i + offset, (u_longlong_t)histo[i],
 271                     &histo_stars[(max - histo[i]) * histo_width / max]);
 272         }
 273 }
 274 
 275 static void
 276 dump_zap_stats(objset_t *os, uint64_t object)
 277 {
 278         int error;
 279         zap_stats_t zs;
 280 
 281         error = zap_get_stats(os, object, &zs);
 282         if (error)
 283                 return;
 284 
 285         if (zs.zs_ptrtbl_len == 0) {
 286                 ASSERT(zs.zs_num_blocks == 1);
 287                 (void) printf("\tmicrozap: %llu bytes, %llu entries\n",
 288                     (u_longlong_t)zs.zs_blocksize,
 289                     (u_longlong_t)zs.zs_num_entries);
 290                 return;
 291         }
 292 
 293         (void) printf("\tFat ZAP stats:\n");
 294 
 295         (void) printf("\t\tPointer table:\n");
 296         (void) printf("\t\t\t%llu elements\n",
 297             (u_longlong_t)zs.zs_ptrtbl_len);
 298         (void) printf("\t\t\tzt_blk: %llu\n",
 299             (u_longlong_t)zs.zs_ptrtbl_zt_blk);
 300         (void) printf("\t\t\tzt_numblks: %llu\n",
 301             (u_longlong_t)zs.zs_ptrtbl_zt_numblks);
 302         (void) printf("\t\t\tzt_shift: %llu\n",
 303             (u_longlong_t)zs.zs_ptrtbl_zt_shift);
 304         (void) printf("\t\t\tzt_blks_copied: %llu\n",
 305             (u_longlong_t)zs.zs_ptrtbl_blks_copied);
 306         (void) printf("\t\t\tzt_nextblk: %llu\n",
 307             (u_longlong_t)zs.zs_ptrtbl_nextblk);
 308 
 309         (void) printf("\t\tZAP entries: %llu\n",
 310             (u_longlong_t)zs.zs_num_entries);
 311         (void) printf("\t\tLeaf blocks: %llu\n",
 312             (u_longlong_t)zs.zs_num_leafs);
 313         (void) printf("\t\tTotal blocks: %llu\n",
 314             (u_longlong_t)zs.zs_num_blocks);
 315         (void) printf("\t\tzap_block_type: 0x%llx\n",
 316             (u_longlong_t)zs.zs_block_type);
 317         (void) printf("\t\tzap_magic: 0x%llx\n",
 318             (u_longlong_t)zs.zs_magic);
 319         (void) printf("\t\tzap_salt: 0x%llx\n",
 320             (u_longlong_t)zs.zs_salt);
 321 
 322         (void) printf("\t\tLeafs with 2^n pointers:\n");
 323         dump_histogram(zs.zs_leafs_with_2n_pointers, ZAP_HISTOGRAM_SIZE, 0);
 324 
 325         (void) printf("\t\tBlocks with n*5 entries:\n");
 326         dump_histogram(zs.zs_blocks_with_n5_entries, ZAP_HISTOGRAM_SIZE, 0);
 327 
 328         (void) printf("\t\tBlocks n/10 full:\n");
 329         dump_histogram(zs.zs_blocks_n_tenths_full, ZAP_HISTOGRAM_SIZE, 0);
 330 
 331         (void) printf("\t\tEntries with n chunks:\n");
 332         dump_histogram(zs.zs_entries_using_n_chunks, ZAP_HISTOGRAM_SIZE, 0);
 333 
 334         (void) printf("\t\tBuckets with n entries:\n");
 335         dump_histogram(zs.zs_buckets_with_n_entries, ZAP_HISTOGRAM_SIZE, 0);
 336 }
 337 
 338 /*ARGSUSED*/
 339 static void
 340 dump_none(objset_t *os, uint64_t object, void *data, size_t size)
 341 {
 342 }
 343 
 344 /*ARGSUSED*/
 345 static void
 346 dump_unknown(objset_t *os, uint64_t object, void *data, size_t size)
 347 {
 348         (void) printf("\tUNKNOWN OBJECT TYPE\n");
 349 }
 350 
 351 /*ARGSUSED*/
 352 void
 353 dump_uint8(objset_t *os, uint64_t object, void *data, size_t size)
 354 {
 355 }
 356 
 357 /*ARGSUSED*/
 358 static void
 359 dump_uint64(objset_t *os, uint64_t object, void *data, size_t size)
 360 {
 361 }
 362 
 363 /*ARGSUSED*/
 364 static void
 365 dump_zap(objset_t *os, uint64_t object, void *data, size_t size)
 366 {
 367         zap_cursor_t zc;
 368         zap_attribute_t attr;
 369         void *prop;
 370         int i;
 371 
 372         dump_zap_stats(os, object);
 373         (void) printf("\n");
 374 
 375         for (zap_cursor_init(&zc, os, object);
 376             zap_cursor_retrieve(&zc, &attr) == 0;
 377             zap_cursor_advance(&zc)) {
 378                 (void) printf("\t\t%s = ", attr.za_name);
 379                 if (attr.za_num_integers == 0) {
 380                         (void) printf("\n");
 381                         continue;
 382                 }
 383                 prop = umem_zalloc(attr.za_num_integers *
 384                     attr.za_integer_length, UMEM_NOFAIL);
 385                 (void) zap_lookup(os, object, attr.za_name,
 386                     attr.za_integer_length, attr.za_num_integers, prop);
 387                 if (attr.za_integer_length == 1) {
 388                         (void) printf("%s", (char *)prop);
 389                 } else {
 390                         for (i = 0; i < attr.za_num_integers; i++) {
 391                                 switch (attr.za_integer_length) {
 392                                 case 2:
 393                                         (void) printf("%u ",
 394                                             ((uint16_t *)prop)[i]);
 395                                         break;
 396                                 case 4:
 397                                         (void) printf("%u ",
 398                                             ((uint32_t *)prop)[i]);
 399                                         break;
 400                                 case 8:
 401                                         (void) printf("%lld ",
 402                                             (u_longlong_t)((int64_t *)prop)[i]);
 403                                         break;
 404                                 }
 405                         }
 406                 }
 407                 (void) printf("\n");
 408                 umem_free(prop, attr.za_num_integers * attr.za_integer_length);
 409         }
 410         zap_cursor_fini(&zc);
 411 }
 412 
 413 /*ARGSUSED*/
 414 static void
 415 dump_ddt_zap(objset_t *os, uint64_t object, void *data, size_t size)
 416 {
 417         dump_zap_stats(os, object);
 418         /* contents are printed elsewhere, properly decoded */
 419 }
 420 
 421 /*ARGSUSED*/
 422 static void
 423 dump_sa_attrs(objset_t *os, uint64_t object, void *data, size_t size)
 424 {
 425         zap_cursor_t zc;
 426         zap_attribute_t attr;
 427 
 428         dump_zap_stats(os, object);
 429         (void) printf("\n");
 430 
 431         for (zap_cursor_init(&zc, os, object);
 432             zap_cursor_retrieve(&zc, &attr) == 0;
 433             zap_cursor_advance(&zc)) {
 434                 (void) printf("\t\t%s = ", attr.za_name);
 435                 if (attr.za_num_integers == 0) {
 436                         (void) printf("\n");
 437                         continue;
 438                 }
 439                 (void) printf(" %llx : [%d:%d:%d]\n",
 440                     (u_longlong_t)attr.za_first_integer,
 441                     (int)ATTR_LENGTH(attr.za_first_integer),
 442                     (int)ATTR_BSWAP(attr.za_first_integer),
 443                     (int)ATTR_NUM(attr.za_first_integer));
 444         }
 445         zap_cursor_fini(&zc);
 446 }
 447 
 448 /*ARGSUSED*/
 449 static void
 450 dump_sa_layouts(objset_t *os, uint64_t object, void *data, size_t size)
 451 {
 452         zap_cursor_t zc;
 453         zap_attribute_t attr;
 454         uint16_t *layout_attrs;
 455         int i;
 456 
 457         dump_zap_stats(os, object);
 458         (void) printf("\n");
 459 
 460         for (zap_cursor_init(&zc, os, object);
 461             zap_cursor_retrieve(&zc, &attr) == 0;
 462             zap_cursor_advance(&zc)) {
 463                 (void) printf("\t\t%s = [", attr.za_name);
 464                 if (attr.za_num_integers == 0) {
 465                         (void) printf("\n");
 466                         continue;
 467                 }
 468 
 469                 VERIFY(attr.za_integer_length == 2);
 470                 layout_attrs = umem_zalloc(attr.za_num_integers *
 471                     attr.za_integer_length, UMEM_NOFAIL);
 472 
 473                 VERIFY(zap_lookup(os, object, attr.za_name,
 474                     attr.za_integer_length,
 475                     attr.za_num_integers, layout_attrs) == 0);
 476 
 477                 for (i = 0; i != attr.za_num_integers; i++)
 478                         (void) printf(" %d ", (int)layout_attrs[i]);
 479                 (void) printf("]\n");
 480                 umem_free(layout_attrs,
 481                     attr.za_num_integers * attr.za_integer_length);
 482         }
 483         zap_cursor_fini(&zc);
 484 }
 485 
 486 /*ARGSUSED*/
 487 static void
 488 dump_zpldir(objset_t *os, uint64_t object, void *data, size_t size)
 489 {
 490         zap_cursor_t zc;
 491         zap_attribute_t attr;
 492         const char *typenames[] = {
 493                 /* 0 */ "not specified",
 494                 /* 1 */ "FIFO",
 495                 /* 2 */ "Character Device",
 496                 /* 3 */ "3 (invalid)",
 497                 /* 4 */ "Directory",
 498                 /* 5 */ "5 (invalid)",
 499                 /* 6 */ "Block Device",
 500                 /* 7 */ "7 (invalid)",
 501                 /* 8 */ "Regular File",
 502                 /* 9 */ "9 (invalid)",
 503                 /* 10 */ "Symbolic Link",
 504                 /* 11 */ "11 (invalid)",
 505                 /* 12 */ "Socket",
 506                 /* 13 */ "Door",
 507                 /* 14 */ "Event Port",
 508                 /* 15 */ "15 (invalid)",
 509         };
 510 
 511         dump_zap_stats(os, object);
 512         (void) printf("\n");
 513 
 514         for (zap_cursor_init(&zc, os, object);
 515             zap_cursor_retrieve(&zc, &attr) == 0;
 516             zap_cursor_advance(&zc)) {
 517                 (void) printf("\t\t%s = %lld (type: %s)\n",
 518                     attr.za_name, ZFS_DIRENT_OBJ(attr.za_first_integer),
 519                     typenames[ZFS_DIRENT_TYPE(attr.za_first_integer)]);
 520         }
 521         zap_cursor_fini(&zc);
 522 }
 523 
 524 int
 525 get_dtl_refcount(vdev_t *vd)
 526 {
 527         int refcount = 0;
 528 
 529         if (vd->vdev_ops->vdev_op_leaf) {
 530                 space_map_t *sm = vd->vdev_dtl_sm;
 531 
 532                 if (sm != NULL &&
 533                     sm->sm_dbuf->db_size == sizeof (space_map_phys_t))
 534                         return (1);
 535                 return (0);
 536         }
 537 
 538         for (int c = 0; c < vd->vdev_children; c++)
 539                 refcount += get_dtl_refcount(vd->vdev_child[c]);
 540         return (refcount);
 541 }
 542 
 543 int
 544 get_metaslab_refcount(vdev_t *vd)
 545 {
 546         int refcount = 0;
 547 
 548         if (vd->vdev_top == vd) {
 549                 for (int m = 0; m < vd->vdev_ms_count; m++) {
 550                         space_map_t *sm = vd->vdev_ms[m]->ms_sm;
 551 
 552                         if (sm != NULL &&
 553                             sm->sm_dbuf->db_size == sizeof (space_map_phys_t))
 554                                 refcount++;
 555                 }
 556         }
 557         for (int c = 0; c < vd->vdev_children; c++)
 558                 refcount += get_metaslab_refcount(vd->vdev_child[c]);
 559 
 560         return (refcount);
 561 }
 562 
 563 static int
 564 verify_spacemap_refcounts(spa_t *spa)
 565 {
 566         uint64_t expected_refcount = 0;
 567         uint64_t actual_refcount;
 568 
 569         (void) feature_get_refcount(spa,
 570             &spa_feature_table[SPA_FEATURE_SPACEMAP_HISTOGRAM],
 571             &expected_refcount);
 572         actual_refcount = get_dtl_refcount(spa->spa_root_vdev);
 573         actual_refcount += get_metaslab_refcount(spa->spa_root_vdev);
 574 
 575         if (expected_refcount != actual_refcount) {
 576                 (void) printf("space map refcount mismatch: expected %lld != "
 577                     "actual %lld\n",
 578                     (longlong_t)expected_refcount,
 579                     (longlong_t)actual_refcount);
 580                 return (2);
 581         }
 582         return (0);
 583 }
 584 
 585 static void
 586 dump_spacemap(objset_t *os, space_map_t *sm)
 587 {
 588         uint64_t alloc, offset, entry;
 589         char *ddata[] = { "ALLOC", "FREE", "CONDENSE", "INVALID",
 590                             "INVALID", "INVALID", "INVALID", "INVALID" };
 591 
 592         if (sm == NULL)
 593                 return;
 594 
 595         /*
 596          * Print out the freelist entries in both encoded and decoded form.
 597          */
 598         alloc = 0;
 599         for (offset = 0; offset < space_map_length(sm);
 600             offset += sizeof (entry)) {
 601                 uint8_t mapshift = sm->sm_shift;
 602 
 603                 VERIFY0(dmu_read(os, space_map_object(sm), offset,
 604                     sizeof (entry), &entry, DMU_READ_PREFETCH));
 605                 if (SM_DEBUG_DECODE(entry)) {
 606 
 607                         (void) printf("\t    [%6llu] %s: txg %llu, pass %llu\n",
 608                             (u_longlong_t)(offset / sizeof (entry)),
 609                             ddata[SM_DEBUG_ACTION_DECODE(entry)],
 610                             (u_longlong_t)SM_DEBUG_TXG_DECODE(entry),
 611                             (u_longlong_t)SM_DEBUG_SYNCPASS_DECODE(entry));
 612                 } else {
 613                         (void) printf("\t    [%6llu]    %c  range:"
 614                             " %010llx-%010llx  size: %06llx\n",
 615                             (u_longlong_t)(offset / sizeof (entry)),
 616                             SM_TYPE_DECODE(entry) == SM_ALLOC ? 'A' : 'F',
 617                             (u_longlong_t)((SM_OFFSET_DECODE(entry) <<
 618                             mapshift) + sm->sm_start),
 619                             (u_longlong_t)((SM_OFFSET_DECODE(entry) <<
 620                             mapshift) + sm->sm_start +
 621                             (SM_RUN_DECODE(entry) << mapshift)),
 622                             (u_longlong_t)(SM_RUN_DECODE(entry) << mapshift));
 623                         if (SM_TYPE_DECODE(entry) == SM_ALLOC)
 624                                 alloc += SM_RUN_DECODE(entry) << mapshift;
 625                         else
 626                                 alloc -= SM_RUN_DECODE(entry) << mapshift;
 627                 }
 628         }
 629         if (alloc != space_map_allocated(sm)) {
 630                 (void) printf("space_map_object alloc (%llu) INCONSISTENT "
 631                     "with space map summary (%llu)\n",
 632                     (u_longlong_t)space_map_allocated(sm), (u_longlong_t)alloc);
 633         }
 634 }
 635 
 636 static void
 637 dump_metaslab_stats(metaslab_t *msp)
 638 {
 639         char maxbuf[32];
 640         range_tree_t *rt = msp->ms_tree;
 641         avl_tree_t *t = &msp->ms_size_tree;
 642         int free_pct = range_tree_space(rt) * 100 / msp->ms_size;
 643 
 644         zdb_nicenum(metaslab_block_maxsize(msp), maxbuf);
 645 
 646         (void) printf("\t %25s %10lu   %7s  %6s   %4s %4d%%\n",
 647             "segments", avl_numnodes(t), "maxsize", maxbuf,
 648             "freepct", free_pct);
 649         (void) printf("\tIn-memory histogram:\n");
 650         dump_histogram(rt->rt_histogram, RANGE_TREE_HISTOGRAM_SIZE, 0);
 651 }
 652 
 653 static void
 654 dump_metaslab(metaslab_t *msp)
 655 {
 656         vdev_t *vd = msp->ms_group->mg_vd;
 657         spa_t *spa = vd->vdev_spa;
 658         space_map_t *sm = msp->ms_sm;
 659         char freebuf[32];
 660 
 661         zdb_nicenum(msp->ms_size - space_map_allocated(sm), freebuf);
 662 
 663         (void) printf(
 664             "\tmetaslab %6llu   offset %12llx   spacemap %6llu   free    %5s\n",
 665             (u_longlong_t)msp->ms_id, (u_longlong_t)msp->ms_start,
 666             (u_longlong_t)space_map_object(sm), freebuf);
 667 
 668         if (dump_opt['m'] > 2 && !dump_opt['L']) {
 669                 mutex_enter(&msp->ms_lock);
 670                 metaslab_load_wait(msp);
 671                 if (!msp->ms_loaded) {
 672                         VERIFY0(metaslab_load(msp));
 673                         range_tree_stat_verify(msp->ms_tree);
 674                 }
 675                 dump_metaslab_stats(msp);
 676                 metaslab_unload(msp);
 677                 mutex_exit(&msp->ms_lock);
 678         }
 679 
 680         if (dump_opt['m'] > 1 && sm != NULL &&
 681             spa_feature_is_active(spa, SPA_FEATURE_SPACEMAP_HISTOGRAM)) {
 682                 /*
 683                  * The space map histogram represents free space in chunks
 684                  * of sm_shift (i.e. bucket 0 refers to 2^sm_shift).
 685                  */
 686                 (void) printf("\tOn-disk histogram:\n");
 687                 dump_histogram(sm->sm_phys->smp_histogram,
 688                     SPACE_MAP_HISTOGRAM_SIZE(sm), sm->sm_shift);
 689         }
 690 
 691         if (dump_opt['d'] > 5 || dump_opt['m'] > 3) {
 692                 ASSERT(msp->ms_size == (1ULL << vd->vdev_ms_shift));
 693 
 694                 mutex_enter(&msp->ms_lock);
 695                 dump_spacemap(spa->spa_meta_objset, msp->ms_sm);
 696                 mutex_exit(&msp->ms_lock);
 697         }
 698 }
 699 
 700 static void
 701 print_vdev_metaslab_header(vdev_t *vd)
 702 {
 703         (void) printf("\tvdev %10llu\n\t%-10s%5llu   %-19s   %-15s   %-10s\n",
 704             (u_longlong_t)vd->vdev_id,
 705             "metaslabs", (u_longlong_t)vd->vdev_ms_count,
 706             "offset", "spacemap", "free");
 707         (void) printf("\t%15s   %19s   %15s   %10s\n",
 708             "---------------", "-------------------",
 709             "---------------", "-------------");
 710 }
 711 
 712 static void
 713 dump_metaslabs(spa_t *spa)
 714 {
 715         vdev_t *vd, *rvd = spa->spa_root_vdev;
 716         uint64_t m, c = 0, children = rvd->vdev_children;
 717 
 718         (void) printf("\nMetaslabs:\n");
 719 
 720         if (!dump_opt['d'] && zopt_objects > 0) {
 721                 c = zopt_object[0];
 722 
 723                 if (c >= children)
 724                         (void) fatal("bad vdev id: %llu", (u_longlong_t)c);
 725 
 726                 if (zopt_objects > 1) {
 727                         vd = rvd->vdev_child[c];
 728                         print_vdev_metaslab_header(vd);
 729 
 730                         for (m = 1; m < zopt_objects; m++) {
 731                                 if (zopt_object[m] < vd->vdev_ms_count)
 732                                         dump_metaslab(
 733                                             vd->vdev_ms[zopt_object[m]]);
 734                                 else
 735                                         (void) fprintf(stderr, "bad metaslab "
 736                                             "number %llu\n",
 737                                             (u_longlong_t)zopt_object[m]);
 738                         }
 739                         (void) printf("\n");
 740                         return;
 741                 }
 742                 children = c + 1;
 743         }
 744         for (; c < children; c++) {
 745                 vd = rvd->vdev_child[c];
 746                 print_vdev_metaslab_header(vd);
 747 
 748                 for (m = 0; m < vd->vdev_ms_count; m++)
 749                         dump_metaslab(vd->vdev_ms[m]);
 750                 (void) printf("\n");
 751         }
 752 }
 753 
 754 static void
 755 dump_dde(const ddt_t *ddt, const ddt_entry_t *dde, uint64_t index)
 756 {
 757         const ddt_phys_t *ddp = dde->dde_phys;
 758         const ddt_key_t *ddk = &dde->dde_key;
 759         char *types[4] = { "ditto", "single", "double", "triple" };
 760         char blkbuf[BP_SPRINTF_LEN];
 761         blkptr_t blk;
 762 
 763         for (int p = 0; p < DDT_PHYS_TYPES; p++, ddp++) {
 764                 if (ddp->ddp_phys_birth == 0)
 765                         continue;
 766                 ddt_bp_create(ddt->ddt_checksum, ddk, ddp, &blk);
 767                 sprintf_blkptr(blkbuf, &blk);
 768                 (void) printf("index %llx refcnt %llu %s %s\n",
 769                     (u_longlong_t)index, (u_longlong_t)ddp->ddp_refcnt,
 770                     types[p], blkbuf);
 771         }
 772 }
 773 
 774 static void
 775 dump_dedup_ratio(const ddt_stat_t *dds)
 776 {
 777         double rL, rP, rD, D, dedup, compress, copies;
 778 
 779         if (dds->dds_blocks == 0)
 780                 return;
 781 
 782         rL = (double)dds->dds_ref_lsize;
 783         rP = (double)dds->dds_ref_psize;
 784         rD = (double)dds->dds_ref_dsize;
 785         D = (double)dds->dds_dsize;
 786 
 787         dedup = rD / D;
 788         compress = rL / rP;
 789         copies = rD / rP;
 790 
 791         (void) printf("dedup = %.2f, compress = %.2f, copies = %.2f, "
 792             "dedup * compress / copies = %.2f\n\n",
 793             dedup, compress, copies, dedup * compress / copies);
 794 }
 795 
 796 static void
 797 dump_ddt(ddt_t *ddt, enum ddt_type type, enum ddt_class class)
 798 {
 799         char name[DDT_NAMELEN];
 800         ddt_entry_t dde;
 801         uint64_t walk = 0;
 802         dmu_object_info_t doi;
 803         uint64_t count, dspace, mspace;
 804         int error;
 805 
 806         error = ddt_object_info(ddt, type, class, &doi);
 807 
 808         if (error == ENOENT)
 809                 return;
 810         ASSERT(error == 0);
 811 
 812         if ((count = ddt_object_count(ddt, type, class)) == 0)
 813                 return;
 814 
 815         dspace = doi.doi_physical_blocks_512 << 9;
 816         mspace = doi.doi_fill_count * doi.doi_data_block_size;
 817 
 818         ddt_object_name(ddt, type, class, name);
 819 
 820         (void) printf("%s: %llu entries, size %llu on disk, %llu in core\n",
 821             name,
 822             (u_longlong_t)count,
 823             (u_longlong_t)(dspace / count),
 824             (u_longlong_t)(mspace / count));
 825 
 826         if (dump_opt['D'] < 3)
 827                 return;
 828 
 829         zpool_dump_ddt(NULL, &ddt->ddt_histogram[type][class]);
 830 
 831         if (dump_opt['D'] < 4)
 832                 return;
 833 
 834         if (dump_opt['D'] < 5 && class == DDT_CLASS_UNIQUE)
 835                 return;
 836 
 837         (void) printf("%s contents:\n\n", name);
 838 
 839         while ((error = ddt_object_walk(ddt, type, class, &walk, &dde)) == 0)
 840                 dump_dde(ddt, &dde, walk);
 841 
 842         ASSERT(error == ENOENT);
 843 
 844         (void) printf("\n");
 845 }
 846 
 847 static void
 848 dump_all_ddts(spa_t *spa)
 849 {
 850         ddt_histogram_t ddh_total = { 0 };
 851         ddt_stat_t dds_total = { 0 };
 852 
 853         for (enum zio_checksum c = 0; c < ZIO_CHECKSUM_FUNCTIONS; c++) {
 854                 ddt_t *ddt = spa->spa_ddt[c];
 855                 for (enum ddt_type type = 0; type < DDT_TYPES; type++) {
 856                         for (enum ddt_class class = 0; class < DDT_CLASSES;
 857                             class++) {
 858                                 dump_ddt(ddt, type, class);
 859                         }
 860                 }
 861         }
 862 
 863         ddt_get_dedup_stats(spa, &dds_total);
 864 
 865         if (dds_total.dds_blocks == 0) {
 866                 (void) printf("All DDTs are empty\n");
 867                 return;
 868         }
 869 
 870         (void) printf("\n");
 871 
 872         if (dump_opt['D'] > 1) {
 873                 (void) printf("DDT histogram (aggregated over all DDTs):\n");
 874                 ddt_get_dedup_histogram(spa, &ddh_total);
 875                 zpool_dump_ddt(&dds_total, &ddh_total);
 876         }
 877 
 878         dump_dedup_ratio(&dds_total);
 879 }
 880 
 881 static void
 882 dump_dtl_seg(void *arg, uint64_t start, uint64_t size)
 883 {
 884         char *prefix = arg;
 885 
 886         (void) printf("%s [%llu,%llu) length %llu\n",
 887             prefix,
 888             (u_longlong_t)start,
 889             (u_longlong_t)(start + size),
 890             (u_longlong_t)(size));
 891 }
 892 
 893 static void
 894 dump_dtl(vdev_t *vd, int indent)
 895 {
 896         spa_t *spa = vd->vdev_spa;
 897         boolean_t required;
 898         char *name[DTL_TYPES] = { "missing", "partial", "scrub", "outage" };
 899         char prefix[256];
 900 
 901         spa_vdev_state_enter(spa, SCL_NONE);
 902         required = vdev_dtl_required(vd);
 903         (void) spa_vdev_state_exit(spa, NULL, 0);
 904 
 905         if (indent == 0)
 906                 (void) printf("\nDirty time logs:\n\n");
 907 
 908         (void) printf("\t%*s%s [%s]\n", indent, "",
 909             vd->vdev_path ? vd->vdev_path :
 910             vd->vdev_parent ? vd->vdev_ops->vdev_op_type : spa_name(spa),
 911             required ? "DTL-required" : "DTL-expendable");
 912 
 913         for (int t = 0; t < DTL_TYPES; t++) {
 914                 range_tree_t *rt = vd->vdev_dtl[t];
 915                 if (range_tree_space(rt) == 0)
 916                         continue;
 917                 (void) snprintf(prefix, sizeof (prefix), "\t%*s%s",
 918                     indent + 2, "", name[t]);
 919                 mutex_enter(rt->rt_lock);
 920                 range_tree_walk(rt, dump_dtl_seg, prefix);
 921                 mutex_exit(rt->rt_lock);
 922                 if (dump_opt['d'] > 5 && vd->vdev_children == 0)
 923                         dump_spacemap(spa->spa_meta_objset, vd->vdev_dtl_sm);
 924         }
 925 
 926         for (int c = 0; c < vd->vdev_children; c++)
 927                 dump_dtl(vd->vdev_child[c], indent + 4);
 928 }
 929 
 930 static void
 931 dump_history(spa_t *spa)
 932 {
 933         nvlist_t **events = NULL;
 934         char buf[SPA_MAXBLOCKSIZE];
 935         uint64_t resid, len, off = 0;
 936         uint_t num = 0;
 937         int error;
 938         time_t tsec;
 939         struct tm t;
 940         char tbuf[30];
 941         char internalstr[MAXPATHLEN];
 942 
 943         do {
 944                 len = sizeof (buf);
 945 
 946                 if ((error = spa_history_get(spa, &off, &len, buf)) != 0) {
 947                         (void) fprintf(stderr, "Unable to read history: "
 948                             "error %d\n", error);
 949                         return;
 950                 }
 951 
 952                 if (zpool_history_unpack(buf, len, &resid, &events, &num) != 0)
 953                         break;
 954 
 955                 off -= resid;
 956         } while (len != 0);
 957 
 958         (void) printf("\nHistory:\n");
 959         for (int i = 0; i < num; i++) {
 960                 uint64_t time, txg, ievent;
 961                 char *cmd, *intstr;
 962                 boolean_t printed = B_FALSE;
 963 
 964                 if (nvlist_lookup_uint64(events[i], ZPOOL_HIST_TIME,
 965                     &time) != 0)
 966                         goto next;
 967                 if (nvlist_lookup_string(events[i], ZPOOL_HIST_CMD,
 968                     &cmd) != 0) {
 969                         if (nvlist_lookup_uint64(events[i],
 970                             ZPOOL_HIST_INT_EVENT, &ievent) != 0)
 971                                 goto next;
 972                         verify(nvlist_lookup_uint64(events[i],
 973                             ZPOOL_HIST_TXG, &txg) == 0);
 974                         verify(nvlist_lookup_string(events[i],
 975                             ZPOOL_HIST_INT_STR, &intstr) == 0);
 976                         if (ievent >= ZFS_NUM_LEGACY_HISTORY_EVENTS)
 977                                 goto next;
 978 
 979                         (void) snprintf(internalstr,
 980                             sizeof (internalstr),
 981                             "[internal %s txg:%lld] %s",
 982                             zfs_history_event_names[ievent], txg,
 983                             intstr);
 984                         cmd = internalstr;
 985                 }
 986                 tsec = time;
 987                 (void) localtime_r(&tsec, &t);
 988                 (void) strftime(tbuf, sizeof (tbuf), "%F.%T", &t);
 989                 (void) printf("%s %s\n", tbuf, cmd);
 990                 printed = B_TRUE;
 991 
 992 next:
 993                 if (dump_opt['h'] > 1) {
 994                         if (!printed)
 995                                 (void) printf("unrecognized record:\n");
 996                         dump_nvlist(events[i], 2);
 997                 }
 998         }
 999 }
1000 
1001 /*ARGSUSED*/
1002 static void
1003 dump_dnode(objset_t *os, uint64_t object, void *data, size_t size)
1004 {
1005 }
1006 
1007 static uint64_t
1008 blkid2offset(const dnode_phys_t *dnp, const blkptr_t *bp, const zbookmark_t *zb)
1009 {
1010         if (dnp == NULL) {
1011                 ASSERT(zb->zb_level < 0);
1012                 if (zb->zb_object == 0)
1013                         return (zb->zb_blkid);
1014                 return (zb->zb_blkid * BP_GET_LSIZE(bp));
1015         }
1016 
1017         ASSERT(zb->zb_level >= 0);
1018 
1019         return ((zb->zb_blkid <<
1020             (zb->zb_level * (dnp->dn_indblkshift - SPA_BLKPTRSHIFT))) *
1021             dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT);
1022 }
1023 
1024 static void
1025 sprintf_blkptr_compact(char *blkbuf, const blkptr_t *bp)
1026 {
1027         const dva_t *dva = bp->blk_dva;
1028         int ndvas = dump_opt['d'] > 5 ? BP_GET_NDVAS(bp) : 1;
1029 
1030         if (dump_opt['b'] >= 6) {
1031                 sprintf_blkptr(blkbuf, bp);
1032                 return;
1033         }
1034 
1035         blkbuf[0] = '\0';
1036 
1037         for (int i = 0; i < ndvas; i++)
1038                 (void) sprintf(blkbuf + strlen(blkbuf), "%llu:%llx:%llx ",
1039                     (u_longlong_t)DVA_GET_VDEV(&dva[i]),
1040                     (u_longlong_t)DVA_GET_OFFSET(&dva[i]),
1041                     (u_longlong_t)DVA_GET_ASIZE(&dva[i]));
1042 
1043         (void) sprintf(blkbuf + strlen(blkbuf),
1044             "%llxL/%llxP F=%llu B=%llu/%llu",
1045             (u_longlong_t)BP_GET_LSIZE(bp),
1046             (u_longlong_t)BP_GET_PSIZE(bp),
1047             (u_longlong_t)bp->blk_fill,
1048             (u_longlong_t)bp->blk_birth,
1049             (u_longlong_t)BP_PHYSICAL_BIRTH(bp));
1050 }
1051 
1052 static void
1053 print_indirect(blkptr_t *bp, const zbookmark_t *zb,
1054     const dnode_phys_t *dnp)
1055 {
1056         char blkbuf[BP_SPRINTF_LEN];
1057         int l;
1058 
1059         ASSERT3U(BP_GET_TYPE(bp), ==, dnp->dn_type);
1060         ASSERT3U(BP_GET_LEVEL(bp), ==, zb->zb_level);
1061 
1062         (void) printf("%16llx ", (u_longlong_t)blkid2offset(dnp, bp, zb));
1063 
1064         ASSERT(zb->zb_level >= 0);
1065 
1066         for (l = dnp->dn_nlevels - 1; l >= -1; l--) {
1067                 if (l == zb->zb_level) {
1068                         (void) printf("L%llx", (u_longlong_t)zb->zb_level);
1069                 } else {
1070                         (void) printf(" ");
1071                 }
1072         }
1073 
1074         sprintf_blkptr_compact(blkbuf, bp);
1075         (void) printf("%s\n", blkbuf);
1076 }
1077 
1078 static int
1079 visit_indirect(spa_t *spa, const dnode_phys_t *dnp,
1080     blkptr_t *bp, const zbookmark_t *zb)
1081 {
1082         int err = 0;
1083 
1084         if (bp->blk_birth == 0)
1085                 return (0);
1086 
1087         print_indirect(bp, zb, dnp);
1088 
1089         if (BP_GET_LEVEL(bp) > 0) {
1090                 uint32_t flags = ARC_WAIT;
1091                 int i;
1092                 blkptr_t *cbp;
1093                 int epb = BP_GET_LSIZE(bp) >> SPA_BLKPTRSHIFT;
1094                 arc_buf_t *buf;
1095                 uint64_t fill = 0;
1096 
1097                 err = arc_read(NULL, spa, bp, arc_getbuf_func, &buf,
1098                     ZIO_PRIORITY_ASYNC_READ, ZIO_FLAG_CANFAIL, &flags, zb);
1099                 if (err)
1100                         return (err);
1101                 ASSERT(buf->b_data);
1102 
1103                 /* recursively visit blocks below this */
1104                 cbp = buf->b_data;
1105                 for (i = 0; i < epb; i++, cbp++) {
1106                         zbookmark_t czb;
1107 
1108                         SET_BOOKMARK(&czb, zb->zb_objset, zb->zb_object,
1109                             zb->zb_level - 1,
1110                             zb->zb_blkid * epb + i);
1111                         err = visit_indirect(spa, dnp, cbp, &czb);
1112                         if (err)
1113                                 break;
1114                         fill += cbp->blk_fill;
1115                 }
1116                 if (!err)
1117                         ASSERT3U(fill, ==, bp->blk_fill);
1118                 (void) arc_buf_remove_ref(buf, &buf);
1119         }
1120 
1121         return (err);
1122 }
1123 
1124 /*ARGSUSED*/
1125 static void
1126 dump_indirect(dnode_t *dn)
1127 {
1128         dnode_phys_t *dnp = dn->dn_phys;
1129         int j;
1130         zbookmark_t czb;
1131 
1132         (void) printf("Indirect blocks:\n");
1133 
1134         SET_BOOKMARK(&czb, dmu_objset_id(dn->dn_objset),
1135             dn->dn_object, dnp->dn_nlevels - 1, 0);
1136         for (j = 0; j < dnp->dn_nblkptr; j++) {
1137                 czb.zb_blkid = j;
1138                 (void) visit_indirect(dmu_objset_spa(dn->dn_objset), dnp,
1139                     &dnp->dn_blkptr[j], &czb);
1140         }
1141 
1142         (void) printf("\n");
1143 }
1144 
1145 /*ARGSUSED*/
1146 static void
1147 dump_dsl_dir(objset_t *os, uint64_t object, void *data, size_t size)
1148 {
1149         dsl_dir_phys_t *dd = data;
1150         time_t crtime;
1151         char nice[32];
1152 
1153         if (dd == NULL)
1154                 return;
1155 
1156         ASSERT3U(size, >=, sizeof (dsl_dir_phys_t));
1157 
1158         crtime = dd->dd_creation_time;
1159         (void) printf("\t\tcreation_time = %s", ctime(&crtime));
1160         (void) printf("\t\thead_dataset_obj = %llu\n",
1161             (u_longlong_t)dd->dd_head_dataset_obj);
1162         (void) printf("\t\tparent_dir_obj = %llu\n",
1163             (u_longlong_t)dd->dd_parent_obj);
1164         (void) printf("\t\torigin_obj = %llu\n",
1165             (u_longlong_t)dd->dd_origin_obj);
1166         (void) printf("\t\tchild_dir_zapobj = %llu\n",
1167             (u_longlong_t)dd->dd_child_dir_zapobj);
1168         zdb_nicenum(dd->dd_used_bytes, nice);
1169         (void) printf("\t\tused_bytes = %s\n", nice);
1170         zdb_nicenum(dd->dd_compressed_bytes, nice);
1171         (void) printf("\t\tcompressed_bytes = %s\n", nice);
1172         zdb_nicenum(dd->dd_uncompressed_bytes, nice);
1173         (void) printf("\t\tuncompressed_bytes = %s\n", nice);
1174         zdb_nicenum(dd->dd_quota, nice);
1175         (void) printf("\t\tquota = %s\n", nice);
1176         zdb_nicenum(dd->dd_reserved, nice);
1177         (void) printf("\t\treserved = %s\n", nice);
1178         (void) printf("\t\tprops_zapobj = %llu\n",
1179             (u_longlong_t)dd->dd_props_zapobj);
1180         (void) printf("\t\tdeleg_zapobj = %llu\n",
1181             (u_longlong_t)dd->dd_deleg_zapobj);
1182         (void) printf("\t\tflags = %llx\n",
1183             (u_longlong_t)dd->dd_flags);
1184 
1185 #define DO(which) \
1186         zdb_nicenum(dd->dd_used_breakdown[DD_USED_ ## which], nice); \
1187         (void) printf("\t\tused_breakdown[" #which "] = %s\n", nice)
1188         DO(HEAD);
1189         DO(SNAP);
1190         DO(CHILD);
1191         DO(CHILD_RSRV);
1192         DO(REFRSRV);
1193 #undef DO
1194 }
1195 
1196 /*ARGSUSED*/
1197 static void
1198 dump_dsl_dataset(objset_t *os, uint64_t object, void *data, size_t size)
1199 {
1200         dsl_dataset_phys_t *ds = data;
1201         time_t crtime;
1202         char used[32], compressed[32], uncompressed[32], unique[32];
1203         char blkbuf[BP_SPRINTF_LEN];
1204 
1205         if (ds == NULL)
1206                 return;
1207 
1208         ASSERT(size == sizeof (*ds));
1209         crtime = ds->ds_creation_time;
1210         zdb_nicenum(ds->ds_referenced_bytes, used);
1211         zdb_nicenum(ds->ds_compressed_bytes, compressed);
1212         zdb_nicenum(ds->ds_uncompressed_bytes, uncompressed);
1213         zdb_nicenum(ds->ds_unique_bytes, unique);
1214         sprintf_blkptr(blkbuf, &ds->ds_bp);
1215 
1216         (void) printf("\t\tdir_obj = %llu\n",
1217             (u_longlong_t)ds->ds_dir_obj);
1218         (void) printf("\t\tprev_snap_obj = %llu\n",
1219             (u_longlong_t)ds->ds_prev_snap_obj);
1220         (void) printf("\t\tprev_snap_txg = %llu\n",
1221             (u_longlong_t)ds->ds_prev_snap_txg);
1222         (void) printf("\t\tnext_snap_obj = %llu\n",
1223             (u_longlong_t)ds->ds_next_snap_obj);
1224         (void) printf("\t\tsnapnames_zapobj = %llu\n",
1225             (u_longlong_t)ds->ds_snapnames_zapobj);
1226         (void) printf("\t\tnum_children = %llu\n",
1227             (u_longlong_t)ds->ds_num_children);
1228         (void) printf("\t\tuserrefs_obj = %llu\n",
1229             (u_longlong_t)ds->ds_userrefs_obj);
1230         (void) printf("\t\tcreation_time = %s", ctime(&crtime));
1231         (void) printf("\t\tcreation_txg = %llu\n",
1232             (u_longlong_t)ds->ds_creation_txg);
1233         (void) printf("\t\tdeadlist_obj = %llu\n",
1234             (u_longlong_t)ds->ds_deadlist_obj);
1235         (void) printf("\t\tused_bytes = %s\n", used);
1236         (void) printf("\t\tcompressed_bytes = %s\n", compressed);
1237         (void) printf("\t\tuncompressed_bytes = %s\n", uncompressed);
1238         (void) printf("\t\tunique = %s\n", unique);
1239         (void) printf("\t\tfsid_guid = %llu\n",
1240             (u_longlong_t)ds->ds_fsid_guid);
1241         (void) printf("\t\tguid = %llu\n",
1242             (u_longlong_t)ds->ds_guid);
1243         (void) printf("\t\tflags = %llx\n",
1244             (u_longlong_t)ds->ds_flags);
1245         (void) printf("\t\tnext_clones_obj = %llu\n",
1246             (u_longlong_t)ds->ds_next_clones_obj);
1247         (void) printf("\t\tprops_obj = %llu\n",
1248             (u_longlong_t)ds->ds_props_obj);
1249         (void) printf("\t\tbp = %s\n", blkbuf);
1250 }
1251 
1252 /* ARGSUSED */
1253 static int
1254 dump_bptree_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
1255 {
1256         char blkbuf[BP_SPRINTF_LEN];
1257 
1258         if (bp->blk_birth != 0) {
1259                 sprintf_blkptr(blkbuf, bp);
1260                 (void) printf("\t%s\n", blkbuf);
1261         }
1262         return (0);
1263 }
1264 
1265 static void
1266 dump_bptree(objset_t *os, uint64_t obj, char *name)
1267 {
1268         char bytes[32];
1269         bptree_phys_t *bt;
1270         dmu_buf_t *db;
1271 
1272         if (dump_opt['d'] < 3)
1273                 return;
1274 
1275         VERIFY3U(0, ==, dmu_bonus_hold(os, obj, FTAG, &db));
1276         bt = db->db_data;
1277         zdb_nicenum(bt->bt_bytes, bytes);
1278         (void) printf("\n    %s: %llu datasets, %s\n",
1279             name, (unsigned long long)(bt->bt_end - bt->bt_begin), bytes);
1280         dmu_buf_rele(db, FTAG);
1281 
1282         if (dump_opt['d'] < 5)
1283                 return;
1284 
1285         (void) printf("\n");
1286 
1287         (void) bptree_iterate(os, obj, B_FALSE, dump_bptree_cb, NULL, NULL);
1288 }
1289 
1290 /* ARGSUSED */
1291 static int
1292 dump_bpobj_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
1293 {
1294         char blkbuf[BP_SPRINTF_LEN];
1295 
1296         ASSERT(bp->blk_birth != 0);
1297         sprintf_blkptr_compact(blkbuf, bp);
1298         (void) printf("\t%s\n", blkbuf);
1299         return (0);
1300 }
1301 
1302 static void
1303 dump_bpobj(bpobj_t *bpo, char *name, int indent)
1304 {
1305         char bytes[32];
1306         char comp[32];
1307         char uncomp[32];
1308 
1309         if (dump_opt['d'] < 3)
1310                 return;
1311 
1312         zdb_nicenum(bpo->bpo_phys->bpo_bytes, bytes);
1313         if (bpo->bpo_havesubobj && bpo->bpo_phys->bpo_subobjs != 0) {
1314                 zdb_nicenum(bpo->bpo_phys->bpo_comp, comp);
1315                 zdb_nicenum(bpo->bpo_phys->bpo_uncomp, uncomp);
1316                 (void) printf("    %*s: object %llu, %llu local blkptrs, "
1317                     "%llu subobjs, %s (%s/%s comp)\n",
1318                     indent * 8, name,
1319                     (u_longlong_t)bpo->bpo_object,
1320                     (u_longlong_t)bpo->bpo_phys->bpo_num_blkptrs,
1321                     (u_longlong_t)bpo->bpo_phys->bpo_num_subobjs,
1322                     bytes, comp, uncomp);
1323 
1324                 for (uint64_t i = 0; i < bpo->bpo_phys->bpo_num_subobjs; i++) {
1325                         uint64_t subobj;
1326                         bpobj_t subbpo;
1327                         int error;
1328                         VERIFY0(dmu_read(bpo->bpo_os,
1329                             bpo->bpo_phys->bpo_subobjs,
1330                             i * sizeof (subobj), sizeof (subobj), &subobj, 0));
1331                         error = bpobj_open(&subbpo, bpo->bpo_os, subobj);
1332                         if (error != 0) {
1333                                 (void) printf("ERROR %u while trying to open "
1334                                     "subobj id %llu\n",
1335                                     error, (u_longlong_t)subobj);
1336                                 continue;
1337                         }
1338                         dump_bpobj(&subbpo, "subobj", indent + 1);
1339                         bpobj_close(&subbpo);
1340                 }
1341         } else {
1342                 (void) printf("    %*s: object %llu, %llu blkptrs, %s\n",
1343                     indent * 8, name,
1344                     (u_longlong_t)bpo->bpo_object,
1345                     (u_longlong_t)bpo->bpo_phys->bpo_num_blkptrs,
1346                     bytes);
1347         }
1348 
1349         if (dump_opt['d'] < 5)
1350                 return;
1351 
1352 
1353         if (indent == 0) {
1354                 (void) bpobj_iterate_nofree(bpo, dump_bpobj_cb, NULL, NULL);
1355                 (void) printf("\n");
1356         }
1357 }
1358 
1359 static void
1360 dump_deadlist(dsl_deadlist_t *dl)
1361 {
1362         dsl_deadlist_entry_t *dle;
1363         uint64_t unused;
1364         char bytes[32];
1365         char comp[32];
1366         char uncomp[32];
1367 
1368         if (dump_opt['d'] < 3)
1369                 return;
1370 
1371         zdb_nicenum(dl->dl_phys->dl_used, bytes);
1372         zdb_nicenum(dl->dl_phys->dl_comp, comp);
1373         zdb_nicenum(dl->dl_phys->dl_uncomp, uncomp);
1374         (void) printf("\n    Deadlist: %s (%s/%s comp)\n",
1375             bytes, comp, uncomp);
1376 
1377         if (dump_opt['d'] < 4)
1378                 return;
1379 
1380         (void) printf("\n");
1381 
1382         /* force the tree to be loaded */
1383         dsl_deadlist_space_range(dl, 0, UINT64_MAX, &unused, &unused, &unused);
1384 
1385         for (dle = avl_first(&dl->dl_tree); dle;
1386             dle = AVL_NEXT(&dl->dl_tree, dle)) {
1387                 if (dump_opt['d'] >= 5) {
1388                         char buf[128];
1389                         (void) snprintf(buf, sizeof (buf), "mintxg %llu -> ",
1390                             (longlong_t)dle->dle_mintxg,
1391                             (longlong_t)dle->dle_bpobj.bpo_object);
1392 
1393                         dump_bpobj(&dle->dle_bpobj, buf, 0);
1394                 } else {
1395                         (void) printf("mintxg %llu -> obj %llu\n",
1396                             (longlong_t)dle->dle_mintxg,
1397                             (longlong_t)dle->dle_bpobj.bpo_object);
1398 
1399                 }
1400         }
1401 }
1402 
1403 static avl_tree_t idx_tree;
1404 static avl_tree_t domain_tree;
1405 static boolean_t fuid_table_loaded;
1406 static boolean_t sa_loaded;
1407 sa_attr_type_t *sa_attr_table;
1408 
1409 static void
1410 fuid_table_destroy()
1411 {
1412         if (fuid_table_loaded) {
1413                 zfs_fuid_table_destroy(&idx_tree, &domain_tree);
1414                 fuid_table_loaded = B_FALSE;
1415         }
1416 }
1417 
1418 /*
1419  * print uid or gid information.
1420  * For normal POSIX id just the id is printed in decimal format.
1421  * For CIFS files with FUID the fuid is printed in hex followed by
1422  * the domain-rid string.
1423  */
1424 static void
1425 print_idstr(uint64_t id, const char *id_type)
1426 {
1427         if (FUID_INDEX(id)) {
1428                 char *domain;
1429 
1430                 domain = zfs_fuid_idx_domain(&idx_tree, FUID_INDEX(id));
1431                 (void) printf("\t%s     %llx [%s-%d]\n", id_type,
1432                     (u_longlong_t)id, domain, (int)FUID_RID(id));
1433         } else {
1434                 (void) printf("\t%s     %llu\n", id_type, (u_longlong_t)id);
1435         }
1436 
1437 }
1438 
1439 static void
1440 dump_uidgid(objset_t *os, uint64_t uid, uint64_t gid)
1441 {
1442         uint32_t uid_idx, gid_idx;
1443 
1444         uid_idx = FUID_INDEX(uid);
1445         gid_idx = FUID_INDEX(gid);
1446 
1447         /* Load domain table, if not already loaded */
1448         if (!fuid_table_loaded && (uid_idx || gid_idx)) {
1449                 uint64_t fuid_obj;
1450 
1451                 /* first find the fuid object.  It lives in the master node */
1452                 VERIFY(zap_lookup(os, MASTER_NODE_OBJ, ZFS_FUID_TABLES,
1453                     8, 1, &fuid_obj) == 0);
1454                 zfs_fuid_avl_tree_create(&idx_tree, &domain_tree);
1455                 (void) zfs_fuid_table_load(os, fuid_obj,
1456                     &idx_tree, &domain_tree);
1457                 fuid_table_loaded = B_TRUE;
1458         }
1459 
1460         print_idstr(uid, "uid");
1461         print_idstr(gid, "gid");
1462 }
1463 
1464 /*ARGSUSED*/
1465 static void
1466 dump_znode(objset_t *os, uint64_t object, void *data, size_t size)
1467 {
1468         char path[MAXPATHLEN * 2];      /* allow for xattr and failure prefix */
1469         sa_handle_t *hdl;
1470         uint64_t xattr, rdev, gen;
1471         uint64_t uid, gid, mode, fsize, parent, links;
1472         uint64_t pflags;
1473         uint64_t acctm[2], modtm[2], chgtm[2], crtm[2];
1474         time_t z_crtime, z_atime, z_mtime, z_ctime;
1475         sa_bulk_attr_t bulk[12];
1476         int idx = 0;
1477         int error;
1478 
1479         if (!sa_loaded) {
1480                 uint64_t sa_attrs = 0;
1481                 uint64_t version;
1482 
1483                 VERIFY(zap_lookup(os, MASTER_NODE_OBJ, ZPL_VERSION_STR,
1484                     8, 1, &version) == 0);
1485                 if (version >= ZPL_VERSION_SA) {
1486                         VERIFY(zap_lookup(os, MASTER_NODE_OBJ, ZFS_SA_ATTRS,
1487                             8, 1, &sa_attrs) == 0);
1488                 }
1489                 if ((error = sa_setup(os, sa_attrs, zfs_attr_table,
1490                     ZPL_END, &sa_attr_table)) != 0) {
1491                         (void) printf("sa_setup failed errno %d, can't "
1492                             "display znode contents\n", error);
1493                         return;
1494                 }
1495                 sa_loaded = B_TRUE;
1496         }
1497 
1498         if (sa_handle_get(os, object, NULL, SA_HDL_PRIVATE, &hdl)) {
1499                 (void) printf("Failed to get handle for SA znode\n");
1500                 return;
1501         }
1502 
1503         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_UID], NULL, &uid, 8);
1504         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_GID], NULL, &gid, 8);
1505         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_LINKS], NULL,
1506             &links, 8);
1507         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_GEN], NULL, &gen, 8);
1508         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_MODE], NULL,
1509             &mode, 8);
1510         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_PARENT],
1511             NULL, &parent, 8);
1512         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_SIZE], NULL,
1513             &fsize, 8);
1514         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_ATIME], NULL,
1515             acctm, 16);
1516         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_MTIME], NULL,
1517             modtm, 16);
1518         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_CRTIME], NULL,
1519             crtm, 16);
1520         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_CTIME], NULL,
1521             chgtm, 16);
1522         SA_ADD_BULK_ATTR(bulk, idx, sa_attr_table[ZPL_FLAGS], NULL,
1523             &pflags, 8);
1524 
1525         if (sa_bulk_lookup(hdl, bulk, idx)) {
1526                 (void) sa_handle_destroy(hdl);
1527                 return;
1528         }
1529 
1530         error = zfs_obj_to_path(os, object, path, sizeof (path));
1531         if (error != 0) {
1532                 (void) snprintf(path, sizeof (path), "\?\?\?<object#%llu>",
1533                     (u_longlong_t)object);
1534         }
1535         if (dump_opt['d'] < 3) {
1536                 (void) printf("\t%s\n", path);
1537                 (void) sa_handle_destroy(hdl);
1538                 return;
1539         }
1540 
1541         z_crtime = (time_t)crtm[0];
1542         z_atime = (time_t)acctm[0];
1543         z_mtime = (time_t)modtm[0];
1544         z_ctime = (time_t)chgtm[0];
1545 
1546         (void) printf("\tpath   %s\n", path);
1547         dump_uidgid(os, uid, gid);
1548         (void) printf("\tatime  %s", ctime(&z_atime));
1549         (void) printf("\tmtime  %s", ctime(&z_mtime));
1550         (void) printf("\tctime  %s", ctime(&z_ctime));
1551         (void) printf("\tcrtime %s", ctime(&z_crtime));
1552         (void) printf("\tgen    %llu\n", (u_longlong_t)gen);
1553         (void) printf("\tmode   %llo\n", (u_longlong_t)mode);
1554         (void) printf("\tsize   %llu\n", (u_longlong_t)fsize);
1555         (void) printf("\tparent %llu\n", (u_longlong_t)parent);
1556         (void) printf("\tlinks  %llu\n", (u_longlong_t)links);
1557         (void) printf("\tpflags %llx\n", (u_longlong_t)pflags);
1558         if (sa_lookup(hdl, sa_attr_table[ZPL_XATTR], &xattr,
1559             sizeof (uint64_t)) == 0)
1560                 (void) printf("\txattr  %llu\n", (u_longlong_t)xattr);
1561         if (sa_lookup(hdl, sa_attr_table[ZPL_RDEV], &rdev,
1562             sizeof (uint64_t)) == 0)
1563                 (void) printf("\trdev   0x%016llx\n", (u_longlong_t)rdev);
1564         sa_handle_destroy(hdl);
1565 }
1566 
1567 /*ARGSUSED*/
1568 static void
1569 dump_acl(objset_t *os, uint64_t object, void *data, size_t size)
1570 {
1571 }
1572 
1573 /*ARGSUSED*/
1574 static void
1575 dump_dmu_objset(objset_t *os, uint64_t object, void *data, size_t size)
1576 {
1577 }
1578 
1579 static object_viewer_t *object_viewer[DMU_OT_NUMTYPES + 1] = {
1580         dump_none,              /* unallocated                  */
1581         dump_zap,               /* object directory             */
1582         dump_uint64,            /* object array                 */
1583         dump_none,              /* packed nvlist                */
1584         dump_packed_nvlist,     /* packed nvlist size           */
1585         dump_none,              /* bplist                       */
1586         dump_none,              /* bplist header                */
1587         dump_none,              /* SPA space map header         */
1588         dump_none,              /* SPA space map                */
1589         dump_none,              /* ZIL intent log               */
1590         dump_dnode,             /* DMU dnode                    */
1591         dump_dmu_objset,        /* DMU objset                   */
1592         dump_dsl_dir,           /* DSL directory                */
1593         dump_zap,               /* DSL directory child map      */
1594         dump_zap,               /* DSL dataset snap map         */
1595         dump_zap,               /* DSL props                    */
1596         dump_dsl_dataset,       /* DSL dataset                  */
1597         dump_znode,             /* ZFS znode                    */
1598         dump_acl,               /* ZFS V0 ACL                   */
1599         dump_uint8,             /* ZFS plain file               */
1600         dump_zpldir,            /* ZFS directory                */
1601         dump_zap,               /* ZFS master node              */
1602         dump_zap,               /* ZFS delete queue             */
1603         dump_uint8,             /* zvol object                  */
1604         dump_zap,               /* zvol prop                    */
1605         dump_uint8,             /* other uint8[]                */
1606         dump_uint64,            /* other uint64[]               */
1607         dump_zap,               /* other ZAP                    */
1608         dump_zap,               /* persistent error log         */
1609         dump_uint8,             /* SPA history                  */
1610         dump_history_offsets,   /* SPA history offsets          */
1611         dump_zap,               /* Pool properties              */
1612         dump_zap,               /* DSL permissions              */
1613         dump_acl,               /* ZFS ACL                      */
1614         dump_uint8,             /* ZFS SYSACL                   */
1615         dump_none,              /* FUID nvlist                  */
1616         dump_packed_nvlist,     /* FUID nvlist size             */
1617         dump_zap,               /* DSL dataset next clones      */
1618         dump_zap,               /* DSL scrub queue              */
1619         dump_zap,               /* ZFS user/group used          */
1620         dump_zap,               /* ZFS user/group quota         */
1621         dump_zap,               /* snapshot refcount tags       */
1622         dump_ddt_zap,           /* DDT ZAP object               */
1623         dump_zap,               /* DDT statistics               */
1624         dump_znode,             /* SA object                    */
1625         dump_zap,               /* SA Master Node               */
1626         dump_sa_attrs,          /* SA attribute registration    */
1627         dump_sa_layouts,        /* SA attribute layouts         */
1628         dump_zap,               /* DSL scrub translations       */
1629         dump_none,              /* fake dedup BP                */
1630         dump_zap,               /* deadlist                     */
1631         dump_none,              /* deadlist hdr                 */
1632         dump_zap,               /* dsl clones                   */
1633         dump_none,              /* bpobj subobjs                */
1634         dump_unknown,           /* Unknown type, must be last   */
1635 };
1636 
1637 static void
1638 dump_object(objset_t *os, uint64_t object, int verbosity, int *print_header)
1639 {
1640         dmu_buf_t *db = NULL;
1641         dmu_object_info_t doi;
1642         dnode_t *dn;
1643         void *bonus = NULL;
1644         size_t bsize = 0;
1645         char iblk[32], dblk[32], lsize[32], asize[32], fill[32];
1646         char bonus_size[32];
1647         char aux[50];
1648         int error;
1649 
1650         if (*print_header) {
1651                 (void) printf("\n%10s  %3s  %5s  %5s  %5s  %5s  %6s  %s\n",
1652                     "Object", "lvl", "iblk", "dblk", "dsize", "lsize",
1653                     "%full", "type");
1654                 *print_header = 0;
1655         }
1656 
1657         if (object == 0) {
1658                 dn = DMU_META_DNODE(os);
1659         } else {
1660                 error = dmu_bonus_hold(os, object, FTAG, &db);
1661                 if (error)
1662                         fatal("dmu_bonus_hold(%llu) failed, errno %u",
1663                             object, error);
1664                 bonus = db->db_data;
1665                 bsize = db->db_size;
1666                 dn = DB_DNODE((dmu_buf_impl_t *)db);
1667         }
1668         dmu_object_info_from_dnode(dn, &doi);
1669 
1670         zdb_nicenum(doi.doi_metadata_block_size, iblk);
1671         zdb_nicenum(doi.doi_data_block_size, dblk);
1672         zdb_nicenum(doi.doi_max_offset, lsize);
1673         zdb_nicenum(doi.doi_physical_blocks_512 << 9, asize);
1674         zdb_nicenum(doi.doi_bonus_size, bonus_size);
1675         (void) sprintf(fill, "%6.2f", 100.0 * doi.doi_fill_count *
1676             doi.doi_data_block_size / (object == 0 ? DNODES_PER_BLOCK : 1) /
1677             doi.doi_max_offset);
1678 
1679         aux[0] = '\0';
1680 
1681         if (doi.doi_checksum != ZIO_CHECKSUM_INHERIT || verbosity >= 6) {
1682                 (void) snprintf(aux + strlen(aux), sizeof (aux), " (K=%s)",
1683                     ZDB_CHECKSUM_NAME(doi.doi_checksum));
1684         }
1685 
1686         if (doi.doi_compress != ZIO_COMPRESS_INHERIT || verbosity >= 6) {
1687                 (void) snprintf(aux + strlen(aux), sizeof (aux), " (Z=%s)",
1688                     ZDB_COMPRESS_NAME(doi.doi_compress));
1689         }
1690 
1691         (void) printf("%10lld  %3u  %5s  %5s  %5s  %5s  %6s  %s%s\n",
1692             (u_longlong_t)object, doi.doi_indirection, iblk, dblk,
1693             asize, lsize, fill, ZDB_OT_NAME(doi.doi_type), aux);
1694 
1695         if (doi.doi_bonus_type != DMU_OT_NONE && verbosity > 3) {
1696                 (void) printf("%10s  %3s  %5s  %5s  %5s  %5s  %6s  %s\n",
1697                     "", "", "", "", "", bonus_size, "bonus",
1698                     ZDB_OT_NAME(doi.doi_bonus_type));
1699         }
1700 
1701         if (verbosity >= 4) {
1702                 (void) printf("\tdnode flags: %s%s%s\n",
1703                     (dn->dn_phys->dn_flags & DNODE_FLAG_USED_BYTES) ?
1704                     "USED_BYTES " : "",
1705                     (dn->dn_phys->dn_flags & DNODE_FLAG_USERUSED_ACCOUNTED) ?
1706                     "USERUSED_ACCOUNTED " : "",
1707                     (dn->dn_phys->dn_flags & DNODE_FLAG_SPILL_BLKPTR) ?
1708                     "SPILL_BLKPTR" : "");
1709                 (void) printf("\tdnode maxblkid: %llu\n",
1710                     (longlong_t)dn->dn_phys->dn_maxblkid);
1711 
1712                 object_viewer[ZDB_OT_TYPE(doi.doi_bonus_type)](os, object,
1713                     bonus, bsize);
1714                 object_viewer[ZDB_OT_TYPE(doi.doi_type)](os, object, NULL, 0);
1715                 *print_header = 1;
1716         }
1717 
1718         if (verbosity >= 5)
1719                 dump_indirect(dn);
1720 
1721         if (verbosity >= 5) {
1722                 /*
1723                  * Report the list of segments that comprise the object.
1724                  */
1725                 uint64_t start = 0;
1726                 uint64_t end;
1727                 uint64_t blkfill = 1;
1728                 int minlvl = 1;
1729 
1730                 if (dn->dn_type == DMU_OT_DNODE) {
1731                         minlvl = 0;
1732                         blkfill = DNODES_PER_BLOCK;
1733                 }
1734 
1735                 for (;;) {
1736                         char segsize[32];
1737                         error = dnode_next_offset(dn,
1738                             0, &start, minlvl, blkfill, 0);
1739                         if (error)
1740                                 break;
1741                         end = start;
1742                         error = dnode_next_offset(dn,
1743                             DNODE_FIND_HOLE, &end, minlvl, blkfill, 0);
1744                         zdb_nicenum(end - start, segsize);
1745                         (void) printf("\t\tsegment [%016llx, %016llx)"
1746                             " size %5s\n", (u_longlong_t)start,
1747                             (u_longlong_t)end, segsize);
1748                         if (error)
1749                                 break;
1750                         start = end;
1751                 }
1752         }
1753 
1754         if (db != NULL)
1755                 dmu_buf_rele(db, FTAG);
1756 }
1757 
1758 static char *objset_types[DMU_OST_NUMTYPES] = {
1759         "NONE", "META", "ZPL", "ZVOL", "OTHER", "ANY" };
1760 
1761 static void
1762 dump_dir(objset_t *os)
1763 {
1764         dmu_objset_stats_t dds;
1765         uint64_t object, object_count;
1766         uint64_t refdbytes, usedobjs, scratch;
1767         char numbuf[32];
1768         char blkbuf[BP_SPRINTF_LEN + 20];
1769         char osname[MAXNAMELEN];
1770         char *type = "UNKNOWN";
1771         int verbosity = dump_opt['d'];
1772         int print_header = 1;
1773         int i, error;
1774 
1775         dsl_pool_config_enter(dmu_objset_pool(os), FTAG);
1776         dmu_objset_fast_stat(os, &dds);
1777         dsl_pool_config_exit(dmu_objset_pool(os), FTAG);
1778 
1779         if (dds.dds_type < DMU_OST_NUMTYPES)
1780                 type = objset_types[dds.dds_type];
1781 
1782         if (dds.dds_type == DMU_OST_META) {
1783                 dds.dds_creation_txg = TXG_INITIAL;
1784                 usedobjs = os->os_rootbp->blk_fill;
1785                 refdbytes = os->os_spa->spa_dsl_pool->
1786                     dp_mos_dir->dd_phys->dd_used_bytes;
1787         } else {
1788                 dmu_objset_space(os, &refdbytes, &scratch, &usedobjs, &scratch);
1789         }
1790 
1791         ASSERT3U(usedobjs, ==, os->os_rootbp->blk_fill);
1792 
1793         zdb_nicenum(refdbytes, numbuf);
1794 
1795         if (verbosity >= 4) {
1796                 (void) sprintf(blkbuf, ", rootbp ");
1797                 (void) sprintf_blkptr(blkbuf + strlen(blkbuf), os->os_rootbp);
1798         } else {
1799                 blkbuf[0] = '\0';
1800         }
1801 
1802         dmu_objset_name(os, osname);
1803 
1804         (void) printf("Dataset %s [%s], ID %llu, cr_txg %llu, "
1805             "%s, %llu objects%s\n",
1806             osname, type, (u_longlong_t)dmu_objset_id(os),
1807             (u_longlong_t)dds.dds_creation_txg,
1808             numbuf, (u_longlong_t)usedobjs, blkbuf);
1809 
1810         if (zopt_objects != 0) {
1811                 for (i = 0; i < zopt_objects; i++)
1812                         dump_object(os, zopt_object[i], verbosity,
1813                             &print_header);
1814                 (void) printf("\n");
1815                 return;
1816         }
1817 
1818         if (dump_opt['i'] != 0 || verbosity >= 2)
1819                 dump_intent_log(dmu_objset_zil(os));
1820 
1821         if (dmu_objset_ds(os) != NULL)
1822                 dump_deadlist(&dmu_objset_ds(os)->ds_deadlist);
1823 
1824         if (verbosity < 2)
1825                 return;
1826 
1827         if (os->os_rootbp->blk_birth == 0)
1828                 return;
1829 
1830         dump_object(os, 0, verbosity, &print_header);
1831         object_count = 0;
1832         if (DMU_USERUSED_DNODE(os) != NULL &&
1833             DMU_USERUSED_DNODE(os)->dn_type != 0) {
1834                 dump_object(os, DMU_USERUSED_OBJECT, verbosity, &print_header);
1835                 dump_object(os, DMU_GROUPUSED_OBJECT, verbosity, &print_header);
1836         }
1837 
1838         object = 0;
1839         while ((error = dmu_object_next(os, &object, B_FALSE, 0)) == 0) {
1840                 dump_object(os, object, verbosity, &print_header);
1841                 object_count++;
1842         }
1843 
1844         ASSERT3U(object_count, ==, usedobjs);
1845 
1846         (void) printf("\n");
1847 
1848         if (error != ESRCH) {
1849                 (void) fprintf(stderr, "dmu_object_next() = %d\n", error);
1850                 abort();
1851         }
1852 }
1853 
1854 static void
1855 dump_uberblock(uberblock_t *ub, const char *header, const char *footer)
1856 {
1857         time_t timestamp = ub->ub_timestamp;
1858 
1859         (void) printf(header ? header : "");
1860         (void) printf("\tmagic = %016llx\n", (u_longlong_t)ub->ub_magic);
1861         (void) printf("\tversion = %llu\n", (u_longlong_t)ub->ub_version);
1862         (void) printf("\ttxg = %llu\n", (u_longlong_t)ub->ub_txg);
1863         (void) printf("\tguid_sum = %llu\n", (u_longlong_t)ub->ub_guid_sum);
1864         (void) printf("\ttimestamp = %llu UTC = %s",
1865             (u_longlong_t)ub->ub_timestamp, asctime(localtime(&timestamp)));
1866         if (dump_opt['u'] >= 3) {
1867                 char blkbuf[BP_SPRINTF_LEN];
1868                 sprintf_blkptr(blkbuf, &ub->ub_rootbp);
1869                 (void) printf("\trootbp = %s\n", blkbuf);
1870         }
1871         (void) printf(footer ? footer : "");
1872 }
1873 
1874 static void
1875 dump_config(spa_t *spa)
1876 {
1877         dmu_buf_t *db;
1878         size_t nvsize = 0;
1879         int error = 0;
1880 
1881 
1882         error = dmu_bonus_hold(spa->spa_meta_objset,
1883             spa->spa_config_object, FTAG, &db);
1884 
1885         if (error == 0) {
1886                 nvsize = *(uint64_t *)db->db_data;
1887                 dmu_buf_rele(db, FTAG);
1888 
1889                 (void) printf("\nMOS Configuration:\n");
1890                 dump_packed_nvlist(spa->spa_meta_objset,
1891                     spa->spa_config_object, (void *)&nvsize, 1);
1892         } else {
1893                 (void) fprintf(stderr, "dmu_bonus_hold(%llu) failed, errno %d",
1894                     (u_longlong_t)spa->spa_config_object, error);
1895         }
1896 }
1897 
1898 static void
1899 dump_cachefile(const char *cachefile)
1900 {
1901         int fd;
1902         struct stat64 statbuf;
1903         char *buf;
1904         nvlist_t *config;
1905 
1906         if ((fd = open64(cachefile, O_RDONLY)) < 0) {
1907                 (void) printf("cannot open '%s': %s\n", cachefile,
1908                     strerror(errno));
1909                 exit(1);
1910         }
1911 
1912         if (fstat64(fd, &statbuf) != 0) {
1913                 (void) printf("failed to stat '%s': %s\n", cachefile,
1914                     strerror(errno));
1915                 exit(1);
1916         }
1917 
1918         if ((buf = malloc(statbuf.st_size)) == NULL) {
1919                 (void) fprintf(stderr, "failed to allocate %llu bytes\n",
1920                     (u_longlong_t)statbuf.st_size);
1921                 exit(1);
1922         }
1923 
1924         if (read(fd, buf, statbuf.st_size) != statbuf.st_size) {
1925                 (void) fprintf(stderr, "failed to read %llu bytes\n",
1926                     (u_longlong_t)statbuf.st_size);
1927                 exit(1);
1928         }
1929 
1930         (void) close(fd);
1931 
1932         if (nvlist_unpack(buf, statbuf.st_size, &config, 0) != 0) {
1933                 (void) fprintf(stderr, "failed to unpack nvlist\n");
1934                 exit(1);
1935         }
1936 
1937         free(buf);
1938 
1939         dump_nvlist(config, 0);
1940 
1941         nvlist_free(config);
1942 }
1943 
1944 #define ZDB_MAX_UB_HEADER_SIZE 32
1945 
1946 static void
1947 dump_label_uberblocks(vdev_label_t *lbl, uint64_t ashift)
1948 {
1949         vdev_t vd;
1950         vdev_t *vdp = &vd;
1951         char header[ZDB_MAX_UB_HEADER_SIZE];
1952 
1953         vd.vdev_ashift = ashift;
1954         vdp->vdev_top = vdp;
1955 
1956         for (int i = 0; i < VDEV_UBERBLOCK_COUNT(vdp); i++) {
1957                 uint64_t uoff = VDEV_UBERBLOCK_OFFSET(vdp, i);
1958                 uberblock_t *ub = (void *)((char *)lbl + uoff);
1959 
1960                 if (uberblock_verify(ub))
1961                         continue;
1962                 (void) snprintf(header, ZDB_MAX_UB_HEADER_SIZE,
1963                     "Uberblock[%d]\n", i);
1964                 dump_uberblock(ub, header, "");
1965         }
1966 }
1967 
1968 static void
1969 dump_label(const char *dev)
1970 {
1971         int fd;
1972         vdev_label_t label;
1973         char *path, *buf = label.vl_vdev_phys.vp_nvlist;
1974         size_t buflen = sizeof (label.vl_vdev_phys.vp_nvlist);
1975         struct stat64 statbuf;
1976         uint64_t psize, ashift;
1977         int len = strlen(dev) + 1;
1978 
1979         if (strncmp(dev, "/dev/dsk/", 9) == 0) {
1980                 len++;
1981                 path = malloc(len);
1982                 (void) snprintf(path, len, "%s%s", "/dev/rdsk/", dev + 9);
1983         } else {
1984                 path = strdup(dev);
1985         }
1986 
1987         if ((fd = open64(path, O_RDONLY)) < 0) {
1988                 (void) printf("cannot open '%s': %s\n", path, strerror(errno));
1989                 free(path);
1990                 exit(1);
1991         }
1992 
1993         if (fstat64(fd, &statbuf) != 0) {
1994                 (void) printf("failed to stat '%s': %s\n", path,
1995                     strerror(errno));
1996                 free(path);
1997                 (void) close(fd);
1998                 exit(1);
1999         }
2000 
2001         if (S_ISBLK(statbuf.st_mode)) {
2002                 (void) printf("cannot use '%s': character device required\n",
2003                     path);
2004                 free(path);
2005                 (void) close(fd);
2006                 exit(1);
2007         }
2008 
2009         psize = statbuf.st_size;
2010         psize = P2ALIGN(psize, (uint64_t)sizeof (vdev_label_t));
2011 
2012         for (int l = 0; l < VDEV_LABELS; l++) {
2013                 nvlist_t *config = NULL;
2014 
2015                 (void) printf("--------------------------------------------\n");
2016                 (void) printf("LABEL %d\n", l);
2017                 (void) printf("--------------------------------------------\n");
2018 
2019                 if (pread64(fd, &label, sizeof (label),
2020                     vdev_label_offset(psize, l, 0)) != sizeof (label)) {
2021                         (void) printf("failed to read label %d\n", l);
2022                         continue;
2023                 }
2024 
2025                 if (nvlist_unpack(buf, buflen, &config, 0) != 0) {
2026                         (void) printf("failed to unpack label %d\n", l);
2027                         ashift = SPA_MINBLOCKSHIFT;
2028                 } else {
2029                         nvlist_t *vdev_tree = NULL;
2030 
2031                         dump_nvlist(config, 4);
2032                         if ((nvlist_lookup_nvlist(config,
2033                             ZPOOL_CONFIG_VDEV_TREE, &vdev_tree) != 0) ||
2034                             (nvlist_lookup_uint64(vdev_tree,
2035                             ZPOOL_CONFIG_ASHIFT, &ashift) != 0))
2036                                 ashift = SPA_MINBLOCKSHIFT;
2037                         nvlist_free(config);
2038                 }
2039                 if (dump_opt['u'])
2040                         dump_label_uberblocks(&label, ashift);
2041         }
2042 
2043         free(path);
2044         (void) close(fd);
2045 }
2046 
2047 /*ARGSUSED*/
2048 static int
2049 dump_one_dir(const char *dsname, void *arg)
2050 {
2051         int error;
2052         objset_t *os;
2053 
2054         error = dmu_objset_own(dsname, DMU_OST_ANY, B_TRUE, FTAG, &os);
2055         if (error) {
2056                 (void) printf("Could not open %s, error %d\n", dsname, error);
2057                 return (0);
2058         }
2059         dump_dir(os);
2060         dmu_objset_disown(os, FTAG);
2061         fuid_table_destroy();
2062         sa_loaded = B_FALSE;
2063         return (0);
2064 }
2065 
2066 /*
2067  * Block statistics.
2068  */
2069 #define PSIZE_HISTO_SIZE (SPA_MAXBLOCKSIZE / SPA_MINBLOCKSIZE + 1)
2070 typedef struct zdb_blkstats {
2071         uint64_t zb_asize;
2072         uint64_t zb_lsize;
2073         uint64_t zb_psize;
2074         uint64_t zb_count;
2075         uint64_t zb_gangs;
2076         uint64_t zb_ditto_samevdev;
2077         uint64_t zb_psize_histogram[PSIZE_HISTO_SIZE];
2078 } zdb_blkstats_t;
2079 
2080 /*
2081  * Extended object types to report deferred frees and dedup auto-ditto blocks.
2082  */
2083 #define ZDB_OT_DEFERRED (DMU_OT_NUMTYPES + 0)
2084 #define ZDB_OT_DITTO    (DMU_OT_NUMTYPES + 1)
2085 #define ZDB_OT_OTHER    (DMU_OT_NUMTYPES + 2)
2086 #define ZDB_OT_TOTAL    (DMU_OT_NUMTYPES + 3)
2087 
2088 static char *zdb_ot_extname[] = {
2089         "deferred free",
2090         "dedup ditto",
2091         "other",
2092         "Total",
2093 };
2094 
2095 #define ZB_TOTAL        DN_MAX_LEVELS
2096 
2097 typedef struct zdb_cb {
2098         zdb_blkstats_t  zcb_type[ZB_TOTAL + 1][ZDB_OT_TOTAL + 1];
2099         uint64_t        zcb_dedup_asize;
2100         uint64_t        zcb_dedup_blocks;
2101         uint64_t        zcb_start;
2102         uint64_t        zcb_lastprint;
2103         uint64_t        zcb_totalasize;
2104         uint64_t        zcb_errors[256];
2105         int             zcb_readfails;
2106         int             zcb_haderrors;
2107         spa_t           *zcb_spa;
2108 } zdb_cb_t;
2109 
2110 static void
2111 zdb_count_block(zdb_cb_t *zcb, zilog_t *zilog, const blkptr_t *bp,
2112     dmu_object_type_t type)
2113 {
2114         uint64_t refcnt = 0;
2115 
2116         ASSERT(type < ZDB_OT_TOTAL);
2117 
2118         if (zilog && zil_bp_tree_add(zilog, bp) != 0)
2119                 return;
2120 
2121         for (int i = 0; i < 4; i++) {
2122                 int l = (i < 2) ? BP_GET_LEVEL(bp) : ZB_TOTAL;
2123                 int t = (i & 1) ? type : ZDB_OT_TOTAL;
2124                 int equal;
2125                 zdb_blkstats_t *zb = &zcb->zcb_type[l][t];
2126 
2127                 zb->zb_asize += BP_GET_ASIZE(bp);
2128                 zb->zb_lsize += BP_GET_LSIZE(bp);
2129                 zb->zb_psize += BP_GET_PSIZE(bp);
2130                 zb->zb_count++;
2131                 zb->zb_psize_histogram[BP_GET_PSIZE(bp) >> SPA_MINBLOCKSHIFT]++;
2132 
2133                 zb->zb_gangs += BP_COUNT_GANG(bp);
2134 
2135                 switch (BP_GET_NDVAS(bp)) {
2136                 case 2:
2137                         if (DVA_GET_VDEV(&bp->blk_dva[0]) ==
2138                             DVA_GET_VDEV(&bp->blk_dva[1]))
2139                                 zb->zb_ditto_samevdev++;
2140                         break;
2141                 case 3:
2142                         equal = (DVA_GET_VDEV(&bp->blk_dva[0]) ==
2143                             DVA_GET_VDEV(&bp->blk_dva[1])) +
2144                             (DVA_GET_VDEV(&bp->blk_dva[0]) ==
2145                             DVA_GET_VDEV(&bp->blk_dva[2])) +
2146                             (DVA_GET_VDEV(&bp->blk_dva[1]) ==
2147                             DVA_GET_VDEV(&bp->blk_dva[2]));
2148                         if (equal != 0)
2149                                 zb->zb_ditto_samevdev++;
2150                         break;
2151                 }
2152 
2153         }
2154 
2155         if (dump_opt['L'])
2156                 return;
2157 
2158         if (BP_GET_DEDUP(bp)) {
2159                 ddt_t *ddt;
2160                 ddt_entry_t *dde;
2161 
2162                 ddt = ddt_select(zcb->zcb_spa, bp);
2163                 ddt_enter(ddt);
2164                 dde = ddt_lookup(ddt, bp, B_FALSE);
2165 
2166                 if (dde == NULL) {
2167                         refcnt = 0;
2168                 } else {
2169                         ddt_phys_t *ddp = ddt_phys_select(dde, bp);
2170                         ddt_phys_decref(ddp);
2171                         refcnt = ddp->ddp_refcnt;
2172                         if (ddt_phys_total_refcnt(dde) == 0)
2173                                 ddt_remove(ddt, dde);
2174                 }
2175                 ddt_exit(ddt);
2176         }
2177 
2178         VERIFY3U(zio_wait(zio_claim(NULL, zcb->zcb_spa,
2179             refcnt ? 0 : spa_first_txg(zcb->zcb_spa),
2180             bp, NULL, NULL, ZIO_FLAG_CANFAIL)), ==, 0);
2181 }
2182 
2183 static void
2184 zdb_blkptr_done(zio_t *zio)
2185 {
2186         spa_t *spa = zio->io_spa;
2187         blkptr_t *bp = zio->io_bp;
2188         int ioerr = zio->io_error;
2189         zdb_cb_t *zcb = zio->io_private;
2190         zbookmark_t *zb = &zio->io_bookmark;
2191 
2192         zio_data_buf_free(zio->io_data, zio->io_size);
2193 
2194         mutex_enter(&spa->spa_scrub_lock);
2195         spa->spa_scrub_inflight--;
2196         cv_broadcast(&spa->spa_scrub_io_cv);
2197 
2198         if (ioerr && !(zio->io_flags & ZIO_FLAG_SPECULATIVE)) {
2199                 char blkbuf[BP_SPRINTF_LEN];
2200 
2201                 zcb->zcb_haderrors = 1;
2202                 zcb->zcb_errors[ioerr]++;
2203 
2204                 if (dump_opt['b'] >= 2)
2205                         sprintf_blkptr(blkbuf, bp);
2206                 else
2207                         blkbuf[0] = '\0';
2208 
2209                 (void) printf("zdb_blkptr_cb: "
2210                     "Got error %d reading "
2211                     "<%llu, %llu, %lld, %llx> %s -- skipping\n",
2212                     ioerr,
2213                     (u_longlong_t)zb->zb_objset,
2214                     (u_longlong_t)zb->zb_object,
2215                     (u_longlong_t)zb->zb_level,
2216                     (u_longlong_t)zb->zb_blkid,
2217                     blkbuf);
2218         }
2219         mutex_exit(&spa->spa_scrub_lock);
2220 }
2221 
2222 static int
2223 zdb_blkptr_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
2224     const zbookmark_t *zb, const dnode_phys_t *dnp, void *arg)
2225 {
2226         zdb_cb_t *zcb = arg;
2227         char blkbuf[BP_SPRINTF_LEN];
2228         dmu_object_type_t type;
2229         boolean_t is_metadata;
2230 
2231         if (bp == NULL)
2232                 return (0);
2233 
2234         type = BP_GET_TYPE(bp);
2235 
2236         zdb_count_block(zcb, zilog, bp,
2237             (type & DMU_OT_NEWTYPE) ? ZDB_OT_OTHER : type);
2238 
2239         is_metadata = (BP_GET_LEVEL(bp) != 0 || DMU_OT_IS_METADATA(type));
2240 
2241         if (dump_opt['c'] > 1 || (dump_opt['c'] && is_metadata)) {
2242                 size_t size = BP_GET_PSIZE(bp);
2243                 void *data = zio_data_buf_alloc(size);
2244                 int flags = ZIO_FLAG_CANFAIL | ZIO_FLAG_SCRUB | ZIO_FLAG_RAW;
2245 
2246                 /* If it's an intent log block, failure is expected. */
2247                 if (zb->zb_level == ZB_ZIL_LEVEL)
2248                         flags |= ZIO_FLAG_SPECULATIVE;
2249 
2250                 mutex_enter(&spa->spa_scrub_lock);
2251                 while (spa->spa_scrub_inflight > max_inflight)
2252                         cv_wait(&spa->spa_scrub_io_cv, &spa->spa_scrub_lock);
2253                 spa->spa_scrub_inflight++;
2254                 mutex_exit(&spa->spa_scrub_lock);
2255 
2256                 zio_nowait(zio_read(NULL, spa, bp, data, size,
2257                     zdb_blkptr_done, zcb, ZIO_PRIORITY_ASYNC_READ, flags, zb));
2258         }
2259 
2260         zcb->zcb_readfails = 0;
2261 
2262         if (dump_opt['b'] >= 5) {
2263                 sprintf_blkptr(blkbuf, bp);
2264                 (void) printf("objset %llu object %llu "
2265                     "level %lld offset 0x%llx %s\n",
2266                     (u_longlong_t)zb->zb_objset,
2267                     (u_longlong_t)zb->zb_object,
2268                     (longlong_t)zb->zb_level,
2269                     (u_longlong_t)blkid2offset(dnp, bp, zb),
2270                     blkbuf);
2271         }
2272 
2273         if (dump_opt['b'] < 5 && isatty(STDERR_FILENO) &&
2274             gethrtime() > zcb->zcb_lastprint + NANOSEC) {
2275                 uint64_t now = gethrtime();
2276                 char buf[10];
2277                 uint64_t bytes = zcb->zcb_type[ZB_TOTAL][ZDB_OT_TOTAL].zb_asize;
2278                 int kb_per_sec =
2279                     1 + bytes / (1 + ((now - zcb->zcb_start) / 1000 / 1000));
2280                 int sec_remaining =
2281                     (zcb->zcb_totalasize - bytes) / 1024 / kb_per_sec;
2282 
2283                 zfs_nicenum(bytes, buf, sizeof (buf));
2284                 (void) fprintf(stderr,
2285                     "\r%5s completed (%4dMB/s) "
2286                     "estimated time remaining: %uhr %02umin %02usec        ",
2287                     buf, kb_per_sec / 1024,
2288                     sec_remaining / 60 / 60,
2289                     sec_remaining / 60 % 60,
2290                     sec_remaining % 60);
2291 
2292                 zcb->zcb_lastprint = now;
2293         }
2294 
2295         return (0);
2296 }
2297 
2298 static void
2299 zdb_leak(void *arg, uint64_t start, uint64_t size)
2300 {
2301         vdev_t *vd = arg;
2302 
2303         (void) printf("leaked space: vdev %llu, offset 0x%llx, size %llu\n",
2304             (u_longlong_t)vd->vdev_id, (u_longlong_t)start, (u_longlong_t)size);
2305 }
2306 
2307 static metaslab_ops_t zdb_metaslab_ops = {
2308         NULL,   /* alloc */
2309         NULL    /* fragmented */
2310 };
2311 
2312 static void
2313 zdb_ddt_leak_init(spa_t *spa, zdb_cb_t *zcb)
2314 {
2315         ddt_bookmark_t ddb = { 0 };
2316         ddt_entry_t dde;
2317         int error;
2318 
2319         while ((error = ddt_walk(spa, &ddb, &dde)) == 0) {
2320                 blkptr_t blk;
2321                 ddt_phys_t *ddp = dde.dde_phys;
2322 
2323                 if (ddb.ddb_class == DDT_CLASS_UNIQUE)
2324                         return;
2325 
2326                 ASSERT(ddt_phys_total_refcnt(&dde) > 1);
2327 
2328                 for (int p = 0; p < DDT_PHYS_TYPES; p++, ddp++) {
2329                         if (ddp->ddp_phys_birth == 0)
2330                                 continue;
2331                         ddt_bp_create(ddb.ddb_checksum,
2332                             &dde.dde_key, ddp, &blk);
2333                         if (p == DDT_PHYS_DITTO) {
2334                                 zdb_count_block(zcb, NULL, &blk, ZDB_OT_DITTO);
2335                         } else {
2336                                 zcb->zcb_dedup_asize +=
2337                                     BP_GET_ASIZE(&blk) * (ddp->ddp_refcnt - 1);
2338                                 zcb->zcb_dedup_blocks++;
2339                         }
2340                 }
2341                 if (!dump_opt['L']) {
2342                         ddt_t *ddt = spa->spa_ddt[ddb.ddb_checksum];
2343                         ddt_enter(ddt);
2344                         VERIFY(ddt_lookup(ddt, &blk, B_TRUE) != NULL);
2345                         ddt_exit(ddt);
2346                 }
2347         }
2348 
2349         ASSERT(error == ENOENT);
2350 }
2351 
2352 static void
2353 zdb_leak_init(spa_t *spa, zdb_cb_t *zcb)
2354 {
2355         zcb->zcb_spa = spa;
2356 
2357         if (!dump_opt['L']) {
2358                 vdev_t *rvd = spa->spa_root_vdev;
2359                 for (int c = 0; c < rvd->vdev_children; c++) {
2360                         vdev_t *vd = rvd->vdev_child[c];
2361                         for (int m = 0; m < vd->vdev_ms_count; m++) {
2362                                 metaslab_t *msp = vd->vdev_ms[m];
2363                                 mutex_enter(&msp->ms_lock);
2364                                 metaslab_unload(msp);
2365 
2366                                 /*
2367                                  * For leak detection, we overload the metaslab
2368                                  * ms_tree to contain allocated segments
2369                                  * instead of free segments. As a result,
2370                                  * we can't use the normal metaslab_load/unload
2371                                  * interfaces.
2372                                  */
2373                                 if (msp->ms_sm != NULL) {
2374                                         msp->ms_ops = &zdb_metaslab_ops;
2375                                         VERIFY0(space_map_load(msp->ms_sm,
2376                                             msp->ms_tree, SM_ALLOC));
2377                                         msp->ms_loaded = B_TRUE;
2378                                 }
2379                                 mutex_exit(&msp->ms_lock);
2380                         }
2381                 }
2382         }
2383 
2384         spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
2385 
2386         zdb_ddt_leak_init(spa, zcb);
2387 
2388         spa_config_exit(spa, SCL_CONFIG, FTAG);
2389 }
2390 
2391 static void
2392 zdb_leak_fini(spa_t *spa)
2393 {
2394         if (!dump_opt['L']) {
2395                 vdev_t *rvd = spa->spa_root_vdev;
2396                 for (int c = 0; c < rvd->vdev_children; c++) {
2397                         vdev_t *vd = rvd->vdev_child[c];
2398                         for (int m = 0; m < vd->vdev_ms_count; m++) {
2399                                 metaslab_t *msp = vd->vdev_ms[m];
2400                                 mutex_enter(&msp->ms_lock);
2401 
2402                                 /*
2403                                  * The ms_tree has been overloaded to
2404                                  * contain allocated segments. Now that we
2405                                  * finished traversing all blocks, any
2406                                  * block that remains in the ms_tree
2407                                  * represents an allocated block that we
2408                                  * did not claim during the traversal.
2409                                  * Claimed blocks would have been removed
2410                                  * from the ms_tree.
2411                                  */
2412                                 range_tree_vacate(msp->ms_tree, zdb_leak, vd);
2413                                 msp->ms_loaded = B_FALSE;
2414 
2415                                 mutex_exit(&msp->ms_lock);
2416                         }
2417                 }
2418         }
2419 }
2420 
2421 /* ARGSUSED */
2422 static int
2423 count_block_cb(void *arg, const blkptr_t *bp, dmu_tx_t *tx)
2424 {
2425         zdb_cb_t *zcb = arg;
2426 
2427         if (dump_opt['b'] >= 5) {
2428                 char blkbuf[BP_SPRINTF_LEN];
2429                 sprintf_blkptr(blkbuf, bp);
2430                 (void) printf("[%s] %s\n",
2431                     "deferred free", blkbuf);
2432         }
2433         zdb_count_block(zcb, NULL, bp, ZDB_OT_DEFERRED);
2434         return (0);
2435 }
2436 
2437 static int
2438 dump_block_stats(spa_t *spa)
2439 {
2440         zdb_cb_t zcb = { 0 };
2441         zdb_blkstats_t *zb, *tzb;
2442         uint64_t norm_alloc, norm_space, total_alloc, total_found;
2443         int flags = TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA | TRAVERSE_HARD;
2444         int leaks = 0;
2445 
2446         (void) printf("\nTraversing all blocks %s%s%s%s%s...\n\n",
2447             (dump_opt['c'] || !dump_opt['L']) ? "to verify " : "",
2448             (dump_opt['c'] == 1) ? "metadata " : "",
2449             dump_opt['c'] ? "checksums " : "",
2450             (dump_opt['c'] && !dump_opt['L']) ? "and verify " : "",
2451             !dump_opt['L'] ? "nothing leaked " : "");
2452 
2453         /*
2454          * Load all space maps as SM_ALLOC maps, then traverse the pool
2455          * claiming each block we discover.  If the pool is perfectly
2456          * consistent, the space maps will be empty when we're done.
2457          * Anything left over is a leak; any block we can't claim (because
2458          * it's not part of any space map) is a double allocation,
2459          * reference to a freed block, or an unclaimed log block.
2460          */
2461         zdb_leak_init(spa, &zcb);
2462 
2463         /*
2464          * If there's a deferred-free bplist, process that first.
2465          */
2466         (void) bpobj_iterate_nofree(&spa->spa_deferred_bpobj,
2467             count_block_cb, &zcb, NULL);
2468         if (spa_version(spa) >= SPA_VERSION_DEADLISTS) {
2469                 (void) bpobj_iterate_nofree(&spa->spa_dsl_pool->dp_free_bpobj,
2470                     count_block_cb, &zcb, NULL);
2471         }
2472         if (spa_feature_is_active(spa, SPA_FEATURE_ASYNC_DESTROY)) {
2473                 VERIFY3U(0, ==, bptree_iterate(spa->spa_meta_objset,
2474                     spa->spa_dsl_pool->dp_bptree_obj, B_FALSE, count_block_cb,
2475                     &zcb, NULL));
2476         }
2477 
2478         if (dump_opt['c'] > 1)
2479                 flags |= TRAVERSE_PREFETCH_DATA;
2480 
2481         zcb.zcb_totalasize = metaslab_class_get_alloc(spa_normal_class(spa));
2482         zcb.zcb_start = zcb.zcb_lastprint = gethrtime();
2483         zcb.zcb_haderrors |= traverse_pool(spa, 0, flags, zdb_blkptr_cb, &zcb);
2484 
2485         /*
2486          * If we've traversed the data blocks then we need to wait for those
2487          * I/Os to complete. We leverage "The Godfather" zio to wait on
2488          * all async I/Os to complete.
2489          */
2490         if (dump_opt['c']) {
2491                 (void) zio_wait(spa->spa_async_zio_root);
2492                 spa->spa_async_zio_root = zio_root(spa, NULL, NULL,
2493                     ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE |
2494                     ZIO_FLAG_GODFATHER);
2495         }
2496 
2497         if (zcb.zcb_haderrors) {
2498                 (void) printf("\nError counts:\n\n");
2499                 (void) printf("\t%5s  %s\n", "errno", "count");
2500                 for (int e = 0; e < 256; e++) {
2501                         if (zcb.zcb_errors[e] != 0) {
2502                                 (void) printf("\t%5d  %llu\n",
2503                                     e, (u_longlong_t)zcb.zcb_errors[e]);
2504                         }
2505                 }
2506         }
2507 
2508         /*
2509          * Report any leaked segments.
2510          */
2511         zdb_leak_fini(spa);
2512 
2513         tzb = &zcb.zcb_type[ZB_TOTAL][ZDB_OT_TOTAL];
2514 
2515         norm_alloc = metaslab_class_get_alloc(spa_normal_class(spa));
2516         norm_space = metaslab_class_get_space(spa_normal_class(spa));
2517 
2518         total_alloc = norm_alloc + metaslab_class_get_alloc(spa_log_class(spa));
2519         total_found = tzb->zb_asize - zcb.zcb_dedup_asize;
2520 
2521         if (total_found == total_alloc) {
2522                 if (!dump_opt['L'])
2523                         (void) printf("\n\tNo leaks (block sum matches space"
2524                             " maps exactly)\n");
2525         } else {
2526                 (void) printf("block traversal size %llu != alloc %llu "
2527                     "(%s %lld)\n",
2528                     (u_longlong_t)total_found,
2529                     (u_longlong_t)total_alloc,
2530                     (dump_opt['L']) ? "unreachable" : "leaked",
2531                     (longlong_t)(total_alloc - total_found));
2532                 leaks = 1;
2533         }
2534 
2535         if (tzb->zb_count == 0)
2536                 return (2);
2537 
2538         (void) printf("\n");
2539         (void) printf("\tbp count:      %10llu\n",
2540             (u_longlong_t)tzb->zb_count);
2541         (void) printf("\tganged count:  %10llu\n",
2542             (longlong_t)tzb->zb_gangs);
2543         (void) printf("\tbp logical:    %10llu      avg: %6llu\n",
2544             (u_longlong_t)tzb->zb_lsize,
2545             (u_longlong_t)(tzb->zb_lsize / tzb->zb_count));
2546         (void) printf("\tbp physical:   %10llu      avg:"
2547             " %6llu     compression: %6.2f\n",
2548             (u_longlong_t)tzb->zb_psize,
2549             (u_longlong_t)(tzb->zb_psize / tzb->zb_count),
2550             (double)tzb->zb_lsize / tzb->zb_psize);
2551         (void) printf("\tbp allocated:  %10llu      avg:"
2552             " %6llu     compression: %6.2f\n",
2553             (u_longlong_t)tzb->zb_asize,
2554             (u_longlong_t)(tzb->zb_asize / tzb->zb_count),
2555             (double)tzb->zb_lsize / tzb->zb_asize);
2556         (void) printf("\tbp deduped:    %10llu    ref>1:"
2557             " %6llu   deduplication: %6.2f\n",
2558             (u_longlong_t)zcb.zcb_dedup_asize,
2559             (u_longlong_t)zcb.zcb_dedup_blocks,
2560             (double)zcb.zcb_dedup_asize / tzb->zb_asize + 1.0);
2561         (void) printf("\tSPA allocated: %10llu     used: %5.2f%%\n",
2562             (u_longlong_t)norm_alloc, 100.0 * norm_alloc / norm_space);
2563 
2564         if (tzb->zb_ditto_samevdev != 0) {
2565                 (void) printf("\tDittoed blocks on same vdev: %llu\n",
2566                     (longlong_t)tzb->zb_ditto_samevdev);
2567         }
2568 
2569         if (dump_opt['b'] >= 2) {
2570                 int l, t, level;
2571                 (void) printf("\nBlocks\tLSIZE\tPSIZE\tASIZE"
2572                     "\t  avg\t comp\t%%Total\tType\n");
2573 
2574                 for (t = 0; t <= ZDB_OT_TOTAL; t++) {
2575                         char csize[32], lsize[32], psize[32], asize[32];
2576                         char avg[32], gang[32];
2577                         char *typename;
2578 
2579                         if (t < DMU_OT_NUMTYPES)
2580                                 typename = dmu_ot[t].ot_name;
2581                         else
2582                                 typename = zdb_ot_extname[t - DMU_OT_NUMTYPES];
2583 
2584                         if (zcb.zcb_type[ZB_TOTAL][t].zb_asize == 0) {
2585                                 (void) printf("%6s\t%5s\t%5s\t%5s"
2586                                     "\t%5s\t%5s\t%6s\t%s\n",
2587                                     "-",
2588                                     "-",
2589                                     "-",
2590                                     "-",
2591                                     "-",
2592                                     "-",
2593                                     "-",
2594                                     typename);
2595                                 continue;
2596                         }
2597 
2598                         for (l = ZB_TOTAL - 1; l >= -1; l--) {
2599                                 level = (l == -1 ? ZB_TOTAL : l);
2600                                 zb = &zcb.zcb_type[level][t];
2601 
2602                                 if (zb->zb_asize == 0)
2603                                         continue;
2604 
2605                                 if (dump_opt['b'] < 3 && level != ZB_TOTAL)
2606                                         continue;
2607 
2608                                 if (level == 0 && zb->zb_asize ==
2609                                     zcb.zcb_type[ZB_TOTAL][t].zb_asize)
2610                                         continue;
2611 
2612                                 zdb_nicenum(zb->zb_count, csize);
2613                                 zdb_nicenum(zb->zb_lsize, lsize);
2614                                 zdb_nicenum(zb->zb_psize, psize);
2615                                 zdb_nicenum(zb->zb_asize, asize);
2616                                 zdb_nicenum(zb->zb_asize / zb->zb_count, avg);
2617                                 zdb_nicenum(zb->zb_gangs, gang);
2618 
2619                                 (void) printf("%6s\t%5s\t%5s\t%5s\t%5s"
2620                                     "\t%5.2f\t%6.2f\t",
2621                                     csize, lsize, psize, asize, avg,
2622                                     (double)zb->zb_lsize / zb->zb_psize,
2623                                     100.0 * zb->zb_asize / tzb->zb_asize);
2624 
2625                                 if (level == ZB_TOTAL)
2626                                         (void) printf("%s\n", typename);
2627                                 else
2628                                         (void) printf("    L%d %s\n",
2629                                             level, typename);
2630 
2631                                 if (dump_opt['b'] >= 3 && zb->zb_gangs > 0) {
2632                                         (void) printf("\t number of ganged "
2633                                             "blocks: %s\n", gang);
2634                                 }
2635 
2636                                 if (dump_opt['b'] >= 4) {
2637                                         (void) printf("psize "
2638                                             "(in 512-byte sectors): "
2639                                             "number of blocks\n");
2640                                         dump_histogram(zb->zb_psize_histogram,
2641                                             PSIZE_HISTO_SIZE, 0);
2642                                 }
2643                         }
2644                 }
2645         }
2646 
2647         (void) printf("\n");
2648 
2649         if (leaks)
2650                 return (2);
2651 
2652         if (zcb.zcb_haderrors)
2653                 return (3);
2654 
2655         return (0);
2656 }
2657 
2658 typedef struct zdb_ddt_entry {
2659         ddt_key_t       zdde_key;
2660         uint64_t        zdde_ref_blocks;
2661         uint64_t        zdde_ref_lsize;
2662         uint64_t        zdde_ref_psize;
2663         uint64_t        zdde_ref_dsize;
2664         avl_node_t      zdde_node;
2665 } zdb_ddt_entry_t;
2666 
2667 /* ARGSUSED */
2668 static int
2669 zdb_ddt_add_cb(spa_t *spa, zilog_t *zilog, const blkptr_t *bp,
2670     const zbookmark_t *zb, const dnode_phys_t *dnp, void *arg)
2671 {
2672         avl_tree_t *t = arg;
2673         avl_index_t where;
2674         zdb_ddt_entry_t *zdde, zdde_search;
2675 
2676         if (bp == NULL)
2677                 return (0);
2678 
2679         if (dump_opt['S'] > 1 && zb->zb_level == ZB_ROOT_LEVEL) {
2680                 (void) printf("traversing objset %llu, %llu objects, "
2681                     "%lu blocks so far\n",
2682                     (u_longlong_t)zb->zb_objset,
2683                     (u_longlong_t)bp->blk_fill,
2684                     avl_numnodes(t));
2685         }
2686 
2687         if (BP_IS_HOLE(bp) || BP_GET_CHECKSUM(bp) == ZIO_CHECKSUM_OFF ||
2688             BP_GET_LEVEL(bp) > 0 || DMU_OT_IS_METADATA(BP_GET_TYPE(bp)))
2689                 return (0);
2690 
2691         ddt_key_fill(&zdde_search.zdde_key, bp);
2692 
2693         zdde = avl_find(t, &zdde_search, &where);
2694 
2695         if (zdde == NULL) {
2696                 zdde = umem_zalloc(sizeof (*zdde), UMEM_NOFAIL);
2697                 zdde->zdde_key = zdde_search.zdde_key;
2698                 avl_insert(t, zdde, where);
2699         }
2700 
2701         zdde->zdde_ref_blocks += 1;
2702         zdde->zdde_ref_lsize += BP_GET_LSIZE(bp);
2703         zdde->zdde_ref_psize += BP_GET_PSIZE(bp);
2704         zdde->zdde_ref_dsize += bp_get_dsize_sync(spa, bp);
2705 
2706         return (0);
2707 }
2708 
2709 static void
2710 dump_simulated_ddt(spa_t *spa)
2711 {
2712         avl_tree_t t;
2713         void *cookie = NULL;
2714         zdb_ddt_entry_t *zdde;
2715         ddt_histogram_t ddh_total = { 0 };
2716         ddt_stat_t dds_total = { 0 };
2717 
2718         avl_create(&t, ddt_entry_compare,
2719             sizeof (zdb_ddt_entry_t), offsetof(zdb_ddt_entry_t, zdde_node));
2720 
2721         spa_config_enter(spa, SCL_CONFIG, FTAG, RW_READER);
2722 
2723         (void) traverse_pool(spa, 0, TRAVERSE_PRE | TRAVERSE_PREFETCH_METADATA,
2724             zdb_ddt_add_cb, &t);
2725 
2726         spa_config_exit(spa, SCL_CONFIG, FTAG);
2727 
2728         while ((zdde = avl_destroy_nodes(&t, &cookie)) != NULL) {
2729                 ddt_stat_t dds;
2730                 uint64_t refcnt = zdde->zdde_ref_blocks;
2731                 ASSERT(refcnt != 0);
2732 
2733                 dds.dds_blocks = zdde->zdde_ref_blocks / refcnt;
2734                 dds.dds_lsize = zdde->zdde_ref_lsize / refcnt;
2735                 dds.dds_psize = zdde->zdde_ref_psize / refcnt;
2736                 dds.dds_dsize = zdde->zdde_ref_dsize / refcnt;
2737 
2738                 dds.dds_ref_blocks = zdde->zdde_ref_blocks;
2739                 dds.dds_ref_lsize = zdde->zdde_ref_lsize;
2740                 dds.dds_ref_psize = zdde->zdde_ref_psize;
2741                 dds.dds_ref_dsize = zdde->zdde_ref_dsize;
2742 
2743                 ddt_stat_add(&ddh_total.ddh_stat[highbit(refcnt) - 1], &dds, 0);
2744 
2745                 umem_free(zdde, sizeof (*zdde));
2746         }
2747 
2748         avl_destroy(&t);
2749 
2750         ddt_histogram_stat(&dds_total, &ddh_total);
2751 
2752         (void) printf("Simulated DDT histogram:\n");
2753 
2754         zpool_dump_ddt(&dds_total, &ddh_total);
2755 
2756         dump_dedup_ratio(&dds_total);
2757 }
2758 
2759 static void
2760 dump_zpool(spa_t *spa)
2761 {
2762         dsl_pool_t *dp = spa_get_dsl(spa);
2763         int rc = 0;
2764 
2765         if (dump_opt['S']) {
2766                 dump_simulated_ddt(spa);
2767                 return;
2768         }
2769 
2770         if (!dump_opt['e'] && dump_opt['C'] > 1) {
2771                 (void) printf("\nCached configuration:\n");
2772                 dump_nvlist(spa->spa_config, 8);
2773         }
2774 
2775         if (dump_opt['C'])
2776                 dump_config(spa);
2777 
2778         if (dump_opt['u'])
2779                 dump_uberblock(&spa->spa_uberblock, "\nUberblock:\n", "\n");
2780 
2781         if (dump_opt['D'])
2782                 dump_all_ddts(spa);
2783 
2784         if (dump_opt['d'] > 2 || dump_opt['m'])
2785                 dump_metaslabs(spa);
2786 
2787         if (dump_opt['d'] || dump_opt['i']) {
2788                 dump_dir(dp->dp_meta_objset);
2789                 if (dump_opt['d'] >= 3) {
2790                         dump_bpobj(&spa->spa_deferred_bpobj,
2791                             "Deferred frees", 0);
2792                         if (spa_version(spa) >= SPA_VERSION_DEADLISTS) {
2793                                 dump_bpobj(&spa->spa_dsl_pool->dp_free_bpobj,
2794                                     "Pool snapshot frees", 0);
2795                         }
2796 
2797                         if (spa_feature_is_active(spa,
2798                             SPA_FEATURE_ASYNC_DESTROY)) {
2799                                 dump_bptree(spa->spa_meta_objset,
2800                                     spa->spa_dsl_pool->dp_bptree_obj,
2801                                     "Pool dataset frees");
2802                         }
2803                         dump_dtl(spa->spa_root_vdev, 0);
2804                 }
2805                 (void) dmu_objset_find(spa_name(spa), dump_one_dir,
2806                     NULL, DS_FIND_SNAPSHOTS | DS_FIND_CHILDREN);
2807         }
2808         if (dump_opt['b'] || dump_opt['c'])
2809                 rc = dump_block_stats(spa);
2810 
2811         if (rc == 0)
2812                 rc = verify_spacemap_refcounts(spa);
2813 
2814         if (dump_opt['s'])
2815                 show_pool_stats(spa);
2816 
2817         if (dump_opt['h'])
2818                 dump_history(spa);
2819 
2820         if (rc != 0)
2821                 exit(rc);
2822 }
2823 
2824 #define ZDB_FLAG_CHECKSUM       0x0001
2825 #define ZDB_FLAG_DECOMPRESS     0x0002
2826 #define ZDB_FLAG_BSWAP          0x0004
2827 #define ZDB_FLAG_GBH            0x0008
2828 #define ZDB_FLAG_INDIRECT       0x0010
2829 #define ZDB_FLAG_PHYS           0x0020
2830 #define ZDB_FLAG_RAW            0x0040
2831 #define ZDB_FLAG_PRINT_BLKPTR   0x0080
2832 
2833 int flagbits[256];
2834 
2835 static void
2836 zdb_print_blkptr(blkptr_t *bp, int flags)
2837 {
2838         char blkbuf[BP_SPRINTF_LEN];
2839 
2840         if (flags & ZDB_FLAG_BSWAP)
2841                 byteswap_uint64_array((void *)bp, sizeof (blkptr_t));
2842 
2843         sprintf_blkptr(blkbuf, bp);
2844         (void) printf("%s\n", blkbuf);
2845 }
2846 
2847 static void
2848 zdb_dump_indirect(blkptr_t *bp, int nbps, int flags)
2849 {
2850         int i;
2851 
2852         for (i = 0; i < nbps; i++)
2853                 zdb_print_blkptr(&bp[i], flags);
2854 }
2855 
2856 static void
2857 zdb_dump_gbh(void *buf, int flags)
2858 {
2859         zdb_dump_indirect((blkptr_t *)buf, SPA_GBH_NBLKPTRS, flags);
2860 }
2861 
2862 static void
2863 zdb_dump_block_raw(void *buf, uint64_t size, int flags)
2864 {
2865         if (flags & ZDB_FLAG_BSWAP)
2866                 byteswap_uint64_array(buf, size);
2867         (void) write(1, buf, size);
2868 }
2869 
2870 static void
2871 zdb_dump_block(char *label, void *buf, uint64_t size, int flags)
2872 {
2873         uint64_t *d = (uint64_t *)buf;
2874         int nwords = size / sizeof (uint64_t);
2875         int do_bswap = !!(flags & ZDB_FLAG_BSWAP);
2876         int i, j;
2877         char *hdr, *c;
2878 
2879 
2880         if (do_bswap)
2881                 hdr = " 7 6 5 4 3 2 1 0   f e d c b a 9 8";
2882         else
2883                 hdr = " 0 1 2 3 4 5 6 7   8 9 a b c d e f";
2884 
2885         (void) printf("\n%s\n%6s   %s  0123456789abcdef\n", label, "", hdr);
2886 
2887         for (i = 0; i < nwords; i += 2) {
2888                 (void) printf("%06llx:  %016llx  %016llx  ",
2889                     (u_longlong_t)(i * sizeof (uint64_t)),
2890                     (u_longlong_t)(do_bswap ? BSWAP_64(d[i]) : d[i]),
2891                     (u_longlong_t)(do_bswap ? BSWAP_64(d[i + 1]) : d[i + 1]));
2892 
2893                 c = (char *)&d[i];
2894                 for (j = 0; j < 2 * sizeof (uint64_t); j++)
2895                         (void) printf("%c", isprint(c[j]) ? c[j] : '.');
2896                 (void) printf("\n");
2897         }
2898 }
2899 
2900 /*
2901  * There are two acceptable formats:
2902  *      leaf_name         - For example: c1t0d0 or /tmp/ztest.0a
2903  *      child[.child]*    - For example: 0.1.1
2904  *
2905  * The second form can be used to specify arbitrary vdevs anywhere
2906  * in the heirarchy.  For example, in a pool with a mirror of
2907  * RAID-Zs, you can specify either RAID-Z vdev with 0.0 or 0.1 .
2908  */
2909 static vdev_t *
2910 zdb_vdev_lookup(vdev_t *vdev, char *path)
2911 {
2912         char *s, *p, *q;
2913         int i;
2914 
2915         if (vdev == NULL)
2916                 return (NULL);
2917 
2918         /* First, assume the x.x.x.x format */
2919         i = (int)strtoul(path, &s, 10);
2920         if (s == path || (s && *s != '.' && *s != '\0'))
2921                 goto name;
2922         if (i < 0 || i >= vdev->vdev_children)
2923                 return (NULL);
2924 
2925         vdev = vdev->vdev_child[i];
2926         if (*s == '\0')
2927                 return (vdev);
2928         return (zdb_vdev_lookup(vdev, s+1));
2929 
2930 name:
2931         for (i = 0; i < vdev->vdev_children; i++) {
2932                 vdev_t *vc = vdev->vdev_child[i];
2933 
2934                 if (vc->vdev_path == NULL) {
2935                         vc = zdb_vdev_lookup(vc, path);
2936                         if (vc == NULL)
2937                                 continue;
2938                         else
2939                                 return (vc);
2940                 }
2941 
2942                 p = strrchr(vc->vdev_path, '/');
2943                 p = p ? p + 1 : vc->vdev_path;
2944                 q = &vc->vdev_path[strlen(vc->vdev_path) - 2];
2945 
2946                 if (strcmp(vc->vdev_path, path) == 0)
2947                         return (vc);
2948                 if (strcmp(p, path) == 0)
2949                         return (vc);
2950                 if (strcmp(q, "s0") == 0 && strncmp(p, path, q - p) == 0)
2951                         return (vc);
2952         }
2953 
2954         return (NULL);
2955 }
2956 
2957 /*
2958  * Read a block from a pool and print it out.  The syntax of the
2959  * block descriptor is:
2960  *
2961  *      pool:vdev_specifier:offset:size[:flags]
2962  *
2963  *      pool           - The name of the pool you wish to read from
2964  *      vdev_specifier - Which vdev (see comment for zdb_vdev_lookup)
2965  *      offset         - offset, in hex, in bytes
2966  *      size           - Amount of data to read, in hex, in bytes
2967  *      flags          - A string of characters specifying options
2968  *               b: Decode a blkptr at given offset within block
2969  *              *c: Calculate and display checksums
2970  *               d: Decompress data before dumping
2971  *               e: Byteswap data before dumping
2972  *               g: Display data as a gang block header
2973  *               i: Display as an indirect block
2974  *               p: Do I/O to physical offset
2975  *               r: Dump raw data to stdout
2976  *
2977  *              * = not yet implemented
2978  */
2979 static void
2980 zdb_read_block(char *thing, spa_t *spa)
2981 {
2982         blkptr_t blk, *bp = &blk;
2983         dva_t *dva = bp->blk_dva;
2984         int flags = 0;
2985         uint64_t offset = 0, size = 0, psize = 0, lsize = 0, blkptr_offset = 0;
2986         zio_t *zio;
2987         vdev_t *vd;
2988         void *pbuf, *lbuf, *buf;
2989         char *s, *p, *dup, *vdev, *flagstr;
2990         int i, error;
2991 
2992         dup = strdup(thing);
2993         s = strtok(dup, ":");
2994         vdev = s ? s : "";
2995         s = strtok(NULL, ":");
2996         offset = strtoull(s ? s : "", NULL, 16);
2997         s = strtok(NULL, ":");
2998         size = strtoull(s ? s : "", NULL, 16);
2999         s = strtok(NULL, ":");
3000         flagstr = s ? s : "";
3001 
3002         s = NULL;
3003         if (size == 0)
3004                 s = "size must not be zero";
3005         if (!IS_P2ALIGNED(size, DEV_BSIZE))
3006                 s = "size must be a multiple of sector size";
3007         if (!IS_P2ALIGNED(offset, DEV_BSIZE))
3008                 s = "offset must be a multiple of sector size";
3009         if (s) {
3010                 (void) printf("Invalid block specifier: %s  - %s\n", thing, s);
3011                 free(dup);
3012                 return;
3013         }
3014 
3015         for (s = strtok(flagstr, ":"); s; s = strtok(NULL, ":")) {
3016                 for (i = 0; flagstr[i]; i++) {
3017                         int bit = flagbits[(uchar_t)flagstr[i]];
3018 
3019                         if (bit == 0) {
3020                                 (void) printf("***Invalid flag: %c\n",
3021                                     flagstr[i]);
3022                                 continue;
3023                         }
3024                         flags |= bit;
3025 
3026                         /* If it's not something with an argument, keep going */
3027                         if ((bit & (ZDB_FLAG_CHECKSUM |
3028                             ZDB_FLAG_PRINT_BLKPTR)) == 0)
3029                                 continue;
3030 
3031                         p = &flagstr[i + 1];
3032                         if (bit == ZDB_FLAG_PRINT_BLKPTR)
3033                                 blkptr_offset = strtoull(p, &p, 16);
3034                         if (*p != ':' && *p != '\0') {
3035                                 (void) printf("***Invalid flag arg: '%s'\n", s);
3036                                 free(dup);
3037                                 return;
3038                         }
3039                 }
3040         }
3041 
3042         vd = zdb_vdev_lookup(spa->spa_root_vdev, vdev);
3043         if (vd == NULL) {
3044                 (void) printf("***Invalid vdev: %s\n", vdev);
3045                 free(dup);
3046                 return;
3047         } else {
3048                 if (vd->vdev_path)
3049                         (void) fprintf(stderr, "Found vdev: %s\n",
3050                             vd->vdev_path);
3051                 else
3052                         (void) fprintf(stderr, "Found vdev type: %s\n",
3053                             vd->vdev_ops->vdev_op_type);
3054         }
3055 
3056         psize = size;
3057         lsize = size;
3058 
3059         pbuf = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
3060         lbuf = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
3061 
3062         BP_ZERO(bp);
3063 
3064         DVA_SET_VDEV(&dva[0], vd->vdev_id);
3065         DVA_SET_OFFSET(&dva[0], offset);
3066         DVA_SET_GANG(&dva[0], !!(flags & ZDB_FLAG_GBH));
3067         DVA_SET_ASIZE(&dva[0], vdev_psize_to_asize(vd, psize));
3068 
3069         BP_SET_BIRTH(bp, TXG_INITIAL, TXG_INITIAL);
3070 
3071         BP_SET_LSIZE(bp, lsize);
3072         BP_SET_PSIZE(bp, psize);
3073         BP_SET_COMPRESS(bp, ZIO_COMPRESS_OFF);
3074         BP_SET_CHECKSUM(bp, ZIO_CHECKSUM_OFF);
3075         BP_SET_TYPE(bp, DMU_OT_NONE);
3076         BP_SET_LEVEL(bp, 0);
3077         BP_SET_DEDUP(bp, 0);
3078         BP_SET_BYTEORDER(bp, ZFS_HOST_BYTEORDER);
3079 
3080         spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
3081         zio = zio_root(spa, NULL, NULL, 0);
3082 
3083         if (vd == vd->vdev_top) {
3084                 /*
3085                  * Treat this as a normal block read.
3086                  */
3087                 zio_nowait(zio_read(zio, spa, bp, pbuf, psize, NULL, NULL,
3088                     ZIO_PRIORITY_SYNC_READ,
3089                     ZIO_FLAG_CANFAIL | ZIO_FLAG_RAW, NULL));
3090         } else {
3091                 /*
3092                  * Treat this as a vdev child I/O.
3093                  */
3094                 zio_nowait(zio_vdev_child_io(zio, bp, vd, offset, pbuf, psize,
3095                     ZIO_TYPE_READ, ZIO_PRIORITY_SYNC_READ,
3096                     ZIO_FLAG_DONT_CACHE | ZIO_FLAG_DONT_QUEUE |
3097                     ZIO_FLAG_DONT_PROPAGATE | ZIO_FLAG_DONT_RETRY |
3098                     ZIO_FLAG_CANFAIL | ZIO_FLAG_RAW, NULL, NULL));
3099         }
3100 
3101         error = zio_wait(zio);
3102         spa_config_exit(spa, SCL_STATE, FTAG);
3103 
3104         if (error) {
3105                 (void) printf("Read of %s failed, error: %d\n", thing, error);
3106                 goto out;
3107         }
3108 
3109         if (flags & ZDB_FLAG_DECOMPRESS) {
3110                 /*
3111                  * We don't know how the data was compressed, so just try
3112                  * every decompress function at every inflated blocksize.
3113                  */
3114                 enum zio_compress c;
3115                 void *pbuf2 = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
3116                 void *lbuf2 = umem_alloc(SPA_MAXBLOCKSIZE, UMEM_NOFAIL);
3117 
3118                 bcopy(pbuf, pbuf2, psize);
3119 
3120                 VERIFY(random_get_pseudo_bytes((uint8_t *)pbuf + psize,
3121                     SPA_MAXBLOCKSIZE - psize) == 0);
3122 
3123                 VERIFY(random_get_pseudo_bytes((uint8_t *)pbuf2 + psize,
3124                     SPA_MAXBLOCKSIZE - psize) == 0);
3125 
3126                 for (lsize = SPA_MAXBLOCKSIZE; lsize > psize;
3127                     lsize -= SPA_MINBLOCKSIZE) {
3128                         for (c = 0; c < ZIO_COMPRESS_FUNCTIONS; c++) {
3129                                 if (zio_decompress_data(c, pbuf, lbuf,
3130                                     psize, lsize) == 0 &&
3131                                     zio_decompress_data(c, pbuf2, lbuf2,
3132                                     psize, lsize) == 0 &&
3133                                     bcmp(lbuf, lbuf2, lsize) == 0)
3134                                         break;
3135                         }
3136                         if (c != ZIO_COMPRESS_FUNCTIONS)
3137                                 break;
3138                         lsize -= SPA_MINBLOCKSIZE;
3139                 }
3140 
3141                 umem_free(pbuf2, SPA_MAXBLOCKSIZE);
3142                 umem_free(lbuf2, SPA_MAXBLOCKSIZE);
3143 
3144                 if (lsize <= psize) {
3145                         (void) printf("Decompress of %s failed\n", thing);
3146                         goto out;
3147                 }
3148                 buf = lbuf;
3149                 size = lsize;
3150         } else {
3151                 buf = pbuf;
3152                 size = psize;
3153         }
3154 
3155         if (flags & ZDB_FLAG_PRINT_BLKPTR)
3156                 zdb_print_blkptr((blkptr_t *)(void *)
3157                     ((uintptr_t)buf + (uintptr_t)blkptr_offset), flags);
3158         else if (flags & ZDB_FLAG_RAW)
3159                 zdb_dump_block_raw(buf, size, flags);
3160         else if (flags & ZDB_FLAG_INDIRECT)
3161                 zdb_dump_indirect((blkptr_t *)buf, size / sizeof (blkptr_t),
3162                     flags);
3163         else if (flags & ZDB_FLAG_GBH)
3164                 zdb_dump_gbh(buf, flags);
3165         else
3166                 zdb_dump_block(thing, buf, size, flags);
3167 
3168 out:
3169         umem_free(pbuf, SPA_MAXBLOCKSIZE);
3170         umem_free(lbuf, SPA_MAXBLOCKSIZE);
3171         free(dup);
3172 }
3173 
3174 static boolean_t
3175 pool_match(nvlist_t *cfg, char *tgt)
3176 {
3177         uint64_t v, guid = strtoull(tgt, NULL, 0);
3178         char *s;
3179 
3180         if (guid != 0) {
3181                 if (nvlist_lookup_uint64(cfg, ZPOOL_CONFIG_POOL_GUID, &v) == 0)
3182                         return (v == guid);
3183         } else {
3184                 if (nvlist_lookup_string(cfg, ZPOOL_CONFIG_POOL_NAME, &s) == 0)
3185                         return (strcmp(s, tgt) == 0);
3186         }
3187         return (B_FALSE);
3188 }
3189 
3190 static char *
3191 find_zpool(char **target, nvlist_t **configp, int dirc, char **dirv)
3192 {
3193         nvlist_t *pools;
3194         nvlist_t *match = NULL;
3195         char *name = NULL;
3196         char *sepp = NULL;
3197         char sep;
3198         int count = 0;
3199         importargs_t args = { 0 };
3200 
3201         args.paths = dirc;
3202         args.path = dirv;
3203         args.can_be_active = B_TRUE;
3204 
3205         if ((sepp = strpbrk(*target, "/@")) != NULL) {
3206                 sep = *sepp;
3207                 *sepp = '\0';
3208         }
3209 
3210         pools = zpool_search_import(g_zfs, &args);
3211 
3212         if (pools != NULL) {
3213                 nvpair_t *elem = NULL;
3214                 while ((elem = nvlist_next_nvpair(pools, elem)) != NULL) {
3215                         verify(nvpair_value_nvlist(elem, configp) == 0);
3216                         if (pool_match(*configp, *target)) {
3217                                 count++;
3218                                 if (match != NULL) {
3219                                         /* print previously found config */
3220                                         if (name != NULL) {
3221                                                 (void) printf("%s\n", name);
3222                                                 dump_nvlist(match, 8);
3223                                                 name = NULL;
3224                                         }
3225                                         (void) printf("%s\n",
3226                                             nvpair_name(elem));
3227                                         dump_nvlist(*configp, 8);
3228                                 } else {
3229                                         match = *configp;
3230                                         name = nvpair_name(elem);
3231                                 }
3232                         }
3233                 }
3234         }
3235         if (count > 1)
3236                 (void) fatal("\tMatched %d pools - use pool GUID "
3237                     "instead of pool name or \n"
3238                     "\tpool name part of a dataset name to select pool", count);
3239 
3240         if (sepp)
3241                 *sepp = sep;
3242         /*
3243          * If pool GUID was specified for pool id, replace it with pool name
3244          */
3245         if (name && (strstr(*target, name) != *target)) {
3246                 int sz = 1 + strlen(name) + ((sepp) ? strlen(sepp) : 0);
3247 
3248                 *target = umem_alloc(sz, UMEM_NOFAIL);
3249                 (void) snprintf(*target, sz, "%s%s", name, sepp ? sepp : "");
3250         }
3251 
3252         *configp = name ? match : NULL;
3253 
3254         return (name);
3255 }
3256 
3257 int
3258 main(int argc, char **argv)
3259 {
3260         int i, c;
3261         struct rlimit rl = { 1024, 1024 };
3262         spa_t *spa = NULL;
3263         objset_t *os = NULL;
3264         int dump_all = 1;
3265         int verbose = 0;
3266         int error = 0;
3267         char **searchdirs = NULL;
3268         int nsearch = 0;
3269         char *target;
3270         nvlist_t *policy = NULL;
3271         uint64_t max_txg = UINT64_MAX;
3272         int rewind = ZPOOL_NEVER_REWIND;
3273 
3274         (void) setrlimit(RLIMIT_NOFILE, &rl);
3275         (void) enable_extended_FILE_stdio(-1, -1);
3276 
3277         dprintf_setup(&argc, argv);
3278 
3279         while ((c = getopt(argc, argv, "bcdhilmM:suCDRSAFLXevp:t:U:P")) != -1) {
3280                 switch (c) {
3281                 case 'b':
3282                 case 'c':
3283                 case 'd':
3284                 case 'h':
3285                 case 'i':
3286                 case 'l':
3287                 case 'm':
3288                 case 's':
3289                 case 'u':
3290                 case 'C':
3291                 case 'D':
3292                 case 'R':
3293                 case 'S':
3294                         dump_opt[c]++;
3295                         dump_all = 0;
3296                         break;
3297                 case 'A':
3298                 case 'F':
3299                 case 'L':
3300                 case 'X':
3301                 case 'e':
3302                 case 'P':
3303                         dump_opt[c]++;
3304                         break;
3305                 case 'v':
3306                         verbose++;
3307                         break;
3308                 case 'M':
3309                         max_inflight = strtoull(optarg, NULL, 0);
3310                         if (max_inflight == 0) {
3311                                 (void) fprintf(stderr, "maximum number "
3312                                     "of inflight I/Os must be greater "
3313                                     "than 0\n");
3314                                 usage();
3315                         }
3316                         break;
3317                 case 'p':
3318                         if (searchdirs == NULL) {
3319                                 searchdirs = umem_alloc(sizeof (char *),
3320                                     UMEM_NOFAIL);
3321                         } else {
3322                                 char **tmp = umem_alloc((nsearch + 1) *
3323                                     sizeof (char *), UMEM_NOFAIL);
3324                                 bcopy(searchdirs, tmp, nsearch *
3325                                     sizeof (char *));
3326                                 umem_free(searchdirs,
3327                                     nsearch * sizeof (char *));
3328                                 searchdirs = tmp;
3329                         }
3330                         searchdirs[nsearch++] = optarg;
3331                         break;
3332                 case 't':
3333                         max_txg = strtoull(optarg, NULL, 0);
3334                         if (max_txg < TXG_INITIAL) {
3335                                 (void) fprintf(stderr, "incorrect txg "
3336                                     "specified: %s\n", optarg);
3337                                 usage();
3338                         }
3339                         break;
3340                 case 'U':
3341                         spa_config_path = optarg;
3342                         break;
3343                 default:
3344                         usage();
3345                         break;
3346                 }
3347         }
3348 
3349         if (!dump_opt['e'] && searchdirs != NULL) {
3350                 (void) fprintf(stderr, "-p option requires use of -e\n");
3351                 usage();
3352         }
3353 
3354         kernel_init(FREAD);
3355         g_zfs = libzfs_init();
3356         ASSERT(g_zfs != NULL);
3357 
3358         if (dump_all)
3359                 verbose = MAX(verbose, 1);
3360 
3361         for (c = 0; c < 256; c++) {
3362                 if (dump_all && !strchr("elAFLRSXP", c))
3363                         dump_opt[c] = 1;
3364                 if (dump_opt[c])
3365                         dump_opt[c] += verbose;
3366         }
3367 
3368         aok = (dump_opt['A'] == 1) || (dump_opt['A'] > 2);
3369         zfs_recover = (dump_opt['A'] > 1);
3370 
3371         argc -= optind;
3372         argv += optind;
3373 
3374         if (argc < 2 && dump_opt['R'])
3375                 usage();
3376         if (argc < 1) {
3377                 if (!dump_opt['e'] && dump_opt['C']) {
3378                         dump_cachefile(spa_config_path);
3379                         return (0);
3380                 }
3381                 usage();
3382         }
3383 
3384         if (dump_opt['l']) {
3385                 dump_label(argv[0]);
3386                 return (0);
3387         }
3388 
3389         if (dump_opt['X'] || dump_opt['F'])
3390                 rewind = ZPOOL_DO_REWIND |
3391                     (dump_opt['X'] ? ZPOOL_EXTREME_REWIND : 0);
3392 
3393         if (nvlist_alloc(&policy, NV_UNIQUE_NAME_TYPE, 0) != 0 ||
3394             nvlist_add_uint64(policy, ZPOOL_REWIND_REQUEST_TXG, max_txg) != 0 ||
3395             nvlist_add_uint32(policy, ZPOOL_REWIND_REQUEST, rewind) != 0)
3396                 fatal("internal error: %s", strerror(ENOMEM));
3397 
3398         error = 0;
3399         target = argv[0];
3400 
3401         if (dump_opt['e']) {
3402                 nvlist_t *cfg = NULL;
3403                 char *name = find_zpool(&target, &cfg, nsearch, searchdirs);
3404 
3405                 error = ENOENT;
3406                 if (name) {
3407                         if (dump_opt['C'] > 1) {
3408                                 (void) printf("\nConfiguration for import:\n");
3409                                 dump_nvlist(cfg, 8);
3410                         }
3411                         if (nvlist_add_nvlist(cfg,
3412                             ZPOOL_REWIND_POLICY, policy) != 0) {
3413                                 fatal("can't open '%s': %s",
3414                                     target, strerror(ENOMEM));
3415                         }
3416                         if ((error = spa_import(name, cfg, NULL,
3417                             ZFS_IMPORT_MISSING_LOG)) != 0) {
3418                                 error = spa_import(name, cfg, NULL,
3419                                     ZFS_IMPORT_VERBATIM);
3420                         }
3421                 }
3422         }
3423 
3424         if (error == 0) {
3425                 if (strpbrk(target, "/@") == NULL || dump_opt['R']) {
3426                         error = spa_open_rewind(target, &spa, FTAG, policy,
3427                             NULL);
3428                         if (error) {
3429                                 /*
3430                                  * If we're missing the log device then
3431                                  * try opening the pool after clearing the
3432                                  * log state.
3433                                  */
3434                                 mutex_enter(&spa_namespace_lock);
3435                                 if ((spa = spa_lookup(target)) != NULL &&
3436                                     spa->spa_log_state == SPA_LOG_MISSING) {
3437                                         spa->spa_log_state = SPA_LOG_CLEAR;
3438                                         error = 0;
3439                                 }
3440                                 mutex_exit(&spa_namespace_lock);
3441 
3442                                 if (!error) {
3443                                         error = spa_open_rewind(target, &spa,
3444                                             FTAG, policy, NULL);
3445                                 }
3446                         }
3447                 } else {
3448                         error = dmu_objset_own(target, DMU_OST_ANY,
3449                             B_TRUE, FTAG, &os);
3450                 }
3451         }
3452         nvlist_free(policy);
3453 
3454         if (error)
3455                 fatal("can't open '%s': %s", target, strerror(error));
3456 
3457         argv++;
3458         argc--;
3459         if (!dump_opt['R']) {
3460                 if (argc > 0) {
3461                         zopt_objects = argc;
3462                         zopt_object = calloc(zopt_objects, sizeof (uint64_t));
3463                         for (i = 0; i < zopt_objects; i++) {
3464                                 errno = 0;
3465                                 zopt_object[i] = strtoull(argv[i], NULL, 0);
3466                                 if (zopt_object[i] == 0 && errno != 0)
3467                                         fatal("bad number %s: %s",
3468                                             argv[i], strerror(errno));
3469                         }
3470                 }
3471                 if (os != NULL) {
3472                         dump_dir(os);
3473                 } else if (zopt_objects > 0 && !dump_opt['m']) {
3474                         dump_dir(spa->spa_meta_objset);
3475                 } else {
3476                         dump_zpool(spa);
3477                 }
3478         } else {
3479                 flagbits['b'] = ZDB_FLAG_PRINT_BLKPTR;
3480                 flagbits['c'] = ZDB_FLAG_CHECKSUM;
3481                 flagbits['d'] = ZDB_FLAG_DECOMPRESS;
3482                 flagbits['e'] = ZDB_FLAG_BSWAP;
3483                 flagbits['g'] = ZDB_FLAG_GBH;
3484                 flagbits['i'] = ZDB_FLAG_INDIRECT;
3485                 flagbits['p'] = ZDB_FLAG_PHYS;
3486                 flagbits['r'] = ZDB_FLAG_RAW;
3487 
3488                 for (i = 0; i < argc; i++)
3489                         zdb_read_block(argv[i], spa);
3490         }
3491 
3492         (os != NULL) ? dmu_objset_disown(os, FTAG) : spa_close(spa, FTAG);
3493 
3494         fuid_table_destroy();
3495         sa_loaded = B_FALSE;
3496 
3497         libzfs_fini(g_zfs);
3498         kernel_fini();
3499 
3500         return (0);
3501 }