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